diff --git a/blocksuite/crates/playground/src/database_authoring/geometry.rs b/blocksuite/crates/playground/src/database_authoring/geometry.rs index 07e4a12885..8e096e46a3 100644 --- a/blocksuite/crates/playground/src/database_authoring/geometry.rs +++ b/blocksuite/crates/playground/src/database_authoring/geometry.rs @@ -46,6 +46,25 @@ pub(super) fn inline_cell_font(target: &DatabaseInlineTarget, cell_h: f32) -> (f } impl PlaygroundView { + /// Get the screen position and open state of a database's overflow view control. + pub fn database_view_overflow_control( + &self, + block_id: &str, + window: &Window, + ) -> Option<(Point, bool)> { + let hit = self + .flow + .database_hits(block_id) + .iter() + .find(|hit| matches!(hit.kind, database::DatabaseHitKind::ToggleMoreViews))?; + let rect = self.database_local_rect_to_screen(block_id, hit.rect, hit.scrolls_x, window)?; + let open = self.flow.database_state.state_for(block_id).more_views_open; + Some(( + point(px(rect.x + rect.w / 2.0), px(rect.y + rect.h / 2.0)), + open, + )) + } + /// Locate the screen-space center of the first database authoring hit matching `pred`. pub fn database_authoring_hit_screen_center( &self, diff --git a/blocksuite/crates/playground/src/database_authoring/keys.rs b/blocksuite/crates/playground/src/database_authoring/keys.rs index a754b06e8e..2af4b478dd 100644 --- a/blocksuite/crates/playground/src/database_authoring/keys.rs +++ b/blocksuite/crates/playground/src/database_authoring/keys.rs @@ -19,17 +19,6 @@ impl PlaygroundView { window: &mut Window, cx: &mut Context, ) -> bool { - if event.keystroke.key == "escape" - && matches!( - self.database_drag, - Some(super::DatabaseDragState::KanbanLane(_)) - ) - { - self.database_drag = None; - self.clear_database_hover(cx); - cx.notify(); - return true; - } let Some(block_id) = self.active_database_authoring_block() else { return false; }; @@ -54,13 +43,6 @@ impl PlaygroundView { .as_ref() .is_some_and(|d| d.anchored.input.composing()) { - if key == "escape" { - let _ = self.database_authoring_input_edit(window, cx, |a| { - a.input.cancel_preedit(); - None - }); - return true; - } return false; } if key == "enter" @@ -97,7 +79,6 @@ impl PlaygroundView { } let mapped = match key { "enter" => Some(DatabaseAuthoringKey::Enter), - "escape" => Some(DatabaseAuthoringKey::Escape), "tab" if m.shift => Some(DatabaseAuthoringKey::ShiftTab), "tab" => Some(DatabaseAuthoringKey::Tab), _ => None, @@ -105,9 +86,78 @@ impl PlaygroundView { let Some(auth_key) = mapped else { return false; }; - if auth_key == DatabaseAuthoringKey::Escape - && self.flow.database_state.close_more_views(&block_id) + if self.database_input.as_ref().is_some_and(|d| { + matches!( + d.target, + DatabaseInlineTarget::LiveRichCell { .. } + | DatabaseInlineTarget::RecordBody { .. } + | DatabaseInlineTarget::RecordTitle { .. } + ) + }) && auth_key == DatabaseAuthoringKey::Enter { + self.finish_inline_targets( + crate::overlays::InlineTargetEnd::CommitPreedit, + Some(window), + Some(cx), + ); + return true; + } + if self + .flow + .database_state + .state_for(&block_id) + .authoring + .active_cell + .is_some_and(|cell| cell.col_type == "date") + { + return true; + } + let handled = self.dispatch_database_authoring_key(&block_id, auth_key, cx); + if handled { + self.sync_database_authoring_input(Some(window), cx); + } + handled + } + + pub(crate) fn dismiss_database_transient_on_escape( + &mut self, + window: &mut Window, + cx: &mut Context, + ) -> bool { + if self.database_drag.take().is_some() { + let ids: Vec<_> = self + .flow + .database_state + .states() + .filter(|(_, state)| { + let auth = &state.authoring; + auth.column_resize.is_some() + || auth.progress_preview.is_some() + || auth.calendar_drag.is_some() + || auth.calendar_resize_end.is_some() + || auth.kanban_drag.is_some() + }) + .map(|(id, _)| id.clone()) + .collect(); + for id in ids { + let auth = self.flow.database_state.authoring_mut(&id); + auth.column_resize = None; + auth.progress_preview = None; + auth.calendar_drag = None; + auth.calendar_resize_end = None; + auth.kanban_drag = None; + } + self.clear_database_hover(cx); + cx.notify(); + return true; + } + if self.database_record_sheet.is_some() && !self.record_input_active() { + return self.close_database_record_sheet(cx); + } + let Some(block_id) = self.active_database_authoring_block() else { + return false; + }; + if self.flow.database_state.close_more_views(&block_id) { cx.notify(); return true; } @@ -118,34 +168,31 @@ impl PlaygroundView { | DatabaseInlineTarget::RecordBody { .. } | DatabaseInlineTarget::RecordTitle { .. } ) - }) && matches!( - auth_key, - DatabaseAuthoringKey::Enter | DatabaseAuthoringKey::Escape - ) { - let end = if auth_key == DatabaseAuthoringKey::Enter { - crate::overlays::InlineTargetEnd::CommitPreedit - } else { - crate::overlays::InlineTargetEnd::DiscardPreedit - }; - self.finish_inline_targets(end, Some(window), Some(cx)); - return true; + }) { + return self.finish_inline_targets( + crate::overlays::InlineTargetEnd::DiscardPreedit, + Some(window), + Some(cx), + ); } - let auth = self.flow.database_state.state_for(&block_id).authoring; - if auth.active_cell.is_some_and(|cell| cell.col_type == "date") - && auth_key != DatabaseAuthoringKey::Escape - { - return true; + if self.database_navigation_ready(&block_id) { + return false; } - let clears_search = auth_key == DatabaseAuthoringKey::Escape - && auth.toolbar_panel == Some(database::ActiveToolbarPanel::Search); - let handled = self.dispatch_database_authoring_key(&block_id, auth_key, cx); - if handled && clears_search { + let clears_search = self + .flow + .database_state + .state_for(&block_id) + .authoring + .toolbar_panel + == Some(database::ActiveToolbarPanel::Search); + if !self.dispatch_database_authoring_key(&block_id, DatabaseAuthoringKey::Escape, cx) { + return false; + } + if clears_search { self.clear_database_search_hover(cx); } - if handled { - self.sync_database_authoring_input(Some(window), cx); - } - handled + self.sync_database_authoring_input(Some(window), cx); + true } pub(super) fn clear_database_search_hover(&mut self, cx: &mut Context) { diff --git a/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs b/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs index d89bd6e3a3..cf64712b63 100644 --- a/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs +++ b/blocksuite/crates/playground/src/database_authoring/tests_inline_and_overflow.rs @@ -305,7 +305,8 @@ fn more_views_popover_toggles_escapes_and_switches_view() { is_held: false, prefer_character_input: false, }; - assert!(v.database_authoring_key_down(&esc, w, cx)); + v.editor_key_down(&esc, w, cx); + assert!(w.default_prevented()); assert!( !v.flow.database_state.state_for(&db_id).more_views_open, "Escape must dismiss open More views popover" @@ -344,7 +345,8 @@ fn more_views_popover_toggles_escapes_and_switches_view() { is_held: false, prefer_character_input: false, }; - assert!(v.database_authoring_key_down(&esc, w, cx)); + v.editor_key_down(&esc, w, cx); + assert!(w.default_prevented()); let after = v.flow.database_state.state_for(&db_id); assert!(!after.more_views_open); assert!(after.authoring.toolbar_panel.is_none()); diff --git a/blocksuite/crates/playground/src/edgeless/commands.rs b/blocksuite/crates/playground/src/edgeless/commands.rs index 0d4adfdbd8..e273143e22 100644 --- a/blocksuite/crates/playground/src/edgeless/commands.rs +++ b/blocksuite/crates/playground/src/edgeless/commands.rs @@ -209,6 +209,42 @@ impl PlaygroundView { } } + pub(crate) fn dismiss_edgeless_transient_on_escape( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) -> bool { + if self.edgeless.authoring.custom_color_editing + && self.edgeless_element_color_picker.is_some() + { + return self.handle_edgeless_custom_color_key_down(event, "escape", cx); + } + if self.dismiss_edgeless_element_popovers() { + cx.notify(); + return true; + } + if self.edgeless.authoring.inline_edit.is_some() { + self.edgeless_commit_inline_edit(window, cx); + return true; + } + if self.edgeless.authoring.shape_picker_open { + let now_ms = self.now_ms(cx); + self.edgeless.authoring.shape_picker_open = false; + self.edgeless.authoring.tool = EdgelessTool::Select; + if let Some(presence) = self.edgeless_shape_picker_presence.as_mut() { + presence.close(now_ms); + } + cx.notify(); + return true; + } + if self.edgeless.authoring.gesture.take().is_some() { + cx.notify(); + return true; + } + false + } + /// Handle keyboard events in Edgeless mode. Returns `true` if consumed. pub(crate) fn edgeless_key_down( &mut self, @@ -220,16 +256,6 @@ impl PlaygroundView { let cmd = m.secondary(cx); let key = e.keystroke.key.as_str(); - if key == "escape" && self.overlays.close_context_menu(self.now_ms(cx)) { - cx.notify(); - return true; - } - if key == "escape" && self.doc_panel_tab.is_some() { - self.doc_panel_tab = None; - cx.notify(); - return true; - } - // Custom `#RRGGBB` input inside the element toolbar color picker. if self.edgeless.authoring.custom_color_editing && self.edgeless_element_color_picker.is_some() @@ -257,20 +283,10 @@ impl PlaygroundView { // 1. Active inline label editor (Shape / Connector / SurfaceText / Frame title). if let Some(ed) = self.edgeless.authoring.label_editor_mut() { if ed.composing() || e.prefer_character_input { - if key == "escape" { - ed.cancel_preedit(); - window.notify_text_input_changed(&self.editor_focus); - cx.notify(); - return true; - } return false; } let word_mod = m.alt || (m.control && !m.platform); match key { - "escape" => { - self.edgeless_commit_inline_edit(window, cx); - return true; - } "tab" if matches!(ed.target, super::LabelTarget::Shape { .. }) && !ed.input.multiline => @@ -432,19 +448,7 @@ impl PlaygroundView { } } - // 2. Active inline spatial block edit (Note / EdgelessText): Escape closes open overlays - // first; a second Escape exits spatial block editing. if self.edgeless.authoring.editing_spatial_block().is_some() { - if key == "escape" && !self.editor.composing() { - if self.overlays.slash_menu().is_some() - || self.overlays.linked_doc_menu().is_some() - || self.overlays.active_text_field().is_some() - { - return false; - } - self.edgeless_commit_inline_edit(window, cx); - return true; - } return false; } @@ -472,17 +476,7 @@ impl PlaygroundView { return true; } "escape" => { - if self.dismiss_edgeless_element_popovers() { - cx.notify(); - return true; - } - let now_ms = self.now_ms(cx); self.edgeless.authoring.tool = EdgelessTool::Select; - self.edgeless.authoring.shape_picker_open = false; - if let Some(p) = self.edgeless_shape_picker_presence.as_mut() { - p.close(now_ms); - } - self.edgeless.authoring.gesture = None; self.edgeless.authoring.hovered_note_slice = None; self.edgeless.authoring.selection.clear(); cx.notify(); diff --git a/blocksuite/crates/playground/src/editor_session/commands.rs b/blocksuite/crates/playground/src/editor_session/commands.rs index 8a917e1ad2..c182afc0dd 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, LinkPopupAction, LinkPopupTarget, OverlayEvent}; +use crate::overlays::{LinkPopupAction, LinkPopupTarget, OverlayEvent}; use crate::rich_text::TextBiIndex; #[cfg(test)] @@ -592,62 +592,7 @@ impl PlaygroundView { w: &mut Window, cx: &mut Context, ) { - if self.pdf_viewer_key_down(e, cx) { - w.prevent_default(); - cx.stop_propagation(); - return; - } - if self.touch_selection_menu_open { - self.touch_selection_menu_open = false; - cx.notify(); - } - if self.mode == crate::PlaygroundMode::Edgeless { - // A caption edited on the canvas owns every key; unhandled ones arrive as text. - if self.caption_editor.is_some() { - if self.caption_editor_key_down(e, w, cx) { - w.prevent_default(); - cx.stop_propagation(); - } - return; - } - if self.edgeless_key_down(e, w, cx) { - w.prevent_default(); - cx.stop_propagation(); - return; - } - if self.edgeless.authoring.editing_spatial_block().is_none() { - return; - } - } - if self.editor.preedit.is_some() || e.prefer_character_input { - return; - } - // An open link field or slash menu takes its keys before the document does. - if self.overlay_key_down(e, w, cx) { - w.prevent_default(); - cx.stop_propagation(); - return; - } - // A composition in the link or equation field keeps its keys from the document as well. - if self - .overlays - .active_text_field() - .is_some_and(LinkBar::composing) - { - return; - } - // Focused in-place table cell or caption editor intercepts keys before document commands. - if self.table_cell_key_down(e, w, cx) || self.caption_editor_key_down(e, w, cx) { - w.prevent_default(); - cx.stop_propagation(); - return; - } - if self.table_cell.is_some() || self.caption_editor.is_some() { - return; - } - if self.database_authoring_key_down(e, w, cx) { - w.prevent_default(); - cx.stop_propagation(); + if self.route_editor_key_before_document(e, w, cx) { return; } // Active whole-block selection intercepts navigation/edit/clipboard keys first. diff --git a/blocksuite/crates/playground/src/editor_session/escape.rs b/blocksuite/crates/playground/src/editor_session/escape.rs new file mode 100644 index 0000000000..83575e1117 --- /dev/null +++ b/blocksuite/crates/playground/src/editor_session/escape.rs @@ -0,0 +1,147 @@ +use ui::{Context, EntityInputHandler, KeyDownEvent, Window}; + +use crate::{PlaygroundMode, PlaygroundView, overlays::LinkBar}; + +impl PlaygroundView { + /// Whether the editor's document input owns keyboard focus. + pub fn editor_input_is_focused(&self, window: &Window) -> bool { + self.editor_focus.is_focused(window) + } + + /// Cancel the active editor input's composition without writing text to the document. + pub fn cancel_active_composition( + &mut self, + window: &mut Window, + cx: &mut Context, + ) -> bool { + if self.marked_text_range(window, cx).is_none() { + return false; + } + self.replace_and_mark_text_in_range(None, "", None, window, cx); + true + } + + /// Cancel the active composition or dismiss one transient editor interaction. + /// A body caret or block selection does not claim Escape. + pub fn dismiss_transient_on_escape( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) -> bool { + debug_assert_eq!(event.keystroke.key, "escape"); + if self.cancel_active_composition(window, cx) || self.pdf_viewer_key_down(event, cx) { + return true; + } + if std::mem::take(&mut self.touch_selection_menu_open) { + cx.notify(); + return true; + } + if self.doc_panel_tab.take().is_some() { + cx.notify(); + return true; + } + if self.overlay_key_down(event, window, cx) { + return true; + } + if self.overlays.keyboard_toolbar_active_panel().is_some() { + self.overlays.close_keyboard_toolbar_panel(); + cx.notify(); + return true; + } + if self.image_resize_drag.is_some() { + self.cancel_image_resize_drag(); + cx.notify(); + return true; + } + if self.scrollbar_drag.take().is_some() + || self.overlays.table_hover.add_drag.take().is_some() + { + cx.notify(); + return true; + } + if self.table_cell_key_down(event, window, cx) + || self.caption_editor_key_down(event, window, cx) + || self.dismiss_database_transient_on_escape(window, cx) + { + return true; + } + self.mode == PlaygroundMode::Edgeless + && self.dismiss_edgeless_transient_on_escape(event, window, cx) + } + + pub(super) fn route_editor_key_before_document( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let escape = event.keystroke.key == "escape"; + let handled = if escape { + if self.dismiss_transient_on_escape(event, window, cx) { + true + } else if !self.editor_input_is_focused(window) + && self.editor_focus.contains_focused(window, cx) + { + return true; + } else if self.mode == PlaygroundMode::Edgeless { + self.edgeless_key_down(event, window, cx) + } else { + self.database_authoring_key_down(event, window, cx) + } + } else if self.pdf_viewer_key_down(event, cx) { + true + } else { + if std::mem::take(&mut self.touch_selection_menu_open) { + cx.notify(); + } + if self.mode == PlaygroundMode::Edgeless { + // A canvas caption owns its keys, including text sent through the input handler. + if self.caption_editor.is_some() { + let handled = self.caption_editor_key_down(event, window, cx); + if handled { + window.prevent_default(); + cx.stop_propagation(); + } + return true; + } + if self.edgeless_key_down(event, window, cx) { + window.prevent_default(); + cx.stop_propagation(); + return true; + } + if self.edgeless.authoring.editing_spatial_block().is_none() { + return true; + } + } + if self.editor.preedit.is_some() || event.prefer_character_input { + return true; + } + if self.overlay_key_down(event, window, cx) { + true + } else { + if self + .overlays + .active_text_field() + .is_some_and(LinkBar::composing) + { + return true; + } + if self.table_cell_key_down(event, window, cx) + || self.caption_editor_key_down(event, window, cx) + { + true + } else if self.table_cell.is_some() || self.caption_editor.is_some() { + return true; + } else { + self.database_authoring_key_down(event, window, cx) + } + } + }; + if handled { + window.prevent_default(); + cx.stop_propagation(); + } + handled + } +} diff --git a/blocksuite/crates/playground/src/editor_session/mod.rs b/blocksuite/crates/playground/src/editor_session/mod.rs index 6d2833e6fd..0c612dc7f5 100644 --- a/blocksuite/crates/playground/src/editor_session/mod.rs +++ b/blocksuite/crates/playground/src/editor_session/mod.rs @@ -5,6 +5,7 @@ mod clipboard_ops; mod commands; mod composition; mod edit_ops; +mod escape; mod input_handler; mod markdown; mod navigation; diff --git a/blocksuite/crates/playground/src/overlays/view.rs b/blocksuite/crates/playground/src/overlays/view.rs index 1b1153a601..ca63b26cfb 100644 --- a/blocksuite/crates/playground/src/overlays/view.rs +++ b/blocksuite/crates/playground/src/overlays/view.rs @@ -691,27 +691,13 @@ impl PlaygroundView { cx.notify(); } - /// Offer a key to the open record sheet, link field, linked-doc menu, or slash menu before the document gets it. + /// Offer a key to the linked-doc menu and overlay controls. pub(crate) fn overlay_key_down( &mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context, ) -> bool { - // `Escape` in the record title ends the edit (see `database_authoring_key_down`), then - // closes the record sheet. - if self.database_record_sheet.is_some() - && event.keystroke.key.as_str() == "escape" - && !self.record_input_active() - { - self.close_database_record_sheet(cx); - return true; - } - if self.doc_panel_tab.is_some() && event.keystroke.key.as_str() == "escape" { - self.doc_panel_tab = None; - cx.notify(); - return true; - } if self.handle_linked_doc_key_down(event, window, cx) { return true; } diff --git a/blocksuite/crates/playground/src/overlays/view_context_menu.rs b/blocksuite/crates/playground/src/overlays/view_context_menu.rs index 2a6db61845..e809973b9a 100644 --- a/blocksuite/crates/playground/src/overlays/view_context_menu.rs +++ b/blocksuite/crates/playground/src/overlays/view_context_menu.rs @@ -1964,7 +1964,7 @@ mod tests { app.update(|cx| { win.update(cx, |v, w, cx| { - v.edgeless_key_down( + v.editor_key_down( &ui::KeyDownEvent { keystroke: ui::Keystroke::parse("escape").unwrap(), is_held: false, diff --git a/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs b/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs index 3a882b7dfa..f1f2aefd17 100644 --- a/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs +++ b/blocksuite/crates/playground/src/overlays/view_table_cell/mod.rs @@ -514,7 +514,7 @@ impl PlaygroundView { let key = e.keystroke.key.as_str(); let m = e.keystroke.modifiers; let cmd = m.secondary(cx); - if composing || e.prefer_character_input { + if composing || (e.prefer_character_input && key != "escape") { if key == "escape" { let _ = self.table_cell_input(window, cx, |cell| { cell.input.cancel_preedit(); diff --git a/packages/frontend/desktop/src/editor_host/references.rs b/packages/frontend/desktop/src/editor_host/references.rs index f4dec52a21..03b051ca26 100644 --- a/packages/frontend/desktop/src/editor_host/references.rs +++ b/packages/frontend/desktop/src/editor_host/references.rs @@ -11,7 +11,9 @@ use ui::{ App, Bounds, Context, Entity, MouseButton, MouseDownEvent, WeakEntity, Window, point, px, }; -use crate::{split_view::PaneId, workbench::DesktopShellView}; +use crate::{split_view::PaneId, state::DesktopAppState, workbench::DesktopShellView}; + +use super::DesktopEditorHost; pub(crate) fn reference_modifiers( shift: Rc>, @@ -34,14 +36,10 @@ pub(crate) fn open_inline_reference( if event.button != MouseButton::Left || event.click_count != 1 || event.modifiers.alt { return; } - if let Some(doc_id) = inline_reference_at(editor.read(app), event, window) - && shell - .update(app, |shell, cx| { - shell.open_editor_reference(pane_id, &doc_id, event.modifiers.shift, cx) - }) - .ok() - == Some(true) - { + if let Some(doc_id) = inline_reference_at(editor.read(app), event, window) { + let _ = shell.update(app, |shell, cx| { + shell.open_editor_reference(pane_id, &doc_id, event.modifiers.shift, cx); + }); window.prevent_default(); app.stop_propagation(); } @@ -95,13 +93,15 @@ impl DesktopShellView { doc_id: &str, peek: bool, cx: &mut Context, - ) -> bool { - if self.state.store.ensure_doc_hydrated(doc_id) != Ok(true) { - return false; + ) { + if !self.state.is_openable_doc(doc_id) + || self.state.store.ensure_doc_hydrated(doc_id) != Ok(true) + { + return; } if let Some(id) = pane_id { let Some(index) = self.state.split.panes.iter().position(|pane| pane.id == id) else { - return false; + return; }; self.state.split.focus_pane(index); } @@ -112,6 +112,31 @@ impl DesktopShellView { self.state.open_doc_in_active_pane(doc_id); } cx.notify(); - true + } +} + +impl DesktopEditorHost { + pub(crate) fn rendered_pane_entity(&self, id: PaneId) -> Option> { + if !self.rendered_panes_this_frame.contains(&id) { + return None; + } + self.pane_entity(id) + } + + pub(crate) fn retain_openable_editors(&mut self, state: &DesktopAppState, cx: &App) { + let workspace = &state.store.active_workspace().id; + self.pane_editors.retain(|_, mounted| { + let keep = &mounted.workspace_id != workspace || state.is_openable_doc(&mounted.doc_id); + if !keep { + mounted.entity.read(cx).clear_wasm_html_embeds(); + } + keep + }); + if self.peek_editor.as_ref().is_some_and(|mounted| { + &mounted.workspace_id != workspace || !state.is_openable_doc(&mounted.doc_id) + }) && let Some(mounted) = self.peek_editor.take() + { + mounted.entity.read(cx).clear_wasm_html_embeds(); + } } } diff --git a/packages/frontend/desktop/src/peek_view.rs b/packages/frontend/desktop/src/peek_view.rs index 6f6f185508..82ff99da60 100644 --- a/packages/frontend/desktop/src/peek_view.rs +++ b/packages/frontend/desktop/src/peek_view.rs @@ -2,12 +2,16 @@ use playground::PlaygroundView; use ui::{ - App, AppContext, BoxShadow, Context, Entity, InteractiveElement, IntoElement, ParentElement, - RenderOnce, StatefulInteractiveElement, Styled, Window, div, hsla, px, svg, + App, AppContext, BoxShadow, Context, Entity, FocusHandle, InteractiveElement, IntoElement, + ParentElement, RenderOnce, StatefulInteractiveElement, Styled, WeakFocusHandle, Window, div, + hsla, px, svg, }; use crate::{ CLOSE_ICON_SVG, DesktopFlexExt, DesktopPalette, SPLIT_ICON_SVG, + editor_host::DesktopEditorHost, + split_view::PaneId, + state::DesktopAppState, workbench::{DesktopShellView, backdrop}, }; @@ -25,6 +29,7 @@ pub struct PeekViewState { pub doc_id: Option, pub source_doc_id: Option, pub scroll_y: f32, + pub(crate) focus_pane: Option, } impl PeekViewState { @@ -36,15 +41,164 @@ impl PeekViewState { self.doc_id = Some(target_doc_id.into()); self.source_doc_id = source_doc_id; self.scroll_y = 0.0; + self.focus_pane = None; } pub fn close(&mut self) { self.doc_id = None; self.source_doc_id = None; self.scroll_y = 0.0; + self.focus_pane = None; } } +pub(crate) struct PeekFocus { + pub(crate) active_pane_focus: FocusHandle, + pub(crate) editor_scope: FocusHandle, + pub(crate) last_active_pane: Option, + session: Option, +} + +struct PeekFocusSession { + workspace: String, + target: Option, + source_pane: PaneId, + source_doc: Option, + source_focus: Option, +} + +impl PeekFocus { + pub(crate) fn new(cx: &mut App) -> Self { + Self { + active_pane_focus: cx.focus_handle(), + editor_scope: cx.focus_handle(), + last_active_pane: None, + session: None, + } + } + + pub(crate) fn mount( + &mut self, + state: &mut DesktopAppState, + host: &mut DesktopEditorHost, + size: (f32, f32), + window: &mut Window, + cx: &mut Context, + ) -> Option> { + let doc_id = state.peek_view.doc_id.as_deref()?; + let workspace = &state.store.active_workspace().id; + let source = state.split.active(); + if self + .session + .as_ref() + .is_none_or(|session| &session.workspace != workspace) + { + let focused_pane = self + .last_active_pane + .filter(|_| self.active_pane_focus.contains_focused(window, cx)); + self.session = Some(PeekFocusSession { + workspace: workspace.clone(), + target: None, + source_pane: source.id, + source_doc: source.active_route().doc_id().map(ToOwned::to_owned), + source_focus: window + .focused(cx) + .filter(|focus| { + focused_pane == Some(source.id) && focus != &self.active_pane_focus + }) + .map(|focus| focus.downgrade()), + }); + cancel_composition( + host.pane_entity(focused_pane.unwrap_or(source.id)).as_ref(), + window, + cx, + ); + } + let session = self.session.as_mut()?; + let changed = session.target.as_deref() != Some(doc_id); + if changed { + cancel_composition(host.peek_entity().as_ref(), window, cx); + } + let editor = + host.ensure_peek_editor(doc_id, state.theme, size.0, size.1, &mut state.store, cx)?; + if changed { + focus_editor(&editor, window, cx); + session.target = Some(doc_id.to_owned()); + } + Some(editor) + } + + pub(crate) fn cover(&mut self, host: &DesktopEditorHost, window: &mut Window, cx: &mut App) { + if self + .session + .as_mut() + .and_then(|session| session.target.take()) + .is_some() + { + cancel_composition(host.peek_entity().as_ref(), window, cx); + } + } + + pub(crate) fn leave( + &mut self, + state: &mut DesktopAppState, + host: &DesktopEditorHost, + shell_focus: &FocusHandle, + window: &mut Window, + cx: &mut App, + ) { + let destination = state.peek_view.focus_pane.take(); + let Some(session) = self.session.take() else { + return; + }; + cancel_composition(host.peek_entity().as_ref(), window, cx); + let pane = state.split.panes.iter().find(|pane| { + if let Some(id) = destination { + pane.id == id + } else { + session.workspace == state.store.active_workspace().id + && pane.id == session.source_pane + && pane.active_route().doc_id() == session.source_doc.as_deref() + } + }); + if let Some(pane) = pane + && let Some(doc_id) = pane.active_route().doc_id() + && state.is_openable_doc(doc_id) + && (destination.is_some() || !state.store.is_readonly_sqlite()) + && let Some(editor) = host.rendered_pane_entity(pane.id) + { + if destination.is_none() + && state.split.active().id == pane.id + && let Some(focus) = session.source_focus.and_then(|focus| focus.upgrade()) + && self.active_pane_focus.contains(&focus, window) + { + window.focus(&focus, cx); + editor.update(cx, |_, cx| cx.notify()); + } else { + focus_editor(&editor, window, cx); + } + } else { + window.focus(shell_focus, cx); + } + } +} + +fn cancel_composition(editor: Option<&Entity>, window: &mut Window, cx: &mut App) { + if let Some(editor) = editor { + editor.update(cx, |view, cx| view.cancel_active_composition(window, cx)); + } +} + +fn focus_editor(editor: &Entity, window: &mut Window, cx: &mut App) { + editor.update(cx, |view, cx| { + if let Some(selection) = view.document_selection().cloned() { + view.select_document_range(selection, window, cx); + } else { + view.focus_first_text_block(window, cx); + } + }); +} + const EXPAND_FULL_ICON_SVG: &[u8] = br#""#; const CONTROL_SIZE: f32 = 32.0; const CONTROL_GAP: f32 = 8.0; @@ -83,11 +237,13 @@ fn peek_left(vw: f32, width: f32) -> f32 { pub(crate) fn render_peek_view_modal( peek_entity: Option>, + editor_scope: FocusHandle, palette: DesktopPalette, cx: &mut Context, ) -> impl IntoElement { ui::ViewElement::new(PeekModal { editor: peek_entity, + editor_scope, palette, shell: cx.entity(), }) @@ -95,6 +251,7 @@ pub(crate) fn render_peek_view_modal( struct PeekModal { editor: Option>, + editor_scope: FocusHandle, palette: DesktopPalette, shell: Entity, } @@ -114,6 +271,7 @@ impl RenderOnce for PeekModal { let body = if let Some(editor) = self.editor { div() + .track_focus(&self.editor_scope) .w_full() .h_full() .capture_any_mouse_down(crate::editor_host::open_inline_reference( @@ -189,11 +347,11 @@ impl RenderOnce for PeekModal { scrim: hsla(0.0, 0.0, 0.0, 0.70), ..palette }, - move |_, window, app| { + move |_, _, app| { shell.update(app, |shell, cx| { shell.sync_editors(cx); shell.state.apply_peek_action(PeekAction::Close); - shell.dismiss_modal(window, cx); + cx.notify(); }); }, )) @@ -267,12 +425,12 @@ fn control( .flex() .items_center() .justify_center() - .on_click(move |_, window, app| { + .on_click(move |_, _, app| { app.stop_propagation(); shell.update(app, |shell, cx| { shell.sync_editors(cx); shell.state.apply_peek_action(action); - shell.dismiss_modal(window, cx); + cx.notify(); }); }) .child( diff --git a/packages/frontend/desktop/src/split_view.rs b/packages/frontend/desktop/src/split_view.rs index ca7f4a8d01..e9f0518a28 100644 --- a/packages/frontend/desktop/src/split_view.rs +++ b/packages/frontend/desktop/src/split_view.rs @@ -1,7 +1,7 @@ //! Multi-tab workbench panes, side-by-side Split View, and per-pane independent //! navigation history (`Alt/Cmd+[` and `Alt/Cmd+]`) backed by `affine_client::NavHistory`. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use affine_client::{DirectKind, NavEntry, NavHistory, NavTarget, Origin, Scope}; use blocksuite_editor::{block_flow::BlockFlow, edgeless::EdgelessCanvasState}; @@ -342,6 +342,68 @@ impl SplitLayout { .flat_map(PaneState::history_entries) } + pub(crate) fn retain_doc_routes(&mut self, scope: &Scope, openable: impl Fn(&str) -> bool) { + for pane in self.panes.iter_mut().chain( + self.app_tab_splits + .values_mut() + .flat_map(|split| &mut split.panes), + ) { + for history in + std::iter::once(&mut pane.history).chain(pane.inactive_history.values_mut()) + { + let invalid: BTreeSet<_> = history + .entries() + .iter() + .filter_map(|entry| { + entry + .target + .doc_id() + .filter(|id| !openable(id)) + .map(ToOwned::to_owned) + }) + .collect(); + for id in invalid { + history.remove_target(scope, &NavTarget::Doc(id)); + } + } + let active_removed = pane.active_route().doc_id().is_some_and(|id| !openable(id)); + for tab in &mut pane.tabs { + if tab.route.doc_id().is_some_and(|id| !openable(id)) { + tab.route = DesktopRoute::AllDocs; + tab.mode = DocViewMode::Page; + if let Some(history) = pane.inactive_history.get_mut(&tab.id) + && history + .current() + .is_none_or(|entry| entry.target != NavTarget::AllDocs) + { + history.push( + scope.clone(), + NavTarget::AllDocs, + Origin::Direct(DirectKind::AllDocs), + None, + ); + } + } + } + if active_removed { + if pane + .history + .current() + .is_none_or(|entry| entry.target != NavTarget::AllDocs) + { + pane.history.push( + scope.clone(), + NavTarget::AllDocs, + Origin::Direct(DirectKind::AllDocs), + None, + ); + } + pane.scroll_y = 0.0; + pane.edgeless.camera_initialized = false; + } + } + } + pub fn set_split_ratio(&mut self, ratio: f32) { self.split_ratio = ratio.clamp(Self::MIN_RATIO, Self::MAX_RATIO); } diff --git a/packages/frontend/desktop/src/state.rs b/packages/frontend/desktop/src/state.rs index 9998a15f00..b0ffd1b1a0 100644 --- a/packages/frontend/desktop/src/state.rs +++ b/packages/frontend/desktop/src/state.rs @@ -68,6 +68,7 @@ pub struct DesktopAppState { pub peek_view: PeekViewState, pub inspector_tab: Option, pub modal: Option, + doc_routes_revision: Option, } impl DesktopAppState { @@ -214,6 +215,7 @@ impl DesktopAppState { peek_view: PeekViewState::default(), inspector_tab: None, modal: None, + doc_routes_revision: None, } } @@ -237,8 +239,10 @@ impl DesktopAppState { }); let previous = std::mem::replace(&mut self.split, next); self.parked_layouts.insert(old_id, previous); + self.doc_routes_revision = None; self.sidebar.scroll_y = 0.0; self.peek_view.close(); + self.reconcile_doc_routes(); } pub fn set_theme_preference(&mut self, pref: ThemePreference) { @@ -277,27 +281,59 @@ impl DesktopAppState { }; } - pub fn navigate_active_pane(&mut self, route: DesktopRoute) { - let scope = self.current_scope(); - let mode = match &route { - DesktopRoute::Doc(id) => self.store.get_doc(id).map(|e| match e.meta.default_mode { + /// Whether this workspace contains a document that can be opened outside Trash. + pub fn is_openable_doc(&self, doc_id: &str) -> bool { + is_openable_doc(&self.store, doc_id) + } + + fn openable_doc_mode(&self, doc_id: &str) -> Option { + if !self.is_openable_doc(doc_id) { + return None; + } + self.store + .get_doc(doc_id) + .map(|entry| match entry.meta.default_mode { DocMode::Page => DocViewMode::Page, DocMode::Edgeless => DocViewMode::Edgeless, - }), - _ => None, + }) + } + + pub(crate) fn reconcile_doc_routes(&mut self) { + if self + .peek_view + .doc_id + .as_deref() + .is_some_and(|id| !self.is_openable_doc(id)) + { + self.peek_view.close(); + } + let revision = self.store.derived.meta_rev; + if self.doc_routes_revision != Some(revision) { + let scope = self.current_scope(); + self.split + .retain_doc_routes(&scope, |id| is_openable_doc(&self.store, id)); + self.doc_routes_revision = Some(revision); + } + } + + pub fn navigate_active_pane(&mut self, route: DesktopRoute) { + let mode = if let Some(doc_id) = route.doc_id() { + let Some(mode) = self.openable_doc_mode(doc_id) else { + return; + }; + Some(mode) + } else { + None }; + let scope = self.current_scope(); self.split.active_mut().navigate(scope, route, mode); } pub fn open_doc_in_active_pane(&mut self, doc_id: &str) { + let Some(mode) = self.openable_doc_mode(doc_id) else { + return; + }; let scope = self.current_scope(); - let mode = - self.store - .get_doc(doc_id) - .map_or(DocViewMode::Page, |e| match e.meta.default_mode { - DocMode::Page => DocViewMode::Page, - DocMode::Edgeless => DocViewMode::Edgeless, - }); let route = DesktopRoute::Doc(doc_id.to_string()); if self.web_chrome || self.split.active_pane != 0 { self.split.active_mut().navigate(scope, route, Some(mode)); @@ -308,16 +344,9 @@ impl DesktopAppState { } pub fn open_doc_in_split(&mut self, doc_id: &str) { - let scope = self.current_scope(); - let mode = - self.store - .get_doc(doc_id) - .map_or(DocViewMode::Page, |e| match e.meta.default_mode { - DocMode::Page => DocViewMode::Page, - DocMode::Edgeless => DocViewMode::Edgeless, - }); - self.split - .open_in_split(scope, DesktopRoute::Doc(doc_id.to_string()), mode); + if let Some(mode) = self.openable_doc_mode(doc_id) { + self.open_doc_in_split_with_mode(doc_id.to_owned(), mode); + } } pub(crate) fn open_app_tab(&mut self, mode: DocViewMode) { @@ -331,14 +360,14 @@ impl DesktopAppState { use affine_store::directory::{CreateDocId, CreateDocRequest, DocId}; use blocksuite_playground_doc::{session::PageDocSession, try_random_client_id}; - if self.store.is_readonly_sqlite() || !self.store.ensure_doc_hydrated(doc_id).ok()? { + if self.store.is_readonly_sqlite() + || !self.is_openable_doc(doc_id) + || !self.store.ensure_doc_hydrated(doc_id).ok()? + { return None; } let now = self.tick_ms(); - let source = self - .store - .get_doc(doc_id) - .filter(|entry| !entry.meta.trashed)?; + let source = self.store.get_doc(doc_id)?; let client_id = try_random_client_id().ok()?; let id = format!("doc-{client_id:x}"); let mut page = PageDocSession::new(&id, client_id).ok()?; @@ -394,6 +423,9 @@ impl DesktopAppState { } pub(crate) fn open_doc_in_split_with_mode(&mut self, doc_id: String, mode: DocViewMode) { + if !self.is_openable_doc(&doc_id) { + return; + } let scope = self.current_scope(); self.split .open_in_split(scope, DesktopRoute::Doc(doc_id), mode); @@ -404,7 +436,8 @@ impl DesktopAppState { || !self .store .get_doc(doc_id) - .is_some_and(|doc| !doc.meta.trashed && doc.meta.title != title) + .is_some_and(|doc| doc.meta.title != title) + || !self.is_openable_doc(doc_id) { return false; } @@ -413,6 +446,15 @@ impl DesktopAppState { } pub fn open_split_edgeless_for_active_doc(&mut self) { + if self + .split + .active() + .active_route() + .doc_id() + .is_some_and(|id| !self.is_openable_doc(id)) + { + return; + } let scope = self.current_scope(); self.split.split_active_doc_opposite_mode(scope); } @@ -472,17 +514,17 @@ impl DesktopAppState { return false; } let now = self.tick_ms(); - self.store.trash_doc(doc_id, now) + let changed = self.store.trash_doc(doc_id, now); + if changed { + self.reconcile_doc_routes(); + } + changed } pub(crate) fn trash_header_doc(&mut self, doc_id: &str) { - if self.trash_doc(doc_id) { - let scope = self.current_scope(); - for pane in &mut self.split.panes { - if pane.active_route().doc_id() == Some(doc_id) { - pane.navigate(scope.clone(), DesktopRoute::Trash, None); - } - } + let active_doc = self.split.active().active_route().doc_id() == Some(doc_id); + if self.trash_doc(doc_id) && active_doc { + self.navigate_active_pane(DesktopRoute::Trash); } } @@ -498,7 +540,11 @@ impl DesktopAppState { if self.store.is_readonly_sqlite() { return false; } - self.store.permanently_delete_doc(doc_id) + let changed = self.store.permanently_delete_doc(doc_id); + if changed { + self.reconcile_doc_routes(); + } + changed } pub fn open_quick_search(&mut self) { @@ -508,6 +554,9 @@ impl DesktopAppState { } pub fn open_peek_view(&mut self, target_doc_id: &str) { + if !self.is_openable_doc(target_doc_id) { + return; + } self.modal = None; self.quick_search.close(); let source = self @@ -522,12 +571,17 @@ impl DesktopAppState { pub fn apply_peek_action(&mut self, action: PeekAction) { let target = self.peek_view.doc_id.clone(); self.peek_view.close(); - if let Some(doc_id) = target { + if let Some(doc_id) = target.filter(|id| self.is_openable_doc(id)) { match action { - PeekAction::OpenInCurrentPane => self.open_doc_in_active_pane(&doc_id), + PeekAction::OpenInCurrentPane => { + let pane = self.split.active_pane; + self.open_doc_in_active_pane(&doc_id); + self.split.focus_pane(pane); + } PeekAction::OpenInSplitView => self.open_doc_in_split(&doc_id), - PeekAction::Close => {} + PeekAction::Close => return, } + self.peek_view.focus_pane = Some(self.split.active().id); } } @@ -618,9 +672,15 @@ impl DesktopAppState { } } +fn is_openable_doc(store: &DesktopDocStore, doc_id: &str) -> bool { + store + .get_doc(doc_id) + .is_some_and(|entry| !entry.meta.trashed) +} + /// First route of a workspace that has no layout yet. fn initial_route(store: &DesktopDocStore) -> DesktopRoute { - if store.get_doc("doc-arch").is_some() { + if is_openable_doc(store, "doc-arch") { DesktopRoute::Doc("doc-arch".into()) } else if let Some(first) = store.visible_docs().first() { DesktopRoute::Doc(first.id.clone()) diff --git a/packages/frontend/desktop/src/workbench/mod.rs b/packages/frontend/desktop/src/workbench/mod.rs index d119d815f4..756a8ae4ca 100644 --- a/packages/frontend/desktop/src/workbench/mod.rs +++ b/packages/frontend/desktop/src/workbench/mod.rs @@ -9,6 +9,9 @@ mod preferences; mod search_input; mod topbar; +#[cfg(test)] +mod peek_lifecycle_tests; + pub use local_workspace::{LocalDocStore, LocalWorkspaces, StoredDocs, StoredWorkspaces}; use blocksuite_editor::inline_input::Utf16ImeBuffer; @@ -32,7 +35,7 @@ use crate::{ editor_host::{DesktopEditorHost, reference_modifiers}, palette_for, pane_render::render_pane_content, - peek_view::{peek_body_size, render_peek_view_modal}, + peek_view::{PeekFocus, peek_body_size, render_peek_view_modal}, quick_search::{QUICK_SEARCH_HEIGHT, render_quick_search_modal}, settings_modal::render_settings_modal, sidebar::render_sidebar, @@ -59,6 +62,7 @@ pub struct DesktopShellView { #[cfg(target_arch = "wasm32")] was_split: bool, modal_return_focus: Option, + peek_focus: PeekFocus, search_input: Utf16ImeBuffer, resize: Option, docked_sidebar_open: Option, @@ -89,6 +93,7 @@ impl DesktopShellView { #[cfg(target_arch = "wasm32")] was_split: false, modal_return_focus: None, + peek_focus: PeekFocus::new(cx), search_input: Utf16ImeBuffer::default(), resize: None, docked_sidebar_open: None, @@ -119,6 +124,28 @@ impl DesktopShellView { } } else { self.capture_modal_key(event, window, cx); + if key == "escape" && !window.default_prevented() && self.state.peek_view.is_open() { + let editor = self.editor_host.peek_entity().filter(|editor| { + editor.read(cx).active_doc_id() == self.state.peek_view.doc_id.as_deref() + }); + if self.peek_focus.editor_scope.contains_focused(window, cx) + && editor + .as_ref() + .is_some_and(|editor| !editor.read(cx).editor_input_is_focused(window)) + { + return; + } + if !editor.is_some_and(|editor| { + editor.update(cx, |view, cx| { + view.dismiss_transient_on_escape(event, window, cx) + }) + }) { + self.state.peek_view.close(); + } + window.prevent_default(); + cx.stop_propagation(); + cx.notify(); + } } } @@ -194,6 +221,7 @@ impl DesktopShellView { /// Synchronize live CRDT edits across all mounted `Entity` panes. pub fn sync_editors(&mut self, cx: &mut Context) { + self.editor_host.retain_openable_editors(&self.state, cx); self.editor_host.sync_all(&mut self.state.store, cx); } @@ -220,12 +248,12 @@ impl DesktopShellView { { return false; } - self.editor_host.sync_all(store, cx); let previous = store.active_workspace_idx; + self.sync_editors(cx); self.state.switch_workspace(index); - let store = &mut self.state.store; - if store.active_workspace_idx != index - || store.ensure_doc_hydrated(&target.doc_id) != Ok(true) + if self.state.store.active_workspace_idx != index + || !self.state.is_openable_doc(&target.doc_id) + || self.state.store.ensure_doc_hydrated(&target.doc_id) != Ok(true) { self.state.switch_workspace(previous); return false; @@ -246,6 +274,7 @@ impl DesktopShellView { /// 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) { + self.editor_host.retain_openable_editors(&self.state, cx); if self.editor_host.sync_all(&mut self.state.store, cx) { cx.notify(); } @@ -275,10 +304,11 @@ impl Render for DesktopShellView { } // Sync all mounted editors BEFORE pruning closed panes so closing a split pane // never discards uncommitted Yjs V1 edits. - self.editor_host.sync_all(&mut self.state.store, cx); + self.sync_editors(cx); if !self.state.web_chrome { self.state.split.sync_app_tab(); } + self.state.reconcile_doc_routes(); self.save_local_workspaces_if_changed(); #[cfg(target_arch = "wasm32")] { @@ -296,10 +326,9 @@ impl Render for DesktopShellView { self.editor_host.begin_html_embed_frame(); let quick_search_open = self.state.quick_search.open; - let peek_open = !quick_search_open && self.state.peek_view.doc_id.is_some(); - let settings_open = !quick_search_open - && !peek_open - && matches!(self.state.modal, Some(DesktopModal::Settings)); + let settings_open = + !quick_search_open && matches!(self.state.modal, Some(DesktopModal::Settings)); + let peek_open = !quick_search_open && !settings_open && self.state.peek_view.is_open(); if quick_search_open || peek_open || settings_open { self.header_overlay = None; @@ -468,6 +497,9 @@ impl Render for DesktopShellView { .bg(palette.border), ); } + if idx == self.state.split.active_pane { + pane_el = pane_el.track_focus(&self.peek_focus.active_pane_focus); + } panes_row = panes_row.child(pane_el); } @@ -635,17 +667,23 @@ impl Render for DesktopShellView { palette, cx, )); - } else if peek_open && let Some(peek_doc_id) = self.state.peek_view.doc_id.clone() { - let (peek_w, peek_h) = peek_body_size(vp_w, vp_h); - let peek_entity = self.editor_host.ensure_peek_editor( - &peek_doc_id, - self.state.theme, - peek_w, - peek_h, - &mut self.state.store, + } else if peek_open { + let peek_entity = self.peek_focus.mount( + &mut self.state, + &mut self.editor_host, + peek_body_size(vp_w, vp_h), + window, cx, ); - root = root.child(render_peek_view_modal(peek_entity, palette, cx)); + if peek_entity.is_none() { + window.focus(&self.focus_handle, cx); + } + root = root.child(render_peek_view_modal( + peek_entity, + self.peek_focus.editor_scope.clone(), + palette, + cx, + )); } else if settings_open { root = root.child(render_settings_modal( self.state.theme_preference, @@ -661,6 +699,18 @@ impl Render for DesktopShellView { if let Some(header_overlay) = render_header_overlay(self, (vp_w, vp_h), palette, cx) { root = root.child(header_overlay); } + if quick_search_open || settings_open || self.header_overlay.is_some() { + self.peek_focus.cover(&self.editor_host, window, cx); + } else if !peek_open { + self.peek_focus.leave( + &mut self.state, + &self.editor_host, + &self.focus_handle, + window, + cx, + ); + } + self.peek_focus.last_active_pane = Some(self.state.split.active().id); self.editor_host.sync_html_embeds(panes_shielded, cx); root diff --git a/packages/frontend/desktop/src/workbench/peek_lifecycle_tests.rs b/packages/frontend/desktop/src/workbench/peek_lifecycle_tests.rs new file mode 100644 index 0000000000..533cfc21aa --- /dev/null +++ b/packages/frontend/desktop/src/workbench/peek_lifecycle_tests.rs @@ -0,0 +1,742 @@ +#![cfg(not(target_family = "wasm"))] + +use std::{cell::RefCell, rc::Rc}; + +use blocksuite_editor::{ + block_flow::{FlowTextLayout, page_geometry_with_full_width}, + overlays::OverlayEvent, + rich_text::DecorationKind, +}; +use blocksuite_playground_doc::{ + read::BlockContent, + schema::{BlockSpec, DatabaseSpec, DatabaseViewSpec, ParagraphType}, +}; +use ui::{ + AnyWindowHandle, ApplicationHandle, Context, HeadlessPlatform, HeadlessWindow, Keystroke, + Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, PlatformInput, + PlatformInputHandler, PlatformWindow, Point, Window, WindowHandle, point, px, +}; +use ui_tokens::ThemeMode; + +use super::{DesktopAppState, DesktopShellView, LocalDocStore, StoredWorkspaces}; +use crate::{ + editor_host::tests::open_test_shell, + split_view::{DesktopRoute, DocViewMode}, +}; + +const SOURCE: &str = "doc-arch"; +const TARGET: &str = "doc-sync"; +const DATE: &str = "2026-12-02"; +const NOW: i64 = 1_764_400_000_000; + +struct Workbench { + platform: Rc, + app: ApplicationHandle, + handle: WindowHandle, + window: HeadlessWindow, +} + +impl Workbench { + fn new(state: DesktopAppState) -> Self { + let (platform, app, handle, window) = open_test_shell(state, 1440, 900); + let view = Self { + platform, + app, + handle, + window, + }; + view.frame(); + view + } + + 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(|app| self.handle.update(app, f).expect("desktop shell")) + } + + fn escape(&self) { + self.app.update(|app| { + AnyWindowHandle::from(self.handle) + .update(app, |_, window, cx| { + window.dispatch_keystroke(Keystroke::parse("escape").unwrap(), cx); + }) + .unwrap(); + }); + self.window.request_frame(); + } + + fn click_paragraph(&self) { + let position = self.shell(|shell, window, cx| { + let editor = shell + .editor_host() + .pane_entity(shell.state.split.active().id) + .unwrap(); + let editor = editor.read(cx); + let layout = editor.flow_layout().unwrap(); + let paragraph = layout.block("p-1").unwrap(); + let (origin, size) = editor.canvas_rect(window); + let column = page_geometry_with_full_width( + size.width.into(), + editor.is_current_page_full_width(), + ); + point( + origin.x + px(column.column_x + paragraph.x + 12.0), + origin.y + px(paragraph.y - editor.scroll_offset() + paragraph.body.height * 0.5), + ) + }); + self.window.simulate_click(position); + self.frame(); + } + + fn click_reference(&self, shift: bool) { + let position = self.shell(|shell, window, cx| { + let editor = shell.editor_host().pane_entity(shell.state.split.active().id).unwrap(); + let editor = editor.read(cx); + let layout = editor.flow_layout().unwrap(); + let quote = layout.block("q-1").unwrap(); + let text = quote.body.text.as_ref().unwrap(); + let FlowTextLayout::Rich(rich) = &text.layout else { + panic!("expected rich text in the reference block"); + }; + let chip = rich.inline_decorations().iter().find(|decoration| { + matches!(&decoration.kind, DecorationKind::ReferenceChip(reference) if reference.page_id == TARGET) + }).expect("target reference chip"); + let (origin, size) = editor.canvas_rect(window); + let column = page_geometry_with_full_width(size.width.into(), editor.is_current_page_full_width()); + point( + origin.x + px(column.column_x + quote.x + text.x) + chip.bounds.center().x, + origin.y + px(quote.y + text.y - editor.scroll_offset()) + chip.bounds.center().y, + ) + }); + let modifiers = Modifiers { + shift, + ..Default::default() + }; + self.window + .dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { + position, + modifiers, + ..Default::default() + })); + self.window + .dispatch_input(PlatformInput::MouseDown(MouseDownEvent { + button: MouseButton::Left, + position, + modifiers, + click_count: 1, + first_mouse: false, + })); + self.window + .dispatch_input(PlatformInput::MouseUp(MouseUpEvent { + button: MouseButton::Left, + position, + modifiers, + click_count: 1, + })); + self.window.request_frame(); + } + + fn click(&self, id: &str) { + let position: Point = self.shell(|_, window, _| { + let bounds = window.frame_snapshot().elements[id].bounds; + point( + px(bounds.x + bounds.width / 2.0), + px(bounds.y + bounds.height / 2.0), + ) + }); + self.window.simulate_click(position); + self.window.request_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("platform text handler for this frame"); + let result = f(&mut handler); + window.set_input_handler(handler); + result + } + + fn update(&self, doc_id: &str) -> Vec { + self.shell(|shell, _, _| { + shell + .state + .store + .get_doc(doc_id) + .unwrap() + .session + .encode_update_v1() + .unwrap() + }) + } + + fn has_text(&self, doc_id: &str, marker: &str) -> bool { + self.shell(|shell, _, _| { + shell + .state + .store + .get_doc(doc_id) + .unwrap() + .snapshot + .root + .as_ref() + .unwrap() + .walk() + .any(|block| { + matches!(&block.content, + BlockContent::Paragraph { text, .. } if text.plain.contains(marker)) + }) + }) + } +} + +#[test] +fn shift_click_peek_owns_first_ime_input_and_close_restores_source_in_one_frame() { + let ui = Workbench::new(DesktopAppState::seed_showcase(ThemeMode::Light, DATE)); + ui.click_paragraph(); + let source_focus = ui.input(|input| { + input.replace_text_in_range(None, "SOURCE-FIRST"); + input.focus_id().expect("source editor focus") + }); + ui.frame(); + assert!(ui.has_text(SOURCE, "SOURCE-FIRST")); + let source = ui.update(SOURCE); + let target = ui.update(TARGET); + ui.input(|input| { + input.replace_and_mark_text_in_range(None, "source-preedit", None); + assert!(input.marked_text_range().is_some()); + }); + ui.frame(); + + ui.click_reference(true); + ui.shell(|shell, _, _| assert_eq!(shell.state.peek_view.doc_id.as_deref(), Some(TARGET))); + ui.input(|input| { + assert_ne!(input.focus_id(), Some(source_focus)); + assert_eq!(input.marked_text_range(), None); + input.replace_and_mark_text_in_range(None, "目标", Some(2..2)); + assert!(input.marked_text_range().is_some()); + }); + assert_eq!(ui.update(SOURCE), source); + assert_eq!(ui.update(TARGET), target); + ui.frame(); + ui.input(|input| input.replace_text_in_range(None, "目标已提交")); + ui.frame(); + assert!(ui.has_text(TARGET, "目标已提交")); + assert_eq!(ui.update(SOURCE), source); + + ui.click("desktop.peek.close"); + ui.input(|input| { + assert_eq!(input.focus_id(), Some(source_focus)); + assert_eq!(input.marked_text_range(), None); + input.replace_text_in_range(None, "SOURCE-RETURN"); + }); + ui.frame(); + assert!(ui.has_text(SOURCE, "SOURCE-RETURN")); + assert!(!ui.has_text(SOURCE, "目标已提交")); + assert!(!ui.has_text(TARGET, "SOURCE-RETURN")); +} + +#[test] +fn trashed_reference_rejects_normal_and_shift_click_without_changing_the_target() { + let mut state = DesktopAppState::seed_showcase(ThemeMode::Light, DATE); + assert!(state.trash_doc(TARGET)); + assert_eq!(state.store.ensure_doc_hydrated(TARGET), Ok(true)); + let ui = Workbench::new(state); + let target = ui.update(TARGET); + for shift in [false, true] { + ui.click_reference(shift); + ui.shell(|shell, _, _| { + assert!(!shell.state.peek_view.is_open()); + assert_eq!( + shell.state.split.active().active_route().doc_id(), + Some(SOURCE) + ); + assert!(shell.editor_host().peek_entity().is_none()); + }); + assert_eq!(ui.update(TARGET), target); + } +} + +#[derive(Default)] +struct MemoryStore(RefCell); + +impl LocalDocStore for MemoryStore { + fn push_update(&self, workspace_id: &str, doc_id: &str, update: Vec) { + self.0 + .borrow_mut() + .entry(workspace_id.to_owned()) + .or_default() + .entry(doc_id.to_owned()) + .or_default() + .push(update); + } + + fn delete_doc(&self, workspace_id: &str, doc_id: &str) { + if let Some(docs) = self.0.borrow_mut().get_mut(workspace_id) { + docs.remove(doc_id); + } + } + + fn set_route(&self, _: &str, _: Option<&str>) {} +} + +#[test] +fn trash_and_permanent_delete_clear_peek_panes_parked_tabs_and_history_and_survive_reopen() { + for projected in [false, true] { + let disk = Rc::new(MemoryStore::default()); + let (state, sessions) = + DesktopAppState::open_local(&disk.0.borrow(), ThemeMode::Light, DATE, NOW).unwrap(); + let ui = Workbench::new(state); + let parked = ui.shell(|shell, _, cx| { + shell.bind_local_workspaces(sessions, disk.clone(), NOW, cx); + let state = &mut shell.state; + state.open_doc_in_split(TARGET); + let parked_tab = state.split.panes[0].active_tab().id; + let pane = state.split.active_mut(); + let scope = pane.history.current().unwrap().scope.clone(); + pane.open_tab( + scope, + DesktopRoute::Doc(TARGET.into()), + DocViewMode::Edgeless, + ); + pane.select_tab(0); + cx.notify(); + (parked_tab, pane.id) + }); + ui.frame(); + let visible = ui.shell(|shell, _, cx| { + assert!(shell.editor_host().pane_entity(parked.1).is_some()); + let state = &mut shell.state; + state.split.focus_pane(0); + state.open_doc_in_active_pane(TARGET); + state.open_doc_in_split(TARGET); + let visible = state.split.active().id; + state.split.focus_pane(0); + state.open_peek_view(TARGET); + cx.notify(); + visible + }); + ui.frame(); + ui.shell(|shell, _, cx| { + assert!(shell.editor_host().peek_entity().is_some()); + assert!(shell.editor_host().pane_entity(visible).is_some()); + assert_eq!( + shell.state.split.app_tab_split_panes(parked.0)[0].id, + parked.1 + ); + if projected { + assert!(shell.state.store.trash_doc(TARGET, NOW)); + } else { + assert!(shell.state.trash_doc(TARGET)); + assert!(!shell.state.peek_view.is_open()); + } + cx.notify(); + }); + ui.frame(); + ui.shell(|shell, window, cx| { + assert!(!shell.state.peek_view.is_open()); + assert!(shell.editor_host().peek_entity().is_none()); + assert!(shell.editor_host().pane_entity(visible).is_none()); + assert!(shell.editor_host().pane_entity(parked.1).is_none()); + let parked_pane = &shell.state.split.app_tab_split_panes(parked.0)[0]; + assert!( + parked_pane + .tabs + .iter() + .all(|tab| tab.route == DesktopRoute::AllDocs) + ); + assert!( + shell + .state + .split + .panes + .iter() + .all(|pane| pane.active_route() == &DesktopRoute::AllDocs) + ); + assert!( + shell + .state + .split + .history_entries() + .all(|entry| entry.target.doc_id() != Some(TARGET)) + ); + assert!(shell.focus_handle.is_focused(window)); + if projected { + assert!(shell.state.permanently_delete_doc(TARGET)); + } else { + shell.state.navigate_active_pane(DesktopRoute::Trash); + } + cx.notify(); + }); + if !projected { + ui.frame(); + ui.click("desktop.trash.empty"); + ui.click("desktop.trash.confirm.delete"); + } + ui.shell(|shell, _, cx| { + assert!(shell.state.store.get_doc(TARGET).is_none()); + shell.state.navigate_active_pane(DesktopRoute::AllDocs); + shell + .state + .navigate_active_pane(DesktopRoute::Doc(TARGET.into())); + shell.state.open_doc_in_active_pane(TARGET); + shell.state.open_doc_in_split(TARGET); + shell + .state + .open_doc_in_split_with_mode(TARGET.into(), DocViewMode::Page); + shell.state.open_peek_view(TARGET); + assert!(!shell.state.peek_view.is_open()); + assert_eq!( + shell.state.split.active().active_route(), + &DesktopRoute::AllDocs + ); + assert_eq!(shell.state.split.panes.len(), 2); + shell.save_local_workspaces(); + cx.notify(); + }); + drop(ui); + let (cold, _) = + DesktopAppState::open_local(&disk.0.borrow(), ThemeMode::Light, DATE, NOW).unwrap(); + assert!(cold.store.get_doc(TARGET).is_none()); + let ui = Workbench::new(cold); + ui.shell(|shell, _, _| { + assert!(!shell.state.peek_view.is_open()); + assert!(shell.editor_host().peek_entity().is_none()); + assert_eq!( + shell.state.split.active().active_route().doc_id(), + Some(SOURCE) + ); + }); + } +} + +#[test] +fn peek_promotes_focus_to_the_current_or_new_split_editor() { + for (control, split) in [ + ("desktop.peek.open_current", false), + ("desktop.peek.open_split", true), + ] { + let ui = Workbench::new(DesktopAppState::seed_showcase(ThemeMode::Light, DATE)); + ui.click_paragraph(); + ui.click_reference(true); + ui.click(control); + ui.input(|input| input.replace_text_in_range(None, "AFTER-PROMOTION")); + ui.frame(); + ui.shell(|shell, _, _| { + assert_eq!(shell.state.split.is_split(), split); + assert_eq!( + shell.state.split.active().active_route().doc_id(), + Some(TARGET) + ); + assert!(!shell.state.peek_view.is_open()); + }); + assert!(ui.has_text(TARGET, "AFTER-PROMOTION")); + assert!(!ui.has_text(SOURCE, "AFTER-PROMOTION")); + } +} + +#[test] +fn retargeting_peek_cancels_preedit_and_escape_restores_the_original_editor() { + const RETARGETED: &str = "doc-journal-today"; + let ui = Workbench::new(DesktopAppState::seed_showcase(ThemeMode::Light, DATE)); + ui.click_paragraph(); + let source_focus = ui.input(|input| input.focus_id().unwrap()); + let source = ui.update(SOURCE); + ui.click_reference(true); + let first = ui.update(TARGET); + ui.input(|input| { + input.replace_and_mark_text_in_range(None, "discard-on-retarget", None); + assert!(input.marked_text_range().is_some()); + }); + ui.shell(|shell, _, cx| { + shell.state.open_peek_view(RETARGETED); + cx.notify(); + }); + ui.frame(); + ui.input(|input| { + assert_eq!(input.marked_text_range(), None); + input.replace_text_in_range(None, "AFTER-RETARGET"); + }); + ui.frame(); + assert!(ui.has_text(RETARGETED, "AFTER-RETARGET")); + assert_eq!(ui.update(TARGET), first); + + ui.escape(); + ui.shell(|shell, _, _| assert!(!shell.state.peek_view.is_open())); + assert_eq!(ui.input(|input| input.focus_id()), Some(source_focus)); + assert_eq!(ui.update(SOURCE), source); +} + +#[test] +fn escape_dismisses_ime_or_slash_before_closing_peek_and_restoring_source() { + for slash_menu in [false, true] { + let ui = Workbench::new(DesktopAppState::seed_showcase(ThemeMode::Light, DATE)); + ui.click_paragraph(); + let source_focus = ui.input(|input| input.focus_id().expect("source focus")); + let target = ui.update(TARGET); + ui.click_reference(true); + let peek_focus = ui.input(|input| input.focus_id().expect("peek focus")); + assert_ne!(peek_focus, source_focus); + + if slash_menu { + ui.shell(|shell, window, cx| { + let peek = shell.editor_host().peek_entity().unwrap(); + peek.update(cx, |view, cx| { + view.dispatch_overlay( + OverlayEvent::OpenSlashMenu { + block_id: "p-sync".to_owned(), + utf16_offset: 0, + anchor: None, + }, + window, + cx, + ); + assert!(view.overlays().slash_menu().is_some()); + }); + }); + } else { + ui.input(|input| { + input.replace_and_mark_text_in_range(None, "編集中", Some(3..3)); + assert!(input.marked_text_range().is_some()); + }); + } + ui.frame(); + + ui.escape(); + ui.shell(|shell, _, cx| { + assert!(shell.state.peek_view.is_open()); + let peek = shell.editor_host().peek_entity().unwrap(); + assert!(peek.read(cx).overlays().slash_menu().is_none()); + }); + ui.input(|input| { + assert_eq!(input.marked_text_range(), None); + assert_eq!(input.focus_id(), Some(peek_focus)); + }); + assert_eq!(ui.update(TARGET), target); + + ui.escape(); + ui.shell(|shell, _, _| assert!(!shell.state.peek_view.is_open())); + assert_eq!(ui.input(|input| input.focus_id()), Some(source_focus)); + } +} + +#[derive(Clone, Copy, Debug)] +enum PeekControl { + MoreViews, + CalloutPicker, + Caption, + CodeLanguage, +} + +impl PeekControl { + fn open(self, ui: &Workbench) { + match self { + Self::MoreViews => { + ui.shell(|shell, _, cx| { + let peek = shell.editor_host().peek_entity().unwrap(); + peek.update(cx, |view, cx| { + view.edit_document(cx, |doc| { + let page = doc.workspace.page_mut(TARGET).unwrap(); + let views = (0..8) + .map(|index| DatabaseViewSpec { + id: format!("view-{index}"), + name: format!("Planning and delivery tracker {index}"), + mode: "table".into(), + raw: serde_json::json!({ "columns": [] }), + }) + .collect(); + page.add_block( + "peek-db", + BlockSpec::Database(DatabaseSpec { + title: "Planning".into(), + views, + ..Default::default() + }), + Some("note-sync"), + Some(0), + 70, + ) + .unwrap(); + }); + }); + }); + ui.frame(); + let center = ui.shell(|shell, window, cx| { + let peek = shell.editor_host().peek_entity().unwrap(); + let (center, open) = peek + .read(cx) + .database_view_overflow_control("peek-db", window) + .expect("N More trigger"); + assert!(!open); + center + }); + ui.window.simulate_click(center); + } + Self::CalloutPicker => { + ui.shell(|shell, _, cx| { + let peek = shell.editor_host().peek_entity().unwrap(); + peek.update(cx, |view, cx| { + view.edit_document(cx, |doc| { + let page = doc.workspace.page_mut(TARGET).unwrap(); + page.add_block( + "peek-callout", + BlockSpec::Callout { + icon: "💡".into(), + background_color: None, + }, + Some("note-sync"), + None, + 70, + ) + .unwrap(); + page.add_block( + "peek-callout-text", + BlockSpec::Paragraph { + paragraph_type: ParagraphType::Text, + text: "Project note".into(), + }, + Some("peek-callout"), + None, + 71, + ) + .unwrap(); + }); + }); + }); + ui.frame(); + ui.click("page.block.peek-callout.callout_icon"); + ui.shell(|shell, _, cx| { + let peek = shell.editor_host().peek_entity().unwrap(); + assert!(peek.read(cx).block_selection().is_empty()); + }); + } + Self::Caption | Self::CodeLanguage => { + let position = ui.shell(|shell, window, cx| { + let peek = shell.editor_host().peek_entity().unwrap(); + let editor = peek.read(cx); + let layout = editor.flow_layout().unwrap(); + let block = layout.block("code-sync").unwrap(); + let (origin, size) = editor.canvas_rect(window); + let col = page_geometry_with_full_width( + size.width.into(), + editor.is_current_page_full_width(), + ); + point( + origin.x + px(col.column_x + block.x + 50.0), + origin.y + px(block.y - editor.scroll_offset() + 24.0), + ) + }); + ui.window + .dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { + position, + ..Default::default() + })); + ui.frame(); + ui.click(if matches!(self, Self::Caption) { + "page.block.code-sync.caption_btn" + } else { + "page.block.code-sync.language" + }); + } + } + ui.frame(); + } + + fn is_open(self, ui: &Workbench) -> bool { + ui.shell(|shell, window, cx| { + assert!( + shell.state.peek_view.is_open(), + "{self:?} must keep Peek open" + ); + let peek = shell.editor_host().peek_entity().unwrap(); + let editor = peek.read(cx); + match self { + Self::MoreViews => { + editor + .database_view_overflow_control("peek-db", window) + .unwrap() + .1 + } + Self::CalloutPicker => window + .frame_snapshot() + .elements + .contains_key("overlay.callout_icon_picker"), + Self::Caption => editor.active_caption_editor().is_some(), + Self::CodeLanguage => editor.overlays().code_lang_picker().is_some(), + } + }) + } +} + +#[test] +fn escape_dismisses_clicked_control_before_closing_peek_and_restoring_source() { + for control in [ + PeekControl::MoreViews, + PeekControl::CalloutPicker, + PeekControl::Caption, + PeekControl::CodeLanguage, + ] { + let ui = Workbench::new(DesktopAppState::seed_showcase(ThemeMode::Light, DATE)); + ui.click_paragraph(); + let source_focus = ui.input(|input| input.focus_id().expect("source editor focus")); + ui.click_reference(true); + let peek_focus = ui.input(|input| input.focus_id().expect("Peek editor focus")); + + control.open(&ui); + assert!(control.is_open(&ui), "{control:?} opened by click"); + + ui.escape(); + ui.frame(); + assert!(!control.is_open(&ui), "Escape dismisses {control:?}"); + assert_eq!(ui.input(|input| input.focus_id()), Some(peek_focus)); + + ui.escape(); + ui.frame(); + ui.shell(|shell, _, _| assert!(!shell.state.peek_view.is_open())); + assert_eq!(ui.input(|input| input.focus_id()), Some(source_focus)); + } +} + +#[test] +fn escape_cancels_callout_picker_composition_before_dismissing_the_picker() { + let ui = Workbench::new(DesktopAppState::seed_showcase(ThemeMode::Light, DATE)); + ui.click_paragraph(); + let source_focus = ui.input(|input| input.focus_id()); + ui.click_reference(true); + let peek_focus = ui.input(|input| input.focus_id()); + let control = PeekControl::CalloutPicker; + control.open(&ui); + let picker_focus = ui.input(|input| { + input.replace_and_mark_text_in_range(None, "月🌙", Some(3..3)); + assert!(input.marked_text_range().is_some()); + input.focus_id().expect("picker input focus") + }); + assert_ne!(Some(picker_focus), peek_focus); + + ui.escape(); + ui.frame(); + assert!(control.is_open(&ui)); + ui.input(|input| { + assert_eq!(input.marked_text_range(), None); + assert_eq!(input.focus_id(), Some(picker_focus)); + }); + + ui.escape(); + ui.frame(); + assert!(!control.is_open(&ui)); + assert_eq!(ui.input(|input| input.focus_id()), peek_focus); + + ui.escape(); + ui.frame(); + ui.shell(|shell, _, _| assert!(!shell.state.peek_view.is_open())); + assert_eq!(ui.input(|input| input.focus_id()), source_focus); +}