diff --git a/blocksuite/crates/playground/src/editor_session/commands.rs b/blocksuite/crates/playground/src/editor_session/commands.rs index b1e840440d..8a917e1ad2 100644 --- a/blocksuite/crates/playground/src/editor_session/commands.rs +++ b/blocksuite/crates/playground/src/editor_session/commands.rs @@ -7,7 +7,7 @@ use ui::{EntityInputHandler, KeyDownEvent}; use y_octo::{Any, TextAttributes, TextDeltaOp}; use super::*; -use crate::overlays::LinkBar; +use crate::overlays::{LinkBar, LinkPopupAction, LinkPopupTarget, OverlayEvent}; use crate::rich_text::TextBiIndex; #[cfg(test)] @@ -685,6 +685,7 @@ impl PlaygroundView { cx.stop_propagation(); return; } + let link_shortcut = cmd || (self.hide_chrome && (m.platform || m.control)); let result = match key { "escape" => { if let Some(sel) = self.editor.selection.as_ref() @@ -727,8 +728,33 @@ impl PlaygroundView { self.run_selection_select_all(None, w, cx); Ok(()) } - "k" if cmd && !m.alt && !m.shift && !page_ro => { - self.open_link_bar_shortcut(w, cx); + "k" if link_shortcut && !m.alt && !m.shift && !page_ro => { + if self.hide_chrome + && self + .editor + .selection + .as_ref() + .is_none_or(|selection| selection.empty()) + { + let now = self.now_ms(cx); + if let Some(layout) = self.flow_layout() { + self.sync_link_popup_for_caret(&layout, now); + } + if self.overlays.link_popup().is_some_and(|popup| { + !popup.from_hover && matches!(popup.target, LinkPopupTarget::Link { .. }) + }) { + self.dispatch_overlay( + OverlayEvent::LinkPopupAction(LinkPopupAction::Edit), + w, + cx, + ); + } + } else { + self.open_link_bar_shortcut(w, cx); + } + if self.hide_chrome && self.link_input_state().is_none() { + return; + } Ok(()) } "c" | "x" if cmd => { diff --git a/packages/frontend/desktop/src/quick_search.rs b/packages/frontend/desktop/src/quick_search.rs index fadd8e26cb..91e8ad31cb 100644 --- a/packages/frontend/desktop/src/quick_search.rs +++ b/packages/frontend/desktop/src/quick_search.rs @@ -1,16 +1,18 @@ //! `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::{ - Context, FontWeight, InteractiveElement, IntoElement, ParentElement, - StatefulInteractiveElement, Styled, div, px, svg, + 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, + doc_store::DesktopDocStore, + workbench::{DesktopShellView, backdrop, search_input_handler}, }; /// Built-in command actions available from `Cmd/Ctrl+K`. @@ -76,12 +78,14 @@ pub struct QuickSearchState { 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; } @@ -89,6 +93,7 @@ impl QuickSearchState { pub fn close(&mut self) { self.open = false; self.query.clear(); + self.text_bounds = None; self.selected_index = 0; self.scroll_y = 0.0; } @@ -133,15 +138,44 @@ impl QuickSearchState { } } +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() @@ -154,18 +188,24 @@ pub(crate) fn render_quick_search_modal( .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() - .gap(px(4.0)) - .mt(px(-qs.scroll_y)); + .mt(px(-qs.scroll_y.min(max_scroll))); if !doc_items.is_empty() { list = list.child( div() .px(px(12.0)) - .py(px(4.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) @@ -195,17 +235,18 @@ pub(crate) fn render_quick_search_modal( .justify_between() .w_full() .px(px(12.0)) - .py(px(8.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, _, _, cx| { - this.state.open_doc_in_active_pane(&doc_id_click); - this.state.quick_search.close(); - cx.notify(); + .on_click(cx.listener(move |this, _, window, cx| { + this.sync_editors(cx); + this.open_search_result(&doc_id_click, false, window, cx); })) .child( div() @@ -247,13 +288,19 @@ pub(crate) fn render_quick_search_modal( .min_w_0() .child( div() + .text_ellipsis() .text_size(px(13.5)) .font_weight(FontWeight::MEDIUM) .text_color(palette.text_primary) - .child(title.clone()), + .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()), @@ -267,12 +314,13 @@ pub(crate) fn render_quick_search_modal( .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, _, _, cx| { - this.state.open_doc_in_split(&doc_id_split); - this.state.quick_search.close(); - cx.notify(); + .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"), ), @@ -285,8 +333,10 @@ pub(crate) fn render_quick_search_modal( list = list.child( div() .px(px(12.0)) - .pt(px(8.0)) - .pb(px(4.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) @@ -312,17 +362,18 @@ pub(crate) fn render_quick_search_modal( .justify_between() .w_full() .px(px(12.0)) - .py(px(8.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, _, _, cx| { - this.state.execute_quick_command(cmd_copy); - this.state.quick_search.close(); - cx.notify(); + .on_click(cx.listener(move |this, _, window, cx| { + this.sync_editors(cx); + this.run_search_command(cmd_copy, window, cx); })) .child( div() @@ -330,6 +381,7 @@ pub(crate) fn render_quick_search_modal( .flex_row() .items_center() .gap(px(10.0)) + .min_w_0() .child( svg() .data(icon_bytes) @@ -339,6 +391,8 @@ pub(crate) fn render_quick_search_modal( ) .child( div() + .min_w_0() + .text_ellipsis() .text_size(px(13.5)) .text_color(palette.text_primary) .child(cmd_copy.label()), @@ -350,6 +404,7 @@ pub(crate) fn render_quick_search_modal( .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()), @@ -370,34 +425,32 @@ pub(crate) fn render_quick_search_modal( ); } - let query_display = if qs.query.is_empty() { - "Search documents, tags, or type a command...".to_string() - } else { - qs.query.clone() - }; - let query_color = if qs.query.is_empty() { - palette.text_muted - } else { - palette.text_primary - }; + let focus = focus.clone(); div() - .id("desktop.qs.backdrop") .absolute() - .top(px(0.0)) - .left(px(0.0)) + .top_0() + .left_0() .w_full() .h_full() - .bg(palette.scrim) .flex() - .flex_col() .items_center() - .pt(px(56.0)) + .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(640.0)) + .w(px(width)) + .h(px(height)) + .occlude() + .overflow_hidden() .rounded(px(38.0)) .bg(palette.bg_elevated) .border_1() @@ -434,9 +487,8 @@ pub(crate) fn render_quick_search_modal( .flex() .items_center() .justify_center() - .on_click(cx.listener(|this, _, _, cx| { - this.state.quick_search.close(); - cx.notify(); + .on_click(cx.listener(|this, _, window, cx| { + this.dismiss_modal(window, cx); })) .child( svg() @@ -452,6 +504,17 @@ pub(crate) fn render_quick_search_modal( 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() @@ -467,14 +530,27 @@ pub(crate) fn render_quick_search_modal( .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)) - .text_color(query_color) - .child(query_display), + .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( @@ -482,20 +558,16 @@ pub(crate) fn render_quick_search_modal( div() .id("desktop.qs.results") .w_full() - .h(px(360.0)) + .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(|this, event: &ui::ScrollEvent, _, cx| { + .on_scroll(cx.listener(move |this, event: &ui::ScrollEvent, _, cx| { let dy: f32 = event.delta.pixel_delta(px(20.0)).y.into(); - let max_scroll = - (this.state.quick_search.items(&this.state.store).len() as f32 - * 52.0 - - 300.0) - .max(0.0); this.state.quick_search.scroll_y = (this.state.quick_search.scroll_y - dy).clamp(0.0, max_scroll); cx.notify(); @@ -508,11 +580,15 @@ pub(crate) fn render_quick_search_modal( .flex_row() .items_center() .justify_between() - .pt(px(6.0)) - .px(px(8.0)) + .gap(px(8.0)) + .px(px(4.0)) .text_size(px(11.5)) .text_color(palette.text_muted) - .child("↑↓ Navigate ↵ Open ⌘↵ Split View Esc Close") + .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 { diff --git a/packages/frontend/desktop/src/settings_modal.rs b/packages/frontend/desktop/src/settings_modal.rs index 5b86b9b8d4..fcb2cfc0ad 100644 --- a/packages/frontend/desktop/src/settings_modal.rs +++ b/packages/frontend/desktop/src/settings_modal.rs @@ -3,7 +3,7 @@ //! three-state `System / Light / Dark` theme switcher, and independent wheel scrolling. use ui::{ - Context, FontWeight, InteractiveElement, IntoElement, ParentElement, ScrollEvent, + Context, FocusHandle, FontWeight, InteractiveElement, IntoElement, ParentElement, StatefulInteractiveElement, Styled, div, px, svg, }; use ui_tokens::FONT_SANS; @@ -13,7 +13,7 @@ use crate::{ doc_store::DesktopDocStore, draft_store::{ComposerDraftStore, DesktopDraftBackend}, state::ThemePreference, - workbench::DesktopShellView, + workbench::{DesktopShellView, backdrop}, }; fn info_row(label: &'static str, value: String, palette: DesktopPalette) -> ui::Div { @@ -22,6 +22,8 @@ fn info_row(label: &'static str, value: String, palette: DesktopPalette) -> ui:: .flex_row() .items_center() .justify_between() + .flex_wrap() + .gap(px(4.0)) .w_full() .py(px(4.0)) .child( @@ -35,6 +37,8 @@ fn info_row(label: &'static str, value: String, palette: DesktopPalette) -> ui:: .text_size(px(12.5)) .font_weight(FontWeight::MEDIUM) .text_color(palette.text_primary) + .min_w_0() + .text_ellipsis() .child(value), ) } @@ -77,9 +81,10 @@ fn theme_pill( /// Render the centered `Settings` modal (Appearance `System/Light/Dark`, Workspace & Local Drafts). pub(crate) fn render_settings_modal( pref: ThemePreference, - scroll_y: f32, store: &DesktopDocStore, draft_store: &ComposerDraftStore, + focus: &FocusHandle, + (width, height): (f32, f32), palette: DesktopPalette, cx: &mut Context, ) -> impl IntoElement { @@ -89,7 +94,7 @@ pub(crate) fn render_settings_modal( .flex_col() .w_full() .gap(px(12.0)) - .mt(px(-scroll_y)) + .flex_shrink(0.0) .child( // Concentric inner card: R_inner = 38 - 16 = 22px div() @@ -112,6 +117,8 @@ pub(crate) fn render_settings_modal( div() .flex() .flex_row() + .flex_wrap() + .gap(px(8.0)) .items_center() .justify_between() .child( @@ -186,29 +193,51 @@ pub(crate) fn render_settings_modal( draft_store.draft_count().to_string(), palette, )) - .child(info_row( - "SHA-256 Deduplicated Blobs", - draft_store.attachment_count().to_string(), - palette, - )), + .child( + info_row( + "SHA-256 Deduplicated Blobs", + draft_store.attachment_count().to_string(), + palette, + ) + .snapshot( + "desktop.settings.deduplicated_blobs", + Some("desktop.settings.modal"), + ), + ), ); + let mut scroll = div() + .id("desktop.settings.scroll") + .w_full() + .flex_1() + .min_h_0(); + scroll.style().overflow.y = Some(ui::Overflow::Scroll); + div() - .id("desktop.settings.backdrop") .absolute() - .top(px(0.0)) - .left(px(0.0)) + .top_0() + .left_0() .w_full() .h_full() - .bg(palette.scrim) .flex() .items_center() .justify_center() + .child(backdrop( + "desktop.settings.backdrop", + palette, + cx.listener(|this, _, window, cx| { + this.dismiss_modal(window, cx); + }), + )) .child( div() .id("desktop.settings.modal") .snapshot("desktop.settings.modal", Some("desktop.shell.root")) - .w(px(640.0)) + .w(px(width)) + .h(px(height)) + .track_focus(focus) + .occlude() + .overflow_hidden() .rounded(px(38.0)) .bg(palette.bg_elevated) .border_1() @@ -244,9 +273,8 @@ pub(crate) fn render_settings_modal( .flex() .items_center() .justify_center() - .on_click(cx.listener(|this, _, _, cx| { - this.state.close_modal(); - cx.notify(); + .on_click(cx.listener(|this, _, window, cx| { + this.dismiss_modal(window, cx); })) .child( svg() @@ -257,19 +285,6 @@ pub(crate) fn render_settings_modal( ), ), ) - .child( - div() - .id("desktop.settings.scroll") - .w_full() - .h(px(360.0)) - .overflow_hidden() - .on_scroll(cx.listener(|this, event: &ScrollEvent, _, cx| { - let dy: f32 = event.delta.pixel_delta(px(20.0)).y.into(); - this.state.settings_scroll_y = - (this.state.settings_scroll_y - dy).clamp(0.0, 240.0); - cx.notify(); - })) - .child(content), - ), + .child(scroll.child(content)), ) } diff --git a/packages/frontend/desktop/src/sidebar.rs b/packages/frontend/desktop/src/sidebar.rs index 0326df97c1..3a267fc562 100644 --- a/packages/frontend/desktop/src/sidebar.rs +++ b/packages/frontend/desktop/src/sidebar.rs @@ -5,7 +5,7 @@ use std::collections::BTreeSet; use ui::{ - Context, FontWeight, InteractiveElement, IntoElement, ParentElement, + Context, FontWeight, InteractiveElement, IntoElement, MouseButton, ParentElement, StatefulInteractiveElement, Styled, div, prelude::FluentBuilder as _, px, svg, }; use ui_tokens::FONT_SANS; @@ -92,6 +92,7 @@ impl SidebarState { } pub(crate) fn clip_label(s: &str, max: usize) -> String { + let s = if s.is_empty() { "Untitled" } else { s }; let mut it = s.chars(); let head: String = it.by_ref().take(max).collect(); if it.next().is_some() { @@ -108,10 +109,11 @@ pub(crate) fn render_sidebar( store: &DesktopDocStore, rows: &mut SidebarRowIndex, active_route: &DesktopRoute, + width: f32, viewport_height: f32, palette: DesktopPalette, cx: &mut Context, -) -> impl IntoElement { +) -> impl IntoElement + use<> { let ws = store.active_workspace(); let trash_count = store.views().trashed.len(); let tree_col = render_tree_rows( @@ -213,9 +215,9 @@ pub(crate) fn render_sidebar( .bg(palette.bg_elevated) .border_1() .border_color(palette.border) - .on_click(cx.listener(|this, _, _, cx| { - this.state.open_quick_search(); - cx.notify(); + .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default()) + .on_click(cx.listener(|this, _, window, cx| { + this.open_search(window, cx); })) .child( div() @@ -391,16 +393,16 @@ pub(crate) fn render_sidebar( palette, ) .snapshot("desktop.sidebar.settings", Some("desktop.sidebar")) - .on_click(cx.listener(|this, _, _, cx| { - this.state.open_settings(); - cx.notify(); + .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default()) + .on_click(cx.listener(|this, _, window, cx| { + this.open_settings(window, cx); })), ); div() .id("desktop.sidebar") .snapshot("desktop.sidebar", Some("desktop.shell.root")) - .w(px(sidebar.width)) + .w(px(width)) .h_full() .flex_shrink(0.0) .bg(palette.bg_sidebar) diff --git a/packages/frontend/desktop/src/split_view.rs b/packages/frontend/desktop/src/split_view.rs index b6cabfc0fc..2f51763225 100644 --- a/packages/frontend/desktop/src/split_view.rs +++ b/packages/frontend/desktop/src/split_view.rs @@ -203,11 +203,11 @@ impl PaneState { return false; } self.tabs.remove(idx); - if self.active_tab >= self.tabs.len() { - self.active_tab = self.tabs.len() - 1; + if idx < self.active_tab { + self.active_tab -= 1; + } else if idx == self.active_tab { + self.select_tab(idx.min(self.tabs.len() - 1)); } - self.scroll_y = 0.0; - self.edgeless.camera_initialized = false; true } diff --git a/packages/frontend/desktop/src/state.rs b/packages/frontend/desktop/src/state.rs index 4f4799df27..8503a79abf 100644 --- a/packages/frontend/desktop/src/state.rs +++ b/packages/frontend/desktop/src/state.rs @@ -72,7 +72,6 @@ pub struct DesktopAppState { pub peek_view: PeekViewState, pub inspector_tab: Option, pub modal: Option, - pub settings_scroll_y: f32, } impl DesktopAppState { @@ -217,7 +216,6 @@ impl DesktopAppState { peek_view: PeekViewState::default(), inspector_tab: None, modal: None, - settings_scroll_y: 0.0, } } @@ -342,7 +340,7 @@ impl DesktopAppState { } let now = self.tick_ms(); let title = match mode { - DocMode::Page => format!("Untitled Page {}", self.store.docs.len() + 1), + DocMode::Page => String::new(), DocMode::Edgeless => format!("Untitled Board {}", self.store.docs.len() + 1), }; let id = self.store.create_doc(title, mode, None, now); @@ -501,8 +499,8 @@ impl DesktopAppState { DesktopRoute::Doc(id) => self .store .get_doc(id) - .map(|e| e.meta.title.clone()) - .unwrap_or_else(|| "Untitled".to_string()), + .filter(|e| !e.meta.title.is_empty()) + .map_or_else(|| "Untitled".to_string(), |e| e.meta.title.clone()), DesktopRoute::AllDocs => "All Docs".to_string(), DesktopRoute::Favorites => "Favorites".to_string(), DesktopRoute::Journals => "Journals".to_string(), @@ -563,6 +561,20 @@ mod tests { assert!(state.store.get_doc(&doc_id).is_none()); } + #[test] + fn new_page_stores_an_empty_title_and_displays_untitled() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + let id = state.create_new_doc(DocMode::Page); + let doc = state.store.get_doc(&id).expect("new page"); + assert!(doc.meta.title.is_empty()); + let (title, _) = doc.session.read_editable_text("root").expect("page title"); + assert!(title.is_empty()); + assert_eq!( + state.route_title(state.split.active().active_route()), + "Untitled" + ); + } + #[test] fn split_view_shares_live_crdt_doc_across_page_and_edgeless_panes() { let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-11-28"); diff --git a/packages/frontend/desktop/src/workbench/interaction.rs b/packages/frontend/desktop/src/workbench/interaction.rs new file mode 100644 index 0000000000..d174d800ac --- /dev/null +++ b/packages/frontend/desktop/src/workbench/interaction.rs @@ -0,0 +1,377 @@ +use ui::{ + ClickEvent, Context, CursorStyle, DispatchPhase, FocusHandle, InteractiveElement, IntoElement, + KeyDownEvent, MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement, + StatefulInteractiveElement, Styled, Window, canvas, div, px, svg, +}; + +use crate::{ + CLOSE_ICON_SVG, DesktopFlexExt, DesktopModal, DesktopPalette, quick_search::QuickCommandId, +}; + +use super::DesktopShellView; + +impl DesktopShellView { + fn focus_modal(&mut self, focus: &FocusHandle, window: &mut Window, cx: &mut Context) { + if self.modal_return_focus.is_none() { + self.modal_return_focus = window + .focused(cx) + .or_else(|| Some(self.focus_handle.clone())); + } + window.focus(focus, cx); + } + + pub(super) fn update_shell_focus( + &mut self, + modal: Option, + window: &mut Window, + cx: &mut Context, + ) { + if let Some(focus) = modal { + self.focus_modal(&focus, window, cx); + } else if let Some(restore) = self.modal_return_focus.take() { + window.focus(&restore, cx); + } else if window.focused(cx).is_none() { + window.focus(&self.focus_handle, cx); + } + } + + pub(crate) fn open_search(&mut self, window: &mut Window, cx: &mut Context) { + self.state.open_quick_search(); + self.sync_search_input(); + self.focus_modal(&self.quick_search_focus.clone(), window, cx); + cx.notify(); + } + + pub(crate) fn open_settings(&mut self, window: &mut Window, cx: &mut Context) { + self.state.open_settings(); + self.focus_modal(&self.settings_focus.clone(), window, cx); + cx.notify(); + } + + pub(crate) fn dismiss_modal(&mut self, window: &mut Window, cx: &mut Context) { + self.state.quick_search.close(); + self.state.close_modal(); + self.update_shell_focus(None, window, cx); + cx.notify(); + } + + pub(crate) fn open_search_result( + &mut self, + doc_id: &str, + split: bool, + window: &mut Window, + cx: &mut Context, + ) { + if split { + self.state.open_doc_in_split(doc_id); + } else { + self.state.open_doc_in_active_pane(doc_id); + } + self.finish_search(true, window, cx); + } + + pub(crate) fn run_search_command( + &mut self, + command: QuickCommandId, + window: &mut Window, + cx: &mut Context, + ) { + use affine_store::directory::DocMode; + + let navigated = match command { + QuickCommandId::NewPage => !self.state.create_new_doc(DocMode::Page).is_empty(), + QuickCommandId::NewEdgeless => !self.state.create_new_doc(DocMode::Edgeless).is_empty(), + QuickCommandId::OpenTodayJournal => !self.state.open_today_journal().is_empty(), + QuickCommandId::ToggleTheme + | QuickCommandId::ToggleSidebar + | QuickCommandId::SplitView => { + self.state.execute_quick_command(command); + command == QuickCommandId::SplitView + } + }; + self.finish_search(navigated, window, cx); + } + + fn finish_search(&mut self, close_drawer: bool, window: &mut Window, cx: &mut Context) { + if close_drawer && self.docked_sidebar_open.is_some() { + self.state.sidebar.open = false; + } + self.modal_return_focus = Some(self.focus_handle.clone()); + self.dismiss_modal(window, cx); + } + + pub(super) fn capture_modal_key( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + if self.state.quick_search.open { + if self.handle_search_key(event, window, cx) { + window.prevent_default(); + cx.stop_propagation(); + } + } else if matches!(self.state.modal, Some(DesktopModal::Settings)) { + if event.keystroke.key == "escape" { + self.dismiss_modal(window, cx); + } + window.prevent_default(); + cx.stop_propagation(); + } else if self.docked_sidebar_open.is_some() + && self.state.sidebar.open + && event.keystroke.key == "escape" + { + self.state.sidebar.open = false; + window.prevent_default(); + cx.stop_propagation(); + cx.notify(); + } + } + + pub(super) fn handle_key_down( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + if self.state.quick_search.open { + return; + } + let key = event.keystroke.key.as_str(); + if self.state.peek_view.is_open() { + if key == "escape" { + self.state.peek_view.close(); + window.prevent_default(); + cx.stop_propagation(); + cx.notify(); + } + return; + } + + let modifiers = event.keystroke.modifiers; + if !(modifiers.platform || modifiers.control) || modifiers.alt { + return; + } + let command = match (key, modifiers.shift) { + ("n", false) => QuickCommandId::NewPage, + ("n", true) => QuickCommandId::NewEdgeless, + ("l", true) => QuickCommandId::ToggleTheme, + ("j", false) => QuickCommandId::OpenTodayJournal, + ("/", false) => QuickCommandId::ToggleSidebar, + ("\\", false) => QuickCommandId::SplitView, + ("k", false) => { + self.open_search(window, cx); + window.prevent_default(); + cx.stop_propagation(); + return; + } + ("[" | "]", false) => { + let pane = self.state.split.active_mut(); + if key == "[" { + pane.go_back(); + } else { + pane.go_forward(); + } + window.prevent_default(); + cx.stop_propagation(); + cx.notify(); + return; + } + _ => return, + }; + self.editor_host.sync_all(&mut self.state.store, cx); + self.state.execute_quick_command(command); + window.prevent_default(); + cx.stop_propagation(); + cx.notify(); + } +} + +pub(crate) fn modal_size(viewport_w: f32, viewport_h: f32, height: f32) -> (f32, f32) { + ( + (viewport_w - 32.0).clamp(0.0, 640.0), + (viewport_h - 32.0).clamp(0.0, height), + ) +} + +pub(crate) fn backdrop( + id: &'static str, + palette: DesktopPalette, + dismiss: impl Fn(&ClickEvent, &mut Window, &mut ui::App) + 'static, +) -> ui::Stateful { + div() + .id(id) + .absolute() + .top_0() + .left_0() + .w_full() + .h_full() + .snapshot(id, Some("desktop.shell.root")) + .occlude() + .bg(palette.scrim) + .on_click(dismiss) +} + +pub(super) fn close_tab_button( + pane: usize, + tab: usize, + palette: DesktopPalette, + cx: &mut Context, +) -> impl IntoElement + use<> { + let id = format!("desktop.pane.{pane}.tab.{tab}.close"); + div() + .id(ui::SharedString::from(id.clone())) + .snapshot(id, Some("desktop.workbench")) + .w(px(24.0)) + .h(px(24.0)) + .flex_shrink(0.0) + .flex() + .items_center() + .justify_center() + .rounded(px(5.0)) + .cursor_pointer() + .tab_index(0) + .hover(move |s| s.bg(palette.bg_active)) + .focus_visible(move |s| s.bg(palette.bg_active)) + .on_click(cx.listener(move |this, _, window, cx| { + cx.stop_propagation(); + this.editor_host.sync_all(&mut this.state.store, cx); + if let Some(pane) = this.state.split.panes.get_mut(pane) + && pane.close_tab(tab) + { + window.focus(&this.focus_handle, cx); + cx.notify(); + } + })) + .child( + svg() + .data(CLOSE_ICON_SVG) + .w(px(12.0)) + .h(px(12.0)) + .text_color(palette.text_muted), + ) +} + +#[derive(Clone, Copy)] +pub(super) enum ResizeTarget { + Sidebar, + Split(f32), +} + +#[derive(Clone, Copy)] +pub(super) struct ResizeDrag { + target: ResizeTarget, + pointer_x: f32, + start: f32, +} + +impl ResizeDrag { + fn apply(self, position: f32, shell: &mut DesktopShellView) { + let delta = position - self.pointer_x; + match self.target { + ResizeTarget::Sidebar => shell.state.sidebar.set_width(self.start + delta), + ResizeTarget::Split(width) => shell + .state + .split + .set_split_ratio(self.start + delta / width), + } + } +} + +pub(super) fn resize_handle( + target: ResizeTarget, + x: f32, + top: f32, + palette: DesktopPalette, + cx: &mut Context, +) -> impl IntoElement + use<> { + let id = match target { + ResizeTarget::Sidebar => "desktop.sidebar.resize", + ResizeTarget::Split(_) => "desktop.split.resize", + }; + div() + .id(id) + .snapshot(id, Some("desktop.shell.root")) + .absolute() + .top(px(top)) + .bottom(px(0.0)) + .left(px((x - 4.0).max(0.0))) + .w(px(8.0)) + .occlude() + .cursor(CursorStyle::ResizeColumn) + .hover(move |style| style.bg(palette.accent_soft)) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &ui::MouseDownEvent, _, cx| { + let start = match target { + ResizeTarget::Sidebar => x, + ResizeTarget::Split(_) => this.state.split.split_ratio, + }; + this.resize = Some(ResizeDrag { + target, + pointer_x: event.position.x.into(), + start, + }); + cx.stop_propagation(); + cx.notify(); + }), + ) +} + +pub(super) fn resize_capture( + active: bool, + cx: &Context, +) -> impl IntoElement + use<> { + let on_move = cx.listener(|this, event: &MouseMoveEvent, _, cx| { + if let Some(drag) = this.resize { + if event.pressed_button == Some(MouseButton::Left) { + drag.apply(event.position.x.into(), this); + } else { + this.resize = None; + } + cx.stop_propagation(); + cx.notify(); + } + }); + let on_up = cx.listener(|this, event: &MouseUpEvent, _, cx| { + if let Some(drag) = this.resize.take() { + drag.apply(event.position.x.into(), this); + cx.stop_propagation(); + cx.notify(); + } + }); + div() + .absolute() + .top_0() + .left_0() + .w_full() + .h_full() + .children(active.then(|| { + div() + .absolute() + .top_0() + .left_0() + .w_full() + .h_full() + .occlude() + .cursor(CursorStyle::ResizeColumn) + })) + .child( + canvas( + |_, _, _| (), + move |_, (), window, _| { + window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { + if phase == DispatchPhase::Capture { + on_move(event, window, cx); + } + }); + window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| { + if phase == DispatchPhase::Capture && event.button == MouseButton::Left { + on_up(event, window, cx); + } + }); + }, + ) + .absolute(), + ) +} diff --git a/packages/frontend/desktop/src/workbench/interaction_tests.rs b/packages/frontend/desktop/src/workbench/interaction_tests.rs new file mode 100644 index 0000000000..4e3d307d07 --- /dev/null +++ b/packages/frontend/desktop/src/workbench/interaction_tests.rs @@ -0,0 +1,356 @@ +use blocksuite_playground_doc::read::BlockContent; +use playground::editor_session::{DocPoint, DocumentSelection}; +use ui::{ + AnyWindowHandle, AppContext, Application, ApplicationHandle, Bounds, Context, HeadlessPlatform, + HeadlessWindow, Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, + MouseUpEvent, Pixels, PlatformInput, Point, Window, WindowBounds, WindowHandle, WindowOptions, + point, px, size, +}; +use ui_tokens::ThemeMode; + +use super::DesktopShellView; +use crate::{DesktopAppState, DesktopModal, register_desktop_fonts, sidebar::SidebarState}; + +struct Workbench { + app: ApplicationHandle, + handle: WindowHandle, + window: HeadlessWindow, +} + +impl Workbench { + fn new(width: u32, height: u32) -> Self { + 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"); + 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( + DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"), + cx, + ) + }) + }, + ) + .expect("desktop window") + }); + let window = platform + .windows() + .into_iter() + .next() + .expect("headless window"); + window.request_frame(); + Self { + app, + handle, + window, + } + } + + fn shell( + &self, + f: impl FnOnce(&mut DesktopShellView, &mut Window, &mut Context) -> T, + ) -> T { + self.app + .update(|cx| self.handle.update(cx, f).expect("desktop view")) + } + + fn bounds(&self, id: &str) -> Bounds { + self.shell(|_, window, _| { + let bounds = window.frame_snapshot().elements[id].bounds; + Bounds::new( + point(px(bounds.x), px(bounds.y)), + size(px(bounds.width), px(bounds.height)), + ) + }) + } + + fn click(&self, id: &str) { + self.window.simulate_click(self.bounds(id).center()); + self.window.request_frame(); + } + + fn key(&self, key: &'static str) { + self.app.update(|cx| { + AnyWindowHandle::from(self.handle) + .update(cx, |_, window, cx| { + window.dispatch_keystroke(Keystroke::parse(key).expect("key"), cx); + }) + .expect("desktop window"); + }); + self.window.request_frame(); + } + + fn down(&self, position: Point) { + self.window + .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { + button: MouseButton::Left, + position, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + })); + } + + fn up(&self, position: Point) { + self.window + .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { + button: MouseButton::Left, + position, + modifiers: Modifiers::default(), + click_count: 1, + })); + self.window.request_frame(); + } + + fn drag(&self, id: &str, x: f32) { + let from = self.bounds(id).center(); + let to = point(px(x), from.y); + self.down(from); + self.window + .dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { + position: to, + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + })); + self.window.request_frame(); + self.up(to); + } + + fn focus_paragraph(&self, selected: bool) { + self.shell(|shell, window, cx| { + let pane = shell.state.split.active(); + let editor = shell.editor_host.pane_entity(pane.id).expect("page editor"); + editor.update(cx, |view, cx| { + let block = view.page_snapshot().expect("page snapshot").root.as_ref() + .expect("page root").walk().find(|block| matches!( + &block.content, BlockContent::Paragraph { text, .. } if text.plain.len() >= 5 + )).expect("paragraph").id.clone(); + view.select_document_range(DocumentSelection { + anchor: DocPoint::new(&block, 1), + focus: DocPoint::new(&block, if selected { 5 } else { 1 }), + }, window, cx); + }); + }); + self.window.request_frame(); + } + + fn doc_update(&self, id: &str) -> Vec { + self.shell(|shell, _, _| { + shell + .state + .store + .get_doc(id) + .expect("original page") + .session + .encode_update_v1() + .expect("page update") + }) + } +} + +#[test] +fn command_k_searches_with_a_caret_and_opens_the_link_field_with_selected_text() { + let app = Workbench::new(1100, 780); + for shortcut in ["ctrl-k", "cmd-k"] { + app.focus_paragraph(false); + app.key(shortcut); + app.shell(|view, window, _| { + assert!(view.state.quick_search.open); + assert!(view.quick_search_focus.is_focused(window)); + }); + app.key("escape"); + app.focus_paragraph(true); + app.key(shortcut); + app.shell(|view, window, _| { + assert!(!view.state.quick_search.open); + assert!( + window + .frame_snapshot() + .elements + .contains_key("overlay.format_toolbar.link_input") + ); + }); + app.key("escape"); + } +} + +#[test] +fn search_and_settings_own_keyboard_and_pointer_until_dismissed() { + let app = Workbench::new(1100, 780); + let original = app.doc_update("doc-arch"); + app.focus_paragraph(false); + app.click("desktop.sidebar.quick_search"); + app.key("s"); + app.key("y"); + app.key("n"); + app.key("x"); + app.key("backspace"); + app.shell(|view, _, _| assert_eq!(view.state.quick_search.query, "syn")); + app.key("down"); + app.key("up"); + app.key("enter"); + app.shell(|view, _, _| { + assert!(!view.state.quick_search.open); + assert_eq!( + view.state.split.active().active_route().doc_id(), + Some("doc-sync") + ); + }); + + app.focus_paragraph(false); + let focused = app.shell(|_, window, cx| window.focused(cx).expect("editor focus")); + let sync_before = app.doc_update("doc-sync"); + for (button, card, modal) in [ + ("desktop.sidebar.quick_search", "desktop.qs.modal", None), + ( + "desktop.sidebar.settings", + "desktop.settings.modal", + Some(DesktopModal::Settings), + ), + ] { + app.click(button); + let bounds = app.bounds(card); + app.window + .simulate_click(point(bounds.left() + px(28.0), bounds.top() + px(22.0))); + app.window.request_frame(); + app.shell(|view, _, _| { + assert_eq!(view.state.modal, modal); + assert_eq!(view.state.quick_search.open, modal.is_none()); + }); + app.window.simulate_click(point(px(600.0), px(80.0))); + app.window.request_frame(); + app.shell(|view, window, _| { + assert!(focused.is_focused(window)); + assert!(view.state.modal.is_none()); + assert!(!view.state.quick_search.open); + }); + app.click(button); + app.key("x"); + app.key("backspace"); + if modal.is_some() { + app.key("enter"); + } + app.key("escape"); + app.shell(|view, window, _| { + assert!(focused.is_focused(window)); + assert!(view.state.modal.is_none()); + assert!(!view.state.quick_search.open); + }); + } + assert_eq!(app.doc_update("doc-sync"), sync_before); + app.key("x"); + assert_ne!(app.doc_update("doc-sync"), sync_before); + assert_eq!(app.doc_update("doc-arch"), original); +} + +#[test] +fn resizing_clamps_at_limits_and_pointer_down_activates_either_split_pane() { + let app = Workbench::new(1440, 900); + let original = app.doc_update("doc-arch"); + for (target, expected) in [(350.0, 350.0), (800.0, SidebarState::MAX_WIDTH)] { + app.drag("desktop.sidebar.resize", target); + assert_eq!(app.bounds("desktop.sidebar").size.width, px(expected)); + } + app.key("ctrl-\\"); + for (target, expected) in [(1000.0, 580.0), (1420.0, 765.0)] { + app.drag("desktop.split.resize", target); + assert!((f32::from(app.bounds("desktop.pane.0").size.width) - expected).abs() < 0.5); + } + for idx in [0, 1] { + let pane = app.bounds(&format!("desktop.pane.{idx}")); + let position = point(pane.center().x, pane.top() + px(200.0)); + app.down(position); + app.shell(|view, _, _| assert_eq!(view.state.split.active_pane, idx)); + app.up(position); + } + assert_eq!(app.doc_update("doc-arch"), original); +} + +#[test] +fn workbench_buttons_close_an_inactive_tab_and_move_the_current_page_to_trash() { + let app = Workbench::new(1100, 780); + app.key("ctrl-n"); + let new_id = app.shell(|view, _, _| { + assert_eq!(view.state.split.active().tabs.len(), 2); + view.state + .split + .active() + .active_route() + .doc_id() + .expect("new page") + .to_string() + }); + app.click("desktop.pane.0.tab.0.close"); + app.shell(|view, _, _| { + assert_eq!(view.state.split.active().tabs.len(), 1); + assert_eq!( + view.state.split.active().active_route().doc_id(), + Some(new_id.as_str()) + ); + }); + app.click("desktop.topbar.move_to_trash"); + app.shell(|view, _, _| { + assert!( + view.state + .store + .trashed_docs() + .iter() + .any(|doc| doc.id == new_id) + ); + assert!(matches!( + view.state.split.active().active_route(), + crate::split_view::DesktopRoute::Trash + )); + }); +} + +#[test] +fn narrow_workbench_drawer_and_centered_modals_fit_the_viewport() { + for (width, height) in [(560, 800), (390, 844)] { + let app = Workbench::new(width, height); + let workbench = app.bounds("desktop.workbench"); + assert_eq!(workbench.size.width, px(width as f32)); + app.click("desktop.topbar.sidebar_toggle"); + let drawer = app.bounds("desktop.sidebar"); + assert!(drawer.right() < workbench.right()); + + for (button, card) in [ + ("desktop.sidebar.quick_search", "desktop.qs.modal"), + ("desktop.sidebar.settings", "desktop.settings.modal"), + ] { + app.click(button); + let bounds = app.bounds(card); + assert_eq!(bounds.size.width, px(width as f32 - 32.0)); + assert_eq!(bounds.center().x, px(width as f32 / 2.0)); + assert_eq!(bounds.center().y, px(height as f32 / 2.0)); + assert!(bounds.top() >= px(16.0)); + assert!(bounds.bottom() <= px(height as f32 - 16.0)); + if card == "desktop.settings.modal" { + app.shell(|_, window, _| { + let row = + &window.frame_snapshot().elements["desktop.settings.deduplicated_blobs"]; + assert!( + row.bounds.y + row.bounds.height + <= row.content_mask.y + row.content_mask.height + ); + }); + } + app.key("escape"); + } + + app.window + .simulate_click(point(px(width as f32 - 10.0), px(100.0))); + app.window.request_frame(); + app.shell(|view, _, _| assert!(!view.state.sidebar.open)); + assert_eq!(app.bounds("desktop.workbench"), workbench); + } +} diff --git a/packages/frontend/desktop/src/workbench/mod.rs b/packages/frontend/desktop/src/workbench/mod.rs index c81700aa15..fff0c91254 100644 --- a/packages/frontend/desktop/src/workbench/mod.rs +++ b/packages/frontend/desktop/src/workbench/mod.rs @@ -3,14 +3,20 @@ #[cfg(not(target_family = "wasm"))] mod connected_workspace; +mod interaction; mod local_workspace; +mod search_input; mod topbar; pub use local_workspace::{LocalDocStore, LocalWorkspaces, StoredDocs, StoredWorkspaces}; +use blocksuite_editor::inline_input::Utf16ImeBuffer; +pub(crate) use interaction::backdrop; +use interaction::{ResizeDrag, ResizeTarget, resize_capture, resize_handle}; +pub(crate) use search_input::search_input_handler; use ui::{ - Context, FocusHandle, Focusable, FontWeight, InteractiveElement, IntoElement, KeyDownEvent, - ParentElement, Render, StatefulInteractiveElement, Styled, Window, div, px, svg, + Context, FocusHandle, Focusable, FontWeight, InteractiveElement, IntoElement, ParentElement, + Render, StatefulInteractiveElement, Styled, Window, div, px, svg, }; use ui_tokens::FONT_SANS; @@ -18,10 +24,16 @@ pub use crate::state::{DesktopAppState, DesktopModal, DocInspectorTab}; use crate::{ CLOSE_ICON_SVG, DOC_ICON_SVG, DesktopFlexExt, EDGELESS_ICON_SVG, - editor_host::DesktopEditorHost, palette_for, pane_render::render_pane_content, - peek_view::render_peek_view_modal, quick_search::render_quick_search_modal, - settings_modal::render_settings_modal, sidebar::render_sidebar, sidebar_tree::SidebarRowIndex, - split_view::DocViewMode, views_extra::render_doc_inspector, + editor_host::DesktopEditorHost, + palette_for, + pane_render::render_pane_content, + peek_view::render_peek_view_modal, + quick_search::{QUICK_SEARCH_HEIGHT, render_quick_search_modal}, + settings_modal::render_settings_modal, + sidebar::render_sidebar, + sidebar_tree::SidebarRowIndex, + split_view::DocViewMode, + views_extra::render_doc_inspector, }; /// Interactive GPU UI root view for AFFiNE Web Desktop & Electron shell. @@ -31,6 +43,12 @@ pub struct DesktopShellView { pending_block: Option, pub(crate) sidebar_rows: SidebarRowIndex, focus_handle: FocusHandle, + quick_search_focus: FocusHandle, + settings_focus: FocusHandle, + modal_return_focus: Option, + search_input: Utf16ImeBuffer, + resize: Option, + docked_sidebar_open: Option, #[cfg(not(target_family = "wasm"))] connection: Option, local: Option, @@ -47,6 +65,12 @@ impl DesktopShellView { connection: None, local: None, focus_handle: cx.focus_handle(), + quick_search_focus: cx.focus_handle(), + settings_focus: cx.focus_handle(), + modal_return_focus: None, + search_input: Utf16ImeBuffer::default(), + resize: None, + docked_sidebar_open: None, } } @@ -118,81 +142,6 @@ impl DesktopShellView { true } - fn handle_key_down( - &mut self, - event: &KeyDownEvent, - _window: &mut Window, - cx: &mut Context, - ) { - let key = event.keystroke.key.as_str(); - let cmd_or_ctrl = event.keystroke.modifiers.platform || event.keystroke.modifiers.control; - - if self.state.quick_search.open { - let total = self.state.quick_search.items(&self.state.store).len(); - match key { - "escape" => self.state.quick_search.close(), - "down" => self.state.quick_search.move_selection(1, total), - "up" => self.state.quick_search.move_selection(-1, total), - "enter" => { - self.state.confirm_quick_search(cmd_or_ctrl); - } - "backspace" => { - self.state.quick_search.query.pop(); - self.state.quick_search.selected_index = 0; - } - _ => { - if let Some(ch) = &event.keystroke.key_char - && !cmd_or_ctrl - && !ch.chars().any(char::is_control) - { - self.state.quick_search.query.push_str(ch); - self.state.quick_search.selected_index = 0; - } - } - } - cx.notify(); - return; - } - - if key == "escape" { - if self.state.peek_view.is_open() { - self.state.peek_view.close(); - cx.notify(); - return; - } - if self.state.modal.is_some() { - self.state.close_modal(); - cx.notify(); - return; - } - } - - if cmd_or_ctrl { - match key { - "k" => { - self.state.open_quick_search(); - cx.notify(); - } - "\\" => { - self.state.open_split_edgeless_for_active_doc(); - cx.notify(); - } - "[" => { - self.state.split.active_mut().go_back(); - cx.notify(); - } - "]" => { - self.state.split.active_mut().go_forward(); - cx.notify(); - } - "/" => { - self.state.sidebar.toggle_open(); - cx.notify(); - } - _ => {} - } - } - } /// Flush any mounted `Entity` edits into `DesktopDocStore` and fan out /// to sibling panes/outline/topbar immediately when an observed editor changes. pub(crate) fn sync_editors_from_observer(&mut self, cx: &mut Context) { @@ -236,23 +185,53 @@ impl Render for DesktopShellView { let settings_open = !quick_search_open && !peek_open && matches!(self.state.modal, Some(DesktopModal::Settings)); - let panes_shielded = quick_search_open || peek_open || settings_open; + + let modal_focus = if quick_search_open { + Some(self.quick_search_focus.clone()) + } else if settings_open { + Some(self.settings_focus.clone()) + } else { + None + }; + self.update_shell_focus(modal_focus, window, cx); + self.sync_search_input(); let palette = palette_for(self.state.theme); let vp = window.viewport_size(); let vp_w: f32 = vp.width.into(); let vp_h: f32 = vp.height.into(); - let sidebar_w = if self.state.sidebar.open { - self.state.sidebar.width + let compact = vp_w < 700.0; + match (compact, self.docked_sidebar_open) { + (true, None) => { + self.docked_sidebar_open = Some(self.state.sidebar.open); + self.state.sidebar.open = false; + } + (false, Some(open)) => { + self.state.sidebar.open = open; + self.docked_sidebar_open = None; + } + _ => {} + } + let drawer_open = compact && self.state.sidebar.open; + let sidebar_w = if self.state.sidebar.open && !compact { + self.state.sidebar.width.min(vp_w - 390.0) } else { 0.0 }; - let inspector_w = if self.state.inspector_tab.is_some() { - 250.0 - } else { - 0.0 - }; - let workbench_w = (vp_w - sidebar_w - inspector_w).max(320.0); + let inspector_w = + if self.state.inspector_tab.is_some() && vp_w - sidebar_w >= 640.0 && !compact { + 250.0 + } else { + 0.0 + }; + let inspector_floating = inspector_w == 0.0 && self.state.inspector_tab.is_some(); + let workbench_w = (vp_w - sidebar_w - inspector_w).max(0.0); + let panes_shielded = quick_search_open + || peek_open + || settings_open + || drawer_open + || inspector_floating + || self.resize.is_some(); let pane_body_h = (vp_h - 86.0).max(160.0); let active_route = self.state.split.active().active_route().clone(); @@ -278,6 +257,11 @@ impl Render for DesktopShellView { can_back, can_fwd, is_readonly_sqlite, + active_doc_id + .as_deref() + .and_then(|id| self.state.store.get_doc(id)) + .is_some_and(|entry| !entry.meta.trashed), + workbench_w < 640.0, self.state.split.is_split(), palette, cx, @@ -340,19 +324,29 @@ impl Render for DesktopShellView { palette.border }); - let mut tab_strip = div().flex().flex_row().items_center().gap(px(4.0)); + let can_close_tabs = tab_meta.len() > 1; + let mut tab_strip = div() + .id(ui::SharedString::from(format!("desktop.pane.{idx}.tabs"))) + .flex() + .flex_row() + .items_center() + .gap(px(4.0)) + .min_w_0(); + tab_strip.style().overflow.x = Some(ui::Overflow::Scroll); for (t_idx, label, mode, is_active_tab) in tab_meta { + let mut tab = div().id(ui::SharedString::from(format!( + "desktop.pane.{idx}.tab.{t_idx}" + ))); + tab.style().max_size.width = Some(px(200.0).into()); tab_strip = tab_strip.child( - div() - .id(ui::SharedString::from(format!( - "desktop.pane.{idx}.tab.{t_idx}" - ))) - .flex() + tab.flex() .flex_row() .items_center() .gap(px(6.0)) - .h(px(26.0)) - .px(px(10.0)) + .h(px(28.0)) + .flex_shrink(0.0) + .pl(px(8.0)) + .pr(px(4.0)) .rounded(px(6.0)) .bg(if is_active_tab { palette.bg_elevated @@ -387,6 +381,8 @@ impl Render for DesktopShellView { ) .child( div() + .min_w_0() + .text_ellipsis() .text_size(px(12.0)) .font_weight(if is_active_tab { FontWeight::MEDIUM @@ -399,6 +395,10 @@ impl Render for DesktopShellView { palette.text_secondary }) .child(label), + ) + .children( + can_close_tabs + .then(|| interaction::close_tab_button(idx, t_idx, palette, cx)), ), ); } @@ -491,9 +491,11 @@ impl Render for DesktopShellView { .flex_col() .min_w_0() .min_h_0() - .on_click(cx.listener(move |this, _, _, cx| { - this.state.split.focus_pane(idx); - cx.notify(); + .capture_any_mouse_down(cx.listener(move |this, _, _, cx| { + if this.state.split.active_pane != idx { + this.state.split.focus_pane(idx); + cx.notify(); + } })) .child(tab_bar) .child(div().flex_1().min_h_0().w_full().child(content)); @@ -520,6 +522,7 @@ impl Render for DesktopShellView { .id("desktop.shell.root") .snapshot("desktop.shell.root", None) .track_focus(&self.focus_handle) + .capture_key_down(cx.listener(Self::capture_modal_key)) .on_key_down(cx.listener(Self::handle_key_down)) .relative() .w_full() @@ -530,12 +533,13 @@ impl Render for DesktopShellView { .flex_row() .items_stretch(); - if self.state.sidebar.open { + if sidebar_w > 0.0 { root = root.child(render_sidebar( &mut self.state.sidebar, &self.state.store, &mut self.sidebar_rows, &active_route, + sidebar_w, vp_h, palette, cx, @@ -544,20 +548,117 @@ impl Render for DesktopShellView { root = root.child(workbench); - if let Some(tab) = self.state.inspector_tab { - root = root.child(render_doc_inspector( - tab, - active_doc_id.as_deref(), - &self.state.store, + if let Some(tab) = self.state.inspector_tab.filter(|_| inspector_w > 0.0) { + root = root.child(div().w(px(inspector_w)).h_full().overflow_hidden().child( + render_doc_inspector( + tab, + active_doc_id.as_deref(), + &self.state.store, + palette, + cx, + ), + )); + } + + if sidebar_w > 0.0 { + root = root.child(resize_handle( + ResizeTarget::Sidebar, + sidebar_w, + 0.0, palette, cx, )); } + if pane_count == 2 && workbench_w > 0.0 { + root = root.child(resize_handle( + ResizeTarget::Split(workbench_w), + sidebar_w + workbench_w * split_ratio, + 48.0, + palette, + cx, + )); + } + root = root.child(resize_capture(self.resize.is_some(), cx)); + + if inspector_floating && let Some(tab) = self.state.inspector_tab { + root = root.child( + div() + .absolute() + .top_0() + .left_0() + .w_full() + .h_full() + .child(backdrop( + "desktop.inspector.backdrop", + palette, + cx.listener(|this, _, _, cx| { + this.state.inspector_tab = None; + cx.notify(); + }), + )) + .child( + div() + .absolute() + .top_0() + .right(px(0.0)) + .h_full() + .occlude() + .child(render_doc_inspector( + tab, + active_doc_id.as_deref(), + &self.state.store, + palette, + cx, + )), + ), + ); + } + + if drawer_open { + let sidebar = render_sidebar( + &mut self.state.sidebar, + &self.state.store, + &mut self.sidebar_rows, + &active_route, + (vp_w - 32.0).clamp(0.0, 320.0), + vp_h, + palette, + cx, + ); + root = root.child( + div() + .absolute() + .top_0() + .left_0() + .w_full() + .h_full() + .child(interaction::backdrop( + "desktop.sidebar.backdrop", + palette, + cx.listener(|this, _, _, cx| { + this.state.sidebar.open = false; + cx.notify(); + }), + )) + .child( + div() + .absolute() + .top_0() + .left_0() + .h_full() + .occlude() + .child(sidebar), + ), + ); + } if quick_search_open { root = root.child(render_quick_search_modal( &self.state.quick_search, &self.state.store, + &self.quick_search_focus, + &self.search_input, + interaction::modal_size(vp_w, vp_h, QUICK_SEARCH_HEIGHT), palette, cx, )); @@ -586,9 +687,10 @@ impl Render for DesktopShellView { } else if settings_open { root = root.child(render_settings_modal( self.state.theme_preference, - self.state.settings_scroll_y, &self.state.store, &self.state.draft_store, + &self.settings_focus, + interaction::modal_size(vp_w, vp_h, if vp_w < 480.0 { 496.0 } else { 448.0 }), palette, cx, )); @@ -700,3 +802,6 @@ mod tests { } } } + +#[cfg(test)] +mod interaction_tests; diff --git a/packages/frontend/desktop/src/workbench/search_input.rs b/packages/frontend/desktop/src/workbench/search_input.rs new file mode 100644 index 0000000000..dd33ba1ecb --- /dev/null +++ b/packages/frontend/desktop/src/workbench/search_input.rs @@ -0,0 +1,634 @@ +use std::ops::Range; + +use blocksuite_editor::inline_input::{Utf16ImeBuffer, sanitize_input, utf16_len, utf16_to_byte}; +use ui::{ + Bounds, ClipboardItem, Context, ElementInputHandler, FocusHandle, Hsla, IntoElement, + KeyDownEvent, MouseDownEvent, Pixels, Point, ShapedLine, SharedString, Styled, TextAlign, + TextRun, UTF16Selection, Window, canvas, fill, point, px, size, +}; + +use crate::{ + DesktopPalette, + quick_search::{QUICK_SEARCH_HEIGHT, QuickSearchItem}, +}; + +use super::{DesktopShellView, interaction::modal_size}; + +struct SearchLine { + line: ShapedLine, + bounds: Bounds, + origin: Point, +} + +impl SearchLine { + fn new( + text: SharedString, + caret: usize, + bounds: Bounds, + color: Hsla, + window: &Window, + ) -> Self { + let mut font = ui::font(ui_tokens::FONT_SANS); + font.fallbacks = Some(blocksuite_editor::default_font_fallbacks()); + let run = TextRun { + len: text.len(), + font, + color, + background_color: None, + underline: None, + strikethrough: None, + }; + let line = window + .text_system() + .shape_line(text, px(14.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)); + let origin = point(bounds.origin.x - scroll, bounds.origin.y); + Self { + line, + bounds, + origin, + } + } + + fn index_at_x(&self, x: Pixels) -> usize { + let x = x.clamp(self.bounds.origin.x, self.bounds.right()); + let byte = self.line.closest_index_for_x(x - self.origin.x); + utf16_len(&self.line.text[..byte]) + } + + fn bounds_for_range(&self, range: Range) -> Bounds { + let x_at = |offset| { + self.origin.x + + self + .line + .x_for_index(utf16_to_byte(&self.line.text, offset)) + }; + let (start, end) = (x_at(range.start), x_at(range.end)); + let min_x = self.bounds.origin.x; + let max_x = self.bounds.right(); + let left = start.min(end).clamp(min_x, (max_x - px(1.0)).max(min_x)); + let right = end.max(start).max(left + px(1.0)).min(max_x); + Bounds::new( + point(left, self.origin.y), + size(right - left, self.bounds.size.height), + ) + } +} + +impl DesktopShellView { + pub(super) fn sync_search_input(&mut self) { + let qs = &mut self.state.quick_search; + if qs.open && self.search_input.display_text() != qs.query { + qs.query = sanitize_input(&qs.query, false); + self.search_input = Utf16ImeBuffer::new(qs.query.clone(), false); + } + } + + fn search_line(&self, bounds: Bounds, window: &Window) -> SearchLine { + let (selection, reversed) = self.search_input.shown_selection(); + SearchLine::new( + self.search_input.display_text().into(), + if reversed { + selection.start + } else { + selection.end + }, + bounds, + Hsla::default(), + window, + ) + } + + pub(crate) fn click_search_input( + &mut self, + event: &MouseDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + window.focus(&self.quick_search_focus, cx); + if let Some(bounds) = self.state.quick_search.text_bounds { + let index = self + .search_line(bounds, window) + .index_at_x(event.position.x); + self.search_input.unmark(); + self.search_input.move_caret(index, event.modifiers.shift); + self.search_input_changed(window, cx); + } + window.request_virtual_keyboard(); + } + + fn search_input_changed(&mut self, window: &Window, cx: &mut Context) { + let text = self.search_input.display_text(); + if text != self.state.quick_search.query { + self.state.quick_search.set_query(text); + window.notify_text_input_changed(&self.quick_search_focus); + } + window.notify_text_selection_changed(&self.quick_search_focus); + cx.notify(); + } + + pub(super) fn handle_search_key( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let key = event.keystroke.key.as_str(); + let modifiers = event.keystroke.modifiers; + let command = modifiers.platform || modifiers.control; + if !self.quick_search_focus.is_focused(window) { + window.focus(&self.quick_search_focus, cx); + return true; + } + if self.search_input.composing() { + if key == "escape" { + self.search_input.cancel_preedit(); + self.search_input_changed(window, cx); + return true; + } + return false; + } + + match key { + "escape" => self.dismiss_modal(window, cx), + "up" | "down" => { + let qs = &mut self.state.quick_search; + let items = qs.items(&self.state.store); + 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, + ); + 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) + { + 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), + None => {} + } + } + "c" | "x" if command => { + let selected = self.search_input.selected_text(); + if !selected.is_empty() { + cx.write_to_clipboard(ClipboardItem::new_string(selected.to_string())); + if key == "x" { + self.search_input.replace(None, ""); + self.search_input_changed(window, cx); + } + } + } + "v" if command => return false, + _ => { + if self + .search_input + .key(key, modifiers.shift, command) + .is_some() + { + self.search_input_changed(window, cx); + } else { + return event.keystroke.key_char.is_none() || command; + } + } + } + true + } +} + +pub(crate) fn search_input_handler( + input: &Utf16ImeBuffer, + focus: FocusHandle, + palette: DesktopPalette, + cx: &Context, +) -> impl IntoElement + use<> { + let entity = cx.entity(); + let shown = input.display_text().into(); + let (selection, reversed) = input.shown_selection(); + let caret = if reversed { + selection.start + } else { + selection.end + }; + canvas( + move |bounds, window, _| { + SearchLine::new(shown, caret, bounds, palette.text_primary, window) + }, + move |bounds, layout, window, cx| { + entity.update(cx, |view, _| { + view.state.quick_search.text_bounds = Some(bounds); + }); + window.handle_input(&focus, ElementInputHandler::new(bounds, entity), cx); + + if !selection.is_empty() { + let byte_range = utf16_to_byte(&layout.line.text, selection.start) + ..utf16_to_byte(&layout.line.text, selection.end); + for rect in layout.line.selection_rects_for_range(byte_range) { + let origin = point(layout.origin.x + rect.origin.x, bounds.origin.y); + window.paint_quad(fill( + Bounds::new(origin, size(rect.size.width, bounds.size.height)), + palette.accent_soft, + )); + } + } + let _ = layout.line.paint( + layout.origin, + bounds.size.height, + TextAlign::Left, + None, + window, + cx, + ); + if selection.is_empty() { + window.paint_quad(fill(layout.bounds_for_range(caret..caret), palette.accent)); + } + }, + ) + .absolute() + .inset_0() +} + +impl ui::EntityInputHandler for DesktopShellView { + fn text_for_range( + &mut self, + range: Range, + adjusted_range: &mut Option>, + _: &mut Window, + _: &mut Context, + ) -> Option { + let (text, range) = self.search_input.text_for_range(range); + *adjusted_range = Some(range); + Some(text) + } + + fn selected_text_range( + &mut self, + _: bool, + _: &mut Window, + _: &mut Context, + ) -> Option { + let (range, reversed) = self.search_input.shown_selection(); + Some(UTF16Selection { range, reversed }) + } + + fn marked_text_range(&self, _: &mut Window, _: &mut Context) -> Option> { + self.search_input.marked_range() + } + + fn unmark_text(&mut self, window: &mut Window, cx: &mut Context) { + if self.state.quick_search.open { + self.search_input.unmark(); + self.search_input_changed(window, cx); + } + } + + fn replace_text_in_range( + &mut self, + range: Option>, + text: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.state.quick_search.open { + self.search_input.replace(range, text); + self.search_input_changed(window, cx); + } + } + + fn replace_and_mark_text_in_range( + &mut self, + range: Option>, + text: &str, + selection: Option>, + window: &mut Window, + cx: &mut Context, + ) { + if self.state.quick_search.open { + self.search_input.mark(range, text, selection); + self.search_input_changed(window, cx); + } + } + + fn bounds_for_range( + &mut self, + range_utf16: Range, + bounds: Bounds, + window: &mut Window, + _: &mut Context, + ) -> Option> { + self.state.quick_search.open.then(|| { + self.search_line(bounds, window) + .bounds_for_range(range_utf16) + }) + } + + fn character_index_for_point( + &mut self, + point: Point, + window: &mut Window, + _: &mut Context, + ) -> Option { + let bounds = self.state.quick_search.text_bounds?; + (self.state.quick_search.open && bounds.contains(&point)) + .then(|| self.search_line(bounds, window).index_at_x(point.x)) + } +} + +#[cfg(test)] +mod tests { + use std::rc::Rc; + + use ui::{ + AnyWindowHandle, AppContext, Application, ApplicationHandle, HeadlessPlatform, + HeadlessWindow, Keystroke, PlatformInputHandler, PlatformWindow, WindowBounds, + WindowHandle, WindowOptions, + }; + use ui_tokens::ThemeMode; + + use super::*; + use crate::{DesktopAppState, register_desktop_fonts}; + + struct TestShell { + app: ApplicationHandle, + handle: WindowHandle, + window: HeadlessWindow, + platform: Rc, + } + + impl TestShell { + fn new(width: u32, height: u32) -> Self { + 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"); + 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| { + 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"); + let shell = Self { + app, + handle, + window, + platform, + }; + shell.frame(); + shell + } + + fn frame(&self) { + self.window.request_frame(); + self.platform.run_until_parked(); + } + + fn shell( + &self, + f: impl FnOnce(&mut DesktopShellView, &mut Window, &mut Context) -> T, + ) -> T { + self.app + .update(|cx| self.handle.update(cx, f).expect("desktop view")) + } + + fn click(&self, id: &str) { + let pos = self.shell(|_, window, _| { + let b = window.frame_snapshot().elements[id].bounds; + point(px(b.x + b.width * 0.5), px(b.y + b.height * 0.5)) + }); + self.window.simulate_click(pos); + self.frame(); + } + + fn key(&self, key: &'static str) { + self.app.update(|cx| { + AnyWindowHandle::from(self.handle) + .update(cx, |_, window, cx| { + window.dispatch_keystroke(Keystroke::parse(key).expect("key"), cx); + }) + .expect("desktop window"); + }); + self.frame(); + } + + fn input(&self, f: impl FnOnce(&mut PlatformInputHandler) -> T) -> T { + let mut window = self.window.clone(); + let mut handler = window.take_input_handler().expect("search input handler"); + let out = f(&mut handler); + window.set_input_handler(handler); + self.frame(); + out + } + + fn active_document_update(&self) -> Vec { + self.shell(|shell, _, cx| { + let pane = shell.state.split.active(); + let doc_id = pane.active_route().doc_id().expect("open document"); + shell + .editor_host() + .pane_entity(pane.id) + .expect("mounted editor") + .read(cx) + .document() + .workspace + .page(doc_id) + .expect("editor session") + .encode_update_v1() + .expect("document update") + }) + } + } + + #[test] + fn quick_search_hit_testing_and_ime_bounds_follow_the_shaped_utf16_line() { + let app = TestShell::new(1100, 780); + app.click("desktop.sidebar.quick_search"); + + for (text, offsets) in [("ab中文cd", [0, 2, 3, 4, 6]), ("ab🚀cd", [0, 2, 4, 5, 6])] { + app.input(|handler| handler.replace_text_in_range(Some(0..6), text)); + app.input(|handler| { + let mut previous_x = None; + for offset in offsets { + let b = handler + .bounds_for_range(offset..offset) + .expect("caret bounds"); + assert!(previous_x.is_none_or(|x| b.origin.x > x)); + assert_eq!(handler.character_index_for_point(b.origin), Some(offset)); + previous_x = Some(b.origin.x); + } + let start = handler.bounds_for_range(0..0).expect("first caret"); + let end = handler.bounds_for_range(4..4).expect("fourth caret"); + let range = handler.bounds_for_range(0..4).expect("range bounds"); + assert_eq!(range.origin, start.origin); + assert_eq!(range.right(), end.origin.x); + assert_eq!(range.size.height, end.size.height); + assert_eq!( + handler + .character_index_for_point(point(start.origin.x, start.origin.y - px(1.0))), + None + ); + if text.contains('🚀') { + assert_eq!( + handler.bounds_for_range(3..3), + handler.bounds_for_range(2..2) + ); + } + }); + } + + app.input(|handler| handler.replace_text_in_range(Some(0..6), "ab中文cd")); + let middle = app.input(|handler| handler.bounds_for_range(3..3).expect("CJK caret")); + app.window.simulate_click(middle.center()); + app.input(|handler| { + assert_eq!( + handler.selected_text_range(false).expect("selection").range, + 3..3 + ); + handler.replace_text_in_range(None, "X"); + }); + app.shell(|shell, _, _| assert_eq!(shell.state.quick_search.query, "ab中X文cd")); + } + + #[test] + fn quick_search_preedit_and_commit_leave_the_active_crdt_unchanged() { + let app = TestShell::new(1100, 780); + let before = app.active_document_update(); + app.click("desktop.sidebar.quick_search"); + app.input(|handler| handler.replace_and_mark_text_in_range(None, "中文", Some(1..1))); + app.shell(|shell, _, _| { + assert_eq!(shell.search_input.text(), ""); + assert_eq!(shell.state.quick_search.query, "中文"); + }); + assert_eq!(app.active_document_update(), before); + app.input(|handler| handler.unmark_text()); + app.shell(|shell, _, _| assert_eq!(shell.search_input.text(), "中文")); + assert_eq!(app.active_document_update(), before); + } + + #[test] + fn quick_search_copy_and_cut_only_change_the_clipboard_with_a_selection() { + let app = TestShell::new(1100, 780); + app.click("desktop.sidebar.quick_search"); + for modifier in ["ctrl", "cmd"] { + app.input(|handler| handler.replace_text_in_range(None, "sea")); + app.shell(|_, _, cx| cx.write_to_clipboard(ClipboardItem::new_string("prior".into()))); + let (copy, cut) = if modifier == "ctrl" { + ("ctrl-c", "ctrl-x") + } else { + ("cmd-c", "cmd-x") + }; + app.key(copy); + app.key(cut); + app.shell(|shell, _, cx| { + assert_eq!(shell.state.quick_search.query, "sea"); + assert_eq!( + cx.read_from_clipboard() + .and_then(|item| item.text()) + .as_deref(), + Some("prior") + ); + }); + app.key("ctrl-a"); + app.key(copy); + app.shell(|shell, _, cx| { + assert_eq!(shell.state.quick_search.query, "sea"); + assert_eq!(shell.search_input.shown_selection().0, 0..3); + assert_eq!( + cx.read_from_clipboard() + .and_then(|item| item.text()) + .as_deref(), + Some("sea") + ); + cx.write_to_clipboard(ClipboardItem::new_string("prior".into())); + }); + app.key(cut); + app.shell(|shell, _, cx| { + assert!(shell.state.quick_search.query.is_empty()); + assert_eq!( + cx.read_from_clipboard() + .and_then(|item| item.text()) + .as_deref(), + Some("sea") + ); + }); + } + } + + #[test] + fn narrow_quick_search_preserves_the_drawer_on_cancel_and_closes_it_on_navigation() { + for confirm in ["enter", "click"] { + let app = TestShell::new(390, 844); + app.click("desktop.topbar.sidebar_toggle"); + + for cancel in ["escape", "backdrop"] { + app.click("desktop.sidebar.quick_search"); + if cancel == "escape" { + app.key("escape"); + } else { + app.window.simulate_click(point(px(8.0), px(80.0))); + app.frame(); + } + app.shell(|shell, _, _| { + assert!(!shell.state.quick_search.open); + assert!(shell.state.sidebar.open); + }); + } + + app.click("desktop.sidebar.quick_search"); + app.input(|handler| handler.replace_text_in_range(None, "syn")); + if confirm == "enter" { + app.key("enter"); + } else { + app.click("desktop.qs.doc.doc-sync"); + } + app.shell(|shell, window, _| { + assert_eq!( + shell.state.split.active().active_route().doc_id(), + Some("doc-sync") + ); + assert!(!shell.state.quick_search.open); + assert!(!shell.state.sidebar.open); + assert!( + !window + .frame_snapshot() + .elements + .contains_key("desktop.sidebar.backdrop") + ); + }); + } + } +} diff --git a/packages/frontend/desktop/src/workbench/topbar.rs b/packages/frontend/desktop/src/workbench/topbar.rs index 319f8ea75c..17f5205ae7 100644 --- a/packages/frontend/desktop/src/workbench/topbar.rs +++ b/packages/frontend/desktop/src/workbench/topbar.rs @@ -8,7 +8,8 @@ use ui::{ use crate::{ CHEVRON_LEFT_SVG, CHEVRON_RIGHT_SVG, DOC_ICON_SVG, DesktopFlexExt, DesktopPalette, EDGELESS_ICON_SVG, INFO_ICON_SVG, PEEK_ICON_SVG, SIDEBAR_TOGGLE_SVG, SPLIT_ICON_SVG, - STAR_FILLED_SVG, STAR_ICON_SVG, split_view::DocViewMode, + STAR_FILLED_SVG, STAR_ICON_SVG, TRASH_ICON_SVG, + split_view::{DesktopRoute, DocViewMode}, }; use super::DesktopShellView; @@ -22,6 +23,8 @@ pub(super) fn render_topbar( can_back: bool, can_fwd: bool, is_readonly_sqlite: bool, + is_live_doc: bool, + compact: bool, is_split: bool, palette: DesktopPalette, cx: &mut Context, @@ -36,7 +39,9 @@ pub(super) fn render_topbar( .justify_between() .w_full() .h(px(48.0)) - .px(px(14.0)) + .px(px(if compact { 8.0 } else { 14.0 })) + .gap(px(if compact { 4.0 } else { 8.0 })) + .overflow_hidden() .flex_shrink(0.0) .bg(palette.bg_canvas) .border_b_1() @@ -46,7 +51,9 @@ pub(super) fn render_topbar( .flex() .flex_row() .items_center() - .gap(px(8.0)) + .gap(px(if compact { 2.0 } else { 8.0 })) + .flex_1() + .min_w_0() .child(icon_btn( "desktop.topbar.sidebar_toggle", SIDEBAR_TOGGLE_SVG, @@ -80,12 +87,14 @@ pub(super) fn render_topbar( .child( div() .pl(px(4.0)) + .min_w_0() + .text_ellipsis() .text_size(px(14.0)) .font_weight(FontWeight::SEMIBOLD) .text_color(palette.text_primary) .child(active_title.to_string()), ) - .when_some(active_doc_id.clone(), |el, doc_id| { + .when_some(active_doc_id.clone().filter(|_| !compact), |el, doc_id| { let fav_btn = div() .id("desktop.topbar.favorite") .w(px(28.0)) @@ -119,7 +128,7 @@ pub(super) fn render_topbar( })) }) }) - .when(is_readonly_sqlite, |el| { + .when(is_readonly_sqlite && !compact, |el| { el.child(crate::pane_render::render_readonly_sqlite_badge(palette)) }), ) @@ -135,13 +144,14 @@ pub(super) fn render_topbar( .flex_row() .items_center() .p(px(3.0)) + .flex_shrink(0.0) .gap(px(2.0)) .rounded(px(9.0)) .bg(palette.bg_pill) .child(mode_pill( "desktop.topbar.mode.page", DOC_ICON_SVG, - "Page", + (!compact).then_some("Page"), active_mode == DocViewMode::Page, DocViewMode::Page, palette, @@ -150,7 +160,7 @@ pub(super) fn render_topbar( .child(mode_pill( "desktop.topbar.mode.edgeless", EDGELESS_ICON_SVG, - "Edgeless", + (!compact).then_some("Edgeless"), active_mode == DocViewMode::Edgeless, DocViewMode::Edgeless, palette, @@ -163,12 +173,50 @@ pub(super) fn render_topbar( .flex() .flex_row() .items_center() - .gap(px(6.0)) + .gap(px(if compact { 2.0 } else { 6.0 })) + .flex_shrink(0.0) + .when_some( + active_doc_id.filter(|_| is_live_doc && !is_readonly_sqlite), + |el, id| { + el.child( + div() + .id("desktop.topbar.move_to_trash") + .snapshot( + "desktop.topbar.move_to_trash", + Some("desktop.workbench.topbar"), + ) + .h(px(28.0)) + .px(px(6.0)) + .gap(px(4.0)) + .rounded(px(6.0)) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .tab_index(0) + .hover(move |s| s.bg(palette.bg_active)) + .focus_visible(move |s| s.bg(palette.bg_active)) + .text_color(palette.text_secondary) + .on_click(cx.listener(move |this, _, window, cx| { + this.sync_editors(cx); + if this.state.trash_doc(&id) { + this.state.navigate_active_pane(DesktopRoute::Trash); + window.focus(&this.focus_handle, cx); + cx.notify(); + } + })) + .child(svg().data(TRASH_ICON_SVG).w(px(16.0)).h(px(16.0))) + .when(!compact, |el| { + el.child(div().text_size(px(12.0)).child("Move to Trash")) + }), + ) + }, + ) .child( div() .id("desktop.topbar.peek_ref") .h(px(28.0)) - .px(px(9.0)) + .px(px(if compact { 6.0 } else { 9.0 })) .rounded(px(7.0)) .bg(palette.bg_pill) .flex() @@ -190,14 +238,14 @@ pub(super) fn render_topbar( .h(px(14.0)) .text_color(palette.text_secondary), ) - .child("Peek"), + .when(!compact, |el| el.child("Peek")), ) .child( div() .id("desktop.topbar.split_btn") .snapshot("desktop.topbar.split_btn", Some("desktop.workbench.topbar")) .h(px(28.0)) - .px(px(9.0)) + .px(px(if compact { 6.0 } else { 9.0 })) .rounded(px(7.0)) .bg(if is_split { palette.accent_soft @@ -238,7 +286,9 @@ pub(super) fn render_topbar( palette.text_secondary }), ) - .child(if is_split { "Split On" } else { "Split" }), + .when(!compact, |el| { + el.child(if is_split { "Split On" } else { "Split" }) + }), ) .child(icon_btn( "desktop.topbar.inspector_toggle", @@ -264,8 +314,10 @@ fn icon_btn( ) -> ui::Stateful { div() .id(id) + .snapshot(id, Some("desktop.workbench.topbar")) .w(px(28.0)) .h(px(28.0)) + .flex_shrink(0.0) .rounded(px(6.0)) .flex() .items_center() @@ -287,7 +339,7 @@ fn icon_btn( fn mode_pill( id: &'static str, icon: &'static [u8], - label: &'static str, + label: Option<&'static str>, active: bool, mode: DocViewMode, palette: DesktopPalette, @@ -296,7 +348,7 @@ fn mode_pill( div() .id(id) .h(px(26.0)) - .px(px(10.0)) + .px(px(if label.is_some() { 10.0 } else { 6.0 })) .rounded(px(6.0)) .bg(if active { palette.bg_elevated @@ -333,5 +385,5 @@ fn mode_pill( palette.text_muted }), ) - .child(label) + .children(label) }