perf(edgeless): reduce scene and text lookup costs

Read canvas block flags when the scene collects them.
Read the text block and its children on blur.

Check live mindmap membership before a drag changes node positions.
Check group locks across all surfaces on the page.
Stop the drag at a locked branch.
This commit is contained in:
DarkSky committed 2026-12-02 11:00:19 +09:00
1 parent 5465a17d33
commit 2ecdd5a6ef
5 files changed
+591 -169

No files matched your search

@@ -93,22 +93,54 @@ impl PageDocSession {
/// Remove an empty frame in the same undo item as its last local deletion.
pub fn remove_empty_edgeless_text(&mut self, id: &str, now_ms: u64) -> DocResult<PageCommit> {
use crate::read::BlockContent;
let snap = self.read_page_snapshot()?;
let Some(block) = snap.block(id) else {
let Some(SessionReadValue::Map(block)) =
self.session.get_map_value(&self.blocks_target, id)?
else {
return Ok(None);
};
let last = self.text_deletion_time(block);
self.last_text_deletion = None;
let empty_paragraph = |child: &crate::read::BlockNode| {
child.children.is_empty()
&& matches!(&child.content, BlockContent::Paragraph { text, .. } if text.is_empty())
};
if !matches!(block.content, BlockContent::EdgelessText { .. })
|| !block.children.iter().all(empty_paragraph)
let flavour = self
.session
.get_map_value(&TypeTarget::Identity(block), "sys:flavour")?;
if !matches!(flavour, Some(SessionReadValue::Any(Any::String(name))) if name == "affine:edgeless-text")
{
self.last_text_deletion = None;
return Ok(None);
}
let children = self.unique_children(id)?;
let last = self.deletion_capture_for(children.iter().map(String::as_str));
self.last_text_deletion = None;
for child in children {
let Some(SessionReadValue::Map(block)) =
self.session.get_map_value(&self.blocks_target, &child)?
else {
continue;
};
let target = TypeTarget::Identity(block);
let flavour = self.session.get_map_value(&target, "sys:flavour")?;
if !matches!(flavour, Some(SessionReadValue::Any(Any::String(name))) if name == "affine:paragraph")
{
return Ok(None);
}
let empty = match self.session.get_map_value(&target, "prop:text")? {
Some(SessionReadValue::Text(text)) => crate::read::coalesce_delta(
self.session.read_text_delta(&TypeTarget::Identity(text))?,
)
.is_empty(),
Some(SessionReadValue::Any(Any::String(text))) => text.is_empty(),
_ => true,
};
if !empty {
return Ok(None);
}
for id in self.unique_children(&child)? {
if matches!(
self.session.get_map_value(&self.blocks_target, &id)?,
Some(SessionReadValue::Map(_))
) {
return Ok(None);
}
}
}
let time = last.unwrap_or(now_ms);
self.compound_edit(time, last.is_none(), true, |page| {
page.delete_blocks_and_elements_with_connectors(&[id], &[], time)?;
@@ -839,6 +871,34 @@ mod tests {
}
}
#[test]
fn nonempty_cleanup_consumes_capture_and_undo_restores_the_last_paragraph() {
let mut page = text_box();
page.insert_text("tail", "prop:text", 0, "X", 10).unwrap();
page.remove_text("line", "prop:text", 0, 2, 1_000).unwrap();
assert!(page.last_text_deletion.is_some());
assert!(
page.remove_empty_edgeless_text("box", 2_000)
.unwrap()
.is_none()
);
assert!(page.last_text_deletion.is_none());
page.remove_text("tail", "prop:text", 0, 1, 3_000).unwrap();
let before = page.read_page_snapshot().unwrap();
assert!(
page.remove_empty_edgeless_text("box", 4_000)
.unwrap()
.is_some()
);
assert!(page.read_page_snapshot().unwrap().block("box").is_none());
page.undo().unwrap().unwrap();
let restored = page.read_page_snapshot().unwrap();
assert!(restored.block("box").is_some());
assert_eq!(restored.block("line"), before.block("line"));
assert_ne!(restored.block("tail"), before.block("tail"));
}
#[test]
fn cleanup_preserves_whitespace_embed_nested_and_nontext_children() {
for case in ["space", "embed", "nested", "divider"] {
+15 -16
View File
@@ -57,6 +57,7 @@ pub fn prepare_edgeless_scene(
let mut notes = Vec::new();
let mut texts = Vec::new();
let mut surface_blocks = Vec::new();
let mut surface_block_flags = Vec::new();
// Preserve exact `sys:children` order across Frames, Notes, EdgelessTexts, and surface blocks
// when merging equal-index items into `Layers::merge`.
let mut spatial_order: Vec<(String, PaintItem)> = Vec::new();
@@ -64,7 +65,6 @@ pub fn prepare_edgeless_scene(
if let Some(root) = &input.snapshot.root {
let mut active_notes = Vec::new();
let mut active_texts = Vec::new();
let mut active_surface_blocks = Vec::new();
let mut next_page_order = 1usize;
for child in spatial_blocks(root) {
@@ -327,7 +327,11 @@ pub fn prepare_edgeless_scene(
.get(&child.id)
.map(|o| (o.rect, o.rotate_deg));
if let Some(sb) = prepare_surface_block(state, child, input, ov, window) {
active_surface_blocks.push(child.id.clone());
surface_block_flags.push((
child.id.as_str(),
prop_bool(child, "prop:lockedBySelf", false),
matches!(child.content, BlockContent::Image { .. }),
));
let idx = surface_blocks.len();
surface_blocks.push(sb);
spatial_order.push((child.id.clone(), PaintItem::SurfaceBlock(idx)));
@@ -343,10 +347,12 @@ pub fn prepare_edgeless_scene(
if state.text_flows.len() > active_texts.len() {
state.text_flows.retain(|id, _| active_texts.contains(id));
}
if state.surface_block_flows.len() > active_surface_blocks.len() {
state
.surface_block_flows
.retain(|id, _| active_surface_blocks.contains(id));
if state.surface_block_flows.len() > surface_block_flags.len() {
state.surface_block_flows.retain(|id, _| {
surface_block_flags
.iter()
.any(|(active, _, _)| *active == id)
});
}
super::scene_headers::apply_nested_frame_title_offsets(&mut frames, state.camera.zoom);
}
@@ -609,11 +615,8 @@ pub fn prepare_edgeless_scene(
}
PaintItem::SurfaceBlock(i) => {
let b = &surface_blocks[i];
if input
.snapshot
.block(&b.id)
.is_some_and(|n| matches!(n.content, BlockContent::Image { .. }))
{
let (_, locked, is_image) = surface_block_flags[i];
if is_image {
state.authoring.image_ids.insert(b.id.clone());
}
built_items.push(SpatialItemInfo {
@@ -631,11 +634,7 @@ pub fn prepare_edgeless_scene(
group_children: Vec::new(),
parent_group_id: resolve_outermost_group(&b.id),
title_pill_rect: None,
locked: input
.snapshot
.block(&b.id)
.is_some_and(|n| prop_bool(n, "prop:lockedBySelf", false))
|| has_locked_ancestor_group(&b.id),
locked: locked || has_locked_ancestor_group(&b.id),
in_mindmap: false,
});
}
@@ -1,6 +1,9 @@
//! Pointer-up gesture commit to `PageDocSession` (shapes, connectors, brushes, notes, frames, transforms).
use std::collections::BTreeSet;
use blocksuite_playground_doc::{
DocResult,
read::{BlockContent, SurfaceElementKind},
schema::{ConnectorEndpointSpec, SurfaceElementSpec, map_array_any},
session::PageDocSession,
@@ -9,17 +12,40 @@ use ui::{Context, MouseUpEvent, Window};
use y_octo::{Any, SessionValue};
use crate::{
PlaygroundView,
MindmapDrag, PlaygroundView,
editor_session::{DocPoint, DocumentSelection},
};
use super::{
EdgelessGesture, EdgelessInlineEdit, EdgelessTool, HandleKind, NOTE_MIN_WIDTH, SpatialItemKind,
WorldRect, compute_frame_membership_updates, constrain_shift_drag, constrain_shift_square,
mindmap_ops::{eligible_mindmap_drag_nodes, page_group_parents},
next_index_after, next_spatial_index, normalized_rect, resized_rect_constrained,
rotated_bounds,
};
fn mindmap_drag_exclusions<'a>(
page: &PageDocSession,
drags: &'a [MindmapDrag],
) -> DocResult<BTreeSet<&'a str>> {
let mut excluded = BTreeSet::new();
if drags.is_empty() {
return Ok(excluded);
}
let live = page.read_page_snapshot()?;
let group_parents = page_group_parents(&live);
for drag in drags {
let eligible = eligible_mindmap_drag_nodes(&live, &group_parents, drag).unwrap_or_default();
excluded.extend(
drag.members
.keys()
.map(String::as_str)
.filter(|id| !eligible.contains(id)),
);
}
Ok(excluded)
}
impl PlaygroundView {
pub(crate) fn on_edgeless_left_up(
&mut self,
@@ -31,6 +57,7 @@ impl PlaygroundView {
return;
};
self.edgeless.authoring.hover_cursor = None;
let mindmap_drags = std::mem::take(&mut self.mindmap_drags);
let stationary = std::mem::take(&mut self.edgeless.authoring.stationary_mindmap_nodes);
let now_ms = self.now_ms(cx) as u64;
match gesture {
@@ -56,7 +83,7 @@ impl PlaygroundView {
EdgelessGesture::DragSelection {
start_world,
current_world,
initial,
mut initial,
shift,
alt_clone,
pending_dblclick,
@@ -94,14 +121,17 @@ impl PlaygroundView {
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,
constrained_world,
);
let painted = self.edgeless.authoring.painted_items.clone();
let commit = self.page_mut().ok().and_then(|page| {
page.structural_edit(now_ms, move |page| {
let excluded = mindmap_drag_exclusions(page, &mindmap_drags)?;
initial.retain(|item| !excluded.contains(item.id.as_str()));
let frame_updates =
compute_frame_membership_updates(&painted, &initial, constrained_world);
for (surface, id, r, original) in &stationary {
if excluded.contains(id.as_str()) {
continue;
}
page.materialize_shape_position(
surface,
id,
@@ -765,3 +795,305 @@ impl PlaygroundView {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::edgeless::{
canvas_interaction_tests::{pointer, press, release},
edgeless_toolbar_tests::start_edgeless_toolbar_view,
find_surface_element,
group_ops::add_surface_group,
};
use blocksuite_playground_doc::{
read::PageSnapshot,
schema::{BlockSpec, MindmapNodeSpec},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PeerEdit {
LockChild,
RemoveChild,
LockOuterGroup,
GroupMindmap,
GroupRoot,
GroupChild,
GroupMindmapDuringBranchDrag,
CrossSurfaceGroup { locked: bool },
}
const NODES: [&str; 4] = ["mm-root", "mm-c1", "mm-c2", "mm-leaf"];
fn positions(snapshot: &PageSnapshot) -> [serde_json::Value; 4] {
NODES.map(|id| find_surface_element(snapshot, id).unwrap().1.props["xywh"].clone())
}
#[test]
fn mindmap_drag_commit_respects_live_membership_and_locks() {
use PeerEdit::*;
for (edit, moved) in [
(LockChild, [true, false, true, false]),
(RemoveChild, [true, false, true, false]),
(LockOuterGroup, [false; 4]),
(GroupMindmap, [false; 4]),
(GroupRoot, [false; 4]),
(GroupChild, [true, false, true, false]),
(GroupMindmapDuringBranchDrag, [false; 4]),
(CrossSurfaceGroup { locked: true }, [false; 4]),
(CrossSurfaceGroup { locked: false }, [true; 4]),
] {
let branch_drag = edit == GroupMindmapDuringBranchDrag;
let start_id = if branch_drag { "mm-c1" } else { "mm-root" };
let (_, app, win, hw) = start_edgeless_toolbar_view();
app.update(|cx| {
win.update(cx, |v, _, cx| {
let commit = v
.page_mut()
.unwrap()
.structural_edit(200, |page| {
page.add_surface_element(
"surf",
"mm-leaf",
"aA",
SurfaceElementSpec::Shape {
shape_type: "rect".into(),
xywh: "[890,475,140,48]".into(),
seed: 25,
filled: true,
text: Some("Leaf".into()),
},
200,
)?;
page.update_mindmap_children(
"surf",
"mm-1",
&[
(
"mm-root".into(),
MindmapNodeSpec {
index: "a0".into(),
parent: None,
collapsed: !branch_drag,
},
),
(
"mm-c1".into(),
MindmapNodeSpec {
index: "a1".into(),
parent: Some("mm-root".into()),
collapsed: branch_drag,
},
),
(
"mm-leaf".into(),
MindmapNodeSpec {
index: "a3".into(),
parent: Some("mm-c1".into()),
collapsed: false,
},
),
],
&[],
200,
)?;
if branch_drag {
for id in NODES {
page.set_surface_element_field(
"surf",
id,
"xywh",
SessionValue::Any(Any::String("[430,520,140,48]".into())),
200,
)?;
}
}
if edit == LockOuterGroup {
for (id, index, child) in
[("inner", "aB", "mm-1"), ("outer", "aC", "inner")]
{
add_surface_group(
page,
id.into(),
index,
26,
id.into(),
vec![child.into()],
false,
200,
)?;
}
}
if matches!(edit, CrossSurfaceGroup { .. }) {
page.add_block(
"surface-a",
BlockSpec::Surface,
Some("root"),
Some(0),
200,
)?;
let surface = add_surface_group(
page,
"outer".into(),
"aB",
28,
"Outer".into(),
vec!["mm-1".into()],
false,
200,
)?;
assert_eq!(surface, "surface-a");
}
Ok(())
})
.unwrap()
.unwrap();
v.did_edgeless_doc_commit(commit, cx);
})
})
.unwrap();
hw.request_frame();
let (before, end, mut peer) = app
.update(|cx| {
win.update(cx, |v, w, cx| {
let before = positions(v.page_snapshot().unwrap());
let painted = &v.edgeless.authoring.painted_items;
assert!(painted.iter().all(|item| item.id != "mm-leaf"), "{edit:?}");
let (x, y) = painted
.iter()
.find(|i| i.id == start_id)
.unwrap()
.rect
.center();
let start = pointer(v, w, (x, y));
let end = pointer(v, w, (x + 63., y + 37.));
v.on_edgeless_left_down(&press(start, 1), w, cx);
assert!(
matches!(
&v.edgeless.authoring.gesture,
Some(EdgelessGesture::DragSelection { initial, .. })
if initial.iter().any(|item| item.id == "mm-leaf")
),
"{edit:?}"
);
if branch_drag {
assert!(
v.edgeless
.authoring
.stationary_mindmap_nodes
.iter()
.any(|(_, id, _, _)| id == "mm-c2")
);
}
v.on_edgeless_pointer_move(
&ui::MouseMoveEvent {
position: end,
pressed_button: Some(ui::MouseButton::Left),
modifiers: Default::default(),
},
w,
cx,
);
let page = v.page_mut().unwrap();
let mut peer = PageDocSession::new(page.guid(), 33105).unwrap();
peer.apply_remote_update_v1(&page.encode_update_v1().unwrap())
.unwrap();
let remote = peer
.structural_edit(300, |page| {
match edit {
LockChild
| LockOuterGroup
| CrossSurfaceGroup { locked: true } => {
let surface = if matches!(edit, CrossSurfaceGroup { .. }) {
"surface-a"
} else {
"surf"
};
let id = if edit == LockChild { "mm-c1" } else { "outer" };
page.set_surface_element_field(
surface,
id,
"lockedBySelf",
SessionValue::Any(Any::True),
300,
)?;
}
CrossSurfaceGroup { locked: false } => {}
RemoveChild => {
page.update_mindmap_children(
"surf",
"mm-1",
&[],
&["mm-c1".into()],
300,
)?;
}
GroupMindmap
| GroupRoot
| GroupChild
| GroupMindmapDuringBranchDrag => {
let child = match edit {
GroupRoot => "mm-root",
GroupChild => "mm-c1",
_ => "mm-1",
};
add_surface_group(
page,
"peer-group".into(),
"aB",
27,
"Group".into(),
vec![child.into()],
true,
300,
)?;
}
}
Ok(())
})
.unwrap();
if let Some(remote) = remote {
page.apply_remote_update_v1(&remote.update).unwrap();
}
v.refresh_document();
(before, end, peer)
})
})
.unwrap();
hw.request_frame();
let after = app
.update(|cx| {
win.update(cx, |v, w, cx| {
if let CrossSurfaceGroup { locked } = edit {
let root = v
.edgeless
.authoring
.painted_items
.iter()
.find(|item| item.id == start_id)
.unwrap();
assert_eq!(root.surface_id.as_deref(), Some("surf"));
assert_eq!(root.locked, locked, "{edit:?}");
}
v.on_edgeless_left_up(&release(end), w, cx);
peer.apply_remote_update_v1(&v.page().unwrap().encode_update_v1().unwrap())
.unwrap();
positions(v.page_snapshot().unwrap())
})
})
.unwrap();
assert_eq!(
after,
positions(&peer.read_page_snapshot().unwrap()),
"{edit:?}"
);
for (index, id) in NODES.into_iter().enumerate() {
assert_eq!(
after[index] != before[index],
moved[index],
"{edit:?}: {id}"
);
}
}
}
}
@@ -1,14 +1,12 @@
//! MindMap node interaction & toolbar commands:
//! layout/style switching, node collapse/expand, `Tab` add child, `Enter` add sibling,
//! and atomic subtree deletion planning.
//! Mindmap node interactions and toolbar commands.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use blocksuite_editor::surface::{WorldBounds, compute_mindmap_layout};
use blocksuite_playground_doc::{
read::{
BlockContent, MindmapLayoutType, MindmapNodeDetail, MindmapStyle, PageSnapshot,
SurfaceElementKind, SurfaceMindmap, SurfaceShape,
SurfaceElement, SurfaceElementKind, SurfaceMindmap, SurfaceShape,
},
schema::{MindmapNodeSpec, SurfaceElementSpec},
session::PageDocSession,
@@ -16,7 +14,7 @@ use blocksuite_playground_doc::{
use ui::Context;
use y_octo::{Any, SessionValue};
use crate::PlaygroundView;
use crate::{MindmapDrag, PlaygroundView};
use super::{next_index_after, next_spatial_index};
@@ -35,7 +33,7 @@ struct FoundMindmap<'a> {
node_min_sizes: BTreeMap<String, (f64, f64)>,
}
/// Planned MindMap cascading deletions and surviving-tree relayouts for `edgeless_delete_ids`.
#[derive(Default)]
pub(super) struct MindmapDeletePlan {
/// Additional `(surface_id, element_id)` surface elements to delete (descendant shapes, or the
/// entire `mindmap` + all its shapes when the root node is deleted).
@@ -49,26 +47,97 @@ pub(super) struct MindmapDeletePlan {
pub relayout_xywh: Vec<(String, String, [f64; 4])>,
}
fn subtree_ids(mm: &SurfaceMindmap, mut nodes: BTreeSet<String>) -> BTreeSet<String> {
fn subtree_ids(
mm: &SurfaceMindmap,
mut nodes: BTreeSet<String>,
can_visit: impl Fn(&str) -> bool,
) -> BTreeSet<String> {
let mut by_parent = BTreeMap::<&str, Vec<&str>>::new();
for (id, detail) in &mm.nodes {
if let Some(parent) = detail.parent.as_deref() {
if let Some(parent) = detail.parent.as_deref().filter(|_| can_visit(id)) {
by_parent.entry(parent).or_default().push(id);
}
}
let mut pending: Vec<_> = nodes.iter().cloned().collect();
while let Some(id) = pending.pop() {
if let Some(children) = by_parent.get(id.as_str()) {
for &child in children {
if nodes.insert(child.to_owned()) {
pending.push(child.to_owned());
}
for &child in by_parent.get(id.as_str()).into_iter().flatten() {
if nodes.insert(child.to_owned()) {
pending.push(child.to_owned());
}
}
}
nodes
}
pub(super) fn page_group_parents(snapshot: &PageSnapshot) -> HashMap<&str, &SurfaceElement> {
let mut group_parents = HashMap::new();
for node in snapshot.root.iter().flat_map(|root| &root.children) {
let BlockContent::Surface { elements, .. } = &node.content else {
continue;
};
for group in elements {
if let SurfaceElementKind::Group { children, .. } = &group.kind {
group_parents.extend(children.iter().map(|id| (id.as_str(), group)));
}
}
}
group_parents
}
pub(super) fn eligible_mindmap_drag_nodes<'a>(
snapshot: &'a PageSnapshot,
group_parents: &HashMap<&str, &SurfaceElement>,
drag: &MindmapDrag,
) -> Option<BTreeSet<&'a str>> {
let surface = super::find_block(snapshot, &drag.surface_id)?;
let BlockContent::Surface { elements, .. } = &surface.content else {
return None;
};
let has_locked_ancestor_group = |id: &str| {
let mut visited = BTreeSet::new();
let mut parent = group_parents.get(id);
while let Some(group) = parent.filter(|g| visited.insert(g.id.as_str())) {
if group.locked_by_self {
return true;
}
parent = group_parents.get(group.id.as_str());
}
false
};
let map = elements.iter().find(|el| el.id == drag.mindmap_id)?;
if map.locked_by_self || has_locked_ancestor_group(&map.id) {
return None;
}
let SurfaceElementKind::Mindmap(mindmap) = &map.kind else {
return None;
};
let mut unlocked: BTreeSet<_> = elements
.iter()
.filter(|el| {
matches!(el.kind, SurfaceElementKind::Shape(_))
&& mindmap.nodes.contains_key(&el.id)
&& !el.locked_by_self
&& !has_locked_ancestor_group(&el.id)
})
.map(|el| el.id.as_str())
.collect();
let roots = drag
.roots
.iter()
.filter(|id| unlocked.contains(id.as_str()))
.cloned()
.collect();
let moving = subtree_ids(mindmap, roots, |id| unlocked.contains(id));
unlocked.retain(|id| {
!moving.is_empty()
&& drag
.members
.get(*id)
.is_some_and(|was_moving| !was_moving || moving.contains(*id))
});
Some(unlocked)
}
fn detail_to_spec(d: &MindmapNodeDetail) -> MindmapNodeSpec {
MindmapNodeSpec {
index: d.index.clone(),
@@ -119,7 +188,7 @@ fn mindmap_node_min_size(shape: &SurfaceShape) -> (f64, f64) {
}
fn collect_mindmap_geometry(
elements: &[blocksuite_playground_doc::read::SurfaceElement],
elements: &[SurfaceElement],
mm: &SurfaceMindmap,
) -> (BTreeMap<String, [f64; 4]>, BTreeMap<String, (f64, f64)>) {
let mut node_rects = BTreeMap::new();
@@ -135,39 +204,29 @@ fn collect_mindmap_geometry(
(node_rects, node_min_sizes)
}
/// When node origins still coincide on the wire, preserve the layout the user sees
/// before a drag gives the first node an explicit position.
/// Preserve the visible layout when node origins still coincide on the wire.
fn initial_drag_layout(
elements: &[blocksuite_playground_doc::read::SurfaceElement],
elements: &[SurfaceElement],
mm: &SurfaceMindmap,
painted: &[super::SpatialItemInfo],
visible: &HashMap<&str, super::WorldRect>,
) -> BTreeMap<String, super::WorldRect> {
let raw: BTreeMap<_, _> = elements
.iter()
.filter(|el| mm.nodes.contains_key(&el.id))
.filter_map(|el| {
if let SurfaceElementKind::Shape(shape) = &el.kind
&& mm.nodes.contains_key(&el.id)
{
Some((
el.id.clone(),
WorldBounds {
xywh: shape.xywh,
rotate: el.rotate,
},
))
} else {
None
}
let SurfaceElementKind::Shape(shape) = &el.kind else {
return None;
};
let bounds = WorldBounds {
xywh: shape.xywh,
rotate: el.rotate,
};
Some((el.id.clone(), bounds))
})
.collect();
if !blocksuite_editor::surface::mindmap::needs_auto_layout(mm, &raw) {
return BTreeMap::new();
}
let visible: BTreeMap<_, _> = painted
.iter()
.filter(|i| mm.nodes.contains_key(&i.id))
.map(|i| (i.id.as_str(), i.rect))
.collect();
let mut expanded = mm.clone();
for node in expanded.nodes.values_mut() {
node.collapsed = false;
@@ -195,8 +254,7 @@ fn find_mindmap_containing<'a>(
snapshot: &'a PageSnapshot,
node_id: &str,
) -> Option<FoundMindmap<'a>> {
let root = snapshot.root.as_ref()?;
for node in root.walk() {
for node in snapshot.root.as_ref()?.walk() {
let BlockContent::Surface { elements, .. } = &node.content else {
continue;
};
@@ -252,22 +310,13 @@ fn compute_relayout_xywh(
.collect()
}
/// Plan MindMap subtree cascade deletions, incremental `children` `Y.Map` removals, and
/// surviving-node relayouts for `deleting_surface_ids` (already filtered to unlocked items).
/// Plan subtree deletions and relayouts for unlocked items.
pub(super) fn plan_mindmap_deletes(
snapshot: &PageSnapshot,
deleting_surface_ids: &BTreeSet<String>,
) -> MindmapDeletePlan {
let mut plan = MindmapDeletePlan {
extra_surface_elements: Vec::new(),
refused_surface_elements: BTreeSet::new(),
mindmap_removals: Vec::new(),
relayout_xywh: Vec::new(),
};
let Some(root) = snapshot.root.as_ref() else {
return plan;
};
for node in root.walk() {
let mut plan = MindmapDeletePlan::default();
for node in snapshot.root.iter().flat_map(|root| root.walk()) {
let BlockContent::Surface { elements, .. } = &node.content else {
continue;
};
@@ -331,8 +380,7 @@ pub(super) fn plan_mindmap_deletes(
continue;
}
// Expand non-root deletions to all descendants in `mm.nodes`.
let cascade = subtree_ids(mm, hit_nodes.clone());
let cascade = subtree_ids(mm, hit_nodes.clone(), |_| true);
if cascade.iter().any(|nid| locked_ids.contains(nid.as_str())) {
plan.refused_surface_elements.extend(hit_nodes);
continue;
@@ -343,9 +391,11 @@ pub(super) fn plan_mindmap_deletes(
.push((node.id.clone(), nid.clone()));
}
}
let removed_list: Vec<String> = cascade.iter().cloned().collect();
plan.mindmap_removals
.push((node.id.clone(), el.id.clone(), removed_list));
plan.mindmap_removals.push((
node.id.clone(),
el.id.clone(),
cascade.iter().cloned().collect(),
));
let mut updated_mm = mm.clone();
updated_mm.nodes.retain(|nid, _| !cascade.contains(nid));
@@ -361,30 +411,27 @@ pub(super) fn plan_mindmap_deletes(
}
impl PlaygroundView {
/// Switch the layout direction (`Right` / `Left` / `Balance`) of the selected Mindmap.
fn selected_unlocked_mindmap(&self) -> Option<(&str, FoundMindmap<'_>)> {
if self.is_edgeless_write_readonly() {
return None;
}
let selected = self
.edgeless
.authoring
.single_selected()
.filter(|item| !item.locked)?;
let found = find_mindmap_containing(self.snapshot.as_deref()?, &selected.id)?;
(!found.mindmap_locked).then_some((&selected.id, found))
}
pub(crate) fn edgeless_set_mindmap_layout(
&mut self,
layout_type: MindmapLayoutType,
cx: &mut Context<Self>,
) -> bool {
if self.is_edgeless_write_readonly() {
return false;
}
let Some(selected) = self.edgeless.authoring.single_selected().cloned() else {
let Some((_, found)) = self.selected_unlocked_mindmap() else {
return false;
};
if selected.locked {
return false;
}
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let Some(found) = find_mindmap_containing(&snapshot, &selected.id) else {
return false;
};
if found.mindmap_locked {
return false;
}
let surface_id = found.surface_id.to_string();
let mindmap_id = found.mindmap_id.to_string();
let mut updated_mm = found.mindmap.clone();
@@ -422,30 +469,14 @@ impl PlaygroundView {
false
}
/// Switch the 4-preset visual style (`One`..`Four`) of the selected Mindmap.
pub(crate) fn edgeless_set_mindmap_style(
&mut self,
style: MindmapStyle,
cx: &mut Context<Self>,
) -> bool {
if self.is_edgeless_write_readonly() {
return false;
}
let Some(selected) = self.edgeless.authoring.single_selected().cloned() else {
let Some((_, found)) = self.selected_unlocked_mindmap() else {
return false;
};
if selected.locked {
return false;
}
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let Some(found) = find_mindmap_containing(&snapshot, &selected.id) else {
return false;
};
if found.mindmap_locked {
return false;
}
let surface_id = found.surface_id.to_string();
let mindmap_id = found.mindmap_id.to_string();
let now_ms = self.now_ms(cx) as u64;
@@ -473,13 +504,13 @@ impl PlaygroundView {
pub(super) fn collect_move_initials(&mut self) -> Vec<super::DragItemInitial> {
self.edgeless.authoring.stationary_mindmap_nodes.clear();
self.mindmap_drags.clear();
let mut items = self.collect_drag_initials();
if !self
.edgeless
.authoring
let authoring = &mut self.edgeless.authoring;
if !authoring
.painted_items
.iter()
.any(|item| item.in_mindmap && self.edgeless.authoring.selection.contains(&item.id))
.any(|item| item.in_mindmap && authoring.selection.contains(&item.id))
{
return items;
}
@@ -487,6 +518,12 @@ impl PlaygroundView {
return items;
};
let mut known: BTreeSet<_> = items.iter().map(|item| item.id.clone()).collect();
let visible: HashMap<_, _> = authoring
.painted_items
.iter()
.rev()
.map(|i| (i.id.as_str(), i.rect))
.collect();
for node in snapshot.root.iter().flat_map(|root| root.walk()) {
let BlockContent::Surface { elements, .. } = &node.content else {
continue;
@@ -504,7 +541,7 @@ impl PlaygroundView {
if roots.is_empty() {
continue;
}
let moving = subtree_ids(mm, roots);
let moving = subtree_ids(mm, roots.clone(), |_| true);
if el.locked_by_self
|| elements
.iter()
@@ -513,13 +550,12 @@ impl PlaygroundView {
items.retain(|n| !moving.contains(&n.id));
continue;
}
let layout =
initial_drag_layout(elements, mm, &self.edgeless.authoring.painted_items);
let layout = initial_drag_layout(elements, mm, &visible);
for el in elements {
if !moving.contains(&el.id)
&& let Some(rect) = layout.get(&el.id)
{
self.edgeless.authoring.stationary_mindmap_nodes.push((
authoring.stationary_mindmap_nodes.push((
node.id.clone(),
el.id.clone(),
*rect,
@@ -535,13 +571,9 @@ impl PlaygroundView {
continue;
}
let [x, y, w, h] = shape.xywh.map(|v| v as f32);
let rect = self
.edgeless
.authoring
.painted_items
.iter()
.find(|i| i.id == child.id)
.map(|i| i.rect)
let rect = visible
.get(child.id.as_str())
.copied()
.or_else(|| layout.get(&child.id).copied())
.unwrap_or(super::WorldRect::new(x, y, w, h));
items.push(super::DragItemInitial {
@@ -556,40 +588,33 @@ impl PlaygroundView {
connector_label_xywh: None,
});
}
self.mindmap_drags.push(MindmapDrag {
surface_id: node.id.clone(),
mindmap_id: el.id.clone(),
roots,
members: mm
.nodes
.keys()
.map(|id| (id.clone(), moving.contains(id)))
.collect(),
});
}
}
items
}
/// Toggle `collapsed` on the currently selected Mindmap node in one atomic undo step
/// using an incremental `Y.Map` entry update on `"children"`.
pub(crate) fn edgeless_toggle_mindmap_collapse(&mut self, cx: &mut Context<Self>) -> bool {
if self.is_edgeless_write_readonly() {
return false;
}
let Some(selected) = self.edgeless.authoring.single_selected().cloned() else {
let Some((selected, found)) = self.selected_unlocked_mindmap() else {
return false;
};
if selected.locked {
return false;
}
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let Some(found) = find_mindmap_containing(&snapshot, &selected.id) else {
return false;
};
if found.mindmap_locked {
return false;
}
let Some(existing) = found.mindmap.nodes.get(&selected.id) else {
let Some(existing) = found.mindmap.nodes.get(selected) else {
return false;
};
let mut updated = existing.clone();
updated.collapsed = !updated.collapsed;
let surface_id = found.surface_id.to_string();
let mindmap_id = found.mindmap_id.to_string();
let upserts = vec![(selected.id.clone(), detail_to_spec(&updated))];
let upserts = vec![(selected.to_owned(), detail_to_spec(&updated))];
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| {
@@ -607,31 +632,26 @@ impl PlaygroundView {
false
}
/// Add a Mindmap child (`add_child == true`, `Tab`) or sibling (`add_child == false`, `Enter`)
/// relative to the currently selected Mindmap node, relayouting the tree in one atomic undo step.
/// Add a child or sibling and lay out the tree in one undo step.
pub(crate) fn edgeless_add_mindmap_node(
&mut self,
add_child: bool,
cx: &mut Context<Self>,
) -> bool {
if self.is_edgeless_write_readonly() {
return false;
}
let Some(selected) = self.edgeless.authoring.single_selected().cloned() else {
return false;
};
if selected.locked {
if selected.locked || self.is_edgeless_write_readonly() {
return false;
}
let Some(snapshot) = self.snapshot.clone() else {
return false;
};
let Some(found) = find_mindmap_containing(&snapshot, &selected.id) else {
let Some(found) =
find_mindmap_containing(&snapshot, &selected.id).filter(|m| !m.mindmap_locked)
else {
return false;
};
if found.mindmap_locked {
return false;
}
let parent_id = if add_child {
selected.id.clone()
} else {
+11
View File
@@ -138,6 +138,15 @@ pub(crate) struct ImageResizeDrag {
pub via_touch: bool,
}
/// The mindmap branches and node roles captured when a drag starts.
#[derive(Clone)]
pub(crate) struct MindmapDrag {
surface_id: String,
mindmap_id: String,
roots: BTreeSet<String>,
members: BTreeMap<String, bool>,
}
pub(crate) use touch_interaction::{ModalTouchTarget, PopoverFlingTarget, TouchStrokeOwner};
/// Interactive GPUI root view for desktop, Web canvas, and headless verification sessions.
@@ -204,6 +213,7 @@ pub struct PlaygroundView {
pub(crate) edgeless_shape_picker_presence: Option<edgeless::ShapePickerPresence>,
pub(crate) edgeless_element_color_picker:
Option<(edgeless::ElementColorSlot, BTreeSet<String>)>,
pub(crate) mindmap_drags: Vec<MindmapDrag>,
pub(crate) pointer_kind: PointerKind,
pub(crate) form_factor: FormFactor,
pub(crate) page_readonly: bool,
@@ -384,6 +394,7 @@ impl PlaygroundView {
edgeless_camera_transition: None,
edgeless_shape_picker_presence: None,
edgeless_element_color_picker: None,
mindmap_drags: Vec::new(),
pointer_kind: options.pointer_kind,
form_factor: options.form_factor,
page_readonly: options.page_readonly,