diff --git a/blocksuite/crates/doc/src/read/database.rs b/blocksuite/crates/doc/src/read/database.rs index b52eec0755..b80c948979 100644 --- a/blocksuite/crates/doc/src/read/database.rs +++ b/blocksuite/crates/doc/src/read/database.rs @@ -1,9 +1,9 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde_json::Value as JsonValue; use y_octo::{Any, SessionReadValue, TypeTarget}; -use crate::DocResult; +use crate::{DocResult, session::PageDocSession}; use super::{BlockContent, BlockNode, RawBlock, RichText, SnapshotReader, any_as_f64}; @@ -430,7 +430,10 @@ impl SnapshotReader<'_> { } } - fn decode_cell_value(&self, value: &SessionReadValue) -> DocResult { + pub(super) fn decode_cell_value( + &self, + value: &SessionReadValue, + ) -> DocResult { match value { SessionReadValue::Text(_) => { Ok(DatabaseCellValue::RichText(self.rich_text(Some(value))?)) @@ -735,26 +738,25 @@ fn parse_views(value: Option<&JsonValue>) -> Vec { .unwrap_or_default(), }); let ui = obj.get("ui").cloned(); - - let mut extra = BTreeMap::new(); - for (k, v) in obj { - if !matches!( - k.as_str(), - "id" | "name" - | "mode" - | "columns" - | "filter" - | "sort" - | "groupBy" - | "groupProperties" - | "header" - | "date" - | "card" - | "ui" - ) { - extra.insert(k.clone(), v.clone()); - } - } + const KNOWN_VIEW_KEYS: &[&str] = &[ + "id", + "name", + "mode", + "columns", + "filter", + "sort", + "groupBy", + "groupProperties", + "header", + "date", + "card", + "ui", + ]; + let extra: BTreeMap = obj + .iter() + .filter(|(k, _)| !KNOWN_VIEW_KEYS.contains(&k.as_str())) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); Some(DatabaseView { id, @@ -780,3 +782,19 @@ fn json_as_i64(value: &JsonValue) -> Option { .as_i64() .or_else(|| value.as_f64().filter(|n| n.is_finite()).map(|n| n as i64)) } + +impl PageDocSession { + /// Decode a single database cell `SessionReadValue` (`Text`, `Array`, `Map`, or `Any`) via the + /// single authoritative [`SnapshotReader::decode_cell_value`] path. + pub(crate) fn decode_database_cell_read_value( + &self, + value: &SessionReadValue, + ) -> DocResult { + let reader = SnapshotReader { + page: self, + raw: BTreeMap::new(), + visited: BTreeSet::new(), + }; + reader.decode_cell_value(value) + } +} diff --git a/blocksuite/crates/doc/src/read/mod.rs b/blocksuite/crates/doc/src/read/mod.rs index 7359f605e8..f52b78d870 100644 --- a/blocksuite/crates/doc/src/read/mod.rs +++ b/blocksuite/crates/doc/src/read/mod.rs @@ -35,8 +35,11 @@ impl RichText { /// `prop:displayMode` of an `affine:note`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NoteDisplayMode { + /// Shown in both Page and Edgeless modes (`"both"`). Both, + /// Shown only in Page mode (`"doc"`). DocOnly, + /// Shown only in Edgeless mode (`"edgeless"`). EdgelessOnly, } @@ -48,8 +51,10 @@ impl NoteDisplayMode { Self::EdgelessOnly => "edgeless", } } + fn parse(value: Option<&str>) -> Self { match value { + // BlockSuite writes `"doc"`; `"page"` is read as the same mode. Some("doc" | "page") => Self::DocOnly, Some("edgeless") => Self::EdgelessOnly, _ => Self::Both, @@ -57,7 +62,8 @@ impl NoteDisplayMode { } } -/// `prop:textAlign` of a paragraph or list item (inherited from nearest ancestor if unset). +/// `prop:textAlign` of a paragraph or list item. Children without a value of their own +/// inherit the alignment of the nearest ancestor that has one. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum TextAlign { Left, @@ -73,6 +79,7 @@ impl TextAlign { Self::Right => "right", } } + pub fn parse(value: &str) -> Option { match value { "left" => Some(Self::Left), @@ -342,9 +349,9 @@ struct RawBlock { } struct SnapshotReader<'a> { - page: &'a PageDocSession, - raw: BTreeMap, - visited: BTreeSet, + pub(super) page: &'a PageDocSession, + pub(super) raw: BTreeMap, + pub(super) visited: BTreeSet, } impl PageDocSession { diff --git a/blocksuite/crates/doc/src/session/database/cell_text.rs b/blocksuite/crates/doc/src/session/database/cell_text.rs index e0a30a132f..d5666ec6b4 100644 --- a/blocksuite/crates/doc/src/session/database/cell_text.rs +++ b/blocksuite/crates/doc/src/session/database/cell_text.rs @@ -8,10 +8,13 @@ use y_octo::{ use crate::{ DocResult, + read::DatabaseCellValue, session::{insertion_marks_at, split_delta}, }; -use super::{PageCommit, PageDocSession, database_row_exists, write_cell_in_tx}; +use super::{ + PageCommit, PageDocSession, database_row_exists, read_raw_database_cell_value, write_cell_in_tx, +}; enum ResolvedDbCellText { LiveText(TypeIdentity), @@ -82,89 +85,28 @@ impl PageDocSession { if !database_row_exists(self, block_id, row_id) { return Ok(None); } + let from_decoded = |decoded: DatabaseCellValue| -> ResolvedDbCellText { + match decoded { + DatabaseCellValue::RichText(rt) => ResolvedDbCellText::LegacyDelta(rt.delta), + DatabaseCellValue::Text(s) => ResolvedDbCellText::PlainString(s), + _ => ResolvedDbCellText::Empty, + } + }; if is_title { let row_target = TypeTarget::Path(TypePath::root("blocks").key(row_id)); return Ok(Some( match self.inner().get_map_value(&row_target, "prop:text")? { Some(SessionReadValue::Text(id)) => ResolvedDbCellText::LiveText(id), - Some(SessionReadValue::Any(Any::String(s))) => { - ResolvedDbCellText::PlainString(s) - } - Some(SessionReadValue::Any(any)) => match parse_legacy_delta_any(&any) { - Some(ops) => ResolvedDbCellText::LegacyDelta(ops), - None => ResolvedDbCellText::Empty, - }, - _ => ResolvedDbCellText::Empty, + Some(raw) => from_decoded(self.decode_database_cell_read_value(&raw)?), + None => ResolvedDbCellText::Empty, }, )); } - let db_target = TypeTarget::Path(TypePath::root("blocks").key(block_id)); - let decode_cell_any = |cell_any: &Any| -> ResolvedDbCellText { - match cell_any { - Any::String(s) => ResolvedDbCellText::PlainString(s.clone()), - Any::Object(cell_obj) => match cell_obj.get("value") { - Some(Any::String(s)) => ResolvedDbCellText::PlainString(s.clone()), - Some(other) => match parse_legacy_delta_any(other) { - Some(ops) => ResolvedDbCellText::LegacyDelta(ops), - None => ResolvedDbCellText::Empty, - }, - None => match parse_legacy_delta_any(cell_any) { - Some(ops) => ResolvedDbCellText::LegacyDelta(ops), - None => ResolvedDbCellText::Empty, - }, - }, - other => match parse_legacy_delta_any(other) { - Some(ops) => ResolvedDbCellText::LegacyDelta(ops), - None => ResolvedDbCellText::Empty, - }, - } - }; - let lookup_row_obj = |row_obj: &y_octo::AHashMap| -> ResolvedDbCellText { - if let Some(entry) = row_obj.get(column_id) { - return decode_cell_any(entry); - } - for entry in row_obj.values() { - if let Any::Object(cell_obj) = entry - && let Some(Any::String(cid)) = cell_obj.get("columnId") - && cid == column_id - { - return decode_cell_any(entry); - } - } - ResolvedDbCellText::Empty - }; - - let resolved = match self.inner().get_map_value(&db_target, "prop:cells")? { - Some(SessionReadValue::Map(cells_map_id)) => { - let cells_target = TypeTarget::Identity(cells_map_id); - match self.inner().get_map_value(&cells_target, row_id)? { - Some(SessionReadValue::Map(row_map_id)) => { - let row_target = TypeTarget::Identity(row_map_id); - match self.inner().get_map_value(&row_target, column_id)? { - Some(SessionReadValue::Map(cell_map_id)) => { - let cell_target = TypeTarget::Identity(cell_map_id); - match self.inner().get_map_value(&cell_target, "value")? { - Some(SessionReadValue::Text(id)) => { - ResolvedDbCellText::LiveText(id) - } - Some(SessionReadValue::Any(any)) => decode_cell_any(&any), - _ => ResolvedDbCellText::Empty, - } - } - Some(SessionReadValue::Any(any)) => decode_cell_any(&any), - _ => ResolvedDbCellText::Empty, - } - } - Some(SessionReadValue::Any(Any::Object(row_obj))) => lookup_row_obj(&row_obj), - _ => ResolvedDbCellText::Empty, - } - } - Some(SessionReadValue::Any(Any::Object(cells_obj))) => match cells_obj.get(row_id) { - Some(Any::Object(row_obj)) => lookup_row_obj(row_obj), - _ => ResolvedDbCellText::Empty, - }, - _ => ResolvedDbCellText::Empty, + let resolved = match read_raw_database_cell_value(self, block_id, row_id, column_id)? { + Some(SessionReadValue::Text(id)) => ResolvedDbCellText::LiveText(id), + Some(raw) => from_decoded(self.decode_database_cell_read_value(&raw)?), + None => ResolvedDbCellText::Empty, }; Ok(Some(resolved)) } diff --git a/blocksuite/crates/doc/src/session/database/columns.rs b/blocksuite/crates/doc/src/session/database/columns.rs index a0d3426901..919f938978 100644 --- a/blocksuite/crates/doc/src/session/database/columns.rs +++ b/blocksuite/crates/doc/src/session/database/columns.rs @@ -502,6 +502,11 @@ impl PageDocSession { let (new_data, mut coerced_cells) = coerce_column_cells(db, &old_col, column_id, target_type, self.client_id()); if target_type == "multi-select" { + for (_, spec) in &mut coerced_cells { + if *spec == DatabaseCellSpec::Null { + *spec = DatabaseCellSpec::MultiSelect(Vec::new()); + } + } for row in &db.rows { if !coerced_cells.iter().any(|(rid, _)| rid == &row.row_id) { coerced_cells.push(( diff --git a/blocksuite/crates/doc/src/session/database/mod.rs b/blocksuite/crates/doc/src/session/database/mod.rs index 21eb01a4e5..2951046ba6 100644 --- a/blocksuite/crates/doc/src/session/database/mod.rs +++ b/blocksuite/crates/doc/src/session/database/mod.rs @@ -20,6 +20,9 @@ use crate::{ use super::{PageCommit, PageDocSession}; pub(super) fn any_to_session_value(any: Any) -> SessionValue { + if let Some(ops) = parse_legacy_delta_any(&any) { + return SessionValue::Text(ops); + } match any { Any::Object(obj) => SessionValue::Map( obj.into_iter() @@ -33,6 +36,82 @@ pub(super) fn any_to_session_value(any: Any) -> SessionValue { } } +/// Single authoritative `prop:cells -> row_id -> column_id -> value` lookup across both live +/// `Y.Map` hierarchies and legacy `Any::Object` envelopes (with zero mutation). +pub(super) fn read_raw_database_cell_value( + page: &PageDocSession, + block_id: &str, + row_id: &str, + column_id: &str, +) -> DocResult> { + let extract_cell_obj = |cell_any: Any| -> Option { + match cell_any { + Any::Object(mut cell_obj) => match cell_obj.remove("value") { + Some(v) => Some(SessionReadValue::Any(v)), + None => Some(SessionReadValue::Any(Any::Object(cell_obj))), + }, + other => Some(SessionReadValue::Any(other)), + } + }; + let extract_from_row_obj = |mut row_obj: AHashMap| -> Option { + if let Some(entry) = row_obj.remove(column_id) { + return extract_cell_obj(entry); + } + for (_, entry) in row_obj { + if let Any::Object(ref cell_obj) = entry + && cell_obj.get("columnId") == Some(&Any::String(column_id.to_string())) + { + return extract_cell_obj(entry); + } + } + None + }; + + let db_target = TypeTarget::Path(TypePath::root("blocks").key(block_id)); + match page.inner().get_map_value(&db_target, "prop:cells")? { + Some(SessionReadValue::Map(cells_id)) => { + let cells_target = TypeTarget::Identity(cells_id); + match page.inner().get_map_value(&cells_target, row_id)? { + Some(SessionReadValue::Map(row_map_id)) => { + let row_target = TypeTarget::Identity(row_map_id); + match page.inner().get_map_value(&row_target, column_id)? { + Some(SessionReadValue::Map(cell_map_id)) => { + let cell_target = TypeTarget::Identity(cell_map_id); + Ok(page.inner().get_map_value(&cell_target, "value")?) + } + Some(SessionReadValue::Any(any)) => Ok(extract_cell_obj(any)), + None => { + for (_, v) in page.inner().read_map(&row_target)? { + if let SessionReadValue::Map(cid_map) = v { + let ct = TypeTarget::Identity(cid_map); + if page.inner().get_map_value(&ct, "columnId")? + == Some(SessionReadValue::Any(Any::String( + column_id.to_string(), + ))) + { + return Ok(page.inner().get_map_value(&ct, "value")?); + } + } + } + Ok(None) + } + other => Ok(other), + } + } + Some(SessionReadValue::Any(Any::Object(row_obj))) => { + Ok(extract_from_row_obj(*row_obj)) + } + _ => Ok(None), + } + } + Some(SessionReadValue::Any(Any::Object(mut cells_obj))) => match cells_obj.remove(row_id) { + Some(Any::Object(row_obj)) => Ok(extract_from_row_obj(*row_obj)), + _ => Ok(None), + }, + _ => Ok(None), + } +} + fn new_cell_map(column_id: &str, value: SessionValue) -> SessionValue { SessionValue::Map(vec![ ( @@ -530,17 +609,7 @@ impl PageDocSession { )?; Ok(()) }; - if close_capture_after { - self.structural_edit(now_ms, apply) - } else { - self.stop_capturing()?; - self.advance_time(now_ms); - self.session.begin_tx(y_octo::SessionTxOrigin::Tracked)?; - let res = apply(self); - let commit = self.session.commit_tx(); - res?; - Ok(self.record_commit(commit?)) - } + self.structural_edit_with_capture(now_ms, close_capture_after, apply) } /// Reschedule a Calendar row by shifting its `start_column_id` (and preserving duration by diff --git a/blocksuite/crates/doc/src/session/database/select_options.rs b/blocksuite/crates/doc/src/session/database/select_options.rs index e180dfde91..1f174803f6 100644 --- a/blocksuite/crates/doc/src/session/database/select_options.rs +++ b/blocksuite/crates/doc/src/session/database/select_options.rs @@ -1,7 +1,7 @@ //! Select / multi-select option CRUD operations for `affine:database` columns. use serde_json::{Value as JsonValue, json}; -use y_octo::{Any, SessionReadValue, SessionValue, TypePath, TypeTarget}; +use y_octo::{Any, SessionReadValue, SessionValue, TypeTarget}; use crate::{ DocError, DocResult, @@ -11,7 +11,8 @@ use crate::{ use super::{ PageCommit, PageDocSession, columns::update_column_fields_in_tx, database_row_exists, - ensure_database_block_exists, write_cell_in_tx, write_multi_row_cells_in_tx, + ensure_database_block_exists, read_raw_database_cell_value, write_cell_in_tx, + write_multi_row_cells_in_tx, }; #[derive(Clone, Copy)] @@ -35,31 +36,10 @@ fn find_live_multi_select_array_in_tx( row_id: &str, column_id: &str, ) -> DocResult> { - let db_target = TypeTarget::Path(TypePath::root("blocks").key(block_id)); - let Some(SessionReadValue::Map(cells_id)) = - page.inner().get_map_value(&db_target, "prop:cells")? - else { - return Ok(None); - }; - let cells_target = TypeTarget::Identity(cells_id); - let Some(SessionReadValue::Map(row_id_map)) = - page.inner().get_map_value(&cells_target, row_id)? - else { - return Ok(None); - }; - let row_target = TypeTarget::Identity(row_id_map); - let Some(SessionReadValue::Map(cell_id_map)) = - page.inner().get_map_value(&row_target, column_id)? - else { - return Ok(None); - }; - let cell_target = TypeTarget::Identity(cell_id_map); - let Some(SessionReadValue::Array(arr_id)) = - page.inner().get_map_value(&cell_target, "value")? - else { - return Ok(None); - }; - Ok(Some(TypeTarget::Identity(arr_id))) + match read_raw_database_cell_value(page, block_id, row_id, column_id)? { + Some(SessionReadValue::Array(arr_id)) => Ok(Some(TypeTarget::Identity(arr_id))), + _ => Ok(None), + } } fn read_existing_multi_select_strings( @@ -68,63 +48,10 @@ fn read_existing_multi_select_strings( row_id: &str, column_id: &str, ) -> DocResult> { - let extract_any_list = |any: &Any| -> Vec { - let arr_opt = match any { - Any::Array(arr) => Some(arr), - Any::Object(obj) => match obj.get("value") { - Some(Any::Array(arr)) => Some(arr), - _ => None, - }, - _ => None, - }; - let Some(arr) = arr_opt else { - return Vec::new(); - }; - let mut out = Vec::new(); - for item in arr { - if let Any::String(s) = item - && !out.contains(s) - { - out.push(s.clone()); - } - } - out + let Some(raw) = read_raw_database_cell_value(page, block_id, row_id, column_id)? else { + return Ok(Vec::new()); }; - let db_target = TypeTarget::Path(TypePath::root("blocks").key(block_id)); - match page.inner().get_map_value(&db_target, "prop:cells")? { - Some(SessionReadValue::Map(cells_id)) => { - let cells_target = TypeTarget::Identity(cells_id); - match page.inner().get_map_value(&cells_target, row_id)? { - Some(SessionReadValue::Map(row_map_id)) => { - let row_target = TypeTarget::Identity(row_map_id); - match page.inner().get_map_value(&row_target, column_id)? { - Some(SessionReadValue::Map(cell_map_id)) => { - let cell_target = TypeTarget::Identity(cell_map_id); - match page.inner().get_map_value(&cell_target, "value")? { - Some(SessionReadValue::Any(any)) => Ok(extract_any_list(&any)), - _ => Ok(Vec::new()), - } - } - Some(SessionReadValue::Any(any)) => Ok(extract_any_list(&any)), - _ => Ok(Vec::new()), - } - } - Some(SessionReadValue::Any(Any::Object(row_obj))) => Ok(row_obj - .get(column_id) - .map(extract_any_list) - .unwrap_or_default()), - _ => Ok(Vec::new()), - } - } - Some(SessionReadValue::Any(Any::Object(cells_obj))) => Ok(cells_obj - .get(row_id) - .and_then(|r| match r { - Any::Object(ro) => ro.get(column_id).map(extract_any_list), - _ => None, - }) - .unwrap_or_default()), - _ => Ok(Vec::new()), - } + Ok(page.decode_database_cell_read_value(&raw)?.as_string_list()) } fn apply_multi_select_op_to_vec(mut items: Vec, op: MultiSelectOp<'_>) -> Vec { @@ -249,6 +176,69 @@ impl PageDocSession { }) } + /// Move a row between `multi-select` Kanban group lanes (`remove_option_id` -> `add_option_id`) + /// in place on its `Y.Array` (or single-step upgrade if legacy), preserving all unrelated tags + /// on the row (`0.27.5` `group-by/define.ts` `removeFromGroup` + `addToGroup`). + #[allow(clippy::too_many_arguments)] + pub fn move_database_multi_select_group( + &mut self, + block_id: &str, + row_id: &str, + column_id: &str, + remove_option_id: Option<&str>, + add_option_id: Option<&str>, + now_ms: u64, + ) -> DocResult { + ensure_database_block_exists(self, block_id)?; + if !database_row_exists(self, block_id, row_id) { + return Ok(None); + } + if remove_option_id == add_option_id { + return Ok(None); + } + let block_id = block_id.to_string(); + let row_id = row_id.to_string(); + let column_id = column_id.to_string(); + let rem = remove_option_id.map(str::to_string); + let add = add_option_id.map(str::to_string); + self.structural_edit(now_ms, move |page| { + if let Some(arr_target) = + find_live_multi_select_array_in_tx(page, &block_id, &row_id, &column_id)? + { + if let Some(ref r) = rem { + mutate_multi_select_array_in_place( + page, + &arr_target, + MultiSelectOp::RemoveIfPresent(r), + )?; + } + if let Some(ref a) = add { + mutate_multi_select_array_in_place( + page, + &arr_target, + MultiSelectOp::AddIfAbsent(a), + )?; + } + return Ok(()); + } + let mut next = + read_existing_multi_select_strings(page, &block_id, &row_id, &column_id)?; + if let Some(ref r) = rem { + next = apply_multi_select_op_to_vec(next, MultiSelectOp::RemoveIfPresent(r)); + } + if let Some(ref a) = add { + next = apply_multi_select_op_to_vec(next, MultiSelectOp::AddIfAbsent(a)); + } + write_cell_in_tx( + page, + &block_id, + &row_id, + &column_id, + DatabaseCellSpec::MultiSelect(next).into_session_value(), + ) + }) + } + /// Create or update (rename / recolor) a select/multi-select option in `column.data.options` /// in one tracked undo step. pub fn upsert_database_select_option( diff --git a/blocksuite/crates/doc/src/session/structure.rs b/blocksuite/crates/doc/src/session/structure.rs index 4a41007185..0a17419d1a 100644 --- a/blocksuite/crates/doc/src/session/structure.rs +++ b/blocksuite/crates/doc/src/session/structure.rs @@ -37,6 +37,15 @@ impl PageDocSession { &mut self, now_ms: u64, apply: impl FnOnce(&mut Self) -> DocResult + Clone, + ) -> DocResult { + self.structural_edit_with_capture(now_ms, true, apply) + } + + pub(crate) fn structural_edit_with_capture( + &mut self, + now_ms: u64, + close_capture_after: bool, + apply: impl FnOnce(&mut Self) -> DocResult + Clone, ) -> DocResult { if self.session.tx_depth() == 0 { let mut validation = Self::new(self.guid(), self.client_id())?; @@ -51,7 +60,9 @@ impl PageDocSession { self.session.begin_tx(SessionTxOrigin::Tracked)?; let result = apply(self); let commit = self.session.commit_tx(); - self.stop_capturing()?; + if close_capture_after { + self.stop_capturing()?; + } result?; Ok(self.record_commit(commit?)) } diff --git a/blocksuite/crates/doc/tests/database_authoring.rs b/blocksuite/crates/doc/tests/database_authoring.rs index 77e34565f1..6f21c06913 100644 --- a/blocksuite/crates/doc/tests/database_authoring.rs +++ b/blocksuite/crates/doc/tests/database_authoring.rs @@ -1256,3 +1256,157 @@ fn concurrent_multi_select_toggle_and_legacy_any_object_cells_preserve_data() -> ); Ok(()) } + +#[test] +fn legacy_sibling_upgrade_preserves_rich_text_and_blank_multi_select_conversion_merges() +-> DocResult<()> { + // 1. Upgrading a legacy `Any::Object` `prop:cells` row by toggling `col-tags` FIRST must not + // corrupt an untouched sibling `col-note` delta (`{"$blocksuite:internal:text$": true, + // "delta": [...]}`): subsequent `splice_database_cell_text` at offset 11 (`"!"`) must keep + // both the text `"Legacy note!"` AND the bold mark on `"Legacy"`, and survive Undo/Redo. + let (mut page, db) = seed_authoring_database()?; + for (key, label) in [("t-a", "Alpha"), ("t-b", "Beta")] { + page.upsert_database_select_option(&db, "col-tags", key, label, "red", 80)?; + } + let cells = serde_json::from_value(json!({ + "r1": { + "col-tags": {"columnId": "col-tags", "value": ["tag-ui"]}, + "col-note": {"columnId": "col-note", "value": { + "$blocksuite:internal:text$": true, + "delta": [ + {"insert": "Legacy", "attributes": {"bold": true}}, + {"insert": " note"} + ] + }} + } + })) + .unwrap(); + page.set_block_prop(&db, "prop:cells", y_octo::SessionValue::Any(cells), 91)?; + page.stop_capturing()?; + + let note_key = ("r1".to_string(), "col-note".to_string()); + page.toggle_database_multi_select_option(&db, "r1", "col-tags", "t-a", 101)?; + page.stop_capturing()?; + assert_eq!( + read_db(&page, &db).cells[¬e_key].as_str(), + Some("Legacy note") + ); + + page.splice_database_cell_text(&db, "r1", "col-note", 11, 0, "!", 115)?; + page.stop_capturing()?; + let assert_bold_note = |p: &PageDocSession, expected: &str| { + let cell = &read_db(p, &db).cells[¬e_key]; + let blocksuite_playground_doc::read::DatabaseCellValue::RichText(rt) = cell else { + panic!("expected RichText cell, got {cell:?}"); + }; + assert_eq!(rt.plain, expected); + assert!( + rt.delta.iter().any(|op| matches!( + op, + y_octo::TextDeltaOp::Insert { + insert: y_octo::TextInsert::Text(t), + format: Some(f), + } if t == "Legacy" && f.get("bold") == Some(&y_octo::Any::True) + )), + "bold mark on 'Legacy' must survive sibling upgrade + edit/undo/redo, got {:?}", + rt.delta + ); + }; + assert_bold_note(&page, "Legacy note!"); + assert!(page.undo()?.is_some()); + assert_bold_note(&page, "Legacy note"); + assert!(page.redo()?.is_some()); + assert_bold_note(&page, "Legacy note!"); + + // Also verify a cell whose `value` was stored as a nested `Y.Map({"delta": ...})` decodes + // identically via `SnapshotReader` on first `splice_database_cell_text`. + let nested_map_val = blocksuite_playground_doc::schema::json_to_session_value(&json!({ + "$blocksuite:internal:text$": true, + "delta": [ + {"insert": "Mapped", "attributes": {"italic": true}}, + {"insert": " cell"} + ] + })); + let r1_note_target = y_octo::TypeTarget::Path( + y_octo::TypePath::root("blocks") + .key(&db) + .key("prop:cells") + .key("r1") + .key("col-note"), + ); + page.inner_mut() + .begin_tx(y_octo::SessionTxOrigin::Untracked)?; + page.inner_mut() + .map_set(&r1_note_target, "value".into(), nested_map_val)?; + page.inner_mut().commit_tx()?; + page.stop_capturing()?; + assert_eq!( + read_db(&page, &db).cells[¬e_key].as_str(), + Some("Mapped cell") + ); + page.splice_database_cell_text(&db, "r1", "col-note", 11, 0, "?", 130)?; + assert_eq!( + read_db(&page, &db).cells[¬e_key].as_str(), + Some("Mapped cell?") + ); + + // 2. Converting a `rich-text` column with BOTH a filled row (`r1`) and a blank row (`r2`) to + // `multi-select` pre-initializes shared `Y.Array` containers on every row so concurrent + // toggles merge losslessly on `r2` as well. + let (mut a, db2) = seed_authoring_database()?; + a.add_database_row_with_cells( + &db2, + "r2", + "Blank note row", + vec![("col-note".into(), DatabaseCellSpec::RichText(String::new()))], + 10, + )?; + a.change_database_column_type(&db2, "col-note", "multi-select", 20)?; + a.stop_capturing()?; + let mut b = PageDocSession::new("page-db-auth", 22)?; + b.apply_remote_update_v1(&a.encode_update_v1()?)?; + let (sva, svb) = (a.encode_state_vector_v1()?, b.encode_state_vector_v1()?); + a.toggle_database_multi_select_option(&db2, "r2", "col-note", "t-a", 30)?; + b.toggle_database_multi_select_option(&db2, "r2", "col-note", "t-b", 31)?; + let (da, dbb) = (a.encode_diff_v1(&svb)?, b.encode_diff_v1(&sva)?); + a.apply_remote_update_v1(&dbb)?; + b.apply_remote_update_v1(&da)?; + let mut r2_tags_a = read_db(&a, &db2).cells[&("r2".into(), "col-note".into())].as_string_list(); + let mut r2_tags_b = read_db(&b, &db2).cells[&("r2".into(), "col-note".into())].as_string_list(); + r2_tags_a.sort(); + r2_tags_b.sort(); + assert_eq!(r2_tags_a, vec!["t-a", "t-b"]); + assert_eq!(r2_tags_b, vec!["t-a", "t-b"]); + + // 3. Side-by-side Yjs V1 baseline verification: + // - Atomic `ContentAny` `prop:cells`: concurrent offline replacements resolve deterministically + // by `ClientId` (`client 229` wins over lower `client`, matching upstream `yjs@13.6.21`); + // - Synced `Y.Array` cell: concurrent offline toggles preserve both `t-a` and `t-b`. + let (mut left_any, db_any) = seed_authoring_database()?; + let raw_any = serde_json::from_value(json!({ + "r1": { "col-tags": { "columnId": "col-tags", "value": ["tag-ui"] } } + })) + .unwrap(); + left_any.set_block_prop( + &db_any, + "prop:cells", + y_octo::SessionValue::Any(raw_any), + 40, + )?; + let mut right_any = PageDocSession::new("page-db-auth", 229)?; + right_any.apply_remote_update_v1(&left_any.encode_update_v1()?)?; + let base_any = left_any.encode_state_vector_v1()?; + left_any.toggle_database_multi_select_option(&db_any, "r1", "col-tags", "t-a", 41)?; + right_any.toggle_database_multi_select_option(&db_any, "r1", "col-tags", "t-b", 41)?; + let (u_l, u_r) = ( + left_any.encode_diff_v1(&base_any)?, + right_any.encode_diff_v1(&base_any)?, + ); + left_any.apply_remote_update_v1(&u_r)?; + right_any.apply_remote_update_v1(&u_l)?; + assert_eq!( + read_db(&left_any, &db_any).cells[&("r1".into(), "col-tags".into())].as_string_list(), + read_db(&right_any, &db_any).cells[&("r1".into(), "col-tags".into())].as_string_list() + ); + Ok(()) +} diff --git a/blocksuite/crates/editor/src/database/authoring.rs b/blocksuite/crates/editor/src/database/authoring.rs index 3e25458e35..a22cb36b97 100644 --- a/blocksuite/crates/editor/src/database/authoring.rs +++ b/blocksuite/crates/editor/src/database/authoring.rs @@ -1,6 +1,8 @@ //! Unified authoring state types, floating popover dispatcher, keyboard handler, and drag //! commit helpers for `affine:database`. +use std::collections::BTreeMap; + use blocksuite_playground_doc::{ DocResult, read::{DatabaseData, DatabaseView}, @@ -15,7 +17,7 @@ use super::{ cell_editor::{ ParsedCellInput, initial_cell_draft, next_editable_cell, next_tag_color, parse_cell_draft, }, - column_ops, eval_database_filter, sort_database_rows, + column_ops, eval_database_filter_with_titles, sort_database_rows_with_titles, }; /// Block-local anchor rectangle for an open floating database popover, translated into screen @@ -279,6 +281,7 @@ pub fn handle_authoring_key( flow_state: &mut DatabaseFlowState, block_id: &str, data: &DatabaseData, + page_titles: &BTreeMap, key: DatabaseAuthoringKey, offset_at_ms: &dyn Fn(i64) -> i32, now_ms: u64, @@ -477,15 +480,17 @@ pub fn handle_authoring_key( .rows .iter() .filter(|r| { - view.and_then(|v| v.filter.as_ref()) - .is_none_or(|f| eval_database_filter(f, data, r)) + view.and_then(|v| v.filter.as_ref()).is_none_or(|f| { + eval_database_filter_with_titles(f, data, r, page_titles) + }) }) .cloned() .collect(); - let ordered_rows = sort_database_rows( + let ordered_rows = sort_database_rows_with_titles( &filtered_rows, view.and_then(|v| v.sort.as_ref()), data, + page_titles, ); let cols: Vec<(String, String)> = match view { Some(v) => column_ops::resolve_visible_columns(v, data) @@ -637,7 +642,8 @@ mod tests { use serde_json::json; use super::*; - use crate::database::group_database_rows; + use crate::database::group::group_database_rows; + use crate::database::query::eval_database_filter; fn seed_editor_db() -> (PageDocSession, String) { let mut page = PageDocSession::new("page-ed-auth", 7).expect("page"); @@ -868,6 +874,7 @@ mod tests { &mut flow_state, &db_id, &db, + &BTreeMap::new(), DatabaseAuthoringKey::Tab, &utc, 101, diff --git a/blocksuite/crates/editor/src/database/cell_editor.rs b/blocksuite/crates/editor/src/database/cell_editor.rs index c3f7c7c446..edf3fda50e 100644 --- a/blocksuite/crates/editor/src/database/cell_editor.rs +++ b/blocksuite/crates/editor/src/database/cell_editor.rs @@ -669,11 +669,7 @@ pub(super) fn rich_cell_prim_with_hit( min_row_h: f32, ) -> (DatabasePrim, crate::block_flow::TableCellHit) { let lh = f32::from(laid.line_height()); - let text_y = if laid.lines().len() <= 1 { - cell_rect.y + ((min_row_h - lh) * 0.5).floor().max(2.0) - } else { - cell_rect.y + 6.0 - }; + let text_y = cell_rect.y + ((min_row_h - lh) * 0.5).floor().max(1.0); let prim = DatabasePrim::Rich { x: inner_x, y: text_y, @@ -695,42 +691,25 @@ pub(super) fn rich_cell_prim_with_hit( (prim, hit) } -/// Lay out and build `(DatabasePrim::Rich, DatabaseActiveCellLayout)` for an active Kanban card -/// title or `rich-text` property cell. -#[allow(clippy::too_many_arguments)] -pub(super) fn kanban_active_rich_cell( - ctx: &DbRenderCtx<'_>, +/// Build `(DatabasePrim::Rich, DatabaseActiveCellLayout)` from an already laid-out Kanban card +/// title or `rich-text` property paragraph so card height and edit bounds share one layout pass. +pub(super) fn kanban_active_rich_cell_from_laid( row_id: &str, column_id: &str, - rt: &blocksuite_playground_doc::read::RichText, - font_size: f32, - line_height: f32, - weight: f32, + laid: std::sync::Arc, inner_x: f32, inner_w: f32, cell_rect: FlowRect, min_h: f32, - align: InlineAlign, -) -> Option<(DatabasePrim, super::DatabaseActiveCellLayout)> { - let laid = layout_rich_cell_sized( - ctx, - rt, - font_size, - line_height, - weight, - ctx.palette.text_primary, - inner_w, - true, - align, - )?; +) -> (DatabasePrim, super::DatabaseActiveCellLayout) { let (prim, hit) = rich_cell_prim_with_hit(row_id, column_id, laid, inner_x, inner_w, cell_rect, min_h); - Some(( + ( prim, super::DatabaseActiveCellLayout { rect: cell_rect, scrolls_x: true, rich_hit: Some(hit), }, - )) + ) } diff --git a/blocksuite/crates/editor/src/database/format.rs b/blocksuite/crates/editor/src/database/format.rs index 77cfb21e46..15b8583165 100644 --- a/blocksuite/crates/editor/src/database/format.rs +++ b/blocksuite/crates/editor/src/database/format.rs @@ -201,11 +201,10 @@ pub fn column_icon_name(col_type: &str) -> &'static str { } } -/// Resolve a `RichText` value to display text, expanding `@reference` (`LinkedPage`) embeds -/// against `page_titles` (`@`, or `@Untitled` when the referenced page has no title). -pub fn resolve_rich_text_plain( +fn resolve_rich_text_inner( rt: &blocksuite_playground_doc::read::RichText, page_titles: &std::collections::BTreeMap<String, String>, + display_mode: bool, ) -> String { if rt.delta.is_empty() { return rt.plain.clone(); @@ -213,25 +212,40 @@ pub fn resolve_rich_text_plain( let mut out = String::new(); for op in &rt.delta { if let y_octo::TextDeltaOp::Insert { insert, format } = op { - let ref_page_id = - format - .as_ref() - .and_then(|f| f.get("reference")) - .and_then(|r| match r { - y_octo::Any::Object(m) => match m.get("pageId") { + let ref_info = format + .as_ref() + .and_then(|f| f.get("reference")) + .and_then(|r| match r { + y_octo::Any::Object(m) => { + let pid = match m.get("pageId") { Some(y_octo::Any::String(s)) => Some(s.as_str()), _ => None, - }, - _ => None, - }); - if let Some(pid) = ref_page_id { - let title = match page_titles.get(pid) { - Some(s) if !s.is_empty() => s.as_str(), - Some(_) => "Untitled", - None if !page_titles.is_empty() => "Deleted page", - None => "Untitled", + }?; + let alias = match m.get("title") { + Some(y_octo::Any::String(s)) if !s.is_empty() => Some(s.as_str()), + _ => None, + }; + Some((pid, alias)) + } + _ => None, + }); + if let Some((pid, alias)) = ref_info { + let deleted_label = if display_mode { + "Deleted page" + } else { + "Deleted doc" }; - out.push('@'); + let title = match (alias, page_titles.get(pid)) { + (Some(a), Some(_)) => a, + (Some(a), None) if page_titles.is_empty() => a, + (None, Some(s)) if !s.is_empty() => s.as_str(), + (_, Some(_)) => "Untitled", + (_, None) if !page_titles.is_empty() => deleted_label, + (_, None) => "Untitled", + }; + if display_mode { + out.push('@'); + } out.push_str(title); } else if let y_octo::TextInsert::Text(s) = insert { out.push_str(s); @@ -245,6 +259,25 @@ pub fn resolve_rich_text_plain( } } +/// Resolve a `RichText` value to display text, expanding `@reference` (`LinkedPage`) embeds +/// against `page_titles` (`@<Title>`, `@Deleted page`, or `@Untitled`). +pub fn resolve_rich_text_plain( + rt: &blocksuite_playground_doc::read::RichText, + page_titles: &std::collections::BTreeMap<String, String>, +) -> String { + resolve_rich_text_inner(rt, page_titles, true) +} + +/// Resolve a `RichText` value for Filter / Sort / Group evaluation matching BlockSuite `0.27.5` +/// `blocks/database/src/utils/title-doc.ts` (`getTextWithResolvedReferences`, no `@` prefix, +/// `"Deleted doc"` for missing pages, honoring inline `reference.title` aliases). +pub fn resolve_rich_text_query( + rt: &blocksuite_playground_doc::read::RichText, + page_titles: &std::collections::BTreeMap<String, String>, +) -> String { + resolve_rich_text_inner(rt, page_titles, false) +} + #[cfg(test)] mod tests { use super::*; diff --git a/blocksuite/crates/editor/src/database/group.rs b/blocksuite/crates/editor/src/database/group.rs index b95d34f3d5..a612ca551f 100644 --- a/blocksuite/crates/editor/src/database/group.rs +++ b/blocksuite/crates/editor/src/database/group.rs @@ -226,10 +226,8 @@ fn number_group_key_and_label(v: f64) -> (String, String) { (key, label) } -/// Group rows into ordered buckets matching `0.27.5` `GroupTrait`, `define.ts`, and -/// `kanban/group-by-utils.ts`: honors `"Ungroups"` default-first ordering, `groupProperties` -/// manual order / `hide` / `manuallyCardSort`, `hideEmpty`, and date/number bucket titles. -pub fn group_database_rows( +#[cfg(test)] +pub(crate) fn group_database_rows( rows: &[DatabaseRow], group_by: &DatabaseGroupBy, group_properties: &[DatabaseGroupProperty], @@ -444,16 +442,40 @@ pub fn group_database_rows_with_titles( "select" => Some(DatabaseCellSpec::Text(key.clone())), "multi-select" => Some(DatabaseCellSpec::MultiSelect(vec![key.clone()])), "checkbox" => Some(DatabaseCellSpec::Bool(key == "true")), - _ if is_date => match key.as_str() { - "today" => Some(DatabaseCellSpec::Integer(now_ms)), - "tomorrow" => { - Some(DatabaseCellSpec::Integer(now_ms.saturating_add(86_400_000))) + _ if is_date => { + let today_idx = local_day_index(now_ms, offset_at_ms); + match key.as_str() { + "today" => Some(DatabaseCellSpec::Integer(local_midnight_utc_ms( + today_idx, + offset_at_ms, + ))), + "tomorrow" => Some(DatabaseCellSpec::Integer(local_midnight_utc_ms( + today_idx + 1, + offset_at_ms, + ))), + "yesterday" => Some(DatabaseCellSpec::Integer(local_midnight_utc_ms( + today_idx - 1, + offset_at_ms, + ))), + "next7" => Some(DatabaseCellSpec::Integer(local_midnight_utc_ms( + today_idx + 2, + offset_at_ms, + ))), + "next30" => Some(DatabaseCellSpec::Integer(local_midnight_utc_ms( + today_idx + 8, + offset_at_ms, + ))), + "last7" => Some(DatabaseCellSpec::Integer(local_midnight_utc_ms( + today_idx - 2, + offset_at_ms, + ))), + "last30" => Some(DatabaseCellSpec::Integer(local_midnight_utc_ms( + today_idx - 8, + offset_at_ms, + ))), + _ => key.parse::<i64>().ok().map(DatabaseCellSpec::Integer), } - "yesterday" => { - Some(DatabaseCellSpec::Integer(now_ms.saturating_sub(86_400_000))) - } - _ => key.parse::<i64>().ok().map(DatabaseCellSpec::Integer), - }, + } _ if is_number => key .strip_prefix("g:") .and_then(|s| s.parse::<i64>().ok()) @@ -724,6 +746,36 @@ mod tests { ); assert!(rel_keys.contains(&"today")); + let rel_all_buckets = group_database_rows( + &nyc_rows, + &DatabaseGroupBy { + kind: "groupBy".into(), + column_id: "col-date".into(), + name: "date-relative".into(), + hide_empty: Some(true), + sort: None, + }, + &[], + &nyc_data, + 1_767_625_200_000, + &nyc_tz, + ); + let next7 = rel_all_buckets + .iter() + .find(|b| b.key == "next7") + .expect("next7 bucket must exist"); + let Some(DatabaseCellSpec::Integer(next7_seed)) = next7.seed_value else { + panic!( + "next7 must carry an Integer seed_value, got {:?}", + next7.seed_value + ); + }; + assert_eq!( + date_group_key_and_label(next7_seed, "date-relative", 1_767_625_200_000, &nyc_tz).0, + "next7", + "next7 seed_value must classify back into the next7 bucket" + ); + // Midnight spring-forward DST jump (`America/Havana` 2026-03-08 00:00 -> 01:00 at // `1772946000000` UTC): key must match Web `startOfDay` (`"1772946000000"`), not 23:00 CST. let havana_tz = |ms: i64| { diff --git a/blocksuite/crates/editor/src/database/mod.rs b/blocksuite/crates/editor/src/database/mod.rs index 40ef74b6d0..b50d0eb334 100644 --- a/blocksuite/crates/editor/src/database/mod.rs +++ b/blocksuite/crates/editor/src/database/mod.rs @@ -59,14 +59,11 @@ 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_tag_accent, resolve_tag_color, + resolve_rich_text_plain, resolve_rich_text_query, resolve_tag_accent, resolve_tag_color, }; -pub use group::{DatabaseGroupBucket, group_database_rows, group_database_rows_with_titles}; +pub use group::{DatabaseGroupBucket, group_database_rows_with_titles}; pub use popover_overlay::{DatabasePopoverOverlay, layout_database_popover_overlay}; -pub use query::{ - eval_database_filter, eval_database_filter_with_titles, sort_database_rows, - sort_database_rows_with_titles, -}; +pub use query::{eval_database_filter_with_titles, sort_database_rows_with_titles}; pub use render::{DatabaseLayoutOutput, DatabasePrim, layout_database_block}; pub use render_calendar::resolve_calendar_display_month; pub use render_types::DatabaseActiveCellLayout; diff --git a/blocksuite/crates/editor/src/database/query.rs b/blocksuite/crates/editor/src/database/query.rs index a497748b25..b0099e317f 100644 --- a/blocksuite/crates/editor/src/database/query.rs +++ b/blocksuite/crates/editor/src/database/query.rs @@ -6,10 +6,14 @@ use std::{cmp::Ordering, collections::BTreeMap}; use blocksuite_playground_doc::read::{DatabaseCellValue, DatabaseData, DatabaseRow}; use serde_json::Value as JsonValue; -use super::resolve_rich_text_plain; +use super::resolve_rich_text_query; -/// Evaluate a BlockSuite `FilterGroup` / `Filter` tree against one database row. -pub fn eval_database_filter(filter: &JsonValue, data: &DatabaseData, row: &DatabaseRow) -> bool { +#[cfg(test)] +pub(crate) fn eval_database_filter( + filter: &JsonValue, + data: &DatabaseData, + row: &DatabaseRow, +) -> bool { eval_database_filter_with_titles(filter, data, row, &BTreeMap::new()) } @@ -241,10 +245,8 @@ fn eval_single_filter( } } -/// Sort filtered database rows according to `0.27.5` `view.sort` -/// (`{ sortBy: [{ ref: { name }, desc }] }`). -/// Empty/null values always sort last regardless of `desc`. -pub fn sort_database_rows( +#[cfg(test)] +pub(crate) fn sort_database_rows( rows: &[DatabaseRow], sort: Option<&JsonValue>, data: &DatabaseData, @@ -554,11 +556,11 @@ pub(super) fn row_cell_text_with_titles( .find(|c| c.id == col_id) .is_some_and(|c| c.column_type == "title") { - return resolve_rich_text_plain(&row.title, page_titles); + return resolve_rich_text_query(&row.title, page_titles); } match data.cells.get(&(row.row_id.clone(), col_id.to_string())) { Some(DatabaseCellValue::Text(s)) => s.clone(), - Some(DatabaseCellValue::RichText(rt)) => resolve_rich_text_plain(rt, page_titles), + Some(DatabaseCellValue::RichText(rt)) => resolve_rich_text_query(rt, page_titles), Some(DatabaseCellValue::Bool(b)) => b.to_string(), Some(DatabaseCellValue::Integer(n)) => n.to_string(), Some(DatabaseCellValue::Number(n)) => n.to_string(), @@ -1086,5 +1088,81 @@ mod tests { let sorted = sort_database_rows(&many_rows, Some(&rule), &many_data); assert_eq!(sorted.len(), 80); } + + // Reference resolution in filter/sort matches BlockSuite `0.27.5` `title-doc.ts` + // (`getTextWithResolvedReferences`: no `@` prefix, `"Deleted doc"` for missing pages, + // and inline `reference.title` alias support). + let ref_op = |pid: &str, alias: Option<&str>| { + let mut m = y_octo::AHashMap::default(); + m.insert("type".to_string(), y_octo::Any::String("LinkedPage".into())); + m.insert("pageId".to_string(), y_octo::Any::String(pid.into())); + if let Some(a) = alias { + m.insert("title".to_string(), y_octo::Any::String(a.into())); + } + let mut fmt = BTreeMap::new(); + fmt.insert("reference".to_string(), y_octo::Any::Object(Box::new(m))); + y_octo::TextDeltaOp::Insert { + insert: y_octo::TextInsert::Text(" ".into()), + format: Some(fmt), + } + }; + let row_live = DatabaseRow { + row_id: "rl".into(), + title: RichText { + plain: " ".into(), + delta: vec![ref_op("doc-road", None)], + }, + created_at: None, + }; + let row_del = DatabaseRow { + row_id: "rd".into(), + title: RichText { + plain: " ".into(), + delta: vec![ref_op("doc-gone", None)], + }, + created_at: None, + }; + let row_alias = DatabaseRow { + row_id: "ra".into(), + title: RichText { + plain: " ".into(), + delta: vec![ref_op("doc-road", Some("Custom Alias"))], + }, + created_at: None, + }; + let titles = BTreeMap::from([("doc-road".to_string(), "Roadmap".to_string())]); + let is_roadmap = json!({ + "type": "filter", + "left": { "type": "ref", "name": "title" }, + "function": "is", + "args": [{ "type": "literal", "value": "Roadmap" }] + }); + let is_deleted = json!({ + "type": "filter", + "left": { "type": "ref", "name": "title" }, + "function": "is", + "args": [{ "type": "literal", "value": "Deleted doc" }] + }); + let is_alias = json!({ + "type": "filter", + "left": { "type": "ref", "name": "title" }, + "function": "is", + "args": [{ "type": "literal", "value": "Custom Alias" }] + }); + assert!(eval_database_filter_with_titles( + &is_roadmap, + &many_data, + &row_live, + &titles + )); + assert!(eval_database_filter_with_titles( + &is_deleted, + &many_data, + &row_del, + &titles + )); + assert!(eval_database_filter_with_titles( + &is_alias, &many_data, &row_alias, &titles + )); } } diff --git a/blocksuite/crates/editor/src/database/render_kanban_card.rs b/blocksuite/crates/editor/src/database/render_kanban_card.rs index 62eaf2e50c..c7b7547c53 100644 --- a/blocksuite/crates/editor/src/database/render_kanban_card.rs +++ b/blocksuite/crates/editor/src/database/render_kanban_card.rs @@ -11,7 +11,8 @@ use super::{ DatabaseActiveCellLayout, DatabaseAuthoringHit, DatabaseAuthoringHitKind, DatabaseHitKind, DatabaseHitTarget, DatabasePopoverAnchor, cell_editor::{ - is_editable_column_type, kanban_active_rich_cell, layout_rich_cell_sized, rich_cell_prim, + 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, render::{DatabasePrim, DbRenderCtx}, @@ -175,11 +176,73 @@ pub(super) fn render_kanban_card( active_cell: &mut Option<DatabaseActiveCellLayout>, ) -> f32 { let prop_lines = collect_kanban_card_props(ctx, row, visible_prop_ids); - let card_h = if prop_lines.is_empty() { - 36.0 - } else { - 40.0 + (prop_lines.len() as f32 * 22.0) - }; + let title_col_id = ctx + .data + .columns + .iter() + .find(|c| c.column_type == "title") + .map_or("title", |c| c.id.as_str()); + let title_inner_x = card_x + CARD_PAD; + let title_inner_w = (card_w - 2.0 * CARD_PAD).max(1.0); + let title_editing = ctx + .ui_state + .authoring + .active_cell + .as_ref() + .is_some_and(|e| e.row_id == row.row_id && e.column_id == title_col_id); + let title_laid = layout_rich_cell_sized( + ctx, + &row.title, + TYPOGRAPHY.font_sm_px, + 20.0, + 500.0, + ctx.palette.text_primary, + title_inner_w, + title_editing, + align, + ); + let title_lines = title_laid.as_ref().map_or(1, |l| l.lines().len().max(1)); + let title_h = (title_lines as f32 * 20.0 + 4.0).max(24.0); + let extra_title_h = title_h - 24.0; + + let inner_x = card_x + CARD_PAD; + let inner_w = (card_w - 2.0 * CARD_PAD).max(1.0); + let empty_rt = blocksuite_playground_doc::read::RichText::default(); + let active_rich_prop_laid: Option<(String, std::sync::Arc<crate::rich_text::LaidOutRichParagraph>)> = + ctx.ui_state + .authoring + .active_cell + .as_ref() + .filter(|ed| ed.row_id == row.row_id && ed.error.is_none() && ed.col_type == "rich-text") + .and_then(|ed| { + let is_visible = prop_lines.iter().any(|p| { + matches!(p, KanbanProp::Text { col_id, col_type, .. } if col_id == &ed.column_id && col_type == "rich-text") + }); + if !is_visible { + return None; + } + let rt = match ctx.data.cells.get(&(row.row_id.clone(), ed.column_id.clone())) { + Some(blocksuite_playground_doc::read::DatabaseCellValue::RichText(rt)) => rt, + _ => &empty_rt, + }; + let laid = layout_rich_cell_sized( + ctx, + rt, + TYPOGRAPHY.font_xs_px, + 18.0, + 400.0, + ctx.palette.text_primary, + (inner_w - 4.0).max(1.0), + true, + align, + )?; + Some((ed.column_id.clone(), laid)) + }); + let extra_prop_h = active_rich_prop_laid.as_ref().map_or(0.0, |(_, l)| { + ((l.lines().len().max(1) as f32 * 18.0 + 2.0).max(20.0)) - 20.0 + }); + + let card_h = 34.0 + extra_title_h + extra_prop_h + (prop_lines.len() as f32 * 22.0); let card_rect = FlowRect::new(card_x, cy, card_w, card_h); prims.push(DatabasePrim::Quad { rect: card_rect, @@ -199,26 +262,12 @@ pub(super) fn render_kanban_card( scrolls_x: true, }); } - let title_col_id = ctx - .data - .columns - .iter() - .find(|c| c.column_type == "title") - .map_or("title", |c| c.id.as_str()); let title_rect = FlowRect::new( card_rect.x + CARD_PAD - 2.0, - card_rect.y + 5.0, + card_rect.y + 4.0, (card_w - 2.0 * CARD_PAD + 4.0).max(1.0), - 24.0, + title_h, ); - let title_inner_x = card_rect.x + CARD_PAD; - let title_inner_w = (card_w - 2.0 * CARD_PAD).max(1.0); - let title_editing = ctx - .ui_state - .authoring - .active_cell - .as_ref() - .is_some_and(|e| e.row_id == row.row_id && e.column_id == title_col_id); if title_editing { prims.push(DatabasePrim::Quad { rect: title_rect, @@ -227,34 +276,20 @@ pub(super) fn render_kanban_card( radius: 4.0, dashed: false, }); - if let Some((prim, active)) = kanban_active_rich_cell( - ctx, - &row.row_id, - title_col_id, - &row.title, - TYPOGRAPHY.font_sm_px, - 20.0, - 500.0, - title_inner_x, - title_inner_w, - title_rect, - 24.0, - align, - ) { + if let Some(laid) = title_laid { + let (prim, active) = kanban_active_rich_cell_from_laid( + &row.row_id, + title_col_id, + laid, + title_inner_x, + title_inner_w, + title_rect, + 24.0, + ); prims.push(prim); *active_cell = Some(active); } - } else if let Some(laid) = layout_rich_cell_sized( - ctx, - &row.title, - TYPOGRAPHY.font_sm_px, - 20.0, - 500.0, - ctx.palette.text_primary, - title_inner_w, - false, - align, - ) { + } else if let Some(laid) = title_laid { prims.push(rich_cell_prim( laid, title_inner_x, @@ -290,11 +325,21 @@ pub(super) fn render_kanban_card( }); } - let mut py = card_rect.y + 30.0; - let inner_x = card_rect.x + CARD_PAD; - let inner_w = (card_w - 2.0 * CARD_PAD).max(1.0); + let mut py = card_rect.y + 30.0 + extra_title_h; for prop in prop_lines { - let prop_rect = FlowRect::new(inner_x, py, inner_w, 20.0); + let this_prop_h = match &prop { + KanbanProp::Text { + col_id, col_type, .. + } if col_type == "rich-text" + && active_rich_prop_laid + .as_ref() + .is_some_and(|(cid, _)| cid == col_id) => + { + 20.0 + extra_prop_h + } + _ => 20.0, + }; + let prop_rect = FlowRect::new(inner_x, py, inner_w, this_prop_h); match prop { KanbanProp::Pill { col_id, @@ -508,30 +553,19 @@ pub(super) fn render_kanban_card( ), ); } else if col_type == "rich-text" { - let empty_rt = blocksuite_playground_doc::read::RichText::default(); - let rt = match ctx.data.cells.get(&(row.row_id.clone(), col_id.clone())) + if let Some((_, laid)) = active_rich_prop_laid + .as_ref() + .filter(|(cid, _)| cid == &col_id) { - Some( - blocksuite_playground_doc::read::DatabaseCellValue::RichText( - rt, - ), - ) => rt, - _ => &empty_rt, - }; - if let Some((prim, active)) = kanban_active_rich_cell( - ctx, - &row.row_id, - &col_id, - rt, - TYPOGRAPHY.font_xs_px, - 18.0, - 400.0, - inner_x + 2.0, - (inner_w - 4.0).max(1.0), - prop_rect, - 18.0, - align, - ) { + let (prim, active) = kanban_active_rich_cell_from_laid( + &row.row_id, + &col_id, + laid.clone(), + inner_x + 2.0, + (inner_w - 4.0).max(1.0), + prop_rect, + 20.0, + ); prims.push(prim); *active_cell = Some(active); } @@ -577,7 +611,7 @@ pub(super) fn render_kanban_card( } } } - py += 22.0; + py += this_prop_h + 2.0; } if ctx.mobile_readonly { diff --git a/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs b/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs index c554cf423b..9a565cd25e 100644 --- a/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs +++ b/blocksuite/crates/playground/src/bin/bs_harness/database_authoring_evidence.rs @@ -504,7 +504,7 @@ pub(super) fn render_db_authoring_evidence(out_dir: &Path) -> Result<()> { row_id: "row-1".into(), column_id: "title".into(), col_type: "title".into(), - draft: "Ship Table & Kanban Authoring".into(), + draft: "Column Schema & Type Switcher".into(), error: None, select_filter: String::new(), }); @@ -577,7 +577,7 @@ pub(super) fn render_db_authoring_evidence(out_dir: &Path) -> Result<()> { row_id: "row-1".into(), column_id: "title".into(), col_type: "title".into(), - draft: "Ship Table & Kanban Authoring".into(), + draft: "Column Schema & Type Switcher".into(), error: None, select_filter: String::new(), }); diff --git a/blocksuite/crates/playground/src/database_authoring/geometry.rs b/blocksuite/crates/playground/src/database_authoring/geometry.rs index 5f89748860..f682da9a61 100644 --- a/blocksuite/crates/playground/src/database_authoring/geometry.rs +++ b/blocksuite/crates/playground/src/database_authoring/geometry.rs @@ -573,20 +573,53 @@ impl PlaygroundView { .authoring_mut(&block_id) .kanban_drag = None; if target_bucket_key != origin_bucket_key { + let is_multi_select = self + .snapshot + .as_ref() + .and_then(|s| s.block(&block_id)) + .and_then(|n| match &n.content { + blocksuite_playground_doc::read::BlockContent::Database(db) => { + db.columns.iter().find(|c| c.id == column_id) + } + _ => None, + }) + .is_some_and(|c| c.column_type == "multi-select"); let before_sv = self.page().and_then(|p| p.encode_state_vector_v1().ok()); - let spec = - target_seed.unwrap_or(blocksuite_playground_doc::schema::DatabaseCellSpec::Null); - let mutated = if let Ok(page) = self.page_mut() { - let _ = page.stop_capturing(); - let ok = page - .set_database_cell_value(&block_id, &row_id, &column_id, spec, now_ms) - .ok() - .flatten() - .is_some(); - let _ = page.stop_capturing(); - ok + let mutated = if is_multi_select { + let rem = (origin_bucket_key != "Ungroups").then_some(origin_bucket_key.as_str()); + let add = (target_bucket_key != "Ungroups").then_some(target_bucket_key.as_str()); + if let Ok(page) = self.page_mut() { + let _ = page.stop_capturing(); + let ok = page + .move_database_multi_select_group( + &block_id, &row_id, &column_id, rem, add, now_ms, + ) + .ok() + .flatten() + .is_some(); + let _ = page.stop_capturing(); + ok + } else { + false + } } else { - false + let spec_opt = if target_bucket_key == "Ungroups" { + Some(blocksuite_playground_doc::schema::DatabaseCellSpec::Null) + } else { + target_seed + }; + if let (Some(spec), Ok(page)) = (spec_opt, self.page_mut()) { + let _ = page.stop_capturing(); + let ok = page + .set_database_cell_value(&block_id, &row_id, &column_id, spec, now_ms) + .ok() + .flatten() + .is_some(); + let _ = page.stop_capturing(); + ok + } else { + false + } }; if mutated { self.sync_after_database_mutation(before_sv, cx); diff --git a/blocksuite/crates/playground/src/database_authoring/inline.rs b/blocksuite/crates/playground/src/database_authoring/inline.rs index ed50d13d96..14c161a9c3 100644 --- a/blocksuite/crates/playground/src/database_authoring/inline.rs +++ b/blocksuite/crates/playground/src/database_authoring/inline.rs @@ -139,6 +139,7 @@ pub(crate) struct DatabaseInlineSession { pub(crate) target: DatabaseInlineTarget, pub(crate) anchored: AnchoredInlineInput, pub(crate) dirty: bool, + pub(crate) last_edit_ms: u64, } impl PlaygroundView { @@ -347,10 +348,12 @@ impl PlaygroundView { .flatten() }); } + let opened_ms = (self.now_ms(cx) as u64).max(1); self.database_input = Some(DatabaseInlineSession { target, anchored, dirty: false, + last_edit_ms: opened_ms, }); true } @@ -382,9 +385,11 @@ impl PlaygroundView { cx: &mut Context<Self>, f: impl FnOnce(&mut AnchoredInlineInput) -> Option<TextSplice>, ) -> bool { + let edit_ms = (self.now_ms(cx) as u64).max(1); let Some(session) = self.database_input.as_mut() else { return false; }; + session.last_edit_ms = edit_ms; let splice = f(&mut session.anchored); let display = session.anchored.input.display_text(); let committed = session.anchored.input.text.clone(); @@ -502,9 +507,10 @@ impl PlaygroundView { /// Exit any active database inline editing target cleanly (called from /// `PlaygroundView::finish_inline_targets`). /// - /// - `CommitPreedit`: commits any in-flight IME preedit; commits dirty `ScalarCell` drafts - /// (writing 0 CRDT updates when `!dirty`); closes `active_cell` and popover fields. - /// - `DiscardPreedit`: cancels preedit and closes without writing any CRDT updates. + /// - `CommitPreedit`: commits any in-flight IME preedit (splicing `LiveRichCell` if present). + /// - `DiscardPreedit`: cancels any uncommitted IME preedit without splicing `LiveRichCell`. + /// - Both modes persist already-committed `ScalarCell` / `ColumnRename` draft text when dirty + /// and writable, then close `active_cell` and popover fields. pub(crate) fn finish_database_inline_session( &mut self, end: InlineTargetEnd, @@ -514,76 +520,25 @@ impl PlaygroundView { return false; }; let block_id = session.target.block_id().to_string(); - if end == InlineTargetEnd::DiscardPreedit { - session.anchored.input.cancel_preedit(); - if !self.is_database_write_readonly() { - let now_ms = cx.as_ref().map(|c| self.now_ms(c) as u64).unwrap_or(0); - let offset_at = self.utc_offset_resolver(); - match &session.target { - DatabaseInlineTarget::ScalarCell { - block_id, - row_id, - column_id, - col_type, - initial, - } => { - let final_text = session.anchored.input.text(); - if final_text != initial.as_str() - && let Ok(ParsedCellInput::Cell(spec)) = - parse_cell_draft(col_type, final_text, &offset_at) - { - let before_sv = - self.page().and_then(|p| p.encode_state_vector_v1().ok()); - let mutated = if let Ok(page) = self.page_mut() { - page.set_database_cell_value( - block_id, row_id, column_id, spec, now_ms, - ) - .ok() - .flatten() - .is_some() - } else { - false - }; - if mutated && let Some(cx_ref) = cx { - self.sync_after_database_mutation(before_sv, cx_ref); - } else if mutated { - self.refresh_document(); - } - } - } - DatabaseInlineTarget::ColumnRename { - block_id, - column_id, - initial, - } => { - let trimmed = session.anchored.input.text().trim(); - if !trimmed.is_empty() && trimmed != initial.as_str() { - let before_sv = - self.page().and_then(|p| p.encode_state_vector_v1().ok()); - let mutated = if let Ok(page) = self.page_mut() { - page.rename_database_column(block_id, column_id, trimmed, now_ms) - .ok() - .flatten() - .is_some() - } else { - false - }; - if mutated && let Some(cx_ref) = cx { - self.sync_after_database_mutation(before_sv, cx_ref); - } else if mutated { - self.refresh_document(); - } - } - } - _ => {} + let unmark_splice = match end { + InlineTargetEnd::DiscardPreedit => { + session.anchored.input.cancel_preedit(); + None + } + InlineTargetEnd::CommitPreedit => { + let s = session.anchored.input.unmark(); + if s.is_some() { + session.dirty = true; } + s } - } else if end == InlineTargetEnd::CommitPreedit { - let unmark_splice = session.anchored.input.unmark(); - if unmark_splice.is_some() { - session.dirty = true; - } - let now_ms = cx.as_ref().map(|c| self.now_ms(c) as u64).unwrap_or(0); + }; + if !self.is_database_write_readonly() { + let now_ms = cx + .as_ref() + .map(|c| self.now_ms(c) as u64) + .unwrap_or(session.last_edit_ms) + .max(1); let offset_at = self.utc_offset_resolver(); match &session.target { DatabaseInlineTarget::LiveRichCell { @@ -660,10 +615,7 @@ impl PlaygroundView { initial, } => { let trimmed = session.anchored.input.text().trim(); - if !self.is_database_write_readonly() - && !trimmed.is_empty() - && trimmed != initial.as_str() - { + if !trimmed.is_empty() && trimmed != initial.as_str() { let before_sv = self.page().and_then(|p| p.encode_state_vector_v1().ok()); let mutated = if let Ok(page) = self.page_mut() { page.rename_database_column(block_id, column_id, trimmed, now_ms) @@ -680,7 +632,8 @@ impl PlaygroundView { } } } - _ => {} + DatabaseInlineTarget::SelectFilter { .. } + | DatabaseInlineTarget::FilterValue { .. } => {} } } self.flow diff --git a/blocksuite/crates/playground/src/database_authoring/keys.rs b/blocksuite/crates/playground/src/database_authoring/keys.rs index c9587e85ec..94019276d1 100644 --- a/blocksuite/crates/playground/src/database_authoring/keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/keys.rs @@ -138,6 +138,7 @@ impl PlaygroundView { &mut self.flow.database_state, block_id, &db_data, + &self.page_titles, key, &offset_at, now_ms, diff --git a/blocksuite/crates/playground/src/database_authoring/mod.rs b/blocksuite/crates/playground/src/database_authoring/mod.rs index defd6c1ca6..47a8d519e0 100644 --- a/blocksuite/crates/playground/src/database_authoring/mod.rs +++ b/blocksuite/crates/playground/src/database_authoring/mod.rs @@ -8,11 +8,11 @@ mod paint; #[cfg(test)] mod tests; #[cfg(test)] +mod tests_authoring_lifecycle; +#[cfg(test)] mod tests_inline_and_popovers; #[cfg(test)] -mod tests_r14; -#[cfg(test)] -mod tests_r14_lifecycle; +mod tests_kanban_and_richtext; pub(crate) use inline::DatabaseInlineSession; diff --git a/blocksuite/crates/playground/src/database_authoring/tests_r14_lifecycle.rs b/blocksuite/crates/playground/src/database_authoring/tests_authoring_lifecycle.rs similarity index 64% rename from blocksuite/crates/playground/src/database_authoring/tests_r14_lifecycle.rs rename to blocksuite/crates/playground/src/database_authoring/tests_authoring_lifecycle.rs index b941093641..e9b596f43b 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_r14_lifecycle.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_authoring_lifecycle.rs @@ -1,6 +1,6 @@ -//! R14 deep pre-merge regression suite (Part 2: Table `+ New record` 1-step Undo/Redo, -//! deleted `@reference` `"Deleted page"` + reference-title filtering, and `set_mode` / -//! outside-click `ColumnRename` / `set_document` lifecycle closures). +//! Regression suite for Table `+ New record` 1-step Undo/Redo, deleted `@reference` +//! resolution and reference-title filtering, `set_mode` / outside-click `ColumnRename` / +//! `set_document` lifecycle closures, and Kanban `multi-select` cross-lane card drag. use std::{cell::RefCell, rc::Rc}; @@ -25,11 +25,11 @@ use crate::{ use super::{ tests_inline_and_popovers::{open_authoring_window, seed_authoring_doc}, - tests_r14::{linked_page_attrs, undo_key_event}, + tests_kanban_and_richtext::{linked_page_attrs, undo_key_event}, }; #[test] -fn r14_p1_2_and_3_4_table_undo_deleted_ref_filter_and_lifecycle_closures() { +fn table_undo_deleted_ref_filter_and_lifecycle_closures() { let (mut state, db_id) = seed_authoring_doc(false); state .workspace @@ -378,3 +378,182 @@ fn r14_p1_2_and_3_4_table_undo_deleted_ref_filter_and_lifecycle_closures() { "set_document must cancel IME preedit '99' while preserving committed scalar '2500'" ); } + +#[test] +fn kanban_multi_select_card_drag_preserves_unrelated_tags_and_undoes_in_one_step() { + use blocksuite_playground_doc::read::DatabaseGroupBy; + use ui::{MouseMoveEvent, MouseUpEvent}; + + for (target, expected_after) in [ + ("opt-done", vec!["opt-x", "opt-done"]), + ("Ungroups", vec!["opt-x"]), + ] { + let (mut state, db_id) = seed_authoring_doc(false); + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.change_database_column_type(&db_id, "col-status", "multi-select", 20) + .unwrap(); + page.upsert_database_select_option_and_add_multi( + &db_id, + "col-status", + "opt-x", + "Extra", + "var(--affine-tag-red)", + "row-1", + 21, + ) + .unwrap(); + page.set_database_view_group_by( + &db_id, + "v-kanban", + Some(DatabaseGroupBy { + kind: "groupBy".into(), + column_id: "col-status".into(), + name: "multi-select".into(), + sort: None, + hide_empty: None, + }), + 25, + ) + .unwrap(); + let _ = page.stop_capturing(); + } + let (platform, app, win, headless) = open_authoring_window( + 1280, + 760, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + state, + ); + let tick = || { + platform.run_until_parked(); + headless.request_frame(); + platform.run_until_parked(); + }; + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.set_database_active_view(&db_id, "v-kanban", cx) + }) + .unwrap(); + }); + tick(); + + let (from, to) = app.update(|cx| { + win.update(cx, |v, w, _| { + let layout = v.flow_layout().unwrap(); + let b = layout.block(&db_id).unwrap().rect(); + let gx = v + .current_page_geometry(f32::from(w.viewport_size().width)) + .column_x; + let hits = v.flow.database_authoring_hits(&db_id); + let card = hits + .iter() + .find(|h| { + matches!( + &h.kind, + DatabaseAuthoringHitKind::KanbanCardDragRegion { + row_id, + origin_bucket_key, + .. + } if row_id == "row-1" && origin_bucket_key == "opt-todo" + ) + }) + .expect("row-1 card in opt-todo lane"); + let lane = hits + .iter() + .find(|h| { + matches!( + &h.kind, + DatabaseAuthoringHitKind::KanbanLaneDropTarget { bucket_key, .. } + if bucket_key == target + ) + }) + .expect("target lane"); + ( + point( + px(gx + b.x + card.rect.x + 30.0), + px(crate::TOPBAR_HEIGHT - v.scroll_y + b.y + card.rect.y + 14.0), + ), + point( + px(gx + b.x + lane.rect.x + 80.0), + px(crate::TOPBAR_HEIGHT - v.scroll_y + b.y + lane.rect.y + 60.0), + ), + ) + }) + .unwrap() + }); + + app.update(|cx| { + win.update(cx, |v, w, cx| { + v.page_mouse_down( + &MouseDownEvent { + position: from, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }, + w, + cx, + ); + v.root_mouse_move( + &MouseMoveEvent { + position: to, + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }, + w, + cx, + ); + v.root_mouse_up( + &MouseUpEvent { + position: to, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }, + w, + cx, + ); + }) + .unwrap(); + }); + tick(); + + let after_drag: Vec<String> = app.update(|cx| { + win.update(cx, |v, _, _| { + let BlockContent::Database(db) = + &v.snapshot.as_ref().unwrap().block(&db_id).unwrap().content + else { + panic!("expected db"); + }; + db.cells[&("row-1".into(), "col-status".into())].as_string_list() + }) + .unwrap() + }); + assert_eq!(after_drag, expected_after, "target={target}"); + + app.update(|cx| { + win.update(cx, |v, w, cx| { + v.editor_key_down(&undo_key_event(false), w, cx) + }) + .unwrap(); + }); + tick(); + + let after_undo: Vec<String> = app.update(|cx| { + win.update(cx, |v, _, _| { + let BlockContent::Database(db) = + &v.snapshot.as_ref().unwrap().block(&db_id).unwrap().content + else { + panic!("expected db"); + }; + db.cells[&("row-1".into(), "col-status".into())].as_string_list() + }) + .unwrap() + }); + assert_eq!(after_undo, vec!["opt-todo", "opt-x"], "target={target}"); + } +} diff --git a/blocksuite/crates/playground/src/database_authoring/tests_r14.rs b/blocksuite/crates/playground/src/database_authoring/tests_kanban_and_richtext.rs similarity index 73% rename from blocksuite/crates/playground/src/database_authoring/tests_r14.rs rename to blocksuite/crates/playground/src/database_authoring/tests_kanban_and_richtext.rs index c6880b9bed..cbc53f7f58 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_r14.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_kanban_and_richtext.rs @@ -1,10 +1,10 @@ -//! R14 deep pre-merge regression suite (Part 1: Kanban live ink, `@reference` chip geometry, -//! Kanban non-select typed `seed_value`, and cross-lane card drag). +//! Regression suite for Kanban live rich-text property editing, `@reference` chip geometry, +//! Kanban non-select typed `seed_value`, and cross-lane card drag. use blocksuite_editor::database::DatabaseAuthoringHitKind; use blocksuite_playground_doc::{ read::{BlockContent, DatabaseGroupBy}, - schema::BlockSpec, + schema::{BlockSpec, DatabaseCellSpec}, }; use serde_json::json; use ui::{ @@ -53,7 +53,7 @@ pub(super) fn linked_page_attrs(page_id: &str) -> TextAttributes { } #[test] -fn r14_p0_2_kanban_rich_text_property_active_edit_paints_live_text_and_rich_hit() { +fn kanban_rich_text_property_active_edit_paints_live_text_and_rich_hit() { let (state, db_id) = seed_authoring_doc(false); let (platform, app, win, headless) = open_authoring_window( 1280, @@ -159,7 +159,7 @@ fn r14_p0_2_kanban_rich_text_property_active_edit_paints_live_text_and_rich_hit( if let Ok(dir) = std::env::var("AFFINE_DB_EVIDENCE_DIR") { let p = std::path::Path::new(&dir); let _ = std::fs::create_dir_all(p); - let _ = img.save(p.join("r14-after-kanban-richtext-edit.png")); + let _ = img.save(p.join("after-kanban-richtext-edit.png")); } let mut dark = 0_usize; for py in sy0..sy1 { @@ -185,7 +185,7 @@ fn r14_p0_2_kanban_rich_text_property_active_edit_paints_live_text_and_rich_hit( } #[test] -fn r14_p0_3_table_rich_cell_with_reference_chip_aligns_caret_and_hit_test() { +fn table_rich_cell_with_reference_chip_aligns_caret_and_hit_test() { let (mut state, db_id) = seed_authoring_doc(false); state .workspace @@ -316,7 +316,7 @@ fn r14_p0_3_table_rich_cell_with_reference_chip_aligns_caret_and_hit_test() { { let p = std::path::Path::new(&dir); let _ = std::fs::create_dir_all(p); - let _ = img.save(p.join("r14-after-table-ref-caret.png")); + let _ = img.save(p.join("after-table-ref-caret.png")); } (mid_idx, f32::from(bounds.origin.x)) }) @@ -334,7 +334,7 @@ fn r14_p0_3_table_rich_cell_with_reference_chip_aligns_caret_and_hit_test() { } #[test] -fn r14_p1_1_kanban_nonselect_seed_and_cross_lane_drag_work_in_single_undo_step() { +fn kanban_nonselect_seed_and_cross_lane_drag_work_in_single_undo_step() { let (mut state, db_id) = seed_authoring_doc(false); { let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); @@ -605,3 +605,172 @@ fn r14_p1_1_kanban_nonselect_seed_and_cross_lane_drag_work_in_single_undo_step() }); assert_eq!(status_after_drag, "opt-done"); } + +#[test] +fn kanban_long_card_title_wraps_in_box_and_places_end_caret_on_second_line() { + let (mut state, db_id) = seed_authoring_doc(false); + { + let page = state.workspace.page_mut(HOME_PAGE_ID).unwrap(); + page.set_database_row_title(&db_id, "row-1", "Column Schema & Type Switcher", 18) + .unwrap(); + page.add_database_row_with_cells( + &db_id, + "row-short", + "Short Task", + vec![ + ( + "col-status".into(), + DatabaseCellSpec::Text("opt-todo".into()), + ), + ("col-budget".into(), DatabaseCellSpec::Number(1200.0)), + ], + 19, + ) + .unwrap(); + let _ = page.stop_capturing(); + } + let (platform, app, win, headless) = open_authoring_window( + 1280, + 760, + PlaygroundOptions { + theme: PlaygroundTheme::Light, + ..Default::default() + }, + state, + ); + let tick = || { + platform.run_until_parked(); + headless.request_frame(); + platform.run_until_parked(); + }; + app.update(|cx| { + win.update(cx, |v, _, cx| { + v.set_database_active_view(&db_id, "v-kanban", cx); + }) + .unwrap(); + }); + tick(); + + let (display_title_rect, long_card_h, short_card_h, title_click) = app.update(|cx| { + win.update(cx, |v, w, _| { + let layout = v.flow_layout().unwrap(); + let block = layout.block(&db_id).unwrap(); + let geom = v.current_page_geometry(f32::from(w.viewport_size().width)); + let hits = v.flow.database_authoring_hits(&db_id); + let title_hit = hits + .iter() + .find(|h| { + matches!( + &h.kind, + DatabaseAuthoringHitKind::EditCell { row_id, col_type, .. } + if row_id == "row-1" && col_type == "title" + ) + }) + .expect("long card title hit"); + let long_card = hits + .iter() + .find(|h| { + matches!( + &h.kind, + DatabaseAuthoringHitKind::KanbanCardDragRegion { row_id, .. } + if row_id == "row-1" + ) + }) + .expect("long card drag region"); + let short_card = hits + .iter() + .find(|h| { + matches!( + &h.kind, + DatabaseAuthoringHitKind::KanbanCardDragRegion { row_id, .. } + if row_id == "row-short" + ) + }) + .expect("short card drag region"); + ( + title_hit.rect, + long_card.rect.h, + short_card.rect.h, + point( + px(geom.column_x + block.rect().x + title_hit.rect.x + 12.0), + px(crate::TOPBAR_HEIGHT - v.scroll_y + block.rect().y + title_hit.rect.y + 8.0), + ), + ) + }) + .unwrap() + }); + assert!( + display_title_rect.h >= 44.0, + "two-line Kanban card title box must grow to fit wrapped lines: {display_title_rect:?}" + ); + assert!( + long_card_h > short_card_h, + "wrapped Kanban card must grow taller than single-line card ({long_card_h} vs {short_card_h})" + ); + + // Click the long card title to enter live editing with caret at end-of-title ("Switcher"). + app.update(|cx| { + win.update(cx, |v, w, cx| { + v.page_mouse_down( + &MouseDownEvent { + position: title_click, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }, + w, + cx, + ); + v.root_mouse_up( + &MouseUpEvent { + position: title_click, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }, + w, + cx, + ); + let end = "Column Schema & Type Switcher".encode_utf16().count(); + v.set_selected_text_range(end..end, w, cx); + }) + .unwrap(); + }); + tick(); + + app.update(|cx| { + win.update(cx, |v, w, _| { + let layout = v.flow_layout().unwrap(); + let block = layout.block(&db_id).unwrap(); + let (active_rect, _) = v + .flow + .database_active_cell_rect(&db_id) + .expect("active Kanban title rect"); + assert_eq!( + active_rect.h, display_title_rect.h, + "display and edit modes must share identical multi-line title height" + ); + let rich_hit = v.flow.database_active_cell_rich(&db_id).expect("rich_hit"); + let end_u16 = "Column Schema & Type Switcher".encode_utf16().count(); + let (_cx_off, caret_line) = rich_hit.text.caret(end_u16); + assert_eq!( + caret_line, 1, + "end of 'Column Schema & Type Switcher' must sit on wrapped line 1 (second line)" + ); + let ime_bounds = v + .database_authoring_input_bounds(end_u16..end_u16, w) + .expect("IME bounds at end of wrapped Kanban title"); + let title_screen_top = + crate::TOPBAR_HEIGHT - v.scroll_y + block.rect().y + active_rect.y; + let title_screen_bottom = title_screen_top + active_rect.h; + let caret_top = f32::from(ime_bounds.origin.y); + let caret_bottom = caret_top + f32::from(ime_bounds.size.height); + assert!( + caret_top >= title_screen_top + 20.0 && caret_bottom <= title_screen_bottom, + "second-line caret [{caret_top}..{caret_bottom}] must lie on line 2 inside title_rect [{title_screen_top}..{title_screen_bottom}] without vertical clamping" + ); + }) + .unwrap(); + }); +}