Add collaborative rich-text editing to the native page

This commit is contained in:
DarkSky committed 2026-11-23 13:58:04 +09:00
1 parent bdad4ecff5
commit 222d6d6de0
17 files changed
+6164 -50

No files matched your search

+12 -2
View File
@@ -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.<blockId>`, `page.presence.<clientId>.caret|label`, `chrome.theme_toggle`, `chrome.presence.<clientId>`. 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.<blockId>`, `page.presence.<clientId>.caret|label`, `chrome.theme_toggle`, `chrome.presence.<clientId>`. 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 <room> [--relay <ws_url>]`), a browser `WebSocket` on the Web (`?room=<room>&ws=<ws_url>`), 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 `<pageId>` or `<pageId>:<managerId>` (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 `<pageId>: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 `<svg fill>` 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
@@ -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<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
@@ -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,
@@ -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 {
@@ -277,6 +277,13 @@ fn map_array_any(items: Vec<Any>) -> 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 {
@@ -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<M = SelectionSnapshot> {
@@ -45,6 +52,99 @@ pub struct PageMeta {
pub tags: Vec<String>,
}
type PageCommit = Option<SessionCommit<SelectionSnapshot>>;
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<SessionValue> {
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<TextDeltaOp>, Vec<TextDeltaOp>)> {
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<String, Vec<String>>;
fn descendants(graph: &ChildGraph, roots: impl IntoIterator<Item = String>) -> BTreeSet<String> {
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<SelectionSnapshot>` 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<Vec<u8>> {
@@ -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<Option<SessionCommit<SelectionSnapshot>>> {
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<Option<SessionCommit<SelectionSnapshot>>> {
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<Option<SessionCommit<SelectionSnapshot>>> {
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<Option<SessionCommit<SelectionSnapshot>>> {
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<Option<SessionCommit<SelectionSnapshot>>> {
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<Option<SessionCommit<SelectionSnapshot>>> {
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<Option<SessionCommit<SelectionSnapshot>>> {
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<Option<SessionCommit<SelectionSnapshot>>> {
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<ChildGraph> {
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<u64> {
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<PageCommit> {
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<PageCommit> {
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<Option<i32>> {
let block = block_target(id);
let string_is = |key, expected: &str| -> DocResult<bool> {
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<PageCommit> {
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<PageCommit> {
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<PageCommit> {
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<PageCommit> {
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<PageCommit> {
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<PageCommit> {
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<PageCommit> {
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<PageCommit> {
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<PageCommit> {
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<SelectionSnapshot> {
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<TypeTarget> {
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<Option<ResolvedSelection>> {
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<bool> {
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<JsonMap<String, JsonValue>> {
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<JsonValue> {
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::<DocResult<_>>()?,
))
}
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::<DocResult<_>>()?,
))
}
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<JsonValue> {
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<Option<SessionCommit<()>>> {
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<Vec<PageMeta>> {
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
let Ok(items) = self.root.read_array(&pages_target) else {
@@ -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(())
}
File diff suppressed because it is too large. Load diff
@@ -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<FlowRect> {
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<CaretPosition> {
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<String>>,
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<String>>,
) -> 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<BlockBody> {
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<Rc<InlineLayout>> = 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,
};
@@ -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<SliceBlock>,
}
#[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<i64>,
pub props: BTreeMap<String, Value>,
pub children: Vec<SliceBlock>,
}
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<Vec<TextDeltaOp>> {
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<String, SliceBlock>,
out: &mut Vec<SliceBlock>,
) {
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<Item = &Self> {
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<String, Value>,
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<TextDeltaOp> {
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<Vec<(String, y_octo::SessionValue)>> {
use y_octo::SessionValue;
fn value(v: &Value) -> blocksuite_playground_doc::DocResult<SessionValue> {
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::<blocksuite_playground_doc::DocResult<_>>()?,
),
Value::Array(items) => SessionValue::Array(
items
.iter()
.map(value)
.collect::<blocksuite_playground_doc::DocResult<_>>()?,
),
_ => 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}</{tag}>");
}
}
if let Some(Any::String(link)) = attrs.get("link") {
s = format!("<a href=\"{}\">{s}</a>", escape(link));
}
}
inner += &s;
}
match self.spec() {
BlockSpec::Code { .. } => format!("<pre><code>{inner}</code></pre>"),
BlockSpec::Divider => "<hr>".into(),
BlockSpec::List { list_type, .. } => {
let tag = if list_type == ListType::Numbered {
"ol"
} else {
"ul"
};
format!("<{tag}><li>{inner}</li></{tag}>")
}
BlockSpec::Paragraph { paragraph_type, .. } => {
let tag = match paragraph_type {
ParagraphType::Text => "p",
ParagraphType::Quote => "blockquote",
h => h.as_str(),
};
format!("<{tag}>{inner}</{tag}>")
}
_ => inner,
}
}
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
}
fn unescape(s: &str) -> String {
s.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&#39;", "'")
.replace("&nbsp;", " ")
.replace("&amp;", "&")
}
impl Slice {
pub fn new(workspace: &str, page: &str, content: Vec<SliceBlock>) -> 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::<Vec<_>>()
.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!(
"<div data-blocksuite-snapshot=\"{attr}\">{}</div>",
self.content
.iter()
.flat_map(SliceBlock::walk)
.map(SliceBlock::html)
.collect::<String>()
)
}
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<Self> {
if let Some(meta) = item
.metadata()
.and_then(|s| serde_json::from_str::<Value>(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<Self> {
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<Self> {
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::<Value>(&decoded)
&& let Some(raw) = map["BLOCKSUITE/SNAPSHOT"].as_str()
&& let Ok(wrapped) = serde_json::from_str::<Value>(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<usize, u16>| {
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<String> {
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<usize> {
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<Slice> {
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<SliceBlock>,
delta: &mut Vec<TextDeltaOp>,
blocks: &mut Vec<SliceBlock>| {
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::<TextAttributes>()),
});
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("<h2>中<strong>🪶</strong></h2><ol><li><a href='https://example.org'>a&amp;b</a></li></ol><pre><code>x\ny</code></pre>").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<super::Slice> {
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()))
}
File diff suppressed because it is too large. Load diff
@@ -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<Motion>,
editor: editor_session::EditorSession,
editor_focus: ui::FocusHandle,
reading_anchor: Option<(String, f32)>,
state: DocState,
room: Option<RoomRuntime>,
page_id: Option<String>,
@@ -182,6 +187,7 @@ pub struct PlaygroundView {
/// from its blob and is final.
images: HashMap<String, ImageSlot>,
blob_fetches: BTreeMap<String, BlobFetchState>,
dirty_text: Option<BTreeSet<String>>,
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>) {
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<Self>,
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<String, String> = 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<Self>,
) -> 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<DocState> {
.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<PlaygroundView>)| {
s.app.update(|cx| s.window.update(cx, f)).unwrap();
};
fn select(
v: &mut PlaygroundView,
offset: u64,
w: &mut Window,
cx: &mut Context<PlaygroundView>,
) {
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();
@@ -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);
}
@@ -120,16 +120,15 @@ impl Pasteboard {
}
fn read_string_from_pasteboard(&self) -> Option<ClipboardEntry> {
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::<serde_json::Value>(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 = "<p><a href='https://example.org'>linked page</a></p>";
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];
}
}
}
@@ -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();
})
}
@@ -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"
}
]
@@ -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;
@@ -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<ListBlockModel>('split')?.props.order).toBe(
2
);
});
await edit('indent');
await vi.waitFor(() => {
expect(children('converted')).toEqual(['split']);
expect(store.getModelById<ListBlockModel>('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<ListBlockModel>('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<RootBlockModel>('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;