mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 19:25:00 +03:00
feat(desktop): add sidebar doc drops and linked doc rows
A doc row that you drag from any sidebar section onto an organize folder adds a link to that doc in the folder. If the folder already has a link to that doc, the drop moves the link. A drop on an organize row still moves that row. A doc row that you drop on a tag row adds the tag to the doc. The tag change is idempotent and stays after the workspace opens again. Escape, or a release outside the sidebar, cancels the drag and writes nothing. Doc rows that link to other docs now expand to show the linked docs. Rows start collapsed. The expansion state uses the full row path, and a doc that is already an ancestor in the path does not show again. "Add linked doc" expands the parent row. The "show linked docs in sidebar" setting is on by default and Web Desktop keeps it in localStorage. When the setting is off, doc rows show no arrow and no linked docs.
This commit is contained in:
1 parent
cacab32acd
commit
96709cab51
11 files changed
+1022
-83
No files matched your search
@@ -262,13 +262,15 @@ impl FolderForest {
|
||||
}
|
||||
}
|
||||
|
||||
/// Place a folder or document link relative to a row in the organization tree.
|
||||
/// Where a sidebar drag drops: relative to a row of the organization tree, or onto a tag.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum FolderDrop<'a> {
|
||||
Before(&'a str),
|
||||
After(&'a str),
|
||||
Inside(&'a str),
|
||||
Root,
|
||||
/// Add the tag to the dragged document. No folder row changes.
|
||||
Tag(&'a str),
|
||||
}
|
||||
|
||||
impl<'a> FolderDrop<'a> {
|
||||
@@ -280,6 +282,20 @@ impl<'a> FolderDrop<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a sidebar drag moves: a row of the organization tree, or a document from any other
|
||||
/// section of the sidebar.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DropSource<'a> {
|
||||
Row(&'a str),
|
||||
Doc(&'a str),
|
||||
}
|
||||
|
||||
impl<'a> From<&'a String> for DropSource<'a> {
|
||||
fn from(id: &'a String) -> Self {
|
||||
Self::Row(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the changed rows for a valid drop. A drop that keeps the current order can be empty.
|
||||
pub fn plan_folder_drop(
|
||||
rows: &[FolderRow],
|
||||
@@ -301,6 +317,7 @@ pub fn plan_folder_drop(
|
||||
}
|
||||
FolderDrop::Inside(target) => (Some(target), None),
|
||||
FolderDrop::Root => (None, None),
|
||||
FolderDrop::Tag(_) => return None,
|
||||
};
|
||||
if parent.is_none() && source.folder_type != "folder" {
|
||||
return None;
|
||||
@@ -391,6 +408,40 @@ pub fn plan_folder_drop(
|
||||
}])
|
||||
}
|
||||
|
||||
/// Return the changed rows that link `doc_id` at `drop`. When the destination folder already
|
||||
/// links the document, that link moves. Otherwise the plan adds the link row `link_id`.
|
||||
pub fn plan_doc_link_drop(
|
||||
rows: &[FolderRow],
|
||||
doc_id: &str,
|
||||
link_id: &str,
|
||||
drop: FolderDrop<'_>,
|
||||
) -> Option<Vec<FolderRow>> {
|
||||
let parent = match drop {
|
||||
FolderDrop::Before(target) | FolderDrop::After(target) => rows
|
||||
.iter()
|
||||
.find(|row| row.id == target)?
|
||||
.parent_id
|
||||
.as_deref(),
|
||||
FolderDrop::Inside(target) => Some(target),
|
||||
FolderDrop::Root | FolderDrop::Tag(_) => return None,
|
||||
};
|
||||
if let Some(existing) = rows.iter().find(|row| {
|
||||
row.folder_type == "doc" && row.data == doc_id && row.parent_id.as_deref() == parent
|
||||
}) {
|
||||
return plan_folder_drop(rows, &existing.id, drop);
|
||||
}
|
||||
let mut linked = Vec::with_capacity(rows.len() + 1);
|
||||
linked.extend_from_slice(rows);
|
||||
linked.push(FolderRow {
|
||||
id: link_id.to_owned(),
|
||||
parent_id: None,
|
||||
data: doc_id.to_owned(),
|
||||
folder_type: "doc".to_owned(),
|
||||
index: String::new(),
|
||||
});
|
||||
plan_folder_drop(&linked, link_id, drop)
|
||||
}
|
||||
|
||||
/// Revision-keyed cache avoiding redundant forest sanitization when `db$folders` has not changed.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FolderForestCache {
|
||||
@@ -567,6 +618,66 @@ mod tests {
|
||||
assert_eq!(forest.placements_for_doc("doc-ok").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_link_drop_adds_one_link_per_folder_and_moves_an_existing_link() {
|
||||
let rows = vec![
|
||||
folder("f-a", None, "A", "a0"),
|
||||
folder("f-b", None, "B", "a1"),
|
||||
doc_link("l-1", Some("f-a"), "doc-1", "a0"),
|
||||
doc_link("l-2", Some("f-a"), "doc-2", "a1"),
|
||||
];
|
||||
let parent_and_index = |plan: &[FolderRow], id: &str| {
|
||||
plan.iter()
|
||||
.find(|row| row.id == id)
|
||||
.map(|row| (row.parent_id.clone(), row.index.clone()))
|
||||
};
|
||||
// A new link goes inside, before, or after a row of the destination folder.
|
||||
for (drop, after, before) in [
|
||||
(FolderDrop::Inside("f-b"), None, None),
|
||||
(FolderDrop::Before("l-1"), None, Some("a0")),
|
||||
(FolderDrop::After("l-1"), Some("a0"), Some("a1")),
|
||||
(FolderDrop::After("l-2"), Some("a1"), None),
|
||||
] {
|
||||
let plan = plan_doc_link_drop(&rows, "doc-3", "l-new", drop).unwrap();
|
||||
let (parent, index) = parent_and_index(&plan, "l-new").unwrap();
|
||||
let expected = match drop {
|
||||
FolderDrop::Inside(id) => id,
|
||||
_ => "f-a",
|
||||
};
|
||||
assert_eq!(parent.as_deref(), Some(expected), "{drop:?}");
|
||||
assert!(after.is_none_or(|after| after < index.as_str()), "{drop:?}");
|
||||
assert!(
|
||||
before.is_none_or(|before| index.as_str() < before),
|
||||
"{drop:?}"
|
||||
);
|
||||
assert_eq!(plan[0].data, "doc-3");
|
||||
}
|
||||
// The folder that links the document moves its link and adds no row.
|
||||
let plan = plan_doc_link_drop(&rows, "doc-1", "l-new", FolderDrop::After("l-2")).unwrap();
|
||||
assert_eq!(plan.len(), 1);
|
||||
assert_eq!(plan[0].id, "l-1");
|
||||
assert!(parent_and_index(&plan, "l-new").is_none());
|
||||
// The root, a tag, an unknown anchor, and the link itself are no destinations.
|
||||
for drop in [
|
||||
FolderDrop::Root,
|
||||
FolderDrop::Tag("tag"),
|
||||
FolderDrop::Before("missing"),
|
||||
FolderDrop::Before("f-a"),
|
||||
FolderDrop::Before("l-1"),
|
||||
] {
|
||||
let doc = if drop == FolderDrop::Before("l-1") {
|
||||
"doc-1"
|
||||
} else {
|
||||
"doc-3"
|
||||
};
|
||||
assert_eq!(
|
||||
plan_doc_link_drop(&rows, doc, "l-new", drop),
|
||||
None,
|
||||
"{drop:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dfs_folders_emits_true_preorder_hierarchy_and_depths() {
|
||||
let rows = vec![
|
||||
|
||||
@@ -471,6 +471,7 @@ mod tests {
|
||||
assert!(stored.index > existing.index)
|
||||
}
|
||||
FolderDrop::Root => assert!(stored.parent_id.is_none()),
|
||||
FolderDrop::Tag(_) => unreachable!("the table holds no tag drop"),
|
||||
}
|
||||
assert_eq!(
|
||||
session.move_folder_row(id, drop, 1_040).unwrap(),
|
||||
|
||||
@@ -1,30 +1,75 @@
|
||||
//! Sidebar order changes.
|
||||
//! Sidebar order changes and drops of documents onto folders and tags.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use affine_client::organize::{FolderDrop, plan_folder_drop};
|
||||
use affine_client::organize::{DropSource, FolderDrop, plan_doc_link_drop, plan_folder_drop};
|
||||
use affine_store::workspace_db::FolderRow;
|
||||
|
||||
use super::DesktopDocStore;
|
||||
|
||||
/// The writes of a valid drop.
|
||||
enum DropPlan {
|
||||
/// Move a row of the organization tree.
|
||||
Move(Vec<FolderRow>),
|
||||
/// Add or move the link of a document from outside the organization tree.
|
||||
Link(Vec<FolderRow>),
|
||||
/// Add a tag to a document. `None` keeps a document that already has the tag.
|
||||
Tag {
|
||||
doc: String,
|
||||
tags: Option<Vec<String>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl DesktopDocStore {
|
||||
pub(crate) fn can_drop_folder_row(&self, id: &str, drop: FolderDrop<'_>) -> bool {
|
||||
!self.is_readonly_sqlite() && plan_folder_drop(&self.folder_rows, id, drop).is_some()
|
||||
pub(crate) fn can_drop_folder_row<'a>(
|
||||
&self,
|
||||
source: impl Into<DropSource<'a>>,
|
||||
drop: FolderDrop<'_>,
|
||||
) -> bool {
|
||||
!self.is_readonly_sqlite() && self.plan_drop(source.into(), "", drop).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn drop_folder_row(&mut self, id: &str, drop: FolderDrop<'_>) -> bool {
|
||||
pub(crate) fn drop_folder_row<'a>(
|
||||
&mut self,
|
||||
source: impl Into<DropSource<'a>>,
|
||||
drop: FolderDrop<'_>,
|
||||
) -> bool {
|
||||
if self.is_readonly_sqlite() {
|
||||
return false;
|
||||
}
|
||||
let now = self.writer_now();
|
||||
let changed = match self.with_session(now, |session| session.move_folder_row(id, drop, now))
|
||||
{
|
||||
Some(Ok(rows)) => rows,
|
||||
Some(Err(_)) => return false,
|
||||
None => plan_folder_drop(&self.folder_rows, id, drop),
|
||||
let source = source.into();
|
||||
let link = match source {
|
||||
DropSource::Doc(_) => self.next_folder_row_id("link"),
|
||||
DropSource::Row(_) => String::new(),
|
||||
};
|
||||
let Some(changed) = changed else {
|
||||
let Some(plan) = self.plan_drop(source, &link, drop) else {
|
||||
return false;
|
||||
};
|
||||
let now = self.writer_now();
|
||||
let changed = match plan {
|
||||
DropPlan::Move(rows) => {
|
||||
let DropSource::Row(id) = source else {
|
||||
return false;
|
||||
};
|
||||
match self.with_session(now, |session| session.move_folder_row(id, drop, now)) {
|
||||
Some(Ok(Some(rows))) => rows,
|
||||
Some(_) => return false,
|
||||
None => rows,
|
||||
}
|
||||
}
|
||||
DropPlan::Link(rows) => {
|
||||
if let Some(Err(_)) = self.with_session(now, |session| {
|
||||
rows.iter()
|
||||
.try_for_each(|row| session.upsert_folder_row(row, now))
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
rows
|
||||
}
|
||||
DropPlan::Tag { doc, tags } => {
|
||||
return tags.is_none_or(|tags| self.write_doc_tags(&doc, tags, now));
|
||||
}
|
||||
};
|
||||
if !changed.is_empty() {
|
||||
let mut by_id: HashMap<_, _> = changed
|
||||
.into_iter()
|
||||
@@ -40,6 +85,63 @@ impl DesktopDocStore {
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Plan a drop of `source` at `drop`. A document from outside the organization tree gets
|
||||
/// the new link row `link`.
|
||||
fn plan_drop(
|
||||
&self,
|
||||
source: DropSource<'_>,
|
||||
link: &str,
|
||||
drop: FolderDrop<'_>,
|
||||
) -> Option<DropPlan> {
|
||||
let FolderDrop::Tag(tag) = drop else {
|
||||
return match source {
|
||||
DropSource::Row(id) => {
|
||||
plan_folder_drop(&self.folder_rows, id, drop).map(DropPlan::Move)
|
||||
}
|
||||
DropSource::Doc(doc) => {
|
||||
self.get_doc(doc).filter(|entry| !entry.meta.trashed)?;
|
||||
plan_doc_link_drop(&self.folder_rows, doc, link, drop).map(DropPlan::Link)
|
||||
}
|
||||
};
|
||||
};
|
||||
let doc = match source {
|
||||
DropSource::Doc(doc) => doc,
|
||||
DropSource::Row(id) => {
|
||||
let row = self.folder_rows.iter().find(|row| row.id == id)?;
|
||||
(row.folder_type == "doc").then_some(row.data.as_str())?
|
||||
}
|
||||
};
|
||||
let meta = &self.get_doc(doc).filter(|entry| !entry.meta.trashed)?.meta;
|
||||
self.views().tag(tag)?;
|
||||
let tags = (!meta.tags.iter().any(|id| id == tag)).then(|| {
|
||||
let mut tags = meta.tags.clone();
|
||||
tags.push(tag.to_owned());
|
||||
tags
|
||||
});
|
||||
Some(DropPlan::Tag {
|
||||
doc: doc.to_owned(),
|
||||
tags,
|
||||
})
|
||||
}
|
||||
|
||||
/// Save the tags of `doc` in the workspace root and project them.
|
||||
fn write_doc_tags(&mut self, doc: &str, tags: Vec<String>, now: i64) -> bool {
|
||||
let saved =
|
||||
match self.with_session(now, |session| session.set_document_tags(doc, &tags, now)) {
|
||||
Some(result) => result.is_ok(),
|
||||
None if self.directory.db().root().is_meta_initialized() => {
|
||||
self.directory.db_mut().set_page_tags(doc, &tags).is_ok()
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
let Some(entry) = saved.then(|| self.docs.get_mut(doc)).flatten() else {
|
||||
return false;
|
||||
};
|
||||
entry.meta.tags = tags;
|
||||
self.touch_meta();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -111,4 +213,118 @@ mod tests {
|
||||
drop(reopened);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn document_drops_link_folders_once_and_tag_documents_across_sqlite_reopen() {
|
||||
use affine_store::directory::DocMode;
|
||||
|
||||
let mut store = DesktopDocStore::seed_showcase("2026-12-02");
|
||||
store.folder_rows.clear();
|
||||
let workspace = store.active_workspace().id.clone();
|
||||
let dir = std::env::temp_dir().join(format!("affine-doc-drops-{}", std::process::id()));
|
||||
let sqlite = SqliteWorkspaceStore::open(&dir, "workspace", "local", &workspace)
|
||||
.await
|
||||
.unwrap();
|
||||
let session = Arc::new(Mutex::new(
|
||||
sqlite
|
||||
.load_workspace_session("user", 42, HostKind::Native, "", "", 1_000)
|
||||
.await
|
||||
.unwrap(),
|
||||
));
|
||||
store.bind_writer(SessionWriter::new(
|
||||
workspace,
|
||||
session.clone(),
|
||||
Default::default(),
|
||||
1_010,
|
||||
));
|
||||
let folder = store.create_folder("Folder", None);
|
||||
let other = store.create_folder("Other", None);
|
||||
let [doc, linked] =
|
||||
["Dropped", "Linked"].map(|title| store.create_doc(title, DocMode::Page, None, 1_011));
|
||||
assert!(store.create_tag("Review"));
|
||||
assert!(store.create_tag("Later"));
|
||||
let tag = |store: &DesktopDocStore, name: &str| {
|
||||
store
|
||||
.views()
|
||||
.tags
|
||||
.iter()
|
||||
.find(|tag| tag.definition.name == name)
|
||||
.unwrap()
|
||||
.definition
|
||||
.id
|
||||
.clone()
|
||||
};
|
||||
let (review, later) = (tag(&store, "Review"), tag(&store, "Later"));
|
||||
store.move_doc_to_folder(&linked, Some(&other));
|
||||
let link = store
|
||||
.folder_rows
|
||||
.iter()
|
||||
.find(|row| row.data == linked)
|
||||
.unwrap()
|
||||
.id
|
||||
.clone();
|
||||
|
||||
// A second drop of the same document keeps one link and one tag.
|
||||
for _ in 0..2 {
|
||||
assert!(store.drop_folder_row(DropSource::Doc(&doc), FolderDrop::Inside(&folder)));
|
||||
assert!(store.drop_folder_row(DropSource::Doc(&doc), FolderDrop::Tag(&review)));
|
||||
}
|
||||
// A link of the organization tree tags the document that it links.
|
||||
assert!(store.drop_folder_row(&link, FolderDrop::Tag(&later)));
|
||||
for (source, drop) in [
|
||||
(DropSource::Doc(&doc), FolderDrop::Tag("missing")),
|
||||
(DropSource::Doc(&doc), FolderDrop::Root),
|
||||
(DropSource::Doc("missing"), FolderDrop::Inside(&folder)),
|
||||
(DropSource::Row(&folder), FolderDrop::Tag(&review)),
|
||||
] {
|
||||
assert!(
|
||||
!store.can_drop_folder_row(source, drop),
|
||||
"{source:?} {drop:?}"
|
||||
);
|
||||
}
|
||||
|
||||
store.unbind_writer();
|
||||
let mut session = Arc::into_inner(session).unwrap().into_inner().unwrap();
|
||||
assert!(
|
||||
sqlite
|
||||
.flush_session_mutations(&mut session, None, 1_020)
|
||||
.await
|
||||
.unwrap()
|
||||
> 0
|
||||
);
|
||||
let file = sqlite.storage().path().to_owned();
|
||||
sqlite.close().await;
|
||||
|
||||
let (mut reopened, _) = crate::sqlite_loader::open_sqlite_workspace(file).unwrap();
|
||||
let links: Vec<_> = reopened
|
||||
.folder_rows
|
||||
.iter()
|
||||
.filter(|row| row.folder_type == "doc" && row.data == doc)
|
||||
.collect();
|
||||
assert_eq!(links.len(), 1);
|
||||
assert_eq!(links[0].parent_id.as_deref(), Some(folder.as_str()));
|
||||
assert_eq!(
|
||||
reopened.get_doc(&doc).unwrap().meta.tags,
|
||||
std::slice::from_ref(&review)
|
||||
);
|
||||
assert_eq!(reopened.get_doc(&linked).unwrap().meta.tags, [later]);
|
||||
let before = reopened.folder_rows.clone();
|
||||
assert!(
|
||||
!reopened.can_drop_folder_row(DropSource::Doc(&linked), FolderDrop::Inside(&folder))
|
||||
);
|
||||
assert!(!reopened.drop_folder_row(DropSource::Doc(&linked), FolderDrop::Inside(&folder)));
|
||||
assert!(!reopened.drop_folder_row(DropSource::Doc(&linked), FolderDrop::Tag(&review)));
|
||||
assert_eq!(reopened.folder_rows, before);
|
||||
assert!(
|
||||
reopened
|
||||
.get_doc(&linked)
|
||||
.unwrap()
|
||||
.meta
|
||||
.tags
|
||||
.iter()
|
||||
.all(|t| t != &review)
|
||||
);
|
||||
drop(reopened);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -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, SidebarRowKey, TreeGroup, nav_row, render_tree_rows},
|
||||
sidebar_tree::{DocPath, SidebarRowIndex, SidebarRowKey, TreeGroup, nav_row, render_tree_rows},
|
||||
split_view::DesktopRoute,
|
||||
workbench::DesktopShellView,
|
||||
};
|
||||
@@ -28,6 +28,8 @@ pub(crate) use tree_menu::{TreeMenu, TreeTarget, add_doc_or_folder};
|
||||
const TREE_TOP: f32 = 146.0;
|
||||
const FOOTER_HEIGHT: f32 = 42.0;
|
||||
const DRAWER_BREAKPOINT: f32 = 700.0;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
const SHOW_LINKED_DOC_KEY: &str = "affine.desktop.showLinkedDocInSidebar";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
|
||||
pub enum SidebarSection {
|
||||
@@ -48,6 +50,9 @@ pub struct SidebarState {
|
||||
pub expanded_folders: BTreeSet<String>,
|
||||
pub workspace_menu_open: bool,
|
||||
pub(crate) expanded_groups: BTreeSet<TreeGroup>,
|
||||
/// Expanded document rows. A document row shows the documents that it links to.
|
||||
pub(crate) expanded_docs: BTreeSet<DocPath>,
|
||||
show_linked_doc_in_sidebar: bool,
|
||||
pub(crate) hovered_row: Option<SidebarRowKey>,
|
||||
pub(crate) popup: Option<Popup>,
|
||||
}
|
||||
@@ -73,6 +78,8 @@ impl Default for SidebarState {
|
||||
]),
|
||||
workspace_menu_open: false,
|
||||
expanded_groups: BTreeSet::new(),
|
||||
expanded_docs: BTreeSet::new(),
|
||||
show_linked_doc_in_sidebar: stored_show_linked_doc(),
|
||||
hovered_row: None,
|
||||
popup: None,
|
||||
}
|
||||
@@ -105,12 +112,35 @@ impl SidebarState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether document rows show the documents that they link to. Web keeps the choice in
|
||||
/// `localStorage`.
|
||||
pub fn show_linked_doc_in_sidebar(&self) -> bool {
|
||||
self.show_linked_doc_in_sidebar
|
||||
}
|
||||
|
||||
pub fn set_show_linked_doc_in_sidebar(&mut self, show: bool) {
|
||||
self.show_linked_doc_in_sidebar = show;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
crate::wasm_entry::web_local_storage_set(
|
||||
SHOW_LINKED_DOC_KEY,
|
||||
if show { "true" } else { "false" },
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn dismiss_popups(&mut self) {
|
||||
self.workspace_menu_open = false;
|
||||
self.popup = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn stored_show_linked_doc() -> bool {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
if let Some(value) = crate::wasm_entry::web_local_storage_get(SHOW_LINKED_DOC_KEY) {
|
||||
return value != "false";
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn close_drawer(sidebar: &mut SidebarState, window: &Window) {
|
||||
if f32::from(window.viewport_size().width) < DRAWER_BREAKPOINT {
|
||||
sidebar.open = false;
|
||||
|
||||
@@ -692,6 +692,7 @@ fn sidebar_tree_menu_flips_up_and_scrolls_in_a_short_viewport() {
|
||||
let target = TreeTarget::Doc {
|
||||
id,
|
||||
folder_id: Some("folder".into()),
|
||||
path: None,
|
||||
};
|
||||
view.state.sidebar.popup = Some(Popup::Tree(TreeMenu::new(
|
||||
target,
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::{
|
||||
use crate::{
|
||||
DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, FOLDER_ICON_SVG, INFO_ICON_SVG, PLUS_ICON_SVG,
|
||||
TRASH_ICON_SVG,
|
||||
sidebar_tree::TreeGroup,
|
||||
sidebar_tree::{DocPath, TreeGroup},
|
||||
split_view::{DesktopRoute, DocViewMode},
|
||||
workbench::DesktopShellView,
|
||||
};
|
||||
@@ -37,6 +37,8 @@ pub(crate) enum TreeTarget {
|
||||
Doc {
|
||||
id: String,
|
||||
folder_id: Option<String>,
|
||||
/// The sidebar row of the document, which shows a new linked document.
|
||||
path: Option<DocPath>,
|
||||
},
|
||||
Folder(String),
|
||||
Group(DesktopRoute),
|
||||
@@ -99,9 +101,12 @@ pub(crate) fn add_doc_or_folder(
|
||||
close_drawer(&mut shell.state.sidebar, window);
|
||||
}
|
||||
}
|
||||
TreeTarget::Doc { id, .. } => {
|
||||
TreeTarget::Doc { id, path, .. } => {
|
||||
shell.sync_editors(cx);
|
||||
if let Some(child) = create_linked_page(&mut shell.state, id) {
|
||||
if let Some(path) = path {
|
||||
shell.state.sidebar.expanded_docs.insert(path.clone());
|
||||
}
|
||||
shell.state.open_doc_in_active_pane(&child);
|
||||
shell.sync_editors(cx);
|
||||
close_drawer(&mut shell.state.sidebar, window);
|
||||
@@ -605,7 +610,7 @@ impl Command {
|
||||
close_drawer(&mut shell.state.sidebar, window);
|
||||
}
|
||||
}
|
||||
(Self::RemovePlacement, TreeTarget::Doc { id, folder_id }) => {
|
||||
(Self::RemovePlacement, TreeTarget::Doc { id, folder_id, .. }) => {
|
||||
if let Some(folder) = folder_id {
|
||||
shell.state.store.remove_doc_from_folder(id, folder);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Pointer capture and drop indicators for the Organize tree.
|
||||
//! Pointer capture and drop indicators for drags of sidebar rows onto the Organize tree and
|
||||
//! onto tags.
|
||||
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use affine_client::organize::FolderDrop;
|
||||
use affine_client::organize::{DropSource, FolderDrop};
|
||||
use ui::{
|
||||
AnyElement, Bounds, Context, InteractiveElement, IntoElement, MouseButton, ParentElement,
|
||||
Pixels, Point, Styled, canvas, div, px,
|
||||
@@ -10,7 +11,9 @@ use ui::{
|
||||
|
||||
use super::{SidebarRow, SidebarRowIndex};
|
||||
use crate::{
|
||||
DesktopPalette, doc_store::DesktopDocStore, sidebar::SidebarSection,
|
||||
DesktopPalette,
|
||||
doc_store::{DesktopDocStore, DocViews},
|
||||
sidebar::SidebarSection,
|
||||
workbench::DesktopShellView,
|
||||
};
|
||||
|
||||
@@ -19,6 +22,25 @@ pub(crate) enum DropRow {
|
||||
Folder(String),
|
||||
Doc(String),
|
||||
Root,
|
||||
Tag(String),
|
||||
}
|
||||
|
||||
/// The row that a sidebar drag holds.
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub(crate) enum SidebarDragSource {
|
||||
/// A folder or a document link of the Organize tree, by its row ID.
|
||||
Row(String),
|
||||
/// A document row outside the Organize tree.
|
||||
Doc(String),
|
||||
}
|
||||
|
||||
impl<'a> From<&'a SidebarDragSource> for DropSource<'a> {
|
||||
fn from(source: &'a SidebarDragSource) -> Self {
|
||||
match source {
|
||||
SidebarDragSource::Row(id) => Self::Row(id),
|
||||
SidebarDragSource::Doc(id) => Self::Doc(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
@@ -38,6 +60,7 @@ impl DropTarget {
|
||||
pub(crate) fn placement(&self) -> FolderDrop<'_> {
|
||||
match (&self.row, self.edge) {
|
||||
(DropRow::Root, _) => FolderDrop::Root,
|
||||
(DropRow::Tag(id), _) => FolderDrop::Tag(id),
|
||||
(DropRow::Folder(id) | DropRow::Doc(id), Edge::Before) => FolderDrop::Before(id),
|
||||
(DropRow::Folder(id) | DropRow::Doc(id), Edge::After) => FolderDrop::After(id),
|
||||
(DropRow::Folder(id) | DropRow::Doc(id), Edge::Inside) => FolderDrop::Inside(id),
|
||||
@@ -47,7 +70,7 @@ impl DropTarget {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SidebarDrag {
|
||||
pub(crate) source: String,
|
||||
pub(crate) source: SidebarDragSource,
|
||||
workspace: String,
|
||||
origin: Point<Pixels>,
|
||||
pub(crate) active: bool,
|
||||
@@ -86,7 +109,7 @@ impl DragRows {
|
||||
let edge = match hit.row {
|
||||
DropRow::Folder(_) if fraction < 0.25 => Edge::Before,
|
||||
DropRow::Folder(_) if fraction > 0.75 => Edge::After,
|
||||
DropRow::Folder(_) | DropRow::Root => Edge::Inside,
|
||||
DropRow::Folder(_) | DropRow::Root | DropRow::Tag(_) => Edge::Inside,
|
||||
DropRow::Doc(_) if fraction < 0.5 => Edge::Before,
|
||||
DropRow::Doc(_) => Edge::After,
|
||||
};
|
||||
@@ -102,6 +125,7 @@ pub(super) fn drop_row(
|
||||
element: AnyElement,
|
||||
index: &SidebarRowIndex,
|
||||
store: &DesktopDocStore,
|
||||
views: &DocViews,
|
||||
palette: DesktopPalette,
|
||||
cx: &Context<DesktopShellView>,
|
||||
) -> AnyElement {
|
||||
@@ -109,41 +133,61 @@ pub(super) fn drop_row(
|
||||
return element;
|
||||
}
|
||||
let (row, source) = match row {
|
||||
SidebarRow::Folder { id, .. } => (DropRow::Folder(id.clone()), Some(id.clone())),
|
||||
SidebarRow::FolderDoc { link_id, .. } => {
|
||||
(DropRow::Doc(link_id.clone()), Some(link_id.clone()))
|
||||
SidebarRow::Folder { id, .. } => (
|
||||
Some(DropRow::Folder(id.clone())),
|
||||
Some(SidebarDragSource::Row(id.clone())),
|
||||
),
|
||||
SidebarRow::FolderDoc { link_id, .. } => (
|
||||
Some(DropRow::Doc(link_id.clone())),
|
||||
Some(SidebarDragSource::Row(link_id.clone())),
|
||||
),
|
||||
SidebarRow::Section(SidebarSection::Folders) => (Some(DropRow::Root), None),
|
||||
SidebarRow::Tag(index) => (
|
||||
views
|
||||
.tags
|
||||
.get(*index)
|
||||
.map(|tag| DropRow::Tag(tag.definition.id.clone())),
|
||||
None,
|
||||
),
|
||||
SidebarRow::Favorite(doc_id) | SidebarRow::GroupDoc { doc_id, .. } => {
|
||||
(None, Some(SidebarDragSource::Doc(doc_id.clone())))
|
||||
}
|
||||
SidebarRow::LinkedDoc { path, .. } => {
|
||||
(None, Some(SidebarDragSource::Doc(path.doc_id().to_owned())))
|
||||
}
|
||||
SidebarRow::Section(SidebarSection::Folders) => (DropRow::Root, None),
|
||||
_ => return element,
|
||||
};
|
||||
let edge = index
|
||||
.drag
|
||||
.as_ref()
|
||||
.and_then(|drag| drag.target.as_ref())
|
||||
.filter(|target| target.row == row)
|
||||
.filter(|target| Some(&target.row) == row.as_ref())
|
||||
.map(|target| target.edge);
|
||||
let top = if row == DropRow::Root { 4.0 } else { 0.0 };
|
||||
let hits = index.drag_rows.clone();
|
||||
let mut wrapper = div().w_full().flex_shrink(0.0).child(element).child(
|
||||
canvas(
|
||||
|_, _, _| (),
|
||||
move |bounds, (), window, _| {
|
||||
let clipped = bounds.intersect(&window.content_mask().bounds);
|
||||
if clipped.size.width > px(0.0) && clipped.size.height > px(0.0) {
|
||||
hits.0.borrow_mut().push(Hit {
|
||||
bounds,
|
||||
clipped,
|
||||
row,
|
||||
});
|
||||
}
|
||||
},
|
||||
)
|
||||
.absolute()
|
||||
.top(px(top))
|
||||
.bottom(px(0.0))
|
||||
.left(px(0.0))
|
||||
.right(px(0.0)),
|
||||
);
|
||||
let top = if row == Some(DropRow::Root) { 4.0 } else { 0.0 };
|
||||
let mut wrapper = div().w_full().flex_shrink(0.0).child(element);
|
||||
if let Some(row) = row {
|
||||
let hits = index.drag_rows.clone();
|
||||
wrapper = wrapper.child(
|
||||
canvas(
|
||||
|_, _, _| (),
|
||||
move |bounds, (), window, _| {
|
||||
let clipped = bounds.intersect(&window.content_mask().bounds);
|
||||
if clipped.size.width > px(0.0) && clipped.size.height > px(0.0) {
|
||||
hits.0.borrow_mut().push(Hit {
|
||||
bounds,
|
||||
clipped,
|
||||
row,
|
||||
});
|
||||
}
|
||||
},
|
||||
)
|
||||
.absolute()
|
||||
.top(px(top))
|
||||
.bottom(px(0.0))
|
||||
.left(px(0.0))
|
||||
.right(px(0.0)),
|
||||
);
|
||||
}
|
||||
if let Some(source) = source {
|
||||
wrapper = wrapper.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Linked documents below the document rows of the sidebar tree.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use super::RowRef;
|
||||
use crate::{doc_store::DesktopDocStore, sidebar::SidebarState};
|
||||
|
||||
/// The placement of the document row at the top of a linked document chain.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) enum DocRoot {
|
||||
Favorites,
|
||||
/// A document link of the organization tree, by its row ID.
|
||||
Folder(String),
|
||||
Collection(String),
|
||||
Tag(String),
|
||||
}
|
||||
|
||||
/// A document row of the sidebar tree: its placement and the documents from the top of the
|
||||
/// placement down to the row. Each document row keeps its own expansion state.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) struct DocPath {
|
||||
root: DocRoot,
|
||||
docs: Vec<String>,
|
||||
}
|
||||
|
||||
impl DocPath {
|
||||
pub(crate) fn new(root: DocRoot, doc_id: &str) -> Self {
|
||||
Self {
|
||||
root,
|
||||
docs: vec![doc_id.to_owned()],
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn doc_id(&self) -> &str {
|
||||
self.docs.last().map_or("", String::as_str)
|
||||
}
|
||||
|
||||
fn child(&self, doc_id: &str) -> Self {
|
||||
let mut docs = Vec::with_capacity(self.docs.len() + 1);
|
||||
docs.extend_from_slice(&self.docs);
|
||||
docs.push(doc_id.to_owned());
|
||||
Self {
|
||||
root: self.root.clone(),
|
||||
docs,
|
||||
}
|
||||
}
|
||||
|
||||
/// A document that also occurs above itself in the chain shows no children, so that
|
||||
/// documents which link to each other give a finite tree.
|
||||
pub(crate) fn repeats_ancestor(&self) -> bool {
|
||||
self.docs
|
||||
.split_last()
|
||||
.is_some_and(|(doc, ancestors)| ancestors.contains(doc))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for DocPath {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match &self.root {
|
||||
DocRoot::Favorites => f.write_str("fav")?,
|
||||
DocRoot::Folder(link) => write!(f, "fdoc:{link}")?,
|
||||
DocRoot::Collection(id) => write!(f, "col:{id}")?,
|
||||
DocRoot::Tag(id) => write!(f, "tag:{id}")?,
|
||||
}
|
||||
for doc in &self.docs {
|
||||
write!(f, "/{doc}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the row at `path` shows the expand control.
|
||||
pub(crate) fn can_expand(sidebar: &SidebarState, path: &DocPath) -> bool {
|
||||
sidebar.show_linked_doc_in_sidebar() && !path.repeats_ancestor()
|
||||
}
|
||||
|
||||
/// The documents that `doc_id` links to and that are not in the trash, once each in link order.
|
||||
fn linked_children<'a>(store: &'a DesktopDocStore, doc_id: &str) -> Vec<&'a str> {
|
||||
let mut children: Vec<&str> = Vec::new();
|
||||
for child in store
|
||||
.get_doc(doc_id)
|
||||
.into_iter()
|
||||
.flat_map(|entry| &entry.meta.outgoing_refs)
|
||||
{
|
||||
if !children.contains(&child.as_str())
|
||||
&& store.get_doc(child).is_some_and(|doc| !doc.meta.trashed)
|
||||
{
|
||||
children.push(child);
|
||||
}
|
||||
}
|
||||
children
|
||||
}
|
||||
|
||||
/// Linked document rows below the document rows of one row build.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct LinkedRows(pub(super) Vec<(DocPath, u16)>);
|
||||
|
||||
impl LinkedRows {
|
||||
/// Push the rows below the document row at `path` when that row is expanded. `depth` is
|
||||
/// the depth of the row at `path`.
|
||||
pub(super) fn push_children(
|
||||
&mut self,
|
||||
rows: &mut Vec<RowRef>,
|
||||
sidebar: &SidebarState,
|
||||
store: &DesktopDocStore,
|
||||
root: impl FnOnce() -> DocRoot,
|
||||
doc_id: &str,
|
||||
depth: u16,
|
||||
) {
|
||||
if sidebar.expanded_docs.is_empty() || !sidebar.show_linked_doc_in_sidebar() {
|
||||
return;
|
||||
}
|
||||
let path = DocPath::new(root(), doc_id);
|
||||
if sidebar.expanded_docs.contains(&path) {
|
||||
self.push_expanded(rows, sidebar, store, &path, depth);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_expanded(
|
||||
&mut self,
|
||||
rows: &mut Vec<RowRef>,
|
||||
sidebar: &SidebarState,
|
||||
store: &DesktopDocStore,
|
||||
path: &DocPath,
|
||||
depth: u16,
|
||||
) {
|
||||
let start = rows.len();
|
||||
for child in linked_children(store, path.doc_id()) {
|
||||
let child = path.child(child);
|
||||
rows.push(RowRef::Linked(self.0.len() as u32));
|
||||
self.0.push((child.clone(), depth + 1));
|
||||
if !child.repeats_ancestor() && sidebar.expanded_docs.contains(&child) {
|
||||
self.push_expanded(rows, sidebar, store, &child, depth + 1);
|
||||
}
|
||||
}
|
||||
if rows.len() == start {
|
||||
rows.push(RowRef::Empty("No linked docs", depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,12 @@ use crate::{
|
||||
};
|
||||
|
||||
mod drag;
|
||||
mod linked;
|
||||
mod rows;
|
||||
pub(crate) use drag::SidebarDrag;
|
||||
use drag::{DragRows, drop_row};
|
||||
use linked::LinkedRows;
|
||||
pub(crate) use linked::{DocPath, DocRoot};
|
||||
pub(crate) use rows::nav_row;
|
||||
use rows::render_row;
|
||||
|
||||
@@ -160,6 +163,10 @@ pub(crate) enum SidebarRow {
|
||||
group: TreeGroup,
|
||||
doc_id: String,
|
||||
},
|
||||
LinkedDoc {
|
||||
path: DocPath,
|
||||
depth: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -182,6 +189,7 @@ pub(crate) enum SidebarRowKey {
|
||||
tag_id: String,
|
||||
doc_id: String,
|
||||
},
|
||||
LinkedDoc(DocPath),
|
||||
}
|
||||
|
||||
impl SidebarRowKey {
|
||||
@@ -212,6 +220,7 @@ impl SidebarRowKey {
|
||||
"sidebar-tag-doc",
|
||||
ui::hash(&(tag_id.as_str(), doc_id.as_str())),
|
||||
),
|
||||
Self::LinkedDoc(path) => ("sidebar-linked-doc", ui::hash(path)),
|
||||
};
|
||||
ui::ElementId::NamedInteger(ui::SharedString::new_static(kind), hash)
|
||||
}
|
||||
@@ -244,6 +253,8 @@ enum RowRef {
|
||||
tag_idx: u32,
|
||||
doc_idx: u32,
|
||||
},
|
||||
/// A linked document row, by its index in [`LinkedRows`].
|
||||
Linked(u32),
|
||||
}
|
||||
|
||||
impl RowRef {
|
||||
@@ -266,6 +277,8 @@ struct RowKey {
|
||||
sections: BTreeSet<SidebarSection>,
|
||||
folders: BTreeSet<String>,
|
||||
groups: BTreeSet<TreeGroup>,
|
||||
docs: BTreeSet<DocPath>,
|
||||
show_linked: bool,
|
||||
workspace_id: String,
|
||||
}
|
||||
|
||||
@@ -274,6 +287,7 @@ struct RowKey {
|
||||
pub struct SidebarRowIndex {
|
||||
key: Option<RowKey>,
|
||||
rows: Vec<RowRef>,
|
||||
linked: LinkedRows,
|
||||
list: Option<VirtualList>,
|
||||
viewport_height: f32,
|
||||
builds: u64,
|
||||
@@ -325,12 +339,15 @@ impl SidebarRowIndex {
|
||||
&& k.sections == sidebar.expanded_sections
|
||||
&& k.folders == sidebar.expanded_folders
|
||||
&& k.groups == sidebar.expanded_groups
|
||||
&& k.docs == sidebar.expanded_docs
|
||||
&& k.show_linked == sidebar.show_linked_doc_in_sidebar()
|
||||
&& k.workspace_id == store.active_workspace().id
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
self.rows.clear();
|
||||
build_row_refs(&mut self.rows, sidebar, store, views);
|
||||
self.linked.0.clear();
|
||||
build_row_refs(&mut self.rows, &mut self.linked, sidebar, store, views);
|
||||
self.list = Some(VirtualList::variable(
|
||||
self.rows.iter().map(RowRef::extent).collect(),
|
||||
));
|
||||
@@ -341,6 +358,8 @@ impl SidebarRowIndex {
|
||||
key.sections.clone_from(&sidebar.expanded_sections);
|
||||
key.folders.clone_from(&sidebar.expanded_folders);
|
||||
key.groups.clone_from(&sidebar.expanded_groups);
|
||||
key.docs.clone_from(&sidebar.expanded_docs);
|
||||
key.show_linked = sidebar.show_linked_doc_in_sidebar();
|
||||
key.workspace_id.clone_from(&store.active_workspace().id);
|
||||
}
|
||||
None => {
|
||||
@@ -350,6 +369,8 @@ impl SidebarRowIndex {
|
||||
sections: sidebar.expanded_sections.clone(),
|
||||
folders: sidebar.expanded_folders.clone(),
|
||||
groups: sidebar.expanded_groups.clone(),
|
||||
docs: sidebar.expanded_docs.clone(),
|
||||
show_linked: sidebar.show_linked_doc_in_sidebar(),
|
||||
workspace_id: store.active_workspace().id.clone(),
|
||||
});
|
||||
}
|
||||
@@ -411,16 +432,25 @@ impl<'a> ExpandedGroupsLookup<'a> {
|
||||
|
||||
fn build_row_refs(
|
||||
rows: &mut Vec<RowRef>,
|
||||
linked: &mut LinkedRows,
|
||||
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());
|
||||
build_row_refs_with_lookup(
|
||||
rows,
|
||||
linked,
|
||||
sidebar,
|
||||
store,
|
||||
views,
|
||||
expanded_groups.as_ref(),
|
||||
);
|
||||
}
|
||||
|
||||
fn build_row_refs_with_lookup(
|
||||
rows: &mut Vec<RowRef>,
|
||||
linked: &mut LinkedRows,
|
||||
sidebar: &SidebarState,
|
||||
store: &DesktopDocStore,
|
||||
views: &DocViews,
|
||||
@@ -441,9 +471,14 @@ fn build_row_refs_with_lookup(
|
||||
match section {
|
||||
SidebarSection::Favorites => {
|
||||
rows.reserve(views.favorites.len());
|
||||
rows.extend((0..views.favorites.len() as u32).map(RowRef::Favorite));
|
||||
for (index, doc_id) in views.favorites.iter().enumerate() {
|
||||
rows.push(RowRef::Favorite(index as u32));
|
||||
linked.push_children(rows, sidebar, store, || DocRoot::Favorites, doc_id, 0);
|
||||
}
|
||||
}
|
||||
SidebarSection::Folders => {
|
||||
push_folder_row_refs(rows, linked, &views.folders, sidebar, store)
|
||||
}
|
||||
SidebarSection::Folders => push_folder_row_refs(rows, &views.folders, sidebar),
|
||||
SidebarSection::Tags => {
|
||||
for (index, tag) in views.tags.iter().enumerate() {
|
||||
rows.push(RowRef::Tag(index as u32));
|
||||
@@ -455,10 +490,20 @@ fn build_row_refs_with_lookup(
|
||||
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 {
|
||||
tag_idx: index as u32,
|
||||
doc_idx,
|
||||
}));
|
||||
for (doc_idx, doc_id) in tag.docs.iter().enumerate() {
|
||||
rows.push(RowRef::TagDoc {
|
||||
tag_idx: index as u32,
|
||||
doc_idx: doc_idx as u32,
|
||||
});
|
||||
linked.push_children(
|
||||
rows,
|
||||
sidebar,
|
||||
store,
|
||||
|| DocRoot::Tag(tag.definition.id.clone()),
|
||||
doc_id,
|
||||
1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -482,6 +527,14 @@ fn build_row_refs_with_lookup(
|
||||
col_idx: index as u32,
|
||||
visible_idx: visible_idx as u32,
|
||||
});
|
||||
linked.push_children(
|
||||
rows,
|
||||
sidebar,
|
||||
store,
|
||||
|| DocRoot::Collection(collection.id.clone()),
|
||||
doc_id,
|
||||
1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -496,7 +549,13 @@ fn build_row_refs_with_lookup(
|
||||
}
|
||||
}
|
||||
|
||||
fn push_folder_row_refs(rows: &mut Vec<RowRef>, tree: &SidebarFolderTree, sidebar: &SidebarState) {
|
||||
fn push_folder_row_refs(
|
||||
rows: &mut Vec<RowRef>,
|
||||
linked: &mut LinkedRows,
|
||||
tree: &SidebarFolderTree,
|
||||
sidebar: &SidebarState,
|
||||
store: &DesktopDocStore,
|
||||
) {
|
||||
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)));
|
||||
@@ -523,11 +582,21 @@ fn push_folder_row_refs(rows: &mut Vec<RowRef>, tree: &SidebarFolderTree, sideba
|
||||
}
|
||||
}
|
||||
}
|
||||
FolderChild::Doc { .. } => rows.push(RowRef::FolderDoc {
|
||||
parent_row,
|
||||
child_idx,
|
||||
depth,
|
||||
}),
|
||||
FolderChild::Doc { link, doc } => {
|
||||
rows.push(RowRef::FolderDoc {
|
||||
parent_row,
|
||||
child_idx,
|
||||
depth,
|
||||
});
|
||||
linked.push_children(
|
||||
rows,
|
||||
sidebar,
|
||||
store,
|
||||
|| DocRoot::Folder(link.clone()),
|
||||
doc,
|
||||
depth,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -564,6 +633,7 @@ fn resolve_folder_child<'a>(
|
||||
fn materialize_row(
|
||||
row_ref: &RowRef,
|
||||
rows: &[RowRef],
|
||||
linked: &LinkedRows,
|
||||
views: &DocViews,
|
||||
store: &DesktopDocStore,
|
||||
) -> Option<SidebarRow> {
|
||||
@@ -630,16 +700,23 @@ fn materialize_row(
|
||||
doc_id: doc_id.clone(),
|
||||
})
|
||||
}
|
||||
RowRef::Linked(index) => {
|
||||
let (path, depth) = linked.0.get(*index as usize)?;
|
||||
Some(SidebarRow::LinkedDoc {
|
||||
path: path.clone(),
|
||||
depth: usize::from(*depth),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
let (mut refs, mut linked) = (Vec::new(), LinkedRows::default());
|
||||
build_row_refs(&mut refs, &mut linked, sidebar, store, &views);
|
||||
refs.iter()
|
||||
.filter_map(|row_ref| materialize_row(row_ref, &refs, &views, store))
|
||||
.filter_map(|row_ref| materialize_row(row_ref, &refs, &linked, &views, store))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -674,11 +751,11 @@ pub(crate) fn render_tree_rows(
|
||||
col = col.child(div().w_full().h(px(window.leading_spacer - ROW_GAP)));
|
||||
}
|
||||
for row_ref in &index.rows[window.visible_range.clone()] {
|
||||
let Some(row) = materialize_row(row_ref, &index.rows, &views, store) else {
|
||||
let Some(row) = materialize_row(row_ref, &index.rows, &index.linked, &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));
|
||||
col = col.child(drop_row(&row, element, index, store, &views, palette, cx));
|
||||
}
|
||||
if window.visible_range.end < index.rows.len() {
|
||||
col = col.child(div().w_full().h(px(window.trailing_spacer - ROW_GAP)));
|
||||
@@ -1298,7 +1375,13 @@ mod tests {
|
||||
// 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);
|
||||
build_row_refs(
|
||||
&mut refs,
|
||||
&mut LinkedRows::default(),
|
||||
&sidebar,
|
||||
&store,
|
||||
&views,
|
||||
);
|
||||
assert_eq!(refs.len(), 5 + group_count * 2);
|
||||
|
||||
// 2. Mixed expanded set: even tags + odd collections expanded.
|
||||
@@ -1318,10 +1401,23 @@ mod tests {
|
||||
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));
|
||||
build_row_refs_with_lookup(
|
||||
&mut probed_refs,
|
||||
&mut LinkedRows::default(),
|
||||
&sidebar,
|
||||
&store,
|
||||
&views,
|
||||
Some(&lookup),
|
||||
);
|
||||
assert_eq!(lookup.probes.get(), group_count * 2);
|
||||
refs.clear();
|
||||
build_row_refs(&mut refs, &sidebar, &store, &views);
|
||||
build_row_refs(
|
||||
&mut refs,
|
||||
&mut LinkedRows::default(),
|
||||
&sidebar,
|
||||
&store,
|
||||
&views,
|
||||
);
|
||||
assert_eq!(refs, probed_refs);
|
||||
assert_eq!(refs.len(), 5 + group_count * 2 + group_count);
|
||||
let tag0_pos = refs
|
||||
@@ -1355,6 +1451,7 @@ mod tests {
|
||||
probed_refs.clear();
|
||||
build_row_refs_with_lookup(
|
||||
&mut probed_refs,
|
||||
&mut LinkedRows::default(),
|
||||
&sidebar,
|
||||
&store,
|
||||
&views,
|
||||
@@ -1362,7 +1459,13 @@ mod tests {
|
||||
);
|
||||
assert_eq!(full_lookup.probes.get(), group_count * 2);
|
||||
refs.clear();
|
||||
build_row_refs(&mut refs, &sidebar, &store, &views);
|
||||
build_row_refs(
|
||||
&mut refs,
|
||||
&mut LinkedRows::default(),
|
||||
&sidebar,
|
||||
&store,
|
||||
&views,
|
||||
);
|
||||
assert_eq!(refs, probed_refs);
|
||||
assert_eq!(refs.len(), 5 + group_count * 4);
|
||||
let col0_pos = refs
|
||||
|
||||
@@ -7,8 +7,8 @@ use ui::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
RowOpenMode, SPLIT_BREAKPOINT, SidebarRow, SidebarRowKey, TreeGroup, click_open_mode,
|
||||
open_sidebar_route,
|
||||
DocPath, DocRoot, RowOpenMode, SPLIT_BREAKPOINT, SidebarRow, SidebarRowKey, TreeGroup,
|
||||
click_open_mode, linked::can_expand, open_sidebar_route,
|
||||
};
|
||||
use crate::{
|
||||
CHEVRON_DOWN_SVG, CHEVRON_RIGHT_SVG, COLLECTION_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt,
|
||||
@@ -77,6 +77,7 @@ pub(super) fn render_row(
|
||||
ui::snap_id!("desktop.sidebar.fav.{doc_id}"),
|
||||
store.get_doc(doc_id).map(|doc| &doc.meta),
|
||||
None,
|
||||
DocPath::new(DocRoot::Favorites, doc_id),
|
||||
0,
|
||||
),
|
||||
SidebarRow::FolderDoc {
|
||||
@@ -96,16 +97,18 @@ pub(super) fn render_row(
|
||||
),
|
||||
store.get_doc(doc_id).map(|doc| &doc.meta),
|
||||
folder_id.clone(),
|
||||
DocPath::new(DocRoot::Folder(link_id.clone()), doc_id),
|
||||
*depth,
|
||||
),
|
||||
SidebarRow::GroupDoc { group, doc_id } => {
|
||||
let (key, snap_id) = match group {
|
||||
let (key, snap_id, root) = 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}"),
|
||||
DocRoot::Collection(id.clone()),
|
||||
),
|
||||
TreeGroup::Tag(tag) => (
|
||||
SidebarRowKey::TagDoc {
|
||||
@@ -113,6 +116,7 @@ pub(super) fn render_row(
|
||||
doc_id: doc_id.clone(),
|
||||
},
|
||||
ui::snap_id!("desktop.sidebar.tag_doc.{tag}.{doc_id}"),
|
||||
DocRoot::Tag(tag.clone()),
|
||||
),
|
||||
};
|
||||
presentation.document(
|
||||
@@ -120,9 +124,18 @@ pub(super) fn render_row(
|
||||
snap_id,
|
||||
store.get_doc(doc_id).map(|doc| &doc.meta),
|
||||
None,
|
||||
DocPath::new(root, doc_id),
|
||||
1,
|
||||
)
|
||||
}
|
||||
SidebarRow::LinkedDoc { path, depth } => presentation.document(
|
||||
SidebarRowKey::LinkedDoc(path.clone()),
|
||||
ui::snap_id!("desktop.sidebar.linked_doc.{path}"),
|
||||
store.get_doc(path.doc_id()).map(|doc| &doc.meta),
|
||||
None,
|
||||
path.clone(),
|
||||
*depth,
|
||||
),
|
||||
SidebarRow::Folder { id, depth } => {
|
||||
let key = SidebarRowKey::Folder(id.clone());
|
||||
let name = views.folders.name(id).unwrap_or_default().to_owned();
|
||||
@@ -379,6 +392,7 @@ impl RowPresentation<'_, '_> {
|
||||
snap_id: ui::SnapshotId,
|
||||
doc: Option<&DesktopDocMeta>,
|
||||
folder_id: Option<String>,
|
||||
path: DocPath,
|
||||
depth: usize,
|
||||
) -> ui::AnyElement {
|
||||
let Some(doc) = doc else {
|
||||
@@ -392,19 +406,41 @@ impl RowPresentation<'_, '_> {
|
||||
DOC_ICON_SVG
|
||||
};
|
||||
let doc_id = doc.id.clone();
|
||||
let expandable = can_expand(self.sidebar, &path);
|
||||
let expanded = expandable && self.sidebar.expanded_docs.contains(&path);
|
||||
let target = TreeTarget::Doc {
|
||||
id: doc_id.clone(),
|
||||
folder_id,
|
||||
path: Some(path.clone()),
|
||||
};
|
||||
let row = self.node(
|
||||
&key,
|
||||
snap_id,
|
||||
NodeIcon::Svg(icon),
|
||||
doc.title.clone(),
|
||||
depth,
|
||||
None,
|
||||
let disclosure = div()
|
||||
.id("disclosure")
|
||||
.size(px(20.0))
|
||||
.flex_shrink(0.0)
|
||||
.child(self.node_icon(&key, NodeIcon::Svg(icon), expandable.then_some(expanded)))
|
||||
.when(expandable, |el| {
|
||||
el.on_click(self.cx.listener(move |this, _, _, cx| {
|
||||
if !this.state.sidebar.expanded_docs.remove(&path) {
|
||||
// The links of a document that is not loaded yet are not known.
|
||||
let _ = this.state.store.ensure_doc_hydrated(path.doc_id());
|
||||
this.state.sidebar.expanded_docs.insert(path.clone());
|
||||
}
|
||||
this.state.sidebar.dismiss_popups();
|
||||
cx.stop_propagation();
|
||||
cx.notify();
|
||||
}))
|
||||
});
|
||||
let palette = self.palette;
|
||||
let row = row_shell(
|
||||
key.element_id(),
|
||||
matches!(self.active_route, DesktopRoute::Doc(id) if id == &doc_id),
|
||||
);
|
||||
palette.hover_color,
|
||||
)
|
||||
.snapshot(snap_id, Some("desktop.sidebar"))
|
||||
.pl(px(indent(depth)))
|
||||
.child(disclosure)
|
||||
.child(title_label(doc.title.clone(), palette));
|
||||
let row = self.hover_row(row, key.clone());
|
||||
let row = self.bind_route_open(row, DesktopRoute::Doc(doc_id), true);
|
||||
self.actions(row, &key, target, !self.readonly)
|
||||
.into_any_element()
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
//! Sidebar drags of document rows onto Organize folders and tags, and linked document rows
|
||||
//! below document rows.
|
||||
|
||||
use affine_desktop::{DesktopAppState, DesktopShellView, register_desktop_fonts};
|
||||
use ui::{
|
||||
AnyWindowHandle, AppContext, Application, ApplicationHandle, Bounds, HeadlessPlatform,
|
||||
HeadlessWindow, Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent,
|
||||
MouseUpEvent, PlatformInput, Point, WindowBounds, WindowHandle, WindowOptions, point, px, size,
|
||||
};
|
||||
use ui_tokens::ThemeMode;
|
||||
|
||||
struct Shell {
|
||||
app: ApplicationHandle,
|
||||
handle: WindowHandle<DesktopShellView>,
|
||||
window: HeadlessWindow,
|
||||
}
|
||||
|
||||
impl Shell {
|
||||
fn new() -> Self {
|
||||
let platform = HeadlessPlatform::new(1280, 1200, 1.0);
|
||||
let app = Application::with_platform(platform.clone()).run_embedded(|_| {});
|
||||
let handle = app.update(|cx| {
|
||||
register_desktop_fonts(cx).expect("desktop fonts");
|
||||
cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
|
||||
point(px(0.0), px(0.0)),
|
||||
size(px(1280.0), px(1200.0)),
|
||||
))),
|
||||
..WindowOptions::default()
|
||||
},
|
||||
|_, cx| {
|
||||
let state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02");
|
||||
cx.new(|cx| DesktopShellView::new(state, cx))
|
||||
},
|
||||
)
|
||||
.expect("desktop window")
|
||||
});
|
||||
let window = platform.windows().remove(0);
|
||||
window.request_frame();
|
||||
Self {
|
||||
app,
|
||||
handle,
|
||||
window,
|
||||
}
|
||||
}
|
||||
|
||||
fn update<T>(
|
||||
&self,
|
||||
f: impl FnOnce(&mut DesktopShellView, &mut ui::Window, &mut ui::Context<DesktopShellView>) -> T,
|
||||
) -> T {
|
||||
self.app
|
||||
.update(|cx| self.handle.update(cx, f).expect("desktop view"))
|
||||
}
|
||||
|
||||
fn row(&self, id: &str) -> Option<ui::SnapshotRect> {
|
||||
self.update(|_, window, _| {
|
||||
window
|
||||
.frame_snapshot()
|
||||
.elements
|
||||
.get(id)
|
||||
.map(|element| element.bounds)
|
||||
})
|
||||
}
|
||||
|
||||
fn center(&self, id: &str) -> Point<ui::Pixels> {
|
||||
let bounds = self
|
||||
.row(id)
|
||||
.unwrap_or_else(|| panic!("{id} is not mounted"));
|
||||
point(
|
||||
px(bounds.x + bounds.width / 2.0),
|
||||
px(bounds.y + bounds.height / 2.0),
|
||||
)
|
||||
}
|
||||
|
||||
/// Click the icon of a tree row, which expands or collapses the row.
|
||||
fn toggle(&self, id: &str, depth: f32) {
|
||||
let bounds = self
|
||||
.row(id)
|
||||
.unwrap_or_else(|| panic!("{id} is not mounted"));
|
||||
let at = point(
|
||||
px(bounds.x + 6.0 + depth * 20.0 + 10.0),
|
||||
px(bounds.y + bounds.height / 2.0),
|
||||
);
|
||||
self.window.simulate_click(at);
|
||||
self.window.request_frame();
|
||||
}
|
||||
|
||||
fn drag(&self, from: &str, to: Point<ui::Pixels>, cancel: bool) {
|
||||
let modifiers = Modifiers::default();
|
||||
self.window
|
||||
.dispatch_input(PlatformInput::MouseDown(MouseDownEvent {
|
||||
button: MouseButton::Left,
|
||||
position: self.center(from),
|
||||
modifiers,
|
||||
click_count: 1,
|
||||
first_mouse: false,
|
||||
}));
|
||||
self.window
|
||||
.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent {
|
||||
position: to,
|
||||
pressed_button: Some(MouseButton::Left),
|
||||
modifiers,
|
||||
}));
|
||||
self.window.request_frame();
|
||||
if cancel {
|
||||
self.app.update(|cx| {
|
||||
AnyWindowHandle::from(self.handle)
|
||||
.update(cx, |_, window, cx| {
|
||||
window.dispatch_keystroke(Keystroke::parse("escape").expect("key"), cx);
|
||||
})
|
||||
.expect("desktop window");
|
||||
});
|
||||
}
|
||||
self.window
|
||||
.dispatch_input(PlatformInput::MouseUp(MouseUpEvent {
|
||||
button: MouseButton::Left,
|
||||
position: to,
|
||||
modifiers,
|
||||
click_count: 1,
|
||||
}));
|
||||
self.window.request_frame();
|
||||
}
|
||||
|
||||
fn links(&self, doc: &str) -> Vec<Option<String>> {
|
||||
self.update(|view, _, _| {
|
||||
view.state
|
||||
.store
|
||||
.folder_rows
|
||||
.iter()
|
||||
.filter(|row| row.folder_type == "doc" && row.data == doc)
|
||||
.map(|row| row.parent_id.clone())
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
fn tags(&self, doc: &str) -> Vec<String> {
|
||||
self.update(|view, _, _| {
|
||||
view.state
|
||||
.store
|
||||
.get_doc(doc)
|
||||
.expect("doc")
|
||||
.meta
|
||||
.tags
|
||||
.clone()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_rows_drop_onto_folders_and_tags_and_cancel_without_writes() {
|
||||
let app = Shell::new();
|
||||
let source = "desktop.sidebar.fav.doc-sync";
|
||||
let folder = "desktop.sidebar.folder.f-specs";
|
||||
let tag = "desktop.sidebar.tag.design";
|
||||
let initial = (app.links("doc-sync"), app.tags("doc-sync"));
|
||||
|
||||
// Escape, a release outside the sidebar, and a drop onto a row that takes no document
|
||||
// write nothing.
|
||||
for (to, cancel) in [
|
||||
(app.center(folder), true),
|
||||
(app.center(tag), true),
|
||||
(point(px(900.0), px(400.0)), false),
|
||||
(app.center("desktop.sidebar.sec.folders"), false),
|
||||
] {
|
||||
app.drag(source, to, cancel);
|
||||
assert_eq!((app.links("doc-sync"), app.tags("doc-sync")), initial);
|
||||
}
|
||||
|
||||
// A favorite document dropped inside a folder gets one link there, also when dropped again.
|
||||
for _ in 0..2 {
|
||||
app.drag(source, app.center(folder), false);
|
||||
let links = app.links("doc-sync");
|
||||
assert_eq!(
|
||||
links
|
||||
.iter()
|
||||
.filter(|p| p.as_deref() == Some("f-specs"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(links.len(), initial.0.len() + 1);
|
||||
}
|
||||
assert!(app.row("desktop.sidebar.fdoc.f-specs.doc-sync").is_some());
|
||||
|
||||
// A document dropped onto a tag gets the tag once.
|
||||
for _ in 0..2 {
|
||||
app.drag(source, app.center(tag), false);
|
||||
let tags = app.tags("doc-sync");
|
||||
assert_eq!(tags.iter().filter(|t| *t == "design").count(), 1);
|
||||
assert_eq!(tags.len(), initial.1.len() + 1);
|
||||
}
|
||||
|
||||
// A document link of the Organize tree also tags the document that it links.
|
||||
app.drag(
|
||||
"desktop.sidebar.fdoc.f-specs.doc-board",
|
||||
app.center("desktop.sidebar.tag.release"),
|
||||
false,
|
||||
);
|
||||
assert!(app.tags("doc-board").iter().any(|t| t == "release"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_rows_expand_linked_documents_by_path_and_follow_the_setting() {
|
||||
let app = Shell::new();
|
||||
let arch = "desktop.sidebar.fav.doc-arch";
|
||||
let sync = "desktop.sidebar.linked_doc.fav/doc-arch/doc-sync";
|
||||
let board = "desktop.sidebar.linked_doc.fav/doc-arch/doc-board";
|
||||
let back = "desktop.sidebar.linked_doc.fav/doc-arch/doc-sync/doc-arch";
|
||||
let mounted = |ids: &[&str]| {
|
||||
ids.iter()
|
||||
.map(|id| app.row(id).is_some())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
assert_eq!(mounted(&[sync, board]), [false, false]);
|
||||
app.toggle(arch, 0.0);
|
||||
assert_eq!(mounted(&[sync, board]), [true, true]);
|
||||
assert!(app.row(sync).unwrap().y < app.row(board).unwrap().y);
|
||||
|
||||
// A linked document that links back to an ancestor shows as a leaf.
|
||||
app.toggle(sync, 1.0);
|
||||
assert!(app.row(back).is_some());
|
||||
app.toggle(back, 2.0);
|
||||
assert!(
|
||||
app.row("desktop.sidebar.linked_doc.fav/doc-arch/doc-sync/doc-arch/doc-sync")
|
||||
.is_none()
|
||||
);
|
||||
|
||||
// The same document in another section keeps its own expansion state.
|
||||
assert!(
|
||||
app.row("desktop.sidebar.linked_doc.fdoc:link-arch-1/doc-arch/doc-sync")
|
||||
.is_none()
|
||||
);
|
||||
|
||||
// With the setting off, document rows show no linked documents and keep their state.
|
||||
app.update(|view, _, cx| {
|
||||
view.state.sidebar.set_show_linked_doc_in_sidebar(false);
|
||||
cx.notify();
|
||||
});
|
||||
app.window.request_frame();
|
||||
assert_eq!(mounted(&[sync, board, back]), [false, false, false]);
|
||||
app.update(|view, _, cx| {
|
||||
assert!(!view.state.sidebar.show_linked_doc_in_sidebar());
|
||||
view.state.sidebar.set_show_linked_doc_in_sidebar(true);
|
||||
cx.notify();
|
||||
});
|
||||
app.window.request_frame();
|
||||
assert_eq!(mounted(&[sync, board, back]), [true, true, true]);
|
||||
|
||||
app.toggle(arch, 0.0);
|
||||
assert_eq!(mounted(&[sync, board, back]), [false, false, false]);
|
||||
}
|
||||
Reference in new issue
Block a user