diff --git a/.github/workflows/native-playground.yml b/.github/workflows/native-playground.yml index b9ceb6d171..b1c9a04c24 100644 --- a/.github/workflows/native-playground.yml +++ b/.github/workflows/native-playground.yml @@ -154,6 +154,7 @@ jobs: echo "Run 2 SHA256: $sha2" test "$sha1" = "$sha2" cargo run --locked --bin bs-harness --features harness -- audit --snapshot artifacts/linux-run1.json + cargo run --locked --bin bs-harness --features harness -- audit-states cargo run --locked --bin bs-harness --features harness -- fps-check cargo run --locked --bin bs-harness --features harness -- bench \ --json artifacts/perf-metrics.json \ diff --git a/AGENTS.md b/AGENTS.md index b77316fd6c..cc6ffb2108 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,12 @@ These rules apply at repository root on the `darksky/native-playground` branch a - **Performance regression gate:** Any CI benchmark metric regressing by **more than 10%** against the rolling `N-3` baseline is routed to the dedicated performance guardian before landing. - **Cargo rustflags isolation:** Root `.cargo/config.toml` injects NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`) that Cargo concatenates into nested workspaces. Always build and test `blocksuite/native-playground` with `CARGO_ENCODED_RUSTFLAGS=""` in the environment. +## Engineering & testing principles + +- **Global optimum over band-aid patches**: Favor clean structural refactoring and bold deletion over minimal-diff workarounds, defensive clutter, or over-abstraction. Delete obsolete helpers, structs, and files outright, and fold single-caller one-way fragments back into their caller when they add indirection without clarity. +- **Test names match actual scope**: Every test file and test function name must accurately reflect everything it asserts — never append unrelated assertions to a narrowly named test without renaming it to match. +- **Table-driven tests**: Group related scenarios (geometry/hit-testing, parsers, key sequences, IME cases) into concise table-driven loops rather than proliferating near-identical `#[test]` functions. + ## Keeping rules true - When a change makes any statement, path, command, or invariant in an `AGENTS.md` file inaccurate, update that `AGENTS.md` in the same commit. diff --git a/blocksuite/native-playground/AGENTS.md b/blocksuite/native-playground/AGENTS.md index d18a28607c..08f74aefc6 100644 --- a/blocksuite/native-playground/AGENTS.md +++ b/blocksuite/native-playground/AGENTS.md @@ -51,9 +51,9 @@ This document records the active engineering invariants enforced in CI today alo - **Overlay motion**: Popovers fade over 150 ms with an ease-out cubic `EaseOut` evaluated at scheduler time. An opening popover mounts on its first frame at zero opacity so its hitboxes are live immediately; a closed popover at zero opacity is unmounted, and one fading out carries no listeners and is dropped when the fade ends. Disclosure chevrons turn over the same 150 ms. Nothing here loops per frame. - **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.`, `.group.`, `.query`, `.empty`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer), and a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Without matches the list keeps a `No results` row. Items follow BlockSuite's order in two groups (`Basic`: text, the six headings, code block, quote, divider; `List`: bulleted, numbered, to-do, toggle); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 32 px, and the menu has no border, only its shadow. - **Formatting toolbar** (`overlay.format_toolbar`, buttons `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.link`, `.align_left|center|right`, link field `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text, single-block or across blocks, while no composition runs and no slash menu is up; a selection touching the title or code gets none. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches, empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The link field is a one-line text input of its own (`LinkBar`: text, selection, composition). While it is open it is the view's text input: every `EntityInputHandler` call goes to it, `editor.composing()` stays false, and the document's text, selection and composition are untouched until `Apply`; opening, closing and every change of it are reported with `notify_text_input_changed`. Caret keys, deletion, select-all, copy and cut are the field's, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field. It has the only caret; the document keeps showing the selection. -- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's grabber: a 4 × 12 px bar while the pointer is on the block's row, and two columns of three dots on a 14 px pill once the pointer is on the handle or drags it. A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings. -- **Block controls**: `page.block..checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block..copy` appears on a hovered code block and reads `Copied` for 1.5 s on the scheduler clock. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections, and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view. -- **Sizes and radii**: Interactive targets are at least 24 × 24 px (toolbar buttons 28 × 28, edge to edge). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows (BlockSuite pads its menu `8px 4px 8px 8px`; 4 px all around keeps the radii concentric), 8 px toolbar with 4 px padding and 4 px buttons. The toolbar is 297 px wide, with 8 px on either side of the line between the mark and the alignment buttons, and fits a 320 px window between its 8 px margins. +- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's Page-mode grabber: a 4 × 12 px vertical bar while the pointer is on the block's row, narrowing to a 2 × 12 px vertical bar once hovered or dragged (the 2 × 3 six-dot 14 px pill is reserved for Edgeless `gfx` drag handles). A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings. +- **Block controls**: `page.block..checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block..copy` appears on a hovered code block and reads `Copied` for 1.5 s on the scheduler clock. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections (translated per highlight span's own block scroll before clamping), and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view. +- **Sizes and radii**: Interactive targets are at least 24 × 24 px (toolbar buttons 28 × 28, edge to edge). Rows and buttons round concentrically with their container: 8 px menu with 4 px padding and 4 px rows (BlockSuite pads its menu `8px 4px 8px 8px`; 4 px all around keeps the radii concentric), 8 px toolbar with 4 px padding and 4 px buttons (`gap = 2px, pad = 4px`, intentionally compact relative to JS `8px / 0 6px` so the toolbar fits a 320 px window between its 8 px margins). The toolbar is 297 px wide, with 8 px on either side of the line between the mark and the alignment buttons. - **Verification**: `bs-harness render --state ` renders one overlay state of the showcase, `bs-harness audit-states` audits every state in both themes at `1280` and `320` px, and `bs-harness record-demo ` writes the frames of a 60 fps walk through typing, composition, the slash menu, the toolbar and the block controls; all drive the view through input events, the input handler and `dispatch_overlay` only. ### Performance guardrail and theme/style oracle @@ -69,20 +69,27 @@ This document records the active engineering invariants enforced in CI today alo - **End-to-end GPU transforms and local clip masks**: `Window::with_paint_transformation` composes 2D affine transforms (`TransformationMatrix`) on a stack and `Window::with_local_paint_mask` intersects pre-transform local clip rects (`ContentMask`). All GPU primitives (`Quad`, `Shadow`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, and `PathRasterizationVertex`) are 16-byte aligned (`size_of % 16 == 0`, verified by compile-time assertions) for WebGL2 `RGBA32U` instance-texture decoding. Both Metal (`shaders.metal`) and wgpu/WebGL2 (`shaders.wgsl`, `shaders_webgl.wgsl`, `shaders_subpixel.wgsl`) transform vertices on the GPU, evaluate SDFs in local space scaled by `transform_scale` for 1-device-pixel anti-aliasing across zooms and rotations, and clip against both screen-space `content_mask` and pre-transform `local_content_mask`. - **Quarter-octave glyph zoom bucketing**: Under non-unit paint scales, `Window::paint_glyph` and `Window::paint_glyph_in_run` quantize rasterization scale to quarter-octave buckets (`2^(round(4*log2(s))/4)` clamped to `[0.25, 8.0]`), rasterizing atlas tiles at `font_size * bucket` while scaling local quad bounds by `1 / bucket` so cached `1.0x` `RichParagraph` / `BlockFlow` layouts render crisply at `0.1x..6.0x` without re-shaping or relayouting during pan/zoom. - **Procedural dot-grid (`BackgroundTag::DotGrid = 4`)**: Renders the Edgeless background grid in a single fullscreen `Quad` draw call with 1-device-pixel anti-aliased dots centered in each tile with screen offset `(0.5 * gap - pan * zoom).rem_euclid(gap)` per axis and spacing matching BlockSuite's `getBgGridGap(zoom)`. -- **Spatial camera & canvas**: `edgeless_camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds. `edgeless_canvas.rs` renders Surface-parented Frames and EdgelessText and root-parented Notes. Note dimensions are world units. Layout uses the logical width divided by scale. Collapsed notes clip to the stored world height, which already includes scale. The canvas merges the block and vector paint streams by fractional index and Frame/Group ancestry. Equal indices continue the active stream, with blocks first at the start. Notes reuse their cached `BlockFlow::layout_nodes` during pan/zoom. All items paint under `edgeless.viewport`, with bottom-right screen-space zoom controls (`chrome.edgeless_zoom`). `bs-harness render --mode edgeless [--zoom ] [--pan ,]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`. +- **Spatial camera & canvas (`edgeless/`)**: `edgeless/camera.rs` (`EdgelessCamera`) manages pan/zoom (`[0.1, 6.0]`), cursor-anchored wheel zoom, and fit-to-bounds (initialized before building `chrome.edgeless_zoom` so Frame 1 displays the fitted zoom percentage). `edgeless/scene.rs` and `edgeless/canvas_paint.rs` prepare and render Surface-parented Frames and EdgelessText and root-parented Notes in a single snapshot pass. Note dimensions are world units. Layout uses the logical width divided by scale. Collapsed notes clip to the stored world height, which already includes scale. The canvas merges the block and vector paint streams by fractional index and Frame/Group ancestry (`prop:childElementIds` treats every present key as a frame member, and equal indices preserve source enumeration order within each stream). Equal indices continue the active stream, with blocks first at the start. Notes reuse their cached `BlockFlow::layout_nodes` during pan/zoom. All items paint under `edgeless.viewport`, with bottom-centered creation toolbar (`chrome.edgeless_toolbar`) and bottom-right screen-space zoom controls (`chrome.edgeless_zoom`, stacked cleanly above `chrome.edgeless_toolbar` on narrow viewports `< 660 px`). `bs-harness render --mode edgeless [--zoom ] [--pan ,]` renders spatial states, `bs-harness audit-states` audits Edgeless default + `0.5x` + `2.0x` + authoring states (`edgeless_selected`, `edgeless_marquee`, `edgeless_inline_edit`, `edgeless_authoring`) in Light/Dark at `1280` and `320` px, and `bs-harness bench` measures `edgeless_1k_pan_zoom_frame_ms` and asserts `edgeless_1k_pan_zoom_blocks_relayout == 0`. +- **Edgeless interactive authoring & inline IME editing (`edgeless/{toolbar,hit_test,overlay,label_editor,inline_edit,gestures,commit,commands}.rs`)**: `chrome.edgeless_toolbar` provides Select (`V`/`Escape`), Hand (`H` or holding `Space`), Note (`N`), Shape (`S` with rect/ellipse/diamond/triangle picker), Connector (`C` with cardinal port snapping and live orthogonal connector preview), Brush (`P`), Highlighter, Text (`T`), and Frame (`F`, populating `prop:childElementIds`). World-space hit-testing walks exact reverse paint order (inverse-rotated OBBs for shapes/texts, routed polyline distance from `SurfaceLayout` for connectors/strokes, exact `layout_inline` title pill and border for frames). Selection renders a screen-crisp `edgeless.selection_box`, 8 resize handles (`edgeless.handle.nw..w`), top rotation handle (`edgeless.handle.rotate`, `15°` snap with `Shift`), and `2×3` 6-dot `14px` Edgeless `gfx` drag handle (`edgeless.drag_handle`) on selected blocks; resize and rotation handles are suppressed while inline label editing is active, and the underlying static label is hidden until commit. Dragging, resizing, rotating, deleting (`Backspace`/`Delete`), and z-reordering (`[`/`]` via `fractional-indexing@3.2.0` keys in `crates/doc/src/fractional_index.rs`) commit single atomic undo steps on `PageDocSession` and broadcast over `RoomProtocol`. Double-clicking a Note or EdgelessText edits rich text inline via `EditorSession` + `EntityInputHandler` with camera-mapped `bounds_for_range`; double-clicking a Shape, Connector, SurfaceText, or Frame title edits its `Y.Text` inline (`edgeless.inline_edit`) with full UTF-16 + IME preedit support. ### Surface reading and painting -- `BlockContent::Surface` retains the element count and exposes typed elements sorted by fractional index then id. Each element keeps all normalized wire properties, including unknown types. Connector labels retain their stored size and follow the route at the label offset. When `labelXYWH` is absent, the native renderer measures the label at paint time. This extends BlockSuite’s `hasLabel()` behavior with zero document writebacks. +- `BlockContent::Surface` retains the element count and exposes typed elements sorted by fractional index in wire creation order. Each element keeps all normalized wire properties and unknown types (`textDisplay` on shapes is `@local()` and defaults to `true` locally without reading from the wire). Straight connector labels interpolate linearly (`Vec.lrp`), orthogonal labels follow polyline distance, and curved labels follow the cubic Bézier parameter. Connector labels retain their stored size and follow the route at the label offset. When `labelXYWH` is absent, the native renderer measures the label at paint time. This extends BlockSuite’s `hasLabel()` behavior with zero document writebacks. - `surface::layout_surface` accepts element snapshots and world bounds for external blocks. It finds ports on rotated shape outlines and routes orthogonal connectors using their two endpoint bounds. The router follows BlockSuite's `ConnectorPathGenerator`. A connector's `rough` flag enables jitter and `roughness` sets its amplitude. Scribbled shapes follow RoughJS hachure, `pointsOnPath` sampling and seeded operation order. Brush and highlighter share the perfect-freehand pressure outline and midpoint quadratic curves. EdgelessCanvas caches geometry by document revision, theme and environment revision. Fully visible elements emit `edgeless.surface.` in screen coordinates. The standalone harness uses the same painter. - The canvas clips its viewport in screen coordinates. Within the camera transform, each rotated shape or text pushes its own center rotation before its label mask. The GPU inverse-maps coverage into the label's local coordinates while retaining the screen-space viewport clip. - The JS surface oracle runs the BlockSuite shape, connector and freehand implementations and compares their coordinates to `tokens/surface-oracle.json`. Rust tests consume the same geometry and font baselines. - With repository JavaScript dependencies installed, `cargo test --locked -p blocksuite-playground-doc --example bs_doc_driver js_authored_surface` verifies data and rich-text marks written by Yjs against the typed Rust snapshot and compares the encoded document before and after reading. +### Rust Module Organization & Fast Verification +- **Proactive modularization**: Split files by responsibility (targeting ~500–800 production lines; promote `.rs` to `/mod.rs` when introducing submodules). Keep each `mod.rs` as the dependency and visibility hub (`pub(super) use ...`), import siblings via `use super::...`, and hoist cross-layer shared items to the narrowest common ancestor `mod.rs`. +- **Global optimum & clean boundaries**: Prefer structural cleanup and bold deletion over band-aid patches. Delete obsolete code outright, fold single-caller one-way fragments back into their caller, and extract shared helpers only for stable domain concepts, genuine multi-site reuse, or key invariants — never for one-line expressions. +- **Focused, table-driven tests**: Keep test-only imports and helpers inside `#[cfg(test)] mod tests`, placing unit tests in the file under test and cross-submodule tests in the lowest common `mod.rs`. Keep every test file and function name aligned with its actual assertion scope, and group similar scenarios into table-driven loops rather than proliferating near-identical `#[test]` functions. +- **Sub-60-second verification loop**: Validate uncertain paths with minimal focused spikes first and remove scaffolding before landing. Keep routine edit-verify turns under **60 seconds** using targeted `cargo check --locked -p ...` / `cargo test --locked -p ... --lib ` and `./scripts/check-invariants.sh` (which enforces `super::super` bans, `mod.rs` layout, orphan-file detection, and per-file LOC limits automatically alongside `rustfmt.toml`). + ## Planned Contracts (upcoming crates & features) -- **Whiteboard surface elements & interaction**: Mindmaps and pointer selection/drag editing on the Edgeless spatial canvas. +- **Whiteboard surface elements**: Mindmap tree layout and editing on the Edgeless spatial canvas. ## Build & verification commands diff --git a/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs b/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs index 11eb3b178b..da31fd7bd1 100644 --- a/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs +++ b/blocksuite/native-playground/crates/doc/examples/bs_doc_driver.rs @@ -91,6 +91,98 @@ enum Command { mode: i32, now_ms: u64, }, + GenerateKeyBetween { + a: Option, + b: Option, + }, + AddShape { + page_id: String, + surface_id: String, + element_id: String, + index: String, + shape_type: String, + xywh: String, + text: Option, + now_ms: u64, + }, + UpdateShapeRotate { + page_id: String, + surface_id: String, + element_id: String, + rotate: f64, + now_ms: u64, + }, + AddConnector { + page_id: String, + surface_id: String, + element_id: String, + index: String, + source_id: String, + target_id: String, + now_ms: u64, + }, + AddBrush { + page_id: String, + surface_id: String, + element_id: String, + index: String, + xywh: String, + points: Vec>, + now_ms: u64, + }, + UpdateBrushPoints { + page_id: String, + surface_id: String, + element_id: String, + points: Vec>, + now_ms: u64, + }, + UpdateConnectorLabelXywh { + page_id: String, + surface_id: String, + element_id: String, + label_xywh: [f64; 4], + now_ms: u64, + }, + AddNoteWithText { + page_id: String, + root_id: String, + note_id: String, + para_id: String, + xywh: [f64; 4], + text: String, + now_ms: u64, + }, + SpliceSurfaceElementText { + page_id: String, + surface_id: String, + element_id: String, + field: String, + utf16_start: u64, + utf16_delete_len: u64, + insert: String, + now_ms: u64, + }, + CommitConnectorLabel { + page_id: String, + surface_id: String, + element_id: String, + trimmed_text: String, + label_xywh: [f64; 4], + now_ms: u64, + }, + DeleteWithConnectors { + page_id: String, + block_ids: Vec, + surface_elements: Vec<(String, String)>, + now_ms: u64, + }, + Undo { + page_id: String, + }, + Redo { + page_id: String, + }, SetAwareness { name: String, color: String, @@ -761,6 +853,377 @@ async fn main() { } json!({ "ok": true }) } + Command::GenerateKeyBetween { a, b } => { + match blocksuite_playground_doc::fractional_index::generate_key_between( + a.as_deref(), + b.as_deref(), + ) { + Ok(key) => json!({ "ok": true, "key": key }), + Err(err) => json!({ "ok": false, "error": err }), + } + } + Command::AddShape { + page_id, + surface_id, + element_id, + index, + shape_type, + xywh, + text, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .structural_edit(now_ms, move |p| { + p.add_surface_element( + &surface_id, + element_id.clone(), + &index, + SurfaceElementSpec::Shape { + shape_type: shape_type.clone(), + xywh: xywh.clone(), + seed: 101, + filled: true, + text: text.clone(), + }, + now_ms, + )?; + Ok(()) + }) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::UpdateShapeRotate { + page_id, + surface_id, + element_id, + rotate, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .structural_edit(now_ms, move |p| { + p.set_surface_element_field( + &surface_id, + &element_id, + "rotate", + SessionValue::Any(Any::Float64(rotate.into())), + now_ms, + )?; + Ok(()) + }) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::AddConnector { + page_id, + surface_id, + element_id, + index, + source_id, + target_id, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .structural_edit(now_ms, move |p| { + p.add_surface_element( + &surface_id, + element_id.clone(), + &index, + SurfaceElementSpec::Connector { + mode: 1, + seed: 202, + source: ConnectorEndpointSpec::element( + source_id.clone(), + Some([1.0, 0.5]), + ), + target: ConnectorEndpointSpec::element( + target_id.clone(), + Some([0.0, 0.5]), + ), + text: None, + label_xywh: None, + }, + now_ms, + )?; + Ok(()) + }) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::AddBrush { + page_id, + surface_id, + element_id, + index, + xywh, + points, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .structural_edit(now_ms, move |p| { + p.add_surface_element( + &surface_id, + element_id.clone(), + &index, + SurfaceElementSpec::Brush { + seed: 303, + points: points.clone(), + xywh: xywh.clone(), + }, + now_ms, + )?; + Ok(()) + }) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::UpdateBrushPoints { + page_id, + surface_id, + element_id, + points, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + let encoded: Vec = points + .into_iter() + .map(|p| Any::Array(p.into_iter().map(|v| Any::Float64(v.into())).collect())) + .collect(); + if let Some(c) = page + .set_surface_element_field( + &surface_id, + &element_id, + "points", + SessionValue::Any(blocksuite_playground_doc::schema::map_array_any( + encoded, + )), + now_ms, + ) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::UpdateConnectorLabelXywh { + page_id, + surface_id, + element_id, + label_xywh, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + let encoded: Vec = label_xywh + .into_iter() + .map(|v| Any::Float64(v.into())) + .collect(); + if let Some(c) = page + .set_surface_element_field( + &surface_id, + &element_id, + "labelXYWH", + SessionValue::Any(blocksuite_playground_doc::schema::map_array_any( + encoded, + )), + now_ms, + ) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::AddNoteWithText { + page_id, + root_id, + note_id, + para_id, + xywh, + text, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .add_edgeless_note(&root_id, ¬e_id, ¶_id, "a5", xywh, &text, now_ms) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::SpliceSurfaceElementText { + page_id, + surface_id, + element_id, + field, + utf16_start, + utf16_delete_len, + insert, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .splice_surface_element_text( + &surface_id, + &element_id, + &field, + utf16_start, + utf16_delete_len, + &insert, + now_ms, + ) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::CommitConnectorLabel { + page_id, + surface_id, + element_id, + trimmed_text, + label_xywh, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page + .commit_connector_label( + &surface_id, + &element_id, + &trimmed_text, + label_xywh, + now_ms, + ) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::DeleteWithConnectors { + page_id, + block_ids, + surface_elements, + now_ms, + } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + let b_refs: Vec<&str> = block_ids.iter().map(String::as_str).collect(); + let s_refs: Vec<(&str, &str)> = surface_elements + .iter() + .map(|(s, e)| (s.as_str(), e.as_str())) + .collect(); + if let Some(c) = page + .delete_blocks_and_elements_with_connectors(&b_refs, &s_refs, now_ms) + .unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::Undo { page_id } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page.undo().unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } + Command::Redo { page_id } => { + let page = ws_session.ensure_page(&page_id).unwrap(); + if let Some(c) = page.redo().unwrap() + && !c.update.is_empty() + { + let f = encode_binary_frame(&RoomBinaryFrame::Doc { + doc_id: page_id, + message: DocMessage::Update(c.update), + }) + .unwrap(); + ws.send(WsMsg::Binary(f.into())).await.unwrap(); + } + json!({ "ok": true }) + } Command::SetAwareness { name, color, diff --git a/blocksuite/native-playground/crates/doc/src/fractional_index.rs b/blocksuite/native-playground/crates/doc/src/fractional_index.rs new file mode 100644 index 0000000000..c2c3d2463f --- /dev/null +++ b/blocksuite/native-playground/crates/doc/src/fractional_index.rs @@ -0,0 +1,287 @@ +//! Exact `fractional-indexing@3.2.0` (base-62) key generation compatible with BlockSuite. +//! +//! Integer keys start with a head character encoding their digit count: +//! - `'a'`..=`'z'` have `1..=26` base-62 digits (`"a0"`..`"a9"`, `"aA"`..`"az"`, `"b00"`..`"bzz"`). +//! - `'Z'`..=`'A'` have `1..=26` negative base-62 digits (`"Zz"`..`"Z0"`, `"Yzz"`..`"Y00"`). +//! Note that `"b0"` is invalid because `'b'` requires 2 integer digits (`"b00"`..`"bzz"`). + +const BASE_62_DIGITS: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; +const SMALLEST_INTEGER: &str = "A00000000000000000000000000"; +const INTEGER_ZERO: &str = "a0"; + +fn digit_index(ch: u8) -> Option { + BASE_62_DIGITS.iter().position(|&b| b == ch) +} + +fn integer_length(head: u8) -> Result { + if head.is_ascii_lowercase() { + Ok((head - b'a') as usize + 2) + } else if head.is_ascii_uppercase() { + Ok((b'Z' - head) as usize + 2) + } else { + Err(format!("invalid order key head: {:?}", head as char)) + } +} + +fn validate_integer(int: &str) -> Result<(), String> { + let bytes = int.as_bytes(); + if bytes.is_empty() { + return Err("empty integer part".into()); + } + let expected = integer_length(bytes[0])?; + if bytes.len() != expected { + return Err(format!("invalid integer part of order key: {int}")); + } + for &b in &bytes[1..] { + if digit_index(b).is_none() { + return Err(format!("invalid base-62 digit in order key: {int}")); + } + } + Ok(()) +} + +fn get_integer_part(key: &str) -> Result<&str, String> { + let bytes = key.as_bytes(); + if bytes.is_empty() { + return Err("empty order key".into()); + } + let len = integer_length(bytes[0])?; + if len > bytes.len() { + return Err(format!("invalid order key: {key}")); + } + let int = &key[..len]; + validate_integer(int)?; + Ok(int) +} + +/// Validate that `key` is a legal `fractional-indexing@3.2.0` base-62 order key. +pub fn validate_order_key(key: &str) -> Result<(), String> { + if key == SMALLEST_INTEGER { + return Err(format!("invalid order key: {key}")); + } + let int = get_integer_part(key)?; + let frac = &key[int.len()..]; + for &b in frac.as_bytes() { + if digit_index(b).is_none() { + return Err(format!("invalid fractional digit in order key: {key}")); + } + } + if frac.ends_with(BASE_62_DIGITS[0] as char) { + return Err(format!("invalid order key trailing zero: {key}")); + } + Ok(()) +} + +fn increment_integer(x: &str) -> Result, String> { + validate_integer(x)?; + let bytes = x.as_bytes(); + let head = bytes[0]; + let mut digs = bytes[1..].to_vec(); + let mut carry = true; + for d in digs.iter_mut().rev() { + if !carry { + break; + } + let idx = digit_index(*d).unwrap() + 1; + if idx == BASE_62_DIGITS.len() { + *d = BASE_62_DIGITS[0]; + } else { + *d = BASE_62_DIGITS[idx]; + carry = false; + } + } + if carry { + if head == b'Z' { + return Ok(Some(INTEGER_ZERO.to_string())); + } + if head == b'z' { + return Ok(None); + } + let next_head = head + 1; + if next_head > b'a' { + digs.push(BASE_62_DIGITS[0]); + } else { + digs.pop(); + } + let mut out = String::with_capacity(1 + digs.len()); + out.push(next_head as char); + out.push_str(std::str::from_utf8(&digs).unwrap()); + Ok(Some(out)) + } else { + let mut out = String::with_capacity(1 + digs.len()); + out.push(head as char); + out.push_str(std::str::from_utf8(&digs).unwrap()); + Ok(Some(out)) + } +} + +fn decrement_integer(x: &str) -> Result, String> { + validate_integer(x)?; + let bytes = x.as_bytes(); + let head = bytes[0]; + let mut digs = bytes[1..].to_vec(); + let mut borrow = true; + for d in digs.iter_mut().rev() { + if !borrow { + break; + } + let idx = digit_index(*d).unwrap(); + if idx == 0 { + *d = *BASE_62_DIGITS.last().unwrap(); + } else { + *d = BASE_62_DIGITS[idx - 1]; + borrow = false; + } + } + if borrow { + if head == b'a' { + return Ok(Some(format!( + "Z{}", + *BASE_62_DIGITS.last().unwrap() as char + ))); + } + if head == b'A' { + return Ok(None); + } + let prev_head = head - 1; + if prev_head < b'Z' { + digs.push(*BASE_62_DIGITS.last().unwrap()); + } else { + digs.pop(); + } + let mut out = String::with_capacity(1 + digs.len()); + out.push(prev_head as char); + out.push_str(std::str::from_utf8(&digs).unwrap()); + Ok(Some(out)) + } else { + let mut out = String::with_capacity(1 + digs.len()); + out.push(head as char); + out.push_str(std::str::from_utf8(&digs).unwrap()); + Ok(Some(out)) + } +} + +fn midpoint(a: &str, b: Option<&str>) -> Result { + let zero = BASE_62_DIGITS[0]; + if let Some(b) = b + && a >= b + { + return Err(format!("{a} >= {b}")); + } + if a.ends_with(zero as char) || b.is_some_and(|b| b.ends_with(zero as char)) { + return Err("trailing zero in midpoint".into()); + } + if let Some(b) = b { + let a_bytes = a.as_bytes(); + let b_bytes = b.as_bytes(); + let mut n = 0; + while n < b_bytes.len() && a_bytes.get(n).copied().unwrap_or(zero) == b_bytes[n] { + n += 1; + } + if n > 0 { + let sub_a = if n < a.len() { &a[n..] } else { "" }; + return Ok(format!("{}{}", &b[..n], midpoint(sub_a, Some(&b[n..]))?)); + } + } + let digit_a = a + .as_bytes() + .first() + .map_or(0, |&c| digit_index(c).unwrap_or(0)); + let digit_b = b + .and_then(|s| s.as_bytes().first()) + .map_or(BASE_62_DIGITS.len(), |&c| digit_index(c).unwrap_or(0)); + if digit_b - digit_a > 1 { + let mid = ((digit_a + digit_b) as f64 * 0.5).round() as usize; + return Ok((BASE_62_DIGITS[mid] as char).to_string()); + } + if let Some(b) = b + && b.len() > 1 + { + return Ok(b[..1].to_string()); + } + let sub_a = if a.len() > 1 { &a[1..] } else { "" }; + Ok(format!( + "{}{}", + BASE_62_DIGITS[digit_a] as char, + midpoint(sub_a, None)? + )) +} + +/// Generate a valid `fractional-indexing@3.2.0` base-62 key strictly between `a` and `b`. +pub fn generate_key_between(a: Option<&str>, b: Option<&str>) -> Result { + if let Some(a) = a { + validate_order_key(a)?; + } + if let Some(b) = b { + validate_order_key(b)?; + } + if let (Some(a), Some(b)) = (a, b) + && a >= b + { + return Err(format!("{a} >= {b}")); + } + if a.is_none() { + let Some(b) = b else { + return Ok(INTEGER_ZERO.to_string()); + }; + let ib = get_integer_part(b)?; + let fb = &b[ib.len()..]; + if ib == SMALLEST_INTEGER { + return Ok(format!("{ib}{}", midpoint("", Some(fb))?)); + } + if ib < b { + return Ok(ib.to_string()); + } + let res = decrement_integer(ib)? + .ok_or_else(|| "cannot decrement smallest integer".to_string())?; + return Ok(res); + } + let a = a.unwrap(); + if b.is_none() { + let ia = get_integer_part(a)?; + let fa = &a[ia.len()..]; + return match increment_integer(ia)? { + Some(i) => Ok(i), + None => Ok(format!("{ia}{}", midpoint(fa, None)?)), + }; + } + let b = b.unwrap(); + let ia = get_integer_part(a)?; + let fa = &a[ia.len()..]; + let ib = get_integer_part(b)?; + let fb = &b[ib.len()..]; + if ia == ib { + return Ok(format!("{ia}{}", midpoint(fa, Some(fb))?)); + } + let i = increment_integer(ia)?.ok_or_else(|| "cannot increment largest integer".to_string())?; + if i.as_str() < b { + Ok(i) + } else { + Ok(format!("{ia}{}", midpoint(fa, None)?)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_fractional_indexing_3_2_0_vectors() { + assert_eq!(generate_key_between(None, None).unwrap(), "a0"); + assert_eq!(generate_key_between(Some("a0"), None).unwrap(), "a1"); + assert_eq!(generate_key_between(Some("a9"), None).unwrap(), "aA"); + assert_eq!(generate_key_between(Some("aZ"), None).unwrap(), "aa"); + assert_eq!(generate_key_between(Some("az"), None).unwrap(), "b00"); + assert_eq!(generate_key_between(None, Some("a0")).unwrap(), "Zz"); + assert_eq!(generate_key_between(None, Some("Z0")).unwrap(), "Yzz"); + assert_eq!(generate_key_between(Some("a0"), Some("a1")).unwrap(), "a0V"); + assert_eq!(generate_key_between(Some("a0"), Some("a2")).unwrap(), "a1"); + assert_eq!( + generate_key_between(Some("a0V"), Some("a1")).unwrap(), + "a0l" + ); + // "b0" is invalid in fractional-indexing@3.2.0 ('b' requires 2 base-62 digits). + assert!(validate_order_key("b0").is_err()); + assert!(validate_order_key("b00").is_ok()); + } +} diff --git a/blocksuite/native-playground/crates/doc/src/lib.rs b/blocksuite/native-playground/crates/doc/src/lib.rs index 671e634ef0..7b5e513811 100644 --- a/blocksuite/native-playground/crates/doc/src/lib.rs +++ b/blocksuite/native-playground/crates/doc/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] pub mod awareness; +pub mod fractional_index; pub mod read; #[cfg(all(feature = "server", not(target_family = "wasm")))] pub mod room; diff --git a/blocksuite/native-playground/crates/doc/src/read.rs b/blocksuite/native-playground/crates/doc/src/read.rs index 0766521838..34ec6e131b 100644 --- a/blocksuite/native-playground/crates/doc/src/read.rs +++ b/blocksuite/native-playground/crates/doc/src/read.rs @@ -158,6 +158,7 @@ pub struct SurfaceShape { pub shape_style: ShapeStyle, pub roughness: f64, pub text: RichText, + pub text_display: bool, pub color: ColorValue, pub font_family: String, pub font_size: f64, @@ -366,6 +367,7 @@ impl SurfaceElement { ShapeStyle::General }, text, + text_display: true, color: font.color, font_family: font.font_family, font_size: font.font_size, @@ -807,8 +809,11 @@ impl SnapshotReader<'_> { title: self.rich_text(entries.get("prop:title"))?, }, "affine:surface" => { - let elements = self - .surface_elements(entries.get("prop:elements"), props.get("prop:elements"))?; + let elements = self.surface_elements( + id, + entries.get("prop:elements"), + props.get("prop:elements"), + )?; BlockContent::Surface { element_count: elements.len(), elements, @@ -902,6 +907,7 @@ impl SnapshotReader<'_> { fn surface_elements( &self, + surface_id: &str, value: Option<&SessionReadValue>, normalized: Option<&JsonValue>, ) -> DocResult> { @@ -920,8 +926,16 @@ impl SnapshotReader<'_> { else { return Ok(vec![]); }; - let mut elements = Vec::with_capacity(raw.len()); - for (id, value) in session.read_map(&TypeTarget::Identity(value))? { + let map_entries = session.read_map(&TypeTarget::Identity(value))?; + let ordered_ids = self + .page + .refresh_surface_element_order(surface_id, &map_entries); + let mut by_id: BTreeMap = map_entries.into_iter().collect(); + let mut elements = Vec::with_capacity(ordered_ids.len()); + for id in ordered_ids { + let Some(value) = by_id.remove(&id) else { + continue; + }; let properties = raw.get(&id).unwrap_or(&JsonValue::Null); let (props, text) = if let SessionReadValue::Map(identity) = value { let key = if properties["type"] == "group" { @@ -936,7 +950,7 @@ impl SnapshotReader<'_> { }; elements.push(SurfaceElement::from_properties(id, props, text)); } - elements.sort_by(|a, b| (&a.index, &a.id).cmp(&(&b.index, &b.id))); + elements.sort_by(|a, b| a.index.cmp(&b.index)); Ok(elements) } } @@ -1061,8 +1075,10 @@ fn number(value: Option<&SessionReadValue>) -> Option { #[cfg(test)] mod surface_tests { use super::*; - use crate::schema::{BlockSpec, ConnectorEndpointSpec, SurfaceElementSpec as Spec}; - use y_octo::SessionValue; + use crate::schema::{ + BlockSpec, ConnectorEndpointSpec, SurfaceElementSpec, SurfaceElementSpec as Spec, + }; + use y_octo::{SessionValue, TypePath}; #[test] fn partial_normalized_surface_map_keeps_missing_entry_as_unknown() -> DocResult { @@ -1089,6 +1105,7 @@ mod surface_tests { reader.load()?; let partial = serde_json::json!({"value":{}}); let result = reader.surface_elements( + "surface", reader.raw["surface"].entries.get("prop:elements"), Some(&partial), )?; @@ -1194,19 +1211,22 @@ mod surface_tests { assert_eq!( elements.iter().map(|e| e.id.as_str()).collect::>(), [ - "brush", - "connector", - "group", - "highlighter", "shape", + "connector", + "brush", + "highlighter", + "group", "text" ] ); - let SurfaceElementKind::Brush(s) = &elements[0].kind else { + let SurfaceElementKind::Shape(s) = &elements[0].kind else { panic!() }; - assert_eq!(s.points, [[0., 2., 0.5], [5., 3., 0.75]]); - assert_eq!(s.xywh, [100., 20., 40., 10.]); + assert_eq!(s.shape_type, ShapeType::Rect); + assert_eq!(s.radius, 0.1); + assert_eq!(s.padding, [10., 20.]); + assert_eq!(s.text.plain, "Label"); + assert_eq!(elements[0].props["future"], 17); let SurfaceElementKind::Connector(c) = &elements[1].kind else { panic!() }; @@ -1217,24 +1237,21 @@ mod surface_tests { assert_eq!(c.source.id.as_deref(), Some("shape")); assert_eq!(c.target.position, Some([99., 22.])); assert_eq!(c.text.plain, "Edge"); - let SurfaceElementKind::Group { title, children } = &elements[2].kind else { + let SurfaceElementKind::Brush(s) = &elements[2].kind else { panic!() }; - assert_eq!(title.plain, "Group"); - assert_eq!(children, &["shape", "text"]); + assert_eq!(s.points, [[0., 2., 0.5], [5., 3., 0.75]]); + assert_eq!(s.xywh, [100., 20., 40., 10.]); let SurfaceElementKind::Highlighter(s) = &elements[3].kind else { panic!() }; assert_eq!(s.points, [[3., 4., 0.5]]); assert_eq!(s.color, ColorValue::Single("#84cfff4d".into())); - let SurfaceElementKind::Shape(s) = &elements[4].kind else { + let SurfaceElementKind::Group { title, children } = &elements[4].kind else { panic!() }; - assert_eq!(s.shape_type, ShapeType::Rect); - assert_eq!(s.radius, 0.1); - assert_eq!(s.padding, [10., 20.]); - assert_eq!(s.text.plain, "Label"); - assert_eq!(elements[4].props["future"], 17); + assert_eq!(title.plain, "Group"); + assert_eq!(children, &["shape", "text"]); let SurfaceElementKind::Text(t) = &elements[5].kind else { panic!() }; @@ -1259,4 +1276,197 @@ mod surface_tests { assert!(e.hidden && e.locked_by_self); assert_eq!(e.props["nested"]["extra"][1], 2); } + + #[test] + fn equal_index_surface_elements_preserve_per_surface_insertion_order_despite_earlier_global_key() + -> DocResult<()> { + // Adversarial test: insert key `"a"` in an unrelated block first, then insert + // equal-index shapes `"z"` ("a1") and `"a"` ("a1") into `prop:elements.value`. + // Both a single V1 update and two incremental updates must preserve `["z", "a"]`. + let mut author = PageDocSession::new("p-order", 1)?; + author.add_block( + "page-1", + BlockSpec::Page { + title: "Order".into(), + }, + None, + None, + 1, + )?; + author.add_block( + "a", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "global key a".into(), + }, + Some("page-1"), + None, + 2, + )?; + let surf = author.ensure_surface_block(3)?; + let u_base = author.encode_update_v1()?; + let u_z = author + .add_surface_element( + &surf, + "z", + "a1", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[0,0,100,80]".into(), + seed: 1, + filled: true, + text: Some("Z".into()), + }, + 4, + )? + .unwrap() + .update; + let u_a = author + .add_surface_element( + &surf, + "a", + "a1", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[20,20,100,80]".into(), + seed: 2, + filled: true, + text: Some("A".into()), + }, + 5, + )? + .unwrap() + .update; + let u_full = author.encode_update_v1()?; + + let extract_ids = |doc: &PageDocSession| -> Vec { + let snap = doc.read_page_snapshot().unwrap(); + let surf_node = snap + .root + .unwrap() + .children + .into_iter() + .find(|c| c.id == surf) + .unwrap(); + let BlockContent::Surface { elements, .. } = surf_node.content else { + unreachable!() + }; + elements.into_iter().map(|e| e.id).collect() + }; + + assert_eq!(extract_ids(&author), vec!["z", "a"]); + + // Single V1 update decode on fresh peer: + let mut peer_single = PageDocSession::new("p-order", 2)?; + peer_single.apply_remote_update_v1(&u_full)?; + assert_eq!(extract_ids(&peer_single), vec!["z", "a"]); + + // Two incremental updates on fresh peer: + let mut peer_inc = PageDocSession::new("p-order", 3)?; + peer_inc.apply_remote_update_v1(&u_base)?; + peer_inc.apply_remote_update_v1(&u_z)?; + peer_inc.apply_remote_update_v1(&u_a)?; + assert_eq!(extract_ids(&peer_inc), vec!["z", "a"]); + Ok(()) + } + + #[test] + fn concurrent_two_peer_shape_label_splice_and_undo_redo_preserve_marks() -> DocResult<()> { + let mut peer_a = PageDocSession::new("p-collab", 11)?; + peer_a.add_block( + "page-1", + BlockSpec::Page { + title: "Collab".into(), + }, + None, + None, + 1, + )?; + let surf = peer_a.ensure_surface_block(2)?; + peer_a.add_surface_element( + &surf, + "s1", + "a0", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[0,0,160,80]".into(), + seed: 7, + filled: true, + text: Some("Hello".into()), + }, + 3, + )?; + // Apply bold mark to "Hello" directly on Y.Text. + let target = TypeTarget::Path( + TypePath::root("blocks") + .key(&surf) + .key("prop:elements") + .key("value") + .key("s1") + .key("text"), + ); + let mut bold = y_octo::TextAttributes::new(); + bold.insert("bold".into(), Any::True); + peer_a.inner_mut().text_format(&target, 0, 5, bold)?; + peer_a.stop_capturing()?; + + let mut peer_b = PageDocSession::new("p-collab", 22)?; + peer_b.apply_remote_update_v1(&peer_a.encode_update_v1()?)?; + + // Concurrent edits: B prepends "X ", A appends "!" + let upd_b = peer_b + .splice_surface_element_text(&surf, "s1", "text", 0, 0, "X ", 100)? + .unwrap() + .update; + let upd_a = peer_a + .splice_surface_element_text(&surf, "s1", "text", 5, 0, "!", 100)? + .unwrap() + .update; + peer_a.apply_remote_update_v1(&upd_b)?; + peer_b.apply_remote_update_v1(&upd_a)?; + + let read_shape_text = |doc: &PageDocSession| -> RichText { + let snap = doc.read_page_snapshot().unwrap(); + let snode = snap + .root + .unwrap() + .children + .into_iter() + .find(|c| c.id == surf) + .unwrap(); + let BlockContent::Surface { elements, .. } = snode.content else { + unreachable!() + }; + let SurfaceElementKind::Shape(sh) = &elements[0].kind else { + unreachable!() + }; + sh.text.clone() + }; + + let ta = read_shape_text(&peer_a); + let tb = read_shape_text(&peer_b); + assert_eq!(ta.plain, "X Hello!"); + assert_eq!(tb.plain, "X Hello!"); + assert!( + ta.delta.iter().any(|op| matches!( + op, + TextDeltaOp::Insert { insert: TextInsert::Text(t), format: Some(f) } + if t.contains("Hello") && f.get("bold") == Some(&Any::True) + )), + "untouched bold mark on 'Hello' must survive concurrent splices: {:?}", + ta.delta + ); + + // Peer A undoes "!" -> "X Hello" survives; redoes -> "X Hello!". + let u_undo = peer_a.undo()?.unwrap().update; + peer_b.apply_remote_update_v1(&u_undo)?; + assert_eq!(read_shape_text(&peer_a).plain, "X Hello"); + assert_eq!(read_shape_text(&peer_b).plain, "X Hello"); + + let u_redo = peer_a.redo()?.unwrap().update; + peer_b.apply_remote_update_v1(&u_redo)?; + assert_eq!(read_shape_text(&peer_a).plain, "X Hello!"); + assert_eq!(read_shape_text(&peer_b).plain, "X Hello!"); + Ok(()) + } } diff --git a/blocksuite/native-playground/crates/doc/src/schema.rs b/blocksuite/native-playground/crates/doc/src/schema.rs index a18bc69640..a43c83c3bd 100644 --- a/blocksuite/native-playground/crates/doc/src/schema.rs +++ b/blocksuite/native-playground/crates/doc/src/schema.rs @@ -273,7 +273,7 @@ fn nonzero_seed(seed: i32) -> i32 { /// `y-octo`'s `From for Content` converts a top-level `Any::Array(v)` into /// multi-element `Content::Any(v)`. Wrapping once produces `Content::Any(vec![Any::Array(v)])`, /// matching Yjs `yMap.set(key, array)`. -fn map_array_any(items: Vec) -> Any { +pub fn map_array_any(items: Vec) -> Any { Any::Array(vec![Any::Array(items)]) } diff --git a/blocksuite/native-playground/crates/doc/src/session.rs b/blocksuite/native-playground/crates/doc/src/session.rs index af7b17dc33..bfe59ed0ee 100644 --- a/blocksuite/native-playground/crates/doc/src/session.rs +++ b/blocksuite/native-playground/crates/doc/src/session.rs @@ -1,11 +1,14 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::{ + cell::RefCell, + collections::{BTreeMap, BTreeSet}, +}; use serde::{Deserialize, Serialize}; use serde_json::{Map as JsonMap, Value as JsonValue}; use y_octo::{ Any, DocOptions, DocSession, RelativePosition, SessionCommit, SessionConfig, SessionOriginKind, SessionReadValue, SessionTxOrigin, SessionUndoConfig, SessionValue, TextAttributes, - TextDeltaOp, TextInsert, TypePath, TypeTarget, UndoStackId, YTypeKind, + TextDeltaOp, TextInsert, TypeIdentity, TypePath, TypeTarget, UndoStackId, YTypeKind, }; use crate::{ @@ -151,6 +154,7 @@ pub struct PageDocSession { session: DocSession, undo_stack_id: UndoStackId, blocks_target: TypeTarget, + surface_element_order: RefCell>>, } impl PageDocSession { @@ -174,9 +178,77 @@ impl PageDocSession { session, undo_stack_id, blocks_target, + surface_element_order: RefCell::new(BTreeMap::new()), }) } + /// Update and return per-surface first-integration key order for `prop:elements.value`, + /// preserving established order for surviving keys and appending newly integrated keys + /// sorted by `(Reverse(id.client), id.clock)` from `TypeIdentity::Item(id)` to match + /// Yjs 13.6.21 merged update encoding order (higher client IDs first, ascending clock per client). + pub(crate) fn refresh_surface_element_order( + &self, + surface_id: &str, + entries: &[(String, SessionReadValue)], + ) -> Vec { + let present: BTreeMap<&str, (u64, u64)> = entries + .iter() + .map(|(k, v)| { + let key_order = match v { + SessionReadValue::Map(TypeIdentity::Item(id)) => (id.client, id.clock), + _ => (0, u64::MAX), + }; + (k.as_str(), key_order) + }) + .collect(); + let mut map = self.surface_element_order.borrow_mut(); + let order = map.entry(surface_id.to_string()).or_default(); + order.retain(|k| present.contains_key(k.as_str())); + let existing: BTreeSet = order.iter().cloned().collect(); + let mut added: Vec<(&str, (u64, u64))> = present + .iter() + .filter(|(k, _)| !existing.contains(**k)) + .map(|(&k, &ord)| (k, ord)) + .collect(); + added.sort_by(|a, b| { + b.1.0 + .cmp(&a.1.0) + .then_with(|| a.1.1.cmp(&b.1.1)) + .then_with(|| a.0.cmp(b.0)) + }); + order.extend(added.into_iter().map(|(k, _)| k.to_string())); + order.clone() + } + + /// Refresh per-surface element orders across all `affine:surface` blocks currently in `blocks`. + fn refresh_all_surface_orders(&self) { + let Ok(blocks) = self.session.read_map(&self.blocks_target) else { + return; + }; + for (block_id, value) in blocks { + let SessionReadValue::Map(block_ident) = value else { + continue; + }; + let block_target = TypeTarget::Identity(block_ident); + let is_surface = matches!( + self.session.get_map_value(&block_target, "sys:flavour"), + Ok(Some(SessionReadValue::Any(Any::String(f)))) if f == "affine:surface" + ); + if !is_surface { + continue; + } + if let Ok(Some(SessionReadValue::Map(elems_ident))) = + self.session.get_map_value(&block_target, "prop:elements") + && let Ok(Some(SessionReadValue::Map(val_ident))) = self + .session + .get_map_value(&TypeTarget::Identity(elems_ident), "value") + && let Ok(entries) = self.session.read_map(&TypeTarget::Identity(val_ident)) + { + self.refresh_surface_element_order(&block_id, &entries); + } + } + } + pub fn guid(&self) -> &str { self.session.guid() } @@ -223,6 +295,7 @@ impl PageDocSession { /// commits so the caller can broadcast them back to the room. pub fn apply_remote_update_v1(&mut self, bytes: &[u8]) -> DocResult { let commits = self.session.apply_update_v1(bytes)?; + self.refresh_all_surface_orders(); let outbound_updates = commits .iter() .filter(|c| { @@ -487,6 +560,685 @@ impl PageDocSession { Ok(self.session.map_set(&target, field.into(), value)?) } + /// Format `[x, y, w, h]` into BlockSuite's wire `xywh` JSON string. + pub fn format_xywh(xywh: [f64; 4]) -> String { + let fmt = |v: f64| { + let rounded = (v * 100.0).round() / 100.0; + if (rounded - rounded.round()).abs() < 1e-6 { + format!("{}", rounded.round() as i64) + } else { + format!("{rounded}") + } + }; + format!( + "[{},{},{},{}]", + fmt(xywh[0]), + fmt(xywh[1]), + fmt(xywh[2]), + fmt(xywh[3]) + ) + } + + /// Find the page's existing `affine:surface` block, or create one under the root page. + pub fn ensure_surface_block(&mut self, now_ms: u64) -> DocResult { + let snapshot = self.read_page_snapshot()?; + let root = snapshot + .root + .as_ref() + .ok_or_else(|| DocError::InvalidState("page has no root block".into()))?; + if let Some(surface) = root + .children + .iter() + .find(|c| matches!(c.content, crate::read::BlockContent::Surface { .. })) + { + return Ok(surface.id.clone()); + } + let surface_id = format!("surface:{}", root.id); + self.add_block( + surface_id.clone(), + BlockSpec::Surface, + Some(&root.id), + Some(0), + now_ms, + )?; + Ok(surface_id) + } + + /// Remove a surface element from `surface_block_id`'s `prop:elements.value` `Y.Map`. + /// Recursively clear all children of a Yjs container leaf-first so every underlying + /// `store.delete_item` deletes a single item (`ranges.len() == 1`), keeping + /// `DeleteSet` ranges sorted regardless of map iteration order. + fn clear_value_canonically(&mut self, value: SessionReadValue) -> DocResult<()> { + match value { + SessionReadValue::Map(ident) => { + let target = TypeTarget::Identity(ident); + let mut entries = self.session.read_map(&target)?; + entries.sort_by(|a, b| a.0.cmp(&b.0)); + for (k, v) in entries { + self.clear_value_canonically(v)?; + self.session.map_remove(&target, &k)?; + } + } + SessionReadValue::Array(ident) => { + let target = TypeTarget::Identity(ident); + let items = self.session.read_array(&target)?; + for (idx, v) in items.into_iter().enumerate().rev() { + self.clear_value_canonically(v)?; + self.session.array_remove(&target, idx as u64, 1)?; + } + } + SessionReadValue::Text(ident) => { + let target = TypeTarget::Identity(ident); + let len = self.session.read_text_len(&target)?; + if len > 0 { + self.session.text_remove(&target, 0, len)?; + } + } + _ => {} + } + Ok(()) + } + + pub fn remove_surface_element( + &mut self, + surface_block_id: &str, + element_id: &str, + now_ms: u64, + ) -> DocResult { + let elements_value_target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value"), + ); + let element_id = element_id.to_string(); + if self.session.tx_depth() == 0 { + return self.structural_edit(now_ms, move |page| { + if let Some(val) = page + .session + .get_map_value(&elements_value_target, &element_id)? + { + page.clear_value_canonically(val)?; + } + page.session + .map_remove(&elements_value_target, &element_id)?; + Ok(()) + }); + } + self.advance_time(now_ms); + if let Some(val) = self + .session + .get_map_value(&elements_value_target, &element_id)? + { + self.clear_value_canonically(val)?; + } + Ok(self + .session + .map_remove(&elements_value_target, &element_id)?) + } + + /// Update multiple fields on an existing surface element in one tracked transaction. + pub fn update_surface_element_fields( + &mut self, + surface_block_id: &str, + element_id: &str, + fields: Vec<(String, SessionValue)>, + now_ms: u64, + ) -> DocResult { + let surface_block_id = surface_block_id.to_string(); + let element_id = element_id.to_string(); + self.structural_edit(now_ms, move |page| { + let target = TypeTarget::Path( + TypePath::root("blocks") + .key(&surface_block_id) + .key("prop:elements") + .key("value") + .key(&element_id), + ); + for (field, value) in fields { + page.session.map_set(&target, field, value)?; + } + Ok(()) + }) + } + + /// Splice a UTF-16 range on a surface element's `Y.Text` field (`"text"` or `"title"`), + /// preserving untouched prefix/suffix characters and formatting marks under concurrent edits. + #[allow(clippy::too_many_arguments)] + pub fn splice_surface_element_text( + &mut self, + surface_block_id: &str, + element_id: &str, + field: &str, + utf16_start: u64, + utf16_delete_len: u64, + insert: &str, + now_ms: u64, + ) -> DocResult { + self.advance_time(now_ms); + let elem_target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value") + .key(element_id), + ); + match self.session.get_map_value(&elem_target, field)? { + Some(SessionReadValue::Text(identity)) => { + let target = TypeTarget::Identity(identity); + let len = self.session.read_text_len(&target)?; + let start = utf16_start.min(len); + let del = utf16_delete_len.min(len.saturating_sub(start)); + if del > 0 && !insert.is_empty() { + let insert = insert.to_string(); + self.structural_edit(now_ms, move |page| { + page.session.text_remove(&target, start, del)?; + page.session.text_insert(&target, start, &insert)?; + Ok(()) + }) + } else if del > 0 { + Ok(self.session.text_remove(&target, start, del)?) + } else if !insert.is_empty() { + Ok(self.session.text_insert(&target, start, insert)?) + } else { + Ok(None) + } + } + _ => { + let delta = if insert.is_empty() { + Vec::new() + } else { + vec![TextDeltaOp::Insert { + insert: TextInsert::Text(insert.to_string()), + format: None, + }] + }; + Ok(self.session.map_set( + &elem_target, + field.to_string(), + SessionValue::Text(delta), + )?) + } + } + } + + /// Splice a UTF-16 range on a block's `prop:title` `Y.Text` (e.g. `affine:frame`), + /// preserving untouched prefix/suffix characters and marks. + pub fn splice_block_title_text( + &mut self, + block_id: &str, + utf16_start: u64, + utf16_delete_len: u64, + insert: &str, + now_ms: u64, + ) -> DocResult { + self.advance_time(now_ms); + let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key("prop:title")); + let len = self.session.read_text_len(&target).unwrap_or(0); + let start = utf16_start.min(len); + let del = utf16_delete_len.min(len.saturating_sub(start)); + if del > 0 && !insert.is_empty() { + let insert = insert.to_string(); + self.structural_edit(now_ms, move |page| { + page.session.text_remove(&target, start, del)?; + page.session.text_insert(&target, start, &insert)?; + Ok(()) + }) + } else if del > 0 { + Ok(self.session.text_remove(&target, start, del)?) + } else if !insert.is_empty() { + Ok(self.session.text_insert(&target, start, insert)?) + } else { + Ok(None) + } + } + + /// Encode a `RelativePosition` at UTF-16 `offset` on a surface element's `Y.Text` field. + pub fn encode_surface_text_relative_position( + &self, + surface_block_id: &str, + element_id: &str, + field: &str, + offset: u64, + ) -> DocResult> { + let elem_target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value") + .key(element_id), + ); + let Some(SessionReadValue::Text(identity)) = + self.session.get_map_value(&elem_target, field)? + else { + return Ok(None); + }; + let target = TypeTarget::Identity(identity); + let clamped = offset.min(self.session.read_text_len(&target)?); + Ok(Some( + self.session + .create_relative_position(&target, clamped, -1)?, + )) + } + + /// Resolve a `RelativePosition` back to a UTF-16 offset on a surface element's `Y.Text` field. + pub fn resolve_surface_text_relative_position( + &self, + surface_block_id: &str, + element_id: &str, + field: &str, + pos: &RelativePosition, + ) -> DocResult> { + let elem_target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value") + .key(element_id), + ); + let Some(SessionReadValue::Text(identity)) = + self.session.get_map_value(&elem_target, field)? + else { + return Ok(None); + }; + let Some(abs) = self.session.resolve_relative_position(pos, true) else { + return Ok(None); + }; + Ok((abs.r#type == identity).then_some(abs.index)) + } + + /// Encode a `RelativePosition` at UTF-16 `offset` on a block's `prop:title` `Y.Text`. + pub fn encode_block_title_relative_position( + &self, + block_id: &str, + offset: u64, + ) -> DocResult> { + let block = TypeTarget::Path(TypePath::root("blocks").key(block_id)); + let Some(SessionReadValue::Text(identity)) = + self.session.get_map_value(&block, "prop:title")? + else { + return Ok(None); + }; + let target = TypeTarget::Identity(identity); + let clamped = offset.min(self.session.read_text_len(&target)?); + Ok(Some( + self.session + .create_relative_position(&target, clamped, -1)?, + )) + } + + /// Resolve a `RelativePosition` back to a UTF-16 offset on a block's `prop:title` `Y.Text`. + pub fn resolve_block_title_relative_position( + &self, + block_id: &str, + pos: &RelativePosition, + ) -> DocResult> { + let block = TypeTarget::Path(TypePath::root("blocks").key(block_id)); + let Some(SessionReadValue::Text(identity)) = + self.session.get_map_value(&block, "prop:title")? + else { + return Ok(None); + }; + let Some(abs) = self.session.resolve_relative_position(pos, true) else { + return Ok(None); + }; + Ok((abs.r#type == identity).then_some(abs.index)) + } + + /// Create an Edgeless-only Note (`prop:displayMode = "edgeless"`) with an initial paragraph + /// child in one atomic undoable transaction. + #[allow(clippy::too_many_arguments)] + pub fn add_edgeless_note( + &mut self, + root_id: &str, + note_id: &str, + para_id: &str, + index: &str, + xywh: [f64; 4], + text: &str, + now_ms: u64, + ) -> DocResult { + let root_id = root_id.to_string(); + let note_id = note_id.to_string(); + let para_id = para_id.to_string(); + let index = index.to_string(); + let text = text.to_string(); + self.structural_edit(now_ms, move |page| { + page.add_block( + ¬e_id, + BlockSpec::Note { + xywh: Some(Self::format_xywh(xywh)), + }, + Some(&root_id), + None, + now_ms, + )?; + let note_target = block_target(¬e_id); + page.session.map_set( + ¬e_target, + "prop:displayMode".to_string(), + SessionValue::Any(Any::String("edgeless".into())), + )?; + page.set_block_index(¬e_id, &index, now_ms)?; + page.add_block( + ¶_id, + BlockSpec::Paragraph { + paragraph_type: crate::schema::ParagraphType::Text, + text, + }, + Some(¬e_id), + None, + now_ms, + )?; + Ok(()) + }) + } + + /// Create an `affine:frame` under `surface_id` (creating `affine:surface` inside the same + /// transaction when `surface_id` is `None`), set its `prop:index`, and populate + /// `prop:childElementIds` with `enclosed_ids` in one atomic undoable transaction. + #[allow(clippy::too_many_arguments)] + pub fn add_frame_with_children( + &mut self, + surface_id: Option<&str>, + frame_id: &str, + title: &str, + index: &str, + xywh: [f64; 4], + enclosed_ids: &[&str], + now_ms: u64, + ) -> DocResult { + let surface_id = surface_id.map(str::to_string); + let frame_id = frame_id.to_string(); + let title = title.to_string(); + let index = index.to_string(); + let enclosed_ids: Vec = enclosed_ids.iter().map(|s| (*s).to_string()).collect(); + self.structural_edit(now_ms, move |page| { + let sid = match &surface_id { + Some(id) => id.clone(), + None => page.ensure_surface_block(now_ms)?, + }; + page.add_block( + &frame_id, + BlockSpec::Frame { + title, + xywh: Some(Self::format_xywh(xywh)), + presentation_index: Some(index.clone()), + }, + Some(&sid), + None, + now_ms, + )?; + page.set_block_index(&frame_id, &index, now_ms)?; + if !enclosed_ids.is_empty() { + page.set_frame_child_element_ids(&frame_id, &enclosed_ids, now_ms)?; + } + Ok(()) + }) + } + + /// Commit a connector label on close (matching BlockSuite `edgeless-connector-label-editor.ts`): + /// - If `trimmed_text.is_empty()`, removes `"text"`, `"labelXYWH"`, and `"labelOffset"`. + /// - Otherwise sets `labelDisplay: true`, writes `labelOffset` (`{ distance: 0.5, anchor: "center" }`) + /// as a plain `Any::Object` if absent, and writes `labelXYWH` wrapped via [`crate::schema::map_array_any`]. + pub fn commit_connector_label( + &mut self, + surface_block_id: &str, + element_id: &str, + trimmed_text: &str, + label_xywh: [f64; 4], + now_ms: u64, + ) -> DocResult { + self.advance_time(now_ms); + let elem_target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value") + .key(element_id), + ); + if trimmed_text.is_empty() { + return self.structural_edit(now_ms, move |page| { + for key in ["text", "labelXYWH", "labelOffset"] { + let _ = page.session.map_remove(&elem_target, key); + } + Ok(()) + }); + } + let has_offset = self + .session + .get_map_value(&elem_target, "labelOffset")? + .is_some(); + let mut fields = vec![ + ("labelDisplay".to_string(), SessionValue::Any(Any::True)), + ( + "labelXYWH".to_string(), + SessionValue::Any(crate::schema::map_array_any( + label_xywh + .into_iter() + .map(|v| Any::Float64(v.into())) + .collect(), + )), + ), + ]; + if !has_offset { + let mut offset_map = y_octo::AHashMap::default(); + offset_map.insert("distance".to_string(), Any::Float64(0.5.into())); + offset_map.insert("anchor".to_string(), Any::String("center".to_string())); + fields.push(( + "labelOffset".to_string(), + SessionValue::Any(Any::Object(Box::new(offset_map))), + )); + } + self.update_surface_element_fields(surface_block_id, element_id, fields, now_ms) + } + + /// Delete the given blocks and surface elements, cascading to remove every `Connector` + /// in any `affine:surface` whose `source.id` or `target.id` references a deleted ID, + /// in one atomic undoable transaction. + pub fn delete_blocks_and_elements_with_connectors( + &mut self, + block_ids: &[&str], + surface_elements: &[(&str, &str)], + now_ms: u64, + ) -> DocResult { + let snap = self.read_page_snapshot()?; + let mut deleted_ids: std::collections::HashSet = block_ids + .iter() + .map(|s| (*s).to_string()) + .chain(surface_elements.iter().map(|(_, eid)| (*eid).to_string())) + .collect(); + let mut cascade_connectors: Vec<(String, String)> = Vec::new(); + if let Some(root) = &snap.root { + for node in root.walk() { + if let crate::read::BlockContent::Surface { elements, .. } = &node.content { + for el in elements { + if let crate::read::SurfaceElementKind::Connector(c) = &el.kind { + let src_hit = c + .source + .id + .as_deref() + .is_some_and(|id| deleted_ids.contains(id)); + let tgt_hit = c + .target + .id + .as_deref() + .is_some_and(|id| deleted_ids.contains(id)); + if (src_hit || tgt_hit) && deleted_ids.insert(el.id.clone()) { + cascade_connectors.push((node.id.clone(), el.id.clone())); + } + } + } + } + } + } + let block_parents: Vec<(String, Option)> = block_ids + .iter() + .map(|&bid| { + let parent = snap.root.as_ref().and_then(|root| { + root.walk() + .find(|n| n.children.iter().any(|c| c.id == bid)) + .map(|n| n.id.clone()) + }); + (bid.to_string(), parent) + }) + .collect(); + let mut all_surf: Vec<(String, String)> = surface_elements + .iter() + .map(|(s, e)| ((*s).to_string(), (*e).to_string())) + .collect(); + all_surf.extend(cascade_connectors); + + self.structural_edit(now_ms, move |page| { + for (sid, eid) in &all_surf { + page.remove_surface_element(sid, eid, now_ms)?; + } + for (bid, parent) in &block_parents { + if let Some(parent_id) = parent { + page.delete_block_subtree(parent_id, bid, now_ms)?; + } + } + Ok(()) + }) + } + + /// Replace the `Y.Text` field (`"text"` or `"title"`) on a surface element. + pub fn set_surface_element_text( + &mut self, + surface_block_id: &str, + element_id: &str, + field: &str, + text: &str, + now_ms: u64, + ) -> DocResult { + self.advance_time(now_ms); + let elem_target = TypeTarget::Path( + TypePath::root("blocks") + .key(surface_block_id) + .key("prop:elements") + .key("value") + .key(element_id), + ); + let existing = self.session.get_map_value(&elem_target, field)?; + match existing { + Some(SessionReadValue::Text(identity)) => { + let target = TypeTarget::Identity(identity); + let len = self.session.read_text_len(&target)?; + let text = text.to_string(); + self.structural_edit(now_ms, move |page| { + if len > 0 { + page.session.text_remove(&target, 0, len)?; + } + if !text.is_empty() { + page.session.text_insert(&target, 0, &text)?; + } + Ok(()) + }) + } + _ => { + let delta = if text.is_empty() { + Vec::new() + } else { + vec![TextDeltaOp::Insert { + insert: TextInsert::Text(text.to_string()), + format: None, + }] + }; + Ok(self.session.map_set( + &elem_target, + field.to_string(), + SessionValue::Text(delta), + )?) + } + } + } + + /// Replace `prop:title` `Y.Text` on a block (such as `affine:frame` or `affine:page`). + pub fn set_block_title_text( + &mut self, + block_id: &str, + text: &str, + now_ms: u64, + ) -> DocResult { + self.advance_time(now_ms); + let target = TypeTarget::Path(TypePath::root("blocks").key(block_id).key("prop:title")); + let len = self.session.read_text_len(&target).unwrap_or(0); + let text = text.to_string(); + self.structural_edit(now_ms, move |page| { + if len > 0 { + page.session.text_remove(&target, 0, len)?; + } + if !text.is_empty() { + page.session.text_insert(&target, 0, &text)?; + } + Ok(()) + }) + } + + /// Update `prop:xywh` on a spatial block (`affine:note`, `affine:frame`, `affine:edgeless-text`). + pub fn set_block_xywh( + &mut self, + block_id: &str, + xywh: [f64; 4], + now_ms: u64, + ) -> DocResult { + self.set_block_prop( + block_id, + "prop:xywh", + SessionValue::Any(Any::String(Self::format_xywh(xywh))), + now_ms, + ) + } + + /// Update `prop:index` on a spatial block. + pub fn set_block_index( + &mut self, + block_id: &str, + index: &str, + now_ms: u64, + ) -> DocResult { + self.set_block_prop( + block_id, + "prop:index", + SessionValue::Any(Any::String(index.to_string())), + now_ms, + ) + } + + /// Update `prop:rotate` on a spatial block (e.g. `affine:edgeless-text`). + pub fn set_block_rotate( + &mut self, + block_id: &str, + rotate: f64, + now_ms: u64, + ) -> DocResult { + self.set_block_prop( + block_id, + "prop:rotate", + SessionValue::Any(Any::Float64(rotate.into())), + now_ms, + ) + } + + /// Replace `prop:childElementIds` on an `affine:frame` block. + pub fn set_frame_child_element_ids( + &mut self, + frame_id: &str, + child_ids: &[String], + now_ms: u64, + ) -> DocResult { + let entries = child_ids + .iter() + .map(|id| (id.clone(), SessionValue::Any(Any::True))) + .collect(); + self.set_block_prop( + frame_id, + "prop:childElementIds", + SessionValue::Map(entries), + now_ms, + ) + } + fn child_graph(&self) -> DocResult { self.session .read_map(&self.blocks_target)? @@ -557,6 +1309,9 @@ impl PageDocSession { page.session .array_remove(&children_target(parent_id), index, 1)?; for id in candidates.difference(&retained) { + if let Some(val) = page.session.get_map_value(&page.blocks_target, id)? { + page.clear_value_canonically(val)?; + } page.session.map_remove(&page.blocks_target, id)?; } Ok(()) @@ -1151,11 +1906,15 @@ impl PageDocSession { } pub fn undo(&mut self) -> DocResult>> { - Ok(self.session.undo_stack(self.undo_stack_id)?) + let res = self.session.undo_stack(self.undo_stack_id)?; + self.refresh_all_surface_orders(); + Ok(res) } pub fn redo(&mut self) -> DocResult>> { - Ok(self.session.redo_stack(self.undo_stack_id)?) + let res = self.session.redo_stack(self.undo_stack_id)?; + self.refresh_all_surface_orders(); + Ok(res) } pub fn can_undo(&self) -> bool { diff --git a/blocksuite/native-playground/crates/doc/tests/structural_edits.rs b/blocksuite/native-playground/crates/doc/tests/structural_edits.rs index 841131a564..7b13ce72a4 100644 --- a/blocksuite/native-playground/crates/doc/tests/structural_edits.rs +++ b/blocksuite/native-playground/crates/doc/tests/structural_edits.rs @@ -334,3 +334,247 @@ fn converting_to_a_leaf_lifts_children_at_the_replaced_slot() -> DocResult { assert_eq!(p.export_doc_json()?, original); Ok(()) } + +#[test] +fn commit_connector_label_encodes_single_array_item_and_plain_object_offset() -> DocResult { + use blocksuite_playground_doc::schema::{ConnectorEndpointSpec, SurfaceElementSpec}; + use y_octo::{SessionReadValue, StateVector, TypePath, TypeTarget}; + + let mut p = PageDocSession::new("doc", 42)?; + p.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?; + p.add_block("surf", BlockSpec::Surface, Some("root"), None, 1)?; + p.add_surface_element( + "surf", + "c1", + "a0", + SurfaceElementSpec::Connector { + mode: 1, + seed: 7, + source: ConnectorEndpointSpec::point(0.0, 0.0), + target: ConnectorEndpointSpec::point(200.0, 100.0), + text: None, + label_xywh: None, + }, + 2, + )?; + // Clear any default labelOffset first so commit_connector_label exercises both labelXYWH and labelOffset writes. + p.commit_connector_label("surf", "c1", "", [0.0; 4], 3)?; + let sv_before = StateVector::decode_v1(&p.encode_state_vector_v1()?)?; + let clock_before = sv_before.get(&42); + let commit = p + .commit_connector_label("surf", "c1", "Edge", [120.0, 140.0, 64.0, 24.0], 4)? + .expect("commit"); + let sv_after = StateVector::decode_v1(&p.encode_state_vector_v1()?)?; + let clock_after = sv_after.get(&42); + // Exactly 3 single-element map items: labelDisplay (1) + labelXYWH (1, NOT 4!) + labelOffset (1). + assert_eq!( + clock_after - clock_before, + 3, + "labelXYWH must consume 1 CRDT clock (single Content::Any wrapping Any::Array), not 4" + ); + + let mut peer = PageDocSession::new("doc", 99)?; + peer.apply_remote_update_v1(&p.encode_update_v1()?)?; + let _ = commit; + let elem_target = TypeTarget::Path( + TypePath::root("blocks") + .key("surf") + .key("prop:elements") + .key("value") + .key("c1"), + ); + match peer.inner().get_map_value(&elem_target, "labelXYWH")? { + Some(SessionReadValue::Any(Any::Array(vals))) => { + assert_eq!(vals.len(), 4); + assert_eq!(vals[0], Any::Float64(120.0.into())); + assert_eq!(vals[3], Any::Float64(24.0.into())); + } + other => panic!("expected Any::Array(4) for labelXYWH, got {other:?}"), + } + match peer.inner().get_map_value(&elem_target, "labelOffset")? { + Some(SessionReadValue::Any(Any::Object(obj))) => { + assert_eq!(obj.get("distance"), Some(&Any::Float64(0.5.into()))); + assert_eq!(obj.get("anchor"), Some(&Any::String("center".to_string()))); + } + other => panic!("expected plain Any::Object for labelOffset, got {other:?}"), + } + Ok(()) +} + +#[test] +fn fresh_page_frame_creation_is_atomic_across_peer_sync_and_undo() -> DocResult { + let mut a = PageDocSession::new("doc", 43)?; + a.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?; + let mut peer = PageDocSession::new("doc", 44)?; + peer.apply_remote_update_v1(&a.encode_update_v1()?)?; + let initial_json = a.export_doc_json()?; + + let commit = a + .add_frame_with_children( + None, + "frame-1", + "Frame", + "a0", + [10.0, 20.0, 300.0, 200.0], + &[], + 10, + )? + .expect("single atomic commit"); + peer.apply_remote_update_v1(&commit.update)?; + assert_eq!(peer.export_doc_json()?, a.export_doc_json()?); + let snap = peer.read_page_snapshot()?; + assert!(snap.block("frame-1").is_some()); + + a.undo()?; + assert_eq!(a.export_doc_json()?, initial_json); + Ok(()) +} + +#[test] +fn multi_author_merged_v1_surface_tiebreak_matches_yjs_client_desc_clock_asc() -> DocResult { + use blocksuite_playground_doc::{read::BlockContent, schema::SurfaceElementSpec}; + + let mut base = PageDocSession::new("doc", 5)?; + base.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?; + base.add_block("surf", BlockSpec::Surface, Some("root"), None, 1)?; + let seed = base.encode_update_v1()?; + + let mut c10 = PageDocSession::new("doc", 10)?; + c10.apply_remote_update_v1(&seed)?; + let mut c20 = PageDocSession::new("doc", 20)?; + c20.apply_remote_update_v1(&seed)?; + + let shape = |xywh: &str| SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: xywh.into(), + seed: 1, + filled: true, + text: None, + }; + let u20 = c20 + .add_surface_element("surf", "z", "a0", shape("[0,0,40,40]"), 10)? + .unwrap() + .update; + let u10_a = c10 + .add_surface_element("surf", "a", "a0", shape("[10,0,40,40]"), 10)? + .unwrap() + .update; + c20.apply_remote_update_v1(&u10_a)?; + let merged = c20.encode_update_v1()?; + + let mut observer = PageDocSession::new("doc", 99)?; + observer.apply_remote_update_v1(&merged)?; + let snap = observer.read_page_snapshot()?; + let BlockContent::Surface { elements, .. } = &snap.block("surf").unwrap().content else { + panic!("expected surface"); + }; + let ids: Vec<&str> = elements.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, vec!["z", "a"]); + + // Same-client sequential inserts with equal index preserve clock ascending order. + let mut seq = PageDocSession::new("doc", 30)?; + seq.apply_remote_update_v1(&seed)?; + seq.add_surface_element("surf", "first", "a0", shape("[0,0,20,20]"), 10)?; + seq.add_surface_element("surf", "second", "a0", shape("[30,0,20,20]"), 11)?; + let mut seq_obs = PageDocSession::new("doc", 31)?; + seq_obs.apply_remote_update_v1(&seq.encode_update_v1()?)?; + let seq_snap = seq_obs.read_page_snapshot()?; + let BlockContent::Surface { elements, .. } = &seq_snap.block("surf").unwrap().content else { + panic!("expected surface"); + }; + let seq_ids: Vec<&str> = elements.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(seq_ids, vec!["first", "second"]); + let _ = u20; + Ok(()) +} + +#[test] +fn cascade_delete_after_property_mutations_undoes_and_redoes_all_elements() -> DocResult { + use blocksuite_playground_doc::{ + read::BlockContent, + schema::{ConnectorEndpointSpec, SurfaceElementSpec}, + }; + use y_octo::SessionValue; + + let mut page = PageDocSession::new("doc", 77)?; + page.add_block("root", BlockSpec::Page { title: "T".into() }, None, None, 0)?; + page.add_block("surf", BlockSpec::Surface, Some("root"), None, 1)?; + page.add_surface_element( + "surf", + "sh-1", + "a0", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[100,100,120,80]".into(), + seed: 11, + filled: true, + text: Some("Box".into()), + }, + 2, + )?; + page.add_surface_element( + "surf", + "conn-att", + "a1", + SurfaceElementSpec::Connector { + mode: 0, + seed: 12, + source: ConnectorEndpointSpec::element("sh-1", Some([1.0, 0.5])), + target: ConnectorEndpointSpec::point(340.0, 140.0), + text: None, + label_xywh: None, + }, + 3, + )?; + // Mutate sh-1 fields after conn-att so sh-1 holds clocks both below and above conn-att. + page.set_surface_element_field( + "surf", + "sh-1", + "xywh", + SessionValue::Any(Any::String("[140,125,120,80]".into())), + 4, + )?; + page.set_surface_element_field( + "surf", + "sh-1", + "rotate", + SessionValue::Any(Any::Float64(45.0.into())), + 5, + )?; + page.set_surface_element_field( + "surf", + "sh-1", + "index", + SessionValue::Any(Any::String("a2".into())), + 6, + )?; + page.stop_capturing()?; + + let before_delete = page.export_doc_json()?; + page.delete_blocks_and_elements_with_connectors(&[], &[("surf", "sh-1")], 10)?; + let after_delete = page.export_doc_json()?; + let snap_del = page.read_page_snapshot()?; + let BlockContent::Surface { elements, .. } = &snap_del.block("surf").unwrap().content else { + panic!("expected surface"); + }; + assert!( + elements.is_empty(), + "both sh-1 and conn-att must be deleted" + ); + + page.undo()?; + assert_eq!(page.export_doc_json()?, before_delete); + let snap_undo = page.read_page_snapshot()?; + let BlockContent::Surface { elements, .. } = &snap_undo.block("surf").unwrap().content else { + panic!("expected surface"); + }; + let ids: Vec<&str> = elements.iter().map(|e| e.id.as_str()).collect(); + assert!( + ids.contains(&"sh-1") && ids.contains(&"conn-att"), + "undo must restore both sh-1 and conn-att: {ids:?}" + ); + + page.redo()?; + assert_eq!(page.export_doc_json()?, after_delete); + Ok(()) +} diff --git a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs index 0238776c18..7aa30b0186 100644 --- a/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs +++ b/blocksuite/native-playground/crates/playground/src/bin/bs_harness.rs @@ -290,6 +290,10 @@ enum OverlayState { DragDropIndicator, CodeHover, CodeHoverCopied, + EdgelessSelected, + EdgelessMarquee, + EdgelessInlineEdit, + EdgelessAuthoring, } impl OverlayState { @@ -308,6 +312,13 @@ impl OverlayState { Self::CodeHoverCopied, ]; + const ALL_EDGELESS: [Self; 4] = [ + Self::EdgelessSelected, + Self::EdgelessMarquee, + Self::EdgelessInlineEdit, + Self::EdgelessAuthoring, + ]; + fn name(self) -> &'static str { match self { Self::Default => "default", @@ -322,11 +333,28 @@ impl OverlayState { Self::DragDropIndicator => "drag_drop_indicator", Self::CodeHover => "code_hover", Self::CodeHoverCopied => "code_hover_copied", + Self::EdgelessSelected => "edgeless_selected", + Self::EdgelessMarquee => "edgeless_marquee", + Self::EdgelessInlineEdit => "edgeless_inline_edit", + Self::EdgelessAuthoring => "edgeless_authoring", } } fn parse(value: &str) -> Option { - Self::ALL.into_iter().find(|state| state.name() == value) + Self::ALL + .into_iter() + .chain(Self::ALL_EDGELESS) + .find(|state| state.name() == value) + } + + fn is_edgeless(self) -> bool { + matches!( + self, + Self::EdgelessSelected + | Self::EdgelessMarquee + | Self::EdgelessInlineEdit + | Self::EdgelessAuthoring + ) } /// Snapshot ids the state must show once it is applied. @@ -351,6 +379,26 @@ impl OverlayState { Self::DragHandleHover => &["overlay.drag_handle"], Self::DragDropIndicator => &["overlay.drag_handle", "overlay.drop_indicator"], Self::CodeHover | Self::CodeHoverCopied => &["page.block.showcase-code.copy"], + Self::EdgelessSelected => &[ + "edgeless.viewport", + "chrome.edgeless_toolbar", + "chrome.edgeless_zoom", + ], + Self::EdgelessMarquee => &[ + "edgeless.viewport", + "chrome.edgeless_toolbar", + "chrome.edgeless_zoom", + ], + Self::EdgelessInlineEdit => &[ + "edgeless.viewport", + "chrome.edgeless_toolbar", + "edgeless.inline_edit", + ], + Self::EdgelessAuthoring => &[ + "edgeless.viewport", + "chrome.edgeless_toolbar", + "chrome.edgeless_zoom", + ], } } } @@ -458,6 +506,73 @@ fn apply_overlay_state(session: &HeadlessSession, state: OverlayState) -> Result session.headless_win.simulate_click(point(px(x), px(y))); } } + OverlayState::EdgelessSelected => { + session.frame()?; + session.update(|v, _, cx| { + v.edgeless_set_selection(["collect".to_string()], cx); + })?; + } + OverlayState::EdgelessMarquee => { + session.frame()?; + session.update(|v, _, cx| { + v.edgeless_set_selection(["collect".to_string(), "review".to_string()], cx); + v.edgeless_set_marquee((-120.0, -60.0), (540.0, 260.0), cx); + })?; + } + OverlayState::EdgelessInlineEdit => { + session.frame()?; + session.update(|v, w, cx| { + // Zoom to 1.4x centered on "collect" [818, 522, 150, 82] so inline edit is crisp and non-overlapping. + v.set_edgeless_camera(436.0, 296.0, 1.4, cx); + v.edgeless_begin_inline_edit("collect", w, cx); + v.replace_and_mark_text_in_range(None, " + edit", None, w, cx); + })?; + } + OverlayState::EdgelessAuthoring => { + session.frame()?; + // Frame open whiteboard space to the right (world x = 1220..1640, y = 220..760) + // alongside "collect"/"review" so authored items never overlap Page Note text. + session.update(|v, _, cx| { + v.set_edgeless_camera(740.0, 140.0, 0.85, cx); + })?; + session.frame()?; + // 1. Draw a Diamond shape in open canvas space: world (1250, 240) -> (1410, 360). + session.update(|v, w, cx| { + v.edgeless_select_tool( + playground::edgeless::EdgelessTool::Shape( + blocksuite_playground_doc::read::ShapeType::Diamond, + ), + w, + cx, + ); + })?; + session.pointer_down(433.5, 137.0); + session.pointer_move(569.5, 239.0, true); + session.pointer_up(569.5, 239.0); + session.frame()?; + // 2. Draw a port-snapped Orthogonal Connector from "review" right port to the new Diamond. + session.update(|v, w, cx| { + v.edgeless_select_tool(playground::edgeless::EdgelessTool::Connector, w, cx); + })?; + session.pointer_down(343.0, 578.0); + session.pointer_move(501.5, 239.0, true); + session.pointer_up(501.5, 239.0); + session.frame()?; + // 3. Draw a freehand Brush stroke in open canvas space: world (1260, 520) -> (1580, 560). + session.update(|v, w, cx| { + v.edgeless_select_tool(playground::edgeless::EdgelessTool::Brush, w, cx); + })?; + session.pointer_down(442.0, 375.0); + session.pointer_move(510.0, 345.0, true); + session.pointer_move(590.0, 415.0, true); + session.pointer_move(680.0, 365.0, true); + session.pointer_up(680.0, 365.0); + session.frame()?; + // 4. Show marquee selection around the open-space authored elements. + session.update(|v, _, cx| { + v.edgeless_set_marquee((1220.0, 210.0), (1620.0, 620.0), cx); + })?; + } } // Past every overlay transition, short of the `Copied` label's timeout. session.frame()?; @@ -592,6 +707,32 @@ fn run_audit_states() -> Result<()> { snapshot.elements.contains_key("chrome.edgeless_zoom"), "chrome.edgeless_zoom missing in {context}" ); + anyhow::ensure!( + snapshot.elements.contains_key("chrome.edgeless_toolbar"), + "chrome.edgeless_toolbar missing in {context}" + ); + audited += 1; + } + + // Audit Edgeless interactive authoring states in both themes and widths. + for state in OverlayState::ALL_EDGELESS { + let context = format!("{} {width}x{height} {}", state.name(), theme.as_str()); + let session = start_headless_session( + width, + height, + PlaygroundOptions { + theme, + mode: PlaygroundMode::Edgeless, + ..PlaygroundOptions::default() + }, + )?; + apply_overlay_state(&session, state).with_context(|| context.clone())?; + let snapshot = session.frame()?; + let violations = audit_frame_snapshot(&snapshot); + anyhow::ensure!( + violations.is_empty(), + "audit violations in {context}: {violations:#?}" + ); audited += 1; } } @@ -609,8 +750,11 @@ fn render_headless( zoom: Option, pan: Option<(f32, f32)>, state: OverlayState, - options: PlaygroundOptions, + mut options: PlaygroundOptions, ) -> Result<()> { + if state.is_edgeless() { + options.mode = PlaygroundMode::Edgeless; + } let theme = options.theme; let mode = options.mode; let session = start_headless_session(width, height, options)?; @@ -2539,6 +2683,162 @@ impl DemoRecorder<'_> { } } +/// Record a 60 fps full-product walkthrough: Page editing -> Edgeless switch -> +/// select/drag/rotate shape with live connector rerouting -> create shape, connector & brush -> +/// double-click inline IME label editing -> Undo/Redo -> Dark/Light theme toggle. +fn record_authoring_demo(dir: PathBuf) -> Result<()> { + std::fs::create_dir_all(&dir)?; + let session = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.frame()?; + let mut demo = DemoRecorder { + session: &session, + dir, + frames: 0, + pointer: (640.0, 400.0), + pressed: false, + }; + + // 1. Page editing (~0.8s). + demo.hold(12)?; + let intro_end = session.plain_text("showcase-intro")?.encode_utf16().count(); + let (ix, iy) = demo.text_point("showcase-intro", intro_end)?; + demo.move_to((ix + 16.0, iy), 10)?; + demo.click()?; + demo.type_text(" live!", 6)?; + demo.hold(12)?; + + // 2. Smooth mode switch to Edgeless (~0.6s). + let snap = session.frame()?; + let (ex, ey) = element_center(&snap, "chrome.mode_switcher.edgeless")?; + demo.move_to((ex, ey), 10)?; + demo.click()?; + demo.hold(24)?; + + // 3. Select & drag "collect" shape with live connector rerouting (~1.1s). + let snap = session.frame()?; + if let Ok((sx, sy)) = element_center(&snap, "edgeless.surface.collect") { + demo.move_to((sx, sy), 12)?; + demo.press(); + demo.move_to((sx + 70.0, sy - 35.0), 30)?; + demo.release(); + demo.hold(15)?; + } + + // 4. Rotate selected shape via top rotation handle (~0.8s). + let snap = session.frame()?; + if let Ok((rx, ry)) = element_center(&snap, "edgeless.handle.rotate") { + demo.move_to((rx, ry), 10)?; + demo.press(); + demo.move_to((rx + 48.0, ry + 18.0), 24)?; + demo.release(); + demo.hold(12)?; + } + + // 5. Frame clean open whiteboard space to the right (world x >= 1220) and draw a Diamond shape (~1.0s). + session.update(|v, _, cx| { + v.set_edgeless_camera(740.0, 140.0, 0.85, cx); + })?; + demo.hold(10)?; + let snap = session.frame()?; + if let Ok((tx, ty)) = element_center(&snap, "chrome.edgeless_toolbar.shape") { + demo.move_to((tx, ty), 10)?; + demo.click()?; + demo.hold(6)?; + } + session.update(|v, w, cx| { + v.edgeless_select_tool( + playground::edgeless::EdgelessTool::Shape( + blocksuite_playground_doc::read::ShapeType::Diamond, + ), + w, + cx, + ); + })?; + demo.move_to((433.5, 137.0), 10)?; + demo.press(); + demo.move_to((569.5, 239.0), 22)?; + demo.release(); + demo.hold(12)?; + + // 6. Pick Connector tool and drag a port-snapped orthogonal connector from "review" to the Diamond (~1.0s). + let snap = session.frame()?; + if let Ok((cx_t, cy_t)) = element_center(&snap, "chrome.edgeless_toolbar.connector") { + demo.move_to((cx_t, cy_t), 10)?; + demo.click()?; + demo.hold(6)?; + } + demo.move_to((343.0, 578.0), 10)?; + demo.press(); + demo.move_to((501.5, 239.0), 22)?; + demo.release(); + demo.hold(12)?; + + // 7. Pick Brush tool and draw a smooth freehand stroke in open canvas space (~1.0s). + let snap = session.frame()?; + if let Ok((bx, by)) = element_center(&snap, "chrome.edgeless_toolbar.brush") { + demo.move_to((bx, by), 10)?; + demo.click()?; + demo.hold(6)?; + } + demo.move_to((442.0, 385.0), 8)?; + demo.press(); + for step in 1..=24 { + let t = step as f32 / 24.0; + let x = 442.0 + t * 260.0; + let y = 385.0 + (t * std::f32::consts::TAU).sin() * 34.0; + demo.move_to((x, y), 1)?; + } + demo.release(); + demo.hold(12)?; + + // 8. Inline IME editing on "collect" shape label using bundled Inter glyphs (0 tofu boxes, ~1.2s). + session.update(|v, w, cx| { + v.edgeless_select_tool(playground::edgeless::EdgelessTool::Select, w, cx); + v.edgeless_begin_inline_edit("collect", w, cx); + })?; + demo.hold(12)?; + for pre in ["s", "sy", "syn", "sync"] { + session.update(|v, w, cx| { + v.replace_and_mark_text_in_range(None, pre, None, w, cx); + })?; + demo.hold(8)?; + } + session.update(|v, w, cx| { + v.replace_text_in_range(None, " + synced", w, cx); + v.edgeless_commit_inline_edit(w, cx); + })?; + demo.hold(16)?; + + // 9. Undo & Redo (~0.8s). + demo.key("z", true, 16)?; + demo.hold(14)?; + session.key("z", true, true); + demo.hold(18)?; + + // 10. Dark / Light theme toggle (~0.9s). + let snap = session.frame()?; + if let Ok((thx, thy)) = element_center(&snap, "chrome.theme_toggle") { + demo.move_to((thx, thy), 10)?; + demo.click()?; + demo.hold(24)?; + demo.click()?; + demo.hold(18)?; + } + + println!( + "record-authoring-demo wrote {} frames at 60 fps", + demo.frames + ); + Ok(()) +} + /// Record a walk through the page editor and its overlays at 60 fps into `dir` as /// `frame-.png`: typing with marks and a composition, a slash command, a mouse selection /// formatted from the toolbar, the block controls, and undo. Every step is an input event @@ -2751,7 +3051,7 @@ fn main() -> Result<()> { let mut args = std::env::args().skip(1); let Some(cmd) = args.next() else { bail!( - "usage: bs-harness [options]" + "usage: bs-harness [options]" ); }; @@ -2847,6 +3147,11 @@ fn main() -> Result<()> { .context("record-edgeless-demo requires an output directory")? .into(), ), + "record-authoring-demo" => record_authoring_demo( + args.next() + .context("record-authoring-demo requires an output directory")? + .into(), + ), "record-demo" => { let dir = args .next() diff --git a/blocksuite/native-playground/crates/playground/src/block_flow.rs b/blocksuite/native-playground/crates/playground/src/block_flow.rs index be976366cb..513dc00c22 100644 --- a/blocksuite/native-playground/crates/playground/src/block_flow.rs +++ b/blocksuite/native-playground/crates/playground/src/block_flow.rs @@ -2322,7 +2322,10 @@ pub struct PresenceMark { pub client_id: u64, pub name: SharedString, pub color: Hsla, - pub highlights: Vec, + /// `(block_id, rect)` for each selection highlight span; code-block spans are + /// translated by `-scroll_x` before clamping in `page_elements`. + pub highlights: Vec<(String, FlowRect)>, + pub caret_block_id: String, pub caret: FlowRect, pub label: FlowRect, label_text: ShapedLine, @@ -2366,14 +2369,23 @@ impl FlowLayout { let mut highlights = Vec::new(); let mut cover = |position: usize, start: usize, end: usize| { let (_, block, text) = text_blocks[position]; + let scrollable_code = block.body.code_scroll.is_some(); for (line, x0, x1) in text.layout.selection_spans(start, end) { let left = (block.x + text.x + x0).floor(); - let right = (block.x + text.x + x1).ceil().min(self.width); - highlights.push(FlowRect::new( - left, - block.y + text.y + line as f32 * text.layout.line_height(), - (right - left).max(0.0), - text.layout.line_height(), + let raw_right = (block.x + text.x + x1).ceil(); + let right = if scrollable_code { + raw_right + } else { + raw_right.min(self.width) + }; + highlights.push(( + block.block_id.clone(), + FlowRect::new( + left, + block.y + text.y + line as f32 * text.layout.line_height(), + (right - left).max(0.0), + text.layout.line_height(), + ), )); } }; @@ -2398,10 +2410,13 @@ impl FlowLayout { let (_, block, text) = text_blocks[caret_position]; let (caret_x, caret_line) = text.layout.caret(caret_offset); let line_height = text.layout.line_height(); + let raw_caret_x = (block.x + text.x + caret_x - 1.0).round(); let caret = FlowRect::new( - (block.x + text.x + caret_x - 1.0) - .round() - .clamp(0.0, (self.width - 2.0).max(0.0)), + if block.body.code_scroll.is_some() { + raw_caret_x + } else { + raw_caret_x.clamp(0.0, (self.width - 2.0).max(0.0)) + }, block.y + text.y + caret_line as f32 * line_height, 2.0, line_height, @@ -2414,7 +2429,7 @@ impl FlowLayout { let label_width = (f32::from(label_text.width()).ceil() + 8.0).min(self.width); // The tag hangs above the caret, shifted left at the column edge and flipped // below the caret when there is no room above. - let label_x = caret.x.min((self.width - label_width).max(0.0)); + let label_x = caret.x.clamp(0.0, (self.width - label_width).max(0.0)); let label_y = if caret.y >= PRESENCE_LABEL_HEIGHT { caret.y - PRESENCE_LABEL_HEIGHT } else { @@ -2425,6 +2440,7 @@ impl FlowLayout { name: SharedString::from(presence.name.clone()), color: presence.color, highlights, + caret_block_id: block.block_id.clone(), caret, label: FlowRect::new(label_x, label_y, label_width, PRESENCE_LABEL_HEIGHT), label_text, @@ -2519,19 +2535,52 @@ pub fn page_elements( } // Presence paints after every block so name tags stay above neighbouring text. Marks - // in a sideways-scrolled code block follow its lines and stay inside its code area. - let scrolled = paint.scrolled_code(layout); + // in a sideways-scrolled code block follow its lines and stay inside its code area; + // each highlight span uses its own block's horizontal scroll before clamping. + let code_blocks: HashMap<&str, ScrolledCode> = layout + .blocks + .iter() + .filter_map(|block| { + let code = block.body.code_scroll?; + let scroll_x = paint + .blocks + .get(&block.block_id) + .map_or(0.0, |state| state.code_scroll_x) + .clamp(0.0, code.max_x); + Some(( + block.block_id.as_str(), + ScrolledCode { + block: block.rect(), + area: code.area.translated(block.x, block.y), + scroll_x, + }, + )) + }) + .collect(); for mut mark in marks { - if let Some(code) = ScrolledCode::containing(&scrolled, &mark.caret) { - mark.highlights = mark - .highlights - .iter() - .filter_map(|rect| code.span(*rect)) - .collect(); + let mut resolved_highlights = Vec::with_capacity(mark.highlights.len()); + for (block_id, rect) in &mark.highlights { + let clamped = if let Some(code) = code_blocks.get(block_id.as_str()) { + code.span(*rect).and_then(|r| { + let left = r.x.max(0.0); + let right = r.right().min(layout.width); + (right > left).then(|| FlowRect::new(left, r.y, right - left, r.h)) + }) + } else { + let left = rect.x.max(0.0); + let right = rect.right().min(layout.width); + (right > left).then(|| FlowRect::new(left, rect.y, right - left, rect.h)) + }; + if let Some(rect) = clamped { + resolved_highlights.push(rect); + } + } + if let Some(code) = code_blocks.get(mark.caret_block_id.as_str()) { match code.caret(mark.caret) { - Some(caret) => { - mark.label.x = (mark.label.x - (mark.caret.x - caret.x)).max(0.0); + Some(mut caret) => { + caret.x = caret.x.clamp(0.0, (layout.width - 2.0).max(0.0)); mark.caret = caret; + mark.label.x = caret.x.clamp(0.0, (layout.width - mark.label.w).max(0.0)); } None => { // The caret scrolled out; its name tag goes with it. @@ -2550,7 +2599,7 @@ pub fn page_elements( }; // Same wash and corner radius as BlockSuite's remote selection rects. let highlight = mark.color.opacity(0.2); - for rect in &mark.highlights { + for rect in &resolved_highlights { if !viewport.intersects(rect) { continue; } diff --git a/blocksuite/native-playground/crates/playground/src/edgeless_camera.rs b/blocksuite/native-playground/crates/playground/src/edgeless/camera.rs similarity index 98% rename from blocksuite/native-playground/crates/playground/src/edgeless_camera.rs rename to blocksuite/native-playground/crates/playground/src/edgeless/camera.rs index 978d1335af..820f50ec2a 100644 --- a/blocksuite/native-playground/crates/playground/src/edgeless_camera.rs +++ b/blocksuite/native-playground/crates/playground/src/edgeless/camera.rs @@ -46,6 +46,13 @@ impl WorldRect { && self.bottom() > other.y } + pub fn contains_rect(self, inner: Self) -> bool { + inner.x >= self.x + && inner.y >= self.y + && inner.right() <= self.right() + && inner.bottom() <= self.bottom() + } + pub fn union(self, other: Self) -> Self { if self.is_empty() { return other; diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/canvas.rs b/blocksuite/native-playground/crates/playground/src/edgeless/canvas.rs new file mode 100644 index 0000000000..81b300f975 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/canvas.rs @@ -0,0 +1,463 @@ +//! Spatial Edgeless canvas state, layout caching, and world-space item preparation. + +use std::{ + collections::{BTreeMap, HashMap}, + rc::Rc, +}; + +use blocksuite_playground_doc::read::{BlockContent, BlockNode, NoteDisplayMode, PageSnapshot}; +use serde_json::Value as JsonValue; +use ui::{BorderStyle, Bounds, Hsla, Pixels, Point, Size, point, px}; + +use crate::{ + block_flow::{BlockFlow, FlowLayout, ImageSlot, InlineLayout}, + editor_session::{DocPoint, DocumentSelection}, + surface::{SurfaceLayout, WorldBounds}, + theme::{Palette, PlaygroundTheme}, +}; + +use super::{ + EdgelessAuthoringState, EdgelessCamera, PaintItem, SpatialItemInfo, WorldRect, parse_xywh, +}; + +pub const EDGELESS_VIEWPORT_ID: &str = "edgeless.viewport"; +/// Inner padding of an `affine:note` card on the Edgeless canvas (world px). +pub const NOTE_CARD_PADDING: f32 = 24.0; +/// Default corner radius of an `affine:note` card (world px). +pub(super) const CARD_RADIUS: f32 = 8.0; +/// Corner radius of an `affine:frame` container (world px, matching BlockSuite). +pub(super) const FRAME_RADIUS: f32 = 2.0; +/// Frame title pill height and vertical gap above the frame top edge (world px). +pub(super) const FRAME_TITLE_HEIGHT: f32 = 22.0; +pub(super) const FRAME_TITLE_GAP: f32 = 6.0; +/// Screen-space zoom bar constants (concentric radii: outer 8 - pad 4 == inner 4). +pub(super) const ZOOM_BAR_MARGIN: f32 = 12.0; +pub(super) const ZOOM_BAR_PAD: f32 = 4.0; +pub(super) const ZOOM_BAR_RADIUS: f32 = 8.0; +pub(super) const ZOOM_BTN_RADIUS: f32 = 4.0; +pub(super) const ZOOM_BTN_HEIGHT: f32 = 28.0; + +type NoteLayoutKey = (u64, u32, u32, PlaygroundTheme, u64, u64); + +pub(super) struct CachedNoteFlow { + pub(super) flow: BlockFlow, + pub(super) key: NoteLayoutKey, + pub(super) layout: Rc, +} + +pub(super) struct CachedSurfaces { + pub(super) key: (u64, PlaygroundTheme, u64), + pub(super) layouts: Rc<[SurfaceLayout]>, + pub(super) order: Rc<[PaintItem]>, + pub(super) painted_items: Rc<[SpatialItemInfo]>, +} + +pub(super) fn world_rect(b: Bounds) -> WorldRect { + WorldRect::new( + b.origin.x.into(), + b.origin.y.into(), + b.size.width.into(), + b.size.height.into(), + ) +} +pub(super) fn world_bounds(r: WorldRect, rotate: f32) -> WorldBounds { + WorldBounds { + xywh: [r.x.into(), r.y.into(), r.w.into(), r.h.into()], + rotate: rotate.into(), + } +} +pub(super) fn rotated_bounds(r: WorldRect, degrees: f32) -> WorldRect { + world_rect(world_bounds(r, degrees).aabb().ui()) +} + +/// Persistent Edgeless camera, interaction state, and cached per-Note/EdgelessText layouts. +#[derive(Default)] +pub struct EdgelessCanvasState { + pub camera: EdgelessCamera, + pub camera_initialized: bool, + pub drag_pan_anchor: Option>, + pub authoring: EdgelessAuthoringState, + pub(super) surfaces: Option, + pub(super) note_flows: HashMap, + pub(super) text_flows: HashMap, + /// Number of block bodies laid out during the most recent Edgeless frame. + pub last_frame_relayouts: u64, +} + +/// Collect spatial blocks (`Frame`, Edgeless-visible `Note`, `EdgelessText`) from `root.children` +/// and any `BlockContent::Surface`'s children in document order. +pub(super) fn spatial_blocks(root: &BlockNode) -> Vec<&BlockNode> { + let mut out = Vec::new(); + for child in &root.children { + match &child.content { + BlockContent::Surface { .. } => { + for sub in &child.children { + if is_spatial_block(sub) { + out.push(sub); + } + } + } + _ if is_spatial_block(child) => out.push(child), + _ => {} + } + } + out +} + +fn is_spatial_block(node: &BlockNode) -> bool { + match &node.content { + BlockContent::Frame { .. } | BlockContent::EdgelessText { .. } => true, + BlockContent::Note { + display_mode, + hidden: false, + .. + } => *display_mode != NoteDisplayMode::DocOnly, + _ => false, + } +} + +fn edgeless_prop<'a>( + node: &'a BlockNode, + flat_key: &str, + nested: &[&str], +) -> Option<&'a JsonValue> { + if let Some(v) = node.props.get(flat_key) { + return Some(v); + } + let mut cur = node.props.get("prop:edgeless")?; + for seg in nested { + cur = cur.get(*seg)?; + } + Some(cur) +} + +pub(super) fn note_scale(node: &BlockNode) -> f32 { + edgeless_prop(node, "prop:edgeless.scale", &["scale"]) + .and_then(JsonValue::as_f64) + .map(|v| v as f32) + .filter(|v| v.is_finite()) + .unwrap_or(1.0) + .clamp(0.1, 10.0) +} + +pub(super) fn note_collapse(node: &BlockNode) -> bool { + edgeless_prop(node, "prop:edgeless.collapse", &["collapse"]) + .and_then(JsonValue::as_bool) + .unwrap_or(false) +} + +pub(super) fn note_border_style(node: &BlockNode) -> Option<(BorderStyle, f32)> { + let style = edgeless_prop( + node, + "prop:edgeless.style.borderStyle", + &["style", "borderStyle"], + ) + .and_then(JsonValue::as_str) + .unwrap_or("none"); + let border_style = match style { + "solid" => BorderStyle::Solid, + "dash" | "dashed" => BorderStyle::Dashed, + _ => return None, + }; + let size = edgeless_prop( + node, + "prop:edgeless.style.borderSize", + &["style", "borderSize"], + ) + .and_then(JsonValue::as_f64) + .map(|v| v as f32) + .filter(|v| v.is_finite() && *v >= 0.0) + .unwrap_or(4.0); + if size <= 0.0 { + None + } else { + Some((border_style, size)) + } +} + +pub(super) fn note_border_radius(node: &BlockNode) -> f32 { + edgeless_prop( + node, + "prop:edgeless.style.borderRadius", + &["style", "borderRadius"], + ) + .and_then(JsonValue::as_f64) + .map(|v| v as f32) + .filter(|v| v.is_finite() && *v >= 0.0) + .unwrap_or(CARD_RADIUS) +} + +pub(super) fn note_shadow_type(node: &BlockNode) -> &str { + edgeless_prop( + node, + "prop:edgeless.style.shadowType", + &["style", "shadowType"], + ) + .and_then(JsonValue::as_str) + .unwrap_or("--affine-note-shadow-box") +} + +impl EdgelessCanvasState { + pub fn new() -> Self { + Self::default() + } + + pub fn set_camera(&mut self, pan_x: f32, pan_y: f32, zoom: f32) { + self.camera = EdgelessCamera::new(pan_x, pan_y, zoom); + self.camera_initialized = true; + } + + pub fn ensure_camera_initialized( + &mut self, + snapshot: &PageSnapshot, + viewport_size: Size, + ) { + if !self.camera_initialized + && f32::from(viewport_size.width) > 0.0 + && f32::from(viewport_size.height) > 0.0 + { + let bounds = self.scene_world_bounds(snapshot); + self.camera.fit_to_bounds(bounds, viewport_size, 48.0); + self.camera_initialized = true; + } + } + + pub fn cached_block_layout(&self, block_id: &str, is_note: bool) -> Option> { + if is_note { + self.note_flows.get(block_id).map(|c| c.layout.clone()) + } else { + self.text_flows.get(block_id).map(|c| c.layout.clone()) + } + } + + pub fn set_zoom_centered( + &mut self, + zoom: f32, + viewport_origin: Point, + viewport_size: Size, + ) { + let center = point( + px(f32::from(viewport_origin.x) + f32::from(viewport_size.width) * 0.5), + px(f32::from(viewport_origin.y) + f32::from(viewport_size.height) * 0.5), + ); + self.camera.zoom_at(zoom, center, viewport_origin); + self.camera_initialized = true; + } + + pub fn set_pan(&mut self, pan_x: f32, pan_y: f32) { + self.camera.pan_x = pan_x; + self.camera.pan_y = pan_y; + self.camera_initialized = true; + } + + #[cfg(test)] + pub fn cached_note_layout(&self, id: &str) -> Option> { + self.note_flows.get(id).map(|entry| entry.layout.clone()) + } + + #[cfg(test)] + pub(crate) fn cached_surface_layouts(&self) -> Rc<[SurfaceLayout]> { + self.surfaces.as_ref().unwrap().layouts.clone() + } + + #[cfg(test)] + pub fn cached_text_layout(&self, id: &str) -> Option> { + self.text_flows.get(id).map(|entry| entry.layout.clone()) + } + + /// Compute the bounding box of all Edgeless-visible Frames, Notes, and EdgelessTexts. + pub fn scene_world_bounds(&self, snapshot: &PageSnapshot) -> WorldRect { + let mut union = WorldRect::default(); + let Some(root) = &snapshot.root else { + return union; + }; + for child in spatial_blocks(root) { + match &child.content { + BlockContent::Frame { xywh, .. } => { + if let Some(rect) = parse_xywh(xywh) { + let with_title = WorldRect::new( + rect.x, + rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP, + rect.w, + rect.h + FRAME_TITLE_HEIGHT + FRAME_TITLE_GAP, + ); + union = union.union(with_title); + } + } + BlockContent::Note { + display_mode, + xywh, + hidden, + .. + } if !hidden && *display_mode != NoteDisplayMode::DocOnly => { + let mut rect = + parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0)); + if !note_collapse(child) + && let Some(cached) = self.note_flows.get(&child.id) + { + let scale = note_scale(child); + rect.h = rect + .h + .max((cached.layout.height + 2.0 * NOTE_CARD_PADDING) * scale); + } + union = union.union(rect); + } + BlockContent::EdgelessText { xywh } => { + if let Some(mut rect) = parse_xywh(xywh) { + let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0); + if let Some(cached) = self.text_flows.get(&child.id) { + rect.h = (cached.layout.height * scale).max(rect.h); + } + union = + union.union(rotated_bounds(rect, prop_f32(child, "prop:rotate", 0.))); + } + } + _ => {} + } + } + if let Some(surfaces) = &self.surfaces { + for layout in surfaces.layouts.iter() { + for (_, bounds) in layout.bounds() { + union = union.union(world_rect(bounds)); + } + } + } + union + } +} + +/// Resolved frame card ready to paint on the GPU canvas. +pub(super) struct PaintFrame { + pub(super) id: String, + pub(super) title: String, + pub(super) index: String, + pub(super) frame_children: Vec, + pub(super) rect: WorldRect, + pub(super) title_inline: Rc, + pub(super) title_pill_rect: WorldRect, + pub(super) fill: Option, +} + +/// Resolved note card with its cached `FlowLayout`. +pub(super) struct PaintNote { + pub(super) id: String, + pub(super) index: String, + pub(super) rect: WorldRect, + pub(super) scale: f32, + pub(super) border: Option<(BorderStyle, f32)>, + pub(super) border_radius: f32, + pub(super) shadows: Vec, + pub(super) fill: Hsla, + pub(super) layout: Rc, +} + +/// Resolved edgeless-text block with its cached `FlowLayout` and rotation/scale. +pub(super) struct PaintEdgelessText { + pub(super) world_aabb: WorldRect, + pub(super) id: String, + pub(super) index: String, + pub(super) rect: WorldRect, + pub(super) scale: f32, + pub(super) rotate_deg: f32, + pub(super) layout: Rc, +} + +/// Resolve a BlockSuite `{ light, dark }` color map or string color token against `theme`. +pub fn resolve_edgeless_color(value: &JsonValue, theme: PlaygroundTheme) -> Option { + let raw = match value { + JsonValue::String(s) => s.as_str(), + JsonValue::Object(map) => { + let key = match theme { + PlaygroundTheme::Light => "light", + PlaygroundTheme::Dark => "dark", + }; + map.get(key) + .and_then(JsonValue::as_str) + .or_else(|| map.get("normal").and_then(JsonValue::as_str))? + } + _ => return None, + }; + if raw.eq_ignore_ascii_case("transparent") || raw.is_empty() { + return Some(Hsla::transparent_black()); + } + theme.css_color(raw) +} + +pub(super) fn prop_f32(node: &BlockNode, key: &str, default: f32) -> f32 { + node.props + .get(key) + .and_then(JsonValue::as_f64) + .map(|v| v as f32) + .filter(|v| v.is_finite()) + .unwrap_or(default) +} + +pub(super) fn prop_bool(node: &BlockNode, key: &str, default: bool) -> bool { + node.props + .get(key) + .and_then(JsonValue::as_bool) + .unwrap_or(default) +} + +/// Inputs needed to prepare and build one Edgeless canvas frame. +pub struct EdgelessRenderInput<'a> { + pub snapshot: &'a PageSnapshot, + pub doc_rev: u64, + pub env_rev: u64, + pub preedit_nonce: u64, + pub theme: PlaygroundTheme, + pub palette: &'a Palette, + pub page_titles: &'a BTreeMap, + pub images: &'a HashMap, + pub viewport_width: f32, + pub viewport_height: f32, + pub editing_selection: Option<(String, bool, DocumentSelection, DocPoint)>, +} + +#[cfg(test)] +mod tests { + use ui::AppContext; + + #[test] + fn frame_one_zoom_badge_matches_fitted_camera_zoom() { + let platform = ui::HeadlessPlatform::new(1280, 800, 1.0); + let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let win = app + .update(|cx| { + cx.open_window(ui::WindowOptions::default(), |_window, cx| { + cx.new(|cx| { + crate::PlaygroundView::with_options( + crate::PlaygroundOptions { + mode: crate::PlaygroundMode::Edgeless, + ..Default::default() + }, + cx, + ) + }) + }) + }) + .unwrap(); + let hw = platform.windows().into_iter().next().unwrap(); + hw.request_frame(); + // Frame 1 must already display the fitted zoom percentage (not stale "100%"). + let snap = app + .update(|cx| win.update(cx, |_, window, _| window.frame_snapshot().clone())) + .unwrap(); + let badge = snap + .elements + .get("chrome.edgeless_zoom.reset") + .expect("chrome.edgeless_zoom.reset missing on frame 1"); + let text = badge.text.as_deref().unwrap_or(""); + assert_ne!( + text, "100%", + "Frame 1 zoom badge must reflect fitted camera, got {text}" + ); + assert!(text.ends_with('%'), "expected percentage badge, got {text}"); + assert!( + snap.elements.contains_key("chrome.edgeless_toolbar"), + "chrome.edgeless_toolbar must be mounted on Frame 1" + ); + } +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/canvas_paint.rs b/blocksuite/native-playground/crates/playground/src/edgeless/canvas_paint.rs new file mode 100644 index 0000000000..d0bec5ed2b --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/canvas_paint.rs @@ -0,0 +1,451 @@ +//! GPU painting and screen-space snapshot markers for the Edgeless spatial canvas. + +use ui::{ + AnyElement, Background, BorderStyle, Bounds, ContentMask, Corners, Edges, Hsla, ScaledPixels, + SharedString, TransformationMatrix, Window, canvas, div, point, prelude::*, px, size, +}; + +use crate::block_flow::{BlockPaint, FlowLayout, FlowRect}; +use crate::editor_session::DocumentSelection; + +use super::{ + EDGELESS_VIEWPORT_ID, EdgelessCanvasState, EdgelessInlineEdit, EdgelessRenderInput, + FRAME_RADIUS, NOTE_CARD_PADDING, PaintItem, PreparedEdgelessScene, WorldRect, bg_grid_gap, + build_edgeless_authoring_overlay, prepare_edgeless_scene, world_rect, +}; + +/// Prepare cached Note & EdgelessText layouts (zero relayout when camera moves), fit camera +/// on first render, and return the spatial canvas element plus screen-space snapshot markers. +pub fn build_edgeless_layer( + state: &mut EdgelessCanvasState, + input: &EdgelessRenderInput<'_>, + window: &Window, + zoom_controls: AnyElement, + toolbar: AnyElement, +) -> AnyElement { + let PreparedEdgelessScene { + frames, + notes, + texts, + surfaces, + order, + } = prepare_edgeless_scene(state, input, window); + if !state.camera_initialized && input.viewport_width > 0.0 && input.viewport_height > 0.0 { + let bounds = state.scene_world_bounds(input.snapshot); + state.camera.fit_to_bounds( + bounds, + size(px(input.viewport_width), px(input.viewport_height)), + 48.0, + ); + state.camera_initialized = true; + } + + let camera = state.camera; + let palette = *input.palette; + let theme = input.theme; + let visible_world = + camera.visible_world_bounds(size(px(input.viewport_width), px(input.viewport_height))); + + // Record screen-space snapshot markers for fully-visible spatial items so `bs-harness audit` + // and tests can inspect their screen bounds without triggering false clipping violations. + let mut snapshot_markers: Vec = Vec::new(); + let vp_origin = point(px(0.0), px(0.0)); + let push_marker = + |markers: &mut Vec, id: String, rect: WorldRect, text: Option| { + let tl = camera.world_to_screen(point(px(rect.x), px(rect.y)), vp_origin); + let br = camera.world_to_screen(point(px(rect.right()), px(rect.bottom())), vp_origin); + let x = f32::from(tl.x); + let y = f32::from(tl.y); + let w = f32::from(br.x) - x; + let h = f32::from(br.y) - y; + if x >= 0.0 + && y >= 0.0 + && x + w <= input.viewport_width + && y + h <= input.viewport_height + && w >= 1.0 + && h >= 1.0 + { + let mut el = div() + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(w)) + .h(px(h)) + .snapshot(SharedString::from(id), Some(EDGELESS_VIEWPORT_ID)); + if let Some(t) = text { + el = el.snapshot_text(t); + } + markers.push(el.into_any_element()); + } + }; + + for frame in &frames { + push_marker( + &mut snapshot_markers, + format!("edgeless.frame.{}", frame.id), + frame.rect, + Some(frame.title.clone()), + ); + } + for layout in surfaces.iter() { + for (id, bounds) in layout.bounds() { + push_marker( + &mut snapshot_markers, + format!("edgeless.surface.{id}"), + world_rect(bounds), + None, + ); + } + } + for note in ¬es { + push_marker( + &mut snapshot_markers, + format!("edgeless.note.{}", note.id), + note.rect, + None, + ); + } + for et in &texts { + push_marker( + &mut snapshot_markers, + format!("edgeless.text.{}", et.id), + et.world_aabb, + None, + ); + } + + let frame_border = theme + .css_var("--affine-v2-edgeless-frame-border") + .unwrap_or(palette.border); + let frame_pill_bg = palette.panel; + + let authoring_overlays = build_edgeless_authoring_overlay( + &state.authoring, + camera, + input.viewport_width, + input.viewport_height, + &palette, + theme, + ); + let editing_overlay: Option<(String, bool, Vec, Option)> = input + .editing_selection + .as_ref() + .and_then(|(editing_id, is_note, sel, focus)| { + let layout = state.cached_block_layout(editing_id, *is_note)?; + let sel_rects = spatial_selection_rects(sel, &layout); + let caret = layout + .block(&focus.block_id) + .and_then(|b| b.caret_rect(focus.caret)); + Some((editing_id.clone(), *is_note, sel_rects, caret)) + }); + let editing_label_id: Option = match &state.authoring.inline_edit { + Some(EdgelessInlineEdit::Label(ed)) => Some(ed.target.item_id().to_string()), + _ => None, + }; + + let paint_canvas = canvas( + |_, _, _| (), + move |bounds, _, window, cx| { + // 1. Single-draw-call procedural dot-grid background. + let gap = bg_grid_gap(camera.zoom); + let (phase_x, phase_y) = camera.dot_grid_phase(gap); + window.paint_quad(ui::fill( + bounds, + Background::dot_grid( + palette.background, + palette.edgeless_grid, + gap, + 1.0, + phase_x, + phase_y, + ), + )); + + let cam_matrix = camera.to_transformation_matrix(bounds.origin); + let cull_world = visible_world.dilate(120.0); + + window.with_content_mask(Some(ContentMask { bounds }), |window| { + window.with_paint_transformation(cam_matrix, |window| { + let viewport_world = Bounds::new( + point(px(visible_world.x), px(visible_world.y)), + size(px(visible_world.w), px(visible_world.h)), + ); + for item in order.iter() { + match *item { + PaintItem::Frame(i) => { + let frame = &frames[i]; + if !frame.rect.intersects(cull_world) { + continue; + } + let fb = Bounds::new( + point(px(frame.rect.x), px(frame.rect.y)), + size(px(frame.rect.w), px(frame.rect.h)), + ); + window.paint_quad(ui::quad( + fb, + Corners::all(px(FRAME_RADIUS)), + frame.fill.unwrap_or_else(Hsla::transparent_black), + Edges::all(px(1.0)), + frame_border, + BorderStyle::Solid, + )); + + // Frame title pill above top-left corner (shared exact layout with hit-test). + let pill = frame.title_pill_rect; + window.paint_quad(ui::quad( + Bounds::new( + point(px(pill.x), px(pill.y)), + size(px(pill.w), px(pill.h)), + ), + Corners::all(px(4.0)), + frame_pill_bg, + Edges::all(px(1.0)), + palette.border, + BorderStyle::Solid, + )); + if editing_label_id.as_deref() != Some(frame.id.as_str()) { + frame.title_inline.paint( + point(px(pill.x + 8.0), px(pill.y)), + window, + cx, + ); + } + } + + PaintItem::Surface(l, i) => surfaces[l].paint_item( + i, + viewport_world, + editing_label_id.as_deref(), + window, + cx, + ), + PaintItem::Note(i) => { + let note = ¬es[i]; + if !note.rect.intersects(cull_world) { + continue; + } + let nb = Bounds::new( + point(px(note.rect.x), px(note.rect.y)), + size(px(note.rect.w), px(note.rect.h)), + ); + if !note.shadows.is_empty() { + window.paint_drop_shadows( + nb, + Corners::all(px(note.border_radius)), + ¬e.shadows, + ); + } + let (border_widths, border_color, border_style) = match note.border + { + Some((style, width)) => { + (Edges::all(px(width)), palette.border, style) + } + None => ( + Edges::default(), + Hsla::transparent_black(), + BorderStyle::Solid, + ), + }; + window.paint_quad(ui::quad( + nb, + Corners::all(px(note.border_radius)), + note.fill, + border_widths, + border_color, + border_style, + )); + + let scale_transform = TransformationMatrix::unit() + .translate(point( + ScaledPixels(note.rect.x), + ScaledPixels(note.rect.y), + )) + .scale(size(note.scale, note.scale)) + .translate(point( + ScaledPixels(-note.rect.x), + ScaledPixels(-note.rect.y), + )); + let inner_bounds = Bounds::new( + point( + px(note.rect.x + NOTE_CARD_PADDING), + px(note.rect.y + NOTE_CARD_PADDING), + ), + size( + px((note.rect.w / note.scale - 2.0 * NOTE_CARD_PADDING) + .max(0.0)), + px((note.rect.h / note.scale - 2.0 * NOTE_CARD_PADDING) + .max(0.0)), + ), + ); + window.with_paint_transformation(scale_transform, |window| { + window.with_local_paint_mask( + ContentMask { + bounds: inner_bounds, + }, + |window| { + for block in ¬e.layout.blocks { + let origin = point( + px(note.rect.x + NOTE_CARD_PADDING + block.x), + px(note.rect.y + NOTE_CARD_PADDING + block.y), + ); + block.body.paint( + origin, + BlockPaint::default(), + window, + cx, + ); + } + if let Some((ref eid, true, ref sel_rects, caret)) = + editing_overlay + && eid == ¬e.id + { + for sr in sel_rects { + let sb = Bounds::new( + point( + px(note.rect.x + + NOTE_CARD_PADDING + + sr.x), + px(note.rect.y + + NOTE_CARD_PADDING + + sr.y), + ), + size(px(sr.w), px(sr.h)), + ); + window.paint_quad(ui::fill( + sb, + palette.brand.opacity(0.22), + )); + } + if let Some(caret) = caret { + let cb = Bounds::new( + point( + px(note.rect.x + + NOTE_CARD_PADDING + + caret.x), + px(note.rect.y + + NOTE_CARD_PADDING + + caret.y), + ), + size( + px(caret.w.max(2.0)), + px(caret.h.max(16.0)), + ), + ); + window.paint_quad(ui::fill(cb, palette.brand)); + } + } + }, + ); + }); + } + + PaintItem::Text(i) => { + let et = &texts[i]; + if !et.world_aabb.intersects(cull_world) { + continue; + } + let (cx_w, cy_w) = et.rect.center(); + let scale_from_tl = TransformationMatrix::unit() + .translate(point( + ScaledPixels(et.rect.x), + ScaledPixels(et.rect.y), + )) + .scale(size(et.scale, et.scale)) + .translate(point( + ScaledPixels(-et.rect.x), + ScaledPixels(-et.rect.y), + )); + let rotate_around_center = TransformationMatrix::unit() + .translate(point(ScaledPixels(cx_w), ScaledPixels(cy_w))) + .rotate(ui::radians(et.rotate_deg.to_radians())) + .translate(point(ScaledPixels(-cx_w), ScaledPixels(-cy_w))); + let local_transform = rotate_around_center.compose(scale_from_tl); + window.with_paint_transformation(local_transform, |window| { + for block in &et.layout.blocks { + let origin = + point(px(et.rect.x + block.x), px(et.rect.y + block.y)); + block.body.paint(origin, BlockPaint::default(), window, cx); + } + if let Some((ref eid, false, ref sel_rects, caret)) = + editing_overlay + && eid == &et.id + { + for sr in sel_rects { + let sb = Bounds::new( + point(px(et.rect.x + sr.x), px(et.rect.y + sr.y)), + size(px(sr.w), px(sr.h)), + ); + window.paint_quad(ui::fill( + sb, + palette.brand.opacity(0.22), + )); + } + if let Some(caret) = caret { + let cb = Bounds::new( + point( + px(et.rect.x + caret.x), + px(et.rect.y + caret.y), + ), + size(px(caret.w.max(2.0)), px(caret.h.max(16.0))), + ); + window.paint_quad(ui::fill(cb, palette.brand)); + } + } + }); + } + } + } + }); + }); + }, + ) + .size_full(); + + div() + .relative() + .flex_1() + .w_full() + .min_h_0() + .overflow_hidden() + .snapshot(EDGELESS_VIEWPORT_ID, Some("root.canvas")) + .child(paint_canvas) + .children(snapshot_markers) + .children(authoring_overlays) + .child(toolbar) + .child(zoom_controls) + .into_any_element() +} + +fn spatial_selection_rects(sel: &DocumentSelection, layout: &FlowLayout) -> Vec { + let mut out = Vec::new(); + if sel.empty() { + return out; + } + let Some((start, end, a, b, _)) = sel.ordered(layout) else { + return out; + }; + for block in &layout.blocks[a..=b] { + let from = if start.block_id == block.block_id { + start.offset() + } else { + 0 + }; + let to = if end.block_id == block.block_id { + end.offset() + } else { + block.body.plain.encode_utf16().count() as u64 + }; + if let Some(t) = &block.body.text { + for (line, x0, x1) in t.layout.selection_spans(from as usize, to as usize) { + let top = block.y + t.y + line as f32 * t.layout.line_height(); + out.push(FlowRect::new( + block.x + t.x + x0, + top, + (x1 - x0).max(2.0), + t.layout.line_height(), + )); + } + } + } + out +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/commands.rs b/blocksuite/native-playground/crates/playground/src/edgeless/commands.rs new file mode 100644 index 0000000000..afae857211 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/commands.rs @@ -0,0 +1,1326 @@ +//! Edgeless keyboard shortcuts, selection/z-order commands, and snapshot spatial helpers. + +use blocksuite_playground_doc::{ + fractional_index::generate_key_between, + read::{BlockContent, BlockNode, PageSnapshot, SurfaceElement}, +}; +use ui::{Context, KeyDownEvent, Window}; +use y_octo::{Any, SessionValue}; + +use crate::PlaygroundView; + +use super::{EdgelessGesture, EdgelessTool, SpatialItemInfo}; +#[cfg(test)] +use super::{HandleKind, SpatialItemKind}; + +/// Helper to compute the highest existing fractional index across all spatial items in a snapshot. +pub fn max_spatial_index(snapshot: &PageSnapshot) -> Option { + let root = snapshot.root.as_ref()?; + let mut max_idx: Option = None; + for node in root.walk() { + if let Some(idx) = node.props.get("prop:index").and_then(|v| v.as_str()) + && max_idx.as_deref().is_none_or(|m| idx > m) + { + max_idx = Some(idx.to_string()); + } + if let BlockContent::Surface { elements, .. } = &node.content { + for e in elements { + if max_idx.as_deref().is_none_or(|m| e.index.as_str() > m) { + max_idx = Some(e.index.clone()); + } + } + } + } + max_idx +} + +pub fn min_spatial_index(snapshot: &PageSnapshot) -> Option { + let root = snapshot.root.as_ref()?; + let mut min_idx: Option = None; + for node in root.walk() { + if matches!( + node.content, + BlockContent::Note { .. } + | BlockContent::Frame { .. } + | BlockContent::EdgelessText { .. } + ) && let Some(idx) = node.props.get("prop:index").and_then(|v| v.as_str()) + && min_idx.as_deref().is_none_or(|m| idx < m) + { + min_idx = Some(idx.to_string()); + } + if let BlockContent::Surface { elements, .. } = &node.content { + for e in elements { + if min_idx.as_deref().is_none_or(|m| e.index.as_str() < m) { + min_idx = Some(e.index.clone()); + } + } + } + } + min_idx +} + +pub(super) fn find_surface_element<'a>( + snapshot: &'a PageSnapshot, + id: &str, +) -> Option<(&'a str, &'a SurfaceElement)> { + let root = snapshot.root.as_ref()?; + for child in &root.children { + if let BlockContent::Surface { elements, .. } = &child.content + && let Some(el) = elements.iter().find(|e| e.id == id) + { + return Some((child.id.as_str(), el)); + } + } + None +} + +pub(super) fn find_block<'a>(snapshot: &'a PageSnapshot, id: &str) -> Option<&'a BlockNode> { + snapshot.root.as_ref()?.walk().find(|n| n.id == id) +} + +impl PlaygroundView { + /// Switch the active Edgeless authoring tool. + pub fn edgeless_select_tool( + &mut self, + tool: EdgelessTool, + window: &mut Window, + cx: &mut Context, + ) { + if let EdgelessTool::Shape(s) = tool { + self.edgeless.authoring.last_shape_type = Some(s); + } + self.edgeless_commit_inline_edit(window, cx); + self.edgeless.authoring.tool = tool; + self.edgeless.authoring.gesture = None; + cx.notify(); + } + + /// Programmatically select Edgeless item ids (used by harness states and tests). + pub fn edgeless_set_selection( + &mut self, + ids: impl IntoIterator, + cx: &mut Context, + ) { + self.edgeless.authoring.selection = ids.into_iter().collect(); + cx.notify(); + } + + /// Programmatically set an active marquee box (used by harness states). + pub fn edgeless_set_marquee( + &mut self, + start_world: (f32, f32), + current_world: (f32, f32), + cx: &mut Context, + ) { + self.edgeless.authoring.gesture = Some(EdgelessGesture::Marquee { + start_world, + current_world, + }); + cx.notify(); + } + + pub(crate) fn did_edgeless_doc_commit( + &mut self, + commit: y_octo::SessionCommit, + cx: &mut Context, + ) { + if !commit.update.is_empty() { + if let (Some(room), Some(id)) = (&self.room, &self.page_id) { + room.link + .send_binary(blocksuite_playground_doc::wire::RoomBinaryFrame::Doc { + doc_id: id.clone(), + message: blocksuite_playground_doc::wire::DocMessage::Update(commit.update), + }); + } + self.dirty_text = None; + self.snapshot = self + .page() + .and_then(|page| page.read_page_snapshot().ok()) + .map(std::rc::Rc::new); + self.doc_rev += 1; + cx.notify(); + } + } + + /// Handle keyboard events in Edgeless mode. Returns `true` if consumed. + pub(crate) fn edgeless_key_down( + &mut self, + e: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let m = e.keystroke.modifiers; + let cmd = m.secondary(cx); + let key = e.keystroke.key.as_str(); + + // 1. Active inline label editor (Shape / Connector / SurfaceText / Frame title). + if let Some(ed) = self.edgeless.authoring.label_editor_mut() { + if ed.composing() || e.prefer_character_input { + if key == "escape" { + ed.cancel_preedit(); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + return true; + } + return false; + } + match key { + "escape" => { + self.edgeless_commit_inline_edit(window, cx); + return true; + } + "enter" if !ed.multiline || cmd => { + self.edgeless_commit_inline_edit(window, cx); + return true; + } + "enter" => { + self.edgeless_label_edit(window, cx, |ed| ed.replace(None, "\n")); + return true; + } + "backspace" => { + self.edgeless_label_edit( + window, + cx, + super::EdgelessLabelEditor::delete_backward, + ); + return true; + } + "delete" => { + self.edgeless_label_edit( + window, + cx, + super::EdgelessLabelEditor::delete_forward, + ); + return true; + } + "left" => { + ed.move_caret(true, m.shift); + let sel = ed.selection.clone(); + self.edgeless_update_label_anchors(sel); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + return true; + } + "right" => { + ed.move_caret(false, m.shift); + let sel = ed.selection.clone(); + self.edgeless_update_label_anchors(sel); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + return true; + } + "a" if cmd => { + ed.select_all(); + let sel = ed.selection.clone(); + self.edgeless_update_label_anchors(sel); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + return true; + } + "c" | "x" if cmd => { + let s = ed.selected_text().to_string(); + if !s.is_empty() { + cx.write_to_clipboard(ui::ClipboardItem::new_string(s)); + if key == "x" { + self.edgeless_label_edit(window, cx, |ed| ed.replace(None, "")); + } + } + return true; + } + "v" if cmd => { + if let Some(item) = cx.read_from_clipboard() { + if let Some(text) = item.text() { + self.edgeless_label_edit(window, cx, |ed| ed.replace(None, &text)); + } + return true; + } + return false; + } + _ => return false, + } + } + + // 2. Active inline spatial block edit (Note / EdgelessText): Escape exits, else EditorSession. + if self.edgeless.authoring.editing_spatial_block().is_some() { + if key == "escape" && !self.editor.composing() { + self.edgeless_commit_inline_edit(window, cx); + return true; + } + return false; + } + + // 3. Canvas-level shortcuts when not inline-editing. + match key { + "space" if !cmd => { + self.edgeless.authoring.space_pan = true; + return true; + } + "escape" => { + self.edgeless.authoring.tool = EdgelessTool::Select; + self.edgeless.authoring.gesture = None; + self.edgeless.authoring.selection.clear(); + cx.notify(); + return true; + } + "v" if !cmd => { + self.edgeless_select_tool(EdgelessTool::Select, window, cx); + return true; + } + "h" if !cmd => { + self.edgeless_select_tool(EdgelessTool::Hand, window, cx); + return true; + } + "n" if !cmd => { + self.edgeless_select_tool(EdgelessTool::Note, window, cx); + return true; + } + "s" if !cmd => { + let shape = self.edgeless.authoring.active_shape_type(); + self.edgeless_select_tool(EdgelessTool::Shape(shape), window, cx); + return true; + } + "c" if !cmd => { + self.edgeless_select_tool(EdgelessTool::Connector, window, cx); + return true; + } + "p" if !cmd => { + self.edgeless_select_tool(EdgelessTool::Brush, window, cx); + return true; + } + "t" if !cmd => { + self.edgeless_select_tool(EdgelessTool::Text, window, cx); + return true; + } + "f" if !cmd => { + self.edgeless_select_tool(EdgelessTool::Frame, window, cx); + return true; + } + "a" if cmd => { + self.edgeless.authoring.selection = self + .edgeless + .authoring + .painted_items + .iter() + .map(|i| i.id.clone()) + .collect(); + cx.notify(); + return true; + } + "backspace" | "delete" => { + self.edgeless_delete_selection(cx); + return true; + } + "[" => { + self.edgeless_reorder_selection(false, cx); + return true; + } + "]" => { + self.edgeless_reorder_selection(true, cx); + return true; + } + "z" if cmd => { + let commit = self.page_mut().ok().and_then(|page| { + if m.shift { + page.redo().ok().flatten() + } else { + page.undo().ok().flatten() + } + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + return true; + } + _ => false, + } + } + + pub(crate) fn edgeless_delete_selection(&mut self, cx: &mut Context) { + if self.edgeless.authoring.selection.is_empty() { + return; + } + let Some(snapshot) = self.snapshot.clone() else { + return; + }; + let root_id = snapshot.root.as_ref().map(|r| r.id.clone()); + let selected: Vec = self + .edgeless + .authoring + .painted_items + .iter() + .filter(|i| self.edgeless.authoring.selection.contains(&i.id)) + .cloned() + .collect(); + let mut block_ids: Vec = Vec::new(); + let mut surface_elements: Vec<(String, String)> = Vec::new(); + for item in &selected { + if root_id.as_deref() == Some(item.id.as_str()) { + continue; + } + if item.kind.is_block() { + block_ids.push(item.id.clone()); + } else if let Some(surface_id) = &item.surface_id { + surface_elements.push((surface_id.clone(), item.id.clone())); + } + } + let now_ms = self.now_ms(cx) as u64; + let commit = self.page_mut().ok().and_then(|page| { + let b_refs: Vec<&str> = block_ids.iter().map(String::as_str).collect(); + let s_refs: Vec<(&str, &str)> = surface_elements + .iter() + .map(|(s, e)| (s.as_str(), e.as_str())) + .collect(); + page.delete_blocks_and_elements_with_connectors(&b_refs, &s_refs, now_ms) + .ok() + .flatten() + }); + self.edgeless.authoring.selection.clear(); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + cx.notify(); + } + + pub(crate) fn edgeless_reorder_selection( + &mut self, + bring_to_front: bool, + cx: &mut Context, + ) { + if self.edgeless.authoring.selection.is_empty() { + return; + } + let Some(snapshot) = self.snapshot.clone() else { + return; + }; + let mut cursor = if bring_to_front { + max_spatial_index(&snapshot) + } else { + min_spatial_index(&snapshot) + }; + let selected: Vec = self + .edgeless + .authoring + .painted_items + .iter() + .filter(|i| self.edgeless.authoring.selection.contains(&i.id)) + .cloned() + .collect(); + let now_ms = self.now_ms(cx) as u64; + let mut updates = Vec::new(); + let ordered: Vec = if bring_to_front { + selected + } else { + selected.into_iter().rev().collect() + }; + for item in ordered { + let next = if bring_to_front { + generate_key_between(cursor.as_deref(), None).ok() + } else { + generate_key_between(None, cursor.as_deref()).ok() + }; + if let Some(key) = next { + cursor = Some(key.clone()); + updates.push((item, key)); + } + } + if updates.is_empty() { + return; + } + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + for (item, key) in &updates { + if item.kind.is_block() { + page.set_block_index(&item.id, key, now_ms)?; + } else if let Some(surface_id) = &item.surface_id { + page.set_surface_element_field( + surface_id, + &item.id, + "index", + SessionValue::Any(Any::String(key.clone())), + now_ms, + )?; + } + } + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } +} + +/// Collect `SpatialItemInfo` from a `PageSnapshot` in paint order (used by hit-testing & tests). +pub fn collect_frame_children(node: &BlockNode) -> Vec { + node.props + .get("prop:childElementIds") + .and_then(|v| v.as_object()) + .map(|m| m.keys().cloned().collect()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use blocksuite_playground_doc::{ + read::SurfaceElementKind, + schema::{BlockSpec, SurfaceElementSpec}, + session::PageDocSession, + }; + + #[test] + fn surface_crud_and_atomic_undo_redo_in_page_doc_session() { + let mut page = PageDocSession::new("doc:edgeless", 42).unwrap(); + page.add_block( + "page:1", + BlockSpec::Page { + title: "Edgeless".into(), + }, + None, + None, + 1, + ) + .unwrap(); + let surface_id = page.ensure_surface_block(2).unwrap(); + let k1 = generate_key_between(None, None).unwrap(); + let k2 = generate_key_between(Some(&k1), None).unwrap(); + page.structural_edit(10, |p| { + p.add_surface_element( + &surface_id, + "s1", + &k1, + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: PageDocSession::format_xywh([10.0, 20.0, 160.0, 100.0]), + seed: 7, + filled: true, + text: Some("Initial".into()), + }, + 10, + )?; + Ok(()) + }) + .unwrap(); + page.set_surface_element_text(&surface_id, "s1", "text", "Updated", 20) + .unwrap(); + let snap = page.read_page_snapshot().unwrap(); + let root = snap.root.as_ref().unwrap(); + let surf = root.children.iter().find(|c| c.id == surface_id).unwrap(); + let BlockContent::Surface { elements, .. } = &surf.content else { + unreachable!() + }; + assert_eq!(elements.len(), 1); + let SurfaceElementKind::Shape(s) = &elements[0].kind else { + unreachable!() + }; + assert_eq!(s.text.plain, "Updated"); + + // Undo restores "Initial"; redo restores "Updated". + page.undo().unwrap(); + let snap2 = page.read_page_snapshot().unwrap(); + let BlockContent::Surface { elements, .. } = + &snap2.root.as_ref().unwrap().children[0].content + else { + unreachable!() + }; + let SurfaceElementKind::Shape(s) = &elements[0].kind else { + unreachable!() + }; + assert_eq!(s.text.plain, "Initial"); + + page.redo().unwrap(); + page.remove_surface_element(&surface_id, "s1", 30).unwrap(); + assert_ne!(k1, k2); + } + + fn open_edgeless_view( + app: &ui::ApplicationHandle, + platform: &ui::HeadlessPlatform, + ) -> ui::WindowHandle { + use ui::AppContext; + let win = app + .update(|cx| { + cx.open_window(ui::WindowOptions::default(), |_window, cx| { + cx.new(|cx| { + PlaygroundView::with_options( + crate::PlaygroundOptions { + mode: crate::PlaygroundMode::Edgeless, + ..Default::default() + }, + cx, + ) + }) + }) + }) + .unwrap(); + platform + .windows() + .into_iter() + .next() + .unwrap() + .request_frame(); + win + } + + fn mouse_down(x: f32, y: f32, click_count: usize) -> ui::MouseDownEvent { + ui::MouseDownEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(x), ui::px(y)), + modifiers: ui::Modifiers::default(), + click_count, + first_mouse: false, + } + } + + fn mouse_move(x: f32, y: f32, pressed: bool) -> ui::MouseMoveEvent { + ui::MouseMoveEvent { + position: ui::point(ui::px(x), ui::px(y)), + pressed_button: pressed.then_some(ui::MouseButton::Left), + modifiers: ui::Modifiers::default(), + } + } + + fn mouse_up(x: f32, y: f32) -> ui::MouseUpEvent { + ui::MouseUpEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(x), ui::px(y)), + modifiers: ui::Modifiers::default(), + click_count: 1, + } + } + + #[test] + fn idle_edgeless_canvas_isolates_text_ime_and_image_paste() { + use ui::EntityInputHandler; + + let platform = ui::HeadlessPlatform::new(1280, 800, 1.0); + let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let win = open_edgeless_view(&app, &platform); + + app.update(|cx| { + win.update(cx, |view, window, cx| { + // Seed a pre-existing Page selection so any leaked input would mutate the doc. + let para_id = view + .snapshot + .as_ref() + .and_then(|s| s.root.as_ref()) + .and_then(|r| { + r.walk().find_map(|n| match n.content { + BlockContent::Paragraph { .. } => Some(n.id.clone()), + _ => None, + }) + }) + .unwrap(); + let pt = crate::editor_session::DocPoint::new(¶_id, 0); + view.editor.selection = Some(crate::editor_session::DocumentSelection { + anchor: pt.clone(), + focus: pt, + }); + + let before_json = view.page().unwrap().export_doc_json().unwrap(); + let before_rev = view.doc_rev; + + // Idle Edgeless canvas: typing, CJK mark/unmark, and paste must be total no-ops. + view.replace_text_in_range(None, "q", window, cx); + view.replace_and_mark_text_in_range(None, "nihao", None, window, cx); + view.unmark_text(window, cx); + view.paste(ui::ClipboardItem::new_string("leaked".into()), window, cx); + + assert_eq!( + view.doc_rev, before_rev, + "idle Edgeless must not mutate doc_rev" + ); + assert_eq!( + view.page().unwrap().export_doc_json().unwrap(), + before_json, + "idle Edgeless must leave doc JSON byte-identical" + ); + + // Image-only ClipboardItem (text() == None) paste into open label editor leaves text intact. + let shape_id = view + .edgeless + .authoring + .painted_items + .iter() + .find(|i| i.kind == SpatialItemKind::Shape) + .map(|i| i.id.clone()) + .unwrap(); + assert!(view.edgeless_begin_inline_edit(&shape_id, window, cx)); + view.edgeless_label_edit(window, cx, |ed| ed.replace(None, "KeepMe")); + view.edgeless_label_input(window, cx, |ed| ed.select(0..4)); + let before_label = view.edgeless.authoring.label_editor().unwrap().text.clone(); + let image_only = ui::ClipboardItem { + entries: vec![ui::ClipboardEntry::Image(ui::Image { + bytes: vec![1, 2, 3, 4], + format: ui::ImageFormat::Png, + id: 1, + })], + }; + view.paste(image_only, window, cx); + assert_eq!( + view.edgeless.authoring.label_editor().unwrap().text, + before_label, + "image-only paste must not erase selected label text" + ); + }) + .unwrap(); + }); + } + + #[test] + fn edgeless_view_authoring_gestures_and_note_preedit_parity() { + use blocksuite_playground_doc::read::ShapeType; + use ui::EntityInputHandler; + + let platform = ui::HeadlessPlatform::new(1280, 800, 1.0); + let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let win = open_edgeless_view(&app, &platform); + let hw = platform.windows().into_iter().next().unwrap(); + + app.update(|cx| { + win.update(cx, |view, window, cx| { + // Set predictable 1:1 camera at (0, 0). + view.edgeless.set_camera(0.0, 0.0, 1.0); + let top = crate::TOPBAR_HEIGHT; + + // 1. Create Shape via pointer gesture. + view.edgeless_select_tool(EdgelessTool::Shape(ShapeType::Rect), window, cx); + view.on_edgeless_left_down(&mouse_down(100.0, top + 100.0, 1), window, cx); + view.on_edgeless_pointer_move(&mouse_move(220.0, top + 180.0, true), window, cx); + view.on_edgeless_left_up(&mouse_up(220.0, top + 180.0), window, cx); + let shape_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + assert!(shape_id.starts_with("shape:")); + + // 2. Create Note -> sets prop:displayMode == "edgeless", enters SpatialBlock edit, + // and CJK preedit renders in preedit_snapshot() without mutating doc until commit. + view.edgeless_select_tool(EdgelessTool::Note, window, cx); + view.on_edgeless_left_down(&mouse_down(320.0, top + 100.0, 1), window, cx); + view.on_edgeless_pointer_move(&mouse_move(600.0, top + 240.0, true), window, cx); + view.on_edgeless_left_up(&mouse_up(600.0, top + 240.0), window, cx); + let note_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + let doc_json = view.page().unwrap().export_doc_json().unwrap(); + assert_eq!(doc_json["blocks"][¬e_id]["prop:displayMode"], "edgeless"); + let before_preedit_json = doc_json.clone(); + view.replace_and_mark_text_in_range(None, "中文", None, window, cx); + assert_eq!( + view.page().unwrap().export_doc_json().unwrap(), + before_preedit_json, + "Note preedit must not publish updates before commit" + ); + let pre_snap = view.preedit_snapshot().expect("preedit_snapshot active"); + let note_text: String = pre_snap + .root + .as_ref() + .unwrap() + .walk() + .filter_map(|n| match &n.content { + BlockContent::Paragraph { text, .. } => Some(text.plain.as_str()), + _ => None, + }) + .collect(); + assert!( + note_text.contains("中文"), + "preedit text must appear in Note snapshot" + ); + view.replace_text_in_range(None, "", window, cx); + assert!(!view.editor.composing()); + view.edgeless_commit_inline_edit(window, cx); + assert!(view.editor.selection.is_none()); + + // 3. Create 2D Brush stroke -> inflated xywh & 2-element points. + view.edgeless_select_tool(EdgelessTool::Brush, window, cx); + view.on_edgeless_left_down(&mouse_down(50.0, top + 300.0, 1), window, cx); + view.on_edgeless_pointer_move(&mouse_move(110.0, top + 340.0, true), window, cx); + view.on_edgeless_left_up(&mouse_up(110.0, top + 340.0), window, cx); + let brush_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + let (_, brush_el) = + find_surface_element(view.snapshot.as_ref().unwrap(), &brush_id).unwrap(); + let SurfaceElementKind::Brush(b) = &brush_el.kind else { + unreachable!() + }; + assert!(b.simulated_pressure, "2D brush must set simulated_pressure"); + assert!( + b.xywh[2] >= 64.0, + "brush xywh must be inflated by lineWidth" + ); + + // 4. Create Text + Escape removes empty element. + view.edgeless_select_tool(EdgelessTool::Text, window, cx); + view.on_edgeless_left_down(&mouse_down(50.0, top + 420.0, 1), window, cx); + let text_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + assert!(find_surface_element(view.snapshot.as_ref().unwrap(), &text_id).is_some()); + view.edgeless_commit_inline_edit(window, cx); + assert!( + find_surface_element(view.snapshot.as_ref().unwrap(), &text_id).is_none(), + "empty newly-created SurfaceText must be removed on close" + ); + }) + .unwrap(); + }); + hw.request_frame(); + + app.update(|cx| { + win.update(cx, |view, window, cx| { + let top = crate::TOPBAR_HEIGHT; + // 5. Create Frame capturing only fully contained shape (not partially overlapping note). + view.edgeless_select_tool(EdgelessTool::Frame, window, cx); + view.on_edgeless_left_down(&mouse_down(90.0, top + 90.0, 1), window, cx); + view.on_edgeless_pointer_move(&mouse_move(360.0, top + 200.0, true), window, cx); + view.on_edgeless_left_up(&mouse_up(360.0, top + 200.0), window, cx); + let frame_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + let frame_node = find_block(view.snapshot.as_ref().unwrap(), &frame_id).unwrap(); + let children = collect_frame_children(frame_node); + assert!( + children.iter().any(|c| c.starts_with("shape:")), + "frame must enclose fully-contained shape: {children:?}" + ); + assert!( + !children.iter().any(|c| c.starts_with("note:")), + "frame must exclude partially-overlapping note: {children:?}" + ); + + // 6. Create free Connector, edit its label (writes labelXYWH + labelOffset), + // then drag it (moves endpoints + labelXYWH, never writes synthetic xywh). + view.edgeless_select_tool(EdgelessTool::Connector, window, cx); + view.on_edgeless_left_down(&mouse_down(700.0, top + 300.0, 1), window, cx); + view.on_edgeless_pointer_move(&mouse_move(820.0, top + 360.0, true), window, cx); + view.on_edgeless_left_up(&mouse_up(820.0, top + 360.0), window, cx); + let conn_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + // Trigger frame so painted_items includes conn_id. + assert!(conn_id.starts_with("conn:")); + }) + .unwrap(); + }); + hw.request_frame(); + + app.update(|cx| { + win.update(cx, |view, window, cx| { + let conn_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + assert!(view.edgeless_begin_inline_edit(&conn_id, window, cx)); + view.edgeless_label_edit(window, cx, |ed| ed.replace(None, "Flow")); + view.edgeless_commit_inline_edit(window, cx); + let (surf_id, c_text, c_label_xywh) = { + let (sid, el) = + find_surface_element(view.snapshot.as_ref().unwrap(), &conn_id).unwrap(); + let SurfaceElementKind::Connector(c) = &el.kind else { + unreachable!() + }; + (sid.to_string(), c.text.plain.clone(), c.label_xywh) + }; + assert_eq!(c_text, "Flow"); + assert!( + c_label_xywh.is_some(), + "connector label must write labelXYWH" + ); + let doc_json = view.page().unwrap().export_doc_json().unwrap(); + assert!( + doc_json["blocks"][&surf_id]["prop:elements"]["value"][&conn_id]["labelOffset"] + .is_object(), + "connector label must write labelOffset" + ); + assert!( + doc_json["blocks"][&surf_id]["prop:elements"]["value"][&conn_id] + .get("xywh") + .is_none(), + "connector must never have synthetic xywh" + ); + // Empty trim removes label fields cleanly. + assert!(view.edgeless_begin_inline_edit(&conn_id, window, cx)); + view.edgeless_label_edit(window, cx, |ed| { + ed.select_all(); + ed.replace(None, " ") + }); + view.edgeless_commit_inline_edit(window, cx); + let doc_json = view.page().unwrap().export_doc_json().unwrap(); + let conn_json = &doc_json["blocks"][&surf_id]["prop:elements"]["value"][&conn_id]; + assert!(conn_json.get("labelXYWH").is_none()); + assert!(conn_json.get("labelOffset").is_none()); + }) + .unwrap(); + }); + } + + #[test] + fn edgeless_view_drag_resize_rotate_z_reorder_cascade_delete_and_group_frame() { + use blocksuite_playground_doc::schema::{ConnectorEndpointSpec, SurfaceElementSpec}; + + let platform = ui::HeadlessPlatform::new(1280, 800, 1.0); + let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let win = open_edgeless_view(&app, &platform); + let hw = platform.windows().into_iter().next().unwrap(); + + // Seed a shape, an attached connector, a labeled free connector, a 2D brush, and a grouped shape. + let mut ids = ( + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + String::new(), + ); + app.update(|cx| { + win.update(cx, |view, _window, cx| { + view.edgeless.set_camera(0.0, 0.0, 1.0); + let commit = view + .page_mut() + .unwrap() + .structural_edit(100, |p| { + let sid = p.ensure_surface_block(100)?; + p.add_surface_element( + &sid, + "sh-1", + "aA", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[100,100,120,80]".into(), + seed: 11, + filled: true, + text: None, + }, + 100, + )?; + p.add_surface_element( + &sid, + "conn-att", + "aB", + SurfaceElementSpec::Connector { + mode: 0, + seed: 12, + source: ConnectorEndpointSpec::element("sh-1", Some([1.0, 0.5])), + target: ConnectorEndpointSpec::point(340.0, 140.0), + text: None, + label_xywh: None, + }, + 100, + )?; + p.add_surface_element( + &sid, + "conn-free", + "aC", + SurfaceElementSpec::Connector { + mode: 0, + seed: 13, + source: ConnectorEndpointSpec::point(100.0, 260.0), + target: ConnectorEndpointSpec::point(260.0, 260.0), + text: Some("Tag".into()), + label_xywh: Some([150.0, 248.0, 60.0, 24.0]), + }, + 100, + )?; + p.add_surface_element( + &sid, + "br-1", + "aD", + SurfaceElementSpec::Brush { + seed: 14, + points: vec![vec![0.0, 0.0], vec![60.0, 30.0]], + xywh: "[400,100,64,34]".into(), + }, + 100, + )?; + p.add_surface_element( + &sid, + "sh-grp", + "aE", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[520,120,60,40]".into(), + seed: 15, + filled: true, + text: None, + }, + 100, + )?; + p.add_surface_element( + &sid, + "grp-1", + "aF", + SurfaceElementSpec::Group { + seed: 16, + title: "G".into(), + children: vec!["sh-grp".into()], + }, + 100, + )?; + Ok(()) + }) + .unwrap() + .unwrap(); + view.did_edgeless_doc_commit(commit, cx); + ids = ( + "sh-1".into(), + "conn-att".into(), + "conn-free".into(), + "br-1".into(), + "sh-grp".into(), + "grp-1".into(), + ); + }) + .unwrap(); + }); + hw.request_frame(); + + app.update(|cx| { + win.update(cx, |view, window, cx| { + let top = crate::TOPBAR_HEIGHT; + let (sh_id, conn_att, conn_free, br_id, sh_grp, grp_id) = &ids; + + // 1. Drag shape + labeled free connector together -> moves xywh + labelXYWH. + view.edgeless.authoring.selection.clear(); + view.edgeless.authoring.selection.insert(sh_id.clone()); + view.edgeless.authoring.selection.insert(conn_free.clone()); + let initial = view.collect_drag_initials(); + view.edgeless.authoring.gesture = Some(EdgelessGesture::DragSelection { + start_world: (120.0, 120.0), + current_world: (160.0, 145.0), + initial, + }); + view.on_edgeless_left_up(&mouse_up(160.0, top + 145.0), window, cx); + let (_, sh_el) = + find_surface_element(view.snapshot.as_ref().unwrap(), sh_id).unwrap(); + let SurfaceElementKind::Shape(s) = &sh_el.kind else { + unreachable!() + }; + assert!((s.xywh[0] - 140.0).abs() < 0.5 && (s.xywh[1] - 125.0).abs() < 0.5); + let (cf_sid, cf_el) = + find_surface_element(view.snapshot.as_ref().unwrap(), conn_free).unwrap(); + let SurfaceElementKind::Connector(c) = &cf_el.kind else { + unreachable!() + }; + let lxywh = c.label_xywh.expect("labelXYWH preserved after drag"); + assert!((lxywh[0] - 190.0).abs() < 0.5 && (lxywh[1] - 273.0).abs() < 0.5); + let cf_target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(cf_sid) + .key("prop:elements") + .key("value") + .key(conn_free), + ); + assert!(matches!( + view.page().unwrap().inner().get_map_value(&cf_target, "labelXYWH").unwrap(), + Some(y_octo::SessionReadValue::Any(Any::Array(v))) if v.len() == 4 + )); + + // 2. Resize 2D brush -> scales points and encodes as valid array. + view.edgeless.authoring.selection.clear(); + view.edgeless.authoring.selection.insert(br_id.clone()); + let initial = view.collect_drag_initials(); + let ibox = view.edgeless.authoring.selection_world_box().unwrap(); + view.edgeless.authoring.gesture = Some(EdgelessGesture::ResizeSelection { + handle: HandleKind::SE, + start_world: (ibox.right(), ibox.bottom()), + current_world: (ibox.right() + ibox.w, ibox.bottom() + ibox.h), + initial_box: ibox, + initial, + }); + view.on_edgeless_left_up(&mouse_up(0.0, 0.0), window, cx); + let (br_sid, br_el) = + find_surface_element(view.snapshot.as_ref().unwrap(), br_id).unwrap(); + let SurfaceElementKind::Brush(b) = &br_el.kind else { + unreachable!() + }; + assert_eq!(b.points.len(), 2); + assert!( + b.points[1][0] > 100.0, + "brush points should scale: {:?}", + b.points + ); + let br_target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(br_sid) + .key("prop:elements") + .key("value") + .key(br_id), + ); + assert!(matches!( + view.page().unwrap().inner().get_map_value(&br_target, "points").unwrap(), + Some(y_octo::SessionReadValue::Any(Any::Array(v))) if v.len() == 2 + )); + + // 3. Rotate shape via HandleKind::Rotate gesture. + view.edgeless.authoring.selection.clear(); + view.edgeless.authoring.selection.insert(sh_id.clone()); + let sh_info = view.edgeless.authoring.single_selected().unwrap().clone(); + view.edgeless.authoring.gesture = Some(EdgelessGesture::RotateSelection { + id: sh_info.id, + surface_id: sh_info.surface_id, + is_block: false, + center_world: sh_info.rect.center(), + start_angle: 0.0, + initial_rotate: 0.0, + current_rotate: 45.0, + }); + view.on_edgeless_left_up(&mouse_up(0.0, 0.0), window, cx); + let (_, sh_el) = + find_surface_element(view.snapshot.as_ref().unwrap(), sh_id).unwrap(); + assert!((sh_el.rotate - 45.0).abs() < 0.1); + + // 4. Z-reorder (`]` / `[`) changes fractional index. + let idx_before = sh_el.index.clone(); + view.edgeless_reorder_selection(true, cx); + let idx_after = find_surface_element(view.snapshot.as_ref().unwrap(), sh_id) + .unwrap() + .1 + .index + .clone(); + assert!(idx_after > idx_before, "bring forward must increase index"); + view.edgeless_reorder_selection(false, cx); + + // 5. CreateFrame excludes grouped child `sh-grp` while keeping top-level `grp-1`. + view.edgeless_select_tool(EdgelessTool::Frame, window, cx); + view.on_edgeless_left_down(&mouse_down(500.0, top + 100.0, 1), window, cx); + view.on_edgeless_pointer_move(&mouse_move(620.0, top + 200.0, true), window, cx); + view.on_edgeless_left_up(&mouse_up(620.0, top + 200.0), window, cx); + let frame_id = view + .edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone(); + let frame_children = collect_frame_children( + find_block(view.snapshot.as_ref().unwrap(), &frame_id).unwrap(), + ); + assert!( + !frame_children.iter().any(|c| c == sh_grp), + "grouped child must be excluded from frame: {frame_children:?}" + ); + let _ = grp_id; + + // 6. Cascade delete shape + attached connector in 1 undo step, restored in 1 undo. + let _ = view.page_mut().unwrap().stop_capturing(); + view.edgeless.authoring.selection.clear(); + view.edgeless.authoring.selection.insert(sh_id.clone()); + view.edgeless_delete_selection(cx); + assert!(find_surface_element(view.snapshot.as_ref().unwrap(), sh_id).is_none()); + assert!(find_surface_element(view.snapshot.as_ref().unwrap(), conn_att).is_none()); + if let Some(c) = view.page_mut().unwrap().undo().unwrap() { + view.did_edgeless_doc_commit(c, cx); + } + assert!(find_surface_element(view.snapshot.as_ref().unwrap(), sh_id).is_some()); + assert!(find_surface_element(view.snapshot.as_ref().unwrap(), conn_att).is_some()); + }) + .unwrap(); + }); + } + + #[test] + fn label_editor_click_hit_tests_line_and_preedit_anchors_track_remote_prepend() { + use blocksuite_playground_doc::{schema::SurfaceElementSpec, session::PageDocSession}; + use ui::EntityInputHandler; + + let platform = ui::HeadlessPlatform::new(1280, 800, 1.0); + let app = ui::Application::with_platform(platform.clone()).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let win = open_edgeless_view(&app, &platform); + let hw = platform.windows().into_iter().next().unwrap(); + + app.update(|cx| { + win.update(cx, |view, _window, cx| { + view.edgeless.set_camera(0.0, 0.0, 1.0); + let commit = view + .page_mut() + .unwrap() + .structural_edit(100, |p| { + let sid = p.ensure_surface_block(100)?; + p.add_surface_element( + &sid, + "sh-2line", + "aG", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[100,100,220,90]".into(), + seed: 21, + filled: true, + text: Some("first line\nsecond line".into()), + }, + 100, + )?; + p.add_surface_element( + &sid, + "sh-ime", + "aH", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[360,100,180,80]".into(), + seed: 22, + filled: true, + text: Some("abc".into()), + }, + 100, + )?; + Ok(()) + }) + .unwrap() + .unwrap(); + view.did_edgeless_doc_commit(commit, cx); + }) + .unwrap(); + }); + hw.request_frame(); + + app.update(|cx| { + win.update(cx, |view, window, cx| { + // 1. Open 2-line shape label, click inside line 1, type '*', assert '*' lands in line 1. + assert!(view.edgeless_begin_inline_edit("sh-2line", window, cx)); + let bounds = view.edgeless_label_screen_bounds().unwrap(); + let line1_x = f32::from(bounds.origin.x) + 24.0; + let line1_y = f32::from(bounds.origin.y) + 14.0; + view.on_edgeless_left_down(&mouse_down(line1_x, line1_y, 1), window, cx); + view.replace_text_in_range(None, "*", window, cx); + let text = view.edgeless.authoring.label_editor().unwrap().text.clone(); + let mut lines = text.lines(); + let first = lines.next().unwrap_or(""); + let second = lines.next().unwrap_or(""); + assert!( + first.contains('*') && !second.contains('*'), + "expected '*' in line 1, got {text:?}" + ); + view.edgeless_commit_inline_edit(window, cx); + + // 2. Open 'abc', select 1..2 ('b'), start IME preedit 'ni', remote peer prepends 'X', + // refresh and commit '文' -> final text is 'Xa文c'. + assert!(view.edgeless_begin_inline_edit("sh-ime", window, cx)); + view.set_selected_text_range(1..2, window, cx); + view.replace_and_mark_text_in_range(None, "ni", None, window, cx); + + let seed = view.page().unwrap().encode_update_v1().unwrap(); + let (surf_id, _) = + find_surface_element(view.snapshot.as_ref().unwrap(), "sh-ime").unwrap(); + let surf_id = surf_id.to_string(); + let mut peer_b = PageDocSession::new("doc:home", 777).unwrap(); + peer_b.apply_remote_update_v1(&seed).unwrap(); + let remote_commit = peer_b + .splice_surface_element_text(&surf_id, "sh-ime", "text", 0, 0, "X", 200) + .unwrap() + .unwrap(); + view.page_mut() + .unwrap() + .apply_remote_update_v1(&remote_commit.update) + .unwrap(); + view.snapshot = view + .page() + .unwrap() + .read_page_snapshot() + .ok() + .map(std::rc::Rc::new); + view.edgeless_refresh_label_editor_from_snapshot(); + + view.replace_text_in_range(None, "文", window, cx); + view.edgeless_commit_inline_edit(window, cx); + let (_, el) = + find_surface_element(view.snapshot.as_ref().unwrap(), "sh-ime").unwrap(); + let SurfaceElementKind::Shape(s) = &el.kind else { + unreachable!() + }; + assert_eq!(s.text.plain, "Xa文c"); + + // 3. Same-string remote shift ("aaaa": peer deletes 0 and appends 'a' while 2..3 is marked) + // must still resolve preedit_anchors so committing '文' produces "a文aa". + let _ = view + .page_mut() + .unwrap() + .splice_surface_element_text(&surf_id, "sh-ime", "text", 0, 4, "aaaa", 250); + view.snapshot = view + .page() + .unwrap() + .read_page_snapshot() + .ok() + .map(std::rc::Rc::new); + assert!(view.edgeless_begin_inline_edit("sh-ime", window, cx)); + view.set_selected_text_range(2..3, window, cx); + view.replace_and_mark_text_in_range(None, "ni", None, window, cx); + let seed2 = view.page().unwrap().encode_update_v1().unwrap(); + let mut peer_c = PageDocSession::new("doc:home", 778).unwrap(); + peer_c.apply_remote_update_v1(&seed2).unwrap(); + let shift_commit = peer_c + .structural_edit(300, |p| { + p.splice_surface_element_text(&surf_id, "sh-ime", "text", 0, 1, "", 300)?; + p.splice_surface_element_text(&surf_id, "sh-ime", "text", 3, 0, "a", 300)?; + Ok(()) + }) + .unwrap() + .unwrap(); + view.page_mut() + .unwrap() + .apply_remote_update_v1(&shift_commit.update) + .unwrap(); + view.snapshot = view + .page() + .unwrap() + .read_page_snapshot() + .ok() + .map(std::rc::Rc::new); + view.edgeless_refresh_label_editor_from_snapshot(); + view.replace_text_in_range(None, "文", window, cx); + view.edgeless_commit_inline_edit(window, cx); + let (_, el2) = + find_surface_element(view.snapshot.as_ref().unwrap(), "sh-ime").unwrap(); + let SurfaceElementKind::Shape(s2) = &el2.kind else { + unreachable!() + }; + assert_eq!(s2.text.plain, "a文aa"); + }) + .unwrap(); + }); + } +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/commit.rs b/blocksuite/native-playground/crates/playground/src/edgeless/commit.rs new file mode 100644 index 0000000000..e498478aba --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/commit.rs @@ -0,0 +1,680 @@ +//! Pointer-up gesture commit to `PageDocSession` (shapes, connectors, brushes, notes, frames, transforms). + +use blocksuite_playground_doc::{ + fractional_index::generate_key_between, + read::{BlockContent, ShapeType, SurfaceElementKind}, + schema::{ConnectorEndpointSpec, SurfaceElementSpec, map_array_any}, + session::PageDocSession, +}; +use ui::{Context, MouseUpEvent, Window}; +use y_octo::{Any, SessionValue}; + +use crate::{ + PlaygroundView, + editor_session::{DocPoint, DocumentSelection}, +}; + +use super::{ + EdgelessGesture, EdgelessInlineEdit, EdgelessLabelEditor, EdgelessTool, LabelTarget, + SpatialItemKind, WorldRect, max_spatial_index, normalized_rect, resized_rect, rotated_bounds, +}; + +impl PlaygroundView { + pub(crate) fn on_edgeless_left_up( + &mut self, + _event: &MouseUpEvent, + window: &mut Window, + cx: &mut Context, + ) { + let Some(gesture) = self.edgeless.authoring.gesture.take() else { + return; + }; + let now_ms = self.now_ms(cx) as u64; + match gesture { + EdgelessGesture::Pan { .. } | EdgelessGesture::Marquee { .. } => { + cx.notify(); + } + EdgelessGesture::DragSelection { + start_world, + current_world, + initial, + } => { + let dx = (current_world.0 - start_world.0) as f64; + let dy = (current_world.1 - start_world.1) as f64; + if dx.hypot(dy) < 0.5 { + cx.notify(); + return; + } + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + for item in &initial { + let new_xywh = [ + item.rect.x as f64 + dx, + item.rect.y as f64 + dy, + item.rect.w as f64, + item.rect.h as f64, + ]; + if item.kind.is_block() { + page.set_block_xywh(&item.id, new_xywh, now_ms)?; + } else if item.kind == SpatialItemKind::Connector { + if let Some(surface_id) = &item.surface_id { + if let Some((None, Some([sx, sy]))) = &item.connector_source { + page.set_surface_element_field( + surface_id, + &item.id, + "source", + SessionValue::Any( + ConnectorEndpointSpec::point(sx + dx, sy + dy) + .to_any(), + ), + now_ms, + )?; + } + if let Some((None, Some([tx, ty]))) = &item.connector_target { + page.set_surface_element_field( + surface_id, + &item.id, + "target", + SessionValue::Any( + ConnectorEndpointSpec::point(tx + dx, ty + dy) + .to_any(), + ), + now_ms, + )?; + } + if let Some([lx, ly, lw, lh]) = item.connector_label_xywh { + page.set_surface_element_field( + surface_id, + &item.id, + "labelXYWH", + SessionValue::Any(map_array_any(vec![ + Any::Float64((lx + dx).into()), + Any::Float64((ly + dy).into()), + Any::Float64(lw.into()), + Any::Float64(lh.into()), + ])), + now_ms, + )?; + } + } + } else if item.kind == SpatialItemKind::Group { + // Groups derive bounds from their children; never write synthetic xywh. + } else if let Some(surface_id) = &item.surface_id { + page.set_surface_element_field( + surface_id, + &item.id, + "xywh", + SessionValue::Any(Any::String(PageDocSession::format_xywh( + new_xywh, + ))), + now_ms, + )?; + } + } + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } + EdgelessGesture::ResizeSelection { + handle, + start_world, + current_world, + initial_box, + initial, + } => { + let new_box = resized_rect(initial_box, handle, start_world, current_world); + if (new_box.x - initial_box.x).abs() < 0.5 + && (new_box.y - initial_box.y).abs() < 0.5 + && (new_box.w - initial_box.w).abs() < 0.5 + && (new_box.h - initial_box.h).abs() < 0.5 + { + cx.notify(); + return; + } + let sx = (new_box.w / initial_box.w.max(1.0)) as f64; + let sy = (new_box.h / initial_box.h.max(1.0)) as f64; + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + for item in &initial { + let nx = new_box.x as f64 + (item.rect.x - initial_box.x) as f64 * sx; + let ny = new_box.y as f64 + (item.rect.y - initial_box.y) as f64 * sy; + let nw = (item.rect.w as f64 * sx).max(16.0); + let nh = (item.rect.h as f64 * sy).max(16.0); + if item.kind.is_block() { + page.set_block_xywh(&item.id, [nx, ny, nw, nh], now_ms)?; + } else if item.kind == SpatialItemKind::Connector { + if let Some(surface_id) = &item.surface_id { + if let Some((None, Some([px_0, py_0]))) = &item.connector_source + { + let ex = + new_box.x as f64 + (px_0 - initial_box.x as f64) * sx; + let ey = + new_box.y as f64 + (py_0 - initial_box.y as f64) * sy; + page.set_surface_element_field( + surface_id, + &item.id, + "source", + SessionValue::Any( + ConnectorEndpointSpec::point(ex, ey).to_any(), + ), + now_ms, + )?; + } + if let Some((None, Some([px_0, py_0]))) = &item.connector_target + { + let ex = + new_box.x as f64 + (px_0 - initial_box.x as f64) * sx; + let ey = + new_box.y as f64 + (py_0 - initial_box.y as f64) * sy; + page.set_surface_element_field( + surface_id, + &item.id, + "target", + SessionValue::Any( + ConnectorEndpointSpec::point(ex, ey).to_any(), + ), + now_ms, + )?; + } + } + } else if item.kind == SpatialItemKind::Group { + // Groups derive bounds from their children; never write synthetic xywh. + } else if let Some(surface_id) = &item.surface_id { + page.set_surface_element_field( + surface_id, + &item.id, + "xywh", + SessionValue::Any(Any::String(PageDocSession::format_xywh([ + nx, ny, nw, nh, + ]))), + now_ms, + )?; + if let Some(points) = &item.points { + let scaled: Vec = points + .iter() + .map(|p| { + if p.len() >= 3 { + Any::Array(vec![ + Any::Float64((p[0] * sx).into()), + Any::Float64((p[1] * sy).into()), + Any::Float64(p[2].into()), + ]) + } else { + Any::Array(vec![ + Any::Float64((p[0] * sx).into()), + Any::Float64((p[1] * sy).into()), + ]) + } + }) + .collect(); + page.set_surface_element_field( + surface_id, + &item.id, + "points", + SessionValue::Any(map_array_any(scaled)), + now_ms, + )?; + } + } + } + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } + EdgelessGesture::RotateSelection { + id, + surface_id, + is_block, + initial_rotate, + current_rotate, + .. + } => { + if (current_rotate - initial_rotate).abs() < 0.1 { + cx.notify(); + return; + } + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + if is_block { + page.set_block_rotate(&id, current_rotate, now_ms)?; + } else if let Some(sid) = &surface_id { + page.set_surface_element_field( + sid, + &id, + "rotate", + SessionValue::Any(Any::Float64(current_rotate.into())), + now_ms, + )?; + } + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } + EdgelessGesture::CreateShape { + shape_type, + start_world, + current_world, + } => { + let mut r = normalized_rect(start_world, current_world); + if r.w < 12.0 && r.h < 12.0 { + r = WorldRect::new(start_world.0 - 80.0, start_world.1 - 50.0, 160.0, 100.0); + } else { + r.w = r.w.max(40.0); + r.h = r.h.max(32.0); + } + let next_idx = self + .snapshot + .as_deref() + .and_then(max_spatial_index) + .and_then(|m| generate_key_between(Some(&m), None).ok()) + .unwrap_or_else(|| "a0".to_string()); + let shape_str = match shape_type { + ShapeType::Rect => "rect", + ShapeType::Ellipse => "ellipse", + ShapeType::Diamond => "diamond", + ShapeType::Triangle => "triangle", + }; + let seed = (self.edgeless.authoring.next_id_seq as i32 + 17) * 97; + let cid = self.page().map(|p| p.client_id()); + let id_opt = cid.map(|c| self.edgeless.authoring.next_id("shape", c)); + if let Some(elem_id) = id_opt { + let elem_id_clone = elem_id.clone(); + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + let surface_id = page.ensure_surface_block(now_ms)?; + page.add_surface_element( + &surface_id, + elem_id_clone.clone(), + &next_idx, + SurfaceElementSpec::Shape { + shape_type: shape_str.to_string(), + xywh: PageDocSession::format_xywh([ + r.x as f64, r.y as f64, r.w as f64, r.h as f64, + ]), + seed, + filled: true, + text: None, + }, + now_ms, + )?; + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + self.edgeless.authoring.selection.clear(); + self.edgeless.authoring.selection.insert(elem_id); + self.edgeless.authoring.tool = EdgelessTool::Select; + } + } + } + EdgelessGesture::CreateFrame { + start_world, + current_world, + } => { + let mut r = normalized_rect(start_world, current_world); + if r.w < 20.0 && r.h < 20.0 { + r = WorldRect::new(start_world.0 - 160.0, start_world.1 - 120.0, 320.0, 240.0); + } else { + r.w = r.w.max(120.0); + r.h = r.h.max(80.0); + } + let next_idx = self + .snapshot + .as_deref() + .and_then(max_spatial_index) + .and_then(|m| generate_key_between(Some(&m), None).ok()) + .unwrap_or_else(|| "a0".to_string()); + let mut grouped_ids = std::collections::HashSet::<&str>::new(); + if let Some(root) = self.snapshot.as_ref().and_then(|s| s.root.as_ref()) { + for node in root.walk() { + if let BlockContent::Surface { elements, .. } = &node.content { + for el in elements { + if let SurfaceElementKind::Group { children, .. } = &el.kind { + for cid in children { + grouped_ids.insert(cid.as_str()); + } + } + } + } + } + } + let enclosed: Vec = self + .edgeless + .authoring + .painted_items + .iter() + .filter(|item| { + item.kind != SpatialItemKind::Frame + && !grouped_ids.contains(item.id.as_str()) + && r.contains_rect(rotated_bounds(item.rect, item.rotate_deg)) + }) + .map(|item| item.id.clone()) + .collect(); + let cid = self.page().map(|p| p.client_id()); + let id_opt = cid.map(|c| self.edgeless.authoring.next_id("frame", c)); + if let Some(frame_id) = id_opt { + let frame_id_clone = frame_id.clone(); + let commit = self.page_mut().ok().and_then(|page| { + let enclosed_refs: Vec<&str> = + enclosed.iter().map(String::as_str).collect(); + page.add_frame_with_children( + None, + &frame_id_clone, + "Frame", + &next_idx, + [r.x as f64, r.y as f64, r.w as f64, r.h as f64], + &enclosed_refs, + now_ms, + ) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + self.edgeless.authoring.selection.clear(); + self.edgeless.authoring.selection.insert(frame_id); + self.edgeless.authoring.tool = EdgelessTool::Select; + } + } + } + EdgelessGesture::CreateNote { + start_world, + current_world, + } => { + let mut r = normalized_rect(start_world, current_world); + if r.w < 40.0 { + r = WorldRect::new(start_world.0 - 200.0, start_world.1 - 60.0, 440.0, 140.0); + } else { + r.w = r.w.max(240.0); + r.h = r.h.max(92.0); + } + let next_idx = self + .snapshot + .as_deref() + .and_then(max_spatial_index) + .and_then(|m| generate_key_between(Some(&m), None).ok()) + .unwrap_or_else(|| "a0".to_string()); + let root_id = self + .snapshot + .as_ref() + .and_then(|s| s.root.as_ref()) + .map(|r| r.id.clone()); + let cid = self.page().map(|p| p.client_id()); + let ids = cid.map(|c| { + ( + self.edgeless.authoring.next_id("note", c), + self.edgeless.authoring.next_id("para", c), + ) + }); + if let (Some(root_id), Some((note_id, para_id))) = (root_id, ids) { + let note_id_clone = note_id.clone(); + let para_id_clone = para_id.clone(); + let commit = self.page_mut().ok().and_then(|page| { + page.add_edgeless_note( + &root_id, + ¬e_id_clone, + ¶_id_clone, + &next_idx, + [r.x as f64, r.y as f64, r.w as f64, r.h as f64], + "", + now_ms, + ) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + self.edgeless.authoring.selection.clear(); + self.edgeless.authoring.selection.insert(note_id.clone()); + self.edgeless.authoring.tool = EdgelessTool::Select; + self.edgeless.authoring.inline_edit = + Some(EdgelessInlineEdit::SpatialBlock { + block_id: note_id, + is_note: true, + }); + let pt = DocPoint::new(¶_id, 0); + self.editor.selection = Some(DocumentSelection { + anchor: pt.clone(), + focus: pt, + }); + window.notify_text_input_changed(&self.editor_focus); + } + } + } + EdgelessGesture::CreateConnector { + source_id, + source_port, + source_world, + current_world, + target_id, + target_port, + target_world, + } => { + let dst = target_world.unwrap_or(current_world); + if (dst.0 - source_world.0).hypot(dst.1 - source_world.1) < 8.0 + && target_id.is_none() + { + cx.notify(); + return; + } + let next_idx = self + .snapshot + .as_deref() + .and_then(max_spatial_index) + .and_then(|m| generate_key_between(Some(&m), None).ok()) + .unwrap_or_else(|| "a0".to_string()); + let seed = (self.edgeless.authoring.next_id_seq as i32 + 31) * 89; + let cid = self.page().map(|p| p.client_id()); + let id_opt = cid.map(|c| self.edgeless.authoring.next_id("conn", c)); + if let Some(conn_id) = id_opt { + let conn_id_clone = conn_id.clone(); + let source = match (source_id, source_port) { + (Some(id), port) => ConnectorEndpointSpec::element(id, port), + _ => ConnectorEndpointSpec::point( + source_world.0 as f64, + source_world.1 as f64, + ), + }; + let target = match (target_id, target_port) { + (Some(id), port) => ConnectorEndpointSpec::element(id, port), + _ => ConnectorEndpointSpec::point(dst.0 as f64, dst.1 as f64), + }; + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + let surface_id = page.ensure_surface_block(now_ms)?; + page.add_surface_element( + &surface_id, + conn_id_clone.clone(), + &next_idx, + SurfaceElementSpec::Connector { + mode: 1, // Orthogonal + seed, + source: source.clone(), + target: target.clone(), + text: None, + label_xywh: None, + }, + now_ms, + )?; + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + self.edgeless.authoring.selection.clear(); + self.edgeless.authoring.selection.insert(conn_id); + self.edgeless.authoring.tool = EdgelessTool::Select; + } + } + } + EdgelessGesture::DrawStroke { + highlighter, + points_world, + } => { + if points_world.len() < 2 { + cx.notify(); + return; + } + let mut min_x = f64::INFINITY; + let mut min_y = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + let mut max_y = f64::NEG_INFINITY; + for &(x, y) in &points_world { + min_x = min_x.min(x); + min_y = min_y.min(y); + max_x = max_x.max(x); + max_y = max_y.max(y); + } + let line_width = if highlighter { 22.0 } else { 4.0 }; + let half = line_width * 0.5; + let bx = min_x - half; + let by = min_y - half; + let bw = (max_x - min_x + line_width).max(line_width); + let bh = (max_y - min_y + line_width).max(line_width); + let local_points: Vec> = points_world + .iter() + .map(|&(x, y)| vec![x - bx, y - by]) + .collect(); + let next_idx = self + .snapshot + .as_deref() + .and_then(max_spatial_index) + .and_then(|m| generate_key_between(Some(&m), None).ok()) + .unwrap_or_else(|| "a0".to_string()); + let seed = (self.edgeless.authoring.next_id_seq as i32 + 53) * 61; + let prefix = if highlighter { "hl" } else { "brush" }; + let cid = self.page().map(|p| p.client_id()); + let id_opt = cid.map(|c| self.edgeless.authoring.next_id(prefix, c)); + if let Some(stroke_id) = id_opt { + let stroke_id_clone = stroke_id.clone(); + let xywh = PageDocSession::format_xywh([bx, by, bw, bh]); + let spec = if highlighter { + SurfaceElementSpec::Highlighter { + seed, + points: local_points, + xywh, + } + } else { + SurfaceElementSpec::Brush { + seed, + points: local_points, + xywh, + } + }; + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + let surface_id = page.ensure_surface_block(now_ms)?; + page.add_surface_element( + &surface_id, + stroke_id_clone.clone(), + &next_idx, + spec.clone(), + now_ms, + )?; + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + self.edgeless.authoring.selection.clear(); + self.edgeless.authoring.selection.insert(stroke_id); + } + } + } + } + } + + pub(super) fn create_surface_text_at( + &mut self, + wx: f32, + wy: f32, + window: &mut Window, + cx: &mut Context, + ) { + let now_ms = self.now_ms(cx) as u64; + let next_idx = self + .snapshot + .as_deref() + .and_then(max_spatial_index) + .and_then(|m| generate_key_between(Some(&m), None).ok()) + .unwrap_or_else(|| "a0".to_string()); + let seed = (self.edgeless.authoring.next_id_seq as i32 + 71) * 43; + let cid = self.page().map(|p| p.client_id()); + let id_opt = cid.map(|c| self.edgeless.authoring.next_id("text", c)); + let Some(text_id) = id_opt else { return }; + let text_id_clone = text_id.clone(); + let rect = WorldRect::new(wx, wy, 180.0, 36.0); + let surface_id_out = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let surface_id_ref = std::rc::Rc::clone(&surface_id_out); + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + let sid = page.ensure_surface_block(now_ms)?; + *surface_id_ref.borrow_mut() = sid.clone(); + page.add_surface_element( + &sid, + text_id_clone.clone(), + &next_idx, + SurfaceElementSpec::Text { + seed, + text: String::new(), + xywh: PageDocSession::format_xywh([ + rect.x as f64, + rect.y as f64, + rect.w as f64, + rect.h as f64, + ]), + }, + now_ms, + )?; + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + self.edgeless.authoring.selection.clear(); + self.edgeless.authoring.selection.insert(text_id.clone()); + self.edgeless.authoring.tool = EdgelessTool::Select; + let mut ed = EdgelessLabelEditor::new( + LabelTarget::SurfaceText { + surface_id: surface_id_out.borrow().clone(), + id: text_id, + }, + String::new(), + rect, + 0.0, + true, + ); + ed.created_new_text = true; + self.edgeless.authoring.inline_edit = Some(EdgelessInlineEdit::Label(ed)); + if let Ok(page) = self.page_mut() { + let _ = page.stop_capturing(); + } + self.edgeless_update_label_anchors(0..0); + window.notify_text_input_changed(&self.editor_focus); + } + } +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/gestures.rs b/blocksuite/native-playground/crates/playground/src/edgeless/gestures.rs new file mode 100644 index 0000000000..7a5a1a6440 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/gestures.rs @@ -0,0 +1,459 @@ +//! Pointer down/move gesture state machine for Edgeless selection, drag, resize, rotate, and tool creation. + +use std::collections::BTreeSet; + +use blocksuite_playground_doc::read::SurfaceElementKind; +use ui::{Context, MouseDownEvent, MouseMoveEvent, Window, point, px}; + +use crate::{PlaygroundView, TOPBAR_HEIGHT, editor_session::DocumentSelection}; + +use super::{ + DragItemInitial, EdgelessGesture, EdgelessTool, HandleKind, NOTE_CARD_PADDING, SpatialItemKind, + find_surface_element, layout_label_editor_paragraph, normalized_rect, point_in_rotated_rect, + rotate_point_around, +}; + +impl PlaygroundView { + pub(crate) fn on_edgeless_left_down( + &mut self, + event: &MouseDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + self.editor_focus.focus(window, cx); + let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT)); + let world_pt = self + .edgeless + .camera + .screen_to_world(event.position, vp_origin); + let wx = f32::from(world_pt.x); + let wy = f32::from(world_pt.y); + + // Hand tool or Space-hold pans with left drag. + if self.edgeless.authoring.tool == EdgelessTool::Hand || self.edgeless.authoring.space_pan { + self.edgeless_commit_inline_edit(window, cx); + self.edgeless.authoring.gesture = Some(EdgelessGesture::Pan { + last_screen: event.position, + }); + cx.notify(); + return; + } + + // If currently inline-editing a Note/EdgelessText and clicking inside it, route to EditorSession. + if let Some((editing_id, is_note)) = self.edgeless.authoring.editing_spatial_block() { + let editing_id = editing_id.to_string(); + if let Some(info) = self + .edgeless + .authoring + .painted_items + .iter() + .find(|i| i.id == editing_id) + .cloned() + && point_in_rotated_rect(wx, wy, info.rect, info.rotate_deg) + { + let (cx_w, cy_w) = info.rect.center(); + let (lx, ly) = rotate_point_around(wx, wy, cx_w, cy_w, -info.rotate_deg); + let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 }; + let flow_x = (lx - info.rect.x) / info.scale - pad; + let flow_y = (ly - info.rect.y) / info.scale - pad; + if let Some(layout) = self.edgeless.cached_block_layout(&editing_id, is_note) + && let Some(pt) = Self::hit_test_flow_layout(&layout, flow_x, flow_y) + { + let sel = DocumentSelection { + anchor: pt.clone(), + focus: pt, + }; + self.change_selection(sel, window, cx); + return; + } + } + } + + // If currently inline-editing a label (Shape/Connector/SurfaceText/Frame) and clicking + // inside its overlay bounds, hit-test the laid-out RichParagraph and place the caret. + if let Some(ed) = self.edgeless.authoring.label_editor() { + let bounds = self.edgeless_label_screen_bounds(); + let inside_overlay = bounds.is_some_and(|b| b.contains(&event.position)) + || point_in_rotated_rect(wx, wy, ed.world_rect, ed.rotate_deg); + if inside_overlay { + let off = bounds + .and_then(|b| { + let laid_out = layout_label_editor_paragraph( + ed, + f32::from(b.size.width), + self.theme, + window, + )?; + let local_pt = point( + event.position.x - b.origin.x - px(6.0), + event.position.y - b.origin.y - px(6.0), + ); + Some(laid_out.hit_test(local_pt).utf16_offset as usize) + }) + .unwrap_or_else(|| ed.text.encode_utf16().count()); + if let Some(ed_mut) = self.edgeless.authoring.label_editor_mut() { + ed_mut.select(off..off); + } + self.edgeless_update_label_anchors(off..off); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + return; + } + } + + // Clicking outside an active inline label/block edit commits and exits it. + if self.edgeless.authoring.inline_edit.is_some() { + self.edgeless_commit_inline_edit(window, cx); + } + + match self.edgeless.authoring.tool { + EdgelessTool::Select => { + // Double-click enters inline rich-text / label IME editing. + if event.click_count >= 2 { + if let Some(hit) = self + .edgeless + .authoring + .hit_test_world(wx, wy, self.edgeless.camera.zoom) + .cloned() + { + self.edgeless_begin_inline_edit(&hit.id, window, cx); + return; + } + } + + // 1. Check active selection handles first. + let vp_w = self.window_size.0.max(1.0); + let vp_h = (self.window_size.1 - TOPBAR_HEIGHT).max(1.0); + if let Some(handle) = self.edgeless.authoring.hit_test_handles( + event.position, + vp_origin, + vp_w, + vp_h, + self.edgeless.camera, + ) { + match handle { + HandleKind::Rotate => { + if let Some(single) = self.edgeless.authoring.single_selected().cloned() + { + let center = single.rect.center(); + let start_angle = ((wy - center.1) as f64) + .atan2((wx - center.0) as f64) + .to_degrees(); + self.edgeless.authoring.gesture = + Some(EdgelessGesture::RotateSelection { + id: single.id, + surface_id: single.surface_id, + is_block: single.kind.is_block(), + center_world: center, + start_angle, + initial_rotate: single.rotate_deg as f64, + current_rotate: single.rotate_deg as f64, + }); + cx.notify(); + return; + } + } + HandleKind::DragHandle => { + let initial = self.collect_drag_initials(); + if !initial.is_empty() { + self.edgeless.authoring.gesture = + Some(EdgelessGesture::DragSelection { + start_world: (wx, wy), + current_world: (wx, wy), + initial, + }); + cx.notify(); + return; + } + } + _ => { + if let Some(initial_box) = self.edgeless.authoring.selection_world_box() + { + let initial = self.collect_drag_initials(); + self.edgeless.authoring.gesture = + Some(EdgelessGesture::ResizeSelection { + handle, + start_world: (wx, wy), + current_world: (wx, wy), + initial_box, + initial, + }); + cx.notify(); + return; + } + } + } + } + + // 2. Top-to-bottom reverse paint-order hit-test. + if let Some(hit) = self + .edgeless + .authoring + .hit_test_world(wx, wy, self.edgeless.camera.zoom) + .cloned() + { + if event.modifiers.shift { + if !self.edgeless.authoring.selection.remove(&hit.id) { + self.edgeless.authoring.selection.insert(hit.id.clone()); + } + } else if !self.edgeless.authoring.selection.contains(&hit.id) { + self.edgeless.authoring.selection.clear(); + self.edgeless.authoring.selection.insert(hit.id.clone()); + } + let initial = self.collect_drag_initials(); + if !initial.is_empty() { + self.edgeless.authoring.gesture = Some(EdgelessGesture::DragSelection { + start_world: (wx, wy), + current_world: (wx, wy), + initial, + }); + } + cx.notify(); + } else { + // Empty canvas: clear selection and start marquee box. + if !event.modifiers.shift { + self.edgeless.authoring.selection.clear(); + } + self.edgeless.authoring.gesture = Some(EdgelessGesture::Marquee { + start_world: (wx, wy), + current_world: (wx, wy), + }); + cx.notify(); + } + } + EdgelessTool::Shape(shape_type) => { + self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateShape { + shape_type, + start_world: (wx, wy), + current_world: (wx, wy), + }); + cx.notify(); + } + EdgelessTool::Frame => { + self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateFrame { + start_world: (wx, wy), + current_world: (wx, wy), + }); + cx.notify(); + } + EdgelessTool::Note => { + self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateNote { + start_world: (wx, wy), + current_world: (wx, wy), + }); + cx.notify(); + } + EdgelessTool::Connector => { + let snapped = self.edgeless.authoring.snap_connector_port( + wx, + wy, + self.edgeless.camera.zoom, + None, + ); + let (source_id, source_port, source_world) = match snapped { + Some((id, port, pt)) => (Some(id), Some(port), pt), + None => (None, None, (wx, wy)), + }; + self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateConnector { + source_id, + source_port, + source_world, + current_world: (wx, wy), + target_id: None, + target_port: None, + target_world: None, + }); + cx.notify(); + } + EdgelessTool::Brush | EdgelessTool::Highlighter => { + let highlighter = self.edgeless.authoring.tool == EdgelessTool::Highlighter; + self.edgeless.authoring.gesture = Some(EdgelessGesture::DrawStroke { + highlighter, + points_world: vec![(wx as f64, wy as f64)], + }); + cx.notify(); + } + EdgelessTool::Text => { + self.create_surface_text_at(wx, wy, window, cx); + } + EdgelessTool::Hand => {} + } + } + + pub(crate) fn on_edgeless_pointer_move( + &mut self, + event: &MouseMoveEvent, + _window: &mut Window, + cx: &mut Context, + ) { + // Middle-button pan continues to work as before. + if let Some(prev) = self.edgeless.drag_pan_anchor { + let dx = f32::from(event.position.x) - f32::from(prev.x); + let dy = f32::from(event.position.y) - f32::from(prev.y); + self.edgeless.camera.pan_by_screen_delta(dx, dy); + self.edgeless.drag_pan_anchor = Some(event.position); + self.edgeless.camera_initialized = true; + cx.notify(); + return; + } + let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT)); + let world_pt = self + .edgeless + .camera + .screen_to_world(event.position, vp_origin); + let wx = f32::from(world_pt.x); + let wy = f32::from(world_pt.y); + let shift = event.modifiers.shift; + let zoom = self.edgeless.camera.zoom; + + let conn_snap = match &self.edgeless.authoring.gesture { + Some(EdgelessGesture::CreateConnector { source_id, .. }) => self + .edgeless + .authoring + .snap_connector_port(wx, wy, zoom, source_id.as_deref()), + _ => None, + }; + + match self.edgeless.authoring.gesture.as_mut() { + Some(EdgelessGesture::Pan { last_screen }) => { + let dx = f32::from(event.position.x) - f32::from(last_screen.x); + let dy = f32::from(event.position.y) - f32::from(last_screen.y); + self.edgeless.camera.pan_by_screen_delta(dx, dy); + *last_screen = event.position; + self.edgeless.camera_initialized = true; + cx.notify(); + } + Some(EdgelessGesture::Marquee { + start_world, + current_world, + }) => { + *current_world = (wx, wy); + let marquee = normalized_rect(*start_world, *current_world); + let hits: BTreeSet = self + .edgeless + .authoring + .painted_items + .iter() + .filter(|item| item.rect.intersects(marquee)) + .map(|item| item.id.clone()) + .collect(); + self.edgeless.authoring.selection = hits; + cx.notify(); + } + Some(EdgelessGesture::DragSelection { current_world, .. }) + | Some(EdgelessGesture::ResizeSelection { current_world, .. }) + | Some(EdgelessGesture::CreateShape { current_world, .. }) + | Some(EdgelessGesture::CreateFrame { current_world, .. }) + | Some(EdgelessGesture::CreateNote { current_world, .. }) => { + *current_world = (wx, wy); + cx.notify(); + } + Some(EdgelessGesture::RotateSelection { + center_world, + start_angle, + initial_rotate, + current_rotate, + .. + }) => { + let angle = ((wy - center_world.1) as f64) + .atan2((wx - center_world.0) as f64) + .to_degrees(); + let mut next = (*initial_rotate + (angle - *start_angle)).rem_euclid(360.0); + if shift { + next = (next / 15.0).round() * 15.0; + } + *current_rotate = next; + cx.notify(); + } + Some(EdgelessGesture::CreateConnector { + current_world, + target_id, + target_port, + target_world, + .. + }) => { + *current_world = (wx, wy); + if let Some((tid, port, pt)) = conn_snap { + *target_id = Some(tid); + *target_port = Some(port); + *target_world = Some(pt); + } else { + *target_id = None; + *target_port = None; + *target_world = None; + } + cx.notify(); + } + Some(EdgelessGesture::DrawStroke { points_world, .. }) => { + let should_push = points_world + .last() + .is_none_or(|&(lx, ly)| ((wx as f64 - lx).hypot(wy as f64 - ly)) >= 2.0); + if should_push { + points_world.push((wx as f64, wy as f64)); + cx.notify(); + } + } + None => {} + } + } + + pub(super) fn collect_drag_initials(&self) -> Vec { + let Some(snapshot) = &self.snapshot else { + return Vec::new(); + }; + let mut ids: BTreeSet = self.edgeless.authoring.selection.clone(); + // When dragging a Frame, include all of its `prop:childElementIds` members too! + for item in self.edgeless.authoring.painted_items.iter() { + if item.kind == SpatialItemKind::Frame && ids.contains(&item.id) { + for child_id in &item.frame_children { + ids.insert(child_id.clone()); + } + } + } + let mut out = Vec::new(); + for item in self.edgeless.authoring.painted_items.iter() { + if !ids.contains(&item.id) { + continue; + } + let mut points = None; + let mut connector_source = None; + let mut connector_target = None; + let mut connector_label_xywh = None; + if let Some((_, el)) = find_surface_element(snapshot, &item.id) { + match &el.kind { + SurfaceElementKind::Brush(s) | SurfaceElementKind::Highlighter(s) => { + points = Some( + s.points + .iter() + .map(|p| { + if s.simulated_pressure { + vec![p[0], p[1]] + } else { + vec![p[0], p[1], p[2]] + } + }) + .collect(), + ); + } + SurfaceElementKind::Connector(c) => { + connector_source = Some((c.source.id.clone(), c.source.position)); + connector_target = Some((c.target.id.clone(), c.target.position)); + connector_label_xywh = c.label_xywh; + } + _ => {} + } + } + out.push(DragItemInitial { + id: item.id.clone(), + kind: item.kind, + surface_id: item.surface_id.clone(), + rect: item.rect, + points, + connector_source, + connector_target, + connector_label_xywh, + }); + } + out + } +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/hit_test.rs b/blocksuite/native-playground/crates/playground/src/edgeless/hit_test.rs new file mode 100644 index 0000000000..b86c8ef210 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/hit_test.rs @@ -0,0 +1,854 @@ +//! Edgeless selection state, reverse paint-order world hit-testing, and geometry helpers. + +use std::{ + collections::{BTreeMap, BTreeSet}, + rc::Rc, +}; + +use blocksuite_playground_doc::read::ShapeType; +use ui::{Pixels, Point, point, px}; + +use super::{EdgelessCamera, EdgelessInlineEdit, EdgelessLabelEditor, EdgelessTool, WorldRect}; + +/// Interactive handle on the current Edgeless selection box. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HandleKind { + NW, + N, + NE, + E, + SE, + S, + SW, + W, + Rotate, + DragHandle, +} + +impl HandleKind { + pub const RESIZE_HANDLES: [Self; 8] = [ + Self::NW, + Self::N, + Self::NE, + Self::E, + Self::SE, + Self::S, + Self::SW, + Self::W, + ]; + + pub fn snapshot_id(self) -> &'static str { + match self { + Self::NW => "edgeless.handle.nw", + Self::N => "edgeless.handle.n", + Self::NE => "edgeless.handle.ne", + Self::E => "edgeless.handle.e", + Self::SE => "edgeless.handle.se", + Self::S => "edgeless.handle.s", + Self::SW => "edgeless.handle.sw", + Self::W => "edgeless.handle.w", + Self::Rotate => "edgeless.handle.rotate", + Self::DragHandle => "edgeless.drag_handle", + } + } +} + +/// Spatial item classification for hit-testing, handles, and mutations. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SpatialItemKind { + Note, + Frame, + EdgelessText, + Shape, + Connector, + Brush, + Highlighter, + SurfaceText, + Group, +} + +impl SpatialItemKind { + pub fn is_block(self) -> bool { + matches!(self, Self::Note | Self::Frame | Self::EdgelessText) + } + + pub fn is_rotatable(self) -> bool { + matches!(self, Self::Shape | Self::EdgelessText) + } + + pub fn has_gfx_drag_handle(self) -> bool { + matches!(self, Self::Note | Self::Frame | Self::EdgelessText) + } +} + +/// Snapshot-derived world-space descriptor for one painted Edgeless item in paint order. +#[derive(Clone, Debug)] +pub struct SpatialItemInfo { + pub id: String, + pub kind: SpatialItemKind, + pub surface_id: Option, + pub rect: WorldRect, + pub rotate_deg: f32, + pub index: String, + pub scale: f32, + pub stroke_width: f32, + pub polyline: Vec<(f32, f32)>, + pub frame_children: Vec, + pub title_pill_rect: Option, +} + +/// Target of an inline UTF-16 + IME label editor on the Edgeless canvas. + +#[derive(Clone, Debug)] +pub struct DragItemInitial { + pub id: String, + pub kind: SpatialItemKind, + pub surface_id: Option, + pub rect: WorldRect, + pub points: Option>>, + pub connector_source: Option<(Option, Option<[f64; 2]>)>, + pub connector_target: Option<(Option, Option<[f64; 2]>)>, + pub connector_label_xywh: Option<[f64; 4]>, +} + +/// Active pointer gesture on the Edgeless canvas. +#[derive(Clone, Debug)] +pub enum EdgelessGesture { + Pan { + last_screen: Point, + }, + Marquee { + start_world: (f32, f32), + current_world: (f32, f32), + }, + DragSelection { + start_world: (f32, f32), + current_world: (f32, f32), + initial: Vec, + }, + ResizeSelection { + handle: HandleKind, + start_world: (f32, f32), + current_world: (f32, f32), + initial_box: WorldRect, + initial: Vec, + }, + RotateSelection { + id: String, + surface_id: Option, + is_block: bool, + center_world: (f32, f32), + start_angle: f64, + initial_rotate: f64, + current_rotate: f64, + }, + CreateShape { + shape_type: ShapeType, + start_world: (f32, f32), + current_world: (f32, f32), + }, + CreateFrame { + start_world: (f32, f32), + current_world: (f32, f32), + }, + CreateNote { + start_world: (f32, f32), + current_world: (f32, f32), + }, + CreateConnector { + source_id: Option, + source_port: Option<[f64; 2]>, + source_world: (f32, f32), + current_world: (f32, f32), + target_id: Option, + target_port: Option<[f64; 2]>, + target_world: Option<(f32, f32)>, + }, + DrawStroke { + highlighter: bool, + points_world: Vec<(f64, f64)>, + }, +} + +/// Live geometry override applied during an active drag/resize/rotate gesture before commit. +#[derive(Clone, Copy, Debug)] +pub struct LiveGeomOverride { + pub rect: WorldRect, + pub rotate_deg: Option, + pub delta: (f32, f32), +} + +/// Interactive authoring state owned by `EdgelessCanvasState`. +#[derive(Default)] +pub struct EdgelessAuthoringState { + pub tool: EdgelessTool, + pub last_shape_type: Option, + pub selection: BTreeSet, + pub(super) gesture: Option, + pub inline_edit: Option, + pub space_pan: bool, + pub next_id_seq: u64, + /// Items in exact paint order from the most recent rendered frame. + pub(super) painted_items: Rc<[SpatialItemInfo]>, +} + +impl EdgelessAuthoringState { + pub fn reset_transient(&mut self) { + self.gesture = None; + self.space_pan = false; + } + + pub fn active_shape_type(&self) -> ShapeType { + match self.tool { + EdgelessTool::Shape(t) => t, + _ => self.last_shape_type.unwrap_or(ShapeType::Rect), + } + } + + pub fn label_editor(&self) -> Option<&EdgelessLabelEditor> { + match &self.inline_edit { + Some(EdgelessInlineEdit::Label(ed)) => Some(ed), + _ => None, + } + } + + pub fn label_editor_mut(&mut self) -> Option<&mut EdgelessLabelEditor> { + match &mut self.inline_edit { + Some(EdgelessInlineEdit::Label(ed)) => Some(ed), + _ => None, + } + } + + pub fn editing_spatial_block(&self) -> Option<(&str, bool)> { + match &self.inline_edit { + Some(EdgelessInlineEdit::SpatialBlock { block_id, is_note }) => { + Some((block_id.as_str(), *is_note)) + } + _ => None, + } + } + + pub fn next_id(&mut self, prefix: &str, client_id: u64) -> String { + self.next_id_seq += 1; + format!("{prefix}:{client_id}:{}", self.next_id_seq) + } + + /// Compute live per-item geometry overrides for an active drag/resize/rotate gesture. + pub fn live_overrides(&self) -> BTreeMap { + let mut out = BTreeMap::new(); + match &self.gesture { + Some(EdgelessGesture::DragSelection { + start_world, + current_world, + initial, + }) => { + let dx = current_world.0 - start_world.0; + let dy = current_world.1 - start_world.1; + for item in initial { + out.insert( + item.id.clone(), + LiveGeomOverride { + rect: WorldRect::new( + item.rect.x + dx, + item.rect.y + dy, + item.rect.w, + item.rect.h, + ), + rotate_deg: None, + delta: (dx, dy), + }, + ); + } + } + Some(EdgelessGesture::ResizeSelection { + handle, + start_world, + current_world, + initial_box, + initial, + }) => { + let new_box = resized_rect(*initial_box, *handle, *start_world, *current_world); + let sx = if initial_box.w > 1e-3 { + new_box.w / initial_box.w + } else { + 1.0 + }; + let sy = if initial_box.h > 1e-3 { + new_box.h / initial_box.h + } else { + 1.0 + }; + for item in initial { + let nx = new_box.x + (item.rect.x - initial_box.x) * sx; + let ny = new_box.y + (item.rect.y - initial_box.y) * sy; + let nw = (item.rect.w * sx).max(16.0); + let nh = (item.rect.h * sy).max(16.0); + out.insert( + item.id.clone(), + LiveGeomOverride { + rect: WorldRect::new(nx, ny, nw, nh), + rotate_deg: None, + delta: (0.0, 0.0), + }, + ); + } + } + Some(EdgelessGesture::RotateSelection { + id, current_rotate, .. + }) => { + if let Some(info) = self.painted_items.iter().find(|i| i.id == *id) { + out.insert( + id.clone(), + LiveGeomOverride { + rect: info.rect, + rotate_deg: Some(*current_rotate as f32), + delta: (0.0, 0.0), + }, + ); + } + } + _ => {} + } + out + } + + /// True if the selection contains at least one item that supports the 8 resize handles + /// (connectors hide the 8 resize handles because their geometry comes from endpoints). + pub fn selection_has_non_connector(&self) -> bool { + self.painted_items.iter().any(|item| { + self.selection.contains(&item.id) && item.kind != SpatialItemKind::Connector + }) + } + + /// Compute the selection's combined world-space bounding box (with live gesture overrides). + pub fn selection_world_box(&self) -> Option { + let overrides = self.live_overrides(); + let mut combined = WorldRect::default(); + let mut any = false; + for item in self.painted_items.iter() { + if !self.selection.contains(&item.id) { + continue; + } + let rect = overrides.get(&item.id).map_or(item.rect, |o| o.rect); + combined = if any { combined.union(rect) } else { rect }; + any = true; + } + any.then_some(combined) + } + + /// Return the single selected item if `selection.len() == 1`. + pub fn single_selected(&self) -> Option<&SpatialItemInfo> { + if self.selection.len() != 1 { + return None; + } + let id = self.selection.iter().next()?; + self.painted_items.iter().find(|i| i.id == *id) + } + + /// Hit-test active selection handles in screen space (`vp_origin`-relative). + pub fn hit_test_handles( + &self, + screen_pt: Point, + vp_origin: Point, + viewport_width: f32, + viewport_height: f32, + camera: EdgelessCamera, + ) -> Option { + let sel_box = self.selection_world_box()?; + let tl = camera.world_to_screen(point(px(sel_box.x), px(sel_box.y)), vp_origin); + let br = + camera.world_to_screen(point(px(sel_box.right()), px(sel_box.bottom())), vp_origin); + let x0 = f32::from(tl.x); + let y0 = f32::from(tl.y); + let x1 = f32::from(br.x); + let y1 = f32::from(br.y); + let mx = (x0 + x1) * 0.5; + let my = (y0 + y1) * 0.5; + let px_s = f32::from(screen_pt.x); + let py_s = f32::from(screen_pt.y); + + let single = self.single_selected(); + let rot_deg = single + .filter(|s| s.kind.is_rotatable() && s.rotate_deg.abs() > 1e-3) + .map_or(0.0, |s| s.rotate_deg); + let (rx_pt, ry_pt) = if rot_deg.abs() > 1e-3 { + rotate_point_around(px_s, py_s, mx, my, -rot_deg) + } else { + (px_s, py_s) + }; + + // Rotation handle (24px above top-center for single rotatable item). + if let Some(single) = single + && single.kind.is_rotatable() + { + let rx = mx; + let ry = y0 - 24.0; + if (rx_pt - rx).hypot(ry_pt - ry) <= 10.0 { + return Some(HandleKind::Rotate); + } + } + + // Edgeless gfx 2x3 drag handle left of single selected block (matches overlay.rs clamp). + if let Some(single) = single + && single.kind.has_gfx_drag_handle() + { + let vp_x = f32::from(vp_origin.x); + let vp_y = f32::from(vp_origin.y); + let hx = (x0 - vp_x - 20.0) + .clamp(4.0, (viewport_width - 18.0).max(4.0)) + .round() + + vp_x; + let hy = (y0 - vp_y) + .clamp(4.0, (viewport_height - 28.0).max(4.0)) + .round() + + vp_y; + if px_s >= hx && px_s <= hx + 14.0 && py_s >= hy && py_s <= hy + 24.0 { + return Some(HandleKind::DragHandle); + } + } + + if !self.selection_has_non_connector() { + return None; + } + + let coords = [ + (HandleKind::NW, x0, y0), + (HandleKind::N, mx, y0), + (HandleKind::NE, x1, y0), + (HandleKind::E, x1, my), + (HandleKind::SE, x1, y1), + (HandleKind::S, mx, y1), + (HandleKind::SW, x0, y1), + (HandleKind::W, x0, my), + ]; + for (kind, hx, hy) in coords { + if (rx_pt - hx).abs() <= 7.0 && (ry_pt - hy).abs() <= 7.0 { + return Some(kind); + } + } + None + } + + /// Top-to-bottom hit-testing in exact reverse `edgeless_order.rs` paint order. + pub fn hit_test_world( + &self, + world_x: f32, + world_y: f32, + zoom: f32, + ) -> Option<&SpatialItemInfo> { + let inv_zoom = 1.0 / zoom.max(0.1); + for item in self.painted_items.iter().rev() { + match item.kind { + SpatialItemKind::Shape + | SpatialItemKind::SurfaceText + | SpatialItemKind::EdgelessText => { + if point_in_rotated_rect(world_x, world_y, item.rect, item.rotate_deg) { + return Some(item); + } + } + SpatialItemKind::Note => { + if world_x >= item.rect.x + && world_x <= item.rect.right() + && world_y >= item.rect.y + && world_y <= item.rect.bottom() + { + return Some(item); + } + } + SpatialItemKind::Connector + | SpatialItemKind::Brush + | SpatialItemKind::Highlighter => { + let threshold = (item.stroke_width * 0.5 + 6.0 * inv_zoom).max(6.0); + if !item.polyline.is_empty() { + if distance_to_polyline((world_x, world_y), &item.polyline) <= threshold { + return Some(item); + } + } else if world_x >= item.rect.x - threshold + && world_x <= item.rect.right() + threshold + && world_y >= item.rect.y - threshold + && world_y <= item.rect.bottom() + threshold + { + return Some(item); + } + } + SpatialItemKind::Frame => { + // Frame hit-tests on its title pill and border so clicking inside an + // unselected frame can hit inner items or start a marquee selection. + if let Some(pill) = item.title_pill_rect + && world_x >= pill.x + && world_x <= pill.right() + && world_y >= pill.y + && world_y <= pill.bottom() + { + return Some(item); + } + let tol = (8.0 * inv_zoom).max(6.0); + let in_outer = world_x >= item.rect.x - tol + && world_x <= item.rect.right() + tol + && world_y >= item.rect.y - tol + && world_y <= item.rect.bottom() + tol; + let in_inner = world_x > item.rect.x + tol + && world_x < item.rect.right() - tol + && world_y > item.rect.y + tol + && world_y < item.rect.bottom() - tol; + if in_outer && !in_inner { + return Some(item); + } + } + SpatialItemKind::Group => {} + } + } + None + } + + /// Snap a world coordinate to the nearest cardinal port on a Shape or Note within `snap_world`. + pub fn snap_connector_port( + &self, + world_x: f32, + world_y: f32, + zoom: f32, + exclude_id: Option<&str>, + ) -> Option<(String, [f64; 2], (f32, f32))> { + let snap_dist = (24.0 / zoom.max(0.1)).max(16.0); + let ports: [[f64; 2]; 4] = [[0.5, 0.0], [1.0, 0.5], [0.5, 1.0], [0.0, 0.5]]; + let mut best: Option<(f32, String, [f64; 2], (f32, f32))> = None; + for item in self.painted_items.iter() { + if !matches!(item.kind, SpatialItemKind::Shape | SpatialItemKind::Note) { + continue; + } + if exclude_id.is_some_and(|ex| ex == item.id) { + continue; + } + for port in ports { + let px_w = item.rect.x + item.rect.w * port[0] as f32; + let py_w = item.rect.y + item.rect.h * port[1] as f32; + let (wx, wy) = rotate_point_around( + px_w, + py_w, + item.rect.center().0, + item.rect.center().1, + item.rotate_deg, + ); + let d = (world_x - wx).hypot(world_y - wy); + if d <= snap_dist && best.as_ref().is_none_or(|b| d < b.0) { + best = Some((d, item.id.clone(), port, (wx, wy))); + } + } + } + best.map(|(_, id, port, pt)| (id, port, pt)) + } +} + +pub fn rotate_point_around(x: f32, y: f32, cx: f32, cy: f32, deg: f32) -> (f32, f32) { + if deg.abs() < 1e-4 { + return (x, y); + } + let (s, c) = deg.to_radians().sin_cos(); + let dx = x - cx; + let dy = y - cy; + (cx + dx * c - dy * s, cy + dx * s + dy * c) +} + +pub fn point_in_rotated_rect(wx: f32, wy: f32, rect: WorldRect, rotate_deg: f32) -> bool { + let (cx, cy) = rect.center(); + let (lx, ly) = rotate_point_around(wx, wy, cx, cy, -rotate_deg); + lx >= rect.x && lx <= rect.right() && ly >= rect.y && ly <= rect.bottom() +} + +pub fn distance_to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 { + let vx = b.0 - a.0; + let vy = b.1 - a.1; + let len_sq = vx * vx + vy * vy; + if len_sq < 1e-8 { + return (p.0 - a.0).hypot(p.1 - a.1); + } + let t = (((p.0 - a.0) * vx + (p.1 - a.1) * vy) / len_sq).clamp(0.0, 1.0); + let proj_x = a.0 + t * vx; + let proj_y = a.1 + t * vy; + (p.0 - proj_x).hypot(p.1 - proj_y) +} + +pub fn distance_to_polyline(p: (f32, f32), pts: &[(f32, f32)]) -> f32 { + if pts.is_empty() { + return f32::INFINITY; + } + if pts.len() == 1 { + return (p.0 - pts[0].0).hypot(p.1 - pts[0].1); + } + pts.windows(2) + .map(|w| distance_to_segment(p, w[0], w[1])) + .fold(f32::INFINITY, f32::min) +} + +pub fn normalized_rect(a: (f32, f32), b: (f32, f32)) -> WorldRect { + let x = a.0.min(b.0); + let y = a.1.min(b.1); + WorldRect::new(x, y, (a.0 - b.0).abs(), (a.1 - b.1).abs()) +} + +pub fn resized_rect( + initial: WorldRect, + handle: HandleKind, + start: (f32, f32), + current: (f32, f32), +) -> WorldRect { + let dx = current.0 - start.0; + let dy = current.1 - start.1; + let mut left = initial.x; + let mut top = initial.y; + let mut right = initial.right(); + let mut bottom = initial.bottom(); + const MIN_DIM: f32 = 24.0; + match handle { + HandleKind::NW => { + left = (left + dx).min(right - MIN_DIM); + top = (top + dy).min(bottom - MIN_DIM); + } + HandleKind::N => { + top = (top + dy).min(bottom - MIN_DIM); + } + HandleKind::NE => { + right = (right + dx).max(left + MIN_DIM); + top = (top + dy).min(bottom - MIN_DIM); + } + HandleKind::E => { + right = (right + dx).max(left + MIN_DIM); + } + HandleKind::SE => { + right = (right + dx).max(left + MIN_DIM); + bottom = (bottom + dy).max(top + MIN_DIM); + } + HandleKind::S => { + bottom = (bottom + dy).max(top + MIN_DIM); + } + HandleKind::SW => { + left = (left + dx).min(right - MIN_DIM); + bottom = (bottom + dy).max(top + MIN_DIM); + } + HandleKind::W => { + left = (left + dx).min(right - MIN_DIM); + } + HandleKind::Rotate | HandleKind::DragHandle => {} + } + WorldRect::new(left, top, right - left, bottom - top) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + surface::{WorldBounds, layout_surface}, + theme::PlaygroundTheme, + }; + use blocksuite_playground_doc::{ + read::{BlockContent, SurfaceElementKind}, + schema::{BlockSpec, ConnectorEndpointSpec, SurfaceElementSpec}, + session::PageDocSession, + }; + use std::collections::BTreeMap; + use ui::{AppContext, Application, HeadlessPlatform}; + + #[test] + fn reverse_paint_order_hit_test_handles_rotated_obb_polyline_and_frame_border() { + let mut state = EdgelessAuthoringState::default(); + state.painted_items = vec![ + SpatialItemInfo { + id: "frame1".into(), + kind: SpatialItemKind::Frame, + surface_id: None, + rect: WorldRect::new(0.0, 0.0, 400.0, 300.0), + rotate_deg: 0.0, + index: "a0".into(), + scale: 1.0, + stroke_width: 1.0, + polyline: vec![], + frame_children: vec!["rot_shape".into()], + title_pill_rect: Some(WorldRect::new(0.0, -28.0, 80.0, 22.0)), + }, + SpatialItemInfo { + id: "rot_shape".into(), + kind: SpatialItemKind::Shape, + surface_id: Some("surf".into()), + rect: WorldRect::new(100.0, 100.0, 100.0, 40.0), + rotate_deg: 90.0, + index: "a1".into(), + scale: 1.0, + stroke_width: 2.0, + polyline: vec![], + frame_children: vec![], + title_pill_rect: None, + }, + SpatialItemInfo { + id: "brush1".into(), + kind: SpatialItemKind::Brush, + surface_id: Some("surf".into()), + rect: WorldRect::new(250.0, 50.0, 100.0, 10.0), + rotate_deg: 0.0, + index: "a2".into(), + scale: 1.0, + stroke_width: 4.0, + polyline: vec![(250.0, 55.0), (350.0, 55.0)], + frame_children: vec![], + title_pill_rect: None, + }, + ] + .into(); + // Clicking empty interior of frame does NOT hit frame (allows marquee). + assert!(state.hit_test_world(50.0, 50.0, 1.0).is_none()); + // Clicking frame title pill hits frame. + assert_eq!(state.hit_test_world(20.0, -15.0, 1.0).unwrap().id, "frame1"); + // Clicking frame border hits frame. + assert_eq!(state.hit_test_world(2.0, 150.0, 1.0).unwrap().id, "frame1"); + // Rotated 90° around (150, 120): (150, 75) is inside rotated 100x40 box! + assert_eq!( + state.hit_test_world(150.0, 75.0, 1.0).unwrap().id, + "rot_shape" + ); + // Polyline hit within stroke_width/2 + 6px. + assert_eq!(state.hit_test_world(300.0, 58.0, 1.0).unwrap().id, "brush1"); + assert!(state.hit_test_world(300.0, 75.0, 1.0).is_none()); + } + + #[test] + fn hit_test_world_hits_shapes_and_routed_element_bound_connector() { + let mut page = PageDocSession::new("p1", 1).unwrap(); + page.add_block( + "page-1", + BlockSpec::Page { + title: "Test".into(), + }, + None, + None, + 1, + ) + .unwrap(); + let surf = page.ensure_surface_block(2).unwrap(); + page.add_surface_element( + &surf, + "collect", + "a0", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[818,522,150,82]".into(), + seed: 31, + filled: true, + text: Some("Collect".into()), + }, + 3, + ) + .unwrap(); + page.add_surface_element( + &surf, + "review", + "a1", + SurfaceElementSpec::Shape { + shape_type: "rect".into(), + xywh: "[988,722,156,74]".into(), + seed: 37, + filled: true, + text: Some("Review".into()), + }, + 4, + ) + .unwrap(); + page.add_surface_element( + &surf, + "handoff", + "a2", + SurfaceElementSpec::Connector { + mode: 1, + seed: 41, + source: ConnectorEndpointSpec::element("collect", Some([1.0, 0.5])), + target: ConnectorEndpointSpec::element("review", Some([0.5, 0.0])), + text: Some("Synthesize".into()), + label_xywh: None, + }, + 5, + ) + .unwrap(); + let snap = page.read_page_snapshot().unwrap(); + let surf_node = snap + .root + .as_ref() + .unwrap() + .children + .iter() + .find(|c| c.id == surf) + .unwrap(); + let BlockContent::Surface { elements, .. } = &surf_node.content else { + unreachable!() + }; + + let platform = HeadlessPlatform::new(64, 64, 1.0); + let app = Application::with_platform(platform).run_embedded(|cx| { + crate::register_bundled_fonts(cx).unwrap(); + }); + let hits: Vec<(&str, Option)> = app.update(|cx| { + let win = cx + .open_window(Default::default(), |_, cx| cx.new(|_| ui::Empty)) + .unwrap(); + let layout = win + .update(cx, |_, window, _| { + layout_surface( + elements, + &BTreeMap::::new(), + PlaygroundTheme::Light, + window, + ) + }) + .unwrap(); + let mut st = EdgelessAuthoringState::default(); + let mut items = Vec::new(); + for (idx, id) in layout.item_ids().enumerate() { + let el = elements.iter().find(|e| e.id == id).unwrap(); + let (kind, rect) = match &el.kind { + SurfaceElementKind::Shape(s) => ( + SpatialItemKind::Shape, + WorldRect::new( + s.xywh[0] as f32, + s.xywh[1] as f32, + s.xywh[2] as f32, + s.xywh[3] as f32, + ), + ), + SurfaceElementKind::Connector(_) => { + (SpatialItemKind::Connector, WorldRect::default()) + } + _ => continue, + }; + items.push(SpatialItemInfo { + id: id.to_string(), + kind, + surface_id: Some(surf.clone()), + rect, + rotate_deg: el.rotate as f32, + index: el.index.clone(), + scale: 1.0, + stroke_width: layout.item_stroke_width(idx), + polyline: layout.item_polyline(idx).to_vec(), + frame_children: Vec::new(), + title_pill_rect: None, + }); + } + st.painted_items = items.into(); + [ + ("connector_mid", (1066.0, 640.0)), + ("collect_shape", (893.0, 563.0)), + ("review_shape", (1066.0, 759.0)), + ("empty_canvas", (50.0, 50.0)), + ] + .into_iter() + .map(|(case, (wx, wy))| (case, st.hit_test_world(wx, wy, 1.0).map(|it| it.id.clone()))) + .collect() + }); + assert_eq!( + hits, + vec![ + ("connector_mid", Some("handoff".to_string())), + ("collect_shape", Some("collect".to_string())), + ("review_shape", Some("review".to_string())), + ("empty_canvas", None), + ] + ); + } +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/inline_edit.rs b/blocksuite/native-playground/crates/playground/src/edgeless/inline_edit.rs new file mode 100644 index 0000000000..b8b737842e --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/inline_edit.rs @@ -0,0 +1,609 @@ +//! Double-click inline rich-text & IME editing for Edgeless shapes, connectors, text, frames, and notes. + +use std::ops::Range; + +use blocksuite_playground_doc::read::{ + BlockContent, ConnectorMode, SurfaceConnector, SurfaceElementKind, TextAlign, +}; +use ui::{Bounds, Context, FontWeight, Pixels, Window, point, px, size}; +use y_octo::{TextDeltaOp, TextInsert}; + +use crate::{ + PlaygroundView, TOPBAR_HEIGHT, + editor_session::{DocPoint, DocumentSelection}, + rich_text::{RichParagraph, RichParagraphStyle}, + theme::ThemeMode, +}; + +use super::{ + EdgelessInlineEdit, EdgelessLabelEditor, LabelSplice, LabelTarget, NOTE_CARD_PADDING, + SpatialItemKind, WorldRect, find_block, find_surface_element, rotate_point_around, utf16_len, +}; + +/// Sample the routed connector polyline at `distance` (`0.0..=1.0`), matching +/// `surface::paint`'s `route.point_at_distance(mode, distance)`. +fn connector_label_anchor_point( + polyline: &[(f32, f32)], + fallback_center: (f32, f32), + mode: ConnectorMode, + distance: f64, +) -> (f64, f64) { + if polyline.len() < 2 { + return (fallback_center.0 as f64, fallback_center.1 as f64); + } + let d = distance.clamp(0.0, 1.0); + if mode == ConnectorMode::Curve { + let f = d * (polyline.len() - 1) as f64; + let i = (f.floor() as usize).min(polyline.len() - 2); + let t = f - i as f64; + let a = polyline[i]; + let b = polyline[i + 1]; + return ( + a.0 as f64 + (b.0 as f64 - a.0 as f64) * t, + a.1 as f64 + (b.1 as f64 - a.1 as f64) * t, + ); + } + let seg_len = |a: (f32, f32), b: (f32, f32)| ((b.0 - a.0) as f64).hypot((b.1 - a.1) as f64); + let total: f64 = polyline.windows(2).map(|w| seg_len(w[0], w[1])).sum(); + let mut rem = total * d; + for w in polyline.windows(2) { + let l = seg_len(w[0], w[1]); + if rem <= l && l > 0.0 { + let t = rem / l; + return ( + w[0].0 as f64 + (w[1].0 as f64 - w[0].0 as f64) * t, + w[0].1 as f64 + (w[1].1 as f64 - w[0].1 as f64) * t, + ); + } + rem -= l; + } + let last = *polyline.last().unwrap(); + (last.0 as f64, last.1 as f64) +} + +fn measure_connector_label_xywh( + c: &SurfaceConnector, + polyline: &[(f32, f32)], + fallback_center: (f32, f32), + trimmed: &str, + theme_mode: ThemeMode, + window: &Window, +) -> [f64; 4] { + let p = + connector_label_anchor_point(polyline, fallback_center, c.mode, c.label_offset.distance); + let l = &c.label_style; + let max_w = if c.label_constraints.has_max_width { + c.label_constraints.max_width as f32 + } else { + 1e6_f32 + }; + let mut style = RichParagraphStyle { + font_family: l + .font_family + .trim_start_matches("blocksuite:surface:") + .to_string() + .into(), + font_size: l.font_size as f32, + base_weight: FontWeight(l.font_weight.parse().unwrap_or(if l.font_weight == "bold" { + 700.0 + } else { + 400.0 + })), + align: match l.text_align { + TextAlign::Left => ui::TextAlign::Left, + TextAlign::Center => ui::TextAlign::Center, + TextAlign::Right => ui::TextAlign::Right, + }, + ..RichParagraphStyle::from_theme(theme_mode) + }; + let ts = window.text_system(); + let mut face = ui::font(style.font_family.clone()); + face.weight = style.base_weight; + let font_id = ts.resolve_font(&face); + let font_px = px(style.font_size); + let ascent = f32::from(ts.ascent(font_id, font_px)); + let descent = f32::from(ts.descent(font_id, font_px)).abs(); + style.line_height = ascent + descent; + style.baseline_offset = Some(ascent); + let delta = vec![TextDeltaOp::Insert { + insert: TextInsert::Text(trimmed.to_string()), + format: None, + }]; + let (w, h) = if let Ok(para) = RichParagraph::from_delta(delta) { + let laid = para.layout(ts, &style, max_w); + let measured_w = laid + .lines() + .iter() + .map(|line| f32::from(line.width)) + .fold(0.0_f32, f32::max) + .ceil() + .max(1.0) as f64; + let measured_h = f64::from(f32::from(laid.size().height)).max(1.0); + (measured_w, measured_h) + } else { + let fallback_w = (trimmed.chars().count() as f64 * 8.0 + 24.0).clamp(64.0, 260.0); + (fallback_w, 28.0) + }; + [p.0 - w * 0.5, p.1 - h * 0.5, w, h] +} + +impl PlaygroundView { + /// Apply a live UTF-16 splice on the active inline label editor directly into `PageDocSession` + /// and update its `RelativePosition` anchors so concurrent remote edits merge cleanly. + pub(crate) fn edgeless_label_edit( + &mut self, + window: &mut Window, + cx: &mut Context, + f: impl FnOnce(&mut EdgelessLabelEditor) -> Option, + ) -> Option<()> { + let (target, splice, sel_after) = { + let ed = self.edgeless.authoring.label_editor_mut()?; + let splice = f(ed); + (ed.target.clone(), splice, ed.selection.clone()) + }; + if let Some(splice) = splice { + let now_ms = self.now_ms(cx) as u64; + let commit = self + .page_mut() + .ok() + .and_then(|page| target.splice(page, splice, now_ms)); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } + self.edgeless_update_label_anchors(sel_after); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + Some(()) + } + + pub(crate) fn edgeless_update_label_anchors(&mut self, sel: Range) { + let Some((target, preedit_range)) = self.edgeless.authoring.label_editor().map(|ed| { + ( + ed.target.clone(), + ed.preedit.as_ref().map(|p| p.replacement.clone()), + ) + }) else { + return; + }; + let (anchors, preedit_anchors) = match self.page() { + Some(page) => { + let a = target + .encode_pos(page, sel.start) + .zip(target.encode_pos(page, sel.end)); + let pa = preedit_range.and_then(|r| { + target + .encode_pos(page, r.start) + .zip(target.encode_pos(page, r.end)) + }); + (a, pa) + } + None => (None, None), + }; + if let Some(ed) = self.edgeless.authoring.label_editor_mut() { + ed.anchors = anchors; + ed.preedit_anchors = preedit_anchors; + } + } + + /// Refresh an open `EdgelessLabelEditor` from the latest snapshot after a remote update, + /// resolving its `RelativePosition` selection and preedit anchors so the local caret and + /// active composition track remote insertions. + pub(crate) fn edgeless_refresh_label_editor_from_snapshot(&mut self) { + let Some((target, anchors, preedit_anchors)) = + self.edgeless.authoring.label_editor().map(|ed| { + ( + ed.target.clone(), + ed.anchors.clone(), + ed.preedit_anchors.clone(), + ) + }) + else { + return; + }; + let Some(snapshot) = self.snapshot.clone() else { + return; + }; + let latest = match &target { + LabelTarget::Shape { id, .. } + | LabelTarget::Connector { id, .. } + | LabelTarget::SurfaceText { id, .. } => { + find_surface_element(&snapshot, id).and_then(|(_, el)| match &el.kind { + SurfaceElementKind::Shape(s) => Some(s.text.plain.clone()), + SurfaceElementKind::Connector(c) => Some(c.text.plain.clone()), + SurfaceElementKind::Text(t) => Some(t.text.plain.clone()), + _ => None, + }) + } + LabelTarget::FrameTitle { id } => { + find_block(&snapshot, id).and_then(|n| match &n.content { + BlockContent::Frame { title, .. } => Some(title.plain.clone()), + _ => None, + }) + } + }; + let Some(latest_text) = latest else { + self.edgeless.authoring.inline_edit = None; + return; + }; + let resolve_pair = |pair: Option<(y_octo::RelativePosition, y_octo::RelativePosition)>| { + let (a, b) = pair?; + let page = self.page()?; + let s = target.resolve_pos(page, &a)?; + let e = target.resolve_pos(page, &b)?; + Some(s.min(e)..s.max(e)) + }; + let resolved_sel = resolve_pair(anchors); + let resolved_preedit = resolve_pair(preedit_anchors); + if let Some(ed) = self.edgeless.authoring.label_editor_mut() { + ed.text = latest_text; + let len = utf16_len(&ed.text); + ed.selection = match resolved_sel { + Some(r) => r.start.min(len)..r.end.min(len), + None => ed.selection.start.min(len)..ed.selection.end.min(len), + }; + if let Some(pre) = &mut ed.preedit { + pre.replacement = match resolved_preedit { + Some(r) => r.start.min(len)..r.end.min(len), + None => pre.replacement.start.min(len)..pre.replacement.end.min(len), + }; + } + } + } + + /// Flush and commit an active inline label edit to `PageDocSession`, returning `true` if one was active. + pub(crate) fn edgeless_flush_label_edit( + &mut self, + window: &Window, + cx: &mut Context, + ) -> bool { + let Some(EdgelessInlineEdit::Label(mut ed)) = self.edgeless.authoring.inline_edit.take() + else { + return false; + }; + let now_ms = self.now_ms(cx) as u64; + if let Some(splice) = ed.unmark() { + let commit = self + .page_mut() + .ok() + .and_then(|page| ed.target.splice(page, splice, now_ms)); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } + + if ed.created_new_text && ed.text.trim().is_empty() { + if let LabelTarget::SurfaceText { surface_id, id } = &ed.target { + let sid = surface_id.clone(); + let eid = id.clone(); + self.edgeless.authoring.selection.remove(&eid); + let commit = self.page_mut().ok().and_then(|page| { + page.structural_edit(now_ms, move |page| { + page.remove_surface_element(&sid, &eid, now_ms)?; + Ok(()) + }) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } + } else if let LabelTarget::Connector { surface_id, id } = &ed.target + && ed.dirty + { + let trimmed = ed.text.trim(); + let label_xywh = if trimmed.is_empty() { + [0.0; 4] + } else { + let polyline: Vec<(f32, f32)> = self + .edgeless + .authoring + .painted_items + .iter() + .find(|i| i.id == *id) + .map(|i| i.polyline.clone()) + .unwrap_or_default(); + if let Some((_, el)) = self + .snapshot + .as_deref() + .and_then(|snap| find_surface_element(snap, id)) + && let SurfaceElementKind::Connector(c) = &el.kind + { + measure_connector_label_xywh( + c, + &polyline, + ed.world_rect.center(), + trimmed, + self.theme.mode(), + window, + ) + } else { + let (cx_w, cy_w) = ed.world_rect.center(); + let lw = (trimmed.chars().count() as f64 * 8.0 + 24.0).clamp(64.0, 260.0); + let lh = 28.0; + [cx_w as f64 - lw * 0.5, cy_w as f64 - lh * 0.5, lw, lh] + } + }; + let commit = self.page_mut().ok().and_then(|page| { + page.commit_connector_label(surface_id, id, trimmed, label_xywh, now_ms) + .ok() + .flatten() + }); + if let Some(commit) = commit { + self.did_edgeless_doc_commit(commit, cx); + } + } + + if let Ok(page) = self.page_mut() { + let _ = page.stop_capturing(); + } + true + } + + /// Commit and exit any active Edgeless inline edit (label or spatial block). + pub fn edgeless_commit_inline_edit(&mut self, window: &mut Window, cx: &mut Context) { + if matches!( + self.edgeless.authoring.inline_edit, + Some(EdgelessInlineEdit::Label(_)) + ) { + self.edgeless_flush_label_edit(window, cx); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + return; + } + let Some(EdgelessInlineEdit::SpatialBlock { .. }) = + self.edgeless.authoring.inline_edit.take() + else { + return; + }; + self.clear_composition(window, cx); + self.editor.selection = None; + self.announce_selection(cx); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + } + + /// Open inline editing on an Edgeless item (Note, EdgelessText, Shape, Connector, SurfaceText, or Frame). + pub fn edgeless_begin_inline_edit( + &mut self, + item_id: &str, + window: &mut Window, + cx: &mut Context, + ) -> bool { + self.edgeless_commit_inline_edit(window, cx); + let Some(snapshot) = self.snapshot.clone() else { + return false; + }; + let Some(info) = self + .edgeless + .authoring + .painted_items + .iter() + .find(|i| i.id == item_id) + .cloned() + else { + return false; + }; + match info.kind { + SpatialItemKind::Note | SpatialItemKind::EdgelessText => { + let is_note = info.kind == SpatialItemKind::Note; + let first_text_id = find_block(&snapshot, item_id).and_then(|node| { + node.walk() + .find(|n| { + matches!( + n.content, + BlockContent::Paragraph { .. } + | BlockContent::List { .. } + | BlockContent::Code { .. } + ) + }) + .map(|n| n.id.clone()) + }); + self.edgeless.authoring.selection.clear(); + self.edgeless + .authoring + .selection + .insert(item_id.to_string()); + self.edgeless.authoring.inline_edit = Some(EdgelessInlineEdit::SpatialBlock { + block_id: item_id.to_string(), + is_note, + }); + if let Some(tid) = first_text_id { + let pt = DocPoint::new(&tid, 0); + self.editor.selection = Some(DocumentSelection { + anchor: pt.clone(), + focus: pt, + }); + } + self.editor_focus.focus(window, cx); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + true + } + SpatialItemKind::Shape | SpatialItemKind::Connector | SpatialItemKind::SurfaceText => { + let Some((surface_id, el)) = find_surface_element(&snapshot, item_id) else { + return false; + }; + let (target, initial, multiline, edit_rect) = match &el.kind { + SurfaceElementKind::Shape(s) => ( + LabelTarget::Shape { + surface_id: surface_id.to_string(), + id: el.id.clone(), + }, + s.text.plain.clone(), + true, + info.rect, + ), + SurfaceElementKind::Connector(c) => { + let p = connector_label_anchor_point( + &info.polyline, + info.rect.center(), + c.mode, + c.label_offset.distance, + ); + ( + LabelTarget::Connector { + surface_id: surface_id.to_string(), + id: el.id.clone(), + }, + c.text.plain.clone(), + false, + WorldRect::new(p.0 as f32 - 80.0, p.1 as f32 - 18.0, 160.0, 36.0), + ) + } + SurfaceElementKind::Text(t) => ( + LabelTarget::SurfaceText { + surface_id: surface_id.to_string(), + id: el.id.clone(), + }, + t.text.plain.clone(), + true, + info.rect, + ), + _ => return false, + }; + let len = utf16_len(&initial); + self.edgeless.authoring.selection.clear(); + self.edgeless + .authoring + .selection + .insert(item_id.to_string()); + self.edgeless.authoring.inline_edit = + Some(EdgelessInlineEdit::Label(EdgelessLabelEditor::new( + target, + initial, + edit_rect, + info.rotate_deg, + multiline, + ))); + if let Ok(page) = self.page_mut() { + let _ = page.stop_capturing(); + } + self.edgeless_update_label_anchors(len..len); + self.editor_focus.focus(window, cx); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + true + } + SpatialItemKind::Frame => { + let initial = find_block(&snapshot, item_id) + .and_then(|n| match &n.content { + BlockContent::Frame { title, .. } => Some(title.plain.clone()), + _ => None, + }) + .unwrap_or_default(); + let len = utf16_len(&initial); + let rect = info.title_pill_rect.unwrap_or_else(|| { + WorldRect::new(info.rect.x, info.rect.y - 28.0, 140.0, 24.0) + }); + self.edgeless.authoring.selection.clear(); + self.edgeless + .authoring + .selection + .insert(item_id.to_string()); + self.edgeless.authoring.inline_edit = + Some(EdgelessInlineEdit::Label(EdgelessLabelEditor::new( + LabelTarget::FrameTitle { + id: item_id.to_string(), + }, + initial, + rect, + 0.0, + false, + ))); + if let Ok(page) = self.page_mut() { + let _ = page.stop_capturing(); + } + self.edgeless_update_label_anchors(len..len); + self.editor_focus.focus(window, cx); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + true + } + _ => false, + } + } + + pub(crate) fn edgeless_label_input( + &mut self, + window: &mut Window, + cx: &mut Context, + f: impl FnOnce(&mut EdgelessLabelEditor) -> R, + ) -> Option { + let (out, sel) = { + let ed = self.edgeless.authoring.label_editor_mut()?; + let out = f(ed); + (out, ed.selection.clone()) + }; + self.edgeless_update_label_anchors(sel); + window.notify_text_input_changed(&self.editor_focus); + cx.notify(); + Some(out) + } + + pub(crate) fn edgeless_label_screen_bounds(&self) -> Option> { + let ed = self.edgeless.authoring.label_editor()?; + let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT)); + let vp_w = self.window_size.0.max(1.0); + let vp_h = (self.window_size.1 - TOPBAR_HEIGHT).max(1.0); + let cam = self.edgeless.camera; + let tl = cam.world_to_screen(point(px(ed.world_rect.x), px(ed.world_rect.y)), vp_origin); + let br = cam.world_to_screen( + point(px(ed.world_rect.right()), px(ed.world_rect.bottom())), + vp_origin, + ); + let w = (f32::from(br.x) - f32::from(tl.x)) + .max(120.0) + .min(vp_w - 16.0); + let h = (f32::from(br.y) - f32::from(tl.y)) + .max(32.0) + .min(vp_h - 16.0); + let x = f32::from(tl.x).clamp(8.0, (vp_w - w - 8.0).max(8.0)); + let y = + (f32::from(tl.y) - TOPBAR_HEIGHT).clamp(8.0, (vp_h - h - 8.0).max(8.0)) + TOPBAR_HEIGHT; + Some(Bounds::new(point(px(x), px(y)), size(px(w), px(h)))) + } + + /// Map a local caret `FlowRect` inside an actively edited Edgeless Note or EdgelessText + /// to screen-space `Bounds` for macOS IME candidates & Web `ImeMirror`. + pub(crate) fn edgeless_spatial_block_caret_bounds( + &self, + block_id: &str, + offset: u64, + ) -> Option> { + let (editing_id, is_note) = self.edgeless.authoring.editing_spatial_block()?; + let info = self + .edgeless + .authoring + .painted_items + .iter() + .find(|i| i.id == editing_id)?; + let caret = self + .edgeless + .cached_block_layout(editing_id, is_note)? + .block(block_id)? + .caret_rect(DocPoint::new(block_id, offset).caret)?; + let pad = if is_note { NOTE_CARD_PADDING } else { 0.0 }; + let (cx_w, cy_w) = info.rect.center(); + let (rx, ry) = rotate_point_around( + info.rect.x + (pad + caret.x) * info.scale, + info.rect.y + (pad + caret.y) * info.scale, + cx_w, + cy_w, + info.rotate_deg, + ); + let tl = self + .edgeless + .camera + .world_to_screen(point(px(rx), px(ry)), point(px(0.0), px(TOPBAR_HEIGHT))); + let z = self.edgeless.camera.zoom; + Some(Bounds::new( + tl, + size( + px((caret.w * info.scale * z).max(2.0)), + px((caret.h * info.scale * z).max(16.0)), + ), + )) + } +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/label_editor.rs b/blocksuite/native-playground/crates/playground/src/edgeless/label_editor.rs new file mode 100644 index 0000000000..a267ba624e --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/label_editor.rs @@ -0,0 +1,424 @@ +//! Pure UTF-16 + IME inline label editor state for Edgeless shapes, connectors, text, and frames. + +use std::ops::Range; + +use blocksuite_playground_doc::session::{PageDocSession, SelectionSnapshot}; +use y_octo::{RelativePosition, SessionCommit}; + +use super::WorldRect; + +/// Result of a text-mutating operation on [`EdgelessLabelEditor`]: `(utf16_start, utf16_delete_len, insert)`. +pub type LabelSplice = (usize, usize, String); + +/// Target of an inline UTF-16 + IME label editor on the Edgeless canvas. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LabelTarget { + Shape { surface_id: String, id: String }, + Connector { surface_id: String, id: String }, + SurfaceText { surface_id: String, id: String }, + FrameTitle { id: String }, +} + +impl LabelTarget { + pub fn item_id(&self) -> &str { + match self { + Self::Shape { id, .. } + | Self::Connector { id, .. } + | Self::SurfaceText { id, .. } + | Self::FrameTitle { id } => id, + } + } + + pub(super) fn splice( + &self, + page: &mut PageDocSession, + (start, del_len, insert): LabelSplice, + now_ms: u64, + ) -> Option> { + match self { + Self::Shape { surface_id, id } + | Self::Connector { surface_id, id } + | Self::SurfaceText { surface_id, id } => page + .splice_surface_element_text( + surface_id, + id, + "text", + start as u64, + del_len as u64, + &insert, + now_ms, + ) + .ok() + .flatten(), + Self::FrameTitle { id } => page + .splice_block_title_text(id, start as u64, del_len as u64, &insert, now_ms) + .ok() + .flatten(), + } + } + + pub(super) fn encode_pos( + &self, + page: &PageDocSession, + offset: usize, + ) -> Option { + match self { + Self::Shape { surface_id, id } + | Self::Connector { surface_id, id } + | Self::SurfaceText { surface_id, id } => page + .encode_surface_text_relative_position(surface_id, id, "text", offset as u64) + .ok() + .flatten(), + Self::FrameTitle { id } => page + .encode_block_title_relative_position(id, offset as u64) + .ok() + .flatten(), + } + } + + pub(super) fn resolve_pos( + &self, + page: &PageDocSession, + pos: &RelativePosition, + ) -> Option { + let off = match self { + Self::Shape { surface_id, id } + | Self::Connector { surface_id, id } + | Self::SurfaceText { surface_id, id } => page + .resolve_surface_text_relative_position(surface_id, id, "text", pos) + .ok() + .flatten()?, + Self::FrameTitle { id } => page + .resolve_block_title_relative_position(id, pos) + .ok() + .flatten()?, + }; + Some(off as usize) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LabelPreedit { + pub replacement: Range, + pub text: String, + pub selected: Range, +} + +/// Inline UTF-16 + IME editor for Shape, Connector, SurfaceText, and Frame title labels. +#[derive(Clone, Debug)] +pub struct EdgelessLabelEditor { + pub(super) target: LabelTarget, + pub text: String, + pub original_text: String, + pub selection: Range, + pub reversed: bool, + pub(super) preedit: Option, + pub world_rect: WorldRect, + pub rotate_deg: f32, + pub multiline: bool, + pub created_new_text: bool, + pub dirty: bool, + pub(super) anchors: Option<(RelativePosition, RelativePosition)>, + pub(super) preedit_anchors: Option<(RelativePosition, RelativePosition)>, +} + +pub(super) fn utf16_len(s: &str) -> usize { + s.encode_utf16().count() +} + +pub(super) fn utf16_to_byte(s: &str, target: usize) -> usize { + let mut u16_pos = 0; + for (byte_idx, ch) in s.char_indices() { + if u16_pos >= target { + return byte_idx; + } + u16_pos += ch.len_utf16(); + } + s.len() +} + +impl EdgelessLabelEditor { + pub fn new( + target: LabelTarget, + initial: String, + world_rect: WorldRect, + rotate_deg: f32, + multiline: bool, + ) -> Self { + let len = utf16_len(&initial); + Self { + target, + original_text: initial.clone(), + text: initial, + selection: len..len, + reversed: false, + preedit: None, + world_rect, + rotate_deg, + multiline, + created_new_text: false, + dirty: false, + anchors: None, + preedit_anchors: None, + } + } + + pub fn composing(&self) -> bool { + self.preedit.is_some() + } + + pub fn display_text(&self) -> String { + let Some(pre) = &self.preedit else { + return self.text.clone(); + }; + let start = utf16_to_byte(&self.text, pre.replacement.start); + let end = utf16_to_byte(&self.text, pre.replacement.end); + let mut out = String::with_capacity(self.text.len() + pre.text.len()); + out.push_str(&self.text[..start]); + out.push_str(&pre.text); + out.push_str(&self.text[end..]); + out + } + + pub fn shown_selection(&self) -> (Range, bool) { + if let Some(pre) = &self.preedit { + let base = pre.replacement.start; + return (base + pre.selected.start..base + pre.selected.end, false); + } + (self.selection.clone(), self.reversed) + } + + pub fn marked_range(&self) -> Option> { + let pre = self.preedit.as_ref()?; + let start = pre.replacement.start; + Some(start..start + utf16_len(&pre.text)) + } + + pub fn text_for_range(&self, range: Range) -> (String, Range) { + let text = self.display_text(); + let start = utf16_to_byte(&text, range.start); + let end = utf16_to_byte(&text, range.end).max(start); + let covered = utf16_len(&text[..start])..utf16_len(&text[..end]); + (text[start..end].to_string(), covered) + } + + fn clamped(&self, range: Range) -> Range { + let at = |offset: usize| utf16_len(&self.text[..utf16_to_byte(&self.text, offset)]); + let a = at(range.start.min(range.end)); + let b = at(range.start.max(range.end)); + a..b + } + + pub fn cancel_preedit(&mut self) { + self.preedit = None; + self.preedit_anchors = None; + } + + pub fn replace(&mut self, range: Option>, text: &str) -> Option { + if self.preedit.is_some() && text.is_empty() { + self.cancel_preedit(); + return None; + } + self.preedit_anchors = None; + let target = match self.preedit.take() { + Some(pre) => pre.replacement, + None => range.map_or(self.selection.clone(), |r| self.clamped(r)), + }; + let cleaned: String = if self.multiline { + text.chars() + .filter(|ch| !ch.is_control() || *ch == '\n') + .collect() + } else { + text.chars().filter(|ch| !ch.is_control()).collect() + }; + let start = utf16_to_byte(&self.text, target.start); + let end = utf16_to_byte(&self.text, target.end); + self.text.replace_range(start..end, &cleaned); + let caret = target.start + utf16_len(&cleaned); + self.selection = caret..caret; + self.reversed = false; + let del_len = target.end.saturating_sub(target.start); + if del_len == 0 && cleaned.is_empty() { + None + } else { + self.dirty = true; + Some((target.start, del_len, cleaned)) + } + } + + pub fn mark( + &mut self, + range: Option>, + text: &str, + selected: Option>, + ) { + if text.is_empty() { + self.preedit = None; + self.preedit_anchors = None; + return; + } + let replacement = match &self.preedit { + Some(pre) => pre.replacement.clone(), + None => range.map_or(self.selection.clone(), |r| self.clamped(r)), + }; + let cleaned: String = text.chars().filter(|ch| !ch.is_control()).collect(); + let len = utf16_len(&cleaned); + let selected = selected.unwrap_or(len..len); + self.preedit = Some(LabelPreedit { + replacement, + text: cleaned, + selected: selected.start.min(len)..selected.end.min(len), + }); + } + + pub fn unmark(&mut self) -> Option { + if let Some(pre) = &self.preedit { + let text = pre.text.clone(); + self.replace(None, &text) + } else { + None + } + } + + pub fn select(&mut self, range: Range) { + self.preedit = None; + self.preedit_anchors = None; + self.selection = self.clamped(range); + self.reversed = false; + } + + pub fn delete_backward(&mut self) -> Option { + self.preedit = None; + self.preedit_anchors = None; + if self.selection.start != self.selection.end { + return self.replace(None, ""); + } + let pos = self.selection.start; + if pos == 0 { + return None; + } + let byte_end = utf16_to_byte(&self.text, pos); + let prev_char = self.text[..byte_end].chars().next_back(); + let byte_start = prev_char.map_or(0, |c| byte_end - c.len_utf8()); + let new_pos = utf16_len(&self.text[..byte_start]); + let del_len = pos.saturating_sub(new_pos); + self.text.replace_range(byte_start..byte_end, ""); + self.selection = new_pos..new_pos; + self.reversed = false; + self.dirty = true; + Some((new_pos, del_len, String::new())) + } + + pub fn delete_forward(&mut self) -> Option { + self.preedit = None; + self.preedit_anchors = None; + if self.selection.start != self.selection.end { + return self.replace(None, ""); + } + let pos = self.selection.start; + let byte_start = utf16_to_byte(&self.text, pos); + if byte_start >= self.text.len() { + return None; + } + let next_char = self.text[byte_start..].chars().next(); + let byte_end = next_char.map_or(self.text.len(), |c| byte_start + c.len_utf8()); + let del_len = next_char.map_or(0, char::len_utf16); + self.text.replace_range(byte_start..byte_end, ""); + self.dirty = true; + Some((pos, del_len, String::new())) + } + + pub fn move_caret(&mut self, left: bool, extend: bool) { + self.preedit = None; + self.preedit_anchors = None; + let focus = if self.reversed { + self.selection.start + } else { + self.selection.end + }; + let anchor = if self.reversed { + self.selection.end + } else { + self.selection.start + }; + let next = if left { + let b = utf16_to_byte(&self.text, focus); + let nb = self.text[..b] + .chars() + .next_back() + .map_or(0, |c| b - c.len_utf8()); + utf16_len(&self.text[..nb]) + } else { + let b = utf16_to_byte(&self.text, focus); + let nb = self.text[b..] + .chars() + .next() + .map_or(self.text.len(), |c| b + c.len_utf8()); + utf16_len(&self.text[..nb]) + }; + if extend { + self.selection = anchor.min(next)..anchor.max(next); + self.reversed = next < anchor; + } else { + self.selection = next..next; + self.reversed = false; + } + } + + pub fn select_all(&mut self) { + self.preedit = None; + self.preedit_anchors = None; + let len = utf16_len(&self.text); + self.selection = 0..len; + self.reversed = false; + } + + pub fn selected_text(&self) -> &str { + let s = utf16_to_byte(&self.text, self.selection.start); + let e = utf16_to_byte(&self.text, self.selection.end); + &self.text[s..e] + } +} + +/// Active inline editing session on the Edgeless canvas. +#[derive(Clone, Debug)] +pub enum EdgelessInlineEdit { + /// Live rich-text `EditorSession` editing inside a Note or EdgelessText block. + SpatialBlock { block_id: String, is_note: bool }, + /// Inline UTF-16 + IME editing on a Shape, Connector, SurfaceText, or Frame title. + Label(EdgelessLabelEditor), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn label_editor_ime_preedit_cancel_and_commit() { + let mut ed = EdgelessLabelEditor::new( + LabelTarget::Shape { + surface_id: "surf".into(), + id: "s1".into(), + }, + "hello".into(), + WorldRect::new(0.0, 0.0, 160.0, 80.0), + 0.0, + true, + ); + ed.select(1..4); + assert_eq!(ed.selected_text(), "ell"); + ed.mark(None, "nihao", None); + assert!(ed.composing()); + assert_eq!(ed.display_text(), "hnihaoo"); + // Empty replace during preedit cancels and restores original selection. + ed.replace(None, ""); + assert!(!ed.composing()); + assert_eq!(ed.display_text(), "hello"); + assert_eq!(ed.selected_text(), "ell"); + // Commit replaces selection. + ed.mark(None, "你好", None); + ed.unmark(); + assert!(!ed.composing()); + assert_eq!(ed.display_text(), "h你好o"); + } +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/mod.rs b/blocksuite/native-playground/crates/playground/src/edgeless/mod.rs new file mode 100644 index 0000000000..e2c9a2cdf1 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/mod.rs @@ -0,0 +1,43 @@ +//! Edgeless spatial whiteboard subsystem: camera, paint ordering, canvas rendering, +//! interactive authoring toolbar, hit-testing, overlays, inline IME editing, and gestures. + +mod camera; +mod canvas; +mod canvas_paint; +mod commands; +mod commit; +mod gestures; +mod hit_test; +mod inline_edit; +mod label_editor; +mod order; +mod overlay; +mod scene; +mod toolbar; + +pub use camera::{EdgelessCamera, WorldRect, bg_grid_gap, parse_xywh}; +pub use canvas::{ + EDGELESS_VIEWPORT_ID, EdgelessCanvasState, EdgelessRenderInput, NOTE_CARD_PADDING, + resolve_edgeless_color, +}; +pub use canvas_paint::build_edgeless_layer; +pub use hit_test::EdgelessAuthoringState; +pub use label_editor::{EdgelessInlineEdit, EdgelessLabelEditor}; +pub use toolbar::{EdgelessTool, build_edgeless_toolbar, build_zoom_controls}; + +use canvas::{ + CachedNoteFlow, CachedSurfaces, FRAME_RADIUS, FRAME_TITLE_GAP, FRAME_TITLE_HEIGHT, + PaintEdgelessText, PaintFrame, PaintNote, ZOOM_BAR_MARGIN, ZOOM_BAR_PAD, ZOOM_BAR_RADIUS, + ZOOM_BTN_HEIGHT, ZOOM_BTN_RADIUS, note_border_radius, note_border_style, note_collapse, + note_scale, note_shadow_type, prop_bool, prop_f32, rotated_bounds, spatial_blocks, + world_bounds, world_rect, +}; +use commands::{collect_frame_children, find_block, find_surface_element, max_spatial_index}; +use hit_test::{ + DragItemInitial, EdgelessGesture, HandleKind, SpatialItemInfo, SpatialItemKind, + normalized_rect, point_in_rotated_rect, resized_rect, rotate_point_around, +}; +use label_editor::{LabelSplice, LabelTarget, utf16_len, utf16_to_byte}; +use order::{Layers, PaintItem}; +use overlay::{build_edgeless_authoring_overlay, layout_label_editor_paragraph}; +use scene::{PreparedEdgelessScene, prepare_edgeless_scene}; diff --git a/blocksuite/native-playground/crates/playground/src/edgeless_order.rs b/blocksuite/native-playground/crates/playground/src/edgeless/order.rs similarity index 82% rename from blocksuite/native-playground/crates/playground/src/edgeless_order.rs rename to blocksuite/native-playground/crates/playground/src/edgeless/order.rs index e884e66659..4f68b0ee09 100644 --- a/blocksuite/native-playground/crates/playground/src/edgeless_order.rs +++ b/blocksuite/native-playground/crates/playground/src/edgeless/order.rs @@ -33,10 +33,8 @@ impl<'a> Layers<'a> { .get("prop:childElementIds") .and_then(|v| v.as_object()) { - for (child, present) in children { - if present.as_bool() == Some(true) { - layers.set_parent(child, &node.id); - } + for child in children.keys() { + layers.set_parent(child, &node.id); } } } @@ -75,7 +73,6 @@ impl<'a> Layers<'a> { items: impl IntoIterator, ) -> Vec { struct Entry<'a> { - id: &'a str, item: PaintItem, path: Vec<&'a str>, } @@ -89,7 +86,7 @@ impl<'a> Layers<'a> { node = parent; } path.reverse(); - Entry { id, item, path } + Entry { item, path } }) .partition(|e| matches!(e.item, PaintItem::Surface(..))); let compare = |a: &Entry<'_>, b: &Entry<'_>| { @@ -106,7 +103,7 @@ impl<'a> Layers<'a> { a.path.len().cmp(&b.path.len()) }; for stream in [&mut canvas, &mut blocks] { - stream.sort_by(|a, b| compare(a, b).then_with(|| a.id.cmp(b.id))); + stream.sort_by(|a, b| compare(a, b)); } let mut output = Vec::with_capacity(canvas.len() + blocks.len()); let (mut blocks, mut canvas) = @@ -158,7 +155,7 @@ mod tests { "prop:childElementIds", SessionValue::Map(vec![ ("member".into(), SessionValue::Any(Any::True)), - ("unrelated".into(), SessionValue::Any(Any::False)), + ("false_member".into(), SessionValue::Any(Any::False)), ]), ), ] { @@ -166,17 +163,26 @@ mod tests { } let snapshot = page.read_page_snapshot().unwrap(); let mut layers = Layers::from_root(snapshot.root.as_ref().unwrap()); - layers - .indices - .extend([("member", "a0"), ("earlier", "a1"), ("unrelated", "a5")]); - let (frame, member, earlier, unrelated) = ( + layers.indices.extend([ + ("member", "a0"), + ("false_member", "a0"), + ("earlier", "a1"), + ("unrelated", "a5"), + ]); + let (frame, member, false_member, earlier, unrelated) = ( PaintItem::Frame(0), PaintItem::Surface(0, 0), PaintItem::Surface(0, 1), PaintItem::Surface(0, 2), + PaintItem::Surface(0, 3), ); - let order = layers.merge([("earlier", earlier), ("frame", frame), ("member", member)]); - assert_eq!(order, [earlier, frame, member]); + let order = layers.merge([ + ("earlier", earlier), + ("frame", frame), + ("member", member), + ("false_member", false_member), + ]); + assert_eq!(order, [earlier, frame, member, false_member]); let order = layers.merge([ ("earlier", earlier), ("frame", frame), @@ -184,4 +190,13 @@ mod tests { ]); assert_eq!(order, [earlier, unrelated, frame]); } + + #[test] + fn equal_indices_preserve_source_order_within_each_stream() { + let mut layers = Layers::default(); + layers.indices.extend([("z", "a1"), ("a", "a1")]); + let (z, a) = (PaintItem::Surface(0, 0), PaintItem::Surface(0, 1)); + assert_eq!(layers.merge([("z", z), ("a", a)]), [z, a]); + assert_eq!(layers.merge([("a", a), ("z", z)]), [a, z]); + } } diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/overlay.rs b/blocksuite/native-playground/crates/playground/src/edgeless/overlay.rs new file mode 100644 index 0000000000..45645df70c --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/overlay.rs @@ -0,0 +1,558 @@ +//! Screen-space selection frame, handles, marquee, live creation previews, and inline label editor overlay. + +use std::collections::BTreeMap; + +use ui::{ + AnyElement, BorderStyle, Bounds, Corners, Edges, Hsla, PathBuilder, Pixels, Point, canvas, div, + point, prelude::*, px, size, +}; +use y_octo::{Any, TextDeltaOp, TextInsert}; + +use crate::{ + rich_text::{CaretPosition, RichParagraph, RichParagraphStyle, WrapAffinity}, + theme::{FONT_SANS, Palette, PlaygroundTheme}, +}; + +use super::{ + EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera, EdgelessGesture, + EdgelessLabelEditor, HandleKind, normalized_rect, rotate_point_around, utf16_to_byte, +}; + +/// Screen-space selection frame, 8 resize handles, rotation handle, Edgeless `2×3` `gfx` drag handle, +/// marquee box, live creation previews, and inline label editor overlay. +pub fn build_edgeless_authoring_overlay( + authoring: &EdgelessAuthoringState, + camera: EdgelessCamera, + viewport_width: f32, + viewport_height: f32, + palette: &Palette, + theme: PlaygroundTheme, +) -> Vec { + let mut elements = Vec::new(); + let vp_origin = point(px(0.0), px(0.0)); + let brand = palette.brand; + let white = Hsla::white(); + + // 1. Selection box + 8 resize handles + rotation handle + Edgeless gfx 2x3 drag handle. + if let Some(sel_box) = authoring.selection_world_box() { + let tl = camera.world_to_screen(point(px(sel_box.x), px(sel_box.y)), vp_origin); + let br = + camera.world_to_screen(point(px(sel_box.right()), px(sel_box.bottom())), vp_origin); + let x0 = f32::from(tl.x); + let y0 = f32::from(tl.y); + let x1 = f32::from(br.x); + let y1 = f32::from(br.y); + let w = (x1 - x0).max(2.0); + let h = (y1 - y0).max(2.0); + + let mx = (x0 + x1) * 0.5; + let my = (y0 + y1) * 0.5; + let live_overrides = authoring.live_overrides(); + let single_rotatable = authoring + .single_selected() + .filter(|s| s.kind.is_rotatable()); + let rot_deg = single_rotatable + .map(|s| { + live_overrides + .get(&s.id) + .and_then(|o| o.rotate_deg) + .unwrap_or(s.rotate_deg) + }) + .filter(|r| r.abs() > 1e-3) + .unwrap_or(0.0); + + let visible_box = + x0 >= 0.0 && y0 >= 0.0 && x0 + w <= viewport_width && y0 + h <= viewport_height; + if rot_deg.abs() > 1e-3 { + let c0 = rotate_point_around(x0, y0, mx, my, rot_deg); + let c1 = rotate_point_around(x1, y0, mx, my, rot_deg); + let c2 = rotate_point_around(x1, y1, mx, my, rot_deg); + let c3 = rotate_point_around(x0, y1, mx, my, rot_deg); + elements.push( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let ox = f32::from(bounds.origin.x); + let oy = f32::from(bounds.origin.y); + let mut pb = PathBuilder::stroke(px(2.0)); + pb.move_to(point(px(ox + c0.0), px(oy + c0.1))); + pb.line_to(point(px(ox + c1.0), px(oy + c1.1))); + pb.line_to(point(px(ox + c2.0), px(oy + c2.1))); + pb.line_to(point(px(ox + c3.0), px(oy + c3.1))); + pb.line_to(point(px(ox + c0.0), px(oy + c0.1))); + if let Ok(path) = pb.build() { + window.paint_path(path, brand); + } + }, + ) + .absolute() + .inset_0() + .into_any_element(), + ); + if visible_box { + elements.push( + div() + .absolute() + .left(px(x0)) + .top(px(y0)) + .w(px(w)) + .h(px(h)) + .snapshot("edgeless.selection_box", Some(EDGELESS_VIEWPORT_ID)) + .into_any_element(), + ); + } + } else { + let mut box_el = div() + .absolute() + .left(px(x0)) + .top(px(y0)) + .w(px(w)) + .h(px(h)) + .border_color(brand) + .border_2(); + if visible_box { + box_el = box_el.snapshot("edgeless.selection_box", Some(EDGELESS_VIEWPORT_ID)); + } + elements.push(box_el.into_any_element()); + } + + if authoring.inline_edit.is_none() { + if authoring.selection_has_non_connector() { + let handle_coords = [ + (HandleKind::NW, x0, y0), + (HandleKind::N, mx, y0), + (HandleKind::NE, x1, y0), + (HandleKind::E, x1, my), + (HandleKind::SE, x1, y1), + (HandleKind::S, mx, y1), + (HandleKind::SW, x0, y1), + (HandleKind::W, x0, my), + ]; + for (kind, hx, hy) in handle_coords { + let (hx, hy) = rotate_point_around(hx, hy, mx, my, rot_deg); + let lx = (hx - 4.0).round(); + let ty = (hy - 4.0).round(); + let mut h_el = div() + .absolute() + .left(px(lx)) + .top(px(ty)) + .w(px(8.0)) + .h(px(8.0)) + .rounded(px(2.0)) + .bg(white) + .border_1() + .border_color(brand); + if lx >= 0.0 + && ty >= 0.0 + && lx + 8.0 <= viewport_width + && ty + 8.0 <= viewport_height + { + h_el = h_el.snapshot(kind.snapshot_id(), Some(EDGELESS_VIEWPORT_ID)); + } + elements.push(h_el.into_any_element()); + } + } + + // Top rotation handle for rotatable items (Shape / EdgelessText). + if single_rotatable.is_some() { + let stem_a = rotate_point_around(mx, y0, mx, my, rot_deg); + let stem_b = rotate_point_around(mx, y0 - 20.0, mx, my, rot_deg); + let knob_c = rotate_point_around(mx, y0 - 24.0, mx, my, rot_deg); + let rx = (knob_c.0 - 5.0).round(); + let ry = (knob_c.1 - 5.0).round(); + // Connector stem from top-center to rotate knob. + elements.push( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let ox = f32::from(bounds.origin.x); + let oy = f32::from(bounds.origin.y); + let mut pb = PathBuilder::stroke(px(1.5)); + pb.move_to(point(px(ox + stem_a.0), px(oy + stem_a.1))); + pb.line_to(point(px(ox + stem_b.0), px(oy + stem_b.1))); + if let Ok(path) = pb.build() { + window.paint_path(path, brand); + } + }, + ) + .absolute() + .inset_0() + .into_any_element(), + ); + let mut r_el = div() + .absolute() + .left(px(rx)) + .top(px(ry)) + .w(px(10.0)) + .h(px(10.0)) + .rounded(px(5.0)) + .bg(white) + .border_1() + .border_color(brand); + if rx >= 0.0 + && ry >= 0.0 + && rx + 10.0 <= viewport_width + && ry + 10.0 <= viewport_height + { + r_el = + r_el.snapshot(HandleKind::Rotate.snapshot_id(), Some(EDGELESS_VIEWPORT_ID)); + } + elements.push(r_el.into_any_element()); + } + } + + // 2x3 6-dot 14px Edgeless gfx drag handle for Note / Frame / EdgelessText. + if let Some(single) = authoring.single_selected() + && single.kind.has_gfx_drag_handle() + { + let hx = (x0 - 20.0) + .clamp(4.0, (viewport_width - 18.0).max(4.0)) + .round(); + let hy = y0.clamp(4.0, (viewport_height - 28.0).max(4.0)).round(); + let dots_color = theme + .css_var("--affine-v2-icon-secondary") + .unwrap_or(palette.icon); + let pill_bg = theme + .css_var("--affine-v2-layer-background-hoverOverlay") + .unwrap_or(palette.hover); + let mut dh = div() + .absolute() + .left(px(hx)) + .top(px(hy)) + .w(px(14.0)) + .h(px(24.0)) + .rounded(px(4.0)) + .bg(pill_bg) + .flex() + .items_center() + .justify_center() + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + for row in 0..3 { + for col in 0..2 { + let dot = Bounds::new( + point( + bounds.origin.x + px(col as f32 * 5.0), + bounds.origin.y + px(row as f32 * 5.0), + ), + size(px(3.0), px(3.0)), + ); + window.paint_quad( + ui::fill(dot, dots_color).corner_radii(px(1.5)), + ); + } + } + }, + ) + .w(px(8.0)) + .h(px(13.0)), + ); + if hx >= 0.0 && hy >= 0.0 && hx + 14.0 <= viewport_width && hy + 24.0 <= viewport_height + { + dh = dh.snapshot( + HandleKind::DragHandle.snapshot_id(), + Some(EDGELESS_VIEWPORT_ID), + ); + } + elements.push(dh.into_any_element()); + } + } + + // 2. Active gesture previews (marquee, shape/frame/note creation, connector routing, freehand stroke). + match &authoring.gesture { + Some(EdgelessGesture::Marquee { + start_world, + current_world, + }) => { + let r = normalized_rect(*start_world, *current_world); + let tl = camera.world_to_screen(point(px(r.x), px(r.y)), vp_origin); + let br = camera.world_to_screen(point(px(r.right()), px(r.bottom())), vp_origin); + let x = f32::from(tl.x).max(0.0); + let y = f32::from(tl.y).max(0.0); + let w = (f32::from(br.x).min(viewport_width) - x).max(1.0); + let h = (f32::from(br.y).min(viewport_height) - y).max(1.0); + let mut mq = div() + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(w)) + .h(px(h)) + .bg(brand.opacity(0.12)) + .border_1() + .border_color(brand); + if x >= 0.0 && y >= 0.0 && x + w <= viewport_width && y + h <= viewport_height { + mq = mq.snapshot("edgeless.marquee", Some(EDGELESS_VIEWPORT_ID)); + } + elements.push(mq.into_any_element()); + } + Some(EdgelessGesture::CreateShape { + start_world, + current_world, + .. + }) + | Some(EdgelessGesture::CreateFrame { + start_world, + current_world, + }) + | Some(EdgelessGesture::CreateNote { + start_world, + current_world, + }) => { + let r = normalized_rect(*start_world, *current_world); + let tl = camera.world_to_screen(point(px(r.x), px(r.y)), vp_origin); + let br = camera.world_to_screen(point(px(r.right()), px(r.bottom())), vp_origin); + let x = f32::from(tl.x); + let y = f32::from(tl.y); + let w = (f32::from(br.x) - x).max(2.0); + let h = (f32::from(br.y) - y).max(2.0); + elements.push( + div() + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(w)) + .h(px(h)) + .bg(brand.opacity(0.08)) + .border_1() + .border_color(brand) + .rounded(px(4.0)) + .into_any_element(), + ); + } + Some(EdgelessGesture::CreateConnector { + source_world, + current_world, + target_world, + .. + }) => { + let src = *source_world; + let dst = target_world.unwrap_or(*current_world); + let p0 = camera.world_to_screen(point(px(src.0), px(src.1)), vp_origin); + let p1 = camera.world_to_screen(point(px(dst.0), px(dst.1)), vp_origin); + let mid_x = (f32::from(p0.x) + f32::from(p1.x)) * 0.5; + let snapped_target = target_world.is_some(); + elements.push( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let ox = f32::from(bounds.origin.x); + let oy = f32::from(bounds.origin.y); + let a = point(px(ox + f32::from(p0.x)), px(oy + f32::from(p0.y))); + let m1 = point(px(ox + mid_x), px(oy + f32::from(p0.y))); + let m2 = point(px(ox + mid_x), px(oy + f32::from(p1.y))); + let b = point(px(ox + f32::from(p1.x)), px(oy + f32::from(p1.y))); + let mut pb = PathBuilder::stroke(px(2.0)); + pb.move_to(a); + pb.line_to(m1); + pb.line_to(m2); + pb.line_to(b); + if let Ok(path) = pb.build() { + window.paint_path(path, brand); + } + // Live port rings at source and snapped target. + for (pt, highlight) in [(a, true), (b, snapped_target)] { + if highlight { + let ring = Bounds::new( + point(pt.x - px(5.0), pt.y - px(5.0)), + size(px(10.0), px(10.0)), + ); + window.paint_quad(ui::quad( + ring, + Corners::all(px(5.0)), + white, + Edges::all(px(2.0)), + brand, + BorderStyle::Solid, + )); + } + } + }, + ) + .absolute() + .inset_0() + .into_any_element(), + ); + } + Some(EdgelessGesture::DrawStroke { + highlighter, + points_world, + }) if points_world.len() >= 2 => { + let pts: Vec> = points_world + .iter() + .map(|&(wx, wy)| { + camera.world_to_screen(point(px(wx as f32), px(wy as f32)), vp_origin) + }) + .collect(); + let width = if *highlighter { + (22.0 * camera.zoom).max(4.0) + } else { + (4.0 * camera.zoom).max(2.0) + }; + let color = if *highlighter { + ui::rgba(0x84cfff70).into() + } else { + palette.text_primary + }; + elements.push( + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let ox = f32::from(bounds.origin.x); + let oy = f32::from(bounds.origin.y); + let mut pb = PathBuilder::stroke(px(width)); + pb.move_to(point( + px(ox + f32::from(pts[0].x)), + px(oy + f32::from(pts[0].y)), + )); + for p in &pts[1..] { + pb.line_to(point(px(ox + f32::from(p.x)), px(oy + f32::from(p.y)))); + } + if let Ok(path) = pb.build() { + window.paint_path(path, color); + } + }, + ) + .absolute() + .inset_0() + .into_any_element(), + ); + } + _ => {} + } + + // 3. Inline label editor overlay (Shape / Connector / SurfaceText / Frame title). + if let Some(editor) = authoring.label_editor() { + let tl = camera.world_to_screen( + point(px(editor.world_rect.x), px(editor.world_rect.y)), + vp_origin, + ); + let br = camera.world_to_screen( + point( + px(editor.world_rect.right()), + px(editor.world_rect.bottom()), + ), + vp_origin, + ); + let w = (f32::from(br.x) - f32::from(tl.x)) + .max(120.0) + .min(viewport_width - 16.0); + let h = (f32::from(br.y) - f32::from(tl.y)) + .max(32.0) + .min(viewport_height - 16.0); + let x = f32::from(tl.x).clamp(8.0, (viewport_width - w - 8.0).max(8.0)); + let y = f32::from(tl.y).clamp(8.0, (viewport_height - h - 8.0).max(8.0)); + let display = editor.display_text(); + let (sel, reversed) = editor.shown_selection(); + let selection_color = palette.brand.opacity(0.22); + let caret_color = palette.brand; + let bg = palette.panel; + let border = palette.brand; + let editor_clone = editor.clone(); + + let el = div() + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(w)) + .h(px(h)) + .rounded(px(4.0)) + .bg(bg) + .border_2() + .border_color(border) + .snapshot("edgeless.inline_edit", Some(EDGELESS_VIEWPORT_ID)) + .snapshot_text(display) + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, cx| { + let pad = 6.0; + if let Some(laid_out) = layout_label_editor_paragraph( + &editor_clone, + f32::from(bounds.size.width), + theme, + window, + ) { + let mut selections = Vec::new(); + if sel.start != sel.end { + selections + .push((sel.start as u64..sel.end as u64, selection_color)); + } + let focus = if reversed { sel.start } else { sel.end }; + let carets = [( + CaretPosition { + utf16_offset: focus as u64, + affinity: WrapAffinity::Upstream, + }, + caret_color, + )]; + laid_out.paint_at( + point(bounds.origin.x + px(pad), bounds.origin.y + px(pad)), + &selections, + &carets, + None, + window, + cx, + ); + } + }, + ) + .size_full(), + ); + elements.push(el.into_any_element()); + } + + elements +} + +/// Lay out an open [`EdgelessLabelEditor`]'s display text (including IME underline marks) +/// for both overlay painting and inside-label pointer hit-testing. +pub(super) fn layout_label_editor_paragraph( + editor: &EdgelessLabelEditor, + width: f32, + theme: PlaygroundTheme, + window: &ui::Window, +) -> Option { + let pad = 6.0; + let wrap_w = (width - 2.0 * pad).max(20.0); + let display = editor.display_text(); + let marked = editor.marked_range(); + let mut delta = Vec::new(); + if let Some(m) = &marked { + let b0 = utf16_to_byte(&display, m.start); + let b1 = utf16_to_byte(&display, m.end); + if b0 > 0 { + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(display[..b0].to_string()), + format: None, + }); + } + if b1 > b0 { + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(display[b0..b1].to_string()), + format: Some(BTreeMap::from([("underline".to_string(), Any::True)])), + }); + } + if b1 < display.len() { + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(display[b1..].to_string()), + format: None, + }); + } + } else if !display.is_empty() { + delta.push(TextDeltaOp::Insert { + insert: TextInsert::Text(display), + format: None, + }); + } + let style = RichParagraphStyle { + font_family: FONT_SANS.into(), + font_size: 14.0, + line_height: 20.0, + text_color: theme.palette().text_primary, + ..RichParagraphStyle::from_theme(theme.mode()) + }; + let para = RichParagraph::from_delta(delta).ok()?; + Some(para.layout(window.text_system(), &style, wrap_w)) +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/scene.rs b/blocksuite/native-playground/crates/playground/src/edgeless/scene.rs new file mode 100644 index 0000000000..a7b1cb6960 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/scene.rs @@ -0,0 +1,564 @@ +//! Single-pass Edgeless scene preparation: cached note/text/surface layout and paint-order hit-test metadata. + +use std::rc::Rc; + +use blocksuite_playground_doc::read::{BlockContent, NoteDisplayMode}; +use ui::Window; + +use crate::{ + block_flow::{ + BlockFlow, FlowInput, FlowLayout, InlineAlign, InlineBaseline, InlineStyle, layout_inline, + }, + surface::{SurfaceLayout, layout_surface}, + theme::FONT_SANS, +}; + +use super::{ + CachedNoteFlow, CachedSurfaces, EdgelessCanvasState, EdgelessRenderInput, FRAME_TITLE_GAP, + FRAME_TITLE_HEIGHT, Layers, NOTE_CARD_PADDING, PaintEdgelessText, PaintFrame, PaintItem, + PaintNote, SpatialItemInfo, SpatialItemKind, WorldRect, collect_frame_children, + note_border_radius, note_border_style, note_collapse, note_scale, note_shadow_type, parse_xywh, + prop_bool, prop_f32, resolve_edgeless_color, rotated_bounds, spatial_blocks, world_bounds, + world_rect, +}; + +pub(super) struct PreparedEdgelessScene { + pub(super) frames: Vec, + pub(super) notes: Vec, + pub(super) texts: Vec, + pub(super) surfaces: Rc<[SurfaceLayout]>, + pub(super) order: Rc<[PaintItem]>, +} + +pub(super) fn prepare_edgeless_scene( + state: &mut EdgelessCanvasState, + input: &EdgelessRenderInput<'_>, + window: &Window, +) -> PreparedEdgelessScene { + state.last_frame_relayouts = 0; + let live_overrides = state.authoring.live_overrides(); + + let mut frames = Vec::new(); + let mut notes = Vec::new(); + let mut texts = Vec::new(); + // Preserve exact `sys:children` order across Frames, Notes, and EdgelessTexts when merging + // equal-index items into `Layers::merge`. + let mut spatial_order: Vec<(String, PaintItem)> = Vec::new(); + + if let Some(root) = &input.snapshot.root { + let mut active_notes = Vec::new(); + let mut active_texts = Vec::new(); + + for child in spatial_blocks(root) { + match &child.content { + BlockContent::Frame { title, xywh } => { + if let Some(mut rect) = parse_xywh(xywh) { + if let Some(ov) = live_overrides.get(&child.id) { + rect = ov.rect; + } + let fill = child + .props + .get("prop:background") + .and_then(|v| resolve_edgeless_color(v, input.theme)) + .filter(|c| !c.is_transparent()); + let title_text = if title.plain.is_empty() { + "Frame" + } else { + title.plain.as_str() + }; + let title_style = + InlineStyle::new(FONT_SANS, 12.0, 500.0, input.palette.text_secondary); + let title_inline = Rc::new(layout_inline( + title_text, + &title_style, + rect.w.max(80.0), + FRAME_TITLE_HEIGHT, + InlineBaseline::Of(&title_style), + InlineAlign::Left, + window, + )); + let pill_w = (title_inline.content_width() + 16.0).min(rect.w.max(80.0)); + let title_pill_rect = WorldRect::new( + rect.x, + rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP, + pill_w, + FRAME_TITLE_HEIGHT, + ); + let index = child + .props + .get("prop:index") + .and_then(|v| v.as_str()) + .unwrap_or("a0") + .to_string(); + let frame_children = collect_frame_children(child); + let idx = frames.len(); + frames.push(PaintFrame { + id: child.id.clone(), + title: title_text.to_string(), + index, + frame_children, + rect, + title_inline, + title_pill_rect, + fill, + }); + spatial_order.push((child.id.clone(), PaintItem::Frame(idx))); + } + } + BlockContent::Note { + display_mode, + xywh, + background, + hidden, + } if !hidden && *display_mode != NoteDisplayMode::DocOnly => { + let mut rect = + parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0)); + if let Some(ov) = live_overrides.get(&child.id) { + rect = ov.rect; + } + let scale = note_scale(child); + let collapse = note_collapse(child); + let border = note_border_style(child); + let border_radius = note_border_radius(child); + let shadows = input.theme.shadows(note_shadow_type(child)); + let inner_width = (rect.w / scale - 2.0 * NOTE_CARD_PADDING).max(120.0); + let key = ( + input.doc_rev, + inner_width.to_bits(), + scale.to_bits(), + input.theme, + input.env_rev, + input.preedit_nonce, + ); + let layout = match state.note_flows.get_mut(&child.id) { + Some(cached) if cached.key == key => cached.layout.clone(), + _ => { + let flow_input = FlowInput { + snapshot: input.snapshot, + width: inner_width, + theme: input.theme, + page_titles: input.page_titles, + images: input.images, + env_rev: input.env_rev, + }; + let entry = + state.note_flows.entry(child.id.clone()).or_insert_with(|| { + CachedNoteFlow { + flow: BlockFlow::new(), + key: (u64::MAX, 0, 0, input.theme, 0, 0), + layout: Rc::new(FlowLayout { + blocks: Vec::new(), + width: inner_width, + height: 0.0, + stats: Default::default(), + }), + } + }); + let laid_out = + entry + .flow + .layout_nodes(&child.children, &flow_input, window); + state.last_frame_relayouts += laid_out.stats.laid_out as u64; + let rc = Rc::new(laid_out); + entry.key = key; + entry.layout = rc.clone(); + rc + } + }; + if !collapse { + rect.h = rect + .h + .max((layout.height + 2.0 * NOTE_CARD_PADDING) * scale); + } + let fill = resolve_edgeless_color(background, input.theme) + .filter(|c| !c.is_transparent()) + .unwrap_or(input.palette.background); + active_notes.push(child.id.clone()); + let index = child + .props + .get("prop:index") + .and_then(|v| v.as_str()) + .unwrap_or("a0") + .to_string(); + let idx = notes.len(); + notes.push(PaintNote { + id: child.id.clone(), + index, + rect, + scale, + border, + border_radius, + shadows, + fill, + layout, + }); + spatial_order.push((child.id.clone(), PaintItem::Note(idx))); + } + BlockContent::EdgelessText { xywh } => { + if let Some(mut rect) = parse_xywh(xywh) { + let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0); + let mut rotate_deg = prop_f32(child, "prop:rotate", 0.0); + if let Some(ov) = live_overrides.get(&child.id) { + rect = ov.rect; + if let Some(r) = ov.rotate_deg { + rotate_deg = r; + } + } + let has_max_width = prop_bool(child, "prop:hasMaxWidth", true); + let text_width = if has_max_width { + (rect.w / scale).max(60.0) + } else { + (rect.w / scale).max(320.0) + }; + let key = ( + input.doc_rev, + text_width.to_bits(), + scale.to_bits(), + input.theme, + input.env_rev, + input.preedit_nonce, + ); + let layout = match state.text_flows.get_mut(&child.id) { + Some(cached) if cached.key == key => cached.layout.clone(), + _ => { + let flow_input = FlowInput { + snapshot: input.snapshot, + width: text_width, + theme: input.theme, + page_titles: input.page_titles, + images: input.images, + env_rev: input.env_rev, + }; + let entry = state + .text_flows + .entry(child.id.clone()) + .or_insert_with(|| CachedNoteFlow { + flow: BlockFlow::new(), + key: (u64::MAX, 0, 0, input.theme, 0, 0), + layout: Rc::new(FlowLayout { + blocks: Vec::new(), + width: text_width, + height: 0.0, + stats: Default::default(), + }), + }); + let laid_out = + entry + .flow + .layout_nodes(&child.children, &flow_input, window); + state.last_frame_relayouts += laid_out.stats.laid_out as u64; + let rc = Rc::new(laid_out); + entry.key = key; + entry.layout = rc.clone(); + rc + } + }; + rect.h = (layout.height * scale).max(rect.h); + active_texts.push(child.id.clone()); + let index = child + .props + .get("prop:index") + .and_then(|v| v.as_str()) + .unwrap_or("a0") + .to_string(); + let idx = texts.len(); + texts.push(PaintEdgelessText { + world_aabb: rotated_bounds(rect, rotate_deg), + id: child.id.clone(), + index, + rect, + scale, + rotate_deg, + layout, + }); + spatial_order.push((child.id.clone(), PaintItem::Text(idx))); + } + } + _ => {} + } + } + + if state.note_flows.len() > active_notes.len() { + state.note_flows.retain(|id, _| active_notes.contains(id)); + } + if state.text_flows.len() > active_texts.len() { + state.text_flows.retain(|id, _| active_texts.contains(id)); + } + } + + let key = (input.doc_rev, input.theme, input.env_rev); + let has_live_overrides = !live_overrides.is_empty(); + let (surfaces, order, painted_items) = match &state.surfaces { + Some(cached) if cached.key == key && !has_live_overrides => ( + Rc::clone(&cached.layouts), + Rc::clone(&cached.order), + Rc::clone(&cached.painted_items), + ), + _ => { + let external = frames + .iter() + .map(|f| (f.id.clone(), world_bounds(f.rect, 0.))) + .chain( + notes + .iter() + .map(|n| (n.id.clone(), world_bounds(n.rect, 0.))), + ) + .chain( + texts + .iter() + .map(|t| (t.id.clone(), world_bounds(t.rect, t.rotate_deg))), + ) + .collect(); + let layouts: Rc<[SurfaceLayout]> = input + .snapshot + .root + .iter() + .flat_map(|root| &root.children) + .filter_map(|node| match &node.content { + BlockContent::Surface { elements, .. } => { + if has_live_overrides { + let mut patched = elements.clone(); + for el in &mut patched { + if let Some(ov) = live_overrides.get(&el.id) { + if let Some(r) = ov.rotate_deg { + el.rotate = r as f64; + } + let xywh = [ + ov.rect.x as f64, + ov.rect.y as f64, + ov.rect.w as f64, + ov.rect.h as f64, + ]; + match &mut el.kind { + blocksuite_playground_doc::read::SurfaceElementKind::Shape(s) => s.xywh = xywh, + blocksuite_playground_doc::read::SurfaceElementKind::Text(t) => t.xywh = xywh, + blocksuite_playground_doc::read::SurfaceElementKind::Brush(b) + | blocksuite_playground_doc::read::SurfaceElementKind::Highlighter(b) => b.xywh = xywh, + blocksuite_playground_doc::read::SurfaceElementKind::Connector(c) => { + let (dx, dy) = (ov.delta.0 as f64, ov.delta.1 as f64); + if c.source.id.is_none() + && let Some([sx, sy]) = c.source.position + { + c.source.position = Some([sx + dx, sy + dy]); + } + if c.target.id.is_none() + && let Some([tx, ty]) = c.target.position + { + c.target.position = Some([tx + dx, ty + dy]); + } + if let Some([lx, ly, lw, lh]) = c.label_xywh { + c.label_xywh = Some([lx + dx, ly + dy, lw, lh]); + } + } + _ => {} + } + } + } + Some(layout_surface(&patched, &external, input.theme, window)) + } else { + Some(layout_surface(elements, &external, input.theme, window)) + } + } + _ => None, + }) + .collect(); + let order: Rc<[PaintItem]> = input + .snapshot + .root + .as_ref() + .map(|root| { + let items = spatial_order + .iter() + .map(|(id, item)| (id.as_str(), *item)) + .chain(layouts.iter().enumerate().flat_map(|(l, layout)| { + layout + .item_ids() + .enumerate() + .map(move |(i, id)| (id, PaintItem::Surface(l, i))) + })); + Layers::from_root(root).merge(items) + }) + .unwrap_or_default() + .into(); + + // Build painted_items in exact paint order once per doc/theme/env revision (or during live drag). + let mut built_items = Vec::with_capacity(order.len()); + let surface_nodes: Vec<(&str, &[blocksuite_playground_doc::read::SurfaceElement])> = + input + .snapshot + .root + .iter() + .flat_map(|root| &root.children) + .filter_map(|node| match &node.content { + BlockContent::Surface { elements, .. } => { + Some((node.id.as_str(), elements.as_slice())) + } + _ => None, + }) + .collect(); + for item in order.iter() { + match *item { + PaintItem::Frame(i) => { + let f = &frames[i]; + built_items.push(SpatialItemInfo { + id: f.id.clone(), + kind: SpatialItemKind::Frame, + surface_id: None, + rect: f.rect, + rotate_deg: 0.0, + index: f.index.clone(), + scale: 1.0, + stroke_width: 1.0, + polyline: Vec::new(), + frame_children: f.frame_children.clone(), + title_pill_rect: Some(f.title_pill_rect), + }); + } + PaintItem::Note(i) => { + let n = ¬es[i]; + built_items.push(SpatialItemInfo { + id: n.id.clone(), + kind: SpatialItemKind::Note, + surface_id: None, + rect: n.rect, + rotate_deg: 0.0, + index: n.index.clone(), + scale: n.scale, + stroke_width: 1.0, + polyline: Vec::new(), + frame_children: Vec::new(), + title_pill_rect: None, + }); + } + PaintItem::Text(i) => { + let t = &texts[i]; + built_items.push(SpatialItemInfo { + id: t.id.clone(), + kind: SpatialItemKind::EdgelessText, + surface_id: None, + rect: t.rect, + rotate_deg: t.rotate_deg, + index: t.index.clone(), + scale: t.scale, + stroke_width: 1.0, + polyline: Vec::new(), + frame_children: Vec::new(), + title_pill_rect: None, + }); + } + PaintItem::Surface(l, i) => { + let Some(id) = surfaces_item_id(&layouts, l, i) else { + continue; + }; + let Some((surface_id, elements)) = surface_nodes.get(l) else { + continue; + }; + let Some(el) = elements.iter().find(|e| e.id == id) else { + continue; + }; + let bounds_rect = layouts[l] + .bounds() + .find(|(bid, _)| *bid == id) + .map(|(_, b)| world_rect(b)) + .unwrap_or_default(); + let (kind, rect) = match &el.kind { + blocksuite_playground_doc::read::SurfaceElementKind::Shape(s) => ( + SpatialItemKind::Shape, + WorldRect::new( + s.xywh[0] as f32, + s.xywh[1] as f32, + s.xywh[2] as f32, + s.xywh[3] as f32, + ), + ), + blocksuite_playground_doc::read::SurfaceElementKind::Connector(_) => { + (SpatialItemKind::Connector, bounds_rect) + } + blocksuite_playground_doc::read::SurfaceElementKind::Brush(s) => ( + SpatialItemKind::Brush, + WorldRect::new( + s.xywh[0] as f32, + s.xywh[1] as f32, + s.xywh[2] as f32, + s.xywh[3] as f32, + ), + ), + blocksuite_playground_doc::read::SurfaceElementKind::Highlighter(s) => { + ( + SpatialItemKind::Highlighter, + WorldRect::new( + s.xywh[0] as f32, + s.xywh[1] as f32, + s.xywh[2] as f32, + s.xywh[3] as f32, + ), + ) + } + blocksuite_playground_doc::read::SurfaceElementKind::Text(s) => ( + SpatialItemKind::SurfaceText, + WorldRect::new( + s.xywh[0] as f32, + s.xywh[1] as f32, + s.xywh[2] as f32, + s.xywh[3] as f32, + ), + ), + blocksuite_playground_doc::read::SurfaceElementKind::Group { + .. + } => (SpatialItemKind::Group, bounds_rect), + blocksuite_playground_doc::read::SurfaceElementKind::Unknown { + .. + } => { + continue; + } + }; + let stroke_width = layouts[l].item_stroke_width(i); + let polyline = layouts[l].item_polyline(i).to_vec(); + let final_rect = live_overrides.get(id).map_or(rect, |o| o.rect); + let final_rot = live_overrides + .get(id) + .and_then(|o| o.rotate_deg) + .unwrap_or(el.rotate as f32); + built_items.push(SpatialItemInfo { + id: el.id.clone(), + kind, + surface_id: Some((*surface_id).to_string()), + rect: final_rect, + rotate_deg: final_rot, + index: el.index.clone(), + scale: 1.0, + stroke_width, + polyline, + frame_children: Vec::new(), + title_pill_rect: None, + }); + } + } + } + let painted_items: Rc<[SpatialItemInfo]> = built_items.into(); + if !has_live_overrides { + state.surfaces = Some(CachedSurfaces { + key, + layouts: Rc::clone(&layouts), + order: Rc::clone(&order), + painted_items: Rc::clone(&painted_items), + }); + } + (layouts, order, painted_items) + } + }; + + state.authoring.painted_items = painted_items; + + PreparedEdgelessScene { + frames, + notes, + texts, + surfaces, + order, + } +} + +fn surfaces_item_id(layouts: &[SurfaceLayout], l: usize, i: usize) -> Option<&str> { + layouts.get(l).and_then(|lay| lay.item_ids().nth(i)) +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless/toolbar.rs b/blocksuite/native-playground/crates/playground/src/edgeless/toolbar.rs new file mode 100644 index 0000000000..a440998022 --- /dev/null +++ b/blocksuite/native-playground/crates/playground/src/edgeless/toolbar.rs @@ -0,0 +1,385 @@ +//! Screen-space Edgeless authoring toolbar, shape picker popover, and zoom controls. + +use blocksuite_playground_doc::read::ShapeType; +use ui::{AnyElement, Context, MouseButton, Window, canvas, div, prelude::*, px}; + +use crate::{ + PlaygroundView, + theme::{IconPaint, Palette, PlaygroundTheme}, +}; + +use super::{ + EDGELESS_VIEWPORT_ID, ZOOM_BAR_MARGIN, ZOOM_BAR_PAD, ZOOM_BAR_RADIUS, ZOOM_BTN_HEIGHT, + ZOOM_BTN_RADIUS, +}; + +/// Active tool selected in `chrome.edgeless_toolbar`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum EdgelessTool { + #[default] + Select, + Hand, + Note, + Shape(ShapeType), + Connector, + Brush, + Highlighter, + Text, + Frame, +} + +impl EdgelessTool { + pub fn is_shape(self) -> bool { + matches!(self, Self::Shape(_)) + } +} + +/// Bottom screen-space creation toolbar (`chrome.edgeless_toolbar`). +/// Concentric radii: outer `8px`, padding `4px`, buttons `4px` (`28×28`, `2px` gap). +pub fn build_edgeless_toolbar( + tool: EdgelessTool, + viewport_width: f32, + palette: &Palette, + theme: PlaygroundTheme, + cx: &mut Context, +) -> AnyElement { + const BAR_MARGIN: f32 = 12.0; + const BAR_PAD: f32 = 4.0; + const BAR_RADIUS: f32 = 8.0; + const BTN_SIZE: f32 = 28.0; + const BTN_RADIUS: f32 = 4.0; + const BTN_GAP: f32 = 2.0; + + let shadows = theme.shadows("--affine-toolbar-shadow"); + let tools: [(&'static str, &'static str, &'static str, EdgelessTool); 9] = [ + ( + "edgeless-tool-select", + "chrome.edgeless_toolbar.select", + "SelectIcon", + EdgelessTool::Select, + ), + ( + "edgeless-tool-hand", + "chrome.edgeless_toolbar.hand", + "HandIcon", + EdgelessTool::Hand, + ), + ( + "edgeless-tool-note", + "chrome.edgeless_toolbar.note", + "NoteShadowDuotoneIcon", + EdgelessTool::Note, + ), + ( + "edgeless-tool-shape", + "chrome.edgeless_toolbar.shape", + "ShapeIcon", + EdgelessTool::Shape(ShapeType::Rect), + ), + ( + "edgeless-tool-connector", + "chrome.edgeless_toolbar.connector", + "ConnectorEIcon", + EdgelessTool::Connector, + ), + ( + "edgeless-tool-brush", + "chrome.edgeless_toolbar.brush", + "PenIcon", + EdgelessTool::Brush, + ), + ( + "edgeless-tool-highlighter", + "chrome.edgeless_toolbar.highlighter", + "BrushIcon", + EdgelessTool::Highlighter, + ), + ( + "edgeless-tool-text", + "chrome.edgeless_toolbar.text", + "AddTextIcon", + EdgelessTool::Text, + ), + ( + "edgeless-tool-frame", + "chrome.edgeless_toolbar.frame", + "FrameIcon", + EdgelessTool::Frame, + ), + ]; + + let bar_w = tools.len() as f32 * BTN_SIZE + (tools.len() - 1) as f32 * BTN_GAP + 2.0 * BAR_PAD; + let bar_left = ((viewport_width - bar_w) * 0.5).max(8.0).round(); + + let mut bar = div() + .absolute() + .left(px(bar_left)) + .bottom(px(BAR_MARGIN)) + .p(px(BAR_PAD)) + .rounded(px(BAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .flex() + .items_center() + .gap(px(BTN_GAP)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .snapshot("chrome.edgeless_toolbar", Some(EDGELESS_VIEWPORT_ID)); + + for (el_id, snap_id, icon_name, target_tool) in tools { + let active = match (tool, target_tool) { + (EdgelessTool::Shape(_), EdgelessTool::Shape(_)) => true, + (a, b) => a == b, + }; + let icon_color = if active { palette.brand } else { palette.icon }; + let mut btn = div() + .id(el_id) + .w(px(BTN_SIZE)) + .h(px(BTN_SIZE)) + .rounded(px(BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|s| s.bg(palette.hover)) + .snapshot(snap_id, Some("chrome.edgeless_toolbar")) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + let chosen = match target_tool { + EdgelessTool::Shape(_) => { + if let EdgelessTool::Shape(cur) = this.edgeless.authoring.tool { + let next = match cur { + ShapeType::Rect => ShapeType::Ellipse, + ShapeType::Ellipse => ShapeType::Diamond, + ShapeType::Diamond => ShapeType::Triangle, + ShapeType::Triangle => ShapeType::Rect, + }; + EdgelessTool::Shape(next) + } else { + EdgelessTool::Shape(this.edgeless.authoring.active_shape_type()) + } + } + other => other, + }; + this.edgeless_select_tool(chosen, window, cx); + }), + ) + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, cx| { + IconPaint::named(icon_name).paint(bounds, icon_color, window, cx); + }, + ) + .w(px(18.0)) + .h(px(18.0)), + ); + if active { + btn = btn.bg(palette.brand.opacity(0.14)); + } + bar = bar.child(btn); + } + + if !shadows.is_empty() { + bar = bar.shadow(shadows.clone().into()); + } + + // When the Shape tool is active, mount a compact concentric shape-variant sub-pill above the bar. + if let EdgelessTool::Shape(active_shape) = tool { + let variants: [(&'static str, &'static str, &'static str, ShapeType); 4] = [ + ( + "shape-rect", + "chrome.edgeless_toolbar.shape.rect", + "SquareIcon", + ShapeType::Rect, + ), + ( + "shape-ellipse", + "chrome.edgeless_toolbar.shape.ellipse", + "RoundedRectangleIcon", + ShapeType::Ellipse, + ), + ( + "shape-diamond", + "chrome.edgeless_toolbar.shape.diamond", + "DiamondIcon", + ShapeType::Diamond, + ), + ( + "shape-triangle", + "chrome.edgeless_toolbar.shape.triangle", + "TriangleIcon", + ShapeType::Triangle, + ), + ]; + let sub_w = variants.len() as f32 * BTN_SIZE + + (variants.len() - 1) as f32 * BTN_GAP + + 2.0 * BAR_PAD; + let sub_left = ((viewport_width - sub_w) * 0.5).max(8.0).round(); + let mut sub = div() + .absolute() + .left(px(sub_left)) + .bottom(px(BAR_MARGIN + BTN_SIZE + 2.0 * BAR_PAD + 8.0)) + .p(px(BAR_PAD)) + .rounded(px(BAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .flex() + .items_center() + .gap(px(BTN_GAP)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .snapshot( + "chrome.edgeless_toolbar.shape_picker", + Some(EDGELESS_VIEWPORT_ID), + ); + if !shadows.is_empty() { + sub = sub.shadow(shadows.into()); + } + for (el_id, snap_id, icon_name, shape_kind) in variants { + let active = active_shape == shape_kind; + let icon_color = if active { palette.brand } else { palette.icon }; + let mut btn = div() + .id(el_id) + .w(px(BTN_SIZE)) + .h(px(BTN_SIZE)) + .rounded(px(BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover(|s| s.bg(palette.hover)) + .snapshot(snap_id, Some("chrome.edgeless_toolbar.shape_picker")) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + this.edgeless_select_tool(EdgelessTool::Shape(shape_kind), window, cx); + }), + ) + .child( + canvas( + |_, _, _| (), + move |bounds, _, window, cx| { + IconPaint::named(icon_name).paint(bounds, icon_color, window, cx); + }, + ) + .w(px(16.0)) + .h(px(16.0)), + ); + if active { + btn = btn.bg(palette.brand.opacity(0.14)); + } + sub = sub.child(btn); + } + return div() + .absolute() + .inset_0() + .child(sub) + .child(bar) + .into_any_element(); + } + + bar.into_any_element() +} + +/// Build the bottom-right screen-space zoom control bar (`chrome.edgeless_zoom`). +/// On narrow viewports (`viewport_width < 660.0`), stacks cleanly above `chrome.edgeless_toolbar` +/// so the two screen-space bars never overlap or clip. +pub fn build_zoom_controls( + zoom: f32, + viewport_width: f32, + palette: &Palette, + theme: PlaygroundTheme, + on_out: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, + on_reset: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, + on_in: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, + on_fit: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, + cx: &mut ui::Context, +) -> AnyElement { + let pct_label = format!("{}%", (zoom * 100.0).round() as i32); + let shadows = theme.shadows("--affine-toolbar-shadow"); + + let button = |id: &'static str, snap_id: &'static str, label: String, width: f32| { + div() + .id(id) + .w(px(width)) + .h(px(ZOOM_BTN_HEIGHT)) + .rounded(px(ZOOM_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .text_size(px(12.0)) + .font_weight(ui::FontWeight::MEDIUM) + .text_color(palette.text_primary) + .cursor_pointer() + .hover(|s| s.bg(palette.hover)) + .snapshot(snap_id, Some("chrome.edgeless_zoom")) + .snapshot_text(label.clone()) + .child(label) + }; + + let zoom_bottom = if viewport_width < 660.0 { + ZOOM_BAR_MARGIN + ZOOM_BTN_HEIGHT + 2.0 * ZOOM_BAR_PAD + 8.0 + } else { + ZOOM_BAR_MARGIN + }; + let mut bar = div() + .absolute() + .right(px(ZOOM_BAR_MARGIN)) + .bottom(px(zoom_bottom)) + .p(px(ZOOM_BAR_PAD)) + .rounded(px(ZOOM_BAR_RADIUS)) + .bg(palette.panel) + .border_1() + .border_color(palette.border) + .flex() + .items_center() + .gap(px(4.0)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .snapshot("chrome.edgeless_zoom", Some(EDGELESS_VIEWPORT_ID)) + .child( + button( + "edgeless-zoom-out", + "chrome.edgeless_zoom.out", + "-".into(), + 28.0, + ) + .on_mouse_down(MouseButton::Left, cx.listener(on_out)), + ) + .child( + button( + "edgeless-zoom-reset", + "chrome.edgeless_zoom.reset", + pct_label, + 48.0, + ) + .on_mouse_down(MouseButton::Left, cx.listener(on_reset)), + ) + .child( + button( + "edgeless-zoom-in", + "chrome.edgeless_zoom.in", + "+".into(), + 28.0, + ) + .on_mouse_down(MouseButton::Left, cx.listener(on_in)), + ) + .child( + button( + "edgeless-zoom-fit", + "chrome.edgeless_zoom.fit", + "Fit".into(), + 36.0, + ) + .on_mouse_down(MouseButton::Left, cx.listener(on_fit)), + ); + + if !shadows.is_empty() { + bar = bar.shadow(shadows.into()); + } + + bar.into_any_element() +} diff --git a/blocksuite/native-playground/crates/playground/src/edgeless_canvas.rs b/blocksuite/native-playground/crates/playground/src/edgeless_canvas.rs deleted file mode 100644 index 4b26705315..0000000000 --- a/blocksuite/native-playground/crates/playground/src/edgeless_canvas.rs +++ /dev/null @@ -1,1044 +0,0 @@ -//! Spatial Edgeless canvas rendering: procedural dot-grid, `affine:frame`, `affine:note`, -//! `affine:edgeless-text`, cached per-note `BlockFlow` (zero relayout on pan/zoom), and -//! screen-space zoom controls (`chrome.edgeless_zoom`). - -use std::{ - collections::{BTreeMap, HashMap}, - rc::Rc, -}; - -use blocksuite_playground_doc::read::{BlockContent, BlockNode, NoteDisplayMode, PageSnapshot}; -use serde_json::Value as JsonValue; -use ui::{ - AnyElement, Background, BorderStyle, Bounds, ContentMask, Corners, Edges, Hsla, MouseButton, - Pixels, Point, ScaledPixels, SharedString, Size, TransformationMatrix, Window, canvas, div, - point, prelude::*, px, size, -}; - -use crate::{ - block_flow::{ - BlockFlow, BlockPaint, FlowInput, FlowLayout, ImageSlot, InlineAlign, InlineBaseline, - InlineStyle, layout_inline, - }, - edgeless_camera::{EdgelessCamera, WorldRect, bg_grid_gap, parse_xywh}, - edgeless_order::{Layers, PaintItem}, - surface::{SurfaceLayout, WorldBounds, layout_surface}, - theme::{FONT_SANS, Palette, PlaygroundTheme}, -}; - -/// Snapshot id of the Edgeless spatial viewport under `root.canvas`. -pub const EDGELESS_VIEWPORT_ID: &str = "edgeless.viewport"; -/// Inner padding of an `affine:note` card on the Edgeless canvas (world px). -pub const NOTE_CARD_PADDING: f32 = 24.0; -/// Default corner radius of an `affine:note` card (world px). -const CARD_RADIUS: f32 = 8.0; -/// Corner radius of an `affine:frame` container (world px, matching BlockSuite). -const FRAME_RADIUS: f32 = 2.0; -/// Frame title pill height and vertical gap above the frame top edge (world px). -const FRAME_TITLE_HEIGHT: f32 = 22.0; -const FRAME_TITLE_GAP: f32 = 6.0; -/// Screen-space zoom bar constants (concentric radii: outer 8 - pad 4 == inner 4). -const ZOOM_BAR_MARGIN: f32 = 12.0; -const ZOOM_BAR_PAD: f32 = 4.0; -const ZOOM_BAR_RADIUS: f32 = 8.0; -const ZOOM_BTN_RADIUS: f32 = 4.0; -const ZOOM_BTN_HEIGHT: f32 = 28.0; - -type NoteLayoutKey = (u64, u32, u32, PlaygroundTheme, u64); - -struct CachedNoteFlow { - flow: BlockFlow, - key: NoteLayoutKey, - layout: Rc, -} - -struct CachedSurfaces { - key: (u64, PlaygroundTheme, u64), - layouts: Rc<[SurfaceLayout]>, - order: Rc<[PaintItem]>, -} - -fn world_rect(b: Bounds) -> WorldRect { - WorldRect::new( - b.origin.x.into(), - b.origin.y.into(), - b.size.width.into(), - b.size.height.into(), - ) -} -fn world_bounds(r: WorldRect, rotate: f32) -> WorldBounds { - WorldBounds { - xywh: [r.x.into(), r.y.into(), r.w.into(), r.h.into()], - rotate: rotate.into(), - } -} -fn rotated_bounds(r: WorldRect, degrees: f32) -> WorldRect { - world_rect(world_bounds(r, degrees).aabb().ui()) -} - -/// Persistent Edgeless camera, interaction state, and cached per-Note/EdgelessText layouts. -#[derive(Default)] -pub struct EdgelessCanvasState { - pub camera: EdgelessCamera, - pub camera_initialized: bool, - pub drag_pan_anchor: Option>, - surfaces: Option, - note_flows: HashMap, - text_flows: HashMap, - /// Number of block bodies laid out during the most recent Edgeless frame. - pub last_frame_relayouts: u64, -} - -/// Collect spatial blocks (`Frame`, Edgeless-visible `Note`, `EdgelessText`) from `root.children` -/// and any `BlockContent::Surface`'s children in document order. -fn spatial_blocks(root: &BlockNode) -> Vec<&BlockNode> { - let mut out = Vec::new(); - for child in &root.children { - match &child.content { - BlockContent::Surface { .. } => { - for sub in &child.children { - if is_spatial_block(sub) { - out.push(sub); - } - } - } - _ if is_spatial_block(child) => out.push(child), - _ => {} - } - } - out -} - -fn is_spatial_block(node: &BlockNode) -> bool { - match &node.content { - BlockContent::Frame { .. } | BlockContent::EdgelessText { .. } => true, - BlockContent::Note { - display_mode, - hidden: false, - .. - } => *display_mode != NoteDisplayMode::DocOnly, - _ => false, - } -} - -fn edgeless_prop<'a>( - node: &'a BlockNode, - flat_key: &str, - nested: &[&str], -) -> Option<&'a JsonValue> { - if let Some(v) = node.props.get(flat_key) { - return Some(v); - } - let mut cur = node.props.get("prop:edgeless")?; - for seg in nested { - cur = cur.get(*seg)?; - } - Some(cur) -} - -fn note_scale(node: &BlockNode) -> f32 { - edgeless_prop(node, "prop:edgeless.scale", &["scale"]) - .and_then(JsonValue::as_f64) - .map(|v| v as f32) - .filter(|v| v.is_finite()) - .unwrap_or(1.0) - .clamp(0.1, 10.0) -} - -fn note_collapse(node: &BlockNode) -> bool { - edgeless_prop(node, "prop:edgeless.collapse", &["collapse"]) - .and_then(JsonValue::as_bool) - .unwrap_or(false) -} - -fn note_border_style(node: &BlockNode) -> Option<(BorderStyle, f32)> { - let style = edgeless_prop( - node, - "prop:edgeless.style.borderStyle", - &["style", "borderStyle"], - ) - .and_then(JsonValue::as_str) - .unwrap_or("none"); - let border_style = match style { - "solid" => BorderStyle::Solid, - "dash" | "dashed" => BorderStyle::Dashed, - _ => return None, - }; - let size = edgeless_prop( - node, - "prop:edgeless.style.borderSize", - &["style", "borderSize"], - ) - .and_then(JsonValue::as_f64) - .map(|v| v as f32) - .filter(|v| v.is_finite() && *v >= 0.0) - .unwrap_or(4.0); - if size <= 0.0 { - None - } else { - Some((border_style, size)) - } -} - -fn note_border_radius(node: &BlockNode) -> f32 { - edgeless_prop( - node, - "prop:edgeless.style.borderRadius", - &["style", "borderRadius"], - ) - .and_then(JsonValue::as_f64) - .map(|v| v as f32) - .filter(|v| v.is_finite() && *v >= 0.0) - .unwrap_or(CARD_RADIUS) -} - -fn note_shadow_type(node: &BlockNode) -> &str { - edgeless_prop( - node, - "prop:edgeless.style.shadowType", - &["style", "shadowType"], - ) - .and_then(JsonValue::as_str) - .unwrap_or("--affine-note-shadow-box") -} - -impl EdgelessCanvasState { - pub fn new() -> Self { - Self::default() - } - - pub fn set_camera(&mut self, pan_x: f32, pan_y: f32, zoom: f32) { - self.camera = EdgelessCamera::new(pan_x, pan_y, zoom); - self.camera_initialized = true; - } - - pub fn set_zoom_centered( - &mut self, - zoom: f32, - viewport_origin: Point, - viewport_size: Size, - ) { - let center = point( - px(f32::from(viewport_origin.x) + f32::from(viewport_size.width) * 0.5), - px(f32::from(viewport_origin.y) + f32::from(viewport_size.height) * 0.5), - ); - self.camera.zoom_at(zoom, center, viewport_origin); - self.camera_initialized = true; - } - - pub fn set_pan(&mut self, pan_x: f32, pan_y: f32) { - self.camera.pan_x = pan_x; - self.camera.pan_y = pan_y; - self.camera_initialized = true; - } - - #[cfg(test)] - pub fn cached_note_layout(&self, id: &str) -> Option> { - self.note_flows.get(id).map(|entry| entry.layout.clone()) - } - - #[cfg(test)] - pub(crate) fn cached_surface_layouts(&self) -> Rc<[SurfaceLayout]> { - self.surfaces.as_ref().unwrap().layouts.clone() - } - - #[cfg(test)] - pub fn cached_text_layout(&self, id: &str) -> Option> { - self.text_flows.get(id).map(|entry| entry.layout.clone()) - } - - /// Compute the bounding box of all Edgeless-visible Frames, Notes, and EdgelessTexts. - pub fn scene_world_bounds(&self, snapshot: &PageSnapshot) -> WorldRect { - let mut union = WorldRect::default(); - let Some(root) = &snapshot.root else { - return union; - }; - for child in spatial_blocks(root) { - match &child.content { - BlockContent::Frame { xywh, .. } => { - if let Some(rect) = parse_xywh(xywh) { - let with_title = WorldRect::new( - rect.x, - rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP, - rect.w, - rect.h + FRAME_TITLE_HEIGHT + FRAME_TITLE_GAP, - ); - union = union.union(with_title); - } - } - BlockContent::Note { - display_mode, - xywh, - hidden, - .. - } if !hidden && *display_mode != NoteDisplayMode::DocOnly => { - let mut rect = - parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0)); - if !note_collapse(child) - && let Some(cached) = self.note_flows.get(&child.id) - { - let scale = note_scale(child); - rect.h = rect - .h - .max((cached.layout.height + 2.0 * NOTE_CARD_PADDING) * scale); - } - union = union.union(rect); - } - BlockContent::EdgelessText { xywh } => { - if let Some(mut rect) = parse_xywh(xywh) { - let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0); - if let Some(cached) = self.text_flows.get(&child.id) { - rect.h = (cached.layout.height * scale).max(rect.h); - } - union = - union.union(rotated_bounds(rect, prop_f32(child, "prop:rotate", 0.))); - } - } - _ => {} - } - } - if let Some(surfaces) = &self.surfaces { - for layout in surfaces.layouts.iter() { - for (_, bounds) in layout.bounds() { - union = union.union(world_rect(bounds)); - } - } - } - union - } -} - -/// Resolved frame card ready to paint on the GPU canvas. -struct PaintFrame { - id: String, - rect: WorldRect, - title: String, - fill: Option, -} - -/// Resolved note card with its cached `FlowLayout`. -struct PaintNote { - id: String, - rect: WorldRect, - scale: f32, - border: Option<(BorderStyle, f32)>, - border_radius: f32, - shadows: Vec, - fill: Hsla, - layout: Rc, -} - -/// Resolved edgeless-text block with its cached `FlowLayout` and rotation/scale. -struct PaintEdgelessText { - world_aabb: WorldRect, - id: String, - rect: WorldRect, - scale: f32, - rotate_deg: f32, - layout: Rc, -} - -/// Resolve a BlockSuite `{ light, dark }` color map or string color token against `theme`. -pub fn resolve_edgeless_color(value: &JsonValue, theme: PlaygroundTheme) -> Option { - let raw = match value { - JsonValue::String(s) => s.as_str(), - JsonValue::Object(map) => { - let key = match theme { - PlaygroundTheme::Light => "light", - PlaygroundTheme::Dark => "dark", - }; - map.get(key) - .and_then(JsonValue::as_str) - .or_else(|| map.get("normal").and_then(JsonValue::as_str))? - } - _ => return None, - }; - if raw.eq_ignore_ascii_case("transparent") || raw.is_empty() { - return Some(Hsla::transparent_black()); - } - theme.css_color(raw) -} - -fn prop_f32(node: &BlockNode, key: &str, default: f32) -> f32 { - node.props - .get(key) - .and_then(JsonValue::as_f64) - .map(|v| v as f32) - .filter(|v| v.is_finite()) - .unwrap_or(default) -} - -fn prop_bool(node: &BlockNode, key: &str, default: bool) -> bool { - node.props - .get(key) - .and_then(JsonValue::as_bool) - .unwrap_or(default) -} - -/// Inputs needed to prepare and build one Edgeless canvas frame. -pub struct EdgelessRenderInput<'a> { - pub snapshot: &'a PageSnapshot, - pub doc_rev: u64, - pub env_rev: u64, - pub theme: PlaygroundTheme, - pub palette: &'a Palette, - pub page_titles: &'a BTreeMap, - pub images: &'a HashMap, - pub viewport_width: f32, - pub viewport_height: f32, -} - -/// Prepare cached Note & EdgelessText layouts (zero relayout when camera moves), fit camera -/// on first render, and return the spatial canvas element plus screen-space snapshot markers. -pub fn build_edgeless_layer( - state: &mut EdgelessCanvasState, - input: &EdgelessRenderInput<'_>, - window: &Window, - zoom_controls: AnyElement, -) -> AnyElement { - state.last_frame_relayouts = 0; - - let mut frames = Vec::new(); - let mut notes = Vec::new(); - let mut texts = Vec::new(); - - if let Some(root) = &input.snapshot.root { - let mut active_notes = Vec::new(); - let mut active_texts = Vec::new(); - - for child in spatial_blocks(root) { - match &child.content { - BlockContent::Frame { title, xywh } => { - if let Some(rect) = parse_xywh(xywh) { - let fill = child - .props - .get("prop:background") - .and_then(|v| resolve_edgeless_color(v, input.theme)) - .filter(|c| !c.is_transparent()); - frames.push(PaintFrame { - id: child.id.clone(), - rect, - title: if title.plain.is_empty() { - "Frame".to_string() - } else { - title.plain.clone() - }, - fill, - }); - } - } - BlockContent::Note { - display_mode, - xywh, - background, - hidden, - } if !hidden && *display_mode != NoteDisplayMode::DocOnly => { - let mut rect = - parse_xywh(xywh).unwrap_or(WorldRect::new(0.0, 0.0, 800.0, 95.0)); - let scale = note_scale(child); - let collapse = note_collapse(child); - let border = note_border_style(child); - let border_radius = note_border_radius(child); - let shadows = input.theme.shadows(note_shadow_type(child)); - let inner_width = (rect.w / scale - 2.0 * NOTE_CARD_PADDING).max(120.0); - let key = ( - input.doc_rev, - inner_width.to_bits(), - scale.to_bits(), - input.theme, - input.env_rev, - ); - let layout = match state.note_flows.get_mut(&child.id) { - Some(cached) if cached.key == key => cached.layout.clone(), - _ => { - let flow_input = FlowInput { - snapshot: input.snapshot, - width: inner_width, - theme: input.theme, - page_titles: input.page_titles, - images: input.images, - env_rev: input.env_rev, - }; - let entry = - state.note_flows.entry(child.id.clone()).or_insert_with(|| { - CachedNoteFlow { - flow: BlockFlow::new(), - key: (u64::MAX, 0, 0, input.theme, 0), - layout: Rc::new(FlowLayout { - blocks: Vec::new(), - width: inner_width, - height: 0.0, - stats: Default::default(), - }), - } - }); - let laid_out = - entry - .flow - .layout_nodes(&child.children, &flow_input, window); - state.last_frame_relayouts += laid_out.stats.laid_out as u64; - let rc = Rc::new(laid_out); - entry.key = key; - entry.layout = rc.clone(); - rc - } - }; - if !collapse { - rect.h = rect - .h - .max((layout.height + 2.0 * NOTE_CARD_PADDING) * scale); - } - let fill = resolve_edgeless_color(background, input.theme) - .filter(|c| !c.is_transparent()) - .unwrap_or(input.palette.background); - active_notes.push(child.id.clone()); - notes.push(PaintNote { - id: child.id.clone(), - rect, - scale, - border, - border_radius, - shadows, - fill, - layout, - }); - } - BlockContent::EdgelessText { xywh } => { - if let Some(mut rect) = parse_xywh(xywh) { - let scale = prop_f32(child, "prop:scale", 1.0).clamp(0.1, 10.0); - let rotate_deg = prop_f32(child, "prop:rotate", 0.0); - let has_max_width = prop_bool(child, "prop:hasMaxWidth", true); - let text_width = if has_max_width { - (rect.w / scale).max(60.0) - } else { - (rect.w / scale).max(320.0) - }; - let key = ( - input.doc_rev, - text_width.to_bits(), - scale.to_bits(), - input.theme, - input.env_rev, - ); - let layout = match state.text_flows.get_mut(&child.id) { - Some(cached) if cached.key == key => cached.layout.clone(), - _ => { - let flow_input = FlowInput { - snapshot: input.snapshot, - width: text_width, - theme: input.theme, - page_titles: input.page_titles, - images: input.images, - env_rev: input.env_rev, - }; - let entry = state - .text_flows - .entry(child.id.clone()) - .or_insert_with(|| CachedNoteFlow { - flow: BlockFlow::new(), - key: (u64::MAX, 0, 0, input.theme, 0), - layout: Rc::new(FlowLayout { - blocks: Vec::new(), - width: text_width, - height: 0.0, - stats: Default::default(), - }), - }); - let laid_out = - entry - .flow - .layout_nodes(&child.children, &flow_input, window); - state.last_frame_relayouts += laid_out.stats.laid_out as u64; - let rc = Rc::new(laid_out); - entry.key = key; - entry.layout = rc.clone(); - rc - } - }; - rect.h = (layout.height * scale).max(rect.h); - active_texts.push(child.id.clone()); - texts.push(PaintEdgelessText { - world_aabb: rotated_bounds(rect, rotate_deg), - id: child.id.clone(), - rect, - scale, - rotate_deg, - layout, - }); - } - } - _ => {} - } - } - - if state.note_flows.len() > active_notes.len() { - state.note_flows.retain(|id, _| active_notes.contains(id)); - } - if state.text_flows.len() > active_texts.len() { - state.text_flows.retain(|id, _| active_texts.contains(id)); - } - } - - let key = (input.doc_rev, input.theme, input.env_rev); - let (surfaces, order) = match &state.surfaces { - Some(cached) if cached.key == key => (Rc::clone(&cached.layouts), Rc::clone(&cached.order)), - _ => { - let external = frames - .iter() - .map(|f| (f.id.clone(), world_bounds(f.rect, 0.))) - .chain( - notes - .iter() - .map(|n| (n.id.clone(), world_bounds(n.rect, 0.))), - ) - .chain( - texts - .iter() - .map(|t| (t.id.clone(), world_bounds(t.rect, t.rotate_deg))), - ) - .collect(); - let layouts: Rc<[SurfaceLayout]> = input - .snapshot - .root - .iter() - .flat_map(|root| &root.children) - .filter_map(|node| match &node.content { - BlockContent::Surface { elements, .. } => { - Some(layout_surface(elements, &external, input.theme, window)) - } - _ => None, - }) - .collect(); - let order: Rc<[PaintItem]> = input - .snapshot - .root - .as_ref() - .map(|root| { - let items = frames - .iter() - .enumerate() - .map(|(i, v)| (v.id.as_str(), PaintItem::Frame(i))) - .chain( - notes - .iter() - .enumerate() - .map(|(i, v)| (v.id.as_str(), PaintItem::Note(i))), - ) - .chain( - texts - .iter() - .enumerate() - .map(|(i, v)| (v.id.as_str(), PaintItem::Text(i))), - ) - .chain(layouts.iter().enumerate().flat_map(|(l, layout)| { - layout - .item_ids() - .enumerate() - .map(move |(i, id)| (id, PaintItem::Surface(l, i))) - })); - Layers::from_root(root).merge(items) - }) - .unwrap_or_default() - .into(); - state.surfaces = Some(CachedSurfaces { - key, - layouts: Rc::clone(&layouts), - order: Rc::clone(&order), - }); - (layouts, order) - } - }; - - if !state.camera_initialized && input.viewport_width > 0.0 && input.viewport_height > 0.0 { - let bounds = state.scene_world_bounds(input.snapshot); - state.camera.fit_to_bounds( - bounds, - size(px(input.viewport_width), px(input.viewport_height)), - 48.0, - ); - state.camera_initialized = true; - } - - let camera = state.camera; - let palette = *input.palette; - let theme = input.theme; - let visible_world = - camera.visible_world_bounds(size(px(input.viewport_width), px(input.viewport_height))); - - // Record screen-space snapshot markers for fully-visible spatial items so `bs-harness audit` - // and tests can inspect their screen bounds without triggering false clipping violations. - let mut snapshot_markers: Vec = Vec::new(); - let vp_origin = point(px(0.0), px(0.0)); - let push_marker = - |markers: &mut Vec, id: String, rect: WorldRect, text: Option| { - let tl = camera.world_to_screen(point(px(rect.x), px(rect.y)), vp_origin); - let br = camera.world_to_screen(point(px(rect.right()), px(rect.bottom())), vp_origin); - let x = f32::from(tl.x); - let y = f32::from(tl.y); - let w = f32::from(br.x) - x; - let h = f32::from(br.y) - y; - if x >= 0.0 - && y >= 0.0 - && x + w <= input.viewport_width - && y + h <= input.viewport_height - && w >= 1.0 - && h >= 1.0 - { - let mut el = div() - .absolute() - .left(px(x)) - .top(px(y)) - .w(px(w)) - .h(px(h)) - .snapshot(SharedString::from(id), Some(EDGELESS_VIEWPORT_ID)); - if let Some(t) = text { - el = el.snapshot_text(t); - } - markers.push(el.into_any_element()); - } - }; - - for frame in &frames { - push_marker( - &mut snapshot_markers, - format!("edgeless.frame.{}", frame.id), - frame.rect, - Some(frame.title.clone()), - ); - } - for layout in surfaces.iter() { - for (id, bounds) in layout.bounds() { - push_marker( - &mut snapshot_markers, - format!("edgeless.surface.{id}"), - world_rect(bounds), - None, - ); - } - } - for note in ¬es { - push_marker( - &mut snapshot_markers, - format!("edgeless.note.{}", note.id), - note.rect, - None, - ); - } - for et in &texts { - push_marker( - &mut snapshot_markers, - format!("edgeless.text.{}", et.id), - et.world_aabb, - None, - ); - } - - let frame_border = theme - .css_var("--affine-v2-edgeless-frame-border") - .unwrap_or(palette.border); - let frame_pill_bg = palette.panel; - - let paint_canvas = canvas( - |_, _, _| (), - move |bounds, _, window, cx| { - // 1. Single-draw-call procedural dot-grid background. - let gap = bg_grid_gap(camera.zoom); - let (phase_x, phase_y) = camera.dot_grid_phase(gap); - window.paint_quad(ui::fill( - bounds, - Background::dot_grid( - palette.background, - palette.edgeless_grid, - gap, - 1.0, - phase_x, - phase_y, - ), - )); - - let cam_matrix = camera.to_transformation_matrix(bounds.origin); - let cull_world = visible_world.dilate(120.0); - - window.with_content_mask(Some(ContentMask { bounds }), |window| { - window.with_paint_transformation(cam_matrix, |window| { - let viewport_world = Bounds::new( - point(px(visible_world.x), px(visible_world.y)), - size(px(visible_world.w), px(visible_world.h)), - ); - for item in order.iter() { - match *item { - PaintItem::Frame(i) => { - let frame = &frames[i]; - if !frame.rect.intersects(cull_world) { - continue; - } - let fb = Bounds::new( - point(px(frame.rect.x), px(frame.rect.y)), - size(px(frame.rect.w), px(frame.rect.h)), - ); - window.paint_quad(ui::quad( - fb, - Corners::all(px(FRAME_RADIUS)), - frame.fill.unwrap_or_else(Hsla::transparent_black), - Edges::all(px(1.0)), - frame_border, - BorderStyle::Solid, - )); - - // Frame title pill above top-left corner. - let title_style = InlineStyle::new( - FONT_SANS, - 12.0, - 500.0, - palette.text_secondary, - ); - let title_inline = layout_inline( - &frame.title, - &title_style, - frame.rect.w.max(80.0), - FRAME_TITLE_HEIGHT, - InlineBaseline::Of(&title_style), - InlineAlign::Left, - window, - ); - let pill_w = (title_inline.content_width() + 16.0) - .min(frame.rect.w.max(80.0)); - let pill_x = frame.rect.x; - let pill_y = frame.rect.y - FRAME_TITLE_HEIGHT - FRAME_TITLE_GAP; - window.paint_quad(ui::quad( - Bounds::new( - point(px(pill_x), px(pill_y)), - size(px(pill_w), px(FRAME_TITLE_HEIGHT)), - ), - Corners::all(px(4.0)), - frame_pill_bg, - Edges::all(px(1.0)), - palette.border, - BorderStyle::Solid, - )); - title_inline.paint(point(px(pill_x + 8.0), px(pill_y)), window, cx); - } - - PaintItem::Surface(l, i) => { - surfaces[l].paint_item(i, viewport_world, window, cx) - } - PaintItem::Note(i) => { - let note = ¬es[i]; - if !note.rect.intersects(cull_world) { - continue; - } - let nb = Bounds::new( - point(px(note.rect.x), px(note.rect.y)), - size(px(note.rect.w), px(note.rect.h)), - ); - if !note.shadows.is_empty() { - window.paint_drop_shadows( - nb, - Corners::all(px(note.border_radius)), - ¬e.shadows, - ); - } - let (border_widths, border_color, border_style) = match note.border - { - Some((style, width)) => { - (Edges::all(px(width)), palette.border, style) - } - None => ( - Edges::default(), - Hsla::transparent_black(), - BorderStyle::Solid, - ), - }; - window.paint_quad(ui::quad( - nb, - Corners::all(px(note.border_radius)), - note.fill, - border_widths, - border_color, - border_style, - )); - - let scale_transform = TransformationMatrix::unit() - .translate(point( - ScaledPixels(note.rect.x), - ScaledPixels(note.rect.y), - )) - .scale(size(note.scale, note.scale)) - .translate(point( - ScaledPixels(-note.rect.x), - ScaledPixels(-note.rect.y), - )); - let inner_bounds = Bounds::new( - point( - px(note.rect.x + NOTE_CARD_PADDING), - px(note.rect.y + NOTE_CARD_PADDING), - ), - size( - px((note.rect.w / note.scale - 2.0 * NOTE_CARD_PADDING) - .max(0.0)), - px((note.rect.h / note.scale - 2.0 * NOTE_CARD_PADDING) - .max(0.0)), - ), - ); - window.with_paint_transformation(scale_transform, |window| { - window.with_local_paint_mask( - ContentMask { - bounds: inner_bounds, - }, - |window| { - for block in ¬e.layout.blocks { - let origin = point( - px(note.rect.x + NOTE_CARD_PADDING + block.x), - px(note.rect.y + NOTE_CARD_PADDING + block.y), - ); - block.body.paint( - origin, - BlockPaint::default(), - window, - cx, - ); - } - }, - ); - }); - } - - PaintItem::Text(i) => { - let et = &texts[i]; - if !et.world_aabb.intersects(cull_world) { - continue; - } - let (cx_w, cy_w) = et.rect.center(); - let scale_from_tl = TransformationMatrix::unit() - .translate(point( - ScaledPixels(et.rect.x), - ScaledPixels(et.rect.y), - )) - .scale(size(et.scale, et.scale)) - .translate(point( - ScaledPixels(-et.rect.x), - ScaledPixels(-et.rect.y), - )); - let rotate_around_center = TransformationMatrix::unit() - .translate(point(ScaledPixels(cx_w), ScaledPixels(cy_w))) - .rotate(ui::radians(et.rotate_deg.to_radians())) - .translate(point(ScaledPixels(-cx_w), ScaledPixels(-cy_w))); - let local_transform = rotate_around_center.compose(scale_from_tl); - window.with_paint_transformation(local_transform, |window| { - for block in &et.layout.blocks { - let origin = - point(px(et.rect.x + block.x), px(et.rect.y + block.y)); - block.body.paint(origin, BlockPaint::default(), window, cx); - } - }); - } - } - } - }); - }); - }, - ) - .size_full(); - - div() - .relative() - .flex_1() - .w_full() - .min_h_0() - .overflow_hidden() - .snapshot(EDGELESS_VIEWPORT_ID, Some("root.canvas")) - .child(paint_canvas) - .children(snapshot_markers) - .child(zoom_controls) - .into_any_element() -} - -/// Build the bottom-right screen-space zoom control bar (`chrome.edgeless_zoom`). -pub fn build_zoom_controls( - zoom: f32, - palette: &Palette, - theme: PlaygroundTheme, - on_out: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, - on_reset: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, - on_in: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, - on_fit: impl Fn(&mut V, &ui::MouseDownEvent, &mut Window, &mut ui::Context) + 'static, - cx: &mut ui::Context, -) -> AnyElement { - let pct_label = format!("{}%", (zoom * 100.0).round() as i32); - let shadows = theme.shadows("--affine-toolbar-shadow"); - - let button = |id: &'static str, snap_id: &'static str, label: String, width: f32| { - div() - .id(id) - .w(px(width)) - .h(px(ZOOM_BTN_HEIGHT)) - .rounded(px(ZOOM_BTN_RADIUS)) - .flex() - .items_center() - .justify_center() - .text_size(px(12.0)) - .font_weight(ui::FontWeight::MEDIUM) - .text_color(palette.text_primary) - .cursor_pointer() - .hover(|s| s.bg(palette.hover)) - .snapshot(snap_id, Some("chrome.edgeless_zoom")) - .snapshot_text(label.clone()) - .child(label) - }; - - let mut bar = div() - .absolute() - .right(px(ZOOM_BAR_MARGIN)) - .bottom(px(ZOOM_BAR_MARGIN)) - .p(px(ZOOM_BAR_PAD)) - .rounded(px(ZOOM_BAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .flex() - .items_center() - .gap(px(4.0)) - .snapshot("chrome.edgeless_zoom", Some(EDGELESS_VIEWPORT_ID)) - .child( - button( - "edgeless-zoom-out", - "chrome.edgeless_zoom.out", - "-".into(), - 28.0, - ) - .on_mouse_down(MouseButton::Left, cx.listener(on_out)), - ) - .child( - button( - "edgeless-zoom-reset", - "chrome.edgeless_zoom.reset", - pct_label, - 48.0, - ) - .on_mouse_down(MouseButton::Left, cx.listener(on_reset)), - ) - .child( - button( - "edgeless-zoom-in", - "chrome.edgeless_zoom.in", - "+".into(), - 28.0, - ) - .on_mouse_down(MouseButton::Left, cx.listener(on_in)), - ) - .child( - button( - "edgeless-zoom-fit", - "chrome.edgeless_zoom.fit", - "Fit".into(), - 36.0, - ) - .on_mouse_down(MouseButton::Left, cx.listener(on_fit)), - ); - - if !shadows.is_empty() { - bar = bar.shadow(shadows.into()); - } - - bar.into_any_element() -} diff --git a/blocksuite/native-playground/crates/playground/src/editor_session.rs b/blocksuite/native-playground/crates/playground/src/editor_session.rs index 642da8cdc8..8010703cc9 100644 --- a/blocksuite/native-playground/crates/playground/src/editor_session.rs +++ b/blocksuite/native-playground/crates/playground/src/editor_session.rs @@ -160,6 +160,21 @@ impl EditorSession { pub(crate) fn composing(&self) -> bool { self.preedit.is_some() } + + pub(crate) fn clear_preedit_state(&mut self) { + self.preedit = None; + } + + pub(crate) fn preedit_nonce(&self) -> u64 { + self.preedit.as_ref().map_or(0u64, |pre| { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + pre.text.hash(&mut hasher); + pre.selected.hash(&mut hasher); + pre.backward.hash(&mut hasher); + hasher.finish().max(1) + }) + } } fn word_range(text: &str, offset: u64) -> Range { @@ -308,7 +323,12 @@ impl PlaygroundView { self.change_selection(selection, w, cx); } - fn change_selection(&mut self, sel: DocumentSelection, w: &mut Window, cx: &mut Context) { + pub(crate) fn change_selection( + &mut self, + sel: DocumentSelection, + w: &mut Window, + cx: &mut Context, + ) { if self.editor.preedit.take().is_some() { self.dirty_text = None; self.doc_rev += 1; @@ -755,7 +775,7 @@ impl PlaygroundView { } Some(snapshot) } - fn clear_composition(&mut self, w: &mut Window, cx: &mut Context) { + pub(crate) fn clear_composition(&mut self, w: &mut Window, cx: &mut Context) { if let Some(sel) = self.composition_selection() { self.editor.selection = Some(sel); } @@ -771,7 +791,7 @@ impl PlaygroundView { cx.notify(); } } - fn visual_focus(&self) -> Option { + pub(crate) fn visual_focus(&self) -> Option { if let Some((id, r)) = self.composed_range() { return Some(DocPoint::new( id, @@ -1201,10 +1221,20 @@ impl PlaygroundView { impl EntityInputHandler for PlaygroundView { fn paste(&mut self, item: ui::ClipboardItem, w: &mut Window, cx: &mut Context) { - let text = item.text().unwrap_or_default(); - if self - .link_input(w, cx, |link| link.replace(None, &text)) - .is_some() + if self.overlays.link_field().is_some() { + if let Some(text) = item.text() { + let _ = self.link_input(w, cx, |link| link.replace(None, &text)); + } + return; + } + if self.edgeless.authoring.label_editor().is_some() { + if let Some(text) = item.text() { + let _ = self.edgeless_label_edit(w, cx, |ed| ed.replace(None, &text)); + } + return; + } + if self.mode == crate::PlaygroundMode::Edgeless + && self.edgeless.authoring.editing_spatial_block().is_none() { return; } @@ -1227,6 +1257,11 @@ impl EntityInputHandler for PlaygroundView { *adjusted = Some(covered); return Some(text); } + if let Some(ed) = self.edgeless.authoring.label_editor() { + let (text, covered) = ed.text_for_range(range); + *adjusted = Some(covered); + return Some(text); + } let text = self.display_text()?; let index = TextBiIndex::new(&text); let start = index.utf16_to_utf8_clamped(range.start as u64); @@ -1244,6 +1279,10 @@ impl EntityInputHandler for PlaygroundView { let (range, reversed) = link.shown_selection(); return Some(UTF16Selection { range, reversed }); } + if let Some(ed) = self.edgeless.authoring.label_editor() { + let (range, reversed) = ed.shown_selection(); + return Some(UTF16Selection { range, reversed }); + } if let Some((_, r)) = self.composed_range() && let Some(pre) = &self.editor.preedit { @@ -1268,6 +1307,9 @@ impl EntityInputHandler for PlaygroundView { if let Some(link) = self.overlays.link_field() { return Some(link.text().encode_utf16().count()); } + if let Some(ed) = self.edgeless.authoring.label_editor() { + return Some(ed.display_text().encode_utf16().count()); + } Some(self.display_text()?.encode_utf16().count()) } fn set_selected_text_range(&mut self, r: Range, w: &mut Window, cx: &mut Context) { @@ -1277,6 +1319,12 @@ impl EntityInputHandler for PlaygroundView { { return; } + if self + .edgeless_label_input(w, cx, |ed| ed.select(r.clone())) + .is_some() + { + return; + } if let Some(focus) = self.visual_focus() { self.change_selection( DocumentSelection { @@ -1292,6 +1340,9 @@ impl EntityInputHandler for PlaygroundView { if let Some(link) = self.overlays.link_field() { return link.marked_range(); } + if let Some(ed) = self.edgeless.authoring.label_editor() { + return ed.marked_range(); + } let (_, r) = self.composed_range()?; let start = r.start as usize; Some(start..start + self.editor.preedit.as_ref()?.text.encode_utf16().count()) @@ -1300,6 +1351,17 @@ impl EntityInputHandler for PlaygroundView { if self.link_input(w, cx, LinkBar::unmark).is_some() { return; } + if self + .edgeless_label_edit(w, cx, crate::edgeless::EdgelessLabelEditor::unmark) + .is_some() + { + return; + } + if self.mode == crate::PlaygroundMode::Edgeless + && self.edgeless.authoring.editing_spatial_block().is_none() + { + return; + } if let Some(pre) = self.editor.preedit.as_ref() { let text = pre.text.clone(); self.replace_text_in_range(None, &text, w, cx); @@ -1318,6 +1380,17 @@ impl EntityInputHandler for PlaygroundView { { return; } + if self + .edgeless_label_edit(w, cx, |ed| ed.replace(r.clone(), text)) + .is_some() + { + return; + } + if self.mode == crate::PlaygroundMode::Edgeless + && self.edgeless.authoring.editing_spatial_block().is_none() + { + return; + } self.begin_input(); let selection = self.replacement_selection(r); if self.editor.preedit.is_some() { @@ -1346,6 +1419,17 @@ impl EntityInputHandler for PlaygroundView { { return; } + if self + .edgeless_label_input(w, cx, |ed| ed.mark(r.clone(), text, selected.clone())) + .is_some() + { + return; + } + if self.mode == crate::PlaygroundMode::Edgeless + && self.edgeless.authoring.editing_spatial_block().is_none() + { + return; + } self.begin_input(); if text.is_empty() { self.clear_composition(w, cx); @@ -1357,6 +1441,8 @@ impl EntityInputHandler for PlaygroundView { let Some(page) = self.page() else { return }; let backward = if let Some(pre) = &self.editor.preedit { pre.backward + } else if sel.empty() { + false } else { let Some(layout) = self.flow_layout() else { return; @@ -1409,6 +1495,21 @@ impl EntityInputHandler for PlaygroundView { .into_iter() .collect(); } + if self.mode == crate::PlaygroundMode::Edgeless { + if let Some(bounds) = self.edgeless_label_screen_bounds() { + return vec![bounds]; + } + if let Some(sel) = &self.editor.selection { + let id = self + .composed_range() + .map(|(id, _)| id) + .unwrap_or_else(|| sel.focus.block_id.clone()); + if let Some(bounds) = self.edgeless_spatial_block_caret_bounds(&id, r.start as u64) + { + return vec![bounds]; + } + } + } let Some(sel) = &self.editor.selection else { return vec![]; }; @@ -1926,12 +2027,52 @@ impl PlaygroundView { Ok(()) } + pub(crate) fn hit_test_flow_layout(layout: &FlowLayout, x: f32, y: f32) -> Option { + let block = layout + .blocks + .iter() + .filter(|b| b.editable()) + .min_by(|a, b| { + let ar = a.rect(); + let br = b.rect(); + let da = if y < ar.y { + ar.y - y + } else if y > ar.bottom() { + y - ar.bottom() + } else { + 0.0 + }; + let db = if y < br.y { + br.y - y + } else if y > br.bottom() { + y - br.bottom() + } else { + 0.0 + }; + da.total_cmp(&db) + })?; + Some(DocPoint { + block_id: block.block_id.clone(), + caret: block.hit_text(x, y)?, + }) + } + pub(super) fn editor_key_down( &mut self, e: &KeyDownEvent, w: &mut Window, cx: &mut Context, ) { + if self.mode == crate::PlaygroundMode::Edgeless { + if self.edgeless_key_down(e, w, cx) { + w.prevent_default(); + cx.stop_propagation(); + return; + } + if self.edgeless.authoring.editing_spatial_block().is_none() { + return; + } + } if self.editor.preedit.is_some() || e.prefer_character_input { return; } diff --git a/blocksuite/native-playground/crates/playground/src/lib.rs b/blocksuite/native-playground/crates/playground/src/lib.rs index 36d09b8f79..5a3e2fb399 100644 --- a/blocksuite/native-playground/crates/playground/src/lib.rs +++ b/blocksuite/native-playground/crates/playground/src/lib.rs @@ -6,9 +6,7 @@ pub mod block_flow; pub mod clipboard; -pub mod edgeless_camera; -pub mod edgeless_canvas; -mod edgeless_order; +pub mod edgeless; pub mod editor_session; pub mod overlays; pub mod rich_text; @@ -202,7 +200,7 @@ pub struct PlaygroundView { max_scroll: f32, /// Window size of the latest frame, in logical pixels. window_size: (f32, f32), - edgeless: edgeless_canvas::EdgelessCanvasState, + edgeless: edgeless::EdgelessCanvasState, overlays: Overlays, /// Timer that ends a code block's `Copied` label; a newer copy replaces it. copied_timer: Option>, @@ -287,7 +285,7 @@ impl PlaygroundView { scroll_y: 0.0, max_scroll: 0.0, window_size: (0.0, 0.0), - edgeless: edgeless_canvas::EdgelessCanvasState::new(), + edgeless: edgeless::EdgelessCanvasState::new(), overlays: Overlays::new(), copied_timer: None, _tasks: tasks, @@ -304,7 +302,7 @@ impl PlaygroundView { self.theme } - pub fn edgeless_camera(&self) -> edgeless_camera::EdgelessCamera { + pub fn edgeless_camera(&self) -> edgeless::EdgelessCamera { self.edgeless.camera } @@ -372,22 +370,6 @@ impl PlaygroundView { cx.notify(); } - fn on_edgeless_pan_move( - &mut self, - event: &ui::MouseMoveEvent, - _: &mut Window, - cx: &mut Context, - ) { - if let Some(prev) = self.edgeless.drag_pan_anchor { - let dx = f32::from(event.position.x) - f32::from(prev.x); - let dy = f32::from(event.position.y) - f32::from(prev.y); - self.edgeless.camera.pan_by_screen_delta(dx, dy); - self.edgeless.drag_pan_anchor = Some(event.position); - self.edgeless.camera_initialized = true; - cx.notify(); - } - } - fn on_edgeless_pan_end( &mut self, _: &ui::MouseUpEvent, @@ -445,8 +427,14 @@ impl PlaygroundView { self.snapshot.as_deref() } - /// World-space layout painted by the latest Page frame. + /// World-space layout painted by the latest Page frame, or the active inline-edited + /// Edgeless Note/EdgelessText layout when editing on the Edgeless canvas. pub fn flow_layout(&self) -> Option> { + if self.mode == PlaygroundMode::Edgeless + && let Some((block_id, is_note)) = self.edgeless.authoring.editing_spatial_block() + { + return self.edgeless.cached_block_layout(block_id, is_note); + } self.layout.as_ref().map(|(_, layout)| layout.clone()) } @@ -619,6 +607,7 @@ impl PlaygroundView { .filter(|snapshot| snapshot.root.is_some()) .map(Rc::new); self.doc_rev += 1; + self.edgeless_refresh_label_editor_from_snapshot(); let mut referenced = BTreeSet::new(); for node in self @@ -682,12 +671,21 @@ impl PlaygroundView { } } - fn set_mode(&mut self, target: PlaygroundMode, cx: &mut Context) { + fn set_mode(&mut self, target: PlaygroundMode, window: &mut Window, cx: &mut Context) { if self.mode == target { return; } let now_ms = self.now_ms(cx); let current_x = self.indicator_x(now_ms); + // Commit any pending inline Edgeless edit cleanly before switching modes. + self.edgeless_flush_label_edit(window, cx); + if self.edgeless.authoring.editing_spatial_block().is_some() { + self.edgeless.authoring.inline_edit = None; + self.editor.clear_preedit_state(); + self.editor.selection = None; + self.announce_selection(cx); + } + self.edgeless.authoring.reset_transient(); self.mode = target; self.overlays.reset(); self.pill_motion = Some(Motion::new( @@ -877,8 +875,8 @@ impl PlaygroundView { }; let page_button = segment("mode-page", PILL_PAGE_X, is_page) - .on_click(cx.listener(|this, _, _, cx| { - this.set_mode(PlaygroundMode::Page, cx); + .on_click(cx.listener(|this, _, window, cx| { + this.set_mode(PlaygroundMode::Page, window, cx); })) .snapshot("chrome.mode_switcher.page", Some("chrome.mode_switcher")) .snapshot_focused(is_page) @@ -886,8 +884,8 @@ impl PlaygroundView { .child("Page"); let edgeless_button = segment("mode-edgeless", PILL_EDGELESS_X, is_edgeless) - .on_click(cx.listener(|this, _, _, cx| { - this.set_mode(PlaygroundMode::Edgeless, cx); + .on_click(cx.listener(|this, _, window, cx| { + this.set_mode(PlaygroundMode::Edgeless, window, cx); })) .snapshot( "chrome.mode_switcher.edgeless", @@ -1256,33 +1254,41 @@ impl PlaygroundView { .w_full() .min_h_0() .bg(palette.background_secondary) - .snapshot(edgeless_canvas::EDGELESS_VIEWPORT_ID, Some("root.canvas")) + .snapshot(edgeless::EDGELESS_VIEWPORT_ID, Some("root.canvas")) .into_any_element(); }; let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT)); let vp_size = size(px(viewport_width.max(1.0)), px(viewport_height.max(1.0))); + if viewport_width > 0.0 && viewport_height > 0.0 { + self.edgeless.ensure_camera_initialized(&snapshot, vp_size); + } - let zoom_controls = edgeless_canvas::build_zoom_controls( + let zoom_controls = edgeless::build_zoom_controls( self.edgeless.camera.zoom, + viewport_width, palette, self.theme, move |this: &mut Self, _, _, cx| { + cx.stop_propagation(); this.edgeless.camera.zoom_out(vp_origin, vp_size); this.edgeless.camera_initialized = true; cx.notify(); }, move |this: &mut Self, _, _, cx| { + cx.stop_propagation(); this.edgeless.camera.reset_zoom(vp_origin, vp_size); this.edgeless.camera_initialized = true; cx.notify(); }, move |this: &mut Self, _, _, cx| { + cx.stop_propagation(); this.edgeless.camera.zoom_in(vp_origin, vp_size); this.edgeless.camera_initialized = true; cx.notify(); }, move |this: &mut Self, _, _, cx| { + cx.stop_propagation(); if let Some(snap) = &this.snapshot { let bounds = this.edgeless.scene_world_bounds(snap); this.edgeless.camera.fit_to_bounds(bounds, vp_size, 48.0); @@ -1292,39 +1298,86 @@ impl PlaygroundView { }, cx, ); + let toolbar = edgeless::build_edgeless_toolbar( + self.edgeless.authoring.tool, + viewport_width, + palette, + self.theme, + cx, + ); - let input = edgeless_canvas::EdgelessRenderInput { - snapshot: &snapshot, + let render_snapshot = self + .preedit_snapshot() + .map(Rc::new) + .unwrap_or_else(|| Rc::clone(&snapshot)); + let preedit_nonce = self.editor.preedit_nonce(); + let editing_selection = + self.edgeless + .authoring + .editing_spatial_block() + .and_then(|(editing_id, is_note)| { + let sel = self.editor.selection.clone()?; + let focus = self.visual_focus()?; + Some((editing_id.to_string(), is_note, sel, focus)) + }); + + let input = edgeless::EdgelessRenderInput { + snapshot: &render_snapshot, doc_rev: self.doc_rev, env_rev: self.env_rev, + preedit_nonce, theme: self.theme, palette, page_titles: &self.page_titles, images: &self.images, viewport_width, viewport_height, + editing_selection, }; - let layer = edgeless_canvas::build_edgeless_layer( + let layer = edgeless::build_edgeless_layer( &mut self.edgeless, &input, window, zoom_controls, + toolbar, ); + let needs_text_input = + self.edgeless.authoring.inline_edit.is_some() || self.overlays.link_field().is_some(); + let input_overlay = needs_text_input.then(|| { + let focus = self.editor_focus.clone(); + let entity = cx.entity(); + canvas( + |_, _, _| (), + move |bounds, _, window, cx| { + window.handle_input(&focus, ui::ElementInputHandler::new(bounds, entity), cx) + }, + ) + .absolute() + .size_full() + }); div() + .relative() .flex_1() .w_full() .min_h_0() .flex() .flex_col() + .track_focus(&self.editor_focus) + .on_key_down(cx.listener(Self::editor_key_down)) + .on_key_up(cx.listener(|this, event: &ui::KeyUpEvent, _, _| { + if event.keystroke.key == "space" { + this.edgeless.authoring.space_pan = false; + } + })) .on_scroll(cx.listener(Self::on_edgeless_scroll)) + .on_mouse_down(MouseButton::Left, cx.listener(Self::on_edgeless_left_down)) .on_mouse_down( MouseButton::Middle, cx.listener(Self::on_edgeless_pan_start), ) - .on_mouse_move(cx.listener(Self::on_edgeless_pan_move)) - .on_mouse_up(MouseButton::Middle, cx.listener(Self::on_edgeless_pan_end)) .child(layer) + .children(input_overlay) .into_any_element() } } @@ -1381,6 +1434,14 @@ impl ui::Render for PlaygroundView { .text_color(palette.text_primary) .on_mouse_move(cx.listener(Self::root_mouse_move)) .on_mouse_up(MouseButton::Left, cx.listener(Self::root_mouse_up)) + .on_mouse_up( + MouseButton::Middle, + cx.listener(|this, e, w, cx| { + if this.mode == PlaygroundMode::Edgeless { + this.on_edgeless_pan_end(e, w, cx); + } + }), + ) .snapshot("root.canvas", None) .child( div() @@ -4616,7 +4677,7 @@ mod tests { (note_layout.width, text_layout.width, lines) }); assert!( - (note_w - (400.0 / 2.0 - 2.0 * edgeless_canvas::NOTE_CARD_PADDING)).abs() < 0.01, + (note_w - (400.0 / 2.0 - 2.0 * edgeless::NOTE_CARD_PADDING)).abs() < 0.01, "expected Note logical width 152.0, got {note_w}" ); assert!( diff --git a/blocksuite/native-playground/crates/playground/src/overlays.rs b/blocksuite/native-playground/crates/playground/src/overlays.rs index 6ddb10cfb9..27fd361f82 100644 --- a/blocksuite/native-playground/crates/playground/src/overlays.rs +++ b/blocksuite/native-playground/crates/playground/src/overlays.rs @@ -94,13 +94,12 @@ const POPOVER_BORDER: f32 = 1.0; /// Side of the gutter drag handle's hit target. pub const DRAG_HANDLE_SIZE: f32 = 24.0; -/// The handle at rest: BlockSuite's upright grabber bar. +/// The Page-mode handle at rest: BlockSuite's 4 × 12 px upright grabber bar. const DRAG_GRABBER_WIDTH: f32 = 4.0; +/// The Page-mode handle under the pointer or in a drag: narrows to a 2 × 12 px vertical bar +/// (the 2 × 3 six-dot pill is reserved for Edgeless `gfx` drag handles). +const DRAG_GRABBER_HOT_WIDTH: f32 = 2.0; const DRAG_GRABBER_HEIGHT: f32 = 12.0; -/// The handle under the pointer or in a drag: two columns of three dots on a pill. -const DRAG_DOTS_PILL_WIDTH: f32 = 14.0; -const DRAG_DOT: f32 = 4.0; -const DRAG_DOT_GAP: f32 = 2.0; /// Closest the drag handle comes to the left window edge. pub const DRAG_HANDLE_MIN_X: f32 = 4.0; /// Thickness of the drop indicator line. @@ -885,10 +884,19 @@ impl LinkBar { start..end } + /// Abandon any running composition, restoring the original URL and selection. + pub(crate) fn cancel_preedit(&mut self) { + self.preedit = None; + } + /// Put `text` in place of a running composition, else of `range`, else of the /// selection, and leave the caret behind it. Control characters are dropped: the /// field is one line. pub(crate) fn replace(&mut self, range: Option>, text: &str) { + if self.preedit.is_some() && text.is_empty() { + self.cancel_preedit(); + return; + } let target = match self.preedit.take() { Some(preedit) => preedit.replacement, None => range.map_or(self.selection.clone(), |range| self.clamped(range)), @@ -2357,49 +2365,19 @@ impl Overlays { .snapshot_focused(dragging) .snapshot_text(block.block_id.clone()); } - // BlockSuite's grabber: an upright bar while the pointer is on the block, and - // two columns of dots on a pill once it is on the handle or drags it. + // BlockSuite's Page-mode grabber: a 4 × 12 px bar while the pointer is on the + // block's row, narrowing to a 2 × 12 px vertical bar when hovered or dragged. let theme = palette.theme; let grip = if dragging || self.handle_hot { - let dots = theme + let color = theme .css_var("--affine-v2-icon-secondary") .unwrap_or(palette.icon); div() .flex_none() - .w(px(DRAG_DOTS_PILL_WIDTH)) - .h(px(DRAG_HANDLE_SIZE)) - .rounded(px(4.0)) - .bg(theme - .css_var("--affine-v2-layer-background-hoverOverlay") - .unwrap_or(palette.hover)) - .flex() - .items_center() - .justify_center() - .child( - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - for row in 0..3 { - for column in 0..2 { - let step = DRAG_DOT + DRAG_DOT_GAP; - let dot = ui::Bounds::new( - point( - bounds.origin.x + px(column as f32 * step), - bounds.origin.y + px(row as f32 * step), - ), - size(px(DRAG_DOT), px(DRAG_DOT)), - ); - window.paint_quad( - ui::fill(dot, dots).corner_radii(px(DRAG_DOT / 2.0)), - ); - } - } - }, - ) - .flex_none() - .w(px(2.0 * DRAG_DOT + DRAG_DOT_GAP)) - .h(px(3.0 * DRAG_DOT + 2.0 * DRAG_DOT_GAP)), - ) + .w(px(DRAG_GRABBER_HOT_WIDTH)) + .h(px(DRAG_GRABBER_HEIGHT)) + .rounded(px(1.0)) + .bg(color) } else { div() .flex_none() @@ -3299,7 +3277,9 @@ impl PlaygroundView { if effects.paste { match cx.read_from_clipboard() { Some(item) => { - self.overlays.link_insert(&item.text().unwrap_or_default()); + if let Some(text) = item.text() { + self.overlays.link_insert(&text); + } } // A browser hands a paste over as an event of its own, and only when the // key keeps its default action; that event reaches the link field through @@ -3353,6 +3333,10 @@ impl PlaygroundView { window, cx, ); + if self.mode == PlaygroundMode::Edgeless { + self.on_edgeless_pointer_move(event, window, cx); + return; + } if self.mode == PlaygroundMode::Page && self.overlays.dragged_block().is_none() { let selecting = self.editor.dragging; self.editor_mouse_move(event, window, cx); @@ -3364,10 +3348,13 @@ impl PlaygroundView { pub(crate) fn root_mouse_up( &mut self, - _: &MouseUpEvent, + event: &MouseUpEvent, window: &mut Window, cx: &mut Context, ) { + if self.mode == PlaygroundMode::Edgeless { + self.on_edgeless_left_up(event, window, cx); + } // The selection is finished: the formatting toolbar may open over it. if std::mem::take(&mut self.editor.dragging) { cx.notify(); @@ -6409,4 +6396,69 @@ mod tests { f32::from(moved.origin.x) )); } + + #[test] + fn link_bar_empty_replace_during_preedit_restores_url_and_selection() { + let mut bar = LinkBar::new("abc".into()); + bar.select(1..2); + assert_eq!(bar.selected_text(), "b"); + bar.mark(None, "ni", None); + assert!(bar.composing()); + assert_eq!(bar.text(), "anic"); + // Chromium sends compositionend("") on IME cancel: must restore "abc" with "b" selected. + bar.replace(None, ""); + assert!(!bar.composing()); + assert_eq!(bar.url(), "abc"); + assert_eq!(bar.selected_text(), "b"); + assert_eq!(bar.shown_selection(), (1..2, false)); + } + + #[test] + fn link_bar_non_text_clipboard_paste_does_not_erase_selection() { + let session = open(1280, 800, PlaygroundTheme::Light); + let _ = session.frame(); + session.select("showcase-intro", "bold"); + let _ = session.frame(); + session.overlay(OverlayEvent::Format(FormatAction::Link)); + let _ = session.frame(); + session.update(|view, _window, cx| { + if let Some(link) = view.overlays.link_field_mut() { + link.replace(Some(0..0), "https://affine.pro"); + link.select(0..18); + } + // Write a non-text ClipboardItem (`text() == None`). + let item = ClipboardItem { + entries: vec![ui::ClipboardEntry::ExternalPaths( + ui::ExternalPaths::default(), + )], + }; + assert_eq!(item.text(), None); + cx.write_to_clipboard(item); + }); + let _ = session.frame(); + // Trigger Ctrl/Cmd+V in the link field. + let _ = session.update(|view, window, cx| { + let mut m = ui::Modifiers::default(); + #[cfg(target_os = "macos")] + { + m.platform = true; + } + #[cfg(not(target_os = "macos"))] + { + m.control = true; + } + let event = KeyDownEvent { + keystroke: ui::Keystroke { + modifiers: m, + key: "v".into(), + key_char: Some("v".into()), + }, + is_held: false, + prefer_character_input: false, + }; + view.overlay_key_down(&event, window, cx) + }); + let url = session.view(|view, _| view.overlays().link_url().map(str::to_string)); + assert_eq!(url.as_deref(), Some("https://affine.pro")); + } } diff --git a/blocksuite/native-playground/crates/playground/src/surface/connector.rs b/blocksuite/native-playground/crates/playground/src/surface/connector.rs index f2d4952b40..02cfad5fe4 100644 --- a/blocksuite/native-playground/crates/playground/src/surface/connector.rs +++ b/blocksuite/native-playground/crates/playground/src/surface/connector.rs @@ -135,18 +135,21 @@ pub(super) struct Route { } impl Route { pub(super) fn point_at_distance(&self, mode: ConnectorMode, t: f64) -> P { - if mode == ConnectorMode::Orthogonal { - return along(&self.samples, t); - } - let a = self.contour.start; - let (b, c, d) = match self.contour.edges[..] { - [Edge::Cubic(b, c, d)] => (b, c, d), - _ => { - let d = *self.samples.last().unwrap(); - (a, d, d) + match mode { + ConnectorMode::Straight => self.contour.start.lerp(*self.samples.last().unwrap(), t), + ConnectorMode::Orthogonal => along(&self.samples, t), + ConnectorMode::Curve => { + let a = self.contour.start; + let (b, c, d) = match self.contour.edges[..] { + [Edge::Cubic(b, c, d)] => (b, c, d), + _ => { + let d = *self.samples.last().unwrap(); + (a, d, d) + } + }; + cubic(a, b, c, d, t) } - }; - cubic(a, b, c, d, t) + } } /// Endpoint and inward-facing tangent for each cap. A stationary Bézier endpoint @@ -323,11 +326,8 @@ mod tests { } #[test] - fn labels_follow_the_bezier_parameter_for_curve_and_straight() { - for (mode, end, expected) in [ - (2, [180, 60], P(61.875, 9.375)), - (0, [100, 0], P(15.625, 0.)), - ] { + fn labels_follow_the_bezier_parameter_for_curve_and_linear_for_straight() { + for (mode, end, expected) in [(2, [180, 60], P(61.875, 9.375)), (0, [100, 0], P(25., 0.))] { let e = SurfaceElement::from_properties( "line".into(), json!({"type":"connector","mode":mode,"source":{"position":[0,0]},"target":{"position":end}}), diff --git a/blocksuite/native-playground/crates/playground/src/surface/paint.rs b/blocksuite/native-playground/crates/playground/src/surface/paint.rs index 412e4c053a..a14911ff33 100644 --- a/blocksuite/native-playground/crates/playground/src/surface/paint.rs +++ b/blocksuite/native-playground/crates/playground/src/surface/paint.rs @@ -44,6 +44,8 @@ struct Item { label: Option