From 61e2097adae4ccd6b7e5d50e91f225bdacc98181 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Wed, 18 Nov 2026 10:31:21 +0100 Subject: [PATCH 01/20] feat(core): give sidebar folders a colour, a fold and validated moves Folders gain an optional soft-hue colour and a persisted fold. Core owns creating, moving, renaming, recolouring, folding and ungrouping them, with cycle, depth, anchor and content checks. The session snapshot moves to schema 3; earlier snapshots read as open, plain folders. --- .../zephium-app/src/shell/tests/operations.rs | 9 +- .../src/shell/tests/projections.rs | 2 +- crates/zephium-core/src/item.rs | 30 +- crates/zephium-core/src/items.rs | 61 +- crates/zephium-core/src/items/folders.rs | 540 ++++++++++++++++++ crates/zephium-core/src/session.rs | 96 +++- crates/zephium-store/src/actor.rs | 2 +- crates/zephium-store/src/actor/tests.rs | 4 +- crates/zephium-store/src/essentials.rs | 2 +- crates/zephium-store/src/hub/compatibility.rs | 4 +- crates/zephium-store/src/hub/mod.rs | 3 +- crates/zephium-store/src/hub/session.rs | 82 ++- crates/zephium-store/src/legacy.rs | 2 +- 13 files changed, 758 insertions(+), 79 deletions(-) create mode 100644 crates/zephium-core/src/items/folders.rs diff --git a/crates/zephium-app/src/shell/tests/operations.rs b/crates/zephium-app/src/shell/tests/operations.rs index cafef2b95..abae195e6 100644 --- a/crates/zephium-app/src/shell/tests/operations.rs +++ b/crates/zephium-app/src/shell/tests/operations.rs @@ -1394,14 +1394,7 @@ fn keyboard_selection_walks_the_sidebar_from_favorites_through_pinned_folders() Placement::Favorites { space }, page("favorite.example"), ), - item( - pinned_folder, - None, - pinned, - PersistedKind::Folder { - name: "Work".into(), - }, - ), + item(pinned_folder, None, pinned, PersistedKind::folder("Work")), item( pinned_child, Some(pinned_folder), diff --git a/crates/zephium-app/src/shell/tests/projections.rs b/crates/zephium-app/src/shell/tests/projections.rs index 13cb93d99..a63a7f767 100644 --- a/crates/zephium-app/src/shell/tests/projections.rs +++ b/crates/zephium-app/src/shell/tests/projections.rs @@ -5,7 +5,7 @@ fn folder(id: ItemId, parent: Option, placement: Placement, name: &str) id, parent, placement, - kind: PersistedKind::Folder { name: name.into() }, + kind: PersistedKind::folder(name), } } diff --git a/crates/zephium-core/src/item.rs b/crates/zephium-core/src/item.rs index 5d4a888cd..b913e91e1 100644 --- a/crates/zephium-core/src/item.rs +++ b/crates/zephium-core/src/item.rs @@ -239,12 +239,40 @@ impl TabState { } } +/// A folder's colour: one of the interface's soft hues, or none. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FolderColor { + Sky, + Mint, + Lemon, + Peach, + Rose, + Lilac, +} + #[derive(Clone, Debug)] pub enum ItemKind { - Folder { name: String }, + Folder { + name: String, + color: Option, + /// Folded in the sidebar. Kept with the session. + collapsed: bool, + }, Tab(TabState), } +impl ItemKind { + /// An open folder without a colour. + pub fn folder(name: impl Into) -> Self { + Self::Folder { + name: name.into(), + color: None, + collapsed: false, + } + } +} + #[derive(Clone, Debug)] pub struct Item { pub id: ItemId, diff --git a/crates/zephium-core/src/items.rs b/crates/zephium-core/src/items.rs index 69d030433..54bb94ee6 100644 --- a/crates/zephium-core/src/items.rs +++ b/crates/zephium-core/src/items.rs @@ -14,6 +14,9 @@ use crate::navigation; use crate::ports::engine::NavigationRequestId; use crate::spaces::RemovedProfileSpaces; +mod folders; +pub use folders::MAX_FOLDER_DEPTH; + #[derive(Clone, Debug, PartialEq, Eq)] pub enum Effect { CreateView { @@ -266,54 +269,8 @@ impl Items { placement: Placement, before: Option, ) -> bool { - let Some(item) = self.items.get(&id).filter(|item| item.tab().is_some()) else { - return false; - }; - match item.tab().expect("tab filtered above").content { - TabContent::Web => {} - TabContent::BrowserOwned(_) => { - if !matches!( - (item.placement, placement), - ( - Placement::Space { space: current, .. }, - Placement::Space { space: destination, .. } - ) if current == destination - ) { - return false; - } - } - TabContent::ExtensionOwned if item.placement != placement => return false, - TabContent::ExtensionOwned => {} - } - if before == Some(id) { - return item.placement == placement && item.parent.is_none(); - } - if before.is_some_and(|target| { - self.items - .get(&target) - .is_none_or(|item| item.parent.is_some() || item.placement != placement) - }) { - return false; - } - let parent = item.parent; - let old_placement = item.placement; - let siblings = match parent { - Some(parent) => self.children.get_mut(&parent), - None => self.roots.get_mut(&old_placement), - }; - if let Some(siblings) = siblings { - siblings.retain(|item| *item != id); - } - let target = self.roots.entry(placement).or_default(); - let index = before - .and_then(|before| target.iter().position(|item| *item == before)) - .unwrap_or(target.len()); - target.insert(index, id); - if let Some(item) = self.items.get_mut(&id) { - item.parent = None; - item.placement = placement; - } - true + self.items.get(&id).is_some_and(|item| item.tab().is_some()) + && self.move_item(id, placement, None, before) } pub fn remove(&mut self, id: ItemId) -> Vec { @@ -950,7 +907,7 @@ mod tests { id: fid, parent: None, placement: today(), - kind: ItemKind::Folder { name: "F".into() }, + kind: ItemKind::folder("F"), })); fid } @@ -1012,7 +969,7 @@ mod tests { placement: Placement::Favorites { space: target_space, }, - kind: ItemKind::Folder { name: "F".into() }, + kind: ItemKind::folder("F"), })); assert!(items.insert_tab( structurally_foreign_child, @@ -1075,7 +1032,7 @@ mod tests { id: child, parent: Some(parent), placement: today(), - kind: ItemKind::Folder { name: "F".into() }, + kind: ItemKind::folder("F"), })); parent = child; } @@ -1437,7 +1394,7 @@ mod tests { id: id(n), parent: None, placement: today(), - kind: ItemKind::Folder { name: "F".into() }, + kind: ItemKind::folder("F"), }; if items.insert(item) { ids.push(id(n)); diff --git a/crates/zephium-core/src/items/folders.rs b/crates/zephium-core/src/items/folders.rs new file mode 100644 index 000000000..9aa88cad6 --- /dev/null +++ b/crates/zephium-core/src/items/folders.rs @@ -0,0 +1,540 @@ +//! Folders in the item tree. Every caller gets the same invariants: a folder +//! never lands in Essentials or inside itself, nesting stays bounded, and a +//! subtree shares one placement. + +use super::*; +use crate::item::FolderColor; + +/// How many folders may stand inside one another. A restored tree deeper +/// than this keeps its shape; only new nesting is refused. +pub const MAX_FOLDER_DEPTH: usize = 3; + +/// A person's folder name, bounded like other session names and trimmed. +pub(crate) fn folder_name(name: &str) -> String { + crate::session::bounded_name(name.trim(), "Folder") + .trim() + .to_owned() +} + +impl Items { + pub fn is_folder(&self, id: ItemId) -> bool { + self.items + .get(&id) + .is_some_and(|item| matches!(item.kind, ItemKind::Folder { .. })) + } + + /// Folders from the section root down to `id`, `id` included when it is + /// one. + pub fn folder_depth(&self, id: ItemId) -> usize { + let mut depth = 0; + let mut at = Some(id); + for _ in 0..=crate::session::MAX_ITEM_TREE_DEPTH { + let Some(item) = at.and_then(|id| self.items.get(&id)) else { + break; + }; + if matches!(item.kind, ItemKind::Folder { .. }) { + depth += 1; + } + at = item.parent; + } + depth + } + + /// Folder levels in `id`'s subtree, `id` included. + fn folder_height(&self, id: ItemId) -> usize { + if !self.is_folder(id) { + return 0; + } + 1 + self + .children(id) + .iter() + .map(|child| self.folder_height(*child)) + .max() + .unwrap_or(0) + } + + /// Whether `id` is `ancestor` or stands somewhere inside it. + pub fn is_within(&self, id: ItemId, ancestor: ItemId) -> bool { + let mut at = Some(id); + for _ in 0..=crate::session::MAX_ITEM_TREE_DEPTH { + let Some(current) = at else { + return false; + }; + if current == ancestor { + return true; + } + at = self.items.get(¤t).and_then(|item| item.parent); + } + false + } + + /// The tabs in `id`'s subtree in sidebar order, `id` itself when a tab. + pub fn subtree_tabs(&self, id: ItemId) -> Vec { + let mut ordered = Vec::new(); + let mut pending = vec![id]; + while let Some(next) = pending.pop() { + if self.tab(next).is_some() { + ordered.push(next); + } else { + pending.extend(self.children(next).iter().rev().copied()); + } + } + ordered + } + + /// Whether `before` may anchor an insertion into this container. + fn anchors( + &self, + before: Option, + parent: Option, + placement: Placement, + ) -> bool { + before.is_none_or(|before| { + self.items + .get(&before) + .is_some_and(|item| item.parent == parent && item.placement == placement) + }) + } + + fn container_mut(&mut self, parent: Option, placement: Placement) -> &mut Vec { + match parent { + Some(parent) => self.children.entry(parent).or_default(), + None => self.roots.entry(placement).or_default(), + } + } + + fn detach(&mut self, id: ItemId, parent: Option, placement: Placement) { + let siblings = match parent { + Some(parent) => self.children.get_mut(&parent), + None => self.roots.get_mut(&placement), + }; + if let Some(siblings) = siblings { + siblings.retain(|item| *item != id); + } + } + + fn attach( + &mut self, + id: ItemId, + parent: Option, + placement: Placement, + before: Option, + ) { + let target = self.container_mut(parent, placement); + let index = before + .and_then(|before| target.iter().position(|item| *item == before)) + .unwrap_or(target.len()); + target.insert(index, id); + } + + /// Inserts an open folder before `before` in its container, or at the + /// end. Never in Essentials, and never past [`MAX_FOLDER_DEPTH`]. + pub fn insert_folder( + &mut self, + id: ItemId, + placement: Placement, + parent: Option, + before: Option, + name: &str, + color: Option, + ) -> bool { + if matches!(placement, Placement::Favorites { .. }) + || parent.is_some_and(|parent| { + !self.is_folder(parent) || self.folder_depth(parent) >= MAX_FOLDER_DEPTH + }) + || !self.anchors(before, parent, placement) + { + return false; + } + let inserted = self.insert(Item { + id, + parent, + placement, + kind: ItemKind::Folder { + name: folder_name(name), + color, + collapsed: false, + }, + }); + if inserted && before.is_some() { + self.detach(id, parent, placement); + self.attach(id, parent, placement, before); + } + inserted + } + + /// Moves a tab or a folder, with everything in it, into `parent` (a + /// folder, or the section root when `None`) before `before`, or at the + /// end. Native identities are untouched; the caller authorizes scope. + pub fn move_item( + &mut self, + id: ItemId, + placement: Placement, + parent: Option, + before: Option, + ) -> bool { + let Some(item) = self.items.get(&id) else { + return false; + }; + if let Some(parent) = parent { + let Some(folder) = self.items.get(&parent) else { + return false; + }; + if !matches!(folder.kind, ItemKind::Folder { .. }) + || folder.placement != placement + || self.is_within(parent, id) + { + return false; + } + } + match &item.kind { + ItemKind::Folder { .. } => { + if matches!(placement, Placement::Favorites { .. }) { + return false; + } + let base = parent.map_or(0, |parent| self.folder_depth(parent)); + if parent != item.parent && base + self.folder_height(id) > MAX_FOLDER_DEPTH { + return false; + } + } + ItemKind::Tab(tab) => match tab.content { + TabContent::Web => {} + // Pages the browser owns stay loose in their own space: a + // snapshot never restores one inside a folder. + TabContent::BrowserOwned(_) => { + if parent.is_some() + || !matches!( + (item.placement, placement), + ( + Placement::Space { space: current, .. }, + Placement::Space { space: destination, .. } + ) if current == destination + ) + { + return false; + } + } + TabContent::ExtensionOwned => { + if parent.is_some() || item.placement != placement { + return false; + } + } + }, + } + if before == Some(id) { + return item.parent == parent && item.placement == placement; + } + if !self.anchors(before, parent, placement) { + return false; + } + let (old_parent, old_placement) = (item.parent, item.placement); + self.detach(id, old_parent, old_placement); + self.attach(id, parent, placement, before); + if let Some(item) = self.items.get_mut(&id) { + item.parent = parent; + item.placement = placement; + } + if old_placement != placement { + let mut pending = self.children(id).to_vec(); + while let Some(next) = pending.pop() { + pending.extend(self.children(next).iter().copied()); + if let Some(item) = self.items.get_mut(&next) { + item.placement = placement; + } + } + } + true + } + + fn folder_mut( + &mut self, + id: ItemId, + ) -> Option<(&mut String, &mut Option, &mut bool)> { + match &mut self.items.get_mut(&id)?.kind { + ItemKind::Folder { + name, + color, + collapsed, + } => Some((name, color, collapsed)), + ItemKind::Tab(_) => None, + } + } + + /// `None` when `id` is not a folder; otherwise whether the name changed. + pub fn rename_folder(&mut self, id: ItemId, name: &str) -> Option { + let name = folder_name(name); + let (current, _, _) = self.folder_mut(id)?; + let changed = *current != name; + *current = name; + Some(changed) + } + + pub fn set_folder_color(&mut self, id: ItemId, color: Option) -> Option { + let (_, current, _) = self.folder_mut(id)?; + let changed = *current != color; + *current = color; + Some(changed) + } + + pub fn set_folder_collapsed(&mut self, id: ItemId, collapsed: bool) -> Option { + let (_, _, current) = self.folder_mut(id)?; + let changed = *current != collapsed; + *current = collapsed; + Some(changed) + } + + /// Takes a folder away and leaves what it held in its place, in order. + pub fn ungroup(&mut self, id: ItemId) -> bool { + let Some(item) = self + .items + .get(&id) + .filter(|item| matches!(item.kind, ItemKind::Folder { .. })) + else { + return false; + }; + let (parent, placement) = (item.parent, item.placement); + let held = self.children.remove(&id).unwrap_or_default(); + for child in &held { + if let Some(child) = self.items.get_mut(child) { + child.parent = parent; + } + } + let container = self.container_mut(parent, placement); + let at = container + .iter() + .position(|item| *item == id) + .unwrap_or(container.len()); + container.splice(at..(at + 1).min(container.len()), held); + self.items.remove(&id); + true + } + + /// A tab that knows its page but has not loaded it, put in a folder or + /// section before `before`: how a kept tab stays where it was closed. + pub fn insert_unloaded_tab_at( + &mut self, + id: ItemId, + placement: Placement, + parent: Option, + before: Option, + url: Url, + title: &str, + ) -> bool { + if !navigation::is_allowed(&url) || !self.anchors(before, parent, placement) { + return false; + } + let mut tab = TabState::new(); + tab.url = Some(url); + tab.title = sanitize_page_title(title); + if !self.insert(Item { + id, + parent, + placement, + kind: ItemKind::Tab(tab), + }) { + return false; + } + if before.is_some() { + self.detach(id, parent, placement); + self.attach(id, parent, placement, before); + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ids::SpaceId; + use crate::item::SpaceSection; + + fn id(n: u128) -> ItemId { + ItemId::from(n) + } + + fn today() -> Placement { + Placement::Space { + space: SpaceId::from(1), + section: SpaceSection::Today, + } + } + + fn tab(items: &mut Items, n: u128) -> ItemId { + assert!(items.insert_tab(id(n), today())); + id(n) + } + + fn folder(items: &mut Items, n: u128, parent: Option) -> ItemId { + assert!(items.insert_folder(id(n), today(), parent, None, "F", None)); + id(n) + } + + #[test] + fn a_folder_is_placed_before_its_anchor_and_its_name_is_bounded() { + let mut items = Items::default(); + let a = tab(&mut items, 1); + let b = tab(&mut items, 2); + assert!(items.insert_folder(id(3), today(), None, Some(b), " Research ", None)); + assert_eq!(items.roots(today()), [a, id(3), b]); + let Some(ItemKind::Folder { + name, collapsed, .. + }) = items.get(id(3)).map(|i| &i.kind) + else { + panic!("folder"); + }; + assert_eq!(name, "Research"); + assert!(!collapsed); + + assert!(items.insert_folder(id(4), today(), None, None, "\u{202e}\u{0}", None)); + assert!(matches!( + &items.get(id(4)).unwrap().kind, + ItemKind::Folder { name, .. } if name == "Folder" + )); + let long = "x".repeat(10_000); + assert!(items.insert_folder(id(5), today(), None, None, &long, None)); + assert!(matches!( + &items.get(id(5)).unwrap().kind, + ItemKind::Folder { name, .. } + if name.chars().count() == crate::session::MAX_SESSION_NAME_CHARS + )); + } + + #[test] + fn folders_refuse_essentials_foreign_anchors_tabs_as_parents_and_deep_nesting() { + let mut items = Items::default(); + let space = SpaceId::from(1); + let loose = tab(&mut items, 1); + assert!(!items.insert_folder(id(2), Placement::Favorites { space }, None, None, "F", None)); + assert!(!items.insert_folder(id(2), today(), Some(loose), None, "F", None)); + let outer = folder(&mut items, 3, None); + // An anchor must be a sibling in the target container. + assert!(!items.insert_folder(id(2), today(), Some(outer), Some(loose), "F", None)); + let middle = folder(&mut items, 4, Some(outer)); + let inner = folder(&mut items, 5, Some(middle)); + assert_eq!(items.folder_depth(inner), MAX_FOLDER_DEPTH); + assert!(!items.insert_folder(id(6), today(), Some(inner), None, "F", None)); + // Tabs still go anywhere inside. + assert!(items.move_item(loose, today(), Some(inner), None)); + assert_eq!(items.children(inner), [loose]); + } + + #[test] + fn a_folder_never_moves_into_itself_or_past_the_depth_limit() { + let mut items = Items::default(); + let outer = folder(&mut items, 1, None); + let inner = folder(&mut items, 2, Some(outer)); + let other = folder(&mut items, 3, None); + assert!(!items.move_item(outer, today(), Some(outer), None)); + assert!(!items.move_item(outer, today(), Some(inner), None)); + // outer holds two levels; inside a nested folder it would make four. + let nested = folder(&mut items, 4, Some(other)); + assert!(!items.move_item(outer, today(), Some(nested), None)); + assert!(items.move_item(outer, today(), Some(other), None)); + assert_eq!(items.children(other), [nested, outer]); + assert_eq!(items.folder_depth(inner), 3); + let space = SpaceId::from(1); + assert!(!items.move_item(other, Placement::Favorites { space }, None, None)); + } + + #[test] + fn moving_reorders_reparents_and_carries_the_subtree_between_sections() { + let mut items = Items::default(); + let a = tab(&mut items, 1); + let f = folder(&mut items, 2, None); + let b = tab(&mut items, 3); + assert!(items.move_item(b, today(), Some(f), None)); + assert!(items.move_item(a, today(), Some(f), Some(b))); + assert_eq!(items.children(f), [a, b]); + assert_eq!(items.roots(today()), [f]); + assert_eq!(items.get(a).unwrap().parent, Some(f)); + // Before itself where it already is: nothing to do, and true. + assert!(items.move_item(a, today(), Some(f), Some(a))); + assert!(!items.move_item(a, today(), None, Some(a))); + // A stale anchor in another container is refused, not guessed. + assert!(!items.move_item(a, today(), None, Some(b))); + + let pinned = Placement::Space { + space: SpaceId::from(1), + section: SpaceSection::Pinned, + }; + assert!(items.move_item(f, pinned, None, None)); + assert!(items.roots(today()).is_empty()); + for child in [a, b] { + assert_eq!(items.get(child).unwrap().placement, pinned); + } + assert_eq!(items.subtree_tabs(f), [a, b]); + } + + #[test] + fn only_web_pages_go_into_folders() { + let mut items = Items::default(); + let f = folder(&mut items, 1, None); + assert!(items.insert_browser_tab(id(2), today(), BrowserOwnedTab::Extensions)); + assert!(items.insert_extension_tab(id(3), today())); + assert!(!items.move_item(id(2), today(), Some(f), None)); + assert!(!items.move_item(id(3), today(), Some(f), None)); + assert!(items.children(f).is_empty()); + // Browser pages still reorder among the open tabs. + assert!(items.move_item(id(2), today(), None, Some(f))); + assert_eq!(items.roots(today()), [id(2), f, id(3)]); + } + + #[test] + fn ungrouping_leaves_the_contents_in_the_folders_place() { + let mut items = Items::default(); + let a = tab(&mut items, 1); + let f = folder(&mut items, 2, None); + let z = tab(&mut items, 3); + let inner = folder(&mut items, 4, Some(f)); + let b = tab(&mut items, 5); + let c = tab(&mut items, 6); + assert!(items.move_item(b, today(), Some(f), Some(inner))); + assert!(items.move_item(c, today(), Some(inner), None)); + assert!(items.ungroup(f)); + assert_eq!(items.roots(today()), [a, b, inner, z]); + assert_eq!(items.get(inner).unwrap().parent, None); + assert_eq!(items.children(inner), [c]); + assert!(items.get(f).is_none()); + assert!(!items.ungroup(a)); + assert!(!items.ungroup(f)); + } + + #[test] + fn folder_settings_report_change_and_refuse_tabs() { + let mut items = Items::default(); + let f = folder(&mut items, 1, None); + let t = tab(&mut items, 2); + assert_eq!(items.rename_folder(f, "Trips"), Some(true)); + assert_eq!(items.rename_folder(f, " Trips "), Some(false)); + assert_eq!( + items.set_folder_color(f, Some(FolderColor::Mint)), + Some(true) + ); + assert_eq!( + items.set_folder_color(f, Some(FolderColor::Mint)), + Some(false) + ); + assert_eq!(items.set_folder_collapsed(f, true), Some(true)); + assert_eq!(items.rename_folder(t, "x"), None); + assert_eq!(items.set_folder_collapsed(t, true), None); + assert_eq!(items.set_folder_color(id(99), None), None); + } + + #[test] + fn a_kept_tab_returns_unloaded_to_its_slot() { + let mut items = Items::default(); + let f = folder(&mut items, 1, None); + let a = tab(&mut items, 2); + let b = tab(&mut items, 3); + assert!(items.move_item(a, today(), Some(f), None)); + assert!(items.move_item(b, today(), Some(f), None)); + let url = Url::parse("https://example.com/").unwrap(); + items.remove(a); + assert!(items.insert_unloaded_tab_at(id(4), today(), Some(f), Some(b), url.clone(), "E")); + assert_eq!(items.children(f), [id(4), b]); + assert!(!items.tab(id(4)).unwrap().has_view()); + let unsafe_url = Url::parse("javascript:alert(1)").unwrap(); + assert!(!items.insert_unloaded_tab_at(id(5), today(), Some(f), None, unsafe_url, "x")); + assert!(!items.insert_unloaded_tab_at(id(5), today(), None, Some(b), url, "x")); + } +} diff --git a/crates/zephium-core/src/session.rs b/crates/zephium-core/src/session.rs index 97aa8c232..76b0fae6f 100644 --- a/crates/zephium-core/src/session.rs +++ b/crates/zephium-core/src/session.rs @@ -68,6 +68,11 @@ pub struct PersistedItem { pub enum PersistedKind { Folder { name: String, + /// Absent on snapshots before schema 3, and for a folder with none. + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + collapsed: bool, }, Tab { url: String, @@ -78,9 +83,18 @@ pub enum PersistedKind { last_active_ms: Option, }, /// Browser-owned pages have no navigable URL or native content view. - BrowserTab { - page: BrowserOwnedTab, - }, + BrowserTab { page: BrowserOwnedTab }, +} + +impl PersistedKind { + /// An open folder without a colour. + pub fn folder(name: impl Into) -> Self { + Self::Folder { + name: name.into(), + color: None, + collapsed: false, + } + } } /// Bounded browser-owned state for restoring a recently closed regular tab. @@ -207,7 +221,15 @@ fn collect(items: &Items, placement: Placement, out: &mut Vec) { return; }; let kind = match &item.kind { - ItemKind::Folder { name } => PersistedKind::Folder { name: name.clone() }, + ItemKind::Folder { + name, + color, + collapsed, + } => PersistedKind::Folder { + name: name.clone(), + color: *color, + collapsed: *collapsed, + }, ItemKind::Tab(tab) => match tab.content { // The document a source tab shows lives in memory only. TabContent::BrowserOwned(BrowserOwnedTab::Source) => return, @@ -299,8 +321,14 @@ pub fn restore(state: SessionState) -> Restored { continue; } let kind = match i.kind { - PersistedKind::Folder { name } => ItemKind::Folder { + PersistedKind::Folder { + name, + color, + collapsed, + } => ItemKind::Folder { name: bounded_name(&name, "Folder"), + color, + collapsed, }, PersistedKind::Tab { url, @@ -530,6 +558,64 @@ mod tests { items.set_committed_url(id, url); } + #[test] + fn folders_keep_their_colour_fold_and_contents_across_a_restart() { + let (profiles, spaces, mut items, _profile, space) = seed(); + let (folder, inner, tab) = (ItemId::from(20), ItemId::from(21), ItemId::from(22)); + assert!(items.insert_folder(folder, today(space), None, None, "Trips", None)); + assert!(items.insert_folder(inner, today(space), Some(folder), None, "Rome", None)); + assert_eq!( + items.set_folder_color(folder, Some(crate::item::FolderColor::Peach)), + Some(true) + ); + assert_eq!(items.set_folder_collapsed(inner, true), Some(true)); + items.insert_tab(tab, today(space)); + navigate_and_commit(&mut items, tab, "example.com"); + assert!(items.move_item(tab, today(space), Some(inner), None)); + + let state = snapshot(&profiles, &spaces, &items, Some(space), None, None); + let json = serde_json::to_string(&state).unwrap(); + assert!(json.contains(r#""color":"peach""#)); + assert_eq!(json.matches(r#""collapsed":true"#).count(), 1); + let restored = restore(serde_json::from_str(&json).unwrap()); + let Some(ItemKind::Folder { + name, + color, + collapsed, + }) = restored.items.get(folder).map(|item| &item.kind) + else { + panic!("folder"); + }; + assert_eq!( + (name.as_str(), *color, *collapsed), + ("Trips", Some(crate::item::FolderColor::Peach), false) + ); + assert!(matches!( + restored.items.get(inner).map(|item| &item.kind), + Some(ItemKind::Folder { + collapsed: true, + .. + }) + )); + assert_eq!(restored.items.children(inner), [tab]); + assert_eq!(canonicalize(state.clone()), state); + + // A snapshot from before folders had looks reads as open and plain. + let legacy: PersistedKind = serde_json::from_str(r#"{"Folder":{"name":"Old"}}"#).unwrap(); + assert_eq!( + legacy, + PersistedKind::Folder { + name: "Old".into(), + color: None, + collapsed: false + } + ); + assert!(serde_json::from_str::( + r#"{"Folder":{"name":"Old","color":"neon"}}"# + ) + .is_err()); + } + #[test] fn snapshot_restore_roundtrips_ids_order_and_splits() { let (profiles, spaces, mut items, _profile, space) = seed(); diff --git a/crates/zephium-store/src/actor.rs b/crates/zephium-store/src/actor.rs index b57ab57de..a5dc30c34 100644 --- a/crates/zephium-store/src/actor.rs +++ b/crates/zephium-store/src/actor.rs @@ -1840,7 +1840,7 @@ fn admissible_session(session: &SessionState) -> bool { .iter() .all(|space| space.name.len() <= MAX_NAME_BYTES) && session.items.iter().all(|item| match &item.kind { - PersistedKind::Folder { name } => name.len() <= MAX_NAME_BYTES, + PersistedKind::Folder { name, .. } => name.len() <= MAX_NAME_BYTES, PersistedKind::Tab { url, title, zoom, .. } => { diff --git a/crates/zephium-store/src/actor/tests.rs b/crates/zephium-store/src/actor/tests.rs index 4dba052d7..d5cfb51df 100644 --- a/crates/zephium-store/src/actor/tests.rs +++ b/crates/zephium-store/src/actor/tests.rs @@ -301,9 +301,7 @@ fn sample() -> SessionState { space, section: SpaceSection::Pinned, }, - kind: PersistedKind::Folder { - name: "Work".into(), - }, + kind: PersistedKind::folder("Work"), }, PersistedItem { id: ItemId::from(21), diff --git a/crates/zephium-store/src/essentials.rs b/crates/zephium-store/src/essentials.rs index aa827c88b..ef2c8f382 100644 --- a/crates/zephium-store/src/essentials.rs +++ b/crates/zephium-store/src/essentials.rs @@ -246,7 +246,7 @@ mod tests { id: ItemId::from(41), parent: None, placement: essentials(1), - kind: PersistedKind::Folder { name: "F".into() }, + kind: PersistedKind::folder("F"), }; let items = vec![ folder, diff --git a/crates/zephium-store/src/hub/compatibility.rs b/crates/zephium-store/src/hub/compatibility.rs index 5e508b5fb..4841ccbb0 100644 --- a/crates/zephium-store/src/hub/compatibility.rs +++ b/crates/zephium-store/src/hub/compatibility.rs @@ -81,7 +81,7 @@ impl Hub { } }; let (kind, name, url, title, zoom) = match &item.kind { - PersistedKind::Folder { name } => { + PersistedKind::Folder { name, .. } => { ("folder", Some(name.as_str()), None, None, 1.0) } PersistedKind::Tab { @@ -270,7 +270,7 @@ impl Hub { } }; let kind = match (kind.as_str(), name, url) { - ("folder", Some(name), None) => PersistedKind::Folder { name }, + ("folder", Some(name), None) => PersistedKind::folder(name), ("tab", None, Some(url)) => PersistedKind::Tab { url, title: title.unwrap_or_default(), diff --git a/crates/zephium-store/src/hub/mod.rs b/crates/zephium-store/src/hub/mod.rs index 9be4b12e5..cd1839502 100644 --- a/crates/zephium-store/src/hub/mod.rs +++ b/crates/zephium-store/src/hub/mod.rs @@ -89,7 +89,8 @@ use filesystem::{ /// 2 gave every space its own Essentials. A session saved as 1 holds one set /// per profile; reading it copies that set into each of the profile's spaces. -const SESSION_SCHEMA_VERSION: i64 = 2; +/// 3 gave folders a colour and a fold; older sessions read as open and plain. +const SESSION_SCHEMA_VERSION: i64 = 3; pub(crate) const MAX_SESSION_SNAPSHOT_BYTES: usize = 16 * 1024 * 1024; pub(crate) const MAX_URL_BYTES: usize = 8 * 1024; pub(crate) const MAX_TITLE_BYTES: usize = zephium_core::item::MAX_PAGE_TITLE_CHARS * 4; diff --git a/crates/zephium-store/src/hub/session.rs b/crates/zephium-store/src/hub/session.rs index 7e92be238..2145244d5 100644 --- a/crates/zephium-store/src/hub/session.rs +++ b/crates/zephium-store/src/hub/session.rs @@ -106,6 +106,11 @@ enum BoundedPlacement { enum BoundedKind { Folder { name: String, + /// Only in sessions saved as version 3 or later. + #[serde(default)] + color: Option, + #[serde(default)] + collapsed: Option, }, Tab { url: String, @@ -143,7 +148,7 @@ where { bounded_json::deserialize_bounded_vec(deserializer, MAX_SESSION_ITEMS, |item| { match &item.kind { - BoundedKind::Folder { name } => name.len() <= MAX_NAME_BYTES, + BoundedKind::Folder { name, .. } => name.len() <= MAX_NAME_BYTES, BoundedKind::Tab { url, title, zoom, .. } => { @@ -177,7 +182,8 @@ where impl BoundedSessionState { /// `version` is the schema the snapshot was saved under, which decides - /// whose Essentials its items name: a space's (2), or a profile's (1). + /// whose Essentials its items name: a space's (2), or a profile's (1), + /// and whether its folders may carry a look (3). fn into_state(self, version: i64) -> Option { let spaces: Vec = self .spaces @@ -225,7 +231,22 @@ impl BoundedSessionState { parent: item.parent, placement, kind: match item.kind { - BoundedKind::Folder { name } => PersistedKind::Folder { name }, + BoundedKind::Folder { + name, + color, + collapsed, + } => { + // A folder's look came with version 3; an older + // snapshot naming one is not what it claims to be. + if version < 3 && (color.is_some() || collapsed.is_some()) { + return None; + } + PersistedKind::Folder { + name, + color, + collapsed: collapsed.unwrap_or(false), + } + } BoundedKind::Tab { url, title, @@ -2974,6 +2995,61 @@ mod essentials_per_space_tests { assert!(decode_snapshot(&version_two, 1).is_none()); } + #[test] + fn folders_carry_a_look_from_version_three_and_older_sessions_read_as_plain() { + let today = Placement::Space { + space: SpaceId::from(HOME), + section: SpaceSection::Today, + }; + let folder = |kind| PersistedItem { + id: ItemId::from(90), + parent: None, + placement: today, + kind, + }; + let mut plain = session(SECOND); + plain.items.push(folder(PersistedKind::folder("Trips"))); + let mut styled = session(SECOND); + styled.items.push(folder(PersistedKind::Folder { + name: "Trips".into(), + color: Some(zephium_core::item::FolderColor::Rose), + collapsed: true, + })); + let plain_json = serde_json::to_string(&plain).unwrap(); + let styled_json = serde_json::to_string(&styled).unwrap(); + + assert_eq!(decode_snapshot(&plain_json, 2), Some(plain.clone())); + assert_eq!(decode_snapshot(&styled_json, 3), Some(styled.clone())); + assert!(decode_snapshot(&styled_json, 2).is_none()); + let last = plain.items.len() - 1; + let mut half = serde_json::to_value(&plain).unwrap(); + half["items"][last]["kind"]["Folder"]["collapsed"] = serde_json::json!(false); + assert!(decode_snapshot(&half.to_string(), 2).is_none()); + assert!(decode_snapshot(&half.to_string(), 3).is_some()); + let mut unknown = serde_json::to_value(&styled).unwrap(); + unknown["items"][last]["kind"]["Folder"]["color"] = serde_json::json!("neon"); + assert!(decode_snapshot(&unknown.to_string(), 3).is_none()); + + let mut hub = Hub::in_memory().unwrap(); + hub.save(&core_session::canonicalize(styled)).unwrap(); + let loaded = hub.load().unwrap().unwrap(); + assert!(loaded.items.iter().any(|item| matches!( + &item.kind, + PersistedKind::Folder { + color: Some(zephium_core::item::FolderColor::Rose), + collapsed: true, + .. + } + ))); + let version: i64 = hub + .meta + .query_row("SELECT schema_version FROM session_snapshot", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(version, 3); + } + #[test] fn essentials_naming_both_a_profile_and_a_space_are_not_a_session() { let state = session(SECOND); diff --git a/crates/zephium-store/src/legacy.rs b/crates/zephium-store/src/legacy.rs index 02641aeb1..2edd13395 100644 --- a/crates/zephium-store/src/legacy.rs +++ b/crates/zephium-store/src/legacy.rs @@ -335,7 +335,7 @@ fn decode_item( _ => return None, }; let kind = match (item.folder, item.url) { - (Some(name), None) => PersistedKind::Folder { name }, + (Some(name), None) => PersistedKind::folder(name), (None, Some(url)) => PersistedKind::Tab { url, title: item.title.unwrap_or_default(), From f02130d4ff30dc388a1974c3bd502839cd4326f3 Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Wed, 18 Nov 2026 10:31:21 +0100 Subject: [PATCH 02/20] feat(tabs): create, move and keep sidebar folders natively One typed folder intent reaches the shell: create from tabs or empty, rename, colour, fold, move tabs and folders, remove a tab, ungroup, close a folder's tabs, delete, and move a folder to another space. A folder's tabs are kept like Essentials: closing one ends its page and leaves it asleep in place, and closing the front tab never wakes a sleeping one. A deleted folder comes back whole, asleep, from Reopen Closed Tab during the run. Folders get a native menu, the tab menu lists them, and Group into Folder is a rebindable command. --- crates/zephium-app/src/actor/mod.rs | 1 + crates/zephium-app/src/api.rs | 42 ++ crates/zephium-app/src/lib.rs | 8 +- crates/zephium-app/src/shell/folders.rs | 505 +++++++++++++++++ crates/zephium-app/src/shell/mod.rs | 7 + crates/zephium-app/src/shell/operations.rs | 9 + crates/zephium-app/src/shell/projections.rs | 13 +- crates/zephium-app/src/shell/spaces.rs | 9 +- crates/zephium-app/src/shell/tabs.rs | 78 ++- crates/zephium-app/src/shell/tests/folders.rs | 521 ++++++++++++++++++ crates/zephium-app/src/shell/tests/mod.rs | 1 + .../src/shell/tests/projections.rs | 6 + crates/zephium-core/src/commands.rs | 9 + crates/zephium-core/src/item.rs | 1 + crates/zephium-ipc/src/lib.rs | 62 ++- desktop/src/folders.rs | 484 ++++++++++++++++ desktop/src/lib.rs | 35 +- frame/src/shared/ipc/bindings.ts | 52 +- 18 files changed, 1811 insertions(+), 32 deletions(-) create mode 100644 crates/zephium-app/src/shell/folders.rs create mode 100644 crates/zephium-app/src/shell/tests/folders.rs create mode 100644 desktop/src/folders.rs diff --git a/crates/zephium-app/src/actor/mod.rs b/crates/zephium-app/src/actor/mod.rs index dc285b227..515dea092 100644 --- a/crates/zephium-app/src/actor/mod.rs +++ b/crates/zephium-app/src/actor/mod.rs @@ -1301,6 +1301,7 @@ fn tracked_operation_command(command: &Command) -> bool { | Command::LeaveSplit(_) | Command::TabAction { .. } | Command::Space(_) + | Command::Folder(_) | Command::DropTab { .. } | Command::DividerRelease { .. } | Command::Run(_) diff --git a/crates/zephium-app/src/api.rs b/crates/zephium-app/src/api.rs index 62f6a4161..a27394fee 100644 --- a/crates/zephium-app/src/api.rs +++ b/crates/zephium-app/src/api.rs @@ -251,6 +251,46 @@ pub enum SpaceCommand { MoveActive(zephium_core::ids::SpaceId), } +/// Folder mutations from chrome, menus and keys, with ids parsed. The shell +/// checks each against the focused space. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FolderCommand { + Create { + name: String, + color: Option, + tabs: Vec, + parent: Option, + before: Option, + }, + Rename { + id: ItemId, + name: String, + }, + SetColor { + id: ItemId, + color: Option, + }, + SetCollapsed { + id: ItemId, + collapsed: bool, + }, + Move { + id: ItemId, + parent: Option, + before: Option, + }, + /// Takes a tab out of its folder, to just below it. + RemoveFromFolder(ItemId), + Ungroup(ItemId), + CloseTabs(ItemId), + Delete(ItemId), + /// The folder and everything in it, to another of the profile's spaces. + MoveToSpace { + id: ItemId, + space: zephium_core::ids::SpaceId, + }, +} + /// What the person chose for a page's request to open another application /// or a blocked new tab. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -493,6 +533,8 @@ pub enum Command { }, /// Something done to the focused profile's spaces. Space(Box), + /// Something done to the focused space's folders. + Folder(Box), SetWindowSize(Size), /// Whether the OS can currently present the main window. Minimized /// windows hide native content views so the engine can lower their memory diff --git a/crates/zephium-app/src/lib.rs b/crates/zephium-app/src/lib.rs index ba56b0555..c2a5391db 100644 --- a/crates/zephium-app/src/lib.rs +++ b/crates/zephium-app/src/lib.rs @@ -146,8 +146,8 @@ mod work_synthesis; pub mod work_trace; pub use api::{ BookmarkCompletion, BrowsingDataCompletion, ExportCompletion, FaviconPageSource, FaviconProbe, - FaviconProber, FaviconProberAttachment, HistoryCompletion, HistoryListCompletion, - ImportCompletion, ImportDestination, ImportDestinationCompletion, NoteCompletion, - NotesAttachment, PageSource, ResourceCompletion, SourceCompletion, SpaceCommand, TabAction, - TabCompletion, TimeCompletion, ZoomCompletion, + FaviconProber, FaviconProberAttachment, FolderCommand, HistoryCompletion, + HistoryListCompletion, ImportCompletion, ImportDestination, ImportDestinationCompletion, + NoteCompletion, NotesAttachment, PageSource, ResourceCompletion, SourceCompletion, + SpaceCommand, TabAction, TabCompletion, TimeCompletion, ZoomCompletion, }; diff --git a/crates/zephium-app/src/shell/folders.rs b/crates/zephium-app/src/shell/folders.rs new file mode 100644 index 000000000..cdf22027a --- /dev/null +++ b/crates/zephium-app/src/shell/folders.rs @@ -0,0 +1,505 @@ +//! Folders in a space's open tabs: making, naming, colouring, folding, +//! moving, ungrouping and deleting them. A folder keeps its tabs: closing one +//! ends its page and leaves it in place (see `tabs::kept_slot`). A deleted +//! folder comes back whole from Reopen Closed Tab while the app runs. + +use super::*; +use crate::FolderCommand; +use zephium_core::ids::ClosedSessionId; +use zephium_core::item::{FolderColor, ItemKind}; +use zephium_core::items::MAX_FOLDER_DEPTH; + +/// Deleted folders Reopen Closed Tab can still bring back. +const MAX_DELETED_FOLDERS: usize = 8; + +pub(super) struct DeletedFolder { + profile: ProfileId, + parent: Option, + before: Option, + node: DeletedNode, + /// The Recently Closed records its tabs left. + closed: Vec, +} + +enum DeletedNode { + Folder { + name: String, + color: Option, + collapsed: bool, + children: Vec, + }, + Tab { + url: url::Url, + title: String, + }, +} + +fn rejected(reason: OperationReason) -> OperationDisposition { + operation_result(OperationOutcome::Rejected, reason) +} + +fn unchanged() -> OperationDisposition { + operation_result(OperationOutcome::NoOp, OperationReason::StateUnchanged) +} + +fn today(space: SpaceId) -> Placement { + Placement::Space { + space, + section: SpaceSection::Today, + } +} + +impl Shell { + pub(super) fn operation_folder(&mut self, command: FolderCommand) -> OperationDisposition { + if !self.bootstrapped { + return rejected(OperationReason::NoFocusedWindow); + } + // Private browsing keeps nothing, so it has nothing to file. + let Some((profile, space)) = self.space_scope() else { + return rejected(OperationReason::InvalidScope); + }; + match command { + FolderCommand::Create { + name, + color, + tabs, + parent, + before, + } => self.create_folder(space, &name, color, &tabs, parent, before), + FolderCommand::Rename { id, name } => { + self.change_folder(space, id, |items| items.rename_folder(id, &name)) + } + FolderCommand::SetColor { id, color } => { + self.change_folder(space, id, |items| items.set_folder_color(id, color)) + } + FolderCommand::SetCollapsed { id, collapsed } => { + self.change_folder(space, id, |items| items.set_folder_collapsed(id, collapsed)) + } + FolderCommand::Move { id, parent, before } => self.move_into(space, id, parent, before), + FolderCommand::RemoveFromFolder(id) => self.remove_from_folder(space, id), + FolderCommand::Ungroup(id) => { + if !self.folder_in_space(id, space) || !self.items.ungroup(id) { + return rejected(OperationReason::InvalidScope); + } + mutation_result(self.commit(Vec::new())) + } + FolderCommand::CloseTabs(id) => self.close_folder_tabs(space, id), + FolderCommand::Delete(id) => self.delete_folder(profile, space, id), + FolderCommand::MoveToSpace { id, space: target } => { + self.move_folder_to_space(profile, space, id, target) + } + } + } + + fn folder_in_space(&self, id: ItemId, space: SpaceId) -> bool { + self.items.get(id).is_some_and(|item| { + matches!(item.kind, ItemKind::Folder { .. }) + && matches!(item.placement, Placement::Space { space: at, .. } if at == space) + }) + } + + /// A tab or folder of the focused space, by the same rule as every + /// other item the chrome names. + fn node_in_space(&self, id: ItemId, space: SpaceId) -> bool { + self.folder_in_space(id, space) || self.item_in_focused_scope(id) + } + + fn change_folder( + &mut self, + space: SpaceId, + id: ItemId, + change: impl FnOnce(&mut Items) -> Option, + ) -> OperationDisposition { + if !self.folder_in_space(id, space) { + return rejected(OperationReason::InvalidScope); + } + match change(&mut self.items) { + None => rejected(OperationReason::InvalidInput), + Some(false) => unchanged(), + Some(true) => mutation_result(self.commit(Vec::new())), + } + } + + fn create_folder( + &mut self, + space: SpaceId, + name: &str, + color: Option, + tabs: &[ItemId], + parent: Option, + before: Option, + ) -> OperationDisposition { + if tabs.len() > zephium_core::session::MAX_SESSION_ITEMS { + return rejected(OperationReason::InvalidInput); + } + if tabs.iter().any(|tab| { + !self.item_in_focused_scope(*tab) + || self + .items + .tab(*tab) + .is_none_or(|tab| tab.content != zephium_core::item::TabContent::Web) + }) { + return rejected(OperationReason::InvalidScope); + } + // The tabs go in as the sidebar lists them, whatever order they came. + let order = self.keyboard_tabs(space); + let mut tabs = tabs.to_vec(); + tabs.sort_by_key(|tab| order.iter().position(|id| id == tab)); + tabs.dedup(); + let placement = today(space); + let (mut parent, mut before) = match tabs.iter().find(|tab| { + self.items + .get(**tab) + .is_some_and(|item| item.placement == placement) + }) { + // A folder made of tabs stands where the first of them stood. + Some(first) => ( + self.items.get(*first).and_then(|item| item.parent), + Some(*first), + ), + None if !tabs.is_empty() => (None, None), + None => { + if parent.is_some_and(|parent| { + !self.folder_in_space(parent, space) + || self.items.get(parent).map(|item| item.placement) != Some(placement) + }) || before.is_some_and(|before| !self.node_in_space(before, space)) + { + return rejected(OperationReason::InvalidScope); + } + (parent, before) + } + }; + // Too deep to nest further: it stands beside the deepest folder. + while let Some(folder) = + parent.filter(|folder| self.items.folder_depth(*folder) >= MAX_FOLDER_DEPTH) + { + before = Some(folder); + parent = self.items.get(folder).and_then(|item| item.parent); + } + let Some(id) = (0..8).map(|_| ItemId::generate()).find(|id| { + self.items + .insert_folder(*id, placement, parent, before, name, color) + }) else { + return rejected(OperationReason::InvalidInput); + }; + for tab in tabs { + let _ = self.items.move_item(tab, placement, Some(id), None); + } + mutation_result(self.commit(Vec::new())) + } + + fn move_into( + &mut self, + space: SpaceId, + id: ItemId, + parent: Option, + before: Option, + ) -> OperationDisposition { + if !self.node_in_space(id, space) + || parent.is_some_and(|parent| !self.folder_in_space(parent, space)) + || before.is_some_and(|before| !self.node_in_space(before, space)) + { + return rejected(OperationReason::InvalidScope); + } + // Into the section its new neighbours are in: the open tabs, or the + // pinned section an imported folder may still stand in. + let placement = parent + .or(before) + .and_then(|anchor| self.items.get(anchor)) + .map(|item| item.placement) + .filter(|placement| matches!(placement, Placement::Space { .. })) + .unwrap_or_else(|| today(space)); + let Some(item) = self.items.get(id) else { + return rejected(OperationReason::InvalidScope); + }; + if item.parent == parent && item.placement == placement { + let siblings = match parent { + Some(parent) => self.items.children(parent), + None => self.items.roots(placement), + }; + let at = siblings.iter().position(|sibling| *sibling == id); + let next = at.and_then(|at| siblings.get(at + 1).copied()); + if before == Some(id) || (at.is_some() && next == before) { + return unchanged(); + } + } + if !self.items.move_item(id, placement, parent, before) { + return rejected(OperationReason::InvalidInput); + } + mutation_result(self.commit(Vec::new())) + } + + fn remove_from_folder(&mut self, space: SpaceId, id: ItemId) -> OperationDisposition { + let Some(folder) = self + .items + .get(id) + .and_then(|item| item.parent) + .filter(|folder| self.folder_in_space(*folder, space)) + else { + return rejected(OperationReason::InvalidScope); + }; + let Some(holder) = self.items.get(folder) else { + return rejected(OperationReason::InvalidScope); + }; + let (parent, placement) = (holder.parent, holder.placement); + let siblings = match parent { + Some(parent) => self.items.children(parent), + None => self.items.roots(placement), + }; + let before = siblings + .iter() + .position(|sibling| *sibling == folder) + .and_then(|at| siblings.get(at + 1).copied()); + if !self.item_in_focused_scope(id) || !self.items.move_item(id, placement, parent, before) { + return rejected(OperationReason::InvalidInput); + } + mutation_result(self.commit(Vec::new())) + } + + fn close_folder_tabs(&mut self, space: SpaceId, id: ItemId) -> OperationDisposition { + if !self.folder_in_space(id, space) { + return rejected(OperationReason::InvalidScope); + } + let awake: Vec = self + .items + .subtree_tabs(id) + .into_iter() + .filter(|tab| self.items.tab(*tab).is_some_and(TabState::has_view)) + .collect(); + if awake.is_empty() { + return unchanged(); + } + // The window leaves the folder first, so ending the one in front + // never wakes the rest in turn. + let mut native = NativeWork::default(); + if let Some(active) = self.windows.focused().and_then(|window| window.active) { + if awake.contains(&active) { + native.merge(self.close(active)); + } + } + for tab in awake { + if self.items.tab(tab).is_some_and(TabState::has_view) { + native.merge(self.close(tab)); + } + } + mutation_result(native) + } + + fn capture(&self, id: ItemId) -> Option { + let item = self.items.get(id)?; + match &item.kind { + ItemKind::Folder { + name, + color, + collapsed, + } => Some(DeletedNode::Folder { + name: name.clone(), + color: *color, + collapsed: *collapsed, + children: self + .items + .children(id) + .iter() + .filter_map(|child| self.capture(*child)) + .collect(), + }), + ItemKind::Tab(tab) => (tab.content == zephium_core::item::TabContent::Web) + .then(|| tab.url.clone()) + .flatten() + .map(|url| DeletedNode::Tab { + url, + title: tab.title.clone(), + }), + } + } + + fn delete_folder( + &mut self, + profile: ProfileId, + space: SpaceId, + id: ItemId, + ) -> OperationDisposition { + if !self.folder_in_space(id, space) { + return rejected(OperationReason::InvalidScope); + } + let Some(item) = self.items.get(id) else { + return rejected(OperationReason::InvalidScope); + }; + let (parent, placement) = (item.parent, item.placement); + let siblings = match parent { + Some(parent) => self.items.children(parent), + None => self.items.roots(placement), + }; + let before = siblings + .iter() + .position(|sibling| *sibling == id) + .and_then(|at| siblings.get(at + 1).copied()); + let node = self.capture(id); + let mut closed = Vec::new(); + let mut native = NativeWork::default(); + for tab in self.items.subtree_tabs(id) { + let newest = |shell: &Self| shell.recently_closed.last().and_then(|e| e.session_id); + let previous = newest(self); + native.merge(self.close_tab(tab, false)); + if self.items.get(tab).is_some() { + // The lone New Tab of a space stays; so does its folder. + continue; + } + if let Some(record) = newest(self).filter(|record| Some(*record) != previous) { + closed.push(record); + } + } + let effects = self.items.remove(id); + native.merge(self.commit(effects)); + if let Some(node) = node.filter(|_| !closed.is_empty()) { + if self.deleted_folders.len() == MAX_DELETED_FOLDERS { + self.deleted_folders.remove(0); + } + self.deleted_folders.push(DeletedFolder { + profile, + parent, + before, + node, + closed, + }); + } + mutation_result(native) + } + + /// Brings back the newest deleted folder of `profile` when what it left + /// is still the newest thing in Recently Closed. Its tabs return asleep. + pub(super) fn reopen_deleted_folder(&mut self, profile: ProfileId) -> Option { + let (current, persistent) = self.windows.focused().map(|window| { + ( + window.space, + window.profile == profile && !self.incognito_profile(profile), + ) + })?; + if !persistent { + return None; + } + let newest = self + .recently_closed + .iter() + .rev() + .find(|entry| entry.profile == profile)? + .session_id?; + let at = self + .deleted_folders + .iter() + .rposition(|folder| folder.profile == profile && folder.closed.contains(&newest))?; + let deleted = self.deleted_folders.remove(at); + // Where it was, when that is still the space in front; else here. + let space = current; + let placement = today(space); + let parent = deleted + .parent + .filter(|parent| self.folder_in_space(*parent, space)) + .filter(|parent| self.items.folder_depth(*parent) < MAX_FOLDER_DEPTH); + let before = deleted.before.filter(|before| { + self.items + .get(*before) + .is_some_and(|item| item.parent == parent && item.placement == placement) + }); + if !self.restore_node(&deleted.node, placement, parent, before) { + return None; + } + self.recently_closed.retain(|entry| { + entry + .session_id + .is_none_or(|id| !deleted.closed.contains(&id)) + }); + self.extension_sessions_changed(profile); + Some(self.commit(Vec::new())) + } + + fn restore_node( + &mut self, + node: &DeletedNode, + placement: Placement, + parent: Option, + before: Option, + ) -> bool { + match node { + DeletedNode::Tab { url, title } => (0..8).any(|_| { + self.items.insert_unloaded_tab_at( + ItemId::generate(), + placement, + parent, + before, + url.clone(), + title, + ) + }), + DeletedNode::Folder { + name, + color, + collapsed, + children, + } => { + let Some(id) = (0..8).map(|_| ItemId::generate()).find(|id| { + self.items + .insert_folder(*id, placement, parent, before, name, *color) + }) else { + return false; + }; + let _ = self.items.set_folder_collapsed(id, *collapsed); + for child in children { + // A nested folder past the depth limit comes back loose. + if !self.restore_node(child, placement, Some(id), None) { + let _ = self.restore_node(child, placement, parent, before); + } + } + true + } + } + } + + fn move_folder_to_space( + &mut self, + profile: ProfileId, + space: SpaceId, + id: ItemId, + target: SpaceId, + ) -> OperationDisposition { + if !self.folder_in_space(id, space) || !self.owned_space(profile, target) { + return rejected(OperationReason::InvalidScope); + } + if space == target { + return unchanged(); + } + let tabs = self.items.subtree_tabs(id); + let active = self.windows.focused().and_then(|window| window.active); + let at = active.and_then(|active| { + self.successor_pool(profile, space) + .iter() + .position(|tab| *tab == active) + }); + if !self.items.move_item(id, today(target), None, None) { + return rejected(OperationReason::InvalidInput); + } + let was_active = active.filter(|active| tabs.contains(active)); + if let Some(window) = self.windows.focused_mut() { + if let Some(tree) = window.splits.take() { + window.splits = tabs.iter().try_fold(tree, |tree, tab| tree.remove(*tab)); + } + if was_active.is_some() { + window.active = None; + } + } + if self + .work_pane + .as_ref() + .is_some_and(|pane| tabs.contains(&pane.tab)) + { + self.clear_work_pane(); + } + let mut effects = Vec::new(); + if let Some(tab) = was_active { + self.items.set_lifecycle(tab, Lifecycle::Inactive); + self.remember_left_tab(target, tab); + effects.extend(self.take_over(profile, space, at)); + } + mutation_result(self.commit(effects)) + } +} diff --git a/crates/zephium-app/src/shell/mod.rs b/crates/zephium-app/src/shell/mod.rs index 362232f42..37f70b1e1 100644 --- a/crates/zephium-app/src/shell/mod.rs +++ b/crates/zephium-app/src/shell/mod.rs @@ -202,6 +202,7 @@ impl AgentLifecycleOwner { } mod browser_pages; +mod folders; mod kept_sites; mod spaces; mod work_pane; @@ -249,6 +250,8 @@ pub struct Shell { spaces: Spaces, items: Items, recently_closed: Vec, + /// Folders deleted this run, for Reopen Closed Tab. Never persisted. + deleted_folders: Vec, windows: Windows, recent_tabs: recent_tabs::RecentTabs, tab_previews: tab_previews::TabPreviews, @@ -525,6 +528,7 @@ impl Shell { spaces: Spaces::default(), items: Items::default(), recently_closed: Vec::new(), + deleted_folders: Vec::new(), windows: Windows::default(), pending_size: Size::default(), favicons: FaviconState::default(), @@ -1010,6 +1014,9 @@ impl Shell { Command::Space(command) => { let _ = self.operation_space(*command); } + Command::Folder(command) => { + let _ = self.operation_folder(*command); + } Command::SetWindowSize(size) => match self.windows.focused_mut() { Some(win) => { win.size = size; diff --git a/crates/zephium-app/src/shell/operations.rs b/crates/zephium-app/src/shell/operations.rs index be0359890..2026b6c79 100644 --- a/crates/zephium-app/src/shell/operations.rs +++ b/crates/zephium-app/src/shell/operations.rs @@ -64,6 +64,7 @@ impl Shell { Command::LeaveSplit(id) => self.operation_leave_split(id), Command::TabAction { id, action } => self.operation_tab_action(id, action), Command::Space(command) => self.operation_space(*command), + Command::Folder(command) => self.operation_folder(*command), Command::DropTab { id, x, y } => self.operation_drop_tab(id, x, y), Command::DividerRelease { x, y } => self.operation_divider_release(x.zip(y)), Command::Run(id) => self.operation_run_command(&id), @@ -611,6 +612,9 @@ impl Shell { self.browser_after_return = Some(Box::new(Command::Close(id))); return self.request_browser_return(); } + if self.kept_asleep(id) { + return operation_result(OperationOutcome::NoOp, OperationReason::StateUnchanged); + } let discard_closing = matches!( self.residency.discard_probes.get(&id), Some(PendingDiscardProbe::Closing { .. }) @@ -1161,6 +1165,11 @@ impl Shell { let Some(profile) = self.windows.focused().map(|window| window.profile) else { return operation_result(OperationOutcome::Rejected, OperationReason::NoFocusedWindow); }; + if named.is_none() { + if let Some(native) = self.reopen_deleted_folder(profile) { + return mutation_result(native); + } + } match self.restore_recently_closed_tab(profile, named) { Some((_, native)) => mutation_result(native), None => operation_result(OperationOutcome::NoOp, OperationReason::MutationApplied), diff --git a/crates/zephium-app/src/shell/projections.rs b/crates/zephium-app/src/shell/projections.rs index 1098aa541..4f2a18fd2 100644 --- a/crates/zephium-app/src/shell/projections.rs +++ b/crates/zephium-app/src/shell/projections.rs @@ -367,7 +367,15 @@ impl Shell { let id_string = id.to_string(); let kind = match &item.kind { - ItemKind::Folder { name } => SidebarNodeKindView::Folder { name: name.clone() }, + ItemKind::Folder { + name, + color, + collapsed, + } => SidebarNodeKindView::Folder { + name: name.clone(), + color: *color, + collapsed: *collapsed, + }, ItemKind::Tab(tab) => { projection.tab_ids.insert(id); projection @@ -742,6 +750,9 @@ fn tab_view( } }, loading: tab.loading, + asleep: tab.content == zephium_core::item::TabContent::Web + && tab.url.is_some() + && !tab.has_view(), page_request: tab.page_request.as_deref().map(|request| match request { zephium_core::item::PageRequest::ExternalApp { url, app, site } => { zephium_ipc::PageRequestView::ExternalApp { diff --git a/crates/zephium-app/src/shell/spaces.rs b/crates/zephium-app/src/shell/spaces.rs index 5780ded4e..aa7c8859f 100644 --- a/crates/zephium-app/src/shell/spaces.rs +++ b/crates/zephium-app/src/shell/spaces.rs @@ -148,7 +148,7 @@ impl Shell { /// The focused window's persistent profile and space. Private browsing /// keeps a single space, and a profile being deleted has none to change. - fn space_scope(&self) -> Option<(ProfileId, SpaceId)> { + pub(super) fn space_scope(&self) -> Option<(ProfileId, SpaceId)> { let window = self.windows.focused()?; let persistent = self .profiles @@ -158,7 +158,12 @@ impl Shell { .then_some((window.profile, window.space)) } - fn owned_space(&self, profile: ProfileId, space: SpaceId) -> bool { + /// The tab a space shows when the window next returns to it. + pub(super) fn remember_left_tab(&mut self, space: SpaceId, tab: ItemId) { + self.space_memory.left_at.insert(space, tab); + } + + pub(super) fn owned_space(&self, profile: ProfileId, space: SpaceId) -> bool { self.spaces .get(space) .is_some_and(|candidate| candidate.profile == profile) diff --git a/crates/zephium-app/src/shell/tabs.rs b/crates/zephium-app/src/shell/tabs.rs index c5d0340d2..59c7e2625 100644 --- a/crates/zephium-app/src/shell/tabs.rs +++ b/crates/zephium-app/src/shell/tabs.rs @@ -140,6 +140,8 @@ impl TabPreferences { struct KeptSlot { placement: Placement, + /// The folder it was kept in; none for an Essential. + parent: Option, url: url::Url, title: String, before: Option, @@ -275,15 +277,25 @@ impl Shell { } pub(super) fn close(&mut self, id: ItemId) -> NativeWork { + self.close_tab(id, true) + } + + /// Closes a tab; with `keep`, an Essential or a tab in a folder ends its + /// page and stays where it was, asleep. Without, it goes either way. + pub(super) fn close_tab(&mut self, id: ItemId, keep: bool) -> NativeWork { if !self.item_in_focused_scope(id) || self.is_lone_new_tab(id) { return NativeWork::default(); } + if keep && self.kept_asleep(id) { + return NativeWork::default(); + } + let kept = keep.then(|| self.kept_slot(id)).flatten(); self.forget_removed_tab_state(id); self.forget_content_fullscreen(id); self.forget_tab_media(id); self.native_openers.remove(&id); - // An Essential is kept, not closed: the page ends and the site stays. - let kept = self.kept_slot(id); + // An Essential or a folder's tab is kept, not closed: the page ends + // and the site stays. let closed = kept .is_none() .then(|| self.closed_record(id, unix_millis())) @@ -344,23 +356,40 @@ impl Shell { native } - /// Where an Essential sits, so closing it can leave it there unloaded. + /// A kept tab already asleep, and not in front: closing it has no page + /// to end. + pub(super) fn kept_asleep(&self, id: ItemId) -> bool { + self.kept_slot(id).is_some() + && !self.items.tab(id).is_some_and(TabState::has_view) + && self + .windows + .focused() + .is_none_or(|win| win.active != Some(id)) + } + + /// Where an Essential or a folder's tab sits, so closing it can leave it + /// there unloaded. fn kept_slot(&self, id: ItemId) -> Option { let item = self.items.get(id)?; let tab = item.tab()?; - if item.parent.is_some() - || !matches!(item.placement, Placement::Favorites { .. }) - || tab.content != zephium_core::item::TabContent::Web - { + let kept = match item.parent { + Some(folder) => self.items.is_folder(folder), + None => matches!(item.placement, Placement::Favorites { .. }), + }; + if !kept || tab.content != zephium_core::item::TabContent::Web { return None; } - let roots = self.items.roots(item.placement); - let at = roots.iter().position(|candidate| *candidate == id)?; + let siblings = match item.parent { + Some(folder) => self.items.children(folder), + None => self.items.roots(item.placement), + }; + let at = siblings.iter().position(|candidate| *candidate == id)?; Some(KeptSlot { placement: item.placement, + parent: item.parent, url: tab.url.clone()?, title: tab.title.clone(), - before: roots.get(at + 1).copied(), + before: siblings.get(at + 1).copied(), }) } @@ -369,27 +398,34 @@ impl Shell { fn restore_kept_slot(&mut self, kept: KeptSlot) { for _ in 0..8 { let id = ItemId::generate(); - if self - .items - .insert_unloaded_tab(id, kept.placement, kept.url.clone(), &kept.title) - { - if let Some(before) = kept.before { - self.items - .move_tab_to_root(id, kept.placement, Some(before)); - } + if self.items.insert_unloaded_tab_at( + id, + kept.placement, + kept.parent, + kept.before, + kept.url.clone(), + &kept.title, + ) { return; } } } /// The tabs a closed active one may hand the window to: the space's open - /// tabs only, so closing never wakes an Essential or a pinned page. The - /// private window has no such sections and keeps walking every tab. + /// tabs only, so closing never wakes an Essential, a pinned page or a + /// folder's sleeping tab. The private window has no such sections and + /// keeps walking every tab. pub(super) fn successor_pool(&self, profile: ProfileId, space: SpaceId) -> Vec { if self.incognito_profile(profile) { self.keyboard_tabs(space) } else { - self.regular_tabs(space) + let mut tabs = self.regular_tabs(space); + tabs.retain(|id| { + self.items.get(*id).is_some_and(|item| { + item.parent.is_none() || item.tab().is_some_and(TabState::has_view) + }) + }); + tabs } } diff --git a/crates/zephium-app/src/shell/tests/folders.rs b/crates/zephium-app/src/shell/tests/folders.rs new file mode 100644 index 000000000..30bcef663 --- /dev/null +++ b/crates/zephium-app/src/shell/tests/folders.rs @@ -0,0 +1,521 @@ +use super::*; +use crate::{FolderCommand, SpaceCommand}; +use zephium_core::item::{FolderColor, ItemKind}; + +fn browsed() -> (Shell, Arc, Screen, Arc) { + let store = Arc::new(FakeStore::default()); + let (mut shell, engine, screen) = setup_with(store.clone()); + shell.handle(Command::Bootstrap); + (shell, engine, screen, store) +} + +/// Applied, with native work still to come counting as applied. +fn op(shell: &mut Shell, command: Command) -> OperationDisposition { + let mut done = shell.handle_operation(command); + if done.outcome == OperationOutcome::Deferred { + done.outcome = OperationOutcome::Applied; + } + done +} + +fn folder_op(shell: &mut Shell, command: FolderCommand) -> OperationDisposition { + op(shell, Command::Folder(Box::new(command))) +} + +fn space(shell: &Shell) -> SpaceId { + shell.windows.focused().unwrap().space +} + +fn today(shell: &Shell) -> Placement { + Placement::Space { + space: space(shell), + section: SpaceSection::Today, + } +} + +/// Opens `pages` loaded tabs after the first one, which shows `first`. +fn tabs(shell: &mut Shell, screen: &Screen, pages: &[&str]) -> Vec { + let mut ids = vec![active_id(screen)]; + navigate_and_commit(shell, ids[0], pages[0]); + for page in &pages[1..] { + shell.handle(Command::Open); + let id = active_id(screen); + navigate_and_commit(shell, id, page); + ids.push(id); + } + ids +} + +fn group(shell: &mut Shell, name: &str, tabs: Vec) -> ItemId { + let made = folder_op( + shell, + FolderCommand::Create { + name: name.into(), + color: None, + tabs, + parent: None, + before: None, + }, + ); + assert_eq!(made.outcome, OperationOutcome::Applied, "{made:?}"); + *shell + .items + .roots(today(shell)) + .iter() + .find(|id| { + matches!(&shell.items.get(**id).unwrap().kind, + ItemKind::Folder { name: made, .. } if made == name) + }) + .expect("folder") +} + +fn folder_view(state: &ItemsState, id: ItemId) -> SidebarNodeKindView { + state + .nodes + .iter() + .find(|node| node.id == id.to_string()) + .map(|node| node.kind.clone()) + .expect("projected folder") +} + +#[test] +fn tabs_grouped_into_a_folder_take_the_first_ones_place_in_sidebar_order() { + let (mut shell, _engine, screen, store) = browsed(); + let ids = tabs( + &mut shell, + &screen, + &["a.example", "b.example", "c.example"], + ); + let folder = group(&mut shell, "Research", vec![ids[2], ids[1]]); + + assert_eq!(shell.items.roots(today(&shell)), [ids[0], folder]); + assert_eq!(shell.items.children(folder), [ids[1], ids[2]]); + let state = last(&screen); + assert_eq!( + folder_view(&state, folder), + SidebarNodeKindView::Folder { + name: "Research".into(), + color: None, + collapsed: false, + } + ); + let child = state + .nodes + .iter() + .find(|node| node.id == ids[1].to_string()) + .unwrap(); + assert_eq!(child.parent_id, Some(folder.to_string())); + + shell.persist(); + let saved = store.saved.lock().unwrap().clone().unwrap(); + let kept = saved.items.iter().find(|item| item.id == folder).unwrap(); + assert_eq!(kept.kind, PersistedKind::folder("Research")); + assert_eq!( + saved + .items + .iter() + .filter(|item| item.parent == Some(folder)) + .count(), + 2 + ); +} + +#[test] +fn a_folder_is_renamed_coloured_and_folded_and_keeps_that_across_a_restart() { + let (mut shell, _engine, screen, store) = browsed(); + let ids = tabs(&mut shell, &screen, &["a.example", "b.example"]); + let folder = group(&mut shell, "F", vec![ids[1]]); + for (command, outcome) in [ + ( + FolderCommand::Rename { + id: folder, + name: " Trips ".into(), + }, + OperationOutcome::Applied, + ), + ( + FolderCommand::Rename { + id: folder, + name: "Trips".into(), + }, + OperationOutcome::NoOp, + ), + ( + FolderCommand::SetColor { + id: folder, + color: Some(FolderColor::Lilac), + }, + OperationOutcome::Applied, + ), + ( + FolderCommand::SetCollapsed { + id: folder, + collapsed: true, + }, + OperationOutcome::Applied, + ), + ] { + assert_eq!(folder_op(&mut shell, command).outcome, outcome); + } + assert_eq!( + folder_view(&last(&screen), folder), + SidebarNodeKindView::Folder { + name: "Trips".into(), + color: Some(FolderColor::Lilac), + collapsed: true, + } + ); + + shell.persist(); + let saved = store.saved.lock().unwrap().clone().unwrap(); + let restarted = Arc::new(FakeStore::default()); + *restarted.saved.lock().unwrap() = Some(saved); + let (mut again, _engine, screen) = setup_with(restarted); + again.handle(Command::Bootstrap); + assert_eq!( + folder_view(&last(&screen), folder), + SidebarNodeKindView::Folder { + name: "Trips".into(), + color: Some(FolderColor::Lilac), + collapsed: true, + } + ); + // Restored folder tabs are asleep until opened. + let child = again.items.children(folder)[0]; + assert!(!again.items.tab(child).unwrap().has_view()); + let view = last(&screen) + .tabs + .into_iter() + .find(|tab| tab.id == child.to_string()) + .unwrap(); + assert!(view.asleep); +} + +#[test] +fn closing_a_folder_tab_keeps_it_asleep_in_its_place_and_never_wakes_another() { + let (mut shell, _engine, screen, _store) = browsed(); + let ids = tabs( + &mut shell, + &screen, + &["a.example", "b.example", "c.example", "d.example"], + ); + let folder = group(&mut shell, "Keep", vec![ids[1], ids[2], ids[3]]); + let closed_before = shell.recently_closed.len(); + + // The one in front is d, inside the folder. Closing it keeps it, asleep + // where it stood, and hands the window to a tab that is still awake. + assert_eq!(active_id(&screen), ids[3]); + assert_eq!( + op(&mut shell, Command::Close(ids[3])).outcome, + OperationOutcome::Applied + ); + let held = shell.items.children(folder).to_vec(); + assert_eq!(held.len(), 3); + assert_eq!(&held[..2], &ids[1..3]); + let kept = shell.items.tab(held[2]).unwrap(); + assert_eq!(kept.url.as_ref().unwrap().host_str(), Some("d.example")); + assert!(!kept.has_view()); + assert_eq!(shell.recently_closed.len(), closed_before); + let next = active_id(&screen); + assert!(shell.items.tab(next).unwrap().has_view()); + assert_ne!(next, held[2]); + + // An asleep tab out of the window has nothing to end. + assert_eq!( + op(&mut shell, Command::Close(held[2])).outcome, + OperationOutcome::NoOp + ); + assert_eq!(shell.items.children(folder), held); + + // Closing the folder's tabs ends every page and keeps every tab. + assert_eq!( + folder_op(&mut shell, FolderCommand::CloseTabs(folder)).outcome, + OperationOutcome::Applied + ); + let held = shell.items.children(folder).to_vec(); + assert_eq!(held.len(), 3); + assert!(held + .iter() + .all(|id| !shell.items.tab(*id).unwrap().has_view())); + assert_eq!(active_id(&screen), ids[0]); + assert_eq!( + folder_op(&mut shell, FolderCommand::CloseTabs(folder)).outcome, + OperationOutcome::NoOp + ); +} + +#[test] +fn a_deleted_folder_comes_back_whole_and_asleep_from_reopen_closed_tab() { + let (mut shell, _engine, screen, _store) = browsed(); + let ids = tabs( + &mut shell, + &screen, + &["a.example", "b.example", "c.example"], + ); + let outer = group(&mut shell, "Outer", vec![ids[1]]); + let made = folder_op( + &mut shell, + FolderCommand::Create { + name: "Inner".into(), + color: Some(FolderColor::Sky), + tabs: vec![], + parent: Some(outer), + before: None, + }, + ); + assert_eq!(made.outcome, OperationOutcome::Applied); + let inner = shell.items.children(outer)[1]; + assert_eq!( + folder_op( + &mut shell, + FolderCommand::Move { + id: ids[2], + parent: Some(inner), + before: None, + }, + ) + .outcome, + OperationOutcome::Applied + ); + + assert_eq!( + folder_op(&mut shell, FolderCommand::Delete(outer)).outcome, + OperationOutcome::Applied + ); + assert_eq!(shell.items.roots(today(&shell)), [ids[0]]); + assert!(shell.items.get(ids[1]).is_none()); + assert_eq!(shell.recently_closed.len(), 2); + + shell.handle(Command::Run("tab.reopen".into())); + let roots = shell.items.roots(today(&shell)).to_vec(); + assert_eq!(roots.len(), 2); + let back = roots[1]; + assert!(matches!( + &shell.items.get(back).unwrap().kind, + ItemKind::Folder { name, .. } if name == "Outer" + )); + let held = shell.items.children(back).to_vec(); + assert_eq!(held.len(), 2); + let tab = shell.items.tab(held[0]).unwrap(); + assert_eq!(tab.url.as_ref().unwrap().host_str(), Some("b.example")); + assert!(!tab.has_view()); + assert!(matches!( + &shell.items.get(held[1]).unwrap().kind, + ItemKind::Folder { name, color: Some(FolderColor::Sky), .. } if name == "Inner" + )); + assert_eq!(shell.items.subtree_tabs(held[1]).len(), 1); + // Its tabs leave Recently Closed with it, so they cannot come back twice. + assert!(shell.recently_closed.is_empty()); + assert_eq!(active_id(&screen), ids[0]); +} + +#[test] +fn ungrouping_and_removing_from_a_folder_leave_tabs_open_beside_it() { + let (mut shell, _engine, screen, _store) = browsed(); + let ids = tabs( + &mut shell, + &screen, + &["a.example", "b.example", "c.example", "d.example"], + ); + let folder = group(&mut shell, "F", vec![ids[1], ids[2]]); + assert_eq!( + folder_op(&mut shell, FolderCommand::RemoveFromFolder(ids[1])).outcome, + OperationOutcome::Applied + ); + assert_eq!( + shell.items.roots(today(&shell)), + [ids[0], folder, ids[1], ids[3]] + ); + assert_eq!( + folder_op(&mut shell, FolderCommand::Ungroup(folder)).outcome, + OperationOutcome::Applied + ); + assert_eq!( + shell.items.roots(today(&shell)), + [ids[0], ids[2], ids[1], ids[3]] + ); + assert!(shell.items.get(folder).is_none()); + assert!(shell.items.tab(ids[2]).unwrap().has_view()); +} + +#[test] +fn folder_requests_outside_the_focused_space_or_its_rules_are_refused() { + let (mut shell, _engine, screen, _store) = browsed(); + let ids = tabs(&mut shell, &screen, &["a.example", "b.example"]); + let folder = group(&mut shell, "F", vec![ids[1]]); + let unknown = ItemId::from(987_654); + let refused = [ + FolderCommand::Rename { + id: unknown, + name: "x".into(), + }, + // A tab is not a folder. + FolderCommand::Rename { + id: ids[0], + name: "x".into(), + }, + FolderCommand::SetCollapsed { + id: ids[0], + collapsed: true, + }, + FolderCommand::Move { + id: folder, + parent: Some(folder), + before: None, + }, + FolderCommand::Move { + id: ids[0], + parent: Some(ids[1]), + before: None, + }, + FolderCommand::Move { + id: ids[0], + parent: Some(folder), + before: Some(ids[0]), + }, + FolderCommand::Move { + id: unknown, + parent: None, + before: None, + }, + FolderCommand::Create { + name: "x".into(), + color: None, + tabs: vec![unknown], + parent: None, + before: None, + }, + FolderCommand::Create { + name: "x".into(), + color: None, + tabs: vec![], + parent: Some(ids[0]), + before: None, + }, + FolderCommand::RemoveFromFolder(ids[0]), + FolderCommand::Ungroup(ids[0]), + FolderCommand::Delete(unknown), + FolderCommand::CloseTabs(ids[0]), + ]; + for command in refused { + let label = format!("{command:?}"); + assert_eq!( + folder_op(&mut shell, command).outcome, + OperationOutcome::Rejected, + "{label}" + ); + } + assert_eq!(shell.items.roots(today(&shell)), [ids[0], folder]); + assert_eq!(shell.items.children(folder), [ids[1]]); + + // Another space's folder is out of reach from this one. + let created = shell.handle_operation(Command::Space(Box::new(SpaceCommand::Create { + name: "Other".into(), + look: Default::default(), + }))); + assert_ne!(created.outcome, OperationOutcome::Rejected); + assert_eq!( + folder_op( + &mut shell, + FolderCommand::Rename { + id: folder, + name: "x".into(), + }, + ) + .outcome, + OperationOutcome::Rejected + ); +} + +#[test] +fn nesting_stops_at_the_depth_limit_by_standing_beside_the_deepest_folder() { + let (mut shell, _engine, screen, _store) = browsed(); + let ids = tabs(&mut shell, &screen, &["a.example"]); + let mut parent = None; + let mut chain = Vec::new(); + for depth in 0..4 { + let made = folder_op( + &mut shell, + FolderCommand::Create { + name: format!("L{depth}"), + color: None, + tabs: vec![], + parent, + before: None, + }, + ); + assert_eq!(made.outcome, OperationOutcome::Applied); + if depth == 3 { + // The fourth asked for inside the third stands beside it instead. + let beside = shell.items.children(chain[1]); + assert_eq!(beside.len(), 2); + assert_eq!(beside[1], chain[2]); + continue; + } + let id = match parent { + Some(parent) => *shell.items.children(parent).last().unwrap(), + None => *shell.items.roots(today(&shell)).last().unwrap(), + }; + if depth < 3 { + chain.push(id); + parent = Some(id); + } + } + assert_eq!( + folder_op( + &mut shell, + FolderCommand::Move { + id: chain[0], + parent: Some(chain[2]), + before: None, + }, + ) + .outcome, + OperationOutcome::Rejected + ); + assert_eq!(shell.items.roots(today(&shell)), [ids[0], chain[0]]); +} + +#[test] +fn a_folder_moves_to_another_space_with_its_tabs_and_the_window_stays() { + let (mut shell, _engine, screen, _store) = browsed(); + let home = space(&shell); + let ids = tabs(&mut shell, &screen, &["a.example", "b.example"]); + let folder = group(&mut shell, "Move me", vec![ids[1]]); + let created = shell.handle_operation(Command::Space(Box::new(SpaceCommand::Create { + name: "Other".into(), + look: Default::default(), + }))); + assert_ne!(created.outcome, OperationOutcome::Rejected); + let other = space(&shell); + let switched = shell.handle_operation(Command::Space(Box::new(SpaceCommand::Switch(home)))); + assert_ne!(switched.outcome, OperationOutcome::Rejected); + assert_ne!( + op(&mut shell, Command::Activate(ids[1])).outcome, + OperationOutcome::Rejected + ); + assert_eq!(active_id(&screen), ids[1]); + + assert_eq!( + folder_op( + &mut shell, + FolderCommand::MoveToSpace { + id: folder, + space: other, + }, + ) + .outcome, + OperationOutcome::Applied + ); + let moved = shell.items.get(ids[1]).unwrap(); + assert_eq!( + moved.placement, + Placement::Space { + space: other, + section: SpaceSection::Today + } + ); + assert_eq!(moved.parent, Some(folder)); + assert_eq!(space(&shell), home); + assert_eq!(active_id(&screen), ids[0]); +} diff --git a/crates/zephium-app/src/shell/tests/mod.rs b/crates/zephium-app/src/shell/tests/mod.rs index 76c6a659d..8f80a5dee 100644 --- a/crates/zephium-app/src/shell/tests/mod.rs +++ b/crates/zephium-app/src/shell/tests/mod.rs @@ -2669,6 +2669,7 @@ mod extension_browser_requests; mod extension_browser_surface; mod extension_data; mod favicons; +mod folders; mod fullscreen; mod history; mod history_list; diff --git a/crates/zephium-app/src/shell/tests/projections.rs b/crates/zephium-app/src/shell/tests/projections.rs index a63a7f767..0d11ef055 100644 --- a/crates/zephium-app/src/shell/tests/projections.rs +++ b/crates/zephium-app/src/shell/tests/projections.rs @@ -186,6 +186,8 @@ fn items_projection_is_one_ordered_authoritative_focused_sidebar_snapshot() { section: SidebarSectionView::Favorites, kind: SidebarNodeKindView::Folder { name: "Essentials".into(), + color: None, + collapsed: false, }, }, SidebarNodeView { @@ -210,6 +212,8 @@ fn items_projection_is_one_ordered_authoritative_focused_sidebar_snapshot() { section: SidebarSectionView::Pinned, kind: SidebarNodeKindView::Folder { name: "Pinned folder".into(), + color: None, + collapsed: false, }, }, SidebarNodeView { @@ -234,6 +238,8 @@ fn items_projection_is_one_ordered_authoritative_focused_sidebar_snapshot() { section: SidebarSectionView::Today, kind: SidebarNodeKindView::Folder { name: "Today folder".into(), + color: None, + collapsed: false, }, }, SidebarNodeView { diff --git a/crates/zephium-core/src/commands.rs b/crates/zephium-core/src/commands.rs index 508b3c913..1d6e56e32 100644 --- a/crates/zephium-core/src/commands.rs +++ b/crates/zephium-core/src/commands.rs @@ -173,6 +173,15 @@ pub const REGISTRY: &[CommandSpec] = &[ Group::File, ), command("split.choose", "Split View…", Keys::NONE, Group::File), + // The selected tabs, else the one in front, into a new folder. Shift + // and a letter, as the tool panels are: never Alt, which is AltGr on + // many Windows layouts. + command( + "tab.group", + "Group into Folder", + Keys::same("CmdOrCtrl+Shift+L"), + Group::File, + ), command( "page.save", "Save Page As…", diff --git a/crates/zephium-core/src/item.rs b/crates/zephium-core/src/item.rs index b913e91e1..4bd5c53d2 100644 --- a/crates/zephium-core/src/item.rs +++ b/crates/zephium-core/src/item.rs @@ -241,6 +241,7 @@ impl TabState { /// A folder's colour: one of the interface's soft hues, or none. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ipc-types", derive(specta::Type))] #[serde(rename_all = "snake_case")] pub enum FolderColor { Sky, diff --git a/crates/zephium-ipc/src/lib.rs b/crates/zephium-ipc/src/lib.rs index 327cc87f0..1a97551b4 100644 --- a/crates/zephium-ipc/src/lib.rs +++ b/crates/zephium-ipc/src/lib.rs @@ -64,6 +64,10 @@ pub struct TabView { #[serde(default)] #[specta(optional)] pub audio: Option, + /// A web page whose address is kept but which has no live view: it + /// loads when opened. + #[serde(default)] + pub asleep: bool, } /// The sidebar's player: the media of the tab that most recently started @@ -631,8 +635,62 @@ pub enum SidebarSectionView { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(tag = "type", rename_all = "snake_case")] pub enum SidebarNodeKindView { - Folder { name: String }, - Tab { tab_id: String }, + Folder { + name: String, + color: Option, + /// Folded: its rows are hidden, the active tab's excepted. + collapsed: bool, + }, + Tab { + tab_id: String, + }, +} + +/// What chrome asks of the sidebar's folders. Every id is one the focused +/// space projected; native checks each against that space again. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum FolderIntent { + /// A new folder holding `tabs`, in sidebar order. With tabs it takes the + /// first one's place; without, it goes into `parent` before `before`. + Create { + name: String, + color: Option, + tabs: Vec, + parent: Option, + before: Option, + }, + Rename { + id: String, + name: String, + }, + SetColor { + id: String, + color: Option, + }, + SetCollapsed { + id: String, + collapsed: bool, + }, + /// A tab or a folder, into `parent` (none: the open tabs) before + /// `before` (none: at the end). + Move { + id: String, + parent: Option, + before: Option, + }, + /// The folder goes; what it held stays where it was. + Ungroup { + id: String, + }, + /// Every page in the folder ends; the tabs stay in it, asleep. + CloseTabs { + id: String, + }, + /// The folder and its tabs close. Reopen Closed Tab brings it back. + Delete { + id: String, + }, } /// One pre-order entry in the focused sidebar tree. Parents always precede diff --git a/desktop/src/folders.rs b/desktop/src/folders.rs new file mode 100644 index 000000000..9e1d3c8cb --- /dev/null +++ b/desktop/src/folders.rs @@ -0,0 +1,484 @@ +//! Sidebar folders at the desktop edge: the typed folder intent, a folder's +//! native menu and the tab menu's folder section. Native follows the +//! projected folders only to name them in its menus; the shell checks every +//! action against the focused space again. +use std::sync::Mutex; + +use tauri::menu::{IsMenuItem, Menu, MenuItemBuilder, PredefinedMenuItem, Submenu, SubmenuBuilder}; +use tauri::{AppHandle, Manager, State, WebviewWindow}; +use zephium_app::{Command, FolderCommand, Handle}; +use zephium_core::ids::{ItemId, SpaceId}; +use zephium_core::item::FolderColor; +use zephium_ipc::{FolderIntent, ItemsState, OperationAdmission, SidebarNodeKindView}; + +use crate::menu_text; + +/// Bytes a folder name may carry over IPC; core bounds it again by chars. +const MAX_FOLDER_NAME_BYTES: usize = zephium_core::session::MAX_SESSION_NAME_CHARS * 4; +/// Folders the tab menu lists to move a tab into. +const MAX_LISTED_FOLDERS: usize = 32; + +const FOLDER_MENU: &str = "foldermenu."; +const TAB_MENU_FOLDER: &str = "folder="; +pub(crate) const TAB_MENU_NEW_FOLDER: &str = "newFolder"; +pub(crate) const TAB_MENU_UNFOLDER: &str = "unfolder"; +/// Delivered to privileged chrome, which edits a name in place and holds the +/// folder its menu was opened on. +const RENAME_COMMAND: &str = "folder.rename"; +const SUBFOLDER_COMMAND: &str = "folder.newSubfolder"; +/// Chrome makes a folder of the tab its menu was opened on. +pub(crate) const TAB_NEW_FOLDER_COMMAND: &str = "tab.newFolder"; + +const COLORS: [(&str, Option, &str); 7] = [ + ("none", None, "No Color"), + ("sky", Some(FolderColor::Sky), "Sky"), + ("mint", Some(FolderColor::Mint), "Mint"), + ("lemon", Some(FolderColor::Lemon), "Lemon"), + ("peach", Some(FolderColor::Peach), "Peach"), + ("rose", Some(FolderColor::Rose), "Rose"), + ("lilac", Some(FolderColor::Lilac), "Lilac"), +]; + +/// The active space's folders, in sidebar order, with their depth. +static FOLDERS: Mutex> = Mutex::new(Vec::new()); + +/// The folder a native menu was opened on. Popups are modal, so one at most. +#[derive(Default)] +pub(crate) struct FolderMenuTarget(Mutex>); + +impl FolderMenuTarget { + fn arm(&self, id: ItemId) -> bool { + self.0.lock().map(|mut slot| *slot = Some(id)).is_ok() + } + + fn take(&self) -> Option { + self.0.lock().ok().and_then(|mut slot| slot.take()) + } +} + +/// Follows each sidebar projection, for the menus to name its folders. +pub(crate) fn follow(state: &ItemsState) { + let mut depths: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + let mut folders = Vec::new(); + for node in &state.nodes { + let SidebarNodeKindView::Folder { name, .. } = &node.kind else { + continue; + }; + let depth = node + .parent_id + .as_deref() + .and_then(|parent| depths.get(parent)) + .map_or(0, |depth| depth + 1); + depths.insert(node.id.as_str(), depth); + if folders.len() < MAX_LISTED_FOLDERS { + folders.push((node.id.clone(), name.clone(), depth)); + } + } + *FOLDERS.lock().unwrap_or_else(|e| e.into_inner()) = folders; +} + +fn item(value: &str) -> Option { + super::bounded(value, super::MAX_ITEM_ID_BYTES) + .then(|| ItemId::parse(value)) + .flatten() +} + +fn optional_item(value: Option) -> Result, ()> { + value.map(|value| item(&value).ok_or(())).transpose() +} + +fn name(value: String) -> Option { + super::bounded(&value, MAX_FOLDER_NAME_BYTES).then_some(value) +} + +/// The intent with its ids parsed and its text bounded, or nothing. +fn command(intent: FolderIntent) -> Option { + Some(match intent { + FolderIntent::Create { + name: label, + color, + tabs, + parent, + before, + } => { + if tabs.len() > zephium_core::session::MAX_SESSION_ITEMS { + return None; + } + FolderCommand::Create { + name: name(label)?, + color, + tabs: tabs.iter().map(|tab| item(tab)).collect::>()?, + parent: optional_item(parent).ok()?, + before: optional_item(before).ok()?, + } + } + FolderIntent::Rename { id, name: label } => FolderCommand::Rename { + id: item(&id)?, + name: name(label)?, + }, + FolderIntent::SetColor { id, color } => FolderCommand::SetColor { + id: item(&id)?, + color, + }, + FolderIntent::SetCollapsed { id, collapsed } => FolderCommand::SetCollapsed { + id: item(&id)?, + collapsed, + }, + FolderIntent::Move { id, parent, before } => FolderCommand::Move { + id: item(&id)?, + parent: optional_item(parent).ok()?, + before: optional_item(before).ok()?, + }, + FolderIntent::Ungroup { id } => FolderCommand::Ungroup(item(&id)?), + FolderIntent::CloseTabs { id } => FolderCommand::CloseTabs(item(&id)?), + FolderIntent::Delete { id } => FolderCommand::Delete(item(&id)?), + }) +} + +fn dispatch(app: &AppHandle, shell: &Handle, command: FolderCommand) -> OperationAdmission { + super::dispatch_operation(app, shell, Command::Folder(Box::new(command))) +} + +#[tauri::command] +#[specta::specta] +pub(crate) fn tabs_folder( + caller: WebviewWindow, + shell: State<'_, Handle>, + intent: FolderIntent, +) -> OperationAdmission { + if !super::authorize(&caller, super::CallerPolicy::Main, "tabs_folder") + || super::shutdown_started(caller.app_handle()) + { + return super::rejected_operation(); + } + match command(intent) { + Some(command) => dispatch(caller.app_handle(), &shell, command), + None => super::rejected_operation(), + } +} + +/// What a folder's menu can offer, as the sidebar sees it. Only +/// availability: the shell checks every action again. +#[derive(Clone, Debug, serde::Deserialize, specta::Type)] +pub(crate) struct FolderMenuContext { + color: Option, + /// Another folder level fits inside this one. + can_nest: bool, + /// A page in it is loaded. + awake: bool, +} + +#[tauri::command] +#[specta::specta] +pub(crate) fn folder_menu_popup( + caller: WebviewWindow, + app: AppHandle, + id: String, + x: f64, + y: f64, + context: FolderMenuContext, +) -> bool { + if !super::authorize(&caller, super::CallerPolicy::Main, "folder_menu_popup") { + return false; + } + let Some(folder) = item(&id) else { + return false; + }; + let (Ok(size), Ok(scale)) = (caller.inner_size(), caller.scale_factor()) else { + return false; + }; + if !scale.is_finite() || scale <= 0.0 { + return false; + } + let Some(anchor) = super::menu_popup_anchor( + x, + y, + f64::from(size.width) / scale, + f64::from(size.height) / scale, + ) else { + return false; + }; + let Some(target) = app.try_state::() else { + return false; + }; + if !target.arm(folder) { + return false; + } + let Ok(menu) = build_folder_menu(&app, &context) else { + return false; + }; + caller.popup_menu_at(&menu, anchor).is_ok() +} + +type Items = Vec>>; + +fn refs(items: &Items) -> Vec<&dyn IsMenuItem> { + items.iter().map(|item| item.as_ref()).collect() +} + +fn entry( + handle: &AppHandle, + id: &str, + title: &str, + enabled: bool, +) -> tauri::Result>> { + Ok(Box::new( + MenuItemBuilder::with_id(format!("{FOLDER_MENU}{id}"), menu_text::label(title)) + .enabled(enabled) + .build(handle)?, + )) +} + +fn build_folder_menu( + handle: &AppHandle, + context: &FolderMenuContext, +) -> tauri::Result> { + use tauri::menu::CheckMenuItemBuilder; + let mut colors: Items = Vec::new(); + for (id, color, title) in COLORS { + colors.push(Box::new( + CheckMenuItemBuilder::with_id( + format!("{FOLDER_MENU}color={id}"), + menu_text::label(title), + ) + .checked(context.color == color) + .build(handle)?, + )); + } + let color = SubmenuBuilder::new(handle, menu_text::label("Color")) + .items(&refs(&colors)) + .build()?; + let mut items: Items = vec![ + entry(handle, "rename", "Rename Folder…", true)?, + Box::new(color), + entry(handle, "subfolder", "New Folder Inside", context.can_nest)?, + Box::new(PredefinedMenuItem::separator(handle)?), + entry(handle, "closeTabs", "Close Tabs in Folder", context.awake)?, + entry(handle, "ungroup", "Ungroup", true)?, + ]; + if let Some(spaces) = super::spaces::tab_menu_section(handle, &format!("{FOLDER_MENU}space="))? + { + items.push(Box::new(spaces)); + } + items.push(Box::new(PredefinedMenuItem::separator(handle)?)); + items.push(entry(handle, "delete", "Delete Folder and Tabs", true)?); + Menu::with_items(handle, &refs(&items)) +} + +/// "Move to Folder ▸" for the tab menu: the space's folders, indented by +/// depth, then a new one; and the way out when the tab is in one. +pub(crate) fn tab_menu_section( + handle: &AppHandle, + prefix: &str, + in_folder: bool, +) -> tauri::Result>> { + let folders = FOLDERS.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let mut items: Items = Vec::new(); + for (id, name, depth) in &folders { + let label = format!( + "{}{}", + " ".repeat((*depth).min(4)), + super::extension_menu_label(name) + ); + items.push(Box::new( + MenuItemBuilder::with_id(format!("{prefix}{TAB_MENU_FOLDER}{id}"), label) + .build(handle)?, + )); + } + if !items.is_empty() { + items.push(Box::new(PredefinedMenuItem::separator(handle)?)); + } + items.push(Box::new( + MenuItemBuilder::with_id( + format!("{prefix}{TAB_MENU_NEW_FOLDER}"), + menu_text::label("New Folder…"), + ) + .build(handle)?, + )); + if in_folder { + items.push(Box::new( + MenuItemBuilder::with_id( + format!("{prefix}{TAB_MENU_UNFOLDER}"), + menu_text::label("Remove from Folder"), + ) + .build(handle)?, + )); + } + SubmenuBuilder::new(handle, menu_text::label("Move to Folder")) + .items(&refs(&items)) + .build() + .map(Some) +} + +/// A tab menu action naming a folder, or asking for a new one or out. +pub(crate) fn tab_action(app: &AppHandle, tab: ItemId, action: &str) -> Option { + let shell = || app.try_state::(); + if let Some(folder) = action.strip_prefix(TAB_MENU_FOLDER) { + return Some(match (shell(), item(folder)) { + (Some(shell), Some(folder)) => dispatch( + app, + &shell, + FolderCommand::Move { + id: tab, + parent: Some(folder), + before: None, + }, + ), + _ => super::rejected_operation(), + }); + } + match action { + TAB_MENU_UNFOLDER => Some(shell().map_or_else(super::rejected_operation, |shell| { + dispatch(app, &shell, FolderCommand::RemoveFromFolder(tab)) + })), + TAB_MENU_NEW_FOLDER => Some(emit(app, TAB_NEW_FOLDER_COMMAND)), + _ => None, + } +} + +fn emit(app: &AppHandle, command: &str) -> OperationAdmission { + if super::try_emit_to_privileged(app, super::MAIN_LABEL, super::EVENT_UI, &command) { + super::accepted_ui_operation() + } else { + super::rejected_operation() + } +} + +/// Menu ids this module owns; anything else is not a folder action. +pub(crate) fn execute(app: &AppHandle, id: &str) -> Option { + let action = id.strip_prefix(FOLDER_MENU)?; + // Chrome keeps the folder it opened the menu on for what it edits + // itself; everything else is armed here and taken once. + match action { + "rename" => return Some(emit(app, RENAME_COMMAND)), + "subfolder" => return Some(emit(app, SUBFOLDER_COMMAND)), + _ => {} + } + let (Some(target), Some(shell)) = ( + app.try_state::(), + app.try_state::(), + ) else { + return Some(super::rejected_operation()); + }; + let Some(folder) = target.take() else { + return Some(super::rejected_operation()); + }; + let command = if let Some(color) = action.strip_prefix("color=") { + match COLORS.iter().find(|(id, _, _)| *id == color) { + Some((_, color, _)) => FolderCommand::SetColor { + id: folder, + color: *color, + }, + None => return Some(super::rejected_operation()), + } + } else if let Some(space) = action.strip_prefix("space=") { + match SpaceId::parse(space).filter(|id| id.to_string() == space) { + Some(space) => FolderCommand::MoveToSpace { id: folder, space }, + None => return Some(super::rejected_operation()), + } + } else { + match action { + "closeTabs" => FolderCommand::CloseTabs(folder), + "ungroup" => FolderCommand::Ungroup(folder), + "delete" => FolderCommand::Delete(folder), + _ => return Some(super::rejected_operation()), + } + }; + Some(dispatch(app, &shell, command)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn id() -> String { + ItemId::generate().to_string() + } + + #[test] + fn folder_intents_are_admitted_only_with_parsed_ids_and_bounded_text() { + let good = id(); + assert!(matches!( + command(FolderIntent::Rename { + id: good.clone(), + name: "Trips".into() + }), + Some(FolderCommand::Rename { .. }) + )); + for refused in [ + FolderIntent::Rename { + id: "not an id".into(), + name: "x".into(), + }, + FolderIntent::Rename { + id: good.clone(), + name: "x".repeat(MAX_FOLDER_NAME_BYTES + 1), + }, + FolderIntent::Move { + id: good.clone(), + parent: Some("x".repeat(super::super::MAX_ITEM_ID_BYTES + 1)), + before: None, + }, + FolderIntent::Create { + name: "x".into(), + color: None, + tabs: vec![good.clone(), "bogus".into()], + parent: None, + before: None, + }, + FolderIntent::Create { + name: "x".into(), + color: None, + tabs: vec![good.clone(); zephium_core::session::MAX_SESSION_ITEMS + 1], + parent: None, + before: None, + }, + FolderIntent::Delete { id: String::new() }, + ] { + assert!(command(refused.clone()).is_none(), "{refused:?}"); + } + assert!(matches!( + command(FolderIntent::Create { + name: String::new(), + color: Some(FolderColor::Mint), + tabs: vec![good.clone()], + parent: None, + before: Some(good), + }), + Some(FolderCommand::Create { tabs, .. }) if tabs.len() == 1 + )); + } + + #[test] + fn the_tab_menu_lists_the_projected_folders_by_depth() { + let node = |id: &str, parent: Option<&str>, name: &str| zephium_ipc::SidebarNodeView { + id: id.into(), + parent_id: parent.map(Into::into), + section: zephium_ipc::SidebarSectionView::Today, + kind: SidebarNodeKindView::Folder { + name: name.into(), + color: None, + collapsed: false, + }, + }; + let state = ItemsState { + projection_revision: String::new(), + profile: None, + spaces: Vec::new(), + active_space_id: None, + nodes: vec![node("a", None, "Outer"), node("b", Some("a"), "Inner")], + tabs: Vec::new(), + active: None, + split_group: None, + }; + follow(&state); + let listed = FOLDERS.lock().unwrap().clone(); + assert_eq!( + listed, + [ + ("a".into(), "Outer".into(), 0), + ("b".into(), "Inner".into(), 1) + ] + ); + } +} diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs index d67dac157..1fa41fbab 100644 --- a/desktop/src/lib.rs +++ b/desktop/src/lib.rs @@ -83,6 +83,7 @@ mod external_links; #[cfg(feature = "work-product")] mod favicon_probe; mod focus_alerts; +mod folders; mod haptics; mod help; mod history_menu; @@ -2093,6 +2094,8 @@ fn specta_builder() -> tauri_specta::Builder { tabs_activate, tabs_close, tabs_set_essential, + folders::tabs_folder, + folders::folder_menu_popup, essentials_keep, essentials_release, profile_rename, @@ -4367,7 +4370,7 @@ fn execute_command_or( rejected_operation() }; } - if id == "split.choose" { + if matches!(id, "split.choose" | "tab.group") { return if try_emit_to_privileged(app, MAIN_LABEL, EVENT_UI, &id) { accepted_ui_operation() } else { @@ -4380,6 +4383,9 @@ fn execute_command_or( if let Some(step) = id.strip_prefix(history_menu::ID_PREFIX) { return history_menu::execute(app, step); } + if let Some(admission) = folders::execute(app, id) { + return admission; + } if let Some(admission) = spaces::execute(app, id) { return admission; } @@ -4506,6 +4512,10 @@ fn execute_tab_menu_action( axis: Axis::Row, }, ), + action if action.starts_with(TAB_MENU_FOLDER_PREFIX) => { + folders::tab_action(app, id, &action[TAB_MENU_FOLDER_PREFIX.len()..]) + .unwrap_or_else(rejected_operation) + } action if action.starts_with(spaces::TAB_MENU_MOVE) => { spaces::move_tab(app, id, &action[spaces::TAB_MENU_MOVE.len()..]) } @@ -6550,8 +6560,17 @@ struct TabMenuContext { /// Only what acts on the page's camera, microphone and sound, for the /// in-use indicator. media_only: bool, + /// A web page that may go into a folder. + #[serde(default)] + fileable: bool, + /// The tab is in a folder now. + #[serde(default)] + in_folder: bool, } +/// Tab menu actions about folders, after `tabmenu.`. +const TAB_MENU_FOLDER_PREFIX: &str = "folders."; + /// `site_protected` is the page's protection standing, absent where site /// controls do not apply; the frame owns both actions, and clearing the data /// of a page, offered where the page keeps any. @@ -6749,6 +6768,15 @@ fn build_tab_menu( let others = item(8, "Close Other Tabs", context.others)?; let below = item(9, "Close Tabs Below", context.below)?; let move_to = spaces::tab_menu_section(handle, &format!("tabmenu.{}", spaces::TAB_MENU_MOVE))?; + let folder = if context.fileable { + folders::tab_menu_section( + handle, + &format!("tabmenu.{TAB_MENU_FOLDER_PREFIX}"), + context.in_folder, + )? + } else { + None + }; let mut items: Vec<&dyn tauri::menu::IsMenuItem> = vec![ &reload, &duplicate, @@ -6759,6 +6787,9 @@ fn build_tab_menu( &keep, &split, ]; + if let Some(folder) = &folder { + items.push(folder); + } if let Some(move_to) = &move_to { items.push(move_to); } @@ -7351,6 +7382,7 @@ fn finish_browser_setup( let operation_ledger = OperationLedger::default(); app.manage(operation_ledger.clone()); app.manage(TabMenuTarget::default()); + app.manage(folders::FolderMenuTarget::default()); app.manage(history_menu::HistoryMenuTarget::default()); app.manage(keymap::Keymap::load()); @@ -7453,6 +7485,7 @@ fn finish_browser_setup( #[cfg(feature = "adblock-qa")] blocker_bench::items(&state); spaces::follow(&emit_handle, &state); + folders::follow(&state); page_assist::observe_items(&state); emit_to_privileged(&emit_handle, MAIN_LABEL, EVENT_ITEMS, &state) } diff --git a/frame/src/shared/ipc/bindings.ts b/frame/src/shared/ipc/bindings.ts index d66c0cce1..48e877873 100644 --- a/frame/src/shared/ipc/bindings.ts +++ b/frame/src/shared/ipc/bindings.ts @@ -256,6 +256,8 @@ export const commands = { tabsActivate: (id: string) => __TAURI_INVOKE("tabs_activate", { id }), tabsClose: (id: string) => __TAURI_INVOKE("tabs_close", { id }), tabsSetEssential: (id: string, essential: boolean, before: string | null) => __TAURI_INVOKE("tabs_set_essential", { id, essential, before }), + tabsFolder: (intent: FolderIntent) => __TAURI_INVOKE("tabs_folder", { intent }), + folderMenuPopup: (id: string, x: number | null, y: number | null, context: FolderMenuContext) => __TAURI_INVOKE("folder_menu_popup", { id, x, y, context }), /** * Onboarding keeps a site by its catalog id; native owns the address and * the mark, so chrome can never pin an arbitrary URL through this path. @@ -1611,6 +1613,43 @@ export type FocusView = { allowed: string[], }; +/** A folder's colour: one of the interface's soft hues, or none. */ +export type FolderColor = "sky" | "mint" | "lemon" | "peach" | "rose" | "lilac"; + +/** + * What chrome asks of the sidebar's folders. Every id is one the focused + * space projected; native checks each against that space again. + */ +export type FolderIntent = +/** + * A new folder holding `tabs`, in sidebar order. With tabs it takes the + * first one's place; without, it goes into `parent` before `before`. + */ +{ type: "create"; name: string; color: FolderColor | null; tabs: string[]; parent: string | null; before: string | null } | { type: "rename"; id: string; name: string } | { type: "set_color"; id: string; color: FolderColor | null } | { type: "set_collapsed"; id: string; collapsed: boolean } | +/** + * A tab or a folder, into `parent` (none: the open tabs) before + * `before` (none: at the end). + */ +{ type: "move"; id: string; parent: string | null; before: string | null } | +/** The folder goes; what it held stays where it was. */ +{ type: "ungroup"; id: string } | +/** Every page in the folder ends; the tabs stay in it, asleep. */ +{ type: "close_tabs"; id: string } | +/** The folder and its tabs close. Reopen Closed Tab brings it back. */ +{ type: "delete"; id: string }; + +/** + * What a folder's menu can offer, as the sidebar sees it. Only + * availability: the shell checks every action again. + */ +export type FolderMenuContext = { + color: FolderColor | null, + /** Another folder level fits inside this one. */ + can_nest: boolean, + /** A page in it is loaded. */ + awake: boolean, +}; + export type HapticKind = "align" | "level"; /** @@ -3094,7 +3133,9 @@ export type SidebarMenuExtension = { * into [`ItemsState::tabs`]. The node id and tab id intentionally match, but * the explicit reference keeps consumers from inferring that invariant. */ -export type SidebarNodeKindView = { type: "folder"; name: string } | { type: "tab"; tab_id: string }; +export type SidebarNodeKindView = { type: "folder"; name: string; color: FolderColor | null; +/** Folded: its rows are hidden, the active tab's excepted. */ +collapsed: boolean } | { type: "tab"; tab_id: string }; /** * One pre-order entry in the focused sidebar tree. Parents always precede @@ -3316,6 +3357,10 @@ export type TabMenuContext = { * in-use indicator. */ media_only: boolean, + /** A web page that may go into a folder. */ + fileable?: boolean, + /** The tab is in a folder now. */ + in_folder?: boolean, }; export type TabSwitcherAction = { type: "step"; reverse: boolean } | { type: "select"; index: number } | { type: "commit" } | { type: "cancel" } | { type: "close" } | @@ -3387,6 +3432,11 @@ export type TabView = { zoom?: number | null, /** Present while the page plays sound, and for as long as it is muted. */ audio?: TabAudioView | null, + /** + * A web page whose address is kept but which has no live view: it + * loads when opened. + */ + asleep?: boolean, }; /** From 347518538a72fa9ac6ea19b8c4ef3d216ea93cae Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Wed, 18 Nov 2026 10:54:23 +0100 Subject: [PATCH 03/20] feat(tabs): take a folder's sleeping tab out when it is closed again Closing a folder's tab ends its page and keeps it asleep in place. Closing it again, asleep, now removes it from the folder and records it in Recently Closed, so the sidebar's close control can mean "close page" while awake and "remove" while asleep. An asleep Essential still has nothing to end and stays. --- crates/zephium-app/src/shell/operations.rs | 2 +- crates/zephium-app/src/shell/tabs.rs | 13 +++++++++++++ crates/zephium-app/src/shell/tests/folders.rs | 12 +++++++----- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/zephium-app/src/shell/operations.rs b/crates/zephium-app/src/shell/operations.rs index 2026b6c79..6267c2275 100644 --- a/crates/zephium-app/src/shell/operations.rs +++ b/crates/zephium-app/src/shell/operations.rs @@ -612,7 +612,7 @@ impl Shell { self.browser_after_return = Some(Box::new(Command::Close(id))); return self.request_browser_return(); } - if self.kept_asleep(id) { + if self.kept_asleep(id) && !self.asleep_in_folder(id) { return operation_result(OperationOutcome::NoOp, OperationReason::StateUnchanged); } let discard_closing = matches!( diff --git a/crates/zephium-app/src/shell/tabs.rs b/crates/zephium-app/src/shell/tabs.rs index 59c7e2625..a2fd426bc 100644 --- a/crates/zephium-app/src/shell/tabs.rs +++ b/crates/zephium-app/src/shell/tabs.rs @@ -286,6 +286,9 @@ impl Shell { if !self.item_in_focused_scope(id) || self.is_lone_new_tab(id) { return NativeWork::default(); } + // Closing a folder's tab that is already asleep removes it; an + // asleep Essential has nothing to end and stays. + let keep = keep && !self.asleep_in_folder(id); if keep && self.kept_asleep(id) { return NativeWork::default(); } @@ -367,6 +370,16 @@ impl Shell { .is_none_or(|win| win.active != Some(id)) } + /// A folder's tab already asleep: closing it again takes it out. + pub(super) fn asleep_in_folder(&self, id: ItemId) -> bool { + self.kept_asleep(id) + && self + .items + .get(id) + .and_then(|item| item.parent) + .is_some_and(|parent| self.items.is_folder(parent)) + } + /// Where an Essential or a folder's tab sits, so closing it can leave it /// there unloaded. fn kept_slot(&self, id: ItemId) -> Option { diff --git a/crates/zephium-app/src/shell/tests/folders.rs b/crates/zephium-app/src/shell/tests/folders.rs index 30bcef663..bbb42758b 100644 --- a/crates/zephium-app/src/shell/tests/folders.rs +++ b/crates/zephium-app/src/shell/tests/folders.rs @@ -192,7 +192,7 @@ fn a_folder_is_renamed_coloured_and_folded_and_keeps_that_across_a_restart() { } #[test] -fn closing_a_folder_tab_keeps_it_asleep_in_its_place_and_never_wakes_another() { +fn closing_a_folder_tab_keeps_it_asleep_once_then_takes_it_out() { let (mut shell, _engine, screen, _store) = browsed(); let ids = tabs( &mut shell, @@ -220,12 +220,14 @@ fn closing_a_folder_tab_keeps_it_asleep_in_its_place_and_never_wakes_another() { assert!(shell.items.tab(next).unwrap().has_view()); assert_ne!(next, held[2]); - // An asleep tab out of the window has nothing to end. + // Closing it again, asleep, takes it out of the folder for good. assert_eq!( op(&mut shell, Command::Close(held[2])).outcome, - OperationOutcome::NoOp + OperationOutcome::Applied ); - assert_eq!(shell.items.children(folder), held); + assert_eq!(shell.items.children(folder), &held[..2]); + assert_eq!(shell.recently_closed.len(), closed_before + 1); + let held = shell.items.children(folder).to_vec(); // Closing the folder's tabs ends every page and keeps every tab. assert_eq!( @@ -233,7 +235,7 @@ fn closing_a_folder_tab_keeps_it_asleep_in_its_place_and_never_wakes_another() { OperationOutcome::Applied ); let held = shell.items.children(folder).to_vec(); - assert_eq!(held.len(), 3); + assert_eq!(held.len(), 2); assert!(held .iter() .all(|id| !shell.items.tab(*id).unwrap().has_view())); From 47e4d01c059d4a0fcf652fde81b61831143f14ab Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Wed, 18 Nov 2026 20:08:35 +0100 Subject: [PATCH 04/20] feat(sidebar): fold, rename, drag and file tabs into folders Folders in a space's open tabs get their own row: the folder's colour on its glyph and a hairline down the rows it holds, a fold kept by native across restarts, and, folded, a live summary of what it holds (the first sites' icons with their loading state, how many more, and a speaker while one plays). A folded folder keeps the tab in front visible beneath it. Rows reorder as a tree: a folder drags with what it holds, the gap a row waits in bounds how deep it can go, and sideways travel picks the level, shown by setting the row in and lighting the folder it would join. Native admits every move; a refused one slides home. New folders come from the space bar, the tab menu, the selection bar and Group into Folder; each opens for its name once native has made it. Double-click or F2 renames, the arrow keys fold, unfold and walk out, and the context-menu key opens the folder's native menu. A folder's tab offers "close page" while awake and "remove" once asleep. The browser bundle's recorded size rises by 14.3 KB of JS and 2.7 KB of CSS over this branch's base (measured with pnpm run budgets on both); only the startup entry is re-recorded. --- desktop/src/folders.rs | 24 ++ desktop/src/menu_text.rs | 1 + frame/bundle-budgets.json | 4 +- frame/messages/en.json | 33 +- frame/src/app/browser/Shell.svelte | 17 + frame/src/domain/tabs/tabs.svelte.ts | 43 ++- .../src/domain/tabs/tests/tabs-model.test.ts | 2 +- .../features/onboarding/tests/kept.test.ts | 2 +- .../src/features/settings/lib/keymap-model.ts | 1 + .../features/tabs/components/FolderRow.svelte | 358 ++++++++++++++++-- .../tabs/components/SidebarBody.svelte | 17 + .../features/tabs/components/SpaceBar.svelte | 11 +- .../tabs/components/SplitGroupRow.svelte | 4 + .../features/tabs/components/TabList.svelte | 140 +++++-- .../features/tabs/components/TabRow.svelte | 27 +- .../tabs/components/TabSelectionBar.svelte | 26 ++ frame/src/features/tabs/lib/folder-group.ts | 20 + frame/src/features/tabs/lib/folder-look.ts | 20 + frame/src/features/tabs/lib/sidebar-model.ts | 109 +++++- .../tabs/tests/SpaceBar.component.test.ts | 3 +- .../tabs/tests/TabFolders.component.test.ts | 274 ++++++++++++++ .../tabs/tests/TabSelection.component.test.ts | 11 +- frame/src/features/tabs/tests/folders.test.ts | 129 +++++++ .../features/tabs/tests/sidebar-model.test.ts | 7 +- frame/src/session/folder-edit.svelte.ts | 119 ++++++ frame/src/session/reorder.ts | 115 ++++-- frame/src/session/row-drag.svelte.ts | 85 ++++- frame/src/session/tests/tree-drop.test.ts | 61 +++ frame/src/session/tree-drop.ts | 60 +++ frame/src/styles/browser.css | 48 +-- 30 files changed, 1616 insertions(+), 155 deletions(-) create mode 100644 frame/src/features/tabs/lib/folder-group.ts create mode 100644 frame/src/features/tabs/lib/folder-look.ts create mode 100644 frame/src/features/tabs/tests/TabFolders.component.test.ts create mode 100644 frame/src/features/tabs/tests/folders.test.ts create mode 100644 frame/src/session/folder-edit.svelte.ts create mode 100644 frame/src/session/tests/tree-drop.test.ts create mode 100644 frame/src/session/tree-drop.ts diff --git a/desktop/src/folders.rs b/desktop/src/folders.rs index 9e1d3c8cb..a3e420b65 100644 --- a/desktop/src/folders.rs +++ b/desktop/src/folders.rs @@ -449,6 +449,30 @@ mod tests { )); } + #[test] + fn every_folder_menu_label_has_an_english_message() { + let english: std::collections::HashMap = + serde_json::from_str(include_str!("../../frame/messages/en.json")).unwrap(); + let entries = include_str!("folders.rs") + .split("entry(handle, \"") + .skip(1) + .filter_map(|rest| rest.split_once("\", \"")?.1.split_once('"')) + .map(|(label, _)| label); + let labels: Vec<&str> = COLORS + .iter() + .map(|(_, _, title)| *title) + .chain(entries) + .collect(); + assert_eq!(labels.len(), 12); + for label in labels { + assert_eq!( + english.get(&menu_text::key(label)).map(String::as_str), + Some(label), + "{label}" + ); + } + } + #[test] fn the_tab_menu_lists_the_projected_folders_by_depth() { let node = |id: &str, parent: Option<&str>, name: &str| zephium_ipc::SidebarNodeView { diff --git a/desktop/src/menu_text.rs b/desktop/src/menu_text.rs index cb5197e3e..b35cfd507 100644 --- a/desktop/src/menu_text.rs +++ b/desktop/src/menu_text.rs @@ -170,6 +170,7 @@ mod tests { let sources = [ include_str!("lib.rs"), include_str!("spaces.rs"), + include_str!("folders.rs"), include_str!("help.rs"), include_str!("recently_closed.rs"), include_str!("resource_close.rs"), diff --git a/frame/bundle-budgets.json b/frame/bundle-budgets.json index 997957724..03c5bb61c 100644 --- a/frame/bundle-budgets.json +++ b/frame/bundle-budgets.json @@ -1,8 +1,8 @@ { "browser-panel": { "browser": { - "js": 517238, - "css": 159147 + "js": 537494, + "css": 161757 }, "lazy:app/browser/WorkWorkspace.svelte": { "js": 38319, diff --git a/frame/messages/en.json b/frame/messages/en.json index 54b39c0e8..d032fb3fe 100644 --- a/frame/messages/en.json +++ b/frame/messages/en.json @@ -263,6 +263,7 @@ "command_window_show_private": "Switch to private window", "command_note_new": "New note", "command_split_choose": "Split view", + "command_tab_group": "Group into folder", "command_page_print": "Print", "command_page_save": "Save page as", "command_page_devtools": "Developer Tools", @@ -3998,5 +3999,35 @@ "blocker_hiding_hidden": "{label} hidden", "blocker_hiding_pick": "Click anything on the page", "blocker_hiding_undo": "Undo", - "blocker_hiding_done": "Done" + "blocker_hiding_done": "Done", + "native_rename_folder_more": "Rename Folder…", + "native_color": "Color", + "native_no_color": "No Color", + "native_sky": "Sky", + "native_mint": "Mint", + "native_lemon": "Lemon", + "native_peach": "Peach", + "native_rose": "Rose", + "native_lilac": "Lilac", + "native_new_folder_inside": "New Folder Inside", + "native_close_tabs_in_folder": "Close Tabs in Folder", + "native_ungroup": "Ungroup", + "native_delete_folder_and_tabs": "Delete Folder and Tabs", + "native_move_to_folder": "Move to Folder", + "native_new_folder_more": "New Folder…", + "native_remove_from_folder": "Remove from Folder", + "native_group_into_folder": "Group into Folder", + "folder_default_name": "New folder", + "folder_label": "{name}, folder, {count} tabs", + "folder_label_folded": "{name}, folder, {count} tabs, folded", + "folder_label_one": "{name}, folder, 1 tab", + "folder_label_folded_one": "{name}, folder, 1 tab, folded", + "folder_name": "Folder name", + "folder_new": "New folder", + "folder_playing": "Playing sound", + "folder_tab_sleep": "Close page, keep tab", + "folder_tab_sleep_named": "Close {title} and keep it in the folder", + "folder_tab_remove": "Remove tab", + "folder_tab_remove_named": "Remove {title} from the folder", + "tab_selection_group": "Group selected tabs into a folder" } diff --git a/frame/src/app/browser/Shell.svelte b/frame/src/app/browser/Shell.svelte index d5b0ae94c..df37bbd80 100644 --- a/frame/src/app/browser/Shell.svelte +++ b/frame/src/app/browser/Shell.svelte @@ -33,6 +33,7 @@ import { loadNavigationError, loadTabCapacityState } from "$features/tabs"; import { selectionGlide } from "$features/tabs"; import * as tabDrag from "$session/tab-drag.svelte"; + import * as folderEdit from "$session/folder-edit.svelte"; import { requestTab } from "$session/work-tab.svelte"; import { expanded as sidebarWidth, expandBriefly } from "$session/sidebar-mode.svelte"; import { uiCommands as ui } from "$domain/ui-commands"; @@ -337,6 +338,22 @@ handledCommand = command.seq; untrack(() => { if (command.id === "split.choose") chooseSplit(); + if (command.id === "tab.group") folderEdit.askGroup(); + if (command.id === "tab.newFolder") { + const tab = tabs.takeMenuTarget(); + if (tab) void folderEdit.create(m.folder_default_name(), { tabs: [tab] }); + } + if (command.id === "folder.rename") { + const folder = tabs.takeFolderMenuTarget(); + if (folder) folderEdit.rename(folder); + } + if (command.id === "folder.newSubfolder") { + const folder = tabs.takeFolderMenuTarget(); + if (folder) { + void folderEdit.setFolded(folder, false); + void folderEdit.create(m.folder_default_name(), { parent: folder }); + } + } if (command.id === "tab.copyLink") void tabs.copyMenuTargetLink().then(linkCopied); if (command.id === "page.copyLink") void tabs.copyActiveLink().then(linkCopied); if (command.id === "tab.clearSiteData") clearRequest.ask(tabs.takeMenuTargetUrl()); diff --git a/frame/src/domain/tabs/tabs.svelte.ts b/frame/src/domain/tabs/tabs.svelte.ts index 13f346c05..ffe0dc5a0 100644 --- a/frame/src/domain/tabs/tabs.svelte.ts +++ b/frame/src/domain/tabs/tabs.svelte.ts @@ -1,7 +1,14 @@ import { listenAll } from "$shared/lib/lifecycle"; import { forgetDrafts } from "$shared/lib/drafts"; import { flushSync } from "svelte"; -import type { ItemsState, SpaceLookInputV1, TabMenuContext, TabView } from "$shared/ipc/bindings"; +import type { + FolderIntent, + FolderMenuContext, + ItemsState, + SpaceLookInputV1, + TabMenuContext, + TabView, +} from "$shared/ipc/bindings"; import { settle } from "$domain/operations"; import { commands } from "$shared/ipc/bindings"; import { events } from "$shared/ipc/native-events"; @@ -168,7 +175,11 @@ function tabMenuContext(id: string, mediaOnly = false): TabMenuContext { .map(tabOf) .filter((candidate) => candidate !== null); const at = open.indexOf(id); + const node = state.nodes.find((candidate) => tabOf(candidate) === id); return { + fileable: + (tab?.content ?? "web") === "web" && node !== undefined && node.section !== "favorites", + in_folder: node?.parent_id != null, page: (tab?.content ?? "web") === "web" && (tab?.url ?? null) !== null, can_split: canSplitWith(id), essential: state.nodes.some((node) => tabOf(node) === id && node.section === "favorites"), @@ -180,6 +191,13 @@ function tabMenuContext(id: string, mediaOnly = false): TabMenuContext { }; } +/** The tab the menu was opened on, taken once: its New Folder… files it. */ +export function takeMenuTarget(): string | null { + const id = menuTarget; + menuTarget = null; + return id; +} + export function openTabMenu(id: string, x: number, y: number) { menuTarget = id; void commands.tabMenuPopup(id, x, y, tabMenuContext(id)); @@ -226,6 +244,29 @@ function copyLink(url: string | null | undefined): Promise { ); } +/** Folder intents settle on native's answer; the projection carries the result. */ +export const folder = (intent: FolderIntent) => settle(commands.tabsFolder(intent)); + +let folderMenuTarget: string | null = null; + +/** A folder's own menu; native names its spaces and checks every action. */ +export function openFolderMenu( + id: string, + x: number | null, + y: number | null, + context: FolderMenuContext, +) { + folderMenuTarget = id; + void commands.folderMenuPopup(id, x, y, context); +} + +/** The folder its menu was opened on, taken once by Rename or New Folder Inside. */ +export function takeFolderMenuTarget(): string | null { + const id = folderMenuTarget; + folderMenuTarget = null; + return id; +} + /** Space intents settle on native's answer; the projection carries the result. */ export const switchSpace = (id: string) => settle(commands.spacesSwitch(id)); export const stepSpace = (step: 1 | -1) => settle(commands.spacesStep(step)); diff --git a/frame/src/domain/tabs/tests/tabs-model.test.ts b/frame/src/domain/tabs/tests/tabs-model.test.ts index cf27ffedf..4331eccf4 100644 --- a/frame/src/domain/tabs/tests/tabs-model.test.ts +++ b/frame/src/domain/tabs/tests/tabs-model.test.ts @@ -119,7 +119,7 @@ describe("tab projection admission", () => { id: "folder", parent_id: null, section: "pinned", - kind: { type: "folder", name: "Project" }, + kind: { type: "folder", name: "Project", color: null, collapsed: false }, }, { id: "b", diff --git a/frame/src/features/onboarding/tests/kept.test.ts b/frame/src/features/onboarding/tests/kept.test.ts index 7a5b46dc3..bf8eb73d9 100644 --- a/frame/src/features/onboarding/tests/kept.test.ts +++ b/frame/src/features/onboarding/tests/kept.test.ts @@ -48,7 +48,7 @@ describe("keptSites", () => { id: "f", parent_id: null, section: "favorites", - kind: { type: "folder", name: "Work" }, + kind: { type: "folder", name: "Work", color: null, collapsed: false }, }; expect(keptSites([folder, node("n", "favorites")], [tab("n", null)], URLS).size).toBe(0); }); diff --git a/frame/src/features/settings/lib/keymap-model.ts b/frame/src/features/settings/lib/keymap-model.ts index 8844f95f2..6926e58e1 100644 --- a/frame/src/features/settings/lib/keymap-model.ts +++ b/frame/src/features/settings/lib/keymap-model.ts @@ -14,6 +14,7 @@ const TITLES: Record string> = { "window.showPrivate": m.command_window_show_private, "note.new": m.command_note_new, "split.choose": m.command_split_choose, + "tab.group": m.command_tab_group, "page.save": m.command_page_save, "page.print": m.command_page_print, "page.viewSource": m.command_page_view_source, diff --git a/frame/src/features/tabs/components/FolderRow.svelte b/frame/src/features/tabs/components/FolderRow.svelte index e9a5c1bfb..1f821a0d5 100644 --- a/frame/src/features/tabs/components/FolderRow.svelte +++ b/frame/src/features/tabs/components/FolderRow.svelte @@ -1,33 +1,345 @@ -
  • - +
  • + {#if editing} +
    + + { + if (event.isComposing) return; + if (event.key === "Enter") { + event.preventDefault(); + finish(true); + } else if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + finish(false); + } + }} + onblur={() => finish(true)} + /> +
    + {:else} + + {/if}
  • + + diff --git a/frame/src/features/tabs/components/SidebarBody.svelte b/frame/src/features/tabs/components/SidebarBody.svelte index a446ab1ac..da64f0257 100644 --- a/frame/src/features/tabs/components/SidebarBody.svelte +++ b/frame/src/features/tabs/components/SidebarBody.svelte @@ -14,6 +14,8 @@ import { arrive, spaceSwipe, stepSpace } from "../lib/space-swipe"; import { openOnBackgroundMiddleClick } from "../lib/middle-click"; import { untrack, type Snippet } from "svelte"; + import * as folderEdit from "$session/folder-edit.svelte"; + import { groupable } from "../lib/folder-group"; let { pinned, @@ -36,6 +38,21 @@ selection.clear(); } + // Group into Folder: the selected tabs, or the one in front. + let groupHandled = folderEdit.groupAsked(); + $effect(() => { + const asked = folderEdit.groupAsked(); + if (asked === groupHandled) return; + groupHandled = asked; + untrack(() => { + const chosen = selection.value.ids.length > 0 ? selection.value.ids : [tabs.activeId()]; + const ids = groupable(chosen, tabs.tabs(), tabs.sidebarNodes()); + if (ids.length === 0) return; + selection.clear(); + void folderEdit.create(m.folder_default_name(), { tabs: ids }); + }); + }); + let pinnedOrder = $state.raw([]); let todayOrder = $state.raw([]); const rangeOrder = $derived([...pinnedOrder, ...todayOrder]); diff --git a/frame/src/features/tabs/components/SpaceBar.svelte b/frame/src/features/tabs/components/SpaceBar.svelte index c94ad279b..41ec049ed 100644 --- a/frame/src/features/tabs/components/SpaceBar.svelte +++ b/frame/src/features/tabs/components/SpaceBar.svelte @@ -1,7 +1,8 @@