From 9cc5f74559a043df6024bbdc7ba41e0090143078 Mon Sep 17 00:00:00 2001 From: DarkSky <25152247+darkskygit@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:48:36 +0900 Subject: [PATCH] fix(desktop): restore search navigation and peek layout --- packages/frontend/client/src/nav/mod.rs | 72 ++- packages/frontend/desktop/src/peek_view.rs | 540 ++++++++++------ packages/frontend/desktop/src/quick_search.rs | 599 ----------------- .../frontend/desktop/src/quick_search/mod.rs | 392 +++++++++++ .../desktop/src/quick_search/modal.rs | 606 ++++++++++++++++++ .../desktop/src/workbench/search_input.rs | 247 ++++++- 6 files changed, 1614 insertions(+), 842 deletions(-) delete mode 100644 packages/frontend/desktop/src/quick_search.rs create mode 100644 packages/frontend/desktop/src/quick_search/mod.rs create mode 100644 packages/frontend/desktop/src/quick_search/modal.rs diff --git a/packages/frontend/client/src/nav/mod.rs b/packages/frontend/client/src/nav/mod.rs index e9f7c6a9ae..8ac74b0e00 100644 --- a/packages/frontend/client/src/nav/mod.rs +++ b/packages/frontend/client/src/nav/mod.rs @@ -5,6 +5,7 @@ pub mod breadcrumb; use std::collections::HashSet; +use std::sync::atomic::{AtomicU64, Ordering}; use serde::{Deserialize, Serialize}; @@ -19,6 +20,8 @@ pub const NAV_HISTORY_CAPACITY: usize = 128; /// Schema version tag embedded in Web `history.state` JSON payloads. pub const WEB_HISTORY_STATE_SCHEMA_VERSION: u32 = 1; +static NEXT_VISIT_SEQ: AtomicU64 = AtomicU64::new(1); + /// Isolation boundary: provenance walks stop immediately whenever `Scope` changes. #[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -119,7 +122,7 @@ pub enum LocationChoice { } /// One entry in the per-pane navigation history stack. -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NavEntry { pub seq: u64, @@ -128,8 +131,33 @@ pub struct NavEntry { pub origin: Origin, #[serde(default, skip_serializing_if = "Option::is_none")] pub pick: Option, + #[serde(skip)] + visit_seq: u64, } +impl NavEntry { + /// Order this visit across pane histories. Decoded entries use their original sequence. + pub fn visit_seq(&self) -> u64 { + if self.visit_seq == 0 { + self.seq + } else { + self.visit_seq + } + } +} + +impl PartialEq for NavEntry { + fn eq(&self, other: &Self) -> bool { + self.seq == other.seq + && self.scope == other.scope + && self.target == other.target + && self.origin == other.origin + && self.pick == other.pick + } +} + +impl Eq for NavEntry {} + /// Schema-versioned envelope for serializing a [`NavEntry`] into Web `history.state`. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -196,8 +224,7 @@ impl NavHistory { return None; } self.entries.truncate(cur); - self.cursor = Some(cur - 1); - self.entries.get(cur - 1) + self.back() } /// Replace the current history entry in place without increasing stack depth. @@ -216,6 +243,7 @@ impl NavHistory { target, origin, pick, + visit_seq: NEXT_VISIT_SEQ.fetch_add(1, Ordering::Relaxed), }; if let Some(cur) = self.cursor && cur < self.entries.len() @@ -252,6 +280,7 @@ impl NavHistory { target, origin, pick, + visit_seq: NEXT_VISIT_SEQ.fetch_add(1, Ordering::Relaxed), }); if self.entries.len() > NAV_HISTORY_CAPACITY { @@ -268,8 +297,7 @@ impl NavHistory { if cur == 0 { return None; } - self.cursor = Some(cur - 1); - self.entries.get(cur - 1) + self.visit_at(cur - 1) } /// Step forward in chronological history. @@ -278,8 +306,14 @@ impl NavHistory { if cur + 1 >= self.entries.len() { return None; } - self.cursor = Some(cur + 1); - self.entries.get(cur + 1) + self.visit_at(cur + 1) + } + + fn visit_at(&mut self, index: usize) -> Option<&NavEntry> { + let entry = self.entries.get_mut(index)?; + self.cursor = Some(index); + entry.visit_seq = NEXT_VISIT_SEQ.fetch_add(1, Ordering::Relaxed); + Some(entry) } /// Remove every history entry matching `(scope, target)` while preserving the original @@ -390,6 +424,7 @@ impl NavHistory { target: fallback_target.clone(), origin: Origin::Direct(DirectKind::External), pick: None, + visit_seq: 0, }; let Ok(envelope) = serde_json::from_str::(raw) else { @@ -418,6 +453,29 @@ impl NavHistory { mod tests { use super::*; + #[test] + fn visits_keep_web_history_state_and_local_sequence() { + let scope = Scope::new("u1", "https://app.affine.pro", "ws1"); + let target = NavTarget::Doc("doc".into()); + let origin = Origin::Direct(DirectKind::Link); + let mut history = NavHistory::new(); + let seq = history.push(scope.clone(), target.clone(), origin.clone(), None); + let first = history.current().unwrap().clone(); + let json = history.encode_current_web_state_json().unwrap(); + let mut other = NavHistory::default(); + other.replace_current(scope.clone(), NavTarget::Home, origin.clone(), None); + assert!(other.current().unwrap().visit_seq() > first.visit_seq()); + + history.push(scope.clone(), NavTarget::Home, origin, None); + assert!(history.back().unwrap().visit_seq() > other.current().unwrap().visit_seq()); + assert_eq!(history.entry_by_seq(seq), Some(&first)); + assert_eq!(history.encode_current_web_state_json().unwrap(), json); + assert!(!json.contains("visitSeq")); + let decoded = NavHistory::decode_web_state_json(&json, scope, target, &HashSet::new()); + assert_eq!(decoded, first); + assert_eq!(decoded.visit_seq(), seq); + } + #[test] fn remove_target_purges_all_matching_entries_and_keeps_seqs_intact() { let scope = Scope::new("u1", "https://app.affine.pro", "ws1"); diff --git a/packages/frontend/desktop/src/peek_view.rs b/packages/frontend/desktop/src/peek_view.rs index c2ee91a1ad..236ee956de 100644 --- a/packages/frontend/desktop/src/peek_view.rs +++ b/packages/frontend/desktop/src/peek_view.rs @@ -1,18 +1,14 @@ -//! Centered `PeekView` modal for previewing and editing `@` referenced documents -//! via a live embedded `Entity`, adhering to iOS 27 `pane_corner = 38pt` -//! geometry (`22pt` concentric inner card, fixed short `Peek` title, `36×36pt` close button, -//! and bottom action bar). +//! Center Peek shell for the live document preview. use playground::PlaygroundView; use ui::{ - Context, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, - StatefulInteractiveElement, Styled, div, px, svg, + App, AppContext, BoxShadow, Context, Entity, InteractiveElement, IntoElement, ParentElement, + RenderOnce, StatefulInteractiveElement, Styled, Window, div, hsla, px, svg, }; -use ui_tokens::FONT_SANS; use crate::{ - CLOSE_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, SPLIT_ICON_SVG, - workbench::DesktopShellView, + CLOSE_ICON_SVG, DesktopFlexExt, DesktopPalette, SPLIT_ICON_SVG, + workbench::{DesktopShellView, backdrop}, }; /// Actions that promote or dismiss [`PeekViewState`]. @@ -49,217 +45,337 @@ impl PeekViewState { } } -/// Render the centered `PeekView` modal following iOS 27 `pane_corner = 38pt` geometry. +const EXPAND_FULL_ICON_SVG: &[u8] = br#""#; +const CONTROL_SIZE: f32 = 32.0; +const CONTROL_GAP: f32 = 8.0; +const COMPACT_HEADER_HEIGHT: f32 = 48.0; + +fn peek_modal_height(vh: f32) -> f32 { + (vh * 0.90).min(900.0).round() +} + +pub(crate) fn peek_body_size(vw: f32, vh: f32) -> (f32, f32) { + let compact = vw < 640.0; + let width = if compact { + (vw - 32.0).max(0.0) + } else { + (vw * 0.90).min(1248.0) + }; + let height = peek_modal_height(vh); + let body_height = if compact { + (height - COMPACT_HEADER_HEIGHT).max(0.0) + } else { + height + }; + (width.round(), body_height) +} + pub(crate) fn render_peek_view_modal( peek_entity: Option>, - width: f32, - height: f32, + _width: f32, + _height: f32, palette: DesktopPalette, cx: &mut Context, ) -> impl IntoElement { - let body: ui::AnyElement = if let Some(entity) = peek_entity { - div() - .flex() - .flex_col() - .w_full() - .h_full() - .overflow_hidden() - .child(entity) - .into_any_element() - } else { - div() - .flex() - .items_center() - .justify_center() - .w_full() - .h_full() - .text_size(px(14.0)) - .text_color(palette.text_muted) - .child("Document not found") - .into_any_element() - }; + ui::ViewElement::new(PeekModal { + editor: peek_entity, + palette, + shell: cx.entity(), + }) +} - div() - .id("desktop.peek.backdrop") - // Keeps pointer presses on the modal from also focusing the editors behind it. - .occlude() - .absolute() - .top(px(0.0)) - .left(px(0.0)) - .w_full() - .h_full() - .bg(palette.scrim) +struct PeekModal { + editor: Option>, + palette: DesktopPalette, + shell: Entity, +} + +impl RenderOnce for PeekModal { + fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement { + let viewport = window.viewport_size(); + let vw = f32::from(viewport.width); + let vh = f32::from(viewport.height); + let compact = vw < 640.0; + let (width, body_height) = peek_body_size(vw, vh); + let height = peek_modal_height(vh); + let header_height = height - body_height; + let rail_width = CONTROL_SIZE + CONTROL_GAP; + let left = ((vw - width) * 0.5).min((vw - width - rail_width - CONTROL_GAP).max(0.0)); + let left = if compact { (vw - width) * 0.5 } else { left }; + let left = left.round(); + let top = ((vh - height) * 0.5).round(); + let palette = self.palette; + + let body = if let Some(editor) = self.editor { + editor.into_any_element() + } else { + div() + .flex() + .items_center() + .justify_center() + .w_full() + .h_full() + .text_size(px(14.0)) + .text_color(palette.text_muted) + .child("Document not found") + .into_any_element() + }; + + let close = control( + &self.shell, + "desktop.peek.close", + "Close", + CLOSE_ICON_SVG, + PeekAction::Close, + palette, + ); + let expand = control( + &self.shell, + "desktop.peek.open_current", + "Expand to full page", + EXPAND_FULL_ICON_SVG, + PeekAction::OpenInCurrentPane, + palette, + ); + let mut controls = div().flex().gap(px(CONTROL_GAP)); + let controls = if compact { + controls.style().justify_content = Some(ui::JustifyContent::FlexEnd); + controls + .h(px(header_height)) + .flex_shrink(0.0) + .items_center() + .px(px(CONTROL_GAP)) + .child(expand) + .child(close) + } else { + controls = controls.flex_col().child(close).child(expand); + controls.child(control( + &self.shell, + "desktop.peek.open_split", + "Open in split view", + SPLIT_ICON_SVG, + PeekAction::OpenInSplitView, + palette, + )) + }; + + let (header, rail) = if compact { + (Some(controls.into_any_element()), None) + } else { + (None, Some(controls.into_any_element())) + }; + let shell = self.shell; + div() + .absolute() + .inset_0() + .child(backdrop( + "desktop.peek.backdrop", + DesktopPalette { + scrim: hsla(0.0, 0.0, 0.0, 0.70), + ..palette + }, + move |_, window, app| { + shell.update(app, |shell, cx| { + shell.sync_editors(cx); + shell.state.apply_peek_action(PeekAction::Close); + shell.dismiss_modal(window, cx); + }); + }, + )) + .child( + div() + .absolute() + .left(px(left)) + .top(px(top)) + .id("desktop.peek.modal") + .snapshot("desktop.peek.modal", Some("desktop.shell.root")) + .w(px(width)) + .h(px(height)) + .occlude() + .on_click(|_, _, app| app.stop_propagation()) + .rounded(px(12.0)) + .bg(palette.bg_canvas) + .shadow( + [BoxShadow::new(px(0.0), px(8.0), hsla(0.0, 0.0, 0.0, 0.2)) + .blur_radius(px(28.0))] + .into_iter() + .collect(), + ) + .child( + div() + .id("desktop.peek.card") + .snapshot("desktop.peek.card", Some("desktop.peek.modal")) + .rounded(px(12.0)) + .overflow_hidden() + .w_full() + .h_full() + .flex() + .flex_col() + .children(header) + .child( + div() + .h(px(body_height)) + .w_full() + .overflow_hidden() + .child(body), + ), + ), + ) + .children(rail.map(|rail| { + div() + .absolute() + .left(px(left + width + CONTROL_GAP)) + .top(px(top + CONTROL_GAP)) + .child(rail) + })) + } +} + +fn control( + shell: &Entity, + id: &'static str, + label: &'static str, + icon: &'static [u8], + action: PeekAction, + palette: DesktopPalette, +) -> impl IntoElement + use<> { + let shell = shell.clone(); + let mut button = div() + .id(id) + .snapshot(id, Some("desktop.peek.modal")) + .w(px(CONTROL_SIZE)) + .h(px(CONTROL_SIZE)) + .rounded(px(8.0)) + .bg(palette.bg_elevated) + .cursor_pointer() + .hover(move |style| style.bg(palette.bg_surface)) .flex() .items_center() .justify_center() + .on_click(move |_, window, app| { + app.stop_propagation(); + shell.update(app, |shell, cx| { + shell.sync_editors(cx); + shell.state.apply_peek_action(action); + shell.dismiss_modal(window, cx); + }); + }) .child( - div() - .id("desktop.peek.modal") - .snapshot("desktop.peek.modal", Some("desktop.shell.root")) - .w(px(width)) - .h(px(height)) - .rounded(px(38.0)) - .bg(palette.bg_elevated) - .border_1() - .border_color(palette.border_strong) - .font_family(FONT_SANS) - .flex() - .flex_col() - .p(px(16.0)) - .gap(px(12.0)) - .child( - // Fixed short title "Peek" + top-right 36x36 (r=18) circular close button - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .w_full() - .px(px(4.0)) - .pt(px(4.0)) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(px(8.0)) - .child( - svg() - .data(DOC_ICON_SVG) - .w(px(16.0)) - .h(px(16.0)) - .flex_shrink(0.0) - .text_color(palette.accent), - ) - .child( - div() - .text_size(px(15.0)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text_primary) - .child("Peek"), - ), - ) - .child( - div() - .id("desktop.peek.close") - .snapshot("desktop.peek.close", Some("desktop.peek.modal")) - .w(px(36.0)) - .h(px(36.0)) - .rounded(px(18.0)) - .bg(palette.bg_pill) - .flex() - .items_center() - .justify_center() - .on_click(cx.listener(|this, _, _, cx| { - this.state.apply_peek_action(PeekAction::Close); - cx.notify(); - })) - .child( - svg() - .data(CLOSE_ICON_SVG) - .w(px(14.0)) - .h(px(14.0)) - .text_color(palette.text_primary), - ), - ), - ) - .child( - // Concentric inner live editor card (R_inner = 38 - 16 = 22px) - div() - .id("desktop.peek.card") - .snapshot("desktop.peek.card", Some("desktop.peek.modal")) - .flex() - .flex_col() - .flex_1() - .min_h_0() - .w_full() - .rounded(px(22.0)) - .overflow_hidden() - .bg(palette.bg_canvas) - .border_1() - .border_color(palette.border) - .child(body), - ) - .child( - // Clean bottom action bar (separated from the top-right close button) - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .w_full() - .px(px(4.0)) - .child( - div() - .text_size(px(12.0)) - .text_color(palette.text_muted) - .child("Live editable preview"), - ) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(px(8.0)) - .child( - div() - .id("desktop.peek.open_split") - .snapshot( - "desktop.peek.open_split", - Some("desktop.peek.modal"), - ) - .h(px(34.0)) - .px(px(14.0)) - .rounded(px(14.0)) - .bg(palette.bg_pill) - .border_1() - .border_color(palette.border) - .flex() - .flex_row() - .items_center() - .gap(px(6.0)) - .text_size(px(12.5)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_primary) - .on_click(cx.listener(|this, _, _, cx| { - this.state - .apply_peek_action(PeekAction::OpenInSplitView); - cx.notify(); - })) - .child( - svg() - .data(SPLIT_ICON_SVG) - .w(px(14.0)) - .h(px(14.0)) - .text_color(palette.text_primary), - ) - .child("Open in Split View"), - ) - .child( - div() - .id("desktop.peek.open_current") - .snapshot( - "desktop.peek.open_current", - Some("desktop.peek.modal"), - ) - .h(px(34.0)) - .px(px(14.0)) - .rounded(px(14.0)) - .bg(palette.accent) - .flex() - .items_center() - .justify_center() - .text_size(px(12.5)) - .font_weight(FontWeight::MEDIUM) - .text_color(ui::hsla(0.0, 0.0, 1.0, 1.0)) - .on_click(cx.listener(|this, _, _, cx| { - this.state - .apply_peek_action(PeekAction::OpenInCurrentPane); - cx.notify(); - })) - .child("Open in Current Pane"), - ), - ), - ), - ) + svg() + .data(icon) + .size(px(20.0)) + .text_color(palette.text_secondary), + ); + button + .interactivity() + .tooltip(move |_, app| app.new(|_| ControlTooltip(label, palette)).into()); + button +} + +struct ControlTooltip(&'static str, DesktopPalette); + +impl ui::Render for ControlTooltip { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + .px(px(8.0)) + .py(px(4.0)) + .rounded(px(4.0)) + .bg(self.1.bg_elevated) + .text_color(self.1.text_primary) + .text_size(px(12.0)) + .child(self.0) + } +} + +#[cfg(test)] +mod tests { + use ui::{Application, Bounds, HeadlessPlatform, WindowBounds, WindowOptions, point, size}; + use ui_tokens::ThemeMode; + + use crate::{DesktopAppState, register_desktop_fonts}; + + use super::*; + + #[test] + fn peek_body_size_accounts_for_compact_header_and_desktop_limits() { + for (vw, vh, expected) in [ + (639.0, 800.0, (607.0, 672.0)), + (640.0, 800.0, (576.0, 720.0)), + (390.0, 40.0, (358.0, 0.0)), + (1920.0, 1200.0, (1248.0, 900.0)), + ] { + assert_eq!(peek_body_size(vw, vh), expected); + } + } + + #[test] + fn peek_view_backdrop_dismisses_only_outside_the_preview() { + for (width, height) in [(1280, 800), (640, 800), (390, 844)] { + let platform = HeadlessPlatform::new(width, height, 1.0); + let app = Application::with_platform(platform.clone()).run_embedded(|_| {}); + let handle = app.update(|cx| { + register_desktop_fonts(cx).expect("desktop fonts"); + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + state.open_peek_view("doc-sync"); + 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 as f32)), + ))), + ..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(); + app.update(|cx| { + handle + .update(cx, |shell, window, _| { + assert!(shell.state.peek_view.is_open()); + let frame = window.frame_snapshot(); + let modal = frame.elements["desktop.peek.modal"].bounds; + let close = frame.elements["desktop.peek.close"].bounds; + assert_eq!(close.width, 32.0); + assert!(close.x + close.width <= width as f32); + if width >= 640 { + assert!(close.x >= modal.x + modal.width + CONTROL_GAP); + assert!(frame.elements.contains_key("desktop.peek.open_split")); + } else { + assert!(close.x < modal.x + modal.width); + assert!(!frame.elements.contains_key("desktop.peek.open_split")); + } + }) + .expect("desktop view"); + }); + + window.simulate_click(point(px(width as f32 / 2.0), px(height as f32 / 2.0))); + app.update(|cx| { + handle + .update(cx, |shell, _, _| assert!(shell.state.peek_view.is_open())) + .expect("desktop view"); + }); + window.simulate_click(point(px(4.0), px(4.0))); + window.request_frame(); + app.update(|cx| { + handle + .update(cx, |shell, window, _| { + assert!(!shell.state.peek_view.is_open()); + assert!( + !window + .frame_snapshot() + .elements + .contains_key("desktop.peek.modal") + ); + }) + .expect("desktop view"); + }); + } + } } diff --git a/packages/frontend/desktop/src/quick_search.rs b/packages/frontend/desktop/src/quick_search.rs deleted file mode 100644 index 91e8ad31cb..0000000000 --- a/packages/frontend/desktop/src/quick_search.rs +++ /dev/null @@ -1,599 +0,0 @@ -//! `Cmd/Ctrl+K` QuickSearch modal: fuzzy & substring document search plus quick commands, -//! keyboard navigation (`Up`/`Down`/`Enter`/`Cmd+Enter`/`Escape`), and clean modal UI. - -use blocksuite_editor::inline_input::Utf16ImeBuffer; -use ui::{ - Bounds, Context, CursorStyle, FocusHandle, FontWeight, InteractiveElement, IntoElement, - MouseButton, ParentElement, Pixels, StatefulInteractiveElement, Styled, div, px, svg, -}; -use ui_tokens::FONT_SANS; - -use crate::{ - CLOSE_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, - JOURNAL_ICON_SVG, PLUS_ICON_SVG, SEARCH_ICON_SVG, SIDEBAR_TOGGLE_SVG, SPLIT_ICON_SVG, - doc_store::DesktopDocStore, - workbench::{DesktopShellView, backdrop, search_input_handler}, -}; - -/// Built-in command actions available from `Cmd/Ctrl+K`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum QuickCommandId { - NewPage, - NewEdgeless, - ToggleTheme, - OpenTodayJournal, - ToggleSidebar, - SplitView, -} - -impl QuickCommandId { - pub const ALL: [Self; 6] = [ - Self::NewPage, - Self::NewEdgeless, - Self::ToggleTheme, - Self::OpenTodayJournal, - Self::ToggleSidebar, - Self::SplitView, - ]; - - pub const fn label(self) -> &'static str { - match self { - Self::NewPage => "New Page", - Self::NewEdgeless => "New Edgeless Whiteboard", - Self::ToggleTheme => "Toggle Theme (Light / Dark)", - Self::OpenTodayJournal => "Open Today's Journal", - Self::ToggleSidebar => "Toggle Sidebar", - Self::SplitView => "Split View (Page + Edgeless)", - } - } - - pub const fn shortcut(self) -> &'static str { - match self { - Self::NewPage => "⌘N", - Self::NewEdgeless => "⌘⇧N", - Self::ToggleTheme => "⌘⇧L", - Self::OpenTodayJournal => "⌘J", - Self::ToggleSidebar => "⌘/", - Self::SplitView => "⌘\\", - } - } -} - -/// One selectable entry in the QuickSearch results list. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum QuickSearchItem { - Doc { - doc_id: String, - title: String, - summary: String, - is_edgeless: bool, - }, - Command(QuickCommandId), -} - -/// Interactive state for the `Cmd/Ctrl+K` QuickSearch modal. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct QuickSearchState { - pub open: bool, - pub query: String, - pub selected_index: usize, - pub scroll_y: f32, - pub(crate) text_bounds: Option>, -} - -impl QuickSearchState { - pub fn open(&mut self) { - self.open = true; - self.query.clear(); - self.text_bounds = None; - self.selected_index = 0; - self.scroll_y = 0.0; - } - - pub fn close(&mut self) { - self.open = false; - self.query.clear(); - self.text_bounds = None; - self.selected_index = 0; - self.scroll_y = 0.0; - } - - pub fn set_query(&mut self, query: impl Into) { - self.query = query.into(); - self.selected_index = 0; - self.scroll_y = 0.0; - } - - /// Compute ordered document matches + matching quick commands. - pub fn items(&self, store: &DesktopDocStore) -> Vec { - let mut out = Vec::new(); - let hits = store.search_docs(&self.query, 8); - for hit in hits { - if let Some(entry) = store.get_doc(&hit.doc_id) { - out.push(QuickSearchItem::Doc { - doc_id: entry.meta.id.clone(), - title: entry.meta.title.clone(), - summary: entry.meta.summary.clone(), - is_edgeless: entry.meta.default_mode - == affine_store::directory::DocMode::Edgeless, - }); - } - } - let q = self.query.trim().to_ascii_lowercase(); - for cmd in QuickCommandId::ALL { - if q.is_empty() || cmd.label().to_ascii_lowercase().contains(&q) { - out.push(QuickSearchItem::Command(cmd)); - } - } - out - } - - pub fn move_selection(&mut self, delta: isize, total: usize) { - if total == 0 { - self.selected_index = 0; - return; - } - let cur = self.selected_index.min(total - 1) as isize; - self.selected_index = (cur + delta).rem_euclid(total as isize) as usize; - } -} - -pub(crate) const QUICK_SEARCH_HEIGHT: f32 = 516.0; -const RESULT_ROW: f32 = 52.0; -const SECTION_HEADER: f32 = 24.0; - -fn results_height(modal_height: f32) -> f32 { - (modal_height - 156.0).max(0.0) -} - -impl QuickSearchState { - pub(crate) fn reveal_selection(&mut self, doc_count: usize, modal_height: f32) { - let headers = if self.selected_index >= doc_count && doc_count > 0 { - 2.0 - } else { - 1.0 - }; - let top = headers * SECTION_HEADER + self.selected_index as f32 * RESULT_ROW; - let visible = (results_height(modal_height) - 18.0).max(0.0); - self.scroll_y = self - .scroll_y - .min(top) - .max(top + RESULT_ROW - visible) - .max(0.0); - } -} - -/// Render the centered `Cmd/Ctrl+K` QuickSearch command palette modal. -pub(crate) fn render_quick_search_modal( - qs: &QuickSearchState, - store: &DesktopDocStore, - focus: &FocusHandle, - input: &Utf16ImeBuffer, - (width, height): (f32, f32), - palette: DesktopPalette, - cx: &mut Context, -) -> impl IntoElement { - let items = qs.items(store); - let selected = qs.selected_index.min(items.len().saturating_sub(1)); - let results_h = results_height(height); - - let doc_items: Vec<(usize, &QuickSearchItem)> = items - .iter() - .enumerate() - .filter(|(_, item)| matches!(item, QuickSearchItem::Doc { .. })) - .collect(); - let cmd_items: Vec<(usize, &QuickSearchItem)> = items - .iter() - .enumerate() - .filter(|(_, item)| matches!(item, QuickSearchItem::Command(_))) - .collect(); - - let header_count = usize::from(!doc_items.is_empty()) + usize::from(!cmd_items.is_empty()); - let max_scroll = - (items.len() as f32 * RESULT_ROW + header_count as f32 * SECTION_HEADER + 18.0 - results_h) - .max(0.0); - let mut list = div() - .flex() - .flex_col() - .w_full() - .mt(px(-qs.scroll_y.min(max_scroll))); - - if !doc_items.is_empty() { - list = list.child( - div() - .px(px(12.0)) - .h(px(SECTION_HEADER)) - .flex_shrink(0.0) - .flex() - .items_center() - .text_size(px(11.0)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_muted) - .child("DOCUMENTS"), - ); - for (idx, item) in doc_items { - if let QuickSearchItem::Doc { - doc_id, - title, - summary, - is_edgeless, - } = item - { - let is_sel = idx == selected; - let doc_id_click = doc_id.clone(); - let doc_id_split = doc_id.clone(); - list = list.child( - div() - .id(ui::SharedString::from(format!("desktop.qs.doc.{doc_id}"))) - .snapshot( - format_args!("desktop.qs.doc.{doc_id}"), - Some("desktop.qs.modal"), - ) - .flex() - .flex_row() - .items_center() - .justify_between() - .w_full() - .px(px(12.0)) - .h(px(RESULT_ROW)) - .flex_shrink(0.0) - .gap(px(6.0)) - .rounded(px(10.0)) - .bg(if is_sel { - palette.bg_active - } else { - ui::hsla(0.0, 0.0, 0.0, 0.0) - }) - .on_click(cx.listener(move |this, _, window, cx| { - this.sync_editors(cx); - this.open_search_result(&doc_id_click, false, window, cx); - })) - .child( - div() - .flex() - .flex_row() - .items_start() - .gap(px(10.0)) - .flex_1() - .min_w_0() - .child( - div() - .w(px(20.0)) - .h(px(20.0)) - .flex() - .items_center() - .justify_center() - .child( - svg() - .data(if *is_edgeless { - EDGELESS_ICON_SVG - } else { - DOC_ICON_SVG - }) - .w(px(16.0)) - .h(px(16.0)) - .text_color(if is_sel { - palette.accent - } else { - palette.text_secondary - }), - ), - ) - .child( - div() - .flex() - .flex_col() - .gap(px(2.0)) - .flex_1() - .min_w_0() - .child( - div() - .text_ellipsis() - .text_size(px(13.5)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_primary) - .child(if title.is_empty() { - "Untitled".to_string() - } else { - title.clone() - }), - ) - .child( - div() - .text_ellipsis() - .text_size(px(12.0)) - .text_color(palette.text_muted) - .child(summary.clone()), - ), - ), - ) - .child( - div() - .id(ui::SharedString::from(format!("desktop.qs.split.{doc_id}"))) - .px(px(8.0)) - .py(px(4.0)) - .rounded(px(6.0)) - .bg(palette.bg_pill) - .flex_shrink(0.0) - .text_size(px(11.0)) - .text_color(palette.text_secondary) - .on_click(cx.listener(move |this, _, window, cx| { - cx.stop_propagation(); - this.sync_editors(cx); - this.open_search_result(&doc_id_split, true, window, cx); - })) - .child("⌘↵ Split"), - ), - ); - } - } - } - - if !cmd_items.is_empty() { - list = list.child( - div() - .px(px(12.0)) - .h(px(SECTION_HEADER)) - .flex_shrink(0.0) - .flex() - .items_center() - .text_size(px(11.0)) - .font_weight(FontWeight::MEDIUM) - .text_color(palette.text_muted) - .child("COMMANDS"), - ); - for (idx, item) in cmd_items { - if let QuickSearchItem::Command(cmd) = item { - let is_sel = idx == selected; - let cmd_copy = *cmd; - let icon_bytes = match cmd_copy { - QuickCommandId::NewPage | QuickCommandId::NewEdgeless => PLUS_ICON_SVG, - QuickCommandId::OpenTodayJournal => JOURNAL_ICON_SVG, - QuickCommandId::ToggleSidebar => SIDEBAR_TOGGLE_SVG, - QuickCommandId::SplitView => SPLIT_ICON_SVG, - QuickCommandId::ToggleTheme => SEARCH_ICON_SVG, - }; - list = list.child( - div() - .id(ui::SharedString::from(format!("desktop.qs.cmd.{idx}"))) - .flex() - .flex_row() - .items_center() - .justify_between() - .w_full() - .px(px(12.0)) - .h(px(RESULT_ROW)) - .flex_shrink(0.0) - .gap(px(6.0)) - .rounded(px(10.0)) - .bg(if is_sel { - palette.bg_active - } else { - ui::hsla(0.0, 0.0, 0.0, 0.0) - }) - .on_click(cx.listener(move |this, _, window, cx| { - this.sync_editors(cx); - this.run_search_command(cmd_copy, window, cx); - })) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(px(10.0)) - .min_w_0() - .child( - svg() - .data(icon_bytes) - .w(px(16.0)) - .h(px(16.0)) - .text_color(palette.text_secondary), - ) - .child( - div() - .min_w_0() - .text_ellipsis() - .text_size(px(13.5)) - .text_color(palette.text_primary) - .child(cmd_copy.label()), - ), - ) - .child( - div() - .px(px(7.0)) - .py(px(3.0)) - .rounded(px(6.0)) - .bg(palette.bg_pill) - .flex_shrink(0.0) - .text_size(px(11.0)) - .text_color(palette.text_muted) - .child(cmd_copy.shortcut()), - ), - ); - } - } - } - - if items.is_empty() { - list = list.child( - div() - .px(px(16.0)) - .py(px(28.0)) - .text_size(px(13.0)) - .text_color(palette.text_muted) - .child("No matching documents or commands."), - ); - } - - let focus = focus.clone(); - - div() - .absolute() - .top_0() - .left_0() - .w_full() - .h_full() - .flex() - .items_center() - .justify_center() - .child(backdrop( - "desktop.qs.backdrop", - palette, - cx.listener(|this, _, window, cx| { - this.dismiss_modal(window, cx); - }), - )) - .child( - div() - .id("desktop.qs.modal") - .snapshot("desktop.qs.modal", Some("desktop.shell.root")) - .w(px(width)) - .h(px(height)) - .occlude() - .overflow_hidden() - .rounded(px(38.0)) - .bg(palette.bg_elevated) - .border_1() - .border_color(palette.border_strong) - .font_family(FONT_SANS) - .flex() - .flex_col() - .p(px(16.0)) - .gap(px(12.0)) - .child( - // Fixed short header + top-right 36x36 (r=18) circular close button - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .px(px(4.0)) - .pt(px(4.0)) - .child( - div() - .text_size(px(15.0)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(palette.text_primary) - .child("Quick Search"), - ) - .child( - div() - .id("desktop.qs.close") - .snapshot("desktop.qs.close", Some("desktop.qs.modal")) - .w(px(36.0)) - .h(px(36.0)) - .rounded(px(18.0)) - .bg(palette.bg_pill) - .flex() - .items_center() - .justify_center() - .on_click(cx.listener(|this, _, window, cx| { - this.dismiss_modal(window, cx); - })) - .child( - svg() - .data(CLOSE_ICON_SVG) - .w(px(14.0)) - .h(px(14.0)) - .text_color(palette.text_primary), - ), - ), - ) - .child( - // Search input box (concentric inner radius <= 22px) - div() - .id("desktop.qs.input") - .snapshot("desktop.qs.input", Some("desktop.qs.modal")) - .snapshot_text(qs.query.clone()) - .snapshot_focused(true) - .track_focus(&focus) - .cursor(CursorStyle::IBeam) - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, event, window, cx| { - this.click_search_input(event, window, cx); - }), - ) - .overflow_hidden() - .flex() - .flex_row() - .items_center() - .gap(px(10.0)) - .px(px(14.0)) - .h(px(44.0)) - .rounded(px(14.0)) - .bg(palette.bg_surface) - .border_1() - .border_color(palette.accent) - .child( - svg() - .data(SEARCH_ICON_SVG) - .w(px(16.0)) - .h(px(16.0)) - .flex_shrink(0.0) - .text_color(palette.accent), - ) - .child( - div() - .relative() - .flex_1() - .min_w_0() - .h(px(17.0)) - .overflow_hidden() - .text_size(px(14.0)) - .children(qs.query.is_empty().then(|| { - div() - .absolute() - .inset_0() - .text_color(palette.text_muted) - .text_ellipsis() - .pl(px(5.0)) - .child("Search documents, tags, or commands") - })) - .child(search_input_handler(input, focus.clone(), palette, cx)), - ), - ) - .child( - // Scrollable concentric results card (R_inner = 22px) - div() - .id("desktop.qs.results") - .w_full() - .flex_1() - .min_h_0() - .rounded(px(22.0)) - .bg(palette.bg_surface) - .border_1() - .border_color(palette.border) - .p(px(8.0)) - .overflow_hidden() - .on_scroll(cx.listener(move |this, event: &ui::ScrollEvent, _, cx| { - let dy: f32 = event.delta.pixel_delta(px(20.0)).y.into(); - this.state.quick_search.scroll_y = - (this.state.quick_search.scroll_y - dy).clamp(0.0, max_scroll); - cx.notify(); - })) - .child(list), - ) - .child( - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .gap(px(8.0)) - .px(px(4.0)) - .text_size(px(11.5)) - .text_color(palette.text_muted) - .child(div().min_w_0().text_ellipsis().child(if width < 450.0 { - "↑↓ Navigate · ↵ Open · Esc Close" - } else { - "↑↓ Navigate · ↵ Open · ⌘↵ Split View · Esc Close" - })) - .child(if items.len() == 1 { - "1 result".to_string() - } else { - format!("{} results", items.len()) - }), - ), - ) -} diff --git a/packages/frontend/desktop/src/quick_search/mod.rs b/packages/frontend/desktop/src/quick_search/mod.rs new file mode 100644 index 0000000000..e48ce4323d --- /dev/null +++ b/packages/frontend/desktop/src/quick_search/mod.rs @@ -0,0 +1,392 @@ +//! Quick Search results, commands, and keyboard selection. + +use affine_client::Scope; +use affine_store::directory::DocMode; +use ui::{Bounds, Context, Pixels, Window}; + +use crate::{doc_store::DesktopDocStore, split_view::SplitLayout, workbench::DesktopShellView}; + +mod modal; + +pub(crate) use modal::render_quick_search_modal; + +/// Built-in command actions available from `Cmd/Ctrl+K`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum QuickCommandId { + NewPage, + NewEdgeless, + ToggleTheme, + OpenTodayJournal, + ToggleSidebar, + SplitView, +} + +impl QuickCommandId { + pub const ALL: [Self; 6] = [ + Self::NewPage, + Self::NewEdgeless, + Self::ToggleTheme, + Self::OpenTodayJournal, + Self::ToggleSidebar, + Self::SplitView, + ]; + + pub const fn label(self) -> &'static str { + match self { + Self::NewPage => "New Page", + Self::NewEdgeless => "New Edgeless Whiteboard", + Self::ToggleTheme => "Toggle Theme (Light / Dark)", + Self::OpenTodayJournal => "Open Today's Journal", + Self::ToggleSidebar => "Toggle Sidebar", + Self::SplitView => "Split View (Page + Edgeless)", + } + } + + pub const fn shortcut(self) -> &'static str { + match self { + Self::NewPage => "⌘N", + Self::ToggleSidebar => "⌘/", + Self::NewEdgeless | Self::ToggleTheme | Self::OpenTodayJournal | Self::SplitView => "", + } + } +} + +/// One selectable entry in the QuickSearch results list. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum QuickSearchItem { + Doc { + doc_id: String, + title: String, + summary: String, + is_edgeless: bool, + recent: bool, + }, + Command(QuickCommandId), +} + +impl QuickSearchItem { + fn group(&self) -> &'static str { + match self { + Self::Doc { recent: true, .. } => "Recent", + Self::Doc { .. } => "Docs", + Self::Command(_) => "Actions", + } + } +} + +/// Interactive state for the `Cmd/Ctrl+K` QuickSearch modal. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct QuickSearchState { + pub open: bool, + pub query: String, + pub selected_index: usize, + pub scroll_y: f32, + pub(crate) text_bounds: Option>, +} + +impl QuickSearchState { + pub fn open(&mut self) { + self.open = true; + self.query.clear(); + self.text_bounds = None; + self.selected_index = 0; + self.scroll_y = 0.0; + } + + pub fn close(&mut self) { + self.open = false; + self.query.clear(); + self.text_bounds = None; + self.selected_index = 0; + self.scroll_y = 0.0; + } + + pub fn set_query(&mut self, query: impl Into) { + self.query = query.into(); + self.selected_index = 0; + self.scroll_y = 0.0; + } + + /// Compute ordered document matches + matching quick commands. + pub fn items(&self, store: &DesktopDocStore) -> Vec { + self.items_with_recent(store, &[]) + } + + pub(crate) fn items_with_split( + &self, + store: &DesktopDocStore, + split: &SplitLayout, + ) -> Vec { + if !self.query.trim().is_empty() { + return self.items(store); + } + + let scope = Scope::new( + "local-user", + "https://app.affine.pro", + &store.active_workspace().id, + ); + let active = split.active(); + let active_doc = active.active_route().doc_id().filter(|_| { + active + .history + .current() + .is_none_or(|entry| entry.scope == scope) + }); + let mut visits: Vec<_> = split + .panes + .iter() + .flat_map(|pane| pane.history.entries()) + .filter(|entry| entry.scope == scope) + .filter_map(|entry| Some((entry.visit_seq(), entry.target.doc_id()?))) + .collect(); + visits.sort_by_key(|(seq, _)| std::cmp::Reverse(*seq)); + + let mut recent = Vec::with_capacity(RECENT_COUNT); + for id in active_doc + .into_iter() + .chain(visits.into_iter().map(|(_, id)| id)) + { + if !recent.contains(&id) && store.get_doc(id).is_some_and(|entry| !entry.meta.trashed) { + recent.push(id); + if recent.len() == RECENT_COUNT { + break; + } + } + } + self.items_with_recent(store, &recent) + } + + fn items_with_recent(&self, store: &DesktopDocStore, recent: &[&str]) -> Vec { + let query = self.query.trim(); + let tag = query.strip_prefix('#').map(str::trim); + let hits = match tag { + Some("") => Vec::new(), + Some(name) => store.search_docs(name, 0), + None => store.search_docs(query, if query.is_empty() { 16 } else { 8 }), + }; + let visited = recent.iter().map(|&id| (id, &[][..], true)); + let matched = hits + .iter() + .filter(|hit| tag.is_none() || !hit.matched_tags.is_empty()) + .filter(|hit| !recent.contains(&hit.doc_id.as_str())) + .map(|hit| (hit.doc_id.as_str(), hit.matched_tags.as_slice(), false)); + let mut out: Vec<_> = visited + .chain(matched) + .filter_map(|(doc_id, tags, recent)| { + let entry = store.get_doc(doc_id)?; + let summary = if tags.is_empty() { + entry.meta.summary.clone() + } else { + tags.iter() + .map(|name| format!("#{name}")) + .collect::>() + .join(" ") + }; + Some(QuickSearchItem::Doc { + doc_id: entry.meta.id.clone(), + title: entry.meta.title.clone(), + summary, + is_edgeless: entry.meta.default_mode == DocMode::Edgeless, + recent, + }) + }) + .take(8) + .collect(); + let q = query.to_ascii_lowercase(); + for cmd in QuickCommandId::ALL { + if !q.is_empty() && matches!(cmd, QuickCommandId::NewPage | QuickCommandId::NewEdgeless) + { + continue; + } + if q.is_empty() || cmd.label().to_ascii_lowercase().contains(&q) { + out.push(QuickSearchItem::Command(cmd)); + } + } + if !query.is_empty() && !store.is_readonly_sqlite() { + out.push(QuickSearchItem::Command(QuickCommandId::NewPage)); + out.push(QuickSearchItem::Command(QuickCommandId::NewEdgeless)); + } + out + } + + pub fn move_selection(&mut self, delta: isize, total: usize) { + if total == 0 { + self.selected_index = 0; + return; + } + let cur = self.selected_index.min(total - 1) as isize; + self.selected_index = (cur + delta).rem_euclid(total as isize) as usize; + } +} + +pub(crate) const QUICK_SEARCH_HEIGHT: f32 = 422.0; +const INPUT_HEIGHT: f32 = 66.0; +const RESULT_ROW: f32 = 44.0; +const SECTION_HEADER: f32 = 28.0; +const LIST_PAD: f32 = 8.0; +const RECENT_COUNT: usize = 3; +const MAX_LIST_HEIGHT: f32 = 330.0; + +fn row_ends(items: &[QuickSearchItem]) -> Vec { + let mut end = LIST_PAD; + let mut previous = ""; + items + .iter() + .map(|item| { + let group = item.group(); + if group != previous { + end += SECTION_HEADER; + previous = group; + } + end += RESULT_ROW; + end + }) + .collect() +} + +fn modal_top(vh: f32) -> f32 { + (vh * 0.13).min((vh - INPUT_HEIGHT - 16.0).max(0.0)).round() +} + +fn list_height(ends: &[f32], content_height: f32, vw: f32, vh: f32, modal_height: f32) -> f32 { + let limit = if vw < 640.0 { + vh - 32.0 + } else { + vh - modal_top(vh) - 16.0 + }; + let budget = (modal_height.min(limit) - INPUT_HEIGHT - LIST_PAD).clamp(0.0, MAX_LIST_HEIGHT); + if content_height <= budget { + content_height + } else { + ends.iter() + .rev() + .copied() + .find(|&end| end <= budget) + .unwrap_or(budget) + } +} + +impl QuickSearchState { + pub(crate) fn reveal_selection( + &mut self, + items: &[QuickSearchItem], + vw: f32, + vh: f32, + modal_height: f32, + ) { + let ends = row_ends(items); + let (Some(&bottom), Some(&content_height)) = (ends.get(self.selected_index), ends.last()) + else { + return; + }; + let visible = list_height(&ends, content_height, vw, vh, modal_height); + self.scroll_y = self + .scroll_y + .round() + .min(bottom - RESULT_ROW) + .max(bottom - visible) + .clamp(0.0, (content_height - visible).max(0.0)); + } +} + +impl DesktopShellView { + /// Create a document with the query as its title and open it. + pub(crate) fn submit_search_command( + &mut self, + command: QuickCommandId, + window: &mut Window, + cx: &mut Context, + ) { + let query = self.state.quick_search.query.trim(); + let mode = match command { + QuickCommandId::NewPage => Some(DocMode::Page), + QuickCommandId::NewEdgeless => Some(DocMode::Edgeless), + _ => None, + }; + if let Some(mode) = mode.filter(|_| !query.is_empty()) { + if self.state.store.is_readonly_sqlite() { + return; + } + let title = query.to_owned(); + self.state.logical_clock_ms += 10; + let id = self + .state + .store + .create_doc(title, mode, None, self.state.logical_clock_ms); + if !id.is_empty() { + self.open_search_result(&id, false, window, cx); + } + } else { + self.run_search_command(command, window, cx); + } + } +} + +#[cfg(test)] +mod tests { + use crate::split_view::{DesktopRoute, DocViewMode}; + + use super::*; + + #[test] + fn recent_orders_visits_and_revisits_across_panes() { + for (left, right, expected, after_back) in [ + ( + &["A", "B", "C", "D", "L"][..], + ["X", "Y"], + ["Y", "X", "L"], + None, + ), + ( + &["白板", "架构", "同步"][..], + ["白板", "日记"], + ["日记", "白板", "同步"], + Some(["同步", "白板", "日记"]), + ), + ] { + let mut store = DesktopDocStore::seed_showcase("2026-12-02"); + let mut ids = std::collections::HashMap::new(); + for (index, name) in left.iter().chain(&right).copied().enumerate() { + ids.entry(name) + .or_insert_with(|| store.create_doc(name, DocMode::Page, None, index as i64)); + } + let scope = Scope::new( + "local-user", + "https://app.affine.pro", + &store.active_workspace().id, + ); + let route = |name: &str| DesktopRoute::Doc(ids[name].clone()); + let mut split = SplitLayout::single(scope.clone(), route(left[0]), DocViewMode::Page); + for name in &left[1..] { + split + .active_mut() + .navigate(scope.clone(), route(name), None); + } + split.open_in_split(scope.clone(), route(right[0]), DocViewMode::Page); + split.active_mut().navigate(scope, route(right[1]), None); + + let recent = |split: &SplitLayout| { + QuickSearchState::default() + .items_with_split(&store, split) + .into_iter() + .take_while(|item| matches!(item, QuickSearchItem::Doc { recent: true, .. })) + .map(|item| match item { + QuickSearchItem::Doc { title, .. } => title, + QuickSearchItem::Command(_) => unreachable!(), + }) + .collect::>() + }; + assert_eq!(recent(&split), expected); + if let Some(expected) = after_back { + assert!(split.active_mut().go_back()); + split.focus_pane(0); + assert_eq!(recent(&split), expected); + split.focus_pane(1); + assert!(split.active_mut().go_forward()); + split.focus_pane(0); + assert_eq!(recent(&split), ["同步", "日记", "白板"]); + } + } + } +} diff --git a/packages/frontend/desktop/src/quick_search/modal.rs b/packages/frontend/desktop/src/quick_search/modal.rs new file mode 100644 index 0000000000..b966eb3004 --- /dev/null +++ b/packages/frontend/desktop/src/quick_search/modal.rs @@ -0,0 +1,606 @@ +use blocksuite_editor::{ + database::format_database_created_time, + inline_input::{Utf16ImeBuffer, utf16_to_byte}, + match_exact_substring_utf16, +}; +use ui::{ + App, BoxShadow, Context, CursorStyle, FocusHandle, FontWeight, HighlightStyle, + InteractiveElement, IntoElement, MouseButton, ParentElement, RenderOnce, SharedString, + StatefulInteractiveElement, Styled, StyledText, Window, div, hsla, px, svg, +}; +use ui_tokens::{DARK_THEME, FONT_SANS, LIGHT_THEME}; + +use crate::{ + DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, JOURNAL_ICON_SVG, + PLUS_ICON_SVG, SEARCH_ICON_SVG, SIDEBAR_TOGGLE_SVG, SPLIT_ICON_SVG, + doc_store::DesktopDocStore, + rgba_to_hsla, + workbench::{DesktopShellView, search_input_handler}, +}; + +use super::{ + INPUT_HEIGHT, LIST_PAD, QuickCommandId, QuickSearchItem, QuickSearchState, RESULT_ROW, + SECTION_HEADER, list_height, modal_top, row_ends, +}; + +/// Render the desktop command palette. +pub(crate) fn render_quick_search_modal( + _qs: &QuickSearchState, + _store: &DesktopDocStore, + focus: &FocusHandle, + input: &Utf16ImeBuffer, + (width, height): (f32, f32), + palette: DesktopPalette, + cx: &mut Context, +) -> impl IntoElement { + ui::ViewElement::new(QuickSearchModal { + width, + height, + focus: focus.clone(), + input: input.clone(), + palette, + shell: cx.entity(), + }) +} + +struct QuickSearchModal { + width: f32, + height: f32, + focus: FocusHandle, + input: Utf16ImeBuffer, + palette: DesktopPalette, + shell: ui::Entity, +} + +impl RenderOnce for QuickSearchModal { + fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { + let state = self.shell.read(app).state(); + let qs = &state.quick_search; + let store = &state.store; + let items = qs.items_with_split(store, &state.split); + let palette = self.palette; + let selected = qs.selected_index.min(items.len().saturating_sub(1)); + let command_modifier = if app.platform_info().is_mac() { + "⌘" + } else { + "Ctrl+" + }; + let query = qs.query.trim(); + let needle = query.strip_prefix('#').unwrap_or(query).trim(); + let mut rows = Vec::new(); + let ends = row_ends(&items); + let content_height = ends.last().copied().unwrap_or(LIST_PAD + RESULT_ROW); + let mut last_group = ""; + for (index, item) in items.into_iter().enumerate() { + let group = item.group(); + let offset = ends[index] - RESULT_ROW; + if group != last_group { + rows.push(( + offset - SECTION_HEADER, + SECTION_HEADER, + div() + .h(px(SECTION_HEADER)) + .flex_shrink(0.0) + .flex() + .items_center() + .px(px(8.0)) + .text_size(px(12.0)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(palette.text_muted) + .child(group) + .into_any_element(), + )); + last_group = group; + } + let (id, icon, title, subtitle, detail) = match &item { + QuickSearchItem::Doc { + doc_id, + title, + summary, + is_edgeless, + .. + } => ( + format!("desktop.qs.doc.{doc_id}"), + if *is_edgeless { + EDGELESS_ICON_SVG + } else { + DOC_ICON_SVG + }, + if title.is_empty() { + "Untitled".into() + } else { + title.clone() + }, + if query.is_empty() { + String::new() + } else { + summary.clone() + }, + store + .get_doc(doc_id) + .map(|entry| updated_time(entry.meta.updated_at_ms)) + .unwrap_or_default(), + ), + QuickSearchItem::Command(cmd) => { + let mode = match cmd { + QuickCommandId::NewPage => "Page", + QuickCommandId::NewEdgeless => "Edgeless", + _ => "", + }; + let title = if !mode.is_empty() && !query.is_empty() { + format!("Create \"{query}\" as {mode}") + } else { + cmd.label().into() + }; + let icon = match cmd { + QuickCommandId::NewPage | QuickCommandId::NewEdgeless => PLUS_ICON_SVG, + QuickCommandId::OpenTodayJournal => JOURNAL_ICON_SVG, + QuickCommandId::ToggleSidebar => SIDEBAR_TOGGLE_SVG, + QuickCommandId::SplitView => SPLIT_ICON_SVG, + QuickCommandId::ToggleTheme => SEARCH_ICON_SVG, + }; + ( + format!("desktop.qs.cmd.{index}"), + icon, + title, + String::new(), + if mode.is_empty() || query.is_empty() { + cmd.shortcut().replace('⌘', command_modifier) + } else { + String::new() + }, + ) + } + }; + let title = highlighted(title, needle, palette); + let subtitle = (!subtitle.is_empty()).then(|| highlighted(subtitle, needle, palette)); + let is_doc = matches!(item, QuickSearchItem::Doc { .. }); + let shell = self.shell.clone(); + rows.push(( + offset, + RESULT_ROW, + div() + .id(SharedString::from(id.clone())) + .snapshot(id, Some("desktop.qs.modal")) + .w_full() + .h(px(RESULT_ROW)) + .flex_shrink(0.0) + .flex() + .items_center() + .px(px(12.0)) + .gap(px(12.0)) + .rounded(px(4.0)) + .bg(if index == selected { + palette.bg_pill + } else { + hsla(0.0, 0.0, 0.0, 0.0) + }) + .cursor_pointer() + .hover(move |s| s.bg(palette.bg_pill)) + .on_click(move |_, window, app| { + shell.update(app, |shell, cx| { + shell.sync_editors(cx); + match &item { + QuickSearchItem::Doc { doc_id, .. } => { + shell.open_search_result(doc_id, false, window, cx); + } + QuickSearchItem::Command(command) => { + shell.submit_search_command(*command, window, cx); + } + } + }); + }) + .child( + svg() + .data(icon) + .size(px(20.0)) + .flex_shrink(0.0) + .text_color(palette.text_secondary), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + div() + .text_size(px(14.0)) + .line_height(px(20.0)) + .text_color(palette.text_primary) + .text_ellipsis() + .child(title), + ) + .children(subtitle.map(|text| { + div() + .text_size(px(12.0)) + .line_height(px(16.0)) + .text_color(palette.text_secondary) + .text_ellipsis() + .child(text) + })), + ) + .children((!detail.is_empty()).then(|| { + let detail = div() + .flex_shrink(0.0) + .text_size(px(11.0)) + .text_color(palette.text_secondary) + .child(detail); + if is_doc { + detail + } else { + detail.bg(palette.bg_pill).px(px(4.0)).rounded(px(4.0)) + } + })) + .into_any_element(), + )); + } + + if rows.is_empty() { + rows.push(( + LIST_PAD, + RESULT_ROW, + div() + .h(px(RESULT_ROW)) + .flex() + .items_center() + .px(px(12.0)) + .text_size(px(14.0)) + .text_color(palette.text_secondary) + .child("No matches") + .into_any_element(), + )); + } + + let input_shell = self.shell.clone(); + let focus = self.focus; + let empty = qs.query.is_empty(); + let input = div() + .id("desktop.qs.input") + .snapshot("desktop.qs.input", Some("desktop.qs.modal")) + .snapshot_text(qs.query.clone()) + .snapshot_focused(true) + .track_focus(&focus) + .cursor(CursorStyle::IBeam) + .on_mouse_down(MouseButton::Left, move |event, window, app| { + input_shell.update(app, |shell, cx| shell.click_search_input(event, window, cx)); + }) + .flex() + .items_center() + .px(px(16.0)) + .h(px(INPUT_HEIGHT)) + .flex_shrink(0.0) + .border_b_1() + .border_color(palette.border) + .child( + div() + .relative() + .flex_1() + .min_w_0() + .h(px(28.0)) + .overflow_hidden() + .children(empty.then(|| { + div() + .absolute() + .inset_0() + .text_color(palette.text_muted) + .text_ellipsis() + .text_size(px(18.0)) + .line_height(px(28.0)) + .child("Search docs, tags, or commands…") + })) + .child(search_input_handler( + &self.input, + focus, + palette, + self.shell.clone(), + )), + ) + .into_any_element(); + + let viewport = window.viewport_size(); + let vp_w = f32::from(viewport.width); + let vp_h = f32::from(viewport.height); + let compact = vp_w < 640.0; + let width = if compact { + self.width + } else { + self.width.min(vp_w - 50.0) + }; + let height = list_height(&ends, content_height, vp_w, vp_h, self.height); + let top = if compact { + ((vp_h - INPUT_HEIGHT - height - LIST_PAD - 2.0) * 0.5).max(0.0) + } else { + modal_top(vp_h) + }; + let max_scroll = (content_height - height).max(0.0); + let theme = if palette.bg_canvas.l < 0.5 { + DARK_THEME + } else { + LIGHT_THEME + }; + let panel = rgba_to_hsla(theme.background_overlay_panel); + let scroll_y = qs.scroll_y.clamp(0.0, max_scroll); + let row_origin = scroll_y.round(); + let scroll_shell = self.shell.clone(); + let shell = self.shell; + div() + .absolute() + .inset_0() + .flex() + .flex_col() + .items_center() + .pt(px(top)) + .child( + div() + .id("desktop.qs.backdrop") + .snapshot("desktop.qs.backdrop", Some("desktop.shell.root")) + .absolute() + .inset_0() + .occlude() + .on_click(move |_, window, app| { + shell.update(app, |shell, cx| shell.dismiss_modal(window, cx)); + }), + ) + .child( + div() + .id("desktop.qs.modal") + .snapshot("desktop.qs.modal", Some("desktop.shell.root")) + .w(px(width)) + .flex() + .flex_col() + .occlude() + .rounded(px(12.0)) + .bg(panel) + .border_1() + .border_color(palette.border) + .shadow( + [BoxShadow::new(px(0.0), px(16.0), hsla(0.0, 0.0, 0.0, 0.22)) + .blur_radius(px(64.0))] + .into_iter() + .collect(), + ) + .font_family(FONT_SANS) + .child(input) + .child( + div() + .id("desktop.qs.results") + .relative() + .mx(px(6.0)) + .mb(px(LIST_PAD)) + .h(px(height)) + .overflow_hidden() + .on_scroll(move |event: &ui::ScrollEvent, _, app| { + let delta = f32::from(event.delta.pixel_delta(px(20.0)).y); + let next = (scroll_y - delta).clamp(0.0, max_scroll); + if next != scroll_y { + scroll_shell.update(app, |shell, cx| { + shell.state.quick_search.scroll_y = next; + cx.notify(); + }); + } + app.stop_propagation(); + }) + .children( + rows.into_iter() + .filter(|(offset, row_height, _)| { + let top = offset - row_origin; + top + row_height > 0.0 && top < height + }) + .map(|(offset, _, row)| { + div() + .absolute() + .top(px(offset - row_origin)) + .w_full() + .pr(px(6.0)) + .child(row) + }), + ) + .children((max_scroll > 0.0 && height > 0.0).then(|| { + let thumb = (height * height / content_height) + .clamp(16.0_f32.min(height), height); + div() + .absolute() + .right(px(0.0)) + .top(px((height - thumb) * scroll_y / max_scroll)) + .w(px(4.0)) + .h(px(thumb)) + .rounded(px(2.0)) + .bg(palette.border_strong) + })), + ), + ) + } +} + +fn updated_time(timestamp_ms: i64) -> String { + // Some older local documents store Unix seconds in the millisecond field. + let timestamp_ms = if (1_000_000_000..=4_102_444_800).contains(×tamp_ms) { + timestamp_ms * 1_000 + } else { + timestamp_ms + }; + format_database_created_time(timestamp_ms, 0) +} + +fn highlighted(text: String, query: &str, palette: DesktopPalette) -> StyledText { + let spans = if query.is_empty() { + Vec::new() + } else { + match_exact_substring_utf16(&text, query).map_or_else(Vec::new, |(_, spans)| spans) + }; + let highlights: Vec<_> = spans + .into_iter() + .map(|span| { + ( + utf16_to_byte(&text, span.start)..utf16_to_byte(&text, span.end), + HighlightStyle { + font_weight: Some(FontWeight::SEMIBOLD), + color: Some(palette.accent), + ..HighlightStyle::default() + }, + ) + }) + .collect(); + StyledText::new(text).with_highlights(highlights) +} + +#[cfg(test)] +mod tests { + use affine_store::directory::DocMode; + use ui::{ + AppContext, Application, ApplicationHandle, Bounds, HeadlessPlatform, HeadlessWindow, + WindowBounds, WindowHandle, WindowOptions, point, size, + }; + use ui_tokens::ThemeMode; + + use crate::{DesktopAppState, register_desktop_fonts}; + + use super::*; + + #[test] + fn quick_search_restricts_tag_queries_and_appends_named_create_actions() { + let store = DesktopDocStore::seed_showcase("2026-12-02"); + let mut qs = QuickSearchState::default(); + for query in ["#architecture", "tags."] { + qs.set_query(query); + let items = qs.items(&store); + assert!(items.ends_with(&[ + QuickSearchItem::Command(QuickCommandId::NewPage), + QuickSearchItem::Command(QuickCommandId::NewEdgeless), + ])); + if query.starts_with('#') { + assert!(items[..items.len() - 2].iter().any(|item| { + matches!(item, QuickSearchItem::Doc { summary, .. } if summary.contains(query)) + })); + } + } + } + + #[test] + fn quick_search_formats_legacy_and_current_update_times_consistently() { + assert_eq!(updated_time(1_764_300_950), updated_time(1_764_300_950_000)); + } + + fn open_test_shell() -> ( + ApplicationHandle, + WindowHandle, + HeadlessWindow, + ) { + 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("desktop 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| { + let state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + DesktopShellView::new(state, cx) + }) + }, + ) + .expect("desktop window") + }); + let window = platform + .windows() + .into_iter() + .next() + .expect("headless window"); + (app, handle, window) + } + + #[test] + fn quick_search_desktop_modal_uses_640_pixels_and_13_percent_top_inset() { + let (app, handle, window) = open_test_shell(); + app.update(|cx| { + handle + .update(cx, |shell, window, cx| shell.open_search(window, cx)) + .expect("desktop view"); + }); + window.request_frame(); + app.update(|cx| { + handle + .update(cx, |_, window, _| { + let modal = window.frame_snapshot().elements["desktop.qs.modal"].bounds; + assert_eq!(modal.width, 640.0); + assert_eq!(modal.y, 104.0); + }) + .expect("desktop view"); + }); + } + + #[test] + fn quick_search_submit_and_click_persist_the_query_as_document_title() { + let (app, handle, window) = open_test_shell(); + for (click, command, mode) in [ + (false, QuickCommandId::NewPage, DocMode::Page), + (true, QuickCommandId::NewEdgeless, DocMode::Edgeless), + ] { + let row = app.update(|cx| { + handle + .update(cx, |shell, window, cx| { + shell.open_search(window, cx); + shell.state.quick_search.set_query(" tags. "); + if click { + let items = shell.state.quick_search.items(&shell.state.store); + Some( + items + .iter() + .position(|item| *item == QuickSearchItem::Command(command)) + .expect("create action"), + ) + } else { + shell.submit_search_command(command, window, cx); + None + } + }) + .expect("desktop view") + }); + if let Some(row) = row { + window.request_frame(); + let click_at = app.update(|cx| { + handle + .update(cx, |_, window, _| { + let id = format!("desktop.qs.cmd.{row}"); + let bounds = window.frame_snapshot().elements[id.as_str()].bounds; + point( + px(bounds.x + bounds.width * 0.5), + px(bounds.y + bounds.height * 0.5), + ) + }) + .expect("desktop view") + }); + window.simulate_click(click_at); + window.request_frame(); + } + + app.update(|cx| { + handle + .update(cx, |shell, _, _| { + let route = shell.state.split.active().active_route(); + let id = route.doc_id().expect("new document route"); + let entry = shell.state.store.get_doc(id).expect("new document"); + assert_eq!(entry.meta.title, "tags."); + assert_eq!(entry.meta.default_mode, mode); + assert_eq!( + entry + .session + .read_page_snapshot() + .expect("document snapshot") + .title(), + "tags." + ); + assert!(!shell.state.quick_search.open); + }) + .expect("desktop view"); + }); + } + } +} diff --git a/packages/frontend/desktop/src/workbench/search_input.rs b/packages/frontend/desktop/src/workbench/search_input.rs index dd33ba1ecb..f2d2c4e9f0 100644 --- a/packages/frontend/desktop/src/workbench/search_input.rs +++ b/packages/frontend/desktop/src/workbench/search_input.rs @@ -40,7 +40,7 @@ impl SearchLine { }; let line = window .text_system() - .shape_line(text, px(14.0), &[run], None); + .shape_line(text, px(18.0), &[run], None); let caret_x = line.x_for_index(utf16_to_byte(&line.text, caret)); let room = (bounds.size.width - px(1.0)).max(px(0.0)); let scroll = (caret_x - room).max(px(0.0)); @@ -155,35 +155,26 @@ impl DesktopShellView { "escape" => self.dismiss_modal(window, cx), "up" | "down" => { let qs = &mut self.state.quick_search; - let items = qs.items(&self.state.store); + let items = qs.items_with_split(&self.state.store, &self.state.split); qs.move_selection(if key == "up" { -1 } else { 1 }, items.len()); - let doc_count = items - .iter() - .take_while(|item| matches!(item, QuickSearchItem::Doc { .. })) - .count(); - qs.reveal_selection( - doc_count, - modal_size( - window.viewport_size().width.into(), - window.viewport_size().height.into(), - QUICK_SEARCH_HEIGHT, - ) - .1, - ); + let vw = window.viewport_size().width.into(); + let vh = window.viewport_size().height.into(); + qs.reveal_selection(&items, vw, vh, modal_size(vw, vh, QUICK_SEARCH_HEIGHT).1); cx.notify(); } "enter" => { - self.editor_host.sync_all(&mut self.state.store, cx); let qs = &self.state.quick_search; - match qs - .items(&self.state.store) - .into_iter() - .nth(qs.selected_index) - { + let items = qs.items_with_split(&self.state.store, &self.state.split); + let index = qs.selected_index.min(items.len().saturating_sub(1)); + let selected = items.into_iter().nth(index); + self.sync_editors(cx); + match selected { Some(QuickSearchItem::Doc { doc_id, .. }) => { self.open_search_result(&doc_id, command, window, cx); } - Some(QuickSearchItem::Command(cmd)) => self.run_search_command(cmd, window, cx), + Some(QuickSearchItem::Command(cmd)) => { + self.submit_search_command(cmd, window, cx); + } None => {} } } @@ -218,9 +209,8 @@ pub(crate) fn search_input_handler( input: &Utf16ImeBuffer, focus: FocusHandle, palette: DesktopPalette, - cx: &Context, + entity: ui::Entity, ) -> impl IntoElement + use<> { - let entity = cx.entity(); let shown = input.display_text().into(); let (selection, reversed) = input.shown_selection(); let caret = if reversed { @@ -588,6 +578,215 @@ mod tests { } } + #[test] + fn quick_search_recent_uses_visits_and_opens_the_first_result() { + use std::collections::HashSet; + + use affine_store::directory::DocMode; + + for click in [false, true] { + let app = TestShell::new(1280, 800); + let (id, updated_at) = app.shell(|shell, _, cx| { + for i in 0..8 { + shell.state.store.create_doc( + format!("Search fixture {i}"), + DocMode::Page, + None, + 1_764_310_000_000 + i, + ); + } + let id = shell.state.store.search_docs("", 8)[7].doc_id.clone(); + let updated_at = shell + .state + .store + .get_doc(&id) + .expect("document") + .meta + .updated_at_ms; + shell.state.open_doc_in_active_pane(&id); + cx.notify(); + (id, updated_at) + }); + app.frame(); + app.click("desktop.sidebar.quick_search"); + let row = format!("desktop.qs.doc.{id}"); + app.shell(|shell, window, _| { + let state = &shell.state; + let items = state + .quick_search + .items_with_split(&state.store, &state.split); + assert!(matches!( + &items[0], + QuickSearchItem::Doc { doc_id, recent: true, .. } if doc_id == &id + )); + let mut docs = HashSet::new(); + let mut recent_count = 0; + for item in items { + if let QuickSearchItem::Doc { doc_id, recent, .. } = item { + assert!(docs.insert(doc_id)); + recent_count += usize::from(recent); + } + } + assert_eq!(docs.len(), 8); + assert_eq!(recent_count, 2); + let snapshot = window.frame_snapshot(); + assert_eq!( + snapshot.elements[row.as_str()].bounds.y, + snapshot.elements["desktop.qs.input"].bounds.y + 66.0 + 36.0 + ); + }); + app.key("escape"); + app.click("desktop.sidebar.all_docs"); + app.click("desktop.sidebar.quick_search"); + if click { + app.click(&row); + } else { + app.key("enter"); + } + app.shell(|shell, _, _| { + assert_eq!( + shell.state.split.active().active_route().doc_id(), + Some(id.as_str()) + ); + assert_eq!( + shell + .state + .store + .get_doc(&id) + .expect("document") + .meta + .updated_at_ms, + updated_at + ); + assert!(!shell.state.quick_search.open); + }); + } + } + + #[test] + fn quick_search_clips_a_partial_row_and_its_visible_area_opens_the_document() { + let app = TestShell::new(1280, 800); + app.click("desktop.sidebar.all_docs"); + app.click("desktop.sidebar.quick_search"); + app.shell(|shell, _, cx| { + shell.state.quick_search.scroll_y = 37.0; + cx.notify(); + }); + app.frame(); + let (id, click) = app.shell(|shell, window, _| { + let state = &shell.state; + let items = state + .quick_search + .items_with_split(&state.store, &state.split); + let QuickSearchItem::Doc { doc_id, .. } = &items[0] else { + panic!("first result must be a document"); + }; + let row = + &window.frame_snapshot().elements[format!("desktop.qs.doc.{doc_id}").as_str()]; + assert_eq!(row.bounds.height, 44.0); + assert_eq!(row.content_mask.y, row.bounds.y + 1.0); + assert_eq!(row.bounds.y + row.bounds.height - row.content_mask.y, 43.0); + ( + doc_id.clone(), + point(px(row.bounds.x + 12.0), px(row.content_mask.y + 5.0)), + ) + }); + app.window.simulate_click(click); + app.frame(); + app.shell(|shell, _, _| { + assert_eq!( + shell.state.split.active().active_route().doc_id(), + Some(id.as_str()) + ); + assert!(!shell.state.quick_search.open); + }); + } + + #[test] + fn quick_search_arrow_keys_reveal_each_result_in_a_short_desktop_window() { + let app = TestShell::new(800, 300); + app.click("desktop.sidebar.quick_search"); + let row_ids = app.shell(|shell, _, _| { + let state = &shell.state; + state + .quick_search + .items_with_split(&state.store, &state.split) + .into_iter() + .enumerate() + .map(|(index, item)| match item { + QuickSearchItem::Doc { doc_id, .. } => format!("desktop.qs.doc.{doc_id}"), + QuickSearchItem::Command(_) => format!("desktop.qs.cmd.{index}"), + }) + .collect::>() + }); + assert_eq!(row_ids.len(), 10); + for (index, id) in row_ids + .iter() + .enumerate() + .cycle() + .skip(1) + .take(row_ids.len()) + { + app.key("down"); + app.shell(|shell, window, _| { + assert_eq!(shell.state.quick_search.selected_index, index); + let row = &window.frame_snapshot().elements[id.as_str()]; + assert!(row.bounds.y >= row.content_mask.y, "{id}"); + assert!( + row.bounds.y + row.bounds.height + <= row.content_mask.y + row.content_mask.height, + "{id}" + ); + }); + } + } + + #[test] + fn quick_search_arrow_and_enter_create_a_page_with_the_query_title() { + use crate::quick_search::QuickCommandId; + + let app = TestShell::new(1280, 800); + app.click("desktop.sidebar.quick_search"); + app.input(|handler| handler.replace_text_in_range(None, "Quarterly Spec")); + app.key("down"); + app.key("up"); + app.shell(|shell, _, _| { + let state = &shell.state; + let items = state + .quick_search + .items_with_split(&state.store, &state.split); + assert_eq!( + items[state.quick_search.selected_index], + QuickSearchItem::Command(QuickCommandId::NewPage) + ); + }); + app.key("enter"); + app.shell(|shell, _, _| { + let state = &shell.state; + let id = state + .split + .active() + .active_route() + .doc_id() + .expect("active document"); + let entry = state.store.get_doc(id).expect("created document"); + assert_eq!(entry.meta.title, "Quarterly Spec"); + assert_eq!( + entry.meta.default_mode, + affine_store::directory::DocMode::Page + ); + assert_eq!( + entry + .session + .read_page_snapshot() + .expect("document snapshot") + .title(), + "Quarterly Spec" + ); + assert!(!state.quick_search.open); + }); + } + #[test] fn narrow_quick_search_preserves_the_drawer_on_cancel_and_closes_it_on_navigation() { for confirm in ["enter", "click"] {