diff --git a/blocksuite/crates/editor/src/block_flow/layout.rs b/blocksuite/crates/editor/src/block_flow/layout.rs index 0a1a78c88e..5c2d2eef42 100644 --- a/blocksuite/crates/editor/src/block_flow/layout.rs +++ b/blocksuite/crates/editor/src/block_flow/layout.rs @@ -23,6 +23,7 @@ pub struct BlockFlow { database_authoring_hits: HashMap>, database_popover_anchors: HashMap, database_active_cells: HashMap, + database_overflow_tabs: 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). @@ -55,6 +56,7 @@ pub(super) struct FlowPass<'a> { pub(super) database_authoring_hits: HashMap>, 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) code_preview_blocks: &'a BTreeSet, pub(super) local_collapsed: &'a BTreeSet, @@ -114,6 +116,13 @@ impl BlockFlow { .and_then(|c| c.rich_hit.as_ref()) } + /// Overflow view indices computed for `block_id`'s desktop `"N More"` view menu. + pub fn database_overflow_tabs(&self, block_id: &str) -> &[usize] { + self.database_overflow_tabs + .get(block_id) + .map_or(&[], Vec::as_slice) + } + /// 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) { self.database_view_tabs_max_scroll @@ -160,6 +169,7 @@ impl BlockFlow { database_authoring_hits: std::mem::take(&mut self.database_authoring_hits), database_popover_anchors: std::mem::take(&mut self.database_popover_anchors), database_active_cells: std::mem::take(&mut self.database_active_cells), + database_overflow_tabs: std::mem::take(&mut self.database_overflow_tabs), database_view_tabs_max_scroll: std::mem::take(&mut self.database_view_tabs_max_scroll), code_preview_blocks: &self.code_preview_blocks, local_collapsed: &self.local_collapsed, @@ -227,6 +237,7 @@ impl BlockFlow { self.database_authoring_hits = pass.database_authoring_hits; self.database_popover_anchors = pass.database_popover_anchors; self.database_active_cells = pass.database_active_cells; + self.database_overflow_tabs = pass.database_overflow_tabs; self.database_view_tabs_max_scroll = pass.database_view_tabs_max_scroll; FlowLayout { blocks: pass.blocks, @@ -274,6 +285,7 @@ impl BlockFlow { database_authoring_hits: std::mem::take(&mut self.database_authoring_hits), database_popover_anchors: std::mem::take(&mut self.database_popover_anchors), database_active_cells: std::mem::take(&mut self.database_active_cells), + database_overflow_tabs: std::mem::take(&mut self.database_overflow_tabs), database_view_tabs_max_scroll: std::mem::take(&mut self.database_view_tabs_max_scroll), code_preview_blocks: &self.code_preview_blocks, local_collapsed: &self.local_collapsed, @@ -299,6 +311,7 @@ impl BlockFlow { self.database_authoring_hits = pass.database_authoring_hits; self.database_popover_anchors = pass.database_popover_anchors; self.database_active_cells = pass.database_active_cells; + self.database_overflow_tabs = pass.database_overflow_tabs; self.database_view_tabs_max_scroll = pass.database_view_tabs_max_scroll; FlowLayout { blocks: pass.blocks, diff --git a/blocksuite/crates/editor/src/block_flow/table_block.rs b/blocksuite/crates/editor/src/block_flow/table_block.rs index fd2683a70d..95c888280c 100644 --- a/blocksuite/crates/editor/src/block_flow/table_block.rs +++ b/blocksuite/crates/editor/src/block_flow/table_block.rs @@ -235,6 +235,12 @@ impl FlowPass<'_> { } else { self.database_active_cells.remove(block_id); } + if output.overflow_tabs.is_empty() { + self.database_overflow_tabs.remove(block_id); + } else { + self.database_overflow_tabs + .insert(block_id.to_string(), output.overflow_tabs); + } self.database_view_tabs_max_scroll.insert( block_id.to_string(), (output.view_tabs_scroll_px, output.view_tabs_max_scroll_px), diff --git a/blocksuite/crates/editor/src/database/authoring.rs b/blocksuite/crates/editor/src/database/authoring.rs index 49a66f7cdf..b7f319eee7 100644 --- a/blocksuite/crates/editor/src/database/authoring.rs +++ b/blocksuite/crates/editor/src/database/authoring.rs @@ -49,7 +49,7 @@ pub struct ProgressScrubPreview { pub value: i64, } -/// Active in-place cell editor (Table or Kanban). +/// Active in-place cell editor (Table, Kanban, or Calendar). #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ActiveCellEditor { pub row_id: String, @@ -58,6 +58,7 @@ pub struct ActiveCellEditor { pub draft: String, pub error: Option, pub select_filter: String, + pub calendar_day_index: Option, } /// Currently open top toolbar dropdown panel. @@ -230,6 +231,9 @@ pub enum DatabaseAuthoringHitKind { CalendarDayDropTarget { day_index: i64, }, + SwitchView { + view_id: String, + }, } /// One positioned authoring hit target in block-local coordinates. @@ -553,6 +557,7 @@ pub fn handle_authoring_key( draft: next_draft, error: None, select_filter: String::new(), + calendar_day_index: None, }); return Ok(AuthoringActionResult { handled: true, @@ -623,6 +628,13 @@ pub fn handle_authoring_key( } } + if key == DatabaseAuthoringKey::Escape && flow_state.close_more_views(block_id) { + return Ok(AuthoringActionResult { + handled: true, + doc_mutated: false, + }); + } + Ok(AuthoringActionResult { handled: false, doc_mutated: false, diff --git a/blocksuite/crates/editor/src/database/authoring_dispatch.rs b/blocksuite/crates/editor/src/database/authoring_dispatch.rs index b8b1a4e564..04bced8bfe 100644 --- a/blocksuite/crates/editor/src/database/authoring_dispatch.rs +++ b/blocksuite/crates/editor/src/database/authoring_dispatch.rs @@ -278,6 +278,7 @@ pub fn handle_authoring_hit( draft, error: None, select_filter: String::new(), + calendar_day_index: None, }); Ok(AuthoringActionResult { handled: true, @@ -624,6 +625,7 @@ pub fn handle_authoring_hit( draft: String::new(), error: None, select_filter: String::new(), + calendar_day_index: None, }); Ok(AuthoringActionResult { handled: true, @@ -643,7 +645,7 @@ pub fn handle_authoring_hit( &view, data, &row_id, - "New Event", + "", *day_index, offset_at_ms, now_ms, @@ -660,9 +662,10 @@ pub fn handle_authoring_hit( row_id, column_id: title_col_id, col_type: "title".to_string(), - draft: "New Event".to_string(), + draft: String::new(), error: None, select_filter: String::new(), + calendar_day_index: Some(*day_index), }); } Ok(AuthoringActionResult { @@ -670,6 +673,14 @@ pub fn handle_authoring_hit( doc_mutated: mutated, }) } + DatabaseAuthoringHitKind::SwitchView { view_id } => { + flow_state.set_active_view(block_id, view_id.clone()); + flow_state.authoring_mut(block_id).dismiss_popovers(); + Ok(AuthoringActionResult { + handled: true, + doc_mutated: false, + }) + } DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, day_index } => { flow_state.authoring_mut(block_id).calendar_drag = Some(CalendarDragState { row_id: row_id.clone(), diff --git a/blocksuite/crates/editor/src/database/calendar_edit.rs b/blocksuite/crates/editor/src/database/calendar_edit.rs index d764507f2c..81ff278c40 100644 --- a/blocksuite/crates/editor/src/database/calendar_edit.rs +++ b/blocksuite/crates/editor/src/database/calendar_edit.rs @@ -12,10 +12,66 @@ use blocksuite_playground_doc::{ use crate::block_flow::{FlowRect, FormFactor, civil_from_days}; use super::{ - DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseUiState, local_day_index, + CalendarEntry, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseUiState, + local_day_index, render::{DatabasePrim, DbRenderCtx}, + resolve_rich_text_plain, }; +pub(super) fn collect_calendar_entries( + ctx: &DbRenderCtx<'_>, + start_col_id: &str, + end_col_id: Option<&str>, +) -> Vec { + ctx.rows + .iter() + .filter_map(|row| { + let start_at = ctx + .data + .cells + .get(&(row.row_id.clone(), start_col_id.to_string())) + .and_then(DatabaseCellValue::as_i64)?; + let end_at = end_col_id.and_then(|eid| { + ctx.data + .cells + .get(&(row.row_id.clone(), eid.to_string())) + .and_then(DatabaseCellValue::as_i64) + .filter(|&e| e >= start_at) + }); + let color = ctx + .data + .columns + .iter() + .find(|c| c.column_type == "select") + .and_then(|c| { + let val = ctx + .data + .cells + .get(&(row.row_id.clone(), c.id.clone())) + .and_then(DatabaseCellValue::as_str)?; + c.select_options() + .into_iter() + .find(|o| o.id == val || o.value == val) + .map(|o| o.color) + }); + let resolved_title = resolve_rich_text_plain(&row.title, ctx.page_titles); + Some(CalendarEntry { + id: format!("database:{}", row.row_id), + row_id: row.row_id.clone(), + title: if resolved_title.trim().is_empty() { + "Untitled".to_string() + } else { + resolved_title + }, + color, + start_at_ms: start_at, + end_at_ms: end_at, + badges: Vec::new(), + }) + }) + .collect() +} + /// Single authoritative resolver for a Calendar view's displayed `(year, month 1..=12)`, /// shared by `render_calendar_view`, `layout_database_block`, and `PlaygroundView`. pub fn resolve_calendar_display_month( diff --git a/blocksuite/crates/editor/src/database/mod.rs b/blocksuite/crates/editor/src/database/mod.rs index f697ad3e7a..f718b41c72 100644 --- a/blocksuite/crates/editor/src/database/mod.rs +++ b/blocksuite/crates/editor/src/database/mod.rs @@ -222,9 +222,24 @@ impl DatabaseFlowState { pub fn toggle_more_views(&mut self, block_id: &str) { let entry = self.ui_states.entry(block_id.to_string()).or_default(); entry.more_views_open = !entry.more_views_open; + if entry.more_views_open { + entry.authoring.dismiss_popovers(); + } self.revision = self.revision.wrapping_add(1); } + pub fn close_more_views(&mut self, block_id: &str) -> bool { + let Some(entry) = self.ui_states.get_mut(block_id) else { + return false; + }; + if !entry.more_views_open { + return false; + } + entry.more_views_open = false; + self.revision = self.revision.wrapping_add(1); + true + } + pub fn scroll_view_tabs(&mut self, block_id: &str, delta_px: i32, max_px: i32) -> bool { let entry = self.ui_states.entry(block_id.to_string()).or_default(); entry.reveal_active_tab = false; diff --git a/blocksuite/crates/editor/src/database/popover_overlay.rs b/blocksuite/crates/editor/src/database/popover_overlay.rs index 6c073246fa..5cb78505d7 100644 --- a/blocksuite/crates/editor/src/database/popover_overlay.rs +++ b/blocksuite/crates/editor/src/database/popover_overlay.rs @@ -8,16 +8,16 @@ use blocksuite_playground_doc::read::DatabaseData; use ui::{Direction, Window}; use crate::{ - block_flow::{FlowRect, FormFactor}, + block_flow::{FlowRect, FormFactor, InlineStyle}, overlays::{Placement, place_popover}, - theme::PlaygroundTheme, + theme::{FONT_SANS, PlaygroundTheme, TYPOGRAPHY}, }; use super::{ DatabaseUiState, - authoring::{DatabaseAuthoringHit, DatabasePopoverAnchor}, + authoring::{DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePopoverAnchor}, cell_editor, column_ops, eval_database_filter_with_titles, filter_sort_bar, - render::{DatabasePrim, DbRenderCtx}, + render::{DatabasePrim, DbRenderCtx, tab_label_for}, sort_database_rows_with_titles, }; @@ -43,8 +43,10 @@ pub fn layout_database_popover_overlay( data: &DatabaseData, ui_state: &DatabaseUiState, block_screen_origin: (f32, f32), + block_width: f32, scroll_x: f32, anchor: Option, + overflow_tabs: &[usize], window_size: (f32, f32), topbar_h: f32, theme: PlaygroundTheme, @@ -56,15 +58,16 @@ pub fn layout_database_popover_overlay( page_titles: &BTreeMap, window: &Window, ) -> Option { - if mobile_readonly { - return None; - } let auth = &ui_state.authoring; - let has_select = auth - .active_cell - .as_ref() - .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select")); - if auth.column_menu.is_none() && !has_select && auth.toolbar_panel.is_none() { + let has_select = !mobile_readonly + && auth + .active_cell + .as_ref() + .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select")); + let has_writable_popover = !mobile_readonly + && (auth.column_menu.is_some() || has_select || auth.toolbar_panel.is_some()); + let has_more_views = !form_factor.is_touch_form_factor() && ui_state.more_views_open; + if !has_writable_popover && !has_more_views { return None; } @@ -100,7 +103,7 @@ pub fn layout_database_popover_overlay( palette, direction, form_factor, - width: window_size.0, + width: block_width.max(1.0), mobile_readonly, now_ms, offset_at_ms, @@ -132,7 +135,7 @@ pub fn layout_database_popover_overlay( let mut prims = Vec::new(); let mut hits = Vec::new(); - let (bounds, text_input_rect) = if let Some(menu) = &auth.column_menu { + let (bounds, text_input_rect) = if !mobile_readonly && let Some(menu) = &auth.column_menu { let size = column_ops::measure_column_menu_size(&ctx, menu); let placed = place_popover( anchor_screen, @@ -151,10 +154,11 @@ pub fn layout_database_popover_overlay( &mut hits, ); (placed.rect, Some(input_rect)) - } else if let Some(ed) = auth - .active_cell - .as_ref() - .filter(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) + } else if !mobile_readonly + && let Some(ed) = auth + .active_cell + .as_ref() + .filter(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) { let size = cell_editor::measure_select_popover_size(&ctx, ed)?; let placed = place_popover( @@ -168,7 +172,7 @@ pub fn layout_database_popover_overlay( let input_rect = cell_editor::render_select_popover_at(&ctx, ed, placed.rect, &mut prims, &mut hits); (placed.rect, input_rect) - } else if let Some(panel) = auth.toolbar_panel { + } else if !mobile_readonly && let Some(panel) = auth.toolbar_panel { let size = filter_sort_bar::measure_toolbar_panel_size(&ctx, active_view, panel); let placed = place_popover( anchor_screen, @@ -187,6 +191,30 @@ pub fn layout_database_popover_overlay( &mut hits, ); (placed.rect, input_rect) + } else if has_more_views { + if overflow_tabs.is_empty() { + return None; + } + let item_h = 30.0_f32; + let menu_w = 180.0_f32.min((ctx.width - 16.0).max(120.0)); + let menu_h = overflow_tabs.len() as f32 * item_h + 8.0; + let placed = place_popover( + anchor_screen, + (menu_w, menu_h), + viewport, + Placement::BelowStart, + 4.0, + 8.0, + ); + render_more_views_popover_at( + &ctx, + active_view, + overflow_tabs, + placed.rect, + &mut prims, + &mut hits, + ); + (placed.rect, None) } else { return None; }; @@ -198,3 +226,68 @@ pub fn layout_database_popover_overlay( text_input_rect, }) } + +fn render_more_views_popover_at( + ctx: &DbRenderCtx<'_>, + active_view: &blocksuite_playground_doc::read::DatabaseView, + overflow: &[usize], + menu_rect: FlowRect, + prims: &mut Vec, + hits: &mut Vec, +) { + let item_h = 30.0_f32; + prims.push(DatabasePrim::Quad { + rect: menu_rect, + fill: Some(ctx.palette.panel), + border: Some(ctx.palette.border), + radius: 8.0, + dashed: false, + }); + for (row_idx, &tab_idx) in overflow.iter().enumerate() { + let Some(view) = ctx.data.views.get(tab_idx) else { + continue; + }; + let is_active = view.id == active_view.id; + let label = tab_label_for(view); + let item_rect = FlowRect::new( + menu_rect.x + 4.0, + menu_rect.y + 4.0 + row_idx as f32 * item_h, + (menu_rect.w - 8.0).max(1.0), + item_h, + ); + if is_active { + prims.push(DatabasePrim::Quad { + rect: item_rect, + fill: Some(ctx.palette.hover), + border: None, + radius: 4.0, + dashed: false, + }); + } + let row_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + if is_active { 500.0 } else { 400.0 }, + if is_active { + ctx.palette.text_primary + } else { + ctx.palette.text_secondary + }, + ); + let (_, row_layout) = + ctx.truncate_text(label, row_style, (item_rect.w - 16.0).max(1.0), item_h); + prims.push(DatabasePrim::Text { + x: item_rect.x + 8.0, + y: item_rect.y, + layout: row_layout, + clip: Some(item_rect), + }); + hits.push(DatabaseAuthoringHit { + rect: item_rect, + kind: DatabaseAuthoringHitKind::SwitchView { + view_id: view.id.clone(), + }, + scrolls_x: false, + }); + } +} diff --git a/blocksuite/crates/editor/src/database/render.rs b/blocksuite/crates/editor/src/database/render.rs index be3f77207b..e2b8501d55 100644 --- a/blocksuite/crates/editor/src/database/render.rs +++ b/blocksuite/crates/editor/src/database/render.rs @@ -117,18 +117,6 @@ pub fn layout_database_block( .css_var("--affine-hover-color-filled") .unwrap_or(palette.hover); - fn tab_label_for(view: &DatabaseView) -> &str { - if view.name.is_empty() { - match view.mode { - DatabaseViewMode::Table => "Table View", - DatabaseViewMode::Kanban => "Kanban View", - DatabaseViewMode::Calendar => "Calendar View", - DatabaseViewMode::Unknown(ref s) => s.as_str(), - } - } else { - view.name.as_str() - } - } let icon_for = |mode: &DatabaseViewMode| match mode { DatabaseViewMode::Table => "SquareIcon", DatabaseViewMode::Kanban => "FrameIcon", @@ -138,7 +126,6 @@ pub fn layout_database_block( struct MeasuredTab<'a> { view: &'a DatabaseView, - label: &'a str, is_active: bool, w: f32, layout: Rc, @@ -193,7 +180,6 @@ pub fn layout_database_block( }; measured_tabs.push(MeasuredTab { view, - label, is_active, w: tab_w, layout, @@ -276,6 +262,8 @@ pub fn layout_database_block( let mut authoring_hits = Vec::new(); let mut inline_toolbar_anchor: Option = None; + 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; @@ -314,8 +302,8 @@ pub fn layout_database_block( cursor += tab.w + tab_gap; } } else { - // Desktop: single horizontal toolbar row (`databaseToolbarRowStyles`): - // view tabs on the left, borderless Filter / Sort / Group triggers on the right. + // Desktop: single horizontal toolbar row when wide enough; wraps Filter/Sort/Group onto + // a dedicated second row on narrow containers (`390px`) so tabs never collide with tools. let inline_ctx = DbRenderCtx { data, view: active_view, @@ -333,6 +321,7 @@ pub fn layout_database_block( window, }; let mut inline_tool_prims = Vec::new(); + let mut inline_tool_hits = Vec::new(); let (tools_w, anchor) = filter_sort_bar::render_inline_toolbar_triggers( &inline_ctx, active_view, @@ -340,35 +329,50 @@ pub fn layout_database_block( tab_h, strip_right, &mut inline_tool_prims, - &mut authoring_hits, + &mut inline_tool_hits, ); - inline_toolbar_anchor = anchor; - let tabs_right = if tools_w > 0.0 { + let active_idx = measured_tabs.iter().position(|t| t.is_active).unwrap_or(0); + let active_w = measured_tabs.get(active_idx).map_or(72.0, |t| t.w); + let more_reserve = if measured_tabs.len() > 1 { + 68.0 + tab_gap + } else { + 0.0 + }; + let min_inline_tabs_w = active_w + more_reserve + 12.0; + if tools_w > 0.0 && strip_w < tools_w + min_inline_tabs_w { + wrap_toolbar_below = true; + } + let tabs_right = if !wrap_toolbar_below && tools_w > 0.0 { (strip_right - tools_w - 12.0).max(strip_left + 72.0) } else { strip_right }; - let more_reserve = 72.0_f32; + let tab_widths: Vec = measured_tabs.iter().map(|t| t.w).collect(); + let (visible_tabs, over) = + partition_desktop_view_tabs(&tab_widths, active_idx, tabs_right - strip_left, tab_gap); + overflow_tabs = over; let mut cursor = strip_left; - for (idx, tab) in measured_tabs.iter().enumerate() { - let remaining = measured_tabs.len() - idx - 1; - let limit = if remaining > 0 { - tabs_right - more_reserve - tab_gap - } else { - tabs_right - }; - if cursor + tab.w <= limit || idx == 0 { - emit_tab(tab, cursor, y, None); - cursor += tab.w + tab_gap; - } else { - overflow_tabs.push(idx); - } + for idx in visible_tabs { + let tab = &measured_tabs[idx]; + emit_tab( + tab, + cursor, + y, + Some(axis.map_rect(FlowRect::new(strip_left, y, tabs_right - strip_left, tab_h))), + ); + cursor += tab.w + tab_gap; + } + if !wrap_toolbar_below { + inline_toolbar_anchor = anchor; + prims.extend(inline_tool_prims); + authoring_hits.extend(inline_tool_hits); } - prims.extend(inline_tool_prims); if !overflow_tabs.is_empty() { let more_label = format!("{} More", overflow_tabs.len()); let more_w = 68.0_f32.min((tabs_right - cursor).max(52.0)); - let more_rect = axis.map_rect(FlowRect::new(cursor, y, more_w, tab_h)); + let more_x = cursor.min((tabs_right - more_w).max(strip_left)); + let more_rect = axis.map_rect(FlowRect::new(more_x, y, more_w, tab_h)); + more_views_anchor = Some(more_rect); if ui_state.more_views_open { prims.push(DatabasePrim::Quad { rect: more_rect, @@ -408,76 +412,6 @@ pub fn layout_database_block( } y += tab_h + 8.0; - if !is_touch && ui_state.more_views_open && !overflow_tabs.is_empty() { - let menu_w = 180.0_f32.min(strip_w); - let item_h = 30.0_f32; - let menu_h = overflow_tabs.len() as f32 * item_h + 8.0; - let menu_rect = axis.map_rect(FlowRect::new( - (strip_right - menu_w).max(strip_left), - y - 4.0, - menu_w, - menu_h, - )); - prims.push(DatabasePrim::Quad { - rect: menu_rect, - fill: Some(palette.panel), - border: Some(palette.border), - radius: 8.0, - dashed: false, - }); - for (row_idx, &tab_idx) in overflow_tabs.iter().enumerate() { - let tab = &measured_tabs[tab_idx]; - let item_rect = FlowRect::new( - menu_rect.x + 4.0, - menu_rect.y + 4.0 + row_idx as f32 * item_h, - (menu_rect.w - 8.0).max(1.0), - item_h, - ); - if tab.is_active { - prims.push(DatabasePrim::Quad { - rect: item_rect, - fill: Some(palette.hover), - border: None, - radius: 4.0, - dashed: false, - }); - } - let row_style = InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px + 1.0, - if tab.is_active { 500.0 } else { 400.0 }, - if tab.is_active { - palette.text_primary - } else { - palette.text_secondary - }, - ); - let row_layout = Rc::new(layout_inline( - tab.label, - &row_style, - (item_rect.w - 16.0).max(1.0), - item_h, - InlineBaseline::Of(&row_style), - InlineAlign::Left, - window, - )); - prims.push(DatabasePrim::Text { - x: item_rect.x + 8.0, - y: item_rect.y, - layout: row_layout, - clip: Some(item_rect), - }); - hits.push(DatabaseHitTarget { - rect: item_rect, - kind: DatabaseHitKind::SwitchView { - view_id: tab.view.id.clone(), - }, - scrolls_x: false, - }); - } - y += menu_h + 6.0; - } - // 3. Optional mobile read-only notice banner. if mobile_readonly && ui_state.mobile_readonly_notice { let banner_h = 34.0; @@ -547,9 +481,9 @@ pub fn layout_database_block( }; // 4b. Active Filter/Sort chips on Desktop (triggers already sit inline on the tab row) or - // compact wrapping toolbar on Touch. Open dropdown panels render in screen-space `Overlays` - // so opening a panel never changes the `affine:database` block height. - let (y, toolbar_anchor) = if is_touch { + // compact wrapping toolbar on Touch / narrow Desktop containers. Open dropdown panels + // render in screen-space `Overlays` so opening a panel never changes block height. + let (y, toolbar_anchor) = if is_touch || wrap_toolbar_below { filter_sort_bar::render_view_toolbar(&ctx, active_view, y, &mut prims, &mut authoring_hits) } else { let next_y = filter_sort_bar::render_active_rule_chips( @@ -585,12 +519,17 @@ pub fn layout_database_block( .and_then(|ed| { vah.iter().find_map(|hit| match &hit.kind { super::DatabaseAuthoringHitKind::CalendarDragEventStart { - row_id, .. - } if row_id == &ed.row_id => Some(super::DatabaseActiveCellLayout { - rect: hit.rect, - scrolls_x: false, - rich_hit: None, - }), + row_id, + day_index, + } if row_id == &ed.row_id + && ed.calendar_day_index.is_none_or(|d| d == *day_index) => + { + Some(super::DatabaseActiveCellLayout { + rect: hit.rect, + scrolls_x: false, + rich_hit: None, + }) + } _ => None, }) }); @@ -627,6 +566,11 @@ pub fn layout_database_block( rect, scrolls_x: false, }) + } else if ui_state.more_views_open && !overflow_tabs.is_empty() { + more_views_anchor.map(|rect| DatabasePopoverAnchor { + rect, + scrolls_x: false, + }) } else { None }; @@ -691,7 +635,60 @@ pub fn layout_database_block( authoring_hits, popover_anchor, active_cell, + overflow_tabs, view_tabs_scroll_px, view_tabs_max_scroll_px, } } + +pub(super) fn tab_label_for(view: &DatabaseView) -> &str { + if view.name.is_empty() { + match view.mode { + DatabaseViewMode::Table => "Table View", + DatabaseViewMode::Kanban => "Kanban View", + DatabaseViewMode::Calendar => "Calendar View", + DatabaseViewMode::Unknown(ref s) => s.as_str(), + } + } else { + view.name.as_str() + } +} + +/// Partition desktop view tabs into `(visible_indices, overflow_indices)` within `avail_w`, +/// guaranteeing that `active_idx` always stays visible in natural order rather than hiding behind +/// an inactive index-0 tab. +pub(super) fn partition_desktop_view_tabs( + tab_widths: &[f32], + active_idx: usize, + avail_w: f32, + tab_gap: f32, +) -> (Vec, Vec) { + if tab_widths.is_empty() { + return (Vec::new(), Vec::new()); + } + let total_w: f32 = + tab_widths.iter().sum::() + tab_widths.len().saturating_sub(1) as f32 * tab_gap; + if total_w <= avail_w + 0.5 { + return ((0..tab_widths.len()).collect(), Vec::new()); + } + let active_idx = active_idx.min(tab_widths.len() - 1); + let more_reserve = 68.0_f32 + tab_gap; + let limit = (avail_w - more_reserve).max(tab_widths[active_idx]); + let mut visible = Vec::with_capacity(tab_widths.len()); + let mut overflow = Vec::new(); + let mut used = tab_widths[active_idx]; + for (idx, &w) in tab_widths.iter().enumerate() { + if idx == active_idx { + visible.push(idx); + continue; + } + let step = w + tab_gap; + if used + step <= limit + 0.5 { + used += step; + visible.push(idx); + } else { + overflow.push(idx); + } + } + (visible, overflow) +} diff --git a/blocksuite/crates/editor/src/database/render_calendar.rs b/blocksuite/crates/editor/src/database/render_calendar.rs index 6078c41c4b..5547bea74b 100644 --- a/blocksuite/crates/editor/src/database/render_calendar.rs +++ b/blocksuite/crates/editor/src/database/render_calendar.rs @@ -1,8 +1,6 @@ //! Calendar view renderer for `affine:database` (`0.27.5` `calendar/layout.ts` & //! `calendar-view-manager.ts`). -use blocksuite_playground_doc::read::DatabaseCellValue; - use crate::{ block_flow::{FlowRect, InlineAlign, InlineStyle, civil_from_days}, theme::{FONT_SANS, TYPOGRAPHY}, @@ -12,7 +10,7 @@ use super::{ CalendarEntry, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseHitKind, DatabaseHitTarget, InlineAxis, create_calendar_month_layout, isolate_ltr, local_day_index, render::{DatabasePrim, DbRenderCtx}, - resolve_rich_text_plain, resolve_tag_accent, + resolve_tag_accent, }; const PAD_X: f32 = 8.0; @@ -37,6 +35,7 @@ fn push_calendar_event_chip( draw_stripe: bool, text_pad_x: f32, drag_start_day: Option, + hide_active_chip: &mut Option<(&str, Option)>, prims: &mut Vec, hits: &mut Vec, authoring_hits: &mut Vec, @@ -71,20 +70,29 @@ fn push_calendar_event_chip( } else { InlineAlign::Left }; - prims.push(ctx.single_line_clipped( - &entry.title, - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - 500.0, - ctx.palette.text_primary, - ), - rect.x + text_pad_x, - rect.y, - (rect.w - text_pad_x - 4.0).max(1.0), - EVENT_CHIP_HEIGHT, - align, - )); + let should_hide_title = hide_active_chip.is_some_and(|(active_row, active_day)| { + active_row == entry.row_id + && drag_start_day.is_some() + && active_day.is_none_or(|d| Some(d) == drag_start_day) + }); + if should_hide_title { + *hide_active_chip = None; + } else { + prims.push(ctx.single_line_clipped( + &entry.title, + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 500.0, + ctx.palette.text_primary, + ), + rect.x + text_pad_x, + rect.y, + (rect.w - text_pad_x - 4.0).max(1.0), + EVENT_CHIP_HEIGHT, + align, + )); + } if ctx.mobile_readonly { hits.push(DatabaseHitTarget { rect, @@ -151,55 +159,7 @@ pub(super) fn render_calendar_view( // Determine displayed month via the single authoritative resolver. let today_day = local_day_index(ctx.now_ms, ctx.offset_at_ms); - let entries: Vec = ctx - .rows - .iter() - .filter_map(|row| { - let start_at = ctx - .data - .cells - .get(&(row.row_id.clone(), start_col_id.to_string())) - .and_then(DatabaseCellValue::as_i64)?; - let end_at = end_col_id.and_then(|eid| { - ctx.data - .cells - .get(&(row.row_id.clone(), eid.to_string())) - .and_then(DatabaseCellValue::as_i64) - .filter(|&e| e >= start_at) - }); - // Derive optional accent color from the first select column if present. - let color = ctx - .data - .columns - .iter() - .find(|c| c.column_type == "select") - .and_then(|c| { - let val = ctx - .data - .cells - .get(&(row.row_id.clone(), c.id.clone())) - .and_then(DatabaseCellValue::as_str)?; - c.select_options() - .into_iter() - .find(|o| o.id == val || o.value == val) - .map(|o| o.color) - }); - let resolved_title = resolve_rich_text_plain(&row.title, ctx.page_titles); - Some(CalendarEntry { - id: format!("database:{}", row.row_id), - row_id: row.row_id.clone(), - title: if resolved_title.trim().is_empty() { - "Untitled".to_string() - } else { - resolved_title - }, - color, - start_at_ms: start_at, - end_at_ms: end_at, - badges: Vec::new(), - }) - }) - .collect(); + let entries = super::calendar_edit::collect_calendar_entries(ctx, start_col_id, end_col_id); let is_phone = ctx.form_factor == crate::block_flow::FormFactor::Phone; let (year, month) = resolve_calendar_display_month( @@ -223,7 +183,7 @@ pub(super) fn render_calendar_view( let nav_h = if is_phone { 44.0 } else { NAV_HEIGHT }; let btn_h = if is_phone { 44.0 } else { 28.0 }; let (step_w, today_w) = if is_phone { (44.0, 62.0) } else { (28.0, 56.0) }; - let nav_buttons: [(&str, f32, DatabaseHitKind); 3] = if ctx.direction.is_rtl() { + let nav_buttons = if ctx.direction.is_rtl() { [ (">", step_w, DatabaseHitKind::CalendarNextMonth), ("Today", today_w, DatabaseHitKind::CalendarToday), @@ -246,14 +206,15 @@ pub(super) fn render_calendar_view( } else { (PAD_X, InlineAlign::Left) }; + let title_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_base_px, + 600.0, + ctx.palette.text_primary, + ); prims.push(ctx.single_line_clipped( &month_label, - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_base_px, - 600.0, - ctx.palette.text_primary, - ), + title_style, month_x, y, month_w, @@ -285,25 +246,25 @@ pub(super) fn render_calendar_view( icon_sz, icon_sz, ); - let icon = if label == "<" { - crate::theme::IconPaint::named("ToggleRightIcon").rotated(std::f32::consts::PI) - } else { - crate::theme::IconPaint::named("ToggleRightIcon") - }; + let mut icon = crate::theme::IconPaint::named("ToggleRightIcon"); + if label == "<" { + icon = icon.rotated(std::f32::consts::PI); + } prims.push(DatabasePrim::Icon { rect: icon_rect, icon, color: ctx.palette.icon, }); } else { + let btn_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 500.0, + ctx.palette.brand, + ); prims.push(ctx.single_line_clipped( label, - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px + 1.0, - 500.0, - ctx.palette.brand, - ), + btn_style, rect.x, rect.y, rect.w, @@ -600,6 +561,16 @@ pub(super) fn render_calendar_view( crate::theme::PlaygroundTheme::Dark => 0.22, }; let grid_top_y = y; + let mut hide_active_row = (!ctx.mobile_readonly) + .then(|| { + ctx.ui_state + .authoring + .active_cell + .as_ref() + .filter(|ed| ed.col_type == "title" && ed.error.is_none()) + .map(|ed| (ed.row_id.as_str(), ed.calendar_day_index)) + }) + .flatten(); prims.push(DbRenderCtx::hairline( FlowRect::new(PAD_X, grid_top_y, actual_grid_w, 1.0), grid_border, @@ -718,6 +689,7 @@ pub(super) fn render_calendar_view( true, 6.0, Some(day.day_index), + &mut hide_active_row, &mut prims, &mut hits, &mut authoring_hits, @@ -765,6 +737,7 @@ pub(super) fn render_calendar_view( !seg.starts_before_week, 7.0, week.get(seg.start_index).map(|d| d.day_index), + &mut hide_active_row, &mut prims, &mut hits, &mut authoring_hits, diff --git a/blocksuite/crates/editor/src/database/render_types.rs b/blocksuite/crates/editor/src/database/render_types.rs index 3520c72665..2b82d3eafa 100644 --- a/blocksuite/crates/editor/src/database/render_types.rs +++ b/blocksuite/crates/editor/src/database/render_types.rs @@ -69,6 +69,7 @@ pub struct DatabaseLayoutOutput { pub authoring_hits: Vec, 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, } diff --git a/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs b/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs index 9a565cd25e..0bf92f43c6 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs @@ -364,6 +364,7 @@ pub(super) fn render_db_authoring_evidence(out_dir: &Path) -> Result<()> { draft: String::new(), error: None, select_filter: "Urgent".into(), + calendar_day_index: None, }); }, cx, @@ -435,6 +436,7 @@ pub(super) fn render_db_authoring_evidence(out_dir: &Path) -> Result<()> { draft: String::new(), error: None, select_filter: String::new(), + calendar_day_index: None, }); }, cx, @@ -507,6 +509,7 @@ pub(super) fn render_db_authoring_evidence(out_dir: &Path) -> Result<()> { draft: "Column Schema & Type Switcher".into(), error: None, select_filter: String::new(), + calendar_day_index: None, }); }, cx, @@ -580,6 +583,7 @@ pub(super) fn render_db_authoring_evidence(out_dir: &Path) -> Result<()> { draft: "Column Schema & Type Switcher".into(), error: None, select_filter: String::new(), + calendar_day_index: None, }); }, cx, diff --git a/blocksuite/crates/playground/src/bin/bs_harness/db_visual_evidence.rs b/blocksuite/crates/playground/src/bin/bs_harness/db_visual_evidence.rs index a90266d948..fc4ecefec7 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/db_visual_evidence.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/db_visual_evidence.rs @@ -16,6 +16,10 @@ use super::{ }; fn build_db_visual_doc() -> Result<(DocState, String)> { + build_db_visual_doc_ext(false) +} + +fn build_db_visual_doc_ext(extra_overflow_views: bool) -> Result<(DocState, String)> { let mut state = new_doc_state("Database Visual Parity")?; let db_id = "db-visual".to_string(); { @@ -201,7 +205,28 @@ fn build_db_visual_doc() -> Result<(DocState, String)> { } }), }, - ], + ] + .into_iter() + .chain( + extra_overflow_views + .then_some([ + DatabaseViewSpec { + id: "v-roadmap".into(), + name: "Release Roadmap".into(), + mode: "table".into(), + raw: json!({}), + }, + DatabaseViewSpec { + id: "v-backlog".into(), + name: "Sprint Backlog".into(), + mode: "table".into(), + raw: json!({}), + }, + ]) + .into_iter() + .flatten(), + ) + .collect(), cells, }), Some("p-note"), @@ -294,3 +319,185 @@ pub(super) fn render_db_visual_evidence( Ok(()) } + +pub(super) fn render_r19_visual_evidence(out_dir: &Path, prefix: &str) -> Result<()> { + use anyhow::Context as _; + use playground::database::DatabaseAuthoringHitKind; + + use super::dnd_motion_evidence::db_hit_screen_center; + + std::fs::create_dir_all(out_dir)?; + let save_r19_png = |session: &super::HeadlessSession, stem: &str| -> Result<()> { + let path = out_dir.join(format!("{stem}.png")); + save_session_png(session, &path, stem) + }; + + // 1. R19-P1-1: Calendar in-place title edit (`v-cal`, clicking `row-2` chip). + { + let (state, db_id) = build_db_visual_doc()?; + let session = start_headless_session( + 960, + 680, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| { + v.set_document(state, cx); + v.set_database_active_view(&db_id, "v-cal", cx); + })?; + session.settle(60); + session.frame()?; + let chip_pt = db_hit_screen_center(&session, &db_id, |k| { + matches!( + k, + DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, .. } if row_id == "row-2" + ) + }) + .or_else(|| { + db_hit_screen_center(&session, &db_id, |k| { + matches!(k, DatabaseAuthoringHitKind::CalendarDragEventStart { .. }) + }) + }) + .context("calendar chip not found")?; + session.pointer_move(chip_pt.0, chip_pt.1, false); + session.pointer_down(chip_pt.0, chip_pt.1); + session.settle(16); + session.pointer_up(chip_pt.0, chip_pt.1); + session.settle(30); + let stem = format!("{prefix}-r19-calendar-inline-edit-light"); + save_r19_png(&session, &stem)?; + } + + // 2. R19-P2-1: Wide Table row drag inside 760px viewport (`TableRowReorder` drop line clipped). + { + let (state, db_id) = build_db_visual_doc()?; + let session = start_headless_session( + 760, + 560, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| { + v.set_document(state, cx); + v.set_database_active_view(&db_id, "v-table", cx); + })?; + session.settle(60); + session.frame()?; + let row1_cell = db_hit_screen_center(&session, &db_id, |k| { + matches!( + k, + DatabaseAuthoringHitKind::EditCell { row_id, column_id, .. } + if row_id == "row-1" && column_id == "title" + ) + }) + .context("row-1 title cell not found")?; + let row3_cell = db_hit_screen_center(&session, &db_id, |k| { + matches!( + k, + DatabaseAuthoringHitKind::EditCell { row_id, column_id, .. } + if row_id == "row-3" && column_id == "title" + ) + }) + .context("row-3 title cell not found")?; + session.pointer_move(row1_cell.0, row1_cell.1, false); + session.settle(32); + session.frame()?; + let handle_pt = (row1_cell.0 - 115.0, row1_cell.1); + session.pointer_move(handle_pt.0, handle_pt.1, false); + session.settle(16); + session.pointer_down(handle_pt.0, handle_pt.1); + session.settle(32); + for step in 1..=8 { + let t = step as f32 / 8.0; + let x = handle_pt.0 + 18.0 * t; + let y = handle_pt.1 + (row3_cell.1 + 16.0 - handle_pt.1) * t; + session.pointer_move(x, y, true); + session.settle(16); + } + let stem = format!("{prefix}-r19-table-row-drag-clipped-light"); + save_r19_png(&session, &stem)?; + session.pointer_up(handle_pt.0 + 18.0, row3_cell.1 + 16.0); + } + + // 3. R19-P2-2: 390x844 narrow Desktop Kanban view switcher (closed & floating More open, Dark). + { + let (state, db_id) = build_db_visual_doc_ext(true)?; + let session = start_headless_session( + 390, + 844, + PlaygroundOptions { + theme: PlaygroundTheme::Dark, + form_factor: playground::FormFactor::Desktop, + ..Default::default() + }, + )?; + session.view(|v, cx| { + v.set_document(state, cx); + v.set_database_active_view(&db_id, "v-kanban", cx); + })?; + session.settle(60); + session.frame()?; + let stem_closed = format!("{prefix}-r19-narrow-desktop-kanban-dark"); + save_r19_png(&session, &stem_closed)?; + + session.view(|v, cx| { + let more_rect = v + .database_hits(&db_id) + .iter() + .find(|h| { + matches!( + h.kind, + playground::database::DatabaseHitKind::ToggleMoreViews + ) + }) + .map(|h| h.rect); + if let Some(r) = more_rect { + let _ = v.click_database_point(&db_id, r.x + r.w * 0.5, r.y + r.h * 0.5, None, cx); + } + })?; + session.settle(60); + let stem_open = format!("{prefix}-r19-narrow-desktop-kanban-more-dark"); + save_r19_png(&session, &stem_open)?; + } + + // 4. R19-P2-3: Table `Title` cell first click in middle of string places caret at click X. + { + let (state, db_id) = build_db_visual_doc()?; + let session = start_headless_session( + 960, + 520, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + )?; + session.view(|v, cx| { + v.set_document(state, cx); + v.set_database_active_view(&db_id, "v-table", cx); + })?; + session.settle(60); + session.frame()?; + let row2_cell = db_hit_screen_center(&session, &db_id, |k| { + matches!( + k, + DatabaseAuthoringHitKind::EditCell { row_id, column_id, .. } + if row_id == "row-2" && column_id == "title" + ) + }) + .context("row-2 title cell not found")?; + let click_pt = (row2_cell.0 - 44.0, row2_cell.1); + session.pointer_move(click_pt.0, click_pt.1, false); + session.pointer_down(click_pt.0, click_pt.1); + session.settle(16); + session.pointer_up(click_pt.0, click_pt.1); + session.settle(30); + let stem = format!("{prefix}-r19-table-first-click-caret-light"); + save_r19_png(&session, &stem)?; + } + + Ok(()) +} diff --git a/blocksuite/crates/playground/src/bin/bs_harness/dnd_motion_evidence.rs b/blocksuite/crates/playground/src/bin/bs_harness/dnd_motion_evidence.rs index 7859288241..3d91f3bab7 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/dnd_motion_evidence.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/dnd_motion_evidence.rs @@ -317,7 +317,11 @@ fn build_edgeless_motion_doc() -> Result { Ok(state) } -fn db_hit_screen_center(session: &HeadlessSession, block_id: &str, pred: F) -> Option<(f32, f32)> +pub(super) fn db_hit_screen_center( + session: &HeadlessSession, + block_id: &str, + pred: F, +) -> Option<(f32, f32)> where F: Fn(&DatabaseAuthoringHitKind) -> bool, { diff --git a/blocksuite/crates/playground/src/bin/bs_harness/main.rs b/blocksuite/crates/playground/src/bin/bs_harness/main.rs index 297c2b8978..ff3dc432dd 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/main.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/main.rs @@ -501,6 +501,7 @@ fn main() -> Result<()> { ); let mut prefix = "after".to_string(); let mut include_phone = false; + let mut include_r19 = false; while let Some(arg) = args.next() { match arg.as_str() { "--prefix" => { @@ -509,10 +510,17 @@ fn main() -> Result<()> { "--phone" => { include_phone = true; } + "--r19" => { + include_r19 = true; + } other => bail!("unknown render-db-visual-evidence argument {other:?}"), } } - db_visual_evidence::render_db_visual_evidence(&dir, &prefix, include_phone) + if include_r19 { + db_visual_evidence::render_r19_visual_evidence(&dir, &prefix) + } else { + db_visual_evidence::render_db_visual_evidence(&dir, &prefix, include_phone) + } } "render-editor-media-evidence" => { media_evidence::render_editor_media_evidence(&PathBuf::from( diff --git a/blocksuite/crates/playground/src/database_authoring/dnd.rs b/blocksuite/crates/playground/src/database_authoring/dnd.rs index 97720f1026..cbcdb01901 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd.rs @@ -572,13 +572,21 @@ impl PlaygroundView { }; if !promoted { if let Some((hit, click_x)) = pending_click { - return self.dispatch_database_authoring_hit( + let handled = self.dispatch_database_authoring_hit( &block_id, &hit, click_x, Some(window), cx, ); + if handled && matches!(hit.kind, DatabaseAuthoringHitKind::EditCell { .. }) { + self.place_database_inline_caret_at_point( + ui::point(ui::px(pointer_screen.0), ui::px(pointer_screen.1)), + window, + cx, + ); + } + return handled; } return false; } @@ -680,11 +688,17 @@ impl PlaygroundView { draft: row.title.plain.clone(), error: None, select_filter: String::new(), + calendar_day_index: Some(origin_day), }); self.editor_focus.focus(window, cx); self.env_rev += 1; cx.notify(); self.sync_database_authoring_input(Some(window), cx); + self.place_database_inline_caret_at_point( + ui::point(ui::px(pointer_screen.0), ui::px(pointer_screen.1)), + window, + cx, + ); return true; } return false; @@ -763,30 +777,4 @@ impl PlaygroundView { cx.notify(); true } - - pub(crate) fn database_local_rect_to_screen( - &self, - block_id: &str, - local_rect: FlowRect, - scrolls_x: bool, - window: &Window, - ) -> Option { - let layout = self.flow_layout()?; - let block = layout.block(block_id)?; - let scroll_x = if scrolls_x { - block - .body - .code_scroll - .map_or(0.0, |cs| self.overlays.code_scroll_x_for(block_id, cs)) - } else { - 0.0 - }; - let geom = self.current_page_geometry(f32::from(window.viewport_size().width)); - Some(FlowRect::new( - geom.column_x + block.x + local_rect.x - scroll_x, - TOPBAR_HEIGHT + block.y + local_rect.y - self.scroll_y, - local_rect.w, - local_rect.h, - )) - } } diff --git a/blocksuite/crates/playground/src/database_authoring/geometry.rs b/blocksuite/crates/playground/src/database_authoring/geometry.rs index cf98d2ab2f..a9b9ecf77b 100644 --- a/blocksuite/crates/playground/src/database_authoring/geometry.rs +++ b/blocksuite/crates/playground/src/database_authoring/geometry.rs @@ -152,6 +152,116 @@ impl PlaygroundView { ) } + pub(crate) fn database_local_rect_to_screen( + &self, + block_id: &str, + local_rect: FlowRect, + scrolls_x: bool, + window: &Window, + ) -> Option { + let layout = self.flow_layout()?; + let block = layout.block(block_id)?; + let scroll_x = if scrolls_x { + block + .body + .code_scroll + .map_or(0.0, |cs| self.overlays.code_scroll_x_for(block_id, cs)) + } else { + 0.0 + }; + let geom = self.current_page_geometry(f32::from(window.viewport_size().width)); + Some(FlowRect::new( + geom.column_x + block.x + local_rect.x - scroll_x, + TOPBAR_HEIGHT + block.y + local_rect.y - self.scroll_y, + local_rect.w, + local_rect.h, + )) + } + + /// Convert a block-local database rect to screen space and clip horizontally to the visible + /// bounds of `block_id` (`[column_x + block.x, column_x + block.x + block.body.width]`). + pub(crate) fn database_clipped_local_rect_to_screen( + &self, + block_id: &str, + local_rect: FlowRect, + scrolls_x: bool, + window: &Window, + ) -> Option { + let raw = self.database_local_rect_to_screen(block_id, local_rect, scrolls_x, window)?; + let layout = self.flow_layout()?; + let block = layout.block(block_id)?; + let geom = self.current_page_geometry(f32::from(window.viewport_size().width)); + let (vis_left, vis_right) = if let Some(cs) = block.body.code_scroll { + ( + geom.column_x + block.x + cs.area.x, + geom.column_x + block.x + cs.area.right(), + ) + } else { + ( + geom.column_x + block.x + 8.0, + geom.column_x + block.x + (block.body.width - 8.0).max(9.0), + ) + }; + let left = raw.x.max(vis_left); + let right = raw.right().min(vis_right); + (right > left).then(|| FlowRect::new(left, raw.y, right - left, raw.h)) + } + + fn resolve_active_cell_local_rect( + &self, + session: &super::DatabaseInlineSession, + ) -> Option<(FlowRect, bool)> { + let block_id = session.target.block_id(); + let (target_row, target_col, is_title) = match &session.target { + DatabaseInlineTarget::LiveRichCell { + row_id, + column_id, + is_title, + .. + } => (row_id.as_str(), column_id.as_str(), *is_title), + DatabaseInlineTarget::ScalarCell { + row_id, column_id, .. + } => (row_id.as_str(), column_id.as_str(), false), + _ => return None, + }; + if let Some(hit) = self.flow.database_active_cell_rich(block_id) + && hit.row_id == target_row + && hit.column_id == target_col + && let Some(active) = self.flow.database_active_cell_rect(block_id) + { + return Some(active); + } + let active_cal_day = self + .flow + .database_state + .state_for(block_id) + .authoring + .active_cell + .as_ref() + .and_then(|ed| ed.calendar_day_index); + let auth_hits = self.flow.database_authoring_hits(block_id); + if is_title + && let Some(h) = auth_hits.iter().find(|h| match &h.kind { + database::DatabaseAuthoringHitKind::CalendarDragEventStart { + row_id, + day_index, + } => row_id == target_row && active_cal_day.is_none_or(|d| d == *day_index), + _ => false, + }) + { + return Some((h.rect, h.scrolls_x)); + } + if let Some(h) = auth_hits.iter().rev().find(|h| match &h.kind { + database::DatabaseAuthoringHitKind::EditCell { + row_id, column_id, .. + } => row_id == target_row && column_id == target_col, + _ => false, + }) { + return Some((h.rect, h.scrolls_x)); + } + self.flow.database_active_cell_rect(block_id) + } + /// Screen-space box `(rect, font_size)` of the active database inline input (cell or popover /// text box), accounting for horizontal table scroll and page vertical scroll. pub(crate) fn database_inline_screen_box(&self, w: &Window) -> Option<(FlowRect, f32)> { @@ -163,7 +273,7 @@ impl PlaygroundView { } let block_id = session.target.block_id(); let block = layout.block(block_id)?; - let (cell_rect, scrolls_x) = self.flow.database_active_cell_rect(block_id)?; + let (cell_rect, scrolls_x) = self.resolve_active_cell_local_rect(session)?; let scroll_x = if scrolls_x { block .body @@ -175,9 +285,14 @@ impl PlaygroundView { let geom = self.current_page_geometry(f32::from(w.viewport_size().width)); let screen_x = geom.column_x + block.x + cell_rect.x - scroll_x; let screen_y = TOPBAR_HEIGHT + block.y + cell_rect.y - self.scroll_y; + let font_px = if cell_rect.h <= 26.0 { + TYPOGRAPHY.font_xs_px + } else { + TYPOGRAPHY.font_sm_px + }; Some(( FlowRect::new(screen_x, screen_y, cell_rect.w, cell_rect.h), - TYPOGRAPHY.font_sm_px, + font_px, )) } @@ -190,10 +305,19 @@ impl PlaygroundView { let session = self.database_input.as_ref()?; if !session.target.is_popover_field() { let block_id = session.target.block_id(); - if let Some(layout) = self.flow_layout() + let target_ids = match &session.target { + DatabaseInlineTarget::LiveRichCell { + row_id, column_id, .. + } => Some((row_id.as_str(), column_id.as_str())), + _ => None, + }; + if let Some((target_row, target_col)) = target_ids + && let Some(layout) = self.flow_layout() && let Some(block) = layout.block(block_id) && let Some((_, scrolls_x)) = self.flow.database_active_cell_rect(block_id) && let Some(hit) = self.flow.database_active_cell_rich(block_id) + && hit.row_id == target_row + && hit.column_id == target_col { let scroll_x = if scrolls_x { block @@ -337,6 +461,27 @@ impl PlaygroundView { Some(FlowRect::new(caret_x, caret_y, 2.0, lh).bounds(point(px(0.0), px(0.0)))) } + /// Position the caret of a newly focused database inline cell at the exact clicked character + /// index rather than defaulting to `end..end`. + pub(crate) fn place_database_inline_caret_at_point( + &mut self, + p: Point, + window: &mut Window, + cx: &mut Context, + ) { + if self + .database_input + .as_ref() + .is_some_and(|s| !s.target.is_popover_field()) + && let Some(off) = self.database_inline_character_index_for_point(p, window) + { + let _ = self.database_authoring_input_edit(window, cx, |a| { + a.input.select(off..off); + None + }); + } + } + /// Focus the first visible editable non-checkbox column of `row_id` into the database inline /// editor (used after `+ New record` on both title and title-less tables). pub(crate) fn focus_database_first_editable_cell( @@ -442,6 +587,7 @@ impl PlaygroundView { draft, error: None, select_filter: String::new(), + calendar_day_index: None, }); self.env_rev += 1; let mut window = window; diff --git a/blocksuite/crates/playground/src/database_authoring/inline.rs b/blocksuite/crates/playground/src/database_authoring/inline.rs index b2d4984ce6..19500dd62b 100644 --- a/blocksuite/crates/playground/src/database_authoring/inline.rs +++ b/blocksuite/crates/playground/src/database_authoring/inline.rs @@ -197,6 +197,11 @@ impl PlaygroundView { /// Block id of whichever `affine:database` block currently has an open authoring popover or /// active inline editor. pub(crate) fn active_database_authoring_block(&self) -> Option { + for (block_id, st) in &self.flow.database_state.ui_states { + if st.more_views_open { + return Some(block_id.clone()); + } + } if self.is_database_write_readonly() { return None; } diff --git a/blocksuite/crates/playground/src/database_authoring/keys.rs b/blocksuite/crates/playground/src/database_authoring/keys.rs index 94019276d1..943e53da4b 100644 --- a/blocksuite/crates/playground/src/database_authoring/keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/keys.rs @@ -31,6 +31,7 @@ impl PlaygroundView { Some(window), Some(cx), ); + let _ = self.flow.database_state.close_more_views(&block_id); self.flow .database_state .authoring_mut(&block_id) @@ -88,6 +89,13 @@ impl PlaygroundView { let Some(auth_key) = mapped else { return false; }; + if auth_key == DatabaseAuthoringKey::Escape + && self.flow.database_state.close_more_views(&block_id) + { + self.env_rev += 1; + cx.notify(); + return true; + } if self .database_input .as_ref() diff --git a/blocksuite/crates/playground/src/database_authoring/mod.rs b/blocksuite/crates/playground/src/database_authoring/mod.rs index 5835016374..e1d53853b1 100644 --- a/blocksuite/crates/playground/src/database_authoring/mod.rs +++ b/blocksuite/crates/playground/src/database_authoring/mod.rs @@ -25,6 +25,8 @@ mod tests_inline_and_popovers; mod tests_kanban_and_richtext; #[cfg(test)] mod tests_scalar_edgeless_calendar; +#[cfg(test)] +mod tests_wave5e_r2; pub(crate) use dnd::DatabaseDropSettle; pub(crate) use dnd_table::TableHoverState; @@ -152,7 +154,8 @@ impl PlaygroundView { for id in ids { let st = self.flow.database_state.state_for(&id); let a = &st.authoring; - if a.column_menu.is_some() + if st.more_views_open + || a.column_menu.is_some() || a.active_cell.is_some() || a.toolbar_panel.is_some() || a.calendar_drag.is_some() @@ -160,6 +163,7 @@ impl PlaygroundView { || a.column_resize.is_some() || a.progress_preview.is_some() { + let _ = self.flow.database_state.close_more_views(&id); let auth = self.flow.database_state.authoring_mut(&id); auth.dismiss_popovers(); auth.calendar_drag = None; @@ -311,6 +315,7 @@ impl PlaygroundView { pos_y, ) { + let _ = self.flow.database_state.close_more_views(block_id); if let Some(w) = window { self.editor_focus.focus(w, cx); } @@ -339,6 +344,8 @@ impl PlaygroundView { return false; }; + let _ = self.flow.database_state.close_more_views(block_id); + let click_x = if hit.scrolls_x { local_x + scroll_x } else { diff --git a/blocksuite/crates/playground/src/database_authoring/paint.rs b/blocksuite/crates/playground/src/database_authoring/paint.rs index df22436828..f8dfe6caac 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint.rs @@ -165,9 +165,6 @@ impl PlaygroundView { layout: &FlowLayout, window: &Window, ) -> Option<(String, DatabasePopoverOverlay)> { - if self.is_database_write_readonly() { - return None; - } let block_id = self.active_database_authoring_block()?; let ui_state = self.flow.database_state.state_for(&block_id); let block = layout.block(&block_id)?; @@ -188,13 +185,16 @@ impl PlaygroundView { .code_scroll .map_or(0.0, |cs| self.overlays.code_scroll_x_for(&block_id, cs)); let anchor = self.flow.database_popover_anchor(&block_id); + let overflow_tabs = self.flow.database_overflow_tabs(&block_id); let offset_at = self.utc_offset_resolver(); let overlay = layout_database_popover_overlay( data, &ui_state, block_screen_origin, + block.body.width, scroll_x, anchor, + overflow_tabs, self.window_size, TOPBAR_HEIGHT, self.theme, @@ -351,11 +351,21 @@ impl PlaygroundView { cell_world.w, cell_world.h, ); + let (font_px, weight) = if cell_world.h <= 26.0 { + (TYPOGRAPHY.font_xs_px, 500.0) + } else if matches!( + session.target, + super::inline::DatabaseInlineTarget::LiveRichCell { is_title: true, .. } + ) { + (TYPOGRAPHY.font_sm_px, 500.0) + } else { + (TYPOGRAPHY.font_sm_px, 400.0) + }; out.extend(paint_inline_box_elements( &session.anchored.input, page_local_rect, - TYPOGRAPHY.font_sm_px, - 400.0, + font_px, + weight, true, palette, caret_alpha, @@ -552,6 +562,12 @@ impl PlaygroundView { return true; }; + if let database::DatabaseAuthoringHitKind::SwitchView { view_id } = &hit.kind { + self.set_database_active_view(&block_id, view_id, cx); + self.editor_focus.focus(window, cx); + return true; + } + let Some(db_data) = self.database_snapshot_data(&block_id) else { return true; }; diff --git a/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs b/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs index 69dbb066b8..aa57df22b5 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs @@ -489,9 +489,12 @@ impl PlaygroundView { promoted, .. } if promoted => { - if let Some(src_screen) = - self.database_local_rect_to_screen(&block_id, source_row_rect, true, window) - { + if let Some(src_screen) = self.database_clipped_local_rect_to_screen( + &block_id, + source_row_rect, + true, + window, + ) { out.push( div() .absolute() @@ -504,7 +507,7 @@ impl PlaygroundView { ); } if let Some((lx, ly, lw)) = drop_line_local - && let Some(line_screen) = self.database_local_rect_to_screen( + && let Some(line_screen) = self.database_clipped_local_rect_to_screen( &block_id, FlowRect::new(lx, ly, lw, 2.0), true, @@ -557,7 +560,7 @@ impl PlaygroundView { promoted, .. } if promoted => { - if let Some(src_screen) = self.database_local_rect_to_screen( + if let Some(src_screen) = self.database_clipped_local_rect_to_screen( &block_id, source_header_rect, true, @@ -575,7 +578,7 @@ impl PlaygroundView { ); } if let Some((lx, ly, lh)) = drop_line_local - && let Some(line_screen) = self.database_local_rect_to_screen( + && let Some(line_screen) = self.database_clipped_local_rect_to_screen( &block_id, FlowRect::new(lx, ly, 2.0, lh), true, diff --git a/blocksuite/crates/playground/src/database_authoring/tests_inline_and_popovers.rs b/blocksuite/crates/playground/src/database_authoring/tests_inline_and_popovers.rs index e6da6792f7..e5cad590bd 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_inline_and_popovers.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_inline_and_popovers.rs @@ -361,6 +361,7 @@ fn noop_richtext_focus_writes_zero_crdt_updates_and_shift_enter_splices() { draft: "Keep formatted note".into(), error: None, select_filter: String::new(), + calendar_day_index: None, }); }, cx, @@ -406,6 +407,7 @@ fn noop_richtext_focus_writes_zero_crdt_updates_and_shift_enter_splices() { draft: "Keep formatted note".into(), error: None, select_filter: String::new(), + calendar_day_index: None, }); }, cx, @@ -582,6 +584,7 @@ fn selection_move_tracks_remote_insert_and_remote_col_type_change_invalidates_ed draft: "Keep formatted note".into(), error: None, select_filter: String::new(), + calendar_day_index: None, }); }, cx, diff --git a/blocksuite/crates/playground/src/database_authoring/tests_scalar_edgeless_calendar.rs b/blocksuite/crates/playground/src/database_authoring/tests_scalar_edgeless_calendar.rs index 9934af5719..b4441627f4 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_scalar_edgeless_calendar.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_scalar_edgeless_calendar.rs @@ -416,6 +416,239 @@ fn database_three_view_visual_layout_toolbar_kanban_hover_pills_and_table_header hovered_out.prims.len() > idle_out.prims.len(), "hovering a Kanban lane must paint the lane header ops and footer Add button" ); + + // 3. Narrow 390px Desktop container (`342px` block width): keeps active `v-kanban` + // visible in natural order, wraps Filter/Sort/Group onto the second row without + // colliding with `More`, and keeps block height invariant when `more_views_open`. + let mut narrow_kanban = DatabaseUiState { + active_view_id: Some("v-kanban".into()), + ..Default::default() + }; + let narrow_closed = layout_database_block( + &db_data, + &narrow_kanban, + 342.0, + PlaygroundTheme::Dark, + ui::Direction::Ltr, + crate::FormFactor::Desktop, + false, + 1_773_014_400_000, + &zero_offset, + &titles, + window, + ); + assert!( + narrow_closed.hits.iter().any(|h| matches!( + &h.kind, + DatabaseHitKind::SwitchView { view_id } if view_id == "v-kanban" + )), + "active Kanban tab must remain visible on 390px narrow desktop viewport" + ); + let narrow_tab_y = narrow_closed + .hits + .iter() + .find_map(|h| { + matches!(h.kind, DatabaseHitKind::SwitchView { .. }).then_some(h.rect.y) + }) + .expect("narrow view tab"); + let narrow_filter_y = narrow_closed + .authoring_hits + .iter() + .find_map(|h| { + matches!(h.kind, DatabaseAuthoringHitKind::ToolbarToggleFilter) + .then_some(h.rect.y) + }) + .expect("narrow Filter trigger"); + assert!( + narrow_filter_y > narrow_tab_y + 20.0, + "narrow 342px desktop block must wrap Filter/Sort/Group onto the second row" + ); + narrow_kanban.more_views_open = true; + let narrow_open = layout_database_block( + &db_data, + &narrow_kanban, + 342.0, + PlaygroundTheme::Dark, + ui::Direction::Ltr, + crate::FormFactor::Desktop, + false, + 1_773_014_400_000, + &zero_offset, + &titles, + window, + ); + assert_eq!( + narrow_closed.height, narrow_open.height, + "opening More views menu must render in screen-space Overlays without shifting block height" + ); + }) + .unwrap(); + }); +} + +#[test] +fn calendar_add_event_hides_underlying_chip_text_clips_drop_line_and_places_first_click_caret() { + let (state, db_id) = seed_authoring_doc(false); + let (platform, app, win, headless) = open_authoring_window( + 1024, + 760, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + state, + ); + let tick = || { + platform.run_until_parked(); + headless.request_frame(); + platform.run_until_parked(); + }; + tick(); + + // 1. First single-click near the left/middle of an unfocused Table `Title` cell places the + // caret inside the string (`< len`), not at `end..end`. + let title_mid_pt = app.update(|cx| { + win.update(cx, |v, w, _| { + let geom = v.current_page_geometry(f32::from(w.viewport_size().width)); + let layout = v.flow_layout().expect("layout"); + let block = layout.block(&db_id).expect("db block"); + let hit = v + .flow + .database_authoring_hits(&db_id) + .iter() + .find(|h| matches!(&h.kind, DatabaseAuthoringHitKind::EditCell { col_type, .. } if col_type == "title")) + .expect("title EditCell hit"); + point( + px(geom.column_x + block.x + hit.rect.x + 24.0), + px(crate::TOPBAR_HEIGHT + block.y + hit.rect.y + hit.rect.h * 0.5 - v.scroll_y), + ) + }) + .unwrap() + }); + headless.simulate_click(title_mid_pt); + tick(); + app.update(|cx| { + win.update(cx, |v, w, _| { + let sess = v.database_input.as_ref().expect("active title session"); + let text_len = sess.anchored.input.text.encode_utf16().count(); + let (sel, _) = sess.anchored.input.shown_selection(); + assert!( + text_len >= 6 && sel.start > 0 && sel.start < text_len, + "first click inside Title text must place caret mid-word (got {}..{} of len {})", + sel.start, + sel.end, + text_len + ); + // Clipped local-to-screen rect clamps wide table row drop lines to the horizontal grid + // scroll area (`code_scroll.area`, `8..width-8`), never protruding 8px past the grid border. + let layout = v.flow_layout().expect("layout"); + let block = layout.block(&db_id).expect("db block"); + let geom = v.current_page_geometry(f32::from(w.viewport_size().width)); + let grid_right = block.body.code_scroll.map_or( + geom.column_x + block.x + (block.body.width - 8.0).max(9.0), + |cs| geom.column_x + block.x + cs.area.right(), + ); + let clipped = v + .database_clipped_local_rect_to_screen( + &db_id, + blocksuite_editor::block_flow::FlowRect::new( + 8.0, + 80.0, + block.body.width + 240.0, + 2.0, + ), + true, + w, + ) + .expect("clipped rect"); + assert!( + (clipped.right() - grid_right).abs() <= 0.5, + "table drop line right edge ({}) must clip cleanly to grid viewport right ({})", + clipped.right(), + grid_right + ); + }) + .unwrap(); + }); + + // 2. Switch to Calendar view on `build_e2e_database_doc`, hover a day cell, click `+`, and + // verify empty initial draft (no `"New Event"` prefix). + let (cal_state, cal_db_id) = build_e2e_database_doc(); + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.dismiss_all_database_authoring(None, cx); + v.set_document(cal_state, cx); + v.set_database_active_view(&cal_db_id, "v-cal", cx); + }) + .unwrap(); + }); + tick(); + headless.dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(640.0), px(380.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(-100_000.0))), + modifiers: Modifiers::default(), + touch_phase: TouchPhase::Moved, + source: ScrollSource::Pointer, + })); + tick(); + let day_pt = app.update(|cx| { + win.update(cx, |v, w, _| { + let layout = v.flow_layout().unwrap(); + let geom = v.current_page_geometry(f32::from(w.viewport_size().width)); + let db_block = layout.block(&cal_db_id).unwrap(); + let rect = v + .database_authoring_hits(&cal_db_id) + .iter() + .find_map(|h| match h.kind { + DatabaseAuthoringHitKind::CalendarDayDropTarget { .. } => Some(h.rect), + _ => None, + }) + .expect("calendar day cell"); + point( + px(geom.column_x + db_block.x + rect.x + 24.0), + px(crate::TOPBAR_HEIGHT + db_block.y - v.scroll_y + rect.y + 24.0), + ) + }) + .unwrap() + }); + app.update(|cx| { + win.update(cx, |v, w, cx| { + v.root_mouse_move( + &MouseMoveEvent { + position: day_pt, + pressed_button: None, + modifiers: Modifiers::default(), + }, + w, + cx, + ); + }) + .unwrap(); + }); + tick(); + let plus_pt = app.update(|cx| { + win.update(cx, |v, w, _| { + v.database_authoring_hit_screen_center(&cal_db_id, w, |k| { + matches!(k, DatabaseAuthoringHitKind::CalendarAddRowOnDay { .. }) + }) + .map(|(x, y)| point(px(x), px(y))) + .expect("Calendar day + button") + }) + .unwrap() + }); + headless.simulate_click(plus_pt); + tick(); + app.update(|cx| { + win.update(cx, |v, _, _| { + let sess = v + .database_input + .as_ref() + .expect("active calendar title input"); + assert_eq!( + sess.anchored.input.display_text(), + "", + "Calendar + must open with empty draft rather than prepending 'New Event'" + ); }) .unwrap(); }); diff --git a/blocksuite/crates/playground/src/database_authoring/tests_wave5e_r2.rs b/blocksuite/crates/playground/src/database_authoring/tests_wave5e_r2.rs new file mode 100644 index 0000000000..44fe0a2a7c --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/tests_wave5e_r2.rs @@ -0,0 +1,531 @@ +//! Regression tests for Wave 5E R2: +//! - Desktop `"N More"` overflow view popover toggle (`true -> false`), `Escape` dismissal, +//! mutual exclusion with `Filter`/`Sort`/`GroupBy` toolbar panels, clicking an overflow view item +//! to switch active view, single-source `database_overflow_tabs` across unnamed views, and +//! `database_clipped_local_rect_to_screen` horizontal clipping under `scroll_x > 0`; +//! - Multi-week Calendar event inline editing (`calendar_day_index`), aligning the inline editor +//! and hidden underlying chip label on whichever week segment was clicked while keeping all +//! other week segments' titles visible. + +use std::collections::BTreeMap; + +use blocksuite_editor::{ + block_flow::FlowRect, + database::{ActiveToolbarPanel, DatabaseAuthoringHitKind, DatabaseHitKind, DatabasePrim}, +}; +use blocksuite_playground_doc::schema::{ + BlockSpec, DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec, ParagraphType, +}; +use serde_json::json; +use ui::{Modifiers, PlatformInput, ScrollDelta, ScrollEvent, ScrollSource, TouchPhase, point, px}; + +use crate::{HOME_PAGE_ID, PlaygroundOptions, PlaygroundTheme, room_client::DocState}; + +use super::tests_inline_and_popovers::open_authoring_window; + +fn build_wave5e_r2_doc() -> (DocState, String) { + let mut doc = DocState::new("wave5e-r2", 88).expect("doc"); + doc.workspace.initialize_meta().unwrap(); + doc.workspace + .create_page(HOME_PAGE_ID, "Wave 5E R2", 1_773_000_000_000) + .unwrap(); + let page = doc.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + page.add_block( + "p-root", + BlockSpec::Page { + title: "Wave 5E R2".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block( + "p-note", + BlockSpec::Note { xywh: None }, + Some("p-root"), + None, + 2, + ) + .unwrap(); + let db_id = "db-w5e".to_string(); + let mut cells = BTreeMap::new(); + // Span `r1` across Sat 2026-03-07 .. Tue 2026-03-10 (`1_772_841_600_000` .. `1_773_100_800_000`) + // so Calendar view renders two distinct week segments in March 2026. + cells.insert( + "r1".into(), + BTreeMap::from([ + ("c-status".into(), DatabaseCellSpec::Text("opt-todo".into())), + ("c-due".into(), DatabaseCellSpec::Integer(1_772_841_600_000)), + ("c-end".into(), DatabaseCellSpec::Integer(1_773_100_800_000)), + ]), + ); + page.add_block( + &db_id, + BlockSpec::Database(DatabaseSpec { + title: "Wave 5E R2 Roadmap".into(), + columns: vec![ + DatabaseColumnSpec { + id: "title".into(), + column_type: "title".into(), + name: "Task".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "c-status".into(), + column_type: "select".into(), + name: "Status".into(), + data: json!({ + "options": [ + { "id": "opt-todo", "value": "Todo", "color": "var(--affine-tag-blue)" }, + { "id": "opt-done", "value": "Done", "color": "var(--affine-tag-green)" } + ] + }), + }, + DatabaseColumnSpec { + id: "c-due".into(), + column_type: "date".into(), + name: "Start".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "c-end".into(), + column_type: "date".into(), + name: "End".into(), + data: json!({}), + }, + ], + // Include unnamed views (`""`) so `"Table View"` / `"Kanban View"` fallback labels + // overflow on narrow desktop (`390px`) and test single-source `database_overflow_tabs`. + views: vec![ + DatabaseViewSpec { + id: "v-table".into(), + name: "Main Table".into(), + mode: "table".into(), + raw: json!({ + "columns": [ + { "id": "title", "width": 260 }, + { "id": "c-status", "width": 240 }, + { "id": "c-due", "width": 240 }, + { "id": "c-end", "width": 240 } + ] + }), + }, + DatabaseViewSpec { + id: "v-cal".into(), + name: "Release Calendar".into(), + mode: "calendar".into(), + raw: json!({ + "date": { + "startColumnId": "c-due", + "endColumnId": "c-end" + } + }), + }, + DatabaseViewSpec { + id: "v-unnamed-table".into(), + name: String::new(), + mode: "table".into(), + raw: json!({}), + }, + DatabaseViewSpec { + id: "v-unnamed-kanban".into(), + name: String::new(), + mode: "kanban".into(), + raw: json!({ + "groupBy": { + "type": "groupBy", + "columnId": "c-status", + "name": "select" + } + }), + }, + ], + cells, + }), + Some("p-note"), + None, + 3, + ) + .unwrap(); + page.add_block( + "r1", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Ship Wiring".into(), + }, + Some(&db_id), + None, + 4, + ) + .unwrap(); + page.stop_capturing().unwrap(); + (doc, db_id) +} + +#[test] +fn more_views_popover_toggles_escapes_switches_view_and_clips_scrolled_drop_line() { + let (state, db_id) = build_wave5e_r2_doc(); + let (platform, app, win, headless) = open_authoring_window( + 390, + 844, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + form_factor: crate::FormFactor::Desktop, + ..Default::default() + }, + state, + ); + let tick = || { + platform.run_until_parked(); + headless.request_frame(); + platform.run_until_parked(); + }; + tick(); + + let more_center = || { + app.update(|cx| { + win.update(cx, |v, w, _| { + let geom = v.current_page_geometry(f32::from(w.viewport_size().width)); + let layout = v.flow_layout().expect("layout"); + let block = layout.block(&db_id).expect("db block"); + let hit = v + .flow + .database_hits(&db_id) + .iter() + .find(|h| matches!(h.kind, DatabaseHitKind::ToggleMoreViews)) + .expect("ToggleMoreViews hit"); + point( + px(geom.column_x + block.x + hit.rect.x + hit.rect.w * 0.5), + px(crate::TOPBAR_HEIGHT + block.y + hit.rect.y + hit.rect.h * 0.5 - v.scroll_y), + ) + }) + .unwrap() + }) + }; + + // 1. Click `N More` -> opens; click `N More` again -> closes cleanly (`true -> false`). + let pt = more_center(); + headless.simulate_click(pt); + tick(); + app.update(|cx| { + win.update(cx, |v, w, _| { + assert!(v.flow.database_state.state_for(&db_id).more_views_open); + let layout = v.flow_layout().unwrap(); + let (_, overlay) = v + .database_popover_overlay(&layout, w) + .expect("More popover overlay"); + let overflow_count = v.flow.database_overflow_tabs(&db_id).len(); + assert!(overflow_count >= 2); + assert_eq!( + overlay.hits.len(), + overflow_count, + "More popover items must come directly from single-source `database_overflow_tabs`" + ); + }) + .unwrap(); + }); + headless.simulate_click(pt); + tick(); + app.update(|cx| { + win.update(cx, |v, w, _| { + assert!( + !v.flow.database_state.state_for(&db_id).more_views_open, + "second click on N More button must toggle More menu closed" + ); + let layout = v.flow_layout().unwrap(); + assert!(v.database_popover_overlay(&layout, w).is_none()); + }) + .unwrap(); + }); + + // 2. Open `N More` -> press `Escape` -> closes cleanly. + headless.simulate_click(pt); + tick(); + app.update(|cx| { + win.update(cx, |v, w, cx| { + assert!(v.flow.database_state.state_for(&db_id).more_views_open); + let esc = ui::KeyDownEvent { + keystroke: ui::Keystroke::parse("escape").unwrap(), + is_held: false, + prefer_character_input: false, + }; + assert!(v.database_authoring_key_down(&esc, w, cx)); + assert!( + !v.flow.database_state.state_for(&db_id).more_views_open, + "Escape must dismiss open More views popover" + ); + }) + .unwrap(); + }); + tick(); + + // 3. Open `N More` -> click `Filter` -> `More` closes immediately so dismissing `Filter` + // never resurrects `More`. + headless.simulate_click(pt); + tick(); + let filter_pt = app.update(|cx| { + win.update(cx, |v, w, _| { + v.database_authoring_hit_screen_center(&db_id, w, |k| { + matches!(k, DatabaseAuthoringHitKind::ToolbarToggleFilter) + }) + .map(|(x, y)| point(px(x), px(y))) + .expect("Filter button") + }) + .unwrap() + }); + headless.simulate_click(filter_pt); + tick(); + app.update(|cx| { + win.update(cx, |v, w, cx| { + let st = v.flow.database_state.state_for(&db_id); + assert!( + !st.more_views_open, + "opening Filter must immediately clear more_views_open" + ); + assert_eq!(st.authoring.toolbar_panel, Some(ActiveToolbarPanel::Filter)); + let esc = ui::KeyDownEvent { + keystroke: ui::Keystroke::parse("escape").unwrap(), + is_held: false, + prefer_character_input: false, + }; + assert!(v.database_authoring_key_down(&esc, w, cx)); + let after = v.flow.database_state.state_for(&db_id); + assert!(!after.more_views_open); + assert!(after.authoring.toolbar_panel.is_none()); + }) + .unwrap(); + }); + tick(); + + // 4. Horizontal scroll (`scroll_x > 0`) clips row drop indicator strictly to `code_scroll.area`. + app.update(|cx| { + win.update(cx, |v, w, cx| { + v.scroll_database_x(&db_id, 140.0, cx); + let layout = v.flow_layout().unwrap(); + let block = layout.block(&db_id).unwrap(); + let cs = block.body.code_scroll.expect("table code_scroll"); + let geom = v.current_page_geometry(f32::from(w.viewport_size().width)); + let clipped = v + .database_clipped_local_rect_to_screen( + &db_id, + FlowRect::new(8.0, 120.0, cs.area.w + cs.max_x, 2.0), + true, + w, + ) + .expect("clipped drop line"); + assert!( + (clipped.x - (geom.column_x + block.x + cs.area.x)).abs() < 0.01 + && (clipped.right() - (geom.column_x + block.x + cs.area.right())).abs() < 0.01, + "scrolled row drop line must clip strictly to table grid area: got {clipped:?}" + ); + }) + .unwrap(); + }); + + // 5. Open `N More` -> click the last overflow item (`v-unnamed-kanban`) -> switches view & closes. + let pt = more_center(); + headless.simulate_click(pt); + tick(); + let (target_view_id, item_pt) = app.update(|cx| { + win.update(cx, |v, w, _| { + let layout = v.flow_layout().unwrap(); + let (_, overlay) = v.database_popover_overlay(&layout, w).unwrap(); + let last = overlay.hits.last().expect("overflow item"); + let vid = match &last.kind { + DatabaseAuthoringHitKind::SwitchView { view_id } => view_id.clone(), + other => panic!("unexpected More hit: {other:?}"), + }; + ( + vid, + point( + px(last.rect.x + last.rect.w * 0.5), + px(last.rect.y + last.rect.h * 0.5), + ), + ) + }) + .unwrap() + }); + headless.simulate_click(item_pt); + tick(); + app.update(|cx| { + win.update(cx, |v, _, _| { + let st = v.flow.database_state.state_for(&db_id); + assert!(!st.more_views_open); + assert_eq!( + st.active_view_id.as_deref(), + Some(target_view_id.as_str()), + "clicking an item in N More popover must switch active view" + ); + }) + .unwrap(); + }); +} + +#[test] +fn multi_week_calendar_event_inline_edit_aligns_chip_segment_and_preserves_other_week_label() { + let (state, db_id) = build_wave5e_r2_doc(); + let (platform, app, win, headless) = open_authoring_window( + 1024, + 820, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + state, + ); + let tick = || { + platform.run_until_parked(); + headless.request_frame(); + platform.run_until_parked(); + }; + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.set_database_active_view(&db_id, "v-cal", cx); + }) + .unwrap(); + }); + tick(); + headless.dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(512.0), px(400.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(-100_000.0))), + modifiers: Modifiers::default(), + touch_phase: TouchPhase::Moved, + source: ScrollSource::Pointer, + })); + tick(); + + let segments: Vec<(i64, FlowRect, ui::Point)> = app.update(|cx| { + win.update(cx, |v, w, _| { + let geom = v.current_page_geometry(f32::from(w.viewport_size().width)); + let layout = v.flow_layout().unwrap(); + let block = layout.block(&db_id).unwrap(); + v.flow + .database_authoring_hits(&db_id) + .iter() + .filter_map(|h| match &h.kind { + DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, day_index } + if row_id == "r1" => + { + Some(( + *day_index, + h.rect, + point( + px(geom.column_x + block.x + h.rect.x + 18.0), + px(crate::TOPBAR_HEIGHT + block.y + h.rect.y + h.rect.h * 0.5 + - v.scroll_y), + ), + )) + } + _ => None, + }) + .collect() + }) + .unwrap() + }); + assert_eq!( + segments.len(), + 2, + "2-week March event must emit 2 CalendarDragEventStart week segments" + ); + assert!( + (segments[0].1.y - segments[1].1.y).abs() > 40.0, + "Week 1 and Week 2 segments must be on distinct calendar rows" + ); + + let chip_label_ys = |v: &crate::PlaygroundView, w: &ui::Window| -> Vec { + let st = v.flow.database_state.state_for(&db_id); + let db = v.database_snapshot_data(&db_id).unwrap(); + let zero_off = |_: i64| 0; + let titles = BTreeMap::new(); + let out = blocksuite_editor::database::layout_database_block( + &db, + &st, + 720.0, + PlaygroundTheme::Light, + ui::Direction::Ltr, + crate::FormFactor::Desktop, + false, + 1_773_014_400_000, + &zero_off, + &titles, + w, + ); + out.prims + .iter() + .filter_map(|p| match p { + DatabasePrim::Text { + y, clip: Some(c), .. + } if (c.h - 22.0).abs() < 0.1 => Some(*y), + _ => None, + }) + .collect() + }; + + app.update(|cx| { + win.update(cx, |v, w, _| { + assert_eq!( + chip_label_ys(v, w).len(), + 2, + "both week segments must render chip labels when idle" + ); + }) + .unwrap(); + }); + + // Click Week 1 segment -> inline box overlays Week 1 AND Week 2 keeps its label primitive! + headless.simulate_click(segments[0].2); + tick(); + app.update(|cx| { + win.update(cx, |v, w, _| { + let st = v.flow.database_state.state_for(&db_id); + assert_eq!( + st.authoring + .active_cell + .as_ref() + .and_then(|e| e.calendar_day_index), + Some(segments[0].0) + ); + let (box_rect, _) = v.database_inline_screen_box(w).expect("week 1 inline box"); + assert!( + (box_rect.y - f32::from(segments[0].2.y)).abs() < 16.0, + "clicking Week 1 segment must place inline editor on Week 1 row" + ); + let ys = chip_label_ys(v, w); + assert_eq!(ys.len(), 1); + assert!( + (ys[0] - segments[1].1.y).abs() < 20.0, + "Week 2 segment must remain visible while editing Week 1" + ); + }) + .unwrap(); + }); + + // Click Week 2 segment -> inline box overlays Week 2 AND Week 1 keeps its label primitive! + headless.simulate_click(segments[1].2); + tick(); + app.update(|cx| { + win.update(cx, |v, w, _| { + let st = v.flow.database_state.state_for(&db_id); + assert_eq!( + st.authoring + .active_cell + .as_ref() + .and_then(|e| e.calendar_day_index), + Some(segments[1].0) + ); + let (box_rect, _) = v.database_inline_screen_box(w).expect("week 2 inline box"); + assert!( + (box_rect.y - f32::from(segments[1].2.y)).abs() < 16.0, + "clicking Week 2 segment must place inline editor on Week 2 row" + ); + let ys = chip_label_ys(v, w); + assert_eq!(ys.len(), 1); + assert!( + (ys[0] - segments[0].1.y).abs() < 20.0, + "Week 1 segment must remain visible while editing Week 2" + ); + }) + .unwrap(); + }); +} diff --git a/blocksuite/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs index 20c95a00bd..3fd332b197 100644 --- a/blocksuite/crates/playground/src/overlays/view.rs +++ b/blocksuite/crates/playground/src/overlays/view.rs @@ -412,8 +412,15 @@ impl PlaygroundView { .then(|| (block.block_id.clone(), world_x - r.x, world_y - r.y)) }) { self.dismiss_all_database_authoring(Some(&block_id), cx); + let prev_slot = self.database_input.as_ref().map(|s| s.target.clone()); let consumed = self.click_database_point(&block_id, local_x, local_y, Some(window), cx); + if self.database_input.as_ref().is_some_and(|s| { + !s.target.is_popover_field() + && prev_slot.as_ref().is_none_or(|p| !p.same_slot(&s.target)) + }) { + self.place_database_inline_caret_at_point(event.position, window, cx); + } self.show_database_readonly_toast_once(cx); if self.database_input.is_none() { self.clear_body_selection(window, cx); diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/database.rs b/blocksuite/crates/playground/src/overlays/view_mobile/database.rs index c153e6292f..1f8f3d8be2 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/database.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/database.rs @@ -362,6 +362,11 @@ impl PlaygroundView { } let hits = self.flow.database_hits(block_id); if hits.is_empty() { + if self.flow.database_state.close_more_views(block_id) { + self.env_rev += 1; + cx.notify(); + return true; + } return false; } let code_scroll = self @@ -387,8 +392,16 @@ impl PlaygroundView { }) .cloned(); let Some(target) = target else { + if self.flow.database_state.close_more_views(block_id) { + self.env_rev += 1; + cx.notify(); + return true; + } return false; }; + if !matches!(target.kind, database::DatabaseHitKind::ToggleMoreViews) { + let _ = self.flow.database_state.close_more_views(block_id); + } match &target.kind { database::DatabaseHitKind::SwitchView { view_id } => { self.set_database_active_view(block_id, view_id, cx);