diff --git a/packages/frontend/desktop/src/pane_render.rs b/packages/frontend/desktop/src/pane_render.rs index 5790d71ff4..ec65574c58 100644 --- a/packages/frontend/desktop/src/pane_render.rs +++ b/packages/frontend/desktop/src/pane_render.rs @@ -121,7 +121,7 @@ pub(crate) fn render_pane_content( "All Docs", "All active collaborative documents in this workspace.", store.visible_docs(), - scroll_y, + pane_width, palette, cx, ) @@ -139,7 +139,7 @@ pub(crate) fn render_pane_content( name, "Smart collection filtered dynamically by rules.", store.docs_for_collection(&col_id), - scroll_y, + pane_width, palette, cx, ) @@ -150,7 +150,7 @@ pub(crate) fn render_pane_content( &store.tag_label(&tag), "Documents carrying this workspace tag.", store.docs_for_tag(&tag), - scroll_y, + pane_width, palette, cx, ) diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/cache.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/cache.rs index 79903cde85..31e8a3cdd0 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/cache.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/cache.rs @@ -44,7 +44,6 @@ pub(super) struct ExplorerOrderCache { ascending: bool, group_by: Option, collapsed: BTreeSet, - grid_grouped: bool, selecting_grouped: bool, selected_grouped: BTreeSet, today_date: String, @@ -65,14 +64,12 @@ impl ExplorerOrderCache { ascending: bool, group_by: Option, collapsed: &BTreeSet, - grid: bool, selecting: bool, selected: &BTreeSet, today_date: &str, theme: ThemeMode, ) -> CachedExplorerOrder { let views = store.views(); - let grid_grouped = group_by.is_some() && grid; let selecting_grouped = group_by.is_some() && selecting; let selected_grouped = if selecting_grouped { selected.clone() @@ -93,7 +90,6 @@ impl ExplorerOrderCache { && cached.ascending == ascending && cached.group_by == group_by && cached.collapsed == collapsed_grouped - && cached.grid_grouped == grid_grouped && cached.selecting_grouped == selecting_grouped && cached.selected_grouped == selected_grouped && cached.today_date == today_date @@ -129,7 +125,7 @@ impl ExplorerOrderCache { &docs_by_id, &views, &collapsed_grouped, - (grid_grouped, selecting_grouped, &selected_grouped), + (selecting_grouped, &selected_grouped), )); (groups, order_ids, row_keys) } else { @@ -151,7 +147,6 @@ impl ExplorerOrderCache { ascending, group_by, collapsed: collapsed_grouped, - grid_grouped, selecting_grouped, selected_grouped, today_date: today_date.to_owned(), @@ -198,7 +193,6 @@ mod tests { None, &empty_set, false, - false, &empty_set, "2026-12-03", ThemeMode::Light, @@ -318,7 +312,6 @@ mod tests { None, &empty_set, false, - false, &empty_set, "2026-12-03", ThemeMode::Light, diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/grouping.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/grouping.rs index fc0659555c..10538842f3 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/grouping.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/grouping.rs @@ -27,7 +27,6 @@ use crate::{ const DAY_MS: i64 = 86_400_000; pub(super) const GROUP_HEADER_PREFIX: &str = "\0hdr:"; -pub(super) const GRID_PAIR_PREFIX: &str = "\0pair:"; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(super) enum GroupHeaderIcon { @@ -370,7 +369,7 @@ pub(super) fn build_grouped_row_keys( docs_by_id: &BTreeMap<&str, &DesktopDocMeta>, views: &DocViews, collapsed: &BTreeSet, - (grid, selecting, selected): (bool, bool, &BTreeSet), + (selecting, selected): (bool, &BTreeSet), ) -> Vec { let mut keys = Vec::new(); for group in groups { @@ -400,53 +399,13 @@ pub(super) fn build_grouped_row_keys( updated_at_ms: group.doc_ids.len() as i64, outgoing_refs: Vec::new(), }; - keys.push(DocRowKey::explorer(&header_meta, views)); + keys.push(DocRowKey::explorer(&header_meta, views).full_width()); if is_collapsed { continue; } - if grid { - for pair in group.doc_ids.chunks(2) { - let Some(first) = docs_by_id.get(pair[0].as_str()).copied() else { - continue; - }; - let second = pair - .get(1) - .and_then(|id| docs_by_id.get(id.as_str()).copied()); - let pair_id = match second { - Some(b) => format!("{GRID_PAIR_PREFIX}{}\0{}", first.id, b.id), - None => format!("{GRID_PAIR_PREFIX}{}", first.id), - }; - let mut pair_tags = first.tags.clone(); - if let Some(b) = second { - pair_tags.extend(b.tags.iter().cloned()); - } - let pair_meta = DesktopDocMeta { - id: pair_id, - title: match second { - Some(b) => format!("{}\0{}", first.title, b.title), - None => first.title.clone(), - }, - summary: match second { - Some(b) => format!("{}\0{}", first.summary, b.summary), - None => first.summary.clone(), - }, - default_mode: first.default_mode, - page_width: first.page_width, - tags: pair_tags, - is_favorite: first.is_favorite || second.is_some_and(|b| b.is_favorite), - trashed: false, - journal_date: first.journal_date.clone(), - updated_at_ms: first.updated_at_ms - ^ second.map_or(0, |b| b.updated_at_ms.rotate_left(17)), - outgoing_refs: Vec::new(), - }; - keys.push(DocRowKey::explorer(&pair_meta, views)); - } - } else { - for doc_id in &group.doc_ids { - if let Some(doc) = docs_by_id.get(doc_id.as_str()).copied() { - keys.push(DocRowKey::explorer(doc, views)); - } + for doc_id in &group.doc_ids { + if let Some(doc) = docs_by_id.get(doc_id.as_str()).copied() { + keys.push(DocRowKey::explorer(doc, views)); } } } @@ -579,9 +538,7 @@ pub(super) fn render_group_header( ) .group(hover_group) .w_full() - .h(px(28.0)) - .mt(px(6.0)) - .mb(px(2.0)) + .h(px(24.0)) .px(px(6.0)) .rounded(px(4.0)) .flex() diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs index ce932babfd..61cf29337c 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/mod.rs @@ -40,7 +40,7 @@ use super::{ doc_order::{DocOrder, order_docs}, journals::LocalZone, max_width, menu_button, normalize_timestamp, resolve_tag_color, - scroll::{DocRowKey, RowStyle, doc_identity, virtual_scroll_shared}, + scroll::{DocRowKey, RowStyle, doc_identity, virtual_scroll}, selection_icon, tag_chip, update_tag, vertical_scroll, }; use crate::{ @@ -55,12 +55,13 @@ pub(crate) fn render_doc_list_view( heading: &str, _subtitle: &str, docs: Vec<&DesktopDocMeta>, - _scroll_y: f32, + pane_width: f32, palette: DesktopPalette, cx: &mut Context, ) -> impl IntoElement { ui::ViewElement::new(DocsExplorer { pane_idx, + pane_width, heading: heading.into(), ids: docs.into_iter().map(|doc| doc.id.clone()).collect(), palette, @@ -70,6 +71,7 @@ pub(crate) fn render_doc_list_view( struct DocsExplorer { pane_idx: usize, + pane_width: f32, heading: SharedString, ids: Vec, palette: DesktopPalette, @@ -172,12 +174,18 @@ impl RenderOnce for DocsExplorer { let viewport_size = window.viewport_size(); let compact_width = viewport_size.width <= px(720.0); let compact_height = viewport_size.height < px(280.0); - let mut header = div().flex().items_center().gap(px(2.0)).w_full().min_w_0(); - header = if compact_height { - header.overflow_hidden() - } else { - header.flex_wrap() + // A narrow pane wraps the controls. A short pane makes them smaller so that the rows + // keep their height, but every control keeps its full width. + let compact = |button: ui::Stateful| { + button.when(compact_height, |button| button.min_h(px(24.0)).px(px(4.0))) }; + let mut header = div() + .flex() + .flex_wrap() + .items_center() + .gap(px(2.0)) + .w_full() + .min_w_0(); for (id, name, target) in [ ("desktop.explorer.nav.docs", "All Docs", Destination::Docs), ( @@ -195,7 +203,7 @@ impl RenderOnce for DocsExplorer { let navigate = controls.navigate(DesktopRoute::AllDocs, Some(target)); let controls = controls.clone(); header = header.child( - button(id, name, palette, true) + compact(button(id, name, palette, true)) .snapshot(id, Some("desktop.workbench")) .font_weight(if active { FontWeight::SEMIBOLD @@ -240,7 +248,6 @@ impl RenderOnce for DocsExplorer { prefs.ascending, prefs.group_by.clone(), &collapsed_groups, - grid, selecting && writable, &selected_set, &today_date, @@ -285,7 +292,13 @@ impl RenderOnce for DocsExplorer { .flex() .flex_col() .size_full() - .px(px(if compact_width { 12.0 } else { 24.0 })) + // The responsive side padding of the web docs list, smaller in a short pane. + .px(px(match self.pane_width { + _ if compact_height => 12.0, + width if width > 500.0 => 24.0, + width if width > 393.0 => 20.0, + _ => 16.0, + })) .pt(px(if compact_height { 4.0 } else { 14.0 })) .gap(px(if compact_height { 4.0 } else { 12.0 })) .font_family(FONT_SANS) @@ -295,7 +308,7 @@ impl RenderOnce for DocsExplorer { header = header .child(div().flex_1()) .child( - button("desktop.explorer.list", "List", palette, true) + compact(button("desktop.explorer.list", "List", palette, true)) .bg(if grid { ui::transparent_black() } else { @@ -318,7 +331,7 @@ impl RenderOnce for DocsExplorer { }), ) .child( - button("desktop.explorer.grid", "Grid", palette, true) + compact(button("desktop.explorer.grid", "Grid", palette, true)) .snapshot("desktop.explorer.grid", Some("desktop.workbench")) .bg(if grid { palette.bg_pill @@ -342,28 +355,33 @@ impl RenderOnce for DocsExplorer { }), ) .child( - menu_button("desktop.explorer.sort", "Sort", palette, true) + compact(menu_button("desktop.explorer.sort", "Sort", palette, true)) .on_click(controls.open_popup(|| Menu::Order)), ) .child({ let trigger_bounds = controls.display_menu.read(app).trigger_bounds_cell(); - menu_button("desktop.explorer.display", "Display", palette, true) - .snapshot("desktop.explorer.display", Some("desktop.workbench")) - .relative() - .child( - ui::canvas( - move |bounds, _, _| { - trigger_bounds.set(Some(bounds)); - }, - |_, (), _, _| {}, - ) - .absolute() - .inset_0(), + compact(menu_button( + "desktop.explorer.display", + "Display", + palette, + true, + )) + .snapshot("desktop.explorer.display", Some("desktop.workbench")) + .relative() + .child( + ui::canvas( + move |bounds, _, _| { + trigger_bounds.set(Some(bounds)); + }, + |_, (), _, _| {}, ) - .on_click(controls.open_display_menu()) + .absolute() + .inset_0(), + ) + .on_click(controls.open_display_menu()) }) .child( - menu_button( + compact(menu_button( "desktop.explorer.filter", match filter { None => "All types", @@ -372,16 +390,16 @@ impl RenderOnce for DocsExplorer { }, palette, true, - ) + )) .on_click(controls.open_popup(|| Menu::Filter)), ) .child( - button( + compact(button( "desktop.explorer.select", if selecting { "Done" } else { "Select" }, palette, writable, - ) + )) .snapshot("desktop.explorer.select", Some("desktop.workbench")) .when(writable, |button| { button.on_click(controls.change(|state, _| { @@ -397,7 +415,11 @@ impl RenderOnce for DocsExplorer { .when(on_route == DesktopRoute::AllDocs, |header| { header.child( div() - .pl(px(if compact_width { 2.0 } else { 8.0 })) + .pl(px(if compact_width || compact_height { + 2.0 + } else { + 8.0 + })) .child(new_doc_button(&controls, palette, writable)), ) }); @@ -574,7 +596,7 @@ impl RenderOnce for DocsExplorer { let render_controls = controls.clone(); let selecting_rows = selecting && writable; let grouped = prefs.group_by.is_some(); - let style = if grid && !grouped { + let style = if grid { RowStyle::Grid { selecting: selecting_rows, } @@ -593,14 +615,14 @@ impl RenderOnce for DocsExplorer { grouped, active_pinned_col.as_deref().unwrap_or_default() )); - root.child(virtual_scroll_shared( + root.child(virtual_scroll( scroll_key, state_key, cached.row_keys, style, - move |keys, app| { + move |key, app| { doc_row( - keys, + key, (grid, writable, can_split), &order_ids, &prefs_for_rows, diff --git a/packages/frontend/desktop/src/views_extra/docs_explorer/rows.rs b/packages/frontend/desktop/src/views_extra/docs_explorer/rows.rs index c86b324c89..c4729e03fa 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/rows.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/rows.rs @@ -11,7 +11,7 @@ use ui_tokens::{ThemeMode, icons}; use super::{ Controls, DocAction, DocRowKey, ExplorerGroup, ExplorerState, PageWidth, display_time, doc_identity, - grouping::{GRID_PAIR_PREFIX, GROUP_HEADER_PREFIX, render_group_header}, + grouping::{GROUP_HEADER_PREFIX, render_group_header}, max_width, resolve_tag_color, selection_icon, tag_chip, }; use crate::{ @@ -23,7 +23,7 @@ use crate::{ #[allow(clippy::too_many_arguments)] pub(super) fn doc_row( - keys: &[DocRowKey], + key: &DocRowKey, (grid, writable, can_split): (bool, bool, bool), order: &Rc>, prefs: &DisplayPreference, @@ -33,16 +33,13 @@ pub(super) fn doc_row( controls: &Controls, app: &App, ) -> AnyElement { - let Some(first_key) = keys.first() else { - return div().into_any_element(); - }; let shell = controls.shell.read(app); let store = &shell.state.store; let theme = shell.state.theme; let state = controls.state.read(app); let selecting = state.selecting && writable; - if let Some(group_key) = first_key.id.strip_prefix(GROUP_HEADER_PREFIX) { + if let Some(group_key) = key.id.strip_prefix(GROUP_HEADER_PREFIX) { let Some(group) = groups.iter().find(|g| g.key == group_key) else { return div().into_any_element(); }; @@ -57,72 +54,22 @@ pub(super) fn doc_row( ); } - let tag_color = |tag: &str| resolve_tag_color(tag, store, theme); - let views = store.views(); - - if let Some(pair) = first_key.id.strip_prefix(GRID_PAIR_PREFIX) { - let mut ids = pair.split('\0').filter(|s| !s.is_empty()); - let first_doc = ids.next().and_then(|id| store.get_doc(id)).map(|e| &e.meta); - let second_doc = ids.next().and_then(|id| store.get_doc(id)).map(|e| &e.meta); - let Some(first) = first_doc else { - return div().into_any_element(); - }; - let render_card = |doc: &DesktopDocMeta| { - doc_item( - doc, - (&views, &tag_color), - (true, writable, can_split), - (selecting, state.selected.contains(&doc.id)), - prefs, - props, - (palette, theme), - (controls, order), - ) - }; - let first_el = render_card(first); - let second_el = second_doc.map_or_else(|| div().flex_1().into_any_element(), render_card); - return div() - .flex() - .w_full() - .gap(px(12.0)) - .pb(px(12.0)) - .child(first_el) - .child(second_el) - .into_any_element(); - } - - let mut cards = keys.iter().filter_map(|key| { - let doc = &store.get_doc(&key.id)?.meta; - Some(doc_item( - doc, - (&views, &tag_color), - (grid, writable, can_split), - (selecting, state.selected.contains(&doc.id)), - prefs, - props, - (palette, theme), - (controls, order), - )) - }); - let Some(first) = cards.next() else { + let Some(entry) = store.get_doc(&key.id) else { return div().into_any_element(); }; - if grid { - div() - .flex() - .w_full() - .gap(px(12.0)) - .pb(px(12.0)) - .child(first) - .child( - cards - .next() - .unwrap_or_else(|| div().flex_1().into_any_element()), - ) - .into_any_element() - } else { - first - } + let doc = &entry.meta; + doc_item( + doc, + (&store.views(), &|tag: &str| { + resolve_tag_color(tag, store, theme) + }), + (grid, writable, can_split), + (selecting, state.selected.contains(&doc.id)), + prefs, + props, + (palette, theme), + (controls, order), + ) } pub(super) fn empty(label: &'static str, palette: DesktopPalette) -> Div { @@ -288,9 +235,8 @@ fn doc_item( header_row = header_row.child(act); } base.flex() - .flex_1() + .size_full() .flex_col() - .min_h(px(148.0)) .p(px(16.0)) .gap(px(8.0)) .rounded(px(12.0)) @@ -308,9 +254,10 @@ fn doc_item( card.child( div() .flex_1() - .min_h_0() - .truncate() - .text_size(px(13.0)) + .min_h(px(20.0)) + .overflow_hidden() + .text_size(px(12.0)) + .line_height(px(20.0)) .text_color(palette.text_muted) .child(doc.summary.clone()), ) @@ -324,7 +271,7 @@ fn doc_item( .flex_wrap() .items_center() .gap(px(8.0)) - .min_h(px(38.0)) + .min_h(px(42.0)) .px(px(8.0)) .py(px(4.0)) .rounded(px(4.0)) @@ -727,13 +674,14 @@ mod tests { .context("create the tag")?; } store.load_navigation(); - store + let meta = &mut store .docs .get_mut("doc-sync") .context("get the showcase document")? - .meta - .tags - .extend(["semantic".into(), "literal".into()]); + .meta; + meta.tags.extend(["semantic".into(), "literal".into()]); + // The newest document takes the first grid row, inside the viewport. + meta.updated_at_ms = 1_900_000_000_000; store.touch_meta(); state.navigate_active_pane(DesktopRoute::AllDocs); diff --git a/packages/frontend/desktop/src/views_extra/scroll.rs b/packages/frontend/desktop/src/views_extra/scroll.rs index f1b5fe9d65..43b767336d 100644 --- a/packages/frontend/desktop/src/views_extra/scroll.rs +++ b/packages/frontend/desktop/src/views_extra/scroll.rs @@ -101,6 +101,8 @@ pub(super) fn doc_identity(id: &str) -> u64 { pub(super) struct DocRowKey { pub(super) id: String, content: u64, + /// The key fills a row of its own, as a group header does in a grid. + full_width: bool, } impl DocRowKey { @@ -123,16 +125,44 @@ impl DocRowKey { Self::new(doc, ()) } + pub(super) fn full_width(self) -> Self { + Self { + full_width: true, + ..self + } + } + fn new(doc: &DesktopDocMeta, content: impl Hash) -> Self { let mut hasher = DefaultHasher::new(); (&doc.title, doc.updated_at_ms, content).hash(&mut hasher); Self { id: doc.id.clone(), content: hasher.finish(), + full_width: false, } } } +/// The desktop `Masonry` metrics of the web docs explorer: the minimum card width, the gap between +/// grid cards, the card height to width ratio, the gap between list rows, and the gap around group +/// headers. +const GRID_MIN_WIDTH: f32 = 220.0; +const GRID_GAP: f32 = 24.0; +const GRID_RATIO: f32 = 1.26; +const LIST_GAP: f32 = 12.0; +const GROUP_GAP: f32 = 12.0; +const LIST_ROW_HEIGHT: f32 = 42.0; +const TRASH_ROW_HEIGHT: f32 = 38.0; + +/// The number of grid columns for an available width. Like the web `calcColumns`, the minimum +/// widths and the gaps of all columns stay strictly narrower than the available width, and a +/// narrow pane keeps one column. +pub(super) fn grid_columns(available: f32) -> usize { + // The cast takes NaN to zero and saturates an infinite width. + let columns = ((available + GRID_GAP) / (GRID_MIN_WIDTH + GRID_GAP)).ceil() as usize; + columns.saturating_sub(1).clamp(1, 64) +} + #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum RowStyle { List { selecting: bool }, @@ -141,19 +171,11 @@ pub(super) enum RowStyle { } impl RowStyle { - fn columns(self) -> usize { - if matches!(self, Self::Grid { .. }) { - 2 - } else { - 1 - } - } - - fn min_height(self) -> f32 { - if matches!(self, Self::Grid { .. }) { - 160.0 - } else { - 38.0 + fn gap(self) -> f32 { + match self { + Self::List { .. } => LIST_GAP, + Self::Grid { .. } => GRID_GAP, + Self::Trash => 0.0, } } @@ -162,6 +184,53 @@ impl RowStyle { } } +/// The columns of a row and the size of each grid card. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct RowTrack { + pub(super) columns: usize, + pub(super) item_width: f32, + pub(super) item_height: f32, +} + +/// The keys of one row and the gap above it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct RowSpan { + start: usize, + end: usize, + gap: f32, +} + +/// Puts each full-width key in a row of its own and packs the other keys into rows of `columns`. +fn partition(documents: &[DocRowKey], columns: usize, gap: f32) -> Vec { + let mut spans: Vec = Vec::with_capacity(documents.len().div_ceil(columns)); + let mut start = 0; + while start < documents.len() { + let end = if documents[start].full_width { + start + 1 + } else { + documents[start..] + .iter() + .take(columns) + .position(|key| key.full_width) + .map_or((start + columns).min(documents.len()), |offset| { + start + offset + }) + }; + let gap = match spans.last() { + None => 0.0, + Some(previous) + if documents[start].full_width || documents[previous.start].full_width => + { + GROUP_GAP + } + Some(_) => gap, + }; + spans.push(RowSpan { start, end, gap }); + start = end; + } + spans +} + #[derive(PartialEq)] pub(super) struct RowGeometry { pub(super) width: Pixels, @@ -171,8 +240,34 @@ pub(super) struct RowGeometry { pub(super) style: RowStyle, } +impl RowGeometry { + fn track(&self) -> RowTrack { + let width = f32::from(self.width); + let columns = if matches!(self.style, RowStyle::Grid { .. }) { + grid_columns(width) + } else { + 1 + }; + let item_width = ((width - (columns - 1) as f32 * GRID_GAP) / columns as f32).max(0.0); + RowTrack { + columns, + item_width, + item_height: item_width * GRID_RATIO, + } + } + + fn estimate(&self) -> f32 { + match self.style { + RowStyle::List { .. } => LIST_ROW_HEIGHT + LIST_GAP, + RowStyle::Grid { .. } => self.track().item_height + GRID_GAP, + RowStyle::Trash => TRASH_ROW_HEIGHT, + } + } +} + pub(super) struct RowLayout { documents: Rc>, + spans: Rc>, geometry: Option, list: VirtualList, measured: Vec, @@ -186,6 +281,7 @@ impl Default for RowLayout { fn default() -> Self { Self { documents: Rc::new(Vec::new()), + spans: Rc::new(Vec::new()), geometry: None, list: VirtualList::fixed(0, 0.0), measured: Vec::new(), @@ -215,17 +311,20 @@ impl RowLayout { } } - let columns = geometry.style.columns(); - let old_columns = self.geometry.as_ref().map_or(1, |old| old.style.columns()); + let spans = partition(&documents, geometry.track().columns, geometry.style.gap()); let anchor = self.list.capture_anchor(self.scroll).and_then(|anchor| { - let positions: HashMap<_, _> = documents + let positions: HashMap<_, _> = spans .iter() .enumerate() - .map(|(index, key)| (&key.id, index / columns)) + .flat_map(|(index, span)| { + documents[span.start..span.end] + .iter() + .map(move |key| (&key.id, index)) + }) .collect(); - let start = anchor.index * old_columns; - let (before, from_start) = self.documents.split_at(start); - let (row, after) = from_start.split_at(from_start.len().min(old_columns)); + let old = self.spans.get(anchor.index)?; + let (before, from_start) = self.documents.split_at(old.start); + let (row, after) = from_start.split_at(old.end - old.start); let locate = |key: &DocRowKey| positions.get(&key.id).copied(); row.iter() .find_map(locate) @@ -241,23 +340,28 @@ impl RowLayout { }) }) }); - let estimate = geometry.style.min_height(); - let row_count = documents.len().div_ceil(columns); + let estimate = geometry.estimate(); + let row_count = spans.len(); let mut measured = vec![false; row_count]; self.list = if same_geometry { + // A measured height includes the gap above the row, so the gap is part of the key. let heights: HashMap<_, _> = self - .documents - .chunks(old_columns) + .spans + .iter() .enumerate() .filter(|(index, _)| self.measured[*index]) - .filter_map(|(index, row)| Some((row, self.list.item_height(index)?))) + .filter_map(|(index, span)| { + let row = &self.documents[span.start..span.end]; + Some(((row, span.gap.to_bits()), self.list.item_height(index)?)) + }) .collect(); VirtualList::variable( - documents - .chunks(columns) + spans + .iter() .zip(&mut measured) - .map(|(row, measured)| { - let height = heights.get(row); + .map(|(span, measured)| { + let row = &documents[span.start..span.end]; + let height = heights.get(&(row, span.gap.to_bits())); *measured = height.is_some(); height.copied().unwrap_or(estimate) }) @@ -273,6 +377,7 @@ impl RowLayout { self.measured = measured; self.geometry = Some(geometry); self.documents = documents; + self.spans = Rc::new(spans); self.pending_anchor = anchor; if anchor.is_none() { self.scroll = 0.0; @@ -358,7 +463,6 @@ impl RowLayout { } // Complete the prefix in row order so wheel offsets use measured heights. - let columns = self.geometry.as_ref().map_or(1, |g| g.style.columns()); let mut updated = None; while index < self.measured.len() && (index < row_count || top < bottom) { let previous = self.list.item_height(index).unwrap_or_default(); @@ -366,7 +470,7 @@ impl RowLayout { previous } else { self.measured[index] = true; - let height = measure(index, top, self.row(index, columns)); + let height = measure(index, top, self.row(index)); if height != previous { let heights = updated.get_or_insert_with(|| match self.list.metrics() { VirtualListMetrics::Fixed { count, item_height } => { @@ -390,9 +494,10 @@ impl RowLayout { } } - fn row(&self, index: usize, columns: usize) -> &[DocRowKey] { - let start = index * columns; - &self.documents[start..(start + columns).min(self.documents.len())] + fn row(&self, index: usize) -> &[DocRowKey] { + self.spans + .get(index) + .map_or(&[], |span| &self.documents[span.start..span.end]) } fn resolve(&self, anchor: ScrollAnchor) -> f32 { @@ -403,21 +508,11 @@ impl RowLayout { } pub(super) fn virtual_scroll( - id: impl Into, - state_key: impl Into, - documents: Vec, - style: RowStyle, - render: impl Fn(&[DocRowKey], &App) -> AnyElement + 'static, -) -> impl IntoElement { - virtual_scroll_shared(id, state_key, Rc::new(documents), style, render) -} - -pub(super) fn virtual_scroll_shared( id: impl Into, state_key: impl Into, documents: Rc>, style: RowStyle, - render: impl Fn(&[DocRowKey], &App) -> AnyElement + 'static, + render: impl Fn(&DocRowKey, &App) -> AnyElement + 'static, ) -> impl IntoElement { ui::ViewElement::new(VirtualScroll { id: id.into(), @@ -436,7 +531,7 @@ struct VirtualScroll { render: F, } -impl AnyElement + 'static> RenderOnce for VirtualScroll { +impl AnyElement + 'static> RenderOnce for VirtualScroll { fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { let state = window.use_keyed_state(self.state_key, app, |_, _| { Rc::new(RefCell::new(RowLayout::default())) @@ -462,20 +557,40 @@ impl AnyElement + 'static> RenderOnce for VirtualSc ); let overscan = 120.0; let available = ui::size(bounds.size.width.into(), AvailableSpace::MaxContent); - let layout_row = |keys: &[DocRowKey], window: &mut Window, app: &mut App| { - let content = (self.render)(keys, app); - let mut element = div() - .flex() - .flex_col() - .w_full() - .child(content) - .into_any_element(); - let height = element.layout_as_root(available, window, app).height.into(); - (element, height) - }; + let spans = Rc::clone(&rows.spans); + let track = rows.geometry.as_ref().map(RowGeometry::track); + let grid = matches!(style, RowStyle::Grid { .. }); + let layout_row = + |index: usize, keys: &[DocRowKey], window: &mut Window, app: &mut App| { + let content = match (keys, track) { + ([key], _) if key.full_width || !grid => (self.render)(key, app), + (keys, Some(track)) => div() + .flex() + .w_full() + .gap(px(GRID_GAP)) + .children(keys.iter().map(|key| { + div() + .flex_shrink(0.0) + .w(px(track.item_width)) + .h(px(track.item_height)) + .child((self.render)(key, app)) + })) + .into_any_element(), + _ => div().into_any_element(), + }; + let mut element = div() + .flex() + .flex_col() + .w_full() + .pt(px(spans.get(index).map_or(0.0, |span| span.gap))) + .child(content) + .into_any_element(); + let height = element.layout_as_root(available, window, app).height.into(); + (element, height) + }; let mut measured = VecDeque::new(); let mounted = rows.prepare_window(height, overscan, |index, top, keys| { - let (element, row_height) = layout_row(keys, window, app); + let (element, row_height) = layout_row(index, keys, window, app); // Keep enough elements for the viewport if the wheel reaches the end. let before = top - height - 2.0 * overscan; while measured.front().is_some_and(|&(_, end, _)| end <= before) { @@ -484,7 +599,6 @@ impl AnyElement + 'static> RenderOnce for VirtualSc measured.push_back((index, top + row_height, element)); row_height }); - let columns = style.columns(); let mut elements = Vec::with_capacity(mounted.visible_range.len()); for index in mounted.visible_range { while measured.front().is_some_and(|&(row, _, _)| row < index) { @@ -495,7 +609,7 @@ impl AnyElement + 'static> RenderOnce for VirtualSc } else { None } - .unwrap_or_else(|| layout_row(rows.row(index, columns), window, app).0); + .unwrap_or_else(|| layout_row(index, rows.row(index), window, app).0); let top = rows.list.item_offset(index).unwrap_or_default() - rows.scroll; elements.push((element, bounds.origin + ui::point(px(0.0), px(top)))); } @@ -541,3 +655,67 @@ impl RowLayout { Rc::ptr_eq(&self.documents, documents) } } + +#[cfg(test)] +mod tests { + use super::{DocRowKey, RowSpan, grid_columns, partition}; + + #[test] + fn grid_columns_match_the_web_masonry_breakpoints() { + // Container widths less the 24 px padding on each side. + for (container, columns) in [ + (100.0, 1), + (252.0, 1), + (512.0, 1), + (513.0, 2), + (756.0, 2), + (757.0, 3), + (1000.0, 3), + (1001.0, 4), + (1040.0, 4), + (1280.0, 5), + ] { + assert_eq!(grid_columns(container - 48.0), columns, "{container}"); + } + assert_eq!(grid_columns(f32::NAN), 1); + assert_eq!(grid_columns(f32::INFINITY), 64); + } + + #[test] + fn partition_gives_headers_full_rows_and_packs_cards_left_to_right() { + let key = |id: &str| DocRowKey { + id: id.into(), + content: 0, + full_width: false, + }; + let keys = [ + key("h1").full_width(), + key("a"), + key("b"), + key("c"), + key("d"), + key("h2").full_width(), + key("e"), + ]; + let span = |start, end, gap| RowSpan { start, end, gap }; + assert_eq!( + partition(&keys, 3, 24.0), + [ + span(0, 1, 0.0), + span(1, 4, 12.0), + span(4, 5, 24.0), + span(5, 6, 12.0), + span(6, 7, 12.0), + ] + ); + assert_eq!( + partition(&keys[1..5], 1, 12.0), + [ + span(0, 1, 0.0), + span(1, 2, 12.0), + span(2, 3, 12.0), + span(3, 4, 12.0), + ] + ); + } +} diff --git a/packages/frontend/desktop/src/views_extra/tests/mod.rs b/packages/frontend/desktop/src/views_extra/tests/mod.rs index d9e7c495af..91fdda020d 100644 --- a/packages/frontend/desktop/src/views_extra/tests/mod.rs +++ b/packages/frontend/desktop/src/views_extra/tests/mod.rs @@ -19,7 +19,7 @@ use ui_tokens::ThemeMode; use super::{ FALLBACK_TAG_RGB, outline_rail::HIDDEN_MAX_PANE_WIDTH, - scroll::{DocRowKey, RowGeometry, RowLayout, RowStyle}, + scroll::{DocRowKey, RowGeometry, RowLayout, RowStyle, grid_columns}, }; use crate::{DesktopAppState, DesktopRoute, DesktopShellView, register_desktop_fonts}; @@ -232,11 +232,17 @@ fn trash_confirmation_blocks_shortcuts_and_escape_leaves_the_trash_unchanged() { assert_eq!(app.route(), DesktopRoute::Trash); let id = app.update(|shell, _, _| shell.state.store.trashed_docs()[0].id.clone()); let before = app.root_update(); - for button in [ - format!("desktop.trash.delete.{id}"), - "desktop.trash.empty".into(), + // The web trash has no `Empty Trash` button. The select mode deletes many documents. + assert!(!app.contains("desktop.trash.empty")); + let row_delete = format!("desktop.trash.delete.{id}"); + let select = format!("desktop.trash.select.{id}"); + for clicks in [ + vec![row_delete.as_str()], + vec![select.as_str(), "desktop.trash.delete_selected"], ] { - app.click(&button); + for button in clicks { + app.click(button); + } assert!(app.contains("desktop.trash.confirm")); for key in ["ctrl-k", "cmd-k", "ctrl-n", "ctrl-enter"] { app.key(key); @@ -253,6 +259,57 @@ fn trash_confirmation_blocks_shortcuts_and_escape_leaves_the_trash_unchanged() { app.update(|shell, _, _| assert!(shell.state.quick_search.open)); } +#[test] +fn trash_select_mode_after_clear_ignores_bar_actions_and_toggles_documents_on_title_click() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + assert!(state.trash_doc("doc-sync")); + state.navigate_active_pane(DesktopRoute::Trash); + let app = Shell::with_state(1280, state); + let ids = app.update(|shell, _, _| { + let docs = shell.state.store.trashed_docs(); + docs.iter().map(|doc| doc.id.clone()).collect::>() + }); + assert_eq!(ids.len(), 2); + let text = |id: &str| { + app.update(|_, window, _| window.frame_snapshot().elements.get(id)?.text.clone()) + }; + let before = app.root_update(); + + app.click(&format!("desktop.trash.select.{}", ids[0])); + for label in ["Select all", "Clear"] { + assert_eq!(text("desktop.trash.select_all").as_deref(), Some(label)); + app.click("desktop.trash.select_all"); + } + // `Clear` keeps the select mode with no documents. + assert_eq!( + text("desktop.trash.select_all").as_deref(), + Some("Select all") + ); + for button in [ + "desktop.trash.delete_selected", + "desktop.trash.restore_selected", + ] { + app.click(button); + assert!(!app.contains("desktop.trash.confirm"), "{button}"); + assert!(app.contains("desktop.trash.select_done"), "{button}"); + assert_eq!(app.root_update(), before, "{button}"); + } + + app.click(&format!("desktop.trash.open.{}", ids[1])); + assert_eq!(app.route(), DesktopRoute::Trash); + assert!(app.contains("desktop.trash.select_done")); + app.click("desktop.trash.delete_selected"); + assert_eq!( + text("desktop.trash.confirm.description").as_deref(), + Some("This document will be permanently deleted. This action cannot be undone.") + ); + app.click("desktop.trash.confirm.delete"); + app.update(|shell, _, _| { + assert!(shell.state.store.get_doc(&ids[1]).is_none()); + assert!(shell.state.store.get_doc(&ids[0]).is_some()); + }); +} + #[test] fn explorer_row_menu_offers_split_only_at_or_above_640_pixels() { for (width, split) in [(639, false), (640, true)] { diff --git a/packages/frontend/desktop/src/views_extra/tests/virtual_rows.rs b/packages/frontend/desktop/src/views_extra/tests/virtual_rows.rs index 9a0ebe354b..11756f0211 100644 --- a/packages/frontend/desktop/src/views_extra/tests/virtual_rows.rs +++ b/packages/frontend/desktop/src/views_extra/tests/virtual_rows.rs @@ -5,7 +5,7 @@ use ui_tokens::ThemeMode; use super::{ DesktopAppState, DesktopRoute, DocRowKey, FALLBACK_TAG_RGB, RowGeometry, RowLayout, RowStyle, - Shell, + Shell, grid_columns, }; const ROW_TIME: i64 = 1_900_000_000_000; @@ -205,25 +205,49 @@ fn trash_rows_measure_wrapped_commands_at_narrow_width() { } #[test] -fn explorer_grid_keeps_two_columns_and_reaches_an_odd_final_row() { +fn explorer_grid_fills_responsive_columns_and_keeps_the_final_card_width() { let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let existing = state.store.visible_docs().len(); - let count = if existing.is_multiple_of(2) { 41 } else { 40 }; - let docs = append_rows(&mut state, count, ROW_TIME, false); + append_rows(&mut state, 41, ROW_TIME, false); let last = state.store.visible_docs().last().unwrap().id.clone(); state.navigate_active_pane(DesktopRoute::AllDocs); let app = Shell::with_state(1280, state); app.click("desktop.explorer.grid"); - let left = app.bounds(&format!("desktop.list.doc.{}", docs[docs.len() - 1])); - let right = app.bounds(&format!("desktop.list.doc.{}", docs[docs.len() - 2])); - assert_eq!(left.y, right.y); - assert_eq!(left.x + left.width + 12.0, right.x); + let cards = || { + app.update(|_, window, _| { + let mut cards: Vec<_> = window + .frame_snapshot() + .elements + .iter() + .filter(|(id, _)| id.starts_with("desktop.list.doc.")) + .map(|(_, card)| card.bounds) + .collect(); + cards.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x))); + cards + }) + }; + let top = cards(); + let first_row: Vec<_> = top.iter().filter(|card| card.y == top[0].y).collect(); + let columns = first_row.len(); + let content = first_row[columns - 1].x + first_row[columns - 1].width - first_row[0].x; + assert_eq!(columns, grid_columns(content)); + assert!(columns > 2, "{columns} columns in {content} px"); + for pair in first_row.windows(2) { + assert_eq!(pair[0].width, pair[1].width); + assert!((pair[0].x + pair[0].width + 24.0 - pair[1].x).abs() < 0.5); + assert!((pair[0].height - pair[0].width * 1.26).abs() < 1.0); + } + let second_row = top.iter().find(|card| card.y > top[0].y).unwrap(); + assert!((second_row.y - (top[0].y + top[0].height + 24.0)).abs() < 1.0); + app.scroll(850.0, 600.0, -100_000.0); - assert!(!app.contains(&format!("desktop.list.doc.{}", docs[docs.len() - 1]))); - let final_row = app.bounds(&format!("desktop.list.doc.{last}")); - assert_eq!(final_row.x, left.x); - assert!(final_row.width < right.x + right.width - final_row.x); - assert!(final_row.y + final_row.height < 800.0); + let final_card = app.bounds(&format!("desktop.list.doc.{last}")); + assert_eq!(final_card.width, first_row[0].width); + assert!( + first_row + .iter() + .any(|card| (card.x - final_card.x).abs() < 0.5) + ); + assert!(final_card.y + final_card.height < 800.0); } #[test] @@ -363,3 +387,33 @@ fn explorer_row_key_invalidates_when_attached_tag_is_renamed() { ); assert!(before != after); } + +#[test] +fn trash_select_all_round_trips_in_the_select_mode_until_escape() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let ids = append_rows(&mut state, 3, ROW_TIME, true); + state.navigate_active_pane(DesktopRoute::Trash); + let app = Shell::with_state(1280, state); + let label = |app: &Shell| { + app.update(|_, window, _| { + let snapshot = window.frame_snapshot(); + snapshot + .elements + .get("desktop.trash.select_all") + .and_then(|button| button.text.clone()) + }) + }; + assert_eq!(label(&app), None); + + app.click(&format!("desktop.trash.select.{}", ids[0])); + // `Clear` empties the selection and keeps the select mode, so `Select all` stays. + for expected in ["Select all", "Clear", "Select all", "Clear"] { + assert_eq!(label(&app).as_deref(), Some(expected)); + assert!(app.contains("desktop.trash.select_done")); + app.click("desktop.trash.select_all"); + } + assert_eq!(label(&app).as_deref(), Some("Select all")); + app.key("escape"); + assert_eq!(label(&app), None); + assert!(!app.contains("desktop.trash.select_done")); +} diff --git a/packages/frontend/desktop/src/views_extra/trash/footer.rs b/packages/frontend/desktop/src/views_extra/trash/footer.rs index b91fbec0e1..41b77c5e26 100644 --- a/packages/frontend/desktop/src/views_extra/trash/footer.rs +++ b/packages/frontend/desktop/src/views_extra/trash/footer.rs @@ -9,10 +9,7 @@ use ui::{ }; use ui_tokens::FONT_SANS; -use super::{ - DeleteRequest, TrashConfirmations, TrashControls, TrashSelection, confirmation, - is_activation_key, -}; +use super::{TrashConfirmations, TrashControls, TrashSelection, confirmation, is_activation_key}; use crate::{ DesktopFlexExt, DesktopPalette, TRASH_ICON_SVG, peek_view::{TOOLTIP_GAP, tooltip_bubble}, @@ -300,10 +297,7 @@ impl RenderOnce for TrashFooter { let delete_action: Option> = writable.then(|| { Rc::new(controls.action(ids, |selection, _, ids| { - selection.pending = Some(DeleteRequest { - ids, - empty_trash: false, - }); + selection.pending = Some(ids); })) as Rc }); diff --git a/packages/frontend/desktop/src/views_extra/trash/mod.rs b/packages/frontend/desktop/src/views_extra/trash/mod.rs index b3635768bf..48ccacdeac 100644 --- a/packages/frontend/desktop/src/views_extra/trash/mod.rs +++ b/packages/frontend/desktop/src/views_extra/trash/mod.rs @@ -1,10 +1,12 @@ use std::{ + cell::RefCell, collections::{BTreeSet, HashMap}, rc::Rc, + sync::Arc, }; use ui::{ - AnyElement, App, Context, Div, Entity, EntityId, Focusable, FontWeight, Global, + AnyElement, App, Context, Div, Entity, EntityId, FocusHandle, Focusable, FontWeight, Global, InteractiveElement, IntoElement, KeyDownEvent, ParentElement, RenderOnce, StatefulInteractiveElement, Styled, WeakEntity, WeakFocusHandle, Window, div, px, svg, }; @@ -25,7 +27,7 @@ use crate::{ ConfirmAction, ConfirmFocus, ConfirmIds, ConfirmKey, ConfirmModal, OverlayScroll, confirm_key, float_confirm, }, - doc_store::{DesktopDocMeta, DesktopDocStore}, + doc_store::{DesktopDocMeta, DesktopDocStore, DocViews}, state::DesktopAppState, workbench::DesktopShellView, }; @@ -46,8 +48,11 @@ pub(crate) fn render_trash_view( #[derive(Default)] struct TrashSelection { + /// The multi-select mode of the web trash. It stays on when `Clear` empties the selection. + select_mode: bool, selected: BTreeSet, - pending: Option, + /// The documents that wait for the permanent delete confirmation. + pending: Option>, confirmation_focus: Option, failed: bool, } @@ -153,28 +158,29 @@ fn resolve_confirmation( cx.notify(); } -struct DeleteRequest { - ids: Vec, - empty_trash: bool, -} - impl TrashSelection { + fn leave_select_mode(&mut self) { + self.select_mode = false; + self.selected.clear(); + } + fn dismiss(&mut self) { self.pending = None; } fn confirm(&mut self, state: &mut DesktopAppState) { - let Some(request) = self.pending.take() else { + let Some(ids) = self.pending.take() else { return; }; self.failed = false; - for id in request.ids { + for id in ids { if state.permanently_delete_doc(&id) { self.selected.remove(&id); } else { self.failed = true; } } + self.select_mode &= !self.selected.is_empty(); } } @@ -186,6 +192,31 @@ struct TrashView { type TrashAction = fn(&mut TrashSelection, &mut DesktopAppState, Vec); +/// The row keys of the trash, shared while the document views stay the same. +#[derive(Default)] +struct TrashRowKeys(RefCell, Rc>)>>); + +impl TrashRowKeys { + fn resolve(&self, store: &DesktopDocStore) -> Rc> { + let views = store.views(); + if let Some((cached, keys)) = self.0.borrow().as_ref() + && Arc::ptr_eq(cached, &views) + { + return Rc::clone(keys); + } + let keys = Rc::new( + views + .trashed + .iter() + .filter_map(|id| store.get_doc(id)) + .map(|entry| DocRowKey::trash(&entry.meta)) + .collect::>(), + ); + *self.0.borrow_mut() = Some((views, Rc::clone(&keys))); + keys + } +} + #[derive(Clone)] struct TrashControls { shell: Entity, @@ -222,6 +253,15 @@ impl TrashControls { &self, ids: Vec, action: TrashAction, + ) -> impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static { + self.rows_action(move || ids.clone(), action) + } + + /// Like `action`, but reads the document IDs only on a click. + fn rows_action( + &self, + ids: impl Fn() -> Vec + 'static, + action: TrashAction, ) -> impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static { let this = self.clone(); move |_, window, app| { @@ -233,7 +273,7 @@ impl TrashControls { return; } let pending = this.selection.update(cx, |selection, cx| { - action(selection, &mut shell.state, ids.clone()); + action(selection, &mut shell.state, ids()); if selection.pending.is_some() && selection.confirmation_focus.is_none() { let focus = ConfirmationFocus { buttons: ConfirmFocus::new(cx), @@ -285,6 +325,16 @@ impl RenderOnce for TrashView { let selection = window.use_keyed_state(location.key("desktop.trash.state"), app, |_, _| { TrashSelection::default() }); + let row_keys = + window.use_keyed_state(location.key("desktop.trash.row_keys"), app, |_, _| { + TrashRowKeys::default() + }); + let focus = window + .use_keyed_state(location.key("desktop.trash.focus"), app, |_, cx| { + cx.focus_handle() + }) + .read(app) + .clone(); let controls = TrashControls { shell: self.shell.clone(), location, @@ -293,17 +343,24 @@ impl RenderOnce for TrashView { let palette = self.palette; let shell = self.shell.read(app); let store = &shell.state.store; - let docs = store.trashed_docs(); + let keys = row_keys.read(app).resolve(store); let writable = !store.is_readonly_sqlite(); let state = controls.selection.read(app); - let selected: Vec<_> = docs - .iter() - .filter(|doc| state.selected.contains(&doc.id)) - .map(|doc| doc.id.clone()) - .collect(); - let has_rows = !docs.is_empty(); - let all_selected = has_rows && docs.len() == selected.len(); - let has_selection = !selected.is_empty(); + let selected: Vec<_> = if state.selected.is_empty() { + Vec::new() + } else { + keys.iter() + .filter(|key| state.selected.contains(&key.id)) + .map(|key| key.id.clone()) + .collect() + }; + let has_rows = !keys.is_empty(); + let all_selected = has_rows && keys.len() == selected.len(); + let select_mode = state.select_mode && writable && has_rows; + let all_ids = { + let keys = Rc::clone(&keys); + move || keys.iter().map(|key| key.id.clone()).collect::>() + }; let mut heading = div() .flex() .flex_wrap() @@ -323,44 +380,55 @@ impl RenderOnce for TrashView { .child("Trash"), ); - if has_rows { - let select_all = button( - "desktop.trash.select_all", - if all_selected { "Clear" } else { "Select all" }, - palette, - writable, + // As on the web, `Select all` shows only in the multi-select mode. + if select_mode { + heading = heading.child( + button( + "desktop.trash.select_all", + if all_selected { "Clear" } else { "Select all" }, + palette, + writable, + ) + .snapshot("desktop.trash.select_all", Some("desktop.trash.view")) + .snapshot_text(if all_selected { "Clear" } else { "Select all" }) + .on_click({ + let toggle = controls.rows_action(all_ids, |selection, _, ids| { + if ids.iter().all(|id| selection.selected.contains(id)) { + selection.selected.clear(); + } else { + selection.selected = ids.into_iter().collect(); + } + }); + let select_bar = focus.clone(); + // The multi-select bar keeps the focus so that `Escape` leaves the mode. + move |event, window, app| { + toggle(event, window, app); + window.focus(&select_bar, app); + } + }), ); - let empty = button("desktop.trash.empty", "Empty Trash", palette, writable) - .snapshot("desktop.trash.empty", Some("desktop.trash.view")) - .text_color(palette.danger); - heading = if writable { - let all: Vec<_> = docs.iter().map(|doc| doc.id.clone()).collect(); - heading - .child(select_all.on_click(controls.action( - all.clone(), - |selection, _, ids| { - if ids.iter().all(|id| selection.selected.contains(id)) { - selection.selected.clear(); - } else { - selection.selected = ids.into_iter().collect(); - } - }, - ))) - .child(confirmation_trigger( - empty, - palette, - controls.action(all, |selection, _, ids| { - selection.pending = Some(DeleteRequest { - ids, - empty_trash: true, - }); - }), - )) - } else { - heading.child(select_all).child(empty) - }; } + let escape = { + let selection = controls.selection.clone(); + move |event: &KeyDownEvent, window: &mut Window, app: &mut App| { + if event.keystroke.key != "escape" { + return; + } + let left = selection.update(app, |selection, cx| { + let left = selection.pending.is_none() && selection.select_mode; + if left { + selection.leave_select_mode(); + cx.notify(); + } + left + }); + if left { + window.prevent_default(); + app.stop_propagation(); + } + } + }; let mut root = div() .id("desktop.trash.view") .snapshot("desktop.trash.view", Some("desktop.workbench")) @@ -374,9 +442,11 @@ impl RenderOnce for TrashView { .font_family(FONT_SANS) .text_color(palette.text_primary) .child(heading); - if has_selection { + if select_mode { root = root.child( div() + .track_focus(&focus) + .on_key_down(escape) .flex() .flex_wrap() .items_center() @@ -397,7 +467,14 @@ impl RenderOnce for TrashView { palette, writable, &controls, - )), + )) + .child( + button("desktop.trash.select_done", "Done", palette, writable) + .snapshot("desktop.trash.select_done", Some("desktop.trash.view")) + .on_click(controls.action(Vec::new(), |selection, _, _| { + selection.leave_select_mode(); + })), + ), ); } if state.failed { @@ -412,22 +489,27 @@ impl RenderOnce for TrashView { let scroll_key = controls.location.key("desktop.trash.scroll"); root = if has_rows { let render_controls = controls.clone(); + let select_bar = focus.clone(); root.child(virtual_scroll( scroll_key, controls.location.key("desktop.trash.rows"), - docs.into_iter().map(DocRowKey::trash).collect(), + keys, RowStyle::Trash, - move |keys, app| { + move |key, app| { let store = &render_controls.shell.read(app).state.store; let selection = render_controls.selection.read(app); - keys.first() - .and_then(|key| store.get_doc(&key.id)) - .map_or_else( - || div().into_any_element(), - |doc| { - trash_row(&doc.meta, selection, palette, writable, &render_controls) - }, - ) + store.get_doc(&key.id).map_or_else( + || div().into_any_element(), + |doc| { + trash_row( + &doc.meta, + selection, + (palette, writable), + &render_controls, + &select_bar, + ) + }, + ) }, )) } else { @@ -457,24 +539,54 @@ impl RenderOnce for TrashView { fn trash_row( doc: &DesktopDocMeta, state: &TrashSelection, - palette: DesktopPalette, - writable: bool, + (palette, writable): (DesktopPalette, bool), controls: &TrashControls, + select_bar: &FocusHandle, ) -> AnyElement { let identity = doc_identity(&doc.id); let checked = state.selected.contains(&doc.id); - let select = button(("DesktopTrashSelect", identity), "", palette, writable) - .child(selection_icon(checked, palette)); - let select = if writable { - select.on_click(controls.action(vec![doc.id.clone()], |selection, _, ids| { + let toggle = writable.then(|| { + let toggle = Rc::new(controls.action(vec![doc.id.clone()], |selection, _, ids| { + selection.select_mode = true; if let Some(id) = ids.into_iter().next() && !selection.selected.remove(&id) { selection.selected.insert(id); } - })) - } else { - select + })); + let select_bar = select_bar.clone(); + // The multi-select bar takes the focus so that `Escape` can leave the mode. + move |event: &ui::ClickEvent, window: &mut Window, app: &mut App| { + toggle(event, window, app); + window.focus(&select_bar, app); + } + }); + let select = button(("DesktopTrashSelect", identity), "", palette, writable) + .snapshot( + ui::snap_id!("desktop.trash.select.{}", doc.id), + Some("desktop.trash.view"), + ) + .child(selection_icon(checked, palette)); + let select = match toggle.clone() { + Some(toggle) => select.on_click(toggle), + None => select, + }; + // As on the web, a click on the title in the select mode toggles the document, even + // when `Clear` emptied the selection. + let title = div() + .id(("DesktopTrashOpen", identity)) + .snapshot( + ui::snap_id!("desktop.trash.open.{}", doc.id), + Some("desktop.trash.view"), + ) + .flex_1() + .min_w(px(100.0)) + .truncate() + .cursor_pointer() + .child(doc.title.clone()); + let title = match toggle.filter(|_| state.select_mode) { + Some(toggle) => title.on_click(toggle), + None => title.on_click(controls.open(doc.id.clone())), }; div() .id(("DesktopTrashRow", identity)) @@ -490,20 +602,7 @@ fn trash_row( .rounded(px(6.0)) .hover(move |style| style.bg(palette.hover_overlay)) .child(select) - .child( - div() - .id(("DesktopTrashOpen", identity)) - .snapshot( - ui::snap_id!("desktop.trash.open.{}", doc.id), - Some("desktop.trash.view"), - ) - .flex_1() - .min_w(px(100.0)) - .truncate() - .cursor_pointer() - .child(doc.title.clone()) - .on_click(controls.open(doc.id.clone())), - ) + .child(title) .child( div() .text_size(px(12.0)) @@ -537,9 +636,11 @@ fn restore_button( writable: bool, controls: &TrashControls, ) -> ui::Stateful
{ + // `Clear` keeps the select mode with no documents, and then the bar actions do nothing. + let enabled = writable && !ids.is_empty(); let button = - button(id, "Restore", palette, writable).snapshot(snapshot, Some("desktop.trash.view")); - if !writable { + button(id, "Restore", palette, enabled).snapshot(snapshot, Some("desktop.trash.view")); + if !enabled { return button; } button.on_click(controls.action(ids, |selection, state, ids| { @@ -548,6 +649,7 @@ fn restore_button( selection.selected.remove(&id); } } + selection.select_mode &= !selection.selected.is_empty(); })) } @@ -559,21 +661,17 @@ fn delete_button( writable: bool, controls: &TrashControls, ) -> ui::Stateful
{ - let button = button(id, "Delete permanently", palette, writable) - .snapshot(snapshot, Some("desktop.trash.view")) - .text_color(palette.danger); - if !writable { + let enabled = writable && !ids.is_empty(); + let button = button(id, "Delete permanently", palette, enabled) + .snapshot(snapshot, Some("desktop.trash.view")); + if !enabled { return button; } + let button = button.text_color(palette.danger); confirmation_trigger( button, palette, - controls.action(ids, |selection, _, ids| { - selection.pending = Some(DeleteRequest { - ids, - empty_trash: false, - }); - }), + controls.action(ids, |selection, _, ids| selection.pending = Some(ids)), ) } @@ -618,15 +716,10 @@ fn confirmation( buttons.settle(writable, window, app); } let state = controls.selection.read(app); - let (Some(request), Some(focus)) = (&state.pending, &state.confirmation_focus) else { + let (Some(ids), Some(focus)) = (&state.pending, &state.confirmation_focus) else { return div().into_any_element(); }; - let count = request.ids.len(); - let title = if request.empty_trash { - "Empty Trash?" - } else { - "Delete permanently?" - }; + let count = ids.len(); let description = if count == 1 { "This document will be permanently deleted. This action cannot be undone.".to_string() } else { @@ -647,7 +740,7 @@ fn confirmation( body: ui::snap_id!("desktop.trash.confirm.body"), description: ui::snap_id!("desktop.trash.confirm.description"), }, - title: title.into(), + title: "Delete permanently?".into(), description: description.into(), confirm_label: "Delete permanently", writable, @@ -682,10 +775,7 @@ mod tests { let id = state.store.trashed_docs()[0].id.clone(); let active_id = state.store.visible_docs()[0].id.clone(); let mut selection = TrashSelection { - pending: Some(DeleteRequest { - ids: vec![id.clone()], - empty_trash: false, - }), + pending: Some(vec![id.clone()]), ..TrashSelection::default() }; let before = state diff --git a/packages/frontend/desktop/src/workbench/peek_lifecycle_tests.rs b/packages/frontend/desktop/src/workbench/peek_lifecycle_tests.rs index 793c8c45ab..db534075f1 100644 --- a/packages/frontend/desktop/src/workbench/peek_lifecycle_tests.rs +++ b/packages/frontend/desktop/src/workbench/peek_lifecycle_tests.rs @@ -365,7 +365,10 @@ fn trash_and_permanent_delete_clear_peek_panes_parked_tabs_and_history_and_survi }); if !projected { ui.frame(); - ui.click("desktop.trash.empty"); + // The select mode deletes every trashed document, as the web trash does. + ui.click(&format!("desktop.trash.select.{TARGET}")); + ui.click("desktop.trash.select_all"); + ui.click("desktop.trash.delete_selected"); ui.click("desktop.trash.confirm.delete"); } ui.frame(); diff --git a/packages/frontend/desktop/tests/docs_explorer_order_cache.rs b/packages/frontend/desktop/tests/docs_explorer_order_cache.rs index 11da18796c..b6000cc4bf 100644 --- a/packages/frontend/desktop/tests/docs_explorer_order_cache.rs +++ b/packages/frontend/desktop/tests/docs_explorer_order_cache.rs @@ -379,8 +379,8 @@ fn bench_1024_docs_explorer_scroll_and_redraw_frames() { // Cached Title redraws must not pay per-doc to_lowercase() allocations // (small delta reflects different visible rows in the viewport). assert!( - redraw_allocs_by_mode[1].abs_diff(redraw_allocs_by_mode[0]) < 600, - "Title redraw allocs ({}) diverged from Updated ({})", + redraw_allocs_by_mode[1].saturating_sub(redraw_allocs_by_mode[0]) < 600, + "Title redraw allocs ({}) exceeded Updated ({}) by 600 or more", redraw_allocs_by_mode[1], redraw_allocs_by_mode[0] ); diff --git a/packages/frontend/desktop/tests/docs_explorer_rows.rs b/packages/frontend/desktop/tests/docs_explorer_rows.rs index 7c3c1f898f..f416c9c9a2 100644 --- a/packages/frontend/desktop/tests/docs_explorer_rows.rs +++ b/packages/frontend/desktop/tests/docs_explorer_rows.rs @@ -1,5 +1,5 @@ -//! Docs explorer rows over a large tagged workspace: the per-frame allocations of the row keys, -//! and the row menu button. +//! Docs explorer and trash rows over a large workspace: the per-frame allocations of the row keys, +//! the list spacing, the row menu button, and the explorer controls in short windows. use std::{ alloc::{GlobalAlloc, Layout, System}, @@ -74,9 +74,28 @@ struct Shell { impl Shell { fn new(theme: ThemeMode, tags_per_doc: usize) -> Self { + Self::open(theme, tags_per_doc, DesktopRoute::AllDocs) + } + + fn open(theme: ThemeMode, tags_per_doc: usize, route: DesktopRoute) -> Self { + Self::sized(theme, tags_per_doc, route, (1280, 800)) + } + + fn sized(theme: ThemeMode, tags_per_doc: usize, route: DesktopRoute, size: (u32, u32)) -> Self { + Self::with_docs(theme, tags_per_doc, route, size, DOCS) + } + + fn with_docs( + theme: ThemeMode, + tags_per_doc: usize, + route: DesktopRoute, + (width, height): (u32, u32), + docs: usize, + ) -> Self { + let trash = route == DesktopRoute::Trash; let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02"); let mut last = String::new(); - for index in 0..DOCS { + for index in 0..docs { last = state.store.create_doc( format!("Tagged document {index:04}"), DocMode::Page, @@ -88,6 +107,9 @@ impl Shell { .iter() .map(|tag| (*tag).to_owned()) .collect(); + if trash { + assert!(state.store.trash_doc(&last, 1_900_000_000_000)); + } } // A metadata edit after the tag writes builds the views again. assert!( @@ -95,8 +117,8 @@ impl Shell { .store .rename_doc(&last, "Tagged document last", 1_900_000_010_000) ); - state.navigate_active_pane(DesktopRoute::AllDocs); - let platform = HeadlessPlatform::new(1280, 800, 1.0); + state.navigate_active_pane(route); + let platform = HeadlessPlatform::new(width, height, 1.0); let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); let handle = app.update(|cx| { register_desktop_fonts(cx).expect("desktop fonts"); @@ -104,7 +126,7 @@ impl Shell { WindowOptions { window_bounds: Some(WindowBounds::Windowed(Bounds::new( point(px(0.0), px(0.0)), - size(px(1280.0), px(800.0)), + size(px(width as f32), px(height as f32)), ))), ..WindowOptions::default() }, @@ -137,6 +159,25 @@ impl Shell { COUNTS.with(Cell::get) } + /// The bounds of the snapshot elements whose IDs start with `prefix`, from top to bottom. + fn column(&self, prefix: &str) -> Vec { + self.app.update(|cx| { + self.handle + .update(cx, |_, window, _| { + let mut rects: Vec<_> = window + .frame_snapshot() + .elements + .iter() + .filter(|(id, _)| id.starts_with(prefix)) + .map(|(_, element)| element.bounds) + .collect(); + rects.sort_by(|a, b| a.y.total_cmp(&b.y)); + rects + }) + .expect("desktop view") + }) + } + fn bounds(&self, id: &str) -> SnapshotRect { self.app.update(|cx| { self.handle @@ -167,6 +208,28 @@ impl Shell { }) } + /// The center of an element, after a check that the window and the clip show all of it. + fn visible_center(&self, id: &str, (width, height): (u32, u32)) -> (f32, f32) { + let (b, mask) = self.app.update(|cx| { + self.handle + .update(cx, |_, window, _| { + let element = &window.frame_snapshot().elements[id]; + (element.bounds, element.content_mask) + }) + .expect("desktop view") + }); + let label = format!("{width}x{height}: {id} at {b:?} in {mask:?}"); + assert!(b.width > 0.0 && b.height > 0.0, "{label}"); + assert!( + b.x >= mask.x.max(0.0) - 0.5 + && b.y >= mask.y.max(0.0) - 0.5 + && b.right() <= mask.right().min(width as f32) + 0.5 + && b.bottom() <= mask.bottom().min(height as f32) + 0.5, + "{label}" + ); + (b.x + b.width / 2.0, b.y + b.height / 2.0) + } + fn pointer(&self, x: f32, y: f32) { self.window .dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { @@ -199,6 +262,125 @@ fn explorer_frame_allocations_do_not_grow_with_the_tags_of_every_document() { ); } +#[test] +fn trash_frame_allocations_do_not_grow_with_the_trashed_documents() { + let mut frames = Vec::new(); + for docs in [64, DOCS] { + let shell = Shell::with_docs(ThemeMode::Light, 0, DesktopRoute::Trash, (1280, 800), docs); + assert!(!shell.column("desktop.trash.row.").is_empty()); + shell.frame_allocations(); + let (calls, bytes) = shell.frame_allocations(); + println!("{docs} trashed documents: {calls} allocations, {bytes} bytes per frame"); + frames.push(calls); + } + // Before the trash shared its row keys, every frame allocated a key for each document. + let extra = frames[1].saturating_sub(frames[0]); + assert!( + extra < (DOCS / 4) as u64, + "{extra} extra allocations per frame for {DOCS} trashed documents" + ); +} + +#[test] +fn explorer_list_spaces_group_headers_and_rows_like_the_web_list() { + let shell = Shell::new(ThemeMode::Light, 0); + let header = shell.column("desktop.explorer.group_header.")[0]; + let rows = shell.column("desktop.list.doc."); + assert_eq!(header.height, 24.0); + // The web list puts 12 px under a group header and between the rows. + assert_eq!(rows[0].y - header.y, 24.0 + 12.0); + for pair in rows[..4].windows(2) { + assert!(pair[0].height >= 42.0); + assert_eq!(pair[1].y - pair[0].bottom(), 12.0); + } +} + +#[test] +fn explorer_grid_columns_and_display_menu_follow_the_window_size() { + for (width, height, columns) in [ + (1280, 800, 4), + (1024, 768, 3), + (568, 320, 2), + (568, 250, 2), + (400, 250, 1), + ] { + let shell = Shell::sized(ThemeMode::Light, 0, DesktopRoute::AllDocs, (width, height)); + let click = |id: &str| { + let target = shell.bounds(id); + let (x, y) = ( + target.x + target.width / 2.0, + target.y + target.height / 2.0, + ); + assert!( + target.x >= 0.0 && target.x + target.width <= width as f32 && y < height as f32, + "{width}x{height}: {id} at {target:?}" + ); + shell.window.simulate_click(point(px(x), px(y))); + shell.window.request_frame(); + }; + click("desktop.explorer.grid"); + let cards = shell.column("desktop.list.doc."); + let first_row = cards.iter().filter(|card| card.y == cards[0].y).count(); + assert_eq!(first_row, columns, "{width}x{height}"); + click("desktop.explorer.display"); + assert!( + shell.contains("desktop.explorer.menu"), + "{width}x{height}: Display menu" + ); + } +} + +#[test] +fn explorer_controls_wrap_and_stay_clickable_in_short_windows() { + const CONTROLS: [&str; 7] = [ + "desktop.explorer.nav.docs", + "desktop.explorer.nav.collections", + "desktop.explorer.nav.tags", + "desktop.explorer.display", + "desktop.explorer.select", + "desktop.explorer.new_doc", + "desktop.explorer.new_doc.menu", + ]; + for size in [(400, 279), (400, 250), (320, 250), (640, 204)] { + let open = || Shell::with_docs(ThemeMode::Light, 0, DesktopRoute::AllDocs, size, 8); + let shell = open(); + for id in CONTROLS { + shell.visible_center(id, size); + } + // A short window still shows the center of the first document row under the controls. + let first = shell.column("desktop.list.doc.")[0]; + assert!( + first.y + first.height / 2.0 < size.1 as f32, + "{size:?}: {first:?}" + ); + if size == (640, 204) { + // The controls stay on one line, so that the rows keep the space. + let line = shell.bounds("desktop.explorer.nav.docs").y; + assert_eq!(shell.bounds("desktop.explorer.select").y, line, "{size:?}"); + assert!( + shell.bounds("desktop.explorer.new_doc").y < line + 12.0, + "{size:?}" + ); + } + + for (id, shows) in [ + ("desktop.explorer.display", "desktop.explorer.menu"), + ("desktop.explorer.new_doc.menu", "desktop.explorer.menu"), + ("desktop.explorer.select", "desktop.explorer.selected"), + ( + "desktop.explorer.nav.collections", + "desktop.explorer.group.0", + ), + ] { + let shell = open(); + let (x, y) = shell.visible_center(id, size); + shell.window.simulate_click(point(px(x), px(y))); + shell.window.request_frame(); + assert!(shell.contains(shows), "{size:?}: {id}"); + } + } +} + fn rgb(color: Hsla) -> [f32; 3] { let color = Rgba::from(color); [color.r * 255.0, color.g * 255.0, color.b * 255.0]