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 75132963e8..407cbec675 100644 --- a/packages/frontend/desktop/src/views_extra/docs_explorer/rows.rs +++ b/packages/frontend/desktop/src/views_extra/docs_explorer/rows.rs @@ -10,7 +10,7 @@ use crate::{ DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, doc_store::DesktopDocMeta, views_extra::{ - display_time, + display_time, resolve_tag_color, scroll::{DocRowKey, doc_identity}, selection_icon, tag_chip, }, @@ -26,14 +26,8 @@ pub(super) fn doc_row( ) -> AnyElement { let shell = controls.shell.read(app); let store = &shell.state.store; - let tokens = crate::theme_tokens_for(shell.state.theme); - let views = store.views(); - let tag_color = |tag: &str| { - views - .tag(tag) - .map(|definition| definition.color(tokens)) - .or_else(|| store.tag_colors.get(tag).copied()) - }; + let theme = shell.state.theme; + let tag_color = |tag: &str| resolve_tag_color(tag, store, theme); let state = controls.state.read(app); let mut cards = keys.iter().filter_map(|key| { let doc = &store.get_doc(&key.id)?.meta; @@ -81,7 +75,7 @@ pub(super) fn empty(label: &'static str, palette: DesktopPalette) -> Div { fn doc_item( doc: &DesktopDocMeta, - tag_color: &impl Fn(&str) -> Option, + tag_color: &impl Fn(&str) -> u32, grid: bool, (selecting, selected): (bool, bool), palette: DesktopPalette, diff --git a/packages/frontend/desktop/src/views_extra/mod.rs b/packages/frontend/desktop/src/views_extra/mod.rs index a791944f96..282ff4e4dd 100644 --- a/packages/frontend/desktop/src/views_extra/mod.rs +++ b/packages/frontend/desktop/src/views_extra/mod.rs @@ -166,11 +166,25 @@ fn display_time(ms: Option) -> String { } /// Dot color of a tag that has no color yet, such as a tag that a peer added -/// before its definition arrived. The inspector uses the same color. -const UNHYDRATED_TAG_FALLBACK_RGB: u32 = 0x64748b; +/// before its definition arrived. +const FALLBACK_TAG_RGB: u32 = 0x64748b; -fn tag_chip(tag: &str, color: Option, palette: DesktopPalette) -> Div { - let dot = ui::rgb(color.unwrap_or(UNHYDRATED_TAG_FALLBACK_RGB) & 0x00ff_ffff); +fn resolve_tag_color( + tag: &str, + store: &crate::doc_store::DesktopDocStore, + theme: ui_tokens::ThemeMode, +) -> u32 { + let tokens = crate::theme_tokens_for(theme); + store + .views() + .tag(tag) + .map(|tag| tag.color(tokens)) + .or_else(|| store.tag_colors.get(tag).copied()) + .unwrap_or(FALLBACK_TAG_RGB) +} + +fn tag_chip(tag: &str, color: u32, palette: DesktopPalette) -> Div { + let dot = ui::rgb(color & 0x00ff_ffff); max_width(div(), ui::relative(1.0)) .flex() .items_center() diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar.rs b/packages/frontend/desktop/src/views_extra/right_sidebar.rs deleted file mode 100644 index c7e0318bc2..0000000000 --- a/packages/frontend/desktop/src/views_extra/right_sidebar.rs +++ /dev/null @@ -1,880 +0,0 @@ -use std::rc::Rc; - -use ui::{ - App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, IntoElement, - ParentElement, RenderOnce, SharedString, Stateful, StatefulInteractiveElement, Styled, Window, - div, px, svg, -}; -use ui_tokens::{DARK_THEME, FONT_SANS, LIGHT_THEME, ThemeMode, icons::BULLETED_LIST}; - -use super::{button, created_at, display_time, max_width, tag_chip, update_tag, vertical_scroll}; -use crate::{ - CLOSE_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, INFO_ICON_SVG, JOURNAL_ICON_SVG, - doc_store::{DesktopDocMeta, DesktopDocStore, OutlineHeading}, - workbench::{DesktopShellView, DocInspectorTab}, -}; - -pub const WORKBENCH_SIDEBAR_WIDTH: f32 = 320.0; - -const FALLBACK_TAG_RGB: u32 = 0x64748b; - -pub(crate) fn render_doc_inspector( - tab: DocInspectorTab, - doc_id: Option<&str>, - store: &DesktopDocStore, - palette: DesktopPalette, - cx: &mut Context, -) -> impl IntoElement { - let mut body = div().flex().flex_col().gap(px(10.0)).w_full(); - match (tab, doc_id) { - (DocInspectorTab::Outline, Some(id)) => { - body = body.child(ui::ViewElement::new(OutlinePanel { - shell: cx.entity(), - doc: id.to_owned(), - workspace: store.active_workspace().id.clone(), - palette, - })); - } - (DocInspectorTab::Info, Some(id)) => { - body = body.child(ui::ViewElement::new(Properties { - shell: cx.entity(), - doc: id.to_owned(), - workspace: store.active_workspace().id.clone(), - palette, - })); - } - (DocInspectorTab::Journal, _) => { - body = body.child(super::journals::journal_month_picker(palette, cx)); - } - (_, None) => {} - } - let key = format!( - "desktop.inspector.scroll.{}.{doc_id:?}.{tab:?}", - store.active_workspace().id - ); - max_width(div().id("desktop.inspector"), ui::relative(1.0)) - .snapshot("desktop.inspector", Some("desktop.shell.root")) - .w(px(WORKBENCH_SIDEBAR_WIDTH)) - .h_full() - .flex_shrink(0.0) - .bg(palette.bg_canvas) - .border_l_1() - .border_color(palette.border) - .font_family(FONT_SANS) - .flex() - .flex_col() - .child( - div() - .flex() - .items_center() - .gap(px(4.0)) - .px(px(12.0)) - .h(px(52.0)) - .flex_shrink(0.0) - .border_b_1() - .border_color(palette.border) - .child(inspector_tab_btn( - "desktop.inspector.tab.outline", - "Outline", - BULLETED_LIST.svg.as_bytes(), - tab, - DocInspectorTab::Outline, - palette, - cx, - )) - .child(inspector_tab_btn( - "desktop.inspector.tab.info", - "Properties", - INFO_ICON_SVG, - tab, - DocInspectorTab::Info, - palette, - cx, - )) - .child(inspector_tab_btn( - "desktop.inspector.tab.journal", - "Journal", - JOURNAL_ICON_SVG, - tab, - DocInspectorTab::Journal, - palette, - cx, - )) - .child(div().flex_1()) - .child( - button("desktop.inspector.close", "", palette, true) - .child( - svg() - .data(CLOSE_ICON_SVG) - .size(px(16.0)) - .text_color(palette.text_secondary), - ) - .on_click(cx.listener(|this, _, _, cx| { - this.state.inspector_tab = None; - cx.notify(); - })), - ), - ) - .child(vertical_scroll(key, body.p(px(16.0)))) -} - -fn inspector_tab_btn( - id: &'static str, - label: &'static str, - icon: &'static [u8], - current: DocInspectorTab, - target: DocInspectorTab, - palette: DesktopPalette, - cx: &mut Context, -) -> Stateful
{ - div() - .id(id) - .snapshot(id, Some("desktop.inspector")) - .tab_stop(true) - .flex() - .items_center() - .gap(px(6.0)) - .h(px(32.0)) - .px(px(7.0)) - .rounded(px(6.0)) - .text_size(px(13.0)) - .bg(if current == target { - palette.bg_pill - } else { - ui::transparent_black() - }) - .text_color(if current == target { - palette.text_primary - } else { - palette.text_secondary - }) - .cursor_pointer() - .hover(move |style| style.bg(palette.bg_hover)) - .child( - svg() - .data(icon) - .size(px(16.0)) - .text_color(palette.text_secondary), - ) - .child(label) - .on_click(cx.listener(move |this, _, _, cx| { - this.state.inspector_tab = Some(target); - cx.notify(); - })) -} - -fn section_title(label: &'static str, palette: DesktopPalette) -> Div { - div() - .text_size(px(14.0)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_primary) - .child(label) -} - -#[derive(Default)] -struct OutlineCache { - workspace: String, - doc: String, - rev: Option, - headings: Rc<[OutlineHeading]>, -} - -struct OutlinePanel { - shell: Entity, - doc: String, - workspace: String, - palette: DesktopPalette, -} - -impl RenderOnce for OutlinePanel { - fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { - let palette = self.palette; - let cache = window.use_keyed_state( - ElementId::NamedInteger( - SharedString::new_static("inspector-outline-cache"), - ui::hash(&(&self.workspace, &self.doc)), - ), - app, - |_, _| OutlineCache::default(), - ); - let doc_rev = self - .shell - .read(app) - .state - .store - .get_doc(&self.doc) - .map(|entry| entry.revision); - let headings = { - let cached = cache.read(app); - if doc_rev.is_some() - && cached.workspace == self.workspace - && cached.doc == self.doc - && cached.rev == doc_rev - { - Rc::clone(&cached.headings) - } else { - let shell = &self.shell; - let doc = &self.doc; - cache.update(app, |cache, cx| { - let store = &shell.read(cx).state.store; - store.sync_outline_headings( - doc, - &mut cache.workspace, - &mut cache.doc, - &mut cache.rev, - &mut cache.headings, - ); - Rc::clone(&cache.headings) - }) - } - }; - let body = div() - .flex() - .flex_col() - .gap(px(10.0)) - .w_full() - .child(section_title("Table of Contents", palette)); - if headings.is_empty() { - return body.child(div().text_color(palette.text_muted).child("No headings")); - } - let mut rows = Vec::with_capacity(headings.len()); - for h in headings.iter() { - let shell = self.shell.clone(); - let doc_id = self.doc.clone(); - let workspace_id = self.workspace.clone(); - let block_id = h.block_id.clone(); - let indent = (h.level.saturating_sub(1) as f32) * 12.0; - rows.push( - div() - .id(ElementId::NamedInteger( - SharedString::new_static("inspector-heading"), - ui::hash(&block_id), - )) - .snapshot( - ui::snap_id!("desktop.inspector.heading.{block_id}"), - Some("desktop.inspector"), - ) - .h(px(28.0)) - .flex_shrink(0.0) - .flex() - .items_center() - .pl(px(indent)) - .truncate() - .rounded(px(4.0)) - .cursor_pointer() - .hover(move |s| s.bg(palette.bg_hover)) - .text_size(px(12.5)) - .font_weight(if h.level == 1 { - FontWeight::MEDIUM - } else { - FontWeight::NORMAL - }) - .text_color(palette.text_primary) - .on_click(move |_, _, app| { - shell.update(app, |this, cx| { - let pane = this.state.split.active(); - if pane.active_route().doc_id() != Some(doc_id.as_str()) - || this.state.store.active_workspace().id != workspace_id - { - return; - } - let origin = this - .editor_host() - .workspace_origins - .get(&workspace_id) - .cloned() - .unwrap_or_else(playground::default_block_link_origin); - this.open_block_link( - playground::BlockLink { - origin, - workspace_id: workspace_id.clone(), - doc_id: doc_id.clone(), - block_id: block_id.clone(), - }, - cx, - ); - }); - }) - .child(h.text.clone()) - .into_any_element(), - ); - } - body.children(rows) - } -} - -struct Properties { - shell: Entity, - doc: String, - workspace: String, - palette: DesktopPalette, -} - -#[derive(Default)] -struct Tags { - open: bool, - error: bool, -} - -impl RenderOnce for Properties { - fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { - let picker = window.use_keyed_state( - format!("desktop.properties.tags.{}/{}", self.workspace, self.doc), - app, - |_, _| Tags::default(), - ); - let palette = self.palette; - let state_ref = self.shell.read(app); - let theme = state_ref.state.theme; - let store = &state_ref.state.store; - let Some(entry) = store.get_doc(&self.doc) else { - return div(); - }; - let meta = &entry.meta; - let writable = !store.is_readonly_sqlite() && !meta.trashed; - let mut tags = div().flex().flex_wrap().items_center().gap(px(4.0)); - let change = |tag: String, add: bool| { - let shell = self.shell.clone(); - let picker = picker.clone(); - let doc = self.doc.clone(); - let workspace = self.workspace.clone(); - move |_: &ui::ClickEvent, _: &mut Window, app: &mut App| { - shell.update(app, |shell, cx| { - if shell.state.store.active_workspace().id != workspace { - return; - } - let success = update_tag(&mut shell.state, &doc, &tag, add); - picker.update(cx, |picker, cx| { - picker.error = !success; - if success { - picker.open = false; - } - cx.notify(); - }); - cx.notify(); - }); - } - }; - for tag in &meta.tags { - let chip = tag_chip(tag, Some(resolve_tag_color(tag, store, theme)), palette); - tags = tags.child(if writable { - chip.child( - button( - ElementId::NamedInteger( - SharedString::new_static("inspector-tag-remove"), - ui::hash(&tag), - ), - "×", - palette, - true, - ) - .min_h(px(24.0)) - .px(px(4.0)) - .on_click(change(tag.clone(), false)), - ) - } else { - chip - }); - } - if writable { - let picker = picker.clone(); - tags = tags.child( - button("desktop.inspector.tag.add", "Add tag", palette, true).on_click( - move |_, _, app| { - picker.update(app, |picker, cx| { - picker.open = !picker.open; - picker.error = false; - cx.notify(); - }); - }, - ), - ); - } - if meta.tags.is_empty() && !writable { - tags = tags.child(div().text_color(palette.text_muted).child("Empty")); - } - let mut properties = div() - .flex() - .flex_col() - .gap(px(10.0)) - .child(section_title("Workspace properties", palette)) - .child(property( - "Created", - div().child(display_time(created_at(store, &self.doc))), - palette, - )) - .child(property( - "Updated", - div().child(display_time(Some(meta.updated_at_ms))), - palette, - )) - .child(property("Tags", tags, palette)); - let state = picker.read(app); - if writable && state.open { - let mut options = div().flex().flex_wrap().gap(px(4.0)).p(px(4.0)); - let mut has_options = false; - for (tag, _, _) in store.all_tags_with_counts() { - if !meta.tags.contains(&tag) { - has_options = true; - let color = resolve_tag_color(&tag, store, theme); - let option = button( - ElementId::NamedInteger( - SharedString::new_static("inspector-tag-option"), - ui::hash(&tag), - ), - "", - palette, - true, - ) - .gap(px(5.0)) - .child( - div() - .size(px(6.0)) - .flex_shrink(0.0) - .rounded(px(3.0)) - .bg(ui::rgb(color & 0x00ff_ffff)), - ); - options = options.child(option.child(tag.clone()).on_click(change(tag, true))); - } - } - if !has_options { - options = options.child( - div() - .text_color(palette.text_muted) - .child("No other workspace tags"), - ); - } - properties = properties.child(options); - } - if state.error { - properties = properties.child( - div() - .text_color(palette.danger) - .child("Could not update tags."), - ); - } - let outgoing = meta - .outgoing_refs - .iter() - .filter_map(|id| store.get_doc(id).map(|entry| &entry.meta)); - properties - .child(self.links("Outgoing links", outgoing, palette)) - .child(self.links( - "Backlinks", - store.backlinks_for(&self.doc).into_iter(), - palette, - )) - } -} - -impl Properties { - fn links<'a>( - &self, - title: &'static str, - docs: impl Iterator, - palette: DesktopPalette, - ) -> Div { - let mut links = div() - .flex() - .flex_col() - .gap(px(2.0)) - .pt(px(12.0)) - .border_t_1() - .border_color(palette.border) - .child(section_title(title, palette)); - let mut empty = true; - for doc in docs.filter(|doc| !doc.trashed) { - empty = false; - let shell = self.shell.clone(); - let workspace = self.workspace.clone(); - let id = doc.id.clone(); - links = links.child( - div() - .id(ElementId::NamedInteger( - SharedString::new_static("inspector-link"), - ui::hash(&(title, id.as_str())), - )) - .flex() - .items_center() - .gap(px(6.0)) - .min_h(px(28.0)) - .px(px(6.0)) - .rounded(px(6.0)) - .text_size(px(13.0)) - .text_color(palette.text_primary) - .cursor_pointer() - .hover(move |style| style.bg(palette.bg_hover)) - .child( - svg() - .data(DOC_ICON_SVG) - .size(px(16.0)) - .flex_shrink(0.0) - .text_color(palette.text_muted), - ) - .child(div().min_w_0().truncate().child(doc.title.clone())) - .on_click(move |_, _, app| { - shell.update(app, |shell, cx| { - if shell.state.store.active_workspace().id == workspace { - shell.state.open_doc_in_active_pane(&id); - cx.notify(); - } - }); - }), - ); - } - if empty { - links = links.child( - div() - .text_size(px(12.0)) - .text_color(palette.text_muted) - .child("None"), - ); - } - links - } -} - -fn resolve_tag_color(tag: &str, store: &DesktopDocStore, theme: ThemeMode) -> u32 { - let tokens = match theme { - ThemeMode::Light => &LIGHT_THEME, - ThemeMode::Dark => &DARK_THEME, - }; - store - .views() - .tag(tag) - .map(|tag| tag.color(tokens)) - .or_else(|| store.tag_colors.get(tag).copied()) - .unwrap_or(FALLBACK_TAG_RGB) -} - -fn property(label: &'static str, value: Div, palette: DesktopPalette) -> Div { - div() - .flex() - .items_start() - .gap(px(10.0)) - .w_full() - .text_size(px(13.0)) - .child( - div() - .w(px(60.0)) - .flex_shrink(0.0) - .text_color(palette.text_muted) - .child(label), - ) - .child(value.flex_1().min_w_0().text_color(palette.text_primary)) -} - -/// Render the standalone document information dialog at the workbench root. -pub fn render_doc_info_dialog( - doc_id: &str, - store: &DesktopDocStore, - palette: DesktopPalette, - viewport_height: f32, - dismiss: impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static, - cx: &mut Context, -) -> impl IntoElement { - let dismiss = Rc::new(dismiss); - let dismiss_backdrop = Rc::clone(&dismiss); - let title = store.get_doc(doc_id).map_or_else( - || "Document information".to_owned(), - |entry| entry.meta.title.clone(), - ); - div() - .absolute() - .inset_0() - .flex() - .items_center() - .justify_center() - .p(px(16.0)) - .child(crate::workbench::backdrop( - "desktop.doc_info.backdrop", - palette, - move |event, window, app| dismiss_backdrop(event, window, app), - )) - .child( - max_width(div().id("desktop.doc_info.dialog").occlude(), px(480.0)) - .relative() - .w_full() - .h(px((viewport_height - 32.0).clamp(0.0, 560.0))) - .flex() - .flex_col() - .p(px(24.0)) - .gap(px(14.0)) - .rounded(px(12.0)) - .bg(palette.bg_elevated) - .font_family(FONT_SANS) - .child( - div() - .flex() - .items_center() - .gap(px(8.0)) - .child( - div() - .flex_1() - .min_w_0() - .truncate() - .font_weight(FontWeight::SEMIBOLD) - .text_size(px(18.0)) - .text_color(palette.text_primary) - .child(title), - ) - .child( - button("desktop.doc_info.close", "", palette, true) - .child( - svg() - .data(CLOSE_ICON_SVG) - .size(px(16.0)) - .text_color(palette.text_secondary), - ) - .on_click(move |event, window, app| dismiss(event, window, app)), - ), - ) - .child(vertical_scroll( - "desktop.doc_info.scroll", - ui::ViewElement::new(Properties { - shell: cx.entity(), - doc: doc_id.to_owned(), - workspace: store.active_workspace().id.clone(), - palette, - }), - )), - ) -} - -#[cfg(test)] -mod tests { - use affine_store::workspace_db::{NavigationEdit, WorkspaceDb, WorkspaceTag}; - use ui::{ - AppContext as _, Application, Bounds, HeadlessPlatform, PlatformInput, ScrollDelta, - ScrollEvent, WindowBounds, WindowOptions, point, px, size, - }; - - use super::*; - use crate::{DesktopAppState, doc_store::LocalUpdates, register_desktop_fonts}; - - #[test] - fn inspector_and_sidebar_tag_colors_track_the_theme_and_preserve_literal_rgb() { - let mut store = DesktopDocStore::seed_showcase("2026-12-02"); - let cases = [ - ("literal", "#E1EEFF", 0xe1eeff), - ("token", "var(--affine-tag-blue)", 0x084388), - ("bare-token", "--affine-tag-blue", 0x084388), - ]; - for (id, color, _) in cases { - store - .directory - .db_mut() - .edit_navigation( - &NavigationEdit::CreateTag(WorkspaceTag { - id: id.into(), - name: id.into(), - color: color.into(), - }), - 1_764_300_950, - ) - .unwrap() - .unwrap(); - } - store.load_navigation(); - store.touch_meta(); - - let views = store.views(); - for (id, _, dark) in cases { - let tag = views.tag(id).expect("sidebar tag"); - for (mode, tokens, expected) in [ - (ThemeMode::Light, &LIGHT_THEME, 0xe1eeff), - (ThemeMode::Dark, &DARK_THEME, dark), - ] { - assert_eq!(tag.color(tokens), expected, "{id} in {mode:?}"); - assert_eq!( - resolve_tag_color(id, &store, mode), - expected, - "{id} in {mode:?}" - ); - } - } - store.tag_colors.insert("cached-only".into(), 0xe1eeff); - assert!(store.views().tag("cached-only").is_none()); - for mode in [ThemeMode::Light, ThemeMode::Dark] { - assert_eq!(resolve_tag_color("cached-only", &store, mode), 0xe1eeff); - assert_eq!(resolve_tag_color("missing", &store, mode), FALLBACK_TAG_RGB); - } - } - - #[test] - fn inspector_renders_peer_tags_before_navigation_reload() { - const DOC_ID: &str = "doc-sync"; - const NOW: i64 = 1_764_301_000; - let tags = ["architecture".into(), "peer-new".into()]; - let platform = HeadlessPlatform::new(1280, 800, 1.0); - let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); - let handle = app.update(|cx| { - register_desktop_fonts(cx).expect("fonts"); - let (mut state, sessions) = DesktopAppState::open_local( - &Default::default(), - ThemeMode::Dark, - "2026-12-02", - NOW, - ) - .expect("open workspace"); - state.open_doc_in_active_pane(DOC_ID); - state.inspector_tab = Some(DocInspectorTab::Info); - cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(Bounds::new( - point(px(0.0), px(0.0)), - size(px(1280.0), px(800.0)), - ))), - ..WindowOptions::default() - }, - |_, cx| { - cx.new(|cx| { - let mut shell = DesktopShellView::new(state, cx); - shell.bind_local_workspaces( - sessions, - Rc::new(LocalUpdates::default()), - NOW, - cx, - ); - let store = &mut shell.state.store; - let peer_tags = store - .with_session(NOW, |session| { - let mut dir = session.directory().lock_directory(); - let db = dir.db_mut(); - let mut peer = WorkspaceDb::from_root_update_v1( - db.space_id(), - "u-peer", - 2, - &db.root().encode_update_v1()?, - &[], - )?; - let update = peer.set_page_tags(DOC_ID, &tags)?.unwrap(); - db.apply_remote_root_update(&update)?; - Ok(db.root().get_page(DOC_ID)?.unwrap().tags) - }) - .expect("bound writer") - .expect("apply peer update"); - assert_eq!(peer_tags, tags); - store.docs.get_mut(DOC_ID).unwrap().meta.tags = peer_tags; - store.touch_meta(); - assert!(store.views().tag("architecture").is_some()); - assert!(store.views().tag("peer-new").is_none()); - shell - }) - }, - ) - .expect("window") - }); - platform - .windows() - .into_iter() - .next() - .unwrap() - .request_frame(); - platform.run_until_parked(); - - app.update(|cx| { - handle - .update(cx, |_, window, _| { - let inspector = window.frame_snapshot().elements["desktop.inspector"].bounds; - let frame = window.render_to_image().expect("render inspector"); - for (tag, rgb) in [ - ("architecture", [0x7c, 0x5c, 0xfa]), - ("peer-new", [0x64, 0x74, 0x8b]), - ] { - assert!( - frame.enumerate_pixels().any(|(x, y, pixel)| { - x >= inspector.x as u32 - && x < (inspector.x + inspector.width) as u32 - && y < 300 - && pixel.0[..3] == rgb - }), - "no color dot for {tag}" - ); - } - }) - .expect("view"); - }); - } - - #[test] - fn inspector_outline_and_rail_preserve_snapshots_across_scroll_and_body_edits() { - let platform = HeadlessPlatform::new(1280, 800, 1.0); - let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); - let handle = app.update(|cx| { - register_desktop_fonts(cx).expect("fonts"); - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - state.inspector_tab = Some(DocInspectorTab::Outline); - cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(Bounds::new( - point(px(0.0), px(0.0)), - size(px(1280.0), px(800.0)), - ))), - ..WindowOptions::default() - }, - |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), - ) - .expect("window") - }); - let win = platform.windows().into_iter().next().expect("window"); - win.request_frame(); - platform.run_until_parked(); - - app.update(|cx| { - handle - .update(cx, |_, window, _| { - let elements = &window.frame_snapshot().elements; - assert!(elements.contains_key("desktop.inspector")); - assert!(elements.contains_key("desktop.inspector.heading.h1-1")); - assert!(elements.contains_key("desktop.inspector.heading.h2-1")); - }) - .expect("view") - }); - - // Scroll inspector outline and re-render. - win.dispatch_input(PlatformInput::Scroll(ScrollEvent { - position: point(px(1160.0), px(300.0)), - delta: ScrollDelta::Pixels(point(px(0.0), px(-40.0))), - modifiers: ui::Modifiers::default(), - touch_phase: ui::TouchPhase::Moved, - source: ui::ScrollSource::Pointer, - })); - win.request_frame(); - platform.run_until_parked(); - - // Pure body edit without touching headings. - app.update(|cx| { - handle - .update(cx, |shell, _, cx| { - let doc_id = shell - .state - .split - .active() - .active_route() - .doc_id() - .expect("doc") - .to_owned(); - let now = shell.state.logical_clock_ms + 10; - shell - .state - .store - .append_paragraph(&doc_id, "Body paragraph edit", now); - cx.notify(); - }) - .expect("update") - }); - win.request_frame(); - platform.run_until_parked(); - - app.update(|cx| { - handle - .update(cx, |_, window, _| { - let elements = &window.frame_snapshot().elements; - assert!(elements.contains_key("desktop.inspector.heading.h1-1")); - assert!(elements.contains_key("desktop.inspector.heading.h2-1")); - }) - .expect("view") - }); - } -} diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs new file mode 100644 index 0000000000..9d3ab6d78e --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs @@ -0,0 +1,186 @@ +mod outline; +mod properties; +#[cfg(test)] +mod tests; + +pub use properties::render_doc_info_dialog; + +use ui::{ + Context, Div, FontWeight, InteractiveElement, IntoElement, ParentElement, Stateful, + StatefulInteractiveElement, Styled, div, px, svg, +}; +use ui_tokens::{FONT_SANS, icons::BULLETED_LIST}; + +#[cfg(test)] +pub(super) use super::FALLBACK_TAG_RGB; +pub(super) use super::{ + button, created_at, display_time, max_width, resolve_tag_color, tag_chip, update_tag, + vertical_scroll, +}; +use crate::{ + CLOSE_ICON_SVG, DesktopFlexExt, DesktopPalette, INFO_ICON_SVG, JOURNAL_ICON_SVG, + doc_store::DesktopDocStore, + workbench::{DesktopShellView, DocInspectorTab}, +}; + +pub const WORKBENCH_SIDEBAR_WIDTH: f32 = 320.0; + +pub(crate) fn render_doc_inspector( + tab: DocInspectorTab, + doc_id: Option<&str>, + store: &DesktopDocStore, + palette: DesktopPalette, + cx: &mut Context, +) -> impl IntoElement { + let key = format!( + "desktop.inspector.scroll.{}.{doc_id:?}.{tab:?}", + store.active_workspace().id + ); + let content = match (tab, doc_id) { + (DocInspectorTab::Info, Some(id)) => ui::ViewElement::new(properties::Properties::new( + cx.entity(), + id.to_owned(), + store.active_workspace().id.clone(), + key.into(), + 16.0, + Some("desktop.inspector"), + palette, + )) + .into_any_element(), + _ => { + let mut body = div().flex().flex_col().gap(px(10.0)).w_full(); + match (tab, doc_id) { + (DocInspectorTab::Outline, Some(id)) => { + body = body.child(ui::ViewElement::new(outline::OutlinePanel { + shell: cx.entity(), + doc: id.to_owned(), + workspace: store.active_workspace().id.clone(), + palette, + })); + } + (DocInspectorTab::Journal, _) => { + body = body.child(super::journals::journal_month_picker(palette, cx)); + } + _ => {} + } + vertical_scroll(key, body.p(px(16.0))).into_any_element() + } + }; + max_width(div().id("desktop.inspector"), ui::relative(1.0)) + .snapshot("desktop.inspector", Some("desktop.shell.root")) + .w(px(WORKBENCH_SIDEBAR_WIDTH)) + .h_full() + .flex_shrink(0.0) + .bg(palette.bg_canvas) + .border_l_1() + .border_color(palette.border) + .font_family(FONT_SANS) + .flex() + .flex_col() + .child( + div() + .flex() + .items_center() + .gap(px(4.0)) + .px(px(12.0)) + .h(px(52.0)) + .flex_shrink(0.0) + .border_b_1() + .border_color(palette.border) + .child(inspector_tab_btn( + "desktop.inspector.tab.outline", + "Outline", + BULLETED_LIST.svg.as_bytes(), + tab, + DocInspectorTab::Outline, + palette, + cx, + )) + .child(inspector_tab_btn( + "desktop.inspector.tab.info", + "Properties", + INFO_ICON_SVG, + tab, + DocInspectorTab::Info, + palette, + cx, + )) + .child(inspector_tab_btn( + "desktop.inspector.tab.journal", + "Journal", + JOURNAL_ICON_SVG, + tab, + DocInspectorTab::Journal, + palette, + cx, + )) + .child(div().flex_1()) + .child( + button("desktop.inspector.close", "", palette, true) + .child( + svg() + .data(CLOSE_ICON_SVG) + .size(px(16.0)) + .text_color(palette.text_secondary), + ) + .on_click(cx.listener(|this, _, _, cx| { + this.state.inspector_tab = None; + cx.notify(); + })), + ), + ) + .child(content) +} + +fn inspector_tab_btn( + id: &'static str, + label: &'static str, + icon: &'static [u8], + current: DocInspectorTab, + target: DocInspectorTab, + palette: DesktopPalette, + cx: &mut Context, +) -> Stateful
{ + div() + .id(id) + .snapshot(id, Some("desktop.inspector")) + .tab_stop(true) + .flex() + .items_center() + .gap(px(6.0)) + .h(px(32.0)) + .px(px(7.0)) + .rounded(px(6.0)) + .text_size(px(13.0)) + .bg(if current == target { + palette.bg_pill + } else { + ui::transparent_black() + }) + .text_color(if current == target { + palette.text_primary + } else { + palette.text_secondary + }) + .cursor_pointer() + .hover(move |style| style.bg(palette.bg_hover)) + .child( + svg() + .data(icon) + .size(px(16.0)) + .text_color(palette.text_secondary), + ) + .child(label) + .on_click(cx.listener(move |this, _, _, cx| { + this.state.inspector_tab = Some(target); + cx.notify(); + })) +} + +pub(super) fn section_title(label: &'static str, palette: DesktopPalette) -> Div { + div() + .text_size(px(14.0)) + .font_weight(FontWeight::MEDIUM) + .text_color(palette.text_primary) + .child(label) +} diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs new file mode 100644 index 0000000000..ebdda53bc6 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs @@ -0,0 +1,153 @@ +use std::rc::Rc; + +use ui::{ + App, ElementId, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, RenderOnce, + SharedString, StatefulInteractiveElement, Styled, Window, div, px, +}; + +use super::section_title; +use crate::{DesktopPalette, doc_store::OutlineHeading, workbench::DesktopShellView}; + +const EMPTY_OUTLINE_MESSAGE: &str = "Use headings to create a table of contents."; + +#[derive(Default)] +struct OutlineCache { + workspace: String, + doc: String, + rev: Option, + headings: Rc<[OutlineHeading]>, +} + +pub(super) struct OutlinePanel { + pub(super) shell: Entity, + pub(super) doc: String, + pub(super) workspace: String, + pub(super) palette: DesktopPalette, +} + +impl RenderOnce for OutlinePanel { + fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { + let palette = self.palette; + let cache = window.use_keyed_state( + ElementId::NamedInteger( + SharedString::new_static("inspector-outline-cache"), + ui::hash(&(&self.workspace, &self.doc)), + ), + app, + |_, _| OutlineCache::default(), + ); + let doc_rev = self + .shell + .read(app) + .state + .store + .get_doc(&self.doc) + .map(|entry| entry.revision); + let headings = { + let cached = cache.read(app); + if doc_rev.is_some() + && cached.workspace == self.workspace + && cached.doc == self.doc + && cached.rev == doc_rev + { + Rc::clone(&cached.headings) + } else { + let shell = &self.shell; + let doc = &self.doc; + cache.update(app, |cache, cx| { + let store = &shell.read(cx).state.store; + store.sync_outline_headings( + doc, + &mut cache.workspace, + &mut cache.doc, + &mut cache.rev, + &mut cache.headings, + ); + Rc::clone(&cache.headings) + }) + } + }; + let body = div() + .flex() + .flex_col() + .gap(px(10.0)) + .w_full() + .child(section_title("Table of Contents", palette)); + if headings.is_empty() { + return body.child( + div() + .id("desktop.inspector.outline.empty") + .snapshot( + ui::snap_id!("desktop.inspector.outline.empty"), + Some("desktop.inspector"), + ) + .snapshot_text(EMPTY_OUTLINE_MESSAGE) + .text_color(palette.text_muted) + .child(EMPTY_OUTLINE_MESSAGE), + ); + } + let mut rows = Vec::with_capacity(headings.len()); + for h in headings.iter() { + let shell = self.shell.clone(); + let doc_id = self.doc.clone(); + let workspace_id = self.workspace.clone(); + let block_id = h.block_id.clone(); + let indent = (h.level.saturating_sub(1) as f32) * 12.0; + rows.push( + div() + .id(ElementId::NamedInteger( + SharedString::new_static("inspector-heading"), + ui::hash(&block_id), + )) + .snapshot( + ui::snap_id!("desktop.inspector.heading.{block_id}"), + Some("desktop.inspector"), + ) + .h(px(28.0)) + .flex_shrink(0.0) + .flex() + .items_center() + .pl(px(indent)) + .truncate() + .rounded(px(4.0)) + .cursor_pointer() + .hover(move |s| s.bg(palette.bg_hover)) + .text_size(px(12.5)) + .font_weight(if h.level == 1 { + FontWeight::MEDIUM + } else { + FontWeight::NORMAL + }) + .text_color(palette.text_primary) + .on_click(move |_, _, app| { + shell.update(app, |this, cx| { + let pane = this.state.split.active(); + if pane.active_route().doc_id() != Some(doc_id.as_str()) + || this.state.store.active_workspace().id != workspace_id + { + return; + } + let origin = this + .editor_host() + .workspace_origins + .get(&workspace_id) + .cloned() + .unwrap_or_else(playground::default_block_link_origin); + this.open_block_link( + playground::BlockLink { + origin, + workspace_id: workspace_id.clone(), + doc_id: doc_id.clone(), + block_id: block_id.clone(), + }, + cx, + ); + }); + }) + .child(h.text.clone()) + .into_any_element(), + ); + } + body.children(rows) + } +} diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/properties.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/properties.rs new file mode 100644 index 0000000000..5944955409 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/properties.rs @@ -0,0 +1,585 @@ +use std::{cell::Cell, rc::Rc}; + +use blocksuite_editor::scroll::{ScrollAxis, wheel_delta}; +use ui::{ + App, Context, Div, ElementId, Entity, FontWeight, InteractiveElement, IntoElement, + ParentElement, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, canvas, + div, px, svg, +}; +use ui_kit::{VirtualList, VirtualWindow}; +use ui_tokens::FONT_SANS; + +use super::{ + button, created_at, display_time, max_width, resolve_tag_color, section_title, tag_chip, + update_tag, +}; +use crate::{ + CLOSE_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, + doc_store::{DesktopDocMeta, DesktopDocStore}, + workbench::DesktopShellView, +}; + +const LINK_ROW_HEIGHT: f32 = 28.0; +const LINK_ROW_GAP: f32 = 2.0; +const LINK_ROW_STRIDE: f32 = LINK_ROW_HEIGHT + LINK_ROW_GAP; +const BACKLINKS_OVERSCAN: f32 = 60.0; + +pub(super) struct Properties { + shell: Entity, + doc: String, + workspace: String, + scroll_key: ElementId, + padding: f32, + parent_snapshot: Option<&'static str>, + palette: DesktopPalette, +} + +impl Properties { + pub(super) fn new( + shell: Entity, + doc: String, + workspace: String, + scroll_key: ElementId, + padding: f32, + parent_snapshot: Option<&'static str>, + palette: DesktopPalette, + ) -> Self { + Self { + shell, + doc, + workspace, + scroll_key, + padding, + parent_snapshot, + palette, + } + } +} + +#[derive(Default)] +struct Tags { + open: bool, + error: bool, +} + +#[derive(Default)] +struct PropertiesScrollState { + offset: f32, + viewport_height: Rc>>, + backlinks_top: Rc>>, + non_backlinks_height: Rc>>, +} + +fn backlinks_window( + count: usize, + scroll_y: f32, + viewport_height: f32, + backlinks_top: f32, +) -> VirtualWindow { + let vis_top = (scroll_y - backlinks_top).max(0.0); + let vis_bottom = (scroll_y + viewport_height - backlinks_top).max(0.0); + let vis_height = (vis_bottom - vis_top).max(0.0); + VirtualList::fixed(count, LINK_ROW_STRIDE).window(vis_height, vis_top, BACKLINKS_OVERSCAN) +} + +impl RenderOnce for Properties { + fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { + let picker = window.use_keyed_state( + format!("desktop.properties.tags.{}/{}", self.workspace, self.doc), + app, + |_, _| Tags::default(), + ); + let scroll = window.use_keyed_state( + ElementId::NamedInteger( + SharedString::new_static("properties-scroll"), + ui::hash(&(&self.workspace, &self.doc, self.parent_snapshot)), + ), + app, + |_, _| PropertiesScrollState::default(), + ); + let palette = self.palette; + let state_ref = self.shell.read(app); + let theme = state_ref.state.theme; + let store = &state_ref.state.store; + let Some(entry) = store.get_doc(&self.doc) else { + return div().flex_1().min_h_0().w_full().into_any_element(); + }; + let meta = &entry.meta; + let writable = !store.is_readonly_sqlite() && !meta.trashed; + let mut tags = div().flex().flex_wrap().items_center().gap(px(4.0)); + let change = |tag: String, add: bool| { + let shell = self.shell.clone(); + let picker = picker.clone(); + let doc = self.doc.clone(); + let workspace = self.workspace.clone(); + move |_: &ui::ClickEvent, _: &mut Window, app: &mut App| { + shell.update(app, |shell, cx| { + if shell.state.store.active_workspace().id != workspace { + return; + } + let success = update_tag(&mut shell.state, &doc, &tag, add); + picker.update(cx, |picker, cx| { + picker.error = !success; + if success { + picker.open = false; + } + cx.notify(); + }); + cx.notify(); + }); + } + }; + for tag in &meta.tags { + let chip = tag_chip(tag, resolve_tag_color(tag, store, theme), palette); + tags = tags.child(if writable { + chip.child( + button( + ElementId::NamedInteger( + SharedString::new_static("inspector-tag-remove"), + ui::hash(&tag), + ), + "×", + palette, + true, + ) + .min_h(px(24.0)) + .px(px(4.0)) + .on_click(change(tag.clone(), false)), + ) + } else { + chip + }); + } + if writable { + let picker = picker.clone(); + tags = tags.child( + button("desktop.inspector.tag.add", "Add tag", palette, true).on_click( + move |_, _, app| { + picker.update(app, |picker, cx| { + picker.open = !picker.open; + picker.error = false; + cx.notify(); + }); + }, + ), + ); + } + if meta.tags.is_empty() && !writable { + tags = tags.child(div().text_color(palette.text_muted).child("Empty")); + } + let mut properties = div() + .flex() + .flex_col() + .gap(px(10.0)) + .w_full() + .child(section_title("Workspace properties", palette)) + .child(property( + "Created", + div().child(display_time(created_at(store, &self.doc))), + palette, + )) + .child(property( + "Updated", + div().child(display_time(Some(meta.updated_at_ms))), + palette, + )) + .child(property("Tags", tags, palette)); + if self.padding > 0.0 { + properties = properties.p(px(self.padding)); + } + let state = picker.read(app); + if writable && state.open { + let mut options = div().flex().flex_wrap().gap(px(4.0)).p(px(4.0)); + let mut has_options = false; + for (tag, _, _) in store.all_tags_with_counts() { + if !meta.tags.contains(&tag) { + has_options = true; + let color = resolve_tag_color(&tag, store, theme); + let option = button( + ElementId::NamedInteger( + SharedString::new_static("inspector-tag-option"), + ui::hash(&tag), + ), + "", + palette, + true, + ) + .gap(px(5.0)) + .child( + div() + .size(px(6.0)) + .flex_shrink(0.0) + .rounded(px(3.0)) + .bg(ui::rgb(color & 0x00ff_ffff)), + ); + options = options.child(option.child(tag.clone()).on_click(change(tag, true))); + } + } + if !has_options { + options = options.child( + div() + .text_color(palette.text_muted) + .child("No other workspace tags"), + ); + } + properties = properties.child(options); + } + if state.error { + properties = properties.child( + div() + .text_color(palette.danger) + .child("Could not update tags."), + ); + } + let outgoing = meta + .outgoing_refs + .iter() + .filter_map(|id| store.get_doc(id).map(|entry| &entry.meta)); + let backlinks = store.backlinks_for(&self.doc); + let backlinks_count = backlinks.len(); + let backlinks_height = if backlinks_count == 0 { + 0.0 + } else { + backlinks_count as f32 * LINK_ROW_STRIDE - LINK_ROW_GAP + }; + + let scroll_read = scroll.read(app); + let raw_offset = scroll_read.offset; + let measured_viewport = scroll_read.viewport_height.get(); + let measured_backlinks_top = scroll_read.backlinks_top.get(); + let measured_non_backlinks = scroll_read.non_backlinks_height.get(); + let viewport_cell = Rc::clone(&scroll_read.viewport_height); + let backlinks_top_cell = Rc::clone(&scroll_read.backlinks_top); + let non_backlinks_cell = Rc::clone(&scroll_read.non_backlinks_height); + + let offset = match (measured_viewport, measured_non_backlinks) { + (Some(vp), Some(non_bl)) => raw_offset.min((non_bl + backlinks_height - vp).max(0.0)), + _ => raw_offset, + }; + let viewport_height = measured_viewport + .unwrap_or_else(|| f32::from(window.viewport_size().height).max(800.0)); + let backlinks_top = measured_backlinks_top.unwrap_or(0.0); + + properties = properties + .child(self.links("Outgoing links", outgoing, palette)) + .child(self.backlinks_section( + &backlinks, + offset, + viewport_height, + backlinks_top, + &scroll, + &viewport_cell, + &backlinks_top_cell, + palette, + )); + + let measured_limit = Rc::new(Cell::new(0.0_f32)); + let wheel_scroll = scroll.clone(); + let wheel_limit = Rc::clone(&measured_limit); + let scroll_for_limit = scroll.clone(); + let measure = canvas( + move |bounds, window, app| { + let visible_height: f32 = window.content_mask().bounds.size.height.into(); + let content_height: f32 = bounds.size.height.into(); + non_backlinks_cell.set(Some((content_height - backlinks_height).max(0.0))); + viewport_cell.set(Some(visible_height)); + let limit = (content_height - visible_height).max(0.0); + measured_limit.set(limit); + if raw_offset > limit { + window.defer(app, move |_, app| { + scroll_for_limit.update(app, |state, cx| { + if state.offset > limit { + state.offset = limit; + cx.notify(); + } + }); + }); + } + }, + |_, (), _, _| {}, + ) + .absolute() + .inset_0(); + + div() + .id(self.scroll_key) + .flex() + .flex_col() + .flex_1() + .min_h_0() + .w_full() + .relative() + .overflow_hidden() + .on_scroll(move |event, _, app| { + wheel_scroll.update(app, |state, cx| { + let (_, dy) = wheel_delta(event, 0.0); + let mut axis = ScrollAxis::new(state.offset, wheel_limit.get()); + if axis.apply(dy) { + state.offset = axis.offset; + cx.stop_propagation(); + cx.notify(); + } + }); + }) + .child( + div() + .relative() + .top(px(-offset)) + .flex_shrink(0.0) + .w_full() + .child(properties) + .child(measure), + ) + .into_any_element() + } +} + +impl Properties { + fn link_row( + &self, + title: &'static str, + doc: &DesktopDocMeta, + palette: DesktopPalette, + ) -> ui::Stateful
{ + let shell = self.shell.clone(); + let workspace = self.workspace.clone(); + let id = doc.id.clone(); + let label: SharedString = doc.title.clone().into(); + let mut row = div() + .id(ElementId::NamedInteger( + SharedString::new_static("inspector-link"), + ui::hash(&(title, id.as_str())), + )) + .flex() + .items_center() + .gap(px(6.0)) + .min_h(px(LINK_ROW_HEIGHT)) + .px(px(6.0)) + .rounded(px(6.0)) + .text_size(px(13.0)) + .text_color(palette.text_primary) + .cursor_pointer() + .hover(move |style| style.bg(palette.bg_hover)) + .child( + svg() + .data(DOC_ICON_SVG) + .size(px(16.0)) + .flex_shrink(0.0) + .text_color(palette.text_muted), + ) + .child(div().min_w_0().truncate().child(label.clone())) + .on_click(move |_, _, app| { + shell.update(app, |shell, cx| { + if shell.state.store.active_workspace().id == workspace { + shell.state.open_doc_in_active_pane(&id); + cx.notify(); + } + }); + }); + if title == "Backlinks" { + row = row + .snapshot( + ui::snap_id!("desktop.inspector.backlink.{}", doc.id), + self.parent_snapshot, + ) + .snapshot_text(label); + } + row + } + + fn links<'a>( + &self, + title: &'static str, + docs: impl Iterator, + palette: DesktopPalette, + ) -> Div { + let mut section = links_section_shell(title, palette); + let mut empty = true; + for doc in docs.filter(|doc| !doc.trashed) { + empty = false; + section = section.child(self.link_row(title, doc, palette)); + } + if empty { + section = section.child(empty_links_label(palette)); + } + section + } + + #[allow(clippy::too_many_arguments)] + fn backlinks_section( + &self, + backlinks: &[&DesktopDocMeta], + offset: f32, + viewport_height: f32, + backlinks_top: f32, + scroll: &Entity, + viewport_cell: &Rc>>, + backlinks_top_cell: &Rc>>, + palette: DesktopPalette, + ) -> Div { + let section = links_section_shell("Backlinks", palette); + let count = backlinks.len(); + if count == 0 { + backlinks_top_cell.set(None); + return section.child(empty_links_label(palette)); + } + let slice = backlinks_window(count, offset, viewport_height, backlinks_top); + let rendered_range = slice.visible_range.clone(); + let mut items = div().relative().flex().flex_col().w_full(); + if slice.leading_spacer > 0.0 { + items = items.child(div().h(px(slice.leading_spacer)).flex_shrink(0.0)); + } + for (idx_in_slice, doc) in backlinks[slice.visible_range.clone()].iter().enumerate() { + let index = slice.visible_range.start + idx_in_slice; + let mut row = self.link_row("Backlinks", doc, palette); + if index + 1 < count { + row = row.mb(px(LINK_ROW_GAP)); + } + items = items.child(row); + } + let trailing_spacer = if slice.visible_range.end < count { + ((count - slice.visible_range.end) as f32 * LINK_ROW_STRIDE - LINK_ROW_GAP).max(0.0) + } else { + 0.0 + }; + if trailing_spacer > 0.0 { + items = items.child(div().h(px(trailing_spacer)).flex_shrink(0.0)); + } + + let scroll_for_top = scroll.clone(); + let viewport_cell = Rc::clone(viewport_cell); + let backlinks_top_cell = Rc::clone(backlinks_top_cell); + let measure_top = canvas( + move |bounds, window, app| { + let mask = window.content_mask().bounds; + let actual_top = f32::from(bounds.origin.y) - f32::from(mask.origin.y) + offset; + let actual_viewport = f32::from(mask.size.height); + backlinks_top_cell.set(Some(actual_top)); + viewport_cell.set(Some(actual_viewport)); + let new_range = + backlinks_window(count, offset, actual_viewport, actual_top).visible_range; + if new_range != rendered_range { + window.defer(app, move |_, app| { + scroll_for_top.update(app, |_, cx| cx.notify()); + }); + } + }, + |_, (), _, _| {}, + ) + .absolute() + .inset_0(); + section.child(items.child(measure_top)) + } +} + +fn links_section_shell(title: &'static str, palette: DesktopPalette) -> Div { + div() + .flex() + .flex_col() + .gap(px(2.0)) + .pt(px(12.0)) + .border_t_1() + .border_color(palette.border) + .child(section_title(title, palette)) +} + +fn empty_links_label(palette: DesktopPalette) -> Div { + div() + .text_size(px(12.0)) + .text_color(palette.text_muted) + .child("None") +} + +fn property(label: &'static str, value: Div, palette: DesktopPalette) -> Div { + div() + .flex() + .items_start() + .gap(px(10.0)) + .w_full() + .text_size(px(13.0)) + .child( + div() + .w(px(60.0)) + .flex_shrink(0.0) + .text_color(palette.text_muted) + .child(label), + ) + .child(value.flex_1().min_w_0().text_color(palette.text_primary)) +} + +/// Render the standalone document information dialog at the workbench root. +pub fn render_doc_info_dialog( + doc_id: &str, + store: &DesktopDocStore, + palette: DesktopPalette, + viewport_height: f32, + dismiss: impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static, + cx: &mut Context, +) -> impl IntoElement { + let dismiss = Rc::new(dismiss); + let dismiss_backdrop = Rc::clone(&dismiss); + let title = store.get_doc(doc_id).map_or_else( + || "Document information".to_owned(), + |entry| entry.meta.title.clone(), + ); + div() + .absolute() + .inset_0() + .flex() + .items_center() + .justify_center() + .p(px(16.0)) + .child(crate::workbench::backdrop( + "desktop.doc_info.backdrop", + palette, + move |event, window, app| dismiss_backdrop(event, window, app), + )) + .child( + max_width(div().id("desktop.doc_info.dialog").occlude(), px(480.0)) + .relative() + .w_full() + .h(px((viewport_height - 32.0).clamp(0.0, 560.0))) + .flex() + .flex_col() + .p(px(24.0)) + .gap(px(14.0)) + .rounded(px(12.0)) + .bg(palette.bg_elevated) + .font_family(FONT_SANS) + .child( + div() + .flex() + .items_center() + .gap(px(8.0)) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .font_weight(FontWeight::SEMIBOLD) + .text_size(px(18.0)) + .text_color(palette.text_primary) + .child(title), + ) + .child( + button("desktop.doc_info.close", "", palette, true) + .child( + svg() + .data(CLOSE_ICON_SVG) + .size(px(16.0)) + .text_color(palette.text_secondary), + ) + .on_click(move |event, window, app| dismiss(event, window, app)), + ), + ) + .child(ui::ViewElement::new(Properties::new( + cx.entity(), + doc_id.to_owned(), + store.active_workspace().id.clone(), + "desktop.doc_info.scroll".into(), + 0.0, + None, + palette, + ))), + ) +} diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/tests.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/tests.rs new file mode 100644 index 0000000000..cac29b9d69 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/tests.rs @@ -0,0 +1,582 @@ +use std::rc::Rc; + +use affine_store::{ + directory::DocMode, + workspace_db::{NavigationEdit, WorkspaceDb, WorkspaceTag}, +}; +use blocksuite_playground_doc::schema::BlockSpec; +use ui::{ + AppContext as _, Application, Bounds, HeadlessPlatform, PlatformInput, ScrollDelta, + ScrollEvent, WindowBounds, WindowOptions, point, px, size, +}; +use ui_tokens::{DARK_THEME, LIGHT_THEME, ThemeMode}; + +use super::{FALLBACK_TAG_RGB, resolve_tag_color}; +use crate::{ + DesktopAppState, DesktopRoute, doc_store::DesktopDocStore, doc_store::LocalUpdates, + register_desktop_fonts, workbench::DesktopShellView, workbench::DocInspectorTab, +}; + +#[test] +fn inspector_and_sidebar_tag_colors_track_the_theme_and_preserve_literal_rgb() { + let mut store = DesktopDocStore::seed_showcase("2026-12-02"); + let cases = [ + ("literal", "#E1EEFF", 0xe1eeff), + ("token", "var(--affine-tag-blue)", 0x084388), + ("bare-token", "--affine-tag-blue", 0x084388), + ]; + for (id, color, _) in cases { + store + .directory + .db_mut() + .edit_navigation( + &NavigationEdit::CreateTag(WorkspaceTag { + id: id.into(), + name: id.into(), + color: color.into(), + }), + 1_764_300_950, + ) + .unwrap() + .unwrap(); + } + store.load_navigation(); + store.touch_meta(); + + let views = store.views(); + for (id, _, dark) in cases { + let tag = views.tag(id).expect("sidebar tag"); + for (mode, tokens, expected) in [ + (ThemeMode::Light, &LIGHT_THEME, 0xe1eeff), + (ThemeMode::Dark, &DARK_THEME, dark), + ] { + assert_eq!(tag.color(tokens), expected, "{id} in {mode:?}"); + assert_eq!( + resolve_tag_color(id, &store, mode), + expected, + "{id} in {mode:?}" + ); + } + } + store.tag_colors.insert("cached-only".into(), 0xe1eeff); + assert!(store.views().tag("cached-only").is_none()); + for mode in [ThemeMode::Light, ThemeMode::Dark] { + assert_eq!(resolve_tag_color("cached-only", &store, mode), 0xe1eeff); + assert_eq!(resolve_tag_color("missing", &store, mode), FALLBACK_TAG_RGB); + } +} + +#[test] +fn inspector_renders_peer_tags_before_navigation_reload() { + const DOC_ID: &str = "doc-sync"; + const NOW: i64 = 1_764_301_000; + let tags = ["architecture".into(), "peer-new".into()]; + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).expect("fonts"); + let (mut state, sessions) = + DesktopAppState::open_local(&Default::default(), ThemeMode::Dark, "2026-12-02", NOW) + .expect("open workspace"); + state.open_doc_in_active_pane(DOC_ID); + state.inspector_tab = Some(DocInspectorTab::Info); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(1280.0), px(800.0)), + ))), + ..WindowOptions::default() + }, + |_, cx| { + cx.new(|cx| { + let mut shell = DesktopShellView::new(state, cx); + shell.bind_local_workspaces( + sessions, + Rc::new(LocalUpdates::default()), + NOW, + cx, + ); + let store = &mut shell.state.store; + let peer_tags = store + .with_session(NOW, |session| { + let mut dir = session.directory().lock_directory(); + let db = dir.db_mut(); + let mut peer = WorkspaceDb::from_root_update_v1( + db.space_id(), + "u-peer", + 2, + &db.root().encode_update_v1()?, + &[], + )?; + let update = peer.set_page_tags(DOC_ID, &tags)?.unwrap(); + db.apply_remote_root_update(&update)?; + Ok(db.root().get_page(DOC_ID)?.unwrap().tags) + }) + .expect("bound writer") + .expect("apply peer update"); + assert_eq!(peer_tags, tags); + store.docs.get_mut(DOC_ID).unwrap().meta.tags = peer_tags; + store.touch_meta(); + assert!(store.views().tag("architecture").is_some()); + assert!(store.views().tag("peer-new").is_none()); + shell + }) + }, + ) + .expect("window") + }); + platform + .windows() + .into_iter() + .next() + .unwrap() + .request_frame(); + platform.run_until_parked(); + + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let inspector = window.frame_snapshot().elements["desktop.inspector"].bounds; + let frame = window.render_to_image().expect("render inspector"); + for (tag, rgb) in [ + ("architecture", [0x7c, 0x5c, 0xfa]), + ("peer-new", [0x64, 0x74, 0x8b]), + ] { + assert!( + frame.enumerate_pixels().any(|(x, y, pixel)| { + x >= inspector.x as u32 + && x < (inspector.x + inspector.width) as u32 + && y < 300 + && pixel.0[..3] == rgb + }), + "no color dot for {tag}" + ); + } + }) + .expect("view"); + }); +} + +#[test] +fn inspector_outline_and_rail_preserve_snapshots_across_scroll_and_body_edits() { + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).expect("fonts"); + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + state.inspector_tab = Some(DocInspectorTab::Outline); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(1280.0), px(800.0)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + .expect("window") + }); + let win = platform.windows().into_iter().next().expect("window"); + win.request_frame(); + platform.run_until_parked(); + + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let elements = &window.frame_snapshot().elements; + assert!(elements.contains_key("desktop.inspector")); + assert!(elements.contains_key("desktop.inspector.heading.h1-1")); + assert!(elements.contains_key("desktop.inspector.heading.h2-1")); + }) + .expect("view") + }); + + // Scroll inspector outline and re-render. + win.dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(1160.0), px(300.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(-40.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + win.request_frame(); + platform.run_until_parked(); + + // Pure body edit without touching headings. + app.update(|cx| { + handle + .update(cx, |shell, _, cx| { + let doc_id = shell + .state + .split + .active() + .active_route() + .doc_id() + .expect("doc") + .to_owned(); + let now = shell.state.logical_clock_ms + 10; + shell + .state + .store + .append_paragraph(&doc_id, "Body paragraph edit", now); + cx.notify(); + }) + .expect("update") + }); + win.request_frame(); + platform.run_until_parked(); + + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let elements = &window.frame_snapshot().elements; + assert!(elements.contains_key("desktop.inspector.heading.h1-1")); + assert!(elements.contains_key("desktop.inspector.heading.h2-1")); + }) + .expect("view") + }); +} + +#[test] +fn inspector_outline_empty_state_matches_web_copy() { + for mode in [DocMode::Page, DocMode::Edgeless] { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let doc = state.store.create_doc("Empty Outline", mode, None, 10); + if mode == DocMode::Edgeless { + let entry = state.store.docs.get_mut(&doc).unwrap(); + entry + .session + .structural_edit(20, |page| { + page.add_block( + "edgeless-only-note", + BlockSpec::Note { + xywh: Some("[0,0,400,200]".into()), + }, + Some("root"), + None, + 20, + )?; + page.set_block_prop( + "edgeless-only-note", + "prop:displayMode", + y_octo::SessionValue::Any(y_octo::Any::String("edgeless".into())), + 21, + )?; + Ok(()) + }) + .unwrap(); + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + } + state.open_doc_in_active_pane(&doc); + state.inspector_tab = Some(DocInspectorTab::Outline); + + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).expect("fonts"); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(1280.0), px(800.0)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + .expect("window") + }); + let win = platform.windows().into_iter().next().expect("window"); + win.request_frame(); + platform.run_until_parked(); + + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let elements = &window.frame_snapshot().elements; + let empty = elements + .get("desktop.inspector.outline.empty") + .expect("empty outline placeholder"); + assert_eq!( + empty.text.as_deref(), + Some("Use headings to create a table of contents.") + ); + assert!(!window.rendered_scene().monochrome_sprites.is_empty()); + }) + .expect("view") + }); + } +} + +#[test] +fn inspector_properties_virtualizes_1002_backlinks_and_updates_across_mutations() { + const MAX_MOUNTED_ROWS: usize = 32; + let platform = HeadlessPlatform::new(1280, 800, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).expect("fonts"); + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let existing = state.store.backlinks_for("doc-arch").len(); + let needed = 1002 - existing; + for i in 0..needed { + let id = state.store.create_doc( + format!("Backlink Source {i:04}"), + DocMode::Page, + None, + 1_764_400_000 + i as i64, + ); + // Push duplicate refs to verify deduplication (one row per source doc). + let refs = &mut state.store.docs.get_mut(&id).unwrap().meta.outgoing_refs; + refs.push("doc-arch".into()); + refs.push("doc-arch".into()); + } + state.store.touch_meta(); + assert_eq!(state.store.backlinks_for("doc-arch").len(), 1002); + state.open_doc_in_active_pane("doc-arch"); + state.inspector_tab = Some(DocInspectorTab::Info); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(1280.0), px(800.0)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + .expect("window") + }); + let win = platform.windows().into_iter().next().expect("window"); + win.request_frame(); + platform.run_until_parked(); + + let (first_id, last_id) = app.update(|cx| { + handle + .update(cx, |shell, window, _| { + let backlinks = shell.state.store.backlinks_for("doc-arch"); + assert_eq!(backlinks.len(), 1002); + let mounted: Vec<_> = window + .frame_snapshot() + .elements + .keys() + .filter(|id| id.starts_with("desktop.inspector.backlink.")) + .cloned() + .collect(); + assert!( + !mounted.is_empty() && mounted.len() <= MAX_MOUNTED_ROWS, + "mounted {} backlinks on first frame", + mounted.len() + ); + let first = backlinks[0].id.clone(); + let last = backlinks[1001].id.clone(); + assert!( + mounted.contains(&format!("desktop.inspector.backlink.{first}")), + "first backlink missing on initial frame" + ); + assert!( + !mounted.contains(&format!("desktop.inspector.backlink.{last}")), + "1002nd backlink should not be mounted at scroll=0" + ); + (first, last) + }) + .expect("view") + }); + + // Scroll outer Properties container to bottom and click the 1,002nd backlink. + win.dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(1160.0), px(400.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(-1_000_000.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + win.request_frame(); + + let last_pos = app.update(|cx| { + handle + .update(cx, |_, window, _| { + let elements = &window.frame_snapshot().elements; + let mounted = elements + .keys() + .filter(|id| id.starts_with("desktop.inspector.backlink.")) + .count(); + assert!( + mounted > 0 && mounted <= MAX_MOUNTED_ROWS, + "mounted {mounted} backlinks after scroll to bottom" + ); + assert!(!elements.contains_key(&format!("desktop.inspector.backlink.{first_id}"))); + let last_el = elements + .get(&format!("desktop.inspector.backlink.{last_id}")) + .expect("1002nd backlink must be mounted at bottom"); + let b = &last_el.bounds; + assert!( + b.y + b.height <= 800.5, + "1002nd row outside viewport: {b:?}" + ); + point(px(b.x + b.width / 2.0), px(b.y + b.height / 2.0)) + }) + .expect("view") + }); + + win.simulate_click(last_pos); + win.request_frame(); + app.update(|cx| { + handle + .update(cx, |shell, _, _| { + assert_eq!( + shell.state.split.active().active_route(), + &DesktopRoute::Doc(last_id.clone()) + ); + }) + .expect("view") + }); + + // Return to doc-arch, scroll to bottom, then rename & trash to verify immediate sync and clamp. + app.update(|cx| { + handle + .update(cx, |shell, _, cx| { + shell.state.open_doc_in_active_pane("doc-arch"); + cx.notify(); + }) + .expect("view") + }); + win.request_frame(); + platform.run_until_parked(); + + win.dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(1160.0), px(400.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(-1_000_000.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + win.request_frame(); + + // Rename the 1002nd backlink and trash 900 backlinks -> scroll clamps cleanly and updates immediately. + let surviving_last = app.update(|cx| { + handle + .update(cx, |shell, _, cx| { + assert!( + shell + .state + .store + .rename_doc(&last_id, "Renamed Last Backlink", 10_000) + ); + let to_trash: Vec = shell + .state + .store + .backlinks_for("doc-arch") + .into_iter() + .skip(102) + .map(|doc| doc.id.clone()) + .collect(); + for (idx, id) in to_trash.iter().enumerate() { + assert!(shell.state.store.trash_doc(id, 20_000 + idx as i64)); + } + let remaining = shell.state.store.backlinks_for("doc-arch"); + assert_eq!(remaining.len(), 102); + let new_last = remaining.last().unwrap().id.clone(); + cx.notify(); + new_last + }) + .expect("view") + }); + win.request_frame(); + platform.run_until_parked(); + + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let elements = &window.frame_snapshot().elements; + let mounted = elements + .keys() + .filter(|id| id.starts_with("desktop.inspector.backlink.")) + .count(); + assert!(mounted > 0 && mounted <= MAX_MOUNTED_ROWS); + let el = elements + .get(&format!("desktop.inspector.backlink.{surviving_last}")) + .expect("clamped bottom backlink must be mounted"); + assert!(el.bounds.y + el.bounds.height <= 800.5); + assert!(!elements.contains_key(&format!("desktop.inspector.backlink.{last_id}"))); + }) + .expect("view") + }); + + // Restore the renamed doc and verify it reappears immediately with its new title. + app.update(|cx| { + handle + .update(cx, |shell, _, cx| { + assert!(shell.state.store.restore_doc(&last_id, 30_000)); + assert_eq!( + shell.state.store.get_doc(&last_id).unwrap().meta.title, + "Renamed Last Backlink" + ); + cx.notify(); + }) + .expect("view") + }); + win.request_frame(); + platform.run_until_parked(); + win.dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(1160.0), px(400.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(-1_000_000.0))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + win.request_frame(); + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let elements = &window.frame_snapshot().elements; + let restored = elements + .get(&format!("desktop.inspector.backlink.{last_id}")) + .expect("restored backlink must be mounted"); + assert_eq!(restored.text.as_deref(), Some("Renamed Last Backlink")); + }) + .expect("view") + }); + + // Switching workspace immediately clears stale backlinks from the previous workspace. + app.update(|cx| { + handle + .update(cx, |shell, _, cx| { + assert!(shell.state.store.workspaces.len() >= 2); + shell.state.switch_workspace(1); + cx.notify(); + }) + .expect("view") + }); + win.request_frame(); + platform.run_until_parked(); + app.update(|cx| { + handle + .update(cx, |shell, window, _| { + let expected = shell + .state + .split + .active() + .active_route() + .doc_id() + .map(|id| shell.state.store.backlinks_for(id).len()) + .unwrap_or(0); + let mounted = window + .frame_snapshot() + .elements + .keys() + .filter(|id| id.starts_with("desktop.inspector.backlink.")) + .count(); + assert_eq!(mounted, expected); + assert!( + !window + .frame_snapshot() + .elements + .contains_key(&format!("desktop.inspector.backlink.{last_id}")) + ); + }) + .expect("view") + }); +} diff --git a/packages/frontend/desktop/src/views_extra/tests.rs b/packages/frontend/desktop/src/views_extra/tests.rs deleted file mode 100644 index c185d6af08..0000000000 --- a/packages/frontend/desktop/src/views_extra/tests.rs +++ /dev/null @@ -1,819 +0,0 @@ -use affine_store::directory::DocMode; -use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType}; -use ui::{ - AnyWindowHandle, AppContext, Application, ApplicationHandle, Bounds, Context, HeadlessPlatform, - HeadlessWindow, Keystroke, MouseButton, MouseDownEvent, MouseUpEvent, Pixels, PlatformInput, - Point, Window, WindowBounds, WindowHandle, WindowOptions, point, px, size, -}; -use ui_tokens::ThemeMode; - -use super::{ - UNHYDRATED_TAG_FALLBACK_RGB, - outline_rail::HIDDEN_MAX_PANE_WIDTH, - scroll::{DocRowKey, RowGeometry, RowLayout, RowStyle}, -}; -use crate::{DesktopAppState, DesktopRoute, DesktopShellView, register_desktop_fonts}; - -struct Shell { - app: ApplicationHandle, - handle: WindowHandle, - window: HeadlessWindow, -} - -impl Shell { - fn new(width: u32) -> Self { - Self::with_state( - width, - DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"), - ) - } - - fn with_state(width: u32, state: DesktopAppState) -> Self { - let platform = HeadlessPlatform::new(width, 800, 1.0); - let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); - let handle = app.update(|cx| { - register_desktop_fonts(cx).expect("desktop fonts"); - cx.open_window( - WindowOptions { - window_bounds: Some(WindowBounds::Windowed(Bounds::new( - point(px(0.0), px(0.0)), - size(px(width as f32), px(800.0)), - ))), - ..WindowOptions::default() - }, - |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), - ) - .expect("desktop window") - }); - let window = platform - .windows() - .into_iter() - .next() - .expect("headless window"); - window.request_frame(); - Self { - app, - handle, - window, - } - } - - fn update( - &self, - f: impl FnOnce(&mut DesktopShellView, &mut Window, &mut Context) -> T, - ) -> T { - self.app - .update(|cx| self.handle.update(cx, f).expect("desktop view")) - } - - fn position(&self, id: &str) -> Point { - let b = self.bounds(id); - point(px(b.x + b.width / 2.0), px(b.y + b.height / 2.0)) - } - - fn click(&self, id: &str) { - self.window.simulate_click(self.position(id)); - self.window.request_frame(); - } - - fn right_click(&self, id: &str) { - let position = self.position(id); - self.window - .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { - button: MouseButton::Right, - position, - click_count: 1, - ..Default::default() - })); - self.window - .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { - button: MouseButton::Right, - position, - click_count: 1, - ..Default::default() - })); - self.window.request_frame(); - } - - fn scroll(&self, x: f32, y: f32, delta: f32) { - self.window - .dispatch_input(PlatformInput::Scroll(ui::ScrollEvent { - position: point(px(x), px(y)), - delta: ui::ScrollDelta::Pixels(point(px(0.0), px(delta))), - modifiers: ui::Modifiers::default(), - touch_phase: ui::TouchPhase::Moved, - source: ui::ScrollSource::Pointer, - })); - self.window.request_frame(); - } - - fn hover(&self, id: &str) { - self.window - .dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { - position: self.position(id), - ..Default::default() - })); - self.window.request_frame(); - } - - fn bounds(&self, id: &str) -> ui::SnapshotRect { - self.update(|_, window, _| window.frame_snapshot().elements[id].bounds) - } - - fn key(&self, key: &'static str) { - self.app.update(|cx| { - AnyWindowHandle::from(self.handle) - .update(cx, |_, window, cx| { - window.dispatch_keystroke(Keystroke::parse(key).expect("valid test key"), cx); - }) - .expect("desktop window"); - }); - self.window.request_frame(); - } - - fn contains(&self, id: &str) -> bool { - self.update(|_, window, _| window.frame_snapshot().elements.contains_key(id)) - } - - fn route(&self) -> DesktopRoute { - self.update(|shell, _, _| shell.state.split.active().active_route().clone()) - } - - fn root_update(&self) -> Vec { - self.update(|shell, _, _| { - shell - .state - .store - .directory - .db() - .root() - .encode_update_v1() - .unwrap() - }) - } -} - -#[test] -fn explorer_overview_links_return_from_collection_and_tag_details() { - let app = Shell::new(1280); - let scenarios = [ - ( - "desktop.explorer.nav.collections", - [ - (DesktopRoute::Collection("col-rust-core".into()), "doc-sync"), - ( - DesktopRoute::Collection("col-whiteboards".into()), - "doc-board", - ), - ], - ), - ( - "desktop.explorer.nav.tags", - [ - (DesktopRoute::Tag("architecture".into()), "doc-arch"), - (DesktopRoute::Tag("design".into()), "doc-board"), - ], - ), - ]; - for (nav, [first, second]) in scenarios { - app.click("desktop.sidebar.all_docs"); - app.click(nav); - assert_eq!(app.route(), DesktopRoute::AllDocs); - app.click("desktop.explorer.group.0"); - assert_eq!(app.route(), first.0); - assert!(app.contains(&format!("desktop.list.doc.{}", first.1))); - - app.click("desktop.explorer.nav.docs"); - assert_eq!(app.route(), DesktopRoute::AllDocs); - assert!(app.contains("desktop.list.doc.doc-sync")); - app.click(nav); - assert_eq!(app.route(), DesktopRoute::AllDocs); - assert!(!app.contains(&format!("desktop.list.doc.{}", first.1))); - assert!(app.contains("desktop.explorer.group.0")); - app.click("desktop.explorer.group.1"); - assert_eq!(app.route(), second.0); - assert!(app.contains(&format!("desktop.list.doc.{}", second.1))); - assert!(!app.contains(&format!("desktop.list.doc.{}", first.1))); - - app.click(nav); - assert_eq!(app.route(), DesktopRoute::AllDocs); - assert!(app.contains("desktop.explorer.group.1")); - } -} - -#[test] -fn trash_confirmation_blocks_shortcuts_and_escape_leaves_the_trash_unchanged() { - let app = Shell::new(1280); - app.scroll(120.0, 500.0, -1000.0); - app.click("desktop.sidebar.trash"); - 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(), - ] { - app.click(&button); - assert!(app.contains("desktop.trash.confirm")); - for key in ["ctrl-k", "cmd-k", "ctrl-n", "enter"] { - app.key(key); - assert!(app.contains("desktop.trash.confirm"), "{key}"); - app.update(|shell, _, _| assert!(!shell.state.quick_search.open, "{key}")); - } - app.key("escape"); - assert!(!app.contains("desktop.trash.confirm")); - assert_eq!(app.route(), DesktopRoute::Trash); - assert_eq!(app.root_update(), before); - assert!(app.contains(&format!("desktop.trash.row.{id}"))); - } - app.key("ctrl-k"); - app.update(|shell, _, _| assert!(shell.state.quick_search.open)); -} - -#[test] -fn explorer_row_menu_offers_split_only_at_or_above_640_pixels() { - for (width, split) in [(639, false), (640, true)] { - let app = Shell::new(width); - app.update(|shell, _, cx| { - shell.state.navigate_active_pane(DesktopRoute::AllDocs); - cx.notify(); - }); - app.window.request_frame(); - app.right_click("desktop.list.doc.doc-sync"); - assert!(app.contains("desktop.explorer.menu")); - assert_eq!(app.contains("desktop.explorer.menu.split"), split); - } -} - -const ROW_TIME: i64 = 1_900_000_000_000; - -fn append_rows(state: &mut DesktopAppState, count: i64, start: i64, trashed: bool) -> Vec { - (0..count) - .map(|i| { - let time = start + i; - let id = state.store.create_doc( - format!("Document {i} with a long title for the test"), - DocMode::Page, - None, - time, - ); - if trashed { - assert!(state.store.trash_doc(&id, time)); - } - id - }) - .collect() -} - -#[test] -fn virtual_rows_keep_spacers_and_anchor_after_height_order_and_document_changes() { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - append_rows(&mut state, 8, ROW_TIME, false); - let docs = state.store.visible_docs(); - let keys: Vec<_> = docs.into_iter().map(DocRowKey::explorer).collect(); - let geometry = |width| RowGeometry { - width: px(width), - rem: px(16.0), - scale: 1.0, - text: ui::TextStyle::default(), - style: RowStyle::List { selecting: false }, - }; - let mut layout = RowLayout::default(); - let viewport = 76.0; - let measured = |_, _, row: &[DocRowKey]| { - if row[0].id == keys[0].id { - 58.0 - } else if row[0].id == keys[1].id { - 82.0 - } else { - 38.0 - } - }; - layout.configure(keys.clone(), geometry(700.0)); - assert!(layout.queue_wheel(-70.0, viewport)); - let window = layout.prepare_window(viewport, 0.0, measured); - assert_eq!(window.visible_range.start, 1); - assert_eq!(window.leading_spacer, 58.0); - assert_eq!(layout.window(40.0, 0.0).visible_range, 1..2); - - let mut reordered = keys.clone(); - reordered.swap(1, 2); - layout.configure(reordered.clone(), geometry(700.0)); - layout.prepare_window(viewport, 0.0, measured); - assert_eq!(layout.window(40.0, 0.0).visible_range, 2..3); - - layout.configure(reordered.clone(), geometry(320.0)); - layout.prepare_window( - viewport, - 0.0, - |index, _, _| { - if index == 2 { 96.0 } else { 38.0 } - }, - ); - assert_eq!(layout.window(80.0, 0.0).visible_range, 2..3); - assert_eq!(layout.window(85.0, 0.0).visible_range, 2..4); - - reordered.remove(2); - layout.configure(reordered.clone(), geometry(320.0)); - let final_index = reordered.len() - 1; - let after_removal = |index, _, _: &[DocRowKey]| match index { - 2 => 70.0, - index if index == final_index => 80.0, - _ => 38.0, - }; - layout.prepare_window(viewport, 0.0, after_removal); - assert_eq!(layout.window(69.0, 0.0).visible_range, 2..3); - - assert!(layout.queue_wheel(-1_000_000.0, viewport)); - let last = layout.prepare_window(viewport, 0.0, after_removal); - assert_eq!(last.visible_range.end, reordered.len()); - assert_eq!(last.trailing_spacer, 0.0); - assert_eq!(last.visible_range, final_index..reordered.len()); - let mounted_height = 80.0; - assert_eq!( - last.leading_spacer + mounted_height + last.trailing_spacer, - last.total_height - ); - assert_eq!( - layout.prepare_window(viewport, 0.0, |_, _, _| panic!("row was already measured")), - last - ); -} - -#[test] -fn explorer_shift_click_and_row_menu_keep_the_document_identity() { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let docs = append_rows(&mut state, 60, ROW_TIME, false); - state.navigate_active_pane(DesktopRoute::AllDocs); - let app = Shell::with_state(1280, state); - let target = docs.last().unwrap(); - let row = format!("desktop.list.doc.{target}"); - let position = app.position(&row); - let modifiers = ui::Modifiers { - shift: true, - ..Default::default() - }; - app.window - .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { - button: MouseButton::Left, - position, - modifiers, - click_count: 1, - ..Default::default() - })); - app.window - .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { - button: MouseButton::Left, - position, - modifiers, - click_count: 1, - })); - app.window.request_frame(); - assert!(app.contains("desktop.peek.modal")); - app.click("desktop.peek.close"); - - app.right_click(&row); - assert!(app.contains("desktop.explorer.menu.trash")); - app.scroll(850.0, 600.0, -100_000.0); - assert!(!app.contains(&row)); - assert!(app.contains("desktop.list.doc.doc-sync")); - app.click("desktop.explorer.menu.trash"); - app.update(|shell, _, _| { - assert!(shell.state.store.get_doc(target).unwrap().meta.trashed); - assert!(!shell.state.store.get_doc(&docs[0]).unwrap().meta.trashed); - }); -} - -#[test] -fn explorer_select_all_includes_every_document_in_the_collection() { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let docs = append_rows(&mut state, 48, ROW_TIME, false); - let selected: Vec<_> = docs.iter().step_by(2).cloned().collect(); - state - .store - .collections - .push(crate::doc_store::DesktopCollection { - id: "virtual-list-test".into(), - name: "Selected test documents".into(), - rules: vec![affine_client::domain::CollectionRule::IncludeDocIds( - selected.clone(), - )], - }); - state.navigate_active_pane(DesktopRoute::Collection("virtual-list-test".into())); - let app = Shell::with_state(1280, state); - assert!(!app.contains(&format!("desktop.list.doc.{}", selected[0]))); - app.click("desktop.explorer.select"); - app.click("desktop.explorer.select_all"); - app.click("desktop.explorer.trash"); - app.update(|shell, _, _| { - for (index, id) in docs.iter().enumerate() { - assert_eq!( - shell.state.store.get_doc(id).unwrap().meta.trashed, - index.is_multiple_of(2) - ); - } - }); -} - -#[test] -fn trash_confirmation_keeps_its_document_after_the_row_leaves_the_window() { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let mut target = append_rows(&mut state, 1, ROW_TIME, true); - let target = target.pop().unwrap(); - let anchor = append_rows(&mut state, 1, ROW_TIME + 100, true) - .pop() - .unwrap(); - state.navigate_active_pane(DesktopRoute::Trash); - let app = Shell::with_state(1280, state); - app.click(&format!("desktop.trash.delete.{target}")); - assert!(app.contains("desktop.trash.confirm")); - app.update(|shell, _, cx| { - append_rows(&mut shell.state, 48, ROW_TIME + 10, true); - cx.notify(); - }); - app.window.request_frame(); - assert!(!app.contains(&format!("desktop.trash.row.{target}"))); - app.click("desktop.trash.confirm.delete"); - app.update(|shell, _, _| { - assert!(shell.state.store.get_doc(&target).is_none()); - assert!(shell.state.store.get_doc(&anchor).unwrap().meta.trashed); - }); -} - -#[test] -fn trash_rows_measure_wrapped_commands_at_narrow_width() { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let id = append_rows(&mut state, 1, ROW_TIME, true).pop().unwrap(); - let row = format!("desktop.trash.row.{id}"); - state.navigate_active_pane(DesktopRoute::Trash); - let wide = Shell::with_state(1280, state); - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let id = append_rows(&mut state, 1, ROW_TIME, true).pop().unwrap(); - state.navigate_active_pane(DesktopRoute::Trash); - let narrow = Shell::with_state(380, state); - assert!(narrow.bounds(&format!("desktop.trash.row.{id}")).height > wide.bounds(&row).height); -} - -#[test] -fn explorer_grid_keeps_two_columns_and_reaches_an_odd_final_row() { - 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); - 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); - 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); -} - -#[test] -fn variable_rows_keep_pixel_scroll_independent_of_wheel_step_size() { - fn setup(style: RowStyle, width: u32) -> Shell { - let trash = style == RowStyle::Trash; - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let ids = append_rows(&mut state, 96, ROW_TIME, trash); - if !trash { - for (index, id) in ids.iter().enumerate() { - let tag_count = if matches!(style, RowStyle::Grid { .. }) { - 5 + index % 2 - } else { - 8 + index % 5 - }; - let tags = (0..tag_count) - .map(|tag| format!("project-label-{tag}")) - .collect(); - state.store.docs.get_mut(id).unwrap().meta.tags = tags; - } - state.store.touch_meta(); - } - state.navigate_active_pane(if trash { - DesktopRoute::Trash - } else { - DesktopRoute::AllDocs - }); - let shell = Shell::with_state(width, state); - if matches!(style, RowStyle::Grid { .. }) { - shell.click("desktop.explorer.grid"); - } - shell - } - - fn first_visible(shell: &Shell, prefix: &str) -> (String, f32, f32) { - shell.update(|_, window, _| { - let snapshot = window.frame_snapshot(); - let (id, row) = snapshot - .elements - .iter() - .filter(|(id, row)| { - id.starts_with(prefix) - && row.bounds.y + row.bounds.height > row.content_mask.y - && row.bounds.y < row.content_mask.y + row.content_mask.height - }) - .min_by(|(_, a), (_, b)| { - a.bounds - .y - .total_cmp(&b.bounds.y) - .then(a.bounds.x.total_cmp(&b.bounds.x)) - }) - .expect("visible document row"); - (id.clone(), row.bounds.y, row.bounds.height) - }) - } - - for (style, width, prefix, minimum, distance) in [ - (RowStyle::Trash, 380, "desktop.trash.row.", 38.0, 2_100_i32), - ( - RowStyle::Grid { selecting: false }, - 380, - "desktop.list.doc.", - 148.0, - 2_100, - ), - ( - RowStyle::List { selecting: false }, - 640, - "desktop.list.doc.", - 38.0, - 5_000, - ), - ] { - let single = setup(style, width); - let stepped = setup(style, width); - let start = first_visible(&single, prefix); - assert!(start.2 > minimum, "{prefix}: {start:?}"); - let x = width as f32 * 0.75; - single.scroll(x, 410.0, -distance as f32); - for step in 0..15 { - let delta = (step + 1) * distance / 15 - step * distance / 15; - stepped.scroll(x, 410.0, -delta as f32); - } - let landing = first_visible(&single, prefix); - assert_ne!(landing.0, start.0, "{prefix}"); - assert_eq!(landing, first_visible(&stepped, prefix), "{prefix}"); - - single.scroll(x, 410.0, distance as f32); - assert_eq!(first_visible(&single, prefix), start, "{prefix}"); - } -} - -fn outline_state(count: usize) -> (DesktopAppState, Vec) { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let ids = add_outline_headings(&mut state, "doc-arch", count); - (state, ids) -} - -/// Adds `count` H2 headings `outline-heading-` to the document. -fn add_outline_headings(state: &mut DesktopAppState, doc: &str, count: usize) -> Vec { - let entry = state.store.docs.get_mut(doc).unwrap(); - let ids: Vec = (0..count).map(|i| format!("outline-heading-{i}")).collect(); - entry - .session - .structural_edit(100, |page| { - for (i, id) in ids.iter().enumerate() { - page.add_block( - id, - BlockSpec::Paragraph { - paragraph_type: ParagraphType::H2, - text: format!("Section {i}"), - }, - Some(&entry.note_id), - None, - 101 + i as u64, - )?; - } - Ok(()) - }) - .unwrap(); - entry.snapshot = entry.session.read_page_snapshot().unwrap(); - entry.revision = entry.session.revision(); - ids -} - -#[test] -fn outline_rail_shows_only_above_640_pixel_panes_at_web_edge_insets() { - for (width, visible) in [ - (HIDDEN_MAX_PANE_WIDTH as u32, false), - (HIDDEN_MAX_PANE_WIDTH as u32 + 1, true), - (1280, true), - ] { - let (state, _) = outline_state(4); - let pane_id = state.split.active().id; - let app = Shell::with_state(width, state); - let rail = format!("desktop.outline.rail.{pane_id}"); - let panel = format!("desktop.outline.rail.panel.{pane_id}"); - let pane = app.bounds("desktop.pane.0"); - let pane_right = pane.x + pane.width; - if width < 700 { - assert_eq!(pane.width, width as f32, "pane fills the compact window"); - } - assert_eq!(app.contains(&rail), visible, "rail at {width} px"); - if !visible { - continue; - } - // `top: 204px; right: 22px` below the 52 px header of the pane. - let rail_top = pane.y + 52.0 + 204.0; - let ticks = app.bounds(&rail); - assert_eq!( - (ticks.x + ticks.width, ticks.y), - (pane_right - 22.0, rail_top) - ); - assert_eq!(ticks.width, 24.0); - // The open panel is 200 px wide, moves 10 px away from the ticks, and keeps the - // `max-height: calc(100% - 204px - 76px)` limit. - app.hover(&rail); - let open = app.bounds(&panel); - assert_eq!((open.width, open.y), (200.0, rail_top)); - assert_eq!(open.x + open.width, pane_right - 32.0); - assert!(open.y + open.height <= pane.y + pane.height - 76.0); - } -} - -#[test] -fn outline_rail_mounts_a_bounded_window_of_512_headings_while_it_scrolls_and_reveals() { - const ROW: f32 = 24.0; - const MAX_MOUNTED: usize = 24; - let (state, ids) = outline_state(512); - let pane = state.split.active().id; - let app = Shell::with_state(1280, state); - let rail = format!("desktop.outline.rail.{pane}"); - let panel = format!("desktop.outline.rail.panel.{pane}"); - let heading = |i: usize| format!("desktop.outline.rail.heading.{pane}.{}", ids[i]); - let prefix = format!("desktop.outline.rail.heading.{pane}."); - let mounted = || { - app.update(|_, window, _| { - window - .frame_snapshot() - .elements - .keys() - .filter(|id| id.starts_with(&prefix)) - .count() - }) - }; - - app.hover(&rail); - let open = app.bounds(&panel); - // 1 px border and 8 px padding above and below the list. - let list_top = open.y + 9.0; - let list_bottom = open.y + open.height - 9.0; - // The pane body starts below the 52 px header; the panel keeps 204 px above it and - // 76 px below it, less its border and padding. - let body = app.bounds("desktop.pane.0"); - let list_height = body.height - 52.0 - 204.0 - 76.0 - 18.0; - assert_eq!(list_bottom - list_top, list_height); - // The showcase document has headings of its own above the added ones. - let base = ((app.bounds(&heading(0)).y - list_top) / ROW) as usize; - let max_scroll = (base + 512) as f32 * ROW - list_height; - let (x, y) = (open.x + open.width / 2.0, open.y + open.height / 2.0); - - for (delta, offset) in [ - (0.0, 0.0), - (-5952.0, 5952.0), - (-1.0e6, max_scroll), - (ROW, max_scroll - ROW), - (-1.0e6, max_scroll), - (1.0e6, 0.0), - ] { - app.scroll(x, y, delta); - let count = mounted(); - assert!( - (16..=MAX_MOUNTED).contains(&count), - "{count} rows mounted at offset {offset}" - ); - // The first added heading at or below the top edge of the list. - let first = ((offset / ROW) as usize).max(base) - base; - assert_eq!( - app.bounds(&heading(first)).y, - list_top + (base + first) as f32 * ROW - offset, - "offset {offset}" - ); - if offset == max_scroll { - let last = app.bounds(&heading(511)); - assert_eq!(last.y + last.height, list_bottom); - } - } - - for (delta, target) in [(-5952.0, 250), (-1.0e6, 511)] { - app.scroll(x, y, delta); - let block = format!("page.block.{}", ids[target]); - assert!(!app.contains(&block)); - app.click(&heading(target)); - assert!(app.contains(&block), "heading {target} revealed"); - assert_eq!(app.route(), DesktopRoute::Doc("doc-arch".into())); - app.hover(&rail); - } -} - -#[test] -fn outline_rail_keeps_first_visible_heading_when_the_list_shrinks_and_grows() { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let doc = state.store.create_doc("Outline", DocMode::Page, None, 10); - let ids = add_outline_headings(&mut state, &doc, 90); - state.open_doc_in_active_pane(&doc); - let pane = state.split.active().id; - let app = Shell::with_state(1280, state); - let prefix = format!("desktop.outline.rail.heading.{pane}."); - let first_visible_heading = || { - app.update(|_, window, _| { - window - .frame_snapshot() - .elements - .iter() - .filter(|(id, row)| { - id.starts_with(&prefix) - && row.bounds.y + row.bounds.height > row.content_mask.y - && row.bounds.y < row.content_mask.y + row.content_mask.height - }) - .min_by(|(_, a), (_, b)| a.bounds.y.total_cmp(&b.bounds.y)) - .expect("visible outline heading") - .0 - .clone() - }) - }; - let set_tail_type = |kind: &str, now| { - app.update(|shell, _, cx| { - let entry = shell.state.store.docs.get_mut(&doc).unwrap(); - entry - .session - .structural_edit(now, |page| { - for id in &ids[40..] { - page.set_block_prop( - id, - "prop:type", - y_octo::SessionValue::Any(y_octo::Any::String(kind.into())), - now, - )?; - } - Ok(()) - }) - .unwrap(); - entry.snapshot = entry.session.read_page_snapshot().unwrap(); - entry.revision = entry.session.revision(); - cx.notify(); - }); - app.window.request_frame(); - }; - - app.hover(&format!("desktop.outline.rail.{pane}")); - let center = app.position(&format!("desktop.outline.rail.panel.{pane}")); - app.scroll(center.x.into(), center.y.into(), -1.0e6); - let bottom = first_visible_heading(); - let last = format!("{prefix}{}", ids[89]); - assert!(app.contains(&last)); - - set_tail_type("text", 1000); - let shortened = first_visible_heading(); - assert_ne!(shortened, bottom); - assert!(!app.contains(&last)); - assert!(app.contains(&format!("{prefix}{}", ids[39]))); - - set_tail_type("h2", 2000); - assert_eq!(first_visible_heading(), shortened); - assert!(app.contains(&format!("{prefix}{}", ids[40]))); -} - -// The line ceiling counts this file as production code. This block is test code only. -#[cfg(test)] -mod peer_tag_colors { - use image::GenericImageView; - - use super::*; - - #[test] - fn explorer_list_and_grid_draw_unhydrated_peer_tags_in_the_inspector_fallback_color() { - let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); - let views = state.store.views(); - let known = views.tag("architecture").unwrap(); - let known = known.color(crate::theme_tokens_for(ThemeMode::Light)); - assert!(views.tag("peer-new").is_none()); - assert!(!state.store.tag_colors.contains_key("peer-new")); - let doc = state.store.docs.get_mut("doc-sync").unwrap(); - doc.meta.tags = vec!["architecture".into(), "peer-new".into()]; - state.store.touch_meta(); - state.navigate_active_pane(DesktopRoute::AllDocs); - let app = Shell::with_state(1280, state); - for grid in [false, true] { - if grid { - app.click("desktop.explorer.grid"); - } - let area = app.bounds("desktop.list.doc.doc-sync"); - let frame = app.update(|_, window, _| window.render_to_image().unwrap()); - let (x, y) = (area.x as u32, area.y as u32); - let row = frame.view(x, y, area.width as u32, area.height as u32); - for rgb in [known, UNHYDRATED_TAG_FALLBACK_RGB] { - let [_, r, g, b] = rgb.to_be_bytes(); - let dot = row.pixels().any(|(_, _, pixel)| pixel.0[..3] == [r, g, b]); - assert!(dot, "grid {grid}: no tag dot of #{rgb:06x}"); - } - } - } -} diff --git a/packages/frontend/desktop/src/views_extra/tests/mod.rs b/packages/frontend/desktop/src/views_extra/tests/mod.rs new file mode 100644 index 0000000000..3e8b81612e --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/tests/mod.rs @@ -0,0 +1,247 @@ +mod outline_rail; +mod virtual_rows; + +use ui::{ + AnyWindowHandle, AppContext, Application, ApplicationHandle, Bounds, Context, HeadlessPlatform, + HeadlessWindow, Keystroke, MouseButton, MouseDownEvent, MouseUpEvent, Pixels, PlatformInput, + Point, Window, WindowBounds, WindowHandle, WindowOptions, point, px, size, +}; +use ui_tokens::ThemeMode; + +use super::{ + FALLBACK_TAG_RGB, + outline_rail::HIDDEN_MAX_PANE_WIDTH, + scroll::{DocRowKey, RowGeometry, RowLayout, RowStyle}, +}; +use crate::{DesktopAppState, DesktopRoute, DesktopShellView, register_desktop_fonts}; + +struct Shell { + app: ApplicationHandle, + handle: WindowHandle, + window: HeadlessWindow, +} + +impl Shell { + fn new(width: u32) -> Self { + Self::with_state( + width, + DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"), + ) + } + + fn with_state(width: u32, state: DesktopAppState) -> Self { + let platform = HeadlessPlatform::new(width, 800, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).expect("desktop fonts"); + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(width as f32), px(800.0)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + .expect("desktop window") + }); + let window = platform + .windows() + .into_iter() + .next() + .expect("headless window"); + window.request_frame(); + Self { + app, + handle, + window, + } + } + + fn update( + &self, + f: impl FnOnce(&mut DesktopShellView, &mut Window, &mut Context) -> T, + ) -> T { + self.app + .update(|cx| self.handle.update(cx, f).expect("desktop view")) + } + + fn position(&self, id: &str) -> Point { + let b = self.bounds(id); + point(px(b.x + b.width / 2.0), px(b.y + b.height / 2.0)) + } + + fn click(&self, id: &str) { + self.window.simulate_click(self.position(id)); + self.window.request_frame(); + } + + fn right_click(&self, id: &str) { + let position = self.position(id); + self.window + .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { + button: MouseButton::Right, + position, + click_count: 1, + ..Default::default() + })); + self.window + .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { + button: MouseButton::Right, + position, + click_count: 1, + ..Default::default() + })); + self.window.request_frame(); + } + + fn scroll(&self, x: f32, y: f32, delta: f32) { + self.window + .dispatch_input(PlatformInput::Scroll(ui::ScrollEvent { + position: point(px(x), px(y)), + delta: ui::ScrollDelta::Pixels(point(px(0.0), px(delta))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + self.window.request_frame(); + } + + fn hover(&self, id: &str) { + self.window + .dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { + position: self.position(id), + ..Default::default() + })); + self.window.request_frame(); + } + + fn bounds(&self, id: &str) -> ui::SnapshotRect { + self.update(|_, window, _| window.frame_snapshot().elements[id].bounds) + } + + fn key(&self, key: &'static str) { + self.app.update(|cx| { + AnyWindowHandle::from(self.handle) + .update(cx, |_, window, cx| { + window.dispatch_keystroke(Keystroke::parse(key).expect("valid test key"), cx); + }) + .expect("desktop window"); + }); + self.window.request_frame(); + } + + fn contains(&self, id: &str) -> bool { + self.update(|_, window, _| window.frame_snapshot().elements.contains_key(id)) + } + + fn route(&self) -> DesktopRoute { + self.update(|shell, _, _| shell.state.split.active().active_route().clone()) + } + + fn root_update(&self) -> Vec { + self.update(|shell, _, _| { + shell + .state + .store + .directory + .db() + .root() + .encode_update_v1() + .unwrap() + }) + } +} + +#[test] +fn explorer_overview_links_return_from_collection_and_tag_details() { + let app = Shell::new(1280); + let scenarios = [ + ( + "desktop.explorer.nav.collections", + [ + (DesktopRoute::Collection("col-rust-core".into()), "doc-sync"), + ( + DesktopRoute::Collection("col-whiteboards".into()), + "doc-board", + ), + ], + ), + ( + "desktop.explorer.nav.tags", + [ + (DesktopRoute::Tag("architecture".into()), "doc-arch"), + (DesktopRoute::Tag("design".into()), "doc-board"), + ], + ), + ]; + for (nav, [first, second]) in scenarios { + app.click("desktop.sidebar.all_docs"); + app.click(nav); + assert_eq!(app.route(), DesktopRoute::AllDocs); + app.click("desktop.explorer.group.0"); + assert_eq!(app.route(), first.0); + assert!(app.contains(&format!("desktop.list.doc.{}", first.1))); + + app.click("desktop.explorer.nav.docs"); + assert_eq!(app.route(), DesktopRoute::AllDocs); + assert!(app.contains("desktop.list.doc.doc-sync")); + app.click(nav); + assert_eq!(app.route(), DesktopRoute::AllDocs); + assert!(!app.contains(&format!("desktop.list.doc.{}", first.1))); + assert!(app.contains("desktop.explorer.group.0")); + app.click("desktop.explorer.group.1"); + assert_eq!(app.route(), second.0); + assert!(app.contains(&format!("desktop.list.doc.{}", second.1))); + assert!(!app.contains(&format!("desktop.list.doc.{}", first.1))); + + app.click(nav); + assert_eq!(app.route(), DesktopRoute::AllDocs); + assert!(app.contains("desktop.explorer.group.1")); + } +} + +#[test] +fn trash_confirmation_blocks_shortcuts_and_escape_leaves_the_trash_unchanged() { + let app = Shell::new(1280); + app.scroll(120.0, 500.0, -1000.0); + app.click("desktop.sidebar.trash"); + 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(), + ] { + app.click(&button); + assert!(app.contains("desktop.trash.confirm")); + for key in ["ctrl-k", "cmd-k", "ctrl-n", "enter"] { + app.key(key); + assert!(app.contains("desktop.trash.confirm"), "{key}"); + app.update(|shell, _, _| assert!(!shell.state.quick_search.open, "{key}")); + } + app.key("escape"); + assert!(!app.contains("desktop.trash.confirm")); + assert_eq!(app.route(), DesktopRoute::Trash); + assert_eq!(app.root_update(), before); + assert!(app.contains(&format!("desktop.trash.row.{id}"))); + } + app.key("ctrl-k"); + app.update(|shell, _, _| assert!(shell.state.quick_search.open)); +} + +#[test] +fn explorer_row_menu_offers_split_only_at_or_above_640_pixels() { + for (width, split) in [(639, false), (640, true)] { + let app = Shell::new(width); + app.update(|shell, _, cx| { + shell.state.navigate_active_pane(DesktopRoute::AllDocs); + cx.notify(); + }); + app.window.request_frame(); + app.right_click("desktop.list.doc.doc-sync"); + assert!(app.contains("desktop.explorer.menu")); + assert_eq!(app.contains("desktop.explorer.menu.split"), split); + } +} diff --git a/packages/frontend/desktop/src/views_extra/tests/outline_rail.rs b/packages/frontend/desktop/src/views_extra/tests/outline_rail.rs new file mode 100644 index 0000000000..9392c098e5 --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/tests/outline_rail.rs @@ -0,0 +1,220 @@ +use affine_store::directory::DocMode; +use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType}; +use ui_tokens::ThemeMode; + +use super::{DesktopAppState, DesktopRoute, HIDDEN_MAX_PANE_WIDTH, Shell}; + +fn outline_state(count: usize) -> (DesktopAppState, Vec) { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let ids = add_outline_headings(&mut state, "doc-arch", count); + (state, ids) +} + +/// Adds `count` H2 headings `outline-heading-` to the document. +fn add_outline_headings(state: &mut DesktopAppState, doc: &str, count: usize) -> Vec { + let entry = state.store.docs.get_mut(doc).unwrap(); + let ids: Vec = (0..count).map(|i| format!("outline-heading-{i}")).collect(); + entry + .session + .structural_edit(100, |page| { + for (i, id) in ids.iter().enumerate() { + page.add_block( + id, + BlockSpec::Paragraph { + paragraph_type: ParagraphType::H2, + text: format!("Section {i}"), + }, + Some(&entry.note_id), + None, + 101 + i as u64, + )?; + } + Ok(()) + }) + .unwrap(); + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + ids +} + +#[test] +fn outline_rail_shows_only_above_640_pixel_panes_at_web_edge_insets() { + for (width, visible) in [ + (HIDDEN_MAX_PANE_WIDTH as u32, false), + (HIDDEN_MAX_PANE_WIDTH as u32 + 1, true), + (1280, true), + ] { + let (state, _) = outline_state(4); + let pane_id = state.split.active().id; + let app = Shell::with_state(width, state); + let rail = format!("desktop.outline.rail.{pane_id}"); + let panel = format!("desktop.outline.rail.panel.{pane_id}"); + let pane = app.bounds("desktop.pane.0"); + let pane_right = pane.x + pane.width; + if width < 700 { + assert_eq!(pane.width, width as f32, "pane fills the compact window"); + } + assert_eq!(app.contains(&rail), visible, "rail at {width} px"); + if !visible { + continue; + } + // `top: 204px; right: 22px` below the 52 px header of the pane. + let rail_top = pane.y + 52.0 + 204.0; + let ticks = app.bounds(&rail); + assert_eq!( + (ticks.x + ticks.width, ticks.y), + (pane_right - 22.0, rail_top) + ); + assert_eq!(ticks.width, 24.0); + // The open panel is 200 px wide, moves 10 px away from the ticks, and keeps the + // `max-height: calc(100% - 204px - 76px)` limit. + app.hover(&rail); + let open = app.bounds(&panel); + assert_eq!((open.width, open.y), (200.0, rail_top)); + assert_eq!(open.x + open.width, pane_right - 32.0); + assert!(open.y + open.height <= pane.y + pane.height - 76.0); + } +} + +#[test] +fn outline_rail_mounts_a_bounded_window_of_512_headings_while_it_scrolls_and_reveals() { + const ROW: f32 = 24.0; + const MAX_MOUNTED: usize = 24; + let (state, ids) = outline_state(512); + let pane = state.split.active().id; + let app = Shell::with_state(1280, state); + let rail = format!("desktop.outline.rail.{pane}"); + let panel = format!("desktop.outline.rail.panel.{pane}"); + let heading = |i: usize| format!("desktop.outline.rail.heading.{pane}.{}", ids[i]); + let prefix = format!("desktop.outline.rail.heading.{pane}."); + let mounted = || { + app.update(|_, window, _| { + window + .frame_snapshot() + .elements + .keys() + .filter(|id| id.starts_with(&prefix)) + .count() + }) + }; + + app.hover(&rail); + let open = app.bounds(&panel); + // 1 px border and 8 px padding above and below the list. + let list_top = open.y + 9.0; + let list_bottom = open.y + open.height - 9.0; + // The pane body starts below the 52 px header; the panel keeps 204 px above it and + // 76 px below it, less its border and padding. + let body = app.bounds("desktop.pane.0"); + let list_height = body.height - 52.0 - 204.0 - 76.0 - 18.0; + assert_eq!(list_bottom - list_top, list_height); + // The showcase document has headings of its own above the added ones. + let base = ((app.bounds(&heading(0)).y - list_top) / ROW) as usize; + let max_scroll = (base + 512) as f32 * ROW - list_height; + let (x, y) = (open.x + open.width / 2.0, open.y + open.height / 2.0); + + for (delta, offset) in [ + (0.0, 0.0), + (-5952.0, 5952.0), + (-1.0e6, max_scroll), + (ROW, max_scroll - ROW), + (-1.0e6, max_scroll), + (1.0e6, 0.0), + ] { + app.scroll(x, y, delta); + let count = mounted(); + assert!( + (16..=MAX_MOUNTED).contains(&count), + "{count} rows mounted at offset {offset}" + ); + // The first added heading at or below the top edge of the list. + let first = ((offset / ROW) as usize).max(base) - base; + assert_eq!( + app.bounds(&heading(first)).y, + list_top + (base + first) as f32 * ROW - offset, + "offset {offset}" + ); + if offset == max_scroll { + let last = app.bounds(&heading(511)); + assert_eq!(last.y + last.height, list_bottom); + } + } + + for (delta, target) in [(-5952.0, 250), (-1.0e6, 511)] { + app.scroll(x, y, delta); + let block = format!("page.block.{}", ids[target]); + assert!(!app.contains(&block)); + app.click(&heading(target)); + assert!(app.contains(&block), "heading {target} revealed"); + assert_eq!(app.route(), DesktopRoute::Doc("doc-arch".into())); + app.hover(&rail); + } +} + +#[test] +fn outline_rail_keeps_first_visible_heading_when_the_list_shrinks_and_grows() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let doc = state.store.create_doc("Outline", DocMode::Page, None, 10); + let ids = add_outline_headings(&mut state, &doc, 90); + state.open_doc_in_active_pane(&doc); + let pane = state.split.active().id; + let app = Shell::with_state(1280, state); + let prefix = format!("desktop.outline.rail.heading.{pane}."); + let first_visible_heading = || { + app.update(|_, window, _| { + window + .frame_snapshot() + .elements + .iter() + .filter(|(id, row)| { + id.starts_with(&prefix) + && row.bounds.y + row.bounds.height > row.content_mask.y + && row.bounds.y < row.content_mask.y + row.content_mask.height + }) + .min_by(|(_, a), (_, b)| a.bounds.y.total_cmp(&b.bounds.y)) + .expect("visible outline heading") + .0 + .clone() + }) + }; + let set_tail_type = |kind: &str, now| { + app.update(|shell, _, cx| { + let entry = shell.state.store.docs.get_mut(&doc).unwrap(); + entry + .session + .structural_edit(now, |page| { + for id in &ids[40..] { + page.set_block_prop( + id, + "prop:type", + y_octo::SessionValue::Any(y_octo::Any::String(kind.into())), + now, + )?; + } + Ok(()) + }) + .unwrap(); + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + cx.notify(); + }); + app.window.request_frame(); + }; + + app.hover(&format!("desktop.outline.rail.{pane}")); + let center = app.position(&format!("desktop.outline.rail.panel.{pane}")); + app.scroll(center.x.into(), center.y.into(), -1.0e6); + let bottom = first_visible_heading(); + let last = format!("{prefix}{}", ids[89]); + assert!(app.contains(&last)); + + set_tail_type("text", 1000); + let shortened = first_visible_heading(); + assert_ne!(shortened, bottom); + assert!(!app.contains(&last)); + assert!(app.contains(&format!("{prefix}{}", ids[39]))); + + set_tail_type("h2", 2000); + assert_eq!(first_visible_heading(), shortened); + assert!(app.contains(&format!("{prefix}{}", ids[40]))); +} diff --git a/packages/frontend/desktop/src/views_extra/tests/virtual_rows.rs b/packages/frontend/desktop/src/views_extra/tests/virtual_rows.rs new file mode 100644 index 0000000000..50fd9ad0fb --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/tests/virtual_rows.rs @@ -0,0 +1,359 @@ +use affine_store::directory::DocMode; +use image::GenericImageView; +use ui::{MouseButton, MouseDownEvent, MouseUpEvent, PlatformInput, px}; +use ui_tokens::ThemeMode; + +use super::{ + DesktopAppState, DesktopRoute, DocRowKey, FALLBACK_TAG_RGB, RowGeometry, RowLayout, RowStyle, + Shell, +}; + +const ROW_TIME: i64 = 1_900_000_000_000; + +fn append_rows(state: &mut DesktopAppState, count: i64, start: i64, trashed: bool) -> Vec { + (0..count) + .map(|i| { + let time = start + i; + let id = state.store.create_doc( + format!("Document {i} with a long title for the test"), + DocMode::Page, + None, + time, + ); + if trashed { + assert!(state.store.trash_doc(&id, time)); + } + id + }) + .collect() +} + +#[test] +fn virtual_rows_keep_spacers_and_anchor_after_height_order_and_document_changes() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + append_rows(&mut state, 8, ROW_TIME, false); + let docs = state.store.visible_docs(); + let keys: Vec<_> = docs.into_iter().map(DocRowKey::explorer).collect(); + let geometry = |width| RowGeometry { + width: px(width), + rem: px(16.0), + scale: 1.0, + text: ui::TextStyle::default(), + style: RowStyle::List { selecting: false }, + }; + let mut layout = RowLayout::default(); + let viewport = 76.0; + let measured = |_, _, row: &[DocRowKey]| { + if row[0].id == keys[0].id { + 58.0 + } else if row[0].id == keys[1].id { + 82.0 + } else { + 38.0 + } + }; + layout.configure(keys.clone(), geometry(700.0)); + assert!(layout.queue_wheel(-70.0, viewport)); + let window = layout.prepare_window(viewport, 0.0, measured); + assert_eq!(window.visible_range.start, 1); + assert_eq!(window.leading_spacer, 58.0); + assert_eq!(layout.window(40.0, 0.0).visible_range, 1..2); + + let mut reordered = keys.clone(); + reordered.swap(1, 2); + layout.configure(reordered.clone(), geometry(700.0)); + layout.prepare_window(viewport, 0.0, measured); + assert_eq!(layout.window(40.0, 0.0).visible_range, 2..3); + + layout.configure(reordered.clone(), geometry(320.0)); + layout.prepare_window( + viewport, + 0.0, + |index, _, _| { + if index == 2 { 96.0 } else { 38.0 } + }, + ); + assert_eq!(layout.window(80.0, 0.0).visible_range, 2..3); + assert_eq!(layout.window(85.0, 0.0).visible_range, 2..4); + + reordered.remove(2); + layout.configure(reordered.clone(), geometry(320.0)); + let final_index = reordered.len() - 1; + let after_removal = |index, _, _: &[DocRowKey]| match index { + 2 => 70.0, + index if index == final_index => 80.0, + _ => 38.0, + }; + layout.prepare_window(viewport, 0.0, after_removal); + assert_eq!(layout.window(69.0, 0.0).visible_range, 2..3); + + assert!(layout.queue_wheel(-1_000_000.0, viewport)); + let last = layout.prepare_window(viewport, 0.0, after_removal); + assert_eq!(last.visible_range.end, reordered.len()); + assert_eq!(last.trailing_spacer, 0.0); + assert_eq!(last.visible_range, final_index..reordered.len()); + let mounted_height = 80.0; + assert_eq!( + last.leading_spacer + mounted_height + last.trailing_spacer, + last.total_height + ); + assert_eq!( + layout.prepare_window(viewport, 0.0, |_, _, _| panic!("row was already measured")), + last + ); +} + +#[test] +fn explorer_shift_click_and_row_menu_keep_the_document_identity() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let docs = append_rows(&mut state, 60, ROW_TIME, false); + state.navigate_active_pane(DesktopRoute::AllDocs); + let app = Shell::with_state(1280, state); + let target = docs.last().unwrap(); + let row = format!("desktop.list.doc.{target}"); + let position = app.position(&row); + let modifiers = ui::Modifiers { + shift: true, + ..Default::default() + }; + app.window + .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { + button: MouseButton::Left, + position, + modifiers, + click_count: 1, + ..Default::default() + })); + app.window + .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { + button: MouseButton::Left, + position, + modifiers, + click_count: 1, + })); + app.window.request_frame(); + assert!(app.contains("desktop.peek.modal")); + app.click("desktop.peek.close"); + + app.right_click(&row); + assert!(app.contains("desktop.explorer.menu.trash")); + app.scroll(850.0, 600.0, -100_000.0); + assert!(!app.contains(&row)); + assert!(app.contains("desktop.list.doc.doc-sync")); + app.click("desktop.explorer.menu.trash"); + app.update(|shell, _, _| { + assert!(shell.state.store.get_doc(target).unwrap().meta.trashed); + assert!(!shell.state.store.get_doc(&docs[0]).unwrap().meta.trashed); + }); +} + +#[test] +fn explorer_select_all_includes_every_document_in_the_collection() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let docs = append_rows(&mut state, 48, ROW_TIME, false); + let selected: Vec<_> = docs.iter().step_by(2).cloned().collect(); + state + .store + .collections + .push(crate::doc_store::DesktopCollection { + id: "virtual-list-test".into(), + name: "Selected test documents".into(), + rules: vec![affine_client::domain::CollectionRule::IncludeDocIds( + selected.clone(), + )], + }); + state.navigate_active_pane(DesktopRoute::Collection("virtual-list-test".into())); + let app = Shell::with_state(1280, state); + assert!(!app.contains(&format!("desktop.list.doc.{}", selected[0]))); + app.click("desktop.explorer.select"); + app.click("desktop.explorer.select_all"); + app.click("desktop.explorer.trash"); + app.update(|shell, _, _| { + for (index, id) in docs.iter().enumerate() { + assert_eq!( + shell.state.store.get_doc(id).unwrap().meta.trashed, + index.is_multiple_of(2) + ); + } + }); +} + +#[test] +fn trash_confirmation_keeps_its_document_after_the_row_leaves_the_window() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let mut target = append_rows(&mut state, 1, ROW_TIME, true); + let target = target.pop().unwrap(); + let anchor = append_rows(&mut state, 1, ROW_TIME + 100, true) + .pop() + .unwrap(); + state.navigate_active_pane(DesktopRoute::Trash); + let app = Shell::with_state(1280, state); + app.click(&format!("desktop.trash.delete.{target}")); + assert!(app.contains("desktop.trash.confirm")); + app.update(|shell, _, cx| { + append_rows(&mut shell.state, 48, ROW_TIME + 10, true); + cx.notify(); + }); + app.window.request_frame(); + assert!(!app.contains(&format!("desktop.trash.row.{target}"))); + app.click("desktop.trash.confirm.delete"); + app.update(|shell, _, _| { + assert!(shell.state.store.get_doc(&target).is_none()); + assert!(shell.state.store.get_doc(&anchor).unwrap().meta.trashed); + }); +} + +#[test] +fn trash_rows_measure_wrapped_commands_at_narrow_width() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let id = append_rows(&mut state, 1, ROW_TIME, true).pop().unwrap(); + let row = format!("desktop.trash.row.{id}"); + state.navigate_active_pane(DesktopRoute::Trash); + let wide = Shell::with_state(1280, state); + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let id = append_rows(&mut state, 1, ROW_TIME, true).pop().unwrap(); + state.navigate_active_pane(DesktopRoute::Trash); + let narrow = Shell::with_state(380, state); + assert!(narrow.bounds(&format!("desktop.trash.row.{id}")).height > wide.bounds(&row).height); +} + +#[test] +fn explorer_grid_keeps_two_columns_and_reaches_an_odd_final_row() { + 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); + 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); + 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); +} + +#[test] +fn variable_rows_keep_pixel_scroll_independent_of_wheel_step_size() { + fn setup(style: RowStyle, width: u32) -> Shell { + let trash = style == RowStyle::Trash; + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let ids = append_rows(&mut state, 96, ROW_TIME, trash); + if !trash { + for (index, id) in ids.iter().enumerate() { + let tag_count = if matches!(style, RowStyle::Grid { .. }) { + 5 + index % 2 + } else { + 8 + index % 5 + }; + let tags = (0..tag_count) + .map(|tag| format!("project-label-{tag}")) + .collect(); + state.store.docs.get_mut(id).unwrap().meta.tags = tags; + } + state.store.touch_meta(); + } + state.navigate_active_pane(if trash { + DesktopRoute::Trash + } else { + DesktopRoute::AllDocs + }); + let shell = Shell::with_state(width, state); + if matches!(style, RowStyle::Grid { .. }) { + shell.click("desktop.explorer.grid"); + } + shell + } + + fn first_visible(shell: &Shell, prefix: &str) -> (String, f32, f32) { + shell.update(|_, window, _| { + let snapshot = window.frame_snapshot(); + let (id, row) = snapshot + .elements + .iter() + .filter(|(id, row)| { + id.starts_with(prefix) + && row.bounds.y + row.bounds.height > row.content_mask.y + && row.bounds.y < row.content_mask.y + row.content_mask.height + }) + .min_by(|(_, a), (_, b)| { + a.bounds + .y + .total_cmp(&b.bounds.y) + .then(a.bounds.x.total_cmp(&b.bounds.x)) + }) + .expect("visible document row"); + (id.clone(), row.bounds.y, row.bounds.height) + }) + } + + for (style, width, prefix, minimum, distance) in [ + (RowStyle::Trash, 380, "desktop.trash.row.", 38.0, 2_100_i32), + ( + RowStyle::Grid { selecting: false }, + 380, + "desktop.list.doc.", + 148.0, + 2_100, + ), + ( + RowStyle::List { selecting: false }, + 640, + "desktop.list.doc.", + 38.0, + 5_000, + ), + ] { + let single = setup(style, width); + let stepped = setup(style, width); + let start = first_visible(&single, prefix); + assert!(start.2 > minimum, "{prefix}: {start:?}"); + let x = width as f32 * 0.75; + single.scroll(x, 410.0, -distance as f32); + for step in 0..15 { + let delta = (step + 1) * distance / 15 - step * distance / 15; + stepped.scroll(x, 410.0, -delta as f32); + } + let landing = first_visible(&single, prefix); + assert_ne!(landing.0, start.0, "{prefix}"); + assert_eq!(landing, first_visible(&stepped, prefix), "{prefix}"); + + single.scroll(x, 410.0, distance as f32); + assert_eq!(first_visible(&single, prefix), start, "{prefix}"); + } +} + +#[test] +fn explorer_list_and_grid_draw_unhydrated_peer_tags_in_the_inspector_fallback_color() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let views = state.store.views(); + let known = views.tag("architecture").unwrap(); + let known = known.color(crate::theme_tokens_for(ThemeMode::Light)); + assert!(views.tag("peer-new").is_none()); + assert!(!state.store.tag_colors.contains_key("peer-new")); + let doc = state.store.docs.get_mut("doc-sync").unwrap(); + doc.meta.tags = vec!["architecture".into(), "peer-new".into()]; + state.store.touch_meta(); + state.navigate_active_pane(DesktopRoute::AllDocs); + let app = Shell::with_state(1280, state); + for grid in [false, true] { + if grid { + app.click("desktop.explorer.grid"); + } + let area = app.bounds("desktop.list.doc.doc-sync"); + let frame = app.update(|_, window, _| window.render_to_image().unwrap()); + let (x, y) = (area.x as u32, area.y as u32); + let row = frame.view(x, y, area.width as u32, area.height as u32); + for rgb in [known, FALLBACK_TAG_RGB] { + let [_, r, g, b] = rgb.to_be_bytes(); + let dot = row.pixels().any(|(_, _, pixel)| pixel.0[..3] == [r, g, b]); + assert!(dot, "grid {grid}: no tag dot of #{rgb:06x}"); + } + } +}