diff --git a/blocksuite/native-playground/AGENTS.md b/blocksuite/native-playground/AGENTS.md index 8c8b7f063e..844d38d6ed 100644 --- a/blocksuite/native-playground/AGENTS.md +++ b/blocksuite/native-playground/AGENTS.md @@ -30,11 +30,18 @@ This document records the active engineering invariants enforced in CI today alo - **Style oracle parity**: Block metrics (`paragraph_spec` with baselines and heading letter spacing, quote/code/divider/bookmark constants, margin collapsing, 24px child indent, the 944px container with 96px / 24px side padding) mirror BlockSuite's page CSS and are asserted against `tokens/style-oracle.json` in both themes by `crates/playground` tests, on the constants (L1) and on rendered frames (L2). Change a metric only together with the oracle. - **Block semantics**: `prop:textAlign` (`left` / `center` / `right`) aligns paragraph and list text and is inherited by nested children that set none; a list prefix stays at the left edge. A collapsed heading hides its own children and the siblings under it up to the next heading of its level; a collapsed toggle hides its children. - **First-line prefixes**: List bullets, numbers, checkboxes and toggles are placed against the first line of the item's text, and a numbered prefix sits on that line's baseline. Single-style labels (title, code, captions, cards) use the plain `InlineLayout`. -- **Snapshot ids**: `page.title_block`, `page.block.`, `page.presence..caret|label`, `chrome.theme_toggle`, `chrome.presence.`. A block records its element snapshot only while it lies completely inside the page viewport; a block cut by the fold is clipped on purpose. +- **Snapshot ids**: `page.title_block`, `page.local_caret`, `page.block.`, `page.presence..caret|label`, `chrome.theme_toggle`, `chrome.presence.`. A block records its element snapshot only while it lies completely inside the page viewport; a block cut by the fold is clipped on purpose. - **Room sync**: `RoomProtocol` is the sans-I/O client of the relay's binary room protocol (`SyncStep1` / `SyncStep2` / `Update` document frames, awareness frames, unconditional reverse `Step2`) over a `DocState`. `connect` supplies the transport: `tokio-tungstenite` on a background thread natively (`--room [--relay ]`), a browser `WebSocket` on the Web (`?room=&ws=`), both fetching image blobs from `/api/collection/{room}/blob/{sourceId}` (a bare HTTP/1.1 `GET` over TCP natively, `fetch` on the Web) and reconnecting with backoff. Native transports speak plain `ws://` / `http://` only: `wss://` / `https://` relays are rejected up front (`RoomConfig::validate_native`) and stay available on the Web. A reconnect re-announces local awareness two clocks ahead, above the tombstone the relay wrote when the previous connection dropped. Awareness renewal and expiry run on the scheduler clock, never the wall clock. - **Images and blobs**: A blob present in the document state is decoded once (PNG, JPEG, WebP, GIF, BMP); bytes that are no such image stay `Image unavailable` and are never fetched again. A blob the page references but the relay does not have yet (an uploader writes `sourceId` before its upload finishes, and the relay announces no completed upload) is fetched again on the scheduler clock with a backoff doubling from 500 ms to a 4 s cap, for as long as the page references it and the room is not offline; ordinary document updates never restart a tracked fetch. The frame shows `Loading image`, then `Image unavailable` after three misses, and the image as soon as a retry finds it. - **Remote selections**: Read only from `selectionV2` entries of the shown page, keyed `` or `:` (split at the last colon, stricter than BlockSuite's prefix match); a selection in another page is never drawn. +### Page editing + +- `EditorSession` keeps the anchor, focus, soft-wrap affinity and vertical navigation goal in document coordinates. The platform input handler exposes UTF-16 offsets within the focused block. Selection painting and IME candidate bounds use the same laid-out geometry as pointer hit-testing. +- A compound structural edit validates against a private copy before committing once to the tracked blocks undo stack. Changing flavour creates a fresh block for live JS models. Edits within a flavour retain the block identity. Cross-block deletion, IME preview and clipboard slices follow the full tree order within Page-visible notes, including collapsed content. Subtrees after the endpoint survive. A range starting in code places those subtrees immediately after the code block. Numbered Markdown lists accept zero as a starting number and continue a preceding numbered sibling when present. Typing within the 500 ms scheduler-clock capture window coalesces. Undo and redo resolve stored relative positions in the title or block text. Local commits publish document updates and selection changes publish awareness under `:native`. Preedit temporarily replaces the selected text in the displayed snapshot. Cancellation restores the directional range. Only a commit writes text. Editing the page title also updates workspace page metadata. +- Clipboard slices carry BlockSuite JSON, HTML and plain text. macOS publishes UTF-8 text and `public.html` and reads HTML-only pasteboard items. Web clipboard events expose HTML and the BlockSuite MIME type. HTML includes the LZ-String URI-encoded `data-blocksuite-snapshot` for lossless block properties, child blocks and inline references. The slice preserves shared text types in nested properties. Pasting into one text block preserves relative positions in its untouched suffix. +- A text-only edit refreshes the changed block's text and reuses the other laid-out bodies. Remote updates preserve the screen position of the reading anchor when its block survives. On Linux headless with 10,000 blocks at 1280 × 800, cold layout and frame took 284.078 ms median / 328.501 ms p95. A keystroke in paragraph 5000 and its frame took 17.793 / 19.454 ms and laid out one block. A steady viewport frame including pixel readback took 10.691 / 16.928 ms. These are observed timings. The single-block work count is enforced by the benchmark. + ### Performance guardrail and theme/style oracle - **`perf/` (`schema.json`, `accepted.json`, `compare-n3.mjs`, `compare-n3.test.mjs`)**: Zero-dependency rolling `N-3` CI comparator with strict schema validation and rerun history anchoring (`--run-id` `created_at` cutoff + pagination). Deterministic byte sizes (`artifacts_bytes.*`) and work counters (non-`_ms` `benchmarks.*`) are hard-gated at strictly `> 10%` (`--fail-on-regression` exits `1`); shared-runner wall-clock timings (`benchmarks.*_ms` at `> 10%`, `ci_wall_ms.*` at `> 10%` and `> 15_000 ms`) are report-only `ADVISORY_SLOWDOWN`. Intentional increases are acknowledged via `{ metric, accepted_value, reason }` ceiling entries in `perf/accepted.json` (with report-only `stale_acceptances` once the rolling baseline catches up). Unmeasured sub-keys are omitted or `null` (never padded with synthetic `0`s) so newly introduced metrics transition through `BOOTSTRAP`. - **`tokens/` (`extract-tokens.mjs`, `tokens.rs`, `icons.rs`, `fonts.lock`, `extract-style-oracle.spec.ts`, `style-oracle.json`)**: `extract-tokens.mjs` deterministically generates Rust-`Ord`-sorted `tokens.rs`, `icons.rs` (preserving inherited `` and stroke attributes), and `fonts.lock` (SHA-256 font asset manifest + `CommunityCanvasTextFonts` descriptors), with `--check` and `rustc --edition 2024 --test` enforced on every push in CI. `style-oracle.json` is regenerated via Vitest Browser (`extract-style-oracle.spec.ts`, `isolate: false` reusable iframe) whenever BlockSuite styles or themes change (until its browser CI job lands). @@ -46,7 +53,7 @@ This document records the active engineering invariants enforced in CI today alo ## Planned Contracts (upcoming crates & features) -- **Editor & whiteboard rendering**: `EditorSession`, world-space content transforms/masks implemented end-to-end in the GPU shaders (today `BlockFlow` applies the world-to-screen mapping per element on the CPU), and the Edgeless whiteboard surface (Edgeless mode shows a placeholder card). +- **Whiteboard rendering**: World-space content transforms/masks implemented end-to-end in the GPU shaders (today `BlockFlow` applies the world-to-screen mapping per element on the CPU), and the Edgeless whiteboard surface (Edgeless mode shows a placeholder card). ## Build & verification commands @@ -60,6 +67,9 @@ CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p blocksuite-playground-doc --n CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace --features harness CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --theme dark --mode page --out frame.png --snapshot frame.json +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- probes +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- bench --json perf-metrics.json +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render-editor artifacts/editor ./scripts/check-invariants.sh node --test perf/compare-n3.test.mjs node tokens/extract-tokens.mjs --check diff --git a/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs b/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs index fd85d04433..8648cba0fc 100644 --- a/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs +++ b/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs @@ -42,6 +42,10 @@ enum Command { page_id: String, title: String, }, + StructuralEdit { + page_id: String, + action: StructuralAction, + }, SyncAll, Reconnect, InsertText { @@ -117,6 +121,17 @@ enum Command { Quit, } +#[derive(Debug, Deserialize)] +#[serde(rename_all = "snake_case")] +enum StructuralAction { + Convert, + Split, + Indent, + Outdent, + Merge, + Title, +} + type WsStream = tokio_tungstenite::WebSocketStream>; @@ -504,6 +519,53 @@ async fn main() { } json!({ "ok": true }) } + Command::StructuralEdit { page_id, action } => { + let page = ws_session.page_mut(&page_id).unwrap(); + let numbered = BlockSpec::List { + list_type: ListType::Numbered, + text: String::new(), + checked: false, + order: Some(1), + }; + let commit = match action { + StructuralAction::Convert => { + page.convert_block_flavour("p-2", "converted", numbered, 100) + } + StructuralAction::Split => { + page.split_text_block("converted", "split", 6, numbered, 110) + } + StructuralAction::Indent => { + page.reparent_block("split", "note-1", "converted", 0, 120) + } + StructuralAction::Outdent => page.dedent_block("split", 130), + StructuralAction::Merge => page + .merge_with_previous_text_block("converted", "split", "note-1", 140) + .map(|(_, c)| c), + StructuralAction::Title => { + page.insert_text("page-1", "prop:title", 0, "Edited ", 150) + } + } + .unwrap() + .unwrap(); + let mut frames = vec![(page_id.clone(), commit.update)]; + if matches!(action, StructuralAction::Title) { + let title = page.read_editable_text("page-1").unwrap().0.plain; + let root = ws_session + .set_page_title(&page_id, &title) + .unwrap() + .unwrap(); + frames.push((ws_session.room().into(), root.update)); + } + for (doc_id, update) in frames { + let data = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id, + message: DocMessage::Update(update), + }) + .unwrap(); + ws.send(WsMsg::Binary(data.into())).await.unwrap(); + } + json!({"ok":true}) + } Command::InsertText { page_id, block_id, diff --git a/blocksuite/native-playground/crates/doc/src/read.rs b/blocksuite/native-playground/crates/doc/src/read.rs index dd90b101f0..c3fb63f51b 100644 --- a/blocksuite/native-playground/crates/doc/src/read.rs +++ b/blocksuite/native-playground/crates/doc/src/read.rs @@ -169,6 +169,10 @@ pub struct BlockNode { } impl BlockNode { + pub fn is_page_visible_note(&self) -> bool { + matches!(self.content, BlockContent::Note { hidden: false, .. }) && !self.is_edgeless_only() + } + /// Whether this block exists only on the Edgeless canvas and is left out of Page mode. pub fn is_edgeless_only(&self) -> bool { match &self.content { diff --git a/blocksuite/native-playground/crates/doc/src/schema.rs b/blocksuite/native-playground/crates/doc/src/schema.rs index 95fc7e31b0..e95d665424 100644 --- a/blocksuite/native-playground/crates/doc/src/schema.rs +++ b/blocksuite/native-playground/crates/doc/src/schema.rs @@ -277,6 +277,13 @@ fn map_array_any(items: Vec) -> Any { Any::Array(vec![Any::Array(items)]) } +pub fn is_leaf_flavour(flavour: &str) -> bool { + matches!( + flavour, + "affine:code" | "affine:divider" | "affine:image" | "affine:bookmark" + ) +} + impl BlockSpec { pub fn flavour(&self) -> &'static str { match self { diff --git a/blocksuite/native-playground/crates/doc/src/session.rs b/blocksuite/native-playground/crates/doc/src/session.rs index f1d2e83d95..a2dccf99b8 100644 --- a/blocksuite/native-playground/crates/doc/src/session.rs +++ b/blocksuite/native-playground/crates/doc/src/session.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use serde_json::{Map as JsonMap, Value as JsonValue}; @@ -26,6 +26,13 @@ pub struct SelectionSnapshot { pub focus: RelativePosition, } +/// Both endpoints in the current document, in their original directional order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResolvedSelection { + pub anchor: (String, u64), + pub focus: (String, u64), +} + /// Result of applying a remote V1 update to a session. #[derive(Debug, Clone)] pub struct RemoteApplyResult { @@ -45,6 +52,99 @@ pub struct PageMeta { pub tags: Vec, } +type PageCommit = Option>; + +fn block_target(id: &str) -> TypeTarget { + TypeTarget::Path(TypePath::root("blocks").key(id)) +} + +fn children_target(id: &str) -> TypeTarget { + TypeTarget::Path(TypePath::root("blocks").key(id).key("sys:children")) +} + +fn child_values(ids: &[String]) -> Vec { + ids.iter() + .map(|id| SessionValue::Any(Any::String(id.clone()))) + .collect() +} + +/// Split an insert-only delta at a UTF-16 boundary without discarding attributes or embeds. +pub fn split_delta( + delta: &[TextDeltaOp], + offset: u64, +) -> DocResult<(Vec, Vec)> { + let mut left = Vec::new(); + let mut right = Vec::new(); + let mut remaining = offset; + for op in delta { + let TextDeltaOp::Insert { insert, format } = op else { + return Err(DocError::InvalidState("expected insert-only text".into())); + }; + let len = match insert { + TextInsert::Text(s) => s.encode_utf16().count(), + TextInsert::Embed(items) => items.len(), + } as u64; + if remaining == 0 { + right.push(op.clone()); + } else if remaining >= len { + left.push(op.clone()); + remaining -= len; + } else { + let (before, after) = match insert { + TextInsert::Text(s) => { + let mut count = 0; + let byte = s + .char_indices() + .find_map(|(byte, ch)| { + let found = count == remaining; + count += ch.len_utf16() as u64; + found.then_some(byte) + }) + .ok_or_else(|| { + DocError::InvalidState("offset splits a surrogate pair".into()) + })?; + ( + TextInsert::Text(s[..byte].into()), + TextInsert::Text(s[byte..].into()), + ) + } + TextInsert::Embed(v) => { + let (a, b) = v.split_at(remaining as usize); + (TextInsert::Embed(a.to_vec()), TextInsert::Embed(b.to_vec())) + } + }; + left.push(TextDeltaOp::Insert { + insert: before, + format: format.clone(), + }); + right.push(TextDeltaOp::Insert { + insert: after, + format: format.clone(), + }); + remaining = 0; + } + } + if remaining != 0 { + return Err(DocError::InvalidState("text offset outside block".into())); + } + Ok((left, right)) +} + +type ChildGraph = BTreeMap>; + +fn descendants(graph: &ChildGraph, roots: impl IntoIterator) -> BTreeSet { + let mut pending: Vec<_> = roots.into_iter().collect(); + let mut found = BTreeSet::new(); + while let Some(id) = pending.pop() { + if found.insert(id.clone()) + && let Some(children) = graph.get(&id) + { + pending.extend(children.iter().cloned()); + } + } + found +} + /// Per-page CRDT session wrapping `DocSession` with an /// `UndoStackId` scoped strictly to the `blocks` root `Y.Map`. pub struct PageDocSession { @@ -103,7 +203,8 @@ impl PageDocSession { } pub fn advance_time(&self, now_ms: u64) { - self.session.advance_time(now_ms); + // Zero is the undo manager's stop-capturing sentinel. Preserve clock differences at scheduler startup. + self.session.advance_time(now_ms.saturating_add(1)); } pub fn encode_state_vector_v1(&self) -> DocResult> { @@ -218,7 +319,7 @@ impl PageDocSession { } } - self.session.advance_time(now_ms); + self.advance_time(now_ms); self.session.begin_tx(SessionTxOrigin::Tracked)?; self.session.map_set( @@ -251,7 +352,7 @@ impl PageDocSession { new_index: u64, now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + self.advance_time(now_ms); let children_target = TypeTarget::Path(TypePath::root("blocks").key(parent_id).key("sys:children")); let items = self.session.read_array(&children_target)?; @@ -281,7 +382,7 @@ impl PageDocSession { text: &str, now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + 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)?) } @@ -295,7 +396,7 @@ impl PageDocSession { len: u64, now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + 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)?) } @@ -310,7 +411,7 @@ impl PageDocSession { attrs: TextAttributes, now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + 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)?) } @@ -323,7 +424,7 @@ impl PageDocSession { delta: &[TextDeltaOp], now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + 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)?) } @@ -336,7 +437,7 @@ impl PageDocSession { value: SessionValue, now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + 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)?) } @@ -350,7 +451,7 @@ impl PageDocSession { spec: SurfaceElementSpec, now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + self.advance_time(now_ms); let element_id = element_id.into(); let entries = spec.into_ymap_entries(&element_id, index); let elements_value_target = TypeTarget::Path( @@ -375,7 +476,7 @@ impl PageDocSession { value: SessionValue, now_ms: u64, ) -> DocResult>> { - self.session.advance_time(now_ms); + self.advance_time(now_ms); let target = TypeTarget::Path( TypePath::root("blocks") .key(surface_block_id) @@ -386,6 +487,592 @@ impl PageDocSession { Ok(self.session.map_set(&target, field.into(), value)?) } + fn child_graph(&self) -> DocResult { + self.session + .read_map(&self.blocks_target)? + .into_iter() + .map(|(id, _)| { + let children = self.read_unknown_block(&id)?.children; + Ok((id, children)) + }) + .collect() + } + + fn child_slot(graph: &ChildGraph, parent: &str, child: &str) -> DocResult { + graph + .get(parent) + .and_then(|v| v.iter().position(|id| id == child)) + .map(|i| i as u64) + .ok_or_else(|| DocError::InvalidState(format!("{child} is not a child of {parent}"))) + } + + /// Validate the entire compound operation against the same CRDT state before opening + /// the live transaction. y-octo cannot roll back an open transaction. Nested commands + /// run under the outer validation pass. The closure must only mutate its page argument. + /// Ordinary single-text edits bypass this path. + pub fn structural_edit( + &mut self, + now_ms: u64, + apply: impl FnOnce(&mut Self) -> DocResult + Clone, + ) -> DocResult { + if self.session.tx_depth() == 0 { + let mut validation = Self::new(self.guid(), self.client_id())?; + validation.apply_remote_update_v1(&self.encode_update_v1()?)?; + // The private replica continues the source clock and never publishes its writes. + validation.session.set_client(self.client_id()); + validation.session.begin_tx(SessionTxOrigin::Tracked)?; + apply.clone()(&mut validation)?; + } + self.stop_capturing()?; + self.advance_time(now_ms); + self.session.begin_tx(SessionTxOrigin::Tracked)?; + let result = apply(self); + let commit = self.session.commit_tx(); + self.stop_capturing()?; + result?; + Ok(commit?) + } + + pub fn delete_block_subtree( + &mut self, + parent_id: &str, + block_id: &str, + now_ms: u64, + ) -> DocResult { + let mut graph = self.child_graph()?; + let index = Self::child_slot(&graph, parent_id, block_id)?; + graph.get_mut(parent_id).unwrap().remove(index as usize); + let candidates = descendants(&graph, [block_id.to_owned()]); + let external = graph + .iter() + .filter(|(id, _)| !candidates.contains(*id)) + .flat_map(|(_, children)| { + children + .iter() + .filter(|id| candidates.contains(*id)) + .cloned() + }); + let retained = descendants(&graph, external); + self.structural_edit(now_ms, |page| { + page.session + .array_remove(&children_target(parent_id), index, 1)?; + for id in candidates.difference(&retained) { + page.session.map_remove(&page.blocks_target, id)?; + } + Ok(()) + }) + } + + fn parent_slot(&self, id: &str) -> DocResult<(String, u64)> { + self.child_graph()? + .into_iter() + .find_map(|(p, children)| children.iter().position(|c| c == id).map(|i| (p, i as u64))) + .ok_or_else(|| DocError::InvalidState(format!("block {id} has no parent"))) + } + + fn numbered_order(&self, id: &str) -> DocResult> { + let block = block_target(id); + let string_is = |key, expected: &str| -> DocResult { + Ok( + matches!(self.session.get_map_value(&block, key)?, Some(SessionReadValue::Any(Any::String(s))) if s == expected), + ) + }; + if !string_is("sys:flavour", "affine:list")? || !string_is("prop:type", "numbered")? { + return Ok(None); + } + let value = match self.session.get_map_value(&block, "prop:order")? { + Some(SessionReadValue::Any(n)) => any_to_normalized_json(&n).as_f64().map(|n| n as i32), + _ => None, + }; + Ok(Some(value.unwrap_or(0))) + } + + fn correct_numbered_order_from( + &mut self, + parent: &str, + slot: usize, + initial: i32, + ) -> DocResult { + let children = self.read_unknown_block(parent)?.children; + let Some(first) = children.get(slot) else { + return Ok(()); + }; + if self.numbered_order(first)?.is_none() { + return Ok(()); + } + let mut order = initial; + if let Some(prev) = slot.checked_sub(1).and_then(|i| children.get(i)) + && let Some(previous) = self.numbered_order(prev)? + { + if previous == 0 { + self.session.map_set( + &block_target(prev), + "prop:order".into(), + SessionValue::Any(Any::Integer(1)), + )?; + } + order = previous.max(1).saturating_add(1); + } + for id in &children[slot..] { + let Some(existing) = self.numbered_order(id)? else { + break; + }; + if existing != order { + self.session.map_set( + &block_target(id), + "prop:order".into(), + SessionValue::Any(Any::Integer(order)), + )?; + } + order = order.saturating_add(1); + } + Ok(()) + } + + pub fn dedent_block(&mut self, id: &str, now_ms: u64) -> DocResult { + let (parent, slot) = self.parent_slot(id)?; + let p = self.read_unknown_block(&parent)?; + if !matches!(p.flavour.as_str(), "affine:paragraph" | "affine:list") { + return Err(DocError::InvalidState( + "cannot outdent from this parent".into(), + )); + } + let p_child_count = self.read_unknown_block(id)?.children.len(); + let (grandparent, parent_slot) = self.parent_slot(&parent)?; + self.structural_edit(now_ms, |page| { + let tail = &p.children[slot as usize + 1..]; + if !tail.is_empty() { + page.session.array_remove( + &children_target(&parent), + slot + 1, + tail.len() as u64, + )?; + page.session + .array_push(&children_target(id), child_values(tail))?; + page.correct_numbered_order_from(id, p_child_count, 1)?; + } + page.reparent_block(id, &parent, &grandparent, parent_slot + 1, now_ms)?; + Ok(()) + }) + } + + pub fn remove_lifting_children(&mut self, id: &str, now_ms: u64) -> DocResult { + let (parent, index) = self.parent_slot(id)?; + let children = self.read_unknown_block(id)?.children; + self.structural_edit(now_ms, |page| { + page.session + .array_remove(&children_target(&parent), index, 1)?; + if !children.is_empty() { + page.session.array_insert( + &children_target(&parent), + index, + child_values(&children), + )?; + } + page.session.map_remove(&page.blocks_target, id)?; + Ok(()) + }) + } + + pub fn reparent_block( + &mut self, + block_id: &str, + old_parent_id: &str, + new_parent_id: &str, + new_index: u64, + now_ms: u64, + ) -> DocResult { + let graph = self.child_graph()?; + let index = Self::child_slot(&graph, old_parent_id, block_id)?; + let siblings = graph + .get(new_parent_id) + .ok_or_else(|| DocError::BlockNotFound(new_parent_id.into()))?; + if new_index > siblings.len() as u64 - u64::from(old_parent_id == new_parent_id) + || (old_parent_id != new_parent_id && siblings.iter().any(|s| s == block_id)) + || descendants(&graph, [block_id.to_owned()]).contains(new_parent_id) + { + return Err(DocError::InvalidState("invalid block destination".into())); + } + self.structural_edit(now_ms, |page| { + page.session + .array_remove(&children_target(old_parent_id), index, 1)?; + page.session.array_insert( + &children_target(new_parent_id), + new_index, + vec![SessionValue::Any(Any::String(block_id.into()))], + )?; + if page.read_unknown_block(block_id)?.flavour == "affine:list" { + page.correct_numbered_order_from(old_parent_id, index as usize, 1)?; + } + page.correct_numbered_order_from(new_parent_id, new_index as usize, 1) + }) + } + + pub fn split_text_block( + &mut self, + block_id: &str, + new_block_id: &str, + split_utf16: u64, + new_spec: BlockSpec, + now_ms: u64, + ) -> DocResult { + let graph = self.child_graph()?; + if graph.contains_key(new_block_id) { + return Err(DocError::InvalidState("duplicate block id".into())); + } + let children = graph + .get(block_id) + .ok_or_else(|| DocError::BlockNotFound(block_id.into()))?; + let collapsed = matches!( + self.session + .get_map_value(&block_target(block_id), "prop:collapsed")?, + Some(SessionReadValue::Any(Any::True)) + ); + let is_page = matches!(self.session.get_map_value(&block_target(block_id),"sys:flavour")?,Some(SessionReadValue::Any(Any::String(f))) if f=="affine:page"); + let (parent, index) = if is_page { + let mut note = None; + for id in children { + let b = block_target(id); + if matches!(self.session.get_map_value(&b,"sys:flavour")?,Some(SessionReadValue::Any(Any::String(f))) if f=="affine:note") + && !matches!(self.session.get_map_value(&b,"prop:displayMode")?,Some(SessionReadValue::Any(Any::String(mode))) if mode=="edgeless") + && !matches!( + self.session.get_map_value(&b, "prop:hidden")?, + Some(SessionReadValue::Any(Any::True)) + ) + { + note = Some(id.as_str()); + break; + } + } + ( + note.ok_or_else(|| { + DocError::InvalidState("page has no visible note to receive title text".into()) + })?, + 0, + ) + } else if split_utf16 > 0 && !children.is_empty() && !collapsed { + (block_id, 0) + } else { + graph + .iter() + .find_map(|(parent, children)| { + children + .iter() + .position(|id| id == block_id) + .map(|i| (parent.as_str(), i + 1)) + }) + .ok_or_else(|| DocError::InvalidState("split block has no parent".into()))? + }; + let target = self.editable_text_target(block_id)?; + let length = self.session.read_text_len(&target)?; + let (_, tail) = split_delta(&self.session.read_text_delta(&target)?, split_utf16)?; + let mut entries = new_spec.into_yblock_entries(new_block_id); + let text = entries + .iter_mut() + .find(|(key, _)| key == "prop:text") + .ok_or_else(|| DocError::InvalidState("split requires a text block".into()))?; + text.1 = SessionValue::Text(tail); + self.structural_edit(now_ms, |page| { + if length > split_utf16 { + page.session + .text_remove(&target, split_utf16, length - split_utf16)?; + } + page.session.map_set( + &page.blocks_target, + new_block_id.to_owned(), + SessionValue::Map(entries), + )?; + page.session.array_insert( + &children_target(parent), + index as u64, + vec![SessionValue::Any(Any::String(new_block_id.into()))], + )?; + if split_utf16 == 0 && !is_page && !children.is_empty() { + page.session + .array_remove(&children_target(block_id), 0, children.len() as u64)?; + page.session + .array_push(&children_target(new_block_id), child_values(children))?; + } + page.correct_numbered_order_from(parent, index, 1) + }) + } + + pub fn merge_with_previous_text_block( + &mut self, + target_id: &str, + source_id: &str, + source_parent_id: &str, + now_ms: u64, + ) -> DocResult<(u64, PageCommit)> { + let graph = self.child_graph()?; + Self::child_slot(&graph, source_parent_id, source_id)?; + let join = self + .session + .read_text_len(&self.editable_text_target(target_id)?)?; + let target = self.editable_text_target(target_id)?; + let source = self.editable_text_target(source_id)?; + let delta = self.session.read_text_delta(&source)?; + let source_len = self.session.read_text_len(&source)?; + let keep = self.read_unknown_block(target_id)?.flavour == "affine:page" + && self.read_unknown_block(source_parent_id)?.flavour == "affine:note" + && graph[source_parent_id].len() == 1 + && graph[source_id].is_empty(); + let commit = self.structural_edit(now_ms, |page| { + let mut append = vec![TextDeltaOp::Retain { + retain: join, + format: None, + }]; + append.extend(delta); + page.session.text_apply_delta(&target, &append)?; + if keep { + page.session.text_remove(&source, 0, source_len)?; + } else { + page.remove_lifting_children(source_id, now_ms)?; + } + Ok(()) + })?; + Ok((join, commit)) + } + + /// Endpoints are in document order. The caller supplies the intervening blocks in + /// page-content pre-order, including collapsed descendants, and the roots of surviving subtrees. + pub fn delete_cross_block_range( + &mut self, + start: (&str, u64), + end: (&str, u64), + intermediate: &[String], + survivors: &[String], + now_ms: u64, + ) -> DocResult { + let graph = self.child_graph()?; + let mut removed = intermediate.to_vec(); + removed.push(end.0.to_owned()); + self.join_range( + &graph, start.0, start.1, end.0, end.1, &removed, survivors, now_ms, + ) + } + + #[allow(clippy::too_many_arguments)] + fn join_range( + &mut self, + graph: &ChildGraph, + start: &str, + from: u64, + end: &str, + to: u64, + removed: &[String], + moved: &[String], + now_ms: u64, + ) -> DocResult { + let candidates = descendants(graph, removed.iter().cloned()); + let protected = descendants(graph, moved.iter().cloned()); + if moved.iter().any(|id| !candidates.contains(id)) + || removed.iter().any(|id| protected.contains(id)) + { + return Err(DocError::InvalidState("invalid surviving subtree".into())); + } + let ids: BTreeSet<_> = candidates.difference(&protected).cloned().collect(); + if ids + .iter() + .any(|id| id.as_str() == start || !graph.contains_key(id)) + || !graph.contains_key(start) + { + return Err(DocError::InvalidState("invalid joined block range".into())); + } + let target = self.editable_text_target(start)?; + let source = self.editable_text_target(end)?; + split_delta(&self.session.read_text_delta(&target)?, from)?; + let (_, tail) = split_delta(&self.session.read_text_delta(&source)?, to)?; + let mut delta = vec![TextDeltaOp::Retain { + retain: from, + format: None, + }]; + let len = self.session.read_text_len(&target)? - from; + if len > 0 { + delta.push(TextDeltaOp::Delete { delete: len }); + } + delta.extend(tail); + let flavour = self.read_unknown_block(start)?.flavour; + let title = flavour == "affine:page"; + let dest = if title && !moved.is_empty() { + self.read_page_snapshot()? + .root + .and_then(|root| { + root.children + .into_iter() + .find(|node| node.is_page_visible_note()) + }) + .map(|node| node.id) + .ok_or_else(|| DocError::InvalidState("title has no visible note".into()))? + } else { + start.to_owned() + }; + if moved + .iter() + .any(|id| descendants(graph, [id.clone()]).contains(start)) + { + return Err(DocError::InvalidState("join would create a cycle".into())); + } + self.structural_edit(now_ms, |page| { + page.session.text_apply_delta(&target, &delta)?; + for (id, children) in graph.iter().filter(|(id, _)| !ids.contains(id.as_str())) { + for (index, _) in children + .iter() + .enumerate() + .rev() + .filter(|(_, id)| ids.contains(id.as_str())) + { + page.session + .array_remove(&children_target(id), index as u64, 1)?; + } + } + if !moved.is_empty() { + if title { + page.session + .array_insert(&children_target(&dest), 0, child_values(moved))?; + } else if crate::schema::is_leaf_flavour(&flavour) { + let (parent, slot) = page.parent_slot(start)?; + page.session.array_insert( + &children_target(&parent), + slot + 1, + child_values(moved), + )?; + } else { + page.session + .array_push(&children_target(&dest), child_values(moved))?; + } + } + for id in ids { + page.session.map_remove(&page.blocks_target, &id)?; + } + Ok(()) + }) + } + + pub fn convert_block_flavour( + &mut self, + id: &str, + replacement_id: &str, + spec: BlockSpec, + now_ms: u64, + ) -> DocResult { + self.convert_with_initial_order(id, replacement_id, spec, 1, now_ms) + } + + /// A typed numbered prefix supplies its starting order when no numbered sibling precedes it. + pub fn convert_markdown_block( + &mut self, + id: &str, + replacement_id: &str, + spec: BlockSpec, + now_ms: u64, + ) -> DocResult { + let initial = match &spec { + BlockSpec::List { order: Some(n), .. } => *n, + _ => 1, + }; + self.convert_with_initial_order(id, replacement_id, spec, initial, now_ms) + } + + fn convert_with_initial_order( + &mut self, + id: &str, + replacement_id: &str, + spec: BlockSpec, + initial: i32, + now_ms: u64, + ) -> DocResult { + let accepts_children = matches!( + spec, + BlockSpec::Paragraph { .. } + | BlockSpec::List { .. } + | BlockSpec::Note { .. } + | BlockSpec::Frame { .. } + | BlockSpec::EdgelessText { .. } + | BlockSpec::Page { .. } + ); + let numbered = matches!( + spec, + BlockSpec::List { + list_type: crate::schema::ListType::Numbered, + .. + } + ); + let old = self.read_unknown_block(id)?; + let (parent, slot) = self.parent_slot(id)?; + let same = old.flavour == spec.flavour(); + if !same + && self + .session + .get_map_value(&self.blocks_target, replacement_id)? + .is_some() + { + return Err(DocError::InvalidState( + "replacement id must be fresh".into(), + )); + } + self.structural_edit(now_ms, |page| { + if same { + for (key, value) in spec.into_yblock_entries(id) { + if matches!( + key.as_str(), + "prop:type" | "prop:checked" | "prop:order" | "prop:language" + ) && let SessionValue::Any(v) = &value + && page.session.get_map_value(&block_target(id), &key)? + != Some(SessionReadValue::Any(v.clone())) + { + page.session.map_set(&block_target(id), key, value)?; + } + } + } else { + let delta = if matches!( + spec, + BlockSpec::Paragraph { .. } | BlockSpec::List { .. } | BlockSpec::Code { .. } + ) { + page.read_editable_text(id)?.0.delta + } else { + Vec::new() + }; + let align = page + .session + .get_map_value(&block_target(id), "prop:textAlign")?; + page.add_block(replacement_id, spec, Some(&parent), Some(slot), now_ms)?; + if !delta.is_empty() { + page.apply_text_delta(replacement_id, "prop:text", &delta, now_ms)?; + } + if let Some(SessionReadValue::Any(value)) = align { + page.set_block_prop( + replacement_id, + "prop:textAlign", + SessionValue::Any(value), + now_ms, + )?; + } + page.session + .array_remove(&children_target(&parent), slot + 1, 1)?; + page.session.map_remove(&page.blocks_target, id)?; + if !old.children.is_empty() { + if accepts_children { + page.session.array_push( + &children_target(replacement_id), + child_values(&old.children), + )?; + } else { + page.session.array_insert( + &children_target(&parent), + slot + 1, + child_values(&old.children), + )?; + } + } + } + if numbered { + page.correct_numbered_order_from(&parent, slot as usize, initial)?; + } + Ok(()) + }) + } + /// Capture a relative-position selection snapshot on a text property and attach /// it to the top undo item of this page's `blocks` undo stack. pub fn capture_selection_snapshot( @@ -395,16 +1082,8 @@ impl PageDocSession { focus_block_id: &str, focus_offset: u64, ) -> DocResult { - let anchor_target = TypeTarget::Path( - TypePath::root("blocks") - .key(anchor_block_id) - .key("prop:text"), - ); - let focus_target = TypeTarget::Path( - TypePath::root("blocks") - .key(focus_block_id) - .key("prop:text"), - ); + let anchor_target = self.editable_text_target(anchor_block_id)?; + let focus_target = self.editable_text_target(focus_block_id)?; let anchor = self .session .create_relative_position(&anchor_target, anchor_offset, 0)?; @@ -419,6 +1098,48 @@ impl PageDocSession { }) } + /// Read only the edited Y.Text for incremental layout, together with its snapshot property. + pub fn read_editable_text(&self, id: &str) -> DocResult<(crate::read::RichText, JsonValue)> { + let target = self.editable_text_target(id)?; + let TypeTarget::Identity(identity) = &target else { + unreachable!() + }; + let value = self.export_y_value(&SessionReadValue::Text(identity.clone()))?; + Ok(( + crate::read::RichText { + plain: self.session.read_text_string(&target)?, + delta: self.session.read_text_delta(&target)?, + }, + value, + )) + } + + fn editable_text_target(&self, block_id: &str) -> DocResult { + let block = TypeTarget::Path(TypePath::root("blocks").key(block_id)); + let title = matches!(self.session.get_map_value(&block, "sys:flavour")?, + Some(SessionReadValue::Any(Any::String(name))) if name == "affine:page"); + let key = if title { "prop:title" } else { "prop:text" }; + match self.session.get_map_value(&block, key)? { + Some(SessionReadValue::Text(identity)) => Ok(TypeTarget::Identity(identity)), + _ => Err(DocError::InvalidState(format!("missing {block_id}.{key}"))), + } + } + + pub fn resolve_selection_snapshot( + &self, + snapshot: &SelectionSnapshot, + ) -> DocResult> { + let resolve = |id: &str, position: &RelativePosition| { + let absolute = self.session.resolve_relative_position(position, true)?; + let target = self.editable_text_target(id).ok()?; + (target == TypeTarget::Identity(absolute.r#type)) + .then(|| (id.to_owned(), absolute.index)) + }; + Ok(resolve(&snapshot.anchor_block_id, &snapshot.anchor) + .zip(resolve(&snapshot.focus_block_id, &snapshot.focus)) + .map(|(anchor, focus)| ResolvedSelection { anchor, focus })) + } + pub fn set_undo_selection_snapshot(&self, snapshot: SelectionSnapshot) -> DocResult { Ok(self.session.set_stack_selection_meta( self.undo_stack_id, @@ -529,6 +1250,42 @@ impl PageDocSession { Ok(JsonValue::Object(root)) } + pub fn export_slice_props(&self, id: &str) -> DocResult> { + self.session + .read_map(&block_target(id))? + .into_iter() + .filter(|(key, _)| key.starts_with("prop:")) + .map(|(key, value)| Ok((key, self.export_slice_value(&value)?))) + .collect() + } + + fn export_slice_value(&self, value: &SessionReadValue) -> DocResult { + match value { + SessionReadValue::Map(id) => { + let entries = self.session.read_map(&TypeTarget::Identity(id.clone()))?; + Ok(JsonValue::Object( + entries + .into_iter() + .map(|(k, v)| Ok((k, self.export_slice_value(&v)?))) + .collect::>()?, + )) + } + SessionReadValue::Array(id) => { + let items = self.session.read_array(&TypeTarget::Identity(id.clone()))?; + Ok(JsonValue::Array( + items + .iter() + .map(|v| self.export_slice_value(v)) + .collect::>()?, + )) + } + SessionReadValue::Text(_) => Ok( + serde_json::json!({"$blocksuite:internal:text$":true, "delta":self.export_y_value(value)?}), + ), + _ => self.export_y_value(value), + } + } + pub(crate) fn export_y_value(&self, value: &SessionReadValue) -> DocResult { match value { SessionReadValue::Any(any) => Ok(any_to_normalized_json(any)), @@ -823,6 +1580,33 @@ impl WorkspaceSession { } /// Read all page metadata entries currently in `meta.pages`. + pub fn set_page_title( + &mut self, + page_id: &str, + title: &str, + ) -> DocResult>> { + for item in self + .root + .read_array(&TypeTarget::Path(TypePath::root("meta").key("pages")))? + { + if let SessionReadValue::Map(identity) = item { + let target = TypeTarget::Identity(identity); + if matches!(self.root.get_map_value(&target,"id")?,Some(SessionReadValue::Any(Any::String(id))) if id==page_id) + { + if matches!(self.root.get_map_value(&target,"title")?,Some(SessionReadValue::Any(Any::String(s))) if s==title) + { + return Ok(None); + } + return Ok(self.root.map_set( + &target, + "title".into(), + SessionValue::Any(Any::String(title.into())), + )?); + } + } + } + Ok(None) + } pub fn list_pages(&self) -> DocResult> { let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages")); let Ok(items) = self.root.read_array(&pages_target) else { diff --git a/blocksuite/native-playground/crates/doc/tests/structural_edits.rs b/blocksuite/native-playground/crates/doc/tests/structural_edits.rs new file mode 100644 index 0000000000..841131a564 --- /dev/null +++ b/blocksuite/native-playground/crates/doc/tests/structural_edits.rs @@ -0,0 +1,336 @@ +use blocksuite_playground_doc::{ + DocResult, + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, +}; +use y_octo::{Any, TextAttributes}; + +fn paragraph(text: &str) -> BlockSpec { + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: text.into(), + } +} + +#[test] +fn title_and_backward_range_resolve_after_atomic_join_undo() -> DocResult { + let mut page = PageDocSession::new("doc", 12)?; + page.add_block( + "root", + BlockSpec::Page { + title: "Title".into(), + }, + None, + None, + 0, + )?; + for (id, text) in [("a", "ab"), ("b", "cd"), ("c", "ef")] { + page.add_block(id, paragraph(text), Some("root"), None, 1)?; + } + let title = page.capture_selection_snapshot("root", 2, "a", 0)?; + let before = page.capture_selection_snapshot("c", 1, "a", 1)?; + let original = page.export_doc_json()?; + page.delete_cross_block_range(("a", 1), ("c", 1), &["b".into()], &[], 10)?; + page.set_undo_selection_snapshot(before)?; + let joined = page.export_doc_json()?; + assert_eq!(joined["blocks"]["a"]["prop:text"][0]["insert"], "af"); + assert!(joined["blocks"].get("b").is_none()); + let restored = page.undo()?.unwrap().selection_meta.unwrap(); + assert_eq!(page.export_doc_json()?, original); + let resolved = page.resolve_selection_snapshot(&restored)?.unwrap(); + assert_eq!(resolved.anchor, ("c".into(), 1)); + assert_eq!(resolved.focus, ("a".into(), 1)); + assert_eq!( + page.resolve_selection_snapshot(&title)?.unwrap().anchor, + ("root".into(), 2) + ); + page.redo()?; + assert_eq!(page.export_doc_json()?, joined); + Ok(()) +} + +#[test] +fn split_and_merge_preserve_surrogate_pairs_marks_and_undo_boundaries() -> DocResult { + let mut page = PageDocSession::new("doc", 13)?; + page.add_block( + "root", + BlockSpec::Page { + title: String::new(), + }, + None, + None, + 0, + )?; + page.add_block("a", paragraph("A🪶B"), Some("root"), None, 1)?; + page.format_text( + "a", + "prop:text", + 1, + 2, + TextAttributes::from([("bold".into(), Any::True)]), + 2, + )?; + let original = page.export_doc_json()?; + assert!( + page.split_text_block("a", "b", 2, paragraph(""), 3) + .is_err() + ); + assert_eq!(page.export_doc_json()?, original); + page.split_text_block("a", "b", 1, paragraph(""), 4)?; + let split = page.export_doc_json()?; + assert_eq!( + split["blocks"]["b"]["prop:text"][0]["attributes"]["bold"], + true + ); + let (offset, commit) = page.merge_with_previous_text_block("a", "b", "root", 5)?; + assert_eq!(offset, 1); + assert!(commit.is_some()); + assert_eq!(page.export_doc_json()?, original); + page.undo()?; + assert_eq!(page.export_doc_json()?, split); + page.undo()?; + assert_eq!(page.export_doc_json()?, original); + Ok(()) +} + +#[test] +fn shared_descendants_survive_deletion_and_cycles_are_rejected_before_mutation() -> DocResult { + use y_octo::{SessionValue, TypePath, TypeTarget}; + let mut page = PageDocSession::new("doc", 17)?; + page.add_block( + "root", + BlockSpec::Page { + title: String::new(), + }, + None, + None, + 0, + )?; + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 1, + )?; + for (id, parent) in [ + ("a", "note"), + ("b", "note"), + ("shared", "a"), + ("leaf", "shared"), + ("unique", "a"), + ] { + page.add_block(id, paragraph(id), Some(parent), None, 1)?; + } + let edges = TypeTarget::Path(TypePath::root("blocks").key("b").key("sys:children")); + page.inner_mut().array_push( + &edges, + vec![SessionValue::Any(Any::String("shared".into()))], + )?; + let original = page.export_doc_json()?; + assert!(page.reparent_block("a", "note", "leaf", 0, 5).is_err()); + assert_eq!(page.export_doc_json()?, original); + page.delete_block_subtree("note", "a", 6)?; + let blocks = page.export_doc_json()?["blocks"].clone(); + assert!(blocks.get("a").is_none() && blocks.get("unique").is_none()); + assert!(blocks.get("shared").is_some() && blocks.get("leaf").is_some()); + page.undo()?; + assert_eq!(page.export_doc_json()?, original); + page.reparent_block("b", "note", "a", 0, 8)?; + page.undo()?; + assert_eq!(page.export_doc_json()?, original); + Ok(()) +} + +#[test] +fn split_at_start_moves_children_and_merge_lifts_them_into_the_old_slot() -> DocResult { + let mut page = PageDocSession::new("doc", 21)?; + page.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?; + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 0, + )?; + for (id, parent) in [("a", "note"), ("b", "a"), ("c", "a"), ("d", "note")] { + page.add_block(id, paragraph(id), Some(parent), None, 0)?; + } + let initial = page.export_doc_json()?; + page.split_text_block("a", "second", 0, paragraph(""), 5)?; + assert!(page.read_unknown_block("a")?.children.is_empty()); + assert_eq!(page.read_unknown_block("second")?.children, ["b", "c"]); + assert_eq!( + page.read_unknown_block("note")?.children, + ["a", "second", "d"] + ); + page.merge_with_previous_text_block("a", "second", "note", 10)?; + assert_eq!( + page.read_unknown_block("note")?.children, + ["a", "b", "c", "d"] + ); + assert!(page.read_unknown_block("a")?.children.is_empty()); + page.undo()?; + page.undo()?; + assert_eq!(page.export_doc_json()?, initial); + Ok(()) +} + +#[test] +fn title_range_removes_intermediate_subtrees_and_preserves_end_children_in_note() -> DocResult { + let mut p = PageDocSession::new("doc", 22)?; + p.add_block( + "root", + BlockSpec::Page { + title: "Title".into(), + }, + None, + None, + 0, + )?; + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 0, + )?; + for (id, parent) in [ + ("fold", "note"), + ("hidden", "fold"), + ("end", "note"), + ("child", "end"), + ("next", "note"), + ] { + p.add_block(id, paragraph(id), Some(parent), None, 0)?; + } + let original = p.export_doc_json()?; + p.delete_cross_block_range( + ("root", 2), + ("end", 1), + &["fold".into()], + &["child".into()], + 2, + )?; + assert_eq!(p.read_unknown_block("root")?.children, ["note"]); + assert_eq!(p.read_unknown_block("note")?.children, ["child", "next"]); + assert!(p.read_unknown_block("hidden").is_err()); + assert_eq!(p.read_editable_text("root")?.0.plain, "Tind"); + p.undo()?; + assert_eq!(p.export_doc_json()?, original); + Ok(()) +} + +#[test] +fn sole_note_paragraph_stays_in_place_and_failed_compound_edit_is_invisible() -> DocResult { + let mut p = PageDocSession::new("doc", 23)?; + p.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?; + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 0, + )?; + p.add_block("solo", paragraph("solo"), Some("note"), None, 0)?; + let before = p.export_doc_json()?; + assert!( + p.structural_edit(1, |page| { + page.insert_text("solo", "prop:text", 0, "bad", 1)?; + page.reparent_block("solo", "note", "missing", 0, 1)?; + Ok(()) + }) + .is_err() + ); + assert_eq!(p.export_doc_json()?, before); + p.merge_with_previous_text_block("root", "solo", "note", 2)?; + assert_eq!(p.read_unknown_block("note")?.children, ["solo"]); + assert_eq!(p.read_editable_text("solo")?.0.plain, ""); + assert_eq!(p.read_editable_text("root")?.0.plain, "Tsolo"); + p.undo()?; + assert_eq!(p.export_doc_json()?, before); + Ok(()) +} + +#[test] +fn flavour_changes_preserve_alignment_and_dedent_adopts_trailing_siblings() -> DocResult { + use y_octo::SessionValue; + let mut p = PageDocSession::new("doc", 24)?; + p.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?; + p.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 0, + )?; + for (id, parent) in [("a", "note"), ("b", "a"), ("c", "a"), ("d", "b")] { + p.add_block(id, paragraph(id), Some(parent), None, 0)?; + } + p.set_block_prop( + "a", + "prop:textAlign", + SessionValue::Any(Any::String("center".into())), + 1, + )?; + let spec = BlockSpec::Paragraph { + paragraph_type: ParagraphType::H2, + text: String::new(), + }; + p.convert_block_flavour("a", "spare", spec, 2)?; + let json = p.export_doc_json()?; + assert_eq!(json["blocks"]["a"]["prop:textAlign"], "center"); + assert!(json["blocks"].get("spare").is_none()); + let list = BlockSpec::List { + list_type: blocksuite_playground_doc::schema::ListType::Numbered, + text: String::new(), + checked: false, + order: Some(1), + }; + p.convert_block_flavour("a", "list", list, 3)?; + let json = p.export_doc_json()?; + assert_eq!(json["blocks"]["list"]["prop:textAlign"], "center"); + assert_eq!(p.read_unknown_block("list")?.children, ["b", "c"]); + assert_eq!(p.read_editable_text("list")?.0.plain, "a"); + p.dedent_block("b", 4)?; + assert_eq!(p.read_unknown_block("note")?.children, ["list", "b"]); + assert_eq!(p.read_unknown_block("b")?.children, ["d", "c"]); + p.undo()?; + assert_eq!(p.export_doc_json()?, json); + Ok(()) +} + +#[test] +fn converting_to_a_leaf_lifts_children_at_the_replaced_slot() -> DocResult { + let mut p = PageDocSession::new("doc", 41)?; + p.add_block("note", BlockSpec::Note { xywh: None }, None, None, 0)?; + for (id, parent) in [ + ("p", "note"), + ("child1", "p"), + ("child2", "p"), + ("following", "note"), + ] { + p.add_block(id, paragraph(id), Some(parent), None, 0)?; + } + let original = p.export_doc_json()?; + p.convert_block_flavour( + "p", + "code1", + BlockSpec::Code { + text: String::new(), + language: None, + caption: String::new(), + }, + 1, + )?; + assert_eq!( + p.read_unknown_block("note")?.children, + ["code1", "child1", "child2", "following"] + ); + assert!(p.read_unknown_block("code1")?.children.is_empty()); + assert_eq!(p.read_editable_text("code1")?.0.plain, "p"); + assert!(p.read_unknown_block("p").is_err()); + p.undo()?; + assert_eq!(p.export_doc_json()?, original); + Ok(()) +} diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs index 96e133bbe9..3f9102c7a1 100644 --- a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs +++ b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs @@ -8,12 +8,17 @@ use blocksuite_playground_doc::{ use playground::{ PlaygroundMode, PlaygroundOptions, PlaygroundTheme, PlaygroundView, register_bundled_fonts, }; +use playground::{ + editor_session::{DocPoint, DocumentSelection}, + room_client::DocState, +}; use serde::Serialize; use std::cell::RefCell; use std::path::PathBuf; use std::process::Command; use std::rc::Rc; use std::time::{Duration, UNIX_EPOCH}; +use ui::EntityInputHandler; use ui::{ Application, ApplicationHandle, Bounds, FrameSnapshot, HeadlessPlatform, HeadlessWindow, WindowBounds, WindowHandle, WindowOptions, audit_frame_snapshot, point, prelude::*, px, size, @@ -685,6 +690,180 @@ fn bench_room_sync_1k_ops_ms() -> Result { Ok(timing_stat(samples_ms)) } +impl HeadlessSession { + fn update( + &self, + f: impl FnOnce(&mut PlaygroundView, &mut ui::Window, &mut ui::Context) -> R, + ) -> Result { + self.app.update(|cx| self.window_handle.update(cx, f)) + } + fn select(&self, block: &str, offset: u64) -> Result<()> { + self.update(|v, w, cx| { + let p = DocPoint::new(block, offset); + v.select_document_range( + DocumentSelection { + anchor: p.clone(), + focus: p, + }, + w, + cx, + ); + }) + } + fn type_text(&self, text: &str) -> Result<()> { + self.update(|v, w, cx| v.replace_text_in_range(None, text, w, cx)) + } + fn key(&self, key: &str, shift: bool, command: bool) { + self.headless_win + .dispatch_input(ui::PlatformInput::KeyDown(ui::KeyDownEvent { + keystroke: ui::Keystroke { + key: key.into(), + key_char: None, + modifiers: ui::Modifiers { + shift, + platform: command, + control: command, + ..Default::default() + }, + }, + is_held: false, + prefer_character_input: false, + })); + } + fn caret(&self, id: &str, offset: u64) -> Result> { + self.update(|v, w, _| { + let layout = v.flow_layout().context("page layout")?; + let rect = layout + .block(id) + .context("caret block")? + .caret_rect(DocPoint::new(id, offset).caret) + .context("editable block")?; + let column = + playground::block_flow::page_geometry(f32::from(w.viewport_size().width)).column_x; + Ok(point( + px(column + rect.x), + px(playground::TOPBAR_HEIGHT + rect.y + rect.h * 0.5 - v.scroll_offset()), + )) + })? + } + fn image(&self) -> Result { + self.update(|_, w, _| w.render_to_image())? + } + fn doc_json(&self) -> Result { + Ok(self.update(|v, _, _| { + v.document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap() + .export_doc_json() + })??) + } + fn selection(&self) -> Result { + self.update(|v, _, _| v.document_selection().cloned())? + .context("active selection") + } + fn set_texts(&self, texts: &[&str]) -> Result<()> { + let doc = probe_doc(texts.iter().copied())?; + self.update(|v, _, cx| v.set_document(doc, cx))?; + self.headless_win.request_frame(); + Ok(()) + } +} + +fn probe_doc<'a>(texts: impl IntoIterator) -> Result { + let mut doc = DocState::new("editing", 23)?; + doc.workspace + .create_page(playground::HOME_PAGE_ID, "Editing", 0)?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + page.inner_mut() + .begin_tx(y_octo::SessionTxOrigin::Untracked)?; + page.add_block( + "root", + BlockSpec::Page { + title: "Editing".into(), + }, + None, + None, + 0, + )?; + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 0, + )?; + for (i, text) in texts.into_iter().enumerate() { + page.add_block( + format!("p{i}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: text.into(), + }, + Some("note"), + None, + 0, + )?; + } + page.inner_mut().commit_tx()?; + Ok(doc) +} + +fn bench_page(session: &HeadlessSession) -> Result<(TimingStat, TimingStat, u64)> { + const COUNT: usize = 10_000; + let mut cold = Vec::new(); + let mut edits = Vec::new(); + let mut frames = Vec::new(); + let mut work = 0; + for _ in 0..5 { + let doc = probe_doc(std::iter::repeat_n("An editable paragraph.", COUNT - 2))?; + session.update(|v, _, cx| v.set_document(doc, cx))?; + let t = ui::clock_now(); + session.headless_win.request_frame(); + cold.push(t.elapsed().as_secs_f64() * 1000.); + let laid_out = session.update(|v, _, _| v.flow_layout().unwrap().stats.laid_out)?; + anyhow::ensure!( + laid_out == COUNT - 1, + "cold pass laid out {laid_out} visible-flow blocks" + ); + session.select("p5000", 5)?; + session.headless_win.request_frame(); + for _ in 0..6 { + let t = ui::clock_now(); + session.type_text("x")?; + session.headless_win.request_frame(); + edits.push(t.elapsed().as_secs_f64() * 1000.); + let (count, visible) = session.update(|v, w, _| { + ( + v.flow_layout().unwrap().stats.laid_out, + w.frame_snapshot() + .elements + .keys() + .filter(|id| id.starts_with("page.block.")) + .count(), + ) + })?; + anyhow::ensure!(count == 1, "single edit reshaped {count} blocks"); + anyhow::ensure!( + visible > 0 && visible < 40, + "viewport instantiated {visible} complete blocks" + ); + work = count as u64; + let t = ui::clock_now(); + session.update(|_, w, _| w.refresh())?; + session.headless_win.request_frame(); + let _ = session.image()?; + frames.push(t.elapsed().as_secs_f64() * 1000.); + } + } + let (cold, edits, frames) = (timing_stat(cold), timing_stat(edits), timing_stat(frames)); + println!( + "10k blocks: cold median/p95 {:.3}/{:.3} ms, edit {:.3}/{:.3} ms, restored viewport frame+readback {:.3}/{:.3} ms, {work} body laid out", + cold.median, cold.p95, edits.median, edits.p95, frames.median, frames.p95 + ); + Ok((cold, edits, work)) +} + fn run_bench( out_json: PathBuf, explicit_commit: Option, @@ -728,6 +907,7 @@ fn run_bench( .map(|m| m.len()) .unwrap_or(0); + let (cold, edits, work) = bench_page(&session)?; let metrics = PerfMetricsV1 { schema_version: 1, commit, @@ -741,9 +921,9 @@ fn run_bench( benchmarks: BenchmarksV1 { doc_1k_edits_ms: Some(doc_1k_edits_ms), room_sync_1k_ops_ms: Some(room_sync_1k_ops_ms), - layout_10k_blocks_cold_ms: None, - layout_single_keystroke_ms: None, - layout_single_keystroke_blocks_relayout: None, + layout_10k_blocks_cold_ms: Some(cold), + layout_single_keystroke_ms: Some(edits), + layout_single_keystroke_blocks_relayout: Some(work), edgeless_1k_pan_zoom_frame_ms: None, headless_frame_render_ms: timing_stat(frame_times_ms), }, @@ -762,10 +942,443 @@ fn run_bench( Ok(()) } +fn probe_geometry(s: &HeadlessSession) -> Result<()> { + use playground::rich_text::{ + CaretPosition, RichParagraph, RichParagraphStyle, WrapAffinity, sample_paragraph, + }; + use y_octo::{TextDeltaOp, TextInsert}; + let n = s.update(|_, w, _| -> Result { + let mut delta = sample_paragraph()?.delta().to_vec(); + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text("中文👨‍👩‍👧‍👦".into()), + format: None, + }); + let p = RichParagraph::from_delta(delta)?; + let layout = p.layout(w.text_system(), &RichParagraphStyle::default(), 158.); + let mut n = 0; + let mut offset = 0; + loop { + for affinity in [WrapAffinity::Downstream, WrapAffinity::Upstream] { + let pos = CaretPosition { + utf16_offset: offset, + affinity, + }; + if affinity == WrapAffinity::Upstream + && !layout.lines().windows(2).any(|l| { + l[0].source_utf16.end == offset && l[1].source_utf16.start == offset + }) + { + continue; + } + let rect = layout.caret_rect(pos); + let hit = layout.hit_test(rect.origin + point(px(0.), rect.size.height * 0.5)); + anyhow::ensure!(hit == pos, "P1 {pos:?} at {:?} hit {hit:?}", rect.origin); + n += 1; + } + if offset == p.index().utf16_len() { + break; + } + offset = p.index().next_grapheme_utf16(offset); + } + Ok(n) + })??; + println!("P1 {n} grapheme/affinity positions, zero mismatches"); + let long = "Wrap this line across the page. ".repeat(30); + s.set_texts(&[&long, "", "i", &long])?; + s.select("p0", 15)?; + s.headless_win.request_frame(); + let goal = s.caret("p0", 15)?.x; + let mut visited = std::collections::BTreeSet::new(); + let mut max_drift = 0f32; + let mut steps = 0; + let column = s.update(|_, w, _| { + playground::block_flow::page_geometry(f32::from(w.viewport_size().width)).column_x + })?; + for _ in 0..100 { + s.key("down", false, false); + s.headless_win.request_frame(); + let (sel, x) = s.update(|v, _, _| (v.document_selection().unwrap().clone(), v.goal_x()))?; + let drift = (x.context("P2 missing goal")? + column - f32::from(goal)).abs(); + max_drift = max_drift.max(drift); + visited.insert(sel.focus.block_id.clone()); + steps += 1; + if sel.focus.block_id == "p3" { + break; + } + } + anyhow::ensure!( + steps >= 7 && visited.len() == 4 && max_drift <= 1.0, + "P2 {steps} steps over {visited:?}, drift {max_drift}" + ); + s.key("up", true, false); + s.headless_win.request_frame(); + anyhow::ensure!( + s.selection()?.anchor.block_id == "p3" && s.selection()?.focus.block_id == "p2", + "P2 reverse extension" + ); + println!("P2 sticky goal crossed {steps} lines, drift {max_drift:.3}px"); + Ok(()) +} + +fn mouse(s: &HeadlessSession, id: &str, offset: u64, count: usize, drag: bool) -> Result<()> { + let position = s.caret(id, offset)?; + let mods = ui::Modifiers::default(); + if drag { + s.headless_win + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position, + pressed_button: Some(ui::MouseButton::Left), + modifiers: mods, + })); + } else { + s.headless_win + .dispatch_input(ui::PlatformInput::MouseDown(ui::MouseDownEvent { + position, + button: ui::MouseButton::Left, + click_count: count, + modifiers: mods, + first_mouse: false, + })); + } + s.platform.run_until_parked(); + Ok(()) +} + +fn probe_selection(s: &HeadlessSession) -> Result<()> { + let wrapped = "two beta ".repeat(12); + s.set_texts(&["one alpha", &wrapped, "three gamma"])?; + let original = s.doc_json()?; + for reverse in [false, true] { + let (a, b) = if reverse { + (("p2", 5), ("p0", 3)) + } else { + (("p0", 3), ("p2", 5)) + }; + mouse(s, a.0, a.1, 1, false)?; + mouse(s, b.0, b.1, 1, true)?; + s.headless_win.request_frame(); + let sel = s.selection()?; + anyhow::ensure!( + sel.anchor == DocPoint::new(a.0, a.1) && sel.focus == DocPoint::new(b.0, b.1), + "P3 incorrect drag {sel:?}" + ); + s.update(|v, _, _| -> Result<()> { + let layout = v.flow_layout().context("selection layout")?; + let rects = v.selection_rects(&layout); + let mut previous_bottom = None; + let mut wrapped_rows = 0; + for id in ["p0", "p1", "p2"] { + let b = layout.block(id).context("selected block")?; + let lines: Vec<_> = rects + .iter() + .filter(|r| r.y >= b.y && r.bottom() <= b.y + b.body.height + 0.01) + .collect(); + anyhow::ensure!( + !lines.is_empty() + && lines + .windows(2) + .all(|r| (r[0].bottom() - r[1].y).abs() < 0.01), + "line-box gap or overlap" + ); + anyhow::ensure!( + previous_bottom.is_none_or(|y| y <= lines[0].y), + "non-monotonic block selection" + ); + previous_bottom = lines.last().map(|l| l.bottom()); + wrapped_rows += lines.len(); + } + anyhow::ensure!( + wrapped_rows == rects.len() && wrapped_rows > 3, + "unexpected inter-block rectangles or missing wrapped lines" + ); + Ok(()) + })??; + s.key("backspace", false, false); + s.headless_win.request_frame(); + let joined = s.doc_json()?; + anyhow::ensure!( + joined["blocks"]["p0"]["prop:text"][0]["insert"] == "one gamma" + && joined["blocks"]["p2"].is_null(), + "P3 incorrect joined doc" + ); + s.key("z", false, true); + s.headless_win.request_frame(); + anyhow::ensure!( + s.doc_json()? == original && s.selection()? == sel, + "P3 undo failed to restore the range and document" + ); + } + println!( + "P3 two drag directions, continuous line boxes within blocks, clear margins and one undo per delete" + ); + mouse(s, "p0", 6, 2, false)?; + let sel = s.selection()?; + anyhow::ensure!( + sel.anchor.caret.utf16_offset == 4 && sel.focus.caret.utf16_offset == 9, + "P4 double click {sel:?}" + ); + mouse(s, "p0", 6, 3, false)?; + let sel = s.selection()?; + anyhow::ensure!( + sel.anchor.caret.utf16_offset == 0 && sel.focus.caret.utf16_offset == 9, + "P4 triple click {sel:?}" + ); + println!("P4 double-click 4..9, triple-click 0..9"); + Ok(()) +} + +fn peer_of(s: &HeadlessSession) -> Result { + let mut peer = PageDocSession::new(playground::HOME_PAGE_ID, 31)?; + peer.apply_remote_update_v1(&s.update(|v, _, _| { + v.document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap() + .encode_update_v1() + })??)?; + Ok(peer) +} + +fn receive(s: &HeadlessSession, bytes: &[u8]) -> Result<()> { + s.update(|v, _, cx| { + v.edit_document(cx, |d| { + d.workspace + .page_mut(playground::HOME_PAGE_ID) + .unwrap() + .apply_remote_update_v1(bytes) + }) + })??; + s.headless_win.request_frame(); + Ok(()) +} + +fn probe_input(s: &HeadlessSession) -> Result<()> { + s.set_texts(&["a"])?; + s.select("p0", 1)?; + s.headless_win.request_frame(); + let before = s.image()?; + let left = s.caret("p0", 1)?; + s.type_text("W")?; + s.headless_win.request_frame(); + let after = s.image()?; + let right = s.caret("p0", 2)?; + let x0 = f32::from(left.x).ceil() as u32 + 1; + let x1 = f32::from(right.x).floor() as u32; + let y = f32::from(left.y) as u32; + let ink = (x0..x1) + .flat_map(|x| (y - 8..y + 8).map(move |y| (x, y))) + .filter(|&(x, y)| before.get_pixel(x, y) != after.get_pixel(x, y)) + .count(); + anyhow::ensure!(ink > 0, "P5 next frame has no new glyph ink"); + println!("P5 {ink} changed glyph pixels after one frame"); + s.set_texts(&["ab"])?; + s.select("p0", 1)?; + s.headless_win.request_frame(); + let mut peer = peer_of(s)?; + let initial = s.doc_json()?; + let state = |s: &HeadlessSession| -> Result> { + Ok(s.update(|v, _, _| { + v.document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap() + .encode_state_vector_v1() + })??) + }; + let vector = state(s)?; + for pre in ["ni", "nihao"] { + s.update(|v, w, cx| v.replace_and_mark_text_in_range(None, pre, None, w, cx))?; + s.headless_win.request_frame(); + anyhow::ensure!( + state(s)? == vector && s.doc_json()? == initial, + "P6 preedit changed CRDT" + ); + } + let update = peer + .insert_text("p0", "prop:text", 0, "R", 10)? + .unwrap() + .update; + receive(s, &update)?; + let r = s.update(|v, w, cx| v.marked_text_range(w, cx))?; + anyhow::ensure!(r == Some(2..7), "P6 shifted preedit {r:?}"); + s.type_text("你好")?; + s.headless_win.request_frame(); + anyhow::ensure!( + s.doc_json()?["blocks"]["p0"]["prop:text"][0]["insert"] == "Ra你好b", + "P6 final placement" + ); + println!("P6 no preedit CRDT changes, remote insertion shifted commit to UTF-16 offset 2"); + s.set_texts(&[""])?; + s.select("p0", 0)?; + s.headless_win.request_frame(); + for text in ["a", "b", "c"] { + s.type_text(text)?; + s.platform.advance_clock(Duration::from_millis(100)); + } + s.platform.advance_clock(Duration::from_millis(600)); + s.type_text("d")?; + s.key("z", false, true); + s.headless_win.request_frame(); + anyhow::ensure!( + s.doc_json()?["blocks"]["p0"]["prop:text"][0]["insert"] == "abc", + "P7 late edit was merged" + ); + s.key("z", false, true); + s.headless_win.request_frame(); + anyhow::ensure!( + s.doc_json()?["blocks"]["p0"]["prop:text"] == serde_json::json!([]) + && s.selection()?.focus.caret.utf16_offset == 0, + "P7 early edits did not merge" + ); + s.key("z", true, true); + s.headless_win.request_frame(); + anyhow::ensure!( + s.selection()?.focus.caret.utf16_offset == 3, + "P7 redo caret" + ); + println!("P7 100ms typing merged, 600ms gap split, redo caret restored"); + s.set_texts(&["ab"])?; + s.select("p0", 1)?; + s.headless_win.request_frame(); + let mut peer = peer_of(s)?; + s.type_text("L")?; + let update = peer + .insert_text("p0", "prop:text", 0, "R", 10)? + .unwrap() + .update; + receive(s, &update)?; + s.key("z", false, true); + s.headless_win.request_frame(); + anyhow::ensure!( + s.doc_json()?["blocks"]["p0"]["prop:text"][0]["insert"] == "Rab" + && s.selection()?.focus.caret.utf16_offset == 2, + "P8 remote edit or local selection lost" + ); + println!("P8 remote R survived local undo, caret restored at offset 2"); + Ok(()) +} + +fn probe_anchor(s: &HeadlessSession) -> Result<()> { + s.set_texts(&["A reading paragraph."; 120])?; + s.select("p70", 4)?; + s.headless_win.request_frame(); + let before = s.caret("p70", 4)?; + let mut peer = peer_of(s)?; + let update = peer + .add_block( + "new", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Inserted above fold".into(), + }, + Some("note"), + Some(0), + 50, + )? + .unwrap() + .update; + receive(s, &update)?; + let shift = f32::from(s.caret("p70", 4)?.y - before.y).abs(); + anyhow::ensure!(shift <= 0.5, "P9 anchor moved {shift}px"); + println!("P9 remote insertion above fold, anchor shifted {shift:.3}px"); + Ok(()) +} + +fn replay_editing() -> Result<()> { + let mut reference = None; + for fps in [60, 120, 24, 7] { + let s = start_headless_session(800, 600, Default::default())?; + s.set_texts(&["draft", "second"])?; + s.select("p0", 5)?; + s.headless_win.request_frame(); + s.type_text(" one")?; + s.key("enter", false, false); + s.headless_win.request_frame(); + s.type_text("two")?; + s.headless_win.request_frame(); + for id in ["chrome.mode_switcher.edgeless", "chrome.mode_switcher.page"] { + let p = s.update(|_, w, _| { + let b = w.frame_snapshot().elements[id].bounds; + point(px(b.x + b.width / 2.), px(b.y + b.height / 2.)) + })?; + s.headless_win.simulate_click(p); + for _ in 0..fps { + s.platform + .advance_clock(Duration::from_secs_f64(1.0 / fps as f64)); + s.headless_win.request_frame(); + } + } + let frame = s.update(|_, w, _| serde_json::to_vec(w.frame_snapshot()))??; + let terminal = (frame, serde_json::to_vec(&s.doc_json()?)?); + if let Some(expected) = &reference { + anyhow::ensure!( + &terminal == expected, + "P10 terminal state differs at {fps}fps" + ); + } else { + reference = Some(terminal); + } + } + println!("P10 identical terminal frame and document bytes at 60/120/24/7 fps"); + Ok(()) +} + +fn render_editor(dir: PathBuf) -> Result<()> { + std::fs::create_dir_all(&dir)?; + for theme in [PlaygroundTheme::Light, PlaygroundTheme::Dark] { + let s = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme, + ..Default::default() + }, + )?; + s.headless_win.request_frame(); + let save = |name: &str| -> Result<()> { + s.headless_win.request_frame(); + let violations = s.update(|_, w, _| audit_frame_snapshot(w.frame_snapshot()))?; + anyhow::ensure!( + violations.is_empty(), + "editor render violations: {violations:?}" + ); + s.image()? + .save(dir.join(format!("{name}-{}.png", theme.as_str())))?; + Ok(()) + }; + mouse(&s, "showcase-h1", 4, 1, false)?; + save("caret")?; + mouse(&s, "showcase-quote", 15, 1, true)?; + save("selection")?; + s.select("showcase-h1", 9)?; + s.update(|v, w, cx| v.replace_and_mark_text_in_range(None, " nihao", None, w, cx))?; + save("preedit")?; + s.update(|v, w, cx| v.replace_text_in_range(None, " 你好", w, cx))?; + s.select("showcase-intro", 0)?; + s.type_text("- ")?; + anyhow::ensure!( + s.doc_json()?["blocks"][&s.selection()?.focus.block_id]["sys:flavour"] == "affine:list", + "list conversion" + ); + save("markdown")?; + } + Ok(()) +} +fn run_probes() -> Result<()> { + let s = start_headless_session(640, 720, Default::default())?; + probe_geometry(&s)?; + probe_selection(&s)?; + probe_input(&s)?; + probe_anchor(&s)?; + replay_editing() +} + fn main() -> Result<()> { let mut args = std::env::args().skip(1); let Some(cmd) = args.next() else { - bail!("usage: bs-harness [options]"); + bail!( + "usage: bs-harness [options]" + ); }; match cmd.as_str() { @@ -825,6 +1438,12 @@ fn main() -> Result<()> { } run_audit(snapshot.context("audit requires --snapshot ")?) } + "render-editor" => render_editor( + args.next() + .context("render-editor requires an output directory")? + .into(), + ), + "probes" => run_probes(), "fps-check" => run_fps_check(), "bench" => { let mut out_json = PathBuf::from("perf-metrics.json"); @@ -866,6 +1485,872 @@ fn main() -> Result<()> { mod tests { use super::*; #[test] + fn markdown_and_clipboard_use_the_document_editor_and_undo_stack() -> Result<()> { + use playground::clipboard::Slice; + let s = start_headless_session(800, 600, Default::default())?; + for (prefix, flavour, kind) in [ + ("# ", "affine:paragraph", "h1"), + ("###### ", "affine:paragraph", "h6"), + ("> ", "affine:paragraph", "quote"), + ("* ", "affine:list", "bulleted"), + ("2. ", "affine:list", "numbered"), + ("[x] ", "affine:list", "todo"), + ("```rust ", "affine:code", ""), + ("--- ", "affine:divider", ""), + ] { + s.set_texts(&[""])?; + s.select("p0", 0)?; + s.headless_win.request_frame(); + s.type_text(prefix)?; + let json = s.doc_json()?; + let block = + &json["blocks"][json["blocks"]["note"]["sys:children"][0].as_str().unwrap()]; + assert_eq!(block["sys:flavour"], flavour, "{prefix}"); + if !kind.is_empty() { + assert_eq!(block["prop:type"], kind, "{prefix}"); + } + s.key("z", false, true); + assert_eq!( + s.doc_json()?["blocks"]["p0"]["sys:flavour"], + "affine:paragraph" + ); + } + for delimiter in ["enter", "space"] { + s.set_texts(&[""])?; + s.select("p0", 0)?; + s.headless_win.request_frame(); + for ch in "```rust".chars() { + s.type_text(&ch.to_string())?; + } + if delimiter == "enter" { + s.key("enter", false, false); + } else { + s.type_text(" ")?; + } + let json = s.doc_json()?; + let block = + &json["blocks"][json["blocks"]["note"]["sys:children"][0].as_str().unwrap()]; + assert_eq!(block["prop:language"], "rust"); + assert_eq!(block["prop:text"], serde_json::json!([])); + } + s.set_texts(&[""])?; + s.select("p0", 0)?; + s.headless_win.request_frame(); + for ch in "`code`".chars() { + s.type_text(&ch.to_string())?; + } + assert_eq!( + s.doc_json()?["blocks"]["p0"]["prop:text"], + serde_json::json!([{"insert":"code","attributes":{"code":true}}]) + ); + s.set_texts(&[""])?; + s.select("p0", 0)?; + s.headless_win.request_frame(); + let slice = Slice::from_html( + "

Hello

  1. World
x\ny
", + ) + .unwrap(); + s.update(|v, w, cx| v.paste(slice.item(), w, cx))?; + let json = s.doc_json()?; + let blocks = &json["blocks"]; + let ids = blocks["note"]["sys:children"].as_array().unwrap(); + assert_eq!(ids.len(), 3); + assert_eq!(blocks["p0"]["prop:type"], "h3"); + assert_eq!(blocks["p0"]["prop:text"][0]["attributes"]["italic"], true); + assert_eq!(blocks[ids[1].as_str().unwrap()]["prop:type"], "numbered"); + assert_eq!( + blocks[ids[2].as_str().unwrap()]["prop:text"][0]["insert"], + "x\ny" + ); + s.key("z", false, true); + s.headless_win.request_frame(); + assert_eq!( + s.doc_json()?["blocks"]["note"]["sys:children"], + serde_json::json!(["p0"]) + ); + Ok(()) + } + + #[test] + fn composing_over_a_directional_range_changes_only_the_preview_until_commit() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + for reverse in [false, true] { + s.set_texts(&["one", "middle", "end"])?; + let original = s.doc_json()?; + let (a, b) = if reverse { ("p2", "p0") } else { ("p0", "p2") }; + mouse(&s, a, 1, 1, false)?; + mouse(&s, b, 1, 1, true)?; + let range = s.selection()?; + for cancel_with_commit in [false, true] { + s.update(|v, w, cx| { + v.replace_and_mark_text_in_range(Some(1..1), "ni", None, w, cx) + })?; + s.headless_win.request_frame(); + assert_eq!(s.doc_json()?, original); + s.update(|v, w, cx| { + let layout = v.flow_layout().unwrap(); + assert_eq!(layout.block("p0").unwrap().body.plain, "onind"); + assert!(layout.block("p1").is_none() && layout.block("p2").is_none()); + assert_eq!(v.marked_text_range(w, cx), Some(1..3)); + if cancel_with_commit { + v.replace_text_in_range(None, "", w, cx); + } else { + v.replace_and_mark_text_in_range(None, "", None, w, cx); + } + assert!(v.marked_text_range(w, cx).is_none()); + assert!( + !v.document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap() + .can_undo() + ); + })?; + assert_eq!(s.selection()?, range); + assert_eq!(s.doc_json()?, original); + } + s.update(|v, w, cx| { + v.replace_and_mark_text_in_range(Some(1..1), "nihao", None, w, cx) + })?; + s.headless_win.request_frame(); + s.type_text("你好")?; + assert_eq!( + s.doc_json()?["blocks"]["p0"]["prop:text"][0]["insert"], + "o你好nd" + ); + s.key("z", false, true); + assert_eq!(s.doc_json()?, original); + assert_eq!(s.selection()?, range); + } + Ok(()) + } + + #[test] + fn typing_inherits_marks_with_explicit_overrides_and_unmarked_edges() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + for (key, offset, toggle, ime, expected) in [ + ("bold", 1, false, false, true), + ("bold", 1, false, true, true), + ("bold", 1, true, false, false), + ("bold", 0, false, false, false), + ("link", 1, false, false, true), + ("link", 2, false, true, false), + ("code", 1, false, false, true), + ("code", 2, false, false, false), + ] { + let mut doc = probe_doc(["ab"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + let value = if key == "link" { + y_octo::Any::String("https://example.org".into()) + } else { + y_octo::Any::True + }; + page.format_text( + "p0", + "prop:text", + 0, + 2, + y_octo::TextAttributes::from([(key.into(), value.clone())]), + 1, + )?; + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + s.select("p0", offset)?; + if toggle { + s.key("b", false, true); + } + if ime { + s.update(|v, w, cx| v.replace_and_mark_text_in_range(None, "x", None, w, cx))?; + } + s.type_text("X")?; + let json = s.doc_json()?; + let run = json["blocks"]["p0"]["prop:text"] + .as_array() + .unwrap() + .iter() + .find(|v| v["insert"].as_str().unwrap().contains('X')) + .unwrap(); + assert_eq!( + run["attributes"].get(key).is_some(), + expected, + "{key} {offset} {toggle} {ime}" + ); + } + Ok(()) + } + + #[test] + fn joining_into_a_nested_endpoint_preserves_later_subtrees() -> Result<()> { + use playground::clipboard::Slice; + let s = start_headless_session(800, 600, Default::default())?; + let mut doc = probe_doc(["Ax", "B"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + for (id, parent) in [("B1", "p1"), ("B2", "p1"), ("B2a", "B2"), ("B3", "p1")] { + page.add_block( + id, + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: id.into(), + }, + Some(parent), + None, + 1, + )?; + } + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + let original = s.doc_json()?; + mouse(&s, "p0", 1, 1, false)?; + mouse(&s, "B1", 1, 1, true)?; + let selection = s.selection()?; + s.key("c", false, true); + let item = s + .update(|_, _, cx| cx.read_from_clipboard())? + .context("copied items")?; + let slice = Slice::from_item(&item).context("rich slice")?; + assert_eq!(slice.content.len(), 2); + assert_eq!(slice.content[0].id, "p0"); + assert_eq!(slice.content[1].id, "p1"); + assert_eq!(slice.content[1].children.len(), 1); + assert_eq!(slice.content[1].children[0].id, "B1"); + assert!(slice.content[1].children[0].children.is_empty()); + s.update(|v, w, cx| v.replace_and_mark_text_in_range(None, "ni", None, w, cx))?; + s.headless_win.request_frame(); + s.update(|v, w, cx| { + let layout = v.flow_layout().unwrap(); + let ids: Vec<_> = layout.blocks.iter().map(|b| b.block_id.as_str()).collect(); + assert_eq!(ids, ["root", "p0", "B2", "B2a", "B3"]); + v.replace_text_in_range(None, "", w, cx); + })?; + assert_eq!(s.doc_json()?, original); + s.key("backspace", false, false); + let blocks = &s.doc_json()?["blocks"]; + assert_eq!(blocks["p0"]["prop:text"][0]["insert"], "A1"); + assert_eq!( + blocks["p0"]["sys:children"], + serde_json::json!(["B2", "B3"]) + ); + assert_eq!(blocks["B2"]["sys:children"], serde_json::json!(["B2a"])); + assert_eq!(blocks["note"]["sys:children"], serde_json::json!(["p0"])); + s.key("z", false, true); + assert_eq!(s.doc_json()?, original); + assert_eq!(s.selection()?, selection); + Ok(()) + } + + #[test] + fn markdown_list_order_starts_at_the_typed_number_and_stays_local() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + s.set_texts(&["Above", "", "Below"])?; + s.select("p1", 0)?; + s.type_text("5. ")?; + let first = s.selection()?.focus.block_id; + assert_eq!(s.doc_json()?["blocks"][&first]["prop:order"], 5); + s.type_text("item")?; + s.key("enter", false, false); + let second = s.selection()?.focus.block_id; + assert_eq!(s.doc_json()?["blocks"][&second]["prop:order"], 6); + for id in ["p0", "p2"] { + s.select(id, 1)?; + s.key("enter", false, false); + let blocks = &s.doc_json()?["blocks"]; + assert_eq!(blocks[&first]["prop:order"], 5); + assert_eq!(blocks[&second]["prop:order"], 6); + } + Ok(()) + } + + fn text_block(id: &str, kind: ParagraphType) -> BlockSpec { + BlockSpec::Paragraph { + paragraph_type: kind, + text: id.to_owned(), + } + } + + fn select_across(s: &HeadlessSession, start: &str, end: &str) -> Result<()> { + s.update(|v, w, cx| { + v.select_document_range( + DocumentSelection { + anchor: DocPoint::new(start, 1), + focus: DocPoint::new(end, 1), + }, + w, + cx, + ) + }) + } + + #[test] + fn collapsed_endpoint_children_survive_preview_and_delete() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + let mut doc = probe_doc(["A"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + page.add_block( + "T", + BlockSpec::List { + list_type: blocksuite_playground_doc::schema::ListType::Toggle, + text: "Toggle".into(), + checked: false, + order: None, + }, + Some("note"), + None, + 0, + )?; + page.set_block_prop( + "T", + "prop:collapsed", + y_octo::SessionValue::Any(y_octo::Any::True), + 0, + )?; + for id in ["T1", "T2"] { + page.add_block(id, text_block(id, ParagraphType::Text), Some("T"), None, 0)?; + } + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + let original = s.doc_json()?; + select_across(&s, "p0", "T")?; + s.update(|v, w, cx| v.replace_and_mark_text_in_range(None, "ni", None, w, cx))?; + s.headless_win.request_frame(); + s.update(|v, w, cx| { + let l = v.flow_layout().unwrap(); + assert_eq!( + l.blocks + .iter() + .map(|b| b.block_id.as_str()) + .collect::>(), + ["root", "p0", "T1", "T2"] + ); + v.replace_text_in_range(None, "", w, cx); + })?; + assert_eq!(s.doc_json()?, original); + s.key("backspace", false, false); + assert_eq!( + s.doc_json()?["blocks"]["p0"]["sys:children"], + serde_json::json!(["T1", "T2"]) + ); + s.key("z", false, true); + assert_eq!(s.doc_json()?, original); + Ok(()) + } + + #[test] + fn cut_includes_a_hidden_sibling_before_the_endpoint() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + let mut doc = probe_doc(["Aa", "B"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + for (id, kind) in [ + ("H", ParagraphType::H1), + ("X", ParagraphType::Text), + ("E", ParagraphType::H1), + ("S", ParagraphType::Text), + ] { + page.add_block(id, text_block(id, kind), Some("p1"), None, 0)?; + } + page.set_block_prop( + "H", + "prop:collapsed", + y_octo::SessionValue::Any(y_octo::Any::True), + 0, + )?; + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + assert!(s.update(|v, _, _| v.flow_layout().unwrap().block("X").is_none())?); + let original = s.doc_json()?; + select_across(&s, "p0", "E")?; + s.key("x", false, true); + let cut = s.doc_json()?; + assert!(cut["blocks"].get("X").is_none()); + assert_eq!( + cut["blocks"]["p0"]["sys:children"], + serde_json::json!(["S"]) + ); + let item = s + .update(|_, _, cx| cx.read_from_clipboard())? + .context("cut clipboard")?; + let slice = playground::clipboard::Slice::from_item(&item).context("cut slice")?; + assert_eq!( + slice.content[1] + .children + .iter() + .map(|b| b.id.as_str()) + .collect::>(), + ["H", "X", "E"] + ); + s.key("v", false, true); + let pasted = s.doc_json()?; + let blocks = &pasted["blocks"]; + let parent = blocks["note"]["sys:children"][1].as_str().unwrap(); + let restored = blocks[parent]["sys:children"][1].as_str().unwrap(); + assert_eq!( + blocks[restored]["prop:text"], + original["blocks"]["X"]["prop:text"] + ); + s.key("z", false, true); + assert_eq!(s.doc_json()?, cut); + s.key("z", false, true); + assert_eq!(s.doc_json()?, original); + Ok(()) + } + + #[test] + fn page_title_and_cross_note_cuts_preserve_page_containers() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + let mut doc = probe_doc(["One"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + page.add_block("surface", BlockSpec::Surface, Some("root"), Some(0), 0)?; + for (note, id) in [ + ("canvas", "canvas-text"), + ("hidden", "hidden-text"), + ("note2", "Two"), + ] { + page.add_block(note, BlockSpec::Note { xywh: None }, Some("root"), None, 0)?; + page.add_block(id, text_block(id, ParagraphType::Text), Some(note), None, 0)?; + } + page.set_block_prop( + "canvas", + "prop:displayMode", + y_octo::SessionValue::Any(y_octo::Any::String("edgeless".into())), + 0, + )?; + page.set_block_prop( + "hidden", + "prop:hidden", + y_octo::SessionValue::Any(y_octo::Any::True), + 0, + )?; + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + let original = s.doc_json()?; + for (start, end) in [("root", "p0"), ("p0", "Two")] { + select_across(&s, start, end)?; + s.key("x", false, true); + let cut = s.doc_json()?; + for id in ["surface", "canvas", "canvas-text", "hidden", "hidden-text"] { + assert_eq!(cut["blocks"][id], original["blocks"][id]); + } + assert_eq!( + cut["blocks"]["root"]["sys:children"], + serde_json::json!(["surface", "note", "canvas", "hidden", "note2"]) + ); + for note in ["note", "note2"] { + assert_eq!(cut["blocks"][note]["sys:id"], note); + } + let item = s.update(|_, _, cx| cx.read_from_clipboard())?.unwrap(); + let slice = playground::clipboard::Slice::from_item(&item).unwrap(); + assert_eq!( + slice + .content + .iter() + .map(|b| b.id.as_str()) + .collect::>(), + [start, end] + ); + assert!(slice.content.iter().all(|b| b.children.is_empty())); + s.key("z", false, true); + assert_eq!(s.doc_json()?, original); + } + Ok(()) + } + + #[test] + fn code_range_lifts_following_subtrees_as_siblings() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + let mut doc = probe_doc(["B", "C"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + page.add_block( + "A", + BlockSpec::Code { + text: "Code".into(), + language: None, + caption: String::new(), + }, + Some("note"), + Some(0), + 0, + )?; + for id in ["B1", "B2"] { + page.add_block(id, text_block(id, ParagraphType::Text), Some("p0"), None, 0)?; + } + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + let original = s.doc_json()?; + select_across(&s, "A", "B1")?; + s.update(|v, w, cx| v.replace_and_mark_text_in_range(None, "x", None, w, cx))?; + s.headless_win.request_frame(); + s.update(|v, w, cx| { + let l = v.flow_layout().unwrap(); + assert_eq!(l.block("B2").unwrap().x, l.block("p1").unwrap().x); + v.replace_text_in_range(None, "", w, cx); + })?; + s.key("backspace", false, false); + let cut = s.doc_json()?; + assert_eq!( + cut["blocks"]["note"]["sys:children"], + serde_json::json!(["A", "B2", "p1"]) + ); + assert_eq!(cut["blocks"]["A"]["sys:children"], serde_json::json!([])); + s.key("z", false, true); + assert_eq!(s.doc_json()?, original); + Ok(()) + } + + #[test] + fn zero_based_markdown_and_list_only_order_correction() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + s.set_texts(&["Item", "Break", "Later"])?; + s.select("p0", 0)?; + s.type_text("0. ")?; + let first = s.selection()?.focus.block_id; + let numbered = s.doc_json()?; + assert_eq!(numbered["blocks"][&first]["prop:type"], "numbered"); + assert_eq!(numbered["blocks"][&first]["prop:order"], 0); + s.select(&first, 4)?; + s.key("enter", false, false); + let second = s.selection()?.focus.block_id; + assert_eq!(s.doc_json()?["blocks"][&first]["prop:order"], 1); + assert_eq!(s.doc_json()?["blocks"][&second]["prop:order"], 2); + s.select("p2", 0)?; + s.type_text("5. ")?; + let fifth = s.selection()?.focus.block_id; + s.select(&fifth, 5)?; + s.key("enter", false, false); + let sixth = s.selection()?.focus.block_id; + s.select("p1", 0)?; + s.key("tab", false, false); + let indented = s.doc_json()?; + assert_eq!( + indented["blocks"][&second]["sys:children"], + serde_json::json!(["p1"]) + ); + assert_eq!(indented["blocks"][&fifth]["prop:order"], 5); + assert_eq!(indented["blocks"][&sixth]["prop:order"], 6); + s.set_texts(&["One", "Two", "Three"])?; + let mut ids = Vec::new(); + for id in ["p0", "p1", "p2"] { + s.select(id, 0)?; + s.type_text("1. ")?; + ids.push(s.selection()?.focus.block_id); + } + s.select(&ids[1], 0)?; + s.key("backspace", false, false); + assert_eq!(s.doc_json()?["blocks"][&ids[2]]["prop:order"], 3); + assert_eq!( + s.doc_json()?["blocks"][&s.selection()?.focus.block_id]["sys:flavour"], + "affine:paragraph" + ); + Ok(()) + } + + #[test] + fn paste_preserves_concurrent_suffix_deletion_and_relative_positions() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + s.set_texts(&["abcd"])?; + s.select("p0", 1)?; + let mut peer = peer_of(&s)?; + let suffix = peer.capture_selection_snapshot("p0", 1, "p0", 3)?; + let initial = peer.encode_state_vector_v1()?; + let remote = peer + .remove_text("p0", "prop:text", 2, 1, 1)? + .unwrap() + .update; + s.update(|v, w, cx| v.paste(ui::ClipboardItem::new_string("X".into()), w, cx))?; + let local = s.update(|v, _, _| { + v.document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap() + .encode_diff_v1(&initial) + })??; + receive(&s, &remote)?; + peer.apply_remote_update_v1(&local)?; + assert_eq!(s.doc_json()?, peer.export_doc_json()?); + assert_eq!(peer.read_editable_text("p0")?.0.plain, "aXbd"); + let pos = peer.resolve_selection_snapshot(&suffix)?.unwrap(); + assert_eq!((pos.anchor.1, pos.focus.1), (2, 3)); + assert_eq!( + s.update(|v, _, _| v + .document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap() + .resolve_selection_snapshot(&suffix))??, + Some(pos) + ); + Ok(()) + } + + #[test] + fn typing_and_ime_after_a_reference_leave_exactly_one_chip() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + for (input, ime) in [(" ", false), ("好", true)] { + let mut doc = probe_doc([" "])?; + let reference = serde_json::json!({"type":"LinkedPage","pageId":"dest"}); + let attrs = y_octo::TextAttributes::from([( + "reference".into(), + serde_json::from_value(reference.clone())?, + )]); + doc.workspace + .page_mut(playground::HOME_PAGE_ID) + .unwrap() + .format_text("p0", "prop:text", 0, 1, attrs, 1)?; + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + s.select("p0", 1)?; + if ime { + s.update(|v, w, cx| v.replace_and_mark_text_in_range(None, "hao", None, w, cx))?; + } + s.type_text(input)?; + assert_eq!( + s.doc_json()?["blocks"]["p0"]["prop:text"], + serde_json::json!([{"insert":" ","attributes":{"reference":reference}},{"insert":input}]) + ); + } + Ok(()) + } + + #[test] + fn image_survives_cross_block_cut_paste_and_undo() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + let mut doc = probe_doc(["one", "end"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + page.add_block( + "pic", + BlockSpec::Image { + source_id: "digest".into(), + caption: "caption".into(), + width: 80., + height: 40., + xywh: Some("[1,2,80,40]".into()), + }, + Some("note"), + Some(1), + 1, + )?; + let shared_text = |text: &str| { + y_octo::SessionValue::Text(vec![y_octo::TextDeltaOp::Insert { + insert: y_octo::TextInsert::Text(text.into()), + format: None, + }]) + }; + page.add_raw_block( + "vendor", + "custom:widget", + 4, + vec![ + ("prop:caption".into(), shared_text("Caption")), + ( + "prop:meta".into(), + y_octo::SessionValue::Map(vec![("label".into(), shared_text("Label"))]), + ), + ], + Some("pic"), + None, + 2, + )?; + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + let original = s.doc_json()?; + s.update(|v, w, cx| { + v.select_document_range( + DocumentSelection { + anchor: DocPoint::new("p0", 1), + focus: DocPoint::new("p1", 1), + }, + w, + cx, + ) + })?; + s.key("x", false, true); + s.headless_win.request_frame(); + let cut = s.doc_json()?; + assert!(cut["blocks"].get("pic").is_none()); + let item = s + .update(|_, _, cx| cx.read_from_clipboard())? + .context("cut clipboard item")?; + let slice = playground::clipboard::Slice::from_item(&item).context("snapshot")?; + let html = + playground::clipboard::Slice::from_html(&slice.html()).context("HTML snapshot")?; + assert_eq!(slice, html); + s.update(|v, w, cx| v.paste(html.item(), w, cx))?; + s.headless_win.request_frame(); + let restored = s.doc_json()?; + let ids = restored["blocks"]["note"]["sys:children"] + .as_array() + .unwrap(); + assert_eq!(ids.len(), 3); + let image = &restored["blocks"][ids[1].as_str().unwrap()]; + for key in [ + "sys:flavour", + "sys:version", + "prop:sourceId", + "prop:caption", + "prop:width", + "prop:height", + "prop:xywh", + ] { + assert_eq!(image[key], original["blocks"]["pic"][key], "{key}"); + } + let custom_id = image["sys:children"][0].as_str().unwrap(); + let nested = &restored["blocks"][custom_id]; + assert_eq!(nested["sys:flavour"], "custom:widget"); + assert_eq!(nested["sys:version"], 4); + let mut replica = peer_of(&s)?; + let block = y_octo::TypePath::root("blocks").key(custom_id); + for (parent, key, expected) in [ + (block.clone(), "prop:caption", "Caption"), + (block.key("prop:meta"), "label", "Label"), + ] { + let value = replica + .inner() + .get_map_value(&y_octo::TypeTarget::Path(parent), key)?; + let Some(y_octo::SessionReadValue::Text(identity)) = value else { + panic!("expected shared text at {key}") + }; + let target = y_octo::TypeTarget::Identity(identity); + replica.inner_mut().text_insert(&target, 0, "!")?; + assert_eq!( + replica.inner().read_text_string(&target)?, + format!("!{expected}") + ); + } + s.key("z", false, true); + assert_eq!(s.doc_json()?, cut); + s.key("z", false, true); + assert_eq!(s.doc_json()?, original); + Ok(()) + } + + #[test] + fn multiline_paste_into_a_title_without_a_visible_note_preserves_peer_and_undo() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + let mut doc = probe_doc(["hidden"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + page.inner_mut() + .begin_tx(y_octo::SessionTxOrigin::Untracked)?; + page.set_block_prop( + "note", + "prop:hidden", + y_octo::SessionValue::Any(y_octo::Any::True), + 1, + )?; + page.inner_mut().commit_tx()?; + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + s.select("root", 2)?; + let peer = peer_of(&s)?; + let before = peer.export_doc_json()?; + let vector = peer.encode_state_vector_v1()?; + let original_diff = s.update(|v, _, _| { + v.document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap() + .encode_diff_v1(&vector) + })??; + s.update(|v, w, cx| v.paste(ui::ClipboardItem::new_string("A\nB".into()), w, cx))?; + assert_eq!(s.doc_json()?, before); + s.update(|v, _, _| { + let page = v + .document() + .workspace + .page(playground::HOME_PAGE_ID) + .unwrap(); + assert!(!page.can_undo()); + assert_eq!(page.encode_diff_v1(&vector).unwrap(), original_diff); + })?; + Ok(()) + } + + #[test] + fn title_edits_paste_merge_and_history_update_workspace_metadata() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + s.set_texts(&["body"])?; + let title = || { + s.update(|v, _, _| { + v.document().workspace.list_pages().unwrap()[0] + .title + .clone() + }) + }; + s.select("root", 7)?; + s.type_text("!")?; + assert_eq!(title()?, "Editing!"); + s.update(|v, w, cx| v.paste(ui::ClipboardItem::new_string(" X".into()), w, cx))?; + assert_eq!(title()?, "Editing! X"); + s.select("p0", 0)?; + s.key("backspace", false, false); + assert_eq!(title()?, "Editing! Xbody"); + assert_eq!( + s.doc_json()?["blocks"]["note"]["sys:children"], + serde_json::json!(["p0"]) + ); + s.key("z", false, true); + assert_eq!(title()?, "Editing! X"); + s.key("z", true, true); + assert_eq!(title()?, "Editing! Xbody"); + Ok(()) + } + + #[test] + fn divider_and_fence_keep_trailing_text_and_place_children_at_the_right_level() -> Result<()> { + let s = start_headless_session(800, 600, Default::default())?; + for trigger in ["---", "***", "___", "```c++"] { + let mut doc = probe_doc(["suffix"])?; + let page = doc.workspace.page_mut(playground::HOME_PAGE_ID).unwrap(); + page.add_block( + "child", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "nested".into(), + }, + Some("p0"), + None, + 1, + )?; + s.update(|v, _, cx| v.set_document(doc, cx))?; + s.headless_win.request_frame(); + s.select("p0", 0)?; + s.type_text(trigger)?; + assert_eq!( + s.doc_json()?["blocks"]["p0"]["sys:flavour"], + "affine:paragraph" + ); + s.type_text(" ")?; + let json = s.doc_json()?; + let b = &json["blocks"]; + let ids = b["note"]["sys:children"].as_array().unwrap(); + let new = ids[0].as_str().unwrap(); + if trigger.starts_with('`') { + assert_eq!(b[new]["sys:flavour"], "affine:code"); + assert_eq!(b[new]["prop:language"], "c++"); + assert_eq!( + b[ids[1].as_str().unwrap()]["prop:text"][0]["insert"], + "suffix" + ); + assert_eq!(ids[2], "child"); + assert!(b.get("p0").is_none()); + assert_eq!(s.selection()?.focus, DocPoint::new(new, 0)); + } else { + assert_eq!(b[new]["sys:flavour"], "affine:divider"); + assert_eq!(ids[1], "p0"); + assert_eq!(b["p0"]["sys:children"], serde_json::json!(["child"])); + assert_eq!(s.selection()?.focus, DocPoint::new("p0", 0)); + } + s.key("z", false, true); + assert_eq!( + s.doc_json()?["blocks"]["note"]["sys:children"], + serde_json::json!(["p0"]) + ); + } + Ok(()) + } + + #[test] + fn document_editing_probes() { + run_probes().unwrap(); + } + #[test] fn rich_sample_writes_two_reproducible_pngs() { let dir = tempfile::tempdir().unwrap(); let plain = dir.path().join("plain.png"); diff --git a/blocksuite/native-playground/crates/playground/src/block_flow.rs b/blocksuite/native-playground/crates/playground/src/block_flow.rs index 7f66c70940..8c5ce2a615 100644 --- a/blocksuite/native-playground/crates/playground/src/block_flow.rs +++ b/blocksuite/native-playground/crates/playground/src/block_flow.rs @@ -12,7 +12,7 @@ //! out and painted by [`RichParagraph`]; single-style labels use the plain [`InlineLayout`]. use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, BTreeSet, HashMap}, hash::{Hash, Hasher}, rc::Rc, sync::Arc, @@ -279,6 +279,7 @@ pub enum InlineAlign { Right, } +#[derive(Clone)] struct InlinePiece { line: usize, x: f32, @@ -866,6 +867,62 @@ pub struct FlowBlock { } impl FlowBlock { + pub fn editable(&self) -> bool { + matches!( + self.body.kind, + FlowKind::Title | FlowKind::Paragraph(_) | FlowKind::List(_) | FlowKind::Code + ) + } + + pub fn caret_rect(&self, caret: CaretPosition) -> Option { + let text = self.body.text.as_ref()?; + let height = text.layout.line_height(); + let (x, line) = match &text.layout { + FlowTextLayout::Rich(rich) => { + let (line, x) = rich.caret_line_and_x(caret); + (f32::from(x), line) + } + FlowTextLayout::Plain(plain) => plain.caret(caret.utf16_offset as usize), + }; + Some(FlowRect::new( + self.x + text.x + x, + self.y + text.y + line as f32 * height, + 1.0, + height, + )) + } + + pub fn hit_text(&self, x: f32, y: f32) -> Option { + let text = self.body.text.as_ref()?; + let x = x - self.x - text.x; + let y = y - self.y - text.y; + Some(match &text.layout { + FlowTextLayout::Rich(rich) => rich.hit_test(point(px(x), px(y))), + FlowTextLayout::Plain(plain) => { + let line = + ((y / plain.line_height).floor().max(0.0) as usize).min(plain.line_count - 1); + let index = crate::rich_text::TextBiIndex::new(&self.body.plain); + let mut offset = 0; + let mut best = (usize::MAX, f32::MAX, 0); + loop { + let (at, row) = plain.caret(offset as usize); + let distance = (line.abs_diff(row), (at - x).abs(), offset); + if distance < best { + best = distance; + } + if offset == index.utf16_len() { + break; + } + offset = index.next_grapheme_utf16(offset); + } + CaretPosition { + utf16_offset: best.2, + affinity: WrapAffinity::Downstream, + } + } + }) + } + pub fn rect(&self) -> FlowRect { FlowRect::new(self.x, self.y, self.body.width, self.body.height) } @@ -903,6 +960,17 @@ pub struct FlowLayout { } impl FlowLayout { + /// Hit-test document coordinates against the editable text, including margins + /// between blocks while dragging. Ties go to the earlier block. + pub fn hit_document(&self, x: f32, y: f32) -> Option<(String, CaretPosition)> { + let block = self.blocks.iter().filter(|b| b.editable()).min_by(|a, b| { + let distance = + |block: &FlowBlock| (block.y - y).max(y - block.rect().bottom()).max(0.0); + distance(a).total_cmp(&distance(b)) + })?; + Some((block.block_id.clone(), block.hit_text(x, y)?)) + } + pub fn block(&self, block_id: &str) -> Option<&FlowBlock> { self.blocks.iter().find(|block| block.block_id == block_id) } @@ -915,6 +983,7 @@ pub struct BlockFlow { } struct FlowPass<'a> { + dirty: Option<&'a BTreeSet>, input: &'a FlowInput<'a>, palette: Palette, window: &'a Window, @@ -935,7 +1004,19 @@ impl BlockFlow { /// Lay the snapshot out in world space, reusing the body of every block whose content, /// width and theme did not change since the previous pass. pub fn layout(&mut self, input: &FlowInput<'_>, window: &Window) -> FlowLayout { + self.layout_changed(input, window, None) + } + + /// The caller may identify text-only changes since the last pass when the environment + /// and topology are identical. All other passes fingerprint each block normally. + pub(crate) fn layout_changed( + &mut self, + input: &FlowInput<'_>, + window: &Window, + dirty: Option<&BTreeSet>, + ) -> FlowLayout { let mut pass = FlowPass { + dirty, input, palette: input.theme.palette(), window, @@ -972,6 +1053,7 @@ impl BlockFlow { // Each note is its own flow root: margins never collapse across notes. pass.pending_margin = None; match &child.content { + BlockContent::Note { hidden: true, .. } => continue, BlockContent::Note { .. } => { pass.flow(&child.children, 0.0, 0, BlockAlign::Left) } @@ -1014,6 +1096,14 @@ impl<'a> FlowPass<'a> { content: &dyn std::fmt::Debug, build: impl FnOnce(&mut Self) -> BlockBody, ) -> Rc { + if self.dirty.is_some_and(|ids| !ids.contains(key)) + && let Some((id, cached)) = self.previous.remove_entry(key) + { + self.stats.reused += 1; + let body = cached.1.clone(); + self.next.insert(id, cached); + return body; + } let mut hasher = std::collections::hash_map::DefaultHasher::new(); format!("{content:?}").hash(&mut hasher); self.input.width.to_bits().hash(&mut hasher); @@ -1545,7 +1635,9 @@ impl<'a> FlowPass<'a> { let mut prims = Vec::new(); let mut y = pad_y; - let mut first_line: Option> = None; + let mut code_pieces = Vec::new(); + let mut line_offset = 0; + let mut source_offset = 0; for (index, line) in text.split('\n').enumerate() { let layout = self.plain_inline( line, @@ -1571,7 +1663,27 @@ impl<'a> FlowPass<'a> { clip: None, }); let height = layout.height(); - first_line.get_or_insert_with(|| layout.clone()); + // Empty lines have a caret stop at x=0 even when no glyph was shaped. + if layout.pieces.is_empty() { + code_pieces.push(InlinePiece { + line: line_offset, + x: 0.0, + visible_width: 0.0, + baseline_shift: 0.0, + shaped: shape(self.window, "", &code_style), + source_start: source_offset, + source_len: 0, + }); + } + for piece in &layout.pieces { + code_pieces.push(InlinePiece { + line: line_offset + piece.line, + source_start: source_offset + piece.source_start, + ..piece.clone() + }); + } + line_offset += layout.line_count; + source_offset += line.encode_utf16().count() + 1; prims.push(Prim::Text { x: code_x, y, @@ -1625,10 +1737,16 @@ impl<'a> FlowPass<'a> { margin_bottom: CARD_BLOCK_MARGIN, plain: text.to_string(), prims, - text: first_line.map(|layout| FlowText { + text: Some(FlowText { x: code_x, y: pad_y, - layout: FlowTextLayout::Plain(layout), + layout: FlowTextLayout::Plain(Rc::new(InlineLayout { + pieces: code_pieces, + line_count: line_offset, + line_height, + width: code_width, + baseline: baseline_in_line(line_height, &shape(self.window, "Ag", &code_style)), + })), }), prefix: None, }; diff --git a/blocksuite/native-playground/crates/playground/src/clipboard.rs b/blocksuite/native-playground/crates/playground/src/clipboard.rs new file mode 100644 index 0000000000..74fa455b8e --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/clipboard.rs @@ -0,0 +1,815 @@ +//! BlockSuite's slice snapshot and its two textual clipboard representations. +use std::collections::BTreeMap; + +use blocksuite_playground_doc::{ + read::BlockNode, + schema::{BlockSpec, ListType, ParagraphType}, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use ui::ClipboardItem; +use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert}; + +pub const SNAPSHOT_MIME: &str = "application/x-blocksuite-snapshot"; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Slice { + #[serde(rename = "type")] + pub kind: String, + pub workspace_id: String, + pub page_id: String, + pub content: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SliceBlock { + #[serde(rename = "type")] + pub kind: String, + pub id: String, + pub flavour: String, + #[serde(default)] + pub version: Option, + pub props: BTreeMap, + pub children: Vec, +} + +fn text_value(delta: &[TextDeltaOp]) -> Value { + let ops: Vec<_> = delta + .iter() + .filter_map(|op| { + let TextDeltaOp::Insert { insert, format } = op else { + return None; + }; + let insert = match insert { + TextInsert::Text(s) => json!(s), + TextInsert::Embed(v) if v.len() == 1 => json!(&v[0]), + TextInsert::Embed(v) => json!(v), + }; + let mut out = json!({"insert":insert}); + if let Some(attrs) = format + && !attrs.is_empty() + { + out["attributes"] = json!(attrs); + } + Some(out) + }) + .collect(); + json!({"$blocksuite:internal:text$":true,"delta":ops}) +} + +fn decode_text_value(value: &Value) -> blocksuite_playground_doc::DocResult> { + use blocksuite_playground_doc::DocError; + let ops = value["delta"] + .as_array() + .ok_or_else(|| DocError::InvalidState("missing clipboard text delta".into()))?; + ops.iter() + .map(|op| { + let raw = op + .get("insert") + .ok_or_else(|| DocError::InvalidState("missing clipboard insert".into()))?; + let insert = match raw { + Value::String(text) => TextInsert::Text(text.clone()), + embed => TextInsert::Embed(vec![ + serde_json::from_value(embed.clone()) + .map_err(|e| DocError::InvalidState(e.to_string()))?, + ]), + }; + let format = op + .get("attributes") + .map(|attrs| serde_json::from_value(attrs.clone())) + .transpose() + .map_err(|e| DocError::InvalidState(e.to_string()))?; + Ok(TextDeltaOp::Insert { insert, format }) + }) + .collect() +} + +impl SliceBlock { + pub(crate) fn keep_selected( + node: &BlockNode, + selected: &mut BTreeMap, + out: &mut Vec, + ) { + if let Some(mut item) = selected.remove(&node.id) { + for child in &node.children { + Self::keep_selected(child, selected, &mut item.children); + } + out.push(item); + } else { + for child in &node.children { + Self::keep_selected(child, selected, out); + } + } + } + + pub(crate) fn walk(&self) -> impl Iterator { + let mut stack = vec![self]; + std::iter::from_fn(move || { + let b = stack.pop()?; + stack.extend(b.children.iter().rev()); + Some(b) + }) + } + + pub fn from_node( + node: &BlockNode, + exported: serde_json::Map, + delta: &[TextDeltaOp], + ) -> Self { + let mut props: BTreeMap<_, _> = exported + .into_iter() + .filter_map(|(k, v)| Some((k.strip_prefix("prop:")?.to_owned(), v))) + .collect(); + let key = if node.flavour == "affine:page" { + "title" + } else { + "text" + }; + if matches!( + node.flavour.as_str(), + "affine:page" | "affine:paragraph" | "affine:list" | "affine:code" + ) && props.contains_key(key) + { + props.insert(key.into(), text_value(delta)); + } + Self { + kind: "block".into(), + id: node.id.clone(), + flavour: node.flavour.clone(), + version: node.version, + props, + children: Vec::new(), + } + } + pub(crate) fn plain_block(text: &str, index: usize) -> Self { + let mut b = Self { + kind: "block".into(), + id: index.to_string(), + flavour: "affine:paragraph".into(), + version: Some(1), + props: BTreeMap::new(), + children: Vec::new(), + }; + b.props.insert( + "text".into(), + text_value(&[TextDeltaOp::Insert { + insert: TextInsert::Text(text.into()), + format: None, + }]), + ); + b + } + pub fn delta(&self) -> Vec { + let key = if self.flavour == "affine:page" { + "title" + } else { + "text" + }; + self.props + .get(key) + .and_then(|v| decode_text_value(v).ok()) + .unwrap_or_default() + } + pub fn plain(&self) -> String { + self.delta() + .into_iter() + .filter_map(|op| match op { + TextDeltaOp::Insert { + insert: TextInsert::Text(s), + .. + } => Some(s), + TextDeltaOp::Insert { .. } => Some("\u{fffc}".into()), + _ => None, + }) + .collect() + } + pub(crate) fn editable(&self) -> bool { + matches!( + self.flavour.as_str(), + "affine:page" | "affine:paragraph" | "affine:list" | "affine:code" + ) + } + + pub(crate) fn properties( + &self, + ) -> blocksuite_playground_doc::DocResult> { + use y_octo::SessionValue; + fn value(v: &Value) -> blocksuite_playground_doc::DocResult { + Ok(match v { + Value::Object(map) + if map.get("$blocksuite:internal:text$") == Some(&Value::Bool(true)) => + { + SessionValue::Text(decode_text_value(v)?) + } + Value::Object(map) => SessionValue::Map( + map.iter() + .map(|(k, v)| Ok((k.clone(), value(v)?))) + .collect::>()?, + ), + Value::Array(items) => SessionValue::Array( + items + .iter() + .map(value) + .collect::>()?, + ), + _ => SessionValue::Any(serde_json::from_value(v.clone()).map_err(|e| { + blocksuite_playground_doc::DocError::InvalidState(e.to_string()) + })?), + }) + } + let mut props: BTreeMap<_, _> = if self.editable() { + self.spec() + .into_yblock_entries("") + .into_iter() + .filter(|(k, _)| k.starts_with("prop:")) + .collect() + } else { + BTreeMap::new() + }; + for (key, v) in &self.props { + if self.editable() + && (key == "text" || (self.flavour == "affine:page" && key == "title")) + { + props.insert("prop:text".into(), SessionValue::Text(self.delta())); + } else { + props.insert(format!("prop:{key}"), value(v)?); + } + } + Ok(props.into_iter().collect()) + } + + pub fn spec(&self) -> BlockSpec { + let kind = self + .props + .get("type") + .and_then(Value::as_str) + .unwrap_or("text"); + match self.flavour.as_str() { + "affine:list" => BlockSpec::List { + list_type: serde_json::from_value(json!(kind)).unwrap_or(ListType::Bulleted), + text: String::new(), + checked: self.props.get("checked") == Some(&Value::Bool(true)), + order: self + .props + .get("order") + .and_then(Value::as_i64) + .and_then(|i| i.try_into().ok()), + }, + "affine:code" => BlockSpec::Code { + text: String::new(), + language: self + .props + .get("language") + .and_then(Value::as_str) + .map(str::to_owned), + caption: String::new(), + }, + "affine:divider" => BlockSpec::Divider, + _ => BlockSpec::Paragraph { + paragraph_type: serde_json::from_value(json!(kind)).unwrap_or(ParagraphType::Text), + text: String::new(), + }, + } + } + fn html(&self) -> String { + let mut inner = String::new(); + for op in self.delta() { + let TextDeltaOp::Insert { + insert: TextInsert::Text(s), + format, + } = op + else { + continue; + }; + let mut s = escape(&s); + if let Some(attrs) = format { + for (mark, tag) in [ + ("bold", "strong"), + ("italic", "em"), + ("underline", "u"), + ("strike", "s"), + ("code", "code"), + ] { + if attrs.get(mark) == Some(&Any::True) { + s = format!("<{tag}>{s}"); + } + } + if let Some(Any::String(link)) = attrs.get("link") { + s = format!("{s}", escape(link)); + } + } + inner += &s; + } + match self.spec() { + BlockSpec::Code { .. } => format!("
{inner}
"), + BlockSpec::Divider => "
".into(), + BlockSpec::List { list_type, .. } => { + let tag = if list_type == ListType::Numbered { + "ol" + } else { + "ul" + }; + format!("<{tag}>
  • {inner}
  • ") + } + BlockSpec::Paragraph { paragraph_type, .. } => { + let tag = match paragraph_type { + ParagraphType::Text => "p", + ParagraphType::Quote => "blockquote", + h => h.as_str(), + }; + format!("<{tag}>{inner}") + } + _ => inner, + } + } +} + +fn escape(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} +fn unescape(s: &str) -> String { + s.replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace(" ", " ") + .replace("&", "&") +} + +impl Slice { + pub fn new(workspace: &str, page: &str, content: Vec) -> Self { + Self { + kind: "slice".into(), + workspace_id: workspace.into(), + page_id: page.into(), + content, + } + } + pub fn from_plain(s: &str) -> Self { + let s = s.replace("\r\n", "\n").replace('\r', "\n"); + Self::new( + "", + "", + s.split('\n') + .enumerate() + .map(|(i, line)| SliceBlock::plain_block(line, i)) + .collect(), + ) + } + pub fn plain(&self) -> String { + self.content + .iter() + .flat_map(SliceBlock::walk) + .map(SliceBlock::plain) + .collect::>() + .join("\n") + } + pub fn html(&self) -> String { + let snapshot = json!({"snapshot":self,"blobs":{}}).to_string(); + let attr = encode_html_snapshot(&json!({"BLOCKSUITE/SNAPSHOT":snapshot}).to_string()); + format!( + "
    {}
    ", + self.content + .iter() + .flat_map(SliceBlock::walk) + .map(SliceBlock::html) + .collect::() + ) + } + pub fn item(&self) -> ClipboardItem { + ClipboardItem::new_string_with_json_metadata( + self.plain(), + json!({(SNAPSHOT_MIME):self,"text/html":self.html()}), + ) + } + pub fn from_item(item: &ClipboardItem) -> Option { + if let Some(meta) = item + .metadata() + .and_then(|s| serde_json::from_str::(s).ok()) + { + if let Some(slice) = meta + .get(SNAPSHOT_MIME) + .and_then(|v| Self::parse_json(v.clone())) + { + return Some(slice); + } + if let Some(slice) = meta + .get("text/html") + .and_then(Value::as_str) + .and_then(Self::from_html) + { + return Some(slice); + } + } + item.text().map(|s| Self::from_plain(&s)) + } + fn parse_json(v: Value) -> Option { + let slice: Self = serde_json::from_value(v).ok()?; + (slice.kind == "slice" + && !slice.content.is_empty() + && slice.content.iter().all(|b| b.kind == "block")) + .then_some(slice) + } + pub fn from_html(html: &str) -> Option { + if let Some((_, after)) = html.split_once("data-blocksuite-snapshot=\"") + && let Some((encoded, _)) = after.split_once('"') + && let Some(decoded) = decode_html_snapshot(encoded) + && let Ok(map) = serde_json::from_str::(&decoded) + && let Some(raw) = map["BLOCKSUITE/SNAPSHOT"].as_str() + && let Ok(wrapped) = serde_json::from_str::(raw) + && let Some(slice) = Self::parse_json(wrapped["snapshot"].clone()) + { + return Some(slice); + } + parse_html_blocks(html) + } +} + +const URI_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$"; +struct Width { + bits: usize, + left: usize, +} +impl Width { + fn consume(&mut self) { + self.left -= 1; + if self.left == 0 { + self.left = 1 << self.bits; + self.bits += 1; + } + } +} + +/// LZ-String's URI component format uses UTF-16 symbols and writes code bits +/// least-significant first into six-bit, most-significant-first characters. +fn encode_html_snapshot(s: &str) -> String { + let mut out = String::new(); + let mut pending = 0u8; + let mut used = 0; + let mut write = |count: usize, mut code: usize| { + for _ in 0..count { + pending = (pending << 1) | (code as u8 & 1); + code >>= 1; + used += 1; + if used == 6 { + out.push(URI_ALPHABET[pending as usize] as char); + used = 0; + pending = 0; + } + } + }; + let mut width = Width { bits: 2, left: 2 }; + let mut literals = BTreeMap::new(); + let mut codes = BTreeMap::new(); + let mut fresh = BTreeMap::new(); + let mut next = 3usize; + let mut last = None; + let mut emit = |code, width: &mut Width, fresh: &mut BTreeMap| { + if let Some(unit) = fresh.remove(&code) { + let wide = unit > 255; + write(width.bits, usize::from(wide)); + write(if wide { 16 } else { 8 }, unit as usize); + width.consume(); + } else { + write(width.bits, code); + } + width.consume(); + }; + for u in s.encode_utf16() { + let literal = *literals.entry(u).or_insert_with(|| { + let code = next; + next += 1; + fresh.insert(code, u); + code + }); + let Some(previous) = last else { + last = Some(literal); + continue; + }; + if let Some(&code) = codes.get(&(previous, u)) { + last = Some(code); + continue; + } + emit(previous, &mut width, &mut fresh); + codes.insert((previous, u), next); + next += 1; + last = Some(literal); + } + if let Some(code) = last { + emit(code, &mut width, &mut fresh); + } + write(width.bits, 2); + write(6, 0); + out +} + +fn decode_html_snapshot(s: &str) -> Option { + let mut bits = s + .bytes() + .map(|b| URI_ALPHABET.iter().position(|v| *v == b)) + .flat_map(|v| (0..6).rev().map(move |n| v.map(|v| v >> n & 1))); + let mut read = |count| -> Option { + let mut value = 0; + for bit in 0..count { + value |= bits.next()?? << bit; + } + Some(value) + }; + let first = match read(2)? { + 0 => read(8)?, + 1 => read(16)?, + 2 => return Some(String::new()), + _ => return None, + }; + let mut out = vec![first as u16]; + let mut dict = vec![(0, 0); 3]; + dict.push((0, 1)); + let mut previous = (0, 1); + let mut width = Width { bits: 3, left: 4 }; + loop { + let start = out.len(); + let code = read(width.bits)?; + if code == 2 { + return String::from_utf16(&out).ok(); + } + let entry = if code < 2 { + out.push(read(if code == 0 { 8 } else { 16 })? as u16); + dict.push((start, 1)); + width.consume(); + (start, 1) + } else { + let special = code == dict.len(); + let (pos, len) = if special { previous } else { *dict.get(code)? }; + if len == 0 || start.checked_add(len + 1)? > 16 * 1024 * 1024 { + return None; + } + out.extend_from_within(pos..pos + len); + if special { + out.push(out[pos]); + } + (start, out.len() - start) + }; + dict.push((previous.0, previous.1 + 1)); + width.consume(); + previous = entry; + } +} + +fn attr<'a>(mut attrs: &'a str, key: &str) -> Option<&'a str> { + while !attrs.trim().is_empty() { + attrs = attrs.trim_start(); + let end = attrs + .find(|c: char| c.is_whitespace() || c == '=') + .unwrap_or(attrs.len()); + let name = &attrs[..end]; + attrs = attrs[end..].trim_start(); + let Some(after) = attrs.strip_prefix('=') else { + continue; + }; + attrs = after.trim_start(); + let quote = attrs.chars().next()?; + let (value, rest) = if matches!(quote, '\'' | '"') { + attrs[1..].split_once(quote)? + } else { + let end = attrs.find(char::is_whitespace).unwrap_or(attrs.len()); + attrs.split_at(end) + }; + if name.eq_ignore_ascii_case(key) { + return Some(value); + } + attrs = rest; + } + None +} + +fn parse_html_blocks(mut html: &str) -> Option { + let mut blocks = Vec::new(); + let mut current = None; + let mut delta = Vec::new(); + let mut marks: Vec<(String, Any)> = Vec::new(); + let mut lists = Vec::new(); + let mut pre = false; + let flush = |current: &mut Option, + delta: &mut Vec, + blocks: &mut Vec| { + if let Some(mut b) = current.take() { + b.props.insert("text".into(), text_value(delta)); + blocks.push(b); + } + delta.clear(); + }; + while !html.is_empty() { + if !html.starts_with('<') { + let len = html.find('<').unwrap_or(html.len()); + let raw = &html[..len]; + html = &html[len..]; + if current.is_none() && raw.trim().is_empty() { + continue; + } + current.get_or_insert_with(|| SliceBlock::plain_block("", blocks.len())); + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(unescape(raw)), + format: (!marks.is_empty()) + .then(|| marks.iter().cloned().collect::()), + }); + continue; + } + let (head, rest) = html[1..].split_once('>')?; + html = rest; + let close = head.starts_with('/'); + let head = head.trim_start_matches('/').trim().trim_end_matches('/'); + let (tag, attrs) = head.split_once(char::is_whitespace).unwrap_or((head, "")); + let tag = tag.to_ascii_lowercase(); + match tag.as_str() { + "p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "pre" | "blockquote" | "li" + | "hr" => { + if tag == "div" && current.is_none() { + continue; + } + flush(&mut current, &mut delta, &mut blocks); + if close { + if tag == "pre" { + pre = false; + } + continue; + } + let mut b = SliceBlock::plain_block("", blocks.len()); + match tag.as_str() { + "li" => { + b.flavour = "affine:list".into(); + b.props.insert( + "type".into(), + json!(if lists.last() == Some(&true) { + "numbered" + } else { + "bulleted" + }), + ); + } + "pre" => { + b.flavour = "affine:code".into(); + pre = true; + } + "hr" => b.flavour = "affine:divider".into(), + "blockquote" => { + b.props.insert("type".into(), json!("quote")); + } + h if h.starts_with('h') => { + b.props.insert("type".into(), json!(h)); + } + _ => {} + } + current = Some(b); + } + "ol" | "ul" => { + if close { + lists.pop(); + } else { + lists.push(tag == "ol"); + } + } + "br" => { + current.get_or_insert_with(|| SliceBlock::plain_block("", blocks.len())); + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text("\n".into()), + format: None, + }); + } + _ => { + let key = match tag.as_str() { + "b" | "strong" => "bold", + "em" | "i" => "italic", + "u" => "underline", + "s" | "del" => "strike", + "code" if !pre => "code", + "a" => "link", + _ => continue, + }; + if close { + if let Some(i) = marks.iter().rposition(|(k, _)| k == key) { + marks.remove(i); + } + } else if key == "link" { + if let Some(href) = attr(attrs, "href") { + marks.push((key.into(), Any::String(unescape(href)))); + } + } else { + marks.push((key.into(), Any::True)); + } + } + } + } + flush(&mut current, &mut delta, &mut blocks); + (!blocks.is_empty()).then(|| Slice::new("", "", blocks)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn uri_snapshot_matches_lz_string_javascript() { + let input = "LinkedPage 中文 🪶"; + let golden = "DISwdg1gpgJgCgQwOZQASFo5Q4aasHwbg2vaA"; + assert_eq!(encode_html_snapshot(input), golden); + assert_eq!(decode_html_snapshot(golden).as_deref(), Some(input)); + } + #[test] + fn html_only_clipboard_restores_inline_page_reference_and_label() { + let mut slice = Slice::from_plain(""); + slice.content[0].props.insert("text".into(),json!({"$blocksuite:internal:text$":true,"delta":[ + {"insert":"Go to "},{"insert":" ","attributes":{"reference":{"type":"LinkedPage","pageId":"doc:target"}}} + ]})); + let public_html = ClipboardItem::new_string_with_json_metadata( + String::new(), + json!({"text/html":slice.html()}), + ); + assert_eq!(Slice::from_item(&public_html), Some(slice)); + } + #[test] + fn html_slice_preserves_headings_links_inline_marks_and_non_bmp_text() { + let slice=Slice::from_html("

    中🪶

    1. a&b
    x\ny
    ").unwrap(); + assert_eq!(slice.content.len(), 3); + assert_eq!(slice.plain(), "中🪶\na&b\nx\ny"); + assert_eq!(slice.content[0].props["type"], "h2"); + assert_eq!( + slice.content[1].props["text"]["delta"][0]["attributes"]["link"], + "https://example.org" + ); + assert_eq!(Slice::from_html(&slice.html()), Some(slice.clone())); + assert_eq!(Slice::from_item(&slice.item()), Some(slice)); + } +} + +/// The browser's data transfer object can only be read synchronously in its paste event. +/// Capture its rich entries for the focused textarea's input-handler callback in that turn. +#[cfg(target_family = "wasm")] +pub(crate) mod browser { + use wasm_bindgen::prelude::*; + #[wasm_bindgen(inline_js = r#" +let pasteFormats; +const mime = "application/x-blocksuite-snapshot"; +export function installSliceClipboard() { + window.addEventListener("paste", event => { + if (!(event.target instanceof HTMLTextAreaElement) || !event.clipboardData) return; + const data = event.clipboardData; + pasteFormats = [data.getData(mime), data.getData("text/html")]; + queueMicrotask(() => { pasteFormats = undefined; }); + }, true); +} +export function pastedSnapshot() { return pasteFormats?.[0] || ""; } +export function pastedHtml() { return pasteFormats?.[1] || ""; } +export function writeSliceClipboard(plain, html, json) { + const clipboard = navigator.clipboard; + if (!clipboard) return; + if (!clipboard.write || typeof ClipboardItem === "undefined") { + clipboard.writeText(plain).catch(() => {}); return; + } + const formats = { + "text/plain": new Blob([plain], {type:"text/plain"}), + "text/html": new Blob([html], {type:"text/html"}), + }; + const custom = "web " + mime; + if (ClipboardItem.supports?.(custom)) formats[custom] = new Blob([json], {type:mime}); + clipboard.write([new ClipboardItem(formats)]).catch(() => clipboard.writeText(plain)).catch(() => {}); +} +"#)] + extern "C" { + #[wasm_bindgen(js_name=installSliceClipboard)] + pub fn install(); + #[wasm_bindgen(js_name=pastedSnapshot)] + fn pasted_snapshot() -> String; + #[wasm_bindgen(js_name=pastedHtml)] + fn pasted_html() -> String; + #[wasm_bindgen(js_name=writeSliceClipboard)] + fn write_slice(plain: &str, html: &str, json: &str); + } + pub(super) fn pasted() -> Option { + serde_json::from_str(&pasted_snapshot()) + .ok() + .and_then(super::Slice::parse_json) + .or_else(|| super::Slice::from_html(&pasted_html())) + } + pub(super) fn write(slice: &super::Slice) { + if let Ok(json) = serde_json::to_string(slice) { + write_slice(&slice.plain(), &slice.html(), &json); + } + } +} + +pub(crate) fn write_slice(slice: &Slice, _cx: &mut ui::App) { + #[cfg(target_family = "wasm")] + browser::write(slice); + #[cfg(not(target_family = "wasm"))] + _cx.write_to_clipboard(slice.item()); +} +pub(crate) fn read_slice(item: &ClipboardItem) -> Option<(Slice, bool)> { + #[cfg(target_family = "wasm")] + if let Some(slice) = browser::pasted() { + return Some((slice, true)); + } + Slice::from_item(item).map(|slice| (slice, item.metadata().is_some())) +} diff --git a/blocksuite/native-playground/crates/playground/src/editor_session.rs b/blocksuite/native-playground/crates/playground/src/editor_session.rs new file mode 100644 index 0000000000..79b84cc712 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/editor_session.rs @@ -0,0 +1,2106 @@ +//! Document selection and text input shared by desktop, browser and headless views. +use std::ops::Range; + +use blocksuite_playground_doc::{ + DocError, DocResult, + read::{BlockNode, RichText}, + session::{PageDocSession, SelectionSnapshot, split_delta}, + wire::{DocMessage, RoomBinaryFrame}, +}; +use ui::{ + EntityInputHandler, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, Pixels, Point, + UTF16Selection, +}; +use unicode_segmentation::UnicodeSegmentation; +use y_octo::{SessionCommit, TextDeltaOp, TextInsert}; + +use super::*; +use crate::block_flow::{FlowBlock, FlowRect}; +use crate::rich_text::{CaretPosition, TextBiIndex, WrapAffinity}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DocPoint { + pub block_id: String, + pub caret: CaretPosition, +} + +impl DocPoint { + pub fn new(block_id: impl Into, offset: u64) -> Self { + Self { + block_id: block_id.into(), + caret: CaretPosition { + utf16_offset: offset, + affinity: WrapAffinity::Downstream, + }, + } + } + fn offset(&self) -> u64 { + self.caret.utf16_offset + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DocumentSelection { + pub anchor: DocPoint, + pub focus: DocPoint, +} + +impl DocumentSelection { + fn caret(point: DocPoint) -> Self { + Self { + anchor: point.clone(), + focus: point, + } + } + fn empty(&self) -> bool { + self.anchor.block_id == self.focus.block_id && self.anchor.offset() == self.focus.offset() + } + fn snapshot(&self, page: &PageDocSession) -> DocResult { + page.capture_selection_snapshot( + &self.anchor.block_id, + self.anchor.offset(), + &self.focus.block_id, + self.focus.offset(), + ) + } + fn ordered<'a>( + &'a self, + layout: &FlowLayout, + ) -> Option<(&'a DocPoint, &'a DocPoint, usize, usize, bool)> { + let index = |p: &DocPoint| layout.blocks.iter().position(|b| b.block_id == p.block_id); + let a = index(&self.anchor)?; + let f = index(&self.focus)?; + Some(if (a, self.anchor.offset()) <= (f, self.focus.offset()) { + (&self.anchor, &self.focus, a, f, false) + } else { + (&self.focus, &self.anchor, f, a, true) + }) + } +} + +#[derive(Default)] +struct RangeBlocks { + intermediate: Vec, + survivors: Vec, +} + +/// Root content blocks of Page-mode notes, in document order. +fn page_content_roots(root: &BlockNode) -> impl DoubleEndedIterator { + root.children + .iter() + .filter(|note| note.is_page_visible_note()) + .flat_map(|note| ¬e.children) +} + +impl RangeBlocks { + fn between(snapshot: &PageSnapshot, start: &str, end: &str) -> Option { + if start == end { + return Some(Self::default()); + } + let root = snapshot.root.as_ref()?; + let mut pending: Vec<_> = page_content_roots(root) + .rev() + .map(|node| (node, false)) + .collect(); + let mut intermediate = Vec::new(); + let mut after_start = root.id == start; + // Each pending subtree records whether its parent belongs to the deletion. + // At the endpoint the stack holds its children, then later siblings up the ancestor chain. + while let Some((node, _)) = pending.pop() { + pending.extend(node.children.iter().rev().map(|child| (child, after_start))); + if after_start { + if node.id == end { + let survivors = pending + .into_iter() + .rev() + .filter(|(_, parent_removed)| *parent_removed) + .map(|(child, _)| child.id.clone()) + .collect(); + return Some(Self { + intermediate, + survivors, + }); + } + intermediate.push(node.id.clone()); + } else if node.id == start { + after_start = true; + } + } + None + } +} + +struct Preedit { + replacement: SelectionSnapshot, + backward: bool, + text: String, + selected: Range, +} + +#[derive(Default)] +pub struct EditorSession { + pub selection: Option, + pub goal_x: Option, + preedit: Option, + relative_selection: Option, + pending_marks: BTreeMap>, + last_typing: Option, + reveal: bool, + dragging: bool, + next_id: u64, +} + +fn word_range(text: &str, offset: u64) -> Range { + let index = TextBiIndex::new(text); + let byte = index.utf16_to_utf8_clamped(offset); + text.split_word_bound_indices() + .find(|(i, s)| i + s.len() > byte) + .or_else(|| text.split_word_bound_indices().next_back()) + .map(|(i, s)| index.utf8_to_utf16(i)..index.utf8_to_utf16(i + s.len())) + .unwrap_or(0..0) +} + +fn text_content(node: &BlockNode) -> Option<&str> { + match &node.content { + BlockContent::Page { title } => Some(&title.plain), + BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => Some(&text.plain), + BlockContent::Code { text, .. } => Some(text), + _ => None, + } +} + +fn node_mut<'a>(node: &'a mut BlockNode, id: &str) -> Option<&'a mut BlockNode> { + if node.id == id { + return Some(node); + } + node.children + .iter_mut() + .find_map(|child| node_mut(child, id)) +} + +fn parent_of<'a>(snapshot: &'a PageSnapshot, id: &str) -> Option<(&'a BlockNode, usize)> { + snapshot.root.as_ref()?.walk().find_map(|node| { + node.children + .iter() + .position(|c| c.id == id) + .map(|pos| (node, pos)) + }) +} + +type Commit = SessionCommit; + +impl PlaygroundView { + fn page(&self) -> Option<&PageDocSession> { + self.state.workspace.page(self.page_id.as_deref()?) + } + fn page_mut(&mut self) -> DocResult<&mut PageDocSession> { + self.page_id + .as_deref() + .and_then(|id| self.state.workspace.page_mut(id)) + .ok_or_else(|| DocError::InvalidState("no active page".into())) + } + fn block_text(&self, id: &str) -> Option<&str> { + text_content(self.page_snapshot()?.block(id)?) + } + fn input_point(&self, pos: Point, window: &Window) -> Option { + let geometry = page_geometry(f32::from(window.viewport_size().width)); + let (block_id, mut caret) = self.flow_layout()?.hit_document( + f32::from(pos.x) - geometry.column_x, + f32::from(pos.y) - TOPBAR_HEIGHT + self.scroll_y, + )?; + caret.utf16_offset = caret + .utf16_offset + .min(self.block_text(&block_id)?.encode_utf16().count() as u64); + Some(DocPoint { block_id, caret }) + } + + pub(crate) fn editor_mouse_down( + &mut self, + e: &MouseDownEvent, + w: &mut Window, + cx: &mut Context, + ) { + let Some(p) = self.input_point(e.position, w) else { + return; + }; + self.editor_focus.focus(w, cx); + w.request_virtual_keyboard(); + self.editor.dragging = true; + let mut sel = DocumentSelection::caret(p.clone()); + if e.click_count >= 2 { + let s = self.block_text(&p.block_id).unwrap_or(""); + let range = if e.click_count == 2 { + word_range(s, p.offset()) + } else { + 0..s.encode_utf16().count() as u64 + }; + sel.anchor = DocPoint::new(&p.block_id, range.start); + sel.focus = DocPoint::new(&p.block_id, range.end); + } else if e.modifiers.shift + && let Some(old) = &self.editor.selection + { + sel.anchor = old.anchor.clone(); + } + self.change_selection(sel, w, cx); + } + pub(crate) fn editor_mouse_move( + &mut self, + e: &MouseMoveEvent, + w: &mut Window, + cx: &mut Context, + ) { + if e.pressed_button != Some(MouseButton::Left) { + self.editor.dragging = false; + return; + } + if self.editor.dragging + && let Some(focus) = self.input_point(e.position, w) + && let Some(sel) = &self.editor.selection + { + self.change_selection( + DocumentSelection { + anchor: sel.anchor.clone(), + focus, + }, + w, + cx, + ); + } + } + + pub fn document_selection(&self) -> Option<&DocumentSelection> { + self.editor.selection.as_ref() + } + pub fn goal_x(&self) -> Option { + self.editor.goal_x + } + /// Focus a document range supplied by another page control. + pub fn select_document_range( + &mut self, + selection: DocumentSelection, + w: &mut Window, + cx: &mut Context, + ) { + self.editor_focus.focus(w, cx); + self.change_selection(selection, w, cx); + } + + fn change_selection(&mut self, sel: DocumentSelection, w: &mut Window, cx: &mut Context) { + if self.editor.preedit.take().is_some() { + self.dirty_text = None; + self.doc_rev += 1; + } + self.editor.selection = Some(sel); + self.editor.pending_marks.clear(); + self.editor.last_typing = None; + self.editor.goal_x = None; + self.editor.reveal = true; + if let Ok(page) = self.page_mut() { + let _ = page.stop_capturing(); + } + self.announce_selection(cx); + w.notify_text_selection_changed(&self.editor_focus); + cx.notify(); + } + fn announce_selection(&mut self, cx: &Context) { + self.editor.relative_selection = self + .editor + .selection + .as_ref() + .and_then(|s| s.snapshot(self.page()?).ok()); + let Some(sel) = &self.editor.selection else { + return; + }; + let Some(page_id) = &self.page_id else { return }; + let state = if sel.empty() { + TextSelectionState::caret(&sel.focus.block_id, sel.focus.offset()) + } else { + let Some(layout) = self.flow_layout() else { + return; + }; + let Some((start, end, _, _, reverse)) = sel.ordered(&layout) else { + return; + }; + let single = start.block_id == end.block_id; + let limit = if single { + end.offset() + } else { + self.block_text(&start.block_id) + .map_or(0, |s| s.encode_utf16().count() as u64) + }; + let from = TextRangePoint { + block_id: start.block_id.clone(), + index: start.offset(), + length: limit.saturating_sub(start.offset()), + }; + let to = (!single).then(|| TextRangePoint { + block_id: end.block_id.clone(), + index: 0, + length: end.offset(), + }); + TextSelectionState::range(from, to, reverse) + }; + let now = self.now_ms(cx) as u64; + let mut payload = self + .state + .awareness + .get_payload(self.state.awareness.local_client_id()) + .unwrap_or_else(|| { + AwarenessPayload::new( + room_client::LOCAL_AWARENESS_NAME, + room_client::LOCAL_AWARENESS_COLOR, + ) + }); + if payload + .set_text_selection(format!("{page_id}:native"), state) + .is_ok() + && let Ok(bytes) = self.state.awareness.set_local_payload(&payload, now) + && let Some(room) = &self.room + { + room.link.send_binary(RoomBinaryFrame::Awareness(bytes)); + } + } + + fn did_edit( + &mut self, + commit: Option, + dirty: Option<&str>, + w: &mut Window, + cx: &mut Context, + ) { + if let (Some(commit), Some(room), Some(id)) = (commit, &self.room, &self.page_id) { + room.link.send_binary(RoomBinaryFrame::Doc { + doc_id: id.clone(), + message: DocMessage::Update(commit.update), + }); + } + let previous_title = self + .snapshot + .as_ref() + .and_then(|s| s.root.as_ref()) + .and_then(|r| { + (dirty.is_none() || dirty == Some(r.id.as_str())) + .then(|| text_content(r).map(str::to_owned)) + .flatten() + }); + if !dirty.is_some_and(|id| self.refresh_text_block(id)) { + self.refresh_document(); + } + if let Some(page_id) = self.page_id.clone() + && let Some(root) = self.snapshot.as_ref().and_then(|s| s.root.as_ref()) + && (dirty.is_none() || dirty == Some(root.id.as_str())) + && let BlockContent::Page { title } = &root.content + && previous_title + .as_ref() + .is_some_and(|previous| previous != &title.plain) + && let Ok(Some(commit)) = self.state.workspace.set_page_title(&page_id, &title.plain) + { + self.page_titles.insert(page_id, title.plain.clone()); + self.env_rev += 1; + if let Some(room) = &self.room { + room.link.send_binary(RoomBinaryFrame::Doc { + doc_id: self.state.workspace.room().into(), + message: DocMessage::Update(commit.update), + }); + } + } + self.editor.reveal = true; + self.editor.goal_x = None; + self.announce_selection(cx); + w.notify_text_input_changed(&self.editor_focus); + cx.notify(); + } + + fn refresh_text_block(&mut self, id: &str) -> bool { + let Some(page) = self.page() else { + return false; + }; + let Ok((rich, value)) = page.read_editable_text(id) else { + return false; + }; + let Some(root) = self + .snapshot + .as_mut() + .and_then(|s| Rc::make_mut(s).root.as_mut()) + else { + return false; + }; + let Some(node) = node_mut(root, id) else { + return false; + }; + let key = match &mut node.content { + BlockContent::Page { title } => { + *title = rich; + "prop:title" + } + BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => { + *text = rich; + "prop:text" + } + BlockContent::Code { text, .. } => { + *text = rich.plain; + "prop:text" + } + _ => return false, + }; + if let Some(changed) = &mut self.dirty_text { + changed.insert(if key == "prop:title" { + "\0title".to_owned() + } else { + id.to_owned() + }); + } + node.props.insert(key.into(), value); + self.doc_rev += 1; + true + } + + pub(super) fn resolve_remote_selection(&mut self, cx: &Context) { + if self.editor.relative_selection.is_none() { + return; + } + let restored = self + .editor + .relative_selection + .as_ref() + .and_then(|s| self.page()?.resolve_selection_snapshot(s).ok().flatten()); + if let (Some(r), Some(sel)) = (restored, self.editor.selection.as_mut()) { + if sel.anchor.offset() == r.anchor.1 && sel.focus.offset() == r.focus.1 { + return; + } + sel.anchor.caret.utf16_offset = r.anchor.1; + sel.focus.caret.utf16_offset = r.focus.1; + self.announce_selection(cx); + } else { + self.editor = EditorSession::default(); + } + } + + fn geometry(&self, p: &DocPoint) -> Option { + self.flow_layout()?.block(&p.block_id)?.caret_rect(p.caret) + } + + fn navigate( + &mut self, + key: &str, + shift: bool, + word: bool, + line_edge: bool, + w: &mut Window, + cx: &mut Context, + ) -> Option<()> { + let sel = self.editor.selection.clone()?; + let layout = self.flow_layout()?; + let mut p = sel.focus.clone(); + let block = layout.block(&p.block_id)?; + let text = self.block_text(&p.block_id)?; + let index = TextBiIndex::new(text); + let backward = matches!(key, "left" | "up" | "home"); + let step = |b: &FlowBlock, back: bool| -> Option<&FlowBlock> { + let i = layout + .blocks + .iter() + .position(|other| other.block_id == b.block_id)?; + if back { + layout.blocks[..i].iter().rev().find(|b| b.editable()) + } else { + layout.blocks[i + 1..].iter().find(|b| b.editable()) + } + }; + let mut goal = None; + if !shift && !sel.empty() && matches!(key, "left" | "right") { + let (start, end, ..) = sel.ordered(&layout)?; + p = if backward { start } else { end }.clone(); + } else if matches!(key, "up" | "down") { + let rect = block.caret_rect(p.caret)?; + let x = self.editor.goal_x.unwrap_or(rect.x); + goal = Some(x); + let mut y = rect.y + + if backward { + -rect.h * 0.5 + } else { + rect.h * 1.5 + }; + let field = block.body.text.as_ref()?; + let top = block.y + field.y; + let dest = if y < top || y >= top + field.layout.height() { + let next = step(block, backward)?; + let nt = next.body.text.as_ref()?; + y = next.y + + nt.y + + if backward { + nt.layout.height() - nt.layout.line_height() * 0.5 + } else { + nt.layout.line_height() * 0.5 + }; + next + } else { + block + }; + p = DocPoint { + block_id: dest.block_id.clone(), + caret: dest.hit_text(x, y)?, + }; + } else if line_edge || matches!(key, "home" | "end") { + let rect = block.caret_rect(p.caret)?; + p.caret = block.hit_text( + if backward { -1.0 } else { layout.width + 1. }, + rect.y + rect.h * 0.5, + )?; + } else if (backward && p.offset() == 0) || (!backward && p.offset() == index.utf16_len()) { + let dest = step(block, backward)?; + p = DocPoint::new( + &dest.block_id, + if backward { + self.block_text(&dest.block_id)?.encode_utf16().count() as u64 + } else { + 0 + }, + ); + } else { + let offset = if word { + let at = if backward { + index.prev_grapheme_utf16(p.offset()) + } else { + p.offset() + }; + let range = word_range(text, at); + if backward { range.start } else { range.end } + } else if backward { + index.prev_grapheme_utf16(p.offset()) + } else { + index.next_grapheme_utf16(p.offset()) + }; + p = DocPoint::new(&p.block_id, offset); + } + self.change_selection( + if shift { + DocumentSelection { + anchor: sel.anchor, + focus: p, + } + } else { + DocumentSelection::caret(p) + }, + w, + cx, + ); + self.editor.goal_x = goal; + Some(()) + } +} + +impl PlaygroundView { + fn composition_selection(&self) -> Option { + let r = self + .page()? + .resolve_selection_snapshot(&self.editor.preedit.as_ref()?.replacement) + .ok()??; + Some(DocumentSelection { + anchor: DocPoint::new(r.anchor.0, r.anchor.1), + focus: DocPoint::new(r.focus.0, r.focus.1), + }) + } + fn composition_endpoints(&self) -> Option<(DocPoint, DocPoint)> { + let sel = self.composition_selection()?; + Some(if self.editor.preedit.as_ref()?.backward { + (sel.focus, sel.anchor) + } else { + (sel.anchor, sel.focus) + }) + } + fn composed_range(&self) -> Option<(String, Range)> { + let (start, end) = self.composition_endpoints()?; + let to = if start.block_id == end.block_id { + end.offset() + } else { + self.block_text(&start.block_id)?.encode_utf16().count() as u64 + }; + Some((start.block_id.clone(), start.offset()..to)) + } + fn display_text(&self) -> Option { + if let Some((start, end)) = self.composition_endpoints() { + let left = self.block_text(&start.block_id)?; + let right = self.block_text(&end.block_id)?; + let a = TextBiIndex::new(left).utf16_to_utf8_clamped(start.offset()); + let b = TextBiIndex::new(right).utf16_to_utf8_clamped(end.offset()); + return Some(format!( + "{}{}{}", + &left[..a], + self.editor.preedit.as_ref()?.text, + &right[b..] + )); + } + self.block_text(&self.editor.selection.as_ref()?.focus.block_id) + .map(str::to_owned) + } + pub(super) fn preedit_snapshot(&self) -> Option { + let pre = self.editor.preedit.as_ref()?; + let (start, end) = self.composition_endpoints()?; + let mut snapshot = self.page_snapshot()?.clone(); + let plain = self.display_text()?; + let rich = |p: &DocPoint| { + self.page()? + .read_editable_text(&p.block_id) + .ok() + .map(|(r, _)| r) + }; + let (mut delta, _) = split_delta(&rich(&start)?.delta, start.offset()).ok()?; + let (_, right) = split_delta(&rich(&end)?.delta, end.offset()).ok()?; + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(pre.text.clone()), + format: None, + }); + delta.extend(right); + if start.block_id != end.block_id { + let blocks = RangeBlocks::between(&snapshot, &start.block_id, &end.block_id)?; + let leaf_parent = if blocksuite_playground_doc::schema::is_leaf_flavour( + &snapshot.block(&start.block_id)?.flavour, + ) { + Some(parent_of(&snapshot, &start.block_id)?.0.id.clone()) + } else { + None + }; + let root = snapshot.root.as_mut()?; + let children: Vec<_> = blocks + .survivors + .iter() + .filter_map(|id| root.walk().find(|node| node.id == *id).cloned()) + .collect(); + fn prune(node: &mut BlockNode, hidden: &[String], end: &str) { + node.children.retain_mut(|child| { + if child.id == end || hidden.contains(&child.id) { + return false; + } + prune(child, hidden, end); + true + }); + } + prune(root, &blocks.intermediate, &end.block_id); + if root.id == start.block_id { + if let Some(note) = root.children.iter_mut().find(|n| n.is_page_visible_note()) { + note.children.splice(0..0, children); + } + } else if let Some(parent_id) = leaf_parent { + let parent = node_mut(root, &parent_id)?; + let slot = parent + .children + .iter() + .position(|child| child.id == start.block_id)? + + 1; + parent.children.splice(slot..slot, children); + } else { + node_mut(root, &start.block_id)?.children.extend(children); + } + } + match &mut node_mut(snapshot.root.as_mut()?, &start.block_id)?.content { + BlockContent::Code { text, .. } => *text = plain, + BlockContent::Page { title: rich } + | BlockContent::Paragraph { text: rich, .. } + | BlockContent::List { text: rich, .. } => *rich = RichText { delta, plain }, + _ => return None, + } + Some(snapshot) + } + fn clear_composition(&mut self, w: &mut Window, cx: &mut Context) { + if let Some(sel) = self.composition_selection() { + self.editor.selection = Some(sel); + } + if self.editor.preedit.take().is_some() { + self.dirty_text = None; + self.doc_rev += 1; + self.ensure_layout( + page_geometry(f32::from(w.viewport_size().width)).column_width, + w, + ); + self.announce_selection(cx); + w.notify_text_input_changed(&self.editor_focus); + cx.notify(); + } + } + fn visual_focus(&self) -> Option { + if let Some((id, r)) = self.composed_range() { + return Some(DocPoint::new( + id, + r.start + self.editor.preedit.as_ref()?.selected.end as u64, + )); + } + Some(self.editor.selection.as_ref()?.focus.clone()) + } + pub(super) fn reveal_caret(&mut self, height: f32) { + if std::mem::take(&mut self.editor.reveal) + && let Some(rect) = self.visual_focus().and_then(|p| self.geometry(&p)) + { + if rect.y < self.scroll_y { + self.scroll_y = rect.y.round(); + } else if rect.bottom() > self.scroll_y + height { + self.scroll_y = (rect.bottom() - height).round(); + } + } + } + fn world_spans(block: &FlowBlock, r: Range) -> Vec { + let Some(t) = &block.body.text else { + return Vec::new(); + }; + t.layout + .selection_spans(r.start as usize, r.end as usize) + .into_iter() + .map(|(line, a, b)| { + FlowRect::new( + block.x + t.x + a, + block.y + t.y + line as f32 * t.layout.line_height(), + b - a, + t.layout.line_height(), + ) + }) + .collect() + } + /// Selected glyph runs and the paragraph breaks between them, in page coordinates. + pub fn selection_rects(&self, layout: &FlowLayout) -> Vec { + let mut out = Vec::new(); + let Some(sel) = &self.editor.selection else { + return out; + }; + if sel.empty() { + return out; + } + let Some((start, end, a, b, _)) = sel.ordered(layout) else { + return out; + }; + + for block in &layout.blocks[a..=b] { + let from = if start.block_id == block.block_id { + start.offset() + } else { + 0 + }; + let to = if end.block_id == block.block_id { + end.offset() + } else { + block.body.plain.encode_utf16().count() as u64 + }; + let runs = Self::world_spans(block, from..to); + let first = runs.first().copied().unwrap_or(FlowRect::new( + block.x, + block.y, + 1.0, + block.body.height, + )); + if runs.is_empty() && a != b && block.editable() && block.body.plain.is_empty() { + out.push(first); + } + out.extend(runs); + } + out + } + pub(super) fn local_selection_elements( + &self, + layout: &FlowLayout, + v: PageViewport, + palette: &Palette, + ) -> Vec { + let mut el = Vec::new(); + let mut draw = |r: FlowRect, color: ui::Hsla, caret: bool| { + if r.bottom() < v.scroll_y || r.y > v.scroll_y + v.height { + return; + } + let mut d = div() + .absolute() + .left(px(v.column_x + r.x)) + .top(px(r.y - v.scroll_y)) + .w(px(r.w.max(1.0))) + .h(px(r.h)) + .bg(color); + if caret && r.y >= v.scroll_y && r.bottom() <= v.scroll_y + v.height { + d = d.snapshot("page.local_caret", Some(PAGE_SURFACE_ID)); + } + el.push(d.into_any_element()); + }; + if let Some((id, r)) = self.composed_range() + && let Some(pre) = &self.editor.preedit + && let Some(block) = layout.block(&id) + { + for mut rect in Self::world_spans( + block, + r.start..r.start + pre.text.encode_utf16().count() as u64, + ) { + rect.y += rect.h - 1.0; + rect.h = 1.0; + draw(rect, palette.text_secondary, false); + } + } else { + for r in self.selection_rects(layout) { + draw(r, palette.brand.opacity(0.22), false); + } + } + if let Some(p) = self.visual_focus() + && let Some(rect) = layout + .block(&p.block_id) + .and_then(|b| b.caret_rect(p.caret)) + { + draw(rect, palette.text_primary, true); + } + el + } + fn begin_input(&mut self) { + if self.editor.selection.is_none() + && let Some(root) = self.page_snapshot().and_then(|s| s.root.as_ref()) + { + self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(&root.id, 0))); + } + } + fn replacement_selection(&self, range: Option>) -> Option { + let sel = self.editor.selection.as_ref()?; + if let Some(selection) = self.composition_selection() { + return Some(selection); + } + Some(if let Some(r) = range { + if sel.anchor.block_id != sel.focus.block_id + && r.is_empty() + && r.start as u64 == sel.focus.offset() + { + return Some(sel.clone()); + } + DocumentSelection { + anchor: DocPoint::new(&sel.focus.block_id, r.start as u64), + focus: DocPoint::new(&sel.focus.block_id, r.end as u64), + } + } else { + sel.clone() + }) + } + fn apply_markdown( + &mut self, + sel: &DocumentSelection, + typed: &str, + w: &mut Window, + cx: &mut Context, + ) -> DocResult { + if !sel.empty() || self.editor.preedit.is_some() || typed.is_empty() { + return Ok(false); + } + let Some(snapshot) = self.snapshot.as_ref().cloned() else { + return Ok(false); + }; + let id = &sel.focus.block_id; + let Some(node) = snapshot.block(id) else { + return Ok(false); + }; + let BlockContent::Paragraph { + kind, text: rich, .. + } = &node.content + else { + return Ok(false); + }; + if *kind == ParagraphType::Quote { + return Ok(false); + } + let offset = sel.focus.offset(); + let index = TextBiIndex::new(&rich.plain); + let byte = index.utf16_to_utf8_clamped(offset); + let mut prefix = rich.plain[..byte].to_owned(); + prefix.push_str(typed); + let now = self.now_ms(cx) as u64; + if let Some(spec) = markdown_block(&prefix) { + let Some((parent, index)) = parent_of(&snapshot, id) else { + return Ok(false); + }; + let replacement = self.fresh_block_id(); + let trailing = self.fresh_block_id(); + let divider = matches!(spec, BlockSpec::Divider); + let code = matches!(spec, BlockSpec::Code { .. }); + let focus = if divider || spec.flavour() == node.flavour { + id + } else { + &replacement + }; + let page = self.page_mut()?; + let before = sel.snapshot(page)?; + let commit = page.structural_edit(now, |page| { + if offset > 0 { + page.remove_text(id, "prop:text", 0, offset, now)?; + } + if divider || code { + page.add_block( + &replacement, + spec, + Some(&parent.id), + Some(index as u64), + now, + )?; + if code { + let remaining = page.read_editable_text(id)?.0; + if !remaining.is_empty() { + page.add_block( + &trailing, + paragraph(), + Some(&parent.id), + Some(index as u64 + 1), + now, + )?; + page.apply_text_delta(&trailing, "prop:text", &remaining.delta, now)?; + } + page.remove_lifting_children(id, now)?; + } + } else { + page.convert_markdown_block(id, &replacement, spec, now)?; + } + Ok(()) + })?; + if commit.is_some() { + page.set_undo_selection_snapshot(before)?; + } + self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(focus, 0))); + self.editor.last_typing = None; + self.did_edit(commit, None, w, cx); + return Ok(true); + } + if let Some(body) = prefix.strip_suffix('`') + && let Some(open) = body.rfind('`') + && !body[open + 1..].is_empty() + && !body[open + 1..].contains('\n') + { + let from = body[..open].encode_utf16().count() as u64; + // Preserve existing inline marks in the text between the delimiters. + let existing = offset.saturating_sub(from + 1); + let mut delta = vec![TextDeltaOp::Retain { + retain: from, + format: None, + }]; + if from < offset { + delta.push(TextDeltaOp::Delete { delete: 1 }); + } + let attrs = Some(TextAttributes::from([("code".into(), Any::True)])); + if existing > 0 { + delta.push(TextDeltaOp::Retain { + retain: existing, + format: attrs.clone(), + }); + } + let content = &body[open + 1..]; + let ix = TextBiIndex::new(content); + let new = &content[ix.utf16_to_utf8_clamped(existing)..]; + if !new.is_empty() { + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(new.into()), + format: attrs, + }); + } + let page = self.page_mut()?; + let before = sel.snapshot(page)?; + page.stop_capturing()?; + let commit = page.apply_text_delta(id, "prop:text", &delta, now)?; + if commit.is_some() { + page.set_undo_selection_snapshot(before)?; + } + page.stop_capturing()?; + self.editor.selection = Some(DocumentSelection::caret(DocPoint::new( + id, + from + ix.utf16_len(), + ))); + self.editor.last_typing = None; + self.did_edit(commit, Some(id), w, cx); + return Ok(true); + } + Ok(false) + } + + fn replace_selection( + &mut self, + sel: DocumentSelection, + text: &str, + w: &mut Window, + cx: &mut Context, + ) -> DocResult { + self.ensure_layout( + page_geometry(f32::from(w.viewport_size().width)).column_width, + w, + ); + if self.apply_markdown(&sel, text, w, cx)? { + return Ok(()); + } + let now = self.now_ms(cx) as u64; + let layout = self + .flow_layout() + .ok_or_else(|| DocError::InvalidState("missing layout".into()))?; + let (start, end, a, b, _) = sel + .ordered(&layout) + .ok_or_else(|| DocError::InvalidState("selection is no longer visible".into()))?; + let id = start.block_id.clone(); + let cross = a != b; + let key = if matches!(layout.blocks[a].body.kind, block_flow::FlowKind::Title) { + "prop:title" + } else { + "prop:text" + }; + let mut marks = self.insertion_marks(start)?; + for (key, value) in &self.editor.pending_marks { + if let Some(v) = value { + marks.insert(key.clone(), v.clone()); + } else { + marks.remove(key); + } + } + let group = self + .editor + .last_typing + .is_some_and(|t| now.saturating_sub(t) < 500) + && sel.empty() + && !cross; + let blocks = RangeBlocks::between( + self.page_snapshot() + .ok_or_else(|| DocError::InvalidState("missing page".into()))?, + &id, + &end.block_id, + ) + .ok_or_else(|| DocError::InvalidState("selection outside page content".into()))?; + let page = self.page_mut()?; + let snapshot = sel.snapshot(page)?; + if !group { + page.stop_capturing()?; + } + let mut delta = vec![TextDeltaOp::Retain { + retain: start.offset(), + format: None, + }]; + if !cross && end.offset() > start.offset() { + delta.push(TextDeltaOp::Delete { + delete: end.offset() - start.offset(), + }); + } + if !text.is_empty() { + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(text.into()), + format: (!marks.is_empty()).then_some(marks), + }); + } + let commit = if cross { + page.structural_edit(now, |page| { + page.delete_cross_block_range( + (&id, start.offset()), + (&end.block_id, end.offset()), + &blocks.intermediate, + &blocks.survivors, + now, + )?; + if !text.is_empty() { + page.apply_text_delta(&id, key, &delta, now)?; + } + Ok(()) + })? + } else { + page.apply_text_delta(&id, key, &delta, now)? + }; + if commit.is_some() && !group { + page.set_undo_selection_snapshot(snapshot)?; + } + self.editor.selection = Some(DocumentSelection::caret(DocPoint::new( + &id, + start.offset() + text.encode_utf16().count() as u64, + ))); + self.editor.last_typing = (!cross).then_some(now); + self.editor.preedit = None; + self.did_edit(commit, (!cross).then_some(&id), w, cx); + Ok(()) + } + fn screen_rect(&self, r: FlowRect, w: &Window) -> Bounds { + Bounds::new( + point( + px(page_geometry(f32::from(w.viewport_size().width)).column_x + r.x), + px(TOPBAR_HEIGHT + r.y - self.scroll_y), + ), + size(px(r.w), px(r.h)), + ) + } +} + +impl EntityInputHandler for PlaygroundView { + fn paste(&mut self, item: ui::ClipboardItem, w: &mut Window, cx: &mut Context) { + self.begin_input(); + if let Some((slice, rich)) = crate::clipboard::read_slice(&item) + && let Err(e) = self.paste_slice(slice, rich, w, cx) + { + eprintln!("clipboard paste: {e}"); + } + } + fn text_for_range( + &mut self, + range: Range, + adjusted: &mut Option>, + _: &mut Window, + _: &mut Context, + ) -> Option { + let text = self.display_text()?; + let index = TextBiIndex::new(&text); + let start = index.utf16_to_utf8_clamped(range.start as u64); + let end = index.utf16_to_utf8_clamped(range.end as u64).max(start); + *adjusted = Some(index.utf8_to_utf16(start) as usize..index.utf8_to_utf16(end) as usize); + Some(text[start..end].into()) + } + fn selected_text_range( + &mut self, + _: bool, + _: &mut Window, + _: &mut Context, + ) -> Option { + if let Some((_, r)) = self.composed_range() + && let Some(pre) = &self.editor.preedit + { + return Some(UTF16Selection { + range: r.start as usize + pre.selected.start..r.start as usize + pre.selected.end, + reversed: false, + }); + } + let sel = self.editor.selection.as_ref()?; + let f = sel.focus.offset() as usize; + let a = if sel.anchor.block_id == sel.focus.block_id { + sel.anchor.offset() as usize + } else { + f + }; + Some(UTF16Selection { + range: a.min(f)..a.max(f), + reversed: a > f, + }) + } + fn text_length_utf16(&mut self, _: &mut Window, _: &mut Context) -> Option { + Some(self.display_text()?.encode_utf16().count()) + } + fn set_selected_text_range(&mut self, r: Range, w: &mut Window, cx: &mut Context) { + if let Some(focus) = self.visual_focus() { + self.change_selection( + DocumentSelection { + anchor: DocPoint::new(&focus.block_id, r.start as u64), + focus: DocPoint::new(&focus.block_id, r.end as u64), + }, + w, + cx, + ); + } + } + fn marked_text_range(&self, _: &mut Window, _: &mut Context) -> Option> { + let (_, r) = self.composed_range()?; + let start = r.start as usize; + Some(start..start + self.editor.preedit.as_ref()?.text.encode_utf16().count()) + } + fn unmark_text(&mut self, w: &mut Window, cx: &mut Context) { + if let Some(pre) = self.editor.preedit.as_ref() { + let text = pre.text.clone(); + self.replace_text_in_range(None, &text, w, cx); + } + } + fn replace_text_in_range( + &mut self, + r: Option>, + text: &str, + w: &mut Window, + cx: &mut Context, + ) { + self.begin_input(); + let selection = self.replacement_selection(r); + if self.editor.preedit.is_some() { + self.clear_composition(w, cx); + if text.is_empty() { + return; + } + } + if let Some(sel) = selection + && let Err(e) = self.replace_selection(sel, text, w, cx) + { + eprintln!("text replacement: {e}"); + } + } + fn replace_and_mark_text_in_range( + &mut self, + r: Option>, + text: &str, + selected: Option>, + w: &mut Window, + cx: &mut Context, + ) { + self.begin_input(); + if text.is_empty() { + self.clear_composition(w, cx); + return; + } + let Some(sel) = self.replacement_selection(r) else { + return; + }; + let Some(page) = self.page() else { return }; + let backward = if let Some(pre) = &self.editor.preedit { + pre.backward + } else { + let Some(layout) = self.flow_layout() else { + return; + }; + let Some((_, _, _, _, backward)) = sel.ordered(&layout) else { + return; + }; + backward + }; + let Ok(replacement) = sel.snapshot(page) else { + return; + }; + let n = text.encode_utf16().count(); + let selected = selected.unwrap_or(n..n); + self.dirty_text = None; + self.editor.preedit = Some(Preedit { + replacement, + backward, + text: text.into(), + selected: selected.start.min(n)..selected.end.min(n), + }); + self.editor.reveal = true; + self.doc_rev += 1; + w.notify_text_input_changed(&self.editor_focus); + cx.notify(); + } + fn bounds_for_range( + &mut self, + r: Range, + bounds: Bounds, + w: &mut Window, + cx: &mut Context, + ) -> Option> { + self.selection_bounds_for_range(r, bounds, w, cx) + .into_iter() + .next() + } + fn selection_bounds_for_range( + &mut self, + r: Range, + _: Bounds, + w: &mut Window, + _: &mut Context, + ) -> Vec> { + let Some(sel) = &self.editor.selection else { + return vec![]; + }; + let id = self + .composed_range() + .map(|(id, _)| id) + .unwrap_or_else(|| sel.focus.block_id.clone()); + let Some(layout) = self.ensure_layout( + page_geometry(f32::from(w.viewport_size().width)).column_width, + w, + ) else { + return vec![]; + }; + let Some(block) = layout.block(&id) else { + return vec![]; + }; + let mut rects = Self::world_spans(block, r.start as u64..r.end as u64); + if rects.is_empty() + && let Some(caret) = block.caret_rect(DocPoint::new(id, r.start as u64).caret) + { + rects.push(caret); + } + rects.into_iter().map(|r| self.screen_rect(r, w)).collect() + } + fn character_index_for_point( + &mut self, + p: Point, + w: &mut Window, + _: &mut Context, + ) -> Option { + let p = self.input_point(p, w)?; + (self.editor.selection.as_ref()?.focus.block_id == p.block_id) + .then_some(p.offset() as usize) + } +} + +fn paragraph() -> BlockSpec { + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: String::new(), + } +} +fn list(kind: ListType, checked: bool, order: Option) -> BlockSpec { + BlockSpec::List { + list_type: kind, + text: String::new(), + checked, + order, + } +} +fn markdown_block(input: &str) -> Option { + let spec = match input { + "# " => "h1", + "## " => "h2", + "### " => "h3", + "#### " => "h4", + "##### " => "h5", + "###### " => "h6", + "> " => "quote", + "- " | "* " => return Some(list(ListType::Bulleted, false, None)), + s if s.ends_with(". ") => { + let digits = s.strip_suffix(". ")?; + if !digits.bytes().all(|c| c.is_ascii_digit()) { + return None; + } + let order = digits.parse::().ok().filter(|n| *n >= 0)?; + return Some(list(ListType::Numbered, false, Some(order))); + } + "[] " | "[ ] " => return Some(list(ListType::Todo, false, None)), + "[x] " => return Some(list(ListType::Todo, true, None)), + s if s.strip_suffix(char::is_whitespace).is_some_and(|run| { + run.len() >= 3 + && matches!(run.as_bytes()[0], b'-' | b'*' | b'_') + && run.bytes().all(|b| b == run.as_bytes()[0]) + }) => + { + return Some(BlockSpec::Divider); + } + s if s.starts_with("```") && s.ends_with([' ', '\n']) => { + let language = &s[3..s.len() - 1]; + if !language + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '#' | '.' | '-')) + { + return None; + } + return Some(BlockSpec::Code { + text: String::new(), + language: (!language.is_empty()).then(|| language.into()), + caption: String::new(), + }); + } + _ => return None, + }; + Some(BlockSpec::Paragraph { + paragraph_type: match spec { + "h1" => ParagraphType::H1, + "h2" => ParagraphType::H2, + "h3" => ParagraphType::H3, + "h4" => ParagraphType::H4, + "h5" => ParagraphType::H5, + "h6" => ParagraphType::H6, + _ => ParagraphType::Quote, + }, + text: String::new(), + }) +} + +impl PlaygroundView { + fn fresh_block_id(&mut self) -> String { + loop { + self.editor.next_id += 1; + let id = format!( + "native-{:x}-{:x}", + self.state.awareness.local_client_id(), + self.editor.next_id + ); + if self.page_snapshot().is_none_or(|s| s.block(&id).is_none()) { + return id; + } + } + } + fn history(&mut self, redo: bool, w: &mut Window, cx: &mut Context) -> DocResult { + let sel = self.editor.selection.clone(); + let page = self.page_mut()?; + let opposite = sel.and_then(|s| s.snapshot(page).ok()); + page.stop_capturing()?; + let commit = if redo { page.redo()? } else { page.undo()? }; + let Some(commit) = commit else { return Ok(()) }; + if let Some(other) = opposite { + let stack = if redo { + y_octo::UndoStack::Undo + } else { + y_octo::UndoStack::Redo + }; + page.inner() + .set_stack_selection_meta(page.undo_stack_id(), stack, other)?; + } + let restored = commit + .selection_meta + .as_ref() + .map(|s| page.resolve_selection_snapshot(s)) + .transpose()? + .flatten(); + if let Some(s) = restored { + self.editor.selection = Some(DocumentSelection { + anchor: DocPoint::new(s.anchor.0, s.anchor.1), + focus: DocPoint::new(s.focus.0, s.focus.1), + }); + } + self.editor.last_typing = None; + self.editor.preedit = None; + self.did_edit(Some(commit), None, w, cx); + Ok(()) + } + fn insertion_marks(&self, point: &DocPoint) -> DocResult { + let offset = point.offset(); + if offset == 0 { + return Ok(TextAttributes::new()); + } + let (rich, _) = self + .page() + .ok_or_else(|| DocError::InvalidState("missing page".into()))? + .read_editable_text(&point.block_id)?; + let mut cursor = 0; + for op in rich.delta { + if let TextDeltaOp::Insert { insert, format } = op { + cursor += match &insert { + TextInsert::Text(s) => s.encode_utf16().count(), + TextInsert::Embed(v) => v.len(), + } as u64; + if offset <= cursor { + if matches!(insert, TextInsert::Embed(_)) + || format + .as_ref() + .is_some_and(|attrs| attrs.contains_key("reference")) + { + break; + } + let mut marks = format.unwrap_or_default(); + if offset == cursor { + marks.remove("code"); + marks.remove("link"); + } + return Ok(marks); + } + } + } + Ok(TextAttributes::new()) + } + + fn format_mark(&mut self, key: &str, w: &mut Window, cx: &mut Context) -> DocResult { + let Some(sel) = self.editor.selection.clone() else { + return Ok(()); + }; + if sel.empty() { + let inherited = self.insertion_marks(&sel.focus)?; + let on = self.editor.pending_marks.get(key).map_or_else( + || inherited.get(key) == Some(&Any::True), + |v| *v == Some(Any::True), + ); + self.editor + .pending_marks + .insert(key.into(), (!on).then_some(Any::True)); + 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 page = self.page_mut()?; + let mut ranges = Vec::new(); + let mut marked = true; + 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 (rich, _) = page.read_editable_text(id)?; + let (_, tail) = split_delta(&rich.delta, from)?; + let (part, _) = split_delta(&tail, to - from)?; + marked &= part.iter().all(|op|matches!(op,TextDeltaOp::Insert{format:Some(f),..} if f.get(key)==Some(&Any::True))); + let prop = if matches!(block.body.kind, block_flow::FlowKind::Title) { + "prop:title" + } else { + "prop:text" + }; + ranges.push((id, prop, from, to - from)); + } + let snap = sel.snapshot(page)?; + page.stop_capturing()?; + let commit = page.structural_edit(now, |page| { + for (id, prop, from, n) in ranges { + page.format_text( + id, + prop, + from, + n, + TextAttributes::from([( + key.to_owned(), + if marked { Any::Null } else { Any::True }, + )]), + 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), w, cx); + Ok(()) + } + fn edit_key( + &mut self, + key: &str, + shift: bool, + w: &mut Window, + cx: &mut Context, + ) -> DocResult { + let Some(sel) = self.editor.selection.clone() else { + return Ok(()); + }; + let id = sel.focus.block_id.clone(); + let offset = sel.focus.offset(); + let Some(snapshot) = self.snapshot.clone() else { + return Ok(()); + }; + let Some(node) = snapshot.block(&id) else { + return Ok(()); + }; + let text = text_content(node).unwrap_or(""); + let n = text.encode_utf16().count() as u64; + let code = matches!(node.content, BlockContent::Code { .. }); + let backwards = key == "backspace"; + let now = self.now_ms(cx) as u64; + if key == "enter" && !sel.empty() && !shift && !code { + return self.paste_slice(crate::clipboard::Slice::from_plain("\n"), false, w, cx); + } + if key == "tab" && code { + return self.replace_selection(sel, " ", w, cx); + } + if key == "enter" && !shift && self.apply_markdown(&sel, "\n", w, cx)? { + return Ok(()); + } + if key == "enter" && (shift || code) { + return self.replace_selection(sel, "\n", w, cx); + } + if matches!(key, "backspace" | "delete") + && (!sel.empty() || (backwards && offset > 0) || (!backwards && offset < n)) + { + let range = if !sel.empty() { + sel.clone() + } else { + let idx = TextBiIndex::new(text); + let next = if backwards { + idx.prev_grapheme_utf16(offset) + } else { + idx.next_grapheme_utf16(offset) + }; + DocumentSelection { + anchor: sel.focus.clone(), + focus: DocPoint::new(&id, next), + } + }; + let before = sel.snapshot(self.page_mut()?)?; + self.editor.last_typing = None; + self.replace_selection(range, "", w, cx)?; + self.page_mut()?.set_undo_selection_snapshot(before)?; + self.editor.last_typing = None; + return Ok(()); + } + let before = sel.snapshot(self.page_mut()?)?; + let mut focus = sel.focus.clone(); + let demote = matches!( + node.content, + BlockContent::List { .. } + | BlockContent::Paragraph { + kind: ParagraphType::Quote, + .. + } + ) && ((text.is_empty() && key == "enter") || (backwards && offset == 0)) + || (backwards + && offset == 0 + && matches!(node.content,BlockContent::Paragraph {kind,..} if kind!=ParagraphType::Text)); + let last_nested = backwards + && offset == 0 + && !code + && parent_of(&snapshot, &id).is_some_and(|(parent, pos)| { + matches!( + parent.content, + BlockContent::List { .. } | BlockContent::Paragraph { .. } + ) && pos + 1 == parent.children.len() + }); + let commit = if last_nested { + self.page_mut()?.dedent_block(&id, now)? + } else if demote { + let fresh = self.fresh_block_id(); + if node.flavour != "affine:paragraph" { + focus = DocPoint::new(&fresh, offset); + } + self.page_mut()? + .convert_block_flavour(&id, &fresh, paragraph(), now)? + } else if key == "tab" { + let Some((parent, pos)) = parent_of(&snapshot, &id) else { + return Ok(()); + }; + let dest = if shift { + if !matches!( + parent.content, + BlockContent::List { .. } | BlockContent::Paragraph { .. } + ) { + return Ok(()); + } + parent_of(&snapshot, &parent.id).map(|(p, i)| (&p.id, i + 1)) + } else { + pos.checked_sub(1) + .and_then(|i| parent.children.get(i)) + .filter(|b| { + matches!( + b.content, + BlockContent::List { .. } | BlockContent::Paragraph { .. } + ) + }) + .map(|b| (&b.id, b.children.len())) + }; + let Some((dest, index)) = dest else { + return Ok(()); + }; + if shift { + self.page_mut()?.dedent_block(&id, now)? + } else { + self.page_mut()? + .reparent_block(&id, &parent.id, dest, index as u64, now)? + } + } else if key == "enter" { + let spec = match &node.content { + BlockContent::Paragraph { kind, .. } if offset < n => BlockSpec::Paragraph { + paragraph_type: *kind, + text: String::new(), + }, + BlockContent::List { kind, order, .. } => list( + *kind, + false, + order + .and_then(|i| i.checked_add(1)) + .and_then(|i| i32::try_from(i).ok()), + ), + _ => paragraph(), + }; + let new_id = self.fresh_block_id(); + focus = DocPoint::new(&new_id, 0); + self.page_mut()? + .split_text_block(&id, &new_id, offset, spec, now)? + } else { + let Some(layout) = self.flow_layout() else { + return Ok(()); + }; + let Some(i) = layout.blocks.iter().position(|b| b.block_id == id) else { + return Ok(()); + }; + let adjacent = if backwards { + layout.blocks[..i].last() + } else { + layout.blocks.get(i + 1) + }; + let Some(adjacent) = adjacent else { + return Ok(()); + }; + let nesting = parent_of(&snapshot, &id).filter(|(p, _)| { + matches!( + p.content, + BlockContent::Paragraph { .. } | BlockContent::List { .. } + ) + }); + let mergeable = !code + && adjacent.editable() + && !matches!(adjacent.body.kind, block_flow::FlowKind::Code); + if backwards && !code && !mergeable && nesting.is_some() { + self.page_mut()?.dedent_block(&id, now)? + } else if !mergeable { + if !backwards + || !text.is_empty() + || code + || !parent_of(&snapshot, &id).is_some_and(|(p, _)| p.children.len() > 1) + { + return Ok(()); + } + let Some(next) = layout.blocks[..i] + .iter() + .rev() + .chain(&layout.blocks[i + 1..]) + .find(|b| b.editable()) + else { + return Ok(()); + }; + focus = DocPoint::new( + &next.block_id, + if next.y < layout.blocks[i].y { + next.body.plain.encode_utf16().count() as u64 + } else { + 0 + }, + ); + self.page_mut()?.remove_lifting_children(&id, now)? + } else { + let (target, source) = if backwards { + (&adjacent.block_id, &id) + } else { + (&id, &adjacent.block_id) + }; + let Some((parent, _)) = parent_of(&snapshot, source) else { + return Ok(()); + }; + let (join, commit) = self + .page_mut()? + .merge_with_previous_text_block(target, source, &parent.id, now)?; + focus = DocPoint::new(target, join); + commit + } + }; + if commit.is_some() { + self.page_mut()?.set_undo_selection_snapshot(before)?; + } + self.editor.selection = Some(DocumentSelection::caret(focus)); + self.editor.last_typing = None; + self.did_edit(commit, None, w, cx); + Ok(()) + } + + pub(super) fn editor_key_down( + &mut self, + e: &KeyDownEvent, + w: &mut Window, + cx: &mut Context, + ) { + if self.editor.preedit.is_some() || e.prefer_character_input { + return; + } + let m = e.keystroke.modifiers; + let cmd = m.secondary(cx); + let key = e.keystroke.key.as_str(); + let result = match key { + "left" | "right" | "up" | "down" | "home" | "end" => { + self.navigate( + key, + m.shift, + m.alt, + m.platform && matches!(key, "left" | "right"), + w, + cx, + ); + Ok(()) + } + "enter" | "backspace" | "delete" | "tab" => self.edit_key(key, m.shift, w, cx), + "a" if cmd => { + if let Some(sel) = self.editor.selection.clone() + && let Some(layout) = self.flow_layout() + && let Some(block) = layout.block(&sel.focus.block_id) + { + let mut anchor = DocPoint::new(&block.block_id, 0); + let mut focus = DocPoint::new( + &block.block_id, + block.body.plain.encode_utf16().count() as u64, + ); + if (sel.anchor == anchor && sel.focus == focus + || sel.focus == anchor && sel.anchor == focus) + && let Some(first) = layout.blocks.iter().find(|b| b.editable()) + && let Some(last) = layout.blocks.iter().rfind(|b| b.editable()) + { + anchor = DocPoint::new(&first.block_id, 0); + focus = DocPoint::new( + &last.block_id, + last.body.plain.encode_utf16().count() as u64, + ); + } + self.change_selection(DocumentSelection { anchor, focus }, w, cx); + } + Ok(()) + } + "c" | "x" if cmd => { + if let Some(slice) = self.clipboard_slice() { + crate::clipboard::write_slice(&slice, cx); + if key == "x" { + self.edit_key("backspace", false, w, cx) + } else { + Ok(()) + } + } else { + Ok(()) + } + } + "v" if cmd => { + if let Some(item) = cx.read_from_clipboard() { + self.paste(item, w, cx); + } else { + return; + } + Ok(()) + } + "z" if cmd => self.history(m.shift, w, cx), + "y" if cmd => self.history(true, w, cx), + "b" | "i" | "u" | "e" | "s" if cmd && (key != "s" || m.shift) => self.format_mark( + match key { + "b" => "bold", + "i" => "italic", + "u" => "underline", + "e" => "code", + _ => "strike", + }, + w, + cx, + ), + _ => return, + }; + if let Err(e) = result { + eprintln!("document command {key}: {e}"); + } + w.prevent_default(); + cx.stop_propagation(); + } +} + +impl PlaygroundView { + fn clipboard_slice(&self) -> Option { + let sel = self.editor.selection.as_ref()?; + if sel.empty() { + return None; + } + let layout = self.flow_layout()?; + let (start, end, _, _, _) = sel.ordered(&layout)?; + let snapshot = self.page_snapshot()?; + let page = self.page()?; + let range = RangeBlocks::between(snapshot, &start.block_id, &end.block_id)?; + let mut ids: BTreeSet<_> = range.intermediate.iter().map(String::as_str).collect(); + ids.extend([start.block_id.as_str(), end.block_id.as_str()]); + let root = snapshot.root.as_ref()?; + let mut selected = BTreeMap::new(); + let content = + std::iter::once(root).chain(page_content_roots(root).flat_map(BlockNode::walk)); + for node in content.filter(|n| ids.contains(n.id.as_str())) { + let delta = if text_content(node).is_some() { + let (rich, _) = page.read_editable_text(&node.id).ok()?; + let from = if node.id == start.block_id { + start.offset() + } else { + 0 + }; + let (_, tail) = split_delta(&rich.delta, from).ok()?; + if node.id == end.block_id { + split_delta(&tail, end.offset() - from).ok()?.0 + } else { + tail + } + } else { + Vec::new() + }; + selected.insert( + node.id.clone(), + crate::clipboard::SliceBlock::from_node( + node, + page.export_slice_props(&node.id).ok()?, + &delta, + ), + ); + } + let mut blocks: Vec<_> = selected.remove(&root.id).into_iter().collect(); + for child in page_content_roots(root) { + crate::clipboard::SliceBlock::keep_selected(child, &mut selected, &mut blocks); + } + Some(crate::clipboard::Slice::new( + self.state.workspace.room(), + self.page_id.as_deref()?, + blocks, + )) + } + fn paste_slice( + &mut self, + mut slice: crate::clipboard::Slice, + rich: bool, + w: &mut Window, + cx: &mut Context, + ) -> DocResult { + let Some(sel) = self.editor.selection.clone() else { + return Ok(()); + }; + let Some(layout) = self.flow_layout() else { + return Ok(()); + }; + let Some((start, end, a, b, _)) = sel.ordered(&layout) else { + return Ok(()); + }; + if slice.content.is_empty() { + return Ok(()); + } + if matches!(layout.blocks[a].body.kind, block_flow::FlowKind::Code) { + return self.replace_selection(sel, &slice.plain(), w, cx); + } + let now = self.now_ms(cx) as u64; + let from = start.offset(); + let id = start.block_id.clone(); + let snapshot = self + .snapshot + .clone() + .ok_or_else(|| DocError::InvalidState("missing document".into()))?; + let node = snapshot + .block(&id) + .ok_or_else(|| DocError::BlockNotFound(id.clone()))?; + let title = matches!(node.content, BlockContent::Page { .. }); + let key = if title { "prop:title" } else { "prop:text" }; + let empty = a == b + && text_content(node) + .is_some_and(|s| s.encode_utf16().count() as u64 == end.offset() - from); + let first = &slice.content[0]; + let use_existing = + first.editable() && (!rich || !empty || first.flavour == node.flavour || title); + let discard_empty = !use_existing && empty && !title; + if !slice.content.last().is_some_and(|b| b.editable()) { + slice + .content + .push(crate::clipboard::SliceBlock::plain_block( + "", + slice.content.len(), + )); + } + let dest = if title { + node.children + .iter() + .find(|n| n.is_page_visible_note()) + .map(|n| (n.id.clone(), 0)) + } else { + parent_of(&snapshot, &id) + .map(|(p, slot)| (p.id.clone(), slot + usize::from(!discard_empty))) + }; + if dest.is_none() + && (slice.content.len() > 1 || !use_existing || !slice.content[0].children.is_empty()) + { + return Err(DocError::InvalidState("no parent for pasted blocks".into())); + } + let blocks = RangeBlocks::between(&snapshot, &id, &end.block_id) + .ok_or_else(|| DocError::InvalidState("selection outside page content".into()))?; + let keep_suffix = + slice.content.len() == 1 && use_existing && slice.content[0].children.is_empty(); + let count = slice + .content + .iter() + .map(|b| b.walk().count()) + .sum::(); + let fresh: Vec<_> = (0..count).map(|_| self.fresh_block_id()).collect(); + let mut next = fresh.iter(); + let mut roots = Vec::new(); + let mut entries = Vec::new(); + for (i, block) in slice.content.iter().enumerate() { + let mut pending = vec![(block, None)]; + while let Some((block, parent)) = pending.pop() { + let new_id = next + .next() + .ok_or_else(|| DocError::InvalidState("missing paste id".into()))?; + let existing = i == 0 && parent.is_none() && use_existing; + let target = if existing { id.clone() } else { new_id.clone() }; + if parent.is_none() { + roots.push(target.clone()); + } + entries.push((block, target.clone(), parent, existing, block.properties()?)); + pending.extend( + block + .children + .iter() + .rev() + .map(|b| (b, Some(target.clone()))), + ); + } + } + let last_id = roots + .last() + .cloned() + .ok_or_else(|| DocError::InvalidState("empty paste".into()))?; + let last = slice + .content + .last() + .ok_or_else(|| DocError::InvalidState("empty paste".into()))?; + let last_pos = + last.plain().encode_utf16().count() as u64 + if last_id == id { from } else { 0 }; + let page = self.page_mut()?; + let before = sel.snapshot(page)?; + let commit = page.structural_edit(now, |page| { + if a != b { + page.delete_cross_block_range( + (&id, from), + (&end.block_id, end.offset()), + &blocks.intermediate, + &blocks.survivors, + now, + )?; + } else if end.offset() > from { + page.remove_text(&id, key, from, end.offset() - from, now)?; + } + let suffix = if keep_suffix { + Vec::new() + } else { + let (original, _) = page.read_editable_text(&id)?; + let (_, suffix) = split_delta(&original.delta, from)?; + let suffix_len = original.plain.encode_utf16().count() as u64 - from; + if suffix_len > 0 { + page.remove_text(&id, key, from, suffix_len, now)?; + } + suffix + }; + let mut index = dest.as_ref().map_or(0, |(_, i)| *i); + for (block, target, parent, existing, props) in entries { + if existing { + if rich && empty && !title { + for (k, v) in props.iter().filter(|(k, _)| k != "prop:text") { + page.set_block_prop(&target, k, v.clone(), now)?; + } + } + let mut delta = vec![TextDeltaOp::Retain { + retain: from, + format: None, + }]; + delta.extend(block.delta()); + page.apply_text_delta(&target, key, &delta, now)?; + } else { + let root_parent = dest.as_ref().map(|(id, _)| id.as_str()); + let p = parent.as_deref().or(root_parent).ok_or_else(|| { + DocError::InvalidState("missing paste destination".into()) + })?; + let at = parent.is_none().then_some(index as u64); + if at.is_some() { + index += 1; + } + let flavour = if block.flavour == "affine:page" { + "affine:paragraph" + } else { + &block.flavour + }; + page.add_raw_block( + &target, + flavour, + block + .version + .and_then(|n| i32::try_from(n).ok()) + .unwrap_or(1), + props, + Some(p), + at, + now, + )?; + } + } + if discard_empty { + page.remove_lifting_children(&id, now)?; + } + if !suffix.is_empty() { + let mut delta = vec![TextDeltaOp::Retain { + retain: last_pos, + format: None, + }]; + delta.extend(suffix); + page.apply_text_delta( + &last_id, + if last_id == id { key } else { "prop:text" }, + &delta, + now, + )?; + } + Ok(()) + })?; + if commit.is_some() { + page.set_undo_selection_snapshot(before)?; + } + self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(last_id, last_pos))); + self.editor.last_typing = None; + self.did_edit(commit, None, w, cx); + Ok(()) + } +} diff --git a/blocksuite/native-playground/crates/playground/src/lib.rs b/blocksuite/native-playground/crates/playground/src/lib.rs index 9a76f2764c..52f7d8dd6b 100644 --- a/blocksuite/native-playground/crates/playground/src/lib.rs +++ b/blocksuite/native-playground/crates/playground/src/lib.rs @@ -5,6 +5,8 @@ //! rendered by [`block_flow`]. pub mod block_flow; +pub mod clipboard; +pub mod editor_session; pub mod rich_text; pub mod room_client; pub mod theme; @@ -173,6 +175,9 @@ pub struct PlaygroundView { theme: PlaygroundTheme, origin_time: ui::scheduler::Instant, pill_motion: Option, + editor: editor_session::EditorSession, + editor_focus: ui::FocusHandle, + reading_anchor: Option<(String, f32)>, state: DocState, room: Option, page_id: Option, @@ -182,6 +187,7 @@ pub struct PlaygroundView { /// from its blob and is final. images: HashMap, blob_fetches: BTreeMap, + dirty_text: Option>, doc_rev: u64, env_rev: u64, flow: BlockFlow, @@ -253,11 +259,15 @@ impl PlaygroundView { pill_motion: None, state, room, + editor: Default::default(), + editor_focus: cx.focus_handle(), + reading_anchor: None, page_id: None, snapshot: None, page_titles: BTreeMap::new(), images: HashMap::new(), blob_fetches: BTreeMap::new(), + dirty_text: None, doc_rev: 0, env_rev: 0, flow: BlockFlow::new(), @@ -292,6 +302,10 @@ impl PlaygroundView { /// Replace the shown document, e.g. with one prepared by a host or a test. pub fn set_document(&mut self, state: DocState, cx: &mut Context) { + self.editor = Default::default(); + self.reading_anchor = None; + self.flow = BlockFlow::new(); + self.layout = None; self.state = state; self.images.clear(); self.blob_fetches.clear(); @@ -306,8 +320,10 @@ impl PlaygroundView { cx: &mut Context, edit: impl FnOnce(&mut DocState) -> R, ) -> R { + self.capture_reading_anchor(); let result = edit(&mut self.state); self.refresh_document(); + self.resolve_remote_selection(cx); cx.notify(); result } @@ -416,7 +432,9 @@ impl PlaygroundView { room.link.send(RoomCommand::Send(frame)); } if effects.doc_changed { + self.capture_reading_anchor(); self.refresh_document(); + self.resolve_remote_selection(cx); } } Err(err) => room.error = Some(err.to_string()), @@ -448,8 +466,24 @@ impl PlaygroundView { } } + pub fn scroll_offset(&self) -> f32 { + self.scroll_y + } + 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. fn refresh_document(&mut self) { + self.dirty_text = None; let pages = self.state.workspace.list_pages().unwrap_or_default(); let titles: BTreeMap = pages .iter() @@ -634,7 +668,13 @@ impl PlaygroundView { { return Some(layout.clone()); } - let layout = Rc::new(self.flow.layout( + let snapshot = self.preedit_snapshot().map(Rc::new).unwrap_or(snapshot); + let 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) + }); + let layout = Rc::new(self.flow.layout_changed( &FlowInput { snapshot: &snapshot, width, @@ -644,7 +684,9 @@ impl PlaygroundView { env_rev: self.env_rev, }, window, + dirty.as_ref(), )); + self.dirty_text = Some(BTreeSet::new()); self.layout = Some((key, layout.clone())); Some(layout) } @@ -945,6 +987,9 @@ impl PlaygroundView { window: &mut Window, cx: &mut Context, ) -> AnyElement { + if window.focused(cx).is_none() { + self.editor_focus.focus(window, cx); + } let geometry = page_geometry(viewport_width); let surface = div() .id("page-viewport") @@ -954,6 +999,10 @@ impl PlaygroundView { .min_h_0() .overflow_hidden() .bg(palette.background) + .track_focus(&self.editor_focus) + .on_mouse_down(ui::MouseButton::Left, cx.listener(Self::editor_mouse_down)) + .on_mouse_move(cx.listener(Self::editor_mouse_move)) + .on_key_down(cx.listener(Self::editor_key_down)) .on_scroll(cx.listener(Self::on_scroll)) .snapshot(PAGE_SURFACE_ID, Some("root.canvas")); @@ -965,7 +1014,21 @@ impl PlaygroundView { .into_any_element(); }; self.max_scroll = (layout.height - viewport_height).max(0.0).ceil(); - self.scroll_y = self.scroll_y.clamp(0.0, self.max_scroll).round(); + if let Some((id, screen_y)) = self.reading_anchor.take() + && let Some(block) = layout.block(&id) + { + self.scroll_y = (block.y - screen_y).round(); + } + self.reveal_caret(viewport_height); + self.scroll_y = self.scroll_y.clamp(0.0, self.max_scroll); + let viewport = PageViewport { + column_x: geometry.column_x, + height: viewport_height, + scroll_y: self.scroll_y, + }; + let local = self.local_selection_elements(&layout, viewport, palette); + let focus = self.editor_focus.clone(); + let entity = cx.entity(); let marks = layout.presence_marks(presences, palette, window); surface .children(page_elements( @@ -977,6 +1040,21 @@ impl PlaygroundView { scroll_y: self.scroll_y, }, )) + .children(local) + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, cx| { + window.handle_input( + &focus, + ui::ElementInputHandler::new(bounds, entity), + cx, + ) + }, + ) + .absolute() + .size_full(), + ) .into_any_element() } @@ -1560,6 +1638,10 @@ pub fn seed_showcase_doc() -> DocResult { .insert(SHOWCASE_IMAGE_ID.to_string(), Arc::new(image)); } + let page = state.workspace.ensure_page(HOME_PAGE_ID)?; + let history = page.undo_stack_id(); + page.inner_mut().clear_stack_history(history, true, true)?; + // One remote collaborator selecting the first words of the intro paragraph, which // stay on its first line at every viewport width. let mut peer = RoomAwareness::new(client_id_from_seed(0x0ada))?; @@ -1624,6 +1706,7 @@ fn web_options() -> PlaygroundOptions { #[wasm_bindgen::prelude::wasm_bindgen(start)] pub fn wasm_main() { console_error_panic_hook::set_once(); + clipboard::browser::install(); 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) { @@ -3152,6 +3235,101 @@ mod tests { ); } + #[test] + fn typing_preedit_awareness_and_local_undo_reach_two_live_views() { + use crate::editor_session::{DocPoint, DocumentSelection}; + use ui::EntityInputHandler; + let rt = relay_runtime(); + let addr = start_relay(&rt); + let room = "room-live-editor"; + let mut seed = relay_page_peer(room, client_id_from_seed(92)); + let _socket = join_as_peer(&rt, addr, room, &mut seed); + let options = PlaygroundOptions { + room: Some(RoomConfig::new(room, Some(&format!("ws://{addr}")))), + ..Default::default() + }; + let first = open(800, 600, options.clone()); + let second = open(800, 600, options); + for session in [&first, &second] { + wait_for(session, "the initial editable page", |v| { + v.room_status() == Some(RoomStatus::Live) + && v.page_snapshot().and_then(|p| p.block("p-1")).is_some() + }); + session.frame(); + } + let edit = + |s: &Session, f: fn(&mut PlaygroundView, &mut Window, &mut Context)| { + s.app.update(|cx| s.window.update(cx, f)).unwrap(); + }; + fn select( + v: &mut PlaygroundView, + offset: u64, + w: &mut Window, + cx: &mut Context, + ) { + let p = DocPoint::new("p-1", offset); + v.select_document_range( + DocumentSelection { + anchor: p.clone(), + focus: p, + }, + w, + cx, + ); + } + let first_id = first.view(|v, _| v.document().awareness.local_client_id()); + edit(&first, |v, w, cx| { + select(v, 1, w, cx); + v.replace_and_mark_text_in_range(None, "private-preedit", None, w, cx); + }); + wait_for(&second, "the first native selection", |v| { + v.document() + .awareness + .get_payload(first_id) + .is_some_and(|p| { + p.selection_v2 + .get(&format!("{HOME_PAGE_ID}:native")) + .is_some_and(|s| s[0]["from"]["index"] == 1) + }) + }); + let text_is = |v: &PlaygroundView, s: &str| matches!(&v.page_snapshot().unwrap().block("p-1").unwrap().content,BlockContent::Paragraph{text,..} if text.plain==s); + assert!(second.view(|v, _| text_is(v, "Hello from the relay"))); + edit(&first, |v, w, cx| v.replace_text_in_range(None, "L", w, cx)); + wait_for(&second, "the first native edit", |v| { + text_is(v, "HLello from the relay") + }); + edit(&second, |v, w, cx| { + select(v, 0, w, cx); + v.replace_text_in_range(None, "R", w, cx); + }); + wait_for(&first, "the interleaved peer edit", |v| { + text_is(v, "RHLello from the relay") + }); + first.frame(); + first + .headless + .dispatch_input(ui::PlatformInput::KeyDown(ui::KeyDownEvent { + keystroke: ui::Keystroke { + key: "z".into(), + key_char: None, + modifiers: ui::Modifiers { + platform: true, + control: true, + ..Default::default() + }, + }, + is_held: false, + prefer_character_input: false, + })); + wait_for(&second, "the first editor's undo", |v| { + text_is(v, "RHello from the relay") + }); + assert_eq!( + first.view(|v, _| v.document_selection().unwrap().focus.caret.utf16_offset), + 2 + ); + } + #[test] fn a_blob_uploaded_after_its_image_block_is_fetched_by_capped_retries() { let runtime = relay_runtime(); diff --git a/blocksuite/native-playground/crates/playground/src/room_client.rs b/blocksuite/native-playground/crates/playground/src/room_client.rs index d44afa45f8..1f00d303cd 100644 --- a/blocksuite/native-playground/crates/playground/src/room_client.rs +++ b/blocksuite/native-playground/crates/playground/src/room_client.rs @@ -231,7 +231,10 @@ impl RoomProtocol { self.sync.clear(); self.ready.clear(); - let payload = AwarenessPayload::new(LOCAL_AWARENESS_NAME, LOCAL_AWARENESS_COLOR); + let payload = state + .awareness + .get_payload(state.awareness.local_client_id()) + .unwrap_or_else(|| AwarenessPayload::new(LOCAL_AWARENESS_NAME, LOCAL_AWARENESS_COLOR)); // On a reconnect the relay holds a tombstone for this client that the presence // has to outrank. let awareness = if std::mem::replace(&mut self.has_opened, true) { @@ -441,6 +444,12 @@ impl RoomLink { &self.events } + pub(crate) fn send_binary(&self, frame: RoomBinaryFrame) { + if let Ok(frame) = binary(&frame) { + self.send(RoomCommand::Send(frame)); + } + } + pub fn send(&self, command: RoomCommand) { (self.commands)(command); } diff --git a/blocksuite/native-playground/crates/ui/src/platform/macos/pasteboard.rs b/blocksuite/native-playground/crates/ui/src/platform/macos/pasteboard.rs index a7c21a8331..324bb1fb5e 100644 --- a/blocksuite/native-playground/crates/ui/src/platform/macos/pasteboard.rs +++ b/blocksuite/native-playground/crates/ui/src/platform/macos/pasteboard.rs @@ -120,16 +120,15 @@ impl Pasteboard { } fn read_string_from_pasteboard(&self) -> Option { - let pasteboard_types = self.inner.types()?; - let string_type = NSString::from_str("public.utf8-plain-text"); - - if !pasteboard_types.containsObject(&string_type) { + let html_type = NSString::from_str("public.html"); + let html = self + .data_for_type(&html_type) + .and_then(|v| String::from_utf8(v).ok()); + let bytes = self.data_for_type(&NSString::from_str("public.utf8-plain-text")); + if bytes.is_none() && html.is_none() { return None; } - - let text_bytes = self.data_for_type(&string_type)?; - - let text = String::from_utf8_lossy(&text_bytes).to_string(); + let text = String::from_utf8_lossy(bytes.as_deref().unwrap_or_default()).into_owned(); let metadata = self .data_for_type(&self.text_hash_type) .and_then(|hash_bytes| { @@ -142,7 +141,8 @@ impl Pasteboard { } else { None } - }); + }) + .or_else(|| html.map(|html| serde_json::json!({"text/html":html}).to_string())); Some(ClipboardEntry::String(ClipboardString { text, metadata })) } @@ -203,6 +203,14 @@ impl Pasteboard { .setData_forType(Some(&text_bytes), NSPasteboardTypeString); if let Some(metadata) = string.metadata.as_ref() { + if let Ok(value) = serde_json::from_str::(metadata) + && let Some(html) = value["text/html"].as_str() + { + self.inner.setData_forType( + Some(&NSData::with_bytes(html.as_bytes())), + &NSString::from_str("public.html"), + ); + } let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes(); let hash_bytes = NSData::with_bytes(&hash_bytes); self.inner @@ -294,3 +302,32 @@ impl UTType { &self.0 } } + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn html_on_a_private_pasteboard_survives_plain_text_changes() { + let board = + Pasteboard::new(unsafe { msg_send![class!(NSPasteboard), pasteboardWithUniqueName] }); + let html = "

    linked page

    "; + board.write(ClipboardItem::new_string_with_json_metadata( + "linked page".into(), + serde_json::json!({"text/html":html,"reference":"page-id"}), + )); + let ty = NSString::from_str("public.html"); + assert_eq!(board.data_for_type(&ty).as_deref(), Some(html.as_bytes())); + let read_metadata = || -> serde_json::Value { + serde_json::from_str(board.read().unwrap().metadata().unwrap()).unwrap() + }; + assert_eq!(read_metadata()["reference"], "page-id"); + board.inner.clearContents(); + board + .inner + .setData_forType(Some(&NSData::with_bytes(html.as_bytes())), &ty); + assert_eq!(read_metadata()["text/html"], html); + unsafe { + let _: () = msg_send![&*board.inner, releaseGlobally]; + } + } +} diff --git a/blocksuite/native-playground/crates/ui/src/platform/web/events.rs b/blocksuite/native-playground/crates/ui/src/platform/web/events.rs index bd12faaeef..bffe870c1c 100644 --- a/blocksuite/native-playground/crates/ui/src/platform/web/events.rs +++ b/blocksuite/native-playground/crates/ui/src/platform/web/events.rs @@ -928,6 +928,9 @@ impl WebWindowInner { } this.ime_mirror.adopt_element_state(); + // A block-scoped handler can replace a document selection extending outside + // this textarea. Recheck its window after the import has adopted the DOM edit. + this.schedule_ime_mirror_sync(); }) } diff --git a/blocksuite/native-playground/perf/accepted.json b/blocksuite/native-playground/perf/accepted.json index 97c47755ad..c238b3079f 100644 --- a/blocksuite/native-playground/perf/accepted.json +++ b/blocksuite/native-playground/perf/accepted.json @@ -1,17 +1,17 @@ [ { "metric": "artifacts_bytes.web_wasm_raw", - "accepted_value": 14831945, - "reason": "Links blocksuite-playground-doc, 4 IBM Plex Mono faces, image decoders, RichParagraph, BlockFlow, and native/Web room sync client into playground" + "accepted_value": 15645011, + "reason": "Includes collaborative page editing, IME composition and rich clipboard support in the Web playground" }, { "metric": "artifacts_bytes.web_wasm_gzip", - "accepted_value": 5016905, - "reason": "Links blocksuite-playground-doc, 4 IBM Plex Mono faces, image decoders, RichParagraph, BlockFlow, and native/Web room sync client into playground" + "accepted_value": 5264224, + "reason": "Includes collaborative page editing, IME composition and rich clipboard support in the Web playground" }, { "metric": "artifacts_bytes.headless_bin", - "accepted_value": 92078597, - "reason": "Links blocksuite-playground-doc, 4 IBM Plex Mono faces, image decoders, RichParagraph, BlockFlow, and native/Web room sync client into playground" + "accepted_value": 95194982, + "reason": "Includes the collaborative page editor, rich clipboard, document probes and headless renderer" } ] diff --git a/blocksuite/native-playground/scripts/web-smoke.mjs b/blocksuite/native-playground/scripts/web-smoke.mjs index b01599e5a6..8fd7108889 100755 --- a/blocksuite/native-playground/scripts/web-smoke.mjs +++ b/blocksuite/native-playground/scripts/web-smoke.mjs @@ -285,6 +285,72 @@ class CdpClient { } } +// Exercise the browser input handler through the same hidden textarea a platform IME uses. +async function checkComposition(cdp) { + async function evaluate(expression) { + const reply = await cdp.send('Runtime.evaluate', { expression, returnByValue: true }); + if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception?.description); + return reply.result.value; + } + const mirror = () => evaluate("Array.from(document.querySelectorAll('textarea')).map(t=>({value:t.value,offset:t.selectionStart}))[0]"); + const mouse = (type, [x,y], buttons) => cdp.send('Input.dispatchMouseEvent', { + type, x, y, button: type === 'mouseMoved' ? 'none' : 'left', buttons, clickCount: 1, + }); + const click = async point => { + await mouse('mousePressed',point,1); + await mouse('mouseReleased',point,0); + await sleep(100); + return mirror(); + }; + const waitValue = async value => { + let state; + for (let i=0;i<40;i++) { + state = await mirror(); + if (state.value === value) return; + await sleep(50); + } + throw new Error(`Expected mirrored block ${JSON.stringify(value)}, got ${JSON.stringify(state)}`); + }; + const composition = (type,data) => evaluate(`document.querySelector('textarea').dispatchEvent(new CompositionEvent(${JSON.stringify(type)},{bubbles:true,data:${JSON.stringify(data)}}))`); + const undo = async () => { + for (const type of ['rawKeyDown','keyUp']) { + await cdp.send('Input.dispatchKeyEvent',{type,key:'z',code:'KeyZ',modifiers:2,windowsVirtualKeyCode:90}); + } + }; + const first = [314,215], second = [331,254]; + const start = await click(first), end = await click(second); + if (start.value !== 'Page mode' || !end.value.startsWith('This page')) { + throw new Error(`Unable to select the two showcase blocks: ${JSON.stringify([start,end])}`); + } + for (const reverse of [false,true]) { + const a = reverse ? second : first, b = reverse ? first : second; + const original = reverse ? start : end; + await mouse('mousePressed',a,1); + await mouse('mouseMoved',b,1); + await mouse('mouseReleased',b,0); + await waitValue(original.value); + await composition('compositionstart',''); + await composition('compositionupdate','ni'); + await sleep(75); + await composition('compositionend',''); + await waitValue(original.value); + // Cancellation must restore the directional document range for the next IME. + await composition('compositionstart',''); + await composition('compositionupdate','nihao'); + await sleep(75); + await composition('compositionend','你好'); + const joined = token => start.value.slice(0,start.offset) + token + end.value.slice(end.offset); + await waitValue(joined('你好')); + await undo(); + await waitValue(original.value); + await cdp.send('Input.insertText',{text:'Z'}); + await waitValue(joined('Z')); + await undo(); + await waitValue(original.value); + } + console.log('Forward and backward cross-block typing, IME cancellation, commit and undo passed'); +} + async function main() { const args = parseArgs(process.argv); const pkgJs = path.join(WEB_DIR, 'pkg', 'playground.js'); @@ -422,6 +488,8 @@ async function main() { ); } + if (!args.query) await checkComposition(cdp); + // Click "Edgeless" segment (pill centered at x=640, w=186 -> pill_x=547; edgeless x=548+94..548+180 -> center=685, y=26) const clickX = 685; const clickY = 26; diff --git a/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts b/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts index 8cb936c4fc..55012c2489 100644 --- a/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts +++ b/blocksuite/playground/apps/_common/sync/room/__tests__/room-sync.spec.ts @@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'; import { resolve } from 'node:path'; import { createInterface } from 'node:readline'; +import type { ListBlockModel, RootBlockModel } from '@blocksuite/affine/model'; import { AffineSchemas } from '@blocksuite/affine/schemas'; import { TextSelection } from '@blocksuite/affine/std'; import { BlockSchemaExtension, Schema, Text } from '@blocksuite/affine/store'; @@ -339,6 +340,97 @@ describe('Rust bs-relay + WorkspaceSession <-> JS BlockSuite TestWorkspace', () await driver.quit(); }); + it('applies native structural edits to existing live block models and workspace metadata', async () => { + const room = 'live-native-structure'; + const driver = new RustDriver(relayHttp, room, 2 ** 41 + 381); + await driver.waitReady(); + const client = new RoomWebSocketClient( + `${relayWsBase}/native-sync/rooms/${room}` + ); + const workspace = new TestWorkspace({ + id: room, + docSources: { main: client.createDocSource() }, + awarenessSources: [client.createAwarenessSource()], + blobSources: { main: new MemoryBlobSource() }, + }); + workspace.storeExtensions = AffineSchemas.map(s => BlockSchemaExtension(s)); + try { + await driver.call({ + cmd: 'seed_full_schema', + page_id: 'doc:home', + title: 'Original', + }); + workspace.start(); + await vi.waitFor( + () => expect(workspace.getDoc('doc:home')).toBeTruthy(), + { timeout: 10000 } + ); + const store = workspace.getDoc('doc:home')!.getStore({ id: 'doc:home' }); + store.load(); + const model = (id: string) => store.getBlock(id)?.model; + const children = (id: string) => + model(id)?.children.map(child => child.id); + const edit = (action: string) => + driver.call({ cmd: 'structural_edit', page_id: 'doc:home', action }); + await vi.waitFor(() => + expect(model('p-2')?.flavour).toBe('affine:paragraph') + ); + await edit('convert'); + await vi.waitFor(() => { + expect(model('p-2')).toBeUndefined(); + expect(model('converted')?.flavour).toBe('affine:list'); + expect(children('note-1')?.slice(0, 2)).toEqual(['p-1', 'converted']); + }); + await edit('split'); + await vi.waitFor(() => { + expect(children('note-1')?.slice(0, 3)).toEqual([ + 'p-1', + 'converted', + 'split', + ]); + expect(store.getModelById('split')?.props.order).toBe( + 2 + ); + }); + await edit('indent'); + await vi.waitFor(() => { + expect(children('converted')).toEqual(['split']); + expect(store.getModelById('split')?.props.order).toBe( + 1 + ); + }); + await edit('outdent'); + await vi.waitFor(() => { + expect(children('converted')).toEqual([]); + expect(children('note-1')?.[2]).toBe('split'); + expect(store.getModelById('split')?.props.order).toBe( + 2 + ); + }); + await edit('merge'); + await vi.waitFor(() => { + expect(model('split')).toBeUndefined(); + expect(model('converted')?.text?.toString()).toBe( + 'Shared paragraph text' + ); + }); + await edit('title'); + await vi.waitFor(() => { + expect( + store.getModelById('page-1')?.props.title.toString() + ).toBe('Edited Original'); + expect(workspace.meta.getDocMeta('doc:home')?.title).toBe( + 'Edited Original' + ); + }); + } finally { + workspace.forceStop(); + workspace.dispose(); + client.close(); + await driver.quit(); + } + }); + it('1,000-Step Deterministic Seeded Concurrent Fuzz converges L0 (StateVector, DeleteSet, doc.json, Blob, Awareness)', async () => { const room = 'room-fuzz-1000'; const rustClientId = 2 ** 42 + 7;