From 5384a7074e370e2112ab7d29eedd5ce5af63ff84 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Fri, 4 Dec 2026 16:33:29 +0900 Subject: [PATCH] feat(desktop): add collection editor with docs and rules modes Add the `Pages | Rules` collection editor modal, rule filters (including local calendar day `Created`/`Updated` evaluation via `LocalZone`, viewport-clamped scrollable filter menus with full keyboard navigation, and `Reset` input state synchronization), and `NavigationEdit::UpdateCollection` CRDT persistence. --- .../workspace_db/share_destinations/mod.rs | 217 ++++++- .../share_destinations/records.rs | 85 ++- packages/frontend/client/src/domain.rs | 584 +++++++++++++++++- .../frontend/desktop/src/doc_store/mod.rs | 54 +- .../desktop/src/doc_store/navigation.rs | 184 ++++-- .../frontend/desktop/src/doc_store/views.rs | 4 + .../frontend/desktop/src/sidebar/tree_menu.rs | 24 +- packages/frontend/desktop/src/state/mod.rs | 59 +- .../collection_editor/filter_bar.rs | 458 ++++++++++++++ .../collection_editor/filter_menu.rs | 328 ++++++++++ .../docs_explorer/collection_editor/mod.rs | 541 ++++++++++++++++ .../collection_editor/pages_mode.rs | 166 +++++ .../collection_editor/rules_mode.rs | 441 +++++++++++++ .../docs_explorer/collection_editor/tests.rs | 570 +++++++++++++++++ .../src/views_extra/docs_explorer/header.rs | 64 +- .../src/views_extra/docs_explorer/mod.rs | 39 +- .../{tag_search.rs => text_field.rs} | 101 ++- .../desktop/src/views_extra/journals/mod.rs | 2 + .../desktop/src/views_extra/journals/tz.rs | 18 +- .../desktop/src/workbench/interaction.rs | 1 + .../frontend/desktop/src/workbench/mod.rs | 12 +- 21 files changed, 3765 insertions(+), 187 deletions(-) create mode 100644 packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_bar.rs create mode 100644 packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_menu.rs create mode 100644 packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/mod.rs create mode 100644 packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/pages_mode.rs create mode 100644 packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/rules_mode.rs create mode 100644 packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/tests.rs rename packages/frontend/desktop/src/views_extra/docs_explorer/{tag_search.rs => text_field.rs} (80%) diff --git a/packages/common/store/src/workspace_db/share_destinations/mod.rs b/packages/common/store/src/workspace_db/share_destinations/mod.rs index 4bf0f5b378..d37ccae03c 100644 --- a/packages/common/store/src/workspace_db/share_destinations/mod.rs +++ b/packages/common/store/src/workspace_db/share_destinations/mod.rs @@ -9,8 +9,8 @@ use y_octo::{Any, DocSession, SessionReadValue, SessionValue, TypePath, TypeTarg mod records; use self::records::{ - ListEdit, ListInit, collection_record, edit_list, merge_collection, prepare_list_init, - tag_record, + CollectionChange, ListEdit, ListInit, collection_record, edit_list, merge_collection, + prepare_list_init, tag_record, }; #[cfg(test)] use super::PageIdSource; @@ -46,10 +46,18 @@ pub struct WorkspaceCollection { /// A local edit to workspace tag or collection metadata. pub enum NavigationEdit { CreateTag(WorkspaceTag), - RenameTag { id: String, name: String }, + RenameTag { + id: String, + name: String, + }, DeleteTag(String), CreateCollection(WorkspaceCollection), - RenameCollection { id: String, name: String }, + RenameCollection { + id: String, + name: String, + }, + /// Replace the name, `allowList` and `rules.filters` of the collection with the same ID. + UpdateCollection(WorkspaceCollection), DeleteCollection(String), } @@ -138,30 +146,10 @@ impl WorkspaceRootDoc { groups[*position].push(item); } } - let collections = groups.into_iter().filter_map(|group| { - let merged = merge_collection(root, group)?; - let item = merged.winner; - let filters = field(root, item, "rules") - .and_then(|rules| field(root, &rules, "filters")) - .and_then(|filters| array_values(root, filters).ok().flatten()) - .unwrap_or_default() - .iter() - .map(|filter| CollectionFilter { - kind: field_string(root, filter, "type").unwrap_or_default(), - key: field_string(root, filter, "key").unwrap_or_default(), - method: field_string(root, filter, "method").unwrap_or_default(), - value: field_string(root, filter, "value"), - }) - .collect(); - Some(WorkspaceCollection { - id: field_string(root, item, "id")?, - name: field_string(root, item, "name") - .or_else(|| field_string(root, item, "title")) - .unwrap_or_default(), - allow_list: merged.allow_list, - filters, - }) - }); + let collections = groups + .into_iter() + .filter_map(|group| merge_collection(root, group)) + .filter_map(|merged| read_collection(root, merged.winner, merged.allow_list)); Ok(Some(collections.collect())) } @@ -228,7 +216,8 @@ impl WorkspaceRootDoc { NavigationEdit::RenameTag { id, .. } | NavigationEdit::DeleteTag(id) => { ("meta", TAGS, id) } - NavigationEdit::CreateCollection(collection) => { + NavigationEdit::CreateCollection(collection) + | NavigationEdit::UpdateCollection(collection) => { ("setting", COLLECTIONS, &collection.id) } NavigationEdit::RenameCollection { id, .. } | NavigationEdit::DeleteCollection(id) => { @@ -255,14 +244,26 @@ impl WorkspaceRootDoc { { return Ok(None); } - let Some(record) = - merge_collection(&self.root, matches.iter().map(|(_, item)| *item)) + let Some(value) = + self.replace_collection(&matches, CollectionChange::Rename(name), now_ms)? else { return Ok(None); }; - let next_date = - now_ms.max(record.update_date.map_or(1, |date| date.saturating_add(1))); - ListEdit::Replace(record.into_value(&self.root, Some((name, next_date)))?) + ListEdit::Replace(value) + } + NavigationEdit::UpdateCollection(collection) => { + if let [(_, item)] = matches.as_slice() + && let Some(merged) = merge_collection(&self.root, [*item]) + && read_collection(&self.root, item, merged.allow_list).as_ref() + == Some(collection) + { + return Ok(None); + } + let change = CollectionChange::Update(collection); + let Some(value) = self.replace_collection(&matches, change, now_ms)? else { + return Ok(None); + }; + ListEdit::Replace(value) } NavigationEdit::DeleteTag(_) | NavigationEdit::DeleteCollection(_) => ListEdit::Remove, }; @@ -291,6 +292,24 @@ impl WorkspaceRootDoc { }) } + /// Merge the records of one collection into one record with `change` and a newer + /// `updateDate`, so that a concurrent replica keeps the newest change. + fn replace_collection( + &self, + matches: &[(usize, &SessionReadValue)], + change: CollectionChange<'_>, + now_ms: i64, + ) -> StoreResult> { + let Some(record) = merge_collection(&self.root, matches.iter().map(|(_, item)| *item)) + else { + return Ok(None); + }; + let next_date = now_ms.max(record.update_date.map_or(1, |date| date.saturating_add(1))); + record + .into_value(&self.root, Some((change, next_date))) + .map(Some) + } + /// Validate and apply `tag_ids` (`meta.pages[doc].tags`) and `collection_id` /// (`setting.collections[id].allowList`) atomically in a single transaction, matching /// `0.27.5` `ImportClipperService` (`import.ts:173-193, 339-355`). @@ -426,6 +445,34 @@ fn matching_items<'a>( .collect() } +/// Project one collection record with its merged `allowList`. +fn read_collection( + root: &DocSession<()>, + item: &SessionReadValue, + allow_list: Vec, +) -> Option { + let filters = field(root, item, "rules") + .and_then(|rules| field(root, &rules, "filters")) + .and_then(|filters| array_values(root, filters).ok().flatten()) + .unwrap_or_default() + .iter() + .map(|filter| CollectionFilter { + kind: field_string(root, filter, "type").unwrap_or_default(), + key: field_string(root, filter, "key").unwrap_or_default(), + method: field_string(root, filter, "method").unwrap_or_default(), + value: field_string(root, filter, "value"), + }) + .collect(); + Some(WorkspaceCollection { + id: field_string(root, item, "id")?, + name: field_string(root, item, "name") + .or_else(|| field_string(root, item, "title")) + .unwrap_or_default(), + allow_list, + filters, + }) +} + fn y_error(error: impl std::fmt::Display) -> StoreError { StoreError::YOcto(error.to_string()) } @@ -799,6 +846,108 @@ mod tests { ); } + #[test] + fn collection_update_writes_javascript_rules_and_keeps_other_fields_after_reopen() { + let mut doc = WorkspaceRootDoc::new("ws", 1); + doc.initialize_meta().unwrap(); + // Use the object shape of the JavaScript CollectionStore with two extra fields. + doc.with_tx(|root| { + let setting = TypeTarget::from( + root.ensure_root("setting", y_octo::YTypeKind::Map) + .map_err(y_error)?, + ); + let entry = object([ + ("id", Any::String("c".into())), + ("name", Any::String("Original".into())), + ("custom", Any::String("kept".into())), + ( + "rules", + object([ + ("filters", Any::Array(vec![])), + ("groupBy", Any::String("kept".into())), + ]), + ), + ("allowList", Any::Array(vec![Any::String("old".into())])), + ]); + root.map_set( + &setting, + "collections".into(), + SessionValue::Array(vec![SessionValue::Any(entry)]), + ) + .map(drop) + .map_err(y_error) + }) + .unwrap(); + let filter = |key: &str, method: &str, value: Option<&str>| CollectionFilter { + kind: "system".into(), + key: key.into(), + method: method.into(), + value: value.map(Into::into), + }; + let updated = WorkspaceCollection { + id: "c".into(), + name: "Edited".into(), + allow_list: vec!["page-two".into(), "page-one".into()], + filters: vec![ + filter("tags", "include-any-of", Some("t1,t2")), + filter("docPrimaryMode", "is", Some("edgeless")), + filter("tags", "is-not-empty", None), + ], + }; + let edit = NavigationEdit::UpdateCollection(updated.clone()); + assert!(doc.edit_workspace_navigation(&edit, 5).unwrap().is_some()); + assert!(doc.edit_workspace_navigation(&edit, 6).unwrap().is_none()); + assert_plain_collection_rows(&doc, &[Some(5)]); + + let cold = + WorkspaceRootDoc::from_update_v1("ws", 2, &doc.encode_update_v1().unwrap()).unwrap(); + assert_eq!( + cold.navigation_collections().unwrap().unwrap(), + std::slice::from_ref(&updated) + ); + let rows = cold + .root + .read_array(&TypeTarget::Path( + TypePath::root("setting").key("collections"), + )) + .unwrap(); + let [SessionReadValue::Any(Any::Object(fields))] = rows.as_slice() else { + panic!("expected one plain collection object, got {rows:?}"); + }; + assert_eq!(fields.get("custom"), Some(&Any::String("kept".into()))); + let Some(Any::Object(rules)) = fields.get("rules") else { + panic!("expected a rules object"); + }; + assert_eq!(rules.get("groupBy"), Some(&Any::String("kept".into()))); + let Some(Any::Array(filters)) = rules.get("filters") else { + panic!("expected a filter array"); + }; + let keys: Vec> = filters + .iter() + .map(|filter| { + let Any::Object(filter) = filter else { + panic!("expected a filter object"); + }; + let mut keys: Vec<_> = filter.keys().map(String::as_str).collect(); + keys.sort_unstable(); + keys + }) + .collect(); + assert_eq!( + keys, + [ + vec!["key", "method", "type", "value"], + vec!["key", "method", "type", "value"], + vec!["key", "method", "type"], + ] + ); + // A removed member stays removed, because the update replaces `allowList`. + assert_eq!( + cold.collection_allow_list("c").unwrap(), + Some(updated.allow_list) + ); + } + #[test] fn concurrent_collection_rename_and_share_merge_after_reopen() { use crate::workspace_db::PageIdSource; diff --git a/packages/common/store/src/workspace_db/share_destinations/records.rs b/packages/common/store/src/workspace_db/share_destinations/records.rs index 199bdd1777..482cf0fd56 100644 --- a/packages/common/store/src/workspace_db/share_destinations/records.rs +++ b/packages/common/store/src/workspace_db/share_destinations/records.rs @@ -2,7 +2,9 @@ use std::collections::BTreeSet; use y_octo::{Any, DocSession, SessionReadValue, SessionValue, TypePath, TypeTarget, YTypeKind}; -use super::{WorkspaceCollection, WorkspaceTag, array_values, as_string, field, y_error}; +use super::{ + CollectionFilter, WorkspaceCollection, WorkspaceTag, array_values, as_string, field, y_error, +}; use crate::error::StoreResult; pub(super) fn object(entries: [(&str, Any); N]) -> Any { @@ -29,40 +31,49 @@ pub(super) fn tag_record(tag: &WorkspaceTag, now_ms: i64) -> SessionValue { ) } +/// The `rules.filters` array of a collection, with the `FilterParams` fields of `0.27.5`. +fn filters_value(filters: &[CollectionFilter]) -> Any { + Any::Array( + filters + .iter() + .map(|filter| { + let mut fields = y_octo::AHashMap::from_iter([ + ("type".into(), Any::String(filter.kind.clone())), + ("key".into(), Any::String(filter.key.clone())), + ("method".into(), Any::String(filter.method.clone())), + ]); + if let Some(value) = &filter.value { + fields.insert("value".into(), Any::String(value.clone())); + } + Any::Object(Box::new(fields)) + }) + .collect(), + ) +} + +fn allow_list_value(ids: &[String]) -> Any { + Any::Array(ids.iter().cloned().map(Any::String).collect()) +} + pub(super) fn collection_record(collection: &WorkspaceCollection) -> SessionValue { - let filters = collection - .filters - .iter() - .map(|filter| { - let mut fields = y_octo::AHashMap::from_iter([ - ("type".into(), Any::String(filter.kind.clone())), - ("key".into(), Any::String(filter.key.clone())), - ("method".into(), Any::String(filter.method.clone())), - ]); - if let Some(value) = &filter.value { - fields.insert("value".into(), Any::String(value.clone())); - } - Any::Object(Box::new(fields)) - }) - .collect(); SessionValue::Any(object([ ("id", Any::String(collection.id.clone())), ("name", Any::String(collection.name.clone())), - ("rules", object([("filters", Any::Array(filters))])), ( - "allowList", - Any::Array( - collection - .allow_list - .iter() - .cloned() - .map(Any::String) - .collect(), - ), + "rules", + object([("filters", filters_value(&collection.filters))]), ), + ("allowList", allow_list_value(&collection.allow_list)), ])) } +/// A change that replaces the merged record of a collection. +pub(super) enum CollectionChange<'a> { + Rename(&'a str), + /// Replace `name`, `allowList` and `rules.filters`, and keep all other fields. + Update(&'a WorkspaceCollection), +} + pub(super) struct MergedCollection<'a> { pub(super) winner: &'a SessionReadValue, pub(super) update_date: Option, @@ -112,18 +123,28 @@ impl MergedCollection<'_> { pub(super) fn into_value( self, root: &DocSession<()>, - rename: Option<(&str, i64)>, + change: Option<(CollectionChange<'_>, i64)>, ) -> StoreResult { let Any::Object(mut fields) = plain_value(root, self.winner.clone(), Any::DEFAULT_MAX_DEPTH)? else { return Err(y_error("collection is not an object")); }; - fields.insert( - "allowList".into(), - Any::Array(self.allow_list.into_iter().map(Any::String).collect()), - ); - if let Some((name, date)) = rename { + fields.insert("allowList".into(), allow_list_value(&self.allow_list)); + if let Some((change, date)) = change { + let name = match change { + CollectionChange::Rename(name) => name, + CollectionChange::Update(collection) => { + fields.insert("allowList".into(), allow_list_value(&collection.allow_list)); + let mut rules = match fields.remove("rules") { + Some(Any::Object(rules)) => *rules, + _ => Default::default(), + }; + rules.insert("filters".into(), filters_value(&collection.filters)); + fields.insert("rules".into(), Any::Object(Box::new(rules))); + &collection.name + } + }; fields.insert("name".into(), Any::String(name.into())); fields.insert("updateDate".into(), Any::Float64((date as f64).into())); } diff --git a/packages/frontend/client/src/domain.rs b/packages/frontend/client/src/domain.rs index 0aa0851a89..d1ab21d87f 100644 --- a/packages/frontend/client/src/domain.rs +++ b/packages/frontend/client/src/domain.rs @@ -2,7 +2,7 @@ //! `Tag`, `Favorite`, `Journal`, `Trash`) backed by a shared `Arc>`. use std::{ - collections::BTreeMap, + collections::{BTreeMap, BTreeSet}, sync::{Arc, Mutex, MutexGuard}, }; @@ -60,6 +60,346 @@ pub enum CollectionRule { ModeIs(String), TitleContains(String), IncludeDocIds(Vec), + /// One `rules.filters` entry, kept as it is stored. + Filter(FilterRule), +} + +/// One `rules.filters` entry of a collection (`FilterParams`). +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct FilterParams { + #[serde(rename = "type")] + pub kind: String, + pub key: String, + pub method: String, + pub value: Option, +} + +/// A calendar date as days since `1970-01-01`. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct CivilDate(i32); + +impl CivilDate { + pub fn from_ymd(year: i32, month: u32, day: u32) -> Option { + let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + let days = [ + 31, + if leap { 29 } else { 28 }, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31, + ]; + if !(1..=12).contains(&month) || day == 0 || day > days[month as usize - 1] { + return None; + } + // Days from civil, after Howard Hinnant. + let year = if month <= 2 { year - 1 } else { year }; + let era = year.div_euclid(400); + let year_of_era = year - era * 400; + let month_index = (month as i32 + 9) % 12; + let day_of_year = (153 * month_index + 2) / 5 + day as i32 - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + Some(Self(era * 146_097 + day_of_era - 719_468)) + } + + /// Parse `YYYY-MM-DD`. + pub fn parse(text: &str) -> Option { + let bytes = text.as_bytes(); + if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { + return None; + } + let number = |range: std::ops::Range| { + text.get(range) + .filter(|part| part.bytes().all(|b| b.is_ascii_digit())) + .and_then(|part| part.parse().ok()) + }; + Self::from_ymd(number(0..4)? as i32, number(5..7)?, number(8..10)?) + } + + /// The UTC date of a Unix time in milliseconds. + pub fn from_unix_ms(ms: i64) -> Self { + Self(ms.div_euclid(86_400_000) as i32) + } + + pub fn ymd(self) -> (i32, u32, u32) { + let days = self.0 + 719_468; + let era = days.div_euclid(146_097); + let day_of_era = days - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_index = (5 * day_of_year + 2) / 153; + let day = (day_of_year - (153 * month_index + 2) / 5 + 1) as u32; + let month = if month_index < 10 { + month_index + 3 + } else { + month_index - 9 + } as u32; + (year_of_era + era * 400 + i32::from(month <= 2), month, day) + } + + pub fn add_days(self, days: i32) -> Self { + Self(self.0 + days) + } + + /// The first day of the method's relative range: weeks start on Sunday. + fn range_start(self, method: &str) -> Option { + let (year, month, _) = self.ymd(); + match method { + "last-3-days" => Some(self.add_days(-3)), + "last-7-days" => Some(self.add_days(-7)), + "last-15-days" => Some(self.add_days(-15)), + "last-30-days" => Some(self.add_days(-30)), + // 1970-01-01 was a Thursday. + "this-week" => Some(self.add_days(-(self.0 + 4).rem_euclid(7))), + "this-month" => Self::from_ymd(year, month, 1), + "this-quarter" => Self::from_ymd(year, (month - 1) / 3 * 3 + 1, 1), + "this-year" => Self::from_ymd(year, 1, 1), + _ => None, + } + } +} + +impl std::fmt::Display for CivilDate { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (year, month, day) = self.ymd(); + write!(f, "{year:04}-{month:02}-{day:02}") + } +} + +/// The local time zone that splits times into calendar days, as `dayjs` does in the web +/// client. The default is UTC. +#[derive(Clone, Default)] +pub struct LocalCalendar(Option i32 + Send + Sync>>); + +impl LocalCalendar { + /// A calendar whose `offset_minutes` tells how many minutes the local time runs ahead of + /// UTC at a Unix time in milliseconds. + pub fn new(offset_minutes: impl Fn(i64) -> i32 + Send + Sync + 'static) -> Self { + Self(Some(Arc::new(offset_minutes))) + } + + /// The local date of a Unix time in milliseconds. + pub fn date(&self, ms: i64) -> CivilDate { + let offset = self + .0 + .as_ref() + .map_or(0, |offset_minutes| offset_minutes(ms)); + CivilDate::from_unix_ms(ms.saturating_add(i64::from(offset) * 60_000)) + } +} + +impl std::fmt::Debug for LocalCalendar { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(if self.0.is_some() { + "LocalCalendar(local)" + } else { + "LocalCalendar(UTC)" + }) + } +} + +impl PartialEq for LocalCalendar { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (a, b) => a.is_none() && b.is_none(), + } + } +} + +impl Eq for LocalCalendar {} + +/// Workspace facts that filters read besides the document itself. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct FilterScope { + /// The current local date. Relative date methods match nothing without it. + pub today: Option, + /// The zone that turns document times into local dates. + pub calendar: LocalCalendar, + /// Defined tag IDs, or `None` when the workspace has no tag table and every tag counts. + pub tags: Option>, + /// Creation times in Unix milliseconds by document ID. Documents not in this map were + /// created today. + pub created: BTreeMap, +} + +/// A stored filter with the workspace facts it reads. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct FilterRule { + pub params: FilterParams, + #[serde(skip)] + pub scope: Arc, +} + +/// The document fields that collection filters read. +#[derive(Clone, Copy, Debug)] +pub struct DocFacts<'a> { + pub id: &'a str, + pub title: &'a str, + pub tags: &'a [String], + /// `page` or `edgeless`. + pub mode: &'a str, + /// `standard` or `fullWidth`, or `None` for the default width. + pub page_width: Option<&'a str>, + pub favorite: bool, + pub journal: bool, + pub trashed: bool, + /// Creation time in Unix milliseconds. + pub created: Option, + /// Time of the last change in Unix milliseconds. + pub updated: Option, +} + +impl FilterRule { + /// Whether the document matches the filter, or `None` for a filter that this client does + /// not evaluate (workspace properties, sharing, and unknown keys or methods). + pub fn matches(&self, doc: &DocFacts<'_>) -> Option { + let FilterParams { + kind, key, method, .. + } = &self.params; + let value = self.params.value.as_deref(); + if kind != "system" { + return None; + } + let flag = || match value { + Some("true") => Some(true), + Some("false") => Some(false), + _ => None, + }; + match (key.as_str(), method.as_str()) { + ("tags", _) => self.tags_match(method, doc), + ("createdAt", _) => self.date_match( + doc.created + .or_else(|| self.scope.created.get(doc.id).copied()) + .map(|ms| self.scope.calendar.date(ms)) + .or(self.scope.today), + ), + ("updatedAt", _) => self.date_match(doc.updated.map(|ms| self.scope.calendar.date(ms))), + ("favorite", "is") => Some(doc.favorite == flag()?), + ("trash", "is") => Some(doc.trashed == flag()?), + ("journal", "is") => Some(doc.journal == (value == Some("true"))), + ("journal", "is-not") => Some(doc.journal != (value == Some("true"))), + ("docPrimaryMode", "is") => Some(Some(doc.mode) == value), + ("docPrimaryMode", "is-not") => Some(Some(doc.mode) != value), + ("pageWidth", "is") => Some(Some(doc.page_width.unwrap_or("standard")) == value), + ("pageWidth", "is-not") => Some(Some(doc.page_width.unwrap_or("standard")) != value), + ("title", "match") => Some( + doc.title + .to_lowercase() + .contains(&value.unwrap_or_default().to_lowercase()), + ), + _ => None, + } + } + + fn tags_match(&self, method: &str, doc: &DocFacts<'_>) -> Option { + let defined = |id: &str| { + self.scope + .tags + .as_ref() + .is_none_or(|tags| tags.contains(id)) + }; + let has = |id: &str| doc.tags.iter().any(|tag| tag == id); + let ids: Vec<&str> = self + .params + .value + .as_deref() + .unwrap_or_default() + .split(',') + .filter(|id| !id.is_empty()) + .filter(|id| defined(id)) + .collect(); + let any = || ids.iter().any(|id| has(id)); + let all = || ids.iter().all(|id| has(id)); + match method { + // Missing or deleted tags match no document. + "include-all" | "include-any-of" | "not-include-all" | "not-include-any-of" + if ids.is_empty() => + { + Some(false) + } + "include-all" => Some(all()), + "include-any-of" => Some(any()), + "not-include-all" => Some(!all()), + "not-include-any-of" => Some(!any()), + "is-not-empty" => Some(doc.tags.iter().any(|tag| defined(tag))), + "is-empty" => Some(!doc.tags.iter().any(|tag| defined(tag))), + _ => None, + } + } + + fn date_match(&self, date: Option) -> Option { + let method = self.params.method.as_str(); + let values: Vec = self + .params + .value + .as_deref() + .unwrap_or_default() + .split(',') + .filter_map(CivilDate::parse) + .collect(); + match (method, values.as_slice()) { + ("is-empty", _) => Some(date.is_none()), + ("is-not-empty", _) => Some(date.is_some()), + ("between", [from, to, ..]) => { + Some(date.is_some_and(|date| *from <= date && date <= *to)) + } + ("after", [from, ..]) => Some(date.is_some_and(|date| *from <= date)), + ("before", [to, ..]) => Some(date.is_some_and(|date| date <= *to)), + _ => { + let start = self.scope.today?.range_start(method)?; + Some(date.is_some_and(|date| start <= date)) + } + } + } +} + +impl CollectionRule { + /// The result of one primary filter rule, or `None` for an allow list or an + /// unsupported filter. + fn filter_result(&self, doc: &DocFacts<'_>) -> Option { + match self { + Self::HasTag(tag) => Some(doc.tags.contains(tag)), + Self::ModeIs(mode) => Some(doc.mode == mode), + Self::TitleContains(needle) => { + Some(doc.title.to_lowercase().contains(&needle.to_lowercase())) + } + Self::IncludeDocIds(_) => None, + Self::Filter(rule) => rule.matches(doc), + } + } +} + +/// Whether a collection holds a document, as `CollectionService` decides: a document that is +/// not in Trash is in the collection when its ID is in an allow list or when it matches all +/// filters. A collection without filters matches only its allow list. When the first filter is +/// unsupported, no document matches the filters, and later unsupported filters are ignored. +pub fn collection_holds(rules: &[CollectionRule], doc: &DocFacts<'_>) -> bool { + if doc.trashed { + return false; + } + if rules + .iter() + .any(|rule| matches!(rule, CollectionRule::IncludeDocIds(ids) if ids.iter().any(|id| id == doc.id))) + { + return true; + } + let mut filters = rules + .iter() + .filter(|rule| !matches!(rule, CollectionRule::IncludeDocIds(_))) + .peekable(); + let Some(first) = filters.next() else { + return false; + }; + first.filter_result(doc) == Some(true) + && filters.all(|rule| rule.filter_result(doc) != Some(false)) } /// User-defined collection grouping documents by explicit IDs and filter rules. @@ -395,6 +735,21 @@ fn matches_collection(doc: &DocModel, rules: &[CollectionRule]) -> bool { doc.title.to_lowercase().contains(&needle.to_lowercase()) } CollectionRule::IncludeDocIds(ids) => ids.iter().any(|id| id == &doc.id), + CollectionRule::Filter(rule) => { + let facts = DocFacts { + id: &doc.id, + title: &doc.title, + tags: &doc.tags, + mode: &doc.mode, + page_width: None, + favorite: doc.is_favorite, + journal: doc.journal_date.is_some(), + trashed: doc.trashed, + created: Some(doc.create_date_ms), + updated: Some(doc.updated_date_ms.unwrap_or(doc.create_date_ms)), + }; + rule.matches(&facts) == Some(true) + } }) } @@ -409,6 +764,233 @@ mod tests { use super::*; use crate::doc_directory::StoreBackedDocDirectory; + #[test] + fn civil_dates_round_trip_and_start_relative_ranges() { + for text in ["1969-12-31", "1970-01-01", "2000-02-29", "2026-12-03"] { + let date = CivilDate::parse(text).unwrap(); + assert_eq!(date.to_string(), text); + } + for text in ["2026-02-29", "2026-13-01", "2026-1-01", "x026-01-01"] { + assert_eq!(CivilDate::parse(text), None, "{text}"); + } + assert_eq!( + CivilDate::from_unix_ms(-1), + CivilDate::parse("1969-12-31").unwrap() + ); + // 2026-12-03 is a Thursday. + let today = CivilDate::parse("2026-12-03").unwrap(); + for (method, start) in [ + ("last-3-days", "2026-11-30"), + ("last-30-days", "2026-11-03"), + ("this-week", "2026-11-29"), + ("this-month", "2026-12-01"), + ("this-quarter", "2026-10-01"), + ("this-year", "2026-01-01"), + ] { + assert_eq!(today.range_start(method).unwrap().to_string(), start); + } + } + + #[test] + fn collection_filters_match_like_the_web_client() { + let date = |text| CivilDate::parse(text); + // Noon UTC of a date. + let noon = + |text| date(text).map(|date: CivilDate| i64::from(date.0) * 86_400_000 + 43_200_000); + let scope = Arc::new(FilterScope { + today: date("2026-12-03"), + calendar: LocalCalendar::default(), + tags: Some(BTreeSet::from(["a".into(), "b".into(), "c".into()])), + created: BTreeMap::from([("doc".into(), noon("2026-11-01").unwrap())]), + }); + let tags = vec!["a".to_owned(), "b".to_owned(), "deleted".to_owned()]; + let doc = DocFacts { + id: "doc", + title: "Weekly Standup", + tags: &tags, + mode: "edgeless", + page_width: None, + favorite: true, + journal: false, + trashed: false, + created: None, + updated: noon("2026-12-02"), + }; + let rule = |key: &str, method: &str, value: Option<&str>| FilterRule { + params: FilterParams { + kind: "system".into(), + key: key.into(), + method: method.into(), + value: value.map(Into::into), + }, + scope: scope.clone(), + }; + for (key, method, value, expected) in [ + ("tags", "include-all", Some("a,b"), Some(true)), + ("tags", "include-all", Some("a,c"), Some(false)), + ("tags", "include-all", Some("a,missing"), Some(true)), + ("tags", "include-all", Some("missing"), Some(false)), + ("tags", "include-any-of", Some("c,b"), Some(true)), + ("tags", "not-include-all", Some("a,c"), Some(true)), + ("tags", "not-include-any-of", Some("c"), Some(true)), + ("tags", "not-include-any-of", Some(""), Some(false)), + ("tags", "is-not-empty", None, Some(true)), + ("tags", "is-empty", None, Some(false)), + ("createdAt", "after", Some("2026-11-01"), Some(true)), + ("createdAt", "before", Some("2026-10-31"), Some(false)), + ("createdAt", "last-30-days", None, Some(false)), + ("createdAt", "this-quarter", None, Some(true)), + ( + "updatedAt", + "between", + Some("2026-12-01,2026-12-02"), + Some(true), + ), + ("updatedAt", "this-week", None, Some(true)), + ("updatedAt", "is-empty", None, Some(false)), + ("favorite", "is", Some("true"), Some(true)), + ("favorite", "is", Some("maybe"), None), + ("journal", "is", Some("false"), Some(true)), + ("journal", "is-not", Some("false"), Some(false)), + ("docPrimaryMode", "is", Some("edgeless"), Some(true)), + ("docPrimaryMode", "is-not", Some("edgeless"), Some(false)), + ("pageWidth", "is", Some("standard"), Some(true)), + ("pageWidth", "is-not", Some("fullWidth"), Some(true)), + ("title", "match", Some("standup"), Some(true)), + ("shared", "is", Some("true"), None), + ("tags", "unknown", None, None), + ] { + assert_eq!( + rule(key, method, value).matches(&doc), + expected, + "{key} {method} {value:?}" + ); + } + + let filter = |key, method, value| CollectionRule::Filter(rule(key, method, value)); + let unsupported = || filter("shared", "is", Some("true")); + let edgeless = || filter("docPrimaryMode", "is", Some("edgeless")); + let journal = || filter("journal", "is", Some("true")); + let listed = || CollectionRule::IncludeDocIds(vec!["doc".into()]); + for (rules, expected) in [ + (vec![], false), + (vec![listed()], true), + (vec![edgeless()], true), + (vec![edgeless(), journal()], false), + (vec![journal(), listed()], true), + (vec![edgeless(), unsupported()], true), + (vec![unsupported(), edgeless()], false), + ] { + assert_eq!(collection_holds(&rules, &doc), expected, "{rules:?}"); + } + let trashed = DocFacts { + trashed: true, + ..doc + }; + assert!(!collection_holds(&[listed()], &trashed)); + } + + #[test] + fn date_filters_compare_local_calendar_days_around_midnight() { + // 2026-12-03 14:30Z and 15:30Z are 23:30 and 00:30 in Tokyo (UTC+9); 2026-12-04 07:30Z + // and 08:30Z are 23:30 and 00:30 in Los Angeles (UTC-8). + let tokyo = LocalCalendar::new(|_| 9 * 60); + let los_angeles = LocalCalendar::new(|_| -8 * 60); + let date = |text| CivilDate::parse(text); + for (calendar, today, before, after) in [ + (&tokyo, "2026-12-04", 1_796_308_200_000, 1_796_311_800_000), + ( + &los_angeles, + "2026-12-04", + 1_796_369_400_000, + 1_796_373_000_000, + ), + ] { + assert_eq!(calendar.date(before), date("2026-12-03").unwrap()); + assert_eq!(calendar.date(after), date("2026-12-04").unwrap()); + let scope = Arc::new(FilterScope { + today: date(today), + calendar: calendar.clone(), + ..FilterScope::default() + }); + let rule = |key: &str, method: &str, value: Option<&str>| FilterRule { + params: FilterParams { + kind: "system".into(), + key: key.into(), + method: method.into(), + value: value.map(Into::into), + }, + scope: scope.clone(), + }; + for (method, value, matches_before, matches_after) in [ + ("after", Some("2026-12-04"), false, true), + ("before", Some("2026-12-03"), true, false), + ("between", Some("2026-12-04,2026-12-04"), false, true), + ("between", Some("2026-12-03,2026-12-03"), true, false), + ("last-3-days", None, true, true), + ("this-month", None, true, true), + ] { + for (key, created, updated) in [ + ("createdAt", Some(before), None), + ("updatedAt", None, Some(before)), + ] { + let shifted = |ms: Option| ms.map(|_| after); + for (ms, expected) in [ + ((created, updated), matches_before), + ((shifted(created), shifted(updated)), matches_after), + ] { + let doc = DocFacts { + id: "doc", + title: "", + tags: &[], + mode: "page", + page_width: None, + favorite: false, + journal: false, + trashed: false, + created: ms.0, + updated: ms.1, + }; + assert_eq!( + rule(key, method, value).matches(&doc), + Some(expected), + "{calendar:?} {key} {method} {value:?} {ms:?}" + ); + } + } + } + } + // A creation time from the workspace pages also reads in the local zone. + let scope = Arc::new(FilterScope { + today: date("2026-12-04"), + calendar: tokyo, + created: BTreeMap::from([("doc".into(), 1_796_311_800_000)]), + ..FilterScope::default() + }); + let rule = FilterRule { + params: FilterParams { + kind: "system".into(), + key: "createdAt".into(), + method: "after".into(), + value: Some("2026-12-04".into()), + }, + scope, + }; + let doc = DocFacts { + id: "doc", + title: "", + tags: &[], + mode: "page", + page_width: None, + favorite: false, + journal: false, + trashed: false, + created: None, + updated: None, + }; + assert_eq!(rule.matches(&doc), Some(true)); + } + #[test] fn domain_service_projects_docs_folders_collections_favorites_journals_and_trash() { let mut db = WorkspaceDb::new("ws-dom", "u1", 1); diff --git a/packages/frontend/desktop/src/doc_store/mod.rs b/packages/frontend/desktop/src/doc_store/mod.rs index e938b3d1fd..a2ecdf29b6 100644 --- a/packages/frontend/desktop/src/doc_store/mod.rs +++ b/packages/frontend/desktop/src/doc_store/mod.rs @@ -7,7 +7,10 @@ use std::{cell::RefCell, collections::BTreeMap}; -use affine_client::{FolderForestCache, LinkGraph, WeightedSearchEngine, domain::CollectionRule}; +use affine_client::{ + FolderForestCache, LinkGraph, WeightedSearchEngine, + domain::{CollectionRule, DocFacts, collection_holds}, +}; use affine_store::{ directory::{DocMode, WorkspaceDirectory}, @@ -61,30 +64,31 @@ pub struct DesktopCollection { impl DesktopCollection { pub fn matches(&self, doc: &DesktopDocMeta) -> bool { - if doc.trashed { - return false; - } - if self - .rules - .iter() - .any(|rule| matches!(rule, CollectionRule::IncludeDocIds(ids) if ids.contains(&doc.id))) - { - return true; - } - let mut filters = self - .rules - .iter() - .filter(|rule| !matches!(rule, CollectionRule::IncludeDocIds(_))) - .peekable(); - filters.peek().is_some() - && filters.all(|rule| match rule { - CollectionRule::HasTag(tag) => doc.tags.contains(tag), - CollectionRule::ModeIs(mode) => doc.default_mode.as_str() == mode, - CollectionRule::TitleContains(needle) => { - doc.title.to_lowercase().contains(&needle.to_lowercase()) - } - CollectionRule::IncludeDocIds(_) => true, - }) + collection_holds( + &self.rules, + &DocFacts { + id: &doc.id, + title: &doc.title, + tags: &doc.tags, + mode: doc.default_mode.as_str(), + page_width: doc.page_width.map(PageWidth::as_wire), + favorite: doc.is_favorite, + journal: doc.journal_date.is_some(), + trashed: doc.trashed, + created: None, + updated: stored_ms(doc.updated_at_ms), + }, + ) + } +} + +/// A stored time in Unix milliseconds. Early desktop workspaces stored ten-digit Unix timestamps +/// in millisecond fields. +pub(crate) fn stored_ms(ms: i64) -> Option { + match ms { + 1_000_000_000..=9_999_999_999 => Some(ms * 1_000), + 1.. => Some(ms), + _ => None, } } diff --git a/packages/frontend/desktop/src/doc_store/navigation.rs b/packages/frontend/desktop/src/doc_store/navigation.rs index 07955c52c3..904cf2e38c 100644 --- a/packages/frontend/desktop/src/doc_store/navigation.rs +++ b/packages/frontend/desktop/src/doc_store/navigation.rs @@ -1,8 +1,13 @@ //! Project the workspace root's tag and collection definitions into the desktop store. -use std::collections::{BTreeMap, BTreeSet}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; -use affine_client::domain::CollectionRule; +use affine_client::domain::{ + CivilDate, CollectionRule, FilterParams, FilterRule, FilterScope, LocalCalendar, +}; use affine_store::{ StoreResult, workspace_db::{ @@ -12,7 +17,7 @@ use affine_store::{ use blocksuite_playground_doc::try_random_client_id; use ui_tokens::{LIGHT_THEME, ThemeTokens}; -use super::{DesktopCollection, DesktopDocStore}; +use super::{DesktopCollection, DesktopDocStore, stored_ms}; #[derive(Default)] pub(super) struct NavigationProjection { @@ -23,17 +28,39 @@ pub(super) struct NavigationProjection { struct NavigationSnapshot { tags: StoreResult>>, collections: Option>, + /// Creation dates of the pages, read only when a collection filters by them. + created: BTreeMap, } impl NavigationSnapshot { fn read(root: &WorkspaceRootDoc) -> Self { + let collections = root.navigation_collections().ok().flatten(); + let by_created = collections.iter().flatten().any(|collection| { + collection + .filters + .iter() + .any(|filter| filter.key == "createdAt") + }); Self { tags: root.navigation_tags(), - collections: root.navigation_collections().ok().flatten(), + collections, + created: if by_created { + created_dates(root) + } else { + BTreeMap::new() + }, } } } +fn created_dates(root: &WorkspaceRootDoc) -> BTreeMap { + root.list_pages() + .unwrap_or_default() + .into_iter() + .filter_map(|page| Some((page.id, stored_ms(page.create_date_ms)?))) + .collect() +} + impl DesktopDocStore { pub(crate) fn load_navigation(&mut self) { self.project_navigation(NavigationSnapshot::read(self.directory.db().root())); @@ -75,12 +102,79 @@ impl DesktopDocStore { } } if let Some(collections) = snapshot.collections { - self.collections = collections.into_iter().map(project_collection).collect(); + let scope = self.filter_scope(snapshot.created); + self.collections = collections + .into_iter() + .map(|collection| project_collection(collection, &scope)) + .collect(); changed = true; } changed } + /// Set the local date that relative collection date filters count from and the zone that + /// turns document times into local dates, and project the collections of the workspace + /// root again. + pub(crate) fn set_calendar(&mut self, today: &str, calendar: LocalCalendar) { + self.derived.today = CivilDate::parse(today); + self.derived.calendar = calendar; + self.load_navigation(); + self.touch_meta(); + } + + fn filter_scope(&self, created: BTreeMap) -> Arc { + let tags = self + .derived + .navigation + .get(&self.active_workspace().id) + .and_then(|projection| projection.tags.as_ref()); + Arc::new(FilterScope { + today: self.derived.today, + calendar: self.derived.calendar.clone(), + tags: tags.map(|tags| tags.keys().cloned().collect()), + created, + }) + } + + /// The documents that the filters of `record` match, without its allow list, in the + /// order of the document list. + pub(crate) fn filtered_doc_ids(&self, record: &WorkspaceCollection) -> Vec { + let by_created = record + .filters + .iter() + .any(|filter| filter.key == "createdAt"); + let created = if by_created { + created_dates(self.directory.db().root()) + } else { + BTreeMap::new() + }; + let collection = project_collection( + WorkspaceCollection { + allow_list: Vec::new(), + ..record.clone() + }, + &self.filter_scope(created), + ); + self.visible_docs() + .into_iter() + .filter(|doc| collection.matches(doc)) + .map(|doc| doc.id.clone()) + .collect() + } + + /// The stored form of a collection, as the collection editor edits it. + pub(crate) fn collection_record(&self, id: &str) -> Option { + self.collections + .iter() + .find(|collection| collection.id == id) + .map(store_collection) + } + + /// Replace the name, documents, and filters of a collection. + pub(crate) fn update_collection(&mut self, collection: WorkspaceCollection) -> bool { + self.edit_navigation(NavigationEdit::UpdateCollection(collection)) + } + pub(crate) fn tag_label(&self, id: &str) -> String { self.views().tag_label(id).to_owned() } @@ -139,6 +233,7 @@ impl DesktopDocStore { let collections = match &edit { NavigationEdit::CreateCollection(_) | NavigationEdit::RenameCollection { .. } + | NavigationEdit::UpdateCollection(_) | NavigationEdit::DeleteCollection(_) => Some(std::mem::take(&mut self.collections)), _ => None, }; @@ -236,6 +331,7 @@ fn legacy_definitions( } NavigationEdit::CreateCollection(_) | NavigationEdit::RenameCollection { .. } + | NavigationEdit::UpdateCollection(_) | NavigationEdit::DeleteCollection(_) if !root.has_navigation_collections() => { @@ -267,38 +363,41 @@ pub(super) fn resolve_tag_color(color: &str, theme: &ThemeTokens) -> u32 { .map_or(FALLBACK_TAG_RGB, |rgba| rgba.to_u32() >> 8) } -fn project_collection(collection: WorkspaceCollection) -> DesktopCollection { - let mut rules = Vec::new(); - for filter in collection.filters { - let Some(value) = filter.value.as_deref() else { - rules.clear(); - break; - }; - match ( - filter.kind.as_str(), - filter.key.as_str(), - filter.method.as_str(), - ) { - ("system", "tags", "include-all") => { - rules.extend( - value - .split(',') - .filter(|id| !id.is_empty()) - .map(|id| CollectionRule::HasTag(id.to_owned())), - ); - } - ("system", "docPrimaryMode", "is") => { - rules.push(CollectionRule::ModeIs(value.to_owned())) - } - ("system", "title", "match") => { - rules.push(CollectionRule::TitleContains(value.to_owned())) - } - _ => { - rules.clear(); - break; - } - } - } +fn project_collection( + collection: WorkspaceCollection, + scope: &Arc, +) -> DesktopCollection { + let mut rules: Vec<_> = collection + .filters + .into_iter() + .map(|filter| { + // Keep the three filters that the desktop seeds as their own rules. Each one + // stores back to the same filter. + let simple = match (&*filter.kind, &*filter.key, &*filter.method, &filter.value) { + ("system", "tags", "include-all", Some(tag)) if !tag.contains(',') => { + Some(CollectionRule::HasTag(tag.clone())) + } + ("system", "docPrimaryMode", "is", Some(mode)) => { + Some(CollectionRule::ModeIs(mode.clone())) + } + ("system", "title", "match", Some(title)) => { + Some(CollectionRule::TitleContains(title.clone())) + } + _ => None, + }; + simple.unwrap_or_else(|| { + CollectionRule::Filter(FilterRule { + params: FilterParams { + kind: filter.kind, + key: filter.key, + method: filter.method, + value: filter.value, + }, + scope: Arc::clone(scope), + }) + }) + }) + .collect(); if !collection.allow_list.is_empty() { rules.push(CollectionRule::IncludeDocIds(collection.allow_list)); } @@ -321,6 +420,16 @@ fn store_collection(collection: &DesktopCollection) -> WorkspaceCollection { allow_list.extend(ids.iter().cloned()); continue; } + CollectionRule::Filter(rule) => { + let params = rule.params.clone(); + filters.push(CollectionFilter { + kind: params.kind, + key: params.key, + method: params.method, + value: params.value, + }); + continue; + } }; filters.push(CollectionFilter { kind: "system".into(), @@ -520,6 +629,7 @@ pub(super) mod tests { if store.project_navigation(NavigationSnapshot { tags, collections: None, + created: BTreeMap::new(), }) { store.touch_meta(); } diff --git a/packages/frontend/desktop/src/doc_store/views.rs b/packages/frontend/desktop/src/doc_store/views.rs index 8bbe9b0677..a49a614946 100644 --- a/packages/frontend/desktop/src/doc_store/views.rs +++ b/packages/frontend/desktop/src/doc_store/views.rs @@ -293,6 +293,10 @@ pub(crate) struct TagSearchHit { #[derive(Default)] pub(crate) struct DerivedCache { pub(super) navigation: BTreeMap, + /// The date that relative collection date filters count from. + pub(super) today: Option, + /// The zone that turns document times into local dates for collection date filters. + pub(super) calendar: affine_client::domain::LocalCalendar, /// Advances on every change to document metadata, membership, or folder placement. pub(crate) meta_rev: u64, /// Advances on every change to folder rows; keys the sanitized folder forest. diff --git a/packages/frontend/desktop/src/sidebar/tree_menu.rs b/packages/frontend/desktop/src/sidebar/tree_menu.rs index 6d6b9cb948..8b7c114f52 100644 --- a/packages/frontend/desktop/src/sidebar/tree_menu.rs +++ b/packages/frontend/desktop/src/sidebar/tree_menu.rs @@ -282,9 +282,15 @@ impl TreeMenu { TreeTarget::Group(DesktopRoute::Tag(_)) => { &[ChildDoc, OpenTab, OpenSplit, Rename, DeleteGroup] } - TreeTarget::Group(DesktopRoute::Collection(_)) => { - &[OpenGroup, OpenTab, OpenSplit, Rename, DeleteGroup] - } + TreeTarget::Group(DesktopRoute::Collection(_)) => &[ + OpenGroup, + EditCollection, + AddDocs, + OpenTab, + OpenSplit, + Rename, + DeleteGroup, + ], _ => &[], } } @@ -446,6 +452,8 @@ fn tree_menu_row( #[derive(Clone, Copy)] enum Command { OpenGroup, + EditCollection, + AddDocs, ViewInfo, OpenTab, OpenSplit, @@ -465,6 +473,8 @@ impl Command { fn presentation(self, favorite: bool) -> (&'static str, &'static [u8]) { match self { Self::OpenGroup => ("Open", DOC_ICON_SVG), + Self::EditCollection => ("Edit collection", icons::EDIT.svg.as_bytes()), + Self::AddDocs => ("Add docs", icons::ALL_DOCS.svg.as_bytes()), 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()), @@ -541,6 +551,14 @@ impl Command { return; } match (self, target) { + ( + Self::EditCollection | Self::AddDocs, + TreeTarget::Group(DesktopRoute::Collection(id)), + ) => { + let rules = matches!(self, Self::AddDocs).then_some(false); + shell.state.open_collection_editor(id, rules); + close_drawer(&mut shell.state.sidebar, window); + } (Self::OpenGroup, TreeTarget::Group(route)) => { shell.state.navigate_active_pane(route.clone()); close_drawer(&mut shell.state.sidebar, window); diff --git a/packages/frontend/desktop/src/state/mod.rs b/packages/frontend/desktop/src/state/mod.rs index a328256d4e..f7a158bce4 100644 --- a/packages/frontend/desktop/src/state/mod.rs +++ b/packages/frontend/desktop/src/state/mod.rs @@ -6,7 +6,7 @@ use affine_client::{ Scope, nav::{LocationChoice, LocationRef, Origin}, }; -use affine_store::directory::DocMode; +use affine_store::{directory::DocMode, workspace_db::WorkspaceCollection}; use ui_tokens::ThemeMode; use crate::{ @@ -35,6 +35,24 @@ pub enum DesktopModal { Settings, } +/// The open `EditCollection` dialog and the collection that it edits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CollectionEditor { + /// The collection as it was when the dialog opened. `Reset` returns to its rules. + pub(crate) init: WorkspaceCollection, + pub(crate) value: WorkspaceCollection, + /// `Rules` mode, or `Pages` mode when `false`. + pub(crate) rules: bool, + pub(crate) preview: bool, + pub(crate) include_open: bool, + pub(crate) search: String, + /// Keys the text fields of one opening of the dialog. + pub(crate) session: i64, + /// Counts the `Reset` clicks. The condition fields show the restored values because each + /// reset keys them again. + pub(crate) resets: u64, +} + /// Three-state desktop appearance preference (`System` / `Light` / `Dark`). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum ThemePreference { @@ -106,6 +124,7 @@ pub struct DesktopAppState { pub peek_view: PeekViewState, pub inspector_tab: Option, pub modal: Option, + pub collection_editor: Option, doc_routes_revision: Option, } @@ -218,7 +237,7 @@ impl DesktopAppState { } fn from_doc_store_and_drafts( - store: DesktopDocStore, + mut store: DesktopDocStore, draft_store: ComposerDraftStore, draft_store_error: Option, theme: ThemeMode, @@ -230,6 +249,7 @@ impl DesktopAppState { &store.active_workspace().id, ); let split = SplitLayout::single(scope, initial_route(&store), DocViewMode::Page); + store.use_system_calendar(today_date); let theme_preference = match theme { ThemeMode::Light => ThemePreference::Light, ThemeMode::Dark => ThemePreference::Dark, @@ -254,6 +274,7 @@ impl DesktopAppState { peek_view: PeekViewState::default(), inspector_tab: None, modal: None, + collection_editor: None, doc_routes_revision: None, } } @@ -628,6 +649,40 @@ impl DesktopAppState { self.modal = None; } + /// Open `EditCollection` in `Rules` mode, in `Pages` mode, or in the mode that the + /// collection's filters choose when `rules` is `None`. + pub fn open_collection_editor(&mut self, id: &str, rules: Option) -> bool { + let Some(init) = self.store.collection_record(id) else { + return false; + }; + self.quick_search.close(); + self.peek_view.close(); + self.logical_clock_ms += 1; + self.collection_editor = Some(CollectionEditor { + session: self.logical_clock_ms, + rules: rules.unwrap_or(!init.filters.is_empty()), + include_open: !init.allow_list.is_empty(), + value: init.clone(), + init, + preview: true, + search: String::new(), + resets: 0, + }); + true + } + + /// Write the edited collection and close the dialog. A blank name keeps it open. + pub fn save_collection_editor(&mut self) -> bool { + match self.collection_editor.take() { + Some(editor) if editor.value.name.trim().is_empty() => { + self.collection_editor = Some(editor); + false + } + Some(editor) => self.store.update_collection(editor.value), + None => false, + } + } + pub fn toggle_inspector(&mut self) { self.inspector_tab = match self.inspector_tab { Some(_) => None, diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_bar.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_bar.rs new file mode 100644 index 0000000000..465bb469b0 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_bar.rs @@ -0,0 +1,458 @@ +//! `Filters`: the filter conditions of a collection. + +use affine_store::workspace_db::CollectionFilter; +use ui::{ + App, Div, InteractiveElement, IntoElement, ParentElement, SharedString, Stateful, + StatefulInteractiveElement, Styled, Window, div, px, svg, +}; +use ui_tokens::icons; + +use super::{EditorCx, EditorMenu}; +use crate::{DesktopFlexExt as _, doc_store::DesktopDocStore, state::CollectionEditor}; + +/// How a condition picks its value. +#[derive(Clone, Copy)] +pub(super) enum ValueKind { + /// Tag IDs, separated by commas. + Tags, + /// `YYYY-MM-DD`, or two dates separated by a comma for `between`. + Date, + /// `true` or `false`. + Flag, + /// One stored value with its label. + Choice(&'static [(&'static str, &'static str)]), + /// Any text. + Text, +} + +/// A system property that a condition filters by. +pub(super) struct FilterDef { + pub(super) key: &'static str, + pub(super) name: &'static str, + pub(super) icon: &'static [u8], + pub(super) methods: &'static [(&'static str, &'static str)], + /// The method and value of a new condition, or `None` for a key that the add menu + /// does not offer. + pub(super) default: Option<(&'static str, Option<&'static str>)>, + pub(super) value: ValueKind, +} + +const IS: &[(&str, &str)] = &[("is", "is"), ("is-not", "is-not")]; +const DATE_METHODS: &[(&str, &str)] = &[ + ("after", "after"), + ("before", "before"), + ("between", "between"), + ("last-3-days", "last 3 days"), + ("last-7-days", "last 7 days"), + ("last-15-days", "last 15 days"), + ("last-30-days", "last 30 days"), + ("this-week", "this week"), + ("this-month", "this month"), + ("this-quarter", "this quarter"), + ("this-year", "this year"), +]; + +/// The conditions in the order of the `Add Filter Rule` menu. +pub(super) const FILTERS: &[FilterDef] = &[ + FilterDef { + key: "favorite", + name: "Favourited", + icon: icons::FAVORITE.svg.as_bytes(), + methods: &[("is", "is")], + default: Some(("is", Some("true"))), + value: ValueKind::Flag, + }, + FilterDef { + key: "tags", + name: "Tags", + icon: icons::TAG.svg.as_bytes(), + methods: &[ + ("include-all", "contains all"), + ("include-any-of", "contains one of"), + ("not-include-all", "does not contains all"), + ("not-include-any-of", "does not contains one of"), + ("is-not-empty", "is not empty"), + ("is-empty", "is empty"), + ], + default: Some(("is-not-empty", None)), + value: ValueKind::Tags, + }, + FilterDef { + key: "updatedAt", + name: "Updated", + icon: icons::TODAY.svg.as_bytes(), + methods: DATE_METHODS, + default: Some(("this-week", None)), + value: ValueKind::Date, + }, + FilterDef { + key: "createdAt", + name: "Created", + icon: icons::NOW.svg.as_bytes(), + methods: DATE_METHODS, + default: Some(("this-week", None)), + value: ValueKind::Date, + }, + FilterDef { + key: "pageWidth", + name: "Page width", + icon: icons::PAGE_WIDTH.svg.as_bytes(), + methods: IS, + default: Some(("is", Some("fullWidth"))), + value: ValueKind::Choice(&[("standard", "Standard"), ("fullWidth", "Full width")]), + }, + FilterDef { + key: "docPrimaryMode", + name: "Doc mode", + icon: icons::PAGE.svg.as_bytes(), + methods: IS, + default: Some(("is", Some("page"))), + value: ValueKind::Choice(&[("page", "Page"), ("edgeless", "Edgeless")]), + }, + FilterDef { + key: "journal", + name: "Journal", + icon: icons::TODAY.svg.as_bytes(), + methods: IS, + default: Some(("is", Some("true"))), + value: ValueKind::Flag, + }, + FilterDef { + key: "title", + name: "Title", + icon: icons::TEXT.svg.as_bytes(), + methods: &[("match", "contains")], + default: None, + value: ValueKind::Text, + }, +]; + +pub(super) fn definition(filter: &CollectionFilter) -> Option<&'static FilterDef> { + (filter.kind == "system") + .then(|| FILTERS.iter().find(|def| def.key == filter.key)) + .flatten() +} + +/// Whether the condition shows a value after its method. +pub(super) fn has_value(def: &FilterDef, method: &str) -> bool { + match def.value { + ValueKind::Tags => method.starts_with("include") || method.starts_with("not-include"), + ValueKind::Date => matches!(method, "after" | "before" | "between"), + ValueKind::Flag | ValueKind::Choice(_) | ValueKind::Text => true, + } +} + +impl CollectionEditor { + /// Add a condition with the default method and value of `key`. + pub(crate) fn add_filter(&mut self, key: &str) -> Option { + let def = FILTERS.iter().find(|def| def.key == key)?; + let (method, value) = def.default?; + self.value.filters.push(CollectionFilter { + kind: "system".into(), + key: key.into(), + method: method.into(), + value: value.map(Into::into), + }); + Some(self.value.filters.len() - 1) + } + + /// Change the method of a condition. A value that the new method does not read is removed. + pub(crate) fn set_filter_method(&mut self, index: usize, method: &str) { + let Some(filter) = self.value.filters.get_mut(index) else { + return; + }; + let date_value = |method: &str| matches!(method, "after" | "before" | "between"); + if definition(filter).is_some_and(|def| { + matches!(def.value, ValueKind::Date) && date_value(&filter.method) != date_value(method) + }) { + filter.value = None; + } + filter.method = method.into(); + } + + pub(crate) fn set_filter_value(&mut self, index: usize, value: Option) { + if let Some(filter) = self.value.filters.get_mut(index) { + filter.value = value; + } + } + + /// Add the tag to the value of a tag condition, or remove it when the value has it. + pub(crate) fn toggle_filter_tag(&mut self, index: usize, tag: &str) { + let Some(filter) = self.value.filters.get_mut(index) else { + return; + }; + let mut ids: Vec<&str> = filter + .value + .as_deref() + .unwrap_or_default() + .split(',') + .filter(|id| !id.is_empty()) + .collect(); + match ids.iter().position(|id| *id == tag) { + Some(position) => { + ids.remove(position); + } + None => ids.push(tag), + } + filter.value = Some(ids.join(",")); + } + + pub(crate) fn remove_filter(&mut self, index: usize) { + if index < self.value.filters.len() { + self.value.filters.remove(index); + } + } +} + +/// The conditions and the add button. +pub(super) fn render( + editor: &CollectionEditor, + store: &DesktopDocStore, + ecx: &EditorCx, + window: &mut Window, + app: &mut App, +) -> Div { + let palette = ecx.palette; + let mut bar = div().flex().flex_wrap().items_center().gap(px(10.0)); + for (index, filter) in editor.value.filters.iter().enumerate() { + let count = editor.value.filters.len(); + bar = bar.child(condition( + (index, count, editor.resets), + filter, + store, + ecx, + window, + app, + )); + } + let open = { + let ecx = ecx.clone(); + move |event: &ui::ClickEvent, window: &mut Window, app: &mut App| { + app.stop_propagation(); + ecx.open_menu(EditorMenu::AddFilter, event.position(), window, app); + } + }; + let plus = svg() + .data(icons::PLUS.svg.as_bytes()) + .size(px(16.0)) + .flex_shrink(0.0) + .text_color(palette.text_secondary); + let add = div() + .id("desktop.collection_editor.add_filter") + .snapshot( + "desktop.collection_editor.add_filter", + Some("desktop.collection_editor"), + ) + .flex() + .items_center() + .gap(px(4.0)) + .rounded(px(6.0)) + .cursor_pointer() + .hover(move |style| style.bg(palette.hover_color)) + .on_click(open); + bar.child(if editor.value.filters.is_empty() { + add.h(px(32.0)) + .px(px(12.0)) + .border_1() + .border_color(palette.border) + .text_size(px(14.0)) + .child(plus) + .child("Add Filter Rule") + } else { + add.size(px(24.0)).justify_center().child(plus) + }) +} + +fn condition( + (index, count, resets): (usize, usize, u64), + filter: &CollectionFilter, + store: &DesktopDocStore, + ecx: &EditorCx, + window: &mut Window, + app: &mut App, +) -> Stateful
{ + let palette = ecx.palette; + let def = definition(filter); + let segment = |id: &'static str, label: SharedString, menu: EditorMenu, muted: bool| { + let ecx = ecx.clone(); + div() + .id((id, index)) + .snapshot( + ui::snap_id!("{id}.{index}"), + Some("desktop.collection_editor"), + ) + .snapshot_text(label.clone()) + .min_w_0() + .truncate() + .px(px(4.0)) + .rounded(px(4.0)) + .line_height(px(22.0)) + .text_color(if muted { + palette.text_secondary + } else { + palette.text_primary + }) + .cursor_pointer() + .hover(move |style| style.bg(palette.hover_color)) + .child(label) + .on_click(move |event, window, app| { + app.stop_propagation(); + ecx.open_menu(menu, event.position(), window, app); + }) + }; + let mut chip = super::max_width(div(), ui::relative(1.0)) + .id(("desktop.collection_editor.filter", index)) + .snapshot( + ui::snap_id!("desktop.collection_editor.filter.{index}"), + Some("desktop.collection_editor"), + ) + .flex() + .items_center() + .gap(px(4.0)) + .h(px(32.0)) + .px(px(8.0)) + .overflow_hidden() + .rounded(px(8.0)) + .border_1() + .border_color(palette.border) + .bg(palette.bg_elevated) + .text_size(px(14.0)); + let Some(def) = def else { + // `UnknownFilterCondition`: this client neither shows nor edits the condition. + chip = chip.child( + div() + .min_w_0() + .truncate() + .text_color(palette.text_muted) + .child(format!("{} {}", filter.key, filter.method)), + ); + return chip.child(remove_button(index, ecx)); + }; + chip = chip.child( + div() + .flex() + .flex_shrink(0.0) + .items_center() + .pr(px(4.0)) + .child( + svg() + .data(def.icon) + .size(px(18.0)) + .mr(px(6.0)) + .text_color(palette.text_secondary), + ) + .child(def.name), + ); + let method = def + .methods + .iter() + .find(|(method, _)| *method == filter.method) + .map_or("unknown", |(_, label)| label); + if def.methods.len() > 1 { + chip = chip.child(segment( + "desktop.collection_editor.filter.method", + method.into(), + EditorMenu::Method(index), + true, + )); + } + if has_value(def, &filter.method) { + let value = filter.value.clone().unwrap_or_default(); + chip = chip.child(match def.value { + ValueKind::Date | ValueKind::Text => { + // A new field takes the stored value, so a field of another condition count + // or index, or a field from before `Reset`, never shows a stale value. + let field = ecx.field( + ( + if matches!(def.value, ValueKind::Date) { + "desktop.collection_editor.filter.date" + } else { + "desktop.collection_editor.filter.text" + }, + Some(index), + ui::hash(&(index, count, resets)), + ), + if filter.method == "between" { + "YYYY-MM-DD,YYYY-MM-DD" + } else if matches!(def.value, ValueKind::Date) { + "YYYY-MM-DD" + } else { + "Empty" + }, + &value, + 14.0, + window, + app, + move |editor, text| editor.set_filter_value(index, Some(text.to_owned())), + ); + div() + .w(px(if filter.method == "between" { + 196.0 + } else { + 112.0 + })) + .child(field) + .into_any_element() + } + kind => { + let label = value_label(kind, &value, store); + let empty = label.is_empty(); + segment( + "desktop.collection_editor.filter.value", + if empty { "Empty".into() } else { label.into() }, + EditorMenu::Value(index), + empty, + ) + .into_any_element() + } + }); + } + chip.child(remove_button(index, ecx)) +} + +fn value_label(kind: ValueKind, value: &str, store: &DesktopDocStore) -> String { + match kind { + ValueKind::Tags => value + .split(',') + .filter(|id| !id.is_empty()) + .map(|id| store.tag_label(id)) + .collect::>() + .join(", "), + ValueKind::Flag => match value { + "true" => "True".into(), + "false" => "False".into(), + _ => String::new(), + }, + ValueKind::Choice(choices) => choices + .iter() + .find(|(stored, _)| *stored == value) + .map_or_else(String::new, |(_, label)| (*label).into()), + ValueKind::Date | ValueKind::Text => value.into(), + } +} + +fn remove_button(index: usize, ecx: &EditorCx) -> impl IntoElement { + let (palette, ecx) = (ecx.palette, ecx.clone()); + div() + .id(("desktop.collection_editor.filter.remove", index)) + .snapshot( + ui::snap_id!("desktop.collection_editor.filter.remove.{index}"), + Some("desktop.collection_editor"), + ) + .flex() + .flex_shrink(0.0) + .items_center() + .pl(px(4.0)) + .cursor_pointer() + .child( + svg() + .data(icons::CLOSE.svg.as_bytes()) + .size(px(16.0)) + .text_color(palette.text_secondary), + ) + .on_click(move |_, _, app| { + app.stop_propagation(); + ecx.set_menu(app, None); + ecx.edit(app, |editor| editor.remove_filter(index)); + }) +} diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_menu.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_menu.rs new file mode 100644 index 0000000000..6a47890307 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/filter_menu.rs @@ -0,0 +1,328 @@ +//! The menus of the filters: `Add Filter Rule`, and the method and value menus of each +//! condition. A menu taller than the window scrolls, and the arrow keys, `Enter`, and `Space` +//! choose a row as a click does. + +use blocksuite_editor::scroll::{ScrollAxis, wheel_delta}; +use ui::{ + App, Div, InteractiveElement, ParentElement, SharedString, Stateful, + StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder as _, px, svg, +}; +use ui_tokens::icons; + +use super::{ + EditorCx, EditorMenu, + filter_bar::{FILTERS, ValueKind, definition, has_value}, +}; +use crate::{DesktopFlexExt as _, doc_store::DesktopDocStore, state::CollectionEditor}; + +/// The height of one menu row. +const ROW_HEIGHT: f32 = 32.0; +/// The height of the title and its divider: `2px` padding around a 22 px line, and the 1 px +/// divider with 4 px margins. +const TITLE_HEIGHT: f32 = 35.0; +/// The padding and the border of the panel. +const CHROME_HEIGHT: f32 = 10.0; +/// The space that the menu keeps from the top and the bottom of the window. +const WINDOW_MARGIN: f32 = 8.0; + +/// What a row does to the collection editor. It returns the menu to show next. +type Action = Box Option>; + +struct MenuRow { + label: SharedString, + icon: Option<&'static [u8]>, + checked: bool, + action: Action, +} + +/// The title and the rows of `menu`, or `None` for a menu that has no rows to choose. +fn menu_rows( + menu: EditorMenu, + editor: &CollectionEditor, + store: &DesktopDocStore, +) -> Option<(Option<&'static str>, Vec)> { + let row = |label: SharedString, icon, checked, action: Action| MenuRow { + label, + icon, + checked, + action, + }; + let mut rows = Vec::new(); + match menu { + EditorMenu::AddFilter => { + for def in FILTERS.iter().filter(|def| def.default.is_some()) { + let key = def.key; + rows.push(row( + def.name.into(), + Some(def.icon), + false, + Box::new(move |editor| { + let index = editor.add_filter(key)?; + let filter = &editor.value.filters[index]; + let opens_value = definition(filter).is_some_and(|def| { + has_value(def, &filter.method) + && !matches!(def.value, ValueKind::Date | ValueKind::Text) + }); + opens_value.then_some(EditorMenu::Value(index)) + }), + )); + } + return Some((Some("Filter"), rows)); + } + EditorMenu::Method(index) => { + let filter = editor.value.filters.get(index)?; + for (method, label) in definition(filter)?.methods { + rows.push(row( + (*label).into(), + None, + filter.method == *method, + Box::new(move |editor| { + editor.set_filter_method(index, method); + None + }), + )); + } + } + EditorMenu::Value(index) => { + let filter = editor.value.filters.get(index)?; + let value = filter.value.as_deref().unwrap_or_default(); + match definition(filter)?.value { + ValueKind::Tags => { + let selected: Vec<&str> = value.split(',').collect(); + for (tag, _, _) in store.all_tags_with_counts() { + let checked = selected.contains(&tag.as_str()); + rows.push(row( + store.tag_label(&tag).into(), + Some(icons::TAG.svg.as_bytes()), + checked, + Box::new(move |editor| { + editor.toggle_filter_tag(index, &tag); + Some(EditorMenu::Value(index)) + }), + )); + } + } + ValueKind::Flag => { + for (stored, label) in [("true", "True"), ("false", "False")] { + rows.push(row( + label.into(), + None, + value == stored, + Box::new(move |editor| { + editor.set_filter_value(index, Some(stored.into())); + None + }), + )); + } + } + ValueKind::Choice(choices) => { + for (stored, label) in choices { + rows.push(row( + (*label).into(), + None, + value == *stored, + Box::new(move |editor| { + editor.set_filter_value(index, Some((*stored).into())); + None + }), + )); + } + } + ValueKind::Date | ValueKind::Text => return None, + } + } + } + Some((None, rows)) +} + +/// The height of the rows area in a window `viewport` pixels high, and the height of all rows. +fn rows_height(count: usize, title: bool, viewport: f32) -> (f32, f32) { + let total = count.max(1) as f32 * ROW_HEIGHT; + let room = + viewport - 2.0 * WINDOW_MARGIN - CHROME_HEIGHT - if title { TITLE_HEIGHT } else { 0.0 }; + (total.min(room.max(ROW_HEIGHT)), total) +} + +/// The rows of the open menu with the editor and the store of the shell. +fn open_rows(ecx: &EditorCx, app: &App) -> Option<(Option<&'static str>, Vec)> { + let menu = ecx.view.read(app).menu?.0; + let state = &ecx.shell.read(app).state; + menu_rows(menu, state.collection_editor.as_ref()?, &state.store) +} + +/// Do what a click on row `row` of the open menu does. +pub(super) fn choose(ecx: &EditorCx, row: usize, app: &mut App) { + let Some(action) = open_rows(ecx, app) + .and_then(|(_, rows)| rows.into_iter().nth(row)) + .map(|row| row.action) + else { + return; + }; + let mut next = None; + ecx.edit(app, |editor| next = action(editor)); + let anchor = ecx.view.read(app).menu.map(|(_, point)| point); + ecx.set_menu(app, next.zip(anchor)); +} + +/// Move the highlight of the open menu `step` rows down, and scroll the row into view. +pub(super) fn move_highlight(ecx: &EditorCx, step: isize, window: &Window, app: &mut App) { + let Some((title, rows)) = open_rows(ecx, app) else { + return; + }; + let count = rows.len(); + if count == 0 { + return; + } + let (height, _) = rows_height( + count, + title.is_some(), + f32::from(window.viewport_size().height), + ); + ecx.view.update(app, |view, cx| { + let row = match view.menu_highlight { + None if step > 0 => 0, + None => count - 1, + Some(row) => (row as isize + step).rem_euclid(count as isize) as usize, + }; + view.menu_highlight = Some(row); + let top = row as f32 * ROW_HEIGHT; + view.menu_scroll = view.menu_scroll.min(top).max(top + ROW_HEIGHT - height); + cx.notify(); + }); + ecx.shell.update(app, |_, cx| cx.notify()); +} + +/// The panel of `menu` in a window `viewport` pixels high. +pub(super) fn render( + menu: EditorMenu, + editor: &CollectionEditor, + store: &DesktopDocStore, + ecx: &EditorCx, + viewport: f32, + app: &App, +) -> Option> { + let palette = ecx.palette; + let (title, rows) = menu_rows(menu, editor, store)?; + let (height, total) = rows_height(rows.len(), title.is_some(), viewport); + let max_scroll = total - height; + let view = ecx.view.read(app); + let offset = ScrollAxis::new(view.menu_scroll, max_scroll).offset; + let highlight = view.menu_highlight; + let close = ecx.clone(); + let mut panel = div() + .id("desktop.collection_editor.menu") + .snapshot( + "desktop.collection_editor.menu", + Some("desktop.collection_editor"), + ) + .occlude() + .flex() + .flex_col() + .w(px(230.0)) + .overflow_hidden() + .p(px(4.0)) + .rounded(px(8.0)) + .border_1() + .border_color(palette.border) + .bg(palette.bg_elevated) + .text_color(palette.text_primary) + .shadow(crate::theme_shadow(ecx.theme, "--affine-menu-shadow")) + .on_click(|_, _, app| app.stop_propagation()) + .on_mouse_down_out(move |_, _, app| close.set_menu(app, None)); + if let Some(title) = title { + panel = panel + .child( + div() + .px(px(12.0)) + .py(px(2.0)) + .text_size(px(14.0)) + .font_weight(ui::FontWeight::MEDIUM) + .line_height(px(22.0)) + .child(title), + ) + .child(div().h(px(1.0)).my(px(4.0)).bg(palette.border)); + } + let mut list = div().relative().top(px(-offset)).flex().flex_col(); + if rows.is_empty() { + list = list.child( + div() + .h(px(ROW_HEIGHT)) + .px(px(8.0)) + .py(px(6.0)) + .text_size(px(14.0)) + .text_color(palette.text_muted) + .child("No tags"), + ); + } + for (row, item) in rows.into_iter().enumerate() { + let ecx = ecx.clone(); + list = list.child( + div() + .id(("desktop.collection_editor.menu.item", row)) + .snapshot( + ui::snap_id!("desktop.collection_editor.menu.item.{row}"), + Some("desktop.collection_editor.menu"), + ) + .snapshot_text(item.label.clone()) + .snapshot_focused(item.checked) + .flex() + .flex_shrink(0.0) + .items_center() + .gap(px(8.0)) + .h(px(ROW_HEIGHT)) + .px(px(8.0)) + .rounded(px(4.0)) + .text_size(px(14.0)) + .cursor_pointer() + .when(highlight == Some(row), |row| row.bg(palette.hover_color)) + .hover(move |style| style.bg(palette.hover_color)) + .children(item.icon.map(|icon| { + svg() + .data(icon) + .size(px(20.0)) + .flex_shrink(0.0) + .text_color(palette.text_secondary) + })) + .child(div().flex_1().min_w_0().truncate().child(item.label)) + .when(item.checked, |row| { + row.child( + svg() + .data(icons::DONE.svg.as_bytes()) + .size(px(20.0)) + .flex_shrink(0.0) + .text_color(palette.accent), + ) + }) + .on_click(move |_, _, app| { + app.stop_propagation(); + choose(&ecx, row, app); + }), + ); + } + let scroll = ecx.view.clone(); + Some( + panel.child( + div() + .id("desktop.collection_editor.menu.rows") + .snapshot( + "desktop.collection_editor.menu.rows", + Some("desktop.collection_editor.menu"), + ) + .flex_shrink(0.0) + .h(px(height)) + .overflow_hidden() + .on_scroll(move |event, _, app| { + scroll.update(app, |view, cx| { + let (_, dy) = wheel_delta(event, 0.0); + let mut axis = ScrollAxis::new(view.menu_scroll, max_scroll); + if axis.apply(dy) { + view.menu_scroll = axis.offset; + cx.stop_propagation(); + cx.notify(); + } + }); + }) + .child(list), + ), + ) +} diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/mod.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/mod.rs new file mode 100644 index 0000000000..9ab625c0dc --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/mod.rs @@ -0,0 +1,541 @@ +//! `EditCollection`: the dialog that edits the documents (`Docs` mode) and the filters +//! (`Rules` mode) of a collection. + +mod filter_bar; +mod filter_menu; +mod pages_mode; +mod rules_mode; +#[cfg(test)] +mod tests; + +use affine_client::domain::LocalCalendar; +use blocksuite_editor::scroll::{ScrollAxis, wheel_delta}; +use ui::{ + AnyElement, App, Context, ElementId, Entity, FocusHandle, FontWeight, InteractiveElement, + IntoElement, ParentElement, Pixels, Point, SharedString, StatefulInteractiveElement, Styled, + Window, div, prelude::FluentBuilder as _, px, +}; +use ui_kit::VirtualList; +use ui_tokens::{FONT_SANS, ThemeMode}; + +use super::{LocalZone, text_field::TextField}; +use crate::{ + DesktopFlexExt as _, DesktopPalette, + doc_store::DesktopDocStore, + state::CollectionEditor, + views_extra::{ + button, button_with_fill, display_time, max_width, selection_icon, vertical_scroll, + }, + workbench::DesktopShellView, +}; + +/// The widest dialog (`maxWidth: 944` of `CollectionEditorDialog`). +const MAX_WIDTH: f32 = 944.0; +/// The height of one document row (`DocListItemComponent`). +const ROW_HEIGHT: f32 = 42.0; +/// The height of the bars above and below the content: 20 px padding around a 24 px line. +const BAR_HEIGHT: f32 = 65.0; +/// The height of the row that holds the mode switch: `16px 16px 8px` padding around it. +const TAB_ROW_HEIGHT: f32 = 56.0; + +impl DesktopDocStore { + /// Count relative collection date filters from the local date `today`, and read document + /// times in the local zone of the system, as the web client does. + pub(crate) fn use_system_calendar(&mut self, today: &str) { + let zone = LocalZone::system(); + self.set_calendar(today, LocalCalendar::new(move |ms| zone.offset_minutes(ms))); + } +} + +impl CollectionEditor { + /// Add the document to the allow list, or remove it when the list has it. + pub(crate) fn toggle_doc(&mut self, id: &str) { + let list = &mut self.value.allow_list; + match list.iter().position(|doc| doc == id) { + Some(index) => { + list.remove(index); + } + None => list.push(id.to_owned()), + } + } + + /// Return the filters and the allow list to the values that the dialog opened with. + pub(crate) fn reset(&mut self) { + self.value.filters = self.init.filters.clone(); + self.value.allow_list = self.init.allow_list.clone(); + self.resets += 1; + } + + pub(crate) fn can_save(&self) -> bool { + !self.value.name.trim().is_empty() + } +} + +/// The open menu of the dialog. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum EditorMenu { + AddFilter, + Method(usize), + Value(usize), +} + +/// View state of one opening of the dialog. +#[derive(Default)] +struct EditorView { + menu: Option<(EditorMenu, Point)>, + /// The menu row that the arrow keys moved to. + menu_highlight: Option, + menu_scroll: f32, + list_scroll: f32, + preview_scroll: f32, +} + +/// Everything that the parts of the dialog read and change. +#[derive(Clone)] +struct EditorCx { + shell: Entity, + view: Entity, + /// The focus of the dialog, which takes the keys of an open menu. + focus: FocusHandle, + session: i64, + palette: DesktopPalette, + theme: ThemeMode, +} + +impl EditorCx { + fn key(&self, name: &str, slot: u64) -> ElementId { + ElementId::NamedInteger(SharedString::from(format!("{name}.{}", self.session)), slot) + } + + fn edit(&self, app: &mut App, change: impl FnOnce(&mut CollectionEditor)) { + self.shell.update(app, |shell, cx| { + if let Some(editor) = shell.state.collection_editor.as_mut() { + change(editor); + cx.notify(); + } + }); + } + + fn set_menu(&self, app: &mut App, menu: Option<(EditorMenu, Point)>) { + self.view.update(app, |view, cx| { + if view.menu.map(|(open, _)| open) != menu.map(|(open, _)| open) { + view.menu_highlight = None; + view.menu_scroll = 0.0; + } + view.menu = menu; + cx.notify(); + }); + self.shell.update(app, |_, cx| cx.notify()); + } + + /// Open `menu` at `position`, and move the focus to the dialog so that the arrow keys, + /// `Enter`, and `Escape` reach the menu. + fn open_menu( + &self, + menu: EditorMenu, + position: Point, + window: &mut Window, + app: &mut App, + ) { + window.focus(&self.focus, app); + self.set_menu(app, Some((menu, position))); + } + + fn cancel(&self, app: &mut App) { + self.shell.update(app, |shell, cx| { + shell.state.collection_editor = None; + cx.notify(); + }); + } + + fn save(&self, app: &mut App) { + self.shell.update(app, |shell, cx| { + shell.sync_editors(cx); + shell.state.save_collection_editor(); + cx.notify(); + }); + } + + /// A one-line field whose edits `change` writes to the collection editor. `index` tells + /// apart the snapshots of the fields of one `name`. A new `slot` makes a new field that + /// shows `text`. + #[allow(clippy::too_many_arguments)] + fn field( + &self, + (name, index, slot): (&'static str, Option, u64), + placeholder: &'static str, + text: &str, + size: f32, + window: &mut Window, + app: &mut App, + change: impl Fn(&mut CollectionEditor, &str) + 'static, + ) -> Entity { + let (palette, editor) = (self.palette, self.clone()); + window.use_keyed_state(self.key(name, slot), app, move |_, cx| { + TextField::new( + cx.focus_handle(), + palette, + ( + index.map_or_else(|| name.into(), |index| format!("{name}.{index}").into()), + "desktop.collection_editor", + ), + placeholder, + text.to_owned(), + move |text, app| editor.edit(app, |value| change(value, text)), + ) + .plain(size) + }) + } +} + +impl DesktopShellView { + /// Render the open collection editor over the whole window. + pub(crate) fn render_collection_editor( + &self, + focus: &FocusHandle, + window: &mut Window, + cx: &mut Context, + ) -> Option { + let editor = self.state.collection_editor.as_ref()?; + let palette = crate::palette_for(self.state.theme); + let view = window.use_keyed_state( + ElementId::NamedInteger( + "desktop.collection_editor.view".into(), + editor.session as u64, + ), + cx, + |_, _| EditorView::default(), + ); + let ecx = EditorCx { + shell: cx.entity(), + view, + focus: focus.clone(), + session: editor.session, + palette, + theme: self.state.theme, + }; + let viewport = window.viewport_size(); + let width = (f32::from(viewport.width) - 64.0).clamp(0.0, MAX_WIDTH); + let height = f32::from(viewport.height) * 0.8; + let store = &self.state.store; + let (body, menu) = if editor.rules { + rules_mode::render(editor, store, &ecx, (width, height), window, cx) + } else { + ( + pages_mode::render(editor, store, &ecx, height, window, cx), + None, + ) + }; + let keys = { + let ecx = ecx.clone(); + // Other keys go on to the text input of the focused field. The workbench ignores + // keys while the dialog is open. + move |event: &ui::KeyDownEvent, window: &mut Window, app: &mut App| { + let menu = ecx.view.read(app).menu.is_some(); + match event.keystroke.key.as_str() { + "escape" if menu => ecx.set_menu(app, None), + "escape" => ecx.cancel(app), + "down" if menu => filter_menu::move_highlight(&ecx, 1, window, app), + "up" if menu => filter_menu::move_highlight(&ecx, -1, window, app), + "enter" | "space" if menu => { + if let Some(row) = ecx.view.read(app).menu_highlight { + filter_menu::choose(&ecx, row, app); + } + } + _ => return, + } + window.prevent_default(); + app.stop_propagation(); + } + }; + let card = div() + .id("desktop.collection_editor") + .snapshot("desktop.collection_editor", Some("desktop.shell.root")) + .occlude() + .relative() + .flex() + .flex_col() + .w(px(width)) + .h(px(height)) + .overflow_hidden() + .rounded(px(12.0)) + .bg(palette.bg_canvas) + .shadow(crate::theme_shadow( + self.state.theme, + "--affine-popover-shadow", + )) + .child(body) + .children(menu); + let dismiss = ecx.clone(); + let layer = div() + .id("desktop.collection_editor.layer") + .track_focus(focus) + .on_key_down(keys) + .w(viewport.width) + .h(viewport.height) + .relative() + .flex() + .items_center() + .justify_center() + .font_family(FONT_SANS) + .text_color(palette.text_primary) + .child( + div() + .id("desktop.collection_editor.backdrop") + .snapshot( + "desktop.collection_editor.backdrop", + Some("desktop.shell.root"), + ) + .absolute() + .inset_0() + .occlude() + .bg(palette.scrim) + .on_click(move |_, _, app| dismiss.cancel(app)), + ) + .child(card); + Some( + ui::deferred( + ui::anchored() + .position(ui::point(px(0.0), px(0.0))) + .child(layer), + ) + .priority(1) + .into_any_element(), + ) + } +} + +/// `RadioGroup` of `Docs` and `Rules`. +fn mode_switch(rules: bool, ecx: &EditorCx) -> impl IntoElement { + let palette = ecx.palette; + let item = |id: &'static str, label: &'static str, active: bool, to_rules: bool| { + let ecx = ecx.clone(); + div() + .id(id) + .snapshot(id, Some("desktop.collection_editor")) + .when(active, |item| item.snapshot_focused(true)) + .flex() + .flex_1() + .items_center() + .justify_center() + .h(px(24.0)) + .px(px(8.0)) + .rounded(px(6.0)) + .text_size(px(14.0)) + .cursor_pointer() + .when(active, |item| { + item.bg(palette.bg_elevated) + .font_weight(FontWeight::MEDIUM) + .shadow(crate::theme_shadow(ecx.theme, "--affine-shadow-1")) + }) + .when(!active, |item| item.text_color(palette.text_secondary)) + .child(label) + .on_click(move |_, _, app| { + ecx.set_menu(app, None); + ecx.edit(app, |editor| editor.rules = to_rules); + }) + }; + div() + .flex() + .flex_shrink(0.0) + .min_w(px(158.0)) + .p(px(2.0)) + .gap(px(2.0)) + .rounded(px(8.0)) + .bg(palette.bg_pill) + .child(item( + "desktop.collection_editor.mode.pages", + "Docs", + !rules, + false, + )) + .child(item( + "desktop.collection_editor.mode.rules", + "Rules", + rules, + true, + )) +} + +/// `Cancel` and `Save`. `Save` is off while the name is blank. +fn action_buttons(editor: &CollectionEditor, ecx: &EditorCx) -> impl IntoElement { + let palette = ecx.palette; + let can_save = editor.can_save(); + let cancel = ecx.clone(); + let save = ecx.clone(); + div() + .flex() + .flex_shrink(0.0) + .items_center() + .gap(px(20.0)) + .child( + button("desktop.collection_editor.cancel", "Cancel", palette, true) + .snapshot( + "desktop.collection_editor.cancel", + Some("desktop.collection_editor"), + ) + .min_w(px(80.0)) + .border_1() + .border_color(palette.border) + .on_click(move |_, _, app| cancel.cancel(app)), + ) + .child( + button_with_fill( + "desktop.collection_editor.save", + "Save", + palette, + can_save, + Some(palette.accent), + ) + .snapshot( + "desktop.collection_editor.save", + Some("desktop.collection_editor"), + ) + .min_w(px(80.0)) + .when(can_save, |button| { + button.on_click(move |_, _, app| save.save(app)) + }), + ) +} + +/// One document row: the check box in `Docs` mode, the mode icon, the title, and the time +/// of the last change. +fn doc_row( + doc: &crate::doc_store::DesktopDocMeta, + checked: Option, + palette: DesktopPalette, +) -> ui::Stateful { + let icon = if doc.default_mode == affine_store::directory::DocMode::Edgeless { + crate::EDGELESS_ICON_SVG + } else { + crate::DOC_ICON_SVG + }; + let title = if doc.title.is_empty() { + "Untitled".to_owned() + } else { + doc.title.clone() + }; + div() + .id(ElementId::NamedInteger( + "desktop.collection_editor.row".into(), + ui::hash(&doc.id), + )) + .flex() + .items_center() + .gap(px(8.0)) + .h(px(ROW_HEIGHT)) + .px(px(16.0)) + .rounded(px(4.0)) + .hover(move |style| style.bg(palette.hover_color)) + .children(checked.map(|checked| selection_icon(checked, palette))) + .child( + ui::svg() + .data(icon) + .size(px(18.0)) + .flex_shrink(0.0) + .text_color(palette.text_secondary), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_size(px(14.0)) + .font_weight(FontWeight::MEDIUM) + .child(title), + ) + .child( + div() + .flex_shrink(0.0) + .text_size(px(12.0)) + .text_color(palette.text_muted) + .child(display_time(Some(doc.updated_at_ms))), + ) +} + +/// A list of `heights.len()` rows in `height` pixels that mounts only the rows in view. +fn virtual_rows( + id: &'static str, + heights: Vec, + height: f32, + (view, preview): (&Entity, bool), + app: &App, + mut row: impl FnMut(usize) -> AnyElement, +) -> ui::Stateful { + let list = VirtualList::variable(heights); + let max_scroll = (list.total_height() - height).max(0.0); + let stored = if preview { + view.read(app).preview_scroll + } else { + view.read(app).list_scroll + }; + let offset = ScrollAxis::new(stored, max_scroll).offset; + let slice = list.window(height, offset, 6.0 * ROW_HEIGHT); + let mut rows = div() + .relative() + .top(px(slice.leading_spacer - offset)) + .flex() + .flex_col() + .w_full(); + for index in slice.visible_range { + rows = rows.child(row(index)); + } + let view = view.clone(); + div() + .id(id) + .snapshot(id, Some("desktop.collection_editor")) + .h(px(height)) + .w_full() + .overflow_hidden() + .on_scroll(move |event, _, app| { + view.update(app, |view, cx| { + let (_, dy) = wheel_delta(event, 0.0); + let scroll = if preview { + &mut view.preview_scroll + } else { + &mut view.list_scroll + }; + let mut axis = ScrollAxis::new(*scroll, max_scroll); + if axis.apply(dy) { + *scroll = axis.offset; + cx.stop_propagation(); + cx.notify(); + } + }); + }) + .child(rows) +} + +/// The centered empty state with a title and a tip. +fn empty_state( + id: &'static str, + title: &'static str, + tip: Option, + palette: DesktopPalette, +) -> impl IntoElement { + div() + .snapshot(id, Some("desktop.collection_editor")) + .flex() + .flex_col() + .flex_1() + .items_center() + .justify_center() + .gap(px(18.0)) + .py(px(48.0)) + .px(px(16.0)) + .child( + div() + .text_size(px(20.0)) + .line_height(px(28.0)) + .font_weight(FontWeight::SEMIBOLD) + .child(title), + ) + .children(tip.map(|tip| { + max_width(div(), px(389.0)) + .text_size(px(15.0)) + .line_height(px(24.0)) + .text_color(palette.text_secondary) + .text_align(ui::TextAlign::Center) + .child(tip) + })) +} diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/pages_mode.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/pages_mode.rs new file mode 100644 index 0000000000..2145b4460a --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/pages_mode.rs @@ -0,0 +1,166 @@ +//! `Docs` mode (`SelectPage`): pick the documents of the allow list from a searchable list. + +use ui::{ + App, Div, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, + Window, div, px, +}; + +use super::button; +use super::{ + BAR_HEIGHT, EditorCx, ROW_HEIGHT, TAB_ROW_HEIGHT, action_buttons, doc_row, empty_state, + mode_switch, virtual_rows, +}; +use crate::{DesktopFlexExt as _, doc_store::DesktopDocStore, state::CollectionEditor}; + +/// The documents that are not in Trash and whose titles contain the search text, most +/// recently changed first. +pub(super) fn page_doc_ids(store: &DesktopDocStore, search: &str) -> Vec { + let search = search.trim().to_lowercase(); + store + .visible_docs() + .into_iter() + .filter(|doc| search.is_empty() || doc.title.to_lowercase().contains(&search)) + .map(|doc| doc.id.clone()) + .collect() +} + +pub(super) fn render( + editor: &CollectionEditor, + store: &DesktopDocStore, + ecx: &EditorCx, + height: f32, + window: &mut Window, + app: &mut App, +) -> Div { + let palette = ecx.palette; + let search = ecx.field( + ("desktop.collection_editor.search", None, 0), + "Search doc...", + &editor.search, + 20.0, + window, + app, + |editor, text| editor.search = text.to_owned(), + ); + let ids = page_doc_ids(store, &editor.search); + let list_height = (height - 2.0 * BAR_HEIGHT - TAB_ROW_HEIGHT).max(0.0); + let list = if ids.is_empty() { + let tip = (!editor.search.trim().is_empty()) + .then(|| format!("No doc titles contain {}", editor.search.trim())); + empty_state("desktop.collection_editor.empty", "Empty", tip, palette).into_any_element() + } else { + let selected = editor.value.allow_list.clone(); + virtual_rows( + "desktop.collection_editor.list", + vec![ROW_HEIGHT; ids.len()], + list_height, + (&ecx.view, false), + app, + |index| { + let id = &ids[index]; + let Some(entry) = store.get_doc(id) else { + return div().h(px(ROW_HEIGHT)).into_any_element(); + }; + let checked = selected.contains(id); + let (ecx, id) = (ecx.clone(), id.clone()); + doc_row(&entry.meta, Some(checked), palette) + .snapshot( + ui::snap_id!("desktop.collection_editor.doc.{id}"), + Some("desktop.collection_editor"), + ) + .snapshot_focused(checked) + .cursor_pointer() + .on_click(move |_, _, app| ecx.edit(app, |editor| editor.toggle_doc(&id))) + .into_any_element() + }, + ) + .into_any_element() + }; + let count = editor.value.allow_list.len().to_string(); + let clear = ecx.clone(); + div() + .flex() + .flex_col() + .size_full() + .child( + div() + .flex() + .flex_shrink(0.0) + .items_center() + .min_h(px(BAR_HEIGHT)) + .px(px(16.0)) + .border_b_1() + .border_color(palette.border) + .child(div().flex_1().min_w_0().child(search)), + ) + .child( + div() + .flex() + .flex_1() + .flex_col() + .min_h_0() + .overflow_hidden() + .child( + div() + .flex() + .flex_shrink(0.0) + .items_center() + .justify_between() + .h(px(TAB_ROW_HEIGHT)) + .pt(px(8.0)) + .px(px(16.0)) + .child(mode_switch(false, ecx)), + ) + .child(list), + ) + .child( + div() + .flex() + .flex_shrink(0.0) + .flex_wrap() + .items_center() + .justify_between() + .gap(px(12.0)) + .min_h(px(BAR_HEIGHT)) + .py(px(16.0)) + .px(px(24.0)) + .border_t_1() + .border_color(palette.border) + .child( + div() + .flex() + .items_center() + .gap(px(18.0)) + .text_size(px(12.0)) + .font_weight(ui::FontWeight::MEDIUM) + .child( + div() + .snapshot( + "desktop.collection_editor.selected", + Some("desktop.collection_editor"), + ) + .snapshot_text(count.clone()) + .flex() + .gap(px(7.0)) + .child("Selected") + .child(div().text_color(palette.accent).child(count)), + ) + .child( + button( + "desktop.collection_editor.clear", + "Clear selected", + palette, + true, + ) + .snapshot( + "desktop.collection_editor.clear", + Some("desktop.collection_editor"), + ) + .on_click(move |_, _, app| { + clear.edit(app, |editor| editor.value.allow_list.clear()) + }), + ), + ) + .child(action_buttons(editor, ecx)), + ) +} diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/rules_mode.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/rules_mode.rs new file mode 100644 index 0000000000..2b781153a7 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/rules_mode.rs @@ -0,0 +1,441 @@ +//! `Rules` mode (`RulesMode`): the filters and the allow list at the start, and the documents +//! that they hold at the end. + +use ui::{ + AnyElement, App, Div, FontWeight, InteractiveElement, IntoElement, ParentElement, + StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder as _, px, svg, +}; +use ui_tokens::icons; + +use super::{ + BAR_HEIGHT, EditorCx, ROW_HEIGHT, TAB_ROW_HEIGHT, action_buttons, doc_row, empty_state, + filter_bar, filter_menu, mode_switch, virtual_rows, +}; +use super::{button, button_with_fill}; +use crate::{DesktopFlexExt as _, doc_store::DesktopDocStore, state::CollectionEditor}; + +/// The height of the empty state in the preview (`RulesEmpty`). +const EMPTY_HEIGHT: f32 = 300.0; +/// The height of the `Selected docs` header in the preview. +const GROUP_HEIGHT: f32 = 42.0; + +enum PreviewRow<'a> { + Doc(&'a str), + Empty, + AllowListHeader, +} + +/// Returns the dialog body and the open menu. +pub(super) fn render( + editor: &CollectionEditor, + store: &DesktopDocStore, + ecx: &EditorCx, + (width, height): (f32, f32), + window: &mut Window, + app: &mut App, +) -> (Div, Option) { + let palette = ecx.palette; + let filtered = if editor.value.filters.is_empty() { + Vec::new() + } else { + store.filtered_doc_ids(&editor.value) + }; + let viewport = f32::from(window.viewport_size().height); + let menu = ecx.view.read(app).menu.and_then(|(menu, position)| { + filter_menu::render(menu, editor, store, ecx, viewport, app).map(|panel| { + ui::deferred(ui::anchored().position(position).child(panel)) + .priority(2) + .into_any_element() + }) + }); + let tips = div() + .snapshot( + "desktop.collection_editor.rules.tips", + Some("desktop.collection_editor"), + ) + .flex() + .flex_shrink(0.0) + .items_center() + .gap(px(5.0)) + .min_h(px(BAR_HEIGHT)) + .px(px(24.0)) + .border_b_1() + .border_color(palette.border) + .overflow_hidden() + .text_size(px(20.0)) + .line_height(px(24.0)) + .text_color(palette.text_secondary) + .child( + div() + .min_w_0() + .truncate() + .child("Docs that meet the rules will be added to the current collection"), + ) + .child( + div() + .flex_shrink(0.0) + .italic() + .font_weight(FontWeight::EXTRA_BOLD) + .text_color(palette.accent) + .child("automatically"), + ); + let left = div() + .flex() + .flex_1() + .flex_col() + .min_w_0() + .overflow_hidden() + .child( + div() + .flex() + .flex_shrink(0.0) + .items_center() + .h(px(TAB_ROW_HEIGHT)) + .pt(px(8.0)) + .px(px(16.0)) + .child(mode_switch(true, ecx)), + ) + .child(super::vertical_scroll( + ui::ElementId::Name( + format!("desktop.collection_editor.rules.scroll.{}", ecx.session).into(), + ), + div() + .flex() + .flex_col() + .gap(px(8.0)) + .pt(px(12.0)) + .px(px(16.0)) + .pb(px(16.0)) + .child(filter_bar::render(editor, store, ecx, window, app)) + .child(allow_list(editor, store, ecx)), + )); + let body_height = (height - 2.0 * BAR_HEIGHT).max(0.0); + let mut columns = div() + .flex() + .flex_1() + .min_h_0() + .overflow_hidden() + .child(left); + if editor.preview { + columns = columns.child( + div() + .flex() + .flex_col() + .flex_shrink(0.0) + .w(px(width * 2.0 / 3.0)) + .border_l_1() + .border_color(palette.border) + .child(preview(editor, store, &filtered, ecx, body_height, app)), + ); + } + let toggle_preview = ecx.clone(); + let reset = ecx.clone(); + let footer = div() + .flex() + .flex_shrink(0.0) + .flex_wrap() + .items_center() + .justify_between() + .gap(px(12.0)) + .min_h(px(BAR_HEIGHT)) + .py(px(16.0)) + .px(px(24.0)) + .border_t_1() + .border_color(palette.border) + .child( + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.0)) + .child( + button_with_fill( + "desktop.collection_editor.preview", + "Preview", + palette, + true, + None, + ) + .snapshot( + "desktop.collection_editor.preview", + Some("desktop.collection_editor"), + ) + .snapshot_focused(editor.preview) + .border_1() + .border_color(palette.border) + .on_click(move |_, _, app| { + toggle_preview.edit(app, |editor| editor.preview = !editor.preview) + }), + ) + .child( + button("desktop.collection_editor.reset", "Reset", palette, true) + .snapshot( + "desktop.collection_editor.reset", + Some("desktop.collection_editor"), + ) + .on_click(move |_, _, app| { + reset.set_menu(app, None); + reset.edit(app, CollectionEditor::reset); + }), + ) + .child(count_tips( + editor.value.allow_list.len(), + filtered.len(), + ecx, + )), + ) + .child(action_buttons(editor, ecx)); + ( + div() + .flex() + .flex_col() + .size_full() + .child(tips) + .child(columns) + .child(footer), + menu, + ) +} + +/// `Selected , filtered `. +fn count_tips(selected: usize, filtered: usize, ecx: &EditorCx) -> impl IntoElement { + let palette = ecx.palette; + let number = |value: usize| div().text_color(palette.accent).child(value.to_string()); + div() + .snapshot( + "desktop.collection_editor.count", + Some("desktop.collection_editor"), + ) + .snapshot_text(format!("Selected {selected}, filtered {filtered}")) + .flex() + .items_center() + .text_size(px(12.0)) + .line_height(px(20.0)) + .text_color(palette.text_secondary) + .child("Selected ") + .child(number(selected)) + .child(", filtered ") + .child(number(filtered)) +} + +/// The `Selected docs` toggle and one `Doc is ` chip for each allowed document. +fn allow_list(editor: &CollectionEditor, store: &DesktopDocStore, ecx: &EditorCx) -> Div { + let palette = ecx.palette; + let ids = &editor.value.allow_list; + let mut section = div().flex().flex_col().gap(px(8.0)).flex_shrink(0.0); + if ids.is_empty() { + return section; + } + let toggle = ecx.clone(); + section = section.child( + div() + .id("desktop.collection_editor.include.toggle") + .snapshot( + "desktop.collection_editor.include.toggle", + Some("desktop.collection_editor"), + ) + .snapshot_focused(editor.include_open) + .flex() + .items_center() + .gap(px(10.0)) + .text_size(px(14.0)) + .line_height(px(22.0)) + .cursor_pointer() + .child( + svg() + .data(if editor.include_open { + icons::TOGGLE_DOWN.svg.as_bytes() + } else { + icons::TOGGLE_RIGHT.svg.as_bytes() + }) + .size(px(20.0)) + .text_color(palette.text_secondary), + ) + .child( + div() + .text_color(palette.text_secondary) + .child("Selected docs"), + ) + .on_click(move |_, _, app| { + toggle.edit(app, |editor| editor.include_open = !editor.include_open) + }), + ); + if !editor.include_open { + return section; + } + let mut chips = div().flex().flex_wrap().gap(px(8.0)); + for id in ids { + let entry = store.get_doc(id); + let edgeless = entry.is_some_and(|entry| { + entry.meta.default_mode == affine_store::directory::DocMode::Edgeless + }); + let trashed = entry.is_none_or(|entry| entry.meta.trashed); + let title = entry + .map(|entry| entry.meta.title.clone()) + .filter(|title| !title.is_empty()) + .unwrap_or_else(|| "Untitled".into()); + let remove = ecx.clone(); + let removed = id.clone(); + chips = chips.child( + super::max_width(div(), ui::relative(1.0)) + .snapshot( + ui::snap_id!("desktop.collection_editor.include.{id}"), + Some("desktop.collection_editor"), + ) + .snapshot_text(title.clone()) + .flex() + .items_center() + .gap(px(16.0)) + .overflow_hidden() + .py(px(4.0)) + .px(px(8.0)) + .rounded(px(8.0)) + .border_1() + .border_color(palette.border) + .bg(palette.bg_canvas) + .text_size(px(12.0)) + .line_height(px(20.0)) + .child( + div() + .flex() + .min_w_0() + .items_center() + .gap(px(4.0)) + .child( + svg() + .data(if edgeless { + crate::EDGELESS_ICON_SVG + } else { + crate::DOC_ICON_SVG + }) + .size(px(16.0)) + .flex_shrink(0.0) + .text_color(palette.text_secondary), + ) + .child(div().flex_shrink(0.0).child("Doc")) + .child( + div() + .flex_shrink(0.0) + .px(px(8.0)) + .text_color(palette.text_secondary) + .child("is"), + ) + .child( + div() + .min_w_0() + .truncate() + .font_weight(FontWeight::SEMIBOLD) + .when(trashed, |title| title.text_color(palette.text_muted)) + .child(title), + ), + ) + .child( + div() + .id(ui::ElementId::NamedInteger( + "desktop.collection_editor.include.remove".into(), + ui::hash(id), + )) + .snapshot( + ui::snap_id!("desktop.collection_editor.include.remove.{id}"), + Some("desktop.collection_editor"), + ) + .flex_shrink(0.0) + .cursor_pointer() + .child( + svg() + .data(icons::CLOSE.svg.as_bytes()) + .size(px(14.0)) + .text_color(palette.text_secondary), + ) + .on_click(move |_, _, app| { + remove.edit(app, |editor| { + editor.value.allow_list.retain(|doc| doc != &removed) + }) + }), + ), + ); + } + section.child(chips) +} + +/// The documents that the filters match, then the `Selected docs` group. +fn preview( + editor: &CollectionEditor, + store: &DesktopDocStore, + filtered: &[String], + ecx: &EditorCx, + height: f32, + app: &App, +) -> ui::Stateful<Div> { + let palette = ecx.palette; + let mut rows: Vec<PreviewRow> = if filtered.is_empty() { + vec![PreviewRow::Empty] + } else { + filtered.iter().map(|id| PreviewRow::Doc(id)).collect() + }; + rows.push(PreviewRow::AllowListHeader); + rows.extend(editor.value.allow_list.iter().map(|id| PreviewRow::Doc(id))); + let heights = rows + .iter() + .map(|row| match row { + PreviewRow::Doc(_) => ROW_HEIGHT, + PreviewRow::Empty => EMPTY_HEIGHT, + PreviewRow::AllowListHeader => GROUP_HEIGHT, + }) + .collect(); + let no_rules = editor.value.filters.is_empty(); + virtual_rows( + "desktop.collection_editor.preview_list", + heights, + height, + (&ecx.view, true), + app, + |index| match rows[index] { + PreviewRow::Doc(id) => store.get_doc(id).map_or_else( + || div().h(px(ROW_HEIGHT)).into_any_element(), + |entry| { + doc_row(&entry.meta, None, palette) + .mx(px(12.0)) + .into_any_element() + }, + ), + PreviewRow::Empty => div() + .flex() + .h(px(EMPTY_HEIGHT)) + .child(if no_rules { + empty_state( + "desktop.collection_editor.preview.no_rules", + "No rules", + Some( + "Please add rules to save this collection or switch to Docs, use \ + manual selection mode" + .into(), + ), + palette, + ) + } else { + empty_state( + "desktop.collection_editor.preview.no_results", + "No results", + Some("No docs meet the filtering rules".into()), + palette, + ) + }) + .into_any_element(), + PreviewRow::AllowListHeader => div() + .flex() + .items_center() + .h(px(GROUP_HEIGHT)) + .mx(px(12.0)) + .px(px(8.0)) + .pt(px(8.0)) + .border_t_1() + .border_color(palette.border) + .text_size(px(14.0)) + .line_height(px(22.0)) + .text_color(palette.text_secondary) + .child("Selected docs") + .into_any_element(), + }, + ) +} diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/tests.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/tests.rs new file mode 100644 index 0000000000..ad2cde3691 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/collection_editor/tests.rs @@ -0,0 +1,570 @@ +use std::rc::Rc; + +use affine_store::workspace_db::{CollectionFilter, WorkspaceCollection}; +use ui::{ + AnyWindowHandle, AppContext, Application, ApplicationHandle, Bounds, Context, HeadlessPlatform, + HeadlessWindow, Keystroke, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, + PlatformInput, Window, WindowBounds, WindowHandle, WindowOptions, point, px, size, +}; +use ui_tokens::ThemeMode; + +use crate::{ + DesktopAppState, DesktopRoute, DesktopShellView, doc_store::LocalUpdates, + register_desktop_fonts, +}; + +const RUST: &str = "col-rust-core"; + +/// A shell of the first local workspace that writes to `storage`. +struct Shell { + app: ApplicationHandle, + handle: WindowHandle<DesktopShellView>, + window: HeadlessWindow, + platform: Rc<HeadlessPlatform>, +} + +impl Shell { + fn open(storage: &Rc<LocalUpdates>, (width, height): (u32, u32)) -> Self { + let (state, sessions) = + DesktopAppState::open_local(&storage.0.borrow(), ThemeMode::Light, "2026-12-03", 123) + .expect("local workspace"); + let platform = HeadlessPlatform::new(width, height, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let storage = storage.clone(); + 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(width as f32), px(height as f32)), + ))), + ..WindowOptions::default() + }, + |_, cx| { + cx.new(|cx| { + let mut view = DesktopShellView::new(state, cx); + view.bind_local_workspaces(sessions, storage, 123, cx); + view + }) + }, + ) + .expect("desktop window") + }); + let window = platform.windows().remove(0); + let shell = Self { + app, + handle, + window, + platform, + }; + shell.frame(); + shell + } + + fn frame(&self) { + self.window.request_frame(); + self.platform.run_until_parked(); + } + + fn shell<T>( + &self, + f: impl FnOnce(&mut DesktopShellView, &mut Window, &mut Context<DesktopShellView>) -> T, + ) -> T { + self.app + .update(|cx| self.handle.update(cx, f).expect("desktop shell")) + } + + fn contains(&self, id: &str) -> bool { + self.shell(|_, window, _| window.frame_snapshot().elements.contains_key(id)) + } + + fn text(&self, id: &str) -> Option<String> { + self.shell(|_, window, _| window.frame_snapshot().elements.get(id)?.text.clone()) + } + + fn press(&self, id: &str, button: MouseButton) { + let position = self.shell(|_, window, _| { + let area = window.frame_snapshot().elements[id].bounds; + point( + px(area.x + area.width / 2.0), + px(area.y + area.height / 2.0), + ) + }); + self.press_at(position, button); + } + + fn press_at(&self, position: ui::Point<ui::Pixels>, button: MouseButton) { + self.window + .dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { + position, + pressed_button: None, + modifiers: Default::default(), + })); + for down in [true, false] { + self.window.dispatch_input(if down { + PlatformInput::MouseDown(MouseDownEvent { + position, + button, + modifiers: Default::default(), + click_count: 1, + ..Default::default() + }) + } else { + PlatformInput::MouseUp(MouseUpEvent { + position, + button, + modifiers: Default::default(), + click_count: 1, + }) + }); + } + self.frame(); + } + + fn click(&self, id: &str) { + self.press(id, MouseButton::Left); + } + + fn key(&self, key: &'static str) { + self.app.update(|cx| { + AnyWindowHandle::from(self.handle) + .update(cx, |_, window, cx| { + window.dispatch_keystroke(Keystroke::parse(key).expect("valid key"), cx); + }) + .expect("desktop window"); + }); + self.frame(); + } + + fn collection(&self) -> WorkspaceCollection { + self.shell(|shell, _, _| { + shell + .state + .store + .collection_record(RUST) + .expect("collection") + }) + } + + fn members(&self) -> Vec<String> { + self.shell(|shell, _, _| { + shell + .state + .store + .docs_for_collection(RUST) + .iter() + .map(|doc| doc.id.clone()) + .collect() + }) + } + + fn editor_open(&self) -> bool { + self.shell(|shell, _, _| shell.state.collection_editor.is_some()) + } +} + +fn filter(key: &str, method: &str, value: Option<&str>) -> CollectionFilter { + CollectionFilter { + kind: "system".into(), + key: key.into(), + method: method.into(), + value: value.map(Into::into), + } +} + +#[test] +fn collection_editor_opens_in_the_mode_of_each_entry_and_cancels_without_writing() { + let storage = Rc::new(LocalUpdates::default()); + let app = Shell::open(&storage, (1280, 800)); + let before = app.collection(); + // (open the editor, mode switch that is on) + let entries: [(&dyn Fn(&Shell), &str); 3] = [ + ( + &|app| { + app.press(&format!("desktop.sidebar.col.{RUST}"), MouseButton::Right); + app.click("Edit collection"); + }, + "desktop.collection_editor.mode.rules", + ), + ( + &|app| { + app.press(&format!("desktop.sidebar.col.{RUST}"), MouseButton::Right); + app.click("Add docs"); + }, + "desktop.collection_editor.mode.pages", + ), + ( + &|app| { + app.shell(|shell, _, cx| { + shell + .state + .navigate_active_pane(DesktopRoute::Collection(RUST.into())); + cx.notify(); + }); + app.frame(); + app.click("desktop.explorer.collection.edit"); + }, + "desktop.collection_editor.mode.rules", + ), + ]; + for (index, (open, mode)) in entries.into_iter().enumerate() { + open(&app); + assert!(app.contains("desktop.collection_editor"), "entry {index}"); + assert!( + app.shell(|_, window, _| window.frame_snapshot().elements[mode].focused), + "entry {index}: {mode}" + ); + app.click("desktop.collection_editor.mode.pages"); + app.click(&format!("desktop.collection_editor.doc.{}", "doc-board")); + // Escape and the backdrop cancel the edit. + if index == 0 { + app.key("escape"); + } else if index == 1 { + app.click("desktop.collection_editor.cancel"); + } else { + // The dialog covers the middle of the backdrop. + app.press_at(point(px(8.0), px(8.0)), MouseButton::Left); + } + assert!(!app.editor_open(), "entry {index}"); + assert_eq!(app.collection(), before, "entry {index}"); + } +} + +#[test] +fn collection_editor_saves_docs_and_rules_that_survive_a_cold_reopen() { + let storage = Rc::new(LocalUpdates::default()); + let app = Shell::open(&storage, (1280, 800)); + assert_eq!(app.members(), ["doc-arch", "doc-sync"]); + + // `Docs` mode: add a document to the allow list. + app.shell(|shell, _, cx| { + assert!(shell.state.open_collection_editor(RUST, Some(false))); + cx.notify(); + }); + app.frame(); + app.click("desktop.collection_editor.doc.doc-board"); + assert_eq!( + app.text("desktop.collection_editor.selected").as_deref(), + Some("1") + ); + app.click("desktop.collection_editor.save"); + assert!(!app.editor_open()); + assert_eq!(app.collection().allow_list, ["doc-board"]); + assert!(app.members().contains(&"doc-board".to_owned())); + + // `Rules` mode: replace the tag rule with `Tags` and `Doc mode` conditions. + app.shell(|shell, _, cx| { + assert!(shell.state.open_collection_editor(RUST, None)); + cx.notify(); + }); + app.frame(); + app.click("desktop.collection_editor.filter.remove.0"); + app.click("desktop.collection_editor.add_filter"); + app.click("desktop.collection_editor.menu.item.1"); + app.click("desktop.collection_editor.filter.method.0"); + // `contains one of` + app.click("desktop.collection_editor.menu.item.1"); + app.click("desktop.collection_editor.filter.value.0"); + let tags = app.shell(|shell, _, _| shell.state.store.all_tags_with_counts()); + let design = tags + .iter() + .position(|(tag, _, _)| tag == "design") + .expect("design tag"); + app.click(&format!("desktop.collection_editor.menu.item.{design}")); + app.key("escape"); + assert!(app.editor_open(), "the first Escape closes the menu"); + app.click("desktop.collection_editor.add_filter"); + // `Doc mode` opens its value menu with `Page` and `Edgeless`. + app.click("desktop.collection_editor.menu.item.5"); + app.click("desktop.collection_editor.menu.item.1"); + assert_eq!( + app.text("desktop.collection_editor.count").as_deref(), + Some("Selected 1, filtered 1") + ); + app.click("desktop.collection_editor.save"); + let expected = WorkspaceCollection { + id: RUST.into(), + name: "Rust Native Core".into(), + allow_list: vec!["doc-board".into()], + filters: vec![ + filter("tags", "include-any-of", Some("design")), + filter("docPrimaryMode", "is", Some("edgeless")), + ], + }; + assert_eq!(app.collection(), expected); + assert_eq!(app.members(), ["doc-board"]); + app.shell(|shell, _, _| shell.save_local_workspaces()); + drop(app); + + let reopened = Shell::open(&storage, (1280, 800)); + assert_eq!(reopened.collection(), expected); + assert_eq!(reopened.members(), ["doc-board"]); +} + +#[test] +fn collection_editor_reset_restores_the_rules_and_a_narrow_window_contains_the_dialog() { + let storage = Rc::new(LocalUpdates::default()); + let app = Shell::open(&storage, (768, 600)); + app.shell(|shell, _, cx| { + assert!(shell.state.open_collection_editor(RUST, Some(true))); + cx.notify(); + }); + app.frame(); + let init = app.collection(); + app.click("desktop.collection_editor.filter.remove.0"); + assert_eq!( + app.text("desktop.collection_editor.count").as_deref(), + Some("Selected 0, filtered 0") + ); + assert!(app.contains("desktop.collection_editor.preview.no_rules")); + app.click("desktop.collection_editor.reset"); + assert_eq!( + app.shell(|shell, _, _| shell.state.collection_editor.clone()) + .map(|editor| editor.value), + Some(init) + ); + app.shell(|_, window, _| { + let elements = &window.frame_snapshot().elements; + let card = elements["desktop.collection_editor"].bounds; + assert!(card.x >= 0.0 && card.x + card.width <= 768.0); + assert!(card.y >= 0.0 && card.y + card.height <= 600.0); + for id in [ + "desktop.collection_editor.save", + "desktop.collection_editor.cancel", + "desktop.collection_editor.reset", + ] { + let button = elements[id].bounds; + assert!( + button.x >= card.x + && button.x + button.width <= card.x + card.width + && button.y + button.height <= card.y + card.height, + "{id}: {button:?} in {card:?}" + ); + } + }); +} + +impl Shell { + fn open_editor(&self, rules: Option<bool>) { + self.shell(|shell, _, cx| { + assert!(shell.state.open_collection_editor(RUST, rules)); + cx.notify(); + }); + self.frame(); + } + + fn bounds(&self, id: &str) -> ui::harness::SnapshotRect { + self.shell(|_, window, _| window.frame_snapshot().elements[id].bounds) + } + + fn menu_open(&self) -> bool { + self.contains("desktop.collection_editor.menu") + } +} + +#[test] +fn collection_editor_reset_rebuilds_the_condition_fields_that_the_preview_and_save_read() { + let storage = Rc::new(LocalUpdates::default()); + let app = Shell::open(&storage, (1280, 800)); + app.open_editor(Some(true)); + let offline = vec![filter("title", "match", Some("Offline"))]; + app.shell(|shell, _, cx| { + let editor = shell.state.collection_editor.as_mut().expect("editor"); + editor.init.filters = offline.clone(); + editor.value.filters = offline.clone(); + cx.notify(); + }); + app.frame(); + let field = "desktop.collection_editor.filter.text.0"; + let preview = |app: &Shell| { + app.shell(|shell, _, _| { + let state = &shell.state; + let editor = state.collection_editor.as_ref().expect("editor"); + state.store.filtered_doc_ids(&editor.value) + }) + }; + assert_eq!(app.text(field).as_deref(), Some("Offline")); + assert_eq!(preview(&app), ["doc-sync"]); + + app.click(field); + app.key("ctrl-a"); + for key in ["a", "r", "c", "h", "i", "t", "e", "c", "t", "u", "r", "e"] { + app.key(key); + } + assert_eq!(app.text(field).as_deref(), Some("architecture")); + assert_eq!(preview(&app), ["doc-arch"]); + + app.click("desktop.collection_editor.reset"); + // The field, the preview, and the saved rules show the same value. + assert_eq!(app.text(field).as_deref(), Some("Offline")); + assert_eq!(preview(&app), ["doc-sync"]); + assert_eq!( + app.text("desktop.collection_editor.count").as_deref(), + Some("Selected 0, filtered 1") + ); + app.click("desktop.collection_editor.save"); + assert!(!app.editor_open()); + assert_eq!(app.collection().filters, offline); +} + +#[test] +fn collection_editor_tag_menu_scrolls_by_wheel_and_keys_in_a_short_window() { + let storage = Rc::new(LocalUpdates::default()); + let app = Shell::open(&storage, (768, 600)); + let tags = app.shell(|shell, _, _| { + let store = &mut shell.state.store; + let mut next = 0; + while store.all_tags_with_counts().len() < 29 { + next += 1; + assert!(store.create_tag(&format!("label {next:02}"))); + } + store.all_tags_with_counts() + }); + assert_eq!(tags.len(), 29); + app.open_editor(Some(true)); + app.click("desktop.collection_editor.filter.remove.0"); + app.click("desktop.collection_editor.add_filter"); + // `Tags`, then `contains all`, then the tag menu. + app.click("desktop.collection_editor.menu.item.1"); + app.click("desktop.collection_editor.filter.method.0"); + app.click("desktop.collection_editor.menu.item.0"); + app.click("desktop.collection_editor.filter.value.0"); + let last = "desktop.collection_editor.menu.item.28"; + let rows = app.bounds("desktop.collection_editor.menu.rows"); + let menu = app.bounds("desktop.collection_editor.menu"); + assert!(menu.y >= 0.0 && menu.y + menu.height <= 600.0, "{menu:?}"); + assert!( + app.bounds(last).y >= rows.y + rows.height, + "the last tag starts hidden" + ); + + // The wheel scrolls the last tag into the rows. + app.window + .dispatch_input(PlatformInput::Scroll(ui::ScrollEvent { + position: point(px(rows.x + 20.0), px(rows.y + 20.0)), + delta: ui::ScrollDelta::Pixels(point(px(0.0), px(-800.0))), + ..Default::default() + })); + app.frame(); + let shown = app.bounds(last); + assert!( + shown.y >= rows.y && shown.y + shown.height <= rows.y + rows.height, + "{shown:?} in {rows:?}" + ); + app.click(last); + let value = |app: &Shell| { + app.shell(|shell, _, _| { + shell + .state + .collection_editor + .as_ref() + .expect("editor") + .value + .filters[0] + .value + .clone() + }) + }; + assert_eq!(value(&app), Some(tags[28].0.clone())); + + // Up before any row reaches the last row, and Enter toggles it like a click. + app.key("escape"); + assert!(!app.menu_open() && app.editor_open()); + app.click("desktop.collection_editor.filter.value.0"); + app.key("up"); + let shown = app.bounds(last); + let rows = app.bounds("desktop.collection_editor.menu.rows"); + assert!( + shown.y >= rows.y && shown.y + shown.height <= rows.y + rows.height && shown.y < 600.0, + "{shown:?} in {rows:?}" + ); + app.key("enter"); + assert_eq!(value(&app), Some(String::new())); + assert!(app.menu_open(), "the tag menu stays open"); +} + +#[test] +fn collection_editor_add_filter_menu_takes_arrow_keys_enter_and_escape() { + let storage = Rc::new(LocalUpdates::default()); + let app = Shell::open(&storage, (1280, 800)); + app.open_editor(Some(true)); + let count = |app: &Shell| { + app.shell(|shell, _, _| { + shell + .state + .collection_editor + .as_ref() + .expect("editor") + .value + .filters + .len() + }) + }; + let before = count(&app); + app.click("desktop.collection_editor.add_filter"); + app.key("escape"); + assert!(!app.menu_open() && app.editor_open()); + assert_eq!(count(&app), before); + + // `Favourited`, then `Tags`: `is not empty` has no value menu. + app.click("desktop.collection_editor.add_filter"); + app.key("down"); + app.key("down"); + app.key("enter"); + assert!(!app.menu_open()); + assert_eq!(count(&app), before + 1); + assert_eq!( + app.shell(|shell, _, _| shell.state.collection_editor.clone()) + .map(|editor| editor.value.filters[before].clone()), + Some(filter("tags", "is-not-empty", None)) + ); +} + +#[test] +fn collection_date_filters_read_document_times_in_the_local_zone() { + use affine_client::domain::LocalCalendar; + + use super::LocalZone; + + let storage = Rc::new(LocalUpdates::default()); + let app = Shell::open(&storage, (1280, 800)); + // (zone, 23:30 and 00:30 local time on 2026-12-03 and 2026-12-04) + for (tz, before, after) in [ + ("Asia/Tokyo", 1_796_308_200_000, 1_796_311_800_000), + ("America/Los_Angeles", 1_796_369_400_000, 1_796_373_000_000), + ] { + for (updated, method, value, expected) in [ + (after, "after", "2026-12-04", true), + (before, "after", "2026-12-04", false), + (before, "before", "2026-12-03", true), + (after, "before", "2026-12-03", false), + (after, "between", "2026-12-04,2026-12-04", true), + (before, "between", "2026-12-04,2026-12-04", false), + ] { + let matched = app.shell(|shell, _, _| { + let store = &mut shell.state.store; + let zone = LocalZone::from_tz(Some(tz)); + store.set_calendar( + "2026-12-04", + LocalCalendar::new(move |ms| zone.offset_minutes(ms)), + ); + store + .docs + .get_mut("doc-sync") + .expect("doc") + .meta + .updated_at_ms = updated; + store.touch_meta(); + let record = WorkspaceCollection { + filters: vec![filter("updatedAt", method, Some(value))], + ..store.collection_record(RUST).expect("collection") + }; + store + .filtered_doc_ids(&record) + .contains(&"doc-sync".to_owned()) + }); + assert_eq!(matched, expected, "{tz} {updated} {method} {value}"); + } + } +} diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/header.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/header.rs index 4e8bded264..360a0f5df8 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/header.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/header.rs @@ -6,10 +6,12 @@ use ui::{ }; use ui_tokens::{ThemeMode, icons::ARROW_DOWN_SMALL}; -use super::{Controls, Destination, Menu, Popup, tag_search::TagSearch}; +use super::{Controls, Destination, Menu, Popup, text_field::TextField}; use crate::{ - DesktopFlexExt, DesktopPalette, doc_store::DesktopDocStore, split_view::DesktopRoute, - views_extra::resolve_tag_color, + DesktopFlexExt, DesktopPalette, + doc_store::DesktopDocStore, + split_view::DesktopRoute, + views_extra::{button, resolve_tag_color}, }; /// `PageListNewPageButton`: the label creates a document of the default mode, and the arrow @@ -150,8 +152,15 @@ pub(super) fn tag_breadcrumb( let state = controls.state.clone(); move |event, window, app| { app.stop_propagation(); + let explorer = state.clone(); let search = app.new(|cx| { - TagSearch::new(cx.focus_handle(), palette, state.clone()) + TextField::tag_search( + cx.focus_handle(), + palette, + move |_, app| { + explorer.update(app, |_, cx| cx.notify()); + }, + ) }); let focus = search.read(app).focus.clone(); state.update(app, |state, cx| { @@ -175,3 +184,50 @@ pub(super) fn tag_breadcrumb( })), ) } + +/// `Edit` on the header of a collection (`CollectionListHeader`), or `Add docs` and +/// `Add rules` under an empty collection (`EmptyCollectionDetail`). Each one opens the +/// collection editor. +pub(super) fn collection_actions( + route: &DesktopRoute, + controls: &Controls, + palette: DesktopPalette, + writable: bool, + empty: bool, +) -> Option<Div> { + let DesktopRoute::Collection(id) = route else { + return None; + }; + let open = |rules: Option<bool>| { + let (shell, id) = (controls.shell.clone(), id.clone()); + move |_: &ui::ClickEvent, _: &mut ui::Window, app: &mut ui::App| { + app.stop_propagation(); + shell.update(app, |shell, cx| { + shell.state.open_collection_editor(&id, rules); + cx.notify(); + }); + } + }; + let action = |id: &'static str, label: &'static str, rules: Option<bool>| { + button(id, label, palette, writable) + .snapshot(id, Some("desktop.workbench")) + .border_1() + .border_color(palette.border) + .when(writable, |button| button.on_click(open(rules))) + }; + let row = div().flex().flex_shrink(0.0).justify_center().gap(px(8.0)); + Some(if empty { + row.child(action( + "desktop.explorer.collection.add_docs", + "Add docs", + Some(false), + )) + .child(action( + "desktop.explorer.collection.add_rules", + "Add rules", + Some(true), + )) + } else { + row.child(action("desktop.explorer.collection.edit", "Edit", None)) + }) +} diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs index ed27c44aa0..aa4238608c 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs @@ -1,10 +1,11 @@ mod cache; +mod collection_editor; mod confirm; mod header; mod menu; mod new_tab; mod rows; -mod tag_search; +mod text_field; use std::{cell::RefCell, collections::BTreeSet, rc::Rc}; @@ -18,7 +19,7 @@ use ui_tokens::FONT_SANS; use cache::ExplorerOrderCache; pub(super) use confirm::{TrashPrompt, render_trash_prompt}; -use header::{new_doc_button, tag_breadcrumb}; +use header::{collection_actions, new_doc_button, tag_breadcrumb}; use menu::render_menu; pub(super) use new_tab::open_in_new_tab; use rows::{doc_row, empty}; @@ -26,13 +27,14 @@ use rows::{doc_row, empty}; use super::{ PaneLocation, button, doc_order::{DocOrder, order_docs}, + journals::LocalZone, menu_button, scroll::{DocRowKey, RowStyle, virtual_scroll_shared}, update_tag, vertical_scroll, }; use crate::{ - COLLECTION_ICON_SVG, DesktopPalette, TAG_ICON_SVG, doc_store::DesktopDocMeta, - split_view::DesktopRoute, workbench::DesktopShellView, + COLLECTION_ICON_SVG, DesktopFlexExt as _, DesktopPalette, TAG_ICON_SVG, + doc_store::DesktopDocMeta, split_view::DesktopRoute, workbench::DesktopShellView, }; pub(crate) fn render_doc_list_view( @@ -66,7 +68,7 @@ enum Menu { Order, Filter, Tag, - TagSwitch(String, Entity<tag_search::TagSearch>), + TagSwitch(String, Entity<text_field::TextField>), NewDoc, } @@ -575,13 +577,24 @@ impl RenderOnce for DocsExplorer { tag_menu, )); } else if !overview && !matches!(on_route, DesktopRoute::AllDocs) { + let heading = div() + .snapshot("desktop.explorer.heading", Some("desktop.workbench")) + .snapshot_text(self.heading.clone()) + .flex_1() + .min_w_0() + .truncate() + .text_size(px(20.0)) + .font_weight(FontWeight::SEMIBOLD) + .child(self.heading); root = root.child( div() - .snapshot("desktop.explorer.heading", Some("desktop.workbench")) - .snapshot_text(self.heading.clone()) - .text_size(px(20.0)) - .font_weight(FontWeight::SEMIBOLD) - .child(self.heading), + .flex() + .items_center() + .gap(px(8.0)) + .child(heading) + .children(collection_actions( + on_route, &controls, palette, writable, false, + )), ); } if state.selecting @@ -720,7 +733,11 @@ impl RenderOnce for DocsExplorer { .as_ref() .is_some_and(|cached| cached.order_ids.is_empty()) { - content = content.child(empty("No documents", palette)); + content = content + .child(empty("No documents", palette)) + .children(collection_actions( + on_route, &controls, palette, writable, true, + )); } let scroll_key = format!("desktop.explorer.scroll.{}", self.pane_idx); root = if let Some(cached) = cached.filter(|cached| !cached.order_ids.is_empty()) { diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/tag_search.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/text_field.rs similarity index 80% rename from packages/frontend/desktop/src/views_extra/docs_explorer/tag_search.rs rename to packages/frontend/desktop/src/views_extra/docs_explorer/text_field.rs index 880d443117..d63ac925f7 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/tag_search.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/text_field.rs @@ -1,43 +1,85 @@ -//! The `Search tags` field at the top of the tag switcher (`TagSelectorMenu`). +//! A one-line text field with IME support: the `Search tags` field of the tag switcher +//! (`TagSelectorMenu`) and the fields of the collection editor. -use std::ops::Range; +use std::{ops::Range, rc::Rc}; use blocksuite_editor::inline_input::{Utf16ImeBuffer, utf16_len, utf16_to_byte}; use ui::{ - Bounds, ClipboardItem, Context, ElementInputHandler, Entity, EntityInputHandler, FocusHandle, + App, Bounds, ClipboardItem, Context, ElementInputHandler, EntityInputHandler, FocusHandle, InteractiveElement, IntoElement, KeyDownEvent, MouseButton, ParentElement, Pixels, Point, - Render, ShapedLine, Styled, TextAlign, TextRun, UTF16Selection, Window, canvas, div, fill, - point, px, size, svg, + Render, ShapedLine, SharedString, Styled, TextAlign, TextRun, UTF16Selection, Window, canvas, + div, fill, point, prelude::FluentBuilder as _, px, size, svg, }; use ui_tokens::icons::SEARCH; -use super::ExplorerState; -use crate::DesktopPalette; +use crate::{DesktopFlexExt as _, DesktopPalette}; -pub(super) struct TagSearch { +/// Receives the text after each edit. +type OnChange = Rc<dyn Fn(&str, &mut App)>; + +pub(super) struct TextField { buffer: Utf16ImeBuffer, pub(super) focus: FocusHandle, palette: DesktopPalette, bounds: Option<Bounds<Pixels>>, - /// The explorer filters the switcher rows by the query, so each edit renders it again. - explorer: Entity<ExplorerState>, + /// The snapshot ID of the field and of its parent. + snapshot: (SharedString, &'static str), + placeholder: &'static str, + /// Shows the search icon before the text. + search: bool, + text_size: Pixels, + on_change: OnChange, } -impl TagSearch { +impl TextField { + /// The `Search tags` field. The explorer filters the switcher rows by the query, so each + /// edit renders it again. + pub(super) fn tag_search( + focus: FocusHandle, + palette: DesktopPalette, + on_change: impl Fn(&str, &mut App) + 'static, + ) -> Self { + Self::new( + focus, + palette, + ( + "desktop.explorer.tag_search".into(), + "desktop.explorer.menu", + ), + "Search tags", + String::new(), + on_change, + ) + } + pub(super) fn new( focus: FocusHandle, palette: DesktopPalette, - explorer: Entity<ExplorerState>, + snapshot: (SharedString, &'static str), + placeholder: &'static str, + text: String, + on_change: impl Fn(&str, &mut App) + 'static, ) -> Self { Self { - buffer: Utf16ImeBuffer::new(String::new(), false), + buffer: Utf16ImeBuffer::new(text, false), focus, palette, bounds: None, - explorer, + snapshot, + placeholder, + search: true, + text_size: px(14.0), + on_change: Rc::new(on_change), } } + /// Hide the search icon and show the text at `size`. + pub(super) fn plain(mut self, size: f32) -> Self { + self.search = false; + self.text_size = px(size); + self + } + /// Whether `label` contains the query, ignoring case. pub(super) fn matches(&self, label: &str) -> bool { label @@ -48,7 +90,7 @@ impl TagSearch { fn changed(&self, window: &Window, cx: &mut Context<Self>) { window.notify_text_input_changed(&self.focus); window.notify_text_selection_changed(&self.focus); - self.explorer.update(cx, |_, cx| cx.notify()); + (self.on_change)(self.buffer.text(), cx); cx.notify(); } @@ -86,7 +128,7 @@ impl TagSearch { .buffer .key(key, stroke.modifiers.shift, command) .is_some() => {} - // `Escape` reaches the explorer, which closes the switcher. + // `Escape` reaches the parent, which closes the switcher or the dialog. _ => return, } self.changed(window, cx); @@ -106,7 +148,7 @@ impl TagSearch { font.fallbacks = Some(blocksuite_editor::default_font_fallbacks()); let empty = shown.is_empty(); let text = if empty { - "Search tags".to_owned() + self.placeholder.to_owned() } else { shown }; @@ -124,7 +166,7 @@ impl TagSearch { }; let line = window .text_system() - .shape_line(text.into(), px(14.0), &[run], None); + .shape_line(text.into(), self.text_size, &[run], None); let x = line.x_for_index(utf16_to_byte(&line.text, caret)); let scroll = (x - (bounds.size.width - px(1.0)).max(px(0.0))).max(px(0.0)); InputLine { @@ -169,7 +211,7 @@ impl InputLine { } } -impl Render for TagSearch { +impl Render for TextField { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let (selection, _) = self.buffer.shown_selection(); let marked = self.buffer.marked_range(); @@ -178,28 +220,33 @@ impl Render for TagSearch { let layout_entity = entity.clone(); let focus = self.focus.clone(); let palette = self.palette; + let (id, parent) = self.snapshot.clone(); + let line_height = (self.text_size * 1.5).max(px(22.0)); + let text = self.buffer.text().to_owned(); div() - .id("desktop.explorer.tag_search") - .snapshot("desktop.explorer.tag_search", Some("desktop.explorer.menu")) + .id(ui::ElementId::Name(id.clone())) + .snapshot(id, Some(parent)) + .when(!text.is_empty(), |field| field.snapshot_text(text)) .track_focus(&self.focus) .flex() .items_center() .gap(px(8.0)) - .h(px(30.0)) + .min_h(px(30.0)) .px(px(8.0)) .cursor(ui::CursorStyle::IBeam) - .child( + .children(self.search.then(|| { svg() .data(SEARCH.svg.as_bytes()) .size(px(16.0)) .flex_shrink(0.0) - .text_color(palette.text_secondary), - ) + .text_color(palette.text_secondary) + })) .child( div() .relative() .flex_1() - .h(px(22.0)) + .min_w_0() + .h(line_height) .overflow_hidden() .child( canvas( @@ -274,7 +321,7 @@ impl Render for TagSearch { } } -impl EntityInputHandler for TagSearch { +impl EntityInputHandler for TextField { fn text_for_range( &mut self, range: Range<usize>, diff --git a/packages/frontend/desktop/src/views_extra/journals/mod.rs b/packages/frontend/desktop/src/views_extra/journals/mod.rs index 3562e35c56..55d8793b8c 100644 --- a/packages/frontend/desktop/src/views_extra/journals/mod.rs +++ b/packages/frontend/desktop/src/views_extra/journals/mod.rs @@ -1,6 +1,8 @@ mod panel; mod tz; +pub(crate) use tz::LocalZone; + use std::collections::BTreeSet; use affine_client::nav::{LocationChoice, LocationRef}; diff --git a/packages/frontend/desktop/src/views_extra/journals/tz.rs b/packages/frontend/desktop/src/views_extra/journals/tz.rs index 78cb02b813..b6b5d95b49 100644 --- a/packages/frontend/desktop/src/views_extra/journals/tz.rs +++ b/packages/frontend/desktop/src/views_extra/journals/tz.rs @@ -3,16 +3,16 @@ /// The local time zone of the browser. #[cfg(target_arch = "wasm32")] -pub(super) struct LocalZone; +pub(crate) struct LocalZone; #[cfg(target_arch = "wasm32")] impl LocalZone { - pub(super) fn system() -> Self { + pub(crate) fn system() -> Self { Self } /// Minutes that the local calendar runs ahead of UTC at `ms`. - pub(super) fn offset_minutes(&self, ms: i64) -> i32 { + pub(crate) fn offset_minutes(&self, ms: i64) -> i32 { let date = js_sys::Date::new(&wasm_bindgen::JsValue::from_f64(ms as f64)); let offset = date.get_timezone_offset(); if offset.is_finite() { @@ -25,7 +25,7 @@ impl LocalZone { /// A time zone read once from a zone file or a POSIX `TZ` rule. #[cfg(not(target_arch = "wasm32"))] -pub(super) enum LocalZone { +pub(crate) enum LocalZone { /// A constant UTC offset in seconds. Fixed(i32), Tzif(Tzif), @@ -35,13 +35,13 @@ pub(super) enum LocalZone { #[cfg(not(target_arch = "wasm32"))] impl LocalZone { /// The zone of `TZ`, or of `/etc/localtime` without it. - pub(super) fn system() -> Self { + pub(crate) fn system() -> Self { Self::from_tz(std::env::var("TZ").ok().as_deref()) } /// The zone of a `TZ` value: a zone file name, an absolute zone file path, or a POSIX rule. /// Without a value, the zone in `/etc/localtime`. A zone that does not read is UTC. - pub(super) fn from_tz(tz: Option<&str>) -> Self { + pub(crate) fn from_tz(tz: Option<&str>) -> Self { let zone = match tz.map(|raw| raw.strip_prefix(':').unwrap_or(raw)) { None => std::fs::read("/etc/localtime") .ok() @@ -68,7 +68,7 @@ impl LocalZone { } /// Minutes that the zone runs ahead of UTC at `ms`. - pub(super) fn offset_minutes(&self, ms: i64) -> i32 { + pub(crate) fn offset_minutes(&self, ms: i64) -> i32 { let secs = ms.div_euclid(1000); let seconds = match self { Self::Fixed(offset) => *offset, @@ -81,7 +81,7 @@ impl LocalZone { /// The transitions of a TZif zone file (RFC 8536). #[cfg(not(target_arch = "wasm32"))] -pub(super) struct Tzif { +pub(crate) struct Tzif { transitions: Vec<i64>, /// The local time type that starts at each transition. indices: Vec<u8>, @@ -178,7 +178,7 @@ impl Tzif { /// A POSIX `TZ` rule such as `JST-9` or `EST5EDT,M3.2.0,M11.1.0` (IEEE Std 1003.1). #[cfg(not(target_arch = "wasm32"))] -pub(super) struct PosixRule { +pub(crate) struct PosixRule { /// Standard time offset in seconds east of UTC. standard: i32, daylight: Option<Daylight>, diff --git a/packages/frontend/desktop/src/workbench/interaction.rs b/packages/frontend/desktop/src/workbench/interaction.rs index 4af29cbf91..61871fa9a4 100644 --- a/packages/frontend/desktop/src/workbench/interaction.rs +++ b/packages/frontend/desktop/src/workbench/interaction.rs @@ -415,6 +415,7 @@ impl DesktopShellView { if capture_trash_confirm_key(self, event, window, cx) || self.state.quick_search.open || matches!(self.state.modal, Some(DesktopModal::Settings)) + || self.state.collection_editor.is_some() { return; } diff --git a/packages/frontend/desktop/src/workbench/mod.rs b/packages/frontend/desktop/src/workbench/mod.rs index 0bdb9feb85..f2ff4b8636 100644 --- a/packages/frontend/desktop/src/workbench/mod.rs +++ b/packages/frontend/desktop/src/workbench/mod.rs @@ -68,6 +68,7 @@ pub struct DesktopShellView { focus_handle: FocusHandle, quick_search_focus: FocusHandle, settings_focus: FocusHandle, + collection_editor_focus: FocusHandle, header_focus: FocusHandle, header_overlay: Option<HeaderOverlay>, title_edit: Option<TitleEdit>, @@ -108,6 +109,7 @@ impl DesktopShellView { focus_handle: cx.focus_handle(), quick_search_focus: cx.focus_handle(), settings_focus: cx.focus_handle(), + collection_editor_focus: cx.focus_handle(), header_focus: cx.focus_handle(), header_overlay: None, title_edit: None, @@ -356,7 +358,8 @@ impl Render for DesktopShellView { !quick_search_open && matches!(self.state.modal, Some(DesktopModal::Settings)); let peek_open = !quick_search_open && !settings_open && self.state.peek_view.is_open(); - if quick_search_open || peek_open || settings_open { + let editor_open = self.state.collection_editor.is_some(); + if quick_search_open || peek_open || settings_open || editor_open { self.header_overlay = None; } self.drop_stale_header_controls(cx); @@ -364,6 +367,8 @@ impl Render for DesktopShellView { Some(self.quick_search_focus.clone()) } else if settings_open { Some(self.settings_focus.clone()) + } else if editor_open { + Some(self.collection_editor_focus.clone()) } else if self.header_overlay.is_some() { Some(self.header_focus.clone()) } else { @@ -418,6 +423,7 @@ impl Render for DesktopShellView { let panes_shielded = quick_search_open || peek_open || settings_open + || editor_open || drawer_open || inspector_floating || self.header_overlay.is_some() @@ -723,7 +729,9 @@ impl Render for DesktopShellView { if let Some(header_overlay) = render_header_overlay(self, (vp_w, vp_h), palette, cx) { root = root.child(header_overlay); } - if quick_search_open || settings_open || self.header_overlay.is_some() { + let editor_focus = self.collection_editor_focus.clone(); + root = root.children(self.render_collection_editor(&editor_focus, window, cx)); + if quick_search_open || settings_open || editor_open || self.header_overlay.is_some() { self.peek_focus.cover(&self.editor_host, window, cx); } else if !peek_open { self.peek_focus.leave(