diff --git a/blocksuite/crates/doc/src/session/database/row_mutations.rs b/blocksuite/crates/doc/src/session/database/row_mutations.rs index 338da8cd2d..0b8a280e8d 100644 --- a/blocksuite/crates/doc/src/session/database/row_mutations.rs +++ b/blocksuite/crates/doc/src/session/database/row_mutations.rs @@ -1,6 +1,8 @@ //! Atomic single-transaction row insertion, deletion, and lossless duplication for //! `affine:database` (`sys:version = 3`). +use std::collections::HashSet; + use y_octo::{Any, SessionReadValue, SessionValue, TextDeltaOp, TypePath, TypeTarget}; use crate::{ @@ -208,20 +210,49 @@ impl PageDocSession { block_id: &str, row_id: &str, now_ms: u64, + ) -> DocResult { + self.delete_database_rows(block_id, &[row_id.to_owned()], now_ms) + } + + /// Delete the `affine:database` rows `row_ids` of `block_id` that exist (along with any + /// unshared subtree descendants) AND their `prop:cells` entries in one atomic tracked undo + /// transaction. It reads the block graph once and removes each run of adjacent rows with one + /// array edit, so the work grows with the page size plus the number of rows, not with their + /// product. Returns `None` when no row of `row_ids` exists. + pub fn delete_database_rows( + &mut self, + block_id: &str, + row_ids: &[String], + now_ms: u64, ) -> DocResult { ensure_database_block_exists(self, block_id)?; let (mut graph, dup_parents) = self.child_graph_with_dups()?; let parent_had_dups = dup_parents.contains(block_id); - let Some(index) = graph - .get(block_id) - .and_then(|v| v.iter().position(|id| id == row_id)) - else { + let wanted: HashSet<&str> = row_ids.iter().map(String::as_str).collect(); + let Some(children) = graph.get_mut(block_id) else { return Ok(None); }; - if let Some(children) = graph.get_mut(block_id) { - children.remove(index); + // Index ranges `(start, len)` of the deleted rows in the deduplicated children array. + let mut runs: Vec<(u64, u64)> = Vec::new(); + let mut rows: Vec = Vec::new(); + let mut kept = Vec::with_capacity(children.len()); + for (index, id) in std::mem::take(children).into_iter().enumerate() { + if !wanted.contains(id.as_str()) { + kept.push(id); + continue; + } + let index = index as u64; + match runs.last_mut() { + Some((start, len)) if *start + *len == index => *len += 1, + _ => runs.push((index, 1)), + } + rows.push(id); } - let candidates = descendants(&graph, [row_id.to_owned()]); + *children = kept; + if rows.is_empty() { + return Ok(None); + } + let candidates = descendants(&graph, rows.iter().cloned()); let external = graph .iter() .filter(|(id, _)| !candidates.contains(*id)) @@ -234,15 +265,16 @@ impl PageDocSession { let retained = descendants(&graph, external); let remove_ids: Vec = candidates.difference(&retained).cloned().collect(); let block_id = block_id.to_string(); - let row_id = row_id.to_string(); - let index = index as u64; self.structural_edit(now_ms, move |page| { if parent_had_dups { page.dedup_children_in_tx(&block_id)?; } - page.inner_mut() - .array_remove(&children_target(&block_id), index, 1)?; + // Remove the last run first, so the indices of the runs before it stay valid. + for &(start, len) in runs.iter().rev() { + page.inner_mut() + .array_remove(&children_target(&block_id), start, len)?; + } let blocks_target = TypeTarget::Path(TypePath::root("blocks")); for id in &remove_ids { page.inner_mut().map_remove(&blocks_target, id)?; @@ -252,16 +284,18 @@ impl PageDocSession { match page.inner().get_map_value(&db_target, "prop:cells")? { Some(SessionReadValue::Map(_)) => { let cells_target = TypeTarget::Path(db_path.key("prop:cells")); - if page - .inner() - .get_map_value(&cells_target, &row_id)? - .is_some() - { - page.inner_mut().map_remove(&cells_target, &row_id)?; + for row_id in &rows { + if page.inner().get_map_value(&cells_target, row_id)?.is_some() { + page.inner_mut().map_remove(&cells_target, row_id)?; + } } } Some(SessionReadValue::Any(Any::Object(mut cells_obj))) => { - if cells_obj.remove(&row_id).is_some() { + let before = cells_obj.len(); + for row_id in &rows { + cells_obj.remove(row_id); + } + if cells_obj.len() != before { let upgraded: Vec<(String, SessionValue)> = cells_obj .into_iter() .map(|(k, v)| (k, any_to_session_value(v))) @@ -609,4 +643,70 @@ mod tests { "1 undo after delete_database_row must restore prop:cells[r1]" ); } + + #[test] + fn delete_rows_removes_runs_subtrees_and_cells_in_one_undo_step() { + let mut page = seed_db(); + for (i, id) in ["r3", "r4", "r5"].into_iter().enumerate() { + page.add_block( + id, + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: id.into(), + }, + Some("db1"), + None, + 10 + i as u64, + ) + .unwrap(); + } + page.add_block( + "r2-child", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Nested".into(), + }, + Some("r2"), + None, + 20, + ) + .unwrap(); + let _ = page.stop_capturing(); + let all = ["r1", "r2", "r3", "r4", "r5"]; + assert_eq!(row_ids(&page), all); + let cells_target = TypeTarget::Path(TypePath::root("blocks").key("db1").key("prop:cells")); + let has_cells = |page: &PageDocSession, row: &str| { + page.inner() + .get_map_value(&cells_target, row) + .unwrap() + .is_some() + }; + + // Two runs (`r1, r2` and `r4`), out of order, with a missing id. + let ids = ["r4", "missing", "r2", "r1"].map(String::from); + assert!( + page.delete_database_rows("db1", &ids, 500) + .unwrap() + .is_some() + ); + assert_eq!(row_ids(&page), ["r3", "r5"]); + let snap = page.read_page_snapshot().unwrap(); + for gone in ["r1", "r2", "r2-child", "r4"] { + assert!(snap.block(gone).is_none(), "{gone} must be deleted"); + } + assert!(!has_cells(&page, "r1") && !has_cells(&page, "r2")); + + assert!(page.undo().unwrap().is_some()); + assert_eq!(row_ids(&page), all); + let snap = page.read_page_snapshot().unwrap(); + assert!(snap.block("r2-child").is_some()); + assert!(has_cells(&page, "r1") && has_cells(&page, "r2")); + + let none = ["missing".to_string()]; + assert!( + page.delete_database_rows("db1", &none, 600) + .unwrap() + .is_none() + ); + } } diff --git a/blocksuite/crates/editor/src/database/authoring_id.rs b/blocksuite/crates/editor/src/database/authoring_id.rs index 73d550f4aa..9d880f727b 100644 --- a/blocksuite/crates/editor/src/database/authoring_id.rs +++ b/blocksuite/crates/editor/src/database/authoring_id.rs @@ -1,42 +1,86 @@ +use std::collections::HashSet; + use blocksuite_playground_doc::{read::DatabaseData, session::PageDocSession}; /// Generate a collision-free identifier scoped to `page.client_id()` and verified against all /// existing column, option, view, and row identifiers in `data` (plus page blocks for `"row"`). +/// It borrows the identifiers and looks each candidate row up in the `blocks` map, so it copies +/// no identifier and decodes no page snapshot. pub(super) fn fresh_database_id( page: &PageDocSession, data: &DatabaseData, prefix: &str, ) -> String { - let mut used: std::collections::HashSet = std::collections::HashSet::new(); + let mut used: HashSet<&str> = HashSet::new(); for col in &data.columns { - used.insert(col.id.clone()); + used.insert(&col.id); if let Some(opts) = col.data.get("options").and_then(|v| v.as_array()) { - for opt in opts { - if let Some(id) = opt.get("id").and_then(|v| v.as_str()) { - used.insert(id.to_string()); - } - } + used.extend( + opts.iter() + .filter_map(|opt| opt.get("id").and_then(|v| v.as_str())), + ); } } - for view in &data.views { - used.insert(view.id.clone()); - } - for row in &data.rows { - used.insert(row.row_id.clone()); - } - let snap = if prefix == "row" { - page.read_page_snapshot().ok() - } else { - None + used.extend(data.views.iter().map(|view| view.id.as_str())); + used.extend(data.rows.iter().map(|row| row.row_id.as_str())); + let exists_in_page = |candidate: &str| { + prefix == "row" + && page + .inner() + .get_map_value(page.blocks_target(), candidate) + .is_ok_and(|value| value.is_some()) }; let client_id = page.client_id(); let mut seq = page.revision().saturating_add(1); loop { let candidate = format!("{prefix}-{client_id:x}-{seq:x}"); - let exists_in_page = snap.as_ref().is_some_and(|s| s.block(&candidate).is_some()); - if !used.contains(&candidate) && !exists_in_page { + if !used.contains(candidate.as_str()) && !exists_in_page(&candidate) { return candidate; } seq = seq.wrapping_add(1); } } + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::{ + read::BlockContent, + schema::{BlockSpec, ParagraphType}, + }; + + use super::fresh_database_id; + use crate::database::tests::tagged_database_page; + + #[test] + fn fresh_row_id_skips_rows_and_page_blocks() { + let paragraph = || BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: String::new(), + }; + for rows in [10, 100, 1_000] { + let mut page = tagged_database_page(rows); + // One paragraph moves the revision by `step`; the next one moves it by the same + // step, so it can take the first candidate of the revision it leaves behind. + let before = page.revision(); + page.add_block("spacer", paragraph(), Some("n"), None, 8) + .unwrap(); + let step = page.revision() - before; + let taken = format!( + "row-{:x}-{:x}", + page.client_id(), + page.revision() + step + 1 + ); + page.add_block(taken.clone(), paragraph(), Some("n"), None, 9) + .unwrap(); + let first = format!("row-{:x}-{:x}", page.client_id(), page.revision() + 1); + assert_eq!(first, taken, "{rows} rows"); + let snap = page.read_page_snapshot().unwrap(); + let Some(BlockContent::Database(data)) = snap.block("db").map(|b| &b.content) else { + panic!("database block"); + }; + let id = fresh_database_id(&page, data, "row"); + assert_ne!(id, taken, "{rows} rows"); + assert!(snap.block(&id).is_none(), "{rows} rows: {id}"); + } + } +} diff --git a/blocksuite/crates/editor/src/database/mod.rs b/blocksuite/crates/editor/src/database/mod.rs index a98c632cec..2c2bf39bb4 100644 --- a/blocksuite/crates/editor/src/database/mod.rs +++ b/blocksuite/crates/editor/src/database/mod.rs @@ -214,6 +214,11 @@ impl DatabaseFlowState { self.ui_states.get(block_id).cloned().unwrap_or_default() } + /// The view state of `block_id`, borrowed; `None` when the block has the default state. + pub fn ui_state(&self, block_id: &str) -> Option<&DatabaseUiState> { + self.ui_states.get(block_id) + } + /// Each block that has view state, with that state. pub fn states(&self) -> impl Iterator { self.ui_states.iter() @@ -588,6 +593,100 @@ pub fn resolve_grouped_view_buckets( mod tests { use super::*; + /// A page `p` > note `n` > database `db` with a `title` column, a multi-select `c-tags` + /// column (`opt-a`, `opt-b`, `opt-c`), a Table view `v-table`, a Kanban view `v-board` + /// grouped by `c-tags`, and `rows` rows `r0`, `r1`, ... that each carry all three tags. + pub(super) fn tagged_database_page( + rows: usize, + ) -> blocksuite_playground_doc::session::PageDocSession { + use blocksuite_playground_doc::{ + schema::{ + BlockSpec, DatabaseCellSpec, DatabaseColumnSpec, DatabaseSpec, DatabaseViewSpec, + ParagraphType, + }, + session::PageDocSession, + }; + use serde_json::json; + + let tags = + || DatabaseCellSpec::MultiSelect(vec!["opt-a".into(), "opt-b".into(), "opt-c".into()]); + let mut page = PageDocSession::new("page-tagged-db", 7).unwrap(); + page.add_block( + "p", + BlockSpec::Page { + title: "Tags".into(), + }, + None, + None, + 1, + ) + .unwrap(); + page.add_block("n", BlockSpec::Note { xywh: None }, Some("p"), None, 2) + .unwrap(); + let options: Vec<_> = ["opt-a", "opt-b", "opt-c"] + .iter() + .map(|id| json!({ "id": id, "value": id, "color": "var(--affine-tag-red)" })) + .collect(); + page.add_block( + "db", + BlockSpec::Database(DatabaseSpec { + title: "Tags".into(), + columns: vec![ + DatabaseColumnSpec { + id: "title".into(), + column_type: "title".into(), + name: "Title".into(), + data: json!({}), + }, + DatabaseColumnSpec { + id: "c-tags".into(), + column_type: "multi-select".into(), + name: "Tags".into(), + data: json!({ "options": options }), + }, + ], + views: vec![ + DatabaseViewSpec { + id: "v-table".into(), + name: "Table".into(), + mode: "table".into(), + raw: json!({}), + }, + DatabaseViewSpec { + id: "v-board".into(), + name: "Board".into(), + mode: "kanban".into(), + raw: json!({ + "groupBy": { "type": "groupBy", "columnId": "c-tags", "name": "multi-select" } + }), + }, + ], + cells: (0..rows) + .map(|i| (format!("r{i}"), std::collections::BTreeMap::from([("c-tags".into(), tags())]))) + .collect(), + }), + Some("n"), + None, + 3, + ) + .unwrap(); + for i in 0..rows { + page.add_block( + format!("r{i}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: format!("Row {i}"), + }, + Some("db"), + None, + 4, + ) + .unwrap(); + } + let _ = page.stop_capturing(); + page + } + #[test] fn inline_axis_ltr_rtl_mapping_is_bijective_and_preserves_geometry() { let cases = [ diff --git a/blocksuite/crates/editor/src/database/row_ops.rs b/blocksuite/crates/editor/src/database/row_ops.rs index 2a12eb4f3c..528ce4507d 100644 --- a/blocksuite/crates/editor/src/database/row_ops.rs +++ b/blocksuite/crates/editor/src/database/row_ops.rs @@ -479,31 +479,33 @@ pub(super) fn handle_lane_menu_action( .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, - row, - column_id, - DatabaseCellSpec::Null, - now_ms, - )?; + let commit = if *delete { + page.delete_database_rows(block_id, rows, now_ms)? + } else { + page.structural_edit(now_ms, |page| { + for row in rows { + 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, + row, + column_id, + DatabaseCellSpec::Null, + now_ms, + )?; + } } - } - Ok(()) - })?; + Ok(()) + })? + }; flow_state.authoring_mut(block_id).dismiss_popovers(); Ok(AuthoringActionResult { handled: true, @@ -958,4 +960,41 @@ mod tests { ); } } + + #[test] + fn multi_select_lane_ungroup_removes_only_the_lane_tag_in_one_undo_step() { + let mut page = crate::database::tests::tagged_database_page(3); + let mut flow_state = DatabaseFlowState::default(); + let tags = |page: &PageDocSession, row: &str| { + snap_db(page) + .cells + .get(&(row.to_string(), "c-tags".to_string())) + .map(DatabaseCellValue::as_string_list) + .unwrap_or_default() + }; + let all = ["opt-a", "opt-b", "opt-c"]; + let data = snap_db(&page); + let ungroup = DatabaseAuthoringHitKind::KanbanLaneCards { + column_id: "c-tags".into(), + bucket_key: "opt-b".into(), + rows: vec!["r0".into(), "r2".into()], + delete: false, + }; + let result = + handle_lane_menu_action(&mut page, &mut flow_state, "db", &data, &ungroup, 1_000) + .unwrap(); + assert!(result.doc_mutated); + let _ = page.stop_capturing(); + for (row, want) in [ + ("r0", vec!["opt-a", "opt-c"]), + ("r1", all.to_vec()), + ("r2", vec!["opt-a", "opt-c"]), + ] { + assert_eq!(tags(&page, row), want, "{row}"); + } + assert!(page.undo().unwrap().is_some()); + for row in ["r0", "r1", "r2"] { + assert_eq!(tags(&page, row), all, "{row} after one undo"); + } + } } diff --git a/blocksuite/crates/editor/src/database/table_selection.rs b/blocksuite/crates/editor/src/database/table_selection.rs index 329e322896..5b8a578725 100644 --- a/blocksuite/crates/editor/src/database/table_selection.rs +++ b/blocksuite/crates/editor/src/database/table_selection.rs @@ -257,14 +257,9 @@ pub fn delete_rows( 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()) + Ok(page + .delete_database_rows(block_id, &rows, now_ms)? + .is_some()) } /// Shown Table row slots and columns `(id, type)` in display order. diff --git a/blocksuite/crates/playground/src/database_authoring/dnd.rs b/blocksuite/crates/playground/src/database_authoring/dnd.rs index 59dfeb5c99..49e1f56917 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd.rs @@ -12,7 +12,7 @@ use ui::{Context, Window}; use crate::PlaygroundView; -use super::DatabaseDragState; +use super::{DatabaseDragState, snapshot_database}; /// Duration of the post-drop ease-out landing settle animation (ms). pub(crate) const DROP_SETTLE_DURATION_MS: f64 = 160.0; @@ -106,7 +106,7 @@ impl DatabaseDropSettle { impl PlaygroundView { pub(super) fn calendar_event_range(&self, block_id: &str, row_id: &str) -> Option<(i64, i64)> { - let db = self.database_snapshot_data(block_id)?; + let db = self.database_data(block_id)?; let state = self.flow.database_state.state_for(block_id); let view = state .active_view_id @@ -128,7 +128,8 @@ impl PlaygroundView { /// 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 { + let snap = self.snapshot.clone(); + let Some(db) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) else { return false; }; let state = self.flow.database_state.state_for(block_id); @@ -666,8 +667,11 @@ impl PlaygroundView { duration_ms: DROP_SETTLE_DURATION_MS, }); let offset_at = self.utc_offset_resolver(); + let snap = self.snapshot.clone(); if target_day != origin_day - && let Some(db_data) = self.database_snapshot_data(&block_id) + && let Some(db_data) = snap + .as_deref() + .and_then(|s| snapshot_database(s, &block_id)) { let ui_state = self.flow.database_state.state_for(&block_id); let view = ui_state diff --git a/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs b/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs index 9e5b6882e0..b8ba887efb 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd_grouped.rs @@ -11,6 +11,8 @@ use ui::{Context, CursorStyle}; use crate::PlaygroundView; +use super::snapshot_database; + /// Active pointer drag inside a writable desktop `affine:database` block. #[derive(Clone, Debug)] pub(crate) enum DatabaseDragState { @@ -122,7 +124,8 @@ impl PlaygroundView { target_before_row_id: Option<&str>, now_ms: u64, ) -> (Option>, bool) { - let Some(db_data) = self.database_snapshot_data(block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) else { return (None, false); }; let Some((view_id, group_by, visible_buckets, full_buckets)) = @@ -279,7 +282,11 @@ impl PlaygroundView { let Some(width_px) = preview else { return true; }; - let Some(db_data) = self.database_snapshot_data(&block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap + .as_deref() + .and_then(|s| snapshot_database(s, &block_id)) + else { return true; }; let before_sv = self.page().and_then(|p| p.encode_state_vector_v1().ok()); @@ -431,7 +438,11 @@ impl PlaygroundView { cx.notify(); return true; } - let Some(db_data) = self.database_snapshot_data(&block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap + .as_deref() + .and_then(|s| snapshot_database(s, &block_id)) + else { return false; }; let ui_state = self.flow.database_state.state_for(&block_id); diff --git a/blocksuite/crates/playground/src/database_authoring/dnd_table.rs b/blocksuite/crates/playground/src/database_authoring/dnd_table.rs index 3d8210027f..d737e65fb5 100644 --- a/blocksuite/crates/playground/src/database_authoring/dnd_table.rs +++ b/blocksuite/crates/playground/src/database_authoring/dnd_table.rs @@ -1,6 +1,8 @@ //! Table row drag-to-reorder, column header drag-to-reorder, and row/resize hover tracking //! for `affine:database` Table views. +use std::collections::HashMap; + use blocksuite_editor::{ block_flow::FlowRect, database::{self, DatabaseAuthoringHitKind, DatabaseHitKind}, @@ -10,33 +12,47 @@ use ui::{Context, Window}; use crate::PlaygroundView; -use super::DatabaseDragState; +use super::{DatabaseDragState, snapshot_database}; /// Collect ordered Table row bounding boxes `(row_id, rect)` from `EditCell` authoring hits. /// Keeps distinct rendered row bands separate (e.g. a `multi-select` row shown in two groups). +/// One pass over the hits: each row id links its bands, so a cell finds its band without a scan +/// of the rows collected so far. pub(crate) fn collect_table_row_rects( hits: &[database::DatabaseAuthoringHit], -) -> Vec<(String, FlowRect)> { +) -> Vec<(&str, FlowRect)> { if !hits .iter() .any(|h| matches!(h.kind, DatabaseAuthoringHitKind::OpenColumnMenu { .. })) { return Vec::new(); } - let mut rows: Vec<(String, FlowRect)> = Vec::new(); + let mut rows: Vec<(&str, FlowRect)> = Vec::new(); + // `earlier[i]` is the band of the same row id collected before band `i`. + let mut earlier: Vec> = Vec::new(); + let mut latest: HashMap<&str, usize> = HashMap::new(); for h in hits { - if let DatabaseAuthoringHitKind::EditCell { row_id, .. } = &h.kind { - if let Some((_, existing)) = rows - .iter_mut() - .find(|(id, r)| id == row_id && (r.y - h.rect.y).abs() < 2.0) - { + let DatabaseAuthoringHitKind::EditCell { row_id, .. } = &h.kind else { + continue; + }; + let mut band = latest.get(row_id.as_str()).copied(); + while let Some(i) = band + && (rows[i].1.y - h.rect.y).abs() >= 2.0 + { + band = earlier[i]; + } + match band { + Some(i) => { + let existing = &mut rows[i].1; let left = existing.x.min(h.rect.x); let top = existing.y.min(h.rect.y); let right = existing.right().max(h.rect.right()); let bottom = existing.bottom().max(h.rect.bottom()); *existing = FlowRect::new(left, top, right - left, bottom - top); - } else { - rows.push((row_id.clone(), h.rect)); + } + None => { + earlier.push(latest.insert(row_id.as_str(), rows.len())); + rows.push((row_id.as_str(), h.rect)); } } } @@ -56,15 +72,17 @@ fn table_group_headers(hits: &[database::DatabaseHitTarget]) -> Vec<(String, Flo groups } -fn bucket_for_table_y(groups: &[(String, FlowRect)], y: f32) -> Option { - if groups.is_empty() { - return None; - } +/// The key of the group header at or above block-local `y` (the first group above them all). +fn table_group_at_y(groups: &[(String, FlowRect)], y: f32) -> Option<&String> { groups .iter() .rfind(|(_, r)| y >= r.y) .or_else(|| groups.first()) - .map(|(k, _)| k.clone()) + .map(|(k, _)| k) +} + +fn bucket_for_table_y(groups: &[(String, FlowRect)], y: f32) -> Option { + table_group_at_y(groups, y).cloned() } impl PlaygroundView { @@ -112,10 +130,11 @@ impl PlaygroundView { }) else { return false; }; + let row_id = row_id.to_string(); let groups = table_group_headers(self.flow.database_hits(block_id)); let origin_bucket_key = bucket_for_table_y(&groups, row_rect.y + 1.0); let row_title = self - .database_snapshot_data(block_id) + .database_data(block_id) .and_then(|db| { db.rows.iter().find(|r| r.row_id == row_id).map(|r| { blocksuite_editor::database::resolve_rich_text_plain( @@ -261,10 +280,10 @@ impl PlaygroundView { let groups = table_group_headers(self.flow.database_hits(&block_id)); let next_bucket = bucket_for_table_y(&groups, local_y); let same_group = next_bucket == origin_bucket_key; - let rows: Vec<(String, FlowRect)> = match &next_bucket { + let rows: Vec<(&str, FlowRect)> = match &next_bucket { Some(bk) => all_rows .into_iter() - .filter(|(_, r)| bucket_for_table_y(&groups, r.y + 1.0).as_ref() == Some(bk)) + .filter(|(_, r)| table_group_at_y(&groups, r.y + 1.0) == Some(bk)) .collect(), None => all_rows, }; @@ -273,19 +292,19 @@ impl PlaygroundView { .position(|(_, r)| (r.y + r.bottom()) * 0.5 > local_y); let (target_before_row_id, drop_line_local) = match insert_pos { Some(idx) => { - let (ref rid, rect) = rows[idx]; + let (rid, rect) = rows[idx]; let prev_is_self = idx > 0 && rows[idx - 1].0 == row_id; - if rid == &row_id || prev_is_self { + if rid == row_id || prev_is_self { ( Some(row_id.clone()), (!same_group).then_some((rect.x, rect.y - 1.0, rect.w)), ) } else { - (Some(rid.clone()), Some((rect.x, rect.y - 1.0, rect.w))) + (Some(rid.to_string()), Some((rect.x, rect.y - 1.0, rect.w))) } } None => { - let last_is_self = rows.last().is_some_and(|(id, _)| id == &row_id); + let last_is_self = rows.last().is_some_and(|(id, _)| *id == row_id); if last_is_self { ( Some(row_id.clone()), @@ -549,7 +568,11 @@ impl PlaygroundView { if target_col_index == origin_col_index { return false; } - let Some(db_data) = self.database_snapshot_data(&block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap + .as_deref() + .and_then(|s| snapshot_database(s, &block_id)) + else { return true; }; let ui_state = self.flow.database_state.state_for(&block_id); @@ -603,3 +626,75 @@ impl PlaygroundView { true } } + +#[cfg(test)] +mod tests { + use blocksuite_editor::{ + block_flow::FlowRect, + database::{DatabaseAuthoringHit, DatabaseAuthoringHitKind}, + }; + + use super::collect_table_row_rects; + + fn hit(rect: FlowRect, kind: DatabaseAuthoringHitKind) -> DatabaseAuthoringHit { + DatabaseAuthoringHit { + rect, + kind, + scrolls_x: true, + } + } + + /// Hits of an 8-column Table whose rows show in `groups` groups: every row shows in each + /// group, as a `multi-select` row tagged with every group does. + fn table_hits(rows: usize, groups: usize) -> Vec { + let mut hits: Vec<_> = (0..8) + .map(|c| { + hit( + FlowRect::new(24.0 + c as f32 * 120.0, 40.0, 120.0, 34.0), + DatabaseAuthoringHitKind::OpenColumnMenu { + column_id: format!("c{c}"), + }, + ) + }) + .collect(); + for g in 0..groups { + for r in 0..rows { + let y = 74.0 + ((g * (rows + 1)) + r) as f32 * 34.0; + for c in 0..8 { + hits.push(hit( + FlowRect::new(24.0 + c as f32 * 120.0, y, 120.0, 34.0), + DatabaseAuthoringHitKind::EditCell { + row_id: format!("r{r}"), + column_id: format!("c{c}"), + col_type: "rich-text".into(), + }, + )); + } + } + } + hits + } + + #[test] + fn row_rects_merge_cells_per_band_in_one_pass() { + for (rows, groups) in [(10, 1), (100, 1), (1_000, 1), (10, 3), (100, 2)] { + let hits = table_hits(rows, groups); + let bands = collect_table_row_rects(&hits); + assert_eq!(bands.len(), rows * groups, "{rows} rows x {groups} groups"); + for (i, (id, rect)) in bands.iter().enumerate() { + let (g, r) = (i / rows, i % rows); + let y = 74.0 + ((g * (rows + 1)) + r) as f32 * 34.0; + assert_eq!( + *id, + format!("r{r}"), + "{rows} rows x {groups} groups: band {i}" + ); + assert_eq!(*rect, FlowRect::new(24.0, y, 960.0, 34.0), "band {i}"); + } + } + // Without column headers the hits are no Table grid. + let mut hits = table_hits(3, 1); + hits.drain(..8); + assert!(collect_table_row_rects(&hits).is_empty()); + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/geometry.rs b/blocksuite/crates/playground/src/database_authoring/geometry.rs index 4098c5f1de..07e4a12885 100644 --- a/blocksuite/crates/playground/src/database_authoring/geometry.rs +++ b/blocksuite/crates/playground/src/database_authoring/geometry.rs @@ -21,6 +21,7 @@ use crate::PlaygroundView; use super::{ inline::DatabaseInlineTarget, paint::{INLINE_CARET_WIDTH_PX, InlineBoxLayout}, + snapshot_database, }; /// Height at or below which an in-place cell input is a compact single-line pill (a Calendar @@ -492,7 +493,8 @@ impl PlaygroundView { window: Option<&mut Window>, cx: &mut Context, ) { - let Some(db_data) = self.database_snapshot_data(block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) else { return; }; let ui_state = self.flow.database_state.state_for(block_id); diff --git a/blocksuite/crates/playground/src/database_authoring/hover.rs b/blocksuite/crates/playground/src/database_authoring/hover.rs index c87d82b0a1..1030b6f85c 100644 --- a/blocksuite/crates/playground/src/database_authoring/hover.rs +++ b/blocksuite/crates/playground/src/database_authoring/hover.rs @@ -330,11 +330,11 @@ impl PlaygroundView { let sx = lx + scroll_x; let in_scroll_area = code_scroll.is_none_or(|cs| cs.area.contains(lx, ly)); - let ui_state = self.flow.database_state.state_for(&block_id); - let editing_row_id = ui_state - .authoring - .active_cell - .as_ref() + let editing_row_id = self + .flow + .database_state + .ui_state(&block_id) + .and_then(|st| st.authoring.active_cell.as_ref()) .map(|e| e.row_id.as_str()); let is_editing = editing_row_id.is_some() || self.database_input.is_some(); let auth_hits = self.flow.database_authoring_hits(&block_id); @@ -458,6 +458,7 @@ impl PlaygroundView { ly >= r.y && ly <= r.bottom() && lx >= r.x - GRIP_GUTTER_W && sx <= r.right() }) { + let row_id = row_id.to_string(); let title_rect = auth_hits.iter().find_map(|h| match &h.kind { DatabaseAuthoringHitKind::EditCell { row_id: rid, diff --git a/blocksuite/crates/playground/src/database_authoring/inline.rs b/blocksuite/crates/playground/src/database_authoring/inline.rs index f568b6a842..1f6f715230 100644 --- a/blocksuite/crates/playground/src/database_authoring/inline.rs +++ b/blocksuite/crates/playground/src/database_authoring/inline.rs @@ -363,7 +363,7 @@ impl PlaygroundView { && sheet.title_editing { let title = self - .database_snapshot_data(&sheet.block_id) + .database_data(&sheet.block_id) .and_then(|db| { let row = db.rows.iter().find(|r| r.row_id == sheet.row_id)?; Some(row.title.plain.clone()) diff --git a/blocksuite/crates/playground/src/database_authoring/keys.rs b/blocksuite/crates/playground/src/database_authoring/keys.rs index 42c124c9a3..5684b73536 100644 --- a/blocksuite/crates/playground/src/database_authoring/keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/keys.rs @@ -7,7 +7,7 @@ use ui::{Context, KeyDownEvent, Window}; use crate::PlaygroundView; -use super::inline::DatabaseInlineTarget; +use super::{inline::DatabaseInlineTarget, snapshot_database}; impl PlaygroundView { /// Route control/navigation keys to an active database authoring input. Printable text and @@ -132,7 +132,8 @@ impl PlaygroundView { key: DatabaseAuthoringKey, cx: &mut Context, ) -> bool { - let Some(db_data) = self.database_snapshot_data(block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) else { return false; }; let now_ms = self.now_ms(cx) as u64; @@ -209,7 +210,8 @@ impl PlaygroundView { window: &mut Window, cx: &mut Context, ) -> bool { - let Some(db_data) = self.database_snapshot_data(block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) else { return false; }; let now_ms = self.now_ms(cx) as u64; @@ -255,7 +257,8 @@ impl PlaygroundView { /// 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 snap = self.snapshot.clone(); + if let Some(db) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) { let offset_at = self.utc_offset_resolver(); self.flow.database_state.prune_row_selection( block_id, @@ -330,7 +333,7 @@ impl PlaygroundView { if session.target.tracks_text() { let latest = if let Some((block_id, row_id, column_id, is_title)) = session.target.live_text() { - self.database_snapshot_data(block_id) + self.database_data(block_id) .and_then(|db| { let row = db.rows.iter().find(|r| r.row_id == row_id)?; if is_title { diff --git a/blocksuite/crates/playground/src/database_authoring/mod.rs b/blocksuite/crates/playground/src/database_authoring/mod.rs index 2946e5ca59..89186ac7e1 100644 --- a/blocksuite/crates/playground/src/database_authoring/mod.rs +++ b/blocksuite/crates/playground/src/database_authoring/mod.rs @@ -64,11 +64,23 @@ use blocksuite_editor::{ block_flow::FlowRect, database::{self, ColumnResizePreview, DatabaseAuthoringHitKind, ProgressScrubPreview}, }; -use blocksuite_playground_doc::read::{BlockContent, DatabaseData}; +use blocksuite_playground_doc::read::{BlockContent, DatabaseData, PageSnapshot}; use ui::{Context, Window}; use crate::PlaygroundView; +/// The data of database `block_id` in `snap`. A caller that changes the view while it reads +/// the data borrows it from its own handle of the snapshot (`self.snapshot.clone()`). +pub(super) fn snapshot_database<'a>( + snap: &'a PageSnapshot, + block_id: &str, +) -> Option<&'a DatabaseData> { + match &snap.block(block_id)?.content { + BlockContent::Database(db) => Some(db), + _ => None, + } +} + #[derive(Clone, Debug, PartialEq, Eq)] pub enum RecordParagraph { Draft(String), @@ -185,12 +197,15 @@ impl PlaygroundView { } } + /// The data of database `block_id` in the shown page snapshot, borrowed without a copy. + pub(super) fn database_data(&self, block_id: &str) -> Option<&DatabaseData> { + snapshot_database(self.snapshot.as_deref()?, block_id) + } + + /// An owned copy of [`Self::database_data`], for callers that change the view while they + /// read the data. pub(super) fn database_snapshot_data(&self, block_id: &str) -> Option { - let snap = self.snapshot.as_ref()?; - match &snap.block(block_id)?.content { - BlockContent::Database(db) => Some(db.clone()), - _ => None, - } + self.database_data(block_id).cloned() } fn database_block_local_coords( @@ -432,7 +447,7 @@ impl PlaygroundView { }) .unwrap_or(*day_index); let event_title = - self.database_snapshot_data(block_id) + self.database_data(block_id) .and_then(|db| { db.rows.iter().find(|r| r.row_id == *row_id).map(|r| { database::resolve_rich_text_plain(&r.title, &self.page_titles) @@ -561,7 +576,8 @@ impl PlaygroundView { window: Option<&mut Window>, cx: &mut Context, ) -> bool { - let Some(db_data) = self.database_snapshot_data(block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) else { return false; }; let keep_capturing = matches!( diff --git a/blocksuite/crates/playground/src/database_authoring/paint.rs b/blocksuite/crates/playground/src/database_authoring/paint.rs index 1d40d67e55..db6f3cef05 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint.rs @@ -16,7 +16,10 @@ use ui::{ use crate::PlaygroundView; -use super::geometry::{POPOVER_FIELD_FONT, inline_cell_font}; +use super::{ + geometry::{POPOVER_FIELD_FONT, inline_cell_font}, + snapshot_database, +}; pub(super) const INLINE_CARET_WIDTH_PX: f32 = 1.5; @@ -725,7 +728,11 @@ impl PlaygroundView { return true; } - let Some(db_data) = self.database_snapshot_data(&block_id) else { + let snap = self.snapshot.clone(); + let Some(db_data) = snap + .as_deref() + .and_then(|s| snapshot_database(s, &block_id)) + else { return true; }; let keep_capturing = matches!( diff --git a/blocksuite/crates/playground/src/database_authoring/paint_hover.rs b/blocksuite/crates/playground/src/database_authoring/paint_hover.rs index 4bdccc626a..ed36d82814 100644 --- a/blocksuite/crates/playground/src/database_authoring/paint_hover.rs +++ b/blocksuite/crates/playground/src/database_authoring/paint_hover.rs @@ -11,7 +11,7 @@ use blocksuite_editor::{ }, theme::{IconPaint, Palette, TYPOGRAPHY, icons}, }; -use ui::{AnyElement, FontWeight, Hsla, Window, canvas, div, prelude::*, px}; +use ui::{AnyElement, Div, FontWeight, Hsla, Window, canvas, div, prelude::*, px}; use crate::PlaygroundView; @@ -24,25 +24,17 @@ use super::{ }, }; -/// Shared hover fill quad (mirrors JS `.dv-hover` / `hover`). -pub(super) fn paint_hover_fill( - rect: FlowRect, - radius: f32, - color: Hsla, - snapshot_id: Option<&'static str>, -) -> AnyElement { - let mut el = div() +/// Shared hover fill quad (mirrors JS `.dv-hover` / `hover`). A caller that names it in the +/// frame snapshot adds `.snapshot(..)` before `.into_any_element()`. +pub(super) fn paint_hover_fill(rect: FlowRect, radius: f32, color: Hsla) -> Div { + div() .absolute() .left(px(rect.x)) .top(px(rect.y)) .w(px(rect.w)) .h(px(rect.h)) .rounded(px(radius)) - .bg(color); - if let Some(id) = snapshot_id { - el = el.snapshot(id, None); - } - el.into_any_element() + .bg(color) } /// Shared floating 24×24 icon op button (mirrors JS `.row-op` / `.card-op` / `.group-header-op`). @@ -163,8 +155,13 @@ impl PlaygroundView { if let Some(id) = hovered_block.filter(|id| !blocks.iter().any(|b| b == id)) { blocks.push(id.to_string()); } + let no_rows = std::collections::BTreeSet::new(); for block_id in blocks { - let selected = self.flow.database_state.state_for(&block_id).selected_rows; + let selected = self + .flow + .database_state + .ui_state(&block_id) + .map_or(&no_rows, |st| &st.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 { @@ -231,12 +228,10 @@ impl PlaygroundView { let editing_row = self .flow .database_state - .state_for(block_id) - .authoring - .active_cell - .as_ref() - .map(|e| e.row_id.clone()); - let row_editing = |row_id: &str| editing_row.as_deref() == Some(row_id); + .ui_state(block_id) + .and_then(|st| st.authoring.active_cell.as_ref()) + .map(|e| e.row_id.as_str()); + let row_editing = |row_id: &str| editing_row == Some(row_id); match target { DatabaseHoverTargetKind::PopoverItem { .. } @@ -251,7 +246,7 @@ impl PlaygroundView { && 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)); + out.push(paint_hover_fill(sr, *radius, palette.hover).into_any_element()); } } DatabaseHoverTargetKind::TableHeader { rect, .. } => { @@ -261,12 +256,11 @@ impl PlaygroundView { self.table_rect_scrolls(block_id, *rect), window, ) { - out.push(paint_hover_fill( - sr, - 0.0, - palette.hover, - Some("overlay.table_header_hover"), - )); + out.push( + paint_hover_fill(sr, 0.0, palette.hover) + .snapshot("overlay.table_header_hover", None) + .into_any_element(), + ); // Right-edge `.control-r` 4 px × 32 % resize grip bar. let grip_h = (sr.h * 0.45).clamp(10.0, 16.0); let grip = FlowRect::new( @@ -275,12 +269,10 @@ impl PlaygroundView { 3.0, grip_h, ); - out.push(paint_hover_fill( - grip, - 1.5, - palette.placeholder.opacity(0.75), - None, - )); + out.push( + paint_hover_fill(grip, 1.5, palette.placeholder.opacity(0.75)) + .into_any_element(), + ); } } DatabaseHoverTargetKind::TableResizeHandle { column_id, .. } => { @@ -429,12 +421,11 @@ impl PlaygroundView { if let Some(sr) = self.database_clipped_local_rect_to_screen(block_id, *card_rect, true, window) { - out.push(paint_hover_fill( - sr, - 8.0, - palette.hover.opacity(0.55), - Some("overlay.kanban_card_hover"), - )); + out.push( + paint_hover_fill(sr, 8.0, palette.hover.opacity(0.55)) + .snapshot("overlay.kanban_card_hover", None) + .into_any_element(), + ); } let (peek_local, menu_local) = kanban_card_ops_rects(*card_rect); if row_editing(row_id) { @@ -474,12 +465,11 @@ impl PlaygroundView { self.database_local_rect_to_screen(block_id, *day_rect, false, window) { let tint_alpha = if *is_today { 0.09 } else { 0.02 }; - out.push(paint_hover_fill( - sr, - 0.0, - palette.brand.opacity(tint_alpha), - Some("overlay.calendar_day_hover"), - )); + out.push( + paint_hover_fill(sr, 0.0, palette.brand.opacity(tint_alpha)) + .snapshot("overlay.calendar_day_hover", None) + .into_any_element(), + ); } if !readonly && let Some(sr) = self.database_local_rect_to_screen( @@ -490,7 +480,7 @@ impl PlaygroundView { ) { let (bg, ink) = if *is_today { - (palette.brand, ui::white()) + (palette.brand, palette.on_accent) } else if *new_row_hovered { (palette.hover, palette.text_primary) } else { @@ -528,12 +518,11 @@ impl PlaygroundView { if let Some(sr) = self.database_local_rect_to_screen(block_id, *event_rect, false, window) { - out.push(paint_hover_fill( - sr, - 4.0, - palette.brand.opacity(0.18), - Some("overlay.calendar_event_hover"), - )); + out.push( + paint_hover_fill(sr, 4.0, palette.brand.opacity(0.18)) + .snapshot("overlay.calendar_event_hover", None) + .into_any_element(), + ); if !readonly && sr.w >= 20.0 { let start_c = if *resize_edge == Some(false) { palette.brand @@ -545,28 +534,34 @@ impl PlaygroundView { } else { palette.brand.opacity(0.55) }; - for (enabled, left, color, id) in [ + for (enabled, left, color, edge) in [ ( *start_handle, !window.layout_direction().is_rtl(), start_c, - "overlay.calendar_event_resize_start", + "start", ), ( *end_handle, window.layout_direction().is_rtl(), end_c, - "overlay.calendar_event_resize_end", + "end", ), ] { if enabled { let x = if left { sr.x + 1.0 } else { sr.right() - 4.0 }; - out.push(paint_hover_fill( - FlowRect::new(x, sr.y + 3.0, 3.0, (sr.h - 6.0).max(4.0)), - 1.5, - color, - Some(id), - )); + out.push( + paint_hover_fill( + FlowRect::new(x, sr.y + 3.0, 3.0, (sr.h - 6.0).max(4.0)), + 1.5, + color, + ) + .snapshot( + format_args!("overlay.calendar_event_resize_{edge}"), + None, + ) + .into_any_element(), + ); } } } diff --git a/blocksuite/crates/playground/src/database_authoring/pointer.rs b/blocksuite/crates/playground/src/database_authoring/pointer.rs index f235fd5df7..49711f3eb6 100644 --- a/blocksuite/crates/playground/src/database_authoring/pointer.rs +++ b/blocksuite/crates/playground/src/database_authoring/pointer.rs @@ -6,7 +6,7 @@ use blocksuite_editor::database::{ }; use ui::{Context, MouseButton, MouseMoveEvent, Window}; -use super::DatabaseDragState; +use super::{DatabaseDragState, snapshot_database}; use crate::PlaygroundView; impl PlaygroundView { @@ -26,7 +26,11 @@ impl PlaygroundView { if panel == database::ActiveToolbarPanel::Filter { return false; } - let Some(db) = self.database_snapshot_data(&block_id) else { + let snap = self.snapshot.clone(); + let Some(db) = snap + .as_deref() + .and_then(|s| snapshot_database(s, &block_id)) + else { return false; }; let max = (36.0 + 28.0 * database::panel_row_count(db.columns.len(), panel) as f32 diff --git a/blocksuite/crates/playground/src/database_authoring/record_title.rs b/blocksuite/crates/playground/src/database_authoring/record_title.rs index 4c6275aa5b..ec53d06b3c 100644 --- a/blocksuite/crates/playground/src/database_authoring/record_title.rs +++ b/blocksuite/crates/playground/src/database_authoring/record_title.rs @@ -11,7 +11,7 @@ use ui::{AnyElement, Context, Pixels, Point, Window}; use crate::{PlaygroundView, overlays::InlineTargetEnd}; -use super::{inline::DatabaseInlineTarget, paint::paint_inline_box_elements}; +use super::{inline::DatabaseInlineTarget, paint::paint_inline_box_elements, snapshot_database}; /// Font `(size_px, weight)` of the record peek title. const RECORD_TITLE_FONT: (f32, f32) = (16.0, 600.0); @@ -59,7 +59,7 @@ impl PlaygroundView { if !self.record_title_editing() { self.finish_record_edit(Some(window), cx); let row_exists = self - .database_snapshot_data(&block_id) + .database_data(&block_id) .is_some_and(|db| db.rows.iter().any(|r| r.row_id == row_id)); if !row_exists { return; @@ -226,17 +226,21 @@ impl PlaygroundView { /// True when `block_id` currently has any floating database popover open. pub(crate) fn database_block_has_popover(&self, block_id: &str) -> bool { - let st = self.flow.database_state.state_for(block_id); - let a = &st.authoring; - 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.toolbar_panel.is_some() - || a.active_cell - .as_ref() - .is_some_and(|e| matches!(e.col_type.as_str(), "select" | "multi-select" | "date")) + self.flow + .database_state + .ui_state(block_id) + .is_some_and(|st| { + let a = &st.authoring; + 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.toolbar_panel.is_some() + || a.active_cell.as_ref().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 @@ -250,7 +254,8 @@ impl PlaygroundView { mut window: Option<&mut Window>, cx: &mut Context, ) -> bool { - let Some(db) = self.database_snapshot_data(block_id) else { + let snap = self.snapshot.clone(); + let Some(db) = snap.as_deref().and_then(|s| snapshot_database(s, block_id)) else { return false; }; let Some(row) = db.rows.iter().find(|r| r.row_id == row_id) else { 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 2b9859e966..00049ad5e2 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_dnd_grouped.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_dnd_grouped.rs @@ -270,7 +270,7 @@ fn grouped_table_row_drag_left_gutter_title_click_column_menu_zero_flash_and_cal let v = win.read(cx).unwrap(); super::dnd_table::collect_table_row_rects(v.flow.database_authoring_hits(&db_id)) .into_iter() - .map(|(id, _)| id) + .map(|(id, _)| id.to_string()) .collect() }) }; 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 d52d85ce3e..bf3b656ea1 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 @@ -222,7 +222,7 @@ fn kanban_and_grouped_table_drag_into_non_first_lane_preserves_lane_order() { let v = twin.read(cx).unwrap(); super::dnd_table::collect_table_row_rects(v.flow.database_authoring_hits(&tdb_id)) .into_iter() - .map(|(id, _)| id) + .map(|(id, _)| id.to_string()) .collect() }) }; 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 cb69cdf071..d89bd6e3a3 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 @@ -632,7 +632,7 @@ fn table_row_grip_under_horizontal_scroll_stays_in_fixed_gutter_keeps_scroll_and assert!(cs.max_x > 40.0); let rows = super::dnd_table::collect_table_row_rects(v.flow.database_authoring_hits(&db_id)); - let row = |id: &str| rows.iter().find(|(r, _)| r == id).expect("row").1; + let row = |id: &str| rows.iter().find(|(r, _)| *r == id).expect("row").1; ( geom.column_x + block.x, crate::TOPBAR_HEIGHT + block.y - v.scroll_y, 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 index 966fd6efb3..c3d1a83e26 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_sideways_scroll_controls.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_sideways_scroll_controls.rs @@ -163,7 +163,7 @@ fn row_grip_hover_and_press_share_the_left_edge_of_the_block() { 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") + .find(|(id, _)| *id == "r2") .unwrap() .1; ( diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/editing.rs b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/editing.rs index 4965cd4939..b65bff5445 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/editing.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/editing.rs @@ -19,7 +19,7 @@ impl PlaygroundView { let mut y = body_top - p.scroll_y + p.title_card_h + 10.0; for (hidden, rows) in [(false, &p.visible_rows), (true, &p.hidden_rows)] { if hidden { - if rows.is_empty() { + if p.hidden_count == 0 { continue; } y += 46.0; diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs index c800f7842f..2da83b017d 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/mod.rs @@ -278,7 +278,9 @@ struct PreparedRecordSheet { value_w: f32, notes: Vec<(String, String, f32)>, visible_rows: Vec, + /// Rows of the hidden fields, laid out only while the hidden section is expanded. hidden_rows: Vec, + hidden_count: usize, hidden_expanded: bool, scroll_y: f32, } @@ -396,10 +398,17 @@ impl PlaygroundView { .iter() .map(|c| format_field_entry(c, row, db, self.theme, &offset_at, &self.page_titles)) .collect(); - let hidden_fields: Vec = hidden_cols - .iter() - .map(|c| format_field_entry(c, row, db, self.theme, &offset_at, &self.page_titles)) - .collect(); + // A collapsed hidden section shows only its toggle: its rows are neither formatted nor + // laid out. + let hidden_count = hidden_cols.len(); + let hidden_fields: Vec = if sheet.hidden_expanded { + hidden_cols + .iter() + .map(|c| format_field_entry(c, row, db, self.theme, &offset_at, &self.page_titles)) + .collect() + } else { + Vec::new() + }; let (win_w, win_h) = self.window_size; let is_phone = self.form_factor == crate::FormFactor::Phone || win_w < 600.0; @@ -587,12 +596,12 @@ impl PlaygroundView { let visible_rows: Vec = visible_fields.iter().map(&prepare_row).collect(); let hidden_rows: Vec = hidden_fields.iter().map(&prepare_row).collect(); let visible_h: f32 = visible_rows.iter().map(|r| r.row_h).sum(); - let hidden_toggle_h = if !hidden_rows.is_empty() { + let hidden_toggle_h = if hidden_count > 0 { 10.0 + if is_phone { 44.0 } else { 36.0 } } else { 0.0 }; - let hidden_rows_h: f32 = if !hidden_rows.is_empty() && sheet.hidden_expanded { + let hidden_rows_h: f32 = if hidden_count > 0 && sheet.hidden_expanded { 10.0 + hidden_rows.iter().map(|r| r.row_h).sum::() } else { 0.0 @@ -681,6 +690,7 @@ impl PlaygroundView { notes, visible_rows, hidden_rows, + hidden_count, hidden_expanded: sheet.hidden_expanded, scroll_y: blocksuite_editor::scroll::snap_device_pixel( sheet.scroll_y.clamp(0.0, max_scroll), diff --git a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs index 7482d86a24..86547fe378 100644 --- a/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs +++ b/blocksuite/crates/playground/src/overlays/view_mobile/record_sheet/render.rs @@ -245,8 +245,7 @@ impl PlaygroundView { .cursor_pointer() .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.last_opened_link_url = Some(open_url.clone()); - cx.open_url(&open_url); + this.open_editor_url(open_url.clone(), cx); cx.notify(); })); let mut el = div() @@ -364,11 +363,11 @@ impl PlaygroundView { } body_content = body_content.child(fields_box); - if !p.hidden_rows.is_empty() { + if p.hidden_count > 0 { cursor_y += 10.0; let toggle_h = if p.is_phone { 44.0 } else { 36.0 }; let toggle_vis = in_body_viewport(cursor_y, toggle_h); - let toggle_label = format!("Hidden fields ({})", p.hidden_rows.len()); + let toggle_label = format!("Hidden fields ({})", p.hidden_count); let chevron_icon = crate::theme::IconPaint::named(if p.hidden_expanded { "ToggleDownIcon" } else { @@ -495,7 +494,7 @@ impl PlaygroundView { ); } body_content = body_content.child(note.snapshot( - SharedString::from(format!("overlay.database_record_sheet.note.{index}")), + format_args!("overlay.database_record_sheet.note.{index}"), Some("overlay.database_record_sheet"), )); }