diff --git a/blocksuite/crates/editor/src/block_flow/body.rs b/blocksuite/crates/editor/src/block_flow/body.rs index eb498487a1..d53e6f0958 100644 --- a/blocksuite/crates/editor/src/block_flow/body.rs +++ b/blocksuite/crates/editor/src/block_flow/body.rs @@ -343,6 +343,14 @@ impl BlockBody { for (_, prim) in prims().filter(|(idx, prim)| fixed(*idx, prim)) { self.paint_single_prim(prim, origin, state, window, cx); } + if let Some(frozen) = crate::database::frozen_table_area(scroll_cfg.area) { + window.with_local_paint_mask( + ui::ContentMask { + bounds: frozen.bounds(origin), + }, + |window| self.paint_prims(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); @@ -356,7 +364,7 @@ impl BlockBody { /// Paint everything but the caption slot, so a canvas block can clip its content to its /// frame and place the caption with [`Self::paint_caption`]. - pub(crate) fn paint_content( + pub fn paint_content( &self, origin: Point, state: BlockPaint, diff --git a/blocksuite/crates/editor/src/database/authoring.rs b/blocksuite/crates/editor/src/database/authoring.rs index cb1b222e79..83fb650a1e 100644 --- a/blocksuite/crates/editor/src/database/authoring.rs +++ b/blocksuite/crates/editor/src/database/authoring.rs @@ -67,6 +67,9 @@ pub enum ActiveToolbarPanel { Filter, Sort, GroupBy, + Properties, + NewView, + NewProperty, } /// Transient draft rule inside the Filter panel before clicking Apply. @@ -112,10 +115,13 @@ pub struct DatabaseAuthoringState { pub column_resize: Option, pub progress_preview: Option, pub active_cell: Option, + pub option_menu: Option, pub select_scroll_y: f32, + pub toolbar_scroll_y: f32, pub toolbar_panel: Option, pub filter_draft: FilterDraftState, pub calendar_drag: Option, + pub calendar_resize_end: Option, pub kanban_drag: Option, } @@ -125,7 +131,9 @@ impl DatabaseAuthoringState { self.row_menu = None; self.lane_menu = None; self.active_cell = None; + self.option_menu = None; self.select_scroll_y = 0.0; + self.toolbar_scroll_y = 0.0; self.toolbar_panel = None; } } @@ -134,6 +142,9 @@ impl DatabaseAuthoringState { #[derive(Clone, Debug, PartialEq)] pub enum DatabaseAuthoringHitKind { AddColumn, + CreateProperty { + column_type: String, + }, OpenColumnMenu { column_id: String, }, @@ -185,6 +196,12 @@ pub enum DatabaseAuthoringHitKind { label: String, color: String, }, + SelectOptionMenu { + option_id: String, + }, + SelectSaveOption { + color: Option, + }, SelectDeleteOption { column_id: String, option_id: String, @@ -241,6 +258,18 @@ pub enum DatabaseAuthoringHitKind { view_id: String, }, AddView, + CreateView { + mode: blocksuite_playground_doc::read::DatabaseViewMode, + }, + ToolbarProperties, + SetColumnHidden { + column_id: String, + hidden: bool, + }, + ReorderProperty { + column_id: String, + to_index: usize, + }, OpenRowPeek { row_id: String, }, @@ -275,9 +304,10 @@ pub enum DatabaseAuthoringHitKind { column_id: String, bucket_key: String, }, - KanbanLaneMenuDeleteGroup { + KanbanLaneCards { column_id: String, - option_id: String, + rows: Vec, + delete: bool, }, CalendarResizeEvent { row_id: String, @@ -345,6 +375,28 @@ pub fn handle_authoring_key( }); } + if flow_state + .state_for(block_id) + .authoring + .option_menu + .is_some() + { + match key { + DatabaseAuthoringKey::Enter => { + return super::select_popover::save_option( + page, flow_state, block_id, data, None, now_ms, + ); + } + DatabaseAuthoringKey::Escape => { + super::select_popover::close_option_menu(flow_state, block_id); + return Ok(AuthoringActionResult { + handled: true, + doc_mutated: false, + }); + } + _ => {} + } + } if let Some(menu) = flow_state.state_for(block_id).authoring.column_menu { match key { DatabaseAuthoringKey::Escape => { @@ -911,6 +963,107 @@ mod tests { db.clone() } + #[test] + fn view_and_lane_actions_and_chip_removal_are_isolated_undo_steps() { + use DatabaseAuthoringHitKind as Hit; + use blocksuite_playground_doc::read::DatabaseViewMode; + let actions = [ + Hit::SetColumnHidden { + column_id: "c-prog".into(), + hidden: true, + }, + Hit::ReorderProperty { + column_id: "c-prog".into(), + to_index: 0, + }, + Hit::CreateView { + mode: DatabaseViewMode::Table, + }, + Hit::CreateView { + mode: DatabaseViewMode::Calendar, + }, + Hit::CreateView { + mode: DatabaseViewMode::Kanban, + }, + Hit::SelectToggleOption { + row_id: "r1".into(), + column_id: "c-tags".into(), + option_id: "t-ui".into(), + }, + Hit::SelectToggleOption { + row_id: "r1".into(), + column_id: "c-status".into(), + option_id: "s-todo".into(), + }, + Hit::KanbanLaneCards { + column_id: "c-status".into(), + rows: vec!["r1".into(), "r2".into()], + delete: false, + }, + Hit::KanbanLaneCards { + column_id: "c-status".into(), + rows: vec!["r1".into(), "r2".into()], + delete: true, + }, + ]; + for kind in actions { + let (mut page, id) = seed_editor_db(); + let before = snap_db(&page, &id); + let mut state = DatabaseFlowState::default(); + page.stop_capturing().unwrap(); + let hit = DatabaseAuthoringHit { + kind, + rect: FlowRect::new(0.0, 0.0, 100.0, 24.0), + scrolls_x: false, + }; + let result = + handle_authoring_hit(&mut page, &mut state, &id, &before, &hit, 0.0, &|_| 0, 100) + .unwrap(); + assert!(result.doc_mutated, "{:?}", hit.kind); + let after = snap_db(&page, &id); + assert_eq!(after.columns, before.columns); + match &hit.kind { + Hit::CreateView { mode } => assert_eq!(&after.views.last().unwrap().mode, mode), + Hit::SetColumnHidden { column_id, .. } => assert_eq!( + after.views[0] + .columns + .iter() + .find(|c| &c.id == column_id) + .unwrap() + .hide, + Some(true) + ), + Hit::ReorderProperty { column_id, .. } => { + assert_eq!(&after.views[0].columns[0].id, column_id) + } + Hit::KanbanLaneCards { delete: true, .. } => assert!(after.rows.is_empty()), + Hit::KanbanLaneCards { + column_id, rows, .. + } => { + for row in rows { + assert!( + after + .cells + .get(&(row.clone(), column_id.clone())) + .is_none_or(|v| v.as_string_list().is_empty()) + ); + } + } + Hit::SelectToggleOption { + row_id, column_id, .. + } => assert!( + after + .cells + .get(&(row_id.clone(), column_id.clone())) + .is_none_or(|v| v.as_string_list().is_empty()) + ), + _ => unreachable!(), + } + assert!(page.undo().unwrap().is_some()); + assert_eq!(snap_db(&page, &id), before, "{:?}", hit.kind); + } + } + #[test] fn cell_draft_validation_and_formatting_table_driven() { let utc = |_: i64| 0_i32; diff --git a/blocksuite/crates/editor/src/database/authoring_dispatch.rs b/blocksuite/crates/editor/src/database/authoring_dispatch.rs index 3a4a503988..d55471e304 100644 --- a/blocksuite/crates/editor/src/database/authoring_dispatch.rs +++ b/blocksuite/crates/editor/src/database/authoring_dispatch.rs @@ -13,6 +13,7 @@ use super::{ ActiveCellEditor, ActiveToolbarPanel, AuthoringActionResult, CalendarDragState, ColumnMenuState, DatabaseAuthoringHit, DatabaseAuthoringHitKind, resolve_active_view, }, + authoring_id::fresh_database_id, calendar_edit::{create_calendar_row_on_day, reschedule_calendar_row_to_day}, cell_editor::{is_editable_column_type, progress_from_bar_x}, column_ops::{insert_column_relative, make_new_column_spec, resolve_visible_columns}, @@ -23,47 +24,6 @@ use super::{ }, }; -/// Generate a collision-free identifier scoped to `page.client_id()` and verified against all -/// existing column, option, view, and row identifiers in `data` (plus page blocks for `"row"`). -pub(super) fn fresh_database_id( - page: &PageDocSession, - data: &DatabaseData, - prefix: &str, -) -> String { - let mut used: std::collections::HashSet = std::collections::HashSet::new(); - for col in &data.columns { - used.insert(col.id.clone()); - if let Some(opts) = col.data.get("options").and_then(|v| v.as_array()) { - for opt in opts { - if let Some(id) = opt.get("id").and_then(|v| v.as_str()) { - used.insert(id.to_string()); - } - } - } - } - for view in &data.views { - used.insert(view.id.clone()); - } - for row in &data.rows { - used.insert(row.row_id.clone()); - } - let snap = if prefix == "row" { - page.read_page_snapshot().ok() - } else { - None - }; - let client_id = page.client_id(); - let mut seq = page.revision().saturating_add(1); - loop { - let candidate = format!("{prefix}-{client_id:x}-{seq:x}"); - let exists_in_page = snap.as_ref().is_some_and(|s| s.block(&candidate).is_some()); - if !used.contains(&candidate) && !exists_in_page { - return candidate; - } - seq = seq.wrapping_add(1); - } -} - /// Dispatch a click on one [`DatabaseAuthoringHit`] and commit any resulting CRDT mutation. #[allow(clippy::too_many_arguments)] pub fn handle_authoring_hit( @@ -90,10 +50,14 @@ pub fn handle_authoring_hit( }; match &hit.kind { - DatabaseAuthoringHitKind::AddColumn => { + DatabaseAuthoringHitKind::AddColumn | DatabaseAuthoringHitKind::CreateProperty { .. } => { + let column_type = match &hit.kind { + DatabaseAuthoringHitKind::CreateProperty { column_type } => column_type.as_str(), + _ => "rich-text", + }; let col_id = fresh_database_id(page, data, "col"); let name = format!("Column {}", data.columns.len() + 1); - let spec = make_new_column_spec(col_id, name, "rich-text"); + let spec = make_new_column_spec(col_id, name, column_type); let commit = page.add_database_column(block_id, Some(&view.id), spec, None, now_ms)?; flow_state.authoring_mut(block_id).dismiss_popovers(); Ok(AuthoringActionResult { @@ -381,12 +345,38 @@ pub fn handle_authoring_hit( doc_mutated: commit.is_some(), }) } + DatabaseAuthoringHitKind::SelectOptionMenu { option_id } => { + let auth = flow_state.authoring_mut(block_id); + if let Some(ed) = auth.active_cell.as_mut() + && let Some(opt) = data + .columns + .iter() + .find(|c| c.id == ed.column_id) + .and_then(|c| c.select_options().into_iter().find(|o| o.id == *option_id)) + { + ed.select_filter = opt.value; + auth.option_menu = Some(option_id.clone()); + } + Ok(AuthoringActionResult { + handled: true, + doc_mutated: false, + }) + } + DatabaseAuthoringHitKind::SelectSaveOption { color } => super::select_popover::save_option( + page, + flow_state, + block_id, + data, + color.as_deref(), + now_ms, + ), DatabaseAuthoringHitKind::SelectDeleteOption { column_id, option_id, } => { let commit = page.delete_database_select_option(block_id, column_id, option_id, now_ms)?; + super::select_popover::close_option_menu(flow_state, block_id); Ok(AuthoringActionResult { handled: true, doc_mutated: commit.is_some(), @@ -415,30 +405,42 @@ pub fn handle_authoring_hit( doc_mutated: false, }) } - DatabaseAuthoringHitKind::ToolbarToggleSort => { + DatabaseAuthoringHitKind::ToolbarToggleSort + | DatabaseAuthoringHitKind::ToolbarToggleGroupBy + | DatabaseAuthoringHitKind::ToolbarProperties + | DatabaseAuthoringHitKind::AddView => { + let panel = match hit.kind { + DatabaseAuthoringHitKind::ToolbarToggleSort => ActiveToolbarPanel::Sort, + DatabaseAuthoringHitKind::ToolbarToggleGroupBy => ActiveToolbarPanel::GroupBy, + DatabaseAuthoringHitKind::ToolbarProperties => ActiveToolbarPanel::Properties, + _ => ActiveToolbarPanel::NewView, + }; let auth = flow_state.authoring_mut(block_id); - if auth.toolbar_panel == Some(ActiveToolbarPanel::Sort) { - auth.toolbar_panel = None; - } else { - auth.dismiss_popovers(); - auth.toolbar_panel = Some(ActiveToolbarPanel::Sort); - } + let open = auth.toolbar_panel != Some(panel); + auth.dismiss_popovers(); + auth.toolbar_panel = open.then_some(panel); Ok(AuthoringActionResult { handled: true, doc_mutated: false, }) } - DatabaseAuthoringHitKind::ToolbarToggleGroupBy => { - let auth = flow_state.authoring_mut(block_id); - if auth.toolbar_panel == Some(ActiveToolbarPanel::GroupBy) { - auth.toolbar_panel = None; - } else { - auth.dismiss_popovers(); - auth.toolbar_panel = Some(ActiveToolbarPanel::GroupBy); - } + DatabaseAuthoringHitKind::SetColumnHidden { column_id, hidden } => { + let commit = page + .set_database_view_column_hidden(block_id, &view.id, column_id, *hidden, now_ms)?; Ok(AuthoringActionResult { handled: true, - doc_mutated: false, + doc_mutated: commit.is_some(), + }) + } + DatabaseAuthoringHitKind::ReorderProperty { + column_id, + to_index, + } => { + let commit = page + .reorder_database_view_column(block_id, &view.id, column_id, *to_index, now_ms)?; + Ok(AuthoringActionResult { + handled: true, + doc_mutated: commit.is_some(), }) } DatabaseAuthoringHitKind::FilterDraftCycleColumn => { @@ -688,6 +690,7 @@ pub fn handle_authoring_hit( }) } DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, day_index } => { + flow_state.authoring_mut(block_id).calendar_resize_end = None; flow_state.authoring_mut(block_id).calendar_drag = Some(CalendarDragState { row_id: row_id.clone(), origin_day: *day_index, @@ -733,8 +736,8 @@ pub fn handle_authoring_hit( seed_value.as_ref(), now_ms, ), - DatabaseAuthoringHitKind::AddView => { - super::row_ops::handle_add_view(page, flow_state, block_id, data, now_ms) + DatabaseAuthoringHitKind::CreateView { mode } => { + super::row_ops::handle_add_view(page, flow_state, block_id, data, mode, now_ms) } DatabaseAuthoringHitKind::OpenRowMenu { .. } | DatabaseAuthoringHitKind::RowMenuInsertAbove { .. } @@ -745,7 +748,7 @@ pub fn handle_authoring_hit( ), DatabaseAuthoringHitKind::KanbanLaneMenu { .. } | DatabaseAuthoringHitKind::KanbanLaneMenuAddCard { .. } - | DatabaseAuthoringHitKind::KanbanLaneMenuDeleteGroup { .. } => { + | DatabaseAuthoringHitKind::KanbanLaneCards { .. } => { super::row_ops::handle_lane_menu_action( page, flow_state, block_id, data, &hit.kind, now_ms, ) diff --git a/blocksuite/crates/editor/src/database/authoring_id.rs b/blocksuite/crates/editor/src/database/authoring_id.rs new file mode 100644 index 0000000000..73d550f4aa --- /dev/null +++ b/blocksuite/crates/editor/src/database/authoring_id.rs @@ -0,0 +1,42 @@ +use blocksuite_playground_doc::{read::DatabaseData, session::PageDocSession}; + +/// Generate a collision-free identifier scoped to `page.client_id()` and verified against all +/// existing column, option, view, and row identifiers in `data` (plus page blocks for `"row"`). +pub(super) fn fresh_database_id( + page: &PageDocSession, + data: &DatabaseData, + prefix: &str, +) -> String { + let mut used: std::collections::HashSet = std::collections::HashSet::new(); + for col in &data.columns { + used.insert(col.id.clone()); + if let Some(opts) = col.data.get("options").and_then(|v| v.as_array()) { + for opt in opts { + if let Some(id) = opt.get("id").and_then(|v| v.as_str()) { + used.insert(id.to_string()); + } + } + } + } + for view in &data.views { + used.insert(view.id.clone()); + } + for row in &data.rows { + used.insert(row.row_id.clone()); + } + let snap = if prefix == "row" { + page.read_page_snapshot().ok() + } else { + None + }; + let client_id = page.client_id(); + let mut seq = page.revision().saturating_add(1); + loop { + let candidate = format!("{prefix}-{client_id:x}-{seq:x}"); + let exists_in_page = snap.as_ref().is_some_and(|s| s.block(&candidate).is_some()); + if !used.contains(&candidate) && !exists_in_page { + return candidate; + } + seq = seq.wrapping_add(1); + } +} diff --git a/blocksuite/crates/editor/src/database/calendar_edit.rs b/blocksuite/crates/editor/src/database/calendar_edit.rs index 1a4cf6746c..c0ee0af86b 100644 --- a/blocksuite/crates/editor/src/database/calendar_edit.rs +++ b/blocksuite/crates/editor/src/database/calendar_edit.rs @@ -18,6 +18,25 @@ use super::{ resolve_rich_text_plain, }; +/// Move the transient entry onto its destination before assigning its weekly slots. +pub(super) fn preview_event_range( + entry: &mut CalendarEntry, + target_day: i64, + resize_end: Option, + offset: &dyn Fn(i64) -> i32, +) -> std::ops::RangeInclusive { + let start = entry.start_at_ms; + let end = entry.end_at_ms.unwrap_or(start); + let (a, b) = match resize_end { + Some(true) => (start, timestamp_on_day(end, target_day, offset)), + Some(false) => (timestamp_on_day(start, target_day, offset), end), + None => move_event_times(start, end, target_day, offset), + }; + entry.start_at_ms = a.min(b); + entry.end_at_ms = Some(a.max(b)); + local_day_index(a.min(b), offset)..=local_day_index(a.max(b), offset) +} + pub(super) fn collect_calendar_entries( ctx: &DbRenderCtx<'_>, start_col_id: &str, @@ -66,12 +85,61 @@ pub(super) fn collect_calendar_entries( color, start_at_ms: start_at, end_at_ms: end_at, - badges: Vec::new(), + badges: calendar_badges(ctx, row), }) }) .collect() } +fn calendar_badges( + ctx: &DbRenderCtx<'_>, + row: &blocksuite_playground_doc::read::DatabaseRow, +) -> Vec<(String, Option)> { + let mut badges = Vec::new(); + let Some(card) = &ctx.view.card else { + return badges; + }; + for id in &card.visible_property_ids { + let Some(col) = ctx.data.columns.iter().find(|c| c.id == *id) else { + continue; + }; + let Some(value) = ctx + .data + .cells + .get(&(row.row_id.clone(), id.clone())) + .filter(|v| !v.is_empty()) + else { + continue; + }; + if matches!(col.column_type.as_str(), "select" | "multi-select") { + let options = col.select_options(); + for id in value.as_string_list() { + let option = options.iter().find(|o| o.id == id || o.value == id); + badges.push( + option.map_or_else(|| (id, None), |o| (o.value.clone(), Some(o.color.clone()))), + ); + } + } else { + let label = match col.column_type.as_str() { + "progress" => value.as_i64().map(|v| super::format_database_progress(v).1), + "checkbox" => value + .as_bool() + .map(|checked| format!("{} {}", if checked { "☑" } else { "□" }, col.name)), + _ => Some(super::initial_cell_draft( + ctx.data, + row, + col, + ctx.offset_at_ms, + )), + }; + if let Some(label) = label.filter(|s| !s.is_empty()) { + badges.push((label, None)); + } + } + } + badges +} + /// 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( @@ -120,9 +188,9 @@ pub(super) fn render_calendar_day_controls( return; } let plus_x = if ctx.direction.is_rtl() { - cell_rect.right() - 22.0 - } else { cell_rect.x + 4.0 + } else { + cell_rect.right() - 22.0 }; let plus_rect = FlowRect::new(plus_x, cell_rect.y + 3.0, 18.0, 18.0); if show_plus { @@ -156,6 +224,24 @@ pub fn day_index_to_local_midnight_ms(day_index: i64, offset_at_ms: &dyn Fn(i64) local_wall_ms_to_utc_ms(day_index.saturating_mul(86_400_000), offset_at_ms) } +pub(super) fn timestamp_on_day(ms: i64, day: i64, offset: &dyn Fn(i64) -> i32) -> i64 { + let wall = ms.saturating_add(i64::from(offset(ms)) * 60_000); + if wall.div_euclid(86_400_000) == day { + return ms; + } + local_wall_ms_to_utc_ms( + day.saturating_mul(86_400_000) + .saturating_add(wall.rem_euclid(86_400_000)), + offset, + ) +} + +fn move_event_times(start: i64, end: i64, day: i64, offset: &dyn Fn(i64) -> i32) -> (i64, i64) { + let duration_ms = end.saturating_sub(start); + let moved_start = timestamp_on_day(start, day, offset); + (moved_start, moved_start.saturating_add(duration_ms)) +} + /// Convert local wall-clock epoch milliseconds (`day_index * 86_400_000 + time of day`) to a UTC /// timestamp under `offset_at_ms`. A wall time that a spring-forward gap skips moves forward by /// the gap, and a wall time that a fall-back overlap repeats resolves to its first occurrence. @@ -194,14 +280,24 @@ pub(super) fn push_calendar_event_chip( let accent = entry.color.as_deref().map_or(ctx.palette.brand, |c| { super::resolve_tag_accent(c, ctx.theme) }); + let is_preview = ctx + .ui_state + .authoring + .calendar_drag + .as_ref() + .is_some_and(|drag| drag.row_id == entry.row_id); prims.push(DatabasePrim::Quad { rect, - fill: Some(accent.opacity(chip_tint_alpha)), + fill: Some(if is_preview { + ctx.palette.brand.opacity(0.10) + } else { + accent.opacity(chip_tint_alpha) + }), border: None, radius, dashed: false, }); - if draw_stripe { + if draw_stripe && !is_preview { let bar_x = if ctx.direction.is_rtl() { rect.right() - 3.0 } else { @@ -225,6 +321,37 @@ pub(super) fn push_calendar_event_chip( && drag_start_day.is_some() && active_day.is_none_or(|d| Some(d) == drag_start_day) }); + let mut badge_space = 0.0; + for (label, color) in &entry.badges { + let (bg, ink) = super::resolve_tag_color(color.as_deref().unwrap_or(""), ctx.theme); + let style = crate::block_flow::InlineStyle::new(crate::theme::FONT_SANS, 11.0, 500.0, ink); + let available = rect.w - 36.0 - badge_space; + if available < 24.0 { + break; + } + let (_, layout) = ctx.truncate_text(label, style, available - 10.0, 16.0); + let width = (layout.content_width().ceil() + 10.0).min(available); + let x = if ctx.direction.is_rtl() { + rect.x + badge_space + 4.0 + } else { + rect.right() - badge_space - width - 4.0 + }; + let pill = FlowRect::new(x, rect.y + (rect.h - 16.0) * 0.5, width, 16.0); + prims.push(DatabasePrim::Quad { + rect: pill, + fill: Some(bg), + border: None, + radius: 5.0, + dashed: false, + }); + prims.push(DatabasePrim::Text { + x: x + 5.0, + y: pill.y, + layout, + clip: Some(pill), + }); + badge_space += width + 4.0; + } if should_hide_title { *hide_active_chip = None; } else { @@ -236,9 +363,15 @@ pub(super) fn push_calendar_event_chip( 500.0, ctx.palette.text_primary, ), - rect.x + text_pad_x, + rect.x + + text_pad_x + + if ctx.direction.is_rtl() { + badge_space + } else { + 0.0 + }, rect.y, - (rect.w - text_pad_x - 4.0).max(1.0), + (rect.w - text_pad_x - 4.0 - badge_space).max(1.0), rect.h, align, )); @@ -337,21 +470,25 @@ pub fn reschedule_calendar_row_to_day( .cells .get(&(row_id.to_string(), start_col.to_string())) .and_then(DatabaseCellValue::as_i64); - let new_start_ms = day_index_to_local_midnight_ms(target_day_index, offset_at_ms); - let new_end_ms = end_col.and_then(|eid| { - let old_end = data - .cells - .get(&(row_id.to_string(), eid.to_string())) - .and_then(DatabaseCellValue::as_i64)?; - let old_start = old_start_ms?; - let old_start_day = local_day_index(old_start, offset_at_ms); - let old_end_day = local_day_index(old_end, offset_at_ms); - let span_days = (old_end_day - old_start_day).max(0); - Some(day_index_to_local_midnight_ms( - target_day_index + span_days, - offset_at_ms, - )) + let old_end = end_col.filter(|id| *id != start_col).and_then(|id| { + data.cells + .get(&(row_id.to_string(), id.to_string())) + .and_then(DatabaseCellValue::as_i64) }); + let (new_start_ms, new_end_ms) = match (old_start_ms, old_end) { + (Some(start), Some(end)) if end >= start => { + let (a, b) = move_event_times(start, end, target_day_index, offset_at_ms); + (a, Some(b)) + } + (Some(start), _) => ( + timestamp_on_day(start, target_day_index, offset_at_ms), + None, + ), + (None, _) => ( + day_index_to_local_midnight_ms(target_day_index, offset_at_ms), + None, + ), + }; let commit = page.reschedule_database_calendar_row( block_id, row_id, @@ -424,6 +561,179 @@ mod tests { } } + fn event(start: i64, end: i64) -> super::CalendarEntry { + super::CalendarEntry { + id: "event".into(), + row_id: "row".into(), + title: "Release".into(), + color: None, + start_at_ms: start, + end_at_ms: Some(end), + badges: vec![], + } + } + + #[test] + fn spring_forward_previews_place_moved_and_resized_events_on_their_civil_dates() { + use crate::database::{create_calendar_month_layout, days_from_civil}; + let day = days_from_civil(2026, 10, 4); + for (before, after, elapsed_minutes) in [(600, 660, 1380), (630, 660, 1410)] { + let transition = day * 86_400_000 + (120 - i64::from(before)) * 60_000; + let offset = |ms| if ms < transition { before } else { after }; + let start = day_index_to_local_midnight_ms(day, &offset); + let end = day_index_to_local_midnight_ms(day + 1, &offset); + assert_eq!(end - start, elapsed_minutes * 60_000); + let saturday = day + 6; + for (edge, target, delay, expected_days) in [ + (None, saturday, 0, vec![saturday]), + (None, saturday, 3_600_000, vec![saturday, saturday + 1]), + (Some(false), day, 0, vec![day, day + 1]), + (Some(true), day + 1, 0, vec![day, day + 1]), + ] { + let mut entry = event(start + delay, end + delay); + assert_eq!( + super::preview_event_range(&mut entry, target, edge, &offset), + expected_days[0]..=*expected_days.last().unwrap() + ); + assert_eq!(entry.end_at_ms.unwrap() - entry.start_at_ms, end - start); + let month = create_calendar_month_layout(2026, 10, &[entry], 0, &offset); + let cells: Vec<_> = month + .weeks + .iter() + .flatten() + .filter(|day| day.segment_slots > 0 || !day.entries.is_empty()) + .map(|day| day.day_index) + .collect(); + assert_eq!(cells, expected_days); + } + } + } + + #[test] + fn new_york_spring_forward_moves_preserve_duration_through_preview_reload_and_undo() { + use super::{DatabaseCellSpec, PageDocSession, reschedule_calendar_row_to_day}; + use crate::database::days_from_civil; + use blocksuite_playground_doc::{ + read::BlockContent, + schema::{BlockSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec}, + }; + use serde_json::json; + + let day = days_from_civil(2026, 3, 8); + let utc_midnight = day * 86_400_000; + let hour = 3_600_000; + let offset = |ms| { + if ms < utc_midnight + 7 * hour { + -300 + } else { + -240 + } + }; + let db = DatabaseSpec { + columns: ["start", "end"] + .map(|id| DatabaseColumnSpec { + id: id.into(), + name: id.into(), + column_type: "date".into(), + data: json!({}), + }) + .into(), + views: vec![DatabaseViewSpec { + id: "calendar".into(), + name: "Calendar".into(), + mode: "calendar".into(), + raw: json!({"date": {"startColumnId": "start", "endColumnId": "end"}}), + }], + ..Default::default() + }; + let mut page = PageDocSession::new("calendar", 7).unwrap(); + page.add_block("db", BlockSpec::Database(db), None, None, 1) + .unwrap(); + let read_db = |page: &PageDocSession| { + let snapshot = page.read_page_snapshot().unwrap(); + let BlockContent::Database(data) = &snapshot.block("db").unwrap().content else { + panic!("expected calendar database") + }; + data.clone() + }; + // UTC minutes after midnight on March 7 and March 8; New York skips 02:00 on March 8. + for (row, start_min, duration_ms, moved_min) in [ + ("01:30–03:00", 390, 5_400_000, 390), + ("02:30–03:30", 450, 3_600_000, 450), + ("01:30–03:30", 390, 7_200_000, 390), + ] { + let start = utc_midnight - 86_400_000 + start_min * 60_000; + let end = start + duration_ms; + let moved = utc_midnight + moved_min * 60_000; + page.add_database_row_with_cells( + "db", + row, + row, + vec![ + ("start".into(), DatabaseCellSpec::Integer(start)), + ("end".into(), DatabaseCellSpec::Integer(end)), + ], + 2, + ) + .unwrap(); + let read_times = |page: &PageDocSession| { + let data = read_db(page); + ["start", "end"].map(|id| data.cells[&(row.into(), id.into())].as_i64().unwrap()) + }; + let mut preview = event(start, end); + assert_eq!( + super::preview_event_range(&mut preview, day, None, &offset), + day..=day + ); + let preview_times = [preview.start_at_ms, preview.end_at_ms.unwrap()]; + assert_eq!(preview_times, [moved, moved + duration_ms], "{row}"); + let data = read_db(&page); + assert!( + reschedule_calendar_row_to_day( + &mut page, + "db", + &data.views[0], + &data, + row, + day, + &offset, + 1_000, + ) + .unwrap() + ); + let mut reopened = PageDocSession::new("calendar", 8).unwrap(); + reopened + .apply_remote_update_v1(&page.encode_update_v1().unwrap()) + .unwrap(); + assert_eq!(read_times(&reopened), preview_times, "{row}"); + assert!(page.undo().unwrap().is_some()); + assert_eq!(read_times(&page), [start, end], "{row}"); + } + } + + #[test] + fn timed_events_keep_each_wall_time_across_spring_forward() { + let day = 20_730_i64; + let day_ms = 86_400_000; + for before in [600, 630] { + let after = 660; + let transition = day * day_ms + (120 - i64::from(before)) * 60_000; + let offset = |ms| if ms < transition { before } else { after }; + let wall_start = (day - 1) * day_ms + 9 * 3_600_000 + 12_345; + let wall_end = wall_start + 5_400_000; + let slide = |wall| wall + day_ms - i64::from(after) * 60_000; + assert_eq!( + super::move_event_times( + wall_start - i64::from(before) * 60_000, + wall_end - i64::from(before) * 60_000, + day, + &offset, + ), + (slide(wall_start), slide(wall_end)) + ); + } + } + #[test] fn local_wall_time_resolves_new_york_dst_gap_forward_and_overlap_to_first_occurrence() { // America/New_York 2026: EDT (-240) from 2026-03-08T07:00Z until 2026-11-01T06:00Z. diff --git a/blocksuite/crates/editor/src/database/column_ops.rs b/blocksuite/crates/editor/src/database/column_ops.rs index 7080e34076..6ddc245aea 100644 --- a/blocksuite/crates/editor/src/database/column_ops.rs +++ b/blocksuite/crates/editor/src/database/column_ops.rs @@ -318,7 +318,7 @@ pub(super) fn render_column_menu_at( viewport: FlowRect, prims: &mut Vec, hits: &mut Vec, -) -> (FlowRect, Option) { +) -> (FlowRect, Option<(FlowRect, usize)>) { let col = ctx.data.columns.iter().find(|c| c.id == menu.column_id); let current_type = col.map_or("rich-text", |c| c.column_type.as_str()); let (is_title, rows) = column_menu_rows(ctx, menu); @@ -485,7 +485,7 @@ pub(super) fn render_column_menu_at( .min((viewport.bottom() - 8.0 - sub_h).max(viewport.y + 8.0)) .max(viewport.y + 8.0); let sub_rect = FlowRect::new(sub_x, sub_y, sub_w, sub_h); - submenu_rect = Some(sub_rect); + submenu_rect = Some((sub_rect, hits.len())); prims.push(DatabasePrim::Quad { rect: sub_rect, fill: Some(ctx.palette.panel), diff --git a/blocksuite/crates/editor/src/database/cursor.rs b/blocksuite/crates/editor/src/database/cursor.rs index 5f45e7ccce..d145ca2584 100644 --- a/blocksuite/crates/editor/src/database/cursor.rs +++ b/blocksuite/crates/editor/src/database/cursor.rs @@ -74,6 +74,11 @@ pub fn database_authoring_hit_cursor( | DatabaseAuthoringHitKind::OpenRowPeek { .. } | DatabaseAuthoringHitKind::SwitchView { .. } => CursorStyle::PointingHand, DatabaseAuthoringHitKind::AddColumn + | DatabaseAuthoringHitKind::CreateProperty { .. } + | DatabaseAuthoringHitKind::ToolbarProperties + | DatabaseAuthoringHitKind::SetColumnHidden { .. } + | DatabaseAuthoringHitKind::ReorderProperty { .. } + | DatabaseAuthoringHitKind::CreateView { .. } | DatabaseAuthoringHitKind::AddView | DatabaseAuthoringHitKind::OpenColumnMenu { .. } | DatabaseAuthoringHitKind::OpenRowMenu { .. } @@ -91,6 +96,8 @@ pub fn database_authoring_hit_cursor( | DatabaseAuthoringHitKind::ColumnMenuDelete { .. } | DatabaseAuthoringHitKind::SelectToggleOption { .. } | DatabaseAuthoringHitKind::SelectCreateOption { .. } + | DatabaseAuthoringHitKind::SelectOptionMenu { .. } + | DatabaseAuthoringHitKind::SelectSaveOption { .. } | DatabaseAuthoringHitKind::SelectDeleteOption { .. } | DatabaseAuthoringHitKind::ToolbarToggleFilter | DatabaseAuthoringHitKind::ToolbarToggleSort @@ -108,7 +115,7 @@ pub fn database_authoring_hit_cursor( | DatabaseAuthoringHitKind::KanbanAddRowAtStart { .. } | DatabaseAuthoringHitKind::KanbanLaneMenu { .. } | DatabaseAuthoringHitKind::KanbanLaneMenuAddCard { .. } - | DatabaseAuthoringHitKind::KanbanLaneMenuDeleteGroup { .. } + | DatabaseAuthoringHitKind::KanbanLaneCards { .. } | DatabaseAuthoringHitKind::CalendarAddRowOnDay { .. } => { if readonly { CursorStyle::Arrow diff --git a/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs b/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs index 2a336f4d92..3e706db28d 100644 --- a/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs +++ b/blocksuite/crates/editor/src/database/filter_sort_bar/mod.rs @@ -12,7 +12,7 @@ use crate::{ }; use super::{ - InlineAxis, + COLUMN_TYPES, InlineAxis, authoring::{ActiveToolbarPanel, DatabaseAuthoringHit, DatabaseAuthoringHitKind}, cell_editor::parse_date_input_ms, format_database_date, @@ -391,14 +391,10 @@ pub(super) fn measure_toolbar_panel_size( let rows_h = existing.len().min(5) as f32 * 24.0; (310.0, 96.0 + extra_chips_h + rows_h) } - ActiveToolbarPanel::Sort => { - let count = ctx.data.columns.len().min(8); - (228.0, 34.0 + count as f32 * 26.0 + 10.0) - } - ActiveToolbarPanel::GroupBy => { - let count = ctx.data.columns.len().min(8); - (228.0, 34.0 + (count + 1) as f32 * 26.0 + 10.0) - } + _ => ( + 248.0, + (36.0 + 28.0 * panel_row_count(ctx.data.columns.len(), panel) as f32).min(360.0), + ), } } @@ -414,12 +410,8 @@ pub(super) fn render_toolbar_panel_at( ) -> Option { match panel { ActiveToolbarPanel::Filter => render_filter_panel_at(ctx, view, panel_rect, prims, hits), - ActiveToolbarPanel::Sort => { - panels::render_sort_panel_at(ctx, view, panel_rect, prims, hits); - None - } - ActiveToolbarPanel::GroupBy => { - panels::render_group_by_panel_at(ctx, view, panel_rect, prims, hits); + _ => { + panels::render_column_list(ctx, view, panel, panel_rect, prims, hits); None } } @@ -710,3 +702,12 @@ fn render_filter_panel_at( input_rect_out } + +pub fn panel_row_count(cols: usize, panel: ActiveToolbarPanel) -> usize { + match panel { + ActiveToolbarPanel::NewView => 3, + ActiveToolbarPanel::NewProperty => COLUMN_TYPES.len() - 1, + ActiveToolbarPanel::GroupBy => cols + 1, + _ => cols, + } +} diff --git a/blocksuite/crates/editor/src/database/filter_sort_bar/panels.rs b/blocksuite/crates/editor/src/database/filter_sort_bar/panels.rs index 134d125569..324e968923 100644 --- a/blocksuite/crates/editor/src/database/filter_sort_bar/panels.rs +++ b/blocksuite/crates/editor/src/database/filter_sort_bar/panels.rs @@ -8,8 +8,8 @@ use crate::{ }; use super::{ - ActiveToolbarPanel, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePrim, DbRenderCtx, - parse_sort_rules, + ActiveToolbarPanel, COLUMN_TYPES, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePrim, + DbRenderCtx, parse_sort_rules, }; pub(super) fn column_name_for<'a>(view_cols: &'a [DatabaseColumn], col_id: &'a str) -> &'a str { @@ -68,191 +68,206 @@ pub(super) fn toolbar_buttons<'a>( view.group_by.is_some(), DatabaseAuthoringHitKind::ToolbarToggleGroupBy, )); + out.push(( + ActiveToolbarPanel::Properties, + "Properties".into(), + false, + DatabaseAuthoringHitKind::ToolbarProperties, + )); out } -pub(super) fn render_sort_panel_at( +pub(super) fn render_column_list( ctx: &DbRenderCtx<'_>, view: &DatabaseView, - panel_rect: FlowRect, + panel: ActiveToolbarPanel, + rect: FlowRect, prims: &mut Vec, hits: &mut Vec, ) { - let sort_rules = parse_sort_rules(view.sort.as_ref()); + use DatabaseAuthoringHitKind as Hit; prims.push(DatabasePrim::Quad { - rect: panel_rect, - fill: Some(ctx.palette.background), + rect, + fill: Some(ctx.palette.panel), border: Some(ctx.palette.border), radius: 8.0, dashed: false, }); - let mut py = panel_rect.y + 8.0; + let title = match panel { + ActiveToolbarPanel::Properties => "Properties", + ActiveToolbarPanel::NewView => "New view", + ActiveToolbarPanel::NewProperty => "Add property", + ActiveToolbarPanel::GroupBy => "Group by", + _ => "Sort by column", + }; + let style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 500.0, + ctx.palette.text_primary, + ); prims.push(ctx.single_line_clipped( - "Sort by column", - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - 600.0, - ctx.palette.text_secondary, - ), - panel_rect.x + 10.0, - py, - panel_rect.w - 20.0, - 18.0, + title, + style.clone(), + rect.x + 12.0, + rect.y + 4.0, + rect.w - 24.0, + 24.0, InlineAlign::Left, )); - py += 22.0; - - for col in ctx.data.columns.iter().take(8) { - let active = sort_rules.iter().find(|r| r.column_id == col.id); - let row_rect = FlowRect::new(panel_rect.x + 6.0, py, panel_rect.w - 12.0, 24.0); - if active.is_some() { - prims.push(DatabasePrim::Quad { - rect: row_rect, - fill: Some(ctx.palette.brand.opacity(0.1)), - border: None, - radius: 4.0, - dashed: false, - }); + let top = rect.y + 30.0; + let count = super::panel_row_count(ctx.data.columns.len(), panel); + let max_scroll = (count as f32 * 28.0 - (rect.h - 36.0)).max(0.0); + let scroll = ctx + .ui_state + .authoring + .toolbar_scroll_y + .clamp(0.0, max_scroll); + let mut button = |index: usize, x: f32, width: f32, label: &str, kind: Hit| { + let y = top + index as f32 * 28.0 - scroll; + let y1 = y.max(top); + let y2 = (y + 28.0).min(rect.bottom() - 6.0); + if y2 <= y1 { + return; } - let suffix = match active { - Some(r) if r.desc => " ↓", - Some(_) => " ↑", - None => "", - }; - prims.push(ctx.single_line_clipped( - &format!("{}{suffix}", col.name), - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - if active.is_some() { 600.0 } else { 400.0 }, - if active.is_some() { - ctx.palette.brand - } else { - ctx.palette.text_primary - }, - ), - row_rect.x + 8.0, - row_rect.y, - row_rect.w - 16.0, - row_rect.h, - InlineAlign::Left, - )); + let visible = FlowRect::new(x, y1, width, y2 - y1); + let (_, layout) = ctx.truncate_text(label, style.clone(), (width - 8.0).max(1.0), 28.0); + prims.push(DatabasePrim::Text { + x: x + 4.0, + y, + layout, + clip: Some(visible), + }); hits.push(DatabaseAuthoringHit { - rect: row_rect, - kind: DatabaseAuthoringHitKind::ToolbarAddOrFlipSort { - column_id: col.id.clone(), - }, + rect: visible, + kind, scrolls_x: false, }); - py += 26.0; - } -} - -pub(super) fn render_group_by_panel_at( - ctx: &DbRenderCtx<'_>, - view: &DatabaseView, - panel_rect: FlowRect, - prims: &mut Vec, - hits: &mut Vec, -) { - let cur_gb = view.group_by.as_ref().map(|g| g.column_id.as_str()); - prims.push(DatabasePrim::Quad { - rect: panel_rect, - fill: Some(ctx.palette.background), - border: Some(ctx.palette.border), - radius: 8.0, - dashed: false, - }); - let mut py = panel_rect.y + 8.0; - prims.push(ctx.single_line_clipped( - "Group by", - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - 600.0, - ctx.palette.text_secondary, - ), - panel_rect.x + 10.0, - py, - panel_rect.w - 20.0, - 18.0, - InlineAlign::Left, - )); - py += 22.0; - - let none_rect = FlowRect::new(panel_rect.x + 6.0, py, panel_rect.w - 12.0, 24.0); - if cur_gb.is_none() { - prims.push(DatabasePrim::Quad { - rect: none_rect, - fill: Some(ctx.palette.brand.opacity(0.1)), - border: None, - radius: 4.0, - dashed: false, - }); - } - prims.push(ctx.single_line_clipped( - "None", - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - if cur_gb.is_none() { 600.0 } else { 400.0 }, - if cur_gb.is_none() { - ctx.palette.brand - } else { - ctx.palette.text_primary - }, - ), - none_rect.x + 8.0, - none_rect.y, - none_rect.w - 16.0, - none_rect.h, - InlineAlign::Left, - )); - hits.push(DatabaseAuthoringHit { - rect: none_rect, - kind: DatabaseAuthoringHitKind::ToolbarSetGroupBy { column_id: None }, - scrolls_x: false, - }); - py += 26.0; - - for col in ctx.data.columns.iter().take(8) { - let active = cur_gb == Some(col.id.as_str()); - let row_rect = FlowRect::new(panel_rect.x + 6.0, py, panel_rect.w - 12.0, 24.0); - if active { - prims.push(DatabasePrim::Quad { - rect: row_rect, - fill: Some(ctx.palette.brand.opacity(0.1)), - border: None, - radius: 4.0, - dashed: false, - }); - } - prims.push(ctx.single_line_clipped( - &col.name, - InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px, - if active { 600.0 } else { 400.0 }, - if active { - ctx.palette.brand - } else { - ctx.palette.text_primary + }; + let x = rect.x + 8.0; + let w = rect.w - 16.0; + if panel == ActiveToolbarPanel::NewProperty { + for (i, (id, label)) in COLUMN_TYPES + .iter() + .filter(|(id, _)| *id != "title") + .enumerate() + { + button( + i, + x, + w, + label, + Hit::CreateProperty { + column_type: (*id).into(), }, - ), - row_rect.x + 8.0, - row_rect.y, - row_rect.w - 16.0, - row_rect.h, - InlineAlign::Left, - )); - hits.push(DatabaseAuthoringHit { - rect: row_rect, - kind: DatabaseAuthoringHitKind::ToolbarSetGroupBy { - column_id: Some(col.id.clone()), - }, - scrolls_x: false, + ); + } + return; + } + if panel == ActiveToolbarPanel::NewView { + for (i, (label, mode)) in [ + ("Table", DatabaseViewMode::Table), + ("Kanban", DatabaseViewMode::Kanban), + ("Calendar", DatabaseViewMode::Calendar), + ] + .into_iter() + .enumerate() + { + button(i, x, w, label, Hit::CreateView { mode }); + } + return; + } + let mut columns: Vec<_> = ctx.data.columns.iter().collect(); + if panel == ActiveToolbarPanel::Properties { + columns.sort_by_key(|c| { + view.columns + .iter() + .position(|vc| vc.id == c.id) + .unwrap_or(usize::MAX) }); - py += 26.0; + } + let sort = parse_sort_rules(view.sort.as_ref()); + let group = view.group_by.as_ref().map(|g| &g.column_id); + if panel == ActiveToolbarPanel::GroupBy { + button( + 0, + x, + w, + if group.is_none() { "✓ None" } else { "None" }, + Hit::ToolbarSetGroupBy { column_id: None }, + ); + } + for (i, col) in columns.iter().enumerate() { + let id = &col.id; + match panel { + ActiveToolbarPanel::Properties => { + let hidden = view + .columns + .iter() + .any(|c| c.id == *id && c.hide == Some(true)); + let label = format!("{} {}", if hidden { "□" } else { "☑" }, col.name); + button( + i, + x, + w - 56.0, + &label, + Hit::SetColumnHidden { + column_id: id.clone(), + hidden: !hidden, + }, + ); + if i > 0 { + button( + i, + x + w - 56.0, + 28.0, + "↑", + Hit::ReorderProperty { + column_id: id.clone(), + to_index: i - 1, + }, + ); + } + if i + 1 < columns.len() { + button( + i, + x + w - 28.0, + 28.0, + "↓", + Hit::ReorderProperty { + column_id: id.clone(), + to_index: i + 1, + }, + ); + } + } + ActiveToolbarPanel::GroupBy => { + let label = format!("{}{}", if group == Some(id) { "✓ " } else { "" }, col.name); + button( + i + 1, + x, + w, + &label, + Hit::ToolbarSetGroupBy { + column_id: Some(id.clone()), + }, + ); + } + _ => { + let suffix = sort + .iter() + .find(|r| r.column_id == *id) + .map_or("", |r| if r.desc { " ↓" } else { " ↑" }); + button( + i, + x, + w, + &format!("{}{suffix}", col.name), + Hit::ToolbarAddOrFlipSort { + column_id: id.clone(), + }, + ); + } + } } } diff --git a/blocksuite/crates/editor/src/database/mod.rs b/blocksuite/crates/editor/src/database/mod.rs index 5b038fd620..67bbae3d24 100644 --- a/blocksuite/crates/editor/src/database/mod.rs +++ b/blocksuite/crates/editor/src/database/mod.rs @@ -4,6 +4,7 @@ mod authoring; mod authoring_dispatch; +mod authoring_id; mod calendar; mod calendar_edit; mod cell_editor; @@ -23,6 +24,7 @@ mod render_types; mod row_ops; mod select_popover; mod sort_key; +mod view_tabs; use std::collections::{BTreeSet, HashMap}; @@ -57,8 +59,8 @@ pub use cursor::{database_authoring_hit_cursor, database_hit_cursor}; pub use filter_sort_bar::{ FilterRuleItem, SortRuleItem, append_filter_rule_json, build_group_by_for_column, default_operator_for_column_type, filter_op_label, filter_op_takes_no_arg, - normalize_operator_for_column_type, operators_for_column_type, parse_sort_rules, - remove_filter_condition_json, remove_sort_rule_json, rule_to_condition_json, + normalize_operator_for_column_type, operators_for_column_type, panel_row_count, + parse_sort_rules, remove_filter_condition_json, remove_sort_rule_json, rule_to_condition_json, toggle_sort_rule_dir_json, upsert_sort_rule_json, }; pub use format::{ @@ -67,7 +69,7 @@ pub use format::{ resolve_rich_text_plain, resolve_rich_text_query, resolve_tag_accent, resolve_tag_color, }; pub use group::{DatabaseGroupBucket, group_database_rows_with_titles}; -pub use popover_overlay::{DatabasePopoverOverlay, layout_database_popover_overlay}; +pub use popover_overlay::{DatabasePopoverOverlay, PopoverTarget, layout_database_popover_overlay}; 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; @@ -713,3 +715,11 @@ mod tests { } } } + +pub(crate) fn frozen_table_area( + scroll_area: crate::block_flow::FlowRect, +) -> Option { + let width = scroll_area.x - 8.0; + (width > 0.0) + .then(|| crate::block_flow::FlowRect::new(8.0, scroll_area.y, width, scroll_area.h)) +} diff --git a/blocksuite/crates/editor/src/database/popover_overlay.rs b/blocksuite/crates/editor/src/database/popover_overlay.rs index 95de3afc55..3ac7bc54fd 100644 --- a/blocksuite/crates/editor/src/database/popover_overlay.rs +++ b/blocksuite/crates/editor/src/database/popover_overlay.rs @@ -17,8 +17,9 @@ use super::{ DatabaseUiState, authoring::{DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePopoverAnchor}, column_ops, eval_database_filter_with_titles, filter_sort_bar, - render::{DatabasePrim, DbRenderCtx, tab_label_for}, + render::{DatabasePrim, DbRenderCtx}, select_popover, sort_database_rows_with_titles, + view_tabs::tab_label_for, }; /// Screen-space geometry, paint primitives, and hit targets for an active database popover. @@ -28,6 +29,7 @@ pub struct DatabasePopoverOverlay { pub bounds: FlowRect, /// Optional floating submenu bounds in screen space (e.g. column type submenu). pub submenu_bounds: Option, + submenu_hit_start: usize, /// Paint primitives in screen space (absolute window coordinates). pub prims: Vec, /// Interactive hit targets in screen space. @@ -37,7 +39,34 @@ pub struct DatabasePopoverOverlay { pub text_input_rect: Option, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PopoverTarget { + Item(usize), + Input, + Background, +} + impl DatabasePopoverOverlay { + /// Pick only within the topmost panel under the pointer, including its padding. + pub fn target_at(&self, x: f32, y: f32) -> Option { + let submenu = self.submenu_bounds.is_some_and(|rect| rect.contains(x, y)); + if !submenu && !self.bounds.contains(x, y) { + return None; + } + let range = if submenu { + self.submenu_hit_start..self.hits.len() + } else { + 0..self.submenu_hit_start + }; + if let Some(index) = range.rev().find(|&i| self.hits[i].rect.contains(x, y)) { + return Some(PopoverTarget::Item(index)); + } + if !submenu && self.text_input_rect.is_some_and(|rect| rect.contains(x, y)) { + return Some(PopoverTarget::Input); + } + Some(PopoverTarget::Background) + } + /// Whether `(x, y)` in screen coordinates falls inside this popover or its open submenu. pub fn contains(&self, x: f32, y: f32) -> bool { self.bounds.contains(x, y) || self.submenu_bounds.is_some_and(|r| r.contains(x, y)) @@ -182,7 +211,7 @@ pub fn layout_database_popover_overlay( super::row_ops::render_row_menu_at(&ctx, menu, placed.rect, &mut prims, &mut hits); (placed.rect, None, None) } else if !mobile_readonly && let Some(menu) = &auth.lane_menu { - let size = super::row_ops::measure_lane_menu_size(&ctx, menu); + let size = super::row_ops::measure_lane_menu_size(menu); let placed = place_popover( anchor_screen, size, @@ -260,7 +289,8 @@ pub fn layout_database_popover_overlay( Some(DatabasePopoverOverlay { bounds, - submenu_bounds, + submenu_bounds: submenu_bounds.map(|(rect, _)| rect), + submenu_hit_start: submenu_bounds.map_or(hits.len(), |(_, start)| start), prims, hits, text_input_rect, diff --git a/blocksuite/crates/editor/src/database/render.rs b/blocksuite/crates/editor/src/database/render.rs index ac771c3008..443254d5df 100644 --- a/blocksuite/crates/editor/src/database/render.rs +++ b/blocksuite/crates/editor/src/database/render.rs @@ -14,6 +14,7 @@ use crate::{ pub(super) use super::render_types::DbRenderCtx; pub use super::render_types::{DatabaseLayoutOutput, DatabasePrim}; +use super::view_tabs::{partition_desktop_view_tabs, tab_label_for}; use super::{ DatabaseHitKind, DatabaseHitTarget, DatabasePopoverAnchor, DatabaseUiState, InlineAxis, MOBILE_DATABASE_READONLY_NOTICE, filter_and_sort_view_rows, filter_sort_bar, render_calendar, @@ -558,6 +559,7 @@ pub fn layout_database_block( // 5. Render active view content starting at `y`. let content_top = y; + let mut frozen = 0.0; let ( content_h, content_max_x, @@ -567,7 +569,7 @@ pub fn layout_database_block( view_popover_anchor, active_cell, ) = match active_view.mode { - DatabaseViewMode::Table => render_table::render_table_view(&ctx, content_top), + DatabaseViewMode::Table => render_table::render_table_view(&ctx, content_top, &mut frozen), DatabaseViewMode::Kanban => render_kanban::render_kanban_view(&ctx, content_top), DatabaseViewMode::Calendar => { let (h, mx, vp, vh, vah, pa) = render_calendar::render_calendar_view(&ctx, content_top); @@ -606,7 +608,9 @@ pub fn layout_database_block( cal_active, ) } - DatabaseViewMode::Unknown(_) => render_table::render_table_view(&ctx, content_top), + DatabaseViewMode::Unknown(_) => { + render_table::render_table_view(&ctx, content_top, &mut frozen) + } }; prims.extend(view_prims); @@ -623,6 +627,14 @@ pub fn layout_database_block( .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) { view_popover_anchor + } else if ui_state.authoring.toolbar_panel == Some(super::ActiveToolbarPanel::NewView) { + authoring_hits + .iter() + .find(|h| matches!(h.kind, super::DatabaseAuthoringHitKind::AddView)) + .map(|h| DatabasePopoverAnchor { + rect: h.rect, + scrolls_x: false, + }) } else if ui_state.authoring.toolbar_panel.is_some() { toolbar_anchor.map(|rect| DatabasePopoverAnchor { rect, @@ -655,8 +667,57 @@ pub fn layout_database_block( } else { 0.0 }; + let right = 8.0 + frozen; + let pinned = + |r: FlowRect| frozen > 0.0 && r.x >= 4.0 && r.x < right && r.right() <= right + 4.0; + if frozen > 0.0 { + for hit in &mut authoring_hits { + if hit.scrolls_x && pinned(hit.rect) { + hit.scrolls_x = false; + } + } + let mut fixed_controls = Vec::new(); + for hit in &mut hits { + if hit.scrolls_x + && hit.rect.x < right + && hit.rect.right() > right + && matches!( + hit.kind, + DatabaseHitKind::AddRow + | DatabaseHitKind::ToggleGroup { .. } + | DatabaseHitKind::OpenRecord { .. } + ) + { + let mut fixed = hit.clone(); + fixed.rect.w = right - fixed.rect.x; + fixed.scrolls_x = false; + fixed_controls.push(fixed); + } + if hit.scrolls_x && pinned(hit.rect) { + hit.scrolls_x = false; + } + } + hits.extend(fixed_controls); + } + let popover_anchor = popover_anchor.map(|mut a| { + if pinned(a.rect) { + a.scrolls_x = false; + } + a + }); + let active_cell = active_cell.map(|mut a| { + if pinned(a.rect) { + a.scrolls_x = false; + } + a + }); let code_scroll = (content_max_x > 0.0).then(|| CodeScroll { - area: FlowRect::new(8.0, content_top, (width - 16.0).max(1.0), content_h), + area: FlowRect::new( + 8.0 + frozen, + content_top, + (width - 16.0 - frozen).max(1.0), + content_h, + ), max_x: content_max_x, initial_x, }); @@ -702,55 +763,3 @@ pub fn layout_database_block( 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 c88967418c..fa61dd712c 100644 --- a/blocksuite/crates/editor/src/database/render_calendar.rs +++ b/blocksuite/crates/editor/src/database/render_calendar.rs @@ -72,7 +72,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 = super::calendar_edit::collect_calendar_entries(ctx, start_col_id, end_col_id); + let mut 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( @@ -85,6 +85,22 @@ pub(super) fn render_calendar_view( ctx.offset_at_ms, ); + let preview_range = ctx + .ui_state + .authoring + .calendar_drag + .as_ref() + .and_then(|drag| { + let entry = entries + .iter_mut() + .find(|entry| entry.row_id == drag.row_id)?; + Some(super::calendar_edit::preview_event_range( + entry, + drag.target_day, + ctx.ui_state.authoring.calendar_resize_end, + ctx.offset_at_ms, + )) + }); let layout = create_calendar_month_layout(year, month, &entries, 0, ctx.offset_at_ms); let grid_w = (ctx.width - 2.0 * PAD_X).max(280.0); let col_w = (grid_w / 7.0).floor(); @@ -519,14 +535,11 @@ pub(super) fn render_calendar_view( let visual_col = axis.map_col_span(7, col_idx, 1); let cell_rect = FlowRect::new(PAD_X + visual_col as f32 * col_w, y, col_w, week_h); let is_today = day.day_index == today_day; - let is_drag_target = ctx - .ui_state - .authoring - .calendar_drag + let is_drag_target = preview_range .as_ref() - .is_some_and(|d| d.target_day == day.day_index); + .is_some_and(|range| range.contains(&day.day_index)); let cell_fill = if is_drag_target { - Some(ctx.palette.brand.opacity(0.10)) + Some(ctx.palette.brand.opacity(0.04)) } else if is_today { Some(ctx.palette.brand.opacity(0.06)) } else if !day.in_month { @@ -534,11 +547,11 @@ pub(super) fn render_calendar_view( } else { None }; - if cell_fill.is_some() || is_drag_target { + if cell_fill.is_some() { prims.push(DatabasePrim::Quad { rect: cell_rect, fill: cell_fill, - border: is_drag_target.then_some(ctx.palette.brand), + border: None, radius: 0.0, dashed: false, }); @@ -551,7 +564,8 @@ pub(super) fn render_calendar_view( FlowRect::new(cell_rect.x, cell_rect.bottom() - 1.0, cell_rect.w, 1.0), grid_border, )); - let show_plus = day_plus_allowed + let show_plus = day.in_month + && day_plus_allowed && ctx.form_factor.is_touch_form_factor() && ctx.ui_state.calendar_selected_day == Some(day.day_index); super::calendar_edit::render_calendar_day_controls( @@ -578,9 +592,9 @@ pub(super) fn render_calendar_view( ctx.palette.text_secondary.opacity(0.6) }; let day_align = if ctx.direction.is_rtl() { - InlineAlign::Left - } else { InlineAlign::Right + } else { + InlineAlign::Left }; prims.push(ctx.single_line_clipped( &day_label, @@ -679,6 +693,42 @@ pub(super) fn render_calendar_view( grid_border, )); + if layout.segments.is_empty() + && layout + .weeks + .iter() + .flatten() + .all(|day| day.entries.is_empty()) + { + prims.push(ctx.single_line_clipped( + "Nothing here yet", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_sm_px, + 500.0, + ctx.palette.text_secondary, + ), + PAD_X, + grid_top_y + (y - grid_top_y) * 0.5 - 14.0, + actual_grid_w, + 24.0, + InlineAlign::Center, + )); + prims.push(ctx.single_line_clipped( + "Add a row to any date, it'll appear here on the calendar.", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 400.0, + ctx.palette.text_secondary, + ), + PAD_X, + grid_top_y + (y - grid_top_y) * 0.5 + 10.0, + actual_grid_w, + 20.0, + InlineAlign::Center, + )); + } let max_scroll_x = (actual_grid_w + 2.0 * PAD_X - ctx.width).max(0.0).ceil(); (y - top_y, max_scroll_x, prims, hits, authoring_hits, None) } diff --git a/blocksuite/crates/editor/src/database/render_table.rs b/blocksuite/crates/editor/src/database/render_table.rs index 65eb40fc3f..fe01d5fdb8 100644 --- a/blocksuite/crates/editor/src/database/render_table.rs +++ b/blocksuite/crates/editor/src/database/render_table.rs @@ -33,6 +33,7 @@ const PAD_X: f32 = 8.0; pub(super) fn render_table_view( ctx: &DbRenderCtx<'_>, top_y: f32, + frozen_width: &mut f32, ) -> ( f32, f32, @@ -352,6 +353,21 @@ pub(super) fn render_table_view( } let max_scroll_x = (total_table_w + 2.0 * PAD_X - ctx.width).max(0.0).ceil(); + if max_scroll_x > 0.0 + && !ctx.direction.is_rtl() + && !ctx.form_factor.is_touch_form_factor() + && let Some(first) = cols.first() + && (first.col_type == "title" + || ctx + .view + .header + .as_ref() + .and_then(|h| h.title_column.as_deref()) + == Some(&first.id)) + && ctx.width - first.width > 100.0 + { + *frozen_width = first.width; + } ( y - top_y, max_scroll_x, diff --git a/blocksuite/crates/editor/src/database/row_ops.rs b/blocksuite/crates/editor/src/database/row_ops.rs index 7e495d38b8..ff7457691d 100644 --- a/blocksuite/crates/editor/src/database/row_ops.rs +++ b/blocksuite/crates/editor/src/database/row_ops.rs @@ -17,8 +17,8 @@ use super::{ AuthoringActionResult, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseFlowState, DatabasePrim, authoring::resolve_active_view, - authoring_dispatch::fresh_database_id, - calendar_edit::{local_wall_ms_to_utc_ms, resolve_calendar_date_columns}, + authoring_id::fresh_database_id, + calendar_edit::{resolve_calendar_date_columns, timestamp_on_day}, group::UNGROUPS_KEY, render::DbRenderCtx, resolve_effective_group_by, @@ -185,24 +185,6 @@ pub(super) fn render_row_menu_at( } } -fn resolve_lane_delete_option( - data: &DatabaseData, - column_id: &str, - bucket_key: &str, -) -> Option { - if bucket_key == UNGROUPS_KEY { - return None; - } - let col = data.columns.iter().find(|c| c.id == column_id)?; - if !matches!(col.column_type.as_str(), "select" | "multi-select") { - return None; - } - col.select_options() - .into_iter() - .find(|opt| opt.id == bucket_key) - .map(|opt| opt.id) -} - fn resolve_lane_seed_value( data: &DatabaseData, column_id: &str, @@ -220,15 +202,13 @@ fn resolve_lane_seed_value( } } -pub(super) fn measure_lane_menu_size(ctx: &DbRenderCtx<'_>, menu: &LaneMenuState) -> (f32, f32) { - let has_delete = - resolve_lane_delete_option(ctx.data, &menu.column_id, &menu.bucket_key).is_some(); - let h = if has_delete { - ROW_MENU_PAD * 2.0 + 2.0 * ROW_MENU_ITEM_H + 5.0 +pub(super) fn measure_lane_menu_size(menu: &LaneMenuState) -> (f32, f32) { + let rows = if menu.bucket_key == UNGROUPS_KEY { + 2.0 } else { - ROW_MENU_PAD * 2.0 + ROW_MENU_ITEM_H + 3.0 }; - (ROW_MENU_W, h) + (ROW_MENU_W, ROW_MENU_PAD * 2.0 + rows * ROW_MENU_ITEM_H) } pub(super) fn render_lane_menu_at( @@ -261,32 +241,45 @@ pub(super) fn render_lane_menu_at( hits, ); y += ROW_MENU_ITEM_H; - if let Some(option_id) = resolve_lane_delete_option(ctx.data, &menu.column_id, &menu.bucket_key) - { - prims.push(DbRenderCtx::hairline( - FlowRect::new( - menu_rect.x + 6.0, - y + 2.0, - (menu_rect.w - 12.0).max(1.0), - 1.0, - ), - ctx.palette.border, - )); - y += 5.0; + let Some(group) = resolve_effective_group_by(ctx.view, ctx.data) else { + return; + }; + let buckets = super::group_view_rows_with_titles( + ctx.rows, + ctx.view, + &group, + ctx.data, + ctx.now_ms, + ctx.offset_at_ms, + ctx.page_titles, + ); + let rows: Vec = buckets + .into_iter() + .find(|b| b.key == menu.bucket_key) + .into_iter() + .flat_map(|b| b.rows) + .map(|r| r.row_id) + .collect(); + for (label, delete) in [("Ungroup", false), ("Delete Cards", true)] { + if !delete && menu.bucket_key == UNGROUPS_KEY { + continue; + } push_menu_item( ctx, menu_rect, y, - "Delete Group", - IconPaint::from_def(&ui_tokens::icons::DELETE), - DatabaseAuthoringHitKind::KanbanLaneMenuDeleteGroup { + label, + IconPaint::named(if delete { "DeleteIcon" } else { "GroupByIcon" }), + DatabaseAuthoringHitKind::KanbanLaneCards { column_id: menu.column_id.clone(), - option_id, + rows: rows.clone(), + delete, }, - true, + delete, prims, hits, ); + y += ROW_MENU_ITEM_H; } } @@ -428,7 +421,7 @@ pub(super) fn handle_row_menu_action( } } -/// Handle Kanban lane header `…` menu open and actions (`Insert Card`, `Delete Group`). +/// Handle Kanban lane header `…` menu open and actions. pub(super) fn handle_lane_menu_action( page: &mut PageDocSession, flow_state: &mut DatabaseFlowState, @@ -474,12 +467,27 @@ pub(super) fn handle_lane_menu_action( now_ms, ) } - DatabaseAuthoringHitKind::KanbanLaneMenuDeleteGroup { + DatabaseAuthoringHitKind::KanbanLaneCards { column_id, - option_id, + rows, + delete, } => { - let commit = - page.delete_database_select_option(block_id, column_id, option_id, now_ms)?; + let commit = page.structural_edit(now_ms, |page| { + for row in rows { + if *delete { + page.delete_database_row(block_id, row, now_ms)?; + } else { + page.set_database_cell_value( + block_id, + row, + column_id, + DatabaseCellSpec::Null, + now_ms, + )?; + } + } + Ok(()) + })?; flow_state.authoring_mut(block_id).dismiss_popovers(); Ok(AuthoringActionResult { handled: true, @@ -530,17 +538,10 @@ pub fn resize_calendar_event_day( } else { (cur_start_ms, cur_end_ms) }; - let moved_local_ms = - moved_ms.saturating_add(i64::from(offset_at_ms(moved_ms)).saturating_mul(60_000)); - if moved_local_ms.div_euclid(86_400_000) == target_day { + let new_moved_ms = timestamp_on_day(moved_ms, target_day, offset_at_ms); + if new_moved_ms == moved_ms { return Ok(false); } - let new_moved_ms = local_wall_ms_to_utc_ms( - target_day - .saturating_mul(86_400_000) - .saturating_add(moved_local_ms.rem_euclid(86_400_000)), - offset_at_ms, - ); let (new_start_ms, new_end_ms) = if is_end { (kept_ms, new_moved_ms) } else { @@ -565,6 +566,7 @@ pub(super) fn handle_add_view( flow_state: &mut DatabaseFlowState, block_id: &str, data: &DatabaseData, + mode: &blocksuite_playground_doc::read::DatabaseViewMode, now_ms: u64, ) -> DocResult { let idx = data.views.len() + 1; @@ -574,14 +576,44 @@ pub(super) fn handle_add_view( .iter() .find(|c| c.column_type == "title") .map_or("title", |c| c.id.as_str()); - let view_json = serde_json::json!({ + use blocksuite_playground_doc::read::DatabaseViewMode; + let label = match mode { + DatabaseViewMode::Table => "Table", + DatabaseViewMode::Kanban => "Kanban", + DatabaseViewMode::Calendar => "Calendar", + DatabaseViewMode::Unknown(_) => { + return Ok(AuthoringActionResult { + handled: false, + doc_mutated: false, + }); + } + }; + let mut view_json = serde_json::json!({ "id": view_id, - "name": format!("Table {idx}"), - "mode": "table", + "name": format!("{label} {idx}"), + "mode": mode.as_str(), "columns": [], "filter": { "type": "group", "op": "and", "conditions": [] }, "header": { "titleColumn": title_col_id, "iconColumn": "type" }, }); + if mode.as_str() == "calendar" { + let dates: Vec<_> = data + .columns + .iter() + .filter(|c| c.column_type == "date") + .take(2) + .collect(); + view_json["date"] = serde_json::json!({"startColumnId": dates.first().map(|c| &c.id), "endColumnId": dates.get(1).map(|c| &c.id)}); + } else if mode.as_str() == "kanban" + && let Some(col) = data + .columns + .iter() + .find(|c| matches!(c.column_type.as_str(), "select" | "multi-select")) + .or_else(|| data.columns.first()) + { + view_json["groupBy"] = + serde_json::json!({"type":"groupBy", "columnId":col.id,"name":col.column_type}); + } let commit = page.add_database_view(block_id, view_json, now_ms)?; if commit.is_some() { flow_state.set_active_view(block_id, view_id); diff --git a/blocksuite/crates/editor/src/database/select_popover.rs b/blocksuite/crates/editor/src/database/select_popover.rs index cc1837614a..2040583d28 100644 --- a/blocksuite/crates/editor/src/database/select_popover.rs +++ b/blocksuite/crates/editor/src/database/select_popover.rs @@ -66,7 +66,11 @@ fn compute_select_popover_layout( } else { 0.0 }; - let content_h = list_rows as f32 * SELECT_ROW_H; + let chip_rows = data + .cells + .get(&(editor.row_id.clone(), editor.column_id.clone())) + .map_or(0, |v| v.as_string_list().len().div_ceil(2)); + let content_h = (list_rows + chip_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); @@ -92,6 +96,9 @@ pub(super) fn measure_select_popover_size( ctx: &DbRenderCtx<'_>, editor: &ActiveCellEditor, ) -> Option<(f32, f32)> { + if ctx.ui_state.authoring.option_menu.is_some() { + return Some((260.0, 144.0)); + } let layout = compute_select_popover_layout(ctx.data, editor)?; Some((236.0, layout.total_h)) } @@ -151,6 +158,72 @@ pub(super) fn render_select_popover_at( radius: 4.0, dashed: false, }); + if let Some(option_id) = &ctx.ui_state.authoring.option_menu { + let mut colors = super::column_ops::TAG_COLOR_PALETTE.to_vec(); + colors.extend(["var(--affine-tag-white)", "#bfa889"]); + for (i, color) in colors.into_iter().enumerate() { + let size = ((pop_w - 12.0) / 11.0).min(22.0); + let rect = FlowRect::new( + input_rect.x + i as f32 * size, + input_rect.bottom() + 14.0, + size - 2.0, + 22.0, + ); + let (fill, _) = resolve_tag_color(color, ctx.theme); + prims.push(DatabasePrim::Quad { + rect, + fill: Some(fill), + border: Some(ctx.palette.border), + radius: 6.0, + dashed: false, + }); + authoring_hits.push(DatabaseAuthoringHit { + rect, + kind: DatabaseAuthoringHitKind::SelectSaveOption { + color: Some(color.into()), + }, + scrolls_x: false, + }); + } + for (i, (label, kind)) in [ + ( + "Save name", + DatabaseAuthoringHitKind::SelectSaveOption { color: None }, + ), + ( + "Delete option", + DatabaseAuthoringHitKind::SelectDeleteOption { + column_id: editor.column_id.clone(), + option_id: option_id.clone(), + }, + ), + ] + .into_iter() + .enumerate() + { + let rect = FlowRect::new( + input_rect.x, + input_rect.bottom() + 42.0 + i as f32 * 28.0, + input_rect.w, + 28.0, + ); + prims.push(ctx.single_line_clipped( + label, + InlineStyle::new(FONT_SANS, 13.0, 500.0, ctx.palette.text_primary), + rect.x + 6.0, + rect.y, + rect.w - 12.0, + rect.h, + InlineAlign::Left, + )); + authoring_hits.push(DatabaseAuthoringHit { + rect, + kind, + scrolls_x: false, + }); + } + return Some(input_rect); + } if editor.select_filter.is_empty() { prims.push(ctx.single_line_clipped( "Search or create option…", @@ -170,19 +243,6 @@ pub(super) fn render_select_popover_at( 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); @@ -199,8 +259,71 @@ pub(super) fn render_select_popover_at( let row_w = (pop_w - 2.0 * pad - scrollbar_gutter).max(1.0); let mut ry = list_top - paint_scroll; + for pair in selected_ids.chunks(2) { + for (i, id) in pair.iter().enumerate() { + let opt = options.iter().find(|o| &o.id == id || &o.value == id); + let chip_w = row_w * 0.5 - 3.0; + let visible_top = (ry + 2.0).max(list_top); + let visible_bottom = (ry + row_h - 2.0).min(list_bottom); + if visible_bottom <= visible_top { + continue; + } + let chip = FlowRect::new( + pop_rect.x + pad + i as f32 * (chip_w + 3.0), + visible_top, + chip_w, + visible_bottom - visible_top, + ); + let (bg, ink) = resolve_tag_color(opt.map_or("", |o| o.color.as_str()), ctx.theme); + prims.push(DatabasePrim::Quad { + rect: chip, + fill: Some(bg), + border: None, + radius: 5.0, + dashed: false, + }); + let style = InlineStyle::new(FONT_SANS, 12.0, 500.0, ink); + let (_, layout) = ctx.truncate_text( + opt.map_or(id.as_str(), |o| o.value.as_str()), + style.clone(), + (chip_w - 28.0).max(1.0), + row_h, + ); + prims.push(DatabasePrim::Text { + x: chip.x + 6.0, + y: ry, + layout, + clip: Some(chip), + }); + let close = FlowRect::new(chip.right() - 22.0, chip.y, 22.0, chip.h); + prims.push(ctx.single_line_clipped( + "×", + style, + close.x, + close.y, + close.w, + close.h, + InlineAlign::Center, + )); + authoring_hits.push(DatabaseAuthoringHit { + rect: close, + kind: DatabaseAuthoringHitKind::SelectToggleOption { + row_id: editor.row_id.clone(), + column_id: editor.column_id.clone(), + option_id: id.clone(), + }, + scrolls_x: false, + }); + } + ry += row_h; + } if filtered.is_empty() && !show_create { - let empty_rect = FlowRect::new(pop_rect.x + pad, list_top, row_w, row_h); + let empty_rect = FlowRect::new( + pop_rect.x + pad, + ry.max(list_top), + row_w, + (list_bottom - ry.max(list_top)).clamp(0.0, row_h), + ); prims.push(ctx.single_line_clipped( "No options yet", InlineStyle::new( @@ -290,7 +413,7 @@ pub(super) fn render_select_popover_at( ctx.palette.text_secondary, ); let del_layout = std::rc::Rc::new(crate::block_flow::layout_inline( - "×", + "···", &del_style, del_rect.w, 22.0, @@ -320,8 +443,7 @@ pub(super) fn render_select_popover_at( if del_h > 0.0 { authoring_hits.push(DatabaseAuthoringHit { rect: del_rect, - kind: DatabaseAuthoringHitKind::SelectDeleteOption { - column_id: editor.column_id.clone(), + kind: DatabaseAuthoringHitKind::SelectOptionMenu { option_id: opt.id.clone(), }, scrolls_x: false, @@ -427,3 +549,44 @@ pub(super) fn render_select_popover_at( Some(input_rect) } + +pub(super) fn close_option_menu(flow: &mut super::DatabaseFlowState, block: &str) { + let auth = flow.authoring_mut(block); + auth.option_menu = None; + if let Some(ed) = auth.active_cell.as_mut() { + ed.select_filter.clear(); + } +} + +pub(super) fn save_option( + page: &mut blocksuite_playground_doc::session::PageDocSession, + flow: &mut super::DatabaseFlowState, + block: &str, + data: &DatabaseData, + color: Option<&str>, + now: u64, +) -> blocksuite_playground_doc::DocResult { + let auth = &flow.state_for(block).authoring; + let mut mutated = false; + if let Some(ed) = &auth.active_cell + && let Some(id) = &auth.option_menu + && let Some(opt) = data + .columns + .iter() + .find(|c| c.id == ed.column_id) + .and_then(|c| c.select_options().into_iter().find(|o| o.id == *id)) + { + let label = ed.select_filter.trim(); + let color = color.unwrap_or(&opt.color); + if !label.is_empty() && (label != opt.value || color != opt.color) { + mutated = page + .upsert_database_select_option(block, &ed.column_id, id, label, color, now)? + .is_some(); + } + } + close_option_menu(flow, block); + Ok(super::AuthoringActionResult { + handled: true, + doc_mutated: mutated, + }) +} diff --git a/blocksuite/crates/editor/src/database/view_tabs.rs b/blocksuite/crates/editor/src/database/view_tabs.rs new file mode 100644 index 0000000000..6dfaa9a4ba --- /dev/null +++ b/blocksuite/crates/editor/src/database/view_tabs.rs @@ -0,0 +1,53 @@ +use blocksuite_playground_doc::read::{DatabaseView, DatabaseViewMode}; + +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/playground/src/database_authoring/dnd.rs b/blocksuite/crates/playground/src/database_authoring/dnd.rs index f43ba302a1..9a82deafc9 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd.rs @@ -7,7 +7,7 @@ use blocksuite_editor::{ block_flow::FlowRect, database::{self, DatabaseAuthoringHitKind}, }; -use blocksuite_playground_doc::read::DatabaseData; + use ui::{Context, Window}; use crate::PlaygroundView; @@ -26,8 +26,7 @@ pub(crate) enum DatabaseSettleKind { KanbanCard { block_id: String, row_id: String, - title: String, - tags: Vec, + source: FlowRect, from_rect: FlowRect, to_rect: FlowRect, }, @@ -105,76 +104,28 @@ impl DatabaseDropSettle { } } -pub(crate) fn kanban_card_summary( - db: &DatabaseData, - row_id: &str, - page_titles: &std::collections::BTreeMap, -) -> (String, Vec) { - let title = db - .rows - .iter() - .find(|r| r.row_id == row_id) - .map(|r| blocksuite_editor::database::resolve_rich_text_plain(&r.title, page_titles)) - .filter(|t| !t.trim().is_empty()) - .unwrap_or_else(|| "Untitled".to_string()); - let mut tags = Vec::new(); - for col in &db.columns { - if matches!(col.column_type.as_str(), "select" | "multi-select") - && let Some(val) = db.cells.get(&(row_id.to_string(), col.id.clone())) - { - let opts = col.select_options(); - for id in val.as_string_list() { - if tags.len() >= 3 { - break; - } - let lbl = opts - .iter() - .find(|o| o.id == id || o.value == id) - .map_or(id, |o| o.value.clone()); - if !lbl.is_empty() { - tags.push(lbl); - } - } - } - } - (title, tags) -} - -pub(crate) fn calendar_event_span_days( - db: &DatabaseData, - view_id: Option<&str>, - row_id: &str, -) -> i64 { - let view = view_id - .and_then(|id| db.views.iter().find(|v| v.id == id)) - .or_else(|| db.views.first()); - let start_col = view - .and_then(|v| v.date.as_ref().and_then(|d| d.start_column_id.as_deref())) - .or_else(|| { - db.columns - .iter() - .find(|c| c.column_type == "date") - .map(|c| c.id.as_str()) - }); - let end_col = view.and_then(|v| v.date.as_ref().and_then(|d| d.end_column_id.as_deref())); - let (Some(sc), Some(ec)) = (start_col, end_col) else { - return 1; - }; - let start_ms = db - .cells - .get(&(row_id.to_string(), sc.to_string())) - .and_then(|v| v.as_i64()); - let end_ms = db - .cells - .get(&(row_id.to_string(), ec.to_string())) - .and_then(|v| v.as_i64()); - match (start_ms, end_ms) { - (Some(s), Some(e)) if e > s => ((e - s) / 86_400_000 + 1).clamp(1, 14), - _ => 1, - } -} - impl PlaygroundView { + pub(super) fn calendar_event_range(&self, block_id: &str, row_id: &str) -> Option<(i64, i64)> { + let db = self.database_snapshot_data(block_id)?; + let state = self.flow.database_state.state_for(block_id); + let view = state + .active_view_id + .as_ref() + .and_then(|id| db.views.iter().find(|v| v.id == *id)) + .or_else(|| db.views.first())?; + let (start_col, end_col) = database::resolve_calendar_date_columns(view, &db); + let offset = self.utc_offset_resolver(); + let day = |col: &str| { + db.cells + .get(&(row_id.to_string(), col.to_string())) + .and_then(|value| value.as_i64()) + .map(|ms| database::local_day_index(ms, &offset)) + }; + let start = day(start_col?)?; + let end = end_col.and_then(day).unwrap_or(start).max(start); + Some((start, end)) + } + /// Edge auto-scroll helper shared by Kanban card drag and Table drag: /// scrolls Page `scroll_y` near viewport top/bottom (`56px`) and, when `horizontal` is /// true, `code_scroll_x` near block edges (`48px`). @@ -294,10 +245,6 @@ impl PlaygroundView { } }); if let Some((row_id, column_id, origin_bucket_key, card_rect)) = card { - let (card_title, card_tags) = self - .database_snapshot_data(block_id) - .map(|db| kanban_card_summary(&db, &row_id, &self.page_titles)) - .unwrap_or_else(|| ("Card".to_string(), Vec::new())); self.database_drag = Some(DatabaseDragState::KanbanMoveCard { block_id: block_id.to_string(), row_id, @@ -311,8 +258,6 @@ impl PlaygroundView { grab_offset_x: (click_x - card_rect.x).clamp(0.0, card_rect.w), grab_offset_y: (local_y - card_rect.y).clamp(0.0, card_rect.h), pointer_screen: (pos_x, pos_y), - card_title, - card_tags, start_x: click_x, start_y: local_y, promoted: false, @@ -341,8 +286,6 @@ impl PlaygroundView { source_card_rect, grab_offset_x, grab_offset_y, - card_title, - card_tags, start_x, start_y, promoted, @@ -371,8 +314,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen: (pos_x, pos_y), - card_title, - card_tags, start_x, start_y, promoted, @@ -400,8 +341,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen: (pos_x, pos_y), - card_title, - card_tags, start_x, start_y, promoted: false, @@ -526,8 +465,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen: (pos_x, pos_y), - card_title, - card_tags, start_x, start_y, promoted: true, @@ -563,8 +500,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen, - card_title, - card_tags, promoted, pending_click, .. @@ -627,8 +562,7 @@ impl PlaygroundView { kind: DatabaseSettleKind::KanbanCard { block_id: block_id.clone(), row_id: row_id.clone(), - title: card_title, - tags: card_tags, + source: source_card_rect, from_rect, to_rect, }, diff --git a/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs b/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs index c5ce08a83a..fedf7cb435 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs @@ -33,7 +33,7 @@ pub(crate) enum DatabaseDragState { row_id: String, origin_day: i64, target_day: i64, - span_days: i64, + grab_day_offset: i64, source_chip_rect: FlowRect, grab_offset_x: f32, grab_offset_y: f32, @@ -62,8 +62,6 @@ pub(crate) enum DatabaseDragState { grab_offset_x: f32, grab_offset_y: f32, pointer_screen: (f32, f32), - card_title: String, - card_tags: Vec, start_x: f32, start_y: f32, promoted: bool, @@ -94,7 +92,6 @@ pub(crate) enum DatabaseDragState { grab_offset_x: f32, grab_offset_y: f32, pointer_screen: (f32, f32), - col_name: String, start_x: f32, promoted: bool, pending_click: Option<(database::DatabaseAuthoringHit, f32)>, diff --git a/blocksuite/crates/playground/src/database_authoring/dnd_table.rs b/blocksuite/crates/playground/src/database_authoring/dnd_table.rs index 3887663578..d16d8adef1 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd_table.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd_table.rs @@ -151,15 +151,6 @@ impl PlaygroundView { let Some(origin_idx) = cols.iter().position(|(id, _)| id == column_id) else { return; }; - let col_name = self - .database_snapshot_data(block_id) - .and_then(|db| { - db.columns - .iter() - .find(|c| c.id == column_id) - .map(|c| c.name.clone()) - }) - .unwrap_or_else(|| column_id.to_string()); self.database_drag = Some(DatabaseDragState::TableColumnReorder { block_id: block_id.to_string(), column_id: column_id.to_string(), @@ -170,8 +161,7 @@ impl PlaygroundView { grab_offset_x: (click_x - header_rect.x).clamp(0.0, header_rect.w), grab_offset_y: (local_y - header_rect.y).clamp(0.0, header_rect.h), pointer_screen: (pos_x, pos_y), - col_name, - start_x: click_x, + start_x: pos_x, promoted: false, pending_click, }); @@ -341,7 +331,6 @@ impl PlaygroundView { source_header_rect, grab_offset_x, grab_offset_y, - col_name, start_x, promoted, pending_click, @@ -365,7 +354,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen: (pos_x, pos_y), - col_name, start_x, promoted, pending_click, @@ -375,10 +363,11 @@ impl PlaygroundView { let scroll_x = self .flow_layout() .and_then(|l| l.block(&block_id).and_then(|b| b.body.code_scroll)) + .filter(|cs| local_x >= cs.area.x) .map_or(0.0, |cs| self.overlays.code_scroll_x_for(&block_id, cs)); let cur_x = local_x + scroll_x; if !promoted { - if (cur_x - start_x).abs() < 6.0 { + if (pos_x - start_x).abs() < 6.0 { self.database_drag = Some(DatabaseDragState::TableColumnReorder { block_id, column_id, @@ -389,7 +378,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen: (pos_x, pos_y), - col_name, start_x, promoted: false, pending_click, @@ -447,7 +435,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen: (pos_x, pos_y), - col_name, start_x, promoted: true, pending_click: None, diff --git a/blocksuite/crates/playground/src/database_authoring/geometry.rs b/blocksuite/crates/playground/src/database_authoring/geometry.rs index 2b34ce27c4..6a10734a72 100644 --- a/blocksuite/crates/playground/src/database_authoring/geometry.rs +++ b/blocksuite/crates/playground/src/database_authoring/geometry.rs @@ -204,6 +204,14 @@ impl PlaygroundView { )) } + pub(super) fn table_rect_scrolls(&self, block_id: &str, rect: FlowRect) -> bool { + self.flow_layout() + .and_then(|l| l.block(block_id).and_then(|b| b.body.code_scroll)) + .is_none_or(|cs| { + cs.area.x <= 8.0 || rect.x >= cs.area.x || rect.right() > cs.area.x + 4.0 + }) + } + /// 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( @@ -219,7 +227,7 @@ impl PlaygroundView { 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 + if scrolls_x { cs.area.x } else { 8.0 }, geom.column_x + block.x + cs.area.right(), ) } else { @@ -296,6 +304,24 @@ impl PlaygroundView { if matches!(session.target, DatabaseInlineTarget::RecordTitle { .. }) { return self.record_title_screen_box(w); } + if self.database_record_sheet.is_some() { + match &session.target { + DatabaseInlineTarget::RecordBody { child_id, .. } => { + return Some(( + self.record_value_rect(super::RecordSlot::Note(child_id), w)?, + (14.0, 400.0), + )); + } + DatabaseInlineTarget::ScalarCell { column_id, .. } + | DatabaseInlineTarget::LiveRichCell { column_id, .. } => { + return Some(( + self.record_value_rect(super::RecordSlot::Field(column_id), w)?, + (14.0, 400.0), + )); + } + _ => {} + } + } let layout = self.flow_layout()?; if session.target.is_popover_field() { let (_, overlay) = self.database_popover_overlay(&layout, w)?; @@ -304,22 +330,12 @@ impl PlaygroundView { let block_id = session.target.block_id(); let block = layout.block(block_id)?; let (cell_rect, scrolls_x) = self.resolve_active_cell_local_rect(session)?; - let scroll_x = if scrolls_x { - block - .body - .code_scroll - .map_or(0.0, |cs| self.overlays.code_scroll_x_for(block_id, cs)) + let rect = if scrolls_x && block.body.code_scroll.is_some() { + self.database_clipped_local_rect_to_screen(block_id, cell_rect, true, w)? } else { - 0.0 + self.database_local_rect_to_screen(block_id, cell_rect, scrolls_x, w)? }; - let (origin, canvas_size) = self.canvas_rect(w); - let geom = self.current_page_geometry(f32::from(canvas_size.width)); - let screen_x = f32::from(origin.x) + geom.column_x + block.x + cell_rect.x - scroll_x; - let screen_y = f32::from(origin.y) + block.y + cell_rect.y - self.scroll_y; - Some(( - FlowRect::new(screen_x, screen_y, cell_rect.w, cell_rect.h), - inline_cell_font(&session.target, cell_rect.h), - )) + Some((rect, inline_cell_font(&session.target, cell_rect.h))) } /// Map a screen-space click inside the active database inline input to its UTF-16 offset. @@ -329,7 +345,7 @@ impl PlaygroundView { w: &Window, ) -> Option { let session = self.database_input.as_ref()?; - if !session.target.is_popover_field() { + if self.database_record_sheet.is_none() && !session.target.is_popover_field() { let block_id = session.target.block_id(); let target_ids = match &session.target { DatabaseInlineTarget::LiveRichCell { @@ -411,7 +427,7 @@ impl PlaygroundView { w: &Window, ) -> Option> { let session = self.database_input.as_ref()?; - if !session.target.is_popover_field() { + if self.database_record_sheet.is_none() && !session.target.is_popover_field() { let block_id = session.target.block_id(); if let Some(layout) = self.flow_layout() && let Some(block) = layout.block(block_id) diff --git a/blocksuite/crates/playground/src/database_authoring/hover.rs b/blocksuite/crates/playground/src/database_authoring/hover.rs index f3ba9a9ec8..6d1460911d 100644 --- a/blocksuite/crates/playground/src/database_authoring/hover.rs +++ b/blocksuite/crates/playground/src/database_authoring/hover.rs @@ -101,7 +101,8 @@ pub(crate) enum DatabaseHoverTargetKind { row_id: String, day_index: i64, event_rect: FlowRect, - can_resize: bool, + start_handle: bool, + end_handle: bool, resize_edge: Option, }, ControlRect { @@ -235,22 +236,6 @@ impl PlaygroundView { || self.overlays.code_lang_picker().is_some() } - fn calendar_view_has_end_column(&self, block_id: &str) -> bool { - let Some(db) = self.database_snapshot_data(block_id) else { - return false; - }; - let active_id = self.flow.database_state.state_for(block_id).active_view_id; - let Some(view) = active_id - .as_deref() - .and_then(|id| db.views.iter().find(|v| v.id == id)) - .or_else(|| db.views.first()) - else { - return false; - }; - let (start, end) = database::resolve_calendar_date_columns(view, &db); - matches!((start, end), (Some(s), Some(e)) if s != e) - } - /// Resolve paint-only [`DatabaseHoverState`] and cursor from cached hits and open popovers. /// Zero writes to `DatabaseUiState` or `env_rev` → zero block relayouts. pub(crate) fn update_database_hover( @@ -295,35 +280,28 @@ impl PlaygroundView { // 1. Popover isolation: an open database popover always captures hover first and blocks // any underlying Table / Kanban / Calendar hover or cursor from bleeding through. if let Some((pop_block, overlay)) = self.database_popover_overlay(&layout, window) - && overlay.contains(pos_x, pos_y) + && let Some(target) = overlay.target_at(pos_x, pos_y) { - let (target, cursor) = if let Some((idx, hit)) = overlay - .hits - .iter() - .enumerate() - .rev() - .find(|(_, h)| h.rect.contains(pos_x, pos_y)) - { - ( - DatabaseHoverTargetKind::PopoverItem { - index: idx, - rect: hit.rect, - }, - database_authoring_hit_cursor(&hit.kind, readonly), - ) - } else if overlay - .text_input_rect - .is_some_and(|r| r.contains(pos_x, pos_y)) - { - ( + use blocksuite_editor::database::PopoverTarget; + let (target, cursor) = match target { + PopoverTarget::Item(index) => { + let hit = &overlay.hits[index]; + ( + DatabaseHoverTargetKind::PopoverItem { + index, + rect: hit.rect, + }, + database_authoring_hit_cursor(&hit.kind, readonly), + ) + } + PopoverTarget::Input => ( DatabaseHoverTargetKind::PopoverBackground, CursorStyle::IBeam, - ) - } else { - ( + ), + PopoverTarget::Background => ( DatabaseHoverTargetKind::PopoverBackground, CursorStyle::Arrow, - ) + ), }; self.apply_database_hover(Some(pop_block), Some(target), Some(cursor), cx); return; @@ -426,10 +404,10 @@ impl PlaygroundView { // 4. Table column resize handle & column header hover. if !readonly - && in_scroll_area && let Some(hit) = auth_hits.iter().find(|h| { matches!(h.kind, DatabaseAuthoringHitKind::ResizeColumnHandle { .. }) - && h.rect.contains(sx, ly) + && (!h.scrolls_x || in_scroll_area) + && h.rect.contains(if h.scrolls_x { sx } else { lx }, ly) }) && let DatabaseAuthoringHitKind::ResizeColumnHandle { column_id, .. } = &hit.kind { @@ -446,10 +424,12 @@ impl PlaygroundView { } if !readonly - && in_scroll_area && let Some((col_id, col_rect)) = collect_table_column_rects(auth_hits) .into_iter() - .find(|(_, r)| r.contains(sx, ly)) + .find(|(_, r)| { + let scrolls = self.table_rect_scrolls(&block_id, *r); + (!scrolls || in_scroll_area) && r.contains(if scrolls { sx } else { lx }, ly) + }) { self.apply_database_hover( Some(block_id), @@ -487,6 +467,7 @@ impl PlaygroundView { column_id, col_type, } if rid == &row_id + && in_scroll_area && col_type == "link" && (h.rect.y - row_rect.y).abs() < 2.0 && h.rect.contains(sx, ly) => @@ -505,10 +486,15 @@ impl PlaygroundView { cursor = CursorStyle::OpenHand; } else if let Some(tr) = title_rect { let (peek_r, menu_r) = table_row_ops_rects(tr); - if peek_r.contains(sx, ly) { + let tx = if self.table_rect_scrolls(&block_id, tr) { + sx + } else { + lx + }; + if peek_r.contains(tx, ly) { op_hover = Some(RowOpHover::Peek); cursor = CursorStyle::PointingHand; - } else if !readonly && menu_r.contains(sx, ly) { + } else if !readonly && menu_r.contains(tx, ly) { op_hover = Some(RowOpHover::Menu); cursor = CursorStyle::PointingHand; } @@ -525,18 +511,16 @@ impl PlaygroundView { cursor = CursorStyle::PointingHand; } } - if op_hover.is_none() && in_scroll_area { - if let Some(hit) = base_hits - .iter() - .rev() - .find(|h| h.scrolls_x && h.rect.contains(sx, ly)) - { + if op_hover.is_none() { + if let Some(hit) = base_hits.iter().rev().find(|h| { + (!h.scrolls_x || in_scroll_area) + && h.rect.contains(if h.scrolls_x { sx } else { lx }, ly) + }) { cursor = database_hit_cursor(&hit.kind, readonly); - } else if let Some(hit) = auth_hits - .iter() - .rev() - .find(|h| h.scrolls_x && h.rect.contains(sx, ly)) - { + } else if let Some(hit) = auth_hits.iter().rev().find(|h| { + (!h.scrolls_x || in_scroll_area) + && h.rect.contains(if h.scrolls_x { sx } else { lx }, ly) + }) { cursor = database_authoring_hit_cursor(&hit.kind, readonly); } } @@ -561,15 +545,32 @@ impl PlaygroundView { &hit.kind { let row_editing = editing_row_id == Some(row_id.as_str()); - let can_resize = self.calendar_view_has_end_column(&block_id); - let resize_edge = if can_resize && !readonly && !row_editing && hit.rect.w >= 20.0 { - if lx <= hit.rect.x + 6.0 { - Some(false) - } else if lx >= hit.rect.right() - 6.0 { - Some(true) - } else { - None - } + let range = self.calendar_event_range(&block_id, row_id); + let segment_contains = |day| { + auth_hits.iter().any(|h| { + let DatabaseAuthoringHitKind::CalendarDayDropTarget { day_index } = h.kind + else { + return false; + }; + day_index == day + && h.rect.y <= hit.rect.y + && hit.rect.y < h.rect.bottom() + && hit.rect.x < h.rect.right() + && h.rect.x < hit.rect.right() + }) + }; + let start_handle = + range.is_some_and(|(start, end)| start < end && segment_contains(start)); + let end_handle = range.is_some_and(|(start, end)| start < end && segment_contains(end)); + let rtl = window.layout_direction().is_rtl(); + let at_left = lx <= hit.rect.x + 6.0; + let at_right = lx >= hit.rect.right() - 6.0; + let resize_edge = if readonly || row_editing || hit.rect.w < 20.0 { + None + } else if start_handle && if rtl { at_right } else { at_left } { + Some(false) + } else if end_handle && if rtl { at_left } else { at_right } { + Some(true) } else { None }; @@ -582,9 +583,16 @@ impl PlaygroundView { Some(block_id), (!row_editing).then_some(DatabaseHoverTargetKind::CalendarEvent { row_id: row_id.clone(), - day_index: *day_index, + day_index: range.map_or(*day_index, |(start, end)| { + if resize_edge == Some(true) { + end + } else { + start + } + }), event_rect: hit.rect, - can_resize, + start_handle, + end_handle, resize_edge, }), Some(cursor), @@ -601,6 +609,11 @@ impl PlaygroundView { ) && h.rect.contains(lx, ly) }) && let DatabaseAuthoringHitKind::CalendarDayDropTarget { day_index } = &hit.kind { + let (year, month, _) = crate::block_flow::civil_from_days(*day_index); + if self.resolve_database_calendar_month(&block_id, cx) != (year as i32, month) { + self.clear_database_hover(cx); + return; + } let offset_at = self.utc_offset_resolver(); let today_day = database::local_day_index(self.flow.database_state.clock_ms, &offset_at); diff --git a/blocksuite/crates/playground/src/database_authoring/hover_ops.rs b/blocksuite/crates/playground/src/database_authoring/hover_ops.rs index f426f45a1d..489b921b65 100644 --- a/blocksuite/crates/playground/src/database_authoring/hover_ops.rs +++ b/blocksuite/crates/playground/src/database_authoring/hover_ops.rs @@ -80,23 +80,25 @@ impl PlaygroundView { .. } => { if let Some(tr) = title_rect { + let scrolls = self.table_rect_scrolls(block_id, tr); + let tx = if scrolls { sx } else { local_x }; let (peek_r, menu_r) = table_row_ops_rects(tr); - if peek_r.contains(sx, local_y) { + if peek_r.contains(tx, local_y) { self.open_database_record_sheet(block_id, &row_id, cx); self.clear_database_hover(cx); return true; } - if !readonly && menu_r.contains(sx, local_y) { + if !readonly && menu_r.contains(tx, local_y) { let hit = database::DatabaseAuthoringHit { rect: menu_r, kind: DatabaseAuthoringHitKind::OpenRowMenu { row_id, is_kanban: false, }, - scrolls_x: true, + scrolls_x: scrolls, }; return self - .dispatch_database_authoring_hit(block_id, &hit, sx, window, cx); + .dispatch_database_authoring_hit(block_id, &hit, tx, window, cx); } } if !readonly @@ -193,6 +195,13 @@ impl PlaygroundView { resize_edge: Some(is_end), .. } if !readonly => { + let auth = self.flow.database_state.authoring_mut(block_id); + auth.calendar_resize_end = Some(is_end); + auth.calendar_drag = Some(database::CalendarDragState { + row_id: row_id.clone(), + origin_day: day_index, + target_day: day_index, + }); self.database_drag = Some(DatabaseDragState::CalendarResize { block_id: block_id.to_string(), row_id, diff --git a/blocksuite/crates/playground/src/database_authoring/inline.rs b/blocksuite/crates/playground/src/database_authoring/inline.rs index 0b5352dc9b..24f208138c 100644 --- a/blocksuite/crates/playground/src/database_authoring/inline.rs +++ b/blocksuite/crates/playground/src/database_authoring/inline.rs @@ -16,7 +16,9 @@ use blocksuite_editor::{ inline_input::{AnchoredInlineInput, TextSplice}, }; use blocksuite_playground_doc::read::BlockContent; +use blocksuite_playground_doc::session::PageDocSession; use ui::{Context, Window}; +use y_octo::{RelativePosition, SessionReadValue, TypePath, TypeTarget}; use crate::{PlaygroundView, overlays::InlineTargetEnd}; @@ -39,6 +41,11 @@ pub(crate) enum DatabaseInlineTarget { col_type: String, initial: String, }, + RecordBody { + block_id: String, + row_id: String, + child_id: String, + }, ColumnRename { block_id: String, column_id: String, @@ -64,6 +71,7 @@ impl DatabaseInlineTarget { pub(crate) fn block_id(&self) -> &str { match self { Self::LiveRichCell { block_id, .. } + | Self::RecordBody { block_id, .. } | Self::ScalarCell { block_id, .. } | Self::ColumnRename { block_id, .. } | Self::SelectFilter { block_id, .. } @@ -87,12 +95,62 @@ impl DatabaseInlineTarget { } } + pub(super) fn tracks_text(&self) -> bool { + matches!(self, Self::RecordBody { .. }) || self.live_text().is_some() + } + + fn paragraph_text(&self, page: &PageDocSession) -> Option { + let Self::RecordBody { child_id, .. } = self else { + return None; + }; + let block = TypeTarget::Path(TypePath::root("blocks").key(child_id.as_str())); + match page.inner().get_map_value(&block, "prop:text").ok()?? { + SessionReadValue::Text(id) => Some(TypeTarget::Identity(id)), + _ => None, + } + } + + pub(super) fn encode_anchor( + &self, + page: &PageDocSession, + offset: usize, + ) -> Option { + if let Some((block, row, col, title)) = self.live_text() { + return page + .encode_database_cell_relative_position(block, row, col, title, offset as u64) + .ok() + .flatten(); + } + let target = self.paragraph_text(page)?; + let len = page.inner().read_text_len(&target).ok()?; + page.inner() + .create_relative_position(&target, len.min(offset as u64), -1) + .ok() + } + + pub(super) fn resolve_anchor( + &self, + page: &PageDocSession, + pos: &RelativePosition, + ) -> Option { + if let Some((block, row, col, title)) = self.live_text() { + return page + .resolve_database_cell_relative_position(block, row, col, title, pos) + .ok() + .flatten() + .map(|i| i as usize); + } + let target = self.paragraph_text(page)?; + let absolute = page.inner().resolve_relative_position(pos, true)?; + (target == TypeTarget::Identity(absolute.r#type)).then_some(absolute.index as usize) + } pub(crate) fn is_popover_field(&self) -> bool { matches!( self, Self::ColumnRename { .. } | Self::SelectFilter { .. } | Self::FilterValue { .. } + | Self::RecordBody { .. } | Self::RecordTitle { .. } ) } @@ -164,6 +222,7 @@ impl DatabaseInlineTarget { row_id: r2, }, ) => b1 == b2 && r1 == r2, + (Self::RecordBody { .. }, Self::RecordBody { .. }) => self == other, _ => false, } } @@ -299,6 +358,20 @@ impl PlaygroundView { false, )); } + if let Some(sheet) = &self.database_record_sheet + && let Some(note) = &sheet.note_editing + { + let text = note.text(self.snapshot.as_ref()?.block(&sheet.row_id)?)?; + return Some(( + DatabaseInlineTarget::RecordBody { + block_id: sheet.block_id.clone(), + row_id: sheet.row_id.clone(), + child_id: note.id().to_string(), + }, + text.to_string(), + true, + )); + } for (block_id, st) in self.flow.database_state.states() { let a = &st.authoring; if let Some(menu) = &a.column_menu { @@ -391,7 +464,7 @@ impl PlaygroundView { let desired = self.desired_database_inline_target(); let changed = match (&self.database_input, desired) { (Some(cur), Some((target, text, _))) if cur.target.same_slot(&target) => { - if target.live_text().is_none() + if !target.tracks_text() && !cur.anchored.input.composing() && cur.anchored.input.text != text && let Some(cur_mut) = self.database_input.as_mut() @@ -415,16 +488,10 @@ impl PlaygroundView { } } let mut anchored = AnchoredInlineInput::new(text, multiline); - if let Some((block_id, row_id, column_id, is_title)) = target.live_text() + if target.tracks_text() && let Some(page) = self.page() { - anchored.update_anchors(|off| { - page.encode_database_cell_relative_position( - block_id, row_id, column_id, is_title, off as u64, - ) - .ok() - .flatten() - }); + anchored.update_anchors(|off| target.encode_anchor(page, off)); } let opened_ms = (self.now_ms(cx) as u64).max(1); self.database_input = Some(DatabaseInlineSession { @@ -478,35 +545,25 @@ impl PlaygroundView { session.dirty = true; } - if let Some((block_id, row_id, column_id, is_title)) = target.live_text() { - let mut pending_sync: Option>> = None; - if let Some((start, del, insert)) = splice { - let now_ms = self.now_ms(cx) as u64; - let before_sv = self.page().and_then(|p| p.encode_state_vector_v1().ok()); - if self.splice_database_live_text( - (block_id, row_id, column_id, is_title), - (start, del, &insert), - now_ms, - ) { - pending_sync = Some(before_sv); - } - } + if target.tracks_text() { + let before = splice + .as_ref() + .and_then(|_| self.page()?.encode_state_vector_v1().ok()); + let changed = splice.is_some_and(|(start, del, insert)| { + self.splice_database_input(&target, (start, del, &insert), edit_ms) + }); if let Some(session) = self.database_input.as_mut() && let Some(page) = self .page_id .as_deref() .and_then(|id| self.state.workspace.page(id)) { - session.anchored.update_anchors(|off| { - page.encode_database_cell_relative_position( - block_id, row_id, column_id, is_title, off as u64, - ) - .ok() - .flatten() - }); + session + .anchored + .update_anchors(|off| target.encode_anchor(page, off)); } - if let Some(before_sv) = pending_sync { - self.sync_after_database_mutation(before_sv, cx); + if changed { + self.sync_after_database_mutation(before, cx); } } match &target { @@ -553,7 +610,7 @@ impl PlaygroundView { let auth = self.flow.database_state.authoring_mut(block_id); auth.filter_draft.value = display; } - DatabaseInlineTarget::RecordTitle { .. } => {} + DatabaseInlineTarget::RecordBody { .. } | DatabaseInlineTarget::RecordTitle { .. } => {} } self.reset_caret_blink(cx); @@ -601,13 +658,15 @@ impl PlaygroundView { let offset_at = self.utc_offset_resolver(); match &session.target { DatabaseInlineTarget::LiveRichCell { .. } + | DatabaseInlineTarget::RecordBody { .. } | DatabaseInlineTarget::RecordTitle { .. } => { - if let Some(live) = session.target.live_text() - && let Some((start, del, insert)) = unmark_splice - { + if let Some((start, del, insert)) = unmark_splice { let before_sv = self.page().and_then(|p| p.encode_state_vector_v1().ok()); - let mutated = - self.splice_database_live_text(live, (start, del, &insert), now_ms); + let mutated = self.splice_database_input( + &session.target, + (start, del, &insert), + now_ms, + ); if mutated && let Some(cx_ref) = cx { self.sync_after_database_mutation(before_sv, cx_ref); } else if mutated { @@ -672,6 +731,7 @@ impl PlaygroundView { } if let Some(sheet) = self.database_record_sheet.as_mut() { sheet.title_editing = false; + sheet.note_editing = None; } self.flow .database_state @@ -682,12 +742,21 @@ impl PlaygroundView { /// Splice `(start, delete_len, insert)` UTF-16 units into the live `Y.Text` of /// [`DatabaseInlineTarget::live_text`]. Returns whether the document changed. - fn splice_database_live_text( + fn splice_database_input( &mut self, - (block_id, row_id, column_id, is_title): (&str, &str, &str, bool), + target: &DatabaseInlineTarget, (start, del, insert): (usize, usize, &str), now_ms: u64, ) -> bool { + if let DatabaseInlineTarget::RecordBody { + row_id, child_id, .. + } = target + { + return self.splice_record_note(row_id, child_id, start, del, insert, now_ms); + } + let Some((block_id, row_id, column_id, is_title)) = target.live_text() else { + return false; + }; self.page_mut().is_ok_and(|page| { let res = if is_title { page.splice_database_row_title( diff --git a/blocksuite/crates/playground/src/database_authoring/keys.rs b/blocksuite/crates/playground/src/database_authoring/keys.rs index b3b4601bd0..f754cb3e87 100644 --- a/blocksuite/crates/playground/src/database_authoring/keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/keys.rs @@ -98,6 +98,7 @@ impl PlaygroundView { matches!( d.target, DatabaseInlineTarget::LiveRichCell { .. } + | DatabaseInlineTarget::RecordBody { .. } | DatabaseInlineTarget::RecordTitle { .. } ) }) && matches!( @@ -212,57 +213,49 @@ impl PlaygroundView { let Some(mut session) = self.database_input.take() else { return; }; - if !self + let Some((_, desired_text, _)) = self .desired_database_inline_target() - .is_some_and(|(desired, _, _)| session.target.same_slot(&desired)) - { + .filter(|(desired, _, _)| session.target.same_slot(desired)) + else { // The layout of the session's block can show the preedit of the session. self.flow .database_state .mark_dirty(session.target.block_id()); return; - } - if let Some((block_id, row_id, column_id, is_title)) = session.target.live_text() { - let latest = self - .database_snapshot_data(block_id) - .and_then(|db| { - let row = db.rows.iter().find(|r| r.row_id == row_id)?; - if is_title { - Some(row.title.plain.clone()) - } else { - match db.cells.get(&(row_id.to_string(), column_id.to_string())) { - Some(DatabaseCellValue::RichText(rt)) => Some(rt.plain.clone()), - Some(DatabaseCellValue::Text(s)) => Some(s.clone()), - _ => Some(String::new()), - } - } - }) - .unwrap_or_default(); - session.anchored.reconcile_from_text(latest.clone(), |pos| { - self.page() - .and_then(|p| { - p.resolve_database_cell_relative_position( - block_id, row_id, column_id, is_title, pos, - ) - .ok() - .flatten() - }) - .map(|off| off as usize) - }); + }; + if session.target.tracks_text() { + let latest = + if let Some((block_id, row_id, column_id, is_title)) = session.target.live_text() { + self.database_snapshot_data(block_id) + .and_then(|db| { + let row = db.rows.iter().find(|r| r.row_id == row_id)?; + if is_title { + Some(row.title.plain.clone()) + } else { + match db.cells.get(&(row_id.to_string(), column_id.to_string())) { + Some(DatabaseCellValue::RichText(rt)) => Some(rt.plain.clone()), + Some(DatabaseCellValue::Text(s)) => Some(s.clone()), + _ => Some(String::new()), + } + } + }) + .unwrap_or_default() + } else { + desired_text + }; if let Some(page) = self.page() { - session.anchored.update_anchors(|off| { - page.encode_database_cell_relative_position( - block_id, row_id, column_id, is_title, off as u64, - ) - .ok() - .flatten() + session.anchored.reconcile_from_text(latest.clone(), |pos| { + session.target.resolve_anchor(page, pos) }); + session + .anchored + .update_anchors(|off| session.target.encode_anchor(page, off)); } if matches!(session.target, DatabaseInlineTarget::LiveRichCell { .. }) && let Some(ed) = self .flow .database_state - .authoring_mut(block_id) + .authoring_mut(session.target.block_id()) .active_cell .as_mut() { diff --git a/blocksuite/crates/playground/src/database_authoring/mod.rs b/blocksuite/crates/playground/src/database_authoring/mod.rs index f7d09cdb63..1bed7c30c4 100644 --- a/blocksuite/crates/playground/src/database_authoring/mod.rs +++ b/blocksuite/crates/playground/src/database_authoring/mod.rs @@ -13,6 +13,7 @@ mod paint; mod paint_dnd; mod paint_hover; mod pointer; +mod popover_layout; mod record_title; #[cfg(test)] mod tests; @@ -59,6 +60,45 @@ use ui::{Context, Window}; use crate::PlaygroundView; +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RecordParagraph { + Draft(String), + Existing(String), +} + +impl RecordParagraph { + pub(crate) fn id(&self) -> &str { + match self { + Self::Draft(id) | Self::Existing(id) => id, + } + } + + pub(crate) fn text<'a>( + &self, + row: &'a blocksuite_playground_doc::read::BlockNode, + ) -> Option<&'a str> { + match self { + Self::Draft(_) => Some(""), + Self::Existing(id) => row + .children + .iter() + .find(|n| n.id == *id) + .and_then(|n| match &n.content { + BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } => { + Some(text.plain.as_str()) + } + _ => None, + }), + } + } +} + +pub(crate) enum RecordSlot<'a> { + Field(&'a str), + Note(&'a str), + AddProperty, +} + impl PlaygroundView { /// Unified read-only gate for all `affine:database` write and authoring controls: /// true when either database-level readonly (mobile Stage-1) or Page-level readonly is active. @@ -352,38 +392,37 @@ impl PlaygroundView { cx, ); } - let (span_days, event_title) = self - .database_snapshot_data(block_id) - .map(|db| { - let active_view = self - .flow - .database_state - .state_for(block_id) - .active_view_id - .clone(); - let span = - dnd::calendar_event_span_days(&db, active_view.as_deref(), row_id); - let title = db - .rows - .iter() - .find(|r| r.row_id == *row_id) - .map(|r| { - blocksuite_editor::database::resolve_rich_text_plain( - &r.title, - &self.page_titles, - ) - }) - .filter(|t| !t.trim().is_empty()) - .unwrap_or_else(|| "Event".to_string()); - (span, title) + let origin_day = self + .calendar_event_range(block_id, row_id) + .map_or(*day_index, |range| range.0); + let grabbed_day = self + .flow + .database_authoring_hits(block_id) + .iter() + .find_map(|h| match h.kind { + DatabaseAuthoringHitKind::CalendarDayDropTarget { day_index } + if h.rect.contains(local_x, local_y) => + { + Some(day_index) + } + _ => None, }) - .unwrap_or_else(|| (1, "Event".to_string())); + .unwrap_or(*day_index); + let event_title = + self.database_snapshot_data(block_id) + .and_then(|db| { + db.rows.iter().find(|r| r.row_id == *row_id).map(|r| { + database::resolve_rich_text_plain(&r.title, &self.page_titles) + }) + }) + .filter(|title| !title.trim().is_empty()) + .unwrap_or_else(|| "Event".to_string()); self.database_drag = Some(DatabaseDragState::CalendarReschedule { block_id: block_id.to_string(), row_id: row_id.clone(), - origin_day: *day_index, - target_day: *day_index, - span_days, + origin_day, + target_day: origin_day, + grab_day_offset: grabbed_day - origin_day, source_chip_rect: hit.rect, grab_offset_x: (local_x - hit.rect.x).clamp(0.0, hit.rect.w), grab_offset_y: (local_y - hit.rect.y).clamp(0.0, hit.rect.h), @@ -404,23 +443,7 @@ impl PlaygroundView { } } DatabaseAuthoringHitKind::SetProgress { row_id, column_id } => { - let value = database::progress_from_bar_x(click_x, hit.rect.x, hit.rect.w); - self.database_drag = Some(DatabaseDragState::ProgressScrub { - block_id: block_id.to_string(), - row_id: row_id.clone(), - column_id: column_id.clone(), - bar_x: hit.rect.x, - bar_w: hit.rect.w, - scrolls_x: hit.scrolls_x, - }); - self.flow - .database_state - .authoring_mut(block_id) - .progress_preview = Some(ProgressScrubPreview { - row_id: row_id.clone(), - column_id: column_id.clone(), - value, - }); + self.start_database_progress_scrub(block_id, row_id, column_id, &hit, click_x, cx); if let Some(w) = window { self.editor_focus.focus(w, cx); } @@ -478,7 +501,36 @@ impl PlaygroundView { self.dispatch_database_authoring_hit(block_id, &hit, click_x, window, cx) } - pub(super) fn dispatch_database_authoring_hit( + pub(crate) fn start_database_progress_scrub( + &mut self, + block_id: &str, + row_id: &str, + column_id: &str, + hit: &database::DatabaseAuthoringHit, + click_x: f32, + cx: &mut Context, + ) { + let value = database::progress_from_bar_x(click_x, hit.rect.x, hit.rect.w); + self.database_drag = Some(DatabaseDragState::ProgressScrub { + block_id: block_id.to_string(), + row_id: row_id.to_string(), + column_id: column_id.to_string(), + bar_x: hit.rect.x, + bar_w: hit.rect.w, + scrolls_x: hit.scrolls_x, + }); + self.flow + .database_state + .authoring_mut(block_id) + .progress_preview = Some(ProgressScrubPreview { + row_id: row_id.to_string(), + column_id: column_id.to_string(), + value, + }); + cx.notify(); + } + + pub(crate) fn dispatch_database_authoring_hit( &mut self, block_id: &str, hit: &database::DatabaseAuthoringHit, @@ -514,7 +566,7 @@ impl PlaygroundView { &mut self.flow.database_state, block_id, &db_data, - &hit, + hit, click_x, &offset_at, now_ms, diff --git a/blocksuite/crates/playground/src/database_authoring/paint.rs b/blocksuite/crates/playground/src/database_authoring/paint.rs index deeb837f5c..9bcd178516 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint.rs @@ -6,11 +6,10 @@ use blocksuite_editor::{ FlowLayout, FlowRect, InlineAlign, InlineBaseline, InlineLayout, InlineStyle, PAGE_SURFACE_ID, PageViewport, layout_inline, }, - database::{self, DatabasePopoverOverlay, DatabasePrim, layout_database_popover_overlay}, + database::{self, DatabasePrim}, inline_input::Utf16ImeBuffer, theme::{FONT_SANS, Palette}, }; -use blocksuite_playground_doc::read::BlockContent; use ui::{ AnyElement, BorderStyle, Context, Window, canvas, div, fill, point, prelude::*, px, quad, }; @@ -279,58 +278,6 @@ pub(super) fn paint_inline_box_elements( } impl PlaygroundView { - /// Compute the active screen-space [`DatabasePopoverOverlay`] (`ColumnMenu`, `SelectPicker`, - /// or `ToolbarPanel`) if any writable database block currently has one open. - pub(crate) fn database_popover_overlay( - &self, - layout: &FlowLayout, - window: &Window, - ) -> Option<(String, DatabasePopoverOverlay)> { - 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)?; - let data = - self.snapshot - .as_ref() - .and_then(|snap| match &snap.block(&block_id)?.content { - BlockContent::Database(db) => Some(db), - _ => None, - })?; - let (_, canvas_size) = self.canvas_rect(window); - let topbar = self.topbar_height(); - let geom = self.current_page_geometry(f32::from(canvas_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 + block.y - paint_scroll_y); - let scroll_x = block - .body - .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, - self.theme, - window.layout_direction(), - self.form_factor, - self.is_database_write_readonly(), - self.flow.database_state.clock_ms, - &offset_at, - &self.page_titles, - window, - )?; - Some((block_id, overlay)) - } - /// In-place visual elements for a focused database cell (`LiveRichCell` or `ScalarCell`): /// focus ring, live scalar draft text, selection highlight, IME underline, and 500 ms /// blinking caret. @@ -368,8 +315,9 @@ impl PlaygroundView { if cell_world.bottom() < v.scroll_y || cell_world.y > v.scroll_y + v.height { return out; } - let vis_left = block.x; - let vis_right = block.x + block.body.width; + let clip = block.body.code_scroll.filter(|_| scrolls_x); + let vis_left = block.x + clip.map_or(0.0, |cs| cs.area.x); + let vis_right = block.x + clip.map_or(block.body.width, |cs| cs.area.right()); let left = cell_world.x.max(vis_left); let right = cell_world.right().min(vis_right); if right <= left { @@ -468,9 +416,9 @@ impl PlaygroundView { } } else { let page_local_rect = FlowRect::new( - v.column_x + cell_world.x, - cell_world.y - v.scroll_y, - cell_world.w, + v.column_x + clipped.x, + clipped.y - v.scroll_y, + clipped.w, cell_world.h, ); let (font_px, weight) = inline_cell_font(&session.target, cell_world.h); @@ -498,6 +446,18 @@ impl PlaygroundView { layout: &FlowLayout, window: &Window, cx: &mut Context, + ) -> Vec { + if self.database_record_sheet.is_some() { + return Vec::new(); + } + self.record_picker_elements(layout, window, cx) + } + + pub(crate) fn record_picker_elements( + &self, + layout: &FlowLayout, + window: &Window, + cx: &mut Context, ) -> Vec { let Some((_, overlay)) = self.database_popover_overlay(layout, window) else { return Vec::new(); @@ -533,6 +493,14 @@ impl PlaygroundView { } }), ); + if self.database_record_sheet.is_some() { + shield = shield.occlude().on_scroll(cx.listener( + |this, event: &ui::ScrollEvent, w, cx| { + this.try_scroll_database_popover(event, w, cx); + cx.stop_propagation(); + }, + )); + } if idx == 0 { shield = shield.snapshot("overlay.database_popover", None); } @@ -676,20 +644,18 @@ impl PlaygroundView { let Some((block_id, overlay)) = self.database_popover_overlay(&layout, window) else { return false; }; - let hit = overlay - .hits - .iter() - .rev() - .find(|h| h.rect.contains(screen_x, screen_y)) - .cloned(); - let inside_popover = hit.is_some() || overlay.contains(screen_x, screen_y); - if !inside_popover { + let Some(target) = overlay.target_at(screen_x, screen_y) else { return false; - } - - // Clicking inside the popover's text field repositions the caret cleanly. - if let Some(input_rect) = overlay.text_input_rect - && input_rect.contains(screen_x, screen_y) + }; + let input = match target { + database::PopoverTarget::Input => true, + database::PopoverTarget::Item(i) => matches!( + overlay.hits[i].kind, + database::DatabaseAuthoringHitKind::ColumnMenuRenameInput + ), + database::PopoverTarget::Background => false, + }; + if input && let Some(off) = self.database_inline_character_index_for_point( point(px(screen_x), px(screen_y)), window, @@ -703,12 +669,13 @@ impl PlaygroundView { return true; } - let Some(hit) = hit else { + let database::PopoverTarget::Item(index) = target else { // Click landed on non-button background inside the popover: keep popover open. self.editor_focus.focus(window, cx); return true; }; + let hit = &overlay.hits[index]; 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); @@ -751,7 +718,7 @@ impl PlaygroundView { &mut self.flow.database_state, &block_id, &db_data, - &hit, + hit, screen_x, &offset_at, now_ms, diff --git a/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs b/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs index fa2a9ed8ed..61304e966d 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint_dnd.rs @@ -6,7 +6,7 @@ use blocksuite_editor::{ block_flow::{FlowRect, InlineAlign, InlineBaseline, InlineStyle, layout_inline}, database::DatabaseAuthoringHitKind, - theme::{FONT_SANS, Palette, TYPOGRAPHY}, + theme::{FONT_SANS, TYPOGRAPHY}, }; use ui::{ AnyElement, BorderStyle, Bounds, Context, Hsla, TransformationMatrix, Window, canvas, div, @@ -29,117 +29,6 @@ fn rotation_matrix_around(cx: f32, cy: f32, angle_deg: f32) -> TransformationMat } } -fn paint_floating_kanban_card( - rect: FlowRect, - angle_deg: f32, - title: String, - tags: Vec, - palette: &Palette, - window: &Window, -) -> AnyElement { - let bg = palette.background; - let brand = palette.brand; - let shadow_outer = Hsla::black().opacity(0.10); - let shadow_inner = Hsla::black().opacity(0.14); - let pill_bg = palette.hover; - let title_style = InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_sm_px, - 500.0, - palette.text_primary, - ); - let title_laid = std::rc::Rc::new(layout_inline( - &title, - &title_style, - (rect.w - 20.0).max(20.0), - 20.0, - InlineBaseline::Of(&title_style), - InlineAlign::Left, - window, - )); - let tag_style = InlineStyle::new( - FONT_SANS, - TYPOGRAPHY.font_xs_px - 1.0, - 500.0, - palette.text_secondary, - ); - let tag_layouts: Vec<(f32, std::rc::Rc<_>)> = tags - .iter() - .take(3) - .map(|t| { - let laid = std::rc::Rc::new(layout_inline( - t, - &tag_style, - 100.0, - 16.0, - InlineBaseline::Of(&tag_style), - InlineAlign::Left, - window, - )); - let w = (laid.content_width().ceil() + 10.0).clamp(24.0, 92.0); - (w, laid) - }) - .collect(); - - canvas( - |_, _, _| (), - move |_, _, window, cx| { - let origin = point(px(0.0), px(0.0)); - let cx_p = rect.x + rect.w * 0.5; - let cy_p = rect.y + rect.h * 0.5; - let xform = rotation_matrix_around(cx_p, cy_p, angle_deg); - window.with_paint_transformation(xform, |window| { - // Soft 2-layer elevation shadow. - let s1 = FlowRect::new(rect.x - 2.0, rect.y + 6.0, rect.w + 4.0, rect.h + 2.0); - window.paint_quad(fill(s1.bounds(origin), shadow_outer).corner_radii(px(10.0))); - let s2 = FlowRect::new(rect.x, rect.y + 3.0, rect.w, rect.h); - window.paint_quad(fill(s2.bounds(origin), shadow_inner).corner_radii(px(8.0))); - // Card body with focus brand border (matches JS `kanbanCard.isFocus$.value = true`). - window.paint_quad(quad( - rect.bounds(origin), - px(8.0), - bg, - px(1.5), - brand, - BorderStyle::Solid, - )); - let clip = FlowRect::new( - rect.x + 10.0, - rect.y + 8.0, - (rect.w - 20.0).max(1.0), - (rect.h - 14.0).max(1.0), - ); - window.with_local_paint_mask( - ui::ContentMask { - bounds: clip.bounds(origin), - }, - |window| { - title_laid.paint(point(px(rect.x + 10.0), px(rect.y + 8.0)), window, cx); - let mut tx = rect.x + 10.0; - let ty = rect.y + 32.0; - for (pw, t_laid) in &tag_layouts { - if ty + 16.0 > rect.bottom() - 4.0 || tx + pw > rect.right() - 8.0 { - break; - } - let pr = FlowRect::new(tx, ty, *pw, 16.0); - window - .paint_quad(fill(pr.bounds(origin), pill_bg).corner_radii(px(4.0))); - t_laid.paint(point(px(tx + 5.0), px(ty)), window, cx); - tx += pw + 4.0; - } - }, - ); - }); - }, - ) - .absolute() - .left(px(0.0)) - .top(px(0.0)) - .w(px(1.0)) - .h(px(1.0)) - .into_any_element() -} - fn paint_floating_capsule( rect: FlowRect, label: String, @@ -236,6 +125,78 @@ fn paint_glowing_drop_line( } impl PlaygroundView { + fn floating_database_region( + &self, + block_id: &str, + source: FlowRect, + rect: FlowRect, + angle: f32, + ) -> Option { + let body = self.flow_layout()?.block(block_id)?.body.clone(); + Some( + canvas( + |_, _, _| (), + move |_, _, window, cx| { + let matrix = + rotation_matrix_around(rect.x + rect.w * 0.5, rect.y + rect.h * 0.5, angle); + window.with_paint_transformation(matrix, |window| { + window.with_local_paint_mask( + ui::ContentMask { + bounds: rect.bounds(point(px(0.0), px(0.0))), + }, + |window| { + body.paint_content( + point(px(rect.x - source.x), px(rect.y - source.y)), + Default::default(), + window, + cx, + ); + }, + ); + }); + }, + ) + .absolute() + .size_full() + .into_any_element(), + ) + } + + fn paint_calendar_range_outline( + &self, + block_id: &str, + row_id: &str, + window: &Window, + out: &mut Vec, + ) { + let color = self.theme.palette().border; + for hit in self.flow.database_authoring_hits(block_id) { + if matches!(&hit.kind, DatabaseAuthoringHitKind::CalendarDragEventStart { row_id: id, .. } if id == row_id) + && let Some(rect) = + self.database_local_rect_to_screen(block_id, hit.rect, false, window) + { + out.push( + canvas( + |_, _, _| (), + move |_, _, window, _| { + window.paint_quad(quad( + rect.bounds(point(px(0.0), px(0.0))), + px(5.0), + ui::transparent_black(), + px(1.5), + color, + BorderStyle::Dashed, + )); + }, + ) + .absolute() + .size_full() + .into_any_element(), + ); + } + } + } + /// Screen-space overlay elements for active database drags (Kanban / Calendar / Table), /// hover grips & resize guide lines, and 160 ms ease-out post-drop settle transitions. pub(crate) fn database_dnd_overlay_elements( @@ -269,8 +230,6 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen, - card_title, - card_tags, promoted, .. } if promoted => { @@ -329,14 +288,16 @@ impl PlaygroundView { .snapshot("overlay.kanban_drag_ghost", None) .into_any_element(), ); - out.push(paint_floating_kanban_card( - ghost_rect, -3.0, card_title, card_tags, &palette, window, + out.extend(self.floating_database_region( + &block_id, + source_card_rect, + ghost_rect, + -3.0, )); } DatabaseDragState::CalendarReschedule { block_id, - target_day, - span_days, + row_id, source_chip_rect, grab_offset_x, grab_offset_y, @@ -345,52 +306,7 @@ impl PlaygroundView { promoted, .. } if promoted => { - // Source chip 0.5 opacity dim placeholder. - if let Some(src_screen) = self.database_local_rect_to_screen( - &block_id, - source_chip_rect, - false, - window, - ) { - out.push( - div() - .absolute() - .left(px(src_screen.x)) - .top(px(src_screen.y)) - .w(px(src_screen.w)) - .h(px(src_screen.h)) - .rounded(px(4.0)) - .bg(palette.background.opacity(0.52)) - .into_any_element(), - ); - } - // Multi-day target range highlight across target_day .. target_day + span_days. - if span_days > 1 { - let hits = self.flow.database_authoring_hits(&block_id); - for h in hits { - if let DatabaseAuthoringHitKind::CalendarDayDropTarget { day_index } = - h.kind - && day_index > target_day - && day_index < target_day + span_days - && let Some(dr) = self - .database_local_rect_to_screen(&block_id, h.rect, false, window) - { - out.push( - div() - .absolute() - .left(px(dr.x)) - .top(px(dr.y)) - .w(px(dr.w)) - .h(px(dr.h)) - .bg(palette.brand.opacity(0.14)) - .border_1() - .border_color(palette.brand) - .snapshot("overlay.calendar_multiday_drop_highlight", None) - .into_any_element(), - ); - } - } - } + self.paint_calendar_range_outline(&block_id, &row_id, window, &mut out); // Floating event capsule tracking pointer. let ghost_rect = FlowRect::new( (pointer_screen.0 - grab_offset_x).round(), @@ -418,6 +334,11 @@ impl PlaygroundView { window, )); } + DatabaseDragState::CalendarResize { + block_id, row_id, .. + } => { + self.paint_calendar_range_outline(&block_id, &row_id, window, &mut out); + } DatabaseDragState::TableRowReorder { block_id, drop_line_local, @@ -496,14 +417,13 @@ impl PlaygroundView { grab_offset_x, grab_offset_y, pointer_screen, - col_name, promoted, .. } if promoted => { if let Some(src_screen) = self.database_clipped_local_rect_to_screen( &block_id, source_header_rect, - true, + self.table_rect_scrolls(&block_id, source_header_rect), window, ) { out.push( @@ -537,8 +457,8 @@ impl PlaygroundView { let ghost_rect = FlowRect::new( (pointer_screen.0 - grab_offset_x).round(), (pointer_screen.1 - grab_offset_y).round(), - source_header_rect.w.max(80.0), - source_header_rect.h.max(30.0), + source_header_rect.w, + source_header_rect.h, ); out.push( div() @@ -550,15 +470,14 @@ impl PlaygroundView { .snapshot("overlay.table_column_drag_ghost", None) .into_any_element(), ); - out.push(paint_floating_capsule( + if let Some(header) = self.floating_database_region( + &block_id, + source_header_rect, ghost_rect, - col_name, - palette.background_secondary, - palette.brand, - palette.text_primary, - 0.97, - window, - )); + 0.0, + ) { + out.push(header); + } } _ => {} } @@ -574,12 +493,11 @@ impl PlaygroundView { DatabaseSettleKind::KanbanCard { block_id, row_id, - title, - tags, + source, to_rect, .. } => { - let landed_to = self + let landed_source = self .flow .database_authoring_hits(block_id) .iter() @@ -587,10 +505,12 @@ impl PlaygroundView { DatabaseAuthoringHitKind::KanbanCardDragRegion { row_id: rid, .. - } if rid == row_id => self - .database_local_rect_to_screen(block_id, h.rect, true, window), + } if rid == row_id => Some(h.rect), _ => None, }) + .unwrap_or(*source); + let landed_to = self + .database_local_rect_to_screen(block_id, landed_source, true, window) .unwrap_or(*to_rect); out.push( div() @@ -614,13 +534,11 @@ impl PlaygroundView { .snapshot("overlay.kanban_drop_settle", None) .into_any_element(), ); - out.push(paint_floating_kanban_card( + out.extend(self.floating_database_region( + block_id, + landed_source, rect, angle_deg, - title.clone(), - tags.clone(), - &palette, - window, )); } DatabaseSettleKind::CalendarEvent { title, .. } => { diff --git a/blocksuite/crates/playground/src/database_authoring/paint_hover.rs b/blocksuite/crates/playground/src/database_authoring/paint_hover.rs index 4181e0ab9b..1a808a5ed3 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint_hover.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint_hover.rs @@ -144,9 +144,12 @@ impl PlaygroundView { } } DatabaseHoverTargetKind::TableHeader { rect, .. } => { - if let Some(sr) = - self.database_clipped_local_rect_to_screen(block_id, *rect, true, window) - { + if let Some(sr) = self.database_clipped_local_rect_to_screen( + block_id, + *rect, + self.table_rect_scrolls(block_id, *rect), + window, + ) { out.push(paint_hover_fill( sr, 0.0, @@ -224,9 +227,12 @@ impl PlaygroundView { && !row_editing(row_id) { let (peek_local, menu_local) = table_row_ops_rects(*tr); - if let Some(sr) = self - .database_clipped_local_rect_to_screen(block_id, peek_local, true, window) - { + if let Some(sr) = self.database_clipped_local_rect_to_screen( + block_id, + peek_local, + self.table_rect_scrolls(block_id, *tr), + window, + ) { out.push(paint_op_button( sr, IconPaint::from_def(&icons::CENTER_PEEK), @@ -237,7 +243,10 @@ impl PlaygroundView { } if !readonly && let Some(sr) = self.database_clipped_local_rect_to_screen( - block_id, menu_local, true, window, + block_id, + menu_local, + self.table_rect_scrolls(block_id, *tr), + window, ) { out.push(paint_op_button( @@ -400,7 +409,8 @@ impl PlaygroundView { } DatabaseHoverTargetKind::CalendarEvent { event_rect, - can_resize, + start_handle, + end_handle, resize_edge, .. } => { @@ -413,7 +423,7 @@ impl PlaygroundView { palette.brand.opacity(0.18), Some("overlay.calendar_event_hover"), )); - if *can_resize && !readonly && sr.w >= 20.0 { + if !readonly && sr.w >= 20.0 { let start_c = if *resize_edge == Some(false) { palette.brand } else { @@ -424,18 +434,30 @@ impl PlaygroundView { } else { palette.brand.opacity(0.55) }; - out.push(paint_hover_fill( - FlowRect::new(sr.x + 1.0, sr.y + 3.0, 3.0, (sr.h - 6.0).max(4.0)), - 1.5, - start_c, - Some("overlay.calendar_event_resize_start"), - )); - out.push(paint_hover_fill( - FlowRect::new(sr.right() - 4.0, sr.y + 3.0, 3.0, (sr.h - 6.0).max(4.0)), - 1.5, - end_c, - Some("overlay.calendar_event_resize_end"), - )); + for (enabled, left, color, id) in [ + ( + *start_handle, + !window.layout_direction().is_rtl(), + start_c, + "overlay.calendar_event_resize_start", + ), + ( + *end_handle, + window.layout_direction().is_rtl(), + end_c, + "overlay.calendar_event_resize_end", + ), + ] { + if enabled { + let x = if left { sr.x + 1.0 } else { sr.right() - 4.0 }; + out.push(paint_hover_fill( + FlowRect::new(x, sr.y + 3.0, 3.0, (sr.h - 6.0).max(4.0)), + 1.5, + color, + Some(id), + )); + } + } } } } @@ -555,7 +577,7 @@ impl PlaygroundView { if let Some(sr) = self.database_local_rect_to_screen( block_id, FlowRect::new(guide_x, top, 2.0, guide_h), - true, + handle.scrolls_x, window, ) { out.push( diff --git a/blocksuite/crates/playground/src/database_authoring/pointer.rs b/blocksuite/crates/playground/src/database_authoring/pointer.rs index 7765a3922c..f235fd5df7 100644 --- a/blocksuite/crates/playground/src/database_authoring/pointer.rs +++ b/blocksuite/crates/playground/src/database_authoring/pointer.rs @@ -10,6 +10,38 @@ use super::DatabaseDragState; use crate::PlaygroundView; impl PlaygroundView { + pub(crate) fn scroll_database_panel( + &mut self, + dy: f32, + height: f32, + cx: &mut Context, + ) -> bool { + let Some(block_id) = self.active_database_authoring_block() else { + return false; + }; + let state = self.flow.database_state.state_for(&block_id); + let Some(panel) = state.authoring.toolbar_panel else { + return self.scroll_open_select_popover(dy, cx); + }; + if panel == database::ActiveToolbarPanel::Filter { + return false; + } + let Some(db) = self.database_snapshot_data(&block_id) else { + return false; + }; + let max = (36.0 + 28.0 * database::panel_row_count(db.columns.len(), panel) as f32 + - height) + .max(0.0); + let auth = self.flow.database_state.authoring_mut(&block_id); + let mut axis = blocksuite_editor::scroll::ScrollAxis::new(auth.toolbar_scroll_y, max); + if axis.apply(dy) { + auth.toolbar_scroll_y = axis.offset; + cx.notify(); + return true; + } + false + } + /// Continue an active database column resize, progress scrub, or calendar reschedule drag, /// or update desktop Calendar day-cell hover (`+` button visibility) when idle. pub(crate) fn database_authoring_mouse_move( @@ -48,7 +80,11 @@ impl PlaygroundView { .flow_layout() .and_then(|l| l.block(&block_id).and_then(|b| b.body.code_scroll)) .map_or(0.0, |cs| self.overlays.code_scroll_x_for(&block_id, cs)); - let cur_x = local_x + scroll_x; + let frozen = self.flow.database_authoring_hits(&block_id).iter().any(|hit| { + !hit.scrolls_x && matches!(&hit.kind, + DatabaseAuthoringHitKind::ResizeColumnHandle { column_id: id, .. } if *id == column_id) + }); + let cur_x = if frozen { local_x } else { local_x + scroll_x }; let next_w = (start_width + (cur_x - start_x)).max(65.0).round() as i32; self.flow .database_state @@ -80,7 +116,12 @@ impl PlaygroundView { } else { 0.0 }; - let value = database::progress_from_bar_x(local_x + scroll_x, bar_x, bar_w); + let x = if self.database_record_sheet.is_some() { + pos_x + } else { + local_x + scroll_x + }; + let value = database::progress_from_bar_x(x, bar_x, bar_w); self.flow .database_state .authoring_mut(&block_id) @@ -97,7 +138,7 @@ impl PlaygroundView { row_id, origin_day, target_day, - span_days, + grab_day_offset, source_chip_rect, grab_offset_x, grab_offset_y, @@ -112,7 +153,7 @@ impl PlaygroundView { row_id, origin_day, target_day, - span_days, + grab_day_offset, source_chip_rect, grab_offset_x, grab_offset_y, @@ -151,13 +192,13 @@ impl PlaygroundView { } _ => None, }); - let next_day = hovered_day.unwrap_or(target_day); + let next_day = hovered_day.map_or(target_day, |day| day - grab_day_offset); self.database_drag = Some(DatabaseDragState::CalendarReschedule { block_id: block_id.clone(), row_id: row_id.clone(), origin_day, target_day: next_day, - span_days, + grab_day_offset, source_chip_rect, grab_offset_x, grab_offset_y, @@ -167,6 +208,10 @@ impl PlaygroundView { promoted: true, }); if !promoted || next_day != target_day { + self.flow + .database_state + .authoring_mut(&block_id) + .calendar_resize_end = None; self.flow .database_state .authoring_mut(&block_id) diff --git a/blocksuite/crates/playground/src/database_authoring/popover_layout.rs b/blocksuite/crates/playground/src/database_authoring/popover_layout.rs new file mode 100644 index 0000000000..09ab312898 --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/popover_layout.rs @@ -0,0 +1,81 @@ +use crate::PlaygroundView; +use blocksuite_editor::{ + block_flow::FlowLayout, + database::{self, DatabasePopoverOverlay, layout_database_popover_overlay}, +}; +use blocksuite_playground_doc::read::BlockContent; +use ui::Window; +impl PlaygroundView { + /// Compute the active screen-space [`DatabasePopoverOverlay`] (`ColumnMenu`, `SelectPicker`, + /// or `ToolbarPanel`) if any writable database block currently has one open. + pub(crate) fn database_popover_overlay( + &self, + layout: &FlowLayout, + window: &Window, + ) -> Option<(String, DatabasePopoverOverlay)> { + 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)?; + let data = + self.snapshot + .as_ref() + .and_then(|snap| match &snap.block(&block_id)?.content { + BlockContent::Database(db) => Some(db), + _ => None, + })?; + let (_, canvas_size) = self.canvas_rect(window); + let topbar = self.topbar_height(); + let geom = self.current_page_geometry(f32::from(canvas_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 + block.y - paint_scroll_y); + let scroll_x = block + .body + .code_scroll + .map_or(0.0, |cs| self.overlays.code_scroll_x_for(&block_id, cs)); + let record_anchor = self.database_record_sheet.as_ref().and_then(|sheet| { + if sheet.block_id != block_id { + return None; + } + let slot = if ui_state.authoring.toolbar_panel + == Some(database::ActiveToolbarPanel::NewProperty) + { + super::RecordSlot::AddProperty + } else { + let ed = ui_state.authoring.active_cell.as_ref()?; + if ed.row_id != sheet.row_id { + return None; + } + super::RecordSlot::Field(&ed.column_id) + }; + let rect = self.record_value_rect(slot, window)?; + Some(database::DatabasePopoverAnchor { + rect: rect.translated(-block_screen_origin.0, -block_screen_origin.1), + scrolls_x: false, + }) + }); + let anchor = record_anchor.or_else(|| 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, + self.theme, + window.layout_direction(), + self.form_factor, + self.is_database_write_readonly(), + self.flow.database_state.clock_ms, + &offset_at, + &self.page_titles, + window, + )?; + Some((block_id, overlay)) + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/record_title.rs b/blocksuite/crates/playground/src/database_authoring/record_title.rs index c80905773b..9413d15eb7 100644 --- a/blocksuite/crates/playground/src/database_authoring/record_title.rs +++ b/blocksuite/crates/playground/src/database_authoring/record_title.rs @@ -17,6 +17,21 @@ use super::{inline::DatabaseInlineTarget, paint::paint_inline_box_elements}; const RECORD_TITLE_FONT: (f32, f32) = (16.0, 600.0); impl PlaygroundView { + pub(crate) fn record_input_active(&self) -> bool { + self.database_record_sheet.as_ref().is_some_and(|sheet| { + self.database_input + .as_ref() + .is_some_and(|input| input.target.block_id() == sheet.block_id) + || self + .flow + .database_state + .state_for(&sheet.block_id) + .authoring + .toolbar_panel + == Some(database::ActiveToolbarPanel::NewProperty) + }) + } + pub(crate) fn record_title_editing(&self) -> bool { self.database_input .as_ref() @@ -42,6 +57,7 @@ impl PlaygroundView { return; }; if !self.record_title_editing() { + self.finish_record_edit(Some(window), cx); let row_exists = self .database_snapshot_data(&block_id) .is_some_and(|db| db.rows.iter().any(|r| r.row_id == row_id)); @@ -73,19 +89,38 @@ impl PlaygroundView { } } - /// End an edit of the record peek title, committing an IME composition in progress. Returns - /// whether an edit was in progress. - pub(crate) fn commit_record_title_edit( + pub(crate) fn finish_record_edit( &mut self, window: Option<&mut Window>, cx: &mut Context, - ) -> bool { - if !self.record_title_editing() { - return false; + ) { + if let Some(sheet) = &self.database_record_sheet + && self + .flow + .database_state + .state_for(&sheet.block_id) + .authoring + .toolbar_panel + == Some(database::ActiveToolbarPanel::NewProperty) + { + self.flow + .database_state + .authoring_mut(&sheet.block_id) + .toolbar_panel = None; } - self.finish_inline_targets(InlineTargetEnd::CommitPreedit, window, Some(cx)); - cx.notify(); - true + if self.database_record_sheet.is_some() && self.database_input.is_some() { + self.finish_inline_targets(InlineTargetEnd::CommitPreedit, window, Some(cx)); + } + } + + pub(crate) fn record_field_input_active(&self, column: &str) -> bool { + self.database_input + .as_ref() + .is_some_and(|s| match &s.target { + DatabaseInlineTarget::LiveRichCell { column_id, .. } + | DatabaseInlineTarget::ScalarCell { column_id, .. } => column_id == column, + _ => false, + }) } /// Screen box and font of the title field of the open record peek. @@ -104,14 +139,17 @@ impl PlaygroundView { window: &Window, cx: &Context, ) -> Vec { - let Some(session) = self - .database_input - .as_ref() - .filter(|_| self.record_title_editing()) - else { + let Some(session) = self.database_input.as_ref().filter(|s| { + !matches!( + s.target, + DatabaseInlineTarget::SelectFilter { .. } + | DatabaseInlineTarget::ColumnRename { .. } + | DatabaseInlineTarget::FilterValue { .. } + ) + }) else { return Vec::new(); }; - let Some((rect, (font_size, weight))) = self.record_title_screen_box(window) else { + let Some((rect, (font_size, weight))) = self.database_inline_screen_box(window) else { return Vec::new(); }; paint_inline_box_elements( @@ -123,7 +161,15 @@ impl PlaygroundView { weight, palette, self.caret_blink_alpha(self.now_ms(cx)), - Some("overlay.database_record_sheet.title_caret"), + Some(match session.target { + DatabaseInlineTarget::RecordTitle { .. } => { + "overlay.database_record_sheet.title_caret" + } + DatabaseInlineTarget::RecordBody { .. } => { + "overlay.database_record_sheet.note_caret" + } + _ => "overlay.database_record_sheet.property_caret", + }), window, ) } diff --git a/blocksuite/crates/playground/src/database_authoring/tests_hover_and_cursors.rs b/blocksuite/crates/playground/src/database_authoring/tests_hover_and_cursors.rs index 4a5cd41d88..42de89d402 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_hover_and_cursors.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_hover_and_cursors.rs @@ -320,14 +320,19 @@ fn database_hover_cursors_popover_isolation_and_desktop_peek_and_row_ops() { Some(CursorStyle::PointingHand) ); if let Some(er) = event_rect { - let (esx, esy) = to_screen(er.right() - 2.0, er.y + er.h * 0.5, false); - mouse_move(&headless, esx, esy, false); - tick(); - assert_eq!( - app.update(|cx| win.read(cx).unwrap().database_hover_cursor()), - Some(CursorStyle::ResizeLeftRight), - "hovering Calendar event right 6px handle must show ResizeLeftRight" - ); + for (x, cursor) in [ + (er.x + 2.0, CursorStyle::ResizeLeftRight), + (er.right() - 2.0, CursorStyle::OpenHand), + ] { + let (esx, esy) = to_screen(x, er.y + er.h * 0.5, false); + mouse_move(&headless, esx, esy, false); + tick(); + assert_eq!( + app.update(|cx| win.read(cx).unwrap().database_hover_cursor()), + Some(cursor), + "only the start of the first week segment is a date endpoint" + ); + } } // Check CalendarToday hidden when on current month. 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 e5cad590bd..943319495c 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 @@ -724,3 +724,64 @@ fn selection_move_tracks_remote_insert_and_remote_col_type_change_invalidates_ed "stale rich-text editor must not overwrite collaborator's numeric cell value 42" ); } + +#[test] +fn folded_type_picker_padding_shields_the_delete_column_action() { + use blocksuite_editor::database::{DatabaseAuthoringHitKind as Hit, PopoverTarget}; + let (state, db_id) = seed_authoring_doc(false); + let (platform, app, win, headless) = + open_authoring_window(360, 760, PlaygroundOptions::default(), state); + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.update_database_authoring( + &db_id, + |a| { + a.column_menu = Some(ColumnMenuState { + column_id: "col-note".into(), + rename_draft: "Notes".into(), + type_submenu_open: true, + }); + }, + cx, + ); + }) + .unwrap() + }); + platform.run_until_parked(); + headless.request_frame(); + platform.run_until_parked(); + app.update(|cx| { + win.update(cx, |v, w, cx| { + let (_, panel) = v + .database_popover_overlay(&v.flow_layout().unwrap(), w) + .unwrap(); + let submenu = panel.submenu_bounds.unwrap(); + let delete = panel + .hits + .iter() + .find(|h| matches!(h.kind, Hit::ColumnMenuDelete { .. })) + .unwrap() + .rect; + let x = submenu.right() - 2.0; + let y = delete.y + delete.h * 0.5; + assert!( + delete.contains(x, y) && submenu.contains(x, y), + "parent {delete:?} submenu {submenu:?}" + ); + assert_eq!(panel.target_at(x, y), Some(PopoverTarget::Background)); + v.update_database_hover(Some((x, y)), w, cx); + assert_eq!(v.database_hover.cursor, Some(ui::CursorStyle::Arrow)); + let before = v.page().unwrap().encode_state_vector_v1().unwrap(); + assert!(v.try_click_database_popover(x, y, w, cx)); + assert_eq!(v.page().unwrap().encode_state_vector_v1().unwrap(), before); + assert!( + v.database_snapshot_data(&db_id) + .unwrap() + .columns + .iter() + .any(|c| c.id == "col-note") + ); + }) + .unwrap() + }); +} diff --git a/blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit.rs b/blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit/mod.rs similarity index 62% rename from blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit.rs rename to blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit/mod.rs index eef1a5802c..eacca0e232 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit/mod.rs @@ -18,7 +18,7 @@ use ui::{ use crate::{HOME_PAGE_ID, PlaygroundOptions, PlaygroundTheme, PlaygroundView}; use super::{ - inline::DatabaseInlineTarget, tests_inline_and_overflow::build_roadmap_doc, + RecordSlot, inline::DatabaseInlineTarget, tests_inline_and_overflow::build_roadmap_doc, tests_inline_and_popovers::open_authoring_window, }; @@ -103,7 +103,7 @@ impl Fixture { .expect("r1 capsule"); point( px(geom.column_x + bx + rect.x + 18.0), - px(crate::TOPBAR_HEIGHT + by + rect.y + rect.h * 0.5 - v.scroll_y), + px(v.topbar_height() + by + rect.y + rect.h * 0.5 - v.scroll_y), ) }); f @@ -494,3 +494,280 @@ fn record_peek_title_typing_merges_with_a_peer_edit_and_undoes_only_the_local_ty "one undo removes only the local typing" ); } + +impl Fixture { + fn edit_note(&self) { + self.click( + self.snapshot_bounds("overlay.database_record_sheet.note.0") + .unwrap() + .center(), + 1, + ); + } + + fn receive_update(&self, update: &[u8]) { + self.update(|v, _, cx| { + v.page_mut() + .unwrap() + .apply_remote_update_v1(update) + .unwrap(); + v.refresh_document(); + cx.notify(); + }); + } + + fn create_note(&self) -> String { + self.click(self.capsule, 1); + self.edit_note(); + self.type_text("abcdef"); + self.update(|v, _, _| { + v.snapshot.as_ref().unwrap().block("r1").unwrap().children[0] + .id + .clone() + }) + } +} + +#[test] +fn record_note_selection_and_composition_follow_a_remote_prefix() { + for compose in [false, true] { + let f = Fixture::open(); + let child = f.create_note(); + f.key("enter"); + f.edit_note(); + f.update(|v, w, cx| { + assert!(v.database_authoring_input_edit(w, cx, |input| { + input.input.select(1..2); + None + })); + if compose { + v.replace_and_mark_text_in_range(None, "X", None, w, cx); + } + }); + let mut peer = f.peer(); + let sv = peer.encode_state_vector_v1().unwrap(); + peer.apply_text_delta( + &child, + "prop:text", + &[y_octo::TextDeltaOp::Insert { + insert: y_octo::TextInsert::Text("PEER ".into()), + format: None, + }], + 900, + ) + .unwrap(); + f.receive_update(&peer.encode_diff_v1(&sv).unwrap()); + if compose { + f.update(|v, w, cx| v.unmark_text(w, cx)); + } else { + f.type_text("X"); + } + let reopened_text = || f.peer().read_editable_text(&child).unwrap().0.plain; + assert_eq!(reopened_text(), "PEER aXcdef"); + f.undo_once(); + assert_eq!(reopened_text(), "PEER abcdef"); + } +} + +#[test] +fn remote_note_deletion_discards_typing_and_composition_on_both_replicas() { + for reopen in [false, true] { + for compose in [false, true] { + let f = Fixture::open(); + let child = f.create_note(); + if reopen { + f.key("enter"); + f.edit_note(); + } + if compose { + f.update(|v, w, cx| v.replace_and_mark_text_in_range(None, "L", None, w, cx)); + } + let mut peer = f.peer(); + let sv = peer.encode_state_vector_v1().unwrap(); + peer.delete_block_subtree("r1", &child, 900).unwrap(); + f.receive_update(&peer.encode_diff_v1(&sv).unwrap()); + let before = f.peer().encode_update_v1().unwrap(); + if compose { + f.update(|v, w, cx| v.unmark_text(w, cx)); + } else { + f.type_text("L"); + } + assert_eq!(f.peer().encode_update_v1().unwrap(), before); + f.update(|v, _, _| { + assert!(v.database_record_sheet().unwrap().note_editing.is_none()); + assert!(v.database_input.is_none()); + }); + let local = f.peer(); + peer.apply_remote_update_v1(&local.encode_update_v1().unwrap()) + .unwrap(); + for replica in [local, peer] { + let mut cold = PageDocSession::new(HOME_PAGE_ID, 91).unwrap(); + cold.apply_remote_update_v1(&replica.encode_update_v1().unwrap()) + .unwrap(); + assert!( + cold.inner() + .get_map_value(cold.blocks_target(), &child) + .unwrap() + .is_none() + ); + assert!( + cold.read_page_snapshot() + .unwrap() + .block("r1") + .unwrap() + .children + .is_empty() + ); + } + } + } +} + +#[test] +fn record_note_typing_and_navigation_use_the_selected_row() { + let f = Fixture::open(); + f.click(f.capsule, 1); + let target = |id: &str| { + f.snapshot_bounds(&format!("overlay.database_record_sheet.{id}")) + .unwrap() + .center() + }; + f.click(target("note.0"), 1); + f.type_text("Release "); + f.type_text("notes"); + f.key("enter"); + let notes = || { + f.update(|v, _, _| { + let row = v.snapshot.as_ref().unwrap().block("r1").unwrap(); + row.children + .iter() + .filter_map(|n| match &n.content { + blocksuite_playground_doc::read::BlockContent::Paragraph { text, .. } => { + Some(text.plain.clone()) + } + _ => None, + }) + .collect::>() + }) + }; + assert_eq!(notes(), ["Release notes"]); + f.undo_once(); + assert!(notes().is_empty()); + for (button, row) in [("next", "r2"), ("previous", "r1")] { + f.click(target(button), 1); + assert_eq!( + f.update(|v, _, _| v.database_record_sheet().unwrap().row_id.clone()), + row + ); + } +} + +#[test] +fn calendar_drag_and_resize_preview_matches_committed_week_segments_and_undo() { + for (segment, at, target_day, expected, timed) in [ + (1, 0.50, 20525, (20523, 20526), false), + (0, 0.01, 20517, (20517, 20522), false), + (1, 0.99, 20528, (20519, 20528), false), + (0, 0.50, 20523, (20523, 20523), true), + ] { + let f = Fixture::open(); + let times = (1_772_875_800_000, 1_772_881_200_000); + f.update(|v, _, cx| { + v.set_calendar_clock(Some(std::rc::Rc::new(|| (1_772_841_600_000, 0)))); + if timed { + let page = v.page_mut().unwrap(); + for (column, ms) in [("c-due", times.0), ("c-end", times.1)] { + page.set_database_cell_value( + &f.db_id, + "r1", + column, + blocksuite_playground_doc::schema::DatabaseCellSpec::Integer(ms), + 100, + ) + .unwrap(); + } + page.stop_capturing().unwrap(); + } + v.refresh_document(); + cx.notify(); + }); + let reopened_times = || { + let snap = f.peer().read_page_snapshot().unwrap(); + let blocksuite_playground_doc::read::BlockContent::Database(db) = + &snap.block(&f.db_id).unwrap().content + else { + panic!("expected database") + }; + let ms = |col: &str| db.cells[&("r1".into(), col.into())].as_i64().unwrap(); + (ms("c-due"), ms("c-end")) + }; + let chips = || { + f.update(|v, _, _| { + v.database_authoring_hits(&f.db_id) + .iter() + .filter_map(|h| match &h.kind { + DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, .. } + if row_id == "r1" => + { + Some(h.rect) + } + _ => None, + }) + .collect::>() + }) + }; + let original = chips(); + let (start,end)=f.update(|v,w,_|{ + let r=v.database_local_rect_to_screen(&f.db_id,original[segment],false,w).unwrap(); + let pt=point(px(r.x+r.w*at),px(r.y+r.h*0.5)); + let dest=v.database_authoring_hit_screen_center(&f.db_id,w,|k|matches!(k,DatabaseAuthoringHitKind::CalendarDayDropTarget {day_index} if *day_index==target_day)).unwrap(); + (pt,point(px(dest.0),px(dest.1))) + }); + let move_to = |position, pressed_button| { + f.headless + .dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { + position, + pressed_button, + modifiers: Modifiers::default(), + })); + f.tick(); + }; + move_to(start, None); + f.headless + .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { + button: MouseButton::Left, + position: start, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + f.tick(); + move_to(end, Some(MouseButton::Left)); + let preview = chips(); + assert_ne!(preview, original); + let range = || f.update(|v, _, _| v.calendar_event_range(&f.db_id, "r1").unwrap()); + assert_eq!(range(), (20519, if timed { 20519 } else { 20522 })); + f.headless + .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { + button: MouseButton::Left, + position: end, + modifiers: Modifiers::default(), + click_count: 1, + })); + f.tick(); + assert_eq!(range(), expected); + assert_eq!(chips(), preview); + if timed { + let (a, b) = reopened_times(); + assert_eq!(b - a, 5_400_000); + assert_eq!((a, b), (times.0 + 4 * 86_400_000, times.1 + 4 * 86_400_000)); + } + f.undo_once(); + if timed { + assert_eq!(reopened_times(), times); + } + assert_eq!(chips(), original); + } +} + +mod properties; diff --git a/blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit/properties.rs b/blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit/properties.rs new file mode 100644 index 0000000000..f890be870a --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/tests_record_peek_edit/properties.rs @@ -0,0 +1,326 @@ +use super::*; + +#[test] +fn record_select_option_menu_preserves_cell_and_chip_removal_preserves_schema() { + use DatabaseAuthoringHitKind as Hit; + let f = Fixture::open(); + f.click(f.capsule, 1); + let point_for = |pred: fn(&Hit) -> bool| { + f.update(|v, w, _| { + let layout = v.flow_layout().unwrap(); + let (_, panel) = v.database_popover_overlay(&layout, w).unwrap(); + let hit = panel.hits.iter().find(|h| pred(&h.kind)).unwrap(); + point( + px(hit.rect.x + hit.rect.w * 0.5), + px(hit.rect.y + hit.rect.h * 0.5), + ) + }) + }; + let field = f.update(|v, w, _| { + v.record_value_rect(RecordSlot::Field("c-status"), w) + .unwrap() + }); + f.click(point(px(field.x + 20.0), px(field.y + field.h * 0.5)), 1); + let options = || { + f.update(|v, _, _| { + v.database_snapshot_data(&f.db_id) + .unwrap() + .columns + .into_iter() + .find(|c| c.id == "c-status") + .unwrap() + .select_options() + }) + }; + let selected = || { + f.update(|v, _, _| { + v.database_snapshot_data(&f.db_id) + .unwrap() + .cells + .get(&("r1".into(), "c-status".into())) + .map(DatabaseCellValue::as_string_list) + .unwrap_or_default() + }) + }; + let original = options(); + let menu = point_for(|k| matches!(k,Hit::SelectOptionMenu{option_id} if option_id=="opt-todo")); + f.click(menu, 1); + f.update(|v, w, _| { + let (_, panel) = v + .database_popover_overlay(&v.flow_layout().unwrap(), w) + .unwrap(); + assert_eq!( + panel + .hits + .iter() + .filter(|h| matches!(h.kind, Hit::SelectSaveOption { color: Some(_) })) + .count(), + 11 + ); + }); + f.key("escape"); + assert!(f.sheet_open()); + assert!(f.update(|v, _, _| { + v.flow + .database_state + .state_for(&f.db_id) + .authoring + .option_menu + .is_none() + })); + f.key("escape"); + assert!(f.sheet_open()); + assert!(f.snapshot_bounds("overlay.database_popover").is_none()); + f.click(point(px(field.x + 20.0), px(field.y + field.h * 0.5)), 1); + f.click(menu, 1); + f.update(|v, w, cx| v.replace_text_in_range(Some(0..4), "Ready", w, cx)); + f.click( + point_for(|k| matches!(k, Hit::SelectSaveOption { color: Some(c) } if c.contains("green"))), + 1, + ); + assert_eq!(options()[0].value, "Ready"); + assert_ne!(options()[0].color, original[0].color); + assert_eq!(selected(), ["opt-todo"]); + f.undo_once(); + assert_eq!(options(), original); + f.click( + point_for(|k| matches!(k,Hit::SelectToggleOption{option_id,..} if option_id=="opt-todo")), + 1, + ); + assert!(selected().is_empty()); + assert_eq!(options(), original); + f.undo_once(); + assert_eq!(selected(), ["opt-todo"]); +} + +#[test] +fn toolbar_field_lists_reach_the_last_column_by_wheel() { + use DatabaseAuthoringHitKind as Hit; + let f = Fixture::open(); + f.update(|v, _, cx| { + let page = v.state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + for i in 0..16 { + page.add_database_column( + &f.db_id, + None, + DatabaseColumnSpec { + id: format!("extra-{i}"), + column_type: "number".into(), + name: format!("Extra {i}"), + data: json!({}), + }, + None, + 100 + i, + ) + .unwrap(); + } + v.refresh_document(); + v.set_database_active_view(&f.db_id, "v-table", cx); + }); + for (idx, button) in [ + Hit::ToolbarToggleSort, + Hit::ToolbarToggleGroupBy, + Hit::ToolbarProperties, + ] + .into_iter() + .enumerate() + { + let center = f.update(|v, w, _| { + v.database_authoring_hit_screen_center(&f.db_id, w, |k| *k == button) + .unwrap() + }); + f.click(point(px(center.0), px(center.1)), 1); + let panel = || { + f.update(|v, w, _| { + v.database_popover_overlay(&v.flow_layout().unwrap(), w) + .unwrap() + .1 + }) + }; + let has_last = |h: &Hit| match h { + Hit::ToolbarAddOrFlipSort { column_id } if idx == 0 => column_id == "extra-15", + Hit::ToolbarSetGroupBy { + column_id: Some(column_id), + } if idx == 1 => column_id == "extra-15", + Hit::SetColumnHidden { column_id, .. } if idx == 2 => column_id == "extra-15", + _ => false, + }; + let before = panel(); + assert!(!before.hits.iter().any(|h| has_last(&h.kind))); + f.headless + .dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(before.bounds.x + 20.0), px(before.bounds.y + 40.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(-1000.0))), + modifiers: Modifiers::default(), + touch_phase: TouchPhase::Moved, + source: ScrollSource::Pointer, + })); + f.tick(); + assert!(panel().hits.iter().any(|h| has_last(&h.kind)), "{button:?}"); + f.key("escape"); + } +} + +#[test] +fn record_progress_drag_previews_without_writes_until_release() { + let f = Fixture::open(); + f.update(|v, _, cx| { + let page = v.state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.add_database_column( + &f.db_id, + None, + DatabaseColumnSpec { + id: "progress".into(), + column_type: "progress".into(), + name: "Progress".into(), + data: json!({}), + }, + None, + 100, + ) + .unwrap(); + page.stop_capturing().unwrap(); + v.refresh_document(); + cx.notify(); + }); + f.click(f.capsule, 1); + let rect = f.update(|v, w, _| { + v.record_value_rect(RecordSlot::Field("progress"), w) + .unwrap() + }); + let pos = |fraction: f32| { + point( + px(rect.x + (rect.w - 46.0) * fraction), + px(rect.y + rect.h * 0.5), + ) + }; + let sv = f.state_vector(); + f.headless + .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { + button: MouseButton::Left, + position: pos(0.2), + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + f.tick(); + f.headless + .dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { + position: pos(0.8), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + })); + f.tick(); + assert_eq!(f.state_vector(), sv); + let preview = f.update(|v, _, _| { + v.flow + .database_state + .state_for(&f.db_id) + .authoring + .progress_preview + .unwrap() + .value + }); + assert_eq!(preview, 80); + f.headless + .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { + button: MouseButton::Left, + position: pos(0.8), + modifiers: Modifiers::default(), + click_count: 1, + })); + f.tick(); + let value = || { + f.update(|v, _, _| { + v.database_snapshot_data(&f.db_id) + .unwrap() + .cells + .get(&("r1".into(), "progress".into())) + .and_then(DatabaseCellValue::as_i64) + }) + }; + assert_eq!(value(), Some(preview)); + f.undo_once(); + assert_eq!(value(), None); +} + +#[test] +fn scrolled_table_hits_stop_at_the_frozen_title_boundary() { + let f = Fixture::open(); + f.update(|v, _, cx| v.set_database_active_view(&f.db_id, "v-table", cx)); + f.update(|v, _, cx| v.scroll_database_x(&f.db_id, 160.0, cx)); + for (inset, expected) in [(-110.0, "title"), (12.0, "c-status")] { + let target=f.update(|v,w,_|{ + let layout=v.flow_layout().unwrap(); + let scroll=layout.block(&f.db_id).unwrap().body.code_scroll.unwrap(); + assert!(v.overlays.code_scroll_x_for(&f.db_id,scroll)>60.0); + let cell=v.database_authoring_hits(&f.db_id).iter().find(|h|matches!(&h.kind,DatabaseAuthoringHitKind::EditCell {row_id,column_id,..} if row_id=="r1" && column_id=="title")).unwrap(); + assert!(!cell.scrolls_x); + let rect=v.database_local_rect_to_screen(&f.db_id,cell.rect,false,w).unwrap(); + point(px(rect.x+scroll.area.x-cell.rect.x+inset),px(rect.y+rect.h*0.5)) + }); + f.click(target, 1); + assert_eq!( + f.update(|v, _, _| v + .flow + .database_state + .state_for(&f.db_id) + .authoring + .active_cell + .unwrap() + .column_id), + expected + ); + f.key("escape"); + } +} + +#[test] +fn record_add_property_creates_the_chosen_type_in_one_undo_step() { + let f = Fixture::open(); + f.click(f.capsule, 1); + let before = f.state_vector(); + let columns = || f.update(|v, _, _| v.database_snapshot_data(&f.db_id).unwrap().columns); + let original = columns(); + for commit in [false, true] { + let add = f + .snapshot_bounds("overlay.database_record_sheet.add_property") + .unwrap(); + f.click(add.center(), 1); + let number = f.update(|v, w, _| { + let (_, panel) = v + .database_popover_overlay(&v.flow_layout().unwrap(), w) + .unwrap(); + let types: Vec<_> = panel + .hits + .iter() + .filter_map(|h| match &h.kind { + DatabaseAuthoringHitKind::CreateProperty { column_type } => { + Some((column_type.as_str(), h.rect)) + } + _ => None, + }) + .collect(); + assert_eq!(types.len(), 8); + let rect = types.iter().find(|(kind, _)| *kind == "number").unwrap().1; + point(px(rect.x + 12.0), px(rect.y + rect.h * 0.5)) + }); + assert_eq!(f.state_vector(), before); + if commit { + f.click(number, 1); + let now = columns(); + assert_eq!(now.len(), original.len() + 1); + assert!( + now.iter().any( + |c| c.column_type == "number" && !original.iter().any(|old| old.id == c.id) + ) + ); + f.undo_once(); + assert_eq!(columns(), original); + } else { + f.key("escape"); + assert!(f.snapshot_bounds("overlay.database_popover").is_none()); + } + assert!(f.sheet_open()); + } +} diff --git a/blocksuite/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs index 61d068aba2..76547b0ba4 100644 --- a/blocksuite/crates/playground/src/overlays/view.rs +++ b/blocksuite/crates/playground/src/overlays/view.rs @@ -693,7 +693,7 @@ impl PlaygroundView { // closes the record sheet. if self.database_record_sheet.is_some() && event.keystroke.key.as_str() == "escape" - && !self.record_title_editing() + && !self.record_input_active() { self.close_database_record_sheet(cx); return true; diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/database.rs b/blocksuite/crates/playground/src/overlays/view_mobile/database.rs index 558d48a1dc..44d9d4eeee 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/database.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/database.rs @@ -562,7 +562,11 @@ impl PlaygroundView { } } - fn resolve_database_calendar_month(&self, block_id: &str, cx: &Context) -> (i32, u32) { + pub(crate) fn resolve_database_calendar_month( + &self, + block_id: &str, + cx: &Context, + ) -> (i32, u32) { let ui_state = self.flow.database_state.state_for(block_id); let offset_at = self.utc_offset_resolver(); let (now_ms, _) = self.local_calendar_now(cx); diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/editing.rs b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/editing.rs new file mode 100644 index 0000000000..4965cd4939 --- /dev/null +++ b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/editing.rs @@ -0,0 +1,300 @@ +use crate::{ + PlaygroundView, + database_authoring::{RecordParagraph, RecordSlot}, +}; +use blocksuite_editor::{ + block_flow::FlowRect, + database::{self, DatabaseAuthoringHit, DatabaseAuthoringHitKind as Hit}, +}; +use blocksuite_playground_doc::{ + read::BlockContent, + schema::{BlockSpec, ParagraphType}, +}; +use ui::{Context, Pixels, Point, Window}; + +impl PlaygroundView { + pub(crate) fn record_value_rect(&self, slot: RecordSlot, window: &Window) -> Option { + let p = self.prepare_record_sheet(&self.theme.palette(), window)?; + let body_top = p.sheet_top + p.sheet_h - p.body_viewport_h; + let mut y = body_top - p.scroll_y + p.title_card_h + 10.0; + for (hidden, rows) in [(false, &p.visible_rows), (true, &p.hidden_rows)] { + if hidden { + if rows.is_empty() { + continue; + } + y += 46.0; + if !p.hidden_expanded { + continue; + } + y += 10.0; + } + for row in rows { + if matches!(slot, RecordSlot::Field(id) if row.col_id == id) { + let rect = FlowRect::new( + p.sheet_left + 129.0, + y + 3.0, + p.value_w, + (row.row_h - 6.0).max(1.0), + ); + return (rect.bottom() > body_top && rect.y < p.sheet_top + p.sheet_h) + .then_some(rect); + } + y += row.row_h; + } + } + if matches!(slot, RecordSlot::AddProperty) { + return Some(FlowRect::new( + p.sheet_left + 17.0, + y + 10.0, + p.sheet_w - 34.0, + 34.0, + )); + } + y += 54.0; + for (child, _, height) in p.notes { + if matches!(slot, RecordSlot::Note(id) if child == id) { + let rect = FlowRect::new(p.sheet_left + 17.0, y, p.sheet_w - 34.0, height); + return (rect.bottom() > body_top && rect.y < p.sheet_top + p.sheet_h) + .then_some(rect); + } + y += height + 10.0; + } + None + } + + pub(super) fn record_field_press( + &mut self, + column: &str, + pos: Point, + window: &mut Window, + cx: &mut Context, + ) { + if self.is_database_write_readonly() { + return; + } + let Some((block, row)) = self + .database_record_sheet + .as_ref() + .map(|s| (s.block_id.clone(), s.row_id.clone())) + else { + return; + }; + let Some(col) = self + .database_snapshot_data(&block) + .and_then(|db| db.columns.into_iter().find(|c| c.id == column)) + else { + return; + }; + let Some(rect) = self.record_value_rect(RecordSlot::Field(column), window) else { + return; + }; + if matches!( + col.column_type.as_str(), + "created-time" | "last-edited-time" | "image" | "checkbox" + ) { + return; + } + self.finish_record_edit(Some(window), cx); + let kind = if col.column_type == "progress" { + Hit::SetProgress { + row_id: row, + column_id: col.id, + } + } else { + Hit::EditCell { + row_id: row, + column_id: col.id, + col_type: col.column_type, + } + }; + let hit = DatabaseAuthoringHit { + rect: FlowRect::new( + rect.x, + rect.y, + if matches!(kind, Hit::SetProgress { .. }) { + (rect.w - 46.0).max(1.0) + } else { + rect.w + }, + rect.h, + ), + kind, + scrolls_x: false, + }; + if let Hit::SetProgress { row_id, column_id } = &hit.kind { + self.start_database_progress_scrub( + &block, + row_id, + column_id, + &hit, + f32::from(pos.x), + cx, + ); + return; + } + self.dispatch_database_authoring_hit(&block, &hit, f32::from(pos.x), Some(window), cx); + self.place_database_inline_caret_at_point(pos, window, cx); + } + + pub(super) fn record_add_property(&mut self, window: &mut Window, cx: &mut Context) { + if self.is_database_write_readonly() { + return; + } + let Some(block) = self + .database_record_sheet + .as_ref() + .map(|s| s.block_id.clone()) + else { + return; + }; + self.finish_record_edit(Some(window), cx); + self.update_database_authoring( + &block, + |auth| { + auth.toolbar_panel = Some(database::ActiveToolbarPanel::NewProperty); + }, + cx, + ); + } + + pub(super) fn record_neighbours(&self) -> [Option; 2] { + let Some(sheet) = &self.database_record_sheet else { + return [None, None]; + }; + let Some(BlockContent::Database(db)) = self + .snapshot + .as_ref() + .and_then(|s| s.block(&sheet.block_id)) + .map(|n| &n.content) + else { + return [None, None]; + }; + let state = self.flow.database_state.state_for(&sheet.block_id); + let Some(view) = state + .active_view_id + .as_ref() + .and_then(|id| db.views.iter().find(|v| v.id == *id)) + .or_else(|| db.views.first()) + else { + return [None, None]; + }; + let rows = database::filter_and_sort_view_rows(view, db, &self.page_titles); + let Some(i) = rows.iter().position(|r| r.row_id == sheet.row_id) else { + return [None, None]; + }; + [i.checked_sub(1).and_then(|n| rows.get(n)), rows.get(i + 1)] + .map(|r| r.map(|r| r.row_id.clone())) + } + + pub(super) fn record_note_press( + &mut self, + child: &str, + pos: Point, + window: &mut Window, + cx: &mut Context, + ) { + if self.is_database_write_readonly() { + return; + } + let note = if child.is_empty() { + RecordParagraph::Draft(self.fresh_block_id()) + } else { + RecordParagraph::Existing(child.to_string()) + }; + if !self + .database_record_sheet + .as_ref() + .is_some_and(|s| s.note_editing.as_ref().is_some_and(|n| n.id() == note.id())) + { + self.finish_record_edit(Some(window), cx); + if let Some(sheet) = self.database_record_sheet.as_mut() { + sheet.note_editing = Some(note); + } + if let Ok(page) = self.page_mut() { + let _ = page.stop_capturing(); + } + self.sync_database_authoring_input(Some(window), cx); + } + self.editor_focus.focus(window, cx); + if let Some(offset) = self.database_inline_character_index_for_point(pos, window) { + self.database_authoring_input_edit(window, cx, |a| { + a.input.select(offset..offset); + None + }); + } + } + + pub(crate) fn splice_record_note( + &mut self, + row: &str, + child: &str, + start: usize, + del: usize, + insert: &str, + now: u64, + ) -> bool { + let Some(sheet) = &self.database_record_sheet else { + return false; + }; + let Some(note) = sheet + .note_editing + .as_ref() + .filter(|n| n.id() == child && sheet.row_id == row) + else { + return false; + }; + let Some(snapshot) = &self.snapshot else { + return false; + }; + let Some(parent) = snapshot.block(row) else { + return false; + }; + let draft = matches!(note, RecordParagraph::Draft(_)); + if note.text(parent).is_none() + || (draft && (insert.is_empty() || snapshot.block(child).is_some())) + { + return false; + } + let Ok(page) = self.page_mut() else { + return false; + }; + let result = if !draft { + let mut delta = Vec::new(); + if start > 0 { + delta.push(y_octo::TextDeltaOp::Retain { + retain: start as u64, + format: None, + }); + } + if del > 0 { + delta.push(y_octo::TextDeltaOp::Delete { delete: del as u64 }); + } + if !insert.is_empty() { + delta.push(y_octo::TextDeltaOp::Insert { + insert: y_octo::TextInsert::Text(insert.to_string()), + format: None, + }); + } + page.apply_text_delta(child, "prop:text", &delta, now) + } else { + page.add_block( + child, + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: insert.to_string(), + }, + Some(row), + None, + now, + ) + }; + let changed = result.ok().flatten().is_some(); + if changed + && draft + && let Some(sheet) = &mut self.database_record_sheet + { + sheet.note_editing = Some(RecordParagraph::Existing(child.to_string())); + } + changed + } +} 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 e294ca4b6c..c800f7842f 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 @@ -10,6 +10,7 @@ //! - On a writable page, clicking the title edits it in place and clicking a checkbox flips it, //! each written as one undo step. +use crate::database_authoring::RecordParagraph; use std::rc::Rc; use blocksuite_playground_doc::read::{ @@ -34,6 +35,7 @@ pub struct DatabaseRecordSheetState { pub row_id: String, /// Whether the title is edited in the sheet, keystroke by keystroke in its live `Y.Text`. pub title_editing: bool, + pub note_editing: Option, pub hidden_expanded: bool, pub scroll_y: f32, pub grabber_drag_start_y: Option, @@ -45,6 +47,7 @@ pub struct DatabaseRecordSheetState { } struct FieldEntry { + editable: bool, col_id: String, label: String, value: String, @@ -102,8 +105,8 @@ fn format_field_entry( checkbox = Some(checked); String::new() } - ("progress", Some(v)) => { - let pct = v.as_i64().unwrap_or(0).clamp(0, 100); + ("progress", value) => { + let pct = value.and_then(|v| v.as_i64()).unwrap_or(0).clamp(0, 100); let (ratio, lbl) = format_database_progress(pct); progress = Some((ratio, lbl)); String::new() @@ -171,6 +174,10 @@ fn format_field_entry( (_, None) => "-".to_string(), }; FieldEntry { + editable: !matches!( + col.column_type.as_str(), + "created-time" | "last-edited-time" | "image" + ), col_id: col.id.clone(), label: if col.name.is_empty() { col.column_type.clone() @@ -217,6 +224,7 @@ fn partition_view_columns<'a>( (visible, hidden) } +mod editing; mod render; enum PreparedFieldValue { @@ -240,6 +248,7 @@ enum PreparedFieldValue { } struct PreparedFieldRow { + editable: bool, col_id: String, label_layout: Rc, label_h: f32, @@ -267,6 +276,7 @@ struct PreparedRecordSheet { title_card_h: f32, title_layout: Rc, value_w: f32, + notes: Vec<(String, String, f32)>, visible_rows: Vec, hidden_rows: Vec, hidden_expanded: bool, @@ -299,6 +309,7 @@ impl PlaygroundView { block_id: block_id.into(), row_id: row_id.into(), title_editing: false, + note_editing: None, hidden_expanded: false, scroll_y: 0.0, grabber_drag_start_y: None, @@ -311,7 +322,7 @@ impl PlaygroundView { /// Close the `"Record"` detail sheet if open, writing a title edit in progress first. pub fn close_database_record_sheet(&mut self, cx: &mut Context) -> bool { - self.commit_record_title_edit(None, cx); + self.finish_record_edit(None, cx); if self.database_record_sheet.take().is_some() { cx.notify(); true @@ -328,7 +339,7 @@ impl PlaygroundView { /// Clear the open record sheet if its target database block or row no longer exists in the /// latest document snapshot (e.g. after a remote collaborator delete or Undo). pub(crate) fn sync_database_record_sheet_from_snapshot(&mut self) -> bool { - let Some(sheet) = self.database_record_sheet.as_ref() else { + let Some(sheet) = self.database_record_sheet.as_mut() else { return false; }; let still_exists = self @@ -345,6 +356,17 @@ impl PlaygroundView { self.database_record_sheet = None; return true; } + if let Some(note) = &sheet.note_editing + && self + .snapshot + .as_ref() + .and_then(|s| s.block(&sheet.row_id)) + .and_then(|row| note.text(row)) + .is_none() + { + sheet.note_editing = None; + return true; + } false } @@ -392,7 +414,7 @@ impl PlaygroundView { let sheet_w = if is_phone { win_w.max(280.0) } else if is_desktop_peek { - (win_w - 64.0).clamp(440.0, 580.0) + (win_w - 64.0).min(760.0) } else { win_w.min(480.0) }; @@ -477,10 +499,16 @@ impl PlaygroundView { let (value, value_h) = if let Some(checked) = field.checkbox { (PreparedFieldValue::Checkbox { checked }, 24.0) } else if let Some((ratio, label)) = &field.progress { + let preview = ui_state + .authoring + .progress_preview + .as_ref() + .filter(|p| p.row_id == row.row_id && p.column_id == field.col_id) + .map(|p| p.value); ( PreparedFieldValue::Progress { - ratio: *ratio, - label: label.clone(), + ratio: preview.map_or(*ratio, |v| v as f32 / 100.0), + label: preview.map_or_else(|| label.clone(), |v| format!("{v}%")), }, 20.0, ) @@ -547,6 +575,7 @@ impl PlaygroundView { }; let row_h = label_h.max(value_h) + 17.0; PreparedFieldRow { + editable: field.editable, col_id: field.col_id.clone(), label_layout, label_h, @@ -568,8 +597,54 @@ impl PlaygroundView { } else { 0.0 }; - let body_total_h = - title_card_h + 10.0 + visible_h + hidden_toggle_h + hidden_rows_h + 20.0 + safe_bottom; + let mut notes = Vec::new(); + if is_desktop_peek { + if let Some(node) = snapshot.block(&row.row_id) { + for child in &node.children { + if let BlockContent::Paragraph { text, .. } | BlockContent::List { text, .. } = + &child.content + { + let h = layout_inline( + &text.plain, + &val_style, + (sheet_w - 64.0).max(1.0), + 20.0, + InlineBaseline::At(15.0), + InlineAlign::Left, + window, + ) + .height() + .max(44.0) + + 8.0; + notes.push((child.id.clone(), text.plain.clone(), h)); + } + } + } + if notes.is_empty() { + notes.push(( + sheet + .note_editing + .as_ref() + .map_or("", RecordParagraph::id) + .to_string(), + String::new(), + 64.0, + )); + } + } + let extra_h = if is_desktop_peek { + 44.0 + notes.iter().map(|n| n.2 + 10.0).sum::() + } else { + 0.0 + }; + let body_total_h = extra_h + + title_card_h + + 10.0 + + visible_h + + hidden_toggle_h + + hidden_rows_h + + 20.0 + + safe_bottom; let chrome_h = border_top_h + grabber_h + header_h; let total_h = chrome_h + body_total_h; let sheet_h = total_h.min(max_sheet_h).round(); @@ -603,6 +678,7 @@ impl PlaygroundView { title_card_h, title_layout, value_w, + notes, visible_rows, hidden_rows, hidden_expanded: sheet.hidden_expanded, diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs index 33f40df298..7482d86a24 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs @@ -29,243 +29,285 @@ impl PlaygroundView { y >= -0.5 && (y + h) <= p.body_viewport_h + 0.5 }; - let render_field_row = - |idx: usize, row: &PreparedFieldRow, visible_in_snap: bool, cx: &mut Context| { - let mut row_el = div() - .w_full() - .h(px(row.row_h)) - .py(px(8.0)) - .px(px(4.0)) - .border_b_1() - .border_color(palette.border) - .flex() - .items_center() - .gap(px(12.0)) - .child( - div() - .flex_none() - .w(px(96.0)) - .h(px(row.label_h)) - .overflow_hidden() - .child(inline_canvas(row.label_layout.clone(), 96.0, row.label_h)), - ); - match &row.value { - PreparedFieldValue::Checkbox { checked } => { - let icon = crate::theme::IconPaint::named(if *checked { - "CheckBoxCheckSolidIcon" - } else { - "CheckBoxUnIcon" - }); - let color = if *checked { - palette.brand - } else { - palette.icon - }; - let mut el = div() - .id(SharedString::from(format!("db-record-checkbox-{idx}"))) - .w(px(value_w)) - .min_w(px(0.0)) - .h(px(24.0)) - .flex() - .items_center() - .child( - ui::canvas( - |_, _, _| {}, - move |bounds, _, window, cx| { - icon.paint(bounds, color, window, cx); - }, - ) - .w(px(18.0)) - .h(px(18.0)) - .flex_none(), - ); - if !p.readonly { - let bid = p.block_id.clone(); - let rid = p.row_id.clone(); - let cid = row.col_id.clone(); - let next_val = !*checked; - el = el - .cursor_pointer() - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &ui::MouseDownEvent, window, cx| { - cx.stop_propagation(); - this.commit_record_title_edit(Some(window), cx); - }), - ) - .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| { - let now_ms = this.now_ms(cx) as u64; - let commit = this - .page_mut() + let render_field_row = |idx: usize, + row: &PreparedFieldRow, + visible_in_snap: bool, + cx: &mut Context| { + let mut row_el = div() + .w_full() + .h(px(row.row_h)) + .py(px(8.0)) + .px(px(4.0)) + .border_b_1() + .border_color(palette.border) + .flex() + .items_center() + .gap(px(12.0)) + .child( + div() + .flex_none() + .w(px(96.0)) + .h(px(row.label_h)) + .overflow_hidden() + .child(inline_canvas(row.label_layout.clone(), 96.0, row.label_h)), + ); + let field_editable = p.is_desktop_peek + && !p.readonly + && !matches!(row.value, PreparedFieldValue::Checkbox { .. }) + && row.editable; + if field_editable { + let column = row.col_id.clone(); + row_el = row_el.cursor_pointer().on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &ui::MouseDownEvent, window, cx| { + cx.stop_propagation(); + this.record_field_press(&column, event.position, window, cx); + }), + ); + } + if self.record_field_input_active(&row.col_id) { + return row_el.child( + div() + .w(px(value_w)) + .h(px(row.row_h - 6.0)) + .rounded(px(4.0)) + .border_1() + .border_color(palette.brand), + ); + } + match &row.value { + PreparedFieldValue::Checkbox { checked } => { + let icon = crate::theme::IconPaint::named(if *checked { + "CheckBoxCheckSolidIcon" + } else { + "CheckBoxUnIcon" + }); + let color = if *checked { + palette.brand + } else { + palette.icon + }; + let mut el = div() + .id(SharedString::from(format!("db-record-checkbox-{idx}"))) + .w(px(value_w)) + .min_w(px(0.0)) + .h(px(24.0)) + .flex() + .items_center() + .child( + ui::canvas( + |_, _, _| {}, + move |bounds, _, window, cx| { + icon.paint(bounds, color, window, cx); + }, + ) + .w(px(18.0)) + .h(px(18.0)) + .flex_none(), + ); + if !p.readonly { + let bid = p.block_id.clone(); + let rid = p.row_id.clone(); + let cid = row.col_id.clone(); + let next_val = !*checked; + el = el + .cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &ui::MouseDownEvent, window, cx| { + cx.stop_propagation(); + this.finish_record_edit(Some(window), cx); + }), + ) + .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| { + let now_ms = this.now_ms(cx) as u64; + let commit = this + .page_mut() + .ok() + .and_then(|page| { + page.set_database_cell_bool( + &bid, &rid, &cid, next_val, now_ms, + ) .ok() - .and_then(|page| { - page.set_database_cell_bool( - &bid, &rid, &cid, next_val, now_ms, - ) - .ok() - }) - .flatten(); - this.apply_database_commit(commit, Some(window), cx); - })); - } - if visible_in_snap { - el = el.snapshot( + }) + .flatten(); + this.apply_database_commit(commit, Some(window), cx); + })); + } + if visible_in_snap { + el = el.snapshot( + SharedString::from(format!( + "overlay.database_record_sheet.checkbox.{idx}" + )), + Some("overlay.database_record_sheet"), + ); + } + row_el = row_el.child(el); + } + PreparedFieldValue::Progress { ratio, label } => { + let bar_w = (value_w - 46.0).max(32.0); + let fill_w = if *ratio > 0.0 { + (bar_w * *ratio).max(4.0) + } else { + 0.0 + }; + let mut track = div() + .w(px(bar_w)) + .h(px(8.0)) + .rounded(px(4.0)) + .bg(palette.background_secondary) + .border_1() + .border_color(palette.border) + .overflow_hidden(); + if fill_w > 0.0 { + track = track.child( + div() + .w(px(fill_w)) + .h(px(8.0)) + .rounded(px(4.0)) + .bg(palette.brand), + ); + } + let mut el = div() + .w(px(value_w)) + .min_w(px(0.0)) + .h(px(20.0)) + .flex() + .items_center() + .gap(px(8.0)) + .child(track) + .child( + div() + .w(px(38.0)) + .text_size(px(TYPOGRAPHY.font_xs_px)) + .line_height(px(16.0)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_secondary) + .child(label.clone()), + ); + if visible_in_snap { + el = el + .snapshot( SharedString::from(format!( - "overlay.database_record_sheet.checkbox.{idx}" + "overlay.database_record_sheet.progress.{idx}" )), Some("overlay.database_record_sheet"), - ); - } - row_el = row_el.child(el); + ) + .snapshot_text(label.clone()); } - PreparedFieldValue::Progress { ratio, label } => { - let bar_w = (value_w - 46.0).max(32.0); - let fill_w = if *ratio > 0.0 { - (bar_w * *ratio).max(4.0) - } else { - 0.0 - }; - let mut track = div() - .w(px(bar_w)) - .h(px(8.0)) - .rounded(px(4.0)) - .bg(palette.background_secondary) - .border_1() - .border_color(palette.border) - .overflow_hidden(); - if fill_w > 0.0 { - track = track.child( + row_el = row_el.child(el); + } + PreparedFieldValue::Pills { rows, height } => { + let mut col = div() + .w(px(value_w)) + .min_w(px(0.0)) + .h(px(*height)) + .overflow_hidden() + .flex() + .flex_col() + .gap(px(6.0)); + for pill_row in rows { + let mut line = div().h(px(22.0)).flex().items_center().gap(px(6.0)); + for (lbl, pw, bg, ink) in pill_row { + line = line.child( div() - .w(px(fill_w)) - .h(px(8.0)) - .rounded(px(4.0)) - .bg(palette.brand), - ); - } - let mut el = div() - .w(px(value_w)) - .min_w(px(0.0)) - .h(px(20.0)) - .flex() - .items_center() - .gap(px(8.0)) - .child(track) - .child( - div() - .w(px(38.0)) + .w(px(*pw)) + .h(px(22.0)) + .px(px(8.0)) + .rounded(px(6.0)) + .bg(*bg) + .flex() + .items_center() + .overflow_hidden() .text_size(px(TYPOGRAPHY.font_xs_px)) .line_height(px(16.0)) .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_secondary) - .child(label.clone()), + .text_color(*ink) + .child(lbl.clone()), ); - if visible_in_snap { - el = el - .snapshot( - SharedString::from(format!( - "overlay.database_record_sheet.progress.{idx}" - )), - Some("overlay.database_record_sheet"), - ) - .snapshot_text(label.clone()); } - row_el = row_el.child(el); - } - PreparedFieldValue::Pills { rows, height } => { - let mut col = div() - .w(px(value_w)) - .min_w(px(0.0)) - .h(px(*height)) - .overflow_hidden() - .flex() - .flex_col() - .gap(px(6.0)); - for pill_row in rows { - let mut line = div().h(px(22.0)).flex().items_center().gap(px(6.0)); - for (lbl, pw, bg, ink) in pill_row { - line = line.child( - div() - .w(px(*pw)) - .h(px(22.0)) - .px(px(8.0)) - .rounded(px(6.0)) - .bg(*bg) - .flex() - .items_center() - .overflow_hidden() - .text_size(px(TYPOGRAPHY.font_xs_px)) - .line_height(px(16.0)) - .font_weight(FontWeight::MEDIUM) - .text_color(*ink) - .child(lbl.clone()), - ); - } - col = col.child(line); - } - row_el = row_el.child(col); - } - PreparedFieldValue::Text { - layout, - raw, - url: Some(valid_url), - height, - } => { - let open_url = valid_url.clone(); - let mut el = div() - .id(SharedString::from(format!("db-record-url-{idx}"))) - .w(px(value_w)) - .min_w(px(0.0)) - .h(px(*height)) - .flex() - .items_center() - .overflow_hidden() - .cursor_pointer() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.last_opened_link_url = Some(open_url.clone()); - cx.open_url(&open_url); - cx.notify(); - })) - .child(inline_canvas(layout.clone(), value_w, *height)); - if visible_in_snap { - el = el - .snapshot( - SharedString::from(format!( - "overlay.database_record_sheet.url.{idx}" - )), - Some("overlay.database_record_sheet"), - ) - .snapshot_text(raw.clone()); - } - row_el = row_el.child(el); - } - PreparedFieldValue::Text { - layout, - raw, - url: None, - height, - } => { - let mut el = div() - .w(px(value_w)) - .min_w(px(0.0)) - .h(px(*height)) - .overflow_hidden() - .child(inline_canvas(layout.clone(), value_w, *height)); - if visible_in_snap { - el = el - .snapshot( - SharedString::from(format!( - "overlay.database_record_sheet.field.{idx}" - )), - Some("overlay.database_record_sheet"), - ) - .snapshot_text(raw.clone()); - } - row_el = row_el.child(el); + col = col.child(line); } + row_el = row_el.child(col); } - row_el - }; + PreparedFieldValue::Text { + layout, + raw, + url: Some(valid_url), + height, + } => { + let open_url = valid_url.clone(); + let mut opener = div() + .id(SharedString::from(format!("db-record-open-url-{idx}"))) + .h(px(*height)) + .flex() + .items_center() + .cursor_pointer() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.last_opened_link_url = Some(open_url.clone()); + cx.open_url(&open_url); + cx.notify(); + })); + let mut el = div() + .id(SharedString::from(format!("db-record-url-{idx}"))) + .w(px(value_w)) + .min_w(px(0.0)) + .h(px(*height)) + .flex() + .items_center() + .overflow_hidden(); + if field_editable { + let edit_w = (value_w - 28.0).max(1.0); + el = el.child(div().w(px(edit_w)).overflow_hidden().child(inline_canvas( + layout.clone(), + edit_w, + *height, + ))); + opener = opener.w(px(28.0)).justify_center().child("↗"); + } else { + opener = opener.child(inline_canvas(layout.clone(), value_w, *height)); + } + el = el.child(opener); + if visible_in_snap { + el = el + .snapshot( + SharedString::from(format!( + "overlay.database_record_sheet.url.{idx}" + )), + Some("overlay.database_record_sheet"), + ) + .snapshot_text(raw.clone()); + } + row_el = row_el.child(el); + } + PreparedFieldValue::Text { + layout, + raw, + url: None, + height, + } => { + let mut el = div() + .w(px(value_w)) + .min_w(px(0.0)) + .h(px(*height)) + .overflow_hidden() + .child(inline_canvas(layout.clone(), value_w, *height)); + if visible_in_snap { + el = el + .snapshot( + SharedString::from(format!( + "overlay.database_record_sheet.field.{idx}" + )), + Some("overlay.database_record_sheet"), + ) + .snapshot_text(raw.clone()); + } + row_el = row_el.child(el); + } + } + row_el + }; let mut cursor_y = 0.0_f32; let title_editing = self.record_title_editing(); @@ -360,7 +402,7 @@ impl PlaygroundView { MouseButton::Left, cx.listener(|this, _: &ui::MouseDownEvent, window, cx| { cx.stop_propagation(); - this.commit_record_title_edit(Some(window), cx); + this.finish_record_edit(Some(window), cx); }), ) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { @@ -393,6 +435,71 @@ impl PlaygroundView { } } + if p.is_desktop_peek { + let mut add = div() + .w_full() + .h(px(34.0)) + .flex() + .items_center() + .text_color(palette.text_secondary); + if !p.readonly { + add = add + .cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &ui::MouseDownEvent, w, cx| { + cx.stop_propagation(); + this.record_add_property(w, cx); + }), + ) + .snapshot( + "overlay.database_record_sheet.add_property", + Some("overlay.database_record_sheet"), + ) + .child("+ Add Property"); + } + body_content = body_content.child(add); + for (index, (id, text, height)) in p.notes.iter().enumerate() { + let active = self + .database_record_sheet + .as_ref() + .is_some_and(|s| s.note_editing.as_ref().is_some_and(|note| note.id() == id)); + let mut note = div() + .w_full() + .flex_none() + .h(px(*height)) + .px(px(8.0)) + .py(px(4.0)) + .overflow_hidden() + .border_t(px(1.0)) + .border_color(palette.border) + .text_size(px(14.0)) + .line_height(px(20.0)); + if !active { + if text.is_empty() { + note = note + .text_color(palette.text_secondary) + .child("Write a note…"); + } else { + note = note.text_color(palette.text_primary).child(text.clone()); + } + } + if !p.readonly { + let child = id.clone(); + note = note.cursor(ui::CursorStyle::IBeam).on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &ui::MouseDownEvent, w, cx| { + cx.stop_propagation(); + this.record_note_press(&child, event.position, w, cx); + }), + ); + } + body_content = body_content.child(note.snapshot( + SharedString::from(format!("overlay.database_record_sheet.note.{index}")), + Some("overlay.database_record_sheet"), + )); + } + } let body = div() .w_full() .flex_1() @@ -426,7 +533,7 @@ impl PlaygroundView { .snapshot_text("Close") .child("\u{00D7}"); - let header = div() + let mut header = div() .relative() .w_full() .h(px(p.close_sz + 8.0)) @@ -454,6 +561,54 @@ impl PlaygroundView { .child(close_btn), ); + if p.is_desktop_peek { + let mut nav = div() + .absolute() + .left(px(16.0)) + .top(px(4.0)) + .flex() + .gap(px(4.0)); + for (idx, (target, label)) in self + .record_neighbours() + .into_iter() + .zip(["↑", "↓"]) + .enumerate() + { + let mut btn = div() + .w(px(28.0)) + .h(px(28.0)) + .rounded(px(6.0)) + .flex() + .items_center() + .justify_center() + .child(label); + if let Some(row) = target { + let block = p.block_id.clone(); + btn = btn + .cursor_pointer() + .text_color(palette.text_primary) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _: &ui::MouseDownEvent, w, cx| { + cx.stop_propagation(); + this.finish_record_edit(Some(w), cx); + this.open_database_record_sheet(&block, &row, cx); + }), + ); + } else { + btn = btn.text_color(palette.placeholder); + } + nav = nav.child(btn.snapshot( + if idx == 0 { + "overlay.database_record_sheet.previous" + } else { + "overlay.database_record_sheet.next" + }, + Some("overlay.database_record_sheet"), + )); + } + header = header.child(nav); + } let grabber = div() .id("db-record-sheet-grabber") .w_full() @@ -512,10 +667,15 @@ impl PlaygroundView { MouseButton::Left, cx.listener(|this, _: &ui::MouseDownEvent, window, cx| { cx.stop_propagation(); - this.commit_record_title_edit(Some(window), cx); + this.finish_record_edit(Some(window), cx); }), ) - .on_mouse_move(cx.listener(|this, event: &ui::MouseMoveEvent, _, cx| { + .on_mouse_move(cx.listener(|this, event: &ui::MouseMoveEvent, w, cx| { + if this.database_drag.is_some() && this.database_authoring_mouse_move(event, w, cx) + { + cx.stop_propagation(); + return; + } let start_y = this .database_record_sheet .as_ref() @@ -532,7 +692,11 @@ impl PlaygroundView { })) .on_mouse_up( MouseButton::Left, - cx.listener(|this, event: &ui::MouseUpEvent, _, cx| { + cx.listener(|this, event: &ui::MouseUpEvent, w, cx| { + if this.database_drag.is_some() && this.database_authoring_mouse_up(w, cx) { + cx.stop_propagation(); + return; + } if let Some(y0) = this .database_record_sheet .as_mut() @@ -588,12 +752,31 @@ impl PlaygroundView { } }), ) + .on_mouse_move(cx.listener(|this, event: &ui::MouseMoveEvent, w, cx| { + if this.database_drag.is_some() && this.database_authoring_mouse_move(event, w, cx) + { + cx.stop_propagation(); + } + })) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, _: &ui::MouseUpEvent, w, cx| { + if this.database_drag.is_some() && this.database_authoring_mouse_up(w, cx) { + cx.stop_propagation(); + } + }), + ) .on_scroll(|_, _, cx| cx.stop_propagation()) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { this.close_database_record_sheet(cx); })) .child(sheet_el) - .children(self.record_title_edit_elements(palette, window, cx)); + .children(self.record_title_edit_elements(palette, window, cx)) + .children(self.flow_layout().and_then(|layout| { + let picker = self.record_picker_elements(&layout, window, cx); + (!picker.is_empty()) + .then(|| ui::deferred(div().absolute().inset_0().children(picker))) + })); Some(scrim.into_any_element()) } diff --git a/blocksuite/crates/playground/src/page_scroll.rs b/blocksuite/crates/playground/src/page_scroll.rs index c8b484dc0e..6ef1cca474 100644 --- a/blocksuite/crates/playground/src/page_scroll.rs +++ b/blocksuite/crates/playground/src/page_scroll.rs @@ -73,7 +73,7 @@ impl PlaygroundView { return false; } let (_, dy) = blocksuite_editor::scroll::wheel_delta(event, overlay.bounds.h); - let _ = self.scroll_open_select_popover(dy, cx); + let _ = self.scroll_database_panel(dy, overlay.bounds.h, cx); true }