feat(desktop): add sidebar section menus, empty states, and new-tab routing

Align AppSidebar section headers, row menus, and Web new-tab navigation
with AFFiNE 0.27.5:

- Add Favorites, Organize, Tags, Collections, and Others empty-state
  prompts and inline creation actions, plus right-click and three-dot
  menus across non-active document, tag, collection, and folder rows.
- Open document, tag, and collection "Open in new tab" actions as real
  browser tabs on Web Desktop (/desktop/?workspace=...&doc|tag|collection=...)
  and persist tag/collection view routes across reloads via SavedView
  and start.js URL sync.
This commit is contained in:
DarkSky committed 2026-12-04 10:26:10 +09:00
1 parent 9b75a4adc8
commit 49f4e53cac
10 files changed
+1304 -125

No files matched your search

+423 -2
View File
@@ -24,12 +24,16 @@ impl TestShell {
}
fn at_width(width: u32, web_chrome: bool) -> Self {
Self::at_size(width, 800, web_chrome)
}
fn at_size(width: u32, height: u32, web_chrome: bool) -> Self {
let storage = Rc::new(LocalUpdates::default());
let (mut state, sessions) =
DesktopAppState::open_local(&storage.0.borrow(), ThemeMode::Light, "2026-12-02", 123)
.expect("local workspace");
state.web_chrome = web_chrome;
let platform = HeadlessPlatform::new(width, 800, 1.0);
let platform = HeadlessPlatform::new(width, height, 1.0);
let app = Application::with_platform(platform.clone()).run_embedded(|_| {});
let handle = app.update(|cx| {
register_desktop_fonts(cx).expect("desktop fonts");
@@ -37,7 +41,7 @@ impl TestShell {
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(width as f32), px(800.0)),
size(px(width as f32), px(height as f32)),
))),
..WindowOptions::default()
},
@@ -411,3 +415,420 @@ fn floating_sidebar_keeps_popups_open_and_yields_to_modals_and_narrow_windows()
app.move_pointer(point(px(6.0), px(140.0)));
assert!(!has(floating));
}
#[cfg(test)]
mod document_menu {
use super::*;
#[test]
fn sidebar_doc_menu_runs_document_commands() {
use crate::DesktopRoute;
for command in [
"Remove from favourites",
"Open in new tab",
"Open in split view",
"Duplicate",
"Add linked doc",
] {
let app = TestShell::new();
let (id, tabs, count, refs) = app.shell(|view, _, _| {
let state = view.state();
let doc = state.store.favorite_docs()[0];
(
doc.id.clone(),
state.split.panes[0].tabs.len(),
state.store.docs.len(),
doc.outgoing_refs.clone(),
)
});
let sibling = if command == "Add linked doc" {
let sibling = app.shell(|view, _, cx| {
let pane = view.state.split.active().id;
view.state.open_doc_in_split_with_mode(
id.clone(),
crate::split_view::DocViewMode::Page,
);
cx.notify();
pane
});
app.frame();
Some(sibling)
} else {
None
};
app.hover(&format!("desktop.sidebar.fav.{id}"));
app.click("desktop.sidebar.node.more");
app.click(command);
let state = app.reopen();
let doc = state.store.get_doc(&id).expect("source document");
match command {
"Remove from favourites" => assert!(!doc.meta.is_favorite),
"Duplicate" => {
assert_eq!(state.store.docs.len(), count + 1);
assert!(state.store.docs.values().any(|copy| {
copy.meta.id != id
&& copy.meta.title == format!("Copy of {}", doc.meta.title)
}));
}
"Add linked doc" => {
use blocksuite_playground_doc::read::BlockContent;
assert_eq!(state.store.docs.len(), count + 1);
let child = app.shell(|view, _, _| {
view.state
.split
.active()
.active_route()
.doc_id()
.expect("new page is open")
.to_owned()
});
assert_ne!(id, child);
assert!(!refs.contains(&child));
app.shell(|view, _, cx| {
let editor = view
.editor_host()
.pane_entity(sibling.expect("sibling pane"))
.expect("mounted parent editor");
let snapshot = editor.read(cx).page_snapshot().expect("parent snapshot");
assert!(
blocksuite_playground_doc::refs::extract_outbound_doc_refs(snapshot)
.iter()
.any(|edge| edge.target_doc_id == child)
);
});
assert!(
doc.meta.outgoing_refs.contains(&child),
"persisted links: {:?}",
doc.meta.outgoing_refs
);
let page = state.store.get_doc(&child).expect("saved page");
assert!(!page.meta.trashed);
let root = page.snapshot.root.as_ref().expect("page root");
assert!(
matches!(&root.content, BlockContent::Page { title } if title.plain.is_empty())
);
}
"Open in new tab" => app.shell(|view, _, _| {
let pane = &view.state().split.panes[0];
assert_eq!(pane.tabs.len(), tabs + 1);
assert_eq!(pane.active_route(), &DesktopRoute::Doc(id.clone()));
}),
"Open in split view" => app.shell(|view, _, _| {
let split = &view.state().split;
assert!(split.is_split());
assert_eq!(
split.active().active_route(),
&DesktopRoute::Doc(id.clone())
);
}),
_ => unreachable!(),
}
}
}
#[test]
fn sidebar_doc_dialogs_target_a_document_outside_the_active_pane() {
let app = TestShell::new();
let (id, route) = app.shell(|view, _, _| {
let route = view.state.split.active().active_route();
let doc = view
.state
.store
.favorite_docs()
.into_iter()
.find(|doc| route.doc_id() != Some(doc.id.as_str()))
.expect("favorite outside the active pane");
(doc.id.clone(), route.clone())
});
let row = format!("desktop.sidebar.fav.{id}");
let has =
|id: &str| app.shell(|_, window, _| window.frame_snapshot().elements.contains_key(id));
app.right_click(&row);
app.click("View Info");
assert!(has("desktop.header.dialog"));
assert!(has("desktop.header.info.tag.add"));
app.key("escape");
assert!(!has("desktop.header.dialog"));
for action in ["Cancel", "Escape", "Backdrop", "Confirm"] {
app.right_click(&row);
app.click("Move to trash");
assert!(has("desktop.header.dialog"));
let trashed = || {
app.shell(|view, _, _| {
view.state
.store
.get_doc(&id)
.expect("document")
.meta
.trashed
})
};
assert!(!trashed());
match action {
"Cancel" => app.click("desktop.header.trash.cancel"),
"Escape" => app.key("escape"),
"Backdrop" => {
app.window.simulate_click(point(px(40.0), px(96.0)));
app.frame();
}
"Confirm" => app.click("desktop.header.trash.confirm"),
_ => unreachable!(),
}
assert!(!has("desktop.header.dialog"));
assert_eq!(trashed(), action == "Confirm");
app.shell(|view, _, _| assert_eq!(view.state.split.active().active_route(), &route));
}
assert!(
app.reopen()
.store
.get_doc(&id)
.expect("saved document")
.meta
.trashed
);
}
#[test]
fn sidebar_doc_menu_split_follows_viewport_width() {
for (width, split) in [(320, false), (390, false), (639, false), (640, true)] {
let app = TestShell::at_width(width, false);
if !app.shell(|view, _, _| view.state.sidebar.open) {
app.click("desktop.topbar.sidebar_toggle");
}
let id = app.shell(|view, _, _| view.state().store.favorite_docs()[0].id.clone());
app.right_click(&format!("desktop.sidebar.fav.{id}"));
app.shell(|_, window, _| {
let frame = window.frame_snapshot();
assert!(frame.elements.contains_key("Open in new tab"));
assert_eq!(frame.elements.contains_key("Open in split view"), split);
let menu = frame.elements["desktop.sidebar.tree_menu"].bounds;
assert!(menu.x >= 0.0 && menu.x + menu.width <= width as f32);
});
}
}
}
#[test]
fn sidebar_tree_menu_flips_up_and_scrolls_in_a_short_viewport() {
use super::{Popup, TreeMenu, TreeTarget};
for height in [220, 340] {
let app = TestShell::at_size(1280, height, false);
let origin = height as f32 - 8.0;
app.shell(|view, _, cx| {
let id = view.state.store.favorite_docs()[0].id.clone();
let target = TreeTarget::Doc {
id,
folder_id: Some("folder".into()),
};
view.state.sidebar.popup = Some(Popup::Tree(TreeMenu::new(
target,
point(px(180.0), px(origin)),
&view.state,
)));
cx.notify();
});
app.frame();
let menu = app.shell(|_, window, _| {
let frame = window.frame_snapshot();
let menu = frame.elements["desktop.sidebar.tree_menu"].bounds;
assert!(menu.y >= 0.0 && menu.y < origin);
assert!(menu.y + menu.height <= height as f32);
if height == 340 {
assert_eq!(menu.y + menu.height, origin);
}
menu
});
if height == 220 {
let position = point(px(menu.x + 20.0), px(menu.y + 40.0));
app.move_pointer(position);
app.window
.dispatch_input(PlatformInput::Scroll(ui::ScrollEvent {
position,
delta: ui::ScrollDelta::Pixels(point(px(0.0), px(-500.0))),
..Default::default()
}));
app.frame();
app.shell(|_, window, _| {
let trash = window.frame_snapshot().elements["Move to trash"].bounds;
assert!(
trash.y >= menu.y && trash.y + trash.height <= menu.y + menu.height,
"trash {trash:?} must scroll into the menu {menu:?}",
);
});
}
}
}
#[test]
fn sidebar_tag_actions_create_open_and_persist_tagged_pages() {
use super::SidebarSection;
use crate::sidebar_tree::TreeGroup;
for action in ["desktop.sidebar.node.add", "New doc"] {
let app = TestShell::new();
let tag = app.shell(|view, _, cx| {
view.state.sidebar.expanded_sections = [SidebarSection::Tags].into();
assert!(view.state.store.create_tag("Sidebar test"));
cx.notify();
view.state
.store
.views()
.tags
.iter()
.find(|tag| tag.definition.name == "Sidebar test")
.expect("new tag")
.definition
.id
.clone()
});
app.frame();
let row = format!("desktop.sidebar.tag.{tag}");
app.hover(&row);
if action == "New doc" {
app.click("desktop.sidebar.node.more");
}
app.click(action);
let id = app.shell(|view, _, _| {
assert!(
view.state
.sidebar
.expanded_groups
.contains(&TreeGroup::Tag(tag.clone()))
);
view.state
.split
.active()
.active_route()
.doc_id()
.expect("open page")
.to_owned()
});
assert_eq!(
app.reopen()
.store
.get_doc(&id)
.expect("saved page")
.meta
.tags,
[tag]
);
}
}
#[test]
fn sidebar_empty_section_actions_create_folders_and_collections() {
use super::SidebarSection;
for (section, button) in [
(SidebarSection::Folders, "desktop.sidebar.empty.new_folder"),
(
SidebarSection::Collections,
"desktop.sidebar.empty.new_collection",
),
] {
let app = TestShell::new();
app.shell(|view, _, cx| {
view.state.switch_workspace(1);
if section == SidebarSection::Collections {
let ids: Vec<_> = view
.state
.store
.collections
.iter()
.map(|col| col.id.clone())
.collect();
for id in ids {
assert!(view.state.store.delete_collection(&id));
}
}
view.state.sidebar.expanded_sections = [section].into();
cx.notify();
});
app.frame();
app.click(button);
assert!(app.name_is_open());
if section == SidebarSection::Folders {
app.shell(|view, _, _| {
let folder = view
.state
.store
.folder_rows
.iter()
.find(|row| row.data == "New Folder")
.expect("new folder");
assert!(view.state.sidebar.expanded_folders.contains(&folder.id));
});
}
app.input(|handler| handler.replace_text_in_range(None, "Sidebar test"));
app.key("enter");
app.shell(|view, _, _| {
assert!(view.state.sidebar.expanded_sections.contains(&section));
match section {
SidebarSection::Folders => assert!(
view.state
.store
.folder_rows
.iter()
.any(|row| row.data == "Sidebar test")
),
SidebarSection::Collections => assert!(
view.state
.store
.collections
.iter()
.any(|row| row.name == "Sidebar test")
),
_ => unreachable!(),
}
});
}
}
#[test]
fn sidebar_group_context_menus_open_their_routes() {
use super::SidebarSection;
use crate::DesktopRoute;
for (section, command) in [
(SidebarSection::Collections, "Open"),
(SidebarSection::Collections, "Open in new tab"),
(SidebarSection::Collections, "Open in split view"),
(SidebarSection::Tags, "Open in new tab"),
(SidebarSection::Tags, "Open in split view"),
] {
let app = TestShell::new();
let (node, route, tabs) = app.shell(|view, _, cx| {
view.state.sidebar.expanded_sections = [section].into();
cx.notify();
let store = &view.state.store;
let (node, route) = if section == SidebarSection::Collections {
let id = store.collections[0].id.clone();
(
format!("desktop.sidebar.col.{id}"),
DesktopRoute::Collection(id),
)
} else {
let id = store.views().tags[0].definition.id.clone();
(format!("desktop.sidebar.tag.{id}"), DesktopRoute::Tag(id))
};
(node, route, view.state.split.panes[0].tabs.len())
});
app.frame();
app.right_click(&node);
app.click(command);
app.shell(|view, _, _| {
let split = &view.state.split;
assert_eq!(split.active().active_route(), &route);
assert_eq!(split.is_split(), command == "Open in split view");
assert_eq!(
split.panes[0].tabs.len(),
tabs + usize::from(command == "Open in new tab")
);
});
}
}
@@ -1,20 +1,36 @@
//! Sidebar tree commands and rename menu.
use affine_store::directory::DocMode;
use ui::{
AppContext, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, Pixels,
Point, Stateful, StatefulInteractiveElement, Styled, Window, anchored, deferred, div,
prelude::FluentBuilder as _, px, svg,
use affine_store::{directory::DocMode, workspace_db::derive_page_id_for_op};
use blocksuite_playground_doc::{
schema::{BlockSpec, ParagraphType},
session::PageDocSession,
try_random_client_id,
};
use ui::{
App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, Pixels,
Point, RenderOnce, Stateful, StatefulInteractiveElement, Styled, Window, anchored, deferred,
div, prelude::FluentBuilder as _, px, svg,
};
use ui_tokens::icons;
use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use super::{
Popup, SidebarSection, SidebarState, close_drawer, controls::popup_panel, name_input::NameInput,
};
use crate::{
DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, FOLDER_ICON_SVG, PLUS_ICON_SVG, TRASH_ICON_SVG,
split_view::DesktopRoute, workbench::DesktopShellView,
DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, FOLDER_ICON_SVG, INFO_ICON_SVG, PLUS_ICON_SVG,
TRASH_ICON_SVG,
sidebar_tree::TreeGroup,
split_view::{DesktopRoute, DocViewMode},
workbench::DesktopShellView,
};
const SPLIT_BREAKPOINT: Pixels = px(640.0);
const MENU_ROW_HEIGHT: Pixels = px(30.0);
const MENU_SEPARATOR_MARGIN: Pixels = px(4.0);
const MENU_PADDING_AND_BORDER: Pixels = px(10.0);
#[derive(Clone, Debug)]
pub(crate) enum TreeTarget {
Section(SidebarSection),
@@ -49,11 +65,19 @@ pub(crate) fn add_doc_or_folder(
return;
}
match target {
TreeTarget::Section(
SidebarSection::Folders | SidebarSection::Tags | SidebarSection::Collections,
) => {
shell.state.sidebar.popup = Some(Popup::Tree(TreeMenu::new(target.clone(), position)));
begin_rename(shell, target, window, cx);
TreeTarget::Section(SidebarSection::Folders) => {
let id = shell.state.create_folder("New Folder", None);
if !id.is_empty() {
shell
.state
.sidebar
.expanded_sections
.insert(SidebarSection::Folders);
open_name_input(shell, TreeTarget::Folder(id), position, window, cx);
}
}
TreeTarget::Section(SidebarSection::Tags | SidebarSection::Collections) => {
open_name_input(shell, target.clone(), position, window, cx);
}
TreeTarget::Section(SidebarSection::Favorites) => {
let id = shell.state.create_new_doc(DocMode::Page);
@@ -75,22 +99,193 @@ pub(crate) fn add_doc_or_folder(
close_drawer(&mut shell.state.sidebar, window);
}
}
TreeTarget::Doc { id, .. } => {
shell.sync_editors(cx);
if let Some(child) = create_linked_page(&mut shell.state, id) {
shell.state.open_doc_in_active_pane(&child);
shell.sync_editors(cx);
close_drawer(&mut shell.state.sidebar, window);
}
}
TreeTarget::Group(DesktopRoute::Tag(tag)) => {
if create_tagged_page(&mut shell.state, tag) {
shell
.state
.sidebar
.expanded_groups
.insert(TreeGroup::Tag(tag.clone()));
close_drawer(&mut shell.state.sidebar, window);
}
}
_ => {}
}
}
fn open_name_input(
shell: &mut DesktopShellView,
target: TreeTarget,
position: Point<Pixels>,
window: &mut Window,
cx: &mut Context<DesktopShellView>,
) {
shell.state.sidebar.popup = Some(Popup::Tree(TreeMenu::new(
target.clone(),
position,
&shell.state,
)));
begin_rename(shell, &target, window, cx);
}
fn create_tagged_page(state: &mut crate::DesktopAppState, tag: &str) -> bool {
if state.store.views().tag(tag).is_none() {
return false;
}
let id = state.create_new_doc(DocMode::Page);
if id.is_empty() {
return false;
}
let store = &mut state.store;
let tags = vec![tag.to_owned()];
let now = state.logical_clock_ms;
let saved = match store.with_session(now, |session| session.set_document_tags(&id, &tags, now))
{
Some(result) => result.is_ok(),
None if store.directory.db().root().is_meta_initialized() => {
store.directory.db_mut().set_page_tags(&id, &tags).is_ok()
}
None => true,
};
if !saved {
state.trash_doc(&id);
return false;
}
if let Some(doc) = store.docs.get_mut(&id) {
doc.meta.tags = tags;
store.touch_meta();
}
true
}
fn create_linked_page(state: &mut crate::DesktopAppState, parent: &str) -> Option<String> {
if !state.is_openable_doc(parent) || !state.store.ensure_doc_hydrated(parent).ok()? {
return None;
}
let entry = state.store.get_doc(parent)?;
let note = entry.note_id.clone();
if note.is_empty() {
return None;
}
let client_id = try_random_client_id().ok()?;
let mut page = PageDocSession::new(parent, client_id).ok()?;
page.apply_remote_update_v1(&entry.session.encode_update_v1().ok()?)
.ok()?;
let intent = format!("sidebar-link-{client_id:x}");
let child = derive_page_id_for_op(&state.store.active_workspace().id, &intent);
state.logical_clock_ms += 10;
let now_ms = state.logical_clock_ms;
let now = now_ms.max(0) as u64;
let block = format!("p-{client_id:x}");
let commit = page
.structural_edit(now, |page| {
page.add_block(
&block,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: String::new(),
},
Some(&note),
None,
now,
)?;
page.apply_text_delta(
&block,
"prop:text",
&[TextDeltaOp::Insert {
insert: TextInsert::Text(" ".into()),
format: Some(TextAttributes::from([(
"reference".into(),
Any::Object(Box::new(
[
("type".into(), Any::String("LinkedPage".into())),
("pageId".into(), Any::String(child.clone())),
]
.into_iter()
.collect(),
)),
)])),
}],
now,
)?;
Ok(())
})
.ok()??;
let id = state
.store
.create_linked_doc(String::new(), DocMode::Page, now_ms, &intent);
if id.is_empty() {
return None;
}
if state.store.apply_remote_doc_update(parent, &commit.update) {
return Some(id);
}
state.trash_doc(&id);
None
}
#[derive(Clone, Debug)]
pub(crate) struct TreeMenu {
target: TreeTarget,
position: Point<Pixels>,
rename: Option<Entity<NameInput>>,
favorite: bool,
scroll_y: Pixels,
}
impl TreeMenu {
pub(crate) fn new(target: TreeTarget, position: Point<Pixels>) -> Self {
pub(crate) fn new(
target: TreeTarget,
position: Point<Pixels>,
state: &crate::DesktopAppState,
) -> Self {
let favorite = match &target {
TreeTarget::Doc { id, .. } => state
.store
.get_doc(id)
.is_some_and(|doc| doc.meta.is_favorite),
_ => false,
};
Self {
target,
position,
rename: None,
favorite,
scroll_y: px(0.0),
}
}
fn commands(&self) -> &'static [Command] {
use Command::*;
match &self.target {
TreeTarget::Doc { .. } => &[
ViewInfo,
OpenTab,
OpenSplit,
ToggleFavorite,
AddLinkedPage,
Duplicate,
Rename,
RemovePlacement,
Trash,
],
TreeTarget::Folder(_) => &[ChildDoc, ChildFolder, Rename, DeleteFolder],
TreeTarget::Group(DesktopRoute::Tag(_)) => {
&[ChildDoc, OpenTab, OpenSplit, Rename, DeleteGroup]
}
TreeTarget::Group(DesktopRoute::Collection(_)) => {
&[OpenGroup, OpenTab, OpenSplit, Rename, DeleteGroup]
}
_ => &[],
}
}
}
@@ -104,57 +299,99 @@ pub(super) fn tree_popup(
let Some(Popup::Tree(tree)) = &sidebar.popup else {
return None;
};
let mut menu = popup_panel("desktop.sidebar.tree_menu", 214.0, palette, None, cx);
let mut panel = popup_panel("desktop.sidebar.tree_menu", 214.0, palette, None, cx);
let mut rows = Vec::new();
if let Some(rename) = &tree.rename {
menu = menu.child(
panel = panel.child(
div()
.id("desktop.sidebar.rename_menu")
.child(rename.clone())
.on_key_down(cx.listener(edit_name)),
);
} else {
let items: &[(Command, &str, &[u8])] = match &tree.target {
TreeTarget::Doc { .. } => &[
(Command::Rename, "Rename", DOC_ICON_SVG),
(
Command::RemovePlacement,
"Remove from folder",
FOLDER_ICON_SVG,
),
(Command::Trash, "Move to trash", TRASH_ICON_SVG),
],
TreeTarget::Folder(_) => &[
(Command::ChildDoc, "New Page", PLUS_ICON_SVG),
(Command::ChildFolder, "New folder", FOLDER_ICON_SVG),
(Command::Rename, "Rename", DOC_ICON_SVG),
(Command::DeleteFolder, "Delete folder", TRASH_ICON_SVG),
],
TreeTarget::Group(_) => &[
(Command::OpenGroup, "Open", DOC_ICON_SVG),
(Command::Rename, "Rename", DOC_ICON_SVG),
(Command::DeleteGroup, "Delete", TRASH_ICON_SVG),
],
TreeTarget::Section(_) => &[],
};
for &(command, label, icon) in items {
for &command in tree.commands() {
if matches!(command, Command::RemovePlacement) && !tree.target.has_placement() {
continue;
}
let (label, icon) = command.presentation(tree.favorite);
let target = tree.target.clone();
let enabled = !readonly || matches!(command, Command::OpenGroup);
menu = menu.child(
tree_menu_row(label, icon, palette, enabled)
.snapshot(label, Some("desktop.sidebar.tree_menu"))
.when(enabled, |el| {
el.on_click(cx.listener(move |this, _, window, cx| {
command.run(this, &target, window, cx);
cx.notify();
}))
}),
);
let enabled = !readonly || !command.writes();
let row = tree_menu_row(label, icon, palette, enabled, command.dangerous())
.snapshot(label, Some("desktop.sidebar.tree_menu"))
.when(enabled, |el| {
el.on_click(cx.listener(move |this, _, window, cx| {
command.run(this, &target, window, cx);
cx.notify();
}))
});
rows.push((command, row));
}
}
Some(deferred(anchored().position(tree.position).child(menu)))
Some(ui::ViewElement::new(TreePopup {
panel,
rows,
position: tree.position,
palette,
scroll_y: tree.scroll_y,
shell: cx.entity(),
}))
}
struct TreePopup {
panel: Stateful<Div>,
rows: Vec<(Command, Stateful<Div>)>,
position: Point<Pixels>,
palette: DesktopPalette,
scroll_y: Pixels,
shell: Entity<DesktopShellView>,
}
impl RenderOnce for TreePopup {
fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
let viewport = window.viewport_size();
let mut panel = self.panel;
panel.style().max_size.width = Some(viewport.width.into());
panel.style().max_size.height = Some(viewport.height.into());
let mut content = div().w_full().flex().flex_col().flex_shrink(0.0);
let mut height = px(0.0);
for (command, row) in self.rows {
if matches!(command, Command::OpenSplit) && viewport.width < SPLIT_BREAKPOINT {
continue;
}
if command.dangerous() {
height += MENU_SEPARATOR_MARGIN * 2.0 + px(1.0);
content = content.child(
div()
.h(px(1.0))
.my(MENU_SEPARATOR_MARGIN)
.flex_shrink(0.0)
.bg(self.palette.border),
);
}
height += MENU_ROW_HEIGHT;
content = content.child(row);
}
if height > px(0.0) {
let max_scroll = (height + MENU_PADDING_AND_BORDER - viewport.height).max(px(0.0));
panel = panel.child(content.relative().top(-self.scroll_y.min(max_scroll)));
if max_scroll > px(0.0) {
let shell = self.shell;
panel = panel.overflow_hidden().on_scroll(move |event, _, app| {
let dy = event.delta.pixel_delta(MENU_ROW_HEIGHT).y;
shell.update(app, |shell, cx| {
if let Some(Popup::Tree(tree)) = &mut shell.state.sidebar.popup {
tree.scroll_y = (tree.scroll_y - dy).clamp(px(0.0), max_scroll);
cx.stop_propagation();
cx.notify();
}
});
});
}
}
deferred(anchored().position(self.position).child(panel))
}
}
fn tree_menu_row(
@@ -162,6 +399,7 @@ fn tree_menu_row(
icon: &'static [u8],
palette: DesktopPalette,
enabled: bool,
danger: bool,
) -> Stateful<Div> {
div()
.id(label)
@@ -169,7 +407,7 @@ fn tree_menu_row(
.items_center()
.gap(px(8.0))
.w_full()
.h(px(30.0))
.h(MENU_ROW_HEIGHT)
.flex_shrink(0.0)
.px(px(6.0))
.rounded(px(4.0))
@@ -179,7 +417,11 @@ fn tree_menu_row(
.data(icon)
.size(px(20.0))
.flex_shrink(0.0)
.text_color(palette.text_secondary),
.text_color(if danger {
palette.danger
} else {
palette.text_secondary
}),
)
.child(
div()
@@ -187,7 +429,11 @@ fn tree_menu_row(
.min_w_0()
.truncate()
.text_size(px(14.0))
.text_color(palette.text_primary)
.text_color(if danger {
palette.danger
} else {
palette.text_primary
})
.child(label),
)
.when(enabled, |row| {
@@ -200,6 +446,12 @@ fn tree_menu_row(
#[derive(Clone, Copy)]
enum Command {
OpenGroup,
ViewInfo,
OpenTab,
OpenSplit,
ToggleFavorite,
AddLinkedPage,
Duplicate,
Rename,
RemovePlacement,
Trash,
@@ -210,6 +462,39 @@ enum Command {
}
impl Command {
fn presentation(self, favorite: bool) -> (&'static str, &'static [u8]) {
match self {
Self::OpenGroup => ("Open", DOC_ICON_SVG),
Self::ViewInfo => ("View Info", INFO_ICON_SVG),
Self::OpenTab => ("Open in new tab", icons::OPEN_IN_NEW.svg.as_bytes()),
Self::OpenSplit => ("Open in split view", icons::SPLIT_VIEW.svg.as_bytes()),
Self::ToggleFavorite if favorite => {
("Remove from favourites", icons::FAVORITED.svg.as_bytes())
}
Self::ToggleFavorite => ("Add to favourites", icons::FAVORITE.svg.as_bytes()),
Self::AddLinkedPage => ("Add linked doc", icons::LINKED_PAGE.svg.as_bytes()),
Self::Duplicate => ("Duplicate", icons::DUPLICATE.svg.as_bytes()),
Self::Rename => ("Rename", icons::EDIT.svg.as_bytes()),
Self::RemovePlacement => ("Remove from folder", FOLDER_ICON_SVG),
Self::Trash => ("Move to trash", TRASH_ICON_SVG),
Self::ChildDoc => ("New doc", PLUS_ICON_SVG),
Self::ChildFolder => ("New folder", FOLDER_ICON_SVG),
Self::DeleteFolder => ("Delete folder", TRASH_ICON_SVG),
Self::DeleteGroup => ("Delete", TRASH_ICON_SVG),
}
}
fn writes(self) -> bool {
!matches!(
self,
Self::OpenGroup | Self::ViewInfo | Self::OpenTab | Self::OpenSplit
)
}
fn dangerous(self) -> bool {
matches!(self, Self::Trash | Self::DeleteFolder | Self::DeleteGroup)
}
fn run(
self,
shell: &mut DesktopShellView,
@@ -217,7 +502,9 @@ impl Command {
window: &mut Window,
cx: &mut Context<DesktopShellView>,
) {
if shell.state.store.is_readonly_sqlite() && !matches!(self, Self::OpenGroup) {
if (self.writes() && shell.state.store.is_readonly_sqlite())
|| (matches!(self, Self::OpenSplit) && window.viewport_size().width < SPLIT_BREAKPOINT)
{
return;
}
if matches!(self, Self::Rename) {
@@ -229,20 +516,87 @@ impl Command {
_ => window.mouse_position(),
};
shell.state.sidebar.dismiss_popups();
#[cfg(target_arch = "wasm32")]
if matches!(self, Self::OpenTab)
&& shell.state.web_chrome
&& let Some((key, id)) = match target {
TreeTarget::Doc { id, .. } => Some(("doc", id)),
TreeTarget::Group(DesktopRoute::Tag(id)) => Some(("tag", id)),
TreeTarget::Group(DesktopRoute::Collection(id)) => Some(("collection", id)),
_ => None,
}
{
shell.sync_editors(cx);
let workspace = String::from(js_sys::encode_uri_component(
&shell.state.store.active_workspace().id,
));
let id = String::from(js_sys::encode_uri_component(id));
shell.save_local_workspaces();
crate::wasm_entry::open_document_tab(
&format!("/desktop/?workspace={workspace}&{key}={id}"),
"_blank",
"noopener",
);
close_drawer(&mut shell.state.sidebar, window);
return;
}
match (self, target) {
(Self::OpenGroup, TreeTarget::Group(route)) => {
shell.state.navigate_active_pane(route.clone());
close_drawer(&mut shell.state.sidebar, window);
}
(Self::OpenTab, TreeTarget::Doc { id, .. }) => {
shell.sync_editors(cx);
shell.state.open_header_doc_in_new_tab(id);
close_drawer(&mut shell.state.sidebar, window);
}
(Self::OpenSplit, TreeTarget::Doc { id, .. }) => {
shell.sync_editors(cx);
if let Some(mode) = shell.state.openable_doc_mode(id) {
shell.state.open_doc_in_split_with_mode(id.clone(), mode);
close_drawer(&mut shell.state.sidebar, window);
}
}
(Self::OpenTab | Self::OpenSplit, TreeTarget::Group(route)) => {
shell.sync_editors(cx);
let split = &mut shell.state.split;
let Some(scope) = split
.active()
.history
.current()
.map(|entry| entry.scope.clone())
else {
return;
};
if matches!(self, Self::OpenSplit) {
split.open_in_split(scope, route.clone(), DocViewMode::Page);
} else {
split.panes[0].push_tab(scope, route.clone(), DocViewMode::Page);
split.sync_app_tab();
split.focus_pane(0);
}
close_drawer(&mut shell.state.sidebar, window);
}
(Self::ToggleFavorite, TreeTarget::Doc { id, .. }) => {
shell.state.store.toggle_favorite(id);
}
(Self::Duplicate, TreeTarget::Doc { id, .. }) => {
shell.sync_editors(cx);
if let Some(copy) = shell.state.duplicate_header_doc(id) {
shell.state.open_doc_in_active_pane(&copy);
close_drawer(&mut shell.state.sidebar, window);
}
}
(Self::RemovePlacement, TreeTarget::Doc { id, folder_id }) => {
if let Some(folder) = folder_id {
shell.state.store.remove_doc_from_folder(id, folder);
}
}
(Self::Trash, TreeTarget::Doc { id, .. }) => {
shell.state.trash_doc(id);
(Self::ViewInfo | Self::Trash, TreeTarget::Doc { id, .. }) => {
close_drawer(&mut shell.state.sidebar, window);
shell.show_sidebar_doc_dialog(id, matches!(self, Self::Trash), window, cx);
}
(Self::ChildDoc, TreeTarget::Folder(_)) => {
(Self::ChildDoc | Self::AddLinkedPage, _) => {
add_doc_or_folder(shell, target, position, window, cx);
}
(Self::DeleteGroup, TreeTarget::Group(route)) => {
@@ -260,8 +614,11 @@ impl Command {
}
}
(Self::ChildFolder, TreeTarget::Folder(id)) => {
shell.state.create_folder("New Folder", Some(id.clone()));
shell.state.sidebar.expanded_folders.insert(id.clone());
let child = shell.state.create_folder("New Folder", Some(id.clone()));
if !child.is_empty() {
shell.state.sidebar.expanded_folders.insert(id.clone());
open_name_input(shell, TreeTarget::Folder(child), position, window, cx);
}
}
(Self::DeleteFolder, TreeTarget::Folder(id)) => {
for removed in shell.state.store.delete_folder_subtree(id) {
@@ -300,6 +657,7 @@ fn begin_rename(
let focus = cx.focus_handle();
focus.focus(window, cx);
window.request_virtual_keyboard();
tree.scroll_y = px(0.0);
tree.rename =
Some(cx.new(|_| NameInput::new(value, focus, crate::palette_for(shell.state.theme))));
}
@@ -345,9 +703,6 @@ fn edit_name(
}
TreeTarget::Section(section) => {
match section {
SidebarSection::Folders => {
shell.state.create_folder(&name, None);
}
SidebarSection::Tags => {
shell.state.store.create_tag(&name);
}
@@ -28,6 +28,7 @@ const TREE_BOTTOM: f32 = 12.0;
pub(crate) enum SidebarRow {
Trash,
Empty(&'static str, usize),
EmptySection(SidebarSection),
Section(SidebarSection),
Favorite(String),
Folder {
@@ -107,6 +108,7 @@ impl SidebarRowKey {
enum RowRef {
Trash,
Empty(&'static str, u16),
EmptySection(SidebarSection),
Section(SidebarSection),
Favorite(u32),
Folder {
@@ -135,7 +137,8 @@ impl RowRef {
fn extent(&self) -> f32 {
let height = match self {
Self::Section(_) => 24.0,
Self::Empty(_, _) => 36.0,
Self::EmptySection(SidebarSection::Folders | SidebarSection::Collections) => 128.0,
Self::EmptySection(_) => 86.0,
_ => 30.0,
};
height + ROW_GAP
@@ -297,12 +300,12 @@ fn build_row_refs_with_lookup(
views: &DocViews,
expanded_groups: Option<&ExpandedGroupsLookup<'_>>,
) {
for (section, empty) in [
(SidebarSection::Favorites, "No favorites"),
(SidebarSection::Folders, "Empty"),
(SidebarSection::Tags, "No tags"),
(SidebarSection::Collections, "No collections"),
(SidebarSection::Others, "Empty"),
for section in [
SidebarSection::Favorites,
SidebarSection::Folders,
SidebarSection::Tags,
SidebarSection::Collections,
SidebarSection::Others,
] {
rows.push(RowRef::Section(section));
if !sidebar.expanded_sections.contains(&section) {
@@ -323,7 +326,7 @@ fn build_row_refs_with_lookup(
.is_some_and(|groups| groups.has_tag(&tag.definition.id))
{
if tag.docs.is_empty() {
rows.push(RowRef::Empty("Empty", 1));
rows.push(RowRef::Empty("No docs", 1));
} else {
rows.reserve(tag.docs.len());
rows.extend((0..tag.docs.len() as u32).map(|doc_idx| RowRef::TagDoc {
@@ -342,7 +345,7 @@ fn build_row_refs_with_lookup(
.is_some_and(|groups| groups.has_collection(&collection.id))
{
if views.collection_counts.get(index) == Some(&0) {
rows.push(RowRef::Empty("Empty", 1));
rows.push(RowRef::Empty("Empty collection", 1));
} else {
for (visible_idx, doc_id) in views.visible.iter().enumerate() {
if store
@@ -362,7 +365,7 @@ fn build_row_refs_with_lookup(
SidebarSection::Others => rows.push(RowRef::Trash),
}
if start == rows.len() {
rows.push(RowRef::Empty(empty, 0));
rows.push(RowRef::EmptySection(section));
}
}
}
@@ -383,7 +386,7 @@ fn push_folder_row_refs(rows: &mut Vec<RowRef>, tree: &SidebarFolderTree, sideba
if sidebar.expanded_folders.contains(id) {
let children = tree.children(Some(id));
if children.is_empty() {
rows.push(RowRef::Empty("Empty", depth + 1));
rows.push(RowRef::Empty("Empty folder", depth + 1));
} else {
rows.reserve(children.len());
pending.extend(
@@ -440,6 +443,7 @@ fn materialize_row(
) -> Option<SidebarRow> {
match row_ref {
RowRef::Trash => Some(SidebarRow::Trash),
RowRef::EmptySection(section) => Some(SidebarRow::EmptySection(*section)),
RowRef::Empty(msg, depth) => Some(SidebarRow::Empty(msg, usize::from(*depth))),
RowRef::Section(section) => Some(SidebarRow::Section(*section)),
RowRef::Favorite(idx) => views
@@ -624,7 +628,7 @@ mod tests {
.collect();
assert_eq!(
tag_rows,
[&SidebarRow::Tag(0), &SidebarRow::Empty("Empty", 1)]
[&SidebarRow::Tag(0), &SidebarRow::Empty("No docs", 1)]
);
assert!(store.docs_for_tag("architecture").is_empty());
assert!(store.search_tag_docs("architecture", 8).is_empty());
@@ -637,6 +641,34 @@ mod tests {
assert_eq!(store.docs[&docs[0]].meta.tags, ["architecture"]);
}
#[test]
fn sidebar_empty_children_use_their_node_labels() {
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
store.switch_workspace(1);
let mut sidebar = SidebarState::default();
let folder = store.create_folder("Folder", None);
sidebar.expanded_folders.insert(folder);
assert!(store.create_collection("Collection"));
assert!(store.create_tag("Tag"));
sidebar.expanded_groups.extend([
TreeGroup::Collection(store.collections[0].id.clone()),
TreeGroup::Tag(store.views().tags[0].definition.id.clone()),
]);
let rows = build_rows(&sidebar, &store);
for (node, message) in [
(SidebarSection::Folders, "Empty folder"),
(SidebarSection::Tags, "No docs"),
(SidebarSection::Collections, "Empty collection"),
] {
let section = rows
.iter()
.position(|row| *row == SidebarRow::Section(node))
.unwrap();
assert_eq!(rows[section + 2], SidebarRow::Empty(message, 1));
}
}
#[test]
fn sidebar_tree_keeps_documents_below_four_nested_folders() {
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
@@ -1179,7 +1211,7 @@ mod tests {
));
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)));
assert!(matches!(refs[tag0_pos + 4], RowRef::Empty("No docs", 1)));
// 3. Full expansion (all 1024 tags + all 1024 collections = 2048 expanded groups).
for i in 0..group_count {
@@ -17,6 +17,7 @@ use crate::{
route_row,
},
split_view::DesktopRoute,
theme_color, theme_tokens_for,
workbench::DesktopShellView,
};
@@ -48,20 +49,27 @@ pub(super) fn render_row(
)
.into_any_element(),
SidebarRow::Section(section) => presentation.section(*section).into_any_element(),
SidebarRow::Empty(message, depth) => div()
.flex()
.items_center()
.h(px(36.0))
.flex_shrink(0.0)
.pl(px(indent(*depth)))
.when(*depth == 0, |el| el.justify_center())
.text_size(px(13.0))
.text_color(palette.text_muted)
.when(*message == "No tags", |el| {
el.gap(px(8.0)).child(icon_view(TAG_ICON_SVG, palette))
})
.child(*message)
.into_any_element(),
SidebarRow::Empty(message, depth) => {
let theme = presentation.theme();
div()
.flex()
.items_center()
.h(px(30.0))
.flex_shrink(0.0)
.pl(px(indent(*depth) + 28.0))
.text_size(px(13.0))
.line_height(px(22.0))
.text_color(theme_color(
theme,
"--affine-v2-text-disable",
theme.text_secondary,
))
.child(*message)
.into_any_element()
}
SidebarRow::EmptySection(section) => {
presentation.empty_section(*section).into_any_element()
}
SidebarRow::Favorite(doc_id) => presentation.document(
SidebarRowKey::Favorite(doc_id.clone()),
ui::snap_id!("desktop.sidebar.fav.{doc_id}"),
@@ -156,11 +164,7 @@ pub(super) fn render_row(
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 theme = presentation.theme();
let id = &tag.definition.id;
presentation.group(
SidebarRowKey::Tag(id.clone()),
@@ -189,6 +193,107 @@ struct RowPresentation<'a, 'b> {
}
impl RowPresentation<'_, '_> {
fn theme(&self) -> &'static ui_tokens::ThemeTokens {
theme_tokens_for(if self.palette.bg_canvas.l < 0.5 {
ui_tokens::ThemeMode::Dark
} else {
ui_tokens::ThemeMode::Light
})
}
fn empty_section(&self, section: SidebarSection) -> ui::Div {
let (message, icon, action) = match section {
SidebarSection::Favorites => (
"No favorites",
ui_tokens::icons::FAVORITE.svg.as_bytes(),
None,
),
SidebarSection::Folders => (
"No folders",
FOLDER_ICON_SVG,
Some(("desktop.sidebar.empty.new_folder", "New folder")),
),
SidebarSection::Collections => (
"No collections",
COLLECTION_ICON_SVG,
Some(("desktop.sidebar.empty.new_collection", "New collection")),
),
SidebarSection::Tags => ("No tags", TAG_ICON_SVG, None),
SidebarSection::Others => return div(),
};
let palette = self.palette;
let theme = self.theme();
let icon_bg = theme_color(
theme,
"--affine-v2-button-emptyIconBackground",
theme.background_secondary,
);
let icon_color = theme_color(theme, "--affine-v2-icon-secondary", theme.text_secondary);
let message_color = theme_color(theme, "--affine-v2-text-tertiary", theme.text_secondary);
let button_bg = theme_color(
theme,
"--affine-v2-button-secondary",
theme.background_primary,
);
div()
.w_full()
.flex()
.flex_col()
.flex_shrink(0.0)
.items_center()
.py(px(12.0))
.gap(px(4.0))
.text_size(px(13.0))
.text_color(message_color)
.child(
div()
.size(px(36.0))
.rounded(px(18.0))
.bg(icon_bg)
.flex()
.items_center()
.justify_center()
.child(icon_view(icon, palette).text_color(icon_color)),
)
.child(div().line_height(px(22.0)).child(message))
.children(action.map(|(id, label)| {
div()
.id(id)
.snapshot(id, Some("desktop.sidebar"))
.mt(px(8.0))
.h(px(30.0))
.px(px(8.0))
.flex()
.items_center()
.rounded(px(8.0))
.border_1()
.border_color(palette.border)
.bg(button_bg)
.text_color(palette.text_primary)
.child(label)
.when(self.readonly, |button| button.opacity(0.3))
.when(!self.readonly, |button| {
button
.cursor_pointer()
.hover(move |style| style.bg(palette.hover_overlay))
.on_click(self.cx.listener(
move |this, event: &ui::ClickEvent, window, cx| {
this.state.sidebar.dismiss_popups();
add_doc_or_folder(
this,
&TreeTarget::Section(section),
event.position(),
window,
cx,
);
cx.stop_propagation();
cx.notify();
},
))
})
}))
}
fn section(&self, section: SidebarSection) -> ui::Stateful<ui::Div> {
let (snap_id, parent_id, add_snap_id, label) = match section {
SidebarSection::Favorites => (
@@ -304,7 +409,8 @@ impl RowPresentation<'_, '_> {
close_drawer(&mut this.state.sidebar, window);
cx.notify();
}));
self.actions(row, &key, target, false).into_any_element()
self.actions(row, &key, target, !self.readonly)
.into_any_element()
}
fn group(
@@ -331,6 +437,7 @@ impl RowPresentation<'_, '_> {
cx.stop_propagation();
cx.notify();
}));
let add_child = matches!(route, DesktopRoute::Tag(_)) && !self.readonly;
let target = TreeTarget::Group(route.clone());
let row = row_shell(
key.element_id(),
@@ -346,7 +453,8 @@ impl RowPresentation<'_, '_> {
cx.notify();
}));
let row = self.hover_row(row, key.clone());
self.actions(row, &key, target, false).into_any_element()
self.actions(row, &key, target, add_child)
.into_any_element()
}
fn node(
@@ -427,17 +535,28 @@ impl RowPresentation<'_, '_> {
self.cx
.listener(move |this, event: &ui::MouseDownEvent, _, cx| {
this.state.sidebar.dismiss_popups();
this.state.sidebar.popup =
Some(Popup::Tree(TreeMenu::new(menu.clone(), event.position)));
this.state.sidebar.popup = Some(Popup::Tree(TreeMenu::new(
menu.clone(),
event.position,
&this.state,
)));
cx.stop_propagation();
cx.notify();
}),
)
.when(self.show_actions(key), |el| {
el.when(add_child, |el| {
el.child(self.action_button("add", target.clone(), true))
el.child(
self.action_button("add", target.clone(), true)
.size(px(24.0))
.snapshot("desktop.sidebar.node.add", Some("desktop.sidebar")),
)
})
.child(self.action_button("more", target, false))
.child(
self.action_button("more", target, false)
.size(px(24.0))
.snapshot("desktop.sidebar.node.more", Some("desktop.sidebar")),
)
})
}
@@ -477,6 +596,7 @@ impl RowPresentation<'_, '_> {
this.state.sidebar.popup = Some(Popup::Tree(TreeMenu::new(
target.clone(),
event.position(),
&this.state,
)));
}
cx.stop_propagation();
+95 -3
View File
@@ -22,6 +22,8 @@ pub struct WebDesktopMountOptions {
pub editor_font: EditorFontPreferences,
pub initial_workspace_id: Option<String>,
pub initial_doc_id: Option<String>,
pub initial_tag_id: Option<String>,
pub initial_collection_id: Option<String>,
pub initial_doc_mode: Option<DocMode>,
pub initial_block_ids: Vec<String>,
pub initial_element_ids: Vec<String>,
@@ -38,6 +40,8 @@ impl Default for WebDesktopMountOptions {
editor_font: EditorFontPreferences::default(),
initial_workspace_id: None,
initial_doc_id: None,
initial_tag_id: None,
initial_collection_id: None,
initial_doc_mode: None,
initial_block_ids: Vec::new(),
initial_element_ids: Vec::new(),
@@ -125,6 +129,18 @@ impl WebDesktopMountOptions {
}
None => {}
}
} else if let Some(tag_id) = &self.initial_tag_id
&& state.store.views().tag(tag_id).is_some()
{
state.navigate_active_pane(DesktopRoute::Tag(tag_id.clone()));
} else if let Some(collection_id) = &self.initial_collection_id
&& state
.store
.collections
.iter()
.any(|collection| &collection.id == collection_id)
{
state.navigate_active_pane(DesktopRoute::Collection(collection_id.clone()));
}
if self.split_view {
let initial_pane = state.split.active_pane;
@@ -202,7 +218,10 @@ mod web_store {
use wasm_bindgen::prelude::wasm_bindgen;
use crate::workbench::{LocalDocStore, StoredWorkspaces};
use crate::{
split_view::DesktopRoute,
workbench::{LocalDocStore, StoredWorkspaces},
};
#[wasm_bindgen]
extern "C" {
@@ -243,7 +262,13 @@ mod web_store {
fn retry_blob_writes(this: &WebDesktopStore);
#[wasm_bindgen(method, js_name = setRoute)]
fn set_route(this: &WebDesktopStore, workspace_id: &str, doc_id: Option<String>);
fn set_route(
this: &WebDesktopStore,
workspace_id: &str,
doc_id: Option<String>,
tag_id: Option<String>,
collection_id: Option<String>,
);
#[wasm_bindgen(method, js_name = reportError)]
pub fn report_error(this: &WebDesktopStore, message: &str);
@@ -325,7 +350,17 @@ mod web_store {
}
fn set_route(&self, workspace_id: &str, doc_id: Option<&str>) {
WebDesktopStore::set_route(self, workspace_id, doc_id.map(str::to_owned));
WebDesktopStore::set_route(self, workspace_id, doc_id.map(str::to_owned), None, None);
}
fn set_view_route(&self, workspace_id: &str, route: &DesktopRoute) {
let (doc_id, tag_id, collection_id) = match route {
DesktopRoute::Doc(id) => (Some(id.clone()), None, None),
DesktopRoute::Tag(id) => (None, Some(id.clone()), None),
DesktopRoute::Collection(id) => (None, None, Some(id.clone())),
_ => (None, None, None),
};
WebDesktopStore::set_route(self, workspace_id, doc_id, tag_id, collection_id);
}
}
}
@@ -350,6 +385,12 @@ extern "C" {
#[wasm_bindgen(method, getter, js_name = initialDocMode)]
fn initial_doc_mode(this: &WebDesktopHost) -> Option<String>;
#[wasm_bindgen(method, getter, js_name = initialTagId)]
fn initial_tag_id(this: &WebDesktopHost) -> Option<String>;
#[wasm_bindgen(method, getter, js_name = initialCollectionId)]
fn initial_collection_id(this: &WebDesktopHost) -> Option<String>;
#[wasm_bindgen(method, getter, js_name = initialBlockIds)]
fn initial_block_ids(this: &WebDesktopHost) -> Option<js_sys::Array>;
@@ -478,6 +519,10 @@ pub fn wasm_desktop_main(
},
initial_workspace_id: workspace_id,
initial_doc_id: doc_id,
initial_tag_id: host.as_ref().and_then(WebDesktopHost::initial_tag_id),
initial_collection_id: host
.as_ref()
.and_then(WebDesktopHost::initial_collection_id),
initial_block_ids: read_ids(WebDesktopHost::initial_block_ids),
initial_element_ids: read_ids(WebDesktopHost::initial_element_ids),
initial_doc_mode: match host
@@ -587,6 +632,53 @@ mod tests {
use super::*;
#[test]
fn cold_desktop_resolves_groups_in_the_requested_workspace_after_valid_docs() {
let workspace = crate::showcase::SHOWCASE_WORKSPACE_IDS[0];
let initial = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
let tag = initial.store.views().tags[0].definition.id.clone();
let collection = initial.store.collections[0].id.clone();
let doc = initial.split.active().active_route().clone();
for (doc_id, tag_id, collection_id, expected) in [
(
None,
Some(tag.clone()),
None,
DesktopRoute::Tag(tag.clone()),
),
(
Some("missing-doc".into()),
Some("missing-tag".into()),
Some(collection.clone()),
DesktopRoute::Collection(collection),
),
(
doc.doc_id().map(str::to_owned),
Some(tag),
None,
doc.clone(),
),
(
None,
Some("missing-tag".into()),
Some("missing-collection".into()),
doc,
),
] {
let (state, _) = WebDesktopMountOptions {
initial_workspace_id: Some(workspace.into()),
initial_doc_id: doc_id,
initial_tag_id: tag_id,
initial_collection_id: collection_id,
..Default::default()
}
.build_state(None, 0)
.unwrap();
assert_eq!(state.store.active_workspace().id, workspace);
assert_eq!(state.split.active().active_route(), &expected);
}
}
#[test]
fn cold_block_link_selects_the_ordered_page_targets_in_the_requested_workspace() {
use blocksuite_editor::directory::EditorDocMode;
@@ -34,6 +34,7 @@ use crate::{
merge_pending_updates,
},
showcase::SHOWCASE_WORKSPACE_ID,
split_view::DesktopRoute,
};
/// Stored update frames of each document of a workspace, in write order.
@@ -61,6 +62,11 @@ pub trait LocalDocStore {
/// Remember the active workspace and the document that its active pane shows.
fn set_route(&self, workspace_id: &str, doc_id: Option<&str>);
/// Remember the active route on hosts that expose group destinations.
fn set_view_route(&self, workspace_id: &str, route: &DesktopRoute) {
self.set_route(workspace_id, route.doc_id());
}
/// Read the media already stored for this workspace.
fn load_blobs(&self, _workspace_id: &str) -> StoredBlobs {
StoredBlobs::new()
@@ -290,9 +296,8 @@ impl LocalWorkspaces {
}
}
/// What the shell last wrote: the active workspace, its document list revision, and the
/// open document.
type SavedView = (String, u64, Option<String>);
/// The active workspace, its document list revision, and the route at the last save.
type SavedView = (String, u64, DesktopRoute);
pub(super) struct LocalBinding {
workspaces: Rc<LocalWorkspaces>,
@@ -609,30 +614,30 @@ impl DesktopShellView {
} else {
local.workspaces.save_queued(false);
}
let doc = self.state.split.active().active_route().doc_id();
let view = (active, store.derived.meta_rev, doc.map(str::to_owned));
let route = self.state.split.active().active_route();
let view = (active, store.derived.meta_rev, route.clone());
if local
.saved
.as_ref()
.is_none_or(|saved| (&saved.0, &saved.2) != (&view.0, &view.2))
{
local.workspaces.store.set_route(&view.0, doc);
local.workspaces.store.set_view_route(&view.0, route);
}
local.saved = Some(view);
}
/// Save at once when the active workspace, its document list, or the open document
/// Save at once when the active workspace, its document list, or the active route
/// changed since the last save.
pub(super) fn save_local_workspaces_if_changed(&mut self) {
let Some(local) = &self.local else {
return;
};
let store = &self.state.store;
let doc = self.state.split.active().active_route().doc_id();
let unchanged = local.saved.as_ref().is_some_and(|(id, rev, saved_doc)| {
let route = self.state.split.active().active_route();
let unchanged = local.saved.as_ref().is_some_and(|(id, rev, saved_route)| {
*id == store.active_workspace().id
&& *rev == store.derived.meta_rev
&& saved_doc.as_deref() == doc
&& saved_route == route
});
if !unchanged {
self.save_local_workspaces();
@@ -62,6 +62,17 @@ impl HeaderOverlay {
}
}
fn is_current(&self, shell: &DesktopShellView) -> bool {
match self.kind {
OverlayKind::Info | OverlayKind::Trash => {
doc_dialog_target_is_current(&self.target, shell)
}
OverlayKind::Menu { .. } | OverlayKind::Share { .. } => {
self.target.pane_index(shell).is_some()
}
}
}
pub(super) fn share(target: DocTarget) -> Self {
Self {
target,
@@ -73,12 +84,48 @@ impl HeaderOverlay {
}
}
fn doc_dialog_target_is_current(target: &DocTarget, shell: &DesktopShellView) -> bool {
shell.state.store.active_workspace().id == target.workspace
&& shell.state.is_openable_doc(&target.doc)
}
impl DesktopShellView {
pub(crate) fn show_sidebar_doc_dialog(
&mut self,
doc: &str,
trash: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
if !self.state.is_openable_doc(doc) || (trash && self.state.store.is_readonly_sqlite()) {
return;
}
let pane = self.state.split.active();
let target = DocTarget {
workspace: self.state.store.active_workspace().id.clone(),
pane: pane.id,
tab: pane.active_tab().id,
doc: doc.to_owned(),
};
self.show_header_overlay(
HeaderOverlay {
target,
kind: if trash {
OverlayKind::Trash
} else {
OverlayKind::Info
},
},
window,
cx,
);
}
pub(in crate::workbench) fn drop_stale_header_controls(&mut self, cx: &mut Context<Self>) {
if self
.header_overlay
.as_ref()
.is_some_and(|overlay| overlay.target.pane_index(self).is_none())
.is_some_and(|overlay| !overlay.is_current(self))
{
self.header_overlay = None;
}
@@ -253,9 +300,11 @@ pub(in crate::workbench) fn render_header_overlay(
cx: &mut Context<DesktopShellView>,
) -> Option<AnyElement> {
let overlay = shell.header_overlay.as_ref()?;
if !overlay.is_current(shell) {
return None;
}
let target = &overlay.target;
let entry = shell.state.store.get_doc(&target.doc)?;
let mode = shell.state.split.panes[target.pane_index(shell)?].active_mode();
let locked = shell.state.store.is_readonly_sqlite() || entry.meta.trashed;
let full_width = shell.state.effective_page_full_width(&target.doc);
let (width, height) = size;
@@ -268,7 +317,8 @@ pub(in crate::workbench) fn render_header_overlay(
if entry.meta.trashed {
return None;
}
let is_page = mode == DocViewMode::Page;
let is_page =
shell.state.split.panes[target.pane_index(shell)?].active_mode() == DocViewMode::Page;
let is_journal = entry.meta.journal_date.is_some();
let (mode, view_mode, convert_label, convert_icon) = match entry.meta.default_mode {
DocMode::Page => (
@@ -523,9 +573,22 @@ pub(in crate::workbench) fn render_header_overlay(
palette.danger.opacity(0.88),
palette,
cx.listener(move |shell, _, window, cx| {
if target.activate(shell) {
if doc_dialog_target_is_current(&target, shell)
&& !shell.state.store.is_readonly_sqlite()
{
shell.sync_editors(cx);
shell.state.trash_header_doc(&target.doc);
let pane = target.pane_index(shell).or_else(|| {
shell.state.split.panes.iter().position(|pane| {
pane.active_route().doc_id()
== Some(target.doc.as_str())
})
});
if let Some(pane) = pane {
shell.state.split.focus_pane(pane);
shell.state.trash_header_doc(&target.doc);
} else {
shell.state.trash_doc(&target.doc);
}
}
shell.close_header_overlay(window, cx);
}),
@@ -548,6 +611,7 @@ pub(in crate::workbench) fn render_header_overlay(
));
}
OverlayKind::Share { choices, copied } => {
let mode = shell.state.split.panes[target.pane_index(shell)?].active_mode();
let default = (mode == DocViewMode::Edgeless).then_some(mode);
let origin = if shell.state.web_chrome {
playground::default_block_link_origin()
@@ -49,7 +49,7 @@ fn sidebar_tree_menu_hover_uses_menu_color_only_when_enabled() -> Result<()> {
let color = (!readonly).then_some(palette_for(theme).hover_color);
for (trigger, label) in [
("desktop.sidebar.fav.doc-arch", "Rename"),
("desktop.sidebar.folder.f-eng", "New Page"),
("desktop.sidebar.folder.f-eng", "New doc"),
] {
shell.right_click(trigger)?;
shell.bounds("desktop.sidebar.tree_menu")?;
+10 -3
View File
@@ -241,20 +241,25 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
deleteDoc(workspaceId, docId) {
enqueue(workspaceId, { docId, delete: true });
},
setRoute(workspaceId, docId) {
setRoute(workspaceId, docId, tagId, collectionId) {
if (!env.location || !env.history) return;
const url = new URL(env.location.href);
if (
!docId ||
url.searchParams.get('workspace') !== workspaceId ||
url.searchParams.get('doc') !== (docId ?? null)
url.searchParams.get('doc') !== docId
) {
for (const key of ['mode', 'blockIds', 'elementIds']) {
url.searchParams.delete(key);
}
}
url.searchParams.set('workspace', workspaceId);
for (const key of ['doc', 'tag', 'collection']) {
url.searchParams.delete(key);
}
if (docId) url.searchParams.set('doc', docId);
else url.searchParams.delete('doc');
else if (tagId) url.searchParams.set('tag', tagId);
else if (collectionId) url.searchParams.set('collection', collectionId);
env.history.replaceState(env.history.state, '', url);
},
reportError(message) {
@@ -297,6 +302,8 @@ function desktopHost(env, params, media) {
),
];
return {
initialTagId: params.get('tag') || undefined,
initialCollectionId: params.get('collection') || undefined,
initialBlockIds: ids('blockIds'),
initialElementIds: ids('elementIds'),
initialDocMode: mode === 'page' || mode === 'edgeless' ? mode : undefined,
@@ -1330,3 +1330,86 @@ void test('desktop keeps cold URL targets only for the matching route selected b
);
}
});
void test('desktop group URLs round-trip with one target and drop document selections', async () => {
const indexedDB = createMemoryIdbFactory();
const ids = ['ws'];
const initial = await openDesktopStore(ids, { indexedDB });
initial.pushUpdate('ws', 'page', Uint8Array.of(1));
await initial.flush();
for (const [key, id] of [
['tag', 'tag / 文'],
['collection', 'collection ?#&'],
]) {
const location = {
href: 'https://example.com/desktop/?workspace=ws&doc=page&mode=edgeless&blockIds=note&elementIds=shape&theme=dark',
};
const history = {
replaceState(_state, _title, url) {
location.href = url.href;
},
};
const openStore = () =>
openDesktopStore(ids, { indexedDB, location, history });
const store = await openStore();
const setGroup = store =>
store.setRoute(
'ws',
undefined,
key === 'tag' ? id : undefined,
key === 'collection' ? id : undefined
);
setGroup(store);
const expected = new URLSearchParams({
workspace: 'ws',
theme: 'dark',
[key]: id,
});
assert.deepEqual([...new URL(location.href).searchParams], [...expected]);
const wasm = {
default() {},
web_desktop_workspace_ids: () => ids,
wasm_desktop_main(_dark, _split, workspace, doc, cold, _now, host) {
assert.equal(workspace, 'ws');
assert.equal(doc, undefined);
assert.equal(host.initialTagId, key === 'tag' ? id : undefined);
assert.equal(
host.initialCollectionId,
key === 'collection' ? id : undefined
);
assert.equal(host.initialDocMode, undefined);
assert.deepEqual(host.initialBlockIds, []);
assert.deepEqual(host.initialElementIds, []);
setGroup(cold);
},
};
await startDesktop(
wasm,
[],
new URL(location.href).search,
false,
{},
openStore
);
assert.deepEqual([...new URL(location.href).searchParams], [...expected]);
store.setRoute('ws', 'next-page');
assert.deepEqual(
[...new URL(location.href).searchParams],
[
['workspace', 'ws'],
['theme', 'dark'],
['doc', 'next-page'],
]
);
store.setRoute('ws');
assert.deepEqual(
[...new URL(location.href).searchParams],
[
['workspace', 'ws'],
['theme', 'dark'],
]
);
}
});