diff --git a/packages/frontend/desktop/src/peek_view.rs b/packages/frontend/desktop/src/peek_view.rs index dec33523ae..1090aeb09f 100644 --- a/packages/frontend/desktop/src/peek_view.rs +++ b/packages/frontend/desktop/src/peek_view.rs @@ -1,10 +1,12 @@ //! Center Peek shell for the live document preview. +use std::{cell::Cell, rc::Rc}; + use playground::PlaygroundView; use ui::{ - App, AppContext, Context, Entity, FocusHandle, Hsla, InteractiveElement, IntoElement, - ParentElement, RenderOnce, StatefulInteractiveElement, Styled, WeakFocusHandle, Window, div, - px, svg, + Anchor, App, AppContext, Bounds, Context, Div, Entity, FocusHandle, Hsla, InteractiveElement, + IntoElement, ParentElement, Pixels, RenderOnce, StatefulInteractiveElement, Styled, + WeakFocusHandle, Window, anchored, canvas, div, point, px, svg, }; use crate::{ @@ -384,23 +386,37 @@ impl RenderOnce for PeekModal { .into_any_element() }; + let mut control = |id: &'static str, label, icon: &'static [u8], action| { + let anchor = window.use_keyed_state( + (ui::ElementId::from("peek-control-anchor"), id), + app, + |_, _| Rc::new(Cell::new(Bounds::default())), + ); + control( + &self.shell, + id, + icon, + action, + palette, + button_bg, + ControlTooltip { + label, + theme, + anchor: anchor.read(app).clone(), + }, + ) + }; let close = control( - &self.shell, "desktop.peek.close", "Close", CLOSE_ICON_SVG, PeekAction::Close, - palette, - button_bg, ); let expand = control( - &self.shell, "desktop.peek.open_current", "Expand to full page", ui_tokens::icons::EXPAND_FULL.svg.as_bytes(), PeekAction::OpenInCurrentPane, - palette, - button_bg, ); let controls = if layout.compact { div() @@ -426,13 +442,10 @@ impl RenderOnce for PeekModal { .child(close) .child(expand) .child(control( - &self.shell, "desktop.peek.open_split", "Open in split view", SPLIT_ICON_SVG, PeekAction::OpenInSplitView, - palette, - button_bg, )) }; @@ -482,17 +495,19 @@ impl RenderOnce for PeekModal { fn control( shell: &Entity, id: &'static str, - label: &'static str, icon: &'static [u8], action: PeekAction, palette: DesktopPalette, background: Hsla, + tooltip: ControlTooltip, ) -> impl IntoElement + use<> { let shell = shell.clone(); let hover_bg = overlay_over(background, palette.hover_overlay); + let anchor = tooltip.anchor.clone(); let mut button = div() .id(id) .snapshot(id, Some("desktop.peek.modal")) + .relative() .w(px(CONTROL_SIZE)) .h(px(CONTROL_SIZE)) .rounded(px(8.0)) @@ -516,27 +531,64 @@ fn control( .size(px(20.0)) .text_color(palette.text_secondary), ); + // Use the button bounds with the native tooltip timer. + button = button.child( + canvas(move |bounds, _, _| anchor.set(bounds), |_, (), _, _| {}) + .absolute() + .inset_0(), + ); button .interactivity() - .tooltip(move |_, app| app.new(|_| ControlTooltip(label, palette)).into()); + .tooltip(move |_, app| app.new(|_| tooltip.clone()).into()); button } -struct ControlTooltip(&'static str, DesktopPalette); +#[derive(Clone)] +struct ControlTooltip { + label: &'static str, + theme: ui_tokens::ThemeMode, + anchor: Rc>>, +} impl ui::Render for ControlTooltip { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - div() - .px(px(8.0)) - .py(px(4.0)) - .rounded(px(4.0)) - .bg(self.1.bg_elevated) - .text_color(self.1.text_primary) - .text_size(px(12.0)) - .child(self.0) + anchored() + .anchor(Anchor::BottomCenter) + .attach(self.anchor.get(), Anchor::TopCenter) + .offset(point(px(0.0), px(-TOOLTIP_GAP))) + .child( + tooltip_bubble(self.label, self.theme) + .snapshot("desktop.peek.control.tooltip", Some("desktop.peek.modal")) + .snapshot_text(self.label), + ) } } +pub(crate) const TOOLTIP_GAP: f32 = 5.0; + +pub(crate) fn tooltip_bubble(label: &'static str, theme: ui_tokens::ThemeMode) -> Div { + let tokens = crate::theme_tokens_for(theme); + div() + .px(px(12.0)) + .py(px(5.0)) + .rounded(px(4.0)) + .bg(crate::theme_color( + tokens, + "--affine-v2-tooltips-background", + tokens.background_primary, + )) + .text_color(crate::theme_color( + tokens, + "--affine-v2-tooltips-foreground", + tokens.text_primary, + )) + .font_family(ui_tokens::FONT_SANS) + .text_size(px(14.0)) + .line_height(px(22.0)) + .whitespace_nowrap() + .child(label) +} + #[cfg(test)] mod tests { use anyhow::{Context as _, Result}; diff --git a/packages/frontend/desktop/src/views_extra/tests/mod.rs b/packages/frontend/desktop/src/views_extra/tests/mod.rs index 2495b4c4e1..250a293cef 100644 --- a/packages/frontend/desktop/src/views_extra/tests/mod.rs +++ b/packages/frontend/desktop/src/views_extra/tests/mod.rs @@ -235,7 +235,7 @@ fn trash_confirmation_blocks_shortcuts_and_escape_leaves_the_trash_unchanged() { ] { app.click(&button); assert!(app.contains("desktop.trash.confirm")); - for key in ["ctrl-k", "cmd-k", "ctrl-n", "enter"] { + for key in ["ctrl-k", "cmd-k", "ctrl-n", "ctrl-enter"] { app.key(key); assert!(app.contains("desktop.trash.confirm"), "{key}"); app.update(|shell, _, _| assert!(!shell.state.quick_search.open, "{key}")); diff --git a/packages/frontend/desktop/src/views_extra/trash/footer.rs b/packages/frontend/desktop/src/views_extra/trash/footer.rs index 9d0ed45ed9..b91fbec0e1 100644 --- a/packages/frontend/desktop/src/views_extra/trash/footer.rs +++ b/packages/frontend/desktop/src/views_extra/trash/footer.rs @@ -7,11 +7,16 @@ use ui::{ InteractiveElement, IntoElement, ParentElement, RenderOnce, StatefulInteractiveElement, Styled, WeakEntity, Window, anchored, deferred, div, point, px, svg, }; -use ui_tokens::{FONT_SANS, ThemeMode}; +use ui_tokens::FONT_SANS; -use super::{DeleteRequest, TrashConfirmations, TrashControls, TrashSelection, confirmation}; +use super::{ + DeleteRequest, TrashConfirmations, TrashControls, TrashSelection, confirmation, + is_activation_key, +}; use crate::{ - DesktopFlexExt, DesktopPalette, TRASH_ICON_SVG, views_extra::PaneLocation, + DesktopFlexExt, DesktopPalette, TRASH_ICON_SVG, + peek_view::{TOOLTIP_GAP, tooltip_bubble}, + views_extra::PaneLocation, workbench::DesktopShellView, }; @@ -118,30 +123,6 @@ struct TrashFooter { shell: Entity, } -fn tooltip_bubble( - id: &'static str, - label: &'static str, - palette: DesktopPalette, - theme: ThemeMode, -) -> impl IntoElement { - div() - .id(id) - .snapshot(id, Some("desktop.shell.root")) - .snapshot_text(label) - .px(px(8.0)) - .py(px(4.0)) - .rounded(px(6.0)) - .border_1() - .border_color(palette.border) - .bg(palette.bg_elevated) - .shadow(crate::theme_shadow(theme, "--affine-popover-shadow")) - .text_color(palette.text_primary) - .text_size(px(12.0)) - .line_height(px(16.0)) - .whitespace_nowrap() - .child(label) -} - impl RenderOnce for TrashFooter { fn render(self, window: &mut Window, app: &mut App) -> impl IntoElement { let Some(location) = PaneLocation::read(self.shell.read(app), self.pane_idx) else { @@ -267,12 +248,12 @@ impl RenderOnce for TrashFooter { button = button .on_click(move |event, window, app| on_click(event, window, app)) .on_key_down(move |event, window, app| { - if matches!(event.keystroke.key.as_str(), "enter" | "space" | " ") - && !event.keystroke.modifiers.modified() - { - on_key(&ClickEvent::default(), window, app); + if is_activation_key(event) { window.prevent_default(); app.stop_propagation(); + if !event.is_held { + on_key(&ClickEvent::default(), window, app); + } } else if event.keystroke.key == "tab" && event.keystroke.modifiers.number_of_modifiers() == 0 { @@ -287,12 +268,21 @@ impl RenderOnce for TrashFooter { } if active_tooltip == Some(kind) { button = button.child( - div().absolute().top_0().right(px(0.0)).child(deferred( - anchored() - .anchor(Anchor::BottomRight) - .offset(point(px(0.0), px(-8.0))) - .child(tooltip_bubble(tooltip_id, label, palette, theme)), - )), + div() + .absolute() + .top(px(-2.0)) + .left(ui::relative(0.5)) + .child(deferred( + anchored() + .anchor(Anchor::BottomCenter) + .offset(point(px(0.0), px(-TOOLTIP_GAP))) + .child( + tooltip_bubble(label, theme) + .id(tooltip_id) + .snapshot(tooltip_id, Some("desktop.shell.root")) + .snapshot_text(label), + ), + )), ); } button @@ -379,15 +369,7 @@ impl RenderOnce for TrashFooter { .child(delete), ); if show_confirm { - footer = footer.child(confirmation( - window.viewport_size(), - &controls, - palette, - theme, - 1, - false, - writable, - )); + footer = footer.child(confirmation(window, app, &controls, palette)); } footer.into_any_element() } diff --git a/packages/frontend/desktop/src/views_extra/trash/mod.rs b/packages/frontend/desktop/src/views_extra/trash/mod.rs index 026720148d..92596341d1 100644 --- a/packages/frontend/desktop/src/views_extra/trash/mod.rs +++ b/packages/frontend/desktop/src/views_extra/trash/mod.rs @@ -1,11 +1,11 @@ use std::collections::{BTreeSet, HashMap}; use ui::{ - AnyElement, App, Context, Div, Entity, EntityId, FontWeight, Global, InteractiveElement, - IntoElement, KeyDownEvent, ParentElement, RenderOnce, StatefulInteractiveElement, Styled, - WeakEntity, Window, div, px, svg, + AnyElement, App, Context, Div, Entity, EntityId, FocusHandle, Focusable, FontWeight, Global, + InteractiveElement, IntoElement, KeyDownEvent, ParentElement, RenderOnce, + StatefulInteractiveElement, Styled, WeakEntity, WeakFocusHandle, Window, div, px, svg, }; -use ui_tokens::{FONT_SANS, ThemeMode}; +use ui_tokens::FONT_SANS; mod footer; @@ -41,6 +41,7 @@ pub(crate) fn render_trash_view( struct TrashSelection { selected: BTreeSet, pending: Option, + confirmation_focus: Option, failed: bool, } @@ -58,7 +59,7 @@ impl TrashConfirmations { } pub(crate) fn capture_trash_confirm_key( - shell: &DesktopShellView, + shell: &mut DesktopShellView, event: &KeyDownEvent, window: &mut Window, cx: &mut Context, @@ -81,19 +82,82 @@ pub(crate) fn capture_trash_confirm_key( cx.global_mut::().0.remove(&shell_id); return false; }; - if event.keystroke.key == "escape" { - selection.update(cx, |state, cx| { - state.dismiss(); - cx.notify(); - }); - cx.global_mut::().0.remove(&shell_id); - cx.notify(); - } window.prevent_default(); cx.stop_propagation(); + + let writable = !shell.state.store.is_readonly_sqlite(); + let focus = selection.read(cx).confirmation_focus.clone(); + match event.keystroke.key.as_str() { + "escape" => resolve_confirmation(shell, &selection, false, window, cx), + "tab" + if event.keystroke.modifiers.number_of_modifiers() + == u8::from(event.keystroke.modifiers.shift) => + { + if let Some(focus) = focus { + let next = if writable && focus.cancel.is_focused(window) { + &focus.delete + } else { + &focus.cancel + }; + window.focus(next, cx); + } + } + _ if is_activation_key(event) && !event.is_held => { + if let Some(focus) = focus { + if focus.cancel.is_focused(window) { + resolve_confirmation(shell, &selection, false, window, cx); + } else if writable && focus.delete.is_focused(window) { + resolve_confirmation(shell, &selection, true, window, cx); + } + } + } + _ => {} + } true } +fn is_activation_key(event: &KeyDownEvent) -> bool { + matches!(event.keystroke.key.as_str(), "enter" | "space" | " ") + && !event.keystroke.modifiers.modified() +} + +#[derive(Clone)] +struct ConfirmationFocus { + cancel: FocusHandle, + delete: FocusHandle, + return_focus: Option, +} + +fn resolve_confirmation( + shell: &mut DesktopShellView, + selection: &Entity, + confirm: bool, + window: &mut Window, + cx: &mut Context, +) { + if confirm && shell.state.store.is_readonly_sqlite() { + return; + } + let return_focus = selection.update(cx, |selection, cx| { + let focus = selection.confirmation_focus.take(); + if confirm { + selection.confirm(&mut shell.state); + } else { + selection.dismiss(); + } + cx.notify(); + focus.and_then(|focus| focus.return_focus) + }); + let shell_id = cx.entity_id(); + cx.global_mut::().0.remove(&shell_id); + let target = return_focus + .filter(|_| !confirm) + .and_then(|focus| focus.upgrade()) + .unwrap_or_else(|| shell.focus_handle(cx)); + window.focus(&target, cx); + cx.notify(); +} + struct DeleteRequest { ids: Vec, empty_trash: bool, @@ -165,7 +229,7 @@ impl TrashControls { action: TrashAction, ) -> impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static { let this = self.clone(); - move |_, _, app| { + move |_, window, app| { this.shell.update(app, |shell, cx| { let Some(pane_index) = this.location.pane_index(shell) else { return; @@ -175,6 +239,15 @@ impl TrashControls { } let pending = this.selection.update(cx, |selection, cx| { action(selection, &mut shell.state, ids.clone()); + if selection.pending.is_some() && selection.confirmation_focus.is_none() { + let focus = ConfirmationFocus { + cancel: cx.focus_handle(), + delete: cx.focus_handle(), + return_focus: window.focused(cx).map(|focus| focus.downgrade()), + }; + window.focus(&focus.delete, cx); + selection.confirmation_focus = Some(focus); + } cx.notify(); selection.pending.is_some() }); @@ -187,17 +260,26 @@ impl TrashControls { shell_id, (this.location.clone(), this.selection.downgrade()), ); - } else if cx.has_global::() - && cx - .global::() - .owns(shell_id, &this.selection) - { - cx.global_mut::().0.remove(&shell_id); } cx.notify(); }); } } + + fn resolve(&self, confirm: bool) -> impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static { + let this = self.clone(); + move |_, window, app| { + this.shell.update(app, |shell, cx| { + if this.location.pane_index(shell) == Some(shell.state.split.active_pane) + && cx + .global::() + .owns(cx.entity_id(), &this.selection) + { + resolve_confirmation(shell, &this.selection, confirm, window, cx); + } + }); + } + } } impl RenderOnce for TrashView { @@ -269,12 +351,16 @@ impl RenderOnce for TrashView { } }, ))) - .child(empty.on_click(controls.action(all, |selection, _, ids| { - selection.pending = Some(DeleteRequest { - ids, - empty_trash: true, - }); - }))) + .child(confirmation_trigger( + empty, + palette, + controls.action(all, |selection, _, ids| { + selection.pending = Some(DeleteRequest { + ids, + empty_trash: true, + }); + }), + )) } else { heading.child(select_all).child(empty) }; @@ -327,10 +413,7 @@ impl RenderOnce for TrashView { ); } - let request = state - .pending - .as_ref() - .map(|request| (request.ids.len(), request.empty_trash)); + let pending = state.pending.is_some(); let scroll_key = controls.location.key("desktop.trash.scroll"); root = if has_rows { let render_controls = controls.clone(); @@ -363,22 +446,14 @@ impl RenderOnce for TrashView { .child("Trash is empty."), )) }; - if let Some((count, empty_trash)) = request + if pending && self.pane_idx == shell.state.split.active_pane && app.has_global::() && app .global::() .owns(self.shell.entity_id(), &controls.selection) { - root = root.child(confirmation( - window.viewport_size(), - &controls, - palette, - shell.state.theme, - count, - empty_trash, - writable, - )); + root = root.child(confirmation(window, app, &controls, palette)); } root.into_any_element() } @@ -495,36 +570,64 @@ fn delete_button( if !writable { return button; } - button.on_click(controls.action(ids, |selection, _, ids| { - selection.pending = Some(DeleteRequest { - ids, - empty_trash: false, - }); - })) + confirmation_trigger( + button, + palette, + controls.action(ids, |selection, _, ids| { + selection.pending = Some(DeleteRequest { + ids, + empty_trash: false, + }); + }), + ) +} + +fn confirmation_trigger( + button: ui::Stateful
, + palette: DesktopPalette, + action: impl Fn(&ui::ClickEvent, &mut Window, &mut App) + 'static, +) -> ui::Stateful
{ + let action = std::rc::Rc::new(action); + let on_click = action.clone(); + button + .tab_index(0) + .focus_visible(move |style| style.bg(palette.hover_color)) + .on_click(move |event, window, app| on_click(event, window, app)) + .on_key_down(move |event, window, app| { + if is_activation_key(event) { + window.prevent_default(); + app.stop_propagation(); + if !event.is_held { + action(&ui::ClickEvent::default(), window, app); + } + } + }) } fn confirmation( - viewport: ui::Size, + window: &mut Window, + app: &mut App, controls: &TrashControls, palette: DesktopPalette, - theme: ThemeMode, - count: usize, - empty_trash: bool, - writable: bool, ) -> AnyElement { - let cancel = |controls: &TrashControls| { - let selection = controls.selection.clone(); - let shell_id = controls.shell.entity_id(); - move |_: &ui::ClickEvent, _: &mut Window, app: &mut App| { - app.default_global::() - .0 - .remove(&shell_id); - selection.update(app, |selection, cx| { - selection.dismiss(); - cx.notify(); - }); - } + let state = controls.selection.read(app); + let (Some(request), Some(focus)) = (&state.pending, &state.confirmation_focus) else { + return div().into_any_element(); }; + let count = request.ids.len(); + let title = if request.empty_trash { + "Empty Trash?" + } else { + "Delete permanently?" + }; + let shell = controls.shell.read(app); + let writable = !shell.state.store.is_readonly_sqlite(); + let theme = shell.state.theme; + let focus = focus.clone(); + if !writable && !focus.cancel.is_focused(window) { + window.focus(&focus.cancel, app); + } + let viewport = window.viewport_size(); let confirm = button_with_fill( "desktop.trash.confirm.delete", "Delete permanently", @@ -535,40 +638,105 @@ fn confirmation( .snapshot( "desktop.trash.confirm.delete", Some("desktop.trash.confirm"), - ); + ) + .border_2() + .border_color(ui::transparent_black()); let confirm = if writable { confirm - .on_click(controls.action(Vec::new(), |selection, state, _| selection.confirm(state))) + .track_focus(&focus.delete) + .snapshot_focused(focus.delete.is_focused(window)) + .focus(move |style| style.border_color(palette.text_primary)) + .on_click(controls.resolve(true)) } else { confirm }; - let dialog = div() - .w(viewport.width).h(viewport.height).relative().flex().items_center().justify_center().p(px(16.0)) - .font_family(FONT_SANS).text_color(palette.text_primary) - .child( - div().id("desktop.trash.confirm.backdrop").absolute().inset_0().occlude() - .bg(palette.scrim).on_click(cancel(controls)), + let cancel = button("desktop.trash.confirm.cancel", "Cancel", palette, true) + .snapshot( + "desktop.trash.confirm.cancel", + Some("desktop.trash.confirm"), ) + .track_focus(&focus.cancel) + .snapshot_focused(focus.cancel.is_focused(window)) + .border_2() + .border_color(ui::transparent_black()) + .focus(move |style| style.border_color(palette.text_primary)) + .on_click(controls.resolve(false)); + let description = if count == 1 { + "This document will be permanently deleted. This action cannot be undone.".to_string() + } else { + format!( + "These {count} documents will be permanently deleted. This action cannot be undone." + ) + }; + let body = div() + .snapshot("desktop.trash.confirm.body", Some("desktop.trash.confirm")) + .min_h_0() + .flex() + .flex_col() + .child(vertical_scroll( + "desktop.trash.confirm.scroll", + div() + .snapshot( + "desktop.trash.confirm.description", + Some("desktop.trash.confirm"), + ) + .line_height(px(22.0)) + .text_size(px(14.0)) + .text_color(palette.text_secondary) + .child(description), + )); + let mut footer = div() + .flex() + .flex_wrap() + .flex_shrink(0.0) + .mt(px(40.0)) + .gap(px(20.0)) + .child(cancel) + .child(confirm); + footer.style().justify_content = Some(ui::JustifyContent::FlexEnd); + let mut card = max_width(div().id("desktop.trash.confirm").occlude(), px(440.0)) + .snapshot("desktop.trash.confirm", Some("desktop.shell.root")) + .relative() + .flex() + .flex_col() + .w_full() + .py(px(20.0)) + .px(px(24.0)) + .rounded(px(12.0)) + .bg(palette.bg_elevated) + .shadow(crate::theme_shadow(theme, "--affine-popover-shadow")) .child( - max_width(div().id("desktop.trash.confirm").occlude(), px(440.0)) - .snapshot("desktop.trash.confirm", Some("desktop.shell.root")) - .relative().flex().flex_col().gap(px(16.0)).w_full() - .p(px(24.0)).rounded(px(12.0)).bg(palette.bg_elevated) - .shadow(crate::theme_shadow(theme, "--affine-popover-shadow")) - .child(div().text_size(px(18.0)).font_weight(FontWeight::SEMIBOLD) - .child(if empty_trash { "Empty Trash?" } else { "Delete permanently?" })) - .child(div().text_size(px(14.0)).text_color(palette.text_secondary) - .child(if count == 1 { - "This document will be permanently deleted. This action cannot be undone.".to_string() - } else { - format!("These {count} documents will be permanently deleted. This action cannot be undone.") - })) - .child(div().flex().flex_wrap().gap(px(8.0)).child(div().flex_1()) - .child(button("desktop.trash.confirm.cancel", "Cancel", palette, true) - .snapshot("desktop.trash.confirm.cancel", Some("desktop.trash.confirm")) - .on_click(cancel(controls))) - .child(confirm)), - ); + div() + .flex_shrink(0.0) + .text_size(px(18.0)) + .line_height(px(26.0)) + .mb(px(12.0)) + .font_weight(FontWeight::SEMIBOLD) + .child(title), + ) + .child(body) + .child(footer); + card.style().max_size.height = Some((viewport.height - px(32.0)).max(px(0.0)).into()); + let dialog = div() + .w(viewport.width) + .h(viewport.height) + .relative() + .flex() + .items_center() + .justify_center() + .p(px(16.0)) + .font_family(FONT_SANS) + .text_color(palette.text_primary) + .child( + div() + .id("desktop.trash.confirm.backdrop") + .absolute() + .inset_0() + .occlude() + .bg(palette.scrim) + .on_click(controls.resolve(false)), + ) + .child(card); ui::deferred( ui::anchored() .position(ui::point(px(0.0), px(0.0))) diff --git a/packages/frontend/desktop/tests/trash_confirm_and_tooltip_parity.rs b/packages/frontend/desktop/tests/trash_confirm_and_tooltip_parity.rs new file mode 100644 index 0000000000..7fbd872890 --- /dev/null +++ b/packages/frontend/desktop/tests/trash_confirm_and_tooltip_parity.rs @@ -0,0 +1,381 @@ +//! Keyboard, layout and pixel checks for Trash confirmation and desktop tooltips. + +use std::time::Duration; + +use affine_desktop::{ + DesktopAppState, DesktopRoute, DesktopShellView, register_desktop_fonts, + sqlite_loader::SqliteLazyBacking, +}; +use anyhow::{Context as _, Result}; +use ui::{ + AppContext, Application, ApplicationHandle, Bounds, DebugElementSnapshot, HeadlessPlatform, + HeadlessWindow, KeyDownEvent, Keystroke, Modifiers, MouseButton, MouseDownEvent, + MouseMoveEvent, MouseUpEvent, PlatformInput, ScrollDelta, ScrollEvent, SnapshotRect, + TouchPhase, WindowBounds, WindowHandle, WindowOptions, point, px, size, +}; +use ui_tokens::ThemeMode; + +const DOC: &str = "doc-legacy-draft"; +const OPEN: &str = "desktop.trash.open.doc-legacy-draft"; +const ROW_DELETE: &str = "desktop.trash.delete.doc-legacy-draft"; +const RESTORE: &str = "desktop.trash.footer.restore"; +const DELETE: &str = "desktop.trash.footer.delete"; +const CONFIRM: &str = "desktop.trash.confirm"; +const CANCEL: &str = "desktop.trash.confirm.cancel"; +const CONFIRM_DELETE: &str = "desktop.trash.confirm.delete"; +const BODY: &str = "desktop.trash.confirm.body"; +const DESCRIPTION: &str = "desktop.trash.confirm.description"; +const THEMES: [(ThemeMode, &str, u8); 2] = [ + (ThemeMode::Light, "light", 0), + (ThemeMode::Dark, "dark", 65), +]; + +#[test] +fn trash_confirmation_traps_focus_and_dispatches_each_key_once() -> Result<()> { + for (key, cancel_key) in [("enter", "space"), ("space", "enter")] { + let desktop = Desktop::trash(ThemeMode::Light, 700, 400)?; + desktop.open_preview(false)?; + desktop.key("shift-tab", false)?; + assert!(desktop.element(DELETE)?.focused); + desktop.key(key, true)?; + assert!(desktop.find(CONFIRM)?.is_none()); + + desktop.key(key, false)?; + assert!(desktop.element(CONFIRM_DELETE)?.focused); + assert!(desktop.has_doc()?); + for ignored in [key, "ctrl-a", "ctrl-enter", "shift-space"] { + desktop.key(ignored, ignored == key)?; + assert!(desktop.element(CONFIRM_DELETE)?.focused); + assert!(desktop.has_doc()?); + } + for tab in ["tab", "shift-tab", "shift-tab", "tab"] { + let cancel = desktop.element(CANCEL)?.focused; + desktop.key(tab, false)?; + assert_eq!(desktop.element(CANCEL)?.focused, !cancel); + assert_eq!(desktop.element(CONFIRM_DELETE)?.focused, cancel); + } + + desktop.key("tab", false)?; + desktop.key(cancel_key, false)?; + assert!(desktop.find(CONFIRM)?.is_none()); + assert!(desktop.element(DELETE)?.focused); + assert!(desktop.has_doc()?); + desktop.key(key, false)?; + desktop.key("escape", false)?; + assert!(desktop.element(DELETE)?.focused); + assert!(desktop.has_doc()?); + + desktop.key(key, false)?; + desktop.key(cancel_key, false)?; + assert!(desktop.find(CONFIRM)?.is_none()); + assert!(!desktop.has_doc()?); + } + Ok(()) +} + +#[test] +fn trash_confirmation_restores_row_focus_and_blocks_delete_in_readonly_workspace() -> Result<()> { + let desktop = Desktop::trash(ThemeMode::Dark, 700, 400)?; + desktop.click(ROW_DELETE)?; + assert!(desktop.element(CONFIRM_DELETE)?.focused); + desktop.key("escape", false)?; + assert!(desktop.has_doc()?); + desktop.key("enter", false)?; + assert!(desktop.element(CONFIRM_DELETE)?.focused); + + desktop.app.update(|cx| { + desktop.handle.update(cx, |shell, _, cx| { + shell.state.store.sqlite_backing = Some(SqliteLazyBacking::new( + "readonly-preview.affine", + "preview", + 0, + )); + cx.notify(); + }) + })?; + desktop.frame(); + assert!(desktop.element(CANCEL)?.focused); + for key in ["tab", "shift-tab"] { + desktop.key(key, false)?; + assert!(desktop.element(CANCEL)?.focused); + assert!(!desktop.element(CONFIRM_DELETE)?.focused); + } + desktop.click(CONFIRM_DELETE)?; + assert!(desktop.has_doc()?); + desktop.key("enter", false)?; + assert!(desktop.find(CONFIRM)?.is_none()); + assert!(desktop.has_doc()?); + Ok(()) +} + +#[test] +fn trash_confirmation_keeps_actions_visible_and_scrolls_only_the_body() -> Result<()> { + for (theme, _, _) in THEMES { + for (width, height) in [(640, 320), (700, 400), (640, 204)] { + let desktop = Desktop::trash(theme, width, height)?; + desktop.click(ROW_DELETE)?; + let card = desktop.element(CONFIRM)?.bounds; + let cancel = desktop.element(CANCEL)?.bounds; + let delete = desktop.element(CONFIRM_DELETE)?.bounds; + assert!(card.y >= 16.0 && card.bottom() <= height as f32 - 16.0); + assert_eq!(delete.x - cancel.x - cancel.width, 20.0); + assert_eq!(card.x + card.width - delete.x - delete.width, 24.0); + assert_eq!(card.bottom() - delete.bottom(), 20.0); + let body = desktop.element(BODY)?.bounds; + assert_eq!(body.x - card.x, 24.0); + assert_eq!(card.width - body.width, 48.0); + if height == 204 { + let description = desktop.element(DESCRIPTION)?.bounds; + assert!(body.height < description.height); + desktop + .window + .dispatch_input(PlatformInput::Scroll(ScrollEvent { + position: center(body), + delta: ScrollDelta::Pixels(point(px(0.0), px(-64.0))), + modifiers: Modifiers::default(), + touch_phase: TouchPhase::Moved, + source: Default::default(), + })); + desktop.frame(); + assert!(desktop.element(DESCRIPTION)?.bounds.y < description.y); + assert_eq!(desktop.element(CONFIRM_DELETE)?.bounds, delete); + } + desktop.click(CONFIRM_DELETE)?; + assert!(!desktop.has_doc()?); + } + } + Ok(()) +} + +#[test] +fn trash_and_center_peek_tooltips_match_web_geometry_and_pixels() -> Result<()> { + for (theme, _, fill) in THEMES { + for (width, split) in [(1280, false), (700, true)] { + let desktop = Desktop::trash(theme, width, 800)?; + desktop.open_preview(split)?; + for (button, tip, label) in [ + ( + RESTORE, + "desktop.trash.footer.restore.tooltip", + "Restore it", + ), + ( + DELETE, + "desktop.trash.footer.delete.tooltip", + "Delete permanently", + ), + ] { + desktop.key("tab", false)?; + let tip = desktop.element(tip)?; + assert_eq!(tip.text.as_deref(), Some(label)); + assert_eq!(tip.corner_radius, 4.0); + desktop.check_tooltip(desktop.element(button)?.bounds, tip.bounds, width, fill)?; + } + } + + let shell = Desktop::open(1280, 800, { + let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02"); + state.open_peek_view("doc-arch"); + state + })?; + let control = shell.element("desktop.peek.open_split")?.bounds; + shell.hover(control); + shell.platform.advance_clock(Duration::from_millis(500)); + shell.frame(); + let tip = shell.element("desktop.peek.control.tooltip")?; + assert_eq!(tip.text.as_deref(), Some("Open in split view")); + assert_eq!(tip.corner_radius, 4.0); + shell.check_tooltip(control, tip.bounds, 1280, fill)?; + } + Ok(()) +} + +#[test] +#[ignore = "writes offscreen evidence to TRASH_EVIDENCE_DIR"] +fn capture_trash_tooltip_and_confirmation() -> Result<()> { + let dir = std::path::PathBuf::from( + std::env::var_os("TRASH_EVIDENCE_DIR").context("set TRASH_EVIDENCE_DIR")?, + ); + std::fs::create_dir_all(&dir)?; + for (theme, name, _) in THEMES { + let desktop = Desktop::trash(theme, 1280, 800)?; + desktop.open_preview(false)?; + desktop.key("tab", false)?; + desktop.element("desktop.trash.footer.restore.tooltip")?; + desktop + .image()? + .save(dir.join(format!("trash-tooltip-{name}.png")))?; + + let desktop = Desktop::trash(theme, 700, 400)?; + desktop.open_preview(false)?; + desktop.key("shift-tab", false)?; + desktop.key("enter", false)?; + desktop.element(CONFIRM)?; + desktop + .image()? + .save(dir.join(format!("trash-confirm-{name}.png")))?; + } + Ok(()) +} + +fn center(rect: SnapshotRect) -> ui::Point { + point( + px(rect.x + rect.width / 2.0), + px(rect.y + rect.height / 2.0), + ) +} + +struct Desktop { + platform: std::rc::Rc, + window: HeadlessWindow, + app: ApplicationHandle, + handle: WindowHandle, +} + +impl Desktop { + fn trash(theme: ThemeMode, width: u32, height: u32) -> Result { + let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02"); + state.navigate_active_pane(DesktopRoute::Trash); + Self::open(width, height, state) + } + + fn open(width: u32, height: u32, state: DesktopAppState) -> Result { + 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)?; + cx.open_window( + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::new( + point(px(0.0), px(0.0)), + size(px(width as f32), px(height as f32)), + ))), + ..WindowOptions::default() + }, + |_, cx| cx.new(|cx| DesktopShellView::new(state, cx)), + ) + })?; + let window = platform + .windows() + .into_iter() + .next() + .context("desktop window")?; + let desktop = Self { + platform, + window, + app, + handle, + }; + desktop.frame(); + Ok(desktop) + } + + fn frame(&self) { + self.window.request_frame(); + self.platform.run_until_parked(); + } + + fn find(&self, id: &str) -> Result> { + self.app.update(|cx| { + self.handle.update(cx, |_, window, _| { + window.frame_snapshot().elements.get(id).cloned() + }) + }) + } + + fn element(&self, id: &str) -> Result { + self.find(id)?.with_context(|| format!("find {id}")) + } + + fn has_doc(&self) -> Result { + self.app.update(|cx| { + self.handle + .update(cx, |shell, _, _| shell.state.store.get_doc(DOC).is_some()) + }) + } + + fn click(&self, id: &str) -> Result<()> { + self.window.simulate_click(center(self.element(id)?.bounds)); + self.frame(); + Ok(()) + } + + fn hover(&self, bounds: SnapshotRect) { + self.window + .dispatch_input(PlatformInput::MouseMove(MouseMoveEvent { + position: center(bounds), + ..Default::default() + })); + self.frame(); + } + + fn key(&self, key: &'static str, is_held: bool) -> Result<()> { + self.window + .dispatch_input(PlatformInput::KeyDown(KeyDownEvent { + keystroke: Keystroke::parse(key)?, + is_held, + prefer_character_input: false, + })); + self.frame(); + Ok(()) + } + + fn open_preview(&self, split: bool) -> Result<()> { + let position = center(self.element(OPEN)?.bounds); + let modifiers = Modifiers { + shift: split, + ..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.frame(); + self.element(RESTORE)?; + Ok(()) + } + + fn image(&self) -> Result { + self.app.update(|cx| { + self.handle + .update(cx, |_, window, _| window.render_to_image()) + })? + } + + fn check_tooltip( + &self, + button: SnapshotRect, + tip: SnapshotRect, + width: u32, + fill: u8, + ) -> Result<()> { + assert!(tip.x >= 0.0 && tip.x + tip.width <= width as f32, "{tip:?}"); + assert!(tip.y >= 0.0, "{tip:?}"); + assert_eq!(button.y - tip.bottom(), 5.0, "{button:?} {tip:?}"); + assert_eq!(tip.height, 32.0); + let expected_x = + (button.x + (button.width - tip.width) / 2.0).clamp(0.0, width as f32 - tip.width); + assert!((tip.x - expected_x).abs() <= 1.0, "{button:?} {tip:?}"); + + let image = self.image()?; + let x = tip.x as u32; + let y = tip.y as u32; + assert_eq!(image.get_pixel(x + 6, y + 16).0, [fill, fill, fill, 255]); + assert!( + (x + 12..x + tip.width as u32 - 12) + .any(|x| { (y + 5..y + 27).any(|y| image.get_pixel(x, y).0 == [255; 4]) }) + ); + Ok(()) + } +}