diff --git a/packages/frontend/desktop/AGENTS.md b/packages/frontend/desktop/AGENTS.md index c0e7b883ab..27b77de024 100644 --- a/packages/frontend/desktop/AGENTS.md +++ b/packages/frontend/desktop/AGENTS.md @@ -5,7 +5,9 @@ ## Scope and architecture - `affine-desktop` owns the multi-pane `Workbench`, collapsible and resizable `AppSidebar` (workspace switcher, Quick Search, New Page/Edgeless, All Docs, Favorites, Journals, Folders/Collections/Tags tree, Trash, and Settings), multi-tab Split View with per-pane `Entity` synchronized incrementally via Yjs V1 state-vector diffs (`encode_diff_v1`) through `DesktopDocStore` and per-pane `NavHistory`, `Cmd/Ctrl+K` `QuickSearch`, centered `PeekView`, physically isolated `ComposerDraftStore` with SHA-256 content-addressed attachments and one-way idempotent importers, `wasm32` Web Desktop mount entry (`wasm_desktop_main`), and the `desktop-harness` offscreen verification CLI. -- Native read-only `.affine` / `.db` inspection opens via `SqliteDocStorage::open_read_only` (`sqlite_loader.rs`) with lazy per-document hydration and zero CRDT writeback; interactive mutations operate on in-memory `DesktopDocStore` sessions (the native host binds the active writable session and transport with `DesktopShellView::connect_workspace`). +- Native read-only `.affine` / `.db` inspection opens via `SqliteDocStorage::open_read_only` (`sqlite_loader.rs`) with lazy per-document hydration and zero CRDT writeback. The read worker reuses one read-only connection of the current backing and reopens it when the backing changes, the file is replaced, or the last backing handle is dropped. It holds no read transaction between requests. +- Interactive mutations operate on in-memory `DesktopDocStore` sessions until the native host binds the active writable session and transport with `DesktopShellView::connect_workspace`. From then on that `WorkspaceSession` is the single writer of the workspace (`doc_store/writer.rs`): shell commands (create, journal, rename, favorite, trash, restore, delete, folder placement) write to it first and the store projects the result. Editor and store document edits join one ordered queue, and every session write merges that queue first. +- `doc_store/views.rs` builds the ordered document lists, sidebar counts, sidebar folder tree, and Quick Search index at most once per metadata revision. The sidebar tree flattens into rows by expansion state and mounts only the rows that `ui_kit::VirtualList` places in the viewport and overscan. The workbench drives the connected session every second on the UI scheduler clock. SQLite runs on the host runtime. When the workbench switches workspaces or disconnects, it commits the bound session to its original SQLite store before it stops the timer. @@ -27,5 +29,6 @@ CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-desktop --target wasm3 CARGO_ENCODED_RUSTFLAGS="" cargo test --locked -p affine-desktop CARGO_ENCODED_RUSTFLAGS="" cargo run --locked -p affine-desktop --features harness --bin desktop-harness -- audit CARGO_ENCODED_RUSTFLAGS="" cargo run --locked -p affine-desktop --features harness --bin desktop-harness -- gallery --out evidence/desktop +CARGO_ENCODED_RUSTFLAGS="" cargo run --locked -p affine-desktop --features harness --bin desktop-harness -- scale ./scripts/check-invariants.sh ``` diff --git a/packages/frontend/desktop/src/bin/desktop_harness/main.rs b/packages/frontend/desktop/src/bin/desktop_harness/main.rs index 9520849421..9503a04b39 100644 --- a/packages/frontend/desktop/src/bin/desktop_harness/main.rs +++ b/packages/frontend/desktop/src/bin/desktop_harness/main.rs @@ -6,6 +6,10 @@ //! - `stress-sqlite --db `: opens a real `.affine` SQLite workspace in place, asserts //! zero writeback (byte-identical SHA-256), renders AppSidebar + SplitView + QuickSearch, //! and prints strictly sanitized aggregate metrics. +//! - `scale`: renders `10 / 100 / 1,000` document workspaces at `1280×720` and asserts +//! deterministic work counts: mounted sidebar rows stay within the viewport and overscan, +//! warm frames rebuild no derived view, row index, or search index, and cold reads of +//! every document from one SQLite file open one read connection. use std::{cell::RefCell, path::PathBuf, rc::Rc}; @@ -13,6 +17,7 @@ use affine_desktop::{ ContentHash, DesktopAppState, DesktopDocStore, DesktopRoute, DesktopShellView, DocInspectorTab, register_desktop_fonts, }; +use affine_store::directory::DocMode; use anyhow::{Context as _, Result, bail}; use serde_json::json; use ui::{ @@ -186,11 +191,12 @@ fn setup_states() -> Vec<(&'static str, Box)> { ( "readonly-sqlite", Box::new(|s| { - s.store.sqlite_backing = Some(affine_desktop::sqlite_loader::SqliteLazyBacking { - path: PathBuf::from("readonly-preview.affine"), - space_id: "ws-readonly-preview".to_string(), - blob_count: 0, - }); + s.store.sqlite_backing = + Some(affine_desktop::sqlite_loader::SqliteLazyBacking::new( + PathBuf::from("readonly-preview.affine"), + "ws-readonly-preview".to_string(), + 0, + )); s.inspector_tab = Some(DocInspectorTab::Info); }), ), @@ -328,13 +334,206 @@ fn run_stress_sqlite(db_path: PathBuf) -> Result<()> { Ok(()) } +/// Workspace sizes of the `scale` scenario. +const SCALE_DOC_COUNTS: [usize; 3] = [10, 100, 1_000]; +/// Tallest sidebar viewport plus overscan above and below, over the shortest row extent. +const SCALE_MAX_MOUNTED_ROWS: usize = ((720 - 229 + 2 * 240) / 28) + 2; + +fn scale_state(docs: usize) -> DesktopAppState { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-11-28"); + let folder = state.create_folder("Scale", None); + for i in 0..docs { + let id = state.store.create_doc( + format!("Scale Doc {i:04}"), + DocMode::Page, + None, + 1_764_400_000 + i as i64, + ); + state.store.move_doc_to_folder(&id, Some(&folder)); + if i % 10 == 0 { + state.store.toggle_favorite(&id); + } + } + state +} + +/// Write a SQLite workspace whose root lists `docs` pages that each have one stored update. +fn write_scale_sqlite(path: &std::path::Path, docs: usize) -> Result> { + use affine_store::{directory::CreateDocId, sqlite::SqliteDocStorage}; + use blocksuite_playground_doc::{client_id_from_seed, schema::BlockSpec}; + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + rt.block_on(async { + let storage = SqliteDocStorage::new(path.to_string_lossy().into_owned()); + storage.connect().await?; + let mut db = affine_store::workspace_db::WorkspaceDb::new( + "ws-scale", + "local-user", + client_id_from_seed(7), + ); + db.initialize_meta()?; + let mut dir = affine_store::directory::WorkspaceDirectory::new(db); + let mut ids = Vec::new(); + for i in 0..docs { + let id = format!("scale-{i:04}"); + dir.create_doc(affine_store::directory::CreateDocRequest { + id: CreateDocId::explicit(affine_store::directory::DocId::new(id.clone())?), + title: format!("Scale Doc {i:04}"), + mode: DocMode::Page, + now_ms: 1_764_400_000, + })?; + let mut page = blocksuite_playground_doc::session::PageDocSession::new( + &id, + client_id_from_seed(100 + i as u64), + )?; + page.add_block( + "root", + BlockSpec::Page { + title: format!("Scale Doc {i:04}"), + }, + None, + None, + 1, + )?; + storage + .push_update(&id, &page.encode_update_v1()?, 1_764_400_001) + .await?; + ids.push(id); + } + storage.set_space_id("ws-scale").await?; + storage + .push_update( + "ws-scale", + &dir.db().root().encode_update_v1()?, + 1_764_400_000, + ) + .await?; + storage.checkpoint().await?; + storage.close().await; + Ok::<_, anyhow::Error>(ids) + }) +} + +fn run_scale() -> Result<()> { + let mut report = Vec::new(); + for docs in SCALE_DOC_COUNTS { + let session = start_session(1280, 720, 1.0, scale_state(docs))?; + let read = |s: &DesktopSession| { + s.app.update(|cx| { + s.window_handle.update(cx, |view, _, _| { + let rows = view.sidebar_rows(); + ( + view.state().store.derived_work(), + rows.builds(), + rows.mounted_rows(), + rows.row_count(), + rows.max_scroll(), + ) + }) + }) + }; + session.frame()?; + let (cold, cold_rows, first_mounted, row_count, max_scroll) = read(&session)?; + session.frame()?; + let (warm, warm_rows, ..) = read(&session)?; + anyhow::ensure!( + warm == cold && warm_rows == cold_rows, + "{docs} docs: warm frame rebuilt derived state ({cold:?} -> {warm:?})" + ); + let mut max_mounted = first_mounted; + for step in 0..8 { + session.update_state(|s| s.sidebar.scroll_y = max_scroll * step as f32 / 7.0)?; + session.frame()?; + let (work, rows, mounted, ..) = read(&session)?; + anyhow::ensure!( + work == cold && rows == cold_rows, + "{docs} docs: sidebar scroll rebuilt derived state" + ); + max_mounted = max_mounted.max(mounted); + } + anyhow::ensure!( + max_mounted <= SCALE_MAX_MOUNTED_ROWS, + "{docs} docs: mounted {max_mounted} sidebar rows (limit {SCALE_MAX_MOUNTED_ROWS})" + ); + session.update_state(|s| { + s.open_quick_search(); + s.quick_search.set_query("Scale Doc 00"); + })?; + session.frame()?; + let (searched, ..) = read(&session)?; + session.frame()?; + let (search_warm, ..) = read(&session)?; + anyhow::ensure!( + search_warm == searched, + "{docs} docs: warm Quick Search frame rebuilt its index or results" + ); + let link_updates_before = search_warm.link_index_updates; + session.update_state(|s| { + s.quick_search.close(); + let target = s.create_folder("Moved", None); + let first = s.store.visible_docs()[0].id.clone(); + s.store.move_doc_to_folder(&first, Some(&target)); + })?; + let (moved, ..) = read(&session)?; + anyhow::ensure!( + moved.link_index_updates == link_updates_before, + "{docs} docs: a folder move reindexed links" + ); + + let db = std::env::temp_dir().join(format!( + "desktop-harness-scale-{}-{docs}.affine", + std::process::id() + )); + let _ = std::fs::remove_file(&db); + let ids = write_scale_sqlite(&db, docs)?; + let (mut store, _) = DesktopDocStore::open_sqlite_file(&db)?; + for id in &ids { + store + .ensure_doc_hydrated(id) + .map_err(|e| anyhow::anyhow!(e))?; + } + let opens = store + .sqlite_backing + .as_ref() + .map_or(0, |b| b.read_connection_opens()); + drop(store); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", db.display())); + } + anyhow::ensure!( + opens == 1, + "{docs} docs: cold reads opened {opens} read connections" + ); + report.push(json!({ + "docs": docs, + "sidebar_rows": row_count, + "max_mounted_rows": max_mounted, + "mounted_row_limit": SCALE_MAX_MOUNTED_ROWS, + "view_builds_first_frame": cold.view_builds, + "warm_view_builds": warm.view_builds - cold.view_builds, + "warm_row_index_builds": warm_rows - cold_rows, + "search_index_builds": searched.search_index_builds, + "warm_search_runs": search_warm.search_runs - searched.search_runs, + "move_link_index_updates": moved.link_index_updates - link_updates_before, + "cold_read_docs": ids.len(), + "cold_read_connection_opens": opens, + })); + } + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) +} + fn main() -> Result<()> { let mut args = std::env::args().skip(1); let Some(cmd) = args.next() else { - bail!("usage: desktop-harness | stress-sqlite --db >"); + bail!( + "usage: desktop-harness | stress-sqlite --db | scale>" + ); }; match cmd.as_str() { "audit" => run_audit(), + "scale" => run_scale(), "gallery" => { let mut out_dir = PathBuf::from("evidence/desktop"); while let Some(arg) = args.next() { diff --git a/packages/frontend/desktop/src/doc_store/hydration.rs b/packages/frontend/desktop/src/doc_store/hydration.rs new file mode 100644 index 0000000000..8f989f20a5 --- /dev/null +++ b/packages/frontend/desktop/src/doc_store/hydration.rs @@ -0,0 +1,122 @@ +//! SQLite lazy hydration and editor update intake for [`DesktopDocStore`]. + +use super::{ + DesktopDocStore, DocHydrationState, mutations::merge_into_replica, + populate_note_and_surface_ids, +}; +use blocksuite_playground_doc::read::BlockContent; + +impl DesktopDocStore { + /// Returns `true` when this store is backed by an opened read-only SQLite `.affine` file. + pub fn is_readonly_sqlite(&self) -> bool { + #[cfg(not(target_family = "wasm"))] + { + self.sqlite_backing.is_some() + } + #[cfg(target_family = "wasm")] + { + false + } + } + + /// Open a real `.affine` / `.db` SQLite workspace in place with lazy hydration. + #[cfg(not(target_family = "wasm"))] + pub fn open_sqlite_file( + path: impl AsRef, + ) -> anyhow::Result<(Self, crate::sqlite_loader::SqliteLoadStats)> { + crate::sqlite_loader::open_sqlite_workspace(path) + } + + /// Lazily hydrate one document's CRDT state from its SQLite backing store if not yet loaded. + /// + /// Distinguishes confirmed local documents from uncached remote documents: when SQLite has no + /// row for `doc_id`, marks the entry as [`DocHydrationState::DocumentLoading`] and returns + /// `Err` so callers never render an unhydrated remote document as an editable blank page. + pub fn ensure_doc_hydrated(&mut self, doc_id: &str) -> Result { + let Some(entry) = self.docs.get(doc_id) else { + return Ok(false); + }; + if entry.is_hydrated() { + return Ok(true); + } + #[cfg(not(target_family = "wasm"))] + if let Some(backing) = self.sqlite_backing.clone() { + let maybe_bytes = backing + .load_doc_update(doc_id) + .map_err(|e| format!("failed to read SQLite doc `{doc_id}`: {e}"))?; + let Some(entry) = self.docs.get_mut(doc_id) else { + return Ok(false); + }; + let Some(bytes) = maybe_bytes else { + entry.hydration = DocHydrationState::DocumentLoading; + return Err(format!( + "DocumentLoading: `{doc_id}` has no local SQLite data" + )); + }; + if !bytes.is_empty() && bytes.as_slice() != [0, 0] { + entry + .session + .apply_remote_update_v1(&bytes) + .map_err(|e| format!("failed to apply CRDT update for `{doc_id}`: {e}"))?; + super::mutations::adopt_client_if_required(&mut entry.session); + } + let snap = entry + .session + .read_page_snapshot() + .map_err(|e| format!("failed to read page snapshot for `{doc_id}`: {e}"))?; + populate_note_and_surface_ids(entry, &snap); + let summary_filled = entry.meta.summary.is_empty(); + if summary_filled { + entry.meta.summary = crate::sqlite_loader::extract_snapshot_summary(&snap); + } + entry.snapshot = snap; + entry.revision = entry.session.revision(); + entry.hydration = DocHydrationState::Hydrated; + if summary_filled { + self.touch_meta(); + } + return Ok(true); + } + if let Some(entry) = self.docs.get_mut(doc_id) { + entry.hydration = DocHydrationState::Hydrated; + return Ok(true); + } + Ok(false) + } + + /// Apply a Yjs V1 update originated by a mounted `Entity` into the shared doc + /// and queue it for the connected session. + pub fn apply_remote_doc_update(&mut self, doc_id: &str, update: &[u8]) -> bool { + if update.is_empty() { + return false; + } + let Some(entry) = self.docs.get_mut(doc_id) else { + return false; + }; + if !merge_into_replica(&mut entry.session, update) { + return false; + } + let mut title_changed = false; + if let Ok(snap) = entry.session.read_page_snapshot() { + populate_note_and_surface_ids(entry, &snap); + if let Some(root) = &snap.root + && let BlockContent::Page { title } = &root.content + && !title.plain.trim().is_empty() + && entry.meta.title != title.plain + { + entry.meta.title = title.plain.clone(); + title_changed = true; + } + entry.snapshot = snap; + } + entry.revision = entry.session.revision(); + entry.hydration = DocHydrationState::Hydrated; + self.enqueue_doc_update(doc_id, update.to_vec()); + if title_changed { + self.touch_meta(); + } else { + self.env_rev += 1; + } + true + } +} diff --git a/packages/frontend/desktop/src/doc_store/mod.rs b/packages/frontend/desktop/src/doc_store/mod.rs index fe3fa8cbae..1f2ad6318b 100644 --- a/packages/frontend/desktop/src/doc_store/mod.rs +++ b/packages/frontend/desktop/src/doc_store/mod.rs @@ -5,9 +5,10 @@ //! synchronize incrementally via Yjs V1 state-vector diffs (`encode_diff_v1`) through //! `DesktopEditorHost::sync_all`. -use std::collections::BTreeMap; +use std::{cell::RefCell, collections::BTreeMap}; use affine_client::{FolderForestCache, LinkGraph, WeightedSearchEngine, domain::CollectionRule}; + use affine_store::{ directory::{DocMode, WorkspaceDirectory}, workspace_db::{FolderRow, WorkspaceDb}, @@ -15,6 +16,10 @@ use affine_store::{ use blocksuite_playground_doc::{ read::PageSnapshot, session::PageDocSession, try_random_client_id, }; +pub(crate) use skeleton::{build_basic_doc_session, populate_note_and_surface_ids}; +pub use views::DerivedWork; +pub(crate) use views::{DerivedCache, DocViews, SidebarFolderTree}; +pub use writer::{PendingUpdates, SessionWriter, merge_pending_updates}; /// Local vs Cloud workspace sync flavour. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -159,7 +164,7 @@ pub struct DesktopDocStore { pub directory: WorkspaceDirectory, pub docs: BTreeMap, pub folder_rows: Vec, - pub folder_cache: FolderForestCache, + pub folder_cache: RefCell, pub collections: Vec, pub tag_colors: BTreeMap, pub link_graph: LinkGraph, @@ -167,6 +172,8 @@ pub struct DesktopDocStore { pub next_seq: u64, pub env_rev: u64, pub(crate) workspace_buckets: BTreeMap, + pub(crate) derived: DerivedCache, + pub(crate) writer: Option, #[cfg(not(target_family = "wasm"))] pub sqlite_backing: Option, } @@ -192,13 +199,13 @@ impl DesktopDocStore { std::mem::swap(&mut self.directory, &mut incoming.directory); std::mem::swap(&mut self.docs, &mut incoming.docs); std::mem::swap(&mut self.folder_rows, &mut incoming.folder_rows); - std::mem::swap(&mut self.folder_cache, &mut incoming.folder_cache); + std::mem::swap(self.folder_cache.get_mut(), &mut incoming.folder_cache); std::mem::swap(&mut self.collections, &mut incoming.collections); std::mem::swap(&mut self.tag_colors, &mut incoming.tag_colors); std::mem::swap(&mut self.link_graph, &mut incoming.link_graph); self.workspace_buckets.insert(old_idx, incoming); self.active_workspace_idx = index; - self.env_rev += 1; + self.folders_changed(); } pub fn page_titles(&self) -> BTreeMap { @@ -212,48 +219,21 @@ impl DesktopDocStore { self.docs.get(doc_id) } + /// Non-trashed documents, most recently updated first. pub fn visible_docs(&self) -> Vec<&DesktopDocMeta> { - let mut out: Vec<&DesktopDocMeta> = self - .docs - .values() - .filter(|e| !e.meta.trashed) - .map(|e| &e.meta) - .collect(); - out.sort_by(|a, b| { - b.updated_at_ms - .cmp(&a.updated_at_ms) - .then_with(|| a.id.cmp(&b.id)) - }); - out + self.metas(&self.views().visible) } pub fn favorite_docs(&self) -> Vec<&DesktopDocMeta> { - self.visible_docs() - .into_iter() - .filter(|d| d.is_favorite) - .collect() + self.metas(&self.views().favorites) } pub fn trashed_docs(&self) -> Vec<&DesktopDocMeta> { - let mut out: Vec<&DesktopDocMeta> = self - .docs - .values() - .filter(|e| e.meta.trashed) - .map(|e| &e.meta) - .collect(); - out.sort_by_key(|a| std::cmp::Reverse(a.updated_at_ms)); - out + self.metas(&self.views().trashed) } pub fn journal_docs(&self) -> Vec<&DesktopDocMeta> { - let mut out: Vec<&DesktopDocMeta> = self - .docs - .values() - .filter(|e| !e.meta.trashed && e.meta.journal_date.is_some()) - .map(|e| &e.meta) - .collect(); - out.sort_by(|a, b| b.journal_date.cmp(&a.journal_date)); - out + self.metas(&self.views().journals) } pub fn docs_for_collection(&self, col_id: &str) -> Vec<&DesktopDocMeta> { @@ -273,84 +253,111 @@ impl DesktopDocStore { .collect() } + /// Non-trashed documents placed directly in `folder_id`, in sidebar tree order. pub fn docs_in_folder(&self, folder_id: &str) -> Vec<&DesktopDocMeta> { - let mut doc_ids = Vec::new(); - for row in &self.folder_rows { - if row.folder_type == "doc" && row.parent_id.as_deref() == Some(folder_id) { - doc_ids.push(row.data.as_str()); - } - } - doc_ids - .into_iter() + self.metas(self.views().folders.docs(folder_id)) + } + + pub fn all_tags_with_counts(&self) -> Vec<(String, u32, usize)> { + self.views().tags.clone() + } + + fn metas(&self, ids: &[String]) -> Vec<&DesktopDocMeta> { + ids.iter() .filter_map(|id| self.docs.get(id)) - .filter(|e| !e.meta.trashed) .map(|e| &e.meta) .collect() } - pub fn all_tags_with_counts(&self) -> Vec<(String, u32, usize)> { - let mut counts = BTreeMap::::new(); - for tag in self.tag_colors.keys() { - counts.insert(tag.clone(), 0); - } - for entry in self.docs.values().filter(|e| !e.meta.trashed) { - for tag in &entry.meta.tags { - *counts.entry(tag.clone()).or_insert(0) += 1; - } - } - counts - .into_iter() - .map(|(tag, n)| { - let color = self.tag_colors.get(&tag).copied().unwrap_or(0x1E96EB); - (tag, color, n) - }) - .collect() - } - /// Compute the next fractional-index key after all existing sibling rows under `parent_id`. - fn next_folder_index(&self, parent_id: Option<&str>) -> String { + fn next_folder_index(&self, parent_id: Option<&str>, excluded_doc: Option<&str>) -> String { let max_idx = self .folder_rows .iter() - .filter(|r| r.parent_id.as_deref() == parent_id) + .filter(|r| { + r.parent_id.as_deref() == parent_id + && !(r.folder_type == "doc" && excluded_doc == Some(r.data.as_str())) + }) .map(|r| r.index.as_str()) .max(); blocksuite_playground_doc::fractional_index::generate_key_between(max_idx, None) .unwrap_or_else(|_| format!("{}V", max_idx.unwrap_or("a0"))) } + fn next_folder_row_id(&mut self, prefix: &str) -> String { + loop { + self.next_seq += 1; + let id = format!("{prefix}-{}", self.next_seq); + if !self.folder_rows.iter().any(|row| row.id == id) { + return id; + } + } + } + + fn change_folder_rows( + &mut self, + remove: impl Fn(&FolderRow) -> bool, + insert: Option, + ) -> Vec { + let removed: Vec<_> = self + .folder_rows + .iter() + .filter(|row| remove(row)) + .map(|row| row.id.clone()) + .collect(); + if removed.is_empty() && insert.is_none() { + return removed; + } + + let now = self.writer_now(); + if let Some(Err(_)) = self.with_session(now, |session| { + for id in &removed { + session.soft_delete_folder_row(id, now)?; + } + if let Some(row) = &insert { + session.upsert_folder_row(row, now)?; + } + Ok(()) + }) { + return Vec::new(); + } + + self.folder_rows.retain(|row| !remove(row)); + self.folder_rows.extend(insert); + self.folders_changed(); + removed + } + /// Create a new folder node in the sidebar tree with a valid fractional index. pub fn create_folder(&mut self, name: impl Into, parent_id: Option) -> String { - self.next_seq += 1; - let id = format!("f-{}", self.next_seq); - let idx = self.next_folder_index(parent_id.as_deref()); - self.folder_rows.push(FolderRow { - id: id.clone(), + let row = FolderRow { + id: self.next_folder_row_id("f"), + index: self.next_folder_index(parent_id.as_deref(), None), parent_id, data: name.into(), folder_type: "folder".into(), - index: idx, - }); - self.rebuild_derived(); + }; + let now = self.writer_now(); + if let Some(Err(_)) = self.with_session(now, |session| session.upsert_folder_row(&row, now)) + { + return String::new(); + } + let id = row.id.clone(); + self.folder_rows.push(row); + self.folders_changed(); id } /// Move (or add) a document placement into a folder with a valid fractional index. pub fn move_doc_to_folder(&mut self, doc_id: &str, target_folder_id: Option<&str>) { - self.folder_rows - .retain(|r| !(r.folder_type == "doc" && r.data == doc_id)); - if let Some(folder_id) = target_folder_id { - self.next_seq += 1; - let idx = self.next_folder_index(Some(folder_id)); - self.folder_rows.push(FolderRow { - id: format!("link-{}", self.next_seq), - parent_id: Some(folder_id.to_string()), - data: doc_id.to_string(), - folder_type: "doc".into(), - index: idx, - }); - } - self.rebuild_derived(); + let row = target_folder_id.map(|folder_id| FolderRow { + id: self.next_folder_row_id("link"), + index: self.next_folder_index(Some(folder_id), Some(doc_id)), + parent_id: Some(folder_id.to_string()), + data: doc_id.to_string(), + folder_type: "doc".into(), + }); + self.change_folder_rows(|row| row.folder_type == "doc" && row.data == doc_id, row); } /// Recursively delete a folder and every descendant folder and doc placement under it. @@ -374,38 +381,35 @@ impl DesktopDocStore { break; } } - let mut removed = Vec::new(); - self.folder_rows.retain(|row| { - let drop_row = folders.contains(&row.id) - || row - .parent_id - .as_deref() - .is_some_and(|pid| folders.contains(pid)); - if drop_row { - removed.push(row.id.clone()); - } - !drop_row - }); - if !removed.is_empty() { - self.rebuild_derived(); - } - removed + self.change_folder_rows( + |row| { + folders.contains(&row.id) + || row + .parent_id + .as_deref() + .is_some_and(|pid| folders.contains(pid)) + }, + None, + ) } /// Remove a document from a specific folder without trashing the document. pub fn remove_doc_from_folder(&mut self, doc_id: &str, folder_id: &str) -> bool { - let before = self.folder_rows.len(); - self.folder_rows.retain(|r| { - !(r.folder_type == "doc" - && r.data == doc_id - && r.parent_id.as_deref() == Some(folder_id)) - }); - let changed = self.folder_rows.len() != before; - if changed { - self.rebuild_derived(); - } - changed + !self + .change_folder_rows( + |row| { + row.folder_type == "doc" + && row.data == doc_id + && row.parent_id.as_deref() == Some(folder_id) + }, + None, + ) + .is_empty() } } +mod hydration; mod mutations; +mod skeleton; +mod views; +mod writer; diff --git a/packages/frontend/desktop/src/doc_store/mutations.rs b/packages/frontend/desktop/src/doc_store/mutations.rs index 0255968415..5cf4a72f62 100644 --- a/packages/frontend/desktop/src/doc_store/mutations.rs +++ b/packages/frontend/desktop/src/doc_store/mutations.rs @@ -1,7 +1,10 @@ -//! Document creation, editing, search, outline, SQLite hydration, and remote sync -//! methods for [`DesktopDocStore`]. +//! Document creation, rename, favorite, trash, outline, and link index methods for +//! [`DesktopDocStore`]. +//! +//! When the active workspace has a connected session, each command writes to that session +//! first and the store projects the session result. -use affine_client::{LinkGraph, SearchDocument, SearchHit}; +use affine_client::{ClientError, EditorDocMode, LinkGraph}; use affine_store::directory::{CreateDocId, CreateDocRequest, DocId, DocMode}; use blocksuite_playground_doc::{ read::BlockContent, @@ -11,9 +14,44 @@ use blocksuite_playground_doc::{ try_random_client_id, }; -use crate::showcase::{build_basic_doc_session, populate_note_and_surface_ids}; +use super::{ + DesktopDocMeta, DesktopDocStore, DocHydrationState, LiveDocEntry, OutlineHeading, + build_basic_doc_session, populate_note_and_surface_ids, +}; -use super::{DesktopDocMeta, DesktopDocStore, DocHydrationState, LiveDocEntry, OutlineHeading}; +const NEW_DOC_SUMMARY: &str = "New document ready for collaborative Page and Edgeless editing."; + +fn doc_edges(entry: &LiveDocEntry) -> Vec { + entry + .meta + .outgoing_refs + .iter() + .map(|target| DocRefEdge { + source_doc_id: entry.meta.id.clone(), + target_doc_id: target.clone(), + source_block_id: entry.note_id.clone(), + kind: OutboundRefKind::InlineMention, + }) + .collect() +} + +/// Give a store replica a fresh client ID when merged history reuses its current one. +pub(crate) fn adopt_client_if_required(page: &mut PageDocSession) { + if page.inner().client_required() + && let Ok(cid) = try_random_client_id() + { + page.inner_mut().set_client(cid); + } +} + +/// Merge `update` into a store replica. Returns `false` when the update does not apply. +pub(crate) fn merge_into_replica(page: &mut PageDocSession, update: &[u8]) -> bool { + if page.apply_remote_update_v1(update).is_err() { + return false; + } + adopt_client_if_required(page); + true +} impl DesktopDocStore { /// Create a new live document backed by both `WorkspaceDirectory` and `PageDocSession`. @@ -24,20 +62,15 @@ impl DesktopDocStore { journal_date: Option, now_ms: i64, ) -> String { - let Ok(client_id) = try_random_client_id() else { - return String::new(); - }; - self.next_seq += 1; - let id = format!("doc-{}", self.next_seq); - let Ok(typed_id) = DocId::new(id.clone()) else { - return String::new(); - }; let title = title.into(); - let Some((session, note_id, surface_id)) = - build_basic_doc_session(&id, &title, now_ms as u64, client_id) + let Some((id, session, note_id, surface_id)) = + self.new_doc_session(&title, mode, journal_date.as_deref(), now_ms) else { return String::new(); }; + let Ok(typed_id) = DocId::new(id.clone()) else { + return String::new(); + }; let Ok(snapshot) = session.read_page_snapshot() else { return String::new(); }; @@ -59,34 +92,80 @@ impl DesktopDocStore { } else { Vec::new() }; - let meta = DesktopDocMeta { - id: id.clone(), - title, - summary: "New document ready for collaborative Page and Edgeless editing.".into(), - default_mode: mode, - tags, - is_favorite: false, - trashed: false, - journal_date, - updated_at_ms: now_ms, - outgoing_refs: Vec::new(), - }; - self.docs.insert( - id.clone(), - LiveDocEntry { - meta, - session, - note_id, - surface_id, - snapshot, - revision, - hydration: DocHydrationState::Hydrated, + let mut entry = LiveDocEntry { + meta: DesktopDocMeta { + id: id.clone(), + title, + summary: NEW_DOC_SUMMARY.into(), + default_mode: mode, + tags, + is_favorite: false, + trashed: false, + journal_date, + updated_at_ms: now_ms, + outgoing_refs: Vec::new(), }, - ); - self.rebuild_derived(); + session, + note_id, + surface_id, + snapshot, + revision, + hydration: DocHydrationState::Hydrated, + }; + let snap = entry.snapshot.clone(); + populate_note_and_surface_ids(&mut entry, &snap); + self.docs.insert(id.clone(), entry); + self.index_doc_links(&id); + self.touch_meta(); id } + /// Build the page of a new document. With a connected session, the session creates the + /// document and the store keeps a replica of its page under a client ID of its own. + fn new_doc_session( + &mut self, + title: &str, + mode: DocMode, + journal_date: Option<&str>, + now_ms: i64, + ) -> Option<(String, PageDocSession, String, String)> { + let client_id = try_random_client_id().ok()?; + let editor_mode = match mode { + DocMode::Page => EditorDocMode::Page, + DocMode::Edgeless => EditorDocMode::Edgeless, + }; + let created = self.with_session(now_ms, |s| { + let (summary, pending) = s.create_document(title, editor_mode, None, now_ms)?; + s.enqueue_pending_persist_updates(pending); + let id = summary.id.as_str().to_owned(); + if let Some(date) = journal_date { + s.set_doc_journal_date(&id, date, now_ms)?; + } + let bytes = s + .doc_update_v1(&id) + .ok_or_else(|| ClientError::DocNotFound(id.clone()))?; + Ok((id, bytes)) + }); + match created { + Some(Ok((id, bytes))) => { + let mut session = PageDocSession::new(&id, client_id).ok()?; + if !merge_into_replica(&mut session, &bytes) { + return None; + } + self.mark_writer_started(&id); + Some((id, session, String::new(), String::new())) + } + Some(Err(_)) => None, + None => { + self.next_seq += 1; + let id = format!("doc-{}", self.next_seq); + let (session, note_id, surface_id) = + build_basic_doc_session(&id, title, now_ms as u64, client_id)?; + Some((id, session, note_id, surface_id)) + } + } + } + /// Open or create the daily journal document for `date` (`YYYY-MM-DD`). pub fn open_or_create_journal(&mut self, date: &str, now_ms: i64) -> String { if let Some(existing) = self @@ -112,6 +191,7 @@ impl DesktopDocStore { let block_id = format!("p-{}", self.next_seq); let entry = self.docs.get_mut(doc_id)?; let note_id = entry.note_id.clone(); + let before = entry.session.encode_state_vector_v1().ok()?; entry .session .add_block( @@ -129,7 +209,9 @@ impl DesktopDocStore { entry.revision = entry.session.revision(); entry.meta.updated_at_ms = now_ms; entry.meta.summary = text.to_string(); - self.env_rev += 1; + let delta = entry.session.encode_diff_v1(&before).ok()?; + self.enqueue_doc_update(doc_id, delta); + self.touch_meta(); Some(block_id) } @@ -137,16 +219,23 @@ impl DesktopDocStore { /// /// Mutates the real root block's `prop:title` `Y.Text` in place via `set_block_title_text` /// so concurrent character-level CRDT edits are preserved and non-`"root"` NanoIDs work. + /// With a connected session, the session renames the document and its page, and the store + /// merges the renamed page. pub fn rename_doc(&mut self, doc_id: &str, new_title: &str, now_ms: i64) -> bool { - if self.ensure_doc_hydrated(doc_id).is_err() { - return false; - } - if !self.docs.contains_key(doc_id) { + if self.ensure_doc_hydrated(doc_id).is_err() || !self.docs.contains_key(doc_id) { return false; } let Ok(id) = DocId::new(doc_id) else { return false; }; + let renamed_page = match self.with_session(now_ms, |s| { + s.rename_document(doc_id, new_title, now_ms)?; + Ok(s.doc_update_v1(doc_id)) + }) { + Some(Ok(page)) => page, + Some(Err(_)) => return false, + None => None, + }; if self.directory.db().root().is_meta_initialized() && self.directory.rename_doc(&id, new_title).is_err() { @@ -157,138 +246,117 @@ impl DesktopDocStore { }; entry.meta.title = new_title.to_string(); entry.meta.updated_at_ms = now_ms; - if let Some(root_id) = entry.snapshot.root.as_ref().map(|r| r.id.clone()) { - let _ = entry + let mut delta = None; + if let Some(bytes) = renamed_page { + merge_into_replica(&mut entry.session, &bytes); + } else if let Some(root_id) = entry.snapshot.root.as_ref().map(|r| r.id.clone()) + && let Ok(before) = entry.session.encode_state_vector_v1() + && entry .session - .set_block_title_text(&root_id, new_title, now_ms as u64); + .set_block_title_text(&root_id, new_title, now_ms as u64) + .is_ok() + { + delta = entry.session.encode_diff_v1(&before).ok(); } if let Ok(snap) = entry.session.read_page_snapshot() { populate_note_and_surface_ids(entry, &snap); entry.snapshot = snap; entry.revision = entry.session.revision(); } - self.env_rev += 1; + if let Some(delta) = delta { + self.enqueue_doc_update(doc_id, delta); + } + self.touch_meta(); true } pub fn toggle_favorite(&mut self, doc_id: &str) -> bool { - let Some(entry) = self.docs.get_mut(doc_id) else { + let Some(next) = self.docs.get(doc_id).map(|e| !e.meta.is_favorite) else { return false; }; - entry.meta.is_favorite = !entry.meta.is_favorite; - self.env_rev += 1; - entry.meta.is_favorite + let now = self.writer_now(); + if let Some(Err(_)) = self.with_session(now, |s| s.set_doc_favorite(doc_id, next, now)) { + return !next; + } + if let Some(entry) = self.docs.get_mut(doc_id) { + entry.meta.is_favorite = next; + } + self.touch_meta(); + next } /// Soft-delete a document into Trash. pub fn trash_doc(&mut self, doc_id: &str, now_ms: i64) -> bool { - let Some(trashed) = self.docs.get(doc_id).map(|e| e.meta.trashed) else { - return false; - }; - if trashed { - return false; - } - let Ok(id) = DocId::new(doc_id) else { - return false; - }; - if self.directory.db().root().is_meta_initialized() - && self.directory.trash_doc(&id, now_ms).is_err() - { - return false; - } - let Some(entry) = self.docs.get_mut(doc_id) else { - return false; - }; - entry.meta.trashed = true; - entry.meta.updated_at_ms = now_ms; - self.rebuild_derived(); - true + self.set_trashed(doc_id, true, now_ms) } /// Restore a soft-deleted document from Trash. pub fn restore_doc(&mut self, doc_id: &str, now_ms: i64) -> bool { - let Some(trashed) = self.docs.get(doc_id).map(|e| e.meta.trashed) else { - return false; - }; - if !trashed { + self.set_trashed(doc_id, false, now_ms) + } + + fn set_trashed(&mut self, doc_id: &str, trashed: bool, now_ms: i64) -> bool { + if self.docs.get(doc_id).map(|e| e.meta.trashed) != Some(!trashed) { return false; } let Ok(id) = DocId::new(doc_id) else { return false; }; - if self.directory.db().root().is_meta_initialized() - && self.directory.restore_doc(&id).is_err() - { + let written = self.with_session(now_ms, |s| { + if trashed { + s.trash_document(doc_id, now_ms) + } else { + s.restore_document(doc_id, now_ms) + } + }); + if let Some(Err(_)) = written { return false; } + if self.directory.db().root().is_meta_initialized() { + let local = if trashed { + self.directory.trash_doc(&id, now_ms) + } else { + self.directory.restore_doc(&id) + }; + if local.is_err() { + return false; + } + } let Some(entry) = self.docs.get_mut(doc_id) else { return false; }; - entry.meta.trashed = false; + entry.meta.trashed = trashed; entry.meta.updated_at_ms = now_ms; - self.rebuild_derived(); + self.touch_meta(); true } /// Permanently delete a trashed document from the workspace. pub fn permanently_delete_doc(&mut self, doc_id: &str) -> bool { - let Some(entry) = self.docs.get(doc_id) else { - return false; - }; - if !entry.meta.trashed { + if !self.docs.get(doc_id).is_some_and(|e| e.meta.trashed) { return false; } let Ok(id) = DocId::new(doc_id) else { return false; }; + let now = self.writer_now(); + if let Some(Err(_)) = self.with_session(now, |s| s.delete_document_permanently(doc_id, now)) + { + return false; + } if self.directory.db().root().is_meta_initialized() && self.directory.delete_doc(&id).is_err() { return false; } self.docs.remove(doc_id); + self.link_graph.remove_doc(doc_id); self.folder_rows .retain(|r| !(r.folder_type == "doc" && r.data == doc_id)); - self.rebuild_derived(); + self.folders_changed(); true } - /// Search visible documents using `WeightedSearchEngine` plus fuzzy subsequence fallback. - pub fn search_docs(&self, query: &str, limit: usize) -> Vec { - let docs: Vec = self - .visible_docs() - .into_iter() - .map(|d| SearchDocument { - id: d.id.clone(), - title: d.title.clone(), - tags: d.tags.clone(), - body_preview: d.summary.clone(), - updated_at_ms: d.updated_at_ms, - }) - .collect(); - let mut hits = self.search_engine.search(&docs, query, limit); - if hits.is_empty() && !query.trim().is_empty() { - let q = query.trim().to_ascii_lowercase(); - for d in &docs { - if is_subsequence(&q, &d.title.to_ascii_lowercase()) - || is_subsequence(&q, &d.body_preview.to_ascii_lowercase()) - { - hits.push(SearchHit { - doc_id: d.id.clone(), - title: d.title.clone(), - score: 0.5, - title_highlights: Vec::new(), - matched_tags: Vec::new(), - body_highlights: Vec::new(), - updated_at_ms: d.updated_at_ms, - }); - } - } - hits.truncate(limit); - } - hits - } - /// Extract H1-H6 outline headings from a live document snapshot. pub fn outline_headings(&self, doc_id: &str) -> Vec { let Some(entry) = self.docs.get(doc_id) else { @@ -328,27 +396,26 @@ impl DesktopDocStore { .collect() } - pub(crate) fn rebuild_derived(&mut self) { - self.env_rev += 1; - let _ = self - .folder_cache - .resolve(true, self.env_rev, &self.folder_rows); + /// Replace the outbound link edges of one document. + pub(crate) fn index_doc_links(&mut self, doc_id: &str) { + match self.docs.get(doc_id) { + Some(entry) => self + .link_graph + .replace_edges(doc_id, doc_edges(entry), entry.revision), + None => self.link_graph.remove_doc(doc_id), + } + self.derived.count_link_update(); + } + + /// Index every document link and resolve the folder forest after a bulk load. + pub(crate) fn reindex_all(&mut self) { self.link_graph = LinkGraph::default(); for entry in self.docs.values() { - let edges: Vec = entry - .meta - .outgoing_refs - .iter() - .map(|target| DocRefEdge { - source_doc_id: entry.meta.id.clone(), - target_doc_id: target.clone(), - source_block_id: entry.note_id.clone(), - kind: OutboundRefKind::InlineMention, - }) - .collect(); self.link_graph - .replace_edges(&entry.meta.id, edges, entry.revision); + .replace_edges(&entry.meta.id, doc_edges(entry), entry.revision); + self.derived.count_link_update(); } + self.folders_changed(); } pub(crate) fn register_seeded( @@ -386,131 +453,6 @@ impl DesktopDocStore { hydration: DocHydrationState::Hydrated, }, ); - } - - /// Returns `true` when this store is backed by an opened read-only SQLite `.affine` file. - pub fn is_readonly_sqlite(&self) -> bool { - #[cfg(not(target_family = "wasm"))] - { - self.sqlite_backing.is_some() - } - #[cfg(target_family = "wasm")] - { - false - } - } - - /// Open a real `.affine` / `.db` SQLite workspace in place with lazy hydration. - #[cfg(not(target_family = "wasm"))] - pub fn open_sqlite_file( - path: impl AsRef, - ) -> anyhow::Result<(Self, crate::sqlite_loader::SqliteLoadStats)> { - crate::sqlite_loader::open_sqlite_workspace(path) - } - - /// Lazily hydrate one document's CRDT state from its SQLite backing store if not yet loaded. - /// - /// Distinguishes confirmed local documents from uncached remote documents: when SQLite has no - /// row for `doc_id`, marks the entry as [`DocHydrationState::DocumentLoading`] and returns - /// `Err` so callers never render an unhydrated remote document as an editable blank page. - pub fn ensure_doc_hydrated(&mut self, doc_id: &str) -> Result { - let Some(entry) = self.docs.get(doc_id) else { - return Ok(false); - }; - if entry.is_hydrated() { - return Ok(true); - } - #[cfg(not(target_family = "wasm"))] - if let Some(backing) = self.sqlite_backing.clone() { - let maybe_bytes = backing - .load_doc_update(doc_id) - .map_err(|e| format!("failed to read SQLite doc `{doc_id}`: {e}"))?; - let Some(entry) = self.docs.get_mut(doc_id) else { - return Ok(false); - }; - let Some(bytes) = maybe_bytes else { - entry.hydration = DocHydrationState::DocumentLoading; - return Err(format!( - "DocumentLoading: `{doc_id}` has no local SQLite data" - )); - }; - if !bytes.is_empty() && bytes.as_slice() != [0, 0] { - entry - .session - .apply_remote_update_v1(&bytes) - .map_err(|e| format!("failed to apply CRDT update for `{doc_id}`: {e}"))?; - if entry.session.inner().client_required() - && let Ok(cid) = try_random_client_id() - { - entry.session.inner_mut().set_client(cid); - } - } - let snap = entry - .session - .read_page_snapshot() - .map_err(|e| format!("failed to read page snapshot for `{doc_id}`: {e}"))?; - populate_note_and_surface_ids(entry, &snap); - if entry.meta.summary.is_empty() { - entry.meta.summary = crate::sqlite_loader::extract_snapshot_summary(&snap); - } - entry.snapshot = snap; - entry.revision = entry.session.revision(); - entry.hydration = DocHydrationState::Hydrated; - return Ok(true); - } - if let Some(entry) = self.docs.get_mut(doc_id) { - entry.hydration = DocHydrationState::Hydrated; - return Ok(true); - } - Ok(false) - } - - /// Apply a Yjs V1 update originated by a mounted `Entity` into the shared doc. - pub fn apply_remote_doc_update(&mut self, doc_id: &str, update: &[u8]) -> bool { - if update.is_empty() { - return false; - } - let Some(entry) = self.docs.get_mut(doc_id) else { - return false; - }; - if entry.session.apply_remote_update_v1(update).is_err() { - return false; - } - if entry.session.inner().client_required() - && let Ok(cid) = try_random_client_id() - { - entry.session.inner_mut().set_client(cid); - } - if let Ok(snap) = entry.session.read_page_snapshot() { - populate_note_and_surface_ids(entry, &snap); - if let Some(root) = &snap.root - && let BlockContent::Page { title } = &root.content - && !title.plain.trim().is_empty() - { - entry.meta.title = title.plain.clone(); - } - entry.snapshot = snap; - } - entry.revision = entry.session.revision(); - entry.hydration = DocHydrationState::Hydrated; - self.env_rev += 1; - true + self.touch_meta(); } } - -fn is_subsequence(needle: &str, haystack: &str) -> bool { - let mut chars = needle.chars(); - let mut current = match chars.next() { - Some(c) => c, - None => return true, - }; - for h in haystack.chars() { - if h == current { - match chars.next() { - Some(next) => current = next, - None => return true, - } - } - } - false -} diff --git a/packages/frontend/desktop/src/doc_store/skeleton.rs b/packages/frontend/desktop/src/doc_store/skeleton.rs new file mode 100644 index 0000000000..8198615aec --- /dev/null +++ b/packages/frontend/desktop/src/doc_store/skeleton.rs @@ -0,0 +1,91 @@ +//! Page skeleton of a new desktop document and note and surface ID resolution. + +use blocksuite_playground_doc::{ + read::{BlockContent, PageSnapshot}, + schema::{BlockSpec, ParagraphType}, + session::PageDocSession, +}; + +use super::LiveDocEntry; + +/// Resolve and backfill `note_id` (first page-visible note) and `surface_id` from a hydrated snapshot. +pub(crate) fn populate_note_and_surface_ids(entry: &mut LiveDocEntry, snap: &PageSnapshot) { + let Some(root) = &snap.root else { + return; + }; + let mut fallback_note: Option = None; + let mut visible_note: Option = None; + let mut surface_id: Option = None; + for child in &root.children { + match &child.content { + BlockContent::Note { .. } => { + if child.is_page_visible_note() && visible_note.is_none() { + visible_note = Some(child.id.clone()); + } else if fallback_note.is_none() { + fallback_note = Some(child.id.clone()); + } + } + BlockContent::Surface { .. } if surface_id.is_none() => { + surface_id = Some(child.id.clone()); + } + _ => {} + } + } + if let Some(id) = visible_note.or(fallback_note) { + entry.note_id = id; + } + if let Some(id) = surface_id { + entry.surface_id = id; + } +} + +pub(crate) fn build_basic_doc_session( + doc_id: &str, + title: &str, + now_ms: u64, + client_id: u64, +) -> Option<(PageDocSession, String, String)> { + let mut s = PageDocSession::new(doc_id, client_id).ok()?; + let note_id = format!("note-{doc_id}"); + let surface_id = format!("surface-{doc_id}"); + s.add_block( + "root", + BlockSpec::Page { + title: title.to_string(), + }, + None, + None, + now_ms, + ) + .ok()?; + s.add_block( + &surface_id, + BlockSpec::Surface, + Some("root"), + None, + now_ms + 1, + ) + .ok()?; + s.add_block( + ¬e_id, + BlockSpec::Note { + xywh: Some("[60,80,500,260]".into()), + }, + Some("root"), + None, + now_ms + 2, + ) + .ok()?; + s.add_block( + &format!("p-init-{doc_id}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: format!("{title} — live collaborative Page & Edgeless document."), + }, + Some(¬e_id), + None, + now_ms + 3, + ) + .ok()?; + Some((s, note_id, surface_id)) +} diff --git a/packages/frontend/desktop/src/doc_store/views.rs b/packages/frontend/desktop/src/doc_store/views.rs new file mode 100644 index 0000000000..4c5e435000 --- /dev/null +++ b/packages/frontend/desktop/src/doc_store/views.rs @@ -0,0 +1,345 @@ +//! Revision-keyed derived views of the active workspace: ordered document lists, sidebar +//! counts, the sidebar folder tree, and the Quick Search index with its recent results. +//! +//! Every view is built at most once per metadata revision. Ordinary frames that read the same +//! revision reuse the cached views and do no sorting, grouping, or index building. + +use std::{ + cell::{Cell, RefCell}, + collections::{BTreeMap, HashMap}, + sync::Arc, +}; + +use affine_client::{FolderForest, FolderForestState, SearchDocument, SearchHit}; + +use super::{DesktopDocMeta, DesktopDocStore}; + +/// Most recent distinct Quick Search queries kept per revision. +const SEARCH_RESULT_SLOTS: usize = 16; + +/// Deterministic counts of derived work done by a [`DesktopDocStore`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct DerivedWork { + /// Builds of the ordered document lists, counts, and sidebar folder tree. + pub view_builds: u64, + /// Builds of the Quick Search document index. + pub search_index_builds: u64, + /// Search runs that missed the result cache. + pub search_runs: u64, + /// Documents whose outbound link edges were replaced in the link graph. + pub link_index_updates: u64, +} + +/// Folder rows in sidebar order, built once per revision from the sanitized folder forest. +#[derive(Debug, Default)] +pub(crate) struct SidebarFolderTree { + roots: Vec, + nodes: HashMap, +} + +#[derive(Debug, Default)] +struct FolderNode { + name: String, + folders: Vec, + docs: Vec, +} + +impl SidebarFolderTree { + fn build(forest: Option<&FolderForest>, store: &DesktopDocStore) -> Self { + let Some(forest) = forest else { + return Self::default(); + }; + let folders = forest.list_valid_folders(); + let mut nodes: HashMap = folders + .iter() + .map(|row| { + ( + row.id.clone(), + FolderNode { + name: row.data.clone(), + ..FolderNode::default() + }, + ) + }) + .collect(); + let mut roots = Vec::new(); + for row in &folders { + match row.parent_id.as_deref() { + None => roots.push(row.id.clone()), + Some(parent) => { + if let Some(node) = nodes.get_mut(parent) { + node.folders.push(row.id.clone()); + } + } + } + } + let mut placed: BTreeMap<&str, Vec<(&str, &str, &str)>> = BTreeMap::new(); + for entry in store.docs.values().filter(|e| !e.meta.trashed) { + for placement in forest.placements_for_doc(&entry.meta.id) { + if let Some(parent) = placement.ancestors.last() { + placed.entry(parent.folder_id.as_str()).or_default().push(( + placement.leaf_index.as_str(), + placement.link_id.as_str(), + entry.meta.id.as_str(), + )); + } + } + } + for (folder_id, mut docs) in placed { + docs.sort_unstable(); + if let Some(node) = nodes.get_mut(folder_id) { + node.docs = docs.into_iter().map(|(_, _, id)| id.to_owned()).collect(); + } + } + Self { roots, nodes } + } + + pub(crate) fn roots(&self) -> &[String] { + &self.roots + } + + pub(crate) fn name(&self, folder_id: &str) -> Option<&str> { + self.nodes.get(folder_id).map(|n| n.name.as_str()) + } + + pub(crate) fn child_folders(&self, folder_id: &str) -> &[String] { + self.nodes.get(folder_id).map_or(&[], |n| &n.folders) + } + + pub(crate) fn docs(&self, folder_id: &str) -> &[String] { + self.nodes.get(folder_id).map_or(&[], |n| &n.docs) + } +} + +/// Ordered document lists and sidebar counts of one metadata revision. +#[derive(Debug, Default)] +pub(crate) struct DocViews { + pub(crate) visible: Vec, + pub(crate) favorites: Vec, + pub(crate) trashed: Vec, + pub(crate) journals: Vec, + pub(crate) tags: Vec<(String, u32, usize)>, + /// Matching visible document count of each collection, in `DesktopDocStore::collections` order. + pub(crate) collection_counts: Vec, + pub(crate) folders: SidebarFolderTree, +} + +impl DocViews { + fn build(store: &DesktopDocStore) -> Self { + let ids = |metas: Vec<&DesktopDocMeta>| metas.into_iter().map(|m| m.id.clone()).collect(); + let mut visible: Vec<&DesktopDocMeta> = store + .docs + .values() + .filter(|e| !e.meta.trashed) + .map(|e| &e.meta) + .collect(); + visible.sort_by(|a, b| { + b.updated_at_ms + .cmp(&a.updated_at_ms) + .then_with(|| a.id.cmp(&b.id)) + }); + let favorites = visible.iter().copied().filter(|d| d.is_favorite).collect(); + let mut trashed: Vec<&DesktopDocMeta> = store + .docs + .values() + .filter(|e| e.meta.trashed) + .map(|e| &e.meta) + .collect(); + trashed.sort_by_key(|a| std::cmp::Reverse(a.updated_at_ms)); + let mut journals: Vec<&DesktopDocMeta> = visible + .iter() + .copied() + .filter(|d| d.journal_date.is_some()) + .collect(); + journals.sort_by(|a, b| b.journal_date.cmp(&a.journal_date).then(a.id.cmp(&b.id))); + + let mut tag_counts = BTreeMap::<&str, usize>::new(); + for tag in store.tag_colors.keys() { + tag_counts.insert(tag, 0); + } + for doc in &visible { + for tag in &doc.tags { + *tag_counts.entry(tag).or_insert(0) += 1; + } + } + let tags = tag_counts + .into_iter() + .map(|(tag, n)| { + let color = store.tag_colors.get(tag).copied().unwrap_or(0x1E96EB); + (tag.to_owned(), color, n) + }) + .collect(); + let collection_counts = store + .collections + .iter() + .map(|c| visible.iter().filter(|d| c.matches(d)).count()) + .collect(); + Self { + folders: SidebarFolderTree::build(store.folder_forest().as_deref(), store), + visible: ids(visible), + favorites: ids(favorites), + trashed: ids(trashed), + journals: ids(journals), + tags, + collection_counts, + } + } +} + +#[derive(Default)] +struct SearchCache { + key: Option<(usize, u64)>, + docs: Vec, + results: Vec<(String, usize, Vec)>, +} + +/// Revision counter and lazily built caches of the derived views. +#[derive(Default)] +pub(crate) struct DerivedCache { + /// Advances on every change to document metadata, membership, or folder placement. + pub(crate) meta_rev: u64, + /// Advances on every change to folder rows; keys the sanitized folder forest. + folder_rev: u64, + views: RefCell)>>, + search: RefCell, + work: Cell, +} + +impl DerivedCache { + fn count(&self, f: impl FnOnce(&mut DerivedWork)) { + let mut work = self.work.get(); + f(&mut work); + self.work.set(work); + } + + pub(crate) fn count_link_update(&self) { + self.count(|w| w.link_index_updates += 1); + } +} + +impl DesktopDocStore { + /// Deterministic counts of derived work since this store was created. + pub fn derived_work(&self) -> DerivedWork { + self.derived.work.get() + } + + /// Record a change to document metadata, membership, or ordering. + pub(crate) fn touch_meta(&mut self) { + self.env_rev += 1; + self.derived.meta_rev += 1; + } + + /// Record a change to folder rows. The folder forest is resolved again on next read. + pub(crate) fn folders_changed(&mut self) { + self.touch_meta(); + self.derived.folder_rev += 1; + } + + /// The sanitized folder forest of the current folder rows, built once per folder revision. + fn folder_forest(&self) -> Option> { + match self.folder_cache.borrow_mut().resolve( + true, + self.derived.folder_rev, + &self.folder_rows, + ) { + FolderForestState::Ready(forest) => Some(forest), + FolderForestState::Unresolved => None, + } + } + + pub(crate) fn views(&self) -> Arc { + let rev = self.derived.meta_rev; + if let Some((cached_rev, views)) = self.derived.views.borrow().as_ref() + && *cached_rev == rev + { + return Arc::clone(views); + } + let views = Arc::new(DocViews::build(self)); + self.derived.count(|w| w.view_builds += 1); + *self.derived.views.borrow_mut() = Some((rev, Arc::clone(&views))); + views + } + + /// Search visible documents using `WeightedSearchEngine`. When weighted search finds no + /// hit, falls back to a case-insensitive subsequence match on titles and summaries. + pub fn search_docs(&self, query: &str, limit: usize) -> Vec { + let key = (self.active_workspace_idx, self.derived.meta_rev); + let mut cache = self.derived.search.borrow_mut(); + if cache.key != Some(key) { + cache.docs = self + .visible_docs() + .into_iter() + .map(|d| SearchDocument { + id: d.id.clone(), + title: d.title.clone(), + tags: d.tags.clone(), + body_preview: d.summary.clone(), + updated_at_ms: d.updated_at_ms, + }) + .collect(); + cache.results.clear(); + cache.key = Some(key); + self.derived.count(|w| w.search_index_builds += 1); + } + if let Some((_, _, hits)) = cache + .results + .iter() + .find(|(q, l, _)| q == query && *l == limit) + { + return hits.clone(); + } + let hits = run_search(self, &cache.docs, query, limit); + self.derived.count(|w| w.search_runs += 1); + if cache.results.len() == SEARCH_RESULT_SLOTS { + cache.results.remove(0); + } + cache.results.push((query.to_owned(), limit, hits.clone())); + hits + } +} + +fn run_search( + store: &DesktopDocStore, + docs: &[SearchDocument], + query: &str, + limit: usize, +) -> Vec { + let mut hits = store.search_engine.search(docs, query, limit); + if hits.is_empty() && !query.trim().is_empty() { + let q = query.trim().to_ascii_lowercase(); + for d in docs { + if is_subsequence(&q, &d.title.to_ascii_lowercase()) + || is_subsequence(&q, &d.body_preview.to_ascii_lowercase()) + { + hits.push(SearchHit { + doc_id: d.id.clone(), + title: d.title.clone(), + score: 0.5, + title_highlights: Vec::new(), + matched_tags: Vec::new(), + body_highlights: Vec::new(), + updated_at_ms: d.updated_at_ms, + }); + } + } + hits.truncate(limit); + } + hits +} + +fn is_subsequence(needle: &str, haystack: &str) -> bool { + let mut chars = needle.chars(); + let mut current = match chars.next() { + Some(c) => c, + None => return true, + }; + for h in haystack.chars() { + if h == current { + match chars.next() { + Some(next) => current = next, + None => return true, + } + } + } + false +} diff --git a/packages/frontend/desktop/src/doc_store/writer.rs b/packages/frontend/desktop/src/doc_store/writer.rs new file mode 100644 index 0000000000..16ed0a8af8 --- /dev/null +++ b/packages/frontend/desktop/src/doc_store/writer.rs @@ -0,0 +1,153 @@ +//! Single writer of a connected workspace. +//! +//! While the workbench drives a writable [`WorkspaceSession`], that session is the only +//! durable writer of the workspace. Shell commands write to it first and project the result +//! into [`DesktopDocStore`]. Document edits that start in the store or in a mounted editor +//! join one ordered queue, and every session write drains that queue first, so session +//! operations always see the edits made before them. + +use std::{ + collections::{HashSet, VecDeque}, + sync::{Arc, Mutex}, +}; + +use affine_client::{ClientResult, WorkspaceSession}; +use blocksuite_playground_doc::session::PageDocSession; + +use super::DesktopDocStore; + +/// Document updates waiting to be merged into the connected session, in edit order. +pub type PendingUpdates = Arc)>>>; + +/// Merge every queued document update into `session` in edit order. +pub fn merge_pending_updates( + pending: &PendingUpdates, + session: &mut WorkspaceSession, + time: i64, +) -> ClientResult<()> { + let mut pending = pending.lock().unwrap_or_else(|e| e.into_inner()); + while let Some((doc_id, bytes)) = pending.front() { + session.merge_local_doc_update(doc_id, bytes, time)?; + pending.pop_front(); + } + Ok(()) +} + +/// The connected session bound to one workspace of the store. +#[cfg_attr(target_family = "wasm", allow(dead_code))] +pub struct SessionWriter { + workspace_id: String, + session: Arc>, + pending: PendingUpdates, + /// Documents whose complete state the session already holds, so a delta is enough. + started: HashSet, + /// Latest shell timestamp written through this writer, for commands that carry none. + last_ms: i64, +} + +impl SessionWriter { + pub fn new( + workspace_id: impl Into, + session: Arc>, + pending: PendingUpdates, + now_ms: i64, + ) -> Self { + Self { + workspace_id: workspace_id.into(), + session, + pending, + started: HashSet::new(), + last_ms: now_ms.max(1), + } + } + + /// Lock the session after merging every queued edit into it. + #[cfg(not(target_family = "wasm"))] + fn lock(&mut self, now_ms: i64) -> ClientResult> { + self.last_ms = self.last_ms.max(now_ms); + let mut session = self.session.lock().unwrap_or_else(|e| e.into_inner()); + merge_pending_updates(&self.pending, &mut session, now_ms)?; + Ok(session) + } + + fn enqueue(&mut self, doc_id: &str, page: &PageDocSession, delta: Vec) { + // A newly bound SQLite store may not have the base of a document edited before binding. + let bytes = if self.started.contains(doc_id) { + delta + } else if let Ok(base) = page.encode_update_v1() { + self.started.insert(doc_id.to_owned()); + base + } else { + delta + }; + self.pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push_back((doc_id.to_owned(), bytes)); + } +} + +impl DesktopDocStore { + /// Make `writer` the single durable writer of its workspace. Native hosts only: Web + /// Desktop has no SQLite session to bind. + #[cfg(not(target_family = "wasm"))] + pub fn bind_writer(&mut self, writer: SessionWriter) { + self.writer = Some(writer); + } + + /// Detach the connected session. Later edits stay in memory only. + pub fn unbind_writer(&mut self) { + self.writer = None; + } + + /// The connected session writer when it belongs to the active workspace. + pub(crate) fn active_writer(&mut self) -> Option<&mut SessionWriter> { + let active = &self.workspaces[self.active_workspace_idx].id; + self.writer.as_mut().filter(|w| &w.workspace_id == active) + } + + /// Run `op` on the connected session of the active workspace after it merged every + /// queued edit. Returns `None` when the active workspace has no connected session. + #[cfg(not(target_family = "wasm"))] + pub(crate) fn with_session( + &mut self, + now_ms: i64, + op: impl FnOnce(&mut WorkspaceSession) -> ClientResult, + ) -> Option> { + let writer = self.active_writer()?; + Some(writer.lock(now_ms).and_then(|mut session| op(&mut session))) + } + + /// Web Desktop binds no session writer, so session operations never run and are not linked. + #[cfg(target_family = "wasm")] + pub(crate) fn with_session( + &mut self, + _now_ms: i64, + _op: impl FnOnce(&mut WorkspaceSession) -> ClientResult, + ) -> Option> { + None + } + + /// Queue a document edit for the connected session of the active workspace. + pub(crate) fn enqueue_doc_update(&mut self, doc_id: &str, delta: Vec) { + let Some(entry) = self.docs.get(doc_id) else { + return; + }; + let active = &self.workspaces[self.active_workspace_idx].id; + if let Some(writer) = self.writer.as_mut().filter(|w| &w.workspace_id == active) { + writer.enqueue(doc_id, &entry.session, delta); + } + } + + /// Mark `doc_id` as fully known by the connected session. + pub(crate) fn mark_writer_started(&mut self, doc_id: &str) { + if let Some(writer) = self.active_writer() { + writer.started.insert(doc_id.to_owned()); + } + } + + /// Latest shell timestamp of the connected session, for commands that carry none. + pub(crate) fn writer_now(&mut self) -> i64 { + self.active_writer().map_or(0, |w| w.last_ms) + } +} diff --git a/packages/frontend/desktop/src/editor_host.rs b/packages/frontend/desktop/src/editor_host.rs index d6d0585d9a..42fbdd420f 100644 --- a/packages/frontend/desktop/src/editor_host.rs +++ b/packages/frontend/desktop/src/editor_host.rs @@ -40,8 +40,6 @@ pub struct DesktopEditorHost { pane_editors: HashMap, peek_editor: Option, syncing: bool, - #[cfg(not(target_family = "wasm"))] - pub(crate) connected_updates: Option, } fn to_pg_mode(mode: DocViewMode) -> PlaygroundMode { @@ -198,17 +196,6 @@ impl DesktopEditorHost { // 2. Apply view-originated incremental edits into `DesktopDocStore`. for (doc_id, bytes) in dirty_updates { if store.apply_remote_doc_update(&doc_id, &bytes) { - #[cfg(not(target_family = "wasm"))] - if let Some(updates) = self.connected_updates.as_mut() - && let Some(entry) = store.get_doc(&doc_id) - { - updates.record( - store.active_workspace().id.as_str(), - &doc_id, - &entry.session, - bytes, - ); - } changed = true; } } @@ -251,128 +238,140 @@ impl DesktopEditorHost { changed } - /// Shared constructor and incremental-sync updater for both split-pane and PeekView editors. + /// Mount a new interactive editor for `doc_id`. #[allow(clippy::too_many_arguments)] - fn ensure_mounted_editor( - slot: &mut Option, + fn mount_editor( origin: Option<&str>, doc_id: &str, pg_mode: PlaygroundMode, theme: ThemeMode, width: f32, height: f32, - store: &mut DesktopDocStore, + store: &DesktopDocStore, cx: &mut Context, - ) -> Option> { - if store.ensure_doc_hydrated(doc_id).is_err() { - return None; - } + ) -> Option { let readonly = store.is_readonly_sqlite(); let entry = store.get_doc(doc_id)?; - let pg_theme = playground_theme_for(theme); - let store_sv = entry.session.encode_state_vector_v1().unwrap_or_default(); - - if slot.is_none() { - let shell = cx.weak_entity(); - let entity = cx.new(|cx| { - PlaygroundView::with_options( - PlaygroundOptions { - theme: pg_theme, - mode: pg_mode, - hide_chrome: true, - page_readonly: readonly, - edgeless_readonly: readonly, - database_readonly: readonly, - ..PlaygroundOptions::default() - }, - cx, - ) - }); - let (view_rev, view_sv) = entity.update(cx, |view, cx| { - view.set_block_link_origin(origin); - view.set_embedded_bounds(width, height); - view.set_block_link_handler(move |target, url, app| { - let shell = shell.clone(); - let url = url.to_owned(); - app.defer(move |app| { - if shell - .update(app, |shell, cx| shell.open_block_link(target, cx)) - .ok() - != Some(true) - { - app.open_url(&url); - } - }); + let shell = cx.weak_entity(); + let entity = cx.new(|cx| { + PlaygroundView::with_options( + PlaygroundOptions { + theme: playground_theme_for(theme), + mode: pg_mode, + hide_chrome: true, + page_readonly: readonly, + edgeless_readonly: readonly, + database_readonly: readonly, + ..PlaygroundOptions::default() + }, + cx, + ) + }); + let (view_rev, view_sv) = entity.update(cx, |view, cx| { + view.set_block_link_origin(origin); + view.set_embedded_bounds(width, height); + view.set_block_link_handler(move |target, url, app| { + let shell = shell.clone(); + let url = url.to_owned(); + app.defer(move |app| { + if shell + .update(app, |shell, cx| shell.open_block_link(target, cx)) + .ok() + != Some(true) + { + app.open_url(&url); + } }); - load_doc_into_playground( - view, - doc_id, - &store.active_workspace().id, - &entry.session, - cx, - ) }); - let subscription = cx.observe(&entity, |this: &mut DesktopShellView, _view, cx| { - this.sync_editors_from_observer(cx); - }); - *slot = Some(MountedEditor { - workspace_id: store.active_workspace().id.clone(), - doc_id: doc_id.to_string(), - last_synced_store_rev: entry.revision, - last_synced_store_sv: store_sv, - last_seen_view_rev: view_rev, - last_seen_view_sv: view_sv, - entity: entity.clone(), - _subscription: subscription, - }); - return Some(entity); - } + load_doc_into_playground( + view, + doc_id, + &store.active_workspace().id, + &entry.session, + cx, + ) + }); + let subscription = cx.observe(&entity, |this: &mut DesktopShellView, _view, cx| { + this.sync_editors_from_observer(cx); + }); + Some(MountedEditor { + workspace_id: store.active_workspace().id.clone(), + doc_id: doc_id.to_string(), + last_synced_store_rev: entry.revision, + last_synced_store_sv: entry.session.encode_state_vector_v1().unwrap_or_default(), + last_seen_view_rev: view_rev, + last_seen_view_sv: view_sv, + entity, + _subscription: subscription, + }) + } - let mounted = slot.as_mut()?; - let switched_doc = - mounted.doc_id != doc_id || mounted.workspace_id != store.active_workspace().id; + /// Update a mounted editor: sync bounds, theme, mode, and read-only state, then load a + /// switched document or apply the store diff since the last synced revision. + /// + /// When the editor already shows `doc_id` at the current store revision, encodes no state + /// vector and copies no buffer. + #[allow(clippy::too_many_arguments)] + fn update_mounted( + mounted: &mut MountedEditor, + origin: Option<&str>, + doc_id: &str, + pg_mode: PlaygroundMode, + theme: ThemeMode, + width: f32, + height: f32, + store: &DesktopDocStore, + cx: &mut Context, + ) -> Option> { + let readonly = store.is_readonly_sqlite(); + let entry = store.get_doc(doc_id)?; + let workspace_id = &store.active_workspace().id; + let switched_doc = mounted.doc_id != doc_id || &mounted.workspace_id != workspace_id; + let stale = entry.revision > mounted.last_synced_store_rev; + let pg_theme = playground_theme_for(theme); let entity = mounted.entity.clone(); - let prev_store_sv = mounted.last_synced_store_sv.clone(); - let prev_view = ( - mounted.last_seen_view_rev, - mounted.last_seen_view_sv.clone(), - ); - let (new_view_rev, new_view_sv) = entity.update(cx, |view, cx| { + let base_sv = &mounted.last_synced_store_sv; + let synced = entity.update(cx, |view, cx| { view.set_block_link_origin(origin); view.set_theme(pg_theme, cx); view.set_mode_immediate(pg_mode, cx); view.set_readonly_immediate(readonly, cx); view.set_embedded_bounds(width, height); if switched_doc { - load_doc_into_playground( + Some(load_doc_into_playground( view, doc_id, - &store.active_workspace().id, + workspace_id, &entry.session, cx, - ) - } else if entry.revision > mounted.last_synced_store_rev { - let update = if prev_store_sv.is_empty() { - entry.session.encode_update_v1().unwrap_or_default() + )) + } else if stale { + let update = if base_sv.is_empty() { + entry.session.encode_update_v1() } else { - entry - .session - .encode_diff_v1(&prev_store_sv) - .unwrap_or_default() + entry.session.encode_diff_v1(base_sv) }; - apply_update_to_playground(view, doc_id, &update, cx) + Some(apply_update_to_playground( + view, + doc_id, + &update.unwrap_or_default(), + cx, + )) } else { - prev_view + None } }); - if switched_doc { - mounted.workspace_id = store.active_workspace().id.clone(); - mounted.doc_id = doc_id.to_string(); + if let Some((view_rev, view_sv)) = synced { + if switched_doc { + mounted.workspace_id = workspace_id.clone(); + mounted.doc_id = doc_id.to_string(); + } + mounted.last_synced_store_rev = entry.revision; + mounted.last_synced_store_sv = + entry.session.encode_state_vector_v1().unwrap_or_default(); + mounted.last_seen_view_rev = view_rev; + mounted.last_seen_view_sv = view_sv; } - mounted.last_synced_store_rev = entry.revision; - mounted.last_synced_store_sv = store_sv; - mounted.last_seen_view_rev = new_view_rev; - mounted.last_seen_view_sv = new_view_sv; Some(entity) } @@ -391,24 +390,40 @@ impl DesktopEditorHost { store: &mut DesktopDocStore, cx: &mut Context, ) -> Option> { - let mut slot = self.pane_editors.remove(&pane_id); - let res = Self::ensure_mounted_editor( - &mut slot, - self.workspace_origins - .get(&store.active_workspace().id) - .map(String::as_str), + if store.ensure_doc_hydrated(doc_id).is_err() { + return None; + } + let origin = self + .workspace_origins + .get(&store.active_workspace().id) + .map(String::as_str); + let pg_mode = to_pg_mode(mode); + if let Some(mounted) = self.pane_editors.get_mut(&pane_id) { + return Self::update_mounted( + mounted, + origin, + doc_id, + pg_mode, + theme, + pane_width, + pane_height, + store, + cx, + ); + } + let mounted = Self::mount_editor( + origin, doc_id, - to_pg_mode(mode), + pg_mode, theme, pane_width, pane_height, store, cx, - ); - if let Some(mounted) = slot { - self.pane_editors.insert(pane_id, mounted); - } - res + )?; + let entity = mounted.entity.clone(); + self.pane_editors.insert(pane_id, mounted); + Some(entity) } /// Ensure an interactive `Entity` is mounted for the centered `PeekView`. @@ -424,11 +439,28 @@ impl DesktopEditorHost { store: &mut DesktopDocStore, cx: &mut Context, ) -> Option> { - Self::ensure_mounted_editor( - &mut self.peek_editor, - self.workspace_origins - .get(&store.active_workspace().id) - .map(String::as_str), + if store.ensure_doc_hydrated(doc_id).is_err() { + return None; + } + let origin = self + .workspace_origins + .get(&store.active_workspace().id) + .map(String::as_str); + if let Some(mounted) = self.peek_editor.as_mut() { + return Self::update_mounted( + mounted, + origin, + doc_id, + PlaygroundMode::Page, + theme, + width, + height, + store, + cx, + ); + } + let mounted = Self::mount_editor( + origin, doc_id, PlaygroundMode::Page, theme, @@ -436,7 +468,10 @@ impl DesktopEditorHost { height, store, cx, - ) + )?; + let entity = mounted.entity.clone(); + self.peek_editor = Some(mounted); + Some(entity) } /// Drop any mounted pane editors for panes that have been closed. @@ -679,6 +714,163 @@ mod tests { } } + #[test] + fn clicking_peek_body_moves_keyboard_input_to_the_peek_editor() { + use blocksuite_playground_doc::read::BlockContent; + use ui::PlatformWindow as _; + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-11-28"); + state.open_peek_view("doc-sync"); + let (platform, app, wh, hw) = open_test_shell(state, 1440, 900); + hw.request_frame(); + platform.run_until_parked(); + let text_of = |shell: &DesktopShellView, doc: &str| -> Vec { + let snap = &shell.state().store.get_doc(doc).unwrap().snapshot; + snap.root + .as_ref() + .unwrap() + .walk() + .filter_map(|n| match &n.content { + BlockContent::Paragraph { text, .. } => Some(text.plain.clone()), + _ => None, + }) + .collect() + }; + let (click, arch_before, sync_before) = app + .update(|cx| { + wh.update(cx, |shell, window, cx| { + let pg = shell.editor_host().peek_entity().unwrap(); + let pg = pg.read(cx); + let layout = pg.flow_layout().expect("peek flow layout"); + let block = layout.block("p-sync").expect("peek text block"); + let (origin, canvas) = pg.canvas_rect(window); + let geom = playground::block_flow::page_geometry(f32::from(canvas.width)); + let x = f32::from(origin.x) + geom.column_x + block.x + 12.0; + let y = f32::from(origin.y) + block.y - pg.scroll_offset() + + block.body.height * 0.5; + ( + point(px(x), px(y)), + text_of(shell, "doc-arch"), + text_of(shell, "doc-sync"), + ) + }) + }) + .unwrap(); + hw.simulate_click(click); + hw.request_frame(); + platform.run_until_parked(); + let mut platform_window = hw.clone(); + let mut handler = platform_window + .take_input_handler() + .expect("focused editor input handler"); + handler.replace_text_in_range(None, "Z"); + platform_window.set_input_handler(handler); + hw.request_frame(); + platform.run_until_parked(); + app.update(|cx| { + wh.update(cx, |shell, _, _| { + assert_eq!(text_of(shell, "doc-arch"), arch_before); + let sync_after = text_of(shell, "doc-sync"); + assert_ne!( + sync_after, sync_before, + "typing must reach the peek document" + ); + assert!(sync_after.iter().any(|t| t.contains('Z'))); + }) + }) + .unwrap(); + } + + #[test] + fn cross_workspace_block_link_keeps_split_panes_on_their_own_workspace() { + use blocksuite_playground_doc::read::BlockContent; + const DOC: &str = "doc-arch"; + let marker = |index: usize| format!("Only in workspace {index}"); + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-01"); + let mut other = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-01"); + state.store.switch_workspace(1); + state + .store + .docs + .insert(DOC.into(), other.store.docs.remove(DOC).unwrap()); + for index in [1, 0] { + state.store.switch_workspace(index); + state + .store + .append_paragraph(DOC, &marker(index), 1_764_302_000) + .unwrap(); + } + state.open_split_edgeless_for_active_doc(); + let (platform, app, wh, hw) = open_test_shell(state, 1280, 680); + let frame = || { + for _ in 0..2 { + hw.request_frame(); + platform.run_until_parked(); + } + }; + // Every mounted pane shows its workspace's room and that workspace's copy of `DOC`. + let assert_panes = |expected_panes: usize, index: usize| { + app.update(|cx| { + wh.update(cx, |shell, _, cx| { + let workspace = shell.state.store.workspaces[index].id.clone(); + assert_eq!(shell.state.store.active_workspace().id, workspace); + assert_eq!(shell.state.split.panes.len(), expected_panes); + for pane in &shell.state.split.panes { + assert_eq!(pane.tabs.len(), 1, "{workspace}: tab count"); + assert_eq!(pane.active_route().doc_id(), Some(DOC)); + let pg = shell.editor_host().pane_entity(pane.id).unwrap(); + let pg = pg.read(cx); + assert_eq!(pg.document().workspace.room(), workspace); + let snap = pg + .document() + .workspace + .page(DOC) + .unwrap() + .read_page_snapshot() + .unwrap(); + let texts: Vec = snap + .root + .unwrap() + .walk() + .filter_map(|n| match &n.content { + BlockContent::Paragraph { text, .. } => Some(text.plain.clone()), + _ => None, + }) + .collect(); + assert!(texts.contains(&marker(index)), "{workspace}: content"); + assert!(!texts.contains(&marker(1 - index)), "{workspace}: leak"); + } + }) + .unwrap() + }); + }; + frame(); + assert_panes(2, 0); + let opened = app.update(|cx| { + wh.update(cx, |shell, _, cx| { + let target = playground::BlockLink { + origin: playground::default_block_link_origin(), + workspace_id: shell.state.store.workspaces[1].id.clone(), + doc_id: DOC.into(), + block_id: "p-1".into(), + }; + shell.open_block_link(target, cx) + }) + .unwrap() + }); + assert!(opened); + frame(); + assert_panes(1, 1); + app.update(|cx| { + wh.update(cx, |shell, _, cx| { + shell.state.switch_workspace(0); + cx.notify(); + }) + .unwrap() + }); + frame(); + assert_panes(2, 0); + } + #[test] fn short_window_contains_peek_close_and_split_actions() { let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-11-28"); @@ -770,7 +962,7 @@ mod tests { for index in [0, 1] { app.update(|cx| { wh.update(cx, |shell, _, cx| { - shell.state.store.switch_workspace(index); + shell.state.switch_workspace(index); cx.notify(); }) .unwrap() diff --git a/packages/frontend/desktop/src/lib.rs b/packages/frontend/desktop/src/lib.rs index 2291ce5b03..0dcd3d9bbe 100644 --- a/packages/frontend/desktop/src/lib.rs +++ b/packages/frontend/desktop/src/lib.rs @@ -35,7 +35,8 @@ use ui_tokens::{DARK_THEME, LIGHT_THEME, Rgba, ThemeMode}; use ui_tokens::{bundled_font_bytes, bundled_script_font_bytes}; pub use doc_store::{ - DesktopCollection, DesktopDocMeta, DesktopDocStore, DesktopWorkspace, WorkspaceKind, + DerivedWork, DesktopCollection, DesktopDocMeta, DesktopDocStore, DesktopWorkspace, + WorkspaceKind, }; #[cfg(not(target_family = "wasm"))] pub use draft_store::DiskDraftBackend; @@ -49,6 +50,7 @@ pub use editor_host::DesktopEditorHost; pub use peek_view::{PeekAction, PeekViewState}; pub use quick_search::{QuickCommandId, QuickSearchItem, QuickSearchState}; pub use sidebar::{SidebarSection, SidebarState}; +pub use sidebar_tree::SidebarRowIndex; pub use split_view::{DesktopRoute, DocViewMode, PaneId, PaneState, SplitLayout, TabItem}; pub use state::ThemePreference; pub use wasm_entry::WebDesktopMountOptions; diff --git a/packages/frontend/desktop/src/peek_view.rs b/packages/frontend/desktop/src/peek_view.rs index 699761189f..c2ee91a1ad 100644 --- a/packages/frontend/desktop/src/peek_view.rs +++ b/packages/frontend/desktop/src/peek_view.rs @@ -81,6 +81,8 @@ pub(crate) fn render_peek_view_modal( div() .id("desktop.peek.backdrop") + // Keeps pointer presses on the modal from also focusing the editors behind it. + .occlude() .absolute() .top(px(0.0)) .left(px(0.0)) diff --git a/packages/frontend/desktop/src/quick_search.rs b/packages/frontend/desktop/src/quick_search.rs index f5fc58ca2d..fadd8e26cb 100644 --- a/packages/frontend/desktop/src/quick_search.rs +++ b/packages/frontend/desktop/src/quick_search.rs @@ -186,7 +186,7 @@ pub(crate) fn render_quick_search_modal( div() .id(ui::SharedString::from(format!("desktop.qs.doc.{doc_id}"))) .snapshot( - ui::SharedString::from(format!("desktop.qs.doc.{doc_id}")), + format_args!("desktop.qs.doc.{doc_id}"), Some("desktop.qs.modal"), ) .flex() diff --git a/packages/frontend/desktop/src/showcase.rs b/packages/frontend/desktop/src/showcase.rs index 768f42d12d..a0cf5a4b5b 100644 --- a/packages/frontend/desktop/src/showcase.rs +++ b/packages/frontend/desktop/src/showcase.rs @@ -9,10 +9,10 @@ use blocksuite_playground_doc::{ use y_octo::Any; use crate::doc_store::{ - DesktopCollection, DesktopDocMeta, DesktopDocStore, DesktopWorkspace, LiveDocEntry, - WorkspaceKind, + DesktopCollection, DesktopDocMeta, DesktopDocStore, DesktopWorkspace, WorkspaceKind, + build_basic_doc_session, }; -use affine_client::{FolderForestCache, LinkGraph, WeightedSearchEngine, domain::CollectionRule}; +use affine_client::{LinkGraph, WeightedSearchEngine, domain::CollectionRule}; use affine_store::{ directory::WorkspaceDirectory, workspace_db::{FolderRow, WorkspaceDb}, @@ -49,7 +49,7 @@ impl DesktopDocStore { directory, docs: BTreeMap::new(), folder_rows: Vec::new(), - folder_cache: FolderForestCache::default(), + folder_cache: Default::default(), collections: vec![ DesktopCollection { id: "col-rust-core".into(), @@ -74,6 +74,8 @@ impl DesktopDocStore { next_seq: 100, env_rev: 1, workspace_buckets: BTreeMap::new(), + derived: crate::doc_store::DerivedCache::default(), + writer: None, #[cfg(not(target_family = "wasm"))] sqlite_backing: None, }; @@ -134,7 +136,7 @@ impl DesktopDocStore { index: "a0".into(), }, ]; - store.rebuild_derived(); + store.reindex_all(); store } @@ -565,90 +567,3 @@ fn seed_surface_diagram(session: &mut PageDocSession, surface_id: &str, base_ms: base_ms + 13, ); } - -/// Resolve and backfill `note_id` (first page-visible note) and `surface_id` from a hydrated snapshot. -pub(crate) fn populate_note_and_surface_ids( - entry: &mut LiveDocEntry, - snap: &blocksuite_playground_doc::read::PageSnapshot, -) { - let Some(root) = &snap.root else { - return; - }; - let mut fallback_note: Option = None; - let mut visible_note: Option = None; - let mut surface_id: Option = None; - for child in &root.children { - match &child.content { - blocksuite_playground_doc::read::BlockContent::Note { .. } => { - if child.is_page_visible_note() && visible_note.is_none() { - visible_note = Some(child.id.clone()); - } else if fallback_note.is_none() { - fallback_note = Some(child.id.clone()); - } - } - blocksuite_playground_doc::read::BlockContent::Surface { .. } - if surface_id.is_none() => - { - surface_id = Some(child.id.clone()); - } - _ => {} - } - } - if let Some(id) = visible_note.or(fallback_note) { - entry.note_id = id; - } - if let Some(id) = surface_id { - entry.surface_id = id; - } -} - -pub(crate) fn build_basic_doc_session( - doc_id: &str, - title: &str, - now_ms: u64, - client_id: u64, -) -> Option<(PageDocSession, String, String)> { - let mut s = PageDocSession::new(doc_id, client_id).ok()?; - let note_id = format!("note-{doc_id}"); - let surface_id = format!("surface-{doc_id}"); - s.add_block( - "root", - BlockSpec::Page { - title: title.to_string(), - }, - None, - None, - now_ms, - ) - .ok()?; - s.add_block( - &surface_id, - BlockSpec::Surface, - Some("root"), - None, - now_ms + 1, - ) - .ok()?; - s.add_block( - ¬e_id, - BlockSpec::Note { - xywh: Some("[60,80,500,260]".into()), - }, - Some("root"), - None, - now_ms + 2, - ) - .ok()?; - s.add_block( - &format!("p-init-{doc_id}"), - BlockSpec::Paragraph { - paragraph_type: ParagraphType::Text, - text: format!("{title} — live collaborative Page & Edgeless document."), - }, - Some(¬e_id), - None, - now_ms + 3, - ) - .ok()?; - Some((s, note_id, surface_id)) -} diff --git a/packages/frontend/desktop/src/sidebar.rs b/packages/frontend/desktop/src/sidebar.rs index 3fd7d7c8f5..0326df97c1 100644 --- a/packages/frontend/desktop/src/sidebar.rs +++ b/packages/frontend/desktop/src/sidebar.rs @@ -11,12 +11,19 @@ use ui::{ use ui_tokens::FONT_SANS; use crate::{ - CHEVRON_DOWN_SVG, CHEVRON_RIGHT_SVG, COLLECTION_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, - DesktopPalette, EDGELESS_ICON_SVG, JOURNAL_ICON_SVG, PLUS_ICON_SVG, SEARCH_ICON_SVG, - SETTINGS_ICON_SVG, STAR_ICON_SVG, TAG_ICON_SVG, TRASH_ICON_SVG, doc_store::DesktopDocStore, - sidebar_tree::append_folder_rows, split_view::DesktopRoute, workbench::DesktopShellView, + DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, PLUS_ICON_SVG, SEARCH_ICON_SVG, + SETTINGS_ICON_SVG, TRASH_ICON_SVG, + doc_store::DesktopDocStore, + sidebar_tree::{SidebarRowIndex, nav_row, render_tree_rows}, + split_view::DesktopRoute, + workbench::DesktopShellView, }; +/// Height of everything in `AppSidebar` except the scrollable tree: `10 px` padding above and +/// below, the `40 px` workspace switcher, the `68 px` quick actions, the `71 px` footer, and +/// three `10 px` gaps. +pub(crate) const SIDEBAR_CHROME_HEIGHT: f32 = 229.0; + /// Expandable section identifiers in `AppSidebar`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)] pub enum SidebarSection { @@ -94,344 +101,28 @@ pub(crate) fn clip_label(s: &str, max: usize) -> String { } } -fn nav_row( - id: impl Into, - icon: &'static [u8], - label: impl Into, - badge: Option, - active: bool, - palette: DesktopPalette, -) -> ui::Stateful { - let id_str: ui::SharedString = id.into(); - let label_text = clip_label(&label.into(), 25); - let mut row = div() - .id(id_str) - .flex() - .flex_row() - .items_center() - .justify_between() - .w_full() - .h(px(30.0)) - .px(px(10.0)) - .rounded(px(7.0)) - .overflow_hidden() - .bg(if active { - palette.bg_active - } else { - ui::hsla(0.0, 0.0, 0.0, 0.0) - }) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(px(8.0)) - .flex_1() - .min_w_0() - .overflow_hidden() - .child( - svg() - .data(icon) - .w(px(15.0)) - .h(px(15.0)) - .flex_shrink(0.0) - .text_color(if active { - palette.accent - } else { - palette.text_secondary - }), - ) - .child( - div() - .text_size(px(13.0)) - .font_weight(if active { - FontWeight::MEDIUM - } else { - FontWeight::NORMAL - }) - .text_color(if active { - palette.accent - } else { - palette.text_primary - }) - .child(label_text), - ), - ); - if let Some(badge_text) = badge { - row = row.child( - div() - .px(px(6.0)) - .py(px(1.0)) - .rounded(px(5.0)) - .bg(palette.bg_pill) - .text_size(px(11.0)) - .text_color(palette.text_muted) - .child(badge_text), - ); - } - row -} - -fn section_header( - id: &'static str, - title: &'static str, - expanded: bool, - palette: DesktopPalette, - section: SidebarSection, - cx: &mut Context, -) -> ui::Stateful { - div() - .id(id) - .flex() - .flex_row() - .items_center() - .gap(px(4.0)) - .w_full() - .h(px(24.0)) - .px(px(8.0)) - .mt(px(6.0)) - .on_click(cx.listener(move |this, _, _, cx| { - this.state.sidebar.toggle_section(section); - cx.notify(); - })) - .child( - svg() - .data(if expanded { - CHEVRON_DOWN_SVG - } else { - CHEVRON_RIGHT_SVG - }) - .w(px(12.0)) - .h(px(12.0)) - .text_color(palette.text_muted), - ) - .child( - div() - .text_size(px(11.5)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_muted) - .child(title), - ) -} - /// Render the full left `AppSidebar` panel. +#[allow(clippy::too_many_arguments)] pub(crate) fn render_sidebar( - sidebar: &SidebarState, + sidebar: &mut SidebarState, store: &DesktopDocStore, + rows: &mut SidebarRowIndex, active_route: &DesktopRoute, + viewport_height: f32, palette: DesktopPalette, cx: &mut Context, ) -> impl IntoElement { let ws = store.active_workspace(); - let visible_count = store.visible_docs().len(); - let trash_count = store.trashed_docs().len(); - let journal_count = store.journal_docs().len(); - - let mut tree_col = div() - .flex() - .flex_col() - .w_full() - .gap(px(2.0)) - .flex_1() - .min_h_0(); - - // Primary Navigation: All Docs, Favorites, Journals - tree_col = tree_col - .child( - nav_row( - "desktop.sidebar.all_docs", - DOC_ICON_SVG, - "All Docs", - Some(visible_count.to_string()), - matches!(active_route, DesktopRoute::AllDocs), - palette, - ) - .on_click(cx.listener(|this, _, _, cx| { - this.state.navigate_active_pane(DesktopRoute::AllDocs); - cx.notify(); - })), - ) - .child( - nav_row( - "desktop.sidebar.journals", - JOURNAL_ICON_SVG, - "Journals", - Some(journal_count.to_string()), - matches!(active_route, DesktopRoute::Journals), - palette, - ) - .on_click(cx.listener(|this, _, _, cx| { - this.state.open_today_journal(); - cx.notify(); - })), - ); - - // Favorites section - let fav_open = sidebar - .expanded_sections - .contains(&SidebarSection::Favorites); - tree_col = tree_col.child(section_header( - "desktop.sidebar.sec.favorites", - "Favorites", - fav_open, + let trash_count = store.views().trashed.len(); + let tree_col = render_tree_rows( + rows, + sidebar, + store, + active_route, + (viewport_height - SIDEBAR_CHROME_HEIGHT).max(0.0), palette, - SidebarSection::Favorites, cx, - )); - if fav_open { - for doc in store.favorite_docs() { - let doc_id = doc.id.clone(); - let active = matches!(active_route, DesktopRoute::Doc(id) if id == &doc_id); - tree_col = tree_col.child( - nav_row( - format!("desktop.sidebar.fav.{doc_id}"), - STAR_ICON_SVG, - doc.title.clone(), - None, - active, - palette, - ) - .on_click(cx.listener(move |this, _, _, cx| { - this.state.open_doc_in_active_pane(&doc_id); - cx.notify(); - })), - ); - } - } - - // Folders section - let folders_open = sidebar.expanded_sections.contains(&SidebarSection::Folders); - tree_col = tree_col.child( - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .w_full() - .child(section_header( - "desktop.sidebar.sec.folders", - "Folders", - folders_open, - palette, - SidebarSection::Folders, - cx, - )) - .child({ - let readonly = store.is_readonly_sqlite(); - let btn = div() - .id("desktop.sidebar.new_folder") - .w(px(22.0)) - .h(px(22.0)) - .mr(px(6.0)) - .mt(px(6.0)) - .rounded(px(5.0)) - .flex() - .items_center() - .justify_center() - .when(readonly, |el| el.opacity(0.35)) - .child( - svg() - .data(PLUS_ICON_SVG) - .w(px(13.0)) - .h(px(13.0)) - .text_color(palette.text_muted), - ); - if readonly { - btn - } else { - btn.on_click(cx.listener(|this, _, _, cx| { - this.state.create_folder("New Folder", None); - cx.notify(); - })) - } - }), ); - if folders_open { - let root_folders: Vec<_> = store - .folder_rows - .iter() - .filter(|r| r.folder_type == "folder" && r.parent_id.is_none()) - .collect(); - for folder in root_folders { - tree_col = append_folder_rows( - tree_col, - sidebar, - store, - active_route, - folder.id.as_str(), - 0, - palette, - cx, - ); - } - } - - // Collections section - let cols_open = sidebar - .expanded_sections - .contains(&SidebarSection::Collections); - tree_col = tree_col.child(section_header( - "desktop.sidebar.sec.collections", - "Collections", - cols_open, - palette, - SidebarSection::Collections, - cx, - )); - if cols_open { - for col in &store.collections { - let col_id = col.id.clone(); - let count = store.docs_for_collection(&col_id).len(); - let active = matches!(active_route, DesktopRoute::Collection(id) if id == &col_id); - tree_col = tree_col.child( - nav_row( - format!("desktop.sidebar.col.{col_id}"), - COLLECTION_ICON_SVG, - col.name.clone(), - Some(count.to_string()), - active, - palette, - ) - .on_click(cx.listener(move |this, _, _, cx| { - this.state - .navigate_active_pane(DesktopRoute::Collection(col_id.clone())); - cx.notify(); - })), - ); - } - } - - // Tags section - let tags_open = sidebar.expanded_sections.contains(&SidebarSection::Tags); - tree_col = tree_col.child(section_header( - "desktop.sidebar.sec.tags", - "Tags", - tags_open, - palette, - SidebarSection::Tags, - cx, - )); - if tags_open { - for (tag, _color, count) in store.all_tags_with_counts() { - let tag_clone = tag.clone(); - let active = matches!(active_route, DesktopRoute::Tag(t) if t == &tag_clone); - tree_col = tree_col.child( - nav_row( - format!("desktop.sidebar.tag.{tag}"), - TAG_ICON_SVG, - format!("#{tag}"), - Some(count.to_string()), - active, - palette, - ) - .on_click(cx.listener(move |this, _, _, cx| { - this.state - .navigate_active_pane(DesktopRoute::Tag(tag_clone.clone())); - cx.notify(); - })), - ); - } - } // Workspace header & quick actions let ws_header = div() @@ -459,7 +150,7 @@ pub(crate) fn render_sidebar( { return; } - this.state.store.switch_workspace(next); + this.state.switch_workspace(next); cx.notify(); })) .child( @@ -731,10 +422,7 @@ pub(crate) fn render_sidebar( .overflow_hidden() .on_scroll(cx.listener(|this, event: &ui::ScrollEvent, _, cx| { let dy: f32 = event.delta.pixel_delta(px(20.0)).y.into(); - let est_rows = (this.state.store.docs.len() - + this.state.store.folder_rows.len() - + 12) as f32; - let max_scroll = (est_rows * 30.0 - 360.0).max(0.0); + let max_scroll = this.sidebar_rows.max_scroll(); this.state.sidebar.scroll_y = (this.state.sidebar.scroll_y - dy).clamp(0.0, max_scroll); cx.notify(); diff --git a/packages/frontend/desktop/src/sidebar_tree.rs b/packages/frontend/desktop/src/sidebar_tree.rs index 8002483221..e4255e76e3 100644 --- a/packages/frontend/desktop/src/sidebar_tree.rs +++ b/packages/frontend/desktop/src/sidebar_tree.rs @@ -1,167 +1,673 @@ -//! Hierarchical folder & document tree renderer for `AppSidebar`. +//! Virtualized navigation tree of `AppSidebar`: primary navigation, Favorites, the +//! hierarchical Folders tree, Collections, and Tags. +//! +//! The tree is first flattened into ordered rows by expansion state. The row index is rebuilt +//! only when the document metadata revision or the expansion state changes. Each frame then +//! asks [`ui_kit::VirtualList`] for the rows that intersect the viewport and the overscan, and +//! builds elements for those rows only. + +use std::collections::BTreeSet; use ui::{ - Context, InteractiveElement, ParentElement, StatefulInteractiveElement, Styled, div, px, svg, + Context, FontWeight, InteractiveElement, IntoElement, ParentElement, + StatefulInteractiveElement, Styled, div, prelude::FluentBuilder as _, px, svg, }; +use ui_kit::{VirtualList, VirtualWindow}; use crate::{ - CHEVRON_DOWN_SVG, CHEVRON_RIGHT_SVG, DOC_ICON_SVG, DesktopPalette, FOLDER_ICON_SVG, - doc_store::DesktopDocStore, - sidebar::{SidebarState, clip_label}, + CHEVRON_DOWN_SVG, CHEVRON_RIGHT_SVG, COLLECTION_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, + DesktopPalette, FOLDER_ICON_SVG, JOURNAL_ICON_SVG, PLUS_ICON_SVG, STAR_ICON_SVG, TAG_ICON_SVG, + doc_store::{DesktopDocStore, DocViews, SidebarFolderTree}, + sidebar::{SidebarSection, SidebarState, clip_label}, split_view::DesktopRoute, workbench::DesktopShellView, }; -#[allow(clippy::too_many_arguments)] -pub(crate) fn append_folder_rows( - mut col: ui::Div, +/// Vertical gap between consecutive tree rows. +const ROW_GAP: f32 = 2.0; +/// Rows mounted above and below the viewport, in pixels. +const OVERSCAN_PX: f32 = 240.0; +/// Deepest folder level whose children the tree still shows. +const MAX_EXPANDED_DEPTH: usize = 3; + +/// One flattened row of the sidebar navigation tree. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SidebarRow { + AllDocs, + Journals, + Section(SidebarSection), + Favorite(String), + Folder { + id: String, + depth: usize, + }, + FolderDoc { + folder_id: String, + doc_id: String, + depth: usize, + }, + Collection(usize), + Tag(usize), +} + +impl SidebarRow { + /// Layout height of the row, its top margin, and the gap below it. + fn extent(&self) -> f32 { + let height = match self { + Self::AllDocs + | Self::Journals + | Self::Favorite(_) + | Self::Collection(_) + | Self::Tag(_) => 30.0, + // 24 px header below a 6 px top margin. + Self::Section(_) => 30.0, + Self::Folder { .. } => 28.0, + Self::FolderDoc { .. } => 26.0, + }; + height + ROW_GAP + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct RowKey { + meta_rev: u64, + sections: BTreeSet, + folders: BTreeSet, +} + +/// Ordered sidebar rows and their [`VirtualList`] for one metadata revision and expansion state. +#[derive(Debug, Default)] +pub struct SidebarRowIndex { + key: Option, + rows: Vec, + list: Option, + viewport_height: f32, + builds: u64, + last_window: Option, +} + +impl SidebarRowIndex { + /// Number of row index builds since the shell started. + pub fn builds(&self) -> u64 { + self.builds + } + + /// Total number of rows of the expanded tree. + pub fn row_count(&self) -> usize { + self.rows.len() + } + + /// Rows the last frame built elements for. + pub fn mounted_rows(&self) -> usize { + self.last_window + .as_ref() + .map_or(0, |w| w.visible_range.len()) + } + + /// Height of the scrollable tree viewport of the last frame. + pub fn viewport_height(&self) -> f32 { + self.viewport_height + } + + /// Largest scroll offset that keeps the last row inside the viewport. + pub fn max_scroll(&self) -> f32 { + let content = self + .list + .as_ref() + .map_or(0.0, |l| (l.total_height() - ROW_GAP).max(0.0)); + (content - self.viewport_height).max(0.0) + } + + fn sync(&mut self, sidebar: &SidebarState, store: &DesktopDocStore) { + let meta_rev = store.derived.meta_rev; + if self.key.as_ref().is_some_and(|k| { + k.meta_rev == meta_rev + && k.sections == sidebar.expanded_sections + && k.folders == sidebar.expanded_folders + }) { + return; + } + self.rows = build_rows(sidebar, store); + self.list = Some(VirtualList::variable( + self.rows.iter().map(SidebarRow::extent).collect(), + )); + self.key = Some(RowKey { + meta_rev, + sections: sidebar.expanded_sections.clone(), + folders: sidebar.expanded_folders.clone(), + }); + self.builds += 1; + } +} + +fn build_rows(sidebar: &SidebarState, store: &DesktopDocStore) -> Vec { + let views = store.views(); + let open = |s| sidebar.expanded_sections.contains(&s); + let mut rows = vec![SidebarRow::AllDocs, SidebarRow::Journals]; + rows.push(SidebarRow::Section(SidebarSection::Favorites)); + if open(SidebarSection::Favorites) { + rows.extend(views.favorites.iter().cloned().map(SidebarRow::Favorite)); + } + rows.push(SidebarRow::Section(SidebarSection::Folders)); + if open(SidebarSection::Folders) { + for id in views.folders.roots() { + push_folder_rows(&mut rows, &views.folders, sidebar, id, 0); + } + } + rows.push(SidebarRow::Section(SidebarSection::Collections)); + if open(SidebarSection::Collections) { + rows.extend((0..store.collections.len()).map(SidebarRow::Collection)); + } + rows.push(SidebarRow::Section(SidebarSection::Tags)); + if open(SidebarSection::Tags) { + rows.extend((0..views.tags.len()).map(SidebarRow::Tag)); + } + rows +} + +fn push_folder_rows( + rows: &mut Vec, + tree: &SidebarFolderTree, sidebar: &SidebarState, - store: &DesktopDocStore, - active_route: &DesktopRoute, folder_id: &str, depth: usize, +) { + rows.push(SidebarRow::Folder { + id: folder_id.to_owned(), + depth, + }); + if !sidebar.expanded_folders.contains(folder_id) || depth >= MAX_EXPANDED_DEPTH { + return; + } + for child in tree.child_folders(folder_id) { + push_folder_rows(rows, tree, sidebar, child, depth + 1); + } + rows.extend( + tree.docs(folder_id) + .iter() + .map(|doc_id| SidebarRow::FolderDoc { + folder_id: folder_id.to_owned(), + doc_id: doc_id.clone(), + depth, + }), + ); +} + +/// Build the elements of the visible tree rows plus the spacers that stand in for the rest. +pub(crate) fn render_tree_rows( + index: &mut SidebarRowIndex, + sidebar: &mut SidebarState, + store: &DesktopDocStore, + active_route: &DesktopRoute, + viewport_height: f32, palette: DesktopPalette, cx: &mut Context, ) -> ui::Div { - let Some(folder) = store - .folder_rows - .iter() - .find(|r| r.folder_type == "folder" && r.id == folder_id) - else { - return col; - }; - let expanded = sidebar.expanded_folders.contains(folder_id); - let fid = folder.id.clone(); - let fid_nav = folder.id.clone(); - let indent = (depth as f32) * 14.0; - let active = matches!(active_route, DesktopRoute::Folder(id) if id == folder_id); - - col = col.child( - div() - .id(ui::SharedString::from(format!( - "desktop.sidebar.folder.{folder_id}" - ))) - .snapshot( - ui::SharedString::from(format!("desktop.sidebar.folder.{folder_id}")), - Some("desktop.sidebar"), - ) - .flex() - .flex_row() - .items_center() - .w_full() - .h(px(28.0)) - .pl(px(8.0 + indent)) - .pr(px(8.0)) - .gap(px(6.0)) - .rounded(px(6.0)) - .bg(if active { - palette.bg_active - } else { - ui::hsla(0.0, 0.0, 0.0, 0.0) - }) - .on_click(cx.listener(move |this, _, _, cx| { - this.state.sidebar.toggle_folder(&fid); - this.state - .navigate_active_pane(DesktopRoute::Folder(fid_nav.clone())); - cx.notify(); - })) - .child( - svg() - .data(if expanded { - CHEVRON_DOWN_SVG - } else { - CHEVRON_RIGHT_SVG - }) - .w(px(11.0)) - .h(px(11.0)) - .text_color(palette.text_muted), - ) - .child( - svg() - .data(FOLDER_ICON_SVG) - .w(px(14.0)) - .h(px(14.0)) - .text_color(palette.text_secondary), - ) - .child( - div() - .text_size(px(12.5)) - .text_color(palette.text_primary) - .child(folder.data.clone()), - ), - ); - - if expanded && depth < 3 { - let child_folders: Vec = store - .folder_rows - .iter() - .filter(|r| r.folder_type == "folder" && r.parent_id.as_deref() == Some(folder_id)) - .map(|r| r.id.clone()) - .collect(); - for child_id in child_folders { - col = append_folder_rows( - col, - sidebar, - store, - active_route, - &child_id, - depth + 1, - palette, - cx, - ); - } - for doc in store.docs_in_folder(folder_id) { - let doc_id = doc.id.clone(); - let doc_active = matches!(active_route, DesktopRoute::Doc(id) if id == &doc_id); - let doc_label = clip_label(&doc.title, 22usize.saturating_sub(depth * 2)); - col = col.child( - div() - .id(ui::SharedString::from(format!( - "desktop.sidebar.fdoc.{folder_id}.{doc_id}" - ))) - .flex() - .flex_row() - .items_center() - .w_full() - .h(px(26.0)) - .pl(px(26.0 + indent)) - .pr(px(8.0)) - .gap(px(6.0)) - .rounded(px(6.0)) - .overflow_hidden() - .bg(if doc_active { - palette.bg_active - } else { - ui::hsla(0.0, 0.0, 0.0, 0.0) - }) - .on_click(cx.listener(move |this, _, _, cx| { - this.state.open_doc_in_active_pane(&doc_id); - cx.notify(); - })) - .child( - svg() - .data(DOC_ICON_SVG) - .w(px(13.0)) - .h(px(13.0)) - .flex_shrink(0.0) - .text_color(if doc_active { - palette.accent - } else { - palette.text_muted - }), - ) - .child( - div() - .text_size(px(12.5)) - .text_color(if doc_active { - palette.accent - } else { - palette.text_secondary - }) - .child(doc_label), - ), - ); - } + index.sync(sidebar, store); + index.viewport_height = viewport_height; + sidebar.scroll_y = sidebar.scroll_y.clamp(0.0, index.max_scroll()); + let window = index + .list + .as_ref() + .map(|l| l.window(viewport_height, sidebar.scroll_y, OVERSCAN_PX)) + .unwrap_or(VirtualWindow { + visible_range: 0..0, + leading_spacer: 0.0, + trailing_spacer: 0.0, + total_height: 0.0, + }); + let views = store.views(); + let mut col = div() + .flex() + .flex_col() + .w_full() + .gap(px(ROW_GAP)) + .flex_1() + .min_h_0(); + // The flex gap after each spacer is part of the extent of the rows it stands in for. + if window.visible_range.start > 0 { + col = col.child(div().w_full().h(px(window.leading_spacer - ROW_GAP))); } + for row in &index.rows[window.visible_range.clone()] { + col = col.child(render_row( + row, + sidebar, + store, + &views, + active_route, + palette, + cx, + )); + } + if window.visible_range.end < index.rows.len() { + col = col.child(div().w_full().h(px(window.trailing_spacer - ROW_GAP))); + } + index.last_window = Some(window); col } + +#[allow(clippy::too_many_arguments)] +fn render_row( + row: &SidebarRow, + sidebar: &SidebarState, + store: &DesktopDocStore, + views: &DocViews, + active_route: &DesktopRoute, + palette: DesktopPalette, + cx: &mut Context, +) -> ui::AnyElement { + match row { + SidebarRow::AllDocs => nav_row( + "desktop.sidebar.all_docs", + DOC_ICON_SVG, + "All Docs", + Some(views.visible.len().to_string()), + matches!(active_route, DesktopRoute::AllDocs), + palette, + ) + .snapshot("desktop.sidebar.all_docs", Some("desktop.sidebar")) + .on_click(cx.listener(|this, _, _, cx| { + this.state.navigate_active_pane(DesktopRoute::AllDocs); + cx.notify(); + })) + .into_any_element(), + SidebarRow::Journals => nav_row( + "desktop.sidebar.journals", + JOURNAL_ICON_SVG, + "Journals", + Some(views.journals.len().to_string()), + matches!(active_route, DesktopRoute::Journals), + palette, + ) + .on_click(cx.listener(|this, _, _, cx| { + this.state.open_today_journal(); + cx.notify(); + })) + .into_any_element(), + SidebarRow::Section(section) => render_section(*section, sidebar, store, palette, cx), + SidebarRow::Favorite(doc_id) => { + let title = store + .get_doc(doc_id) + .map(|e| e.meta.title.clone()) + .unwrap_or_default(); + let active = matches!(active_route, DesktopRoute::Doc(id) if id == doc_id); + let doc_id = doc_id.clone(); + nav_row( + format!("desktop.sidebar.fav.{doc_id}"), + STAR_ICON_SVG, + title, + None, + active, + palette, + ) + .on_click(cx.listener(move |this, _, _, cx| { + this.state.open_doc_in_active_pane(&doc_id); + cx.notify(); + })) + .into_any_element() + } + SidebarRow::Folder { id, depth } => { + let name = views.folders.name(id).unwrap_or_default().to_owned(); + render_folder(id, &name, *depth, sidebar, active_route, palette, cx) + } + SidebarRow::FolderDoc { + folder_id, + doc_id, + depth, + } => { + let title = store + .get_doc(doc_id) + .map(|e| e.meta.title.as_str()) + .unwrap_or_default(); + render_folder_doc(folder_id, doc_id, title, *depth, active_route, palette, cx) + } + SidebarRow::Collection(index) => { + let Some(col) = store.collections.get(*index) else { + return div().into_any_element(); + }; + let count = views.collection_counts.get(*index).copied().unwrap_or(0); + let col_id = col.id.clone(); + let active = matches!(active_route, DesktopRoute::Collection(id) if id == &col_id); + nav_row( + format!("desktop.sidebar.col.{col_id}"), + COLLECTION_ICON_SVG, + col.name.clone(), + Some(count.to_string()), + active, + palette, + ) + .on_click(cx.listener(move |this, _, _, cx| { + this.state + .navigate_active_pane(DesktopRoute::Collection(col_id.clone())); + cx.notify(); + })) + .into_any_element() + } + SidebarRow::Tag(index) => { + let Some((tag, _color, count)) = views.tags.get(*index) else { + return div().into_any_element(); + }; + let tag = tag.clone(); + let active = matches!(active_route, DesktopRoute::Tag(t) if t == &tag); + nav_row( + format!("desktop.sidebar.tag.{tag}"), + TAG_ICON_SVG, + format!("#{tag}"), + Some(count.to_string()), + active, + palette, + ) + .on_click(cx.listener(move |this, _, _, cx| { + this.state + .navigate_active_pane(DesktopRoute::Tag(tag.clone())); + cx.notify(); + })) + .into_any_element() + } + } +} + +fn render_section( + section: SidebarSection, + sidebar: &SidebarState, + store: &DesktopDocStore, + palette: DesktopPalette, + cx: &mut Context, +) -> ui::AnyElement { + let expanded = sidebar.expanded_sections.contains(§ion); + let (id, title) = match section { + SidebarSection::Favorites => ("desktop.sidebar.sec.favorites", "Favorites"), + SidebarSection::Folders => ("desktop.sidebar.sec.folders", "Folders"), + SidebarSection::Collections => ("desktop.sidebar.sec.collections", "Collections"), + SidebarSection::Tags => ("desktop.sidebar.sec.tags", "Tags"), + }; + let header = section_header(id, title, expanded, palette, section, cx); + if section != SidebarSection::Folders { + return header.into_any_element(); + } + let readonly = store.is_readonly_sqlite(); + let btn = div() + .id("desktop.sidebar.new_folder") + .w(px(22.0)) + .h(px(22.0)) + .mr(px(6.0)) + .mt(px(6.0)) + .rounded(px(5.0)) + .flex() + .items_center() + .justify_center() + .when(readonly, |el| el.opacity(0.35)) + .child( + svg() + .data(PLUS_ICON_SVG) + .w(px(13.0)) + .h(px(13.0)) + .text_color(palette.text_muted), + ); + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .w_full() + .child(header) + .child(if readonly { + btn + } else { + btn.on_click(cx.listener(|this, _, _, cx| { + this.state.create_folder("New Folder", None); + cx.notify(); + })) + }) + .into_any_element() +} + +fn render_folder( + folder_id: &str, + name: &str, + depth: usize, + sidebar: &SidebarState, + active_route: &DesktopRoute, + palette: DesktopPalette, + cx: &mut Context, +) -> ui::AnyElement { + let expanded = sidebar.expanded_folders.contains(folder_id); + let fid = folder_id.to_owned(); + let fid_nav = folder_id.to_owned(); + let indent = (depth as f32) * 14.0; + let active = matches!(active_route, DesktopRoute::Folder(id) if id == folder_id); + div() + .id(ui::SharedString::from(format!( + "desktop.sidebar.folder.{folder_id}" + ))) + .snapshot( + format_args!("desktop.sidebar.folder.{folder_id}"), + Some("desktop.sidebar"), + ) + .flex() + .flex_row() + .items_center() + .w_full() + .h(px(28.0)) + .pl(px(8.0 + indent)) + .pr(px(8.0)) + .gap(px(6.0)) + .rounded(px(6.0)) + .bg(if active { + palette.bg_active + } else { + ui::hsla(0.0, 0.0, 0.0, 0.0) + }) + .on_click(cx.listener(move |this, _, _, cx| { + this.state.sidebar.toggle_folder(&fid); + this.state + .navigate_active_pane(DesktopRoute::Folder(fid_nav.clone())); + cx.notify(); + })) + .child( + svg() + .data(if expanded { + CHEVRON_DOWN_SVG + } else { + CHEVRON_RIGHT_SVG + }) + .w(px(11.0)) + .h(px(11.0)) + .text_color(palette.text_muted), + ) + .child( + svg() + .data(FOLDER_ICON_SVG) + .w(px(14.0)) + .h(px(14.0)) + .text_color(palette.text_secondary), + ) + .child( + div() + .text_size(px(12.5)) + .text_color(palette.text_primary) + .child(name.to_owned()), + ) + .into_any_element() +} + +fn render_folder_doc( + folder_id: &str, + doc_id: &str, + title: &str, + depth: usize, + active_route: &DesktopRoute, + palette: DesktopPalette, + cx: &mut Context, +) -> ui::AnyElement { + let indent = (depth as f32) * 14.0; + let doc_active = matches!(active_route, DesktopRoute::Doc(id) if id == doc_id); + let doc_label = clip_label(title, 22usize.saturating_sub(depth * 2)); + let open_id = doc_id.to_owned(); + div() + .id(ui::SharedString::from(format!( + "desktop.sidebar.fdoc.{folder_id}.{doc_id}" + ))) + .flex() + .flex_row() + .items_center() + .w_full() + .h(px(26.0)) + .pl(px(26.0 + indent)) + .pr(px(8.0)) + .gap(px(6.0)) + .rounded(px(6.0)) + .overflow_hidden() + .bg(if doc_active { + palette.bg_active + } else { + ui::hsla(0.0, 0.0, 0.0, 0.0) + }) + .on_click(cx.listener(move |this, _, _, cx| { + this.state.open_doc_in_active_pane(&open_id); + cx.notify(); + })) + .child( + svg() + .data(DOC_ICON_SVG) + .w(px(13.0)) + .h(px(13.0)) + .flex_shrink(0.0) + .text_color(if doc_active { + palette.accent + } else { + palette.text_muted + }), + ) + .child( + div() + .text_size(px(12.5)) + .text_color(if doc_active { + palette.accent + } else { + palette.text_secondary + }) + .child(doc_label), + ) + .into_any_element() +} + +pub(crate) fn nav_row( + id: impl Into, + icon: &'static [u8], + label: impl Into, + badge: Option, + active: bool, + palette: DesktopPalette, +) -> ui::Stateful { + let id_str: ui::SharedString = id.into(); + let label_text = clip_label(&label.into(), 25); + let mut row = div() + .id(id_str) + .flex() + .flex_row() + .items_center() + .justify_between() + .w_full() + .h(px(30.0)) + .px(px(10.0)) + .rounded(px(7.0)) + .overflow_hidden() + .bg(if active { + palette.bg_active + } else { + ui::hsla(0.0, 0.0, 0.0, 0.0) + }) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(8.0)) + .flex_1() + .min_w_0() + .overflow_hidden() + .child( + svg() + .data(icon) + .w(px(15.0)) + .h(px(15.0)) + .flex_shrink(0.0) + .text_color(if active { + palette.accent + } else { + palette.text_secondary + }), + ) + .child( + div() + .text_size(px(13.0)) + .font_weight(if active { + FontWeight::MEDIUM + } else { + FontWeight::NORMAL + }) + .text_color(if active { + palette.accent + } else { + palette.text_primary + }) + .child(label_text), + ), + ); + if let Some(badge_text) = badge { + row = row.child( + div() + .px(px(6.0)) + .py(px(1.0)) + .rounded(px(5.0)) + .bg(palette.bg_pill) + .text_size(px(11.0)) + .text_color(palette.text_muted) + .child(badge_text), + ); + } + row +} + +fn section_header( + id: &'static str, + title: &'static str, + expanded: bool, + palette: DesktopPalette, + section: SidebarSection, + cx: &mut Context, +) -> ui::Stateful { + div() + .id(id) + .flex() + .flex_row() + .items_center() + .gap(px(4.0)) + .w_full() + .h(px(24.0)) + .px(px(8.0)) + .mt(px(6.0)) + .on_click(cx.listener(move |this, _, _, cx| { + this.state.sidebar.toggle_section(section); + cx.notify(); + })) + .child( + svg() + .data(if expanded { + CHEVRON_DOWN_SVG + } else { + CHEVRON_RIGHT_SVG + }) + .w(px(12.0)) + .h(px(12.0)) + .text_color(palette.text_muted), + ) + .child( + div() + .text_size(px(11.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_muted) + .child(title), + ) +} diff --git a/packages/frontend/desktop/src/sqlite_loader.rs b/packages/frontend/desktop/src/sqlite_loader.rs index 338761e5b9..35039f7bdf 100644 --- a/packages/frontend/desktop/src/sqlite_loader.rs +++ b/packages/frontend/desktop/src/sqlite_loader.rs @@ -4,10 +4,14 @@ use std::{ collections::BTreeMap, path::{Path, PathBuf}, - sync::{OnceLock, mpsc}, + sync::{ + Arc, OnceLock, + atomic::{AtomicU64, Ordering}, + mpsc, + }, }; -use affine_client::{FolderForestCache, LinkGraph, WeightedSearchEngine}; +use affine_client::{LinkGraph, WeightedSearchEngine}; use affine_store::{ directory::{DocMode, WorkspaceDirectory}, sqlite::SqliteDocStorage, @@ -33,8 +37,11 @@ enum SqliteWorkerReq { LoadDoc { path: PathBuf, doc_id: String, + opens: Arc, reply: mpsc::Sender>>>, }, + /// The last handle of a backing went away: close its read connection. + Release { opens: Arc }, } async fn read_workspace_snapshot(storage: &SqliteDocStorage) -> Result { @@ -86,99 +93,218 @@ fn is_readonly_shm_error(err: &anyhow::Error) -> bool { msg.contains("readonly database") || msg.contains("unable to open database") } +/// Identity of an on-disk SQLite file. A replaced or rewritten file gets a new identity. +#[derive(Clone, Debug, PartialEq, Eq)] +struct FileIdentity { + len: u64, + modified: Option, + #[cfg(unix)] + inode: (u64, u64), +} + +impl FileIdentity { + fn of(path: &Path) -> Result { + let meta = std::fs::metadata(path) + .with_context(|| format!("reading SQLite file metadata `{}`", path.display()))?; + Ok(Self { + len: meta.len(), + modified: meta.modified().ok(), + #[cfg(unix)] + inode: { + use std::os::unix::fs::MetadataExt as _; + (meta.dev(), meta.ino()) + }, + }) + } +} + +/// Read-only connection pool of the current backing, kept by the worker between requests. +/// +/// No read transaction outlives a request, so a reused connection still observes new WAL +/// commits of a live writer. +struct ReadConnection { + opens: Arc, + path: PathBuf, + identity: FileIdentity, + storage: SqliteDocStorage, + immutable: bool, +} + +impl ReadConnection { + /// `true` while the connection still reads the file at `path` with `identity`. + fn serves(&self, path: &Path, identity: &FileIdentity) -> bool { + self.path == path && &self.identity == identity && !(self.immutable && has_sidecar(path)) + } +} + +/// `true` when a `-wal` or `-shm` sidecar exists, which marks a database with a live writer. +fn has_sidecar(path: &Path) -> bool { + ["-wal", "-shm"].iter().any(|suffix| { + let mut sidecar = path.as_os_str().to_owned(); + sidecar.push(suffix); + Path::new(&sidecar).exists() + }) +} + +async fn close_connection(cached: &mut Option) { + if let Some(conn) = cached.take() { + conn.storage.close().await; + } +} + +async fn read_doc(storage: &SqliteDocStorage, doc_id: &str) -> Result>> { + storage + .get_doc_readonly(doc_id) + .await + .map(|r| r.map(|rec| rec.bin)) + .map_err(anyhow::Error::from) +} + +/// Read one document through the cached read connection of `path`, opening it first when the +/// cache holds another file or a stale identity of this one. +async fn load_doc( + cached: &mut Option, + path: &Path, + doc_id: &str, + opens: &Arc, +) -> Result>> { + let canonical = std::fs::canonicalize(path) + .with_context(|| format!("canonicalizing SQLite path `{}`", path.display()))?; + let identity = FileIdentity::of(&canonical)?; + if cached + .as_ref() + .is_some_and(|c| !Arc::ptr_eq(&c.opens, opens) || !c.serves(&canonical, &identity)) + { + close_connection(cached).await; + } + let path_str = canonical.to_string_lossy().into_owned(); + let conn = cached.get_or_insert_with(|| { + opens.fetch_add(1, Ordering::Relaxed); + ReadConnection { + opens: opens.clone(), + path: canonical.clone(), + identity: identity.clone(), + storage: SqliteDocStorage::open_read_only(path_str.clone()), + immutable: false, + } + }); + match read_doc(&conn.storage, doc_id).await { + Ok(bytes) => Ok(bytes), + Err(err) if !conn.immutable && is_readonly_shm_error(&err) => { + close_connection(cached).await; + let storage = SqliteDocStorage::open_backup_immutable(path_str)?; + opens.fetch_add(1, Ordering::Relaxed); + let conn = cached.insert(ReadConnection { + opens: opens.clone(), + path: canonical, + identity, + storage, + immutable: true, + }); + let res = read_doc(&conn.storage, doc_id).await; + if res.is_err() { + close_connection(cached).await; + } + res + } + Err(err) => { + close_connection(cached).await; + Err(err) + } + } +} + +static SQLITE_WORKER: OnceLock, String>> = + OnceLock::new(); + /// Dedicated single-thread background Tokio worker for read-only SQLite access. /// -/// Opens a fresh read-only [`SqliteDocStorage`] per request via the single authoritative -/// [`SqliteDocStorage::open_read_only`] entry point and closes it before returning so live -/// external WAL writes are always observed immediately. When the parent directory itself is -/// read-only and no `-wal`/`-shm` sidecar exists, falls back to -/// [`SqliteDocStorage::open_backup_immutable`]. +/// Opens workspaces through the single authoritative [`SqliteDocStorage::open_read_only`] +/// entry point. Document reads reuse one read-only connection of the current backing and +/// reopen it when the backing changes, the file is replaced, or its last handle is released. +/// When the parent directory itself is read-only and no `-wal`/`-shm` sidecar exists, falls +/// back to [`SqliteDocStorage::open_backup_immutable`] and leaves it as soon as a sidecar appears. fn sqlite_worker() -> Result<&'static mpsc::Sender> { - static TX: OnceLock, String>> = - OnceLock::new(); - TX.get_or_init(|| { - let (tx, rx) = mpsc::channel::(); - std::thread::Builder::new() - .name("affine-desktop-sqlite-ro".into()) - .spawn(move || { - let Ok(rt) = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - else { - return; - }; - while let Ok(req) = rx.recv() { - match req { - SqliteWorkerReq::OpenWorkspace { path, reply } => { - let res = rt.block_on(async { - let canonical_path = - std::fs::canonicalize(&path).with_context(|| { - format!("canonicalizing SQLite path `{}`", path.display()) - })?; - let path_str = canonical_path.to_string_lossy().into_owned(); - let storage = SqliteDocStorage::open_read_only(path_str.clone()); - let snapshot_res = read_workspace_snapshot(&storage).await; - storage.close().await; - match snapshot_res { - Ok(ok) => Ok(ok), - Err(err) if is_readonly_shm_error(&err) => { - let immutable = - SqliteDocStorage::open_backup_immutable(path_str) - .map_err(anyhow::Error::from)?; - let fallback = read_workspace_snapshot(&immutable).await; - immutable.close().await; - fallback - } - Err(err) => Err(err), + SQLITE_WORKER + .get_or_init(|| { + let (tx, rx) = mpsc::channel::(); + std::thread::Builder::new() + .name("affine-desktop-sqlite-ro".into()) + .spawn(move || { + let Ok(rt) = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + else { + return; + }; + let mut cached: Option = None; + while let Ok(req) = rx.recv() { + match req { + SqliteWorkerReq::OpenWorkspace { path, reply } => { + let _ = reply.send(rt.block_on(open_workspace(&path))); + } + SqliteWorkerReq::LoadDoc { + path, + doc_id, + opens, + reply, + } => { + let res = + rt.block_on(load_doc(&mut cached, &path, &doc_id, &opens)); + let _ = reply.send(res); + } + SqliteWorkerReq::Release { opens } => { + if cached + .as_ref() + .is_some_and(|c| Arc::ptr_eq(&c.opens, &opens)) + { + rt.block_on(close_connection(&mut cached)); } - }); - let _ = reply.send(res); - } - SqliteWorkerReq::LoadDoc { - path, - doc_id, - reply, - } => { - let res = rt.block_on(async { - let canonical_path = - std::fs::canonicalize(&path).with_context(|| { - format!("canonicalizing SQLite path `{}`", path.display()) - })?; - let path_str = canonical_path.to_string_lossy().into_owned(); - let storage = SqliteDocStorage::open_read_only(path_str.clone()); - let doc_res = storage - .get_doc_readonly(&doc_id) - .await - .map(|r| r.map(|rec| rec.bin)) - .map_err(anyhow::Error::from); - storage.close().await; - match doc_res { - Ok(ok) => Ok(ok), - Err(err) if is_readonly_shm_error(&err) => { - let immutable = - SqliteDocStorage::open_backup_immutable(path_str) - .map_err(anyhow::Error::from)?; - let fallback = immutable - .get_doc_readonly(&doc_id) - .await - .map(|r| r.map(|rec| rec.bin)) - .map_err(anyhow::Error::from); - immutable.close().await; - fallback - } - Err(err) => Err(err), - } - }); - let _ = reply.send(res); + } } } - } - }) - .map(|_| tx) - .map_err(|e| format!("failed to spawn affine-desktop-sqlite-ro worker thread: {e}")) - }) - .as_ref() - .map_err(|e| anyhow::anyhow!("{e}")) + }) + .map(|_| tx) + .map_err(|e| format!("failed to spawn affine-desktop-sqlite-ro worker thread: {e}")) + }) + .as_ref() + .map_err(|e| anyhow::anyhow!("{e}")) +} + +async fn open_workspace(path: &Path) -> Result { + let canonical_path = std::fs::canonicalize(path) + .with_context(|| format!("canonicalizing SQLite path `{}`", path.display()))?; + let path_str = canonical_path.to_string_lossy().into_owned(); + let storage = SqliteDocStorage::open_read_only(path_str.clone()); + let snapshot_res = read_workspace_snapshot(&storage).await; + storage.close().await; + match snapshot_res { + Ok(ok) => Ok(ok), + Err(err) if is_readonly_shm_error(&err) => { + let immutable = + SqliteDocStorage::open_backup_immutable(path_str).map_err(anyhow::Error::from)?; + let fallback = read_workspace_snapshot(&immutable).await; + immutable.close().await; + fallback + } + Err(err) => Err(err), + } +} + +/// Releases the worker read connection of a backing once its last handle is dropped. +#[derive(Debug)] +struct BackingLease { + opens: Arc, +} + +impl Drop for BackingLease { + fn drop(&mut self) { + if let Some(Ok(tx)) = SQLITE_WORKER.get() { + let _ = tx.send(SqliteWorkerReq::Release { + opens: self.opens.clone(), + }); + } + } } /// Backing handle for on-demand lazy CRDT hydration from an on-disk SQLite workspace file. @@ -187,9 +313,26 @@ pub struct SqliteLazyBacking { pub path: PathBuf, pub space_id: String, pub blob_count: usize, + lease: Arc, } impl SqliteLazyBacking { + pub fn new(path: impl Into, space_id: impl Into, blob_count: usize) -> Self { + Self { + lease: Arc::new(BackingLease { + opens: Arc::default(), + }), + path: path.into(), + space_id: space_id.into(), + blob_count, + } + } + + /// Number of read connections the worker opened for this backing. + pub fn read_connection_opens(&self) -> u64 { + self.lease.opens.load(Ordering::Relaxed) + } + /// Read and merge one document's `snapshots` + `updates` from SQLite without writing back. pub fn load_doc_update(&self, doc_id: &str) -> Result>> { let (reply_tx, reply_rx) = mpsc::channel(); @@ -197,6 +340,7 @@ impl SqliteLazyBacking { .send(SqliteWorkerReq::LoadDoc { path: self.path.clone(), doc_id: doc_id.to_string(), + opens: Arc::clone(&self.lease.opens), reply: reply_tx, }) .map_err(|_| anyhow::anyhow!("sqlite read-only worker channel closed"))?; @@ -351,7 +495,7 @@ pub fn open_sqlite_workspace(path: impl AsRef) -> Result<(DesktopDocStore, directory, docs, folder_rows, - folder_cache: FolderForestCache::default(), + folder_cache: Default::default(), collections: vec![DesktopCollection { id: "col-edgeless".into(), name: "Whiteboards".into(), @@ -365,13 +509,11 @@ pub fn open_sqlite_workspace(path: impl AsRef) -> Result<(DesktopDocStore, next_seq: 1000, env_rev: 1, workspace_buckets: BTreeMap::new(), - sqlite_backing: Some(SqliteLazyBacking { - path, - space_id, - blob_count, - }), + derived: crate::doc_store::DerivedCache::default(), + writer: None, + sqlite_backing: Some(SqliteLazyBacking::new(path, space_id, blob_count)), }; - store.rebuild_derived(); + store.reindex_all(); let stats = SqliteLoadStats { total_docs: store.docs.len(), diff --git a/packages/frontend/desktop/src/state.rs b/packages/frontend/desktop/src/state.rs index dc3c2c1d32..1d0d6d9245 100644 --- a/packages/frontend/desktop/src/state.rs +++ b/packages/frontend/desktop/src/state.rs @@ -1,5 +1,7 @@ //! Complete deterministic state for the AFFiNE Desktop shell (`DesktopAppState`). +use std::collections::BTreeMap; + use affine_client::Scope; use affine_store::directory::DocMode; use ui_tokens::ThemeMode; @@ -64,6 +66,8 @@ pub struct DesktopAppState { pub draft_store_error: Option, pub sidebar: SidebarState, pub split: SplitLayout, + /// Workbench layouts of the inactive workspaces, keyed by workspace ID. + pub parked_layouts: BTreeMap, pub quick_search: QuickSearchState, pub peek_view: PeekViewState, pub inspector_tab: Option, @@ -186,14 +190,7 @@ impl DesktopAppState { "https://app.affine.pro", &store.active_workspace().id, ); - let initial_route = if store.get_doc("doc-arch").is_some() { - DesktopRoute::Doc("doc-arch".into()) - } else if let Some(first) = store.visible_docs().first() { - DesktopRoute::Doc(first.id.clone()) - } else { - DesktopRoute::AllDocs - }; - let split = SplitLayout::single(scope, initial_route, DocViewMode::Page); + let split = SplitLayout::single(scope, initial_route(&store), DocViewMode::Page); let theme_preference = match theme { ThemeMode::Light => ThemePreference::Light, ThemeMode::Dark => ThemePreference::Dark, @@ -210,6 +207,7 @@ impl DesktopAppState { draft_store_error, sidebar: SidebarState::default(), split, + parked_layouts: BTreeMap::new(), quick_search: QuickSearchState::default(), peek_view: PeekViewState::default(), inspector_tab: None, @@ -218,6 +216,30 @@ impl DesktopAppState { } } + /// Make workspace `index` active with its own workbench layout. + /// + /// Panes, tabs, and history belong to one workspace: the layout of the old workspace is + /// parked and the new workspace gets its parked layout back, or a fresh single pane. + pub fn switch_workspace(&mut self, index: usize) { + let old_id = self.store.active_workspace().id.clone(); + self.store.switch_workspace(index); + let new_id = self.store.active_workspace().id.clone(); + if new_id == old_id { + return; + } + let next = self.parked_layouts.remove(&new_id).unwrap_or_else(|| { + SplitLayout::single( + self.current_scope(), + initial_route(&self.store), + DocViewMode::Page, + ) + }); + let previous = std::mem::replace(&mut self.split, next); + self.parked_layouts.insert(old_id, previous); + self.sidebar.scroll_y = 0.0; + self.peek_view.close(); + } + pub fn set_theme_preference(&mut self, pref: ThemePreference) { self.theme_preference = pref; self.theme = pref.resolve(self.system_dark); @@ -353,7 +375,9 @@ impl DesktopAppState { return String::new(); } let id = self.store.create_folder(name, parent_id); - self.sidebar.expanded_folders.insert(id.clone()); + if !id.is_empty() { + self.sidebar.expanded_folders.insert(id.clone()); + } id } @@ -497,6 +521,17 @@ impl DesktopAppState { } } +/// First route of a workspace that has no layout yet. +fn initial_route(store: &DesktopDocStore) -> DesktopRoute { + if store.get_doc("doc-arch").is_some() { + DesktopRoute::Doc("doc-arch".into()) + } else if let Some(first) = store.visible_docs().first() { + DesktopRoute::Doc(first.id.clone()) + } else { + DesktopRoute::AllDocs + } +} + #[cfg(test)] mod tests { use super::*; @@ -791,11 +826,11 @@ mod tests { std::fs::write(temp_root.join(".affine-desktop-drafts"), b"blocker").unwrap(); let mut store = DesktopDocStore::seed_showcase("2026-11-28"); - store.sqlite_backing = Some(crate::sqlite_loader::SqliteLazyBacking { - path: temp_root.join("sample.affine"), - space_id: "ws-blocked".to_string(), - blob_count: 0, - }); + store.sqlite_backing = Some(crate::sqlite_loader::SqliteLazyBacking::new( + temp_root.join("sample.affine"), + "ws-blocked".to_string(), + 0, + )); let mut state = DesktopAppState::from_doc_store(store, ThemeMode::Light, "2026-11-28"); assert!( state.draft_store_error.is_some(), @@ -820,11 +855,11 @@ mod tests { // Path-traversal and forbidden-DB-suffix space_ids must fail closed without panicking. for bad_space_id in ["../escape", "evil.db", "ws.affine"] { let mut store_bad = DesktopDocStore::seed_showcase("2026-11-28"); - store_bad.sqlite_backing = Some(crate::sqlite_loader::SqliteLazyBacking { - path: temp_root.join("sample.affine"), - space_id: bad_space_id.to_string(), - blob_count: 0, - }); + store_bad.sqlite_backing = Some(crate::sqlite_loader::SqliteLazyBacking::new( + temp_root.join("sample.affine"), + bad_space_id.to_string(), + 0, + )); let mut state_bad = DesktopAppState::from_doc_store(store_bad, ThemeMode::Light, "2026-11-28"); assert!( diff --git a/packages/frontend/desktop/src/views_extra.rs b/packages/frontend/desktop/src/views_extra.rs index 5d7d35503b..9b9890c3c9 100644 --- a/packages/frontend/desktop/src/views_extra.rs +++ b/packages/frontend/desktop/src/views_extra.rs @@ -281,7 +281,7 @@ pub(crate) fn render_trash_view( doc.id ))) .snapshot( - ui::SharedString::from(format!("desktop.trash.row.{}", doc.id)), + format_args!("desktop.trash.row.{}", doc.id), Some("desktop.workbench"), ) .flex() diff --git a/packages/frontend/desktop/src/workbench/connected_workspace.rs b/packages/frontend/desktop/src/workbench/connected_workspace.rs index 706a39cf85..b2e5764ed5 100644 --- a/packages/frontend/desktop/src/workbench/connected_workspace.rs +++ b/packages/frontend/desktop/src/workbench/connected_workspace.rs @@ -1,62 +1,12 @@ //! Connected workspace lifecycle of the desktop workbench. use super::DesktopShellView; +use crate::doc_store::{PendingUpdates, SessionWriter, merge_pending_updates}; use affine_client::{ClientError, ClientResult, SqliteSyncHost, WorkspaceSession}; use affine_store::sync::SpaceSyncEvent; -use std::{ - collections::{HashSet, VecDeque}, - sync::{Arc, Mutex}, -}; +use std::sync::{Arc, Mutex}; use ui::Context; -type PendingUpdates = Arc)>>>; - -pub(crate) struct EditorUpdates { - workspace_id: String, - started: HashSet, - pending: PendingUpdates, -} - -impl EditorUpdates { - pub(crate) fn record( - &mut self, - workspace_id: &str, - doc_id: &str, - page: &blocksuite_playground_doc::session::PageDocSession, - delta: Vec, - ) { - if self.workspace_id != workspace_id { - return; - } - // A newly bound SQLite store may not have the mounted editor's base. - let bytes = if self.started.contains(doc_id) { - delta - } else if let Ok(base) = page.encode_update_v1() { - self.started.insert(doc_id.to_owned()); - base - } else { - delta - }; - self.pending - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push_back((doc_id.to_owned(), bytes)); - } -} - -fn merge_editor_updates( - pending: &PendingUpdates, - session: &mut WorkspaceSession, - time: i64, -) -> ClientResult<()> { - let mut pending = pending.lock().unwrap_or_else(|e| e.into_inner()); - while let Some((doc_id, bytes)) = pending.front() { - session.merge_local_doc_update(doc_id, bytes, time)?; - pending.pop_front(); - } - Ok(()) -} - pub(super) struct ConnectedWorkspace { pub(super) workspace_id: String, save: Box ClientResult<()>>, @@ -107,15 +57,16 @@ impl DesktopShellView { clock.now().saturating_duration_since(start).as_millis() as i64 ); let mut session = session.lock().unwrap_or_else(|e| e.into_inner()); - merge_editor_updates(&pending, &mut session, time)?; + merge_pending_updates(&pending, &mut session, time)?; host.save_local(&mut session, time) }) }; - self.editor_host.connected_updates = Some(EditorUpdates { - workspace_id: workspace_id.clone(), - started: HashSet::new(), - pending: pending.clone(), - }); + self.state.store.bind_writer(SessionWriter::new( + workspace_id.clone(), + session.clone(), + pending.clone(), + now_ms, + )); self.connection = Some(ConnectedWorkspace { workspace_id, save, @@ -133,7 +84,7 @@ impl DesktopShellView { .run_tick( session.clone(), move |session, runtime, store, transport, url| { - merge_editor_updates(&pending, session, time)?; + merge_pending_updates(&pending, session, time)?; runtime.block_on(store.on_sync_tick(session, transport, url, time)) }, ) @@ -154,7 +105,7 @@ impl DesktopShellView { pub fn disconnect_workspace(&mut self) -> ClientResult<()> { self.save_connected_workspace()?; - self.editor_host.connected_updates = None; + self.state.store.unbind_writer(); self.connection = None; Ok(()) } @@ -163,13 +114,27 @@ impl DesktopShellView { #[cfg(test)] mod tests { use super::*; - use affine_client::{EditorDocMode, HostKind, MemoryHostBridge, SqliteWorkspaceStore}; + use affine_client::{HostKind, MemoryHostBridge, SqliteWorkspaceStore}; + use affine_store::{ + directory::DocMode, + workspace_db::{FolderRow, WorkspaceDbTableName}, + }; + use blocksuite_playground_doc::read::BlockContent; use ui::{Application, HeadlessPlatform, prelude::*}; use ui_tokens::ThemeMode; + struct SavedDoc { + space: &'static str, + store: Arc, + id: String, + title: String, + body: String, + folder_id: String, + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn replacement_and_disconnect_save_each_session_to_its_own_database() { - let dir = std::env::temp_dir().join(format!("desktop-switch-save-{}", std::process::id())); + async fn shell_commands_persist_through_each_connected_session_and_reopen_isolated() { + let dir = std::env::temp_dir().join(format!("desktop-shell-save-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let app = Application::with_platform(HeadlessPlatform::new(900, 600, 1.0)).run_embedded(|_| {}); @@ -207,9 +172,11 @@ mod tests { "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket".into(), tokio::runtime::Handle::current(), ); - app.update(|cx| { + let title = format!("Saved in {space}"); + let body = format!("Body written in {space}"); + let (id, folder_id) = app.update(|cx| { shell.update(cx, |view, cx| { - view.state.store.switch_workspace(index); + view.state.switch_workspace(index); view.connect_workspace( session.clone(), host, @@ -218,39 +185,176 @@ mod tests { cx, ) .unwrap(); + let state = &mut view.state; + let id = state.create_new_doc(DocMode::Page); + assert!(!id.is_empty(), "{space}: create_new_doc failed"); + let now = state.logical_clock_ms; + state.store.append_paragraph(&id, &body, now).unwrap(); + assert!(state.store.rename_doc(&id, &title, now + 1)); + let folder_id = state.create_folder("Saved Folder", None); + state.store.move_doc_to_folder(&id, Some(&folder_id)); + (id, folder_id) }) }); - let title = format!("Saved in {space}"); - let id = { - let mut session = session.lock().unwrap(); - let (summary, pending) = session - .create_document("", EditorDocMode::Page, None, 1_010) - .unwrap(); - session.enqueue_pending_persist_updates(pending); - let id = summary.id.as_str().to_owned(); - assert!(session.rename_document(&id, &title, 1_020).unwrap()); - id - }; - saved.push((space, store, id, title)); + saved.push(SavedDoc { + space, + store, + id, + title, + body, + folder_id, + }); } app.update(|cx| shell.update(cx, |view, _| view.disconnect_workspace().unwrap())); - for (space, store, id, title) in saved { - store.close().await; - let reopened = SqliteWorkspaceStore::open(&dir, "workspace", "local", space) + for doc in &saved { + doc.store.close().await; + } + for (index, doc) in saved.iter().enumerate() { + let reopened = SqliteWorkspaceStore::open(&dir, "workspace", "local", doc.space) .await .unwrap(); let page = reopened - .load_doc_session(&id, 42) + .load_doc_session(&doc.id, 42) .await .unwrap() - .unwrap() + .unwrap_or_else(|| panic!("{}: page `{}` was not saved", doc.space, doc.id)) .read_page_snapshot() .unwrap(); + let root = page.root.as_ref().unwrap(); assert!( - matches!(page.root.unwrap().content, blocksuite_playground_doc::read::BlockContent::Page { title: stored } if stored.plain == title) + matches!(&root.content, BlockContent::Page { title } if title.plain == doc.title), + "{}: page title", + doc.space + ); + assert!( + root.walk().any(|n| matches!( + &n.content, + BlockContent::Paragraph { text, .. } if text.plain == doc.body + )), + "{}: page body", + doc.space + ); + let session = reopened + .load_workspace_session( + "desktop", + 43, + HostKind::Native, + "local", + "https://app.affine.pro", + 2_000, + ) + .await + .unwrap(); + let other = &saved[1 - index]; + { + let dir_lock = session.directory().lock_directory(); + let db = dir_lock.db(); + let meta = db.root().get_page(&doc.id).unwrap().unwrap(); + assert_eq!(meta.title, doc.title, "{}: directory title", doc.space); + let folders: Vec = db + .db_table(WorkspaceDbTableName::Folders) + .unwrap() + .list_rows() + .unwrap(); + assert!( + folders + .iter() + .any(|r| r.id == doc.folder_id && r.folder_type == "folder"), + "{}: folder row", + doc.space + ); + assert!( + folders.iter().any(|r| r.folder_type == "doc" + && r.data == doc.id + && r.parent_id.as_deref() == Some(doc.folder_id.as_str())), + "{}: placement row", + doc.space + ); + assert!(db.root().get_page(&other.id).unwrap().is_none()); + } + assert!( + reopened + .load_doc_session(&other.id, 44) + .await + .unwrap() + .is_none(), + "{}: holds the page of {}", + doc.space, + other.space ); reopened.close().await; } std::fs::remove_dir_all(dir).unwrap(); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn first_folder_and_favorite_write_clocks_at_or_after_connect_time() { + const NOW_MS: i64 = 1_764_400_000_000; + let dir = std::env::temp_dir().join(format!("desktop-shell-clocks-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let state = crate::DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-01"); + let space = state.store.active_workspace().id.clone(); + let store = Arc::new( + SqliteWorkspaceStore::open(&dir, "workspace", "local", &space) + .await + .unwrap(), + ); + let session = Arc::new(Mutex::new( + store + .load_workspace_session( + "desktop", + 41, + HostKind::Native, + "local", + "https://app.affine.pro", + NOW_MS, + ) + .await + .unwrap(), + )); + let host = SqliteSyncHost::new( + store.clone(), + Arc::new(Mutex::new(MemoryHostBridge::new( + HostKind::Native, + "desktop", + ))), + "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket".into(), + tokio::runtime::Handle::current(), + ); + let app = + Application::with_platform(HeadlessPlatform::new(900, 600, 1.0)).run_embedded(|_| {}); + app.update(|cx| { + let shell = cx.new(|cx| DesktopShellView::new(state, cx)); + shell.update(cx, |view, cx| { + view.connect_workspace(session, host, NOW_MS, |_| panic!("unexpected tick"), cx) + .unwrap(); + assert!(!view.state.create_folder("New Folder", None).is_empty()); + assert!(view.state.store.toggle_favorite("doc-board")); + view.disconnect_workspace().unwrap(); + }); + }); + store.close().await; + + let reopened = SqliteWorkspaceStore::open(&dir, "workspace", "local", &space) + .await + .unwrap(); + for table in [ + WorkspaceDbTableName::Folders, + WorkspaceDbTableName::DocProperties, + ] { + let id = table.local_doc_id(); + let clock = reopened + .storage() + .get_doc_clock(&id) + .await + .unwrap() + .unwrap_or_else(|| panic!("{id} has no clock")); + let timestamp = clock.timestamp.and_utc().timestamp_millis(); + assert!( + timestamp >= NOW_MS, + "{id} clock {timestamp} precedes {NOW_MS}" + ); + } + reopened.close().await; + std::fs::remove_dir_all(dir).unwrap(); + } } diff --git a/packages/frontend/desktop/src/workbench/mod.rs b/packages/frontend/desktop/src/workbench/mod.rs index 9268fa6adc..9a950993d9 100644 --- a/packages/frontend/desktop/src/workbench/mod.rs +++ b/packages/frontend/desktop/src/workbench/mod.rs @@ -3,8 +3,6 @@ #[cfg(not(target_family = "wasm"))] mod connected_workspace; -#[cfg(not(target_family = "wasm"))] -pub(crate) use connected_workspace::EditorUpdates; mod topbar; use ui::{ @@ -19,8 +17,8 @@ use crate::{ CLOSE_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, EDGELESS_ICON_SVG, editor_host::DesktopEditorHost, palette_for, pane_render::render_pane_content, peek_view::render_peek_view_modal, quick_search::render_quick_search_modal, - settings_modal::render_settings_modal, sidebar::render_sidebar, split_view::DocViewMode, - views_extra::render_doc_inspector, + settings_modal::render_settings_modal, sidebar::render_sidebar, sidebar_tree::SidebarRowIndex, + split_view::DocViewMode, views_extra::render_doc_inspector, }; /// Interactive GPU UI root view for AFFiNE Web Desktop & Electron shell. @@ -28,6 +26,7 @@ pub struct DesktopShellView { pub state: DesktopAppState, editor_host: DesktopEditorHost, pending_block: Option, + pub(crate) sidebar_rows: SidebarRowIndex, focus_handle: FocusHandle, #[cfg(not(target_family = "wasm"))] connection: Option, @@ -39,6 +38,7 @@ impl DesktopShellView { state, editor_host: DesktopEditorHost::new(), pending_block: None, + sidebar_rows: SidebarRowIndex::default(), #[cfg(not(target_family = "wasm"))] connection: None, focus_handle: cx.focus_handle(), @@ -57,6 +57,11 @@ impl DesktopShellView { &self.editor_host } + /// Flattened sidebar tree rows and the window the last frame mounted. + pub fn sidebar_rows(&self) -> &SidebarRowIndex { + &self.sidebar_rows + } + /// Synchronize live CRDT edits across all mounted `Entity` panes. pub fn sync_editors(&mut self, cx: &mut Context) { self.editor_host.sync_all(&mut self.state.store, cx); @@ -87,16 +92,17 @@ impl DesktopShellView { } self.editor_host.sync_all(store, cx); let previous = store.active_workspace_idx; - store.switch_workspace(index); + self.state.switch_workspace(index); + let store = &mut self.state.store; if store.active_workspace_idx != index || store.ensure_doc_hydrated(&target.doc_id) != Ok(true) { - store.switch_workspace(previous); + self.state.switch_workspace(previous); return false; } #[cfg(not(target_family = "wasm"))] if previous != index && self.disconnect_workspace().is_err() { - self.state.store.switch_workspace(previous); + self.state.switch_workspace(previous); return false; } self.state.peek_view.close(); @@ -210,7 +216,7 @@ impl Render for DesktopShellView { .position(|ws| ws.id == connection.workspace_id) && self.disconnect_workspace().is_err() { - self.state.store.switch_workspace(index); + self.state.switch_workspace(index); } // Sync all mounted editors BEFORE pruning closed panes so closing a split pane // never discards uncommitted Yjs V1 edits. @@ -462,7 +468,7 @@ impl Render for DesktopShellView { let mut pane_el = div() .id(ui::SharedString::from(format!("desktop.pane.{idx}"))) .snapshot( - ui::SharedString::from(format!("desktop.pane.{idx}")), + format_args!("desktop.pane.{idx}"), Some("desktop.workbench"), ) .w(px(pane_w)) @@ -512,9 +518,11 @@ impl Render for DesktopShellView { if self.state.sidebar.open { root = root.child(render_sidebar( - &self.state.sidebar, + &mut self.state.sidebar, &self.state.store, + &mut self.sidebar_rows, &active_route, + vp_h, palette, cx, )); @@ -575,3 +583,104 @@ impl Render for DesktopShellView { root } } + +#[cfg(test)] +mod tests { + #[test] + fn all_docs_stays_visible_when_a_deep_sidebar_scroll_loses_rows() { + use super::DesktopShellView; + use crate::{DesktopAppState, register_desktop_fonts, sidebar::SidebarSection}; + use affine_store::directory::DocMode; + use ui::{ + Application, Bounds, HeadlessPlatform, WindowBounds, WindowOptions, point, prelude::*, + px, size, + }; + use ui_tokens::ThemeMode; + + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-01"); + let folder = state.create_folder("Scale", None); + for i in 0..1_000 { + let doc = state.store.create_doc( + format!("Scale Doc {i:04}"), + DocMode::Page, + None, + 1_764_400_000 + i, + ); + state.store.move_doc_to_folder(&doc, Some(&folder)); + } + let platform = HeadlessPlatform::new(900, 720, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).unwrap(); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(900.0), px(720.0)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + .unwrap() + }); + let window = platform.windows().into_iter().next().unwrap(); + + for switch_workspace in [false, true] { + app.update(|cx| { + handle + .update(cx, |view, _, cx| { + view.state + .sidebar + .expanded_sections + .insert(SidebarSection::Folders); + cx.notify(); + }) + .unwrap(); + }); + window.request_frame(); + app.update(|cx| { + handle + .update(cx, |view, _, cx| { + let max_scroll = view.sidebar_rows.max_scroll(); + assert!(max_scroll > 10_000.0); + view.state.sidebar.scroll_y = max_scroll; + cx.notify(); + }) + .unwrap(); + }); + window.request_frame(); + app.update(|cx| { + handle + .update(cx, |view, _, cx| { + assert!(view.state.sidebar.scroll_y > 10_000.0); + if switch_workspace { + view.state.switch_workspace(1); + assert_eq!(view.state.sidebar.scroll_y, 0.0); + } else { + view.state.sidebar.toggle_section(SidebarSection::Folders); + } + cx.notify(); + }) + .unwrap(); + }); + window.request_frame(); + app.update(|cx| { + handle + .update(cx, |view, window, _| { + let row = &window.frame_snapshot().elements["desktop.sidebar.all_docs"]; + let bounds = row.bounds; + let clip = row.content_mask; + assert!( + bounds.height > 0.0 + && bounds.y >= clip.y - 0.5 + && bounds.y + bounds.height <= clip.y + clip.height + 0.5, + "All Docs bounds {bounds:?} must fit the tree viewport {clip:?}" + ); + assert!(view.state.sidebar.scroll_y <= view.sidebar_rows.max_scroll()); + }) + .unwrap(); + }); + } + } +}