mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
fix(desktop): use workspace tag definitions in search
Show current tag names and colors. Hide tags that the workspace deletes. Filter documents by tag before scoring. Cache up to eight results per tag query. Keep search row snapshot names in harness builds. Before the first tag edit of a workspace writes its tag table, record the tags of all its documents, including trashed documents.
This commit is contained in:
1 parent
3d7ff37287
commit
f45bc95361
7 files changed
+729
-155
No files matched your search
@@ -19,7 +19,7 @@ use blocksuite_playground_doc::{
|
||||
pub(crate) use load::{LoadedWorkspace, load_workspace};
|
||||
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(crate) use views::{DerivedCache, DocViews, QUICK_SEARCH_DOC_LIMIT, SidebarFolderTree};
|
||||
pub use writer::{PendingUpdates, SessionWriter, merge_pending_updates};
|
||||
|
||||
/// Local vs Cloud workspace sync flavour.
|
||||
@@ -257,10 +257,9 @@ impl DesktopDocStore {
|
||||
}
|
||||
|
||||
pub fn docs_for_tag(&self, tag: &str) -> Vec<&DesktopDocMeta> {
|
||||
self.visible_docs()
|
||||
.into_iter()
|
||||
.filter(|d| d.tags.iter().any(|t| t == tag))
|
||||
.collect()
|
||||
self.views()
|
||||
.tag(tag)
|
||||
.map_or_else(Vec::new, |tag| self.metas(&tag.docs))
|
||||
}
|
||||
|
||||
/// Non-trashed documents placed directly in `folder_id`, in sidebar tree order.
|
||||
@@ -269,7 +268,17 @@ impl DesktopDocStore {
|
||||
}
|
||||
|
||||
pub fn all_tags_with_counts(&self) -> Vec<(String, u32, usize)> {
|
||||
self.views().tags.clone()
|
||||
self.views()
|
||||
.tags
|
||||
.iter()
|
||||
.map(|tag| {
|
||||
(
|
||||
tag.definition.id.clone(),
|
||||
tag.color(&ui_tokens::LIGHT_THEME),
|
||||
tag.docs.len(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn metas(&self, ids: &[String]) -> Vec<&DesktopDocMeta> {
|
||||
|
||||
@@ -1,30 +1,35 @@
|
||||
//! Project the workspace root's tag and collection definitions into the desktop store.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use affine_client::domain::CollectionRule;
|
||||
use affine_store::workspace_db::{
|
||||
CollectionFilter, NavigationEdit, WorkspaceCollection, WorkspaceRootDoc, WorkspaceTag,
|
||||
use affine_store::{
|
||||
StoreResult,
|
||||
workspace_db::{
|
||||
CollectionFilter, NavigationEdit, WorkspaceCollection, WorkspaceRootDoc, WorkspaceTag,
|
||||
},
|
||||
};
|
||||
use blocksuite_playground_doc::try_random_client_id;
|
||||
use ui_tokens::{LIGHT_THEME, ThemeTokens};
|
||||
|
||||
use super::{DesktopCollection, DesktopDocStore};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct NavigationProjection {
|
||||
pub tags: Option<BTreeMap<String, String>>,
|
||||
pub(super) tags: Option<BTreeMap<String, WorkspaceTag>>,
|
||||
legacy_colors: BTreeMap<String, u32>,
|
||||
has_collections: bool,
|
||||
}
|
||||
|
||||
struct NavigationSnapshot {
|
||||
tags: Option<Vec<WorkspaceTag>>,
|
||||
tags: StoreResult<Option<Vec<WorkspaceTag>>>,
|
||||
collections: Option<Vec<WorkspaceCollection>>,
|
||||
}
|
||||
|
||||
impl NavigationSnapshot {
|
||||
fn read(root: &WorkspaceRootDoc) -> Self {
|
||||
Self {
|
||||
tags: root.navigation_tags().ok().flatten(),
|
||||
tags: root.navigation_tags(),
|
||||
collections: root.navigation_collections().ok().flatten(),
|
||||
}
|
||||
}
|
||||
@@ -47,28 +52,41 @@ impl DesktopDocStore {
|
||||
}
|
||||
|
||||
fn project_navigation(&mut self, snapshot: NavigationSnapshot) -> bool {
|
||||
let changed = snapshot.tags.is_some() || snapshot.collections.is_some();
|
||||
let workspace = self.active_workspace().id.clone();
|
||||
let projection = self.derived.navigation.entry(workspace).or_default();
|
||||
if let Some(tags) = snapshot.tags {
|
||||
self.tag_colors = tags
|
||||
.iter()
|
||||
.map(|tag| (tag.id.clone(), tag_rgb(&tag.color)))
|
||||
.collect();
|
||||
projection.tags = Some(tags.into_iter().map(|tag| (tag.id, tag.name)).collect());
|
||||
let mut changed = false;
|
||||
if let Ok(tags) = snapshot.tags {
|
||||
let tags = tags.map(|tags| tags.into_iter().map(|tag| (tag.id.clone(), tag)).collect());
|
||||
if projection.tags != tags {
|
||||
if projection.tags.is_none() {
|
||||
projection.legacy_colors = std::mem::take(&mut self.tag_colors);
|
||||
}
|
||||
self.tag_colors = tags.as_ref().map_or_else(
|
||||
|| std::mem::take(&mut projection.legacy_colors),
|
||||
|tags: &BTreeMap<String, WorkspaceTag>| {
|
||||
tags.iter()
|
||||
.map(|(id, tag)| {
|
||||
(id.clone(), resolve_tag_color(&tag.color, &LIGHT_THEME))
|
||||
})
|
||||
.collect()
|
||||
},
|
||||
);
|
||||
projection.tags = tags;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if let Some(collections) = snapshot.collections {
|
||||
self.collections = collections.into_iter().map(project_collection).collect();
|
||||
projection.has_collections = true;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub(crate) fn tag_label(&self, id: &str) -> String {
|
||||
self.views()
|
||||
.tag_labels
|
||||
.get(id)
|
||||
.map_or_else(|| id.to_owned(), Clone::clone)
|
||||
.tag(id)
|
||||
.map_or_else(|| id.to_owned(), |tag| tag.definition.name.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn create_tag(&mut self, name: &str) -> bool {
|
||||
@@ -120,14 +138,14 @@ impl DesktopDocStore {
|
||||
if self.is_readonly_sqlite() {
|
||||
return false;
|
||||
}
|
||||
self.persist_showcase_definitions(&edit);
|
||||
let seeded = self.persist_legacy_definitions(&edit);
|
||||
let updated = self.apply_navigation_edit(&edit);
|
||||
if updated {
|
||||
if let NavigationEdit::DeleteTag(id) = edit {
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.meta.tags.retain(|tag| tag != &id);
|
||||
}
|
||||
if updated && let NavigationEdit::DeleteTag(id) = edit {
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.meta.tags.retain(|tag| tag != &id);
|
||||
}
|
||||
}
|
||||
if updated || seeded {
|
||||
self.touch_meta();
|
||||
}
|
||||
updated
|
||||
@@ -161,12 +179,10 @@ impl DesktopDocStore {
|
||||
false
|
||||
}
|
||||
|
||||
// Backups created before the demo definitions were stored still show the demo groups.
|
||||
// Record those groups before the first edit so that deleting or editing one retains the others.
|
||||
fn persist_showcase_definitions(&mut self, edit: &NavigationEdit) {
|
||||
if self.active_workspace().id != crate::showcase::SHOWCASE_WORKSPACE_ID {
|
||||
return;
|
||||
}
|
||||
// A workspace without a tag table names its tags by the IDs on its documents. Record each
|
||||
// of those tags, including tags that only trashed documents use, before the first tag edit
|
||||
// writes the table. Record the shown collections before the first collection edit.
|
||||
fn persist_legacy_definitions(&mut self, edit: &NavigationEdit) -> bool {
|
||||
let projection = self.derived.navigation.get(&self.active_workspace().id);
|
||||
let seeds: Vec<_> = match edit {
|
||||
NavigationEdit::CreateTag(_)
|
||||
@@ -174,12 +190,18 @@ impl DesktopDocStore {
|
||||
| NavigationEdit::DeleteTag(_)
|
||||
if projection.is_none_or(|p| p.tags.is_none()) =>
|
||||
{
|
||||
self.tag_colors
|
||||
.iter()
|
||||
.map(|(id, rgb)| {
|
||||
let mut ids: BTreeSet<&str> = self.tag_colors.keys().map(String::as_str).collect();
|
||||
ids.extend(
|
||||
self.docs
|
||||
.values()
|
||||
.flat_map(|entry| entry.meta.tags.iter().map(String::as_str)),
|
||||
);
|
||||
ids.into_iter()
|
||||
.map(|id| {
|
||||
let rgb = self.tag_colors.get(id).copied().unwrap_or(FALLBACK_TAG_RGB);
|
||||
NavigationEdit::CreateTag(WorkspaceTag {
|
||||
id: id.clone(),
|
||||
name: id.clone(),
|
||||
id: id.to_owned(),
|
||||
name: id.to_owned(),
|
||||
color: format!("#{rgb:06x}"),
|
||||
})
|
||||
})
|
||||
@@ -199,25 +221,31 @@ impl DesktopDocStore {
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut changed = false;
|
||||
for seed in &seeds {
|
||||
self.apply_navigation_edit(seed);
|
||||
changed |= self.apply_navigation_edit(seed);
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
fn tag_rgb(color: &str) -> u32 {
|
||||
const FALLBACK_TAG_RGB: u32 = 0x1e96eb;
|
||||
|
||||
pub(super) fn resolve_tag_color(color: &str, theme: &ThemeTokens) -> u32 {
|
||||
let color = color.trim();
|
||||
if let Some(hex) = color.strip_prefix('#')
|
||||
&& hex.len() == 6
|
||||
&& let Ok(rgb) = u32::from_str_radix(hex, 16)
|
||||
{
|
||||
return rgb;
|
||||
}
|
||||
let Some(name) = color.strip_prefix("var(").and_then(|v| v.strip_suffix(')')) else {
|
||||
return 0x1e96eb;
|
||||
};
|
||||
ui_tokens::LIGHT_THEME.color(name).map_or(0x1e96eb, |rgba| {
|
||||
u32::from(rgba.r) << 16 | u32::from(rgba.g) << 8 | u32::from(rgba.b)
|
||||
})
|
||||
let name = color
|
||||
.strip_prefix("var(")
|
||||
.and_then(|name| name.strip_suffix(')'))
|
||||
.map_or(color, str::trim);
|
||||
theme
|
||||
.color(name)
|
||||
.map_or(FALLBACK_TAG_RGB, |rgba| rgba.to_u32() >> 8)
|
||||
}
|
||||
|
||||
fn project_collection(collection: WorkspaceCollection) -> DesktopCollection {
|
||||
@@ -294,12 +322,37 @@ fn store_collection(collection: &DesktopCollection) -> WorkspaceCollection {
|
||||
pub(super) mod tests {
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use affine_store::{
|
||||
directory::{DocMode, WorkspaceDirectory},
|
||||
workspace_db::WorkspaceDb,
|
||||
};
|
||||
use ui::{AppContext, Application, HeadlessPlatform};
|
||||
use ui_tokens::ThemeMode;
|
||||
use y_octo::{
|
||||
DocOptions, DocSession, SessionConfig, SessionTxOrigin, SessionUndoConfig, SessionValue,
|
||||
TypeTarget, YTypeKind,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crate::{DesktopAppState, DesktopShellView, LocalDocStore, StoredWorkspaces};
|
||||
|
||||
const SCRATCH_WORKSPACE_ID: &str = "ws-local-scratch";
|
||||
|
||||
fn legacy_root_update_v1() -> Vec<u8> {
|
||||
let mut root = DocSession::<()>::with_config(
|
||||
DocOptions::from_identity(1, SCRATCH_WORKSPACE_ID.to_owned()),
|
||||
SessionConfig {
|
||||
undo: SessionUndoConfig::Disabled,
|
||||
},
|
||||
);
|
||||
let meta = TypeTarget::from(root.ensure_root("meta", YTypeKind::Map).unwrap());
|
||||
root.ensure_root("spaces", YTypeKind::Map).unwrap();
|
||||
root.begin_tx(SessionTxOrigin::Untracked).unwrap();
|
||||
root.map_set(&meta, "pages".into(), SessionValue::Array(Vec::new()))
|
||||
.unwrap();
|
||||
root.commit_tx().unwrap().unwrap().update
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LocalUpdates(pub(crate) RefCell<StoredWorkspaces>);
|
||||
|
||||
@@ -325,6 +378,7 @@ pub(super) mod tests {
|
||||
|
||||
fn open_with_local_writes<T>(
|
||||
storage: &Rc<LocalUpdates>,
|
||||
workspace: usize,
|
||||
edit: impl FnOnce(&mut DesktopDocStore) -> T,
|
||||
) -> T {
|
||||
let (state, sessions) =
|
||||
@@ -335,6 +389,8 @@ pub(super) mod tests {
|
||||
let view = cx.new(|cx| DesktopShellView::new(state, cx));
|
||||
view.update(cx, |view, cx| {
|
||||
view.bind_local_workspaces(sessions, storage.clone(), 123, cx);
|
||||
view.state_mut().switch_workspace(workspace);
|
||||
view.save_local_workspaces();
|
||||
let output = edit(&mut view.state_mut().store);
|
||||
view.save_local_workspaces();
|
||||
output
|
||||
@@ -342,19 +398,154 @@ pub(super) mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_colors_use_current_theme_and_preserve_custom_rgb() {
|
||||
for (color, light, dark) in [
|
||||
("var(--affine-tag-blue)", 0xe1eeff, 0x084388),
|
||||
("--affine-tag-blue", 0xe1eeff, 0x084388),
|
||||
("var(--affine-palette-line-blue)", 0x4f90ff, 0x4f90ff),
|
||||
("#17aC09", 0x17ac09, 0x17ac09),
|
||||
("var(--unknown-color)", 0x1e96eb, 0x1e96eb),
|
||||
] {
|
||||
assert_eq!(resolve_tag_color(color, &LIGHT_THEME), light, "{color}");
|
||||
assert_eq!(
|
||||
resolve_tag_color(color, &ui_tokens::DARK_THEME),
|
||||
dark,
|
||||
"{color}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_projection_distinguishes_read_failure_empty_and_missing_table() {
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
store.switch_workspace(1);
|
||||
let db = WorkspaceDb::from_root_update_v1(
|
||||
SCRATCH_WORKSPACE_ID,
|
||||
"local-user",
|
||||
2,
|
||||
&legacy_root_update_v1(),
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
store.directory = WorkspaceDirectory::new(db);
|
||||
assert!(store.directory.db().root().is_meta_initialized());
|
||||
store.tag_colors.insert("legacy".into(), 0x7c5cfa);
|
||||
let doc = store.create_doc("Legacy", DocMode::Page, None, 1);
|
||||
store.docs.get_mut(&doc).unwrap().meta.tags = vec!["legacy".into()];
|
||||
store.touch_meta();
|
||||
let legacy = vec![("legacy".to_owned(), 0x7c5cfa, 1)];
|
||||
assert_eq!(store.all_tags_with_counts(), legacy);
|
||||
let definition = WorkspaceTag {
|
||||
id: "defined".into(),
|
||||
name: "Defined".into(),
|
||||
color: "--affine-tag-blue".into(),
|
||||
};
|
||||
let apply = |store: &mut DesktopDocStore, tags| {
|
||||
if store.project_navigation(NavigationSnapshot {
|
||||
tags,
|
||||
collections: None,
|
||||
}) {
|
||||
store.touch_meta();
|
||||
}
|
||||
};
|
||||
apply(&mut store, Ok(Some(vec![definition])));
|
||||
let expected = vec![("defined".to_owned(), 0xe1eeff, 0)];
|
||||
assert_eq!(store.all_tags_with_counts(), expected);
|
||||
assert!(store.docs_for_tag("legacy").is_empty());
|
||||
apply(
|
||||
&mut store,
|
||||
Err(affine_store::StoreError::InvalidBinary("test".into())),
|
||||
);
|
||||
assert_eq!(store.all_tags_with_counts(), expected);
|
||||
|
||||
store.switch_workspace(0);
|
||||
assert_ne!(store.all_tags_with_counts(), expected);
|
||||
store.switch_workspace(1);
|
||||
assert_eq!(store.all_tags_with_counts(), expected);
|
||||
|
||||
apply(&mut store, Ok(Some(Vec::new())));
|
||||
assert!(store.all_tags_with_counts().is_empty());
|
||||
assert!(store.docs_for_tag("legacy").is_empty());
|
||||
store.load_navigation();
|
||||
store.touch_meta();
|
||||
assert_eq!(store.all_tags_with_counts(), legacy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_tag_table_keeps_legacy_tags_of_visible_and_trashed_docs_across_cold_reopen() {
|
||||
let storage = Rc::new(LocalUpdates::default());
|
||||
storage.push_update(
|
||||
SCRATCH_WORKSPACE_ID,
|
||||
SCRATCH_WORKSPACE_ID,
|
||||
legacy_root_update_v1(),
|
||||
);
|
||||
let (visible, trashed, fresh) = open_with_local_writes(&storage, 1, |store| {
|
||||
let tagged = ["legacy-visible", "legacy-trashed"].map(|tag| {
|
||||
let doc = store.create_doc(tag, DocMode::Page, None, 1_000);
|
||||
let tags = vec![tag.to_owned()];
|
||||
store
|
||||
.with_session(1_000, |session| {
|
||||
session.set_document_tags(&doc, &tags, 1_000)
|
||||
})
|
||||
.expect("bound writer")
|
||||
.expect("write tags");
|
||||
store.docs.get_mut(&doc).unwrap().meta.tags = tags;
|
||||
doc
|
||||
});
|
||||
assert!(store.trash_doc(&tagged[1], 1_001));
|
||||
store.tag_colors.insert("legacy-visible".into(), 0x7c5cfa);
|
||||
assert_eq!(
|
||||
store.all_tags_with_counts(),
|
||||
[("legacy-visible".to_owned(), 0x7c5cfa, 1)]
|
||||
);
|
||||
assert!(store.create_tag("Fresh"));
|
||||
let fresh = store
|
||||
.views()
|
||||
.tags
|
||||
.iter()
|
||||
.find(|tag| tag.definition.name == "Fresh")
|
||||
.expect("new tag definition")
|
||||
.definition
|
||||
.id
|
||||
.clone();
|
||||
let [visible, trashed] = tagged;
|
||||
(visible, trashed, fresh)
|
||||
});
|
||||
let expected = |restored: usize| {
|
||||
let mut tags = vec![
|
||||
("legacy-trashed".to_owned(), FALLBACK_TAG_RGB, restored),
|
||||
("legacy-visible".to_owned(), 0x7c5cfa, 1),
|
||||
(fresh.clone(), 0x4f90ff, 0),
|
||||
];
|
||||
tags.sort();
|
||||
tags
|
||||
};
|
||||
open_with_local_writes(&storage, 1, |store| {
|
||||
assert_eq!(store.all_tags_with_counts(), expected(0));
|
||||
assert!(store.restore_doc(&trashed, 1_002));
|
||||
assert_eq!(store.all_tags_with_counts(), expected(1));
|
||||
assert_eq!(store.docs_for_tag("legacy-visible")[0].id, visible);
|
||||
});
|
||||
open_with_local_writes(&storage, 1, |store| {
|
||||
assert_eq!(store.all_tags_with_counts(), expected(1));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidebar_tag_and_collection_crud_survives_cold_reopen() {
|
||||
let storage = Rc::new(LocalUpdates::default());
|
||||
let (tag, collection) = open_with_local_writes(&storage, |store| {
|
||||
let (tag, collection) = open_with_local_writes(&storage, 0, |store| {
|
||||
assert!(store.create_tag("To review"));
|
||||
assert!(store.create_collection("Work to review"));
|
||||
let tag = store
|
||||
.views()
|
||||
.tag_labels
|
||||
.tags
|
||||
.iter()
|
||||
.find(|(_, name)| name.as_str() == "To review")
|
||||
.find(|tag| tag.definition.name == "To review")
|
||||
.expect("tag definition")
|
||||
.0
|
||||
.definition
|
||||
.id
|
||||
.clone();
|
||||
let collection = store
|
||||
.collections
|
||||
@@ -367,7 +558,7 @@ pub(super) mod tests {
|
||||
assert!(store.rename_collection(&collection, "Reviewed work"));
|
||||
(tag, collection)
|
||||
});
|
||||
open_with_local_writes(&storage, |store| {
|
||||
open_with_local_writes(&storage, 0, |store| {
|
||||
assert_eq!(store.tag_label(&tag), "Reviewed");
|
||||
assert!(store.tag_colors.contains_key(&tag));
|
||||
assert!(store.tag_colors.contains_key("architecture"));
|
||||
@@ -389,7 +580,7 @@ pub(super) mod tests {
|
||||
assert!(store.delete_tag(&tag));
|
||||
assert!(store.delete_collection(&collection));
|
||||
});
|
||||
open_with_local_writes(&storage, |store| {
|
||||
open_with_local_writes(&storage, 0, |store| {
|
||||
assert!(!store.tag_colors.contains_key(&tag));
|
||||
assert!(!store.tag_colors.contains_key("architecture"));
|
||||
assert!(
|
||||
|
||||
@@ -5,17 +5,22 @@
|
||||
//! revision reuse the cached views and do no sorting, grouping, or index building.
|
||||
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::{BTreeMap, HashMap},
|
||||
cell::{Cell, RefCell, RefMut},
|
||||
collections::{BTreeMap, BTreeSet, HashMap},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use affine_client::{FolderForest, FolderForestState, SearchDocument, SearchHit};
|
||||
|
||||
use super::{DesktopDocMeta, DesktopDocStore};
|
||||
use affine_store::workspace_db::WorkspaceTag;
|
||||
use blocksuite_editor::match_exact_substring_utf16;
|
||||
use ui_tokens::ThemeTokens;
|
||||
|
||||
use super::{DesktopDocMeta, DesktopDocStore, navigation::resolve_tag_color};
|
||||
|
||||
/// Most recent distinct Quick Search queries kept per revision.
|
||||
const SEARCH_RESULT_SLOTS: usize = 16;
|
||||
pub(crate) const QUICK_SEARCH_DOC_LIMIT: usize = 8;
|
||||
|
||||
/// Deterministic counts of derived work done by a [`DesktopDocStore`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -118,13 +123,81 @@ pub(crate) struct DocViews {
|
||||
pub(crate) favorites: Vec<String>,
|
||||
pub(crate) trashed: Vec<String>,
|
||||
pub(crate) journals: Vec<String>,
|
||||
pub(crate) tags: Vec<(String, u32, usize)>,
|
||||
pub(crate) tag_labels: BTreeMap<String, String>,
|
||||
pub(crate) tags: Vec<VisibleTag>,
|
||||
/// Matching visible document count of each collection, in `DesktopDocStore::collections` order.
|
||||
pub(crate) collection_counts: Vec<usize>,
|
||||
pub(crate) folders: SidebarFolderTree,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct VisibleTag {
|
||||
pub(crate) definition: WorkspaceTag,
|
||||
pub(crate) docs: Vec<String>,
|
||||
}
|
||||
|
||||
impl VisibleTag {
|
||||
pub(crate) fn color(&self, theme: &ThemeTokens) -> u32 {
|
||||
resolve_tag_color(&self.definition.color, theme)
|
||||
}
|
||||
}
|
||||
|
||||
fn visible_tags(store: &DesktopDocStore, visible: &[&DesktopDocMeta]) -> Vec<VisibleTag> {
|
||||
let definitions = store
|
||||
.derived
|
||||
.navigation
|
||||
.get(&store.active_workspace().id)
|
||||
.and_then(|navigation| navigation.tags.as_ref());
|
||||
let mut tags = BTreeMap::new();
|
||||
if let Some(definitions) = definitions {
|
||||
tags.extend(definitions.iter().map(|(id, tag)| {
|
||||
(
|
||||
id.as_str(),
|
||||
VisibleTag {
|
||||
definition: tag.clone(),
|
||||
docs: Vec::new(),
|
||||
},
|
||||
)
|
||||
}));
|
||||
} else {
|
||||
tags.extend(store.tag_colors.iter().map(|(id, rgb)| {
|
||||
(
|
||||
id.as_str(),
|
||||
VisibleTag {
|
||||
definition: WorkspaceTag {
|
||||
id: id.clone(),
|
||||
name: id.clone(),
|
||||
color: format!("#{rgb:06x}"),
|
||||
},
|
||||
docs: Vec::new(),
|
||||
},
|
||||
)
|
||||
}));
|
||||
}
|
||||
for doc in visible {
|
||||
for id in &doc.tags {
|
||||
let tag = if definitions.is_some() {
|
||||
let Some(tag) = tags.get_mut(id.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
tag
|
||||
} else {
|
||||
tags.entry(id).or_insert_with(|| VisibleTag {
|
||||
definition: WorkspaceTag {
|
||||
id: id.clone(),
|
||||
name: id.clone(),
|
||||
color: String::new(),
|
||||
},
|
||||
docs: Vec::new(),
|
||||
})
|
||||
};
|
||||
if tag.docs.last() != Some(&doc.id) {
|
||||
tag.docs.push(doc.id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
tags.into_values().collect()
|
||||
}
|
||||
|
||||
impl DocViews {
|
||||
fn build(store: &DesktopDocStore) -> Self {
|
||||
let ids = |metas: Vec<&DesktopDocMeta>| metas.into_iter().map(|m| m.id.clone()).collect();
|
||||
@@ -154,35 +227,13 @@ impl DocViews {
|
||||
.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 tags = visible_tags(store, &visible);
|
||||
let collection_counts = store
|
||||
.collections
|
||||
.iter()
|
||||
.map(|c| visible.iter().filter(|d| c.matches(d)).count())
|
||||
.collect();
|
||||
let tag_labels = store
|
||||
.derived
|
||||
.navigation
|
||||
.get(&store.active_workspace().id)
|
||||
.and_then(|navigation| navigation.tags.clone())
|
||||
.unwrap_or_default();
|
||||
Self {
|
||||
tag_labels,
|
||||
folders: SidebarFolderTree::build(store.folder_forest().as_deref(), store),
|
||||
visible: ids(visible),
|
||||
favorites: ids(favorites),
|
||||
@@ -192,13 +243,28 @@ impl DocViews {
|
||||
collection_counts,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn tag(&self, id: &str) -> Option<&VisibleTag> {
|
||||
let index = self
|
||||
.tags
|
||||
.binary_search_by_key(&id, |tag| tag.definition.id.as_str())
|
||||
.ok()?;
|
||||
self.tags.get(index)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SearchCache {
|
||||
key: Option<(usize, u64)>,
|
||||
docs: Vec<SearchDocument>,
|
||||
docs: Option<Vec<SearchDocument>>,
|
||||
results: Vec<(String, usize, Vec<SearchHit>)>,
|
||||
tag_results: Vec<(String, usize, Arc<[TagSearchHit]>)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct TagSearchHit {
|
||||
pub(crate) doc_id: String,
|
||||
pub(crate) matched_tags: Vec<String>,
|
||||
}
|
||||
|
||||
/// Revision counter and lazily built caches of the derived views.
|
||||
@@ -272,24 +338,7 @@ impl DesktopDocStore {
|
||||
/// 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<SearchHit> {
|
||||
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);
|
||||
}
|
||||
let mut cache = self.search_cache();
|
||||
if let Some((_, _, hits)) = cache
|
||||
.results
|
||||
.iter()
|
||||
@@ -297,7 +346,15 @@ impl DesktopDocStore {
|
||||
{
|
||||
return hits.clone();
|
||||
}
|
||||
let hits = run_search(self, &cache.docs, query, limit);
|
||||
let docs = cache.docs.get_or_insert_with(|| {
|
||||
let views = self.views();
|
||||
self.derived.count(|w| w.search_index_builds += 1);
|
||||
self.metas(&views.visible)
|
||||
.into_iter()
|
||||
.map(|doc| index_search_doc(doc, &views))
|
||||
.collect()
|
||||
});
|
||||
let hits = run_search(self, docs, query, limit);
|
||||
self.derived.count(|w| w.search_runs += 1);
|
||||
if cache.results.len() == SEARCH_RESULT_SLOTS {
|
||||
cache.results.remove(0);
|
||||
@@ -305,6 +362,85 @@ impl DesktopDocStore {
|
||||
cache.results.push((query.to_owned(), limit, hits.clone()));
|
||||
hits
|
||||
}
|
||||
|
||||
pub(crate) fn search_tag_docs(&self, query: &str, limit: usize) -> Arc<[TagSearchHit]> {
|
||||
let limit = limit.min(QUICK_SEARCH_DOC_LIMIT);
|
||||
let query = query.trim().to_lowercase();
|
||||
if query.is_empty() || limit == 0 {
|
||||
return Arc::from([]);
|
||||
}
|
||||
let mut cache = self.search_cache();
|
||||
if let Some((_, _, hits)) = cache
|
||||
.tag_results
|
||||
.iter()
|
||||
.find(|(q, l, _)| *q == query && *l == limit)
|
||||
{
|
||||
return Arc::clone(hits);
|
||||
}
|
||||
let views = self.views();
|
||||
let candidates: BTreeSet<&str> = views
|
||||
.tags
|
||||
.iter()
|
||||
.filter(|tag| match_exact_substring_utf16(&tag.definition.name, &query).is_some())
|
||||
.flat_map(|tag| tag.docs.iter().map(String::as_str))
|
||||
.collect();
|
||||
let docs: Vec<_> = candidates
|
||||
.into_iter()
|
||||
.filter_map(|id| self.get_doc(id))
|
||||
.map(|entry| index_search_doc(&entry.meta, &views))
|
||||
.collect();
|
||||
let hits: Arc<_> = self
|
||||
.search_engine
|
||||
.search(&docs, &query, limit)
|
||||
.into_iter()
|
||||
.map(|hit| {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut matched_tags = Vec::new();
|
||||
for name in hit.matched_tags {
|
||||
if seen.insert(name.clone()) {
|
||||
matched_tags.push(name);
|
||||
}
|
||||
}
|
||||
TagSearchHit {
|
||||
doc_id: hit.doc_id,
|
||||
matched_tags,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
self.derived.count(|w| w.search_runs += 1);
|
||||
if cache.tag_results.len() == SEARCH_RESULT_SLOTS {
|
||||
cache.tag_results.remove(0);
|
||||
}
|
||||
cache.tag_results.push((query, limit, Arc::clone(&hits)));
|
||||
hits
|
||||
}
|
||||
|
||||
fn search_cache(&self) -> RefMut<'_, SearchCache> {
|
||||
let key = (self.active_workspace_idx, self.derived.meta_rev);
|
||||
let mut cache = self.derived.search.borrow_mut();
|
||||
if cache.key != Some(key) {
|
||||
*cache = SearchCache {
|
||||
key: Some(key),
|
||||
..SearchCache::default()
|
||||
};
|
||||
}
|
||||
cache
|
||||
}
|
||||
}
|
||||
|
||||
fn index_search_doc(doc: &DesktopDocMeta, views: &DocViews) -> SearchDocument {
|
||||
SearchDocument {
|
||||
id: doc.id.clone(),
|
||||
title: doc.title.clone(),
|
||||
tags: doc
|
||||
.tags
|
||||
.iter()
|
||||
.filter_map(|id| views.tag(id))
|
||||
.map(|tag| tag.definition.name.clone())
|
||||
.collect(),
|
||||
body_preview: doc.summary.clone(),
|
||||
updated_at_ms: doc.updated_at_ms,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_search(
|
||||
@@ -352,3 +488,133 @@ fn is_subsequence(needle: &str, haystack: &str) -> bool {
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use affine_store::{directory::DocMode, workspace_db::NavigationEdit};
|
||||
|
||||
use super::*;
|
||||
use crate::quick_search::{QuickSearchItem, QuickSearchState};
|
||||
|
||||
#[test]
|
||||
fn tag_search_filters_before_top_eight_and_bounds_cache_at_1000_docs() {
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
store.docs.clear();
|
||||
for i in 0..17 {
|
||||
let name = match i {
|
||||
0 | 16 => "Old name".into(),
|
||||
_ => format!("test-label-{i:02}"),
|
||||
};
|
||||
assert!(
|
||||
store
|
||||
.directory
|
||||
.db_mut()
|
||||
.edit_navigation(
|
||||
&NavigationEdit::CreateTag(WorkspaceTag {
|
||||
id: format!("test-tag-{i:02}"),
|
||||
name,
|
||||
color: String::new(),
|
||||
}),
|
||||
1,
|
||||
)
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
for i in 0..1000 {
|
||||
let title = if i < 40 && i > 2 { "Notes" } else { "New name" };
|
||||
let updated_at_ms = if i < 40 { i / 2 + 1 } else { 1000 };
|
||||
let id = store.create_doc(title, DocMode::Page, None, updated_at_ms);
|
||||
let meta = &mut store.docs.get_mut(&id).unwrap().meta;
|
||||
if i < 40 {
|
||||
meta.tags = (0..16).map(|i| format!("test-tag-{i:02}")).collect();
|
||||
if i == 0 {
|
||||
meta.tags.push("test-tag-16".into());
|
||||
}
|
||||
if i < 3 {
|
||||
meta.summary = "New name".into();
|
||||
}
|
||||
}
|
||||
}
|
||||
store.reindex_all();
|
||||
let mut qs = QuickSearchState::default();
|
||||
qs.set_query("#Old name");
|
||||
assert!(qs.items(&store).iter().any(|item| matches!(item,
|
||||
QuickSearchItem::Doc { summary, .. } if summary == "#Old name"
|
||||
)));
|
||||
|
||||
assert!(store.rename_tag("test-tag-00", "New name"));
|
||||
assert!(store.rename_tag("test-tag-16", "New name"));
|
||||
assert!(
|
||||
qs.items(&store)
|
||||
.iter()
|
||||
.all(|item| matches!(item, QuickSearchItem::Command(_)))
|
||||
);
|
||||
|
||||
qs.set_query("#New name");
|
||||
let found: Vec<_> = qs
|
||||
.items(&store)
|
||||
.into_iter()
|
||||
.filter_map(|item| match item {
|
||||
QuickSearchItem::Doc {
|
||||
doc_id, summary, ..
|
||||
} => {
|
||||
assert_eq!(summary, "#New name");
|
||||
Some(doc_id)
|
||||
}
|
||||
QuickSearchItem::Command(_) => None,
|
||||
})
|
||||
.collect();
|
||||
let full = store.search_docs("New name", 0);
|
||||
assert_eq!(full.len(), 1000);
|
||||
assert_eq!(
|
||||
full.iter()
|
||||
.take(8)
|
||||
.filter(|hit| !hit.matched_tags.is_empty())
|
||||
.count(),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
full.iter()
|
||||
.filter(|hit| !hit.matched_tags.is_empty())
|
||||
.count(),
|
||||
40
|
||||
);
|
||||
let expected: Vec<_> = full
|
||||
.iter()
|
||||
.filter(|hit| !hit.matched_tags.is_empty())
|
||||
.take(8)
|
||||
.map(|hit| hit.doc_id.as_str())
|
||||
.collect();
|
||||
assert_eq!(found.len(), 8);
|
||||
assert_eq!(found, expected);
|
||||
assert_eq!(found.iter().collect::<BTreeSet<_>>().len(), 8);
|
||||
|
||||
let cached = store.search_tag_docs("New name", 8);
|
||||
assert!(Arc::ptr_eq(
|
||||
&cached,
|
||||
&store.search_tag_docs(" NEW NAME ", 8)
|
||||
));
|
||||
for i in 1..16 {
|
||||
qs.set_query(format!("#test-label-{i:02}"));
|
||||
assert_eq!(
|
||||
qs.items(&store)
|
||||
.into_iter()
|
||||
.filter(|item| matches!(item, QuickSearchItem::Doc { .. }))
|
||||
.count(),
|
||||
8
|
||||
);
|
||||
}
|
||||
let cache = store.derived.search.borrow();
|
||||
assert_eq!(cache.tag_results.len(), 16);
|
||||
assert_eq!(
|
||||
cache
|
||||
.tag_results
|
||||
.iter()
|
||||
.map(|(_, _, hits)| hits.len())
|
||||
.sum::<usize>(),
|
||||
128
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,11 @@ use affine_client::Scope;
|
||||
use affine_store::directory::DocMode;
|
||||
use ui::{Bounds, Context, Pixels, Window};
|
||||
|
||||
use crate::{doc_store::DesktopDocStore, split_view::SplitLayout, workbench::DesktopShellView};
|
||||
use crate::{
|
||||
doc_store::{DesktopDocStore, QUICK_SEARCH_DOC_LIMIT},
|
||||
split_view::SplitLayout,
|
||||
workbench::DesktopShellView,
|
||||
};
|
||||
|
||||
mod modal;
|
||||
|
||||
@@ -160,18 +164,30 @@ impl QuickSearchState {
|
||||
|
||||
fn items_with_recent(&self, store: &DesktopDocStore, recent: &[&str]) -> Vec<QuickSearchItem> {
|
||||
let query = self.query.trim();
|
||||
let tag = query.strip_prefix('#').map(str::trim);
|
||||
let hits = match tag {
|
||||
Some("") => Vec::new(),
|
||||
Some(name) => store.search_docs(name, 0),
|
||||
None => store.search_docs(query, if query.is_empty() { 16 } else { 8 }),
|
||||
let (text_hits, tag_hits) = if let Some(name) = query.strip_prefix('#') {
|
||||
(
|
||||
Vec::new(),
|
||||
store.search_tag_docs(name, QUICK_SEARCH_DOC_LIMIT),
|
||||
)
|
||||
} else {
|
||||
let limit = if query.is_empty() {
|
||||
16
|
||||
} else {
|
||||
QUICK_SEARCH_DOC_LIMIT
|
||||
};
|
||||
(store.search_docs(query, limit), Default::default())
|
||||
};
|
||||
let visited = recent.iter().map(|&id| (id, &[][..], true));
|
||||
let matched = hits
|
||||
let matched = text_hits
|
||||
.iter()
|
||||
.filter(|hit| tag.is_none() || !hit.matched_tags.is_empty())
|
||||
.filter(|hit| !recent.contains(&hit.doc_id.as_str()))
|
||||
.map(|hit| (hit.doc_id.as_str(), hit.matched_tags.as_slice(), false));
|
||||
.map(|hit| (hit.doc_id.as_str(), hit.matched_tags.as_slice()))
|
||||
.chain(
|
||||
tag_hits
|
||||
.iter()
|
||||
.map(|hit| (hit.doc_id.as_str(), hit.matched_tags.as_slice())),
|
||||
)
|
||||
.filter(|(id, _)| !recent.contains(id))
|
||||
.map(|(id, tags)| (id, tags, false));
|
||||
let mut out: Vec<_> = visited
|
||||
.chain(matched)
|
||||
.filter_map(|(doc_id, tags, recent)| {
|
||||
@@ -192,7 +208,7 @@ impl QuickSearchState {
|
||||
recent,
|
||||
})
|
||||
})
|
||||
.take(8)
|
||||
.take(QUICK_SEARCH_DOC_LIMIT)
|
||||
.collect();
|
||||
let q = query.to_ascii_lowercase();
|
||||
for cmd in QuickCommandId::ALL {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
use std::{
|
||||
collections::hash_map::DefaultHasher,
|
||||
hash::{Hash, Hasher},
|
||||
};
|
||||
|
||||
use blocksuite_editor::{
|
||||
database::format_database_created_time,
|
||||
inline_input::{Utf16ImeBuffer, utf16_to_byte},
|
||||
match_exact_substring_utf16,
|
||||
};
|
||||
use ui::{
|
||||
App, BoxShadow, Context, CursorStyle, FocusHandle, FontWeight, HighlightStyle,
|
||||
InteractiveElement, IntoElement, MouseButton, ParentElement, RenderOnce, SharedString,
|
||||
App, BoxShadow, Context, CursorStyle, ElementId, FocusHandle, FontWeight, HighlightStyle,
|
||||
InteractiveElement, IntoElement, MouseButton, ParentElement, RenderOnce,
|
||||
StatefulInteractiveElement, Styled, StyledText, Window, div, hsla, px, svg,
|
||||
};
|
||||
use ui_tokens::{DARK_THEME, FONT_SANS, LIGHT_THEME};
|
||||
@@ -92,35 +97,40 @@ impl RenderOnce for QuickSearchModal {
|
||||
));
|
||||
last_group = group;
|
||||
}
|
||||
let (id, icon, title, subtitle, detail) = match &item {
|
||||
let (id, snapshot, icon, title, subtitle, detail) = match &item {
|
||||
QuickSearchItem::Doc {
|
||||
doc_id,
|
||||
title,
|
||||
summary,
|
||||
is_edgeless,
|
||||
..
|
||||
} => (
|
||||
format!("desktop.qs.doc.{doc_id}"),
|
||||
if *is_edgeless {
|
||||
EDGELESS_ICON_SVG
|
||||
} else {
|
||||
DOC_ICON_SVG
|
||||
},
|
||||
if title.is_empty() {
|
||||
"Untitled".into()
|
||||
} else {
|
||||
title.clone()
|
||||
},
|
||||
if query.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
summary.clone()
|
||||
},
|
||||
store
|
||||
.get_doc(doc_id)
|
||||
.map(|entry| updated_time(entry.meta.updated_at_ms))
|
||||
.unwrap_or_default(),
|
||||
),
|
||||
} => {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
doc_id.hash(&mut hasher);
|
||||
(
|
||||
ElementId::from(("quick-search-document", hasher.finish())),
|
||||
ui::snap_id!("desktop.qs.doc.{doc_id}"),
|
||||
if *is_edgeless {
|
||||
EDGELESS_ICON_SVG
|
||||
} else {
|
||||
DOC_ICON_SVG
|
||||
},
|
||||
if title.is_empty() {
|
||||
"Untitled".into()
|
||||
} else {
|
||||
title.clone()
|
||||
},
|
||||
if query.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
summary.clone()
|
||||
},
|
||||
store
|
||||
.get_doc(doc_id)
|
||||
.map(|entry| updated_time(entry.meta.updated_at_ms))
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
QuickSearchItem::Command(cmd) => {
|
||||
let mode = match cmd {
|
||||
QuickCommandId::NewPage => "Page",
|
||||
@@ -140,7 +150,8 @@ impl RenderOnce for QuickSearchModal {
|
||||
QuickCommandId::ToggleTheme => SEARCH_ICON_SVG,
|
||||
};
|
||||
(
|
||||
format!("desktop.qs.cmd.{index}"),
|
||||
ElementId::from(("quick-search-command", index)),
|
||||
ui::snap_id!("desktop.qs.cmd.{index}"),
|
||||
icon,
|
||||
title,
|
||||
String::new(),
|
||||
@@ -160,8 +171,8 @@ impl RenderOnce for QuickSearchModal {
|
||||
offset,
|
||||
RESULT_ROW,
|
||||
div()
|
||||
.id(SharedString::from(id.clone()))
|
||||
.snapshot(id, Some("desktop.qs.modal"))
|
||||
.id(id)
|
||||
.snapshot(snapshot, Some("desktop.qs.modal"))
|
||||
.w_full()
|
||||
.h(px(RESULT_ROW))
|
||||
.flex_shrink(0.0)
|
||||
@@ -173,7 +184,7 @@ impl RenderOnce for QuickSearchModal {
|
||||
.bg(if index == selected {
|
||||
palette.bg_pill
|
||||
} else {
|
||||
hsla(0.0, 0.0, 0.0, 0.0)
|
||||
ui::transparent_black()
|
||||
})
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(palette.bg_pill))
|
||||
|
||||
@@ -155,14 +155,18 @@ fn build_rows(sidebar: &SidebarState, store: &DesktopDocStore) -> Vec<SidebarRow
|
||||
}
|
||||
SidebarSection::Folders => push_folder_rows(&mut rows, &views.folders, sidebar),
|
||||
SidebarSection::Tags => {
|
||||
for (index, (tag, _, count)) in views.tags.iter().enumerate() {
|
||||
for (index, tag) in views.tags.iter().enumerate() {
|
||||
rows.push(SidebarRow::Tag(index));
|
||||
let group = TreeGroup::Tag(tag.clone());
|
||||
let group = TreeGroup::Tag(tag.definition.id.clone());
|
||||
if sidebar.expanded_groups.contains(&group) {
|
||||
if *count == 0 {
|
||||
if tag.docs.is_empty() {
|
||||
rows.push(SidebarRow::Empty("Empty", 1));
|
||||
} else {
|
||||
push_group_docs(&mut rows, &group, store.docs_for_tag(tag));
|
||||
push_group_docs(
|
||||
&mut rows,
|
||||
&group,
|
||||
store.docs_for_tag(&tag.definition.id),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,6 +299,81 @@ pub(crate) fn render_tree_rows(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sidebar_counts_and_search_hide_deleted_tags_and_keep_empty_definitions() {
|
||||
use affine_store::{
|
||||
directory::DocMode,
|
||||
workspace_db::{NavigationEdit, WorkspaceTag},
|
||||
};
|
||||
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
store.switch_workspace(1);
|
||||
let docs = ["First", "Second"].map(|title| {
|
||||
let id = store.create_doc(title, DocMode::Page, None, 1);
|
||||
store.docs.get_mut(&id).unwrap().meta.tags = vec!["architecture".into()];
|
||||
id
|
||||
});
|
||||
let mut sidebar = SidebarState::default();
|
||||
sidebar.expanded_sections.insert(SidebarSection::Tags);
|
||||
for id in ["architecture", "unassigned"] {
|
||||
assert!(
|
||||
store
|
||||
.directory
|
||||
.db_mut()
|
||||
.edit_navigation(
|
||||
&NavigationEdit::CreateTag(WorkspaceTag {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
color: "--affine-tag-blue".into(),
|
||||
}),
|
||||
1,
|
||||
)
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
store.reindex_all();
|
||||
assert_eq!(store.docs_for_tag("architecture").len(), 2);
|
||||
assert_eq!(store.search_tag_docs("architecture", 8).len(), 2);
|
||||
|
||||
store
|
||||
.directory
|
||||
.db_mut()
|
||||
.edit_navigation(&NavigationEdit::DeleteTag("architecture".into()), 2)
|
||||
.unwrap();
|
||||
// A concurrent page update can reintroduce the deleted ID.
|
||||
let meta = &mut store.docs.get_mut(&docs[0]).unwrap().meta;
|
||||
meta.tags = vec!["architecture".into()];
|
||||
store.reindex_all();
|
||||
|
||||
assert_eq!(
|
||||
store.all_tags_with_counts(),
|
||||
[("unassigned".into(), 0xe1eeff, 0)]
|
||||
);
|
||||
let empty_group = TreeGroup::Tag("unassigned".into());
|
||||
sidebar.expanded_groups.insert(empty_group);
|
||||
let rows = build_rows(&sidebar, &store);
|
||||
let tag_rows: Vec<_> = rows
|
||||
.iter()
|
||||
.skip_while(|row| **row != SidebarRow::Section(SidebarSection::Tags))
|
||||
.skip(1)
|
||||
.take_while(|row| !matches!(row, SidebarRow::Section(_)))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
tag_rows,
|
||||
[&SidebarRow::Tag(0), &SidebarRow::Empty("Empty", 1)]
|
||||
);
|
||||
assert!(store.docs_for_tag("architecture").is_empty());
|
||||
assert!(store.search_tag_docs("architecture", 8).is_empty());
|
||||
assert!(
|
||||
store
|
||||
.search_docs("architecture", 0)
|
||||
.iter()
|
||||
.all(|hit| hit.matched_tags.is_empty())
|
||||
);
|
||||
assert_eq!(store.docs[&docs[0]].meta.tags, ["architecture"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidebar_tree_keeps_documents_below_four_nested_folders() {
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
|
||||
@@ -125,19 +125,21 @@ pub(super) fn render_row(
|
||||
)
|
||||
}
|
||||
SidebarRow::Tag(index) => {
|
||||
let Some((tag, color, _)) = views.tags.get(*index) else {
|
||||
let Some(tag) = views.tags.get(*index) else {
|
||||
return div().into_any_element();
|
||||
};
|
||||
let theme = if palette.bg_canvas.l < 0.5 {
|
||||
&ui_tokens::DARK_THEME
|
||||
} else {
|
||||
&ui_tokens::LIGHT_THEME
|
||||
};
|
||||
let id = &tag.definition.id;
|
||||
presentation.group(
|
||||
format!("desktop.sidebar.tag.{tag}"),
|
||||
NodeIcon::Dot(*color),
|
||||
views
|
||||
.tag_labels
|
||||
.get(tag)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| tag.clone()),
|
||||
TreeGroup::Tag(tag.clone()),
|
||||
DesktopRoute::Tag(tag.clone()),
|
||||
format!("desktop.sidebar.tag.{id}"),
|
||||
NodeIcon::Dot(tag.color(theme)),
|
||||
tag.definition.name.clone(),
|
||||
TreeGroup::Tag(id.clone()),
|
||||
DesktopRoute::Tag(id.clone()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user