From 9ed267770ff50792b3f7690e8d5edd3bfcebc920 Mon Sep 17 00:00:00 2001 From: DarkSky <25152247+darkskygit@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:19:14 +0900 Subject: [PATCH] fix(editor): close link, table, canvas, and code gaps Validate the hovered link before paint and before Open or Copy. Fit and scroll the table axis menu in short panes. Keep Group available in either mixed selection order. Keep the top of a rotated shape in place as its label grows. Show a scrollbar thumb under overflowing code. Model: GPT-6.2 Tests: Rust unit tests and Linux headless input replay. --- .../crates/editor/src/block_flow/blocks.rs | 10 +- .../src/edgeless/element_toolbar/summary.rs | 3 +- .../crates/editor/src/overlays/scrollbar.rs | 75 ++--- .../crates/playground/src/chrome/mod.rs | 3 + .../edgeless_element_toolbar_tests.rs | 80 +++++ .../src/edgeless/inline_edit/mod.rs | 4 + .../src/edgeless/inline_edit/tests.rs | 61 ++++ .../src/overlays/view_link_popup/actions.rs | 21 +- .../view_link_popup/active_note_tests.rs | 146 +++++++-- .../src/overlays/view_link_popup/mod.rs | 18 +- .../playground/src/overlays/view_scrollbar.rs | 183 ++++++++++- .../view_table_cell/controls_tests.rs | 71 +++++ .../src/overlays/view_table_cell/toolbar.rs | 301 +++++++++--------- 13 files changed, 753 insertions(+), 223 deletions(-) diff --git a/blocksuite/crates/editor/src/block_flow/blocks.rs b/blocksuite/crates/editor/src/block_flow/blocks.rs index b9ff80d45f..6c1aaf9f46 100644 --- a/blocksuite/crates/editor/src/block_flow/blocks.rs +++ b/blocksuite/crates/editor/src/block_flow/blocks.rs @@ -285,6 +285,7 @@ impl FlowPass<'_> { width: f32, ) -> BlockBody { const CODE_COLLAPSED_LINES: usize = 8; + const COLLAPSED_SCROLLBAR_PADDING: f32 = 8.0; let (pad_y, pad_x) = super::code_padding_for_form_factor(self.input.form_factor); let line_height = TYPOGRAPHY.font_xs_px + 8.0; let code_style = InlineStyle::new( @@ -394,13 +395,18 @@ impl FlowPass<'_> { }); y += height; } - let height = if is_collapsed_cut { y } else { y + pad_y }; let max_scroll_x = (widest_line - code_width).max(0.0).ceil(); let code_scroll = (!wrap && max_scroll_x > 0.0).then(|| CodeScroll { area: FlowRect::new(code_x, pad_y, code_width, y - pad_y), max_x: max_scroll_x, initial_x: 0.0, }); + let bottom_padding = if is_collapsed_cut { + code_scroll.map_or(0.0, |_| COLLAPSED_SCROLLBAR_PADDING) + } else { + pad_y + }; + let height = y + bottom_padding; prims.insert( 0, @@ -413,7 +419,7 @@ impl FlowPass<'_> { }, ); if is_collapsed_cut { - // 80px linear bottom fade mask over collapsed code blocks (`padding-bottom: 0`). + // Fade the last 80 px of a collapsed code block to its background. const FADE_BANDS: usize = 10; let fade_h = 80.0_f32.min(height); let band_h = fade_h / FADE_BANDS as f32; diff --git a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs index 2f19a97b21..1fbc5efe1b 100644 --- a/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs +++ b/blocksuite/crates/editor/src/edgeless/element_toolbar/summary.rs @@ -283,7 +283,6 @@ pub fn summarize_element_toolbar( let can_align = alignable_count >= 2 && selected_items.iter().all(|item| !item.in_mindmap); let can_group = selected_count >= 2 && can_group_section - && selection_kind != SpatialItemKind::Group && selected_items .iter() .any(|item| item.kind != SpatialItemKind::Connector); @@ -725,7 +724,7 @@ pub fn summarize_element_toolbar( can_draw_connector, has_fill, has_stroke, - stroke_is_text: selection_kind == SpatialItemKind::EdgelessText, + stroke_is_text: !mixed_kinds && selection_kind == SpatialItemKind::EdgelessText, has_text_color, has_text_align, has_stroke_style, diff --git a/blocksuite/crates/editor/src/overlays/scrollbar.rs b/blocksuite/crates/editor/src/overlays/scrollbar.rs index 0d8d04627b..b8872777eb 100644 --- a/blocksuite/crates/editor/src/overlays/scrollbar.rs +++ b/blocksuite/crates/editor/src/overlays/scrollbar.rs @@ -8,7 +8,7 @@ use ui::{AnyElement, Context, Direction, MouseButton, MouseDownEvent, div, prelude::*, px}; use crate::{ - block_flow::{FlowBlock, PAGE_SURFACE_ID}, + block_flow::{FlowBlock, FlowKind, FormFactor, PAGE_SURFACE_ID}, theme::Palette, }; @@ -242,8 +242,7 @@ pub(super) fn block_hscrollbar_world_rect( )) } -/// Build a hover-revealed `4 -> 8px` horizontal scrollbar along the bottom edge of a wide -/// `affine:table`, `affine:database` (Table / Kanban), or unwrapped `affine:code` block. +/// Build the horizontal scrollbar of a wide block. Only pointer hosts get a drag target. #[allow(clippy::too_many_arguments)] pub(super) fn build_block_hscrollbar( block: &FlowBlock, @@ -251,6 +250,7 @@ pub(super) fn build_block_hscrollbar( scroll_x: f32, max_x: f32, dragging: bool, + interactive: bool, scale_factor: f32, palette: &Palette, cx: &mut Context, @@ -267,27 +267,37 @@ pub(super) fn build_block_hscrollbar( let ratio = (scroll_x / max_x).clamp(0.0, 1.0); let thumb_pos = ratio * travel; let thumb_left = track_inset + crate::scroll::snap_device_pixel(thumb_pos, scale_factor); - let block_id = &block.block_id; - let group_name: ui::SharedString = format!("hscroll-{block_id}").into(); let thumb_idle = palette.text_secondary.opacity(0.35); let thumb_hover = palette.text_secondary.opacity(0.55); - let bid = block_id.clone(); - let bar_left = local_rect.x; let initial_h = if dragging { HSCROLLBAR_HOVER_HEIGHT } else { HSCROLLBAR_IDLE_HEIGHT }; let initial_bg = if dragging { thumb_hover } else { thumb_idle }; - + let thumb = div() + .absolute() + .left(px(thumb_left)) + .top(px(2.0)) + .w(px(thumb_w)) + .h(px(initial_h)) + .rounded(px(initial_h * 0.5)) + .bg(initial_bg); + let bar = div() + .absolute() + .left(px(local_rect.x)) + .top(px(local_rect.y)) + .w(px(local_rect.w)); + if !interactive { + return Some(bar.h(px(initial_h + 2.0)).child(thumb).into_any_element()); + } + let block_id = &block.block_id; + let group_name: ui::SharedString = format!("hscroll-{block_id}").into(); + let bid = block_id.clone(); + let bar_left = local_rect.x; Some( - div() - .id(ui::SharedString::from(format!("hscrollbar-{block_id}"))) + bar.id(ui::SharedString::from(format!("hscrollbar-{block_id}"))) .group(group_name.clone()) - .absolute() - .left(px(local_rect.x)) - .top(px(local_rect.y)) - .w(px(local_rect.w)) .h(px(local_rect.h)) .cursor_pointer() .on_mouse_down( @@ -321,21 +331,11 @@ pub(super) fn build_block_hscrollbar( format_args!("{}.hscrollbar", block.snapshot_id()), Some(PAGE_SURFACE_ID), ) - .child( - div() - .absolute() - .left(px(thumb_left)) - .top(px(2.0)) - .w(px(thumb_w)) - .h(px(initial_h)) - .rounded(px(initial_h * 0.5)) - .bg(initial_bg) - .group_hover(group_name, move |s| { - s.h(px(HSCROLLBAR_HOVER_HEIGHT)) - .rounded(px(HSCROLLBAR_HOVER_HEIGHT * 0.5)) - .bg(thumb_hover) - }), - ) + .child(thumb.group_hover(group_name, move |s| { + s.h(px(HSCROLLBAR_HOVER_HEIGHT)) + .rounded(px(HSCROLLBAR_HOVER_HEIGHT * 0.5)) + .bg(thumb_hover) + })) .into_any_element(), ) } @@ -352,8 +352,8 @@ pub struct ScrollCodeOutcome { } impl super::Overlays { - /// Push the horizontal scrollbar of a wide block while the pointer is on it or drags it, on - /// desktop pointers only. + /// Show a code scrollbar in narrow panes and on touch hosts. Other scrollbars follow + /// desktop pointer hover and drag. #[allow(clippy::too_many_arguments)] pub(super) fn push_block_hscrollbar( &self, @@ -370,12 +370,12 @@ impl super::Overlays { .hscroll_drag .as_ref() .is_some_and(|d| d.block_id == block.block_id); - let revealed = + let interactive = !scene.is_touch && scene.form_factor == FormFactor::Desktop; + let show_at_rest = + block.body.kind == FlowKind::Code && (!interactive || scene.window.0 < 600.0); + let hovered_or_dragged = hovered || dragging || self.hscroll_hovered.as_deref() == Some(block.block_id.as_str()); - if !revealed - || scene.is_touch - || scene.form_factor != crate::block_flow::FormFactor::Desktop - { + if !(show_at_rest || interactive && hovered_or_dragged) { return; } if let Some((bar_world, code)) = block_hscrollbar_world_rect(block) @@ -385,7 +385,8 @@ impl super::Overlays { viewport.to_local(&bar_world), self.code_scroll_x_for(&block.block_id, code), code.max_x, - dragging, + interactive && dragging, + interactive, scale_factor, palette, cx, diff --git a/blocksuite/crates/playground/src/chrome/mod.rs b/blocksuite/crates/playground/src/chrome/mod.rs index dd517b8209..55e9328041 100644 --- a/blocksuite/crates/playground/src/chrome/mod.rs +++ b/blocksuite/crates/playground/src/chrome/mod.rs @@ -679,6 +679,9 @@ impl ui::Render for PlaygroundView { popovers.extend(self.database_popover_elements(&layout, window, cx)); popovers.extend(self.database_dnd_overlay_elements(window, cx)); } + if self.mode == PlaygroundMode::Edgeless { + self.sync_hover_link_popup(self.now_ms(cx)); + } popovers.extend(self.overlay_popovers(&palette, window, cx)); popovers.extend(self.render_touch_selection_menu(&palette, window, cx)); popovers.extend(self.render_database_record_sheet(&palette, window, cx)); diff --git a/blocksuite/crates/playground/src/edgeless/edgeless_element_toolbar_tests.rs b/blocksuite/crates/playground/src/edgeless/edgeless_element_toolbar_tests.rs index 276d92673e..379649db3a 100644 --- a/blocksuite/crates/playground/src/edgeless/edgeless_element_toolbar_tests.rs +++ b/blocksuite/crates/playground/src/edgeless/edgeless_element_toolbar_tests.rs @@ -696,6 +696,86 @@ mod toolbar_regressions { .unwrap(); } + #[test] + fn mixed_group_and_shape_toolbar_actions_ignore_paint_order() { + use crate::edgeless::SpatialItemKind; + use y_octo::{Any, SessionValue}; + + let (_, app, win, hw) = start_edgeless_toolbar_view(); + let group_id = app.update(|cx| { + win.update(cx, |view, _, cx| { + view.edgeless_set_selection(["shape-a", "shape-b"].map(str::to_owned), cx); + view.apply_edgeless_element_action(EdgelessElementAction::Group, cx); + view.edgeless + .authoring + .selection + .iter() + .next() + .unwrap() + .clone() + }) + .unwrap() + }); + + let mut commands = None; + for (index, first) in [ + ("a0", SpatialItemKind::Group), + ("az", SpatialItemKind::Shape), + ] { + app.update(|cx| { + win.update(cx, |view, _, cx| { + let commit = view + .page_mut() + .unwrap() + .set_surface_element_field( + "surf", + &group_id, + "index", + SessionValue::Any(Any::String(index.into())), + 100, + ) + .unwrap(); + if let Some(commit) = commit { + view.did_edgeless_doc_commit(commit, cx); + } + view.edgeless_set_selection([group_id.clone(), "shape-c".into()], cx); + }) + .unwrap() + }); + hw.request_frame(); + let actions: Vec<_> = app.update(|cx| { + win.update(cx, |view, window, _| { + let first_selected = view + .edgeless + .authoring + .painted_items + .iter() + .find(|item| view.edgeless.authoring.selection.contains(&item.id)) + .unwrap(); + assert_eq!(first_selected.kind, first); + window + .frame_snapshot() + .elements + .keys() + .filter(|id| id.starts_with("chrome.edgeless_element_toolbar.")) + .cloned() + .collect() + }) + .unwrap() + }); + assert!( + actions + .iter() + .any(|id| id == "chrome.edgeless_element_toolbar.group") + ); + if let Some(expected) = &commands { + assert_eq!(&actions, expected); + } else { + commands = Some(actions); + } + } + } + #[test] fn mixed_selection_keeps_shared_actions_and_more_lock_undoes_once() { use ui::{Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, PlatformInput, point, px}; diff --git a/blocksuite/crates/playground/src/edgeless/inline_edit/mod.rs b/blocksuite/crates/playground/src/edgeless/inline_edit/mod.rs index 6ae027cb1f..d2323f1f91 100644 --- a/blocksuite/crates/playground/src/edgeless/inline_edit/mod.rs +++ b/blocksuite/crates/playground/src/edgeless/inline_edit/mod.rs @@ -107,6 +107,10 @@ impl PlaygroundView { return None; } let mut r = ed.world_rect; + let half_growth = (needed_h - r.h) * 0.5; + let (sin, cos) = ed.rotate_deg.to_radians().sin_cos(); + r.x -= sin * half_growth; + r.y += (cos - 1.0) * half_growth; r.h = needed_h; Some((surface_id.clone(), id.clone(), r)) }) diff --git a/blocksuite/crates/playground/src/edgeless/inline_edit/tests.rs b/blocksuite/crates/playground/src/edgeless/inline_edit/tests.rs index 25f8ec080e..4e063dd7fd 100644 --- a/blocksuite/crates/playground/src/edgeless/inline_edit/tests.rs +++ b/blocksuite/crates/playground/src/edgeless/inline_edit/tests.rs @@ -621,3 +621,64 @@ fn double_click_on_canvas_linked_card_routes_to_self_hosted_block() { platform.run_until_parked(); assert_eq!(*opened.borrow(), [(target, url)]); } + +#[test] +fn rotated_shape_auto_height_keeps_world_top_center() { + let (platform, app, win, hw) = start_edgeless_toolbar_view(); + let read = |snapshot: &PageSnapshot| { + let (_, element) = find_surface_element(snapshot, "shape-a").unwrap(); + let SurfaceElementKind::Shape(shape) = &element.kind else { + panic!("Expected a shape"); + }; + shape.xywh + }; + let top_center = |[x, y, w, h]: [f64; 4]| { + let (sin, cos) = 45.0_f64.to_radians().sin_cos(); + (x + w * 0.5 + sin * h * 0.5, y + (1.0 - cos) * h * 0.5) + }; + let before = app.update(|cx| { + win.update(cx, |view, _, cx| { + let commit = view + .page_mut() + .unwrap() + .set_surface_element_field( + "surf", + "shape-a", + "rotate", + y_octo::SessionValue::Any(Any::Integer(45)), + 100, + ) + .unwrap() + .unwrap(); + view.did_edgeless_doc_commit(commit, cx); + read(view.page_snapshot().unwrap()) + }) + .unwrap() + }); + hw.request_frame(); + let after = app.update(|cx| { + win.update(cx, |view, window, cx| { + assert!(view.edgeless_begin_inline_edit("shape-a", window, cx)); + view.replace_text_in_range(None, "\nOne\nTwo\nThree\nFour\nFive\nSix", window, cx); + view.edgeless_commit_inline_edit(window, cx); + read(view.page_snapshot().unwrap()) + }) + .unwrap() + }); + if let Some(path) = std::env::var_os("TAIL_SHAPE_PNG") { + hw.request_frame(); + platform.run_until_parked(); + app.update(|cx| { + win.update(cx, |_, window, _| { + window.render_to_image().unwrap().save(path).unwrap(); + }) + .unwrap() + }); + } + assert!(after[3] > before[3]); + assert_eq!(after[2], before[2]); + let (before_x, before_y) = top_center(before); + let (after_x, after_y) = top_center(after); + assert!((before_x - after_x).abs() < 0.02, "{before:?} {after:?}"); + assert!((before_y - after_y).abs() < 0.02, "{before:?} {after:?}"); +} diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs index d53deb3604..647dca47d5 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/actions.rs @@ -39,7 +39,11 @@ impl PlaygroundView { let OverlayEvent::LinkPopupAction(action) = event else { return false; }; - let Some(target) = self.overlays.link_popup().map(|p| p.target.clone()) else { + let Some((target, from_hover)) = self + .overlays + .link_popup() + .map(|popup| (popup.target.clone(), popup.from_hover)) + else { return true; }; let now_ms = self.now_ms(cx); @@ -56,10 +60,15 @@ impl PlaygroundView { .. } => { let spans = matching_link_subranges(&doc_text, *start_utf16, *end_utf16, url); - if spans.is_empty() - && !(read_only_action - && !matching_link_subranges(&doc_text, 0, usize::MAX, url).is_empty()) - { + let live = if from_hover && read_only_action { + spans == [(*start_utf16, *end_utf16)] + } else { + !spans.is_empty() + || (read_only_action + && !matching_link_subranges(&doc_text, 0, usize::MAX, url) + .is_empty()) + }; + if !live { return None; } spans @@ -88,7 +97,7 @@ impl PlaygroundView { ) }) }; - if !at_offset && !(read_only_action && still_in_block()) { + if !at_offset && !(read_only_action && !from_hover && still_in_block()) { return None; } Vec::new() diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/active_note_tests.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/active_note_tests.rs index 42c67ad95d..27fe4baf05 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup/active_note_tests.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/active_note_tests.rs @@ -1,13 +1,18 @@ -use ui::{EntityInputHandler as _, point, px}; +use blocksuite_playground_doc::session::PageDocSession; +use ui::{ClipboardItem, EntityInputHandler as _, point, px}; +use y_octo::{Any, TextAttributes}; use crate::{ - PlaygroundMode, PlaygroundView, + HOME_PAGE_ID, PlaygroundMode, PlaygroundView, block_flow::FlowRect, overlays::{LINK_HOVER_DELAY_MS, TOOLBAR_CHROME_OFFSET, tests::Session}, rich_text::DecorationKind, }; -use super::{LinkPopupTarget, OverlayEvent, matching_link_subranges, tests::open_links}; +use super::{ + LinkPopupAction, LinkPopupTarget, OverlayEvent, matching_link_subranges, + tests::{open_links, screen_point}, +}; const POPUP: &str = "overlay.link_popup"; const URL: &str = "https://same.example/"; @@ -50,6 +55,23 @@ fn hover(session: &Session, span: FlowRect) -> ui::FrameSnapshot { session.settle() } +fn enter_active_note(session: &Session, zoom: f32) { + session.view(|view, cx| { + view.set_mode_immediate(PlaygroundMode::Edgeless, cx); + view.set_edgeless_camera(-200.0, -140.0, zoom, cx); + }); + let _ = session.settle(); + session.app.update(|cx| { + session + .window + .update(cx, |view, window, cx| { + assert!(view.edgeless_begin_inline_edit("n", window, cx)); + }) + .unwrap(); + }); + let _ = session.settle(); +} + fn check_popup_anchor(frame: &ui::FrameSnapshot, span: FlowRect) { let popup = frame.elements[POPUP].bounds; let above = (popup.bottom() + TOOLBAR_CHROME_OFFSET - span.y).abs() < 1.0; @@ -76,25 +98,113 @@ fn save_frame(session: &Session, name: &str) { } } +fn replace_first_link(page: &mut PageDocSession, peer_update: bool) { + let attrs = TextAttributes::from([("link".into(), Any::String(NEW_URL.into()))]); + if peer_update { + let mut peer = PageDocSession::new(HOME_PAGE_ID, 177).unwrap(); + peer.apply_remote_update_v1(&page.encode_update_v1().unwrap()) + .unwrap(); + let before = peer.encode_state_vector_v1().unwrap(); + peer.format_text("p-two", "prop:text", 2, 5, attrs, 48) + .unwrap(); + let update = peer.encode_diff_v1(&before).unwrap(); + page.apply_remote_update_v1(&update).unwrap(); + } else { + page.format_text("p-two", "prop:text", 2, 5, attrs, 48) + .unwrap(); + } +} + +#[test] +fn refreshed_hover_popup_closes_and_rejects_actions_for_a_replaced_link() { + const COPY: &str = "overlay.link_popup.copy"; + const CLIPBOARD: &str = "Previous clipboard text"; + + for (peer_update, action) in [ + (false, None), + (true, None), + (false, Some(LinkPopupAction::Open)), + (true, Some(LinkPopupAction::Open)), + (false, Some(LinkPopupAction::Copy)), + (true, Some(LinkPopupAction::Copy)), + ] { + for mode in [PlaygroundMode::Page, PlaygroundMode::Edgeless] { + let (session, _) = open_links(); + let opened = if mode == PlaygroundMode::Edgeless { + enter_active_note(&session, 0.75); + let rect = session.view(|view, _| link_screen(view, "p-two")); + hover(&session, rect) + } else { + let (x, y) = screen_point(&session, "p-two", 3); + session.pointer(x, y, false); + advance(&session); + session.settle() + }; + assert!(opened.elements.contains_key(POPUP), "{mode:?}"); + assert!(opened.elements.contains_key(COPY), "{mode:?}"); + session.app.update(|cx| { + session + .window + .update(cx, |view, window, cx| { + let popup = view.overlays.link_popup().unwrap(); + assert!(popup.from_hover); + assert_eq!( + popup.target, + LinkPopupTarget::Link { + block_id: "p-two".into(), + start_utf16: 2, + end_utf16: 7, + url: URL.into(), + } + ); + cx.write_to_clipboard(ClipboardItem::new_string(CLIPBOARD.into())); + let page = view.state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + replace_first_link(page, peer_update); + view.refresh_document(); + if let Some(action) = action { + view.dispatch_overlay( + OverlayEvent::LinkPopupAction(action), + window, + cx, + ); + } + cx.notify(); + }) + .unwrap(); + }); + let refreshed = session.settle(); + let (target, ranges) = session.view(|view, _| { + assert!(view.last_opened_link_url.is_none()); + let (text, _) = view.page().unwrap().read_editable_text("p-two").unwrap(); + ( + view.overlays.link_popup().map(|popup| popup.target.clone()), + ( + matching_link_subranges(&text, 0, 20, NEW_URL), + matching_link_subranges(&text, 0, 20, URL), + ), + ) + }); + assert_eq!(ranges, (vec![(2, 7)], vec![(12, 17)])); + if target.is_some() && refreshed.elements.contains_key(COPY) { + session.click(&refreshed, COPY); + } + let copied = session + .app + .update(|cx| cx.read_from_clipboard().and_then(|item| item.text())); + let case = format!("{mode:?} {action:?} peer_update={peer_update}"); + assert_eq!(copied.as_deref(), Some(CLIPBOARD), "{case}"); + assert_eq!(target, None, "{case}"); + advance(&session); + assert!(!session.settle().elements.contains_key(POPUP), "{case}"); + } + } +} + #[test] fn active_note_link_hover_actions_and_exit_at_camera_zooms() { for zoom in [0.75, 0.45, 1.0] { let (session, _) = open_links(); - session.view(|view, cx| { - view.set_mode_immediate(PlaygroundMode::Edgeless, cx); - view.set_edgeless_camera(-200.0, -140.0, zoom, cx); - }); - let _ = session.settle(); - session.app.update(|cx| { - session - .window - .update(cx, |view, window, cx| { - assert!(view.edgeless_begin_inline_edit("n", window, cx)); - }) - .unwrap(); - }); - let _ = session.settle(); - + enter_active_note(&session, zoom); let link = session.view(|view, _| link_screen(view, "p-two")); let frame = hover(&session, link); if zoom == 0.75 { diff --git a/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs b/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs index fdca8ea43b..0bac8abe92 100644 --- a/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_link_popup/mod.rs @@ -637,14 +637,24 @@ impl PlaygroundView { })); } - /// Sync caret-triggered link/reference popup when a collapsed caret lands on a link or chip, - /// and re-validate any open hover/caret popup whenever the document revision advances. + /// Revalidate the open hover popup before it is painted. + pub(crate) fn sync_hover_link_popup(&mut self, now_ms: f64) { + if self.mode == PlaygroundMode::Edgeless && self.active_link_note_id().is_none() { + self.link_hover_pending = None; + self.link_hover_timer = None; + self.overlays.close_link_popup(now_ms); + return; + } + self.confirm_hover_link_popup(now_ms); + } + + /// Sync the caret popup when a collapsed caret lands on a link or chip. pub(crate) fn sync_link_popup_for_caret(&mut self, layout: &FlowLayout, now_ms: f64) { + self.sync_hover_link_popup(now_ms); if self.mode != PlaygroundMode::Page { return; } let page_rev = self.page().map_or(0, |p| p.revision()); - self.confirm_hover_link_popup(now_ms); let Some(sel) = self.editor.selection.as_ref().filter(|s| s.empty()) else { self.last_link_popup_caret = None; if self.overlays.link_popup().is_some_and(|p| !p.from_hover) { @@ -860,7 +870,7 @@ mod tests { }) } - fn screen_point(session: &Session, block: &str, offset: u64) -> (f32, f32) { + pub(super) fn screen_point(session: &Session, block: &str, offset: u64) -> (f32, f32) { let caret = caret_world(session, block, offset); let column_x = session.view(|v, _| v.current_page_geometry(1280.0).column_x); ( diff --git a/blocksuite/crates/playground/src/overlays/view_scrollbar.rs b/blocksuite/crates/playground/src/overlays/view_scrollbar.rs index 9d7792beb1..b7442997eb 100644 --- a/blocksuite/crates/playground/src/overlays/view_scrollbar.rs +++ b/blocksuite/crates/playground/src/overlays/view_scrollbar.rs @@ -1,5 +1,4 @@ -//! PlaygroundView glue for desktop Page-mode thin scrollbar thumb dragging, track clicks, -//! and window-root pointer move/up dispatch. +//! Page scrollbar rendering, thumb dragging, track clicks, and root pointer dispatch. use blocksuite_editor::database; use blocksuite_playground_doc::read::BlockContent; @@ -393,3 +392,183 @@ impl PlaygroundView { .into_any_element() } } + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::schema::BlockSpec; + use ui::{ + Modifiers, PlatformInput, ScrollDelta, ScrollEvent, ScrollSource, TouchEvent, TouchId, + TouchPhase, point, px, + }; + use y_octo::{Any, SessionValue}; + + use crate::{ + FormFactor, HOME_PAGE_ID, PlaygroundOptions, PlaygroundTheme, + overlays::tests::{Session, open_with_options}, + room_client::DocState, + }; + + fn open_code(form_factor: FormFactor, text: &str, wrap: bool) -> Session { + let session = open_with_options( + 390, + 844, + PlaygroundOptions { + form_factor, + theme: PlaygroundTheme::Light, + ..Default::default() + }, + ); + let mut state = DocState::new("code-scrollbar", 42).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Code sample", 1) + .unwrap(); + let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + for (id, spec, parent) in [ + ( + "root", + BlockSpec::Page { + title: "Code sample".into(), + }, + None, + ), + ("note", BlockSpec::Note { xywh: None }, Some("root")), + ( + "code", + BlockSpec::Code { + text: text.into(), + language: Some("rust".into()), + caption: String::new(), + }, + Some("note"), + ), + ] { + page.add_block(id, spec, parent, None, 2).unwrap(); + } + page.set_block_prop("code", "prop:wrap", SessionValue::Any(Any::from(wrap)), 3) + .unwrap(); + session.view(|view, cx| view.set_document(state, cx)); + session.settle(); + session + } + + #[test] + fn narrow_code_overflow_scrolls_and_paints_thumb_below_text() { + const LONG_LINE: &str = "let drafts = ComposerDraftStore::in_memory(workspace_id, current_document, initial_selection);"; + for form_factor in [FormFactor::Desktop, FormFactor::Phone] { + let session = open_code(form_factor, LONG_LINE, false); + let scroll = session.view(|view, _| { + view.flow_layout() + .unwrap() + .block("code") + .unwrap() + .body + .code_scroll + .unwrap() + }); + let bounds = session.settle().elements["page.block.code"].bounds; + let position = point( + px(bounds.x + bounds.width * 0.5), + px(bounds.y + scroll.area.y + 5.0), + ); + if form_factor == FormFactor::Phone { + for (phase, dx) in [ + (TouchPhase::Started, 0.0), + (TouchPhase::Moved, -45.0), + (TouchPhase::Moved, -90.0), + ] { + session + .headless + .dispatch_input(PlatformInput::Touch(TouchEvent { + id: TouchId(1), + phase, + position: point(position.x + px(dx), position.y), + ..Default::default() + })); + session.platform.run_until_parked(); + } + } else { + session.pointer(position.x.into(), position.y.into(), false); + session + .headless + .dispatch_input(PlatformInput::Scroll(ScrollEvent { + position, + delta: ScrollDelta::Pixels(point(px(-90.0), px(0.0))), + modifiers: Modifiers::default(), + touch_phase: TouchPhase::Moved, + source: ScrollSource::Pointer, + })); + } + session.settle(); + let offset = session.view(|view, _| view.overlays.code_scroll_x("code")); + if form_factor == FormFactor::Desktop { + assert_eq!(offset, 90.0_f32.min(scroll.max_x)); + } else { + assert!(offset > 0.0 && offset <= scroll.max_x, "{offset}"); + } + let render = || { + session.app.update(|cx| { + session + .window + .update(cx, |_, window, _| window.render_to_image().unwrap()) + .unwrap() + }) + }; + let desktop = form_factor == FormFactor::Desktop; + let hovered = desktop.then(render); + if let Some(image) = &hovered + && let Some(path) = std::env::var_os("TAIL_CODE_HOVER_PNG") + { + image.save(path).unwrap(); + } + if desktop { + session.pointer(1.0, 1.0, false); + session + .platform + .advance_clock(std::time::Duration::from_millis(400)); + } + let frame = session.settle(); + let idle = render(); + if desktop { + if let Some(path) = std::env::var_os("TAIL_CODE_PNG") { + idle.save(path).unwrap(); + } + assert_eq!( + frame.elements["page.block.code.hscrollbar"].bounds.height, + 24.0 + ); + } + let left = (bounds.x + scroll.area.x) as u32; + let right = (bounds.x + scroll.area.right()) as u32; + let y = (bounds.y + scroll.area.bottom() + 4.0) as u32; + let background = idle.get_pixel(left, y); + assert_eq!(background, idle.get_pixel((left + right) / 2, y + 4)); + let painted = (left..right) + .filter(|x| idle.get_pixel(*x, y) != background) + .count(); + let track = scroll.area.w - 8.0; + let thumb_w = (scroll.area.w / (scroll.area.w + scroll.max_x) * track).max(32.0); + assert!( + (painted as f32 - thumb_w).abs() <= 2.0, + "{form_factor:?}: {painted} vs {thumb_w}" + ); + if let Some(hovered) = hovered { + assert!((left..right).all(|x| hovered.get_pixel(x, y) == idle.get_pixel(x, y))); + } + } + for (text, wrap) in [("let x = 1;", false), (LONG_LINE, true)] { + let session = open_code(FormFactor::Desktop, text, wrap); + session.view(|view, _| { + assert!( + view.flow_layout() + .unwrap() + .block("code") + .unwrap() + .body + .code_scroll + .is_none() + ); + }); + } + } +} diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs index 75a46c63b4..edc51862b1 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/controls_tests.rs @@ -201,3 +201,74 @@ fn table_axis_swatches_write_v2_keys_and_clear_in_one_undo_step() { } } } + +#[test] +fn short_desktop_table_axis_menus_scroll_to_delete() { + const MENU: &str = "overlay.table_toolbar.axis_menu"; + const DELETE: &str = "overlay.table_toolbar.axis_menu.delete"; + for (pill, is_row) in [("row_pill", true), ("col_pill", false)] { + let session = open_table( + 560, + 240, + PlaygroundOptions { + hide_chrome: true, + form_factor: FormFactor::Desktop, + ..Default::default() + }, + ); + let before = table_data(&session); + let (x, y) = cell_point(&session, 0, 60.0, 18.0); + session.pointer(x, y, false); + session.click(&session.settle(), &format!("overlay.table_hover.{pill}")); + let frame = session.settle(); + let menu = frame.elements[MENU].bounds; + assert!(menu.y >= 8.0 && menu.y + menu.height <= 232.0, "{menu:?}"); + let visible_delete = |frame: &ui::FrameSnapshot| { + frame.elements.get(DELETE).is_some_and(|item| { + let mid = item.bounds.y + item.bounds.height * 0.5; + mid >= item.content_mask.y && mid < item.content_mask.y + item.content_mask.height + }) + }; + assert!(!visible_delete(&frame)); + let initial_delete = frame.elements.get(DELETE).cloned(); + + let position = ui::point( + ui::px(menu.x + menu.width * 0.5), + ui::px(menu.y + menu.height * 0.5), + ); + session.pointer(position.x.into(), position.y.into(), false); + session + .headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position, + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(0.0), ui::px(-220.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + let frame = session.settle(); + assert!( + visible_delete(&frame), + "{pill}: menu={menu:?} initial={initial_delete:?} final={:?}", + frame.elements.get(DELETE), + ); + session.click(&frame, DELETE); + let after = table_data(&session); + assert_eq!( + after.rows, + if is_row { + &before.rows[1..] + } else { + &before.rows[..] + } + ); + assert_eq!( + after.columns, + if is_row { + &before.columns[..] + } else { + &before.columns[1..] + } + ); + } +} 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 6c22861277..468426b116 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/toolbar.rs @@ -2,13 +2,15 @@ //! corner drag-to-add, 28 × 16 / 16 × 28 three-dot axis pills, 5 px `ew-resize` column dividers, //! and axis action menus) plus mobile touch table toolbar. +use std::{cell::Cell, rc::Rc}; + use ui::{ - AnyElement, CursorStyle, FontWeight, MouseButton, MouseDownEvent, SharedString, Window, div, + AnyElement, CursorStyle, FontWeight, MouseButton, MouseDownEvent, SharedString, div, prelude::*, px, }; use crate::{ - PlaygroundView, + PlaygroundMode, PlaygroundView, block_flow::{FlowLayout, FlowRect, PageViewport}, overlays::{ TOOLBAR_CHROME_BORDER, TOOLBAR_CHROME_RADIUS, TOOLBAR_MENU_MIN_W, TOOLBAR_MENU_PADDING, @@ -400,6 +402,7 @@ impl PlaygroundView { .theme .css_var("--affine-v2-table-indicator-pointerDefault") .unwrap_or(palette.icon); + let dot = || div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color); let pill_bg = chrome_panel_bg(palette); let pill_border = chrome_border_color(palette); let pill_shadow = palette.theme.shadows("--affine-button-shadow"); @@ -442,6 +445,7 @@ impl PlaygroundView { .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, win, cx| { + this.overlays.table_axis_scroll.set(0.0); this.open_table_axis_menu_for( bid_c.clone(), rid_c.clone(), @@ -460,9 +464,7 @@ impl PlaygroundView { .justify_center() .gap(px(2.5)) .snapshot("overlay.table_hover.col_pill", Some("root.canvas")) - .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) - .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) - .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)), + .children([dot(), dot(), dot()]), ), ); @@ -495,6 +497,7 @@ impl PlaygroundView { .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _, win, cx| { + this.overlays.table_axis_scroll.set(0.0); this.open_table_axis_menu_for( bid_r.clone(), rid_r.clone(), @@ -514,9 +517,7 @@ impl PlaygroundView { .justify_center() .gap(px(2.5)) .snapshot("overlay.table_hover.row_pill", Some("root.canvas")) - .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) - .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)) - .child(div().w(px(3.0)).h(px(3.0)).rounded(px(1.5)).bg(dot_color)), + .children([dot(), dot(), dot()]), ), ); } @@ -552,66 +553,11 @@ impl PlaygroundView { ) -> AnyElement { let is_row = axis == TableAxisMenu::Row; let menu_w = TOOLBAR_MENU_MIN_W.max(196.0); - let menu_h = 292.0 + TOOLBAR_MENU_ROW_H; + let max_height = (viewport_h - 16.0).max(120.0); + let menu_h = (292.0 + TOOLBAR_MENU_ROW_H).min(max_height); let left = x.clamp(8.0, (viewport_w - menu_w - 8.0).max(8.0)).round(); let top = y.clamp(8.0, (viewport_h - menu_h - 8.0).max(8.0)).round(); - let hover = palette.hover; - let err_bg = chrome_error_bg(palette); - let err_fg = chrome_error_fg(palette); - - let action_row = - |id: &'static str, - snap: &'static str, - icon: &'static str, - label: &'static str, - destructive: bool, - f: Box)>| { - let h_bg = if destructive { err_bg } else { hover }; - let h_fg = if destructive { - err_fg - } else { - palette.text_primary - }; - div() - .id(id) - .w_full() - .h(px(TOOLBAR_MENU_ROW_H)) - .px(px(8.0)) - .rounded(px(4.0)) - .flex() - .items_center() - .cursor_pointer() - .text_size(px(TYPOGRAPHY.font_sm_px)) - .text_color(palette.text_primary) - .hover(move |s| s.bg(h_bg).text_color(h_fg)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(move |this, _, win, cx| { - if let Some(cell) = this.table_cell.as_mut() { - cell.axis_menu = None; - } - f(this, win, cx); - cx.notify(); - })) - .snapshot( - format_args!("overlay.table_toolbar.axis_menu.{snap}"), - Some("overlay.table_toolbar.axis_menu"), - ) - .snapshot_text(label) - .gap(px(8.0)) - .child( - ui::canvas( - |_, _, _| (), - move |bounds, _, win, cx| { - crate::theme::IconPaint::named(icon).paint(bounds, h_fg, win, cx); - }, - ) - .w(px(16.0)) - .h(px(16.0)), - ) - .child(label) - }; - - div() + let menu = div() .id("table-axis-menu") .absolute() .left(px(left)) @@ -637,7 +583,12 @@ impl PlaygroundView { .snapshot( format_args!("overlay.table_toolbar.axis_menu"), Some("root.canvas"), - ) + ); + let mut contents = div() + .relative() + .flex() + .flex_col() + .flex_none() .child( div() .px(px(8.0)) @@ -648,92 +599,137 @@ impl PlaygroundView { .child("Background color"), ) .child(table_axis_swatches(is_row, palette, cx)) - .child(menu_horizontal_separator(palette)) - .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), + .child(menu_horizontal_separator(palette)); + let pick = |row, column| if is_row { row } else { column }; + let actions = [ + ( + "insert_before", + "PlusIcon", + pick("Insert Above", "Insert Left"), + ), + ( + "insert_after", + "PlusIcon", + pick("Insert Below", "Insert Right"), + ), + ( + "move_earlier", + pick("ArrowUpBigIcon", "MoveLeftIcon"), + pick("Move Up", "Move Left"), + ), + ( + "move_later", + pick("ArrowDownBigIcon", "MoveRightIcon"), + pick("Move Down", "Move Right"), + ), + ( + "duplicate", + "DuplicateIcon", + pick("Duplicate row", "Duplicate column"), + ), + ( + "clear", + "MinusIcon", + pick("Clear row contents", "Clear column contents"), + ), + ("delete", "DeleteIcon", pick("Delete Row", "Delete Column")), + ]; + for (op, (snap, icon, label)) in actions.into_iter().enumerate() { + if snap == "clear" { + contents = contents.child(menu_horizontal_separator(palette)); + } + let (h_bg, h_fg) = if snap == "delete" { + (chrome_error_bg(palette), chrome_error_fg(palette)) + } else { + (palette.hover, palette.text_primary) + }; + contents = contents.child( + div() + .id(snap) + .w_full() + .h(px(TOOLBAR_MENU_ROW_H)) + .px(px(8.0)) + .rounded(px(4.0)) + .flex() + .items_center() + .cursor_pointer() + .text_size(px(TYPOGRAPHY.font_sm_px)) + .text_color(palette.text_primary) + .hover(move |s| s.bg(h_bg).text_color(h_fg)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(move |this, _, win, cx| { + if let Some(cell) = this.table_cell.as_mut() { + cell.axis_menu = None; + } + match (op, is_row) { + (0, true) => _ = this.table_insert_row_before(win, cx), + (0, false) => _ = this.table_insert_column_before(win, cx), + (1, true) => _ = this.table_insert_row_after(win, cx), + (1, false) => _ = this.table_insert_column_after(win, cx), + (2, _) => _ = this.table_move_axis(is_row, true, win, cx), + (3, _) => _ = this.table_move_axis(is_row, false, win, cx), + (4, _) => this.duplicate_table_axis(is_row, win, cx), + (5, _) => _ = this.table_clear_axis(is_row, win, cx), + (6, true) => _ = this.table_delete_focused_row(win, cx), + (6, false) => _ = this.table_delete_focused_column(win, cx), _ => {} - }, - ); - 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() + } + cx.notify(); + })) + .snapshot( + format_args!("overlay.table_toolbar.axis_menu.{snap}"), + Some("overlay.table_toolbar.axis_menu"), + ) + .snapshot_text(label) + .gap(px(8.0)) + .child( + ui::canvas( + |_, _, _| (), + move |bounds, _, win, cx| { + crate::theme::IconPaint::named(icon).paint(bounds, h_fg, win, cx); + }, + ) + .w(px(16.0)) + .h(px(16.0)), + ) + .child(label), + ); + } + if self.mode != PlaygroundMode::Page || self.uses_touch_table_bar(viewport_w) { + return menu.child(contents).into_any_element(); + } + let visible = max_height - 2.0 * (TOOLBAR_MENU_PADDING + TOOLBAR_CHROME_BORDER.ceil()); + let offset = self.overlays.table_axis_scroll.clone(); + let max_scroll = Rc::new(Cell::new(0.0)); + let measured = max_scroll.clone(); + let scroll_position = offset.clone(); + let contents = contents.top(px(-offset.get())).child( + ui::canvas( + move |bounds, window, _| { + let limit = (f32::from(bounds.size.height) - visible).max(0.0); + measured.set(limit); + if scroll_position.get() > limit { + scroll_position.set(limit); + window.refresh(); + } + }, + |_, (), _, _| {}, + ) + .absolute() + .inset_0(), + ); + let mut clip = div() + .overflow_hidden() + .on_scroll(cx.listener(move |_, event, _, cx| { + let dy = blocksuite_editor::scroll::wheel_delta(event, visible).1; + let next = (offset.get() - dy).clamp(0.0, max_scroll.get()); + cx.stop_propagation(); + if next != offset.replace(next) { + cx.notify(); + } + })); + clip.style().max_size.height = Some(px(visible).into()); + menu.child(clip.child(contents)).into_any_element() } } @@ -766,6 +762,7 @@ fn table_axis_swatches( }); swatches.fold( div() + .flex_none() .flex() .flex_wrap() .items_center()