feat(editor): restore 0.27.5 mobile keyboard toolbar, native previews, and fold CRDT codecs

This commit is contained in:
DarkSky committed 2026-11-27 08:18:25 +09:00
1 parent 531da7466d
commit a6bb03e702
93 files changed
+13480 -4438

No files matched your search

+16 -5
View File
@@ -148,17 +148,28 @@ jobs:
workspaces: packages/frontend -> target
key: np-mobile-preview-wasm
- name: Build and verify all four independent blocksuite-preview Wasm workers
- name: Install wasm-bindgen CLI
run: |
mkdir -p /tmp/preview-wasm
WBG_VERSION=$(awk '/^name = "wasm-bindgen"$/{getline; gsub(/"/, "", $3); print $3; exit}' Cargo.lock)
URL="https://github.com/wasm-bindgen/wasm-bindgen/releases/download/${WBG_VERSION}/wasm-bindgen-${WBG_VERSION}-x86_64-unknown-linux-musl.tar.gz"
if curl -fsSL "$URL" | tar -xz -C /tmp; then
sudo install -m 0755 "/tmp/wasm-bindgen-${WBG_VERSION}-x86_64-unknown-linux-musl/wasm-bindgen" /usr/local/bin/wasm-bindgen
else
cargo install --locked wasm-bindgen-cli --version "$WBG_VERSION"
fi
wasm-bindgen --version
- name: Build and verify main playground Wasm bundle and 4 preview Wasm workers
run: |
mkdir -p /tmp/preview-wasm/pkg
for kind in mermaid math typst pdf; do
cargo build --locked --profile wasm-release -p blocksuite-preview --no-default-features --features "${kind},wasm-worker" --target wasm32-unknown-unknown
cp target/wasm32-unknown-unknown/wasm-release/blocksuite_preview.wasm "/tmp/preview-wasm/${kind}.wasm"
test -s "/tmp/preview-wasm/${kind}.wasm"
done
cargo build --locked --profile wasm-release -p affine-store --no-default-features --features wasm-codec --target wasm32-unknown-unknown
cp target/wasm32-unknown-unknown/wasm-release/affine_store.wasm /tmp/preview-wasm/crdt-codec.wasm
test -s /tmp/preview-wasm/crdt-codec.wasm
cargo build --locked --profile wasm-release -p playground --target wasm32-unknown-unknown
wasm-bindgen --target web --out-dir /tmp/preview-wasm/pkg target/wasm32-unknown-unknown/wasm-release/playground.wasm
test -s /tmp/preview-wasm/pkg/playground_bg.wasm
node hosts/web/scripts/stage-preview-workers.mjs /tmp/preview-wasm dev-local
node hosts/web/scripts/verify-preview-workers-e2e.mjs
+2 -1
View File
@@ -40,7 +40,8 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
- **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.<id>`, `.group.<name>`, `.query`, `.empty`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer), and a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Filtering uses case- and whitespace-insensitive subsequence matching (`isFuzzyMatch`); without matches the list keeps a `No results` row. Items follow BlockSuite's order in two groups (`Basic`: text, the six headings, code block, quote, divider, new doc [`SlashCommand::NewDoc`], linked doc [`SlashCommand::LinkedDoc`]; `List`: bulleted, numbered, to-do, toggle); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 44 px (title plus description subtitle, with group headers hidden while filtering), and the menu has no border, only its shadow.
- **Linked-doc `@` menu** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.<idx>`, `overlay.linked_doc_menu.create`): Typing `@` anywhere in paragraph or list text (outside inline code), or typing `[[` or `【【` (which converts the pair into `@`), opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types. `Up`/`Down` move selection across matched docs and the trailing Create row, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, and `Escape` closes the menu while leaving the typed text intact.
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.link`, `.align_left|center|right`, link field `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text, single-block or across blocks, while no composition runs and no slash menu is up; a selection touching the title or code gets none. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches, empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The link field is a one-line text input of its own (`LinkBar`: text, selection, composition). While it is open it is the view's text input: every `EntityInputHandler` call goes to it, `editor.composing()` stays false, and the document's text, selection and composition are untouched until `Apply`; opening, closing and every change of it are reported with `notify_text_input_changed`. Caret keys, deletion, select-all, copy and cut are the field's, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field. It has the only caret; the document keeps showing the selection.
- **Equation editor** (`overlay.equation_editor`, `.input`, `.done`): opens on `$$$$ ` / `$$$$ Enter` (block `affine:latex`), `$$ ` / `$$ Enter` (empty inline equation), or clicking an existing `FlowKind::Latex` block or `DecorationKind::LatexChip`. `Enter`, clicking `Done`, and clicking outside the popover commit the current LaTeX string (including any active IME composition via `LinkBar::into_committed_text`), while unchanged content closes without writing; `Escape` cancels and closes without writing. Open inline targets track remote peer edits via a zero-width CRDT `SelectionSnapshot` identity check and auto-close if the target is deleted or replaced remotely. The input field paints syntax-colored LaTeX directly from `highlight_line` runs.
- **Equation editor** (`overlay.equation_editor`, `.input`, `.done`): opens on `$$$$ ` / `$$$$ Enter` (block `affine:latex`), `$$ ` / `$$ Enter` (empty inline equation), or clicking an existing `FlowKind::Latex` block or `DecorationKind::LatexChip`. `Enter`, clicking `Done`, and clicking outside the popover commit the current LaTeX string (including any active IME composition via `LinkBar::into_committed_text`), while unchanged content closes without writing; `Escape` cancels and closes without writing. Open inline targets track remote peer edits via a zero-width CRDT `SelectionSnapshot` identity check and auto-close if the target is deleted or replaced remotely. The input field paints syntax-colored LaTeX directly from `highlight_line` runs, supports `Up`/`Down` navigation across soft-wrapped visual lines, and maps pointer clicks (`EquationClick`) to the nearest UTF-16 offset on the clicked visual row.
- **Mobile keyboard toolbar & bookmark prompt** (`overlay.keyboard_toolbar`, buttons `overlay.keyboard_toolbar.<id>`, docked panel `overlay.keyboard_toolbar.panel.<group>.<id>`, and `overlay.bookmark_prompt`, `.input`, `.apply`, `.cancel`): mirrors `0.27.5` `defaultKeyboardToolbarConfig` (`More` 8-group scrollable tool panel, `Aa` `textSubToolbarConfig` with `autoShow` on non-collapsed text selections, `Turn into` reusing `SLASH_ITEMS`, and `Highlight` foreground/background swatches). Date actions format against the host's local calendar timezone; `Image` opens the host file picker (`can_pick_images` hides the button on native hosts without a registered picker), queues background upload of the base64url SHA-256 content-addressed blob (retrying on scheduler backoff and reconnect until confirmed), and publishes `affine:image`; `Bookmark` opens `overlay.bookmark_prompt` and commits an `http(s)://` `affine:bookmark` block as one undo step (`Escape`, `Cancel`, outside press, empty input, or relative paths write zero blocks).
- **In-place table cell editing** (`page.table_cell_focus`): `affine:table` cells lay out and paint with `RichParagraph` (preserving bold, italic, underline, strike, inline code, links, and inline math) and carry their `FlowTextLayout` for same-source hit-testing, caret, selection, `character_index_for_point`, and IME candidate bounds. Clicking a cell focuses it directly in place (1.5 px brand border, zero floating popover, zero writeback on focus-only). Typing, deleting, and pasting splice the cell's live `Y.Text` directly via `PageDocSession::splice_table_cell_text` (applying the shared `insertion_marks_at` rule so text typed after inline code, links, references, or math never leaks into those marks, and sharing `AnchoredInlineInput` + `Utf16ImeBuffer` with `EdgelessLabelEditor`). Keystrokes coalesce within the 500 ms undo window, refresh only the table block in O(1) via `PageDocSession::read_table_block` with zero `TableData::clone()`, and mark only the table block in `dirty_text`. IME preedit splices via `split_delta` so surrounding marks keep identical pixels; clicking inside an already-focused inline target (table cell or Edgeless label) commits any in-flight composition via `unmark` into its original replacement range before repositioning the caret (whereas body `change_selection` clears in-flight composition on click). `Shift+Enter` inserts `\n`, `Up`/`Down` step across visual lines, and plain `Enter`/`Escape`, mode switches, or remote deletion exit through `finish_inline_targets` (closing the undo window and suppressing unselected root-title fallback input until the user re-selects a target). While a table cell is focused without a body selection, `KeyboardToolbar` mark/block buttons render disabled; explicit cell mark toggling and `pending_marks` are deferred until body and cell selections unify.
- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's Page-mode grabber: a 4 × 12 px vertical bar while the pointer is on the block's row, narrowing to a 2 × 12 px vertical bar once hovered or dragged (the 2 × 3 six-dot 14 px pill is reserved for Edgeless `gfx` drag handles). A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings.
- **Block controls**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block.<id>.copy` appears on a hovered code block and reads `Copied` for 1.5 s on the scheduler clock. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections (translated per highlight span's own block scroll before clamping), and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view.
+142
View File
@@ -0,0 +1,142 @@
//! Pure `y-octo` Yjs v1 update merging and root-document `meta.pages -> spaces` subdoc GUID
//! extraction shared by `affine-store` and the WebAssembly `playground` bundle.
use y_octo::{
Any, DocOptions, DocSession, SessionConfig, SessionReadValue, SessionUndoConfig, TypePath,
TypeTarget, merge_updates_v1, validate_update_v1,
};
use crate::DocResult;
fn is_empty_crdt_update(bin: &[u8]) -> bool {
bin.is_empty() || bin == [0, 0]
}
/// Merge a slice of encoded Yjs v1 CRDT updates into a single v1 update (native + `wasm32`).
pub fn merge_crdt_updates_v1(updates: &[&[u8]]) -> DocResult<Vec<u8>> {
let non_empty: Vec<&[u8]> = updates
.iter()
.copied()
.filter(|u| !is_empty_crdt_update(u))
.collect();
match non_empty.as_slice() {
[] => Ok(vec![0, 0]),
[single] => {
validate_update_v1(single)?;
Ok((*single).to_vec())
}
many => Ok(merge_updates_v1(many.iter().copied())?.encode_v1()?),
}
}
/// Extract `(page_id, subdoc_guid)` mappings from an encoded Yjs v1 root workspace document.
pub fn extract_page_subdoc_mappings(
root_doc_id: &str,
root_doc_bytes: &[u8],
) -> DocResult<Vec<(String, String)>> {
if is_empty_crdt_update(root_doc_bytes) {
return Ok(Vec::new());
}
let options = DocOptions::from_identity(1, root_doc_id.to_string());
let mut session = DocSession::<()>::with_config(
options,
SessionConfig {
undo: SessionUndoConfig::Disabled,
},
);
session.apply_update_v1(root_doc_bytes)?;
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
let Ok(page_items) = session.read_array(&pages_target) else {
return Ok(Vec::new());
};
let spaces_target = TypeTarget::Path(TypePath::root("spaces"));
let mut mappings = Vec::new();
for item in page_items {
let SessionReadValue::Map(map_id) = item else {
continue;
};
let Ok(Some(SessionReadValue::Any(Any::String(page_id)))) =
session.get_map_value(&TypeTarget::Identity(map_id), "id")
else {
continue;
};
if page_id.is_empty() {
continue;
}
if let Ok(Some(SessionReadValue::Doc { guid, .. })) =
session.get_map_value(&spaces_target, &page_id)
{
mappings.push((page_id, guid));
}
}
Ok(mappings)
}
/// Extract sorted, deduplicated live `meta.pages -> spaces` subdoc GUIDs from one or more
/// encoded Yjs v1 root document updates, rejecting malformed or truncated frames.
pub fn extract_subdoc_guids_from_root_updates(root_updates: &[&[u8]]) -> DocResult<Vec<String>> {
if root_updates.is_empty() {
return Ok(Vec::new());
}
let merged = merge_crdt_updates_v1(root_updates)?;
let mappings = extract_page_subdoc_mappings("", &merged)?;
let mut guids: Vec<String> = mappings.into_iter().map(|(_, guid)| guid).collect();
guids.sort();
guids.dedup();
Ok(guids)
}
#[cfg(test)]
mod tests {
use y_octo::{Doc, DocOptions};
use super::*;
#[test]
fn merge_and_extract_subdoc_guids_handle_real_yjs_v1_and_corrupt_frames() {
assert_eq!(merge_crdt_updates_v1(&[]).unwrap(), vec![0, 0]);
assert!(merge_crdt_updates_v1(&[&[0xff, 0xff, 0xff, 0x80]]).is_err());
let doc_a = Doc::with_options(DocOptions::from_identity(101, String::new()));
let mut text_a = doc_a.get_or_create_text("content").unwrap();
text_a.insert(0, "hello ").unwrap();
let upd_a = doc_a.encode_update_v1().unwrap();
let doc_b = Doc::with_options(DocOptions::from_identity(202, String::new()));
let mut text_b = doc_b.get_or_create_text("content").unwrap();
text_b.insert(0, "world").unwrap();
let upd_b = doc_b.encode_update_v1().unwrap();
let merged = merge_crdt_updates_v1(&[&[0, 0], &upd_a, &[], &upd_b]).unwrap();
let mut check = Doc::with_options(DocOptions::from_identity(303, String::new()));
check.apply_update_from_binary_v1(&merged).unwrap();
let text = check.get_or_create_text("content").unwrap().to_string();
assert!(text.contains("hello ") && text.contains("world"));
let real_yjs_v1: [&[u8]; 2] = [
&[
1, 6, 105, 0, 39, 1, 4, 109, 101, 116, 97, 5, 112, 97, 103, 101, 115, 0, 7, 0, 105,
0, 1, 40, 0, 105, 1, 2, 105, 100, 1, 119, 2, 112, 49, 40, 0, 105, 1, 5, 116, 105,
116, 108, 101, 1, 119, 9, 76, 105, 118, 101, 32, 80, 97, 103, 101, 41, 1, 6, 115,
112, 97, 99, 101, 115, 2, 112, 49, 8, 111, 108, 100, 45, 103, 117, 105, 100, 118,
0, 41, 1, 8, 111, 116, 104, 101, 114, 77, 97, 112, 7, 102, 111, 114, 101, 105, 103,
110, 12, 102, 111, 114, 101, 105, 103, 110, 45, 103, 117, 105, 100, 118, 0, 0,
],
&[
1, 1, 105, 6, 169, 105, 4, 9, 108, 105, 118, 101, 45, 103, 117, 105, 100, 118, 0,
1, 105, 1, 4, 1,
],
];
assert_eq!(
extract_subdoc_guids_from_root_updates(&real_yjs_v1).unwrap(),
vec!["live-guid".to_string()]
);
let merged_root = merge_crdt_updates_v1(&real_yjs_v1).unwrap();
assert_eq!(
extract_subdoc_guids_from_root_updates(&[&merged_root]).unwrap(),
vec!["live-guid".to_string()]
);
}
}
+4
View File
@@ -1,6 +1,7 @@
#![forbid(unsafe_code)]
pub mod awareness;
pub mod crdt_v1;
pub mod fractional_index;
pub mod read;
pub mod refs;
@@ -15,6 +16,9 @@ use thiserror::Error;
/// Maximum client ID representable exactly as a JavaScript IEEE-754 integer (`2^53 - 1`).
pub const MAX_JS_CLIENT_ID: u64 = 0x001F_FFFF_FFFF_FFFF;
/// Maximum blob body size accepted and served by the room relay (`64 MiB`).
pub const MAX_BLOB_BYTES: usize = 64 * 1024 * 1024;
/// Validate that a `client_id` is in the JavaScript-safe 53-bit range `1..=2^53-1`.
pub fn validate_client_id(client_id: u64) -> Result<u64, DocError> {
if client_id == 0 || client_id > MAX_JS_CLIENT_ID {
+1 -1
View File
@@ -27,7 +27,7 @@ use y_octo::{
};
/// Maximum HTTP body size for `/api/collection/{id}/blob/{key}` (64 MiB).
const MAX_BLOB_BODY_BYTES: usize = 64 * 1024 * 1024;
const MAX_BLOB_BODY_BYTES: usize = crate::MAX_BLOB_BYTES;
use crate::wire::{
RoomBinaryFrame, RoomControlFrame, decode_binary_frame, decode_control_frame,
+2 -2
View File
@@ -87,13 +87,13 @@ impl PageDocSession {
pub fn undo(&mut self) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
let res = self.session.undo_stack(self.undo_stack_id)?;
self.refresh_all_surface_orders();
Ok(res)
Ok(self.record_commit(res))
}
pub fn redo(&mut self) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
let res = self.session.redo_stack(self.undo_stack_id)?;
self.refresh_all_surface_orders();
Ok(res)
Ok(self.record_commit(res))
}
pub fn can_undo(&self) -> bool {
+40 -9
View File
@@ -10,7 +10,7 @@ pub use export::any_to_normalized_json;
pub use workspace::WorkspaceSession;
use std::{
cell::RefCell,
cell::{Cell, RefCell},
collections::{BTreeMap, BTreeSet},
};
@@ -203,6 +203,7 @@ pub struct PageDocSession {
undo_stack_id: UndoStackId,
blocks_target: TypeTarget,
surface_element_order: RefCell<BTreeMap<String, Vec<String>>>,
revision: Cell<u64>,
}
impl PageDocSession {
@@ -227,9 +228,27 @@ impl PageDocSession {
undo_stack_id,
blocks_target,
surface_element_order: RefCell::new(BTreeMap::new()),
revision: Cell::new(0),
})
}
/// Monotonically increasing revision bumped on every applied local or remote mutation,
/// including delete-only updates that leave the Yjs state vector unchanged.
pub fn revision(&self) -> u64 {
self.revision.get()
}
pub(super) fn bump_revision(&self) {
self.revision.set(self.revision.get().wrapping_add(1));
}
pub(super) fn record_commit(&self, commit: PageCommit) -> PageCommit {
if commit.is_some() {
self.bump_revision();
}
commit
}
/// Update and return per-surface first-integration key order for `prop:elements.value`,
/// preserving established order for surviving keys and appending newly integrated keys
/// sorted by `(Reverse(id.client), id.clock)` from `TypeIdentity::Item(id)` to match
@@ -319,6 +338,7 @@ impl PageDocSession {
}
pub fn inner_mut(&mut self) -> &mut DocSession<SelectionSnapshot> {
self.bump_revision();
&mut self.session
}
@@ -343,6 +363,9 @@ impl PageDocSession {
/// commits so the caller can broadcast them back to the room.
pub fn apply_remote_update_v1(&mut self, bytes: &[u8]) -> DocResult<RemoteApplyResult> {
let commits = self.session.apply_update_v1(bytes)?;
if !commits.is_empty() {
self.bump_revision();
}
self.refresh_all_surface_orders();
let outbound_updates = commits
.iter()
@@ -462,7 +485,8 @@ impl PageDocSession {
}
}
}
Ok(self.session.commit_tx()?)
let commit = self.session.commit_tx()?;
Ok(self.record_commit(commit))
}
/// Move an existing child block to a new index within `parent_id`'s `sys:children`.
@@ -491,7 +515,8 @@ impl PageDocSession {
clamped_index,
vec![SessionValue::Any(Any::String(child_id.to_string()))],
)?;
Ok(self.session.commit_tx()?)
let commit = self.session.commit_tx()?;
Ok(self.record_commit(commit))
}
/// Insert text into a block's `Y.Text` property (e.g. `"prop:text"` or `"prop:title"`).
@@ -505,7 +530,8 @@ impl PageDocSession {
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
self.advance_time(now_ms);
let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key));
Ok(self.session.text_insert(&target, index, text)?)
let commit = self.session.text_insert(&target, index, text)?;
Ok(self.record_commit(commit))
}
/// Remove a UTF-16 range from a block's `Y.Text` property.
@@ -519,7 +545,8 @@ impl PageDocSession {
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
self.advance_time(now_ms);
let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key));
Ok(self.session.text_remove(&target, index, len)?)
let commit = self.session.text_remove(&target, index, len)?;
Ok(self.record_commit(commit))
}
/// Apply formatting attributes to a range in a block's `Y.Text` property.
@@ -534,7 +561,8 @@ impl PageDocSession {
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
self.advance_time(now_ms);
let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key));
Ok(self.session.text_format(&target, index, len, attrs)?)
let commit = self.session.text_format(&target, index, len, attrs)?;
Ok(self.record_commit(commit))
}
/// Apply a raw delta to a block's `Y.Text` property.
@@ -547,7 +575,8 @@ impl PageDocSession {
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
self.advance_time(now_ms);
let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key(prop_key));
Ok(self.session.text_apply_delta(&target, delta)?)
let commit = self.session.text_apply_delta(&target, delta)?;
Ok(self.record_commit(commit))
}
/// Splice a UTF-16 range on an existing `Y.Text` target via a single tracked
@@ -587,7 +616,8 @@ impl PageDocSession {
});
}
self.advance_time(now_ms);
Ok(self.session.text_apply_delta(target, &ops)?)
let commit = self.session.text_apply_delta(target, &ops)?;
Ok(self.record_commit(commit))
}
/// Set a scalar or nested property on a block (`prop:*`).
@@ -600,6 +630,7 @@ impl PageDocSession {
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
self.advance_time(now_ms);
let target = TypeTarget::Path(TypePath::root("blocks").key(block_id));
Ok(self.session.map_set(&target, prop_key.into(), value)?)
let commit = self.session.map_set(&target, prop_key.into(), value)?;
Ok(self.record_commit(commit))
}
}
@@ -53,7 +53,7 @@ impl PageDocSession {
let commit = self.session.commit_tx();
self.stop_capturing()?;
result?;
Ok(commit?)
Ok(self.record_commit(commit?))
}
pub fn delete_block_subtree(
+14 -9
View File
@@ -29,11 +29,12 @@ impl PageDocSession {
.key("prop:elements")
.key("value"),
);
Ok(self.session.map_set(
let commit = self.session.map_set(
&elements_value_target,
element_id,
SessionValue::Map(entries),
)?)
)?;
Ok(self.record_commit(commit))
}
/// Update a field on an existing surface element.
@@ -53,7 +54,8 @@ impl PageDocSession {
.key("value")
.key(element_id),
);
Ok(self.session.map_set(&target, field.into(), value)?)
let commit = self.session.map_set(&target, field.into(), value)?;
Ok(self.record_commit(commit))
}
/// Format `[x, y, w, h]` into BlockSuite's wire `xywh` JSON string.
@@ -114,9 +116,10 @@ impl PageDocSession {
.key("prop:elements")
.key("value"),
);
Ok(self
let commit = self
.session
.map_remove(&elements_value_target, element_id)?)
.map_remove(&elements_value_target, element_id)?;
Ok(self.record_commit(commit))
}
/// Update multiple fields on an existing surface element in one tracked transaction.
@@ -191,11 +194,12 @@ impl PageDocSession {
}]
};
self.advance_time(now_ms);
Ok(self.session.map_set(
let commit = self.session.map_set(
&elem_target,
field.to_string(),
SessionValue::Text(delta),
)?)
)?;
Ok(self.record_commit(commit))
}
}
}
@@ -568,11 +572,12 @@ impl PageDocSession {
format: None,
}]
};
Ok(self.session.map_set(
let commit = self.session.map_set(
&elem_target,
field.to_string(),
SessionValue::Text(delta),
)?)
)?;
Ok(self.record_commit(commit))
}
}
}
+10 -10
View File
@@ -118,26 +118,26 @@ impl PageDocSession {
};
self.advance_time(now_ms);
match write_target {
let commit = match write_target {
CellWriteTarget::Flat {
block_target,
flat_key,
} => Ok(self
} => self
.session
.map_set(&block_target, flat_key, SessionValue::Text(delta))?),
CellWriteTarget::LegacyNestedCellMap { cell_target } => Ok(self.session.map_set(
&cell_target,
"text".to_string(),
SessionValue::Text(delta),
)?),
.map_set(&block_target, flat_key, SessionValue::Text(delta))?,
CellWriteTarget::LegacyNestedCellMap { cell_target } => {
self.session
.map_set(&cell_target, "text".to_string(), SessionValue::Text(delta))?
}
CellWriteTarget::LegacyNestedCellsMap {
cells_target,
cell_key,
} => {
let cell_val = SessionValue::Map(vec![("text".into(), SessionValue::Text(delta))]);
Ok(self.session.map_set(&cells_target, cell_key, cell_val)?)
self.session.map_set(&cells_target, cell_key, cell_val)?
}
}
};
Ok(self.record_commit(commit))
}
/// Encode a `RelativePosition` at UTF-16 `offset` on a live table cell's `Y.Text`.
+3 -2
View File
@@ -12,12 +12,10 @@ workspace = true
[features]
default = []
harness = ["ui/harness"]
preview-engine = ["dep:blocksuite-preview"]
[dependencies]
anyhow.workspace = true
blocksuite-playground-doc = { path = "../doc", default-features = false }
blocksuite-preview = { path = "../preview", default-features = false, features = ["math", "pdf"], optional = true }
image.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -28,6 +26,9 @@ unicode-linebreak = "0.1"
unicode-segmentation.workspace = true
y-octo = { version = "0.4.0", default-features = false, features = ["session"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
blocksuite-preview = { path = "../preview", default-features = false, features = ["math", "pdf"] }
[dev-dependencies]
ui = { path = "../../../packages/ui/ui", features = ["harness"] }
@@ -341,6 +341,29 @@ impl BlockBody {
state: BlockPaint,
window: &mut Window,
cx: &mut App,
) {
if self.kind == FlowKind::Table
&& let Some(scroll_cfg) = self.code_scroll
{
let scroll = state.code_scroll_x.clamp(0.0, scroll_cfg.max_x);
let shifted = point(origin.x - px(scroll), origin.y);
window.with_local_paint_mask(
ui::ContentMask {
bounds: scroll_cfg.area.bounds(origin),
},
|window| self.paint_prims(shifted, state, window, cx),
);
return;
}
self.paint_prims(origin, state, window, cx);
}
fn paint_prims(
&self,
origin: Point<Pixels>,
state: BlockPaint,
window: &mut Window,
cx: &mut App,
) {
for prim in &self.prims {
match prim {
@@ -415,6 +438,19 @@ impl BlockBody {
false,
);
}
Prim::Surface {
rect,
layout,
world_origin: (wx, wy),
scale,
} => {
let bounds = rect.bounds(origin);
let matrix = crate::edgeless::EdgelessCamera::new(*wx, *wy, *scale)
.to_transformation_matrix(bounds.origin);
window.with_local_paint_mask(ui::ContentMask { bounds }, |window| {
crate::surface::paint_surface_transformed(layout, matrix, window, cx);
});
}
}
}
}
@@ -492,6 +528,20 @@ impl FlowBlock {
}
}
/// Transient committed draft of an open equation editor, used for live zero-writeback preview.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum EquationDraft {
Block {
block_id: String,
latex: String,
},
Inline {
block_id: String,
utf16_offset: u64,
latex: String,
},
}
/// Everything the layout pass reads besides the window's text system.
pub struct FlowInput<'a> {
pub snapshot: &'a PageSnapshot,
@@ -504,6 +554,10 @@ pub struct FlowInput<'a> {
pub images: &'a HashMap<String, ImageSlot>,
/// Rasterized PDF attachment previews keyed by block id or `sourceId`.
pub pdf_previews: Option<&'a HashMap<String, super::PdfPreviewPage>>,
/// Host document directory providing read-only summaries and snapshots for embedded docs.
pub doc_directory: Option<&'a dyn crate::directory::WorkspaceDocDirectory>,
/// Transient committed draft from an open equation editor (zero CRDT writeback).
pub equation_draft: Option<&'a EquationDraft>,
/// Bumped whenever `page_titles`, `images`, or `pdf_previews` change.
pub env_rev: u64,
/// Explicit layout direction supplied by the host shell.
@@ -0,0 +1,470 @@
//! Layout and paint builders for read-only embedded and reference blocks:
//! `affine:embed-linked-doc`, `affine:embed-synced-doc`, and `affine:surface-ref`.
//!
//! Strictly zero internal IDs (`doc:...`, `affine:frame`, `frame-...`) on card surfaces and
//! strictly zero CRDT writeback.
use std::collections::BTreeSet;
use blocksuite_playground_doc::read::{BlockContent, BlockNode, PageSnapshot};
use crate::{
directory::EditorDocId,
theme::{FONT_SANS, IconPaint, TYPOGRAPHY},
};
use super::{
BlockBody, CARD_BLOCK_MARGIN, FlowKind, FlowPass, FlowRect, InlineAlign, InlineStyle, Prim,
inline::truncate_to_width,
};
const MAX_SYNCED_RECURSION_DEPTH: usize = 2;
const MAX_SYNCED_PREVIEW_BLOCKS: usize = 6;
/// Howard Hinnant's `civil_from_days` algorithm: converts days since `1970-01-01` to `(year, month, day)`.
pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = y + i64::from(m <= 2);
(year, m as u32, d as u32)
}
/// Formats a Unix millisecond timestamp into `YYYY-MM-DD` using pure calendar arithmetic
/// (zero host wall-clock calls).
fn format_utc_date(ms: i64) -> Option<String> {
if ms <= 0 {
return None;
}
let (year, m, d) = civil_from_days(ms.div_euclid(86_400_000));
Some(format!("{year:04}-{m:02}-{d:02}"))
}
fn extract_snapshot_snippet(snapshot: &PageSnapshot) -> String {
let Some(root) = &snapshot.root else {
return String::new();
};
let mut parts = Vec::new();
for node in root.walk() {
let text = match &node.content {
BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => {
text.plain.trim()
}
BlockContent::Callout { text, .. } => text.plain.trim(),
BlockContent::Code { text, .. } => text.trim(),
_ => "",
};
if !text.is_empty() {
parts.push(text);
if parts.len() >= 2 {
break;
}
}
}
parts.join(" ")
}
impl FlowPass<'_> {
pub(super) fn embed_linked_doc_body(
&mut self,
page_id: &str,
caption: &str,
width: f32,
) -> BlockBody {
let doc_id = EditorDocId::from(page_id);
let preview = self
.input
.doc_directory
.and_then(|dir| dir.doc_preview(&doc_id));
let title_from_preview = preview
.as_ref()
.map(|p| p.title.as_str())
.filter(|s| !s.trim().is_empty());
let title_from_map = self
.input
.page_titles
.get(page_id)
.map(String::as_str)
.filter(|s| !s.trim().is_empty());
let resolved_title = title_from_preview.or(title_from_map).unwrap_or("Untitled");
let snippet = preview
.as_ref()
.map(|p| p.snippet.trim().to_string())
.filter(|s| !s.is_empty())
.or_else(|| {
self.input
.doc_directory
.and_then(|dir| dir.doc_snapshot(&doc_id))
.map(|snap| extract_snapshot_snippet(&snap))
.filter(|s| !s.is_empty())
});
let date_label = preview
.as_ref()
.and_then(|p| format_utc_date(p.updated_at_ms));
let pad = 12.0;
let inner_w = (width - pad * 2.0 - 28.0).max(40.0);
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
self.palette.text_primary,
);
let snippet_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
let date_style = InlineStyle::new(FONT_SANS, 11.0, 400.0, self.palette.placeholder);
let title_str = truncate_to_width(self.window, resolved_title, &title_style, inner_w)
.text
.to_string();
let mut prims = vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, 72.0),
fill: Some(self.palette.background),
border: Some(self.palette.card_border),
radius: 8.0,
dashed: false,
},
Prim::Icon {
rect: FlowRect::new(pad, 14.0, 18.0, 18.0),
icon: IconPaint::named("LinkedPageIcon"),
color: self.palette.brand,
},
Prim::Text {
x: pad + 26.0,
y: 12.0,
layout: self.plain_inline(
&title_str,
title_style,
inner_w,
22.0,
InlineAlign::Left,
),
clip: None,
},
];
let mut y = 38.0;
if let Some(snippet_text) = snippet.as_deref() {
let line = truncate_to_width(self.window, snippet_text, &snippet_style, inner_w)
.text
.to_string();
prims.push(Prim::Text {
x: pad + 26.0,
y,
layout: self.plain_inline(&line, snippet_style, inner_w, 18.0, InlineAlign::Left),
clip: None,
});
y += 20.0;
}
if let Some(date_text) = date_label.as_deref() {
prims.push(Prim::Text {
x: pad + 26.0,
y,
layout: self.plain_inline(date_text, date_style, inner_w, 16.0, InlineAlign::Left),
clip: None,
});
y += 18.0;
}
let card_h = (y + 10.0).max(52.0);
if let Some(Prim::Quad { rect, .. }) = prims.first_mut() {
rect.h = card_h;
}
let mut body = BlockBody {
kind: FlowKind::EmbedLinkedDoc,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: resolved_title.to_string(),
prims,
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
};
self.push_caption(&mut body, caption);
body
}
pub(super) fn embed_synced_doc_body(
&mut self,
page_id: &str,
caption: &str,
width: f32,
) -> BlockBody {
let doc_id = EditorDocId::from(page_id);
let preview = self
.input
.doc_directory
.and_then(|dir| dir.doc_preview(&doc_id));
let resolved_title = preview
.as_ref()
.map(|p| p.title.as_str())
.filter(|s| !s.trim().is_empty())
.or_else(|| {
self.input
.page_titles
.get(page_id)
.map(String::as_str)
.filter(|s| !s.trim().is_empty())
})
.unwrap_or("Untitled");
let pad = 14.0;
let inner_w = (width - pad * 2.0 - 26.0).max(40.0);
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
self.palette.text_primary,
);
let title_str = truncate_to_width(self.window, resolved_title, &title_style, inner_w)
.text
.to_string();
let mut prims = vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, 88.0),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.card_border),
radius: 8.0,
dashed: false,
},
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, 3.0, 88.0),
fill: Some(self.palette.brand),
border: None,
radius: 1.5,
dashed: false,
},
Prim::Icon {
rect: FlowRect::new(pad, 14.0, 18.0, 18.0),
icon: IconPaint::named("LinkedPageIcon"),
color: self.palette.brand,
},
Prim::Text {
x: pad + 26.0,
y: 12.0,
layout: self.plain_inline(
&title_str,
title_style,
inner_w,
22.0,
InlineAlign::Left,
),
clip: None,
},
];
// Render target document's read-only body blocks with cycle & depth protection.
let mut visited: BTreeSet<String> = self.visited_embeds.clone();
visited.insert(self.input.snapshot.doc_id.clone());
let mut content_y = 40.0;
let mut rendered_any = false;
let mut loaded_empty_doc = false;
if self.embed_depth < MAX_SYNCED_RECURSION_DEPTH
&& !visited.contains(page_id)
&& let Some(target_snap) = self
.input
.doc_directory
.and_then(|dir| dir.doc_snapshot(&doc_id))
&& let Some(root) = &target_snap.root
{
visited.insert(page_id.to_string());
let mut preview_nodes: Vec<BlockNode> = Vec::new();
for child in &root.children {
if child.is_edgeless_only() {
continue;
}
match &child.content {
BlockContent::Note { hidden: true, .. } => continue,
BlockContent::Note { .. } => {
for item in &child.children {
if preview_nodes.len() >= MAX_SYNCED_PREVIEW_BLOCKS {
break;
}
preview_nodes.push(item.clone());
}
}
_ => {
if preview_nodes.len() < MAX_SYNCED_PREVIEW_BLOCKS {
preview_nodes.push(child.clone());
}
}
}
}
if preview_nodes.is_empty() {
loaded_empty_doc = true;
} else {
let nested_w = (width - 2.0 * pad).max(60.0);
let mut nested_flow = super::BlockFlow::new();
let nested_input = super::FlowInput {
snapshot: &target_snap,
width: nested_w,
theme: self.input.theme,
page_titles: self.input.page_titles,
images: self.input.images,
pdf_previews: self.input.pdf_previews,
doc_directory: self.input.doc_directory,
equation_draft: None,
env_rev: self.input.env_rev,
direction: self.direction,
};
let nested = nested_flow.layout_nodes_nested(
&preview_nodes,
&nested_input,
self.window,
self.embed_depth + 1,
visited,
);
for block in &nested.blocks {
let dx = pad + block.x;
let dy = content_y + block.y;
for prim in &block.body.prims {
prims.push(translate_prim(prim, dx, dy));
}
}
content_y += nested.height;
rendered_any = true;
}
}
if !rendered_any {
let fallback = preview
.as_ref()
.map(|p| p.snippet.trim())
.filter(|s| !s.is_empty())
.or(loaded_empty_doc.then_some("Empty document"));
if let Some(fallback_text) = fallback {
let empty_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
prims.push(Prim::Text {
x: pad,
y: content_y,
layout: self.plain_inline(
fallback_text,
empty_style,
(width - 2.0 * pad).max(40.0),
20.0,
InlineAlign::Left,
),
clip: None,
});
content_y += 22.0;
}
}
let min_card_h = if rendered_any || loaded_empty_doc {
76.0
} else {
48.0
};
let card_h = (content_y + pad).max(min_card_h);
if let Some(Prim::Quad { rect, .. }) = prims.get_mut(0) {
rect.h = card_h;
}
if let Some(Prim::Quad { rect, .. }) = prims.get_mut(1) {
rect.h = card_h;
}
let mut body = BlockBody {
kind: FlowKind::EmbedSyncedDoc,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: resolved_title.to_string(),
prims,
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
};
self.push_caption(&mut body, caption);
body
}
}
fn translate_prim(prim: &Prim, dx: f32, dy: f32) -> Prim {
match prim {
Prim::Quad {
rect,
fill,
border,
radius,
dashed,
} => Prim::Quad {
rect: rect.translated(dx, dy),
fill: *fill,
border: *border,
radius: *radius,
dashed: *dashed,
},
Prim::Text { x, y, layout, clip } => Prim::Text {
x: x + dx,
y: y + dy,
layout: layout.clone(),
clip: clip.map(|r| r.translated(dx, dy)),
},
Prim::CodeLine { x, y, layout, clip } => Prim::CodeLine {
x: x + dx,
y: y + dy,
layout: layout.clone(),
clip: clip.translated(dx, dy),
},
Prim::Rich { x, y, layout } => Prim::Rich {
x: x + dx,
y: y + dy,
layout: layout.clone(),
},
Prim::Icon { rect, icon, color } => Prim::Icon {
rect: rect.translated(dx, dy),
icon: icon.clone(),
color: *color,
},
Prim::Chevron {
rect,
collapsed,
color,
} => Prim::Chevron {
rect: rect.translated(dx, dy),
collapsed: *collapsed,
color: *color,
},
Prim::Image { rect, image } => Prim::Image {
rect: rect.translated(dx, dy),
image: image.clone(),
},
Prim::Surface {
rect,
layout,
world_origin,
scale,
} => Prim::Surface {
rect: rect.translated(dx, dy),
layout: layout.clone(),
world_origin: *world_origin,
scale: *scale,
},
}
}
@@ -545,24 +545,44 @@ pub enum ImageSlot {
Ready(Arc<RenderImage>),
}
/// Decode PNG, JPEG, WebP, GIF (first frame) or BMP bytes into a renderable image; any
/// other format is rejected.
pub fn decode_image(bytes: &[u8]) -> Option<Arc<RenderImage>> {
/// Maximum encoded image payload decoded on the UI thread, matching the room relay's
/// 64 MiB blob limit so existing workspace images up to [`blocksuite_playground_doc::MAX_BLOB_BYTES`]
/// remain readable (picker admission enforces its own stricter limit separately).
const MAX_IMAGE_DECODE_BYTES: usize = blocksuite_playground_doc::MAX_BLOB_BYTES;
/// Decode PNG, JPEG, WebP, GIF (first frame) or BMP bytes into a renderable image along
/// with its intrinsic pixel `(width, height)` in a single pass; any other format or payload
/// exceeding [`MAX_IMAGE_DECODE_BYTES`] is rejected.
pub fn decode_image_with_dimensions(bytes: &[u8]) -> Option<(Arc<RenderImage>, u32, u32)> {
use image::ImageFormat::{Bmp, Gif, Jpeg, Png, WebP};
if bytes.len() > MAX_IMAGE_DECODE_BYTES {
return None;
}
let format = image::guess_format(bytes)
.ok()
.filter(|format| matches!(format, Png | Jpeg | WebP | Gif | Bmp))?;
let mut buffer = image::load_from_memory_with_format(bytes, format)
.ok()?
.into_rgba8();
if buffer.width() == 0 || buffer.height() == 0 {
let (width, height) = (buffer.width(), buffer.height());
if width == 0 || height == 0 {
return None;
}
// The renderer samples BGRA.
for pixel in buffer.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)])))
Some((
Arc::new(RenderImage::new(vec![image::Frame::new(buffer)])),
width,
height,
))
}
/// Decode PNG, JPEG, WebP, GIF (first frame) or BMP bytes into a renderable image; any
/// other format is rejected.
pub fn decode_image(bytes: &[u8]) -> Option<Arc<RenderImage>> {
decode_image_with_dimensions(bytes).map(|(img, _, _)| img)
}
/// Paint primitive of a block, positioned relative to the block's own origin.
@@ -609,4 +629,10 @@ pub(super) enum Prim {
rect: FlowRect,
image: Arc<RenderImage>,
},
Surface {
rect: FlowRect,
layout: Rc<crate::surface::SurfaceLayout>,
world_origin: (f32, f32),
scale: f32,
},
}
+237 -31
View File
@@ -37,6 +37,8 @@ pub(super) struct FlowPass<'a> {
pub(super) y: f32,
/// Bottom margin of the previous sibling, `None` at the start of a flow root.
pub(super) pending_margin: Option<f32>,
pub(super) embed_depth: usize,
pub(super) visited_embeds: BTreeSet<String>,
}
impl BlockFlow {
@@ -75,6 +77,8 @@ impl BlockFlow {
stats: FlowStats::default(),
y: 0.0,
pending_margin: None,
embed_depth: 0,
visited_embeds: BTreeSet::new(),
};
if let Some(root) = &input.snapshot.root {
@@ -103,8 +107,16 @@ impl BlockFlow {
pass.pending_margin = None;
match &child.content {
BlockContent::Note { hidden: true, .. } => continue,
BlockContent::Note { .. } => pass.flow(&child.children, 0.0, 0, default_align),
_ => pass.flow(std::slice::from_ref(child), 0.0, 0, default_align),
BlockContent::Note { .. } => {
pass.flow(&child.children, 0.0, input.width, 0, default_align)
}
_ => pass.flow(
std::slice::from_ref(child),
0.0,
input.width,
0,
default_align,
),
}
pass.y += pass.pending_margin.take().unwrap_or(0.0);
}
@@ -128,6 +140,17 @@ impl BlockFlow {
nodes: &[BlockNode],
input: &FlowInput<'_>,
window: &Window,
) -> FlowLayout {
self.layout_nodes_nested(nodes, input, window, 0, BTreeSet::new())
}
pub(super) fn layout_nodes_nested(
&mut self,
nodes: &[BlockNode],
input: &FlowInput<'_>,
window: &Window,
embed_depth: usize,
visited_embeds: BTreeSet<String>,
) -> FlowLayout {
let direction = input.direction;
let default_align = match direction {
@@ -146,8 +169,10 @@ impl BlockFlow {
stats: FlowStats::default(),
y: 0.0,
pending_margin: None,
embed_depth,
visited_embeds,
};
pass.flow(nodes, 0.0, 0, default_align);
pass.flow(nodes, 0.0, input.width, 0, default_align);
pass.y += pass.pending_margin.take().unwrap_or(0.0);
self.bodies = pass.next;
FlowLayout {
@@ -213,12 +238,14 @@ impl<'a> FlowPass<'a> {
body
}
/// Place `nodes` as siblings at horizontal offset `x`, collapsing vertical margins.
/// `inherited_align` is the text alignment of the nearest ancestor that sets one.
/// Place `nodes` as siblings at horizontal offset `x` within `max_right`, collapsing
/// vertical margins. `inherited_align` is the text alignment of the nearest ancestor
/// that sets one.
fn flow(
&mut self,
nodes: &[BlockNode],
x: f32,
max_right: f32,
list_depth: usize,
inherited_align: BlockAlign,
) {
@@ -234,22 +261,51 @@ impl<'a> FlowPass<'a> {
continue;
}
let width = (self.input.width - x).max(0.0);
let width = (max_right - x).max(0.0);
let block_x = match self.direction {
ui::Direction::Ltr => x,
ui::Direction::Rtl => 0.0,
ui::Direction::Rtl => (self.input.width - max_right).max(0.0),
};
let align = match &node.content {
BlockContent::Paragraph { text_align, .. }
| BlockContent::List { text_align, .. } => text_align.unwrap_or(inherited_align),
_ => inherited_align,
};
let draft_for_node = self.input.equation_draft.filter(|d| match d {
EquationDraft::Block { block_id, .. } | EquationDraft::Inline { block_id, .. } => {
block_id == &node.id
}
});
let preview_rev = super::preview::node_preview_fingerprint(
node,
draft_for_node,
self.input.pdf_previews,
);
let embed_preview = match &node.content {
BlockContent::EmbedLinkedDoc { page_id, .. }
| BlockContent::EmbedSyncedDoc { page_id, .. } => {
self.input.doc_directory.and_then(|dir| {
dir.doc_preview(&crate::directory::EditorDocId::from(page_id.as_str()))
})
}
_ => None,
};
let surface_ref_sig = match &node.content {
BlockContent::SurfaceRef { reference, .. } => {
super::surface_ref::surface_ref_fingerprint(self.input.snapshot, reference)
}
_ => 0,
};
let fingerprint = (
&node.content,
node.children.is_empty(),
width.to_bits(),
list_depth,
align,
preview_rev,
draft_for_node,
embed_preview,
surface_ref_sig,
);
let body = self.body(&node.id, &fingerprint, |pass| {
pass.block_body(node, width, list_depth, align)
@@ -262,6 +318,10 @@ impl<'a> FlowPass<'a> {
let block_idx = self.blocks.len();
let block_top = self.y;
let is_callout = matches!(node.content, BlockContent::Callout { .. });
let callout_has_own_text = matches!(
&node.content,
BlockContent::Callout { text, .. } if !text.plain.trim().is_empty()
);
self.blocks.push(FlowBlock {
block_id: node.id.clone(),
snapshot_id: SharedString::from(format!("page.block.{}", node.id)),
@@ -282,18 +342,44 @@ impl<'a> FlowPass<'a> {
_ => (true, 0),
};
if shows_children && !node.children.is_empty() {
// The block's own row has no bottom margin; the last child's bottom margin
// collapses through the children container into the block's.
self.pending_margin = Some(0.0);
let child_x = if is_callout {
x + 16.0
} else {
x + CHILD_INDENT
};
self.flow(&node.children, child_x, child_depth, align);
if is_callout {
let pad_bottom = 12.0;
let wrapped_h = (self.y - block_top + pad_bottom).max(body.height);
// Horizontal callout layout (`callout-block-styles.ts`):
// emoji sits at `(x + 10, block_top + 5)` and child content starts on the
// SAME row at `(x + 44, block_top + 5)` with width `width - 54`.
let pad_top = super::rich_blocks::CALLOUT_PAD_Y;
let pad_x = super::rich_blocks::CALLOUT_PAD_X;
let content_indent = pad_x
+ super::rich_blocks::CALLOUT_ICON_SLOT
+ super::rich_blocks::CALLOUT_CONTENT_GAP;
let start_y = if callout_has_own_text {
self.y
} else {
block_top + pad_top
};
self.y = start_y;
self.pending_margin = None;
let child_start_idx = self.blocks.len();
let child_x = x + content_indent;
let child_max_right = (x + width - pad_x).max(child_x + 1.0);
self.flow(&node.children, child_x, child_max_right, child_depth, align);
// Suppress top margin of the first child so it aligns directly with the emoji.
if !callout_has_own_text
&& let Some(first_child) = self.blocks.get(child_start_idx)
{
let shift_up = first_child.y - start_y;
if shift_up > 0.0 {
for child_blk in &mut self.blocks[child_start_idx..] {
child_blk.y -= shift_up;
}
self.y -= shift_up;
}
}
let content_bottom = self.blocks[child_start_idx..]
.iter()
.map(|b| b.rect().bottom())
.fold(start_y, f32::max);
let wrapped_h = (content_bottom - block_top + pad_top)
.max(super::rich_blocks::CALLOUT_MIN_HEIGHT);
let mut wrapped = (*self.blocks[block_idx].body).clone();
wrapped.height = wrapped_h;
if let Some(Prim::Quad { rect, .. }) = wrapped.prims.first_mut() {
@@ -301,8 +387,18 @@ impl<'a> FlowPass<'a> {
}
self.blocks[block_idx].body = Rc::new(wrapped);
self.y = block_top + wrapped_h;
self.pending_margin = Some(CARD_BLOCK_MARGIN);
self.pending_margin = Some(super::rich_blocks::CALLOUT_MARGIN_Y);
} else {
// The block's own row has no bottom margin; the last child's bottom margin
// collapses through the children container into the block's.
self.pending_margin = Some(0.0);
self.flow(
&node.children,
x + CHILD_INDENT,
max_right,
child_depth,
align,
);
self.pending_margin =
Some(self.pending_margin.unwrap_or(0.0).max(body.margin_bottom));
}
@@ -374,6 +470,7 @@ impl<'a> FlowPass<'a> {
BlockAlign::Right => TextAlign::Right,
};
style.text_color = ink;
style.dpr = self.window.scale_factor();
FlowTextLayout::Rich(Arc::new(paragraph.layout(
self.window.text_system(),
&style,
@@ -456,7 +553,19 @@ impl<'a> FlowPass<'a> {
text,
collapsed,
..
} => self.paragraph_body(*kind, text, *collapsed, width, align),
} => {
if let Some(EquationDraft::Inline {
block_id,
utf16_offset,
latex,
}) = self.input.equation_draft
&& block_id == &node.id
{
let patched = patch_inline_latex_draft(text, *utf16_offset, latex);
return self.paragraph_body(*kind, &patched, *collapsed, width, align);
}
self.paragraph_body(*kind, text, *collapsed, width, align)
}
BlockContent::List {
kind,
checked,
@@ -464,16 +573,37 @@ impl<'a> FlowPass<'a> {
text,
numbered_index,
..
} => self.list_body(
*kind,
*checked,
*collapsed && !node.children.is_empty(),
text,
numbered_index.unwrap_or(1),
list_depth,
width,
align,
),
} => {
if let Some(EquationDraft::Inline {
block_id,
utf16_offset,
latex,
}) = self.input.equation_draft
&& block_id == &node.id
{
let patched = patch_inline_latex_draft(text, *utf16_offset, latex);
return self.list_body(
*kind,
*checked,
*collapsed && !node.children.is_empty(),
&patched,
numbered_index.unwrap_or(1),
list_depth,
width,
align,
);
}
self.list_body(
*kind,
*checked,
*collapsed && !node.children.is_empty(),
text,
numbered_index.unwrap_or(1),
list_depth,
width,
align,
)
}
BlockContent::Divider => self.divider_body(width),
BlockContent::Code {
language,
@@ -499,7 +629,16 @@ impl<'a> FlowPass<'a> {
caption,
width,
),
BlockContent::Latex { latex } => self.latex_body(latex, width),
BlockContent::Latex { latex } => {
let effective = match self.input.equation_draft {
Some(EquationDraft::Block {
block_id,
latex: draft,
}) if block_id == &node.id => draft.as_str(),
_ => latex.as_str(),
};
self.latex_body(effective, width)
}
BlockContent::Callout {
icon,
text,
@@ -537,3 +676,70 @@ impl<'a> FlowPass<'a> {
}
}
}
/// Applies an in-flight committed equation draft to a single inline latex unit at `utf16_offset`
/// without mutating the CRDT document.
fn patch_inline_latex_draft(text: &RichText, target_utf16: u64, draft: &str) -> RichText {
let mut patched = Vec::with_capacity(text.delta.len() + 2);
let mut pos = 0u64;
for op in &text.delta {
match op {
y_octo::TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text(s),
format,
} => {
let len = s.encode_utf16().count() as u64;
if target_utf16 >= pos
&& target_utf16 < pos + len
&& format.as_ref().is_some_and(|f| f.contains_key("latex"))
{
let rel = (target_utf16 - pos) as usize;
let mut u16_cursor = 0usize;
let mut byte_start = 0usize;
let mut byte_end = s.len();
for (b, ch) in s.char_indices() {
if u16_cursor == rel {
byte_start = b;
byte_end = b + ch.len_utf8();
break;
}
u16_cursor += ch.len_utf16();
}
if byte_start > 0 {
patched.push(y_octo::TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text(s[..byte_start].to_string()),
format: format.clone(),
});
}
let mut new_fmt = format.clone().unwrap_or_default();
new_fmt.insert("latex".to_string(), y_octo::Any::String(draft.to_string()));
patched.push(y_octo::TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text(s[byte_start..byte_end].to_string()),
format: Some(new_fmt),
});
if byte_end < s.len() {
patched.push(y_octo::TextDeltaOp::Insert {
insert: y_octo::TextInsert::Text(s[byte_end..].to_string()),
format: format.clone(),
});
}
} else {
patched.push(op.clone());
}
pos += len;
}
y_octo::TextDeltaOp::Insert {
insert: y_octo::TextInsert::Embed(v),
..
} => {
patched.push(op.clone());
pos += v.len() as u64;
}
_ => patched.push(op.clone()),
}
}
RichText {
plain: text.plain.clone(),
delta: patched,
}
}
@@ -1,775 +0,0 @@
//! Zero-dependency pure-Rust 2D mathematical typesetting for LaTeX expressions.
//!
//! Renders common LaTeX constructs (`\frac`, `\sqrt`, superscripts/subscripts,
//! `\int`/`\sum`/`\prod` limits, Greek letters, and mathematical operators) into
//! GPUI `Prim::Text` and `Prim::Quad` vector primitives using the already-bundled
//! fonts, avoiding any binary size overhead in the main Web Wasm bundle.
use std::rc::Rc;
use ui::{Hsla, Window};
use crate::theme::FONT_SANS;
use super::{
FlowRect, InlineAlign, InlineBaseline, InlineStyle, Prim,
inline::{layout_inline, shape},
};
#[derive(Clone, Debug, PartialEq)]
enum MathNode {
Text(String),
BigOp(String),
Frac {
num: Vec<MathNode>,
den: Vec<MathNode>,
},
Sqrt(Vec<MathNode>),
Script {
base: Box<MathNode>,
sup: Option<Vec<MathNode>>,
sub: Option<Vec<MathNode>>,
},
Group(Vec<MathNode>),
}
fn latex_symbol(cmd: &str) -> Option<&'static str> {
Some(match cmd {
"alpha" => "\u{03B1}",
"beta" => "\u{03B2}",
"gamma" => "\u{03B3}",
"delta" => "\u{03B4}",
"epsilon" | "varepsilon" => "\u{03B5}",
"zeta" => "\u{03B6}",
"eta" => "\u{03B7}",
"theta" | "vartheta" => "\u{03B8}",
"iota" => "\u{03B9}",
"kappa" => "\u{03BA}",
"lambda" => "\u{03BB}",
"mu" => "\u{03BC}",
"nu" => "\u{03BD}",
"xi" => "\u{03BE}",
"pi" | "varpi" => "\u{03C0}",
"rho" | "varrho" => "\u{03C1}",
"sigma" | "varsigma" => "\u{03C3}",
"tau" => "\u{03C4}",
"upsilon" => "\u{03C5}",
"phi" | "varphi" => "\u{03C6}",
"chi" => "\u{03C7}",
"psi" => "\u{03C8}",
"omega" => "\u{03C9}",
"Gamma" => "\u{0393}",
"Delta" => "\u{0394}",
"Theta" => "\u{0398}",
"Lambda" => "\u{039B}",
"Xi" => "\u{039E}",
"Pi" => "\u{03A0}",
"Sigma" => "\u{03A3}",
"Phi" => "\u{03A6}",
"Psi" => "\u{03A8}",
"Omega" => "\u{03A9}",
"infty" => "\u{221E}",
"pm" => "\u{00B1}",
"mp" => "\u{2213}",
"times" => "\u{00D7}",
"cdot" => "\u{00B7}",
"div" => "\u{00F7}",
"leq" | "le" => "\u{2264}",
"geq" | "ge" => "\u{2265}",
"neq" | "ne" => "\u{2260}",
"approx" => "\u{2248}",
"equiv" => "\u{2261}",
"to" | "rightarrow" => "\u{2192}",
"leftarrow" => "\u{2190}",
"Rightarrow" => "\u{21D2}",
"Leftarrow" => "\u{21D0}",
"iff" | "Leftrightarrow" => "\u{21D4}",
"partial" => "\u{2202}",
"nabla" => "\u{2207}",
"forall" => "\u{2200}",
"exists" => "\u{2203}",
"in" => "\u{2208}",
"notin" => "\u{2209}",
"subset" => "\u{2282}",
"subseteq" => "\u{2286}",
"cup" => "\u{222A}",
"cap" => "\u{2229}",
"dots" | "ldots" | "cdots" => "\u{2026}",
"sin" => "sin",
"cos" => "cos",
"tan" => "tan",
"log" => "log",
"ln" => "ln",
"exp" => "exp",
"lim" => "lim",
"max" => "max",
"min" => "min",
"," | ";" | " " | "quad" | "qquad" => " ",
"left" | "right" | "displaystyle" | "textstyle" => "",
_ => return None,
})
}
fn big_op_symbol(cmd: &str) -> Option<&'static str> {
Some(match cmd {
"int" => "\u{222B}",
"iint" => "\u{222C}",
"oint" => "\u{222E}",
"sum" => "\u{2211}",
"prod" => "\u{220F}",
_ => return None,
})
}
const MAX_MATH_NESTING: usize = 64;
struct Parser<'a> {
src: &'a str,
pos: usize,
}
impl<'a> Parser<'a> {
fn new(src: &'a str) -> Self {
Self { src, pos: 0 }
}
fn peek(&self) -> Option<char> {
self.src[self.pos..].chars().next()
}
fn bump(&mut self) -> Option<char> {
let ch = self.peek()?;
self.pos += ch.len_utf8();
Some(ch)
}
fn skip_ws(&mut self) {
while matches!(self.peek(), Some(c) if c.is_whitespace()) {
self.bump();
}
}
fn parse_seq(&mut self, stop_brace: bool, depth: usize) -> Vec<MathNode> {
let mut nodes = Vec::new();
while let Some(ch) = self.peek() {
if stop_brace && ch == '}' {
self.bump();
break;
}
if ch.is_whitespace() {
self.bump();
continue;
}
if depth >= MAX_MATH_NESTING {
self.bump();
nodes.push(MathNode::Text(ch.to_string()));
continue;
}
if ch == '^' || ch == '_' {
let is_sup = ch == '^';
self.bump();
let arg = self.parse_arg(depth + 1);
let base = nodes.pop().unwrap_or_else(|| MathNode::Text(String::new()));
let merged = match base {
MathNode::Script {
base,
mut sup,
mut sub,
} => {
if is_sup {
sup = Some(arg);
} else {
sub = Some(arg);
}
MathNode::Script { base, sup, sub }
}
other => MathNode::Script {
base: Box::new(other),
sup: is_sup.then_some(arg.clone()),
sub: (!is_sup).then_some(arg),
},
};
nodes.push(merged);
continue;
}
if let Some(atom) = self.parse_atom(depth) {
nodes.push(atom);
}
}
nodes
}
fn consume_flat_token(&mut self) -> Option<String> {
let ch = self.bump()?;
if ch == '\\' {
let start = self.pos;
if let Some(next) = self.peek() {
if next.is_ascii_alphabetic() {
while matches!(self.peek(), Some(c) if c.is_ascii_alphabetic()) {
self.bump();
}
} else {
self.bump();
}
}
let cmd = &self.src[start..self.pos];
return Some(format!("\\{cmd}"));
}
Some(ch.to_string())
}
fn parse_arg(&mut self, depth: usize) -> Vec<MathNode> {
self.skip_ws();
if depth >= MAX_MATH_NESTING {
if self.peek() == Some('{') {
self.bump();
let mut lit = String::new();
let mut balance = 1usize;
while let Some(c) = self.bump() {
match c {
'{' => {
balance += 1;
lit.push(c);
}
'}' => {
balance -= 1;
if balance == 0 {
break;
}
lit.push(c);
}
_ => lit.push(c),
}
}
return vec![MathNode::Text(lit)];
}
return self
.consume_flat_token()
.map(|t| vec![MathNode::Text(t)])
.unwrap_or_default();
}
if self.peek() == Some('{') {
self.bump();
self.parse_seq(true, depth + 1)
} else {
self.parse_atom(depth).into_iter().collect()
}
}
fn parse_braced_plain(&mut self) -> String {
self.skip_ws();
if self.peek() != Some('{') {
return self.bump().map(|c| c.to_string()).unwrap_or_default();
}
self.bump();
let mut out = String::new();
while let Some(c) = self.bump() {
if c == '}' {
break;
}
out.push(c);
}
out
}
fn parse_atom(&mut self, depth: usize) -> Option<MathNode> {
if depth >= MAX_MATH_NESTING {
return self.consume_flat_token().map(MathNode::Text);
}
let ch = self.bump()?;
match ch {
'{' => {
if depth >= MAX_MATH_NESTING {
Some(MathNode::Text("{".into()))
} else {
Some(MathNode::Group(self.parse_seq(true, depth + 1)))
}
}
'\\' => {
let start = self.pos;
if let Some(next) = self.peek() {
if next.is_ascii_alphabetic() {
while matches!(self.peek(), Some(c) if c.is_ascii_alphabetic()) {
self.bump();
}
} else {
self.bump();
}
}
let cmd = &self.src[start..self.pos];
match cmd {
"\\" => Some(MathNode::Text("; ".into())),
"frac" | "dfrac" | "tfrac" => {
let num = self.parse_arg(depth + 1);
let den = self.parse_arg(depth + 1);
Some(MathNode::Frac { num, den })
}
"sqrt" => {
self.skip_ws();
if self.peek() == Some('[') {
while let Some(c) = self.bump() {
if c == ']' {
break;
}
}
}
let body = self.parse_arg(depth + 1);
Some(MathNode::Sqrt(body))
}
"mathbb" => {
let arg = self.parse_braced_plain();
let mapped: String = arg
.chars()
.map(|c| match c {
'R' => '\u{211D}',
'N' => '\u{2115}',
'Z' => '\u{2124}',
'Q' => '\u{211A}',
'C' => '\u{2102}',
other => other,
})
.collect();
Some(MathNode::Text(mapped))
}
"vec" | "hat" | "bar" | "tilde" => {
let arg = self.parse_braced_plain();
let mark = match cmd {
"vec" => '\u{20D7}',
"hat" => '\u{0302}',
"bar" => '\u{0304}',
_ => '\u{0303}',
};
let mut out = String::new();
for c in arg.chars() {
out.push(c);
out.push(mark);
}
Some(MathNode::Text(out))
}
"begin" => {
let env = self.parse_braced_plain();
let open = match env.as_str() {
"pmatrix" => "(",
"bmatrix" => "[",
"Bmatrix" => "{",
"vmatrix" => "|",
_ => "",
};
if open.is_empty() {
None
} else {
Some(MathNode::Text(open.to_string()))
}
}
"end" => {
let env = self.parse_braced_plain();
let close = match env.as_str() {
"pmatrix" => ")",
"bmatrix" => "]",
"Bmatrix" => "}",
"vmatrix" => "|",
_ => "",
};
if close.is_empty() {
None
} else {
Some(MathNode::Text(close.to_string()))
}
}
"text" | "mathrm" | "mathbf" | "mathit" | "operatorname" => {
Some(MathNode::Group(self.parse_arg(depth + 1)))
}
_ if big_op_symbol(cmd).is_some() => {
Some(MathNode::BigOp(big_op_symbol(cmd).unwrap().to_string()))
}
_ if latex_symbol(cmd).is_some() => {
let sym = latex_symbol(cmd).unwrap();
if sym.is_empty() {
None
} else {
Some(MathNode::Text(sym.to_string()))
}
}
_ => Some(MathNode::Text(cmd.to_string())),
}
}
'&' => Some(MathNode::Text(" ".into())),
'-' => Some(MathNode::Text("\u{2212}".into())),
'=' | '+' | '<' | '>' => Some(MathNode::Text(format!(" {ch} "))),
other => Some(MathNode::Text(other.to_string())),
}
}
}
struct MathBox {
width: f32,
ascent: f32,
descent: f32,
prims: Vec<Prim>,
}
impl MathBox {
fn height(&self) -> f32 {
self.ascent + self.descent
}
}
fn translate_prims(prims: &mut [Prim], dx: f32, dy: f32) {
for prim in prims {
match prim {
Prim::Text { x, y, .. } => {
*x += dx;
*y += dy;
}
Prim::Quad { rect, .. } | Prim::Image { rect, .. } | Prim::Icon { rect, .. } => {
*rect = rect.translated(dx, dy);
}
_ => {}
}
}
}
fn layout_text_atom(text: &str, size: f32, color: Hsla, window: &Window) -> MathBox {
let style = InlineStyle::new(FONT_SANS, size, 400.0, color);
let width = f32::from(shape(window, text, &style).width).max(1.0);
let line_height = (size * 1.25).ceil();
let layout = Rc::new(layout_inline(
text,
&style,
width + 2.0,
line_height,
InlineBaseline::Of(&style),
InlineAlign::Left,
window,
));
let ascent = (line_height * 0.78).round();
let descent = (line_height - ascent).max(2.0);
MathBox {
width,
ascent,
descent,
prims: vec![Prim::Text {
x: 0.0,
y: 0.0,
layout,
clip: None,
}],
}
}
fn layout_seq(nodes: &[MathNode], size: f32, color: Hsla, window: &Window) -> MathBox {
let mut boxes: Vec<MathBox> = nodes
.iter()
.map(|n| layout_node(n, size, color, window))
.collect();
let ascent = boxes
.iter()
.map(|b| b.ascent)
.fold((size * 0.78).round(), f32::max);
let descent = boxes
.iter()
.map(|b| b.descent)
.fold((size * 0.25).round(), f32::max);
let mut x = 0.0;
let mut prims = Vec::new();
for b in &mut boxes {
let dy = ascent - b.ascent;
translate_prims(&mut b.prims, x, dy);
prims.append(&mut b.prims);
x += b.width;
}
MathBox {
width: x.max(1.0),
ascent,
descent,
prims,
}
}
fn layout_node(node: &MathNode, size: f32, color: Hsla, window: &Window) -> MathBox {
match node {
MathNode::Text(s) => layout_text_atom(s, size, color, window),
MathNode::BigOp(s) => layout_text_atom(s, size * 1.45, color, window),
MathNode::Group(children) => layout_seq(children, size, color, window),
MathNode::Frac { num, den } => {
let sub_size = (size * 0.84).max(10.0);
let mut n = layout_seq(num, sub_size, color, window);
let mut d = layout_seq(den, sub_size, color, window);
let n_h = n.height();
let d_h = d.height();
let bar_w = n.width.max(d.width) + 6.0;
let bar_h = 1.25;
let gap = 2.5;
let num_x = ((bar_w - n.width) / 2.0).round();
let den_x = ((bar_w - d.width) / 2.0).round();
let axis_y = n_h + gap;
let den_y = axis_y + bar_h + gap;
translate_prims(&mut n.prims, num_x, 0.0);
translate_prims(&mut d.prims, den_x, den_y);
let mut prims = n.prims;
prims.push(Prim::Quad {
rect: FlowRect::new(0.0, axis_y, bar_w, bar_h),
fill: Some(color),
border: None,
radius: 0.0,
dashed: false,
});
prims.append(&mut d.prims);
let total_h = den_y + d_h;
let math_axis_from_baseline = size * 0.30;
let ascent = (axis_y + math_axis_from_baseline).max(n_h);
let descent = (total_h - ascent).max(d_h * 0.5);
MathBox {
width: bar_w + 4.0,
ascent,
descent,
prims,
}
}
MathNode::Sqrt(body) => {
let mut inner = layout_seq(body, size, color, window);
let mut rad = layout_text_atom("\u{221A}", size * 1.1, color, window);
let pad_top = 3.0;
let rad_w = rad.width;
let rad_dy = (inner.height() - rad.height()).max(0.0);
let bar_y = 1.0;
translate_prims(&mut rad.prims, 0.0, rad_dy);
translate_prims(&mut inner.prims, rad_w + 1.0, pad_top);
let mut prims = rad.prims;
prims.push(Prim::Quad {
rect: FlowRect::new(rad_w, bar_y, inner.width + 3.0, 1.2),
fill: Some(color),
border: None,
radius: 0.0,
dashed: false,
});
prims.append(&mut inner.prims);
MathBox {
width: rad_w + inner.width + 5.0,
ascent: inner.ascent + pad_top,
descent: inner.descent,
prims,
}
}
MathNode::Script { base, sup, sub } => {
let mut b = layout_node(base, size, color, window);
let script_size = (size * 0.70).max(9.0);
let mut sup_box = sup
.as_ref()
.map(|s| layout_seq(s, script_size, color, window));
let mut sub_box = sub
.as_ref()
.map(|s| layout_seq(s, script_size, color, window));
let script_x = b.width + 1.0;
let script_w = sup_box
.as_ref()
.map_or(0.0, |s| s.width)
.max(sub_box.as_ref().map_or(0.0, |s| s.width));
let sup_lift = (b.ascent * 0.52).round();
let extra_top = sup_box
.as_ref()
.map_or(0.0, |s| (s.ascent + sup_lift - b.ascent).max(0.0));
let sub_drop = (b.descent + script_size * 0.35).round();
let extra_bottom = sub_box
.as_ref()
.map_or(0.0, |s| (sub_drop + s.descent - b.descent).max(0.0));
translate_prims(&mut b.prims, 0.0, extra_top);
let mut prims = b.prims;
let baseline = extra_top + b.ascent;
if let Some(mut s) = sup_box.take() {
let sy = (baseline - sup_lift - s.ascent).max(0.0);
translate_prims(&mut s.prims, script_x, sy);
prims.append(&mut s.prims);
}
if let Some(mut s) = sub_box.take() {
let sy = baseline + sub_drop - s.ascent;
translate_prims(&mut s.prims, script_x, sy);
prims.append(&mut s.prims);
}
MathBox {
width: script_x + script_w + 2.0,
ascent: b.ascent + extra_top,
descent: b.descent + extra_bottom,
prims,
}
}
}
}
/// Lay out a LaTeX expression into 2D vector primitives (`(width, height, prims)`).
pub(super) fn layout_math_2d(
latex: &str,
font_size: f32,
color: Hsla,
window: &Window,
) -> (f32, f32, Vec<Prim>) {
let nodes = Parser::new(latex).parse_seq(false, 0);
let mbox = layout_seq(&nodes, font_size, color, window);
(mbox.width, mbox.height(), mbox.prims)
}
fn to_superscript_char(ch: char) -> Option<char> {
Some(match ch {
'0' => '\u{2070}',
'1' => '\u{00B9}',
'2' => '\u{00B2}',
'3' => '\u{00B3}',
'4' => '\u{2074}',
'5' => '\u{2075}',
'6' => '\u{2076}',
'7' => '\u{2077}',
'8' => '\u{2078}',
'9' => '\u{2079}',
'+' => '\u{207A}',
'-' | '\u{2212}' => '\u{207B}',
'=' => '\u{207C}',
'(' => '\u{207D}',
')' => '\u{207E}',
'i' => '\u{2071}',
'n' => '\u{207F}',
_ => return None,
})
}
fn to_subscript_char(ch: char) -> Option<char> {
Some(match ch {
'0' => '\u{2080}',
'1' => '\u{2081}',
'2' => '\u{2082}',
'3' => '\u{2083}',
'4' => '\u{2084}',
'5' => '\u{2085}',
'6' => '\u{2086}',
'7' => '\u{2087}',
'8' => '\u{2088}',
'9' => '\u{2089}',
'+' => '\u{208A}',
'-' | '\u{2212}' => '\u{208B}',
'=' => '\u{208C}',
'(' => '\u{208D}',
')' => '\u{208E}',
'i' => '\u{1D62}',
'n' => '\u{2099}',
'x' => '\u{2093}',
_ => return None,
})
}
fn format_nodes_inline(nodes: &[MathNode], out: &mut String) {
for node in nodes {
match node {
MathNode::Text(s) | MathNode::BigOp(s) => out.push_str(s),
MathNode::Group(g) => format_nodes_inline(g, out),
MathNode::Frac { num, den } => {
out.push('(');
format_nodes_inline(num, out);
out.push('/');
format_nodes_inline(den, out);
out.push(')');
}
MathNode::Sqrt(body) => {
out.push('\u{221A}');
out.push('(');
format_nodes_inline(body, out);
out.push(')');
}
MathNode::Script { base, sup, sub } => {
format_nodes_inline(std::slice::from_ref(base.as_ref()), out);
if let Some(s) = sub {
let mut tmp = String::new();
format_nodes_inline(s, &mut tmp);
if tmp.chars().all(|c| to_subscript_char(c).is_some()) {
for c in tmp.chars() {
out.push(to_subscript_char(c).unwrap());
}
} else {
out.push('_');
out.push_str(&tmp);
}
}
if let Some(s) = sup {
let mut tmp = String::new();
format_nodes_inline(s, &mut tmp);
if tmp.chars().all(|c| to_superscript_char(c).is_some()) {
for c in tmp.chars() {
out.push(to_superscript_char(c).unwrap());
}
} else {
out.push('^');
out.push_str(&tmp);
}
}
}
}
}
}
/// Format an inline LaTeX expression into Unicode math symbols and scripts when
/// no external `MathPreviewProvider` rasterizer is mounted.
pub fn format_inline_math_unicode(latex: &str) -> String {
let nodes = Parser::new(latex).parse_seq(false, 0);
let mut out = String::new();
format_nodes_inline(&nodes, &mut out);
out.trim().to_string()
}
#[cfg(test)]
mod tests {
use super::{MathNode, Parser, format_inline_math_unicode};
fn ast_depth(nodes: &[MathNode]) -> usize {
nodes
.iter()
.map(|n| match n {
MathNode::Text(_) | MathNode::BigOp(_) => 1,
MathNode::Group(inner) | MathNode::Sqrt(inner) => 1 + ast_depth(inner),
MathNode::Frac { num, den } => 1 + ast_depth(num).max(ast_depth(den)),
MathNode::Script { base, sup, sub } => {
let b = ast_depth(std::slice::from_ref(base.as_ref()));
let s1 = sup.as_deref().map(ast_depth).unwrap_or(0);
let s2 = sub.as_deref().map(ast_depth).unwrap_or(0);
1 + b.max(s1).max(s2)
}
})
.max()
.unwrap_or(0)
}
#[test]
fn math_parser_handles_deep_nesting_on_1mib_stack_and_common_commands() {
assert_eq!(
format_inline_math_unicode(r"\mathbb{R}^n"),
"\u{211D}\u{207F}"
);
let matrix = format_inline_math_unicode(r"\begin{matrix} a & b \\ c & d \end{matrix}");
assert!(
!matrix.contains("beginmatrix"),
"unexpected matrix output: {matrix}"
);
assert!(matrix.contains("; "));
// Braced and unbraced command chains must never overflow a 1 MiB stack
// and must produce strictly bounded AST depth (<= 66).
let handle = std::thread::Builder::new()
.stack_size(1024 * 1024)
.spawn(|| {
let cases = [
format!("{}x{}", "{".repeat(128_000), "}".repeat(128_000)),
format!("{}x", r"\sqrt".repeat(64_000)),
format!("{}2", r"\frac 1 ".repeat(32_000)),
r"\text a ".repeat(64_000),
];
for src in &cases {
let nodes = Parser::new(src).parse_seq(false, 0);
let depth = ast_depth(&nodes);
assert!(depth <= 66, "AST depth exceeded bound: {depth}");
let out = format_inline_math_unicode(src);
assert!(!out.is_empty());
}
})
.expect("spawn 1MiB thread");
handle
.join()
.expect("deep nesting must not overflow 1 MiB stack");
}
}
+16 -9
View File
@@ -13,27 +13,32 @@
mod blocks;
mod body;
mod embed_blocks;
mod inline;
mod layout;
mod math_layout;
mod preview;
mod rich_blocks;
mod surface_ref;
mod table_block;
mod viewport;
pub use body::{
AttachmentPdfControls, BlockBody, BlockPaint, CodeScroll, FlowBlock, FlowInput, FlowKind,
FlowLayout, FlowStats, FlowText, FlowTextLayout, PagePaint, ScrolledCode, TableCellHit,
paint_chevron,
AttachmentPdfControls, BlockBody, BlockPaint, CodeScroll, EquationDraft, FlowBlock, FlowInput,
FlowKind, FlowLayout, FlowStats, FlowText, FlowTextLayout, PagePaint, ScrolledCode,
TableCellHit, paint_chevron,
};
pub use embed_blocks::civil_from_days;
pub use inline::{
ImageSlot, InlineAlign, InlineBaseline, InlineLayout, InlineStyle, decode_image, layout_inline,
ImageSlot, InlineAlign, InlineBaseline, InlineLayout, InlineStyle, decode_image,
decode_image_with_dimensions, layout_inline,
};
pub use layout::BlockFlow;
pub use math_layout::format_inline_math_unicode;
pub use preview::{
EmbeddedPdfDocument, MathPreviewProvider, MathRenderSlot, PdfPageProvider, PdfPreviewPage,
can_render_pdf_pages, parse_pdf_renderer, register_math_preview_provider,
register_pdf_page_provider, render_math_cached, render_pdf_page,
EmbeddedPdfDocument, MathPreviewProvider, MathRenderResult, MathRenderSlot, PdfPageCount,
PdfPageProvider, PdfParseResult, PdfPreviewPage, bump_latex_formula_revision,
bump_preview_revision, can_render_pdf_pages, hsla_to_css_hex, latex_formula_revision,
parse_pdf_document, parse_pdf_renderer, preview_revision, register_math_preview_provider,
register_pdf_page_provider, render_math_cached, render_pdf_page, rgba_pixels_to_render_image,
};
pub use viewport::{
PAGE_SURFACE_ID, PageViewport, PresenceMark, RemotePoint, RemotePresence, RemoteSelection,
@@ -534,6 +539,8 @@ mod tests {
page_titles: &titles,
images: &images,
pdf_previews: None,
doc_directory: None,
equation_draft: None,
env_rev: 0,
direction: Direction::Ltr,
};
+474 -315
View File
@@ -1,18 +1,23 @@
//! Narrow preview ports (`MathPreviewProvider`, `PdfPageProvider`) and optional
//! `preview-engine` (`RaTeX` + `Hayro`) bridge for `block_flow`.
//! Narrow preview ports (`MathPreviewProvider`, `PdfPageProvider`) and pure-Rust
//! `blocksuite-preview` (`RaTeX` + `Hayro`) integration for `block_flow`.
//!
//! When the `preview-engine` Cargo feature is enabled, this module uses in-process
//! `blocksuite-preview` (`RaTeX` + `Hayro`). When disabled (the default for the main Web
//! Wasm bundle and default `bs-harness`), callers can inject host/worker-rendered RGBA
//! frames via `register_math_preview_provider` / `register_pdf_page_provider`, and
//! `latex_body` renders genuine 2D mathematical notation using `math_layout::layout_math_2d`.
//! On all non-`wasm32` targets, `blocksuite-preview` (`math` + `pdf`) is compiled in directly.
//! On `wasm32`, hosts register worker-backed providers via `register_math_preview_provider` /
//! `register_pdf_page_provider` and bump [`bump_preview_revision`] whenever an async worker
//! result lands in cache so [`BlockFlow`] invalidates and repaints automatically.
use std::sync::{Arc, OnceLock, RwLock};
use std::{
collections::{HashMap, VecDeque},
hash::{Hash, Hasher},
sync::{
Arc, OnceLock, RwLock,
atomic::{AtomicU64, Ordering},
},
};
#[cfg(feature = "preview-engine")]
use std::collections::HashMap;
use blocksuite_playground_doc::read::{BlockContent, BlockNode, RichText};
#[cfg(feature = "preview-engine")]
#[cfg(not(target_arch = "wasm32"))]
use blocksuite_preview::{
FontPool, SvgRasterizer,
math::{MathDisplayMode, MathRenderOptions, render_latex_rgba},
@@ -21,7 +26,7 @@ use blocksuite_preview::{
};
use ui::{Hsla, RenderImage};
#[cfg(feature = "preview-engine")]
#[cfg(not(target_arch = "wasm32"))]
use crate::theme::{bundled_font_bytes, bundled_script_font_bytes};
/// Rasterized LaTeX formula ready to paint as a GPUI [`RenderImage`].
@@ -33,6 +38,18 @@ pub struct MathRenderSlot {
pub descent_pt: f32,
}
/// Three-state outcome of rendering a LaTeX math expression.
///
/// Distinguishes genuine syntax/parse errors (`Error` -> red `"Error equation"`) from async
/// Web Worker computations still in flight or an unconfigured worker (`Pending` -> clean
/// unframed fallback text, never `"Error equation"`).
#[derive(Clone)]
pub enum MathRenderResult {
Ready(MathRenderSlot),
Pending,
Error,
}
/// Rasterized PDF page preview ready to paint inside an `affine:attachment` block.
#[derive(Clone)]
pub struct PdfPreviewPage {
@@ -43,20 +60,39 @@ pub struct PdfPreviewPage {
pub height_pt: f32,
}
/// Narrow port allowing platform hosts (iOS PDFKit, Android PdfRenderer, Web PDF worker)
/// or tests to supply rasterized PDF pages without statically linking `hayro`.
/// Three-state outcome of querying a PDF's page count.
///
/// Distinguishes an asynchronous Web Worker computation still in flight (`Pending`) from a
/// corrupt/empty PDF (`Invalid`) so callers never permanently mark an in-flight PDF as failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PdfPageCount {
Ready(usize),
Pending,
Invalid,
}
/// Three-state outcome of parsing an [`EmbeddedPdfDocument`].
pub enum PdfParseResult {
Ready(EmbeddedPdfDocument),
Pending,
Invalid,
}
/// Narrow port allowing platform hosts (Web PDF worker, iOS PDFKit, Android PdfRenderer)
/// or tests to supply rasterized PDF pages.
pub trait PdfPageProvider: Send + Sync {
fn page_count(&self, bytes: &[u8]) -> Option<usize>;
fn page_count(&self, cache_key: &str, bytes: &[u8]) -> PdfPageCount;
fn render_pdf_page(
&self,
cache_key: &str,
bytes: &[u8],
page_index: usize,
scale: f32,
) -> Option<PdfPreviewPage>;
}
/// Narrow port allowing platform hosts (Web math worker, native RaTeX) or tests to supply
/// rasterized LaTeX math bitmaps without statically linking `ratex-katex-fonts`.
/// Narrow port allowing platform hosts (Web RaTeX math worker) or tests to supply
/// rasterized LaTeX math bitmaps.
pub trait MathPreviewProvider: Send + Sync {
fn render_math(
&self,
@@ -64,7 +100,132 @@ pub trait MathPreviewProvider: Send + Sync {
display: bool,
font_size_pt: f32,
color: Hsla,
) -> Option<MathRenderSlot>;
dpr: f32,
) -> MathRenderResult;
}
static PREVIEW_REVISION: AtomicU64 = AtomicU64::new(0);
fn formula_revisions() -> &'static RwLock<(HashMap<String, u64>, VecDeque<String>)> {
static REVS: OnceLock<RwLock<(HashMap<String, u64>, VecDeque<String>)>> = OnceLock::new();
REVS.get_or_init(|| RwLock::new((HashMap::new(), VecDeque::new())))
}
/// Monotonic revision bumped whenever an asynchronous preview result (math or PDF) lands in
/// cache. Views include this in their layout cache key to wake `BlockFlow` passes, while
/// per-block reuse fingerprints read [`latex_formula_revision`] and `pdf_previews` so only
/// blocks referencing the resolved formula or PDF page re-layout.
pub fn preview_revision() -> u64 {
PREVIEW_REVISION.load(Ordering::Acquire)
}
/// Increment [`preview_revision`] after writing a new preview result into a provider cache.
pub fn bump_preview_revision() -> u64 {
PREVIEW_REVISION.fetch_add(1, Ordering::AcqRel) + 1
}
/// Returns the per-formula revision stamp for `latex` (`0` before any async worker delivery).
pub fn latex_formula_revision(latex: &str) -> u64 {
let trimmed = latex.trim();
if trimmed.is_empty() {
return 0;
}
formula_revisions()
.read()
.ok()
.and_then(|guard| guard.0.get(trimmed).copied())
.unwrap_or(0)
}
/// Increments the per-formula revision stamp for `latex` and bumps [`preview_revision`].
pub fn bump_latex_formula_revision(latex: &str) -> u64 {
let trimmed = latex.trim();
if !trimmed.is_empty()
&& let Ok(mut guard) = formula_revisions().write()
{
let (map, order) = &mut *guard;
let next = map.get(trimmed).copied().unwrap_or(0).wrapping_add(1);
if !map.contains_key(trimmed) {
while map.len() >= 1024 {
let Some(oldest) = order.pop_front() else {
break;
};
map.remove(&oldest);
}
order.push_back(trimmed.to_string());
}
map.insert(trimmed.to_string(), next);
}
bump_preview_revision()
}
fn hash_rich_text_inline_latex<H: Hasher>(text: &RichText, hasher: &mut H, touched: &mut bool) {
for op in &text.delta {
if let y_octo::TextDeltaOp::Insert {
format: Some(attrs),
..
} = op
&& let Some(y_octo::Any::String(tex)) = attrs.get("latex")
{
*touched = true;
tex.trim().hash(hasher);
latex_formula_revision(tex).hash(hasher);
}
}
}
/// Computes a surgical per-block preview fingerprint so resolving one formula or PDF page
/// re-layouts only blocks referencing that specific formula or attachment (`0` for all other
/// blocks, and unchanged when an unrelated or stale formula finishes).
pub(super) fn node_preview_fingerprint(
node: &BlockNode,
draft_for_node: Option<&super::EquationDraft>,
pdf_previews: Option<&HashMap<String, PdfPreviewPage>>,
) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
let mut touched = false;
if let Some(draft) = draft_for_node {
touched = true;
match draft {
super::EquationDraft::Block { latex, .. }
| super::EquationDraft::Inline { latex, .. } => {
latex.trim().hash(&mut hasher);
latex_formula_revision(latex).hash(&mut hasher);
}
}
}
match &node.content {
BlockContent::Latex { latex } => {
touched = true;
latex.trim().hash(&mut hasher);
latex_formula_revision(latex).hash(&mut hasher);
}
BlockContent::Attachment { .. } => {
if let Some(pdf) = pdf_previews.and_then(|m| m.get(&node.id)) {
touched = true;
pdf.page_index.hash(&mut hasher);
pdf.page_count.hash(&mut hasher);
pdf.width_pt.to_bits().hash(&mut hasher);
pdf.height_pt.to_bits().hash(&mut hasher);
(Arc::as_ptr(&pdf.image) as usize).hash(&mut hasher);
}
}
BlockContent::Paragraph { text, .. }
| BlockContent::List { text, .. }
| BlockContent::Callout { text, .. } => {
hash_rich_text_inline_latex(text, &mut hasher, &mut touched);
}
BlockContent::Table(table) => {
for cell in table.cells.values() {
hash_rich_text_inline_latex(&cell.text, &mut hasher, &mut touched);
}
}
_ => {}
}
if touched { hasher.finish() } else { 0 }
}
fn pdf_provider_slot() -> &'static RwLock<Option<Arc<dyn PdfPageProvider>>> {
@@ -82,16 +243,17 @@ pub fn register_pdf_page_provider(provider: Option<Arc<dyn PdfPageProvider>>) {
if let Ok(mut guard) = pdf_provider_slot().write() {
*guard = provider;
}
bump_preview_revision();
}
/// Whether PDF page rasterization is available in this runtime (either via the built-in
/// `preview-engine` feature or a host-registered [`PdfPageProvider`]).
/// Whether PDF page rasterization is available in this runtime (built-in Hayro on native
/// targets or a host-registered [`PdfPageProvider`] on Web).
pub fn can_render_pdf_pages() -> bool {
#[cfg(feature = "preview-engine")]
#[cfg(not(target_arch = "wasm32"))]
{
true
}
#[cfg(not(feature = "preview-engine"))]
#[cfg(target_arch = "wasm32")]
{
pdf_provider_slot().read().ok().is_some_and(|g| g.is_some())
}
@@ -102,33 +264,44 @@ pub fn register_math_preview_provider(provider: Option<Arc<dyn MathPreviewProvid
if let Ok(mut guard) = math_provider_slot().write() {
*guard = provider;
}
bump_preview_revision();
}
/// Parsed PDF handle used to rasterize attachment preview pages on demand.
pub struct EmbeddedPdfDocument {
#[cfg(feature = "preview-engine")]
renderer: HayroPdfRenderer,
#[cfg(not(feature = "preview-engine"))]
#[cfg(not(target_arch = "wasm32"))]
renderer: Option<HayroPdfRenderer>,
#[cfg(not(target_arch = "wasm32"))]
provider_key: String,
#[cfg(not(target_arch = "wasm32"))]
provider_bytes: Vec<u8>,
#[cfg(not(target_arch = "wasm32"))]
provider_page_count: usize,
#[cfg(target_arch = "wasm32")]
cache_key: String,
#[cfg(target_arch = "wasm32")]
bytes: Vec<u8>,
#[cfg(not(feature = "preview-engine"))]
#[cfg(target_arch = "wasm32")]
page_count: usize,
}
impl EmbeddedPdfDocument {
/// Total number of pages in this PDF without rasterizing any page.
pub fn page_count(&self) -> usize {
#[cfg(feature = "preview-engine")]
#[cfg(not(target_arch = "wasm32"))]
{
self.renderer.page_count()
self.renderer
.as_ref()
.map_or(self.provider_page_count, |r| r.page_count())
}
#[cfg(not(feature = "preview-engine"))]
#[cfg(target_arch = "wasm32")]
{
self.page_count
}
}
}
#[cfg(feature = "preview-engine")]
#[cfg(not(target_arch = "wasm32"))]
fn shared_font_pool() -> &'static FontPool {
static POOL: OnceLock<FontPool> = OnceLock::new();
POOL.get_or_init(|| {
@@ -143,28 +316,39 @@ fn shared_font_pool() -> &'static FontPool {
})
}
#[cfg(feature = "preview-engine")]
#[cfg(not(target_arch = "wasm32"))]
fn shared_rasterizer() -> &'static SvgRasterizer {
static RASTER: OnceLock<SvgRasterizer> = OnceLock::new();
RASTER.get_or_init(|| SvgRasterizer::new(shared_font_pool()))
}
/// Convert an RGBA8 [`RgbaImageBuffer`] into a GPUI BGRA8 [`RenderImage`].
#[cfg(feature = "preview-engine")]
pub fn rgba_buffer_to_render_image(buf: &RgbaImageBuffer) -> Option<Arc<RenderImage>> {
if buf.width_px == 0 || buf.height_px == 0 {
/// Convert raw RGBA8 pixels into a GPUI BGRA8 [`RenderImage`].
pub fn rgba_pixels_to_render_image(
width_px: u32,
height_px: u32,
rgba: &[u8],
) -> Option<Arc<RenderImage>> {
if width_px == 0
|| height_px == 0
|| rgba.len() != (width_px as usize) * (height_px as usize) * 4
{
return None;
}
let mut bgra = buf.pixels.clone();
let mut bgra = rgba.to_vec();
for px in bgra.chunks_exact_mut(4) {
ui::swap_rgba_pa_to_bgra(px);
}
let img = image::RgbaImage::from_raw(buf.width_px, buf.height_px, bgra)?;
let img = image::RgbaImage::from_raw(width_px, height_px, bgra)?;
Some(Arc::new(RenderImage::new(vec![image::Frame::new(img)])))
}
#[cfg(feature = "preview-engine")]
fn hsla_to_css_hex(color: Hsla) -> String {
/// Convert an RGBA8 [`RgbaImageBuffer`] into a GPUI BGRA8 [`RenderImage`].
#[cfg(not(target_arch = "wasm32"))]
pub fn rgba_buffer_to_render_image(buf: &RgbaImageBuffer) -> Option<Arc<RenderImage>> {
rgba_pixels_to_render_image(buf.width_px, buf.height_px, &buf.pixels)
}
pub fn hsla_to_css_hex(color: Hsla) -> String {
let rgba: ui::Rgba = color.into();
let r = (rgba.r.clamp(0.0, 1.0) * 255.0).round() as u8;
let g = (rgba.g.clamp(0.0, 1.0) * 255.0).round() as u8;
@@ -172,29 +356,34 @@ fn hsla_to_css_hex(color: Hsla) -> String {
format!("#{r:02x}{g:02x}{b:02x}")
}
#[cfg(feature = "preview-engine")]
type MathCacheKey = (String, bool, u32, String);
#[cfg(not(target_arch = "wasm32"))]
type MathCacheKey = (String, bool, u32, String, u32);
/// Render and cache a LaTeX math expression through any registered [`MathPreviewProvider`]
/// or (when `preview-engine` is enabled) through pure-Rust RaTeX outlines.
/// or (on non-`wasm32` targets) through pure-Rust RaTeX outlines.
pub fn render_math_cached(
latex: &str,
display: bool,
font_size_pt: f32,
color: Hsla,
) -> Option<MathRenderSlot> {
dpr: f32,
) -> MathRenderResult {
let trimmed = latex.trim();
if trimmed.is_empty() {
return None;
return MathRenderResult::Pending;
}
let norm_dpr = if dpr.is_finite() && dpr > 0.0 {
dpr.clamp(1.0, 4.0)
} else {
2.0
};
if let Ok(guard) = math_provider_slot().read()
&& let Some(provider) = guard.as_ref()
&& let Some(slot) = provider.render_math(trimmed, display, font_size_pt, color)
{
return Some(slot);
return provider.render_math(trimmed, display, font_size_pt, color, norm_dpr);
}
#[cfg(feature = "preview-engine")]
#[cfg(not(target_arch = "wasm32"))]
{
let color_css = hsla_to_css_hex(color);
let key = (
@@ -202,12 +391,17 @@ pub fn render_math_cached(
display,
font_size_pt.to_bits(),
color_css.clone(),
norm_dpr.to_bits(),
);
static CACHE: OnceLock<RwLock<HashMap<MathCacheKey, Option<MathRenderSlot>>>> =
OnceLock::new();
let cache = CACHE.get_or_init(|| RwLock::new(HashMap::new()));
static CACHE: OnceLock<
RwLock<(
HashMap<MathCacheKey, MathRenderResult>,
VecDeque<MathCacheKey>,
)>,
> = OnceLock::new();
let cache = CACHE.get_or_init(|| RwLock::new((HashMap::new(), VecDeque::new())));
if let Ok(guard) = cache.read()
&& let Some(hit) = guard.get(&key)
&& let Some(hit) = guard.0.get(&key)
{
return hit.clone();
}
@@ -222,36 +416,44 @@ pub fn render_math_cached(
padding_pt: if display { 4.0 } else { 1.5 },
color_css,
};
let rendered = render_latex_rgba(
let rendered = match render_latex_rgba(
trimmed,
&options,
shared_font_pool(),
shared_rasterizer(),
2.0,
)
.ok()
.and_then(|out| {
let image = rgba_buffer_to_render_image(&out.image)?;
Some(MathRenderSlot {
image,
width_pt: out.width_pt as f32,
ascent_pt: out.ascent_pt as f32,
descent_pt: out.descent_pt as f32,
})
});
norm_dpr,
) {
Ok(out) => match rgba_buffer_to_render_image(&out.image) {
Some(image) => MathRenderResult::Ready(MathRenderSlot {
image,
width_pt: out.width_pt as f32,
ascent_pt: out.ascent_pt as f32,
descent_pt: out.descent_pt as f32,
}),
None => MathRenderResult::Error,
},
Err(_) => MathRenderResult::Error,
};
if let Ok(mut guard) = cache.write() {
if guard.len() > 256 {
guard.clear();
let (map, order) = &mut *guard;
if !map.contains_key(&key) {
while map.len() >= 1024 {
let Some(oldest) = order.pop_front() else {
break;
};
map.remove(&oldest);
}
order.push_back(key.clone());
}
guard.insert(key, rendered.clone());
map.insert(key, rendered.clone());
}
rendered
}
#[cfg(not(feature = "preview-engine"))]
#[cfg(target_arch = "wasm32")]
{
let _ = (display, font_size_pt, color);
None
let _ = (display, font_size_pt, color, norm_dpr);
MathRenderResult::Pending
}
}
@@ -261,15 +463,33 @@ pub fn render_pdf_page(
page_index: usize,
scale: f32,
) -> Option<PdfPreviewPage> {
#[cfg(feature = "preview-engine")]
if let Ok(guard) = pdf_provider_slot().read()
&& let Some(provider) = guard.as_ref()
{
let page_count = doc.renderer.page_count();
let total = doc.page_count();
if total == 0 {
return None;
}
let idx = page_index.min(total - 1);
#[cfg(target_arch = "wasm32")]
{
return provider.render_pdf_page(&doc.cache_key, &doc.bytes, idx, scale);
}
#[cfg(not(target_arch = "wasm32"))]
{
return provider.render_pdf_page(&doc.provider_key, &doc.provider_bytes, idx, scale);
}
}
#[cfg(not(target_arch = "wasm32"))]
{
let renderer = doc.renderer.as_ref()?;
let page_count = renderer.page_count();
if page_count == 0 {
return None;
}
let idx = page_index.min(page_count - 1);
let buf = doc
.renderer
let buf = renderer
.render_page(PdfRenderRequest::for_page(idx, scale))
.ok()?;
let image = rgba_buffer_to_render_image(&buf)?;
@@ -281,45 +501,71 @@ pub fn render_pdf_page(
height_pt: buf.logical_height,
})
}
#[cfg(not(feature = "preview-engine"))]
#[cfg(target_arch = "wasm32")]
{
if doc.page_count == 0 {
return None;
}
let idx = page_index.min(doc.page_count - 1);
if let Ok(guard) = pdf_provider_slot().read()
&& let Some(provider) = guard.as_ref()
{
return provider.render_pdf_page(&doc.bytes, idx, scale);
}
// Honest fallback: without `preview-engine` or a registered host `PdfPageProvider`,
// return `None` so `attachment_body` renders a clean file card rather than a fake box.
let _ = (doc, page_index, scale);
None
}
}
/// Construct an [`EmbeddedPdfDocument`] from raw PDF bytes.
pub fn parse_pdf_renderer(bytes: &[u8]) -> Option<EmbeddedPdfDocument> {
#[cfg(feature = "preview-engine")]
{
HayroPdfRenderer::from_bytes(bytes.to_vec())
.ok()
.map(|renderer| EmbeddedPdfDocument { renderer })
/// Parse an [`EmbeddedPdfDocument`] with explicit `Pending` vs `Invalid` outcome so async Web
/// Worker page-count lookups never permanently poison attachment preview caches.
pub fn parse_pdf_document(cache_key: &str, bytes: &[u8]) -> PdfParseResult {
if !bytes.starts_with(b"%PDF-") {
return PdfParseResult::Invalid;
}
#[cfg(not(feature = "preview-engine"))]
if let Ok(guard) = pdf_provider_slot().read()
&& let Some(provider) = guard.as_ref()
{
if !bytes.starts_with(b"%PDF-") {
return None;
return match provider.page_count(cache_key, bytes) {
PdfPageCount::Ready(0) | PdfPageCount::Invalid => PdfParseResult::Invalid,
PdfPageCount::Pending => PdfParseResult::Pending,
PdfPageCount::Ready(page_count) => PdfParseResult::Ready(EmbeddedPdfDocument {
#[cfg(not(target_arch = "wasm32"))]
renderer: None,
#[cfg(not(target_arch = "wasm32"))]
provider_key: cache_key.to_string(),
#[cfg(not(target_arch = "wasm32"))]
provider_bytes: bytes.to_vec(),
#[cfg(not(target_arch = "wasm32"))]
provider_page_count: page_count,
#[cfg(target_arch = "wasm32")]
cache_key: cache_key.to_string(),
#[cfg(target_arch = "wasm32")]
bytes: bytes.to_vec(),
#[cfg(target_arch = "wasm32")]
page_count,
}),
};
}
#[cfg(not(target_arch = "wasm32"))]
{
let _ = cache_key;
match HayroPdfRenderer::from_bytes(bytes.to_vec()) {
Ok(renderer) if renderer.page_count() > 0 => {
PdfParseResult::Ready(EmbeddedPdfDocument {
renderer: Some(renderer),
provider_key: String::new(),
provider_bytes: Vec::new(),
provider_page_count: 0,
})
}
_ => PdfParseResult::Invalid,
}
let page_count = pdf_provider_slot().read().ok().and_then(|guard| {
guard
.as_ref()
.and_then(|provider| provider.page_count(bytes))
})?;
(page_count > 0).then(|| EmbeddedPdfDocument {
bytes: bytes.to_vec(),
page_count,
})
}
#[cfg(target_arch = "wasm32")]
{
let _ = cache_key;
PdfParseResult::Pending
}
}
/// Construct an [`EmbeddedPdfDocument`] from raw PDF bytes when immediately ready.
pub fn parse_pdf_renderer(bytes: &[u8]) -> Option<EmbeddedPdfDocument> {
match parse_pdf_document("", bytes) {
PdfParseResult::Ready(doc) => Some(doc),
PdfParseResult::Pending | PdfParseResult::Invalid => None,
}
}
@@ -328,138 +574,143 @@ impl super::FlowPass<'_> {
use super::{
BlockBody, CARD_BLOCK_MARGIN, FlowKind, FlowRect, InlineAlign, InlineStyle, Prim,
};
use crate::theme::{FONT_SANS, TYPOGRAPHY};
use crate::theme::{FONT_CODE, FONT_SANS, TYPOGRAPHY};
let pad_x = 16.0;
let pad_y = 14.0;
// Match BlockSuite `latex/src/styles.ts:5-40`: `padding: 10px 24px`, `border-radius: 4px`,
// transparent at rest with zero permanent background or border (hover tint is drawn in
// `overlays/paint_page`).
let pad_x = 24.0;
let pad_y = 10.0;
let inner = (width - 2.0 * pad_x).max(1.0);
let empty = latex.trim().is_empty();
if !empty
&& let Some(math) = render_math_cached(latex, true, 18.0, self.palette.text_primary)
{
let natural_w = math.width_pt.max(1.0);
let natural_h = (math.ascent_pt + math.descent_pt).max(18.0);
let scale = if natural_w > inner {
inner / natural_w
} else {
1.0
};
let img_w = (natural_w * scale).round().max(1.0);
let img_h = (natural_h * scale).round().max(1.0);
let height = (img_h + 2.0 * pad_y).max(56.0);
let img_x = ((width - img_w) / 2.0).floor().max(pad_x);
let img_y = ((height - img_h) / 2.0).floor().max(pad_y);
return BlockBody {
kind: FlowKind::Latex,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: latex.to_string(),
prims: vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, height),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.border),
radius: 8.0,
dashed: false,
},
Prim::Image {
rect: FlowRect::new(img_x, img_y, img_w, img_h),
image: math.image,
},
],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
};
}
if !empty {
let (mw, mh, mut math_prims) = super::math_layout::layout_math_2d(
latex,
18.0,
self.palette.text_primary,
self.window,
if empty {
let style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
500.0,
self.palette.text_secondary,
);
let height = (mh + 2.0 * pad_y).max(56.0);
let offset_x = ((width - mw) / 2.0).floor().max(pad_x);
let offset_y = ((height - mh) / 2.0).floor().max(pad_y);
for prim in &mut math_prims {
match prim {
Prim::Text { x, y, .. } => {
*x += offset_x;
*y += offset_y;
}
Prim::Quad { rect, .. }
| Prim::Image { rect, .. }
| Prim::Icon { rect, .. } => {
*rect = rect.translated(offset_x, offset_y);
}
_ => {}
}
}
let mut prims = Vec::with_capacity(math_prims.len() + 1);
prims.push(Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, height),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.border),
radius: 8.0,
dashed: false,
});
prims.extend(math_prims);
let layout = self.plain_inline("Equation", style, inner, 20.0, InlineAlign::Center);
let height = (layout.height() + 2.0 * pad_y).max(40.0);
let text_y = ((height - layout.height()) / 2.0).floor().max(pad_y);
return BlockBody {
kind: FlowKind::Latex,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: latex.to_string(),
prims,
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
};
}
let style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
400.0,
self.palette.text_secondary,
);
let layout = self.plain_inline("Add an equation", style, inner, 22.0, InlineAlign::Center);
let height = (layout.height() + 2.0 * pad_y).max(52.0);
let text_y = ((height - layout.height()) / 2.0).floor().max(pad_y);
BlockBody {
kind: FlowKind::Latex,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: "Add an equation".to_string(),
prims: vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, height),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.border),
radius: 8.0,
dashed: false,
},
Prim::Text {
plain: "Equation".to_string(),
prims: vec![Prim::Text {
x: pad_x,
y: text_y,
layout,
clip: Some(FlowRect::new(pad_x, pad_y, inner, height - 2.0 * pad_y)),
},
],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
}],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
};
}
let dpr = self.window.scale_factor();
match render_math_cached(latex, true, 18.0, self.palette.text_primary, dpr) {
MathRenderResult::Ready(math) => {
let natural_w = math.width_pt.max(1.0);
let natural_h = (math.ascent_pt + math.descent_pt).max(18.0);
let scale = if natural_w > inner {
inner / natural_w
} else {
1.0
};
let img_w = (natural_w * scale).round().max(1.0);
let img_h = (natural_h * scale).round().max(1.0);
let height = (img_h + 2.0 * pad_y).max(40.0);
let img_x = ((width - img_w) / 2.0).floor().max(pad_x);
let img_y = ((height - img_h) / 2.0).floor().max(pad_y);
BlockBody {
kind: FlowKind::Latex,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: latex.to_string(),
prims: vec![Prim::Image {
rect: FlowRect::new(img_x, img_y, img_w, img_h),
image: math.image,
}],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
}
}
MathRenderResult::Error => {
let err_color = self
.input
.theme
.css_var("--affine-v2-text-highlight-fg-red")
.or_else(|| self.input.theme.css_var("--affine-error-color"))
.unwrap_or_else(|| ui::rgb(0xeb4335).into());
let style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, err_color);
let layout =
self.plain_inline("Error equation", style, inner, 20.0, InlineAlign::Center);
let height = (layout.height() + 2.0 * pad_y).max(40.0);
let text_y = ((height - layout.height()) / 2.0).floor().max(pad_y);
BlockBody {
kind: FlowKind::Latex,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: "Error equation".to_string(),
prims: vec![Prim::Text {
x: pad_x,
y: text_y,
layout,
clip: Some(FlowRect::new(pad_x, pad_y, inner, height - 2.0 * pad_y)),
}],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
}
}
MathRenderResult::Pending => {
// Async worker calculation in progress: keep clean unframed source text with
// zero box, zero border, and never "Error equation".
let style = InlineStyle::new(
FONT_CODE,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
let layout = self.plain_inline(latex, style, inner, 20.0, InlineAlign::Center);
let height = (layout.height() + 2.0 * pad_y).max(40.0);
let text_y = ((height - layout.height()) / 2.0).floor().max(pad_y);
BlockBody {
kind: FlowKind::Latex,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: latex.to_string(),
prims: vec![Prim::Text {
x: pad_x,
y: text_y,
layout,
clip: Some(FlowRect::new(pad_x, pad_y, inner, height - 2.0 * pad_y)),
}],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
}
}
}
}
@@ -532,96 +783,4 @@ impl super::FlowPass<'_> {
table_cells: Vec::new(),
}
}
pub(super) fn surface_ref_body(
&mut self,
reference: &str,
ref_flavour: &str,
caption: &str,
width: f32,
) -> super::BlockBody {
use super::{
BlockBody, CARD_BLOCK_MARGIN, FlowKind, FlowRect, InlineAlign, InlineStyle, Prim,
inline::truncate_to_width,
};
use crate::theme::{FONT_CODE, FONT_SANS, TYPOGRAPHY};
let card_h = 84.0;
let pad = 14.0;
let inner_w = (width - pad * 2.0 - 32.0).max(40.0);
let title = if caption.is_empty() {
reference
} else {
caption
};
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
self.palette.text_primary,
);
let sub_style = InlineStyle::new(
FONT_CODE,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
let title_str = truncate_to_width(self.window, title, &title_style, inner_w)
.text
.to_string();
let sub = format!("Surface ref {ref_flavour} {reference}");
let sub_str = truncate_to_width(self.window, &sub, &sub_style, inner_w)
.text
.to_string();
BlockBody {
kind: FlowKind::SurfaceRef,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: title.to_string(),
prims: vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, card_h),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.card_border),
radius: 8.0,
dashed: false,
},
Prim::Icon {
rect: FlowRect::new(pad, 16.0, 20.0, 20.0),
icon: crate::theme::IconPaint::named("EdgelessIcon"),
color: self.palette.icon,
},
Prim::Text {
x: pad + 28.0,
y: 14.0,
layout: self.plain_inline(
&title_str,
title_style,
inner_w,
22.0,
InlineAlign::Left,
),
clip: None,
},
Prim::Text {
x: pad + 28.0,
y: 42.0,
layout: self.plain_inline(
&sub_str,
sub_style,
inner_w,
18.0,
InlineAlign::Left,
),
clip: None,
},
],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
}
}
}
@@ -1,19 +1,19 @@
//! Layout and paint builders for the 7 rich Page block flavours:
//! `affine:callout`, `affine:table`, `affine:attachment` (card + embedded PDF preview),
//! `affine:embed-linked-doc`, `affine:embed-synced-doc`, and `affine:surface-ref`
//! (with `affine:latex` upgraded to RaTeX vector math in `blocks.rs`).
use blocksuite_playground_doc::read::TableData;
//! Layout and paint builders for `affine:callout` and `affine:attachment` (card + embedded PDF).
use crate::theme::{FONT_SANS, IconPaint, TYPOGRAPHY};
use super::{
BlockBody, CARD_BLOCK_MARGIN, FlowKind, FlowPass, FlowRect, InlineAlign, InlineStyle, Prim,
body::{AttachmentPdfControls, TableCellHit},
inline::truncate_to_width,
mirror_x_in_width,
body::AttachmentPdfControls, inline::truncate_to_width, mirror_x_in_width,
};
pub(super) const CALLOUT_MARGIN_Y: f32 = 8.0;
pub(super) const CALLOUT_PAD_X: f32 = 10.0;
pub(super) const CALLOUT_PAD_Y: f32 = 5.0;
pub(super) const CALLOUT_ICON_SLOT: f32 = 24.0;
pub(super) const CALLOUT_CONTENT_GAP: f32 = 10.0;
pub(super) const CALLOUT_MIN_HEIGHT: f32 = 34.0;
fn format_byte_size(bytes: i64) -> String {
let b = bytes.max(0) as f64;
if b < 1024.0 {
@@ -25,20 +25,33 @@ fn format_byte_size(bytes: i64) -> String {
}
}
fn semantic_callout_color(name: &str, theme: crate::theme::PlaygroundTheme) -> Option<ui::Hsla> {
let var = match name.trim().to_ascii_lowercase().as_str() {
"red" => "--affine-tag-red",
"orange" => "--affine-tag-orange",
"yellow" => "--affine-tag-yellow",
"green" => "--affine-tag-green",
"teal" => "--affine-tag-teal",
"blue" => "--affine-tag-blue",
"purple" => "--affine-tag-purple",
"magenta" | "pink" => "--affine-tag-pink",
"grey" | "gray" => "--affine-tag-gray",
_ => return theme.css_color(name),
/// Resolves BlockSuite callout background color names directly to the 9 semantic
/// `--affine-v2-block-callout-background-*` tokens (`callout-block.ts:212-238`).
///
/// Empty / `"default"` normalizes to `"grey"`; unknown names fall back to `None` (transparent).
fn semantic_callout_background(
raw: Option<&str>,
theme: crate::theme::PlaygroundTheme,
) -> Option<ui::Hsla> {
let key = raw.map(str::trim).unwrap_or("");
let normalized = if key.is_empty() || key.eq_ignore_ascii_case("default") {
"grey"
} else {
key
};
theme.css_var(var).or_else(|| theme.css_color(name))
let var = match normalized.to_ascii_lowercase().as_str() {
"blue" => "--affine-v2-block-callout-background-blue",
"green" => "--affine-v2-block-callout-background-green",
"grey" | "gray" => "--affine-v2-block-callout-background-grey",
"magenta" => "--affine-v2-block-callout-background-magenta",
"orange" => "--affine-v2-block-callout-background-orange",
"purple" => "--affine-v2-block-callout-background-purple",
"red" => "--affine-v2-block-callout-background-red",
"teal" => "--affine-v2-block-callout-background-teal",
"yellow" => "--affine-v2-block-callout-background-yellow",
_ => return None,
};
theme.css_var(var)
}
impl FlowPass<'_> {
@@ -50,34 +63,27 @@ impl FlowPass<'_> {
has_children: bool,
width: f32,
) -> BlockBody {
let pad_x = 14.0;
let pad_y = 12.0;
let icon_box = 24.0;
let resolved = background_color.and_then(|c| semantic_callout_color(c, self.input.theme));
let fill = resolved.unwrap_or_else(|| self.palette.background_secondary);
let tint = if fill.a > 0.35 {
fill.opacity(0.18)
} else {
fill
};
let border = resolved
.map(|c| c.opacity(0.32))
.unwrap_or(self.palette.border);
let fill = semantic_callout_background(background_color, self.input.theme);
let icon_text = if icon.trim().is_empty() {
"\u{1F4A1}"
} else {
icon.trim()
};
let icon_x = mirror_x_in_width(pad_x, icon_box, width, self.direction);
let icon_x = mirror_x_in_width(CALLOUT_PAD_X, CALLOUT_ICON_SLOT, width, self.direction);
let icon_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_base_px,
600.0,
(TYPOGRAPHY.font_base_px * 1.2).round(),
400.0,
self.palette.text_primary,
);
let icon_layout =
self.plain_inline(icon_text, icon_style, icon_box, 22.0, InlineAlign::Center);
let icon_layout = self.plain_inline(
icon_text,
icon_style,
CALLOUT_ICON_SLOT,
CALLOUT_ICON_SLOT,
InlineAlign::Center,
);
let mut glyph_count = 0usize;
let mut has_notdef = false;
for piece in &icon_layout.pieces {
@@ -93,7 +99,7 @@ impl FlowPass<'_> {
let icon_prim = if glyph_count > 0 && !has_notdef {
Prim::Text {
x: icon_x,
y: pad_y,
y: CALLOUT_PAD_Y,
layout: icon_layout,
clip: None,
}
@@ -108,23 +114,24 @@ impl FlowPass<'_> {
_ => "QuoteIcon",
};
Prim::Icon {
rect: FlowRect::new(icon_x + 2.0, pad_y + 1.0, 20.0, 20.0),
rect: FlowRect::new(icon_x + 2.0, CALLOUT_PAD_Y + 2.0, 20.0, 20.0),
icon: IconPaint::named(fallback_name),
color: resolved.unwrap_or(self.palette.icon),
color: self.palette.icon,
}
};
let title_trimmed = text.trim();
let text_w = (width - pad_x * 2.0 - icon_box - 8.0).max(1.0);
let content_offset_x = CALLOUT_PAD_X + CALLOUT_ICON_SLOT + CALLOUT_CONTENT_GAP;
let text_w = (width - content_offset_x - CALLOUT_PAD_X).max(1.0);
let title_x = match self.direction {
ui::Direction::Ltr => pad_x + icon_box + 8.0,
ui::Direction::Rtl => pad_x,
ui::Direction::Ltr => content_offset_x,
ui::Direction::Rtl => CALLOUT_PAD_X,
};
let mut prims = vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, pad_y * 2.0 + 22.0),
fill: Some(tint),
border: Some(border),
rect: FlowRect::new(0.0, 0.0, width, CALLOUT_MIN_HEIGHT),
fill,
border: None,
radius: 8.0,
dashed: false,
},
@@ -133,31 +140,33 @@ impl FlowPass<'_> {
let content_h = if !title_trimmed.is_empty() {
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
TYPOGRAPHY.font_base_px,
400.0,
self.palette.text_primary,
);
let align = match self.direction {
ui::Direction::Ltr => InlineAlign::Left,
ui::Direction::Rtl => InlineAlign::Right,
};
let title_layout = self.plain_inline(title_trimmed, title_style, text_w, 22.0, align);
let h = title_layout.height().max(22.0);
let title_layout = self.plain_inline(
title_trimmed,
title_style,
text_w,
TYPOGRAPHY.line_height_base_px,
align,
);
let h = title_layout.height().max(CALLOUT_ICON_SLOT);
prims.push(Prim::Text {
x: title_x,
y: pad_y,
y: CALLOUT_PAD_Y,
layout: title_layout,
clip: None,
});
h
} else {
22.0
};
let height = if has_children && title_trimmed.is_empty() {
pad_y + 22.0
} else {
pad_y * 2.0 + content_h
CALLOUT_ICON_SLOT
};
let height = (content_h + 2.0 * CALLOUT_PAD_Y).max(CALLOUT_MIN_HEIGHT);
if let Some(Prim::Quad { rect, .. }) = prims.first_mut() {
rect.h = height;
}
@@ -166,8 +175,8 @@ impl FlowPass<'_> {
kind: FlowKind::Callout,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: if has_children { 4.0 } else { CARD_BLOCK_MARGIN },
margin_top: CALLOUT_MARGIN_Y,
margin_bottom: if has_children { 0.0 } else { CALLOUT_MARGIN_Y },
plain: if title_trimmed.is_empty() {
icon_text.to_string()
} else {
@@ -182,142 +191,6 @@ impl FlowPass<'_> {
}
}
pub(super) fn table_body(&mut self, data: &TableData, width: f32) -> BlockBody {
let col_count = data.columns.len().max(1);
let row_count = data.rows.len().max(1);
// Logical inline-start to inline-end column ordering.
let ordered_cols: Vec<usize> = match self.direction {
ui::Direction::Ltr => (0..data.columns.len()).collect(),
ui::Direction::Rtl => (0..data.columns.len()).rev().collect(),
};
// Scale column weights proportionally so even 8+ column tables never overflow `width`.
let raw_weights: Vec<f32> = ordered_cols
.iter()
.map(|&idx| data.columns[idx].width.unwrap_or(160.0).max(20.0) as f32)
.collect();
let weight_sum: f32 = raw_weights.iter().sum::<f32>().max(1.0);
let col_widths: Vec<f32> = if raw_weights.is_empty() {
vec![width.max(1.0)]
} else {
let mut widths: Vec<f32> = raw_weights
.iter()
.map(|w| (width * (*w / weight_sum)).floor().max(1.0))
.collect();
let used: f32 = widths.iter().sum();
let rem = width - used;
if let Some(last) = widths.last_mut() {
*last = (*last + rem).max(1.0);
}
widths
};
let table_w = width.max(1.0);
let cell_pad_x = if (table_w / col_count as f32) < 52.0 {
4.0
} else {
10.0
};
let cell_pad_y = 8.0;
let line_h = 20.0;
let mut prims = Vec::new();
let mut table_cells = Vec::new();
let mut y = 0.0_f32;
let mut plain_rows = Vec::with_capacity(row_count);
let empty_rich = blocksuite_playground_doc::read::RichText::default();
let block_align = match self.direction {
ui::Direction::Ltr => blocksuite_playground_doc::read::TextAlign::Left,
ui::Direction::Rtl => blocksuite_playground_doc::read::TextAlign::Right,
};
for (r_idx, row) in data.rows.iter().enumerate() {
let is_header = r_idx == 0;
let spec = super::TextSpec {
font_size: TYPOGRAPHY.font_sm_px,
font_weight: if is_header { 600.0 } else { 400.0 },
line_height: line_h,
baseline: 15.0,
letter_spacing: 0.0,
margin_top: 0.0,
margin_bottom: 0.0,
};
let mut row_layouts = Vec::with_capacity(ordered_cols.len());
let mut row_h = line_h + 2.0 * cell_pad_y;
let mut row_texts = Vec::with_capacity(ordered_cols.len());
for (visual_col, &c_idx) in ordered_cols.iter().enumerate() {
let col = &data.columns[c_idx];
let col_w = col_widths[visual_col];
let inner_w = (col_w - 2.0 * cell_pad_x).max(1.0);
let rich = data
.cells
.get(&(row.row_id.clone(), col.column_id.clone()))
.map(|c| &c.text)
.unwrap_or(&empty_rich);
row_texts.push(rich.plain.clone());
let layout =
self.block_text(rich, &spec, self.palette.text_primary, inner_w, block_align);
row_h = row_h.max(layout.height() + 2.0 * cell_pad_y);
row_layouts.push((col.column_id.clone(), col_w, layout));
}
plain_rows.push(row_texts.join(" | "));
let mut cell_x = 0.0_f32;
for (col_id, col_w, layout) in row_layouts {
let cell_rect = FlowRect::new(cell_x, y, col_w, row_h);
let fill = if is_header {
Some(self.palette.background_secondary)
} else {
Some(self.palette.background)
};
prims.push(Prim::Quad {
rect: cell_rect,
fill,
border: Some(self.palette.border),
radius: 0.0,
dashed: false,
});
let text_x = cell_x + cell_pad_x;
let text_y = y + cell_pad_y;
prims.push(layout.prim(text_x, text_y));
table_cells.push(TableCellHit {
row_id: row.row_id.clone(),
column_id: col_id,
rect: cell_rect,
text_origin: (text_x, text_y),
text: layout,
});
cell_x += col_w;
}
y += row_h;
}
let height = y.max(36.0);
if data.rows.is_empty() {
prims.push(Prim::Quad {
rect: FlowRect::new(0.0, 0.0, table_w, height),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.border),
radius: 6.0,
dashed: false,
});
}
BlockBody {
kind: FlowKind::Table,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: plain_rows.join("\n"),
prims,
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells,
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn attachment_body(
&mut self,
@@ -421,7 +294,6 @@ impl FlowPass<'_> {
clip: None,
});
// Rendered PDF page image framed on crisp white paper.
let img_rect = FlowRect::new(img_x, header_h + pad, img_w, img_h);
prims.push(Prim::Quad {
rect: img_rect,
@@ -435,7 +307,6 @@ impl FlowPass<'_> {
image: pdf.image.clone(),
});
// Footer pagination bar: Prev | Page k / N | Next.
let footer_y = total_h - footer_h;
let btn_w = 64.0;
let btn_h = 28.0;
@@ -526,7 +397,6 @@ impl FlowPass<'_> {
return body;
}
// Compact horizontal file card mode.
let card_h = 64.0;
let pad = 12.0;
let inner_w = (width - pad * 2.0 - 36.0).max(40.0);
@@ -602,188 +472,4 @@ impl FlowPass<'_> {
self.push_caption(&mut body, caption);
body
}
pub(super) fn embed_linked_doc_body(
&mut self,
page_id: &str,
caption: &str,
width: f32,
) -> BlockBody {
let resolved_title = self
.input
.page_titles
.get(page_id)
.filter(|s| !s.is_empty())
.map(String::as_str)
.unwrap_or("Untitled");
let card_h = 72.0;
let pad = 14.0;
let inner_w = (width - pad * 2.0 - 32.0).max(40.0);
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
self.palette.text_primary,
);
let sub_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
let title_str = truncate_to_width(self.window, resolved_title, &title_style, inner_w)
.text
.to_string();
let sub = format!("Linked doc {page_id}");
let sub_str = truncate_to_width(self.window, &sub, &sub_style, inner_w)
.text
.to_string();
let mut body = BlockBody {
kind: FlowKind::EmbedLinkedDoc,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: resolved_title.to_string(),
prims: vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, card_h),
fill: Some(self.palette.background),
border: Some(self.palette.card_border),
radius: 8.0,
dashed: false,
},
Prim::Icon {
rect: FlowRect::new(pad, 16.0, 20.0, 20.0),
icon: IconPaint::named("LinkedPageIcon"),
color: self.palette.brand,
},
Prim::Text {
x: pad + 28.0,
y: 14.0,
layout: self.plain_inline(
&title_str,
title_style,
inner_w,
22.0,
InlineAlign::Left,
),
clip: None,
},
Prim::Text {
x: pad + 28.0,
y: 38.0,
layout: self.plain_inline(
&sub_str,
sub_style,
inner_w,
18.0,
InlineAlign::Left,
),
clip: None,
},
],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
};
self.push_caption(&mut body, caption);
body
}
pub(super) fn embed_synced_doc_body(
&mut self,
page_id: &str,
caption: &str,
width: f32,
) -> BlockBody {
let resolved_title = self
.input
.page_titles
.get(page_id)
.filter(|s| !s.is_empty())
.map(String::as_str)
.unwrap_or("Untitled");
let card_h = 88.0;
let pad = 14.0;
let inner_w = (width - pad * 2.0 - 32.0).max(40.0);
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
600.0,
self.palette.text_primary,
);
let body_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_xs_px,
400.0,
self.palette.text_secondary,
);
let title_str = truncate_to_width(self.window, resolved_title, &title_style, inner_w)
.text
.to_string();
let preview_line = format!("Synced document preview ({page_id})");
let mut body = BlockBody {
kind: FlowKind::EmbedSyncedDoc,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: resolved_title.to_string(),
prims: vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, card_h),
fill: Some(self.palette.background_secondary),
border: Some(self.palette.brand.opacity(0.45)),
radius: 8.0,
dashed: false,
},
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, 3.0, card_h),
fill: Some(self.palette.brand),
border: None,
radius: 1.5,
dashed: false,
},
Prim::Icon {
rect: FlowRect::new(pad, 14.0, 18.0, 18.0),
icon: IconPaint::named("LinkedPageIcon"),
color: self.palette.brand,
},
Prim::Text {
x: pad + 26.0,
y: 12.0,
layout: self.plain_inline(
&title_str,
title_style,
inner_w,
22.0,
InlineAlign::Left,
),
clip: None,
},
Prim::Text {
x: pad,
y: 44.0,
layout: self.plain_inline(
&preview_line,
body_style,
(width - 2.0 * pad).max(40.0),
20.0,
InlineAlign::Left,
),
clip: None,
},
],
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
};
self.push_caption(&mut body, caption);
body
}
}
@@ -0,0 +1,358 @@
//! Layout and cache fingerprinting for `affine:surface-ref` whiteboard preview cards.
use std::{collections::BTreeSet, rc::Rc};
use blocksuite_playground_doc::read::{BlockContent, BlockNode, PageSnapshot};
use crate::theme::{FONT_SANS, IconPaint, TYPOGRAPHY};
use super::{
BlockBody, CARD_BLOCK_MARGIN, FlowKind, FlowPass, FlowRect, InlineAlign, InlineStyle, Prim,
inline::truncate_to_width,
};
fn parse_xywh_rect(raw: &str) -> Option<(f32, f32, f32, f32)> {
let trimmed = raw.trim().trim_start_matches('[').trim_end_matches(']');
let mut parts = trimmed.split(',').map(|s| s.trim().parse::<f32>().ok());
Some((
parts.next()??,
parts.next()??,
parts.next()??,
parts.next()??,
))
}
fn find_frame_node<'a>(root: &'a BlockNode, reference: &str) -> Option<&'a BlockNode> {
root.walk()
.find(|node| node.id == reference && matches!(node.content, BlockContent::Frame { .. }))
}
fn frame_member_ids(frame_node: &BlockNode) -> BTreeSet<String> {
match frame_node.props.get("prop:childElementIds") {
Some(serde_json::Value::Object(map)) => map.keys().cloned().collect(),
_ => BTreeSet::new(),
}
}
fn xywh_intersects([x, y, w, h]: [f64; 4], (fx, fy, fw, fh): (f32, f32, f32, f32)) -> bool {
let (x, y, w, h) = (x as f32, y as f32, w as f32, h as f32);
!(x + w < fx || x > fx + fw || y + h < fy || y > fy + fh)
}
fn frame_relevant_surface_elements(
frame_node: &BlockNode,
frect: (f32, f32, f32, f32),
spatial_in_frame_ids: &BTreeSet<String>,
elements: &[blocksuite_playground_doc::read::SurfaceElement],
) -> Vec<blocksuite_playground_doc::read::SurfaceElement> {
use blocksuite_playground_doc::read::SurfaceElementKind;
let pt_in = |pt: Option<[f64; 2]>| {
pt.is_some_and(|[px, py]| {
let (x, y) = (px as f32, py as f32);
x >= frect.0 && x <= frect.0 + frect.2 && y >= frect.1 && y <= frect.1 + frect.3
})
};
let members = frame_member_ids(frame_node);
let mut inc = spatial_in_frame_ids.clone();
for el in elements.iter().filter(|el| !el.hidden) {
let hit = members.contains(&el.id)
|| match &el.kind {
SurfaceElementKind::Shape(s) => xywh_intersects(s.xywh, frect),
SurfaceElementKind::Text(t) => xywh_intersects(t.xywh, frect),
SurfaceElementKind::Brush(st) | SurfaceElementKind::Highlighter(st) => {
xywh_intersects(st.xywh, frect)
}
SurfaceElementKind::Connector(c) => {
pt_in(c.source.position) || pt_in(c.target.position)
}
_ => false,
};
if hit {
inc.insert(el.id.clone());
}
}
elements
.iter()
.filter(|el| {
!el.hidden
&& (inc.contains(&el.id)
|| match &el.kind {
SurfaceElementKind::Connector(c) => {
c.source.id.as_deref().is_some_and(|id| inc.contains(id))
|| c.target.id.as_deref().is_some_and(|id| inc.contains(id))
}
SurfaceElementKind::Group { children, .. } => {
children.iter().any(|id| inc.contains(id))
}
_ => false,
})
})
.cloned()
.collect()
}
/// Deterministic cache fingerprint of the referenced `Frame`, intersecting spatial blocks,
/// and frame-relevant whiteboard elements so `BlockFlow` invalidates a `SurfaceRef` card on edit.
pub(super) fn surface_ref_fingerprint(snapshot: &PageSnapshot, reference: &str) -> u64 {
use std::hash::{Hash, Hasher};
let Some((root, frame_node)) = snapshot
.root
.as_ref()
.and_then(|r| Some((r, find_frame_node(r, reference)?)))
else {
return 0;
};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
format!("{:?}", (&frame_node.content, frame_member_ids(frame_node))).hash(&mut hasher);
if let BlockContent::Frame { xywh, .. } = &frame_node.content
&& let Some(frect) = parse_xywh_rect(xywh)
&& frect.2 > 1.0
&& frect.3 > 1.0
{
let mut spatial_in_frame = BTreeSet::new();
for sp in crate::edgeless::spatial_blocks(root) {
if let BlockContent::Note {
xywh,
hidden: false,
..
}
| BlockContent::EdgelessText { xywh } = &sp.content
&& let Some((nx, ny, nw, nh)) = parse_xywh_rect(xywh)
&& xywh_intersects([nx.into(), ny.into(), nw.into(), nh.into()], frect)
{
spatial_in_frame.insert(sp.id.clone());
let rot = crate::edgeless::prop_f32(sp, "prop:rotate", 0.0);
format!("{:?}", (&sp.id, &sp.content, rot.to_bits())).hash(&mut hasher);
}
}
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
let rel =
frame_relevant_surface_elements(frame_node, frect, &spatial_in_frame, elements);
format!("{rel:?}").hash(&mut hasher);
}
}
}
hasher.finish()
}
impl FlowPass<'_> {
pub(super) fn surface_ref_body(
&mut self,
reference: &str,
_ref_flavour: &str,
caption: &str,
width: f32,
) -> BlockBody {
let frame_node = self
.input
.snapshot
.root
.as_ref()
.and_then(|root| find_frame_node(root, reference));
let frame_title = frame_node.and_then(|node| match &node.content {
BlockContent::Frame { title, .. } if !title.plain.trim().is_empty() => {
Some(title.plain.trim())
}
_ => None,
});
let frame_xywh = frame_node.and_then(|node| match &node.content {
BlockContent::Frame { xywh, .. } => parse_xywh_rect(xywh),
_ => None,
});
let clean_title = frame_title
.or_else(|| (!caption.trim().is_empty()).then_some(caption.trim()))
.unwrap_or("Canvas Frame");
let pad = 12.0;
let thumb_h = 120.0;
let header_h = 34.0;
let card_h = pad + thumb_h + header_h;
let thumb_rect = FlowRect::new(pad, pad, (width - 2.0 * pad).max(40.0), thumb_h);
let mut prims = vec![
Prim::Quad {
rect: FlowRect::new(0.0, 0.0, width, card_h),
fill: Some(self.palette.background),
border: Some(self.palette.card_border),
radius: 8.0,
dashed: false,
},
Prim::Quad {
rect: thumb_rect,
fill: Some(self.palette.background_secondary),
border: Some(self.palette.border),
radius: 6.0,
dashed: false,
},
];
// Project surface shapes/elements inside the referenced frame's world bounds into the
// miniature canvas thumbnail (reusing snapshot surface data, zero second renderer).
let mut drew_canvas_items = false;
if let (Some((fx, fy, fw, fh)), Some(root)) = (frame_xywh, &self.input.snapshot.root)
&& fw > 1.0
&& fh > 1.0
{
let inset = 8.0;
let avail_w = (thumb_rect.w - 2.0 * inset).max(1.0);
let avail_h = (thumb_rect.h - 2.0 * inset).max(1.0);
let scale = (avail_w / fw).min(avail_h / fh);
let draw_w = fw * scale;
let draw_h = fh * scale;
let ox = thumb_rect.x + (thumb_rect.w - draw_w) * 0.5;
let oy = thumb_rect.y + (thumb_rect.h - draw_h) * 0.5;
prims.push(Prim::Quad {
rect: FlowRect::new(ox, oy, draw_w, draw_h),
fill: Some(self.palette.background),
border: Some(self.palette.brand.opacity(0.45)),
radius: 4.0,
dashed: false,
});
drew_canvas_items = true;
let mut external_bounds = std::collections::BTreeMap::new();
let mut spatial_in_frame = BTreeSet::new();
for spatial in crate::edgeless::spatial_blocks(root) {
match &spatial.content {
BlockContent::Note {
xywh,
background,
hidden: false,
..
} => {
if let Some((nx, ny, nw, nh)) = parse_xywh_rect(xywh)
&& nw > 1.0
&& nh > 1.0
{
external_bounds.insert(
spatial.id.clone(),
crate::surface::WorldBounds {
xywh: [nx.into(), ny.into(), nw.into(), nh.into()],
rotate: 0.0,
},
);
if !(nx + nw < fx || nx > fx + fw || ny + nh < fy || ny > fy + fh) {
spatial_in_frame.insert(spatial.id.clone());
let note_fill = crate::edgeless::resolve_edgeless_color(
background,
self.input.theme,
)
.filter(|c| !c.is_transparent())
.unwrap_or(self.palette.background_secondary);
let sx = ox + (nx - fx).max(0.0) * scale;
let sy = oy + (ny - fy).max(0.0) * scale;
let sw = (nw * scale).min(ox + draw_w - sx).max(6.0);
let sh = (nh * scale).min(oy + draw_h - sy).max(6.0);
prims.push(Prim::Quad {
rect: FlowRect::new(sx, sy, sw, sh),
fill: Some(note_fill),
border: Some(self.palette.card_border),
radius: 3.0,
dashed: false,
});
}
}
}
BlockContent::Frame { xywh, .. } | BlockContent::EdgelessText { xywh } => {
if let Some((bx, by, bw, bh)) = parse_xywh_rect(xywh) {
let rot = crate::edgeless::prop_f32(spatial, "prop:rotate", 0.0);
external_bounds.insert(
spatial.id.clone(),
crate::surface::WorldBounds {
xywh: [bx.into(), by.into(), bw.into(), bh.into()],
rotate: rot.into(),
},
);
if matches!(spatial.content, BlockContent::EdgelessText { .. })
&& !(bx + bw < fx || bx > fx + fw || by + bh < fy || by > fy + fh)
{
spatial_in_frame.insert(spatial.id.clone());
}
}
}
_ => {}
}
}
if let Some(fnode) = frame_node {
for node in root.walk() {
if let BlockContent::Surface { elements, .. } = &node.content {
let rel = frame_relevant_surface_elements(
fnode,
(fx, fy, fw, fh),
&spatial_in_frame,
elements,
);
if !rel.is_empty() {
let surface_layout = crate::surface::layout_surface(
&rel,
&external_bounds,
self.input.theme,
self.window,
);
prims.push(Prim::Surface {
rect: FlowRect::new(ox, oy, draw_w, draw_h),
layout: Rc::new(surface_layout),
world_origin: (fx, fy),
scale,
});
}
}
}
}
}
if !drew_canvas_items {
let icon_size = 24.0;
prims.push(Prim::Icon {
rect: FlowRect::new(
thumb_rect.x + (thumb_rect.w - icon_size) * 0.5,
thumb_rect.y + (thumb_rect.h - icon_size) * 0.5,
icon_size,
icon_size,
),
icon: IconPaint::named("EdgelessIcon"),
color: self.palette.icon,
});
}
let footer_y = pad + thumb_h + 7.0;
let inner_w = (width - pad * 2.0 - 26.0).max(40.0);
let title_style = InlineStyle::new(
FONT_SANS,
TYPOGRAPHY.font_sm_px,
500.0,
self.palette.text_primary,
);
let title_str = truncate_to_width(self.window, clean_title, &title_style, inner_w)
.text
.to_string();
prims.push(Prim::Icon {
rect: FlowRect::new(pad, footer_y + 2.0, 16.0, 16.0),
icon: IconPaint::named("EdgelessIcon"),
color: self.palette.icon,
});
prims.push(Prim::Text {
x: pad + 24.0,
y: footer_y,
layout: self.plain_inline(&title_str, title_style, inner_w, 20.0, InlineAlign::Left),
clip: None,
});
BlockBody {
kind: FlowKind::SurfaceRef,
width,
height: card_h,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: clean_title.to_string(),
prims,
text: None,
prefix: None,
code_scroll: None,
pdf_controls: None,
table_cells: Vec::new(),
}
}
}
@@ -0,0 +1,185 @@
//! Layout and paint builder for `affine:table` blocks (BlockSuite `table/src/consts.ts` &
//! `table-cell.ts:535-543` parity).
//!
//! - Unset `column.width` auto-sizes per column in `[120.0, 240.0]` (`DefaultColumnWidth`..`ColumnMaxWidth`)
//! based on intrinsic cell text widths; explicit `column.width` uses `w.max(60.0)` (`ColumnMinWidth`).
//! - Total table width is `max-content` (sum of column widths), never stretched to fill the column.
//! - Zero automatic header row grey background or bold weight; cell background priority is
//! `column.background_color ?? row.background_color ?? default`.
//! - Tables wider than the available container width expose horizontal scrolling via `code_scroll`.
use blocksuite_playground_doc::read::{RichText, TableData, TextAlign as BlockAlign};
use crate::theme::TYPOGRAPHY;
use super::{
BlockBody, CARD_BLOCK_MARGIN, CodeScroll, FlowKind, FlowPass, FlowRect, Prim, TextSpec,
body::TableCellHit,
};
const DEFAULT_COLUMN_WIDTH: f32 = 120.0;
const COLUMN_MAX_WIDTH: f32 = 240.0;
const COLUMN_MIN_WIDTH: f32 = 60.0;
const TABLE_PAD_TOP: f32 = 10.0;
const TABLE_PAD_BOTTOM: f32 = 18.0;
const TABLE_PAD_LEFT: f32 = 10.0;
const CELL_PAD_X: f32 = 10.0;
const CELL_PAD_Y: f32 = 8.0;
const CELL_LINE_H: f32 = 20.0;
fn resolve_table_bg(raw: Option<&str>, theme: crate::theme::PlaygroundTheme) -> Option<ui::Hsla> {
let raw = raw?.trim();
if raw.is_empty() {
return None;
}
theme.css_color(raw).or_else(|| theme.css_var(raw))
}
impl FlowPass<'_> {
pub(super) fn table_body(&mut self, data: &TableData, width: f32) -> BlockBody {
let row_count = data.rows.len().max(1);
let ordered_cols: Vec<usize> = match self.direction {
ui::Direction::Ltr => (0..data.columns.len()).collect(),
ui::Direction::Rtl => (0..data.columns.len()).rev().collect(),
};
let spec = TextSpec {
font_size: TYPOGRAPHY.font_sm_px,
font_weight: 400.0,
line_height: CELL_LINE_H,
baseline: 15.0,
letter_spacing: 0.0,
margin_top: 0.0,
margin_bottom: 0.0,
};
let empty_rich = RichText::default();
let block_align = match self.direction {
ui::Direction::Ltr => BlockAlign::Left,
ui::Direction::Rtl => BlockAlign::Right,
};
// Compute `max-content` column widths: explicit `column.width` (>= 60px), or intrinsic
// cell width clamped to `[120.0, 240.0]`.
let col_widths: Vec<f32> = ordered_cols
.iter()
.map(|&c_idx| {
let col = &data.columns[c_idx];
if let Some(explicit) = col.width {
return (explicit as f32).max(COLUMN_MIN_WIDTH).round();
}
let mut widest = DEFAULT_COLUMN_WIDTH;
for row in &data.rows {
let Some(cell) = data.cells.get(&(row.row_id.clone(), col.column_id.clone()))
else {
continue;
};
if cell.text.plain.is_empty() {
continue;
}
let measured = self.block_text(
&cell.text,
&spec,
self.palette.text_primary,
COLUMN_MAX_WIDTH - 2.0 * CELL_PAD_X,
block_align,
);
let needed = measured.content_width().ceil() + 2.0 * CELL_PAD_X + 2.0;
widest = widest.max(needed);
if widest >= COLUMN_MAX_WIDTH {
return COLUMN_MAX_WIDTH;
}
}
widest.clamp(DEFAULT_COLUMN_WIDTH, COLUMN_MAX_WIDTH).ceil()
})
.collect();
let table_content_w: f32 = col_widths.iter().sum::<f32>().max(DEFAULT_COLUMN_WIDTH);
let mut prims = Vec::new();
let mut table_cells = Vec::new();
let mut y = TABLE_PAD_TOP;
let mut plain_rows = Vec::with_capacity(row_count);
for row in &data.rows {
let row_bg = resolve_table_bg(row.background_color.as_deref(), self.input.theme);
let mut row_layouts = Vec::with_capacity(ordered_cols.len());
let mut row_h = CELL_LINE_H + 2.0 * CELL_PAD_Y;
let mut row_texts = Vec::with_capacity(ordered_cols.len());
for (visual_col, &c_idx) in ordered_cols.iter().enumerate() {
let col = &data.columns[c_idx];
let col_w = col_widths[visual_col];
let col_bg = resolve_table_bg(col.background_color.as_deref(), self.input.theme);
let inner_w = (col_w - 2.0 * CELL_PAD_X).max(1.0);
let rich = data
.cells
.get(&(row.row_id.clone(), col.column_id.clone()))
.map(|c| &c.text)
.unwrap_or(&empty_rich);
row_texts.push(rich.plain.clone());
let layout =
self.block_text(rich, &spec, self.palette.text_primary, inner_w, block_align);
row_h = row_h.max(layout.height() + 2.0 * CELL_PAD_Y);
row_layouts.push((col.column_id.clone(), col_w, col_bg.or(row_bg), layout));
}
plain_rows.push(row_texts.join(" | "));
let mut cell_x = TABLE_PAD_LEFT;
for (col_id, col_w, cell_bg, layout) in row_layouts {
let cell_rect = FlowRect::new(cell_x, y, col_w, row_h);
prims.push(Prim::Quad {
rect: cell_rect,
fill: Some(cell_bg.unwrap_or(self.palette.background)),
border: Some(self.palette.border),
radius: 0.0,
dashed: false,
});
let text_x = cell_x + CELL_PAD_X;
let text_y = y + CELL_PAD_Y;
prims.push(layout.prim(text_x, text_y));
table_cells.push(TableCellHit {
row_id: row.row_id.clone(),
column_id: col_id,
rect: cell_rect,
text_origin: (text_x, text_y),
text: layout,
});
cell_x += col_w;
}
y += row_h;
}
if data.rows.is_empty() {
let empty_h = 36.0;
prims.push(Prim::Quad {
rect: FlowRect::new(TABLE_PAD_LEFT, TABLE_PAD_TOP, table_content_w, empty_h),
fill: Some(self.palette.background),
border: Some(self.palette.border),
radius: 0.0,
dashed: false,
});
y += empty_h;
}
let height = (y + TABLE_PAD_BOTTOM).max(TABLE_PAD_TOP + 36.0 + TABLE_PAD_BOTTOM);
let total_needed_w = TABLE_PAD_LEFT + table_content_w + TABLE_PAD_LEFT;
let max_scroll_x = (total_needed_w - width).max(0.0).ceil();
let code_scroll = (max_scroll_x > 0.0).then(|| CodeScroll {
area: FlowRect::new(0.0, 0.0, width, height),
max_x: max_scroll_x,
});
BlockBody {
kind: FlowKind::Table,
width,
height,
margin_top: CARD_BLOCK_MARGIN,
margin_bottom: CARD_BLOCK_MARGIN,
plain: plain_rows.join("\n"),
prims,
text: None,
prefix: None,
code_scroll,
pdf_controls: None,
table_cells,
}
}
}
+59
View File
@@ -65,6 +65,15 @@ pub struct EditorDocSummary {
pub updated_at_ms: i64,
}
/// Read-only preview metadata rendered inside `affine:embed-linked-doc` cards.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EditorDocPreview {
pub title: String,
pub snippet: String,
pub updated_at_ms: i64,
pub revision: u64,
}
/// Cooperative cancellation token for paginated linked-document queries.
#[derive(Clone, Debug, Default)]
pub struct DocQueryCancelToken {
@@ -203,6 +212,21 @@ pub trait WorkspaceDocDirectory {
/// Marks `id` as durably registered in the workspace root page list so that a subsequent
/// directory refresh where `id` is absent treats `id` as deleted rather than still-pending.
fn mark_doc_root_registered(&mut self, id: &EditorDocId);
/// Read-only summary (title, body snippet, updated timestamp, revision) for an embedded
/// linked-document card. Returns `None` when the host has no cached preview for `id`.
fn doc_preview(&self, _id: &EditorDocId) -> Option<EditorDocPreview> {
None
}
/// Read-only snapshot of a referenced document for `affine:embed-synced-doc` inline
/// preview rendering (zero CRDT writeback).
fn doc_snapshot(
&self,
_id: &EditorDocId,
) -> Option<Arc<blocksuite_playground_doc::read::PageSnapshot>> {
None
}
}
/// Pure-Rust contiguous substring matcher returning `(score, utf16_highlights)`.
@@ -303,6 +327,8 @@ struct IntentRecord {
#[derive(Clone, Debug)]
pub struct InMemoryDocDirectory {
docs: BTreeMap<EditorDocId, EditorDocSummary>,
previews: BTreeMap<EditorDocId, EditorDocPreview>,
snapshots: BTreeMap<EditorDocId, Arc<blocksuite_playground_doc::read::PageSnapshot>>,
intents: BTreeMap<String, IntentRecord>,
pending_root_docs: std::collections::BTreeSet<EditorDocId>,
id_prefix: String,
@@ -314,6 +340,8 @@ impl Default for InMemoryDocDirectory {
fn default() -> Self {
Self {
docs: BTreeMap::new(),
previews: BTreeMap::new(),
snapshots: BTreeMap::new(),
intents: BTreeMap::new(),
pending_root_docs: std::collections::BTreeSet::new(),
id_prefix: "doc:linked".to_string(),
@@ -350,6 +378,18 @@ impl InMemoryDocDirectory {
self.docs.insert(doc.id.clone(), doc);
}
pub fn upsert_preview(&mut self, id: EditorDocId, preview: EditorDocPreview) {
self.previews.insert(id, preview);
}
pub fn upsert_snapshot(
&mut self,
id: EditorDocId,
snapshot: Arc<blocksuite_playground_doc::read::PageSnapshot>,
) {
self.snapshots.insert(id, snapshot);
}
/// Synchronizes the directory's documents with `docs` while preserving `next_id`,
/// existing `intents` entries whose target documents remain present, and existing
/// `mode` / non-zero `updated_at_ms` metadata.
@@ -557,6 +597,25 @@ impl WorkspaceDocDirectory for InMemoryDocDirectory {
}
}
}
fn doc_preview(&self, id: &EditorDocId) -> Option<EditorDocPreview> {
if let Some(preview) = self.previews.get(id) {
return Some(preview.clone());
}
self.docs.get(id).map(|doc| EditorDocPreview {
title: doc.title.clone(),
snippet: String::new(),
updated_at_ms: doc.updated_at_ms,
revision: 0,
})
}
fn doc_snapshot(
&self,
id: &EditorDocId,
) -> Option<Arc<blocksuite_playground_doc::read::PageSnapshot>> {
self.snapshots.get(id).cloned()
}
}
#[cfg(test)]
@@ -37,7 +37,7 @@ pub(super) const ZOOM_BAR_RADIUS: f32 = 8.0;
pub(super) const ZOOM_BTN_RADIUS: f32 = 4.0;
pub(super) const ZOOM_BTN_HEIGHT: f32 = 28.0;
type NoteLayoutKey = (u64, u32, u32, PlaygroundTheme, u64, u64, bool);
type NoteLayoutKey = (u64, u32, u32, PlaygroundTheme, u64, u64, u64, bool);
pub(super) struct CachedNoteFlow {
pub(super) flow: BlockFlow,
@@ -401,11 +401,14 @@ pub struct EdgelessRenderInput<'a> {
pub snapshot: &'a PageSnapshot,
pub doc_rev: u64,
pub env_rev: u64,
pub preview_rev: u64,
pub preedit_nonce: u64,
pub theme: PlaygroundTheme,
pub palette: &'a Palette,
pub page_titles: &'a BTreeMap<String, String>,
pub images: &'a HashMap<String, ImageSlot>,
pub pdf_previews: Option<&'a HashMap<String, crate::block_flow::PdfPreviewPage>>,
pub doc_directory: Option<&'a dyn crate::directory::WorkspaceDocDirectory>,
pub viewport_width: f32,
pub viewport_height: f32,
pub direction: ui::Direction,
+10 -4
View File
@@ -137,6 +137,7 @@ pub fn prepare_edgeless_scene(
scale.to_bits(),
input.theme,
input.env_rev,
input.preview_rev,
input.preedit_nonce,
is_rtl,
);
@@ -149,7 +150,9 @@ pub fn prepare_edgeless_scene(
theme: input.theme,
page_titles: input.page_titles,
images: input.images,
pdf_previews: None,
pdf_previews: input.pdf_previews,
doc_directory: input.doc_directory,
equation_draft: None,
env_rev: input.env_rev,
direction: input.direction,
};
@@ -157,7 +160,7 @@ pub fn prepare_edgeless_scene(
state.note_flows.entry(child.id.clone()).or_insert_with(|| {
CachedNoteFlow {
flow: BlockFlow::new(),
key: (u64::MAX, 0, 0, input.theme, 0, 0, !is_rtl),
key: (u64::MAX, 0, 0, input.theme, 0, 0, 0, !is_rtl),
layout: Rc::new(FlowLayout {
blocks: Vec::new(),
width: inner_width,
@@ -230,6 +233,7 @@ pub fn prepare_edgeless_scene(
scale.to_bits(),
input.theme,
input.env_rev,
input.preview_rev,
input.preedit_nonce,
is_rtl,
);
@@ -242,7 +246,9 @@ pub fn prepare_edgeless_scene(
theme: input.theme,
page_titles: input.page_titles,
images: input.images,
pdf_previews: None,
pdf_previews: input.pdf_previews,
doc_directory: input.doc_directory,
equation_draft: None,
env_rev: input.env_rev,
direction: input.direction,
};
@@ -251,7 +257,7 @@ pub fn prepare_edgeless_scene(
.entry(child.id.clone())
.or_insert_with(|| CachedNoteFlow {
flow: BlockFlow::new(),
key: (u64::MAX, 0, 0, input.theme, 0, 0, !is_rtl),
key: (u64::MAX, 0, 0, input.theme, 0, 0, 0, !is_rtl),
layout: Rc::new(FlowLayout {
blocks: Vec::new(),
width: text_width,
+2 -2
View File
@@ -17,8 +17,8 @@ pub mod theme;
pub use directory::{
DirectoryError, DocQueryCancelToken, DocQueryPage, DocQueryRequest, EditorDocId, EditorDocMode,
EditorDocSummary, InMemoryDocDirectory, MatchedDocSummary, Utf16HighlightSpan,
WorkspaceDocDirectory, match_exact_substring_utf16,
EditorDocPreview, EditorDocSummary, InMemoryDocDirectory, MatchedDocSummary,
Utf16HighlightSpan, WorkspaceDocDirectory, match_exact_substring_utf16,
};
pub use fuse::{FuseHighlightMode, FuseMatch, fuse_search_utf16};
pub use theme::{PlaygroundTheme, register_bundled_fonts};
@@ -0,0 +1,353 @@
use ui::{
AnyElement, ClickEvent, Context, FontWeight, Hsla, MouseDownEvent, SharedString, TextRun,
Window, div, prelude::*, px,
};
use crate::{
block_flow::FlowRect,
theme::{FONT_SANS, Palette, TYPOGRAPHY},
};
use super::*;
const BOOKMARK_FIELD_WIDTH: f32 = 220.0;
const BOOKMARK_APPLY_WIDTH: f32 = 56.0;
const BOOKMARK_CANCEL_WIDTH: f32 = 56.0;
const BOOKMARK_PAD: f32 = 6.0;
const BOOKMARK_GAP: f32 = 4.0;
/// Floating URL input prompt opened by the mobile keyboard toolbar's `Bookmark` action.
/// Cancelling (`Escape`, `Cancel`, outside press, or empty/invalid URL) writes zero blocks.
#[derive(Clone, Debug, PartialEq)]
pub struct BookmarkPrompt {
pub block_id: String,
pub input: LinkBar,
pub(super) presence: Presence,
pub(super) rect: Option<FlowRect>,
}
impl Overlays {
/// Active bookmark URL prompt, if open (not closing).
pub fn bookmark_prompt(&self) -> Option<&BookmarkPrompt> {
self.bookmark.as_ref().filter(|p| !p.presence.closing)
}
/// Mutable access to the open bookmark URL prompt.
pub fn bookmark_prompt_mut(&mut self) -> Option<&mut BookmarkPrompt> {
self.bookmark.as_mut().filter(|p| !p.presence.closing)
}
/// Open and focus the bookmark URL prompt anchored to `block_id`.
pub fn open_bookmark_prompt(&mut self, block_id: String, now_ms: f64) {
self.close_slash(now_ms);
self.close_linked_doc(now_ms);
self.close_link_field();
self.close_equation_editor_at(now_ms);
let presence = match self.bookmark.take() {
Some(existing) => existing.presence.reopened(now_ms),
None => Presence::opening(now_ms),
};
self.bookmark = Some(BookmarkPrompt {
block_id,
input: LinkBar::new(String::new()),
presence,
rect: None,
});
}
/// Close the bookmark URL prompt immediately without inserting a block.
pub fn close_bookmark_prompt(&mut self) {
self.bookmark = None;
}
/// Dismiss the bookmark URL prompt with a fade-out transition (zero document writes).
pub fn close_bookmark_prompt_at(&mut self, now_ms: f64) -> bool {
match self.bookmark_prompt_mut() {
Some(prompt) => {
prompt.presence.close(now_ms);
true
}
None => false,
}
}
pub(super) fn apply_bookmark(&mut self, now_ms: f64, effects: &mut OverlayEffects) {
let Some(prompt) = self.bookmark_prompt_mut() else {
return;
};
let raw = prompt.input.clone().into_committed_text();
let url = if raw.trim().starts_with('/') {
String::new()
} else {
normalize_url(&raw)
};
if url.starts_with("http://") || url.starts_with("https://") {
effects.edits.push(DocEdit::Bookmark {
block_id: prompt.block_id.clone(),
url,
});
}
prompt.presence.close(now_ms);
effects.redraw = true;
}
pub(super) fn render_bookmark<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
palette: &Palette,
now_ms: f64,
window: &mut Window,
cx: &mut Context<V>,
) -> Option<AnyElement> {
let prompt = self.bookmark.as_mut()?;
prompt.rect = None;
let progress = prompt.presence.progress(now_ms);
if prompt.presence.closing && progress <= 0.0 {
return None;
}
let interactive = !prompt.presence.closing;
let progress = if interactive {
progress.max(0.01)
} else {
progress
};
let anchor_world = scene.layout.block(&prompt.block_id).map(|b| b.rect())?;
if !scene.page_viewport().intersects(&anchor_world) {
return None;
}
let anchor = scene.world_to_screen(&anchor_world);
let viewport = scene.popover_viewport();
let max_w = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(200.0);
let desired_w = BOOKMARK_FIELD_WIDTH
+ BOOKMARK_APPLY_WIDTH
+ BOOKMARK_CANCEL_WIDTH
+ 2.0 * BOOKMARK_GAP
+ 2.0 * BOOKMARK_PAD
+ 2.0;
let width = desired_w.min(max_w).floor();
let field_width = (width
- 2.0 * BOOKMARK_PAD
- 2.0
- 2.0 * BOOKMARK_GAP
- BOOKMARK_APPLY_WIDTH
- BOOKMARK_CANCEL_WIDTH)
.max(84.0);
let height = TOOLBAR_BUTTON + 2.0 * BOOKMARK_PAD + 2.0;
let placed = place_popover(
anchor,
(width, height),
viewport,
Placement::BelowStart,
POPOVER_GAP,
POPOVER_EDGE_MARGIN,
);
prompt.rect = Some(placed.rect);
prompt.input.bounds = Some(FlowRect::new(
placed.rect.x + BOOKMARK_PAD + 1.0,
placed.rect.y + BOOKMARK_PAD + 1.0,
field_width,
TOOLBAR_BUTTON,
));
let text = prompt.input.text();
let (selection, reversed) = prompt.input.shown_selection();
let marked = prompt.input.marked_range();
let shown = SharedString::from(text.clone());
let mut font = ui::font(FONT_SANS);
font.weight = FontWeight::NORMAL;
let line = window.text_system().shape_line(
shown.clone(),
px(TYPOGRAPHY.font_xs_px),
&[TextRun {
len: shown.len(),
font,
color: palette.text_primary,
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
let text_room = (field_width - 16.0).max(16.0);
let inner_height = TOOLBAR_BUTTON - 2.0;
let caret_height = 15.0;
let caret_top = ((inner_height - caret_height) * 0.5).round();
let x_at = |off: usize| f32::from(line.x_for_index(utf16_to_byte(&text, off)));
let text_width = f32::from(line.width());
let caret_x = x_at(if reversed {
selection.start
} else {
selection.end
});
let scroll = if text_width + 1.0 <= text_room {
0.0
} else {
(caret_x + 1.0 - text_room)
.clamp(0.0, text_width + 1.0 - text_room)
.round()
};
let mut inner = div()
.relative()
.flex_none()
.w(px(text_room))
.h(px(inner_height))
.overflow_hidden();
let strip = |from: usize, to: usize, top: f32, h: f32, color: Hsla| {
div()
.absolute()
.left(px((x_at(from) - scroll).round()))
.top(px(top))
.w(px((x_at(to) - x_at(from)).round().max(1.0)))
.h(px(h))
.bg(color)
};
if marked.is_none() && !selection.is_empty() {
inner = inner.child(strip(
selection.start,
selection.end,
caret_top,
caret_height,
palette.brand.opacity(0.22),
));
}
inner = inner.child(if text.is_empty() {
div()
.absolute()
.left(px(1.0))
.top(px(0.0))
.h(px(inner_height))
.flex()
.items_center()
.whitespace_nowrap()
.text_color(palette.placeholder)
.child("Paste or type a bookmark link")
} else {
div()
.absolute()
.left(px(-scroll))
.top(px(0.0))
.h(px(inner_height))
.flex()
.items_center()
.whitespace_nowrap()
.text_color(palette.text_primary)
.child(shown)
});
if let Some(m) = &marked {
inner = inner.child(strip(
m.start,
m.end,
caret_top + caret_height - 1.0,
1.0,
palette.text_secondary,
));
}
inner = inner.child(
div()
.absolute()
.left(px((caret_x - scroll).round()))
.top(px(caret_top))
.w(px(1.0))
.h(px(caret_height))
.bg(palette.text_primary),
);
let field = div()
.flex_none()
.w(px(field_width))
.h(px(TOOLBAR_BUTTON))
.px(px(8.0))
.rounded(px(4.0))
.bg(palette.background)
.border_1()
.border_color(palette.brand)
.flex()
.items_center()
.overflow_hidden()
.text_size(px(TYPOGRAPHY.font_xs_px))
.snapshot(
"overlay.bookmark_prompt.input",
Some("overlay.bookmark_prompt"),
)
.snapshot_focused(true)
.snapshot_text(text)
.child(inner);
let mut apply = div()
.id("bookmark_apply")
.flex_none()
.w(px(BOOKMARK_APPLY_WIDTH))
.h(px(TOOLBAR_BUTTON))
.rounded(px(4.0))
.bg(palette.brand)
.text_color(palette.on_accent)
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.snapshot(
"overlay.bookmark_prompt.apply",
Some("overlay.bookmark_prompt"),
)
.snapshot_text("Apply")
.child("Apply");
let hover_bg = palette.hover;
let mut cancel = div()
.id("bookmark_cancel")
.flex_none()
.w(px(BOOKMARK_CANCEL_WIDTH))
.h(px(TOOLBAR_BUTTON))
.rounded(px(4.0))
.text_color(palette.text_secondary)
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.snapshot(
"overlay.bookmark_prompt.cancel",
Some("overlay.bookmark_prompt"),
)
.snapshot_text("Cancel")
.child("Cancel");
if interactive {
apply = apply
.cursor_pointer()
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::BookmarkApply));
cancel = cancel
.cursor_pointer()
.hover(move |s| s.bg(hover_bg))
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::CloseBookmarkPrompt));
}
let mut root = place(placed.rect)
.id("bookmark-prompt")
.flex()
.items_center()
.gap(px(BOOKMARK_GAP))
.p(px(BOOKMARK_PAD))
.rounded(px(8.0))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
.opacity(progress)
.snapshot("overlay.bookmark_prompt", Some("root.canvas"))
.snapshot_focused(interactive)
.child(field)
.child(apply)
.child(cancel);
if interactive {
root = root
.occlude()
.on_mouse_down_out(emit(cx, |_: &MouseDownEvent| {
OverlayEvent::CloseBookmarkPrompt
}));
}
Some(root.into_any_element())
}
}
+571 -151
View File
@@ -1,17 +1,26 @@
use ui::{
AnyElement, ClickEvent, Context, FontWeight, Hsla, MouseDownEvent, SharedString, TextRun,
Window, div, prelude::*, px,
AnyElement, ClickEvent, Context, FontWeight, Hsla, MouseButton, MouseDownEvent, ShapedLine,
SharedString, TextRun, Window, canvas, div, point, prelude::*, px,
};
use crate::{
block_flow::FlowRect,
inline_input::{Utf16ImeBuffer, utf16_len},
theme::{FONT_CODE, FONT_SANS, Palette, TYPOGRAPHY},
};
use super::*;
const EQUATION_POPOVER_WIDTH: f32 = 304.0;
const EQUATION_DONE_WIDTH: f32 = 52.0;
const EQUATION_FIELD_WIDTH: f32 = 280.0;
const EQUATION_FIELD_PAD_X: f32 = 10.0;
const EQUATION_FIELD_PAD_Y: f32 = 4.0;
const EQUATION_LINE_HEIGHT: f32 = 20.0;
const EQUATION_FIELD_MAX_HEIGHT: f32 = 400.0;
const EQUATION_DONE_SIZE: f32 = 24.0;
const EQUATION_POPOVER_PAD: f32 = 8.0;
const EQUATION_GAP: f32 = 8.0;
const EQUATION_HINT_TOP: f32 = 6.0;
const EQUATION_HINT_HEIGHT: f32 = 16.0;
/// Target block or inline equation edited by [`EquationEditor`].
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -30,7 +39,61 @@ impl EquationTarget {
}
}
/// Lightweight single-line LaTeX equation editor popover anchored to a block or inline formula.
/// Cached visual soft-wrap line geometry for `Up`/`Down` navigation and pointer hit-testing.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct VisualLatexLine {
pub(super) start_u16: usize,
pub(super) end_u16: usize,
/// `true` when the next visual line starts at the same UTF-16 offset (soft wrap without `\n`).
pub(super) soft_wrapped_next: bool,
/// `(utf16_offset, x_px)` stops across this visual line, ordered by `utf16_offset`.
pub(super) stops: Vec<(usize, f32)>,
}
impl VisualLatexLine {
fn x_for_u16(&self, u16_off: usize) -> f32 {
let clamped = u16_off.clamp(self.start_u16, self.end_u16);
self.stops
.iter()
.find(|&&(off, _)| off >= clamped)
.or_else(|| self.stops.last())
.map_or(0.0, |&(_, x)| x)
}
fn nearest_u16_for_x(&self, target_x: f32) -> usize {
let max_off = if self.soft_wrapped_next && self.end_u16 > self.start_u16 {
self.end_u16 - 1
} else {
self.end_u16
};
let mut best_off = self.start_u16;
let mut best_dist = f32::INFINITY;
for &(off, x) in &self.stops {
if off > max_off {
break;
}
let dist = (x - target_x).abs();
if dist < best_dist {
best_dist = dist;
best_off = off;
}
}
best_off
}
}
impl EquationEditor {
/// Returns the `(start_u16, end_u16)` span of each laid-out visual row (including soft wraps).
pub fn visual_line_ranges(&self) -> Vec<(usize, usize)> {
self.visual_lines
.iter()
.map(|l| (l.start_u16, l.end_u16))
.collect()
}
}
/// Multiline auto-wrapping LaTeX equation editor popover anchored to a block or inline formula
/// (matching BlockSuite `latex-editor-menu.ts`).
#[derive(Clone, Debug, PartialEq)]
pub struct EquationEditor {
pub target: EquationTarget,
@@ -38,6 +101,263 @@ pub struct EquationEditor {
pub(super) initial_latex: String,
pub(super) presence: Presence,
pub(super) rect: Option<FlowRect>,
pub(super) scroll_y: f32,
pub(super) visual_lines: Vec<VisualLatexLine>,
}
impl EquationEditor {
/// Committed draft text (excluding any in-flight IME preedit so half-typed pinyin never
/// flashes `"Error equation"` in the live preview).
pub fn committed_draft(&self) -> &str {
self.input.url()
}
fn visual_line_index_for_u16(&self, u16_off: usize) -> usize {
for (idx, line) in self.visual_lines.iter().enumerate() {
let at_soft_wrap_end = line.soft_wrapped_next && u16_off == line.end_u16;
if u16_off >= line.start_u16 && u16_off <= line.end_u16 && !at_soft_wrap_end {
return idx;
}
}
self.visual_lines.len().saturating_sub(1)
}
/// Move the caret up or down one visual (soft-wrapped or `\n`-broken) line inside the
/// multiline equation buffer.
pub(super) fn move_vertical_line(&mut self, down: bool, shift: bool) {
let focus = self.input.input.focus();
if !self.visual_lines.is_empty() {
let cur_idx = self.visual_line_index_for_u16(focus);
let cur_x = self.visual_lines[cur_idx].x_for_u16(focus);
let next_off = if down {
if cur_idx + 1 < self.visual_lines.len() {
self.visual_lines[cur_idx + 1].nearest_u16_for_x(cur_x)
} else {
self.visual_lines.last().map_or(0, |l| l.end_u16)
}
} else if cur_idx > 0 {
self.visual_lines[cur_idx - 1].nearest_u16_for_x(cur_x)
} else {
0
};
self.input.input.move_caret(next_off, shift);
return;
}
// Pre-first-frame fallback: split on explicit `\n` lines.
let text = self.input.input.text();
let mut lines: Vec<(usize, usize)> = Vec::new();
let mut u16_pos = 0usize;
for part in text.split('\n') {
let len = utf16_len(part);
lines.push((u16_pos, u16_pos + len));
u16_pos += len + 1;
}
if lines.is_empty() {
return;
}
let cur_idx = lines
.iter()
.position(|&(s, e)| focus >= s && focus <= e)
.unwrap_or(lines.len() - 1);
let col = focus.saturating_sub(lines[cur_idx].0);
let next_off = if down {
if cur_idx + 1 < lines.len() {
let (ns, ne) = lines[cur_idx + 1];
(ns + col).min(ne)
} else {
lines.last().map_or(0, |&(_, e)| e)
}
} else if cur_idx > 0 {
let (ps, pe) = lines[cur_idx - 1];
(ps + col).min(pe)
} else {
0
};
self.input.input.move_caret(next_off, shift);
}
/// Map a window-space point `(screen_x, screen_y)` inside the multiline equation field
/// to its nearest UTF-16 character offset across wrapped visual rows.
pub fn hit_test_point(&self, screen_x: f32, screen_y: f32) -> Option<usize> {
let bounds = self.input.bounds?;
if !bounds.contains(screen_x, screen_y) || self.visual_lines.is_empty() {
return None;
}
let local_x = (screen_x - (bounds.x + EQUATION_FIELD_PAD_X + 1.0)).max(0.0);
let local_y = (screen_y - (bounds.y + EQUATION_FIELD_PAD_Y + 1.0) + self.scroll_y).max(0.0);
let row_idx = ((local_y / EQUATION_LINE_HEIGHT).floor() as usize)
.min(self.visual_lines.len().saturating_sub(1));
Some(self.visual_lines[row_idx].nearest_u16_for_x(local_x))
}
/// Place or extend the caret at `(screen_x, screen_y)` inside the multiline equation field.
pub(super) fn click_at(&mut self, screen_x: f32, screen_y: f32, shift: bool) -> bool {
let Some(bounds) = self.input.bounds else {
return false;
};
let local_x = (screen_x - (bounds.x + EQUATION_FIELD_PAD_X + 1.0)).max(0.0);
let local_y = (screen_y - (bounds.y + EQUATION_FIELD_PAD_Y + 1.0) + self.scroll_y).max(0.0);
if self.visual_lines.is_empty() {
return false;
}
if self.input.composing() {
self.input.unmark();
}
let row_idx = ((local_y / EQUATION_LINE_HEIGHT).floor() as usize)
.min(self.visual_lines.len().saturating_sub(1));
let off = self.visual_lines[row_idx].nearest_u16_for_x(local_x);
self.input.input.move_caret(off, shift);
true
}
}
struct WrappedLatexLine {
shaped: ShapedLine,
start_u16: usize,
end_u16: usize,
text: String,
}
fn shape_latex_segment(
segment: &str,
font: &ui::Font,
theme_mode: crate::theme::ThemeMode,
default_color: Hsla,
window: &Window,
) -> ShapedLine {
let shown = SharedString::from(segment.to_string());
let hl = crate::highlight::highlight_line(
crate::highlight::LanguageId::Latex,
segment,
crate::highlight::LineState::Normal,
);
let runs: Vec<TextRun> = if hl.spans.is_empty() {
vec![TextRun {
len: shown.len(),
font: font.clone(),
color: default_color,
background_color: None,
underline: None,
strikethrough: None,
}]
} else {
hl.spans
.iter()
.filter(|s| s.bytes.end > s.bytes.start)
.map(|s| TextRun {
len: s.bytes.end - s.bytes.start,
font: font.clone(),
color: crate::highlight::syntax_color(s.kind, theme_mode),
background_color: None,
underline: None,
strikethrough: None,
})
.collect()
};
window
.text_system()
.shape_line(shown, px(TYPOGRAPHY.font_xs_px), &runs, None)
}
fn wrap_latex_lines(
text: &str,
max_w: f32,
font: &ui::Font,
theme_mode: crate::theme::ThemeMode,
default_color: Hsla,
window: &Window,
) -> Vec<WrappedLatexLine> {
let mut out = Vec::new();
let mut base_u16 = 0usize;
for raw_line in text.split('\n') {
if raw_line.is_empty() {
let shaped = shape_latex_segment("", font, theme_mode, default_color, window);
out.push(WrappedLatexLine {
shaped,
start_u16: base_u16,
end_u16: base_u16,
text: String::new(),
});
base_u16 += 1;
continue;
}
let mut rem = raw_line;
let mut seg_u16 = base_u16;
while !rem.is_empty() {
let full = shape_latex_segment(rem, font, theme_mode, default_color, window);
if f32::from(full.width()) <= max_w {
let len_u16 = utf16_len(rem);
out.push(WrappedLatexLine {
shaped: full,
start_u16: seg_u16,
end_u16: seg_u16 + len_u16,
text: rem.to_string(),
});
break;
}
let mut best_byte = 0usize;
let mut last_space = 0usize;
for (byte, ch) in rem.char_indices() {
if byte == 0 {
continue;
}
let w = f32::from(full.x_for_index(byte));
if w > max_w {
break;
}
best_byte = byte;
if ch.is_whitespace() {
last_space = byte + ch.len_utf8();
}
}
let split_at = if last_space > 0 && last_space <= best_byte {
last_space
} else if best_byte > 0 {
best_byte
} else {
rem.chars().next().map_or(rem.len(), char::len_utf8)
};
let (head, tail) = rem.split_at(split_at);
let len_u16 = utf16_len(head);
let shaped = shape_latex_segment(head, font, theme_mode, default_color, window);
out.push(WrappedLatexLine {
shaped,
start_u16: seg_u16,
end_u16: seg_u16 + len_u16,
text: head.to_string(),
});
seg_u16 += len_u16;
rem = tail;
}
base_u16 += utf16_len(raw_line) + 1;
}
out
}
fn build_visual_lines(wrapped: &[WrappedLatexLine]) -> Vec<VisualLatexLine> {
wrapped
.iter()
.enumerate()
.map(|(idx, line)| {
let soft_wrapped_next =
idx + 1 < wrapped.len() && wrapped[idx + 1].start_u16 == line.end_u16;
let mut stops = Vec::with_capacity(line.text.chars().count() + 1);
let mut rel_u16 = 0usize;
for (byte_idx, ch) in line.text.char_indices() {
let x = f32::from(line.shaped.x_for_index(byte_idx));
stops.push((line.start_u16 + rel_u16, x));
rel_u16 += ch.len_utf16();
}
stops.push((line.end_u16, f32::from(line.shaped.width())));
VisualLatexLine {
start_u16: line.start_u16,
end_u16: line.end_u16,
soft_wrapped_next,
stops,
}
})
.collect()
}
impl Overlays {
@@ -55,11 +375,12 @@ impl Overlays {
.filter(|editor| !editor.presence.closing)
}
/// Open and focus the single-line equation editor for `target`.
/// Open and focus the multiline equation editor for `target`.
pub fn open_equation_editor(&mut self, target: EquationTarget, initial: String, now_ms: f64) {
self.close_slash(now_ms);
self.close_linked_doc(now_ms);
self.close_link_field();
self.close_bookmark_prompt_at(now_ms);
let presence = match self.equation.take() {
Some(existing) => existing.presence.reopened(now_ms),
None => Presence::opening(now_ms),
@@ -67,9 +388,14 @@ impl Overlays {
self.equation = Some(EquationEditor {
target,
initial_latex: initial.clone(),
input: LinkBar::new(initial),
input: LinkBar {
input: Utf16ImeBuffer::new(initial, true),
bounds: None,
},
presence,
rect: None,
scroll_y: 0.0,
visual_lines: Vec::new(),
});
}
@@ -136,12 +462,45 @@ impl Overlays {
}
let anchor = scene.world_to_screen(&anchor_world);
let viewport = scene.popover_viewport();
let width = EQUATION_POPOVER_WIDTH
.min(viewport.w - 2.0 * POPOVER_EDGE_MARGIN)
.max(120.0)
.floor();
let chrome = 2.0 * (TOOLBAR_PADDING + POPOVER_BORDER);
let height = TOOLBAR_BUTTON + chrome;
let max_popover_w = (viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(160.0);
let desired_popover_w = EQUATION_FIELD_WIDTH
+ EQUATION_GAP
+ EQUATION_DONE_SIZE
+ 2.0 * EQUATION_POPOVER_PAD
+ 1.0;
let width = desired_popover_w.min(max_popover_w).floor();
let field_width =
(width - 2.0 * EQUATION_POPOVER_PAD - 1.0 - EQUATION_GAP - EQUATION_DONE_SIZE)
.max(80.0);
let text_room = (field_width - 2.0 * (EQUATION_FIELD_PAD_X + 1.0)).max(24.0);
let text = editor.input.text();
let (selection, reversed) = editor.input.shown_selection();
let marked = editor.input.marked_range();
let mut font = ui::font(FONT_CODE);
font.weight = FontWeight::NORMAL;
let theme_mode = palette.theme.mode();
let wrapped = wrap_latex_lines(
&text,
text_room,
&font,
theme_mode,
palette.text_primary,
window,
);
editor.visual_lines = build_visual_lines(&wrapped);
let content_h = (wrapped.len().max(1) as f32) * EQUATION_LINE_HEIGHT;
let max_inner_h = EQUATION_FIELD_MAX_HEIGHT - 2.0 * (EQUATION_FIELD_PAD_Y + 1.0);
let inner_h = content_h.clamp(EQUATION_LINE_HEIGHT, max_inner_h);
let field_height = (inner_h + 2.0 * (EQUATION_FIELD_PAD_Y + 1.0)).round();
let height = (2.0 * EQUATION_POPOVER_PAD
+ 1.0
+ field_height
+ EQUATION_HINT_TOP
+ EQUATION_HINT_HEIGHT)
.round();
let placed = place_popover(
anchor,
(width, height),
@@ -151,112 +510,137 @@ impl Overlays {
POPOVER_EDGE_MARGIN,
);
editor.rect = Some(placed.rect);
let inner_width = (width - chrome).max(60.0);
let field_width = (inner_width - EQUATION_DONE_WIDTH - LINK_GAP).max(40.0);
let inset = POPOVER_BORDER + TOOLBAR_PADDING;
editor.input.bounds = Some(FlowRect::new(
placed.rect.x + inset,
placed.rect.y + inset,
placed.rect.x + EQUATION_POPOVER_PAD,
placed.rect.y + EQUATION_POPOVER_PAD,
field_width,
TOOLBAR_BUTTON,
field_height,
));
let radius = TOOLBAR_RADIUS - TOOLBAR_PADDING;
let text_room = (field_width - 2.0 * (8.0 + POPOVER_BORDER)).max(1.0);
let inner_height = TOOLBAR_BUTTON - 2.0 * POPOVER_BORDER;
let caret_height = 16.0;
let caret_top = (inner_height - caret_height) / 2.0;
let text = editor.input.text();
let (selection, reversed) = editor.input.shown_selection();
let marked = editor.input.marked_range();
let mut font = ui::font(FONT_CODE);
font.weight = FontWeight::NORMAL;
let shown = SharedString::from(text.clone());
let latex_hl = crate::highlight::highlight_line(
crate::highlight::LanguageId::Latex,
&text,
crate::highlight::LineState::Normal,
);
let theme_mode = palette.theme.mode();
let latex_runs: Vec<TextRun> = if latex_hl.spans.is_empty() {
vec![TextRun {
len: shown.len(),
font: font.clone(),
color: palette.text_primary,
background_color: None,
underline: None,
strikethrough: None,
}]
} else {
latex_hl
.spans
.iter()
.filter(|s| s.bytes.end > s.bytes.start)
.map(|s| TextRun {
len: s.bytes.end - s.bytes.start,
font: font.clone(),
color: crate::highlight::syntax_color(s.kind, theme_mode),
background_color: None,
underline: None,
strikethrough: None,
})
.collect()
};
let line = window.text_system().shape_line(
shown.clone(),
px(TYPOGRAPHY.font_xs_px),
&latex_runs,
None,
);
let x_at = |offset: usize| f32::from(line.x_for_index(utf16_to_byte(&text, offset)));
let text_width = f32::from(line.width());
let caret_x = x_at(if reversed {
let caret_u16 = if reversed {
selection.start
} else {
selection.end
});
let scroll = if text_width + 1.0 <= text_room {
0.0
} else {
(caret_x + 1.0 - text_room)
.clamp(0.0, text_width + 1.0 - text_room)
.round()
};
let (caret_line_idx, caret_x) = wrapped
.iter()
.enumerate()
.find(|(idx, line)| {
caret_u16 >= line.start_u16
&& (caret_u16 < line.end_u16
|| (caret_u16 == line.end_u16
&& (*idx + 1 == wrapped.len()
|| wrapped[*idx + 1].start_u16 > line.end_u16)))
})
.map(|(idx, line)| {
let rel = caret_u16.saturating_sub(line.start_u16);
let bx = f32::from(line.shaped.x_for_index(utf16_to_byte(&line.text, rel)));
(idx, bx)
})
.unwrap_or_else(|| {
let last_idx = wrapped.len().saturating_sub(1);
let bx = wrapped.last().map_or(0.0, |l| f32::from(l.shaped.width()));
(last_idx, bx)
});
let caret_top_y = caret_line_idx as f32 * EQUATION_LINE_HEIGHT;
let max_scroll_y = (content_h - inner_h).max(0.0);
if caret_top_y < editor.scroll_y {
editor.scroll_y = caret_top_y;
} else if caret_top_y + EQUATION_LINE_HEIGHT > editor.scroll_y + inner_h {
editor.scroll_y = caret_top_y + EQUATION_LINE_HEIGHT - inner_h;
}
editor.scroll_y = editor.scroll_y.clamp(0.0, max_scroll_y).round();
let scroll_y = editor.scroll_y;
let mut inner = div()
.relative()
.flex_none()
.w(px(text_room))
.h(px(inner_height))
.h(px(inner_h))
.overflow_hidden();
let make_strip = |x0: f32, x1: f32, top: f32, height: f32, color: Hsla| {
div()
.absolute()
.left(px((x0 - scroll).round()))
.top(px(top))
.w(px((x1 - x0).round().max(1.0)))
.h(px(height))
.bg(color)
};
let sel_span = (marked.is_none() && !selection.is_empty())
.then(|| (x_at(selection.start), x_at(selection.end)));
let marked_span = marked.as_ref().map(|m| (x_at(m.start), x_at(m.end)));
if let Some((x0, x1)) = sel_span {
inner = inner.child(make_strip(
x0,
x1,
caret_top,
caret_height,
palette.brand.opacity(0.22),
));
for (idx, line) in wrapped.iter().enumerate() {
let line_y = idx as f32 * EQUATION_LINE_HEIGHT - scroll_y;
if line_y + EQUATION_LINE_HEIGHT <= 0.0 || line_y >= inner_h {
continue;
}
if marked.is_none() && !selection.is_empty() {
let s0 = selection.start.max(line.start_u16);
let s1 = selection.end.min(line.end_u16);
if s1 > s0 {
let x0 = f32::from(
line.shaped
.x_for_index(utf16_to_byte(&line.text, s0 - line.start_u16)),
);
let x1 = f32::from(
line.shaped
.x_for_index(utf16_to_byte(&line.text, s1 - line.start_u16)),
);
inner = inner.child(
div()
.absolute()
.left(px(x0.round()))
.top(px(line_y + 2.0))
.w(px((x1 - x0).round().max(1.0)))
.h(px(16.0))
.bg(palette.brand.opacity(0.22)),
);
}
}
if let Some(m) = &marked {
let m0 = m.start.max(line.start_u16);
let m1 = m.end.min(line.end_u16);
if m1 > m0 {
let x0 = f32::from(
line.shaped
.x_for_index(utf16_to_byte(&line.text, m0 - line.start_u16)),
);
let x1 = f32::from(
line.shaped
.x_for_index(utf16_to_byte(&line.text, m1 - line.start_u16)),
);
inner = inner.child(
div()
.absolute()
.left(px(x0.round()))
.top(px(line_y + 17.0))
.w(px((x1 - x0).round().max(1.0)))
.h(px(1.0))
.bg(palette.text_secondary),
);
}
}
if !line.text.is_empty() {
let shaped = line.shaped.clone();
inner = inner.child(
ui::canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
let origin = ui::point(bounds.origin.x, bounds.origin.y + px(line_y));
let _ = shaped.paint(
origin,
px(EQUATION_LINE_HEIGHT),
ui::TextAlign::Left,
None,
window,
cx,
);
},
)
.absolute()
.size_full(),
);
}
}
if text.is_empty() {
inner = inner.child(
div()
.absolute()
.left(px(1.0))
.top(px(0.0))
.h(px(inner_height))
.h(px(EQUATION_LINE_HEIGHT))
.flex()
.items_center()
.whitespace_nowrap()
@@ -264,49 +648,42 @@ impl Overlays {
.text_color(palette.placeholder)
.child("Enter LaTeX equation"),
);
} else {
let line_h = px(inner_height);
}
let caret_y = caret_top_y - scroll_y + 2.0;
if caret_y + 16.0 > 0.0 && caret_y < inner_h {
inner = inner.child(
ui::canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
let origin = ui::point(bounds.origin.x - px(scroll), bounds.origin.y);
let _ = line.paint(origin, line_h, ui::TextAlign::Left, None, window, cx);
},
)
.absolute()
.size_full(),
div()
.absolute()
.left(px(caret_x.round()))
.top(px(caret_y))
.w(px(1.0))
.h(px(16.0))
.bg(palette.text_primary),
);
}
if let Some((x0, x1)) = marked_span {
inner = inner.child(make_strip(
x0,
x1,
caret_top + caret_height - 1.0,
1.0,
palette.text_secondary,
));
}
inner = inner.child(
div()
.absolute()
.left(px((caret_x - scroll).round()))
.top(px(caret_top))
.w(px(1.0))
.h(px(caret_height))
.bg(palette.text_primary),
);
let field = div()
let focus_border = palette
.theme
.css_var("--affine-blue-700")
.unwrap_or(palette.brand);
let overlay_bg = palette
.theme
.css_var("--affine-v2-layer-background-overlayPanel")
.unwrap_or(palette.panel);
let hover_bg = palette.hover;
let mut field = div()
.id("equation_input")
.flex_none()
.w(px(field_width))
.h(px(TOOLBAR_BUTTON))
.px(px(8.0))
.rounded(px(radius))
.h(px(field_height))
.px(px(EQUATION_FIELD_PAD_X))
.py(px(EQUATION_FIELD_PAD_Y))
.rounded(px(4.0))
.bg(palette.background)
.border_1()
.border_color(palette.brand)
.flex()
.items_center()
.border_color(focus_border)
.overflow_hidden()
.text_size(px(TYPOGRAPHY.font_xs_px))
.snapshot(
@@ -316,46 +693,89 @@ impl Overlays {
.snapshot_focused(true)
.snapshot_text(text)
.child(inner);
if interactive {
field = field.cursor(ui::CursorStyle::IBeam).on_mouse_down(
MouseButton::Left,
emit(cx, |ev: &MouseDownEvent| OverlayEvent::EquationClick {
x: f32::from(ev.position.x),
y: f32::from(ev.position.y),
shift: ev.modifiers.shift,
}),
);
}
let icon_color = palette.icon;
let done_glyph = canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let mut builder = ui::PathBuilder::stroke(px(1.75));
let x = f32::from(bounds.origin.x);
let y = f32::from(bounds.origin.y);
let w = f32::from(bounds.size.width);
let h = f32::from(bounds.size.height);
builder.move_to(point(px(x + w * 0.22), px(y + h * 0.52)));
builder.line_to(point(px(x + w * 0.42), px(y + h * 0.72)));
builder.line_to(point(px(x + w * 0.78), px(y + h * 0.30)));
if let Ok(path) = builder.build() {
window.paint_path(path, icon_color);
}
},
)
.w(px(20.0))
.h(px(20.0));
let mut done = div()
.id("equation_apply")
.flex_none()
.w(px(EQUATION_DONE_WIDTH))
.h(px(TOOLBAR_BUTTON))
.rounded(px(radius))
.bg(palette.brand)
.text_color(palette.on_accent)
.w(px(EQUATION_DONE_SIZE))
.h(px(EQUATION_DONE_SIZE))
.rounded(px(4.0))
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::MEDIUM)
.snapshot(
"overlay.equation_editor.done",
Some("overlay.equation_editor"),
)
.snapshot_text("Done")
.child("Done");
.child(done_glyph);
if interactive {
done = done
.cursor_pointer()
.hover(move |style| style.bg(hover_bg))
.on_click(emit(cx, |_: &ClickEvent| OverlayEvent::EquationApply));
}
let done_mt = (field_height - EQUATION_DONE_SIZE).max(0.0);
let top_row = div()
.flex()
.gap(px(EQUATION_GAP))
.child(field)
.child(done.mt(px(done_mt)));
let hint_row = div()
.pt(px(EQUATION_HINT_TOP))
.h(px(EQUATION_HINT_TOP + EQUATION_HINT_HEIGHT))
.text_size(px(TYPOGRAPHY.font_xs_px))
.line_height(px(EQUATION_HINT_HEIGHT))
.text_color(palette.placeholder)
.child("Shift Enter to line break");
let mut root = place(placed.rect)
.id("equation-editor")
.flex()
.items_center()
.gap(px(LINK_GAP))
.p(px(TOOLBAR_PADDING))
.rounded(px(TOOLBAR_RADIUS))
.bg(palette.panel)
.border_1()
.flex_col()
.p(px(EQUATION_POPOVER_PAD))
.rounded(px(8.0))
.bg(overlay_bg)
.border(px(0.5))
.border_color(palette.border)
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
.opacity(progress)
.snapshot("overlay.equation_editor", Some("root.canvas"))
.snapshot_focused(interactive)
.child(field)
.child(done);
.child(top_row)
.child(hint_row);
if interactive {
root = root
.occlude()
@@ -1,304 +0,0 @@
//! Mobile soft-keyboard accessory toolbar (`KeyboardToolbar`).
//!
//! Docked above the soft keyboard on mobile / narrow viewports with `>= 44x44 pt`
//! touch targets driving single-step undoable `PageDocSession` edits.
use ui::{AnyElement, ClickEvent, Context, FontWeight, SharedString, div, prelude::*, px};
use crate::{
block_flow::FlowRect,
theme::{Palette, TYPOGRAPHY},
};
use super::*;
/// Minimum touch target dimension for every mobile keyboard toolbar button (44x44 pt).
pub const KEYBOARD_TOOLBAR_BUTTON: f32 = 44.0;
/// Total height of the docked mobile keyboard toolbar strip.
pub const KEYBOARD_TOOLBAR_HEIGHT: f32 = 52.0;
/// Actions exposed by the mobile `KeyboardToolbar`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeyboardToolbarAction {
Undo,
Redo,
H1,
H2,
H3,
Todo,
Bullet,
Numbered,
Quote,
CodeBlock,
Bold,
Italic,
Underline,
InlineCode,
InlineMath,
Indent,
Outdent,
Mention,
Dismiss,
}
impl KeyboardToolbarAction {
pub const ALL: [Self; 19] = [
Self::Undo,
Self::Redo,
Self::Bold,
Self::Italic,
Self::Underline,
Self::InlineCode,
Self::InlineMath,
Self::H1,
Self::H2,
Self::H3,
Self::Todo,
Self::Bullet,
Self::Numbered,
Self::Quote,
Self::CodeBlock,
Self::Indent,
Self::Outdent,
Self::Mention,
Self::Dismiss,
];
pub fn id(self) -> &'static str {
match self {
Self::Undo => "undo",
Self::Redo => "redo",
Self::H1 => "h1",
Self::H2 => "h2",
Self::H3 => "h3",
Self::Todo => "todo",
Self::Bullet => "bullet",
Self::Numbered => "numbered",
Self::Quote => "quote",
Self::CodeBlock => "code_block",
Self::Bold => "bold",
Self::Italic => "italic",
Self::Underline => "underline",
Self::InlineCode => "inline_code",
Self::InlineMath => "inline_math",
Self::Indent => "indent",
Self::Outdent => "outdent",
Self::Mention => "mention",
Self::Dismiss => "dismiss",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Undo => "Undo",
Self::Redo => "Redo",
Self::H1 => "H1",
Self::H2 => "H2",
Self::H3 => "H3",
Self::Todo => "Todo",
Self::Bullet => "List",
Self::Numbered => "1.",
Self::Quote => "Quote",
Self::CodeBlock => "Code",
Self::Bold => "B",
Self::Italic => "I",
Self::Underline => "U",
Self::InlineCode => "</>",
Self::InlineMath => "fx",
Self::Indent => "->",
Self::Outdent => "<-",
Self::Mention => "@",
Self::Dismiss => "Dismiss",
}
}
/// Whether this action requires an active body `EditorSession` selection.
/// When a table cell is focused without a body selection, these buttons render disabled.
pub fn requires_body_selection(self) -> bool {
!matches!(self, Self::Undo | Self::Redo | Self::Dismiss)
}
pub fn icon(self) -> Option<&'static str> {
match self {
Self::Undo => Some("UndoIcon"),
Self::Redo => Some("RedoIcon"),
Self::Bold => Some("BoldIcon"),
Self::Italic => Some("ItalicIcon"),
Self::Underline => Some("UnderLineIcon"),
Self::InlineCode => Some("CodeIcon"),
Self::InlineMath => Some("TeXIcon"),
Self::H1 => Some("Heading1Icon"),
Self::H2 => Some("Heading2Icon"),
Self::H3 => Some("Heading3Icon"),
Self::Todo => Some("CheckBoxCheckLinearIcon"),
Self::Bullet => Some("BulletedListIcon"),
Self::Numbered => Some("NumberedListIcon"),
Self::Quote => Some("QuoteIcon"),
Self::CodeBlock => Some("CodeBlockIcon"),
Self::Indent => Some("RightTabIcon"),
Self::Outdent => Some("CollapseTabIcon"),
Self::Dismiss => Some("KeyboardIcon"),
_ => None,
}
}
}
impl Overlays {
/// Whether the mobile bottom `KeyboardToolbar` is currently visible.
pub fn keyboard_toolbar_visible(&self) -> bool {
self.keyboard_toolbar_visible
}
/// Show or hide the mobile bottom `KeyboardToolbar`.
pub fn set_keyboard_toolbar_visible(&mut self, visible: bool) {
self.keyboard_toolbar_visible = visible;
if !visible {
self.keyboard_toolbar_page = 0;
}
}
/// Whether body-selection-dependent mark/block buttons are disabled (e.g. table cell focus).
pub fn set_keyboard_toolbar_marks_disabled(&mut self, disabled: bool) {
self.keyboard_toolbar_marks_disabled = disabled;
}
/// Current page index of the paginated mobile `KeyboardToolbar`.
pub fn keyboard_toolbar_page(&self) -> usize {
self.keyboard_toolbar_page
}
/// Advance the mobile `KeyboardToolbar` to the next action page.
pub fn next_keyboard_toolbar_page(&mut self) {
self.keyboard_toolbar_page = self.keyboard_toolbar_page.wrapping_add(1);
}
pub(super) fn render_keyboard_toolbar<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
palette: &Palette,
cx: &mut Context<V>,
) -> Option<AnyElement> {
if !self.keyboard_toolbar_visible {
return None;
}
let width = scene.window.0.max(0.0).floor();
let height = KEYBOARD_TOOLBAR_HEIGHT;
let top = (scene.window.1 - height).max(TOPBAR_HEIGHT).floor();
let rect = FlowRect::new(0.0, top, width, height);
let pad_x = 4.0;
let gap = 2.0;
let btn = KEYBOARD_TOOLBAR_BUTTON;
let all_actions: Vec<KeyboardToolbarAction> = KeyboardToolbarAction::ALL
.into_iter()
.filter(|a| *a != KeyboardToolbarAction::Dismiss)
.collect();
// Check whether all 18 editing actions plus Dismiss fit on one row; otherwise
// reserve two rightmost 44x44pt slots for `More` (page toggle) + `Dismiss`.
let total_slots = ((width - pad_x * 2.0 + gap) / (btn + gap)).floor().max(1.0) as usize;
let needs_paging = total_slots < all_actions.len() + 1;
let left_slots = if needs_paging {
total_slots.saturating_sub(2).max(1)
} else {
all_actions.len()
};
let page_count = all_actions.len().div_ceil(left_slots).max(1);
let page = self.keyboard_toolbar_page % page_count;
let start = page * left_slots;
let end = (start + left_slots).min(all_actions.len());
let actions = &all_actions[start..end];
let hover = palette.hover;
let marks_disabled = self.keyboard_toolbar_marks_disabled;
let make_button = |action: KeyboardToolbarAction, cx: &mut Context<V>| {
let disabled = marks_disabled && action.requires_body_selection();
let mut button = div()
.id(SharedString::from(format!("kb-tool-{}", action.id())))
.flex_none()
.w(px(btn))
.h(px(btn))
.rounded(px(8.0))
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::SEMIBOLD)
.text_color(palette.text_primary)
.snapshot(
SharedString::from(format!("overlay.keyboard_toolbar.{}", action.id())),
Some("overlay.keyboard_toolbar"),
)
.snapshot_text(action.label());
if disabled {
button = button.opacity(0.35);
} else {
button = button
.cursor_pointer()
.hover(move |style| style.bg(hover))
.on_click(emit(cx, move |_: &ClickEvent| {
OverlayEvent::KeyboardToolbar(action)
}));
}
button = match action.icon() {
Some(name) => button.child(icon(name, 20.0, palette.icon)),
None => button.child(action.label()),
};
button
};
let mut left_strip = div()
.flex_1()
.min_w(px(0.0))
.h(px(btn))
.flex()
.items_center()
.gap(px(gap))
.overflow_hidden();
for &action in actions {
left_strip = left_strip.child(make_button(action, cx));
}
let dismiss = make_button(KeyboardToolbarAction::Dismiss, cx);
let mut bar = place(rect)
.id("keyboard-toolbar")
.px(px(pad_x))
.flex()
.items_center()
.gap(px(gap))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
.occlude()
.snapshot("overlay.keyboard_toolbar", Some("root.canvas"))
.child(left_strip);
if needs_paging {
let more = div()
.id("kb-tool-more")
.flex_none()
.w(px(btn))
.h(px(btn))
.rounded(px(8.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |style| style.bg(hover))
.on_click(emit(cx, |_: &ClickEvent| {
OverlayEvent::KeyboardToolbarNextPage
}))
.snapshot(
"overlay.keyboard_toolbar.more",
Some("overlay.keyboard_toolbar"),
)
.snapshot_text("More")
.child(icon("MoreHorizontalIcon", 20.0, palette.icon));
bar = bar.child(more);
}
bar = bar.child(dismiss);
Some(bar.into_any_element())
}
}
@@ -0,0 +1,647 @@
//! Declarative `0.27.5` `defaultKeyboardToolbarConfig` tables.
//!
//! Mirrors `blocksuite/affine/widgets/keyboard-toolbar/src/config.ts` verbatim:
//! top-level items, `moreToolPanel` 8-group layout, `textSubToolbarConfig`,
//! `textToolPanel` (`Turn into`), and `showWhen` schema gating.
use blocksuite_playground_doc::schema::{ListType, ParagraphType};
use super::{KeyboardToolbarAction, KeyboardToolbarDateKind, KeyboardToolbarPanel, SlashCommand};
/// Whether the current native Page editor registers and supports creating `flavour`.
/// Mirrors `std.store.schema.flavourSchemaMap.has(flavour)` in `0.27.5` `config.ts`.
pub const fn is_flavour_supported(flavour: &str) -> bool {
matches!(
flavour.as_bytes(),
b"affine:paragraph"
| b"affine:list"
| b"affine:code"
| b"affine:divider"
| b"affine:latex"
| b"affine:table"
| b"affine:callout"
| b"affine:embed-linked-doc"
| b"affine:image"
| b"affine:bookmark"
)
}
/// One action entry in the toolbar strip or a docked tool panel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ToolbarActionSpec {
pub id: &'static str,
pub name: &'static str,
/// Icon name in `ui-tokens` (empty string falls back to typographic glyph).
pub icon: &'static str,
pub action: KeyboardToolbarAction,
/// Required BlockSuite flavour for `showWhen` gating (`None` = always supported).
pub required_flavour: Option<&'static str>,
/// Explicit `showWhen: () => false` in `0.27.5` (e.g. `Attachment` at `config.ts:482,1104`).
pub always_hidden: bool,
}
impl ToolbarActionSpec {
pub const fn is_visible(&self) -> bool {
if self.always_hidden {
return false;
}
match self.required_flavour {
Some(flavour) => is_flavour_supported(flavour),
None => true,
}
}
pub const fn is_visible_for(&self, can_pick_images: bool) -> bool {
if !self.is_visible() {
return false;
}
if matches!(self.action, KeyboardToolbarAction::Image) {
return can_pick_images;
}
true
}
}
/// One entry of a toolbar strip (action button, sub-toolbar trigger, or panel trigger).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ToolbarItemSpec {
Action(ToolbarActionSpec),
SubToolbar {
id: &'static str,
name: &'static str,
icon: &'static str,
action: KeyboardToolbarAction,
},
ToolPanel {
id: &'static str,
name: &'static str,
icon: &'static str,
panel: KeyboardToolbarPanel,
action: KeyboardToolbarAction,
},
}
impl ToolbarItemSpec {
pub const fn id(&self) -> &'static str {
match self {
Self::Action(spec) => spec.id,
Self::SubToolbar { id, .. } | Self::ToolPanel { id, .. } => id,
}
}
pub const fn name(&self) -> &'static str {
match self {
Self::Action(spec) => spec.name,
Self::SubToolbar { name, .. } | Self::ToolPanel { name, .. } => name,
}
}
pub const fn icon(&self) -> &'static str {
match self {
Self::Action(spec) => spec.icon,
Self::SubToolbar { icon, .. } | Self::ToolPanel { icon, .. } => icon,
}
}
pub const fn action(&self) -> KeyboardToolbarAction {
match self {
Self::Action(spec) => spec.action,
Self::SubToolbar { action, .. } | Self::ToolPanel { action, .. } => *action,
}
}
pub const fn is_visible(&self) -> bool {
match self {
Self::Action(spec) => spec.is_visible(),
Self::SubToolbar { .. } | Self::ToolPanel { .. } => true,
}
}
pub const fn is_visible_for(&self, can_pick_images: bool) -> bool {
match self {
Self::Action(spec) => spec.is_visible_for(can_pick_images),
Self::SubToolbar { .. } | Self::ToolPanel { .. } => true,
}
}
}
/// One named group inside a docked tool panel (`moreToolPanel` / `textToolPanel`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ToolPanelGroupSpec {
pub id: &'static str,
pub name: &'static str,
pub items: &'static [ToolbarActionSpec],
}
const fn act(
id: &'static str,
name: &'static str,
icon: &'static str,
action: KeyboardToolbarAction,
required_flavour: Option<&'static str>,
) -> ToolbarActionSpec {
ToolbarActionSpec {
id,
name,
icon,
action,
required_flavour,
always_hidden: false,
}
}
const fn hidden_act(
id: &'static str,
name: &'static str,
icon: &'static str,
action: KeyboardToolbarAction,
required_flavour: Option<&'static str>,
) -> ToolbarActionSpec {
ToolbarActionSpec {
id,
name,
icon,
action,
required_flavour,
always_hidden: true,
}
}
/// `textToolActionItems` (`config.ts:190-330`), reusing `SlashCommand` for block conversions.
pub const TURN_INTO_PANEL_ITEMS: [ToolbarActionSpec; 14] = [
act(
"text",
"Text",
"TextIcon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::Text)),
Some("affine:paragraph"),
),
act(
"h1",
"Heading 1",
"Heading1Icon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::H1)),
Some("affine:paragraph"),
),
act(
"h2",
"Heading 2",
"Heading2Icon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::H2)),
Some("affine:paragraph"),
),
act(
"h3",
"Heading 3",
"Heading3Icon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::H3)),
Some("affine:paragraph"),
),
act(
"h4",
"Heading 4",
"Heading4Icon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::H4)),
Some("affine:paragraph"),
),
act(
"h5",
"Heading 5",
"Heading5Icon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::H5)),
Some("affine:paragraph"),
),
act(
"h6",
"Heading 6",
"Heading6Icon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::H6)),
Some("affine:paragraph"),
),
act(
"code_block",
"Code Block",
"CodeBlockIcon",
KeyboardToolbarAction::Slash(SlashCommand::Code),
Some("affine:code"),
),
act(
"equation_block",
"Equation",
"TeXIcon",
KeyboardToolbarAction::EquationBlock,
Some("affine:latex"),
),
act(
"quote",
"Quote",
"QuoteIcon",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(ParagraphType::Quote)),
Some("affine:paragraph"),
),
act(
"divider",
"Divider",
"DividerIcon",
KeyboardToolbarAction::Slash(SlashCommand::Divider),
Some("affine:divider"),
),
act(
"inline_math",
"Inline Eq",
"TeXIcon",
KeyboardToolbarAction::InlineMath,
Some("affine:paragraph"),
),
act(
"table",
"Table",
"SquareIcon",
KeyboardToolbarAction::Table,
Some("affine:table"),
),
act(
"callout",
"Callout",
"InformationIcon",
KeyboardToolbarAction::Callout,
Some("affine:callout"),
),
];
/// `listToolActionItems` (`config.ts:332-372`, extended with `Toggle List` from `SLASH_ITEMS`).
pub const LIST_TOOL_ACTION_ITEMS: [ToolbarActionSpec; 4] = [
act(
"bullet",
"Bulleted",
"BulletedListIcon",
KeyboardToolbarAction::Slash(SlashCommand::List(ListType::Bulleted)),
Some("affine:list"),
),
act(
"numbered",
"Numbered",
"NumberedListIcon",
KeyboardToolbarAction::Slash(SlashCommand::List(ListType::Numbered)),
Some("affine:list"),
),
act(
"todo",
"To-do",
"CheckBoxCheckLinearIcon",
KeyboardToolbarAction::Slash(SlashCommand::List(ListType::Todo)),
Some("affine:list"),
),
act(
"toggle",
"Toggle",
"ToggleRightIcon",
KeyboardToolbarAction::Slash(SlashCommand::List(ListType::Toggle)),
Some("affine:list"),
),
];
const PAGE_TOOL_ITEMS: [ToolbarActionSpec; 2] = [
act(
"new_page",
"New Page",
"PageIcon",
KeyboardToolbarAction::Slash(SlashCommand::NewDoc),
Some("affine:embed-linked-doc"),
),
act(
"linked_page",
"Linked Page",
"LinkedPageIcon",
KeyboardToolbarAction::Slash(SlashCommand::LinkedDoc),
Some("affine:embed-linked-doc"),
),
];
const CONTENT_MEDIA_ITEMS: [ToolbarActionSpec; 4] = [
act(
"image",
"Image",
"",
KeyboardToolbarAction::Image,
Some("affine:image"),
),
act(
"bookmark",
"Link",
"LinkIcon",
KeyboardToolbarAction::Bookmark,
Some("affine:bookmark"),
),
hidden_act(
"attachment",
"Attachment",
"",
KeyboardToolbarAction::Attachment,
Some("affine:attachment"),
),
act(
"equation_block",
"Equation",
"TeXIcon",
KeyboardToolbarAction::EquationBlock,
Some("affine:latex"),
),
];
const EMBED_TOOL_ITEMS: [ToolbarActionSpec; 6] = [
act(
"embed_iframe",
"Embed",
"LinkIcon",
KeyboardToolbarAction::EmbedIframe,
Some("affine:embed-iframe"),
),
act(
"embed_youtube",
"Youtube",
"LinkIcon",
KeyboardToolbarAction::EmbedYoutube,
Some("affine:embed-youtube"),
),
act(
"embed_github",
"Github",
"LinkIcon",
KeyboardToolbarAction::EmbedGithub,
Some("affine:embed-github"),
),
act(
"embed_figma",
"Figma",
"LinkIcon",
KeyboardToolbarAction::EmbedFigma,
Some("affine:embed-figma"),
),
act(
"embed_loom",
"Loom",
"LinkIcon",
KeyboardToolbarAction::EmbedLoom,
Some("affine:embed-loom"),
),
act(
"equation_block",
"Equation",
"TeXIcon",
KeyboardToolbarAction::EquationBlock,
Some("affine:latex"),
),
];
const DOC_GROUP_FRAME_ITEMS: [ToolbarActionSpec; 0] = [];
const DATE_TOOL_ITEMS: [ToolbarActionSpec; 4] = [
act(
"date_today",
"Today",
"",
KeyboardToolbarAction::Date(KeyboardToolbarDateKind::Today),
None,
),
act(
"date_tomorrow",
"Tomorrow",
"",
KeyboardToolbarAction::Date(KeyboardToolbarDateKind::Tomorrow),
None,
),
act(
"date_yesterday",
"Yesterday",
"",
KeyboardToolbarAction::Date(KeyboardToolbarDateKind::Yesterday),
None,
),
act(
"date_now",
"Now",
"",
KeyboardToolbarAction::Date(KeyboardToolbarDateKind::Now),
None,
),
];
const DATABASE_TOOL_ITEMS: [ToolbarActionSpec; 2] = [
act(
"database_table",
"Table view",
"SquareIcon",
KeyboardToolbarAction::DatabaseTableView,
Some("affine:database"),
),
act(
"database_kanban",
"Kanban view",
"SquareIcon",
KeyboardToolbarAction::DatabaseKanbanView,
Some("affine:database"),
),
];
/// All 8 groups of `moreToolPanel` in exact `config.ts:862-871` order.
pub const MORE_TOOL_PANEL_GROUPS: [ToolPanelGroupSpec; 8] = [
ToolPanelGroupSpec {
id: "basic",
name: "Basic",
items: &TURN_INTO_PANEL_ITEMS,
},
ToolPanelGroupSpec {
id: "list",
name: "List",
items: &LIST_TOOL_ACTION_ITEMS,
},
ToolPanelGroupSpec {
id: "page",
name: "Page",
items: &PAGE_TOOL_ITEMS,
},
ToolPanelGroupSpec {
id: "content_media",
name: "Content & Media",
items: &CONTENT_MEDIA_ITEMS,
},
ToolPanelGroupSpec {
id: "embeds",
name: "Embeds",
items: &EMBED_TOOL_ITEMS,
},
ToolPanelGroupSpec {
id: "doc_group_frame",
name: "Document Group&Frame",
items: &DOC_GROUP_FRAME_ITEMS,
},
ToolPanelGroupSpec {
id: "date",
name: "Date",
items: &DATE_TOOL_ITEMS,
},
ToolPanelGroupSpec {
id: "database",
name: "Database",
items: &DATABASE_TOOL_ITEMS,
},
];
/// `textSubToolbarConfig.items` (`config.ts:1056-1071`).
pub const TEXT_SUB_TOOLBAR_ITEMS: [ToolbarItemSpec; 9] = [
ToolbarItemSpec::ToolPanel {
id: "turn_into",
name: "Turn into",
icon: "TextIcon",
panel: KeyboardToolbarPanel::TurnInto,
action: KeyboardToolbarAction::ToggleTurnIntoPanel,
},
ToolbarItemSpec::Action(act(
"bold",
"Bold",
"BoldIcon",
KeyboardToolbarAction::Bold,
None,
)),
ToolbarItemSpec::Action(act(
"italic",
"Italic",
"ItalicIcon",
KeyboardToolbarAction::Italic,
None,
)),
ToolbarItemSpec::Action(act(
"underline",
"Underline",
"UnderLineIcon",
KeyboardToolbarAction::Underline,
None,
)),
ToolbarItemSpec::Action(act(
"strike",
"Strike",
"StrikeThroughIcon",
KeyboardToolbarAction::Strike,
None,
)),
ToolbarItemSpec::Action(act(
"inline_code",
"Code",
"CodeIcon",
KeyboardToolbarAction::InlineCode,
None,
)),
ToolbarItemSpec::Action(act(
"link",
"Link",
"LinkIcon",
KeyboardToolbarAction::Link,
None,
)),
ToolbarItemSpec::Action(act(
"inline_math",
"InlineTex",
"TeXIcon",
KeyboardToolbarAction::InlineMath,
None,
)),
ToolbarItemSpec::ToolPanel {
id: "highlight",
name: "Highlight",
icon: "",
panel: KeyboardToolbarPanel::Highlight,
action: KeyboardToolbarAction::ToggleHighlightPanel,
},
];
/// `defaultKeyboardToolbarConfig.items` (`config.ts:1082-1225`).
pub const DEFAULT_KEYBOARD_TOOLBAR_ITEMS: [ToolbarItemSpec; 16] = [
ToolbarItemSpec::ToolPanel {
id: "more_panel",
name: "More",
icon: "PlusIcon",
panel: KeyboardToolbarPanel::More,
action: KeyboardToolbarAction::ToggleMorePanel,
},
ToolbarItemSpec::SubToolbar {
id: "text_style",
name: "Aa",
icon: "",
action: KeyboardToolbarAction::OpenTextSubToolbar,
},
ToolbarItemSpec::Action(act(
"image",
"Image",
"",
KeyboardToolbarAction::Image,
Some("affine:image"),
)),
ToolbarItemSpec::Action(hidden_act(
"attachment",
"Attachment",
"",
KeyboardToolbarAction::Attachment,
Some("affine:attachment"),
)),
ToolbarItemSpec::Action(act(
"undo",
"Undo",
"UndoIcon",
KeyboardToolbarAction::Undo,
None,
)),
ToolbarItemSpec::Action(act(
"redo",
"Redo",
"RedoIcon",
KeyboardToolbarAction::Redo,
None,
)),
ToolbarItemSpec::Action(act(
"indent",
"Indent",
"RightTabIcon",
KeyboardToolbarAction::Indent,
None,
)),
ToolbarItemSpec::Action(LIST_TOOL_ACTION_ITEMS[0]),
ToolbarItemSpec::Action(LIST_TOOL_ACTION_ITEMS[1]),
ToolbarItemSpec::Action(LIST_TOOL_ACTION_ITEMS[2]),
ToolbarItemSpec::Action(LIST_TOOL_ACTION_ITEMS[3]),
ToolbarItemSpec::Action(act(
"divider",
"Divider",
"DividerIcon",
KeyboardToolbarAction::Slash(SlashCommand::Divider),
Some("affine:divider"),
)),
ToolbarItemSpec::Action(act(
"outdent",
"Outdent",
"CollapseTabIcon",
KeyboardToolbarAction::Outdent,
None,
)),
ToolbarItemSpec::Action(act(
"copy",
"Copy",
"CopyIcon",
KeyboardToolbarAction::Copy,
None,
)),
ToolbarItemSpec::Action(act(
"duplicate",
"Duplicate",
"NoteShadowDuotoneIcon",
KeyboardToolbarAction::Duplicate,
None,
)),
ToolbarItemSpec::Action(act(
"delete",
"Delete",
"DeleteIcon",
KeyboardToolbarAction::Delete,
None,
)),
];
@@ -0,0 +1,779 @@
//! Mobile soft-keyboard accessory toolbar (`KeyboardToolbar`), 1:1 with BlockSuite
//! `0.27.5` `defaultKeyboardToolbarConfig`.
//!
//! Docked above the soft keyboard on mobile / narrow viewports with `>= 44x44 pt`
//! touch targets, top-level bar (`+`, `Aa`, `Image`, `Undo`, `Redo`, `RightTab`,
//! lists, `Divider`, `CollapseTab`, `Copy`, `Duplicate`, `Delete`, fixed `Dismiss`),
//! `Aa` text-style sub-toolbar (with `autoShow` on non-collapsed selection),
//! 8-group `+` insert panel, `Turn into` panel, and 9-color `Highlight` panel.
mod config;
mod render;
pub use config::{
DEFAULT_KEYBOARD_TOOLBAR_ITEMS, MORE_TOOL_PANEL_GROUPS, TEXT_SUB_TOOLBAR_ITEMS,
TURN_INTO_PANEL_ITEMS, ToolPanelGroupSpec, ToolbarActionSpec, ToolbarItemSpec,
is_flavour_supported,
};
use super::{Overlays, SlashCommand};
/// Minimum touch target dimension for every mobile keyboard toolbar button (44x44 pt).
pub const KEYBOARD_TOOLBAR_BUTTON: f32 = 44.0;
/// Total height of the docked mobile keyboard toolbar strip.
pub const KEYBOARD_TOOLBAR_HEIGHT: f32 = 52.0;
/// Preferred height of the docked mobile keyboard tool panel below the toolbar strip
/// (aligned with BlockSuite `0.27.5` `keyboard-toolbar.ts` `330px` panel budget).
pub const KEYBOARD_TOOL_PANEL_HEIGHT: f32 = 316.0;
/// Highlight palette matching `0.27.5` `highlightToolPanel` (Default + 8 semantic colors).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HighlightColor {
Default,
Red,
Orange,
Yellow,
Green,
Teal,
Blue,
Purple,
Grey,
}
impl HighlightColor {
pub const ALL: [Self; 9] = [
Self::Default,
Self::Red,
Self::Orange,
Self::Yellow,
Self::Green,
Self::Teal,
Self::Blue,
Self::Purple,
Self::Grey,
];
pub const fn id(self) -> &'static str {
match self {
Self::Default => "default",
Self::Red => "red",
Self::Orange => "orange",
Self::Yellow => "yellow",
Self::Green => "green",
Self::Teal => "teal",
Self::Blue => "blue",
Self::Purple => "purple",
Self::Grey => "grey",
}
}
pub const fn label(self) -> &'static str {
match self {
Self::Default => "Default",
Self::Red => "Red",
Self::Orange => "Orange",
Self::Yellow => "Yellow",
Self::Green => "Green",
Self::Teal => "Teal",
Self::Blue => "Blue",
Self::Purple => "Purple",
Self::Grey => "Grey",
}
}
/// Foreground text highlight CSS variable (`var(--affine-v2-text-highlight-fg-*)`),
/// or `None` for Default (clears the `color` mark).
pub const fn fg_css_var(self) -> Option<&'static str> {
match self {
Self::Default => None,
Self::Red => Some("var(--affine-v2-text-highlight-fg-red)"),
Self::Orange => Some("var(--affine-v2-text-highlight-fg-orange)"),
Self::Yellow => Some("var(--affine-v2-text-highlight-fg-yellow)"),
Self::Green => Some("var(--affine-v2-text-highlight-fg-green)"),
Self::Teal => Some("var(--affine-v2-text-highlight-fg-teal)"),
Self::Blue => Some("var(--affine-v2-text-highlight-fg-blue)"),
Self::Purple => Some("var(--affine-v2-text-highlight-fg-purple)"),
Self::Grey => Some("var(--affine-v2-text-highlight-fg-grey)"),
}
}
/// Background highlight CSS variable (`var(--affine-v2-text-highlight-bg-*)`),
/// or `None` for Default (clears the `background` mark).
pub const fn bg_css_var(self) -> Option<&'static str> {
match self {
Self::Default => None,
Self::Red => Some("var(--affine-v2-text-highlight-bg-red)"),
Self::Orange => Some("var(--affine-v2-text-highlight-bg-orange)"),
Self::Yellow => Some("var(--affine-v2-text-highlight-bg-yellow)"),
Self::Green => Some("var(--affine-v2-text-highlight-bg-green)"),
Self::Teal => Some("var(--affine-v2-text-highlight-bg-teal)"),
Self::Blue => Some("var(--affine-v2-text-highlight-bg-blue)"),
Self::Purple => Some("var(--affine-v2-text-highlight-bg-purple)"),
Self::Grey => Some("var(--affine-v2-text-highlight-bg-grey)"),
}
}
}
/// Date insertion presets matching `0.27.5` `dateToolGroup`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeyboardToolbarDateKind {
Today,
Tomorrow,
Yesterday,
Now,
}
impl KeyboardToolbarDateKind {
pub const fn id(self) -> &'static str {
match self {
Self::Today => "date_today",
Self::Tomorrow => "date_tomorrow",
Self::Yesterday => "date_yesterday",
Self::Now => "date_now",
}
}
pub const fn label(self) -> &'static str {
match self {
Self::Today => "Today",
Self::Tomorrow => "Tomorrow",
Self::Yesterday => "Yesterday",
Self::Now => "Now",
}
}
pub const fn badge(self) -> &'static str {
match self {
Self::Today => "0d",
Self::Tomorrow => "+1",
Self::Yesterday => "-1",
Self::Now => "Now",
}
}
}
/// Active docked bottom panel of `KeyboardToolbar`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeyboardToolbarPanel {
/// `+` (`moreToolPanel`): 8-group block insert panel.
More,
/// `Turn into` (`textToolPanel`): block conversion panel inside `Aa`.
TurnInto,
/// `Highlight` (`highlightToolPanel`): 9-color fg + 9-color bg panel inside `Aa`.
Highlight,
}
/// Active navigation level of `KeyboardToolbar`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KeyboardToolbarLevel {
#[default]
Main,
/// `Aa` (`textSubToolbarConfig`).
TextStyle,
}
/// Actions exposed by the mobile `KeyboardToolbar` and its panels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyboardToolbarAction {
/// Toggle `+` (`moreToolPanel`).
ToggleMorePanel,
/// Enter `Aa` (`textSubToolbarConfig`).
OpenTextSubToolbar,
/// Return from `Aa` sub-toolbar to top-level toolbar.
BackToMainToolbar,
/// Toggle `Turn into` panel inside `Aa`.
ToggleTurnIntoPanel,
/// Toggle `Highlight` panel inside `Aa`.
ToggleHighlightPanel,
/// Reuse `SlashCommand` for block conversions & inserts (`Text`, `H1..H6`, `Code`,
/// `Quote`, `Divider`, `Bulleted`, `Numbered`, `Todo`, `Toggle`, `NewDoc`, `LinkedDoc`).
Slash(SlashCommand),
/// Insert a block LaTeX equation and open the equation editor.
EquationBlock,
/// Insert a 2x2 table block.
Table,
/// Insert a callout block with a child paragraph.
Callout,
/// Insert an image block.
Image,
/// Insert a bookmark card block.
Bookmark,
/// Declared for `0.27.5` parity (`showWhen: () => false`).
Attachment,
/// Schema-gated embeds (`showWhen` hidden when flavour unsupported).
EmbedIframe,
EmbedYoutube,
EmbedGithub,
EmbedFigma,
EmbedLoom,
/// Schema-gated database views (`showWhen` hidden before S4 `affine:database`).
DatabaseTableView,
DatabaseKanbanView,
/// Insert formatted date/time text using the deterministic scheduler clock.
Date(KeyboardToolbarDateKind),
Undo,
Redo,
Indent,
Outdent,
Copy,
Duplicate,
Delete,
Bold,
Italic,
Underline,
Strike,
InlineCode,
Link,
InlineMath,
SetTextColor(HighlightColor),
SetBgColor(HighlightColor),
Dismiss,
}
impl KeyboardToolbarAction {
/// Whether this action requires an active body `EditorSession` selection.
/// When a table cell is focused without a body selection, these buttons render disabled.
pub fn requires_body_selection(self) -> bool {
!matches!(self, Self::Undo | Self::Redo | Self::Dismiss)
}
/// Stable snapshot id suffix for `overlay.keyboard_toolbar.<id>`.
pub fn id(self) -> &'static str {
match self {
Self::ToggleMorePanel => "more_panel",
Self::OpenTextSubToolbar => "text_style",
Self::BackToMainToolbar => "back",
Self::ToggleTurnIntoPanel => "turn_into",
Self::ToggleHighlightPanel => "highlight",
Self::Slash(cmd) => match cmd {
SlashCommand::Paragraph(p) => match p {
blocksuite_playground_doc::schema::ParagraphType::Text => "text",
blocksuite_playground_doc::schema::ParagraphType::H1 => "h1",
blocksuite_playground_doc::schema::ParagraphType::H2 => "h2",
blocksuite_playground_doc::schema::ParagraphType::H3 => "h3",
blocksuite_playground_doc::schema::ParagraphType::H4 => "h4",
blocksuite_playground_doc::schema::ParagraphType::H5 => "h5",
blocksuite_playground_doc::schema::ParagraphType::H6 => "h6",
blocksuite_playground_doc::schema::ParagraphType::Quote => "quote",
},
SlashCommand::List(l) => match l {
blocksuite_playground_doc::schema::ListType::Bulleted => "bullet",
blocksuite_playground_doc::schema::ListType::Numbered => "numbered",
blocksuite_playground_doc::schema::ListType::Todo => "todo",
blocksuite_playground_doc::schema::ListType::Toggle => "toggle",
},
SlashCommand::Divider => "divider",
SlashCommand::Code => "code_block",
SlashCommand::NewDoc => "new_page",
SlashCommand::LinkedDoc => "linked_page",
},
Self::EquationBlock => "equation_block",
Self::Table => "table",
Self::Callout => "callout",
Self::Image => "image",
Self::Bookmark => "bookmark",
Self::Attachment => "attachment",
Self::EmbedIframe => "embed_iframe",
Self::EmbedYoutube => "embed_youtube",
Self::EmbedGithub => "embed_github",
Self::EmbedFigma => "embed_figma",
Self::EmbedLoom => "embed_loom",
Self::DatabaseTableView => "database_table",
Self::DatabaseKanbanView => "database_kanban",
Self::Date(kind) => kind.id(),
Self::Undo => "undo",
Self::Redo => "redo",
Self::Indent => "indent",
Self::Outdent => "outdent",
Self::Copy => "copy",
Self::Duplicate => "duplicate",
Self::Delete => "delete",
Self::Bold => "bold",
Self::Italic => "italic",
Self::Underline => "underline",
Self::Strike => "strike",
Self::InlineCode => "inline_code",
Self::Link => "link",
Self::InlineMath => "inline_math",
Self::SetTextColor(c) => match c {
HighlightColor::Default => "fg_default",
HighlightColor::Red => "fg_red",
HighlightColor::Orange => "fg_orange",
HighlightColor::Yellow => "fg_yellow",
HighlightColor::Green => "fg_green",
HighlightColor::Teal => "fg_teal",
HighlightColor::Blue => "fg_blue",
HighlightColor::Purple => "fg_purple",
HighlightColor::Grey => "fg_grey",
},
Self::SetBgColor(c) => match c {
HighlightColor::Default => "bg_default",
HighlightColor::Red => "bg_red",
HighlightColor::Orange => "bg_orange",
HighlightColor::Yellow => "bg_yellow",
HighlightColor::Green => "bg_green",
HighlightColor::Teal => "bg_teal",
HighlightColor::Blue => "bg_blue",
HighlightColor::Purple => "bg_purple",
HighlightColor::Grey => "bg_grey",
},
Self::Dismiss => "dismiss",
}
}
}
/// Per-frame dynamic editor capabilities fed to `KeyboardToolbar`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct KeyboardToolbarCapabilities {
pub can_undo: bool,
pub can_redo: bool,
pub can_indent: bool,
pub can_dedent: bool,
pub can_pick_images: bool,
pub has_body_selection: bool,
pub has_non_collapsed_selection: bool,
}
/// Complete state of the mobile `KeyboardToolbar` owned by [`Overlays`].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct KeyboardToolbarState {
pub visible: bool,
pub level: KeyboardToolbarLevel,
pub manual_text_subtoolbar: bool,
pub active_panel: Option<KeyboardToolbarPanel>,
pub page: usize,
pub panel_scroll: f32,
pub marks_disabled: bool,
pub capabilities: KeyboardToolbarCapabilities,
}
impl KeyboardToolbarState {
pub fn close_transient(&mut self) {
self.active_panel = None;
self.panel_scroll = 0.0;
self.page = 0;
if !self.capabilities.has_non_collapsed_selection {
self.level = KeyboardToolbarLevel::Main;
self.manual_text_subtoolbar = false;
}
}
}
impl Overlays {
/// Whether the mobile bottom `KeyboardToolbar` is currently visible.
pub fn keyboard_toolbar_visible(&self) -> bool {
self.keyboard_toolbar.visible
}
/// Show or hide the mobile bottom `KeyboardToolbar`.
pub fn set_keyboard_toolbar_visible(&mut self, visible: bool) {
self.keyboard_toolbar.visible = visible;
if !visible {
self.keyboard_toolbar.page = 0;
self.keyboard_toolbar.active_panel = None;
self.keyboard_toolbar.panel_scroll = 0.0;
self.keyboard_toolbar.level = KeyboardToolbarLevel::Main;
self.keyboard_toolbar.manual_text_subtoolbar = false;
}
}
/// Whether body-selection-dependent mark/block buttons are disabled (e.g. table cell focus).
/// Also auto-collapses any open `+` / `Aa` sub-panel per table-cell gating rules.
pub fn set_keyboard_toolbar_marks_disabled(&mut self, disabled: bool) {
self.keyboard_toolbar.marks_disabled = disabled;
if disabled {
self.keyboard_toolbar.active_panel = None;
self.keyboard_toolbar.panel_scroll = 0.0;
self.keyboard_toolbar.level = KeyboardToolbarLevel::Main;
self.keyboard_toolbar.manual_text_subtoolbar = false;
}
}
/// Sync per-frame undo/redo/indent/dedent and `autoShow` selection capabilities.
pub fn set_keyboard_toolbar_capabilities(&mut self, caps: KeyboardToolbarCapabilities) {
let prev_non_collapsed = self
.keyboard_toolbar
.capabilities
.has_non_collapsed_selection;
self.keyboard_toolbar.capabilities = caps;
if self.keyboard_toolbar.marks_disabled {
self.keyboard_toolbar.active_panel = None;
self.keyboard_toolbar.level = KeyboardToolbarLevel::Main;
self.keyboard_toolbar.manual_text_subtoolbar = false;
return;
}
// `textSubToolbarConfig.autoShow`: switch to `Aa` when a non-collapsed text selection
// opens, and return to top-level bar when collapsed unless opened manually.
if caps.has_non_collapsed_selection && !prev_non_collapsed {
self.keyboard_toolbar.level = KeyboardToolbarLevel::TextStyle;
self.keyboard_toolbar.page = 0;
} else if !caps.has_non_collapsed_selection
&& prev_non_collapsed
&& !self.keyboard_toolbar.manual_text_subtoolbar
{
self.keyboard_toolbar.level = KeyboardToolbarLevel::Main;
if matches!(
self.keyboard_toolbar.active_panel,
Some(KeyboardToolbarPanel::TurnInto | KeyboardToolbarPanel::Highlight)
) {
self.keyboard_toolbar.active_panel = None;
self.keyboard_toolbar.panel_scroll = 0.0;
}
self.keyboard_toolbar.page = 0;
}
}
/// Current navigation level (`Main` or `TextStyle`).
pub fn keyboard_toolbar_level(&self) -> KeyboardToolbarLevel {
self.keyboard_toolbar.level
}
/// Currently expanded docked tool panel, if any.
pub fn keyboard_toolbar_active_panel(&self) -> Option<KeyboardToolbarPanel> {
self.keyboard_toolbar.active_panel
}
/// Current page index of the paginated mobile `KeyboardToolbar`.
pub fn keyboard_toolbar_page(&self) -> usize {
self.keyboard_toolbar.page
}
/// Advance the mobile `KeyboardToolbar` to the next action page.
pub fn next_keyboard_toolbar_page(&mut self) {
self.keyboard_toolbar.page = self.keyboard_toolbar.page.wrapping_add(1);
}
/// Toggle one docked bottom tool panel (`More`, `TurnInto`, or `Highlight`).
pub fn toggle_keyboard_toolbar_panel(&mut self, panel: KeyboardToolbarPanel) {
if self.keyboard_toolbar.marks_disabled {
return;
}
if self.keyboard_toolbar.active_panel == Some(panel) {
self.keyboard_toolbar.active_panel = None;
} else {
self.keyboard_toolbar.active_panel = Some(panel);
}
self.keyboard_toolbar.panel_scroll = 0.0;
}
/// Close any open keyboard tool panel.
pub fn close_keyboard_toolbar_panel(&mut self) {
self.keyboard_toolbar.active_panel = None;
self.keyboard_toolbar.panel_scroll = 0.0;
}
/// Enter the `Aa` text-style sub-toolbar manually.
pub fn open_keyboard_text_subtoolbar(&mut self) {
if self.keyboard_toolbar.marks_disabled {
return;
}
self.keyboard_toolbar.active_panel = None;
self.keyboard_toolbar.panel_scroll = 0.0;
self.keyboard_toolbar.level = KeyboardToolbarLevel::TextStyle;
self.keyboard_toolbar.manual_text_subtoolbar = true;
self.keyboard_toolbar.page = 0;
}
/// Return from the `Aa` text-style sub-toolbar to the top-level toolbar.
pub fn close_keyboard_text_subtoolbar(&mut self) {
self.keyboard_toolbar.active_panel = None;
self.keyboard_toolbar.panel_scroll = 0.0;
self.keyboard_toolbar.level = KeyboardToolbarLevel::Main;
self.keyboard_toolbar.manual_text_subtoolbar = false;
self.keyboard_toolbar.page = 0;
}
/// Scroll an open keyboard tool panel (`+`, `Turn into`, or `Highlight`) by `delta_y` px.
pub(super) fn scroll_active_keyboard_tool_panel(
&mut self,
scene: &crate::overlays::OverlayScene<'_>,
delta_y: f32,
) -> bool {
if !self.keyboard_toolbar.visible || self.keyboard_toolbar.marks_disabled {
return false;
}
let Some(panel) = self.keyboard_toolbar.active_panel else {
return false;
};
if delta_y == 0.0 {
return true;
}
let width = scene.window.0.max(0.0).floor();
let win_h = scene.window.1.max(0.0).floor();
let max_panel = (win_h - crate::TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0);
let panel_height = KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor();
let pad_x = if width <= 340.0 { 8.0 } else { 12.0 };
let inner_w = (width - pad_x * 2.0 - 2.0).max(120.0);
let list_h = (panel_height - 16.0 - 2.0).max(80.0);
let cols: usize = ((inner_w + 6.0) / (KEYBOARD_TOOLBAR_BUTTON + 6.0))
.floor()
.clamp(3.0, 5.0) as usize;
let header_h = 18.0;
let tile_row_h = KEYBOARD_TOOLBAR_BUTTON + 14.0;
let row_gap = 4.0;
let group_gap = 8.0;
let can_pick_images = self.keyboard_toolbar.capabilities.can_pick_images;
let mut cursor_y = 0.0_f32;
match panel {
KeyboardToolbarPanel::More => {
let mut first = true;
for group in MORE_TOOL_PANEL_GROUPS {
let count = group
.items
.iter()
.filter(|i| i.is_visible_for(can_pick_images))
.count();
if count == 0 {
continue;
}
if !first {
cursor_y += group_gap;
}
first = false;
cursor_y += header_h + row_gap;
cursor_y += (count.div_ceil(cols) as f32) * (tile_row_h + row_gap);
}
}
KeyboardToolbarPanel::TurnInto => {
let count = TURN_INTO_PANEL_ITEMS
.iter()
.filter(|i| i.is_visible_for(can_pick_images))
.count();
cursor_y += header_h + row_gap;
cursor_y += (count.div_ceil(cols) as f32) * (tile_row_h + row_gap);
}
KeyboardToolbarPanel::Highlight => {
for idx in 0..2 {
if idx > 0 {
cursor_y += group_gap;
}
cursor_y += header_h + row_gap;
cursor_y +=
(HighlightColor::ALL.len().div_ceil(cols) as f32) * (tile_row_h + row_gap);
}
}
}
let max_scroll = (cursor_y - list_h).max(0.0);
self.keyboard_toolbar.panel_scroll = (self.keyboard_toolbar.panel_scroll - delta_y)
.clamp(0.0, max_scroll)
.round();
true
}
/// Scroll an open keyboard tool panel when `(x, y)` lies inside its docked rect.
pub(super) fn scroll_keyboard_tool_panel(
&mut self,
scene: &crate::overlays::OverlayScene<'_>,
x: f32,
y: f32,
delta_y: f32,
) -> bool {
if !self.keyboard_toolbar.visible
|| self.keyboard_toolbar.marks_disabled
|| self.keyboard_toolbar.active_panel.is_none()
{
return false;
}
let width = scene.window.0.max(0.0).floor();
let win_h = scene.window.1.max(0.0).floor();
let max_panel = (win_h - crate::TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0);
let panel_height = KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor();
let top = (win_h - (KEYBOARD_TOOLBAR_HEIGHT + panel_height))
.max(crate::TOPBAR_HEIGHT)
.floor();
let panel_rect = crate::block_flow::FlowRect::new(
0.0,
top + KEYBOARD_TOOLBAR_HEIGHT,
width,
panel_height,
);
panel_rect.contains(x, y) && self.scroll_active_keyboard_tool_panel(scene, delta_y)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::overlays::slash_item_by_id;
#[test]
fn config_matches_0275_top_level_and_8_panel_groups_order() {
let top_ids: Vec<&str> = DEFAULT_KEYBOARD_TOOLBAR_ITEMS
.iter()
.map(ToolbarItemSpec::id)
.collect();
assert_eq!(
top_ids,
vec![
"more_panel",
"text_style",
"image",
"attachment",
"undo",
"redo",
"indent",
"bullet",
"numbered",
"todo",
"toggle",
"divider",
"outdent",
"copy",
"duplicate",
"delete",
]
);
let group_names: Vec<&str> = MORE_TOOL_PANEL_GROUPS.iter().map(|g| g.name).collect();
assert_eq!(
group_names,
vec![
"Basic",
"List",
"Page",
"Content & Media",
"Embeds",
"Document Group&Frame",
"Date",
"Database",
]
);
// Attachment is declared in both top-level and Content & Media with showWhen == false.
let top_att = DEFAULT_KEYBOARD_TOOLBAR_ITEMS
.iter()
.find(|i| i.id() == "attachment")
.expect("Attachment declared");
assert!(!top_att.is_visible());
// Database views are declared and hidden by schema showWhen before S4.
let db = MORE_TOOL_PANEL_GROUPS
.iter()
.find(|g| g.name == "Database")
.expect("Database group declared");
assert_eq!(db.items.len(), 2);
assert!(db.items.iter().all(|item| !item.is_visible()));
assert!(!is_flavour_supported("affine:database"));
}
#[test]
fn slash_backed_toolbar_items_reuse_slash_items_definitions() {
for (slash_id, expected_action) in [
(
"text",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(
blocksuite_playground_doc::schema::ParagraphType::Text,
)),
),
(
"h1",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(
blocksuite_playground_doc::schema::ParagraphType::H1,
)),
),
(
"h6",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(
blocksuite_playground_doc::schema::ParagraphType::H6,
)),
),
("code", KeyboardToolbarAction::Slash(SlashCommand::Code)),
(
"quote",
KeyboardToolbarAction::Slash(SlashCommand::Paragraph(
blocksuite_playground_doc::schema::ParagraphType::Quote,
)),
),
(
"divider",
KeyboardToolbarAction::Slash(SlashCommand::Divider),
),
(
"bulleted",
KeyboardToolbarAction::Slash(SlashCommand::List(
blocksuite_playground_doc::schema::ListType::Bulleted,
)),
),
(
"numbered",
KeyboardToolbarAction::Slash(SlashCommand::List(
blocksuite_playground_doc::schema::ListType::Numbered,
)),
),
(
"todo",
KeyboardToolbarAction::Slash(SlashCommand::List(
blocksuite_playground_doc::schema::ListType::Todo,
)),
),
(
"toggle",
KeyboardToolbarAction::Slash(SlashCommand::List(
blocksuite_playground_doc::schema::ListType::Toggle,
)),
),
(
"new_doc",
KeyboardToolbarAction::Slash(SlashCommand::NewDoc),
),
(
"linked_doc",
KeyboardToolbarAction::Slash(SlashCommand::LinkedDoc),
),
] {
let slash = slash_item_by_id(slash_id).expect("slash item exists");
assert_eq!(KeyboardToolbarAction::Slash(slash.command), expected_action);
}
}
#[test]
fn autoshow_switches_to_text_subtoolbar_and_table_gate_collapses_panels() {
let mut overlays = Overlays::new();
overlays.set_keyboard_toolbar_visible(true);
assert_eq!(
overlays.keyboard_toolbar_level(),
KeyboardToolbarLevel::Main
);
overlays.set_keyboard_toolbar_capabilities(KeyboardToolbarCapabilities {
has_body_selection: true,
has_non_collapsed_selection: true,
..Default::default()
});
assert_eq!(
overlays.keyboard_toolbar_level(),
KeyboardToolbarLevel::TextStyle
);
overlays.toggle_keyboard_toolbar_panel(KeyboardToolbarPanel::Highlight);
assert_eq!(
overlays.keyboard_toolbar_active_panel(),
Some(KeyboardToolbarPanel::Highlight)
);
// Collapsing selection returns to Main and closes sub-panel.
overlays.set_keyboard_toolbar_capabilities(KeyboardToolbarCapabilities {
has_body_selection: true,
has_non_collapsed_selection: false,
..Default::default()
});
assert_eq!(
overlays.keyboard_toolbar_level(),
KeyboardToolbarLevel::Main
);
assert_eq!(overlays.keyboard_toolbar_active_panel(), None);
// Table cell focus gate collapses any open panel immediately.
overlays.toggle_keyboard_toolbar_panel(KeyboardToolbarPanel::More);
assert_eq!(
overlays.keyboard_toolbar_active_panel(),
Some(KeyboardToolbarPanel::More)
);
overlays.set_keyboard_toolbar_marks_disabled(true);
assert_eq!(overlays.keyboard_toolbar_active_panel(), None);
assert_eq!(
overlays.keyboard_toolbar_level(),
KeyboardToolbarLevel::Main
);
}
}
@@ -0,0 +1,759 @@
//! Painting for `KeyboardToolbar` strip and its docked bottom tool panels
//! (`+` 8-group insert panel, `Turn into` panel, and 9-color `Highlight` panel).
use ui::{AnyElement, ClickEvent, Context, FontWeight, Hsla, SharedString, div, prelude::*, px};
use crate::{
TOPBAR_HEIGHT,
block_flow::FlowRect,
overlays::{
MarkState, OverlayEvent, OverlayHost, OverlayScene, Overlays,
paint_page::{emit, icon, place},
},
theme::{Palette, TYPOGRAPHY},
};
use super::{
DEFAULT_KEYBOARD_TOOLBAR_ITEMS, HighlightColor, KEYBOARD_TOOL_PANEL_HEIGHT,
KEYBOARD_TOOLBAR_BUTTON, KEYBOARD_TOOLBAR_HEIGHT, KeyboardToolbarAction, KeyboardToolbarLevel,
KeyboardToolbarPanel, MORE_TOOL_PANEL_GROUPS, TEXT_SUB_TOOLBAR_ITEMS, TURN_INTO_PANEL_ITEMS,
ToolbarActionSpec, ToolbarItemSpec,
};
fn image_icon_glyph(color: Hsla) -> AnyElement {
ui::canvas(
|_, _, _| (),
move |bounds, (), window, _| {
let x = f32::from(bounds.origin.x);
let y = f32::from(bounds.origin.y);
let w = f32::from(bounds.size.width);
let h = f32::from(bounds.size.height);
// Outer rounded-ish frame + mountain ridge + sun dot (20x20).
let mut frame = ui::PathBuilder::stroke(px(1.5));
frame.move_to(ui::point(px(x + w * 0.16), px(y + h * 0.20)));
frame.line_to(ui::point(px(x + w * 0.84), px(y + h * 0.20)));
frame.line_to(ui::point(px(x + w * 0.84), px(y + h * 0.80)));
frame.line_to(ui::point(px(x + w * 0.16), px(y + h * 0.80)));
frame.close();
if let Ok(path) = frame.build() {
window.paint_path(path, color);
}
let mut ridge = ui::PathBuilder::stroke(px(1.5));
ridge.move_to(ui::point(px(x + w * 0.20), px(y + h * 0.72)));
ridge.line_to(ui::point(px(x + w * 0.44), px(y + h * 0.48)));
ridge.line_to(ui::point(px(x + w * 0.60), px(y + h * 0.64)));
ridge.line_to(ui::point(px(x + w * 0.72), px(y + h * 0.52)));
ridge.line_to(ui::point(px(x + w * 0.82), px(y + h * 0.68)));
if let Ok(path) = ridge.build() {
window.paint_path(path, color);
}
let mut sun = ui::PathBuilder::fill();
let cx_pt = x + w * 0.66;
let cy_pt = y + h * 0.36;
let r = w * 0.075;
sun.move_to(ui::point(px(cx_pt - r), px(cy_pt)));
sun.line_to(ui::point(px(cx_pt), px(cy_pt - r)));
sun.line_to(ui::point(px(cx_pt + r), px(cy_pt)));
sun.line_to(ui::point(px(cx_pt), px(cy_pt + r)));
sun.close();
if let Ok(path) = sun.build() {
window.paint_path(path, color);
}
},
)
.w(px(20.0))
.h(px(20.0))
.into_any_element()
}
impl Overlays {
pub(crate) fn render_keyboard_toolbar<V: OverlayHost>(
&mut self,
scene: &OverlayScene<'_>,
palette: &Palette,
cx: &mut Context<V>,
) -> Option<AnyElement> {
if !self.keyboard_toolbar.visible {
return None;
}
let width = scene.window.0.max(0.0).floor();
let win_h = scene.window.1.max(0.0).floor();
let active_panel = if self.keyboard_toolbar.marks_disabled {
None
} else {
self.keyboard_toolbar.active_panel
};
let panel_height = if active_panel.is_some() {
let max_panel = (win_h - TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0);
KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor()
} else {
0.0
};
let total_height = KEYBOARD_TOOLBAR_HEIGHT + panel_height;
let top = (win_h - total_height).max(TOPBAR_HEIGHT).floor();
let marks = self
.open_toolbar()
.map(|t| t.selection.marks.clone())
.unwrap_or_default();
let bar_rect = FlowRect::new(0.0, top, width, KEYBOARD_TOOLBAR_HEIGHT);
let bar = self.render_toolbar_strip(bar_rect, &marks, palette, cx);
if let Some(panel_kind) = active_panel {
let panel_rect = FlowRect::new(0.0, top + KEYBOARD_TOOLBAR_HEIGHT, width, panel_height);
let panel = self.render_tool_panel(panel_kind, panel_rect, palette, cx);
let container = place(FlowRect::new(0.0, top, width, total_height))
.id("keyboard-toolbar-shell")
.flex()
.flex_col()
.child(bar)
.child(panel);
Some(container.into_any_element())
} else {
Some(place(bar_rect).child(bar).into_any_element())
}
}
fn is_action_disabled(&self, action: KeyboardToolbarAction) -> bool {
let state = &self.keyboard_toolbar;
if state.marks_disabled && action.requires_body_selection() {
return true;
}
match action {
KeyboardToolbarAction::Undo => !state.capabilities.can_undo,
KeyboardToolbarAction::Redo => !state.capabilities.can_redo,
KeyboardToolbarAction::Indent => !state.capabilities.can_indent,
KeyboardToolbarAction::Outdent => !state.capabilities.can_dedent,
_ => false,
}
}
fn is_item_active(&self, item: &ToolbarItemSpec, marks: &MarkState) -> bool {
match item {
ToolbarItemSpec::ToolPanel { panel, .. } => {
!self.keyboard_toolbar.marks_disabled
&& self.keyboard_toolbar.active_panel == Some(*panel)
}
ToolbarItemSpec::SubToolbar { .. } => {
!self.keyboard_toolbar.marks_disabled
&& self.keyboard_toolbar.level == KeyboardToolbarLevel::TextStyle
}
ToolbarItemSpec::Action(spec) => match spec.action {
KeyboardToolbarAction::Bold => marks.bold,
KeyboardToolbarAction::Italic => marks.italic,
KeyboardToolbarAction::Underline => marks.underline,
KeyboardToolbarAction::Strike => marks.strike,
KeyboardToolbarAction::InlineCode => marks.code,
KeyboardToolbarAction::Link => marks.link.is_some() || self.link_field().is_some(),
_ => false,
},
}
}
fn render_toolbar_strip<V: OverlayHost>(
&self,
rect: FlowRect,
marks: &MarkState,
palette: &Palette,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let pad_x = 4.0;
let gap = 2.0;
let btn = KEYBOARD_TOOLBAR_BUTTON;
let in_sub = !self.keyboard_toolbar.marks_disabled
&& self.keyboard_toolbar.level == KeyboardToolbarLevel::TextStyle;
let can_pick_images = self.keyboard_toolbar.capabilities.can_pick_images;
let visible_items: Vec<ToolbarItemSpec> = if in_sub {
TEXT_SUB_TOOLBAR_ITEMS
.into_iter()
.filter(|item| item.is_visible_for(can_pick_images))
.collect()
} else {
DEFAULT_KEYBOARD_TOOLBAR_ITEMS
.into_iter()
.filter(|item| item.is_visible_for(can_pick_images))
.collect()
};
// Reserve fixed slots: Back (when in Aa sub-toolbar) + right divider (9px) + Dismiss (44px)
// plus optional More (44px) when remaining items overflow.
let fixed_right = btn + gap + 9.0;
let fixed_left = if in_sub { btn + gap } else { 0.0 };
let avail_no_more = (rect.w - pad_x * 2.0 - fixed_right - fixed_left).max(btn);
let slots_no_more = ((avail_no_more + gap) / (btn + gap)).floor().max(1.0) as usize;
let needs_paging = slots_no_more < visible_items.len();
let left_slots = if needs_paging {
let avail_with_more = (avail_no_more - btn - gap).max(btn);
((avail_with_more + gap) / (btn + gap)).floor().max(1.0) as usize
} else {
visible_items.len().max(1)
};
let page_count = visible_items.len().div_ceil(left_slots).max(1);
let page = self.keyboard_toolbar.page % page_count;
let start = page * left_slots;
let end = (start + left_slots).min(visible_items.len());
let slice = &visible_items[start..end];
let hover = palette.hover;
let active_bg = palette.brand.opacity(0.14);
let mut left_strip = div()
.flex_1()
.min_w(px(0.0))
.h(px(btn))
.flex()
.items_center()
.gap(px(gap))
.overflow_hidden();
if in_sub {
left_strip = left_strip.child(self.render_strip_button(
"back",
"Back",
"",
KeyboardToolbarAction::BackToMainToolbar,
false,
false,
palette,
hover,
active_bg,
cx,
));
}
for item in slice {
let action = item.action();
let disabled = self.is_action_disabled(action);
let active = self.is_item_active(item, marks);
left_strip = left_strip.child(self.render_strip_button(
item.id(),
item.name(),
item.icon(),
action,
disabled,
active,
palette,
hover,
active_bg,
cx,
));
}
let divider = div()
.flex_none()
.w(px(1.0))
.h(px(24.0))
.mx(px(3.0))
.bg(palette.border);
let dismiss = self.render_strip_button(
"dismiss",
"Dismiss",
"KeyboardIcon",
KeyboardToolbarAction::Dismiss,
false,
false,
palette,
hover,
active_bg,
cx,
);
let mut bar = div()
.id("keyboard-toolbar")
.flex_none()
.w(px(rect.w))
.h(px(KEYBOARD_TOOLBAR_HEIGHT))
.px(px(pad_x))
.flex()
.items_center()
.gap(px(gap))
.bg(palette.panel)
.border_1()
.border_color(palette.border)
.shadow(palette.theme.shadows("--affine-toolbar-shadow").into())
.occlude()
.snapshot("overlay.keyboard_toolbar", Some("root.canvas"))
.child(left_strip);
if needs_paging {
let more = div()
.id("kb-tool-more")
.flex_none()
.w(px(btn))
.h(px(btn))
.rounded(px(8.0))
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |style| style.bg(hover))
.on_click(emit(cx, |_: &ClickEvent| {
OverlayEvent::KeyboardToolbarNextPage
}))
.snapshot(
"overlay.keyboard_toolbar.more",
Some("overlay.keyboard_toolbar"),
)
.snapshot_text("More")
.child(icon("MoreHorizontalIcon", 20.0, palette.icon));
bar = bar.child(more);
}
bar.child(divider).child(dismiss)
}
#[allow(clippy::too_many_arguments)]
fn render_strip_button<V: OverlayHost>(
&self,
id: &'static str,
label: &'static str,
icon_name: &'static str,
action: KeyboardToolbarAction,
disabled: bool,
active: bool,
palette: &Palette,
hover: Hsla,
active_bg: Hsla,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let btn = KEYBOARD_TOOLBAR_BUTTON;
let ink = if active { palette.brand } else { palette.icon };
let mut button = div()
.id(SharedString::from(format!("kb-tool-{id}")))
.flex_none()
.w(px(btn))
.h(px(btn))
.rounded(px(8.0))
.flex()
.items_center()
.justify_center()
.text_size(px(TYPOGRAPHY.font_sm_px))
.font_weight(FontWeight::SEMIBOLD)
.text_color(ink)
.when(active, |el| el.bg(active_bg))
.snapshot(
SharedString::from(format!("overlay.keyboard_toolbar.{id}")),
Some("overlay.keyboard_toolbar"),
)
.snapshot_focused(active)
.snapshot_text(label);
if disabled {
button = button.opacity(0.35);
} else {
button = button
.cursor_pointer()
.hover(move |style| style.bg(hover))
.on_click(emit(cx, move |_: &ClickEvent| {
OverlayEvent::KeyboardToolbar(action)
}));
}
match action {
KeyboardToolbarAction::ToggleMorePanel if active => button.child(
div()
.text_size(px(20.0))
.text_color(palette.brand)
.child("\u{00D7}"),
),
KeyboardToolbarAction::OpenTextSubToolbar => button.child("Aa"),
KeyboardToolbarAction::BackToMainToolbar => {
button.child(div().text_size(px(18.0)).child("\u{2190}"))
}
KeyboardToolbarAction::Image => button.child(image_icon_glyph(ink)),
KeyboardToolbarAction::ToggleHighlightPanel => button.child(
div()
.flex()
.flex_col()
.items_center()
.justify_center()
.child(div().text_size(px(14.0)).line_height(px(15.0)).child("A"))
.child(
div()
.w(px(14.0))
.h(px(3.0))
.rounded(px(1.5))
.bg(palette.brand),
),
),
_ if !icon_name.is_empty() => button.child(icon(icon_name, 20.0, ink)),
_ => button.child(label),
}
}
fn render_tool_panel<V: OverlayHost>(
&self,
panel: KeyboardToolbarPanel,
rect: FlowRect,
palette: &Palette,
cx: &mut Context<V>,
) -> ui::Stateful<ui::Div> {
let pad_x = if rect.w <= 340.0 { 8.0 } else { 12.0 };
let pad_y = 8.0;
let col_gap = 6.0;
let inner_w = (rect.w - pad_x * 2.0 - 2.0).max(120.0);
let list_h = (rect.h - pad_y * 2.0 - 2.0).max(80.0);
let cols: usize = ((inner_w + col_gap) / (KEYBOARD_TOOLBAR_BUTTON + col_gap))
.floor()
.clamp(3.0, 5.0) as usize;
let tile_w = ((inner_w - col_gap * (cols as f32 - 1.0)) / cols as f32)
.floor()
.max(KEYBOARD_TOOLBAR_BUTTON);
let header_h = 18.0;
let tile_row_h = KEYBOARD_TOOLBAR_BUTTON + 14.0;
let row_gap = 4.0;
let group_gap = 8.0;
let mut list = div()
.relative()
.flex_none()
.w(px(inner_w))
.h(px(list_h))
.overflow_hidden();
let scroll = self.keyboard_toolbar.panel_scroll.max(0.0);
let mut cursor_y = 0.0_f32;
let push_header = |list: ui::Div, group_id: &'static str, title: &'static str, y: f32| {
let top = y - scroll;
if top + header_h <= 0.0 || top >= list_h {
return list;
}
list.child(
div()
.absolute()
.left(px(0.0))
.top(px(top))
.w(px(inner_w))
.h(px(header_h))
.flex()
.items_center()
.text_size(px(TYPOGRAPHY.font_xs_px))
.font_weight(FontWeight::SEMIBOLD)
.text_color(palette.text_secondary)
.snapshot(
SharedString::from(format!("overlay.keyboard_toolbar.group.{group_id}")),
Some("overlay.keyboard_toolbar.panel"),
)
.snapshot_text(title)
.child(title),
)
};
let can_pick_images = self.keyboard_toolbar.capabilities.can_pick_images;
match panel {
KeyboardToolbarPanel::More => {
let mut first = true;
for group in MORE_TOOL_PANEL_GROUPS {
let visible: Vec<&ToolbarActionSpec> = group
.items
.iter()
.filter(|i| i.is_visible_for(can_pick_images))
.collect();
if visible.is_empty() {
continue;
}
if !first {
cursor_y += group_gap;
}
first = false;
list = push_header(list, group.id, group.name, cursor_y);
cursor_y += header_h + row_gap;
for chunk in visible.chunks(cols) {
let top = cursor_y - scroll;
if top + tile_row_h > 0.0 && top < list_h {
list = list.child(self.render_action_row(
group.id, chunk, top, inner_w, tile_w, tile_row_h, col_gap,
palette, cx,
));
}
cursor_y += tile_row_h + row_gap;
}
}
}
KeyboardToolbarPanel::TurnInto => {
let visible: Vec<&ToolbarActionSpec> = TURN_INTO_PANEL_ITEMS
.iter()
.filter(|i| i.is_visible_for(can_pick_images))
.collect();
list = push_header(list, "turn_into", "Turn into", cursor_y);
cursor_y += header_h + row_gap;
for chunk in visible.chunks(cols) {
let top = cursor_y - scroll;
if top + tile_row_h > 0.0 && top < list_h {
list = list.child(self.render_action_row(
"turn_into",
chunk,
top,
inner_w,
tile_w,
tile_row_h,
col_gap,
palette,
cx,
));
}
cursor_y += tile_row_h + row_gap;
}
}
KeyboardToolbarPanel::Highlight => {
for (idx, (group_id, title, is_bg)) in [
("color", "Color", false),
("background", "Background", true),
]
.into_iter()
.enumerate()
{
if idx > 0 {
cursor_y += group_gap;
}
list = push_header(list, group_id, title, cursor_y);
cursor_y += header_h + row_gap;
for chunk in HighlightColor::ALL.chunks(cols) {
let top = cursor_y - scroll;
if top + tile_row_h > 0.0 && top < list_h {
list = list.child(self.render_highlight_row(
group_id, is_bg, chunk, top, inner_w, tile_w, tile_row_h, col_gap,
palette, cx,
));
}
cursor_y += tile_row_h + row_gap;
}
}
}
}
if cursor_y > list_h {
let thumb_h = (list_h * list_h / cursor_y).max(24.0).round();
let max_scroll = (cursor_y - list_h).max(1.0);
let thumb_top = ((list_h - thumb_h) * (scroll / max_scroll).clamp(0.0, 1.0)).round();
list = list.child(
div()
.absolute()
.left(px(inner_w - 3.0))
.top(px(thumb_top))
.w(px(3.0))
.h(px(thumb_h))
.rounded(px(1.5))
.bg(palette.text_secondary.opacity(0.35)),
);
}
div()
.id("keyboard-tool-panel")
.flex_none()
.w(px(rect.w))
.h(px(rect.h))
.px(px(pad_x))
.py(px(pad_y))
.bg(palette.background)
.border_1()
.border_color(palette.border)
.overflow_hidden()
.occlude()
.on_scroll(emit(cx, |ev: &ui::ScrollEvent| {
OverlayEvent::KeyboardToolbarPanelScroll(f32::from(
ev.delta.pixel_delta(px(20.0)).y,
))
}))
.snapshot("overlay.keyboard_toolbar.panel", Some("root.canvas"))
.child(list)
}
#[allow(clippy::too_many_arguments)]
fn render_action_row<V: OverlayHost>(
&self,
group_id: &'static str,
chunk: &[&ToolbarActionSpec],
top: f32,
inner_w: f32,
tile_w: f32,
row_h: f32,
col_gap: f32,
palette: &Palette,
cx: &mut Context<V>,
) -> ui::Div {
let hover = palette.hover;
let mut row = div()
.absolute()
.left(px(0.0))
.top(px(top))
.w(px(inner_w))
.h(px(row_h))
.flex()
.gap(px(col_gap));
for spec in chunk {
let action = spec.action;
let tile_id = format!("kb-panel-{group_id}-{}", spec.id);
let snap_id = format!("overlay.keyboard_toolbar.panel.{group_id}.{}", spec.id);
let glyph: AnyElement = match action {
KeyboardToolbarAction::Date(kind) => div()
.text_size(px(13.0))
.font_weight(FontWeight::SEMIBOLD)
.text_color(palette.icon)
.child(kind.badge())
.into_any_element(),
KeyboardToolbarAction::Image => image_icon_glyph(palette.icon),
_ if !spec.icon.is_empty() => {
icon(spec.icon, 20.0, palette.icon).into_any_element()
}
_ => div()
.text_size(px(12.0))
.text_color(palette.icon)
.child(spec.name)
.into_any_element(),
};
let tile = div()
.id(SharedString::from(tile_id))
.flex_none()
.w(px(tile_w))
.h(px(row_h))
.flex()
.flex_col()
.items_center()
.gap(px(2.0))
.cursor_pointer()
.on_click(emit(cx, move |_: &ClickEvent| {
OverlayEvent::KeyboardToolbar(action)
}))
.snapshot(
SharedString::from(snap_id),
Some("overlay.keyboard_toolbar.panel"),
)
.snapshot_text(spec.name)
.child(
div()
.w(px(tile_w))
.h(px(KEYBOARD_TOOLBAR_BUTTON))
.rounded(px(6.0))
.bg(palette.background_secondary)
.hover(move |style| style.bg(hover))
.flex()
.items_center()
.justify_center()
.child(glyph),
)
.child(
div()
.w(px(tile_w))
.h(px(12.0))
.overflow_hidden()
.whitespace_nowrap()
.text_size(px(10.0))
.line_height(px(12.0))
.text_color(palette.text_secondary)
.flex()
.justify_center()
.child(spec.name),
);
row = row.child(tile);
}
row
}
#[allow(clippy::too_many_arguments)]
fn render_highlight_row<V: OverlayHost>(
&self,
group_id: &'static str,
is_bg: bool,
chunk: &[HighlightColor],
top: f32,
inner_w: f32,
tile_w: f32,
row_h: f32,
col_gap: f32,
palette: &Palette,
cx: &mut Context<V>,
) -> ui::Div {
let hover = palette.hover;
let mut row = div()
.absolute()
.left(px(0.0))
.top(px(top))
.w(px(inner_w))
.h(px(row_h))
.flex()
.gap(px(col_gap));
for &color in chunk {
let action = if is_bg {
KeyboardToolbarAction::SetBgColor(color)
} else {
KeyboardToolbarAction::SetTextColor(color)
};
let swatch_bg = if is_bg {
color
.bg_css_var()
.and_then(|v| palette.theme.css_color(v))
.unwrap_or(palette.background_secondary)
} else {
palette.background_secondary
};
let swatch_fg = if is_bg {
palette.text_primary
} else {
color
.fg_css_var()
.and_then(|v| palette.theme.css_color(v))
.unwrap_or(palette.text_primary)
};
let tile_id = format!("kb-hl-{group_id}-{}", color.id());
let snap_id = format!("overlay.keyboard_toolbar.panel.{group_id}.{}", color.id());
let tile = div()
.id(SharedString::from(tile_id))
.flex_none()
.w(px(tile_w))
.h(px(row_h))
.flex()
.flex_col()
.items_center()
.gap(px(2.0))
.cursor_pointer()
.on_click(emit(cx, move |_: &ClickEvent| {
OverlayEvent::KeyboardToolbar(action)
}))
.snapshot(
SharedString::from(snap_id),
Some("overlay.keyboard_toolbar.panel"),
)
.snapshot_text(color.label())
.child(
div()
.w(px(tile_w))
.h(px(KEYBOARD_TOOLBAR_BUTTON))
.rounded(px(6.0))
.bg(swatch_bg)
.border_1()
.border_color(palette.border)
.hover(move |style| style.bg(hover))
.flex()
.items_center()
.justify_center()
.text_size(px(16.0))
.font_weight(FontWeight::SEMIBOLD)
.text_color(swatch_fg)
.child("A"),
)
.child(
div()
.w(px(tile_w))
.h(px(12.0))
.overflow_hidden()
.whitespace_nowrap()
.text_size(px(10.0))
.line_height(px(12.0))
.text_color(palette.text_secondary)
.flex()
.justify_center()
.child(color.label()),
);
row = row.child(tile);
}
row
}
}
+45 -25
View File
@@ -1,24 +1,10 @@
//! Screen-space overlays and interactive block controls of the Page view.
//! Screen-space overlays and interactive block controls of the Page view (`Overlays`).
//!
//! [`Overlays`] owns what floats above or reacts inside the page: the slash menu, the
//! formatting toolbar of the text selection, the gutter drag handle with its drop
//! indicator, and the clickable parts of blocks (to-do boxes, toggle and heading chevrons,
//! the code block's copy button and sideways scroll). The text selection itself is the
//! editor's (`editor_session`); the overlays read it.
//!
//! The state machine is data in, commands out: an [`OverlayScene`] and an
//! [`OverlayEvent`] or key go in, [`OverlayEffects`] come out (document edits, clipboard
//! text, a timer to start). It reads no clock: every transition is an [`EaseOut`]
//! evaluated at the scheduler time passed in. The `PlaygroundView` glue at the end of the
//! module feeds it input and carries each edit out through the editor's document session
//! as one undo step.
//!
//! Popovers are placed by the pure [`place_popover`]. Opening popovers mount on frame 1
//! with opacity clamped to at least `0.01` so interactive controls are immediately clickable
//! without triggering `zero-opacity-hit-through`; a popover that is fully closed is not
//! mounted at all, and one that is fading out carries no handlers, so nothing invisible can
//! be clicked.
//! State transitions are pure functions of `OverlayScene` and scheduler time `now_ms`,
//! emitting `OverlayEffects` (single-undo-step `DocEdit`s, clipboard writes, and timers).
//! Popovers mount at `>= 0.01` opacity while opening and drop listeners while fading out.
mod bookmark_prompt;
mod equation;
mod keyboard_toolbar;
mod paint_linked_doc;
@@ -29,14 +15,20 @@ mod state;
mod table_cell;
mod toolbar;
pub use bookmark_prompt::BookmarkPrompt;
pub use equation::{EquationEditor, EquationTarget};
pub use keyboard_toolbar::{
DEFAULT_KEYBOARD_TOOLBAR_ITEMS, HighlightColor, KEYBOARD_TOOL_PANEL_HEIGHT,
KEYBOARD_TOOLBAR_BUTTON, KEYBOARD_TOOLBAR_HEIGHT, KeyboardToolbarAction,
KeyboardToolbarCapabilities, KeyboardToolbarDateKind, KeyboardToolbarLevel,
KeyboardToolbarPanel, KeyboardToolbarState, MORE_TOOL_PANEL_GROUPS, TEXT_SUB_TOOLBAR_ITEMS,
TURN_INTO_PANEL_ITEMS, ToolPanelGroupSpec, ToolbarActionSpec, ToolbarItemSpec,
is_flavour_supported,
};
pub use paint_page::{block_text, bounding_rect, find_parent, shared_alignment};
pub use slash::{
SLASH_ITEMS, SlashCommand, SlashItem, SlashMenu, SlashRow, filter_slash_items, slash_rows,
slash_rows_for_query,
SLASH_ITEMS, SlashCommand, SlashItem, SlashMenu, SlashRow, filter_slash_items,
slash_item_by_id, slash_rows, slash_rows_for_query,
};
pub use state::normalize_url;
pub use table_cell::InlineTableCell;
@@ -384,6 +376,8 @@ pub enum DocEdit {
target: EquationTarget,
latex: String,
},
/// Insert a validated `affine:bookmark` block below `block_id`.
Bookmark { block_id: String, url: String },
}
/// Something that happened to the overlays: input routed by the view, or a call of the
@@ -455,12 +449,33 @@ pub enum OverlayEvent {
},
/// Commit the equation editor's current LaTeX string.
EquationApply,
/// Click inside the multiline equation editor at window coordinates `(x, y)`.
EquationClick {
x: f32,
y: f32,
shift: bool,
},
/// Dismiss the equation editor without committing.
CloseEquationEditor,
/// Open the bookmark URL prompt anchored to `block_id`.
OpenBookmarkPrompt {
block_id: String,
},
/// Commit the bookmark URL prompt (no-op if empty or invalid).
BookmarkApply,
/// Dismiss the bookmark URL prompt without inserting a block.
CloseBookmarkPrompt,
/// Insert a decoded image blob chosen from the host file picker as an `affine:image` block.
InsertImageBytes {
bytes: Vec<u8>,
caption: String,
},
/// Show or hide the mobile bottom keyboard toolbar.
SetKeyboardToolbarVisible(bool),
/// Cycle to the next action page on narrow mobile viewports.
KeyboardToolbarNextPage,
/// Scroll the active mobile keyboard tool panel (`+`, `Turn into`, or `Highlight`) by `delta_y` px.
KeyboardToolbarPanelScroll(f32),
/// Trigger one action button on the mobile bottom keyboard toolbar.
KeyboardToolbar(KeyboardToolbarAction),
/// Focus an `affine:table` cell in place for live `Y.Text` CRDT editing.
@@ -595,9 +610,8 @@ pub struct Overlays {
pub(super) copied_generation: u64,
pub(super) linked_doc: Option<LinkedDocMenuState>,
pub(super) equation: Option<EquationEditor>,
pub(super) keyboard_toolbar_visible: bool,
pub(super) keyboard_toolbar_page: usize,
pub(super) keyboard_toolbar_marks_disabled: bool,
pub(super) bookmark: Option<BookmarkPrompt>,
pub(super) keyboard_toolbar: KeyboardToolbarState,
pub format_cache: Option<FormatCache>,
}
@@ -660,10 +674,11 @@ impl Overlays {
self.open_toolbar_mut()?.link.as_mut()
}
/// Whichever single-line overlay text field currently owns text input (equation editor or link field).
/// Whichever overlay text field currently owns text input (equation, bookmark, or link).
pub fn active_text_field(&self) -> Option<&LinkBar> {
self.equation_editor()
.map(|editor| &editor.input)
.or_else(|| self.bookmark_prompt().map(|prompt| &prompt.input))
.or_else(|| self.link_field())
}
@@ -671,6 +686,9 @@ impl Overlays {
if self.equation_editor().is_some() {
return self.equation_editor_mut().map(|editor| &mut editor.input);
}
if self.bookmark_prompt().is_some() {
return self.bookmark_prompt_mut().map(|prompt| &mut prompt.input);
}
self.link_field_mut()
}
@@ -762,6 +780,8 @@ impl Overlays {
self.chevrons.clear();
self.linked_doc = None;
self.equation = None;
self.bookmark = None;
self.keyboard_toolbar.close_transient();
self.format_cache = None;
}
}
@@ -0,0 +1,316 @@
//! Pure geometry, hit-testing, and block-tree helpers for Page-layer overlays.
use std::collections::HashMap;
use blocksuite_playground_doc::{
read::{BlockContent, BlockNode, RichText, TextAlign as BlockAlign},
schema::ParagraphType,
};
use ui::{App, Context, Div, Hsla, Window, canvas, div, point, prelude::*, px, size};
use crate::{
TOPBAR_HEIGHT,
block_flow::{FlowBlock, FlowKind, FlowLayout, FlowRect},
theme::IconPaint,
};
use super::{
CONTROL_HIT_SIZE, DRAG_HANDLE_MIN_X, DRAG_HANDLE_SIZE, DropSlot, HOVER_SLACK, OverlayEvent,
OverlayHost, OverlayScene,
};
/// Hit target of a block's gutter handle in world space, `None` where the gutter has no
/// room for it. The handle hangs left of the block on its first line; a heading keeps the
/// place next to its text for its collapse chevron, so its handle sits one step further
/// out and is left away where the gutter is too narrow for both.
pub(crate) fn drag_handle_rect(
block: &FlowBlock,
column_x: f32,
window_width: f32,
direction: ui::Direction,
) -> Option<FlowRect> {
let body = &block.body;
if body.kind == FlowKind::Title {
return None;
}
let center_y = match &body.text {
Some(text) if body.kind != FlowKind::Code => text.y + text.layout.line_height() / 2.0,
_ => (body.height / 2.0).min(18.0),
};
let heading = is_heading(body.kind);
let handle_x = match direction {
ui::Direction::Ltr => {
let wanted = block.x - DRAG_HANDLE_SIZE - if heading { CONTROL_HIT_SIZE } else { 0.0 };
// `DRAG_HANDLE_MIN_X` is a screen coordinate; the world starts at `column_x`.
let min_x = DRAG_HANDLE_MIN_X - column_x;
if heading && wanted < min_x {
return None;
}
wanted.max(min_x)
}
ui::Direction::Rtl => {
let wanted = block.rect().right() + if heading { CONTROL_HIT_SIZE } else { 0.0 };
let max_x = window_width - DRAG_HANDLE_MIN_X - column_x - DRAG_HANDLE_SIZE;
if heading && wanted > max_x {
return None;
}
wanted.min(max_x)
}
};
Some(FlowRect::new(
handle_x,
(block.y + center_y - DRAG_HANDLE_SIZE / 2.0).round(),
DRAG_HANDLE_SIZE,
DRAG_HANDLE_SIZE,
))
}
/// An absolutely positioned box at `rect`.
pub(crate) fn place(rect: FlowRect) -> Div {
div()
.absolute()
.left(px(rect.x))
.top(px(rect.y))
.w(px(rect.w))
.h(px(rect.h))
}
/// A generated icon as a fixed-size element.
pub(crate) fn icon(name: &'static str, side: f32, color: Hsla) -> impl IntoElement {
let icon = IconPaint::named(name);
canvas(
|_, _, _| (),
move |bounds, _, window, cx| icon.paint(bounds, color, window, cx),
)
.flex_none()
.w(px(side))
.h(px(side))
}
/// Text alignment glyph: four bars, the short ones on the side the text aligns to.
pub(crate) fn align_glyph(align: BlockAlign, color: Hsla) -> impl IntoElement {
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
const LONG: f32 = 14.0;
const SHORT: f32 = 8.0;
for (index, width) in [LONG, SHORT, LONG, SHORT].into_iter().enumerate() {
let x = 3.0
+ match align {
BlockAlign::Left => 0.0,
BlockAlign::Center => (LONG - width) / 2.0,
BlockAlign::Right => LONG - width,
};
let bar = ui::Bounds::new(
point(
bounds.origin.x + px(x),
bounds.origin.y + px(3.5 + index as f32 * 4.0),
),
size(px(width), px(1.5)),
);
window.paint_quad(ui::fill(bar, color).corner_radii(px(0.75)));
}
},
)
.flex_none()
.w(px(20.0))
.h(px(20.0))
}
/// A listener that turns an input event into an [`OverlayEvent`] for the view.
pub(crate) fn emit<V: OverlayHost, E: 'static>(
cx: &Context<V>,
event: impl Fn(&E) -> OverlayEvent + 'static,
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
cx.listener(move |view: &mut V, input: &E, window, cx| {
view.dispatch_overlay(event(input), window, cx);
})
}
/// The alignment the blocks `ids` under `node` share: `Some(None)` once two of them
/// differ. A block that sets none takes its nearest aligned ancestor's, like the renderer.
pub fn shared_alignment(
node: &BlockNode,
inherited: BlockAlign,
ids: &[&str],
shared: &mut Option<Option<BlockAlign>>,
) {
let own = match &node.content {
BlockContent::Paragraph { text_align, .. } | BlockContent::List { text_align, .. } => {
text_align.unwrap_or(inherited)
}
_ => inherited,
};
if ids.contains(&node.id.as_str()) {
*shared = Some(match *shared {
None => Some(own),
Some(all) => all.filter(|all| *all == own),
});
}
for child in &node.children {
shared_alignment(child, own, ids, shared);
}
}
pub(crate) fn is_heading(kind: FlowKind) -> bool {
matches!(
kind,
FlowKind::Paragraph(
ParagraphType::H1
| ParagraphType::H2
| ParagraphType::H3
| ParagraphType::H4
| ParagraphType::H5
| ParagraphType::H6
)
)
}
/// Parent of block `id` and the block's index among the parent's children.
pub fn find_parent<'a>(node: &'a BlockNode, id: &str) -> Option<(&'a BlockNode, usize)> {
if let Some(index) = node.children.iter().position(|child| child.id == id) {
return Some((node, index));
}
node.children
.iter()
.find_map(|child| find_parent(child, id))
}
pub fn block_text(node: &BlockNode) -> Option<&RichText> {
match &node.content {
BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => Some(text),
_ => None,
}
}
pub(crate) fn text_len(scene: &OverlayScene<'_>, block_id: &str) -> usize {
scene
.snapshot
.block(block_id)
.and_then(block_text)
.map_or(0, |text| text.plain.encode_utf16().count())
}
/// The block whose row the pointer is on, if any. The title is not a block of the flow.
pub(crate) fn hover_block(scene: &OverlayScene<'_>, x: f32, y: f32) -> Option<String> {
if y < TOPBAR_HEIGHT || x < 0.0 || x >= scene.window.0 {
return None;
}
let (_, world_y) = scene.screen_to_world(x, y);
let mut best: Option<(f32, &FlowBlock)> = None;
for block in &scene.layout.blocks {
if block.body.kind == FlowKind::Title {
continue;
}
let rect = block.rect();
let distance = if world_y < rect.y {
rect.y - world_y
} else if world_y >= rect.bottom() {
world_y - rect.bottom()
} else {
0.0
};
if distance <= HOVER_SLACK && best.is_none_or(|(nearest, _)| distance < nearest) {
best = Some((distance, block));
}
}
best.map(|(_, block)| block.block_id.clone())
}
/// World-space caret box of a UTF-16 offset in a block; the block's top-left corner for a
/// block without text.
pub(crate) fn caret_world_rect(
layout: &FlowLayout,
block_id: &str,
utf16_offset: usize,
) -> Option<FlowRect> {
let block = layout.block(block_id)?;
Some(match &block.body.text {
Some(text) => {
let (x, line) = text.layout.caret(utf16_offset);
let line_height = text.layout.line_height();
FlowRect::new(
block.x + text.x + x,
block.y + text.y + line as f32 * line_height,
1.0,
line_height,
)
}
None => FlowRect::new(block.x, block.y, 1.0, block.body.height.min(24.0)),
})
}
pub fn bounding_rect(rects: &[FlowRect]) -> Option<FlowRect> {
let first = rects.first()?;
let (mut left, mut top, mut right, mut bottom) =
(first.x, first.y, first.right(), first.bottom());
for rect in &rects[1..] {
left = left.min(rect.x);
top = top.min(rect.y);
right = right.max(rect.right());
bottom = bottom.max(rect.bottom());
}
Some(FlowRect::new(left, top, right - left, bottom - top))
}
/// The nearest slot among the dragged block's siblings for a pointer at `world_y`.
pub(crate) fn drop_slot(
scene: &OverlayScene<'_>,
block_id: &str,
world_y: f32,
) -> Option<DropSlot> {
let root = scene.snapshot.root.as_ref()?;
let (parent, old_index) = find_parent(root, block_id)?;
let blocks = &scene.layout.blocks;
let laid_out: HashMap<&str, usize> = blocks
.iter()
.enumerate()
.map(|(at, block)| (block.block_id.as_str(), at))
.collect();
let siblings: Vec<(usize, usize)> = parent
.children
.iter()
.enumerate()
.filter_map(|(raw, child)| laid_out.get(child.id.as_str()).map(|at| (raw, *at)))
.collect();
let &(_, first_at) = siblings.first()?;
let &(last_raw, last_at) = siblings.last()?;
let x = blocks[first_at].x;
let sibling_width = blocks[first_at].body.width;
let mut candidates: Vec<(usize, f32)> = siblings
.iter()
.map(|&(raw, at)| {
let top = blocks[at].y;
let above = match at.checked_sub(1) {
Some(previous) => blocks[previous].rect().bottom(),
None => top,
};
(raw, ((above + top) / 2.0).round())
})
.collect();
let mut end = last_at;
while end + 1 < blocks.len()
&& match scene.direction {
ui::Direction::Ltr => blocks[end + 1].x > blocks[last_at].x,
ui::Direction::Rtl => blocks[end + 1].rect().right() < blocks[last_at].rect().right(),
}
{
end += 1;
}
let bottom = blocks[end].rect().bottom();
let below = blocks.get(end + 1).map_or(bottom + 10.0, |block| block.y);
candidates.push((last_raw + 1, ((bottom + below) / 2.0).round()));
let (insert_index, indicator_world_y) = candidates
.into_iter()
.min_by(|a, b| (a.1 - world_y).abs().total_cmp(&(b.1 - world_y).abs()))?;
Some(DropSlot {
parent_id: parent.id.clone(),
insert_index,
old_index,
indicator_world_y,
indicator_world_x: x,
indicator_world_width: sibling_width,
})
}
@@ -1,22 +1,24 @@
use std::collections::HashMap;
mod geometry;
use blocksuite_playground_doc::{
read::{BlockContent, BlockNode, RichText, TextAlign as BlockAlign},
schema::{ListType, ParagraphType},
pub(super) use geometry::{
align_glyph, caret_world_rect, drag_handle_rect, drop_slot, emit, hover_block, icon,
is_heading, place, text_len,
};
pub use geometry::{block_text, bounding_rect, find_parent, shared_alignment};
use blocksuite_playground_doc::{read::BlockContent, schema::ListType};
use ui::{
AnyElement, App, ClickEvent, Context, Div, FontWeight, Hsla, MouseButton, MouseDownEvent,
SharedString, Window, canvas, div, point, prelude::*, px, size,
AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, SharedString, Window,
canvas, div, point, prelude::*, px, size,
};
use crate::{
TOPBAR_HEIGHT,
block_flow::{
CODE_RADIUS, FlowBlock, FlowKind, FlowLayout, FlowRect, PAGE_SURFACE_ID, PagePaint,
CODE_RADIUS, FlowKind, FlowRect, PAGE_SURFACE_ID, PagePaint,
heading_marker_rect_for_direction, paint_chevron, paragraph_spec,
},
rich_text::DecorationKind,
theme::{IconPaint, Palette, TYPOGRAPHY},
theme::{Palette, TYPOGRAPHY},
};
use super::*;
@@ -249,11 +251,17 @@ impl Overlays {
},
initial,
};
let element = place(viewport.to_local(&rect))
let hover_bg = palette.hover;
let mut element = place(viewport.to_local(&rect))
.id(SharedString::from(format!("latex-{}", block.block_id)))
.rounded(px(4.0))
.cursor_pointer()
.hover(move |style| style.bg(hover_bg))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(emit(cx, move |_: &ClickEvent| event.clone()));
if hovered {
element = element.bg(hover_bg);
}
elements.push(element.into_any_element());
}
FlowKind::Table => {
@@ -263,8 +271,17 @@ impl Overlays {
BlockContent::Table(t) => Some(&t.cells),
_ => None,
});
let table_scroll_x = self.code_scroll_x(&block.block_id);
let vis_left = rect.x;
let vis_right = rect.right();
for cell in &block.body.table_cells {
let target = cell.rect.translated(rect.x, rect.y);
let raw_target = cell.rect.translated(rect.x - table_scroll_x, rect.y);
let left = raw_target.x.max(vis_left);
let right = raw_target.right().min(vis_right);
if right <= left {
continue;
}
let target = FlowRect::new(left, raw_target.y, right - left, raw_target.h);
if !viewport.intersects(&target) {
continue;
}
@@ -496,303 +513,3 @@ impl Overlays {
(paint, elements)
}
}
/// Hit target of a block's gutter handle in world space, `None` where the gutter has no
/// room for it. The handle hangs left of the block on its first line; a heading keeps the
/// place next to its text for its collapse chevron, so its handle sits one step further
/// out and is left away where the gutter is too narrow for both.
pub(super) fn drag_handle_rect(
block: &FlowBlock,
column_x: f32,
window_width: f32,
direction: ui::Direction,
) -> Option<FlowRect> {
let body = &block.body;
if body.kind == FlowKind::Title {
return None;
}
let center_y = match &body.text {
Some(text) if body.kind != FlowKind::Code => text.y + text.layout.line_height() / 2.0,
_ => (body.height / 2.0).min(18.0),
};
let heading = is_heading(body.kind);
let handle_x = match direction {
ui::Direction::Ltr => {
let wanted = block.x - DRAG_HANDLE_SIZE - if heading { CONTROL_HIT_SIZE } else { 0.0 };
// `DRAG_HANDLE_MIN_X` is a screen coordinate; the world starts at `column_x`.
let min_x = DRAG_HANDLE_MIN_X - column_x;
if heading && wanted < min_x {
return None;
}
wanted.max(min_x)
}
ui::Direction::Rtl => {
let wanted = block.rect().right() + if heading { CONTROL_HIT_SIZE } else { 0.0 };
let max_x = window_width - DRAG_HANDLE_MIN_X - column_x - DRAG_HANDLE_SIZE;
if heading && wanted > max_x {
return None;
}
wanted.min(max_x)
}
};
Some(FlowRect::new(
handle_x,
(block.y + center_y - DRAG_HANDLE_SIZE / 2.0).round(),
DRAG_HANDLE_SIZE,
DRAG_HANDLE_SIZE,
))
}
/// An absolutely positioned box at `rect`.
pub(super) fn place(rect: FlowRect) -> Div {
div()
.absolute()
.left(px(rect.x))
.top(px(rect.y))
.w(px(rect.w))
.h(px(rect.h))
}
/// A generated icon as a fixed-size element.
pub(super) fn icon(name: &'static str, side: f32, color: Hsla) -> impl IntoElement {
let icon = IconPaint::named(name);
canvas(
|_, _, _| (),
move |bounds, _, window, cx| icon.paint(bounds, color, window, cx),
)
.flex_none()
.w(px(side))
.h(px(side))
}
/// Text alignment glyph: four bars, the short ones on the side the text aligns to.
pub(super) fn align_glyph(align: BlockAlign, color: Hsla) -> impl IntoElement {
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
const LONG: f32 = 14.0;
const SHORT: f32 = 8.0;
for (index, width) in [LONG, SHORT, LONG, SHORT].into_iter().enumerate() {
let x = 3.0
+ match align {
BlockAlign::Left => 0.0,
BlockAlign::Center => (LONG - width) / 2.0,
BlockAlign::Right => LONG - width,
};
let bar = ui::Bounds::new(
point(
bounds.origin.x + px(x),
bounds.origin.y + px(3.5 + index as f32 * 4.0),
),
size(px(width), px(1.5)),
);
window.paint_quad(ui::fill(bar, color).corner_radii(px(0.75)));
}
},
)
.flex_none()
.w(px(20.0))
.h(px(20.0))
}
/// A listener that turns an input event into an [`OverlayEvent`] for the view.
pub(super) fn emit<V: OverlayHost, E: 'static>(
cx: &Context<V>,
event: impl Fn(&E) -> OverlayEvent + 'static,
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
cx.listener(move |view: &mut V, input: &E, window, cx| {
view.dispatch_overlay(event(input), window, cx);
})
}
/// The alignment the blocks `ids` under `node` share: `Some(None)` once two of them
/// differ. A block that sets none takes its nearest aligned ancestor's, like the renderer.
pub fn shared_alignment(
node: &BlockNode,
inherited: BlockAlign,
ids: &[&str],
shared: &mut Option<Option<BlockAlign>>,
) {
let own = match &node.content {
BlockContent::Paragraph { text_align, .. } | BlockContent::List { text_align, .. } => {
text_align.unwrap_or(inherited)
}
_ => inherited,
};
if ids.contains(&node.id.as_str()) {
*shared = Some(match *shared {
None => Some(own),
Some(all) => all.filter(|all| *all == own),
});
}
for child in &node.children {
shared_alignment(child, own, ids, shared);
}
}
pub(super) fn is_heading(kind: FlowKind) -> bool {
matches!(
kind,
FlowKind::Paragraph(
ParagraphType::H1
| ParagraphType::H2
| ParagraphType::H3
| ParagraphType::H4
| ParagraphType::H5
| ParagraphType::H6
)
)
}
/// Parent of block `id` and the block's index among the parent's children.
pub fn find_parent<'a>(node: &'a BlockNode, id: &str) -> Option<(&'a BlockNode, usize)> {
if let Some(index) = node.children.iter().position(|child| child.id == id) {
return Some((node, index));
}
node.children
.iter()
.find_map(|child| find_parent(child, id))
}
pub fn block_text(node: &BlockNode) -> Option<&RichText> {
match &node.content {
BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => Some(text),
_ => None,
}
}
pub(super) fn text_len(scene: &OverlayScene<'_>, block_id: &str) -> usize {
scene
.snapshot
.block(block_id)
.and_then(block_text)
.map_or(0, |text| text.plain.encode_utf16().count())
}
/// The block whose row the pointer is on, if any. The title is not a block of the flow.
pub(super) fn hover_block(scene: &OverlayScene<'_>, x: f32, y: f32) -> Option<String> {
if y < TOPBAR_HEIGHT || x < 0.0 || x >= scene.window.0 {
return None;
}
let (_, world_y) = scene.screen_to_world(x, y);
let mut best: Option<(f32, &FlowBlock)> = None;
for block in &scene.layout.blocks {
if block.body.kind == FlowKind::Title {
continue;
}
let rect = block.rect();
let distance = if world_y < rect.y {
rect.y - world_y
} else if world_y >= rect.bottom() {
world_y - rect.bottom()
} else {
0.0
};
if distance <= HOVER_SLACK && best.is_none_or(|(nearest, _)| distance < nearest) {
best = Some((distance, block));
}
}
best.map(|(_, block)| block.block_id.clone())
}
/// World-space caret box of a UTF-16 offset in a block; the block's top-left corner for a
/// block without text.
pub(super) fn caret_world_rect(
layout: &FlowLayout,
block_id: &str,
utf16_offset: usize,
) -> Option<FlowRect> {
let block = layout.block(block_id)?;
Some(match &block.body.text {
Some(text) => {
let (x, line) = text.layout.caret(utf16_offset);
let line_height = text.layout.line_height();
FlowRect::new(
block.x + text.x + x,
block.y + text.y + line as f32 * line_height,
1.0,
line_height,
)
}
None => FlowRect::new(block.x, block.y, 1.0, block.body.height.min(24.0)),
})
}
pub fn bounding_rect(rects: &[FlowRect]) -> Option<FlowRect> {
let first = rects.first()?;
let (mut left, mut top, mut right, mut bottom) =
(first.x, first.y, first.right(), first.bottom());
for rect in &rects[1..] {
left = left.min(rect.x);
top = top.min(rect.y);
right = right.max(rect.right());
bottom = bottom.max(rect.bottom());
}
Some(FlowRect::new(left, top, right - left, bottom - top))
}
/// The nearest slot among the dragged block's siblings for a pointer at `world_y`.
pub(super) fn drop_slot(
scene: &OverlayScene<'_>,
block_id: &str,
world_y: f32,
) -> Option<DropSlot> {
let root = scene.snapshot.root.as_ref()?;
let (parent, old_index) = find_parent(root, block_id)?;
let blocks = &scene.layout.blocks;
// One pass over the layout, so a parent with thousands of children is no slower to
// drag in than a short one.
let laid_out: HashMap<&str, usize> = blocks
.iter()
.enumerate()
.map(|(at, block)| (block.block_id.as_str(), at))
.collect();
// Siblings that are laid out, as (index among the parent's children, index in layout).
let siblings: Vec<(usize, usize)> = parent
.children
.iter()
.enumerate()
.filter_map(|(raw, child)| laid_out.get(child.id.as_str()).map(|at| (raw, *at)))
.collect();
let &(_, first_at) = siblings.first()?;
let &(last_raw, last_at) = siblings.last()?;
let x = blocks[first_at].x;
let sibling_width = blocks[first_at].body.width;
let mut candidates: Vec<(usize, f32)> = siblings
.iter()
.map(|&(raw, at)| {
let top = blocks[at].y;
let above = match at.checked_sub(1) {
Some(previous) => blocks[previous].rect().bottom(),
None => top,
};
(raw, ((above + top) / 2.0).round())
})
.collect();
// Below the last sibling and everything nested under it (compare logical indent edge).
let mut end = last_at;
while end + 1 < blocks.len()
&& match scene.direction {
ui::Direction::Ltr => blocks[end + 1].x > blocks[last_at].x,
ui::Direction::Rtl => blocks[end + 1].rect().right() < blocks[last_at].rect().right(),
}
{
end += 1;
}
let bottom = blocks[end].rect().bottom();
let below = blocks.get(end + 1).map_or(bottom + 10.0, |block| block.y);
candidates.push((last_raw + 1, ((bottom + below) / 2.0).round()));
let (insert_index, indicator_world_y) = candidates
.into_iter()
.min_by(|a, b| (a.1 - world_y).abs().total_cmp(&(b.1 - world_y).abs()))?;
Some(DropSlot {
parent_id: parent.id.clone(),
insert_index,
old_index,
indicator_world_y,
indicator_world_x: x,
indicator_world_width: sibling_width,
})
}
@@ -27,6 +27,7 @@ impl Overlays {
elements.extend(self.render_slash(scene, palette, now_ms, cx));
elements.extend(self.render_linked_doc(scene, palette, now_ms, cx));
elements.extend(self.render_equation(scene, palette, now_ms, window, cx));
elements.extend(self.render_bookmark(scene, palette, now_ms, window, cx));
elements.extend(self.render_keyboard_toolbar(scene, palette, cx));
elements
}
@@ -229,6 +229,11 @@ pub const SLASH_ITEMS: [SlashItem; 16] = [
),
];
/// Look up a built-in slash item by its stable `id` (shared by `KeyboardToolbar`).
pub fn slash_item_by_id(id: &str) -> Option<&'static SlashItem> {
SLASH_ITEMS.iter().find(|item| item.id == id)
}
fn is_fuzzy_match(haystack: &str, needle: &str) -> bool {
let mut chars = needle.chars();
let Some(mut target) = chars.next() else {
+74 -12
View File
@@ -101,6 +101,7 @@ impl Overlays {
self.close_linked_doc(now_ms);
self.close_link_field();
self.close_equation_editor_at(now_ms);
self.close_bookmark_prompt_at(now_ms);
self.drag = None;
}
@@ -250,6 +251,7 @@ impl Overlays {
self.linked_doc_menu().and_then(|menu| menu.rect),
self.open_toolbar().and_then(|toolbar| toolbar.rect),
self.equation_editor().and_then(|editor| editor.rect),
self.bookmark_prompt().and_then(|prompt| prompt.rect),
]
.into_iter()
.flatten()
@@ -411,15 +413,39 @@ impl Overlays {
effects.redraw = true;
}
OverlayEvent::EquationApply => self.apply_equation(now_ms, &mut effects),
OverlayEvent::EquationClick { x, y, shift } => {
if let Some(editor) = self.equation_editor_mut()
&& editor.click_at(x, y, shift)
{
effects.redraw = true;
}
}
OverlayEvent::CloseEquationEditor => {
if self.close_equation_editor_at(now_ms) {
effects.redraw = true;
}
}
OverlayEvent::OpenBookmarkPrompt { block_id } => {
self.open_bookmark_prompt(block_id.clone(), now_ms);
effects.redraw = true;
}
OverlayEvent::BookmarkApply => self.apply_bookmark(now_ms, &mut effects),
OverlayEvent::CloseBookmarkPrompt => {
if self.close_bookmark_prompt_at(now_ms) {
effects.redraw = true;
}
}
OverlayEvent::KeyboardToolbarNextPage => {
self.next_keyboard_toolbar_page();
effects.redraw = true;
}
OverlayEvent::KeyboardToolbarPanelScroll(delta_y) => {
if let Some(s) = scene
&& self.scroll_active_keyboard_tool_panel(s, delta_y)
{
effects.redraw = true;
}
}
OverlayEvent::OpenLinkedDocMenu { .. }
| OverlayEvent::SetLinkedDocQuery(_)
| OverlayEvent::LinkedDocHover(_)
@@ -428,6 +454,7 @@ impl Overlays {
| OverlayEvent::CreateLinkedDoc { .. }
| OverlayEvent::SetKeyboardToolbarVisible(_)
| OverlayEvent::KeyboardToolbar(_)
| OverlayEvent::InsertImageBytes { .. }
| OverlayEvent::FocusTableCell { .. }
| OverlayEvent::AttachmentPdfPage { .. }
| OverlayEvent::OpenEmbedDoc { .. }
@@ -450,14 +477,22 @@ impl Overlays {
let key = keystroke.key.as_str();
let shift = keystroke.modifiers.shift;
#[derive(Clone, Copy, PartialEq, Eq)]
enum ActiveFieldKind {
Equation,
Bookmark,
Link,
}
let active_kind = if self.equation_editor().is_some() {
Some(true)
Some(ActiveFieldKind::Equation)
} else if self.bookmark_prompt().is_some() {
Some(ActiveFieldKind::Bookmark)
} else if self.link_field().is_some() {
Some(false)
Some(ActiveFieldKind::Link)
} else {
None
};
if let Some(is_equation) = active_kind {
if let Some(field_kind) = active_kind {
if self.active_text_field().is_some_and(LinkBar::composing) {
if key == "escape"
&& let Some(field) = self.active_text_field_mut()
@@ -471,20 +506,35 @@ impl Overlays {
effects.handled = true;
effects.redraw = true;
match key {
"enter" => {
if is_equation {
self.apply_equation(now_ms, &mut effects);
} else {
self.apply_link(false, &mut effects);
"enter" => match field_kind {
ActiveFieldKind::Equation => {
if shift {
if let Some(field) = self.active_text_field_mut() {
field.replace(None, "\n");
}
} else {
self.apply_equation(now_ms, &mut effects);
}
}
ActiveFieldKind::Bookmark => self.apply_bookmark(now_ms, &mut effects),
ActiveFieldKind::Link => self.apply_link(false, &mut effects),
},
"up" | "down" if field_kind == ActiveFieldKind::Equation && !secondary => {
if let Some(editor) = self.equation_editor_mut() {
editor.move_vertical_line(key == "down", shift);
}
}
"escape" => {
if is_equation {
"escape" => match field_kind {
ActiveFieldKind::Equation => {
self.close_equation_editor_at(now_ms);
} else {
}
ActiveFieldKind::Bookmark => {
self.close_bookmark_prompt_at(now_ms);
}
ActiveFieldKind::Link => {
self.close_link_field();
}
}
},
"v" if secondary => effects.paste = true,
"c" | "x" if secondary => {
if let Some(field) = self.active_text_field_mut()
@@ -627,6 +677,9 @@ impl Overlays {
delta_x: f32,
delta_y: f32,
) -> bool {
if self.scroll_keyboard_tool_panel(scene, x, y, delta_y) {
return true;
}
if delta_x == 0.0 || delta_x.abs() < delta_y.abs() {
return false;
}
@@ -708,6 +761,11 @@ impl Overlays {
}) {
self.equation = None;
}
if self.bookmark.as_ref().is_some_and(|prompt| {
prompt.presence.gone(now_ms) || layout.block(&prompt.block_id).is_none()
}) {
self.bookmark = None;
}
}
pub(super) fn in_flight(&self, now_ms: f64) -> bool {
@@ -727,5 +785,9 @@ impl Overlays {
.equation
.as_ref()
.is_some_and(|editor| editor.presence.in_flight(now_ms) || editor.presence.closing)
|| self
.bookmark
.as_ref()
.is_some_and(|prompt| prompt.presence.in_flight(now_ms) || prompt.presence.closing)
}
}
@@ -265,20 +265,45 @@ impl ParagraphLayout<'_> {
};
let is_code = !first.chip && first.marks.code;
let is_latex = first.chip && first.marks.latex.is_some();
let font_size = if is_code || is_latex {
let math_result = if is_latex {
first.marks.latex.as_deref().map(|tex| {
if tex.trim().is_empty() {
crate::block_flow::MathRenderResult::Pending
} else {
crate::block_flow::render_math_cached(
tex,
false,
style.font_size * 0.92,
style.text_color,
style.dpr,
)
}
})
} else {
None
};
let is_latex_error = matches!(
math_result,
Some(crate::block_flow::MathRenderResult::Error)
);
let font_size = if is_code {
style.code_font_size
} else if is_latex {
12.0
} else {
style.font_size
};
let display_text: std::borrow::Cow<'_, str> = if is_latex {
first
.marks
.latex
.as_deref()
.map(|tex| {
std::borrow::Cow::Owned(crate::block_flow::format_inline_math_unicode(tex))
})
.unwrap_or(std::borrow::Cow::Borrowed(text))
if is_latex_error {
std::borrow::Cow::Borrowed("Error equation")
} else {
let raw_tex = first.marks.latex.as_deref().unwrap_or("").trim();
if raw_tex.is_empty() {
std::borrow::Cow::Borrowed("Equation")
} else {
std::borrow::Cow::Borrowed(text)
}
}
} else {
std::borrow::Cow::Borrowed(text)
};
@@ -291,17 +316,32 @@ impl ParagraphLayout<'_> {
&style.font_family
});
// CSS `bolder`: regular and medium text step to 700, heavier text to 900.
font.weight = if !s.marks.bold {
font.weight = if is_latex {
FontWeight::MEDIUM
} else if !s.marks.bold {
style.base_weight
} else if style.base_weight.0 <= 500.0 {
FontWeight::BOLD
} else {
FontWeight::BLACK
};
if s.marks.italic {
if s.marks.italic && !is_latex {
font.style = FontStyle::Italic;
}
let color = span_color(style, s);
let color = if is_latex_error {
style
.theme
.css_var("--affine-v2-text-highlight-fg-red")
.or_else(|| style.theme.css_var("--affine-error-color"))
.unwrap_or(style.text_color)
} else if is_latex {
style
.theme
.css_var("--affine-text-secondary-color")
.unwrap_or(style.text_color)
} else {
span_color(style, s)
};
let len = if s.chip {
display_text.len()
} else {
@@ -323,26 +363,19 @@ impl ParagraphLayout<'_> {
);
let (inset_start, inset_end) = if first.chip && first.marks.reference.is_some() {
(px(font_size + 4.), px(2.))
} else if is_code || is_latex {
} else if is_code {
let inset = px(style.code_padding_x + style.code_border_width);
(inset, inset)
} else {
(Pixels::ZERO, Pixels::ZERO)
};
let math = if is_latex {
first.marks.latex.as_deref().and_then(|tex| {
let slot = crate::block_flow::render_math_cached(
tex,
false,
style.font_size * 0.92,
style.text_color,
)?;
let math = match math_result {
Some(crate::block_flow::MathRenderResult::Ready(slot)) => {
let h = (slot.ascent_pt + slot.descent_pt).max(12.0);
let w = slot.width_pt.max(8.0);
Some((slot.image, size(px(w), px(h)), px(slot.ascent_pt)))
})
} else {
None
}
_ => None,
};
Some(StyledFragment {
spans: group,
@@ -477,14 +510,8 @@ impl ParagraphLayout<'_> {
{
decorate(
DecorationKind::LatexChip(latex.clone()),
rect(
baseline_y - px(style.code_baseline),
px(style.code_baseline
+ style.code_descent
+ style.code_padding_bottom
+ style.code_border_width),
),
style.code_bg,
rect(top, self.line_height),
ui::transparent_black(),
);
} else if span.marks.code {
decorate(
@@ -285,6 +285,8 @@ pub struct RichParagraphStyle {
pub icon_color: Hsla,
pub chip_bg: Hsla,
pub chip_fg: Hsla,
/// Display scale factor used for rasterizing inline math formulas.
pub dpr: f32,
}
impl Default for RichParagraphStyle {
@@ -366,6 +368,7 @@ impl RichParagraphStyle {
icon_color: color(theme.icon),
chip_bg: color(raw_tokens::Rgba::TRANSPARENT),
chip_fg: color(theme.text_primary),
dpr: 2.0,
}
}
}
@@ -29,12 +29,13 @@ impl LaidOutRichParagraph {
DecorationKind::Highlight | DecorationKind::ReferenceChip(_) => {
window.paint_quad(fill(bounds, d.color));
}
DecorationKind::CodePill | DecorationKind::LatexChip(_) => window.paint_quad(
DecorationKind::CodePill => window.paint_quad(
fill(bounds, d.color)
.corner_radii(px(style.code_radius))
.border_widths(px(style.code_border_width))
.border_color(style.code_border),
),
DecorationKind::LatexChip(_) => {}
DecorationKind::PageGlyph => PAGE_ICON
.get_or_init(|| IconPaint::named("LinkedPageIcon"))
.paint(bounds, d.color, window, cx),
@@ -8,6 +8,7 @@ mod rough;
mod shapes;
mod strokes;
pub(crate) use paint::paint_surface_transformed;
pub use paint::{SurfaceLayout, layout_surface, paint_surface, surface_element};
use ui::{Bounds, Pixels, Point, point, px, size};
@@ -654,6 +654,19 @@ pub fn paint_surface(
}
}
/// Paint all visible items of `layout` under an arbitrary world-to-screen `matrix`
/// (shared by `SurfaceRef` frame thumbnails in `BlockFlow`).
pub(crate) fn paint_surface_transformed(
layout: &SurfaceLayout,
matrix: TransformationMatrix,
window: &mut Window,
cx: &mut App,
) {
for item in layout.visible_items() {
item.paint(matrix, false, window, cx);
}
}
impl Item {
fn paint(
&self,
+3 -1
View File
@@ -15,7 +15,6 @@ crate-type = ["cdylib", "rlib"]
[features]
default = []
harness = ["ui/harness", "blocksuite-editor/harness"]
preview-engine = ["blocksuite-editor/preview-engine"]
[[bin]]
name = "native-playground"
@@ -34,6 +33,7 @@ blocksuite-playground-doc = { path = "../doc", default-features = false }
image.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
ui = { path = "../../../packages/ui/ui" }
y-octo = { version = "0.4.0", default-features = false, features = ["session"] }
@@ -43,6 +43,7 @@ ui = { path = "../../../packages/ui/ui", features = ["harness"] }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] }
jiff.workspace = true
tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync", "time"] }
tokio-tungstenite = "0.26"
@@ -64,6 +65,7 @@ web-sys = { workspace = true, features = [
"HtmlCanvasElement",
"Location",
"MessageEvent",
"RequestInit",
"Response",
"UrlSearchParams",
"WebSocket",
@@ -4,6 +4,7 @@ mod fps;
mod probes;
mod render;
mod s3_evidence;
mod s3_evidence_fixtures;
mod states;
use bench::run_bench;
@@ -8,123 +8,16 @@ use playground::{
HOME_PAGE_ID, PlaygroundOptions, PlaygroundTheme,
directory::{EditorDocId, EditorDocMode, EditorDocSummary, InMemoryDocDirectory},
overlays::{ActiveSelection, OverlayEvent},
room_client::DocState,
};
use ui::{EntityInputHandler, audit_frame_snapshot, point, px};
use ui::{EntityInputHandler, point, px};
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use super::{HeadlessSession, element_center, start_headless_session};
/// Builds a valid 2-page PDF 1.4 fixture with distinct vector art and labels on each page.
pub(crate) fn build_two_page_pdf_fixture() -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
let mut offsets = vec![0usize];
let mut push_obj = |body: &str| {
offsets.push(out.len());
let id = offsets.len() - 1;
out.extend_from_slice(format!("{id} 0 obj\n{body}\nendobj\n").as_bytes());
};
push_obj("<< /Type /Catalog /Pages 2 0 R >>");
push_obj("<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>");
push_obj(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 360 220] \
/Resources << /Font << /F1 5 0 R >> >> /Contents 6 0 R >>",
);
push_obj(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 360 220] \
/Resources << /Font << /F1 5 0 R >> >> /Contents 7 0 R >>",
);
push_obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
let p1 = "0.12 0.42 0.88 rg 24 148 312 44 re f \
1 1 1 rg BT /F1 18 Tf 36 164 Td (AFFiNE Mobile Architecture) Tj ET \
0.92 0.95 0.99 rg 24 28 148 102 re f \
0.2 0.25 0.35 rg BT /F1 13 Tf 36 106 Td (Page 1: Overview) Tj ET \
0.2 0.25 0.35 rg BT /F1 11 Tf 36 82 Td (Pure Rust Hayro PDF) Tj ET \
0.12 0.65 0.42 rg 188 28 148 102 re f \
1 1 1 rg BT /F1 13 Tf 202 80 Td (Zero JS Runtime) Tj ET";
push_obj(&format!(
"<< /Length {} >>\nstream\n{p1}\nendstream",
p1.len()
));
let p2 = "0.48 0.22 0.84 rg 24 148 312 44 re f \
1 1 1 rg BT /F1 18 Tf 36 164 Td (Page 2: Performance Budget) Tj ET \
0.96 0.93 1.0 rg 24 28 312 102 re f \
0.2 0.15 0.35 rg BT /F1 13 Tf 36 104 Td (Single-Keystroke Relayout = 1 Block) Tj ET \
0.2 0.15 0.35 rg BT /F1 11 Tf 36 78 Td (10k Blocks Interactive on Mobile) Tj ET";
push_obj(&format!(
"<< /Length {} >>\nstream\n{p2}\nendstream",
p2.len()
));
let xref_pos = out.len();
out.extend_from_slice(format!("xref\n0 {}\n", offsets.len()).as_bytes());
out.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets.iter().skip(1) {
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n",
offsets.len()
)
.as_bytes(),
);
out
}
fn save_session_png(session: &HeadlessSession, path: &Path, label: &str) -> Result<()> {
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {label}: {violations:#?}"
);
let image = session.app.update(|cx| {
session
.window_handle
.update(cx, |_, window, _| window.render_to_image())
})??;
image
.save(path)
.with_context(|| format!("saving {}", path.display()))?;
println!(
"saved {} ({}x{})",
path.display(),
image.width(),
image.height()
);
Ok(())
}
fn new_doc_state(title: &str) -> Result<DocState> {
let mut state = DocState::new("s3-evidence", 77)?;
state.workspace.create_page(HOME_PAGE_ID, title, 1)?;
state
.workspace
.create_page("doc:roadmap", "Mobile Rust Roadmap 2026", 2)?;
state
.workspace
.create_page("doc:synced-spec", "Synced Design Tokens", 3)?;
let page = state.workspace.ensure_page(HOME_PAGE_ID)?;
page.add_block(
"p-root",
BlockSpec::Page {
title: title.into(),
},
None,
None,
1,
)?;
page.add_block("p-surface", BlockSpec::Surface, Some("p-root"), None, 2)?;
page.add_block(
"p-note",
BlockSpec::Note { xywh: None },
Some("p-root"),
None,
3,
)?;
Ok(state)
}
pub(crate) use super::s3_evidence_fixtures::build_two_page_pdf_fixture;
use super::{
element_center,
s3_evidence_fixtures::{new_doc_state, save_session_png},
start_headless_session,
};
pub(super) fn render_s3_evidence(out_dir: &Path) -> Result<()> {
std::fs::create_dir_all(out_dir)?;
@@ -368,27 +261,20 @@ pub(super) fn render_s3_evidence(out_dir: &Path) -> Result<()> {
&out_dir.join("03a-pdf-page-1.png"),
"03a-pdf-page-1",
)?;
if let Ok((nx, ny)) = element_center(&snap_p1, "page.block.b-pdf.pdf_next") {
session.headless_win.simulate_click(point(px(nx), px(ny)));
session.settle(200);
let page_idx = session.view(|v, _| v.attachment_pdf_page_index("b-pdf"))?;
anyhow::ensure!(
page_idx == Some(1),
"expected PDF page index 1, got {page_idx:?}"
);
save_session_png(
&session,
&out_dir.join("03-pdf-attachment-page-2.png"),
"03-pdf-attachment-page-2",
)?;
} else {
// Default build without `preview-engine`: renders honest attachment file card.
save_session_png(
&session,
&out_dir.join("03-pdf-attachment-fallback-card.png"),
"03-pdf-attachment-fallback-card",
)?;
}
let (nx, ny) = element_center(&snap_p1, "page.block.b-pdf.pdf_next")
.context("expected live Hayro PDF page controls on native")?;
session.headless_win.simulate_click(point(px(nx), px(ny)));
session.settle(200);
let page_idx = session.view(|v, _| v.attachment_pdf_page_index("b-pdf"))?;
anyhow::ensure!(
page_idx == Some(1),
"expected PDF page index 1, got {page_idx:?}"
);
save_session_png(
&session,
&out_dir.join("03-pdf-attachment-page-2.png"),
"03-pdf-attachment-page-2",
)?;
}
// 4. Mobile 390x844 narrow viewport: KeyboardToolbar (44x44pt) + @ exact-substring
@@ -0,0 +1,259 @@
//! Shared PDF and workspace document fixtures for `s3_evidence` offscreen rendering.
use std::path::Path;
use anyhow::{Context as _, Result};
use blocksuite_playground_doc::schema::{
BlockSpec, ConnectorEndpointSpec, ParagraphType, SurfaceElementSpec,
};
use playground::{HOME_PAGE_ID, room_client::DocState};
use ui::audit_frame_snapshot;
use super::HeadlessSession;
/// Builds a valid 2-page PDF 1.4 fixture with distinct vector art and labels on each page.
pub(crate) fn build_two_page_pdf_fixture() -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
let mut offsets = vec![0usize];
let mut push_obj = |body: &str| {
offsets.push(out.len());
let id = offsets.len() - 1;
out.extend_from_slice(format!("{id} 0 obj\n{body}\nendobj\n").as_bytes());
};
push_obj("<< /Type /Catalog /Pages 2 0 R >>");
push_obj("<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>");
push_obj(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 360 220] \
/Resources << /Font << /F1 5 0 R >> >> /Contents 6 0 R >>",
);
push_obj(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 360 220] \
/Resources << /Font << /F1 5 0 R >> >> /Contents 7 0 R >>",
);
push_obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
let p1 = "0.12 0.42 0.88 rg 24 148 312 44 re f \
1 1 1 rg BT /F1 18 Tf 36 164 Td (AFFiNE Mobile Architecture) Tj ET \
0.92 0.95 0.99 rg 24 28 148 102 re f \
0.2 0.25 0.35 rg BT /F1 13 Tf 36 106 Td (Page 1: Overview) Tj ET \
0.2 0.25 0.35 rg BT /F1 11 Tf 36 82 Td (Pure Rust Hayro PDF) Tj ET \
0.12 0.65 0.42 rg 188 28 148 102 re f \
1 1 1 rg BT /F1 13 Tf 202 80 Td (Zero JS Runtime) Tj ET";
push_obj(&format!(
"<< /Length {} >>\nstream\n{p1}\nendstream",
p1.len()
));
let p2 = "0.48 0.22 0.84 rg 24 148 312 44 re f \
1 1 1 rg BT /F1 18 Tf 36 164 Td (Page 2: Performance Budget) Tj ET \
0.96 0.93 1.0 rg 24 28 312 102 re f \
0.2 0.15 0.35 rg BT /F1 13 Tf 36 104 Td (Single-Keystroke Relayout = 1 Block) Tj ET \
0.2 0.15 0.35 rg BT /F1 11 Tf 36 78 Td (10k Blocks Interactive on Mobile) Tj ET";
push_obj(&format!(
"<< /Length {} >>\nstream\n{p2}\nendstream",
p2.len()
));
let xref_pos = out.len();
out.extend_from_slice(format!("xref\n0 {}\n", offsets.len()).as_bytes());
out.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets.iter().skip(1) {
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n",
offsets.len()
)
.as_bytes(),
);
out
}
pub(super) fn save_session_png(session: &HeadlessSession, path: &Path, label: &str) -> Result<()> {
let snapshot = session.frame()?;
let violations = audit_frame_snapshot(&snapshot);
anyhow::ensure!(
violations.is_empty(),
"audit violations in {label}: {violations:#?}"
);
let image = session.app.update(|cx| {
session
.window_handle
.update(cx, |_, window, _| window.render_to_image())
})??;
image
.save(path)
.with_context(|| format!("saving {}", path.display()))?;
println!(
"saved {} ({}x{})",
path.display(),
image.width(),
image.height()
);
Ok(())
}
pub(super) fn new_doc_state(title: &str) -> Result<DocState> {
let mut state = DocState::new("s3-evidence", 77)?;
state.workspace.create_page(HOME_PAGE_ID, title, 1)?;
state
.workspace
.create_page("doc:roadmap", "Mobile Rust Roadmap 2026", 2)?;
{
let roadmap = state.workspace.ensure_page("doc:roadmap")?;
roadmap.add_block(
"rm-root",
BlockSpec::Page {
title: "Mobile Rust Roadmap 2026".into(),
},
None,
None,
1,
)?;
roadmap.add_block(
"rm-note",
BlockSpec::Note { xywh: None },
Some("rm-root"),
None,
2,
)?;
roadmap.add_block(
"rm-p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Pure-Rust cross-platform BlockSuite editor targeting iOS, Android, and Web with 1:1 visual parity.".into(),
},
Some("rm-note"),
None,
3,
)?;
}
state
.workspace
.create_page("doc:synced-spec", "Synced Design Tokens", 3)?;
{
let synced = state.workspace.ensure_page("doc:synced-spec")?;
synced.add_block(
"sy-root",
BlockSpec::Page {
title: "Synced Design Tokens".into(),
},
None,
None,
1,
)?;
synced.add_block(
"sy-note",
BlockSpec::Note { xywh: None },
Some("sy-root"),
None,
2,
)?;
synced.add_block(
"sy-p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Semantic tokens are generated from packages/ui/tokens and shared across Light and Dark themes.".into(),
},
Some("sy-note"),
None,
3,
)?;
}
let page = state.workspace.ensure_page(HOME_PAGE_ID)?;
page.add_block(
"p-root",
BlockSpec::Page {
title: title.into(),
},
None,
None,
1,
)?;
page.add_block("p-surface", BlockSpec::Surface, Some("p-root"), None, 2)?;
page.add_block(
"frame-overview",
BlockSpec::Frame {
title: "Architecture Canvas Frame".into(),
xywh: Some("[0,0,660,220]".into()),
presentation_index: None,
},
Some("p-surface"),
None,
3,
)?;
page.add_surface_element(
"p-surface",
"shape-store",
"a0",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[28,56,172,108]".into(),
seed: 11,
filled: true,
text: Some("CRDT Store".into()),
},
4,
)?;
page.add_surface_element(
"p-surface",
"shape-editor",
"a1",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[240,56,176,108]".into(),
seed: 22,
filled: true,
text: Some("BlockFlow GPU".into()),
},
5,
)?;
page.add_surface_element(
"p-surface",
"shape-preview",
"a2",
SurfaceElementSpec::Shape {
shape_type: "ellipse".into(),
xywh: "[456,56,176,108]".into(),
seed: 33,
filled: true,
text: Some("RaTeX + Hayro".into()),
},
6,
)?;
page.add_surface_element(
"p-surface",
"conn-1",
"a3",
SurfaceElementSpec::Connector {
mode: 1,
seed: 44,
source: ConnectorEndpointSpec::element("shape-store", Some([1.0, 0.5])),
target: ConnectorEndpointSpec::element("shape-editor", Some([0.0, 0.5])),
text: None,
label_xywh: None,
},
7,
)?;
page.add_surface_element(
"p-surface",
"conn-2",
"a4",
SurfaceElementSpec::Connector {
mode: 1,
seed: 55,
source: ConnectorEndpointSpec::element("shape-editor", Some([1.0, 0.5])),
target: ConnectorEndpointSpec::element("shape-preview", Some([0.0, 0.5])),
text: None,
label_xywh: None,
},
8,
)?;
page.add_block(
"p-note",
BlockSpec::Note { xywh: None },
Some("p-root"),
None,
9,
)?;
Ok(state)
}
@@ -523,15 +523,22 @@ impl PlaygroundView {
Some((editing_id.to_string(), is_note, sel, focus))
});
let doc_dir: &dyn crate::directory::WorkspaceDocDirectory = self
.custom_doc_directory
.as_deref()
.unwrap_or(&self.default_doc_directory);
let input = edgeless::EdgelessRenderInput {
snapshot: &render_snapshot,
doc_rev: self.doc_rev,
env_rev: self.env_rev,
preview_rev: crate::block_flow::preview_revision(),
preedit_nonce,
theme: self.theme,
palette,
page_titles: &self.page_titles,
images: &self.images,
pdf_previews: Some(&self.pdf_previews),
doc_directory: Some(doc_dir),
viewport_width,
viewport_height,
direction: window.layout_direction(),
@@ -590,6 +597,7 @@ impl ui::Render for PlaygroundView {
self.overlays.set_keyboard_toolbar_marks_disabled(
self.table_cell.is_some() && self.editor.selection.is_none(),
);
self.sync_keyboard_toolbar_state();
window.set_touch_gestures_enabled(true);
for gesture in window.take_touch_gestures() {
if self.mode == PlaygroundMode::Page
@@ -762,4 +762,36 @@ impl PlaygroundView {
w.prevent_default();
cx.stop_propagation();
}
pub(crate) fn open_link_bar_from_toolbar(&mut self, w: &mut Window, cx: &mut Context<Self>) {
self.open_link_bar_shortcut(w, cx);
}
pub(crate) fn copy_toolbar_selection_or_block(&mut self, cx: &mut Context<Self>) {
if let Some(slice) = self.clipboard_slice() {
crate::clipboard::write_slice(&slice, cx);
return;
}
if let Some(id) = self.editor.selection.as_ref().map(|s| &s.focus.block_id)
&& let Some(text) = self.block_text(id)
{
cx.write_to_clipboard(ui::ClipboardItem::new_string(text.to_string()));
}
}
pub(crate) fn insert_toolbar_plain_text(
&mut self,
text: &str,
w: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let Some(sel) = self.editor.selection.clone() else {
return Ok(());
};
self.page_mut()?.stop_capturing()?;
self.editor.last_typing = None;
self.replace_selection(sel, text, w, cx)?;
self.page_mut()?.stop_capturing()?;
Ok(())
}
}
@@ -409,6 +409,11 @@ impl EntityInputHandler for PlaygroundView {
w: &mut Window,
_: &mut Context<Self>,
) -> Option<usize> {
if let Some(editor) = self.overlays.equation_editor()
&& let Some(idx) = editor.hit_test_point(f32::from(p.x), f32::from(p.y))
{
return Some(idx);
}
if let Some(link) = self.overlays.active_text_field() {
let (selection, reversed) = link.shown_selection();
return link
@@ -0,0 +1,410 @@
//! Layout cache, document refresh, and mode/scroll transitions for [`PlaygroundView`].
use std::{
collections::{BTreeMap, BTreeSet},
rc::Rc,
};
use blocksuite_playground_doc::read::BlockContent;
use ui::{Motion, MotionCurve, ScrollEvent, Window, px};
use crate::{
HOME_PAGE_ID, PILL_EDGELESS_X, PILL_PAGE_X, PILL_TRANSITION_MS, PlaygroundMode, PlaygroundView,
SCROLL_LINE,
block_flow::{FlowInput, FlowLayout, ImageSlot, decode_image},
directory,
overlays::InlineTargetEnd,
room_client::RoomCommand,
view_room::BlobFetchState,
};
impl PlaygroundView {
pub(crate) fn capture_reading_anchor(&mut self) {
if self.reading_anchor.is_none() && self.scroll_y > 0.0 {
self.reading_anchor = self.flow_layout().and_then(|layout| {
layout
.blocks
.iter()
.find(|block| block.rect().bottom() > self.scroll_y)
.map(|block| (block.block_id.clone(), block.y - self.scroll_y))
});
}
}
/// Re-read the shown page from the workspace and bring images in line with the blobs.
pub(crate) fn refresh_document(&mut self) {
self.dirty_text = None;
let pages = self.state.workspace.list_pages().ok();
if let Some(ref pages) = pages {
let titles: BTreeMap<String, String> = pages
.iter()
.map(|page| (page.id.clone(), page.title.clone()))
.collect();
if titles != self.page_titles {
self.page_titles = titles;
self.env_rev += 1;
}
self.page_id = pages
.iter()
.find(|page| page.id == HOME_PAGE_ID)
.or(pages.first())
.map(|page| page.id.clone());
} else if self
.page_id
.as_deref()
.is_some_and(|id| self.state.workspace.page(id).is_none())
{
self.page_id = None;
}
self.snapshot = self
.page_id
.as_deref()
.and_then(|id| self.state.workspace.page(id))
.and_then(|page| page.read_page_snapshot().ok())
.filter(|snapshot| snapshot.root.is_some())
.map(Rc::new);
self.doc_rev += 1;
if let Some(pages) = pages
&& self.custom_doc_directory.is_none()
{
use blocksuite_editor::WorkspaceDocDirectory as _;
let mode = match self.mode {
PlaygroundMode::Page => directory::EditorDocMode::Page,
PlaygroundMode::Edgeless => directory::EditorDocMode::Edgeless,
};
let docs = pages.iter().map(|page| directory::EditorDocSummary {
id: directory::EditorDocId::new(&page.id),
title: page.title.clone(),
mode,
updated_at_ms: 0,
});
self.default_doc_directory.retain_and_upsert_docs(docs);
self.cached_page_revisions
.retain(|id, _| pages.iter().any(|p| p.id == *id));
for page in &pages {
let doc_id = directory::EditorDocId::new(&page.id);
let is_active = self.page_id.as_deref() == Some(page.id.as_str());
let cached_preview = self.default_doc_directory.doc_preview(&doc_id);
let has_snapshot = self.default_doc_directory.doc_snapshot(&doc_id).is_some();
let current_rev = (!is_active)
.then(|| self.state.workspace.page(&page.id).map(|s| s.revision()))
.flatten();
// Avoid re-decoding non-active workspace pages on every local keystroke while
// immediately invalidating whenever any local or remote update (including pure
// Yjs deletes that leave the state vector unchanged) bumps `page.revision()`
// or changes the workspace title.
if !is_active
&& has_snapshot
&& cached_preview
.as_ref()
.is_some_and(|p| p.title == page.title)
&& current_rev.is_some()
&& self.cached_page_revisions.get(&page.id).copied() == current_rev
{
continue;
}
let next_snap = if is_active {
self.snapshot.as_deref().cloned()
} else {
self.state
.workspace
.page(&page.id)
.and_then(|s| s.read_page_snapshot().ok())
};
if let Some(snap) = next_snap {
if let Some(rev) = current_rev {
self.cached_page_revisions.insert(page.id.clone(), rev);
}
let snippet = snap
.root
.as_ref()
.map(|root| {
let mut parts = Vec::new();
for node in root.walk() {
let text = match &node.content {
BlockContent::Paragraph { text, .. }
| BlockContent::List { text, .. } => text.plain.trim(),
BlockContent::Callout { text, .. } => text.plain.trim(),
_ => "",
};
if !text.is_empty() {
parts.push(text.to_string());
if parts.len() >= 2 {
break;
}
}
}
parts.join(" ")
})
.unwrap_or_default();
let next_rev = match cached_preview {
Some(prev)
if !is_active
&& prev.title == page.title
&& prev.snippet == snippet =>
{
prev.revision
}
Some(prev) => prev.revision.wrapping_add(1),
None => 1,
};
self.default_doc_directory.upsert_preview(
doc_id.clone(),
directory::EditorDocPreview {
title: page.title.clone(),
snippet,
updated_at_ms: 0,
revision: next_rev,
},
);
self.default_doc_directory
.upsert_snapshot(doc_id, std::sync::Arc::new(snap));
}
}
}
self.edgeless_refresh_label_editor_from_snapshot();
self.sync_table_cell_from_snapshot();
let mut referenced = BTreeSet::new();
let mut pdf_attachments: Vec<(String, String)> = Vec::new();
for node in self
.snapshot
.iter()
.flat_map(|snapshot| snapshot.root.iter())
.flat_map(|root| root.walk())
{
match &node.content {
BlockContent::Image { source_id, .. } if !source_id.is_empty() => {
referenced.insert(source_id.clone());
}
BlockContent::Attachment {
name,
mime_type,
source_id,
embed,
..
} if !source_id.is_empty() => {
referenced.insert(source_id.clone());
if *embed
&& (mime_type.eq_ignore_ascii_case("application/pdf")
|| name.to_ascii_lowercase().ends_with(".pdf"))
{
pdf_attachments.push((node.id.clone(), source_id.clone()));
}
}
_ => {}
}
}
self.refresh_pdf_previews(&pdf_attachments);
// Fetches of blobs the page no longer references stop. An ordinary document
// update never restarts a fetch that is already tracked.
let images = &mut self.images;
self.blob_fetches.retain(|source_id, _| {
let keep = referenced.contains(source_id);
if !keep {
images.remove(source_id);
}
keep
});
for source_id in referenced {
if let Some(bytes) = self.state.blobs.get(&source_id) {
// Decoded once; a blob that is no image stays unavailable.
if !self.images.contains_key(&source_id)
|| self.blob_fetches.remove(&source_id).is_some()
{
let slot = decode_image(bytes).map_or(ImageSlot::Unavailable, ImageSlot::Ready);
self.images.insert(source_id, slot);
self.env_rev += 1;
}
} else if let Some(room) = &self.room
&& !self.blob_fetches.contains_key(&source_id)
{
self.blob_fetches.insert(
source_id.clone(),
BlobFetchState {
in_flight: true,
..BlobFetchState::default()
},
);
room.link.send(RoomCommand::FetchBlob(source_id));
}
}
}
pub(crate) fn target_pill_x(mode: PlaygroundMode) -> f64 {
match mode {
PlaygroundMode::Page => PILL_PAGE_X,
PlaygroundMode::Edgeless => PILL_EDGELESS_X,
}
}
pub(crate) fn indicator_x(&self, now_ms: f64) -> f64 {
match self.pill_motion {
Some(motion) => motion.value_at(now_ms),
None => Self::target_pill_x(self.mode),
}
}
pub(crate) fn set_mode(
&mut self,
target: PlaygroundMode,
window: &mut Window,
cx: &mut ui::Context<Self>,
) {
if self.mode == target {
return;
}
let now_ms = self.now_ms(cx);
let current_x = self.indicator_x(now_ms);
// Commit any pending inline edit (table cell or Edgeless label) cleanly before switching modes.
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
if self.edgeless.authoring.editing_spatial_block().is_some() {
self.edgeless.authoring.inline_edit = None;
self.editor.clear_preedit_state();
self.editor.selection = None;
self.announce_selection(cx);
}
self.edgeless.authoring.reset_transient();
self.mode = target;
self.dirty_text = None;
self.overlays.reset();
self.pill_motion = Some(Motion::new(
current_x,
Self::target_pill_x(target),
MotionCurve::EaseInOutCubic,
now_ms,
PILL_TRANSITION_MS,
));
cx.notify();
}
pub(crate) fn on_scroll(
&mut self,
event: &ScrollEvent,
window: &mut Window,
cx: &mut ui::Context<Self>,
) {
let delta = event.delta.pixel_delta(px(SCROLL_LINE));
// A sideways scroll over an unwrapped code block or wide table scrolls it, not the page.
if let Some((snapshot, layout)) = self.snapshot.clone().zip(self.flow_layout()) {
let scene = self.overlay_scene(&snapshot, &layout, window.layout_direction(), None);
if self.overlays.scroll_code(
&scene,
f32::from(event.position.x),
f32::from(event.position.y),
f32::from(delta.x),
f32::from(delta.y),
) {
cx.notify();
return;
}
}
let delta = f32::from(delta.y);
let target = (self.scroll_y - delta).clamp(0.0, self.max_scroll).round();
if target != self.scroll_y {
self.scroll_y = target;
cx.notify();
}
}
pub(crate) fn ensure_layout(&mut self, width: f32, window: &Window) -> Option<Rc<FlowLayout>> {
use std::hash::{Hash, Hasher};
let snapshot = self.snapshot.clone()?;
let is_rtl = window.layout_direction().is_rtl();
let preview_rev = crate::block_flow::preview_revision();
let equation_draft = self
.overlays
.equation_editor()
.map(|editor| match &editor.target {
crate::overlays::EquationTarget::Block { block_id } => {
crate::block_flow::EquationDraft::Block {
block_id: block_id.clone(),
latex: editor.committed_draft().to_string(),
}
}
crate::overlays::EquationTarget::Inline {
block_id,
utf16_offset,
} => crate::block_flow::EquationDraft::Inline {
block_id: block_id.clone(),
utf16_offset: *utf16_offset,
latex: editor.committed_draft().to_string(),
},
});
let draft_hash = {
let mut h = std::collections::hash_map::DefaultHasher::new();
equation_draft.hash(&mut h);
h.finish()
};
let key = (
self.doc_rev,
width.to_bits(),
self.theme,
self.env_rev,
preview_rev,
draft_hash,
is_rtl,
);
if let Some((cached, layout)) = &self.layout
&& *cached == key
{
return Some(layout.clone());
}
let snapshot = self.preedit_snapshot().map(Rc::new).unwrap_or(snapshot);
let mut dirty = self.dirty_text.take().filter(|_| {
self.layout.as_ref().is_some_and(|(old, _)| {
old.1 == key.1
&& old.2 == key.2
&& old.3 == key.3
&& old.4 == key.4
&& old.6 == key.6
})
});
// If only the live equation draft changed, mark just the target block dirty so sibling
// blocks stay cached (preserving single-keystroke relayout == 1).
if let Some((old, _)) = &self.layout
&& old.5 != key.5
{
if let Some(ref mut set) = dirty {
if let Some(draft) = &equation_draft {
let bid = match draft {
crate::block_flow::EquationDraft::Block { block_id, .. }
| crate::block_flow::EquationDraft::Inline { block_id, .. } => {
block_id.clone()
}
};
set.insert(bid);
} else {
// Equation editor closed; full pass reconciles the previously overridden block.
dirty = None;
}
}
}
let doc_dir = self
.custom_doc_directory
.as_deref()
.unwrap_or(&self.default_doc_directory);
let layout = Rc::new(self.flow.layout_changed(
&FlowInput {
snapshot: &snapshot,
width,
theme: self.theme,
page_titles: &self.page_titles,
images: &self.images,
pdf_previews: Some(&self.pdf_previews),
doc_directory: Some(doc_dir),
equation_draft: equation_draft.as_ref(),
env_rev: self.env_rev,
direction: window.layout_direction(),
},
window,
dirty.as_ref(),
));
self.dirty_text = Some(BTreeSet::new());
self.layout = Some((key, layout.clone()));
Some(layout)
}
}
File diff suppressed because it is too large. Load diff
@@ -2784,8 +2784,9 @@ mod tests {
let bar = element(&frame, "overlay.keyboard_toolbar");
assert_eq!(bar.bounds.height, KEYBOARD_TOOLBAR_HEIGHT);
for id in [
"overlay.keyboard_toolbar.more_panel",
"overlay.keyboard_toolbar.text_style",
"overlay.keyboard_toolbar.undo",
"overlay.keyboard_toolbar.bold",
"overlay.keyboard_toolbar.dismiss",
] {
let btn = element(&frame, id);
@@ -2795,7 +2796,7 @@ mod tests {
);
}
// Long-press on the bidi paragraph selects an ICU word.
// Long-press on the bidi paragraph selects an ICU word and autoShows the `Aa` sub-toolbar.
let bidi_bounds = element(&frame, "page.block.bidi-p").bounds;
session.overlay(OverlayEvent::LongPressWord {
x: bidi_bounds.x + 10.0,
@@ -2804,6 +2805,10 @@ mod tests {
let sel = session.selection().expect("word selection");
assert_eq!(sel.0, "bidi-p");
assert!(sel.3 > sel.1, "long-press must select a non-empty ICU word");
let sub_frame = session.frame();
assert_no_violations(&sub_frame, "mobile keyboard toolbar autoShow Aa");
let bold_btn = element(&sub_frame, "overlay.keyboard_toolbar.bold");
assert!(bold_btn.bounds.width >= 44.0 && bold_btn.bounds.height >= 44.0);
// Clicking Bold on KeyboardToolbar applies bold in one undoable step.
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Bold));
@@ -2839,6 +2844,10 @@ mod tests {
#[test]
fn mobile_keyboard_toolbar_pagination_reaches_all_18_actions_on_390px() {
let session = open(390, 844, PlaygroundTheme::Light);
session.view(|v, cx| {
v.set_image_picker(Some(std::rc::Rc::new(|| {})));
cx.notify();
});
session.edit(|page| {
page.add_block(
"mob-p",
@@ -2852,75 +2861,98 @@ mod tests {
)
.expect("add mobile paragraph");
});
session.select("mob-p", "Tap");
// Collapsed caret starts on top-level bar (0.27.5 defaultKeyboardToolbarConfig).
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"mob-p", 0,
))));
session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true));
let visible_top: Vec<&str> = DEFAULT_KEYBOARD_TOOLBAR_ITEMS
.iter()
.filter(|i| i.is_visible())
.map(ToolbarItemSpec::id)
.collect();
let mut seen = std::collections::HashSet::new();
for _ in 0..6 {
let frame = session.frame();
assert_no_violations(&frame, "mobile toolbar page");
assert_no_violations(&frame, "mobile toolbar top page");
let more = element(&frame, "overlay.keyboard_toolbar.more");
let dismiss = element(&frame, "overlay.keyboard_toolbar.dismiss");
assert!(more.bounds.width >= 44.0 && more.bounds.height >= 44.0);
assert!(dismiss.bounds.width >= 44.0 && dismiss.bounds.height >= 44.0);
for action in KeyboardToolbarAction::ALL {
if action == KeyboardToolbarAction::Dismiss {
continue;
}
let id = format!("overlay.keyboard_toolbar.{}", action.id());
if let Some(el) = frame.elements.get(id.as_str()) {
for &id in &visible_top {
let full_id = format!("overlay.keyboard_toolbar.{id}");
if let Some(el) = frame.elements.get(full_id.as_str()) {
assert!(
el.bounds.width >= 44.0 && el.bounds.height >= 44.0,
"{id} < 44x44"
"{full_id} < 44x44"
);
seen.insert(action);
seen.insert(id);
}
}
session.click(&frame, "overlay.keyboard_toolbar.more");
}
for action in KeyboardToolbarAction::ALL {
if action != KeyboardToolbarAction::Dismiss {
assert!(
seen.contains(&action),
"action {action:?} unreachable via More pagination on 390px viewport"
);
}
for &id in &visible_top {
assert!(
seen.contains(id),
"top-level item {id} unreachable via More pagination on 390px viewport"
);
}
// Helper to page until `target_id` is visible and click it on canvas.
let click_paged = |target_id: &str| {
for _ in 0..6 {
let frame = session.frame();
if frame.elements.contains_key(target_id) {
session.click(&frame, target_id);
return;
}
session.click(&frame, "overlay.keyboard_toolbar.more");
}
panic!("could not find {target_id} on any toolbar page");
};
// Click H1 -> converts paragraph to h1, Undo -> reverts, Todo -> converts to todo,
// CodeBlock -> converts to code, Mention -> opens @ picker, Dismiss -> hides bar.
click_paged("overlay.keyboard_toolbar.h1");
let after_h1 = session.frame();
assert!(after_h1.elements.contains_key("page.block.mob-p"));
click_paged("overlay.keyboard_toolbar.undo");
click_paged("overlay.keyboard_toolbar.todo");
click_paged("overlay.keyboard_toolbar.undo");
click_paged("overlay.keyboard_toolbar.code_block");
click_paged("overlay.keyboard_toolbar.undo");
click_paged("overlay.keyboard_toolbar.mention");
session.platform.advance_clock(Duration::from_millis(160));
session.platform.run_until_parked();
let with_mention = session.frame();
// Open `+` (`moreToolPanel`): H1, To-do, Code Block, Linked Page all work in 1 Undo step.
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
let panel_frame = session.frame();
assert_no_violations(&panel_frame, "mobile toolbar more panel");
assert!(
with_mention
panel_frame
.elements
.contains_key("overlay.linked_doc_menu")
.contains_key("overlay.keyboard_toolbar.panel")
);
let dismiss_frame = session.frame();
session.click(&dismiss_frame, "overlay.keyboard_toolbar.dismiss");
session.click(&panel_frame, "overlay.keyboard_toolbar.panel.basic.h1");
assert!(session.frame().elements.contains_key("page.block.mob-p"));
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
let todo_frame = session.frame();
session.click(&todo_frame, "overlay.keyboard_toolbar.panel.list.todo");
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
let code_frame = session.frame();
session.click(
&code_frame,
"overlay.keyboard_toolbar.panel.basic.code_block",
);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
// Non-collapsed selection autoShows `Aa` sub-toolbar with Strike, Link, Highlight.
session.select("mob-p", "Tap");
let aa_frame = session.frame();
assert_no_violations(&aa_frame, "mobile toolbar autoShow Aa");
assert!(
aa_frame
.elements
.contains_key("overlay.keyboard_toolbar.back")
);
assert!(
aa_frame
.elements
.contains_key("overlay.keyboard_toolbar.bold")
);
assert!(
aa_frame
.elements
.contains_key("overlay.keyboard_toolbar.strike")
);
// Dismiss hides the bar cleanly.
session.click(&aa_frame, "overlay.keyboard_toolbar.dismiss");
let dismissed = session.frame();
assert!(!dismissed.elements.contains_key("overlay.keyboard_toolbar"));
}
@@ -96,6 +96,7 @@ impl PlaygroundView {
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
self.overlays.close_link_field();
self.overlays.close_equation_editor();
self.overlays.close_bookmark_prompt();
self.equation_snapshot = None;
match selection {
Some(selection) => {
@@ -140,6 +140,9 @@ impl PlaygroundView {
command,
typed,
} => self.run_slash_command(&block_id, command, typed, window, cx),
DocEdit::Bookmark { block_id, url } => {
self.insert_bookmark_after_block(&block_id, url, window, cx)
}
edit @ (DocEdit::SetProp { .. } | DocEdit::Reorder { .. }) => {
let before = self.selection_snapshot();
let page = self.page_mut()?;
@@ -0,0 +1,787 @@
//! Single-step Undo document commands driven by the mobile `KeyboardToolbar`:
//! inline/block color highlights, block duplicate/delete, block inserts
//! (equation, table, callout, image, bookmark), inline math, and deterministic
//! scheduler-clock date formatting.
use blocksuite_playground_doc::{
DocError, DocResult,
read::{BlockContent, BlockNode},
schema::{BlockSpec, ListType, ParagraphType},
};
use ui::{Context, Window};
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use crate::{
PlaygroundView,
block_flow::{FlowKind, civil_from_days},
editor_session::{DocPoint, DocumentSelection},
overlays::{EquationTarget, KeyboardToolbarDateKind, OverlayEvent, find_parent},
};
/// Encodes a 32-byte SHA-256 digest as 44-character padded base64url (`[A-Za-z0-9_-]{43}=`),
/// matching BlockSuite `0.27.5` `sha()` (`toBase64(sha256(bytes)).replace(/\+/g, '-').replace(/\//g, '_')`).
pub(crate) fn sha256_base64url(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
use sha2::{Digest, Sha256};
let digest = Sha256::digest(bytes);
let mut out = String::with_capacity(44);
let mut i = 0usize;
while i + 3 <= 32 {
let n = ((digest[i] as u32) << 16) | ((digest[i + 1] as u32) << 8) | (digest[i + 2] as u32);
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push(TABLE[(n & 0x3f) as usize] as char);
i += 3;
}
let rem = ((digest[30] as u32) << 16) | ((digest[31] as u32) << 8);
out.push(TABLE[((rem >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((rem >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((rem >> 6) & 0x3f) as usize] as char);
out.push('=');
out
}
/// Format a UTC Unix timestamp (`utc_epoch_ms`) shifted by `utc_offset_minutes` into
/// BlockSuite `0.27.5` local calendar `formatDate` (`yyyy-mm-dd`) or `formatTime` (`mm-dd hh:mm`).
pub(super) fn format_keyboard_toolbar_local_date(
utc_epoch_ms: i64,
utc_offset_minutes: i32,
kind: KeyboardToolbarDateKind,
) -> String {
let local_ms = utc_epoch_ms.saturating_add(i64::from(utc_offset_minutes) * 60_000);
let total_secs = local_ms.div_euclid(1_000);
let days = total_secs.div_euclid(86_400);
let sec_of_day = total_secs.rem_euclid(86_400);
match kind {
KeyboardToolbarDateKind::Today => {
let (y, m, d) = civil_from_days(days);
format!("{y:04}-{m:02}-{d:02}")
}
KeyboardToolbarDateKind::Tomorrow => {
let (y, m, d) = civil_from_days(days + 1);
format!("{y:04}-{m:02}-{d:02}")
}
KeyboardToolbarDateKind::Yesterday => {
let (y, m, d) = civil_from_days(days - 1);
format!("{y:04}-{m:02}-{d:02}")
}
KeyboardToolbarDateKind::Now => {
let (_, m, d) = civil_from_days(days);
let hh = sec_of_day / 3_600;
let mm = (sec_of_day % 3_600) / 60;
format!("{m:02}-{d:02} {hh:02}:{mm:02}")
}
}
}
fn clone_block_spec(node: &BlockNode) -> BlockSpec {
match &node.content {
BlockContent::Paragraph { kind, .. } => BlockSpec::Paragraph {
paragraph_type: *kind,
text: String::new(),
},
BlockContent::List {
kind,
checked,
order,
..
} => BlockSpec::List {
list_type: *kind,
text: String::new(),
checked: *checked,
order: order.and_then(|v| i32::try_from(v).ok()),
},
BlockContent::Code {
language, caption, ..
} => BlockSpec::Code {
text: String::new(),
language: (!language.is_empty()).then(|| language.clone()),
caption: caption.clone(),
},
BlockContent::Divider => BlockSpec::Divider,
BlockContent::Latex { latex } => BlockSpec::Latex {
latex: latex.clone(),
},
BlockContent::Callout {
icon,
background_color,
..
} => BlockSpec::Callout {
icon: icon.clone(),
background_color: background_color.clone(),
},
BlockContent::Image {
source_id,
caption,
width,
height,
} => BlockSpec::Image {
source_id: source_id.clone(),
caption: caption.clone(),
width: width.unwrap_or(320.0),
height: height.unwrap_or(180.0),
xywh: None,
},
BlockContent::Bookmark {
url,
title,
description,
..
} => BlockSpec::Bookmark {
url: url.clone(),
title: title.clone(),
description: description.clone(),
},
BlockContent::Table(table) => {
let rows = table
.rows
.iter()
.map(|r| {
table
.columns
.iter()
.map(|c| {
table
.cells
.get(&(r.row_id.clone(), c.column_id.clone()))
.map(|cell| cell.text.plain.clone())
.unwrap_or_default()
})
.collect()
})
.collect();
BlockSpec::Table { rows }
}
_ => BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
}
}
impl PlaygroundView {
pub(super) fn can_indent_current_block(&self) -> bool {
let Some(id) = self
.editor
.selection
.as_ref()
.map(|s| s.focus.block_id.as_str())
else {
return false;
};
let Some(snapshot) = self.snapshot.as_ref() else {
return false;
};
if snapshot
.block(id)
.is_some_and(|n| matches!(n.content, BlockContent::Code { .. }))
{
return true;
}
let Some(root) = snapshot.root.as_ref() else {
return false;
};
let Some((parent, pos)) = find_parent(root, id) else {
return false;
};
pos.checked_sub(1)
.and_then(|i| parent.children.get(i))
.is_some_and(|b| {
matches!(
b.content,
BlockContent::List { .. } | BlockContent::Paragraph { .. }
)
})
}
pub(super) fn can_dedent_current_block(&self) -> bool {
let Some(id) = self
.editor
.selection
.as_ref()
.map(|s| s.focus.block_id.as_str())
else {
return false;
};
let Some(snapshot) = self.snapshot.as_ref() else {
return false;
};
let Some(root) = snapshot.root.as_ref() else {
return false;
};
let Some((parent, _)) = find_parent(root, id) else {
return false;
};
matches!(
parent.content,
BlockContent::List { .. } | BlockContent::Paragraph { .. }
) && find_parent(root, &parent.id).is_some()
}
/// Apply or clear a `color` or `background` rich-text highlight mark in one undo step.
pub(super) fn format_color_mark(
&mut self,
key: &str,
value: Option<&str>,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let Some(sel) = self.editor.selection.clone() else {
return Ok(());
};
if sel.empty() {
self.editor
.pending_marks
.insert(key.into(), value.map(|v| Any::String(v.to_owned())));
return Ok(());
}
let Some(layout) = self.flow_layout() else {
return Ok(());
};
let Some((start, end, a, b, _)) = sel.ordered(&layout) else {
return Ok(());
};
let now = self.now_ms(cx) as u64;
let mut ranges = Vec::new();
for block in layout.blocks[a..=b].iter().filter(|b| b.editable()) {
let id = &block.block_id;
let from = if id == &start.block_id {
start.offset()
} else {
0
};
let to = if id == &end.block_id {
end.offset()
} else {
block.body.plain.encode_utf16().count() as u64
};
if to <= from {
continue;
}
let prop = if matches!(block.body.kind, FlowKind::Title) {
"prop:title"
} else {
"prop:text"
};
ranges.push((id.as_str(), prop, from, to - from));
}
if ranges.is_empty() {
return Ok(());
}
let page = self.page_mut()?;
let snap = sel.snapshot(page)?;
page.stop_capturing()?;
let attr_val = value.map_or(Any::Null, |v| Any::String(v.to_owned()));
let commit = page.structural_edit(now, |page| {
for (id, prop, from, len) in ranges {
page.format_text(
id,
prop,
from,
len,
TextAttributes::from([(key.to_owned(), attr_val.clone())]),
now,
)?;
}
Ok(())
})?;
if commit.is_some() {
page.set_undo_selection_snapshot(snap)?;
}
self.editor.last_typing = None;
self.did_edit(commit, (a == b).then_some(&start.block_id), window, cx);
Ok(())
}
/// Insert an inline LaTeX equation placeholder at the caret and open the equation editor.
pub(super) fn insert_inline_math_from_toolbar(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(sel) = self.editor.selection.clone() else {
return;
};
let offset = sel.focus.offset();
let now = self.now_ms(cx) as u64;
let before = self.selection_snapshot();
if let Ok(page) = self.page_mut() {
let _ = page.stop_capturing();
let mut delta = Vec::new();
if offset > 0 {
delta.push(TextDeltaOp::Retain {
retain: offset,
format: None,
});
}
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(" ".into()),
format: Some(TextAttributes::from([(
"latex".to_string(),
Any::String(String::new()),
)])),
});
if let Ok(commit) = page.apply_text_delta(&sel.focus.block_id, "prop:text", &delta, now)
{
if commit.is_some()
&& let Some(before) = before
{
let _ = page.set_undo_selection_snapshot(before);
}
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(
&sel.focus.block_id,
offset + 1,
)));
self.did_edit(commit, Some(&sel.focus.block_id), window, cx);
self.dispatch_overlay(
OverlayEvent::OpenEquationEditor {
target: EquationTarget::Inline {
block_id: sel.focus.block_id,
utf16_offset: offset,
},
initial: String::new(),
},
window,
cx,
);
}
}
}
/// Clone the currently focused block directly below it as one undoable `structural_edit`.
pub(super) fn duplicate_current_block(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let Some(sel) = self.editor.selection.clone() else {
return Ok(());
};
let block_id = sel.focus.block_id.clone();
let snapshot = self
.snapshot
.clone()
.ok_or_else(|| DocError::InvalidState("missing page".into()))?;
let Some((parent, slot)) = snapshot
.root
.as_ref()
.and_then(|root| find_parent(root, &block_id))
else {
return Ok(());
};
let node = &parent.children[slot];
let spec = clone_block_spec(node);
let is_numbered = matches!(
node.content,
BlockContent::List {
kind: ListType::Numbered,
..
}
);
let has_text = matches!(
node.content,
BlockContent::Paragraph { .. } | BlockContent::List { .. } | BlockContent::Code { .. }
);
let existing_delta = if has_text {
self.page()
.and_then(|p| p.read_editable_text(&block_id).ok())
.map(|(rich, _)| rich.delta)
} else {
None
};
let fresh = self.fresh_block_id();
let parent_id = parent.id.clone();
let now = self.now_ms(cx) as u64;
let before = self.selection_snapshot();
let page = self.page_mut()?;
page.stop_capturing()?;
let commit = page.structural_edit(now, |page| {
page.add_block(&fresh, spec, Some(&parent_id), Some(slot as u64 + 1), now)?;
if let Some(delta) = existing_delta.as_ref()
&& !delta.is_empty()
{
page.apply_text_delta(&fresh, "prop:text", delta, now)?;
}
if is_numbered {
page.correct_numbered_order_from(&parent_id, slot + 1, 1)?;
}
Ok(())
})?;
if commit.is_some()
&& let Some(before) = before
{
page.set_undo_selection_snapshot(before)?;
}
if has_text {
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(&fresh, 0)));
}
self.editor.last_typing = None;
self.did_edit(commit, None, window, cx);
Ok(())
}
/// Delete the currently focused block in one undoable `structural_edit`.
/// When deleting the last remaining block of its parent, inserts a fresh empty paragraph.
pub(super) fn delete_current_block(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let Some(sel) = self.editor.selection.clone() else {
return Ok(());
};
let block_id = sel.focus.block_id.clone();
let snapshot = self
.snapshot
.clone()
.ok_or_else(|| DocError::InvalidState("missing page".into()))?;
let Some((parent, slot)) = snapshot
.root
.as_ref()
.and_then(|root| find_parent(root, &block_id))
else {
return Ok(());
};
let parent_id = parent.id.clone();
let is_last_child = parent.children.len() <= 1;
let fallback_id = if is_last_child {
Some(self.fresh_block_id())
} else {
None
};
let next_focus_id = if let Some(ref fresh) = fallback_id {
Some(fresh.clone())
} else if slot > 0 {
Some(parent.children[slot - 1].id.clone())
} else {
parent.children.get(slot + 1).map(|n| n.id.clone())
};
let now = self.now_ms(cx) as u64;
let before = self.selection_snapshot();
let page = self.page_mut()?;
page.stop_capturing()?;
let commit = page.structural_edit(now, |page| {
if let Some(ref fresh) = fallback_id {
page.add_block(
fresh,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
Some(&parent_id),
Some(0),
now,
)?;
}
page.delete_block_subtree(&parent_id, &block_id, now)?;
Ok(())
})?;
if commit.is_some()
&& let Some(before) = before
{
page.set_undo_selection_snapshot(before)?;
}
self.editor.selection =
next_focus_id.map(|id| DocumentSelection::caret(DocPoint::new(id, 0)));
self.editor.last_typing = None;
self.did_edit(commit, None, window, cx);
Ok(())
}
fn insert_sibling_after_block(
&mut self,
anchor_block_id: &str,
spec: BlockSpec,
child_paragraph: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult<Option<String>> {
let snapshot = self
.snapshot
.clone()
.ok_or_else(|| DocError::InvalidState("missing page".into()))?;
let Some((parent, slot)) = snapshot
.root
.as_ref()
.and_then(|root| find_parent(root, anchor_block_id))
else {
return Ok(None);
};
let parent_id = parent.id.clone();
let fresh = self.fresh_block_id();
let child_id = child_paragraph.then(|| self.fresh_block_id());
let now = self.now_ms(cx) as u64;
let before = self.selection_snapshot();
let page = self.page_mut()?;
page.stop_capturing()?;
let commit = page.structural_edit(now, |page| {
page.add_block(&fresh, spec, Some(&parent_id), Some(slot as u64 + 1), now)?;
if let Some(ref cid) = child_id {
page.add_block(
cid,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
Some(&fresh),
Some(0),
now,
)?;
}
Ok(())
})?;
if commit.is_some()
&& let Some(before) = before
{
page.set_undo_selection_snapshot(before)?;
}
page.stop_capturing()?;
if let Some(ref cid) = child_id {
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(cid, 0)));
}
self.editor.last_typing = None;
self.did_edit(commit, None, window, cx);
Ok(Some(fresh))
}
fn insert_sibling_block(
&mut self,
spec: BlockSpec,
child_paragraph: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult<Option<String>> {
let Some(sel) = self.editor.selection.clone() else {
return Ok(None);
};
let block_id = sel.focus.block_id.clone();
self.insert_sibling_after_block(&block_id, spec, child_paragraph, window, cx)
}
pub(super) fn insert_equation_block_from_toolbar(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
if let Some(block_id) = self.insert_sibling_block(
BlockSpec::Latex {
latex: String::new(),
},
false,
window,
cx,
)? {
self.dispatch_overlay(
OverlayEvent::OpenEquationEditor {
target: EquationTarget::Block { block_id },
initial: String::new(),
},
window,
cx,
);
}
Ok(())
}
pub(super) fn insert_table_block_from_toolbar(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let _ = self.insert_sibling_block(
BlockSpec::Table {
rows: vec![
vec![String::new(), String::new()],
vec![String::new(), String::new()],
],
},
false,
window,
cx,
)?;
Ok(())
}
pub(super) fn insert_callout_block_from_toolbar(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let _ = self.insert_sibling_block(
BlockSpec::Callout {
icon: "\u{1F4A1}".into(),
background_color: None,
},
true,
window,
cx,
)?;
Ok(())
}
/// Triggers the host image file picker without mutating the document until a valid image is chosen.
pub(super) fn trigger_image_picker_from_toolbar(&mut self, _cx: &mut Context<Self>) {
if let Some(picker) = self.image_picker.clone() {
picker();
return;
}
#[cfg(target_family = "wasm")]
crate::wasm_preview::request_host_image_picker();
}
/// Maximum encoded image size accepted when picking a new photo on mobile/Web (32 MiB).
/// Existing room blobs up to `MAX_BLOB_BYTES` (64 MiB) remain readable via `decode_image`.
const MAX_PICKED_IMAGE_BYTES: usize = 32 * 1024 * 1024;
/// Decodes chosen image bytes in a single pass, stores and uploads the content-addressed
/// SHA-256 blob, and inserts an `affine:image` block with its intrinsic logical dimensions
/// as one Undo step. Invalid or oversized bytes leave the document untouched.
pub(super) fn insert_picked_image_bytes(
&mut self,
bytes: &[u8],
caption: &str,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
if bytes.is_empty() || bytes.len() > Self::MAX_PICKED_IMAGE_BYTES {
return Ok(());
}
let Some((render_img, px_w, px_h)) = crate::block_flow::decode_image_with_dimensions(bytes)
else {
return Ok(());
};
let w = (px_w.max(1) as f64).min(720.0);
let scale = w / (px_w.max(1) as f64);
let h = ((px_h.max(1) as f64) * scale).round().max(1.0);
let source_id = sha256_base64url(bytes);
let shared_bytes = std::sync::Arc::new(bytes.to_vec());
self.state
.blobs
.insert(source_id.clone(), shared_bytes.clone());
self.images.insert(
source_id.clone(),
crate::block_flow::ImageSlot::Ready(render_img),
);
self.queue_blob_upload(source_id.clone(), shared_bytes, cx);
self.env_rev += 1;
let _ = self.insert_sibling_block(
BlockSpec::Image {
source_id,
caption: caption.to_string(),
width: w,
height: h,
xywh: None,
},
false,
window,
cx,
)?;
Ok(())
}
/// Stores and uploads a PDF blob under its base64url SHA-256 `sourceId` and inserts an
/// embedded `affine:attachment` block (`embed: true`) so Hayro renders its pages in-document.
pub fn insert_picked_pdf_bytes(
&mut self,
bytes: &[u8],
name: &str,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
if bytes.len() < 5 || bytes.len() > 64 * 1024 * 1024 || !bytes.starts_with(b"%PDF-") {
return Ok(());
}
let source_id = sha256_base64url(bytes);
let shared_bytes = std::sync::Arc::new(bytes.to_vec());
self.state
.blobs
.insert(source_id.clone(), shared_bytes.clone());
self.queue_blob_upload(source_id.clone(), shared_bytes, cx);
let spec = BlockSpec::Attachment {
name: if name.trim().is_empty() {
"document.pdf".to_string()
} else {
name.trim().to_string()
},
size: bytes.len() as i64,
mime_type: "application/pdf".to_string(),
source_id,
embed: true,
caption: String::new(),
};
if self.editor.selection.is_some() {
let _ = self.insert_sibling_block(spec, false, window, cx)?;
return Ok(());
}
let Some(anchor_id) = self.snapshot.as_ref().and_then(|snap| {
let root = snap.root.as_ref()?;
let note = root.children.iter().find(|c| {
matches!(
c.content,
blocksuite_playground_doc::read::BlockContent::Note { .. }
)
})?;
note.children.first().map(|c| c.id.clone())
}) else {
return Ok(());
};
let _ = self.insert_sibling_after_block(&anchor_id, spec, false, window, cx)?;
Ok(())
}
/// Inserts an `affine:bookmark` block after `anchor_block_id` once the user confirms a valid URL.
pub(crate) fn insert_bookmark_after_block(
&mut self,
anchor_block_id: &str,
url: String,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
let trimmed = url.trim();
if trimmed.is_empty() {
return Ok(());
}
let _ = self.insert_sibling_after_block(
anchor_block_id,
BlockSpec::Bookmark {
url: trimmed.to_string(),
title: None,
description: None,
},
false,
window,
cx,
)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn local_date_formatter_matches_0275_formats_and_crosses_midnight() {
// 2026-11-26T16:30:00Z = 1795710600000 ms; at UTC+08:00 (+480 min) -> 2026-11-27 00:30 local!
let ts = 1_795_710_600_000_i64;
assert_eq!(
format_keyboard_toolbar_local_date(ts, 480, KeyboardToolbarDateKind::Today),
"2026-11-27"
);
assert_eq!(
format_keyboard_toolbar_local_date(ts, 480, KeyboardToolbarDateKind::Tomorrow),
"2026-11-28"
);
assert_eq!(
format_keyboard_toolbar_local_date(ts, 480, KeyboardToolbarDateKind::Yesterday),
"2026-11-26"
);
assert_eq!(
format_keyboard_toolbar_local_date(ts, 480, KeyboardToolbarDateKind::Now),
"11-27 00:30"
);
}
}
@@ -1,19 +1,40 @@
//! Mobile `KeyboardToolbar`, long-press ICU word selection, embedded PDF paging,
//! table cell editing, and embedded doc navigation handlers for `PlaygroundView`.
use blocksuite_playground_doc::schema::{ListType, ParagraphType};
mod actions;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_parity;
#[cfg(test)]
mod tests_sync;
use ui::{Context, Window, point, px};
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use crate::{
PlaygroundView,
block_flow::{parse_pdf_renderer, render_pdf_page},
block_flow::{PdfParseResult, parse_pdf_document, render_pdf_page},
editor_session::{DocPoint, DocumentSelection, word_range},
};
use super::*;
impl PlaygroundView {
/// Sync per-frame undo/redo/indent/dedent and `autoShow` selection capabilities
/// into `Overlays` for `KeyboardToolbar`.
pub(crate) fn sync_keyboard_toolbar_state(&mut self) {
let caps = KeyboardToolbarCapabilities {
can_undo: self.page().is_some_and(|p| p.can_undo()),
can_redo: self.page().is_some_and(|p| p.can_redo()),
can_indent: self.can_indent_current_block(),
can_dedent: self.can_dedent_current_block(),
can_pick_images: cfg!(target_family = "wasm") || self.image_picker.is_some(),
has_body_selection: self.editor.selection.is_some(),
has_non_collapsed_selection: self.editor.selection.as_ref().is_some_and(|s| !s.empty()),
};
self.overlays.set_keyboard_toolbar_capabilities(caps);
}
/// Handles mobile keyboard toolbar, PDF paging, table cell edit, embed doc open,
/// and touch long-press word selection events. Returns `true` when consumed.
pub(super) fn handle_mobile_and_rich_event(
@@ -25,6 +46,9 @@ impl PlaygroundView {
match event {
OverlayEvent::SetKeyboardToolbarVisible(visible) => {
self.overlays.set_keyboard_toolbar_visible(*visible);
if *visible {
self.sync_keyboard_toolbar_state();
}
cx.notify();
true
}
@@ -32,6 +56,10 @@ impl PlaygroundView {
self.run_keyboard_toolbar_action(*action, window, cx);
true
}
OverlayEvent::InsertImageBytes { bytes, caption } => {
let _ = self.insert_picked_image_bytes(bytes, caption, window, cx);
true
}
OverlayEvent::AttachmentPdfPage { block_id, delta } => {
self.step_attachment_pdf_page(block_id, *delta, cx);
true
@@ -80,6 +108,29 @@ impl PlaygroundView {
.as_ref()
.map(|sel| sel.focus.block_id.clone());
match action {
KeyboardToolbarAction::ToggleMorePanel => {
self.overlays
.toggle_keyboard_toolbar_panel(KeyboardToolbarPanel::More);
cx.notify();
}
KeyboardToolbarAction::OpenTextSubToolbar => {
self.overlays.open_keyboard_text_subtoolbar();
cx.notify();
}
KeyboardToolbarAction::BackToMainToolbar => {
self.overlays.close_keyboard_text_subtoolbar();
cx.notify();
}
KeyboardToolbarAction::ToggleTurnIntoPanel => {
self.overlays
.toggle_keyboard_toolbar_panel(KeyboardToolbarPanel::TurnInto);
cx.notify();
}
KeyboardToolbarAction::ToggleHighlightPanel => {
self.overlays
.toggle_keyboard_toolbar_panel(KeyboardToolbarPanel::Highlight);
cx.notify();
}
KeyboardToolbarAction::Undo => {
let _ = self.history(false, window, cx);
}
@@ -95,105 +146,101 @@ impl PlaygroundView {
KeyboardToolbarAction::Underline => {
let _ = self.format_mark("underline", window, cx);
}
KeyboardToolbarAction::Strike => {
let _ = self.format_mark("strike", window, cx);
}
KeyboardToolbarAction::InlineCode => {
let _ = self.format_mark("code", window, cx);
}
KeyboardToolbarAction::InlineMath => {
if let Some(sel) = self.editor.selection.clone() {
let offset = sel.focus.offset();
let now = self.now_ms(cx) as u64;
let before = self.selection_snapshot();
if let Ok(page) = self.page_mut() {
let _ = page.stop_capturing();
let mut delta = Vec::new();
if offset > 0 {
delta.push(TextDeltaOp::Retain {
retain: offset,
format: None,
});
}
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(" ".into()),
format: Some(TextAttributes::from([(
"latex".to_string(),
Any::String(String::new()),
)])),
});
if let Ok(commit) =
page.apply_text_delta(&sel.focus.block_id, "prop:text", &delta, now)
{
if commit.is_some()
&& let Some(before) = before
{
let _ = page.set_undo_selection_snapshot(before);
}
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(
&sel.focus.block_id,
offset + 1,
)));
self.did_edit(commit, Some(&sel.focus.block_id), window, cx);
self.dispatch_overlay(
OverlayEvent::OpenEquationEditor {
target: EquationTarget::Inline {
block_id: sel.focus.block_id,
utf16_offset: offset,
},
initial: String::new(),
},
window,
cx,
);
}
}
}
KeyboardToolbarAction::Link => {
self.overlays.close_keyboard_toolbar_panel();
self.open_link_bar_from_toolbar(window, cx);
}
KeyboardToolbarAction::H1
| KeyboardToolbarAction::H2
| KeyboardToolbarAction::H3
| KeyboardToolbarAction::Todo
| KeyboardToolbarAction::Bullet
| KeyboardToolbarAction::Numbered
| KeyboardToolbarAction::Quote
| KeyboardToolbarAction::CodeBlock => {
KeyboardToolbarAction::InlineMath => {
self.overlays.close_keyboard_toolbar_panel();
self.insert_inline_math_from_toolbar(window, cx);
}
KeyboardToolbarAction::SetTextColor(color) => {
let _ = self.format_color_mark("color", color.fg_css_var(), window, cx);
self.overlays.close_keyboard_toolbar_panel();
cx.notify();
}
KeyboardToolbarAction::SetBgColor(color) => {
let _ = self.format_color_mark("background", color.bg_css_var(), window, cx);
self.overlays.close_keyboard_toolbar_panel();
cx.notify();
}
KeyboardToolbarAction::Slash(cmd) => {
let Some(id) = block_id else {
return;
};
let cmd = match action {
KeyboardToolbarAction::H1 => SlashCommand::Paragraph(ParagraphType::H1),
KeyboardToolbarAction::H2 => SlashCommand::Paragraph(ParagraphType::H2),
KeyboardToolbarAction::H3 => SlashCommand::Paragraph(ParagraphType::H3),
KeyboardToolbarAction::Todo => SlashCommand::List(ListType::Todo),
KeyboardToolbarAction::Bullet => SlashCommand::List(ListType::Bulleted),
KeyboardToolbarAction::Numbered => SlashCommand::List(ListType::Numbered),
KeyboardToolbarAction::Quote => SlashCommand::Paragraph(ParagraphType::Quote),
_ => SlashCommand::Code,
};
self.overlays.close_keyboard_toolbar_panel();
let _ = self.run_slash_command(&id, cmd, false, window, cx);
}
KeyboardToolbarAction::EquationBlock => {
self.overlays.close_keyboard_toolbar_panel();
let _ = self.insert_equation_block_from_toolbar(window, cx);
}
KeyboardToolbarAction::Table => {
self.overlays.close_keyboard_toolbar_panel();
let _ = self.insert_table_block_from_toolbar(window, cx);
}
KeyboardToolbarAction::Callout => {
self.overlays.close_keyboard_toolbar_panel();
let _ = self.insert_callout_block_from_toolbar(window, cx);
}
KeyboardToolbarAction::Image => {
self.overlays.close_keyboard_toolbar_panel();
self.trigger_image_picker_from_toolbar(cx);
}
KeyboardToolbarAction::Bookmark => {
let Some(id) = block_id else {
return;
};
self.overlays.close_keyboard_toolbar_panel();
self.dispatch_overlay(
OverlayEvent::OpenBookmarkPrompt { block_id: id },
window,
cx,
);
}
KeyboardToolbarAction::Date(kind) => {
let (utc_ms, tz_offset_min) = self.local_calendar_now(cx);
let formatted =
actions::format_keyboard_toolbar_local_date(utc_ms, tz_offset_min, kind);
self.overlays.close_keyboard_toolbar_panel();
let _ = self.insert_toolbar_plain_text(&formatted, window, cx);
}
KeyboardToolbarAction::Indent => {
let _ = self.edit_key("tab", false, window, cx);
}
KeyboardToolbarAction::Outdent => {
let _ = self.edit_key("tab", true, window, cx);
}
KeyboardToolbarAction::Mention => {
if let Some(sel) = self.editor.selection.clone() {
self.dispatch_overlay(
OverlayEvent::OpenLinkedDocMenu {
block_id: sel.focus.block_id,
query: String::new(),
},
window,
cx,
);
}
KeyboardToolbarAction::Copy => {
self.copy_toolbar_selection_or_block(cx);
}
KeyboardToolbarAction::Duplicate => {
let _ = self.duplicate_current_block(window, cx);
}
KeyboardToolbarAction::Delete => {
let _ = self.delete_current_block(window, cx);
}
KeyboardToolbarAction::Attachment
| KeyboardToolbarAction::EmbedIframe
| KeyboardToolbarAction::EmbedYoutube
| KeyboardToolbarAction::EmbedGithub
| KeyboardToolbarAction::EmbedFigma
| KeyboardToolbarAction::EmbedLoom
| KeyboardToolbarAction::DatabaseTableView
| KeyboardToolbarAction::DatabaseKanbanView => {}
KeyboardToolbarAction::Dismiss => {
self.keyboard_toolbar_dismissed = true;
self.overlays.set_keyboard_toolbar_visible(false);
cx.notify();
}
}
self.sync_keyboard_toolbar_state();
}
fn step_attachment_pdf_page(&mut self, block_id: &str, delta: i32, cx: &mut Context<Self>) {
@@ -210,7 +257,7 @@ impl PlaygroundView {
let Some(bytes) = self.state.blobs.get(&source_id) else {
return;
};
let Some(renderer) = parse_pdf_renderer(bytes) else {
let PdfParseResult::Ready(renderer) = parse_pdf_document(&source_id, bytes) else {
return;
};
let total = renderer.page_count();
@@ -219,15 +266,18 @@ impl PlaygroundView {
}
let current = self.pdf_page_indices.get(block_id).copied().unwrap_or(0) as i64;
let next = (current + i64::from(delta)).clamp(0, (total - 1) as i64) as usize;
// Persist target `next` before kicking off `render_pdf_page` so async Web Worker
// completion in `refresh_pdf_previews` lands on `next` instead of reverting to `0`.
self.pdf_page_indices.insert(block_id.to_string(), next);
if let Some(preview) = render_pdf_page(&renderer, next, 1.5) {
self.pdf_page_indices
.insert(block_id.to_string(), preview.page_index);
self.pdf_preview_keys
.insert(block_id.to_string(), (source_id, preview.page_index));
self.pdf_previews.insert(block_id.to_string(), preview);
self.env_rev += 1;
cx.notify();
crate::block_flow::bump_preview_revision();
}
cx.notify();
}
/// Collect all embedded PDF attachment `(block_id, source_id)` pairs in the active snapshot.
@@ -277,7 +327,7 @@ impl PlaygroundView {
self.pdf_previews.remove(&block_id);
self.pdf_preview_keys.remove(&block_id);
self.pdf_page_indices.remove(&block_id);
self.env_rev += 1;
crate::block_flow::bump_preview_revision();
}
self.pdf_previews
.retain(|block_id, _| active_pdf_map.contains_key(block_id.as_str()));
@@ -294,18 +344,19 @@ impl PlaygroundView {
if self.failed_pdf_blobs.contains(&fail_key) {
continue;
}
match parse_pdf_renderer(bytes) {
Some(renderer) => {
match parse_pdf_document(source_id, bytes) {
PdfParseResult::Ready(renderer) => {
if let Some(preview) = render_pdf_page(&renderer, page_idx, 1.5) {
let actual_idx = preview.page_index;
self.pdf_page_indices.insert(block_id.clone(), actual_idx);
self.pdf_preview_keys
.insert(block_id.clone(), (source_id.clone(), actual_idx));
self.pdf_previews.insert(block_id.clone(), preview);
self.env_rev += 1;
crate::block_flow::bump_preview_revision();
}
}
None => {
PdfParseResult::Pending => {}
PdfParseResult::Invalid => {
self.failed_pdf_blobs.insert(fail_key);
}
}
@@ -0,0 +1,686 @@
//! Comprehensive `0.27.5` `defaultKeyboardToolbarConfig` integration tests,
//! soft-wrapped equation navigation/hit-test checks, surgical per-formula layout
//! invalidation checks, and offscreen PNG evidence generator.
use std::{cell::Cell, cell::RefCell, rc::Rc, time::Duration};
use blocksuite_playground_doc::{
read::BlockContent,
schema::{BlockSpec, ListType, ParagraphType},
};
use ui::{
AppContext, Application, ApplicationHandle, Bounds, EntityInputHandler, FrameSnapshot,
HeadlessPlatform, HeadlessWindow, KeyDownEvent, Keystroke, Modifiers, PlatformInput,
WindowBounds, WindowHandle, WindowOptions, audit_frame_snapshot, point, px, size,
};
use y_octo::{Any, TextDeltaOp};
use crate::{
PlaygroundOptions, PlaygroundTheme, PlaygroundView,
block_flow::ImageSlot,
overlays::{
ActiveSelection, HighlightColor, KEYBOARD_TOOLBAR_HEIGHT, KeyboardToolbarAction,
KeyboardToolbarLevel, KeyboardToolbarPanel, OverlayEvent, SlashCommand,
},
register_bundled_fonts,
};
pub(super) struct MobileSession {
pub(super) platform: Rc<HeadlessPlatform>,
pub(super) app: ApplicationHandle,
pub(super) window: WindowHandle<PlaygroundView>,
pub(super) headless: HeadlessWindow,
}
impl MobileSession {
pub(super) fn open(width: u32, height: u32, theme: PlaygroundTheme) -> Self {
let platform = HeadlessPlatform::new(width, height, 1.0);
let handle_cell: Rc<RefCell<Option<WindowHandle<PlaygroundView>>>> =
Rc::new(RefCell::new(None));
let handle_out = handle_cell.clone();
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
register_bundled_fonts(cx).expect("bundled fonts");
let options = PlaygroundOptions {
theme,
..PlaygroundOptions::default()
};
let window = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(width as f32), px(height as f32)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| PlaygroundView::with_options(options, cx)),
)
.expect("open headless window");
*handle_out.borrow_mut() = Some(window);
});
let window = handle_cell.borrow_mut().take().expect("window opened");
let headless = platform
.windows()
.into_iter()
.next()
.expect("headless window registered");
let session = Self {
platform,
app,
window,
headless,
};
session.frame();
session.platform.run_until_parked();
session
}
pub(super) fn edit(
&self,
f: impl FnOnce(&mut blocksuite_playground_doc::session::PageDocSession),
) {
self.app.update(|cx| {
self.window
.update(cx, |v, _, cx| {
let page = v.page_mut().expect("active page");
f(page);
v.refresh_document();
cx.notify();
})
.unwrap();
});
}
pub(super) fn overlay(&self, event: OverlayEvent) {
self.app.update(|cx| {
self.window
.update(cx, |v, w, cx| v.dispatch_overlay(event, w, cx))
.unwrap();
});
}
pub(super) fn frame(&self) -> FrameSnapshot {
self.headless.request_frame();
self.app.update(|cx| {
self.window
.update(cx, |_, window, _| window.frame_snapshot().clone())
.unwrap()
})
}
pub(super) fn click_id(&self, snap: &FrameSnapshot, id: &str) {
let b = snap
.elements
.get(id)
.unwrap_or_else(|| panic!("missing snapshot element {id}"))
.bounds;
self.headless
.simulate_click(point(px(b.x + b.width * 0.5), px(b.y + b.height * 0.5)));
self.platform.run_until_parked();
}
pub(super) fn key(&self, key: &str) {
self.frame();
self.platform.run_until_parked();
self.headless
.dispatch_input(PlatformInput::KeyDown(KeyDownEvent {
keystroke: Keystroke {
modifiers: Modifiers::default(),
key: key.to_string(),
key_char: (key.chars().count() == 1).then(|| key.to_string()),
},
is_held: false,
prefer_character_input: false,
}));
self.platform.run_until_parked();
}
pub(super) fn type_into_field(&self, text: &str) {
self.app.update(|cx| {
self.window
.update(cx, |v, w, cx| {
v.replace_text_in_range(None, text, w, cx);
})
.unwrap();
});
self.frame();
}
pub(super) fn text(&self, block_id: &str) -> blocksuite_playground_doc::read::RichText {
self.app.update(|cx| {
self.window
.update(cx, |v, _, _| {
v.page()
.expect("page")
.read_editable_text(block_id)
.expect("text")
.0
})
.unwrap()
})
}
pub(super) fn block_count(&self, parent_id: &str) -> usize {
self.app.update(|cx| {
self.window
.update(cx, |v, _, _| {
v.page_snapshot()
.and_then(|s| s.block(parent_id))
.map(|n| n.children.len())
.unwrap_or(0)
})
.unwrap()
})
}
pub(super) fn view<R>(&self, f: impl FnOnce(&PlaygroundView) -> R) -> R {
self.app
.update(|cx| self.window.update(cx, |v, _, _| f(v)).unwrap())
}
pub(super) fn save_png(&self, path: &std::path::Path, label: &str) {
let snap = self.frame();
let violations = audit_frame_snapshot(&snap);
assert!(
violations.is_empty(),
"audit violations in {label}: {violations:#?}"
);
let img = self
.app
.update(|cx| {
self.window
.update(cx, |_, window, _| window.render_to_image())
.unwrap()
})
.expect("render image");
img.save(path)
.unwrap_or_else(|e| panic!("save {}: {e}", path.display()));
}
}
pub(super) fn encode_test_png(width: u32, height: u32) -> Vec<u8> {
let mut img = image::RgbaImage::new(width, height);
for (x, y, px) in img.enumerate_pixels_mut() {
*px = image::Rgba([(x * 17) as u8, (y * 29) as u8, 180, 255]);
}
let mut out = Vec::new();
let mut cursor = std::io::Cursor::new(&mut out);
image::DynamicImage::ImageRgba8(img)
.write_to(&mut cursor, image::ImageFormat::Png)
.expect("encode test png");
out
}
#[test]
fn keyboard_toolbar_0275_highlights_marks_and_link_single_step_undo() {
let session = MobileSession::open(390, 844, PlaygroundTheme::Light);
session.edit(|page| {
page.add_block(
"hl-p",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Hello highlight world".into(),
},
Some("showcase-note"),
Some(0),
5_000_000,
)
.expect("add paragraph");
});
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection {
block_id: "hl-p".into(),
start_utf16: 6,
end_utf16: 15,
})));
session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true));
let frame = session.frame();
assert!(audit_frame_snapshot(&frame).is_empty());
assert_eq!(
session.view(|v| v.overlays().keyboard_toolbar_level()),
KeyboardToolbarLevel::TextStyle
);
for (action, key) in [
(KeyboardToolbarAction::Bold, "bold"),
(KeyboardToolbarAction::Italic, "italic"),
(KeyboardToolbarAction::Underline, "underline"),
(KeyboardToolbarAction::Strike, "strike"),
(KeyboardToolbarAction::InlineCode, "code"),
] {
session.overlay(OverlayEvent::KeyboardToolbar(action));
let marked = session.text("hl-p");
assert!(
marked.delta.iter().any(|op| matches!(
op,
TextDeltaOp::Insert { format: Some(f), .. } if f.get(key) == Some(&Any::True)
)),
"mark {key} not applied"
);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
let undone = session.text("hl-p");
assert!(
undone.delta.iter().all(|op| !matches!(
op,
TextDeltaOp::Insert { format: Some(f), .. } if f.get(key) == Some(&Any::True)
)),
"mark {key} not undone in 1 step"
);
}
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleHighlightPanel,
));
let hl_frame = session.frame();
assert!(audit_frame_snapshot(&hl_frame).is_empty());
assert!(
hl_frame
.elements
.contains_key("overlay.keyboard_toolbar.panel.color.red")
);
assert!(
hl_frame
.elements
.contains_key("overlay.keyboard_toolbar.panel.background.yellow")
);
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::SetTextColor(HighlightColor::Red),
));
let colored = session.text("hl-p");
assert!(colored.delta.iter().any(|op| matches!(
op,
TextDeltaOp::Insert { format: Some(f), .. }
if f.get("color") == Some(&Any::String("var(--affine-v2-text-highlight-fg-red)".into()))
)));
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
let after_fg_undo = session.text("hl-p");
assert!(after_fg_undo.delta.iter().all(|op| !matches!(
op,
TextDeltaOp::Insert { format: Some(f), .. } if f.contains_key("color")
)));
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::SetBgColor(HighlightColor::Yellow),
));
let bg_colored = session.text("hl-p");
assert!(bg_colored.delta.iter().any(|op| matches!(
op,
TextDeltaOp::Insert { format: Some(f), .. }
if f.get("background")
== Some(&Any::String("var(--affine-v2-text-highlight-bg-yellow)".into()))
)));
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
let after_bg_undo = session.text("hl-p");
assert!(after_bg_undo.delta.iter().all(|op| !matches!(
op,
TextDeltaOp::Insert { format: Some(f), .. } if f.contains_key("background")
)));
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Link));
let _ = session.frame();
assert!(session.view(|v| v.overlays().link_field().is_some()));
}
#[test]
fn keyboard_toolbar_0275_local_dates_image_picker_bookmark_prompt_and_table_gate() {
let session = MobileSession::open(390, 844, PlaygroundTheme::Light);
session.edit(|page| {
page.add_block(
"ops-p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
Some("showcase-note"),
Some(0),
6_000_000,
)
.expect("add p1");
page.add_block(
"ops-p2",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Second block".into(),
},
Some("showcase-note"),
Some(1),
6_000_001,
)
.expect("add p2");
});
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"ops-p2", 12,
))));
session.overlay(OverlayEvent::SetKeyboardToolbarVisible(true));
let base_count = session.block_count("showcase-note");
// Duplicate & Delete each undo in 1 step.
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::Duplicate,
));
assert_eq!(session.block_count("showcase-note"), base_count + 1);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
assert_eq!(session.block_count("showcase-note"), base_count);
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"ops-p2", 0,
))));
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Delete));
assert_eq!(session.block_count("showcase-note"), base_count - 1);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
assert_eq!(session.block_count("showcase-note"), base_count);
let scroll_more_panel = |dy: f32| {
let s = session.frame();
let p = s.elements["overlay.keyboard_toolbar.panel"].bounds;
session
.headless
.dispatch_input(PlatformInput::Scroll(ui::ScrollEvent {
position: point(px(p.x + p.width * 0.5), px(p.y + p.height * 0.5)),
delta: ui::ScrollDelta::Pixels(point(px(0.0), px(dy))),
modifiers: Modifiers::default(),
touch_phase: ui::TouchPhase::Moved,
source: ui::ScrollSource::Pointer,
}));
session.platform.run_until_parked();
session.frame()
};
// 1a. Deterministic UTC+0 daytime calendar clock (`2026-11-26T14:05:00Z` = `1_795_701_900_000` ms):
// must format via the test clock without depending on host wall-clock time.
session.app.update(|cx| {
session
.window
.update(cx, |v, _, _| {
v.set_calendar_clock(Some(Rc::new(|| (1_795_701_900_000_i64, 0))));
})
.unwrap();
});
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"ops-p1", 0,
))));
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
let more_snap = scroll_more_panel(-800.0);
session.click_id(&more_snap, "overlay.keyboard_toolbar.panel.date.date_today");
assert_eq!(session.text("ops-p1").plain, "2026-11-26");
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
assert_eq!(session.text("ops-p1").plain, "");
// 1b. Cross-midnight local timezone rollover via visible panel buttons:
// UTC = 2026-11-26T16:30:00Z (1795710600000 ms), local offset = +480 min (UTC+8) -> 2026-11-27 00:30!
session.app.update(|cx| {
session
.window
.update(cx, |v, _, _| {
v.set_calendar_clock(Some(Rc::new(|| (1_795_710_600_000_i64, 480))));
})
.unwrap();
});
for (tile_id, expected) in [
(
"overlay.keyboard_toolbar.panel.date.date_today",
"2026-11-27",
),
(
"overlay.keyboard_toolbar.panel.date.date_yesterday",
"2026-11-26",
),
(
"overlay.keyboard_toolbar.panel.date.date_tomorrow",
"2026-11-28",
),
(
"overlay.keyboard_toolbar.panel.date.date_now",
"11-27 00:30",
),
] {
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"ops-p1", 0,
))));
if session.view(|v| v.overlays().keyboard_toolbar_active_panel())
!= Some(KeyboardToolbarPanel::More)
{
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
}
let snap = scroll_more_panel(-800.0);
session.click_id(&snap, tile_id);
assert_eq!(
session.text("ops-p1").plain,
expected,
"mismatch for visible button {tile_id}"
);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
assert_eq!(session.text("ops-p1").plain, "");
}
if session.view(|v| v.overlays().keyboard_toolbar_active_panel())
== Some(KeyboardToolbarPanel::More)
{
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
}
// 2. Native default without registered `image_picker` hides `Image`; once host registers picker,
// cancelling writes ZERO blocks and delivering real PNG inserts SHA-256 content-addressed Image!
let pre_picker_snap = session.frame();
assert!(
!pre_picker_snap
.elements
.contains_key("overlay.keyboard_toolbar.image"),
"native PlaygroundView without a registered image picker must hide Image button"
);
let picker_calls = Rc::new(Cell::new(0usize));
let picker_calls_cb = picker_calls.clone();
session.app.update(|cx| {
session
.window
.update(cx, |v, _, cx| {
v.set_image_picker(Some(Rc::new(move || {
picker_calls_cb.set(picker_calls_cb.get() + 1);
})));
cx.notify();
})
.unwrap();
});
let top_snap = session.frame();
session.click_id(&top_snap, "overlay.keyboard_toolbar.image");
assert_eq!(picker_calls.get(), 1);
assert_eq!(
session.block_count("showcase-note"),
base_count,
"cancelling/unfulfilled image picker must write zero placeholder blocks"
);
let png_bytes = encode_test_png(16, 10);
session.overlay(OverlayEvent::InsertImageBytes {
bytes: png_bytes,
caption: "Picked photo".into(),
});
assert_eq!(session.block_count("showcase-note"), base_count + 1);
let inserted_img = session.view(|v| {
v.page_snapshot()
.and_then(|s| s.block("showcase-note").cloned())
.and_then(|note| {
note.children
.into_iter()
.find_map(|child| match child.content {
BlockContent::Image {
source_id,
caption,
width,
height,
} if caption == "Picked photo" => {
let ready =
matches!(v.images.get(&source_id), Some(ImageSlot::Ready(_)));
Some((source_id, width, height, ready))
}
_ => None,
})
})
});
let (src_id, img_w, img_h, is_ready) = inserted_img.expect("inserted picked image block");
assert_eq!(
super::actions::sha256_base64url(b""),
"47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU=",
"empty SHA-256 base64url test vector must match BlockSuite 0.27.5 sha()"
);
assert_eq!(
src_id.len(),
44,
"source_id must be 44-char padded base64url SHA-256 matching 0.27.5 sha()"
);
assert!(
src_id.ends_with('=')
&& src_id[..43]
.bytes()
.all(|b| { b.is_ascii_alphanumeric() || b == b'-' || b == b'_' }),
"source_id must be base64url SHA-256: {src_id}"
);
assert_eq!((img_w, img_h), (Some(16.0), Some(10.0)));
assert!(
is_ready,
"picked image blob must decode to ImageSlot::Ready"
);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
assert_eq!(session.block_count("showcase-note"), base_count);
// 3. Visible `Bookmark` button in `More` panel: Escape & Cancel write ZERO blocks; Apply inserts Bookmark!
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
let cm_snap = scroll_more_panel(-240.0);
session.click_id(
&cm_snap,
"overlay.keyboard_toolbar.panel.content_media.bookmark",
);
let bm_snap = session.frame();
assert!(audit_frame_snapshot(&bm_snap).is_empty());
assert!(bm_snap.elements.contains_key("overlay.bookmark_prompt"));
assert_eq!(
session.block_count("showcase-note"),
base_count,
"opening bookmark prompt must not pre-insert a placeholder bookmark"
);
session.key("escape");
assert_eq!(
session.block_count("showcase-note"),
base_count,
"cancelling bookmark prompt with Escape must leave document unchanged"
);
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::Bookmark,
));
let bm_cancel_snap = session.frame();
session.type_into_field("https://ignored-on-cancel.example");
session.click_id(&bm_cancel_snap, "overlay.bookmark_prompt.cancel");
assert_eq!(
session.block_count("showcase-note"),
base_count,
"clicking Cancel on bookmark prompt must write zero blocks"
);
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::Bookmark,
));
let _ = session.frame();
session.type_into_field("/relative-only-path");
let bm_rel = session.frame();
session.click_id(&bm_rel, "overlay.bookmark_prompt.apply");
assert_eq!(
session.block_count("showcase-note"),
base_count,
"relative path in BookmarkPrompt must be rejected without writing a bookmark block"
);
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::Bookmark,
));
let _ = session.frame();
session.type_into_field("docs.affine.pro/mobile");
let bm_typed = session.frame();
session.click_id(&bm_typed, "overlay.bookmark_prompt.apply");
assert_eq!(session.block_count("showcase-note"), base_count + 1);
let bookmark_url = session.view(|v| {
v.page_snapshot()
.and_then(|s| s.block("showcase-note").cloned())
.and_then(|note| {
note.children
.into_iter()
.find_map(|child| match child.content {
BlockContent::Bookmark { url, .. } => Some(url),
_ => None,
})
})
});
assert_eq!(
bookmark_url.as_deref(),
Some("https://docs.affine.pro/mobile")
);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
assert_eq!(session.block_count("showcase-note"), base_count);
// 4. Table, Callout, EquationBlock, Divider, Toggle each insert & undo in 1 step.
for action in [
KeyboardToolbarAction::Table,
KeyboardToolbarAction::Callout,
KeyboardToolbarAction::EquationBlock,
KeyboardToolbarAction::Slash(SlashCommand::Divider),
KeyboardToolbarAction::Slash(SlashCommand::List(ListType::Toggle)),
] {
session.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"ops-p1", 0,
))));
session.overlay(OverlayEvent::KeyboardToolbar(action));
session.overlay(OverlayEvent::CloseEquationEditor);
session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo));
}
// 5. Table-cell focus gate disables non-Undo/Redo/Dismiss buttons and collapses open panels.
session.edit(|page| {
page.add_block(
"gate-tbl",
BlockSpec::Table {
rows: vec![vec!["A".into(), "B".into()]],
},
Some("showcase-note"),
Some(0),
6_000_100,
)
.expect("add table");
});
session.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
assert_eq!(
session.view(|v| v.overlays().keyboard_toolbar_active_panel()),
Some(KeyboardToolbarPanel::More)
);
session.overlay(OverlayEvent::FocusTableCell {
block_id: "gate-tbl".into(),
row_id: "row-0".into(),
column_id: "col-0".into(),
screen_pos: None,
});
session.platform.advance_clock(Duration::from_millis(160));
let gated = session.frame();
assert!(audit_frame_snapshot(&gated).is_empty());
assert_eq!(
session.view(|v| v.overlays().keyboard_toolbar_active_panel()),
None
);
assert_eq!(
gated
.elements
.get("overlay.keyboard_toolbar")
.map(|e| e.bounds.height),
Some(KEYBOARD_TOOLBAR_HEIGHT)
);
}
@@ -0,0 +1,709 @@
//! Equation soft-wrap navigation/click hit-testing, per-formula surgical layout
//! invalidation tests, and offscreen PNG evidence generator for mobile keyboard toolbar.
use std::{collections::HashMap, sync::Arc, sync::RwLock};
use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType};
use ui::{Modifiers, MouseButton, MouseDownEvent, PlatformInput, audit_frame_snapshot, point, px};
use y_octo::Any;
use crate::{
HOME_PAGE_ID, PlaygroundTheme,
block_flow::{
MathPreviewProvider, MathRenderResult, MathRenderSlot, bump_latex_formula_revision,
page_geometry, register_math_preview_provider, rgba_pixels_to_render_image,
},
overlays::{ActiveSelection, EquationTarget, KeyboardToolbarAction, OverlayEvent},
room_client::DocState,
};
use super::tests::MobileSession;
#[test]
fn equation_editor_soft_wrap_up_down_and_multiline_click_hit_testing() {
let session = MobileSession::open(390, 844, PlaygroundTheme::Light);
let long_single_line = r"\frac{x_1 + x_2 + x_3 + x_4 + x_5}{y_1 + y_2 + y_3} + \sqrt{a_1^2 + a_2^2 + a_3^2 + a_4^2} + \sum_{k=0}^{n} k^3";
assert!(!long_single_line.contains('\n'));
session.edit(|page| {
page.add_block(
"eq-wrap",
BlockSpec::Latex {
latex: long_single_line.into(),
},
Some("showcase-note"),
Some(0),
7_000_000,
)
.expect("add latex block");
});
session.overlay(OverlayEvent::OpenEquationEditor {
target: EquationTarget::Block {
block_id: "eq-wrap".into(),
},
initial: long_single_line.into(),
});
let snap = session.frame();
assert!(audit_frame_snapshot(&snap).is_empty());
let line_ranges: Vec<(usize, usize)> = session.view(|v| {
v.overlays()
.equation_editor()
.expect("open equation editor")
.visual_line_ranges()
});
assert!(
line_ranges.len() >= 3,
"expected long single-line formula to soft-wrap into >=3 visual rows, got {line_ranges:?}"
);
let total_u16 = long_single_line.encode_utf16().count();
// Caret starts at end (last visual row); Up must step to the middle wrapped row, NOT jump to 0!
let caret_end = session.view(|v| {
v.overlays()
.equation_editor()
.unwrap()
.input
.shown_selection()
.0
.end
});
assert_eq!(caret_end, total_u16);
session.key("up");
let caret_prev_row = session.view(|v| {
v.overlays()
.equation_editor()
.unwrap()
.input
.shown_selection()
.0
.end
});
let mid_idx = line_ranges.len() - 2;
assert!(
caret_prev_row >= line_ranges[mid_idx].0 && caret_prev_row < line_ranges[mid_idx].1,
"Up from last wrapped row must land on middle wrapped row {:?}, got {}",
line_ranges[mid_idx],
caret_prev_row
);
// Down from middle wrapped row must step back to the last wrapped row!
session.key("down");
let caret_down = session.view(|v| {
v.overlays()
.equation_editor()
.unwrap()
.input
.shown_selection()
.0
.end
});
assert!(
caret_down >= line_ranges.last().unwrap().0,
"Down must return to last wrapped row {:?}, got {}",
line_ranges.last(),
caret_down
);
// Move caret to 0 first, then click on visual row 2 (3rd row) and verify caret lands on row 2!
for _ in 0..line_ranges.len() {
session.key("up");
}
assert_eq!(
session.view(|v| v
.overlays()
.equation_editor()
.unwrap()
.input
.shown_selection()
.0
.end),
0
);
let input_bounds = snap.elements["overlay.equation_editor.input"].bounds;
let row2_click_x = input_bounds.x + 28.0;
let row2_click_y = input_bounds.y + 5.0 + 2.0 * 20.0 + 10.0;
session
.headless
.dispatch_input(PlatformInput::MouseDown(MouseDownEvent {
button: MouseButton::Left,
position: point(px(row2_click_x), px(row2_click_y)),
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
}));
session.platform.run_until_parked();
let clicked_caret = session.view(|v| {
v.overlays()
.equation_editor()
.unwrap()
.input
.shown_selection()
.0
.end
});
assert!(
clicked_caret >= line_ranges[2].0 && clicked_caret <= line_ranges[2].1,
"clicking visual row 2 must place caret inside {:?}, got {}",
line_ranges[2],
clicked_caret
);
}
#[test]
fn per_formula_worker_delivery_relayouts_single_block_and_ignores_stale_reply() {
struct ResetMath;
impl Drop for ResetMath {
fn drop(&mut self) {
register_math_preview_provider(None);
}
}
let _provider_lock = crate::GLOBAL_PREVIEW_PROVIDER_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let _reset = ResetMath;
struct MockAsyncMathProvider {
ready: RwLock<HashMap<String, MathRenderSlot>>,
}
impl MathPreviewProvider for MockAsyncMathProvider {
fn render_math(
&self,
latex: &str,
_display: bool,
_font_size_pt: f32,
_color: ui::Hsla,
_dpr: f32,
) -> MathRenderResult {
if let Some(slot) = self.ready.read().unwrap().get(latex.trim()) {
MathRenderResult::Ready(slot.clone())
} else {
MathRenderResult::Pending
}
}
}
let provider = Arc::new(MockAsyncMathProvider {
ready: RwLock::new(HashMap::new()),
});
register_math_preview_provider(Some(provider.clone()));
let session = MobileSession::open(390, 844, PlaygroundTheme::Light);
session.edit(|page| {
page.add_block(
"math-a",
BlockSpec::Latex {
latex: r"E = mc^2".into(),
},
Some("showcase-note"),
Some(0),
8_000_000,
)
.expect("math-a");
page.add_block(
"math-b",
BlockSpec::Latex {
latex: r"\frac{1}{2}".into(),
},
Some("showcase-note"),
Some(1),
8_000_001,
)
.expect("math-b");
});
let _ = session.frame();
let dummy_img = rgba_pixels_to_render_image(8, 4, &[20_u8; 8 * 4 * 4]).expect("render image");
provider.ready.write().unwrap().insert(
r"E = mc^2".to_string(),
MathRenderSlot {
image: dummy_img.clone(),
width_pt: 48.0,
ascent_pt: 14.0,
descent_pt: 4.0,
},
);
bump_latex_formula_revision(r"E = mc^2");
// Delivering `math-a` must re-layout ONLY `math-a` (1 block laid out; `math-b` & siblings reused).
let laid_out_a = session.app.update(|cx| {
session
.window
.update(cx, |v, w, _| {
let col_w = page_geometry(f32::from(w.viewport_size().width)).column_width;
v.ensure_layout(col_w, w).unwrap().stats.laid_out
})
.unwrap()
});
assert_eq!(
laid_out_a, 1,
"worker completion for formula A must re-layout only block A"
);
// Rapidly edit `math-b` from `\frac{1}{2}` to `\sqrt{2}`, then deliver stale `\frac{1}{2}` late.
session.edit(|page| {
page.set_block_prop(
"math-b",
"prop:latex",
y_octo::SessionValue::Any(Any::String(r"\sqrt{2}".into())),
8_000_010,
)
.expect("edit math-b");
});
let _ = session.frame();
provider.ready.write().unwrap().insert(
r"\frac{1}{2}".to_string(),
MathRenderSlot {
image: dummy_img,
width_pt: 24.0,
ascent_pt: 18.0,
descent_pt: 12.0,
},
);
bump_latex_formula_revision(r"\frac{1}{2}");
let (laid_out_stale, plain_b) = session.app.update(|cx| {
session
.window
.update(cx, |v, w, _| {
let col_w = page_geometry(f32::from(w.viewport_size().width)).column_width;
let layout = v.ensure_layout(col_w, w).unwrap();
let b_plain = layout.block("math-b").unwrap().body.plain.clone();
(layout.stats.laid_out, b_plain)
})
.unwrap()
});
register_math_preview_provider(None);
assert_eq!(
laid_out_stale, 0,
"late stale worker reply for superseded formula must trigger 0 block relayouts"
);
assert_eq!(plain_b, r"\sqrt{2}");
}
#[test]
fn edgeless_note_and_text_relayout_when_async_math_preview_arrives() {
struct ResetMath;
impl Drop for ResetMath {
fn drop(&mut self) {
register_math_preview_provider(None);
}
}
let _provider_lock = crate::GLOBAL_PREVIEW_PROVIDER_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let _reset = ResetMath;
struct MockAsyncMath {
ready: RwLock<HashMap<String, MathRenderSlot>>,
}
impl MathPreviewProvider for MockAsyncMath {
fn render_math(
&self,
latex: &str,
_display: bool,
_font_size_pt: f32,
_color: ui::Hsla,
_dpr: f32,
) -> MathRenderResult {
if let Some(slot) = self.ready.read().unwrap().get(latex.trim()) {
MathRenderResult::Ready(slot.clone())
} else {
MathRenderResult::Pending
}
}
}
let provider = Arc::new(MockAsyncMath {
ready: RwLock::new(HashMap::new()),
});
register_math_preview_provider(Some(provider.clone()));
let session = MobileSession::open(800, 600, PlaygroundTheme::Light);
session.edit(|page| {
page.add_block(
"eg-math",
BlockSpec::Latex {
latex: r"\sum_{i=1}^n i".into(),
},
Some("showcase-edgeless-note"),
Some(0),
9_000_001,
)
.expect("add edgeless note math");
page.add_block(
"et-math",
BlockSpec::Latex {
latex: r"\alpha + \beta".into(),
},
Some("showcase-edgeless-text"),
Some(0),
9_000_002,
)
.expect("add edgeless text math");
});
session.app.update(|cx| {
session
.window
.update(cx, |v, w, cx| {
v.set_mode(crate::PlaygroundMode::Edgeless, w, cx);
})
.unwrap();
});
let _ = session.frame();
// Steady Edgeless frame with no changes must do 0 relayouts.
let _ = session.frame();
assert_eq!(session.view(|v| v.edgeless.last_frame_relayouts), 0);
// Deliver async worker result ONLY for `eg-math` (without bumping doc_rev or env_rev!).
let img = rgba_pixels_to_render_image(32, 16, &[40_u8; 32 * 16 * 4]).expect("math img");
provider.ready.write().unwrap().insert(
r"\sum_{i=1}^n i".to_string(),
MathRenderSlot {
image: img,
width_pt: 96.0,
ascent_pt: 28.0,
descent_pt: 12.0,
},
);
bump_latex_formula_revision(r"\sum_{i=1}^n i");
session.app.update(|cx| {
session.window.update(cx, |_, _, cx| cx.notify()).unwrap();
});
let _ = session.frame();
let note_relayouts = session.view(|v| v.edgeless.last_frame_relayouts);
assert_eq!(
note_relayouts, 1,
"Edgeless Note must relayout when async math preview arrives"
);
// Deliver async worker result ONLY for `et-math` inside `EdgelessText`!
let img_et = rgba_pixels_to_render_image(28, 14, &[60_u8; 28 * 14 * 4]).expect("et math img");
provider.ready.write().unwrap().insert(
r"\alpha + \beta".to_string(),
MathRenderSlot {
image: img_et,
width_pt: 84.0,
ascent_pt: 20.0,
descent_pt: 8.0,
},
);
bump_latex_formula_revision(r"\alpha + \beta");
session.app.update(|cx| {
session.window.update(cx, |_, _, cx| cx.notify()).unwrap();
});
let _ = session.frame();
let text_relayouts = session.view(|v| v.edgeless.last_frame_relayouts);
register_math_preview_provider(None);
assert_eq!(
text_relayouts, 1,
"EdgelessText must also relayout when async math preview arrives"
);
}
#[test]
fn non_active_workspace_page_body_edit_invalidates_default_doc_directory() {
use blocksuite_editor::WorkspaceDocDirectory as _;
let session = MobileSession::open(390, 844, PlaygroundTheme::Light);
let ref_id = blocksuite_editor::EditorDocId::new("doc:edgeless-notes");
let before = session
.view(|v| v.default_doc_directory.doc_preview(&ref_id))
.expect("initial preview for non-active workspace page");
// Mutate ONLY the body of the non-active page (`doc:edgeless-notes`), keeping its title unchanged!
session.app.update(|cx| {
session
.window
.update(cx, |v, _, cx| {
let peer_page = v
.state
.workspace
.page_mut("doc:edgeless-notes")
.expect("non-active page");
peer_page
.add_block(
"remote-body-p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Fresh collaborator body update".into(),
},
Some("edgeless-notes-note"),
Some(0),
9_100_000,
)
.or_else(|_| {
peer_page.add_block(
"edgeless-notes-root",
BlockSpec::Page {
title: "Edgeless notes".into(),
},
None,
None,
9_100_001,
)?;
peer_page.add_block(
"edgeless-notes-note",
BlockSpec::Note { xywh: None },
Some("edgeless-notes-root"),
None,
9_100_002,
)?;
peer_page.add_block(
"remote-body-p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Fresh collaborator body update".into(),
},
Some("edgeless-notes-note"),
Some(0),
9_100_003,
)
})
.expect("mutate non-active page body");
v.refresh_document();
cx.notify();
})
.unwrap();
});
let after = session
.view(|v| v.default_doc_directory.doc_preview(&ref_id))
.expect("updated preview");
assert!(
after.snippet.contains("Fresh collaborator body update"),
"non-active page snippet must refresh on body edit, got {:?}",
after.snippet
);
assert!(
after.revision > before.revision,
"non-active page preview revision must increment ({} -> {})",
before.revision,
after.revision
);
// Subsequent local edit on active `HOME_PAGE_ID` must NOT bump `doc:edgeless-notes` revision!
session.edit(|page| {
page.insert_text("showcase-h1", "prop:text", 0, "!", 9_100_010)
.expect("local active edit");
});
let after_local = session
.view(|v| v.default_doc_directory.doc_preview(&ref_id))
.unwrap();
assert_eq!(after_local.revision, after.revision);
// Pure Yjs text deletion from a remote collaborator leaves `encode_state_vector_v1()`
// byte-for-byte unchanged, yet MUST still invalidate the cached non-active page excerpt!
session.app.update(|cx| {
session
.window
.update(cx, |v, _, cx| {
let full_state = v
.state
.workspace
.page("doc:edgeless-notes")
.expect("non-active page")
.encode_update_v1()
.expect("encode non-active page");
let mut remote_peer = blocksuite_playground_doc::session::PageDocSession::new(
"doc:edgeless-notes",
999_777,
)
.expect("remote peer");
remote_peer
.apply_remote_update_v1(&full_state)
.expect("sync remote peer");
let del_len = "Fresh collaborator body update".encode_utf16().count() as u64;
let del_commit = remote_peer
.remove_text("remote-body-p1", "prop:text", 0, del_len, 9_100_020)
.expect("remove text")
.expect("delete commit");
let local_page = v
.state
.workspace
.page_mut("doc:edgeless-notes")
.expect("non-active page mut");
let sv_before = local_page.encode_state_vector_v1().expect("sv before");
local_page
.apply_remote_update_v1(&del_commit.update)
.expect("apply pure delete update");
let sv_after = local_page.encode_state_vector_v1().expect("sv after");
assert_eq!(
sv_before, sv_after,
"pure Yjs deletion must not advance state vector"
);
v.refresh_document();
cx.notify();
})
.unwrap();
});
let after_del = session
.view(|v| v.default_doc_directory.doc_preview(&ref_id))
.expect("preview after pure delete");
assert!(
!after_del.snippet.contains("Fresh collaborator body update"),
"deleted paragraph text must not linger in non-active page snippet: {:?}",
after_del.snippet
);
assert!(
after_del.revision > after_local.revision,
"pure delete on non-active page must advance preview revision ({} -> {})",
after_local.revision,
after_del.revision
);
}
#[test]
#[ignore = "offscreen PNG evidence generator for mobile keyboard toolbar"]
fn render_mobile_keyboard_toolbar_evidence() {
let out_dir = std::env::var("KEYBOARD_TOOLBAR_OUT_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| std::path::PathBuf::from("target/keyboard-toolbar-after"));
std::fs::create_dir_all(&out_dir).expect("create out_dir");
let build_doc = |title: &str| {
let mut state = DocState::new("kb-toolbar", 77).expect("doc");
state
.workspace
.create_page(HOME_PAGE_ID, title, 1)
.expect("page");
let page = state.workspace.ensure_page(HOME_PAGE_ID).expect("page");
page.add_block(
"p-root",
BlockSpec::Page {
title: title.into(),
},
None,
None,
1,
)
.unwrap();
page.add_block("p-surface", BlockSpec::Surface, Some("p-root"), None, 2)
.unwrap();
page.add_block(
"p-note",
BlockSpec::Note { xywh: None },
Some("p-root"),
None,
3,
)
.unwrap();
page.add_block(
"p-body",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Select text to open Aa formatting and highlight colors.".into(),
},
Some("p-note"),
None,
4,
)
.unwrap();
page.add_block(
"p-tbl",
BlockSpec::Table {
rows: vec![
vec!["Task".into(), "Status".into()],
vec!["KeyboardToolbar".into(), "Parity".into()],
],
},
Some("p-note"),
None,
5,
)
.unwrap();
state
};
for (w, h, tag) in [(390, 844, "390"), (320, 568, "320")] {
for (theme, tname) in [
(PlaygroundTheme::Light, "light"),
(PlaygroundTheme::Dark, "dark"),
] {
let s = MobileSession::open(w, h, theme);
let doc = build_doc("Mobile Keyboard Toolbar");
s.app.update(|cx| {
s.window
.update(cx, |v, _, cx| {
v.set_image_picker(Some(std::rc::Rc::new(|| {})));
v.set_document(doc, cx);
})
.unwrap();
});
s.frame();
s.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"p-body", 0,
))));
s.overlay(OverlayEvent::SetKeyboardToolbarVisible(true));
s.save_png(
&out_dir.join(format!("after-{tag}-01-default-{tname}.png")),
&format!("after-{tag}-01-default-{tname}"),
);
if theme == PlaygroundTheme::Light {
s.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
s.save_png(
&out_dir.join(format!("after-{tag}-02-more-panel.png")),
&format!("after-{tag}-02-more-panel"),
);
s.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleMorePanel,
));
s.overlay(OverlayEvent::SetSelection(Some(ActiveSelection {
block_id: "p-body".into(),
start_utf16: 0,
end_utf16: 11,
})));
s.save_png(
&out_dir.join(format!("after-{tag}-03-autoshow-aa.png")),
&format!("after-{tag}-03-autoshow-aa"),
);
s.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::ToggleHighlightPanel,
));
s.save_png(
&out_dir.join(format!("after-{tag}-04-highlight-panel.png")),
&format!("after-{tag}-04-highlight-panel"),
);
s.overlay(OverlayEvent::FocusTableCell {
block_id: "p-tbl".into(),
row_id: "row-1".into(),
column_id: "col-0".into(),
screen_pos: None,
});
s.overlay(OverlayEvent::SetKeyboardToolbarVisible(true));
s.save_png(
&out_dir.join(format!("after-{tag}-05-table-disabled.png")),
&format!("after-{tag}-05-table-disabled"),
);
s.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"p-body", 0,
))));
s.overlay(OverlayEvent::KeyboardToolbar(
KeyboardToolbarAction::Bookmark,
));
s.platform
.advance_clock(std::time::Duration::from_millis(200));
s.type_into_field("https://affine.pro");
s.save_png(
&out_dir.join(format!("after-{tag}-06-bookmark-prompt.png")),
&format!("after-{tag}-06-bookmark-prompt"),
);
}
}
}
}
@@ -0,0 +1,757 @@
//! Surgical PDF attachment single-block relayout and two-peer `RoomHub` SHA-256
//! picked-image blob upload/fetch verification tests.
use std::sync::Arc;
use blocksuite_playground_doc::{
client_id_from_seed,
schema::{BlockSpec, ParagraphType},
};
use ui::{point, px};
use crate::{
DocState, HOME_PAGE_ID, PlaygroundTheme,
block_flow::{
PdfPageCount, PdfPageProvider, PdfPreviewPage, page_geometry, register_pdf_page_provider,
rgba_pixels_to_render_image,
},
overlays::{ActiveSelection, OverlayEvent},
room_client::RoomStatus,
};
use super::tests::MobileSession;
#[test]
fn pdf_attachment_render_and_page_flip_relayout_only_target_block() {
struct ResetPdf;
impl Drop for ResetPdf {
fn drop(&mut self) {
register_pdf_page_provider(None);
}
}
let _provider_lock = crate::GLOBAL_PREVIEW_PROVIDER_TEST_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let _reset = ResetPdf;
struct TwoPageMockPdfProvider;
impl PdfPageProvider for TwoPageMockPdfProvider {
fn page_count(&self, _key: &str, _bytes: &[u8]) -> PdfPageCount {
PdfPageCount::Ready(2)
}
fn render_pdf_page(
&self,
_key: &str,
_bytes: &[u8],
page_index: usize,
_scale: f32,
) -> Option<PdfPreviewPage> {
let shade = if page_index == 0 { 40_u8 } else { 180_u8 };
let image = rgba_pixels_to_render_image(24, 16, &[shade; 24 * 16 * 4])?;
Some(PdfPreviewPage {
page_index: page_index.min(1),
page_count: 2,
image,
width_pt: 240.0,
height_pt: 160.0,
})
}
}
register_pdf_page_provider(Some(Arc::new(TwoPageMockPdfProvider)));
let session = MobileSession::open(390, 844, PlaygroundTheme::Light);
session.app.update(|cx| {
session
.window
.update(cx, |v, _, cx| {
v.state
.blobs
.insert("blob-pdf-1".into(), Arc::new(b"%PDF-mock-1".to_vec()));
v.state
.blobs
.insert("blob-pdf-2".into(), Arc::new(b"%PDF-mock-2".to_vec()));
let page = v.state.workspace.page_mut(HOME_PAGE_ID).unwrap();
for (id, src) in [("pdf-att-1", "blob-pdf-1"), ("pdf-att-2", "blob-pdf-2")] {
page.add_block(
id,
BlockSpec::Attachment {
name: format!("{id}.pdf"),
size: 128,
mime_type: "application/pdf".into(),
source_id: src.into(),
embed: true,
caption: String::new(),
},
Some("showcase-note"),
Some(0),
9_200_000,
)
.unwrap();
}
v.doc_rev += 1;
v.refresh_document();
cx.notify();
})
.unwrap();
});
let _ = session.frame();
// Flip ONLY `pdf-att-1` to page 2 (`delta = +1`): sibling paragraph & `pdf-att-2` must stay cached!
session.overlay(OverlayEvent::AttachmentPdfPage {
block_id: "pdf-att-1".into(),
delta: 1,
});
let stats = session.app.update(|cx| {
session
.window
.update(cx, |v, w, _| {
let col_w = page_geometry(f32::from(w.viewport_size().width)).column_width;
v.ensure_layout(col_w, w).unwrap().stats
})
.unwrap()
});
register_pdf_page_provider(None);
assert_eq!(
stats.laid_out, 1,
"flipping one PDF attachment page must relayout ONLY that 1 attachment block, got {stats:?}"
);
assert!(
stats.reused >= 2,
"sibling paragraphs and second PDF attachment must be reused, got {stats:?}"
);
}
#[test]
fn picked_image_uploads_sha256_blob_to_relay_and_renders_on_second_peer() {
use ui::{AppContext as _, Application, HeadlessPlatform, WindowOptions, size};
let runtime = crate::tests::relay_runtime();
let addr = crate::tests::start_relay(&runtime);
let room_name = "picked-image-sync";
let mut seeder = crate::tests::relay_page_peer(room_name, client_id_from_seed(88));
let _seeder_socket = crate::tests::join_as_peer(&runtime, addr, room_name, &mut seeder);
let relay_url = format!("ws://{addr}");
let make_peer = || {
let platform = HeadlessPlatform::new(390, 844, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let cfg = crate::RoomConfig::new(room_name, Some(&relay_url));
let win = app
.update(|cx| {
cx.open_window(
WindowOptions {
window_bounds: Some(ui::WindowBounds::Windowed(ui::Bounds::new(
point(px(0.0), px(0.0)),
size(px(390.0), px(844.0)),
))),
..Default::default()
},
|_, cx| {
cx.new(|cx| {
crate::PlaygroundView::with_options(
crate::PlaygroundOptions {
room: Some(cfg),
..Default::default()
},
cx,
)
})
},
)
})
.unwrap();
(platform, app, win)
};
let (plat_a, app_a, win_a) = make_peer();
let (plat_b, app_b, win_b) = make_peer();
let pump_both = || {
for (plat, app, win) in [(&plat_a, &app_a, &win_a), (&plat_b, &app_b, &win_b)] {
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.pump_room(cx);
})
.unwrap();
});
plat.run_until_parked();
}
};
for _ in 0..300 {
pump_both();
let ready_a = app_a.update(|cx| {
win_a
.read_with(cx, |v, _| {
v.room_status() == Some(RoomStatus::Live)
&& v.page_snapshot().is_some_and(|s| s.block("p-1").is_some())
})
.unwrap()
});
let ready_b = app_b.update(|cx| {
win_b
.read_with(cx, |v, _| {
v.room_status() == Some(RoomStatus::Live)
&& v.page_snapshot().is_some_and(|s| s.block("p-1").is_some())
})
.unwrap()
});
if ready_a && ready_b {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let png = super::tests::encode_test_png(12, 8);
app_a.update(|cx| {
win_a
.update(cx, |v, w, cx| {
v.dispatch_overlay(
OverlayEvent::SetSelection(Some(ActiveSelection::caret("p-1", 0))),
w,
cx,
);
v.dispatch_overlay(
OverlayEvent::InsertImageBytes {
bytes: png.clone(),
caption: "Synced photo".into(),
},
w,
cx,
);
})
.unwrap();
});
let mut peer_b_ready = false;
for _ in 0..250 {
plat_b.advance_clock(std::time::Duration::from_millis(600));
app_b.update(|cx| {
win_b
.update(cx, |v, _, cx| {
v.tick_room(cx);
v.pump_room(cx);
})
.unwrap();
});
pump_both();
peer_b_ready = app_b.update(|cx| {
win_b
.read_with(cx, |v, _| {
v.page_snapshot()
.and_then(|s| s.block("note").cloned())
.is_some_and(|note| {
note.children.iter().any(|c| match &c.content {
blocksuite_playground_doc::read::BlockContent::Image {
source_id,
caption,
..
} if caption == "Synced photo" => matches!(
v.images.get(source_id),
Some(crate::block_flow::ImageSlot::Ready(_))
),
_ => false,
})
})
})
.unwrap()
});
if peer_b_ready {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
peer_b_ready,
"second room peer must receive uploaded SHA-256 image blob and decode ImageSlot::Ready"
);
}
#[test]
fn transient_503_blob_upload_retries_and_delivers_original_bytes_to_peer() {
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use ui::{AppContext as _, Application, HeadlessPlatform, WindowOptions, size};
let runtime = crate::tests::relay_runtime();
let hub_addr = crate::tests::start_relay(&runtime);
let room_name = "sync-503-room";
let mut seeder = crate::tests::relay_page_peer(room_name, client_id_from_seed(77));
let _seeder_socket = crate::tests::join_as_peer(&runtime, hub_addr, room_name, &mut seeder);
// Fault-injecting TCP proxy: fails the FIRST `PUT` with `503 Service Unavailable`,
// and forwards all WebSocket upgrades + subsequent `PUT`/`GET` requests to `hub_addr`.
let put_attempts = Arc::new(AtomicUsize::new(0));
let put_attempts_proxy = put_attempts.clone();
let proxy_addr = runtime.block_on(async move {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
while let Ok((mut client, _)) = listener.accept().await {
let attempts = put_attempts_proxy.clone();
tokio::spawn(async move {
let mut prefix = Vec::with_capacity(1024);
let mut tmp = [0_u8; 1024];
loop {
let Ok(n) = client.read(&mut tmp).await else {
return;
};
if n == 0 {
return;
}
prefix.extend_from_slice(&tmp[..n]);
if prefix.windows(4).any(|w| w == b"\r\n\r\n") || prefix.len() >= 4096 {
break;
}
}
if prefix.starts_with(b"PUT ") && attempts.fetch_add(1, Ordering::SeqCst) == 0 {
let _ = client
.write_all(
b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
)
.await;
let _ = client.shutdown().await;
return;
}
let Ok(mut upstream) = tokio::net::TcpStream::connect(hub_addr).await else {
return;
};
if upstream.write_all(&prefix).await.is_err() {
return;
}
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
});
}
});
addr
});
let open_peer = |relay_url: String| {
let platform = HeadlessPlatform::new(390, 844, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|cx| {
crate::register_bundled_fonts(cx).unwrap();
});
let cfg = crate::RoomConfig::new(room_name, Some(&relay_url));
let win = app
.update(|cx| {
cx.open_window(
WindowOptions {
window_bounds: Some(ui::WindowBounds::Windowed(ui::Bounds::new(
point(px(0.0), px(0.0)),
size(px(390.0), px(844.0)),
))),
..Default::default()
},
|_, cx| {
cx.new(|cx| {
crate::PlaygroundView::with_options(
crate::PlaygroundOptions {
room: Some(cfg),
..Default::default()
},
cx,
)
})
},
)
})
.unwrap();
(platform, app, win)
};
let (plat_a, app_a, win_a) = open_peer(format!("ws://{proxy_addr}"));
let (plat_b, app_b, win_b) = open_peer(format!("ws://{hub_addr}"));
let pump_both = || {
for (plat, app, win) in [(&plat_a, &app_a, &win_a), (&plat_b, &app_b, &win_b)] {
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.pump_room(cx);
})
.unwrap();
});
plat.run_until_parked();
}
};
for _ in 0..300 {
pump_both();
let ready = [(&app_a, &win_a), (&app_b, &win_b)]
.into_iter()
.all(|(app, win)| {
app.update(|cx| {
win.read_with(cx, |v, _| {
v.room_status() == Some(RoomStatus::Live)
&& v.page_snapshot().is_some_and(|s| s.block("p-1").is_some())
})
.unwrap()
})
});
if ready {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
let png = super::tests::encode_test_png(10, 6);
app_a.update(|cx| {
win_a
.update(cx, |v, w, cx| {
v.dispatch_overlay(
OverlayEvent::SetSelection(Some(ActiveSelection::caret("p-1", 0))),
w,
cx,
);
v.dispatch_overlay(
OverlayEvent::InsertImageBytes {
bytes: png.clone(),
caption: "Recovered after 503".into(),
},
w,
cx,
);
})
.unwrap();
});
let mut recovered_on_b = false;
for _ in 0..250 {
for (plat, app, win) in [(&plat_a, &app_a, &win_a), (&plat_b, &app_b, &win_b)] {
plat.advance_clock(std::time::Duration::from_millis(600));
app.update(|cx| {
win.update(cx, |v, _, cx| {
v.tick_room(cx);
v.pump_room(cx);
})
.unwrap();
});
plat.run_until_parked();
}
recovered_on_b = app_b.update(|cx| {
win_b
.read_with(cx, |v, _| {
v.page_snapshot()
.and_then(|s| s.block("note").cloned())
.is_some_and(|note| {
note.children.iter().any(|c| match &c.content {
blocksuite_playground_doc::read::BlockContent::Image {
source_id,
caption,
..
} if caption == "Recovered after 503" => {
matches!(
v.images.get(source_id),
Some(crate::block_flow::ImageSlot::Ready(_))
) && v
.state
.blobs
.get(source_id)
.is_some_and(|b| b.as_slice() == png.as_slice())
}
_ => false,
})
})
})
.unwrap()
});
if recovered_on_b && put_attempts.load(Ordering::SeqCst) >= 2 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(25));
}
assert!(
put_attempts.load(Ordering::SeqCst) >= 2,
"uploader must retry after initial 503 (attempts={})",
put_attempts.load(Ordering::SeqCst)
);
assert!(
recovered_on_b,
"second peer must fetch exact original PNG bytes once uploader recovers from initial 503"
);
let upload_queue_empty = app_a.update(|cx| {
win_a
.read_with(cx, |v, _| v.blob_uploads.is_empty())
.unwrap()
});
assert!(
upload_queue_empty,
"blob_uploads must clear once retry succeeds"
);
}
#[test]
fn legacy_33mib_bmp_decodes_from_relay_while_picker_admission_caps_at_32mib() {
// 3000 x 2890 x 4 bytes = 34,680,000 bytes + 54-byte BMP header = 34,680,054 bytes (~33.07 MiB).
let width: u32 = 3000;
let height: u32 = 2890;
let pixel_bytes = (width as usize) * (height as usize) * 4;
let file_size = 54 + pixel_bytes;
assert!(file_size > 32 * 1024 * 1024 && file_size <= 64 * 1024 * 1024);
let mut bmp = vec![0_u8; file_size];
bmp[0..2].copy_from_slice(b"BM");
bmp[2..6].copy_from_slice(&(file_size as u32).to_le_bytes());
bmp[10..14].copy_from_slice(&54_u32.to_le_bytes());
bmp[14..18].copy_from_slice(&40_u32.to_le_bytes());
bmp[18..22].copy_from_slice(&(width as i32).to_le_bytes());
bmp[22..26].copy_from_slice(&(height as i32).to_le_bytes());
bmp[26..28].copy_from_slice(&1_u16.to_le_bytes());
bmp[28..30].copy_from_slice(&32_u16.to_le_bytes());
bmp[34..38].copy_from_slice(&(pixel_bytes as u32).to_le_bytes());
for px_chunk in bmp[54..54 + 4096].chunks_exact_mut(4) {
px_chunk.copy_from_slice(&[0x40, 0x80, 0xC0, 0xFF]);
}
assert!(
crate::block_flow::decode_image(&bmp).is_some(),
"existing 33 MiB BMP blob within relay's 64 MiB limit must decode cleanly"
);
let s = super::tests::MobileSession::open(390, 844, PlaygroundTheme::Light);
let initial_children = s
.view(|v| {
v.page_snapshot()
.and_then(|snap| snap.block("showcase-note"))
.map(|n| n.children.len())
})
.unwrap();
s.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret(
"showcase-p1",
0,
))));
s.overlay(OverlayEvent::InsertImageBytes {
bytes: bmp,
caption: "Oversized pick".into(),
});
let after_children = s
.view(|v| {
v.page_snapshot()
.and_then(|snap| snap.block("showcase-note"))
.map(|n| n.children.len())
})
.unwrap();
assert_eq!(
after_children, initial_children,
"picker admission must continue rejecting > 32 MiB uploads"
);
}
#[test]
fn surface_ref_relayouts_single_block_on_whiteboard_edit_and_clips_under_edgeless_zoom() {
use blocksuite_playground_doc::schema::SurfaceElementSpec;
let s = super::tests::MobileSession::open(800, 640, PlaygroundTheme::Light);
let mut state = DocState::new("surf-ref-test", 123).unwrap();
state
.workspace
.create_page(HOME_PAGE_ID, "SurfaceRef Parity", 1)
.unwrap();
{
let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap();
page.add_block(
"root",
BlockSpec::Page {
title: "SurfaceRef Parity".into(),
},
None,
None,
1,
)
.unwrap();
page.add_block("surf", BlockSpec::Surface, Some("root"), None, 2)
.unwrap();
page.add_block(
"frame-1",
BlockSpec::Frame {
title: "Initial Frame".into(),
xywh: Some("[0,0,400,200]".into()),
presentation_index: Some("a0".into()),
},
Some("surf"),
None,
3,
)
.unwrap();
page.add_surface_element(
"surf",
"shape-red",
"a1",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[40,30,320,140]".into(),
seed: 42,
filled: true,
text: None,
},
4,
)
.unwrap();
page.set_surface_element_field(
"surf",
"shape-red",
"fillColor",
y_octo::SessionValue::Any(y_octo::Any::String("#e53935".into())),
4,
)
.unwrap();
page.add_block(
"note",
BlockSpec::Note {
xywh: Some("[600,320,448,360]".into()),
},
Some("root"),
None,
5,
)
.unwrap();
page.add_block(
"p-before",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Sibling before".into(),
},
Some("note"),
None,
6,
)
.unwrap();
page.add_block(
"sref-1",
BlockSpec::SurfaceRef {
reference: "frame-1".into(),
ref_flavour: "affine:frame".into(),
caption: String::new(),
},
Some("note"),
None,
7,
)
.unwrap();
page.add_block(
"p-after",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Sibling after".into(),
},
Some("note"),
None,
8,
)
.unwrap();
}
s.app.update(|cx| {
s.window
.update(cx, |v, _, cx| v.set_document(state, cx))
.unwrap();
});
let _ = s.frame();
let render_window_image = || {
s.app
.update(|cx| {
s.window
.update(cx, |_, window, _| window.render_to_image())
.unwrap()
})
.expect("render image")
};
// E3: Mutate the referenced whiteboard shape color + frame title while staying in Page mode:
// ONLY `sref-1` (`laid_out == 1`) must relayout, sibling paragraphs must hit cache (`reused >= 2`),
// and the card title + rendered pixels must update immediately!
let page_img_before = render_window_image();
s.edit(|page| {
page.set_block_title_text("frame-1", "Renamed Architecture Frame", 10)
.unwrap();
page.set_surface_element_field(
"surf",
"shape-red",
"fillColor",
y_octo::SessionValue::Any(y_octo::Any::String("#1e88e5".into())),
11,
)
.unwrap();
});
let _ = s.frame();
let (stats, card_plain) = s.view(|v| {
let layout = v.flow_layout().unwrap();
let plain = layout
.blocks
.iter()
.find(|b| b.block_id == "sref-1")
.unwrap()
.body
.plain
.clone();
(layout.stats, plain)
});
assert_eq!(
stats.laid_out, 1,
"whiteboard shape/frame edit must relayout ONLY the SurfaceRef block, got {stats:?}"
);
assert!(
stats.reused >= 2,
"sibling paragraphs must reuse cached bodies"
);
assert_eq!(card_plain, "Renamed Architecture Frame");
let page_img_after = render_window_image();
assert_ne!(
page_img_before.as_raw(),
page_img_after.as_raw(),
"SurfaceRef thumbnail pixels must update when referenced shape fillColor changes"
);
// E2: Switch to Edgeless mode with camera pan & zoom != 1.0 (`0.55x`) so `note` sits shifted
// away from its world `[600, 320]` coords: `Prim::Surface` inside `note` MUST clip via
// `with_local_paint_mask` so the blue `#1e88e5` shape inside `sref-1` renders visibly!
s.app.update(|cx| {
s.window
.update(cx, |v, w, cx| {
v.set_mode(crate::PlaygroundMode::Edgeless, w, cx);
v.edgeless.camera =
blocksuite_editor::edgeless::EdgelessCamera::new(500.0, 220.0, 0.55);
v.edgeless.camera_initialized = true;
cx.notify();
})
.unwrap();
});
let _ = s.frame();
let edgeless_img = render_window_image();
let dpr = 1.0_f32;
// Note world `[600, 320]` at camera `(500, 220, 0.55)` starts at screen `x = (600-500)*0.55 = 55`,
// `y = 53 + (320-220)*0.55 = 108` (well away from raw world `[600, 320]`!).
// Scan the note's screen region `[40..340] x [100..360]` for the `#1e88e5` blue shape inside `sref-1`.
let w_px = edgeless_img.width();
let raw = edgeless_img.as_raw();
let mut blue_pixels_in_note = 0usize;
for py in ((100.0 * dpr) as u32)..((360.0 * dpr) as u32).min(edgeless_img.height()) {
for px_x in ((40.0 * dpr) as u32)..((340.0 * dpr) as u32).min(w_px) {
let idx = ((py * w_px + px_x) * 4) as usize;
// BGRA or RGBA check: blue channel dominant (`#1e88e5` -> R=30, G=136, B=229).
let (c0, c1, c2) = (raw[idx], raw[idx + 1], raw[idx + 2]);
let is_blue =
(c2 >= 180 && c1 >= 90 && c0 <= 80) || (c0 >= 180 && c1 >= 90 && c2 <= 80);
if is_blue {
blue_pixels_in_note += 1;
}
}
}
assert!(
blue_pixels_in_note >= 100,
"SurfaceRef inside Edgeless Note at 0.55x zoom must render its shape pixels (found {blue_pixels_in_note})"
);
if let Ok(png_path) = std::env::var("EDGELESS_SURFACE_REF_PNG") {
s.save_png(
std::path::Path::new(&png_path),
"edgeless-surface-ref-055x-zoom",
);
}
}
@@ -1,21 +1,18 @@
//! In-place live `Y.Text` editing glue for `affine:table` cells on [`PlaygroundView`].
use std::{ops::Range, rc::Rc};
mod paint;
use std::rc::Rc;
use blocksuite_editor::inline_input::{TextSplice, utf16_len};
use blocksuite_playground_doc::{
read::{BlockContent, TableCell, TableData},
session::split_delta,
};
use ui::{Bounds, Context, KeyDownEvent, Pixels, Point, Window, div, prelude::*, px};
use y_octo::{TextDeltaOp, TextInsert};
use blocksuite_playground_doc::read::{BlockContent, TableData};
use ui::{Context, KeyDownEvent, Window};
use crate::{
PlaygroundView, TOPBAR_HEIGHT,
block_flow::{FlowLayout, FlowRect, PAGE_SURFACE_ID, PageViewport, page_geometry},
block_flow::{FlowLayout, page_geometry},
edgeless::EdgelessInlineEdit,
overlays::InlineTableCell,
theme::Palette,
};
/// How [`PlaygroundView::finish_inline_targets`] handles any in-flight IME preedit.
@@ -133,7 +130,7 @@ impl PlaygroundView {
Self::find_table_cell_hit(&layout, &block_id, &row_id, &column_id)
&& let Some(cell) = self.table_cell.as_mut()
{
let local_x = sx - geom.column_x - bx;
let local_x = sx - geom.column_x - bx + self.overlays.code_scroll_x(&block_id);
let local_y = sy - TOPBAR_HEIGHT + self.scroll_y - by;
let off = hit
.hit_text(local_x, local_y, &cell.input.text)
@@ -187,7 +184,7 @@ impl PlaygroundView {
)
{
let geom = page_geometry(f32::from(window.viewport_size().width));
let local_x = sx - geom.column_x - bx;
let local_x = sx - geom.column_x - bx + self.overlays.code_scroll_x(&cell.block_id);
let local_y = sy - TOPBAR_HEIGHT + self.scroll_y - by;
let off = hit.hit_text(local_x, local_y, &initial).utf16_offset as usize;
cell.input.select(off..off);
@@ -569,230 +566,4 @@ impl PlaygroundView {
}
}
}
/// Splice any active table cell IME preedit into a cloned snapshot using `split_delta` so
/// all existing formatting marks (bold, code, link, chips) left and right of the preedit
/// stay 100% intact.
pub(crate) fn apply_table_cell_preedit_to_snapshot(
&self,
snapshot: &mut blocksuite_playground_doc::read::PageSnapshot,
) -> bool {
let Some(cell) = self.table_cell.as_ref() else {
return false;
};
let Some(pre) = cell.input.preedit.as_ref() else {
return false;
};
let Some(root) = snapshot.root.as_mut() else {
return false;
};
let display = cell.input.display_text();
let rep = pre.replacement.clone();
let pre_text = pre.text.as_str();
fn patch_node(
node: &mut blocksuite_playground_doc::read::BlockNode,
block_id: &str,
row_id: &str,
column_id: &str,
rep: &Range<usize>,
pre_text: &str,
display: &str,
) -> bool {
if node.id == block_id {
if let BlockContent::Table(table) = &mut node.content {
let entry = table
.cells
.entry((row_id.to_string(), column_id.to_string()))
.or_insert_with(|| TableCell {
text: blocksuite_playground_doc::read::RichText::default(),
});
let delta = if let Ok((mut before, rest)) =
split_delta(&entry.text.delta, rep.start as u64)
&& let Ok((_, after)) =
split_delta(&rest, (rep.end.saturating_sub(rep.start)) as u64)
{
if !pre_text.is_empty() {
before.push(TextDeltaOp::Insert {
insert: TextInsert::Text(pre_text.to_string()),
format: None,
});
}
before.extend(after);
before
} else if display.is_empty() {
Vec::new()
} else {
vec![TextDeltaOp::Insert {
insert: TextInsert::Text(display.to_string()),
format: None,
}]
};
entry.text = blocksuite_playground_doc::read::RichText {
plain: display.to_string(),
delta,
};
return true;
}
return false;
}
for child in &mut node.children {
if patch_node(child, block_id, row_id, column_id, rep, pre_text, display) {
return true;
}
}
false
}
patch_node(
root,
&cell.block_id,
&cell.row_id,
&cell.column_id,
&rep,
pre_text,
&display,
)
}
/// Map a screen-space pointer location to a UTF-16 offset inside the focused table cell.
pub(crate) fn table_cell_character_index_for_point(
&self,
p: Point<Pixels>,
w: &Window,
) -> Option<usize> {
let cell = self.table_cell.as_ref()?;
let layout = self.flow_layout()?;
let (bx, by, hit) =
Self::find_table_cell_hit(&layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
let geom = page_geometry(f32::from(w.viewport_size().width));
let local_x = f32::from(p.x) - geom.column_x - bx;
let local_y = f32::from(p.y) - TOPBAR_HEIGHT + self.scroll_y - by;
hit.rect.contains(local_x, local_y).then(|| {
hit.hit_text(local_x, local_y, &cell.input.display_text())
.utf16_offset as usize
})
}
/// Screen-space IME candidate bounds for the focused table cell.
pub(crate) fn table_cell_selection_bounds(
&self,
r: Range<usize>,
layout: &FlowLayout,
w: &Window,
) -> Vec<Bounds<Pixels>> {
let Some((bx, by, hit)) = self.table_cell.as_ref().and_then(|cell| {
Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)
}) else {
return Vec::new();
};
let (lh, ox, oy) = (
hit.text.line_height(),
bx + hit.text_origin.0,
by + hit.text_origin.1,
);
let mut rects: Vec<FlowRect> = hit
.text
.selection_spans(r.start, r.end)
.into_iter()
.map(|(line, a, b)| FlowRect::new(ox + a, oy + line as f32 * lh, (b - a).max(1.0), lh))
.collect();
if rects.is_empty() {
let (cx, line) = hit.text.caret(r.start);
rects.push(FlowRect::new(ox + cx, oy + line as f32 * lh, 1.5, lh));
}
rects.into_iter().map(|r| self.screen_rect(r, w)).collect()
}
/// In-place visual elements for a focused table cell: 1.5px brand focus border,
/// selection highlight band, IME preedit underline, and live caret.
pub(crate) fn table_cell_selection_elements(
&self,
layout: &FlowLayout,
v: PageViewport,
palette: &Palette,
) -> Vec<ui::AnyElement> {
let mut out = Vec::new();
let Some(cell) = self.table_cell.as_ref() else {
return out;
};
let Some((bx, by, hit)) =
Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)
else {
return out;
};
let cell_world = hit.rect.translated(bx, by);
if cell_world.bottom() < v.scroll_y || cell_world.y > v.scroll_y + v.height {
return out;
}
let mut ring = div()
.absolute()
.left(px(v.column_x + cell_world.x))
.top(px(cell_world.y - v.scroll_y))
.w(px(cell_world.w))
.h(px(cell_world.h))
.border(px(1.5))
.border_color(palette.brand);
if v.fully_visible(&cell_world) {
ring = ring
.snapshot("page.table_cell_focus", Some(PAGE_SURFACE_ID))
.snapshot_focused(true)
.snapshot_text(cell.input.display_text());
}
out.push(ring.into_any_element());
let lh = hit.text.line_height();
let ox = bx + hit.text_origin.0;
let oy = by + hit.text_origin.1;
let (sel, reversed) = cell.input.shown_selection();
let marked = cell.input.marked_range();
if let Some(marked) = &marked {
for (line, a, b) in hit.text.selection_spans(marked.start, marked.end) {
let y = oy + line as f32 * lh + lh - 1.0;
out.push(
div()
.absolute()
.left(px(v.column_x + ox + a))
.top(px(y - v.scroll_y))
.w(px((b - a).max(1.0)))
.h(px(1.0))
.bg(palette.text_secondary)
.into_any_element(),
);
}
} else if !sel.is_empty() {
let mut first = true;
for (line, a, b) in hit.text.selection_spans(sel.start, sel.end) {
let r = FlowRect::new(ox + a, oy + line as f32 * lh, (b - a).max(1.0), lh);
let mut d = div()
.absolute()
.left(px(v.column_x + r.x))
.top(px(r.y - v.scroll_y))
.w(px(r.w))
.h(px(r.h))
.bg(palette.brand.opacity(0.22));
if v.fully_visible(&r) && std::mem::take(&mut first) {
d = d.snapshot("page.selection", Some(PAGE_SURFACE_ID));
}
out.push(d.into_any_element());
}
}
let caret_u16 = if reversed { sel.start } else { sel.end };
let (cx_local, line) = hit.text.caret(caret_u16);
let caret_rect = FlowRect::new(ox + cx_local, oy + line as f32 * lh, 1.5, lh);
if caret_rect.bottom() >= v.scroll_y && caret_rect.y <= v.scroll_y + v.height {
let mut caret_el = div()
.absolute()
.left(px(v.column_x + caret_rect.x))
.top(px(caret_rect.y - v.scroll_y))
.w(px(1.5))
.h(px(caret_rect.h))
.bg(palette.brand);
if v.fully_visible(&caret_rect) {
caret_el = caret_el.snapshot("page.table_cell_caret", Some(PAGE_SURFACE_ID));
}
out.push(caret_el.into_any_element());
}
out
}
}
@@ -0,0 +1,278 @@
//! Table cell preedit snapshot patching, hit-testing, IME bounds, and focus/caret/selection painting.
use std::ops::Range;
use blocksuite_playground_doc::{
read::{BlockContent, TableCell},
session::split_delta,
};
use ui::{Bounds, Pixels, Point, Window, div, prelude::*, px};
use y_octo::{TextDeltaOp, TextInsert};
use crate::{
PlaygroundView, TOPBAR_HEIGHT,
block_flow::{FlowLayout, FlowRect, PAGE_SURFACE_ID, PageViewport, page_geometry},
theme::Palette,
};
impl PlaygroundView {
/// Splice any active table cell IME preedit into a cloned snapshot using `split_delta` so
/// all existing formatting marks (bold, code, link, chips) left and right of the preedit
/// stay 100% intact.
pub(crate) fn apply_table_cell_preedit_to_snapshot(
&self,
snapshot: &mut blocksuite_playground_doc::read::PageSnapshot,
) -> bool {
let Some(cell) = self.table_cell.as_ref() else {
return false;
};
let Some(pre) = cell.input.preedit.as_ref() else {
return false;
};
let Some(root) = snapshot.root.as_mut() else {
return false;
};
let display = cell.input.display_text();
let rep = pre.replacement.clone();
let pre_text = pre.text.as_str();
fn patch_node(
node: &mut blocksuite_playground_doc::read::BlockNode,
block_id: &str,
row_id: &str,
column_id: &str,
rep: &Range<usize>,
pre_text: &str,
display: &str,
) -> bool {
if node.id == block_id {
if let BlockContent::Table(table) = &mut node.content {
let entry = table
.cells
.entry((row_id.to_string(), column_id.to_string()))
.or_insert_with(|| TableCell {
text: blocksuite_playground_doc::read::RichText::default(),
});
let delta = if let Ok((mut before, rest)) =
split_delta(&entry.text.delta, rep.start as u64)
&& let Ok((_, after)) =
split_delta(&rest, (rep.end.saturating_sub(rep.start)) as u64)
{
if !pre_text.is_empty() {
before.push(TextDeltaOp::Insert {
insert: TextInsert::Text(pre_text.to_string()),
format: None,
});
}
before.extend(after);
before
} else if display.is_empty() {
Vec::new()
} else {
vec![TextDeltaOp::Insert {
insert: TextInsert::Text(display.to_string()),
format: None,
}]
};
entry.text = blocksuite_playground_doc::read::RichText {
plain: display.to_string(),
delta,
};
return true;
}
return false;
}
for child in &mut node.children {
if patch_node(child, block_id, row_id, column_id, rep, pre_text, display) {
return true;
}
}
false
}
patch_node(
root,
&cell.block_id,
&cell.row_id,
&cell.column_id,
&rep,
pre_text,
&display,
)
}
/// Map a screen-space pointer location to a UTF-16 offset inside the focused table cell,
/// accounting for any horizontal scroll offset of a wide table.
pub(crate) fn table_cell_character_index_for_point(
&self,
p: Point<Pixels>,
w: &Window,
) -> Option<usize> {
let cell = self.table_cell.as_ref()?;
let layout = self.flow_layout()?;
let (bx, by, hit) =
Self::find_table_cell_hit(&layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
let scroll_x = self.overlays.code_scroll_x(&cell.block_id);
let geom = page_geometry(f32::from(w.viewport_size().width));
let local_x = f32::from(p.x) - geom.column_x - bx + scroll_x;
let local_y = f32::from(p.y) - TOPBAR_HEIGHT + self.scroll_y - by;
hit.rect.contains(local_x, local_y).then(|| {
hit.hit_text(local_x, local_y, &cell.input.display_text())
.utf16_offset as usize
})
}
/// Screen-space IME candidate bounds for the focused table cell, accounting for horizontal
/// table scroll.
pub(crate) fn table_cell_selection_bounds(
&self,
r: Range<usize>,
layout: &FlowLayout,
w: &Window,
) -> Vec<Bounds<Pixels>> {
let Some((scroll_x, bx, by, hit)) = self.table_cell.as_ref().and_then(|cell| {
let scroll_x = self.overlays.code_scroll_x(&cell.block_id);
let (bx, by, hit) =
Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)?;
Some((scroll_x, bx, by, hit))
}) else {
return Vec::new();
};
let (lh, ox, oy) = (
hit.text.line_height(),
bx + hit.text_origin.0 - scroll_x,
by + hit.text_origin.1,
);
let mut rects: Vec<FlowRect> = hit
.text
.selection_spans(r.start, r.end)
.into_iter()
.map(|(line, a, b)| FlowRect::new(ox + a, oy + line as f32 * lh, (b - a).max(1.0), lh))
.collect();
if rects.is_empty() {
let (cx, line) = hit.text.caret(r.start);
rects.push(FlowRect::new(ox + cx, oy + line as f32 * lh, 1.5, lh));
}
rects.into_iter().map(|r| self.screen_rect(r, w)).collect()
}
/// In-place visual elements for a focused table cell: 1.5px brand focus border,
/// selection highlight band, IME preedit underline, and live caret (shifted by any
/// horizontal table scroll and clipped to the table viewport width).
pub(crate) fn table_cell_selection_elements(
&self,
layout: &FlowLayout,
v: PageViewport,
palette: &Palette,
) -> Vec<ui::AnyElement> {
let mut out = Vec::new();
let Some(cell) = self.table_cell.as_ref() else {
return out;
};
let Some(block) = layout.block(&cell.block_id) else {
return out;
};
let Some((bx, by, hit)) =
Self::find_table_cell_hit(layout, &cell.block_id, &cell.row_id, &cell.column_id)
else {
return out;
};
let scroll_x = self.overlays.code_scroll_x(&cell.block_id);
let vis_left = bx;
let vis_right = bx + block.body.width;
let clip_x = |r: FlowRect| -> Option<FlowRect> {
let left = r.x.max(vis_left);
let right = r.right().min(vis_right);
(right > left).then(|| FlowRect::new(left, r.y, right - left, r.h))
};
let cell_world = hit.rect.translated(bx - scroll_x, by);
if cell_world.bottom() < v.scroll_y || cell_world.y > v.scroll_y + v.height {
return out;
}
if let Some(clipped) = clip_x(cell_world) {
let mut ring = div()
.absolute()
.left(px(v.column_x + clipped.x))
.top(px(clipped.y - v.scroll_y))
.w(px(clipped.w))
.h(px(clipped.h))
.border(px(1.5))
.border_color(palette.brand);
if v.fully_visible(&clipped) {
ring = ring
.snapshot("page.table_cell_focus", Some(PAGE_SURFACE_ID))
.snapshot_focused(true)
.snapshot_text(cell.input.display_text());
}
out.push(ring.into_any_element());
}
let lh = hit.text.line_height();
let ox = bx + hit.text_origin.0 - scroll_x;
let oy = by + hit.text_origin.1;
let (sel, reversed) = cell.input.shown_selection();
let marked = cell.input.marked_range();
if let Some(marked) = &marked {
for (line, a, b) in hit.text.selection_spans(marked.start, marked.end) {
let y = oy + line as f32 * lh + lh - 1.0;
if let Some(clipped) = clip_x(FlowRect::new(ox + a, y, (b - a).max(1.0), 1.0)) {
out.push(
div()
.absolute()
.left(px(v.column_x + clipped.x))
.top(px(clipped.y - v.scroll_y))
.w(px(clipped.w))
.h(px(1.0))
.bg(palette.text_secondary)
.into_any_element(),
);
}
}
} else if !sel.is_empty() {
let mut first = true;
for (line, a, b) in hit.text.selection_spans(sel.start, sel.end) {
let Some(r) = clip_x(FlowRect::new(
ox + a,
oy + line as f32 * lh,
(b - a).max(1.0),
lh,
)) else {
continue;
};
let mut d = div()
.absolute()
.left(px(v.column_x + r.x))
.top(px(r.y - v.scroll_y))
.w(px(r.w))
.h(px(r.h))
.bg(palette.brand.opacity(0.22));
if v.fully_visible(&r) && std::mem::take(&mut first) {
d = d.snapshot("page.selection", Some(PAGE_SURFACE_ID));
}
out.push(d.into_any_element());
}
}
let caret_u16 = if reversed { sel.start } else { sel.end };
let (cx_local, line) = hit.text.caret(caret_u16);
let caret_rect = FlowRect::new(ox + cx_local, oy + line as f32 * lh, 1.5, lh);
if caret_rect.bottom() >= v.scroll_y
&& caret_rect.y <= v.scroll_y + v.height
&& caret_rect.right() > vis_left
&& caret_rect.x < vis_right
{
let mut caret_el = div()
.absolute()
.left(px(v.column_x + caret_rect.x))
.top(px(caret_rect.y - v.scroll_y))
.w(px(1.5))
.h(px(caret_rect.h))
.bg(palette.brand);
if v.fully_visible(&caret_rect) {
caret_el = caret_el.snapshot("page.table_cell_caret", Some(PAGE_SURFACE_ID));
}
out.push(caret_el.into_any_element());
}
out
}
}
@@ -164,6 +164,11 @@ pub enum RoomEvent {
source_id: String,
bytes: Option<Vec<u8>>,
},
/// A blob upload attempt finished; `ok` is `true` when the relay stored it.
BlobUploaded {
source_id: String,
ok: bool,
},
}
/// Something the UI thread asks of the transport.
@@ -171,6 +176,10 @@ pub enum RoomEvent {
pub enum RoomCommand {
Send(RoomFrame),
FetchBlob(String),
UploadBlob {
source_id: String,
bytes: Arc<Vec<u8>>,
},
Close,
}
@@ -51,7 +51,7 @@ pub fn connect(config: RoomConfig) -> RoomLink {
}
/// Largest blob body accepted from the relay.
const MAX_BLOB_BYTES: usize = 64 * 1024 * 1024;
const MAX_BLOB_BYTES: usize = blocksuite_playground_doc::MAX_BLOB_BYTES;
/// Longest wait for the relay to connect, finish a handshake, accept a request or send
/// more bytes.
const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
@@ -168,6 +168,76 @@ fn spawn_fetch(config: &RoomConfig, events: &async_channel::Sender<RoomEvent>, s
});
}
async fn put_blob_once(url: &str, body: &[u8]) -> bool {
let Some(rest) = url.strip_prefix("http://") else {
return false;
};
let (authority, path) = match rest.find('/') {
Some(slash) => rest.split_at(slash),
None => (rest, "/"),
};
let has_port = authority
.rsplit_once(':')
.is_some_and(|(_, port)| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()));
let address = if has_port {
authority.to_string()
} else {
format!("{authority}:80")
};
let Ok(Ok(mut stream)) = timeout(HTTP_TIMEOUT, TcpStream::connect(address)).await else {
return false;
};
let head = format!(
"PUT {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
if timeout(HTTP_TIMEOUT, stream.write_all(head.as_bytes()))
.await
.ok()
.and_then(Result::ok)
.is_none()
{
return false;
}
if timeout(HTTP_TIMEOUT, stream.write_all(body))
.await
.ok()
.and_then(Result::ok)
.is_none()
{
return false;
}
let mut response = Vec::new();
let mut chunk = [0_u8; 4096];
loop {
let Ok(Ok(read)) = timeout(HTTP_TIMEOUT, stream.read(&mut chunk)).await else {
return false;
};
if read == 0 {
break;
}
response.extend_from_slice(&chunk[..read]);
if response.len() > 64 * 1024 {
break;
}
}
parse_http_response(&response).is_some()
}
fn spawn_upload(
config: &RoomConfig,
events: &async_channel::Sender<RoomEvent>,
source_id: String,
bytes: std::sync::Arc<Vec<u8>>,
) {
let url = config.blob_url(&source_id);
let events = events.clone();
tokio::spawn(async move {
let ok = put_blob_once(&url, &bytes).await;
let _ = events.try_send(RoomEvent::BlobUploaded { source_id, ok });
});
}
/// Serve a command while no socket is open; `false` once the link is gone.
fn serve_unconnected(
command: Option<RoomCommand>,
@@ -179,6 +249,10 @@ fn serve_unconnected(
spawn_fetch(config, events, source_id);
true
}
Some(RoomCommand::UploadBlob { source_id, bytes }) => {
spawn_upload(config, events, source_id, bytes);
true
}
// Frames addressed to a closed socket are dropped: the next handshake resends
// whatever the relay is missing.
Some(RoomCommand::Send(_)) => true,
@@ -248,6 +322,9 @@ async fn run(
Some(RoomCommand::FetchBlob(source_id)) => {
spawn_fetch(&config, &events, source_id);
}
Some(RoomCommand::UploadBlob { source_id, bytes }) => {
spawn_upload(&config, &events, source_id, bytes);
}
Some(RoomCommand::Close) | None => {
let _ = sink.close().await;
return;
@@ -40,6 +40,7 @@ pub fn connect(config: RoomConfig) -> RoomLink {
}
}
RoomCommand::FetchBlob(source_id) => fetch_blob(&transport, source_id),
RoomCommand::UploadBlob { source_id, bytes } => upload_blob(&transport, source_id, bytes),
RoomCommand::Close => {
*transport.closed.borrow_mut() = true;
let socket = transport.socket.borrow_mut().take();
@@ -150,3 +151,26 @@ async fn fetch_bytes(url: &str) -> Option<Vec<u8>> {
.ok()?;
Some(js_sys::Uint8Array::new(&buffer).to_vec())
}
fn upload_blob(transport: &Rc<WebTransport>, source_id: String, bytes: std::sync::Arc<Vec<u8>>) {
let url = transport.config.blob_url(&source_id);
let events = transport.events.clone();
wasm_bindgen_futures::spawn_local(async move {
let ok = put_bytes(&url, &bytes).await.is_some();
let _ = events.try_send(RoomEvent::BlobUploaded { source_id, ok });
});
}
async fn put_bytes(url: &str, bytes: &[u8]) -> Option<()> {
let window = web_sys::window()?;
let init = web_sys::RequestInit::new();
init.set_method("PUT");
let payload = js_sys::Uint8Array::from(bytes);
init.set_body(&payload);
let response = wasm_bindgen_futures::JsFuture::from(window.fetch_with_str_and_init(url, &init))
.await
.ok()?
.dyn_into::<web_sys::Response>()
.ok()?;
response.ok().then_some(())
}
+132 -3
View File
@@ -37,6 +37,17 @@ pub(crate) struct BlobFetchState {
pub(crate) next_retry_ms: u64,
}
/// Upload of a content-addressed blob referenced by a locally inserted image or attachment.
/// Kept until the relay confirms storage (`2xx`), retrying on scheduler backoff or reconnect
/// so transient `503` / network drops never strand remote peers on a missing `sourceId`.
#[derive(Clone, Debug)]
pub(crate) struct BlobUploadState {
pub(crate) bytes: Arc<Vec<u8>>,
pub(crate) in_flight: bool,
pub(crate) failures: u32,
pub(crate) next_retry_ms: u64,
}
pub(crate) struct RoomRuntime {
pub(crate) config: RoomConfig,
pub(crate) protocol: RoomProtocol,
@@ -74,6 +85,75 @@ impl PlaygroundView {
* 1000.0
}
/// Override the host calendar clock `(utc_epoch_ms, utc_offset_minutes)` used by user-facing
/// date insertion actions (such as KeyboardToolbar `Today` / `Yesterday` / `Tomorrow` / `Now`).
pub fn set_calendar_clock(&mut self, clock: Option<crate::CalendarClockFn>) {
self.calendar_clock = clock;
}
/// Override the host file-picker callback triggered by the KeyboardToolbar `Image` button.
pub fn set_image_picker(&mut self, picker: Option<crate::ImagePickerFn>) {
self.image_picker = picker;
self.sync_keyboard_toolbar_state();
}
/// Enqueue a content-addressed blob for room upload and retain it until the relay confirms
/// `2xx` storage, retrying on scheduler backoff or reconnect after transient failures.
pub(crate) fn queue_blob_upload(
&mut self,
source_id: String,
bytes: Arc<Vec<u8>>,
cx: &Context<Self>,
) {
let now_ms = self.now_ms(cx) as u64;
let in_flight = if let Some(room) = &self.room {
room.link.send(RoomCommand::UploadBlob {
source_id: source_id.clone(),
bytes: bytes.clone(),
});
true
} else {
false
};
self.blob_uploads.insert(
source_id,
BlobUploadState {
bytes,
in_flight,
failures: 0,
next_retry_ms: now_ms,
},
);
}
/// Returns `(utc_epoch_ms, utc_offset_minutes)` from the configured override or host clock.
pub(crate) fn local_calendar_now(&self, _cx: &Context<Self>) -> (i64, i32) {
if let Some(clock) = &self.calendar_clock {
return clock();
}
#[cfg(target_family = "wasm")]
let (utc_ms, offset_min) = {
let d = js_sys::Date::new_0();
(
d.get_time().round() as i64,
-(d.get_timezone_offset().round() as i32),
)
};
#[cfg(not(target_family = "wasm"))]
let (utc_ms, offset_min) = {
let ms = ui::system_now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
let off = jiff::Timestamp::from_millisecond(ms)
.ok()
.map(|ts| jiff::tz::TimeZone::system().to_offset(ts).seconds() / 60)
.unwrap_or(0);
(ms, off)
};
(utc_ms, offset_min)
}
pub(crate) fn handle_room_event(&mut self, event: RoomEvent, cx: &mut Context<Self>) {
let now_ms = self.now_ms(cx) as u64;
let Some(room) = self.room.as_mut() else {
@@ -83,7 +163,18 @@ impl PlaygroundView {
let effects = match event {
RoomEvent::Opened => {
let effects = room.protocol.on_open(&mut self.state, now_ms);
// A fresh connection fetches every missing blob again right away.
// A fresh connection retries every pending upload and missing blob right away.
for (source_id, upload) in &mut self.blob_uploads {
upload.failures = 0;
upload.next_retry_ms = now_ms;
if !upload.in_flight {
upload.in_flight = true;
room.link.send(RoomCommand::UploadBlob {
source_id: source_id.clone(),
bytes: upload.bytes.clone(),
});
}
}
for (source_id, fetch) in &mut self.blob_fetches {
fetch.misses = 0;
fetch.next_retry_ms = now_ms;
@@ -133,6 +224,17 @@ impl PlaygroundView {
}
Ok(RoomEffects::default())
}
RoomEvent::BlobUploaded { source_id, ok } => {
if ok {
self.blob_uploads.remove(&source_id);
} else if let Some(upload) = self.blob_uploads.get_mut(&source_id) {
upload.in_flight = false;
upload.failures = upload.failures.saturating_add(1);
upload.next_retry_ms =
now_ms.saturating_add(blob_retry_backoff_ms(upload.failures));
}
Ok(RoomEffects::default())
}
};
match effects {
Ok(effects) => {
@@ -168,8 +270,18 @@ impl PlaygroundView {
cx.notify();
}
}
// Fetch missing blobs again once their backoff ran out, unless the room is offline.
// Retry unconfirmed blob uploads and missing blob fetches once their backoff ran out,
// unless the room is offline.
if !matches!(room.protocol.status(), RoomStatus::Offline(_)) {
for (source_id, upload) in &mut self.blob_uploads {
if !upload.in_flight && now_ms >= upload.next_retry_ms {
upload.in_flight = true;
room.link.send(RoomCommand::UploadBlob {
source_id: source_id.clone(),
bytes: upload.bytes.clone(),
});
}
}
for (source_id, fetch) in &mut self.blob_fetches {
if !fetch.in_flight && now_ms >= fetch.next_retry_ms {
fetch.in_flight = true;
@@ -281,6 +393,21 @@ fn web_options() -> PlaygroundOptions {
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn wasm_main() {
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;
}
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) {
@@ -288,7 +415,9 @@ pub fn wasm_main() {
}
let options = web_options();
if let Err(err) = cx.open_window(ui::WindowOptions::default(), |_, cx| {
cx.new(|cx| PlaygroundView::with_options(options, cx))
let view = cx.new(|cx| PlaygroundView::with_options(options, cx));
crate::wasm_preview::install_wasm_preview_providers(view.downgrade(), cx);
view
}) {
panic!("failed to open playground web window: {err:#}");
}
@@ -0,0 +1,43 @@
//! WebAssembly `#[wasm_bindgen]` CRDT exports served directly from the main `playground`
//! bundle, eliminating any redundant standalone `crdt-codec.wasm`.
use blocksuite_playground_doc::crdt_v1;
use wasm_bindgen::{JsCast, prelude::*};
fn collect_byte_frames(frames: &js_sys::Array) -> Result<Vec<Vec<u8>>, JsValue> {
let len = frames.length();
let mut out = Vec::with_capacity(len as usize);
for idx in 0..len {
let item = frames.get(idx);
let view = item.dyn_into::<js_sys::Uint8Array>().map_err(|_| {
JsValue::from_str(&format!("CRDT frame at index {idx} must be a Uint8Array"))
})?;
out.push(view.to_vec());
}
Ok(out)
}
/// Merge an array of Yjs v1 binary `Uint8Array` updates into a single `Uint8Array`.
#[wasm_bindgen]
pub fn merge_updates_v1(frames: js_sys::Array) -> Result<js_sys::Uint8Array, JsValue> {
let owned = collect_byte_frames(&frames)?;
let slices: Vec<&[u8]> = owned.iter().map(Vec::as_slice).collect();
let merged = crdt_v1::merge_crdt_updates_v1(&slices)
.map_err(|err| JsValue::from_str(&err.to_string()))?;
Ok(js_sys::Uint8Array::from(merged.as_slice()))
}
/// Extract sorted, deduplicated live `meta.pages -> spaces` subdoc GUIDs from an array of
/// Yjs v1 root document `Uint8Array` updates.
#[wasm_bindgen]
pub fn extract_subdoc_ids(frames: js_sys::Array) -> Result<js_sys::Array, JsValue> {
let owned = collect_byte_frames(&frames)?;
let slices: Vec<&[u8]> = owned.iter().map(Vec::as_slice).collect();
let guids = crdt_v1::extract_subdoc_guids_from_root_updates(&slices)
.map_err(|err| JsValue::from_str(&err.to_string()))?;
let out = js_sys::Array::new_with_length(guids.len() as u32);
for (idx, guid) in guids.into_iter().enumerate() {
out.set(idx as u32, JsValue::from_str(&guid));
}
Ok(out)
}
@@ -0,0 +1,456 @@
//! WebAssembly (`wasm32`) worker-backed preview providers (`WasmMathPreviewProvider` +
//! `WasmPdfPageProvider`) bridging Dedicated Web Workers (`math-worker.js`, `pdf-worker.js`)
//! to `blocksuite-editor`'s preview cache and automatic GPUI window repaint.
use std::{
cell::RefCell,
collections::{HashMap, HashSet, VecDeque},
hash::{Hash, Hasher},
sync::{Arc, OnceLock, RwLock},
};
use ui::{Hsla, WeakEntity};
use wasm_bindgen::prelude::*;
use crate::{
PlaygroundView,
block_flow::{
MathPreviewProvider, MathRenderResult, MathRenderSlot, PdfPageCount, PdfPageProvider,
PdfPreviewPage, bump_latex_formula_revision, bump_preview_revision, hsla_to_css_hex,
register_math_preview_provider, register_pdf_page_provider, rgba_pixels_to_render_image,
},
overlays::OverlayEvent,
};
const MAX_MATH_CACHE_ENTRIES: usize = 1024;
const MAX_PDF_CACHE_ENTRIES: usize = 64;
type MathKey = (String, bool, u32, String, u32);
type PdfPageKey = (String, usize, u32);
type FifoCache<K, V> = (HashMap<K, V>, VecDeque<K>);
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = requestMath, catch)]
fn js_request_math(
latex: &str,
display: bool,
font_size_pt: f32,
color_css: &str,
dpr: f32,
) -> Result<(), JsValue>;
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = requestPdfPageCount, catch)]
fn js_request_pdf_page_count(pdf_key: &str, bytes: &[u8]) -> Result<(), JsValue>;
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = requestPdfPage, catch)]
fn js_request_pdf_page(
pdf_key: &str,
bytes: &[u8],
page_index: usize,
scale: f32,
) -> Result<(), JsValue>;
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = pickImages, catch)]
fn js_pick_images() -> Result<(), JsValue>;
}
/// Opens the browser `<input type="file" accept="image/*">` picker via `preview-workers.js`.
pub(crate) fn request_host_image_picker() {
let _ = js_pick_images();
}
fn resolve_pdf_key(cache_key: &str, bytes: &[u8]) -> String {
if !cache_key.is_empty() {
return cache_key.to_string();
}
let mut h = std::collections::hash_map::DefaultHasher::new();
bytes.len().hash(&mut h);
bytes.hash(&mut h);
format!("{:016x}", h.finish())
}
fn fifo_insert<K: Clone + Eq + Hash, V>(
map: &mut HashMap<K, V>,
order: &mut VecDeque<K>,
cap: usize,
key: K,
val: V,
) {
if !map.contains_key(&key) {
while map.len() >= cap {
let Some(oldest) = order.pop_front() else {
break;
};
map.remove(&oldest);
}
order.push_back(key.clone());
}
map.insert(key, val);
}
fn math_cache() -> &'static RwLock<FifoCache<MathKey, MathRenderResult>> {
static CACHE: OnceLock<RwLock<FifoCache<MathKey, MathRenderResult>>> = OnceLock::new();
CACHE.get_or_init(|| RwLock::new((HashMap::new(), VecDeque::new())))
}
fn math_in_flight() -> &'static RwLock<HashSet<MathKey>> {
static SET: OnceLock<RwLock<HashSet<MathKey>>> = OnceLock::new();
SET.get_or_init(|| RwLock::new(HashSet::new()))
}
fn pdf_counts() -> &'static RwLock<HashMap<String, PdfPageCount>> {
static CACHE: OnceLock<RwLock<HashMap<String, PdfPageCount>>> = OnceLock::new();
CACHE.get_or_init(|| RwLock::new(HashMap::new()))
}
fn pdf_count_in_flight() -> &'static RwLock<HashSet<String>> {
static SET: OnceLock<RwLock<HashSet<String>>> = OnceLock::new();
SET.get_or_init(|| RwLock::new(HashSet::new()))
}
fn pdf_pages() -> &'static RwLock<FifoCache<PdfPageKey, PdfPreviewPage>> {
static CACHE: OnceLock<RwLock<FifoCache<PdfPageKey, PdfPreviewPage>>> = OnceLock::new();
CACHE.get_or_init(|| RwLock::new((HashMap::new(), VecDeque::new())))
}
fn pdf_in_flight() -> &'static RwLock<HashSet<PdfPageKey>> {
static SET: OnceLock<RwLock<HashSet<PdfPageKey>>> = OnceLock::new();
SET.get_or_init(|| RwLock::new(HashSet::new()))
}
std::thread_local! {
static ACTIVE_VIEW: RefCell<Option<(WeakEntity<PlaygroundView>, ui::AsyncApp)>> =
const { RefCell::new(None) };
}
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);
}
cx.notify();
});
});
}
});
}
struct WasmMathPreviewProvider;
impl MathPreviewProvider for WasmMathPreviewProvider {
fn render_math(
&self,
latex: &str,
display: bool,
font_size_pt: f32,
color: Hsla,
dpr: f32,
) -> MathRenderResult {
let color_css = hsla_to_css_hex(color);
let key: MathKey = (
latex.to_string(),
display,
font_size_pt.to_bits(),
color_css.clone(),
dpr.to_bits(),
);
if let Ok(guard) = math_cache().read()
&& let Some(hit) = guard.0.get(&key)
{
return hit.clone();
}
let should_request = math_in_flight()
.write()
.map(|mut set| set.insert(key.clone()))
.unwrap_or(false);
if should_request && js_request_math(latex, display, font_size_pt, &color_css, dpr).is_err()
{
if let Ok(mut set) = math_in_flight().write() {
set.remove(&key);
}
}
MathRenderResult::Pending
}
}
struct WasmPdfPageProvider;
impl PdfPageProvider for WasmPdfPageProvider {
fn page_count(&self, cache_key: &str, bytes: &[u8]) -> PdfPageCount {
let pdf_key = resolve_pdf_key(cache_key, bytes);
if let Ok(guard) = pdf_counts().read()
&& let Some(&status) = guard.get(&pdf_key)
{
return status;
}
let should_request = pdf_count_in_flight()
.write()
.map(|mut set| set.insert(pdf_key.clone()))
.unwrap_or(false);
if should_request && js_request_pdf_page_count(&pdf_key, bytes).is_err() {
if let Ok(mut set) = pdf_count_in_flight().write() {
set.remove(&pdf_key);
}
return PdfPageCount::Invalid;
}
PdfPageCount::Pending
}
fn render_pdf_page(
&self,
cache_key: &str,
bytes: &[u8],
page_index: usize,
scale: f32,
) -> Option<PdfPreviewPage> {
let pdf_key = resolve_pdf_key(cache_key, bytes);
let key: PdfPageKey = (pdf_key.clone(), page_index, scale.to_bits());
if let Ok(guard) = pdf_pages().read()
&& let Some(hit) = guard.0.get(&key)
{
return Some(hit.clone());
}
let should_request = pdf_in_flight()
.write()
.map(|mut set| set.insert(key.clone()))
.unwrap_or(false);
if should_request && js_request_pdf_page(&pdf_key, bytes, page_index, scale).is_err() {
if let Ok(mut set) = pdf_in_flight().write() {
set.remove(&key);
}
}
None
}
}
/// 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()));
});
register_math_preview_provider(Some(Arc::new(WasmMathPreviewProvider)));
register_pdf_page_provider(Some(Arc::new(WasmPdfPageProvider)));
}
/// Callback invoked by `preview-workers.js` when a RaTeX math formula finishes rasterizing.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn deliver_math_preview(
latex: String,
display: bool,
font_size_pt: f32,
color_css: String,
dpr: f32,
width_pt: f32,
ascent_pt: f32,
descent_pt: f32,
width_px: u32,
height_px: u32,
rgba: &[u8],
) {
let latex_for_rev = latex.clone();
let key: MathKey = (
latex,
display,
font_size_pt.to_bits(),
color_css,
dpr.to_bits(),
);
if let Ok(mut set) = math_in_flight().write() {
set.remove(&key);
}
let result = match rgba_pixels_to_render_image(width_px, height_px, rgba) {
Some(image) => MathRenderResult::Ready(MathRenderSlot {
image,
width_pt,
ascent_pt,
descent_pt,
}),
None => MathRenderResult::Error,
};
if let Ok(mut guard) = math_cache().write() {
let (map, order) = &mut *guard;
fifo_insert(map, order, MAX_MATH_CACHE_ENTRIES, key, result);
}
bump_latex_formula_revision(&latex_for_rev);
notify_active_view(false);
}
/// Callback invoked by `preview-workers.js` when RaTeX reports a definitive syntax/parse error
/// or the worker fails to initialize.
#[wasm_bindgen]
pub fn deliver_math_error(
latex: String,
display: bool,
font_size_pt: f32,
color_css: String,
dpr: f32,
) {
let latex_for_rev = latex.clone();
let key: MathKey = (
latex,
display,
font_size_pt.to_bits(),
color_css,
dpr.to_bits(),
);
if let Ok(mut set) = math_in_flight().write() {
set.remove(&key);
}
if let Ok(mut guard) = math_cache().write() {
let (map, order) = &mut *guard;
fifo_insert(
map,
order,
MAX_MATH_CACHE_ENTRIES,
key,
MathRenderResult::Error,
);
}
bump_latex_formula_revision(&latex_for_rev);
notify_active_view(false);
}
/// Callback invoked by `preview-workers.js` when Hayro reports a PDF's page count.
#[wasm_bindgen]
pub fn deliver_pdf_page_count(pdf_key: String, page_count: usize) {
if let Ok(mut set) = pdf_count_in_flight().write() {
set.remove(&pdf_key);
}
let status = if page_count > 0 {
PdfPageCount::Ready(page_count)
} else {
PdfPageCount::Invalid
};
if let Ok(mut guard) = pdf_counts().write() {
guard.insert(pdf_key, status);
}
bump_preview_revision();
notify_active_view(true);
}
/// Callback invoked by `preview-workers.js` when Hayro fails to parse/render a PDF or the PDF
/// worker fails to load.
#[wasm_bindgen]
pub fn deliver_pdf_error(pdf_key: String) {
if let Ok(mut set) = pdf_count_in_flight().write() {
set.remove(&pdf_key);
}
if let Ok(mut set) = pdf_in_flight().write() {
set.retain(|(k, _, _)| k != &pdf_key);
}
if let Ok(mut guard) = pdf_counts().write() {
guard.insert(pdf_key, PdfPageCount::Invalid);
}
bump_preview_revision();
notify_active_view(true);
}
/// Callback invoked by `preview-workers.js` when Hayro finishes rasterizing a PDF page.
#[wasm_bindgen]
#[allow(clippy::too_many_arguments)]
pub fn deliver_pdf_page(
pdf_key: String,
page_index: usize,
page_count: usize,
scale: f32,
width_px: u32,
height_px: u32,
rgba: &[u8],
) {
let key: PdfPageKey = (pdf_key.clone(), page_index, scale.to_bits());
if let Ok(mut set) = pdf_in_flight().write() {
set.remove(&key);
}
if let Some(image) = rgba_pixels_to_render_image(width_px, height_px, rgba) {
if let Ok(mut counts) = pdf_counts().write() {
counts.insert(pdf_key, PdfPageCount::Ready(page_count));
}
if let Ok(mut pages) = pdf_pages().write() {
let (map, order) = &mut *pages;
fifo_insert(
map,
order,
MAX_PDF_CACHE_ENTRIES,
key,
PdfPreviewPage {
page_index,
page_count,
image,
width_pt: (width_px as f32) / scale.max(0.25),
height_pt: (height_px as f32) / scale.max(0.25),
},
);
}
bump_preview_revision();
notify_active_view(true);
}
}
/// Callback invoked by `preview-workers.js` when the user selects an image file in the picker.
#[wasm_bindgen]
pub fn deliver_picked_image(bytes: &[u8]) {
if bytes.is_empty() {
return;
}
let payload = bytes.to_vec();
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 Some(entity) = weak.upgrade() else {
return;
};
for window in cx.windows() {
let _ = window.update(cx, |_, win, cx| {
entity.update(cx, |view, cx| {
view.dispatch_overlay(
OverlayEvent::InsertImageBytes {
bytes: payload.clone(),
caption: String::new(),
},
win,
cx,
);
});
});
}
});
}
});
}
/// Callback invoked by the Web host to insert an embedded PDF attachment block into the active view.
#[wasm_bindgen]
pub fn deliver_picked_pdf(bytes: &[u8], name: String) {
if bytes.is_empty() {
return;
}
let payload = bytes.to_vec();
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 Some(entity) = weak.upgrade() else {
return;
};
for window in cx.windows() {
let _ = window.update(cx, |_, win, cx| {
entity.update(cx, |view, cx| {
let _ = view.insert_picked_pdf_bytes(&payload, &name, win, cx);
});
});
}
});
}
});
}
+7 -1
View File
@@ -3,6 +3,10 @@
<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:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' https: wss: http: ws:; base-uri 'none'; object-src 'none'"
/>
<title>Native BlockSuite Playground (WebAssembly)</title>
<style>
html,
@@ -23,9 +27,11 @@
</head>
<body>
<script type="module">
import init from './pkg/playground.js';
import init, * as playgroundWasm from './pkg/playground.js';
import { installPlaygroundPreviewBridge } from './preview-workers.js';
window.__playgroundReady = false;
window.__playgroundError = null;
installPlaygroundPreviewBridge(playgroundWasm, window.location.href);
init()
.then(() => {
window.__playgroundReady = true;
@@ -0,0 +1,241 @@
// Dedicated Web Worker & host file-picker bridge for `playground` Wasm RaTeX math,
// Hayro PDF previews, and image insertion.
export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.location.href) {
let mathWorker = null;
let pdfWorker = null;
let nextId = 1;
const pendingMath = new Map();
const pendingPdf = new Map();
const cachedPdfBytes = new Map();
function rememberPdfBytes(pdfKey, bytes) {
if (cachedPdfBytes.has(pdfKey)) {
return cachedPdfBytes.get(pdfKey);
}
if (cachedPdfBytes.size >= 16) {
const oldestKey = cachedPdfBytes.keys().next().value;
if (oldestKey !== undefined) cachedPdfBytes.delete(oldestKey);
}
const copy = new Uint8Array(bytes);
cachedPdfBytes.set(pdfKey, copy);
return copy;
}
function failAllPendingMath() {
const entries = Array.from(pendingMath.values());
pendingMath.clear();
mathWorker = null;
for (const req of entries) {
wasmExports.deliver_math_error(
req.latex,
req.display,
req.fontSizePt,
req.colorCss,
req.dpr
);
}
}
function failAllPendingPdf() {
const entries = Array.from(pendingPdf.values());
pendingPdf.clear();
pdfWorker = null;
const seenKeys = new Set();
for (const req of entries) {
if (!seenKeys.has(req.pdfKey)) {
seenKeys.add(req.pdfKey);
if (typeof wasmExports.deliver_pdf_error === 'function') {
wasmExports.deliver_pdf_error(req.pdfKey);
}
}
}
}
function spawnWorker(scriptRel, wasmRel) {
const scriptUrl = new URL(scriptRel, baseUrl).toString();
const wasmUrl = new URL(wasmRel, baseUrl).toString();
const src = [
`globalThis.AFFINE_WORKER_WASM_URL = ${JSON.stringify(wasmUrl)};`,
'const __q = [];',
'const __onMsg = e => __q.push(e);',
"globalThis.addEventListener('message', __onMsg);",
`await import(${JSON.stringify(scriptUrl)});`,
"globalThis.removeEventListener('message', __onMsg);",
"for (const e of __q) globalThis.dispatchEvent(new MessageEvent('message', { data: e.data, ports: e.ports }));",
].join('\n');
const blobUrl = URL.createObjectURL(new Blob([src], { type: 'text/javascript' }));
return new Worker(blobUrl, { type: 'module' });
}
function resolveWorkerAsset(key, fallbackRel) {
const assets = globalThis.window?.__AFFINE_WORKER_ASSETS__;
const override = assets && typeof assets[key] === 'string' && assets[key].trim();
return override || fallbackRel;
}
function ensureMathWorker() {
if (!mathWorker) {
mathWorker = spawnWorker(
resolveWorkerAsset('mathScript', './workers/math-worker.js'),
resolveWorkerAsset('mathWasm', './workers/math-worker.wasm')
);
mathWorker.addEventListener('error', failAllPendingMath);
mathWorker.addEventListener('messageerror', failAllPendingMath);
mathWorker.addEventListener('message', event => {
const msg = event?.data;
if (!msg || !pendingMath.has(msg.id)) return;
const req = pendingMath.get(msg.id);
pendingMath.delete(msg.id);
if (!msg.ok || !msg.result?.rgba) {
wasmExports.deliver_math_error(
req.latex,
req.display,
req.fontSizePt,
req.colorCss,
req.dpr
);
return;
}
wasmExports.deliver_math_preview(
req.latex,
req.display,
req.fontSizePt,
req.colorCss,
req.dpr,
msg.result.widthPt,
msg.result.ascentPt,
msg.result.descentPt,
msg.result.widthPx,
msg.result.heightPx,
msg.result.rgba
);
});
}
return mathWorker;
}
function ensurePdfWorker() {
if (!pdfWorker) {
pdfWorker = spawnWorker(
resolveWorkerAsset('pdfScript', './workers/pdf-worker.js'),
resolveWorkerAsset('pdfWasm', './workers/pdf-worker.wasm')
);
pdfWorker.addEventListener('error', failAllPendingPdf);
pdfWorker.addEventListener('messageerror', failAllPendingPdf);
pdfWorker.addEventListener('message', event => {
const msg = event?.data;
if (!msg || !pendingPdf.has(msg.id)) return;
const req = pendingPdf.get(msg.id);
pendingPdf.delete(msg.id);
if (!msg.ok || !msg.result) {
if (typeof wasmExports.deliver_pdf_error === 'function') {
wasmExports.deliver_pdf_error(req.pdfKey);
}
return;
}
if (req.op === 'page_count') {
wasmExports.deliver_pdf_page_count(req.pdfKey, msg.result.pageCount ?? 0);
} else if (msg.result.rgba) {
wasmExports.deliver_pdf_page(
req.pdfKey,
req.pageIndex,
msg.result.pageCount ?? 1,
req.scale,
msg.result.widthPx,
msg.result.heightPx,
msg.result.rgba
);
} else if (typeof wasmExports.deliver_pdf_error === 'function') {
wasmExports.deliver_pdf_error(req.pdfKey);
}
});
}
return pdfWorker;
}
window.__playgroundPreview = {
requestMath(latex, display, fontSizePt, colorCss, dpr) {
const id = nextId++;
pendingMath.set(id, { latex, display, fontSizePt, colorCss, dpr });
try {
ensureMathWorker().postMessage({
id,
op: 'rgba',
latex,
display,
fontSizePt,
paddingPt: display ? 4.0 : 1.5,
colorCss,
scaleFactor: dpr,
});
} catch {
pendingMath.delete(id);
wasmExports.deliver_math_error(latex, display, fontSizePt, colorCss, dpr);
}
},
requestPdfPageCount(pdfKey, bytes) {
const id = nextId++;
const payload = rememberPdfBytes(pdfKey, bytes);
pendingPdf.set(id, { op: 'page_count', pdfKey });
try {
ensurePdfWorker().postMessage({ id, op: 'page_count', pdfBytes: payload });
} catch {
pendingPdf.delete(id);
if (typeof wasmExports.deliver_pdf_error === 'function') {
wasmExports.deliver_pdf_error(pdfKey);
}
}
},
requestPdfPage(pdfKey, bytes, pageIndex, scale) {
const id = nextId++;
const payload = rememberPdfBytes(pdfKey, bytes);
pendingPdf.set(id, { op: 'render_page', pdfKey, pageIndex, scale });
try {
ensurePdfWorker().postMessage({
id,
pdfBytes: payload,
pageIndex,
scale,
});
} catch {
pendingPdf.delete(id);
if (typeof wasmExports.deliver_pdf_error === 'function') {
wasmExports.deliver_pdf_error(pdfKey);
}
}
},
pickImages() {
const doc = globalThis.document;
if (!doc || typeof doc.createElement !== 'function') return;
const input = doc.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.multiple = true;
input.style.display = 'none';
const cleanup = () => {
input.remove();
};
input.addEventListener('change', async () => {
try {
const files = Array.from(input.files || []);
for (const file of files) {
const buf = await file.arrayBuffer();
if (buf.byteLength > 0 && typeof wasmExports.deliver_picked_image === 'function') {
wasmExports.deliver_picked_image(new Uint8Array(buf));
}
}
} finally {
cleanup();
}
});
input.addEventListener('cancel', cleanup);
doc.body?.append(input);
input.click();
},
deliverPdfAttachment(bytes, name = 'document.pdf') {
if (typeof wasmExports.deliver_picked_pdf === 'function') {
wasmExports.deliver_picked_pdf(bytes, String(name));
}
},
};
}
@@ -0,0 +1,372 @@
use ratex_types::color::Color;
use crate::error::PreviewError;
/// Exact W3C CSS Color Module Level 4 named colors plus `transparent` (149 keywords, sorted lowercase).
const CSS_NAMED_COLORS: &[&str] = &[
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgreen",
"darkgrey",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"green",
"greenyellow",
"grey",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgreen",
"lightgrey",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"rebeccapurple",
"red",
"rosybrown",
"royalblue",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"transparent",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen",
];
pub(super) fn validate_css_color(raw: &str) -> Result<String, PreviewError> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(PreviewError::InvalidColor(
"color_css must not be empty".to_string(),
));
}
if trimmed.chars().any(|ch| {
matches!(
ch,
'"' | '\'' | '<' | '>' | '&' | ';' | '\\' | '\n' | '\r' | '\0'
)
}) {
return Err(PreviewError::InvalidColor(format!(
"color_css contains forbidden characters: {trimmed}"
)));
}
if trimmed.eq_ignore_ascii_case("currentColor") {
return Ok("currentColor".to_string());
}
if let Some(hex) = trimmed.strip_prefix('#') {
if matches!(hex.len(), 3 | 4 | 6 | 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Ok(format!("#{}", hex.to_ascii_lowercase()));
}
return Err(PreviewError::InvalidColor(format!(
"invalid hex CSS color: {trimmed}"
)));
}
let lower = trimmed.to_ascii_lowercase();
if let Some(inner) = lower
.strip_prefix("rgb(")
.or_else(|| lower.strip_prefix("rgba("))
.and_then(|rest| rest.strip_suffix(')'))
{
return parse_and_normalize_rgb(inner, trimmed);
}
if CSS_NAMED_COLORS.binary_search(&lower.as_str()).is_ok() {
return Ok(lower);
}
Err(PreviewError::InvalidColor(format!(
"unsupported CSS color syntax: {trimmed}"
)))
}
fn parse_and_normalize_rgb(inner: &str, raw: &str) -> Result<String, PreviewError> {
let err = |msg: &str| PreviewError::InvalidColor(format!("{msg}: {raw}"));
let inner = inner.trim();
if inner.is_empty() {
return Err(err("empty rgb/rgba channel list"));
}
let (channels, alpha_str) = if inner.contains(',') {
if inner.contains('/') {
return Err(err("cannot mix ',' and '/' in rgb/rgba"));
}
let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
if parts.iter().any(|p| p.is_empty()) || !matches!(parts.len(), 3 | 4) {
return Err(err("invalid comma-separated rgb/rgba channels"));
}
let is_pct = [parts[0], parts[1], parts[2]].map(|p| p.ends_with('%'));
if is_pct[0] != is_pct[1] || is_pct[1] != is_pct[2] {
return Err(err(
"comma-separated rgb/rgba cannot mix numbers and percentages",
));
}
([parts[0], parts[1], parts[2]], parts.get(3).copied())
} else {
let mut slash_split = inner.split('/');
let rgb_part = slash_split.next().unwrap_or("").trim();
let alpha_part = slash_split.next().map(str::trim);
if slash_split.next().is_some() {
return Err(err("multiple '/' separators in rgb/rgba"));
}
let rgb_tokens: Vec<&str> = rgb_part.split_ascii_whitespace().collect();
if rgb_tokens.len() != 3 {
return Err(err("expected 3 space-separated rgb channels"));
}
if let Some(a) = alpha_part
&& (a.is_empty() || a.split_ascii_whitespace().count() != 1)
{
return Err(err("invalid alpha component after '/'"));
}
([rgb_tokens[0], rgb_tokens[1], rgb_tokens[2]], alpha_part)
};
let r = parse_rgb_channel(channels[0], raw)?;
let g = parse_rgb_channel(channels[1], raw)?;
let b = parse_rgb_channel(channels[2], raw)?;
if let Some(alpha_tok) = alpha_str {
let a = parse_alpha_channel(alpha_tok, raw)?;
Ok(format!("rgba({r},{g},{b},{a:.4})"))
} else {
Ok(format!("rgb({r},{g},{b})"))
}
}
fn parse_rgb_channel(tok: &str, raw: &str) -> Result<u8, PreviewError> {
if let Some(pct) = tok.strip_suffix('%') {
let v = parse_css_number_in_range(pct, 0.0..=100.0, "rgb percentage", raw)?;
Ok(((v * 255.0) / 100.0).round().clamp(0.0, 255.0) as u8)
} else {
let v = parse_css_number_in_range(tok, 0.0..=255.0, "rgb channel", raw)?;
Ok(v.round() as u8)
}
}
fn parse_alpha_channel(tok: &str, raw: &str) -> Result<f64, PreviewError> {
if let Some(pct) = tok.strip_suffix('%') {
Ok(parse_css_number_in_range(pct, 0.0..=100.0, "alpha percentage", raw)? / 100.0)
} else {
parse_css_number_in_range(tok, 0.0..=1.0, "alpha", raw)
}
}
fn is_valid_css_number(tok: &str) -> bool {
let b = tok.as_bytes();
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
let int_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
let has_int = i > int_start;
let mut has_frac = false;
if i < b.len() && b[i] == b'.' {
i += 1;
let frac_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
has_frac = i > frac_start;
if !has_frac {
return false;
}
}
if !has_int && !has_frac {
return false;
}
if i < b.len() && matches!(b[i], b'e' | b'E') {
i += 1;
i += usize::from(i < b.len() && matches!(b[i], b'+' | b'-'));
let exp_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
if i == exp_start {
return false;
}
}
i == b.len()
}
fn parse_css_number_in_range(
tok: &str,
range: std::ops::RangeInclusive<f64>,
label: &str,
raw: &str,
) -> Result<f64, PreviewError> {
if !is_valid_css_number(tok) {
return Err(PreviewError::InvalidColor(format!(
"invalid CSS number '{tok}' in {raw}"
)));
}
let val = tok
.parse::<f64>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| {
PreviewError::InvalidColor(format!("invalid numeric channel '{tok}' in {raw}"))
})?;
if !range.contains(&val) {
return Err(PreviewError::InvalidColor(format!(
"{label} out of range: {raw}"
)));
}
Ok(val)
}
fn escape_xml_attr(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => out.push_str("&amp;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
_ => out.push(ch),
}
}
out
}
pub(super) fn format_paint(color: Color, default_css: &str, attr_prefix: &str) -> (String, String) {
let is_default_black =
color.r == 0.0 && color.g == 0.0 && color.b == 0.0 && (color.a - 1.0).abs() < 1e-4;
if is_default_black {
// Use explicit #000000 when caller passed currentColor so resvg renders black cleanly.
let css = if default_css.eq_ignore_ascii_case("currentColor") {
"#000000".to_string()
} else {
escape_xml_attr(default_css)
};
return (css, String::new());
}
let r = (color.r.clamp(0.0, 1.0) * 255.0).round() as u8;
let g = (color.g.clamp(0.0, 1.0) * 255.0).round() as u8;
let b = (color.b.clamp(0.0, 1.0) * 255.0).round() as u8;
let paint = format!("rgb({r},{g},{b})");
let opacity = if color.a < 0.999 {
format!(r#" {attr_prefix}-opacity="{:.3}""#, color.a.clamp(0.0, 1.0))
} else {
String::new()
};
(paint, opacity)
}
@@ -1,7 +1,8 @@
mod css_color;
use std::fmt::Write;
use ratex_layout::{LayoutOptions, layout, to_display_list};
use ratex_types::color::Color;
use ratex_types::display_item::{DisplayItem, DisplayList};
use ratex_types::math_style::MathStyle;
use ratex_types::path_command::PathCommand;
@@ -10,6 +11,8 @@ use crate::error::PreviewError;
use crate::font_pool::FontPool;
use crate::svg_raster::{RasterOptions, RgbaImageBuffer, SvgRasterizer};
use self::css_color::{format_paint, validate_css_color};
/// Display mode for LaTeX mathematical formulas.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MathDisplayMode {
@@ -100,7 +103,8 @@ pub fn render_latex_svg(
let layout_box = layout(&nodes, &layout_opts);
let display_list = to_display_list(&layout_box);
let svg = display_list_to_outline_svg(&display_list, options, &validated_color, font_pool)?;
let svg =
display_list_to_outline_svg(&display_list, options, &validated_color, font_pool, None)?;
let width_pt = display_list.width * options.font_size_pt + 2.0 * options.padding_pt;
let ascent_pt = display_list.height * options.font_size_pt + options.padding_pt;
let descent_pt = display_list.depth * options.font_size_pt + options.padding_pt;
@@ -114,6 +118,10 @@ pub fn render_latex_svg(
}
/// Renders a LaTeX math formula to RGBA8 pixels with exact baseline metrics.
///
/// Horizontal math rules (fraction bars and square-root overlines) are snapped to device-pixel
/// rows with a `>= 1px` device-pixel floor at `scale_factor` so thin rules stay crisp in both
/// light and dark themes at `1x` and `2x` DPR.
pub fn render_latex_rgba(
latex: &str,
options: &MathRenderOptions,
@@ -121,13 +129,45 @@ pub fn render_latex_rgba(
rasterizer: &SvgRasterizer,
scale_factor: f32,
) -> Result<MathRgbaOutput, PreviewError> {
let svg_out = render_latex_svg(latex, options, font_pool)?;
let image =
rasterizer.rasterize_with_options(&svg_out.svg, RasterOptions::with_scale(scale_factor))?;
if latex.trim().is_empty() {
return Err(PreviewError::EmptyInput);
}
if !options.font_size_pt.is_finite() || options.font_size_pt <= 0.0 {
return Err(PreviewError::InvalidSize(format!(
"font_size_pt must be positive and finite, got {}",
options.font_size_pt
)));
}
let validated_color = validate_css_color(&options.color_css)?;
let nodes = ratex_parser::parse(latex).map_err(|err| PreviewError::Math(err.to_string()))?;
let style = match options.mode {
MathDisplayMode::Inline => MathStyle::Text,
MathDisplayMode::Display => MathStyle::Display,
};
let layout_opts = LayoutOptions::default().with_style(style);
let layout_box = layout(&nodes, &layout_opts);
let display_list = to_display_list(&layout_box);
let dpr = if scale_factor.is_finite() && scale_factor > 0.0 {
f64::from(scale_factor)
} else {
1.0
};
let svg = display_list_to_outline_svg(
&display_list,
options,
&validated_color,
font_pool,
Some(dpr),
)?;
let ascent_pt = display_list.height * options.font_size_pt + options.padding_pt;
let image = rasterizer.rasterize_with_options(&svg, RasterOptions::with_scale(scale_factor))?;
let width_pt = f64::from(image.logical_width);
let descent_pt = (f64::from(image.logical_height) - ascent_pt).max(0.0);
Ok(MathRgbaOutput {
width_pt: svg_out.width_pt,
ascent_pt: svg_out.ascent_pt,
descent_pt: svg_out.descent_pt,
width_pt,
ascent_pt,
descent_pt,
image,
})
}
@@ -137,11 +177,20 @@ fn display_list_to_outline_svg(
options: &MathRenderOptions,
validated_color: &str,
font_pool: &FontPool,
snap_dpr: Option<f64>,
) -> Result<String, PreviewError> {
let fs = options.font_size_pt;
let pad = options.padding_pt;
let total_w = (list.width * fs + 2.0 * pad).max(1.0);
let total_h = (list.total_height() * fs + 2.0 * pad).max(1.0);
let raw_w = (list.width * fs + 2.0 * pad).max(1.0);
let raw_h = (list.total_height() * fs + 2.0 * pad).max(1.0);
let (total_w, total_h) = if let Some(dpr) = snap_dpr {
(
((raw_w * dpr).ceil().max(1.0)) / dpr,
((raw_h * dpr).ceil().max(1.0)) / dpr,
)
} else {
(raw_w, raw_h)
};
let stroke_w = (fs * 0.04).max(0.5);
let mut out = String::with_capacity(list.items.len() * 128 + 256);
@@ -197,10 +246,17 @@ fn display_list_to_outline_svg(
);
} else {
let (paint, opacity_attr) = format_paint(*color, validated_color, "fill");
let top = y1 - t * 0.5;
let (top, snapped_t) = if let Some(dpr) = snap_dpr {
let dev_t = (t * dpr).max(1.0).round();
let pt_t = dev_t / dpr;
let pt_top = ((y1 - pt_t * 0.5) * dpr).round() / dpr;
(pt_top, pt_t)
} else {
(y1 - t * 0.5, t)
};
let _ = write!(
out,
r#"<rect x="{x1:.3}" y="{top:.3}" width="{w:.3}" height="{t:.3}" fill="{paint}"{opacity_attr}/>"#,
r#"<rect x="{x1:.3}" y="{top:.3}" width="{w:.3}" height="{snapped_t:.3}" fill="{paint}"{opacity_attr}/>"#,
);
}
}
@@ -212,9 +268,20 @@ fn display_list_to_outline_svg(
color,
} => {
let rx = pad + x * fs;
let ry = pad + y * fs;
let mut ry = pad + y * fs;
let rw = width * fs;
let rh = height * fs;
let mut rh = height * fs;
if let Some(dpr) = snap_dpr
&& rh > 0.0
&& rh * dpr < 2.0
&& rw > rh
{
let dev_h = (rh * dpr).max(1.0).round();
let pt_h = dev_h / dpr;
let center_y = ry + rh * 0.5;
ry = ((center_y - pt_h * 0.5) * dpr).round() / dpr;
rh = pt_h;
}
let (paint, opacity_attr) = format_paint(*color, validated_color, "fill");
let _ = write!(
out,
@@ -411,375 +478,6 @@ impl ttf_parser::OutlineBuilder for SvgOutlineBuilder {
}
}
/// Exact W3C CSS Color Module Level 4 named colors plus `transparent` (149 keywords, sorted lowercase).
const CSS_NAMED_COLORS: &[&str] = &[
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgreen",
"darkgrey",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"green",
"greenyellow",
"grey",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgreen",
"lightgrey",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"rebeccapurple",
"red",
"rosybrown",
"royalblue",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"transparent",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen",
];
fn validate_css_color(raw: &str) -> Result<String, PreviewError> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(PreviewError::InvalidColor(
"color_css must not be empty".to_string(),
));
}
if trimmed.chars().any(|ch| {
matches!(
ch,
'"' | '\'' | '<' | '>' | '&' | ';' | '\\' | '\n' | '\r' | '\0'
)
}) {
return Err(PreviewError::InvalidColor(format!(
"color_css contains forbidden characters: {trimmed}"
)));
}
if trimmed.eq_ignore_ascii_case("currentColor") {
return Ok("currentColor".to_string());
}
if let Some(hex) = trimmed.strip_prefix('#') {
if matches!(hex.len(), 3 | 4 | 6 | 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Ok(format!("#{}", hex.to_ascii_lowercase()));
}
return Err(PreviewError::InvalidColor(format!(
"invalid hex CSS color: {trimmed}"
)));
}
let lower = trimmed.to_ascii_lowercase();
if let Some(inner) = lower
.strip_prefix("rgb(")
.or_else(|| lower.strip_prefix("rgba("))
.and_then(|rest| rest.strip_suffix(')'))
{
return parse_and_normalize_rgb(inner, trimmed);
}
if CSS_NAMED_COLORS.binary_search(&lower.as_str()).is_ok() {
return Ok(lower);
}
Err(PreviewError::InvalidColor(format!(
"unsupported CSS color syntax: {trimmed}"
)))
}
fn parse_and_normalize_rgb(inner: &str, raw: &str) -> Result<String, PreviewError> {
let err = |msg: &str| PreviewError::InvalidColor(format!("{msg}: {raw}"));
let inner = inner.trim();
if inner.is_empty() {
return Err(err("empty rgb/rgba channel list"));
}
let (channels, alpha_str) = if inner.contains(',') {
if inner.contains('/') {
return Err(err("cannot mix ',' and '/' in rgb/rgba"));
}
let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
if parts.iter().any(|p| p.is_empty()) || !matches!(parts.len(), 3 | 4) {
return Err(err("invalid comma-separated rgb/rgba channels"));
}
let is_pct = [parts[0], parts[1], parts[2]].map(|p| p.ends_with('%'));
if is_pct[0] != is_pct[1] || is_pct[1] != is_pct[2] {
return Err(err(
"comma-separated rgb/rgba cannot mix numbers and percentages",
));
}
([parts[0], parts[1], parts[2]], parts.get(3).copied())
} else {
let mut slash_split = inner.split('/');
let rgb_part = slash_split.next().unwrap_or("").trim();
let alpha_part = slash_split.next().map(str::trim);
if slash_split.next().is_some() {
return Err(err("multiple '/' separators in rgb/rgba"));
}
let rgb_tokens: Vec<&str> = rgb_part.split_ascii_whitespace().collect();
if rgb_tokens.len() != 3 {
return Err(err("expected 3 space-separated rgb channels"));
}
if let Some(a) = alpha_part
&& (a.is_empty() || a.split_ascii_whitespace().count() != 1)
{
return Err(err("invalid alpha component after '/'"));
}
([rgb_tokens[0], rgb_tokens[1], rgb_tokens[2]], alpha_part)
};
let r = parse_rgb_channel(channels[0], raw)?;
let g = parse_rgb_channel(channels[1], raw)?;
let b = parse_rgb_channel(channels[2], raw)?;
if let Some(alpha_tok) = alpha_str {
let a = parse_alpha_channel(alpha_tok, raw)?;
Ok(format!("rgba({r},{g},{b},{a:.4})"))
} else {
Ok(format!("rgb({r},{g},{b})"))
}
}
fn parse_rgb_channel(tok: &str, raw: &str) -> Result<u8, PreviewError> {
if let Some(pct) = tok.strip_suffix('%') {
let v = parse_css_number_in_range(pct, 0.0..=100.0, "rgb percentage", raw)?;
Ok(((v * 255.0) / 100.0).round().clamp(0.0, 255.0) as u8)
} else {
let v = parse_css_number_in_range(tok, 0.0..=255.0, "rgb channel", raw)?;
Ok(v.round() as u8)
}
}
fn parse_alpha_channel(tok: &str, raw: &str) -> Result<f64, PreviewError> {
if let Some(pct) = tok.strip_suffix('%') {
Ok(parse_css_number_in_range(pct, 0.0..=100.0, "alpha percentage", raw)? / 100.0)
} else {
parse_css_number_in_range(tok, 0.0..=1.0, "alpha", raw)
}
}
fn is_valid_css_number(tok: &str) -> bool {
let b = tok.as_bytes();
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
let int_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
let has_int = i > int_start;
let mut has_frac = false;
if i < b.len() && b[i] == b'.' {
i += 1;
let frac_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
has_frac = i > frac_start;
if !has_frac {
return false;
}
}
if !has_int && !has_frac {
return false;
}
if i < b.len() && matches!(b[i], b'e' | b'E') {
i += 1;
i += usize::from(i < b.len() && matches!(b[i], b'+' | b'-'));
let exp_start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
if i == exp_start {
return false;
}
}
i == b.len()
}
fn parse_css_number_in_range(
tok: &str,
range: std::ops::RangeInclusive<f64>,
label: &str,
raw: &str,
) -> Result<f64, PreviewError> {
if !is_valid_css_number(tok) {
return Err(PreviewError::InvalidColor(format!(
"invalid CSS number '{tok}' in {raw}"
)));
}
let val = tok
.parse::<f64>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| {
PreviewError::InvalidColor(format!("invalid numeric channel '{tok}' in {raw}"))
})?;
if !range.contains(&val) {
return Err(PreviewError::InvalidColor(format!(
"{label} out of range: {raw}"
)));
}
Ok(val)
}
fn escape_xml_attr(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => out.push_str("&amp;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
_ => out.push(ch),
}
}
out
}
fn format_paint(color: Color, default_css: &str, attr_prefix: &str) -> (String, String) {
let is_default_black =
color.r == 0.0 && color.g == 0.0 && color.b == 0.0 && (color.a - 1.0).abs() < 1e-4;
if is_default_black {
// Use explicit #000000 when caller passed currentColor so resvg renders black cleanly.
let css = if default_css.eq_ignore_ascii_case("currentColor") {
"#000000".to_string()
} else {
escape_xml_attr(default_css)
};
return (css, String::new());
}
let r = (color.r.clamp(0.0, 1.0) * 255.0).round() as u8;
let g = (color.g.clamp(0.0, 1.0) * 255.0).round() as u8;
let b = (color.b.clamp(0.0, 1.0) * 255.0).round() as u8;
let paint = format!("rgb({r},{g},{b})");
let opacity = if color.a < 0.999 {
format!(r#" {attr_prefix}-opacity="{:.3}""#, color.a.clamp(0.0, 1.0))
} else {
String::new()
};
(paint, opacity)
}
#[cfg(test)]
mod tests {
use serde::Deserialize;
@@ -806,7 +504,7 @@ mod tests {
#[test]
fn ratex_matches_v0275_katex_metrics_and_emits_zero_text_elements() {
let raw = include_str!("../tests/fixtures/katex_v0275_metrics.json");
let raw = include_str!("../../tests/fixtures/katex_v0275_metrics.json");
let fixture: KatexFixtureFile =
serde_json::from_str(raw).expect("valid katex_v0275_metrics.json");
assert_eq!(fixture.katex_version, "0.18.10");
@@ -946,54 +644,31 @@ mod tests {
.unwrap_or_else(|err| panic!("expected valid color '{valid}' to pass: {err}"));
assert!(
roxmltree::Document::parse(&out.svg).is_ok(),
"rendered SVG must be well-formed XML for color '{valid}'"
"SVG for valid color '{valid}' must parse cleanly"
);
}
assert_eq!(
validate_css_color("rgb(50%,50%,50%)").unwrap(),
"rgb(128,128,128)"
);
let half_gray = render_latex_svg(
"E = mc^2",
&MathRenderOptions {
color_css: "rgb(50%,50%,50%)".to_string(),
..MathRenderOptions::default()
},
&pool,
)
.unwrap();
assert!(half_gray.svg.contains("rgb(128,128,128)"));
for invalid in [
"",
" ",
"notacolor",
r##"#000" onload="alert(1)"##,
"red\" onclick=\"alert(1)",
"#12345",
"rgb(1, 2)",
"rgb(+, ., -)",
"rgb(,,1,2,3)",
"rgb(1.,2,3)",
"rgb(+1., 2, 3)",
"rgb(10%,20,30)",
"rgba(10%, 20, 30, 0.5)",
"rgb(256, 0, 0)",
"rgb(-1, 0, 0)",
"rgb(1, 2 3)",
"rgba(0, 0, 0, 1.5)",
"red; fill:url(http://evil)",
"<script>",
"#zzzzzz",
"rgb(300, 0, 0)",
"rgb(10%, 20, 30)",
"rgb(10 20 30 / 2)",
"rgb(10, 20, 30 / 0.5)",
"notacolor",
"hsl(0, 100%, 50%)",
] {
let opts = MathRenderOptions {
color_css: invalid.to_string(),
..MathRenderOptions::default()
};
let err = render_latex_svg("E = mc^2", &opts, &pool).unwrap_err();
assert!(
matches!(
render_latex_svg("E = mc^2", &opts, &pool),
Err(PreviewError::InvalidColor(_))
),
"expected InvalidColor for '{invalid}'"
matches!(err, PreviewError::InvalidColor(_)),
"expected InvalidColor for '{invalid}', got {err:?}"
);
}
}
@@ -1024,6 +699,50 @@ mod tests {
assert_ne!(img_a.sha256(), img_b.sha256());
}
#[test]
fn fraction_bar_and_sqrt_vinculum_snap_to_crisp_device_pixel_rows() {
let pool = FontPool::new();
let rasterizer = SvgRasterizer::new(&pool);
for (dpr, color) in [
(1.0_f32, "#121212"),
(2.0_f32, "#121212"),
(1.0_f32, "#e6e6e6"),
(2.0_f32, "#e6e6e6"),
] {
let opts = MathRenderOptions {
mode: MathDisplayMode::Display,
font_size_pt: 16.0,
padding_pt: 2.0,
color_css: color.to_string(),
};
let out = render_latex_rgba(r"\frac{\sqrt{\pi}}{2}", &opts, &pool, &rasterizer, dpr)
.expect("render_latex_rgba fraction");
let w = out.image.width_px as usize;
let h = out.image.height_px as usize;
let min_run = (w / 2).max(6);
// At least one row in the middle third must form a crisp full-alpha horizontal bar
// (fraction rule snapped to device-pixel row, alpha >= 250).
let has_crisp_fraction_bar = (h / 3..(h * 2) / 3).any(|row| {
let mut best_run = 0usize;
let mut cur_run = 0usize;
for col in 0..w {
let a = out.image.pixels[(row * w + col) * 4 + 3];
if a >= 250 {
cur_run += 1;
best_run = best_run.max(cur_run);
} else {
cur_run = 0;
}
}
best_run >= min_run
});
assert!(
has_crisp_fraction_bar,
"expected crisp >=250-alpha fraction bar row at dpr={dpr} color={color} ({w}x{h})"
);
}
}
#[cfg(feature = "typst")]
#[test]
fn mitex_typst_candidate_with_prelude_runs_for_parity_comparison() {
+67 -1
View File
@@ -6,7 +6,7 @@ use crate::engine::PreviewEngine;
#[cfg(feature = "typst")]
use crate::PreviewDate;
#[cfg(feature = "math")]
use crate::math::MathRenderOptions;
use crate::math::{MathDisplayMode, MathRenderOptions};
#[cfg(feature = "mermaid")]
use crate::mermaid::{MermaidOptions, MermaidTheme};
#[cfg(feature = "pdf")]
@@ -193,6 +193,72 @@ impl RawWorkerState {
Err("pdf feature disabled in this worker".to_string())
}
}
8 => {
#[cfg(feature = "math")]
{
if payload.len() < 15 {
return Err("missing math rgba header".to_string());
}
let mode = match payload[0] {
0 => MathDisplayMode::Inline,
1 => MathDisplayMode::Display,
other => return Err(format!("invalid math display mode tag {other}")),
};
let raw_fs =
f32::from_le_bytes([payload[1], payload[2], payload[3], payload[4]]);
let raw_pad =
f32::from_le_bytes([payload[5], payload[6], payload[7], payload[8]]);
let raw_scale =
f32::from_le_bytes([payload[9], payload[10], payload[11], payload[12]]);
let color_len = u16::from_le_bytes([payload[13], payload[14]]) as usize;
if payload.len() < 15 + color_len {
return Err("truncated math rgba color_css".to_string());
}
let color_css = std::str::from_utf8(&payload[15..15 + color_len])
.map_err(|e| format!("invalid color_css utf8: {e}"))?
.to_string();
let latex = std::str::from_utf8(&payload[15 + color_len..])
.map_err(|e| format!("invalid latex utf8: {e}"))?;
let font_size_pt = if raw_fs.is_finite() && raw_fs > 0.0 {
f64::from(raw_fs.clamp(6.0, 96.0))
} else {
16.0
};
let padding_pt = if raw_pad.is_finite() && raw_pad >= 0.0 {
f64::from(raw_pad.min(32.0))
} else {
0.0
};
let scale = if raw_scale.is_finite() && raw_scale > 0.0 {
raw_scale.clamp(1.0, 4.0)
} else {
2.0
};
let opts = MathRenderOptions {
mode,
font_size_pt,
padding_pt,
color_css,
};
let out = self
.engine
.render_latex_rgba(latex, &opts, scale)
.map_err(|e| e.to_string())?;
let mut frame = Vec::with_capacity(21 + out.image.pixels.len());
frame.push(1);
frame.extend_from_slice(&(out.width_pt as f32).to_le_bytes());
frame.extend_from_slice(&(out.ascent_pt as f32).to_le_bytes());
frame.extend_from_slice(&(out.descent_pt as f32).to_le_bytes());
frame.extend_from_slice(&out.image.width_px.to_le_bytes());
frame.extend_from_slice(&out.image.height_px.to_le_bytes());
frame.extend_from_slice(&out.image.pixels);
Ok(frame)
}
#[cfg(not(feature = "math"))]
{
Err("math feature disabled in this worker".to_string())
}
}
other => Err(format!("unknown worker opcode {other}")),
}
}
+1 -8
View File
@@ -9,22 +9,15 @@ license.workspace = true
[lints]
workspace = true
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = []
wasm-codec = ["dep:wasm-bindgen"]
[dependencies]
base64.workspace = true
blocksuite-playground-doc = { path = "../../../blocksuite/crates/doc", default-features = false }
chrono.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
thiserror.workspace = true
url.workspace = true
wasm-bindgen = { workspace = true, optional = true }
y-octo.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dependencies]
+13 -74
View File
@@ -1,33 +1,13 @@
use std::collections::BTreeMap;
use y_octo::{
Any, DocOptions, DocSession, SessionConfig, SessionReadValue, SessionUndoConfig, TypePath,
TypeTarget, merge_updates_v1, validate_update_v1,
};
use blocksuite_playground_doc::crdt_v1;
use crate::error::{StoreError, StoreResult};
fn is_empty_crdt_update(bin: &[u8]) -> bool {
bin.is_empty() || bin == [0, 0]
}
/// Merge a slice of encoded Yjs v1 CRDT updates into a single v1 update (native + `wasm32`).
pub fn merge_crdt_updates_v1(updates: &[&[u8]]) -> StoreResult<Vec<u8>> {
let non_empty: Vec<&[u8]> = updates
.iter()
.copied()
.filter(|u| !is_empty_crdt_update(u))
.collect();
match non_empty.as_slice() {
[] => Ok(vec![0, 0]),
[single] => {
validate_update_v1(single).map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
Ok((*single).to_vec())
}
many => merge_updates_v1(many.iter().copied())
.and_then(|merged| merged.encode_v1())
.map_err(|err| StoreError::InvalidBinary(err.to_string())),
}
crdt_v1::merge_crdt_updates_v1(updates)
.map_err(|err| StoreError::InvalidBinary(err.to_string()))
}
/// Bidirectional document ID converter matching `packages/common/nbstore/src/utils/id-converter.ts`.
@@ -93,44 +73,10 @@ impl IdConverter {
let Some(bytes) = root_doc_bytes else {
return Ok(converter);
};
if bytes.is_empty() || bytes == [0, 0] {
return Ok(converter);
}
let options = DocOptions::from_identity(1, effective_root_id.to_string());
let mut session = DocSession::<()>::with_config(
options,
SessionConfig {
undo: SessionUndoConfig::Disabled,
},
);
session
.apply_update_v1(bytes)
let mappings = crdt_v1::extract_page_subdoc_mappings(effective_root_id, bytes)
.map_err(|err| StoreError::InvalidBinary(err.to_string()))?;
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
let Ok(page_items) = session.read_array(&pages_target) else {
return Ok(converter);
};
let spaces_target = TypeTarget::Path(TypePath::root("spaces"));
for item in page_items {
let SessionReadValue::Map(map_id) = item else {
continue;
};
let Ok(Some(SessionReadValue::Any(Any::String(page_id)))) =
session.get_map_value(&TypeTarget::Identity(map_id), "id")
else {
continue;
};
if page_id.is_empty() {
continue;
}
if let Ok(Some(SessionReadValue::Doc { guid, .. })) =
session.get_map_value(&spaces_target, &page_id)
{
converter.register_page_mapping(page_id, guid);
}
for (page_id, guid) in mappings {
converter.register_page_mapping(page_id, guid);
}
Ok(converter)
@@ -139,21 +85,11 @@ impl IdConverter {
/// Extract live `meta.pages -> spaces` subdoc GUIDs from one or more encoded Yjs v1 root
/// document updates (merged via `y-octo`, rejecting malformed or truncated frames).
pub fn extract_subdoc_guids_from_root_updates(
space_id: &str,
_space_id: &str,
root_updates: &[&[u8]],
) -> StoreResult<Vec<String>> {
if root_updates.is_empty() {
return Ok(Vec::new());
}
let merged = merge_crdt_updates_v1(root_updates)?;
let converter = Self::from_root_doc_bytes(space_id, None, Some(&merged))?;
let mut guids = Vec::new();
for (_, guid) in converter.page_mappings() {
if !guids.iter().any(|existing| existing == guid) {
guids.push(guid.to_string());
}
}
Ok(guids)
crdt_v1::extract_subdoc_guids_from_root_updates(root_updates)
.map_err(|err| StoreError::InvalidBinary(err.to_string()))
}
/// Register a bidirectional alias between normalized `page_id` and legacy `subdoc_guid`.
@@ -248,7 +184,10 @@ fn convert_userdata_old_to_new(old_id: &str, space_id: &str) -> Option<String> {
#[cfg(test)]
mod tests {
use y_octo::{SessionTxOrigin, SessionValue, YTypeKind};
use y_octo::{
Any, DocOptions, DocSession, SessionConfig, SessionTxOrigin, SessionUndoConfig,
SessionValue, TypePath, TypeTarget, YTypeKind,
};
use super::*;
-2
View File
@@ -11,8 +11,6 @@ pub mod idb;
#[cfg(not(target_family = "wasm"))]
pub mod sqlite;
pub mod sync;
#[cfg(feature = "wasm-codec")]
pub mod wasm_codec;
pub mod workspace_db;
pub use clock::{Clock, ManualClock};
-360
View File
@@ -1,360 +0,0 @@
//! Pure-safe-Rust scalar `u32` Wasm ABI for Web thin-host CRDT operations.
//!
//! Exports four `#[wasm_bindgen]` scalar functions (`affine_crdt_reset_input`,
//! `affine_crdt_push_input_u32`, `affine_crdt_invoke`, `affine_crdt_output_u32`)
//! so browsers instantiate `crdt-codec.wasm` directly with `WebAssembly.instantiate`
//! without `wasm-bindgen-cli` or third-party JS glue.
use wasm_bindgen::prelude::*;
use crate::id_converter::{IdConverter, merge_crdt_updates_v1};
const OPCODE_MERGE_UPDATES_V1: u8 = 1;
const OPCODE_EXTRACT_SUBDOC_IDS: u8 = 2;
std::thread_local! {
static CODEC_STATE: std::cell::RefCell<RawCodecState> =
std::cell::RefCell::new(RawCodecState::new());
}
struct RawCodecState {
input: Vec<u8>,
output: Vec<u8>,
}
impl RawCodecState {
fn new() -> Self {
Self {
input: Vec::new(),
output: Vec::new(),
}
}
/// Dispatches `[opcode: u8, frame_count: u32_le, (len_i: u32_le, bytes_i)...]`
/// and returns a binary response frame:
/// - `0x01` + payload on success
/// - `0x00` + UTF-8 error text on failure
fn dispatch(&self) -> Result<Vec<u8>, String> {
let (&opcode, payload) = self
.input
.split_first()
.ok_or_else(|| "empty crdt codec request".to_string())?;
let frames = decode_frames(payload)?;
match opcode {
OPCODE_MERGE_UPDATES_V1 => {
let merged = merge_crdt_updates_v1(&frames).map_err(|err| err.to_string())?;
let mut frame = Vec::with_capacity(1 + merged.len());
frame.push(1);
frame.extend_from_slice(&merged);
Ok(frame)
}
OPCODE_EXTRACT_SUBDOC_IDS => {
let mut guids = IdConverter::extract_subdoc_guids_from_root_updates("", &frames)
.map_err(|err| err.to_string())?;
guids.sort();
guids.dedup();
let json = serde_json::to_vec(&guids)
.map_err(|err| format!("failed to serialize subdoc guids: {err}"))?;
let mut frame = Vec::with_capacity(1 + json.len());
frame.push(1);
frame.extend_from_slice(&json);
Ok(frame)
}
other => Err(format!("unknown crdt codec opcode {other}")),
}
}
}
fn decode_frames(payload: &[u8]) -> Result<Vec<&[u8]>, String> {
if payload.len() < 4 {
return Err("truncated frame_count header".to_string());
}
let frame_count = u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]]) as usize;
let mut cursor = 4usize;
let remaining = payload.len().saturating_sub(cursor);
if frame_count > remaining / 4 {
return Err(format!(
"frame_count {frame_count} exceeds payload capacity ({remaining} bytes)"
));
}
let mut frames = Vec::with_capacity(frame_count);
for idx in 0..frame_count {
let len_end = cursor
.checked_add(4)
.ok_or_else(|| format!("frame {idx} length header overflow"))?;
if len_end > payload.len() {
return Err(format!("truncated length header at frame {idx}"));
}
let frame_len = u32::from_le_bytes([
payload[cursor],
payload[cursor + 1],
payload[cursor + 2],
payload[cursor + 3],
]) as usize;
cursor = len_end;
let body_end = cursor
.checked_add(frame_len)
.ok_or_else(|| format!("frame {idx} body length overflow"))?;
if body_end > payload.len() {
return Err(format!(
"truncated frame {idx} body: expected {frame_len} bytes, {} remaining",
payload.len() - cursor
));
}
frames.push(&payload[cursor..body_end]);
cursor = body_end;
}
if cursor != payload.len() {
return Err(format!(
"unexpected trailing bytes in request: {} extra bytes",
payload.len() - cursor
));
}
Ok(frames)
}
/// Clears the codec's raw request and response buffers ahead of streaming a request.
#[wasm_bindgen]
pub fn affine_crdt_reset_input() {
CODEC_STATE.with(|cell| {
let mut st = cell.borrow_mut();
st.input.clear();
st.output.clear();
});
}
/// Appends `valid_bytes` (1..=4) little-endian bytes of `word` to the raw request buffer.
#[wasm_bindgen]
pub fn affine_crdt_push_input_u32(word: u32, valid_bytes: u32) {
let count = (valid_bytes as usize).min(4);
let bytes = word.to_le_bytes();
CODEC_STATE.with(|cell| {
cell.borrow_mut().input.extend_from_slice(&bytes[..count]);
});
}
/// Executes the buffered CRDT request and returns the binary response frame length.
#[wasm_bindgen]
pub fn affine_crdt_invoke() -> usize {
CODEC_STATE.with(|cell| {
let mut st = cell.borrow_mut();
let response = match st.dispatch() {
Ok(ok) => ok,
Err(err) => {
let mut frame = Vec::with_capacity(1 + err.len());
frame.push(0);
frame.extend_from_slice(err.as_bytes());
frame
}
};
st.output = response;
st.output.len()
})
}
/// Reads 4 little-endian bytes from the response frame at `word_index * 4`.
#[wasm_bindgen]
pub fn affine_crdt_output_u32(word_index: usize) -> u32 {
CODEC_STATE.with(|cell| {
let st = cell.borrow();
let base = word_index.saturating_mul(4);
let mut chunk = [0_u8; 4];
for (offset, slot) in chunk.iter_mut().enumerate() {
if let Some(&b) = st.output.get(base + offset) {
*slot = b;
}
}
u32::from_le_bytes(chunk)
})
}
#[cfg(test)]
mod tests {
use y_octo::{Doc, DocOptions};
use super::*;
fn encode_request(opcode: u8, frames: &[&[u8]]) -> Vec<u8> {
let mut out = Vec::new();
out.push(opcode);
out.extend_from_slice(&(frames.len() as u32).to_le_bytes());
for frame in frames {
out.extend_from_slice(&(frame.len() as u32).to_le_bytes());
out.extend_from_slice(frame);
}
out
}
fn invoke_raw(req: &[u8]) -> Vec<u8> {
affine_crdt_reset_input();
for chunk in req.chunks(4) {
let mut word = [0_u8; 4];
word[..chunk.len()].copy_from_slice(chunk);
affine_crdt_push_input_u32(u32::from_le_bytes(word), chunk.len() as u32);
}
let out_len = affine_crdt_invoke();
let mut out = Vec::with_capacity(out_len);
let word_count = out_len.div_ceil(4);
for w in 0..word_count {
let word = affine_crdt_output_u32(w).to_le_bytes();
let remain = out_len - out.len();
out.extend_from_slice(&word[..remain.min(4)]);
}
out
}
#[test]
fn merge_updates_opcode_handles_empty_single_and_multi_frame() {
// 0 frames -> [0x01, 0x00, 0x00] (canonical 2-byte empty Yjs v1 update, identical to native).
let empty_resp = invoke_raw(&encode_request(OPCODE_MERGE_UPDATES_V1, &[]));
assert_eq!(empty_resp, vec![1, 0, 0]);
assert_eq!(&empty_resp[1..], merge_crdt_updates_v1(&[]).unwrap());
// Two concurrent client updates merge losslessly.
let doc_a = Doc::with_options(DocOptions::from_identity(101, String::new()));
let mut text_a = doc_a.get_or_create_text("content").unwrap();
text_a.insert(0, "hello ").unwrap();
let upd_a = doc_a.encode_update_v1().unwrap();
let doc_b = Doc::with_options(DocOptions::from_identity(202, String::new()));
let mut text_b = doc_b.get_or_create_text("content").unwrap();
text_b.insert(0, "world").unwrap();
let upd_b = doc_b.encode_update_v1().unwrap();
// Native merge_crdt_updates_v1 vs Wasm ABI must be byte-identical across all shapes.
let empty_u8: &[u8] = &[0, 0];
let parity_cases: [&[&[u8]]; 4] = [
&[],
&[&upd_a],
&[&upd_a, &upd_b],
&[empty_u8, &upd_a, &[], &upd_b],
];
for frames in parity_cases {
let native = merge_crdt_updates_v1(frames).unwrap();
let wasm_resp = invoke_raw(&encode_request(OPCODE_MERGE_UPDATES_V1, frames));
assert_eq!(wasm_resp[0], 1);
assert_eq!(
&wasm_resp[1..],
native.as_slice(),
"wasm_codec must be byte-identical to native merge_crdt_updates_v1"
);
}
// Single frame still validates and encodes.
let single_resp = invoke_raw(&encode_request(OPCODE_MERGE_UPDATES_V1, &[&upd_a]));
assert_eq!(single_resp[0], 1);
let mut check_single = Doc::with_options(DocOptions::from_identity(303, String::new()));
check_single
.apply_update_from_binary_v1(&single_resp[1..])
.unwrap();
assert_eq!(
check_single
.get_or_create_text("content")
.unwrap()
.to_string(),
"hello "
);
// Multi-frame merge preserves both clients' insertions.
let merged_resp = invoke_raw(&encode_request(OPCODE_MERGE_UPDATES_V1, &[&upd_a, &upd_b]));
assert_eq!(merged_resp[0], 1);
let mut merged_doc = Doc::with_options(DocOptions::from_identity(404, String::new()));
merged_doc
.apply_update_from_binary_v1(&merged_resp[1..])
.unwrap();
let text = merged_doc
.get_or_create_text("content")
.unwrap()
.to_string();
assert!(text.contains("hello "));
assert!(text.contains("world"));
}
#[test]
fn extract_subdoc_ids_opcode_handles_real_yjs_v1_updates_and_overwrites() {
// Real Yjs v1 binary updates (same fixture as verify-idb-real-browser.mjs):
// update 1 inserts old-guid, update 2 overwrites same key with live-guid + DeleteSet.
let real_yjs_v1: [&[u8]; 2] = [
&[
1, 6, 105, 0, 39, 1, 4, 109, 101, 116, 97, 5, 112, 97, 103, 101, 115, 0, 7, 0, 105,
0, 1, 40, 0, 105, 1, 2, 105, 100, 1, 119, 2, 112, 49, 40, 0, 105, 1, 5, 116, 105,
116, 108, 101, 1, 119, 9, 76, 105, 118, 101, 32, 80, 97, 103, 101, 41, 1, 6, 115,
112, 97, 99, 101, 115, 2, 112, 49, 8, 111, 108, 100, 45, 103, 117, 105, 100, 118,
0, 41, 1, 8, 111, 116, 104, 101, 114, 77, 97, 112, 7, 102, 111, 114, 101, 105, 103,
110, 12, 102, 111, 114, 101, 105, 103, 110, 45, 103, 117, 105, 100, 118, 0, 0,
],
&[
1, 1, 105, 6, 169, 105, 4, 9, 108, 105, 118, 101, 45, 103, 117, 105, 100, 118, 0,
1, 105, 1, 4, 1,
],
];
let resp = invoke_raw(&encode_request(OPCODE_EXTRACT_SUBDOC_IDS, &real_yjs_v1));
assert_eq!(
resp[0],
1,
"unexpected error: {:?}",
String::from_utf8_lossy(&resp[1..])
);
let guids: Vec<String> = serde_json::from_slice(&resp[1..]).unwrap();
assert_eq!(guids, vec!["live-guid".to_string()]);
// Merging first and then extracting produces the exact same live GUID.
let merged_resp = invoke_raw(&encode_request(OPCODE_MERGE_UPDATES_V1, &real_yjs_v1));
assert_eq!(merged_resp[0], 1);
let after_merge = invoke_raw(&encode_request(
OPCODE_EXTRACT_SUBDOC_IDS,
&[&merged_resp[1..]],
));
assert_eq!(after_merge[0], 1);
let guids_after_merge: Vec<String> = serde_json::from_slice(&after_merge[1..]).unwrap();
assert_eq!(guids_after_merge, vec!["live-guid".to_string()]);
}
#[test]
fn malformed_frames_and_corrupt_updates_return_error_frame_without_panicking() {
let invalid_inputs: [(&str, Vec<u8>); 7] = [
("empty input", vec![]),
("truncated frame_count", vec![OPCODE_MERGE_UPDATES_V1, 0, 0]),
(
"impossible frame_count",
vec![OPCODE_MERGE_UPDATES_V1, 0xff, 0xff, 0xff, 0x7f],
),
(
"truncated frame length",
vec![OPCODE_MERGE_UPDATES_V1, 1, 0, 0, 0, 1, 0],
),
(
"truncated frame body",
vec![OPCODE_MERGE_UPDATES_V1, 1, 0, 0, 0, 10, 0, 0, 0, 1, 2],
),
(
"trailing garbage",
vec![OPCODE_MERGE_UPDATES_V1, 0, 0, 0, 0, 0xaa],
),
("unknown opcode", vec![99, 0, 0, 0, 0]),
];
for (label, req) in invalid_inputs {
let resp = invoke_raw(&req);
assert_eq!(
resp.first().copied(),
Some(0),
"case {label} must return 0x00"
);
assert!(
resp.len() > 1,
"case {label} must include non-empty error text"
);
}
// Corrupt Yjs binary must return 0x00 error frame for both opcodes.
let corrupt = [0xff_u8, 0xff, 0xff, 0xff, 0x80];
for opcode in [OPCODE_MERGE_UPDATES_V1, OPCODE_EXTRACT_SUBDOC_IDS] {
let resp = invoke_raw(&encode_request(opcode, &[&corrupt]));
assert_eq!(
resp.first().copied(),
Some(0),
"corrupt binary must fail for opcode {opcode}"
);
}
}
}
+3 -1
View File
@@ -101,6 +101,7 @@ name = "affine-store"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"blocksuite-playground-doc",
"chrono",
"serde",
"serde_json",
@@ -109,7 +110,6 @@ dependencies = [
"thiserror 2.0.21",
"tokio",
"url",
"wasm-bindgen",
"y-octo",
]
@@ -4355,9 +4355,11 @@ dependencies = [
"console_error_panic_hook",
"futures-util",
"image",
"jiff",
"js-sys",
"serde",
"serde_json",
"sha2 0.10.9",
"tempfile",
"tokio",
"tokio-tungstenite 0.26.2",
+222 -2
View File
@@ -20,8 +20,12 @@ use affine_store::{
workspace_db::{PendingDocUpdate, derive_page_id_for_op},
};
use blocksuite_editor::{
DirectoryError, DocQueryPage, DocQueryRequest, EditorDocId, EditorDocMode, EditorDocSummary,
MatchedDocSummary, WorkspaceDocDirectory, match_exact_substring_utf16,
DirectoryError, DocQueryPage, DocQueryRequest, EditorDocId, EditorDocMode, EditorDocPreview,
EditorDocSummary, MatchedDocSummary, WorkspaceDocDirectory, match_exact_substring_utf16,
};
use blocksuite_playground_doc::{
read::{BlockContent, PageSnapshot},
session::PageDocSession,
};
use serde::{Deserialize, Serialize};
@@ -59,6 +63,38 @@ pub struct CreateIntentLedger {
pub intents: BTreeMap<String, CreateIntentEntry>,
}
struct CachedDocContent {
revision: u64,
snippet: String,
snapshot: Arc<PageSnapshot>,
}
type DocUpdateLoader = Arc<dyn Fn(&str) -> Option<(u64, Vec<u8>)> + Send + Sync>;
fn extract_snapshot_snippet(snapshot: &PageSnapshot) -> String {
let Some(root) = &snapshot.root else {
return String::new();
};
let mut parts = Vec::new();
for node in root.walk() {
let text = match &node.content {
BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => {
text.plain.trim()
}
BlockContent::Callout { text, .. } => text.plain.trim(),
BlockContent::Code { text, .. } => text.trim(),
_ => "",
};
if !text.is_empty() {
parts.push(text.to_string());
if parts.len() >= 2 {
break;
}
}
}
parts.join(" ")
}
/// Production [`WorkspaceDocDirectory`] backed by a shared [`WorkspaceDirectory`] and [`CreateIntentLedger`].
pub struct StoreBackedDocDirectory {
directory: Arc<Mutex<WorkspaceDirectory>>,
@@ -66,6 +102,8 @@ pub struct StoreBackedDocDirectory {
now_ms: i64,
replica_seed: Option<String>,
next_ephemeral_op: u64,
page_cache: Mutex<BTreeMap<String, CachedDocContent>>,
doc_loader: Option<DocUpdateLoader>,
}
impl StoreBackedDocDirectory {
@@ -92,9 +130,88 @@ impl StoreBackedDocDirectory {
now_ms: initial_now_ms,
replica_seed,
next_ephemeral_op: 0,
page_cache: Mutex::new(BTreeMap::new()),
doc_loader: None,
}
}
/// Attach an on-demand `(revision, v1_update_bytes)` loader for child page documents so
/// `doc_preview` and `doc_snapshot` resolve embedded linked/synced document cards directly
/// from the host document store.
pub fn with_doc_loader(
mut self,
loader: impl Fn(&str) -> Option<(u64, Vec<u8>)> + Send + Sync + 'static,
) -> Self {
self.doc_loader = Some(Arc::new(loader));
self
}
/// Register or refresh a decoded child page snapshot for `id` (zero CRDT writeback).
pub fn upsert_doc_snapshot(
&self,
id: &EditorDocId,
snapshot: Arc<PageSnapshot>,
revision: u64,
) {
let snippet = extract_snapshot_snippet(&snapshot);
self.page_cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(
id.as_str().to_string(),
CachedDocContent {
revision,
snippet,
snapshot,
},
);
}
/// Decode and cache a child page's binary v1 CRDT update for embedded card previews.
pub fn load_doc_update_v1(
&self,
id: &EditorDocId,
update_v1: &[u8],
revision: u64,
) -> Result<(), DirectoryError> {
let mut session = PageDocSession::new(id.as_str(), 1)
.map_err(|e| DirectoryError::Other(e.to_string()))?;
if !update_v1.is_empty() {
session
.apply_remote_update_v1(update_v1)
.map_err(|e| DirectoryError::Other(e.to_string()))?;
}
let snapshot = session
.read_page_snapshot()
.map_err(|e| DirectoryError::Other(e.to_string()))?;
self.upsert_doc_snapshot(id, Arc::new(snapshot), revision);
Ok(())
}
fn resolve_cached_or_loaded_content(
&self,
doc_id: &str,
) -> Option<(u64, String, Arc<PageSnapshot>)> {
if let Some(loader) = &self.doc_loader
&& let Some((rev, bytes)) = loader(doc_id)
{
let needs_decode = self
.page_cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(doc_id)
.is_none_or(|c| c.revision != rev);
if needs_decode {
let _ = self.load_doc_update_v1(&EditorDocId::new(doc_id), &bytes, rev);
}
}
self.page_cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(doc_id)
.map(|c| (c.revision, c.snippet.clone(), Arc::clone(&c.snapshot)))
}
pub fn shared_directory(&self) -> Arc<Mutex<WorkspaceDirectory>> {
Arc::clone(&self.directory)
}
@@ -386,6 +503,42 @@ impl WorkspaceDocDirectory for StoreBackedDocDirectory {
}
}
}
fn doc_preview(&self, id: &EditorDocId) -> Option<EditorDocPreview> {
let doc_id = DocId::new(id.as_str()).ok()?;
let entry = self
.lock_directory()
.get_doc(&doc_id)
.ok()
.flatten()
.filter(|e| !e.trashed)?;
let updated_at_ms = entry.updated_date_ms.unwrap_or(entry.create_date_ms);
let (revision, snippet) = self
.resolve_cached_or_loaded_content(id.as_str())
.map(|(rev, snip, _)| (rev, snip))
.unwrap_or((1, String::new()));
Some(EditorDocPreview {
title: entry.title,
snippet,
updated_at_ms,
revision,
})
}
fn doc_snapshot(&self, id: &EditorDocId) -> Option<Arc<PageSnapshot>> {
let doc_id = DocId::new(id.as_str()).ok()?;
let exists = self
.lock_directory()
.get_doc(&doc_id)
.ok()
.flatten()
.is_some_and(|e| !e.trashed);
if !exists {
return None;
}
self.resolve_cached_or_loaded_content(id.as_str())
.map(|(_, _, snap)| snap)
}
}
#[cfg(test)]
@@ -512,4 +665,71 @@ mod tests {
.is_some()
);
}
#[test]
fn doc_preview_and_snapshot_resolve_store_backed_linked_and_synced_cards() {
use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType};
let mut dir = new_store_backed_directory();
let created = dir
.create_linked_doc("Mobile Spec", EditorDocMode::Page, Some("spec-1"))
.unwrap();
// Before child page bytes arrive, preview resolves title + timestamp while snapshot is None.
let initial_preview = dir.doc_preview(&created.id).expect("store preview");
assert_eq!(initial_preview.title, "Mobile Spec");
assert_eq!(initial_preview.snippet, "");
assert_eq!(initial_preview.updated_at_ms, 1_000);
assert!(dir.doc_snapshot(&created.id).is_none());
// Populate child page CRDT update and verify both snippet and snapshot resolve cleanly.
let mut child = PageDocSession::new(created.id.as_str(), 7).unwrap();
child
.add_block(
"r",
BlockSpec::Page {
title: "Mobile Spec".into(),
},
None,
None,
1,
)
.unwrap();
child
.add_block("n", BlockSpec::Note { xywh: None }, Some("r"), None, 2)
.unwrap();
child
.add_block(
"p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Synced content from StoreBackedDocDirectory.".into(),
},
Some("n"),
None,
3,
)
.unwrap();
let update_bytes = child.encode_update_v1().unwrap();
dir.load_doc_update_v1(&created.id, &update_bytes, 4)
.unwrap();
let full_preview = dir.doc_preview(&created.id).expect("rich preview");
assert_eq!(full_preview.title, "Mobile Spec");
assert_eq!(
full_preview.snippet,
"Synced content from StoreBackedDocDirectory."
);
assert_eq!(full_preview.revision, 4);
let snap = dir.doc_snapshot(&created.id).expect("synced snapshot");
assert!(snap.block("p1").is_some());
// Trashing the document hides both preview and snapshot.
let store_doc_id = DocId::new(created.id.as_str()).unwrap();
dir.lock_directory()
.trash_doc(&store_doc_id, 2_000)
.unwrap();
assert!(dir.doc_preview(&created.id).is_none());
assert!(dir.doc_snapshot(&created.id).is_none());
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ node --test hosts/web/tests/*.test.mjs
node hosts/web/scripts/verify-zero-third-party-js.mjs
```
After building the four `blocksuite-preview` `wasm32-unknown-unknown` workers and the `affine-store` `wasm-codec` (`crdt-codec.wasm`) binary with `--profile wasm-release` (`target/wasm32-unknown-unknown/wasm-release/*.wasm`), stage the binaries plus static fonts and run the end-to-end worker and real-browser verification scripts:
After building the four `blocksuite-preview` `wasm32-unknown-unknown` workers and the main `playground` Wasm bundle (`wasm-bindgen --target web`) with `--profile wasm-release`, stage the binaries plus static fonts and run the end-to-end worker and real-browser verification scripts:
```sh
node hosts/web/scripts/stage-preview-workers.mjs /tmp/preview-wasm dev-local
+1 -1
View File
@@ -153,7 +153,7 @@
"shellVersion": "mobile-v1",
"buildHash": "dev-local",
"appEntryJs": "/src/default-app-entry.js",
"crdtCodecWasm": "/assets/crdt-codec.dev-local.wasm",
"mainWasmJs": "/assets/pkg/playground.js",
"workers": {
"mermaid": {
"script": "/src/workers/mermaid-worker.js",
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// @ts-check
import { copyFileSync, existsSync, mkdirSync } from 'node:fs';
import { copyFileSync, cpSync, existsSync, mkdirSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -44,11 +44,28 @@ for (const kind of KINDS) {
copyFileSync(src, dst);
}
const crdtCodecSrc = join(SOURCE_DIR, 'crdt-codec.wasm');
if (!existsSync(crdtCodecSrc)) {
throw new Error(`Missing built CRDT codec wasm binary: ${crdtCodecSrc}`);
const PKG_OUT_DIR = join(ASSETS_DIR, 'pkg');
const pkgSrcDir = join(SOURCE_DIR, 'pkg');
if (
existsSync(join(pkgSrcDir, 'playground.js')) &&
existsSync(join(pkgSrcDir, 'playground_bg.wasm'))
) {
mkdirSync(PKG_OUT_DIR, { recursive: true });
copyFileSync(
join(pkgSrcDir, 'playground.js'),
join(PKG_OUT_DIR, 'playground.js')
);
copyFileSync(
join(pkgSrcDir, 'playground_bg.wasm'),
join(PKG_OUT_DIR, 'playground_bg.wasm')
);
const snippetsSrc = join(pkgSrcDir, 'snippets');
if (existsSync(snippetsSrc)) {
cpSync(snippetsSrc, join(PKG_OUT_DIR, 'snippets'), { recursive: true });
}
} else {
throw new Error(`Missing main wasm-bindgen package under: ${pkgSrcDir}`);
}
copyFileSync(crdtCodecSrc, join(ASSETS_DIR, `crdt-codec.${BUILD_HASH}.wasm`));
for (const font of FONT_SPECS) {
if (!existsSync(font.src)) {
@@ -58,5 +75,5 @@ for (const font of FONT_SPECS) {
}
console.log(
`Staged 4 preview Wasm workers, CRDT codec Wasm, and ${FONT_SPECS.length} static fonts into ${ASSETS_DIR}`
`Staged 4 preview Wasm workers, main playground Wasm bundle, and ${FONT_SPECS.length} static fonts into ${ASSETS_DIR}`
);
@@ -110,7 +110,11 @@ const PROBE_HTML = `<!doctype html>
<head><meta charset="utf-8" /></head>
<body>
<script type="module">
import { createCrdtWasmClient } from '/src/crdt-wasm-client.js';
window.__AFFINE_WEB_HOST__ = true;
import initPlayground, {
extract_subdoc_ids,
merge_updates_v1,
} from '/assets/pkg/playground.js';
import {
createIdbV1ReadonlyReader,
createIdbWorkspaceStorage,
@@ -261,20 +265,16 @@ const PROBE_HTML = `<!doctype html>
});
v1Db.close();
const crdtCodec = createCrdtWasmClient(
'/assets/crdt-codec.dev-local.wasm'
);
await crdtCodec.ready();
await initPlayground();
const reader = createIdbV1ReadonlyReader({
workspaceId: 'ws-v1-e2e',
mergeUpdates: updates => crdtCodec.mergeUpdates(updates),
extractSubdocIds: rootUpdates =>
crdtCodec.extractSubdocIds(rootUpdates),
mergeUpdates: updates => merge_updates_v1(updates),
extractSubdocIds: rootUpdates => extract_subdoc_ids(rootUpdates),
});
const listed = await reader.listV1DocIds();
const mergedRoot = await reader.getV1Doc('ws-v1-e2e');
const roundtrippedSubdocs = mergedRoot?.bin
? await crdtCodec.extractSubdocIds([mergedRoot.bin])
? extract_subdoc_ids([mergedRoot.bin])
: [];
const subRaw = await reader.getV1DocRaw('live-guid');
result.v1 = {
@@ -7,7 +7,6 @@ import { join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { Worker as NodeWorker } from 'node:worker_threads';
import { createCrdtWasmClient } from '../src/crdt-wasm-client.js';
import { createWorkerLoader } from '../src/worker-loader.js';
const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
@@ -249,7 +248,7 @@ try {
'Mermaid dark SVG must apply AFFiNE Dark palette'
);
// 3. Math (RaTeX) worker
// 3. Math (RaTeX) worker: both SVG (`op` omitted) and premultiplied RGBA (`op: 'rgba'`).
const mathWorker = /** @type {any} */ (loader.loadWorker('math'));
const mathRes = await mathWorker.rpc({
id: 3,
@@ -258,6 +257,80 @@ try {
assert.equal(mathRes.ok, true, `math worker failed: ${mathRes.error}`);
assert.ok(mathRes.result.svg.includes('<svg'));
const mathInlineRgba = await mathWorker.rpc({
id: 30,
op: 'rgba',
latex: String.raw`\frac{1}{2}`,
display: false,
fontSizePt: 14.72,
paddingPt: 1.5,
colorCss: '#121212',
scaleFactor: 2.0,
});
const mathDisplayRgba = await mathWorker.rpc({
id: 31,
op: 'rgba',
latex: String.raw`\frac{\sqrt{\pi}}{2}`,
display: true,
fontSizePt: 18.0,
paddingPt: 4.0,
colorCss: '#e6e6e6',
scaleFactor: 2.0,
});
assert.equal(
mathInlineRgba.ok,
true,
`math inline rgba failed: ${mathInlineRgba.error}`
);
assert.equal(
mathDisplayRgba.ok,
true,
`math display rgba failed: ${mathDisplayRgba.error}`
);
assert.ok(
mathDisplayRgba.result.ascentPt + mathDisplayRgba.result.descentPt >
mathInlineRgba.result.ascentPt + mathInlineRgba.result.descentPt + 8,
'Display 18pt fraction must be taller than Inline 14.72pt fraction'
);
const inlineTotalPt =
mathInlineRgba.result.ascentPt + mathInlineRgba.result.descentPt;
assert.ok(
Math.abs(mathInlineRgba.result.ascentPt / inlineTotalPt - 0.78) > 0.05,
`Inline fraction baseline must come from real KaTeX metrics, got ${mathInlineRgba.result.ascentPt}/${inlineTotalPt}`
);
// Premultiplied RGBA8 invariant (`R, G, B <= A`) + crisp >=250-alpha dark-mode fraction bar row.
const dPixels = mathDisplayRgba.result.rgba;
const dW = mathDisplayRgba.result.widthPx;
const dH = mathDisplayRgba.result.heightPx;
assert.equal(dPixels.byteLength, dW * dH * 4);
for (let i = 0; i < dPixels.byteLength; i += 4) {
const a = dPixels[i + 3];
assert.ok(
dPixels[i] <= a && dPixels[i + 1] <= a && dPixels[i + 2] <= a,
`math worker RGBA must be premultiplied (pixel ${i / 4}: rgba=${dPixels[i]},${dPixels[i + 1]},${dPixels[i + 2]},${a})`
);
}
let foundCrispBar = false;
for (let row = Math.floor(dH / 3); row < Math.floor((dH * 2) / 3); row += 1) {
let run = 0;
for (let col = 0; col < dW; col += 1) {
if (dPixels[(row * dW + col) * 4 + 3] >= 250) {
run += 1;
if (run >= Math.max(6, Math.floor(dW / 2))) {
foundCrispBar = true;
break;
}
} else {
run = 0;
}
}
if (foundCrispBar) break;
}
assert.ok(
foundCrispBar,
'Dark-mode math worker RGBA must have crisp >=250-alpha fraction bar'
);
// 4. Typst worker: register fonts fetched via `loader.loadFont` and compile document.
const typstWorker = /** @type {any} */ (loader.loadWorker('typst'));
const latinReg = await typstWorker.rpc({
@@ -347,28 +420,20 @@ try {
`blue PDF center pixel mismatch: R=${blueR}, B=${blueB}`
);
// 6. CRDT codec Wasm (`crdt-codec.dev-local.wasm`): strict import check, real Yjs v1 extract + merge + corrupt fail.
const crdtCodecUrl = loader.resolveCrdtCodecUrl();
// 6. Main playground Wasm bundle (`assets/pkg/playground.js`): real Yjs v1 extract + merge + corrupt fail.
const mainWasmJsUrl = loader.resolveMainWasmJsUrl();
assert.ok(
crdtCodecUrl && crdtCodecUrl.includes('crdt-codec.dev-local.wasm'),
`unexpected crdtCodecUrl: ${crdtCodecUrl}`
mainWasmJsUrl && mainWasmJsUrl.includes('/assets/pkg/playground.js'),
`unexpected mainWasmJsUrl: ${mainWasmJsUrl}`
);
const crdtWasmBytes = readFileSync(
join(ASSETS_DIR, 'crdt-codec.dev-local.wasm')
const playgroundWasmBytes = readFileSync(
join(ASSETS_DIR, 'pkg', 'playground_bg.wasm')
);
const crdtClient = createCrdtWasmClient(crdtCodecUrl, {
fetchImpl: async () => /** @type {Response} */ (
/** @type {unknown} */ ({
ok: true,
status: 200,
arrayBuffer: async () =>
crdtWasmBytes.buffer.slice(
crdtWasmBytes.byteOffset,
crdtWasmBytes.byteOffset + crdtWasmBytes.byteLength
),
})
),
});
const playgroundMod = await import(
pathToFileURL(join(ASSETS_DIR, 'pkg', 'playground.js')).toString()
);
playgroundMod.initSync({ module: playgroundWasmBytes });
const realYjsV1 = [
new Uint8Array([
1, 6, 105, 0, 39, 1, 4, 109, 101, 116, 97, 5, 112, 97, 103, 101, 115, 0,
@@ -384,22 +449,22 @@ try {
118, 0, 1, 105, 1, 4, 1,
]),
];
assert.deepEqual(await crdtClient.extractSubdocIds(realYjsV1), ['live-guid']);
const mergedV1 = await crdtClient.mergeUpdates(realYjsV1);
assert.deepEqual(playgroundMod.extract_subdoc_ids(realYjsV1), ['live-guid']);
const mergedV1 = playgroundMod.merge_updates_v1(realYjsV1);
assert.ok(mergedV1 instanceof Uint8Array && mergedV1.byteLength > 0);
assert.deepEqual(await crdtClient.extractSubdocIds([mergedV1]), [
'live-guid',
]);
const emptyMerged = await crdtClient.mergeUpdates([]);
assert.deepEqual(playgroundMod.extract_subdoc_ids([mergedV1]), ['live-guid']);
const emptyMerged = playgroundMod.merge_updates_v1([]);
assert.deepEqual(Array.from(emptyMerged), [0, 0]);
await assert.rejects(
assert.throws(
() =>
crdtClient.extractSubdocIds([new Uint8Array([0xff, 0xff, 0xff, 0x80])]),
playgroundMod.extract_subdoc_ids([
new Uint8Array([0xff, 0xff, 0xff, 0x80]),
]),
/./
);
console.log(
`E2E 4-worker + crdt-codec + static-font verification passed: fonts(${Object.keys(loadedFonts).join(',')}), crdt-codec(${crdtWasmBytes.byteLength}B, merged=${mergedV1.byteLength}B), mermaid(light=${mermaidLight.result.svg.length}B vs dark=${mermaidDark.result.svg.length}B), math(${mathRes.result.svg.length}B), typst(1p ${typstRes.result.svg.length}B), pdf(red R=${redR}/B=${redB}, blue R=${blueR}/B=${blueB}, ${redRes.result.rgba.byteLength}B RGBA)`
`E2E 4-worker + main-wasm-crdt + static-font verification passed: fonts(${Object.keys(loadedFonts).join(',')}), playground_bg.wasm(${playgroundWasmBytes.byteLength}B, merged=${mergedV1.byteLength}B), mermaid(light=${mermaidLight.result.svg.length}B vs dark=${mermaidDark.result.svg.length}B), math(${mathRes.result.svg.length}B), typst(1p ${typstRes.result.svg.length}B), pdf(red R=${redR}/B=${redB}, blue R=${blueR}/B=${blueB}, ${redRes.result.rgba.byteLength}B RGBA)`
);
} finally {
await Promise.all(activeWorkers.map(w => w.terminate()));
@@ -0,0 +1,633 @@
#!/usr/bin/env node
// Real-browser Headless Chromium E2E against the exact `affine-release web bundle`
// served by `wrangler@4.168.0 dev` (`workerd`) + local mock upstream auth server:
// 1) `/` : editable first frame + text readback + RaTeX RGBA light/dark + in-document
// 2-page Hayro PDF attachment card rendered live by `pdf-worker.<hash>.wasm`.
// 2) `/host/`: production default `bootWebHost()` binding (`window.__AFFINE_WEB_HOST__`
// `attachWorkspace(...).v1Reader`, ZERO manual Wasm import or `setCrdtCodecs`
// override!) reading 2-frame Yjs v1 `affine-local` IndexedDB + `'live-guid'`.
// 3) `/sign-in`: cross-origin hidden OAuth + password + 6-digit OTP -> `/api/auth/session`.
// Kills temporary Chromium by exact PID in `finally`.
import assert from 'node:assert/strict';
import { execFileSync, spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const [, , workerdBaseUrl, outDir] = process.argv;
if (!workerdBaseUrl || !outDir) {
console.error(
'Usage: node verify-workerd-bundle-e2e.mjs <workerdBaseUrl> <outDir>'
);
process.exit(2);
}
fs.mkdirSync(outDir, { recursive: true });
const sleep = ms => new Promise(r => setTimeout(r, ms));
function findChrome() {
const candidates = [
process.env.CHROME_BIN,
'/usr/bin/google-chrome-stable',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
'/usr/bin/chromium-browser',
].filter(Boolean);
for (const b of candidates) {
if (fs.existsSync(b)) return b;
}
const pw = path.join(os.homedir(), '.cache/ms-playwright');
if (fs.existsSync(pw)) {
const found = execFileSync('find', [pw, '-name', 'chrome', '-type', 'f'], {
encoding: 'utf8',
})
.split('\n')
.map(s => s.trim())
.find(Boolean);
if (found) return found;
}
throw new Error('No preinstalled Chromium found');
}
// Two real binary Yjs v1 update frames:
// - frame1 creates `meta.pages` (`Live Page`) + `spaces.p1` (`old-guid`) + `otherMap.foreign`
// - frame2 replaces `spaces.p1` with subdoc `'live-guid'` and deletes `'old-guid'`
const REAL_YJS_V1_FRAMES = {
frame1: [
1, 6, 105, 0, 39, 1, 4, 109, 101, 116, 97, 5, 112, 97, 103, 101, 115, 0, 7,
0, 105, 0, 1, 40, 0, 105, 1, 2, 105, 100, 1, 119, 2, 112, 49, 40, 0, 105, 1,
5, 116, 105, 116, 108, 101, 1, 119, 9, 76, 105, 118, 101, 32, 80, 97, 103,
101, 41, 1, 6, 115, 112, 97, 99, 101, 115, 2, 112, 49, 8, 111, 108, 100, 45,
103, 117, 105, 100, 118, 0, 41, 1, 8, 111, 116, 104, 101, 114, 77, 97, 112,
7, 102, 111, 114, 101, 105, 103, 110, 12, 102, 111, 114, 101, 105, 103, 110,
45, 103, 117, 105, 100, 118, 0, 0,
],
frame2: [
1, 1, 105, 6, 169, 105, 4, 9, 108, 105, 118, 101, 45, 103, 117, 105, 100,
118, 0, 1, 105, 1, 4, 1,
],
};
// Valid 2-page PDF (page 1 vivid crimson banner + white bar, page 2 cobalt blue)
// rendered inside `/` by `pdf-worker.<hash>.wasm` (Hayro).
function buildTwoPagePdfBytes() {
const s1 =
'0.95 0.96 0.99 rg 0 0 360 180 re f\n' +
'0.82 0.16 0.24 rg 20 110 320 46 re f\n' +
'0.18 0.24 0.34 rg 20 74 220 14 re f\n' +
'0.42 0.48 0.58 rg 20 46 280 10 re f\n' +
'0.42 0.48 0.58 rg 20 26 190 10 re f\n';
const s2 =
'0.94 0.97 1.00 rg 0 0 360 180 re f\n' +
'0.12 0.38 0.86 rg 20 110 320 46 re f\n' +
'0.18 0.24 0.34 rg 20 74 240 14 re f\n';
const rawObjs = [
'1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n',
'2 0 obj << /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >> endobj\n',
'3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 360 180] /Contents 4 0 R >> endobj\n',
`4 0 obj << /Length ${s1.length} >> stream\n${s1}endstream endobj\n`,
'5 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 360 180] /Contents 6 0 R >> endobj\n',
`6 0 obj << /Length ${s2.length} >> stream\n${s2}endstream endobj\n`,
];
let out = '%PDF-1.4\n';
const offsets = [0];
for (const obj of rawObjs) {
offsets.push(Buffer.byteLength(out, 'ascii'));
out += obj;
}
const xrefOffset = Buffer.byteLength(out, 'ascii');
out += `xref\n0 ${rawObjs.length + 1}\n0000000000 65535 f \n`;
for (let i = 1; i <= rawObjs.length; i++) {
out += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
}
out += `trailer << /Size ${rawObjs.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;
return Array.from(Buffer.from(out, 'ascii'));
}
const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cf-workerd-e2e-'));
const chromeBin = findChrome();
const chrome = spawn(
chromeBin,
[
'--headless=new',
'--no-sandbox',
'--disable-gpu-sandbox',
'--disable-dev-shm-usage',
'--no-first-run',
'--no-default-browser-check',
'--use-gl=angle',
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
'--enable-webgl',
'--ignore-gpu-blocklist',
'--remote-debugging-port=0',
`--user-data-dir=${profileDir}`,
'--window-size=1280,800',
'about:blank',
],
{
stdio: ['ignore', 'ignore', 'pipe'],
env: { ...process.env, DBUS_SESSION_BUS_ADDRESS: 'disabled:' },
}
);
let exitCode = 0;
try {
const debugPort = await new Promise((resolve, reject) => {
let stderr = '';
const timer = setTimeout(
() =>
reject(
new Error(`Timed out waiting for DevTools URL: ${stderr.slice(-400)}`)
),
45000
);
chrome.stderr.on('data', chunk => {
stderr += chunk.toString();
const m = stderr.match(
/DevTools listening on ws:\/\/127\.0\.0\.1:(\d+)\//
);
if (m) {
clearTimeout(timer);
resolve(Number(m[1]));
}
});
});
const target = await (
await fetch(`http://127.0.0.1:${debugPort}/json/new?about:blank`, {
method: 'PUT',
})
).json();
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((res, rej) => {
ws.onopen = res;
ws.onerror = rej;
});
let seq = 0;
const pending = new Map();
const uncaughtErrors = [];
ws.onmessage = ev => {
const msg = JSON.parse(ev.data);
if (msg.id && pending.has(msg.id)) {
const entry = pending.get(msg.id);
pending.delete(msg.id);
if (msg.error) entry.rej(new Error(JSON.stringify(msg.error)));
else entry.res(msg.result);
} else if (msg.method === 'Runtime.exceptionThrown') {
uncaughtErrors.push(
msg.params?.exceptionDetails?.exception?.description ||
msg.params?.exceptionDetails?.text ||
'Runtime.exceptionThrown'
);
}
};
const send = (method, params = {}) =>
new Promise((res, rej) => {
const id = ++seq;
pending.set(id, { res, rej });
ws.send(JSON.stringify({ id, method, params }));
});
const evalJs = async expression => {
const res = await send('Runtime.evaluate', {
expression,
awaitPromise: true,
returnByValue: true,
});
if (res.exceptionDetails) {
throw new Error(
res.exceptionDetails.exception?.description || res.exceptionDetails.text
);
}
return res.result.value;
};
const saveShot = async filename => {
const shot = await send('Page.captureScreenshot', { format: 'png' });
const buf = Buffer.from(shot.data, 'base64');
const outPath = path.join(outDir, filename);
fs.writeFileSync(outPath, buf);
console.log(`[shot] saved ${outPath} (${buf.byteLength} bytes)`);
return buf;
};
const click = async (x, y) => {
await send('Input.dispatchMouseEvent', {
type: 'mousePressed',
x,
y,
button: 'left',
buttons: 1,
clickCount: 1,
});
await send('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x,
y,
button: 'left',
buttons: 0,
clickCount: 1,
});
await sleep(140);
};
const pressKey = async (key, code, vk) => {
for (const type of ['rawKeyDown', 'keyUp']) {
await send('Input.dispatchKeyEvent', {
type,
key,
code,
windowsVirtualKeyCode: vk,
});
}
await sleep(100);
};
const typeText = async text => {
for (const ch of text) {
await send('Input.insertText', { text: ch });
await sleep(20);
}
await sleep(120);
};
await send('Page.enable');
await send('Runtime.enable');
await send('Network.enable');
await send('Emulation.setDeviceMetricsOverride', {
width: 1280,
height: 800,
deviceScaleFactor: 1,
mobile: false,
});
// =========================================================================
// 1. `/` — Editable First Frame + RaTeX RGBA + Real In-Document 2-Page PDF
// =========================================================================
console.log(
'=== [1/3] Verifying `/` on workerd bundle (text input, RaTeX RGBA, in-document 2-page PDF) ==='
);
await send('Page.navigate', { url: `${workerdBaseUrl}/` });
for (let i = 0; i < 160; i++) {
const state = await evalJs(
'({ ready: Boolean(window.__playgroundReady), error: window.__playgroundError || null })'
);
if (state.error) throw new Error(`Playground boot error: ${state.error}`);
if (state.ready) break;
await sleep(250);
}
assert.equal(
await evalJs('Boolean(window.__playgroundReady)'),
true,
'`/` must reach window.__playgroundReady === true'
);
await sleep(1800);
await click(314, 215);
await pressKey('End', 'End', 35);
await pressKey('Enter', 'Enter', 13);
await typeText('Workerd E2E Verified: Euler $$e^{i\\pi}+1=0$$ ');
await typeText('and fraction $$\\frac{a}{b}$$ ');
await typeText('inline.');
const readback1 = await evalJs(
"(() => { const t = document.querySelector('textarea'); return t ? t.value : ''; })()"
);
console.log('[1/3] paragraph textarea readback:', JSON.stringify(readback1));
assert.ok(readback1.includes('Workerd E2E Verified:'));
await pressKey('Enter', 'Enter', 13);
await typeText('$$$$ ');
await sleep(300);
await typeText('\\int_0^\\infty e^{-x^2} dx = \\frac{\\sqrt{\\pi}}{2}');
await sleep(400);
await pressKey('Enter', 'Enter', 13);
await sleep(3500);
const lightMathBuf = await saveShot('workerd-01-editor-math-light.png');
await click(1252, 26);
await sleep(2500);
await saveShot('workerd-02-editor-math-dark.png');
// Return to Light mode, insert a real 2-page embedded PDF attachment block into `/`,
// wait for `pdf-worker.<hash>.wasm` (Hayro) to rasterize page 1 onto the WebGL/WebGPU canvas,
// and capture `workerd-04-editor-pdf.png`!
await click(1252, 26);
await sleep(1200);
const twoPagePdf = buildTwoPagePdfBytes();
const workerAssetsCheck = await evalJs(`(async () => {
const assets = window.__AFFINE_WORKER_ASSETS__ || {};
const mathRes = await fetch(assets.mathWasm);
const pdfRes = await fetch(assets.pdfWasm);
const pdfBytes = Uint8Array.from(${JSON.stringify(twoPagePdf)});
window.__playgroundPreview.deliverPdfAttachment(pdfBytes, 'architecture-spec-2p.pdf');
return {
mathWasm: assets.mathWasm,
mathStatus: mathRes.status,
mathBytes: (await mathRes.arrayBuffer()).byteLength,
pdfWasm: assets.pdfWasm,
pdfStatus: pdfRes.status,
pdfBytes: (await pdfRes.arrayBuffer()).byteLength,
};
})()`);
await sleep(3500);
const pdfShotBuf = await saveShot('workerd-04-editor-pdf.png');
const pdfPixelCheck = await evalJs(`(async () => {
const img = new Image();
img.src = 'data:image/png;base64,${pdfShotBuf.toString('base64')}';
await img.decode();
const off = document.createElement('canvas');
off.width = img.naturalWidth;
off.height = img.naturalHeight;
const ctx = off.getContext('2d');
ctx.drawImage(img, 0, 0);
const { data, width, height } = ctx.getImageData(0, 0, off.width, off.height);
let redBannerPixels = 0;
let navyBarPixels = 0;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// Page 1 content stream draws a crimson banner (0.80, 0.16, 0.22) and navy bar (0.15, 0.22, 0.32).
if (r >= 170 && g <= 65 && b <= 80) redBannerPixels += 1;
if (r >= 25 && r <= 55 && g >= 40 && g <= 72 && b >= 65 && b <= 100) navyBarPixels += 1;
}
return { width, height, redBannerPixels, navyBarPixels };
})()`);
console.log(
'[1/3] worker assets & PDF pixel check:',
JSON.stringify({ ...workerAssetsCheck, ...pdfPixelCheck })
);
assert.match(
workerAssetsCheck.mathWasm,
/^\/assets\/math-worker\.[0-9a-f]{12}\.wasm$/
);
assert.equal(workerAssetsCheck.mathStatus, 200);
assert.match(
workerAssetsCheck.pdfWasm,
/^\/assets\/pdf-worker\.[0-9a-f]{12}\.wasm$/
);
assert.equal(workerAssetsCheck.pdfStatus, 200);
assert.notEqual(
Buffer.compare(lightMathBuf, pdfShotBuf),
0,
'Embedded 2-page PDF rendered by pdf-worker.wasm must visibly update the editor canvas'
);
assert.ok(
pdfPixelCheck.redBannerPixels >= 2000 && pdfPixelCheck.navyBarPixels >= 500,
`PDF page 1 crimson banner and navy bar must be rasterized onto canvas (got ${JSON.stringify(pdfPixelCheck)})`
);
// =========================================================================
// 2. `/host/` — Production Default `bootWebHost()` Binding (NO manual Wasm override!)
// =========================================================================
console.log(
'=== [2/3] Verifying `/host/` default bootWebHost() v1Reader without manual setCrdtCodecs ==='
);
const fixtureFramesJson =
process.env.IDB_TWO_FRAMES_JSON || JSON.stringify(REAL_YJS_V1_FRAMES);
await send('Page.navigate', { url: `${workerdBaseUrl}/host/` });
for (let i = 0; i < 60; i++) {
const booted = await evalJs(
'Boolean(window.__AFFINE_WEB_HOST__ && typeof window.__AFFINE_WEB_HOST__.attachWorkspace === "function")'
);
if (booted) break;
await sleep(150);
}
await sleep(600);
const hostResult = await evalJs(`(async () => {
const manifestEl = document.getElementById('affine-build-manifest');
if (!manifestEl) throw new Error('Missing #affine-build-manifest on /host/');
const manifest = JSON.parse(manifestEl.textContent);
if ('crdtCodecWasm' in manifest) {
throw new Error('crdtCodecWasm must be absent from rewritten manifest');
}
if (!manifest.mainWasmJs || !/^\\/pkg\\/playground\\.[0-9a-f]{12}\\.js$/.test(manifest.mainWasmJs)) {
throw new Error('Unexpected mainWasmJs: ' + manifest.mainWasmJs);
}
const canvasCountBefore = document.querySelectorAll('canvas').length;
const host = window.__AFFINE_WEB_HOST__;
if (!host || typeof host.attachWorkspace !== 'function') {
throw new Error('Expected booted window.__AFFINE_WEB_HOST__ handle on /host/');
}
// Seed real V1 affine-local IndexedDB with 2 Yjs v1 frames + live/stale/foreign subdocs,
// then read exclusively through host.attachWorkspace(...).v1Reader (testing the shipping
// bootWebHost() default mainWasmJs binding with zero manual Wasm import or setCrdtCodecs).
const framesData = ${fixtureFramesJson};
const frame1 = Uint8Array.from(framesData.frame1);
const frame2 = Uint8Array.from(framesData.frame2);
const enc = new TextEncoder();
const v1Db = await new Promise((resolve, reject) => {
const req = indexedDB.open('affine-local', 1);
req.onupgradeneeded = () => {
if (!req.result.objectStoreNames.contains('workspace')) {
req.result.createObjectStore('workspace', { keyPath: 'id' });
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
const tx = v1Db.transaction('workspace', 'readwrite');
const store = tx.objectStore('workspace');
store.put({
id: 'ws-v1-workerd',
updates: [
{ timestamp: 100, update: frame1 },
{ timestamp: 101, update: frame2 },
],
});
store.put({
id: 'live-guid',
updates: [{ timestamp: 200, update: enc.encode('live-subdoc-body') }],
});
store.put({
id: 'old-guid',
updates: [{ timestamp: 200, update: enc.encode('deleted-subdoc-body') }],
});
store.put({
id: 'foreign-guid',
updates: [{ timestamp: 200, update: enc.encode('foreign-subdoc-body') }],
});
await new Promise((resolve, reject) => {
tx.oncomplete = resolve;
tx.onabort = () => reject(tx.error || new Error('v1 seed tx aborted'));
});
v1Db.close();
const { workspaceStorage, v1Reader } = host.attachWorkspace({
flavour: 'local',
type: 'workspace',
id: 'ws-v1-workerd',
});
const listedDocIds = await v1Reader.listV1DocIds();
const mergedRoot = await v1Reader.getV1Doc('ws-v1-workerd');
const canvasCountAfter = document.querySelectorAll('canvas').length;
workspaceStorage.close();
return {
manifestKeys: Object.keys(manifest).sort(),
mainWasmJs: manifest.mainWasmJs,
canvasCountBefore,
canvasCountAfter,
listedDocIds,
mergedRootBytes: mergedRoot?.bin?.byteLength ?? 0,
};
})()`);
console.log(
'[2/3] /host/ default-binding result:',
JSON.stringify(hostResult)
);
assert.equal(hostResult.canvasCountBefore, 1);
assert.equal(
hostResult.canvasCountAfter,
1,
'Default bootWebHost() mainWasmJs binding on /host/ must not mount a second canvas'
);
assert.equal(hostResult.mergedRootBytes, 134);
assert.deepEqual(hostResult.listedDocIds, ['ws-v1-workerd', 'live-guid']);
// =========================================================================
// 3. `/sign-in` — Cross-Origin Proxy: Hidden OAuth + Password + 6-Digit OTP
// =========================================================================
console.log(
'=== [3/3] Verifying `/sign-in` password & 6-digit OTP sign-in via workerd proxy ==='
);
await send('Network.clearBrowserCookies');
await send('Page.navigate', { url: `${workerdBaseUrl}/sign-in` });
for (let i = 0; i < 60; i++) {
const ready = await evalJs("Boolean(document.querySelector('#email'))");
if (ready) break;
await sleep(150);
}
await sleep(600);
const oauthCheck = await evalJs(`(() => {
const container = document.getElementById('oauth-providers');
const visibleButtons = Array.from(document.querySelectorAll('[data-provider], #oauth-providers button'))
.filter(el => !el.hidden && getComputedStyle(el).display !== 'none');
return {
containerHidden: container ? (container.hidden || getComputedStyle(container).display === 'none') : true,
visibleCount: visibleButtons.length,
};
})()`);
console.log('[3/3] cross-origin OAuth check:', JSON.stringify(oauthCheck));
assert.equal(oauthCheck.visibleCount, 0);
await saveShot('workerd-03-signin-email-step.png');
await evalJs(`(() => {
const el = document.querySelector('#email');
el.focus();
el.value = 'pw@affine.fail';
el.dispatchEvent(new Event('input', { bubbles: true }));
document.querySelector('#sign-in-form').requestSubmit();
})()`);
for (let i = 0; i < 40; i++) {
const step = await evalJs(
"document.querySelector('#auth-card')?.dataset?.step || ''"
);
if (step === 'password') break;
await sleep(100);
}
assert.equal(
await evalJs("document.querySelector('#auth-card')?.dataset?.step || ''"),
'password'
);
await evalJs(`(() => {
const pw = document.querySelector('#password');
pw.focus();
pw.value = 'correct-horse-battery';
pw.dispatchEvent(new Event('input', { bubbles: true }));
document.querySelector('#sign-in-form').requestSubmit();
})()`);
for (let i = 0; i < 60; i++) {
if ((await evalJs('window.location.pathname')) === '/') break;
await sleep(150);
}
assert.equal(await evalJs('window.location.pathname'), '/');
const pwSession = await evalJs(
"fetch('/api/auth/session', { credentials: 'same-origin' }).then(r => r.json())"
);
console.log(
'[3/3] password /api/auth/session readback:',
JSON.stringify(pwSession)
);
assert.equal(pwSession?.user?.email, 'pw@affine.fail');
await send('Network.clearBrowserCookies');
await send('Page.navigate', { url: `${workerdBaseUrl}/sign-in` });
for (let i = 0; i < 40; i++) {
if (await evalJs("Boolean(document.querySelector('#email'))")) break;
await sleep(150);
}
await sleep(400);
await evalJs(`(() => {
const el = document.querySelector('#email');
el.focus();
el.value = 'otp@affine.fail';
el.dispatchEvent(new Event('input', { bubbles: true }));
document.querySelector('#sign-in-form').requestSubmit();
})()`);
for (let i = 0; i < 40; i++) {
if (
(await evalJs(
"document.querySelector('#auth-card')?.dataset?.step || ''"
)) === 'otp'
) {
break;
}
await sleep(100);
}
assert.equal(
await evalJs("document.querySelector('#auth-card')?.dataset?.step || ''"),
'otp'
);
await sleep(300);
await evalJs(`(() => {
const otp = document.querySelector('#otp');
otp.focus();
otp.value = '654321';
otp.dispatchEvent(new Event('input', { bubbles: true }));
document.querySelector('#sign-in-form').requestSubmit();
})()`);
for (let i = 0; i < 60; i++) {
if ((await evalJs('window.location.pathname')) === '/') break;
await sleep(150);
}
assert.equal(await evalJs('window.location.pathname'), '/');
const otpSession = await evalJs(
"fetch('/api/auth/session', { credentials: 'same-origin' }).then(r => r.json())"
);
console.log(
'[3/3] OTP /api/auth/session readback:',
JSON.stringify(otpSession)
);
assert.equal(otpSession?.user?.email, 'otp@affine.fail');
assert.deepEqual(
uncaughtErrors,
[],
`Unexpected uncaught runtime exceptions: ${JSON.stringify(uncaughtErrors)}`
);
console.log('ALL WORKERD REAL-BROWSER E2E FLOWS PASSED');
ws.close();
} catch (err) {
console.error('WORKERD E2E FAILED:', err);
exitCode = 1;
} finally {
if (chrome.pid) {
try {
process.kill(chrome.pid, 'SIGKILL');
} catch {}
}
try {
fs.rmSync(profileDir, { recursive: true, force: true });
} catch {}
}
process.exit(exitCode);
@@ -1,177 +0,0 @@
// @ts-check
import {
buildStubImports,
invokeScalarRpc,
resolveWasmExport,
} from './wasm-scalar-rpc.js';
const OPCODE_MERGE_UPDATES_V1 = 1;
const OPCODE_EXTRACT_SUBDOC_IDS = 2;
/**
* Normalizes an update payload into a `Uint8Array`.
*
* @param {unknown} value
* @returns {Uint8Array}
*/
function toUint8Array(value) {
if (value instanceof Uint8Array) {
return value;
}
if (value instanceof ArrayBuffer) {
return new Uint8Array(value);
}
if (ArrayBuffer.isView(value)) {
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
}
throw new TypeError('CRDT update frames must be Uint8Array or ArrayBuffer');
}
/**
* Encodes `[frame_count: u32_le, (len_i: u32_le, bytes_i)...]`.
*
* @param {Uint8Array[]} updates
* @returns {Uint8Array}
*/
function encodeFramesPayload(updates) {
if (!Array.isArray(updates)) {
throw new TypeError('CRDT updates must be an array');
}
const frames = updates.map(toUint8Array);
let totalBytes = 4;
for (const frame of frames) {
totalBytes += 4 + frame.byteLength;
}
const buf = new Uint8Array(totalBytes);
const view = new DataView(buf.buffer);
view.setUint32(0, frames.length >>> 0, true);
let offset = 4;
for (const frame of frames) {
view.setUint32(offset, frame.byteLength >>> 0, true);
offset += 4;
buf.set(frame, offset);
offset += frame.byteLength;
}
return buf;
}
/**
* Creates a zero-dependency WebAssembly client backed by `affine-store`'s
* `wasm-codec` binary (`crdt-codec.<hash>.wasm`).
*
* @param {string} wasmUrl
* @param {{ fetchImpl?: typeof fetch }} [options]
*/
export function createCrdtWasmClient(wasmUrl, { fetchImpl } = {}) {
const decoder = new TextDecoder();
/** @type {Promise<{ resetInput: Function, pushInputU32: Function, invoke: Function, outputU32: Function }> | null} */
let exportsPromise = null;
async function loadExports() {
if (typeof wasmUrl !== 'string' || !wasmUrl.trim()) {
throw new Error('Missing CRDT codec wasm URL');
}
const fetchFn = fetchImpl || globalThis.fetch;
if (typeof fetchFn !== 'function') {
throw new Error('Missing fetch implementation for CRDT codec wasm');
}
const response = await fetchFn(wasmUrl);
if (!response || !response.ok) {
throw new Error(
`Failed to fetch CRDT codec wasm (${response?.status ?? 'unknown'}): ${wasmUrl}`
);
}
const bytes = new Uint8Array(await response.arrayBuffer());
const mod = await WebAssembly.compile(bytes);
const instance = await WebAssembly.instantiate(mod, buildStubImports(mod));
const rawExports = /** @type {Record<string, unknown>} */ (
/** @type {unknown} */ (instance.exports)
);
return {
resetInput: resolveWasmExport(
rawExports,
'affine_crdt_reset_input',
'CRDT codec'
),
pushInputU32: resolveWasmExport(
rawExports,
'affine_crdt_push_input_u32',
'CRDT codec'
),
invoke: resolveWasmExport(rawExports, 'affine_crdt_invoke', 'CRDT codec'),
outputU32: resolveWasmExport(
rawExports,
'affine_crdt_output_u32',
'CRDT codec'
),
};
}
/**
* Loads and instantiates the CRDT codec Wasm binary on first call.
* Failures clear the cached promise so retries are not stuck on a stale error.
*
* @returns {Promise<{ resetInput: Function, pushInputU32: Function, invoke: Function, outputU32: Function }>}
*/
function ready() {
if (!exportsPromise) {
exportsPromise = loadExports().catch(err => {
exportsPromise = null;
throw err;
});
}
return exportsPromise;
}
/**
* Merges one or more Yjs v1 binary updates into a single v1 binary update.
*
* @param {Uint8Array[]} updates
* @returns {Promise<Uint8Array>}
*/
async function mergeUpdates(updates) {
const abi = await ready();
const payload = encodeFramesPayload(updates);
const frame = invokeScalarRpc(abi, OPCODE_MERGE_UPDATES_V1, payload);
if (frame.length < 1 || frame[0] !== 1) {
const msg =
frame.length > 1
? decoder.decode(frame.subarray(1))
: 'CRDT mergeUpdates failed';
throw new Error(msg);
}
return frame.slice(1);
}
/**
* Extracts sorted top-level page subdoc GUIDs from legacy V1 root updates.
*
* @param {Uint8Array[]} rootUpdates
* @returns {Promise<string[]>}
*/
async function extractSubdocIds(rootUpdates) {
const abi = await ready();
const payload = encodeFramesPayload(rootUpdates);
const frame = invokeScalarRpc(abi, OPCODE_EXTRACT_SUBDOC_IDS, payload);
if (frame.length < 1 || frame[0] !== 1) {
const msg =
frame.length > 1
? decoder.decode(frame.subarray(1))
: 'CRDT extractSubdocIds failed';
throw new Error(msg);
}
const parsed = JSON.parse(decoder.decode(frame.subarray(1)));
if (!Array.isArray(parsed)) {
throw new Error('CRDT extractSubdocIds returned non-array payload');
}
return parsed.map(String);
}
return Object.freeze({
wasmUrl,
ready,
mergeUpdates,
extractSubdocIds,
});
}
+33 -17
View File
@@ -1,7 +1,6 @@
// @ts-check
import { createA11yTree } from './a11y.js';
import { createCrdtWasmClient } from './crdt-wasm-client.js';
import {
createIdbV1ReadonlyReader,
createIdbWorkspaceStorage,
@@ -1066,30 +1065,48 @@ export async function bootWebHost(env = {}) {
assetBaseUrl: env.assetBaseUrl,
buildId: env.buildId,
});
const crdtCodecUrl = workerLoader.resolveCrdtCodecUrl();
const crdtCodecClient = crdtCodecUrl
? createCrdtWasmClient(crdtCodecUrl, {
fetchImpl:
env.fetchImpl ||
(typeof win.fetch === 'function' ? win.fetch.bind(win) : undefined),
})
: null;
if (crdtCodecClient) {
win.__AFFINE_WEB_HOST__ = true;
const mainWasmJsUrl = workerLoader.resolveMainWasmJsUrl();
/** @type {Promise<{ merge_updates_v1: Function, extract_subdoc_ids: Function }> | null} */
let mainWasmModPromise = null;
function loadMainWasmExports() {
if (!mainWasmJsUrl) {
return Promise.reject(
new Error('Main Wasm JS module URL is not configured')
);
}
if (!mainWasmModPromise) {
mainWasmModPromise = (async () => {
const mod = await import(mainWasmJsUrl);
if (typeof mod.default === 'function') {
await mod.default();
}
return mod;
})().catch(err => {
mainWasmModPromise = null;
throw err;
});
}
return mainWasmModPromise;
}
if (mainWasmJsUrl) {
if (!activeMergeUpdates) {
activeMergeUpdates = updates => crdtCodecClient.mergeUpdates(updates);
activeMergeUpdates = async updates => {
const mod = await loadMainWasmExports();
return mod.merge_updates_v1(updates);
};
}
if (!activeExtractSubdocIds) {
activeExtractSubdocIds = rootUpdates =>
crdtCodecClient.extractSubdocIds(rootUpdates);
activeExtractSubdocIds = async rootUpdates => {
const mod = await loadMainWasmExports();
return mod.extract_subdoc_ids(rootUpdates);
};
}
workspaceStorage?.setCrdtCodecs?.({ mergeUpdates: activeMergeUpdates });
v1Reader?.setCrdtCodecs?.({
mergeUpdates: activeMergeUpdates,
extractSubdocIds: activeExtractSubdocIds,
});
if (env.preloadCrdtCodec) {
await crdtCodecClient.ready();
}
}
const pdfClient = createPdfPreviewClient({
workerLoader,
@@ -1362,7 +1379,6 @@ export async function bootWebHost(env = {}) {
});
},
workerLoader,
crdtCodecClient,
pdfClient,
gpuRecovery,
safeAreaObserver,
@@ -1283,7 +1283,7 @@ export function createIdbWorkspaceStorage(options) {
*
* Never creates an empty V1 database when none exists, and never mutates V1
* data. Listing subdocs of a non-empty V1 root requires an `extractSubdocIds`
* callback (wired to `crdt-codec.wasm` in `host.js`) or explicit `opts.subdocIds`.
* callback (wired to the main `playground` Wasm bundle in `host.js`) or explicit `opts.subdocIds`.
*
* @param {{
* workspaceId: string,
+63 -10
View File
@@ -537,15 +537,50 @@ export function readClientNonce(
}
/**
* Queries same-origin `/graphql` using the frozen 0.27.5 `ServerConfigType`
* fields (`name`, `features`, `oauthProviders`). Degrades silently to an empty
* provider list when offline or unavailable.
* Returns whether the backend's configured `baseUrl` is a valid absolute URL
* whose origin matches `currentOrigin`.
*
* @param {{ fetchImpl?: typeof fetch, clientVersion?: string }} [options]
* @returns {Promise<{ serverName: string, oauth: boolean, providers: string[] }>}
* @param {string | null | undefined} baseUrl
* @param {string | null | undefined} currentOrigin
* @returns {boolean}
*/
function isSameOriginBaseUrl(baseUrl, currentOrigin) {
if (
typeof baseUrl !== 'string' ||
!baseUrl.trim() ||
typeof currentOrigin !== 'string' ||
!currentOrigin.trim()
) {
return false;
}
try {
const parsedBase = new URL(baseUrl.trim());
const parsedCurrent = new URL(currentOrigin.trim());
return (
(parsedBase.protocol === 'https:' || parsedBase.protocol === 'http:') &&
parsedBase.origin === parsedCurrent.origin
);
} catch {
return false;
}
}
/**
* Queries same-origin `/graphql` using the frozen 0.27.5 `ServerConfigType`
* fields (`name`, `baseUrl`, `features`, `oauthProviders`, `type`).
* Enables third-party OAuth providers ONLY when `baseUrl` is a valid absolute
* URL whose origin matches `currentOrigin`. Degrades silently to an empty
* provider list when offline, unavailable, or behind a cross-origin proxy.
*
* @param {{ fetchImpl?: typeof fetch, clientVersion?: string, currentOrigin?: string | null }} [options]
* @returns {Promise<{ serverName: string, oauth: boolean, providers: string[], crossOriginProxy?: boolean, deploymentType?: string }>}
*/
export async function fetchOAuthProviders(options = {}) {
const fetchImpl = options.fetchImpl || globalThis.fetch;
const currentOrigin =
options.currentOrigin !== undefined
? options.currentOrigin
: globalThis.window?.location?.origin || null;
try {
const response = await fetchImpl('/graphql', {
method: 'POST',
@@ -555,7 +590,8 @@ export async function fetchOAuthProviders(options = {}) {
clientVersion: options.clientVersion,
}),
body: JSON.stringify({
query: 'query { serverConfig { name features oauthProviders type } }',
query:
'query { serverConfig { name baseUrl features oauthProviders type } }',
}),
});
if (!response.ok) {
@@ -572,8 +608,11 @@ export async function fetchOAuthProviders(options = {}) {
const features = Array.isArray(cfg?.features)
? cfg.features.map(f => String(f))
: null;
const sameOrigin = isSameOriginBaseUrl(cfg?.baseUrl, currentOrigin);
const oauthEnabled =
providers.length > 0 && (features === null || features.includes('OAuth'));
sameOrigin &&
providers.length > 0 &&
(features === null || features.includes('OAuth'));
const deploymentType =
typeof cfg?.type === 'string' && cfg.type.trim() ? cfg.type.trim() : null;
return {
@@ -583,6 +622,7 @@ export async function fetchOAuthProviders(options = {}) {
: 'AFFiNE',
oauth: oauthEnabled,
providers: oauthEnabled ? providers : [],
...(!sameOrigin ? { crossOriginProxy: true } : {}),
...(deploymentType ? { deploymentType } : {}),
};
} catch {
@@ -1686,8 +1726,14 @@ export async function bootSignInPage(env = {}) {
syncSubmitButtonsDisabled();
}
let crossOriginProxy = false;
if (oauthContainer || legalNoticeEl) {
const serverOAuth = await fetchOAuthProviders({ fetchImpl, clientVersion });
const serverOAuth = await fetchOAuthProviders({
fetchImpl,
clientVersion,
currentOrigin: currentUrl.origin,
});
crossOriginProxy = Boolean(serverOAuth.crossOriginProxy);
syncLegalNoticeVisibility(serverOAuth.deploymentType);
if (oauthContainer) {
renderOAuthProviders({
@@ -1812,7 +1858,12 @@ export async function bootSignInPage(env = {}) {
setStatus(`Failed to send code (${sendRes.status}).`, 'error');
} else {
runResendCountdown(emailKey);
setStatus('');
setStatus(
crossOriginProxy
? 'Enter the 6-digit verification code sent to your email.'
: '',
'info'
);
}
return sendRes;
} catch {
@@ -1971,7 +2022,9 @@ export async function bootSignInPage(env = {}) {
setStatus(
result.ok
? result.method === 'magic-link-send'
? 'Check your email for the sign-in link.'
? crossOriginProxy
? 'Enter the 6-digit verification code sent to your email.'
: 'Check your email for the sign-in link.'
: 'Signed in.'
: errorText,
result.ok ? 'info' : 'error'
@@ -17,7 +17,7 @@
* @property {string} [buildId]
* @property {string | null} [assetBaseUrl]
* @property {string | null} [appEntryJs]
* @property {string | null} [crdtCodecWasm]
* @property {string | null} [mainWasmJs]
* @property {Record<PreviewWorkerKind, WorkerAssetSpec>} workers
* @property {Record<string, string>} fonts
*/
@@ -63,9 +63,9 @@ export function freezeBuildManifest(raw) {
typeof raw.assetBaseUrl === 'string' && raw.assetBaseUrl.trim()
? raw.assetBaseUrl.trim()
: null;
const crdtCodecWasm =
typeof raw.crdtCodecWasm === 'string' && raw.crdtCodecWasm.trim()
? raw.crdtCodecWasm.trim()
const mainWasmJs =
typeof raw.mainWasmJs === 'string' && raw.mainWasmJs.trim()
? raw.mainWasmJs.trim()
: null;
return Object.freeze({
shellVersion: String(raw.shellVersion || 'mobile-v1'),
@@ -73,7 +73,7 @@ export function freezeBuildManifest(raw) {
buildId: effectiveBuildId,
assetBaseUrl,
appEntryJs: typeof raw.appEntryJs === 'string' ? raw.appEntryJs : null,
crdtCodecWasm,
mainWasmJs,
workers: /** @type {Record<PreviewWorkerKind, WorkerAssetSpec>} */ (
workers
),
@@ -230,16 +230,16 @@ export function createWorkerLoader(rawManifest, options = {}) {
}
/**
* Resolves the pinned CRDT codec `.wasm` URL when declared in the manifest.
* Resolves the pinned main Wasm JS glue URL (`playground.js`) when declared in the manifest.
*
* @returns {string | null}
*/
function resolveCrdtCodecUrl() {
if (!manifest.crdtCodecWasm) {
function resolveMainWasmJsUrl() {
if (!manifest.mainWasmJs) {
return null;
}
return pinUrl(
manifest.crdtCodecWasm,
manifest.mainWasmJs,
baseUrl,
lockedBuildId,
lockedAssetBaseUrl
@@ -332,7 +332,7 @@ export function createWorkerLoader(rawManifest, options = {}) {
assetBaseUrl: lockedAssetBaseUrl,
resolveWorkerAssets,
resolveFontUrl,
resolveCrdtCodecUrl,
resolveMainWasmJsUrl,
loadWorker,
hasLoadedWorker,
terminateWorker,
@@ -13,6 +13,7 @@ const OPCODE_TYPST_SVG = 4;
const OPCODE_PDF_PAGE = 5;
const OPCODE_PDF_PAGE_SCALED = 6;
const OPCODE_PDF_PAGE_COUNT = 7;
const OPCODE_MATH_RGBA = 8;
const KIND_OPCODES = {
mermaid: OPCODE_MERMAID_SVG,
@@ -105,6 +106,36 @@ function prependPageIndexAndScale(pageIndex, scale, body) {
return buf;
}
/**
* Encodes a `math` RGBA rasterization request (`OPCODE_MATH_RGBA = 8`).
*
* @param {TextEncoder} encoder
* @param {{ display?: boolean, fontSizePt?: number, paddingPt?: number, scaleFactor?: number, colorCss?: string, latex?: string, source?: string }} msg
* @returns {Uint8Array}
*/
function encodeMathRgbaPayload(encoder, msg) {
const colorBytes = encoder.encode(String(msg.colorCss || '#000000'));
const latexBytes = encoder.encode(String(msg.latex ?? msg.source ?? ''));
const buf = new Uint8Array(15 + colorBytes.length + latexBytes.length);
const view = new DataView(buf.buffer);
buf[0] = msg.display ? 1 : 0;
view.setFloat32(1, Number(msg.fontSizePt) || 16.0, true);
view.setFloat32(
5,
Number.isFinite(Number(msg.paddingPt))
? Number(msg.paddingPt)
: msg.display
? 4.0
: 1.5,
true
);
view.setFloat32(9, Number(msg.scaleFactor) || 2.0, true);
view.setUint16(13, colorBytes.length, true);
buf.set(colorBytes, 15);
buf.set(latexBytes, 15 + colorBytes.length);
return buf;
}
/**
* Starts a dedicated preview Web Worker for one capability (`mermaid`, `math`,
* `typst`, or `pdf`), reading its pinned `.wasm` URL from
@@ -202,6 +233,9 @@ export function startPreviewWorker(kind) {
} else {
payloadBytes = prependPageIndex(Number(msg.pageIndex ?? 0), pdfBytes);
}
} else if (kind === 'math' && msg.op === 'rgba') {
opcode = OPCODE_MATH_RGBA;
payloadBytes = encodeMathRgbaPayload(encoder, msg);
} else {
payloadBytes = encoder.encode(String(msg.latex ?? msg.source ?? ''));
}
@@ -211,6 +245,46 @@ export function startPreviewWorker(kind) {
throw new Error(decoder.decode(frame.subarray(1)) || 'worker error');
}
if (kind === 'math' && opcode === OPCODE_MATH_RGBA) {
if (frame.length < 21) {
throw new Error(`Truncated math RGBA response (${frame.length})`);
}
const view = new DataView(
frame.buffer,
frame.byteOffset,
frame.byteLength
);
const widthPt = view.getFloat32(1, true);
const ascentPt = view.getFloat32(5, true);
const descentPt = view.getFloat32(9, true);
const widthPx = view.getUint32(13, true);
const heightPx = view.getUint32(17, true);
const rgba = frame.slice(21);
const expectedBytes = widthPx * heightPx * 4;
if (rgba.byteLength !== expectedBytes) {
throw new Error(
`Math RGBA length mismatch: got ${rgba.byteLength}, expected ${expectedBytes}`
);
}
globalThis.postMessage(
{
id,
ok: true,
result: {
kind,
widthPt,
ascentPt,
descentPt,
widthPx,
heightPx,
rgba,
},
},
[rgba.buffer]
);
return;
}
if (kind === 'typst') {
const pageCount = new DataView(
frame.buffer,
@@ -1,125 +0,0 @@
// @ts-check
import assert from 'node:assert/strict';
import test from 'node:test';
import { createCrdtWasmClient } from '../src/crdt-wasm-client.js';
import { buildStubImports } from '../src/wasm-scalar-rpc.js';
import {
createWorkerLoader,
freezeBuildManifest,
} from '../src/worker-loader.js';
const REAL_YJS_V1_UPDATES = [
new Uint8Array([
1, 6, 105, 0, 39, 1, 4, 109, 101, 116, 97, 5, 112, 97, 103, 101, 115, 0, 7,
0, 105, 0, 1, 40, 0, 105, 1, 2, 105, 100, 1, 119, 2, 112, 49, 40, 0, 105, 1,
5, 116, 105, 116, 108, 101, 1, 119, 9, 76, 105, 118, 101, 32, 80, 97, 103,
101, 41, 1, 6, 115, 112, 97, 99, 101, 115, 2, 112, 49, 8, 111, 108, 100, 45,
103, 117, 105, 100, 118, 0, 41, 1, 8, 111, 116, 104, 101, 114, 77, 97, 112,
7, 102, 111, 114, 101, 105, 103, 110, 12, 102, 111, 114, 101, 105, 103, 110,
45, 103, 117, 105, 100, 118, 0, 0,
]),
new Uint8Array([
1, 1, 105, 6, 169, 105, 4, 9, 108, 105, 118, 101, 45, 103, 117, 105, 100,
118, 0, 1, 105, 1, 4, 1,
]),
];
void test('worker-loader freezes and pins optional crdtCodecWasm URL', () => {
const manifest = freezeBuildManifest({
shellVersion: 'mobile-v1',
buildHash: 'abc123',
crdtCodecWasm: '/assets/crdt-codec.wasm',
workers: {
mermaid: { script: '/src/m.js', wasm: '/assets/m.wasm' },
math: { script: '/src/ma.js', wasm: '/assets/ma.wasm' },
typst: { script: '/src/t.js', wasm: '/assets/t.wasm' },
pdf: { script: '/src/p.js', wasm: '/assets/p.wasm' },
},
fonts: {},
});
assert.equal(manifest.crdtCodecWasm, '/assets/crdt-codec.wasm');
const loader = createWorkerLoader(manifest, {
baseUrl: 'https://app.affine.pro/workspace/ws-1/page-2',
assetBaseUrl: 'https://cdn.affine.pro/builds/abc123/',
});
assert.equal(
loader.resolveCrdtCodecUrl(),
'https://cdn.affine.pro/builds/abc123/assets/crdt-codec.wasm'
);
const unpinnedLoader = createWorkerLoader(manifest, {
baseUrl: 'https://app.affine.pro/workspace/ws-1/page-2',
});
assert.equal(
unpinnedLoader.resolveCrdtCodecUrl(),
'https://app.affine.pro/assets/crdt-codec.wasm?v=abc123'
);
const withoutCodec = createWorkerLoader({
shellVersion: 'mobile-v1',
buildHash: 'abc123',
workers: manifest.workers,
fonts: {},
});
assert.equal(withoutCodec.resolveCrdtCodecUrl(), null);
});
void test('createCrdtWasmClient fails explicitly on missing URL, HTTP 404, corrupt wasm, and clears failed cache', async () => {
const emptyClient = createCrdtWasmClient('');
await assert.rejects(
() => emptyClient.ready(),
/Missing CRDT codec wasm URL/
);
let fetchCalls = 0;
const httpFailClient = createCrdtWasmClient('/assets/crdt-codec.wasm', {
fetchImpl: async () => {
fetchCalls += 1;
return /** @type {Response} */ (
/** @type {unknown} */ ({
ok: false,
status: 404,
arrayBuffer: async () => new ArrayBuffer(0),
})
);
},
});
await assert.rejects(
() => httpFailClient.extractSubdocIds(REAL_YJS_V1_UPDATES),
/Failed to fetch CRDT codec wasm \(404\)/
);
// Retrying after failure must re-attempt fetch rather than staying stuck on a stale rejection.
await assert.rejects(
() => httpFailClient.ready(),
/Failed to fetch CRDT codec wasm \(404\)/
);
assert.equal(fetchCalls, 2);
const corruptClient = createCrdtWasmClient('/assets/crdt-codec.wasm', {
fetchImpl: async () => /** @type {Response} */ (
/** @type {unknown} */ ({
ok: true,
status: 200,
arrayBuffer: async () => new Uint8Array([0, 1, 2, 3]).buffer,
})
),
});
await assert.rejects(() => corruptClient.mergeUpdates(REAL_YJS_V1_UPDATES));
});
void test('buildStubImports rejects unexpected non-wbindgen host import modules', async () => {
// Minimal valid Wasm module importing `(import "env" "clock_now" (func (result i32)))`.
const wasmWithEnvImport = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60,
0x00, 0x01, 0x7f, 0x02, 0x11, 0x01, 0x03, 0x65, 0x6e, 0x76, 0x09, 0x63,
0x6c, 0x6f, 0x63, 0x6b, 0x5f, 0x6e, 0x6f, 0x77, 0x00, 0x00,
]);
const mod = await WebAssembly.compile(wasmWithEnvImport);
assert.throws(
() => buildStubImports(mod),
/Unexpected wasm import: env\.clock_now/
);
});
@@ -363,9 +363,10 @@ void test('OAuth login, native client callback handoff, and single-use code retr
});
void test('sign-in 3-step flow, frozen schema.gql OAuth query, Turnstile reset, and offline Use local workspace', async () => {
// 1. Frozen schema.gql ServerConfigType query uses ONLY name, features, oauthProviders.
// 1. Frozen schema.gql ServerConfigType query gates OAuth on same-origin `baseUrl`.
const gqlBodies = [];
const oauthCfg = await fetchOAuthProviders({
currentOrigin: 'https://app.affine.pro',
fetchImpl: async (_url, init) => {
gqlBodies.push(init.body);
return {
@@ -374,6 +375,7 @@ void test('sign-in 3-step flow, frozen schema.gql OAuth query, Turnstile reset,
data: {
serverConfig: {
name: 'AFFiNE Cloud',
baseUrl: 'https://app.affine.pro',
features: ['OAuth', 'Captcha'],
oauthProviders: ['Google', 'Apple', 'Unsupported'],
},
@@ -382,7 +384,7 @@ void test('sign-in 3-step flow, frozen schema.gql OAuth query, Turnstile reset,
};
},
});
assert.ok(gqlBodies[0].includes('name features oauthProviders'));
assert.ok(gqlBodies[0].includes('name baseUrl features oauthProviders'));
assert.ok(!gqlBodies[0].includes('serverName'));
assert.deepEqual(oauthCfg, {
serverName: 'AFFiNE Cloud',
@@ -390,6 +392,41 @@ void test('sign-in 3-step flow, frozen schema.gql OAuth query, Turnstile reset,
providers: ['Google', 'Apple'],
});
// Cross-origin reverse proxy, missing baseUrl, or invalid baseUrl must hide OAuth providers.
for (const [label, baseUrl, currentOrigin] of [
['cross-origin proxy', 'https://affine.fail', 'https://fail.affine.fail'],
['missing baseUrl', undefined, 'https://app.affine.pro'],
['invalid baseUrl', 'not-a-url', 'https://app.affine.pro'],
['scheme mismatch', 'http://app.affine.pro', 'https://app.affine.pro'],
]) {
const gated = await fetchOAuthProviders({
currentOrigin,
fetchImpl: async () => ({
ok: true,
json: async () => ({
data: {
serverConfig: {
name: 'AFFiNE Cloud',
...(baseUrl !== undefined ? { baseUrl } : {}),
features: ['OAuth'],
oauthProviders: ['Google', 'GitHub'],
},
},
}),
}),
});
assert.deepEqual(
gated,
{
serverName: 'AFFiNE Cloud',
oauth: false,
providers: [],
crossOriginProxy: true,
},
`OAuth must be hidden for ${label}`
);
}
// 2. Captcha challenge passthrough + Turnstile reset lifecycle.
const challengeRes = await maybeLoadTurnstile({
fetchImpl: async () => ({
+8 -1
View File
@@ -1 +1,8 @@
[]
[
{
"metric": "artifacts_bytes.headless_bin",
"action": "ceiling",
"accepted_value": 155000000,
"reason": "Native non-wasm32 targets link blocksuite-preview (RaTeX KaTeX math fonts and Hayro PDF renderer) by default for zero-flag inline/block math and PDF rendering; wasm32 main bundle remains isolated via lazy workers."
}
]