From a3a7496b4c37bad35f5ecc98f3eff140a6e7e2d2 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Wed, 2 Dec 2026 19:16:25 +0900 Subject: [PATCH] perf(blocksuite): eliminate snapshot ID leaks and table/toolbar hot-path work Remove harness snapshot ID literals from production Wasm Section 11 across 36 prefixes. Extend `check-snapshot-prefixes.mjs` to lock those 36 prefixes and bare container IDs at zero. - Clip table grow preview to visible viewport rows and columns in one pass. - Defer page table cell focus label formatting behind lazy evaluation. - Compare derived four-state table edge zone on pointer hover to skip center redraws. - Reuse shared `toolbar_chrome` geometry constants and color tokens in edgeless chrome. - Replace multi-pass selection scans and `rotate().transform_point()` math with single passes. --- .../crates/editor/src/edgeless/brush_panel.rs | 29 +- .../element_toolbar/align_and_pickers.rs | 10 +- .../src/edgeless/element_toolbar/bar_items.rs | 66 +- .../edgeless/element_toolbar/color_popover.rs | 11 +- .../edgeless/element_toolbar/media_toolbar.rs | 24 +- .../src/edgeless/element_toolbar/mod.rs | 123 +++ .../src/edgeless/element_toolbar/more_menu.rs | 2 +- .../element_toolbar/note_style_panel.rs | 26 +- .../src/edgeless/element_toolbar/popovers.rs | 6 +- .../src/edgeless/element_toolbar/render.rs | 10 +- .../src/edgeless/element_toolbar/summary.rs | 424 ++++++---- .../edgeless/element_toolbar/typography.rs | 9 +- .../src/edgeless/element_toolbar/widgets.rs | 31 +- .../crates/editor/src/edgeless/overlay.rs | 80 +- .../editor/src/edgeless/quick_connect.rs | 72 +- .../crates/editor/src/edgeless/toolbar/mod.rs | 57 +- .../editor/src/edgeless/toolbar/zoom_bar.rs | 86 +- .../editor/src/overlays/bookmark_toolbar.rs | 2 +- .../editor/src/overlays/callout_bar/mod.rs | 2 +- .../editor/src/overlays/embed_toolbar.rs | 2 +- .../src/overlays/toolbar_chrome/hover.rs | 216 ++++- .../src/overlays/view_table_cell/paint.rs | 741 +++++++++++------- .../src/overlays/view_table_cell/toolbar.rs | 279 ++++--- .../tests/check-snapshot-prefixes.test.mjs | 24 + .../scripts/check-snapshot-prefixes.mjs | 18 +- 25 files changed, 1570 insertions(+), 780 deletions(-) diff --git a/blocksuite/crates/editor/src/edgeless/brush_panel.rs b/blocksuite/crates/editor/src/edgeless/brush_panel.rs index a5a5fff730..e8a571c68c 100644 --- a/blocksuite/crates/editor/src/edgeless/brush_panel.rs +++ b/blocksuite/crates/editor/src/edgeless/brush_panel.rs @@ -6,7 +6,10 @@ use ui::{ canvas, div, point, prelude::*, px, size, }; -use crate::theme::{Palette, PlaygroundTheme}; +use crate::{ + overlays::TOOLBAR_CHROME_BTN_RADIUS, + theme::{Palette, PlaygroundTheme}, +}; use super::toolbar::{ BRUSH_TOOL_SWATCH_SPECS, ChromeHoverTarget, EdgelessChromeMotionState, bind_chrome_button, @@ -108,12 +111,11 @@ pub(super) fn build_brush_panel( let display_color = color.opacity(swatch_alpha); let selected = active_color == token; let token_owned = token.to_string(); - let snap_id = SharedString::from(format!("chrome.edgeless_toolbar.brush_color.{name}")); let mut btn = div() .id(SharedString::from(format!("brush-swatch-{name}"))) .w(px(SWATCH)) .h(px(SWATCH)) - .rounded(px(4.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) .flex() .items_center() .justify_center() @@ -124,7 +126,10 @@ pub(super) fn build_brush_panel( 0.16 })) }) - .snapshot(snap_id, Some("chrome.edgeless_toolbar.brush_panel")) + .snapshot( + format_args!("chrome.edgeless_toolbar.brush_color.{name}"), + Some("chrome.edgeless_toolbar.brush_panel"), + ) .child( canvas( |_, _, _| (), @@ -176,15 +181,12 @@ pub(super) fn build_brush_panel( for (idx, &w_val) in widths.iter().enumerate() { let selected = (active_width - w_val).abs() < 0.5; let dot_px = (4.0 + idx as f32 * 2.5).min(14.0); - let snap_id = SharedString::from(format!( - "chrome.edgeless_toolbar.brush_width.{}", - w_val as i32 - )); + let width_px = w_val as i32; let mut btn = div() - .id(SharedString::from(format!("brush-width-{}", w_val as i32))) + .id(SharedString::from(format!("brush-width-{width_px}"))) .w(px(SWATCH)) .h(px(SWATCH)) - .rounded(px(4.0)) + .rounded(px(TOOLBAR_CHROME_BTN_RADIUS)) .flex() .items_center() .justify_center() @@ -195,8 +197,11 @@ pub(super) fn build_brush_panel( 0.16 })) }) - .snapshot(snap_id, Some("chrome.edgeless_toolbar.brush_panel")) - .snapshot_text(format!("{}px", w_val as i32)) + .snapshot( + format_args!("chrome.edgeless_toolbar.brush_width.{width_px}"), + Some("chrome.edgeless_toolbar.brush_panel"), + ) + .snapshot_text(format_args!("{width_px}px")) .child( canvas( |_, _, _| (), diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/align_and_pickers.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/align_and_pickers.rs index fa9da90bc8..9a6e696bac 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/align_and_pickers.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/align_and_pickers.rs @@ -106,10 +106,10 @@ pub(super) fn build_line_width_panel( ); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.lw_{w_int}")), + format_args!("chrome.edgeless_element_toolbar.sub.lw_{w_int}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) - .snapshot_text(format!("{w_int}px")) + .snapshot_text(format_args!("{w_int}px")) .child( canvas( |_, _, _| (), @@ -258,10 +258,10 @@ pub(super) fn build_font_size_dropdown( ); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.fs_{fs_int}")), + format_args!("chrome.edgeless_element_toolbar.sub.fs_{fs_int}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) - .snapshot_text(label.clone()) + .snapshot_text(&label) .child(div().flex_1().child(label)) .child(if active { "\u{2713}" } else { "" }), ); @@ -377,7 +377,7 @@ pub(super) fn build_align_grid_popover( .font_weight(FontWeight::SEMIBOLD) .text_color(fg) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.{id}")), + format_args!("chrome.edgeless_element_toolbar.sub.{id}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) .snapshot_text(tip) diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs index 00d4138848..c79e4c44e3 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/bar_items.rs @@ -67,7 +67,7 @@ pub(super) fn append_per_type_items( .child(text_action_btn( "el-tb-rename", "chrome.edgeless_element_toolbar.rename", - "Rename".to_string(), + "Rename", 54.0, false, false, @@ -79,7 +79,7 @@ pub(super) fn append_per_type_items( .child(text_action_btn( "el-tb-insert-page", "chrome.edgeless_element_toolbar.insert_page", - "To Page".to_string(), + "To Page", 64.0, false, false, @@ -91,7 +91,7 @@ pub(super) fn append_per_type_items( .child(text_action_btn( "el-tb-ungroup", "chrome.edgeless_element_toolbar.ungroup", - "Ungroup".to_string(), + "Ungroup", 58.0, false, false, @@ -108,7 +108,7 @@ pub(super) fn append_per_type_items( .child(text_action_btn( "el-tb-insert-group-page", "chrome.edgeless_element_toolbar.insert_page", - "To Page".to_string(), + "To Page", 64.0, false, false, @@ -120,7 +120,7 @@ pub(super) fn append_per_type_items( .child(text_action_btn( "el-tb-rename", "chrome.edgeless_element_toolbar.rename", - "Rename".to_string(), + "Rename", 54.0, false, false, @@ -132,7 +132,7 @@ pub(super) fn append_per_type_items( .child(text_action_btn( "el-tb-ungroup", "chrome.edgeless_element_toolbar.ungroup", - "Ungroup".to_string(), + "Ungroup", 58.0, false, false, @@ -161,7 +161,7 @@ pub(super) fn append_per_type_items( bar = bar.child(text_action_btn( "el-tb-mm-layout", "chrome.edgeless_element_toolbar.mindmap_layout", - "Layout".to_string(), + "Layout", 62.0, open_sub == Some(ElementSubMenu::MindmapLayout), true, @@ -175,7 +175,7 @@ pub(super) fn append_per_type_items( bar = bar.child(text_action_btn( "el-tb-mm-fold", "chrome.edgeless_element_toolbar.mindmap_collapse", - if mm.collapsed { "Expand" } else { "Fold" }.to_string(), + if mm.collapsed { "Expand" } else { "Fold" }, 54.0, mm.collapsed, false, @@ -345,7 +345,7 @@ pub(super) fn append_per_type_items( bar = bar.child(text_action_btn( "el-tb-conn-caps", "chrome.edgeless_element_toolbar.connector_caps", - "Caps".to_string(), + "Caps", 48.0, open_sub == Some(ElementSubMenu::ConnectorCaps), true, @@ -384,11 +384,10 @@ pub(super) fn append_per_type_items( if let Some(style) = &summary.typography { let [family_width, weight_width] = font_trigger_widths(compact); - for (menu, id, snapshot_id, label, tooltip, icon, width) in [ + for (menu, id, label, tooltip, icon, width) in [ ( ElementSubMenu::FontFamily, "el-tb-font-family", - "chrome.edgeless_element_toolbar.font_family", style.family, "Font family", "TextIcon", @@ -397,7 +396,6 @@ pub(super) fn append_per_type_items( ( ElementSubMenu::FontWeight, "el-tb-font-weight", - "chrome.edgeless_element_toolbar.font_weight", style.weight, "Font weight", "BoldIcon", @@ -407,10 +405,10 @@ pub(super) fn append_per_type_items( let action = EdgelessElementAction::ToggleSubMenu(menu); let active = open_sub == Some(menu); sub_triggers.push((menu, cursor.place(width))); - bar = bar.child(if compact { - icon_action_btn( + bar = bar.child(match (compact, menu) { + (true, ElementSubMenu::FontFamily) => icon_action_btn( id, - snapshot_id, + "chrome.edgeless_element_toolbar.font_family", tooltip, icon, active, @@ -418,12 +416,22 @@ pub(super) fn append_per_type_items( palette, action, cx, - ) - } else { - text_action_btn( + ), + (true, _) => icon_action_btn( id, - snapshot_id, - label.to_string(), + "chrome.edgeless_element_toolbar.font_weight", + tooltip, + icon, + active, + show_tooltips, + palette, + action, + cx, + ), + (false, ElementSubMenu::FontFamily) => text_action_btn( + id, + "chrome.edgeless_element_toolbar.font_family", + label, width, active, true, @@ -431,7 +439,19 @@ pub(super) fn append_per_type_items( palette, action, cx, - ) + ), + (false, _) => text_action_btn( + id, + "chrome.edgeless_element_toolbar.font_weight", + label, + width, + active, + true, + show_tooltips, + palette, + action, + cx, + ), }); } cursor.place(BTN_SIZE); @@ -486,7 +506,7 @@ pub(super) fn append_per_type_items( bar = bar.child(text_action_btn( "el-tb-note-style", "chrome.edgeless_element_toolbar.note_style", - "Style".to_string(), + "Style", 56.0, style_open, true, @@ -521,7 +541,7 @@ pub(super) fn append_per_type_items( bar = bar.child(text_action_btn( "el-tb-note-display", "chrome.edgeless_element_toolbar.note_display", - label.to_string(), + label, 96.0, summary.note_in_page, false, diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs index 86195793b7..ca3c802790 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/color_popover.rs @@ -115,10 +115,6 @@ pub(super) fn build_color_picker_pill( let ignore_alpha = slot == ElementColorSlot::Stroke && summary.is_highlighter_width; let selected = color_value_matches_swatch(current_val, swatch, theme, ignore_alpha); let wire_val = swatch.to_color_value(); - let snap_id = SharedString::from(format!( - "chrome.edgeless_element_toolbar.color.{slot_tag}.{}", - swatch.key - )); let el_id = SharedString::from(format!("el-tb-swatch-{slot_tag}-{}", swatch.key)); let swatch_bg = if is_transparent { ui::Rgba { @@ -155,7 +151,10 @@ pub(super) fn build_color_picker_pill( ); })) .snapshot( - snap_id, + format_args!( + "chrome.edgeless_element_toolbar.color.{slot_tag}.{}", + swatch.key + ), Some("chrome.edgeless_element_toolbar.color_picker"), ) .child( @@ -299,7 +298,7 @@ pub(super) fn build_color_picker_pill( "chrome.edgeless_element_toolbar.custom_color_input", Some("chrome.edgeless_element_toolbar.color_picker"), ) - .snapshot_text(display_hex.clone()) + .snapshot_text(&display_hex) .child(display_hex), ) .child( diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs index c8f73ef9b4..49a2d03315 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/media_toolbar.rs @@ -170,7 +170,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-caption", "chrome.edgeless_element_toolbar.media_caption", - "Caption".to_string(), + "Caption", 56.0, !sb.caption.is_empty(), false, @@ -229,7 +229,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-view", "chrome.edgeless_element_toolbar.media_view", - view_label.to_string(), + view_label, 68.0, sb.is_embed_view, false, @@ -243,7 +243,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-style", "chrome.edgeless_element_toolbar.media_style", - "Style".to_string(), + "Style", 62.0, open_sub == Some(ElementSubMenu::MediaStyle), true, @@ -257,7 +257,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-caption", "chrome.edgeless_element_toolbar.media_caption", - "Caption".to_string(), + "Caption", 56.0, !sb.caption.is_empty(), false, @@ -287,7 +287,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-open", "chrome.edgeless_element_toolbar.media_open", - "Open".to_string(), + "Open", 64.0, false, false, @@ -316,7 +316,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-view", "chrome.edgeless_element_toolbar.media_view", - view_label.to_string(), + view_label, 68.0, sb.is_embed_view, false, @@ -331,7 +331,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-style", "chrome.edgeless_element_toolbar.media_style", - "Style".to_string(), + "Style", 62.0, open_sub == Some(ElementSubMenu::MediaStyle), true, @@ -345,7 +345,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-caption", "chrome.edgeless_element_toolbar.media_caption", - "Caption".to_string(), + "Caption", 56.0, !sb.caption.is_empty(), false, @@ -362,7 +362,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-open", "chrome.edgeless_element_toolbar.media_open", - "Open".to_string(), + "Open", 58.0, false, false, @@ -390,7 +390,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-view", "chrome.edgeless_element_toolbar.media_view", - view_label.to_string(), + view_label, 68.0, sb.is_embed_view, false, @@ -404,7 +404,7 @@ pub(super) fn append_media_toolbar_items( bar = bar.child(text_action_btn( "el-tb-media-caption", "chrome.edgeless_element_toolbar.media_caption", - "Caption".to_string(), + "Caption", 56.0, !sb.caption.is_empty(), false, @@ -505,7 +505,7 @@ pub(super) fn build_media_style_menu( ); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.style_{key}")), + format_args!("chrome.edgeless_element_toolbar.sub.style_{key}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) .snapshot_text(label) diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/mod.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/mod.rs index 094bb07df0..fcb651927c 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/mod.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/mod.rs @@ -299,3 +299,126 @@ pub struct ElementToolbarSummary { pub note_auto_height: bool, pub note_scale: f32, } + +pub(super) fn find_mindmap_for_node( + snapshot: &blocksuite_playground_doc::read::PageSnapshot, + node_id: &str, +) -> Option { + use blocksuite_playground_doc::read::{BlockContent, SurfaceElementKind}; + let root = snapshot.root.as_ref()?; + for node in root.walk() { + let BlockContent::Surface { elements, .. } = &node.content else { + continue; + }; + for el in elements { + let SurfaceElementKind::Mindmap(mm) = &el.kind else { + continue; + }; + if let Some(detail) = mm.nodes.get(node_id) { + return Some(MindmapToolbarSummary { + mindmap_id: el.id.clone(), + node_id: node_id.to_string(), + layout_type: mm.layout_type, + style: mm.style, + is_root: detail + .parent + .as_deref() + .is_none_or(|p| !mm.nodes.contains_key(p)), + has_children: mm + .nodes + .values() + .any(|d| d.parent.as_deref() == Some(node_id)), + collapsed: detail.collapsed, + }); + } + } + } + None +} + +pub(super) fn resolve_multi_targets<'a>( + snapshot: &'a blocksuite_playground_doc::read::PageSnapshot, + items: &[&SpatialItemInfo], +) -> ( + Vec>, + Vec>, +) { + use blocksuite_playground_doc::read::{BlockContent, BlockNode}; + let (mut blocks, mut surface_els) = (vec![None; items.len()], vec![None; items.len()]); + let (mut block_idx, mut surface_idx) = ( + std::collections::HashMap::new(), + std::collections::HashMap::new(), + ); + for (i, item) in items.iter().enumerate() { + let map = if item.kind.is_block() { + &mut block_idx + } else { + &mut surface_idx + }; + map.insert(item.id.as_str(), i); + } + let (mut rem_blocks, mut rem_surface) = (block_idx.len(), surface_idx.len()); + for node in snapshot.root.iter().flat_map(BlockNode::walk) { + if rem_blocks > 0 + && let Some(&i) = block_idx.get(node.id.as_str()) + && blocks[i].is_none() + { + blocks[i] = Some(node); + rem_blocks -= 1; + } + if rem_surface > 0 + && let BlockContent::Surface { elements, .. } = &node.content + { + for el in elements { + if let Some(&i) = surface_idx.get(el.id.as_str()) + && surface_els[i].is_none() + { + surface_els[i] = Some(el); + rem_surface -= 1; + if rem_surface == 0 { + break; + } + } + } + } + if rem_blocks == 0 && rem_surface == 0 { + return (blocks, surface_els); + } + } + if rem_blocks > 0 { + for node in snapshot.detached.iter().flat_map(BlockNode::walk) { + if let Some(&i) = block_idx.get(node.id.as_str()) + && blocks[i].is_none() + { + blocks[i] = Some(node); + rem_blocks -= 1; + if rem_blocks == 0 { + break; + } + } + } + } + (blocks, surface_els) +} + +pub(super) fn take_first_color_val( + got: &mut bool, + out_rgba: &mut Option, + out_val: &mut Option, + theme: crate::theme::PlaygroundTheme, + val: &ColorValue, + override_val: Option, + opaque_alpha: bool, +) { + if *got { + return; + } + if let Some(mut c) = theme.resolve_color_value(val) { + if opaque_alpha && c.a > 0.0 { + c.a = 1.0; + } + *out_rgba = Some(c); + } + *out_val = Some(override_val.unwrap_or_else(|| val.clone())); + *got = true; +} diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/more_menu.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/more_menu.rs index 53210c4d47..d4b8abbc92 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/more_menu.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/more_menu.rs @@ -310,7 +310,7 @@ pub(super) fn build_more_menu( this.edgeless_element_action(action.clone(), window, cx); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.more.{}", item.id)), + format_args!("chrome.edgeless_element_toolbar.more.{}", item.id), Some("chrome.edgeless_element_toolbar.more_menu"), ) .snapshot_text(item.label) diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs index 06fcc4d47e..adad29d28e 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/note_style_panel.rs @@ -124,10 +124,10 @@ pub(super) fn build_note_style_panel( ); })) .snapshot( - SharedString::from(format!( + format_args!( "chrome.edgeless_element_toolbar.note_style.bg.{}", swatch.key - )), + ), Some("chrome.edgeless_element_toolbar.note_style_panel"), ) .snapshot_text(swatch.key) @@ -215,9 +215,7 @@ pub(super) fn build_note_style_panel( ); })) .snapshot( - SharedString::from(format!( - "chrome.edgeless_element_toolbar.note_style.shadow.{id}" - )), + format_args!("chrome.edgeless_element_toolbar.note_style.shadow.{id}"), Some("chrome.edgeless_element_toolbar.note_style_panel"), ) .snapshot_text(label) @@ -263,9 +261,7 @@ pub(super) fn build_note_style_panel( ); })) .snapshot( - SharedString::from(format!( - "chrome.edgeless_element_toolbar.note_style.border.{id}" - )), + format_args!("chrome.edgeless_element_toolbar.note_style.border.{id}"), Some("chrome.edgeless_element_toolbar.note_style_panel"), ) .snapshot_text(label) @@ -307,12 +303,10 @@ pub(super) fn build_note_style_panel( ); })) .snapshot( - SharedString::from(format!( - "chrome.edgeless_element_toolbar.note_style.border_size.{bs_i}" - )), + format_args!("chrome.edgeless_element_toolbar.note_style.border_size.{bs_i}"), Some("chrome.edgeless_element_toolbar.note_style_panel"), ) - .snapshot_text(format!("{bs_i}px")) + .snapshot_text(format_args!("{bs_i}px")) .child(format!("{bs_i}px")), ); } @@ -352,9 +346,7 @@ pub(super) fn build_note_style_panel( ); })) .snapshot( - SharedString::from(format!( - "chrome.edgeless_element_toolbar.note_style.radius.{rad_i}" - )), + format_args!("chrome.edgeless_element_toolbar.note_style.radius.{rad_i}"), Some("chrome.edgeless_element_toolbar.note_style_panel"), ) .snapshot_text(label) @@ -501,10 +493,10 @@ pub(super) fn build_scale_dropdown( this.edgeless_element_action(action.clone(), window, cx); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.scale_{pct}")), + format_args!("chrome.edgeless_element_toolbar.sub.scale_{pct}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) - .snapshot_text(label.clone()) + .snapshot_text(&label) .child(div().flex_1().child(label)) .child(if active { "\u{2713}" } else { "" }), ); diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/popovers.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/popovers.rs index e2259a687d..2e216f5975 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/popovers.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/popovers.rs @@ -170,7 +170,7 @@ fn build_icon_strip_menu( this.edgeless_element_action(action.clone(), window, cx); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.{id}")), + format_args!("chrome.edgeless_element_toolbar.sub.{id}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) .snapshot_text(label) @@ -439,7 +439,7 @@ pub(super) fn build_sub_menu_pill( ); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.ta_{id}")), + format_args!("chrome.edgeless_element_toolbar.sub.ta_{id}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) .snapshot_text(label) @@ -624,7 +624,7 @@ fn build_text_chip_submenu( this.edgeless_element_action(action.clone(), window, cx); })) .snapshot( - SharedString::from(format!("chrome.edgeless_element_toolbar.sub.{id}")), + format_args!("chrome.edgeless_element_toolbar.sub.{id}"), Some("chrome.edgeless_element_toolbar.sub_menu"), ) .snapshot_text(label) diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs index cf4742d176..20d76db212 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/render.rs @@ -182,7 +182,7 @@ pub fn build_edgeless_element_toolbar( .child(text_action_btn( "el-tb-unlock", "chrome.edgeless_element_toolbar.unlock", - "Click to unlock".to_string(), + "Click to unlock", 118.0, false, false, @@ -396,7 +396,7 @@ pub fn build_edgeless_element_toolbar( bar = bar.child(text_action_btn( "el-tb-release-group", "chrome.edgeless_element_toolbar.release_from_group", - "Release".to_string(), + "Release", 64.0, false, false, @@ -411,7 +411,7 @@ pub fn build_edgeless_element_toolbar( bar = bar.child(text_action_btn( "el-tb-wrap-frame", "chrome.edgeless_element_toolbar.frame", - "Frame".to_string(), + "Frame", 52.0, false, false, @@ -426,7 +426,7 @@ pub fn build_edgeless_element_toolbar( bar = bar.child(text_action_btn( "el-tb-group", "chrome.edgeless_element_toolbar.group", - "Group".to_string(), + "Group", 52.0, false, false, @@ -441,7 +441,7 @@ pub fn build_edgeless_element_toolbar( bar = bar.child(text_action_btn( "el-tb-align", "chrome.edgeless_element_toolbar.align", - "Align".to_string(), + "Align", 58.0, open_sub == Some(ElementSubMenu::Align), true, diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs index 1587be1ffd..93ce6af0b3 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use blocksuite_playground_doc::read::{ BlockContent, ColorValue, ConnectorMode, EndpointStyle, NoteDisplayMode, PageSnapshot, ShapeStyle, ShapeType, StrokeStyle, SurfaceElementKind, TextAlign, @@ -6,10 +8,11 @@ use blocksuite_playground_doc::read::{ use crate::theme::{Palette, PlaygroundTheme}; use super::{ - EdgelessAuthoringState, ElementToolbarSummary, MindmapToolbarSummary, ShapePreset, - SpatialItemInfo, SpatialItemKind, SurfaceBlockToolbarSummary, WorldRect, json_to_color_value, + EdgelessAuthoringState, ElementToolbarSummary, ShapePreset, SpatialItemInfo, SpatialItemKind, + SurfaceBlockToolbarSummary, WorldRect, find_mindmap_for_node, json_to_color_value, note_border_radius, note_border_style, note_collapse, note_scale, note_shadow_type, parse_xywh, - prop_bool, prop_f32, resolve_edgeless_color, typography::ElementTypography, + prop_bool, prop_f32, resolve_edgeless_color, resolve_multi_targets, take_first_color_val, + typography::ElementTypography, }; fn resolve_endpoint_world_point( @@ -76,10 +79,21 @@ pub fn sync_selection_from_snapshot( if authoring.selection.is_empty() { return; } + let painted_ids: Option> = + (authoring.selection.len() > 4 && authoring.painted_items.len() > 4).then(|| { + authoring + .painted_items + .iter() + .map(|p| p.id.as_str()) + .collect() + }); let missing: Vec = authoring .selection .iter() - .filter(|id| !authoring.painted_items.iter().any(|p| p.id == **id)) + .filter(|id| match &painted_ids { + Some(set) => !set.contains(id.as_str()), + None => !authoring.painted_items.iter().any(|p| p.id == **id), + }) .cloned() .collect(); if missing.is_empty() { @@ -209,40 +223,6 @@ fn shape_preset_from_read(shape_type: ShapeType, radius: f64) -> ShapePreset { } } -fn find_mindmap_for_node(snapshot: &PageSnapshot, node_id: &str) -> Option { - let root = snapshot.root.as_ref()?; - for node in root.walk() { - let BlockContent::Surface { elements, .. } = &node.content else { - continue; - }; - for el in elements { - let SurfaceElementKind::Mindmap(mm) = &el.kind else { - continue; - }; - if let Some(detail) = mm.nodes.get(node_id) { - let is_root = detail - .parent - .as_deref() - .is_none_or(|p| !mm.nodes.contains_key(p)); - let has_children = mm - .nodes - .values() - .any(|d| d.parent.as_deref() == Some(node_id)); - return Some(MindmapToolbarSummary { - mindmap_id: el.id.clone(), - node_id: node_id.to_string(), - layout_type: mm.layout_type, - style: mm.style, - is_root, - has_children, - collapsed: detail.collapsed, - }); - } - } - } - None -} - /// Inspect the current Edgeless selection and summarize which toolbar controls apply. pub fn summarize_element_toolbar( snapshot: &PageSnapshot, @@ -254,14 +234,26 @@ pub fn summarize_element_toolbar( if authoring.selection.is_empty() { return None; } - let selected_items: Vec<_> = authoring - .painted_items - .iter() - .filter(|i| authoring.selection.contains(&i.id)) - .collect(); - if selected_items.is_empty() { - return None; - } + let single_slot; + let multi_items: Vec<&SpatialItemInfo>; + let selected_items: &[&SpatialItemInfo] = if authoring.selection.len() == 1 { + let item = authoring + .painted_items + .iter() + .find(|i| authoring.selection.contains(&i.id))?; + single_slot = [item]; + &single_slot + } else { + multi_items = authoring + .painted_items + .iter() + .filter(|i| authoring.selection.contains(&i.id)) + .collect(); + if multi_items.is_empty() { + return None; + } + &multi_items + }; let selected_count = selected_items.len(); let mut is_locked = false; @@ -292,7 +284,9 @@ pub fn summarize_element_toolbar( let has_shape_grip = single.is_some_and(|i| i.kind == SpatialItemKind::Shape); let has_frame_actions = single.is_some_and(|i| i.kind == SpatialItemKind::Frame); let has_group_actions = single.is_some_and(|i| i.kind == SpatialItemKind::Group); - let mindmap = single.and_then(|i| find_mindmap_for_node(snapshot, &i.id)); + let mindmap = single + .filter(|i| i.in_mindmap) + .and_then(|i| find_mindmap_for_node(snapshot, &i.id)); let mut typography = None; let mut can_copy_markdown = false; let mut surface_block: Option = None; @@ -319,19 +313,12 @@ pub fn summarize_element_toolbar( let mut has_non_note_fill = false; let mut is_shape_text = false; - let mut fill_color = theme - .css_color("--affine-palette-shape-yellow") - .unwrap_or(palette.brand); - let mut stroke_color = theme - .css_color("--affine-v2-edgeless-palette-black") - .unwrap_or(palette.text_primary); - let mut text_color = palette.text_primary; - let mut fill_color_value = ColorValue::Single("#fcd34d".into()); - let mut stroke_color_value = ColorValue::Themed { - light: "#000000".into(), - dark: "#ffffff".into(), - }; - let mut text_color_value = ColorValue::Single("#000000".into()); + let mut fill_color = None; + let mut stroke_color = None; + let mut text_color = None; + let mut fill_color_value = None; + let mut stroke_color_value = None; + let mut text_color_value = None; let mut text_align = TextAlign::Center; let mut stroke_style = StrokeStyle::Solid; let mut stroke_width = 2.0; @@ -342,26 +329,13 @@ pub fn summarize_element_toolbar( let mut front_endpoint = EndpointStyle::None; let mut rear_endpoint = EndpointStyle::Arrow; let mut note_in_page = false; - let mut note_shadow = "--affine-note-shadow-box".to_string(); + let mut note_shadow: Option = None; let mut note_border_style_val = StrokeStyle::None; let mut note_border_size_val = 4.0_f64; let mut note_border_radius_val = 8.0_f64; let mut note_auto_height = true; let mut note_scale_val = 1.0_f32; - - let primary_page_note_id: Option<&str> = snapshot.root.as_ref().and_then(|root| { - let mut page_notes = root - .children - .iter() - .filter(|c| c.is_page_visible_note()) - .map(|c| c.id.as_str()); - let first = page_notes.next()?; - if page_notes.next().is_none() { - Some(first) - } else { - None - } - }); + let mut primary_page_note_cache: Option> = None; let mut got_fill = false; let mut got_stroke = false; @@ -375,7 +349,10 @@ pub fn summarize_element_toolbar( let mut got_note_mode = false; let mut got_note_shadow = false; - for item in &selected_items { + let multi_targets = + (selected_count > 1).then(|| resolve_multi_targets(snapshot, selected_items)); + + for (idx, item) in selected_items.iter().enumerate() { if item.locked { is_locked = true; } @@ -424,6 +401,17 @@ pub fn summarize_element_toolbar( has_fill = true; has_note_fill = true; has_note_shadow = true; + let primary_page_note_id = *primary_page_note_cache.get_or_insert_with(|| { + snapshot.root.as_ref().and_then(|root| { + let mut page_notes = root + .children + .iter() + .filter(|c| c.is_page_visible_note()) + .map(|c| c.id.as_str()); + let first = page_notes.next()?; + page_notes.next().is_none().then_some(first) + }) + }); if primary_page_note_id == Some(item.id.as_str()) { note_is_page_root = true; } else { @@ -441,7 +429,11 @@ pub fn summarize_element_toolbar( continue; }; if item.kind.is_block() { - if let Some(node) = snapshot.block(&item.id) { + let block_node = match &multi_targets { + Some((blocks, _)) => blocks[idx], + None => snapshot.block(&item.id), + }; + if let Some(node) = block_node { if super::prop_bool(node, "prop:lockedBySelf", false) { is_locked = true; } @@ -450,10 +442,10 @@ pub fn summarize_element_toolbar( && let Some(bg) = node.props.get("prop:background") { if let Some(c) = resolve_edgeless_color(bg, theme) { - fill_color = c; + fill_color = Some(c); } if let Some(cv) = json_to_color_value(bg) { - fill_color_value = cv; + fill_color_value = Some(cv); } got_fill = true; } @@ -470,7 +462,7 @@ pub fn summarize_element_toolbar( got_note_mode = true; } if !got_note_shadow { - note_shadow = note_shadow_type(node).to_string(); + note_shadow = Some(note_shadow_type(node).to_string()); if let Some((bs, bw)) = note_border_style(node) { note_border_style_val = match bs { ui::BorderStyle::Solid => StrokeStyle::Solid, @@ -506,10 +498,10 @@ pub fn summarize_element_toolbar( }); if !got_stroke && let Some(col) = node.props.get("prop:color") { if let Some(c) = resolve_edgeless_color(col, theme) { - stroke_color = c; + stroke_color = Some(c); } if let Some(cv) = json_to_color_value(col) { - stroke_color_value = cv; + stroke_color_value = Some(cv); } got_stroke = true; } @@ -527,13 +519,16 @@ pub fn summarize_element_toolbar( } continue; } - for node in root.walk() { - let BlockContent::Surface { elements, .. } = &node.content else { - continue; - }; - let Some(el) = elements.iter().find(|e| e.id == item.id) else { - continue; - }; + let surface_el = match &multi_targets { + Some((_, els)) => els[idx], + None => root.walk().find_map(|node| { + let BlockContent::Surface { elements, .. } = &node.content else { + return None; + }; + elements.iter().find(|e| e.id == item.id) + }), + }; + if let Some(el) = surface_el { if el.locked_by_self { is_locked = true; } @@ -552,31 +547,33 @@ pub fn summarize_element_toolbar( } else if single.is_some() && mindmap.is_none() { can_add_text = true; } - if !got_fill { - if let Some(c) = theme.resolve_color_value(&s.fill_color) { - fill_color = c; - } - fill_color_value = if s.filled { - s.fill_color.clone() - } else { - ColorValue::Single("transparent".into()) - }; - got_fill = true; - } - if !got_stroke { - if let Some(c) = theme.resolve_color_value(&s.stroke_color) { - stroke_color = c; - } - stroke_color_value = s.stroke_color.clone(); - got_stroke = true; - } - if !got_text_color { - if let Some(c) = theme.resolve_color_value(&s.color) { - text_color = c; - } - text_color_value = s.color.clone(); - got_text_color = true; - } + take_first_color_val( + &mut got_fill, + &mut fill_color, + &mut fill_color_value, + theme, + &s.fill_color, + (!s.filled).then(|| ColorValue::Single("transparent".into())), + false, + ); + take_first_color_val( + &mut got_stroke, + &mut stroke_color, + &mut stroke_color_value, + theme, + &s.stroke_color, + None, + false, + ); + take_first_color_val( + &mut got_text_color, + &mut text_color, + &mut text_color_value, + theme, + &s.color, + None, + false, + ); if !got_text_align { text_align = s.text_align; got_text_align = true; @@ -615,13 +612,15 @@ pub fn summarize_element_toolbar( } else if single.is_some() { can_add_text = true; } - if !got_stroke { - if let Some(col) = theme.resolve_color_value(&c.stroke) { - stroke_color = col; - } - stroke_color_value = c.stroke.clone(); - got_stroke = true; - } + take_first_color_val( + &mut got_stroke, + &mut stroke_color, + &mut stroke_color_value, + theme, + &c.stroke, + None, + false, + ); if !got_style { stroke_style = c.stroke_style; stroke_width = c.stroke_width; @@ -648,16 +647,15 @@ pub fn summarize_element_toolbar( } SurfaceElementKind::Brush(s) | SurfaceElementKind::Highlighter(s) => { let is_highlighter = matches!(el.kind, SurfaceElementKind::Highlighter(_)); - if !got_stroke { - if let Some(mut col) = theme.resolve_color_value(&s.color) { - if is_highlighter && col.a > 0.0 { - col.a = 1.0; - } - stroke_color = col; - } - stroke_color_value = s.color.clone(); - got_stroke = true; - } + take_first_color_val( + &mut got_stroke, + &mut stroke_color, + &mut stroke_color_value, + theme, + &s.color, + None, + is_highlighter, + ); if !got_style { stroke_width = s.line_width; got_style = true; @@ -668,13 +666,15 @@ pub fn summarize_element_toolbar( typography.get_or_insert_with(|| { ElementTypography::new(&t.font_family, &t.font_weight, &t.font_style) }); - if !got_stroke { - if let Some(col) = theme.resolve_color_value(&t.color) { - stroke_color = col; - } - stroke_color_value = t.color.clone(); - got_stroke = true; - } + take_first_color_val( + &mut got_stroke, + &mut stroke_color, + &mut stroke_color_value, + theme, + &t.color, + None, + false, + ); if !got_font { font_size = t.font_size; got_font = true; @@ -724,12 +724,23 @@ pub fn summarize_element_toolbar( is_shape_text, mindmap, surface_block, - fill_color, - stroke_color, - text_color, - fill_color_value, - stroke_color_value, - text_color_value, + fill_color: fill_color.unwrap_or_else(|| { + theme + .css_color("--affine-palette-shape-yellow") + .unwrap_or(palette.brand) + }), + stroke_color: stroke_color.unwrap_or_else(|| { + theme + .css_color("--affine-v2-edgeless-palette-black") + .unwrap_or(palette.text_primary) + }), + text_color: text_color.unwrap_or(palette.text_primary), + fill_color_value: fill_color_value.unwrap_or_else(|| ColorValue::Single("#fcd34d".into())), + stroke_color_value: stroke_color_value.unwrap_or_else(|| ColorValue::Themed { + light: "#000000".into(), + dark: "#ffffff".into(), + }), + text_color_value: text_color_value.unwrap_or_else(|| ColorValue::Single("#000000".into())), text_align, stroke_style, stroke_width, @@ -741,7 +752,7 @@ pub fn summarize_element_toolbar( front_endpoint, rear_endpoint, note_in_page, - note_shadow, + note_shadow: note_shadow.unwrap_or_else(|| "--affine-note-shadow-box".to_string()), note_border_style: note_border_style_val, note_border_size: note_border_size_val, note_border_radius: note_border_radius_val, @@ -749,3 +760,126 @@ pub fn summarize_element_toolbar( note_scale: note_scale_val, }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::edgeless::{SpatialItemInfo, SpatialItemKind, WorldRect}; + use blocksuite_playground_doc::read::{ + BlockNode, RichText, SurfaceElement, SurfaceShape, VerticalAlign, + }; + use std::collections::{BTreeMap, BTreeSet}; + + fn dummy_item(id: &str, kind: SpatialItemKind, in_mindmap: bool) -> SpatialItemInfo { + SpatialItemInfo { + id: id.into(), + kind, + shape_type: None, + surface_id: Some("surf".into()), + rect: WorldRect::new(0.0, 0.0, 100.0, 50.0), + rotate_deg: 0.0, + 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, + locked: false, + in_mindmap, + } + } + + #[test] + fn summarize_multi_selection_resolves_blocks_and_surface_elements() { + let shape = SurfaceElement { + id: "s1".into(), + index: "a0".into(), + hidden: false, + locked_by_self: false, + seed: 1, + rotate: 0.0, + props: BTreeMap::new(), + kind: SurfaceElementKind::Shape(SurfaceShape { + shape_type: ShapeType::Rect, + radius: 0.2, + xywh: [0.0, 0.0, 80.0, 40.0], + filled: true, + fill_color: ColorValue::Single("#ff0000".into()), + stroke_color: ColorValue::Single("#000000".into()), + stroke_width: 3.0, + stroke_style: StrokeStyle::Dash, + shape_style: ShapeStyle::General, + roughness: 1.0, + text: RichText::default(), + text_display: true, + color: ColorValue::Single("#111111".into()), + font_family: "sans".into(), + font_size: 18.0, + font_weight: "400".into(), + font_style: "normal".into(), + text_align: TextAlign::Left, + text_vertical_align: VerticalAlign::Center, + padding: [0.0, 0.0], + }), + }; + let note = BlockNode { + id: "n1".into(), + flavour: "affine:note".into(), + version: Some(1), + content: BlockContent::Note { + xywh: "[0,0,200,100]".into(), + display_mode: NoteDisplayMode::Both, + background: serde_json::Value::Null, + hidden: false, + }, + props: BTreeMap::from([("prop:background".into(), serde_json::json!("#00ff00"))]), + children: Vec::new(), + }; + let surface = BlockNode { + id: "surf".into(), + flavour: "affine:surface".into(), + version: Some(1), + content: BlockContent::Surface { + element_count: 1, + elements: vec![shape], + }, + props: BTreeMap::new(), + children: Vec::new(), + }; + let root = BlockNode { + id: "page".into(), + flavour: "affine:page".into(), + version: Some(1), + content: BlockContent::Page { + title: RichText::default(), + }, + props: BTreeMap::new(), + children: vec![note, surface], + }; + let snapshot = PageSnapshot { + doc_id: "d".into(), + root: Some(root), + detached: Vec::new(), + }; + let mut authoring = EdgelessAuthoringState::default(); + authoring.selection = BTreeSet::from(["s1".into(), "n1".into()]); + authoring.painted_items = vec![ + dummy_item("s1", SpatialItemKind::Shape, false), + dummy_item("n1", SpatialItemKind::Note, false), + ] + .into(); + let theme = PlaygroundTheme::Light; + let palette = Palette::new(theme); + let summary = summarize_element_toolbar(&snapshot, &authoring, theme, &palette, |_| false) + .expect("summary"); + assert!(summary.has_fill && summary.has_stroke && summary.note_in_page); + assert_eq!( + summary.fill_color_value, + ColorValue::Single("#ff0000".into()) + ); + assert_eq!(summary.stroke_width, 3.0); + assert_eq!(summary.shape_preset, ShapePreset::RoundedRect); + } +} diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/typography.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/typography.rs index d7986ced68..30b0636439 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/typography.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/typography.rs @@ -120,9 +120,9 @@ pub(super) fn build_font_menu( }; let icon = palette.icon; let hover = palette.hover; - let snap_id = SharedString::from(format!("chrome.edgeless_element_toolbar.{id}.{label}")); + let btn_id = SharedString::from(format!("el-tb-{id}-{label}")); div() - .id(snap_id.clone()) + .id(btn_id) .w_full() .h(px(30.0)) .px(px(8.0)) @@ -141,7 +141,10 @@ pub(super) fn build_font_menu( cx.stop_propagation(); this.edgeless_element_action(action.clone(), window, cx); })) - .snapshot(snap_id, Some("chrome.edgeless_element_toolbar.sub_menu")) + .snapshot( + format_args!("chrome.edgeless_element_toolbar.{id}.{label}"), + Some("chrome.edgeless_element_toolbar.sub_menu"), + ) .snapshot_text(label) .child(div().flex_1().child(label)) .when(active, |row| { diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs index 938bdafd8f..84c2100cb4 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/widgets.rs @@ -8,20 +8,24 @@ use ui::{ }; use crate::{ - overlays::align_glyph, + overlays::{ + TOOLBAR_CHROME_BTN, TOOLBAR_CHROME_BTN_RADIUS, TOOLBAR_CHROME_GAP, TOOLBAR_CHROME_HEIGHT, + TOOLBAR_CHROME_ICON, TOOLBAR_CHROME_PX, TOOLBAR_CHROME_RADIUS, TOOLBAR_SEP_SLOT, + align_glyph, chrome_border_color, + }, theme::{IconPaint, Palette, PlaygroundTheme, TYPOGRAPHY}, }; use super::{EdgelessElementAction, EdgelessElementToolbarHost, ElementColorSlot}; -pub(super) const BAR_HEIGHT: f32 = 36.0; -pub(super) const BAR_PAD_X: f32 = 6.0; -pub(super) const BAR_GAP: f32 = 8.0; -pub(super) const BAR_RADIUS: f32 = 8.0; -pub(super) const BTN_SIZE: f32 = 24.0; -pub(super) const ICON_SIZE: f32 = 20.0; -pub(super) const BTN_RADIUS: f32 = 4.0; -pub(super) const SEP_W: f32 = 4.0; +pub(super) const BAR_HEIGHT: f32 = TOOLBAR_CHROME_HEIGHT; +pub(super) const BAR_PAD_X: f32 = TOOLBAR_CHROME_PX; +pub(super) const BAR_GAP: f32 = TOOLBAR_CHROME_GAP; +pub(super) const BAR_RADIUS: f32 = TOOLBAR_CHROME_RADIUS; +pub(super) const BTN_SIZE: f32 = TOOLBAR_CHROME_BTN; +pub(super) const ICON_SIZE: f32 = TOOLBAR_CHROME_ICON; +pub(super) const BTN_RADIUS: f32 = TOOLBAR_CHROME_BTN_RADIUS; +pub(super) const SEP_W: f32 = TOOLBAR_SEP_SLOT; struct ToolbarTooltipView { label: SharedString, @@ -70,9 +74,7 @@ pub(super) fn toolbar_chrome_tokens( let panel_bg = theme .css_color("--affine-background-overlay-panel-color") .unwrap_or(palette.panel); - let border_col = theme - .css_color("--affine-v2-layer-insideBorder-border") - .unwrap_or(palette.border); + let border_col = chrome_border_color(palette); let shadows = { let s = theme.shadows("--affine-overlay-shadow"); if s.is_empty() { @@ -357,7 +359,7 @@ pub(super) fn swatch_btn( pub(super) fn text_action_btn( id: &'static str, snap_id: &'static str, - label: String, + label: impl Into, width: f32, active: bool, has_chevron: bool, @@ -366,6 +368,7 @@ pub(super) fn text_action_btn( action: EdgelessElementAction, cx: &mut Context, ) -> ui::Stateful { + let label = label.into(); let hover_bg = palette.hover; let text_col = if active { palette.brand @@ -398,7 +401,7 @@ pub(super) fn text_action_btn( this.edgeless_element_action(action.clone(), window, cx); })) .snapshot(snap_id, Some("chrome.edgeless_element_toolbar")) - .snapshot_text(label.clone()) + .snapshot_text(&label) .when(unlock, |btn| { btn.child( canvas( diff --git a/blocksuite/crates/editor/src/edgeless/overlay.rs b/blocksuite/crates/editor/src/edgeless/overlay.rs index 119f8a90a0..a3c4c8c112 100644 --- a/blocksuite/crates/editor/src/edgeless/overlay.rs +++ b/blocksuite/crates/editor/src/edgeless/overlay.rs @@ -63,7 +63,7 @@ pub fn build_edgeless_authoring_overlay( .child(circle) .cursor_pointer() .snapshot( - format!("edgeless.mindmap.toggle.{id}"), + format_args!("edgeless.mindmap.toggle.{id}"), Some(EDGELESS_VIEWPORT_ID), ) .into_any_element(), @@ -135,16 +135,18 @@ pub fn build_edgeless_authoring_overlay( .into_any_element(), ); if visible_box { - elements.push( - div() - .absolute() - .left(px(x0)) - .top(px(y0)) - .w(px(w)) - .h(px(h)) - .snapshot("edgeless.selection_box", Some(EDGELESS_VIEWPORT_ID)) - .into_any_element(), - ); + elements.extend(ui::harness::snapshot_children(|boxes| { + boxes.push( + div() + .absolute() + .left(px(x0)) + .top(px(y0)) + .w(px(w)) + .h(px(h)) + .snapshot("edgeless.selection_box", Some(EDGELESS_VIEWPORT_ID)) + .into_any_element(), + ); + })); } } else { let mut box_el = div() @@ -267,33 +269,35 @@ pub fn build_edgeless_authoring_overlay( // Invisible 12px outer-corner rotation hit zones (replacing legacy top protruding knob). if single_rotatable.is_some() { - let rotate_zones = [ - ("edgeless.handle.rotate_nw", x0 - 12.0, y0 - 12.0), - (HandleKind::Rotate.snapshot_id(), x1 + 12.0, y0 - 12.0), - ("edgeless.handle.rotate_se", x1 + 12.0, y1 + 12.0), - ("edgeless.handle.rotate_sw", x0 - 12.0, y1 + 12.0), - ]; - for (snap_id, zx, zy) in rotate_zones { - let (rzx, rzy) = rotate_point_around(zx, zy, mx, my, rot_deg); - let rx = (rzx - 6.0).round(); - let ry = (rzy - 6.0).round(); - if rx >= 0.0 - && ry >= 0.0 - && rx + 12.0 <= viewport_width - && ry + 12.0 <= viewport_height - { - elements.push( - div() - .absolute() - .left(px(rx)) - .top(px(ry)) - .w(px(12.0)) - .h(px(12.0)) - .snapshot(snap_id, Some(EDGELESS_VIEWPORT_ID)) - .into_any_element(), - ); + elements.extend(ui::harness::snapshot_children(|zones| { + let rotate_zones = [ + ("edgeless.handle.rotate_nw", x0 - 12.0, y0 - 12.0), + (HandleKind::Rotate.snapshot_id(), x1 + 12.0, y0 - 12.0), + ("edgeless.handle.rotate_se", x1 + 12.0, y1 + 12.0), + ("edgeless.handle.rotate_sw", x0 - 12.0, y1 + 12.0), + ]; + for (snap_id, zx, zy) in rotate_zones { + let (rzx, rzy) = rotate_point_around(zx, zy, mx, my, rot_deg); + let rx = (rzx - 6.0).round(); + let ry = (rzy - 6.0).round(); + if rx >= 0.0 + && ry >= 0.0 + && rx + 12.0 <= viewport_width + && ry + 12.0 <= viewport_height + { + zones.push( + div() + .absolute() + .left(px(rx)) + .top(px(ry)) + .w(px(12.0)) + .h(px(12.0)) + .snapshot(snap_id, Some(EDGELESS_VIEWPORT_ID)) + .into_any_element(), + ); + } } - } + })); } // Four-way `auto-complete` quick-connect arrows around a single selected unlocked Shape @@ -402,7 +406,7 @@ pub fn build_edgeless_authoring_overlay( .text_size(px(11.0)) .text_color(palette.background) .snapshot("edgeless.transform_hud", Some(EDGELESS_VIEWPORT_ID)) - .snapshot_text(label.clone()) + .snapshot_text(&label) .child(label) .into_any_element(), ); diff --git a/blocksuite/crates/editor/src/edgeless/quick_connect.rs b/blocksuite/crates/editor/src/edgeless/quick_connect.rs index eb11695fa8..3644c7be52 100644 --- a/blocksuite/crates/editor/src/edgeless/quick_connect.rs +++ b/blocksuite/crates/editor/src/edgeless/quick_connect.rs @@ -169,13 +169,29 @@ pub fn auto_complete_arrow_center( camera: EdgelessCamera, vp_origin: Point, ) -> (f32, f32) { - let (x, y) = dir.source_world_anchor(single.rect, single.rotate_deg); - let anchor = camera.world_to_screen(point(px(x), px(y)), vp_origin); + let (cx, cy) = single.rect.center(); + let (ax, ay) = match dir { + QuickConnectDirection::North => (cx, single.rect.y), + QuickConnectDirection::East => (single.rect.right(), cy), + QuickConnectDirection::South => (cx, single.rect.bottom()), + QuickConnectDirection::West => (single.rect.x, cy), + }; let (dx, dy) = dir.unit_vec(); - let (dx, dy) = super::rotate_point_around(dx, dy, 0.0, 0.0, single.rotate_deg); + let ((wx, wy), (vx, vy)) = if single.rotate_deg.abs() < 1e-4 { + ((ax, ay), (dx, dy)) + } else { + let (s, c) = single.rotate_deg.to_radians().sin_cos(); + let ox = ax - cx; + let oy = ay - cy; + ( + (cx + ox * c - oy * s, cy + ox * s + oy * c), + (dx * c - dy * s, dx * s + dy * c), + ) + }; + let anchor = camera.world_to_screen(point(px(wx), px(wy)), vp_origin); ( - f32::from(anchor.x) + dx * AUTO_COMPLETE_OFFSET_PX, - f32::from(anchor.y) + dy * AUTO_COMPLETE_OFFSET_PX, + f32::from(anchor.x) + vx * AUTO_COMPLETE_OFFSET_PX, + f32::from(anchor.y) + vy * AUTO_COMPLETE_OFFSET_PX, ) } @@ -474,4 +490,50 @@ mod tests { assert_eq!((r.x, r.y, r.w, r.h), (ex, ey, 120.0, 80.0)); } } + + #[test] + fn auto_complete_arrow_center_matches_rotated_world_anchor_across_angles() { + let camera = EdgelessCamera { + pan_x: 200.0, + pan_y: 150.0, + zoom: 1.5, + }; + let vp_origin = point(px(12.0), px(28.0)); + let mut item = SpatialItemInfo { + id: "s1".into(), + kind: SpatialItemKind::Shape, + shape_type: None, + surface_id: None, + rect: WorldRect::new(100.0, 120.0, 160.0, 90.0), + rotate_deg: 0.0, + 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, + locked: false, + in_mindmap: false, + }; + for deg in [0.0_f32, 37.5, -90.0, 180.0] { + item.rotate_deg = deg; + for dir in QuickConnectDirection::ALL { + let got = auto_complete_arrow_center(&item, dir, camera, vp_origin); + let (x, y) = dir.source_world_anchor(item.rect, deg); + let anchor = camera.world_to_screen(point(px(x), px(y)), vp_origin); + let (dx, dy) = dir.unit_vec(); + let (rx, ry) = crate::edgeless::rotate_point_around(dx, dy, 0.0, 0.0, deg); + let want = ( + f32::from(anchor.x) + rx * AUTO_COMPLETE_OFFSET_PX, + f32::from(anchor.y) + ry * AUTO_COMPLETE_OFFSET_PX, + ); + assert!( + (got.0 - want.0).abs() <= 1e-4 && (got.1 - want.1).abs() <= 1e-4, + "deg={deg} dir={dir:?}: got={got:?} want={want:?}" + ); + } + } + } } diff --git a/blocksuite/crates/editor/src/edgeless/toolbar/mod.rs b/blocksuite/crates/editor/src/edgeless/toolbar/mod.rs index 8784f27eda..45691995e8 100644 --- a/blocksuite/crates/editor/src/edgeless/toolbar/mod.rs +++ b/blocksuite/crates/editor/src/edgeless/toolbar/mod.rs @@ -167,55 +167,50 @@ pub fn build_edgeless_toolbar( let tools: [(&'static str, &'static str, &'static str, EdgelessTool); 9] = [ ( "edgeless-tool-select", - "chrome.edgeless_toolbar.select", + "select", "SelectIcon", EdgelessTool::Select, ), - ( - "edgeless-tool-hand", - "chrome.edgeless_toolbar.hand", - "HandIcon", - EdgelessTool::Hand, - ), + ("edgeless-tool-hand", "hand", "HandIcon", EdgelessTool::Hand), ( "edgeless-tool-note", - "chrome.edgeless_toolbar.note", + "note", "NoteShadowDuotoneIcon", EdgelessTool::Note, ), ( "edgeless-tool-shape", - "chrome.edgeless_toolbar.shape", + "shape", "ShapeIcon", EdgelessTool::Shape(ShapePreset::Rect), ), ( "edgeless-tool-connector", - "chrome.edgeless_toolbar.connector", + "connector", "ConnectorEIcon", EdgelessTool::Connector, ), ( "edgeless-tool-brush", - "chrome.edgeless_toolbar.brush", + "brush", "PenIcon", EdgelessTool::Brush, ), ( "edgeless-tool-highlighter", - "chrome.edgeless_toolbar.highlighter", + "highlighter", "BrushIcon", EdgelessTool::Highlighter, ), ( "edgeless-tool-text", - "chrome.edgeless_toolbar.text", + "text", "AddTextIcon", EdgelessTool::Text, ), ( "edgeless-tool-frame", - "chrome.edgeless_toolbar.frame", + "frame", "FrameIcon", EdgelessTool::Frame, ), @@ -240,7 +235,7 @@ pub fn build_edgeless_toolbar( .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .snapshot("chrome.edgeless_toolbar", Some(EDGELESS_VIEWPORT_ID)); - for (idx, (el_id, snap_id, icon_name, target_tool)) in tools.into_iter().enumerate() { + for (idx, (el_id, snap_suffix, icon_name, target_tool)) in tools.into_iter().enumerate() { let active = match (tool, target_tool) { (EdgelessTool::Shape(_), EdgelessTool::Shape(_)) => true, (a, b) => a == b, @@ -257,7 +252,10 @@ pub fn build_edgeless_toolbar( .items_center() .justify_center() .cursor_pointer() - .snapshot(snap_id, Some("chrome.edgeless_toolbar")) + .snapshot( + format_args!("chrome.edgeless_toolbar.{snap_suffix}"), + Some("chrome.edgeless_toolbar"), + ) .on_mouse_down( MouseButton::Left, cx.listener(move |this, _, window, cx| { @@ -351,33 +349,23 @@ pub fn build_edgeless_toolbar( Option<&'static str>, ShapePreset, ); 5] = [ - ( - "shape-rect", - "chrome.edgeless_toolbar.shape.rect", - Some("SquareIcon"), - ShapePreset::Rect, - ), - ( - "shape-ellipse", - "chrome.edgeless_toolbar.shape.ellipse", - None, - ShapePreset::Ellipse, - ), + ("shape-rect", "rect", Some("SquareIcon"), ShapePreset::Rect), + ("shape-ellipse", "ellipse", None, ShapePreset::Ellipse), ( "shape-diamond", - "chrome.edgeless_toolbar.shape.diamond", + "diamond", Some("DiamondIcon"), ShapePreset::Diamond, ), ( "shape-triangle", - "chrome.edgeless_toolbar.shape.triangle", + "triangle", Some("TriangleIcon"), ShapePreset::Triangle, ), ( "shape-rounded-rect", - "chrome.edgeless_toolbar.shape.rounded_rect", + "rounded_rect", Some("RoundedRectangleIcon"), ShapePreset::RoundedRect, ), @@ -410,7 +398,7 @@ pub fn build_edgeless_toolbar( if !shadows.is_empty() { sub = sub.shadow(shadows.into()); } - for (idx, (el_id, snap_id, icon_name, shape_kind)) in variants.into_iter().enumerate() { + for (idx, (el_id, snap_suffix, icon_name, shape_kind)) in variants.into_iter().enumerate() { let active = picker.active_shape == shape_kind; let icon_color = if active { palette.brand } else { palette.icon }; let mut btn = div() @@ -421,7 +409,10 @@ pub fn build_edgeless_toolbar( .flex() .items_center() .justify_center() - .snapshot(snap_id, Some("chrome.edgeless_toolbar.shape_picker")) + .snapshot( + format_args!("chrome.edgeless_toolbar.shape.{snap_suffix}"), + Some("chrome.edgeless_toolbar.shape_picker"), + ) .child( canvas( |_, _, _| (), diff --git a/blocksuite/crates/editor/src/edgeless/toolbar/zoom_bar.rs b/blocksuite/crates/editor/src/edgeless/toolbar/zoom_bar.rs index 38b9491647..ad6bc34787 100644 --- a/blocksuite/crates/editor/src/edgeless/toolbar/zoom_bar.rs +++ b/blocksuite/crates/editor/src/edgeless/toolbar/zoom_bar.rs @@ -69,31 +69,37 @@ pub fn build_zoom_controls( }; let icon_color = palette.icon; - let make_button = - |idx: usize, id: &'static str, snap_id: &'static str, label: String, width: f32| { - let target = ChromeHoverTarget::Zoom(idx); - let m_down = motion.clone(); - let btn = div() - .id(id) - .w(px(width)) - .h(px(btn_h)) - .rounded(px(ZOOM_BTN_RADIUS)) - .flex() - .items_center() - .justify_center() - .text_size(px(if touch_mode { 14.0 } else { 12.0 })) - .font_weight(ui::FontWeight::MEDIUM) - .text_color(palette.text_primary) - .cursor_pointer() - .on_mouse_down(MouseButton::Left, move |_, _, cx| { - cx.stop_propagation(); - m_down.update(cx, |s, cx| s.on_mouse_down(target, cx)); - }) - .snapshot(snap_id, Some("chrome.edgeless_zoom")) - .snapshot_text(label.clone()) - .child(label); - bind_chrome_button(btn, target, &motion, cx, false, palette, theme) - }; + let make_button = |idx: usize, + id: &'static str, + snap_suffix: &'static str, + label: ui::SharedString, + width: f32| { + let target = ChromeHoverTarget::Zoom(idx); + let m_down = motion.clone(); + let btn = div() + .id(id) + .w(px(width)) + .h(px(btn_h)) + .rounded(px(ZOOM_BTN_RADIUS)) + .flex() + .items_center() + .justify_center() + .text_size(px(if touch_mode { 14.0 } else { 12.0 })) + .font_weight(ui::FontWeight::MEDIUM) + .text_color(palette.text_primary) + .cursor_pointer() + .on_mouse_down(MouseButton::Left, move |_, _, cx| { + cx.stop_propagation(); + m_down.update(cx, |s, cx| s.on_mouse_down(target, cx)); + }) + .snapshot( + format_args!("chrome.edgeless_zoom.{snap_suffix}"), + Some("chrome.edgeless_zoom"), + ) + .snapshot_text(&label) + .child(label); + bind_chrome_button(btn, target, &motion, cx, false, palette, theme) + }; let fit_target = ChromeHoverTarget::Zoom(0); let m_fit_down = motion.clone(); @@ -149,34 +155,16 @@ pub fn build_zoom_controls( .snapshot("chrome.edgeless_zoom", Some(EDGELESS_VIEWPORT_ID)) .child(fit_btn) .child( - make_button( - 1, - "edgeless-zoom-out", - "chrome.edgeless_zoom.out", - "\u{2212}".into(), - w_step, - ) - .on_click(cx.listener(on_out)), + make_button(1, "edgeless-zoom-out", "out", "\u{2212}".into(), w_step) + .on_click(cx.listener(on_out)), ) .child( - make_button( - 2, - "edgeless-zoom-reset", - "chrome.edgeless_zoom.reset", - pct_label, - w_reset, - ) - .on_click(cx.listener(on_reset)), + make_button(2, "edgeless-zoom-reset", "reset", pct_label.into(), w_reset) + .on_click(cx.listener(on_reset)), ) .child( - make_button( - 3, - "edgeless-zoom-in", - "chrome.edgeless_zoom.in", - "+".into(), - w_step, - ) - .on_click(cx.listener(on_in)), + make_button(3, "edgeless-zoom-in", "in", "+".into(), w_step) + .on_click(cx.listener(on_in)), ); if !shadows.is_empty() { diff --git a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs index 182c0121cc..e249ecad91 100644 --- a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs @@ -340,7 +340,7 @@ impl Overlays { rect, 1.0, true, - "overlay.bookmark_toolbar", + format_args!("overlay.bookmark_toolbar"), palette, ) .child( diff --git a/blocksuite/crates/editor/src/overlays/callout_bar/mod.rs b/blocksuite/crates/editor/src/overlays/callout_bar/mod.rs index e3ae2f7f3d..3852047fd6 100644 --- a/blocksuite/crates/editor/src/overlays/callout_bar/mod.rs +++ b/blocksuite/crates/editor/src/overlays/callout_bar/mod.rs @@ -519,7 +519,7 @@ impl Overlays { rect, 1.0, true, - "overlay.callout_toolbar", + format_args!("overlay.callout_toolbar"), palette, ) .child( diff --git a/blocksuite/crates/editor/src/overlays/embed_toolbar.rs b/blocksuite/crates/editor/src/overlays/embed_toolbar.rs index dd465fb075..90860ba9f3 100644 --- a/blocksuite/crates/editor/src/overlays/embed_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/embed_toolbar.rs @@ -388,7 +388,7 @@ impl Overlays { rect, 1.0, true, - "overlay.embed_toolbar", + format_args!("overlay.embed_toolbar"), palette, ) .child( diff --git a/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs b/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs index 8d8b779ea8..dcea3a4f26 100644 --- a/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs +++ b/blocksuite/crates/editor/src/overlays/toolbar_chrome/hover.rs @@ -3,10 +3,74 @@ use super::{HOVER_ENTER_DELAY_MS, HOVER_LEAVE_DELAY_MS}; use crate::{ - block_flow::{FlowKind, FlowRect, FormFactor}, - overlays::{OverlayScene, Overlays, TableHoverState}, + block_flow::{FlowBlock, FlowKind, FlowRect, FormFactor}, + overlays::{OverlayScene, Overlays, TableAddDragKind, TableHoverState}, }; +fn table_add_zone( + block: &FlowBlock, + scroll_x: f32, + scene: &OverlayScene<'_>, + pointer: (f32, f32), +) -> Option { + let (min_x, min_y, max_r, max_b) = block.body.table_cells.iter().fold( + (f32::INFINITY, f32::INFINITY, 0.0_f32, 0.0_f32), + |(lx, ty, mr, mb), c| { + ( + lx.min(c.rect.x), + ty.min(c.rect.y), + mr.max(c.rect.right()), + mb.max(c.rect.bottom()), + ) + }, + ); + if !min_x.is_finite() || !min_y.is_finite() { + return None; + } + let viewport_width = scene.window.0; + let viewport_height = (scene.window.1 - scene.topbar_height).max(0.0); + let table_screen_left = (scene.geometry.column_x + block.x + min_x - scroll_x).round(); + let table_screen_right = (scene.geometry.column_x + block.x + max_r - scroll_x) + .min(scene.geometry.column_x + block.x + block.body.width) + .round(); + let table_screen_top = (block.y + min_y - scene.scroll_y).round(); + let table_screen_bottom = (block.y + max_b - scene.scroll_y).round(); + if table_screen_bottom < 0.0 || table_screen_top > viewport_height { + return None; + } + let vis_top = table_screen_top.max(0.0).ceil(); + let vis_bottom = table_screen_bottom.min(viewport_height).floor(); + let table_vis_h = (vis_bottom - vis_top).max(0.0); + let table_vis_w = (table_screen_right - table_screen_left).max(0.0); + + let (x, y) = pointer; + let near_right = (table_screen_right - 12.0..=table_screen_right + 20.0).contains(&x); + let near_bottom = (table_screen_bottom - 12.0..=table_screen_bottom + 20.0).contains(&y); + match (near_right, near_bottom) { + (true, true) + if table_screen_right + 18.0 <= viewport_width + && table_screen_bottom + 18.0 <= viewport_height => + { + Some(TableAddDragKind::Both) + } + (true, false) + if (vis_top..=vis_bottom).contains(&y) + && table_vis_h > 0.0 + && table_screen_right + 18.0 <= viewport_width => + { + Some(TableAddDragKind::Column) + } + (false, true) + if (table_screen_left..=table_screen_right).contains(&x) + && table_vis_w > 0.0 + && table_screen_bottom + 18.0 <= viewport_height => + { + Some(TableAddDragKind::Row) + } + _ => None, + } +} + /// Lifecycle phase of a scheduler-clock hover-triggered surface. #[derive(Clone, Debug, PartialEq)] pub enum HoverPhase { @@ -257,6 +321,7 @@ impl Overlays { if self.table_hover.add_drag.is_none() { let (wx, wy) = scene.screen_to_world(x, y); + let pointer = (x, y - scene.topbar_height); let hit_table = scene.layout.blocks.iter().find_map(|b| { if b.body.kind != FlowKind::Table { return None; @@ -283,14 +348,24 @@ impl Overlays { da.total_cmp(&dc) }) }); + let new_zone = table_add_zone(b, scroll_x, scene, pointer); + let prev_zone = if self.table_hover.block_id.as_deref() == Some(b.block_id.as_str()) + { + self.table_hover + .pointer + .and_then(|prev| table_add_zone(b, scroll_x, scene, prev)) + } else { + None + }; Some(( b.block_id.clone(), cell.map(|c| c.row_id.clone()), cell.map(|c| c.column_id.clone()), + new_zone != prev_zone, )) }); match hit_table { - Some((bid, rid, cid)) => { + Some((bid, rid, cid, zone_changed)) => { if self.table_hover.block_id.as_deref() != Some(bid.as_str()) { self.table_hover.hover_since_ms = now_ms; changed = true; @@ -298,9 +373,8 @@ impl Overlays { if self.table_hover.row_id != rid || self.table_hover.column_id != cid { changed = true; } - let pointer = Some((x, y - scene.topbar_height)); - changed |= self.table_hover.pointer != pointer; - self.table_hover.pointer = pointer; + changed |= zone_changed; + self.table_hover.pointer = Some(pointer); self.table_hover.block_id = Some(bid); self.table_hover.row_id = rid; self.table_hover.column_id = cid; @@ -315,3 +389,133 @@ impl Overlays { changed } } + +#[cfg(test)] +mod tests { + use std::{collections::BTreeSet, rc::Rc}; + + use blocksuite_playground_doc::read::PageSnapshot; + use ui::{AppContext, Application, Direction, HeadlessPlatform, WindowOptions, point, px}; + + use super::*; + use crate::{ + block_flow::{ + BlockBody, FlowBlock, FlowKind, FlowLayout, FlowStats, FlowTextLayout, FormFactor, + InlineAlign, InlineBaseline, InlineStyle, PageGeometry, TableCellHit, layout_inline, + }, + overlays::OverlayScene, + theme::FONT_SANS, + }; + + #[test] + fn table_hover_center_moves_do_not_trigger_redraw_and_edge_zone_transitions_do() { + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform).run_embedded(|_| {}); + let win = app + .update(|cx| { + cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| ui::EmptyView)) + }) + .expect("open window"); + let empty_text = app.update(|cx| { + win.update(cx, |_, window, _| { + let style = InlineStyle::new(FONT_SANS, 14.0, 400.0, ui::black()); + FlowTextLayout::Plain(Rc::new(layout_inline( + "", + &style, + 200.0, + 20.0, + InlineBaseline::At(15.0), + InlineAlign::Left, + window, + ))) + }) + .expect("window") + }); + let mut body = BlockBody::test_paragraph(400.0, 120.0); + body.kind = FlowKind::Table; + body.table_cells = vec![ + TableCellHit { + row_id: "r1".into(), + column_id: "c1".into(), + rect: FlowRect::new(0.0, 0.0, 200.0, 60.0), + text_origin: (8.0, 8.0), + text: empty_text.clone(), + }, + TableCellHit { + row_id: "r2".into(), + column_id: "c1".into(), + rect: FlowRect::new(0.0, 60.0, 200.0, 60.0), + text_origin: (8.0, 68.0), + text: empty_text, + }, + ]; + let layout = FlowLayout { + blocks: vec![FlowBlock { + block_id: "tbl-1".into(), + is_title_block: false, + x: 0.0, + y: 100.0, + has_gutter_chevron: false, + body: Rc::new(body), + }], + width: 752.0, + height: 400.0, + direction: Direction::Ltr, + stats: FlowStats::default(), + }; + let snapshot = PageSnapshot { + doc_id: "doc".into(), + root: None, + detached: Vec::new(), + }; + let local_collapsed = BTreeSet::new(); + let scene = OverlayScene { + snapshot: &snapshot, + layout: &layout, + geometry: PageGeometry { + viewport_width: 1280.0, + side_padding: 76.0, + column_x: 100.0, + column_width: 752.0, + }, + window: (1280.0, 800.0), + pane_origin: point(px(0.0), px(0.0)), + bottom_inset: 0.0, + bottom_toolbar_inset: 0.0, + scroll_y: 0.0, + direction: Direction::Ltr, + form_factor: FormFactor::Desktop, + is_touch: false, + focused_code_block: None, + selected_image_block: None, + can_download_blobs: false, + selected_attachment_block: None, + selected_bookmark_block: None, + selected_embed_block: None, + selected_callout_block: None, + selected_latex_block: None, + selection: None, + screen_transform: None, + suppress_floating_format_buttons: false, + page_readonly: false, + local_collapsed: &local_collapsed, + topbar_height: 52.0, + }; + let mut overlays = Overlays::default(); + // Enter table cell r1/c1 center (screen x=200, y=180 -> cell y=28). + assert!(overlays.sync_hover_affordances(&scene, 200.0, 180.0, 100.0)); + // Move inside the same cell center: zero redraws. + for dx in [1.0_f32, 5.0, 15.0] { + assert!( + !overlays.sync_hover_affordances(&scene, 200.0 + dx, 180.0, 110.0), + "moving inside cell center must not trigger redraw" + ); + } + // Enter right edge add-column zone (table_screen_right = 300.0, near_right = 288..=320). + assert!(overlays.sync_hover_affordances(&scene, 295.0, 180.0, 120.0)); + // Move within the same add-column zone in the same cell: zero redraws. + assert!(!overlays.sync_hover_affordances(&scene, 298.0, 182.0, 130.0)); + // Move to corner add-both zone (table_screen_bottom = 220.0, near_bottom = 208..=240). + assert!(overlays.sync_hover_affordances(&scene, 298.0, 270.0, 140.0)); + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/paint.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/paint.rs index b2f2a12652..21ceedfeb8 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/paint.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/paint.rs @@ -15,62 +15,18 @@ use crate::{ theme::Palette, }; -const TABLE_BG_SWATCHES: [(&str, Option<&str>, u32); 6] = [ - ("Default", None, 0xffffff), - ( - "Gray", - Some("var(--affine-background-secondary-color)"), - 0xefeff0, - ), - ("Blue", Some("var(--affine-tag-blue)"), 0xdbeafe), - ("Green", Some("var(--affine-tag-green)"), 0xdcfce7), - ("Yellow", Some("var(--affine-tag-yellow)"), 0xfef9c3), - ("Red", Some("var(--affine-tag-red)"), 0xfee2e2), -]; +struct LazyInputDisplay<'a>(&'a blocksuite_editor::inline_input::Utf16ImeBuffer); + +impl std::fmt::Display for LazyInputDisplay<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.0.preedit.is_some() { + true => f.write_str(&self.0.display_text()), + false => f.write_str(&self.0.text), + } + } +} impl PlaygroundView { - pub(super) fn table_axis_swatches( - &self, - is_row: bool, - palette: &Palette, - cx: &ui::Context, - ) -> ui::Div { - use ui::{MouseButton, SharedString}; - let mut swatches = div() - .flex() - .items_center() - .gap(px(4.0)) - .px(px(6.0)) - .py(px(4.0)); - for (name, css_var, hex) in TABLE_BG_SWATCHES { - swatches = swatches.child( - div() - .id(SharedString::from(format!("tbl-bg-{name}"))) - .flex_none() - .w(px(24.0)) - .h(px(24.0)) - .rounded(px(4.0)) - .bg(ui::rgb(hex)) - .border_1() - .border_color(palette.border) - .cursor_pointer() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(move |this, _, win, cx| { - let _ = this.table_set_axis_background(is_row, css_var, win, cx); - })) - .snapshot( - SharedString::from(format!( - "overlay.table_toolbar.axis_menu.bg_{}", - name.to_lowercase() - )), - Some("overlay.table_toolbar.axis_menu"), - ) - .snapshot_text(name), - ); - } - swatches - } - pub(super) fn table_axis_preview( &self, block: &crate::block_flow::FlowBlock, @@ -114,107 +70,83 @@ impl PlaygroundView { return None; } let cells = &block.body.table_cells; - let first = cells.first()?; - let scroll_x = self.overlays.code_scroll_x(&block.block_id); + let scroll_x = (!cells.is_empty()).then(|| self.overlays.code_scroll_x(&block.block_id))?; + let dashed = + axis.is_none() && drag.is_some_and(|d| d.preview_rows >= 0 && d.preview_cols >= 0); + let body = frame.map(FlowRect::new(block.x, block.y, block.body.width, 0.0)); + let (left, right) = ( + body.x.max(0.0), + if dashed { + width + } else { + width.min(body.right()) + }, + ); + if left >= right || height <= 0.0 { + return None; + } + let (origin, bounds) = ((block.x - scroll_x, block.y), (left, right, height)); let mut rects = Vec::new(); - let mut dashed = false; - let mut id = "overlay.table_toolbar.axis_selection"; + let mut preview_kind: u8 = 0; if let Some((cell, axis)) = axis { - rects.extend( - cells - .iter() - .filter(|hit| match axis { - TableAxisMenu::Row => hit.row_id == cell.row_id, - TableAxisMenu::Column => hit.column_id == cell.column_id, - }) - .map(|c| c.rect), - ); + for hit in cells.iter().filter(|h| match axis { + TableAxisMenu::Row => h.row_id == cell.row_id, + TableAxisMenu::Column => h.column_id == cell.column_id, + }) { + rects.extend(clip_rect(frame, origin, bounds, hit.rect)); + } } else if let Some(drag) = drag { - let rows = drag.preview_rows; - let cols = drag.preview_cols; - let last = cells.last()?; + let (rows, cols) = (drag.preview_rows, drag.preview_cols); if rows < 0 || cols < 0 { - id = "overlay.table_hover.trim_preview"; - let table = self.snapshot.as_ref()?.block(&block.block_id)?; - let BlockContent::Table(table) = &table.content else { + preview_kind = 1; + let BlockContent::Table(t) = + &self.snapshot.as_ref()?.block(&block.block_id)?.content + else { return None; }; - let row_ids: std::collections::HashSet<_> = table - .rows - .iter() - .rev() - .take(rows.unsigned_abs()) - .map(|r| &r.row_id) - .collect(); - let col_ids: std::collections::HashSet<_> = table - .columns - .iter() - .rev() - .take(cols.unsigned_abs()) - .map(|c| &c.column_id) - .collect(); - rects.extend( - cells - .iter() - .filter(|c| row_ids.contains(&c.row_id) || col_ids.contains(&c.column_id)) - .map(|c| c.rect), - ); + let tr = &t.rows[t.rows.len().saturating_sub(rows.unsigned_abs())..]; + let tc = &t.columns[t.columns.len().saturating_sub(cols.unsigned_abs())..]; + for c in cells.iter().filter(|c| { + tr.iter().any(|r| r.row_id == c.row_id) + || tc.iter().any(|k| k.column_id == c.column_id) + }) { + rects.extend(clip_rect(frame, origin, bounds, c.rect)); + } } else { - id = "overlay.table_hover.grow_preview"; - dashed = true; + preview_kind = 2; let rtl = self.active_overlay_target()?.1.direction == ui::Direction::Rtl; - let added_width = cols as f32 * 120.0; - let offset = if rtl { added_width } else { 0.0 }; - let start = if rtl { first.rect.x } else { last.rect.right() }; - let mut columns: Vec<_> = cells - .iter() - .take_while(|c| c.row_id == first.row_id) - .map(|c| (c.rect.x + offset, c.rect.w)) - .collect(); - for col in 0..cols { - let x = start + col as f32 * 120.0; - columns.push((x, 120.0)); - rects.extend( - cells - .iter() - .filter(|c| c.column_id == first.column_id) - .map(|c| FlowRect::new(x, c.rect.y, 120.0, c.rect.h)), - ); - } - for row in 0..rows { - let y = last.rect.bottom() + row as f32 * 36.0; - rects.extend(columns.iter().map(|&(x, w)| FlowRect::new(x, y, w, 36.0))); - } + collect_grow_preview_rects( + cells, rows, cols, rtl, frame, origin, bounds, &mut rects, + ); } } - let body = frame.map(FlowRect::new(block.x, block.y, block.body.width, 0.0)); - let left = body.x.max(0.0); - let right = if dashed { - width - } else { - width.min(body.right()) - }; - rects.retain_mut(|r| { - let m = frame.map(r.translated(block.x - scroll_x, block.y)); - let x = m.x.max(left); - let y = m.y.max(0.0); - *r = FlowRect::new(x, y, m.right().min(right) - x, m.bottom().min(height) - y); - r.w > 0.0 && r.h > 0.0 - }); let first = rects.first()?; let (x, y, r, b) = rects.iter().fold( (first.x, first.y, first.right(), first.bottom()), |(x, y, r, b), c| (x.min(c.x), y.min(c.y), r.max(c.right()), b.max(c.bottom())), ); - let ink = palette.brand; + let (ink, ew, style) = ( + palette.brand, + if dashed { 1.0 } else { 0.0 }, + if dashed { + ui::BorderStyle::Dashed + } else { + ui::BorderStyle::Solid + }, + ); + let box_el = div() + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(r - x)) + .h(px(b - y)); + let box_el = match preview_kind { + 0 => box_el.snapshot("overlay.table_toolbar.axis_selection", Some("root.canvas")), + 1 => box_el.snapshot("overlay.table_hover.trim_preview", Some("root.canvas")), + _ => box_el.snapshot("overlay.table_hover.grow_preview", Some("root.canvas")), + }; Some( - div() - .absolute() - .left(px(x)) - .top(px(y)) - .w(px(r - x)) - .h(px(b - y)) - .snapshot(id, Some("root.canvas")) + box_el .child( ui::canvas( |_, _, _| (), @@ -224,13 +156,9 @@ impl PlaygroundView { cell.translated(-x, -y).bounds(bounds.origin), ui::Corners::all(px(0.0)), ink.opacity(0.12), - ui::Edges::all(px(if dashed { 1.0 } else { 0.0 })), + ui::Edges::all(px(ew)), ink.opacity(0.6), - if dashed { - ui::BorderStyle::Dashed - } else { - ui::BorderStyle::Solid - }, + style, )); } }, @@ -249,28 +177,24 @@ impl PlaygroundView { palette: &Palette, cx: &mut ui::Context, ) -> Vec { - let mut out = Vec::new(); - if self.table_is_readonly() + let blocked = self.table_is_readonly() || self.database_record_sheet.is_some() - || self.active_note_touch_table_bar(self.window_size.0) - { - return out; - } - let Some(cell) = self.table_cell.as_ref() else { - return out; + || self.active_note_touch_table_bar(self.window_size.0); + let (Some(cell), Some(t)) = ( + (!blocked).then_some(self.table_cell.as_ref()).flatten(), + transform, + ) else { + return Vec::new(); }; let Some(axis_menu) = cell.axis_menu else { - return out; + return Vec::new(); }; let Some(block) = layout.block(&cell.block_id) else { - return out; - }; - let Some(t) = transform else { - return out; + return Vec::new(); }; let screen = t.rect_to_screen(&FlowRect::new(block.x, block.y, block.body.width, 40.0)); let (dx, dy) = self.view_window_offset(); - out.push(self.build_table_axis_menu( + vec![self.build_table_axis_menu( axis_menu, screen.x - dx, (screen.y - dy + 8.0).max(self.topbar_height() + 8.0), @@ -278,8 +202,7 @@ impl PlaygroundView { self.window_size.0, palette, cx, - )); - out + )] } /// Whether the edited Note shows the touch table bar of the Page in place of the desktop @@ -314,19 +237,17 @@ impl PlaygroundView { return out; }; let cell = self.table_cell.as_ref(); - let Some(block_id) = self + let block_id = self .overlays .table_hover .add_drag .as_ref() .map(|d| d.block_id.as_str()) - .or_else(|| cell.map(|c| c.block_id.as_str())) - else { - return out; - }; - let Some(block) = layout.block(block_id) else { + .or_else(|| cell.map(|c| c.block_id.as_str())); + let Some(block) = block_id.and_then(|id| layout.block(id)) else { return out; }; + let block_id = block.block_id.as_str(); out.extend(self.table_axis_preview_in(block, frame, width, height, palette)); if self.table_is_readonly() || block.body.table_cells.is_empty() { return out; @@ -429,10 +350,7 @@ impl PlaygroundView { .h(px(table.h)) .when(drag.is_some(), |d| d.bg(blue)) .snapshot( - SharedString::from(format!( - "overlay.table_col_resize.{}", - hit.column_id - )), + format_args!("overlay.table_col_resize.{}", hit.column_id), Some("root.canvas"), ), ) @@ -445,23 +363,26 @@ impl PlaygroundView { .theme .css_var("--affine-v2-table-indicator-hover") .unwrap_or(palette.hover); - for (kind, rect, snap, cursor) in [ + for (kind, rect, dom_id, snap_suffix, cursor) in [ ( TableAddDragKind::Column, FlowRect::new(table.right() + 2.0, table.y, 16.0, table.h), - "overlay.table_hover.add_col", + "an-tbl-add-col", + "add_col", CursorStyle::ResizeLeftRight, ), ( TableAddDragKind::Row, FlowRect::new(table.x, table.bottom() + 2.0, table.w, 16.0), - "overlay.table_hover.add_row", + "an-tbl-add-row", + "add_row", CursorStyle::ResizeUpDown, ), ( TableAddDragKind::Both, FlowRect::new(table.right() + 2.0, table.bottom() + 2.0, 16.0, 16.0), - "overlay.table_hover.add_corner", + "an-tbl-add-corner", + "add_corner", CursorStyle::ResizeUpLeftDownRight, ), ] { @@ -476,7 +397,7 @@ impl PlaygroundView { }; out.push( at(rect.x, rect.y, rect.w, rect.h) - .id(snap) + .id(dom_id) .rounded(px(4.0)) .bg(bar_bg) .flex() @@ -500,7 +421,10 @@ impl PlaygroundView { cx.notify(); }), ) - .snapshot(snap, Some("root.canvas")) + .snapshot( + format_args!("overlay.table_hover.{snap_suffix}"), + Some("root.canvas"), + ) .snapshot_text("+") .child("+") .into_any_element(), @@ -518,16 +442,18 @@ impl PlaygroundView { return out; }; let focus = frame.map(hit.rect.translated(block.x - scroll_x, block.y)); - for (axis, rect, snap) in [ + for (axis, rect, dom_id, snap_suffix) in [ ( TableAxisMenu::Column, FlowRect::new(focus.x + focus.w * 0.5 - 14.0, table.y - 18.0, 28.0, 16.0), - "overlay.table_hover.col_pill", + "an-tbl-col-pill", + "col_pill", ), ( TableAxisMenu::Row, FlowRect::new(table.x - 18.0, focus.y + focus.h * 0.5 - 14.0, 16.0, 28.0), - "overlay.table_hover.row_pill", + "an-tbl-row-pill", + "row_pill", ), ] { let (bid, rid, cid) = ( @@ -544,7 +470,7 @@ impl PlaygroundView { }; out.push( at(rect.x, rect.y, rect.w, rect.h) - .id(snap) + .id(dom_id) .rounded(px(8.0)) .bg(palette.panel) .border_1() @@ -560,7 +486,10 @@ impl PlaygroundView { let (b, r, c) = (bid.clone(), rid.clone(), cid.clone()); this.open_table_axis_menu_for(b, r, c, axis, win, cx); })) - .snapshot(snap, Some("root.canvas")) + .snapshot( + format_args!("overlay.table_hover.{snap_suffix}"), + Some("root.canvas"), + ) .child(dot()) .child(dot()) .child(dot()) @@ -577,80 +506,63 @@ impl PlaygroundView { &self, snapshot: &mut blocksuite_playground_doc::read::PageSnapshot, ) -> bool { - let Some(cell) = self.table_cell.as_ref() else { + let (Some(cell), Some(root)) = (self.table_cell.as_ref(), snapshot.root.as_mut()) else { return false; }; let Some(pre) = cell.input.preedit.as_ref() else { return false; }; - let Some(root) = snapshot.root.as_mut() else { - return false; - }; let display = cell.input.display_text(); - let rep = pre.replacement.clone(); - let pre_text = pre.text.as_str(); + let ids = ( + cell.block_id.as_str(), + cell.row_id.as_str(), + cell.column_id.as_str(), + ); + let text_edit = (&pre.replacement, pre.text.as_str(), display.as_str()); fn patch_node( node: &mut blocksuite_playground_doc::read::BlockNode, - block_id: &str, - row_id: &str, - column_id: &str, - rep: &std::ops::Range, - pre_text: &str, - display: &str, + ids: (&str, &str, &str), + edit: (&std::ops::Range, &str, &str), ) -> bool { - if node.id == block_id { - if let BlockContent::Table(table) = &mut node.content { - let entry = table - .cells - .entry((row_id.to_string(), column_id.to_string())) - .or_insert_with(|| TableCell { - text: blocksuite_playground_doc::read::RichText::default(), - }); - let delta = if let Ok((mut before, rest)) = - split_delta(&entry.text.delta, rep.start as u64) - && let Ok((_, after)) = - split_delta(&rest, (rep.end.saturating_sub(rep.start)) as u64) - { - if !pre_text.is_empty() { - before.push(TextDeltaOp::Insert { - insert: TextInsert::Text(pre_text.to_string()), - format: None, - }); - } - before.extend(after); - before - } else if display.is_empty() { - Vec::new() - } else { - vec![TextDeltaOp::Insert { - insert: TextInsert::Text(display.to_string()), - format: None, - }] - }; - entry.text = blocksuite_playground_doc::read::RichText { - plain: display.to_string(), - delta, - }; - return true; - } + if node.id != ids.0 { + return node.children.iter_mut().any(|c| patch_node(c, ids, edit)); + } + let BlockContent::Table(table) = &mut node.content else { return false; - } - for child in &mut node.children { - if patch_node(child, block_id, row_id, column_id, rep, pre_text, display) { - return true; + }; + let entry = table + .cells + .entry((ids.1.to_string(), ids.2.to_string())) + .or_insert_with(|| TableCell { + text: blocksuite_playground_doc::read::RichText::default(), + }); + let (rep, pre_text, display) = edit; + let op = |s: &str| TextDeltaOp::Insert { + insert: TextInsert::Text(s.to_string()), + format: None, + }; + let delta = if let Ok((mut before, rest)) = + split_delta(&entry.text.delta, rep.start as u64) + && let Ok((_, after)) = + split_delta(&rest, (rep.end.saturating_sub(rep.start)) as u64) + { + if !pre_text.is_empty() { + before.push(op(pre_text)); } - } - false + before.extend(after); + before + } else if display.is_empty() { + Vec::new() + } else { + vec![op(display)] + }; + entry.text = blocksuite_playground_doc::read::RichText { + plain: display.to_string(), + delta, + }; + true } - patch_node( - root, - &cell.block_id, - &cell.row_id, - &cell.column_id, - &rep, - pre_text, - &display, - ) + patch_node(root, ids, text_edit) } /// In-place visual elements for a focused table cell: 1.5px brand focus border, @@ -674,10 +586,12 @@ impl PlaygroundView { caret_alpha: f32, ) -> Vec { let mut out = Vec::new(); - let Some(cell) = self.table_cell.as_ref() else { - return out; - }; - let Some(block) = layout.block(&cell.block_id) else { + let (Some(cell), Some(block)) = ( + self.table_cell.as_ref(), + self.table_cell + .as_ref() + .and_then(|c| layout.block(&c.block_id)), + ) else { return out; }; let Some((bx, by, hit)) = @@ -693,8 +607,7 @@ impl PlaygroundView { let right = r.right().min(vis_right); (right > left).then(|| FlowRect::new(left, r.y, right - left, r.h)) }; - let place = |r: FlowRect| { - let m = frame.map(r); + let mk = |m: FlowRect| { div() .absolute() .left(px(m.x)) @@ -702,14 +615,12 @@ impl PlaygroundView { .w(px(m.w)) .h(px(m.h)) }; + let place = |r: FlowRect| mk(frame.map(r)); let line = |r: FlowRect, h: f32| { - let m = frame.map(r); - div() - .absolute() - .left(px(m.x)) - .top(px(m.bottom() - h)) - .w(px(m.w)) - .h(px(h)) + let mut m = frame.map(r); + m.y = m.bottom() - h; + m.h = h; + mk(m) }; let cell_world = hit.rect.translated(bx - scroll_x, by); @@ -722,7 +633,7 @@ impl PlaygroundView { ring = ring .snapshot("page.table_cell_focus", Some(PAGE_SURFACE_ID)) .snapshot_focused(true) - .snapshot_text(cell.input.display_text()); + .snapshot_text(format_args!("{}", LazyInputDisplay(&cell.input))); } out.push(ring.into_any_element()); } @@ -735,8 +646,12 @@ impl PlaygroundView { if let Some(marked) = &marked { for (line_idx, a, b) in hit.text.selection_spans(marked.start, marked.end) { - let span = FlowRect::new(ox + a, oy + line_idx as f32 * lh, (b - a).max(1.0), lh); - if let Some(clipped) = clip_x(span) { + if let Some(clipped) = clip_x(FlowRect::new( + ox + a, + oy + line_idx as f32 * lh, + (b - a).max(1.0), + lh, + )) { out.push( line(clipped, 1.0) .bg(palette.text_secondary) @@ -744,20 +659,11 @@ impl PlaygroundView { ); } } - if !sel.is_empty() { - for (line_idx, a, b) in hit.text.selection_spans(sel.start, sel.end) { - let span = - FlowRect::new(ox + a, oy + line_idx as f32 * lh, (b - a).max(1.0), lh); - if let Some(c) = clip_x(span) { - out.push(place(c).bg(palette.brand.opacity(0.18)).into_any_element()); - out.push(line(c, 2.0).bg(palette.brand).into_any_element()); - } - } - } - } else if !sel.is_empty() { - let mut first = true; + } + if !sel.is_empty() { + let mut first = marked.is_none(); for (line_idx, a, b) in hit.text.selection_spans(sel.start, sel.end) { - let Some(r) = clip_x(FlowRect::new( + let Some(c) = clip_x(FlowRect::new( ox + a, oy + line_idx as f32 * lh, (b - a).max(1.0), @@ -765,11 +671,16 @@ impl PlaygroundView { )) else { continue; }; - let mut d = place(r).bg(palette.brand.opacity(0.22)); - if frame.fully_visible(&r) && std::mem::take(&mut first) { - d = d.snapshot("page.selection", Some(PAGE_SURFACE_ID)); + if marked.is_some() { + out.push(place(c).bg(palette.brand.opacity(0.18)).into_any_element()); + out.push(line(c, 2.0).bg(palette.brand).into_any_element()); + } else { + let mut d = place(c).bg(palette.brand.opacity(0.22)); + if frame.fully_visible(&c) && std::mem::take(&mut first) { + d = d.snapshot("page.selection", Some(PAGE_SURFACE_ID)); + } + out.push(d.into_any_element()); } - out.push(d.into_any_element()); } } @@ -791,3 +702,279 @@ impl PlaygroundView { out } } + +fn clip_rect( + frame: TablePaintFrame, + origin: (f32, f32), + bounds: (f32, f32, f32), + rect: FlowRect, +) -> Option { + let m = frame.map(rect.translated(origin.0, origin.1)); + let (x, y) = (m.x.max(bounds.0), m.y.max(0.0)); + let (w, h) = (m.right().min(bounds.1) - x, m.bottom().min(bounds.2) - y); + (w > 0.0 && h > 0.0).then(|| FlowRect::new(x, y, w, h)) +} + +#[allow(clippy::too_many_arguments)] +fn collect_grow_preview_rects( + cells: &[crate::block_flow::TableCellHit], + rows: isize, + cols: isize, + rtl: bool, + frame: TablePaintFrame, + origin: (f32, f32), + bounds: (f32, f32, f32), + rects: &mut Vec, +) { + let (Some(first), Some(last)) = (cells.first(), cells.last()) else { + return; + }; + let vis = |r: FlowRect| { + let m = frame.map(r.translated(origin.0, origin.1)); + m.right() > bounds.0 && m.x < bounds.1 && m.bottom() > 0.0 && m.y < bounds.2 + }; + let added_w = cols as f32 * 120.0; + let (offset, start) = ( + if rtl { added_w } else { 0.0 }, + if rtl { first.rect.x } else { last.rect.right() }, + ); + let existing_h = (last.rect.bottom() - first.rect.y).max(0.0); + let vis_cols: Vec = (0..cols) + .filter(|_| existing_h > 0.0) + .map(|c| start + c as f32 * 120.0) + .filter(|&x| vis(FlowRect::new(x, first.rect.y, 120.0, existing_h))) + .collect(); + let first_cols = cells + .iter() + .take_while(|c| c.row_id == first.row_id) + .count(); + let push = |out: &mut Vec, r| out.extend(clip_rect(frame, origin, bounds, r)); + if !vis_cols.is_empty() { + let uniform = first_cols > 0 && cells.len().is_multiple_of(first_cols); + let vis_rows: Vec<(f32, f32)> = cells + .iter() + .step_by(if uniform { first_cols } else { 1 }) + .filter(|c| { + (uniform || c.column_id == first.column_id) + && vis(FlowRect::new(start, c.rect.y, added_w, c.rect.h)) + }) + .map(|c| (c.rect.y, c.rect.h)) + .collect(); + rects.reserve(vis_cols.len() * vis_rows.len()); + for &x in &vis_cols { + for &(y, h) in &vis_rows { + push(rects, FlowRect::new(x, y, 120.0, h)); + } + } + } + if rows <= 0 { + return; + } + let (added_top, added_h) = (last.rect.bottom(), rows as f32 * 36.0); + let cols_xy: Vec<(f32, f32)> = cells[..first_cols] + .iter() + .map(|c| (c.rect.x + offset, c.rect.w)) + .chain((0..cols).map(|c| (start + c as f32 * 120.0, 120.0))) + .filter(|&(x, w)| vis(FlowRect::new(x, added_top, w, added_h))) + .collect(); + if cols_xy.is_empty() { + return; + } + let (min_x, max_r) = cols_xy + .iter() + .fold((f32::INFINITY, f32::NEG_INFINITY), |(mn, mx), &(x, w)| { + (mn.min(x), mx.max(x + w)) + }); + rects.reserve(cols_xy.len() * rows as usize); + for row in 0..rows { + let y = added_top + row as f32 * 36.0; + if vis(FlowRect::new(min_x, y, (max_r - min_x).max(0.0), 36.0)) { + for &(x, w) in &cols_xy { + push(rects, FlowRect::new(x, y, w, 36.0)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::block_flow::TableCellHit; + use blocksuite_editor::{ + block_flow::{FlowTextLayout, InlineAlign, InlineBaseline, InlineStyle, layout_inline}, + overlays::OverlayScreenTransform, + theme::FONT_SANS, + }; + use std::rc::Rc; + use ui::{AppContext, Application, HeadlessPlatform, WindowOptions}; + + fn make_cells(rows: usize, cols: usize) -> Vec { + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform).run_embedded(|_| {}); + let win = app + .update(|cx| { + cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| ui::EmptyView)) + }) + .expect("open window"); + let empty_text = app.update(|cx| { + win.update(cx, |_, window, _| { + let style = InlineStyle::new(FONT_SANS, 14.0, 400.0, ui::black()); + FlowTextLayout::Plain(Rc::new(layout_inline( + "", + &style, + 100.0, + 20.0, + InlineBaseline::At(15.0), + InlineAlign::Left, + window, + ))) + }) + .expect("window") + }); + let mut out = Vec::with_capacity(rows * cols); + for r in 0..rows { + for c in 0..cols { + out.push(TableCellHit { + row_id: format!("r{r}"), + column_id: format!("c{c}"), + rect: FlowRect::new(c as f32 * 100.0, r as f32 * 36.0, 100.0, 36.0), + text_origin: (0.0, 0.0), + text: empty_text.clone(), + }); + } + } + out + } + + fn reference_grow_preview( + cells: &[TableCellHit], + first: &TableCellHit, + last: &TableCellHit, + rows: isize, + cols: isize, + rtl: bool, + frame: TablePaintFrame, + origin: (f32, f32), + left: f32, + right: f32, + height: f32, + ) -> Vec { + let mut out = Vec::new(); + let offset = if rtl { cols as f32 * 120.0 } else { 0.0 }; + let start = if rtl { first.rect.x } else { last.rect.right() }; + for col in 0..cols { + let x = start + col as f32 * 120.0; + for c in cells.iter().filter(|c| c.column_id == first.column_id) { + out.push(FlowRect::new(x, c.rect.y, 120.0, c.rect.h)); + } + } + if rows > 0 { + let mut columns: Vec<(f32, f32)> = cells + .iter() + .take_while(|c| c.row_id == first.row_id) + .map(|c| (c.rect.x + offset, c.rect.w)) + .collect(); + for col in 0..cols { + columns.push((start + col as f32 * 120.0, 120.0)); + } + for row in 0..rows { + let y = last.rect.bottom() + row as f32 * 36.0; + for &(x, w) in &columns { + out.push(FlowRect::new(x, y, w, 36.0)); + } + } + } + out.into_iter() + .filter_map(|r| clip_rect(frame, origin, (left, right, height), r)) + .collect() + } + + #[test] + fn grow_preview_clipped_matches_reference_across_frames() { + struct Case { + name: &'static str, + rows: isize, + cols: isize, + rtl: bool, + origin: (f32, f32), + left: f32, + right: f32, + height: f32, + frame: TablePaintFrame, + } + let cells = make_cells(40, 4); + let first = cells.first().expect("first"); + let last = cells.last().expect("last"); + let cases = [ + Case { + name: "ltr_page_scrolled", + rows: 3, + cols: 5, + rtl: false, + origin: (-80.0, 20.0), + left: 50.0, + right: 760.0, + height: 620.0, + frame: TablePaintFrame::Page(PageViewport { + column_x: 40.0, + scroll_y: 420.0, + height: 620.0, + }), + }, + Case { + name: "rtl_page_scrolled", + rows: 2, + cols: 4, + rtl: true, + origin: (-40.0, 10.0), + left: 0.0, + right: 900.0, + height: 500.0, + frame: TablePaintFrame::Page(PageViewport { + column_x: 20.0, + scroll_y: 300.0, + height: 500.0, + }), + }, + Case { + name: "rotated_active_note", + rows: 4, + cols: 3, + rtl: false, + origin: (10.0, 15.0), + left: 20.0, + right: 880.0, + height: 700.0, + frame: TablePaintFrame::Note { + transform: OverlayScreenTransform { + origin: (60.0, 80.0), + pivot: (300.0, 400.0), + scale: 1.25, + rotate_deg: 17.5, + }, + vp_origin: (10.0, 15.0), + width: 880.0, + height: 700.0, + }, + }, + ]; + for c in cases { + let mut got = Vec::new(); + collect_grow_preview_rects( + &cells, + c.rows, + c.cols, + c.rtl, + c.frame, + c.origin, + (c.left, c.right, c.height), + &mut got, + ); + let want = reference_grow_preview( + &cells, first, last, c.rows, c.cols, c.rtl, c.frame, c.origin, c.left, c.right, + c.height, + ); + assert_eq!(got, want, "case {} mismatch", c.name); + } + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs index 69415b07e7..5bf2d8f74e 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs @@ -134,7 +134,6 @@ impl PlaygroundView { let col_id = c_hit.column_id.clone(); let col_w = c_hit.rect.w; let is_dragging = active_drag.is_some(); - let snap_id = SharedString::from(format!("overlay.table_col_resize.{col_id}")); let guide_color = if is_dragging { active_blue } else { @@ -185,7 +184,10 @@ impl PlaygroundView { .flex() .items_center() .justify_center() - .snapshot(snap_id, Some("root.canvas")) + .snapshot( + format_args!("overlay.table_col_resize.{}", c_hit.column_id), + Some("root.canvas"), + ) .child(div().w(px(2.0)).h(px(table_vis_h)).bg(guide_color)), ), ); @@ -205,7 +207,7 @@ impl PlaygroundView { let bid_owned = active_block_id.to_string(); let make_add_bar = |id: &'static str, - snap: &'static str, + snap_suffix: &'static str, rect: FlowRect, cursor: CursorStyle, kind: TableAddDragKind, @@ -267,7 +269,10 @@ impl PlaygroundView { .flex() .items_center() .justify_center() - .snapshot(snap, Some("root.canvas")) + .snapshot( + format_args!("overlay.table_hover.{snap_suffix}"), + Some("root.canvas"), + ) .snapshot_text("+") .child("+"), ) @@ -298,7 +303,7 @@ impl PlaygroundView { { layer = layer.child(make_add_bar( "tbl-hover-add-col", - "overlay.table_hover.add_col", + "add_col", FlowRect::new(table_screen_right + 2.0, vis_top, 16.0, table_vis_h), CursorStyle::ResizeLeftRight, TableAddDragKind::Column, @@ -311,7 +316,7 @@ impl PlaygroundView { { layer = layer.child(make_add_bar( "tbl-hover-add-row", - "overlay.table_hover.add_row", + "add_row", FlowRect::new( table_screen_left, table_screen_bottom + 2.0, @@ -329,7 +334,7 @@ impl PlaygroundView { { layer = layer.child(make_add_bar( "tbl-hover-add-corner", - "overlay.table_hover.add_corner", + "add_corner", FlowRect::new( table_screen_right + 2.0, table_screen_bottom + 2.0, @@ -378,7 +383,7 @@ impl PlaygroundView { .font_weight(FontWeight::MEDIUM) .text_color(tip_fg) .snapshot("overlay.table_hover.drag_tip", Some("root.canvas")) - .snapshot_text(tip.clone()) + .snapshot_text(&tip) .child(tip), ); } @@ -589,7 +594,7 @@ impl PlaygroundView { cx.notify(); })) .snapshot( - SharedString::from(format!("overlay.table_toolbar.axis_menu.{snap}")), + format_args!("overlay.table_toolbar.axis_menu.{snap}"), Some("overlay.table_toolbar.axis_menu"), ) .snapshot_text(label) @@ -630,7 +635,10 @@ impl PlaygroundView { cx.notify(); } })) - .snapshot("overlay.table_toolbar.axis_menu", Some("root.canvas")) + .snapshot( + format_args!("overlay.table_toolbar.axis_menu"), + Some("root.canvas"), + ) .child( div() .px(px(8.0)) @@ -640,117 +648,148 @@ impl PlaygroundView { .text_color(palette.text_secondary) .child("Background color"), ) - .child(self.table_axis_swatches(is_row, palette, cx)) + .child(table_axis_swatches(is_row, palette, cx)) .child(menu_horizontal_separator(palette)) - .child(action_row( - "tbl-axis-insert-before", - "insert_before", - "PlusIcon", - if is_row { - "Insert Above" - } else { - "Insert Left" - }, - false, - Box::new(move |this, win, cx| { - if is_row { - let _ = this.table_insert_row_before(win, cx); - } else { - let _ = this.table_insert_column_before(win, cx); - } - }), - )) - .child(action_row( - "tbl-axis-insert-after", - "insert_after", - "PlusIcon", - if is_row { - "Insert Below" - } else { - "Insert Right" - }, - false, - Box::new(move |this, win, cx| { - if is_row { - let _ = this.table_insert_row_after(win, cx); - } else { - let _ = this.table_insert_column_after(win, cx); - } - }), - )) - .child(action_row( - "tbl-axis-earlier", - "move_earlier", - if is_row { - "ArrowUpBigIcon" - } else { - "MoveLeftIcon" - }, - if is_row { "Move Up" } else { "Move Left" }, - false, - Box::new(move |this, win, cx| { - let _ = this.table_move_axis(is_row, true, win, cx); - }), - )) - .child(action_row( - "tbl-axis-later", - "move_later", - if is_row { - "ArrowDownBigIcon" - } else { - "MoveRightIcon" - }, - if is_row { "Move Down" } else { "Move Right" }, - false, - Box::new(move |this, win, cx| { - let _ = this.table_move_axis(is_row, false, win, cx); - }), - )) - .child(action_row( - "tbl-axis-duplicate", - "duplicate", - "DuplicateIcon", - if is_row { - "Duplicate row" - } else { - "Duplicate column" - }, - false, - Box::new(move |this, win, cx| this.duplicate_table_axis(is_row, win, cx)), - )) - .child(menu_horizontal_separator(palette)) - .child(action_row( - "tbl-axis-clear", - "clear", - "MinusIcon", - if is_row { - "Clear row contents" - } else { - "Clear column contents" - }, - false, - Box::new(move |this, win, cx| { - let _ = this.table_clear_axis(is_row, win, cx); - }), - )) - .child(action_row( - "tbl-axis-delete", - "delete", - "DeleteIcon", - if is_row { - "Delete Row" - } else { - "Delete Column" - }, - true, - Box::new(move |this, win, cx| { - if is_row { - let _ = this.table_delete_focused_row(win, cx); - } else { - let _ = this.table_delete_focused_column(win, cx); - } - }), - )) + .children({ + let pick = |r, c| if is_row { r } else { c }; + let row = |op: usize, id, snap, icon, label, danger| { + let cb = Box::new( + move |t: &mut PlaygroundView, + w: &mut Window, + c: &mut ui::Context| match ( + op, is_row, + ) { + (0, true) => _ = t.table_insert_row_before(w, c), + (0, false) => _ = t.table_insert_column_before(w, c), + (1, true) => _ = t.table_insert_row_after(w, c), + (1, false) => _ = t.table_insert_column_after(w, c), + (2, _) => _ = t.table_move_axis(is_row, true, w, c), + (3, _) => _ = t.table_move_axis(is_row, false, w, c), + (4, _) => t.duplicate_table_axis(is_row, w, c), + (5, _) => _ = t.table_clear_axis(is_row, w, c), + (6, true) => _ = t.table_delete_focused_row(w, c), + (6, false) => _ = t.table_delete_focused_column(w, c), + _ => {} + }, + ); + action_row(id, snap, icon, label, danger, cb).into_any_element() + }; + [ + row( + 0, + "tbl-axis-insert-before", + "insert_before", + "PlusIcon", + pick("Insert Above", "Insert Left"), + false, + ), + row( + 1, + "tbl-axis-insert-after", + "insert_after", + "PlusIcon", + pick("Insert Below", "Insert Right"), + false, + ), + row( + 2, + "tbl-axis-earlier", + "move_earlier", + pick("ArrowUpBigIcon", "MoveLeftIcon"), + pick("Move Up", "Move Left"), + false, + ), + row( + 3, + "tbl-axis-later", + "move_later", + pick("ArrowDownBigIcon", "MoveRightIcon"), + pick("Move Down", "Move Right"), + false, + ), + row( + 4, + "tbl-axis-duplicate", + "duplicate", + "DuplicateIcon", + pick("Duplicate row", "Duplicate column"), + false, + ), + menu_horizontal_separator(palette).into_any_element(), + row( + 5, + "tbl-axis-clear", + "clear", + "MinusIcon", + pick("Clear row contents", "Clear column contents"), + false, + ), + row( + 6, + "tbl-axis-delete", + "delete", + "DeleteIcon", + pick("Delete Row", "Delete Column"), + true, + ), + ] + }) .into_any_element() } } + +fn table_axis_swatches( + is_row: bool, + palette: &Palette, + cx: &ui::Context, +) -> ui::Div { + const SWATCHES: [(&str, &str, Option<&str>, u32); 6] = [ + ("Default", "default", None, 0xffffff), + ( + "Gray", + "gray", + Some("var(--affine-background-secondary-color)"), + 0xefeff0, + ), + ("Blue", "blue", Some("var(--affine-tag-blue)"), 0xdbeafe), + ("Green", "green", Some("var(--affine-tag-green)"), 0xdcfce7), + ( + "Yellow", + "yellow", + Some("var(--affine-tag-yellow)"), + 0xfef9c3, + ), + ("Red", "red", Some("var(--affine-tag-red)"), 0xfee2e2), + ]; + SWATCHES.into_iter().fold( + div() + .flex() + .items_center() + .gap(px(4.0)) + .px(px(6.0)) + .py(px(4.0)), + |row, (name, slug, css_var, hex)| { + row.child( + div() + .id(SharedString::from(format!("tbl-bg-{name}"))) + .flex_none() + .w(px(24.0)) + .h(px(24.0)) + .rounded(px(4.0)) + .bg(ui::rgb(hex)) + .border_1() + .border_color(palette.border) + .cursor_pointer() + .on_mouse_down(ui::MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(move |this, _, win, cx| { + let _ = this.table_set_axis_background(is_row, css_var, win, cx); + })) + .snapshot( + format_args!("overlay.table_toolbar.axis_menu.bg_{slug}"), + Some("overlay.table_toolbar.axis_menu"), + ) + .snapshot_text(name), + ) + }, + ) +} diff --git a/packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs b/packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs index 92dc819d14..4cdf2d7f84 100644 --- a/packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs +++ b/packages/frontend/hosts/web/tests/check-snapshot-prefixes.test.mjs @@ -188,6 +188,30 @@ await test('fails on passive data segment hit', () => { ]); }); +await test('catches bare container IDs and Slice 9A ratchet prefixes', () => { + const wasm = buildWasm([ + buildDataSection([ + { + mode: 0, + offset: 0, + data: 'overlay.bookmark_toolbar\0overlay.table_hover.add_col\0chrome.edgeless_element_toolbar.opacity\0edgeless.handle.rotate_ne', + }, + ]), + ]); + + const result = scanWasmDataPrefixes(wasm); + assert.equal(result.ok, false); + assert.deepEqual( + result.hits.map(hit => hit.prefix), + [ + 'overlay.bookmark_toolbar', + 'overlay.table_hover.', + 'chrome.edgeless_element_toolbar.', + 'edgeless.handle.rotate_', + ] + ); +}); + await test('ignores matching strings in custom sections', () => { const wasm = buildWasm([ buildCustomSection( diff --git a/packages/frontend/scripts/check-snapshot-prefixes.mjs b/packages/frontend/scripts/check-snapshot-prefixes.mjs index 199cdcc385..7ed3c8d187 100644 --- a/packages/frontend/scripts/check-snapshot-prefixes.mjs +++ b/packages/frontend/scripts/check-snapshot-prefixes.mjs @@ -36,13 +36,25 @@ export const ZERO_IN_PRODUCTION = Object.freeze([ 'overlay.attachment_toolbar.', 'overlay.code_more_menu.', 'overlay.code_lang_picker.item.', - 'overlay.bookmark_toolbar.', - 'overlay.embed_toolbar.', + 'overlay.bookmark_toolbar', + 'overlay.embed_toolbar', 'overlay.format_toolbar.', 'overlay.image_toolbar.', 'overlay.link_popup.', - 'overlay.callout_toolbar.', + 'overlay.callout_toolbar', + 'overlay.callout_icon_picker.', + 'overlay.table_toolbar.axis_menu', + 'overlay.table_col_resize.', + 'overlay.table_hover.', 'overlay.page_scrollbar', + 'page.table_cell_focus', + 'chrome.edgeless_element_toolbar.', + 'chrome.edgeless_toolbar.', + 'chrome.edgeless_zoom.', + 'edgeless.label_format.', + 'edgeless.mindmap.toggle.', + 'edgeless.handle.rotate_', + 'edgeless.selection_box', ]); const WASM_MAGIC = new Uint8Array([0x00, 0x61, 0x73, 0x6d]);