diff --git a/blocksuite/crates/playground/src/chrome/mod.rs b/blocksuite/crates/playground/src/chrome/mod.rs index 55e9328041..c37065d355 100644 --- a/blocksuite/crates/playground/src/chrome/mod.rs +++ b/blocksuite/crates/playground/src/chrome/mod.rs @@ -138,6 +138,7 @@ impl PlaygroundView { self.reveal_caret(effective_viewport_height, reveal_margin); self.scroll_y = self.scroll_y.clamp(0.0, self.max_scroll); self.tick_edge_auto_scroll(&layout, now_ms, window); + self.settle_outline_pin(); if self.database_readonly && !self.database_readonly_toast_shown { let vis_top = self.scroll_y; let vis_bot = self.scroll_y + effective_viewport_height; diff --git a/blocksuite/crates/playground/src/doc_panel.rs b/blocksuite/crates/playground/src/doc_panel.rs index 7eb734a2ed..b3f0b16ac3 100644 --- a/blocksuite/crates/playground/src/doc_panel.rs +++ b/blocksuite/crates/playground/src/doc_panel.rs @@ -551,6 +551,7 @@ impl PlaygroundView { self.full_width_pages.clear(); self.overlays.reset(); self.reading_anchor = None; + self.outline_pin = None; self.flow = crate::block_flow::BlockFlow::new(); self.flow.database_state.mobile_readonly = self.database_readonly; self.flow.database_state.clock_ms = self.local_calendar_now(cx).0; diff --git a/blocksuite/crates/playground/src/embedded.rs b/blocksuite/crates/playground/src/embedded.rs index 2ea485c8c3..caf604992b 100644 --- a/blocksuite/crates/playground/src/embedded.rs +++ b/blocksuite/crates/playground/src/embedded.rs @@ -213,6 +213,7 @@ impl PlaygroundView { self.last_link_popup_caret = None; self.overlays.reset(); self.reading_anchor = None; + self.outline_pin = None; self.flow = crate::block_flow::BlockFlow::new(); self.flow.database_state.mobile_readonly = self.database_readonly; self.flow.database_state.clock_ms = self.local_calendar_now(cx).0; diff --git a/blocksuite/crates/playground/src/lib.rs b/blocksuite/crates/playground/src/lib.rs index 67d88bf287..7b22f6ff30 100644 --- a/blocksuite/crates/playground/src/lib.rs +++ b/blocksuite/crates/playground/src/lib.rs @@ -23,6 +23,7 @@ mod layout_cache; mod media_picker; mod options; pub mod overlays; +mod page_outline; mod page_scroll; pub mod room_client; @@ -160,6 +161,8 @@ pub struct PlaygroundView { table_axis_ids: HashMap, pub(crate) editor_focus: ui::FocusHandle, pub(crate) reading_anchor: Option<(String, f32)>, + /// Outline entry that the last outline reveal scrolled to. + pub(crate) outline_pin: Option, pub(crate) state: DocState, pub(crate) room: Option, pub(crate) page_id: Option, @@ -353,6 +356,7 @@ impl PlaygroundView { table_axis_ids: HashMap::new(), editor_focus: cx.focus_handle(), reading_anchor: None, + outline_pin: None, page_id: None, snapshot: None, page_titles: BTreeMap::new(), @@ -783,14 +787,14 @@ pub(crate) mod tests { WindowBounds, WindowHandle, WindowOptions, audit_frame_snapshot, }; - struct Session { + pub(crate) struct Session { platform: Rc, app: ApplicationHandle, window: WindowHandle, headless: HeadlessWindow, } - fn open(width: u32, height: u32, options: PlaygroundOptions) -> Session { + pub(crate) fn open(width: u32, height: u32, options: PlaygroundOptions) -> Session { let platform = HeadlessPlatform::new(width, height, 1.0); let handle_cell: Rc>>> = Rc::new(RefCell::new(None)); @@ -827,7 +831,7 @@ pub(crate) mod tests { impl Session { /// Draw a frame through the real `Window::draw()` and read it back. - fn frame(&self) -> (FrameSnapshot, image::RgbaImage) { + pub(crate) fn frame(&self) -> (FrameSnapshot, image::RgbaImage) { self.headless.request_frame(); self.app.update(|cx| { self.window @@ -840,7 +844,7 @@ pub(crate) mod tests { }) } - fn view( + pub(crate) fn view( &self, f: impl FnOnce(&mut PlaygroundView, &mut Context) -> R, ) -> R { diff --git a/blocksuite/crates/playground/src/page_outline.rs b/blocksuite/crates/playground/src/page_outline.rs new file mode 100644 index 0000000000..146045c86b --- /dev/null +++ b/blocksuite/crates/playground/src/page_outline.rs @@ -0,0 +1,248 @@ +//! Reading position of the Page outline: the heading that the outline marks as active. + +use blocksuite_playground_doc::schema::ParagraphType; + +use crate::{PlaygroundMode, PlaygroundView, block_flow::FlowKind}; + +/// Space between the top edge of the viewport and a heading that the outline reveals. +const REVEAL_TOP: f32 = 24.0; + +/// Outline entry that a reveal scrolled to. It stays active while the page keeps the scroll +/// position that the reveal set. +pub(crate) struct OutlinePin { + /// Revealed heading, or `None` for the document title. + heading: Option, + /// Scroll position after the reveal, recorded on the first frame that applied it. + scroll_y: Option, +} + +fn is_heading(kind: &FlowKind) -> bool { + matches!( + kind, + FlowKind::Paragraph( + ParagraphType::H1 + | ParagraphType::H2 + | ParagraphType::H3 + | ParagraphType::H4 + | ParagraphType::H5 + | ParagraphType::H6 + ) + ) +} + +impl PlaygroundView { + /// Scroll the page to an outline entry: the title (`None`) to the top, a heading to + /// 24 px below the top edge. The entry stays active until the page scrolls again. + pub fn reveal_outline_heading(&mut self, heading: Option, cx: &mut ui::Context) { + self.editor.reveal = false; + self.page_scroll_fling = None; + match &heading { + Some(id) => self.reading_anchor = Some((id.clone(), REVEAL_TOP)), + None => { + self.reading_anchor = None; + self.scroll_y = 0.0; + } + } + self.outline_pin = Some(OutlinePin { + heading, + scroll_y: None, + }); + cx.notify(); + } + + /// Heading at the reading position of the Page viewport, as BlockSuite's outline finds + /// it: the last laid-out heading whose center lies above the viewport center plus its + /// own height. `None` means the document title, above the first heading. + pub fn active_outline_heading(&self) -> Option<&str> { + if self.mode != PlaygroundMode::Page { + return None; + } + let (_, layout) = self.layout.as_ref()?; + if let Some(pin) = &self.outline_pin + && pin.scroll_y.is_none_or(|y| y == self.scroll_y) + { + match pin.heading.as_deref() { + None => return None, + Some(id) if layout.block(id).is_some() => return Some(id), + Some(_) => {} + } + } + let viewport_height = self.window_size.1 - self.topbar_height(); + let center = self.scroll_y + viewport_height / 2.0; + let mut active = None; + for block in &layout.blocks { + // A later block whose top is a viewport height below the center is past it, + // unless it is taller than two viewports. + if block.y >= center + viewport_height { + break; + } + let height = block.body.height; + if is_heading(&block.body.kind) && block.y + height / 2.0 < center + height { + active = Some(block.block_id.as_str()); + } + } + active + } + + /// Record where a reveal landed, and release it once the page scrolls elsewhere. + pub(crate) fn settle_outline_pin(&mut self) { + let Some(pin) = &mut self.outline_pin else { + return; + }; + match pin.scroll_y { + None => pin.scroll_y = Some(self.scroll_y), + Some(y) if y != self.scroll_y => self.outline_pin = None, + Some(_) => {} + } + } +} + +#[cfg(test)] +mod tests { + use blocksuite_playground_doc::schema::BlockSpec; + + use super::ParagraphType; + use crate::{ + HOME_PAGE_ID, PlaygroundOptions, + room_client::DocState, + tests::{Session, open}, + }; + + /// Headings `h0..h4` after 40 intro paragraphs: `h0` to `h2` and `h3` are 40 paragraphs + /// apart, `h4` follows `h3` directly. + fn outline_doc() -> DocState { + let mut state = DocState::new("outline", 44).unwrap(); + state + .workspace + .create_page(HOME_PAGE_ID, "Guide", 1) + .unwrap(); + let page = state.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + let mut now = 1; + let mut add = |id: String, spec: BlockSpec, parent: Option<&str>| { + now += 1; + page.add_block(&id, spec, parent, None, now).unwrap(); + }; + add( + "root".into(), + BlockSpec::Page { + title: "Guide".into(), + }, + None, + ); + add("note".into(), BlockSpec::Note { xywh: None }, Some("root")); + for line in 0..40 { + add( + format!("intro-{line}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: format!("Intro line {line}."), + }, + Some("note"), + ); + } + for section in 0..5 { + add( + format!("h{section}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::H2, + text: format!("Section {section}"), + }, + Some("note"), + ); + if section == 3 { + continue; + } + for line in 0..40 { + add( + format!("p{section}-{line}"), + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: format!("Line {line} of section {section}."), + }, + Some("note"), + ); + } + } + page.stop_capturing().unwrap(); + state + } + + fn outline_session() -> Session { + let session = open(1280, 800, PlaygroundOptions::default()); + session.view(|view, cx| view.set_document(outline_doc(), cx)); + session.frame(); + session + } + + fn heading_box(session: &Session, id: &str) -> (f32, f32) { + session.view(|view, _| { + let layout = view.flow_layout().unwrap(); + let block = layout.block(id).unwrap(); + (block.y, block.body.height) + }) + } + + fn scroll_to(session: &Session, y: f32) -> Option { + session.view(|view, _| view.scroll_y = y); + session.frame(); + session.view(|view, _| view.active_outline_heading().map(str::to_owned)) + } + + #[test] + fn active_outline_heading_switches_when_the_heading_center_crosses_the_viewport_center() { + let session = outline_session(); + let viewport_height = session.view(|view, _| view.window_size.1 - view.topbar_height()); + assert_eq!(scroll_to(&session, 0.0), None); + for id in ["h0", "h1", "h2"] { + let (y, height) = heading_box(&session, id); + // Active once `y + height / 2 < scroll + viewport / 2 + height`. + let threshold = y - height / 2.0 - viewport_height / 2.0; + let before = scroll_to(&session, (threshold - 1.0).floor()); + assert_ne!(before.as_deref(), Some(id), "{id} before its threshold"); + assert_eq!( + scroll_to(&session, (threshold + 1.0).ceil()).as_deref(), + Some(id), + "{id} after its threshold" + ); + } + } + + #[test] + fn outline_reveal_keeps_its_entry_active_until_the_page_scrolls() { + let session = outline_session(); + let active = || session.view(|view, _| view.active_outline_heading().map(str::to_owned)); + + // `h4` lies right below `h3`, so the geometry alone marks `h4` after the jump. + session.view(|view, cx| view.reveal_outline_heading(Some("h3".into()), cx)); + session.frame(); + let (h3_y, _) = heading_box(&session, "h3"); + assert_eq!(session.view(|view, _| view.scroll_y), (h3_y - 24.0).round()); + assert_eq!(active().as_deref(), Some("h3")); + session.frame(); + assert_eq!( + active().as_deref(), + Some("h3"), + "an idle frame keeps the entry" + ); + let scrolled = session.view(|view, _| view.scroll_y + 1.0); + assert_eq!(scroll_to(&session, scrolled).as_deref(), Some("h4")); + + session.view(|view, cx| view.reveal_outline_heading(None, cx)); + session.frame(); + assert_eq!(session.view(|view, _| view.scroll_y), 0.0); + assert_eq!(active(), None); + + // A revealed heading that has no layout any more gives way to the geometry. + session.view(|view, cx| view.reveal_outline_heading(Some("h1".into()), cx)); + session.frame(); + assert_eq!(active().as_deref(), Some("h1")); + session.view(|view, cx| { + view.edit_document(cx, |doc| { + let page = doc.workspace.ensure_page(HOME_PAGE_ID).unwrap(); + page.delete_block_subtree("note", "h1", 900).unwrap(); + }); + }); + session.frame(); + assert_eq!(active().as_deref(), Some("h0")); + } +} diff --git a/packages/frontend/desktop/src/editor_host/mod.rs b/packages/frontend/desktop/src/editor_host/mod.rs index b350246a60..52bfb58a93 100644 --- a/packages/frontend/desktop/src/editor_host/mod.rs +++ b/packages/frontend/desktop/src/editor_host/mod.rs @@ -636,6 +636,21 @@ impl DesktopEditorHost { self.pane_editors.get(&pane_id).map(|m| m.entity.clone()) } + /// Heading at the reading position of the Page editor of `pane_id` while it shows + /// `doc_id`. `None` means the document title, above the first heading. + pub(crate) fn active_outline_heading<'a>( + &self, + pane_id: PaneId, + doc_id: &str, + cx: &'a ui::App, + ) -> Option<&'a str> { + let mounted = self.pane_editors.get(&pane_id)?; + if mounted.doc_id != doc_id { + return None; + } + mounted.entity.read(cx).active_outline_heading() + } + /// Return the mounted `Entity` for `PeekView`, if any. pub fn peek_entity(&self) -> Option> { self.peek_editor.as_ref().map(|m| m.entity.clone()) diff --git a/packages/frontend/desktop/src/views_extra/outline_rail.rs b/packages/frontend/desktop/src/views_extra/outline_rail.rs index 5fa084b090..042345e57c 100644 --- a/packages/frontend/desktop/src/views_extra/outline_rail.rs +++ b/packages/frontend/desktop/src/views_extra/outline_rail.rs @@ -4,11 +4,12 @@ use std::rc::Rc; use blocksuite_editor::scroll::{ScrollAxis, wheel_delta}; use ui::{ - App, BoxShadow, Context, ElementId, Entity, InteractiveElement, IntoElement, ParentElement, - RenderOnce, SharedString, StatefulInteractiveElement, Styled, ViewElement, Window, div, hsla, - px, + App, BoxShadow, Context, ElementId, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, + ParentElement, RenderOnce, SharedString, StatefulInteractiveElement, Styled, ViewElement, + Window, div, hsla, prelude::FluentBuilder as _, px, }; use ui_kit::VirtualList; +use ui_tokens::ThemeMode; use crate::{ DesktopFlexExt, DesktopPalette, @@ -18,13 +19,18 @@ use crate::{ }; const ROW_HEIGHT: f32 = 24.0; +/// Space of one tick while all ticks fit (`flex: 1 1 16px` in Web). const TICK_HEIGHT: f32 = 16.0; +/// Smallest tick space: ticks shrink to their own height before the rail clips them. +const TICK_MIN_HEIGHT: f32 = 2.0; const PANEL_PADDING: f32 = 8.0; const PANEL_WIDTH: f32 = 200.0; /// Rows mounted above and below the visible part of the heading list. const OVERSCAN_ROWS: f32 = 2.0; -/// Width of the tick column, equal to the widest tick. +/// Width of the tick column, equal to the active tick. const RAIL_WIDTH: f32 = 24.0; +/// Width of a tick that is not active. +const TICK_WIDTH: f32 = 20.0; /// Distance from the pane edge to the tick column (`right: 22px` in Web). const RAIL_INSET: f32 = 22.0; /// Distance from the top of the pane body to the rail (`top: 256px - 52px` in Web). @@ -120,9 +126,45 @@ impl RenderOnce for OutlineRail { }) } }; + // Like BlockSuite's outline viewer, a page without headings shows no rail, even with + // a title. if headings.is_empty() { return ui::Empty.into_any_element(); } + let shell = self.shell.read(app); + // A titled page lists its title first, as the root entry. + let title = shell.state.store.get_doc(&self.doc).and_then(|entry| { + let text = entry.meta.title.trim(); + let root = entry.snapshot.root.as_ref()?; + (!text.is_empty()).then(|| (root.id.clone(), SharedString::from(text.to_owned()))) + }); + let first_heading = usize::from(title.is_some()); + let count = first_heading + headings.len(); + let active = match shell + .editor_host() + .active_outline_heading(self.pane, &self.doc, app) + { + None => title.is_some().then_some(0), + Some(id) => headings + .iter() + .position(|heading| heading.block_id == id) + .map(|index| first_heading + index), + }; + let colors = RailColors::new(shell.state.theme); + + let list = VirtualList::fixed(count, ROW_HEIGHT); + let list_height = list + .total_height() + .min(self.height - 2.0 * PANEL_PADDING - 2.0); + let max_scroll = list.total_height() - list_height; + let scroll = window.use_keyed_state( + ElementId::NamedInteger( + SharedString::new_static("desktop.outline.rail.scroll"), + ui::hash(&(&self.workspace, self.pane, &self.doc)), + ), + app, + |_, _| 0.0_f32, + ); let key = format!( "desktop.outline.rail.{}/{}/{}", self.workspace, self.pane, self.doc @@ -136,7 +178,19 @@ impl RenderOnce for OutlineRail { .snapshot(format_args!("desktop.outline.rail.{}", self.pane), None) .flex() .items_start(); + // Opening the panel centers the active entry in the list, as `scrollIntoView` does in + // Web. While the panel stays open, only the wheel moves the list. + let reveal = active.map(|index| (index as f32 + 0.5) * ROW_HEIGHT - list_height / 2.0); + let reveal_scroll = scroll.clone(); rail.interactivity().on_hover(move |inside, _, app| { + if *inside + && !*hovered.read(app) + && let Some(reveal) = reveal + { + reveal_scroll.update(app, |offset, _| { + *offset = ScrollAxis::new(reveal, max_scroll).offset; + }); + } hovered.update(app, |hovered, cx| { *hovered = *inside; cx.notify(); @@ -168,19 +222,6 @@ impl RenderOnce for OutlineRail { .collect(), ); - let list = VirtualList::fixed(headings.len(), ROW_HEIGHT); - let list_height = list - .total_height() - .min(self.height - 2.0 * PANEL_PADDING - 2.0); - let max_scroll = list.total_height() - list_height; - let scroll = window.use_keyed_state( - ElementId::NamedInteger( - SharedString::new_static("desktop.outline.rail.scroll"), - ui::hash(&(&self.workspace, self.pane, &self.doc)), - ), - app, - |_, _| 0.0_f32, - ); let stored_offset = *scroll.read(app); let offset = ScrollAxis::new(stored_offset, max_scroll).offset; if offset != stored_offset { @@ -193,12 +234,26 @@ impl RenderOnce for OutlineRail { .flex() .flex_col() .w_full(); - for heading in &headings[slice.visible_range] { + for index in slice.visible_range { + let (block, target, text, indent) = match (index.checked_sub(first_heading), &title) + { + (None, Some((root, text))) => (root.clone(), None, text.clone(), 0), + (None, None) => continue, + (Some(heading), _) => { + let heading = &headings[heading]; + ( + heading.block_id.clone(), + Some(heading.block_id.clone()), + SharedString::from(heading.text.clone()), + heading.level.saturating_sub(1), + ) + } + }; + let is_active = active == Some(index); let shell = self.shell.clone(); let workspace = self.workspace.clone(); let doc = self.doc.clone(); let pane = self.pane; - let block = heading.block_id.clone(); let mut row = super::button( ElementId::NamedInteger( SharedString::new_static("outline-rail-heading"), @@ -212,11 +267,14 @@ impl RenderOnce for OutlineRail { ui::snap_id!("desktop.outline.rail.heading.{pane}.{block}"), None, ) + .snapshot_focused(is_active) .h(px(ROW_HEIGHT)) .min_h(px(ROW_HEIGHT)) .w_full() - .pl(px(6.0 + 10.0 * f32::from(heading.level.saturating_sub(1)))) - .child(div().min_w_0().truncate().child(heading.text.clone())) + .pl(px(6.0 + 10.0 * f32::from(indent))) + .font_weight(FontWeight::SEMIBOLD) + .when(is_active, |row| row.text_color(colors.active_text)) + .child(div().min_w_0().truncate().child(text)) .on_click(move |_, _, app| { shell.update(app, |shell, cx| { if shell.state.store.active_workspace().id != workspace { @@ -232,7 +290,7 @@ impl RenderOnce for OutlineRail { if let Some(editor) = shell.editor_host().pane_entity(pane) { shell.state.split.focus_pane(index); editor.update(cx, |view, cx| { - view.reveal_linked_block(block.clone(), cx); + view.reveal_outline_heading(target.clone(), cx); }); cx.notify(); } @@ -268,17 +326,23 @@ impl RenderOnce for OutlineRail { } else { let mut ticks = div().w(px(RAIL_WIDTH)).flex().flex_col(); ticks.style().align_items = Some(ui::AlignItems::FlexEnd); - let tick_limit = (self.height / TICK_HEIGHT).floor().clamp(1.0, 16.0) as usize; - ticks.children(headings.iter().take(tick_limit).map(|heading| { - let width = 24.0 - 4.0 * f32::from(heading.level.clamp(1, 3) - 1); - div().h(px(TICK_HEIGHT)).flex().items_center().child( - div() - .w(px(width)) - .h(px(2.0)) - .rounded(px(1.0)) - .bg(palette.text_muted) - .opacity(0.35), - ) + let (pitch, shown) = tick_layout(count, self.height); + let pane = self.pane; + ticks.children((0..shown).map(|index| { + let is_active = active == Some(index); + let tick = div() + .w(px(if is_active { RAIL_WIDTH } else { TICK_WIDTH })) + .h(px(2.0)) + .rounded(px(1.0)) + .bg(if is_active { + colors.active_tick + } else { + colors.tick + }) + .when(is_active, |tick| { + tick.snapshot(ui::snap_id!("desktop.outline.rail.tick.{pane}"), None) + }); + div().h(px(pitch)).flex().items_center().child(tick) })) }; @@ -290,3 +354,416 @@ impl RenderOnce for OutlineRail { .into_any_element() } } + +/// Space of each tick and the number of ticks that fit in `height`. Ticks keep 16 px each +/// while they fit, then shrink alike down to their own 2 px height, and the rail clips the +/// rest, as the `flex: 1 1 16px` ticks do in Web. +fn tick_layout(count: usize, height: f32) -> (f32, usize) { + let pitch = (height / count as f32).clamp(TICK_MIN_HEIGHT, TICK_HEIGHT); + (pitch, ((height / pitch).floor() as usize).min(count)) +} + +const TICK_TOKEN: &str = "--affine-black-10"; +const ACTIVE_TEXT_TOKEN: &str = "--affine-v2-text-emphasis"; + +/// Theme colors of the rail that the desktop palette does not carry. +#[derive(Clone, Copy)] +struct RailColors { + /// `--affine-black-10` + tick: Hsla, + /// `--affine-text-primary-color` + active_tick: Hsla, + /// `text/emphasis`, the color of the active entry in the panel. + active_text: Hsla, +} + +impl RailColors { + fn new(mode: ThemeMode) -> Self { + let tokens = crate::theme_tokens_for(mode); + let color = |name, fallback| crate::rgba_to_hsla(tokens.color(name).unwrap_or(fallback)); + Self { + tick: color(TICK_TOKEN, tokens.border), + active_tick: crate::rgba_to_hsla(tokens.text_primary), + active_text: color(ACTIVE_TEXT_TOKEN, tokens.text_emphasis), + } + } +} + +#[cfg(test)] +mod tests { + #![cfg(not(target_family = "wasm"))] + use affine_store::directory::DocMode; + use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType}; + use ui::{ + AppContext, Application, ApplicationHandle, Bounds, Context, HeadlessPlatform, + HeadlessWindow, PlatformInput, Window, WindowBounds, WindowHandle, WindowOptions, point, + px, size, + }; + use ui_tokens::ThemeMode; + + use super::{ACTIVE_TEXT_TOKEN, TICK_HEIGHT, TICK_TOKEN, tick_layout}; + use crate::{DesktopAppState, DesktopShellView, register_desktop_fonts, split_view::PaneId}; + + const HEIGHT: f32 = 800.0; + + struct Shell { + app: ApplicationHandle, + handle: WindowHandle, + window: HeadlessWindow, + } + + impl Shell { + fn new(width: u32, state: DesktopAppState) -> Self { + let platform = HeadlessPlatform::new(width, HEIGHT as u32, 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(width as f32), px(HEIGHT)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + .unwrap() + }); + let window = platform.windows().into_iter().next().unwrap(); + 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).unwrap()) + } + + fn element(&self, id: &str) -> Option { + self.update(|_, window, _| window.frame_snapshot().elements.get(id).cloned()) + } + + fn center(&self, id: &str) -> (f32, f32) { + let b = self.element(id).unwrap_or_else(|| panic!("{id}")).bounds; + (b.x + b.width / 2.0, b.y + b.height / 2.0) + } + + fn click(&self, id: &str) { + let (x, y) = self.center(id); + self.window.simulate_click(point(px(x), px(y))); + self.window.request_frame(); + } + + fn hover(&self, x: f32, y: f32) { + self.window + .dispatch_input(PlatformInput::MouseMove(ui::MouseMoveEvent { + position: point(px(x), px(y)), + ..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(); + } + + /// Scrolls the page of the pane at `index`, left of its outline rail. + fn scroll_page(&self, index: usize, delta: f32) { + let pane = self + .element(&format!("desktop.pane.{index}")) + .unwrap() + .bounds; + self.scroll(pane.x + pane.width / 3.0, pane.y + 400.0, delta); + } + + fn active_heading(&self, pane: PaneId, doc: &str) -> Option { + self.update(|shell, _, cx| { + shell + .editor_host() + .active_outline_heading(pane, doc, cx) + .map(str::to_owned) + }) + } + + /// Index of the 24 x 2 px active tick in the collapsed rail of `pane`. + fn active_tick(&self, pane: PaneId, count: usize) -> Option { + let tick = self.element(&format!("desktop.outline.rail.tick.{pane}"))?; + assert_eq!((tick.bounds.width, tick.bounds.height), (24.0, 2.0)); + let rail = self + .element(&format!("desktop.outline.rail.{pane}")) + .unwrap() + .bounds; + let (pitch, _) = tick_layout(count, rail.height.max(TICK_HEIGHT)); + Some(((tick.bounds.y - rail.y) / pitch) as usize) + } + + fn focused_rows(&self, pane: PaneId) -> Vec { + let prefix = format!("desktop.outline.rail.heading.{pane}."); + self.update(|_, window, _| { + let mut rows: Vec = window + .frame_snapshot() + .elements + .iter() + .filter(|(id, row)| row.focused && id.starts_with(&prefix)) + .map(|(id, _)| id[prefix.len()..].to_owned()) + .collect(); + rows.sort(); + rows + }) + } + } + + /// Creates a page with `lines` intro paragraphs, then `sections` H2 headings + /// `-h`, each followed by `lines` paragraphs. + fn add_sections( + state: &mut DesktopAppState, + title: &str, + sections: usize, + lines: usize, + ) -> (String, Vec) { + let doc = state.store.create_doc(title, DocMode::Page, None, 10); + let entry = state.store.docs.get_mut(&doc).unwrap(); + let ids: Vec = (0..sections).map(|i| format!("{doc}-h{i}")).collect(); + let paragraphs = |owner: &str| -> Vec<_> { + (0..lines) + .map(|line| { + ( + format!("{owner}-p{line}"), + ParagraphType::Text, + format!("Line {line} of {owner}."), + ) + }) + .collect() + }; + let mut blocks = paragraphs(&format!("{doc}-intro")); + for (i, id) in ids.iter().enumerate() { + blocks.push((id.clone(), ParagraphType::H2, format!("Section {i}"))); + blocks.extend(paragraphs(id)); + } + entry + .session + .structural_edit(100, |page| { + for (now, (id, paragraph_type, text)) in (101..).zip(blocks) { + page.add_block( + id, + BlockSpec::Paragraph { + paragraph_type, + text, + }, + Some(&entry.note_id), + None, + now, + )?; + } + Ok(()) + }) + .unwrap(); + entry.snapshot = entry.session.read_page_snapshot().unwrap(); + entry.revision = entry.session.revision(); + (doc, ids) + } + + fn root_id(state: &DesktopAppState, doc: &str) -> String { + state.store.docs[doc] + .snapshot + .root + .as_ref() + .unwrap() + .id + .clone() + } + + #[test] + fn rail_color_tokens_exist_in_both_themes() { + for mode in [ThemeMode::Light, ThemeMode::Dark] { + let tokens = crate::theme_tokens_for(mode); + for name in [TICK_TOKEN, ACTIVE_TEXT_TOKEN] { + assert!(tokens.color(name).is_some(), "{name} in {mode:?}"); + } + } + } + + #[test] + fn tick_layout_keeps_16_pixel_ticks_then_shrinks_them_to_2_pixels_and_clips() { + for (count, height, expected) in [ + (4, 400.0, (16.0, 4)), + (25, 400.0, (16.0, 25)), + (50, 400.0, (8.0, 50)), + (512, 400.0, (2.0, 200)), + ] { + assert_eq!(tick_layout(count, height), expected, "{count} ticks"); + } + } + + #[test] + fn split_panes_of_one_page_track_their_own_active_heading() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-03"); + let (doc, ids) = add_sections(&mut state, "Outline", 8, 30); + state.open_doc_in_active_pane(&doc); + state.open_doc_in_split(&doc); + let panes: Vec = state.split.panes.iter().map(|pane| pane.id).collect(); + assert_eq!(panes.len(), 2); + let app = Shell::new(2200, state); + let count = ids.len() + 1; + for pane in &panes { + assert_eq!( + app.active_heading(*pane, &doc), + None, + "pane {pane} at the top" + ); + assert_eq!( + app.active_tick(*pane, count), + Some(0), + "title tick of {pane}" + ); + } + + app.scroll_page(0, -3000.0); + let left = app.active_heading(panes[0], &doc).expect("left heading"); + let left_index = ids.iter().position(|id| *id == left).unwrap(); + assert!(left_index > 0, "{left}"); + assert_eq!(app.active_tick(panes[0], count), Some(left_index + 1)); + assert_eq!(app.active_heading(panes[1], &doc), None); + assert_eq!(app.active_tick(panes[1], count), Some(0)); + + app.scroll_page(1, -1200.0); + let right = app.active_heading(panes[1], &doc).expect("right heading"); + assert_ne!(right, left); + let right_index = ids.iter().position(|id| *id == right).unwrap(); + assert_eq!(app.active_tick(panes[1], count), Some(right_index + 1)); + assert_eq!(app.active_heading(panes[0], &doc), Some(left)); + } + + #[test] + fn outline_rows_reveal_their_heading_or_the_page_top_and_mark_it_active() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-03"); + let (doc, ids) = add_sections(&mut state, "Outline", 6, 30); + state.open_doc_in_active_pane(&doc); + let root = root_id(&state, &doc); + let pane = state.split.active().id; + let app = Shell::new(1280, state); + let row = |id: &str| format!("desktop.outline.rail.heading.{pane}.{id}"); + let (x, y) = app.center(&format!("desktop.outline.rail.{pane}")); + app.hover(x, y); + assert_eq!(app.focused_rows(pane), vec![root.clone()]); + + app.click(&row(&ids[4])); + assert_eq!( + app.active_heading(pane, &doc).as_deref(), + Some(ids[4].as_str()) + ); + assert_eq!(app.focused_rows(pane), vec![ids[4].clone()]); + assert!(app.element(&format!("page.block.{}", ids[4])).is_some()); + + app.click(&row(&root)); + assert_eq!(app.active_heading(pane, &doc), None); + assert_eq!(app.focused_rows(pane), vec![root]); + assert!(app.element("page.title_block").is_some()); + } + + #[test] + fn opening_the_panel_centers_the_active_row_and_the_wheel_moves_it_freely() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-03"); + let (doc, ids) = add_sections(&mut state, "Outline", 60, 2); + state.open_doc_in_active_pane(&doc); + let pane = state.split.active().id; + let app = Shell::new(1280, state); + app.scroll_page(0, -1.0e6); + let active = app.active_heading(pane, &doc).expect("heading at the end"); + let row = format!("desktop.outline.rail.heading.{pane}.{active}"); + assert!(app.element(&row).is_none()); + + let (x, y) = app.center(&format!("desktop.outline.rail.{pane}")); + app.hover(x, y); + let panel = app + .element(&format!("desktop.outline.rail.panel.{pane}")) + .unwrap() + .bounds; + let shown = app + .element(&row) + .expect("active row in the open panel") + .bounds; + assert!(shown.y >= panel.y && shown.y + shown.height <= panel.y + panel.height); + assert_eq!(app.focused_rows(pane), vec![active.clone()]); + + // The wheel scrolls the open list away from the active row and the list stays there. + let (px_, py_) = (panel.x + panel.width / 2.0, panel.y + panel.height / 2.0); + app.scroll(px_, py_, 1.0e6); + let first = format!("desktop.outline.rail.heading.{pane}.{}", ids[0]); + assert!(app.element(&first).is_some()); + assert!(app.element(&row).is_none()); + app.hover(px_, py_ + 1.0); + assert!( + app.element(&row).is_none(), + "an open panel keeps its scroll" + ); + } + + #[test] + fn outline_rail_needs_a_heading_and_lists_a_nonempty_title_first() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-03"); + let (titled, titled_ids) = add_sections(&mut state, "Outline", 3, 30); + let (untitled, untitled_ids) = add_sections(&mut state, "", 3, 30); + let (bare, _) = add_sections(&mut state, "Only a title", 0, 4); + assert_eq!(state.store.docs[&untitled].meta.title, ""); + let titled_rows = [vec![root_id(&state, &titled)], titled_ids].concat(); + let pane = state.split.active().id; + let app = Shell::new(1280, state); + let rail = format!("desktop.outline.rail.{pane}"); + // Rows, ticks, and the tick of the page top for each page. + for (doc, rows, top_tick) in [ + (&titled, titled_rows, Some(0)), + (&untitled, untitled_ids, None), + (&bare, Vec::new(), None), + ] { + app.update(|shell, _, cx| { + shell.state.open_doc_in_active_pane(doc); + cx.notify(); + }); + app.hover(1.0, 1.0); + assert_eq!( + app.element(&rail).is_some(), + !rows.is_empty(), + "rail of {doc}" + ); + if rows.is_empty() { + continue; + } + assert_eq!( + app.active_tick(pane, rows.len()), + top_tick, + "ticks of {doc}" + ); + let (x, y) = app.center(&rail); + app.hover(x, y); + let prefix = format!("desktop.outline.rail.heading.{pane}."); + let shown: Vec = app.update(|_, window, _| { + let snapshot = window.frame_snapshot(); + let mut shown: Vec<_> = snapshot + .elements + .iter() + .filter(|(id, _)| id.starts_with(&prefix)) + .map(|(id, row)| (row.bounds.y, id[prefix.len()..].to_owned())) + .collect(); + shown.sort_by(|a, b| a.0.total_cmp(&b.0)); + shown.into_iter().map(|(_, id)| id).collect() + }); + assert_eq!(shown, rows, "rows of {doc}"); + } + } +}