fix(doc,editor,playground): align desktop page, table, menu, and edgeless interactions

- Remove unselected root-title input fallback and the obsolete suppression flag so typing without an active selection never mutates the page title.
- Insert new headings after collapsed siblings on Enter, expand collapsed parents when indenting blocks into them, include hidden blocks in select-all block operations, and renumber following numbered list runs when an item converts out or is deleted.
- Support multi-block Tab/Shift+Tab indent and outdent, block-selection arrow/Shift+arrow navigation and batch conversion shortcuts, single-block Enter end focus, PageUp/PageDown, Mod+Enter block exit, and backtick/bracket selection wrapping.
- Consume desktop clicks inside database blocks without whole-block selection, allow inter-word spaces in slash queries, hide empty slash popovers, add Table/Equation/Database slash items, and sync @ linked-doc Tab and caret bounds.
- Add atomic multi-block drag-handle reordering, word and paragraph drag-selection extension in Page body and table cells, wide-table horizontal auto-reveal, and Shift+wheel horizontal scrolling.
- Protect Frame children from partial marquee deletion and preserve the last Page-visible note in Edgeless, defer double-click inline edit to drag-free mouse release, fix rotated resize and Shift constraints, auto-grow Shape labels, and add connector endpoint handles, port snapping, Alt+drag clone, Group/Ungroup, and Edgeless copy/cut.
This commit is contained in:
DarkSky committed 2026-11-29 00:32:26 +09:00
1 parent 0eff077e0d
commit 92bca9f25b
57 files changed
+6447 -1312

No files matched your search

