diff --git a/blocksuite/crates/editor/src/block_flow/body.rs b/blocksuite/crates/editor/src/block_flow/body.rs index 9ed713ea8e..556dd79575 100644 --- a/blocksuite/crates/editor/src/block_flow/body.rs +++ b/blocksuite/crates/editor/src/block_flow/body.rs @@ -12,6 +12,7 @@ use ui::{App, Bounds, Corners, Hsla, Pixels, Point, SharedString, Window, point, use crate::{ rich_text::{CaretPosition, LaidOutRichParagraph, WrapAffinity}, + scroll::snap_device_pixel, theme::{IconPaint, PlaygroundTheme}, }; @@ -408,35 +409,31 @@ impl BlockBody { window: &mut Window, cx: &mut App, ) { - if self.kind == FlowKind::Table - && let Some(scroll_cfg) = self.code_scroll + let scale = window.scale_factor(); + if let Some(scroll_cfg) = self.code_scroll + && matches!(self.kind, FlowKind::Table | FlowKind::Database) { - let scroll = state.code_scroll_x.clamp(0.0, scroll_cfg.max_x); + let scroll = snap_device_pixel(state.code_scroll_x.clamp(0.0, scroll_cfg.max_x), scale); let shifted = point(origin.x - px(scroll), origin.y); let bounds = scroll_cfg.area.bounds(origin); - window.with_local_paint_mask(ui::ContentMask { bounds }, |window| { - self.paint_prims(shifted, state, window, cx); - }); - return; - } - if self.kind == FlowKind::Database - && let Some(scroll_cfg) = self.code_scroll - { - let scroll = state.code_scroll_x.clamp(0.0, scroll_cfg.max_x); - let shifted = point(origin.x - px(scroll), origin.y); - let split_y = scroll_cfg.area.y; - // Two passes over the prims in place: the fixed ones, then the scrolled ones. - let fixed = |idx: usize, prim: &Prim| idx == 0 || prim_top_y(prim) < split_y; - let prims = || self.prims.iter().enumerate(); - for (_, prim) in prims().filter(|(idx, prim)| fixed(*idx, prim)) { - self.paint_single_prim(prim, origin, state, window, cx); - } - let bounds = scroll_cfg.area.bounds(origin); - window.with_local_paint_mask(ui::ContentMask { bounds }, |window| { - for (_, prim) in prims().filter(|(idx, prim)| !fixed(*idx, prim)) { - self.paint_single_prim(prim, shifted, state, window, cx); + if self.kind == FlowKind::Table { + window.with_local_paint_mask(ui::ContentMask { bounds }, |window| { + self.paint_prims(shifted, state, window, cx); + }); + } else { + let split_y = scroll_cfg.area.y; + // Two passes over the prims in place: the fixed ones, then the scrolled ones. + let fixed = |idx: usize, prim: &Prim| idx == 0 || prim_top_y(prim) < split_y; + let prims = || self.prims.iter().enumerate(); + for (_, prim) in prims().filter(|(idx, prim)| fixed(*idx, prim)) { + self.paint_single_prim(prim, origin, state, window, cx); } - }); + window.with_local_paint_mask(ui::ContentMask { bounds }, |window| { + for (_, prim) in prims().filter(|(idx, prim)| !fixed(*idx, prim)) { + self.paint_single_prim(prim, shifted, state, window, cx); + } + }); + } return; } self.paint_prims(origin, state, window, cx); @@ -464,9 +461,10 @@ impl BlockBody { ) { match prim { Prim::CodeLine { x, y, layout, clip } => { - let scroll = self - .code_scroll - .map_or(0.0, |code| state.code_scroll_x.clamp(0.0, code.max_x)); + let scale = window.scale_factor(); + let scroll = self.code_scroll.map_or(0.0, |c| { + snap_device_pixel(state.code_scroll_x.clamp(0.0, c.max_x), scale) + }); let text_origin = point(origin.x + px(*x - scroll), origin.y + px(*y)); window.with_local_paint_mask( ui::ContentMask { diff --git a/blocksuite/crates/editor/src/block_flow/layout.rs b/blocksuite/crates/editor/src/block_flow/layout.rs index 06e92ada09..0a80439af5 100644 --- a/blocksuite/crates/editor/src/block_flow/layout.rs +++ b/blocksuite/crates/editor/src/block_flow/layout.rs @@ -24,7 +24,7 @@ pub struct BlockFlow { database_popover_anchors: HashMap, database_active_cells: HashMap, database_overflow_tabs: HashMap>, - database_view_tabs_max_scroll: HashMap, + database_view_tabs_max_scroll: HashMap, pub database_state: crate::database::DatabaseFlowState, /// `affine:code` block ids currently toggled into visual preview mode (zero CRDT writeback). pub code_preview_blocks: BTreeSet, @@ -57,7 +57,7 @@ pub(super) struct FlowPass<'a> { pub(super) database_popover_anchors: HashMap, pub(super) database_active_cells: HashMap, pub(super) database_overflow_tabs: HashMap>, - pub(super) database_view_tabs_max_scroll: HashMap, + pub(super) database_view_tabs_max_scroll: HashMap, pub(super) code_preview_blocks: &'a BTreeSet, pub(super) local_collapsed: &'a BTreeSet, pub(super) focused_table_block: Option<&'a str>, @@ -124,16 +124,16 @@ impl BlockFlow { } /// Measured `(scroll_px, max_scroll_px)` of `block_id`'s touch view-tab strip. - pub fn database_view_tabs_metrics(&self, block_id: &str) -> (i32, i32) { + pub fn database_view_tabs_metrics(&self, block_id: &str) -> (f32, f32) { self.database_view_tabs_max_scroll .get(block_id) .copied() - .unwrap_or((0, 0)) + .unwrap_or((0.0, 0.0)) } - /// Measured horizontal overflow (whole px, `0` when not overflowing) of `block_id`'s + /// Measured horizontal overflow (logical px, `0.0` when not overflowing) of `block_id`'s /// touch view-tab strip from the latest layout pass. - pub fn database_view_tabs_max_scroll(&self, block_id: &str) -> i32 { + pub fn database_view_tabs_max_scroll(&self, block_id: &str) -> f32 { self.database_view_tabs_metrics(block_id).1 } diff --git a/blocksuite/crates/editor/src/database/authoring.rs b/blocksuite/crates/editor/src/database/authoring.rs index b7f319eee7..427298d86f 100644 --- a/blocksuite/crates/editor/src/database/authoring.rs +++ b/blocksuite/crates/editor/src/database/authoring.rs @@ -104,12 +104,13 @@ pub struct KanbanDragState { } /// All transient authoring UI state for one `affine:database` block. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct DatabaseAuthoringState { pub column_menu: Option, pub column_resize: Option, pub progress_preview: Option, pub active_cell: Option, + pub select_scroll_y: f32, pub toolbar_panel: Option, pub filter_draft: FilterDraftState, pub calendar_drag: Option, @@ -120,6 +121,7 @@ impl DatabaseAuthoringState { pub fn dismiss_popovers(&mut self) { self.column_menu = None; self.active_cell = None; + self.select_scroll_y = 0.0; self.toolbar_panel = None; } } @@ -356,9 +358,11 @@ pub fn handle_authoring_key( }); } DatabaseAuthoringKey::Backspace => { - if let Some(ed) = flow_state.authoring_mut(block_id).active_cell.as_mut() { + let auth = flow_state.authoring_mut(block_id); + if let Some(ed) = auth.active_cell.as_mut() { if is_select { ed.select_filter.pop(); + auth.select_scroll_y = 0.0; } else { ed.draft.pop(); ed.error = None; @@ -370,9 +374,11 @@ pub fn handle_authoring_key( }); } DatabaseAuthoringKey::Text(s) => { - if let Some(ed) = flow_state.authoring_mut(block_id).active_cell.as_mut() { + let auth = flow_state.authoring_mut(block_id); + if let Some(ed) = auth.active_cell.as_mut() { if is_select { ed.select_filter.push_str(&s); + auth.select_scroll_y = 0.0; } else { ed.draft.push_str(&s); ed.error = None; diff --git a/blocksuite/crates/editor/src/database/authoring_dispatch.rs b/blocksuite/crates/editor/src/database/authoring_dispatch.rs index 04bced8bfe..dd5e3eefea 100644 --- a/blocksuite/crates/editor/src/database/authoring_dispatch.rs +++ b/blocksuite/crates/editor/src/database/authoring_dispatch.rs @@ -366,9 +366,11 @@ pub fn handle_authoring_hit( if is_multi { if let Some(ed) = auth.active_cell.as_mut() { ed.select_filter.clear(); + auth.select_scroll_y = 0.0; } } else { auth.active_cell = None; + auth.select_scroll_y = 0.0; } Ok(AuthoringActionResult { handled: true, diff --git a/blocksuite/crates/editor/src/database/cell_editor.rs b/blocksuite/crates/editor/src/database/cell_editor.rs index cb88939922..9c5a3f2e0c 100644 --- a/blocksuite/crates/editor/src/database/cell_editor.rs +++ b/blocksuite/crates/editor/src/database/cell_editor.rs @@ -1,25 +1,22 @@ //! In-place cell property editors for `affine:database` (Table & Kanban): //! validation/parsing for Number, Date, URL, Progress, RichText, Title; -//! Select / Multi-select dropdown popover rendering (toggle, create colored pill, rename/delete); -//! and Tab / Shift+Tab navigation across editable cells. +//! rich-text cell layout helpers; and Tab / Shift+Tab navigation across editable cells. use blocksuite_playground_doc::{ - read::{DatabaseCellValue, DatabaseColumn, DatabaseData, DatabaseRow}, + read::{DatabaseColumn, DatabaseData, DatabaseRow}, schema::DatabaseCellSpec, }; use crate::{ - block_flow::{FlowRect, InlineAlign, InlineStyle}, - theme::{FONT_SANS, IconPaint, TYPOGRAPHY}, + block_flow::{FlowRect, InlineAlign}, + theme::TYPOGRAPHY, }; use super::{ - authoring::{ActiveCellEditor, DatabaseAuthoringHit, DatabaseAuthoringHitKind}, calendar::days_from_civil, column_ops::TAG_COLOR_PALETTE, format_database_date, render::{DatabasePrim, DbRenderCtx}, - resolve_tag_color, }; /// Result of validating and parsing an inline cell draft string for commit. @@ -266,283 +263,6 @@ pub fn next_tag_color(existing_count: usize) -> &'static str { TAG_COLOR_PALETTE[existing_count % TAG_COLOR_PALETTE.len()] } -/// Compute screen-space `(width, height)` for the `Select` / `Multi-select` picker popover. -pub(super) fn measure_select_popover_size( - ctx: &DbRenderCtx<'_>, - editor: &ActiveCellEditor, -) -> Option<(f32, f32)> { - let col = ctx.data.columns.iter().find(|c| c.id == editor.column_id)?; - let options = col.select_options(); - let query = editor.select_filter.trim(); - let query_lower = query.to_ascii_lowercase(); - let filtered_len = options - .iter() - .filter(|o| query_lower.is_empty() || o.value.to_ascii_lowercase().contains(&query_lower)) - .count(); - let exact_match = - !query.is_empty() && options.iter().any(|o| o.value.eq_ignore_ascii_case(query)); - let show_create = !query.is_empty() && !exact_match; - let pad = 6.0_f32; - let input_h = 28.0_f32; - let row_h = 28.0_f32; - let create_rows = usize::from(show_create); - let list_rows = filtered_len.max(usize::from(!show_create)); - let pop_h = pad * 2.0 + input_h + 8.0 + (list_rows + create_rows) as f32 * row_h; - Some((236.0, pop_h)) -} - -/// Render the `Select` / `Multi-select` option picker popover at `pop_rect` (screen space), -/// returning the screen-space rect of its search/create input box. -#[allow(clippy::too_many_arguments)] -pub(super) fn render_select_popover_at( - ctx: &DbRenderCtx<'_>, - editor: &ActiveCellEditor, - pop_rect: FlowRect, - prims: &mut Vec, - authoring_hits: &mut Vec, -) -> Option { - let col = ctx.data.columns.iter().find(|c| c.id == editor.column_id)?; - let options = col.select_options(); - let selected_ids: Vec = ctx - .data - .cells - .get(&(editor.row_id.clone(), editor.column_id.clone())) - .map(DatabaseCellValue::as_string_list) - .unwrap_or_default(); - - let query = editor.select_filter.trim(); - let query_lower = query.to_ascii_lowercase(); - let filtered: Vec<_> = options - .iter() - .filter(|o| query_lower.is_empty() || o.value.to_ascii_lowercase().contains(&query_lower)) - .collect(); - let exact_match = - !query.is_empty() && options.iter().any(|o| o.value.eq_ignore_ascii_case(query)); - let show_create = !query.is_empty() && !exact_match; - - let pop_w = pop_rect.w; - let pad = 6.0_f32; - let input_h = 28.0_f32; - let row_h = 28.0_f32; - - prims.push(DatabasePrim::Quad { - rect: pop_rect, - fill: Some(ctx.palette.panel), - border: Some(ctx.palette.border), - radius: 8.0, - dashed: false, - }); - - // Search / create input field (text + caret painted live by InlineBoxPaint when non-empty). - let input_rect = FlowRect::new( - pop_rect.x + pad, - pop_rect.y + pad, - (pop_w - 2.0 * pad).max(1.0), - input_h, - ); - prims.push(DatabasePrim::Quad { - rect: input_rect, - fill: Some(ctx.palette.background), - border: Some(ctx.palette.brand), - radius: 4.0, - dashed: false, - }); - if editor.select_filter.is_empty() { - prims.push(ctx.single_line_clipped( - "Search or create option…", - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px + 1.0, - 400.0, - ctx.palette.placeholder, - ), - input_rect.x + 8.0, - input_rect.y, - (input_rect.w - 16.0).max(1.0), - input_h, - InlineAlign::Left, - )); - } - - // Single divider below input. - let div_y = input_rect.bottom() + 4.0; - prims.push(DatabasePrim::Quad { - rect: FlowRect::new(pop_rect.x + pad, div_y, (pop_w - 2.0 * pad).max(1.0), 1.0), - fill: Some(ctx.palette.border), - border: None, - radius: 0.0, - dashed: false, - }); - - let mut ry = div_y + 4.0; - if filtered.is_empty() && !show_create { - let empty_rect = FlowRect::new(pop_rect.x + pad, ry, (pop_w - 2.0 * pad).max(1.0), row_h); - prims.push(ctx.single_line_clipped( - "No options yet", - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - 400.0, - ctx.palette.text_secondary, - ), - empty_rect.x + 8.0, - empty_rect.y, - (empty_rect.w - 16.0).max(1.0), - row_h, - InlineAlign::Left, - )); - } else { - for opt in filtered { - let is_selected = selected_ids - .iter() - .any(|id| id == &opt.id || id == &opt.value); - let row_rect = FlowRect::new(pop_rect.x + pad, ry, (pop_w - 2.0 * pad).max(1.0), row_h); - if is_selected { - prims.push(DatabasePrim::Quad { - rect: row_rect, - fill: Some(ctx.palette.hover), - border: None, - radius: 4.0, - dashed: false, - }); - } - let (bg, ink) = resolve_tag_color(&opt.color, ctx.theme); - let pill_style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, ink); - let max_pill_w = (row_rect.w - 58.0).max(32.0); - let (_, pill_layout) = - ctx.truncate_text(&opt.value, pill_style, (max_pill_w - 12.0).max(1.0), 20.0); - let pill_w = (pill_layout.content_width().ceil() + 12.0).min(max_pill_w); - let pill_rect = FlowRect::new(row_rect.x + 6.0, row_rect.y + 4.0, pill_w, 20.0); - prims.push(DatabasePrim::Quad { - rect: pill_rect, - fill: Some(bg), - border: None, - radius: 4.0, - dashed: false, - }); - prims.push(DatabasePrim::Text { - x: pill_rect.x + 6.0, - y: pill_rect.y, - layout: pill_layout, - clip: Some(FlowRect::new( - pill_rect.x + 4.0, - pill_rect.y, - (pill_rect.w - 8.0).max(1.0), - 20.0, - )), - }); - - if is_selected { - prims.push(DatabasePrim::Icon { - rect: FlowRect::new(row_rect.right() - 42.0, row_rect.y + 7.0, 14.0, 14.0), - icon: IconPaint::from_def(&ui_tokens::icons::CHECKBOX_CHECKED_LINEAR), - color: ctx.palette.brand, - }); - } - - // Delete option button on trailing edge (22x22 target). - let del_rect = FlowRect::new(row_rect.right() - 24.0, row_rect.y + 3.0, 22.0, 22.0); - prims.push(ctx.single_line_clipped( - "×", - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_sm_px, - 500.0, - ctx.palette.text_secondary, - ), - del_rect.x, - del_rect.y, - del_rect.w, - del_rect.h, - InlineAlign::Center, - )); - - let select_hit_rect = - FlowRect::new(row_rect.x, row_rect.y, (row_rect.w - 26.0).max(1.0), row_h); - authoring_hits.push(DatabaseAuthoringHit { - rect: select_hit_rect, - kind: DatabaseAuthoringHitKind::SelectToggleOption { - row_id: editor.row_id.clone(), - column_id: editor.column_id.clone(), - option_id: opt.id.clone(), - }, - scrolls_x: false, - }); - authoring_hits.push(DatabaseAuthoringHit { - rect: del_rect, - kind: DatabaseAuthoringHitKind::SelectDeleteOption { - column_id: editor.column_id.clone(), - option_id: opt.id.clone(), - }, - scrolls_x: false, - }); - ry += row_h; - } - } - - if show_create { - let create_rect = FlowRect::new(pop_rect.x + pad, ry, (pop_w - 2.0 * pad).max(1.0), row_h); - prims.push(DatabasePrim::Quad { - rect: create_rect, - fill: Some(ctx.palette.background_secondary), - border: None, - radius: 4.0, - dashed: false, - }); - let color = next_tag_color(options.len()); - let (bg, ink) = resolve_tag_color(color, ctx.theme); - prims.push(ctx.single_line_clipped( - "Create", - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - 500.0, - ctx.palette.text_secondary, - ), - create_rect.x + 6.0, - create_rect.y, - 44.0, - row_h, - InlineAlign::Left, - )); - let pill_style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, ink); - let max_pw = (create_rect.w - 60.0).max(24.0); - let (_, pill_layout) = ctx.truncate_text(query, pill_style, (max_pw - 12.0).max(1.0), 20.0); - let pw = (pill_layout.content_width().ceil() + 12.0).min(max_pw); - let pill_rect = FlowRect::new(create_rect.x + 52.0, create_rect.y + 4.0, pw, 20.0); - prims.push(DatabasePrim::Quad { - rect: pill_rect, - fill: Some(bg), - border: None, - radius: 4.0, - dashed: false, - }); - prims.push(DatabasePrim::Text { - x: pill_rect.x + 6.0, - y: pill_rect.y, - layout: pill_layout, - clip: Some(FlowRect::new( - pill_rect.x + 4.0, - pill_rect.y, - (pill_rect.w - 8.0).max(1.0), - 20.0, - )), - }); - authoring_hits.push(DatabaseAuthoringHit { - rect: create_rect, - kind: DatabaseAuthoringHitKind::SelectCreateOption { - row_id: editor.row_id.clone(), - column_id: editor.column_id.clone(), - label: query.to_string(), - color: color.to_string(), - }, - scrolls_x: false, - }); - } - - Some(input_rect) -} - #[allow(clippy::too_many_arguments)] pub(super) fn layout_rich_cell_sized( ctx: &DbRenderCtx<'_>, diff --git a/blocksuite/crates/editor/src/database/mod.rs b/blocksuite/crates/editor/src/database/mod.rs index a14bdf1cc5..a17641cc75 100644 --- a/blocksuite/crates/editor/src/database/mod.rs +++ b/blocksuite/crates/editor/src/database/mod.rs @@ -19,6 +19,7 @@ mod render_kanban; mod render_kanban_card; mod render_table; mod render_types; +mod select_popover; mod sort_key; use std::collections::{BTreeSet, HashMap}; @@ -68,6 +69,7 @@ pub use query::{eval_database_filter_with_titles, sort_database_rows_with_titles pub use render::{DatabaseLayoutOutput, DatabasePrim, layout_database_block}; pub use render_calendar::resolve_calendar_display_month; pub use render_types::DatabaseActiveCellLayout; +pub use select_popover::{SELECT_POPOVER_MAX_HEIGHT, select_popover_max_scroll}; /// Unified logical-to-physical horizontal coordinate mapper shared by `affine:table` /// and `affine:database` (`Table`, `Kanban`, and `Calendar` views). @@ -135,7 +137,7 @@ impl InlineAxis { } /// View-layer (zero-CRDT-writeback) state for one `affine:database` block. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct DatabaseUiState { /// Currently selected view id (mirrors `currentViewStorage` in `0.27.5`). pub active_view_id: Option, @@ -147,8 +149,8 @@ pub struct DatabaseUiState { pub calendar_hovered_day: Option, /// Hovered bucket key in Desktop Kanban view (reveals lane footer `+ Add` button). pub kanban_hovered_lane: Option, - /// Horizontal scroll offset (whole px) for the touch database view tab strip. - pub view_tabs_scroll_px: i32, + /// Horizontal scroll offset (subpixel logical px) for the touch database view tab strip. + pub view_tabs_scroll_px: f32, /// One-shot hint set when switching `active_view_id` so the next layout pass brings the newly /// activated tab into view without overriding subsequent manual horizontal scrolling. pub reveal_active_tab: bool, @@ -295,11 +297,11 @@ impl DatabaseFlowState { } /// Scroll the view tabs from their stored offset. See [`Self::scroll_view_tabs_from`]. - pub fn scroll_view_tabs(&mut self, block_id: &str, delta_px: i32, max_px: i32) -> bool { + pub fn scroll_view_tabs(&mut self, block_id: &str, delta_px: f32, max_px: f32) -> bool { let stored = self .ui_states .get(block_id) - .map_or(0, |state| state.view_tabs_scroll_px); + .map_or(0.0, |state| state.view_tabs_scroll_px); self.scroll_view_tabs_from(block_id, stored, delta_px, max_px) } @@ -310,24 +312,25 @@ impl DatabaseFlowState { pub fn scroll_view_tabs_from( &mut self, block_id: &str, - base_scroll_px: i32, - delta_px: i32, - max_px: i32, + base_scroll_px: f32, + delta_px: f32, + max_px: f32, ) -> bool { let state = self.ui_states.get(block_id); let revealing = state.is_some_and(|state| state.reveal_active_tab); let start = if revealing { base_scroll_px } else { - state.map_or(0, |state| state.view_tabs_scroll_px) + state.map_or(0.0, |state| state.view_tabs_scroll_px) }; - let next = (start - delta_px).clamp(0, max_px.max(0)); - if next == start && !revealing { + let mut axis = crate::scroll::ScrollAxis::new(start, max_px); + let moved = axis.apply(delta_px); + if !moved && !revealing { return false; } let entry = self.ui_states.entry(block_id.to_string()).or_default(); entry.reveal_active_tab = false; - entry.view_tabs_scroll_px = next; + entry.view_tabs_scroll_px = axis.offset; self.mark_dirty(block_id); true } @@ -722,20 +725,21 @@ mod tests { fn view_tabs_scroll_marks_dirty_when_offset_or_reveal_changes_and_adds_no_empty_state() { let mut state = DatabaseFlowState::default(); // A scroll that stays at offset 0 on a block without view state changes nothing. - assert!(!state.scroll_view_tabs("db", 1, 40)); - assert!(!state.scroll_view_tabs_from("db", 0, 1, 40)); + assert!(!state.scroll_view_tabs("db", 1.0, 40.0)); + assert!(!state.scroll_view_tabs_from("db", 0.0, 1.0, 40.0)); assert_eq!((state.ui_states.len(), state.revision()), (0, 0)); // A view switch starts the reveal of the active tab. The stored offset stays 0. state.set_active_view("db", "v-9"); state.take_dirty_blocks(); // (delta, changed, stored offset): the first scroll stays at 0 but stops the reveal. - for (step, (delta, changed, offset)) in [(1, true, 0), (1, false, 0), (-12, true, 12)] - .into_iter() - .enumerate() + for (step, (delta, changed, offset)) in + [(1.0, true, 0.0), (1.0, false, 0.0), (-12.0, true, 12.0)] + .into_iter() + .enumerate() { assert_eq!( - state.scroll_view_tabs("db", delta, 40), + state.scroll_view_tabs("db", delta, 40.0), changed, "step {step}" ); @@ -764,10 +768,10 @@ mod tests { s.close_more_views("db"); }), ("scroll_view_tabs", |s| { - s.scroll_view_tabs("db", -12, 40); + s.scroll_view_tabs("db", -12.0, 40.0); }), ("scroll_view_tabs_from", |s| { - s.scroll_view_tabs_from("db", 0, -12, 40); + s.scroll_view_tabs_from("db", 0.0, -12.0, 40.0); }), ("step_calendar_month", |s| { s.step_calendar_month("db", (2026, 12), 1) diff --git a/blocksuite/crates/editor/src/database/popover_overlay.rs b/blocksuite/crates/editor/src/database/popover_overlay.rs index 5cb78505d7..8ca45147ab 100644 --- a/blocksuite/crates/editor/src/database/popover_overlay.rs +++ b/blocksuite/crates/editor/src/database/popover_overlay.rs @@ -16,9 +16,9 @@ use crate::{ use super::{ DatabaseUiState, authoring::{DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePopoverAnchor}, - cell_editor, column_ops, eval_database_filter_with_titles, filter_sort_bar, + column_ops, eval_database_filter_with_titles, filter_sort_bar, render::{DatabasePrim, DbRenderCtx, tab_label_for}, - sort_database_rows_with_titles, + select_popover, sort_database_rows_with_titles, }; /// Screen-space geometry, paint primitives, and hit targets for an active database popover. @@ -160,7 +160,7 @@ pub fn layout_database_popover_overlay( .as_ref() .filter(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) { - let size = cell_editor::measure_select_popover_size(&ctx, ed)?; + let size = select_popover::measure_select_popover_size(&ctx, ed)?; let placed = place_popover( anchor_screen, size, @@ -170,7 +170,7 @@ pub fn layout_database_popover_overlay( 8.0, ); let input_rect = - cell_editor::render_select_popover_at(&ctx, ed, placed.rect, &mut prims, &mut hits); + select_popover::render_select_popover_at(&ctx, ed, placed.rect, &mut prims, &mut hits); (placed.rect, input_rect) } else if !mobile_readonly && let Some(panel) = auth.toolbar_panel { let size = filter_sort_bar::measure_toolbar_panel_size(&ctx, active_view, panel); diff --git a/blocksuite/crates/editor/src/database/render.rs b/blocksuite/crates/editor/src/database/render.rs index 8da6a3bb53..226d01e62e 100644 --- a/blocksuite/crates/editor/src/database/render.rs +++ b/blocksuite/crates/editor/src/database/render.rs @@ -265,8 +265,8 @@ pub fn layout_database_block( let mut more_views_anchor: Option = None; let mut wrap_toolbar_below = false; let mut overflow_tabs: Vec = Vec::new(); - let mut view_tabs_scroll_px = 0_i32; - let mut view_tabs_max_scroll_px = 0_i32; + let mut view_tabs_scroll_px = 0.0_f32; + let mut view_tabs_max_scroll_px = 0.0_f32; if is_touch { // Phone / Tablet: single-row horizontal scroll strip with clean clipping; // auto-scroll into view runs only when `reveal_active_tab` is set by a view switch @@ -277,8 +277,8 @@ pub fn layout_database_block( let total_w: f32 = measured_tabs.iter().map(|t| t.w).sum::() + measured_tabs.len().saturating_sub(1) as f32 * tab_gap; let max_scroll = (total_w - strip_w).max(0.0); - view_tabs_max_scroll_px = max_scroll.ceil() as i32; - let mut scroll_x = (ui_state.view_tabs_scroll_px as f32).clamp(0.0, max_scroll); + view_tabs_max_scroll_px = max_scroll; + let mut scroll_x = ui_state.view_tabs_scroll_px.clamp(0.0, max_scroll); if ui_state.reveal_active_tab { let mut tab_offset = 0.0_f32; let last_idx = measured_tabs.len().saturating_sub(1); @@ -306,9 +306,10 @@ pub fn layout_database_block( tab_offset += tab.w + tab_gap; } } - view_tabs_scroll_px = scroll_x.round() as i32; + view_tabs_scroll_px = scroll_x; + let snapped_scroll_x = crate::scroll::snap_device_pixel(scroll_x, window.scale_factor()); let clip_rect = axis.map_rect(FlowRect::new(strip_left, y, strip_w, tab_h)); - let mut cursor = strip_left - scroll_x; + let mut cursor = strip_left - snapped_scroll_x; let mut active_bounds: Option<(f32, f32)> = None; for tab in &measured_tabs { let tab_right = cursor + tab.w; diff --git a/blocksuite/crates/editor/src/database/render_types.rs b/blocksuite/crates/editor/src/database/render_types.rs index 3c4a9e2b26..ed40a00da5 100644 --- a/blocksuite/crates/editor/src/database/render_types.rs +++ b/blocksuite/crates/editor/src/database/render_types.rs @@ -70,8 +70,8 @@ pub struct DatabaseLayoutOutput { pub popover_anchor: Option, pub active_cell: Option, pub overflow_tabs: Vec, - pub view_tabs_scroll_px: i32, - pub view_tabs_max_scroll_px: i32, + pub view_tabs_scroll_px: f32, + pub view_tabs_max_scroll_px: f32, } /// Shared rendering context passed into Table / Kanban / Calendar view painters. diff --git a/blocksuite/crates/editor/src/database/select_popover.rs b/blocksuite/crates/editor/src/database/select_popover.rs new file mode 100644 index 0000000000..cc1837614a --- /dev/null +++ b/blocksuite/crates/editor/src/database/select_popover.rs @@ -0,0 +1,429 @@ +//! Capped (`max-height: 400 px`) subpixel-scrollable `Select` / `Multi-select` dropdown popover +//! for `affine:database` cells. + +use blocksuite_playground_doc::read::{DatabaseCellValue, DatabaseData}; + +use crate::{ + block_flow::{FlowRect, InlineAlign, InlineStyle}, + scroll::snap_device_pixel, + theme::{FONT_SANS, IconPaint, TYPOGRAPHY}, +}; + +use super::{ + authoring::{ActiveCellEditor, DatabaseAuthoringHit, DatabaseAuthoringHitKind}, + cell_editor::next_tag_color, + render::{DatabasePrim, DbRenderCtx}, + resolve_tag_color, +}; + +/// Maximum outer height (logical px) for the Database `Select` / `Multi-select` dropdown +/// popover (`maxHeight: 400px; overflowY: auto` in BlockSuite). +pub const SELECT_POPOVER_MAX_HEIGHT: f32 = 400.0; + +const SELECT_POP_PAD: f32 = 6.0; +const SELECT_INPUT_H: f32 = 28.0; +const SELECT_ROW_H: f32 = 28.0; +const SELECT_DIV_H: f32 = 1.0; +const SELECT_DIV_GAP: f32 = 4.0; +const SELECT_HEADER_OFFSET: f32 = + SELECT_POP_PAD + SELECT_INPUT_H + SELECT_DIV_GAP + SELECT_DIV_H + SELECT_DIV_GAP; +const SELECT_CHROME_H: f32 = SELECT_HEADER_OFFSET + SELECT_POP_PAD; +const SELECT_CREATE_SEP_GAP: f32 = 5.0; + +#[derive(Clone, Copy, Debug)] +struct SelectPopoverLayout { + has_list_rows: bool, + content_h: f32, + create_section_h: f32, + max_scroll: f32, + total_h: f32, +} + +fn compute_select_popover_layout( + data: &DatabaseData, + editor: &ActiveCellEditor, +) -> Option { + let col = data.columns.iter().find(|c| c.id == editor.column_id)?; + let options = col.select_options(); + let query = editor.select_filter.trim(); + let query_lower = query.to_ascii_lowercase(); + let filtered_len = options + .iter() + .filter(|o| query_lower.is_empty() || o.value.to_ascii_lowercase().contains(&query_lower)) + .count(); + let exact_match = + !query.is_empty() && options.iter().any(|o| o.value.eq_ignore_ascii_case(query)); + let show_create = !query.is_empty() && !exact_match; + let list_rows = filtered_len.max(usize::from(!show_create)); + let has_list_rows = list_rows > 0; + let create_section_h = if show_create { + SELECT_ROW_H + + if has_list_rows { + SELECT_CREATE_SEP_GAP + } else { + 0.0 + } + } else { + 0.0 + }; + let content_h = list_rows as f32 * SELECT_ROW_H; + let max_list_h = (SELECT_POPOVER_MAX_HEIGHT - SELECT_CHROME_H - create_section_h).max(0.0); + let list_h = content_h.min(max_list_h); + let max_scroll = (content_h - list_h).max(0.0); + let total_h = (SELECT_CHROME_H + list_h + create_section_h).min(SELECT_POPOVER_MAX_HEIGHT); + Some(SelectPopoverLayout { + has_list_rows, + content_h, + create_section_h, + max_scroll, + total_h, + }) +} + +/// Compute the maximum vertical scroll offset (logical px) for an open `Select` / `Multi-select` +/// popover. Returns `0.0` when all rows fit within [`SELECT_POPOVER_MAX_HEIGHT`]. +pub fn select_popover_max_scroll(data: &DatabaseData, editor: &ActiveCellEditor) -> f32 { + compute_select_popover_layout(data, editor).map_or(0.0, |l| l.max_scroll) +} + +/// Compute screen-space `(width, height)` for the `Select` / `Multi-select` picker popover, +/// capped at [`SELECT_POPOVER_MAX_HEIGHT`]. +pub(super) fn measure_select_popover_size( + ctx: &DbRenderCtx<'_>, + editor: &ActiveCellEditor, +) -> Option<(f32, f32)> { + let layout = compute_select_popover_layout(ctx.data, editor)?; + Some((236.0, layout.total_h)) +} + +/// Render the `Select` / `Multi-select` option picker popover at `pop_rect` (screen space), +/// returning the screen-space rect of its search/create input box. +#[allow(clippy::too_many_arguments)] +pub(super) fn render_select_popover_at( + ctx: &DbRenderCtx<'_>, + editor: &ActiveCellEditor, + pop_rect: FlowRect, + prims: &mut Vec, + authoring_hits: &mut Vec, +) -> Option { + let col = ctx.data.columns.iter().find(|c| c.id == editor.column_id)?; + let options = col.select_options(); + let selected_ids: Vec = ctx + .data + .cells + .get(&(editor.row_id.clone(), editor.column_id.clone())) + .map(DatabaseCellValue::as_string_list) + .unwrap_or_default(); + + let query = editor.select_filter.trim(); + let query_lower = query.to_ascii_lowercase(); + let filtered: Vec<_> = options + .iter() + .filter(|o| query_lower.is_empty() || o.value.to_ascii_lowercase().contains(&query_lower)) + .collect(); + let exact_match = + !query.is_empty() && options.iter().any(|o| o.value.eq_ignore_ascii_case(query)); + let show_create = !query.is_empty() && !exact_match; + + let pop_w = pop_rect.w; + let pad = SELECT_POP_PAD; + let input_h = SELECT_INPUT_H; + let row_h = SELECT_ROW_H; + + prims.push(DatabasePrim::Quad { + rect: pop_rect, + fill: Some(ctx.palette.panel), + border: Some(ctx.palette.border), + radius: 8.0, + dashed: false, + }); + + let input_rect = FlowRect::new( + pop_rect.x + pad, + pop_rect.y + pad, + (pop_w - 2.0 * pad).max(1.0), + input_h, + ); + prims.push(DatabasePrim::Quad { + rect: input_rect, + fill: Some(ctx.palette.background), + border: Some(ctx.palette.brand), + radius: 4.0, + dashed: false, + }); + if editor.select_filter.is_empty() { + prims.push(ctx.single_line_clipped( + "Search or create option…", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 400.0, + ctx.palette.placeholder, + ), + input_rect.x + 8.0, + input_rect.y, + (input_rect.w - 16.0).max(1.0), + input_h, + InlineAlign::Left, + )); + } + + let layout = compute_select_popover_layout(ctx.data, editor)?; + let div_y = input_rect.bottom() + SELECT_DIV_GAP; + prims.push(DatabasePrim::Quad { + rect: FlowRect::new( + pop_rect.x + pad, + div_y, + (pop_w - 2.0 * pad).max(1.0), + SELECT_DIV_H, + ), + fill: Some(ctx.palette.border), + border: None, + radius: 0.0, + dashed: false, + }); + + let list_top = div_y + SELECT_DIV_H + SELECT_DIV_GAP; + let avail_body_h = (pop_rect.bottom() - pad - list_top).max(0.0); + let list_h = (avail_body_h - layout.create_section_h).max(0.0); + let list_bottom = list_top + list_h; + let content_h = layout.content_h; + let max_scroll = (content_h - list_h).max(0.0); + let scroll_y = ctx + .ui_state + .authoring + .select_scroll_y + .clamp(0.0, max_scroll); + let paint_scroll = snap_device_pixel(scroll_y, ctx.window.scale_factor()); + let scrollbar_gutter = if max_scroll > 0.0 { 6.0 } else { 0.0 }; + let row_w = (pop_w - 2.0 * pad - scrollbar_gutter).max(1.0); + + let mut ry = list_top - paint_scroll; + if filtered.is_empty() && !show_create { + let empty_rect = FlowRect::new(pop_rect.x + pad, list_top, row_w, row_h); + prims.push(ctx.single_line_clipped( + "No options yet", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 400.0, + ctx.palette.text_secondary, + ), + empty_rect.x + 8.0, + empty_rect.y, + (empty_rect.w - 16.0).max(1.0), + row_h, + InlineAlign::Left, + )); + } else if list_h > 0.0 { + for opt in filtered { + let row_rect = FlowRect::new(pop_rect.x + pad, ry, row_w, row_h); + ry += row_h; + if row_rect.bottom() <= list_top || row_rect.y >= list_bottom { + continue; + } + let vis_top = row_rect.y.max(list_top); + let vis_bot = row_rect.bottom().min(list_bottom); + let vis_h = (vis_bot - vis_top).max(0.0); + if vis_h < 4.0 { + continue; + } + let is_selected = selected_ids + .iter() + .any(|id| id == &opt.id || id == &opt.value); + if is_selected { + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(row_rect.x, vis_top, row_rect.w, vis_h), + fill: Some(ctx.palette.hover), + border: None, + radius: 4.0, + dashed: false, + }); + } + let (bg, ink) = resolve_tag_color(&opt.color, ctx.theme); + let pill_style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, ink); + let max_pill_w = (row_rect.w - 58.0).max(32.0); + let (_, pill_layout) = + ctx.truncate_text(&opt.value, pill_style, (max_pill_w - 12.0).max(1.0), 20.0); + let pill_w = (pill_layout.content_width().ceil() + 12.0).min(max_pill_w); + let pill_rect = FlowRect::new(row_rect.x + 6.0, row_rect.y + 4.0, pill_w, 20.0); + let pill_top = pill_rect.y.max(list_top); + let pill_bot = pill_rect.bottom().min(list_bottom); + if pill_bot > pill_top { + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(pill_rect.x, pill_top, pill_rect.w, pill_bot - pill_top), + fill: Some(bg), + border: None, + radius: 4.0, + dashed: false, + }); + prims.push(DatabasePrim::Text { + x: pill_rect.x + 6.0, + y: pill_rect.y, + layout: pill_layout, + clip: Some(FlowRect::new( + pill_rect.x + 4.0, + pill_top, + (pill_rect.w - 8.0).max(1.0), + (pill_bot - pill_top).max(1.0), + )), + }); + } + + if is_selected && row_rect.y + 7.0 >= list_top && row_rect.y + 21.0 <= list_bottom { + prims.push(DatabasePrim::Icon { + rect: FlowRect::new(row_rect.right() - 42.0, row_rect.y + 7.0, 14.0, 14.0), + icon: IconPaint::from_def(&ui_tokens::icons::CHECKBOX_CHECKED_LINEAR), + color: ctx.palette.brand, + }); + } + + let del_top = (row_rect.y + 3.0).max(list_top); + let del_bot = (row_rect.y + 25.0).min(list_bottom); + let del_h = (del_bot - del_top).max(0.0); + let del_rect = FlowRect::new(row_rect.right() - 24.0, del_top, 22.0, del_h); + if del_h > 0.0 { + let del_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_sm_px, + 500.0, + ctx.palette.text_secondary, + ); + let del_layout = std::rc::Rc::new(crate::block_flow::layout_inline( + "×", + &del_style, + del_rect.w, + 22.0, + crate::block_flow::InlineBaseline::Of(&del_style), + InlineAlign::Center, + ctx.window, + )); + prims.push(DatabasePrim::Text { + x: del_rect.x, + y: row_rect.y + 3.0, + layout: del_layout, + clip: Some(del_rect), + }); + } + + let select_hit_rect = + FlowRect::new(row_rect.x, vis_top, (row_rect.w - 26.0).max(1.0), vis_h); + authoring_hits.push(DatabaseAuthoringHit { + rect: select_hit_rect, + kind: DatabaseAuthoringHitKind::SelectToggleOption { + row_id: editor.row_id.clone(), + column_id: editor.column_id.clone(), + option_id: opt.id.clone(), + }, + scrolls_x: false, + }); + if del_h > 0.0 { + authoring_hits.push(DatabaseAuthoringHit { + rect: del_rect, + kind: DatabaseAuthoringHitKind::SelectDeleteOption { + column_id: editor.column_id.clone(), + option_id: opt.id.clone(), + }, + scrolls_x: false, + }); + } + } + } + + if show_create { + let create_w = (pop_w - 2.0 * pad).max(1.0); + if layout.has_list_rows { + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(pop_rect.x + pad, list_bottom + 2.0, create_w, 1.0), + fill: Some(ctx.palette.border), + border: None, + radius: 0.0, + dashed: false, + }); + } + let create_y = if layout.has_list_rows { + list_bottom + SELECT_CREATE_SEP_GAP + } else { + list_top + }; + let create_rect = FlowRect::new(pop_rect.x + pad, create_y, create_w, row_h); + prims.push(DatabasePrim::Quad { + rect: create_rect, + fill: Some(ctx.palette.background_secondary), + border: None, + radius: 4.0, + dashed: false, + }); + let color = next_tag_color(options.len()); + let (bg, ink) = resolve_tag_color(color, ctx.theme); + prims.push(ctx.single_line_clipped( + "Create", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 500.0, + ctx.palette.text_secondary, + ), + create_rect.x + 6.0, + create_rect.y, + 44.0, + row_h, + InlineAlign::Left, + )); + let pill_style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, ink); + let max_pw = (create_rect.w - 60.0).max(24.0); + let (_, pill_layout) = ctx.truncate_text(query, pill_style, (max_pw - 12.0).max(1.0), 20.0); + let pw = (pill_layout.content_width().ceil() + 12.0).min(max_pw); + let pill_rect = FlowRect::new(create_rect.x + 52.0, create_rect.y + 4.0, pw, 20.0); + prims.push(DatabasePrim::Quad { + rect: pill_rect, + fill: Some(bg), + border: None, + radius: 4.0, + dashed: false, + }); + prims.push(DatabasePrim::Text { + x: pill_rect.x + 6.0, + y: pill_rect.y, + layout: pill_layout, + clip: Some(FlowRect::new( + pill_rect.x + 4.0, + pill_rect.y, + (pill_rect.w - 8.0).max(1.0), + pill_rect.h, + )), + }); + authoring_hits.push(DatabaseAuthoringHit { + rect: create_rect, + kind: DatabaseAuthoringHitKind::SelectCreateOption { + row_id: editor.row_id.clone(), + column_id: editor.column_id.clone(), + label: query.to_string(), + color: color.to_string(), + }, + scrolls_x: false, + }); + } + + if max_scroll > 0.0 && list_h > 4.0 { + let thumb_w = 4.0_f32; + let thumb_h = ((list_h / content_h) * list_h).clamp(24.0_f32.min(list_h), list_h); + let travel = (list_h - thumb_h).max(0.0); + let thumb_top = list_top + + snap_device_pixel((scroll_y / max_scroll) * travel, ctx.window.scale_factor()); + prims.push(DatabasePrim::Quad { + rect: FlowRect::new( + pop_rect.right() - pad - thumb_w, + thumb_top, + thumb_w, + thumb_h, + ), + fill: Some(ctx.palette.text_secondary.opacity(0.45)), + border: None, + radius: thumb_w * 0.5, + dashed: false, + }); + } + + Some(input_rect) +} diff --git a/blocksuite/crates/editor/src/lib.rs b/blocksuite/crates/editor/src/lib.rs index 0f72d47c6d..a01eaeb284 100644 --- a/blocksuite/crates/editor/src/lib.rs +++ b/blocksuite/crates/editor/src/lib.rs @@ -14,6 +14,7 @@ pub mod highlight; pub mod inline_input; pub mod overlays; pub mod rich_text; +pub mod scroll; pub mod surface; pub mod theme; diff --git a/blocksuite/crates/editor/src/overlays/bookmark_prompt.rs b/blocksuite/crates/editor/src/overlays/bookmark_prompt.rs index 3496684c89..7ed3bc62d9 100644 --- a/blocksuite/crates/editor/src/overlays/bookmark_prompt.rs +++ b/blocksuite/crates/editor/src/overlays/bookmark_prompt.rs @@ -240,7 +240,7 @@ impl Overlays { effects.edits.push(DocEdit::SetProp { block_id, key: "prop:url", - value: Any::String(url), + value: y_octo::Any::String(url), }); } } diff --git a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs index 15dcbdf8a8..d13f897176 100644 --- a/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/bookmark_toolbar.rs @@ -360,10 +360,9 @@ impl Overlays { .occlude() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .on_scroll(emit(cx, |event: &ScrollEvent| { - let d = event.delta.pixel_delta(px(20.0)); - let dx = f32::from(d.x); - OverlayEvent::TouchContextBarScroll(if dx != 0.0 { dx } else { f32::from(d.y) }) + .on_scroll(emit(cx, move |event: &ScrollEvent| { + let (dx, dy) = crate::scroll::wheel_delta(event, rect.h); + OverlayEvent::TouchContextBarScroll(crate::scroll::dominant_axis_delta(dx, dy)) })) .p(px(pad)) .rounded(px(TOOLBAR_RADIUS)) @@ -577,7 +576,7 @@ impl Overlays { let root = place(rect) .id("bookmark-toolbar") - .occlude() + .block_mouse_except_scroll() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) .p(px(pad)) diff --git a/blocksuite/crates/editor/src/overlays/callout_bar.rs b/blocksuite/crates/editor/src/overlays/callout_bar.rs index 32b15cd04b..db715ea24a 100644 --- a/blocksuite/crates/editor/src/overlays/callout_bar.rs +++ b/blocksuite/crates/editor/src/overlays/callout_bar.rs @@ -319,10 +319,9 @@ impl Overlays { .occlude() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .on_scroll(emit(cx, |event: &ScrollEvent| { - let d = event.delta.pixel_delta(px(20.0)); - let dx = f32::from(d.x); - OverlayEvent::TouchContextBarScroll(if dx != 0.0 { dx } else { f32::from(d.y) }) + .on_scroll(emit(cx, move |event: &ScrollEvent| { + let (dx, dy) = crate::scroll::wheel_delta(event, rect.h); + OverlayEvent::TouchContextBarScroll(crate::scroll::dominant_axis_delta(dx, dy)) })) .p(px(pad)) .rounded(px(TOOLBAR_RADIUS)) @@ -420,7 +419,7 @@ impl Overlays { } let bar = place(rect) .id("callout-toolbar") - .occlude() + .block_mouse_except_scroll() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) .p(px(pad)) diff --git a/blocksuite/crates/editor/src/overlays/code_lang_picker.rs b/blocksuite/crates/editor/src/overlays/code_lang_picker.rs deleted file mode 100644 index 29200407cc..0000000000 --- a/blocksuite/crates/editor/src/overlays/code_lang_picker.rs +++ /dev/null @@ -1,632 +0,0 @@ -//! Searchable, scrollable code-block language selector (`overlay.code_lang_picker`) wired to -//! `OverlayEvent::SetCodeLanguage`, plus capitalized display names (`"Rust"`, `"TypeScript"`, ...). - -use ui::{ - AnyElement, ClickEvent, Context, FontWeight, MouseButton, MouseDownEvent, ScrollDelta, - ScrollEvent, SharedString, Window, div, prelude::*, px, -}; - -use crate::{ - block_flow::{CODE_PADDING, FlowRect}, - theme::{Palette, TYPOGRAPHY}, -}; - -use super::{ - LinkBar, OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_BORDER, - POPOVER_EDGE_MARGIN, Placement, Presence, TOOLBAR_RADIUS, emit, place, place_popover, -}; - -const VISIBLE_LANG_ROWS_DESKTOP: usize = 8; -const VISIBLE_LANG_ROWS_TOUCH: usize = 5; - -/// Canonical BlockSuite / Shiki language catalog `(wire_id, display_label)`. -pub const CODE_LANGUAGES: &[(&str, &str)] = &[ - ("", "Plain Text"), - ("rust", "Rust"), - ("typescript", "TypeScript"), - ("javascript", "JavaScript"), - ("python", "Python"), - ("go", "Go"), - ("java", "Java"), - ("c", "C"), - ("cpp", "C++"), - ("csharp", "C#"), - ("swift", "Swift"), - ("kotlin", "Kotlin"), - ("html", "HTML"), - ("css", "CSS"), - ("json", "JSON"), - ("yaml", "YAML"), - ("toml", "TOML"), - ("sql", "SQL"), - ("bash", "Bash"), - ("markdown", "Markdown"), - ("mermaid", "Mermaid"), - ("typst", "Typst"), - ("diff", "Diff"), - ("graphql", "GraphQL"), - ("docker", "Dockerfile"), -]; - -/// Format a wire `prop:language` value into its capitalized display name (`"rust"` -> `"Rust"`). -pub fn display_code_language(raw: &str) -> String { - let trimmed = raw.trim(); - if trimmed.is_empty() - || trimmed.eq_ignore_ascii_case("plain") - || trimmed.eq_ignore_ascii_case("plain text") - { - return "Plain Text".to_string(); - } - let lower = trimmed.to_ascii_lowercase(); - for &(id, label) in CODE_LANGUAGES { - if !id.is_empty() && id == lower { - return label.to_string(); - } - } - match lower.as_str() { - "ts" => "TypeScript".to_string(), - "js" => "JavaScript".to_string(), - "py" => "Python".to_string(), - "cs" => "C#".to_string(), - "yml" => "YAML".to_string(), - "sh" | "shell" => "Bash".to_string(), - "md" => "Markdown".to_string(), - "dockerfile" => "Dockerfile".to_string(), - _ => { - let mut chars = trimmed.chars(); - match chars.next() { - Some(first) => format!("{}{}", first.to_uppercase(), chars.as_str()), - None => "Plain Text".to_string(), - } - } - } -} - -/// Filter [`CODE_LANGUAGES`] by case-insensitive substring match against wire id or display label. -pub fn filter_code_languages(query: &str) -> Vec<(&'static str, &'static str)> { - let needle = query.trim().to_ascii_lowercase(); - if needle.is_empty() { - return CODE_LANGUAGES.to_vec(); - } - CODE_LANGUAGES - .iter() - .copied() - .filter(|(id, label)| { - id.contains(needle.as_str()) || label.to_ascii_lowercase().contains(needle.as_str()) - }) - .collect() -} - -/// Open state of the searchable code-block language picker. -#[derive(Clone, Debug, PartialEq)] -pub struct CodeLangPicker { - pub block_id: String, - pub input: LinkBar, - pub last_query: String, - pub selected: usize, - pub scroll_offset: usize, - pub visible_rows: usize, - pub presence: Presence, - pub rect: Option, -} - -impl CodeLangPicker { - pub fn ensure_selected_visible(&mut self, total: usize) { - let rows = self.visible_rows; - self.ensure_selected_visible_rows(total, rows); - } - - pub fn ensure_selected_visible_rows(&mut self, total: usize, visible_rows: usize) { - let rows = visible_rows.max(1); - self.visible_rows = rows; - if total == 0 { - self.selected = 0; - self.scroll_offset = 0; - return; - } - self.selected = self.selected.min(total - 1); - let max_scroll = total.saturating_sub(rows); - if self.selected < self.scroll_offset { - self.scroll_offset = self.selected; - } else if self.selected >= self.scroll_offset + rows { - self.scroll_offset = self.selected + 1 - rows; - } - self.scroll_offset = self.scroll_offset.min(max_scroll); - } -} - -impl Overlays { - /// Active (non-closing) code language picker. - pub fn code_lang_picker(&self) -> Option<&CodeLangPicker> { - self.code_lang_picker - .as_ref() - .filter(|p| !p.presence.closing) - } - - /// Mutable access to the open code language picker. - pub fn code_lang_picker_mut(&mut self) -> Option<&mut CodeLangPicker> { - self.code_lang_picker - .as_mut() - .filter(|p| !p.presence.closing) - } - - /// Open (or toggle off if already open for `block_id`) the searchable code language picker. - pub fn open_code_lang_picker(&mut self, block_id: String, current_lang: &str, now_ms: f64) { - self.open_code_lang_picker_with_rows( - block_id, - current_lang, - VISIBLE_LANG_ROWS_DESKTOP, - now_ms, - ); - } - - pub(super) fn open_code_lang_picker_with_rows( - &mut self, - block_id: String, - current_lang: &str, - visible_rows: usize, - now_ms: f64, - ) { - if self - .code_lang_picker() - .is_some_and(|p| p.block_id == block_id) - { - self.close_code_lang_picker(now_ms); - return; - } - self.close_slash(now_ms); - self.close_linked_doc(now_ms); - self.close_link_field(); - self.close_equation_editor_at(now_ms); - self.close_bookmark_prompt_at(now_ms); - let presence = match self.code_lang_picker.take() { - Some(prev) => prev.presence.reopened(now_ms), - None => Presence::opening(now_ms), - }; - let norm = match current_lang.trim().to_ascii_lowercase().as_str() { - "plain" | "plain text" => String::new(), - "dockerfile" => "docker".to_string(), - other => other.to_string(), - }; - let initial_idx = CODE_LANGUAGES - .iter() - .position(|(id, _)| *id == norm) - .unwrap_or(0); - let rows = visible_rows.max(1); - let mut picker = CodeLangPicker { - block_id, - input: LinkBar::new(String::new()), - last_query: String::new(), - selected: initial_idx, - scroll_offset: 0, - visible_rows: rows, - presence, - rect: None, - }; - picker.ensure_selected_visible_rows(CODE_LANGUAGES.len(), rows); - self.code_lang_picker = Some(picker); - } - - /// Dismiss the code language picker with a fade-out transition. - pub fn close_code_lang_picker(&mut self, now_ms: f64) -> bool { - match self.code_lang_picker_mut() { - Some(picker) => { - picker.presence.close(now_ms); - true - } - None => false, - } - } - - pub(super) fn render_code_lang_picker( - &mut self, - scene: &OverlayScene<'_>, - palette: &Palette, - now_ms: f64, - _window: &mut Window, - cx: &mut Context, - ) -> Option { - let picker = self.code_lang_picker.as_mut()?; - picker.rect = None; - let progress = picker.presence.progress(now_ms); - if picker.presence.closing && progress <= 0.0 { - return None; - } - let interactive = !picker.presence.closing; - let progress = if interactive { - progress.max(0.01) - } else { - progress - }; - let block = scene.layout.block(&picker.block_id)?; - let (_, pad_x) = CODE_PADDING; - let anchor_world = FlowRect::new(block.x + pad_x, block.y + 8.0, 120.0, 22.0); - if !scene.anchor_visible(&anchor_world) { - return None; - } - let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; - let visible_rows = if touch { - VISIBLE_LANG_ROWS_TOUCH - } else { - VISIBLE_LANG_ROWS_DESKTOP - }; - let query = picker.input.text(); - let items = filter_code_languages(&query); - let modality_changed = picker.visible_rows != visible_rows; - picker.visible_rows = visible_rows; - if query != picker.last_query { - picker.last_query = query.clone(); - picker.selected = 0; - picker.scroll_offset = 0; - } else if items.is_empty() { - picker.selected = 0; - picker.scroll_offset = 0; - } else if modality_changed { - picker.ensure_selected_visible_rows(items.len(), visible_rows); - } else { - picker.selected = picker.selected.min(items.len() - 1); - picker.scroll_offset = picker - .scroll_offset - .min(items.len().saturating_sub(visible_rows.max(1))); - } - let max_rows = items.len().clamp(1, visible_rows); - let row_h = if touch { 44.0_f32 } else { 26.0_f32 }; - let search_h = if touch { 40.0_f32 } else { 28.0_f32 }; - let pad = 6.0_f32; - let width = if touch { 220.0_f32 } else { 196.0_f32 }; - let height = - (2.0 * (pad + POPOVER_BORDER) + search_h + 6.0 + max_rows as f32 * row_h).round(); - let anchor = scene.world_to_screen(&anchor_world); - let mut viewport = scene.popover_viewport(); - if touch { - viewport.h = (viewport.h - 60.0).max(height + 2.0 * POPOVER_EDGE_MARGIN); - } - let placed = place_popover( - anchor, - (width, height), - viewport, - Placement::BelowStart, - 4.0, - POPOVER_EDGE_MARGIN, - ); - picker.rect = Some(placed.rect); - - let block_id = picker.block_id.clone(); - let selected_idx = picker.selected; - let scroll_off = picker.scroll_offset; - let hover_bg = palette.hover; - let current_lang = scene - .snapshot - .block(&block_id) - .and_then(|n| match &n.content { - blocksuite_playground_doc::read::BlockContent::Code { language, .. } => { - let l = language.trim().to_ascii_lowercase(); - Some(if l == "dockerfile" { - "docker".to_string() - } else if l == "plain" || l == "plain text" { - String::new() - } else { - l - }) - } - _ => None, - }) - .unwrap_or_default(); - - let search_box = div() - .flex_none() - .w_full() - .h(px(search_h)) - .px(px(8.0)) - .rounded(px(4.0)) - .bg(palette.background) - .border_1() - .border_color(palette.brand) - .flex() - .items_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .text_color(if query.is_empty() { - palette.placeholder - } else { - palette.text_primary - }) - .snapshot( - "overlay.code_lang_picker.search", - Some("overlay.code_lang_picker"), - ) - .snapshot_focused(true) - .snapshot_text(query.clone()) - .child(if query.is_empty() { - "Search language...".to_string() - } else { - query - }); - - let mut list = div().flex().flex_col().overflow_hidden(); - for (idx, &(wire_id, label)) in items.iter().enumerate().skip(scroll_off).take(visible_rows) - { - let is_current = current_lang == wire_id; - let is_sel = idx == selected_idx; - let bid = block_id.clone(); - let lang = wire_id.to_string(); - let mut row = div() - .id(SharedString::from(format!("code-lang-row-{idx}"))) - .flex_none() - .w_full() - .h(px(row_h)) - .px(px(8.0)) - .rounded(px(4.0)) - .flex() - .items_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .font_weight(if is_current { - FontWeight::SEMIBOLD - } else { - FontWeight::NORMAL - }) - .text_color(if is_current { - palette.brand - } else { - palette.text_primary - }) - .when(is_sel, |el| el.bg(hover_bg)) - .snapshot( - SharedString::from(format!( - "overlay.code_lang_picker.item.{}", - if wire_id.is_empty() { "plain" } else { wire_id } - )), - Some("overlay.code_lang_picker"), - ) - .snapshot_focused(is_current) - .snapshot_text(label) - .child(label); - if interactive { - row = row - .cursor_pointer() - .hover(move |s| s.bg(hover_bg)) - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(emit(cx, move |_: &ClickEvent| { - OverlayEvent::SetCodeLanguage { - block_id: bid.clone(), - language: lang.clone(), - } - })); - } - list = list.child(row); - } - if items.is_empty() { - list = list.child( - div() - .h(px(row_h)) - .px(px(8.0)) - .flex() - .items_center() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .text_color(palette.text_secondary) - .child("No matching language"), - ); - } - - let mut root = place(placed.rect) - .id("code-lang-picker") - .flex() - .flex_col() - .gap(px(6.0)) - .p(px(pad)) - .rounded(px(TOOLBAR_RADIUS)) - .bg(palette.panel) - .border_1() - .border_color(palette.border) - .shadow( - palette - .theme - .shadows("--affine-overlay-panel-shadow") - .into(), - ) - .opacity(progress) - .snapshot("overlay.code_lang_picker", Some("root.canvas")) - .snapshot_focused(interactive) - .child(search_box) - .child(list); - if interactive { - root = root - .occlude() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_scroll(cx.listener(move |view: &mut V, ev: &ScrollEvent, w, cx| { - cx.stop_propagation(); - let dy = match ev.delta { - ScrollDelta::Pixels(p) => f32::from(p.y), - ScrollDelta::Lines(l) => l.y * row_h, - }; - if dy.abs() > 0.1 { - let scaled = (-dy / row_h).round() as isize; - let rows = if scaled != 0 { - scaled.clamp(-12, 12) - } else if dy < 0.0 { - 1 - } else { - -1 - }; - view.dispatch_overlay(OverlayEvent::CodeLangPickerScroll(rows), w, cx); - } - })) - .on_mouse_down_out(emit(cx, |_: &MouseDownEvent| { - OverlayEvent::CloseCodeLangPicker - })); - } - Some(root.into_any_element()) - } - - pub(super) fn handle_code_and_media_event( - &mut self, - event: &OverlayEvent, - scene: Option<&OverlayScene<'_>>, - now_ms: f64, - effects: &mut super::OverlayEffects, - ) { - match event { - OverlayEvent::SetCodeLanguage { block_id, language } => { - self.close_code_lang_picker(now_ms); - effects.edits.push(super::DocEdit::SetProp { - block_id: block_id.clone(), - key: "prop:language", - value: super::helpers::normalize_code_language(language), - }); - effects.redraw = true; - } - OverlayEvent::TouchContextBarScroll(delta_x) => { - if delta_x.abs() > 0.1 { - self.touch_bar_scroll_x = (self.touch_bar_scroll_x - delta_x).max(0.0); - effects.redraw = true; - } - } - OverlayEvent::OpenCodeLangPicker(block_id) => { - let current_lang = scene - .and_then(|s| s.snapshot.block(block_id)) - .and_then(|n| match &n.content { - blocksuite_playground_doc::read::BlockContent::Code { - language, .. - } => Some(language.as_str()), - _ => None, - }) - .unwrap_or(""); - let visible_rows = if scene.is_some_and(|s| { - s.is_touch || s.form_factor != crate::block_flow::FormFactor::Desktop - }) { - VISIBLE_LANG_ROWS_TOUCH - } else { - VISIBLE_LANG_ROWS_DESKTOP - }; - self.open_code_lang_picker_with_rows( - block_id.clone(), - current_lang, - visible_rows, - now_ms, - ); - effects.redraw = true; - } - OverlayEvent::CodeLangPickerScroll(delta_rows) => { - let visible_rows = if scene.is_some_and(|s| { - s.is_touch || s.form_factor != crate::block_flow::FormFactor::Desktop - }) { - VISIBLE_LANG_ROWS_TOUCH - } else { - VISIBLE_LANG_ROWS_DESKTOP - }; - if let Some(picker) = self.code_lang_picker_mut() { - picker.visible_rows = visible_rows; - let total = filter_code_languages(&picker.input.text()).len(); - let max_scroll = total.saturating_sub(visible_rows); - picker.scroll_offset = picker - .scroll_offset - .saturating_add_signed(*delta_rows) - .min(max_scroll); - effects.redraw = true; - } - } - OverlayEvent::CloseCodeLangPicker => { - effects.redraw = self.close_code_lang_picker(now_ms); - } - OverlayEvent::ToggleCodeLineNumber(block_id) => { - let current = scene - .and_then(|s| s.snapshot.block(block_id)) - .and_then(|n| n.props.get("prop:lineNumber").and_then(|v| v.as_bool())) - .unwrap_or( - scene.is_none_or(|s| s.form_factor != crate::block_flow::FormFactor::Phone), - ); - effects.edits.push(super::DocEdit::SetProp { - block_id: block_id.clone(), - key: "prop:lineNumber", - value: if current { - y_octo::Any::False - } else { - y_octo::Any::True - }, - }); - effects.redraw = true; - } - OverlayEvent::ToggleCodeCollapsed(block_id) => { - let current = scene - .and_then(|s| s.snapshot.block(block_id)) - .and_then(|n| n.props.get("prop:collapsed").and_then(|v| v.as_bool())) - .unwrap_or(false); - effects.edits.push(super::DocEdit::SetProp { - block_id: block_id.clone(), - key: "prop:collapsed", - value: if current { - y_octo::Any::False - } else { - y_octo::Any::True - }, - }); - effects.redraw = true; - } - ev if self.handle_image_lightbox_event(ev, now_ms, effects) => {} - OverlayEvent::CalloutAction { block_id, action } => { - self.handle_callout_action(block_id, action, effects); - } - OverlayEvent::CloseCalloutIconPicker => { - effects.redraw = self.close_callout_icon_picker(); - } - _ => {} - } - } - - pub(super) fn handle_code_lang_picker_key( - &mut self, - key: &str, - now_ms: f64, - effects: &mut super::OverlayEffects, - ) -> bool { - let Some(picker) = self.code_lang_picker_mut() else { - return false; - }; - let items = filter_code_languages(&picker.input.text()); - match key { - "up" | "down" => { - let len = items.len(); - if len > 0 { - let cur = picker.selected.min(len - 1); - picker.selected = if key == "down" { - (cur + 1) % len - } else { - (cur + len - 1) % len - }; - picker.ensure_selected_visible(len); - effects.redraw = true; - } - effects.handled = true; - true - } - "enter" => { - if let Some(&(wire_id, _)) = - items.get(picker.selected.min(items.len().saturating_sub(1))) - { - let block_id = picker.block_id.clone(); - self.close_code_lang_picker(now_ms); - effects.edits.push(super::DocEdit::SetProp { - block_id, - key: "prop:language", - value: super::helpers::normalize_code_language(wire_id), - }); - } else { - self.close_code_lang_picker(now_ms); - } - effects.handled = true; - effects.redraw = true; - true - } - "escape" => { - if picker.input.composing() { - picker.input.cancel_preedit(); - } else { - self.close_code_lang_picker(now_ms); - } - effects.handled = true; - effects.redraw = true; - true - } - _ => false, - } - } -} diff --git a/blocksuite/crates/editor/src/overlays/code_lang_picker/catalog.rs b/blocksuite/crates/editor/src/overlays/code_lang_picker/catalog.rs new file mode 100644 index 0000000000..dc034b0d0a --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/code_lang_picker/catalog.rs @@ -0,0 +1,586 @@ +//! Shiki-compatible code-block language catalog, alias normalization, and prefix/alias +//! ranking matching BlockSuite `affine-filterable-list`. + +/// One code-block language entry with its wire id, display label, and short search aliases. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CodeLanguageSpec { + pub id: &'static str, + pub label: &'static str, + pub aliases: &'static [&'static str], +} + +/// Core 25-entry `(wire_id, display_label)` slice kept for callers inspecting the compact list. +pub const CODE_LANGUAGES: &[(&str, &str)] = &[ + ("", "Plain Text"), + ("rust", "Rust"), + ("typescript", "TypeScript"), + ("javascript", "JavaScript"), + ("python", "Python"), + ("go", "Go"), + ("java", "Java"), + ("c", "C"), + ("cpp", "C++"), + ("csharp", "C#"), + ("swift", "Swift"), + ("kotlin", "Kotlin"), + ("html", "HTML"), + ("css", "CSS"), + ("json", "JSON"), + ("yaml", "YAML"), + ("toml", "TOML"), + ("sql", "SQL"), + ("bash", "Bash"), + ("markdown", "Markdown"), + ("mermaid", "Mermaid"), + ("typst", "Typst"), + ("diff", "Diff"), + ("graphql", "GraphQL"), + ("docker", "Dockerfile"), +]; + +/// Full Shiki-aligned language catalog with prefix-searchable aliases. +pub const CODE_LANGUAGE_CATALOG: &[CodeLanguageSpec] = &[ + CodeLanguageSpec { + id: "", + label: "Plain Text", + aliases: &["plain", "plaintext", "txt", "text"], + }, + CodeLanguageSpec { + id: "typescript", + label: "TypeScript", + aliases: &["ts", "mts", "cts"], + }, + CodeLanguageSpec { + id: "javascript", + label: "JavaScript", + aliases: &["js", "mjs", "cjs"], + }, + CodeLanguageSpec { + id: "tsx", + label: "TSX", + aliases: &["typescriptreact"], + }, + CodeLanguageSpec { + id: "jsx", + label: "JSX", + aliases: &["javascriptreact"], + }, + CodeLanguageSpec { + id: "python", + label: "Python", + aliases: &["py", "py3"], + }, + CodeLanguageSpec { + id: "rust", + label: "Rust", + aliases: &["rs"], + }, + CodeLanguageSpec { + id: "go", + label: "Go", + aliases: &["golang"], + }, + CodeLanguageSpec { + id: "java", + label: "Java", + aliases: &[], + }, + CodeLanguageSpec { + id: "c", + label: "C", + aliases: &["h"], + }, + CodeLanguageSpec { + id: "cpp", + label: "C++", + aliases: &["c++", "cc", "cxx", "hpp"], + }, + CodeLanguageSpec { + id: "csharp", + label: "C#", + aliases: &["cs", "c#"], + }, + CodeLanguageSpec { + id: "swift", + label: "Swift", + aliases: &[], + }, + CodeLanguageSpec { + id: "kotlin", + label: "Kotlin", + aliases: &["kt", "kts"], + }, + CodeLanguageSpec { + id: "html", + label: "HTML", + aliases: &["htm"], + }, + CodeLanguageSpec { + id: "css", + label: "CSS", + aliases: &[], + }, + CodeLanguageSpec { + id: "scss", + label: "SCSS", + aliases: &[], + }, + CodeLanguageSpec { + id: "sass", + label: "Sass", + aliases: &[], + }, + CodeLanguageSpec { + id: "less", + label: "Less", + aliases: &[], + }, + CodeLanguageSpec { + id: "json", + label: "JSON", + aliases: &["jsonc", "json5"], + }, + CodeLanguageSpec { + id: "yaml", + label: "YAML", + aliases: &["yml"], + }, + CodeLanguageSpec { + id: "toml", + label: "TOML", + aliases: &[], + }, + CodeLanguageSpec { + id: "xml", + label: "XML", + aliases: &["svg"], + }, + CodeLanguageSpec { + id: "sql", + label: "SQL", + aliases: &["mysql", "postgres", "sqlite"], + }, + CodeLanguageSpec { + id: "bash", + label: "Bash", + aliases: &["sh", "shell", "zsh", "shellscript"], + }, + CodeLanguageSpec { + id: "powershell", + label: "PowerShell", + aliases: &["ps", "ps1", "pwsh"], + }, + CodeLanguageSpec { + id: "markdown", + label: "Markdown", + aliases: &["md"], + }, + CodeLanguageSpec { + id: "mdx", + label: "MDX", + aliases: &[], + }, + CodeLanguageSpec { + id: "mermaid", + label: "Mermaid", + aliases: &["mmd"], + }, + CodeLanguageSpec { + id: "typst", + label: "Typst", + aliases: &["typ"], + }, + CodeLanguageSpec { + id: "latex", + label: "LaTeX", + aliases: &["tex"], + }, + CodeLanguageSpec { + id: "diff", + label: "Diff", + aliases: &["patch"], + }, + CodeLanguageSpec { + id: "graphql", + label: "GraphQL", + aliases: &["gql"], + }, + CodeLanguageSpec { + id: "docker", + label: "Dockerfile", + aliases: &["dockerfile"], + }, + CodeLanguageSpec { + id: "makefile", + label: "Makefile", + aliases: &["make", "mk"], + }, + CodeLanguageSpec { + id: "cmake", + label: "CMake", + aliases: &[], + }, + CodeLanguageSpec { + id: "ruby", + label: "Ruby", + aliases: &["rb"], + }, + CodeLanguageSpec { + id: "php", + label: "PHP", + aliases: &[], + }, + CodeLanguageSpec { + id: "dart", + label: "Dart", + aliases: &[], + }, + CodeLanguageSpec { + id: "elixir", + label: "Elixir", + aliases: &["ex", "exs"], + }, + CodeLanguageSpec { + id: "erlang", + label: "Erlang", + aliases: &["erl"], + }, + CodeLanguageSpec { + id: "haskell", + label: "Haskell", + aliases: &["hs"], + }, + CodeLanguageSpec { + id: "scala", + label: "Scala", + aliases: &[], + }, + CodeLanguageSpec { + id: "clojure", + label: "Clojure", + aliases: &["clj", "cljs"], + }, + CodeLanguageSpec { + id: "lua", + label: "Lua", + aliases: &[], + }, + CodeLanguageSpec { + id: "perl", + label: "Perl", + aliases: &["pl"], + }, + CodeLanguageSpec { + id: "r", + label: "R", + aliases: &[], + }, + CodeLanguageSpec { + id: "julia", + label: "Julia", + aliases: &["jl"], + }, + CodeLanguageSpec { + id: "zig", + label: "Zig", + aliases: &[], + }, + CodeLanguageSpec { + id: "nix", + label: "Nix", + aliases: &[], + }, + CodeLanguageSpec { + id: "solidity", + label: "Solidity", + aliases: &["sol"], + }, + CodeLanguageSpec { + id: "proto", + label: "Protocol Buffers", + aliases: &["protobuf"], + }, + CodeLanguageSpec { + id: "prisma", + label: "Prisma", + aliases: &[], + }, + CodeLanguageSpec { + id: "terraform", + label: "Terraform", + aliases: &["tf", "hcl"], + }, + CodeLanguageSpec { + id: "nginx", + label: "Nginx", + aliases: &[], + }, + CodeLanguageSpec { + id: "ini", + label: "INI", + aliases: &["properties", "cfg"], + }, + CodeLanguageSpec { + id: "csv", + label: "CSV", + aliases: &[], + }, + CodeLanguageSpec { + id: "vue", + label: "Vue", + aliases: &[], + }, + CodeLanguageSpec { + id: "svelte", + label: "Svelte", + aliases: &[], + }, + CodeLanguageSpec { + id: "astro", + label: "Astro", + aliases: &[], + }, + CodeLanguageSpec { + id: "wgsl", + label: "WGSL", + aliases: &[], + }, + CodeLanguageSpec { + id: "glsl", + label: "GLSL", + aliases: &[], + }, + CodeLanguageSpec { + id: "objc", + label: "Objective-C", + aliases: &["objective-c"], + }, + CodeLanguageSpec { + id: "objcpp", + label: "Objective-C++", + aliases: &["objective-cpp"], + }, + CodeLanguageSpec { + id: "asm", + label: "Assembly", + aliases: &["nasm"], + }, + CodeLanguageSpec { + id: "wasm", + label: "WebAssembly", + aliases: &["wat"], + }, + CodeLanguageSpec { + id: "groovy", + label: "Groovy", + aliases: &[], + }, + CodeLanguageSpec { + id: "fsharp", + label: "F#", + aliases: &["fs", "f#"], + }, + CodeLanguageSpec { + id: "ocaml", + label: "OCaml", + aliases: &["ml"], + }, + CodeLanguageSpec { + id: "scheme", + label: "Scheme", + aliases: &["scm"], + }, + CodeLanguageSpec { + id: "lisp", + label: "Common Lisp", + aliases: &["cl"], + }, + CodeLanguageSpec { + id: "fortran", + label: "Fortran", + aliases: &["f90"], + }, + CodeLanguageSpec { + id: "pascal", + label: "Pascal", + aliases: &["pas"], + }, + CodeLanguageSpec { + id: "verilog", + label: "Verilog", + aliases: &["sv", "systemverilog"], + }, + CodeLanguageSpec { + id: "vhdl", + label: "VHDL", + aliases: &[], + }, + CodeLanguageSpec { + id: "bat", + label: "Batch", + aliases: &["batch", "cmd"], + }, + CodeLanguageSpec { + id: "fish", + label: "Fish", + aliases: &[], + }, + CodeLanguageSpec { + id: "viml", + label: "VimL", + aliases: &["vim", "vimscript"], + }, + CodeLanguageSpec { + id: "http", + label: "HTTP", + aliases: &[], + }, + CodeLanguageSpec { + id: "regex", + label: "RegExp", + aliases: &["regexp"], + }, + CodeLanguageSpec { + id: "log", + label: "Log", + aliases: &[], + }, +]; + +/// Normalize a raw `prop:language` string or alias to its canonical catalog wire id +/// (`"ts"` -> `"typescript"`, `"plain text"` -> `""`, `"dockerfile"` -> `"docker"`). +pub fn canonical_code_language(raw: &str) -> String { + let trimmed = raw.trim(); + if trimmed.is_empty() + || trimmed.eq_ignore_ascii_case("plain") + || trimmed.eq_ignore_ascii_case("plain text") + || trimmed.eq_ignore_ascii_case("plaintext") + { + return String::new(); + } + let lower = trimmed.to_ascii_lowercase(); + for spec in CODE_LANGUAGE_CATALOG { + if !spec.id.is_empty() && spec.id == lower { + return spec.id.to_string(); + } + if spec.aliases.contains(&lower.as_str()) { + return spec.id.to_string(); + } + if spec.label.eq_ignore_ascii_case(&lower) { + return spec.id.to_string(); + } + } + lower +} + +/// Format a wire `prop:language` value into its capitalized display name (`"rust"` -> `"Rust"`). +pub fn display_code_language(raw: &str) -> String { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return "Plain Text".to_string(); + } + let canon = canonical_code_language(trimmed); + for spec in CODE_LANGUAGE_CATALOG { + if spec.id == canon { + return spec.label.to_string(); + } + } + let mut chars = trimmed.chars(); + match chars.next() { + Some(first) => format!("{}{}", first.to_uppercase(), chars.as_str()), + None => "Plain Text".to_string(), + } +} + +/// Filter [`CODE_LANGUAGE_CATALOG`] by prefix match on id/aliases (rank 0) then display label +/// (rank 1), matching JS `affine-filterable-list`. +pub fn filter_code_languages(query: &str) -> Vec<(&'static str, &'static str)> { + filter_code_languages_ordered(query, "", &[]) +} + +/// Filter and rank [`CODE_LANGUAGE_CATALOG`] with active-language pinning and MRU recent history. +/// +/// - When `query` is empty: the active `current_lang` is sorted first, followed by `recent_langs` +/// in most-recently-used order, then the remaining catalog entries. +/// - When `query` is non-empty: prefix matches on `id` or `aliases` rank ahead of prefix matches +/// on `label`, with active/recent order breaking ties. Returns an empty list on zero matches. +pub fn filter_code_languages_ordered( + query: &str, + current_lang: &str, + recent_langs: &[String], +) -> Vec<(&'static str, &'static str)> { + let needle = query.trim().to_ascii_lowercase(); + let active = canonical_code_language(current_lang); + + let priority_bucket = |id: &str| -> (u8, usize) { + if id == active { + (0, 0) + } else if let Some(pos) = recent_langs.iter().position(|r| r == id) { + (1, pos) + } else { + (2, 0) + } + }; + + let mut ranked: Vec<(u8, u8, usize, usize, &'static str, &'static str)> = Vec::new(); + for (idx, spec) in CODE_LANGUAGE_CATALOG.iter().enumerate() { + let match_rank = if needle.is_empty() { + 0 + } else if (!spec.id.is_empty() && spec.id.starts_with(needle.as_str())) + || spec + .aliases + .iter() + .any(|alias| alias.starts_with(needle.as_str())) + { + 0 + } else if spec.label.to_ascii_lowercase().starts_with(needle.as_str()) { + 1 + } else { + continue; + }; + let (bucket, recent_pos) = priority_bucket(spec.id); + ranked.push((match_rank, bucket, recent_pos, idx, spec.id, spec.label)); + } + ranked.sort_by_key(|&(mr, bucket, rpos, idx, _, _)| (mr, bucket, rpos, idx)); + ranked + .into_iter() + .map(|(_, _, _, _, id, label)| (id, label)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prefix_and_alias_search_matches_expected_languages() { + let cases = [ + ("ts", "typescript", "TypeScript"), + ("js", "javascript", "JavaScript"), + ("py", "python", "Python"), + ("rs", "rust", "Rust"), + ("md", "markdown", "Markdown"), + ("sh", "bash", "Bash"), + ("yml", "yaml", "YAML"), + ("gql", "graphql", "GraphQL"), + ]; + for (query, expected_id, expected_label) in cases { + let results = filter_code_languages(query); + assert!( + results.first() == Some(&(expected_id, expected_label)), + "query {query:?} must rank ({expected_id:?}, {expected_label:?}) first, got {:?}", + results.first() + ); + } + assert!(filter_code_languages("zzzz_no_lang").is_empty()); + } + + #[test] + fn active_language_pins_first_and_recent_languages_follow() { + let recent = vec!["python".to_string(), "go".to_string()]; + let ordered = filter_code_languages_ordered("", "rust", &recent); + assert_eq!(ordered[0], ("rust", "Rust")); + assert_eq!(ordered[1], ("python", "Python")); + assert_eq!(ordered[2], ("go", "Go")); + } +} diff --git a/blocksuite/crates/editor/src/overlays/code_lang_picker/mod.rs b/blocksuite/crates/editor/src/overlays/code_lang_picker/mod.rs new file mode 100644 index 0000000000..23cc3b15ba --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/code_lang_picker/mod.rs @@ -0,0 +1,428 @@ +//! Searchable, pixel-scrollable code-block language selector (`overlay.code_lang_picker`) +//! aligned 1:1 with BlockSuite's `affine-filterable-list`. + +mod catalog; +mod render; + +pub use catalog::{ + CODE_LANGUAGE_CATALOG, CODE_LANGUAGES, CodeLanguageSpec, canonical_code_language, + display_code_language, filter_code_languages, filter_code_languages_ordered, +}; + +use crate::{block_flow::FlowRect, scroll::ScrollAxis}; + +use super::{ + LinkBar, OverlayEvent, OverlayHost, OverlayScene, Overlays, POPOVER_EDGE_MARGIN, Placement, + Presence, SingleLineInputSpec, TOOLBAR_RADIUS, emit, paint_single_line_input_inner_sized, + place, place_popover, +}; + +pub(super) const PICKER_WIDTH: f32 = 230.0; +pub(super) const PICKER_PADDING: f32 = 8.0; +pub(super) const PICKER_MAX_HEIGHT: f32 = 440.0; +pub(super) const PICKER_EDGE_PAD: f32 = 12.0; +pub(super) const PICKER_ANCHOR_OFFSET: f32 = 4.0; +pub(super) const PICKER_FONT_PX: f32 = 14.0; +pub(super) const PICKER_ROW_HEIGHT_DESKTOP: f32 = 32.0; +pub(super) const PICKER_ROW_HEIGHT_TOUCH: f32 = 44.0; +pub(super) const PICKER_SEARCH_HEIGHT_DESKTOP: f32 = 32.0; +pub(super) const PICKER_SEARCH_HEIGHT_TOUCH: f32 = 40.0; +pub(super) const PICKER_SEP_MARGIN: f32 = 8.0; +pub(super) const PICKER_SEP_HEIGHT: f32 = 1.0; +pub(super) const PICKER_SCROLLBAR_WIDTH: f32 = 4.0; +pub(super) const PICKER_SCROLLBAR_GUTTER: f32 = 6.0; +pub(super) const PICKER_MIN_THUMB: f32 = 24.0; +const MAX_RECENT_LANGUAGES: usize = 16; + +/// Open state of the searchable code-block language picker. +#[derive(Clone, Debug, PartialEq)] +pub struct CodeLangPicker { + pub block_id: String, + pub current_lang: String, + pub input: LinkBar, + pub last_query: String, + pub selected: usize, + /// Subpixel vertical scroll offset in logical pixels (never rounded in state). + pub scroll_offset: f32, + /// Latest measured maximum scroll offset in logical pixels. + pub max_scroll: f32, + /// Latest measured list viewport height in logical pixels. + pub list_height: f32, + /// Active row height in logical pixels (`32.0` desktop, `44.0` touch). + pub row_height: f32, + pub presence: Presence, + pub rect: Option, +} + +impl CodeLangPicker { + /// Keep `selected` inside the visible pixel viewport after keyboard navigation. + pub fn ensure_selected_visible(&mut self, total: usize) { + if total == 0 { + self.selected = 0; + self.scroll_offset = 0.0; + self.max_scroll = 0.0; + return; + } + self.selected = self.selected.min(total - 1); + let row_h = self.row_height.max(1.0); + let content_h = total as f32 * row_h; + let list_h = self.list_height.max(row_h); + self.max_scroll = (content_h - list_h).max(0.0); + let row_top = self.selected as f32 * row_h; + let row_bottom = row_top + row_h; + if row_top < self.scroll_offset { + self.scroll_offset = row_top; + } else if row_bottom > self.scroll_offset + list_h { + self.scroll_offset = row_bottom - list_h; + } + self.scroll_offset = self.scroll_offset.clamp(0.0, self.max_scroll); + } + + /// Apply a subpixel scroll delta in logical pixels via [`ScrollAxis`]. + pub fn scroll_by_px(&mut self, delta_y: f32) -> bool { + let mut axis = ScrollAxis::new(self.scroll_offset, self.max_scroll); + if axis.apply(delta_y) { + self.scroll_offset = axis.offset; + true + } else { + false + } + } +} + +impl Overlays { + /// Active (non-closing) code language picker. + pub fn code_lang_picker(&self) -> Option<&CodeLangPicker> { + self.code_lang_picker + .as_ref() + .filter(|p| !p.presence.closing) + } + + /// Mutable access to the open code language picker. + pub fn code_lang_picker_mut(&mut self) -> Option<&mut CodeLangPicker> { + self.code_lang_picker + .as_mut() + .filter(|p| !p.presence.closing) + } + + fn record_recent_code_language(&mut self, raw_lang: &str) { + let canon = canonical_code_language(raw_lang); + self.recent_code_languages.retain(|id| id != &canon); + self.recent_code_languages.insert(0, canon); + self.recent_code_languages.truncate(MAX_RECENT_LANGUAGES); + } + + /// Open (or toggle off if already open for `block_id`) the searchable code language picker. + pub fn open_code_lang_picker(&mut self, block_id: String, current_lang: &str, now_ms: f64) { + self.open_code_lang_picker_internal(block_id, current_lang, false, now_ms); + } + + pub(super) fn open_code_lang_picker_internal( + &mut self, + block_id: String, + current_lang: &str, + touch: bool, + now_ms: f64, + ) { + if self + .code_lang_picker() + .is_some_and(|p| p.block_id == block_id) + { + self.close_code_lang_picker(now_ms); + return; + } + self.close_slash(now_ms); + self.close_linked_doc(now_ms); + self.close_link_field(); + self.close_equation_editor_at(now_ms); + self.close_bookmark_prompt_at(now_ms); + let presence = match self.code_lang_picker.take() { + Some(prev) => prev.presence.reopened(now_ms), + None => Presence::opening(now_ms), + }; + let norm = canonical_code_language(current_lang); + let row_h = if touch { + PICKER_ROW_HEIGHT_TOUCH + } else { + PICKER_ROW_HEIGHT_DESKTOP + }; + let items = filter_code_languages_ordered("", &norm, &self.recent_code_languages); + let initial_idx = items.iter().position(|(id, _)| *id == norm).unwrap_or(0); + let default_list_h = if touch { 5.0 * row_h } else { 10.0 * row_h }; + let mut picker = CodeLangPicker { + block_id, + current_lang: norm, + input: LinkBar::new(String::new()), + last_query: String::new(), + selected: initial_idx, + scroll_offset: 0.0, + max_scroll: (items.len() as f32 * row_h - default_list_h).max(0.0), + list_height: default_list_h, + row_height: row_h, + presence, + rect: None, + }; + picker.ensure_selected_visible(items.len()); + self.code_lang_picker = Some(picker); + } + + /// Dismiss the code language picker with a fade-out transition. + pub fn close_code_lang_picker(&mut self, now_ms: f64) -> bool { + match self.code_lang_picker_mut() { + Some(picker) => { + picker.presence.close(now_ms); + true + } + None => false, + } + } + + pub(super) fn handle_code_and_media_event( + &mut self, + event: &OverlayEvent, + scene: Option<&OverlayScene<'_>>, + now_ms: f64, + effects: &mut super::OverlayEffects, + ) { + match event { + OverlayEvent::SetCodeLanguage { block_id, language } => { + self.record_recent_code_language(language); + self.close_code_lang_picker(now_ms); + effects.edits.push(super::DocEdit::SetProp { + block_id: block_id.clone(), + key: "prop:language", + value: super::helpers::normalize_code_language(language), + }); + effects.redraw = true; + } + OverlayEvent::TouchContextBarScroll(delta_x) => { + if *delta_x != 0.0 { + self.touch_bar_scroll_x = (self.touch_bar_scroll_x - delta_x).max(0.0); + effects.redraw = true; + } + } + OverlayEvent::OpenCodeLangPicker(block_id) => { + let current_lang = scene + .and_then(|s| s.snapshot.block(block_id)) + .and_then(|n| match &n.content { + blocksuite_playground_doc::read::BlockContent::Code { + language, .. + } => Some(language.as_str()), + _ => None, + }) + .unwrap_or(""); + let touch = scene.is_some_and(|s| { + s.is_touch || s.form_factor != crate::block_flow::FormFactor::Desktop + }); + self.open_code_lang_picker_internal(block_id.clone(), current_lang, touch, now_ms); + effects.redraw = true; + } + OverlayEvent::CodeLangPickerScroll(delta_y) => { + if let Some(picker) = self.code_lang_picker_mut() + && picker.scroll_by_px(*delta_y) + { + effects.redraw = true; + } + } + OverlayEvent::CodeLangPickerHover(idx) => { + if let Some(picker) = self.code_lang_picker_mut() + && picker.selected != *idx + { + picker.selected = *idx; + effects.redraw = true; + } + } + OverlayEvent::SetBlockScrollX { block_id, scroll_x } => { + self.set_code_scroll_x(block_id, *scroll_x); + effects.redraw = true; + } + OverlayEvent::StartBlockHScrollDrag { + block_id, + pointer_x, + scroll_x, + track_travel, + max_scroll_x, + } => { + self.start_hscroll_drag(super::scrollbar::BlockHScrollDrag { + block_id: block_id.clone(), + start_pointer_x: *pointer_x, + start_scroll_x: *scroll_x, + track_travel: *track_travel, + max_scroll_x: *max_scroll_x, + }); + effects.redraw = true; + } + OverlayEvent::CloseCodeLangPicker => { + effects.redraw = self.close_code_lang_picker(now_ms); + } + OverlayEvent::ToggleCodeLineNumber(block_id) => { + let current = scene + .and_then(|s| s.snapshot.block(block_id)) + .and_then(|n| n.props.get("prop:lineNumber").and_then(|v| v.as_bool())) + .unwrap_or( + scene.is_none_or(|s| s.form_factor != crate::block_flow::FormFactor::Phone), + ); + effects.edits.push(super::DocEdit::SetProp { + block_id: block_id.clone(), + key: "prop:lineNumber", + value: if current { + y_octo::Any::False + } else { + y_octo::Any::True + }, + }); + effects.redraw = true; + } + OverlayEvent::ToggleCodeCollapsed(block_id) => { + let current = scene + .and_then(|s| s.snapshot.block(block_id)) + .and_then(|n| n.props.get("prop:collapsed").and_then(|v| v.as_bool())) + .unwrap_or(false); + effects.edits.push(super::DocEdit::SetProp { + block_id: block_id.clone(), + key: "prop:collapsed", + value: if current { + y_octo::Any::False + } else { + y_octo::Any::True + }, + }); + effects.redraw = true; + } + ev if self.handle_image_lightbox_event(ev, now_ms, effects) => {} + OverlayEvent::CalloutAction { block_id, action } => { + self.handle_callout_action(block_id, action, effects); + } + OverlayEvent::CloseCalloutIconPicker => { + effects.redraw = self.close_callout_icon_picker(); + } + _ => {} + } + } + + pub(super) fn handle_code_lang_picker_key( + &mut self, + key: &str, + now_ms: f64, + effects: &mut super::OverlayEffects, + ) -> bool { + let recent = self.recent_code_languages.clone(); + let Some(picker) = self.code_lang_picker_mut() else { + return false; + }; + let items = + filter_code_languages_ordered(&picker.input.text(), &picker.current_lang, &recent); + match key { + "up" | "down" => { + let len = items.len(); + if len > 0 { + let cur = picker.selected.min(len - 1); + picker.selected = if key == "down" { + (cur + 1) % len + } else { + (cur + len - 1) % len + }; + picker.ensure_selected_visible(len); + effects.redraw = true; + } + effects.handled = true; + true + } + "enter" => { + if let Some(&(wire_id, _)) = + items.get(picker.selected.min(items.len().saturating_sub(1))) + { + let block_id = picker.block_id.clone(); + self.record_recent_code_language(wire_id); + self.close_code_lang_picker(now_ms); + effects.edits.push(super::DocEdit::SetProp { + block_id, + key: "prop:language", + value: super::helpers::normalize_code_language(wire_id), + }); + } else { + self.close_code_lang_picker(now_ms); + } + effects.handled = true; + effects.redraw = true; + true + } + "escape" => { + if picker.input.composing() { + picker.input.cancel_preedit(); + } else { + self.close_code_lang_picker(now_ms); + } + effects.handled = true; + effects.redraw = true; + true + } + _ => false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn code_lang_picker_trackpad_micro_scroll_accumulates_subpixel_without_row_jumps() { + let mut overlays = Overlays::new(); + overlays.open_code_lang_picker("b-code".into(), "rust", 0.0); + let picker = overlays.code_lang_picker_mut().unwrap(); + picker.max_scroll = 1000.0; + picker.scroll_offset = 0.0; + for _ in 0..20 { + assert!(picker.scroll_by_px(-0.25)); + } + assert!( + (picker.scroll_offset - 5.0).abs() < 1e-5, + "20 x 0.25px micro-scrolls must accumulate to 5.0px (not 20 rows), got {}", + picker.scroll_offset + ); + } + + #[test] + fn code_lang_picker_hover_moves_single_focused_row_and_remembers_recent() { + let mut overlays = Overlays::new(); + overlays.open_code_lang_picker("b-code".into(), "rust", 0.0); + let mut effects = super::super::OverlayEffects::default(); + overlays.handle_code_and_media_event( + &OverlayEvent::CodeLangPickerHover(4), + None, + 10.0, + &mut effects, + ); + assert_eq!(overlays.code_lang_picker().unwrap().selected, 4); + assert!(effects.redraw); + + overlays.handle_code_and_media_event( + &OverlayEvent::SetCodeLanguage { + block_id: "b-code".into(), + language: "python".into(), + }, + None, + 20.0, + &mut effects, + ); + assert_eq!( + overlays.recent_code_languages.first().map(String::as_str), + Some("python") + ); + } + + #[test] + fn plain_text_pins_first_ahead_of_recent_languages() { + let recent = vec!["rust".to_string(), "python".to_string()]; + for raw in ["", "plain text", "text", "Plain"] { + let ordered = filter_code_languages_ordered("", raw, &recent); + assert_eq!( + ordered.first(), + Some(&("", "Plain Text")), + "active {raw:?} must pin Plain Text first" + ); + assert_eq!(ordered.get(1), Some(&("rust", "Rust"))); + } + } +} diff --git a/blocksuite/crates/editor/src/overlays/code_lang_picker/render.rs b/blocksuite/crates/editor/src/overlays/code_lang_picker/render.rs new file mode 100644 index 0000000000..1e438b988b --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/code_lang_picker/render.rs @@ -0,0 +1,437 @@ +//! Rendering for the searchable, pixel-scrollable code-block language selector +//! (`overlay.code_lang_picker`). + +use ui::{ + AnyElement, ClickEvent, Context, FontWeight, Hsla, MouseButton, MouseDownEvent, MouseMoveEvent, + ScrollEvent, SharedString, Window, canvas, div, point, prelude::*, px, +}; + +use crate::{ + block_flow::{CODE_PADDING, FlowRect}, + scroll::{snap_device_pixel, wheel_delta}, + theme::Palette, +}; + +use super::{ + OverlayEvent, OverlayHost, OverlayScene, Overlays, PICKER_ANCHOR_OFFSET, PICKER_EDGE_PAD, + PICKER_FONT_PX, PICKER_MAX_HEIGHT, PICKER_MIN_THUMB, PICKER_PADDING, PICKER_ROW_HEIGHT_DESKTOP, + PICKER_ROW_HEIGHT_TOUCH, PICKER_SCROLLBAR_GUTTER, PICKER_SCROLLBAR_WIDTH, + PICKER_SEARCH_HEIGHT_DESKTOP, PICKER_SEARCH_HEIGHT_TOUCH, PICKER_SEP_HEIGHT, PICKER_SEP_MARGIN, + PICKER_WIDTH, POPOVER_EDGE_MARGIN, Placement, SingleLineInputSpec, TOOLBAR_RADIUS, + canonical_code_language, emit, filter_code_languages_ordered, + paint_single_line_input_inner_sized, place, place_popover, +}; + +fn paint_search_icon(color: Hsla) -> AnyElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let x = f32::from(bounds.origin.x); + let y = f32::from(bounds.origin.y); + let w = f32::from(bounds.size.width); + let h = f32::from(bounds.size.height); + let cx = x + w * 0.44; + let cy = y + h * 0.44; + let r = w.min(h) * 0.28; + let mut ring = ui::PathBuilder::stroke(px(1.5)); + const SEGMENTS: usize = 16; + for i in 0..=SEGMENTS { + let theta = (i as f32 / SEGMENTS as f32) * std::f32::consts::TAU; + let pt = point(px(cx + r * theta.cos()), px(cy + r * theta.sin())); + if i == 0 { + ring.move_to(pt); + } else { + ring.line_to(pt); + } + } + ring.close(); + if let Ok(path) = ring.build() { + window.paint_path(path, color); + } + let mut handle = ui::PathBuilder::stroke(px(1.5)); + let d = r * 0.72; + handle.move_to(point(px(cx + d), px(cy + d))); + handle.line_to(point(px(x + w * 0.84), px(y + h * 0.84))); + if let Ok(path) = handle.build() { + window.paint_path(path, color); + } + }, + ) + .flex_none() + .w(px(16.0)) + .h(px(16.0)) + .into_any_element() +} + +fn paint_done_icon(color: Hsla) -> AnyElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let x = f32::from(bounds.origin.x); + let y = f32::from(bounds.origin.y); + let w = f32::from(bounds.size.width); + let h = f32::from(bounds.size.height); + let mut check = ui::PathBuilder::stroke(px(1.75)); + check.move_to(point(px(x + w * 0.20), px(y + h * 0.52))); + check.line_to(point(px(x + w * 0.42), px(y + h * 0.72))); + check.line_to(point(px(x + w * 0.80), px(y + h * 0.30))); + if let Ok(path) = check.build() { + window.paint_path(path, color); + } + }, + ) + .flex_none() + .w(px(20.0)) + .h(px(20.0)) + .into_any_element() +} + +impl Overlays { + pub(crate) fn render_code_lang_picker( + &mut self, + scene: &OverlayScene<'_>, + palette: &Palette, + now_ms: f64, + window: &mut Window, + cx: &mut Context, + ) -> Option { + let recent = self.recent_code_languages.clone(); + let picker = self.code_lang_picker.as_mut()?; + picker.rect = None; + let progress = picker.presence.progress(now_ms); + if picker.presence.closing && progress <= 0.0 { + return None; + } + let interactive = !picker.presence.closing; + let progress = if interactive { + progress.max(0.01) + } else { + progress + }; + let block = scene.layout.block(&picker.block_id)?; + let (_, pad_x) = CODE_PADDING; + let current_lang = scene + .snapshot + .block(&picker.block_id) + .and_then(|n| match &n.content { + blocksuite_playground_doc::read::BlockContent::Code { language, .. } => { + Some(canonical_code_language(language)) + } + _ => None, + }) + .unwrap_or_else(|| picker.current_lang.clone()); + picker.current_lang = current_lang.clone(); + + // Anchor to the language button position inside the code block's top bar. + let anchor_world = FlowRect::new(block.x + pad_x, block.y + 4.0, 96.0, 28.0); + if !scene.anchor_visible(&anchor_world) { + return None; + } + let touch = scene.is_touch || scene.form_factor != crate::block_flow::FormFactor::Desktop; + let row_h = if touch { + PICKER_ROW_HEIGHT_TOUCH + } else { + PICKER_ROW_HEIGHT_DESKTOP + }; + let search_h = if touch { + PICKER_SEARCH_HEIGHT_TOUCH + } else { + PICKER_SEARCH_HEIGHT_DESKTOP + }; + picker.row_height = row_h; + + let query = picker.input.text(); + let items = filter_code_languages_ordered(&query, ¤t_lang, &recent); + + let anchor = scene.world_to_screen(&anchor_world); + let mut viewport = scene.popover_viewport(); + if touch { + viewport.h = (viewport.h - 60.0).max(160.0); + } + let room_below = + (viewport.bottom() - anchor.bottom() - PICKER_ANCHOR_OFFSET - PICKER_EDGE_PAD).max(0.0); + let room_above = (anchor.y - viewport.y - PICKER_ANCHOR_OFFSET - PICKER_EDGE_PAD).max(0.0); + let available_h = room_below.max(room_above).max(120.0); + let max_panel_h = PICKER_MAX_HEIGHT.min(available_h); + + let chrome_h = + 2.0 * PICKER_PADDING + search_h + 2.0 * PICKER_SEP_MARGIN + PICKER_SEP_HEIGHT + 1.0; + let empty_h = row_h.max(36.0); + let content_h = if items.is_empty() { + empty_h + } else { + items.len() as f32 * row_h + }; + let max_list_h = (max_panel_h - chrome_h).max(0.0); + let list_h = content_h.min(max_list_h); + let panel_h = (chrome_h + list_h).min(max_panel_h); + let width = PICKER_WIDTH.min((viewport.w - 2.0 * POPOVER_EDGE_MARGIN).max(160.0)); + + picker.list_height = list_h; + let max_scroll = if items.is_empty() { + 0.0 + } else { + (content_h - list_h).max(0.0) + }; + picker.max_scroll = max_scroll; + if query != picker.last_query { + picker.last_query = query.clone(); + picker.selected = 0; + picker.scroll_offset = 0.0; + } else if items.is_empty() { + picker.selected = 0; + picker.scroll_offset = 0.0; + } else { + picker.selected = picker.selected.min(items.len() - 1); + picker.scroll_offset = picker.scroll_offset.clamp(0.0, max_scroll); + } + + let placed = place_popover( + anchor, + (width, panel_h), + viewport, + Placement::BelowStart, + PICKER_ANCHOR_OFFSET, + PICKER_EDGE_PAD, + ); + picker.rect = Some(placed.rect); + + let block_id = picker.block_id.clone(); + let selected_idx = picker.selected; + let scale = window.scale_factor(); + let paint_scroll = snap_device_pixel(picker.scroll_offset, scale); + let panel_bg = palette + .theme + .css_color("--affine-v2-layer-background-overlayPanel") + .unwrap_or(palette.panel); + let border_color = palette + .theme + .css_color("--affine-v2-layer-insideBorder-border") + .unwrap_or(palette.border); + let focus_blue = palette + .theme + .css_color("--affine-blue-700") + .unwrap_or(palette.brand); + let hover_filled = palette + .theme + .css_color("--affine-hover-color-filled") + .unwrap_or(palette.hover); + let thumb_color = palette + .theme + .css_color("--affine-v2-icon-secondary") + .unwrap_or_else(|| palette.text_secondary.opacity(0.45)); + + let inner_w = (width - 2.0 * PICKER_PADDING - 1.0).max(1.0); + let text_room = (inner_w - 20.0 - 16.0 - 6.0).max(24.0); + let shown: SharedString = picker.input.input.display_text().into(); + let search_inner_h = (search_h - 8.0).max(16.0); + let input_inner = paint_single_line_input_inner_sized( + &picker.input, + &shown, + SingleLineInputSpec { + text_room, + inner_height: search_inner_h, + caret_height: 16.0, + caret_top: ((search_inner_h - 16.0) * 0.5).max(0.0), + placeholder: "Search for a language", + focused: interactive, + }, + PICKER_FONT_PX, + palette, + window, + ); + + let search_box = div() + .flex_none() + .w_full() + .h(px(search_h)) + .px(px(10.0)) + .py(px(4.0)) + .gap(px(6.0)) + .rounded(px(4.0)) + .bg(palette.background) + .border_1() + .border_color(if interactive { + focus_blue + } else { + ui::transparent_black() + }) + .when(interactive, |el| { + el.shadow(palette.theme.shadows("--affine-active-shadow").into()) + }) + .flex() + .items_center() + .text_size(px(PICKER_FONT_PX)) + .snapshot( + "overlay.code_lang_picker.search", + Some("overlay.code_lang_picker"), + ) + .snapshot_focused(interactive) + .snapshot_text(query) + .child(paint_search_icon(palette.icon)) + .child(input_inner); + + let separator = div() + .flex_none() + .w_full() + .h(px(PICKER_SEP_HEIGHT)) + .my(px(PICKER_SEP_MARGIN)) + .bg(palette.divider); + + let row_width = if max_scroll > 0.0 { + (inner_w - PICKER_SCROLLBAR_GUTTER).max(1.0) + } else { + inner_w + }; + let mut list = div() + .relative() + .flex_none() + .w(px(inner_w)) + .h(px(list_h)) + .overflow_hidden(); + + if items.is_empty() { + list = list.child( + div() + .size_full() + .flex() + .items_center() + .justify_center() + .text_size(px(PICKER_FONT_PX - 1.0)) + .text_color(palette.text_secondary) + .snapshot( + "overlay.code_lang_picker.empty", + Some("overlay.code_lang_picker"), + ) + .snapshot_text("No matching language") + .child("No matching language"), + ); + } else { + for (idx, &(wire_id, label)) in items.iter().enumerate() { + let top = idx as f32 * row_h - paint_scroll; + if top + row_h <= 0.0 || top >= list_h { + continue; + } + let fully_visible = top >= -0.5 && top + row_h <= list_h + 0.5; + let is_current = current_lang == wire_id; + let is_focused = idx == selected_idx; + let bid = block_id.clone(); + let lang = wire_id.to_string(); + let mut row = div() + .id(SharedString::from(format!("code-lang-row-{idx}"))) + .absolute() + .left(px(0.0)) + .top(px(top)) + .w(px(row_width)) + .h(px(row_h)) + .px(px(12.0)) + .gap(px(4.0)) + .rounded(px(4.0)) + .flex() + .items_center() + .text_size(px(PICKER_FONT_PX)) + .font_weight(FontWeight::NORMAL) + .text_color(if is_focused { + focus_blue + } else { + palette.text_primary + }) + .when(is_focused, |el| el.bg(hover_filled)) + .child(div().flex_1().overflow_hidden().child(label)); + if fully_visible { + row = row + .snapshot( + SharedString::from(format!( + "overlay.code_lang_picker.item.{}", + if wire_id.is_empty() { "plain" } else { wire_id } + )), + Some("overlay.code_lang_picker"), + ) + .snapshot_focused(is_current) + .snapshot_text(label); + } + if is_current { + row = row.child(paint_done_icon(focus_blue)); + } + if interactive { + row = row + .cursor_pointer() + .on_mouse_move(emit(cx, move |_: &MouseMoveEvent| { + OverlayEvent::CodeLangPickerHover(idx) + })) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(emit(cx, move |_: &ClickEvent| { + OverlayEvent::SetCodeLanguage { + block_id: bid.clone(), + language: lang.clone(), + } + })); + } + list = list.child(row); + } + } + + if max_scroll > 0.0 && list_h > 4.0 { + let thumb_h = + ((list_h / content_h) * list_h).clamp(PICKER_MIN_THUMB.min(list_h), list_h); + let travel = (list_h - thumb_h).max(0.0); + let thumb_top = snap_device_pixel((picker.scroll_offset / max_scroll) * travel, scale); + list = list.child( + div() + .absolute() + .right(px(0.0)) + .top(px(thumb_top)) + .w(px(PICKER_SCROLLBAR_WIDTH)) + .h(px(thumb_h)) + .rounded(px(PICKER_SCROLLBAR_WIDTH * 0.5)) + .bg(thumb_color) + .snapshot( + "overlay.code_lang_picker.scrollbar", + Some("overlay.code_lang_picker"), + ), + ); + } + + let overlay_shadow = { + let s = palette.theme.shadows("--affine-overlay-shadow"); + if s.is_empty() { + palette.theme.shadows("--affine-overlay-panel-shadow") + } else { + s + } + }; + let mut root = place(placed.rect) + .id("code-lang-picker") + .flex() + .flex_col() + .p(px(PICKER_PADDING)) + .rounded(px(TOOLBAR_RADIUS)) + .bg(panel_bg) + .border(px(0.5)) + .border_color(border_color) + .shadow(overlay_shadow.into()) + .opacity(progress) + .snapshot("overlay.code_lang_picker", Some("root.canvas")) + .snapshot_focused(interactive) + .child(search_box) + .child(separator) + .child(list); + + if interactive { + root = root + .occlude() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_scroll(cx.listener(move |view: &mut V, ev: &ScrollEvent, w, cx| { + cx.stop_propagation(); + let (_, dy) = wheel_delta(ev, list_h.max(row_h)); + if dy != 0.0 { + view.dispatch_overlay(OverlayEvent::CodeLangPickerScroll(dy), w, cx); + } + })) + .on_mouse_down_out(emit(cx, |_: &MouseDownEvent| { + OverlayEvent::CloseCodeLangPicker + })); + } + Some(root.into_any_element()) + } +} diff --git a/blocksuite/crates/editor/src/overlays/equation.rs b/blocksuite/crates/editor/src/overlays/equation.rs index 7b9c10d0cd..ba5b141769 100644 --- a/blocksuite/crates/editor/src/overlays/equation.rs +++ b/blocksuite/crates/editor/src/overlays/equation.rs @@ -551,8 +551,8 @@ impl Overlays { } else if caret_top_y + EQUATION_LINE_HEIGHT > editor.scroll_y + inner_h { editor.scroll_y = caret_top_y + EQUATION_LINE_HEIGHT - inner_h; } - editor.scroll_y = editor.scroll_y.clamp(0.0, max_scroll_y).round(); - let scroll_y = editor.scroll_y; + editor.scroll_y = editor.scroll_y.clamp(0.0, max_scroll_y); + let scroll_y = crate::scroll::snap_device_pixel(editor.scroll_y, window.scale_factor()); let mut inner = div() .relative() diff --git a/blocksuite/crates/editor/src/overlays/events.rs b/blocksuite/crates/editor/src/overlays/events.rs new file mode 100644 index 0000000000..ffc14da204 --- /dev/null +++ b/blocksuite/crates/editor/src/overlays/events.rs @@ -0,0 +1,412 @@ +use blocksuite_playground_doc::read::TextAlign as BlockAlign; +use y_octo::Any; + +use crate::block_flow::FlowRect; + +use super::{ + ActiveSelection, AttachmentToolbarAction, BlockMenuAction, BookmarkToolbarAction, + CalloutAction, ContextMenuAction, EquationTarget, FormatAction, FormatMoreAction, + HighlightColor, ImageResizeSide, ImageToolbarAction, KeyboardToolbarAction, LinkEditField, + LinkPopupAction, PdfViewerEvent, SlashCommand, SlashEmbedKind, +}; + +/// A document edit an overlay asks the view for. The view carries each out through the +/// editor's document session as one undo step. +#[derive(Clone, Debug, PartialEq)] +pub enum DocEdit { + SetProp { + block_id: String, + key: &'static str, + value: Any, + }, + /// Reorder one or more blocks as one atomic undo step before `insert_index` in `parent_id`. + ReorderMany { + parent_id: String, + child_ids: Vec, + insert_index: usize, + }, + /// Insert an empty sibling paragraph below `block_id` (after a collapsed heading section). + InsertParagraphBelow { block_id: String }, + Slash { + block_id: String, + command: SlashCommand, + /// Whether the command was typed into the block after a `/`, which goes first. + typed: bool, + }, + /// Toggle an inline mark over the text selection. + Mark(&'static str), + /// Convert the selected block(s) via desktop `FormatToolbar`'s `Turn into ▾` dropdown. + TurnInto(SlashCommand), + /// Set or clear a rich-text `color` or `background` highlight mark over the selection. + ColorMark { + key: &'static str, + value: Option<&'static str>, + }, + /// Align the selected blocks. + Align(BlockAlign), + /// Link the text selection to a URL, or clear its link, optionally updating display text. + Link { + url: Option, + /// When editing an existing uniform link, preserves peer edits outside sub-ranges still + /// matching `expected_prev_url`. + expected_prev_url: Option, + /// Original selected text when the dual-field `Text` + `Link` editor opened, used to + /// abort stale display-text replacement if a peer modified or partially unlinked the span. + expected_prev_text: Option, + /// Optional updated display text from the dual-field `Text` + `Link` editor. + display_text: Option, + }, + /// Convert the current text selection into an inline LaTeX equation and open `EquationEditor`. + InlineEquationFromSelection, + /// Create a linked document from the current text selection and replace it with an `@reference`. + CreateLinkedDocFromSelection, + /// Execute a command from the desktop formatting toolbar's `More (...)` dropdown. + FormatMore(FormatMoreAction), + /// Commit a LaTeX equation string to a block or inline target. + Equation { + target: EquationTarget, + latex: String, + }, + /// Insert a validated `affine:bookmark` block below `block_id`. + Bookmark { + block_id: String, + url: String, + remove_empty_block: bool, + }, + /// Update `prop:caption` on `block_id` as one undo step. + SetCaption { block_id: String, caption: String }, + /// Set or clear `prop:icon` (`IconData` Map `{"type":"emoji","unicode":...}` or `Null`) on a Callout. + SetCalloutIcon { block_id: String, unicode: String }, + /// Update custom alias (`reference.title`) on an inline `@reference` chip as one undo step. + SetReferenceAlias { + block_id: String, + utf16_offset: usize, + page_id: String, + alias: Option, + }, +} + +/// Something that happened to the overlays: input routed by the view, or a call of the +/// public API (`PlaygroundView::dispatch_overlay`). Pointer positions are in window space. +#[derive(Clone, Debug, PartialEq)] +pub enum OverlayEvent { + PointerMoved { + x: f32, + y: f32, + /// Whether the primary button is held. + pressed: bool, + }, + PointerUp, + /// Open the slash menu for a block with a filter of its own. `anchor` is a + /// screen-space rectangle to hang the menu from; the caret of `utf16_offset` when + /// absent. + OpenSlashMenu { + block_id: String, + utf16_offset: usize, + anchor: Option, + }, + /// Replace the slash menu's filter. `in_document` says the filter is text typed into + /// the block after its `/`. + SetSlashQuery { + query: String, + in_document: bool, + }, + CloseSlashMenu, + SlashHover(usize), + SlashExecute(usize), + SlashSubmenuHover(usize), + SlashSubmenuExecute(usize), + SlashScroll(f32), + /// Set or clear the editor's text selection. + SetSelection(Option), + Format(FormatAction), + /// Execute a block conversion from desktop `FormatToolbar`'s `Turn into ▾` dropdown. + FormatTurnInto(SlashCommand), + /// Apply or clear a foreground text color from desktop `FormatToolbar`'s `Highlight` palette. + FormatTextColor(HighlightColor), + /// Apply or clear a background highlight color from desktop `FormatToolbar`'s `Highlight` palette. + FormatBgColor(HighlightColor), + /// Execute a command from desktop `FormatToolbar`'s `More (...)` dropdown. + FormatMore(FormatMoreAction), + /// Focus either the `Text` or `Url` input inside the dual-field `LinkBar`. + FocusLinkField(LinkEditField), + LinkApply, + LinkRemove, + /// Text pasted into the link field. + Paste(String), + ToggleChecked(String), + ToggleCollapsed(String), + CopyCode(String), + /// Toggle `prop:wrap` on an `affine:code` block as one undo step. + ToggleCodeWrap(String), + /// Cycle or update `prop:language` on an `affine:code` block as one undo step. + SetCodeLanguage { + block_id: String, + language: String, + }, + /// Open or toggle the searchable code-block language picker. + OpenCodeLangPicker(String), + /// Scroll the searchable code-block language picker list by `delta_y` logical pixels. + CodeLangPickerScroll(f32), + /// Synchronize the focused row index of the code-block language picker on pointer hover. + CodeLangPickerHover(usize), + /// Set the horizontal scroll offset of a wide code, table, or database block. + SetBlockScrollX { + block_id: String, + scroll_x: f32, + }, + /// Start dragging a wide block's horizontal scrollbar thumb (or track jump + drag). + StartBlockHScrollDrag { + block_id: String, + pointer_x: f32, + scroll_x: f32, + track_travel: f32, + max_scroll_x: f32, + }, + /// Dismiss the searchable code-block language picker. + CloseCodeLangPicker, + /// Toggle `prop:lineNumber` on an `affine:code` block as one undo step. + ToggleCodeLineNumber(String), + /// Toggle `prop:collapsed` (8-line fold) on an `affine:code` block as one undo step. + ToggleCodeCollapsed(String), + /// Select a single block into `block_selection` (e.g., first click on block LaTeX / Bookmark / Callout). + SelectBlock(String), + /// Open the fullscreen image Lightbox for `block_id`. + OpenImageLightbox(String), + /// Adjust image Lightbox zoom (`0.0` resets to `100%`). + ImageLightboxZoom(f32), + /// Pan the zoomed image inside the open Lightbox by `(dx, dy)` logical px. + ImageLightboxPan { + dx: f32, + dy: f32, + }, + /// Begin pointer drag-pan inside the open Lightbox at window-space `(x, y)`. + ImageLightboxDragStart { + x: f32, + y: f32, + }, + /// Continue pointer drag-pan inside the open Lightbox at window-space `(x, y)`. + ImageLightboxDragMove { + x: f32, + y: f32, + }, + /// Finish pointer drag-pan inside the open Lightbox. + ImageLightboxDragEnd, + /// Click on the Lightbox backdrop (closes unless suppressed by an active drag). + ImageLightboxBackdropClick, + /// Scroll the touch bottom context bar (`image_toolbar` / `bookmark_toolbar` / `callout_toolbar`). + TouchContextBarScroll(f32), + /// Close the fullscreen image Lightbox. + CloseImageLightbox, + /// Open a Bookmark block's external URL. + OpenBookmarkUrl(String), + /// Execute a command from `overlay.bookmark_toolbar`. + BookmarkToolbarAction { + block_id: String, + action: BookmarkToolbarAction, + }, + /// Execute a command from `overlay.callout_toolbar` or `overlay.callout_icon_picker`. + CalloutAction { + block_id: String, + action: CalloutAction, + }, + /// Dismiss the Callout emoji/icon picker. + CloseCalloutIconPicker, + /// Toggle transient visual preview mode on a `mermaid`, `typst`, or `html` code block. + ToggleCodePreview(String), + /// Click or activate an external embed card (`Idle` -> `Selected` -> `Active`). + ExternalEmbedInteract { + block_id: String, + activate: bool, + }, + DragStart(String), + /// Pointer press on the gutter drag handle: drag after threshold, or click to toggle block menu. + DragHandlePress { + block_id: String, + anchor: (f32, f32), + }, + /// Click on the `+` quick-insert button beside the drag handle. + AddBlockBelow(String), + /// Begin a Page-margin marquee selection (`PageDraggingArea`) at window coordinates `(x, y)`. + MarqueeStart { + x: f32, + y: f32, + }, + /// Toggle the `Turn into` submenu inside the open drag-handle block action menu. + BlockMenuToggleTurnInto, + /// Dismiss the drag-handle block action menu. + CloseBlockMenu, + /// Execute a command from the drag-handle block action menu. + BlockMenuAction { + block_id: String, + action: BlockMenuAction, + }, + /// Open the `@` linked-document picker with an initial query. + OpenLinkedDocMenu { + block_id: String, + query: String, + }, + /// Update the open `@` linked-document picker query. + SetLinkedDocQuery(String), + /// Hover a row in the open `@` linked-document picker (`0..items.len()` or `items.len()` for Create). + LinkedDocHover(usize), + /// Select a row in the open `@` linked-document picker (`0..items.len()` inserts existing doc chip; + /// `items.len()` creates a new linked doc and inserts its chip). + LinkedDocSelect(usize), + /// Scroll the `@` linked-document picker list vertically by `delta` px. + LinkedDocScroll(f32), + /// Expand the `@` linked-document picker to load/show all remaining documents. + LinkedDocExpandMore, + /// Dismiss the `@` linked-document picker. + CloseLinkedDocMenu, + /// Dismiss the lightweight link / `@reference` capsule. + CloseLinkPopup, + /// Execute an action from the lightweight link / `@reference` capsule. + LinkPopupAction(LinkPopupAction), + /// Create a linked document (or convert a line to a linked doc) through the host directory + /// and insert its `LinkedPage` inline reference chip into `block_id` as one undo step. + CreateLinkedDoc { + block_id: String, + title: String, + mode: crate::directory::EditorDocMode, + intent_id: Option, + }, + /// Open the equation editor for a block or inline latex target. + OpenEquationEditor { + target: EquationTarget, + initial: String, + }, + /// Commit the equation editor's current LaTeX string. + EquationApply, + /// Click inside the multiline equation editor at window coordinates `(x, y)`. + EquationClick { + x: f32, + y: f32, + shift: bool, + }, + /// Dismiss the equation editor without committing. + CloseEquationEditor, + /// Open the bookmark URL prompt anchored to `block_id`. + OpenBookmarkPrompt { + block_id: String, + }, + /// Open the caption editor anchored to `block_id`. + OpenCaptionPrompt { + block_id: String, + }, + /// Commit the bookmark URL or caption prompt (no-op if empty/invalid or unchanged). + BookmarkApply, + /// Dismiss the bookmark URL or caption prompt without mutating the document. + CloseBookmarkPrompt, + /// Select an `affine:image` block in Page mode. + SelectImageBlock(String), + /// Begin dragging an `affine:image` corner resize handle at window x `start_x`. + ImageResizeStart { + block_id: String, + side: ImageResizeSide, + start_x: f32, + }, + /// Execute a command from the floating `overlay.image_toolbar`. + ImageToolbarAction { + block_id: String, + action: ImageToolbarAction, + }, + /// Insert a decoded image blob chosen from the host file picker as an `affine:image` block. + InsertImageBytes { + bytes: Vec, + caption: String, + }, + /// Insert an arbitrary attachment file blob under its content-addressed `sourceId`. + InsertAttachmentBytes { + name: String, + mime_type: String, + bytes: Vec, + }, + /// Scroll the horizontal mobile keyboard toolbar strip by `delta_x` px. + KeyboardToolbarScroll(f32), + /// Scroll the active mobile keyboard tool panel (`+`, `Turn into`, or `Highlight`) by `delta_y` px. + KeyboardToolbarPanelScroll(f32), + /// Trigger one action button on the mobile bottom keyboard toolbar. + KeyboardToolbar(KeyboardToolbarAction), + /// Focus an `affine:table` cell in place for live `Y.Text` CRDT editing. + FocusTableCell { + block_id: String, + row_id: String, + column_id: String, + screen_pos: Option<(f32, f32)>, + }, + /// Pointer press on an `affine:table` cell (supports click, double/triple click, Shift+click, drag). + TableCellMouseDown { + block_id: String, + row_id: String, + column_id: String, + screen_pos: (f32, f32), + click_count: usize, + shift: bool, + }, + AttachmentPdfPage { + block_id: String, + delta: i32, + }, + SelectAttachmentBlock(String), + AttachmentToolbarAction { + block_id: String, + action: AttachmentToolbarAction, + }, + PdfViewer(PdfViewerEvent), + /// Open the target document of an `affine:embed-linked-doc` or `affine:embed-synced-doc` card. + OpenEmbedDoc { + page_id: String, + }, + /// Switch to Edgeless mode and fit the camera to the `Frame` / `Group` referenced by an + /// `affine:surface-ref` card. + JumpToSurfaceRef { + reference: String, + }, + /// Touch long-press at window coordinates `(x, y)` to select the ICU word under the finger. + LongPressWord { + x: f32, + y: f32, + }, + /// Open the desktop right-click context menu at window coordinates `(x, y)`. + OpenContextMenu { + x: f32, + y: f32, + }, + /// Dismiss the desktop right-click context menu. + CloseContextMenu, + /// Execute a command from the desktop right-click context menu. + ContextMenuAction(ContextMenuAction), +} + +/// What the view has to do after an [`OverlayEvent`] or a key. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct OverlayEffects { + /// Edits to carry out, in order. + pub edits: Vec, + /// Text to put on the clipboard. + pub clipboard: Option, + /// Start a [`COPIED_MS`] timer on the scheduler clock and report its end with + /// [`Overlays::copied_expired`] and this generation. + pub copied_timer: Option, + /// Read the clipboard into the link field. + pub paste: bool, + /// Desktop context-menu command triggered via keyboard (`Enter`). + pub context_menu_action: Option, + /// Drag-handle block menu command triggered via keyboard (`Enter`) or click. + pub block_menu_action: Option<(String, BlockMenuAction)>, + /// Block id to select into `block_selection` when the drag-handle block menu opens. + pub select_block: Option, + /// Replace `block_selection` live during Page-margin marquee selection (`PageDraggingArea`). + pub set_block_selection: Option>, + /// Local-only collapse toggle for non-heading `Paragraph`/`Quote` blocks (zero CRDT write). + pub toggle_local_collapse: Option, + /// External embed insertion requested by the single-line URL prompt: + /// `(block_id, kind, url, remove_empty_block)`. + pub embed_insert: Option<(String, SlashEmbedKind, String, bool)>, + /// Schedule a one-shot 800 ms wakeup so the Slash preview card opens without extra pointer moves. + pub slash_preview_timer: bool, + pub redraw: bool, + /// Whether a key was consumed. + pub handled: bool, +} diff --git a/blocksuite/crates/editor/src/overlays/helpers.rs b/blocksuite/crates/editor/src/overlays/helpers.rs index d0d09f3571..07764ac160 100644 --- a/blocksuite/crates/editor/src/overlays/helpers.rs +++ b/blocksuite/crates/editor/src/overlays/helpers.rs @@ -349,6 +349,8 @@ impl Overlays { /// Hide the hovered gutter handle (e.g. when typing or scrolling). pub fn hide_hover(&mut self) { self.hovered = None; + self.hscroll_hovered = None; + self.hscroll_drag = None; self.handle_hot = false; self.handle_stretch = None; } @@ -519,6 +521,8 @@ impl Overlays { /// replaced. pub fn reset(&mut self) { self.hovered = None; + self.hscroll_hovered = None; + self.hscroll_drag = None; self.handle_hot = false; self.handle_stretch = None; self.slash = None; diff --git a/blocksuite/crates/editor/src/overlays/image_toolbar.rs b/blocksuite/crates/editor/src/overlays/image_toolbar.rs index 34fcd361f1..2d3f78b369 100644 --- a/blocksuite/crates/editor/src/overlays/image_toolbar.rs +++ b/blocksuite/crates/editor/src/overlays/image_toolbar.rs @@ -309,10 +309,9 @@ impl Overlays { .occlude() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) - .on_scroll(emit(cx, |event: &ScrollEvent| { - let d = event.delta.pixel_delta(px(20.0)); - let dx = f32::from(d.x); - OverlayEvent::TouchContextBarScroll(if dx != 0.0 { dx } else { f32::from(d.y) }) + .on_scroll(emit(cx, move |event: &ScrollEvent| { + let (dx, dy) = crate::scroll::wheel_delta(event, rect.h); + OverlayEvent::TouchContextBarScroll(crate::scroll::dominant_axis_delta(dx, dy)) })) .p(px(TOOLBAR_PADDING)) .rounded(px(TOOLBAR_RADIUS)) @@ -476,7 +475,7 @@ impl Overlays { let root = place(placed.rect) .id("image-toolbar") - .occlude() + .block_mouse_except_scroll() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_mouse_down_out(|_: &MouseDownEvent, _, _| {}) .p(px(TOOLBAR_PADDING)) diff --git a/blocksuite/crates/editor/src/overlays/input_field.rs b/blocksuite/crates/editor/src/overlays/input_field.rs index f721904657..a5b356db23 100644 --- a/blocksuite/crates/editor/src/overlays/input_field.rs +++ b/blocksuite/crates/editor/src/overlays/input_field.rs @@ -31,13 +31,25 @@ pub(super) fn single_line_scroll_x(text_width: f32, caret_x: f32, text_room: f32 } } -/// Paint the scrollable inner viewport of a single-line [`LinkBar`] input. +/// Paint the scrollable inner viewport of a single-line [`LinkBar`] input at default `font_xs`. pub(super) fn paint_single_line_input_inner( bar: &LinkBar, shown: &SharedString, spec: SingleLineInputSpec, palette: &Palette, window: &mut Window, +) -> ui::Div { + paint_single_line_input_inner_sized(bar, shown, spec, TYPOGRAPHY.font_xs_px, palette, window) +} + +/// Paint the scrollable inner viewport of a single-line [`LinkBar`] input at an explicit `font_size`. +pub(super) fn paint_single_line_input_inner_sized( + bar: &LinkBar, + shown: &SharedString, + spec: SingleLineInputSpec, + font_size: f32, + palette: &Palette, + window: &mut Window, ) -> ui::Div { let (selection, reversed) = bar.shown_selection(); let marked = bar.marked_range(); @@ -46,7 +58,7 @@ pub(super) fn paint_single_line_input_inner( font.fallbacks = Some(crate::default_font_fallbacks()); let line = window.text_system().shape_line( shown.clone(), - px(TYPOGRAPHY.font_xs_px), + px(font_size), &[TextRun { len: shown.len(), font, diff --git a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs index 2a5dcfee1f..a34875e6f6 100644 --- a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs +++ b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/mod.rs @@ -516,9 +516,8 @@ impl Overlays { self.keyboard_toolbar.strip_scroll = 0.0; return true; } - self.keyboard_toolbar.strip_scroll = (self.keyboard_toolbar.strip_scroll - delta_x) - .clamp(0.0, max_scroll) - .round(); + self.keyboard_toolbar.strip_scroll = + (self.keyboard_toolbar.strip_scroll - delta_x).clamp(0.0, max_scroll); true } @@ -554,7 +553,7 @@ impl Overlays { if !bar_rect.contains(x, y) { return false; } - let step = if delta_x != 0.0 { delta_x } else { delta_y }; + let step = crate::scroll::dominant_axis_delta(delta_x, delta_y); self.scroll_keyboard_toolbar_strip(scene, step) } @@ -689,9 +688,8 @@ impl Overlays { } } let max_scroll = (cursor_y - list_h).max(0.0); - self.keyboard_toolbar.panel_scroll = (self.keyboard_toolbar.panel_scroll - delta_y) - .clamp(0.0, max_scroll) - .round(); + self.keyboard_toolbar.panel_scroll = + (self.keyboard_toolbar.panel_scroll - delta_y).clamp(0.0, max_scroll); true } diff --git a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs index a2908bc923..c3db67e368 100644 --- a/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs +++ b/blocksuite/crates/editor/src/overlays/keyboard_toolbar/render.rs @@ -309,11 +309,9 @@ impl Overlays { .border_color(palette.border) .shadow(palette.theme.shadows("--affine-toolbar-shadow").into()) .occlude() - .on_scroll(emit(cx, |event: &ScrollEvent| { - let d = event.delta.pixel_delta(px(20.0)); - let dx = f32::from(d.x); - let step = if dx != 0.0 { dx } else { f32::from(d.y) }; - OverlayEvent::KeyboardToolbarScroll(step) + .on_scroll(emit(cx, move |event: &ScrollEvent| { + let (dx, dy) = crate::scroll::wheel_delta(event, rect.h); + OverlayEvent::KeyboardToolbarScroll(crate::scroll::dominant_axis_delta(dx, dy)) })) .snapshot("overlay.keyboard_toolbar", Some("root.canvas")); diff --git a/blocksuite/crates/editor/src/overlays/mod.rs b/blocksuite/crates/editor/src/overlays/mod.rs index 31bf0d099f..35b49c6548 100644 --- a/blocksuite/crates/editor/src/overlays/mod.rs +++ b/blocksuite/crates/editor/src/overlays/mod.rs @@ -14,6 +14,7 @@ mod context_menu; mod drag; mod embed_url; mod equation; +mod events; mod helpers; mod image_lightbox; mod image_toolbar; @@ -43,7 +44,9 @@ pub use bookmark_prompt::{BookmarkPrompt, BookmarkPromptKind}; pub use bookmark_toolbar::{BookmarkCardStyle, BookmarkToolbarAction}; pub use callout_bar::{CALLOUT_BG_COLORS, CALLOUT_ICON_PRESETS, CalloutAction}; pub use code_lang_picker::{ - CODE_LANGUAGES, CodeLangPicker, display_code_language, filter_code_languages, + CODE_LANGUAGE_CATALOG, CODE_LANGUAGES, CodeLangPicker, CodeLanguageSpec, + canonical_code_language, display_code_language, filter_code_languages, + filter_code_languages_ordered, }; pub use context_menu::{ CONTEXT_MENU_PADDING, CONTEXT_MENU_RADIUS, CONTEXT_MENU_ROW_HEIGHT, CONTEXT_MENU_WIDTH, @@ -63,7 +66,9 @@ pub use equation::{EquationEditor, EquationTarget}; use helpers::typed_text; pub use image_lightbox::ImageLightboxState; pub use image_toolbar::{ImageResizeSide, ImageToolbarAction}; -use input_field::{SingleLineInputSpec, paint_single_line_input_inner}; +use input_field::{ + SingleLineInputSpec, paint_single_line_input_inner, paint_single_line_input_inner_sized, +}; pub use keyboard_toolbar::{ DEFAULT_KEYBOARD_TOOLBAR_ITEMS, HighlightColor, KEYBOARD_TOOL_PANEL_HEIGHT, KEYBOARD_TOOLBAR_BUTTON, KEYBOARD_TOOLBAR_HEIGHT, KeyboardToolbarAction, @@ -92,7 +97,7 @@ pub use pdf_viewer::{ }; pub use scrollbar::{ SCROLLBAR_EDGE_INSET, SCROLLBAR_HIT_WIDTH, SCROLLBAR_MIN_THUMB, SCROLLBAR_VERTICAL_INSET, - SCROLLBAR_WIDTH, ScrollbarDrag, ScrollbarMetrics, build_page_scrollbar, + SCROLLBAR_WIDTH, ScrollCodeOutcome, ScrollbarDrag, ScrollbarMetrics, build_page_scrollbar, }; pub use selection_cache::{ BlockFormatCache, BlockSelectionRectsCache, FormatCache, LayoutCacheKey, @@ -120,7 +125,7 @@ use toolbar::{FormatToolbar, utf16_to_byte}; use std::collections::{BTreeSet, HashMap}; -use blocksuite_playground_doc::read::{PageSnapshot, TextAlign as BlockAlign}; +use blocksuite_playground_doc::read::PageSnapshot; use ui::{Context, Motion, MotionCurve, Window}; /// Host callbacks required by [`Overlays`] page-layer and popover builders. @@ -132,7 +137,6 @@ pub trait OverlayHost: 'static + Sized { cx: &mut Context, ); } -use y_octo::Any; use crate::{ TOPBAR_HEIGHT, @@ -208,391 +212,7 @@ pub(super) const COPY_BUTTON_INSET: f32 = 4.0; /// A pointer this close to a block's row still counts as hovering it. pub(super) const HOVER_SLACK: f32 = 9.0; -/// A document edit an overlay asks the view for. The view carries each out through the -/// editor's document session as one undo step. -#[derive(Clone, Debug, PartialEq)] -pub enum DocEdit { - SetProp { - block_id: String, - key: &'static str, - value: Any, - }, - /// Reorder one or more blocks as one atomic undo step before `insert_index` in `parent_id`. - ReorderMany { - parent_id: String, - child_ids: Vec, - insert_index: usize, - }, - /// Insert an empty sibling paragraph below `block_id` (after a collapsed heading section). - InsertParagraphBelow { block_id: String }, - Slash { - block_id: String, - command: SlashCommand, - /// Whether the command was typed into the block after a `/`, which goes first. - typed: bool, - }, - /// Toggle an inline mark over the text selection. - Mark(&'static str), - /// Convert the selected block(s) via desktop `FormatToolbar`'s `Turn into ▾` dropdown. - TurnInto(SlashCommand), - /// Set or clear a rich-text `color` or `background` highlight mark over the selection. - ColorMark { - key: &'static str, - value: Option<&'static str>, - }, - /// Align the selected blocks. - Align(BlockAlign), - /// Link the text selection to a URL, or clear its link, optionally updating display text. - Link { - url: Option, - /// When editing an existing uniform link, preserves peer edits outside sub-ranges still - /// matching `expected_prev_url`. - expected_prev_url: Option, - /// Original selected text when the dual-field `Text` + `Link` editor opened, used to - /// abort stale display-text replacement if a peer modified or partially unlinked the span. - expected_prev_text: Option, - /// Optional updated display text from the dual-field `Text` + `Link` editor. - display_text: Option, - }, - /// Convert the current text selection into an inline LaTeX equation and open `EquationEditor`. - InlineEquationFromSelection, - /// Create a linked document from the current text selection and replace it with an `@reference`. - CreateLinkedDocFromSelection, - /// Execute a command from the desktop formatting toolbar's `More (...)` dropdown. - FormatMore(FormatMoreAction), - /// Commit a LaTeX equation string to a block or inline target. - Equation { - target: EquationTarget, - latex: String, - }, - /// Insert a validated `affine:bookmark` block below `block_id`. - Bookmark { - block_id: String, - url: String, - remove_empty_block: bool, - }, - /// Update `prop:caption` on `block_id` as one undo step. - SetCaption { block_id: String, caption: String }, - /// Set or clear `prop:icon` (`IconData` Map `{"type":"emoji","unicode":...}` or `Null`) on a Callout. - SetCalloutIcon { block_id: String, unicode: String }, - /// Update custom alias (`reference.title`) on an inline `@reference` chip as one undo step. - SetReferenceAlias { - block_id: String, - utf16_offset: usize, - page_id: String, - alias: Option, - }, -} - -/// Something that happened to the overlays: input routed by the view, or a call of the -/// public API (`PlaygroundView::dispatch_overlay`). Pointer positions are in window space. -#[derive(Clone, Debug, PartialEq)] -pub enum OverlayEvent { - PointerMoved { - x: f32, - y: f32, - /// Whether the primary button is held. - pressed: bool, - }, - PointerUp, - /// Open the slash menu for a block with a filter of its own. `anchor` is a - /// screen-space rectangle to hang the menu from; the caret of `utf16_offset` when - /// absent. - OpenSlashMenu { - block_id: String, - utf16_offset: usize, - anchor: Option, - }, - /// Replace the slash menu's filter. `in_document` says the filter is text typed into - /// the block after its `/`. - SetSlashQuery { - query: String, - in_document: bool, - }, - CloseSlashMenu, - SlashHover(usize), - SlashExecute(usize), - SlashSubmenuHover(usize), - SlashSubmenuExecute(usize), - SlashScroll(f32), - /// Set or clear the editor's text selection. - SetSelection(Option), - Format(FormatAction), - /// Execute a block conversion from desktop `FormatToolbar`'s `Turn into ▾` dropdown. - FormatTurnInto(SlashCommand), - /// Apply or clear a foreground text color from desktop `FormatToolbar`'s `Highlight` palette. - FormatTextColor(HighlightColor), - /// Apply or clear a background highlight color from desktop `FormatToolbar`'s `Highlight` palette. - FormatBgColor(HighlightColor), - /// Execute a command from desktop `FormatToolbar`'s `More (...)` dropdown. - FormatMore(FormatMoreAction), - /// Focus either the `Text` or `Url` input inside the dual-field `LinkBar`. - FocusLinkField(LinkEditField), - LinkApply, - LinkRemove, - /// Text pasted into the link field. - Paste(String), - ToggleChecked(String), - ToggleCollapsed(String), - CopyCode(String), - /// Toggle `prop:wrap` on an `affine:code` block as one undo step. - ToggleCodeWrap(String), - /// Cycle or update `prop:language` on an `affine:code` block as one undo step. - SetCodeLanguage { - block_id: String, - language: String, - }, - /// Open or toggle the searchable code-block language picker. - OpenCodeLangPicker(String), - /// Scroll the searchable code-block language picker list by `delta_rows`. - CodeLangPickerScroll(isize), - /// Dismiss the searchable code-block language picker. - CloseCodeLangPicker, - /// Toggle `prop:lineNumber` on an `affine:code` block as one undo step. - ToggleCodeLineNumber(String), - /// Toggle `prop:collapsed` (8-line fold) on an `affine:code` block as one undo step. - ToggleCodeCollapsed(String), - /// Select a single block into `block_selection` (e.g., first click on block LaTeX / Bookmark / Callout). - SelectBlock(String), - /// Open the fullscreen image Lightbox for `block_id`. - OpenImageLightbox(String), - /// Adjust image Lightbox zoom (`0.0` resets to `100%`). - ImageLightboxZoom(f32), - /// Pan the zoomed image inside the open Lightbox by `(dx, dy)` logical px. - ImageLightboxPan { - dx: f32, - dy: f32, - }, - /// Begin pointer drag-pan inside the open Lightbox at window-space `(x, y)`. - ImageLightboxDragStart { - x: f32, - y: f32, - }, - /// Continue pointer drag-pan inside the open Lightbox at window-space `(x, y)`. - ImageLightboxDragMove { - x: f32, - y: f32, - }, - /// Finish pointer drag-pan inside the open Lightbox. - ImageLightboxDragEnd, - /// Click on the Lightbox backdrop (closes unless suppressed by an active drag). - ImageLightboxBackdropClick, - /// Scroll the touch bottom context bar (`image_toolbar` / `bookmark_toolbar` / `callout_toolbar`). - TouchContextBarScroll(f32), - /// Close the fullscreen image Lightbox. - CloseImageLightbox, - /// Open a Bookmark block's external URL. - OpenBookmarkUrl(String), - /// Execute a command from `overlay.bookmark_toolbar`. - BookmarkToolbarAction { - block_id: String, - action: BookmarkToolbarAction, - }, - /// Execute a command from `overlay.callout_toolbar` or `overlay.callout_icon_picker`. - CalloutAction { - block_id: String, - action: CalloutAction, - }, - /// Dismiss the Callout emoji/icon picker. - CloseCalloutIconPicker, - /// Toggle transient visual preview mode on a `mermaid`, `typst`, or `html` code block. - ToggleCodePreview(String), - /// Click or activate an external embed card (`Idle` -> `Selected` -> `Active`). - ExternalEmbedInteract { - block_id: String, - activate: bool, - }, - DragStart(String), - /// Pointer press on the gutter drag handle: drag after threshold, or click to toggle block menu. - DragHandlePress { - block_id: String, - anchor: (f32, f32), - }, - /// Click on the `+` quick-insert button beside the drag handle. - AddBlockBelow(String), - /// Begin a Page-margin marquee selection (`PageDraggingArea`) at window coordinates `(x, y)`. - MarqueeStart { - x: f32, - y: f32, - }, - /// Toggle the `Turn into` submenu inside the open drag-handle block action menu. - BlockMenuToggleTurnInto, - /// Dismiss the drag-handle block action menu. - CloseBlockMenu, - /// Execute a command from the drag-handle block action menu. - BlockMenuAction { - block_id: String, - action: BlockMenuAction, - }, - /// Open the `@` linked-document picker with an initial query. - OpenLinkedDocMenu { - block_id: String, - query: String, - }, - /// Update the open `@` linked-document picker query. - SetLinkedDocQuery(String), - /// Hover a row in the open `@` linked-document picker (`0..items.len()` or `items.len()` for Create). - LinkedDocHover(usize), - /// Select a row in the open `@` linked-document picker (`0..items.len()` inserts existing doc chip; - /// `items.len()` creates a new linked doc and inserts its chip). - LinkedDocSelect(usize), - /// Scroll the `@` linked-document picker list vertically by `delta` px. - LinkedDocScroll(f32), - /// Expand the `@` linked-document picker to load/show all remaining documents. - LinkedDocExpandMore, - /// Dismiss the `@` linked-document picker. - CloseLinkedDocMenu, - /// Dismiss the lightweight link / `@reference` capsule. - CloseLinkPopup, - /// Execute an action from the lightweight link / `@reference` capsule. - LinkPopupAction(LinkPopupAction), - /// Create a linked document (or convert a line to a linked doc) through the host directory - /// and insert its `LinkedPage` inline reference chip into `block_id` as one undo step. - CreateLinkedDoc { - block_id: String, - title: String, - mode: crate::directory::EditorDocMode, - intent_id: Option, - }, - /// Open the equation editor for a block or inline latex target. - OpenEquationEditor { - target: EquationTarget, - initial: String, - }, - /// Commit the equation editor's current LaTeX string. - EquationApply, - /// Click inside the multiline equation editor at window coordinates `(x, y)`. - EquationClick { - x: f32, - y: f32, - shift: bool, - }, - /// Dismiss the equation editor without committing. - CloseEquationEditor, - /// Open the bookmark URL prompt anchored to `block_id`. - OpenBookmarkPrompt { - block_id: String, - }, - /// Open the caption editor anchored to `block_id`. - OpenCaptionPrompt { - block_id: String, - }, - /// Commit the bookmark URL or caption prompt (no-op if empty/invalid or unchanged). - BookmarkApply, - /// Dismiss the bookmark URL or caption prompt without mutating the document. - CloseBookmarkPrompt, - /// Select an `affine:image` block in Page mode. - SelectImageBlock(String), - /// Begin dragging an `affine:image` corner resize handle at window x `start_x`. - ImageResizeStart { - block_id: String, - side: ImageResizeSide, - start_x: f32, - }, - /// Execute a command from the floating `overlay.image_toolbar`. - ImageToolbarAction { - block_id: String, - action: ImageToolbarAction, - }, - /// Insert a decoded image blob chosen from the host file picker as an `affine:image` block. - InsertImageBytes { - bytes: Vec, - caption: String, - }, - /// Insert an arbitrary attachment file blob under its content-addressed `sourceId`. - InsertAttachmentBytes { - name: String, - mime_type: String, - bytes: Vec, - }, - /// Scroll the horizontal mobile keyboard toolbar strip by `delta_x` px. - KeyboardToolbarScroll(f32), - /// Scroll the active mobile keyboard tool panel (`+`, `Turn into`, or `Highlight`) by `delta_y` px. - KeyboardToolbarPanelScroll(f32), - /// Trigger one action button on the mobile bottom keyboard toolbar. - KeyboardToolbar(KeyboardToolbarAction), - /// Focus an `affine:table` cell in place for live `Y.Text` CRDT editing. - FocusTableCell { - block_id: String, - row_id: String, - column_id: String, - screen_pos: Option<(f32, f32)>, - }, - /// Pointer press on an `affine:table` cell (supports click, double/triple click, Shift+click, drag). - TableCellMouseDown { - block_id: String, - row_id: String, - column_id: String, - screen_pos: (f32, f32), - click_count: usize, - shift: bool, - }, - AttachmentPdfPage { - block_id: String, - delta: i32, - }, - SelectAttachmentBlock(String), - AttachmentToolbarAction { - block_id: String, - action: AttachmentToolbarAction, - }, - PdfViewer(PdfViewerEvent), - /// Open the target document of an `affine:embed-linked-doc` or `affine:embed-synced-doc` card. - OpenEmbedDoc { - page_id: String, - }, - /// Switch to Edgeless mode and fit the camera to the `Frame` / `Group` referenced by an - /// `affine:surface-ref` card. - JumpToSurfaceRef { - reference: String, - }, - /// Touch long-press at window coordinates `(x, y)` to select the ICU word under the finger. - LongPressWord { - x: f32, - y: f32, - }, - /// Open the desktop right-click context menu at window coordinates `(x, y)`. - OpenContextMenu { - x: f32, - y: f32, - }, - /// Dismiss the desktop right-click context menu. - CloseContextMenu, - /// Execute a command from the desktop right-click context menu. - ContextMenuAction(ContextMenuAction), -} - -/// What the view has to do after an [`OverlayEvent`] or a key. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct OverlayEffects { - /// Edits to carry out, in order. - pub edits: Vec, - /// Text to put on the clipboard. - pub clipboard: Option, - /// Start a [`COPIED_MS`] timer on the scheduler clock and report its end with - /// [`Overlays::copied_expired`] and this generation. - pub copied_timer: Option, - /// Read the clipboard into the link field. - pub paste: bool, - /// Desktop context-menu command triggered via keyboard (`Enter`). - pub context_menu_action: Option, - /// Drag-handle block menu command triggered via keyboard (`Enter`) or click. - pub block_menu_action: Option<(String, BlockMenuAction)>, - /// Block id to select into `block_selection` when the drag-handle block menu opens. - pub select_block: Option, - /// Replace `block_selection` live during Page-margin marquee selection (`PageDraggingArea`). - pub set_block_selection: Option>, - /// Local-only collapse toggle for non-heading `Paragraph`/`Quote` blocks (zero CRDT write). - pub toggle_local_collapse: Option, - /// External embed insertion requested by the single-line URL prompt: - /// `(block_id, kind, url, remove_empty_block)`. - pub embed_insert: Option<(String, SlashEmbedKind, String, bool)>, - /// Schedule a one-shot 800 ms wakeup so the Slash preview card opens without extra pointer moves. - pub slash_preview_timer: bool, - pub redraw: bool, - /// Whether a key was consumed. - pub handled: bool, -} +pub use events::{DocEdit, OverlayEffects, OverlayEvent}; /// Everything the overlays read about the page for one event or frame. #[derive(Clone, Copy)] @@ -691,6 +311,11 @@ impl OverlayScene<'_> { #[derive(Default)] pub struct Overlays { pub(super) hovered: Option, + /// Wide Table/Database block whose body is under the pointer (used to reveal its horizontal + /// scrollbar even when `hovered` hides the outer Page drag handle inside a Database body). + pub(super) hscroll_hovered: Option, + /// Active thumb drag session for a block's horizontal scrollbar. + pub(super) hscroll_drag: Option, /// Whether the pointer is on the hovered block's drag handle itself. pub(super) handle_hot: bool, /// Smooth 250 ms grabber hover-stretch progress (`0.0` rest -> `1.0` stretched). @@ -718,6 +343,7 @@ pub struct Overlays { pub(super) equation: Option, pub(super) bookmark: Option, pub(super) code_lang_picker: Option, + pub(super) recent_code_languages: Vec, pub(super) image_lightbox: Option, pub(super) image_toolbar_rect: Option, pub(super) attachment_toolbar_rect: Option, diff --git a/blocksuite/crates/editor/src/overlays/paint_linked_doc.rs b/blocksuite/crates/editor/src/overlays/paint_linked_doc.rs index b12163adb5..f79b7558c4 100644 --- a/blocksuite/crates/editor/src/overlays/paint_linked_doc.rs +++ b/blocksuite/crates/editor/src/overlays/paint_linked_doc.rs @@ -444,7 +444,7 @@ impl Overlays { menu.scroll = sel_y + sel_h - list_height; } } - menu.scroll = menu.scroll.clamp(0.0, max_scroll).round(); + menu.scroll = menu.scroll.clamp(0.0, max_scroll); let scroll = menu.scroll; let row_width = if max_scroll > 0.0 { (list_width - SLASH_SCROLL_GUTTER).max(0.0) @@ -472,8 +472,8 @@ impl Overlays { if interactive { panel = panel .occlude() - .on_scroll(emit(cx, |event: &ScrollEvent| { - OverlayEvent::LinkedDocScroll(f32::from(event.delta.pixel_delta(px(20.0)).y)) + .on_scroll(emit(cx, move |event: &ScrollEvent| { + OverlayEvent::LinkedDocScroll(crate::scroll::wheel_delta(event, viewport.h).1) })) .on_mouse_down_out(emit(cx, |_: &MouseDownEvent| { OverlayEvent::CloseLinkedDocMenu diff --git a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs index a6043ed617..2eaf19f31a 100644 --- a/blocksuite/crates/editor/src/overlays/paint_page/mod.rs +++ b/blocksuite/crates/editor/src/overlays/paint_page/mod.rs @@ -206,6 +206,34 @@ impl Overlays { cx, &mut elements, ), + FlowKind::Database => { + let dragging = self + .hscroll_drag + .as_ref() + .is_some_and(|d| d.block_id == block.block_id); + if (hovered + || self.hscroll_hovered.as_deref() == Some(block.block_id.as_str()) + || dragging) + && !scene.is_touch + && scene.form_factor == crate::block_flow::FormFactor::Desktop + && let Some((bar_world, code)) = + scrollbar::block_hscrollbar_world_rect(block) + && viewport.intersects(&bar_world) + && let Some(el) = scrollbar::build_block_hscrollbar( + &block.block_id, + &block.snapshot_id, + viewport.to_local(&bar_world), + self.code_scroll_x_for(&block.block_id, code), + code.max_x, + dragging, + window.scale_factor(), + palette, + cx, + ) + { + elements.push(el); + } + } FlowKind::Image => self.push_image_controls( block, rect, @@ -274,6 +302,32 @@ impl Overlays { &mut elements, ), FlowKind::Table => { + let dragging = self + .hscroll_drag + .as_ref() + .is_some_and(|d| d.block_id == block.block_id); + if (hovered + || self.hscroll_hovered.as_deref() == Some(block.block_id.as_str()) + || dragging) + && !scene.is_touch + && scene.form_factor == crate::block_flow::FormFactor::Desktop + && let Some((bar_world, code)) = + scrollbar::block_hscrollbar_world_rect(block) + && viewport.intersects(&bar_world) + && let Some(el) = scrollbar::build_block_hscrollbar( + &block.block_id, + &block.snapshot_id, + viewport.to_local(&bar_world), + self.code_scroll_x_for(&block.block_id, code), + code.max_x, + dragging, + window.scale_factor(), + palette, + cx, + ) + { + elements.push(el); + } let table_cells = scene.snapshot.block(&block.block_id).and_then(|n| match &n .content { diff --git a/blocksuite/crates/editor/src/overlays/paint_slash.rs b/blocksuite/crates/editor/src/overlays/paint_slash.rs index c248646772..f788ec0b15 100644 --- a/blocksuite/crates/editor/src/overlays/paint_slash.rs +++ b/blocksuite/crates/editor/src/overlays/paint_slash.rs @@ -139,7 +139,7 @@ impl Overlays { menu.scroll = y + row_height - list_height; } } - menu.scroll = menu.scroll.clamp(0.0, max_scroll).round(); + menu.scroll = menu.scroll.clamp(0.0, max_scroll); let scroll = menu.scroll; let selected = menu.selected; let submenu_open = menu.submenu_open && menu.query.trim().is_empty(); @@ -372,8 +372,8 @@ impl Overlays { if interactive { root = root .occlude() - .on_scroll(emit(cx, |event: &ScrollEvent| { - OverlayEvent::SlashScroll(f32::from(event.delta.pixel_delta(px(20.0)).y)) + .on_scroll(emit(cx, move |event: &ScrollEvent| { + OverlayEvent::SlashScroll(crate::scroll::wheel_delta(event, viewport.h).1) })) .on_mouse_down_out(cx.listener(move |this, ev: &MouseDownEvent, window, cx| { let (mx, my) = (f32::from(ev.position.x), f32::from(ev.position.y)); diff --git a/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs b/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs index 1b3d3a5699..abe0510471 100644 --- a/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs +++ b/blocksuite/crates/editor/src/overlays/paint_toolbar/mod.rs @@ -158,7 +158,7 @@ impl Overlays { .snapshot("overlay.format_toolbar", Some("root.canvas")) .snapshot_focused(interactive); if interactive { - root = root.occlude(); + root = root.block_mouse_except_scroll(); } if !link_only { diff --git a/blocksuite/crates/editor/src/overlays/scrollbar.rs b/blocksuite/crates/editor/src/overlays/scrollbar.rs index e30a16e10e..ac22304070 100644 --- a/blocksuite/crates/editor/src/overlays/scrollbar.rs +++ b/blocksuite/crates/editor/src/overlays/scrollbar.rs @@ -101,9 +101,7 @@ impl ScrollbarMetrics { return 0.0; } let top = (local_y - grab_offset_y - self.track_y).clamp(0.0, self.travel); - ((top / self.travel) * max_scroll) - .clamp(0.0, max_scroll) - .round() + ((top / self.travel) * max_scroll).clamp(0.0, max_scroll) } /// Compute the new `scroll_y` when clicking the track outside the thumb (page jump). @@ -120,7 +118,7 @@ impl ScrollbarMetrics { } else { current_scroll_y + step }; - next.clamp(0.0, max_scroll).round() + next.clamp(0.0, max_scroll) } /// Whether `local_y` (relative to the page viewport top) hits the thumb. @@ -191,30 +189,255 @@ pub fn build_page_scrollbar( .into_any_element() } +/// Active thumb drag state for a block's horizontal scrollbar (`affine:table`, `affine:database`, +/// or unwrapped `affine:code`). +#[derive(Clone, Debug, PartialEq)] +pub struct BlockHScrollDrag { + pub block_id: String, + pub start_pointer_x: f32, + pub start_scroll_x: f32, + pub track_travel: f32, + pub max_scroll_x: f32, +} + +/// Interactive hit-target height of a block's hover-revealed horizontal scrollbar gutter (`>= 24px`). +pub const HSCROLLBAR_HIT_HEIGHT: f32 = 24.0; +/// Idle visual height of a block's horizontal scrollbar thumb (expands to `8px` on hover). +pub const HSCROLLBAR_IDLE_HEIGHT: f32 = 4.0; +/// Hovered visual height of a block's horizontal scrollbar thumb. +pub const HSCROLLBAR_HOVER_HEIGHT: f32 = 8.0; +/// Minimum horizontal scrollbar thumb width in logical pixels. +pub const HSCROLLBAR_MIN_THUMB: f32 = 32.0; + +/// Compute the world-space `24px` interactive hitbox rect and scroll metrics for a wide +/// `affine:table` or `affine:database` block's bottom horizontal scrollbar. +pub(super) fn block_hscrollbar_world_rect( + block: &crate::block_flow::FlowBlock, +) -> Option<(crate::block_flow::FlowRect, crate::block_flow::CodeScroll)> { + if !matches!( + block.body.kind, + crate::block_flow::FlowKind::Table | crate::block_flow::FlowKind::Database + ) { + return None; + } + let code = block.body.code_scroll?; + if code.max_x <= 0.0 { + return None; + } + let rect = block.rect(); + Some(( + crate::block_flow::FlowRect::new( + rect.x + code.area.x, + rect.y + code.area.bottom(), + code.area.w, + HSCROLLBAR_HIT_HEIGHT, + ), + code, + )) +} + +/// Build a hover-revealed `4 -> 8px` horizontal scrollbar along the bottom edge of a wide +/// `affine:table` or `affine:database` (Table / Kanban) block. +#[allow(clippy::too_many_arguments)] +pub(super) fn build_block_hscrollbar( + block_id: &str, + snapshot_id: &str, + local_rect: crate::block_flow::FlowRect, + scroll_x: f32, + max_x: f32, + dragging: bool, + scale_factor: f32, + palette: &Palette, + cx: &mut Context, +) -> Option { + if max_x <= 0.0 || local_rect.w <= 16.0 { + return None; + } + let track_inset = 4.0_f32; + let track_w = (local_rect.w - 2.0 * track_inset).max(8.0); + let content_w = local_rect.w + max_x; + let min_thumb = HSCROLLBAR_MIN_THUMB.min(track_w); + let thumb_w = ((local_rect.w / content_w) * track_w).clamp(min_thumb, track_w); + let travel = (track_w - thumb_w).max(0.0); + 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 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.to_string(); + 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 }; + + Some( + div() + .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( + MouseButton::Left, + cx.listener(move |view: &mut V, ev: &MouseDownEvent, w, cx| { + cx.stop_propagation(); + let pointer_x = f32::from(ev.position.x); + let click_x = pointer_x - bar_left - track_inset; + let on_thumb = click_x >= thumb_pos && click_x <= thumb_pos + thumb_w; + let start_scroll_x = if on_thumb { + scroll_x.clamp(0.0, max_x) + } else if travel > 0.0 { + (((click_x - thumb_w * 0.5) / travel).clamp(0.0, 1.0)) * max_x + } else { + 0.0 + }; + view.dispatch_overlay( + super::OverlayEvent::StartBlockHScrollDrag { + block_id: bid.clone(), + pointer_x, + scroll_x: start_scroll_x, + track_travel: travel, + max_scroll_x: max_x, + }, + w, + cx, + ); + }), + ) + .snapshot( + ui::SharedString::from(format!("{snapshot_id}.hscrollbar")), + 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) + }), + ) + .into_any_element(), + ) +} + +/// Per-axis consumption outcome for horizontal block and docked-toolbar scroll routing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ScrollCodeOutcome { + /// Whether the horizontal delta was consumed by a code/table/database block or toolbar. + pub consumed_x: bool, + /// Whether the vertical delta was consumed by a contained overlay (e.g. docked keyboard panel). + pub consumed_y: bool, + /// Whether any visible scroll offset changed and requires a redraw. + pub changed: bool, +} + impl super::Overlays { - /// Set the horizontal scroll offset (clamped `>= 0.0`) of a code or database block directly. - pub fn set_code_scroll_x(&mut self, block_id: &str, scroll_x: f32) { - self.code_scroll - .insert(block_id.to_string(), scroll_x.max(0.0).round()); + /// Whether a horizontal block scrollbar thumb drag is currently active. + pub fn is_hscroll_dragging(&self) -> bool { + self.hscroll_drag.is_some() } - /// Scroll the unwrapped code block under a screen-space point sideways. Returns whether - /// the scroll belonged to a code block or docked keyboard toolbar (and must not scroll the page). - pub fn scroll_code( + /// Begin dragging a block's horizontal scrollbar thumb (and apply any immediate track-click jump). + pub(super) fn start_hscroll_drag(&mut self, drag: BlockHScrollDrag) { + self.set_code_scroll_x(&drag.block_id, drag.start_scroll_x); + self.hscroll_hovered = Some(drag.block_id.clone()); + self.hscroll_drag = Some(drag); + } + + /// Update an active horizontal block scrollbar thumb drag on pointer move. + /// Returns `Some(redraw)` when a drag was active (consuming the pointer move). + pub(super) fn handle_hscroll_pointer_move(&mut self, x: f32, pressed: bool) -> Option { + if !pressed { + return self.hscroll_drag.take().map(|_| true); + } + let drag = self.hscroll_drag.as_ref()?; + let next = if drag.track_travel > 0.0 { + let dx = x - drag.start_pointer_x; + (drag.start_scroll_x + (dx / drag.track_travel) * drag.max_scroll_x) + .clamp(0.0, drag.max_scroll_x) + } else { + 0.0 + }; + let block_id = drag.block_id.clone(); + self.set_code_scroll_x(&block_id, next); + self.hscroll_hovered = Some(block_id); + Some(true) + } + + /// Finish any active horizontal block scrollbar thumb drag on pointer release. + pub(super) fn end_hscroll_drag(&mut self) -> bool { + self.hscroll_drag.take().is_some() + } + + /// Resolve which wide block should keep its horizontal scrollbar revealed at `(world_x, world_y)`, + /// covering both the block body and its full `24px` bottom scrollbar hitbox. + pub(super) fn resolve_hscroll_hovered( + &self, + scene: &super::OverlayScene<'_>, + world_x: f32, + world_y: f32, + ) -> Option { + if let Some(drag) = self.hscroll_drag.as_ref() { + return Some(drag.block_id.clone()); + } + scene + .layout + .blocks + .iter() + .find(|b| { + block_hscrollbar_world_rect(b).is_some_and(|(bar_world, _)| { + b.rect().contains(world_x, world_y) || bar_world.contains(world_x, world_y) + }) + }) + .map(|b| b.block_id.clone()) + } + + /// Set the horizontal scroll offset (clamped `>= 0.0`, unrounded subpixel `f32`) of a code, + /// table, or database block directly. + pub fn set_code_scroll_x(&mut self, block_id: &str, scroll_x: f32) { + self.code_scroll + .insert(block_id.to_string(), scroll_x.max(0.0)); + } + + /// Split-axis scroll router for docked keyboard toolbars and horizontally scrollable blocks + /// (code, table, database). + /// + /// Horizontal deltas route to the block under `(x, y)` using subpixel [`crate::scroll::ScrollAxis`] + /// without consuming `delta_y`, so diagonal gestures and edge overscroll still chain `delta_y` + /// to the page. + pub fn scroll_code_split( &mut self, scene: &super::OverlayScene<'_>, x: f32, y: f32, delta_x: f32, delta_y: f32, - ) -> bool { + ) -> ScrollCodeOutcome { if self.scroll_keyboard_toolbar_at(scene, x, y, delta_x, delta_y) || self.scroll_keyboard_tool_panel(scene, x, y, delta_y) { - return true; + return ScrollCodeOutcome { + consumed_x: true, + consumed_y: true, + changed: true, + }; } - if delta_x == 0.0 || delta_x.abs() < delta_y.abs() { - return false; + if delta_x == 0.0 { + return ScrollCodeOutcome::default(); } let (world_x, world_y) = scene.screen_to_world(x, y); for block in &scene.layout.blocks { @@ -225,11 +448,33 @@ impl super::Overlays { continue; } let current = self.code_scroll_x_for(&block.block_id, code); - let next = (current - delta_x).clamp(0.0, code.max_x).round(); - self.code_scroll.insert(block.block_id.clone(), next); - return true; + let mut axis = crate::scroll::ScrollAxis::new(current, code.max_x); + let (consumed, _) = axis.scroll_by(delta_x); + if consumed != 0.0 { + self.code_scroll.insert(block.block_id.clone(), axis.offset); + return ScrollCodeOutcome { + consumed_x: true, + consumed_y: false, + changed: true, + }; + } + return ScrollCodeOutcome::default(); } - false + ScrollCodeOutcome::default() + } + + /// Scroll the unwrapped code, table, or database block under a screen-space point sideways. + /// Returns whether any axis was consumed. + pub fn scroll_code( + &mut self, + scene: &super::OverlayScene<'_>, + x: f32, + y: f32, + delta_x: f32, + delta_y: f32, + ) -> bool { + let out = self.scroll_code_split(scene, x, y, delta_x, delta_y); + out.consumed_x || out.consumed_y } } diff --git a/blocksuite/crates/editor/src/overlays/state.rs b/blocksuite/crates/editor/src/overlays/state.rs index 4ef42a8dab..b2cfc99909 100644 --- a/blocksuite/crates/editor/src/overlays/state.rs +++ b/blocksuite/crates/editor/src/overlays/state.rs @@ -126,6 +126,12 @@ impl Overlays { let Some(scene) = scene else { return effects; }; + if let Some(redraw) = self.handle_hscroll_pointer_move(x, pressed) { + effects.redraw |= redraw; + if pressed { + return effects; + } + } // The button was released where no release event reached the page. if !pressed && (self.drag.take().is_some() || self.marquee.take().is_some()) { self.drop_indicator_motion = None; @@ -191,6 +197,11 @@ impl Overlays { hover_block(scene, x, y) }; let (world_x, world_y) = scene.screen_to_world(x, y); + let hscroll_hovered = if shielded { + self.hscroll_hovered.clone() + } else { + self.resolve_hscroll_hovered(scene, world_x, world_y) + }; let handle_hot = !shielded && !scene.page_readonly && hovered @@ -198,14 +209,21 @@ impl Overlays { .and_then(|block_id| scene.layout.block(block_id)) .and_then(|block| paint_page::effective_drag_handle_rect(scene, block)) .is_some_and(|handle| handle.contains(world_x, world_y)); - if hovered != self.hovered || handle_hot != self.handle_hot { + if hovered != self.hovered + || hscroll_hovered != self.hscroll_hovered + || handle_hot != self.handle_hot + { self.hovered = hovered; + self.hscroll_hovered = hscroll_hovered; self.set_handle_hot(handle_hot, now_ms); effects.redraw = true; } } } OverlayEvent::PointerUp => { + if self.end_hscroll_drag() { + effects.redraw = true; + } if self.marquee.take().is_some() { effects.redraw = true; } @@ -441,6 +459,9 @@ impl Overlays { OverlayEvent::SetCodeLanguage { .. } | OverlayEvent::OpenCodeLangPicker(_) | OverlayEvent::CodeLangPickerScroll(_) + | OverlayEvent::CodeLangPickerHover(_) + | OverlayEvent::SetBlockScrollX { .. } + | OverlayEvent::StartBlockHScrollDrag { .. } | OverlayEvent::CloseCodeLangPicker | OverlayEvent::ToggleCodeLineNumber(_) | OverlayEvent::ToggleCodeCollapsed(_) diff --git a/blocksuite/crates/editor/src/scroll.rs b/blocksuite/crates/editor/src/scroll.rs new file mode 100644 index 0000000000..95036e9e05 --- /dev/null +++ b/blocksuite/crates/editor/src/scroll.rs @@ -0,0 +1,331 @@ +//! Unified subpixel scrolling core for Page, code/table/database horizontal containers, +//! popover lists, docked keyboard toolbars, record sheets, and database view tabs. +//! +//! All stored offsets remain unrounded `f32` logical pixels so high-frequency Magic Trackpad +//! and touch subpixel deltas (`0.2–0.5 px`) accumulate losslessly. Snapping to the device +//! pixel grid happens strictly at paint time via [`snap_device_pixel`]. + +use ui::{ScrollEvent, ScrollSource, TouchPhase, px}; + +/// Shared logical pixels per discrete wheel line across the editor and playground. +pub const SCROLL_LINE_PX: f32 = 20.0; + +/// Idle timeout (scheduler milliseconds) after which [`AxisLatch`] resets its locked axis. +pub const AXIS_LATCH_IDLE_MS: f64 = 160.0; + +/// Horizontal-to-vertical ratio above which a gesture locks to the horizontal axis. +pub const AXIS_LATCH_RATIO: f32 = 1.2; + +/// Minimum accumulated movement (logical px) before locking a precise gesture to one axis. +const AXIS_LATCH_THRESHOLD_PX: f32 = 4.0; + +/// Convert a [`ScrollEvent`] delta to logical `(dx, dy)` pixels using the shared [`SCROLL_LINE_PX`]. +/// +/// `viewport_height` is accepted for page-mode scaling consistency. +pub fn wheel_delta(event: &ScrollEvent, _viewport_height: f32) -> (f32, f32) { + let d = event.delta.pixel_delta(px(SCROLL_LINE_PX)); + (f32::from(d.x), f32::from(d.y)) +} + +/// Select the dominant-axis delta (`dx` when `|dx| >= |dy|`, otherwise `dy`) so minor +/// cross-axis trackpad noise never overrides an intentional scroll gesture. +#[inline] +pub fn dominant_axis_delta(dx: f32, dy: f32) -> f32 { + if dx.abs() >= dy.abs() { dx } else { dy } +} + +/// Snap a logical coordinate to the nearest physical device pixel at paint time. +#[inline] +pub fn snap_device_pixel(value: f32, scale_factor: f32) -> f32 { + let scale = scale_factor.max(1.0); + (value * scale).round() / scale +} + +/// Subpixel 1D scroll axis (`offset` in `0.0..=max`). +/// +/// Follows the platform scroll convention where a positive delta moves content down/right +/// (decreasing `offset`) and a negative delta moves content up/left (increasing `offset`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ScrollAxis { + pub offset: f32, + pub max: f32, +} + +impl ScrollAxis { + /// Create a clamped scroll axis with `max >= 0.0` and `offset` in `0.0..=max`. + #[inline] + pub fn new(offset: f32, max: f32) -> Self { + let max = max.max(0.0); + Self { + offset: offset.clamp(0.0, max), + max, + } + } + + /// Update the maximum scroll bound and clamp the current offset. + #[inline] + pub fn set_max(&mut self, max: f32) { + self.max = max.max(0.0); + self.offset = self.offset.clamp(0.0, self.max); + } + + /// Apply a signed scroll `delta`, returning `(consumed_delta, remaining_delta)`. + /// + /// Never rounds `self.offset` and never discards subpixel deltas. + #[inline] + pub fn scroll_by(&mut self, delta: f32) -> (f32, f32) { + if delta == 0.0 || !delta.is_finite() { + return (0.0, 0.0); + } + let prev = self.offset; + let next = (prev - delta).clamp(0.0, self.max); + self.offset = next; + let consumed = prev - next; + (consumed, delta - consumed) + } + + /// Apply a signed scroll `delta` and return whether `offset` changed. + #[inline] + pub fn apply(&mut self, delta: f32) -> bool { + let prev = self.offset; + let _ = self.scroll_by(delta); + self.offset != prev + } + + /// Snap the current offset to the device pixel grid for painting. + #[inline] + pub fn snapped(&self, scale_factor: f32) -> f32 { + snap_device_pixel(self.offset, scale_factor) + } +} + +/// Locked dominant axis for a precise touch or trackpad scroll gesture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ScrollAxisLock { + Horizontal, + Vertical, +} + +/// Stateful axis latch shared by `ScrollSource::Touch` and precise trackpad (`delta.precise()`) +/// scroll streams. Discrete wheel notches (`ScrollDelta::Lines`) bypass latching. +/// +/// Driven strictly by scheduler time (`now_ms`), never by the system wall clock. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AxisLatch { + locked: Option, + from_touch: bool, + last_event_ms: Option, + accum_x: f32, + accum_y: f32, +} + +impl AxisLatch { + /// Reset any active axis lock. + pub fn reset(&mut self) { + self.locked = None; + self.from_touch = false; + self.last_event_ms = None; + self.accum_x = 0.0; + self.accum_y = 0.0; + } + + /// Reset the axis lock only when it was established by a touch gesture, leaving active + /// desktop trackpad latches intact across render frames. + pub fn reset_touch(&mut self) { + if self.from_touch { + self.reset(); + } + } + + /// Currently locked axis, if any. + pub fn locked(&self) -> Option { + self.locked + } + + /// Filter `(dx, dy)` through the axis latch for `event` at scheduler time `now_ms`. + /// + /// - Discrete wheel events (`!precise && source != Touch`) pass through unlatched. + /// - Touch gestures lock to one axis (`|dx| > 1.2 * |dy|` -> `Horizontal`, else `Vertical`) + /// once movement reaches `4 px`, resetting on `Started`/`Ended`/`Cancelled` or after + /// `160 ms` idle. + /// - Precise trackpad gestures (`delta.precise()`) lock when one axis dominates while the + /// orthogonal axis stays below threshold, preventing stray trackpad jitter from jerking + /// code blocks during vertical scrolls, while still allowing intentional diagonal scrolls + /// and resetting after `160 ms` idle. + pub fn filter(&mut self, event: &ScrollEvent, dx: f32, dy: f32, now_ms: f64) -> (f32, f32) { + let is_touch = event.source == ScrollSource::Touch; + let is_precise = is_touch || event.delta.precise(); + if !is_precise { + return (dx, dy); + } + + if self + .last_event_ms + .is_some_and(|prev| now_ms - prev > AXIS_LATCH_IDLE_MS) + || (self.locked.is_some() && self.from_touch != is_touch) + { + self.locked = None; + self.from_touch = false; + self.accum_x = 0.0; + self.accum_y = 0.0; + } + self.from_touch = is_touch; + + match event.touch_phase { + TouchPhase::Started => { + self.locked = None; + self.accum_x = 0.0; + self.accum_y = 0.0; + self.last_event_ms = Some(now_ms); + } + TouchPhase::Ended | TouchPhase::Cancelled => { + self.locked = None; + self.accum_x = 0.0; + self.accum_y = 0.0; + self.last_event_ms = None; + } + TouchPhase::Moved => { + self.last_event_ms = Some(now_ms); + } + } + + if self.locked.is_none() { + self.accum_x += dx.abs(); + self.accum_y += dy.abs(); + if is_touch { + if self.accum_x >= AXIS_LATCH_THRESHOLD_PX + || self.accum_y >= AXIS_LATCH_THRESHOLD_PX + { + self.locked = Some(if self.accum_x > self.accum_y * AXIS_LATCH_RATIO { + ScrollAxisLock::Horizontal + } else { + ScrollAxisLock::Vertical + }); + } + } else if self.accum_x >= AXIS_LATCH_THRESHOLD_PX + && self.accum_y < AXIS_LATCH_THRESHOLD_PX + && self.accum_x > self.accum_y * AXIS_LATCH_RATIO + { + self.locked = Some(ScrollAxisLock::Horizontal); + } else if self.accum_y >= AXIS_LATCH_THRESHOLD_PX + && self.accum_x < AXIS_LATCH_THRESHOLD_PX + && self.accum_x <= self.accum_y * AXIS_LATCH_RATIO + { + self.locked = Some(ScrollAxisLock::Vertical); + } + } + + if !is_touch { + const AXIS_LATCH_BREAK_PX: f32 = 16.0; + match self.locked { + Some(ScrollAxisLock::Horizontal) + if dy.abs() >= AXIS_LATCH_BREAK_PX + && dy.abs() > dx.abs() * AXIS_LATCH_RATIO => + { + self.locked = Some(ScrollAxisLock::Vertical); + } + Some(ScrollAxisLock::Vertical) + if dx.abs() >= AXIS_LATCH_BREAK_PX + && dx.abs() > dy.abs() * AXIS_LATCH_RATIO => + { + self.locked = Some(ScrollAxisLock::Horizontal); + } + _ => {} + } + } + + match self.locked { + Some(ScrollAxisLock::Horizontal) => (dx, 0.0), + Some(ScrollAxisLock::Vertical) => (0.0, dy), + None => (dx, dy), + } + } +} + +#[cfg(test)] +mod tests { + use ui::{Modifiers, Point, ScrollDelta, ScrollEvent, ScrollSource, TouchPhase, point, px}; + + use super::*; + + fn precise_event(dx: f32, dy: f32, source: ScrollSource, phase: TouchPhase) -> ScrollEvent { + ScrollEvent { + position: Point::default(), + delta: ScrollDelta::Pixels(point(px(dx), px(dy))), + modifiers: Modifiers::default(), + touch_phase: phase, + source, + } + } + + #[test] + fn subpixel_scroll_axis_accumulates_without_rounding_loss() { + let mut axis = ScrollAxis::new(0.0, 200.0); + for _ in 0..20 { + let (consumed, rem) = axis.scroll_by(-0.25); + assert!((consumed + 0.25).abs() < 1e-6); + assert!(rem.abs() < 1e-6); + } + assert!((axis.offset - 5.0).abs() < 1e-5); + assert_eq!(axis.snapped(2.0), 5.0); + + // Mixed subpixel sequence sums exactly. + let mut sum_axis = ScrollAxis::new(0.0, 500.0); + let deltas = [-0.3_f32, -0.6, -2.0, -0.25, -0.35]; + for d in deltas { + assert!(sum_axis.apply(d)); + } + assert!((sum_axis.offset - 3.5).abs() < 1e-5); + assert_eq!(snap_device_pixel(0.3, 2.0), 0.5); + assert_eq!(snap_device_pixel(0.3, 1.0), 0.0); + } + + #[test] + fn scroll_axis_reports_remaining_delta_at_edges() { + let mut axis = ScrollAxis::new(98.0, 100.0); + let (consumed, rem) = axis.scroll_by(-5.0); + assert!((consumed + 2.0).abs() < 1e-6); + assert!((rem + 3.0).abs() < 1e-6); + assert_eq!(axis.offset, 100.0); + + let (consumed2, rem2) = axis.scroll_by(-4.0); + assert_eq!(consumed2, 0.0); + assert_eq!(rem2, -4.0); + } + + #[test] + fn axis_latch_locks_precise_trackpad_and_resets_after_idle() { + let mut latch = AxisLatch::default(); + // Mostly vertical trackpad gesture locks Vertical. + let ev1 = precise_event(-0.4, -6.0, ScrollSource::Pointer, TouchPhase::Moved); + assert_eq!(latch.filter(&ev1, -0.4, -6.0, 100.0), (0.0, -6.0)); + assert_eq!(latch.locked(), Some(ScrollAxisLock::Vertical)); + + // Noisy cross-axis event during same gesture is suppressed on X. + let ev2 = precise_event(-2.0, -1.0, ScrollSource::Pointer, TouchPhase::Moved); + assert_eq!(latch.filter(&ev2, -2.0, -1.0, 140.0), (0.0, -1.0)); + + // After > 160 ms scheduler idle, latch resets and accepts horizontal gesture. + let ev3 = precise_event(-8.0, -0.5, ScrollSource::Pointer, TouchPhase::Moved); + assert_eq!(latch.filter(&ev3, -8.0, -0.5, 320.0), (-8.0, 0.0)); + assert_eq!(latch.locked(), Some(ScrollAxisLock::Horizontal)); + + // Intentional diagonal gesture after idle keeps both axes unlocked. + let ev4 = precise_event(-8.0, -6.0, ScrollSource::Pointer, TouchPhase::Moved); + assert_eq!(latch.filter(&ev4, -8.0, -6.0, 600.0), (-8.0, -6.0)); + assert_eq!(latch.locked(), None); + } + + #[test] + fn dominant_axis_picks_larger_magnitude() { + let cases = [ + (0.1_f32, -8.0_f32, -8.0_f32), + (-6.0, -2.0, -6.0), + (0.0, 3.5, 3.5), + (-4.0, 4.0, -4.0), + ]; + for (dx, dy, expected) in cases { + assert_eq!(dominant_axis_delta(dx, dy), expected); + } + } +} diff --git a/blocksuite/crates/playground/src/bin/bs_harness/main.rs b/blocksuite/crates/playground/src/bin/bs_harness/main.rs index 80112d2295..b6a7dcdfb0 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/main.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/main.rs @@ -13,6 +13,7 @@ mod probes; mod render; mod s3_evidence; mod s3_evidence_fixtures; +mod scroll_picker_evidence; mod states; use bench::run_bench; @@ -547,6 +548,14 @@ fn main() -> Result<()> { let mode = args.next().unwrap_or_else(|| "after".to_string()); pdf_parity_evidence::render_pdf_parity_evidence(&out_dir, &mode) } + "render-scroll-picker-evidence" => { + let out_dir = PathBuf::from( + args.next() + .context("render-scroll-picker-evidence requires an output directory")?, + ); + let prefix = args.next().unwrap_or_else(|| "after".to_string()); + scroll_picker_evidence::render_scroll_picker_evidence(&out_dir, &prefix) + } "record-edgeless-demo" => record_edgeless_demo( args.next() .context("record-edgeless-demo requires an output directory")? diff --git a/blocksuite/crates/playground/src/bin/bs_harness/scroll_picker_evidence.rs b/blocksuite/crates/playground/src/bin/bs_harness/scroll_picker_evidence.rs new file mode 100644 index 0000000000..6974f64693 --- /dev/null +++ b/blocksuite/crates/playground/src/bin/bs_harness/scroll_picker_evidence.rs @@ -0,0 +1,465 @@ +//! Offscreen PNG evidence renderer for subpixel scrolling, wide Table/Kanban horizontal +//! scrollbars, Database Select 400 px scrollable picker, and `CodeLangPicker` parity. + +use std::{collections::BTreeMap, path::Path}; + +use anyhow::Result; +use blocksuite_playground_doc::schema::{ + BlockSpec, DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec, ParagraphType, +}; +use playground::{ + HOME_PAGE_ID, PlaygroundOptions, PlaygroundTheme, database::ActiveCellEditor, + overlays::OverlayEvent, room_client::DocState, +}; +use serde_json::json; + +use super::{ + s3_evidence_fixtures::{new_doc_state, save_session_png}, + start_headless_session, +}; + +fn build_code_lang_doc() -> Result<(DocState, String)> { + let mut state = new_doc_state("Code Language Picker Showcase")?; + let code_id = "b-code-lang".to_string(); + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.add_block( + "b-intro", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Select a syntax language for the code block below.".into(), + }, + Some("p-note"), + None, + 10, + )?; + page.add_block( + &code_id, + BlockSpec::Code { + text: "fn accumulate(deltas: &[f32]) -> f32 {\n deltas.iter().copied().sum()\n}" + .into(), + language: Some("rust".into()), + caption: String::new(), + }, + Some("p-note"), + None, + 11, + )?; + } + Ok((state, code_id)) +} + +fn build_wide_db_and_select_doc() -> Result<(DocState, String)> { + let mut state = new_doc_state("Wide Table & Select Scroll Showcase")?; + let db_id = "db-scroll-showcase".to_string(); + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + let options: Vec = (1..=26) + .map(|i| { + let colors = [ + "var(--affine-tag-blue)", + "var(--affine-tag-green)", + "var(--affine-tag-orange)", + "var(--affine-tag-purple)", + "var(--affine-tag-red)", + "var(--affine-tag-teal)", + ]; + json!({ + "id": format!("opt-{i:02}"), + "value": format!("Category Option {i:02}"), + "color": colors[(i - 1) % colors.len()], + }) + }) + .collect(); + let mut cells = BTreeMap::new(); + for r in 1..=3 { + cells.insert( + format!("row-{r}"), + BTreeMap::from([ + ( + "col-cat".into(), + DatabaseCellSpec::Text(format!("opt-0{r}")), + ), + ("col-a".into(), DatabaseCellSpec::Number((r * 100) as f64)), + ("col-b".into(), DatabaseCellSpec::Text(format!("Owner {r}"))), + ( + "col-c".into(), + DatabaseCellSpec::Text(format!("Region {r}")), + ), + ( + "col-d".into(), + DatabaseCellSpec::Text(format!("Service {r}")), + ), + ( + "col-e".into(), + DatabaseCellSpec::Text(format!("Pipeline {r}")), + ), + ]), + ); + } + let table_raw = json!({ + "columns": [ + { "id": "title", "width": 200 }, + { "id": "col-cat", "width": 160 }, + { "id": "col-a", "width": 160 }, + { "id": "col-b", "width": 180 }, + { "id": "col-c", "width": 180 }, + { "id": "col-d", "width": 180 }, + { "id": "col-e", "width": 180 } + ] + }); + page.add_block( + &db_id, + BlockSpec::Database(DatabaseSpec { + title: "Release Matrix".into(), + columns: vec![ + DatabaseColumnSpec { + id: "title".into(), + name: "Task".into(), + column_type: "title".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "col-cat".into(), + name: "Category".into(), + column_type: "select".into(), + data: json!({ "options": options }), + }, + DatabaseColumnSpec { + id: "col-a".into(), + name: "Metric".into(), + column_type: "number".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "col-b".into(), + name: "Owner".into(), + column_type: "rich-text".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "col-c".into(), + name: "Region".into(), + column_type: "rich-text".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "col-d".into(), + name: "Service".into(), + column_type: "rich-text".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "col-e".into(), + name: "Pipeline".into(), + column_type: "rich-text".into(), + data: json!({}), + }, + ], + views: vec![DatabaseViewSpec { + id: "v-table".into(), + name: "Table".into(), + mode: "table".into(), + raw: table_raw, + }], + cells, + }), + Some("p-note"), + None, + 10, + )?; + for (idx, title) in ["Scroll kernel", "Language picker", "Table scrollbar"] + .into_iter() + .enumerate() + { + page.add_block( + &format!("row-{}", idx + 1), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: title.into(), + }, + Some(&db_id), + None, + 20 + idx as u64, + )?; + } + } + Ok((state, db_id)) +} + +pub(super) fn render_scroll_picker_evidence(out_dir: &Path, prefix: &str) -> Result<()> { + std::fs::create_dir_all(out_dir)?; + + // 1. CodeLangPicker Light & Dark (default open). + for (theme, suffix) in [ + (PlaygroundTheme::Light, "light"), + (PlaygroundTheme::Dark, "dark"), + ] { + let (doc, code_id) = build_code_lang_doc()?; + let session = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme, + ..Default::default() + }, + )?; + session.view(|v, cx| v.set_document(doc, cx))?; + session.frame()?; + session.overlay(OverlayEvent::OpenCodeLangPicker(code_id))?; + session.settle(200); + let name = format!("{prefix}-code-lang-picker-{suffix}.png"); + save_session_png(&session, &out_dir.join(&name), &name)?; + } + + // 2. CodeLangPicker Light with search query "ts". + { + let (doc, code_id) = build_code_lang_doc()?; + let session = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| v.set_document(doc, cx))?; + session.frame()?; + session.overlay(OverlayEvent::OpenCodeLangPicker(code_id))?; + session.settle(200); + session.type_text("ts")?; + session.settle(100); + let name = format!("{prefix}-code-lang-picker-search-ts-light.png"); + save_session_png(&session, &out_dir.join(&name), &name)?; + } + + // 3. Wide Database Table hovered & scrolled horizontally. + { + let (doc, _db_id) = build_wide_db_and_select_doc()?; + let session = start_headless_session( + 1000, + 720, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| v.set_document(doc, cx))?; + session.frame()?; + session + .headless_win + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(420.0), ui::px(260.0)), + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(-180.0), ui::px(0.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + session.overlay(OverlayEvent::PointerMoved { + x: 420.0, + y: 260.0, + pressed: false, + })?; + session.settle(120); + let name = format!("{prefix}-wide-table-scroll-light.png"); + save_session_png(&session, &out_dir.join(&name), &name)?; + } + + // 4. Database Select 26-option popover (tests 400 px cap + scrollbar). + { + let (doc, db_id) = build_wide_db_and_select_doc()?; + let session = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| { + v.set_document(doc, cx); + v.update_database_authoring( + &db_id, + |auth| { + auth.active_cell = Some(ActiveCellEditor { + row_id: "row-1".into(), + column_id: "col-cat".into(), + col_type: "select".into(), + draft: String::new(), + error: None, + select_filter: String::new(), + calendar_day_index: None, + }); + }, + cx, + ); + })?; + session.settle(120); + let name = format!("{prefix}-db-select-400px-light.png"); + save_session_png(&session, &out_dir.join(&name), &name)?; + } + + // 5. Wide Table hovered 24px hscrollbar & after 240px thumb drag. + { + let mut state = new_doc_state("Wide Table Scrollbar Evidence")?; + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + let row = |r: usize| -> Vec { + (0..16).map(|c| format!("Row {r} col {c} sample")).collect() + }; + page.add_block( + "t-wide", + BlockSpec::Table { + rows: vec![row(0), row(1), row(2)], + }, + Some("p-note"), + None, + 10, + )?; + } + let session = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| v.set_document(state, cx))?; + let f0 = session.frame()?; + if let Some(tb) = f0.elements.get("page.block.t-wide").map(|e| e.bounds) { + let (tx, ty) = (tb.x + tb.width * 0.5, tb.y + tb.height * 0.5); + session.overlay(OverlayEvent::PointerMoved { + x: tx, + y: ty, + pressed: false, + })?; + session.settle(120); + let f1 = session.frame()?; + let name = format!("{prefix}-wide-table-hscroll.png"); + save_session_png(&session, &out_dir.join(&name), &name)?; + + if let Some(bar) = f1 + .elements + .get("page.block.t-wide.hscrollbar") + .map(|e| e.bounds) + { + let (bx, by) = (bar.x + bar.width * 0.2, bar.y + 12.0); + session + .headless_win + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position: ui::point(ui::px(bx), ui::px(by)), + pressed_button: None, + modifiers: ui::Modifiers::default(), + })); + let _ = session.frame(); + session + .headless_win + .dispatch_input(ui::PlatformInput::MouseDown(ui::MouseDownEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(bx), ui::px(by)), + modifiers: ui::Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + let _ = session.frame(); + for step in 1..=6 { + session + .headless_win + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position: ui::point(ui::px(bx + 40.0 * step as f32), ui::px(by)), + pressed_button: Some(ui::MouseButton::Left), + modifiers: ui::Modifiers::default(), + })); + let _ = session.frame(); + } + session + .headless_win + .dispatch_input(ui::PlatformInput::MouseUp(ui::MouseUpEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(bx + 240.0), ui::px(by)), + modifiers: ui::Modifiers::default(), + click_count: 1, + })); + session.settle(120); + let name_drag = format!("{prefix}-wide-table-hscroll-dragged.png"); + save_session_png(&session, &out_dir.join(&name_drag), &name_drag)?; + } + } + } + + // 6. CodeLangPicker Plain Text pinned & checked, plus empty state "No matching language". + { + let mut state = new_doc_state("Plain Text Code Language Picker")?; + let code_id = "b-code-plain".to_string(); + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.add_block( + &code_id, + BlockSpec::Code { + text: "plain text sample line".into(), + language: None, + caption: String::new(), + }, + Some("p-note"), + None, + 10, + )?; + } + let session = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| v.set_document(state, cx))?; + session.frame()?; + session.overlay(OverlayEvent::OpenCodeLangPicker(code_id))?; + session.settle(200); + let name_plain = format!("{prefix}-lang-picker-plain-text.png"); + save_session_png(&session, &out_dir.join(&name_plain), &name_plain)?; + + session.type_text("zzzz")?; + session.settle(100); + let name_empty = format!("{prefix}-lang-picker-empty.png"); + save_session_png(&session, &out_dir.join(&name_empty), &name_empty)?; + } + + // 7. SelectPopover with 26 options + filter showing unclipped pinned Create row at bottom. + { + let (doc, db_id) = build_wide_db_and_select_doc()?; + let session = start_headless_session( + 1280, + 800, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| { + v.set_document(doc, cx); + v.update_database_authoring( + &db_id, + |auth| { + auth.active_cell = Some(ActiveCellEditor { + row_id: "row-1".into(), + column_id: "col-cat".into(), + col_type: "select".into(), + draft: String::new(), + error: None, + select_filter: "Category".into(), + calendar_day_index: None, + }); + }, + cx, + ); + })?; + session.settle(120); + let name_create = format!("{prefix}-select-popover-create.png"); + save_session_png(&session, &out_dir.join(&name_create), &name_create)?; + } + + Ok(()) +} diff --git a/blocksuite/crates/playground/src/chrome/mod.rs b/blocksuite/crates/playground/src/chrome/mod.rs index 718e7019be..f59600a3c6 100644 --- a/blocksuite/crates/playground/src/chrome/mod.rs +++ b/blocksuite/crates/playground/src/chrome/mod.rs @@ -129,10 +129,12 @@ impl PlaygroundView { self.show_database_readonly_toast_once(cx); } } + let paint_scroll_y = + blocksuite_editor::scroll::snap_device_pixel(self.scroll_y, window.scale_factor()); let viewport = PageViewport { column_x: geometry.column_x, height: viewport_height, - scroll_y: self.scroll_y, + scroll_y: paint_scroll_y, }; let caret_alpha = self.caret_blink_alpha(self.now_ms(cx)); let mut local = self.local_selection_elements(&layout, viewport, palette, caret_alpha); @@ -168,16 +170,7 @@ impl PlaygroundView { }); let modal_blocks_input = self.has_non_text_modal_open(); surface - .children(page_elements( - &layout, - marks, - PageViewport { - column_x: geometry.column_x, - height: viewport_height, - scroll_y: self.scroll_y, - }, - &paint, - )) + .children(page_elements(&layout, marks, viewport, &paint)) .children(local) .when(!modal_blocks_input, |el| { el.child( @@ -446,6 +439,7 @@ impl PlaygroundView { impl ui::Render for PlaygroundView { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.last_scale_factor = window.scale_factor(); self.images.drain_pending_dropped(window); self.overlays.set_keyboard_toolbar_marks_disabled( self.table_cell.is_some() && self.editor.selection.is_none(), diff --git a/blocksuite/crates/playground/src/database_authoring/inline.rs b/blocksuite/crates/playground/src/database_authoring/inline.rs index 4ac7404cdb..67f580e4b3 100644 --- a/blocksuite/crates/playground/src/database_authoring/inline.rs +++ b/blocksuite/crates/playground/src/database_authoring/inline.rs @@ -516,8 +516,11 @@ impl PlaygroundView { } DatabaseInlineTarget::SelectFilter { block_id, .. } => { let auth = self.flow.database_state.authoring_mut(block_id); - if let Some(ed) = auth.active_cell.as_mut() { + if let Some(ed) = auth.active_cell.as_mut() + && ed.select_filter != display + { ed.select_filter = display; + auth.select_scroll_y = 0.0; } } DatabaseInlineTarget::FilterValue { block_id } => { diff --git a/blocksuite/crates/playground/src/database_authoring/paint.rs b/blocksuite/crates/playground/src/database_authoring/paint.rs index 8a43b0f827..aa2456dc3b 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint.rs @@ -297,9 +297,11 @@ impl PlaygroundView { _ => None, })?; let geom = self.current_page_geometry(f32::from(window.viewport_size().width)); + let paint_scroll_y = + blocksuite_editor::scroll::snap_device_pixel(self.scroll_y, window.scale_factor()); let block_screen_origin = ( geom.column_x + block.x, - TOPBAR_HEIGHT + block.y - self.scroll_y, + TOPBAR_HEIGHT + block.y - paint_scroll_y, ); let scroll_x = block .body diff --git a/blocksuite/crates/playground/src/database_authoring/tests_view_state_layout_reuse.rs b/blocksuite/crates/playground/src/database_authoring/tests_view_state_layout_reuse.rs index fab67d14c3..17dcd1cbab 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_view_state_layout_reuse.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_view_state_layout_reuse.rs @@ -397,7 +397,7 @@ fn touch_swipe_on_rtl_view_tabs_lays_out_only_the_database_among_10k_paragraphs( touch(TouchPhase::Ended, 200.0); assert_eq!( offsets, - [0, 40, 80, 120], + [0.0, 40.0, 80.0, 120.0], "tab strip offset after each move" ); } @@ -428,17 +428,17 @@ fn tabs_scroll_that_stays_at_zero_after_a_reveal_lays_out_the_database_again() { }); tick(); let (revealed, max) = shown_tabs(); - assert!(revealed > 0, "the reveal must show the last tab"); + assert!(revealed > 0.0, "the reveal must show the last tab"); // The scroll stays at the stored offset 0 and only stops the reveal. The pass that the // other database starts must lay out `db` again, without the reveal. app.update(|cx| { win.update(cx, |v, _, cx| { - assert!(v.flow.database_state.scroll_view_tabs("db", 1, max)); + assert!(v.flow.database_state.scroll_view_tabs("db", 1.0, max)); v.set_database_active_view("other", &other_view, cx); }) .unwrap() }); tick(); - assert_eq!(shown_tabs().0, 0, "the tab strip must leave the reveal"); + assert_eq!(shown_tabs().0, 0.0, "the tab strip must leave the reveal"); } diff --git a/blocksuite/crates/playground/src/doc_panel.rs b/blocksuite/crates/playground/src/doc_panel.rs index ab3065307a..2d3488015c 100644 --- a/blocksuite/crates/playground/src/doc_panel.rs +++ b/blocksuite/crates/playground/src/doc_panel.rs @@ -402,10 +402,13 @@ impl PlaygroundView { .w_full() .overflow_hidden() .on_scroll(cx.listener(move |this, ev: &ui::ScrollEvent, _, cx| { - let dy = f32::from(ev.delta.pixel_delta(px(20.0)).y); - let next = (this.doc_panel_scroll_y - dy).clamp(0.0, max_scroll); - if (next - this.doc_panel_scroll_y).abs() > 0.1 { - this.doc_panel_scroll_y = next; + let (_, dy) = blocksuite_editor::scroll::wheel_delta(ev, list_h); + let mut axis = blocksuite_editor::scroll::ScrollAxis::new( + this.doc_panel_scroll_y, + max_scroll, + ); + if axis.apply(dy) { + this.doc_panel_scroll_y = axis.offset; cx.notify(); } cx.stop_propagation(); @@ -551,9 +554,11 @@ impl PlaygroundView { self.edgeless_element_color_picker = None; self.page_scroll_fling = None; self.code_scroll_fling = None; + self.popover_scroll_fling = None; self.edgeless_pan_fling = None; - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset(); self.active_touch_owner = crate::touch_interaction::TouchStrokeOwner::None; + self.modal_touch_target = crate::touch_interaction::ModalTouchTarget::None; self.touch_long_press_anchor = None; self.touch_selection_menu_open = false; self.edgeless_readonly_selection_target = None; diff --git a/blocksuite/crates/playground/src/layout_cache.rs b/blocksuite/crates/playground/src/layout_cache.rs index a43f6b79fa..9ee6822004 100644 --- a/blocksuite/crates/playground/src/layout_cache.rs +++ b/blocksuite/crates/playground/src/layout_cache.rs @@ -6,7 +6,7 @@ use std::{ }; use blocksuite_playground_doc::read::{BlockContent, PageSnapshot}; -use ui::{Motion, MotionCurve, ScrollEvent, Window, px}; +use ui::{Motion, MotionCurve, Window}; fn extract_page_snippet(snap: &PageSnapshot) -> String { snap.root @@ -35,7 +35,7 @@ fn extract_page_snippet(snap: &PageSnapshot) -> String { use crate::{ HOME_PAGE_ID, PILL_EDGELESS_X, PILL_PAGE_X, PILL_TRANSITION_MS, PlaygroundMode, - PlaygroundTheme, PlaygroundView, SCROLL_LINE, + PlaygroundTheme, PlaygroundView, block_flow::{FlowInput, FlowLayout, FormFactor, ImageSlot, decode_image}, directory, overlays::InlineTargetEnd, @@ -443,6 +443,7 @@ impl PlaygroundView { self.edgeless.authoring.reset_transient(); self.page_scroll_fling = None; self.code_scroll_fling = None; + self.popover_scroll_fling = None; self.edgeless_pan_fling = None; self.touch_long_press_anchor = None; self.touch_selection_menu_open = false; @@ -463,213 +464,6 @@ impl PlaygroundView { cx.notify(); } - pub(crate) fn on_scroll( - &mut self, - event: &ScrollEvent, - window: &mut Window, - cx: &mut ui::Context, - ) { - self.page_scroll_fling = None; - self.code_scroll_fling = None; - if event.source == ui::ScrollSource::Touch { - if event.touch_phase == ui::TouchPhase::Started - || self.active_touch_owner == crate::TouchStrokeOwner::None - { - if self.has_live_modal_touch_overlay(window, cx) { - self.active_touch_owner = crate::TouchStrokeOwner::ModalOverlay; - if let Some((sheet_left, sheet_top, sheet_w, _, _)) = - self.record_sheet_geometry(window) - && let Some(s) = self.database_record_sheet.as_mut() - { - let d = event.delta.pixel_delta(px(SCROLL_LINE)); - let x0 = f32::from(event.position.x) - f32::from(d.x); - let y0 = f32::from(event.position.y) - f32::from(d.y); - let in_sheet_x = x0 >= sheet_left && x0 <= sheet_left + sheet_w; - if in_sheet_x && y0 >= sheet_top && y0 <= sheet_top + 68.0 { - s.grabber_drag_start_y.get_or_insert(y0); - s.touch_body_drag = false; - } - } - } else { - let d = event.delta.pixel_delta(px(SCROLL_LINE)); - let x0 = f32::from(event.position.x) - f32::from(d.x); - let y0 = f32::from(event.position.y) - f32::from(d.y); - if self - .hits_touch_image_resize_handle(x0, y0, window) - .is_some() - { - self.active_touch_owner = crate::TouchStrokeOwner::ImageResize; - } else { - self.active_touch_owner = crate::TouchStrokeOwner::Page; - } - } - } - if self.active_touch_owner == crate::TouchStrokeOwner::ImageResize { - return; - } - if self.active_touch_owner == crate::TouchStrokeOwner::ModalOverlay { - if let Some((_, _, _, _, max_scroll)) = self.record_sheet_geometry(window) { - let drag_in_header = self - .database_record_sheet - .as_ref() - .is_some_and(|s| s.grabber_drag_start_y.is_some()); - if !drag_in_header { - let dy = f32::from(event.delta.pixel_delta(px(SCROLL_LINE)).y); - if let Some(s) = self.database_record_sheet.as_mut() { - s.scroll_fling = None; - let next = (s.scroll_y - dy).clamp(0.0, max_scroll).round(); - if (next - s.scroll_y).abs() > 0.5 { - s.scroll_y = next; - cx.notify(); - } - } - } - } - return; - } - } - if self.database_record_sheet.is_some() { - if let Some((_, _, _, _, max_scroll)) = self.record_sheet_geometry(window) { - let drag_in_header = self - .database_record_sheet - .as_ref() - .is_some_and(|s| s.grabber_drag_start_y.is_some()); - if !drag_in_header { - let dy = f32::from(event.delta.pixel_delta(px(SCROLL_LINE)).y); - if let Some(s) = self.database_record_sheet.as_mut() { - s.scroll_fling = None; - let next = (s.scroll_y - dy).clamp(0.0, max_scroll).round(); - if (next - s.scroll_y).abs() > 0.5 { - s.scroll_y = next; - cx.notify(); - } - } - } - return; - } - self.database_record_sheet = None; - cx.notify(); - } - if self.overlays.bookmark_prompt().is_some() - || self.overlays.equation_editor().is_some() - || self.overlays.active_text_field().is_some() - { - return; - } - if self.touch_selection_menu_open { - self.touch_selection_menu_open = false; - cx.notify(); - } - let raw_delta = event.delta.pixel_delta(px(SCROLL_LINE)); - let (mut dx, mut dy) = (f32::from(raw_delta.x), f32::from(raw_delta.y)); - // On Windows/Linux, Shift+wheel delivers a vertical delta with `modifiers.shift`: - // convert it to horizontal scroll for wide tables, code blocks, and databases. - if event.source != ui::ScrollSource::Touch - && event.modifiers.shift - && dx.abs() < f32::EPSILON - && dy.abs() > f32::EPSILON - { - dx = dy; - dy = 0.0; - } - // Touch scroll axis lock — once a touch drag establishes a dominant axis, - // suppress orthogonal jitter until the gesture ends, restarts, or pauses >160ms. - if event.source == ui::ScrollSource::Touch { - let now_ms = self.now_ms(cx); - if self - .last_touch_scroll_ms - .is_some_and(|prev| now_ms - prev > 160.0) - { - self.touch_scroll_axis_lock = None; - } - match event.touch_phase { - ui::TouchPhase::Started => { - self.touch_scroll_axis_lock = None; - self.last_touch_scroll_ms = Some(now_ms); - } - ui::TouchPhase::Ended | ui::TouchPhase::Cancelled => { - self.touch_scroll_axis_lock = None; - self.last_touch_scroll_ms = None; - } - ui::TouchPhase::Moved => { - self.last_touch_scroll_ms = Some(now_ms); - } - } - if self.touch_scroll_axis_lock.is_none() && (dx.abs() >= 4.0 || dy.abs() >= 4.0) { - self.touch_scroll_axis_lock = Some(if dx.abs() > dy.abs() * 1.2 { - crate::TouchScrollAxis::Horizontal - } else { - crate::TouchScrollAxis::Vertical - }); - } - match self.touch_scroll_axis_lock { - Some(crate::TouchScrollAxis::Horizontal) => dy = 0.0, - Some(crate::TouchScrollAxis::Vertical) => dx = 0.0, - None => {} - } - } - // Horizontal scroll over a touch database view tab strip scrolls the tab strip. - if dx.abs() > dy.abs() - && self.form_factor.is_touch_form_factor() - && let Some(layout) = self.flow_layout() - { - let geom = self.current_page_geometry(self.window_size.0); - let wx = f32::from(event.position.x) - geom.column_x; - let wy = f32::from(event.position.y) - crate::TOPBAR_HEIGHT + self.scroll_y; - if let Some(block) = layout.blocks.iter().find(|b| { - b.body.kind == crate::block_flow::FlowKind::Database - && b.rect().contains(wx, wy) - && (wy - b.y) >= 34.0 - && (wy - b.y) <= 82.0 - }) { - let block_id = block.block_id.clone(); - let (cur_px, max_px) = self.flow.database_view_tabs_metrics(&block_id); - let logical_dx = if window.layout_direction().is_rtl() { - -dx - } else { - dx - }; - if max_px > 0 - && self.flow.database_state.scroll_view_tabs_from( - &block_id, - cur_px, - logical_dx.round() as i32, - max_px, - ) - { - cx.notify(); - return; - } - } - } - // A sideways scroll over an unwrapped code block or wide table scrolls it, not the page. - if let Some((snapshot, layout)) = self.snapshot.clone().zip(self.flow_layout()) { - let local_collapsed = self.flow.local_collapsed.clone(); - let scene = self.overlay_scene( - &snapshot, - &layout, - window.layout_direction(), - None, - &local_collapsed, - ); - if self.overlays.scroll_code( - &scene, - f32::from(event.position.x), - f32::from(event.position.y), - dx, - dy, - ) { - cx.notify(); - return; - } - } - let target = (self.scroll_y - dy).clamp(0.0, self.max_scroll).round(); - if target != self.scroll_y { - self.scroll_y = target; - cx.notify(); - } - } - pub(crate) fn ensure_layout(&mut self, width: f32, window: &Window) -> Option> { use std::hash::{Hash, Hasher}; diff --git a/blocksuite/crates/playground/src/lib.rs b/blocksuite/crates/playground/src/lib.rs index 36f8af706c..6c02a59103 100644 --- a/blocksuite/crates/playground/src/lib.rs +++ b/blocksuite/crates/playground/src/lib.rs @@ -19,6 +19,7 @@ mod image_cache; mod layout_cache; mod media_picker; pub mod overlays; +mod page_scroll; pub mod room_client; mod showcase; @@ -45,19 +46,14 @@ pub use view_room::register_platform_file_pickers; #[cfg(target_arch = "wasm32")] pub use view_room::wasm_main; -use view_room::{BlobFetchState, RoomRuntime}; - -use std::{ - collections::{BTreeMap, BTreeSet, HashMap}, - rc::Rc, - time::Duration, -}; - use blocksuite_playground_doc::{ awareness::{AwarenessPayload, TextRangePoint, TextSelectionState}, read::{BlockContent, PageSnapshot}, }; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::{rc::Rc, time::Duration}; use ui::{Motion, ScrollEvent, Task, Window, point, prelude::*, px, size}; +use view_room::{BlobFetchState, RoomRuntime}; #[cfg(test)] pub(crate) use crate::block_flow::page_geometry; @@ -168,7 +164,7 @@ pub(crate) const PILL_EDGELESS_X: f64 = 94.0; pub(crate) const PILL_TRANSITION_MS: f64 = 200.0; pub(crate) const THEME_TOGGLE_SIZE: f32 = 32.0; pub(crate) const TOPBAR_EDGE: f32 = 12.0; -pub(crate) const SCROLL_LINE: f32 = 20.0; +pub(crate) const SCROLL_LINE: f32 = blocksuite_editor::scroll::SCROLL_LINE_PX; /// Each test that changes the global preview providers or a preview revision holds this lock. /// So does each test that counts the blocks of a layout pass, because a changed revision @@ -197,7 +193,7 @@ pub(crate) struct ImageResizeDrag { pub via_touch: bool, } -pub(crate) use touch_interaction::{TouchScrollAxis, TouchStrokeOwner}; +pub(crate) use touch_interaction::{ModalTouchTarget, PopoverFlingTarget, TouchStrokeOwner}; /// Interactive GPUI root view for desktop, Web canvas, and headless verification sessions. pub struct PlaygroundView { @@ -269,10 +265,12 @@ pub struct PlaygroundView { pub(crate) database_record_sheet: Option, pub(crate) page_scroll_fling: Option, pub(crate) code_scroll_fling: Option<(String, ui::InertialDecay)>, + pub(crate) popover_scroll_fling: Option<(PopoverFlingTarget, ui::InertialDecay)>, pub(crate) edgeless_pan_fling: Option<(ui::InertialDecay, ui::InertialDecay)>, - pub(crate) touch_scroll_axis_lock: Option, + pub(crate) scroll_axis_latch: blocksuite_editor::scroll::AxisLatch, + pub(crate) last_scale_factor: f32, pub(crate) active_touch_owner: TouchStrokeOwner, - pub(crate) last_touch_scroll_ms: Option, + pub(crate) modal_touch_target: ModalTouchTarget, pub(crate) keep_keyboard_on_block_selection: bool, pub(crate) block_selection_return_caret: Option, pub(crate) touch_long_press_anchor: @@ -434,10 +432,12 @@ impl PlaygroundView { database_record_sheet: None, page_scroll_fling: None, code_scroll_fling: None, + popover_scroll_fling: None, edgeless_pan_fling: None, - touch_scroll_axis_lock: None, + scroll_axis_latch: blocksuite_editor::scroll::AxisLatch::default(), + last_scale_factor: 1.0, active_touch_owner: TouchStrokeOwner::None, - last_touch_scroll_ms: None, + modal_touch_target: ModalTouchTarget::None, keep_keyboard_on_block_selection: false, block_selection_return_caret: None, touch_long_press_anchor: None, diff --git a/blocksuite/crates/playground/src/overlays/mod.rs b/blocksuite/crates/playground/src/overlays/mod.rs index 5a562be44b..ecc3a8663f 100644 --- a/blocksuite/crates/playground/src/overlays/mod.rs +++ b/blocksuite/crates/playground/src/overlays/mod.rs @@ -39,6 +39,8 @@ mod tests_pdf_viewer_mobile; #[cfg(test)] mod tests_popovers_toolbars; #[cfg(test)] +mod tests_scroll_and_picker; +#[cfg(test)] mod tests_slash_linked_table; #[cfg(test)] mod tests_tree_dnd_and_marquee; diff --git a/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs b/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs index d17c4fa3d4..773cd08026 100644 --- a/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs +++ b/blocksuite/crates/playground/src/overlays/tests_popovers_toolbars.rs @@ -1214,10 +1214,23 @@ mod tests { "align_block_selection must not pollute non-text Code block with prop:textAlign" ); - // 6. Scrollable 25-language CodeLangPicker reaches index 24 (`docker` / `Dockerfile`). + // 6. Scrollable CodeLangPicker reaches `docker` / `Dockerfile` via keyboard navigation. session.overlay(OverlayEvent::OpenCodeLangPicker("b-code".into())); let _ = session.settle(); - for _ in 0..23 { + let docker_idx = session + .view(|v, _| { + v.overlays().code_lang_picker().and_then(|p| { + blocksuite_editor::overlays::filter_code_languages_ordered( + "", + &p.current_lang, + &[], + ) + .iter() + .position(|(id, _)| *id == "docker") + }) + }) + .expect("docker must exist in language catalog"); + for _ in 0..docker_idx { session.key("down"); } let scrolled_picker = session.frame(); @@ -1225,7 +1238,7 @@ mod tests { scrolled_picker .elements .contains_key("overlay.code_lang_picker.item.docker"), - "scrolling down through all 25 languages must expose docker" + "scrolling down through the language catalog must expose docker" ); session.key("enter"); let docker_lang = session.view(|v, _| { @@ -1741,8 +1754,9 @@ mod tests { ); } - // Phone CodeLangPicker uses 5-row window (>=44pt rows), scrolls Go into view on Down from - // Python (row 4 -> row 5), commits Go on Enter, and closes on Android Back! + // Phone CodeLangPicker uses >=44pt rows capped at <=440px, pins active language (`python`) + // first, scrolls an offscreen language (`html`) into view via Down, commits it on Enter, + // and closes on Android Back. phone.overlay(OverlayEvent::SetCodeLanguage { block_id: "b-code".into(), language: "python".into(), @@ -1759,16 +1773,31 @@ mod tests { assert!( !picker_frame .elements - .contains_key("overlay.code_lang_picker.item.go"), - "Go (idx 5) starts below the 5-row touch window (0..5)" + .contains_key("overlay.code_lang_picker.item.html"), + "HTML starts below the 440px touch picker window" ); - phone.key("down"); + let html_idx = phone + .view(|v, _| { + v.overlays().code_lang_picker().and_then(|p| { + blocksuite_editor::overlays::filter_code_languages_ordered( + "", + &p.current_lang, + &[], + ) + .iter() + .position(|(id, _)| *id == "html") + }) + }) + .expect("html must exist in language catalog"); + for _ in 0..html_idx { + phone.key("down"); + } let picker_down = phone.frame(); assert!( picker_down .elements - .contains_key("overlay.code_lang_picker.item.go"), - "pressing Down from Python on 5-row touch CodeLangPicker must scroll Go into view" + .contains_key("overlay.code_lang_picker.item.html"), + "pressing Down on touch CodeLangPicker must scroll HTML into view" ); phone.key("enter"); let committed_lang = phone.view(|v, _| { @@ -1779,7 +1808,7 @@ mod tests { _ => None, }) }); - assert_eq!(committed_lang.as_deref(), Some("go")); + assert_eq!(committed_lang.as_deref(), Some("html")); phone.overlay(OverlayEvent::OpenCodeLangPicker("b-code".into())); let _ = phone.settle(); let back_consumed = phone @@ -1948,7 +1977,7 @@ mod tests { let dp_bounds = element(&dp, "overlay.code_lang_picker").bounds; let initial_offset = desk .view(|v, _| v.overlays().code_lang_picker().map(|p| p.scroll_offset)) - .unwrap_or(0); + .unwrap_or(0.0); desk.headless .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { position: ui::point( @@ -1964,7 +1993,7 @@ mod tests { let _ = desk.frame(); let scrolled_offset = desk .view(|v, _| v.overlays().code_lang_picker().map(|p| p.scroll_offset)) - .unwrap_or(0); + .unwrap_or(0.0); assert!( scrolled_offset != initial_offset, "CodeLangPicker wheel scroll must change scroll_offset and persist across repaints (before={initial_offset}, after={scrolled_offset})" diff --git a/blocksuite/crates/playground/src/overlays/tests_scroll_and_picker.rs b/blocksuite/crates/playground/src/overlays/tests_scroll_and_picker.rs new file mode 100644 index 0000000000..9b874ac35a --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/tests_scroll_and_picker.rs @@ -0,0 +1,660 @@ +//! End-to-end deterministic tests for subpixel scrolling, split-axis diagonal trackpad routing, +//! `CodeLangPicker` micro-scroll and prefix/alias search, and Database `Select` 400 px scrolling. + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use blocksuite_playground_doc::schema::{ + BlockSpec, DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec, + ParagraphType, + }; + use serde_json::json; + + use crate::{ + HOME_PAGE_ID, PlaygroundOptions, + database::{ActiveCellEditor, SELECT_POPOVER_MAX_HEIGHT}, + overlays::OverlayEvent, + room_client::DocState, + }; + + use super::super::tests::{element, open_with_options}; + + fn scroll_pixels(x: f32, y: f32, dx: f32, dy: f32) -> ui::PlatformInput { + ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(x), ui::px(y)), + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(dx), ui::px(dy))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + }) + } + + fn doc_with_long_page_and_wide_code() -> DocState { + let mut state = DocState::new("scroll-test", 1).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Scroll Test", 1) + .unwrap(); + let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + page.add_block( + "root", + BlockSpec::Page { + title: "Scroll Test".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .unwrap(); + page.add_block( + "b-code", + BlockSpec::Code { + text: format!("let long_line = \"{}\";", "x".repeat(260)), + language: Some("rust".into()), + caption: String::new(), + }, + Some("note"), + None, + 3, + ) + .unwrap(); + for i in 0..40 { + page.add_block( + &format!("p-{i}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: format!("Paragraph {i} keeps the page tall enough to scroll smoothly."), + }, + Some("note"), + None, + 10 + i as u64, + ) + .unwrap(); + } + state + } + + #[test] + fn subpixel_quarter_px_scroll_accumulates_and_diagonal_over_code_chains_dy() { + let s = open_with_options(1280, 600, PlaygroundOptions::default()); + let state = doc_with_long_page_and_wide_code(); + s.app.update(|cx| { + s.window + .update(cx, |v, _, cx| v.set_document(state, cx)) + .unwrap(); + }); + let frame = s.settle(); + let code_bounds = element(&frame, "page.block.b-code").bounds; + + // 1. 20 x 0.25 px vertical page micro-scrolls must accumulate to exact 5.0 px. + let page_x = 640.0; + let page_y = code_bounds.bottom() + 40.0; + for _ in 0..20 { + s.headless + .dispatch_input(scroll_pixels(page_x, page_y, 0.0, -0.25)); + } + let _ = s.frame(); + let page_y_after = s.view(|v, _| v.scroll_offset()); + assert!( + (page_y_after - 5.0).abs() < 1e-4, + "20 x 0.25px page micro-scrolls must sum to 5.0px, got {page_y_after}" + ); + + // 2. 20 x 0.25 px horizontal micro-scrolls over unwrapped code block accumulate to 5.0 px. + let code_cx = code_bounds.x + code_bounds.width * 0.5; + let code_cy = code_bounds.y + code_bounds.height * 0.5; + // Advance clock > 160ms so axis latch resets between gestures. + s.platform + .advance_clock(std::time::Duration::from_millis(200)); + for _ in 0..20 { + s.headless + .dispatch_input(scroll_pixels(code_cx, code_cy, -0.25, 0.0)); + } + let _ = s.frame(); + let code_x_after = s.view(|v, _| v.overlays().code_scroll_x("b-code")); + assert!( + (code_x_after - 5.0).abs() < 1e-4, + "20 x 0.25px code micro-scrolls must sum to 5.0px, got {code_x_after}" + ); + + // 3. Diagonal gesture over code block scrolls BOTH code_x and page_y without eating dy. + s.platform + .advance_clock(std::time::Duration::from_millis(200)); + let page_before_diag = s.view(|v, _| v.scroll_offset()); + let code_before_diag = s.view(|v, _| v.overlays().code_scroll_x("b-code")); + s.headless + .dispatch_input(scroll_pixels(code_cx, code_cy, -12.0, -8.0)); + let _ = s.frame(); + let page_after_diag = s.view(|v, _| v.scroll_offset()); + let code_after_diag = s.view(|v, _| v.overlays().code_scroll_x("b-code")); + assert!( + (code_after_diag - (code_before_diag + 12.0)).abs() < 1e-3, + "diagonal gesture must scroll code_x by 12.0 (before={code_before_diag}, after={code_after_diag})" + ); + assert!( + (page_after_diag - (page_before_diag + 8.0)).abs() < 1e-3, + "diagonal gesture over code block must NOT swallow dy (before={page_before_diag}, after={page_after_diag})" + ); + } + + #[test] + fn code_lang_picker_micro_scroll_and_prefix_alias_search_end_to_end() { + let s = open_with_options(1280, 800, PlaygroundOptions::default()); + let state = doc_with_long_page_and_wide_code(); + s.app.update(|cx| { + s.window + .update(cx, |v, _, cx| v.set_document(state, cx)) + .unwrap(); + }); + let _ = s.settle(); + s.overlay(OverlayEvent::OpenCodeLangPicker("b-code".into())); + let frame = s.settle(); + let picker_bounds = element(&frame, "overlay.code_lang_picker").bounds; + assert!( + (picker_bounds.width - 230.0).abs() <= 1.0, + "CodeLangPicker width must be 230px, got {}", + picker_bounds.width + ); + assert!( + picker_bounds.height <= 440.5, + "CodeLangPicker height must cap at 440px, got {}", + picker_bounds.height + ); + + // 20 x 0.25 px trackpad micro-scrolls move by 5.0 px (never jumping 20 rows). + let px_mid = picker_bounds.x + picker_bounds.width * 0.5; + let py_mid = picker_bounds.y + picker_bounds.height * 0.6; + for _ in 0..20 { + s.headless + .dispatch_input(scroll_pixels(px_mid, py_mid, 0.0, -0.25)); + } + let _ = s.frame(); + let offset = s + .view(|v, _| v.overlays().code_lang_picker().map(|p| p.scroll_offset)) + .unwrap_or(-1.0); + assert!( + (offset - 5.0).abs() < 1e-3, + "CodeLangPicker 20 x 0.25px micro-scroll must equal 5.0px, got {offset}" + ); + + // Prefix + alias search: "ts" surfaces TypeScript as the first selectable item. + s.type_text("ts"); + let ts_frame = s.settle(); + assert!( + ts_frame + .elements + .contains_key("overlay.code_lang_picker.item.typescript"), + "typing 'ts' must match TypeScript by alias" + ); + } + + #[test] + fn database_select_popover_caps_at_400px_and_scrolls_contained() { + let s = open_with_options(1280, 800, PlaygroundOptions::default()); + let mut state = DocState::new("db-select-scroll", 2).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "DB Select Scroll", 1) + .unwrap(); + let options: Vec = (1..=26) + .map(|i| { + json!({ + "id": format!("opt-{i:02}"), + "value": format!("Option {i:02}"), + "color": "var(--affine-tag-blue)", + }) + }) + .collect(); + { + let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + page.add_block( + "root", + BlockSpec::Page { + title: "DB Select Scroll".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .unwrap(); + page.add_block( + "db-1", + BlockSpec::Database(DatabaseSpec { + title: "Select Cap Test".into(), + columns: vec![ + DatabaseColumnSpec { + id: "title".into(), + name: "Name".into(), + column_type: "title".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "col-sel".into(), + name: "Tag".into(), + column_type: "select".into(), + data: json!({ "options": options }), + }, + ], + views: vec![DatabaseViewSpec { + id: "v1".into(), + name: "Table".into(), + mode: "table".into(), + raw: json!({}), + }], + cells: BTreeMap::from([( + "row-1".into(), + BTreeMap::from([( + "col-sel".into(), + DatabaseCellSpec::Text("opt-01".into()), + )]), + )]), + }), + Some("note"), + None, + 3, + ) + .unwrap(); + page.add_block( + "row-1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Item 1".into(), + }, + Some("db-1"), + None, + 4, + ) + .unwrap(); + } + s.app.update(|cx| { + s.window + .update(cx, |v, _, cx| { + v.set_document(state, cx); + v.update_database_authoring( + "db-1", + |auth| { + auth.active_cell = Some(ActiveCellEditor { + row_id: "row-1".into(), + column_id: "col-sel".into(), + col_type: "select".into(), + draft: String::new(), + error: None, + select_filter: String::new(), + calendar_day_index: None, + }); + }, + cx, + ); + }) + .unwrap(); + }); + let _ = s.settle(); + + let pop_bounds = s + .app + .update(|cx| { + s.window + .update(cx, |v, w, _| { + let layout = v.flow_layout()?; + v.database_popover_overlay(&layout, w) + .map(|(_, o)| o.bounds) + }) + .unwrap() + }) + .expect("select popover must be open"); + assert!( + pop_bounds.h <= SELECT_POPOVER_MAX_HEIGHT + 0.5, + "26-option select popover must cap at 400px, got {}", + pop_bounds.h + ); + + let page_before = s.view(|v, _| v.scroll_offset()); + for _ in 0..20 { + s.headless.dispatch_input(scroll_pixels( + pop_bounds.x + pop_bounds.w * 0.5, + pop_bounds.y + pop_bounds.h * 0.5, + 0.0, + -0.25, + )); + } + let _ = s.frame(); + let select_scroll = s.view(|v, _| { + v.flow + .database_state + .state_for("db-1") + .authoring + .select_scroll_y + }); + assert!( + (select_scroll - 5.0).abs() < 1e-3, + "20 x 0.25px select popover micro-scroll must accumulate to 5.0px, got {select_scroll}" + ); + assert_eq!( + s.view(|v, _| v.scroll_offset()), + page_before, + "scrolling inside Select popover must stay contained and not scroll the page" + ); + + // Typing a filter via real keystrokes resets select_scroll_y to 0 and keeps the Create row unclipped at the bottom. + s.type_text("Option"); + let _ = s.settle(); + let select_scroll_after_type = s.view(|v, _| { + v.flow + .database_state + .state_for("db-1") + .authoring + .select_scroll_y + }); + assert_eq!( + select_scroll_after_type, 0.0, + "typing a Select filter via real input must reset select_scroll_y to 0.0" + ); + let (pop_after, create_hit) = s + .app + .update(|cx| { + s.window + .update(cx, |v, w, _| { + let layout = v.flow_layout()?; + let (_, ov) = v.database_popover_overlay(&layout, w)?; + let create = ov.hits.iter().find_map(|h| { + matches!( + h.kind, + crate::database::DatabaseAuthoringHitKind::SelectCreateOption { .. } + ) + .then_some(h.rect) + }); + Some((ov.bounds, create)) + }) + .unwrap() + }) + .expect("select popover with filter must stay open"); + let create_rect = create_hit.expect("Create row must be visible and clickable"); + assert!( + create_rect.y >= pop_after.y && create_rect.bottom() <= pop_after.bottom() + 0.5, + "Create row {:?} must stay unclipped inside popover {:?}", + create_rect, + pop_after + ); + } + + #[test] + fn wide_table_hscrollbar_full_height_hover_click_and_thumb_drag() { + let s = open_with_options(1280, 800, PlaygroundOptions::default()); + let mut state = DocState::new("wide-table-hscroll", 3).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Wide Table", 1) + .unwrap(); + { + let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + page.add_block( + "root", + BlockSpec::Page { + title: "Wide Table".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block( + "note", + BlockSpec::Note { xywh: None }, + Some("root"), + None, + 2, + ) + .unwrap(); + let row = |r: usize| -> Vec { + (0..16) + .map(|c| format!("Row {r} col {c} content")) + .collect() + }; + page.add_block( + "t1", + BlockSpec::Table { + rows: vec![row(0), row(1), row(2)], + }, + Some("note"), + None, + 3, + ) + .unwrap(); + } + s.app.update(|cx| { + s.window + .update(cx, |v, _, cx| v.set_document(state, cx)) + .unwrap(); + }); + let f = s.settle(); + let tb = element(&f, "page.block.t1").bounds; + let (tx, ty) = (tb.x + tb.width * 0.5, tb.y + tb.height * 0.5); + s.pointer(tx, ty, false); + let f = s.settle(); + let bar = element(&f, "page.block.t1.hscrollbar").bounds; + assert!( + bar.height >= 23.5, + "hscrollbar must be 24px tall, got {}", + bar.height + ); + + // Moving pointer across full 24px height keeps the scrollbar mounted. + for dy in [3.0_f32, 8.0, 12.0, 20.0] { + s.pointer(bar.x + bar.width * 0.5, bar.y + dy, false); + let next = s.frame(); + assert!( + next.elements.contains_key("page.block.t1.hscrollbar"), + "scrollbar vanished at dy={dy}" + ); + } + + // Clicking at 90% and 10% across both y+3 and y+12 moves scroll_x. + for (fx, dy, expect_gt) in [ + (0.9_f32, 3.0_f32, true), + (0.1, 3.0, false), + (0.9, 12.0, true), + (0.1, 12.0, false), + ] { + let cx_pt = bar.x + bar.width * fx; + let cy_pt = bar.y + dy; + s.pointer(cx_pt, cy_pt, false); + let _ = s.frame(); + s.headless + .dispatch_input(ui::PlatformInput::MouseDown(ui::MouseDownEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(cx_pt), ui::px(cy_pt)), + modifiers: ui::Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + s.platform.run_until_parked(); + let _ = s.frame(); + s.headless + .dispatch_input(ui::PlatformInput::MouseUp(ui::MouseUpEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(cx_pt), ui::px(cy_pt)), + modifiers: ui::Modifiers::default(), + click_count: 1, + })); + s.platform.run_until_parked(); + let _ = s.frame(); + let sx = s.view(|v, _| v.overlays().code_scroll_x("t1")); + if expect_gt { + assert!( + sx > 100.0, + "click at ({fx},{dy}) must scroll right, got {sx}" + ); + } else { + assert!( + sx < 100.0, + "click at ({fx},{dy}) must scroll left, got {sx}" + ); + } + } + + // Press at 20% and drag 240px right in 6 steps updates scroll_x continuously. + let (bx, by) = (bar.x + bar.width * 0.2, bar.y + 12.0); + s.pointer(bx, by, false); + let _ = s.frame(); + s.headless + .dispatch_input(ui::PlatformInput::MouseDown(ui::MouseDownEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(bx), ui::px(by)), + modifiers: ui::Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + s.platform.run_until_parked(); + let _ = s.frame(); + let after_press = s.view(|v, _| v.overlays().code_scroll_x("t1")); + for step in 1..=6 { + s.headless + .dispatch_input(ui::PlatformInput::MouseMove(ui::MouseMoveEvent { + position: ui::point(ui::px(bx + 40.0 * step as f32), ui::px(by)), + pressed_button: Some(ui::MouseButton::Left), + modifiers: ui::Modifiers::default(), + })); + s.platform.run_until_parked(); + let _ = s.frame(); + } + let after_drag = s.view(|v, _| v.overlays().code_scroll_x("t1")); + s.headless + .dispatch_input(ui::PlatformInput::MouseUp(ui::MouseUpEvent { + button: ui::MouseButton::Left, + position: ui::point(ui::px(bx + 240.0), ui::px(by)), + modifiers: ui::Modifiers::default(), + click_count: 1, + })); + s.platform.run_until_parked(); + let _ = s.frame(); + assert!( + after_drag > after_press + 400.0, + "dragging 240px right must advance scroll_x significantly (press={after_press}, drag={after_drag})" + ); + assert!( + (s.view(|v, _| v.overlays().code_scroll_x("t1")) - after_drag).abs() < 1e-3, + "scroll_x must persist after mouse release" + ); + } + + #[test] + fn input_popovers_block_page_wheel_and_touch_scroll_without_penetration() { + let s = open_with_options(1280, 800, PlaygroundOptions::default()); + let state = doc_with_long_page_and_wide_code(); + s.app.update(|cx| { + s.window + .update(cx, |v, _, cx| v.set_document(state, cx)) + .unwrap(); + }); + let _ = s.settle(); + + // Open CodeLangPicker and send wheel events over the page -> page scroll_y stays 0. + s.overlay(OverlayEvent::OpenCodeLangPicker("b-code".into())); + let frame = s.settle(); + let picker_rect = element(&frame, "overlay.code_lang_picker").bounds; + for _ in 0..6 { + s.headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(1200.0), ui::px(700.0)), + delta: ui::ScrollDelta::Lines(ui::point(0.0, -5.0)), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + s.platform.run_until_parked(); + } + let _ = s.frame(); + assert_eq!( + s.view(|v, _| v.scroll_offset()), + 0.0, + "page must not scroll while CodeLangPicker is open" + ); + + // Touch scroll inside CodeLangPicker scrolls only the picker list (0px page scroll). + let px_mid = picker_rect.x + picker_rect.width * 0.5; + let py_mid = picker_rect.y + picker_rect.height * 0.6; + for phase in [ + ui::TouchPhase::Started, + ui::TouchPhase::Moved, + ui::TouchPhase::Moved, + ui::TouchPhase::Ended, + ] { + let dy = if matches!(phase, ui::TouchPhase::Ended) { + 0.0 + } else { + -40.0 + }; + s.headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(px_mid), ui::px(py_mid)), + delta: ui::ScrollDelta::Pixels(ui::point(ui::px(0.0), ui::px(dy))), + modifiers: ui::Modifiers::default(), + touch_phase: phase, + source: ui::ScrollSource::Touch, + })); + s.platform.run_until_parked(); + } + let _ = s.frame(); + assert_eq!( + s.view(|v, _| v.scroll_offset()), + 0.0, + "touch drag inside CodeLangPicker must have 0px page penetration" + ); + assert!( + s.view(|v, _| v + .overlays() + .code_lang_picker() + .map_or(0.0, |p| p.scroll_offset)) + > 40.0, + "touch drag inside CodeLangPicker must scroll its list" + ); + + // Unmatched query renders centered "No matching language" empty state. + s.type_text("zzzz_no_lang"); + let empty_frame = s.settle(); + let empty_el = element(&empty_frame, "overlay.code_lang_picker.empty"); + assert_eq!(empty_el.text.as_deref(), Some("No matching language")); + s.key("escape"); + let _ = s.settle(); + + // Bookmark prompt open -> wheel events over the page keep scroll_y == 0. + s.overlay(OverlayEvent::OpenBookmarkPrompt { + block_id: "p-0".into(), + }); + let _ = s.settle(); + for _ in 0..6 { + s.headless + .dispatch_input(ui::PlatformInput::Scroll(ui::ScrollEvent { + position: ui::point(ui::px(1200.0), ui::px(700.0)), + delta: ui::ScrollDelta::Lines(ui::point(0.0, -5.0)), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + s.platform.run_until_parked(); + } + let _ = s.frame(); + assert_eq!( + s.view(|v, _| v.scroll_offset()), + 0.0, + "page must not scroll while bookmark prompt is open" + ); + } +} diff --git a/blocksuite/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs index 8cd9101293..4305014929 100644 --- a/blocksuite/crates/playground/src/overlays/view.rs +++ b/blocksuite/crates/playground/src/overlays/view.rs @@ -63,7 +63,10 @@ impl PlaygroundView { window: self.window_size, bottom_inset: self.ime_insets.last_bottom, bottom_toolbar_inset, - scroll_y: self.scroll_y, + scroll_y: blocksuite_editor::scroll::snap_device_pixel( + self.scroll_y, + self.last_scale_factor, + ), direction, form_factor: self.form_factor, is_touch: self.is_touch_host(), diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs index a857e1cdbb..033cb5bfa4 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/mod.rs @@ -626,12 +626,14 @@ impl PlaygroundView { self.layout = None; self.edgeless = crate::edgeless::EdgelessCanvasState::new(); self.active_touch_owner = crate::TouchStrokeOwner::None; + self.modal_touch_target = crate::touch_interaction::ModalTouchTarget::None; self.touch_long_press_anchor = None; - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset(); self.scrollbar_drag = None; self.edgeless_readonly_selection_target = None; self.page_scroll_fling = None; self.code_scroll_fling = None; + self.popover_scroll_fling = None; self.edgeless_pan_fling = None; self.touch_selection_menu_open = false; self.database_record_sheet = None; diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs index d99b910019..6ba36b4409 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs @@ -559,7 +559,10 @@ impl PlaygroundView { visible_rows, hidden_rows, hidden_expanded: sheet.hidden_expanded, - scroll_y: sheet.scroll_y.clamp(0.0, max_scroll).round(), + scroll_y: blocksuite_editor::scroll::snap_device_pixel( + sheet.scroll_y.clamp(0.0, max_scroll), + window.scale_factor(), + ), }) } diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_record_sheet_touch.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_record_sheet_touch.rs index 44c476b5fd..579abaf81d 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests_record_sheet_touch.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_record_sheet_touch.rs @@ -479,7 +479,7 @@ fn rtl_mobile_database_view_tabs_swipe_exposes_and_activates_last_view() { let b = layout.block("db-rtl").unwrap(); (b.x, b.y, v.flow.database_view_tabs_max_scroll("db-rtl")) }); - assert!(max_scroll > 100); + assert!(max_scroll > 100.0); let strip_y = crate::TOPBAR_HEIGHT + block_y + 54.0; // Swipe finger RIGHT (dx > 0) in RTL to reveal trailing views v-9 on the left side. @@ -493,7 +493,7 @@ fn rtl_mobile_database_view_tabs_swipe_exposes_and_activates_last_view() { .view_tabs_scroll_px }); assert!( - scroll_px >= max_scroll - 2, + scroll_px >= max_scroll - 2.0, "RTL rightward swipe must advance view_tabs_scroll_px to expose v-9 (got {scroll_px}/{max_scroll})" ); diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_gestures.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_gestures.rs index c89b72fdd5..fdac9f60b0 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_gestures.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_gestures.rs @@ -49,9 +49,9 @@ fn touch_axis_lock_calendar_month_and_record_sheet_scroll_escape() { let _ = touch.frame(); } assert_eq!( - touch.view(|v| v.touch_scroll_axis_lock), + touch.view(|v| v.scroll_axis_latch.locked()), None, - "lifting first vertical touch gesture must clear touch_scroll_axis_lock" + "lifting first vertical touch gesture must clear scroll_axis_latch" ); let tid2 = TouchId(102); for (phase, x) in [ @@ -71,8 +71,8 @@ fn touch_axis_lock_calendar_month_and_record_sheet_scroll_escape() { touch.platform.run_until_parked(); } assert_eq!( - touch.view(|v| v.touch_scroll_axis_lock), - Some(crate::TouchScrollAxis::Horizontal), + touch.view(|v| v.scroll_axis_latch.locked()), + Some(blocksuite_editor::scroll::ScrollAxisLock::Horizontal), "second independent horizontal touch drag must switch axis lock to Horizontal" ); touch @@ -86,7 +86,7 @@ fn touch_axis_lock_calendar_month_and_record_sheet_scroll_escape() { })); touch.platform.run_until_parked(); let _ = touch.frame(); - assert_eq!(touch.view(|v| v.touch_scroll_axis_lock), None); + assert_eq!(touch.view(|v| v.scroll_axis_latch.locked()), None); // 2. Phone calendar with today = 2026-12-01 and records in March 2026: // header/grid/plain must show 2026-12 and next-month step must land on 2027-01. @@ -209,7 +209,7 @@ fn touch_axis_lock_calendar_month_and_record_sheet_scroll_escape() { let _ = touch.frame(); assert_eq!( touch.view(|v| v.flow.database_view_tabs_max_scroll("db-long")), - 0, + 0.0, "single-tab database must have view_tabs_max_scroll == 0" ); touch.app.update(|cx| { @@ -744,7 +744,7 @@ fn touch_axis_lock_calendar_month_and_record_sheet_scroll_escape() { let _ = touch.frame(); let max_tabs_scroll = touch.view(|v| v.flow.database_view_tabs_max_scroll("db-tabs")); assert!( - max_tabs_scroll > 400, + max_tabs_scroll > 400.0, "10 views at 390pt must overflow horizontally, got {max_tabs_scroll}" ); touch.app.update(|cx| { diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_ux.rs b/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_ux.rs index fc7ddab783..bafd7a0cbf 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_ux.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/tests_touch_ux.rs @@ -461,8 +461,8 @@ fn touch_scroll_axis_lock_context_menu_keyboard_nav_todo_pulse_and_edgeless_zoom })); touch_page.platform.run_until_parked(); assert_eq!( - touch_page.view(|v| v.touch_scroll_axis_lock), - Some(crate::TouchScrollAxis::Vertical) + touch_page.view(|v| v.scroll_axis_latch.locked()), + Some(blocksuite_editor::scroll::ScrollAxisLock::Vertical) ); touch_page .headless @@ -474,7 +474,7 @@ fn touch_scroll_axis_lock_context_menu_keyboard_nav_todo_pulse_and_edgeless_zoom source: ScrollSource::Touch, })); touch_page.platform.run_until_parked(); - assert_eq!(touch_page.view(|v| v.touch_scroll_axis_lock), None); + assert_eq!(touch_page.view(|v| v.scroll_axis_latch.locked()), None); // Backspace in an empty paragraph below a table on Phone with soft keyboard open // must select the table block instead of skipping across it and deleting above-table text. diff --git a/blocksuite/crates/playground/src/overlays/view_scrollbar.rs b/blocksuite/crates/playground/src/overlays/view_scrollbar.rs index abaccc4a65..d5a6bf0bfa 100644 --- a/blocksuite/crates/playground/src/overlays/view_scrollbar.rs +++ b/blocksuite/crates/playground/src/overlays/view_scrollbar.rs @@ -40,6 +40,9 @@ impl PlaygroundView { window, cx, ); + if self.overlays.is_hscroll_dragging() { + return; + } self.sync_link_popup_for_hover(mx, my, pressed, window, cx); if self.mode == PlaygroundMode::Edgeless { self.on_edgeless_pointer_move(event, window, cx); diff --git a/blocksuite/crates/playground/src/page_scroll.rs b/blocksuite/crates/playground/src/page_scroll.rs new file mode 100644 index 0000000000..a06fac7439 --- /dev/null +++ b/blocksuite/crates/playground/src/page_scroll.rs @@ -0,0 +1,332 @@ +//! Page-mode wheel, trackpad, and touch scroll routing for [`PlaygroundView`]. +//! +//! Keeps world-anchored input popovers (`code_lang_picker`, Database `Select` / `Multi-select`, +//! `bookmark_prompt`, `equation_editor`, `link_field`) from scrolling out of view when the wheel +//! turns over the page, while routing contained touch/pointer scrolls inside scrollable popovers +//! with zero page penetration. + +use ui::{Context, ScrollEvent, Window, px}; + +use crate::{PlaygroundView, SCROLL_LINE, database}; + +impl PlaygroundView { + /// Whether any writable database block currently has a `Select` / `Multi-select` popover open. + pub(crate) fn has_open_select_popover(&self) -> bool { + let Some(block_id) = self.active_database_authoring_block() else { + return false; + }; + let state = self.flow.database_state.state_for(&block_id); + state + .authoring + .active_cell + .as_ref() + .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) + } + + /// Apply a signed vertical scroll delta (logical px) to the currently open Database + /// `Select` / `Multi-select` popover, if any. + pub(crate) fn scroll_open_select_popover(&mut self, dy: f32, cx: &mut Context) -> bool { + if dy == 0.0 { + return false; + } + let Some(block_id) = self.active_database_authoring_block() else { + return false; + }; + let Some(db_data) = self.database_snapshot_data(&block_id) else { + return false; + }; + let auth = self.flow.database_state.authoring_mut(&block_id); + let Some(ed) = auth + .active_cell + .as_ref() + .filter(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) + else { + return false; + }; + let max_scroll = database::select_popover_max_scroll(&db_data, ed); + let mut axis = blocksuite_editor::scroll::ScrollAxis::new(auth.select_scroll_y, max_scroll); + if axis.apply(dy) { + auth.select_scroll_y = axis.offset; + cx.notify(); + true + } else { + false + } + } + + /// Scroll an open Database `Select` / `Multi-select` dropdown popover when the pointer is + /// inside its bounds (contained scroll, never leaking to the page behind it). + pub(crate) fn try_scroll_database_popover( + &mut self, + event: &ScrollEvent, + window: &Window, + cx: &mut Context, + ) -> bool { + let Some(layout) = self.flow_layout() else { + return false; + }; + let Some((_block_id, overlay)) = self.database_popover_overlay(&layout, window) else { + return false; + }; + let (sx, sy) = (f32::from(event.position.x), f32::from(event.position.y)); + if !overlay.bounds.contains(sx, sy) { + return false; + } + let (_, dy) = blocksuite_editor::scroll::wheel_delta(event, overlay.bounds.h); + let _ = self.scroll_open_select_popover(dy, cx); + true + } + + fn has_scroll_blocking_input_popover(&self) -> bool { + self.overlays.code_lang_picker().is_some() + || self.overlays.bookmark_prompt().is_some() + || self.overlays.equation_editor().is_some() + || self.overlays.link_field().is_some() + || self.has_open_select_popover() + } + + fn try_scroll_code_lang_picker(&mut self, event: &ScrollEvent, cx: &mut Context) -> bool { + let Some(rect) = self.overlays.code_lang_picker().and_then(|p| p.rect) else { + return false; + }; + let (sx, sy) = (f32::from(event.position.x), f32::from(event.position.y)); + if !rect.contains(sx, sy) { + return false; + } + let (_, dy) = blocksuite_editor::scroll::wheel_delta(event, rect.h); + if dy != 0.0 + && let Some(picker) = self.overlays.code_lang_picker_mut() + && picker.scroll_by_px(dy) + { + cx.notify(); + } + true + } + + pub(crate) fn on_scroll( + &mut self, + event: &ScrollEvent, + window: &mut Window, + cx: &mut Context, + ) { + self.page_scroll_fling = None; + self.code_scroll_fling = None; + self.popover_scroll_fling = None; + if event.source == ui::ScrollSource::Touch { + if event.touch_phase == ui::TouchPhase::Started + || self.active_touch_owner == crate::TouchStrokeOwner::None + { + if self.has_live_modal_touch_overlay(window, cx) { + self.active_touch_owner = crate::TouchStrokeOwner::ModalOverlay; + let d = event.delta.pixel_delta(px(SCROLL_LINE)); + let x0 = f32::from(event.position.x) - f32::from(d.x); + let y0 = f32::from(event.position.y) - f32::from(d.y); + if let Some((sheet_left, sheet_top, sheet_w, _, _)) = + self.record_sheet_geometry(window) + && let Some(s) = self.database_record_sheet.as_mut() + { + let in_sheet_x = x0 >= sheet_left && x0 <= sheet_left + sheet_w; + if in_sheet_x && y0 >= sheet_top && y0 <= sheet_top + 68.0 { + s.grabber_drag_start_y.get_or_insert(y0); + s.touch_body_drag = false; + } + } else { + self.latch_modal_touch_target(x0, y0, window); + } + } else { + let d = event.delta.pixel_delta(px(SCROLL_LINE)); + let x0 = f32::from(event.position.x) - f32::from(d.x); + let y0 = f32::from(event.position.y) - f32::from(d.y); + if self + .hits_touch_image_resize_handle(x0, y0, window) + .is_some() + { + self.active_touch_owner = crate::TouchStrokeOwner::ImageResize; + } else { + self.active_touch_owner = crate::TouchStrokeOwner::Page; + } + } + } + if self.active_touch_owner == crate::TouchStrokeOwner::ImageResize { + return; + } + if self.active_touch_owner == crate::TouchStrokeOwner::ModalOverlay { + if let Some((_, _, _, _, max_scroll)) = self.record_sheet_geometry(window) { + let drag_in_header = self + .database_record_sheet + .as_ref() + .is_some_and(|s| s.grabber_drag_start_y.is_some()); + if !drag_in_header { + let (_, dy) = + blocksuite_editor::scroll::wheel_delta(event, self.window_size.1); + if let Some(s) = self.database_record_sheet.as_mut() { + s.scroll_fling = None; + let mut axis = + blocksuite_editor::scroll::ScrollAxis::new(s.scroll_y, max_scroll); + if axis.apply(dy) { + s.scroll_y = axis.offset; + cx.notify(); + } + } + } + } else { + let (_, dy) = blocksuite_editor::scroll::wheel_delta(event, self.window_size.1); + match self.modal_touch_target { + crate::touch_interaction::ModalTouchTarget::CodeLangPicker => { + if dy != 0.0 + && let Some(picker) = self.overlays.code_lang_picker_mut() + && picker.scroll_by_px(dy) + { + cx.notify(); + } + } + crate::touch_interaction::ModalTouchTarget::SelectPopover => { + let _ = self.scroll_open_select_popover(dy, cx); + } + crate::touch_interaction::ModalTouchTarget::None => { + if !self.try_scroll_code_lang_picker(event, cx) { + let _ = self.try_scroll_database_popover(event, window, cx); + } + } + } + } + return; + } + } + if self.database_record_sheet.is_some() { + if let Some((_, _, _, _, max_scroll)) = self.record_sheet_geometry(window) { + let drag_in_header = self + .database_record_sheet + .as_ref() + .is_some_and(|s| s.grabber_drag_start_y.is_some()); + if !drag_in_header { + let (_, dy) = blocksuite_editor::scroll::wheel_delta(event, self.window_size.1); + if let Some(s) = self.database_record_sheet.as_mut() { + s.scroll_fling = None; + let mut axis = + blocksuite_editor::scroll::ScrollAxis::new(s.scroll_y, max_scroll); + if axis.apply(dy) { + s.scroll_y = axis.offset; + cx.notify(); + } + } + } + return; + } + self.database_record_sheet = None; + cx.notify(); + } + if self.try_scroll_database_popover(event, window, cx) + || self.try_scroll_code_lang_picker(event, cx) + { + return; + } + if self.has_scroll_blocking_input_popover() { + return; + } + if self.touch_selection_menu_open { + self.touch_selection_menu_open = false; + cx.notify(); + } + let (raw_dx, raw_dy) = blocksuite_editor::scroll::wheel_delta(event, self.window_size.1); + let (mut dx, mut dy) = (raw_dx, raw_dy); + // On Windows/Linux, Shift+wheel delivers a vertical delta with `modifiers.shift`: + // convert it to horizontal scroll for wide tables, code blocks, and databases. + let shift_horizontal = event.source != ui::ScrollSource::Touch + && event.modifiers.shift + && dx.abs() < f32::EPSILON + && dy.abs() > f32::EPSILON; + if shift_horizontal { + dx = dy; + dy = 0.0; + } + // Single-source axis latch shared by Touch and precise Magic Trackpad gestures + // (scheduler-clocked, 160 ms idle reset). Discrete wheel notches bypass latching. + let now_ms = self.now_ms(cx); + let (latched_dx, latched_dy) = self.scroll_axis_latch.filter(event, dx, dy, now_ms); + dx = latched_dx; + dy = latched_dy; + // Horizontal scroll over a touch database view tab strip scrolls the tab strip. + let mut changed = false; + let mut horizontal_consumed = false; + if dx != 0.0 + && self.form_factor.is_touch_form_factor() + && let Some(layout) = self.flow_layout() + { + let geom = self.current_page_geometry(self.window_size.0); + let wx = f32::from(event.position.x) - geom.column_x; + let wy = f32::from(event.position.y) - crate::TOPBAR_HEIGHT + self.scroll_y; + if let Some(block) = layout.blocks.iter().find(|b| { + b.body.kind == crate::block_flow::FlowKind::Database + && b.rect().contains(wx, wy) + && (wy - b.y) >= 34.0 + && (wy - b.y) <= 82.0 + }) { + let block_id = block.block_id.clone(); + let (cur_px, max_px) = self.flow.database_view_tabs_metrics(&block_id); + let logical_dx = if window.layout_direction().is_rtl() { + -dx + } else { + dx + }; + if max_px > 0.0 + && self + .flow + .database_state + .scroll_view_tabs_from(&block_id, cur_px, logical_dx, max_px) + { + changed = true; + horizontal_consumed = true; + } + } + } + // Split-axis routing: dx scrolls unwrapped code/table/database blocks without swallowing dy. + let mut vertical_consumed = false; + if !horizontal_consumed + && let Some((snapshot, layout)) = self.snapshot.clone().zip(self.flow_layout()) + { + let local_collapsed = self.flow.local_collapsed.clone(); + let scene = self.overlay_scene( + &snapshot, + &layout, + window.layout_direction(), + None, + &local_collapsed, + ); + let outcome = self.overlays.scroll_code_split( + &scene, + f32::from(event.position.x), + f32::from(event.position.y), + dx, + dy, + ); + if outcome.changed { + changed = true; + } + horizontal_consumed = outcome.consumed_x; + vertical_consumed = outcome.consumed_y; + } + // When a non-touch horizontal gesture hits the horizontal edge (not consumed), chain + // the original vertical component to the page (overscroll-behavior: auto). + if !vertical_consumed + && !horizontal_consumed + && event.source != ui::ScrollSource::Touch + && !shift_horizontal + && dy == 0.0 + && raw_dy != 0.0 + { + dy = raw_dy; + } + if !vertical_consumed && dy != 0.0 { + let mut page_axis = + blocksuite_editor::scroll::ScrollAxis::new(self.scroll_y, self.max_scroll); + if page_axis.apply(dy) { + self.scroll_y = page_axis.offset; + changed = true; + } + } + if changed { + cx.notify(); + } + } +} diff --git a/blocksuite/crates/playground/src/touch_interaction/mod.rs b/blocksuite/crates/playground/src/touch_interaction/mod.rs index c6933c6ef0..b860fdb47c 100644 --- a/blocksuite/crates/playground/src/touch_interaction/mod.rs +++ b/blocksuite/crates/playground/src/touch_interaction/mod.rs @@ -19,11 +19,20 @@ const FLING_FRICTION: f64 = 3.25; const FLING_MIN_VELOCITY: f32 = 20.0; const TOUCH_CONTROL_HIT_SIZE: f32 = 44.0; -/// Axis lock for a single touch scroll gesture. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum TouchScrollAxis { - Horizontal, - Vertical, +/// Which scrollable floating popover currently owns a touch stroke under `ModalOverlay`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum ModalTouchTarget { + #[default] + None, + CodeLangPicker, + SelectPopover, +} + +/// Target of an active inertial touch fling inside a scrollable floating popover. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum PopoverFlingTarget { + CodeLangPicker, + SelectPopover(String), } /// Stroke-level touch ownership latched at finger-down and held until release so closing a @@ -41,6 +50,7 @@ impl PlaygroundView { pub(crate) fn cancel_flings(&mut self) { self.page_scroll_fling = None; self.code_scroll_fling = None; + self.popover_scroll_fling = None; self.edgeless_pan_fling = None; self.pdf_viewer.scroll_fling_x = None; self.pdf_viewer.scroll_fling_y = None; @@ -50,7 +60,7 @@ impl PlaygroundView { if window.active_touch_count() > 0 { self.cancel_flings(); } else { - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); } let now_ms = self.now_ms(cx); let sheet_geom = if self.database_record_sheet.is_some() { @@ -72,7 +82,7 @@ impl PlaygroundView { match (self.mode, gesture) { (PlaygroundMode::Page, TouchGesture::PanStart { origin, .. }) => { self.cancel_flings(); - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); self.touch_selection_menu_open = false; self.edgeless_readonly_selection_target = None; if self.image_resize_drag.as_ref().is_some_and(|d| d.via_touch) @@ -93,13 +103,13 @@ impl PlaygroundView { } (_, TouchGesture::PanStart { .. } | TouchGesture::PinchStart { .. }) => { self.cancel_flings(); - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); self.touch_selection_menu_open = false; self.edgeless_readonly_selection_target = None; } (PlaygroundMode::Page, TouchGesture::Tap { position, count: 1 }) => { self.cancel_flings(); - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); self.touch_selection_menu_open = false; self.edgeless_readonly_selection_target = None; let (x, y) = (f32::from(position.x), f32::from(position.y)); @@ -149,7 +159,7 @@ impl PlaygroundView { } (PlaygroundMode::Edgeless, TouchGesture::Tap { .. }) => { self.cancel_flings(); - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); self.touch_selection_menu_open = false; self.edgeless_readonly_selection_target = None; } @@ -275,7 +285,7 @@ impl PlaygroundView { .. }, ) => { - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); if self.active_touch_owner == TouchStrokeOwner::ImageResize { if cancelled { self.cancel_image_resize_drag(); @@ -318,7 +328,7 @@ impl PlaygroundView { .. }, ) => { - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); if cancelled { continue; } @@ -378,8 +388,9 @@ impl PlaygroundView { cx.notify(); } self.touch_long_press_anchor = None; - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); self.active_touch_owner = TouchStrokeOwner::None; + self.modal_touch_target = ModalTouchTarget::None; } } @@ -387,9 +398,52 @@ impl PlaygroundView { if self.pdf_viewer.is_open() { self.page_scroll_fling = None; self.code_scroll_fling = None; + self.popover_scroll_fling = None; self.step_pdf_viewer_flings(now_ms, window); return; } + if let Some((target, fling)) = self.popover_scroll_fling.clone() { + let next = fling.value_at(now_ms) as f32; + let (max_scroll, alive) = match &target { + PopoverFlingTarget::CodeLangPicker => { + if let Some(picker) = self.overlays.code_lang_picker_mut() { + let max_s = picker.max_scroll; + picker.scroll_offset = next.clamp(0.0, max_s); + (max_s, true) + } else { + (0.0, false) + } + } + PopoverFlingTarget::SelectPopover(block_id) => { + if let Some(db_data) = self.database_snapshot_data(block_id) { + let auth = self.flow.database_state.authoring_mut(block_id); + if let Some(ed) = auth + .active_cell + .as_ref() + .filter(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) + { + let max_s = crate::database::select_popover_max_scroll(&db_data, ed); + auth.select_scroll_y = next.clamp(0.0, max_s); + (max_s, true) + } else { + (0.0, false) + } + } else { + (0.0, false) + } + } + }; + if !alive + || fling.velocity_at(now_ms).abs() <= fling.stop_velocity + || next <= 0.0 + || next >= max_scroll + { + self.popover_scroll_fling = None; + } else { + window.request_animation_frame(); + } + return; + } if self.database_record_sheet.is_some() { if let Some((_, _, _, _, max_scroll)) = self.record_sheet_geometry(window) { self.page_scroll_fling = None; @@ -398,7 +452,7 @@ impl PlaygroundView { && let Some(fling) = s.scroll_fling { let next = fling.value_at(now_ms) as f32; - let clamped = next.clamp(0.0, max_scroll).round(); + let clamped = next.clamp(0.0, max_scroll); s.scroll_y = clamped; if fling.velocity_at(now_ms).abs() <= fling.stop_velocity || next <= 0.0 @@ -415,7 +469,7 @@ impl PlaygroundView { } if let Some(fling) = self.page_scroll_fling { let next = fling.value_at(now_ms) as f32; - let clamped = next.clamp(0.0, self.max_scroll).round(); + let clamped = next.clamp(0.0, self.max_scroll); self.scroll_y = clamped; if fling.velocity_at(now_ms).abs() <= fling.stop_velocity || next <= 0.0 diff --git a/blocksuite/crates/playground/src/touch_interaction/modal.rs b/blocksuite/crates/playground/src/touch_interaction/modal.rs index a2163284fc..291ff26c32 100644 --- a/blocksuite/crates/playground/src/touch_interaction/modal.rs +++ b/blocksuite/crates/playground/src/touch_interaction/modal.rs @@ -7,13 +7,15 @@ use ui::{Context, InertialDecay, TouchGesture, Window}; use crate::{ PlaygroundView, overlays::{ - GRABBER_DISMISS_THRESHOLD_PT, OverlayEvent, PDF_THUMBNAIL_PANEL_WIDTH, + GRABBER_DISMISS_THRESHOLD_PT, InlineTargetEnd, OverlayEvent, PDF_THUMBNAIL_PANEL_WIDTH, PDF_VIEWER_DESKTOP_HEADER_H, PDF_VIEWER_PHONE_GRABBER_H, PDF_VIEWER_PHONE_HEADER_H, PdfViewerEvent, compute_pdf_thumbnail_layout, }, }; -use super::{FLING_FRICTION, FLING_MIN_VELOCITY, TouchStrokeOwner}; +use super::{ + FLING_FRICTION, FLING_MIN_VELOCITY, ModalTouchTarget, PopoverFlingTarget, TouchStrokeOwner, +}; impl PlaygroundView { pub(crate) fn has_live_modal_touch_overlay( @@ -30,11 +32,33 @@ impl PlaygroundView { } self.pdf_viewer.is_open() || self.overlays.image_lightbox().is_some() + || self.overlays.code_lang_picker().is_some() + || self.has_open_select_popover() || self.overlays.bookmark_prompt().is_some() || self.overlays.equation_editor().is_some() || self.overlays.link_field().is_some() } + pub(crate) fn latch_modal_touch_target(&mut self, x: f32, y: f32, window: &Window) { + if self + .overlays + .code_lang_picker() + .and_then(|p| p.rect) + .is_some_and(|r| r.contains(x, y)) + { + self.modal_touch_target = ModalTouchTarget::CodeLangPicker; + } else if self.has_open_select_popover() + && self + .flow_layout() + .and_then(|layout| self.database_popover_overlay(&layout, window)) + .is_some_and(|(_, ov)| ov.bounds.contains(x, y)) + { + self.modal_touch_target = ModalTouchTarget::SelectPopover; + } else { + self.modal_touch_target = ModalTouchTarget::None; + } + } + pub(super) fn handle_modal_touch_gestures( &mut self, sheet_geom: Option<(f32, f32, f32, f32, f32)>, @@ -57,8 +81,8 @@ impl PlaygroundView { match gesture { TouchGesture::PanStart { origin, .. } => { self.active_touch_owner = TouchStrokeOwner::ModalOverlay; + let (x, y) = (f32::from(origin.x), f32::from(origin.y)); if let Some((sheet_left, sheet_top, sheet_w, _, _)) = sheet_geom { - let (x, y) = (f32::from(origin.x), f32::from(origin.y)); if let Some(s) = self.database_record_sheet.as_mut() { s.scroll_fling = None; let in_sheet_x = x >= sheet_left && x <= sheet_left + sheet_w; @@ -73,15 +97,34 @@ impl PlaygroundView { s.touch_body_drag = false; } } + } else { + self.latch_modal_touch_target(x, y, window); } } TouchGesture::Tap { position, count: 1 } => { + let (x, y) = (f32::from(position.x), f32::from(position.y)); if let Some((sheet_left, sheet_top, sheet_w, _, _)) = sheet_geom { - let (x, y) = (f32::from(position.x), f32::from(position.y)); let outside = y < sheet_top || x < sheet_left || x > sheet_left + sheet_w; if outside { self.close_database_record_sheet(cx); } + } else if let Some(rect) = self.overlays.code_lang_picker().and_then(|p| p.rect) + { + if !rect.contains(x, y) { + self.overlays.close_code_lang_picker(now_ms); + cx.notify(); + } + } else if self.has_open_select_popover() + && self + .flow_layout() + .and_then(|layout| self.database_popover_overlay(&layout, window)) + .is_some_and(|(_, ov)| !ov.bounds.contains(x, y)) + { + self.finish_inline_targets( + InlineTargetEnd::CommitPreedit, + Some(window), + Some(cx), + ); } } TouchGesture::PanUpdate { position, .. } => { @@ -102,7 +145,8 @@ impl PlaygroundView { cancelled, .. } => { - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); + let target = std::mem::take(&mut self.modal_touch_target); let y = f32::from(position.y); let vy = f32::from(velocity.y); let header_start = self @@ -131,6 +175,52 @@ impl PlaygroundView { now_ms, )); window.request_animation_frame(); + } else if !cancelled && vy.abs() >= FLING_MIN_VELOCITY { + match target { + ModalTouchTarget::CodeLangPicker => { + if let Some(picker) = self.overlays.code_lang_picker() + && picker.max_scroll > 0.0 + { + self.popover_scroll_fling = Some(( + PopoverFlingTarget::CodeLangPicker, + InertialDecay::new( + f64::from(picker.scroll_offset), + -f64::from(vy), + FLING_FRICTION, + now_ms, + ), + )); + window.request_animation_frame(); + } + } + ModalTouchTarget::SelectPopover => { + if let Some(block_id) = self.active_database_authoring_block() + && let Some(db_data) = self.database_snapshot_data(&block_id) + { + let st = self.flow.database_state.state_for(&block_id); + if let Some(ed) = + st.authoring.active_cell.as_ref().filter(|e| { + matches!(e.col_type.as_str(), "select" | "multi-select") + }) + && crate::database::select_popover_max_scroll(&db_data, ed) + > 0.0 + { + let cur = st.authoring.select_scroll_y; + self.popover_scroll_fling = Some(( + PopoverFlingTarget::SelectPopover(block_id), + InertialDecay::new( + f64::from(cur), + -f64::from(vy), + FLING_FRICTION, + now_ms, + ), + )); + window.request_animation_frame(); + } + } + } + ModalTouchTarget::None => {} + } } } _ => {} @@ -144,8 +234,9 @@ impl PlaygroundView { cx.notify(); } self.touch_long_press_anchor = None; - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); self.active_touch_owner = TouchStrokeOwner::None; + self.modal_touch_target = ModalTouchTarget::None; } } @@ -178,7 +269,7 @@ impl PlaygroundView { ); } TouchGesture::PanEnd { .. } => { - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); self.dispatch_overlay(OverlayEvent::ImageLightboxDragEnd, window, cx); } TouchGesture::PinchStart { .. } => { @@ -294,7 +385,7 @@ impl PlaygroundView { cancelled, .. } => { - self.touch_scroll_axis_lock = None; + self.scroll_axis_latch.reset_touch(); let was_body_pan = self.pdf_viewer.pan_drag_last.take().is_some(); self.pdf_viewer.thumb_drag_last = None; if let Some(y0) = self.pdf_viewer.grabber_drag_start_y.take() { diff --git a/blocksuite/crates/playground/src/touch_selection/mod.rs b/blocksuite/crates/playground/src/touch_selection/mod.rs index f4cd08f960..966490bca1 100644 --- a/blocksuite/crates/playground/src/touch_selection/mod.rs +++ b/blocksuite/crates/playground/src/touch_selection/mod.rs @@ -194,7 +194,7 @@ impl PlaygroundView { || self.page_scroll_fling.is_some() || self.code_scroll_fling.is_some() || self.edgeless_pan_fling.is_some() - || self.touch_scroll_axis_lock.is_some() + || self.scroll_axis_latch.locked().is_some() || window.active_touch_count() > 0 }