diff --git a/blocksuite/crates/editor/src/database/add_group.rs b/blocksuite/crates/editor/src/database/add_group.rs new file mode 100644 index 0000000000..bacd5bc232 --- /dev/null +++ b/blocksuite/crates/editor/src/database/add_group.rs @@ -0,0 +1,153 @@ +//! Kanban `+ Add Group` (`0.27.5` `kanban/pc/add-group`): the button after the last lane and +//! the popover that names the new group. + +use blocksuite_playground_doc::read::DatabaseGroupBy; + +use crate::{ + block_flow::{FlowRect, InlineAlign, InlineStyle}, + theme::{FONT_SANS, IconPaint, TYPOGRAPHY}, +}; + +use super::{ + DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseViewAction, + render::{DatabasePrim, DbRenderCtx}, +}; + +/// Width of the `+ Add Group` button after the last lane. +pub(super) const ADD_GROUP_W: f32 = 132.0; +const FIELD_H: f32 = 28.0; +const PAD: f32 = 8.0; + +/// Whether new groups can be added to the lanes of `group_by` (a select column). +pub(super) fn can_add_group(ctx: &DbRenderCtx<'_>, group_by: &DatabaseGroupBy) -> bool { + !ctx.mobile_readonly + && ctx.data.columns.iter().any(|c| { + c.id == group_by.column_id + && matches!(c.column_type.as_str(), "select" | "multi-select") + }) +} + +/// Paint the `+ Add Group` button at `(x, y)`. +pub(super) fn push_add_group_button( + ctx: &DbRenderCtx<'_>, + x: f32, + y: f32, + prims: &mut Vec, + hits: &mut Vec, +) { + let rect = FlowRect::new(x, y, ADD_GROUP_W, FIELD_H); + if ctx.ui_state.authoring.toolbar_panel == Some(super::ActiveToolbarPanel::AddGroup) { + prims.push(DatabasePrim::Quad { + rect, + fill: Some(ctx.palette.hover), + border: None, + radius: 4.0, + dashed: false, + }); + } + prims.push(DatabasePrim::Icon { + rect: FlowRect::new(rect.x + 8.0, rect.y + 7.0, 14.0, 14.0), + icon: IconPaint::from_def(&ui_tokens::icons::PLUS), + color: ctx.palette.icon, + }); + prims.push(ctx.single_line_clipped( + "Add Group", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 500.0, + ctx.palette.text_secondary, + ), + rect.x + 28.0, + rect.y, + rect.w - 34.0, + FIELD_H, + InlineAlign::Left, + )); + hits.push(DatabaseAuthoringHit { + rect, + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::OpenAddGroup), + scrolls_x: true, + }); +} + +pub(super) fn measure_add_group_panel() -> (f32, f32) { + (240.0, 2.0 * FIELD_H + 3.0 * PAD) +} + +/// Paint the `+ Add Group` popover at `rect` (screen space). Returns the rect of its name field. +pub(super) fn render_add_group_panel_at( + ctx: &DbRenderCtx<'_>, + rect: FlowRect, + prims: &mut Vec, + hits: &mut Vec, +) -> FlowRect { + prims.push(DatabasePrim::Quad { + rect, + fill: Some(ctx.palette.panel), + border: Some(ctx.palette.border), + radius: 8.0, + dashed: false, + }); + let field = FlowRect::new(rect.x + PAD, rect.y + PAD, rect.w - 2.0 * PAD, FIELD_H); + prims.push(DatabasePrim::Quad { + rect: field, + fill: Some(ctx.palette.background), + border: Some(ctx.palette.brand), + radius: 4.0, + dashed: false, + }); + let draft = ctx.ui_state.authoring.group_name_draft.trim(); + if ctx.ui_state.authoring.group_name_draft.is_empty() { + prims.push(ctx.single_line_clipped( + "Group name", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 400.0, + ctx.palette.placeholder, + ), + field.x + 8.0, + field.y, + field.w - 16.0, + FIELD_H, + InlineAlign::Left, + )); + } + let create = FlowRect::new(field.x, field.bottom() + PAD, field.w, FIELD_H); + prims.push(DatabasePrim::Quad { + rect: create, + fill: Some(if draft.is_empty() { + ctx.palette.hover + } else { + ctx.palette.brand + }), + border: None, + radius: 4.0, + dashed: false, + }); + prims.push(ctx.single_line_clipped( + "Create", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 500.0, + if draft.is_empty() { + ctx.palette.text_secondary + } else { + ui::white() + }, + ), + create.x, + create.y, + create.w, + FIELD_H, + InlineAlign::Center, + )); + hits.push(DatabaseAuthoringHit { + rect: create, + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::CreateGroup), + scrolls_x: false, + }); + field +} diff --git a/blocksuite/crates/editor/src/database/authoring.rs b/blocksuite/crates/editor/src/database/authoring.rs index 83fb650a1e..9b588abc54 100644 --- a/blocksuite/crates/editor/src/database/authoring.rs +++ b/blocksuite/crates/editor/src/database/authoring.rs @@ -70,6 +70,10 @@ pub enum ActiveToolbarPanel { Properties, NewView, NewProperty, + /// Live row search field (`0.27.5` toolbar `Search`). + Search, + /// Name field of a new Kanban group (`+ Add Group`). + AddGroup, } /// Transient draft rule inside the Filter panel before clicking Apply. @@ -116,6 +120,8 @@ pub struct DatabaseAuthoringState { pub progress_preview: Option, pub active_cell: Option, pub option_menu: Option, + /// Name of the option when its menu opened: a typed name differs from it. + pub option_menu_name: String, pub select_scroll_y: f32, pub toolbar_scroll_y: f32, pub toolbar_panel: Option, @@ -123,6 +129,12 @@ pub struct DatabaseAuthoringState { pub calendar_drag: Option, pub calendar_resize_end: Option, pub kanban_drag: Option, + /// Month `(year, month 1..=12)` the open `Date` picker shows; `None` follows the cell value. + pub date_picker_month: Option<(i32, u32)>, + /// `(column_id, group_key)` of the footer `Calculate` cell whose menu is open. + pub calc_menu: Option<(String, String)>, + /// Name typed into the `+ Add Group` field. + pub group_name_draft: String, } impl DatabaseAuthoringState { @@ -135,6 +147,9 @@ impl DatabaseAuthoringState { self.select_scroll_y = 0.0; self.toolbar_scroll_y = 0.0; self.toolbar_panel = None; + self.date_picker_month = None; + self.calc_menu = None; + self.group_name_draft.clear(); } } @@ -306,6 +321,7 @@ pub enum DatabaseAuthoringHitKind { }, KanbanLaneCards { column_id: String, + bucket_key: String, rows: Vec, delete: bool, }, @@ -314,6 +330,7 @@ pub enum DatabaseAuthoringHitKind { day_index: i64, is_end: bool, }, + View(super::DatabaseViewAction), } /// One positioned authoring hit target in block-local coordinates. @@ -963,6 +980,136 @@ mod tests { db.clone() } + #[test] + fn option_color_swatch_keeps_a_peer_rename_while_save_name_writes_the_typed_name() { + use DatabaseAuthoringHitKind as Hit; + let (mut local, id) = seed_editor_db(); + local.stop_capturing().unwrap(); + let mut peer = PageDocSession::new("page-ed-auth", 8).unwrap(); + peer.apply_remote_update_v1(&local.encode_update_v1().unwrap()) + .unwrap(); + let option = |page: &PageDocSession| { + let db = snap_db(page, &id); + let col = db.columns.iter().find(|c| c.id == "c-status").unwrap(); + let o = col + .select_options() + .into_iter() + .find(|o| o.id == "s-todo") + .unwrap(); + (o.value, o.color) + }; + let mut state = DatabaseFlowState::default(); + let open_menu = |page: &mut PageDocSession, state: &mut DatabaseFlowState| { + let data = snap_db(page, &id); + for kind in [ + Hit::EditCell { + row_id: "r1".into(), + column_id: "c-status".into(), + col_type: "select".into(), + }, + Hit::SelectOptionMenu { + option_id: "s-todo".into(), + }, + ] { + let hit = DatabaseAuthoringHit { + kind, + rect: FlowRect::new(0.0, 0.0, 10.0, 10.0), + scrolls_x: false, + }; + handle_authoring_hit(page, state, &id, &data, &hit, 0.0, &|_| 0, 10).unwrap(); + } + }; + let click = |page: &mut PageDocSession, state: &mut DatabaseFlowState, kind| { + let data = snap_db(page, &id); + let hit = DatabaseAuthoringHit { + kind, + rect: FlowRect::new(0.0, 0.0, 10.0, 10.0), + scrolls_x: false, + }; + handle_authoring_hit(page, state, &id, &data, &hit, 0.0, &|_| 0, 20).unwrap() + }; + // 1. The menu opens on `Todo`; a peer renames the option before the swatch click. + open_menu(&mut local, &mut state); + let before = peer.encode_state_vector_v1().unwrap(); + peer.upsert_database_select_option( + &id, + "c-status", + "s-todo", + "Peer name", + "var(--affine-tag-blue)", + 15, + ) + .unwrap(); + local + .apply_remote_update_v1(&peer.encode_diff_v1(&before).unwrap()) + .unwrap(); + let red = "var(--affine-tag-red)".to_string(); + assert!( + click( + &mut local, + &mut state, + Hit::SelectSaveOption { + color: Some(red.clone()) + } + ) + .doc_mutated + ); + assert_eq!(option(&local), ("Peer name".to_string(), red)); + // 2. A typed name goes out with a swatch color, and `Save name` keeps the live color. + let green = "var(--affine-tag-green)".to_string(); + for (typed, color, expected) in [ + ("Ready", Some(green.clone()), ("Ready", green.clone())), + ("Typed", None, ("Typed", green.clone())), + ] { + open_menu(&mut local, &mut state); + if let Some(ed) = state.authoring_mut(&id).active_cell.as_mut() { + ed.select_filter = typed.into(); + } + assert!(click(&mut local, &mut state, Hit::SelectSaveOption { color }).doc_mutated); + assert_eq!(option(&local), (expected.0.to_string(), expected.1)); + } + } + + #[test] + fn ungroup_of_a_multi_select_lane_removes_only_that_tag_in_one_undo_step() { + use DatabaseAuthoringHitKind as Hit; + let (mut page, id) = seed_editor_db(); + let tags = |db: &DatabaseData| { + db.cells + .get(&("r1".to_string(), "c-tags".to_string())) + .map(|v| v.as_string_list()) + .unwrap_or_default() + }; + page.set_database_cell_value( + &id, + "r1", + "c-tags", + DatabaseCellSpec::MultiSelect(vec!["t-ui".into(), "t-x".into()]), + 50, + ) + .unwrap(); + page.stop_capturing().unwrap(); + let before = snap_db(&page, &id); + let hit = DatabaseAuthoringHit { + kind: Hit::KanbanLaneCards { + column_id: "c-tags".into(), + bucket_key: "t-ui".into(), + rows: vec!["r1".into()], + delete: false, + }, + rect: FlowRect::new(0.0, 0.0, 100.0, 24.0), + scrolls_x: false, + }; + let mut state = DatabaseFlowState::default(); + let result = + handle_authoring_hit(&mut page, &mut state, &id, &before, &hit, 0.0, &|_| 0, 100) + .unwrap(); + assert!(result.doc_mutated); + assert_eq!(tags(&snap_db(&page, &id)), ["t-x"]); + page.undo().unwrap(); + assert_eq!(tags(&snap_db(&page, &id)), ["t-ui", "t-x"]); + } + #[test] fn view_and_lane_actions_and_chip_removal_are_isolated_undo_steps() { use DatabaseAuthoringHitKind as Hit; @@ -997,11 +1144,13 @@ mod tests { }, Hit::KanbanLaneCards { column_id: "c-status".into(), + bucket_key: "s-todo".into(), rows: vec!["r1".into(), "r2".into()], delete: false, }, Hit::KanbanLaneCards { column_id: "c-status".into(), + bucket_key: "s-todo".into(), rows: vec!["r1".into(), "r2".into()], delete: true, }, diff --git a/blocksuite/crates/editor/src/database/authoring_dispatch.rs b/blocksuite/crates/editor/src/database/authoring_dispatch.rs index d55471e304..8aa79d0bd8 100644 --- a/blocksuite/crates/editor/src/database/authoring_dispatch.rs +++ b/blocksuite/crates/editor/src/database/authoring_dispatch.rs @@ -354,8 +354,9 @@ pub fn handle_authoring_hit( .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; + ed.select_filter = opt.value.clone(); auth.option_menu = Some(option_id.clone()); + auth.option_menu_name = opt.value; } Ok(AuthoringActionResult { handled: true, @@ -753,6 +754,16 @@ pub fn handle_authoring_hit( page, flow_state, block_id, data, &hit.kind, now_ms, ) } + DatabaseAuthoringHitKind::View(action) => super::view_action::handle_view_action( + page, + flow_state, + block_id, + data, + &view, + action, + offset_at_ms, + now_ms, + ), DatabaseAuthoringHitKind::ColumnMenuRenameInput | DatabaseAuthoringHitKind::ResizeColumnHandle { .. } | DatabaseAuthoringHitKind::OpenRowPeek { .. } diff --git a/blocksuite/crates/editor/src/database/calculate.rs b/blocksuite/crates/editor/src/database/calculate.rs new file mode 100644 index 0000000000..ef7369ad17 --- /dev/null +++ b/blocksuite/crates/editor/src/database/calculate.rs @@ -0,0 +1,429 @@ +//! Table footer statistics (`0.27.5` `table/stats`): per-column `Calculate` cells below the rows +//! of the table and of each group, their result formatting, and the statistic menu. + +use blocksuite_playground_doc::read::{DatabaseCellValue, DatabaseData, DatabaseRow}; + +use crate::{ + block_flow::{FlowRect, InlineAlign, InlineStyle}, + theme::{FONT_SANS, TYPOGRAPHY}, +}; + +use super::{ + DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePopoverAnchor, DatabaseViewAction, + column_ops::ResolvedTableCol, + format_number_cell, + render::{DatabasePrim, DbRenderCtx}, +}; + +/// Height of one footer statistic row. +pub(super) const CALC_ROW_HEIGHT: f32 = 32.0; +const MENU_ITEM_H: f32 = 30.0; + +/// Footer statistics as `(statCalcType, menu label, cell label, numeric columns only)`. +pub const STAT_CALC_TYPES: &[(&str, &str, &str, bool)] = &[ + ("none", "None", "", false), + ("count-all", "Count all", "Count", false), + ("count-values", "Count values", "Values", false), + ("count-empty", "Count empty", "Empty", false), + ("percent-empty", "Percent empty", "Empty", false), + ("percent-not-empty", "Percent not empty", "Not empty", false), + ("sum", "Sum", "Sum", true), + ("avg", "Average", "Average", true), + ("min", "Min", "Min", true), + ("max", "Max", "Max", true), +]; + +/// Menu label of the statistic `calc`, or `None` for an unknown `statCalcType`. +pub fn stat_calc_label(calc: &str) -> Option<&'static str> { + STAT_CALC_TYPES + .iter() + .find(|(id, ..)| *id == calc) + .map(|(_, label, ..)| *label) +} + +fn is_numeric_type(col_type: &str) -> bool { + matches!(col_type, "number" | "progress") +} + +/// `(is_empty, value_count, number)` of one cell. +fn cell_stat( + data: &DatabaseData, + column_id: &str, + col_type: &str, + row: &DatabaseRow, +) -> (bool, usize, Option) { + let present = |empty: bool| (empty, usize::from(!empty), None); + match col_type { + "title" => present(row.title.plain.trim().is_empty()), + "created-time" => present(row.created_at.is_none()), + _ => match data.cells.get(&(row.row_id.clone(), column_id.to_string())) { + None | Some(DatabaseCellValue::Null) => present(true), + Some(DatabaseCellValue::MultiSelect(items)) => (items.is_empty(), items.len(), None), + Some(DatabaseCellValue::Bool(checked)) => present(!checked), + Some(DatabaseCellValue::Json(v)) => present(v.is_null()), + Some(value) if is_numeric_type(col_type) => { + let number = value.as_f64(); + (number.is_none(), usize::from(number.is_some()), number) + } + Some(DatabaseCellValue::RichText(rt)) => present(rt.plain.trim().is_empty()), + Some(DatabaseCellValue::Text(s)) => present(s.trim().is_empty()), + Some(_) => present(false), + }, + } +} + +fn trim_decimals(value: f64) -> String { + let raw = format!("{value:.2}"); + raw.trim_end_matches('0').trim_end_matches('.').to_string() +} + +/// Compute the footer statistic `calc` of `column_id` over `rows`. Returns `None` for `none`, +/// an unknown statistic, or a numeric statistic on a column that holds no numbers. +pub fn compute_stat( + calc: &str, + data: &DatabaseData, + column_id: &str, + rows: &[DatabaseRow], +) -> Option { + // `none` (the default of every column) shows nothing: skip the pass over the rows. + if calc == "none" { + return None; + } + let column = data.columns.iter().find(|c| c.id == column_id); + let col_type = column.map_or("title", |c| c.column_type.as_str()); + let stats: Vec<(bool, usize, Option)> = rows + .iter() + .map(|row| cell_stat(data, column_id, col_type, row)) + .collect(); + let total = stats.len(); + let empty = stats.iter().filter(|s| s.0).count(); + let percent = |part: usize| { + let ratio = if total == 0 { + 0.0 + } else { + part as f64 * 100.0 / total as f64 + }; + format!("{}%", trim_decimals(ratio)) + }; + let numbers: Vec = stats.iter().filter_map(|s| s.2).collect(); + let numeric = |value: f64| match col_type { + "progress" => format!("{}%", trim_decimals(value)), + _ => format_number_cell(value, column.map_or(&serde_json::Value::Null, |c| &c.data)), + }; + let fold = |init: f64, f: fn(f64, f64) -> f64| { + (!numbers.is_empty()).then(|| numbers.iter().copied().fold(init, f)) + }; + match calc { + "count-all" => Some(total.to_string()), + "count-values" => Some(stats.iter().map(|s| s.1).sum::().to_string()), + "count-empty" => Some(empty.to_string()), + "percent-empty" => Some(percent(empty)), + "percent-not-empty" => Some(percent(total - empty)), + "sum" if is_numeric_type(col_type) => Some(numeric(numbers.iter().sum())), + "avg" if is_numeric_type(col_type) => (!numbers.is_empty()) + .then(|| numeric(numbers.iter().sum::() / numbers.len() as f64)), + "min" if is_numeric_type(col_type) => fold(f64::INFINITY, f64::min).map(numeric), + "max" if is_numeric_type(col_type) => fold(f64::NEG_INFINITY, f64::max).map(numeric), + _ => None, + } +} + +fn stat_calc_of<'a>(ctx: &'a DbRenderCtx<'_>, column_id: &str) -> &'a str { + ctx.view + .columns + .iter() + .find(|c| c.id == column_id) + .and_then(|c| c.stat_calc_type.as_deref()) + .unwrap_or("none") +} + +/// Paint one footer statistic row for `rows` (the whole table or one group `group_key`) at `y` +/// and return its height. +#[allow(clippy::too_many_arguments)] +pub(super) fn render_calc_footer( + ctx: &DbRenderCtx<'_>, + cols: &[ResolvedTableCol<'_>], + ordered_col_indices: &[usize], + rows: &[DatabaseRow], + group_key: &str, + start_x: f32, + y: f32, + prims: &mut Vec, + authoring_hits: &mut Vec, + popover_anchor: &mut Option, +) -> f32 { + let open = ctx.ui_state.authoring.calc_menu.as_ref(); + let mut x = start_x; + for &c_idx in ordered_col_indices { + let col = &cols[c_idx]; + let rect = FlowRect::new(x, y, col.width, CALC_ROW_HEIGHT); + x += col.width; + let calc = stat_calc_of(ctx, &col.id); + let is_open = open.is_some_and(|(c, g)| *c == col.id && g == group_key); + if is_open { + prims.push(DatabasePrim::Quad { + rect, + fill: Some(ctx.palette.hover), + border: None, + radius: 0.0, + dashed: false, + }); + *popover_anchor = Some(DatabasePopoverAnchor { + rect, + scrolls_x: true, + }); + } + let inner_w = (rect.w - 16.0).max(1.0); + let label = STAT_CALC_TYPES + .iter() + .find(|(id, ..)| *id == calc) + .map_or("", |(_, _, label, _)| *label); + match compute_stat(calc, ctx.data, &col.id, rows) { + Some(value) => { + let value_style = InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 500.0, + ctx.palette.text_primary, + ); + let (_, value_layout) = + ctx.truncate_text(&value, value_style, inner_w, CALC_ROW_HEIGHT); + let value_w = value_layout.content_width().ceil(); + let value_x = rect.right() - 8.0 - value_w; + prims.push(DatabasePrim::Text { + x: value_x, + y, + layout: value_layout, + clip: Some(FlowRect::new(rect.x + 8.0, y, inner_w, CALC_ROW_HEIGHT)), + }); + let label_w = (value_x - rect.x - 14.0).max(0.0); + if label_w > 12.0 { + prims.push(ctx.single_line_clipped( + &label.to_uppercase(), + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px - 1.0, + 500.0, + ctx.palette.text_secondary, + ), + rect.x + 8.0, + y, + label_w, + CALC_ROW_HEIGHT, + InlineAlign::Right, + )); + } + } + None if !ctx.mobile_readonly => prims.push(ctx.single_line_clipped( + "Calculate", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 400.0, + ctx.palette.placeholder, + ), + rect.x + 8.0, + y, + inner_w, + CALC_ROW_HEIGHT, + InlineAlign::Right, + )), + None => {} + } + if !ctx.mobile_readonly { + authoring_hits.push(DatabaseAuthoringHit { + rect, + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::OpenCalcMenu { + column_id: col.id.clone(), + group_key: group_key.to_string(), + }), + scrolls_x: true, + }); + } + } + prims.push(DbRenderCtx::hairline( + FlowRect::new(start_x, y + CALC_ROW_HEIGHT - 1.0, x - start_x, 1.0), + ctx.inside_border(), + )); + CALC_ROW_HEIGHT +} + +/// Statistics offered for the column of an open `Calculate` menu. +fn menu_items(ctx: &DbRenderCtx<'_>, column_id: &str) -> Vec<(&'static str, &'static str)> { + let col_type = ctx + .data + .columns + .iter() + .find(|c| c.id == column_id) + .map_or("title", |c| c.column_type.as_str()); + STAT_CALC_TYPES + .iter() + .filter(|(.., numeric)| !numeric || is_numeric_type(col_type)) + .map(|(id, label, ..)| (*id, *label)) + .collect() +} + +pub(super) fn measure_calc_menu(ctx: &DbRenderCtx<'_>, column_id: &str) -> (f32, f32) { + ( + 200.0, + menu_items(ctx, column_id).len() as f32 * MENU_ITEM_H + 8.0, + ) +} + +/// Paint the open `Calculate` menu of `column_id` at `rect` (screen space). +pub(super) fn render_calc_menu_at( + ctx: &DbRenderCtx<'_>, + column_id: &str, + rect: FlowRect, + prims: &mut Vec, + hits: &mut Vec, +) { + prims.push(DatabasePrim::Quad { + rect, + fill: Some(ctx.palette.panel), + border: Some(ctx.palette.border), + radius: 8.0, + dashed: false, + }); + let current = stat_calc_of(ctx, column_id); + for (idx, (id, label)) in menu_items(ctx, column_id).into_iter().enumerate() { + let item = FlowRect::new( + rect.x + 4.0, + rect.y + 4.0 + idx as f32 * MENU_ITEM_H, + rect.w - 8.0, + MENU_ITEM_H, + ); + let selected = id == current; + if selected { + prims.push(DatabasePrim::Quad { + rect: item, + fill: Some(ctx.palette.hover), + border: None, + radius: 4.0, + dashed: false, + }); + } + let ink = if selected { + ctx.palette.brand + } else { + ctx.palette.text_primary + }; + let style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px + 1.0, 400.0, ink); + prims.push(ctx.single_line_clipped( + label, + style.clone(), + item.x + 8.0, + item.y, + item.w - 36.0, + MENU_ITEM_H, + InlineAlign::Left, + )); + if selected { + prims.push(ctx.single_line_clipped( + "✓", + style, + item.right() - 24.0, + item.y, + 16.0, + MENU_ITEM_H, + InlineAlign::Center, + )); + } + hits.push(DatabaseAuthoringHit { + rect: item, + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::SetCalc { + column_id: column_id.to_string(), + calc: id.to_string(), + }), + scrolls_x: false, + }); + } +} + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::read::{DatabaseColumn, RichText}; + + use super::*; + + #[test] + fn compute_stat_covers_every_statistic_for_number_text_and_multi_select_columns() { + let column = |id: &str, ty: &str| DatabaseColumn { + id: id.to_string(), + name: id.to_string(), + column_type: ty.to_string(), + data: serde_json::json!({}), + }; + let row = |id: &str, title: &str| DatabaseRow { + row_id: id.to_string(), + title: RichText { + plain: title.to_string(), + delta: Vec::new(), + }, + created_at: None, + }; + let mut data = DatabaseData { + columns: vec![ + column("n", "number"), + column("t", "rich-text"), + column("m", "multi-select"), + ], + rows: vec![ + row("r1", "A"), + row("r2", ""), + row("r3", "C"), + row("r4", "D"), + ], + ..Default::default() + }; + for (r, n, t, m) in [ + ("r1", Some(1.5), "x", vec!["a", "b"]), + ("r2", Some(4.0), "", vec![]), + ("r3", None, "y", vec!["c"]), + ("r4", Some(-2.0), "z", vec![]), + ] { + if let Some(n) = n { + data.cells + .insert((r.into(), "n".into()), DatabaseCellValue::Number(n)); + } + data.cells + .insert((r.into(), "t".into()), DatabaseCellValue::Text(t.into())); + data.cells.insert( + (r.into(), "m".into()), + DatabaseCellValue::MultiSelect(m.into_iter().map(String::from).collect()), + ); + } + let rows = data.rows.clone(); + // (statistic, column, expected) + let cases = [ + ("none", "n", None), + ("count-all", "n", Some("4")), + ("count-values", "n", Some("3")), + ("count-empty", "n", Some("1")), + ("percent-empty", "n", Some("25%")), + ("percent-not-empty", "n", Some("75%")), + ("sum", "n", Some("3.5")), + ("avg", "n", Some("1.1667")), + ("min", "n", Some("-2")), + ("max", "n", Some("4")), + ("count-values", "t", Some("3")), + ("percent-not-empty", "t", Some("75%")), + ("sum", "t", None), + ("count-values", "m", Some("3")), + ("count-empty", "m", Some("2")), + ("count-empty", "title", Some("1")), + ]; + for (calc, col, expected) in cases { + let got = compute_stat(calc, &data, col, &rows).map(|s| { + s.trim_start_matches('\u{2066}') + .trim_end_matches('\u{2069}') + .to_string() + }); + assert_eq!(got.as_deref(), expected, "{calc} on {col}"); + } + assert_eq!( + compute_stat("percent-empty", &data, "n", &[]).as_deref(), + Some("0%") + ); + } +} diff --git a/blocksuite/crates/editor/src/database/cursor.rs b/blocksuite/crates/editor/src/database/cursor.rs index d145ca2584..cbf42db92c 100644 --- a/blocksuite/crates/editor/src/database/cursor.rs +++ b/blocksuite/crates/editor/src/database/cursor.rs @@ -74,6 +74,7 @@ pub fn database_authoring_hit_cursor( | DatabaseAuthoringHitKind::OpenRowPeek { .. } | DatabaseAuthoringHitKind::SwitchView { .. } => CursorStyle::PointingHand, DatabaseAuthoringHitKind::AddColumn + | DatabaseAuthoringHitKind::View(_) | DatabaseAuthoringHitKind::CreateProperty { .. } | DatabaseAuthoringHitKind::ToolbarProperties | DatabaseAuthoringHitKind::SetColumnHidden { .. } diff --git a/blocksuite/crates/editor/src/database/date_picker.rs b/blocksuite/crates/editor/src/database/date_picker.rs new file mode 100644 index 0000000000..e835215e60 --- /dev/null +++ b/blocksuite/crates/editor/src/database/date_picker.rs @@ -0,0 +1,302 @@ +//! `Date` cell picker popover (`0.27.5` `date-picker`): a month header with `Today` and month +//! paging, a Sunday-first `7 × 6` day grid that marks today and the picked day, and `Clear`. + +use blocksuite_playground_doc::read::DatabaseCellValue; + +use crate::{ + block_flow::{FlowRect, InlineAlign, InlineStyle, civil_from_days}, + theme::{FONT_SANS, TYPOGRAPHY}, +}; + +use super::{ + ActiveCellEditor, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseViewAction, + days_from_civil, local_day_index, + render::{DatabasePrim, DbRenderCtx}, + weekday_from_days, +}; + +const PAD: f32 = 10.0; +const HEADER_H: f32 = 32.0; +const WEEKDAY_H: f32 = 24.0; +const CELL_W: f32 = 32.0; +const CELL_H: f32 = 30.0; +const FOOTER_H: f32 = 30.0; + +const MONTHS: [&str; 12] = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; +const WEEKDAYS: [&str; 7] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]; + +/// Local day index of the stored value of the `Date` cell under `editor`. +pub(super) fn picked_day(ctx: &DbRenderCtx<'_>, editor: &ActiveCellEditor) -> Option { + let ts = ctx + .data + .cells + .get(&(editor.row_id.clone(), editor.column_id.clone())) + .and_then(DatabaseCellValue::as_i64)?; + Some(local_day_index(ts, ctx.offset_at_ms)) +} + +/// The `(year, month)` the picker shows: the paged month, else the month of the picked day, +/// else the current month. +pub(super) fn shown_month( + paged: Option<(i32, u32)>, + picked: Option, + today: i64, +) -> (i32, u32) { + paged.unwrap_or_else(|| { + let (y, m, _) = civil_from_days(picked.unwrap_or(today)); + (y as i32, m) + }) +} + +/// Step `(year, month)` by `delta` months. +pub(super) fn step_month((year, month): (i32, u32), delta: i32) -> (i32, u32) { + let total = year * 12 + month as i32 - 1 + delta; + (total.div_euclid(12), total.rem_euclid(12) as u32 + 1) +} + +/// The 42 day indexes of the Sunday-first grid that shows `(year, month)`. +pub(super) fn month_grid((year, month): (i32, u32)) -> [i64; 42] { + let first = days_from_civil(year, month, 1); + let start = first - i64::from(weekday_from_days(first)); + std::array::from_fn(|i| start + i as i64) +} + +pub(super) fn measure_date_picker() -> (f32, f32) { + ( + 7.0 * CELL_W + 2.0 * PAD, + 2.0 * PAD + HEADER_H + WEEKDAY_H + 6.0 * CELL_H + 6.0 + FOOTER_H, + ) +} + +fn push_button( + ctx: &DbRenderCtx<'_>, + rect: FlowRect, + label: &str, + action: DatabaseViewAction, + prims: &mut Vec, + hits: &mut Vec, +) { + prims.push(ctx.single_line_clipped( + label, + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 500.0, + ctx.palette.text_secondary, + ), + rect.x, + rect.y, + rect.w, + rect.h, + InlineAlign::Center, + )); + hits.push(DatabaseAuthoringHit { + rect, + kind: DatabaseAuthoringHitKind::View(action), + scrolls_x: false, + }); +} + +/// Paint the picker of the `Date` cell under `editor` at `rect` (screen space). +pub(super) fn render_date_picker_at( + ctx: &DbRenderCtx<'_>, + editor: &ActiveCellEditor, + rect: FlowRect, + prims: &mut Vec, + hits: &mut Vec, +) { + prims.push(DatabasePrim::Quad { + rect, + fill: Some(ctx.palette.panel), + border: Some(ctx.palette.border), + radius: 8.0, + dashed: false, + }); + let today = local_day_index(ctx.now_ms, ctx.offset_at_ms); + let picked = picked_day(ctx, editor); + let month = shown_month(ctx.ui_state.authoring.date_picker_month, picked, today); + let x0 = rect.x + PAD; + let mut y = rect.y + PAD; + + // 1. Header: `December 2026` with `Today`, `<` and `>`. + prims.push(ctx.single_line_clipped( + &format!("{} {}", MONTHS[month.1 as usize - 1], month.0), + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_sm_px, + 600.0, + ctx.palette.text_primary, + ), + x0 + 4.0, + y, + 7.0 * CELL_W - 112.0, + HEADER_H, + InlineAlign::Left, + )); + let right = x0 + 7.0 * CELL_W; + let nav_y = y + (HEADER_H - 24.0) * 0.5; + push_button( + ctx, + FlowRect::new(right - 108.0, nav_y, 52.0, 24.0), + "Today", + DatabaseViewAction::DatePickerToday, + prims, + hits, + ); + push_button( + ctx, + FlowRect::new(right - 52.0, nav_y, 24.0, 24.0), + "‹", + DatabaseViewAction::DatePickerStepMonth { delta: -1 }, + prims, + hits, + ); + push_button( + ctx, + FlowRect::new(right - 26.0, nav_y, 24.0, 24.0), + "›", + DatabaseViewAction::DatePickerStepMonth { delta: 1 }, + prims, + hits, + ); + y += HEADER_H; + + // 2. Weekday labels. + for (i, label) in WEEKDAYS.iter().enumerate() { + prims.push(ctx.single_line_clipped( + label, + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px, + 500.0, + ctx.palette.text_secondary, + ), + x0 + i as f32 * CELL_W, + y, + CELL_W, + WEEKDAY_H, + InlineAlign::Center, + )); + } + y += WEEKDAY_H; + + // 3. Day grid. + for (i, day) in month_grid(month).into_iter().enumerate() { + let cell = FlowRect::new( + x0 + (i % 7) as f32 * CELL_W, + y + (i / 7) as f32 * CELL_H, + CELL_W, + CELL_H, + ); + let mark = FlowRect::new(cell.x + 2.0, cell.y + 2.0, CELL_W - 4.0, CELL_H - 4.0); + let (_, m, d) = civil_from_days(day); + let is_picked = picked == Some(day); + let ink = if is_picked { + ui::white() + } else if day == today { + ctx.palette.brand + } else if m == month.1 { + ctx.palette.text_primary + } else { + ctx.palette.placeholder + }; + if is_picked || day == today { + prims.push(DatabasePrim::Quad { + rect: mark, + fill: is_picked.then_some(ctx.palette.brand), + border: (!is_picked).then_some(ctx.palette.brand), + radius: 6.0, + dashed: false, + }); + } + prims.push(ctx.single_line_clipped( + &d.to_string(), + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + if is_picked || day == today { + 600.0 + } else { + 400.0 + }, + ink, + ), + cell.x, + cell.y, + cell.w, + cell.h, + InlineAlign::Center, + )); + hits.push(DatabaseAuthoringHit { + rect: mark, + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::DatePickerPick { + day_index: day, + }), + scrolls_x: false, + }); + } + y += 6.0 * CELL_H + 6.0; + + // 4. Footer `Clear`. + prims.push(DbRenderCtx::hairline( + FlowRect::new(x0, y - 3.0, 7.0 * CELL_W, 1.0), + ctx.inside_border(), + )); + push_button( + ctx, + FlowRect::new(x0, y, 56.0, FOOTER_H), + "Clear", + DatabaseViewAction::DatePickerClear, + prims, + hits, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn month_grid_paging_and_shown_month_follow_the_civil_calendar() { + // (month, delta, stepped) + for (from, delta, to) in [ + ((2026, 12), 1, (2027, 1)), + ((2026, 1), -1, (2025, 12)), + ((2026, 6), -18, (2024, 12)), + ((2026, 6), 0, (2026, 6)), + ] { + assert_eq!(step_month(from, delta), to, "{from:?} {delta:+}"); + } + // (month, first grid day as (y, m, d), first-of-month slot) + for (month, first, slot) in [ + ((2026, 12), (2026, 11, 29), 2), + ((2026, 2), (2026, 2, 1), 0), + ((2024, 3), (2024, 2, 25), 5), + ] { + let grid = month_grid(month); + let (y, m, d) = civil_from_days(grid[0]); + assert_eq!((y as i32, m, d), first, "{month:?}"); + assert_eq!(weekday_from_days(grid[0]), 0, "{month:?} starts on Sunday"); + assert_eq!(civil_from_days(grid[slot]).2, 1, "{month:?}"); + assert_eq!(grid[41] - grid[0], 41); + } + let today = days_from_civil(2026, 12, 2); + let picked = days_from_civil(2025, 3, 9); + assert_eq!(shown_month(None, None, today), (2026, 12)); + assert_eq!(shown_month(None, Some(picked), today), (2025, 3)); + assert_eq!(shown_month(Some((2030, 7)), Some(picked), today), (2030, 7)); + } +} 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 3e706db28d..05356fdef6 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::{ - COLUMN_TYPES, InlineAxis, + COLUMN_TYPES, DatabaseViewAction, InlineAxis, authoring::{ActiveToolbarPanel, DatabaseAuthoringHit, DatabaseAuthoringHitKind}, cell_editor::parse_date_input_ms, format_database_date, 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 324e968923..6966843381 100644 --- a/blocksuite/crates/editor/src/database/filter_sort_bar/panels.rs +++ b/blocksuite/crates/editor/src/database/filter_sort_bar/panels.rs @@ -9,7 +9,7 @@ use crate::{ use super::{ ActiveToolbarPanel, COLUMN_TYPES, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePrim, - DbRenderCtx, parse_sort_rules, + DatabaseViewAction, DbRenderCtx, parse_sort_rules, }; pub(super) fn column_name_for<'a>(view_cols: &'a [DatabaseColumn], col_id: &'a str) -> &'a str { @@ -48,12 +48,24 @@ pub(super) fn toolbar_buttons<'a>( ), None => "Group by".to_string(), }; + let query = ctx.ui_state.search_query.trim(); + let search_label = if query.is_empty() { + "Search".to_string() + } else { + format!("Search: {query}") + }; let mut out = vec![( + ActiveToolbarPanel::Search, + search_label, + !query.is_empty(), + DatabaseAuthoringHitKind::View(DatabaseViewAction::ToggleSearch), + )]; + out.push(( ActiveToolbarPanel::Filter, filter_label, filter_count > 0, DatabaseAuthoringHitKind::ToolbarToggleFilter, - )]; + )); if view.mode != DatabaseViewMode::Calendar { out.push(( ActiveToolbarPanel::Sort, diff --git a/blocksuite/crates/editor/src/database/format.rs b/blocksuite/crates/editor/src/database/format.rs index 6e6cc59cac..33d17826de 100644 --- a/blocksuite/crates/editor/src/database/format.rs +++ b/blocksuite/crates/editor/src/database/format.rs @@ -30,6 +30,20 @@ pub fn isolate_ltr(text: &str) -> String { format!("\u{2066}{text}\u{2069}") } +/// Format the `number` cell `value` with the `format` and `decimal` settings of its column +/// `data`, as every view shows it. +pub fn format_number_cell(value: f64, data: &serde_json::Value) -> String { + let format = data + .get("format") + .and_then(serde_json::Value::as_str) + .unwrap_or("number"); + let decimals = data + .get("decimal") + .and_then(serde_json::Value::as_u64) + .map(|d| d as usize); + format_database_number(value, format, decimals) +} + /// Format a numeric database cell matching `0.27.5` `property-presets/number/utils/formatter.ts`, /// wrapped in `BidiIsolation::LtrIsolate`. pub fn format_database_number(value: f64, format: &str, decimals: Option) -> String { diff --git a/blocksuite/crates/editor/src/database/mod.rs b/blocksuite/crates/editor/src/database/mod.rs index 67bbae3d24..a98c632cec 100644 --- a/blocksuite/crates/editor/src/database/mod.rs +++ b/blocksuite/crates/editor/src/database/mod.rs @@ -2,14 +2,17 @@ //! `BidiIsolation::LtrIsolate`, query/filter/sort/group evaluation, DST-aware //! calendar month layout, and Page-mode Table / Kanban / Calendar renderers. +mod add_group; mod authoring; mod authoring_dispatch; mod authoring_id; +mod calculate; mod calendar; mod calendar_edit; mod cell_editor; mod column_ops; mod cursor; +mod date_picker; mod filter_sort_bar; mod format; mod group; @@ -20,10 +23,15 @@ mod render_calendar; mod render_kanban; mod render_kanban_card; mod render_table; +mod render_table_parts; mod render_types; mod row_ops; +mod search; mod select_popover; mod sort_key; +mod table_selection; +mod view_action; +mod view_config; mod view_tabs; use std::collections::{BTreeSet, HashMap}; @@ -37,6 +45,7 @@ pub use authoring::{ KanbanDragState, ProgressScrubPreview, commit_column_resize, handle_authoring_key, }; pub use authoring_dispatch::handle_authoring_hit; +pub use calculate::{STAT_CALC_TYPES, compute_stat, stat_calc_label}; pub use calendar::{ CalendarDayLayout, CalendarEntry, CalendarMonthLayout, CalendarRangeSegment, CalendarVisibleRange, create_calendar_month_layout, days_from_civil, @@ -65,8 +74,9 @@ pub use filter_sort_bar::{ }; pub use format::{ BidiIsolation, column_icon_name, format_database_created_time, format_database_date, - format_database_number, format_database_progress, isolate_bidi, isolate_ltr, - resolve_rich_text_plain, resolve_rich_text_query, resolve_tag_accent, resolve_tag_color, + format_database_number, format_database_progress, format_number_cell, isolate_bidi, + isolate_ltr, 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, PopoverTarget, layout_database_popover_overlay}; @@ -75,7 +85,13 @@ pub use render::{DatabaseLayoutOutput, DatabasePrim, layout_database_block}; pub use render_calendar::resolve_calendar_display_month; pub use render_types::DatabaseActiveCellLayout; pub use row_ops::{LaneMenuState, RowMenuState, resize_calendar_event_day}; +pub use search::row_matches_search; pub use select_popover::{SELECT_POPOVER_MAX_HEIGHT, select_popover_max_scroll}; +pub use table_selection::{ + DatabaseNavKey, ROW_SELECT_GUTTER_W, delete_rows, handle_navigation_key, +}; +pub use view_action::{DatabaseViewAction, handle_view_popover_key}; +pub use view_config::set_database_view_stat_calc; /// Unified logical-to-physical horizontal coordinate mapper shared by `affine:table` /// and `affine:database` (`Table`, `Kanban`, and `Calendar` views). @@ -162,6 +178,15 @@ pub struct DatabaseUiState { pub mobile_readonly_notice: bool, /// Group keys collapsed in Table view. pub collapsed_groups: BTreeSet, + /// Rows checked in the Table view (`0.27.5` row selection). Zero CRDT writeback. + pub selected_rows: BTreeSet, + /// Table cell `(row_id, column_id)` that keyboard navigation moves and `Enter` edits. + pub focused_cell: Option<(String, String)>, + /// Group of [`Self::focused_cell`] in a grouped Table, where a multi-select row shows in + /// each group of its tags. `None` stands for the first group that shows the row. + pub focused_group: Option, + /// Live search query of the toolbar `Search` field. It filters the visible rows only. + pub search_query: String, /// Transient desktop/writable authoring state (column menu, in-place cell editor, toolbar /// panels, resize/reorder/calendar drag previews). Zero CRDT writeback until committed. pub authoring: DatabaseAuthoringState, @@ -216,6 +241,10 @@ impl DatabaseFlowState { if entry.active_view_id.as_deref() != Some(next_id.as_str()) { entry.active_view_id = Some(next_id); entry.reveal_active_tab = true; + entry.selected_rows.clear(); + entry.focused_cell = None; + entry.focused_group = None; + entry.search_query.clear(); } entry.more_views_open = false; self.mark_dirty(block_id); @@ -458,19 +487,33 @@ pub fn filter_and_sort_view_rows( view: &blocksuite_playground_doc::read::DatabaseView, data: &blocksuite_playground_doc::read::DatabaseData, page_titles: &std::collections::BTreeMap, +) -> Vec { + filter_search_and_sort_view_rows(view, data, page_titles, "") +} + +/// [`filter_and_sort_view_rows`] that also keeps only the rows matching the toolbar search +/// `query` (see [`row_matches_search`]). An empty query keeps every row. +pub fn filter_search_and_sort_view_rows( + view: &blocksuite_playground_doc::read::DatabaseView, + data: &blocksuite_playground_doc::read::DatabaseData, + page_titles: &std::collections::BTreeMap, + query: &str, ) -> Vec { let sort_rules = sort_key::parse_active_sort_rules(view.sort.as_ref()); - if view.filter.is_none() && sort_rules.is_empty() { + let query = query.trim(); + if view.filter.is_none() && sort_rules.is_empty() && query.is_empty() { return data.rows.clone(); } - let filtered: Vec<&blocksuite_playground_doc::read::DatabaseRow> = match view.filter.as_ref() { - Some(f) => data - .rows - .iter() - .filter(|row| eval_database_filter_with_titles(f, data, row, page_titles)) - .collect(), - None => data.rows.iter().collect(), - }; + let filtered: Vec<&blocksuite_playground_doc::read::DatabaseRow> = data + .rows + .iter() + .filter(|row| { + view.filter + .as_ref() + .is_none_or(|f| eval_database_filter_with_titles(f, data, row, page_titles)) + && row_matches_search(data, row, query, page_titles) + }) + .collect(); if sort_rules.is_empty() { return filtered.into_iter().cloned().collect(); } diff --git a/blocksuite/crates/editor/src/database/popover_overlay.rs b/blocksuite/crates/editor/src/database/popover_overlay.rs index 3ac7bc54fd..852b76e281 100644 --- a/blocksuite/crates/editor/src/database/popover_overlay.rs +++ b/blocksuite/crates/editor/src/database/popover_overlay.rs @@ -14,11 +14,11 @@ use crate::{ }; use super::{ - DatabaseUiState, + ActiveToolbarPanel, DatabaseUiState, add_group, authoring::{DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabasePopoverAnchor}, - column_ops, eval_database_filter_with_titles, filter_sort_bar, + calculate, column_ops, date_picker, eval_database_filter_with_titles, filter_sort_bar, render::{DatabasePrim, DbRenderCtx}, - select_popover, sort_database_rows_with_titles, + search, select_popover, sort_database_rows_with_titles, view_tabs::tab_label_for, }; @@ -97,16 +97,16 @@ pub fn layout_database_popover_overlay( window: &Window, ) -> Option { let auth = &ui_state.authoring; - let has_select = !mobile_readonly - && auth - .active_cell - .as_ref() - .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select")); + let has_cell_popover = auth + .active_cell + .as_ref() + .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select" | "date")); let has_writable_popover = !mobile_readonly && (auth.column_menu.is_some() || auth.row_menu.is_some() || auth.lane_menu.is_some() - || has_select + || auth.calc_menu.is_some() + || has_cell_popover || auth.toolbar_panel.is_some()); let has_more_views = !form_factor.is_touch_form_factor() && ui_state.more_views_open; if !has_writable_popover && !has_more_views { @@ -140,6 +140,7 @@ pub fn layout_database_popover_overlay( data, view: active_view, rows: &ordered_rows, + selectable_rows: &[], ui_state, theme, palette, @@ -176,6 +177,17 @@ pub fn layout_database_popover_overlay( let mut prims = Vec::new(); let mut hits = Vec::new(); + let place = |size: (f32, f32)| { + place_popover( + anchor_screen, + size, + viewport, + Placement::BelowStart, + 4.0, + 8.0, + ) + .rect + }; let (bounds, submenu_bounds, text_input_rect) = if !mobile_readonly && let Some(menu) = &auth.column_menu @@ -240,6 +252,24 @@ pub fn layout_database_popover_overlay( let input_rect = select_popover::render_select_popover_at(&ctx, ed, placed.rect, &mut prims, &mut hits); (placed.rect, None, input_rect) + } else if !mobile_readonly + && let Some(ed) = auth.active_cell.as_ref().filter(|e| e.col_type == "date") + { + let placed = place(date_picker::measure_date_picker()); + date_picker::render_date_picker_at(&ctx, ed, placed, &mut prims, &mut hits); + (placed, None, None) + } else if !mobile_readonly && let Some((column_id, _)) = &auth.calc_menu { + let placed = place(calculate::measure_calc_menu(&ctx, column_id)); + calculate::render_calc_menu_at(&ctx, column_id, placed, &mut prims, &mut hits); + (placed, None, None) + } else if !mobile_readonly && auth.toolbar_panel == Some(ActiveToolbarPanel::Search) { + let placed = place(search::measure_search_panel()); + let field = search::render_search_panel_at(&ctx, placed, &mut prims, &mut hits); + (placed, None, Some(field)) + } else if !mobile_readonly && auth.toolbar_panel == Some(ActiveToolbarPanel::AddGroup) { + let placed = place(add_group::measure_add_group_panel()); + let field = add_group::render_add_group_panel_at(&ctx, placed, &mut prims, &mut hits); + (placed, None, Some(field)) } else if !mobile_readonly && let Some(panel) = auth.toolbar_panel { let size = filter_sort_bar::measure_toolbar_panel_size(&ctx, active_view, panel); let placed = place_popover( diff --git a/blocksuite/crates/editor/src/database/render.rs b/blocksuite/crates/editor/src/database/render.rs index 443254d5df..bfe913d528 100644 --- a/blocksuite/crates/editor/src/database/render.rs +++ b/blocksuite/crates/editor/src/database/render.rs @@ -17,8 +17,8 @@ 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, - render_kanban, render_table, + MOBILE_DATABASE_READONLY_NOTICE, filter_search_and_sort_view_rows, filter_sort_bar, + render_calendar, render_kanban, render_table, render_table_parts, }; /// Lay out an `affine:database` block with its header, view-switcher tabs, optional mobile @@ -160,6 +160,7 @@ pub fn layout_database_block( data, view: active_view, rows: &[], + selectable_rows: &[], ui_state, theme, palette, @@ -356,6 +357,7 @@ pub fn layout_database_block( data, view: active_view, rows: &[], + selectable_rows: &[], ui_state, theme, palette, @@ -522,12 +524,14 @@ pub fn layout_database_block( } // 4. Filter and sort rows for the active view. - let ordered_rows = filter_and_sort_view_rows(active_view, data, page_titles); + let ordered_rows = + filter_search_and_sort_view_rows(active_view, data, page_titles, &ui_state.search_query); let ctx = DbRenderCtx { data, view: active_view, rows: &ordered_rows, + selectable_rows: &[], ui_state, theme, palette, @@ -540,6 +544,11 @@ pub fn layout_database_block( page_titles, window, }; + let selectable_rows = render_table_parts::selectable_rows(&ctx); + let ctx = DbRenderCtx { + selectable_rows: &selectable_rows, + ..ctx + }; // 4b. Active Filter/Sort chips on Desktop (triggers already sit inline on the tab row) or // compact wrapping toolbar on Touch / narrow Desktop containers. Open dropdown panels @@ -557,7 +566,18 @@ pub fn layout_database_block( (next_y, inline_toolbar_anchor) }; - // 5. Render active view content starting at `y`. + // 5. A Table with checked rows shows its selection bar above the sideways scroll area, so + // the bar and its `Delete` / `Clear` targets stay in place while the table scrolls. + let y = if matches!( + active_view.mode, + DatabaseViewMode::Table | DatabaseViewMode::Unknown(_) + ) { + y + render_table_parts::render_selection_bar(&ctx, 8.0, y, &mut prims, &mut authoring_hits) + } else { + y + }; + + // 6. Render active view content starting at `y`. let content_top = y; let mut frozen = 0.0; let ( @@ -620,20 +640,28 @@ pub fn layout_database_block( let popover_anchor = if ui_state.authoring.column_menu.is_some() || ui_state.authoring.row_menu.is_some() || ui_state.authoring.lane_menu.is_some() + || ui_state.authoring.calc_menu.is_some() || ui_state .authoring .active_cell .as_ref() - .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) + .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select" | "date")) { view_popover_anchor - } else if ui_state.authoring.toolbar_panel == Some(super::ActiveToolbarPanel::NewView) { + } else if let Some( + panel @ (super::ActiveToolbarPanel::NewView | super::ActiveToolbarPanel::AddGroup), + ) = ui_state.authoring.toolbar_panel + { + let trigger = match panel { + super::ActiveToolbarPanel::NewView => super::DatabaseAuthoringHitKind::AddView, + _ => super::DatabaseAuthoringHitKind::View(super::DatabaseViewAction::OpenAddGroup), + }; authoring_hits .iter() - .find(|h| matches!(h.kind, super::DatabaseAuthoringHitKind::AddView)) + .find(|h| h.kind == trigger) .map(|h| DatabasePopoverAnchor { rect: h.rect, - scrolls_x: false, + scrolls_x: h.scrolls_x, }) } else if ui_state.authoring.toolbar_panel.is_some() { toolbar_anchor.map(|rect| DatabasePopoverAnchor { diff --git a/blocksuite/crates/editor/src/database/render_kanban.rs b/blocksuite/crates/editor/src/database/render_kanban.rs index f5221ac163..4f40866dda 100644 --- a/blocksuite/crates/editor/src/database/render_kanban.rs +++ b/blocksuite/crates/editor/src/database/render_kanban.rs @@ -9,7 +9,9 @@ use crate::{ use super::{ DatabaseActiveCellLayout, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseHitTarget, - DatabasePopoverAnchor, InlineAxis, group_view_rows_with_titles, + DatabasePopoverAnchor, InlineAxis, + add_group::{ADD_GROUP_W, can_add_group, push_add_group_button}, + group_view_rows_with_titles, render::{DatabasePrim, DbRenderCtx}, render_kanban_card::render_kanban_card, resolve_effective_group_by, resolve_tag_color, @@ -85,9 +87,16 @@ pub(super) fn render_kanban_view( ctx.page_titles, ); let lane_count = buckets.len().max(1); - let total_kanban_w = - lane_count as f32 * LANE_WIDTH + lane_count.saturating_sub(1) as f32 * LANE_GAP; - let axis = InlineAxis::new(ctx.direction, total_kanban_w); + let add_group = can_add_group(ctx, &group_by); + let add_group_w = if add_group { + ADD_GROUP_W + LANE_GAP + } else { + 0.0 + }; + let total_kanban_w = lane_count as f32 * LANE_WIDTH + + lane_count.saturating_sub(1) as f32 * LANE_GAP + + add_group_w; + let axis = InlineAxis::new(ctx.direction, total_kanban_w - add_group_w); let ordered_lanes = axis.order_indices(buckets.len()); // Visible card properties ordered by `view.columns` first, then remaining schema columns @@ -107,6 +116,10 @@ pub(super) fn render_kanban_view( } else { PAD_X }; + if add_group && ctx.direction.is_rtl() { + push_add_group_button(ctx, lane_x, top_y + 6.0, &mut prims, &mut authoring_hits); + lane_x += add_group_w; + } for &b_idx in &ordered_lanes { let bucket = &buckets[b_idx]; @@ -341,6 +354,9 @@ pub(super) fn render_kanban_view( lane_x += LANE_WIDTH + LANE_GAP; } + if add_group && !ctx.direction.is_rtl() { + push_add_group_button(ctx, lane_x, top_y + 6.0, &mut prims, &mut authoring_hits); + } let max_scroll_x = (total_kanban_w + 2.0 * PAD_X - ctx.width).max(0.0).ceil(); ( max_lane_h, diff --git a/blocksuite/crates/editor/src/database/render_kanban_card.rs b/blocksuite/crates/editor/src/database/render_kanban_card.rs index 23a4159adc..2002384865 100644 --- a/blocksuite/crates/editor/src/database/render_kanban_card.rs +++ b/blocksuite/crates/editor/src/database/render_kanban_card.rs @@ -14,7 +14,7 @@ use super::{ is_editable_column_type, kanban_active_rich_cell_from_laid, layout_rich_cell_sized, rich_cell_prim, }, - format_database_date, format_database_number, format_database_progress, + format_database_date, format_database_progress, format_number_cell, render::{DatabasePrim, DbRenderCtx}, resolve_rich_text_plain, resolve_tag_color, }; @@ -158,20 +158,10 @@ fn collect_kanban_card_props( } "number" => { if let Some(n) = val.as_f64() { - let fmt = col - .data - .get("format") - .and_then(serde_json::Value::as_str) - .unwrap_or("number"); - let dec = col - .data - .get("decimal") - .and_then(serde_json::Value::as_u64) - .map(|d| d as usize); prop_lines.push(KanbanProp::Text { col_id: col.id.clone(), col_type: col.column_type.clone(), - text: format_database_number(n, fmt, dec), + text: format_number_cell(n, &col.data), }); } } @@ -618,6 +608,12 @@ pub(super) fn render_kanban_card( .as_ref() .filter(|e| e.row_id == row.row_id && e.column_id == col_id); if let Some(ed) = active_ed { + if col_type == "date" { + *popover_anchor = Some(DatabasePopoverAnchor { + rect: prop_rect, + scrolls_x: true, + }); + } if matches!(col_type.as_str(), "select" | "multi-select") { *popover_anchor = Some(DatabasePopoverAnchor { rect: prop_rect, diff --git a/blocksuite/crates/editor/src/database/render_table.rs b/blocksuite/crates/editor/src/database/render_table.rs index fe01d5fdb8..c495449c03 100644 --- a/blocksuite/crates/editor/src/database/render_table.rs +++ b/blocksuite/crates/editor/src/database/render_table.rs @@ -8,8 +8,9 @@ use crate::{ }; use super::{ - DatabaseActiveCellLayout, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseHitKind, - DatabaseHitTarget, DatabasePopoverAnchor, InlineAxis, + DatabaseActiveCellLayout, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseGroupBucket, + DatabaseHitKind, DatabaseHitTarget, DatabasePopoverAnchor, InlineAxis, + calculate::render_calc_footer, cell_editor::{ is_editable_column_type, prelayout_table_row_rich_cells, rich_cell_prim, rich_cell_prim_with_hit, @@ -18,15 +19,16 @@ use super::{ column_ops::{ MIN_COLUMN_WIDTH, ResolvedTableCol, render_table_select_pills, resolve_visible_columns, }, - format_database_created_time, format_database_date, format_database_number, - format_database_progress, group_view_rows_with_titles, isolate_ltr, + format_database_created_time, format_database_date, format_database_progress, + format_number_cell, group_view_rows_with_titles, isolate_ltr, render::{DatabasePrim, DbRenderCtx}, - resolve_tag_color, + render_table_parts::{ + push_focus_outline, push_header_select, push_row_select, render_group_header, + }, }; const HEADER_HEIGHT: f32 = 34.0; const ROW_HEIGHT: f32 = 34.0; -const GROUP_HEADER_HEIGHT: f32 = 30.0; const PAD_X: f32 = 8.0; #[allow(clippy::type_complexity)] @@ -72,6 +74,13 @@ pub(super) fn render_table_view( let mut y = top_y; let border_col = ctx.inside_border(); + let show_calc = !ctx.mobile_readonly + || ctx.view.columns.iter().any(|c| { + c.stat_calc_type + .as_deref() + .is_some_and(|calc| calc != "none") + }); + push_header_select(ctx, start_x, y, HEADER_HEIGHT, &mut authoring_hits); // 1. Table header row (`table/pc/header/styles.ts`: primary bg + 1px top/bottom hairlines). prims.push(DbRenderCtx::hairline( FlowRect::new(start_x, y, total_table_w, 1.0), @@ -195,72 +204,33 @@ pub(super) fn render_table_view( ctx.offset_at_ms, ctx.page_titles, ); + // A multi-select row shows in each group of its tags; only the focused group (or the + // first group that shows the row) outlines its focused cell. + let shows = |b: &&DatabaseGroupBucket, row: &str| { + !ctx.ui_state.collapsed_groups.contains(&b.key) + && b.rows.iter().any(|r| r.row_id == row) + }; + let focus_group = ctx.ui_state.focused_cell.as_ref().and_then(|(row, _)| { + let focused = ctx.ui_state.focused_group.as_deref(); + buckets + .iter() + .filter(|b| shows(b, row)) + .find(|b| Some(b.key.as_str()) == focused) + .or_else(|| buckets.iter().find(|b| shows(b, row))) + .map(|b| b.key.clone()) + }); for bucket in buckets { let collapsed = ctx.ui_state.collapsed_groups.contains(&bucket.key); - let group_rect = FlowRect::new(start_x, y, total_table_w, GROUP_HEADER_HEIGHT); - prims.push(DbRenderCtx::hairline( - FlowRect::new(group_rect.x, group_rect.bottom() - 1.0, group_rect.w, 1.0), - border_col, - )); - let chev_x = if ctx.direction.is_rtl() { - group_rect.right() - 22.0 - } else { - group_rect.x + 8.0 - }; - prims.push(DatabasePrim::Chevron { - rect: FlowRect::new(chev_x, group_rect.y + 8.0, 14.0, 14.0), - collapsed, - color: ctx.palette.icon, - }); - let pill_label = format!("{} ({})", bucket.label, bucket.rows.len()); - let (pill_bg, pill_ink) = bucket - .color - .as_deref() - .map_or((ctx.palette.hover, ctx.palette.text_primary), |c| { - resolve_tag_color(c, ctx.theme) - }); - let label_x = if ctx.direction.is_rtl() { - group_rect.x + 8.0 - } else { - group_rect.x + 28.0 - }; - let label_w = (group_rect.w - 36.0).max(1.0); - let pill_style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, pill_ink); - let (_, pill_layout) = - ctx.truncate_text(&pill_label, pill_style, (label_w - 12.0).max(1.0), 20.0); - let pill_w = (pill_layout.content_width().ceil() + 12.0).min(label_w); - let pill_x = if ctx.direction.is_rtl() { - group_rect.right() - 28.0 - pill_w - } else { - label_x - }; - prims.push(DatabasePrim::Quad { - rect: FlowRect::new(pill_x, group_rect.y + 5.0, pill_w, 20.0), - fill: Some(pill_bg), - border: None, - radius: 4.0, - dashed: false, - }); - prims.push(DatabasePrim::Text { - x: pill_x + 6.0, - y: group_rect.y + 5.0, - layout: pill_layout, - clip: Some(FlowRect::new( - pill_x + 4.0, - group_rect.y + 5.0, - (pill_w - 8.0).max(1.0), - 20.0, - )), - }); - hits.push(DatabaseHitTarget { - rect: group_rect, - kind: DatabaseHitKind::ToggleGroup { - group_key: bucket.key.clone(), - }, - scrolls_x: true, - }); - y += GROUP_HEADER_HEIGHT; - + let focus_slot = focus_group.as_deref() == Some(bucket.key.as_str()); + y += render_group_header( + ctx, + &bucket, + start_x, + y, + total_table_w, + &mut prims, + &mut hits, + ); if !collapsed { for row in &bucket.rows { y += render_table_row( @@ -268,6 +238,7 @@ pub(super) fn render_table_view( &cols, &ordered_col_indices, row, + focus_slot, start_x, y, &mut prims, @@ -277,6 +248,20 @@ pub(super) fn render_table_view( &mut active_cell_rect, ); } + if show_calc { + y += render_calc_footer( + ctx, + &cols, + &ordered_col_indices, + &bucket.rows, + &bucket.key, + start_x, + y, + &mut prims, + &mut authoring_hits, + &mut popover_anchor, + ); + } } } } else if ctx.rows.is_empty() { @@ -307,6 +292,7 @@ pub(super) fn render_table_view( &cols, &ordered_col_indices, row, + true, start_x, y, &mut prims, @@ -351,6 +337,20 @@ pub(super) fn render_table_view( }); y += 30.0; } + if show_calc && ctx.view.group_by.is_none() { + y += render_calc_footer( + ctx, + &cols, + &ordered_col_indices, + ctx.rows, + "", + start_x, + y, + &mut prims, + &mut authoring_hits, + &mut popover_anchor, + ); + } let max_scroll_x = (total_table_w + 2.0 * PAD_X - ctx.width).max(0.0).ceil(); if max_scroll_x > 0.0 @@ -385,6 +385,7 @@ fn render_table_row( cols: &[ResolvedTableCol<'_>], ordered_col_indices: &[usize], row: &DatabaseRow, + focus_slot: bool, start_x: f32, y: f32, prims: &mut Vec, @@ -401,6 +402,17 @@ fn render_table_row( let (rich_layouts, row_h) = prelayout_table_row_rich_cells(ctx, cols, ordered_col_indices, row, ROW_HEIGHT, align); let border_col = ctx.inside_border(); + let row_w = cols.iter().map(|c| c.width).sum(); + push_row_select( + ctx, + &row.row_id, + start_x, + y, + row_w, + row_h, + prims, + authoring_hits, + ); let mut cell_x = start_x; for (slot_idx, &c_idx) in ordered_col_indices.iter().enumerate() { let col = &cols[c_idx]; @@ -442,6 +454,12 @@ fn render_table_row( let inner_x = cell_rect.x + 8.0; let inner_w = (cell_rect.w - 16.0).max(1.0); if let Some(ed) = active_ed { + if col.col_type == "date" { + *popover_anchor = Some(DatabasePopoverAnchor { + rect: cell_rect, + scrolls_x: true, + }); + } if matches!(col.col_type.as_str(), "select" | "multi-select") { *popover_anchor = Some(DatabasePopoverAnchor { rect: cell_rect, @@ -640,17 +658,10 @@ fn render_table_row( match col.col_type.as_str() { "number" => { if let Some(val) = cell_val.and_then(DatabaseCellValue::as_f64) { - let fmt = col - .schema - .and_then(|c| c.data.get("format")) - .and_then(serde_json::Value::as_str) - .unwrap_or("number"); - let dec = col - .schema - .and_then(|c| c.data.get("decimal")) - .and_then(serde_json::Value::as_u64) - .map(|d| d as usize); - let formatted = format_database_number(val, fmt, dec); + let formatted = format_number_cell( + val, + col.schema.map_or(&serde_json::Value::Null, |c| &c.data), + ); push_text( &formatted, TYPOGRAPHY.font_sm_px, @@ -750,6 +761,9 @@ fn render_table_row( scrolls_x: true, }); } + if focus_slot { + push_focus_outline(ctx, &row.row_id, &col.id, cell_rect, prims); + } cell_x += col.width; } if ctx.mobile_readonly { diff --git a/blocksuite/crates/editor/src/database/render_table_parts.rs b/blocksuite/crates/editor/src/database/render_table_parts.rs new file mode 100644 index 0000000000..c9c6557fc6 --- /dev/null +++ b/blocksuite/crates/editor/src/database/render_table_parts.rs @@ -0,0 +1,272 @@ +//! Table view parts around the cell grid: group headers, the row selection bar and checkbox +//! targets, and the focused cell outline. + +use blocksuite_playground_doc::read::DatabaseViewMode; + +use crate::{ + block_flow::{FlowRect, InlineAlign, InlineStyle}, + theme::{FONT_SANS, TYPOGRAPHY}, +}; + +use super::{ + DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseGroupBucket, DatabaseHitKind, + DatabaseHitTarget, DatabaseViewAction, ROW_SELECT_GUTTER_W, + render::{DatabasePrim, DbRenderCtx}, + resolve_tag_color, + table_selection::{selectable_row_ids, table_row_slots}, +}; + +pub(super) const GROUP_HEADER_HEIGHT: f32 = 30.0; +const SELECTION_BAR_H: f32 = 32.0; + +/// Paint the collapsible header of one group (`table/pc/group.ts`) at `y` and return its height. +pub(super) fn render_group_header( + ctx: &DbRenderCtx<'_>, + bucket: &DatabaseGroupBucket, + start_x: f32, + y: f32, + total_w: f32, + prims: &mut Vec, + hits: &mut Vec, +) -> f32 { + let collapsed = ctx.ui_state.collapsed_groups.contains(&bucket.key); + let group_rect = FlowRect::new(start_x, y, total_w, GROUP_HEADER_HEIGHT); + prims.push(DbRenderCtx::hairline( + FlowRect::new(group_rect.x, group_rect.bottom() - 1.0, group_rect.w, 1.0), + ctx.inside_border(), + )); + let rtl = ctx.direction.is_rtl(); + let chev_x = if rtl { + group_rect.right() - 22.0 + } else { + group_rect.x + 8.0 + }; + prims.push(DatabasePrim::Chevron { + rect: FlowRect::new(chev_x, group_rect.y + 8.0, 14.0, 14.0), + collapsed, + color: ctx.palette.icon, + }); + let pill_label = format!("{} ({})", bucket.label, bucket.rows.len()); + let (pill_bg, pill_ink) = bucket + .color + .as_deref() + .map_or((ctx.palette.hover, ctx.palette.text_primary), |c| { + resolve_tag_color(c, ctx.theme) + }); + let label_w = (group_rect.w - 36.0).max(1.0); + let pill_style = InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px, 500.0, pill_ink); + let (_, pill_layout) = + ctx.truncate_text(&pill_label, pill_style, (label_w - 12.0).max(1.0), 20.0); + let pill_w = (pill_layout.content_width().ceil() + 12.0).min(label_w); + let pill_x = if rtl { + group_rect.right() - 28.0 - pill_w + } else { + group_rect.x + 28.0 + }; + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(pill_x, group_rect.y + 5.0, pill_w, 20.0), + fill: Some(pill_bg), + border: None, + radius: 4.0, + dashed: false, + }); + prims.push(DatabasePrim::Text { + x: pill_x + 6.0, + y: group_rect.y + 5.0, + layout: pill_layout, + clip: Some(FlowRect::new( + pill_x + 4.0, + group_rect.y + 5.0, + (pill_w - 8.0).max(1.0), + 20.0, + )), + }); + hits.push(DatabaseHitTarget { + rect: group_rect, + kind: DatabaseHitKind::ToggleGroup { + group_key: bucket.key.clone(), + }, + scrolls_x: true, + }); + GROUP_HEADER_HEIGHT +} + +/// The checkbox target of a Table row (or of the header, for select-all) in the gutter left of +/// `start_x`. It never scrolls with the cells. +fn gutter_rect(start_x: f32, y: f32, h: f32) -> FlowRect { + FlowRect::new(start_x - ROW_SELECT_GUTTER_W, y, ROW_SELECT_GUTTER_W, h) +} + +/// Highlight a checked row and add the checkbox target of `row_id`. +#[allow(clippy::too_many_arguments)] +pub(super) fn push_row_select( + ctx: &DbRenderCtx<'_>, + row_id: &str, + start_x: f32, + y: f32, + row_w: f32, + row_h: f32, + prims: &mut Vec, + authoring_hits: &mut Vec, +) { + if ctx.mobile_readonly { + return; + } + if ctx.ui_state.selected_rows.contains(row_id) { + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(start_x, y, row_w, row_h), + fill: Some(ctx.palette.brand.opacity(0.06)), + border: None, + radius: 0.0, + dashed: false, + }); + } + authoring_hits.push(DatabaseAuthoringHit { + rect: gutter_rect(start_x, y, row_h), + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::ToggleRowSelected { + row_id: row_id.to_string(), + }), + scrolls_x: false, + }); +} + +/// The rows that select-all and the selection bar of the Table in `ctx` act on (see +/// [`table_row_slots`]). A Kanban or Calendar view has none. +pub(super) fn selectable_rows(ctx: &DbRenderCtx<'_>) -> Vec { + if matches!( + ctx.view.mode, + DatabaseViewMode::Kanban | DatabaseViewMode::Calendar + ) { + return Vec::new(); + } + let slots = table_row_slots( + ctx.view, + ctx.data, + ctx.rows, + &ctx.ui_state.collapsed_groups, + ctx.now_ms, + ctx.offset_at_ms, + ctx.page_titles, + ); + selectable_row_ids(&slots) +} + +/// Add the select-all checkbox target of the header row at `y`. +pub(super) fn push_header_select( + ctx: &DbRenderCtx<'_>, + start_x: f32, + y: f32, + h: f32, + authoring_hits: &mut Vec, +) { + if ctx.mobile_readonly || ctx.selectable_rows.is_empty() { + return; + } + authoring_hits.push(DatabaseAuthoringHit { + rect: gutter_rect(start_x, y, h), + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::ToggleAllRowsSelected { + row_ids: ctx.selectable_rows.to_vec(), + }), + scrolls_x: false, + }); +} + +/// Paint the bar that counts the checked rows and offers `Delete` and `Clear` at `y`. Returns +/// its height, or `0` when no row is checked. +pub(super) fn render_selection_bar( + ctx: &DbRenderCtx<'_>, + start_x: f32, + y: f32, + prims: &mut Vec, + authoring_hits: &mut Vec, +) -> f32 { + let selected: Vec = ctx + .selectable_rows + .iter() + .filter(|id| ctx.ui_state.selected_rows.contains(*id)) + .cloned() + .collect(); + if ctx.mobile_readonly || selected.is_empty() { + return 0.0; + } + let count = selected.len(); + let bar_h = SELECTION_BAR_H - 6.0; + let label = format!("{count} selected"); + let style = |ink| InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_xs_px + 1.0, 500.0, ink); + let label_prim = ctx.single_line_clipped( + &label, + style(ctx.palette.text_primary), + start_x + 10.0, + y, + 110.0, + bar_h, + InlineAlign::Left, + ); + let mut x = start_x + 120.0; + let mut buttons = Vec::new(); + for (text, ink, action) in [ + ( + "Delete", + ctx.theme + .css_var("--affine-v2-status-error") + .unwrap_or(ctx.palette.brand), + DatabaseViewAction::DeleteSelectedRows { row_ids: selected }, + ), + ( + "Clear", + ctx.palette.text_secondary, + DatabaseViewAction::ClearRowSelection, + ), + ] { + let rect = FlowRect::new(x, y + 1.0, 60.0, bar_h - 2.0); + buttons.push(ctx.single_line_clipped( + text, + style(ink), + rect.x, + y, + rect.w, + bar_h, + InlineAlign::Center, + )); + authoring_hits.push(DatabaseAuthoringHit { + rect, + kind: DatabaseAuthoringHitKind::View(action), + scrolls_x: false, + }); + x += 64.0; + } + prims.push(DatabasePrim::Quad { + rect: FlowRect::new(start_x, y, x - start_x + 4.0, bar_h), + fill: Some(ctx.palette.brand.opacity(0.08)), + border: Some(ctx.palette.brand.opacity(0.3)), + radius: 6.0, + dashed: false, + }); + prims.push(label_prim); + prims.extend(buttons); + SELECTION_BAR_H +} + +/// Outline the focused cell `(row_id, column_id)` when no inline editor is open on it. +pub(super) fn push_focus_outline( + ctx: &DbRenderCtx<'_>, + row_id: &str, + column_id: &str, + cell_rect: FlowRect, + prims: &mut Vec, +) { + let focused = ctx + .ui_state + .focused_cell + .as_ref() + .is_some_and(|(r, c)| r == row_id && c == column_id); + if focused && ctx.ui_state.authoring.active_cell.is_none() && !ctx.mobile_readonly { + prims.push(DatabasePrim::Quad { + rect: cell_rect, + fill: None, + border: Some(ctx.palette.brand), + radius: 0.0, + dashed: false, + }); + } +} diff --git a/blocksuite/crates/editor/src/database/render_types.rs b/blocksuite/crates/editor/src/database/render_types.rs index ed40a00da5..475f0da428 100644 --- a/blocksuite/crates/editor/src/database/render_types.rs +++ b/blocksuite/crates/editor/src/database/render_types.rs @@ -79,6 +79,8 @@ pub(super) struct DbRenderCtx<'a> { pub data: &'a DatabaseData, pub view: &'a DatabaseView, pub rows: &'a [DatabaseRow], + /// The rows that select-all and the selection bar of a Table act on. + pub selectable_rows: &'a [String], pub ui_state: &'a DatabaseUiState, pub theme: PlaygroundTheme, pub palette: Palette, diff --git a/blocksuite/crates/editor/src/database/row_ops.rs b/blocksuite/crates/editor/src/database/row_ops.rs index ff7457691d..2a12eb4f3c 100644 --- a/blocksuite/crates/editor/src/database/row_ops.rs +++ b/blocksuite/crates/editor/src/database/row_ops.rs @@ -272,6 +272,7 @@ pub(super) fn render_lane_menu_at( IconPaint::named(if delete { "DeleteIcon" } else { "GroupByIcon" }), DatabaseAuthoringHitKind::KanbanLaneCards { column_id: menu.column_id.clone(), + bucket_key: menu.bucket_key.clone(), rows: rows.clone(), delete, }, @@ -469,13 +470,28 @@ pub(super) fn handle_lane_menu_action( } DatabaseAuthoringHitKind::KanbanLaneCards { column_id, + bucket_key, rows, delete, } => { + // `0.27.5` `removeFromGroup`: a multi-select lane drops only its own tag. + let multi = data + .columns + .iter() + .any(|c| c.id == *column_id && c.column_type == "multi-select"); let commit = page.structural_edit(now_ms, |page| { for row in rows { if *delete { page.delete_database_row(block_id, row, now_ms)?; + } else if multi { + page.move_database_multi_select_group( + block_id, + row, + column_id, + Some(bucket_key.as_str()), + None, + now_ms, + )?; } else { page.set_database_cell_value( block_id, diff --git a/blocksuite/crates/editor/src/database/search.rs b/blocksuite/crates/editor/src/database/search.rs new file mode 100644 index 0000000000..03f4ca0bb2 --- /dev/null +++ b/blocksuite/crates/editor/src/database/search.rs @@ -0,0 +1,223 @@ +//! Toolbar `Search` (`0.27.5` `data-view` quick search): case-insensitive substring matching of +//! a row's displayed values, and the search field popover. The query is view state only. + +use std::collections::BTreeMap; + +use blocksuite_playground_doc::read::{DatabaseCellValue, DatabaseData, DatabaseRow}; + +use crate::{ + block_flow::{FlowRect, InlineAlign, InlineStyle}, + theme::{FONT_SANS, TYPOGRAPHY}, +}; + +use super::{ + DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseViewAction, format_database_progress, + format_number_cell, + render::{DatabasePrim, DbRenderCtx}, + resolve_rich_text_plain, +}; + +const FIELD_H: f32 = 28.0; +const PAD: f32 = 8.0; + +/// Whether `row` shows `query` (case-insensitive) in its title or in the displayed value of a +/// text, number, progress, select, or link cell. Numbers match as the column formats them. An empty query matches every row. +pub fn row_matches_search( + data: &DatabaseData, + row: &DatabaseRow, + query: &str, + page_titles: &BTreeMap, +) -> bool { + let needle = query.trim().to_lowercase(); + if needle.is_empty() { + return true; + } + let hit = |text: &str| text.to_lowercase().contains(&needle); + if hit(&resolve_rich_text_plain(&row.title, page_titles)) { + return true; + } + data.columns.iter().any(|col| { + let Some(value) = data.cells.get(&(row.row_id.clone(), col.id.clone())) else { + return false; + }; + let options = col.select_options(); + let option_label = |id: &str| { + options + .iter() + .find(|o| o.id == id) + .is_some_and(|o| hit(&o.value)) + }; + match (col.column_type.as_str(), value) { + ("select" | "multi-select", DatabaseCellValue::MultiSelect(ids)) => { + ids.iter().any(|id| option_label(id)) + } + ("select" | "multi-select", DatabaseCellValue::Text(id)) => option_label(id), + ("number", v) => v + .as_f64() + .is_some_and(|n| hit(&format_number_cell(n, &col.data))), + ("progress", v) => v + .as_i64() + .is_some_and(|n| hit(&format_database_progress(n).1)), + ("checkbox" | "date" | "created-time", _) => false, + (_, DatabaseCellValue::RichText(rt)) => hit(&resolve_rich_text_plain(rt, page_titles)), + (_, DatabaseCellValue::Text(s)) => hit(s), + _ => false, + } + }) +} + +pub(super) fn measure_search_panel() -> (f32, f32) { + (260.0, FIELD_H + 2.0 * PAD) +} + +/// Paint the open search field popover at `rect` (screen space). Returns the rect of its text +/// field. +pub(super) fn render_search_panel_at( + ctx: &DbRenderCtx<'_>, + rect: FlowRect, + prims: &mut Vec, + hits: &mut Vec, +) -> FlowRect { + prims.push(DatabasePrim::Quad { + rect, + fill: Some(ctx.palette.panel), + border: Some(ctx.palette.border), + radius: 8.0, + dashed: false, + }); + let clear_w = 24.0; + let field = FlowRect::new( + rect.x + PAD, + rect.y + PAD, + rect.w - 2.0 * PAD - clear_w - 4.0, + FIELD_H, + ); + prims.push(DatabasePrim::Quad { + rect: field, + fill: Some(ctx.palette.background), + border: Some(ctx.palette.brand), + radius: 4.0, + dashed: false, + }); + if ctx.ui_state.search_query.is_empty() { + prims.push(ctx.single_line_clipped( + "Search…", + InlineStyle::new( + FONT_SANS, + TYPOGRAPHY.font_xs_px + 1.0, + 400.0, + ctx.palette.placeholder, + ), + field.x + 8.0, + field.y, + field.w - 16.0, + FIELD_H, + InlineAlign::Left, + )); + } + let clear = FlowRect::new( + field.right() + 4.0, + field.y + (FIELD_H - clear_w) * 0.5, + clear_w, + clear_w, + ); + prims.push(ctx.single_line_clipped( + "×", + InlineStyle::new(FONT_SANS, TYPOGRAPHY.font_base_px, 400.0, ctx.palette.icon), + clear.x, + clear.y, + clear.w, + clear.h, + InlineAlign::Center, + )); + hits.push(DatabaseAuthoringHit { + rect: clear, + kind: DatabaseAuthoringHitKind::View(DatabaseViewAction::ClearSearch), + scrolls_x: false, + }); + field +} + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::read::{DatabaseColumn, RichText}; + + use super::*; + + #[test] + fn row_matches_search_reads_titles_text_formatted_numbers_progress_and_option_labels_case_insensitively() + { + let column = |id: &str, ty: &str, data: serde_json::Value| DatabaseColumn { + id: id.to_string(), + name: id.to_string(), + column_type: ty.to_string(), + data, + }; + let mut data = DatabaseData { + columns: vec![ + column("t", "rich-text", serde_json::json!({})), + column( + "n", + "number", + serde_json::json!({ "format": "numberWithCommas" }), + ), + column( + "s", + "select", + serde_json::json!({ "options": [{ "id": "o1", "value": "Done", "color": "x" }] }), + ), + column("c", "checkbox", serde_json::json!({})), + column("d", "number", serde_json::json!({ "decimal": 2 })), + column("p", "progress", serde_json::json!({})), + ], + ..Default::default() + }; + let row = DatabaseRow { + row_id: "r1".into(), + title: RichText { + plain: "Quarterly Plan".into(), + delta: Vec::new(), + }, + created_at: None, + }; + data.cells.insert( + ("r1".into(), "t".into()), + DatabaseCellValue::Text("Budget review".into()), + ); + data.cells.insert( + ("r1".into(), "n".into()), + DatabaseCellValue::Number(12345.0), + ); + data.cells.insert( + ("r1".into(), "s".into()), + DatabaseCellValue::Text("o1".into()), + ); + data.cells + .insert(("r1".into(), "c".into()), DatabaseCellValue::Bool(true)); + data.cells + .insert(("r1".into(), "d".into()), DatabaseCellValue::Number(1.5)); + data.cells + .insert(("r1".into(), "p".into()), DatabaseCellValue::Integer(40)); + let titles = BTreeMap::new(); + for (query, expected) in [ + ("", true), + (" ", true), + ("quarterly", true), + ("PLAN", true), + ("budget", true), + ("12,345", true), + ("done", true), + ("1.50", true), + ("40%", true), + ("o1", false), + ("true", false), + ("missing", false), + ] { + assert_eq!( + row_matches_search(&data, &row, query, &titles), + expected, + "{query:?}" + ); + } + } +} diff --git a/blocksuite/crates/editor/src/database/select_popover.rs b/blocksuite/crates/editor/src/database/select_popover.rs index 2040583d28..b30f95bdc3 100644 --- a/blocksuite/crates/editor/src/database/select_popover.rs +++ b/blocksuite/crates/editor/src/database/select_popover.rs @@ -576,7 +576,15 @@ pub(super) fn save_option( .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(); + // A color swatch on an untyped name writes only the color: the name stays the live + // one, so a peer's rename that arrived while the menu was open survives. A typed name + // goes out with the swatch color, or with the live color on `Enter` / `Save name`. + let name_typed = ed.select_filter.trim() != auth.option_menu_name.trim(); + let label = if color.is_some() && !name_typed { + opt.value.as_str() + } else { + ed.select_filter.trim() + }; let color = color.unwrap_or(&opt.color); if !label.is_empty() && (label != opt.value || color != opt.color) { mutated = page diff --git a/blocksuite/crates/editor/src/database/table_selection.rs b/blocksuite/crates/editor/src/database/table_selection.rs new file mode 100644 index 0000000000..329e322896 --- /dev/null +++ b/blocksuite/crates/editor/src/database/table_selection.rs @@ -0,0 +1,557 @@ +//! Table row selection (`0.27.5` row checkboxes and select-all), batch row deletion in one undo +//! step, and keyboard navigation of the focused Table cell. + +use std::collections::{BTreeMap, BTreeSet}; + +use blocksuite_playground_doc::{ + DocResult, + read::{DatabaseData, DatabaseRow, DatabaseView, DatabaseViewMode}, + session::PageDocSession, +}; + +use crate::block_flow::FlowRect; + +use super::{ + AuthoringActionResult, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseFlowState, + authoring::resolve_active_view, column_ops::resolve_visible_columns, + filter_search_and_sort_view_rows, group_view_rows_with_titles, handle_authoring_hit, +}; + +/// Width of the row checkbox target in the gutter left of each Table row. +pub const ROW_SELECT_GUTTER_W: f32 = 18.0; + +/// Navigation key for the focused Table cell (no inline editor open). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DatabaseNavKey { + Up, + Down, + Left, + Right, + Tab, + ShiftTab, + Enter, + Delete, + Escape, +} + +impl DatabaseFlowState { + /// Check or uncheck one Table row. + pub fn toggle_row_selected(&mut self, block_id: &str, row_id: &str) { + let entry = self.ui_states.entry(block_id.to_string()).or_default(); + if !entry.selected_rows.remove(row_id) { + entry.selected_rows.insert(row_id.to_string()); + } + self.mark_dirty(block_id); + } + + /// Check exactly the rows `row_ids` (the rows the view shows), or uncheck every row when + /// each of them is checked already. + pub fn toggle_rows_selected(&mut self, block_id: &str, row_ids: &[String]) { + let entry = self.ui_states.entry(block_id.to_string()).or_default(); + let all = row_ids.iter().all(|id| entry.selected_rows.contains(id)); + entry.selected_rows = if all { + BTreeSet::new() + } else { + row_ids.iter().cloned().collect() + }; + self.mark_dirty(block_id); + } + + /// Keep only the checked rows that the active Table view of `block_id` still shows (see + /// [`table_row_slots`]), and drop the focus of a row it no longer shows. The host calls + /// this after each snapshot refresh and search change, so a row that a filter, a search, + /// a hidden group, or a peer hid is never deleted or counted. + pub fn prune_row_selection( + &mut self, + block_id: &str, + data: &DatabaseData, + page_titles: &BTreeMap, + offset_at_ms: &dyn Fn(i64) -> i32, + ) { + let Some(entry) = self.ui_states.get(block_id) else { + return; + }; + if entry.selected_rows.is_empty() && entry.focused_cell.is_none() { + return; + } + let shown = shown_table_rows(self, block_id, data, page_titles, offset_at_ms); + let entry = self.ui_states.entry(block_id.to_string()).or_default(); + let before = (entry.selected_rows.len(), entry.focused_cell.is_some()); + entry.selected_rows.retain(|id| shown.contains(id)); + if entry + .focused_cell + .as_ref() + .is_some_and(|(row, _)| !shown.contains(row)) + { + entry.focused_cell = None; + entry.focused_group = None; + } + if before != (entry.selected_rows.len(), entry.focused_cell.is_some()) { + self.mark_dirty(block_id); + } + } + + /// Drop the row selection and the focused cell of `block_id`. Returns whether either was set. + pub fn clear_table_focus(&mut self, block_id: &str) -> bool { + let Some(entry) = self.ui_states.get_mut(block_id) else { + return false; + }; + if entry.selected_rows.is_empty() && entry.focused_cell.is_none() { + return false; + } + entry.selected_rows.clear(); + entry.focused_cell = None; + entry.focused_group = None; + self.mark_dirty(block_id); + true + } + + /// Move the focused cell to the cell of the open inline editor of a Table view, so keyboard + /// navigation continues from there once the editor closes. `group_key` is the group the + /// editor opened in, when the Table is grouped: a row can show in several groups. + pub fn follow_active_cell( + &mut self, + block_id: &str, + data: &DatabaseData, + group_key: Option<&str>, + ) { + let is_table = resolve_active_view(data, self, block_id).is_none_or(|v| { + !matches!( + v.mode, + DatabaseViewMode::Kanban | DatabaseViewMode::Calendar + ) + }); + let Some(entry) = self.ui_states.get_mut(block_id) else { + return; + }; + let Some(ed) = entry.authoring.active_cell.as_ref() else { + return; + }; + let cell = (ed.row_id.clone(), ed.column_id.clone()); + if is_table && entry.focused_cell.as_ref() != Some(&cell) { + entry.focused_cell = Some(cell); + entry.focused_group = group_key.map(str::to_string); + self.mark_dirty(block_id); + } + } + + /// Whether `block_id` has a focused cell or checked rows that take navigation keys. + pub fn has_table_focus(&self, block_id: &str) -> bool { + self.ui_states + .get(block_id) + .is_some_and(|s| s.focused_cell.is_some() || !s.selected_rows.is_empty()) + } +} + +/// One shown Table row: the group it shows in (`None` when the view is not grouped) and its +/// row id. A multi-select grouping shows one row in each group of its tags. +pub(super) type RowSlot = (Option, String); + +/// The rows that the Table view `view` shows, in display order. `rows` are the rows that its +/// filter and search let through. A grouped view shows only the rows of each group that +/// `groupProperties[].hide` does not hide and that is not in `collapsed`. Row checkboxes, +/// select-all, the selection bar, `Delete`, and keyboard focus all use these slots. +pub(super) fn table_row_slots( + view: &DatabaseView, + data: &DatabaseData, + rows: &[DatabaseRow], + collapsed: &BTreeSet, + now_ms: i64, + offset_at_ms: &dyn Fn(i64) -> i32, + page_titles: &BTreeMap, +) -> Vec { + let Some(group_by) = &view.group_by else { + return rows.iter().map(|r| (None, r.row_id.clone())).collect(); + }; + group_view_rows_with_titles( + rows, + view, + group_by, + data, + now_ms, + offset_at_ms, + page_titles, + ) + .into_iter() + .filter(|b| !collapsed.contains(&b.key)) + .flat_map(|b| { + let key = b.key; + b.rows + .into_iter() + .map(move |r| (Some(key.clone()), r.row_id)) + }) + .collect() +} + +/// The row ids of `slots`, each once, in display order. +pub(super) fn selectable_row_ids(slots: &[RowSlot]) -> Vec { + let mut seen = BTreeSet::new(); + slots + .iter() + .filter(|(_, row)| seen.insert(row.as_str())) + .map(|(_, row)| row.clone()) + .collect() +} + +/// The active view of `block_id` when it is a Table, with its shown row slots. +fn active_table_slots<'a>( + flow_state: &DatabaseFlowState, + block_id: &str, + data: &'a DatabaseData, + page_titles: &BTreeMap, + offset_at_ms: &dyn Fn(i64) -> i32, +) -> Option<(&'a DatabaseView, Vec)> { + let view = resolve_active_view(data, flow_state, block_id)?; + if matches!( + view.mode, + DatabaseViewMode::Kanban | DatabaseViewMode::Calendar + ) { + return None; + } + let ui = flow_state.state_for(block_id); + let rows = filter_search_and_sort_view_rows(view, data, page_titles, &ui.search_query); + let slots = table_row_slots( + view, + data, + &rows, + &ui.collapsed_groups, + flow_state.clock_ms, + offset_at_ms, + page_titles, + ); + Some((view, slots)) +} + +/// Rows that the active Table view of `block_id` shows (see [`table_row_slots`]). +fn shown_table_rows( + flow_state: &DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + page_titles: &BTreeMap, + offset_at_ms: &dyn Fn(i64) -> i32, +) -> BTreeSet { + active_table_slots(flow_state, block_id, data, page_titles, offset_at_ms) + .map(|(_, slots)| slots.into_iter().map(|(_, row)| row).collect()) + .unwrap_or_default() +} + +/// Delete the rows `row_ids` of `block_id` that still exist in one tracked undo step and clear +/// the selection. The caller passes only checked rows that the view shows. Returns whether the +/// document changed. +pub fn delete_rows( + page: &mut PageDocSession, + flow_state: &mut DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + row_ids: &[String], + now_ms: u64, +) -> DocResult { + let rows: Vec = data + .rows + .iter() + .filter(|r| row_ids.contains(&r.row_id)) + .map(|r| r.row_id.clone()) + .collect(); + flow_state.clear_table_focus(block_id); + flow_state.authoring_mut(block_id).dismiss_popovers(); + if rows.is_empty() { + return Ok(false); + } + let block = block_id.to_string(); + let commit = page.structural_edit(now_ms, move |page| { + for row in &rows { + page.delete_database_row(&block, row, now_ms)?; + } + Ok(()) + })?; + Ok(commit.is_some()) +} + +/// Shown Table row slots and columns `(id, type)` in display order. +fn table_grid( + flow_state: &DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + page_titles: &BTreeMap, + offset_at_ms: &dyn Fn(i64) -> i32, +) -> Option<(Vec, Vec<(String, String)>)> { + let (view, slots) = active_table_slots(flow_state, block_id, data, page_titles, offset_at_ms)?; + let cols = resolve_visible_columns(view, data) + .into_iter() + .map(|c| (c.id, c.col_type)) + .collect(); + Some((slots, cols)) +} + +/// Handle a navigation key for the focused Table cell of `block_id`: arrows and `Tab` move the +/// focus, `Enter` edits the focused cell (or flips a checkbox), `Delete` removes the checked +/// rows the view shows, and `Escape` clears the selection, then the focus. +#[allow(clippy::too_many_arguments)] +pub fn handle_navigation_key( + page: &mut PageDocSession, + flow_state: &mut DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + page_titles: &BTreeMap, + key: DatabaseNavKey, + offset_at_ms: &dyn Fn(i64) -> i32, + now_ms: u64, +) -> DocResult { + let done = |doc_mutated| AuthoringActionResult { + handled: true, + doc_mutated, + }; + if flow_state.mobile_readonly || !flow_state.has_table_focus(block_id) { + return Ok(AuthoringActionResult { + handled: false, + doc_mutated: false, + }); + } + let ui = flow_state.state_for(block_id); + match key { + DatabaseNavKey::Escape => { + let entry = flow_state + .ui_states + .entry(block_id.to_string()) + .or_default(); + if entry.selected_rows.is_empty() { + entry.focused_cell = None; + entry.focused_group = None; + } else { + entry.selected_rows.clear(); + } + flow_state.mark_dirty(block_id); + return Ok(done(false)); + } + DatabaseNavKey::Delete => { + let shown = shown_table_rows(flow_state, block_id, data, page_titles, offset_at_ms); + let rows: Vec = ui.selected_rows.intersection(&shown).cloned().collect(); + if rows.is_empty() { + return Ok(done(false)); + } + return delete_rows(page, flow_state, block_id, data, &rows, now_ms).map(done); + } + _ => {} + } + let Some((rows, cols)) = table_grid(flow_state, block_id, data, page_titles, offset_at_ms) + else { + return Ok(done(false)); + }; + if rows.is_empty() || cols.is_empty() { + return Ok(done(false)); + } + // The focused slot: the row in the focused group, else the first slot of the row. + let position = ui.focused_cell.as_ref().and_then(|(row, col)| { + let in_group = rows + .iter() + .position(|(g, r)| r == row && *g == ui.focused_group); + Some(( + in_group.or_else(|| rows.iter().position(|(_, r)| r == row))?, + cols.iter().position(|(c, _)| c == col)?, + )) + }); + let Some((r, c)) = position else { + let entry = flow_state + .ui_states + .entry(block_id.to_string()) + .or_default(); + entry.focused_cell = Some((rows[0].1.clone(), cols[0].0.clone())); + entry.focused_group = rows[0].0.clone(); + flow_state.mark_dirty(block_id); + return Ok(done(false)); + }; + let last_c = cols.len() - 1; + let last_r = rows.len() - 1; + let (next_r, next_c) = match key { + DatabaseNavKey::Up => (r.saturating_sub(1), c), + DatabaseNavKey::Down => ((r + 1).min(last_r), c), + DatabaseNavKey::Left => (r, c.saturating_sub(1)), + DatabaseNavKey::Right => (r, (c + 1).min(last_c)), + DatabaseNavKey::Tab if c == last_c => { + ((r + 1).min(last_r), if r == last_r { c } else { 0 }) + } + DatabaseNavKey::Tab => (r, c + 1), + DatabaseNavKey::ShiftTab if c == 0 => { + (r.saturating_sub(1), if r == 0 { 0 } else { last_c }) + } + DatabaseNavKey::ShiftTab => (r, c - 1), + _ => (r, c), + }; + if key != DatabaseNavKey::Enter { + let entry = flow_state + .ui_states + .entry(block_id.to_string()) + .or_default(); + entry.focused_cell = Some((rows[next_r].1.clone(), cols[next_c].0.clone())); + entry.focused_group = rows[next_r].0.clone(); + flow_state.mark_dirty(block_id); + return Ok(done(false)); + } + let (row_id, (column_id, col_type)) = (rows[r].1.clone(), cols[c].clone()); + // `EditCell` flips a checkbox in place and ignores columns that cannot be edited. + let hit = DatabaseAuthoringHit { + rect: FlowRect::new(0.0, 0.0, 1.0, 1.0), + kind: DatabaseAuthoringHitKind::EditCell { + row_id, + column_id, + col_type, + }, + scrolls_x: false, + }; + handle_authoring_hit( + page, + flow_state, + block_id, + data, + &hit, + 0.0, + offset_at_ms, + now_ms, + ) +} + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::{ + read::BlockContent, + schema::{BlockSpec, DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec}, + }; + use serde_json::json; + use ui::{AppContext, Application, Direction, HeadlessPlatform, WindowOptions}; + + use super::*; + use crate::{ + block_flow::FormFactor, + database::{DatabasePrim, layout_database_block}, + theme::PlaygroundTheme, + }; + + /// A Table grouped by a multi-select column: `R` is tagged `A` and `B`, `S` only `B`, so the + /// Table shows the slots `[A:R, B:R, B:S]`. + fn grouped_tags() -> DatabaseData { + let column = |id: &str, ty: &str, data| DatabaseColumnSpec { + id: id.into(), + column_type: ty.into(), + name: id.into(), + data, + }; + let db = DatabaseSpec { + title: "Tags".into(), + columns: vec![ + column("title", "title", json!({})), + column( + "tags", + "multi-select", + json!({ "options": [ + { "id": "a", "value": "A", "color": "var(--affine-tag-blue)" }, + { "id": "b", "value": "B", "color": "var(--affine-tag-green)" } + ] }), + ), + ], + views: vec![DatabaseViewSpec { + id: "v".into(), + name: "Table".into(), + mode: "table".into(), + raw: json!({ + "groupBy": { + "type": "groupBy", "columnId": "tags", "name": "multi-select", + "hideEmpty": true + }, + "columns": [{ "id": "title", "width": 180 }, { "id": "tags", "width": 160 }] + }), + }], + ..Default::default() + }; + let mut page = PageDocSession::new("tags", 7).unwrap(); + page.add_block("db", BlockSpec::Database(db), None, None, 1) + .unwrap(); + for (row, tags) in [("R", vec!["a", "b"]), ("S", vec!["b"])] { + let tags = DatabaseCellSpec::MultiSelect(tags.into_iter().map(String::from).collect()); + page.add_database_row_with_cells("db", row, row, vec![("tags".into(), tags)], 2) + .unwrap(); + } + let snapshot = page.read_page_snapshot().unwrap(); + let BlockContent::Database(data) = &snapshot.block("db").unwrap().content else { + panic!("expected a database"); + }; + data.clone() + } + + #[test] + fn arrows_step_through_each_group_slot_of_a_multi_select_row_with_one_focus_outline() { + let data = grouped_tags(); + let mut page = PageDocSession::new("tags", 8).unwrap(); + let mut state = DatabaseFlowState::default(); + state.ui_states.entry("db".into()).or_default().focused_cell = + Some(("R".into(), "title".into())); + let titles = BTreeMap::new(); + let platform = HeadlessPlatform::new(800, 600, 1.0); + let app = Application::with_platform(platform).run_embedded(|cx| { + crate::register_bundled_fonts(cx).expect("register fonts"); + }); + let win = app + .update(|cx| { + cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| ui::EmptyView)) + }) + .expect("open window"); + let brand = PlaygroundTheme::Light.palette().brand; + // The y of every focus outline the Table paints. + let outlines = |state: &DatabaseFlowState| -> Vec { + app.update(|cx| { + win.update(cx, |_, window, _| { + let out = layout_database_block( + &data, + &state.state_for("db"), + 760.0, + PlaygroundTheme::Light, + Direction::Ltr, + FormFactor::Desktop, + false, + 0, + &|_| 0, + &titles, + window, + ); + out.prims + .iter() + .filter_map(|p| match p { + DatabasePrim::Quad { + rect, + fill: None, + border: Some(b), + .. + } if *b == brand => Some(rect.y), + _ => None, + }) + .collect() + }) + }) + .unwrap() + }; + let mut last_y = outlines(&state); + assert_eq!(last_y.len(), 1, "the first slot of `R` is outlined"); + // (key, focused row, outline moves down) + for (key, row, down) in [ + (DatabaseNavKey::Down, "R", true), + (DatabaseNavKey::Down, "S", true), + (DatabaseNavKey::Down, "S", false), + (DatabaseNavKey::Up, "R", false), + (DatabaseNavKey::Up, "R", false), + (DatabaseNavKey::Tab, "R", false), + ] { + handle_navigation_key(&mut page, &mut state, "db", &data, &titles, key, &|_| 0, 1) + .unwrap(); + let focused = state.state_for("db").focused_cell.unwrap(); + assert_eq!(focused.0, row, "{key:?}"); + let y = outlines(&state); + assert_eq!(y.len(), 1, "{key:?}: one outline"); + match (key, down) { + (DatabaseNavKey::Tab, _) => {} + (_, true) => assert!(y[0] > last_y[0], "{key:?}: {y:?} below {last_y:?}"), + (DatabaseNavKey::Down, false) => assert_eq!(y, last_y, "the last slot stays"), + (_, false) => assert!(y[0] < last_y[0], "{key:?}: {y:?} above {last_y:?}"), + } + last_y = y; + } + } +} diff --git a/blocksuite/crates/editor/src/database/view_action.rs b/blocksuite/crates/editor/src/database/view_action.rs new file mode 100644 index 0000000000..fa06ea31f9 --- /dev/null +++ b/blocksuite/crates/editor/src/database/view_action.rs @@ -0,0 +1,292 @@ +//! Actions of the `Date` picker, Table row selection, toolbar `Search`, footer `Calculate`, +//! and Kanban `+ Add Group` controls, and the keys of their popovers. + +use blocksuite_playground_doc::{ + DocResult, + read::{DatabaseCellValue, DatabaseData, DatabaseView}, + schema::DatabaseCellSpec, + session::PageDocSession, +}; + +use super::{ + ActiveToolbarPanel, AuthoringActionResult, DatabaseAuthoringKey, DatabaseFlowState, + authoring_id::fresh_database_id, + calendar_edit::timestamp_on_day, + cell_editor::next_tag_color, + date_picker::{shown_month, step_month}, + day_index_to_local_midnight_ms, local_day_index, resolve_effective_group_by, + set_database_view_stat_calc, + table_selection::delete_rows, +}; + +/// One click on a Table selection, search, statistic, `Date` picker, or group control. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DatabaseViewAction { + DatePickerStepMonth { + delta: i32, + }, + DatePickerToday, + DatePickerPick { + day_index: i64, + }, + DatePickerClear, + ToggleRowSelected { + row_id: String, + }, + /// Header checkbox over the rows `row_ids` the view shows. + ToggleAllRowsSelected { + row_ids: Vec, + }, + /// Selection bar `Delete` over the checked rows `row_ids` the view shows. + DeleteSelectedRows { + row_ids: Vec, + }, + ClearRowSelection, + ToggleSearch, + ClearSearch, + OpenCalcMenu { + column_id: String, + group_key: String, + }, + SetCalc { + column_id: String, + calc: String, + }, + OpenAddGroup, + CreateGroup, +} + +const fn done(doc_mutated: bool) -> AuthoringActionResult { + AuthoringActionResult { + handled: true, + doc_mutated, + } +} + +/// Toggle the toolbar popover `panel`, closing every other popover. +fn toggle_panel(flow_state: &mut DatabaseFlowState, block_id: &str, panel: ActiveToolbarPanel) { + let auth = flow_state.authoring_mut(block_id); + let open = auth.toolbar_panel != Some(panel); + auth.dismiss_popovers(); + auth.toolbar_panel = open.then_some(panel); +} + +/// Write the picked day (or `None` to clear) into the `Date` cell under the open editor and +/// close the picker. A picked day keeps the time of day of the stored value. +fn commit_date( + page: &mut PageDocSession, + flow_state: &mut DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + day_index: Option, + offset_at_ms: &dyn Fn(i64) -> i32, + now_ms: u64, +) -> DocResult { + let Some(ed) = flow_state.state_for(block_id).authoring.active_cell else { + return Ok(done(false)); + }; + let stored = data + .cells + .get(&(ed.row_id.clone(), ed.column_id.clone())) + .and_then(DatabaseCellValue::as_i64); + let next = day_index.map(|day| match stored { + Some(ts) => timestamp_on_day(ts, day, offset_at_ms), + None => day_index_to_local_midnight_ms(day, offset_at_ms), + }); + flow_state.authoring_mut(block_id).dismiss_popovers(); + if next == stored { + return Ok(done(false)); + } + let spec = next.map_or(DatabaseCellSpec::Null, DatabaseCellSpec::Integer); + let commit = page.set_database_cell_value(block_id, &ed.row_id, &ed.column_id, spec, now_ms)?; + Ok(done(commit.is_some())) +} + +/// Create a select option named by the `+ Add Group` field in the column that groups `view`. +fn create_group( + page: &mut PageDocSession, + flow_state: &mut DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + view: &DatabaseView, + now_ms: u64, +) -> DocResult { + let name = flow_state + .state_for(block_id) + .authoring + .group_name_draft + .trim() + .to_string(); + let column = resolve_effective_group_by(view, data) + .and_then(|gb| data.columns.iter().find(|c| c.id == gb.column_id)) + .filter(|c| matches!(c.column_type.as_str(), "select" | "multi-select")); + let Some(column) = column.filter(|_| !name.is_empty()) else { + return Ok(done(false)); + }; + flow_state.authoring_mut(block_id).dismiss_popovers(); + let options = column.select_options(); + if options.iter().any(|o| o.value == name) { + return Ok(done(false)); + } + let option_id = fresh_database_id(page, data, "opt"); + let color = next_tag_color(options.len()); + let commit = + page.upsert_database_select_option(block_id, &column.id, &option_id, &name, color, now_ms)?; + Ok(done(commit.is_some())) +} + +/// Apply one [`DatabaseViewAction`] on `block_id` in view `view`. +#[allow(clippy::too_many_arguments)] +pub(super) fn handle_view_action( + page: &mut PageDocSession, + flow_state: &mut DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + view: &DatabaseView, + action: &DatabaseViewAction, + offset_at_ms: &dyn Fn(i64) -> i32, + now_ms: u64, +) -> DocResult { + let today = local_day_index(flow_state.clock_ms, offset_at_ms); + match action { + DatabaseViewAction::DatePickerStepMonth { delta } => { + let auth = flow_state.authoring_mut(block_id); + let picked = auth.active_cell.as_ref().and_then(|ed| { + data.cells + .get(&(ed.row_id.clone(), ed.column_id.clone())) + .and_then(DatabaseCellValue::as_i64) + .map(|ts| local_day_index(ts, offset_at_ms)) + }); + let shown = shown_month(auth.date_picker_month, picked, today); + auth.date_picker_month = Some(step_month(shown, *delta)); + Ok(done(false)) + } + DatabaseViewAction::DatePickerToday => { + flow_state.authoring_mut(block_id).date_picker_month = + Some(shown_month(None, None, today)); + Ok(done(false)) + } + DatabaseViewAction::DatePickerPick { day_index } => commit_date( + page, + flow_state, + block_id, + data, + Some(*day_index), + offset_at_ms, + now_ms, + ), + DatabaseViewAction::DatePickerClear => { + commit_date(page, flow_state, block_id, data, None, offset_at_ms, now_ms) + } + DatabaseViewAction::ToggleRowSelected { row_id } => { + flow_state.authoring_mut(block_id).dismiss_popovers(); + flow_state.toggle_row_selected(block_id, row_id); + Ok(done(false)) + } + DatabaseViewAction::ToggleAllRowsSelected { row_ids } => { + flow_state.authoring_mut(block_id).dismiss_popovers(); + flow_state.toggle_rows_selected(block_id, row_ids); + Ok(done(false)) + } + DatabaseViewAction::DeleteSelectedRows { row_ids } => { + delete_rows(page, flow_state, block_id, data, row_ids, now_ms).map(done) + } + DatabaseViewAction::ClearRowSelection => { + flow_state.clear_table_focus(block_id); + Ok(done(false)) + } + DatabaseViewAction::ToggleSearch => { + toggle_panel(flow_state, block_id, ActiveToolbarPanel::Search); + Ok(done(false)) + } + DatabaseViewAction::ClearSearch => { + flow_state.set_search_query(block_id, ""); + flow_state.authoring_mut(block_id).dismiss_popovers(); + Ok(done(false)) + } + DatabaseViewAction::OpenCalcMenu { + column_id, + group_key, + } => { + let auth = flow_state.authoring_mut(block_id); + let target = (column_id.clone(), group_key.clone()); + let open = auth.calc_menu.as_ref() != Some(&target); + auth.dismiss_popovers(); + auth.calc_menu = open.then_some(target); + Ok(done(false)) + } + DatabaseViewAction::SetCalc { column_id, calc } => { + flow_state.authoring_mut(block_id).dismiss_popovers(); + set_database_view_stat_calc(page, block_id, view, column_id, calc, now_ms).map(done) + } + DatabaseViewAction::OpenAddGroup => { + toggle_panel(flow_state, block_id, ActiveToolbarPanel::AddGroup); + Ok(done(false)) + } + DatabaseViewAction::CreateGroup => { + create_group(page, flow_state, block_id, data, view, now_ms) + } + } +} + +impl DatabaseFlowState { + /// Set the toolbar search query of `block_id`. It filters the rows each view shows. + pub fn set_search_query(&mut self, block_id: &str, query: &str) { + let entry = self.ui_states.entry(block_id.to_string()).or_default(); + if entry.search_query != query { + entry.search_query = query.to_string(); + self.mark_dirty(block_id); + } + } +} + +/// Handle `Enter` and `Escape` in the `Search`, `+ Add Group`, and `Calculate` popovers: +/// `Enter` keeps the search or creates the group, `Escape` clears the search or closes the +/// popover. Returns `None` for any other key or when none of these popovers is open. +#[allow(clippy::too_many_arguments)] +pub fn handle_view_popover_key( + page: &mut PageDocSession, + flow_state: &mut DatabaseFlowState, + block_id: &str, + data: &DatabaseData, + key: &DatabaseAuthoringKey, + offset_at_ms: &dyn Fn(i64) -> i32, + now_ms: u64, +) -> DocResult> { + let auth = flow_state.state_for(block_id).authoring; + let action = match (auth.toolbar_panel, key) { + (Some(ActiveToolbarPanel::Search), DatabaseAuthoringKey::Escape) => { + DatabaseViewAction::ClearSearch + } + (Some(ActiveToolbarPanel::AddGroup), DatabaseAuthoringKey::Enter) => { + DatabaseViewAction::CreateGroup + } + ( + Some(ActiveToolbarPanel::Search | ActiveToolbarPanel::AddGroup), + DatabaseAuthoringKey::Enter | DatabaseAuthoringKey::Escape, + ) => { + flow_state.authoring_mut(block_id).dismiss_popovers(); + return Ok(Some(done(false))); + } + _ if auth.calc_menu.is_some() && *key == DatabaseAuthoringKey::Escape => { + flow_state.authoring_mut(block_id).dismiss_popovers(); + return Ok(Some(done(false))); + } + _ => return Ok(None), + }; + let Some(view) = super::authoring::resolve_active_view(data, flow_state, block_id).cloned() + else { + return Ok(None); + }; + handle_view_action( + page, + flow_state, + block_id, + data, + &view, + &action, + offset_at_ms, + now_ms, + ) + .map(Some) +} diff --git a/blocksuite/crates/editor/src/database/view_config.rs b/blocksuite/crates/editor/src/database/view_config.rs new file mode 100644 index 0000000000..5df11222c8 --- /dev/null +++ b/blocksuite/crates/editor/src/database/view_config.rs @@ -0,0 +1,256 @@ +//! Per-column footer statistics stored in the live view configuration. + +use blocksuite_playground_doc::{ + DocResult, + read::DatabaseView, + schema::json_to_session_value, + session::{PageDocSession, any_to_normalized_json}, +}; +use serde_json::json; +use y_octo::{Any, SessionReadValue, SessionValue, TypePath, TypeTarget}; + +/// Find the `Y.Map` of view `view_id` inside `prop:views`, upgrading a legacy plain-object view +/// into a shared `Y.Map` in place first. Call only inside a transaction. +fn view_map_in_tx( + page: &mut PageDocSession, + block_id: &str, + view_id: &str, +) -> DocResult> { + let views = TypeTarget::Path(TypePath::root("blocks").key(block_id).key("prop:views")); + for (idx, item) in page.inner().read_array(&views)?.into_iter().enumerate() { + match item { + SessionReadValue::Map(id) => { + let target = TypeTarget::Identity(id); + if matches!( + page.inner().get_map_value(&target, "id")?, + Some(SessionReadValue::Any(Any::String(ref id))) if id == view_id + ) { + return Ok(Some(target)); + } + } + SessionReadValue::Any(Any::Object(obj)) if matches!(obj.get("id"), Some(Any::String(id)) if id == view_id) => + { + let json = any_to_normalized_json(&Any::Object(obj)); + page.inner_mut().array_remove(&views, idx as u64, 1)?; + page.inner_mut().array_insert( + &views, + idx as u64, + vec![json_to_session_value(&json)], + )?; + if let Some(SessionReadValue::Map(id)) = + page.inner().read_array(&views)?.into_iter().nth(idx) + { + return Ok(Some(TypeTarget::Identity(id))); + } + } + _ => {} + } + } + Ok(None) +} + +/// The live `Y.Array` under `key` of `map`, upgrading a legacy plain array in place (or +/// creating an empty one) first, so later writes change single entries instead of replacing the +/// whole array. Call only inside a transaction. +fn live_array_in_tx( + page: &mut PageDocSession, + map: &TypeTarget, + key: &str, +) -> DocResult> { + let value = match page.inner().get_map_value(map, key)? { + Some(SessionReadValue::Array(id)) => return Ok(Some(TypeTarget::Identity(id))), + Some(SessionReadValue::Any(any @ Any::Array(_))) => { + json_to_session_value(&any_to_normalized_json(&any)) + } + _ => SessionValue::Array(Vec::new()), + }; + page.inner_mut().map_set(map, key.to_string(), value)?; + Ok(match page.inner().get_map_value(map, key)? { + Some(SessionReadValue::Array(id)) => Some(TypeTarget::Identity(id)), + _ => None, + }) +} + +/// Persist the footer statistic `calc` (`"none"`, `"count-all"`, `"sum"`, ...) of `column_id` +/// in view `view.id`. It rewrites one entry of `view.columns` and keeps the width and the +/// visibility of every column. +pub fn set_database_view_stat_calc( + page: &mut PageDocSession, + block_id: &str, + view: &DatabaseView, + column_id: &str, + calc: &str, + now_ms: u64, +) -> DocResult { + let current = view + .columns + .iter() + .find(|c| c.id == column_id) + .and_then(|c| c.stat_calc_type.as_deref()) + .unwrap_or("none"); + if current == calc { + return Ok(false); + } + let (block_id, view_id) = (block_id.to_string(), view.id.clone()); + let (column_id, calc) = (column_id.to_string(), calc.to_string()); + let commit = page.structural_edit(now_ms, move |page| { + let Some(view_map) = view_map_in_tx(page, &block_id, &view_id)? else { + return Ok(()); + }; + let value = SessionValue::Any(Any::String(calc.clone())); + let Some(arr) = live_array_in_tx(page, &view_map, "columns")? else { + return Ok(()); + }; + for (idx, item) in page.inner().read_array(&arr)?.into_iter().enumerate() { + match item { + SessionReadValue::Map(id) => { + let col = TypeTarget::Identity(id); + if matches!( + page.inner().get_map_value(&col, "id")?, + Some(SessionReadValue::Any(Any::String(ref id))) if *id == column_id + ) { + page.inner_mut() + .map_set(&col, "statCalcType".to_string(), value)?; + return Ok(()); + } + } + SessionReadValue::Any(Any::Object(mut obj)) + if matches!(obj.get("id"), Some(Any::String(id)) if *id == column_id) => + { + obj.insert("statCalcType".to_string(), Any::String(calc.clone())); + let json = any_to_normalized_json(&Any::Object(obj)); + page.inner_mut().array_remove(&arr, idx as u64, 1)?; + page.inner_mut() + .array_insert(&arr, idx as u64, vec![json_to_session_value(&json)])?; + return Ok(()); + } + _ => {} + } + } + page.inner_mut().array_push( + &arr, + vec![json_to_session_value( + &json!({ "id": column_id, "statCalcType": calc }), + )], + )?; + Ok(()) + })?; + Ok(commit.is_some()) +} + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::{ + read::{BlockContent, DatabaseData}, + schema::{BlockSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec}, + }; + use serde_json::Value as JsonValue; + + use super::*; + + /// A Kanban database grouped by a select column with options `a`, `b`, and `c`. + fn kanban_page(client: u64) -> PageDocSession { + let options = json!({ "options": [ + { "id": "a", "value": "A", "color": "var(--affine-tag-blue)" }, + { "id": "b", "value": "B", "color": "var(--affine-tag-green)" }, + { "id": "c", "value": "C", "color": "var(--affine-tag-red)" } + ] }); + let db = DatabaseSpec { + title: "Lanes".into(), + columns: vec![ + DatabaseColumnSpec { + id: "title".into(), + column_type: "title".into(), + name: "Title".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "s".into(), + column_type: "select".into(), + name: "Status".into(), + data: options, + }, + ], + views: vec![DatabaseViewSpec { + id: "k".into(), + name: "Kanban".into(), + mode: "kanban".into(), + raw: json!({ + "groupBy": { "type": "groupBy", "columnId": "s", "name": "select" }, + "columns": [{ "id": "title", "width": 200 }, { "id": "s", "width": 140 }] + }), + }], + ..Default::default() + }; + let mut page = PageDocSession::new("lanes", client).unwrap(); + page.add_block("db", BlockSpec::Database(db), None, None, 1) + .unwrap(); + page.stop_capturing().unwrap(); + page + } + + fn read(page: &PageDocSession) -> DatabaseData { + let snapshot = page.read_page_snapshot().unwrap(); + let BlockContent::Database(data) = &snapshot.block("db").unwrap().content else { + panic!("expected a database"); + }; + data.clone() + } + + /// Write `value` into `key` of view `k` in one step. + fn set_view_value(page: &mut PageDocSession, key: &str, value: SessionValue) { + let key = key.to_string(); + page.structural_edit(2, move |page| { + let view = view_map_in_tx(page, "db", "k")?.unwrap(); + page.inner_mut().map_set(&view, key, value)?; + Ok(()) + }) + .unwrap(); + page.stop_capturing().unwrap(); + } + + #[test] + fn legacy_plain_columns_keep_widths_when_setting_statistics() { + let mut page = kanban_page(7); + let plain = |v: JsonValue| match json_to_session_value(&v) { + SessionValue::Array(_) => SessionValue::Any(any_from_json(&v)), + other => other, + }; + set_view_value( + &mut page, + "columns", + plain(json!([{ "id": "title", "width": 260 }, { "id": "s", "width": 90 }])), + ); + let view = read(&page).views[0].clone(); + assert!(set_database_view_stat_calc(&mut page, "db", &view, "s", "count-all", 6).unwrap()); + let columns = &read(&page).views[0].columns; + let widths: Vec<_> = columns.iter().map(|c| (c.id.as_str(), c.width)).collect(); + assert_eq!(widths, [("title", Some(260.0)), ("s", Some(90.0))]); + assert_eq!(columns[1].stat_calc_type.as_deref(), Some("count-all")); + } + + /// The plain (`Any`) form of `value`, as an old client stores a whole array. + fn any_from_json(value: &JsonValue) -> Any { + match value { + JsonValue::Null => Any::Null, + JsonValue::Bool(b) => { + if *b { + Any::True + } else { + Any::False + } + } + JsonValue::Number(n) => n + .as_i64() + .and_then(|i| i32::try_from(i).ok()) + .map_or(Any::Float64(n.as_f64().unwrap_or(0.0).into()), Any::Integer), + JsonValue::String(s) => Any::String(s.clone()), + JsonValue::Array(items) => Any::Array(items.iter().map(any_from_json).collect()), + JsonValue::Object(map) => Any::Object(Box::new( + map.iter() + .map(|(k, v)| (k.clone(), any_from_json(v))) + .collect(), + )), + } + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/dnd.rs b/blocksuite/crates/playground/src/database_authoring/dnd.rs index 9a82deafc9..59dfeb5c99 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd.rs @@ -126,6 +126,23 @@ impl PlaygroundView { Some((start, end)) } + /// Whether the active Calendar view of `block_id` stores an end date in a column of its own. + pub(super) fn calendar_has_end_column(&self, block_id: &str) -> bool { + let Some(db) = self.database_snapshot_data(block_id) else { + return false; + }; + 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()); + view.is_some_and(|view| { + let (start, end) = database::resolve_calendar_date_columns(view, &db); + end.is_some_and(|end| start != Some(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`). diff --git a/blocksuite/crates/playground/src/database_authoring/dnd_table.rs b/blocksuite/crates/playground/src/database_authoring/dnd_table.rs index d16d8adef1..3d8210027f 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd_table.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd_table.rs @@ -67,6 +67,13 @@ fn bucket_for_table_y(groups: &[(String, FlowRect)], y: f32) -> Option { .map(|(k, _)| k.clone()) } +impl PlaygroundView { + /// The group of the grouped Table `block_id` that shows block-local `y`. + pub(super) fn table_group_at(&self, block_id: &str, y: f32) -> Option { + bucket_for_table_y(&table_group_headers(self.flow.database_hits(block_id)), y) + } +} + /// Collect ordered Table column header boxes `(column_id, rect)` from `OpenColumnMenu` hits. pub(crate) fn collect_table_column_rects( hits: &[database::DatabaseAuthoringHit], @@ -98,7 +105,10 @@ impl PlaygroundView { let hits = self.flow.database_authoring_hits(block_id); let rows = collect_table_row_rects(&hits); let Some((row_id, row_rect)) = rows.into_iter().find(|(_, r)| { - local_y >= r.y && local_y <= r.bottom() && local_x >= r.x - 20.0 && local_x <= r.x - 2.0 + local_y >= r.y + && local_y <= r.bottom() + && local_x >= r.x - super::hover::GRIP_GUTTER_W + && local_x < r.x - blocksuite_editor::database::ROW_SELECT_GUTTER_W }) else { return false; }; diff --git a/blocksuite/crates/playground/src/database_authoring/hover.rs b/blocksuite/crates/playground/src/database_authoring/hover.rs index 6d1460911d..d67128d44f 100644 --- a/blocksuite/crates/playground/src/database_authoring/hover.rs +++ b/blocksuite/crates/playground/src/database_authoring/hover.rs @@ -7,8 +7,8 @@ use blocksuite_editor::{ block_flow::FlowRect, database::{ - self, DatabaseAuthoringHitKind, DatabaseHitKind, database_authoring_hit_cursor, - database_hit_cursor, + self, DatabaseAuthoringHitKind, DatabaseHitKind, DatabaseViewAction, ROW_SELECT_GUTTER_W, + database_authoring_hit_cursor, database_hit_cursor, }, }; use blocksuite_playground_doc::schema::DatabaseCellSpec; @@ -120,8 +120,16 @@ pub(crate) struct DatabaseHoverState { pub cursor: Option, pub last_pointer: Option<(f32, f32)>, pub doc_rev: u64, + /// `(block_id, row_id, column_id)` of the cell the last press landed on, so a double click + /// counts only when both presses land on the same cell. + pub last_press_cell: Option<(String, String, String)>, } +/// Left gutter of a Table row: the row checkbox right beside the row, the drag grip beyond it. +/// The grip ends 20 px left of the block, where the page still routes a press to the database +/// block, so the grip cursor and a press agree on every pixel. +pub(crate) const GRIP_GUTTER_W: f32 = ROW_SELECT_GUTTER_W + 10.0; + /// Shared square button size (`24×24`, `4px` padding + `16px` SVG) matching `0.27.5` `.row-op`. pub(crate) const HOVER_BTN_H: f32 = 24.0; @@ -386,11 +394,19 @@ impl PlaygroundView { && matches!( h.kind, DatabaseAuthoringHitKind::AddView + | DatabaseAuthoringHitKind::View(_) | DatabaseAuthoringHitKind::AddColumn | DatabaseAuthoringHitKind::ToolbarToggleFilter | DatabaseAuthoringHitKind::ToolbarToggleSort | DatabaseAuthoringHitKind::ToolbarToggleGroupBy ) + && !matches!( + h.kind, + DatabaseAuthoringHitKind::View( + DatabaseViewAction::ToggleRowSelected { .. } + | DatabaseViewAction::ToggleAllRowsSelected { .. } + ) + ) }) { let cursor = database_authoring_hit_cursor(&hit.kind, readonly); let target = (!readonly).then_some(DatabaseHoverTargetKind::ControlRect { @@ -444,9 +460,12 @@ impl PlaygroundView { } // 5. Table rows (including left gutter grip, title cell OPEN / … ops, link edit, cell cursors). - if let Some((row_id, row_rect)) = collect_table_row_rects(auth_hits) - .into_iter() - .find(|(_, r)| ly >= r.y && ly <= r.bottom() && lx >= r.x - 22.0 && sx <= r.right()) + if let Some((row_id, row_rect)) = + collect_table_row_rects(auth_hits) + .into_iter() + .find(|(_, r)| { + ly >= r.y && ly <= r.bottom() && lx >= r.x - GRIP_GUTTER_W && sx <= r.right() + }) { let title_rect = auth_hits.iter().find_map(|h| match &h.kind { DatabaseAuthoringHitKind::EditCell { @@ -481,7 +500,10 @@ impl PlaygroundView { let mut op_hover = None; let mut cursor = CursorStyle::Arrow; if !row_editing { - if !readonly && lx >= row_rect.x - 22.0 && lx <= row_rect.x - 2.0 { + if !readonly + && lx >= row_rect.x - GRIP_GUTTER_W + && lx < row_rect.x - ROW_SELECT_GUTTER_W + { op_hover = Some(RowOpHover::Grip); cursor = CursorStyle::OpenHand; } else if let Some(tr) = title_rect { @@ -559,9 +581,12 @@ impl PlaygroundView { && 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)); + // A view with an end date column stretches one-day events too; a view with a start + // column only keeps them single points. + let stretchable = + |(start, end): (i64, i64)| start < end || self.calendar_has_end_column(&block_id); + let start_handle = range.is_some_and(|r| stretchable(r) && segment_contains(r.0)); + let end_handle = range.is_some_and(|r| stretchable(r) && segment_contains(r.1)); 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; diff --git a/blocksuite/crates/playground/src/database_authoring/inline.rs b/blocksuite/crates/playground/src/database_authoring/inline.rs index 24f208138c..f568b6a842 100644 --- a/blocksuite/crates/playground/src/database_authoring/inline.rs +++ b/blocksuite/crates/playground/src/database_authoring/inline.rs @@ -65,6 +65,18 @@ pub(crate) enum DatabaseInlineTarget { block_id: String, row_id: String, }, + /// Text field of a toolbar popover that writes view state only. + ViewField { + block_id: String, + field: ViewTextField, + }, +} + +/// Field of a [`DatabaseInlineTarget::ViewField`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ViewTextField { + Search, + GroupName, } impl DatabaseInlineTarget { @@ -76,7 +88,8 @@ impl DatabaseInlineTarget { | Self::ColumnRename { block_id, .. } | Self::SelectFilter { block_id, .. } | Self::FilterValue { block_id } - | Self::RecordTitle { block_id, .. } => block_id, + | Self::RecordTitle { block_id, .. } + | Self::ViewField { block_id, .. } => block_id, } } @@ -152,6 +165,7 @@ impl DatabaseInlineTarget { | Self::FilterValue { .. } | Self::RecordBody { .. } | Self::RecordTitle { .. } + | Self::ViewField { .. } ) } @@ -222,7 +236,8 @@ impl DatabaseInlineTarget { row_id: r2, }, ) => b1 == b2 && r1 == r2, - (Self::RecordBody { .. }, Self::RecordBody { .. }) => self == other, + (Self::RecordBody { .. }, Self::RecordBody { .. }) + | (Self::ViewField { .. }, Self::ViewField { .. }) => self == other, _ => false, } } @@ -324,13 +339,18 @@ impl PlaygroundView { if a.column_menu.is_some() || a.row_menu.is_some() || a.lane_menu.is_some() + || a.calc_menu.is_some() || a.active_cell.is_some() || a.toolbar_panel.is_some() { return Some(block_id.clone()); } } - None + self.flow + .database_state + .states() + .find(|(id, _)| self.flow.database_state.has_table_focus(id)) + .map(|(id, _)| id.clone()) } pub(super) fn desired_database_inline_target( @@ -421,6 +441,21 @@ impl PlaygroundView { false, )); } + let field = match a.toolbar_panel { + Some(ActiveToolbarPanel::Search) => Some((ViewTextField::Search, &st.search_query)), + Some(ActiveToolbarPanel::AddGroup) => { + Some((ViewTextField::GroupName, &a.group_name_draft)) + } + _ => None, + }; + if let Some((field, text)) = field { + let block_id = block_id.clone(); + return Some(( + DatabaseInlineTarget::ViewField { block_id, field }, + text.clone(), + false, + )); + } if a.toolbar_panel == Some(ActiveToolbarPanel::Filter) { let col_type = self .snapshot @@ -610,6 +645,22 @@ impl PlaygroundView { let auth = self.flow.database_state.authoring_mut(block_id); auth.filter_draft.value = display; } + DatabaseInlineTarget::ViewField { block_id, field } => match field { + ViewTextField::Search => { + self.flow + .database_state + .set_search_query(block_id, &display); + self.prune_database_row_selection(block_id); + // The `Search` control resizes with the query under a resting pointer. + self.database_hover.target = None; + } + ViewTextField::GroupName => { + self.flow + .database_state + .authoring_mut(block_id) + .group_name_draft = display; + } + }, DatabaseInlineTarget::RecordBody { .. } | DatabaseInlineTarget::RecordTitle { .. } => {} } @@ -726,7 +777,8 @@ impl PlaygroundView { } } DatabaseInlineTarget::SelectFilter { .. } - | DatabaseInlineTarget::FilterValue { .. } => {} + | DatabaseInlineTarget::FilterValue { .. } + | DatabaseInlineTarget::ViewField { .. } => {} } } if let Some(sheet) = self.database_record_sheet.as_mut() { @@ -739,46 +791,4 @@ impl PlaygroundView { .dismiss_popovers(); true } - - /// 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_input( - &mut self, - 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( - block_id, - row_id, - start as u64, - del as u64, - insert, - now_ms, - ) - } else { - page.splice_database_cell_text( - block_id, - row_id, - column_id, - start as u64, - del as u64, - insert, - now_ms, - ) - }; - res.ok().flatten().is_some() - }) - } } diff --git a/blocksuite/crates/playground/src/database_authoring/inline_splice.rs b/blocksuite/crates/playground/src/database_authoring/inline_splice.rs new file mode 100644 index 0000000000..acbf021876 --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/inline_splice.rs @@ -0,0 +1,49 @@ +//! Splicing the edits of the database inline input into the live `Y.Text` it edits. + +use crate::PlaygroundView; + +use super::inline::DatabaseInlineTarget; + +impl PlaygroundView { + /// Splice `(start, delete_len, insert)` UTF-16 units into the live `Y.Text` of + /// [`DatabaseInlineTarget::live_text`]. Returns whether the document changed. + pub(super) fn splice_database_input( + &mut self, + 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( + block_id, + row_id, + start as u64, + del as u64, + insert, + now_ms, + ) + } else { + page.splice_database_cell_text( + block_id, + row_id, + column_id, + start as u64, + del as u64, + insert, + now_ms, + ) + }; + res.ok().flatten().is_some() + }) + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/keys.rs b/blocksuite/crates/playground/src/database_authoring/keys.rs index f754cb3e87..42c124c9a3 100644 --- a/blocksuite/crates/playground/src/database_authoring/keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/keys.rs @@ -1,7 +1,7 @@ //! Keyboard navigation, control-key routing, and snapshot reconciliation for //! [`PlaygroundView`]'s database authoring controller. -use blocksuite_editor::database::{self, DatabaseAuthoringKey}; +use blocksuite_editor::database::{self, DatabaseAuthoringKey, DatabaseNavKey}; use blocksuite_playground_doc::read::{BlockContent, DatabaseCellValue}; use ui::{Context, KeyDownEvent, Window}; @@ -67,6 +67,12 @@ impl PlaygroundView { None }); } + if self.database_input.is_none() + && let Some(nav) = navigation_key(key, m.shift) + && self.database_navigation_ready(&block_id) + { + return self.dispatch_database_navigation(&block_id, nav, window, cx); + } if matches!( key, "backspace" | "delete" | "left" | "right" | "home" | "end" | "up" | "down" @@ -141,16 +147,28 @@ impl PlaygroundView { return false; }; let _ = page.stop_capturing(); - let res = database::handle_authoring_key( + let res = match database::handle_view_popover_key( page, &mut self.flow.database_state, block_id, &db_data, - &self.page_titles, - key, + &key, &offset_at, now_ms, - ); + ) { + Ok(Some(res)) => Ok(res), + Ok(None) => database::handle_authoring_key( + page, + &mut self.flow.database_state, + block_id, + &db_data, + &self.page_titles, + key, + &offset_at, + now_ms, + ), + Err(err) => Err(err), + }; let _ = page.stop_capturing(); res }; @@ -167,11 +185,93 @@ impl PlaygroundView { } } + /// Whether `block_id` has a focused Table cell or checked rows and no popover that takes + /// the keys first. + fn database_navigation_ready(&self, block_id: &str) -> bool { + let st = self.flow.database_state.state_for(block_id); + let a = &st.authoring; + self.flow.database_state.has_table_focus(block_id) + && !st.more_views_open + && a.column_menu.is_none() + && a.row_menu.is_none() + && a.lane_menu.is_none() + && a.calc_menu.is_none() + && a.active_cell.is_none() + && a.toolbar_panel.is_none() + } + + /// Run a navigation key on the focused Table cell of `block_id` (see + /// [`database::handle_navigation_key`]); `Enter` opens the inline editor of the cell. + fn dispatch_database_navigation( + &mut self, + block_id: &str, + key: DatabaseNavKey, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let Some(db_data) = self.database_snapshot_data(block_id) else { + return false; + }; + let now_ms = self.now_ms(cx) as u64; + let offset_at = self.utc_offset_resolver(); + let before_sv = self.page().and_then(|p| p.encode_state_vector_v1().ok()); + let outcome = { + let Some(page) = self + .page_id + .as_deref() + .and_then(|id| self.state.workspace.page_mut(id)) + else { + return false; + }; + let _ = page.stop_capturing(); + let res = database::handle_navigation_key( + page, + &mut self.flow.database_state, + block_id, + &db_data, + &self.page_titles, + key, + &offset_at, + now_ms, + ); + let _ = page.stop_capturing(); + res + }; + let Ok(res) = outcome else { + return false; + }; + self.flow + .database_state + .follow_active_cell(block_id, &db_data, None); + if res.doc_mutated { + self.sync_after_database_mutation(before_sv, cx); + } else { + cx.notify(); + } + self.sync_database_authoring_input(Some(window), cx); + res.handled + } + + /// Keep only the checked rows and the focused cell that the Table `block_id` still shows + /// (see [`database::DatabaseFlowState::prune_row_selection`]). + pub(super) fn prune_database_row_selection(&mut self, block_id: &str) { + if let Some(db) = self.database_snapshot_data(block_id) { + let offset_at = self.utc_offset_resolver(); + self.flow.database_state.prune_row_selection( + block_id, + &db, + &self.page_titles, + &offset_at, + ); + } + } + /// Reconcile open database authoring popovers and `self.database_input` after a snapshot /// refresh (Undo/Redo or remote collaborator edit). pub(crate) fn sync_database_authoring_from_snapshot(&mut self) { let states = self.flow.database_state.states(); let block_ids: Vec = states.map(|(id, _)| id.clone()).collect(); + let offset_at = self.utc_offset_resolver(); for bid in block_ids { let db_opt = self .snapshot @@ -182,6 +282,7 @@ impl PlaygroundView { _ => None, }); let Some(db) = db_opt else { + self.flow.database_state.clear_table_focus(&bid); let a = self.flow.database_state.authoring_mut(&bid); a.dismiss_popovers(); a.calendar_drag = None; @@ -190,6 +291,9 @@ impl PlaygroundView { a.progress_preview = None; continue; }; + self.flow + .database_state + .prune_row_selection(&bid, &db, &self.page_titles, &offset_at); let a = self.flow.database_state.authoring_mut(&bid); if let Some(cm) = &a.column_menu && cm.column_id != "title" @@ -265,3 +369,19 @@ impl PlaygroundView { self.database_input = Some(session); } } + +/// The Table navigation key that `key` (with `shift`) stands for. +fn navigation_key(key: &str, shift: bool) -> Option { + Some(match key { + "up" => DatabaseNavKey::Up, + "down" => DatabaseNavKey::Down, + "left" => DatabaseNavKey::Left, + "right" => DatabaseNavKey::Right, + "tab" if shift => DatabaseNavKey::ShiftTab, + "tab" => DatabaseNavKey::Tab, + "enter" => DatabaseNavKey::Enter, + "backspace" | "delete" => DatabaseNavKey::Delete, + "escape" => DatabaseNavKey::Escape, + _ => return None, + }) +} diff --git a/blocksuite/crates/playground/src/database_authoring/mod.rs b/blocksuite/crates/playground/src/database_authoring/mod.rs index 1bed7c30c4..54ecde087c 100644 --- a/blocksuite/crates/playground/src/database_authoring/mod.rs +++ b/blocksuite/crates/playground/src/database_authoring/mod.rs @@ -8,6 +8,7 @@ mod geometry; mod hover; mod hover_ops; mod inline; +mod inline_splice; mod keys; mod paint; mod paint_dnd; @@ -42,8 +43,16 @@ mod tests_record_peek_edit; #[cfg(test)] mod tests_row_edit_and_popover_hover; #[cfg(test)] +mod tests_row_selection_scope; +#[cfg(test)] mod tests_scalar_edgeless_calendar; #[cfg(test)] +mod tests_sideways_scroll_controls; +#[cfg(test)] +mod tests_view_controls; +#[cfg(test)] +mod tests_view_controls_board; +#[cfg(test)] mod tests_view_state_layout_reuse; pub(crate) use dnd::DatabaseDropSettle; @@ -124,12 +133,14 @@ impl PlaygroundView { .cloned() .collect(); for id in ids { + changed |= self.flow.database_state.clear_table_focus(&id); let st = self.flow.database_state.state_for(&id); let a = &st.authoring; if st.more_views_open || a.column_menu.is_some() || a.row_menu.is_some() || a.lane_menu.is_some() + || a.calc_menu.is_some() || a.active_cell.is_some() || a.toolbar_panel.is_some() || a.calendar_drag.is_some() @@ -291,6 +302,19 @@ impl PlaygroundView { h.rect.contains(test_x, local_y) }) .cloned(); + // A second press counts as a double click only on the cell of the first press. + let press_cell = hit.as_ref().and_then(|h| match &h.kind { + DatabaseAuthoringHitKind::EditCell { + row_id, column_id, .. + } => Some((block_id.to_string(), row_id.clone(), column_id.clone())), + DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, .. } => { + Some((block_id.to_string(), row_id.clone(), "title".to_string())) + } + _ => None, + }); + let same_cell = press_cell.is_some() && self.database_hover.last_press_cell == press_cell; + let click_count = if same_cell { click_count } else { 1 }; + self.database_hover.last_press_cell = press_cell; let (pos_x, pos_y) = window .as_deref() @@ -331,6 +355,7 @@ impl PlaygroundView { if st.authoring.column_menu.is_some() || st.authoring.row_menu.is_some() || st.authoring.lane_menu.is_some() + || st.authoring.calc_menu.is_some() || st.authoring.active_cell.is_some() || st.authoring.toolbar_panel.is_some() { @@ -584,9 +609,15 @@ impl PlaygroundView { }; match outcome { Ok(res) if res.handled => { + let group = self.table_group_at(block_id, hit.rect.y + 1.0); + self.flow + .database_state + .follow_active_cell(block_id, &db_data, group.as_deref()); let mut window = window; if self.database_block_has_popover(block_id) { + // The control under the pointer can change size once its popover opens. self.overlays.hide_hover(); + self.database_hover.target = None; } if let Some(w) = window.as_deref_mut() { self.editor_focus.focus(w, cx); diff --git a/blocksuite/crates/playground/src/database_authoring/paint.rs b/blocksuite/crates/playground/src/database_authoring/paint.rs index 9bcd178516..e1c432d639 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint.rs @@ -467,6 +467,35 @@ impl PlaygroundView { let palette = self.theme.palette(); let mut out = Vec::new(); + // Over a record peek, a press outside the popover closes only the popover, never the peek. + if self.database_record_sheet.is_some() { + out.push( + div() + .absolute() + .inset_0() + .occlude() + .on_mouse_down( + ui::MouseButton::Left, + cx.listener(|this, _: &ui::MouseDownEvent, window, cx| { + if let Some(block) = this + .database_record_sheet + .as_ref() + .map(|s| s.block_id.clone()) + { + this.flow + .database_state + .authoring_mut(&block) + .dismiss_popovers(); + this.sync_database_authoring_input(Some(window), cx); + cx.notify(); + } + cx.stop_propagation(); + }), + ) + .into_any_element(), + ); + } + // Snapshot anchor + pointer shield so clicks inside the popover (or its open submenu) // never fall through to underlying block horizontal scrollbars or page controls. for (idx, rect) in [Some(bounds), overlay.submenu_bounds] diff --git a/blocksuite/crates/playground/src/database_authoring/paint_hover.rs b/blocksuite/crates/playground/src/database_authoring/paint_hover.rs index 1a808a5ed3..4bdccc626a 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint_hover.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint_hover.rs @@ -6,7 +6,9 @@ use blocksuite_editor::{ block_flow::FlowRect, - database::{DatabaseAuthoringHitKind, DatabaseHitKind}, + database::{ + DatabaseAuthoringHitKind, DatabaseHitKind, DatabaseViewAction, ROW_SELECT_GUTTER_W, + }, theme::{IconPaint, Palette, TYPOGRAPHY, icons}, }; use ui::{AnyElement, FontWeight, Hsla, Window, canvas, div, prelude::*, px}; @@ -16,7 +18,7 @@ use crate::PlaygroundView; use super::{ dnd_table::{collect_table_column_rects, collect_table_row_rects}, hover::{ - CardOpHover, DatabaseHoverTargetKind, KanbanLaneOpHover, RowOpHover, + CardOpHover, DatabaseHoverTargetKind, GRIP_GUTTER_W, KanbanLaneOpHover, RowOpHover, calendar_day_new_row_rect, kanban_card_ops_rects, kanban_lane_header_ops_rects, link_cell_edit_rect, table_row_ops_rects, }, @@ -91,14 +93,121 @@ fn paint_op_button( .into_any_element() } +/// A 14 px row or select-all checkbox centered in its gutter target `rect` (screen space). +fn paint_row_checkbox( + rect: FlowRect, + checked: bool, + partial: bool, + palette: &Palette, + snapshot_id: &'static str, +) -> AnyElement { + let icon = IconPaint::from_def(if checked { + &icons::CHECKBOX_CHECKED_SOLID + } else { + &icons::CHECKBOX_UNCHECKED + }); + let color = if checked || partial { + palette.brand + } else { + palette.icon + }; + let size = 14.0; + div() + .absolute() + .left(px(rect.x + (rect.w - size) * 0.5)) + .top(px(rect.y + (rect.h.min(34.0) - size) * 0.5)) + .w(px(size)) + .h(px(size)) + .snapshot(snapshot_id, None) + .child( + canvas( + |_, _, _| {}, + move |bounds, _, window, cx| icon.paint(bounds, color, window, cx), + ) + .size_full(), + ) + .into_any_element() +} + impl PlaygroundView { + /// Row checkboxes of checked rows and of the hovered row, and the select-all checkbox of a + /// hovered table or of a table with checked rows. + fn database_row_checkbox_elements( + &self, + palette: &Palette, + window: &Window, + ) -> Vec { + let mut out = Vec::new(); + if self.is_database_write_readonly() { + return out; + } + let hovered_block = self.database_hover.block_id.as_deref(); + let hovered_row = match &self.database_hover.target { + Some(DatabaseHoverTargetKind::TableRow { row_id, .. }) => Some(row_id.as_str()), + _ => None, + }; + let hovering_table = matches!( + self.database_hover.target, + Some( + DatabaseHoverTargetKind::TableRow { .. } + | DatabaseHoverTargetKind::TableHeader { .. } + ) + ); + let mut blocks: Vec = self + .flow + .database_state + .states() + .filter(|(_, st)| !st.selected_rows.is_empty()) + .map(|(id, _)| id.clone()) + .collect(); + if let Some(id) = hovered_block.filter(|id| !blocks.iter().any(|b| b == id)) { + blocks.push(id.to_string()); + } + for block_id in blocks { + let selected = self.flow.database_state.state_for(&block_id).selected_rows; + let hovered_here = hovered_block == Some(block_id.as_str()); + for hit in self.flow.database_authoring_hits(&block_id) { + let DatabaseAuthoringHitKind::View(action) = &hit.kind else { + continue; + }; + let (checked, partial, id) = match action { + DatabaseViewAction::ToggleRowSelected { row_id } => { + let checked = selected.contains(row_id); + if !checked && !(hovered_here && hovered_row == Some(row_id.as_str())) { + continue; + } + (checked, false, "overlay.table_row_checkbox") + } + DatabaseViewAction::ToggleAllRowsSelected { row_ids } => { + let count = row_ids.iter().filter(|id| selected.contains(*id)).count(); + if count == 0 && !(hovered_here && hovering_table) { + continue; + } + ( + count == row_ids.len(), + count > 0, + "overlay.table_select_all", + ) + } + _ => continue, + }; + if let Some(sr) = + self.database_local_rect_to_screen(&block_id, hit.rect, false, window) + { + out.push(paint_row_checkbox(sr, checked, partial, palette, id)); + } + } + } + out + } + /// Paint-only hover overlay elements for `self.database_hover` (zero layout invalidation). pub(crate) fn database_hover_overlay_elements( &self, palette: &Palette, window: &Window, ) -> Vec { - let mut out = Vec::new(); + let mut out = self.database_row_checkbox_elements(palette, window); if self.database_drag.is_some() || self.database_hover_suppressed_by_modal_or_menu() || self.database_hover.doc_rev != self.doc_rev @@ -137,8 +246,10 @@ impl PlaygroundView { scrolls_x, radius, } => { - if let Some(sr) = - self.database_local_rect_to_screen(block_id, *rect, *scrolls_x, window) + // An open popover takes the hover; a control under it can change size meanwhile. + if !self.database_block_has_popover(block_id) + && let Some(sr) = + self.database_local_rect_to_screen(block_id, *rect, *scrolls_x, window) { out.push(paint_hover_fill(sr, *radius, palette.hover, None)); } @@ -193,7 +304,7 @@ impl PlaygroundView { let grip_hovered = matches!(op_hover, Some(RowOpHover::Grip)); let bar_w = if grip_hovered { 2.0 } else { 4.0 }; let bar_h = 12.0_f32; - let hx = sr.x - 12.0; + let hx = sr.x - GRIP_GUTTER_W; let hy = sr.y + ((sr.h - bar_h) * 0.5).max(2.0); let bar_color = if grip_hovered { palette.brand @@ -203,9 +314,9 @@ impl PlaygroundView { out.push( div() .absolute() - .left(px(hx - 6.0)) + .left(px(hx)) .top(px(hy - 4.0)) - .w(px(16.0)) + .w(px(GRIP_GUTTER_W - ROW_SELECT_GUTTER_W - 2.0)) .h(px(20.0)) .flex() .items_center() diff --git a/blocksuite/crates/playground/src/database_authoring/record_title.rs b/blocksuite/crates/playground/src/database_authoring/record_title.rs index 9413d15eb7..4c6275aa5b 100644 --- a/blocksuite/crates/playground/src/database_authoring/record_title.rs +++ b/blocksuite/crates/playground/src/database_authoring/record_title.rs @@ -145,6 +145,7 @@ impl PlaygroundView { DatabaseInlineTarget::SelectFilter { .. } | DatabaseInlineTarget::ColumnRename { .. } | DatabaseInlineTarget::FilterValue { .. } + | DatabaseInlineTarget::ViewField { .. } ) }) else { return Vec::new(); @@ -231,10 +232,11 @@ impl PlaygroundView { || a.column_menu.is_some() || a.row_menu.is_some() || a.lane_menu.is_some() + || a.calc_menu.is_some() || a.toolbar_panel.is_some() || a.active_cell .as_ref() - .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select")) + .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select" | "date")) } /// Close any pending `RecordPeek` and start in-place title editing on the Calendar event diff --git a/blocksuite/crates/playground/src/database_authoring/tests.rs b/blocksuite/crates/playground/src/database_authoring/tests.rs index 46aad3e865..ee7c239998 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests.rs @@ -153,7 +153,7 @@ pub(super) fn build_e2e_database_doc() -> (DocState, String) { (doc, db_id) } -fn key_event(key: &str, key_char: Option<&str>, modifiers: Modifiers) -> KeyDownEvent { +pub(super) fn key_event(key: &str, key_char: Option<&str>, modifiers: Modifiers) -> KeyDownEvent { KeyDownEvent { keystroke: Keystroke { modifiers, @@ -165,7 +165,7 @@ fn key_event(key: &str, key_char: Option<&str>, modifiers: Modifiers) -> KeyDown } } -fn undo_modifiers() -> Modifiers { +pub(super) fn undo_modifiers() -> Modifiers { if cfg!(target_os = "macos") { Modifiers { platform: true, @@ -179,7 +179,7 @@ fn undo_modifiers() -> Modifiers { } } -fn read_db(view: &PlaygroundView, db_id: &str) -> DatabaseData { +pub(super) fn read_db(view: &PlaygroundView, db_id: &str) -> DatabaseData { let snap = view.snapshot.as_ref().expect("snapshot"); let BlockContent::Database(db) = &snap.block(db_id).expect("db").content else { panic!("expected database"); @@ -187,7 +187,7 @@ fn read_db(view: &PlaygroundView, db_id: &str) -> DatabaseData { db.clone() } -fn screen_pt_for_auth_hit( +pub(super) fn screen_pt_for_auth_hit( view: &PlaygroundView, window: &ui::Window, db_id: &str, @@ -227,7 +227,7 @@ fn screen_pt_for_auth_hit( ) } -fn screen_pt_for_db_hit( +pub(super) fn screen_pt_for_db_hit( view: &PlaygroundView, window: &ui::Window, db_id: &str, diff --git a/blocksuite/crates/playground/src/database_authoring/tests_dnd_grouped.rs b/blocksuite/crates/playground/src/database_authoring/tests_dnd_grouped.rs index e5c3ca895a..2b9859e966 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_dnd_grouped.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_dnd_grouped.rs @@ -222,7 +222,7 @@ fn grouped_table_row_drag_left_gutter_title_click_column_menu_zero_flash_and_cal // 1. Grouped Table (`groupBy = col-status`, `Todo = [r3, r2, r1]`): // - Plain click at `row.x + 10` (first 16 px of Title cell) opens `ActiveCellEditor`. // - MouseDown on `OpenColumnMenu` does NOT open `column_menu` until `!promoted` MouseUp. - // - Left-gutter drag (`row.x - 10`) reorders within `Todo` AND moves across groups to `Doing`! + // - Left-gutter drag (`row.x - 23`) reorders within `Todo` AND moves across groups to `Doing`! let (mut doc, db_id) = build_db_doc("table", false); { let page = doc.workspace.ensure_page(HOME_PAGE_ID).unwrap(); @@ -348,7 +348,7 @@ fn grouped_table_row_drag_left_gutter_title_click_column_menu_zero_flash_and_cal let r3_title = hit_center( &|k| matches!(k, DatabaseAuthoringHitKind::EditCell { row_id, column_id, .. } if row_id == "r3" && column_id == "title"), ); - let gutter_x = r1_title.0 - 110.0; + let gutter_x = r1_title.0 - 123.0; mouse_down(&hw, gutter_x, r1_title.1); mouse_move(&hw, gutter_x, r3_title.1 - 12.0, true); hw.request_frame(); diff --git a/blocksuite/crates/playground/src/database_authoring/tests_dnd_lane_order.rs b/blocksuite/crates/playground/src/database_authoring/tests_dnd_lane_order.rs index 38f61dade4..d52d85ce3e 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_dnd_lane_order.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_dnd_lane_order.rs @@ -244,7 +244,7 @@ fn kanban_and_grouped_table_drag_into_non_first_lane_preserves_lane_order() { }; let r1_title = hit_title("r1"); let r4_title = hit_title("r4"); - let gutter_x = r1_title.0 - 110.0; + let gutter_x = r1_title.0 - 123.0; mouse_down(&thw, gutter_x, r1_title.1); mouse_move(&thw, gutter_x, (r1_title.1 + r4_title.1) * 0.5, true); thw.request_frame(); diff --git a/blocksuite/crates/playground/src/database_authoring/tests_dnd_motion.rs b/blocksuite/crates/playground/src/database_authoring/tests_dnd_motion.rs index 16d7120a0d..58de8ad4da 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_dnd_motion.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_dnd_motion.rs @@ -475,7 +475,7 @@ fn table_row_and_column_drag_reorder_with_single_undo() { let r3 = hit_center( &|k| matches!(k, DatabaseAuthoringHitKind::EditCell { row_id, column_id, .. } if row_id == "r3" && column_id == "title"), ); - let handle_x = r1.0 - 110.0; + let handle_x = r1.0 - 123.0; mouse_down(&hw, handle_x, r1.1); mouse_move(&hw, handle_x + 8.0, r3.1 + 14.0, true); hw.request_frame(); 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 42de89d402..ce2cce0314 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 @@ -89,7 +89,7 @@ fn database_hover_cursors_popover_isolation_and_desktop_peek_and_row_ops() { ( (resize.x + resize.w * 0.5, resize.y + resize.h * 0.5), (title.x + 12.0, title.y + title.h * 0.5), - (title.x - 10.0, title.y + title.h * 0.5), + (title.x - 23.0, title.y + title.h * 0.5), (peek_r.x + peek_r.w * 0.5, peek_r.y + peek_r.h * 0.5), (menu_r.x + menu_r.w * 0.5, menu_r.y + menu_r.h * 0.5), (col_hdr.x + 16.0, col_hdr.y + col_hdr.h * 0.5), diff --git a/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs b/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs index e8accaef36..cb69cdf071 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs @@ -643,7 +643,7 @@ fn table_row_grip_under_horizontal_scroll_stays_in_fixed_gutter_keeps_scroll_and }) .unwrap() }); - let grip_x = origin_x + r1.x - 10.0; + let grip_x = origin_x + r1.x - 23.0; let r1_y = origin_y + r1.y + r1.h * 0.5; // 1. Hovering the left gutter paints the grip right beside the grid's fixed left edge. @@ -656,7 +656,7 @@ fn table_row_grip_under_horizontal_scroll_stays_in_fixed_gutter_keeps_scroll_and .expect("row grip painted under scroll_x = 40") .bounds; assert!( - (grip.x - (origin_x + r1.x - 18.0)).abs() < 0.5 && grip.x + grip.width <= origin_x + r1.x, + (grip.x - (origin_x + r1.x - 28.0)).abs() < 0.5 && grip.x + grip.width <= origin_x + r1.x, "grip must sit in the fixed gutter left of the row (row x {}), got {grip:?}", origin_x + r1.x ); 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 index f890be870a..6d979a1292 100644 --- 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 @@ -324,3 +324,76 @@ fn record_add_property_creates_the_chosen_type_in_one_undo_step() { assert!(f.sheet_open()); } } + +#[test] +fn record_date_field_opens_the_month_picker_above_the_peek_and_writes_a_pick() { + use DatabaseAuthoringHitKind as Hit; + use blocksuite_editor::database::DatabaseViewAction; + let f = Fixture::open(); + f.click(f.capsule, 1); + assert!(f.sheet_open()); + let due = || { + f.update(|v, _, _| { + v.database_snapshot_data(&f.db_id) + .unwrap() + .cells + .get(&("r1".into(), "c-due".into())) + .and_then(DatabaseCellValue::as_i64) + }) + }; + let original = due().expect("r1 has a due date"); + let open_picker = || { + let field = f.update(|v, w, _| v.record_value_rect(RecordSlot::Field("c-due"), w).unwrap()); + f.click(point(px(field.x + 20.0), px(field.y + field.h * 0.5)), 1); + }; + // (day index, screen point) of the picker's day cells; empty when no picker is shown. + let days = || { + f.update(|v, w, _| { + let Some((_, panel)) = v.database_popover_overlay(&v.flow_layout().unwrap(), w) else { + return Vec::new(); + }; + panel + .hits + .iter() + .filter_map(|h| match h.kind { + Hit::View(DatabaseViewAction::DatePickerPick { day_index }) => Some(( + day_index, + point(px(h.rect.x + h.rect.w * 0.5), px(h.rect.y + h.rect.h * 0.5)), + )), + _ => None, + }) + .collect::>() + }) + }; + + // 1. A press on the `Date` value opens the month grid, painted above the peek. + open_picker(); + let grid = days(); + assert_eq!(grid.len(), 42, "a 7 × 6 day grid"); + let peek = f.snapshot_bounds("overlay.database_record_sheet").unwrap(); + let popover = f + .snapshot_bounds("overlay.database_popover") + .expect("the picker paints above the peek"); + assert!(popover.origin.y >= peek.origin.y); + + // 2. A pick writes the day and leaves the peek open; one undo restores the date. + let (day, at) = grid[grid.len() - 1]; + f.click(at, 1); + let picked = due().unwrap(); + let local_day = f.update(|v, _, _| { + blocksuite_editor::database::local_day_index(picked, &v.utc_offset_resolver()) + }); + assert_eq!(local_day, day); + assert!(f.sheet_open()); + assert!(days().is_empty(), "a pick closes the picker"); + f.undo_once(); + assert_eq!(due(), Some(original)); + + // 3. A press outside the picker closes only the picker. + open_picker(); + assert!(!days().is_empty()); + f.click(point(px(6.0), px(814.0)), 1); + assert!(days().is_empty()); + assert!(f.sheet_open(), "the peek stays open"); + assert_eq!(due(), Some(original)); +} diff --git a/blocksuite/crates/playground/src/database_authoring/tests_row_selection_scope.rs b/blocksuite/crates/playground/src/database_authoring/tests_row_selection_scope.rs new file mode 100644 index 0000000000..584a872466 --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/tests_row_selection_scope.rs @@ -0,0 +1,230 @@ +//! End-to-end tests that Table row selection acts only on the rows the view shows: a search, a +//! filter, a hidden or collapsed group, or a peer that hides or deletes a checked row keeps it +//! out of the selection bar, select-all, `Delete`, and `Backspace`. + +use blocksuite_editor::database::{DatabaseAuthoringHitKind, DatabaseHitKind, DatabaseViewAction}; +use blocksuite_playground_doc::read::DatabaseGroupBy; +use ui::Modifiers; + +use super::{tests::screen_pt_for_db_hit, tests_view_controls::Fixture}; +use crate::PlaygroundTheme; + +fn ids(f: &Fixture) -> Vec { + f.db().rows.iter().map(|r| r.row_id.clone()).collect() +} + +fn selected(f: &Fixture) -> Vec { + let db = f.db.clone(); + f.update(|v, _, _| { + v.flow + .database_state + .state_for(&db) + .selected_rows + .into_iter() + .collect() + }) +} + +/// The rows the selection bar `Delete` removes, or `None` when the bar is hidden. +fn bar_rows(f: &Fixture) -> Option> { + let db = f.db.clone(); + f.update(|v, _, _| { + v.flow + .database_authoring_hits(&db) + .iter() + .find_map(|h| match &h.kind { + DatabaseAuthoringHitKind::View(DatabaseViewAction::DeleteSelectedRows { + row_ids, + }) => Some(row_ids.clone()), + _ => None, + }) + }) +} + +fn select(f: &Fixture, row: &str) { + f.view_action(DatabaseViewAction::ToggleRowSelected { row_id: row.into() }); +} + +fn search(f: &Fixture, query: &str) { + f.view_action(DatabaseViewAction::ToggleSearch); + f.type_text(query); + f.key("enter", Modifiers::default()); +} + +fn clear_search(f: &Fixture) { + f.view_action(DatabaseViewAction::ToggleSearch); + f.view_action(DatabaseViewAction::ClearSearch); +} + +#[test] +fn search_filter_and_peer_deletes_keep_hidden_rows_out_of_selection_bar_and_delete() { + let f = Fixture::open(PlaygroundTheme::Light); + let all = ["r1", "r2", "r3", "r4", "r5"]; + + // 1. A search hides a checked row: it leaves the selection, the bar counts the shown one, + // and `Backspace` deletes only that row. + select(&f, "r1"); + select(&f, "r2"); + search(&f, "card two"); + assert_eq!(selected(&f), ["r2"]); + assert_eq!(bar_rows(&f).as_deref(), Some(&["r2".to_string()][..])); + f.key("backspace", Modifiers::default()); + assert_eq!(ids(&f), ["r1", "r3", "r4", "r5"]); + f.undo(); + assert_eq!(ids(&f), all); + + // 2. With every checked row hidden, `Backspace` deletes nothing. + clear_search(&f); + select(&f, "r1"); + search(&f, "five"); + assert!(selected(&f).is_empty()); + assert_eq!(bar_rows(&f), None); + f.key("backspace", Modifiers::default()); + assert_eq!(ids(&f), all); + + // 3. Select-all checks only the rows the search shows; the bar `Delete` removes them. + clear_search(&f); + search(&f, "card t"); + f.click(|k| { + matches!( + k, + DatabaseAuthoringHitKind::View(DatabaseViewAction::ToggleAllRowsSelected { .. }) + ) + }); + assert_eq!(selected(&f), ["r2", "r3"]); + f.click(|k| { + matches!( + k, + DatabaseAuthoringHitKind::View(DatabaseViewAction::DeleteSelectedRows { .. }) + ) + }); + assert_eq!(ids(&f), ["r1", "r4", "r5"]); + f.undo(); + assert_eq!(ids(&f), all); + + // 4. A view filter written to the document hides a checked row the same way. + clear_search(&f); + for row in ["r2", "r4", "r5"] { + select(&f, row); + } + let db = f.db.clone(); + f.update(|v, _, cx| { + let page = v.page_mut().unwrap(); + let filter = serde_json::json!({ + "type": "group", + "op": "and", + "conditions": [{ + "type": "filter", + "left": { "type": "ref", "name": "col-est" }, + "function": "greatThan", + "args": [{ "type": "constant", "value": 4 }] + }] + }); + page.set_database_view_filter(&db, "v-table", Some(filter), 9) + .unwrap(); + page.stop_capturing().unwrap(); + v.refresh_document(); + cx.notify(); + }); + assert_eq!(selected(&f), ["r2", "r4"], "`r5` estimates 1.5"); + + // 5. A peer deletes a checked row: no stale id stays checked. + f.update(|v, _, cx| { + let page = v.page_mut().unwrap(); + page.delete_database_row(&db, "r2", 10).unwrap(); + page.stop_capturing().unwrap(); + v.refresh_document(); + cx.notify(); + }); + assert_eq!(selected(&f), ["r4"]); + assert_eq!(bar_rows(&f).as_deref(), Some(&["r4".to_string()][..])); +} + +/// Group the Table by `Status`, with `hide` set on the groups `hidden`. +fn group_table(f: &Fixture, hidden: &[&str]) { + let db = f.db.clone(); + f.update(|v, _, cx| { + let page = v.page_mut().unwrap(); + let group_by = DatabaseGroupBy { + kind: "groupBy".into(), + column_id: "col-status".into(), + name: "select".into(), + sort: None, + hide_empty: None, + }; + page.set_database_view_group_by(&db, "v-table", Some(group_by), 20) + .unwrap(); + page.stop_capturing().unwrap(); + v.refresh_document(); + cx.notify(); + }); + let props: Vec<_> = ["Ungroups", "opt-todo", "opt-doing", "opt-done"] + .iter() + .map(|key| serde_json::json!({ "key": key, "hide": hidden.contains(key) })) + .collect(); + f.set_group_properties("v-table", serde_json::Value::Array(props)); +} + +fn reopened_ids(f: &Fixture) -> Vec { + f.reopened_db().rows.into_iter().map(|r| r.row_id).collect() +} + +#[test] +fn hidden_and_collapsed_groups_keep_their_rows_out_of_select_all_and_delete() { + let f = Fixture::open(PlaygroundTheme::Light); + let all = ["r1", "r2", "r3", "r4", "r5"]; + let delete_bar = |k: &DatabaseAuthoringHitKind| { + matches!( + k, + DatabaseAuthoringHitKind::View(DatabaseViewAction::DeleteSelectedRows { .. }) + ) + }; + + // 1. The hidden `Todo` group shows none of `r1..r3`: select-all checks `r4` and `r5`, and + // the bar `Delete` removes only them in one undo step. + group_table(&f, &["opt-todo"]); + f.click(|k| { + matches!( + k, + DatabaseAuthoringHitKind::View(DatabaseViewAction::ToggleAllRowsSelected { .. }) + ) + }); + assert_eq!(selected(&f), ["r4", "r5"]); + assert_eq!(bar_rows(&f), Some(vec!["r4".into(), "r5".into()])); + f.click(delete_bar); + assert_eq!(reopened_ids(&f), ["r1", "r2", "r3"]); + f.undo(); + assert_eq!(reopened_ids(&f), all); + + // 2. Rows checked in two groups, then a click collapses `Todo`: the bar, `Delete`, and + // `Backspace` act only on the checked row of the expanded `Doing` group. + group_table(&f, &[]); + let collapse_todo = |f: &Fixture| { + let db = f.db.clone(); + let pt = f.update(|v, w, _| { + screen_pt_for_db_hit(v, w, &db, |k| { + matches!(k, DatabaseHitKind::ToggleGroup { group_key } if group_key == "opt-todo") + }) + }); + f.hw.simulate_click(pt); + f.tick(); + }; + for (step, delete) in [ + ("bar", None), + ("backspace", Some("backspace")), + ("delete", Some("delete")), + ] { + select(&f, "r2"); + select(&f, "r4"); + collapse_todo(&f); + assert_eq!(bar_rows(&f), Some(vec!["r4".into()]), "{step}"); + match delete { + None => f.click(delete_bar), + Some(key) => f.key(key, Modifiers::default()), + } + assert_eq!(reopened_ids(&f), ["r1", "r2", "r3", "r5"], "{step}"); + f.undo(); + assert_eq!(reopened_ids(&f), all, "{step}"); + collapse_todo(&f); + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/tests_sideways_scroll_controls.rs b/blocksuite/crates/playground/src/database_authoring/tests_sideways_scroll_controls.rs new file mode 100644 index 0000000000..966fd6efb3 --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/tests_sideways_scroll_controls.rs @@ -0,0 +1,208 @@ +//! End-to-end tests of the database controls that must stay with their targets while a wide +//! Table or Kanban scrolls sideways: the row selection bar, the `+ Add Group` popover, and the +//! row drag grip at the left edge of the block. + +use blocksuite_editor::database::{DatabaseAuthoringHitKind, DatabaseViewAction}; +use blocksuite_playground_doc::schema::DatabaseColumnSpec; +use serde_json::json; +use ui::CursorStyle; + +use super::{ + DatabaseDragState, + dnd_table::collect_table_row_rects, + tests_dnd_motion::{mouse_down, mouse_move, mouse_up}, + tests_view_controls::Fixture, +}; +use crate::PlaygroundTheme; + +/// Add eight number columns so the Table overflows, then scroll the database to its end. +/// Returns the top of the sideways scroll area. +fn widen_and_scroll(f: &Fixture) -> f32 { + let db = f.db.clone(); + f.update(|v, _, cx| { + let page = v.page_mut().unwrap(); + for i in 0..8 { + let spec = DatabaseColumnSpec { + id: format!("wide-{i}"), + column_type: "number".into(), + name: format!("Wide {i}"), + data: json!({}), + }; + page.add_database_column(&db, None, spec, None, 20 + i) + .unwrap(); + } + page.stop_capturing().unwrap(); + v.refresh_document(); + cx.notify(); + }); + scroll_to_end(f) +} + +fn scroll_to_end(f: &Fixture) -> f32 { + let db = f.db.clone(); + f.update(|v, _, cx| { + let cs = v + .flow_layout() + .unwrap() + .block(&db) + .unwrap() + .body + .code_scroll + .expect("the database scrolls sideways"); + assert!(cs.max_x > 100.0); + v.scroll_database_x(&db, cs.max_x, cx); + cs.area.y + }) +} + +/// The selection bar `Clear` (or `Delete`) button. +fn bar_button(clear: bool) -> impl Fn(&DatabaseAuthoringHitKind) -> bool { + move |k| match k { + DatabaseAuthoringHitKind::View(DatabaseViewAction::ClearRowSelection) => clear, + DatabaseAuthoringHitKind::View(DatabaseViewAction::DeleteSelectedRows { .. }) => !clear, + _ => false, + } +} + +#[test] +fn selection_bar_sits_above_the_sideways_scroll_area_and_its_buttons_hit_under_scroll() { + let f = Fixture::open(PlaygroundTheme::Light); + let area_top = widen_and_scroll(&f); + let db = f.db.clone(); + let selected = + |f: &Fixture| f.update(|v, _, _| v.flow.database_state.state_for(&db).selected_rows.len()); + let ids = |f: &Fixture| { + f.db() + .rows + .iter() + .map(|r| r.row_id.clone()) + .collect::>() + }; + for row in ["r1", "r2"] { + f.view_action(DatabaseViewAction::ToggleRowSelected { row_id: row.into() }); + } + // The bar and its buttons lie above the scroll area: they never move with the cells. + let area_top_now = scroll_to_end(&f); + assert!( + area_top_now > area_top, + "the bar pushes the scroll area down" + ); + for clear in [true, false] { + let rect = f.hit_rect(bar_button(clear)); + assert!( + rect.bottom() <= area_top_now, + "{rect:?} must sit above the scroll area at y {area_top_now}" + ); + let scrolls = f.update(|v, _, _| { + v.flow + .database_authoring_hits(&db) + .iter() + .find(|h| bar_button(clear)(&h.kind)) + .unwrap() + .scrolls_x + }); + assert!(!scrolls); + } + // `Clear` and `Delete` hit at their painted place while the Table is scrolled. + f.click(bar_button(true)); + assert_eq!(selected(&f), 0); + for row in ["r1", "r2"] { + f.view_action(DatabaseViewAction::ToggleRowSelected { row_id: row.into() }); + } + scroll_to_end(&f); + f.click(bar_button(false)); + assert_eq!(ids(&f), ["r3", "r4", "r5"]); +} + +#[test] +fn add_group_popover_follows_the_kanban_sideways_scroll() { + let f = Fixture::open(PlaygroundTheme::Light); + f.switch_view("v-kanban"); + scroll_to_end(&f); + let db = f.db.clone(); + f.view_action(DatabaseViewAction::OpenAddGroup); + let is_add = |k: &DatabaseAuthoringHitKind| { + *k == DatabaseAuthoringHitKind::View(DatabaseViewAction::OpenAddGroup) + }; + let (hit, anchor, button_left, popover) = f.update(|v, w, _| { + let hit = v + .flow + .database_authoring_hits(&db) + .iter() + .find(|h| is_add(&h.kind)) + .unwrap() + .clone(); + let anchor = v.flow.database_popover_anchor(&db); + let center = super::tests::screen_pt_for_auth_hit(v, w, &db, is_add); + let (_, overlay) = v + .database_popover_overlay(&v.flow_layout().unwrap(), w) + .expect("the `+ Add Group` popover"); + ( + hit.clone(), + anchor, + f32::from(center.x) - hit.rect.w * 0.5, + overlay.bounds, + ) + }); + assert!(hit.scrolls_x, "the button scrolls with the lanes"); + let anchor = anchor.expect("popover anchor"); + assert_eq!((anchor.rect, anchor.scrolls_x), (hit.rect, true)); + assert!( + popover.x <= button_left + hit.rect.w && popover.right() >= button_left, + "popover {popover:?} must open at the button (screen x {button_left})" + ); +} + +#[test] +fn row_grip_hover_and_press_share_the_left_edge_of_the_block() { + let f = Fixture::open(PlaygroundTheme::Light); + let db = f.db.clone(); + let (origin, row) = f.update(|v, w, _| { + let layout = v.flow_layout().unwrap(); + let block = layout.block(&db).unwrap(); + let geom = crate::page_geometry(f32::from(w.viewport_size().width)); + let row = collect_table_row_rects(v.flow.database_authoring_hits(&db)) + .into_iter() + .find(|(id, _)| id == "r2") + .unwrap() + .1; + ( + ( + geom.column_x + block.x, + crate::TOPBAR_HEIGHT + block.y - v.scroll_y, + ), + row, + ) + }); + let y = origin.1 + row.y + row.h * 0.5; + // (block-local x, grip under the pointer). A press reaches the block from x = -20. + for (local_x, grip) in [ + (-20.25, false), + (-19.75, true), + (-15.0, true), + (-10.25, true), + ] { + let x = origin.0 + local_x; + mouse_move(&f.hw, x, y, false); + f.tick(); + let cursor = f.update(|v, _, _| v.database_hover_cursor()); + assert_eq!( + cursor == Some(CursorStyle::OpenHand), + grip, + "hover at local x {local_x}: {cursor:?}" + ); + mouse_down(&f.hw, x, y); + f.tick(); + let dragging = f.update(|v, _, _| { + let dragging = matches!( + &v.database_drag, + Some(DatabaseDragState::TableRowReorder { row_id, .. }) if row_id == "r2" + ); + v.database_drag = None; + dragging + }); + mouse_up(&f.hw, x, y); + f.tick(); + assert_eq!(dragging, grip, "press at local x {local_x}"); + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/tests_view_controls.rs b/blocksuite/crates/playground/src/database_authoring/tests_view_controls.rs new file mode 100644 index 0000000000..e9149b8144 --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/tests_view_controls.rs @@ -0,0 +1,610 @@ +//! End-to-end tests of the `Date` picker, Table row selection with batch delete, Table cell +//! keyboard navigation, and the same-cell double click guard. + +use std::{collections::BTreeMap, rc::Rc}; + +use blocksuite_editor::{ + block_flow::FlowRect, + database::{DatabaseAuthoringHitKind, DatabaseViewAction, days_from_civil, local_day_index}, +}; +use blocksuite_playground_doc::{ + DocResult, + read::{BlockContent, DatabaseCellValue, DatabaseData}, + schema::{ + BlockSpec, DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec, + ParagraphType, json_to_session_value, + }, + session::PageDocSession, +}; +use serde_json::json; +use ui::{ + AppContext, Application, Bounds, HeadlessPlatform, Modifiers, WindowBounds, WindowOptions, + point, px, size, +}; +use y_octo::{Any, SessionReadValue, TypePath, TypeTarget}; + +use super::tests::{key_event, read_db, screen_pt_for_auth_hit, undo_modifiers}; +use crate::{ + HOME_PAGE_ID, PlaygroundOptions, PlaygroundTheme, PlaygroundView, room_client::DocState, +}; + +const DAY_MS: i64 = 86_400_000; +/// `2026-03-09T12:00:00Z`, the fixed calendar clock of the fixture. +pub(super) const CLOCK_MS: i64 = 1_773_057_600_000; + +/// A database with `title`, `Status` (select), `Start` (date), `Estimate` (number), and +/// `Progress` columns, +/// five rows, and a Table, a Kanban, and a Calendar view. +fn build_controls_doc(kanban_group_properties: Option) -> (DocState, String) { + let mut doc = DocState::new("db-view-controls", 91).expect("doc"); + doc.workspace.initialize_meta().unwrap(); + doc.workspace + .create_page(HOME_PAGE_ID, "View controls", 1_773_000_000_000) + .unwrap(); + let page = doc.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + page.add_block( + "p-root", + BlockSpec::Page { + title: "View controls".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block( + "p-note", + BlockSpec::Note { xywh: None }, + Some("p-root"), + None, + 2, + ) + .unwrap(); + let db_id = "db-controls".to_string(); + let base_day = CLOCK_MS.div_euclid(DAY_MS); + let rows = [ + ("r1", "Card One", "opt-todo", 0, Some(3.0), 20), + ("r2", "Card Two", "opt-todo", 3 * DAY_MS, Some(5.0), 45), + ( + "r3", + "Card Three", + "opt-todo", + 4 * DAY_MS + 34_200_000, + None, + 60, + ), + ("r4", "Card Four", "opt-doing", 6 * DAY_MS, Some(8.0), 80), + ("r5", "Card Five", "opt-doing", 8 * DAY_MS, Some(1.5), 100), + ]; + let mut cells = BTreeMap::new(); + for (rid, _, status, start, est, progress) in rows { + let mut row = BTreeMap::from([ + ( + "col-status".to_string(), + DatabaseCellSpec::Text(status.into()), + ), + ( + "col-start".to_string(), + DatabaseCellSpec::Integer(base_day * DAY_MS + start), + ), + ("col-prog".to_string(), DatabaseCellSpec::Integer(progress)), + ]); + if let Some(est) = est { + row.insert("col-est".into(), DatabaseCellSpec::Number(est)); + } + cells.insert(rid.to_string(), row); + } + let column = |id: &str, ty: &str, name: &str, data| DatabaseColumnSpec { + id: id.into(), + column_type: ty.into(), + name: name.into(), + data, + }; + let view = |id: &str, mode: &str, raw| DatabaseViewSpec { + id: id.into(), + name: mode.into(), + mode: mode.into(), + raw, + }; + let mut kanban = json!({ + "groupBy": { "type": "groupBy", "columnId": "col-status", "name": "select" }, + "columns": [{ "id": "title" }, { "id": "col-est" }] + }); + if let Some(properties) = kanban_group_properties { + kanban["groupProperties"] = properties; + } + page.add_block( + &db_id, + BlockSpec::Database(DatabaseSpec { + title: "Sprint".into(), + columns: vec![ + column("title", "title", "Title", json!({})), + column( + "col-status", + "select", + "Status", + json!({ "options": [ + { "id": "opt-todo", "value": "Todo", "color": "var(--affine-tag-blue)" }, + { "id": "opt-doing", "value": "Doing", "color": "var(--affine-tag-orange)" }, + { "id": "opt-done", "value": "Done", "color": "var(--affine-tag-green)" } + ] }), + ), + column("col-start", "date", "Start", json!({})), + column("col-est", "number", "Estimate", json!({})), + column("col-prog", "progress", "Progress", json!({})), + ], + views: vec![ + view( + "v-table", + "table", + json!({ "columns": [ + { "id": "title", "width": 180 }, + { "id": "col-status", "width": 110 }, + { "id": "col-start", "width": 130 }, + { "id": "col-est", "width": 100 }, + { "id": "col-prog", "width": 130 } + ] }), + ), + view("v-kanban", "kanban", kanban), + view("v-cal", "calendar", json!({ "date": { "startColumnId": "col-start" } })), + ], + cells, + }), + Some("p-note"), + None, + 3, + ) + .unwrap(); + for (idx, (rid, title, ..)) in rows.into_iter().enumerate() { + page.add_block( + rid, + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: title.into(), + }, + Some(&db_id), + None, + 4 + idx as u64, + ) + .unwrap(); + } + page.stop_capturing().unwrap(); + (doc, db_id) +} + +/// A headless desktop window on [`build_controls_doc`] with a fixed calendar clock. +pub(super) struct Fixture { + pub platform: Rc, + pub app: ui::ApplicationHandle, + pub win: ui::WindowHandle, + pub hw: ui::HeadlessWindow, + pub db: String, +} + +impl Fixture { + pub(super) fn open(theme: PlaygroundTheme) -> Self { + Self::open_with_kanban_groups(theme, None) + } + + pub(super) fn open_with_kanban_groups( + theme: PlaygroundTheme, + kanban_group_properties: Option, + ) -> Self { + let platform = HeadlessPlatform::new(1280, 900, 1.0); + let (doc, db) = build_controls_doc(kanban_group_properties); + let cell = Rc::new(std::cell::RefCell::new(None)); + let out = cell.clone(); + let app = Application::with_platform(platform.clone()).run_embedded(move |cx| { + let _ = crate::register_bundled_fonts(cx); + let options = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(1280.0), px(900.0)), + ))), + ..WindowOptions::default() + }; + let handle = cx + .open_window(options, |_, cx| { + cx.new(|cx| { + let mut v = PlaygroundView::with_options( + PlaygroundOptions { + theme, + ..Default::default() + }, + cx, + ); + v.set_calendar_clock(Some(Rc::new(|| (CLOCK_MS, 0)))); + v.set_document(doc, cx); + v + }) + }) + .unwrap(); + *out.borrow_mut() = Some(handle); + }); + let win = cell.borrow_mut().take().expect("window"); + let hw = platform + .windows() + .into_iter() + .next() + .expect("headless window"); + let fixture = Self { + platform, + app, + win, + hw, + db, + }; + fixture.tick(); + fixture + } + + pub(super) fn tick(&self) { + self.platform.run_until_parked(); + self.hw.request_frame(); + self.platform.run_until_parked(); + } + + pub(super) fn update( + &self, + f: impl FnOnce(&mut PlaygroundView, &mut ui::Window, &mut ui::Context) -> R, + ) -> R { + let out = self.app.update(|cx| self.win.update(cx, f)).unwrap(); + self.tick(); + out + } + + pub(super) fn db(&self) -> DatabaseData { + let db = self.db.clone(); + self.update(|v, _, _| read_db(v, &db)) + } + + /// Click the center of the first authoring hit (popover first) that matches `pred`. + pub(super) fn click(&self, pred: impl Fn(&DatabaseAuthoringHitKind) -> bool) { + let db = self.db.clone(); + let pt = self.update(|v, w, _| screen_pt_for_auth_hit(v, w, &db, pred)); + self.hw.simulate_click(pt); + self.tick(); + } + + pub(super) fn view_action(&self, action: DatabaseViewAction) { + self.click(|k| *k == DatabaseAuthoringHitKind::View(action.clone())); + } + + pub(super) fn key(&self, key: &str, modifiers: Modifiers) { + let event = key_event(key, None, modifiers); + self.update(|v, w, cx| v.editor_key_down(&event, w, cx)); + } + + pub(super) fn undo(&self) { + self.key("z", undo_modifiers()); + } + + pub(super) fn type_text(&self, text: &str) { + self.update(|v, w, cx| { + v.database_authoring_input_edit(w, cx, |a| a.input.replace(None, text)) + }); + } + + /// Switch the database to view `view_id`. + pub(super) fn switch_view(&self, view_id: &str) { + let db = self.db.clone(); + self.update(|v, _, cx| { + v.flow.database_state.set_active_view(&db, view_id); + cx.notify(); + }); + } + + /// The block-local rect of the first authoring hit that matches `pred`. + pub(super) fn hit_rect(&self, pred: impl Fn(&DatabaseAuthoringHitKind) -> bool) -> FlowRect { + let db = self.db.clone(); + self.update(|v, _, _| { + v.flow + .database_authoring_hits(&db) + .iter() + .find(|h| pred(&h.kind)) + .expect("authoring hit") + .rect + }) + } + + /// Write `props` as the `groupProperties` of view `view_id` in one undo step. + pub(super) fn set_group_properties(&self, view_id: &str, props: serde_json::Value) { + let db = self.db.clone(); + self.update(|v, _, cx| { + let page = v.page_mut().unwrap(); + page.structural_edit(21, |page: &mut PageDocSession| -> DocResult<()> { + let views = TypeTarget::Path(TypePath::root("blocks").key(&db).key("prop:views")); + for item in page.inner().read_array(&views)? { + let SessionReadValue::Map(id) = item else { + continue; + }; + let view = TypeTarget::Identity(id); + if matches!( + page.inner().get_map_value(&view, "id")?, + Some(SessionReadValue::Any(Any::String(ref id))) if id == view_id + ) { + let value = json_to_session_value(&props); + page.inner_mut() + .map_set(&view, "groupProperties".into(), value)?; + } + } + Ok(()) + }) + .unwrap(); + page.stop_capturing().unwrap(); + v.refresh_document(); + cx.notify(); + }); + } + + /// The database as a fresh replica reads it from the V1 update of the page. + pub(super) fn reopened_db(&self) -> DatabaseData { + let db = self.db.clone(); + let v1 = self.update(|v, _, _| v.page().unwrap().encode_update_v1().unwrap()); + let mut replica = PageDocSession::new(HOME_PAGE_ID, 4242).unwrap(); + replica.apply_remote_update_v1(&v1).unwrap(); + let snap = replica.read_page_snapshot().unwrap(); + match &snap.block(&db).expect("database").content { + BlockContent::Database(data) => data.clone(), + _ => panic!("expected database"), + } + } +} + +fn start_of(db: &DatabaseData, row: &str) -> Option { + db.cells + .get(&(row.to_string(), "col-start".to_string())) + .and_then(DatabaseCellValue::as_i64) +} + +fn edit_cell(row: &str, col: &str) -> impl Fn(&DatabaseAuthoringHitKind) -> bool { + let (row, col) = (row.to_string(), col.to_string()); + move |k| matches!(k, DatabaseAuthoringHitKind::EditCell { row_id, column_id, .. } if *row_id == row && *column_id == col) +} + +#[test] +fn date_picker_pages_months_picks_and_clears_with_reopen_and_single_undo() { + let f = Fixture::open(PlaygroundTheme::Light); + let original = start_of(&f.db(), "r3").expect("r3 start"); + let time_of_day = original.rem_euclid(DAY_MS); + assert_eq!(time_of_day, 34_200_000, "r3 starts at 09:30"); + + // 1. Clicking a `Date` cell opens the month grid of its value. + f.click(edit_cell("r3", "col-start")); + let db = f.db.clone(); + let picks = f.update(|v, w, _| { + let layout = v.flow_layout().unwrap(); + let (_, overlay) = v.database_popover_overlay(&layout, w).expect("date picker"); + overlay + .hits + .iter() + .filter(|h| { + matches!( + h.kind, + DatabaseAuthoringHitKind::View(DatabaseViewAction::DatePickerPick { .. }) + ) + }) + .count() + }); + assert_eq!(picks, 42, "a 7 × 6 day grid"); + + // 2. `›` pages to April, `Today` back to March, `›` again; picking April 15 keeps 09:30. + f.view_action(DatabaseViewAction::DatePickerStepMonth { delta: 1 }); + let month = |f: &Fixture| { + f.update(|v, _, _| { + v.flow + .database_state + .state_for(&db) + .authoring + .date_picker_month + }) + }; + assert_eq!(month(&f), Some((2026, 4))); + f.view_action(DatabaseViewAction::DatePickerToday); + assert_eq!(month(&f), Some((2026, 3))); + f.view_action(DatabaseViewAction::DatePickerStepMonth { delta: 1 }); + let april_15 = days_from_civil(2026, 4, 15); + f.view_action(DatabaseViewAction::DatePickerPick { + day_index: april_15, + }); + let picked = start_of(&f.db(), "r3"); + assert_eq!(picked, Some(april_15 * DAY_MS + time_of_day)); + f.update(|v, _, _| { + let st = v.flow.database_state.state_for(&db); + assert!( + st.authoring.active_cell.is_none(), + "a pick closes the picker" + ); + assert_eq!(st.focused_cell, Some(("r3".into(), "col-start".into()))); + }); + assert_eq!( + start_of(&f.reopened_db(), "r3"), + picked, + "V1 reopen keeps the pick" + ); + f.undo(); + assert_eq!( + start_of(&f.db(), "r3"), + Some(original), + "one undo restores the day" + ); + + // 3. `Clear` empties the cell; one undo restores it. + f.click(edit_cell("r3", "col-start")); + f.view_action(DatabaseViewAction::DatePickerClear); + assert_eq!(start_of(&f.db(), "r3"), None); + assert_eq!(start_of(&f.reopened_db(), "r3"), None); + f.undo(); + assert_eq!(start_of(&f.db(), "r3"), Some(original)); + + // 4. An empty cell picks local midnight of the day; `Escape` closes without a write. + f.click(edit_cell("r3", "col-start")); + f.key("escape", Modifiers::default()); + assert_eq!( + f.update(|v, _, _| v + .flow + .database_state + .state_for(&db) + .authoring + .active_cell + .is_none()), + true + ); + assert_eq!(start_of(&f.db(), "r3"), Some(original)); + assert_eq!( + local_day_index(CLOCK_MS, &|_| 0), + days_from_civil(2026, 3, 9) + ); +} + +#[test] +fn table_row_selection_batch_delete_navigation_and_same_cell_double_click() { + let f = Fixture::open(PlaygroundTheme::Light); + let db = f.db.clone(); + let ids = |f: &Fixture| { + f.db() + .rows + .iter() + .map(|r| r.row_id.clone()) + .collect::>() + }; + let selected = |f: &Fixture| { + f.update(|v, _, _| { + v.flow + .database_state + .state_for(&db) + .selected_rows + .into_iter() + .collect::>() + }) + }; + let select = |row: &str| DatabaseViewAction::ToggleRowSelected { row_id: row.into() }; + + // 1. Row checkboxes; `Backspace` deletes the checked rows in one undo step. + f.view_action(select("r2")); + f.view_action(select("r4")); + assert_eq!(selected(&f), ["r2", "r4"]); + let before = f.db(); + f.key("backspace", Modifiers::default()); + assert_eq!(ids(&f), ["r1", "r3", "r5"]); + assert!(selected(&f).is_empty()); + f.undo(); + let restored = f.db(); + assert_eq!(ids(&f), ["r1", "r2", "r3", "r4", "r5"]); + assert_eq!( + restored.cells, before.cells, + "one undo restores every deleted cell" + ); + + // 2. Select-all toggles all visible rows; the selection bar `Delete` deletes them as one step. + let all = |k: &DatabaseAuthoringHitKind| { + matches!( + k, + DatabaseAuthoringHitKind::View(DatabaseViewAction::ToggleAllRowsSelected { .. }) + ) + }; + f.click(all); + assert_eq!(selected(&f).len(), 5); + f.click(all); + assert!(selected(&f).is_empty()); + f.view_action(select("r1")); + f.view_action(select("r5")); + f.click(|k| { + matches!( + k, + DatabaseAuthoringHitKind::View(DatabaseViewAction::DeleteSelectedRows { .. }) + ) + }); + assert_eq!(ids(&f), ["r2", "r3", "r4"]); + f.undo(); + assert_eq!(ids(&f), ["r1", "r2", "r3", "r4", "r5"]); + + // 3. Arrow and `Tab` keys move the focused cell; `Enter` edits it. + f.click(edit_cell("r1", "title")); + f.key("escape", Modifiers::default()); + let focus = |f: &Fixture| f.update(|v, _, _| v.flow.database_state.state_for(&db).focused_cell); + assert_eq!(focus(&f), Some(("r1".into(), "title".into()))); + let shift = Modifiers { + shift: true, + ..Default::default() + }; + // (key, modifiers, focused row, focused column) + for (key, modifiers, row, col) in [ + ("right", Modifiers::default(), "r1", "col-status"), + ("down", Modifiers::default(), "r2", "col-status"), + ("tab", Modifiers::default(), "r2", "col-start"), + ("tab", Modifiers::default(), "r2", "col-est"), + ("tab", Modifiers::default(), "r2", "col-prog"), + ("tab", Modifiers::default(), "r3", "title"), + ("tab", shift, "r2", "col-prog"), + ("left", Modifiers::default(), "r2", "col-est"), + ("up", Modifiers::default(), "r1", "col-est"), + ("up", Modifiers::default(), "r1", "col-est"), + ] { + f.key(key, modifiers); + assert_eq!( + focus(&f), + Some((row.into(), col.into())), + "{key} {modifiers:?}" + ); + } + f.key("enter", Modifiers::default()); + f.update(|v, _, _| { + let ed = v + .flow + .database_state + .state_for(&db) + .authoring + .active_cell + .expect("editor"); + assert_eq!((ed.row_id.as_str(), ed.col_type.as_str()), ("r1", "number")); + }); + f.key("escape", Modifiers::default()); + f.key("escape", Modifiers::default()); + assert_eq!(focus(&f), None, "`Escape` drops the focus"); + + // 4. A second press counts as a double click only on the cell of the first press. + f.switch_view("v-cal"); + let event = |row: &'static str| { + f.hit_rect(move |k| matches!(k, DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, .. } if row_id == row)) + }; + let (r1, r2) = (event("r1"), event("r2")); + let press = |rect: FlowRect, count: usize| { + let db = db.clone(); + f.update(move |v, w, cx| { + v.try_click_database_authoring( + &db, + rect.x + rect.w * 0.5, + rect.y + rect.h * 0.5, + count, + Some(w), + cx, + ); + v.database_drag = None; + v.close_database_record_sheet(cx); + }); + }; + let inline_row = |f: &Fixture| { + f.update(|v, _, _| { + v.flow + .database_state + .state_for(&db) + .authoring + .active_cell + .map(|ed| ed.row_id) + }) + }; + press(r1, 1); + press(r2, 2); + assert_eq!( + inline_row(&f), + None, + "a fast press on another event is no double click" + ); + press(r2, 2); + assert_eq!( + inline_row(&f).as_deref(), + Some("r2"), + "a double click on one event edits it" + ); +} diff --git a/blocksuite/crates/playground/src/database_authoring/tests_view_controls_board.rs b/blocksuite/crates/playground/src/database_authoring/tests_view_controls_board.rs new file mode 100644 index 0000000000..90dfb1be23 --- /dev/null +++ b/blocksuite/crates/playground/src/database_authoring/tests_view_controls_board.rs @@ -0,0 +1,487 @@ +//! End-to-end tests of Kanban order and `+ Add Group`, the toolbar `Search` +//! across Table, Kanban, and Calendar, and the Table footer `Calculate` statistics. + +use std::collections::BTreeSet; + +use blocksuite_editor::block_flow::FlowRect; + +use blocksuite_editor::database::{ + self, DatabaseAuthoringHitKind, DatabaseViewAction, compute_stat, +}; +use blocksuite_playground_doc::{ + read::{BlockContent, DatabaseData}, + schema::DatabaseCellSpec, + session::{DatabaseRowGroupUpdate, PageDocSession}, +}; +use ui::{CursorStyle, Modifiers}; + +use super::{ + tests_dnd_motion::{mouse_down, mouse_move, mouse_up}, + tests_view_controls::Fixture, +}; +use crate::PlaygroundTheme; + +fn lane_keys(f: &Fixture) -> Vec { + let db = f.db.clone(); + f.update(|v, _, _| { + v.flow + .database_authoring_hits(&db) + .iter() + .filter_map(|hit| match &hit.kind { + DatabaseAuthoringHitKind::KanbanLaneDropTarget { bucket_key, .. } => { + Some(bucket_key.clone()) + } + _ => None, + }) + .collect() + }) +} + +fn group_order(db: &DatabaseData) -> Vec { + let view = db + .views + .iter() + .find(|v| v.id == "v-kanban") + .expect("kanban view"); + view.group_properties + .iter() + .map(|gp| gp.key.clone()) + .collect() +} + +fn option_names(db: &DatabaseData) -> Vec { + let column = db.columns.iter().find(|c| c.id == "col-status").unwrap(); + column + .select_options() + .into_iter() + .map(|o| o.value) + .collect() +} + +/// Rows the active view shows, read from the title cells, cards, or calendar events it lays out. +fn shown_rows(f: &Fixture) -> BTreeSet { + let db = f.db.clone(); + f.update(|v, _, _| { + v.flow + .database_authoring_hits(&db) + .iter() + .filter_map(|h| match &h.kind { + DatabaseAuthoringHitKind::EditCell { + row_id, col_type, .. + } if col_type == "title" => Some(row_id.clone()), + DatabaseAuthoringHitKind::KanbanCardDragRegion { row_id, .. } + | DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, .. } => { + Some(row_id.clone()) + } + _ => None, + }) + .collect() + }) +} + +/// `compute_stat` without the `LRI … PDI` isolate around formatted numbers. +fn stat(calc: &str, db: &DatabaseData, col: &str) -> Option { + compute_stat(calc, db, col, &db.rows).map(|s| { + s.trim_matches(|c| c == '\u{2066}' || c == '\u{2069}') + .to_string() + }) +} + +fn rows(ids: &[&str]) -> BTreeSet { + ids.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn add_group_creates_a_lane_with_reopen_and_undo() { + let f = Fixture::open(PlaygroundTheme::Light); + f.switch_view("v-kanban"); + assert_eq!( + lane_keys(&f), + ["Ungroups", "opt-todo", "opt-doing", "opt-done"] + ); + + let db = f.db.clone(); + f.update(|v, _, cx| { + let max_x = v + .flow_layout() + .unwrap() + .block(&db) + .unwrap() + .body + .code_scroll + .unwrap() + .max_x; + v.scroll_database_x(&db, max_x, cx); + }); + f.view_action(DatabaseViewAction::OpenAddGroup); + f.type_text("QA Review"); + f.key("enter", Modifiers::default()); + assert_eq!( + option_names(&f.db()), + ["Todo", "Doing", "Done", "QA Review"] + ); + assert_eq!(lane_keys(&f).len(), 5); + assert_eq!( + option_names(&f.reopened_db()).last().map(String::as_str), + Some("QA Review") + ); + f.undo(); + assert_eq!(option_names(&f.db()), ["Todo", "Doing", "Done"]); + assert_eq!(lane_keys(&f).len(), 4); +} + +#[test] +fn kanban_header_drag_keeps_saved_order_and_merges_peer_card_sort() { + let f = Fixture::open_with_kanban_groups( + PlaygroundTheme::Light, + Some(serde_json::json!([ + { "key": "opt-todo" }, + { "key": "opt-doing", "hide": false, "manuallyCardSort": ["r4", "r5"] }, + { "key": "opt-done" }, + { "key": "Ungroups" } + ])), + ); + f.switch_view("v-kanban"); + let expected_lanes = ["opt-todo", "opt-doing", "opt-done", "Ungroups"]; + + let doing_cards = |data: &DatabaseData| { + data.views + .iter() + .find(|view| view.id == "v-kanban") + .unwrap() + .group_properties + .iter() + .find(|lane| lane.key == "opt-doing") + .unwrap() + .manually_card_sort + .clone() + }; + let db = &f.db; + let rendered_doing_cards = || { + f.update(|v, _, _| { + let mut cards: Vec<_> = v + .flow + .database_authoring_hits(db) + .iter() + .filter_map(|hit| match &hit.kind { + DatabaseAuthoringHitKind::KanbanCardDragRegion { + row_id, + origin_bucket_key, + .. + } if origin_bucket_key == "opt-doing" => Some((hit.rect.y, row_id.clone())), + _ => None, + }) + .collect(); + cards.sort_by(|a, b| a.0.total_cmp(&b.0)); + cards + .into_iter() + .map(|(_, row_id)| row_id) + .collect::>() + }) + }; + assert_eq!(lane_keys(&f), expected_lanes); + assert_eq!(group_order(&f.db()), expected_lanes); + assert_eq!(doing_cards(&f.db()), ["r4", "r5"]); + assert_eq!(rendered_doing_cards(), ["r4", "r5"]); + + let encode_local = || f.update(|v, _, _| v.page().unwrap().encode_update_v1().unwrap()); + let initial_update = encode_local(); + let mut peer = PageDocSession::new("board-peer", 72_311).unwrap(); + peer.apply_remote_update_v1(&initial_update).unwrap(); + + let header_point = |key: &str| { + let lane = f.hit_rect(|kind| { + matches!(kind, DatabaseAuthoringHitKind::KanbanLaneDropTarget { bucket_key, .. } if bucket_key == key) + }); + f.update(|v, w, _| { + let point = FlowRect::new(lane.x + 40.0, lane.y + 14.0, 1.0, 1.0); + let screen = v.database_local_rect_to_screen(db, point, true, w).unwrap(); + assert!(screen.x >= 0.0 && screen.x < f32::from(w.viewport_size().width)); + (screen.x, screen.y) + }) + }; + let (start_x, y) = header_point("opt-doing"); + let (end_x, _) = header_point("opt-todo"); + assert!(start_x - end_x > 100.0); + + let assert_no_preview = || { + f.update(|v, w, _| { + assert!(v.database_drag.is_none()); + for id in [ + "overlay.kanban_lane_drag_placeholder", + "overlay.kanban_lane_drop_indicator", + "overlay.kanban_lane_drag_ghost", + ] { + assert!(!w.frame_snapshot().elements.contains_key(id), "{id}"); + } + }); + }; + mouse_move(&f.hw, start_x, y, false); + f.tick(); + f.update(|v, _, _| { + assert_eq!(v.database_hover.block_id.as_deref(), Some(db.as_str())); + assert_eq!(v.database_hover.cursor, Some(CursorStyle::Arrow)); + }); + mouse_down(&f.hw, start_x, y); + f.tick(); + for step in 1..=6 { + let x = start_x + (end_x - start_x) * step as f32 / 6.0; + mouse_move(&f.hw, x, y, true); + f.tick(); + assert_no_preview(); + } + assert!( + encode_local() == initial_update, + "the pointer move wrote to the document" + ); + + let sorted = ["r5".to_string(), "r4".to_string()]; + peer.move_database_grouped_card( + db, + "v-kanban", + "r5", + &expected_lanes.map(String::from), + Some("opt-doing"), + "opt-doing", + &["r4".to_string(), "r5".to_string()], + &sorted, + DatabaseRowGroupUpdate::None, + 78_122, + ) + .unwrap() + .unwrap(); + + mouse_up(&f.hw, end_x, y); + f.tick(); + assert_no_preview(); + assert!( + encode_local() == initial_update, + "the pointer release wrote to the document" + ); + + let to_local = f.update(|v, _, _| { + peer.encode_diff_v1(&v.page().unwrap().encode_state_vector_v1().unwrap()) + .unwrap() + }); + let to_peer = f.update(|v, _, _| { + v.page() + .unwrap() + .encode_diff_v1(&peer.encode_state_vector_v1().unwrap()) + .unwrap() + }); + peer.apply_remote_update_v1(&to_peer).unwrap(); + f.update(|v, _, cx| { + v.page_mut() + .unwrap() + .apply_remote_update_v1(&to_local) + .unwrap(); + v.refresh_document(); + cx.notify(); + }); + + assert_eq!(lane_keys(&f), expected_lanes); + assert_eq!(rendered_doing_cards(), sorted); + let read_db = |page: &PageDocSession| { + let snapshot = page.read_page_snapshot().unwrap(); + let BlockContent::Database(data) = &snapshot.block(db).unwrap().content else { + panic!("expected a database"); + }; + data.clone() + }; + let mut reopened_peer = PageDocSession::new("board-reopen", 72_312).unwrap(); + reopened_peer + .apply_remote_update_v1(&peer.encode_update_v1().unwrap()) + .unwrap(); + for (name, data) in [ + ("local", f.db()), + ("peer", read_db(&peer)), + ("reopened local", f.reopened_db()), + ("reopened peer", read_db(&reopened_peer)), + ] { + assert_eq!(group_order(&data), expected_lanes, "{name}"); + assert_eq!(doing_cards(&data), sorted, "{name}"); + } +} + +#[test] +fn search_filters_table_kanban_and_calendar_rows_and_calculate_persists_and_recomputes() { + let f = Fixture::open(PlaygroundTheme::Light); + let all = rows(&["r1", "r2", "r3", "r4", "r5"]); + assert_eq!(shown_rows(&f), all); + let v1 = |f: &Fixture| f.update(|v, _, _| v.page().unwrap().encode_update_v1().unwrap()); + let before = v1(&f); + + // 1. Table: titles match case-insensitively, option labels match, `Escape` clears. + f.view_action(DatabaseViewAction::ToggleSearch); + f.type_text("CARD T"); + assert_eq!(shown_rows(&f), rows(&["r2", "r3"])); + f.key("escape", Modifiers::default()); + assert_eq!(shown_rows(&f), all); + f.view_action(DatabaseViewAction::ToggleSearch); + f.type_text("doing"); + assert_eq!(shown_rows(&f), rows(&["r4", "r5"])); + f.key("enter", Modifiers::default()); + assert_eq!( + shown_rows(&f), + rows(&["r4", "r5"]), + "`Enter` keeps the search" + ); + + // 2. Kanban and Calendar filter their cards and events the same way. + for (view, query, expected) in [ + ("v-kanban", "five", rows(&["r5"])), + ("v-cal", "one", rows(&["r1"])), + ] { + f.switch_view(view); + assert_eq!( + shown_rows(&f), + all, + "{view}: a view switch clears the search" + ); + f.view_action(DatabaseViewAction::ToggleSearch); + f.type_text(query); + assert_eq!(shown_rows(&f), expected, "{view}"); + f.view_action(DatabaseViewAction::ClearSearch); + assert_eq!(shown_rows(&f), all, "{view}"); + } + assert_eq!(v1(&f), before, "search writes nothing"); + + // 3. Footer statistics persist per column, recompute on edits, and undo in one step. + f.switch_view("v-table"); + let calc = |db: &DatabaseData, col: &str| { + let view = db.views.iter().find(|v| v.id == "v-table").unwrap(); + view.columns + .iter() + .find(|c| c.id == col) + .and_then(|c| c.stat_calc_type.clone()) + }; + // (column, statistic, shown value) + for (col, calc_id, shown) in [ + ("col-est", "sum", "17.5"), + ("col-est", "avg", "4.375"), + ("title", "count-values", "5"), + ("col-start", "percent-not-empty", "100%"), + ] { + f.view_action(DatabaseViewAction::OpenCalcMenu { + column_id: col.into(), + group_key: String::new(), + }); + f.view_action(DatabaseViewAction::SetCalc { + column_id: col.into(), + calc: calc_id.into(), + }); + let db = f.db(); + assert_eq!(calc(&db, col).as_deref(), Some(calc_id), "{col}"); + assert_eq!(stat(calc_id, &db, col).as_deref(), Some(shown), "{col}"); + } + let reopened = f.reopened_db(); + assert_eq!(calc(&reopened, "col-est").as_deref(), Some("avg")); + assert_eq!( + calc(&reopened, "col-start").as_deref(), + Some("percent-not-empty") + ); + let db_id = f.db.clone(); + f.update(|v, _, cx| { + let page = v.page_mut().unwrap(); + page.set_database_cell_value(&db_id, "r3", "col-est", DatabaseCellSpec::Number(10.0), 9) + .unwrap(); + page.stop_capturing().unwrap(); + v.refresh_document(); + cx.notify(); + }); + let db = f.db(); + assert_eq!(stat("avg", &db, "col-est").as_deref(), Some("5.5")); + f.undo(); + f.undo(); + assert_eq!(calc(&f.db(), "col-start"), None, "one undo per statistic"); + assert_eq!(calc(&f.db(), "title").as_deref(), Some("count-values")); + assert!( + database::STAT_CALC_TYPES + .iter() + .any(|(id, ..)| *id == "percent-not-empty") + ); +} + +#[test] +fn one_day_event_in_a_calendar_with_an_end_column_stretches_from_its_right_edge() { + use super::tests_dnd_motion::{build_db_doc, spawn_view}; + let (doc, db) = build_db_doc("calendar", false); + let (platform, app, win, hw) = spawn_view(1280, 800, crate::PlaygroundMode::Page, doc); + let tick = || { + platform.run_until_parked(); + hw.request_frame(); + platform.run_until_parked(); + }; + tick(); + let is_r2 = |k: &DatabaseAuthoringHitKind| matches!(k, DatabaseAuthoringHitKind::CalendarDragEventStart { row_id, .. } if row_id == "r2"); + let (center, width, day_w, start_ms) = app + .update(|cx| { + win.update(cx, |v, w, _| { + let rect = v + .flow + .database_authoring_hits(&db) + .iter() + .find(|h| is_r2(&h.kind)) + .unwrap() + .rect; + let center = v + .database_authoring_hit_screen_center(&db, w, is_r2) + .unwrap(); + let data = super::tests::read_db(v, &db); + let start = data.cells[&("r2".to_string(), "col-start".to_string())] + .as_i64() + .unwrap(); + assert!( + !data + .cells + .contains_key(&("r2".to_string(), "col-end".to_string())) + ); + let day_w = v + .flow + .database_authoring_hits(&db) + .iter() + .find_map(|h| match h.kind { + DatabaseAuthoringHitKind::CalendarDayDropTarget { .. } => Some(h.rect.w), + _ => None, + }) + .unwrap(); + (center, rect.w, day_w, start) + }) + }) + .unwrap(); + // The right edge of the one-day event is a resize handle. + let edge = (center.0 + width * 0.5 - 2.0, center.1); + mouse_move(&hw, edge.0, edge.1, false); + tick(); + let hover_edge = app + .update(|cx| { + win.update(cx, |v, _, _| match &v.database_hover.target { + Some(super::hover::DatabaseHoverTargetKind::CalendarEvent { + resize_edge, .. + }) => *resize_edge, + _ => None, + }) + }) + .unwrap(); + assert_eq!(hover_edge, Some(true)); + // Dragging it two day cells to the right writes an end date two days later. + mouse_down(&hw, edge.0, edge.1); + tick(); + for step in 1..=4 { + mouse_move(&hw, edge.0 + day_w * 2.0 * step as f32 / 4.0, edge.1, true); + tick(); + } + mouse_up(&hw, edge.0 + day_w * 2.0, edge.1); + tick(); + let end = app + .update(|cx| { + win.update(cx, |v, _, _| { + super::tests::read_db(v, &db) + .cells + .get(&("r2".to_string(), "col-end".to_string())) + .and_then(|c| c.as_i64()) + }) + }) + .unwrap(); + assert_eq!(end, Some(start_ms + 2 * 86_400_000)); +}