diff --git a/packages/common/store/src/workspace_db/tables.rs b/packages/common/store/src/workspace_db/tables.rs index f5b9032043..13e0979b3a 100644 --- a/packages/common/store/src/workspace_db/tables.rs +++ b/packages/common/store/src/workspace_db/tables.rs @@ -527,6 +527,28 @@ impl YjsTableDoc { Ok(Some(serde_json::from_value(json)?)) } + /// Read a boolean field of a live row. + pub fn get_row_bool(&self, primary_key: &str, field: &str) -> Option { + if field == DELETED_FLAG_KEY { + return None; + } + let map = self.doc.get_map(primary_key).ok()?; + self.doc + .transact(|tx| { + let row = tx.map(&map).ok()?; + if matches!(row.get(DELETED_FLAG_KEY), Some(Value::Any(Any::True))) { + return None; + } + match row.get(field) { + Some(Value::Any(Any::True)) => Some(true), + Some(Value::Any(Any::False)) => Some(false), + _ => None, + } + }) + .ok() + .flatten() + } + /// Read raw JSON fields of a non-deleted row (including unknown extension keys). pub fn get_raw_row(&self, primary_key: &str) -> Option { let map = self.doc.get_map(primary_key).ok()?; @@ -691,6 +713,35 @@ mod tests { use super::*; + #[test] + fn get_row_bool_reads_only_booleans_from_live_rows() { + let name = WorkspaceDbTableName::DocProperties; + let mut table = YjsTableDoc::new( + name.local_doc_id(), + name.primary_key_field(), + name.known_fields(), + 1, + ); + assert_eq!(table.get_row_bool("doc", "isTemplate"), None); + for (value, expected) in [ + (json!(true), Some(true)), + (json!(false), Some(false)), + (json!("true"), None), + (JsonValue::Null, None), + ] { + table + .upsert_row(&json!({"id": "doc", "isTemplate": value})) + .unwrap(); + assert_eq!(table.get_row_bool("doc", "isTemplate"), expected); + assert_eq!(table.get_row_bool("doc", "absent"), None); + } + table + .upsert_row(&json!({"id": "doc", "isTemplate": true})) + .unwrap(); + table.soft_delete("doc").unwrap(); + assert_eq!(table.get_row_bool("doc", "isTemplate"), None); + } + #[test] fn all_eight_tables_support_typed_upsert_soft_delete_reinsert_and_zero_writeback() { let mut folders = YjsTableDoc::new( diff --git a/packages/frontend/Cargo.lock b/packages/frontend/Cargo.lock index c447177b50..a5e7a94b03 100644 --- a/packages/frontend/Cargo.lock +++ b/packages/frontend/Cargo.lock @@ -86,6 +86,7 @@ dependencies = [ "ui", "ui-kit", "ui-tokens", + "unicode-normalization", "wasm-bindgen", "y-octo", ] diff --git a/packages/frontend/desktop/Cargo.toml b/packages/frontend/desktop/Cargo.toml index 796766f9b3..d3f2955794 100644 --- a/packages/frontend/desktop/Cargo.toml +++ b/packages/frontend/desktop/Cargo.toml @@ -31,6 +31,7 @@ sha2.workspace = true ui = { path = "../../ui/ui" } ui-kit = { path = "../../ui/kit" } ui-tokens = { path = "../../ui/tokens" } +unicode-normalization.workspace = true y-octo.workspace = true [target.'cfg(not(target_family = "wasm"))'.dependencies] diff --git a/packages/frontend/desktop/src/doc_store/database_backlinks.rs b/packages/frontend/desktop/src/doc_store/database_backlinks.rs index 2f4d963505..2b46a95b33 100644 --- a/packages/frontend/desktop/src/doc_store/database_backlinks.rs +++ b/packages/frontend/desktop/src/doc_store/database_backlinks.rs @@ -7,21 +7,23 @@ //! for them, once per revision of the row's document. use std::{ + borrow::Cow, cell::Cell, collections::{BTreeMap, BTreeSet}, ops::Deref, rc::Rc, + slice, sync::{TryLockError, Weak}, }; use affine_store::workspace_db::{WorkspaceDb, WorkspaceDbTableName}; use blocksuite_editor::database::TAG_COLOR_PALETTE; use blocksuite_playground_doc::{ - read::{BlockContent, DatabaseCellValue, DatabaseColumn, DatabaseData}, + read::{BlockContent, BlockNode, DatabaseCellValue, DatabaseColumn, DatabaseData}, schema::DatabaseCellSpec, try_random_client_id, }; -use serde::Deserialize; +use unicode_normalization::{UnicodeNormalization, is_nfc}; use super::{DesktopDocStore, navigation::resolve_tag_color}; @@ -38,7 +40,7 @@ pub(crate) const DATABASE_BACKLINK_CELL_TYPES: [&str; 8] = [ ]; /// Search limit of `0.27.5` `DocsSearchService::watchDatabasesTo`. -const DATABASE_BACKLINK_LIMIT: usize = 100; +const MAX_DATABASE_BACKLINK_CANDIDATES: usize = 100; /// One row of an `affine:database` block in another document that links to a document. #[derive(Clone, Debug, PartialEq)] @@ -136,15 +138,7 @@ struct Built { rows: Rc<[DatabaseBacklink]>, } -#[derive(Deserialize)] -struct TemplateFlag { - #[serde(rename = "isTemplate")] - is_template: Option, -} - -/// A sort key that orders names as `String.prototype.localeCompare` does for Latin text in -/// the default locale: first by letters without accents or case, then by accents, then with -/// lowercase before uppercase. +/// A sort key for Latin names. It compares base letters, accents, and case in that order. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct NameKey { base: String, @@ -154,6 +148,11 @@ struct NameKey { impl NameKey { fn new(name: &str) -> Self { + let name = if is_nfc(name) { + Cow::Borrowed(name) + } else { + Cow::Owned(name.nfc().collect::()) + }; let accents = name.to_lowercase(); let mut base = String::with_capacity(accents.len()); for c in accents.chars() { @@ -206,9 +205,8 @@ fn push_base_letters(out: &mut String, c: char) { fn is_template(db: &WorkspaceDb, doc_id: &str) -> bool { db.db_table(WorkspaceDbTableName::DocProperties) - .and_then(|table| table.get_row::(doc_id).ok().flatten()) - .and_then(|flag| flag.is_template) - == Some(true) + .and_then(|table| table.get_row_bool(doc_id, "isTemplate")) + .unwrap_or(false) } fn template_revision(db: &WorkspaceDb) -> Option { @@ -242,8 +240,8 @@ impl DesktopDocStore { /// Rows of `affine:database` blocks in other documents that link to `doc_id`, as `0.27.5` `DocDatabaseBacklinksService` finds them: a row block whose own /// text or embed references the document, with or without a `?` or `#` part after the - /// document ID. Trashed and template documents and rows without a shown column are left - /// out, and at most the first 100 rows by database name are kept. + /// document ID. The search keeps up to 100 candidates before it removes self-references + /// and templates and sorts by database name. /// /// The flag is `false` while another thread holds the document properties of the /// connected session. The rows are then the previous rows of `doc_id` in `cache`, or, @@ -297,13 +295,7 @@ impl DesktopDocStore { .filter(|row| !flags.contains(&row.doc_id)) .map(|row| (NameKey::new(&row.database_name), row)) .collect(); - rows.sort_by(|(a_key, a), (b_key, b)| { - a_key - .cmp(b_key) - .then_with(|| a.doc_id.cmp(&b.doc_id)) - .then_with(|| a.row_id.cmp(&b.row_id)) - }); - rows.truncate(DATABASE_BACKLINK_LIMIT); + rows.sort_by(|(a_key, _), (b_key, _)| a_key.cmp(b_key)); let rows: Rc<[DatabaseBacklink]> = rows.into_iter().map(|(_, row)| row).collect(); let keys: BTreeSet<&str> = rows.iter().map(|row| row.key.as_str()).collect(); cache.cells.retain(|key, _| keys.contains(key.as_str())); @@ -369,54 +361,76 @@ impl DesktopDocStore { cells } - /// The linked rows of `target` before the template filter, the sort, and the limit, and - /// the documents that link to `target` with their revisions. + /// Collect candidates in document ID and block tree order. Keep source revisions for the + /// cache even when a candidate has no shown columns. fn collect_database_backlinks( &self, target: &str, ) -> (Vec, Vec<(String, u64)>) { let mut found = Vec::new(); let mut sources = Vec::new(); + let mut candidates = 0; for entry in self.docs.values() { - if entry.meta.trashed || entry.meta.id == target { + if entry.meta.trashed { continue; } - let rows: BTreeSet<&str> = self + let roots = entry.snapshot.root.iter().chain(&entry.snapshot.detached); + if entry.meta.id == target { + // The link graph omits links to the same document. Track the snapshot + // revision even when the document has no self-references. + sources.push((entry.meta.id.clone(), entry.revision)); + candidates += blocks_with_parents(roots) + .filter(|(row, parent)| { + parent.is_some_and(|node| matches!(node.content, BlockContent::Database(_))) + && is_self_referencing_row(row, target) + }) + .take(MAX_DATABASE_BACKLINK_CANDIDATES - candidates) + .count(); + if candidates == MAX_DATABASE_BACKLINK_CANDIDATES { + return (found, sources); + } + continue; + } + // The link graph keeps the order in which the snapshot traversal found the edges. + let mut links = self .link_graph .outbound_edges(&entry.meta.id) .iter() .filter(|edge| edge.target_doc_id.split(['?', '#']).next() == Some(target)) .map(|edge| edge.source_block_id.as_str()) - .collect(); - if rows.is_empty() { + .peekable(); + if links.peek().is_none() { continue; } sources.push((entry.meta.id.clone(), entry.revision)); - let nodes = entry.snapshot.root.iter().chain(&entry.snapshot.detached); - for node in nodes.flat_map(|root| root.walk()) { - let BlockContent::Database(data) = &node.content else { - continue; + for (row, parent) in blocks_with_parents(roots) { + let Some(linked_id) = links.peek() else { + break; }; - let shown = data.columns.iter().any(|column| { - DATABASE_BACKLINK_CELL_TYPES.contains(&column.column_type.as_str()) - }); - if !shown { + if *linked_id != row.id.as_str() { continue; } - for row in node - .children - .iter() - .filter(|row| rows.contains(row.id.as_str())) + if let Some(database) = parent + && let BlockContent::Database(data) = &database.content { - found.push(DatabaseBacklink { - doc_id: entry.meta.id.clone(), - doc_title: entry.meta.title.clone(), - database_id: node.id.clone(), - database_name: data.title.plain.clone(), - row_id: row.id.clone(), - key: format!("{}/{}/{}", entry.meta.id, node.id, row.id), - }); + candidates += 1; + if data.columns.iter().any(|column| { + DATABASE_BACKLINK_CELL_TYPES.contains(&column.column_type.as_str()) + }) { + found.push(DatabaseBacklink { + doc_id: entry.meta.id.clone(), + doc_title: entry.meta.title.clone(), + database_id: database.id.clone(), + database_name: data.title.plain.clone(), + row_id: row.id.clone(), + key: format!("{}/{}/{}", entry.meta.id, database.id, row.id), + }); + } + if candidates == MAX_DATABASE_BACKLINK_CANDIDATES { + return (found, sources); + } } + while links.next_if_eq(&row.id.as_str()).is_some() {} } } (found, sources) @@ -545,6 +559,48 @@ impl DesktopDocStore { } } +/// Check the row text and document embeds that the Web block index reads. +fn is_self_referencing_row(row: &BlockNode, target: &str) -> bool { + let matches_target = |id: &str| id.trim().split(['?', '#']).next() == Some(target); + match &row.content { + BlockContent::EmbedLinkedDoc { page_id, .. } + | BlockContent::EmbedSyncedDoc { page_id, .. } => matches_target(page_id), + BlockContent::Paragraph { .. } | BlockContent::List { .. } | BlockContent::Code { .. } => { + row.props + .get("prop:text") + .and_then(serde_json::Value::as_array) + .is_some_and(|ops| { + ops.iter().any(|op| { + op.pointer("/attributes/reference/pageId") + .and_then(serde_json::Value::as_str) + .is_some_and(matches_target) + }) + }) + } + _ => false, + } +} + +/// Walk blocks in depth-first order with their parents and retain one iterator per level. +fn blocks_with_parents<'a>( + mut roots: impl Iterator, +) -> impl Iterator)> { + let mut stack: Vec<(&BlockNode, slice::Iter<'_, BlockNode>)> = Vec::new(); + std::iter::from_fn(move || { + while let Some((parent, children)) = stack.last_mut() { + if let Some(child) = children.next() { + let parent = *parent; + stack.push((child, child.children.iter())); + return Some((child, Some(parent))); + } + stack.pop(); + } + let root = roots.next()?; + stack.push((root, root.children.iter())); + Some((root, None)) + }) +} + fn column_of<'a>(data: &'a DatabaseData, column_id: &str) -> Option<&'a DatabaseColumn> { data.columns.iter().find(|column| column.id == column_id) } @@ -567,3 +623,13 @@ fn utf16_splice(old: &str, new: &str) -> (u64, u64, String) { new[prefix..new.len() - suffix].iter().collect(), ) } + +#[cfg(test)] +mod tests { + use super::NameKey; + + #[test] + fn canonically_equivalent_names_have_equal_keys() { + assert_eq!(NameKey::new("Å"), NameKey::new("A\u{030a}")); + } +} diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/properties/database_backlinks/mod.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/properties/database_backlinks/mod.rs index e7c8fd0dac..aced6285e3 100644 --- a/packages/frontend/desktop/src/views_extra/right_sidebar/properties/database_backlinks/mod.rs +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/properties/database_backlinks/mod.rs @@ -193,8 +193,7 @@ impl Panel<'_> { .border_color(ui::transparent_black()) .cursor_pointer() .focus_visible(move |style| style.border_color(palette.text_primary)) - // `0.27.5` shows `DatabaseTableViewIcon` here, which `ui_tokens` does not carry. - .child(icon(icons::SQUARE, palette.text_primary)) + .child(icon(icons::DATABASE_TABLE_VIEW, palette.text_primary)) .child( div() .flex() diff --git a/packages/frontend/desktop/src/views_extra/tests/database_backlinks.rs b/packages/frontend/desktop/src/views_extra/tests/database_backlinks.rs index 4a3fe9f2fd..5620108d8f 100644 --- a/packages/frontend/desktop/src/views_extra/tests/database_backlinks.rs +++ b/packages/frontend/desktop/src/views_extra/tests/database_backlinks.rs @@ -272,10 +272,10 @@ fn database_backlinks_match_references_with_a_query_or_fragment_after_the_docume } #[test] -fn database_backlinks_sort_before_the_limit_and_skip_templates_and_rows_without_columns() { +fn database_backlinks_limit_candidates_before_sorting_and_filtering_templates() { let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); let store = &mut state.store; - let many: Vec = (0..100).map(|i| format!("zeta-{i:03}")).collect(); + let many: Vec = (0..99).map(|i| format!("zeta-{i:03}")).collect(); add_database_rows( store, PARENT, @@ -297,20 +297,17 @@ fn database_backlinks_sort_before_the_limit_and_skip_templates_and_rows_without_ add_database_rows( store, "doc-journal-today", - "db-bare", - "Bare", - vec![ - column("col-title", "title", "Title", json!({})), - column("col-cover", "image", "Cover", json!({})), - ], + "db-beta", + "Beta", + roadmap_columns(), BTreeMap::new(), - (TARGET, &["bare-0".into()]), + (TARGET, &["beta-0".into()]), ); let rows = store.database_backlinks(TARGET); assert_eq!(rows.len(), 100); assert_eq!(rows[0].database_name, "Alpha"); assert_eq!(rows[1].row_id, "zeta-000"); - assert!(rows.iter().all(|row| row.database_name != "Bare")); + assert_eq!(rows.last().map(|row| row.row_id.as_str()), Some("zeta-098")); let db = store.directory.db_mut(); let template = [("isTemplate", Some(json!(true)))]; @@ -326,10 +323,37 @@ fn database_backlinks_sort_before_the_limit_and_skip_templates_and_rows_without_ .unwrap(); } let rows = store.database_backlinks(TARGET); - assert_eq!(rows.len(), 100); + assert_eq!(rows.len(), 99); assert!(rows.iter().all(|row| row.database_name == "Zeta")); } +#[test] +fn database_backlinks_keep_discovery_order_for_equal_database_names() { + for names in [["Å", "A\u{030a}"], ["A\u{030a}", "Å"]] { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let store = &mut state.store; + for (id, name, doc, rows) in [ + ("db-z", names[0], PARENT, &["row-z", "row-y"][..]), + ("db-a", names[1], PARENT, &["row-b"][..]), + ("db-board", names[0], "doc-board", &["row-a"][..]), + ] { + let rows: Vec<_> = rows.iter().map(|row| (*row).to_owned()).collect(); + add_database_rows( + store, + doc, + id, + name, + roadmap_columns(), + BTreeMap::new(), + (TARGET, &rows), + ); + } + let rows = store.database_backlinks(TARGET); + let actual: Vec<_> = rows.iter().map(|row| row.row_id.as_str()).collect(); + assert_eq!(actual, ["row-z", "row-y", "row-b", "row-a"], "{names:?}"); + } +} + #[test] fn database_backlink_cell_edits_write_the_parent_document_in_one_undo_step() { let cases = [ diff --git a/packages/frontend/desktop/tests/database_backlinks_perf_parity.rs b/packages/frontend/desktop/tests/database_backlinks_perf_parity.rs index 3af44e47c2..6bd0b503bb 100644 --- a/packages/frontend/desktop/tests/database_backlinks_perf_parity.rs +++ b/packages/frontend/desktop/tests/database_backlinks_perf_parity.rs @@ -1,8 +1,10 @@ //! Database backlink rows in the inspector: the row cache and its rebuild triggers, the //! template read that never waits for a held session directory, the 100-row limit, the -//! `localeCompare` order, and the Web `0.27.5` name column and reference tab stop. +//! cold read allocations, the `localeCompare` order, and the Web `0.27.5` name column and reference tab stop. use std::{ + alloc::{GlobalAlloc, Layout, System}, + cell::Cell, collections::BTreeMap, sync::{Arc, Mutex}, }; @@ -57,10 +59,11 @@ fn shown_columns() -> Vec { fn remote_edit( store: &mut DesktopDocStore, doc: &str, + client_id: u64, edit: impl FnOnce(&mut PageDocSession, &str), ) -> Result<()> { let entry = store.docs.get_mut(doc).context("document")?; - let mut replica = PageDocSession::new(doc, 0x7e57)?; + let mut replica = PageDocSession::new(doc, client_id)?; replica.apply_remote_update_v1(&entry.session.encode_update_v1()?)?; edit(&mut replica, &entry.note_id.clone()); let diff = replica.encode_diff_v1(&entry.session.encode_state_vector_v1()?)?; @@ -68,17 +71,17 @@ fn remote_edit( Ok(()) } -/// Add a database named `title` to `doc` whose `rows` reference `TARGET`. +/// Add a database to `doc` whose rows reference `target`. fn add_database( store: &mut DesktopDocStore, doc: &str, (db, title): (&str, &str), columns: Vec, - rows: &[String], + (target, rows): (&str, &[String]), ) -> Result<()> { let mut reference = AHashMap::default(); reference.insert("type".to_owned(), Any::String("LinkedPage".into())); - reference.insert("pageId".to_owned(), Any::String(TARGET.into())); + reference.insert("pageId".to_owned(), Any::String(target.into())); let format = BTreeMap::from([("reference".to_owned(), Any::Object(Box::new(reference)))]); let cells = rows .iter() @@ -88,7 +91,7 @@ fn add_database( (row.clone(), values) }) .collect(); - remote_edit(store, doc, |replica, note| { + remote_edit(store, doc, 0x7e57, |replica, note| { let spec = DatabaseSpec { title: title.into(), columns, @@ -137,7 +140,7 @@ fn workspace(parents: usize, rows_each: usize) -> Result<(DesktopAppState, Vec (u64, u64) { } #[test] -fn database_backlink_rows_keep_the_first_100_after_the_template_filter() -> Result<()> { - // One database per parent; `Database 000` belongs to a template document. - for (candidates, kept, last) in [ - (100, 99, "Database 099"), - (101, 100, "Database 100"), - (102, 100, "Database 100"), - ] { +fn database_backlink_rows_limit_candidates_before_filtering_templates() -> Result<()> { + // One database per parent. Mark the first candidate in document ID order as a template. + for candidates in [100, 101, 102] { let (mut state, docs) = workspace(candidates, 1)?; - set_template(&mut state.store, &docs[0], true)?; + let mut ordered: Vec<_> = docs.iter().enumerate().collect(); + ordered.sort_by_key(|&(_, doc)| doc); + set_template(&mut state.store, ordered[0].1, true)?; + let mut expected: Vec<_> = ordered[1..100] + .iter() + .map(|(i, _)| format!("Database {i:03}")) + .collect(); + expected.sort(); let rows = state.store.database_backlinks(TARGET); - assert_eq!(rows.len(), kept, "{candidates}"); - assert_eq!(rows[0].database_name, "Database 001", "{candidates}"); let names: Vec<_> = rows.iter().map(|row| row.database_name.as_str()).collect(); - assert_eq!(names.last(), Some(&last), "{candidates}"); + assert_eq!(names, expected, "{candidates}"); let cells: Vec<_> = rows[0].cells.iter().map(|(c, _)| c.name.as_str()).collect(); assert_eq!(cells, ["Done", "Estimate", "Notes"], "{candidates}"); } Ok(()) } +#[test] +fn database_backlink_rows_count_self_references_and_refresh_after_edits() -> Result<()> { + let target = "doc-arch"; + for (count, remaining) in [(99, 1), (100, 0)] { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let store = &mut state.store; + let external = ["row-first", "row-second"]; + add_database( + store, + "doc-board", + ("db-external", "External"), + shown_columns(), + (target, &external.map(str::to_owned)), + )?; + + let mut cache = Default::default(); + let mut assert_rows = |store: &DesktopDocStore, expected: &[&str]| { + let (rows, settled) = store.database_backlink_rows(target, &mut cache); + assert!(settled); + let ids: Vec<_> = rows.iter().map(|row| row.row_id.as_str()).collect(); + assert_eq!(ids, expected); + }; + + assert_rows(store, &external); + let self_rows: Vec<_> = (0..count) + .map(|index| format!("self-row-{index}")) + .collect(); + add_database( + store, + target, + ("db-self", "Self"), + shown_columns(), + (target, &self_rows), + )?; + assert_rows(store, &external[..remaining]); + let link_updates = store.derived_work().link_index_updates; + remote_edit(store, target, 0x7e58, |replica, note| { + replica.delete_block_subtree(note, "db-self", 200).unwrap(); + })?; + assert_eq!(store.derived_work().link_index_updates, link_updates); + assert_rows(store, &external); + } + Ok(()) +} + +thread_local! { + static COUNTING: Cell = const { Cell::new(false) }; + static BYTES: Cell = const { Cell::new(0) }; +} + +struct CountingAllocator; + +fn record(bytes: usize) { + if COUNTING.try_with(Cell::get).unwrap_or(false) { + let _ = BYTES.try_with(|total| total.set(total.get() + bytes as u64)); + } +} + +// SAFETY: Delegates directly to `System` while counting allocated bytes per thread in TLS. +unsafe impl GlobalAlloc for CountingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + record(layout.size()); + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + record(layout.size()); + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + record(new_size); + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static ALLOCATOR: CountingAllocator = CountingAllocator; + +fn allocated_bytes(run: impl FnOnce() -> T) -> (T, u64) { + BYTES.with(|total| total.set(0)); + COUNTING.with(|counting| counting.set(true)); + let output = run(); + COUNTING.with(|counting| counting.set(false)); + (output, BYTES.with(Cell::get)) +} + +#[test] +fn database_backlink_cold_reads_do_not_copy_unrelated_properties() -> Result<()> { + let (mut state, docs) = workspace(1, 1)?; + let store = &mut state.store; + let parent = &docs[0]; + let property = store + .create_custom_property(parent, "Notes", "text") + .context("create unrelated property")?; + assert!(store.set_custom_property_value(parent, &property, "short")); + let (small, small_bytes) = allocated_bytes(|| store.database_backlinks(TARGET)); + assert!(store.set_custom_property_value(parent, &property, &"x".repeat(1024 * 1024))); + let (large, large_bytes) = allocated_bytes(|| store.database_backlinks(TARGET)); + println!("Cold read: short property {small_bytes} B, 1 MiB property {large_bytes} B"); + assert_eq!(small.len(), 1); + assert_eq!(small, large); + assert!(large_bytes.abs_diff(small_bytes) < 4096); + Ok(()) +} + #[test] fn database_backlink_rows_and_cells_rebuild_only_when_their_sources_change() -> Result<()> { let (mut state, docs) = workspace(4, 2)?; @@ -203,7 +317,7 @@ fn database_backlink_rows_and_cells_rebuild_only_when_their_sources_change() -> } assert_eq!(builds(), built, "idle reads build nothing"); - remote_edit(&mut state.store, &unrelated, |replica, note| { + remote_edit(&mut state.store, &unrelated, 0x7e57, |replica, note| { let text = BlockSpec::Paragraph { paragraph_type: ParagraphType::Text, text: "Typing elsewhere".into(), @@ -350,7 +464,7 @@ fn database_backlink_rows_and_columns_follow_locale_compare_order() -> Result<() &doc, (&format!("db-{i}"), name), columns.clone(), - &row, + (TARGET, &row), )?; } let rows = state.store.database_backlinks(TARGET); @@ -449,10 +563,14 @@ impl Shell { #[test] fn database_backlink_panel_idle_frames_rebuild_nothing_and_tab_reaches_the_reference() -> Result<()> { - let (state, docs) = workspace(32, 4)?; + let (state, _) = workspace(32, 4)?; + let (rows, _) = state + .store + .database_backlink_rows(TARGET, &mut Default::default()); + let row = rows.first().context("first backlink row")?; + let parent = row.doc_id.clone(); + let header = format!("desktop.inspector.database.{}", row.key); let shell = Shell::new(state)?; - let key = format!("{}/db-000/row-000-0", docs[0]); - let header = format!("desktop.inspector.database.{key}"); shell.element(&header)?; let idle = builds(); for _ in 0..3 { @@ -502,6 +620,6 @@ fn database_backlink_panel_idle_frames_rebuild_nothing_and_tab_reaches_the_refer assert!(shell.element(&header)?.focused); shell.key("tab")?; shell.key("enter")?; - assert_eq!(shell.route()?, DesktopRoute::Doc(docs[0].clone())); + assert_eq!(shell.route()?, DesktopRoute::Doc(parent)); Ok(()) } diff --git a/packages/ui/tokens/extract-tokens.mjs b/packages/ui/tokens/extract-tokens.mjs index c10ca2682c..53fa055629 100644 --- a/packages/ui/tokens/extract-tokens.mjs +++ b/packages/ui/tokens/extract-tokens.mjs @@ -74,6 +74,7 @@ const CORE_ICONS = [ ['PLUS', 'PlusIcon'], ['MINUS', 'MinusIcon'], // Database column menu & record peek + ['DATABASE_TABLE_VIEW', 'DatabaseTableViewIcon'], ['CENTER_PEEK', 'CenterPeekIcon'], ['MOVE_LEFT', 'MoveLeftIcon'], ['ARROW_UP_BIG_TOP', 'ArrowUpBigTopIcon'], diff --git a/packages/ui/tokens/icons.rs b/packages/ui/tokens/icons.rs index 38806c2e14..03e6c3c1e8 100644 --- a/packages/ui/tokens/icons.rs +++ b/packages/ui/tokens/icons.rs @@ -308,6 +308,11 @@ pub const MINUS: IconDef = IconDef { svg: "", }; +pub const DATABASE_TABLE_VIEW: IconDef = IconDef { + name: "DatabaseTableViewIcon", + svg: "", +}; + pub const CENTER_PEEK: IconDef = IconDef { name: "CenterPeekIcon", svg: "", @@ -648,6 +653,7 @@ pub const ALL_ICONS: &[IconDef] = &[ CONNECTOR_ELBOW, CONNECTOR_STRAIGHT, COPY, + DATABASE_TABLE_VIEW, DATE_TIME, DELETE, DIAMOND,