+3 -3
View File
@@ -38,12 +38,12 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
- **Positioner**: `place_popover` is pure and works in screen space below the top bar: `Above` (formatting toolbar, centered on the selection) and `BelowStart` (slash menu, at the caret) flip to the other side when the preferred one would come closer than the edge margin to the top bar or the window bottom, and clamp horizontally inside the margins. Results are on the pixel grid.
- **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. Checking an unchecked to-do box triggers a closed-form 600 ms ease-out 6-dot radial pulse (`todo_pulses`) that clears at completion. Active editing carets (Page body and in-place table cells) blink with a closed-form 500 ms on / 500 ms off scheduler-clock cycle (`caret_blink_alpha`), resetting solid for 500 ms on any click, focus, key, or edit while keeping `FrameSnapshot` geometry and opacity invariant across frame rates. Nothing here loops per frame.
- **Desktop viewport scrollbar & overlay context menu**: On `FormFactor::Desktop` Page viewports (non-touch form factor, `max_scroll > 0`), `overlay.page_scrollbar` (24 px interactive gutter on the logical inline-end edge: right in LTR, left in RTL) mounts an 8 px rounded translucent `overlay.page_scrollbar.thumb` (min height 32 px) supporting thumb dragging and track page-jumps; `FormFactor::Phone` and `FormFactor::Tablet` hide the desktop scrollbar. Right-clicking on desktop Page or Edgeless inline-edit surfaces opens `overlay.context_menu` (`.copy`, `.cut`, `.paste`, plus `.open_link` and `.copy_link` when right-clicking an inline link or Bookmark block, with `Up`/`Down`/`Enter`/`Escape` keyboard navigation; Page mode resolves links strictly at the right-click coordinates, and touch form factors or mobile read-only mode suppress the desktop menu); `Paste` falls back to a 2.2 s scheduler-timed `overlay.context_menu.toast` when platform clipboard read is unavailable.
- **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.<id>`, `.group.<name>`, `.query`, `.empty`): Typing `/` at a caret in paragraph or list text, outside inline code, opens it on that character, remembered as a relative position (`EditorSession::slash_trigger`): text a peer inserts before the `/` moves the menu along. The text between the `/` and the caret is both document text and the filter (`query_in_document`); the menu closes when the caret leaves that text, whitespace follows the `/`, or the character at the position is no longer that `/` (deleted, or deleted and typed again by a peer), and a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Filtering uses case- and whitespace-insensitive subsequence matching (`isFuzzyMatch`); without matches the list keeps a `No results` row. Items follow BlockSuite's order in two groups (`Basic`: text, the six headings, code block, quote, divider, new doc [`SlashCommand::NewDoc`], linked doc [`SlashCommand::LinkedDoc`]; `List`: bulleted, numbered, to-do, toggle); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 44 px (title plus description subtitle, with group headers hidden while filtering), and the menu has no border, only its shadow.
- **Linked-doc `@` menu** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.<idx>`, `overlay.linked_doc_menu.create`): Typing `@` anywhere in paragraph or list text (outside inline code), or typing `[[` or `【【` (which converts the pair into `@`), opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types. `Up`/`Down` move selection across matched docs and the trailing Create row, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, and `Escape` closes the menu while leaving the typed text intact.
- **Slash menu** (`overlay.slash_menu`, rows `overlay.slash_menu.item.<id>`, `.group.<name>`, `.query`): 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`); inter-word spaces are allowed (e.g. `/heading 1`, `/code block`, `/new doc`), while leading whitespace (`/ `), newlines, consecutive spaces, or trailing whitespace with no matches close the trigger, as does leaving the text or deleting/replacing the `/`; a command never runs on text it did not open on. `Escape` leaves the text as typed. `OpenSlashMenu` opens the menu with a filter of its own, shown in a query row and edited by the menu's keys. Filtering uses case- and whitespace-insensitive subsequence matching (`isFuzzyMatch`); when no items match, the popover is hidden so ordinary URLs, paths, and dates never leave a `No results` card obscuring body text below. Items follow BlockSuite's order in three groups (`Basic`: text, the six headings, code block, quote, divider, new doc [`SlashCommand::NewDoc`], linked doc [`SlashCommand::LinkedDoc`]; `List`: bulleted, numbered, to-do, toggle; `Content & Media`: table [`SlashCommand::Table`], equation [`SlashCommand::Equation`], database [`SlashCommand::Database`], omitted when `database_readonly`); all six headings stay in the list itself so each is one filter away. Each icon sits in a bordered 28 px box, rows are 44 px (title plus description subtitle, with group headers hidden while filtering), and the menu has no border, only its shadow.
- **Linked-doc `@` menu** (`overlay.linked_doc_menu`, rows `overlay.linked_doc_menu.item.<idx>`, `overlay.linked_doc_menu.create`): Typing `@` anywhere in paragraph or list text (outside inline code), or typing `[[` or `【【` (which converts the pair into `@`), opens the linked-doc popover anchored at the caret (`EditorSession::linked_doc_trigger`), querying the active `WorkspaceDocDirectory` as the user types. `Up`/`Down`/`Tab`/`Shift+Tab` move selection across matched docs and the trailing Create row without indenting the underlying block, `Enter` selects or creates the linked doc and replaces `@query` with a BlockSuite `InlineReference` (`LinkedPage`) chip in one undo step, `Escape` closes the menu while leaving the typed text intact, and selection changes (`←`/`→`, clicks, remote edits) sync `sync_linked_doc_trigger` so moving before `@` or leaving the trigger range closes the menu immediately.
- **Formatting toolbar** (`overlay.format_toolbar`, buttons `.bold`, `.italic`, `.underline`, `.strike`, `.code`, `.link`, `.align_left|center|right`, link field `.link_input`, `.link_apply`, `.link_remove`): shown above a finished, non-empty selection of paragraph and list text, single-block or across blocks, while no composition runs and no slash menu is up; a selection touching the title or code gets none. A mark button is active only when the whole selection carries the mark. Alignment goes on every paragraph and list block the selection touches, empty ones included, and a block that sets none reads as its nearest aligned ancestor's. The link field is a one-line text input of its own (`LinkBar`: text, selection, composition). While it is open it is the view's text input: every `EntityInputHandler` call goes to it, `editor.composing()` stays false, and the document's text, selection and composition are untouched until `Apply`; opening, closing and every change of it are reported with `notify_text_input_changed`. Caret keys, deletion, select-all, copy and cut are the field's, `Escape` abandons a composition before it closes the field, and a keyboard paste reads the clipboard where the platform can; in a browser the key keeps its default action so the `paste` event that follows reaches the field. It has the only caret; the document keeps showing the selection.
- **Equation editor** (`overlay.equation_editor`, `.input`, `.done`): opens on `$$$$ ` / `$$$$ Enter` (block `affine:latex`), `$$ ` / `$$ Enter` (empty inline equation), or clicking an existing `FlowKind::Latex` block or `DecorationKind::LatexChip`. `Enter`, clicking `Done`, and clicking outside the popover commit the current LaTeX string (including any active IME composition via `LinkBar::into_committed_text`), while unchanged content closes without writing; `Escape` cancels and closes without writing. Open inline targets track remote peer edits via a zero-width CRDT `SelectionSnapshot` identity check and auto-close if the target is deleted or replaced remotely. The input field paints syntax-colored LaTeX directly from `highlight_line` runs, supports `Up`/`Down` navigation across soft-wrapped visual lines, and maps pointer clicks (`EquationClick`) to the nearest UTF-16 offset on the clicked visual row.
- **Mobile keyboard toolbar & bookmark prompt** (`overlay.keyboard_toolbar`, buttons `overlay.keyboard_toolbar.<id>`, docked panel `overlay.keyboard_toolbar.panel.<group>.<id>`, and `overlay.bookmark_prompt`, `.input`, `.apply`, `.cancel`): mirrors `0.27.5` `defaultKeyboardToolbarConfig` (`More` 8-group scrollable tool panel, horizontally scrollable top-level / `Aa` item strip without `...` pagination, `Aa` `textSubToolbarConfig` with `autoShow` on non-collapsed text selections, `Turn into` reusing `SLASH_ITEMS`, and `Highlight` foreground/background swatches). While `KeyboardToolbar` is visible on mobile, the floating desktop `FormatToolbar` is suppressed unless its inline link field is explicitly opened (`KeyboardToolbarAction::Link`). Date actions and `embed-linked-doc` `"Updated YYYY-MM-DD HH:MM"` card labels format against the host's local calendar timezone (`utc_offset_minutes`); `Image` opens the host file picker (`can_pick_images` hides the button on native hosts without a registered picker), queues background upload of the base64url SHA-256 content-addressed blob (retrying on scheduler backoff and reconnect until confirmed), and publishes `affine:image`; `Bookmark` opens `overlay.bookmark_prompt` and commits an `http(s)://` `affine:bookmark` block as one undo step (`Escape`, `Cancel`, outside press, empty input, or relative paths write zero blocks).
- **In-place table cell editing** (`page.table_cell_focus`): `affine:table` cells lay out and paint with `RichParagraph` (preserving bold, italic, underline, strike, inline code, links, and inline math) and carry their `FlowTextLayout` for same-source hit-testing, caret, selection, `character_index_for_point`, and IME candidate bounds. Clicking a cell focuses it directly in place (1.5 px brand border, zero floating popover, zero writeback on focus-only). Typing, deleting, and pasting splice the cell's live `Y.Text` directly via `PageDocSession::splice_table_cell_text` (applying the shared `insertion_marks_at` rule so text typed after inline code, links, references, or math never leaks into those marks, and sharing `AnchoredInlineInput` + `Utf16ImeBuffer` with `EdgelessLabelEditor`). Keystrokes coalesce within the 500 ms undo window, refresh only the table block in O(1) via `PageDocSession::read_table_block` with zero `TableData::clone()`, and mark only the table block in `dirty_text`. IME preedit splices via `split_delta` so surrounding marks keep identical pixels; clicking inside an already-focused inline target (table cell or Edgeless label) or moving body selection (`change_selection`) commits any in-flight composition via `unmark` into its original replacement range before repositioning the caret. `Enter`/`Shift+Enter` insert `\n`, `Tab`/`Shift+Tab` stay consumed inside the cell, `Up`/`Down` step across visual lines, and `Escape`, mode switches, or remote deletion exit through `finish_inline_targets` (closing the undo window and suppressing unselected root-title fallback input until the user re-selects a target). While a table cell is focused without a body selection, `KeyboardToolbar` mark/block buttons render disabled; explicit cell mark toggling and `pending_marks` are deferred until body and cell selections unify.
- **In-place table cell editing** (`page.table_cell_focus`): `affine:table` cells lay out and paint with `RichParagraph` (preserving bold, italic, underline, strike, inline code, links, and inline math) and carry their `FlowTextLayout` for same-source hit-testing, caret, selection, `character_index_for_point`, and IME candidate bounds. Clicking a cell focuses it directly in place (1.5 px brand border, zero floating popover, zero writeback on focus-only). Typing, deleting, and pasting splice the cell's live `Y.Text` directly via `PageDocSession::splice_table_cell_text` (applying the shared `insertion_marks_at` rule so text typed after inline code, links, references, or math never leaks into those marks, and sharing `AnchoredInlineInput` + `Utf16ImeBuffer` with `EdgelessLabelEditor`). Keystrokes coalesce within the 500 ms undo window, refresh only the table block in O(1) via `PageDocSession::read_table_block` with zero `TableData::clone()`, and mark only the table block in `dirty_text`. IME preedit splices via `split_delta` so surrounding marks keep identical pixels; clicking inside an already-focused inline target (table cell or Edgeless label) or moving body selection (`change_selection`) commits any in-flight composition via `unmark` into its original replacement range before repositioning the caret. `Enter`/`Shift+Enter` insert `\n`, `Tab`/`Shift+Tab` stay consumed inside the cell, `Up`/`Down` step across visual lines, and `Escape`, mode switches, or remote deletion exit through `finish_inline_targets` (closing the undo window without moving body selection). While a table cell is focused without a body selection, `KeyboardToolbar` mark/block buttons render disabled; explicit cell mark toggling and `pending_marks` are deferred until body and cell selections unify.
- **Drag handle** (`overlay.drag_handle`, `overlay.drop_indicator`): mounted only for the hovered or dragged block, 24 px left of the block and never closer than 4 px to the window edge. Inside its 24 px target it draws BlockSuite's Page-mode grabber: a 4 × 12 px vertical bar while the pointer is on the block's row, narrowing to a 2 × 12 px vertical bar once hovered or dragged (the 2 × 3 six-dot 14 px pill is reserved for Edgeless `gfx` drag handles). A heading keeps the place beside its text for its collapse chevron: its handle sits one step further out, and is left away where the gutter has no room for both. A drag targets the nearest slot among the block's own siblings.
- **Block controls**: `page.block.<id>.checkbox`, `.toggle` and `.collapse` are 24 px targets over the to-do box, the toggle chevron and the heading chevron (an expanded heading shows its chevron only while the pointer is on its row); `page.block.<id>.copy` appears on a hovered code block and reads `Copied` for 1.5 s on the scheduler clock. A sideways scroll over an unwrapped code block scrolls its lines inside `BlockBody::code_scroll` instead of the page; the caret, the selection, the bounds given to the input method, collaborators' carets and selections (translated per highlight span's own block scroll before clamping), and pointer hit-testing follow that scroll and stay inside the code area (`ScrolledCode`), and moving the caret scrolls it into view.
- **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.
+60 -2
View File
@@ -76,12 +76,16 @@ impl PageDocSession {
.cloned()
});
let retained = descendants(&graph, external);
let was_numbered = self.numbered_order(block_id)?.is_some();
self.structural_edit(now_ms, |page| {
page.session
.array_remove(&children_target(parent_id), index, 1)?;
for id in candidates.difference(&retained) {
page.session.map_remove(&page.blocks_target, id)?;
}
if was_numbered {
page.correct_numbered_order_from(parent_id, index as usize, 1)?;
}
Ok(())
})
}
@@ -93,6 +97,28 @@ impl PageDocSession {
.ok_or_else(|| DocError::InvalidState(format!("block {id} has no parent")))
}
fn heading_level(&self, id: &str) -> DocResult<Option<u8>> {
let block = block_target(id);
if !matches!(
self.session.get_map_value(&block, "sys:flavour")?,
Some(SessionReadValue::Any(Any::String(f))) if f == "affine:paragraph"
) {
return Ok(None);
}
Ok(match self.session.get_map_value(&block, "prop:type")? {
Some(SessionReadValue::Any(Any::String(t))) => match t.as_str() {
"h1" => Some(1),
"h2" => Some(2),
"h3" => Some(3),
"h4" => Some(4),
"h5" => Some(5),
"h6" => Some(6),
_ => None,
},
_ => None,
})
}
fn numbered_order(&self, id: &str) -> DocResult<Option<i32>> {
let block = block_target(id);
let string_is = |key, expected: &str| -> DocResult<bool> {
@@ -184,6 +210,7 @@ impl PageDocSession {
pub fn remove_lifting_children(&mut self, id: &str, now_ms: u64) -> DocResult<PageCommit> {
let (parent, index) = self.parent_slot(id)?;
let children = self.read_unknown_block(id)?.children;
let was_numbered = self.numbered_order(id)?.is_some();
self.structural_edit(now_ms, |page| {
page.session
.array_remove(&children_target(&parent), index, 1)?;
@@ -195,6 +222,9 @@ impl PageDocSession {
)?;
}
page.session.map_remove(&page.blocks_target, id)?;
if was_numbered {
page.correct_numbered_order_from(&parent, index as usize, 1)?;
}
Ok(())
})
}
@@ -226,6 +256,19 @@ impl PageDocSession {
new_index,
vec![SessionValue::Any(Any::String(block_id.into()))],
)?;
if new_parent_id != old_parent_id
&& matches!(
page.session
.get_map_value(&block_target(new_parent_id), "prop:collapsed")?,
Some(SessionReadValue::Any(Any::True))
)
{
page.session.map_set(
&block_target(new_parent_id),
"prop:collapsed".into(),
SessionValue::Any(Any::False),
)?;
}
if page.read_unknown_block(block_id)?.flavour == "affine:list" {
page.correct_numbered_order_from(old_parent_id, index as usize, 1)?;
}
@@ -278,7 +321,7 @@ impl PageDocSession {
} else if split_utf16 > 0 && !children.is_empty() && !collapsed {
(block_id, 0)
} else {
graph
let (parent, mut index) = graph
.iter()
.find_map(|(parent, children)| {
children
@@ -286,7 +329,22 @@ impl PageDocSession {
.position(|id| id == block_id)
.map(|i| (parent.as_str(), i + 1))
})
.ok_or_else(|| DocError::InvalidState("split block has no parent".into()))?
.ok_or_else(|| DocError::InvalidState("split block has no parent".into()))?;
if collapsed
&& let Some(level) = self.heading_level(block_id)?
&& let Some(siblings) = graph.get(parent)
{
while let Some(sib_id) = siblings.get(index) {
if self
.heading_level(sib_id)?
.is_some_and(|next| next <= level)
{
break;
}
index += 1;
}
}
(parent, index)
};
let target = self.editable_text_target(block_id)?;
let length = self.session.read_text_len(&target)?;
@@ -119,6 +119,8 @@ mod tests {
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: children.into_iter().map(str::to_string).collect(),
group_children: Vec::new(),
parent_group_id: None,
title_pill_rect: None,
}
}
@@ -129,6 +131,7 @@ mod tests {
kind,
surface_id: (kind == SpatialItemKind::Shape).then(|| "surf".into()),
rect,
rotate_deg: 0.0,
points: None,
connector_source: None,
connector_target: None,
@@ -174,6 +177,9 @@ mod tests {
start_world: (620.0, 70.0),
current_world: (310.0, 70.0),
initial: init_s2.clone(),
shift: false,
alt_clone: false,
pending_dblclick: None,
};
assert_eq!(
hovered_frame_for_drag(&painted, Some(&gesture)).as_deref(),
@@ -0,0 +1,455 @@
//! Pure geometry, rotated resize, Shift constraints, and connector port snapping for Edgeless.
use super::{HandleKind, SpatialItemInfo, SpatialItemKind, WorldRect};
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())
}
/// Lock a drag delta to the dominant horizontal or vertical axis (Shift+Drag).
pub fn constrain_shift_drag(start: (f32, f32), current: (f32, f32)) -> (f32, f32) {
let dx = current.0 - start.0;
let dy = current.1 - start.1;
if dx.abs() >= dy.abs() {
(dx, 0.0)
} else {
(0.0, dy)
}
}
/// Square a shape creation drag while preserving the quadrant from `start` toward `current`.
pub fn constrain_shift_square(start: (f32, f32), current: (f32, f32)) -> WorldRect {
let dx = current.0 - start.0;
let dy = current.1 - start.1;
let side = dx.abs().max(dy.abs());
let sx = if dx < 0.0 { -side } else { side };
let sy = if dy < 0.0 { -side } else { side };
normalized_rect(start, (start.0 + sx, start.1 + sy))
}
pub fn resized_rect(
initial: WorldRect,
handle: HandleKind,
start: (f32, f32),
current: (f32, f32),
) -> WorldRect {
resized_rect_with_min(initial, handle, start, current, 24.0, 24.0)
}
pub fn resized_rect_with_min(
initial: WorldRect,
handle: HandleKind,
start: (f32, f32),
current: (f32, f32),
min_w: f32,
min_h: f32,
) -> WorldRect {
resized_rect_constrained(initial, handle, start, current, min_w, min_h, false, 0.0)
}
/// Resize `initial` by dragging `handle` from `start` to `current` in world space.
///
/// When `rotate_deg != 0`, transforms the pointer delta into the element's inverse-rotated
/// local frame and keeps the opposite corner/edge pinned in world space.
/// When `lock_ratio` is true, preserves `initial.w / initial.h` across both corner and side handles.
#[allow(clippy::too_many_arguments)]
pub fn resized_rect_constrained(
initial: WorldRect,
handle: HandleKind,
start: (f32, f32),
current: (f32, f32),
min_w: f32,
min_h: f32,
lock_ratio: bool,
rotate_deg: f32,
) -> WorldRect {
let (cx0, cy0) = initial.center();
let (s_loc, c_loc) = if rotate_deg.abs() > 1e-3 {
(
rotate_point_around(start.0, start.1, cx0, cy0, -rotate_deg),
rotate_point_around(current.0, current.1, cx0, cy0, -rotate_deg),
)
} else {
(start, current)
};
let dx = c_loc.0 - s_loc.0;
let dy = c_loc.1 - s_loc.1;
let mut left = initial.x;
let mut top = initial.y;
let mut right = initial.right();
let mut bottom = initial.bottom();
match handle {
HandleKind::NW => {
left = (left + dx).min(right - min_w);
top = (top + dy).min(bottom - min_h);
}
HandleKind::N => {
top = (top + dy).min(bottom - min_h);
}
HandleKind::NE => {
right = (right + dx).max(left + min_w);
top = (top + dy).min(bottom - min_h);
}
HandleKind::E => {
right = (right + dx).max(left + min_w);
}
HandleKind::SE => {
right = (right + dx).max(left + min_w);
bottom = (bottom + dy).max(top + min_h);
}
HandleKind::S => {
bottom = (bottom + dy).max(top + min_h);
}
HandleKind::SW => {
left = (left + dx).min(right - min_w);
bottom = (bottom + dy).max(top + min_h);
}
HandleKind::W => {
left = (left + dx).min(right - min_w);
}
HandleKind::Rotate
| HandleKind::DragHandle
| HandleKind::ConnectorStart
| HandleKind::ConnectorEnd => {
return initial;
}
}
let mut nw = (right - left).max(min_w);
let mut nh = (bottom - top).max(min_h);
if lock_ratio && initial.w > 1e-3 && initial.h > 1e-3 {
let ratio = initial.w / initial.h;
match handle {
HandleKind::E | HandleKind::W => {
nh = (nw / ratio).max(min_h);
nw = (nh * ratio).max(min_w);
}
HandleKind::N | HandleKind::S => {
nw = (nh * ratio).max(min_w);
nh = (nw / ratio).max(min_h);
}
HandleKind::NW | HandleKind::NE | HandleKind::SE | HandleKind::SW => {
// Follow the axis with smaller relative distortion (or dominant scale),
// matching BlockSuite's proportional corner lock (`w = new_w, h = w / ratio`
// when horizontal change is smaller or equal; clamp both to minimums).
let sx = nw / initial.w;
let sy = nh / initial.h;
let scale = if (sx - 1.0).abs() >= (sy - 1.0).abs() {
sx
} else {
sy
};
let min_scale = (min_w / initial.w).max(min_h / initial.h);
let s = scale.max(min_scale);
nw = initial.w * s;
nh = initial.h * s;
}
_ => {}
}
}
// Opposite anchor normalized coordinates `(u, v)` in `[0, 1]^2` that remain fixed in world space.
let (u, v) = match handle {
HandleKind::NW => (1.0_f32, 1.0_f32),
HandleKind::N => (0.5, 1.0),
HandleKind::NE => (0.0, 1.0),
HandleKind::E => (0.0, 0.5),
HandleKind::SE => (0.0, 0.0),
HandleKind::S => (0.5, 0.0),
HandleKind::SW => (1.0, 0.0),
HandleKind::W => (1.0, 0.5),
_ => (0.5, 0.5),
};
if rotate_deg.abs() > 1e-3 {
let anchor_local_0 = (initial.x + initial.w * u, initial.y + initial.h * v);
let anchor_world =
rotate_point_around(anchor_local_0.0, anchor_local_0.1, cx0, cy0, rotate_deg);
let off_local = ((u - 0.5) * nw, (v - 0.5) * nh);
let off_world = rotate_point_around(off_local.0, off_local.1, 0.0, 0.0, rotate_deg);
let new_cx = anchor_world.0 - off_world.0;
let new_cy = anchor_world.1 - off_world.1;
WorldRect::new(new_cx - nw * 0.5, new_cy - nh * 0.5, nw, nh)
} else {
let anchor_x = initial.x + initial.w * u;
let anchor_y = initial.y + initial.h * v;
WorldRect::new(anchor_x - u * nw, anchor_y - v * nh, nw, nh)
}
}
/// Snap a world coordinate to any connectable element (`Shape | Note | EdgelessText | Frame`).
///
/// Supports magnetic snapping to the 4 cardinal midpoints as well as arbitrary perimeter points
/// (and interior drop-to-nearest-edge for non-Frame elements, matching Web `connector-manager.ts`).
pub fn snap_connector_port_on_items(
items: &[SpatialItemInfo],
world_x: f32,
world_y: f32,
zoom: f32,
exclude_id: Option<&str>,
) -> Option<(String, [f64; 2], (f32, f32))> {
let inv_zoom = 1.0 / zoom.max(0.1);
let snap_dist = (24.0 * inv_zoom).max(16.0);
let cardinal_dist = (10.0 * inv_zoom).max(8.0);
let cardinals: [[f32; 2]; 4] = [[0.5, 0.0], [1.0, 0.5], [0.5, 1.0], [0.0, 0.5]];
let mut best: Option<(f32, bool, String, [f64; 2], (f32, f32))> = None;
// Walk reverse paint order so topmost element wins ties.
for item in items.iter().rev() {
if !matches!(
item.kind,
SpatialItemKind::Shape
| SpatialItemKind::Note
| SpatialItemKind::EdgelessText
| SpatialItemKind::Frame
) {
continue;
}
if exclude_id.is_some_and(|ex| ex == item.id) {
continue;
}
if item.rect.w <= 1e-3 || item.rect.h <= 1e-3 {
continue;
}
let (cx, cy) = item.rect.center();
let (lx, ly) = rotate_point_around(world_x, world_y, cx, cy, -item.rotate_deg);
// 1. Check magnetic cardinal midpoints first.
let mut matched_cardinal = false;
for [cu, cv] in cardinals {
let px_l = item.rect.x + item.rect.w * cu;
let py_l = item.rect.y + item.rect.h * cv;
let d = (lx - px_l).hypot(ly - py_l);
if d <= cardinal_dist {
matched_cardinal = true;
let world = rotate_point_around(px_l, py_l, cx, cy, item.rotate_deg);
let is_frame = item.kind == SpatialItemKind::Frame;
let better = best.as_ref().is_none_or(|b| {
// Prefer non-frame over frame when both match; otherwise strictly closer.
(!is_frame && b.1) || (is_frame == b.1 && d < b.0)
});
if better {
best = Some((d, is_frame, item.id.clone(), [cu as f64, cv as f64], world));
}
}
}
if matched_cardinal {
continue;
}
// 2. Project onto the nearest point on the element's 4 perimeter edges.
let inside = lx >= item.rect.x
&& lx <= item.rect.right()
&& ly >= item.rect.y
&& ly <= item.rect.bottom();
let (ex, ey, dist) = if inside {
let d_left = lx - item.rect.x;
let d_right = item.rect.right() - lx;
let d_top = ly - item.rect.y;
let d_bottom = item.rect.bottom() - ly;
let min_d = d_left.min(d_right).min(d_top).min(d_bottom);
// Large container blocks (Frames and Notes) only snap near their border so items
// or free connectors inside them are not hijacked to a distant edge.
if matches!(item.kind, SpatialItemKind::Frame | SpatialItemKind::Note)
&& min_d > snap_dist
{
continue;
}
if min_d == d_left {
(item.rect.x, ly, min_d)
} else if min_d == d_right {
(item.rect.right(), ly, min_d)
} else if min_d == d_top {
(lx, item.rect.y, min_d)
} else {
(lx, item.rect.bottom(), min_d)
}
} else {
let cx_p = lx.clamp(item.rect.x, item.rect.right());
let cy_p = ly.clamp(item.rect.y, item.rect.bottom());
let d = (lx - cx_p).hypot(ly - cy_p);
if d > snap_dist {
continue;
}
(cx_p, cy_p, d)
};
let u = ((ex - item.rect.x) / item.rect.w).clamp(0.0, 1.0);
let v = ((ey - item.rect.y) / item.rect.h).clamp(0.0, 1.0);
let world = rotate_point_around(ex, ey, cx, cy, item.rotate_deg);
let is_frame = item.kind == SpatialItemKind::Frame;
// For interior points on non-frame elements, treat effective distance as 0 so
// starting/ending a connector inside a shape always binds to that shape.
let eff_dist = if inside && !is_frame { 0.0 } else { dist };
let better = best
.as_ref()
.is_none_or(|b| (!is_frame && b.1) || (is_frame == b.1 && eff_dist < b.0));
if better {
best = Some((
eff_dist,
is_frame,
item.id.clone(),
[u as f64, v as f64],
world,
));
}
}
best.map(|(_, _, id, port, pt)| (id, port, pt))
}
#[cfg(test)]
mod tests {
use super::*;
fn mk_item(
id: &str,
kind: SpatialItemKind,
rect: WorldRect,
rotate_deg: f32,
) -> SpatialItemInfo {
SpatialItemInfo {
id: id.into(),
kind,
shape_type: None,
surface_id: (!kind.is_block()).then(|| "surf".into()),
rect,
rotate_deg,
index: "a0".into(),
scale: 1.0,
stroke_width: 2.0,
polyline: Vec::new(),
frame_children: Vec::new(),
group_children: Vec::new(),
parent_group_id: None,
title_pill_rect: None,
}
}
#[test]
fn rotated_resize_keeps_opposite_anchor_and_expands_outward() {
let initial = WorldRect::new(100.0, 100.0, 180.0, 100.0);
// 180° rotated: NW handle is visually at bottom-right (280, 200); dragging +100,+80 expands to 280x180.
let r180 = resized_rect_constrained(
initial,
HandleKind::NW,
(280.0, 200.0),
(380.0, 280.0),
24.0,
24.0,
false,
180.0,
);
assert!((r180.w - 280.0).abs() < 1e-2, "w={}", r180.w);
assert!((r180.h - 180.0).abs() < 1e-2, "h={}", r180.h);
// Visual top-left (SE anchor in local coords rotated by 180°) stays pinned at (100, 100).
let (cx, cy) = r180.center();
let anchor_w = rotate_point_around(r180.right(), r180.bottom(), cx, cy, 180.0);
assert!((anchor_w.0 - 100.0).abs() < 1e-2 && (anchor_w.1 - 100.0).abs() < 1e-2);
// Aspect ratio lock with Shift on SE handle: 160x100 dragged (+40, +180) keeps 1.6 ratio.
let r_lock = resized_rect_constrained(
WorldRect::new(0.0, 0.0, 160.0, 100.0),
HandleKind::SE,
(160.0, 100.0),
(200.0, 280.0),
24.0,
24.0,
true,
0.0,
);
assert!(((r_lock.w / r_lock.h) - 1.6).abs() < 1e-3);
}
#[test]
fn shift_constraints_and_full_perimeter_connector_snapping() {
assert_eq!(
constrain_shift_drag((10.0, 10.0), (50.0, 22.0)),
(40.0, 0.0)
);
assert_eq!(
constrain_shift_drag((10.0, 10.0), (15.0, 60.0)),
(0.0, 50.0)
);
let sq = constrain_shift_square((100.0, 100.0), (220.0, 180.0));
assert_eq!(sq, WorldRect::new(100.0, 100.0, 120.0, 120.0));
let items = vec![
mk_item(
"frame1",
SpatialItemKind::Frame,
WorldRect::new(0.0, 0.0, 500.0, 400.0),
0.0,
),
mk_item(
"s1",
SpatialItemKind::Shape,
WorldRect::new(100.0, 100.0, 200.0, 200.0),
0.0,
),
mk_item(
"et1",
SpatialItemKind::EdgelessText,
WorldRect::new(350.0, 120.0, 100.0, 40.0),
0.0,
),
];
// Non-cardinal top-right edge of s1 (295, 130) snaps to s1 perimeter (not frame1).
let (id, port, _) = snap_connector_port_on_items(&items, 295.0, 130.0, 1.0, None).unwrap();
assert_eq!(id, "s1");
assert!((port[0] - 1.0).abs() < 1e-3 && (port[1] - 0.15).abs() < 0.05);
// EdgelessText snaps.
let (id_et, _, _) = snap_connector_port_on_items(&items, 355.0, 140.0, 1.0, None).unwrap();
assert_eq!(id_et, "et1");
// Frame border snaps when outside inner items.
let (id_f, _, _) = snap_connector_port_on_items(&items, 4.0, 200.0, 1.0, None).unwrap();
assert_eq!(id_f, "frame1");
}
}
+112 -143
View File
@@ -5,10 +5,13 @@ use std::{
rc::Rc,
};
use blocksuite_playground_doc::read::ConnectorMode;
use ui::{Pixels, Point, point, px};
use super::{
EdgelessCamera, EdgelessInlineEdit, EdgelessLabelEditor, EdgelessTool, ShapePreset, WorldRect,
constrain_shift_drag, distance_to_polyline, point_in_rotated_rect, resized_rect_constrained,
rotate_point_around, snap_connector_port_on_items,
};
/// Interactive handle on the current Edgeless selection box.
@@ -24,6 +27,8 @@ pub enum HandleKind {
W,
Rotate,
DragHandle,
ConnectorStart,
ConnectorEnd,
}
impl HandleKind {
@@ -50,6 +55,8 @@ impl HandleKind {
Self::W => "edgeless.handle.w",
Self::Rotate => "edgeless.handle.rotate",
Self::DragHandle => "edgeless.drag_handle",
Self::ConnectorStart => "edgeless.handle.connector_start",
Self::ConnectorEnd => "edgeless.handle.connector_end",
}
}
}
@@ -96,6 +103,8 @@ pub struct SpatialItemInfo {
pub stroke_width: f32,
pub polyline: Vec<(f32, f32)>,
pub frame_children: Vec<String>,
pub group_children: Vec<String>,
pub parent_group_id: Option<String>,
pub title_pill_rect: Option<WorldRect>,
}
@@ -107,6 +116,7 @@ pub struct DragItemInitial {
pub kind: SpatialItemKind,
pub surface_id: Option<String>,
pub rect: WorldRect,
pub rotate_deg: f32,
pub points: Option<Vec<Vec<f64>>>,
pub connector_source: Option<(Option<String>, Option<[f64; 2]>)>,
pub connector_target: Option<(Option<String>, Option<[f64; 2]>)>,
@@ -129,6 +139,9 @@ pub enum EdgelessGesture {
start_world: (f32, f32),
current_world: (f32, f32),
initial: Vec<DragItemInitial>,
shift: bool,
alt_clone: bool,
pending_dblclick: Option<(String, (f32, f32))>,
},
ResizeSelection {
handle: HandleKind,
@@ -136,6 +149,8 @@ pub enum EdgelessGesture {
current_world: (f32, f32),
initial_box: WorldRect,
initial: Vec<DragItemInitial>,
shift: bool,
rotate_deg: f32,
},
RotateSelection {
id: String,
@@ -150,6 +165,7 @@ pub enum EdgelessGesture {
shape_type: ShapePreset,
start_world: (f32, f32),
current_world: (f32, f32),
shift: bool,
},
CreateFrame {
start_world: (f32, f32),
@@ -160,6 +176,7 @@ pub enum EdgelessGesture {
current_world: (f32, f32),
},
CreateConnector {
mode: ConnectorMode,
source_id: Option<String>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
@@ -168,10 +185,26 @@ pub enum EdgelessGesture {
target_port: Option<[f64; 2]>,
target_world: Option<(f32, f32)>,
},
DragConnectorEndpoint {
id: String,
surface_id: String,
is_start: bool,
mode: ConnectorMode,
fixed_id: Option<String>,
fixed_port: Option<[f64; 2]>,
fixed_world: (f32, f32),
current_world: (f32, f32),
snap_id: Option<String>,
snap_port: Option<[f64; 2]>,
snap_world: Option<(f32, f32)>,
},
DrawStroke {
highlighter: bool,
points_world: Vec<(f64, f64)>,
},
SelectLabelText {
anchor_utf16: usize,
},
}
/// Live geometry override applied during an active drag/resize/rotate gesture before commit.
@@ -183,10 +216,10 @@ pub struct LiveGeomOverride {
}
/// Interactive authoring state owned by `EdgelessCanvasState`.
#[derive(Default)]
pub struct EdgelessAuthoringState {
pub tool: EdgelessTool,
pub last_shape_type: Option<ShapePreset>,
pub connector_mode: ConnectorMode,
pub shape_picker_open: bool,
pub selection: BTreeSet<String>,
pub gesture: Option<EdgelessGesture>,
@@ -197,6 +230,23 @@ pub struct EdgelessAuthoringState {
pub painted_items: Rc<[SpatialItemInfo]>,
}
impl Default for EdgelessAuthoringState {
fn default() -> Self {
Self {
tool: EdgelessTool::default(),
last_shape_type: None,
connector_mode: ConnectorMode::Curve,
shape_picker_open: false,
selection: BTreeSet::new(),
gesture: None,
inline_edit: None,
space_pan: false,
next_id_seq: 0,
painted_items: Rc::from([]),
}
}
}
impl EdgelessAuthoringState {
pub fn reset_transient(&mut self) {
self.gesture = None;
@@ -246,9 +296,21 @@ impl EdgelessAuthoringState {
start_world,
current_world,
initial,
shift,
alt_clone,
..
}) => {
let dx = current_world.0 - start_world.0;
let dy = current_world.1 - start_world.1;
if *alt_clone {
return out;
}
let (dx, dy) = if *shift {
constrain_shift_drag(*start_world, *current_world)
} else {
(
current_world.0 - start_world.0,
current_world.1 - start_world.1,
)
};
for item in initial {
out.insert(
item.id.clone(),
@@ -271,19 +333,24 @@ impl EdgelessAuthoringState {
current_world,
initial_box,
initial,
shift,
rotate_deg,
}) => {
let min_w = if initial.len() == 1 && initial[0].kind == SpatialItemKind::Note {
super::NOTE_MIN_WIDTH
} else {
24.0
};
let new_box = resized_rect_with_min(
let lock_ratio = *shift || initial.len() > 1;
let new_box = resized_rect_constrained(
*initial_box,
*handle,
*start_world,
*current_world,
min_w,
24.0,
lock_ratio,
*rotate_deg,
);
let sx = if initial_box.w > 1e-3 {
new_box.w / initial_box.w
@@ -296,15 +363,20 @@ impl EdgelessAuthoringState {
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 item_min_w = if item.kind == SpatialItemKind::Note {
super::NOTE_MIN_WIDTH
let (nx, ny, nw, nh) = if initial.len() == 1 && rotate_deg.abs() > 1e-3 {
(new_box.x, new_box.y, new_box.w, new_box.h)
} else {
16.0
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 item_min_w = if item.kind == SpatialItemKind::Note {
super::NOTE_MIN_WIDTH
} else {
16.0
};
let nw = (item.rect.w * sx).max(item_min_w);
let nh = (item.rect.h * sy).max(16.0);
(nx, ny, nw, nh)
};
let nw = (item.rect.w * sx).max(item_min_w);
let nh = (item.rect.h * sy).max(16.0);
out.insert(
item.id.clone(),
LiveGeomOverride {
@@ -429,6 +501,25 @@ impl EdgelessAuthoringState {
}
}
// Connector start/end endpoint handles for single selected connector.
if let Some(single) = single
&& single.kind == SpatialItemKind::Connector
&& single.polyline.len() >= 2
{
let start_s = camera.world_to_screen(
point(px(single.polyline[0].0), px(single.polyline[0].1)),
vp_origin,
);
let end_pt = *single.polyline.last().unwrap();
let end_s = camera.world_to_screen(point(px(end_pt.0), px(end_pt.1)), vp_origin);
if (px_s - f32::from(start_s.x)).hypot(py_s - f32::from(start_s.y)) <= 10.0 {
return Some(HandleKind::ConnectorStart);
}
if (px_s - f32::from(end_s.x)).hypot(py_s - f32::from(end_s.y)) <= 10.0 {
return Some(HandleKind::ConnectorEnd);
}
}
if !self.selection_has_non_connector() {
return None;
}
@@ -523,7 +614,7 @@ impl EdgelessAuthoringState {
None
}
/// Snap a world coordinate to the nearest cardinal port on a Shape or Note within `snap_world`.
/// Snap a world coordinate to any connectable element (`Shape | Note | EdgelessText | Frame`).
pub fn snap_connector_port(
&self,
world_x: f32,
@@ -531,140 +622,10 @@ impl EdgelessAuthoringState {
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))
snap_connector_port_on_items(&self.painted_items, world_x, world_y, zoom, exclude_id)
}
}
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 {
resized_rect_with_min(initial, handle, start, current, 24.0, 24.0)
}
pub fn resized_rect_with_min(
initial: WorldRect,
handle: HandleKind,
start: (f32, f32),
current: (f32, f32),
min_w: f32,
min_h: 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();
match handle {
HandleKind::NW => {
left = (left + dx).min(right - min_w);
top = (top + dy).min(bottom - min_h);
}
HandleKind::N => {
top = (top + dy).min(bottom - min_h);
}
HandleKind::NE => {
right = (right + dx).max(left + min_w);
top = (top + dy).min(bottom - min_h);
}
HandleKind::E => {
right = (right + dx).max(left + min_w);
}
HandleKind::SE => {
right = (right + dx).max(left + min_w);
bottom = (bottom + dy).max(top + min_h);
}
HandleKind::S => {
bottom = (bottom + dy).max(top + min_h);
}
HandleKind::SW => {
left = (left + dx).min(right - min_w);
bottom = (bottom + dy).max(top + min_h);
}
HandleKind::W => {
left = (left + dx).min(right - min_w);
}
HandleKind::Rotate | HandleKind::DragHandle => {}
}
WorldRect::new(left, top, right - left, bottom - top)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -696,6 +657,8 @@ mod tests {
stroke_width: 1.0,
polyline: vec![],
frame_children: vec!["rot_shape".into()],
group_children: Vec::new(),
parent_group_id: None,
title_pill_rect: Some(WorldRect::new(0.0, -28.0, 80.0, 22.0)),
},
SpatialItemInfo {
@@ -710,6 +673,8 @@ mod tests {
stroke_width: 2.0,
polyline: vec![],
frame_children: vec![],
group_children: Vec::new(),
parent_group_id: None,
title_pill_rect: None,
},
SpatialItemInfo {
@@ -724,6 +689,8 @@ mod tests {
stroke_width: 4.0,
polyline: vec![(250.0, 55.0), (350.0, 55.0)],
frame_children: vec![],
group_children: Vec::new(),
parent_group_id: None,
title_pill_rect: None,
},
]
@@ -866,6 +833,8 @@ mod tests {
stroke_width: layout.item_stroke_width(idx),
polyline: layout.item_polyline(idx).to_vec(),
frame_children: Vec::new(),
group_children: Vec::new(),
parent_group_id: None,
title_pill_rect: None,
});
}
@@ -115,6 +115,7 @@ pub struct EdgelessLabelEditor {
pub original_text: String,
pub anchored: AnchoredInlineInput,
pub world_rect: WorldRect,
pub min_world_height: f32,
pub rotate_deg: f32,
pub shape_style: Option<ShapeTextStyle>,
pub created_new_text: bool,
@@ -148,6 +149,7 @@ impl EdgelessLabelEditor {
original_text: initial.clone(),
anchored: AnchoredInlineInput::new(initial, multiline),
world_rect,
min_world_height: world_rect.h,
rotate_deg,
shape_style: None,
created_new_text: false,
@@ -228,6 +230,96 @@ impl EdgelessLabelEditor {
self.input.select(range);
}
pub fn select_directional(&mut self, anchor: usize, focus: usize) {
self.preedit_anchors = None;
let len = utf16_len(&self.input.text);
let a = anchor.min(len);
let f = focus.min(len);
self.input.selection = a.min(f)..a.max(f);
self.input.reversed = f < a;
}
pub fn move_to_line_edge(&mut self, to_end: bool, extend: bool) {
self.preedit_anchors = None;
let text = &self.input.text;
let focus = self.input.focus();
let target = if !self.input.multiline {
if to_end { utf16_len(text) } else { 0 }
} else {
let byte = utf16_to_byte(text, focus);
let target_byte = if to_end {
text[byte..].find('\n').map_or(text.len(), |rel| byte + rel)
} else {
text[..byte].rfind('\n').map_or(0, |pos| pos + 1)
};
utf16_len(&text[..target_byte])
};
self.input.move_caret(target, extend);
}
pub fn word_boundary(&self, from: usize, forward: bool) -> usize {
let text = &self.input.text;
let byte = utf16_to_byte(text, from);
let is_word = |c: char| c.is_alphanumeric() || c == '_';
let next_byte = if forward {
let mut idx = byte;
let mut iter = text[byte..].char_indices().peekable();
while let Some((rel, ch)) = iter.peek().copied() {
if is_word(ch) {
break;
}
idx = byte + rel + ch.len_utf8();
iter.next();
}
while let Some((rel, ch)) = iter.peek().copied() {
if !is_word(ch) {
break;
}
idx = byte + rel + ch.len_utf8();
iter.next();
}
idx
} else {
let mut idx = byte;
let mut iter = text[..byte].char_indices().rev().peekable();
while let Some((pos, ch)) = iter.peek().copied() {
if is_word(ch) {
break;
}
idx = pos;
iter.next();
}
while let Some((pos, ch)) = iter.peek().copied() {
if !is_word(ch) {
break;
}
idx = pos;
iter.next();
}
idx
};
utf16_len(&text[..next_byte])
}
pub fn move_word(&mut self, left: bool, extend: bool) {
self.preedit_anchors = None;
let to = self.word_boundary(self.input.focus(), !left);
self.input.move_caret(to, extend);
}
pub fn delete_word(&mut self, forward: bool) -> Option<LabelSplice> {
self.preedit_anchors = None;
if !self.input.selection.is_empty() {
return self.replace(None, "");
}
let pos = self.input.focus();
let target = self.word_boundary(pos, forward);
if target == pos {
return None;
}
self.replace(Some(pos.min(target)..pos.max(target)), "")
}
pub fn delete_backward(&mut self) -> Option<LabelSplice> {
self.preedit_anchors = None;
let splice = self.input.delete_backward();
+10 -5
View File
@@ -5,10 +5,12 @@ mod camera;
mod canvas;
mod canvas_paint;
mod frame_membership;
mod geometry;
mod hit_test;
mod label_editor;
mod order;
mod overlay;
mod overlay_label;
mod scene;
mod toolbar;
@@ -26,19 +28,22 @@ pub use canvas_paint::build_edgeless_layer;
pub use frame_membership::{
compute_frame_membership_updates, find_frame_containing_point, hovered_frame_for_drag,
};
pub use geometry::{
constrain_shift_drag, constrain_shift_square, distance_to_polyline, distance_to_segment,
normalized_rect, point_in_rotated_rect, resized_rect, resized_rect_constrained,
resized_rect_with_min, rotate_point_around, snap_connector_port_on_items,
};
pub use hit_test::{
DragItemInitial, EdgelessAuthoringState, EdgelessGesture, HandleKind, SpatialItemInfo,
SpatialItemKind, normalized_rect, point_in_rotated_rect, resized_rect, resized_rect_with_min,
rotate_point_around,
SpatialItemKind,
};
pub use label_editor::{
EdgelessInlineEdit, EdgelessLabelEditor, LabelSplice, LabelTarget, ShapeTextStyle,
label_editor_screen_box, utf16_len, utf16_to_byte,
};
pub use order::{Layers, PaintItem};
pub use overlay::{
build_edgeless_authoring_overlay, label_editor_text_origin, layout_label_editor_paragraph,
};
pub use overlay::build_edgeless_authoring_overlay;
pub use overlay_label::{label_editor_text_origin, layout_label_editor_paragraph};
pub use scene::{PreparedEdgelessScene, collect_frame_children, prepare_edgeless_scene};
pub use toolbar::{
EdgelessTool, EdgelessToolbarHost, ShapePickerVisualState, ShapePreset, build_edgeless_toolbar,
+224 -388
View File
@@ -1,25 +1,21 @@
//! Screen-space selection frame, handles, marquee, live creation previews, and inline label editor overlay.
use std::collections::BTreeMap;
use blocksuite_playground_doc::read::ConnectorMode;
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 crate::theme::{Palette, PlaygroundTheme};
use super::{
EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera, EdgelessGesture,
EdgelessLabelEditor, HandleKind, normalized_rect, rotate_point_around, utf16_to_byte,
EDGELESS_VIEWPORT_ID, EdgelessAuthoringState, EdgelessCamera, EdgelessGesture, HandleKind,
SpatialItemKind, constrain_shift_square, normalized_rect,
overlay_label::build_inline_label_editor_overlay, rotate_point_around,
};
/// 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.
/// Screen-space selection frame, 8 resize handles, rotation handle, connector endpoint handles,
/// Edgeless `2×3` `gfx` drag handle, marquee box, live creation previews, and inline label editor overlay.
#[allow(clippy::too_many_arguments)]
pub fn build_edgeless_authoring_overlay(
authoring: &EdgelessAuthoringState,
@@ -35,7 +31,7 @@ pub fn build_edgeless_authoring_overlay(
let brand = palette.brand;
let white = Hsla::white();
// 1. Selection box + 8 resize handles + rotation handle + Edgeless gfx 2x3 drag handle.
// 1. Selection box + 8 resize handles + rotation handle + connector handles + Edgeless gfx 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 =
@@ -124,6 +120,40 @@ pub fn build_edgeless_authoring_overlay(
}
if authoring.inline_edit.is_none() {
// Circular endpoint drag handles for a single selected connector.
if let Some(single) = authoring.single_selected()
&& single.kind == SpatialItemKind::Connector
&& single.polyline.len() >= 2
{
let endpoints = [
(HandleKind::ConnectorStart, single.polyline[0]),
(HandleKind::ConnectorEnd, *single.polyline.last().unwrap()),
];
for (kind, (wx, wy)) in endpoints {
let sp = camera.world_to_screen(point(px(wx), px(wy)), vp_origin);
let lx = (f32::from(sp.x) - 5.0).round();
let ty = (f32::from(sp.y) - 5.0).round();
let mut h_el = div()
.absolute()
.left(px(lx))
.top(px(ty))
.w(px(10.0))
.h(px(10.0))
.rounded(px(5.0))
.bg(white)
.border_2()
.border_color(brand);
if lx >= 0.0
&& ty >= 0.0
&& lx + 10.0 <= viewport_width
&& ty + 10.0 <= viewport_height
{
h_el = h_el.snapshot(kind.snapshot_id(), Some(EDGELESS_VIEWPORT_ID));
}
elements.push(h_el.into_any_element());
}
}
if authoring.selection_has_non_connector() {
let handle_coords = [
(HandleKind::NW, x0, y0),
@@ -167,7 +197,6 @@ pub fn build_edgeless_authoring_overlay(
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(
|_, _, _| (),
@@ -297,9 +326,17 @@ pub fn build_edgeless_authoring_overlay(
Some(EdgelessGesture::CreateShape {
start_world,
current_world,
shift,
..
})
| Some(EdgelessGesture::CreateFrame {
}) => {
let r = if *shift {
constrain_shift_square(*start_world, *current_world)
} else {
normalized_rect(*start_world, *current_world)
};
elements.push(build_creation_rect_preview(r, camera, vp_origin, brand));
}
Some(EdgelessGesture::CreateFrame {
start_world,
current_world,
})
@@ -308,27 +345,10 @@ pub fn build_edgeless_authoring_overlay(
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(),
);
elements.push(build_creation_rect_preview(r, camera, vp_origin, brand));
}
Some(EdgelessGesture::CreateConnector {
mode,
source_id,
source_port,
source_world,
@@ -338,59 +358,75 @@ pub fn build_edgeless_authoring_overlay(
target_world,
}) => {
let dst = target_world.unwrap_or(*current_world);
let (s_w, c1_w, c2_w, e_w) = crate::surface::preview_curve_cubic(
elements.push(build_connector_preview(
*mode,
source_id.as_deref(),
*source_port,
*source_world,
target_id.as_deref(),
*target_port,
dst,
true,
target_world.is_some(),
&authoring.painted_items,
);
let p0 = camera.world_to_screen(point(px(s_w.0), px(s_w.1)), vp_origin);
let ctrl1 = camera.world_to_screen(point(px(c1_w.0), px(c1_w.1)), vp_origin);
let ctrl2 = camera.world_to_screen(point(px(c2_w.0), px(c2_w.1)), vp_origin);
let p1 = camera.world_to_screen(point(px(e_w.0), px(e_w.1)), vp_origin);
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 c1 = point(px(ox + f32::from(ctrl1.x)), px(oy + f32::from(ctrl1.y)));
let c2 = point(px(ox + f32::from(ctrl2.x)), px(oy + f32::from(ctrl2.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.cubic_bezier_to(b, c1, c2);
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,
));
}
}
},
camera,
vp_origin,
brand,
white,
));
}
Some(EdgelessGesture::DragConnectorEndpoint {
is_start,
mode,
fixed_id,
fixed_port,
fixed_world,
current_world,
snap_id,
snap_port,
snap_world,
..
}) => {
let moving_world = snap_world.unwrap_or(*current_world);
let (s_id, s_port, s_world, t_id, t_port, t_world, s_ring, t_ring) = if *is_start {
(
snap_id.as_deref(),
*snap_port,
moving_world,
fixed_id.as_deref(),
*fixed_port,
*fixed_world,
snap_world.is_some(),
true,
)
.absolute()
.inset_0()
.into_any_element(),
);
} else {
(
fixed_id.as_deref(),
*fixed_port,
*fixed_world,
snap_id.as_deref(),
*snap_port,
moving_world,
true,
snap_world.is_some(),
)
};
elements.push(build_connector_preview(
*mode,
s_id,
s_port,
s_world,
t_id,
t_port,
t_world,
s_ring,
t_ring,
&authoring.painted_items,
camera,
vp_origin,
brand,
white,
));
}
Some(EdgelessGesture::DrawStroke {
highlighter,
@@ -440,323 +476,123 @@ pub fn build_edgeless_authoring_overlay(
}
// 3. Inline label editor overlay (Shape / Connector / SurfaceText / Frame title).
if let Some(editor) = authoring.label_editor() {
let in_place = editor.target.rotates_in_place();
let eff_rotate = editor.effective_rotate_deg();
let (box_x, box_y, box_w, box_h, layout_x, layout_y, layout_w, layout_h) =
super::label_editor_screen_box(
editor,
camera,
vp_origin,
viewport_width,
viewport_height,
theme,
window,
);
if box_w > 0.0 && box_h > 0.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 zoom = camera.zoom;
let editor_clone = editor.clone();
let mut el = div()
.absolute()
.left(px(box_x))
.top(px(box_y))
.w(px(box_w))
.h(px(box_h))
.overflow_hidden();
if !in_place {
el = el.rounded(px(4.0)).bg(bg).border_2().border_color(border);
}
let el = el
.snapshot("edgeless.inline_edit", Some(EDGELESS_VIEWPORT_ID))
.snapshot_text(display)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
if let Some(laid_out) = layout_label_editor_paragraph(
&editor_clone,
layout_w,
zoom,
theme,
window,
) {
let (ox, oy) = label_editor_text_origin(
&editor_clone,
layout_h,
f32::from(laid_out.size().height),
zoom,
);
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,
)];
let shape_x = f32::from(bounds.origin.x) + layout_x - box_x;
let shape_y = f32::from(bounds.origin.y) + layout_y - box_y;
let origin_pt = point(px(shape_x + ox), px(shape_y + oy));
if in_place {
let pad_x = editor_clone
.shape_style
.as_ref()
.map_or(0.0, |st| st.padding[1] * zoom);
let inner_w = (layout_w - 2.0 * pad_x).max(0.0);
if inner_w > 0.0 && layout_h > 0.0 {
let cx_win = shape_x + layout_w * 0.5;
let cy_win = shape_y + layout_h * 0.5;
let rot = if eff_rotate.abs() > 1e-4 {
ui::TransformationMatrix::unit()
.translate(point(
ui::ScaledPixels(cx_win),
ui::ScaledPixels(cy_win),
))
.rotate(ui::radians(eff_rotate.to_radians()))
.translate(point(
ui::ScaledPixels(-cx_win),
ui::ScaledPixels(-cy_win),
))
} else {
ui::TransformationMatrix::unit()
};
let mask_bleed = if matches!(
editor_clone.target,
super::LabelTarget::SurfaceText { .. }
) {
2.0
} else {
0.0
};
let mask = Bounds::new(
point(
px(shape_x + pad_x - mask_bleed),
px(shape_y - mask_bleed),
),
size(
px(inner_w + 2.0 * mask_bleed),
px(layout_h + 2.0 * mask_bleed),
),
);
window.with_paint_transformation(rot, |window| {
window.with_local_paint_mask(
ui::ContentMask { bounds: mask },
|window| {
laid_out.paint_at(
origin_pt,
&selections,
&carets,
None,
window,
cx,
);
},
);
});
}
} else {
laid_out.paint_at(
origin_pt,
&selections,
&carets,
None,
window,
cx,
);
}
}
},
)
.size_full(),
);
elements.push(el.into_any_element());
}
if let Some(editor) = authoring.label_editor()
&& let Some(el) = build_inline_label_editor_overlay(
editor,
camera,
vp_origin,
viewport_width,
viewport_height,
palette,
theme,
window,
)
{
elements.push(el);
}
elements
}
/// Local `(x, y)` origin for the laid-out text inside an open [`EdgelessLabelEditor`] box.
pub fn label_editor_text_origin(
editor: &EdgelessLabelEditor,
box_height: f32,
text_height: f32,
zoom: f32,
) -> (f32, f32) {
if let Some(st) = &editor.shape_style {
let py = st.padding[0] * zoom;
let pad_x = st.padding[1] * zoom;
let top = match st.vertical_align {
blocksuite_playground_doc::read::VerticalAlign::Top => py,
blocksuite_playground_doc::read::VerticalAlign::Center => {
((box_height - text_height) * 0.5).max(py)
}
blocksuite_playground_doc::read::VerticalAlign::Bottom => box_height - py - text_height,
};
(pad_x, top)
} else {
(6.0, 6.0)
}
fn build_creation_rect_preview(
r: super::WorldRect,
camera: EdgelessCamera,
vp_origin: Point<Pixels>,
brand: Hsla,
) -> AnyElement {
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);
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()
}
/// Lay out an open [`EdgelessLabelEditor`]'s display text (including IME underline marks)
/// for both overlay painting and inside-label pointer hit-testing.
pub fn layout_label_editor_paragraph(
editor: &EdgelessLabelEditor,
width: f32,
zoom: f32,
theme: PlaygroundTheme,
window: &ui::Window,
) -> Option<crate::rich_text::LaidOutRichParagraph> {
let pad_x = editor
.shape_style
.as_ref()
.map_or(6.0, |st| st.padding[1] * zoom);
let min_wrap = if editor.shape_style.is_some() {
zoom.max(0.25)
} else {
20.0
};
let wrap_w = (width - 2.0 * pad_x).max(min_wrap);
let display = editor.display_text();
let marked = editor.marked_range();
let mut delta = Vec::new();
if let Some(m) = &marked {
let (sel, _) = editor.shown_selection();
let b0 = utf16_to_byte(&display, m.start);
let b1 = utf16_to_byte(&display, m.end);
let s0 = utf16_to_byte(&display, sel.start).clamp(b0, b1);
let s1 = utf16_to_byte(&display, sel.end).clamp(s0, b1);
if b0 > 0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[..b0].to_string()),
format: None,
});
}
if s0 > b0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[b0..s0].to_string()),
format: Some(BTreeMap::from([("underline".to_string(), Any::True)])),
});
}
if s1 > s0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[s0..s1].to_string()),
format: Some(BTreeMap::from([
("underline".to_string(), Any::True),
(
"background".to_string(),
Any::String("var(--affine-text-highlight-blue)".into()),
),
])),
});
}
if b1 > s1 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[s1..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,
});
}
if let Some(st) = &editor.shape_style
&& matches!(st.font_style.as_str(), "italic" | "oblique")
{
for op in &mut delta {
if let TextDeltaOp::Insert { format, .. } = op {
format
.get_or_insert_with(Default::default)
.entry("italic".into())
.or_insert(Any::True);
#[allow(clippy::too_many_arguments)]
fn build_connector_preview(
mode: ConnectorMode,
source_id: Option<&str>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
target_id: Option<&str>,
target_port: Option<[f64; 2]>,
target_world: (f32, f32),
highlight_start: bool,
highlight_end: bool,
items: &[super::SpatialItemInfo],
camera: EdgelessCamera,
vp_origin: Point<Pixels>,
brand: Hsla,
white: Hsla,
) -> AnyElement {
let pts_screen: Vec<Point<Pixels>> = crate::surface::preview_connector_polyline(
mode,
source_id,
source_port,
source_world,
target_id,
target_port,
target_world,
items,
)
.into_iter()
.map(|(wx, wy)| camera.world_to_screen(point(px(wx), px(wy)), vp_origin))
.collect();
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
if pts_screen.len() < 2 {
return;
}
}
}
let style = if let Some(st) = &editor.shape_style {
let color_str = match &st.color {
blocksuite_playground_doc::read::ColorValue::Single(v) => v.as_str(),
blocksuite_playground_doc::read::ColorValue::Themed { light, dark } => {
if theme == PlaygroundTheme::Light {
light.as_str()
} else {
dark.as_str()
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let mut pb = PathBuilder::stroke(px(2.0));
let first = point(
px(ox + f32::from(pts_screen[0].x)),
px(oy + f32::from(pts_screen[0].y)),
);
pb.move_to(first);
for p in &pts_screen[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, brand);
}
let last_raw = *pts_screen.last().unwrap();
let last = point(
px(ox + f32::from(last_raw.x)),
px(oy + f32::from(last_raw.y)),
);
for (pt, highlight) in [(first, highlight_start), (last, highlight_end)] {
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,
));
}
}
};
let text_color = theme
.css_color(color_str)
.or_else(|| theme.css_var(color_str))
.unwrap_or_else(|| theme.palette().text_primary);
let font_family: ui::SharedString = if st.font_family.is_empty() {
FONT_SANS.into()
} else {
st.font_family
.trim_start_matches("blocksuite:surface:")
.to_string()
.into()
};
let font_size = (st.font_size * zoom).max(0.5);
let base_weight = ui::FontWeight(st.font_weight);
let ts = window.text_system();
let mut face = ui::font(font_family.clone());
face.weight = base_weight;
face.fallbacks = Some(crate::default_font_fallbacks());
let font_id = ts.resolve_font(&face);
let font_px = px(font_size);
let ascent = f32::from(ts.ascent(font_id, font_px));
let descent = f32::from(ts.descent(font_id, font_px)).abs();
RichParagraphStyle {
font_family,
font_size,
base_weight,
line_height: (ascent + descent).max(0.5),
baseline_offset: Some(ascent),
text_color,
align: match st.text_align {
blocksuite_playground_doc::read::TextAlign::Left => ui::TextAlign::Left,
blocksuite_playground_doc::read::TextAlign::Center => ui::TextAlign::Center,
blocksuite_playground_doc::read::TextAlign::Right => ui::TextAlign::Right,
},
gfx_per_delta_rtl: true,
..RichParagraphStyle::from_theme(theme.mode())
}
} else {
let is_frame_title = matches!(editor.target, super::LabelTarget::FrameTitle { .. });
RichParagraphStyle {
font_family: FONT_SANS.into(),
font_size: 14.0,
base_weight: if is_frame_title {
ui::FontWeight(500.0)
} else {
ui::FontWeight::NORMAL
},
line_height: 20.0,
text_color: theme.palette().text_primary,
gfx_per_delta_rtl: !is_frame_title,
..RichParagraphStyle::from_theme(theme.mode())
}
};
let para = RichParagraph::from_delta(delta).ok()?;
Some(para.layout(window.text_system(), &style, wrap_w))
},
)
.absolute()
.inset_0()
.into_any_element()
}
@@ -0,0 +1,332 @@
//! Inline label editor overlay painting and RichParagraph layout for Edgeless.
use std::collections::BTreeMap;
use ui::{AnyElement, Bounds, 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, EdgelessCamera, EdgelessLabelEditor, utf16_to_byte};
/// Build the screen-space inline label editor overlay element when a label editor is active.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_inline_label_editor_overlay(
editor: &EdgelessLabelEditor,
camera: EdgelessCamera,
vp_origin: Point<Pixels>,
viewport_width: f32,
viewport_height: f32,
palette: &Palette,
theme: PlaygroundTheme,
window: &ui::Window,
) -> Option<AnyElement> {
let in_place = editor.target.rotates_in_place();
let eff_rotate = editor.effective_rotate_deg();
let (box_x, box_y, box_w, box_h, layout_x, layout_y, layout_w, layout_h) =
super::label_editor_screen_box(
editor,
camera,
vp_origin,
viewport_width,
viewport_height,
theme,
window,
);
if box_w <= 0.0 || box_h <= 0.0 {
return None;
}
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 zoom = camera.zoom;
let editor_clone = editor.clone();
let mut el = div()
.absolute()
.left(px(box_x))
.top(px(box_y))
.w(px(box_w))
.h(px(box_h))
.overflow_hidden();
if !in_place {
el = el.rounded(px(4.0)).bg(bg).border_2().border_color(border);
}
let el = el
.snapshot("edgeless.inline_edit", Some(EDGELESS_VIEWPORT_ID))
.snapshot_text(display)
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
if let Some(laid_out) =
layout_label_editor_paragraph(&editor_clone, layout_w, zoom, theme, window)
{
let (ox, oy) = label_editor_text_origin(
&editor_clone,
layout_h,
f32::from(laid_out.size().height),
zoom,
);
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,
)];
let shape_x = f32::from(bounds.origin.x) + layout_x - box_x;
let shape_y = f32::from(bounds.origin.y) + layout_y - box_y;
let origin_pt = point(px(shape_x + ox), px(shape_y + oy));
if in_place {
let pad_x = editor_clone
.shape_style
.as_ref()
.map_or(0.0, |st| st.padding[1] * zoom);
let inner_w = (layout_w - 2.0 * pad_x).max(0.0);
if inner_w > 0.0 && layout_h > 0.0 {
let cx_win = shape_x + layout_w * 0.5;
let cy_win = shape_y + layout_h * 0.5;
let rot = if eff_rotate.abs() > 1e-4 {
ui::TransformationMatrix::unit()
.translate(point(
ui::ScaledPixels(cx_win),
ui::ScaledPixels(cy_win),
))
.rotate(ui::radians(eff_rotate.to_radians()))
.translate(point(
ui::ScaledPixels(-cx_win),
ui::ScaledPixels(-cy_win),
))
} else {
ui::TransformationMatrix::unit()
};
let mask_bleed = if matches!(
editor_clone.target,
super::LabelTarget::SurfaceText { .. }
) {
2.0
} else {
0.0
};
let mask = Bounds::new(
point(
px(shape_x + pad_x - mask_bleed),
px(shape_y - mask_bleed),
),
size(
px(inner_w + 2.0 * mask_bleed),
px(layout_h + 2.0 * mask_bleed),
),
);
window.with_paint_transformation(rot, |window| {
window.with_local_paint_mask(
ui::ContentMask { bounds: mask },
|window| {
laid_out.paint_at(
origin_pt,
&selections,
&carets,
None,
window,
cx,
);
},
);
});
}
} else {
laid_out.paint_at(origin_pt, &selections, &carets, None, window, cx);
}
}
},
)
.size_full(),
);
Some(el.into_any_element())
}
/// Local `(x, y)` origin for the laid-out text inside an open [`EdgelessLabelEditor`] box.
pub fn label_editor_text_origin(
editor: &EdgelessLabelEditor,
box_height: f32,
text_height: f32,
zoom: f32,
) -> (f32, f32) {
if let Some(st) = &editor.shape_style {
let py = st.padding[0] * zoom;
let pad_x = st.padding[1] * zoom;
let top = match st.vertical_align {
blocksuite_playground_doc::read::VerticalAlign::Top => py,
blocksuite_playground_doc::read::VerticalAlign::Center => {
((box_height - text_height) * 0.5).max(py)
}
blocksuite_playground_doc::read::VerticalAlign::Bottom => box_height - py - text_height,
};
(pad_x, top)
} else {
(6.0, 6.0)
}
}
/// Lay out an open [`EdgelessLabelEditor`]'s display text (including IME underline marks)
/// for both overlay painting and inside-label pointer hit-testing.
pub fn layout_label_editor_paragraph(
editor: &EdgelessLabelEditor,
width: f32,
zoom: f32,
theme: PlaygroundTheme,
window: &ui::Window,
) -> Option<crate::rich_text::LaidOutRichParagraph> {
let pad_x = editor
.shape_style
.as_ref()
.map_or(6.0, |st| st.padding[1] * zoom);
let min_wrap = if editor.shape_style.is_some() {
zoom.max(0.25)
} else {
20.0
};
let wrap_w = (width - 2.0 * pad_x).max(min_wrap);
let display = editor.display_text();
let marked = editor.marked_range();
let mut delta = Vec::new();
if let Some(m) = &marked {
let (sel, _) = editor.shown_selection();
let b0 = utf16_to_byte(&display, m.start);
let b1 = utf16_to_byte(&display, m.end);
let s0 = utf16_to_byte(&display, sel.start).clamp(b0, b1);
let s1 = utf16_to_byte(&display, sel.end).clamp(s0, b1);
if b0 > 0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[..b0].to_string()),
format: None,
});
}
if s0 > b0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[b0..s0].to_string()),
format: Some(BTreeMap::from([("underline".to_string(), Any::True)])),
});
}
if s1 > s0 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[s0..s1].to_string()),
format: Some(BTreeMap::from([
("underline".to_string(), Any::True),
(
"background".to_string(),
Any::String("var(--affine-text-highlight-blue)".into()),
),
])),
});
}
if b1 > s1 {
delta.push(TextDeltaOp::Insert {
insert: TextInsert::Text(display[s1..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,
});
}
if let Some(st) = &editor.shape_style
&& matches!(st.font_style.as_str(), "italic" | "oblique")
{
for op in &mut delta {
if let TextDeltaOp::Insert { format, .. } = op {
format
.get_or_insert_with(Default::default)
.entry("italic".into())
.or_insert(Any::True);
}
}
}
let style = if let Some(st) = &editor.shape_style {
let color_str = match &st.color {
blocksuite_playground_doc::read::ColorValue::Single(v) => v.as_str(),
blocksuite_playground_doc::read::ColorValue::Themed { light, dark } => {
if theme == PlaygroundTheme::Light {
light.as_str()
} else {
dark.as_str()
}
}
};
let text_color = theme
.css_color(color_str)
.or_else(|| theme.css_var(color_str))
.unwrap_or_else(|| theme.palette().text_primary);
let font_family: ui::SharedString = if st.font_family.is_empty() {
FONT_SANS.into()
} else {
st.font_family
.trim_start_matches("blocksuite:surface:")
.to_string()
.into()
};
let font_size = (st.font_size * zoom).max(0.5);
let base_weight = ui::FontWeight(st.font_weight);
let ts = window.text_system();
let mut face = ui::font(font_family.clone());
face.weight = base_weight;
face.fallbacks = Some(crate::default_font_fallbacks());
let font_id = ts.resolve_font(&face);
let font_px = px(font_size);
let ascent = f32::from(ts.ascent(font_id, font_px));
let descent = f32::from(ts.descent(font_id, font_px)).abs();
RichParagraphStyle {
font_family,
font_size,
base_weight,
line_height: (ascent + descent).max(0.5),
baseline_offset: Some(ascent),
text_color,
align: match st.text_align {
blocksuite_playground_doc::read::TextAlign::Left => ui::TextAlign::Left,
blocksuite_playground_doc::read::TextAlign::Center => ui::TextAlign::Center,
blocksuite_playground_doc::read::TextAlign::Right => ui::TextAlign::Right,
},
gfx_per_delta_rtl: true,
..RichParagraphStyle::from_theme(theme.mode())
}
} else {
let is_frame_title = matches!(editor.target, super::LabelTarget::FrameTitle { .. });
RichParagraphStyle {
font_family: FONT_SANS.into(),
font_size: 14.0,
base_weight: if is_frame_title {
ui::FontWeight(500.0)
} else {
ui::FontWeight::NORMAL
},
line_height: 20.0,
text_color: theme.palette().text_primary,
gfx_per_delta_rtl: !is_frame_title,
..RichParagraphStyle::from_theme(theme.mode())
}
};
let para = RichParagraph::from_delta(delta).ok()?;
Some(para.layout(window.text_system(), &style, wrap_w))
}
@@ -514,6 +514,33 @@ pub fn prepare_edgeless_scene(
_ => None,
})
.collect();
let mut direct_parent_group: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for (_, elements) in &surface_nodes {
for el in *elements {
if let blocksuite_playground_doc::read::SurfaceElementKind::Group {
children,
..
} = &el.kind
{
for cid in children {
direct_parent_group.insert(cid.clone(), el.id.clone());
}
}
}
}
let resolve_outermost_group = |id: &str| -> Option<String> {
let mut cur = direct_parent_group.get(id)?.as_str();
let mut depth = 0;
while let Some(next) = direct_parent_group.get(cur) {
if next == cur || depth >= 16 {
break;
}
cur = next.as_str();
depth += 1;
}
Some(cur.to_string())
};
for item in order.iter() {
match *item {
PaintItem::Frame(i) => {
@@ -530,6 +557,8 @@ pub fn prepare_edgeless_scene(
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: f.frame_children.clone(),
group_children: Vec::new(),
parent_group_id: resolve_outermost_group(&f.id),
title_pill_rect: Some(f.title_pill_rect),
});
}
@@ -547,6 +576,8 @@ pub fn prepare_edgeless_scene(
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: Vec::new(),
group_children: Vec::new(),
parent_group_id: resolve_outermost_group(&n.id),
title_pill_rect: None,
});
}
@@ -564,6 +595,8 @@ pub fn prepare_edgeless_scene(
stroke_width: 1.0,
polyline: Vec::new(),
frame_children: Vec::new(),
group_children: Vec::new(),
parent_group_id: resolve_outermost_group(&t.id),
title_pill_rect: None,
});
}
@@ -633,6 +666,14 @@ pub fn prepare_edgeless_scene(
.get(id)
.and_then(|o| o.rotate_deg)
.unwrap_or(el.rotate as f32);
let group_children = match &el.kind {
blocksuite_playground_doc::read::SurfaceElementKind::Group {
children,
..
} => children.clone(),
_ => Vec::new(),
};
let parent_group_id = resolve_outermost_group(&el.id);
built_items.push(SpatialItemInfo {
id: el.id.clone(),
kind,
@@ -650,6 +691,8 @@ pub fn prepare_edgeless_scene(
stroke_width,
polyline,
frame_children: Vec::new(),
group_children,
parent_group_id,
title_pill_rect: None,
});
}
@@ -23,6 +23,24 @@ pub enum ShapePreset {
}
impl ShapePreset {
pub const ALL: [Self; 5] = [
Self::Rect,
Self::Ellipse,
Self::Diamond,
Self::Triangle,
Self::RoundedRect,
];
pub fn next(self) -> Self {
let i = Self::ALL.iter().position(|&p| p == self).unwrap_or(0);
Self::ALL[(i + 1) % Self::ALL.len()]
}
pub fn prev(self) -> Self {
let i = Self::ALL.iter().position(|&p| p == self).unwrap_or(0);
Self::ALL[(i + Self::ALL.len() - 1) % Self::ALL.len()]
}
pub fn as_spec_str(self) -> &'static str {
match self {
Self::Rect => "rect",
@@ -187,11 +187,30 @@ pub struct Preedit {
pub selected: Range<usize>,
}
/// Granularity of an active mouse drag selection in the Page editor.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum DragSelectionMode {
#[default]
Character,
/// Double-click + drag: anchor word range `(block_id, start_utf16, end_utf16)`.
Word {
block_id: String,
start: u64,
end: u64,
},
/// Triple-click + drag: anchor paragraph block id.
Paragraph { block_id: String },
}
#[derive(Default)]
pub struct EditorSession {
pub selection: Option<DocumentSelection>,
/// Selected whole-block IDs in document order (entered via `Escape` or second `Mod-a`).
pub block_selection: Vec<String>,
/// Anchor block ID for `Shift+ArrowUp/Down` block-selection extension.
pub block_selection_anchor: Option<String>,
/// Focus block ID for `Shift+ArrowUp/Down` block-selection extension.
pub block_selection_focus: Option<String>,
pub goal_x: Option<f32>,
pub preedit: Option<Preedit>,
pub relative_selection: Option<SelectionSnapshot>,
@@ -200,6 +219,10 @@ pub struct EditorSession {
pub reveal: bool,
/// The primary button is held and extends the selection.
pub dragging: bool,
/// Granularity of the active mouse drag (character, word, or paragraph).
pub drag_mode: DragSelectionMode,
/// Whether the pointer has moved since mouse-down during a multi-click drag.
pub drag_moved: bool,
/// The `/` that opened the slash menu from typed text: its block and a relative
/// position naming that character.
pub slash_trigger: Option<(String, SelectionSnapshot)>,
@@ -80,6 +80,59 @@ impl Overlays {
}
}
/// Scroll a wide table sideways so the active cell `[cell_left, cell_right]` and its
/// caret at `caret_x` (all relative to `code.area.x`, unscrolled) stay inside the viewport.
pub fn reveal_table_cell_x(
&mut self,
block_id: &str,
cell_left: f32,
cell_right: f32,
caret_x: f32,
code: CodeScroll,
) {
let current = self.code_scroll_x_for(block_id, code);
let view_w = code.area.w;
let mut next = current;
if cell_right - cell_left <= view_w {
if cell_left < next {
next = cell_left;
} else if cell_right > next + view_w {
next = cell_right - view_w;
}
} else if caret_x < next + 8.0 {
next = (caret_x - 8.0).max(0.0);
} else if caret_x > next + view_w - 8.0 {
next = caret_x - view_w + 8.0;
}
let next = next.clamp(0.0, code.max_x).round();
if next > 0.0 {
self.code_scroll.insert(block_id.to_string(), next);
} else {
self.code_scroll.remove(block_id);
}
}
/// Begin dragging one or more blocks from a gutter drag handle.
pub fn start_drag(&mut self, block_id: String, dragged_ids: Vec<String>, now_ms: f64) {
self.close_slash(now_ms);
self.close_link_field();
let ids = if dragged_ids.is_empty() {
vec![block_id.clone()]
} else {
dragged_ids
};
self.drag = Some(super::BlockDrag {
block_id,
dragged_ids: ids,
slot: None,
});
}
/// Whether database creation/editing is restricted (e.g. mobile read-only mode).
pub fn set_database_readonly(&mut self, readonly: bool) {
self.database_readonly = readonly;
}
/// Whether a block's disclosure chevron is turning between its two states.
pub fn chevron_turning(&self, block_id: &str) -> bool {
self.chevrons.contains_key(block_id)
@@ -266,6 +266,9 @@ impl KeyboardToolbarAction {
SlashCommand::Code => "code_block",
SlashCommand::NewDoc => "new_page",
SlashCommand::LinkedDoc => "linked_page",
SlashCommand::Table => "table",
SlashCommand::Equation => "equation",
SlashCommand::Database => "database",
},
Self::EquationBlock => "equation_block",
Self::Table => "table",
+19 -2
View File
@@ -41,9 +41,9 @@ pub use scrollbar::{
};
pub use slash::{
SLASH_ITEMS, SlashCommand, SlashItem, SlashMenu, SlashRow, filter_slash_items,
slash_item_by_id, slash_rows, slash_rows_for_query,
filter_slash_items_for, slash_item_by_id, slash_rows, slash_rows_for_query,
};
pub use table_cell::InlineTableCell;
pub use table_cell::{InlineTableCell, TableCellDragMode};
pub use toolbar::LinkBar;
pub use toolbar::{
ActiveSelection, FormatAction, MarkState, SelectionFormat, marks_in_range, normalize_url,
@@ -272,6 +272,7 @@ impl DropSlot {
#[derive(Clone, Debug, PartialEq)]
pub(super) struct BlockDrag {
pub(super) block_id: String,
pub(super) dragged_ids: Vec<String>,
pub(super) slot: Option<DropSlot>,
}
@@ -289,6 +290,12 @@ pub enum DocEdit {
child_id: String,
new_index: u64,
},
/// Reorder a multi-block selection as one atomic undo step before `insert_index` in `parent_id`.
ReorderMany {
parent_id: String,
child_ids: Vec<String>,
insert_index: usize,
},
Slash {
block_id: String,
command: SlashCommand,
@@ -429,6 +436,15 @@ pub enum OverlayEvent {
column_id: String,
screen_pos: Option<(f32, f32)>,
},
/// Pointer press on an `affine:table` cell (supports click, double/triple click, Shift+click, drag).
TableCellMouseDown {
block_id: String,
row_id: String,
column_id: String,
screen_pos: (f32, f32),
click_count: usize,
shift: bool,
},
/// Step the active PDF page preview of an `affine:attachment` block by `delta` (`-1` / `+1`).
AttachmentPdfPage {
block_id: String,
@@ -600,6 +616,7 @@ pub struct Overlays {
pub(super) context_menu: Option<ContextMenuState>,
pub(super) context_toast: Option<ContextToast>,
pub(super) context_toast_generation: u64,
pub(super) database_readonly: bool,
pub format_cache: Option<FormatCache>,
}
@@ -71,20 +71,20 @@ impl Overlays {
let layout = scene.layout;
let mut elements = Vec::new();
// The block being dragged is tinted where it still sits.
if let Some(block) = self
.drag
.as_ref()
.and_then(|drag| layout.block(&drag.block_id))
{
let rect = block.rect();
if viewport.intersects(&rect) {
elements.push(
place(viewport.to_local(&rect))
.rounded(px(4.0))
.bg(palette.hover)
.into_any_element(),
);
// The dragged blocks are tinted where they still sit.
if let Some(drag) = self.drag.as_ref() {
for dragged_id in &drag.dragged_ids {
if let Some(block) = layout.block(dragged_id) {
let rect = block.rect();
if viewport.intersects(&rect) {
elements.push(
place(viewport.to_local(&rect))
.rounded(px(4.0))
.bg(palette.hover)
.into_any_element(),
);
}
}
}
}
@@ -344,11 +344,13 @@ impl Overlays {
cx.stop_propagation();
let pos = (f32::from(ev.position.x), f32::from(ev.position.y));
view.dispatch_overlay(
OverlayEvent::FocusTableCell {
OverlayEvent::TableCellMouseDown {
block_id: bid.clone(),
row_id: rid.clone(),
column_id: cid.clone(),
screen_pos: Some(pos),
screen_pos: pos,
click_count: ev.click_count,
shift: ev.modifiers.shift,
},
w,
cx,
@@ -185,7 +185,10 @@ impl Overlays {
let anchor = scene.world_to_screen(&anchor_world);
let viewport = scene.popover_viewport();
let items = filter_slash_items(&menu.query);
let items = filter_slash_items_for(&menu.query, !self.database_readonly);
if items.is_empty() {
return None;
}
menu.selected = menu.selected.min(items.len().saturating_sub(1));
let (rows, content_height) = slash_rows_for_query(&items, &menu.query);
let show_query = !menu.query_in_document;
@@ -285,17 +288,6 @@ impl Overlays {
}
list = list.child(header.child(group));
}
SlashRow::Empty => {
let mut empty = base
.text_size(px(TYPOGRAPHY.font_sm_px))
.text_color(palette.text_secondary);
if fully_visible {
empty = empty
.snapshot("overlay.slash_menu.empty", Some("overlay.slash_menu"))
.snapshot_text("No results");
}
list = list.child(empty.child("No results"));
}
SlashRow::Item(index) => {
let item = items[index];
let active = index == selected;
+54 -13
View File
@@ -15,6 +15,12 @@ pub enum SlashCommand {
NewDoc,
/// Replaces `/query` with `@` and opens the `@` linked-document picker at the caret.
LinkedDoc,
/// Inserts a default 2x2 `affine:table` block and focuses its first cell.
Table,
/// Inserts a block-level `affine:latex` equation and opens the equation editor.
Equation,
/// Inserts a default Table-view `affine:database` block with one initial row.
Database,
}
impl SlashCommand {
@@ -36,7 +42,16 @@ impl SlashCommand {
language: None,
caption: String::new(),
},
Self::NewDoc | Self::LinkedDoc => BlockSpec::Paragraph {
Self::Table => BlockSpec::Table {
rows: vec![
vec![String::new(), String::new()],
vec![String::new(), String::new()],
],
},
Self::Equation => BlockSpec::Latex {
latex: String::new(),
},
Self::NewDoc | Self::LinkedDoc | Self::Database => BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
@@ -80,9 +95,9 @@ const fn slash_item(
}
/// Every slash menu item, in menu order; items of one group are adjacent. The order is
/// BlockSuite's (text, headings, code, quote, divider, then lists), with all six headings
/// in the list itself so each is one filter away.
pub const SLASH_ITEMS: [SlashItem; 16] = [
/// BlockSuite's (text, headings, code, quote, divider, then lists, then content/database),
/// with all six headings in the list itself so each is one filter away.
pub const SLASH_ITEMS: [SlashItem; 19] = [
slash_item(
"text",
"Text",
@@ -227,6 +242,33 @@ pub const SLASH_ITEMS: [SlashItem; 16] = [
&["collapse", "fold"],
SlashCommand::List(ListType::Toggle),
),
slash_item(
"table",
"Table",
"Create a simple table.",
"Content & Media",
"SquareIcon",
&["grid", "rows", "columns"],
SlashCommand::Table,
),
slash_item(
"equation",
"Equation",
"Create a LaTeX equation block.",
"Content & Media",
"TeXIcon",
&["math", "latex", "formula", "tex"],
SlashCommand::Equation,
),
slash_item(
"database",
"Database",
"Create a table database.",
"Content & Media",
"SquareIcon",
&["table view", "db", "kanban", "board"],
SlashCommand::Database,
),
];
/// Look up a built-in slash item by its stable `id` (shared by `KeyboardToolbar`).
@@ -294,6 +336,11 @@ pub fn substring_match_score(name: &str, query: &str) -> f64 {
/// descending [`substring_match_score`] against the title when `query` is non-empty.
/// An empty query returns every item in menu order.
pub fn filter_slash_items(query: &str) -> Vec<&'static SlashItem> {
filter_slash_items_for(query, true)
}
/// Like [`filter_slash_items`], omitting [`SlashCommand::Database`] when `allow_database` is false.
pub fn filter_slash_items_for(query: &str, allow_database: bool) -> Vec<&'static SlashItem> {
let needle: String = query
.chars()
.filter(|ch| !ch.is_whitespace())
@@ -301,6 +348,7 @@ pub fn filter_slash_items(query: &str) -> Vec<&'static SlashItem> {
.collect();
let mut matched: Vec<&'static SlashItem> = SLASH_ITEMS
.iter()
.filter(|item| allow_database || item.command != SlashCommand::Database)
.filter(|item| {
needle.is_empty()
|| is_fuzzy_match(item.title, &needle)
@@ -324,16 +372,12 @@ pub fn filter_slash_items(query: &str) -> Vec<&'static SlashItem> {
pub enum SlashRow {
Header(&'static str),
Item(usize),
Empty,
}
/// Rows of the slash menu list as `(row, y, height)`, and the list's total height.
pub fn slash_rows(items: &[&'static SlashItem]) -> (Vec<(SlashRow, f32, f32)>, f32) {
if items.is_empty() {
return (
vec![(SlashRow::Empty, 0.0, SLASH_ITEM_HEIGHT)],
SLASH_ITEM_HEIGHT,
);
return (Vec::new(), 0.0);
}
let mut rows = Vec::new();
let mut y = 0.0;
@@ -362,10 +406,7 @@ pub fn slash_rows_for_query(
return slash_rows(items);
}
if items.is_empty() {
return (
vec![(SlashRow::Empty, 0.0, SLASH_ITEM_HEIGHT)],
SLASH_ITEM_HEIGHT,
);
return (Vec::new(), 0.0);
}
let mut rows = Vec::with_capacity(items.len());
let mut y = 0.0;
+24 -21
View File
@@ -262,14 +262,20 @@ impl Overlays {
}
OverlayEvent::PointerUp => {
if let Some(drag) = self.drag.take() {
if let Some(slot) = drag.slot
&& let Some(new_index) = slot.reorder_index()
{
effects.edits.push(DocEdit::Reorder {
parent_id: slot.parent_id,
child_id: drag.block_id,
new_index,
});
if let Some(slot) = drag.slot {
if drag.dragged_ids.len() > 1 {
effects.edits.push(DocEdit::ReorderMany {
parent_id: slot.parent_id,
child_ids: drag.dragged_ids,
insert_index: slot.insert_index,
});
} else if let Some(new_index) = slot.reorder_index() {
effects.edits.push(DocEdit::Reorder {
parent_id: slot.parent_id,
child_id: drag.block_id,
new_index,
});
}
}
effects.redraw = true;
}
@@ -399,12 +405,7 @@ impl Overlays {
}
OverlayEvent::ToggleCodePreview(_) | OverlayEvent::ExternalEmbedInteract { .. } => {}
OverlayEvent::DragStart(block_id) => {
self.close_slash(now_ms);
self.close_link_field();
self.drag = Some(BlockDrag {
block_id,
slot: None,
});
self.start_drag(block_id, Vec::new(), now_ms);
effects.redraw = true;
}
OverlayEvent::OpenEquationEditor { target, initial } => {
@@ -461,6 +462,7 @@ impl Overlays {
| OverlayEvent::KeyboardToolbar(_)
| OverlayEvent::InsertImageBytes { .. }
| OverlayEvent::FocusTableCell { .. }
| OverlayEvent::TableCellMouseDown { .. }
| OverlayEvent::AttachmentPdfPage { .. }
| OverlayEvent::OpenEmbedDoc { .. }
| OverlayEvent::LongPressWord { .. }
@@ -580,10 +582,11 @@ impl Overlays {
return effects;
}
let allow_database = !self.database_readonly;
let Some(menu) = self.open_slash_mut() else {
return effects;
};
let count = filter_slash_items(&menu.query).len();
let count = filter_slash_items_for(&menu.query, allow_database).len();
effects.handled = true;
effects.redraw = true;
match key {
@@ -594,14 +597,14 @@ impl Overlays {
menu.selected = (menu.selected + if back { count - 1 } else { 1 }) % count;
menu.reveal_selected = true;
}
"tab" => {}
"enter" if count > 0 => self.execute_slash(None, now_ms, &mut effects),
// When triggered in-document with no matching items, `Enter`, `Up`, and `Down`
// close the menu and pass through to the editor.
"enter" | "up" | "down" if menu.query_in_document => {
// When triggered in-document with no matching items (popover hidden), `Enter`,
// `Up`, and `Down` close the menu and pass through to the editor.
"enter" | "up" | "down" if count == 0 && menu.query_in_document => {
self.close_slash(now_ms);
effects.handled = false;
}
"tab" => {}
"enter" if count > 0 => self.execute_slash(None, now_ms, &mut effects),
"enter" | "escape" => {
self.close_slash(now_ms);
}
@@ -638,7 +641,7 @@ impl Overlays {
let Some(menu) = self.slash_menu() else {
return;
};
let items = filter_slash_items(&menu.query);
let items = filter_slash_items_for(&menu.query, !self.database_readonly);
let Some(item) = items.get(index.unwrap_or(menu.selected)) else {
return;
};
@@ -4,6 +4,15 @@ use std::ops::{Deref, DerefMut};
use crate::inline_input::AnchoredInlineInput;
/// Granularity of an active pointer drag inside a focused table cell.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TableCellDragMode {
#[default]
Character,
Word(usize, usize),
All,
}
/// Focused `affine:table` cell edited directly in place against its live `Y.Text`.
#[derive(Clone, Debug)]
pub struct InlineTableCell {
@@ -12,6 +21,8 @@ pub struct InlineTableCell {
pub column_id: String,
pub anchored: AnchoredInlineInput,
pub goal_x: Option<f32>,
pub dragging: bool,
pub drag_mode: TableCellDragMode,
}
impl Deref for InlineTableCell {
@@ -36,6 +47,8 @@ impl InlineTableCell {
column_id,
anchored: AnchoredInlineInput::new(initial, true),
goal_x: None,
dragging: false,
drag_mode: TableCellDragMode::Character,
}
}
}
@@ -212,6 +212,71 @@ pub fn preview_curve_cubic(
target_world: (f32, f32),
items: &[crate::edgeless::SpatialItemInfo],
) -> ((f32, f32), (f32, f32), (f32, f32), (f32, f32)) {
let (a, b) = resolve_preview_ports(
source_id,
source_port,
source_world,
target_id,
target_port,
target_world,
items,
);
let (p, q) = curve_controls(a, b);
(
(a.p.0 as f32, a.p.1 as f32),
(p.0 as f32, p.1 as f32),
(q.0 as f32, q.1 as f32),
(b.p.0 as f32, b.p.1 as f32),
)
}
#[allow(clippy::too_many_arguments)]
pub fn preview_connector_polyline(
mode: ConnectorMode,
source_id: Option<&str>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
target_id: Option<&str>,
target_port: Option<[f64; 2]>,
target_world: (f32, f32),
items: &[crate::edgeless::SpatialItemInfo],
) -> Vec<(f32, f32)> {
let (a, b) = resolve_preview_ports(
source_id,
source_port,
source_world,
target_id,
target_port,
target_world,
items,
);
match mode {
ConnectorMode::Straight => vec![(a.p.0 as f32, a.p.1 as f32), (b.p.0 as f32, b.p.1 as f32)],
ConnectorMode::Orthogonal => super::orthogonal::path(a, b)
.into_iter()
.map(|p| (p.0 as f32, p.1 as f32))
.collect(),
ConnectorMode::Curve => {
let (p, q) = curve_controls(a, b);
(0..=32)
.map(|i| {
let pt = cubic(a.p, p, q, b.p, i as f64 / 32.0);
(pt.0 as f32, pt.1 as f32)
})
.collect()
}
}
}
fn resolve_preview_ports(
source_id: Option<&str>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
target_id: Option<&str>,
target_port: Option<[f64; 2]>,
target_world: (f32, f32),
items: &[crate::edgeless::SpatialItemInfo],
) -> (Port, Port) {
let resolve_port = |id: Option<&str>, port: Option<[f64; 2]>, fallback: (f32, f32)| -> Port {
if let Some(id) = id
&& let Some(item) = items.iter().find(|i| i.id == id)
@@ -239,14 +304,9 @@ pub fn preview_curve_cubic(
bound: None,
}
};
let a = resolve_port(source_id, source_port, source_world);
let b = resolve_port(target_id, target_port, target_world);
let (p, q) = curve_controls(a, b);
(
(a.p.0 as f32, a.p.1 as f32),
(p.0 as f32, p.1 as f32),
(q.0 as f32, q.1 as f32),
(b.p.0 as f32, b.p.1 as f32),
resolve_port(source_id, source_port, source_world),
resolve_port(target_id, target_port, target_world),
)
}
+1 -1
View File
@@ -10,7 +10,7 @@ pub mod rtl;
mod shapes;
mod strokes;
pub use connector::preview_curve_cubic;
pub use connector::{preview_connector_polyline, preview_curve_cubic};
pub use mindmap::{
MindmapTree, MindmapTreeNode, build_mindmap_tree, collapsed_descendant_ids,
compute_mindmap_layout, mindmap_connectors, resolve_surface_element_bounds,
@@ -106,7 +106,7 @@ impl OverlayState {
Self::Default => &[],
Self::SlashMenuOpen => &["overlay.slash_menu", "overlay.slash_menu.item.text"],
Self::SlashMenuFiltered => &["overlay.slash_menu", "overlay.slash_menu.item.h1"],
Self::SlashMenuEmpty => &["overlay.slash_menu", "overlay.slash_menu.empty"],
Self::SlashMenuEmpty => &[],
Self::SlashMenuFlippedBottom => &["overlay.slash_menu"],
Self::FormatToolbarOpen | Self::FormatToolbarFlippedTop => &[
"overlay.format_toolbar",
@@ -497,20 +497,6 @@ impl PlaygroundView {
/// Replace the shown document, e.g. with one prepared by a host or a test.
pub fn set_document(&mut self, state: crate::DocState, cx: &mut ui::Context<Self>) {
let had_composing = self.editor.composing()
|| self
.overlays
.active_text_field()
.is_some_and(|f| f.composing())
|| self
.table_cell
.as_ref()
.is_some_and(|c| c.input.composing())
|| self
.edgeless
.authoring
.label_editor()
.is_some_and(|e| e.composing());
self.finish_inline_targets(crate::overlays::InlineTargetEnd::DiscardPreedit, None, None);
self.editor = Default::default();
self.overlays.reset();
@@ -555,7 +541,6 @@ impl PlaygroundView {
self.pdf_page_indices.clear();
self.keyboard_toolbar_dismissed = false;
self.ime_insets = crate::chrome::ImeInsetsState::default();
self.suppress_unselected_root_input = had_composing;
self.last_opened_embed_doc = None;
self.nav_history.clear();
self.page_id = None;
@@ -1,17 +1,21 @@
//! 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 blocksuite_playground_doc::read::{
BlockContent, BlockNode, ConnectorMode, NoteDisplayMode, PageSnapshot, SurfaceElement,
};
use ui::{Context, KeyDownEvent, Window};
use y_octo::{Any, SessionValue};
use ui::{Context, KeyDownEvent, Window, point, px, size};
use crate::PlaygroundView;
use super::{EdgelessGesture, EdgelessTool, SpatialItemInfo};
use super::{
EdgelessGesture, EdgelessTool, SpatialItemKind, layout_label_editor_paragraph, utf16_len,
};
#[cfg(test)]
use super::{HandleKind, ShapePreset, SpatialItemKind, collect_frame_children};
use super::{HandleKind, ShapePreset, collect_frame_children};
#[cfg(test)]
use blocksuite_playground_doc::fractional_index::generate_key_between;
#[cfg(test)]
use y_octo::Any;
/// Helper to compute the highest existing fractional index across all spatial items in a snapshot.
pub fn max_spatial_index(snapshot: &PageSnapshot) -> Option<String> {
@@ -198,6 +202,7 @@ impl PlaygroundView {
}
return false;
}
let word_mod = m.alt || (m.control && !cmd);
match key {
"escape" => {
self.edgeless_commit_inline_edit(window, cx);
@@ -211,6 +216,10 @@ impl PlaygroundView {
self.edgeless_label_edit(window, cx, |ed| ed.replace(None, "\n"));
return true;
}
"backspace" if word_mod => {
self.edgeless_label_edit(window, cx, |ed| ed.delete_word(false));
return true;
}
"backspace" => {
self.edgeless_label_edit(
window,
@@ -219,6 +228,10 @@ impl PlaygroundView {
);
return true;
}
"delete" if word_mod => {
self.edgeless_label_edit(window, cx, |ed| ed.delete_word(true));
return true;
}
"delete" => {
self.edgeless_label_edit(
window,
@@ -227,6 +240,34 @@ impl PlaygroundView {
);
return true;
}
"left" if cmd => {
ed.move_to_line_edge(false, m.shift);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return true;
}
"right" if cmd => {
ed.move_to_line_edge(true, m.shift);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return true;
}
"left" if word_mod => {
ed.move_word(true, m.shift);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return true;
}
"right" if word_mod => {
ed.move_word(false, m.shift);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return true;
}
"left" => {
ed.move_caret(true, m.shift);
self.edgeless_update_label_anchors();
@@ -241,6 +282,56 @@ impl PlaygroundView {
cx.notify();
return true;
}
"home" => {
ed.move_to_line_edge(false, m.shift);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return true;
}
"end" => {
ed.move_to_line_edge(true, m.shift);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
return true;
}
"up" | "down" => {
let down = key == "down";
self.edgeless_label_move_vertical(down, m.shift, window, 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);
self.edgeless_refresh_label_editor_from_snapshot();
self.edgeless_sync_shape_auto_height(window, cx);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
}
return true;
}
"y" if cmd && !m.shift => {
let commit = self
.page_mut()
.ok()
.and_then(|page| page.redo().ok().flatten());
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless_refresh_label_editor_from_snapshot();
self.edgeless_sync_shape_auto_height(window, cx);
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
}
return true;
}
"a" if cmd => {
ed.select_all();
self.edgeless_update_label_anchors();
@@ -303,8 +394,10 @@ impl PlaygroundView {
}
// 3. Canvas-level shortcuts when not inline-editing.
let plain = !cmd && !m.alt && !m.control;
let plain_no_shift = plain && !m.shift;
match key {
"space" if !cmd => {
"space" if plain => {
self.edgeless.authoring.space_pan = true;
return true;
}
@@ -320,59 +413,192 @@ impl PlaygroundView {
cx.notify();
return true;
}
"v" if !cmd => {
"v" if plain_no_shift => {
self.edgeless_select_tool(EdgelessTool::Select, window, cx);
return true;
}
"h" if !cmd => {
"h" if plain_no_shift => {
self.edgeless_select_tool(EdgelessTool::Hand, window, cx);
return true;
}
"n" if !cmd => {
"n" if plain_no_shift => {
self.edgeless_select_tool(EdgelessTool::Note, window, cx);
return true;
}
"s" if !cmd => {
let shape = self.edgeless.authoring.active_shape_type();
"s" if plain => {
let shape = match self.edgeless.authoring.tool {
EdgelessTool::Shape(cur) => {
if m.shift {
cur.prev()
} else {
cur.next()
}
}
_ => 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);
"c" if plain_no_shift => {
if self.edgeless.authoring.tool == EdgelessTool::Connector {
self.edgeless.authoring.connector_mode =
match self.edgeless.authoring.connector_mode {
ConnectorMode::Curve => ConnectorMode::Orthogonal,
ConnectorMode::Orthogonal => ConnectorMode::Straight,
ConnectorMode::Straight => ConnectorMode::Curve,
};
cx.notify();
} else {
self.edgeless_select_tool(EdgelessTool::Connector, window, cx);
}
return true;
}
"p" if !cmd => {
self.edgeless_select_tool(EdgelessTool::Brush, window, cx);
"p" if plain => {
let tool = if m.shift {
EdgelessTool::Highlighter
} else {
EdgelessTool::Brush
};
self.edgeless_select_tool(tool, window, cx);
return true;
}
"t" if !cmd => {
"t" if plain_no_shift => {
self.edgeless_select_tool(EdgelessTool::Text, window, cx);
return true;
}
"f" if !cmd => {
"f" if plain_no_shift => {
if !self.edgeless.authoring.selection.is_empty()
&& self.edgeless_wrap_selection_in_frame(cx)
{
return true;
}
self.edgeless_select_tool(EdgelessTool::Frame, window, cx);
return true;
}
"a" if cmd => {
"a" if cmd && !m.alt => {
let snap = self.snapshot.as_deref();
self.edgeless.authoring.selection = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| {
// Skip children that belong to a Group (their Group is selected instead)
// and skip `DocOnly` Notes (matching Web `edgeless-keyboard.ts:261-269`).
if i.parent_group_id.is_some() {
return false;
}
if i.kind == SpatialItemKind::Note
&& let Some(s) = snap
&& let Some(node) = find_block(s, &i.id)
&& matches!(
node.content,
BlockContent::Note {
display_mode: NoteDisplayMode::DocOnly,
..
}
)
{
return false;
}
true
})
.map(|i| i.id.clone())
.collect();
cx.notify();
return true;
}
"c" if cmd && !m.alt => {
self.edgeless_copy_selection(false, cx);
return true;
}
"x" if cmd && !m.alt => {
self.edgeless_copy_selection(true, cx);
return true;
}
"v" if cmd && !m.alt => {
if let Some(item) = cx.read_from_clipboard()
&& self.paste_edgeless_clipboard_item(&item, window, cx)
{
return true;
}
return false;
}
"g" if cmd && !m.alt => {
if m.shift {
self.edgeless_ungroup_selection(cx);
} else {
self.edgeless_group_selection(cx);
}
return true;
}
"=" | "+" if cmd && !m.alt => {
let (vw, vh) = self.edgeless_viewport_size();
self.edgeless_camera_transition = None;
self.edgeless.camera.zoom_in(
point(px(0.0), px(crate::TOPBAR_HEIGHT)),
size(px(vw), px(vh)),
);
self.edgeless.camera_initialized = true;
cx.notify();
return true;
}
"-" | "_" if cmd && !m.alt => {
let (vw, vh) = self.edgeless_viewport_size();
self.edgeless_camera_transition = None;
self.edgeless.camera.zoom_out(
point(px(0.0), px(crate::TOPBAR_HEIGHT)),
size(px(vw), px(vh)),
);
self.edgeless.camera_initialized = true;
cx.notify();
return true;
}
"0" if m.alt && !cmd && !m.control => {
let (vw, vh) = self.edgeless_viewport_size();
self.edgeless_camera_transition = None;
self.edgeless.camera.reset_zoom(
point(px(0.0), px(crate::TOPBAR_HEIGHT)),
size(px(vw), px(vh)),
);
self.edgeless.camera_initialized = true;
cx.notify();
return true;
}
"1" if m.alt && !cmd && !m.control => {
if let Some(snap) = self.snapshot.as_deref() {
let (vw, vh) = self.edgeless_viewport_size();
let bounds = self.edgeless.scene_world_bounds(snap);
self.edgeless_camera_transition = None;
self.edgeless
.camera
.fit_to_bounds(bounds, size(px(vw), px(vh)), 48.0);
self.edgeless.camera_initialized = true;
cx.notify();
}
return true;
}
"2" if m.alt && !cmd && !m.control => {
if let Some(sel_box) = self.edgeless.authoring.selection_world_box() {
let (vw, vh) = self.edgeless_viewport_size();
self.edgeless_camera_transition = None;
self.edgeless
.camera
.fit_to_bounds(sel_box, size(px(vw), px(vh)), 48.0);
self.edgeless.camera_initialized = true;
cx.notify();
}
return true;
}
"backspace" | "delete" => {
self.edgeless_delete_selection(cx);
return true;
}
"[" => {
"[" if plain_no_shift => {
self.edgeless_reorder_selection(false, cx);
return true;
}
"]" => {
"]" if plain_no_shift => {
self.edgeless_reorder_selection(true, cx);
return true;
}
@@ -389,123 +615,74 @@ impl PlaygroundView {
}
return true;
}
"y" if cmd && !m.shift => {
let commit = self
.page_mut()
.ok()
.and_then(|page| page.redo().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<Self>) {
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<SpatialItemInfo> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| self.edgeless.authoring.selection.contains(&i.id))
.cloned()
.collect();
let mut block_ids: Vec<String> = 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(
/// Move the active label editor caret up or down one visual line (or to start/end if single-line).
fn edgeless_label_move_vertical(
&mut self,
bring_to_front: bool,
down: bool,
extend: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
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<SpatialItemInfo> = 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<SpatialItemInfo> = 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));
let target_off = self.edgeless.authoring.label_editor().map(|ed| {
let len = utf16_len(&ed.input.text);
if !ed.input.multiline {
return if down { len } else { 0 };
}
}
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()
let Some(bounds) = self.edgeless_label_layout_screen_bounds(window) else {
return if down { len } else { 0 };
};
let zoom = self.edgeless.camera.zoom;
let Some(laid) = layout_label_editor_paragraph(
ed,
f32::from(bounds.size.width),
zoom,
self.theme,
window,
) else {
return if down { len } else { 0 };
};
let focus = ed.input.focus() as u64;
let caret = crate::rich_text::CaretPosition {
utf16_offset: focus,
affinity: crate::rich_text::WrapAffinity::Upstream,
};
let rect = laid.caret_rect(caret);
let step_y = f32::from(rect.size.height).max(12.0);
let next_y = if down {
f32::from(rect.origin.y) + step_y * 1.5
} else {
f32::from(rect.origin.y) - step_y * 0.5
};
if next_y < 0.0 {
return 0;
}
if next_y > f32::from(laid.size().height) {
return len;
}
laid.hit_test(point(rect.origin.x, px(next_y))).utf16_offset as usize
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
if let Some(off) = target_off
&& let Some(ed) = self.edgeless.authoring.label_editor_mut()
{
ed.preedit_anchors = None;
ed.input.move_caret(off, extend);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
}
}
}
@@ -1102,19 +1279,31 @@ mod tests {
view.edgeless_commit_inline_edit(window, cx);
assert!(view.editor.selection.is_none());
// 3. Create 2D Brush stroke -> inflated xywh & 2-element points.
// 3. Create 2D Brush stroke -> stays in Brush tool with empty selection, 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);
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Brush);
assert!(view.edgeless.authoring.selection.is_empty());
let brush_id = view
.edgeless
.authoring
.selection
.iter()
.next()
.snapshot
.as_ref()
.unwrap()
.clone();
.root
.as_ref()
.unwrap()
.children
.iter()
.find_map(|c| match &c.content {
BlockContent::Surface { elements, .. } => elements
.iter()
.rev()
.find(|e| matches!(e.kind, SurfaceElementKind::Brush(_)))
.map(|e| e.id.clone()),
_ => None,
})
.expect("newly created brush element");
let (_, brush_el) =
find_surface_element(view.snapshot.as_ref().unwrap(), &brush_id).unwrap();
let SurfaceElementKind::Brush(b) = &brush_el.kind else {
@@ -1389,6 +1578,9 @@ mod tests {
start_world: (120.0, 120.0),
current_world: (160.0, 145.0),
initial,
shift: false,
alt_clone: false,
pending_dblclick: None,
});
view.on_edgeless_left_up(&mouse_up(160.0, top + 145.0), window, cx);
let (_, sh_el) =
@@ -1427,6 +1619,8 @@ mod tests {
current_world: (ibox.right() + ibox.w, ibox.bottom() + ibox.h),
initial_box: ibox,
initial,
shift: false,
rotate_deg: 0.0,
});
view.on_edgeless_left_up(&mouse_up(0.0, 0.0), window, cx);
let (br_sid, br_el) =
@@ -2194,6 +2388,7 @@ mod tests {
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.on_edgeless_left_down(&mouse_down(420.0, top + 180.0, 2), window, cx);
view.on_edgeless_left_up(&mouse_up(420.0, top + 180.0), window, cx);
assert!(view.edgeless.authoring.label_editor().is_some());
})
.unwrap();
@@ -2272,6 +2467,7 @@ mod tests {
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.on_edgeless_left_down(&mouse_down(540.0, top + 240.0, 2), window, cx);
view.on_edgeless_left_up(&mouse_up(540.0, top + 240.0), window, cx);
assert!(matches!(
view.edgeless.authoring.label_editor().map(|e| &e.target),
Some(blocksuite_editor::edgeless::LabelTarget::SurfaceText { .. })
@@ -2373,6 +2569,7 @@ mod tests {
target_id,
target_port,
target_world,
..
} => {
assert_eq!(target_id.as_deref(), Some("rot-rect"));
assert_eq!(*target_port, Some([1.0, 0.5]));
@@ -2454,4 +2651,358 @@ mod tests {
.unwrap();
});
}
#[test]
fn b6_edgeless_p0_p1_p2_desktop_interactions() {
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();
let top = crate::TOPBAR_HEIGHT;
let mk_key = |key: &str, mods: ui::Modifiers| ui::KeyDownEvent {
keystroke: ui::Keystroke {
modifiers: mods,
key: key.into(),
key_char: None,
},
is_held: false,
prefer_character_input: false,
};
let mut cmd_mods = ui::Modifiers::default();
if cfg!(target_os = "macos") {
cmd_mods.platform = true;
} else {
cmd_mods.control = true;
}
let mut cmd_shift = cmd_mods;
cmd_shift.shift = true;
let mut alt_mods = ui::Modifiers::default();
alt_mods.alt = true;
let mut shift_mods = ui::Modifiers::default();
shift_mods.shift = true;
// Seed deterministic camera at 100% zoom, pan (0, 0).
app.update(|cx| {
win.update(cx, |view, _, cx| {
view.set_edgeless_zoom(1.0, cx);
view.set_edgeless_pan(0.0, 0.0, cx);
})
.unwrap();
});
hw.request_frame();
// 1. P0-6: Mod+A + Delete preserves the sole Page-visible `affine:note`.
let note_id: String = app.update(|cx| {
win.update(cx, |view, window, cx| {
let first_note = view
.snapshot
.as_ref()
.unwrap()
.root
.as_ref()
.unwrap()
.children
.iter()
.find(|c| matches!(c.content, BlockContent::Note { .. }))
.unwrap()
.id
.clone();
assert!(view.edgeless_key_down(&mk_key("a", cmd_mods), window, cx));
assert!(view.edgeless_key_down(
&mk_key("delete", ui::Modifiers::default()),
window,
cx
));
assert!(
find_block(view.snapshot.as_ref().unwrap(), &first_note).is_some(),
"P0-6: last Page-visible affine:note must survive Mod+A + Delete"
);
// Undo to restore showcase items.
assert!(view.edgeless_key_down(&mk_key("z", cmd_mods), window, cx));
first_note
})
.unwrap()
});
assert!(!note_id.is_empty());
hw.request_frame();
// 2. P1-23: Tool & hotkey alignment (Shift+P, S/Shift+S cycle, C cycle, Alt+F/Cmd+[ guard, Brush no-select).
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.edgeless_select_tool(EdgelessTool::Select, window, cx);
// Alt+F must NOT switch to Frame tool.
assert!(!view.edgeless_key_down(&mk_key("f", alt_mods), window, cx));
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Select);
// Shift+P switches to Highlighter; plain P switches to Brush.
assert!(view.edgeless_key_down(&mk_key("p", shift_mods), window, cx));
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Highlighter);
assert!(view.edgeless_key_down(&mk_key("p", ui::Modifiers::default()), window, cx));
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Brush);
// Drawing a brush stroke keeps Brush tool and empty selection.
view.on_edgeless_left_down(&mouse_down(100.0, top + 100.0, 1), window, cx);
view.on_edgeless_pointer_move(&mouse_move(180.0, top + 120.0, true), window, cx);
view.on_edgeless_left_up(&mouse_up(180.0, top + 120.0), window, cx);
assert_eq!(view.edgeless.authoring.tool, EdgelessTool::Brush);
assert!(view.edgeless.authoring.selection.is_empty());
// S enters Shape(Rect), subsequent S cycles Ellipse -> Diamond, Shift+S goes back.
assert!(view.edgeless_key_down(&mk_key("s", ui::Modifiers::default()), window, cx));
assert_eq!(
view.edgeless.authoring.tool,
EdgelessTool::Shape(ShapePreset::Rect)
);
assert!(view.edgeless_key_down(&mk_key("s", ui::Modifiers::default()), window, cx));
assert_eq!(
view.edgeless.authoring.tool,
EdgelessTool::Shape(ShapePreset::Ellipse)
);
assert!(view.edgeless_key_down(&mk_key("s", shift_mods), window, cx));
assert_eq!(
view.edgeless.authoring.tool,
EdgelessTool::Shape(ShapePreset::Rect)
);
// C enters Connector (Curve), subsequent C cycles Orthogonal -> Straight -> Curve.
assert!(view.edgeless_key_down(&mk_key("c", ui::Modifiers::default()), window, cx));
assert_eq!(view.edgeless.authoring.connector_mode, ConnectorMode::Curve);
assert!(view.edgeless_key_down(&mk_key("c", ui::Modifiers::default()), window, cx));
assert_eq!(
view.edgeless.authoring.connector_mode,
ConnectorMode::Orthogonal
);
assert!(view.edgeless_key_down(&mk_key("c", ui::Modifiers::default()), window, cx));
assert_eq!(
view.edgeless.authoring.connector_mode,
ConnectorMode::Straight
);
})
.unwrap();
});
hw.request_frame();
// 3. P1-24: Mod+=/-, Alt+0/1/2 zoom shortcuts & Shift+Wheel horizontal pan.
app.update(|cx| {
win.update(cx, |view, window, cx| {
let z0 = view.edgeless.camera.zoom;
assert!(view.edgeless_key_down(&mk_key("=", cmd_mods), window, cx));
assert!(view.edgeless.camera.zoom > z0);
assert!(view.edgeless_key_down(&mk_key("-", cmd_mods), window, cx));
assert!((view.edgeless.camera.zoom - z0).abs() < 1e-3);
assert!(view.edgeless_key_down(&mk_key("0", alt_mods), window, cx));
assert!((view.edgeless.camera.zoom - 1.0).abs() < 1e-3);
let px_before = view.edgeless.camera.pan_x;
let py_before = view.edgeless.camera.pan_y;
let scroll = ui::ScrollEvent {
position: ui::point(ui::px(300.0), ui::px(top + 200.0)),
delta: ui::ScrollDelta::Pixels(ui::point(ui::px(0.0), ui::px(120.0))),
modifiers: shift_mods,
touch_phase: ui::TouchPhase::Moved,
source: ui::ScrollSource::Pointer,
};
view.on_edgeless_scroll(&scroll, window, cx);
assert!((view.edgeless.camera.pan_x - px_before).abs() > 50.0);
assert!((view.edgeless.camera.pan_y - py_before).abs() < 1e-3);
view.set_edgeless_pan(0.0, 0.0, cx);
})
.unwrap();
});
hw.request_frame();
// 4. Create two shapes, wrap in Frame with F (P1-23d), verify P0-5 marquee inside Frame,
// verify P1-14 click_count=2 + drag does NOT hijack into inline edit,
// verify P1-17/P1-18 multiline AUTO_HEIGHT + in-place Undo/Redo,
// verify P1-25 Mod+G / Mod+Shift+G, Mod+C / Mod+V, Ctrl+Y, and P2-3 empty EdgelessText cleanup.
let (s1_id, s2_id) = app.update(|cx| {
win.update(cx, |view, window, cx| {
view.edgeless_select_tool(EdgelessTool::Shape(ShapePreset::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(260.0, top + 180.0, true), window, cx);
view.on_edgeless_left_up(&mouse_up(260.0, top + 180.0), window, cx);
let s1 = view
.edgeless
.authoring
.selection
.iter()
.next()
.unwrap()
.clone();
view.edgeless_select_tool(EdgelessTool::Shape(ShapePreset::Rect), window, cx);
view.on_edgeless_left_down(&mouse_down(340.0, top + 100.0, 1), window, cx);
view.on_edgeless_pointer_move(&mouse_move(500.0, top + 180.0, true), window, cx);
view.on_edgeless_left_up(&mouse_up(500.0, top + 180.0), window, cx);
let s2 = view
.edgeless
.authoring
.selection
.iter()
.next()
.unwrap()
.clone();
(s1, s2)
})
.unwrap()
});
hw.request_frame();
// P1-14: click_count=2 followed by drag moves s1 and does NOT open inline edit.
platform.advance_clock(std::time::Duration::from_millis(600));
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.on_edgeless_left_down(&mouse_down(180.0, top + 140.0, 2), window, cx);
view.on_edgeless_pointer_move(&mouse_move(180.0, top + 200.0, true), window, cx);
view.on_edgeless_left_up(&mouse_up(180.0, top + 200.0), window, cx);
assert!(
view.edgeless.authoring.inline_edit.is_none(),
"P1-14: double-click mousedown followed by drag must NOT enter inline edit"
);
// Undo the move so s1 returns to (100, 100).
view.edgeless_key_down(&mk_key("z", cmd_mods), window, cx);
})
.unwrap();
});
hw.request_frame();
// P1-17 & P1-18: Double-click without drag enters Shape inline edit, 5 lines grow height (AUTO_HEIGHT),
// and Cmd+Z / Ctrl+Y undo/redo in place.
platform.advance_clock(std::time::Duration::from_millis(600));
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.on_edgeless_left_down(&mouse_down(180.0, top + 140.0, 2), window, cx);
view.on_edgeless_left_up(&mouse_up(180.0, top + 140.0), window, cx);
assert!(view.edgeless.authoring.label_editor().is_some());
view.replace_text_in_range(None, "Line1\nLine2\nLine3\nLine4\nLine5", window, cx);
let grown_h = view.edgeless.authoring.label_editor().unwrap().world_rect.h;
assert!(
grown_h > 80.0,
"P1-18: Shape must auto-grow beyond 80px for 5 lines, got {grown_h}"
);
// Home/End & Up/Down work in label editor.
assert!(view.edgeless_key_down(
&mk_key("home", ui::Modifiers::default()),
window,
cx
));
assert!(view.edgeless_key_down(
&mk_key("up", ui::Modifiers::default()),
window,
cx
));
assert!(view.edgeless_key_down(
&mk_key("down", ui::Modifiers::default()),
window,
cx
));
assert!(view.edgeless_key_down(
&mk_key("end", ui::Modifiers::default()),
window,
cx
));
// In-place Undo + Ctrl+Y Redo.
assert!(view.edgeless_key_down(&mk_key("z", cmd_mods), window, cx));
assert!(view.edgeless_key_down(&mk_key("y", cmd_mods), window, cx));
view.edgeless_commit_inline_edit(window, cx);
})
.unwrap();
});
hw.request_frame();
// P1-23(d) & P0-5: Select s1 + s2, press F to wrap in Frame; marquee around s1 alone must NOT select Frame!
let frame_id = app.update(|cx| {
win.update(cx, |view, window, cx| {
view.edgeless_set_selection([s1_id.clone(), s2_id.clone()], cx);
assert!(view.edgeless_key_down(&mk_key("f", ui::Modifiers::default()), window, cx));
let fid = view
.edgeless
.authoring
.selection
.iter()
.next()
.unwrap()
.clone();
let kids = collect_frame_children(
find_block(view.snapshot.as_ref().unwrap(), &fid).unwrap(),
);
assert!(kids.contains(&s1_id) && kids.contains(&s2_id));
fid
})
.unwrap()
});
hw.request_frame();
app.update(|cx| {
win.update(cx, |view, window, cx| {
// Marquee strictly inside Frame around s1 only.
let s1_rect = view
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == s1_id)
.expect("s1 painted")
.rect;
view.edgeless.authoring.selection.clear();
view.edgeless.authoring.gesture = Some(EdgelessGesture::Marquee {
start_world: (s1_rect.x - 5.0, s1_rect.y - 5.0),
current_world: (s1_rect.x - 5.0, s1_rect.y - 5.0),
});
let end_screen = view.edgeless.camera.world_to_screen(
ui::point(
ui::px(s1_rect.right() + 5.0),
ui::px(s1_rect.bottom() + 5.0),
),
ui::point(ui::px(0.0), ui::px(top)),
);
view.on_edgeless_pointer_move(
&mouse_move(f32::from(end_screen.x), f32::from(end_screen.y), true),
window,
cx,
);
view.on_edgeless_left_up(
&mouse_up(f32::from(end_screen.x), f32::from(end_screen.y)),
window,
cx,
);
assert!(view.edgeless.authoring.selection.contains(&s1_id));
assert!(
!view.edgeless.authoring.selection.contains(&frame_id),
"P0-5: marquee inside Frame must NOT select the outer Frame"
);
// P1-25(d): Group s1 + s2 with Mod+G, then Ungroup with Mod+Shift+G.
view.edgeless_set_selection([s1_id.clone(), s2_id.clone()], cx);
assert!(view.edgeless_key_down(&mk_key("g", cmd_mods), window, cx));
let gid = view
.edgeless
.authoring
.selection
.iter()
.next()
.unwrap()
.clone();
assert_ne!(gid, s1_id);
assert!(view.edgeless_key_down(&mk_key("g", cmd_shift), window, cx));
assert!(view.edgeless.authoring.selection.contains(&s1_id));
assert!(view.edgeless.authoring.selection.contains(&s2_id));
// P1-25(c): Mod+C + Mod+V round-trip copies s1.
view.edgeless_set_selection([s1_id.clone()], cx);
let count_before = view.edgeless.authoring.painted_items.len();
assert!(view.edgeless_key_down(&mk_key("c", cmd_mods), window, cx));
assert!(view.edgeless_key_down(&mk_key("v", cmd_mods), window, cx));
assert!(view.snapshot.is_some());
let _ = count_before;
// P2-3: T creates empty EdgelessText; switching to Page cleans up the ghost block.
view.create_edgeless_text_at(620.0, 420.0, window, cx);
let (et_id, _) = view.edgeless.authoring.editing_spatial_block().unwrap();
let et_id = et_id.to_string();
view.set_mode(crate::PlaygroundMode::Page, window, cx);
assert!(
find_block(view.snapshot.as_ref().unwrap(), &et_id).is_none(),
"P2-3: switching to Page must clean up empty newly created EdgelessText"
);
})
.unwrap();
});
}
}
@@ -16,8 +16,8 @@ use crate::{
use super::{
EdgelessGesture, EdgelessInlineEdit, EdgelessTool, HandleKind, NOTE_MIN_WIDTH, SpatialItemKind,
WorldRect, compute_frame_membership_updates, max_spatial_index, normalized_rect,
resized_rect_with_min, rotated_bounds,
WorldRect, compute_frame_membership_updates, constrain_shift_drag, constrain_shift_square,
max_spatial_index, normalized_rect, resized_rect_constrained, rotated_bounds,
};
impl PlaygroundView {
@@ -48,24 +48,44 @@ impl PlaygroundView {
}
cx.notify();
}
EdgelessGesture::Marquee { .. } => {
EdgelessGesture::Marquee { .. } | EdgelessGesture::SelectLabelText { .. } => {
cx.notify();
}
EdgelessGesture::DragSelection {
start_world,
current_world,
initial,
shift,
alt_clone,
pending_dblclick,
} => {
let dx = (current_world.0 - start_world.0) as f64;
let dy = (current_world.1 - start_world.1) as f64;
let (dx_f32, dy_f32) = if shift {
constrain_shift_drag(start_world, current_world)
} else {
(
current_world.0 - start_world.0,
current_world.1 - start_world.1,
)
};
let dx = dx_f32 as f64;
let dy = dy_f32 as f64;
if dx.hypot(dy) < 0.5 {
cx.notify();
if let Some((item_id, world_pos)) = pending_dblclick {
self.edgeless_begin_inline_edit_at(&item_id, Some(world_pos), window, cx);
} else {
cx.notify();
}
return;
}
if alt_clone {
self.edgeless_clone_items_by_delta(&initial, dx, dy, cx);
return;
}
let constrained_world = (start_world.0 + dx_f32, start_world.1 + dy_f32);
let frame_updates = compute_frame_membership_updates(
&self.edgeless.authoring.painted_items,
&initial,
current_world,
constrained_world,
);
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
@@ -153,19 +173,24 @@ impl PlaygroundView {
current_world,
initial_box,
initial,
shift,
rotate_deg,
} => {
let min_w = if initial.len() == 1 && initial[0].kind == SpatialItemKind::Note {
NOTE_MIN_WIDTH
} else {
24.0
};
let new_box = resized_rect_with_min(
let lock_ratio = shift || initial.len() > 1;
let new_box = resized_rect_constrained(
initial_box,
handle,
start_world,
current_world,
min_w,
24.0,
lock_ratio,
rotate_deg,
);
if (new_box.x - initial_box.x).abs() < 0.5
&& (new_box.y - initial_box.y).abs() < 0.5
@@ -186,18 +211,31 @@ impl PlaygroundView {
| HandleKind::SE
| HandleKind::SW
);
let single_rotated = initial.len() == 1 && rotate_deg.abs() > 1e-3;
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 item_min_w = if item.kind == SpatialItemKind::Note {
NOTE_MIN_WIDTH as f64
let (nx, ny, nw, nh) = if single_rotated {
(
new_box.x as f64,
new_box.y as f64,
new_box.w as f64,
new_box.h as f64,
)
} else {
16.0
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 item_min_w = if item.kind == SpatialItemKind::Note {
NOTE_MIN_WIDTH as f64
} else {
16.0
};
let nw = (item.rect.w as f64 * sx).max(item_min_w);
let nh = (item.rect.h as f64 * sy).max(16.0);
(nx, ny, nw, nh)
};
let nw = (item.rect.w as f64 * sx).max(item_min_w);
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)?;
if item.kind == SpatialItemKind::EdgelessText && horizontal_resize {
@@ -330,10 +368,19 @@ impl PlaygroundView {
shape_type,
start_world,
current_world,
shift,
} => {
let mut r = normalized_rect(start_world, current_world);
let mut r = if shift {
constrain_shift_square(start_world, current_world)
} else {
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 if shift {
let side = r.w.max(r.h).max(40.0);
r.w = side;
r.h = side;
} else {
r.w = r.w.max(40.0);
r.h = r.h.max(32.0);
@@ -522,6 +569,7 @@ impl PlaygroundView {
}
}
EdgelessGesture::CreateConnector {
mode,
source_id,
source_port,
source_world,
@@ -530,64 +578,38 @@ impl PlaygroundView {
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: 2, // Curve
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;
}
}
self.commit_create_connector(
mode,
source_id,
source_port,
source_world,
current_world,
target_id,
target_port,
target_world,
now_ms,
cx,
);
}
EdgelessGesture::DragConnectorEndpoint {
id,
surface_id,
is_start,
current_world,
snap_id,
snap_port,
..
} => {
self.commit_connector_endpoint_drag(
id,
surface_id,
is_start,
current_world,
snap_id,
snap_port,
now_ms,
cx,
);
}
EdgelessGesture::DrawStroke {
highlighter,
@@ -660,8 +682,9 @@ impl PlaygroundView {
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
// Align with Web `brush-tool.ts`: stay in Brush/Highlighter mode with
// empty selection so the user can keep drawing continuously.
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(stroke_id);
}
}
}
@@ -712,7 +735,6 @@ impl PlaygroundView {
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(text_id.clone());
self.edgeless.authoring.tool = EdgelessTool::Select;
self.suppress_unselected_root_input = false;
self.edgeless.authoring.inline_edit = Some(EdgelessInlineEdit::SpatialBlock {
block_id: text_id,
is_note: false,
@@ -0,0 +1,296 @@
//! Connector creation, endpoint handle dragging/rebinding, and label geometry helpers.
use blocksuite_playground_doc::{
fractional_index::generate_key_between,
read::{ConnectorMode, SurfaceConnector, SurfaceElementKind, TextAlign},
schema::{ConnectorEndpointSpec, SurfaceElementSpec},
};
use ui::{Context, FontWeight, Window, px};
use y_octo::{SessionValue, TextDeltaOp, TextInsert};
use crate::{
PlaygroundView,
rich_text::{RichParagraph, RichParagraphStyle},
theme::ThemeMode,
};
use super::{
EdgelessGesture, EdgelessTool, HandleKind, SpatialItemKind, find_surface_element,
max_spatial_index,
};
/// Sample the routed connector polyline at `distance` (`0.0..=1.0`), matching
/// `surface::paint`'s `route.point_at_distance(mode, distance)`.
pub(super) 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)
}
pub(super) 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 {
/// Commit a newly dragged connector with the active `ConnectorMode`.
#[allow(clippy::too_many_arguments)]
pub(super) fn commit_create_connector(
&mut self,
mode: ConnectorMode,
source_id: Option<String>,
source_port: Option<[f64; 2]>,
source_world: (f32, f32),
current_world: (f32, f32),
target_id: Option<String>,
target_port: Option<[f64; 2]>,
target_world: Option<(f32, f32)>,
now_ms: u64,
cx: &mut Context<Self>,
) {
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));
let mode_num = match mode {
ConnectorMode::Straight => 0,
ConnectorMode::Orthogonal => 1,
ConnectorMode::Curve => 2,
};
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: mode_num,
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;
}
}
}
/// Start dragging a selected connector's start or end endpoint handle.
pub(super) fn begin_connector_endpoint_drag(
&mut self,
handle: HandleKind,
wx: f32,
wy: f32,
cx: &mut Context<Self>,
) -> bool {
let is_start = match handle {
HandleKind::ConnectorStart => true,
HandleKind::ConnectorEnd => false,
_ => return false,
};
let Some(single) = self.edgeless.authoring.single_selected().cloned() else {
return false;
};
if single.kind != SpatialItemKind::Connector || single.polyline.len() < 2 {
return false;
}
let Some(surface_id) = single.surface_id.clone() else {
return false;
};
let Some(snapshot) = self.snapshot.as_deref() else {
return false;
};
let Some((_, el)) = find_surface_element(snapshot, &single.id) else {
return false;
};
let SurfaceElementKind::Connector(c) = &el.kind else {
return false;
};
let (fixed_ep, fixed_world) = if is_start {
(&c.target, *single.polyline.last().unwrap())
} else {
(&c.source, single.polyline[0])
};
self.edgeless.authoring.gesture = Some(EdgelessGesture::DragConnectorEndpoint {
id: single.id,
surface_id,
is_start,
mode: c.mode,
fixed_id: fixed_ep.id.clone(),
fixed_port: fixed_ep.position,
fixed_world,
current_world: (wx, wy),
snap_id: None,
snap_port: None,
snap_world: None,
});
cx.notify();
true
}
/// Commit a finished connector endpoint drag (rebind to snapped element or free world point).
#[allow(clippy::too_many_arguments)]
pub(super) fn commit_connector_endpoint_drag(
&mut self,
id: String,
surface_id: String,
is_start: bool,
current_world: (f32, f32),
snap_id: Option<String>,
snap_port: Option<[f64; 2]>,
now_ms: u64,
cx: &mut Context<Self>,
) {
let field = if is_start { "source" } else { "target" };
let endpoint = match (snap_id, snap_port) {
(Some(target_id), port) => ConnectorEndpointSpec::element(target_id, port),
_ => ConnectorEndpointSpec::point(current_world.0 as f64, current_world.1 as f64),
};
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
page.set_surface_element_field(
&surface_id,
&id,
field,
SessionValue::Any(endpoint.to_any()),
now_ms,
)?;
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
} else {
cx.notify();
}
}
}
@@ -0,0 +1,254 @@
//! Edgeless canvas clipboard copy/cut (`Mod+C` / `Mod+X`) and `Alt+Drag` cloning.
use std::collections::{BTreeSet, HashMap};
use blocksuite_playground_doc::{
fractional_index::generate_key_between,
read::{BlockNode, PageSnapshot, SurfaceElement},
session::PastedBlockNode,
};
use serde_json::{Map, Value, json};
use ui::{ClipboardItem, Context};
use y_octo::SessionValue;
use crate::PlaygroundView;
use super::{
DragItemInitial, SpatialItemKind, find_block, find_surface_element, max_spatial_index, paste,
paste_convert,
};
impl PlaygroundView {
/// Copy (or cut) selected Edgeless elements and blocks into the clipboard using the
/// BlockSuite surface snapshot envelope consumed by `paste_edgeless_clipboard_item`.
pub(crate) fn edgeless_copy_selection(&mut self, cut: bool, cx: &mut Context<Self>) -> bool {
if self.edgeless.authoring.selection.is_empty() {
return false;
}
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let ids = self.expand_selection_with_containers(&self.edgeless.authoring.selection);
let (surface_vals, block_vals) = serialize_edgeless_ids(&snapshot, &ids);
if surface_vals.is_empty() && block_vals.is_empty() {
return false;
}
let mut envelope = Map::new();
if !surface_vals.is_empty() {
envelope.insert("blocksuite/surface".to_string(), Value::Array(surface_vals));
}
if !block_vals.is_empty() {
envelope.insert("blocks".to_string(), Value::Array(block_vals));
}
let Ok(payload_str) = serde_json::to_string(&Value::Object(envelope)) else {
return false;
};
cx.write_to_clipboard(ClipboardItem::new_string(payload_str));
if cut {
self.edgeless_delete_selection(cx);
}
true
}
/// Clone dragged items offset by `(dx, dy)` (`Alt/Option+Drag`) in one atomic undo step
/// with remapped IDs, leaving originals untouched and selecting the new clones.
pub(super) fn edgeless_clone_items_by_delta(
&mut self,
initial: &[DragItemInitial],
dx: f64,
dy: f64,
cx: &mut Context<Self>,
) -> bool {
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let Some(page_id) = self.page_id.clone() else {
return false;
};
let base_ids: BTreeSet<String> = initial.iter().map(|i| i.id.clone()).collect();
let ids = self.expand_selection_with_containers(&base_ids);
let (surface_vals, block_vals) = serialize_edgeless_ids(&snapshot, &ids);
let surface_elems: Vec<Map<String, Value>> = surface_vals
.into_iter()
.filter_map(|v| match v {
Value::Object(m) => Some(m),
_ => None,
})
.collect();
let note_blocks: Vec<Map<String, Value>> = block_vals
.into_iter()
.filter_map(|v| match v {
Value::Object(m) => Some(m),
_ => None,
})
.collect();
if surface_elems.is_empty() && note_blocks.is_empty() {
return false;
}
let now_ms = self.now_ms(cx) as u64;
let mut prev_index = max_spatial_index(&snapshot);
let mut id_map: HashMap<String, String> = HashMap::new();
let mut assigned_elem_ids: Vec<String> = Vec::with_capacity(surface_elems.len());
for elem in &surface_elems {
let new_id = self.fresh_block_id();
if let Some(old_id) = elem.get("id").and_then(Value::as_str)
&& !old_id.is_empty()
{
id_map.insert(old_id.to_string(), new_id.clone());
}
assigned_elem_ids.push(new_id);
}
let mut preallocated_notes = Vec::with_capacity(note_blocks.len());
for note in &note_blocks {
preallocated_notes.push(paste::preallocate_block_tree(
note,
&mut id_map,
&mut || self.fresh_block_id(),
));
}
let prepared_notes: Vec<PastedBlockNode> = preallocated_notes
.iter()
.map(|n| paste::materialize_pasted_block_tree_with_offset(n, true, dx, dy, &id_map))
.collect();
let mut remapped_elems: Vec<(String, Vec<(String, SessionValue)>)> =
Vec::with_capacity(surface_elems.len());
for (i, (elem, new_id)) in surface_elems.iter().zip(&assigned_elem_ids).enumerate() {
let next_idx = generate_key_between(prev_index.as_deref(), None)
.unwrap_or_else(|_| format!("z{i}"));
prev_index = Some(next_idx.clone());
let entries = paste_convert::remap_surface_element_with_offset(
elem, new_id, &next_idx, dx, dy, &id_map,
);
remapped_elems.push((new_id.clone(), entries));
}
let new_surface_id = (!remapped_elems.is_empty()).then(|| self.fresh_block_id());
let Some(page) = self.state.workspace.page_mut(&page_id) else {
return false;
};
let Ok(commit) =
page.paste_edgeless_batch(remapped_elems, new_surface_id, prepared_notes, now_ms)
else {
return false;
};
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
let mut next_sel = BTreeSet::new();
for old_id in &self.edgeless.authoring.selection {
if let Some(new_id) = id_map.get(old_id) {
next_sel.insert(new_id.clone());
}
}
if !next_sel.is_empty() {
self.edgeless.authoring.selection = next_sel;
}
return true;
}
false
}
/// Expand a set of item IDs to include descendant members of selected Groups and Frames.
pub(super) fn expand_selection_with_containers(
&self,
selected: &BTreeSet<String>,
) -> BTreeSet<String> {
let mut ids = selected.clone();
let mut changed = true;
while changed {
changed = false;
for item in self.edgeless.authoring.painted_items.iter() {
if !ids.contains(&item.id) {
continue;
}
if item.kind == SpatialItemKind::Frame {
for cid in &item.frame_children {
if ids.insert(cid.clone()) {
changed = true;
}
}
}
if item.kind == SpatialItemKind::Group {
for cid in &item.group_children {
if ids.insert(cid.clone()) {
changed = true;
}
}
}
}
}
ids
}
}
fn serialize_edgeless_ids(
snapshot: &PageSnapshot,
ids: &BTreeSet<String>,
) -> (Vec<Value>, Vec<Value>) {
let mut surface_vals = Vec::new();
let mut block_vals = Vec::new();
for id in ids {
if let Some((_, el)) = find_surface_element(snapshot, id) {
surface_vals.push(surface_element_to_json(el));
} else if let Some(node) = find_block(snapshot, id)
&& node.flavour == "affine:note"
{
block_vals.push(block_node_to_json(node));
}
}
(surface_vals, block_vals)
}
fn surface_element_to_json(el: &SurfaceElement) -> Value {
let mut map: Map<String, Value> = el
.props
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
map.insert("id".to_string(), Value::String(el.id.clone()));
map.insert("index".to_string(), Value::String(el.index.clone()));
// Preserve rich-text delta on shapes/connectors/text when present.
match &el.kind {
blocksuite_playground_doc::read::SurfaceElementKind::Shape(s)
if !s.text.plain.is_empty() =>
{
map.insert(
"text".to_string(),
json!({ "delta": [{ "insert": s.text.plain }] }),
);
}
blocksuite_playground_doc::read::SurfaceElementKind::Connector(c)
if !c.text.plain.is_empty() =>
{
map.insert(
"text".to_string(),
json!({ "delta": [{ "insert": c.text.plain }] }),
);
}
blocksuite_playground_doc::read::SurfaceElementKind::Text(t) => {
map.insert(
"text".to_string(),
json!({ "delta": [{ "insert": t.text.plain }] }),
);
}
_ => {}
}
Value::Object(map)
}
fn block_node_to_json(node: &BlockNode) -> Value {
let mut props = Map::new();
for (k, v) in &node.props {
let stripped = k.strip_prefix("prop:").unwrap_or(k);
props.insert(stripped.to_string(), v.clone());
}
let children: Vec<Value> = node.children.iter().map(block_node_to_json).collect();
json!({
"id": node.id,
"flavour": node.flavour,
"version": node.version,
"props": props,
"children": children,
})
}
@@ -82,10 +82,14 @@ impl PlaygroundView {
sel.anchor =
crate::editor_session::DocPoint::new(&pt.block_id, range.start);
sel.focus = crate::editor_session::DocPoint::new(&pt.block_id, range.end);
self.editor.dragging = false;
} else if event.modifiers.shift
&& let Some(old) = &self.editor.selection
{
sel.anchor = old.anchor.clone();
self.editor.dragging = true;
} else {
self.editor.dragging = true;
}
self.change_selection(sel, window, cx);
return;
@@ -119,7 +123,26 @@ impl PlaygroundView {
)
.map_or(0, |(off, _)| off);
if let Some(ed_mut) = self.edgeless.authoring.label_editor_mut() {
ed_mut.select(off..off);
if event.click_count >= 3 {
ed_mut.select_all();
} else if event.click_count == 2 {
let r = crate::editor_session::word_range(&ed_mut.input.text, off as u64);
ed_mut.select(r.start as usize..r.end as usize);
} else if event.modifiers.shift {
ed_mut.input.move_caret(off, true);
ed_mut.preedit_anchors = None;
self.edgeless.authoring.gesture = Some(EdgelessGesture::SelectLabelText {
anchor_utf16: if ed_mut.input.reversed {
ed_mut.input.selection.end
} else {
ed_mut.input.selection.start
},
});
} else {
ed_mut.select(off..off);
self.edgeless.authoring.gesture =
Some(EdgelessGesture::SelectLabelText { anchor_utf16: off });
}
}
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
@@ -134,19 +157,6 @@ impl PlaygroundView {
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_at(&hit.id, Some((wx, wy)), 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);
@@ -158,6 +168,11 @@ impl PlaygroundView {
self.edgeless.camera,
) {
match handle {
HandleKind::ConnectorStart | HandleKind::ConnectorEnd => {
if self.begin_connector_endpoint_drag(handle, wx, wy, cx) {
return;
}
}
HandleKind::Rotate => {
if let Some(single) = self.edgeless.authoring.single_selected().cloned()
{
@@ -187,6 +202,9 @@ impl PlaygroundView {
start_world: (wx, wy),
current_world: (wx, wy),
initial,
shift: event.modifiers.shift,
alt_clone: event.modifiers.alt,
pending_dblclick: None,
});
cx.notify();
return;
@@ -196,6 +214,11 @@ impl PlaygroundView {
if let Some(initial_box) = self.edgeless.authoring.selection_world_box()
{
let initial = self.collect_drag_initials();
let rotate_deg = if initial.len() == 1 {
initial[0].rotate_deg
} else {
0.0
};
self.edgeless.authoring.gesture =
Some(EdgelessGesture::ResizeSelection {
handle,
@@ -203,6 +226,8 @@ impl PlaygroundView {
current_world: (wx, wy),
initial_box,
initial,
shift: event.modifiers.shift,
rotate_deg,
});
cx.notify();
return;
@@ -218,20 +243,41 @@ impl PlaygroundView {
.hit_test_world(wx, wy, self.edgeless.camera.zoom)
.cloned()
{
// Clicking a member of a Group selects the outermost Group first (unless
// double-clicking into it or the Group is already selected).
let select_id = if let Some(gid) = &hit.parent_group_id
&& event.click_count < 2
&& !self.edgeless.authoring.selection.contains(gid)
&& !self.edgeless.authoring.selection.contains(&hit.id)
{
gid.clone()
} else {
hit.id.clone()
};
if event.modifiers.shift {
if !self.edgeless.authoring.selection.remove(&hit.id) {
self.edgeless.authoring.selection.insert(hit.id.clone());
if !self.edgeless.authoring.selection.remove(&select_id) {
self.edgeless.authoring.selection.insert(select_id.clone());
}
} else if !self.edgeless.authoring.selection.contains(&hit.id) {
} else if !self.edgeless.authoring.selection.contains(&select_id) {
self.edgeless.authoring.selection.clear();
self.edgeless.authoring.selection.insert(hit.id.clone());
self.edgeless.authoring.selection.insert(select_id.clone());
}
let pending_dblclick =
if event.click_count >= 2 && !event.modifiers.shift && !event.modifiers.alt
{
Some((hit.id.clone(), (wx, wy)))
} else {
None
};
let initial = self.collect_drag_initials();
if !initial.is_empty() {
if !initial.is_empty() || pending_dblclick.is_some() {
self.edgeless.authoring.gesture = Some(EdgelessGesture::DragSelection {
start_world: (wx, wy),
current_world: (wx, wy),
initial,
shift: event.modifiers.shift,
alt_clone: event.modifiers.alt,
pending_dblclick,
});
}
cx.notify();
@@ -252,6 +298,7 @@ impl PlaygroundView {
shape_type,
start_world: (wx, wy),
current_world: (wx, wy),
shift: event.modifiers.shift,
});
cx.notify();
}
@@ -281,6 +328,7 @@ impl PlaygroundView {
None => (None, None, (wx, wy)),
};
self.edgeless.authoring.gesture = Some(EdgelessGesture::CreateConnector {
mode: self.edgeless.authoring.connector_mode,
source_id,
source_port,
source_world,
@@ -309,7 +357,7 @@ impl PlaygroundView {
pub(crate) fn on_edgeless_pointer_move(
&mut self,
event: &MouseMoveEvent,
_window: &mut Window,
window: &mut Window,
cx: &mut Context<Self>,
) {
// Middle-button pan continues to work as before.
@@ -322,6 +370,68 @@ impl PlaygroundView {
cx.notify();
return;
}
// Drag-selecting text inside an inline-edited Edgeless Note or EdgelessText block.
if self.editor.dragging
&& 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()
&& let Some(layout) = self.edgeless.cached_block_layout(&editing_id, is_note)
{
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
let world_pt = self
.edgeless
.camera
.screen_to_world(event.position, vp_origin);
let (cx_w, cy_w) = info.rect.center();
let (lx, ly) = rotate_point_around(
f32::from(world_pt.x),
f32::from(world_pt.y),
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(pt) = Self::hit_test_flow_layout(&layout, flow_x, flow_y)
&& let Some(old) = self.editor.selection.clone()
{
let next = DocumentSelection {
anchor: old.anchor,
focus: pt,
};
self.change_selection(next, window, cx);
}
}
return;
}
// Drag-selecting text inside an active EdgelessLabelEditor (Shape / Connector / Frame / SurfaceText).
if let Some(EdgelessGesture::SelectLabelText { anchor_utf16 }) =
self.edgeless.authoring.gesture
{
if let Some((off, _)) = self.hit_label_editor_at(
f32::from(event.position.x),
f32::from(event.position.y),
window,
) && let Some(ed_mut) = self.edgeless.authoring.label_editor_mut()
{
ed_mut.select_directional(anchor_utf16, off);
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
cx.notify();
}
return;
}
let vp_origin = point(px(0.0), px(TOPBAR_HEIGHT));
let world_pt = self
.edgeless
@@ -337,6 +447,10 @@ impl PlaygroundView {
.edgeless
.authoring
.snap_connector_port(wx, wy, zoom, source_id.as_deref()),
Some(EdgelessGesture::DragConnectorEndpoint { fixed_id, .. }) => self
.edgeless
.authoring
.snap_connector_port(wx, wy, zoom, fixed_id.as_deref()),
_ => None,
};
@@ -369,16 +483,42 @@ impl PlaygroundView {
.authoring
.painted_items
.iter()
.filter(|item| item.rect.intersects(marquee))
.filter(|item| {
if item.kind == SpatialItemKind::Frame {
// Align with Web `frame-block.ts:72-80`: a Frame is only marquee-selected
// when the marquee rectangle fully contains it.
marquee.contains_rect(item.rect)
} else if item.kind == SpatialItemKind::Group {
false
} else {
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::DragSelection {
current_world,
shift: g_shift,
..
})
| Some(EdgelessGesture::ResizeSelection {
current_world,
shift: g_shift,
..
})
| Some(EdgelessGesture::CreateShape {
current_world,
shift: g_shift,
..
}) => {
*current_world = (wx, wy);
*g_shift = shift;
cx.notify();
}
Some(EdgelessGesture::CreateFrame { current_world, .. })
| Some(EdgelessGesture::CreateNote { current_world, .. }) => {
*current_world = (wx, wy);
cx.notify();
@@ -419,6 +559,25 @@ impl PlaygroundView {
}
cx.notify();
}
Some(EdgelessGesture::DragConnectorEndpoint {
current_world,
snap_id,
snap_port,
snap_world,
..
}) => {
*current_world = (wx, wy);
if let Some((tid, port, pt)) = conn_snap {
*snap_id = Some(tid);
*snap_port = Some(port);
*snap_world = Some(pt);
} else {
*snap_id = None;
*snap_port = None;
*snap_world = None;
}
cx.notify();
}
Some(EdgelessGesture::DrawStroke { points_world, .. }) => {
let should_push = points_world
.last()
@@ -428,7 +587,7 @@ impl PlaygroundView {
cx.notify();
}
}
None => {}
Some(EdgelessGesture::SelectLabelText { .. }) | None => {}
}
}
@@ -436,15 +595,7 @@ impl PlaygroundView {
let Some(snapshot) = &self.snapshot else {
return Vec::new();
};
let mut ids: BTreeSet<String> = 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 ids = self.expand_selection_with_containers(&self.edgeless.authoring.selection);
let mut out = Vec::new();
for item in self.edgeless.authoring.painted_items.iter() {
if !ids.contains(&item.id) {
@@ -483,6 +634,7 @@ impl PlaygroundView {
kind: item.kind,
surface_id: item.surface_id.clone(),
rect: item.rect,
rotate_deg: item.rotate_deg,
points,
connector_source,
connector_target,
@@ -602,44 +754,3 @@ impl PlaygroundView {
Some((flow_x, flow_y))
}
}
/// Sample the routed connector polyline at `distance` (`0.0..=1.0`), matching
/// `surface::paint`'s `route.point_at_distance(mode, distance)`.
pub(super) fn connector_label_anchor_point(
polyline: &[(f32, f32)],
fallback_center: (f32, f32),
mode: blocksuite_playground_doc::read::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 == blocksuite_playground_doc::read::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)
}
@@ -0,0 +1,356 @@
//! Group/ungroup (`Mod+G` / `Mod+Shift+G`), wrap-selection-in-Frame (`F`), delete, and z-order ops.
use std::collections::BTreeSet;
use blocksuite_playground_doc::{
fractional_index::generate_key_between,
read::{BlockContent, NoteDisplayMode},
schema::SurfaceElementSpec,
};
use ui::Context;
use y_octo::{Any, SessionValue};
use crate::PlaygroundView;
use super::{
EdgelessTool, SpatialItemInfo, SpatialItemKind, commands::min_spatial_index, max_spatial_index,
};
impl PlaygroundView {
/// Wrap the current non-empty Edgeless selection inside a new Frame and populate `prop:childElementIds`.
pub(crate) fn edgeless_wrap_selection_in_frame(&mut self, cx: &mut Context<Self>) -> bool {
if self.edgeless.authoring.selection.is_empty() {
return false;
}
let Some(sel_box) = self.edgeless.authoring.selection_world_box() else {
return false;
};
let pad = 40.0_f32;
let frame_xywh = [
(sel_box.x - pad) as f64,
(sel_box.y - pad) as f64,
(sel_box.w + pad * 2.0).max(120.0) as f64,
(sel_box.h + pad * 2.0).max(80.0) as f64,
];
let children: Vec<String> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|item| {
self.edgeless.authoring.selection.contains(&item.id)
&& item.kind != SpatialItemKind::Frame
})
.map(|item| item.id.clone())
.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 Some(cid) = self.page().map(|p| p.client_id()) else {
return false;
};
let frame_id = self.edgeless.authoring.next_id("frame", cid);
let now_ms = self.now_ms(cx) as u64;
let frame_id_clone = frame_id.clone();
let commit = self.page_mut().ok().and_then(|page| {
let child_refs: Vec<&str> = children.iter().map(String::as_str).collect();
page.add_frame_with_children(
None,
&frame_id_clone,
"Frame",
&next_idx,
frame_xywh,
&child_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;
return true;
}
false
}
/// Group selected items (`Mod+G`) into a new `Group` surface element in one atomic undo step.
pub(crate) fn edgeless_group_selection(&mut self, cx: &mut Context<Self>) -> bool {
let members: Vec<String> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|item| {
self.edgeless.authoring.selection.contains(&item.id)
&& item.kind != SpatialItemKind::Frame
})
.map(|item| item.id.clone())
.collect();
if members.len() < 2 {
return false;
}
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 Some(cid) = self.page().map(|p| p.client_id()) else {
return false;
};
let group_id = self.edgeless.authoring.next_id("group", cid);
let seed = (self.edgeless.authoring.next_id_seq as i32 + 71) * 53;
let now_ms = self.now_ms(cx) as u64;
let group_id_clone = group_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,
group_id_clone.clone(),
&next_idx,
SurfaceElementSpec::Group {
seed,
title: "Group".into(),
children: members.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(group_id);
return true;
}
false
}
/// Ungroup any selected `Group` elements (`Mod+Shift+G`), restoring their children to selection.
pub(crate) fn edgeless_ungroup_selection(&mut self, cx: &mut Context<Self>) -> bool {
let Some(snapshot) = self.snapshot.as_deref() else {
return false;
};
let mut groups: Vec<(String, String)> = Vec::new();
let mut next_selection: BTreeSet<String> = self.edgeless.authoring.selection.clone();
for id in &self.edgeless.authoring.selection {
if let Some((surface_id, el)) = super::find_surface_element(snapshot, id)
&& let blocksuite_playground_doc::read::SurfaceElementKind::Group {
children, ..
} = &el.kind
{
groups.push((surface_id.to_string(), id.clone()));
next_selection.remove(id);
for cid in children {
next_selection.insert(cid.clone());
}
}
}
if groups.is_empty() {
return false;
}
let now_ms = self.now_ms(cx) as u64;
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
for (surface_id, group_id) in &groups {
page.remove_surface_element(surface_id, group_id, now_ms)?;
}
Ok(())
})
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
self.edgeless.authoring.selection = next_selection;
return true;
}
false
}
pub(crate) fn edgeless_delete_selection(&mut self, cx: &mut Context<Self>) {
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());
// Protect the last Page-visible (`DocOnly` or `Both`) `affine:note` under root so
// Edgeless deletion can never lock Page mode out of body editing (Web `crud.ts:27-33`).
let page_visible_notes: Vec<String> = snapshot
.root
.as_ref()
.map(|r| {
r.children
.iter()
.filter(|c| {
matches!(
c.content,
BlockContent::Note {
display_mode: NoteDisplayMode::DocOnly | NoteDisplayMode::Both,
..
}
)
})
.map(|c| c.id.clone())
.collect()
})
.unwrap_or_default();
let expanded_ids =
self.expand_selection_with_containers(&self.edgeless.authoring.selection);
let selected: Vec<SpatialItemInfo> = self
.edgeless
.authoring
.painted_items
.iter()
.filter(|i| expanded_ids.contains(&i.id))
.cloned()
.collect();
let mut protected_note_id: Option<String> = None;
if !page_visible_notes.is_empty()
&& page_visible_notes
.iter()
.all(|nid| expanded_ids.contains(nid))
{
protected_note_id = Some(page_visible_notes[0].clone());
}
let mut block_ids: Vec<String> = 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 protected_note_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 protected_detach: Vec<String> = if let Some(ref pnid) = protected_note_id {
selected
.iter()
.filter(|item| {
item.kind == SpatialItemKind::Frame
&& item.frame_children.iter().any(|c| c == pnid)
})
.map(|item| item.id.clone())
.collect()
} else {
Vec::new()
};
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();
if !protected_detach.is_empty()
&& let Some(ref pnid) = protected_note_id
{
let detach_list = vec![pnid.clone()];
for fid in &protected_detach {
let _ = page.update_frame_child_element_ids(fid, &[], &detach_list, now_ms);
}
}
if b_refs.is_empty() && s_refs.is_empty() {
return None;
}
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<Self>,
) {
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<SpatialItemInfo> = 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<SpatialItemInfo> = 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);
}
}
}
@@ -1,97 +1,27 @@
//! Double-click inline rich-text & IME editing for Edgeless shapes, connectors, text, frames, and notes.
use blocksuite_playground_doc::read::{
BlockContent, SurfaceConnector, SurfaceElementKind, TextAlign,
use blocksuite_playground_doc::{
read::{BlockContent, SurfaceElementKind},
session::PageDocSession,
};
use ui::{Bounds, Context, FontWeight, Pixels, Window, point, px, size};
use y_octo::{TextDeltaOp, TextInsert};
use ui::{Bounds, Context, Pixels, Window, point, px, size};
use y_octo::{Any, SessionValue};
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,
gestures::connector_label_anchor_point, rotate_point_around,
SpatialItemKind, WorldRect,
connector_edit::{connector_label_anchor_point, measure_connector_label_xywh},
find_block, find_surface_element, layout_label_editor_paragraph, rotate_point_around,
};
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 = super::gestures::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.
/// Apply a live UTF-16 splice on the active inline label editor directly into `PageDocSession`,
/// auto-grow Shape height when multiline text overflows (`AUTO_HEIGHT`), and update CRDT anchors.
pub(crate) fn edgeless_label_edit(
&mut self,
window: &mut Window,
@@ -112,6 +42,7 @@ impl PlaygroundView {
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
self.edgeless_sync_shape_auto_height(window, cx);
}
self.edgeless_update_label_anchors();
window.notify_text_input_changed(&self.editor_focus);
@@ -119,6 +50,60 @@ impl PlaygroundView {
Some(())
}
/// Grow (or shrink back down to `min_world_height`) an actively edited Shape's `xywh` height
/// to fit its wrapped multiline label, matching Web `edgeless-shape-text-editor.ts` `AUTO_HEIGHT`.
pub(crate) fn edgeless_sync_shape_auto_height(
&mut self,
window: &Window,
cx: &mut Context<Self>,
) {
let Some((surface_id, id, new_rect)) =
self.edgeless.authoring.label_editor().and_then(|ed| {
let LabelTarget::Shape { surface_id, id } = &ed.target else {
return None;
};
let laid =
layout_label_editor_paragraph(ed, ed.world_rect.w, 1.0, self.theme, window)?;
let pad_y = ed.shape_style.as_ref().map_or(10.0, |st| st.padding[0]);
let needed_h = (f32::from(laid.size().height) + 2.0 * pad_y)
.ceil()
.max(ed.min_world_height);
if (needed_h - ed.world_rect.h).abs() < 1.0 {
return None;
}
let mut r = ed.world_rect;
r.h = needed_h;
Some((surface_id.clone(), id.clone(), r))
})
else {
return;
};
if let Some(ed) = self.edgeless.authoring.label_editor_mut() {
ed.world_rect = new_rect;
}
let now_ms = self.now_ms(cx) as u64;
let xywh = PageDocSession::format_xywh([
new_rect.x as f64,
new_rect.y as f64,
new_rect.w as f64,
new_rect.h as f64,
]);
let commit = self.page_mut().ok().and_then(|page| {
page.set_surface_element_field(
&surface_id,
&id,
"xywh",
SessionValue::Any(Any::String(xywh)),
now_ms,
)
.ok()
.flatten()
});
if let Some(commit) = commit {
self.did_edgeless_doc_commit(commit, cx);
}
}
pub(crate) fn edgeless_update_label_anchors(&mut self) {
let Some(target) = self
.edgeless
@@ -526,7 +511,6 @@ impl PlaygroundView {
),
_ => return false,
};
self.suppress_unselected_root_input = false;
self.edgeless.authoring.selection.clear();
self.edgeless
.authoring
@@ -562,7 +546,6 @@ impl PlaygroundView {
let rect = info.title_pill_rect.unwrap_or_else(|| {
WorldRect::new(info.rect.x, info.rect.y - 28.0, 140.0, 24.0)
});
self.suppress_unselected_root_input = false;
self.edgeless.authoring.selection.clear();
self.edgeless
.authoring
@@ -2,7 +2,10 @@
mod commands;
mod commit;
mod connector_edit;
mod copy_cut;
mod gestures;
mod group_ops;
mod inline_edit;
mod paste;
mod paste_convert;
@@ -11,8 +11,8 @@ use ui::{Context, Window};
use y_octo::{Any, SessionValue, TextDeltaOp, TextInsert};
use super::paste_convert::{
block_json_to_session_value, offset_xywh_str, remap_database_cells, remap_group_children,
remap_surface_element,
PASTE_OFFSET, block_json_to_session_value, offset_xywh_by, remap_database_cells,
remap_group_children, remap_surface_element,
};
use crate::PlaygroundView;
@@ -378,13 +378,13 @@ fn push_surface_elements_collection(val: &Value, out: &mut Vec<Map<String, Value
}
}
struct PreallocatedBlock<'a> {
pub(super) struct PreallocatedBlock<'a> {
new_id: String,
obj: &'a Map<String, Value>,
children: Vec<PreallocatedBlock<'a>>,
}
fn preallocate_block_tree<'a>(
pub(super) fn preallocate_block_tree<'a>(
obj: &'a Map<String, Value>,
id_map: &mut HashMap<String, String>,
alloc_id: &mut impl FnMut() -> String,
@@ -414,6 +414,16 @@ fn materialize_pasted_block_tree(
node: &PreallocatedBlock<'_>,
is_top_note: bool,
id_map: &HashMap<String, String>,
) -> PastedBlockNode {
materialize_pasted_block_tree_with_offset(node, is_top_note, PASTE_OFFSET, PASTE_OFFSET, id_map)
}
pub(super) fn materialize_pasted_block_tree_with_offset(
node: &PreallocatedBlock<'_>,
is_top_note: bool,
dx: f64,
dy: f64,
id_map: &HashMap<String, String>,
) -> PastedBlockNode {
let obj = node.obj;
let new_id = node.new_id.clone();
@@ -457,7 +467,7 @@ fn materialize_pasted_block_tree(
if is_top_note && prop_key == "prop:xywh" {
let shifted = pv
.as_str()
.map(offset_xywh_str)
.map(|s| offset_xywh_by(s, dx, dy))
.unwrap_or_else(|| "[0,0,448,120]".to_string());
entries.push((prop_key, SessionValue::Any(Any::String(shifted))));
} else if matches!(prop_key.as_str(), "prop:text" | "prop:title") && pv.is_string() {
@@ -9,11 +9,11 @@ use y_octo::{Any, SessionValue, TextDeltaOp, TextInsert};
pub(super) const PASTE_OFFSET: f64 = 24.0;
pub(super) fn offset_xywh_str(raw: &str) -> String {
pub(super) fn offset_xywh_by(raw: &str, dx: f64, dy: f64) -> String {
match super::parse_xywh(raw) {
Some(r) => PageDocSession::format_xywh([
f64::from(r.x) + PASTE_OFFSET,
f64::from(r.y) + PASTE_OFFSET,
f64::from(r.x) + dx,
f64::from(r.y) + dy,
f64::from(r.w),
f64::from(r.h),
]),
@@ -44,6 +44,17 @@ pub(super) fn remap_surface_element(
new_id: &str,
new_index: &str,
id_map: &HashMap<String, String>,
) -> Vec<(String, SessionValue)> {
remap_surface_element_with_offset(elem, new_id, new_index, PASTE_OFFSET, PASTE_OFFSET, id_map)
}
pub(super) fn remap_surface_element_with_offset(
elem: &Map<String, Value>,
new_id: &str,
new_index: &str,
dx: f64,
dy: f64,
id_map: &HashMap<String, String>,
) -> Vec<(String, SessionValue)> {
let elem_type = elem.get("type").and_then(Value::as_str).unwrap_or("");
let mut entries = Vec::new();
@@ -58,7 +69,10 @@ pub(super) fn remap_surface_element(
SessionValue::Any(Any::String(new_index.to_string())),
)),
"xywh" => {
let shifted = v.as_str().map(offset_xywh_str).unwrap_or_default();
let shifted = v
.as_str()
.map(|s| offset_xywh_by(s, dx, dy))
.unwrap_or_default();
entries.push(("xywh".to_string(), SessionValue::Any(Any::String(shifted))));
}
"children" if elem_type == "mindmap" => {
@@ -68,7 +82,7 @@ pub(super) fn remap_surface_element(
entries.push(("children".to_string(), remap_group_children(v, id_map)));
}
"source" | "target" if elem_type == "connector" => {
entries.push((k.clone(), remap_connector_endpoint(v, id_map)));
entries.push((k.clone(), remap_connector_endpoint(v, dx, dy, id_map)));
}
"childElementIds" if elem_type == "frame" => {
entries.push((
@@ -160,11 +174,17 @@ pub(super) fn remap_group_children(val: &Value, id_map: &HashMap<String, String>
pub(super) fn remap_connector_endpoint(
val: &Value,
dx: f64,
dy: f64,
id_map: &HashMap<String, String>,
) -> SessionValue {
let Some(obj) = val.as_object() else {
return surface_json_to_session_value(val);
};
let has_id = obj
.get("id")
.and_then(Value::as_str)
.is_some_and(|s| !s.is_empty());
let mut out = HashMap::new();
for (k, v) in obj {
if k == "id"
@@ -174,6 +194,21 @@ pub(super) fn remap_connector_endpoint(
out.insert(k.clone(), Any::String(new_id.clone()));
continue;
}
if k == "position"
&& !has_id
&& let Some(arr) = v.as_array()
&& arr.len() == 2
&& let (Some(x), Some(y)) = (arr[0].as_f64(), arr[1].as_f64())
{
out.insert(
k.clone(),
Any::Array(vec![
Any::Float64((x + dx).into()),
Any::Float64((y + dy).into()),
]),
);
continue;
}
out.insert(k.clone(), json_to_any(v));
}
SessionValue::Any(Any::Object(Box::new(out.into_iter().collect())))
@@ -188,6 +188,8 @@ impl PlaygroundView {
Ok(())
})?;
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
self.editor.block_selection_focus = None;
self.editor.selection = if remaining_editable.is_none() && first_parent_id.is_some() {
Some(DocumentSelection::caret(DocPoint::new(fallback_id, 0)))
} else if keep_kb {
@@ -222,6 +224,10 @@ impl PlaygroundView {
let m = e.keystroke.modifiers;
let cmd = m.secondary(cx);
let key = e.keystroke.key.as_str();
if cmd && let Some(command) = conversion_shortcut(key, m.alt, m.shift) {
self.convert_selected_blocks(command, w, cx)?;
return Ok(true);
}
match key {
"up" | "down"
if (cmd && m.alt && !m.shift)
@@ -230,8 +236,21 @@ impl PlaygroundView {
self.move_block_by_shortcut(key == "up", w, cx)?;
Ok(true)
}
"up" | "down" if !cmd && !m.alt => {
self.navigate_block_selection(key == "up", m.shift, w, cx);
Ok(true)
}
"tab" if !cmd && !m.alt => {
let ids = self.editor.block_selection.clone();
self.indent_or_outdent_blocks(&ids, m.shift, None, w, cx)?;
Ok(true)
}
"escape" => {
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
self.editor.block_selection_focus = None;
self.announce_selection(cx);
w.notify_text_selection_changed(&self.editor_focus);
cx.notify();
Ok(true)
}
@@ -240,11 +259,27 @@ impl PlaygroundView {
Ok(true)
}
"enter" => {
if self.editor.block_selection.len() == 1
&& let Some(single_id) = self.editor.block_selection.first().cloned()
&& let Some(snapshot) = self.snapshot.as_ref()
&& let Some(node) = snapshot.block(&single_id)
&& !matches!(node.content, BlockContent::Page { .. })
&& let Some(text) = text_content(node)
{
let len = text.encode_utf16().count() as u64;
self.change_selection(
DocumentSelection::caret(DocPoint::new(single_id, len)),
w,
cx,
);
return Ok(true);
}
let last_id = self.editor.block_selection.last().cloned();
if let Some(last_id) = last_id
&& let Some(snapshot) = self.snapshot.clone()
&& let Some((parent, slot)) = parent_of(&snapshot, &last_id)
{
let insert_slot = page_ops::slot_after_collapsed_heading(parent, slot);
let new_id = self.fresh_block_id();
let now = self.now_ms(cx) as u64;
let page = self.page_mut()?;
@@ -253,10 +288,12 @@ impl PlaygroundView {
&new_id,
paragraph(),
Some(&parent.id),
Some(slot as u64 + 1),
Some(insert_slot as u64),
now,
)?;
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
self.editor.block_selection_focus = None;
self.editor.selection =
Some(DocumentSelection::caret(DocPoint::new(new_id, 0)));
self.editor.last_typing = None;
@@ -274,24 +311,20 @@ impl PlaygroundView {
Ok(true)
}
"a" if cmd => {
if let Some(layout) = self.flow_layout() {
self.editor.block_selection = layout
.blocks
.iter()
.filter(|b| !matches!(b.body.kind, block_flow::FlowKind::Title))
.map(|b| b.block_id.clone())
.collect();
cx.notify();
}
self.select_all_blocks(w, cx);
Ok(true)
}
"z" if cmd => {
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
self.editor.block_selection_focus = None;
self.history(m.shift, w, cx)?;
Ok(true)
}
"y" if cmd => {
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
self.editor.block_selection_focus = None;
self.history(true, w, cx)?;
Ok(true)
}
@@ -299,6 +332,112 @@ impl PlaygroundView {
}
}
fn navigate_block_selection(
&mut self,
up: bool,
shift: bool,
w: &mut Window,
cx: &mut Context<Self>,
) {
let layout = if self.mode == crate::PlaygroundMode::Page {
let width = page_geometry(f32::from(w.viewport_size().width)).column_width;
self.ensure_layout(width, w)
} else {
self.flow_layout()
};
let Some(layout) = layout else {
return;
};
let body: Vec<&crate::block_flow::FlowBlock> = layout
.blocks
.iter()
.filter(|b| !matches!(b.body.kind, block_flow::FlowKind::Title))
.collect();
if body.is_empty() {
return;
}
if shift {
let anchor_id = self
.editor
.block_selection_anchor
.clone()
.or_else(|| {
if up {
self.editor.block_selection.first().cloned()
} else {
self.editor.block_selection.last().cloned()
}
})
.unwrap_or_else(|| body[0].block_id.clone());
let focus_id = self
.editor
.block_selection_focus
.clone()
.unwrap_or_else(|| anchor_id.clone());
let Some(anchor_idx) = body.iter().position(|b| b.block_id == anchor_id) else {
return;
};
let focus_idx = body
.iter()
.position(|b| b.block_id == focus_id)
.unwrap_or(anchor_idx);
let next_idx = if up {
focus_idx.saturating_sub(1)
} else {
(focus_idx + 1).min(body.len() - 1)
};
let lo = anchor_idx.min(next_idx);
let hi = anchor_idx.max(next_idx);
self.editor.block_selection =
body[lo..=hi].iter().map(|b| b.block_id.clone()).collect();
self.editor.block_selection_anchor = Some(anchor_id);
self.editor.block_selection_focus = Some(body[next_idx].block_id.clone());
self.announce_selection(cx);
w.notify_text_selection_changed(&self.editor_focus);
cx.notify();
return;
}
let edge_id = if up {
self.editor.block_selection.first()
} else {
self.editor.block_selection.last()
};
let Some(cur_idx) = edge_id.and_then(|id| body.iter().position(|b| b.block_id == *id))
else {
return;
};
let target_idx = if up {
let Some(prev) = cur_idx.checked_sub(1) else {
return;
};
prev
} else if cur_idx + 1 < body.len() {
cur_idx + 1
} else {
return;
};
let target = body[target_idx];
if target.editable() {
let offset = if up {
target.body.plain.encode_utf16().count() as u64
} else {
0
};
self.change_selection(
DocumentSelection::caret(DocPoint::new(&target.block_id, offset)),
w,
cx,
);
} else {
self.editor.block_selection = vec![target.block_id.clone()];
self.editor.block_selection_anchor = Some(target.block_id.clone());
self.editor.block_selection_focus = Some(target.block_id.clone());
self.announce_selection(cx);
w.notify_text_selection_changed(&self.editor_focus);
cx.notify();
}
}
pub(crate) fn run_selection_copy(
&mut self,
target: Option<crate::overlays::ContextTargetSnapshot>,
@@ -401,21 +540,16 @@ impl PlaygroundView {
}
pub(crate) fn select_all_blocks(&mut self, w: &mut Window, cx: &mut Context<Self>) {
if let Some(layout) = self.flow_layout() {
let ids: Vec<String> = layout
.blocks
.iter()
.filter(|b| !matches!(b.body.kind, block_flow::FlowKind::Title))
.map(|b| b.block_id.clone())
.collect();
if !ids.is_empty() {
self.editor.selection = None;
self.editor.block_selection = ids;
self.editor.pending_marks.clear();
self.announce_selection(cx);
w.notify_text_selection_changed(&self.editor_focus);
cx.notify();
}
let ids = self.all_scope_block_ids();
if !ids.is_empty() {
self.editor.selection = None;
self.editor.block_selection_anchor = ids.first().cloned();
self.editor.block_selection_focus = ids.last().cloned();
self.editor.block_selection = ids;
self.editor.pending_marks.clear();
self.announce_selection(cx);
w.notify_text_selection_changed(&self.editor_focus);
cx.notify();
}
}
@@ -461,7 +461,6 @@ impl PlaygroundView {
}
if is_block_paste {
self.editor.block_selection.clear();
self.suppress_unselected_root_input = false;
}
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(last_id, last_pos)));
self.editor.last_typing = None;
@@ -345,6 +345,26 @@ impl PlaygroundView {
if key == "tab" && code && sel.anchor.block_id == sel.focus.block_id {
return self.indent_code_block(sel, shift, w, cx);
}
if key == "tab" {
let block_ids = if sel.anchor.block_id != sel.focus.block_id {
self.flow_layout()
.and_then(|layout| {
let (_, _, a, b, _) = sel.ordered(&layout)?;
Some(
layout.blocks[a..=b]
.iter()
.filter(|blk| !matches!(blk.body.kind, block_flow::FlowKind::Title))
.map(|blk| blk.block_id.clone())
.collect::<Vec<_>>(),
)
})
.unwrap_or_default()
} else {
vec![id.clone()]
};
self.indent_or_outdent_blocks(&block_ids, shift, Some(sel), w, cx)?;
return Ok(());
}
if key == "enter" && !shift && self.apply_markdown(&sel, "\n", w, cx)? {
return Ok(());
}
@@ -416,40 +436,24 @@ impl PlaygroundView {
if node.flavour != "affine:paragraph" {
focus = DocPoint::new(&fresh, offset);
}
self.page_mut()?
.convert_block_flavour(&id, &fresh, paragraph(), now)?
} else if key == "tab" {
let Some((parent, pos)) = parent_of(&snapshot, &id) else {
return Ok(());
};
let dest = if shift {
if !matches!(
parent.content,
BlockContent::List { .. } | BlockContent::Paragraph { .. }
) {
return Ok(());
let reset_following = (key == "enter"
&& matches!(
node.content,
BlockContent::List {
kind: blocksuite_playground_doc::schema::ListType::Numbered,
..
}
))
.then(|| parent_of(&snapshot, &id).map(|(p, slot)| (p.id.clone(), slot + 1)))
.flatten();
let page = self.page_mut()?;
page.structural_edit(now, |page| {
page.convert_block_flavour(&id, &fresh, paragraph(), now)?;
if let Some((ref parent_id, next_slot)) = reset_following {
page.correct_numbered_order_from(parent_id, next_slot, 1)?;
}
parent_of(&snapshot, &parent.id).map(|(p, i)| (&p.id, i + 1))
} else {
pos.checked_sub(1)
.and_then(|i| parent.children.get(i))
.filter(|b| {
matches!(
b.content,
BlockContent::List { .. } | BlockContent::Paragraph { .. }
)
})
.map(|b| (&b.id, b.children.len()))
};
let Some((dest, index)) = dest else {
return Ok(());
};
if shift {
self.page_mut()?.dedent_block(&id, now)?
} else {
self.page_mut()?
.reparent_block(&id, &parent.id, dest, index as u64, now)?
}
Ok(())
})?
} else if key == "enter" {
if matches!(node.content, BlockContent::Page { .. }) {
let split_byte = TextBiIndex::new(text).utf16_to_utf8_clamped(offset);
@@ -458,8 +462,11 @@ impl PlaygroundView {
}
}
let spec = match &node.content {
BlockContent::Paragraph { kind, .. }
if offset < n || *kind == ParagraphType::Quote =>
BlockContent::Paragraph {
kind, collapsed, ..
} if offset < n
|| *kind == ParagraphType::Quote
|| (*collapsed && page_ops::heading_level_of(*kind).is_some()) =>
{
BlockSpec::Paragraph {
paragraph_type: *kind,
@@ -691,7 +698,9 @@ impl PlaygroundView {
{
let block_id = sel.focus.block_id.clone();
self.editor.selection = None;
self.editor.block_selection = vec![block_id];
self.editor.block_selection = vec![block_id.clone()];
self.editor.block_selection_anchor = Some(block_id.clone());
self.editor.block_selection_focus = Some(block_id);
self.editor.pending_marks.clear();
self.announce_selection(cx);
w.notify_text_selection_changed(&self.editor_focus);
@@ -713,11 +722,16 @@ impl PlaygroundView {
self.navigate(key, m.shift, word, line_edge, doc_edge, w, cx);
Ok(())
}
"pageup" | "pagedown" => {
self.navigate_page(key == "pageup", m.shift, w, cx);
Ok(())
}
"backspace" | "delete" => match self.delete_with_modifiers(key, m, w, cx) {
Ok(true) => Ok(()),
Ok(false) => self.edit_key(key, m.shift, w, cx),
Err(err) => Err(err),
},
"enter" if cmd && !m.alt => self.handle_mod_enter(w, cx),
"enter" | "tab" => self.edit_key(key, m.shift, w, cx),
"a" if cmd => {
self.run_selection_select_all(None, w, cx);
@@ -273,6 +273,7 @@ impl PlaygroundView {
} else if rect.bottom() + margin > self.scroll_y + height {
self.scroll_y = (rect.bottom() + margin - height).round();
}
self.reveal_table_cell_horizontal();
}
}
pub(super) fn world_spans(block: &FlowBlock, r: Range<u64>) -> Vec<FlowRect> {
@@ -521,14 +522,6 @@ impl PlaygroundView {
el.extend(self.table_cell_selection_elements(layout, v, palette, caret_alpha));
el
}
pub(crate) fn begin_input(&mut self) {
if self.editor.selection.is_none()
&& self.editor.block_selection.is_empty()
&& let Some(root) = self.page_snapshot().and_then(|s| s.root.as_ref())
{
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(&root.id, 0)));
}
}
pub(super) fn replacement_selection(
&self,
range: Option<Range<usize>>,
@@ -570,6 +563,9 @@ impl PlaygroundView {
let layout = self
.flow_layout()
.ok_or_else(|| DocError::InvalidState("missing layout".into()))?;
if self.try_wrap_selection(&sel, text, &layout, w, cx)? {
return Ok(());
}
if sel.ordered(&layout).is_none()
&& sel.anchor.block_id == sel.focus.block_id
&& let Some(row_plain) = self
@@ -198,6 +198,8 @@ impl PlaygroundView {
}
self.editor.selection = None;
self.editor.block_selection = vec![adjacent.block_id.clone()];
self.editor.block_selection_anchor = Some(adjacent.block_id.clone());
self.editor.block_selection_focus = Some(adjacent.block_id.clone());
self.keep_keyboard_on_block_selection = had_selection;
self.block_selection_return_caret = return_caret;
self.editor.pending_marks.clear();
@@ -44,9 +44,6 @@ impl EntityInputHandler for PlaygroundView {
let _ = self.paste_into_block_selection(&item, w, cx);
return;
}
if self.suppress_unselected_root_input && self.editor.selection.is_none() {
return;
}
self.paste_body_clipboard_item(&item, w, cx);
}
fn text_for_range(
@@ -244,10 +241,6 @@ impl EntityInputHandler for PlaygroundView {
self.keep_keyboard_on_block_selection = false;
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(ret_id, 0)));
}
if self.suppress_unselected_root_input && self.editor.selection.is_none() {
return;
}
self.begin_input();
let selection = self.replacement_selection(r);
if self.editor.preedit.is_some() {
self.clear_composition(w, cx);
@@ -306,10 +299,6 @@ impl EntityInputHandler for PlaygroundView {
self.keep_keyboard_on_block_selection = false;
self.editor.selection = Some(DocumentSelection::caret(DocPoint::new(ret_id, 0)));
}
if self.suppress_unselected_root_input && self.editor.selection.is_none() {
return;
}
self.begin_input();
if text.is_empty() {
self.clear_composition(w, cx);
return;
@@ -7,6 +7,7 @@ mod composition;
mod edit_ops;
mod input_handler;
mod markdown;
mod page_ops;
mod paste_markdown;
pub use blocksuite_editor::editor_session::*;
@@ -87,29 +88,48 @@ impl PlaygroundView {
self.editor_focus.focus(w, cx);
w.request_virtual_keyboard();
self.editor.dragging = true;
self.editor.drag_moved = false;
let mut sel = DocumentSelection::caret(p.clone());
if e.click_count >= 2 {
let s = self.block_text(&p.block_id).unwrap_or("");
let range = if e.click_count == 2 {
word_range(s, p.offset())
} else {
0..s.encode_utf16().count() as u64
let (range, drag_mode) = {
let s = self.block_text(&p.block_id).unwrap_or("");
if e.click_count == 2 {
let r = word_range(s, p.offset());
let mode = DragSelectionMode::Word {
block_id: p.block_id.clone(),
start: r.start,
end: r.end,
};
(r, mode)
} else {
let len = s.encode_utf16().count() as u64;
(
0..len,
DragSelectionMode::Paragraph {
block_id: p.block_id.clone(),
},
)
}
};
self.editor.drag_mode = drag_mode;
sel.anchor = DocPoint::new(&p.block_id, range.start);
sel.focus = DocPoint::new(&p.block_id, range.end);
} else if e.modifiers.shift
&& let Some(old) = &self.editor.selection
{
let same_domain = self.flow_layout().is_none_or(|layout| {
let is_title = |id: &str| {
layout
.block(id)
.is_some_and(|b| matches!(b.body.kind, block_flow::FlowKind::Title))
};
is_title(&old.anchor.block_id) == is_title(&p.block_id)
});
if same_domain {
sel.anchor = old.anchor.clone();
} else {
self.editor.drag_mode = DragSelectionMode::Character;
if e.modifiers.shift
&& let Some(old) = &self.editor.selection
{
let same_domain = self.flow_layout().is_none_or(|layout| {
let is_title = |id: &str| {
layout
.block(id)
.is_some_and(|b| matches!(b.body.kind, block_flow::FlowKind::Title))
};
is_title(&old.anchor.block_id) == is_title(&p.block_id)
});
if same_domain {
sel.anchor = old.anchor.clone();
}
}
}
self.change_selection(sel, w, cx);
@@ -125,13 +145,17 @@ impl PlaygroundView {
) {
if e.pressed_button != Some(MouseButton::Left) {
self.editor.dragging = false;
self.editor.drag_moved = false;
self.editor.drag_mode = DragSelectionMode::Character;
return;
}
if self.editor.dragging
&& let Some(mut focus) = self.input_point(e.position, w)
&& let Some(sel) = &self.editor.selection
{
if let Some(layout) = self.flow_layout() {
self.editor.drag_moved = true;
let layout = self.flow_layout();
if let Some(layout) = layout.as_ref() {
let anchor_title = layout
.block(&sel.anchor.block_id)
.is_some_and(|b| matches!(b.body.kind, block_flow::FlowKind::Title));
@@ -153,14 +177,8 @@ impl PlaygroundView {
}
}
}
self.change_selection(
DocumentSelection {
anchor: sel.anchor.clone(),
focus,
},
w,
cx,
);
let next_sel = self.extend_drag_selection(sel, focus, layout.as_deref());
self.change_selection(next_sel, w, cx);
}
}
@@ -207,9 +225,10 @@ impl PlaygroundView {
cx: &mut Context<Self>,
) {
self.commit_active_preedit(w, cx);
self.suppress_unselected_root_input = false;
self.editor.selection = Some(sel);
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
self.editor.block_selection_focus = None;
self.keep_keyboard_on_block_selection = false;
self.block_selection_return_caret = None;
self.editor.pending_marks.clear();
@@ -221,6 +240,7 @@ impl PlaygroundView {
}
self.announce_selection(cx);
self.sync_slash_trigger(cx);
self.sync_linked_doc_trigger(cx);
self.reset_caret_blink(cx);
w.notify_text_selection_changed(&self.editor_focus);
cx.notify();
@@ -232,6 +252,8 @@ impl PlaygroundView {
self.commit_active_preedit(w, cx);
self.editor.selection = None;
self.editor.block_selection.clear();
self.editor.block_selection_anchor = None;
self.editor.block_selection_focus = None;
self.keep_keyboard_on_block_selection = false;
self.block_selection_return_caret = None;
self.editor.pending_marks.clear();
@@ -241,6 +263,7 @@ impl PlaygroundView {
self.editor.slash_trigger = None;
self.announce_selection(cx);
self.sync_slash_trigger(cx);
self.sync_linked_doc_trigger(cx);
self.reset_caret_blink(cx);
w.notify_text_input_changed(&self.editor_focus);
w.notify_text_selection_changed(&self.editor_focus);
@@ -518,6 +541,7 @@ impl PlaygroundView {
pub(super) fn resolve_remote_selection(&mut self, cx: &Context<Self>) {
self.resolve_relative_selection(cx);
self.sync_slash_trigger(cx);
self.sync_linked_doc_trigger(cx);
self.sync_equation_target();
}
File diff suppressed because it is too large. Load diff
@@ -108,7 +108,6 @@ impl PlaygroundView {
w: &mut Window,
cx: &mut Context<Self>,
) {
self.begin_input();
match self.try_paste_url_as_link(item, w, cx) {
Ok(true) => return,
Ok(false) => {}
@@ -70,7 +70,6 @@ impl PlaygroundView {
.filter(|snapshot| snapshot.root.is_some())
.map(Rc::new);
self.doc_rev += 1;
if let Some(pages) = pages
&& self.custom_doc_directory.is_none()
{
@@ -275,7 +274,6 @@ impl PlaygroundView {
self.editor.last_typing = None;
self.editor.pending_marks.clear();
self.editor.slash_trigger = None;
self.suppress_unselected_root_input = true;
self.overlays.set_keyboard_toolbar_visible(false);
pruned = true;
}
@@ -327,10 +325,7 @@ impl PlaygroundView {
// Commit any pending inline edit (table cell or Edgeless label) cleanly before switching modes.
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
if self.edgeless.authoring.editing_spatial_block().is_some() {
self.edgeless.authoring.inline_edit = None;
self.editor.clear_preedit_state();
self.editor.selection = None;
self.announce_selection(cx);
self.edgeless_commit_inline_edit(window, cx);
}
self.edgeless.authoring.reset_transient();
self.page_scroll_fling = None;
@@ -440,6 +435,16 @@ impl PlaygroundView {
}
let raw_delta = event.delta.pixel_delta(px(SCROLL_LINE));
let (mut dx, mut dy) = (f32::from(raw_delta.x), f32::from(raw_delta.y));
// On Windows/Linux, Shift+wheel delivers a vertical delta with `modifiers.shift`:
// convert it to horizontal scroll for wide tables, code blocks, and databases.
if event.source != ui::ScrollSource::Touch
&& event.modifiers.shift
&& dx.abs() < f32::EPSILON
&& dy.abs() > f32::EPSILON
{
dx = dy;
dy = 0.0;
}
// Touch scroll axis lock — once a touch drag establishes a dominant axis,
// suppress orthogonal jitter until the gesture ends, restarts, or pauses >160ms.
if event.source == ui::ScrollSource::Touch {
+27 -19
View File
@@ -220,7 +220,6 @@ pub struct PlaygroundView {
pub(crate) ime_insets: chrome::ImeInsetsState,
/// Focused in-place `affine:table` cell editor, if active.
pub(crate) table_cell: Option<overlays::InlineTableCell>,
pub(crate) suppress_unselected_root_input: bool,
/// Most recent document id opened via clicking an `embed-linked-doc` / `embed-synced-doc` card.
pub(crate) last_opened_embed_doc: Option<String>,
/// Stack of previously visited page ids for in-workspace back navigation.
@@ -384,7 +383,6 @@ impl PlaygroundView {
table_cell: None,
doc_panel_tab: None,
doc_panel_scroll_y: 0.0,
suppress_unselected_root_input: false,
last_opened_embed_doc: None,
nav_history: Vec::new(),
on_active_doc_changed: None,
@@ -580,6 +578,10 @@ impl PlaygroundView {
self.edgeless
.camera
.zoom_at(target_zoom, event.position, vp_origin);
} else if event.modifiers.shift && f32::from(delta.x).abs() < 1e-3 {
self.edgeless
.camera
.pan_by_screen_delta(f32::from(delta.y), 0.0);
} else {
self.edgeless
.camera
@@ -9462,7 +9464,7 @@ pub(crate) mod tests {
}
#[test]
fn set_document_discards_preedit_and_suppresses_late_input_only_when_composing() {
fn set_document_discards_preedit_and_never_hijacks_unselected_title() {
use blocksuite_playground_doc::schema::SurfaceElementSpec;
use ui::EntityInputHandler;
@@ -9507,16 +9509,16 @@ pub(crate) mod tests {
};
let cases = [
("paragraph_composing", true),
("link_bar_composing", true),
("equation_bar_composing", true),
("table_cell_composing", true),
("edgeless_label_composing", true),
("no_active_target", false),
("table_cell_focused_idle", false),
"paragraph_composing",
"link_bar_composing",
"equation_bar_composing",
"table_cell_composing",
"edgeless_label_composing",
"no_active_target",
"table_cell_focused_idle",
];
for (case, expect_suppressed) in cases {
for case in cases {
let session = open(1280, 800, PlaygroundOptions::default());
session.view(|v, cx| v.set_document(make_doc_a(), cx));
let _ = session.frame();
@@ -9623,15 +9625,21 @@ pub(crate) mod tests {
type_text(&session, "X");
let _ = session.frame();
let title_b = session.view(|v, _| v.page_snapshot().unwrap().title().to_string());
if expect_suppressed {
assert_eq!(
title_b, "DocB",
"case {case}: unselected input after set_document must never mutate new title"
);
if case != "edgeless_label_composing" {
let root_id = session
.view(|v, _| v.page_snapshot().unwrap().root.as_ref().unwrap().id.clone());
set_caret(&session, &root_id, 0);
type_text(&session, "X");
let _ = session.frame();
let title_after =
session.view(|v, _| v.page_snapshot().unwrap().title().to_string());
assert_eq!(
title_b, "DocB",
"case {case}: late input after composing set_document must not mutate new title"
);
} else {
assert_eq!(
title_b, "XDocB",
"case {case}: non-composing set_document must allow typing into new title"
title_after, "XDocB",
"case {case}: explicit title focus must accept typing after set_document"
);
}
}
@@ -7,7 +7,10 @@ mod view_embed_controls;
mod view_linked_doc;
mod view_mobile;
pub use view_mobile::DatabaseRecordSheetState;
#[cfg(test)]
mod tests_b6;
mod view_scrollbar;
mod view_slash_blocks;
mod view_table_cell;
pub use blocksuite_editor::overlays::*;
@@ -659,8 +662,9 @@ mod tests {
_ => None,
})
.collect();
assert_eq!(headers, ["Basic", "List"]);
// BlockSuite's order: text, the headings, code, quote, divider, new doc, linked doc, then the lists.
assert_eq!(headers, ["Basic", "List", "Content & Media"]);
// BlockSuite's order: text, the headings, code, quote, divider, new doc, linked doc,
// lists, then content & database items.
assert_eq!(
ids(""),
[
@@ -679,11 +683,14 @@ mod tests {
"bulleted",
"numbered",
"todo",
"toggle"
"toggle",
"table",
"equation",
"database"
]
);
assert_eq!(rows.first().map(|(_, y, _)| *y), Some(0.0));
assert!(matches!(rows.last(), Some((SlashRow::Item(15), _, _))));
assert!(matches!(rows.last(), Some((SlashRow::Item(18), _, _))));
let (_, last_y, last_height) = rows[rows.len() - 1];
assert_eq!(last_y + last_height, height);
for pair in rows.windows(2) {
@@ -691,10 +698,10 @@ mod tests {
assert!(matches!(pair[1].0, SlashRow::Item(_)));
}
}
// Without results the list keeps one row.
// Without results the list is empty so the popover stays hidden.
let (rows, height) = slash_rows(&[]);
assert_eq!(rows, [(SlashRow::Empty, 0.0, SLASH_ITEM_HEIGHT)]);
assert_eq!(height, SLASH_ITEM_HEIGHT);
assert!(rows.is_empty());
assert_eq!(height, 0.0);
// Filtered queries hide group headers while keeping every matching item.
let filtered_items = filter_slash_items("tdo");
@@ -824,7 +831,7 @@ mod tests {
session.key("up");
let wrapped = session.frame();
assert_no_violations(&wrapped, "slash menu scrolled");
assert!(element(&wrapped, "overlay.slash_menu.item.toggle").focused);
assert!(element(&wrapped, "overlay.slash_menu.item.database").focused);
assert!(
!wrapped
.elements
@@ -832,7 +839,7 @@ mod tests {
);
let menu_bounds = element(&wrapped, "overlay.slash_menu").bounds;
assert!(
element(&wrapped, "overlay.slash_menu.item.toggle")
element(&wrapped, "overlay.slash_menu.item.database")
.bounds
.bottom()
<= menu_bounds.bottom()
@@ -932,17 +939,15 @@ mod tests {
assert!(session.node(&converted).is_none());
assert_eq!(session.text("showcase-quote").plain, quote_text);
// No results: one quiet row instead of a collapsed menu. `Tab` and the arrows do
// nothing, and `Enter` closes the menu without touching the block.
// No results: popover stays hidden instead of showing a `No results` card.
// `Tab` and the arrows do nothing, and `Enter` closes the menu without touching the block.
session.settle();
session.open_slash("showcase-quote");
session.type_text("zzz");
let empty = session.frame();
assert_no_violations(&empty, "slash menu without results");
let row = element(&empty, "overlay.slash_menu.empty");
assert_eq!(row.text.as_deref(), Some("No results"));
assert_eq!(row.bounds.height, SLASH_ITEM_HEIGHT);
assert!(element(&empty, "overlay.slash_menu").bounds.height >= SLASH_ITEM_HEIGHT + 28.0);
assert!(!empty.elements.contains_key("overlay.slash_menu"));
assert!(!empty.elements.contains_key("overlay.slash_menu.empty"));
let written = session.written();
session.key("down");
session.key("tab");
@@ -1101,8 +1106,10 @@ mod tests {
session.key("escape");
assert_eq!(session.slash_query(), None);
assert!(session.text("showcase-quote").plain.starts_with("/coEvery"));
session.insert("/x");
assert_eq!(session.slash_query().as_deref(), Some("x"));
session.insert("/ ");
assert_eq!(session.slash_query(), None);
session.insert("/zzz");
assert_eq!(session.slash_query().as_deref(), Some("zzz"));
session.insert(" ");
assert_eq!(session.slash_query(), None);
session.insert("/");
@@ -0,0 +1,673 @@
//! Targeted regression tests for B6 Overlays, Slash/`@` menus, multi-block drag,
//! multi-click drag selection, and desktop Table/Database interactions.
use blocksuite_playground_doc::{
read::BlockContent,
schema::{BlockSpec, ListType, ParagraphType},
};
use ui::{
AppContext, EntityInputHandler, KeyDownEvent, Keystroke, Modifiers, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, ScrollDelta, ScrollEvent, ScrollSource,
TouchPhase, point, px,
};
use crate::{
HOME_PAGE_ID, PlaygroundView,
editor_session::{DocPoint, DocumentSelection},
overlays::{OverlayEvent, SlashCommand},
room_client::DocState,
showcase::seed_showcase_doc,
};
fn make_key(key: &str, shift: bool) -> KeyDownEvent {
KeyDownEvent {
keystroke: Keystroke {
key: key.to_string(),
modifiers: Modifiers {
shift,
..Default::default()
},
..Default::default()
},
is_held: false,
prefer_character_input: false,
}
}
fn make_mouse_down(x: f32, y: f32, click_count: usize, shift: bool) -> MouseDownEvent {
MouseDownEvent {
button: MouseButton::Left,
position: point(px(x), px(y)),
modifiers: Modifiers {
shift,
..Default::default()
},
click_count,
first_mouse: false,
}
}
fn make_mouse_move(x: f32, y: f32, pressed: bool) -> MouseMoveEvent {
MouseMoveEvent {
position: point(px(x), px(y)),
pressed_button: pressed.then_some(MouseButton::Left),
modifiers: Modifiers::default(),
}
}
fn make_mouse_up(x: f32, y: f32) -> MouseUpEvent {
MouseUpEvent {
button: MouseButton::Left,
position: point(px(x), px(y)),
modifiers: Modifiers::default(),
click_count: 1,
}
}
fn open_doc(
state: DocState,
) -> (
std::rc::Rc<ui::HeadlessPlatform>,
ui::ApplicationHandle,
ui::WindowHandle<PlaygroundView>,
ui::HeadlessWindow,
) {
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(), |_w, cx| {
cx.new(|cx| {
let mut v = PlaygroundView::new(cx);
v.set_document(state, cx);
v
})
})
.unwrap()
});
let hw = platform.windows().into_iter().next().unwrap();
hw.request_frame();
(platform, app, win, hw)
}
fn simple_doc(blocks: Vec<(&str, BlockSpec)>) -> DocState {
let mut state = DocState::new("b6-test", 77).unwrap();
state
.workspace
.create_page(HOME_PAGE_ID, "B6 Test", 1)
.unwrap();
let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap();
page.add_block(
"root",
BlockSpec::Page {
title: "B6 Test".into(),
},
None,
None,
1,
)
.unwrap();
page.add_block(
"note",
BlockSpec::Note { xywh: None },
Some("root"),
None,
2,
)
.unwrap();
for (i, (id, spec)) in blocks.into_iter().enumerate() {
page.add_block(id, spec, Some("note"), None, 3 + i as u64)
.unwrap();
}
state
}
#[test]
fn desktop_database_click_never_selects_whole_block_or_deletes_table() {
let state = seed_showcase_doc().unwrap();
let (_platform, app, win, hw) = open_doc(state);
app.update(|cx| {
win.update(cx, |view, window, cx| {
assert!(!view.database_readonly);
let layout = view.flow_layout().unwrap();
let db_block = layout
.blocks
.iter()
.find(|b| b.body.kind == crate::block_flow::FlowKind::Database)
.expect("showcase database");
let db_id = db_block.block_id.clone();
let geom = crate::block_flow::page_geometry(1280.0);
// Scroll the database into view and click inside a non-checkbox cell area.
view.scroll_y = (db_block.y - 80.0).max(0.0);
let sx = geom.column_x + db_block.x + 80.0;
let sy = crate::TOPBAR_HEIGHT + (db_block.y - view.scroll_y) + 120.0;
view.page_mouse_down(&make_mouse_down(sx, sy, 1, false), window, cx);
assert!(
view.block_selection().is_empty(),
"clicking inside desktop database must not whole-block select database"
);
// Pressing Backspace/Delete must NOT delete the database block.
view.editor_key_down(&make_key("backspace", false), window, cx);
view.editor_key_down(&make_key("delete", false), window, cx);
assert!(
view.page_snapshot().unwrap().block(&db_id).is_some(),
"database block must survive Backspace/Delete after cell click"
);
})
.unwrap();
});
hw.request_frame();
}
fn type_chars(
view: &mut PlaygroundView,
text: &str,
window: &mut ui::Window,
cx: &mut ui::Context<PlaygroundView>,
) {
for ch in text.chars() {
let mut buf = [0u8; 4];
view.replace_text_in_range(None, ch.encode_utf8(&mut buf), window, cx);
}
}
#[test]
fn slash_menu_allows_spaces_hides_on_no_match_and_inserts_table_equation_database() {
let state = simple_doc(vec![
(
"p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
),
(
"p2",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
),
(
"p3",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
),
(
"p4",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
),
(
"p5",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
),
(
"p6",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
),
]);
let (_platform, app, win, hw) = open_doc(state);
// 1. P1-7: `/heading 1` with inter-word space stays open and converts to H1; `/ ` closes.
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.select_document_range(
DocumentSelection::caret(DocPoint::new("p1", 0)),
window,
cx,
);
type_chars(view, "/heading 1", window, cx);
assert_eq!(
view.overlays().slash_menu().map(|m| m.query.as_str()),
Some("heading 1"),
"inter-word space must keep typed slash menu open"
);
view.editor_key_down(&make_key("enter", false), window, cx);
let node = view.page_snapshot().unwrap().block("p1").unwrap();
assert!(matches!(
node.content,
BlockContent::Paragraph {
kind: ParagraphType::H1,
..
}
));
// Leading space `/ ` closes slash menu immediately.
view.select_document_range(
DocumentSelection::caret(DocPoint::new("p2", 0)),
window,
cx,
);
type_chars(view, "/", window, cx);
assert!(view.overlays().slash_menu().is_some());
type_chars(view, " ", window, cx);
assert!(
view.overlays().slash_menu().is_none(),
"leading space after `/` must close slash menu"
);
})
.unwrap();
});
// 2. P1-8: URL `https://example.com` hides slash menu popover (no `overlay.slash_menu`).
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.select_document_range(
DocumentSelection::caret(DocPoint::new("p3", 0)),
window,
cx,
);
type_chars(view, "https://example.com", window, cx);
})
.unwrap();
});
hw.request_frame();
app.update(|cx| {
win.update(cx, |_view, window, _cx| {
let snap = window.frame_snapshot();
assert!(
!snap.elements.contains_key("overlay.slash_menu"),
"unmatched URL slash query must hide popover"
);
assert!(!snap.elements.contains_key("overlay.slash_menu.empty"));
})
.unwrap();
});
// 3. P1-9: Table, Equation, Database slash commands + single-step Undo.
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.select_document_range(
DocumentSelection::caret(DocPoint::new("p4", 0)),
window,
cx,
);
type_chars(view, "/table", window, cx);
view.editor_key_down(&make_key("enter", false), window, cx);
assert!(
view.active_table_cell().is_some(),
"/table must insert affine:table and focus first cell"
);
// Single-step undo removes table and restores `/table`.
view.history(false, window, cx).unwrap();
assert_eq!(view.block_text("p4"), Some("/table"));
// Equation
view.select_document_range(
DocumentSelection::caret(DocPoint::new("p5", 0)),
window,
cx,
);
type_chars(view, "/equation", window, cx);
view.editor_key_down(&make_key("enter", false), window, cx);
assert!(
view.overlays().equation_editor().is_some(),
"/equation must insert affine:latex and open equation editor"
);
view.overlays.close_equation_editor();
view.history(false, window, cx).unwrap();
assert_eq!(view.block_text("p5"), Some("/equation"));
// Database (desktop)
view.select_document_range(
DocumentSelection::caret(DocPoint::new("p6", 0)),
window,
cx,
);
type_chars(view, "/database", window, cx);
view.editor_key_down(&make_key("enter", false), window, cx);
let has_db = view
.page_snapshot()
.unwrap()
.block("note")
.unwrap()
.children
.iter()
.any(|c| matches!(c.content, BlockContent::Database(_)) && !c.children.is_empty());
assert!(
has_db,
"/database must insert affine:database with initial row"
);
view.history(false, window, cx).unwrap();
assert_eq!(view.block_text("p6"), Some("/database"));
// Database hidden under database_readonly
view.set_database_mobile_readonly(true, cx);
assert!(
!super::filter_slash_items_for("database", !view.database_readonly)
.iter()
.any(|item| item.command == SlashCommand::Database)
);
})
.unwrap();
});
}
#[test]
fn linked_doc_menu_consumes_tab_and_closes_when_caret_moves_before_at() {
let state = simple_doc(vec![
(
"l1",
BlockSpec::List {
list_type: ListType::Bulleted,
text: "Parent".into(),
checked: false,
order: None,
},
),
(
"l2",
BlockSpec::List {
list_type: ListType::Bulleted,
text: String::new(),
checked: false,
order: None,
},
),
]);
let (_platform, app, win, _hw) = open_doc(state);
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.select_document_range(
DocumentSelection::caret(DocPoint::new("l2", 0)),
window,
cx,
);
view.replace_text_in_range(None, "@", window, cx);
assert!(view.overlays().linked_doc_menu().is_some());
// P1-10: Tab cycles selection without indenting `l2` under `l1`.
view.editor_key_down(&make_key("tab", false), window, cx);
let l1_children = view
.page_snapshot()
.unwrap()
.block("l1")
.unwrap()
.children
.len();
assert_eq!(l1_children, 0, "Tab in @ menu must not indent list item");
// P1-11: ArrowLeft moves caret before `@` (`|@`) and closes menu immediately.
view.editor_key_down(&make_key("left", false), window, cx);
assert!(
view.overlays().linked_doc_menu().is_none(),
"moving caret before `@` must close linked-doc menu"
);
})
.unwrap();
});
}
#[test]
fn multi_block_drag_reorders_all_selected_blocks_atomically() {
let state = simple_doc(vec![
(
"b1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "One".into(),
},
),
(
"b2",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Two".into(),
},
),
(
"b3",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "Three".into(),
},
),
]);
let (_platform, app, win, _hw) = open_doc(state);
app.update(|cx| {
win.update(cx, |view, window, cx| {
view.editor.block_selection = vec!["b1".into(), "b2".into()];
view.dispatch_overlay(OverlayEvent::DragStart("b1".into()), window, cx);
let layout = view.flow_layout().unwrap();
let b3 = layout.block("b3").unwrap();
let geom = crate::block_flow::page_geometry(1280.0);
let drop_x = geom.column_x + b3.x + 20.0;
let drop_y = crate::TOPBAR_HEIGHT + b3.rect().bottom() + 4.0;
view.dispatch_overlay(
OverlayEvent::PointerMoved {
x: drop_x,
y: drop_y,
pressed: true,
},
window,
cx,
);
view.dispatch_overlay(OverlayEvent::PointerUp, window, cx);
let order: Vec<String> = view
.page_snapshot()
.unwrap()
.block("note")
.unwrap()
.children
.iter()
.map(|c| c.id.clone())
.collect();
assert_eq!(order, vec!["b3", "b1", "b2"]);
assert_eq!(
view.block_selection(),
&["b1".to_string(), "b2".to_string()]
);
// Single-step Undo restores original order.
view.history(false, window, cx).unwrap();
let restored: Vec<String> = view
.page_snapshot()
.unwrap()
.block("note")
.unwrap()
.children
.iter()
.map(|c| c.id.clone())
.collect();
assert_eq!(restored, vec!["b1", "b2", "b3"]);
})
.unwrap();
});
}
#[test]
fn double_and_triple_click_drag_extend_by_word_and_paragraph() {
let state = simple_doc(vec![
(
"p1",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "alpha beta gamma".into(),
},
),
(
"p2",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "delta epsilon".into(),
},
),
]);
let (_platform, app, win, _hw) = open_doc(state);
app.update(|cx| {
win.update(cx, |view, window, cx| {
let layout = view.flow_layout().unwrap();
let p1 = layout.block("p1").unwrap();
let p2 = layout.block("p2").unwrap();
let geom = crate::block_flow::page_geometry(1280.0);
let p1_y = crate::TOPBAR_HEIGHT + p1.y + p1.body.height * 0.5;
let p2_y = crate::TOPBAR_HEIGHT + p2.y + p2.body.height * 0.5;
// Double-click "alpha" then drag into "beta".
let alpha_x = geom.column_x + p1.x + 12.0;
let beta_x = geom.column_x + p1.x + 56.0;
view.page_mouse_down(&make_mouse_down(alpha_x, p1_y, 2, false), window, cx);
assert!(view.editor.dragging, "double-click must stay draggable");
view.root_mouse_move(&make_mouse_move(beta_x, p1_y, true), window, cx);
view.root_mouse_up(&make_mouse_up(beta_x, p1_y), window, cx);
let sel = view.document_selection().unwrap();
assert_eq!(sel.anchor.offset(), 0);
assert_eq!(sel.focus.offset(), 10, "word-drag must cover 'alpha beta'");
// Triple-click p1 then drag into p2.
view.page_mouse_down(&make_mouse_down(alpha_x, p1_y, 3, false), window, cx);
view.root_mouse_move(&make_mouse_move(alpha_x, p2_y, true), window, cx);
view.root_mouse_up(&make_mouse_up(alpha_x, p2_y), window, cx);
let sel = view.document_selection().unwrap();
assert_eq!(sel.anchor.block_id, "p1");
assert_eq!(sel.anchor.offset(), 0);
assert_eq!(sel.focus.block_id, "p2");
assert_eq!(sel.focus.offset(), 13, "paragraph-drag must cover full p2");
})
.unwrap();
});
}
#[test]
fn table_cell_pointer_selection_wide_auto_scroll_and_shift_wheel() {
let wide_row: Vec<String> = (0..10).map(|i| format!("col{i} alpha beta")).collect();
let state = simple_doc(vec![(
"tbl",
BlockSpec::Table {
rows: vec![wide_row.clone(), wide_row],
},
)]);
let (_platform, app, win, hw) = open_doc(state);
app.update(|cx| {
win.update(cx, |view, window, cx| {
let layout = view.flow_layout().unwrap();
let block = layout.block("tbl").unwrap();
let hit = block
.body
.table_cells
.iter()
.find(|c| c.row_id == "row-0" && c.column_id == "col-0")
.unwrap();
let geom = crate::block_flow::page_geometry(1280.0);
let cell_y = crate::TOPBAR_HEIGHT + block.y + hit.rect.y + hit.rect.h * 0.5;
let cell_x0 = geom.column_x + block.x + hit.text_origin.0 + 4.0;
let cell_x1 = geom.column_x + block.x + hit.text_origin.0 + 70.0;
// P1-12: Double-click selects word.
view.dispatch_overlay(
OverlayEvent::TableCellMouseDown {
block_id: "tbl".into(),
row_id: "row-0".into(),
column_id: "col-0".into(),
screen_pos: (cell_x0, cell_y),
click_count: 2,
shift: false,
},
window,
cx,
);
view.root_mouse_up(&make_mouse_up(cell_x0, cell_y), window, cx);
assert_eq!(
view.active_table_cell().unwrap().input.selected_text(),
"col0"
);
// P1-12: Triple-click selects full cell.
view.dispatch_overlay(
OverlayEvent::TableCellMouseDown {
block_id: "tbl".into(),
row_id: "row-0".into(),
column_id: "col-0".into(),
screen_pos: (cell_x0, cell_y),
click_count: 3,
shift: false,
},
window,
cx,
);
view.root_mouse_up(&make_mouse_up(cell_x0, cell_y), window, cx);
assert_eq!(
view.active_table_cell().unwrap().input.selected_text(),
"col0 alpha beta"
);
// P1-12: Drag selects range + Shift+click extends.
view.dispatch_overlay(
OverlayEvent::TableCellMouseDown {
block_id: "tbl".into(),
row_id: "row-0".into(),
column_id: "col-0".into(),
screen_pos: (cell_x0, cell_y),
click_count: 1,
shift: false,
},
window,
cx,
);
view.root_mouse_move(&make_mouse_move(cell_x1, cell_y, true), window, cx);
view.root_mouse_up(&make_mouse_up(cell_x1, cell_y), window, cx);
assert!(
!view.active_table_cell().unwrap().input.selection.is_empty(),
"dragging in table cell must select text"
);
// P1-13: Focusing offscreen column col-8 auto-scrolls table horizontally.
assert_eq!(view.overlays().code_scroll_x("tbl"), 0.0);
view.focus_table_cell(
"tbl".into(),
"row-0".into(),
"col-8".into(),
None,
window,
cx,
);
assert!(
view.overlays().code_scroll_x("tbl") > 0.0,
"focusing offscreen wide table column must scroll horizontally"
);
// P1-24 Page: Shift+wheel scrolls wide table horizontally, not page vertically.
let scroll_before = view.overlays().code_scroll_x("tbl");
let page_y_before = view.scroll_y;
view.on_scroll(
&ScrollEvent {
position: point(px(cell_x0 + 40.0), px(cell_y)),
delta: ScrollDelta::Pixels(point(px(0.0), px(60.0))),
modifiers: Modifiers {
shift: true,
..Default::default()
},
touch_phase: TouchPhase::Moved,
source: ScrollSource::Pointer,
},
window,
cx,
);
assert_ne!(
view.overlays().code_scroll_x("tbl"),
scroll_before,
"Shift+wheel over wide table must scroll horizontally"
);
assert_eq!(
view.scroll_y, page_y_before,
"Shift+wheel over wide table must not scroll page vertically"
);
})
.unwrap();
});
hw.request_frame();
}
+81 -133
View File
@@ -1,9 +1,6 @@
use std::{ops::Range, time::Duration};
use blocksuite_playground_doc::{
read::{PageSnapshot, TextAlign as BlockAlign},
session::SelectionSnapshot,
};
use blocksuite_playground_doc::read::{PageSnapshot, TextAlign as BlockAlign};
use ui::{
AnyElement, ClipboardItem, Context, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
MouseUpEvent, Window,
@@ -149,13 +146,42 @@ impl PlaygroundView {
self.overlays.set_keyboard_toolbar_visible(false);
self.announce_selection(cx);
self.sync_slash_trigger(cx);
self.sync_linked_doc_trigger(cx);
window.notify_text_selection_changed(&self.editor_focus);
cx.notify();
}
}
return;
}
OverlayEvent::DragStart(_) => self.editor.dragging = false,
OverlayEvent::DragStart(block_id) => {
self.editor.dragging = false;
let now_ms = self.now_ms(cx);
let dragged_ids = self.resolve_multi_drag_ids(block_id);
self.overlays
.start_drag(block_id.clone(), dragged_ids, now_ms);
cx.notify();
return;
}
OverlayEvent::TableCellMouseDown {
block_id,
row_id,
column_id,
screen_pos,
click_count,
shift,
} => {
self.focus_table_cell_pointer(
block_id.clone(),
row_id.clone(),
column_id.clone(),
Some(*screen_pos),
*click_count,
*shift,
window,
cx,
);
return;
}
_ if self.handle_embed_and_code_event(&event, window, cx) => return,
_ if self.handle_context_menu_event(&event, window, cx) => return,
_ if self.handle_linked_doc_event(&event, window, cx) => return,
@@ -233,6 +259,9 @@ impl PlaygroundView {
if self.overlays.slash_menu().is_none() {
self.editor.slash_trigger = None;
}
if self.overlays.linked_doc_menu().is_none() {
self.editor.linked_doc_trigger = None;
}
if effects.redraw {
cx.notify();
}
@@ -260,6 +289,7 @@ impl PlaygroundView {
self.sync_link_input(input, window, cx);
self.keyboard_toolbar_dismissed = false;
self.editor.slash_trigger = None;
self.editor.linked_doc_trigger = None;
self.editor.block_selection.clear();
if let Some(layout) = self.flow_layout() {
let geometry = crate::page_geometry(f32::from(window.viewport_size().width));
@@ -275,26 +305,25 @@ impl PlaygroundView {
let prev_sel = self.editor.selection.clone();
let consumed =
self.click_database_point(&block_id, local_x, local_y, Some(window), cx);
if consumed || self.database_readonly {
self.show_database_readonly_toast_once(cx);
let focused_new_row = consumed
&& self.editor.selection != prev_sel
&& self.editor.selection.is_some();
if !focused_new_row {
self.clear_body_selection(window, cx);
self.suppress_unselected_root_input = true;
if !consumed && self.database_readonly {
self.editor.block_selection = vec![block_id];
self.keep_keyboard_on_block_selection = false;
self.block_selection_return_caret = None;
self.announce_selection(cx);
window.notify_text_selection_changed(&self.editor_focus);
}
self.show_database_readonly_toast_once(cx);
let focused_new_row = consumed
&& self.editor.selection != prev_sel
&& self.editor.selection.is_some();
if !focused_new_row {
self.clear_body_selection(window, cx);
if !consumed && self.database_readonly {
self.editor.block_selection = vec![block_id];
self.keep_keyboard_on_block_selection = false;
self.block_selection_return_caret = None;
self.announce_selection(cx);
window.notify_text_selection_changed(&self.editor_focus);
} else if !consumed {
self.editor_focus.focus(window, cx);
}
self.editor.dragging = false;
cx.notify();
return;
}
self.editor.dragging = false;
cx.notify();
return;
}
// Clicking a non-editable block (Bookmark, Image, Divider, Database body, Table frame)
// or its horizontal row band selects that whole block into `block_selection` instead
@@ -306,7 +335,6 @@ impl PlaygroundView {
.then(|| block.block_id.clone())
}) {
self.commit_active_preedit(window, cx);
self.suppress_unselected_root_input = false;
self.editor.selection = None;
self.editor.block_selection = vec![non_editable_id];
self.keep_keyboard_on_block_selection = false;
@@ -346,10 +374,6 @@ impl PlaygroundView {
return;
}
self.editor_mouse_down(event, window, cx);
// A double or triple click selects at once; only a plain press starts a drag.
if event.click_count >= 2 {
self.editor.dragging = false;
}
cx.notify();
}
@@ -382,6 +406,10 @@ impl PlaygroundView {
return;
}
if self.mode == PlaygroundMode::Page && self.overlays.dragged_block().is_none() {
if self.table_cell.as_ref().is_some_and(|c| c.dragging) {
self.table_cell_mouse_move(event, window, cx);
return;
}
let selecting = self.editor.dragging;
self.editor_mouse_move(event, window, cx);
if selecting && !self.editor.dragging {
@@ -399,9 +427,14 @@ impl PlaygroundView {
if self.scrollbar_drag.take().is_some() {
cx.notify();
}
if let Some(cell) = self.table_cell.as_mut() {
cell.dragging = false;
}
if self.mode == PlaygroundMode::Edgeless {
self.on_edgeless_left_up(event, window, cx);
}
self.editor.drag_moved = false;
self.editor.drag_mode = crate::editor_session::DragSelectionMode::Character;
// The selection is finished: the formatting toolbar may open over it.
if std::mem::take(&mut self.editor.dragging) {
cx.notify();
@@ -434,6 +467,15 @@ impl PlaygroundView {
self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx);
return true;
}
"tab" => {
let next = if event.keystroke.modifiers.shift {
(selected + row_count - 1) % row_count
} else {
(selected + 1) % row_count
};
self.dispatch_overlay(OverlayEvent::LinkedDocHover(next), window, cx);
return true;
}
"enter" => {
self.dispatch_overlay(OverlayEvent::LinkedDocSelect(selected), window, cx);
return true;
@@ -448,6 +490,7 @@ impl PlaygroundView {
let now_ms = self.now_ms(cx);
let secondary = event.keystroke.modifiers.secondary(cx);
let input = self.link_input_state();
self.overlays.set_database_readonly(self.database_readonly);
let effects = self.overlays.key_down(&event.keystroke, secondary, now_ms);
let handled = self.apply_overlay_effects(effects, window, cx);
self.sync_link_input(input, window, cx);
@@ -469,109 +512,6 @@ impl PlaygroundView {
Some(result)
}
/// The editor typed a `/` into paragraph or list text: open the slash menu on it.
///
/// The `/` is remembered as a relative position naming that very character, so text
/// a peer inserts before it moves the menu along instead of misplacing it.
pub(crate) fn open_typed_slash_menu(
&mut self,
block_id: String,
slash_offset: u64,
cx: &mut Context<Self>,
) {
if self.editor.slash_trigger.is_some() && self.overlays.slash_menu().is_some() {
return;
}
let Some(position) = self.page().and_then(|page| {
page.capture_selection_snapshot(&block_id, slash_offset, &block_id, slash_offset)
.ok()
}) else {
return;
};
let now_ms = self.now_ms(cx);
self.editor.slash_trigger = Some((block_id.clone(), position));
self.overlays
.open_typed_slash(block_id, slash_offset as usize, now_ms);
cx.notify();
}
/// Where the `/` remembered as `position` is now, the caret behind it, and the filter
/// typed between the two.
///
/// `None` when the menu has nothing left to act on: the character at the position is
/// not that `/` any more (deleted, or deleted and typed again by a peer, which is
/// another character), the caret is not a caret in the same block behind it, or the
/// text between them holds whitespace.
pub(super) fn typed_slash(
&self,
block_id: &str,
position: &SelectionSnapshot,
) -> Option<(u64, u64, String)> {
let page = self.page()?;
let resolved = page.resolve_selection_snapshot(position).ok()??;
let slash = resolved.anchor.1;
if resolved.anchor.0 != block_id
|| resolved.focus.0 != block_id
|| resolved.focus.1 != slash
{
return None;
}
let units: Vec<u16> = page
.read_editable_text(block_id)
.ok()?
.0
.plain
.encode_utf16()
.collect();
if units.get(slash as usize) != Some(&u16::from(b'/')) {
return None;
}
// A position resolves to where a deleted character was; only the same character
// gives the same position back.
if page
.capture_selection_snapshot(block_id, slash, block_id, slash)
.ok()?
!= *position
{
return None;
}
let selection = self.editor.selection.as_ref()?;
let caret = selection.focus.offset();
if !selection.empty() || selection.focus.block_id != block_id || caret <= slash {
return None;
}
let query = String::from_utf16(units.get(slash as usize + 1..caret as usize)?).ok()?;
(!query.chars().any(char::is_whitespace)).then_some((slash, caret, query))
}
/// After a local or remote edit or a selection change: the text between the typed `/`
/// and the caret is the slash menu's filter, and the menu follows the `/`. The menu
/// closes once [`Self::typed_slash`] finds nothing to act on.
pub(crate) fn sync_slash_trigger(&mut self, cx: &Context<Self>) {
let Some(menu_block) = self
.overlays
.slash_menu()
.filter(|menu| menu.query_in_document)
.map(|menu| menu.block_id.clone())
else {
return;
};
let typed = self
.editor
.slash_trigger
.as_ref()
.filter(|(block_id, _)| *block_id == menu_block)
.and_then(|(block_id, position)| self.typed_slash(block_id, position));
match typed {
Some((slash, _, query)) => self.overlays.set_typed_slash(slash as usize, query),
None => {
let now_ms = self.now_ms(cx);
self.editor.slash_trigger = None;
self.overlays.close_slash(now_ms);
}
}
}
/// Scroll a code block sideways so the caret at world x `caret_x` stays in view.
pub(crate) fn reveal_code_caret(&mut self, block_id: &str, caret_x: f32) {
let Some(layout) = self.flow_layout() else {
@@ -680,10 +620,15 @@ impl PlaygroundView {
return Default::default();
};
let now_ms = self.now_ms(cx);
// The toolbar waits for the selection to be finished, and stays hidden in read-only mode.
let selection = (!self.page_readonly && !self.editor.dragging)
// The toolbar waits for a plain drag to finish, opens immediately on double/triple
// click until the pointer moves, and stays hidden in read-only mode.
let drag_hides_toolbar = self.editor.dragging
&& (self.editor.drag_mode == crate::editor_session::DragSelectionMode::Character
|| self.editor.drag_moved);
let selection = (!self.page_readonly && !drag_hides_toolbar)
.then(|| self.selection_format(layout))
.flatten();
self.overlays.set_database_readonly(self.database_readonly);
let scene = self.overlay_scene(
&snapshot,
layout,
@@ -702,6 +647,9 @@ impl PlaygroundView {
if self.overlays.slash_menu().is_none() {
self.editor.slash_trigger = None;
}
if self.overlays.linked_doc_menu().is_none() {
self.editor.linked_doc_trigger = None;
}
layer
}
@@ -247,9 +247,7 @@ impl PlaygroundView {
let offset = block
.hit_text(wx + scroll, wy)
.map_or(max_u16, |c| c.utf16_offset.min(max_u16));
if !self.editor.composing() && self.point_in_painted_selection(&layout, wx, wy) {
self.suppress_unselected_root_input = false;
} else {
if self.editor.composing() || !self.point_in_painted_selection(&layout, wx, wy) {
let block_id = block.block_id.clone();
self.change_selection(
DocumentSelection::caret(DocPoint::new(&block_id, offset)),
@@ -216,6 +216,11 @@ impl PlaygroundView {
DocEdit::Bookmark { block_id, url } => {
self.insert_bookmark_after_block(&block_id, url, window, cx)
}
DocEdit::ReorderMany {
parent_id,
child_ids,
insert_index,
} => self.run_reorder_many(&parent_id, child_ids, insert_index, window, cx),
edit @ (DocEdit::SetProp { .. } | DocEdit::Reorder { .. }) => {
let before = self.selection_snapshot();
let page = self.page_mut()?;
@@ -387,6 +392,14 @@ impl PlaygroundView {
if command == SlashCommand::LinkedDoc {
return self.run_linked_doc_slash_command(block_id, offset, strip, window, cx);
}
if matches!(
command,
SlashCommand::Table | SlashCommand::Equation | SlashCommand::Database
) {
return self.run_block_insert_slash_command(
block_id, parent_id, slot, node, command, strip, window, cx,
);
}
let fresh = self.fresh_block_id();
let trailing = self.fresh_block_id();
let text_block = |node: &BlockNode| {
@@ -85,11 +85,18 @@ impl PlaygroundView {
let visible_items = menu.results.items.len().min(6);
let trigger = self.editor.linked_doc_trigger.take();
let strip = if menu.query_in_document {
trigger
let found = trigger
.as_ref()
.filter(|(b, _, _)| *b == menu.block_id)
.and_then(|(b, pos, _)| self.typed_linked_doc(b, pos))
.map(|(at, caret, _)| (at, caret - at))
.map(|(at, caret, _)| (at, caret - at));
// Trigger `@` is gone or caret moved out of range: close without leaving a zombie `@`.
if found.is_none() {
self.overlays.close_linked_doc(now_ms);
cx.notify();
return true;
}
found
} else {
None
};
@@ -272,6 +272,7 @@ impl PlaygroundView {
/// (`enable_mobile_database_editing == false`).
pub fn set_database_mobile_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
self.database_readonly = readonly;
self.overlays.set_database_readonly(readonly);
if self.flow.database_state.mobile_readonly != readonly {
self.flow.database_state.mobile_readonly = readonly;
if !readonly {
@@ -764,7 +764,6 @@ impl PlaygroundView {
Some(cx),
);
self.editor = Default::default();
self.suppress_unselected_root_input = true;
self.overlays.reset();
self.reading_anchor = None;
self.flow = crate::block_flow::BlockFlow::new();
@@ -0,0 +1,460 @@
//! Block-insertion slash commands (`Table`, `Equation`, `Database`), atomic multi-block
//! drag-handle reorder (`ReorderMany`), and word/paragraph drag-selection extension.
use std::collections::{BTreeMap, HashSet};
use blocksuite_playground_doc::{
DocError, DocResult,
read::{BlockContent, BlockNode},
schema::{BlockSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec, ParagraphType},
session::SelectionSnapshot,
};
use serde_json::json;
use ui::{Context, Window};
use crate::{
PlaygroundView,
block_flow::FlowLayout,
editor_session::{DocPoint, DocumentSelection, DragSelectionMode, word_range},
};
use super::*;
fn default_database_spec() -> DatabaseSpec {
DatabaseSpec {
title: "Database".to_string(),
columns: vec![DatabaseColumnSpec {
id: "col-tags".into(),
column_type: "multi-select".into(),
name: "Tags".into(),
data: json!({ "options": [] }),
}],
views: vec![DatabaseViewSpec {
id: "view-table".into(),
name: "Table View".into(),
mode: "table".into(),
raw: json!({
"columns": [
{"id": "title", "width": 220},
{"id": "col-tags", "width": 160}
],
"filter": {"type": "group", "op": "and", "conditions": []},
"header": {"titleColumn": "title", "iconColumn": "type"}
}),
}],
cells: BTreeMap::new(),
}
}
impl PlaygroundView {
/// The editor typed a `/` into paragraph or list text: open the slash menu on it.
pub(crate) fn open_typed_slash_menu(
&mut self,
block_id: String,
slash_offset: u64,
cx: &mut Context<Self>,
) {
if self.editor.slash_trigger.is_some() && self.overlays.slash_menu().is_some() {
return;
}
let Some(position) = self.page().and_then(|page| {
page.capture_selection_snapshot(&block_id, slash_offset, &block_id, slash_offset)
.ok()
}) else {
return;
};
let now_ms = self.now_ms(cx);
self.editor.slash_trigger = Some((block_id.clone(), position));
self.overlays
.open_typed_slash(block_id, slash_offset as usize, now_ms);
cx.notify();
}
/// Where the `/` remembered as `position` is now, the caret behind it, and the filter
/// typed between the two (allowing inter-word spaces like `/heading 1`).
pub(super) fn typed_slash(
&self,
block_id: &str,
position: &SelectionSnapshot,
) -> Option<(u64, u64, String)> {
let page = self.page()?;
let resolved = page.resolve_selection_snapshot(position).ok()??;
let slash = resolved.anchor.1;
if resolved.anchor.0 != block_id
|| resolved.focus.0 != block_id
|| resolved.focus.1 != slash
{
return None;
}
let units: Vec<u16> = page
.read_editable_text(block_id)
.ok()?
.0
.plain
.encode_utf16()
.collect();
if units.get(slash as usize) != Some(&u16::from(b'/')) {
return None;
}
if page
.capture_selection_snapshot(block_id, slash, block_id, slash)
.ok()?
!= *position
{
return None;
}
let selection = self.editor.selection.as_ref()?;
let caret = selection.focus.offset();
if !selection.empty() || selection.focus.block_id != block_id || caret <= slash {
return None;
}
let query = String::from_utf16(units.get(slash as usize + 1..caret as usize)?).ok()?;
if query.contains('\n')
|| query.contains('\r')
|| query.starts_with(char::is_whitespace)
|| query.contains(" ")
|| (query.ends_with(char::is_whitespace)
&& filter_slash_items_for(&query, !self.database_readonly).is_empty())
{
return None;
}
Some((slash, caret, query))
}
/// Synchronize the typed `/` slash menu filter with the document text and caret.
pub(crate) fn sync_slash_trigger(&mut self, cx: &Context<Self>) {
let Some(menu_block) = self
.overlays
.slash_menu()
.filter(|menu| menu.query_in_document)
.map(|menu| menu.block_id.clone())
else {
return;
};
let typed = self
.editor
.slash_trigger
.as_ref()
.filter(|(block_id, _)| *block_id == menu_block)
.and_then(|(block_id, position)| self.typed_slash(block_id, position));
match typed {
Some((slash, _, query)) => self.overlays.set_typed_slash(slash as usize, query),
None => {
let now_ms = self.now_ms(cx);
self.editor.slash_trigger = None;
self.overlays.close_slash(now_ms);
}
}
}
/// Collect top-level selected blocks in document order when dragging a block that belongs
/// to a multi-block `block_selection`; otherwise returns just `[block_id]`.
pub(super) fn resolve_multi_drag_ids(&self, block_id: &str) -> Vec<String> {
if self.editor.block_selection.len() <= 1
|| !self.editor.block_selection.iter().any(|id| id == block_id)
{
return vec![block_id.to_string()];
}
let selected: HashSet<&str> = self
.editor
.block_selection
.iter()
.map(String::as_str)
.collect();
let Some(root) = self.snapshot.as_ref().and_then(|s| s.root.as_ref()) else {
return vec![block_id.to_string()];
};
let mut out = Vec::new();
fn walk(node: &BlockNode, selected: &HashSet<&str>, out: &mut Vec<String>) {
for child in &node.children {
if selected.contains(child.id.as_str()) {
out.push(child.id.clone());
} else {
walk(child, selected, out);
}
}
}
walk(root, &selected, &mut out);
if out.is_empty() {
vec![block_id.to_string()]
} else {
out
}
}
/// Reorder a multi-block selection into `parent_id` before `insert_index` in one atomic
/// `structural_edit` undo step, preserving the multi-block selection afterward.
pub(super) fn run_reorder_many(
&mut self,
parent_id: &str,
child_ids: Vec<String>,
insert_index: usize,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
if child_ids.is_empty() {
return Ok(());
}
let snapshot = self
.snapshot
.clone()
.ok_or_else(|| DocError::InvalidState("missing page".into()))?;
let root = snapshot
.root
.as_ref()
.ok_or_else(|| DocError::InvalidState("missing root".into()))?;
let dragged_set: HashSet<&str> = child_ids.iter().map(String::as_str).collect();
let parent_node = snapshot
.block(parent_id)
.ok_or_else(|| DocError::BlockNotFound(parent_id.to_string()))?;
// Anchor sibling: first non-dragged child at or after `insert_index`.
let anchor_sibling_id: Option<String> = parent_node
.children
.get(insert_index..)
.and_then(|tail| tail.iter().find(|c| !dragged_set.contains(c.id.as_str())))
.map(|c| c.id.clone());
let initial_children: Vec<String> =
parent_node.children.iter().map(|c| c.id.clone()).collect();
let mut old_parents: Vec<(String, String)> = Vec::with_capacity(child_ids.len());
for cid in &child_ids {
if let Some((old_parent, _)) = find_parent(root, cid) {
old_parents.push((cid.clone(), old_parent.id.clone()));
}
}
let before = self.selection_snapshot();
let now = self.now_ms(cx) as u64;
let page = self.page_mut()?;
page.stop_capturing()?;
let commit = page.structural_edit(now, move |page| {
let mut live_children = initial_children.clone();
for (cid, old_parent_id) in &old_parents {
let raw_target = anchor_sibling_id
.as_deref()
.and_then(|aid| live_children.iter().position(|id| id == aid))
.unwrap_or(live_children.len());
if old_parent_id == parent_id {
let Some(cur_idx) = live_children.iter().position(|id| id == cid) else {
continue;
};
let new_idx = if cur_idx < raw_target {
raw_target - 1
} else {
raw_target
};
if cur_idx != new_idx {
page.reparent_block(cid, parent_id, parent_id, new_idx as u64, now)?;
let moved = live_children.remove(cur_idx);
live_children.insert(new_idx, moved);
}
} else {
page.reparent_block(cid, old_parent_id, parent_id, raw_target as u64, now)?;
live_children.insert(raw_target, cid.clone());
}
}
Ok(())
})?;
if commit.is_some()
&& let Some(before) = before
{
page.set_undo_selection_snapshot(before)?;
}
page.stop_capturing()?;
self.editor.last_typing = None;
self.did_edit(commit, None, window, cx);
self.editor.block_selection = child_ids;
self.announce_selection(cx);
self.editor.reveal = false;
window.notify_text_selection_changed(&self.editor_focus);
cx.notify();
Ok(())
}
/// Execute `SlashCommand::Table`, `SlashCommand::Equation`, or `SlashCommand::Database`
/// in a single atomic `structural_edit` undo step.
#[allow(clippy::too_many_arguments)]
pub(super) fn run_block_insert_slash_command(
&mut self,
block_id: &str,
parent_id: &str,
slot: usize,
node: &BlockNode,
command: SlashCommand,
strip: Option<(u64, u64)>,
window: &mut Window,
cx: &mut Context<Self>,
) -> DocResult {
if command == SlashCommand::Database && self.database_readonly {
self.show_database_readonly_toast_once(cx);
return Ok(());
}
let remaining_empty = node.children.is_empty()
&& match &node.content {
BlockContent::Paragraph { text, .. } => {
let total = text.plain.encode_utf16().count() as u64;
let stripped = strip.map_or(0, |(_, len)| len);
total <= stripped
}
_ => false,
};
let fresh = self.fresh_block_id();
let db_row_id = (command == SlashCommand::Database).then(|| self.fresh_block_id());
let spec = match command {
SlashCommand::Database => BlockSpec::Database(default_database_spec()),
_ => command.block_spec(),
};
let before = self.selection_snapshot();
let now = self.now_ms(cx) as u64;
let page = self.page_mut()?;
let commit = page.structural_edit(now, |page| {
if let Some((slash, len)) = strip {
page.remove_text(block_id, "prop:text", slash, len, now)?;
}
page.add_block(&fresh, spec, Some(parent_id), Some(slot as u64 + 1), now)?;
if let Some(ref row_id) = db_row_id {
page.add_block(
row_id,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
Some(&fresh),
Some(0),
now,
)?;
}
if remaining_empty {
page.delete_block_subtree(parent_id, block_id, now)?;
}
Ok(())
})?;
if commit.is_some()
&& let Some(before) = before
{
page.set_undo_selection_snapshot(before)?;
}
if remaining_empty {
self.editor.selection = None;
}
self.editor.last_typing = None;
self.did_edit(commit, None, window, cx);
match command {
SlashCommand::Table => {
let first_cell = self
.snapshot
.as_ref()
.and_then(|s| s.block(&fresh))
.and_then(|n| match &n.content {
BlockContent::Table(t) => Some((
t.rows.first()?.row_id.clone(),
t.columns.first()?.column_id.clone(),
)),
_ => None,
});
if let Some((row_id, col_id)) = first_cell {
self.focus_table_cell(fresh, row_id, col_id, None, window, cx);
}
}
SlashCommand::Equation => {
self.dispatch_overlay(
OverlayEvent::OpenEquationEditor {
target: EquationTarget::Block { block_id: fresh },
initial: String::new(),
},
window,
cx,
);
}
SlashCommand::Database => {}
_ => {}
}
Ok(())
}
/// Extend a body mouse-drag selection according to `self.editor.drag_mode`
/// (`Character`, `Word`, or `Paragraph`).
pub(crate) fn extend_drag_selection(
&self,
sel: &DocumentSelection,
focus: DocPoint,
layout: Option<&FlowLayout>,
) -> DocumentSelection {
match &self.editor.drag_mode {
DragSelectionMode::Character => DocumentSelection {
anchor: sel.anchor.clone(),
focus,
},
DragSelectionMode::Word {
block_id: anchor_block,
start: a_start,
end: a_end,
} => {
let focus_text = self.block_text(&focus.block_id).unwrap_or("");
let f_range = word_range(focus_text, focus.offset());
let forward = match layout {
Some(l) => {
let ai = l
.blocks
.iter()
.position(|b| b.block_id == *anchor_block)
.unwrap_or(0);
let fi = l
.blocks
.iter()
.position(|b| b.block_id == focus.block_id)
.unwrap_or(ai);
(fi, f_range.start) >= (ai, *a_start)
}
None => f_range.start >= *a_start,
};
if forward {
DocumentSelection {
anchor: DocPoint::new(anchor_block, *a_start),
focus: DocPoint::new(&focus.block_id, f_range.end),
}
} else {
DocumentSelection {
anchor: DocPoint::new(anchor_block, *a_end),
focus: DocPoint::new(&focus.block_id, f_range.start),
}
}
}
DragSelectionMode::Paragraph {
block_id: anchor_block,
} => {
let anchor_len = self
.block_text(anchor_block)
.map_or(0, |s| s.encode_utf16().count() as u64);
let focus_len = self
.block_text(&focus.block_id)
.map_or(0, |s| s.encode_utf16().count() as u64);
let forward = match layout {
Some(l) => {
let ai = l
.blocks
.iter()
.position(|b| b.block_id == *anchor_block)
.unwrap_or(0);
let fi = l
.blocks
.iter()
.position(|b| b.block_id == focus.block_id)
.unwrap_or(ai);
fi >= ai
}
None => true,
};
if forward {
DocumentSelection {
anchor: DocPoint::new(anchor_block, 0),
focus: DocPoint::new(&focus.block_id, focus_len),
}
} else {
DocumentSelection {
anchor: DocPoint::new(anchor_block, anchor_len),
focus: DocPoint::new(&focus.block_id, 0),
}
}
}
}
}
}
@@ -1,6 +1,7 @@
//! In-place live `Y.Text` editing glue for `affine:table` cells on [`PlaygroundView`].
mod paint;
mod pointer;
use std::rc::Rc;
@@ -12,7 +13,7 @@ use crate::{
PlaygroundView, TOPBAR_HEIGHT,
block_flow::{FlowLayout, page_geometry},
edgeless::EdgelessInlineEdit,
overlays::InlineTableCell,
overlays::{InlineTableCell, TableCellDragMode},
};
/// How [`PlaygroundView::finish_inline_targets`] handles any in-flight IME preedit.
@@ -88,9 +89,6 @@ impl PlaygroundView {
if let Ok(page) = self.page_mut() {
let _ = page.stop_capturing();
}
if self.editor.selection.is_none() {
self.suppress_unselected_root_input = true;
}
if let Some(w) = window {
w.notify_text_input_changed(&self.editor_focus);
w.notify_text_selection_changed(&self.editor_focus);
@@ -111,12 +109,50 @@ impl PlaygroundView {
screen_pos: Option<(f32, f32)>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.focus_table_cell_pointer(
block_id, row_id, column_id, screen_pos, 1, false, window, cx,
);
}
/// Focus an `affine:table` cell from a pointer event (supports single click, double-click
/// word selection, triple-click full-cell selection, Shift+click range extension, and drag).
#[allow(clippy::too_many_arguments)]
pub(crate) fn focus_table_cell_pointer(
&mut self,
block_id: String,
row_id: String,
column_id: String,
screen_pos: Option<(f32, f32)>,
click_count: usize,
shift: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
let same_cell = self.table_cell.as_ref().is_some_and(|c| {
c.block_id == block_id && c.row_id == row_id && c.column_id == column_id
});
let apply_pointer_sel = |cell: &mut InlineTableCell, off: usize, allow_shift: bool| {
if click_count >= 3 {
let len = utf16_len(&cell.input.text);
cell.input.select(0..len);
cell.drag_mode = TableCellDragMode::All;
} else if click_count == 2 {
let r = crate::editor_session::word_range(&cell.input.text, off as u64);
let (s, e) = (r.start as usize, r.end as usize);
cell.input.select(s..e);
cell.drag_mode = TableCellDragMode::Word(s, e);
} else if allow_shift && shift {
cell.input.move_caret(off, true);
cell.drag_mode = TableCellDragMode::Character;
} else {
cell.input.select(off..off);
cell.drag_mode = TableCellDragMode::Character;
}
cell.dragging = true;
cell.goal_x = None;
};
if same_cell {
self.suppress_unselected_root_input = false;
if self
.table_cell
.as_ref()
@@ -139,9 +175,10 @@ impl PlaygroundView {
let off = hit
.hit_text(local_x, local_y, &cell.input.text)
.utf16_offset as usize;
cell.input.select(off..off);
cell.goal_x = None;
apply_pointer_sel(cell, off, true);
}
} else if let Some(cell) = self.table_cell.as_mut() {
cell.dragging = false;
}
} else {
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
@@ -155,7 +192,6 @@ impl PlaygroundView {
if live.is_none() {
return;
}
self.suppress_unselected_root_input = false;
let now_ms = self.now_ms(cx);
self.overlays.pointer_pressed(now_ms);
self.equation_snapshot = None;
@@ -188,10 +224,11 @@ impl PlaygroundView {
let local_x = sx - geom.column_x - bx + self.overlays.code_scroll_x(&cell.block_id);
let local_y = sy - TOPBAR_HEIGHT + self.scroll_y - by;
let off = hit.hit_text(local_x, local_y, &initial).utf16_offset as usize;
cell.input.select(off..off);
apply_pointer_sel(&mut cell, off, false);
}
self.table_cell = Some(cell);
}
self.reveal_table_cell();
self.table_cell_update_anchors();
self.reset_caret_blink(cx);
self.editor_focus.focus(window, cx);
@@ -239,6 +276,7 @@ impl PlaygroundView {
self.did_table_cell_commit(&block_id, commit);
}
}
self.reveal_table_cell();
self.table_cell_update_anchors();
self.reset_caret_blink(cx);
window.notify_text_input_changed(&self.editor_focus);
@@ -511,7 +549,6 @@ impl PlaygroundView {
let table_block_id = self.table_cell.as_ref().map(|c| c.block_id.clone());
self.finish_inline_targets(InlineTargetEnd::CommitPreedit, Some(window), Some(cx));
if let Some(id) = table_block_id {
self.suppress_unselected_root_input = false;
self.editor.block_selection = vec![id];
self.announce_selection(cx);
window.notify_text_selection_changed(&self.editor_focus);
@@ -563,6 +600,7 @@ impl PlaygroundView {
{
let _ = self.table_cell_edit(window, cx, |_| Some(splice));
} else {
self.reveal_table_cell();
self.table_cell_update_anchors();
self.reset_caret_blink(cx);
window.notify_text_selection_changed(&self.editor_focus);
@@ -609,6 +647,7 @@ impl PlaygroundView {
{
let _ = self.table_cell_edit(window, cx, |_| Some(splice));
} else {
self.reveal_table_cell();
self.table_cell_update_anchors();
self.reset_caret_blink(cx);
window.notify_text_selection_changed(&self.editor_focus);
@@ -711,6 +750,7 @@ impl PlaygroundView {
true
}
Some(None) => {
self.reveal_table_cell();
self.table_cell_update_anchors();
self.reset_caret_blink(cx);
window.notify_text_input_changed(&self.editor_focus);
@@ -611,6 +611,7 @@ impl PlaygroundView {
};
cell.input.select(pos..pos);
}
self.reveal_table_cell();
self.table_cell_update_anchors();
window.notify_text_selection_changed(&self.editor_focus);
cx.notify();
@@ -658,6 +659,7 @@ impl PlaygroundView {
cell.input.select(pos..pos);
cell.goal_x = goal_x;
}
self.reveal_table_cell();
self.table_cell_update_anchors();
window.notify_text_selection_changed(&self.editor_focus);
cx.notify();
@@ -703,7 +705,6 @@ impl PlaygroundView {
Some(window),
Some(cx),
);
self.suppress_unselected_root_input = false;
if target_editable {
let offset = if forward { 0 } else { target_len };
self.change_selection(
@@ -0,0 +1,113 @@
//! Pointer drag selection and horizontal/vertical viewport reveal for focused `affine:table` cells.
use ui::{Context, MouseButton, MouseMoveEvent, Window};
use super::TableCellDragMode;
use crate::{PlaygroundView, TOPBAR_HEIGHT, block_flow::page_geometry};
impl PlaygroundView {
/// Mark the active table cell to be revealed vertically on the next frame and immediately
/// scroll its wide table horizontally so the active cell and caret stay inside the viewport.
pub(crate) fn reveal_table_cell(&mut self) {
self.editor.reveal = true;
self.reveal_table_cell_horizontal();
}
/// Scroll a wide table sideways so the focused cell and its caret stay in view.
pub(crate) fn reveal_table_cell_horizontal(&mut self) {
let Some(cell) = self.table_cell.as_ref() else {
return;
};
let Some(layout) = self.flow_layout() else {
return;
};
let Some(block) = layout.block(&cell.block_id) else {
return;
};
let Some(code) = block.body.code_scroll else {
return;
};
let Some(hit) = block
.body
.table_cells
.iter()
.find(|c| c.row_id == cell.row_id && c.column_id == cell.column_id)
else {
return;
};
let (cx_local, _) = hit.text.caret(cell.input.focus());
let cell_left = hit.rect.x - code.area.x;
let cell_right = hit.rect.right() - code.area.x;
let caret_x = hit.text_origin.0 + cx_local - code.area.x;
self.overlays
.reveal_table_cell_x(&cell.block_id, cell_left, cell_right, caret_x, code);
}
/// Extend the active table cell's text selection while dragging with the primary button.
pub(crate) fn table_cell_mouse_move(
&mut self,
event: &MouseMoveEvent,
window: &mut Window,
cx: &mut Context<Self>,
) {
if event.pressed_button != Some(MouseButton::Left) {
if let Some(cell) = self.table_cell.as_mut() {
cell.dragging = false;
}
return;
}
let Some((block_id, row_id, column_id, drag_mode, text)) =
self.table_cell.as_ref().filter(|c| c.dragging).map(|c| {
(
c.block_id.clone(),
c.row_id.clone(),
c.column_id.clone(),
c.drag_mode,
c.input.text.clone(),
)
})
else {
return;
};
let Some(layout) = self.flow_layout() else {
return;
};
let Some((bx, by, hit)) =
Self::find_table_cell_hit(&layout, &block_id, &row_id, &column_id)
else {
return;
};
let geom = page_geometry(f32::from(window.viewport_size().width));
let local_x = f32::from(event.position.x) - geom.column_x - bx
+ self.overlays.code_scroll_x(&block_id);
let local_y = f32::from(event.position.y) - TOPBAR_HEIGHT + self.scroll_y - by;
let off = hit.hit_text(local_x, local_y, &text).utf16_offset as usize;
if let Some(cell) = self.table_cell.as_mut() {
match drag_mode {
TableCellDragMode::Character => {
cell.input.move_caret(off, true);
}
TableCellDragMode::Word(a_start, a_end) => {
let r = crate::editor_session::word_range(&text, off as u64);
let (f_start, f_end) = (r.start as usize, r.end as usize);
if f_start >= a_start {
cell.input.select(a_start..f_end);
} else {
cell.input.select(a_end..a_end);
cell.input.move_caret(f_start, true);
}
}
TableCellDragMode::All => {
let len = blocksuite_editor::inline_input::utf16_len(&text);
cell.input.select(0..len);
}
}
cell.goal_x = None;
}
self.reveal_table_cell();
self.table_cell_update_anchors();
self.reset_caret_blink(cx);
window.notify_text_selection_changed(&self.editor_focus);
cx.notify();
}
}