perf(desktop): virtualize sidebar rows and strip snapshot strings

Store compact row references in the sidebar tree index instead of full
row strings. Build full row data only for rows inside the visible
window, and hash structured keys into numeric element IDs.

Replace dynamic snapshot format strings in sidebar and outline rail
elements with fixed static literals via `ui::snap_id!`.

Use the hover overlay color for the sidebar row action buttons, as the
Web `IconButton` does. The hover test now checks the section add button.
This commit is contained in:
DarkSky committed 2026-12-04 05:13:44 +09:00
1 parent 671bf1e4cb
commit c5ee94a3bf
4 files changed
+866 -143

No files matched your search

+2 -2
View File
@@ -11,7 +11,7 @@ use ui_tokens::FONT_SANS;
use crate::{
DesktopFlexExt, DesktopPalette, JOURNAL_ICON_SVG, SETTINGS_ICON_SVG,
doc_store::DesktopDocStore,
sidebar_tree::{SidebarRowIndex, TreeGroup, nav_row, render_tree_rows},
sidebar_tree::{SidebarRowIndex, SidebarRowKey, TreeGroup, nav_row, render_tree_rows},
split_view::DesktopRoute,
workbench::DesktopShellView,
};
@@ -48,7 +48,7 @@ pub struct SidebarState {
pub expanded_folders: BTreeSet<String>,
pub workspace_menu_open: bool,
pub(crate) expanded_groups: BTreeSet<TreeGroup>,
pub(crate) hovered_row: Option<ui::SharedString>,
pub(crate) hovered_row: Option<SidebarRowKey>,
pub(crate) popup: Option<Popup>,
}
+730 -77
View File
@@ -1,13 +1,13 @@
//! Virtualized workspace navigation tree.
use std::collections::BTreeSet;
use std::collections::{BTreeSet, HashSet};
use ui::{Context, ParentElement, Styled, div, px};
use ui_kit::{VirtualList, VirtualWindow};
use crate::{
DesktopPalette,
doc_store::{DesktopDocMeta, DesktopDocStore, FolderChild, SidebarFolderTree},
doc_store::{DesktopDocStore, DocViews, FolderChild, SidebarFolderTree},
sidebar::{SidebarSection, SidebarState},
split_view::DesktopRoute,
workbench::DesktopShellView,
@@ -48,7 +48,90 @@ pub(crate) enum SidebarRow {
},
}
impl SidebarRow {
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum SidebarRowKey {
Section(SidebarSection),
Favorite(String),
Folder(String),
FolderDoc {
folder_id: Option<String>,
link_id: String,
doc_id: String,
},
Collection(String),
CollectionDoc {
col_id: String,
doc_id: String,
},
Tag(String),
TagDoc {
tag_id: String,
doc_id: String,
},
}
impl SidebarRowKey {
pub(super) fn element_id(&self) -> ui::ElementId {
let (kind, hash) = match self {
Self::Section(section) => ("sidebar-sec", *section as u64),
Self::Favorite(doc_id) => ("sidebar-fav", ui::hash(doc_id)),
Self::Folder(id) => ("sidebar-folder", ui::hash(id)),
Self::FolderDoc {
folder_id,
link_id,
doc_id,
} => (
"sidebar-fdoc",
ui::hash(&(
folder_id.as_deref().unwrap_or(""),
link_id.as_str(),
doc_id.as_str(),
)),
),
Self::Collection(id) => ("sidebar-col", ui::hash(id)),
Self::CollectionDoc { col_id, doc_id } => (
"sidebar-col-doc",
ui::hash(&(col_id.as_str(), doc_id.as_str())),
),
Self::Tag(id) => ("sidebar-tag", ui::hash(id)),
Self::TagDoc { tag_id, doc_id } => (
"sidebar-tag-doc",
ui::hash(&(tag_id.as_str(), doc_id.as_str())),
),
};
ui::ElementId::NamedInteger(ui::SharedString::new_static(kind), hash)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RowRef {
Trash,
Empty(&'static str, u16),
Section(SidebarSection),
Favorite(u32),
Folder {
parent_row: Option<u32>,
child_idx: u32,
depth: u16,
},
FolderDoc {
parent_row: Option<u32>,
child_idx: u32,
depth: u16,
},
Collection(u32),
Tag(u32),
CollectionDoc {
col_idx: u32,
visible_idx: u32,
},
TagDoc {
tag_idx: u32,
doc_idx: u32,
},
}
impl RowRef {
fn extent(&self) -> f32 {
let height = match self {
Self::Section(_) => 24.0,
@@ -72,7 +155,7 @@ struct RowKey {
#[derive(Debug, Default)]
pub struct SidebarRowIndex {
key: Option<RowKey>,
rows: Vec<SidebarRow>,
rows: Vec<RowRef>,
list: Option<VirtualList>,
viewport_height: f32,
builds: u64,
@@ -108,7 +191,7 @@ impl SidebarRowIndex {
(content + TREE_BOTTOM - self.viewport_height).max(0.0)
}
fn sync(&mut self, sidebar: &SidebarState, store: &DesktopDocStore) {
fn sync(&mut self, sidebar: &SidebarState, store: &DesktopDocStore, views: &DocViews) {
let meta_rev = store.derived.meta_rev;
if self.key.as_ref().is_some_and(|k| {
k.meta_rev == meta_rev
@@ -119,17 +202,29 @@ impl SidebarRowIndex {
}) {
return;
}
self.rows = build_rows(sidebar, store);
self.rows.clear();
build_row_refs(&mut self.rows, sidebar, store, views);
self.list = Some(VirtualList::variable(
self.rows.iter().map(SidebarRow::extent).collect(),
self.rows.iter().map(RowRef::extent).collect(),
));
self.key = Some(RowKey {
meta_rev,
sections: sidebar.expanded_sections.clone(),
folders: sidebar.expanded_folders.clone(),
groups: sidebar.expanded_groups.clone(),
workspace_id: store.active_workspace().id.clone(),
});
match &mut self.key {
Some(key) => {
key.meta_rev = meta_rev;
key.sections.clone_from(&sidebar.expanded_sections);
key.folders.clone_from(&sidebar.expanded_folders);
key.groups.clone_from(&sidebar.expanded_groups);
key.workspace_id.clone_from(&store.active_workspace().id);
}
None => {
self.key = Some(RowKey {
meta_rev,
sections: sidebar.expanded_sections.clone(),
folders: sidebar.expanded_folders.clone(),
groups: sidebar.expanded_groups.clone(),
workspace_id: store.active_workspace().id.clone(),
});
}
}
self.builds += 1;
}
}
@@ -140,9 +235,68 @@ pub(crate) enum TreeGroup {
Tag(String),
}
fn build_rows(sidebar: &SidebarState, store: &DesktopDocStore) -> Vec<SidebarRow> {
let views = store.views();
let mut rows = Vec::new();
struct ExpandedGroupsLookup<'a> {
collections: HashSet<&'a str>,
tags: HashSet<&'a str>,
#[cfg(test)]
probes: std::cell::Cell<usize>,
}
impl<'a> ExpandedGroupsLookup<'a> {
fn from_groups(groups: &'a BTreeSet<TreeGroup>) -> Option<Self> {
if groups.is_empty() {
return None;
}
let mut collections = HashSet::new();
let mut tags = HashSet::new();
for group in groups {
match group {
TreeGroup::Collection(id) => {
collections.insert(id.as_str());
}
TreeGroup::Tag(id) => {
tags.insert(id.as_str());
}
}
}
Some(Self {
collections,
tags,
#[cfg(test)]
probes: std::cell::Cell::new(0),
})
}
fn has_collection(&self, id: &str) -> bool {
#[cfg(test)]
self.probes.set(self.probes.get() + 1);
self.collections.contains(id)
}
fn has_tag(&self, id: &str) -> bool {
#[cfg(test)]
self.probes.set(self.probes.get() + 1);
self.tags.contains(id)
}
}
fn build_row_refs(
rows: &mut Vec<RowRef>,
sidebar: &SidebarState,
store: &DesktopDocStore,
views: &DocViews,
) {
let expanded_groups = ExpandedGroupsLookup::from_groups(&sidebar.expanded_groups);
build_row_refs_with_lookup(rows, sidebar, store, views, expanded_groups.as_ref());
}
fn build_row_refs_with_lookup(
rows: &mut Vec<RowRef>,
sidebar: &SidebarState,
store: &DesktopDocStore,
views: &DocViews,
expanded_groups: Option<&ExpandedGroupsLookup<'_>>,
) {
for (section, empty) in [
(SidebarSection::Favorites, "No favorites"),
(SidebarSection::Folders, "Empty"),
@@ -150,104 +304,215 @@ fn build_rows(sidebar: &SidebarState, store: &DesktopDocStore) -> Vec<SidebarRow
(SidebarSection::Collections, "No collections"),
(SidebarSection::Others, "Empty"),
] {
rows.push(SidebarRow::Section(section));
rows.push(RowRef::Section(section));
if !sidebar.expanded_sections.contains(&section) {
continue;
}
let start = rows.len();
match section {
SidebarSection::Favorites => {
rows.extend(views.favorites.iter().cloned().map(SidebarRow::Favorite));
rows.reserve(views.favorites.len());
rows.extend((0..views.favorites.len() as u32).map(RowRef::Favorite));
}
SidebarSection::Folders => push_folder_rows(&mut rows, &views.folders, sidebar),
SidebarSection::Folders => push_folder_row_refs(rows, &views.folders, sidebar),
SidebarSection::Tags => {
for (index, tag) in views.tags.iter().enumerate() {
rows.push(SidebarRow::Tag(index));
let group = TreeGroup::Tag(tag.definition.id.clone());
if sidebar.expanded_groups.contains(&group) {
rows.push(RowRef::Tag(index as u32));
if expanded_groups
.as_ref()
.is_some_and(|groups| groups.has_tag(&tag.definition.id))
{
if tag.docs.is_empty() {
rows.push(SidebarRow::Empty("Empty", 1));
rows.push(RowRef::Empty("Empty", 1));
} else {
push_group_docs(
&mut rows,
&group,
store.docs_for_tag(&tag.definition.id),
);
rows.reserve(tag.docs.len());
rows.extend((0..tag.docs.len() as u32).map(|doc_idx| RowRef::TagDoc {
tag_idx: index as u32,
doc_idx,
}));
}
}
}
}
SidebarSection::Collections => {
for (index, collection) in store.collections.iter().enumerate() {
rows.push(SidebarRow::Collection(index));
let group = TreeGroup::Collection(collection.id.clone());
if sidebar.expanded_groups.contains(&group) {
rows.push(RowRef::Collection(index as u32));
if expanded_groups
.as_ref()
.is_some_and(|groups| groups.has_collection(&collection.id))
{
if views.collection_counts.get(index) == Some(&0) {
rows.push(SidebarRow::Empty("Empty", 1));
rows.push(RowRef::Empty("Empty", 1));
} else {
push_group_docs(
&mut rows,
&group,
store.docs_for_collection(&collection.id),
);
for (visible_idx, doc_id) in views.visible.iter().enumerate() {
if store
.get_doc(doc_id)
.is_some_and(|doc| collection.matches(&doc.meta))
{
rows.push(RowRef::CollectionDoc {
col_idx: index as u32,
visible_idx: visible_idx as u32,
});
}
}
}
}
}
}
SidebarSection::Others => rows.push(SidebarRow::Trash),
SidebarSection::Others => rows.push(RowRef::Trash),
}
if start == rows.len() {
rows.push(SidebarRow::Empty(empty, 0));
rows.push(RowRef::Empty(empty, 0));
}
}
rows
}
fn push_group_docs(rows: &mut Vec<SidebarRow>, group: &TreeGroup, docs: Vec<&DesktopDocMeta>) {
rows.extend(docs.into_iter().map(|doc| SidebarRow::GroupDoc {
group: group.clone(),
doc_id: doc.id.clone(),
}));
}
fn push_folder_rows(rows: &mut Vec<SidebarRow>, tree: &SidebarFolderTree, sidebar: &SidebarState) {
let mut pending = Vec::new();
pending.extend(
tree.children(None)
.iter()
.rev()
.map(|child| (None, child, 0)),
);
while let Some((parent, child, depth)) = pending.pop() {
match child {
fn push_folder_row_refs(rows: &mut Vec<RowRef>, tree: &SidebarFolderTree, sidebar: &SidebarState) {
let roots = tree.children(None);
let mut pending = Vec::with_capacity(roots.len());
pending.extend((0..roots.len()).rev().map(|i| (None, None, i as u32, 0u16)));
while let Some((parent_id, parent_row, child_idx, depth)) = pending.pop() {
match &tree.children(parent_id)[child_idx as usize] {
FolderChild::Folder(id) => {
rows.push(SidebarRow::Folder {
id: id.clone(),
let row_idx = rows.len() as u32;
rows.push(RowRef::Folder {
parent_row,
child_idx,
depth,
});
if sidebar.expanded_folders.contains(id) {
let children = tree.children(Some(id));
if children.is_empty() {
rows.push(SidebarRow::Empty("Empty", depth + 1));
rows.push(RowRef::Empty("Empty", depth + 1));
} else {
rows.reserve(children.len());
pending.extend(
(0..children.len())
.rev()
.map(|i| (Some(id.as_str()), Some(row_idx), i as u32, depth + 1)),
);
}
pending.extend(
children
.iter()
.rev()
.map(|child| (Some(id.as_str()), child, depth + 1)),
);
}
}
FolderChild::Doc { link, doc } => rows.push(SidebarRow::FolderDoc {
folder_id: parent.map(str::to_owned),
link_id: link.clone(),
doc_id: doc.clone(),
FolderChild::Doc { .. } => rows.push(RowRef::FolderDoc {
parent_row,
child_idx,
depth,
}),
}
}
}
fn resolve_folder_child<'a>(
rows: &[RowRef],
tree: &'a SidebarFolderTree,
parent_row: Option<u32>,
child_idx: u32,
) -> Option<(Option<&'a str>, &'a FolderChild)> {
let parent_id = match parent_row {
None => None,
Some(idx) => {
let RowRef::Folder {
parent_row: grand_parent,
child_idx: parent_child_idx,
..
} = rows.get(idx as usize)?
else {
return None;
};
let (_, FolderChild::Folder(id)) =
resolve_folder_child(rows, tree, *grand_parent, *parent_child_idx)?
else {
return None;
};
Some(id.as_str())
}
};
let child = tree.children(parent_id).get(child_idx as usize)?;
Some((parent_id, child))
}
fn materialize_row(
row_ref: &RowRef,
rows: &[RowRef],
views: &DocViews,
store: &DesktopDocStore,
) -> Option<SidebarRow> {
match row_ref {
RowRef::Trash => Some(SidebarRow::Trash),
RowRef::Empty(msg, depth) => Some(SidebarRow::Empty(msg, usize::from(*depth))),
RowRef::Section(section) => Some(SidebarRow::Section(*section)),
RowRef::Favorite(idx) => views
.favorites
.get(*idx as usize)
.cloned()
.map(SidebarRow::Favorite),
RowRef::Folder {
parent_row,
child_idx,
depth,
} => {
let (_, FolderChild::Folder(id)) =
resolve_folder_child(rows, &views.folders, *parent_row, *child_idx)?
else {
return None;
};
Some(SidebarRow::Folder {
id: id.clone(),
depth: usize::from(*depth),
})
}
RowRef::FolderDoc {
parent_row,
child_idx,
depth,
} => {
let (folder_id, FolderChild::Doc { link, doc }) =
resolve_folder_child(rows, &views.folders, *parent_row, *child_idx)?
else {
return None;
};
Some(SidebarRow::FolderDoc {
folder_id: folder_id.map(str::to_owned),
link_id: link.clone(),
doc_id: doc.clone(),
depth: usize::from(*depth),
})
}
RowRef::Collection(idx) => Some(SidebarRow::Collection(*idx as usize)),
RowRef::Tag(idx) => Some(SidebarRow::Tag(*idx as usize)),
RowRef::CollectionDoc {
col_idx,
visible_idx,
} => {
let col = store.collections.get(*col_idx as usize)?;
let doc_id = views.visible.get(*visible_idx as usize)?;
Some(SidebarRow::GroupDoc {
group: TreeGroup::Collection(col.id.clone()),
doc_id: doc_id.clone(),
})
}
RowRef::TagDoc { tag_idx, doc_idx } => {
let tag = views.tags.get(*tag_idx as usize)?;
let doc_id = tag.docs.get(*doc_idx as usize)?;
Some(SidebarRow::GroupDoc {
group: TreeGroup::Tag(tag.definition.id.clone()),
doc_id: doc_id.clone(),
})
}
}
}
#[cfg(test)]
fn build_rows(sidebar: &SidebarState, store: &DesktopDocStore) -> Vec<SidebarRow> {
let views = store.views();
let mut refs = Vec::new();
build_row_refs(&mut refs, sidebar, store, &views);
refs.iter()
.filter_map(|row_ref| materialize_row(row_ref, &refs, &views, store))
.collect()
}
/// 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,
@@ -258,7 +523,8 @@ pub(crate) fn render_tree_rows(
palette: DesktopPalette,
cx: &mut Context<DesktopShellView>,
) -> ui::Div {
index.sync(sidebar, store);
let views = store.views();
index.sync(sidebar, store, &views);
index.drag_rows = DragRows::default();
index.viewport_height = viewport_height;
sidebar.scroll_y = sidebar.scroll_y.clamp(0.0, index.max_scroll());
@@ -266,7 +532,6 @@ pub(crate) fn render_tree_rows(
return div();
};
let window = list.window(viewport_height, sidebar.scroll_y, OVERSCAN_PX);
let views = store.views();
let mut col = div()
.flex()
.flex_col()
@@ -278,9 +543,12 @@ pub(crate) fn render_tree_rows(
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()] {
let element = render_row(row, sidebar, store, &views, active_route, palette, cx);
col = col.child(drop_row(row, element, index, store, palette, cx));
for row_ref in &index.rows[window.visible_range.clone()] {
let Some(row) = materialize_row(row_ref, &index.rows, &views, store) else {
continue;
};
let element = render_row(&row, sidebar, store, &views, active_route, palette, cx);
col = col.child(drop_row(&row, element, index, store, palette, cx));
}
if window.visible_range.end < index.rows.len() {
col = col.child(div().w_full().h(px(window.trailing_spacer - ROW_GAP)));
@@ -423,7 +691,7 @@ mod tests {
}
#[test]
fn sidebar_navigation_and_section_rows_use_hover_overlay_and_tree_nodes_use_hover_color()
fn sidebar_navigation_rows_section_rows_and_action_buttons_use_hover_overlay_and_tree_nodes_use_hover_color()
-> anyhow::Result<()> {
use anyhow::Context as _;
use ui::{
@@ -499,6 +767,12 @@ mod tests {
"desktop.sidebar.sec.favorites",
overlay,
),
(
DesktopRoute::AllDocs,
Some("desktop.sidebar.sec.favorites.add"),
"desktop.sidebar.sec.favorites.add",
overlay,
),
(
DesktopRoute::Doc(favorite.clone()),
None,
@@ -563,4 +837,383 @@ mod tests {
}
Ok(())
}
#[test]
fn sidebar_row_index_virtualizes_1024_docs_and_keeps_distinct_row_keys() -> anyhow::Result<()> {
use std::collections::{BTreeSet, HashSet};
use affine_store::directory::DocMode;
use anyhow::Context as _;
use ui::{
AppContext, Application, Bounds, HeadlessPlatform, Modifiers, MouseMoveEvent,
PlatformInput, WindowBounds, WindowOptions, point, px, size,
};
use ui_tokens::ThemeMode;
use crate::{DesktopAppState, register_desktop_fonts};
let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
let folder = state.create_folder("Scale", None);
state.sidebar.expanded_folders.remove(&folder);
let shared_doc = state.store.favorite_docs()[0].id.clone();
let col_id = state.store.collections[0].id.clone();
let tag_id = state
.store
.all_tags_with_counts()
.into_iter()
.find(|t| t.2 > 0)
.context("a populated tag")?
.0;
let tagged_doc = state.store.docs_for_tag(&tag_id)[0].id.clone();
for i in 0..1024 {
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));
}
let keys = [
SidebarRowKey::Favorite(shared_doc.clone()),
SidebarRowKey::FolderDoc {
folder_id: Some(folder.clone()),
link_id: "link-1".into(),
doc_id: shared_doc.clone(),
},
SidebarRowKey::CollectionDoc {
col_id: col_id.clone(),
doc_id: shared_doc.clone(),
},
SidebarRowKey::TagDoc {
tag_id: tag_id.clone(),
doc_id: shared_doc.clone(),
},
];
assert_eq!(
keys.iter().collect::<HashSet<_>>().len(),
keys.len(),
"SidebarRowKey must distinguish every placement kind"
);
assert_eq!(
keys.iter()
.map(|k| format!("{:?}", k.element_id()))
.collect::<BTreeSet<_>>()
.len(),
keys.len(),
"ElementId must distinguish every placement kind"
);
let platform = HeadlessPlatform::new(1280, 720, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|_| {});
let handle = app.update(|cx| {
register_desktop_fonts(cx)?;
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(1280.0), px(720.0)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| DesktopShellView::new(state, cx)),
)
})?;
let window = platform
.windows()
.into_iter()
.next()
.context("get the headless window")?;
window.request_frame();
let collapsed = app.update(|cx| {
handle.update(cx, |view, _, _| {
(
view.sidebar_rows().builds(),
view.sidebar_rows().row_count(),
view.sidebar_rows().mounted_rows(),
)
})
})?;
assert_eq!(collapsed.0, 1);
assert!(collapsed.2 <= 32, "collapsed mounted {}", collapsed.2);
app.update(|cx| {
handle.update(cx, |view, _, cx| {
view.state.sidebar.toggle_folder(&folder);
view.state
.sidebar
.expanded_groups
.insert(TreeGroup::Tag(tag_id.clone()));
cx.notify();
})
})?;
window.request_frame();
let expanded = app.update(|cx| {
handle.update(cx, |view, _, _| {
(
view.sidebar_rows().builds(),
view.sidebar_rows().row_count(),
view.sidebar_rows().mounted_rows(),
view.sidebar_rows().max_scroll(),
)
})
})?;
assert_eq!(expanded.0, 2);
assert!(expanded.1 > 1024, "expected >1024 rows, got {}", expanded.1);
assert!(expanded.2 <= 32, "expanded mounted {}", expanded.2);
// Redraw and scroll must not rebuild the row index.
app.update(|cx| {
handle.update(cx, |view, _, cx| {
view.state.sidebar.scroll_y = expanded.3 * 0.5;
cx.notify();
})
})?;
window.request_frame();
app.update(|cx| {
handle.update(cx, |view, _, _| {
assert_eq!(view.sidebar_rows().builds(), 2);
assert!(view.sidebar_rows().mounted_rows() <= 32);
})
})?;
// Scroll back to top and hover the same doc in Favorites vs Organize folder.
app.update(|cx| {
handle.update(cx, |view, _, cx| {
view.state.sidebar.scroll_y = 0.0;
cx.notify();
})
})?;
window.request_frame();
let (doc_folder, folder_doc) = app.update(|cx| {
handle.update(cx, |_, window, _| {
window
.frame_snapshot()
.elements
.keys()
.find_map(|id| {
let rest = id.strip_prefix("desktop.sidebar.fdoc.")?;
let (folder, doc) = rest.split_once('.')?;
(!folder.is_empty()).then(|| (folder.to_owned(), doc.to_owned()))
})
.context("a mounted folder document row")
})
})??;
app.update(|cx| {
handle.update(cx, |view, _, cx| {
if !view
.state
.store
.get_doc(&folder_doc)
.expect("doc")
.meta
.is_favorite
{
view.state.store.toggle_favorite(&folder_doc);
cx.notify();
}
})
})?;
window.request_frame();
for (snap_id, expected_key) in [
(
format!("desktop.sidebar.fav.{folder_doc}"),
SidebarRowKey::Favorite(folder_doc.clone()),
),
(
format!("desktop.sidebar.fdoc.{doc_folder}.{folder_doc}"),
SidebarRowKey::FolderDoc {
folder_id: Some(doc_folder),
link_id: String::new(),
doc_id: folder_doc.clone(),
},
),
] {
let pos = app.update(|cx| {
handle.update(cx, |_, window, _| {
let b = window.frame_snapshot().elements[&snap_id].bounds;
point(px(b.x + b.width * 0.5), px(b.y + b.height * 0.5))
})
})?;
window.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
position: pos,
pressed_button: None,
modifiers: Modifiers::default(),
}));
window.request_frame();
app.update(|cx| {
handle.update(cx, |view, _, _| {
match (&view.state.sidebar.hovered_row, &expected_key) {
(Some(SidebarRowKey::Favorite(got)), SidebarRowKey::Favorite(exp)) => {
assert_eq!(got, exp)
}
(
Some(SidebarRowKey::FolderDoc {
folder_id,
link_id,
doc_id,
}),
SidebarRowKey::FolderDoc {
folder_id: exp_folder,
doc_id: exp_doc,
..
},
) => {
assert_eq!(folder_id, exp_folder);
assert_eq!(doc_id, exp_doc);
assert!(!link_id.is_empty());
}
other => panic!("unexpected hovered_row: {other:?}"),
}
})
})?;
}
let _ = tagged_doc;
Ok(())
}
#[test]
fn build_row_refs_handles_mixed_and_full_expanded_groups_without_quadratic_scan() {
use affine_store::{
directory::DocMode,
workspace_db::{NavigationEdit, WorkspaceCollection, WorkspaceTag},
};
let mut store = DesktopDocStore::seed_showcase("2026-12-03");
store.switch_workspace(1);
store.collections.clear();
let doc_id = store.create_doc("Grouped Doc", DocMode::Page, None, 10);
let group_count = 1024usize;
for i in 0..group_count {
let tag_id = format!("tag-{i:04}");
let col_id = format!("col-{i:04}");
assert!(
store
.directory
.db_mut()
.edit_navigation(
&NavigationEdit::CreateTag(WorkspaceTag {
id: tag_id.clone(),
name: format!("Tag {i}"),
color: "--affine-tag-blue".into(),
}),
(i as i64) + 1,
)
.unwrap()
.is_some()
);
assert!(
store
.directory
.db_mut()
.edit_navigation(
&NavigationEdit::CreateCollection(WorkspaceCollection {
id: col_id,
name: format!("Collection {i}"),
allow_list: if i == 0 {
vec![doc_id.clone()]
} else {
Vec::new()
},
filters: Vec::new(),
}),
(i as i64) + 1,
)
.unwrap()
.is_some()
);
if i == 0 {
store.docs.get_mut(&doc_id).unwrap().meta.tags = vec![tag_id];
}
}
store.load_navigation();
store.reindex_all();
let views = store.views();
assert_eq!(views.tags.len(), group_count);
assert_eq!(store.collections.len(), group_count);
let mut sidebar = SidebarState::default();
sidebar.expanded_sections =
BTreeSet::from([SidebarSection::Tags, SidebarSection::Collections]);
// 1. Empty expanded_groups skips building lookup sets cleanly.
assert!(ExpandedGroupsLookup::from_groups(&sidebar.expanded_groups).is_none());
let mut refs = Vec::new();
build_row_refs(&mut refs, &sidebar, &store, &views);
assert_eq!(refs.len(), 5 + group_count * 2);
// 2. Mixed expanded set: even tags + odd collections expanded.
for i in 0..group_count {
if i % 2 == 0 {
sidebar
.expanded_groups
.insert(TreeGroup::Tag(format!("tag-{i:04}")));
} else {
sidebar
.expanded_groups
.insert(TreeGroup::Collection(format!("col-{i:04}")));
}
}
let lookup =
ExpandedGroupsLookup::from_groups(&sidebar.expanded_groups).expect("mixed lookup");
assert_eq!(lookup.tags.len(), group_count / 2);
assert_eq!(lookup.collections.len(), group_count / 2);
let mut probed_refs = Vec::new();
build_row_refs_with_lookup(&mut probed_refs, &sidebar, &store, &views, Some(&lookup));
assert_eq!(lookup.probes.get(), group_count * 2);
refs.clear();
build_row_refs(&mut refs, &sidebar, &store, &views);
assert_eq!(refs, probed_refs);
assert_eq!(refs.len(), 5 + group_count * 2 + group_count);
let tag0_pos = refs
.iter()
.position(|row| matches!(row, RowRef::Tag(0)))
.unwrap();
assert!(matches!(
refs[tag0_pos + 1],
RowRef::TagDoc {
tag_idx: 0,
doc_idx: 0
}
));
assert!(matches!(refs[tag0_pos + 2], RowRef::Tag(1)));
assert!(matches!(refs[tag0_pos + 3], RowRef::Tag(2)));
assert!(matches!(refs[tag0_pos + 4], RowRef::Empty("Empty", 1)));
// 3. Full expansion (all 1024 tags + all 1024 collections = 2048 expanded groups).
for i in 0..group_count {
sidebar
.expanded_groups
.insert(TreeGroup::Tag(format!("tag-{i:04}")));
sidebar
.expanded_groups
.insert(TreeGroup::Collection(format!("col-{i:04}")));
}
let full_lookup =
ExpandedGroupsLookup::from_groups(&sidebar.expanded_groups).expect("full lookup");
assert_eq!(full_lookup.tags.len(), group_count);
assert_eq!(full_lookup.collections.len(), group_count);
probed_refs.clear();
build_row_refs_with_lookup(
&mut probed_refs,
&sidebar,
&store,
&views,
Some(&full_lookup),
);
assert_eq!(full_lookup.probes.get(), group_count * 2);
refs.clear();
build_row_refs(&mut refs, &sidebar, &store, &views);
assert_eq!(refs, probed_refs);
assert_eq!(refs.len(), 5 + group_count * 4);
let col0_pos = refs
.iter()
.position(|row| matches!(row, RowRef::Collection(0)))
.unwrap();
assert!(matches!(
refs[col0_pos + 1],
RowRef::CollectionDoc { col_idx: 0, .. }
));
}
}
@@ -6,7 +6,7 @@ use ui::{
StatefulInteractiveElement, Styled, div, prelude::FluentBuilder as _, px, svg,
};
use super::{SidebarRow, TreeGroup};
use super::{SidebarRow, SidebarRowKey, TreeGroup};
use crate::{
CHEVRON_DOWN_SVG, CHEVRON_RIGHT_SVG, COLLECTION_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt,
DesktopPalette, EDGELESS_ICON_SVG, FOLDER_ICON_SVG, JOURNAL_ICON_SVG, PLUS_ICON_SVG,
@@ -63,18 +63,24 @@ pub(super) fn render_row(
.child(*message)
.into_any_element(),
SidebarRow::Favorite(doc_id) => presentation.document(
format!("desktop.sidebar.fav.{doc_id}"),
SidebarRowKey::Favorite(doc_id.clone()),
ui::snap_id!("desktop.sidebar.fav.{doc_id}"),
store.get_doc(doc_id).map(|doc| &doc.meta),
None,
0,
),
SidebarRow::FolderDoc {
folder_id,
link_id,
doc_id,
depth,
..
} => presentation.document(
format!(
SidebarRowKey::FolderDoc {
folder_id: folder_id.clone(),
link_id: link_id.clone(),
doc_id: doc_id.clone(),
},
ui::snap_id!(
"desktop.sidebar.fdoc.{}.{doc_id}",
folder_id.as_deref().unwrap_or("")
),
@@ -82,24 +88,41 @@ pub(super) fn render_row(
folder_id.clone(),
*depth,
),
SidebarRow::GroupDoc { group, doc_id } => presentation.document(
match group {
TreeGroup::Collection(id) => format!("desktop.sidebar.col_doc.{id}.{doc_id}"),
TreeGroup::Tag(tag) => format!("desktop.sidebar.tag_doc.{tag}.{doc_id}"),
},
store.get_doc(doc_id).map(|doc| &doc.meta),
None,
1,
),
SidebarRow::GroupDoc { group, doc_id } => {
let (key, snap_id) = match group {
TreeGroup::Collection(id) => (
SidebarRowKey::CollectionDoc {
col_id: id.clone(),
doc_id: doc_id.clone(),
},
ui::snap_id!("desktop.sidebar.col_doc.{id}.{doc_id}"),
),
TreeGroup::Tag(tag) => (
SidebarRowKey::TagDoc {
tag_id: tag.clone(),
doc_id: doc_id.clone(),
},
ui::snap_id!("desktop.sidebar.tag_doc.{tag}.{doc_id}"),
),
};
presentation.document(
key,
snap_id,
store.get_doc(doc_id).map(|doc| &doc.meta),
None,
1,
)
}
SidebarRow::Folder { id, depth } => {
let row_id = format!("desktop.sidebar.folder.{id}");
let key = SidebarRowKey::Folder(id.clone());
let name = views.folders.name(id).unwrap_or_default().to_owned();
let expanded = sidebar.expanded_folders.contains(id);
let folder = id.clone();
let target = TreeTarget::Folder(id.clone());
let row = presentation
.node(
&row_id,
&key,
ui::snap_id!("desktop.sidebar.folder.{id}"),
NodeIcon::Svg(FOLDER_ICON_SVG),
name,
*depth,
@@ -112,7 +135,7 @@ pub(super) fn render_row(
cx.notify();
}));
presentation
.actions(row, &row_id, target, true)
.actions(row, &key, target, true)
.into_any_element()
}
SidebarRow::Collection(index) => {
@@ -121,7 +144,8 @@ pub(super) fn render_row(
};
let id = collection.id.clone();
presentation.group(
format!("desktop.sidebar.col.{id}"),
SidebarRowKey::Collection(id.clone()),
ui::snap_id!("desktop.sidebar.col.{id}"),
NodeIcon::Svg(COLLECTION_ICON_SVG),
collection.name.clone(),
TreeGroup::Collection(id.clone()),
@@ -139,7 +163,8 @@ pub(super) fn render_row(
};
let id = &tag.definition.id;
presentation.group(
format!("desktop.sidebar.tag.{id}"),
SidebarRowKey::Tag(id.clone()),
ui::snap_id!("desktop.sidebar.tag.{id}"),
NodeIcon::Dot(tag.color(theme)),
tag.definition.name.clone(),
TreeGroup::Tag(id.clone()),
@@ -165,18 +190,44 @@ struct RowPresentation<'a, 'b> {
impl RowPresentation<'_, '_> {
fn section(&self, section: SidebarSection) -> ui::Stateful<ui::Div> {
let (id, label) = match section {
SidebarSection::Favorites => ("desktop.sidebar.sec.favorites", "Favorites"),
SidebarSection::Folders => ("desktop.sidebar.sec.folders", "Organize"),
SidebarSection::Collections => ("desktop.sidebar.sec.collections", "Collections"),
SidebarSection::Tags => ("desktop.sidebar.sec.tags", "Tags"),
SidebarSection::Others => ("desktop.sidebar.sec.others", "Others"),
let (snap_id, parent_id, add_snap_id, label) = match section {
SidebarSection::Favorites => (
ui::snap_id!("desktop.sidebar.sec.favorites"),
"desktop.sidebar.sec.favorites",
ui::snap_id!("desktop.sidebar.sec.favorites.add"),
"Favorites",
),
SidebarSection::Folders => (
ui::snap_id!("desktop.sidebar.sec.folders"),
"desktop.sidebar.sec.folders",
ui::snap_id!("desktop.sidebar.sec.folders.add"),
"Organize",
),
SidebarSection::Collections => (
ui::snap_id!("desktop.sidebar.sec.collections"),
"desktop.sidebar.sec.collections",
ui::snap_id!("desktop.sidebar.sec.collections.add"),
"Collections",
),
SidebarSection::Tags => (
ui::snap_id!("desktop.sidebar.sec.tags"),
"desktop.sidebar.sec.tags",
ui::snap_id!("desktop.sidebar.sec.tags.add"),
"Tags",
),
SidebarSection::Others => (
ui::snap_id!("desktop.sidebar.sec.others"),
"desktop.sidebar.sec.others",
ui::snap_id!("desktop.sidebar.sec.others.add"),
"Others",
),
};
let key = SidebarRowKey::Section(section);
let palette = self.palette;
let arrow = disclosure(self.sidebar.expanded_sections.contains(&section));
let row = div()
.id(id)
.snapshot(id, Some("desktop.sidebar"))
.id(key.element_id())
.snapshot(snap_id, Some("desktop.sidebar"))
.w_full()
.h(px(20.0))
.mt(px(4.0))
@@ -203,10 +254,11 @@ impl RowPresentation<'_, '_> {
| SidebarSection::Folders
| SidebarSection::Tags
| SidebarSection::Collections => {
self.hover_row(row, id).when(self.show_actions(id), |el| {
let show = self.show_actions(&key);
self.hover_row(row, key).when(show, |el| {
el.child(div().flex_1()).child(
self.action_button("add", TreeTarget::Section(section), true)
.snapshot(format!("{id}.add"), Some(id)),
.snapshot(add_snap_id, Some(parent_id)),
)
})
}
@@ -216,7 +268,8 @@ impl RowPresentation<'_, '_> {
fn document(
&self,
row_id: String,
key: SidebarRowKey,
snap_id: ui::SnapshotId,
doc: Option<&DesktopDocMeta>,
folder_id: Option<String>,
depth: usize,
@@ -238,7 +291,8 @@ impl RowPresentation<'_, '_> {
};
let row = self
.node(
&row_id,
&key,
snap_id,
NodeIcon::Svg(icon),
doc.title.clone(),
depth,
@@ -250,12 +304,13 @@ impl RowPresentation<'_, '_> {
close_drawer(&mut this.state.sidebar, window);
cx.notify();
}));
self.actions(row, &row_id, target, false).into_any_element()
self.actions(row, &key, target, false).into_any_element()
}
fn group(
&self,
row_id: String,
key: SidebarRowKey,
snap_id: ui::SnapshotId,
icon: NodeIcon,
label: String,
group: TreeGroup,
@@ -267,7 +322,7 @@ impl RowPresentation<'_, '_> {
.id("disclosure")
.size(px(20.0))
.flex_shrink(0.0)
.child(self.node_icon(&row_id, icon, Some(expanded)))
.child(self.node_icon(&key, icon, Some(expanded)))
.on_click(self.cx.listener(move |this, _, _, cx| {
if !this.state.sidebar.expanded_groups.remove(&group) {
this.state.sidebar.expanded_groups.insert(group.clone());
@@ -278,11 +333,11 @@ impl RowPresentation<'_, '_> {
}));
let target = TreeTarget::Group(route.clone());
let row = row_shell(
row_id.clone().into(),
key.element_id(),
self.active_route == &route,
palette.hover_color,
)
.snapshot(row_id.clone(), Some("desktop.sidebar"))
.snapshot(snap_id, Some("desktop.sidebar"))
.child(disclosure)
.child(title_label(label, palette))
.on_click(self.cx.listener(move |this, _, window, cx| {
@@ -290,13 +345,14 @@ impl RowPresentation<'_, '_> {
close_drawer(&mut this.state.sidebar, window);
cx.notify();
}));
let row = self.hover_row(row, &row_id);
self.actions(row, &row_id, target, false).into_any_element()
let row = self.hover_row(row, key.clone());
self.actions(row, &key, target, false).into_any_element()
}
fn node(
&self,
id: &str,
key: &SidebarRowKey,
snap_id: ui::SnapshotId,
icon: NodeIcon,
label: String,
depth: usize,
@@ -304,19 +360,24 @@ impl RowPresentation<'_, '_> {
active: bool,
) -> ui::Stateful<ui::Div> {
let palette = self.palette;
let row = row_shell(id.to_owned().into(), active, palette.hover_color)
.snapshot(id, Some("desktop.sidebar"))
let row = row_shell(key.element_id(), active, palette.hover_color)
.snapshot(snap_id, Some("desktop.sidebar"))
.pl(px(indent(depth)))
.child(self.node_icon(id, icon, expanded))
.child(self.node_icon(key, icon, expanded))
.when(!label.is_empty(), |el| {
el.child(title_label(label, palette))
});
self.hover_row(row, id)
self.hover_row(row, key.clone())
}
fn node_icon(&self, id: &str, icon: NodeIcon, expanded: Option<bool>) -> ui::AnyElement {
fn node_icon(
&self,
key: &SidebarRowKey,
icon: NodeIcon,
expanded: Option<bool>,
) -> ui::AnyElement {
let palette = self.palette;
match (icon, expanded, self.show_actions(id)) {
match (icon, expanded, self.show_actions(key)) {
(_, Some(open), true) => icon_view(disclosure(open), palette).into_any_element(),
(NodeIcon::Svg(svg), _, _) => icon_view(svg, palette).into_any_element(),
(NodeIcon::Dot(color), _, _) => div()
@@ -330,19 +391,22 @@ impl RowPresentation<'_, '_> {
}
}
fn show_actions(&self, id: &str) -> bool {
self.sidebar.hovered_row.as_deref() == Some(id)
fn show_actions(&self, key: &SidebarRowKey) -> bool {
self.sidebar.hovered_row.as_ref() == Some(key)
}
fn hover_row(&self, mut row: ui::Stateful<ui::Div>, id: &str) -> ui::Stateful<ui::Div> {
let row_id = ui::SharedString::from(id.to_owned());
fn hover_row(
&self,
mut row: ui::Stateful<ui::Div>,
key: SidebarRowKey,
) -> ui::Stateful<ui::Div> {
row.interactivity()
.on_hover(self.cx.listener(move |this, hover, _, cx| {
let current = &mut this.state.sidebar.hovered_row;
if *hover && current.as_ref() != Some(&row_id) {
*current = Some(row_id.clone());
if *hover && current.as_ref() != Some(&key) {
*current = Some(key.clone());
cx.notify();
} else if !*hover && current.as_ref() == Some(&row_id) {
} else if !*hover && current.as_ref() == Some(&key) {
*current = None;
cx.notify();
}
@@ -353,7 +417,7 @@ impl RowPresentation<'_, '_> {
fn actions(
&self,
row: ui::Stateful<ui::Div>,
id: &str,
key: &SidebarRowKey,
target: TreeTarget,
add_child: bool,
) -> ui::Stateful<ui::Div> {
@@ -369,7 +433,7 @@ impl RowPresentation<'_, '_> {
cx.notify();
}),
)
.when(self.show_actions(id), |el| {
.when(self.show_actions(key), |el| {
el.when(add_child, |el| {
el.child(self.action_button("add", target.clone(), true))
})
@@ -402,7 +466,7 @@ impl RowPresentation<'_, '_> {
.when(disabled, |el| el.opacity(0.3))
.when(!disabled, |el| {
el.cursor_pointer()
.hover(move |s| s.bg(palette.bg_pill))
.hover(move |s| s.bg(palette.hover_overlay))
.on_click(
self.cx
.listener(move |this, event: &ui::ClickEvent, window, cx| {
@@ -459,7 +523,7 @@ fn title_label(label: String, palette: DesktopPalette) -> ui::Div {
/// Web paints hover and the active route with one color: `hoverOverlay` on navigation rows
/// and `--affine-hover-color` on tree nodes.
fn row_shell(id: ui::SharedString, active: bool, highlight: Hsla) -> ui::Stateful<ui::Div> {
fn row_shell(id: ui::ElementId, active: bool, highlight: Hsla) -> ui::Stateful<ui::Div> {
div()
.id(id)
.flex()
@@ -483,7 +547,7 @@ pub(crate) fn nav_row(
active: bool,
palette: DesktopPalette,
) -> ui::Stateful<ui::Div> {
row_shell(id.into(), active, palette.hover_overlay)
row_shell(id.into().into(), active, palette.hover_overlay)
.child(icon_view(icon, palette))
.child(title_label(label.into(), palette))
}
@@ -164,15 +164,15 @@ impl RenderOnce for OutlineRail {
let max_scroll = list.total_height() - list_height;
let scroll = window.use_keyed_state(
ElementId::NamedInteger(
SharedString::new_static("desktop.outline.rail.scroll"),
SharedString::new_static("outline-rail-scroll"),
ui::hash(&(&self.workspace, self.pane, &self.doc)),
),
app,
|_, _| 0.0_f32,
);
let key = format!(
"desktop.outline.rail.{}/{}/{}",
self.workspace, self.pane, self.doc
let key = ElementId::NamedInteger(
SharedString::new_static("outline-rail"),
ui::hash(&(&self.workspace, self.pane, &self.doc)),
);
let hovered = window.use_keyed_state(key.clone(), app, |_, _| false);
let expanded = *hovered.read(app);
@@ -180,7 +180,7 @@ impl RenderOnce for OutlineRail {
let mut rail = div()
.id(key)
.occlude()
.snapshot(format_args!("desktop.outline.rail.{}", self.pane), None)
.snapshot(ui::snap_id!("desktop.outline.rail.{}", self.pane), None)
.flex()
.items_start();
// Opening the panel centers the active entry in the list, as `scrollIntoView` does in
@@ -207,9 +207,12 @@ impl RenderOnce for OutlineRail {
let content = if expanded {
let panel = div()
.id("desktop.outline.rail.panel")
.id(ElementId::NamedInteger(
SharedString::new_static("outline-rail-panel"),
self.pane,
))
.snapshot(
format_args!("desktop.outline.rail.panel.{}", self.pane),
ui::snap_id!("desktop.outline.rail.panel.{}", self.pane),
None,
)
.w(px(PANEL_WIDTH))
@@ -307,7 +310,10 @@ impl RenderOnce for OutlineRail {
}
let panel = panel.child(self.header(collapse, colors)).child(
div()
.id("desktop.outline.rail.list")
.id(ElementId::NamedInteger(
SharedString::new_static("outline-rail-list"),
self.pane,
))
.h(px(list_height))
.w_full()
.overflow_hidden()