From 4e2edf3cd9be29de71155380a45147e80d55315f Mon Sep 17 00:00:00 2001 From: DarkSky Date: Thu, 3 Dec 2026 20:31:12 +0900 Subject: [PATCH] perf(desktop): virtualize inspector outline and align hover styles Virtualize the right sidebar outline list inside one scroll container. Keep the 38 px row stride (28 px row and 10 px gap). Cache shared strings for heading rows. Align outline row hover to hoverOverlay. Align the inspector tab switcher to Web RadioGroup active, shadow, and hover tokens. --- .../src/views_extra/right_sidebar/mod.rs | 209 ++++--- .../src/views_extra/right_sidebar/outline.rs | 290 +++++++-- .../views_extra/tests/inspector_outline.rs | 554 ++++++++++++++++++ .../desktop/src/views_extra/tests/mod.rs | 1 + 4 files changed, 951 insertions(+), 103 deletions(-) create mode 100644 packages/frontend/desktop/src/views_extra/tests/inspector_outline.rs diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs index 9d3ab6d78e..6c3efdf222 100644 --- a/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/mod.rs @@ -6,10 +6,10 @@ mod tests; pub use properties::render_doc_info_dialog; use ui::{ - Context, Div, FontWeight, InteractiveElement, IntoElement, ParentElement, Stateful, + Context, Div, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Stateful, StatefulInteractiveElement, Styled, div, px, svg, }; -use ui_tokens::{FONT_SANS, icons::BULLETED_LIST}; +use ui_tokens::{FONT_SANS, ThemeMode, icons::BULLETED_LIST}; #[cfg(test)] pub(super) use super::FALLBACK_TAG_RGB; @@ -25,6 +25,67 @@ use crate::{ pub const WORKBENCH_SIDEBAR_WIDTH: f32 = 320.0; +#[derive(Clone, Copy)] +struct SwitcherStyle { + mode: ThemeMode, + track_bg: Hsla, + active_bg: Hsla, + hover_bg: Hsla, + active_text: Hsla, + inactive_text: Hsla, + active_icon: Hsla, + inactive_icon: Hsla, +} + +impl SwitcherStyle { + fn from_palette(palette: DesktopPalette) -> Self { + let mode = if palette.bg_canvas.l < 0.5 { + ThemeMode::Dark + } else { + ThemeMode::Light + }; + let tokens = crate::theme_tokens_for(mode); + Self { + mode, + track_bg: crate::theme_color( + tokens, + "--affine-v2-switch-switchBackground-background", + tokens.background_secondary, + ), + active_bg: crate::theme_color( + tokens, + "--affine-v2-switch-buttonBackground-active", + tokens.background_primary, + ), + hover_bg: crate::theme_color( + tokens, + "--affine-v2-switch-buttonBackground-hover", + tokens.hover, + ), + active_text: crate::theme_color( + tokens, + "--affine-v2-switch-fontColor-primary", + tokens.text_primary, + ), + inactive_text: crate::theme_color( + tokens, + "--affine-v2-switch-fontColor-tertiary", + tokens.text_secondary, + ), + active_icon: crate::theme_color( + tokens, + "--affine-v2-switch-iconColor-active", + tokens.text_secondary, + ), + inactive_icon: crate::theme_color( + tokens, + "--affine-v2-switch-iconColor-default", + tokens.text_secondary, + ), + } + } +} + pub(crate) fn render_doc_inspector( tab: DocInspectorTab, doc_id: Option<&str>, @@ -47,25 +108,23 @@ pub(crate) fn render_doc_inspector( palette, )) .into_any_element(), + (DocInspectorTab::Outline, Some(id)) => ui::ViewElement::new(outline::OutlinePanel { + shell: cx.entity(), + doc: id.to_owned(), + workspace: store.active_workspace().id.clone(), + scroll_key: key.into(), + 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)); - } - _ => {} + if let (DocInspectorTab::Journal, _) = (tab, doc_id) { + body = body.child(super::journals::journal_month_picker(palette, cx)); } vertical_scroll(key, body.p(px(16.0))).into_any_element() } }; + let switcher = SwitcherStyle::from_palette(palette); max_width(div().id("desktop.inspector"), ui::relative(1.0)) .snapshot("desktop.inspector", Some("desktop.shell.root")) .w(px(WORKBENCH_SIDEBAR_WIDTH)) @@ -87,33 +146,42 @@ pub(crate) fn render_doc_inspector( .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() + .items_center() + .gap(px(2.0)) + .p(px(2.0)) + .rounded(px(8.0)) + .bg(switcher.track_bg) + .child(inspector_tab_btn( + "desktop.inspector.tab.outline", + "Outline", + BULLETED_LIST.svg.as_bytes(), + tab, + DocInspectorTab::Outline, + switcher, + cx, + )) + .child(inspector_tab_btn( + "desktop.inspector.tab.info", + "Properties", + INFO_ICON_SVG, + tab, + DocInspectorTab::Info, + switcher, + cx, + )) + .child(inspector_tab_btn( + "desktop.inspector.tab.journal", + "Journal", + JOURNAL_ICON_SVG, + tab, + DocInspectorTab::Journal, + switcher, + cx, + )), + ) .child(div().flex_1()) .child( button("desktop.inspector.close", "", palette, true) @@ -138,43 +206,44 @@ fn inspector_tab_btn( icon: &'static [u8], current: DocInspectorTab, target: DocInspectorTab, - palette: DesktopPalette, + style: SwitcherStyle, cx: &mut Context, ) -> Stateful
{ - div() + let active = current == target; + let mut btn = 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)) + .gap(px(5.0)) + .h(px(28.0)) + .px(px(6.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(); - })) + .cursor_pointer(); + if active { + btn = btn + .bg(style.active_bg) + .shadow(crate::theme_shadow(style.mode, "--affine-button-shadow")) + .text_color(style.active_text); + } else { + let hover_bg = style.hover_bg; + btn = btn + .bg(ui::transparent_black()) + .text_color(style.inactive_text) + .hover(move |s| s.bg(hover_bg)); + } + btn.child(svg().data(icon).size(px(16.0)).text_color(if active { + style.active_icon + } else { + style.inactive_icon + })) + .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 { diff --git a/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs b/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs index ebdda53bc6..7d72b76aa2 100644 --- a/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs +++ b/packages/frontend/desktop/src/views_extra/right_sidebar/outline.rs @@ -1,14 +1,27 @@ -use std::rc::Rc; +use std::{cell::Cell, collections::HashMap, rc::Rc}; +use blocksuite_editor::scroll::{ScrollAxis, wheel_delta}; use ui::{ App, ElementId, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, RenderOnce, - SharedString, StatefulInteractiveElement, Styled, Window, div, px, + SharedString, StatefulInteractiveElement, Styled, Window, canvas, div, px, }; +use ui_kit::{VirtualList, VirtualWindow}; 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."; +const HEADING_ROW_HEIGHT: f32 = 28.0; +const HEADING_ROW_GAP: f32 = 10.0; +const HEADING_ROW_STRIDE: f32 = HEADING_ROW_HEIGHT + HEADING_ROW_GAP; +const HEADINGS_OVERSCAN: f32 = 360.0; + +#[derive(Clone)] +struct CachedHeading { + block_id: SharedString, + level: u8, + text: SharedString, +} #[derive(Default)] struct OutlineCache { @@ -16,12 +29,39 @@ struct OutlineCache { doc: String, rev: Option, headings: Rc<[OutlineHeading]>, + rows: Rc<[CachedHeading]>, +} + +#[derive(Default)] +struct OutlineScrollState { + offset: f32, + viewport_height: Rc>>, + headings_top: Rc>>, + non_headings_height: Rc>>, +} + +#[derive(Default)] +struct OutlineScrollMap { + entries: HashMap<(String, String), OutlineScrollState>, +} + +fn headings_window( + count: usize, + scroll_y: f32, + viewport_height: f32, + headings_top: f32, +) -> VirtualWindow { + let vis_top = (scroll_y - headings_top).max(0.0); + let vis_bottom = (scroll_y + viewport_height - headings_top).max(0.0); + let vis_height = (vis_bottom - vis_top).max(0.0); + VirtualList::fixed(count, HEADING_ROW_STRIDE).window(vis_height, vis_top, HEADINGS_OVERSCAN) } pub(super) struct OutlinePanel { pub(super) shell: Entity, pub(super) doc: String, pub(super) workspace: String, + pub(super) scroll_key: ElementId, pub(super) palette: DesktopPalette, } @@ -36,6 +76,11 @@ impl RenderOnce for OutlinePanel { app, |_, _| OutlineCache::default(), ); + let scroll_map = window.use_keyed_state( + SharedString::new_static("inspector-outline-scroll-map"), + app, + |_, _| OutlineScrollMap::default(), + ); let doc_rev = self .shell .read(app) @@ -43,38 +88,103 @@ impl RenderOnce for OutlinePanel { .store .get_doc(&self.doc) .map(|entry| entry.revision); - let headings = { + let rows = { 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) + Rc::clone(&cached.rows) } 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( + if store.sync_outline_headings( doc, &mut cache.workspace, &mut cache.doc, &mut cache.rev, &mut cache.headings, - ); - Rc::clone(&cache.headings) + ) { + cache.rows = cache + .headings + .iter() + .map(|h| CachedHeading { + block_id: SharedString::new(&h.block_id), + level: h.level, + text: SharedString::new(&h.text), + }) + .collect::>() + .into(); + } + Rc::clone(&cache.rows) }) } }; - let body = div() + + let count = rows.len(); + let headings_height = if count == 0 { + 0.0 + } else { + count as f32 * HEADING_ROW_STRIDE - HEADING_ROW_GAP + }; + let has_entry = scroll_map + .read(app) + .entries + .contains_key(&(self.workspace.clone(), self.doc.clone())); + if !has_entry { + scroll_map.update(app, |map, _| { + map.entries + .entry((self.workspace.clone(), self.doc.clone())) + .or_default(); + }); + } + let ( + raw_offset, + measured_viewport, + measured_headings_top, + measured_non_headings, + viewport_cell, + headings_top_cell, + non_headings_cell, + ) = { + let map = scroll_map.read(app); + let scroll_read = &map.entries[&(self.workspace.clone(), self.doc.clone())]; + ( + scroll_read.offset, + scroll_read.viewport_height.get(), + scroll_read.headings_top.get(), + scroll_read.non_headings_height.get(), + Rc::clone(&scroll_read.viewport_height), + Rc::clone(&scroll_read.headings_top), + Rc::clone(&scroll_read.non_headings_height), + ) + }; + + let offset = match (measured_viewport, measured_non_headings) { + (Some(vp), Some(non_headings)) => { + raw_offset.min((non_headings + headings_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 headings_top = measured_headings_top.unwrap_or(0.0); + + let mut body = div() .flex() .flex_col() - .gap(px(10.0)) + .gap(px(HEADING_ROW_GAP)) .w_full() + .p(px(16.0)) .child(section_title("Table of Contents", palette)); - if headings.is_empty() { - return body.child( + + if count == 0 { + headings_top_cell.set(None); + non_headings_cell.set(None); + body = body.child( div() .id("desktop.inspector.outline.empty") .snapshot( @@ -85,16 +195,23 @@ impl RenderOnce for OutlinePanel { .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() + } else { + let slice = headings_window(count, offset, viewport_height, headings_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)); + } + let doc_id: Rc = Rc::from(self.doc.as_str()); + let workspace_id: Rc = Rc::from(self.workspace.as_str()); + for (idx_in_slice, h) in rows[slice.visible_range.clone()].iter().enumerate() { + let index = slice.visible_range.start + idx_in_slice; + let shell = self.shell.clone(); + let doc_id = Rc::clone(&doc_id); + let workspace_id = Rc::clone(&workspace_id); + let block_id = h.block_id.clone(); + let indent = (h.level.saturating_sub(1) as f32) * 12.0; + let mut row = div() .id(ElementId::NamedInteger( SharedString::new_static("inspector-heading"), ui::hash(&block_id), @@ -103,7 +220,7 @@ impl RenderOnce for OutlinePanel { ui::snap_id!("desktop.inspector.heading.{block_id}"), Some("desktop.inspector"), ) - .h(px(28.0)) + .h(px(HEADING_ROW_HEIGHT)) .flex_shrink(0.0) .flex() .items_center() @@ -111,7 +228,7 @@ impl RenderOnce for OutlinePanel { .truncate() .rounded(px(4.0)) .cursor_pointer() - .hover(move |s| s.bg(palette.bg_hover)) + .hover(move |s| s.bg(palette.hover_overlay)) .text_size(px(12.5)) .font_weight(if h.level == 1 { FontWeight::MEDIUM @@ -122,32 +239,139 @@ impl RenderOnce for OutlinePanel { .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 + if pane.active_route().doc_id() != Some(doc_id.as_ref()) + || this.state.store.active_workspace().id != workspace_id.as_ref() { return; } let origin = this .editor_host() .workspace_origins - .get(&workspace_id) + .get(workspace_id.as_ref()) .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(), + workspace_id: workspace_id.as_ref().to_owned(), + doc_id: doc_id.as_ref().to_owned(), + block_id: block_id.as_ref().to_owned(), }, cx, ); }); }) - .child(h.text.clone()) - .into_any_element(), - ); + .child(h.text.clone()); + if index + 1 < count { + row = row.mb(px(HEADING_ROW_GAP)); + } + items = items.child(row); + } + let trailing_spacer = if slice.visible_range.end < count { + ((count - slice.visible_range.end) as f32 * HEADING_ROW_STRIDE - HEADING_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_map.clone(); + let viewport_cell = Rc::clone(&viewport_cell); + let headings_top_cell = Rc::clone(&headings_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); + headings_top_cell.set(Some(actual_top)); + viewport_cell.set(Some(actual_viewport)); + let new_range = + headings_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(); + body = body.child(items.child(measure_top)); } - body.children(rows) + + let measured_limit = Rc::new(Cell::new(0.0_f32)); + let wheel_scroll = scroll_map.clone(); + let wheel_limit = Rc::clone(&measured_limit); + let scroll_for_limit = scroll_map; + let ws_wheel = self.workspace.clone(); + let doc_wheel = self.doc.clone(); + let ws_limit = self.workspace; + let doc_limit = self.doc; + 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(); + if count > 0 { + non_headings_cell.set(Some((content_height - headings_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 { + let ws = ws_limit.clone(); + let doc = doc_limit.clone(); + window.defer(app, move |_, app| { + scroll_for_limit.update(app, |map, cx| { + if let Some(state) = map.entries.get_mut(&(ws, doc)) + && 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, |map, cx| { + let state = map + .entries + .entry((ws_wheel.clone(), doc_wheel.clone())) + .or_default(); + 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(body) + .child(measure), + ) } } diff --git a/packages/frontend/desktop/src/views_extra/tests/inspector_outline.rs b/packages/frontend/desktop/src/views_extra/tests/inspector_outline.rs new file mode 100644 index 0000000000..dfd17f512b --- /dev/null +++ b/packages/frontend/desktop/src/views_extra/tests/inspector_outline.rs @@ -0,0 +1,554 @@ +use affine_store::directory::DocMode; +use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType}; +use ui::{ + AppContext, Application, Bounds, HeadlessPlatform, MouseMoveEvent, PlatformInput, Rgba, + ScrollDelta, ScrollEvent, WindowBounds, WindowOptions, point, px, size, +}; +use ui_tokens::ThemeMode; + +use super::Shell; +use crate::{ + DesktopAppState, DesktopShellView, DocInspectorTab, palette_for, register_desktop_fonts, + theme_color, theme_tokens_for, +}; + +fn add_headings(state: &mut DesktopAppState, doc: &str, prefix: &str, count: usize) -> Vec { + let entry = state.store.docs.get_mut(doc).unwrap(); + let ids: Vec = (0..count).map(|i| format!("{prefix}-{i:04}")).collect(); + entry + .session + .structural_edit(100, |page| { + for (i, id) in ids.iter().enumerate() { + page.add_block( + id, + BlockSpec::Paragraph { + paragraph_type: if i % 4 == 0 { + ParagraphType::H1 + } else { + ParagraphType::H2 + }, + text: format!("Heading {i:04}"), + }, + 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 +} + +fn scroll_inspector(shell: &Shell, delta_y: f32) { + shell.scroll(1160.0, 400.0, delta_y); + shell.window.request_frame(); +} + +#[test] +fn inspector_outline_virtualizes_1024_headings_with_38px_stride_and_handles_resize_and_mutations() { + const MAX_MOUNTED_ROWS: usize = 42; + 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).unwrap(); + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let doc = state + .store + .create_doc("Large Outline", DocMode::Page, None, 50); + let _ids = add_headings(&mut state, &doc, "h", 1024); + state.open_doc_in_active_pane(&doc); + 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)), + ) + .unwrap() + }); + let win = platform.windows().into_iter().next().unwrap(); + let settle = || { + win.request_frame(); + platform.run_until_parked(); + win.request_frame(); + }; + let scroll_outline = |delta_y: f32| { + win.dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: point(px(1160.0), px(400.0)), + delta: ScrollDelta::Pixels(point(px(0.0), px(delta_y))), + modifiers: ui::Modifiers::default(), + touch_phase: ui::TouchPhase::Moved, + source: ui::ScrollSource::Pointer, + })); + settle(); + }; + let doc = app.update(|cx| { + handle + .update(cx, |shell, _, _| { + shell + .state + .split + .active() + .active_route() + .doc_id() + .unwrap() + .to_owned() + }) + .unwrap() + }); + let ids: Vec = (0..1024).map(|i| format!("h-{i:04}")).collect(); + let mounted = || -> Vec<(String, ui::SnapshotRect)> { + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let mut items: Vec<_> = window + .frame_snapshot() + .elements + .iter() + .filter_map(|(id, el)| { + id.strip_prefix("desktop.inspector.heading.") + .map(|block_id| (block_id.to_owned(), el.bounds)) + }) + .collect(); + items.sort_by(|a, b| a.1.y.total_cmp(&b.1.y)); + items + }) + .unwrap() + }) + }; + let contains = |id: &str| -> bool { + app.update(|cx| { + handle + .update(cx, |_, window, _| { + window.frame_snapshot().elements.contains_key(id) + }) + .unwrap() + }) + }; + let elem_bounds = |id: &str| -> ui::SnapshotRect { + app.update(|cx| { + handle + .update(cx, |_, window, _| { + window.frame_snapshot().elements[id].bounds + }) + .unwrap() + }) + }; + + settle(); + + // Top: bounded mount count and exact 38 px stride (28 px row + 10 px gap). + let top_mounted = mounted(); + assert!( + !top_mounted.is_empty() && top_mounted.len() <= MAX_MOUNTED_ROWS, + "mounted {} headings at top", + top_mounted.len() + ); + assert_eq!(top_mounted[0].0, ids[0]); + assert_eq!(top_mounted[1].0, ids[1]); + assert!((top_mounted[0].1.height - 28.0).abs() < 0.01); + assert!((top_mounted[1].1.y - top_mounted[0].1.y - 38.0).abs() < 0.01); + assert!(!contains(&format!( + "desktop.inspector.heading.{}", + ids[512] + ))); + assert!(!contains(&format!( + "desktop.inspector.heading.{}", + ids[1023] + ))); + assert!(!contains("desktop.inspector.outline.empty")); + + // Middle: top and bottom are unmounted; middle slice maintains exact 38 px stride. + scroll_outline(-19_000.0); + let mid_mounted = mounted(); + assert!( + !mid_mounted.is_empty() && mid_mounted.len() <= MAX_MOUNTED_ROWS, + "mounted {} headings at middle", + mid_mounted.len() + ); + assert!(!contains(&format!("desktop.inspector.heading.{}", ids[0]))); + assert!(!contains(&format!( + "desktop.inspector.heading.{}", + ids[1023] + ))); + assert!((mid_mounted[1].1.y - mid_mounted[0].1.y - 38.0).abs() < 0.01); + + // Bottom: scroll to end, verify last heading mounted in bounds, and click to navigate. + scroll_outline(-1_000_000.0); + let bottom_mounted = mounted(); + assert!( + !bottom_mounted.is_empty() && bottom_mounted.len() <= MAX_MOUNTED_ROWS, + "mounted {} headings at bottom", + bottom_mounted.len() + ); + assert!(!contains(&format!("desktop.inspector.heading.{}", ids[0]))); + let last_id = &ids[1023]; + let last_bounds = elem_bounds(&format!("desktop.inspector.heading.{last_id}")); + assert!(last_bounds.y + last_bounds.height <= 800.5); + win.simulate_click(point( + px(last_bounds.x + last_bounds.width / 2.0), + px(last_bounds.y + last_bounds.height / 2.0), + )); + settle(); + assert!(contains(&format!("page.block.{last_id}"))); + + // Window resize while scrolled at bottom: shrinks then expands cleanly without gaps or overflow. + for (height, max_rows) in [(460.0_f32, 32_usize), (900.0_f32, 46_usize)] { + app.update(|cx| { + handle + .update(cx, |_, window, _| { + window.resize(size(px(1280.0), px(height))); + }) + .unwrap() + }); + settle(); + scroll_outline(-1_000_000.0); + let resized = mounted(); + assert!( + !resized.is_empty() && resized.len() <= max_rows, + "mounted {} at height {height}", + resized.len() + ); + let b = elem_bounds(&format!("desktop.inspector.heading.{last_id}")); + assert!(b.y + b.height <= height + 0.5); + } + app.update(|cx| { + handle + .update(cx, |_, window, _| { + window.resize(size(px(1280.0), px(800.0))); + }) + .unwrap() + }); + settle(); + scroll_outline(-1_000_000.0); + + // Delete 900 headings -> clamps cleanly and mounts new tail heading. + app.update(|cx| { + handle + .update(cx, |shell_view, _, cx| { + let entry = shell_view.state.store.docs.get_mut(&doc).unwrap(); + let note_id = entry.note_id.clone(); + entry + .session + .structural_edit(2000, |page| { + for id in &ids[124..] { + page.delete_block_subtree(¬e_id, id, 2001)?; + } + Ok(()) + }) + .unwrap(); + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + cx.notify(); + }) + .unwrap() + }); + settle(); + let clamped_mounted = mounted(); + assert!(!clamped_mounted.is_empty() && clamped_mounted.len() <= MAX_MOUNTED_ROWS); + let new_tail = elem_bounds(&format!("desktop.inspector.heading.{}", ids[123])); + assert!(new_tail.y + new_tail.height <= 800.5); + assert!(!contains(&format!("desktop.inspector.heading.{last_id}"))); + + // Add a heading -> scrolling to bottom reveals it immediately. + app.update(|cx| { + handle + .update(cx, |shell_view, _, cx| { + let entry = shell_view.state.store.docs.get_mut(&doc).unwrap(); + entry + .session + .structural_edit(3000, |page| { + page.add_block( + "h-added", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::H1, + text: "Appended Heading".into(), + }, + Some(&entry.note_id), + None, + 3001, + )?; + Ok(()) + }) + .unwrap(); + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + cx.notify(); + }) + .unwrap() + }); + settle(); + scroll_outline(-1_000_000.0); + assert!(contains("desktop.inspector.heading.h-added")); + + // Delete all headings -> empty state placeholder renders cleanly. + app.update(|cx| { + handle + .update(cx, |shell_view, _, cx| { + let entry = shell_view.state.store.docs.get_mut(&doc).unwrap(); + let note_id = entry.note_id.clone(); + entry + .session + .structural_edit(4000, |page| { + for id in &ids[..124] { + page.delete_block_subtree(¬e_id, id, 4001)?; + } + page.delete_block_subtree(¬e_id, "h-added", 4002)?; + Ok(()) + }) + .unwrap(); + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + cx.notify(); + }) + .unwrap() + }); + settle(); + assert!(mounted().is_empty()); + assert!(contains("desktop.inspector.outline.empty")); +} + +#[test] +fn inspector_outline_keeps_independent_scroll_and_navigation_across_split_panes() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let doc_a = state.store.create_doc("Split A", DocMode::Page, None, 50); + let ids_a = add_headings(&mut state, &doc_a, "a", 1024); + let doc_b = state.store.create_doc("Split B", DocMode::Page, None, 60); + let ids_b = add_headings(&mut state, &doc_b, "b", 30); + + state.open_doc_in_active_pane(&doc_a); + state.open_split_edgeless_for_active_doc(); + state.open_doc_in_active_pane(&doc_b); + state.split.focus_pane(0); + state.inspector_tab = Some(DocInspectorTab::Outline); + + let shell = Shell::with_state(1280, state); + shell.window.request_frame(); + scroll_inspector(&shell, -1_000_000.0); + assert!(shell.contains(&format!("desktop.inspector.heading.{}", ids_a[1023]))); + assert!(!shell.contains(&format!("desktop.inspector.heading.{}", ids_a[0]))); + + // Switching to pane 1 shows doc_b's outline at top without disturbing pane 0. + shell.update(|shell_view, _, cx| { + shell_view.state.split.focus_pane(1); + cx.notify(); + }); + shell.window.request_frame(); + assert!(shell.contains(&format!("desktop.inspector.heading.{}", ids_b[0]))); + assert!(!shell.contains(&format!("desktop.inspector.heading.{}", ids_a[1023]))); + + // Clicking a heading in pane 1 navigates only pane 1. + shell.click(&format!("desktop.inspector.heading.{}", ids_b[5])); + assert!(shell.contains(&format!("page.block.{}", ids_b[5]))); + + // Switching back to pane 0 restores doc_a's bottom scroll state. + shell.update(|shell_view, _, cx| { + shell_view.state.split.focus_pane(0); + cx.notify(); + }); + shell.window.request_frame(); + assert!(shell.contains(&format!("desktop.inspector.heading.{}", ids_a[1023]))); + assert!(!shell.contains(&format!("desktop.inspector.heading.{}", ids_a[0]))); +} + +#[test] +fn inspector_outline_empty_document_shows_web_placeholder_without_headings() { + 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", mode, None, 50); + 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).unwrap(); + 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)), + ) + .unwrap() + }); + let win = platform.windows().into_iter().next().unwrap(); + win.request_frame(); + platform.run_until_parked(); + + let text = app.update(|cx| { + handle + .update(cx, |shell_view, window, _| { + let els = &window.frame_snapshot().elements; + assert!( + els.contains_key("desktop.inspector.outline.empty"), + "missing empty placeholder for {mode:?}, inspector_tab={:?}, route={:?}, total_els={}, keys={:?}", + shell_view.state.inspector_tab, + shell_view.state.split.active().active_route(), + els.len(), + els.keys().collect::>() + ); + els["desktop.inspector.outline.empty"].text.clone() + }) + .unwrap() + }); + assert_eq!( + text.as_deref(), + Some("Use headings to create a table of contents.") + ); + } +} + +#[test] +fn inspector_tab_switcher_and_outline_rows_match_web_hover_and_active_tokens() { + for theme in [ThemeMode::Light, ThemeMode::Dark] { + let palette = palette_for(theme); + let tokens = theme_tokens_for(theme); + let track_bg = theme_color( + tokens, + "--affine-v2-switch-switchBackground-background", + tokens.background_secondary, + ); + let active_bg = theme_color( + tokens, + "--affine-v2-switch-buttonBackground-active", + tokens.background_primary, + ); + let switch_hover = theme_color( + tokens, + "--affine-v2-switch-buttonBackground-hover", + tokens.hover, + ); + + 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).unwrap(); + let mut state = DesktopAppState::seed_showcase(theme, "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)), + ) + .unwrap() + }); + let win = platform.windows().into_iter().next().unwrap(); + win.request_frame(); + + let pixel = |x: u32, y: u32| -> [u8; 4] { + app.update(|cx| { + handle + .update(cx, |_, window, _| { + window.render_to_image().unwrap().get_pixel(x, y).0 + }) + .unwrap() + }) + }; + let bounds = |id: &str| -> ui::SnapshotRect { + app.update(|cx| { + handle + .update(cx, |_, window, _| { + window.frame_snapshot().elements[id].bounds + }) + .unwrap() + }) + }; + let hover_at = |x: f32, y: f32| { + win.dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { + position: point(px(x), px(y)), + ..Default::default() + })); + win.request_frame(); + }; + + // 1. Active tab keeps switch_active_bg + shadow even when hovered. + let active_tab = bounds("desktop.inspector.tab.outline"); + let ax = (active_tab.x + active_tab.width - 3.0) as u32; + let ay = (active_tab.y + 4.0) as u32; + hover_at(1278.0, 798.0); + let active_idle = pixel(ax, ay); + let expected_active = Rgba::from(active_bg); + for (i, ch) in [expected_active.r, expected_active.g, expected_active.b] + .into_iter() + .enumerate() + { + assert!( + (f32::from(active_idle[i]) - ch * 255.0).abs() <= 1.0, + "{theme:?} active tab channel {i}: {active_idle:?}" + ); + } + hover_at(ax as f32 + 0.5, ay as f32 + 0.5); + assert_eq!( + pixel(ax, ay), + active_idle, + "{theme:?}: hovering active tab must not alter its indicator" + ); + + // 2. Unchecked tab uses --affine-v2-switch-buttonBackground-hover over the track. + let unchecked_tab = bounds("desktop.inspector.tab.info"); + let ux = (unchecked_tab.x + unchecked_tab.width - 3.0) as u32; + let uy = (unchecked_tab.y + 4.0) as u32; + hover_at(1278.0, 798.0); + let unchecked_idle = pixel(ux, uy); + let expected_track = Rgba::from(track_bg); + for (i, ch) in [expected_track.r, expected_track.g, expected_track.b] + .into_iter() + .enumerate() + { + assert!( + (f32::from(unchecked_idle[i]) - ch * 255.0).abs() <= 1.0, + "{theme:?} track channel {i}: {unchecked_idle:?}" + ); + } + hover_at(ux as f32 + 0.5, uy as f32 + 0.5); + let unchecked_hovered = pixel(ux, uy); + let hover_rgba = Rgba::from(switch_hover); + for (i, ch) in [hover_rgba.r, hover_rgba.g, hover_rgba.b] + .into_iter() + .enumerate() + { + let expected = (ch * 255.0 * hover_rgba.a + + f32::from(unchecked_idle[i]) * (1.0 - hover_rgba.a)) + .round(); + assert!( + (f32::from(unchecked_hovered[i]) - expected).abs() <= 1.0, + "{theme:?} unchecked tab hover channel {i}: {unchecked_idle:?} -> {unchecked_hovered:?}" + ); + } + assert_ne!(unchecked_hovered, active_idle); + + // 3. Outline heading row hover matches layer/background/hoverOverlay (palette.hover_overlay). + let row = bounds("desktop.inspector.heading.h2-1"); + let rx = (row.x + row.width * 0.85) as u32; + let ry = (row.y + row.height / 2.0) as u32; + hover_at(1278.0, 798.0); + let row_idle = pixel(rx, ry); + hover_at(rx as f32 + 0.5, ry as f32 + 0.5); + let row_hovered = pixel(rx, ry); + let overlay = Rgba::from(palette.hover_overlay); + for (i, ch) in [overlay.r, overlay.g, overlay.b].into_iter().enumerate() { + let expected = + (ch * 255.0 * overlay.a + f32::from(row_idle[i]) * (1.0 - overlay.a)).round(); + assert!( + (f32::from(row_hovered[i]) - expected).abs() <= 1.0, + "{theme:?} outline row hover channel {i}: {row_idle:?} -> {row_hovered:?}" + ); + } + } +} diff --git a/packages/frontend/desktop/src/views_extra/tests/mod.rs b/packages/frontend/desktop/src/views_extra/tests/mod.rs index 3e8b81612e..4825fc0b9e 100644 --- a/packages/frontend/desktop/src/views_extra/tests/mod.rs +++ b/packages/frontend/desktop/src/views_extra/tests/mod.rs @@ -1,3 +1,4 @@ +mod inspector_outline; mod outline_rail; mod virtual_rows;