diff --git a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/config.rs b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/config.rs index 87da49262f..9c65fa064a 100644 --- a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/config.rs +++ b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/config.rs @@ -4,13 +4,16 @@ //! top-level items, `moreToolPanel` 8-group layout, `textSubToolbarConfig`, //! `textToolPanel` (`Turn into`), and `showWhen` schema gating. -use super::{ - KeyboardToolbarAction, KeyboardToolbarDateKind, KeyboardToolbarPanel, SlashSurfaceRef, - slash_item_const, -}; +use std::rc::Rc; +use blocksuite_playground_doc::read::{BlockContent, PageSnapshot, SurfaceElementKind}; use ui::SharedString; +use super::{ + KeyboardToolbarAction, KeyboardToolbarDateKind, KeyboardToolbarPanel, SlashCommand, + slash_item_const, surface_ref_key, +}; + /// Whether the current native Page editor registers and supports creating `flavour`. /// Mirrors `std.store.schema.flavourSchemaMap.has(flavour)` in `0.27.5` `config.ts`. pub const fn is_flavour_supported(flavour: &str) -> bool { @@ -418,6 +421,78 @@ pub const MORE_TOOL_PANEL_GROUPS: [ToolPanelGroupSpec; 8] = [ }, ]; +/// Geometry of every docked tool panel, from `0.27.5` `keyboardToolPanelStyles` +/// (`keyboard-toolbar/src/styles.ts`). Scroll limits and painting both read it. +pub(super) mod panel_layout { + /// Panel container padding (`padding: 16px 4px 8px 8px`). + pub const PAD_TOP: f32 = 16.0; + pub const PAD_RIGHT: f32 = 4.0; + pub const PAD_BOTTOM: f32 = 8.0; + pub const PAD_LEFT: f32 = 8.0; + /// Space between groups (`gap: 24px`). + pub const GROUP_GAP: f32 = 24.0; + /// Space between a group header and its first row (`gap: 12px`). + pub const HEADER_GAP: f32 = 12.0; + /// Header font size and line height (`13px` / `18px`). + pub const HEADER_FONT: f32 = 13.0; + pub const HEADER_HEIGHT: f32 = 18.0; + /// `grid-template-columns: repeat(4, minmax(0, 1fr))`. + pub const COLUMNS: usize = 4; + pub const COLUMN_GAP: f32 = 12.0; + pub const ROW_GAP: f32 = 12.0; + /// Button: `16px` padding around a `32px` icon, `4px` radius. + pub const BUTTON_HEIGHT: f32 = 64.0; + pub const BUTTON_RADIUS: f32 = 4.0; + pub const ICON_SIZE: f32 = 32.0; + /// Space between the button and its label (`gap: 4px`). + pub const LABEL_GAP: f32 = 4.0; + /// Label font size and line height (`13px` / `18px`). + pub const LABEL_FONT: f32 = 13.0; + pub const LABEL_HEIGHT: f32 = 18.0; + /// One grid item: button, gap and label. + pub const ITEM_HEIGHT: f32 = BUTTON_HEIGHT + LABEL_GAP + LABEL_HEIGHT; + /// Border of the panel on each side. + const BORDER: f32 = 1.0; + + /// Inner size of the scrolling list of a `panel_w` x `panel_h` panel. + pub fn list_size(panel_w: f32, panel_h: f32) -> (f32, f32) { + ( + (panel_w - PAD_LEFT - PAD_RIGHT - BORDER * 2.0).max(120.0), + (panel_h - PAD_TOP - PAD_BOTTOM - BORDER * 2.0).max(80.0), + ) + } + + /// Width of one grid column in a list `inner_w` wide. + pub fn tile_width(inner_w: f32) -> f32 { + ((inner_w - COLUMN_GAP * (COLUMNS as f32 - 1.0)) / COLUMNS as f32).floor() + } + + /// Offset of grid item `index` from the top-left corner of its group's first row. + pub fn item_offset(index: usize, tile_w: f32) -> (f32, f32) { + let (row, col) = (index / COLUMNS, index % COLUMNS); + ( + col as f32 * (tile_w + COLUMN_GAP), + row as f32 * (ITEM_HEIGHT + ROW_GAP), + ) + } + + /// Height of one group with `count` items: header, header gap and rows. + pub fn group_height(count: usize) -> f32 { + let rows = count.div_ceil(COLUMNS) as f32; + HEADER_HEIGHT + HEADER_GAP + rows * ITEM_HEIGHT + (rows - 1.0).max(0.0) * ROW_GAP + } + + /// Height of a list of non-empty groups with the given item counts. + pub fn content_height(counts: impl IntoIterator) -> f32 { + counts + .into_iter() + .enumerate() + .map(|(idx, count)| group_height(count) + if idx > 0 { GROUP_GAP } else { 0.0 }) + .sum() + } +} + +/// One grid item of a docked tool panel. pub(super) struct ToolPanelTile<'a> { pub id: &'a str, pub name: SharedString, @@ -436,40 +511,107 @@ impl<'a> From<&'a ToolbarActionSpec> for ToolPanelTile<'a> { } } -impl<'a> From<&'a SlashSurfaceRef> for ToolPanelTile<'a> { - fn from(target: &'a SlashSurfaceRef) -> Self { +/// A `Frame: ` or `Group: <title>` item of `Document Group&Frame`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DocTargetTile { + /// Item id (`frame_<id>` or `group_<id>`), as in the slash menu. + pub row_id: String, + pub name: SharedString, + pub icon: &'static str, + pub action: KeyboardToolbarAction, +} + +impl<'a> From<&'a DocTargetTile> for ToolPanelTile<'a> { + fn from(target: &'a DocTargetTile) -> Self { Self { id: &target.row_id, - name: target.title.clone().into(), + name: target.name.clone(), icon: target.icon, - action: KeyboardToolbarAction::Slash(target.command()), + action: target.action, } } } -pub(super) fn more_tool_tiles<'a>( - targets: &'a [SlashSurfaceRef], +fn doc_target(prefix: &str, id: &str, title: &str, icon: &'static str) -> DocTargetTile { + let kind = if prefix == "frame" { "Frame" } else { "Group" }; + DocTargetTile { + row_id: format!("{prefix}_{id}"), + name: format!("{kind}: {title}").into(), + icon, + action: KeyboardToolbarAction::Slash(SlashCommand::SurfaceRef(surface_ref_key(id))), + } +} + +/// `documentGroupFrameToolGroup` (`config.ts:697-750`): the frames in document order +/// (`store.getBlocksByFlavour('affine:frame')`), then the groups in surface order +/// (`getElementsByType('group')`). One walk of the snapshot, no canvas geometry. +pub fn document_group_frame_tiles(snapshot: &PageSnapshot) -> Rc<[DocTargetTile]> { + let mut frames = Vec::new(); + let mut groups = Vec::new(); + let reachable = snapshot.root.iter().map(|node| (node, true)); + let detached = snapshot.detached.iter().map(|node| (node, false)); + for (tree, is_root) in reachable.chain(detached) { + for node in tree.walk() { + match &node.content { + BlockContent::Frame { title, .. } => { + frames.push(doc_target("frame", &node.id, &title.plain, "FrameIcon")); + } + BlockContent::Surface { elements, .. } if is_root => { + groups.extend(elements.iter().filter_map(|element| { + let SurfaceElementKind::Group { title, .. } = &element.kind else { + return None; + }; + Some(doc_target( + "group", + &element.id, + &title.plain, + "GroupingIcon", + )) + })); + } + _ => {} + } + } + } + frames.extend(groups); + frames.into() +} + +/// The non-empty `moreToolPanel` groups with their visible items, borrowing the static +/// tables and the cached `targets` without copying them. +pub(super) fn more_tool_groups<'a>( + targets: &'a [DocTargetTile], can_pick_images: bool, can_pick_attachments: bool, database_readonly: bool, -) -> impl Iterator<Item = (ToolPanelGroupSpec, Vec<ToolPanelTile<'a>>)> { - MORE_TOOL_PANEL_GROUPS.into_iter().filter_map(move |group| { - let tiles: Vec<_> = match group.id { - "doc_group_frame" => targets.iter().map(ToolPanelTile::from).collect(), - "database" if database_readonly => return None, - _ => group +) -> impl Iterator< + Item = ( + ToolPanelGroupSpec, + impl Iterator<Item = ToolPanelTile<'a>> + Clone, + ), +> { + MORE_TOOL_PANEL_GROUPS + .into_iter() + .filter(move |group| !(database_readonly && group.id == "database")) + .map(move |group| { + let dynamic = if group.id == "doc_group_frame" { + targets + } else { + &[] + }; + let tiles = group .items .iter() - .filter(|item| { + .filter(move |item| { item.is_visible_for(can_pick_images) && (item.action != KeyboardToolbarAction::Attachment || can_pick_attachments) }) .map(ToolPanelTile::from) - .collect(), - }; - (!tiles.is_empty()).then_some((group, tiles)) - }) + .chain(dynamic.iter().map(ToolPanelTile::from)); + (group, tiles) + }) + .filter(|(_, tiles)| tiles.clone().next().is_some()) } /// `textSubToolbarConfig.items` (`config.ts:1056-1071`). diff --git a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs index 6ba91dfcb9..7816c19e61 100644 --- a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs +++ b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs @@ -8,16 +8,21 @@ //! 8-group `+` insert panel, `Turn into` panel, and 9-color `Highlight` panel. mod config; +mod panels; mod render; +use std::rc::Rc; + +use blocksuite_playground_doc::read::PageSnapshot; + pub use config::{ - DEFAULT_KEYBOARD_TOOLBAR_ITEMS, MORE_TOOL_PANEL_GROUPS, TEXT_SUB_TOOLBAR_ITEMS, + DEFAULT_KEYBOARD_TOOLBAR_ITEMS, DocTargetTile, MORE_TOOL_PANEL_GROUPS, TEXT_SUB_TOOLBAR_ITEMS, TURN_INTO_PANEL_ITEMS, ToolPanelGroupSpec, ToolbarActionSpec, ToolbarItemSpec, - is_flavour_supported, + document_group_frame_tiles, is_flavour_supported, }; -use super::{Overlays, SlashCommand, SlashSurfaceRef, slash_item_const, slash_surface_refs}; -use config::more_tool_tiles; +use super::{Overlays, SlashCommand, slash::surface_ref_key, slash_item_const}; +use config::{more_tool_groups, panel_layout}; /// Minimum touch target dimension for every mobile keyboard toolbar button (44x44 pt). pub const KEYBOARD_TOOLBAR_BUTTON: f32 = 44.0; @@ -357,6 +362,18 @@ pub struct KeyboardToolbarCapabilities { pub can_pick_attachments: bool, pub has_body_selection: bool, pub has_non_collapsed_selection: bool, + /// Host revision of the shown `PageSnapshot`. With `PageSnapshot::doc_id` it keys the + /// cached `Document Group&Frame` items, so a new revision or document reads them again. + pub snapshot_rev: u64, +} + +/// `Document Group&Frame` items of one snapshot revision, shared by the `More` panel +/// scroll limit and its painting. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct DocTargetsCache { + doc_id: String, + snapshot_rev: u64, + tiles: Rc<[DocTargetTile]>, } /// Complete state of the mobile `KeyboardToolbar` owned by [`Overlays`]. @@ -370,6 +387,13 @@ pub struct KeyboardToolbarState { pub panel_scroll: f32, pub marks_disabled: bool, pub capabilities: KeyboardToolbarCapabilities, + doc_targets: Option<DocTargetsCache>, +} + +/// Height of the docked tool panel in a window `win_h` tall above the keyboard. +fn tool_panel_height(win_h: f32) -> f32 { + let max_panel = (win_h - crate::TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0); + KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor() } impl KeyboardToolbarState { @@ -542,9 +566,7 @@ impl Overlays { let panel_height = if !self.keyboard_toolbar.marks_disabled && self.keyboard_toolbar.active_panel.is_some() { - let max_panel = - (win_h - crate::TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0); - KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor() + tool_panel_height(win_h) } else { 0.0 }; @@ -568,9 +590,7 @@ impl Overlays { let panel_height = if !self.keyboard_toolbar.marks_disabled && self.keyboard_toolbar.active_panel.is_some() { - let max_panel = - (win_h - crate::TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0); - KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor() + tool_panel_height(win_h) } else { 0.0 }; @@ -636,64 +656,54 @@ impl Overlays { let win_h = (scene.window.1 - scene.bottom_inset.max(0.0)) .max(crate::TOPBAR_HEIGHT) .floor(); - let max_panel = (win_h - crate::TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0); - let panel_height = KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor(); - let pad_x = if width <= 340.0 { 8.0 } else { 12.0 }; - let inner_w = (width - pad_x * 2.0 - 2.0).max(120.0); - let list_h = (panel_height - 16.0 - 2.0).max(80.0); - let cols: usize = ((inner_w + 6.0) / (KEYBOARD_TOOLBAR_BUTTON + 6.0)) - .floor() - .clamp(3.0, 5.0) as usize; - let header_h = 18.0; - let tile_row_h = KEYBOARD_TOOLBAR_BUTTON + 14.0; - let row_gap = 4.0; - let group_gap = 8.0; + let (_, list_h) = panel_layout::list_size(width, tool_panel_height(win_h)); let can_pick_images = self.keyboard_toolbar.capabilities.can_pick_images; - let mut cursor_y = 0.0_f32; - match panel { + let content_h = match panel { KeyboardToolbarPanel::More => { - let mut first = true; - let targets = slash_surface_refs(scene.snapshot); - for (_, tiles) in more_tool_tiles( - &targets, - can_pick_images, - self.keyboard_toolbar.capabilities.can_pick_attachments, - self.database_readonly, - ) { - let count = tiles.len(); - if !first { - cursor_y += group_gap; - } - first = false; - cursor_y += header_h + row_gap; - cursor_y += (count.div_ceil(cols) as f32) * (tile_row_h + row_gap); - } - } - KeyboardToolbarPanel::TurnInto => { - let count = TURN_INTO_PANEL_ITEMS - .iter() - .filter(|i| i.is_visible_for(can_pick_images)) - .count(); - cursor_y += header_h + row_gap; - cursor_y += (count.div_ceil(cols) as f32) * (tile_row_h + row_gap); + let targets = self.keyboard_doc_targets(scene.snapshot); + panel_layout::content_height( + more_tool_groups( + &targets, + can_pick_images, + self.keyboard_toolbar.capabilities.can_pick_attachments, + self.database_readonly, + ) + .map(|(_, tiles)| tiles.count()), + ) } + KeyboardToolbarPanel::TurnInto => panel_layout::content_height([TURN_INTO_PANEL_ITEMS + .iter() + .filter(|i| i.is_visible_for(can_pick_images)) + .count()]), KeyboardToolbarPanel::Highlight => { - for idx in 0..2 { - if idx > 0 { - cursor_y += group_gap; - } - cursor_y += header_h + row_gap; - cursor_y += - (HighlightColor::ALL.len().div_ceil(cols) as f32) * (tile_row_h + row_gap); - } + panel_layout::content_height([HighlightColor::ALL.len(); 2]) } - } - let max_scroll = (cursor_y - list_h).max(0.0); + }; + let max_scroll = (content_h - list_h).max(0.0); self.keyboard_toolbar.panel_scroll = (self.keyboard_toolbar.panel_scroll - delta_y).clamp(0.0, max_scroll); true } + /// `Document Group&Frame` items of `snapshot`, read again only when the document or the + /// host snapshot revision changes. + pub(super) fn keyboard_doc_targets(&mut self, snapshot: &PageSnapshot) -> Rc<[DocTargetTile]> { + let snapshot_rev = self.keyboard_toolbar.capabilities.snapshot_rev; + if let Some(cache) = &self.keyboard_toolbar.doc_targets + && cache.snapshot_rev == snapshot_rev + && cache.doc_id == snapshot.doc_id + { + return cache.tiles.clone(); + } + let tiles = document_group_frame_tiles(snapshot); + self.keyboard_toolbar.doc_targets = Some(DocTargetsCache { + doc_id: snapshot.doc_id.clone(), + snapshot_rev, + tiles: tiles.clone(), + }); + tiles + } + /// Scroll an open keyboard tool panel when `(x, y)` lies inside its docked rect. pub(super) fn scroll_keyboard_tool_panel( &mut self, @@ -712,8 +722,7 @@ impl Overlays { let win_h = (scene.window.1 - scene.bottom_inset.max(0.0)) .max(crate::TOPBAR_HEIGHT) .floor(); - let max_panel = (win_h - crate::TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0); - let panel_height = KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor(); + let panel_height = tool_panel_height(win_h); let top = (win_h - (KEYBOARD_TOOLBAR_HEIGHT + panel_height)) .max(crate::TOPBAR_HEIGHT) .floor(); @@ -729,6 +738,10 @@ impl Overlays { #[cfg(test)] mod tests { + use blocksuite_playground_doc::read::{ + BlockContent, BlockNode, RichText, SurfaceElement, SurfaceElementKind, + }; + use super::*; use crate::overlays::slash_item_by_id; @@ -790,32 +803,120 @@ mod tests { assert!(db.items.iter().all(ToolbarActionSpec::is_visible)); } - #[test] - fn more_panel_filters_missing_targets_and_unavailable_insertions() { - let target = SlashSurfaceRef { - row_id: "group_demo".into(), - title: "Group: Demo".into(), - icon: "GroupingIcon", - reference: "demo".into(), - ref_flavour: "group", - }; - let visible = - more_tool_tiles(std::slice::from_ref(&target), true, true, false).collect::<Vec<_>>(); - let group = |id| visible.iter().find(|(group, _)| group.id == id).unwrap(); - assert_eq!(group("embeds").1.len(), 6); - assert_eq!(group("database").1.len(), 2); - assert_eq!( - group("doc_group_frame").1[0].action, - KeyboardToolbarAction::Slash(target.command()), - ); - assert!( - group("content_media") - .1 - .iter() - .any(|tile| tile.id == "attachment") - ); + fn frame_node(id: &str, title: &str, presentation: &str) -> BlockNode { + let mut props = std::collections::BTreeMap::new(); + props.insert("prop:presentationIndex".into(), presentation.into()); + BlockNode { + id: id.into(), + flavour: "affine:frame".into(), + version: None, + content: BlockContent::Frame { + title: RichText { + plain: title.into(), + ..Default::default() + }, + xywh: "[0,0,100,100]".into(), + }, + props, + children: Vec::new(), + } + } - let restricted = more_tool_tiles(&[], false, false, true).collect::<Vec<_>>(); + fn group_element(id: &str, title: &str) -> SurfaceElement { + SurfaceElement { + id: id.into(), + index: "a0".into(), + hidden: false, + locked_by_self: false, + seed: 0, + rotate: 0.0, + props: Default::default(), + kind: SurfaceElementKind::Group { + title: RichText { + plain: title.into(), + ..Default::default() + }, + children: Vec::new(), + }, + } + } + + /// A page whose surface holds `frames` (in write order) and `groups`. + fn page_with(doc_id: &str, frames: &[(&str, &str)], groups: &[(&str, &str)]) -> PageSnapshot { + let surface = BlockNode { + id: "surface".into(), + flavour: "affine:surface".into(), + version: None, + content: BlockContent::Surface { + element_count: groups.len(), + elements: groups.iter().map(|(id, t)| group_element(id, t)).collect(), + }, + props: Default::default(), + // Presentation indices run against write order: Web lists frames by write order. + children: frames + .iter() + .enumerate() + .map(|(idx, (id, t))| frame_node(id, t, &format!("a{}", frames.len() - idx))) + .collect(), + }; + PageSnapshot { + doc_id: doc_id.into(), + root: Some(BlockNode { + id: "root".into(), + flavour: "affine:page".into(), + version: None, + content: BlockContent::Page { + title: Default::default(), + }, + props: Default::default(), + children: vec![surface], + }), + detached: Vec::new(), + } + } + + fn names(tiles: &[DocTargetTile]) -> Vec<&str> { + tiles.iter().map(|tile| tile.name.as_ref()).collect() + } + + #[test] + fn document_group_frame_tiles_list_frames_in_write_order_then_groups() { + for (frames, groups, expected) in [ + ( + [("f1", "One"), ("f2", "Two")], + [("g1", "Alpha")], + ["Frame: One", "Frame: Two", "Group: Alpha"], + ), + ( + [("f2", "Two"), ("f1", "One")], + [("g1", "Alpha")], + ["Frame: Two", "Frame: One", "Group: Alpha"], + ), + ] { + let tiles = document_group_frame_tiles(&page_with("doc", &frames, &groups)); + assert_eq!(names(&tiles), expected); + let first = &frames[0].0; + assert_eq!(tiles[0].row_id, format!("frame_{first}")); + assert_eq!( + tiles[0].action, + KeyboardToolbarAction::Slash(SlashCommand::SurfaceRef(surface_ref_key(first))) + ); + } + } + + #[test] + fn more_panel_groups_borrow_targets_and_hide_unavailable_insertions() { + let tiles = document_group_frame_tiles(&page_with("doc", &[], &[("demo", "Demo")])); + let visible = more_tool_groups(&tiles, true, true, false) + .map(|(group, tiles)| (group.id, tiles.map(|t| t.id).collect::<Vec<_>>())) + .collect::<Vec<_>>(); + let group = |id| &visible.iter().find(|(group, _)| *group == id).unwrap().1; + assert_eq!(group("embeds").len(), 6); + assert_eq!(group("database").len(), 2); + assert_eq!(group("doc_group_frame"), &["group_demo"]); + assert!(group("content_media").contains(&"attachment")); + + let restricted = more_tool_groups(&[], false, false, true).collect::<Vec<_>>(); assert!( !restricted .iter() @@ -823,12 +924,66 @@ mod tests { ); assert!( !restricted - .iter() + .into_iter() .flat_map(|(_, tiles)| tiles) .any(|tile| matches!(tile.id, "image" | "attachment")) ); } + #[test] + fn panel_layout_has_four_columns_and_web_gaps_at_every_width() { + use panel_layout::*; + for (width, tile_w) in [(320.0, 67.0), (390.0, 85.0), (568.0, 129.0)] { + let (inner_w, _) = list_size(width, KEYBOARD_TOOL_PANEL_HEIGHT); + assert_eq!(tile_width(inner_w), tile_w, "{width}px"); + assert_eq!(item_offset(3, tile_w), (3.0 * (tile_w + 12.0), 0.0)); + assert_eq!(item_offset(4, tile_w), (0.0, 86.0 + 12.0)); + assert!(item_offset(3, tile_w).0 + tile_w <= inner_w, "{width}px"); + } + // Header, header gap, two rows; then a group gap and a one-row group. + assert_eq!(group_height(5), 18.0 + 12.0 + 86.0 * 2.0 + 12.0); + assert_eq!( + content_height([5, 1]), + group_height(5) + 24.0 + 18.0 + 12.0 + 86.0 + ); + } + + #[test] + fn more_panel_targets_stay_cached_until_revision_or_document_changes() { + let frames: Vec<(String, String)> = (0..128) + .map(|i| (format!("f{i}"), format!("Frame {i}"))) + .collect(); + let refs: Vec<(&str, &str)> = frames + .iter() + .map(|(id, t)| (id.as_str(), t.as_str())) + .collect(); + let page = page_with("doc-a", &refs, &[]); + let mut renamed = refs.clone(); + renamed[0].1 = "Renamed"; + let renamed = page_with("doc-a", &renamed, &[]); + let other_doc = page_with("doc-b", &refs[..1], &[]); + + let mut overlays = Overlays::new(); + let set_rev = |overlays: &mut Overlays, snapshot_rev| { + overlays.set_keyboard_toolbar_capabilities(KeyboardToolbarCapabilities { + snapshot_rev, + ..Default::default() + }) + }; + set_rev(&mut overlays, 1); + let first = overlays.keyboard_doc_targets(&page); + assert_eq!(first.len(), 128); + // Scroll frames and paint passes of one revision share one read of the page. + for _ in 0..4 { + assert!(Rc::ptr_eq(&first, &overlays.keyboard_doc_targets(&page))); + } + set_rev(&mut overlays, 2); + let after_rename = overlays.keyboard_doc_targets(&renamed); + assert_eq!(after_rename[0].name.as_ref(), "Frame: Renamed"); + let switched = overlays.keyboard_doc_targets(&other_doc); + assert_eq!(names(&switched), ["Frame: Frame 0"]); + } + #[test] fn slash_backed_toolbar_items_reuse_slash_items_definitions() { for (slash_id, expected_action) in [ diff --git a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/panels.rs b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/panels.rs new file mode 100644 index 0000000000..0353f0ba28 --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/panels.rs @@ -0,0 +1,316 @@ +//! Painting for the docked tool panels of `KeyboardToolbar`: the `+` insert panel, +//! `Turn into`, and the `Highlight` swatches. All three use the `0.27.5` four-column +//! grid of `keyboardToolPanelStyles` and paint only the rows inside the viewport. + +use ui::{AnyElement, ClickEvent, Context, FontWeight, Hsla, SharedString, div, prelude::*, px}; + +use crate::{ + block_flow::FlowRect, + overlays::{ + OverlayEvent, OverlayHost, Overlays, + paint_page::{emit, icon}, + }, + theme::Palette, +}; + +use super::{ + DocTargetTile, HighlightColor, KeyboardToolbarAction, KeyboardToolbarPanel, + TURN_INTO_PANEL_ITEMS, + config::{ToolPanelTile, panel_layout as layout}, + more_tool_groups, + render::image_icon_glyph, +}; + +/// The scrolled list that groups are painted into. +struct PanelList { + list: ui::Div, + inner_w: f32, + list_h: f32, + tile_w: f32, + scroll: f32, + cursor_y: f32, +} + +impl PanelList { + /// Whether a band from `top` to `top + h` (in list coordinates) is fully visible. + fn fully_visible(&self, top: f32, h: f32) -> bool { + top >= 0.0 && top + h <= self.list_h + } + + fn intersects(&self, top: f32, h: f32) -> bool { + top + h > 0.0 && top < self.list_h + } +} + +impl Overlays { + pub(super) fn render_tool_panel<V: OverlayHost>( + &self, + panel: KeyboardToolbarPanel, + rect: FlowRect, + targets: &[DocTargetTile], + palette: &Palette, + cx: &mut Context<V>, + ) -> ui::Stateful<ui::Div> { + let (inner_w, list_h) = layout::list_size(rect.w, rect.h); + let mut list = PanelList { + list: div() + .relative() + .flex_none() + .w(px(inner_w)) + .h(px(list_h)) + .overflow_hidden(), + inner_w, + list_h, + tile_w: layout::tile_width(inner_w), + scroll: self.keyboard_toolbar.panel_scroll.max(0.0), + cursor_y: 0.0, + }; + let can_pick_images = self.keyboard_toolbar.capabilities.can_pick_images; + match panel { + KeyboardToolbarPanel::More => { + for (group, tiles) in more_tool_groups( + targets, + can_pick_images, + self.keyboard_toolbar.capabilities.can_pick_attachments, + self.database_readonly, + ) { + paint_group(&mut list, group.id, group.name, tiles, palette, cx); + } + } + KeyboardToolbarPanel::TurnInto => { + let tiles = TURN_INTO_PANEL_ITEMS + .iter() + .filter(|i| i.is_visible_for(can_pick_images)) + .map(ToolPanelTile::from); + paint_group(&mut list, "turn_into", "Turn into", tiles, palette, cx); + } + KeyboardToolbarPanel::Highlight => { + let groups: [(_, _, fn(HighlightColor) -> KeyboardToolbarAction); 2] = [ + ("color", "Color", KeyboardToolbarAction::SetTextColor), + ( + "background", + "Background", + KeyboardToolbarAction::SetBgColor, + ), + ]; + for (group_id, title, action) in groups { + let tiles = HighlightColor::ALL.into_iter().map(|color| ToolPanelTile { + id: color.id(), + name: color.label().into(), + icon: "", + action: action(color), + }); + paint_group(&mut list, group_id, title, tiles, palette, cx); + } + } + } + let PanelList { + list: mut body, + cursor_y: content_h, + scroll, + .. + } = list; + if content_h > list_h { + let thumb_h = (list_h * list_h / content_h).max(24.0).round(); + let max_scroll = (content_h - list_h).max(1.0); + let thumb_top = ((list_h - thumb_h) * (scroll / max_scroll).clamp(0.0, 1.0)).round(); + body = body.child( + div() + .absolute() + .left(px(inner_w - 3.0)) + .top(px(thumb_top)) + .w(px(3.0)) + .h(px(thumb_h)) + .rounded(px(1.5)) + .bg(palette.text_secondary.opacity(0.35)), + ); + } + + div() + .id("keyboard-tool-panel") + .flex_none() + .w(px(rect.w)) + .h(px(rect.h)) + .pt(px(layout::PAD_TOP)) + .pr(px(layout::PAD_RIGHT)) + .pb(px(layout::PAD_BOTTOM)) + .pl(px(layout::PAD_LEFT)) + .bg(palette.background) + .border_1() + .border_color(palette.border) + .overflow_hidden() + .occlude() + .on_scroll(emit(cx, |ev: &ui::ScrollEvent| { + OverlayEvent::KeyboardToolbarPanelScroll(f32::from( + ev.delta.pixel_delta(px(20.0)).y, + )) + })) + .snapshot("overlay.keyboard_toolbar.panel", Some("root.canvas")) + .child(body) + } +} + +/// Paint one group header and its grid at the list cursor, then move the cursor past it. +fn paint_group<'a, V: OverlayHost>( + list: &mut PanelList, + group_id: &'static str, + title: &'static str, + tiles: impl Iterator<Item = ToolPanelTile<'a>>, + palette: &Palette, + cx: &mut Context<V>, +) { + if list.cursor_y > 0.0 { + list.cursor_y += layout::GROUP_GAP; + } + let header_top = list.cursor_y - list.scroll; + let mut body = std::mem::replace(&mut list.list, div()); + if list.intersects(header_top, layout::HEADER_HEIGHT) { + body = body.child( + div() + .absolute() + .left(px(0.0)) + .top(px(header_top)) + .w(px(list.inner_w)) + .h(px(layout::HEADER_HEIGHT)) + .flex() + .items_center() + .text_size(px(layout::HEADER_FONT)) + .line_height(px(layout::HEADER_HEIGHT)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text_secondary) + .when( + list.fully_visible(header_top, layout::HEADER_HEIGHT), + |header| { + header + .snapshot( + format_args!("overlay.keyboard_toolbar.group.{group_id}"), + Some("overlay.keyboard_toolbar.panel"), + ) + .snapshot_text(title) + }, + ) + .child(title), + ); + } + let rows_top = header_top + layout::HEADER_HEIGHT + layout::HEADER_GAP; + let mut count = 0; + for (index, tile) in tiles.enumerate() { + count = index + 1; + let (x, y) = layout::item_offset(index, list.tile_w); + let top = rows_top + y; + if !list.intersects(top, layout::ITEM_HEIGHT) { + continue; + } + let rect = FlowRect::new(x, top, list.tile_w, layout::ITEM_HEIGHT); + let snapshot = list.fully_visible(top, layout::ITEM_HEIGHT); + body = body.child(panel_tile(group_id, tile, rect, snapshot, palette, cx)); + } + list.list = body; + list.cursor_y += layout::group_height(count); +} + +/// Button background and glyph color of a tile: Highlight swatches show their color. +fn tile_colors(action: KeyboardToolbarAction, palette: &Palette) -> (Hsla, Hsla) { + let css = |var: Option<&str>| var.and_then(|v| palette.theme.css_color(v)); + match action { + KeyboardToolbarAction::SetBgColor(color) => ( + css(color.bg_css_var()).unwrap_or(palette.background_secondary), + palette.text_primary, + ), + KeyboardToolbarAction::SetTextColor(color) => ( + palette.background_secondary, + css(color.fg_css_var()).unwrap_or(palette.text_primary), + ), + _ => (palette.background_secondary, palette.icon), + } +} + +/// One grid item: a `64px` button with a `32px` glyph over a `13px` label. +fn panel_tile<V: OverlayHost>( + group_id: &'static str, + tile: ToolPanelTile<'_>, + rect: FlowRect, + record_snapshot: bool, + palette: &Palette, + cx: &mut Context<V>, +) -> ui::Stateful<ui::Div> { + let action = tile.action; + let (button_bg, ink) = tile_colors(action, palette); + let swatch = matches!( + action, + KeyboardToolbarAction::SetTextColor(_) | KeyboardToolbarAction::SetBgColor(_) + ); + let glyph: AnyElement = match action { + KeyboardToolbarAction::Date(kind) => div() + .text_size(px(16.0)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(ink) + .child(kind.badge()) + .into_any_element(), + KeyboardToolbarAction::Image => image_icon_glyph(ink, layout::ICON_SIZE), + _ if swatch => div() + .text_size(px(24.0)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(ink) + .child("A") + .into_any_element(), + _ if !tile.icon.is_empty() => icon(tile.icon, layout::ICON_SIZE, ink).into_any_element(), + _ => div() + .text_size(px(12.0)) + .text_color(ink) + .child(tile.name.clone()) + .into_any_element(), + }; + let hover = palette.hover; + div() + .id(SharedString::from(format!( + "kb-panel-{group_id}-{}", + tile.id + ))) + .absolute() + .left(px(rect.x)) + .top(px(rect.y)) + .w(px(rect.w)) + .h(px(rect.h)) + .flex() + .flex_col() + .items_center() + .gap(px(layout::LABEL_GAP)) + .cursor_pointer() + .on_click(emit(cx, move |_: &ClickEvent| { + OverlayEvent::KeyboardToolbar(action) + })) + .when(record_snapshot, |el| { + el.snapshot( + format_args!("overlay.keyboard_toolbar.panel.{group_id}.{}", tile.id), + Some("overlay.keyboard_toolbar.panel"), + ) + .snapshot_text(tile.name.clone()) + }) + .child( + div() + .w(px(rect.w)) + .h(px(layout::BUTTON_HEIGHT)) + .rounded(px(layout::BUTTON_RADIUS)) + .bg(button_bg) + .when(swatch, |el| el.border_1().border_color(palette.border)) + .hover(move |style| style.bg(hover)) + .flex() + .items_center() + .justify_center() + .child(glyph), + ) + .child( + div() + .w(px(rect.w)) + .h(px(layout::LABEL_HEIGHT)) + .overflow_hidden() + .whitespace_nowrap() + .text_size(px(layout::LABEL_FONT)) + .line_height(px(layout::LABEL_HEIGHT)) + .text_color(palette.text_secondary) + .flex() + .justify_center() + .child(div().min_w(px(0.0)).truncate().child(tile.name)), + ) +} diff --git a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs index 3b759ed01f..a7b5484a78 100644 --- a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs +++ b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs @@ -1,5 +1,4 @@ -//! Painting for `KeyboardToolbar` strip and its docked bottom tool panels -//! (`+` 8-group insert panel, `Turn into` panel, and 9-color `Highlight` panel). +//! Painting for the `KeyboardToolbar` strip and the shell that docks its tool panel. use ui::{ AnyElement, ClickEvent, Context, FontWeight, Hsla, ScrollEvent, SharedString, div, prelude::*, @@ -17,13 +16,13 @@ use crate::{ }; use super::{ - DEFAULT_KEYBOARD_TOOLBAR_ITEMS, HighlightColor, KEYBOARD_TOOL_PANEL_HEIGHT, - KEYBOARD_TOOLBAR_BUTTON, KEYBOARD_TOOLBAR_HEIGHT, KeyboardToolbarAction, KeyboardToolbarLevel, - KeyboardToolbarPanel, TEXT_SUB_TOOLBAR_ITEMS, TURN_INTO_PANEL_ITEMS, ToolbarItemSpec, - config::ToolPanelTile, more_tool_tiles, slash_surface_refs, + DEFAULT_KEYBOARD_TOOLBAR_ITEMS, KEYBOARD_TOOLBAR_BUTTON, KEYBOARD_TOOLBAR_HEIGHT, + KeyboardToolbarAction, KeyboardToolbarLevel, KeyboardToolbarPanel, TEXT_SUB_TOOLBAR_ITEMS, + ToolbarItemSpec, tool_panel_height, }; -fn image_icon_glyph(color: Hsla) -> AnyElement { +/// The `Image` glyph (frame, ridge and sun), `size` px square. +pub(super) fn image_icon_glyph(color: Hsla, size: f32) -> AnyElement { ui::canvas( |_, _, _| (), move |bounds, (), window, _| { @@ -66,8 +65,8 @@ fn image_icon_glyph(color: Hsla) -> AnyElement { } }, ) - .w(px(20.0)) - .h(px(20.0)) + .w(px(size)) + .h(px(size)) .into_any_element() } @@ -91,8 +90,7 @@ impl Overlays { self.keyboard_toolbar.active_panel }; let panel_height = if active_panel.is_some() { - let max_panel = (win_h - TOPBAR_HEIGHT - KEYBOARD_TOOLBAR_HEIGHT - 16.0).max(120.0); - KEYBOARD_TOOL_PANEL_HEIGHT.min(max_panel).floor() + tool_panel_height(win_h) } else { 0.0 }; @@ -120,7 +118,10 @@ impl Overlays { if let Some(panel_kind) = active_panel { let panel_rect = FlowRect::new(0.0, top + KEYBOARD_TOOLBAR_HEIGHT, width, panel_height); - let panel = self.render_tool_panel(panel_kind, panel_rect, scene, palette, cx); + let targets = (panel_kind == KeyboardToolbarPanel::More) + .then(|| self.keyboard_doc_targets(scene.snapshot)) + .unwrap_or_default(); + let panel = self.render_tool_panel(panel_kind, panel_rect, &targets, palette, cx); let container = place(FlowRect::new(0.0, top, width, total_height)) .id("keyboard-toolbar-shell") .flex() @@ -395,7 +396,7 @@ impl Overlays { KeyboardToolbarAction::BackToMainToolbar => { button.child(div().text_size(px(18.0)).child("\u{2190}")) } - KeyboardToolbarAction::Image => button.child(image_icon_glyph(ink)), + KeyboardToolbarAction::Image => button.child(image_icon_glyph(ink, 20.0)), KeyboardToolbarAction::ToggleHighlightPanel => button.child( div() .flex() @@ -415,385 +416,4 @@ impl Overlays { _ => button.child(label), } } - - fn render_tool_panel<V: OverlayHost>( - &self, - panel: KeyboardToolbarPanel, - rect: FlowRect, - scene: &OverlayScene<'_>, - palette: &Palette, - cx: &mut Context<V>, - ) -> ui::Stateful<ui::Div> { - let pad_x = if rect.w <= 340.0 { 8.0 } else { 12.0 }; - let pad_y = 8.0; - let col_gap = 6.0; - let inner_w = (rect.w - pad_x * 2.0 - 2.0).max(120.0); - let list_h = (rect.h - pad_y * 2.0 - 2.0).max(80.0); - let cols: usize = ((inner_w + col_gap) / (KEYBOARD_TOOLBAR_BUTTON + col_gap)) - .floor() - .clamp(3.0, 5.0) as usize; - let tile_w = ((inner_w - col_gap * (cols as f32 - 1.0)) / cols as f32) - .floor() - .max(KEYBOARD_TOOLBAR_BUTTON); - - let header_h = 18.0; - let tile_row_h = KEYBOARD_TOOLBAR_BUTTON + 14.0; - let row_gap = 4.0; - let group_gap = 8.0; - let mut list = div() - .relative() - .flex_none() - .w(px(inner_w)) - .h(px(list_h)) - .overflow_hidden(); - let scroll = self.keyboard_toolbar.panel_scroll.max(0.0); - let mut cursor_y = 0.0_f32; - let push_header = |list: ui::Div, group_id: &'static str, title: &'static str, y: f32| { - let top = y - scroll; - if top + header_h <= 0.0 || top >= list_h { - return list; - } - list.child( - div() - .absolute() - .left(px(0.0)) - .top(px(top)) - .w(px(inner_w)) - .h(px(header_h)) - .flex() - .items_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text_secondary) - .when(top >= 0.0 && top + header_h <= list_h, |header| { - header - .snapshot( - format_args!("overlay.keyboard_toolbar.group.{group_id}"), - Some("overlay.keyboard_toolbar.panel"), - ) - .snapshot_text(title) - }) - .child(title), - ) - }; - let can_pick_images = self.keyboard_toolbar.capabilities.can_pick_images; - match panel { - KeyboardToolbarPanel::More => { - let mut first = true; - let targets = slash_surface_refs(scene.snapshot); - for (group, visible) in more_tool_tiles( - &targets, - can_pick_images, - self.keyboard_toolbar.capabilities.can_pick_attachments, - self.database_readonly, - ) { - if !first { - cursor_y += group_gap; - } - first = false; - list = push_header(list, group.id, group.name, cursor_y); - cursor_y += header_h + row_gap; - for chunk in visible.chunks(cols) { - let top = cursor_y - scroll; - if top + tile_row_h > 0.0 && top < list_h { - list = list.child(self.render_action_row( - group.id, - chunk, - FlowRect::new(0.0, top, inner_w, tile_row_h), - tile_w, - col_gap, - top >= 0.0 && top + tile_row_h <= list_h, - palette, - cx, - )); - } - cursor_y += tile_row_h + row_gap; - } - } - } - KeyboardToolbarPanel::TurnInto => { - let visible: Vec<_> = TURN_INTO_PANEL_ITEMS - .iter() - .filter(|i| i.is_visible_for(can_pick_images)) - .map(ToolPanelTile::from) - .collect(); - list = push_header(list, "turn_into", "Turn into", cursor_y); - cursor_y += header_h + row_gap; - for chunk in visible.chunks(cols) { - let top = cursor_y - scroll; - if top + tile_row_h > 0.0 && top < list_h { - list = list.child(self.render_action_row( - "turn_into", - chunk, - FlowRect::new(0.0, top, inner_w, tile_row_h), - tile_w, - col_gap, - top >= 0.0 && top + tile_row_h <= list_h, - palette, - cx, - )); - } - cursor_y += tile_row_h + row_gap; - } - } - KeyboardToolbarPanel::Highlight => { - for (idx, (group_id, title, is_bg)) in [ - ("color", "Color", false), - ("background", "Background", true), - ] - .into_iter() - .enumerate() - { - if idx > 0 { - cursor_y += group_gap; - } - list = push_header(list, group_id, title, cursor_y); - cursor_y += header_h + row_gap; - for chunk in HighlightColor::ALL.chunks(cols) { - let top = cursor_y - scroll; - if top + tile_row_h > 0.0 && top < list_h { - list = list.child(self.render_highlight_row( - group_id, - is_bg, - chunk, - FlowRect::new(0.0, top, inner_w, tile_row_h), - tile_w, - col_gap, - top >= 0.0 && top + tile_row_h <= list_h, - palette, - cx, - )); - } - cursor_y += tile_row_h + row_gap; - } - } - } - } - if cursor_y > list_h { - let thumb_h = (list_h * list_h / cursor_y).max(24.0).round(); - let max_scroll = (cursor_y - list_h).max(1.0); - let thumb_top = ((list_h - thumb_h) * (scroll / max_scroll).clamp(0.0, 1.0)).round(); - list = list.child( - div() - .absolute() - .left(px(inner_w - 3.0)) - .top(px(thumb_top)) - .w(px(3.0)) - .h(px(thumb_h)) - .rounded(px(1.5)) - .bg(palette.text_secondary.opacity(0.35)), - ); - } - - div() - .id("keyboard-tool-panel") - .flex_none() - .w(px(rect.w)) - .h(px(rect.h)) - .px(px(pad_x)) - .py(px(pad_y)) - .bg(palette.background) - .border_1() - .border_color(palette.border) - .overflow_hidden() - .occlude() - .on_scroll(emit(cx, |ev: &ui::ScrollEvent| { - OverlayEvent::KeyboardToolbarPanelScroll(f32::from( - ev.delta.pixel_delta(px(20.0)).y, - )) - })) - .snapshot("overlay.keyboard_toolbar.panel", Some("root.canvas")) - .child(list) - } - - #[allow(clippy::too_many_arguments)] - fn render_action_row<V: OverlayHost>( - &self, - group_id: &'static str, - chunk: &[ToolPanelTile<'_>], - rect: FlowRect, - tile_w: f32, - col_gap: f32, - record_snapshot: bool, - palette: &Palette, - cx: &mut Context<V>, - ) -> ui::Div { - let hover = palette.hover; - let mut row = div() - .absolute() - .left(px(rect.x)) - .top(px(rect.y)) - .w(px(rect.w)) - .h(px(rect.h)) - .flex() - .gap(px(col_gap)); - for spec in chunk { - let action = spec.action; - let tile_id = format!("kb-panel-{group_id}-{}", spec.id); - let glyph: AnyElement = match action { - KeyboardToolbarAction::Date(kind) => div() - .text_size(px(13.0)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.icon) - .child(kind.badge()) - .into_any_element(), - KeyboardToolbarAction::Image => image_icon_glyph(palette.icon), - _ if !spec.icon.is_empty() => { - icon(spec.icon, 20.0, palette.icon).into_any_element() - } - _ => div() - .text_size(px(12.0)) - .text_color(palette.icon) - .child(spec.name.clone()) - .into_any_element(), - }; - let tile = div() - .id(SharedString::from(tile_id)) - .flex_none() - .w(px(tile_w)) - .h(px(rect.h)) - .flex() - .flex_col() - .items_center() - .gap(px(2.0)) - .cursor_pointer() - .on_click(emit(cx, move |_: &ClickEvent| { - OverlayEvent::KeyboardToolbar(action) - })) - .when(record_snapshot, |tile| { - tile.snapshot( - format_args!("overlay.keyboard_toolbar.panel.{group_id}.{}", spec.id), - Some("overlay.keyboard_toolbar.panel"), - ) - .snapshot_text(spec.name.clone()) - }) - .child( - div() - .w(px(tile_w)) - .h(px(KEYBOARD_TOOLBAR_BUTTON)) - .rounded(px(6.0)) - .bg(palette.background_secondary) - .hover(move |style| style.bg(hover)) - .flex() - .items_center() - .justify_center() - .child(glyph), - ) - .child( - div() - .w(px(tile_w)) - .h(px(12.0)) - .overflow_hidden() - .whitespace_nowrap() - .text_size(px(10.0)) - .line_height(px(12.0)) - .text_color(palette.text_secondary) - .flex() - .justify_center() - .child(div().min_w(px(0.0)).truncate().child(spec.name.clone())), - ); - row = row.child(tile); - } - row - } - - #[allow(clippy::too_many_arguments)] - fn render_highlight_row<V: OverlayHost>( - &self, - group_id: &'static str, - is_bg: bool, - chunk: &[HighlightColor], - rect: FlowRect, - tile_w: f32, - col_gap: f32, - record_snapshot: bool, - palette: &Palette, - cx: &mut Context<V>, - ) -> ui::Div { - let hover = palette.hover; - let mut row = div() - .absolute() - .left(px(rect.x)) - .top(px(rect.y)) - .w(px(rect.w)) - .h(px(rect.h)) - .flex() - .gap(px(col_gap)); - for &color in chunk { - let action = if is_bg { - KeyboardToolbarAction::SetBgColor(color) - } else { - KeyboardToolbarAction::SetTextColor(color) - }; - let swatch_bg = if is_bg { - color - .bg_css_var() - .and_then(|v| palette.theme.css_color(v)) - .unwrap_or(palette.background_secondary) - } else { - palette.background_secondary - }; - let swatch_fg = if is_bg { - palette.text_primary - } else { - color - .fg_css_var() - .and_then(|v| palette.theme.css_color(v)) - .unwrap_or(palette.text_primary) - }; - let tile_id = format!("kb-hl-{group_id}-{}", color.id()); - let tile = div() - .id(SharedString::from(tile_id)) - .flex_none() - .w(px(tile_w)) - .h(px(rect.h)) - .flex() - .flex_col() - .items_center() - .gap(px(2.0)) - .cursor_pointer() - .on_click(emit(cx, move |_: &ClickEvent| { - OverlayEvent::KeyboardToolbar(action) - })) - .when(record_snapshot, |tile| { - tile.snapshot( - format_args!("overlay.keyboard_toolbar.panel.{group_id}.{}", color.id()), - Some("overlay.keyboard_toolbar.panel"), - ) - .snapshot_text(color.label()) - }) - .child( - div() - .w(px(tile_w)) - .h(px(KEYBOARD_TOOLBAR_BUTTON)) - .rounded(px(6.0)) - .bg(swatch_bg) - .border_1() - .border_color(palette.border) - .hover(move |style| style.bg(hover)) - .flex() - .items_center() - .justify_center() - .text_size(px(16.0)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(swatch_fg) - .child("A"), - ) - .child( - div() - .w(px(tile_w)) - .h(px(12.0)) - .overflow_hidden() - .whitespace_nowrap() - .text_size(px(10.0)) - .line_height(px(12.0)) - .text_color(palette.text_secondary) - .flex() - .justify_center() - .child(color.label()), - ); - row = row.child(tile); - } - row - } } diff --git a/blocksuite/crates/playground/src/overlays/mod.rs b/blocksuite/crates/playground/src/overlays/mod.rs index a8ee069467..792c14829f 100644 --- a/blocksuite/crates/playground/src/overlays/mod.rs +++ b/blocksuite/crates/playground/src/overlays/mod.rs @@ -3499,6 +3499,7 @@ mod tests { session.overlay(OverlayEvent::KeyboardToolbar( KeyboardToolbarAction::ToggleMorePanel, )); + session.overlay(OverlayEvent::KeyboardToolbarPanelScroll(-300.0)); let todo_frame = session.frame(); session.click(&todo_frame, "overlay.keyboard_toolbar.panel.list.todo"); session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo)); diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs index b6b4f3bff9..851dbfcb59 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs @@ -65,6 +65,7 @@ impl PlaygroundView { can_pick_attachments: self.can_pick_attachments(), has_body_selection: self.editor.selection.is_some(), has_non_collapsed_selection: self.editor.selection.as_ref().is_some_and(|s| !s.empty()), + snapshot_rev: self.doc_rev, }; self.overlays.set_database_readonly(self.database_readonly); self.overlays.set_keyboard_toolbar_capabilities(caps); @@ -83,6 +84,11 @@ impl PlaygroundView { self.run_keyboard_toolbar_action(*action, window, cx); true } + OverlayEvent::KeyboardToolbarPanelScroll(_) => { + // The scroll limit keys the cached `More` items on the current snapshot revision. + self.sync_keyboard_toolbar_state(); + false + } OverlayEvent::InsertImageBytes { bytes, caption } => { let _ = self.insert_picked_image_bytes(bytes, caption, window, cx); true diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs index 284b1ab92f..e31e6be529 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests.rs @@ -126,6 +126,47 @@ impl MobileSession { self.platform.run_until_parked(); } + /// Scrolls the docked tool panel with the pointer wheel until element `id` + /// lies completely inside the panel, and answers that frame. Fails when + /// the panel stops moving first. + pub(super) fn scroll_panel_to(&self, id: &str) -> FrameSnapshot { + let mut last_rows = None; + loop { + let frame = self.frame(); + let panel = frame.elements["overlay.keyboard_toolbar.panel"].bounds; + if frame.elements.get(id).is_some_and(|tile| { + tile.bounds.y >= panel.y + && tile.bounds.y + tile.bounds.height <= panel.y + panel.height + }) { + return frame; + } + let mut rows: Vec<(String, i32)> = frame + .elements + .iter() + .filter(|(key, _)| key.starts_with("overlay.keyboard_toolbar.panel.")) + .map(|(key, el)| (key.clone(), el.bounds.y.round() as i32)) + .collect(); + rows.sort(); + assert!( + last_rows.as_ref() != Some(&rows), + "could not scroll to {id}" + ); + last_rows = Some(rows); + self.headless + .dispatch_input(PlatformInput::Scroll(ui::ScrollEvent { + position: point( + px(panel.x + panel.width * 0.5), + px(panel.y + panel.height * 0.5), + ), + delta: ui::ScrollDelta::Pixels(point(px(0.0), px(-44.0))), + modifiers: Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + self.platform.run_until_parked(); + } + } + pub(super) fn key(&self, key: &str) { self.frame(); self.platform.run_until_parked(); @@ -284,11 +325,7 @@ fn keyboard_toolbar_0275_highlights_marks_and_link_single_step_undo() { .elements .contains_key("overlay.keyboard_toolbar.panel.color.red") ); - assert!( - hl_frame - .elements - .contains_key("overlay.keyboard_toolbar.panel.background.yellow") - ); + session.scroll_panel_to("overlay.keyboard_toolbar.panel.background.yellow"); session.overlay(OverlayEvent::KeyboardToolbar( KeyboardToolbarAction::SetTextColor(HighlightColor::Red), @@ -377,22 +414,6 @@ fn keyboard_toolbar_0275_local_dates_image_picker_bookmark_prompt_and_table_gate session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo)); assert_eq!(session.block_count("showcase-note"), base_count); - let scroll_more_panel = |dy: f32| { - let s = session.frame(); - let p = s.elements["overlay.keyboard_toolbar.panel"].bounds; - session - .headless - .dispatch_input(PlatformInput::Scroll(ui::ScrollEvent { - position: point(px(p.x + p.width * 0.5), px(p.y + p.height * 0.5)), - delta: ui::ScrollDelta::Pixels(point(px(0.0), px(dy))), - modifiers: Modifiers::default(), - touch_phase: ui::TouchPhase::Moved, - source: ui::ScrollSource::Pointer, - })); - session.platform.run_until_parked(); - session.frame() - }; - // 1a. Deterministic UTC+0 daytime calendar clock (`2026-11-26T14:05:00Z` = `1_795_701_900_000` ms): // must format via the test clock without depending on host wall-clock time. session.app.update(|cx| { @@ -409,8 +430,8 @@ fn keyboard_toolbar_0275_local_dates_image_picker_bookmark_prompt_and_table_gate session.overlay(OverlayEvent::KeyboardToolbar( KeyboardToolbarAction::ToggleMorePanel, )); - let more_snap = scroll_more_panel(-800.0); - session.click_id(&more_snap, "overlay.keyboard_toolbar.panel.date.date_today"); + let today = "overlay.keyboard_toolbar.panel.date.date_today"; + session.click_id(&session.scroll_panel_to(today), today); assert_eq!(session.text("ops-p1").plain, "2026-11-26"); session.overlay(OverlayEvent::KeyboardToolbar(KeyboardToolbarAction::Undo)); assert_eq!(session.text("ops-p1").plain, ""); @@ -453,8 +474,7 @@ fn keyboard_toolbar_0275_local_dates_image_picker_bookmark_prompt_and_table_gate KeyboardToolbarAction::ToggleMorePanel, )); } - let snap = scroll_more_panel(-800.0); - session.click_id(&snap, tile_id); + session.click_id(&session.scroll_panel_to(tile_id), tile_id); assert_eq!( session.text("ops-p1").plain, expected, @@ -561,11 +581,8 @@ fn keyboard_toolbar_0275_local_dates_image_picker_bookmark_prompt_and_table_gate session.overlay(OverlayEvent::KeyboardToolbar( KeyboardToolbarAction::ToggleMorePanel, )); - let cm_snap = scroll_more_panel(-240.0); - session.click_id( - &cm_snap, - "overlay.keyboard_toolbar.panel.content_media.bookmark", - ); + let bookmark = "overlay.keyboard_toolbar.panel.content_media.bookmark"; + session.click_id(&session.scroll_panel_to(bookmark), bookmark); let bm_snap = session.frame(); assert!(audit_frame_snapshot(&bm_snap).is_empty()); assert!(bm_snap.elements.contains_key("overlay.bookmark_prompt")); diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_keyboard_ime.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_keyboard_ime.rs index b320b41305..d95f5e25f5 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests_keyboard_ime.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_keyboard_ime.rs @@ -4,7 +4,7 @@ use blocksuite_playground_doc::{ read::{BlockContent, DatabaseViewMode}, schema::{BlockSpec, ParagraphType, SurfaceElementSpec}, }; -use ui::{EntityInputHandler, FrameSnapshot, point, px}; +use ui::{EntityInputHandler, point, px}; use crate::{ PlaygroundMode, PlaygroundTheme, @@ -26,21 +26,6 @@ fn more_panel(session: &MobileSession) { session.click_id(&frame, "overlay.keyboard_toolbar.more_panel"); } -fn scroll_to_tile(session: &MobileSession, id: &str) -> FrameSnapshot { - for _ in 0..18 { - let frame = session.frame(); - let panel = frame.elements["overlay.keyboard_toolbar.panel"].bounds; - if frame.elements.get(id).is_some_and(|tile| { - tile.bounds.y >= panel.y + 8.0 - && tile.bounds.y + tile.bounds.height <= panel.y + panel.height - 8.0 - }) { - return frame; - } - session.overlay(OverlayEvent::KeyboardToolbarPanelScroll(-44.0)); - } - panic!("could not scroll to {id}"); -} - #[test] fn mobile_more_panel_inserts_database_and_canvas_refs_in_one_undo() { let session = MobileSession::open(390, 844, PlaygroundTheme::Light); @@ -61,7 +46,7 @@ fn mobile_more_panel_inserts_database_and_canvas_refs_in_one_undo() { let before = session.block_count("showcase-note"); more_panel(&session); let id = format!("overlay.keyboard_toolbar.panel.{tile}"); - let frame = scroll_to_tile(&session, &id); + let frame = session.scroll_panel_to(&id); session.click_id(&frame, &id); assert_eq!(session.block_count("showcase-note"), before + 1, "{tile}"); session.view(|view| { @@ -115,7 +100,7 @@ fn mobile_embed_inserts_empty_iframe_and_updates_the_same_block() { let frame = session.frame(); session.click_id(&frame, "overlay.keyboard_toolbar.more_panel"); let id = "overlay.keyboard_toolbar.panel.embeds.embed_iframe"; - session.click_id(&scroll_to_tile(&session, id), id); + session.click_id(&session.scroll_panel_to(id), id); let iframe_id = session.view(|view| { let snapshot = view.page_snapshot().unwrap(); @@ -168,7 +153,7 @@ fn mobile_empty_iframe_reopens_after_cancel_and_undo() { let count = session.view(|view| view.page_snapshot().unwrap().block_count()); more_panel(&session); let tile = "overlay.keyboard_toolbar.panel.embeds.embed_iframe"; - session.click_id(&scroll_to_tile(&session, tile), tile); + session.click_id(&session.scroll_panel_to(tile), tile); let iframe_id = session.view(|view| view.overlays().bookmark_prompt().unwrap().block_id.clone()); let assert_iframe = |expected_url| { @@ -264,7 +249,7 @@ fn mobile_embed_cards_use_submitted_url_and_undo_in_one_step() { let before = session.block_count("showcase-note"); more_panel(&session); let id = format!("overlay.keyboard_toolbar.panel.embeds.{entry}"); - session.click_id(&scroll_to_tile(&session, &id), &id); + session.click_id(&session.scroll_panel_to(&id), &id); assert_eq!( session.block_count("showcase-note"), before, @@ -509,7 +494,7 @@ fn render_mobile_embed_evidence() { let session = MobileSession::open(390, 844, PlaygroundTheme::Light); more_panel(&session); let id = format!("overlay.keyboard_toolbar.panel.embeds.{entry}"); - session.click_id(&scroll_to_tile(&session, &id), &id); + session.click_id(&session.scroll_panel_to(&id), &id); if let Some(url) = url { session.type_into_field(url); session.overlay(OverlayEvent::BookmarkApply); diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_toolbar_chrome.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_toolbar_chrome.rs index aeb1a219e4..b75b61a8d1 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests_toolbar_chrome.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_toolbar_chrome.rs @@ -1,7 +1,7 @@ //! Deterministic headless tests for shared `ToolbarChrome`, `Tooltip`, Image 500 ms hover inner //! toolbar + 4-corner handles, LinkedDoc single-click select vs double-click open, FormatToolbar //! `Align ▾` / `Highlight ▾` / `Create Table` / `⋮ More`, Bookmark/Callout toolbars, and Simple -//! Table hover add-bars & three-dot axis pills. +//! Table hover add-bars & three-dot axis pills, and the mobile `More` panel grid. use std::time::Duration; @@ -465,3 +465,71 @@ fn bookmark_toolbar_uses_shared_chrome_with_hostname_and_dropdowns() { assert!(by_id(&f, "overlay.bookmark_toolbar.style").is_some()); assert!(by_id(&f, "overlay.bookmark_toolbar.more").is_some()); } + +#[test] +fn more_panel_uses_web_four_column_grid_and_reaches_its_last_row() { + for (width, height, theme, evidence) in [ + (320, 640, PlaygroundTheme::Light, Some("more-320-light.png")), + (320, 640, PlaygroundTheme::Dark, Some("more-320-dark.png")), + (390, 844, PlaygroundTheme::Light, Some("more-390-light.png")), + (390, 844, PlaygroundTheme::Dark, Some("more-390-dark.png")), + (568, 844, PlaygroundTheme::Light, None), + ] { + let s = MobileSession::open(width, height, theme); + s.overlay(OverlayEvent::SetSelection(Some(ActiveSelection::caret( + "showcase-intro", + 0, + )))); + let f0 = s.frame(); + s.click_id(&f0, "overlay.keyboard_toolbar.more_panel"); + let f = s.frame(); + if let Some(name) = evidence { + save_evidence_png(&s, name); + } + let tile = |f: &FrameSnapshot, id: &str| { + by_id(f, &format!("overlay.keyboard_toolbar.panel.{id}")) + .unwrap_or_else(|| panic!("{width}px: missing {id}")) + .bounds + }; + let panel = by_id(&f, "overlay.keyboard_toolbar.panel") + .expect("More panel") + .bounds; + let row: Vec<_> = ["text", "h1", "h2", "h3", "h4"] + .iter() + .map(|id| tile(&f, &format!("basic.{id}"))) + .collect(); + let step = row[0].width + 12.0; + for (col, b) in row[..4].iter().enumerate() { + assert_eq!(b.y, row[0].y, "{width}px: first row shares one top"); + assert_eq!( + b.x, + row[0].x + col as f32 * step, + "{width}px: 12 px column gap" + ); + assert_eq!( + b.height, 86.0, + "{width}px: 64 px button, 4 px gap, 18 px label" + ); + } + assert!( + row[3].x + row[3].width <= panel.x + panel.width, + "{width}px: four columns fit the panel" + ); + assert_eq!(row[4].x, row[0].x, "{width}px: the fifth item wraps"); + assert_eq!(row[4].y, row[0].y + 86.0 + 12.0, "{width}px: 12 px row gap"); + + let before = s.block_count("showcase-note"); + s.overlay(OverlayEvent::KeyboardToolbarPanelScroll(-10_000.0)); + let end = s.frame(); + let last = tile(&end, "database.database_kanban"); + assert!( + last.y + last.height <= panel.y + panel.height, + "{width}px: the last row scrolls fully into view" + ); + s.click_id( + &end, + "overlay.keyboard_toolbar.panel.database.database_kanban", + ); + assert_eq!(s.block_count("showcase-note"), before + 1, "{width}px"); + } +}