From 0fd8ea12fb4c4f683a0dc9d2ee247fca23fb5d58 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Tue, 24 Nov 2026 19:41:45 +0700 Subject: [PATCH] chore: stabilize element ids and overlay focus tracking --- crates/signed_app/src/app/mod.rs | 21 +- crates/signed_app/src/explore/helpers.rs | 4 +- crates/signed_app/src/explore/mod.rs | 1 - crates/signed_app/src/issues/helpers.rs | 10 +- crates/signed_app/src/issues/mod.rs | 5 +- crates/signed_app/src/pull_requests/mod.rs | 5 +- crates/signed_app/src/repo/commit_diff.rs | 12 +- crates/signed_app/src/repo/files.rs | 1 + crates/signed_app/src/repo/helpers.rs | 8 +- crates/signed_app/src/repo/mod.rs | 30 +- crates/signed_app/src/shared/event_list.rs | 4 +- .../src/titlebar/repository_switcher.rs | 2 +- crates/ui/src/components/button.rs | 11 +- crates/ui/src/components/clipboard.rs | 19 +- crates/ui/src/components/common.rs | 77 +++-- crates/ui/src/components/dialog.rs | 292 +++++++++--------- crates/ui/src/components/menu.rs | 5 +- crates/ui/src/components/popover.rs | 9 +- crates/ui/src/components/scrollbar.rs | 193 ++++++++---- crates/ui/src/components/tooltip.rs | 110 +------ crates/ui/src/layout/root.rs | 13 +- crates/ui/src/theme/mod.rs | 4 - crates/ui/tests/popover.rs | 112 +++++++ crates/ui/tests/scroll_area.rs | 94 ++++++ 24 files changed, 638 insertions(+), 404 deletions(-) create mode 100644 crates/ui/tests/popover.rs create mode 100644 crates/ui/tests/scroll_area.rs diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index 599cc7a..e5b387e 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -7,7 +7,7 @@ use gpui::{ ParentElement as _, Render, Styled as _, Subscription, WeakEntity, Window, div, }; use helpers::apply_appearance_mode; -use settings::SettingsStore; +use settings::{AppearanceMode, SettingsStore}; use signed_state::{Backend, BackendEvent}; use ui::common::{h_flex, v_flex}; use ui::icons::IconRole; @@ -28,7 +28,7 @@ use crate::titlebar::{ pub struct AppRoot { panels: Entity, titlebar: Entity, - passphrase: Option>, + appearance: AppearanceMode, _subscriptions: Vec, } @@ -66,9 +66,12 @@ impl AppRoot { }, )); - subscriptions.push(cx.observe(&settings, |_this, store, cx| { - let settings = store.read(cx).settings().clone(); - apply_appearance_mode(settings.appearance, cx); + subscriptions.push(cx.observe(&settings, |this, store, cx| { + let appearance = store.read(cx).settings().appearance; + if appearance != this.appearance { + this.appearance = appearance; + apply_appearance_mode(appearance, cx); + } })); window.defer(cx, move |window, cx| { @@ -78,20 +81,18 @@ impl AppRoot { Self::reset_to_explore(&app, window, cx); }); + let appearance = settings.read(cx).settings().appearance; + Self { panels, titlebar, - passphrase: None, + appearance, _subscriptions: subscriptions, } } fn open_passphrase(&mut self, cx: &mut Context) { - if self.passphrase.is_some() { - return; - } let dialog = PassphraseDialog::new(cx); - self.passphrase = Some(dialog.clone()); cx.open_dialog(dialog); } diff --git a/crates/signed_app/src/explore/helpers.rs b/crates/signed_app/src/explore/helpers.rs index e381ff6..0c1475b 100644 --- a/crates/signed_app/src/explore/helpers.rs +++ b/crates/signed_app/src/explore/helpers.rs @@ -65,7 +65,6 @@ impl RepoFilter { } pub(super) fn render_card( - ix: usize, announcement: &Announcement, last_activity: Option, announcements: &[Announcement], @@ -98,7 +97,7 @@ pub(super) fn render_card( }); v_flex() - .id(ix) + .id(SharedString::from(format!("repo-card:{}", announcement.id))) .flex_1() .h_full() .min_w_0() @@ -113,6 +112,7 @@ pub(super) fn render_card( .gap_2() .child( div() + .flex_1() .min_w_0() .text_sm() .font_semibold() diff --git a/crates/signed_app/src/explore/mod.rs b/crates/signed_app/src/explore/mod.rs index e7aaaef..92f829b 100644 --- a/crates/signed_app/src/explore/mod.rs +++ b/crates/signed_app/src/explore/mod.rs @@ -294,7 +294,6 @@ impl Render for ExploreView { }; let activity = last_activity.get(&announcement.addr()).copied(); cards.push(render_card( - ix, announcement, activity, &announcements, diff --git a/crates/signed_app/src/issues/helpers.rs b/crates/signed_app/src/issues/helpers.rs index 31258ad..ec573f0 100644 --- a/crates/signed_app/src/issues/helpers.rs +++ b/crates/signed_app/src/issues/helpers.rs @@ -127,7 +127,15 @@ pub(crate) fn sidebar_section( .picture(profile.picture()) .small(), ) - .child(div().text_base().text_ellipsis().child(name)) + .child( + div() + .flex_1() + .min_w_0() + .whitespace_nowrap() + .text_base() + .text_ellipsis() + .child(name), + ) .into_any_element() })), ) diff --git a/crates/signed_app/src/issues/mod.rs b/crates/signed_app/src/issues/mod.rs index fbc1922..b60e0b8 100644 --- a/crates/signed_app/src/issues/mod.rs +++ b/crates/signed_app/src/issues/mod.rs @@ -182,8 +182,7 @@ impl Render for IssuesView { let rows = visible_issues .iter() - .enumerate() - .filter_map(|(ix, &issue_ix)| { + .filter_map(|&issue_ix| { // The store re-read per frame can shrink below a captured index. let issue = store.read(cx).issues.get(issue_ix)?; let profile = directory.read(cx).profile(&issue.pubkey, cx); @@ -210,7 +209,7 @@ impl Render for IssuesView { }; Some(EventRow { - id: ix.into(), + id: SharedString::from(format!("issue:{id_hex}")).into(), status, title: issue.activity_subject().into(), author: profile.name(), diff --git a/crates/signed_app/src/pull_requests/mod.rs b/crates/signed_app/src/pull_requests/mod.rs index 3ad6cff..b7ebe00 100644 --- a/crates/signed_app/src/pull_requests/mod.rs +++ b/crates/signed_app/src/pull_requests/mod.rs @@ -295,8 +295,7 @@ impl Render for PullRequestsView { let rows = visible .iter() - .enumerate() - .filter_map(|(ix, &pr_ix)| { + .filter_map(|&pr_ix| { // The store re-read per frame can shrink below a captured index. let pr = store.read(cx).pull_requests.get(pr_ix)?; let profile = directory.read(cx).profile(&pr.pubkey, cx); @@ -332,7 +331,7 @@ impl Render for PullRequestsView { }; Some(EventRow { - id: ix.into(), + id: SharedString::from(format!("pr:{id_hex}")).into(), status, title: pr.activity_subject().into(), author: profile.name(), diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index 02e1bcf..1fca3dd 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -559,11 +559,9 @@ fn render_pane_row( impl Render for DiffPane { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - if self.diff.is_none() { + let Some(diff) = self.diff.as_ref() else { return EmptyState::centered("No changes"); - } - - let diff = self.diff.as_ref().expect("diff checked above"); + }; if diff.files.is_empty() { return EmptyState::centered("No files changed"); @@ -822,7 +820,9 @@ impl CommitDiffView { h_flex() .gap_2() .child(Avatar::new(name.clone()).name(name.clone()).small()) - .child(div().truncate().text_ellipsis().child(name)) + .child( + div().min_w_0().truncate().text_ellipsis().child(name), + ) .into_any_element(), ) }) @@ -849,6 +849,7 @@ impl CommitDiffView { .gap_2() .child( div() + .min_w_0() .text_ellipsis() .truncate() .child(SharedString::from(commit.id.clone())), @@ -863,6 +864,7 @@ impl CommitDiffView { .gap_2() .child( div() + .min_w_0() .text_ellipsis() .truncate() .child(SharedString::from(parent.clone())), diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index d26ab5a..4311ead 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -340,6 +340,7 @@ impl RepoFilesView { .text_color(cx.theme().colors.muted_foreground) .child( div() + .min_w_0() .text_xs() .font_medium() .text_ellipsis() diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index 18a1157..1fd53bd 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -211,7 +211,13 @@ pub(super) fn fork_row( .text_base() .text_color(cx.theme().colors.muted_foreground) .child(Icon::named(IconRole::GitBranch).small()) - .child(div().whitespace_nowrap().text_ellipsis().child(label)); + .child( + div() + .min_w_0() + .whitespace_nowrap() + .text_ellipsis() + .child(label), + ); Some(if clickable { row.id("fork-upstream") diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index beb6deb..c5957c4 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -390,7 +390,7 @@ impl RepoDetailView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); return; } @@ -509,7 +509,7 @@ impl RepoDetailView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn apply_repo_data(&mut self, data: RepoData, window: &mut Window, cx: &mut Context) { @@ -609,7 +609,7 @@ impl RepoDetailView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn switch_ref(&mut self, kind: RefKind, name: T, window: &mut Window, cx: &mut Context) @@ -684,7 +684,7 @@ impl RepoDetailView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn reload_worktree(&mut self, cx: &mut Context) { @@ -727,7 +727,7 @@ impl RepoDetailView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } /// Refresh the file explorer and previews after the mirror caught up with the remote. @@ -758,6 +758,12 @@ impl RepoDetailView { Ok(()) }); + self.push_task(task); + } + + /// Reaps finished tasks, then queues another. + fn push_task(&mut self, task: Task>) { + self.tasks.retain(|task| !task.is_ready()); self.tasks.push(task); } @@ -766,7 +772,7 @@ impl RepoDetailView { cx.notify(); let task = self.store.update(cx, |store, cx| store.push_repository(cx)); - self.tasks.push(task); + self.push_task(task); } fn sync_notification_tag(addr: &RepoAddr) -> SharedString { @@ -866,7 +872,7 @@ impl RepoDetailView { Ok(()) }); - self.tasks.push(task); + self.push_task(task); } fn reset_remote(&mut self, window: &mut Window, cx: &mut Context) { @@ -932,7 +938,7 @@ impl RepoDetailView { let task = self .store .update(cx, |store, cx| store.delete_repository(cx)); - self.tasks.push(task); + self.push_task(task); } fn render_files_tab(&self, cx: &App) -> AnyElement { @@ -1122,7 +1128,13 @@ impl RepoDetailView { .text_sm() .font_semibold() .child(avatar) - .child(name), + .child( + div() + .min_w_0() + .whitespace_nowrap() + .text_ellipsis() + .child(name), + ), ) .child( div() diff --git a/crates/signed_app/src/shared/event_list.rs b/crates/signed_app/src/shared/event_list.rs index 8d63d90..b306c3b 100644 --- a/crates/signed_app/src/shared/event_list.rs +++ b/crates/signed_app/src/shared/event_list.rs @@ -226,7 +226,6 @@ pub fn commit_list( let on_click = on_click.clone(); let row_commit = commit.clone(); commit_row( - ix, &commit, action, move |window, cx| on_click(&row_commit, window, cx), @@ -244,14 +243,13 @@ pub fn commit_list( /// One copyable commit summary row: id, subject, author, and age. pub(crate) fn commit_row( - ix: usize, commit: &FileCommit, action: Option, on_click: impl Fn(&mut Window, &mut gpui::App) + 'static, cx: &gpui::App, ) -> gpui::AnyElement { h_flex() - .id(ix) + .id(commit.id.clone()) .px_4() .h(px(COMMIT_ROW_HEIGHT)) .w_full() diff --git a/crates/signed_app/src/titlebar/repository_switcher.rs b/crates/signed_app/src/titlebar/repository_switcher.rs index 99a1721..f4e1dc2 100644 --- a/crates/signed_app/src/titlebar/repository_switcher.rs +++ b/crates/signed_app/src/titlebar/repository_switcher.rs @@ -211,7 +211,7 @@ impl Render for RepositorySwitcher { Some( h_flex() - .id(("repo-switcher-entry", index)) + .id(entry.key.clone()) .role(Role::MenuItem) .w_full() .h(row_height) diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs index b4515cc..bf3ce6a 100644 --- a/crates/ui/src/components/button.rs +++ b/crates/ui/src/components/button.rs @@ -17,12 +17,10 @@ use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, AnyView, App, ClickEvent, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, - StyleRefinement, Styled as _, Window, canvas, relative, transparent_black, + StyleRefinement, Styled as _, Window, relative, transparent_black, }; -use crate::components::common::{ - ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex, record_anchor_bounds, -}; +use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex}; use crate::components::spinner::Spinner; use crate::icons::Icon; use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; @@ -386,11 +384,6 @@ impl RenderOnce for Button { ), ) }) - .child( - canvas(record_anchor_bounds(self.id.clone()), |_, _, _, _| {}) - .absolute() - .inset_0(), - ) .when(self.disabled, |button| button.opacity(DISABLED_OPACITY)) .when_some(self.tooltip, |button, tooltip| { button.tooltip(move |window, cx| tooltip(window, cx)) diff --git a/crates/ui/src/components/clipboard.rs b/crates/ui/src/components/clipboard.rs index a7966ff..bb0c6f4 100644 --- a/crates/ui/src/components/clipboard.rs +++ b/crates/ui/src/components/clipboard.rs @@ -15,7 +15,7 @@ use std::time::Duration; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce, + AnyView, App, ClipboardItem, ElementId, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, Task, Window, div, }; @@ -108,18 +108,17 @@ impl Sizable for ClipboardButton { /// The transient copied marker keyed per button. struct CopiedState { generation: u64, - tasks: Vec>, + task: Option>, } impl RenderOnce for ClipboardButton { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let copied: Entity = - window.use_keyed_state((self.id.clone(), "clipboard-copied"), cx, |_, _| { - CopiedState { - generation: 0, - tasks: Vec::new(), - } - }); + let copied = window.use_keyed_state((self.id.clone(), "clipboard-copied"), cx, |_, _| { + CopiedState { + generation: 0, + task: None, + } + }); let is_copied = copied.read(cx).generation != 0; let selector = if is_copied { @@ -172,7 +171,7 @@ impl RenderOnce for ClipboardButton { }); copied.update(cx, |state, _| { - state.tasks.push(task); + state.task = Some(task); }); // Invoke the callback after copying diff --git a/crates/ui/src/components/common.rs b/crates/ui/src/components/common.rs index 006c3a7..bcfc992 100644 --- a/crates/ui/src/components/common.rs +++ b/crates/ui/src/components/common.rs @@ -10,13 +10,11 @@ //! let column = v_flex().gap_2().child(row); //! ``` -use std::collections::HashMap; - use gpui::prelude::FluentBuilder as _; use gpui::{ - App, Bounds, BoxShadow, Div, ElementId, FocusHandle, FontWeight, Global, Hsla, IntoElement, - Pixels, Refineable as _, Rems, StatefulInteractiveElement, StyleRefinement, Styled, Window, - WindowId, div, px, rems, + App, BoxShadow, Div, ElementId, FocusHandle, FontWeight, Hsla, IntoElement, Pixels, + Refineable as _, Rems, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, + Window, div, px, rems, }; use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD, Size}; @@ -31,22 +29,6 @@ pub const TOAST_LAYER: usize = 3; /// A handler told to clean up after a dismissed surface. pub type DismissHandler = std::rc::Rc; -/// The painted bounds of elements that tooltips anchor to, per window and element id. -#[derive(Default)] -struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); - -impl Global for AnchorBoundsRegistry {} - -impl AnchorBoundsRegistry { - fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { - self.0.insert((window, id), bounds); - } - - fn get(&self, window: WindowId, id: &ElementId) -> Option> { - self.0.get(&(window, id.clone())).copied() - } -} - /// A row whose children center on the cross axis. #[must_use] pub fn h_flex() -> Div { @@ -112,20 +94,47 @@ pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusH .clone() } -/// The last bounds an element painted at, in the given window. -pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option> { - cx.try_global::() - .and_then(|registry| registry.get(window, id)) -} +/// Saves the focused handle while an overlay is open and restores it when the +/// overlay closes, unless another surface already took focus. +pub(crate) fn track_overlay_focus( + id: &ElementId, + overlay_focus: &FocusHandle, + open: bool, + window: &mut Window, + cx: &mut App, +) { + let was_open = window.use_keyed_state( + SharedString::from(format!("overlay-was-open:{id}")), + cx, + |_, _| false, + ); + let previous = window.use_keyed_state( + SharedString::from(format!("overlay-previous-focus:{id}")), + cx, + |_, _| None::, + ); -/// A canvas prepaint closure recording the element's painted bounds. -pub fn record_anchor_bounds( - id: ElementId, -) -> impl Fn(Bounds, &mut Window, &mut App) + 'static { - move |bounds, window, cx| { - let window_id = window.window_handle().window_id(); - cx.default_global::() - .record(window_id, id.clone(), bounds); + let was_open_now = *was_open.read(cx); + if open && !was_open_now { + let focused = window.focused(cx); + previous.update(cx, |previous, _| *previous = focused); + was_open.update(cx, |was_open, _| *was_open = true); + } else if !open && was_open_now { + was_open.update(cx, |was_open, _| *was_open = false); + let Some(restore) = previous.update(cx, |previous, _| previous.take()) else { + return; + }; + // Only take focus back from the closing overlay itself; a surface that + // replaced it owns focus now. + let overlay_focus = overlay_focus.clone(); + window.defer(cx, move |window, cx| { + let holds_focus = window + .focused(cx) + .is_none_or(|current| current == overlay_focus); + if holds_focus && restore.is_rendered(window) { + window.focus(&restore, cx); + } + }); } } diff --git a/crates/ui/src/components/dialog.rs b/crates/ui/src/components/dialog.rs index 090dff5..05e807b 100644 --- a/crates/ui/src/components/dialog.rs +++ b/crates/ui/src/components/dialog.rs @@ -34,7 +34,8 @@ use gpui::{ use crate::components::button::{Button, ButtonVariant}; use crate::components::common::{ - DIALOG_LAYER, Sizable, StyledExt as _, floating_panel, h_flex, v_flex, + DIALOG_LAYER, Sizable, StyledExt as _, floating_panel, focus_handle, h_flex, + track_overlay_focus, v_flex, }; use crate::components::grain::grain; use crate::components::scroll_area::ScrollArea; @@ -254,6 +255,10 @@ impl RenderOnce for Dialog { .as_ref() .map_or(self.open, DialogHandle::is_open); + // Keyboard focus rides the panel across frames. + let focus = focus_handle(&self.id, window, cx); + track_overlay_focus(&self.id, &focus, open, window, cx); + if !open { return root.into_any_element(); } @@ -296,163 +301,162 @@ impl RenderOnce for Dialog { let close_on_backdrop = self.close_on_backdrop; let show_close = !alert && on_change.is_some() && (close_on_escape || close_on_backdrop); - // Keyboard focus rides the panel across frames. - let focus = crate::components::common::focus_handle(&self.id, window, cx); - let content = self.content.map(|build| build(window, cx)); let actions = self.actions.map(|build| build(window, cx)); let height = self.height; let scroll = window - .use_keyed_state("dialog-content-scroll", cx, |_, _| ScrollHandle::new()) + .use_keyed_state((self.id.clone(), "dialog-content-scroll"), cx, |_, _| { + ScrollHandle::new() + }) .read(cx) .clone(); - let panel = floating_panel( - cx, - radius, - v_flex() - .id("dialog-panel") - .track_focus(&focus) - .role(role) - .aria_label(label) - .when_some(self.width, |panel, width| panel.w(width)) - .when(self.width.is_none() && self.min_width.is_none(), |panel| { - panel.min_w(DIALOG_MIN_WIDTH) - }) - .when_some(self.min_width, |panel, width| panel.min_w(width)) - .max_w(relative(0.9)) - .when_some(height, |panel, height| panel.h(height)) - .text_color(foreground), - shadows, - ) - // The panel behind the dialog is `background` (pure white/black), so - // the dialog matches it instead of the muted `surface` tint. - .bg(background) - .overflow_hidden() - .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) - .on_key_down({ - let on_change = on_change.clone(); - move |event: &KeyDownEvent, window, cx| { - if event.keystroke.key == "escape" - && !alert - && close_on_escape - && let Some(on_change) = &on_change - { - on_change(false, window, cx); - } - cx.stop_propagation(); - } - }) - .when(self.title.is_some() || show_close, |panel| { - panel.child( - h_flex() - .h_12() - .px_2() - .gap_2() - .justify_between() - .when(show_close, |row| row.child(div().w_7())) - .when_some(self.title.clone(), |row, title| { - row.child( - div() - .flex_1() - .text_center() - .text_sm() - .font_semibold() - .child(title), - ) - }) - .when(show_close, |row| { - row.child( - Button::new("dialog-close") - .icon(IconRole::Close) - .variant(ButtonVariant::Ghost) - .small() - .debug_selector(|| "dialog-close".to_string()) - .accessibility_label("Close") - .on_click({ - let on_change = on_change.clone(); - move |_, window, cx| { - if let Some(on_change) = &on_change { - on_change(false, window, cx); - } - } - }), - ) - }), - ) - }) - .when_some(content, |panel, content| { - panel.map(|this| { - if height.is_some() { - this.child( - ScrollArea::new("dialog-content") - .handle(scroll) - .flex_1() - .min_h_0() - .child(div().p_2().child(content)), - ) - } else { - this.child(div().p_2().child(content)) - } - }) - }) - .when_some(actions, |panel, actions| { - panel.child( - h_flex() - .px_2() - .h_12() - .justify_end() - .gap_2() - .children(actions), - ) - }) - .child( - canvas(|_, _, _| {}, { - move |_, _, window, cx| { - if !focus.contains_focused(window, cx) { - window.focus(&focus, cx); - } - } - }) - .absolute() - .inset_0(), - ); - - let scrim = div() - .absolute() - .inset_0() - .bg(scrim_color) - .occlude() - .when(self.grain, |scrim| scrim.child(grain())) - .when(!alert && close_on_backdrop, |scrim| { - scrim.on_mouse_down(MouseButton::Left, { - let on_change = on_change.clone(); - move |_, _window, cx| { - if let Some(on_change) = &on_change { - on_change(false, _window, cx); - } - cx.stop_propagation(); - } - }) - }); - deferred( root.flex() .items_center() .justify_center() .p_4() .refine_style(&self.style) - .child(scrim.with_animation( - "dialog-scrim-enter", - Animation::new(enter_duration).with_easing(ease_out_quint()), - |scrim, delta| scrim.opacity(delta), - )) - .child(panel.with_animation( - "dialog-enter", - Animation::new(enter_duration).with_easing(ease_out_quint()), - |panel, delta| panel.opacity(delta), - )), + .child( + div() + .absolute() + .inset_0() + .bg(scrim_color) + .occlude() + .when(self.grain, |scrim| scrim.child(grain())) + .when(!alert && close_on_backdrop, |scrim| { + scrim.on_mouse_down(MouseButton::Left, { + let on_change = on_change.clone(); + move |_, _window, cx| { + if let Some(on_change) = &on_change { + on_change(false, _window, cx); + } + cx.stop_propagation(); + } + }) + }) + .with_animation( + "dialog-scrim-enter", + Animation::new(enter_duration).with_easing(ease_out_quint()), + |scrim, delta| scrim.opacity(delta), + ), + ) + .child( + floating_panel( + cx, + radius, + v_flex() + .id((self.id.clone(), "dialog-panel")) + .track_focus(&focus) + .role(role) + .aria_label(label) + .when_some(self.width, |panel, width| panel.w(width)) + .when(self.width.is_none() && self.min_width.is_none(), |panel| { + panel.min_w(DIALOG_MIN_WIDTH) + }) + .when_some(self.min_width, |panel, width| panel.min_w(width)) + .max_w(relative(0.9)) + .when_some(height, |panel, height| panel.h(height)) + .text_color(foreground), + shadows, + ) + .bg(background) + .overflow_hidden() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_key_down({ + let on_change = on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "escape" + && !alert + && close_on_escape + && let Some(on_change) = &on_change + { + on_change(false, window, cx); + } + cx.stop_propagation(); + } + }) + .when(self.title.is_some() || show_close, |panel| { + panel.child( + h_flex() + .h_12() + .px_2() + .gap_2() + .justify_between() + .when(show_close, |row| row.child(div().w_7())) + .when_some(self.title.clone(), |row, title| { + row.child( + div() + .flex_1() + .text_center() + .text_sm() + .font_semibold() + .child(title), + ) + }) + .when(show_close, |row| { + row.child( + Button::new((self.id.clone(), "dialog-close")) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .small() + .debug_selector(|| "dialog-close".to_string()) + .accessibility_label("Close") + .on_click({ + let on_change = on_change.clone(); + move |_, window, cx| { + if let Some(on_change) = &on_change { + on_change(false, window, cx); + } + } + }), + ) + }), + ) + }) + .when_some(content, |panel, content| { + panel.map(|this| { + if height.is_some() { + this.child( + ScrollArea::new((self.id.clone(), "dialog-content")) + .handle(scroll) + .flex_1() + .min_h_0() + .child(div().p_2().child(content)), + ) + } else { + this.child(div().p_2().child(content)) + } + }) + }) + .when_some(actions, |panel, actions| { + panel.child( + h_flex() + .px_2() + .h_12() + .justify_end() + .gap_2() + .children(actions), + ) + }) + .child( + canvas(|_, _, _| {}, { + move |_, _, window, cx| { + if !focus.contains_focused(window, cx) { + window.focus(&focus, cx); + } + } + }) + .absolute() + .inset_0(), + ) + .with_animation( + "dialog-enter", + Animation::new(enter_duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ), + ), ) .with_priority(DIALOG_LAYER) .into_any_element() diff --git a/crates/ui/src/components/menu.rs b/crates/ui/src/components/menu.rs index cb80f8b..25439d3 100644 --- a/crates/ui/src/components/menu.rs +++ b/crates/ui/src/components/menu.rs @@ -33,7 +33,7 @@ use gpui::{ }; use crate::components::common::{ - OVERLAY_LAYER, StyledExt as _, floating_panel, focus_handle, v_flex, + OVERLAY_LAYER, StyledExt as _, floating_panel, focus_handle, track_overlay_focus, v_flex, wrapping_adjacent_selectable, }; use crate::components::scroll_area::{ScrollArea, ScrollAxes}; @@ -557,6 +557,9 @@ impl RenderOnce for Menu { let trigger_bounds: Rc>>> = Rc::new(RefCell::new(None)); let on_change = self.on_change.clone(); + let panel_focus = focus_handle(&(self.id.clone(), "panel").into(), window, cx); + track_overlay_focus(&self.id, &panel_focus, self.open, window, cx); + let fallback_label = self .a11y_label .clone() diff --git a/crates/ui/src/components/popover.rs b/crates/ui/src/components/popover.rs index 5bfdcb1..835fbff 100644 --- a/crates/ui/src/components/popover.rs +++ b/crates/ui/src/components/popover.rs @@ -29,7 +29,9 @@ use gpui::{ StyleRefinement, Styled as _, Window, div, }; -use crate::components::common::{StyledExt as _, floating_panel, v_flex}; +use crate::components::common::{ + StyledExt as _, floating_panel, focus_handle, track_overlay_focus, v_flex, +}; use crate::components::menu::{ ChangeHandler, TriggerBoundsCell, anchored_overlay, focus_capture, trigger_toggle, }; @@ -133,6 +135,10 @@ impl RenderOnce for Popover { let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + // Keyboard focus rides the panel across frames. + let focus = focus_handle(&self.id, window, cx); + track_overlay_focus(&self.id, &focus, self.open, window, cx); + let fallback_label = self .a11y_label .clone() @@ -153,7 +159,6 @@ impl RenderOnce for Popover { .when(self.open, |wrapper| { let on_change = self.on_change; let label = fallback_label.clone(); - let focus = crate::components::common::focus_handle(&self.id, window, cx); let content = self.content.map(|content| content(window, cx)); wrapper.child(anchored_overlay( diff --git a/crates/ui/src/components/scrollbar.rs b/crates/ui/src/components/scrollbar.rs index 58a0d7e..f186a16 100644 --- a/crates/ui/src/components/scrollbar.rs +++ b/crates/ui/src/components/scrollbar.rs @@ -18,10 +18,10 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use gpui::{ - App, Bounds, DispatchPhase, ElementId, Entity, EntityId, IntoElement, ListState, MouseButton, - MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, RenderOnce, ScrollEvent, - ScrollHandle, SharedString, Styled as _, Task, UniformListScrollHandle, Window, canvas, fill, - point, + App, Bounds, DispatchPhase, ElementId, Entity, EntityId, Hitbox, HitboxBehavior, IntoElement, + ListState, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, + RenderOnce, ScrollEvent, ScrollHandle, SharedString, Styled as _, Task, + UniformListScrollHandle, Window, canvas, fill, point, }; use crate::components::common::ResultLogErr as _; @@ -232,6 +232,98 @@ impl ScrollbarHandle for ListState { } } +/// One frame's painted scrollbar: track, thumb, and the track's hitbox. +struct Metrics { + viewport: Bounds, + thumb_bounds: Bounds, + track_bounds: Bounds, + track_length: Pixels, + thumb_length: Pixels, + max_offset: Pixels, + hitbox: Hitbox, +} + +impl Metrics { + /// Measures the track and thumb, inserting the track's hitbox. + fn new( + handle: &dyn ScrollbarHandle, + axis: Axis, + window: &mut Window, + cx: &mut App, + ) -> Option { + let theme = cx.theme(); + let width = theme.scrollbar.width; + let inset = theme.scrollbar.inset; + let min_thumb = theme.scrollbar.min_thumb; + + let viewport = handle.viewport(); + let viewport_along = axis.viewport_along(&viewport); + let max_offset = axis.along(handle.max_offset()); + + if max_offset <= Pixels::ZERO || viewport_along <= Pixels::ZERO { + return None; + } + + let track_length = viewport_along - inset * 2.0; + let (thumb_length, thumb_travel) = Scrollbar::thumb_geometry( + viewport_along, + viewport_along + max_offset, + axis.along(handle.offset()), + track_length, + min_thumb, + ); + + // The track strip is the thumb's rail plus the padding the thumb rides inside. + let (thumb_bounds, track_bounds) = match axis { + Axis::Vertical => { + let thumb_x = viewport.right() - width - inset; + ( + Bounds::from_corners( + point(thumb_x, viewport.top() + inset + thumb_travel), + point( + thumb_x + width, + viewport.top() + inset + thumb_travel + thumb_length, + ), + ), + Bounds::from_corners( + point(viewport.right() - width, viewport.top() + inset), + point(viewport.right(), viewport.top() + inset + track_length), + ), + ) + } + Axis::Horizontal => { + let thumb_y = viewport.bottom() - width - inset; + ( + Bounds::from_corners( + point(viewport.left() + inset + thumb_travel, thumb_y), + point( + viewport.left() + inset + thumb_travel + thumb_length, + thumb_y + width, + ), + ), + Bounds::from_corners( + point(viewport.left() + inset, viewport.bottom() - width), + point(viewport.left() + inset + track_length, viewport.bottom()), + ), + ) + } + }; + + // A covering surface that blocks mouse input keeps the track unhovered. + let hitbox = window.insert_hitbox(track_bounds, HitboxBehavior::Normal); + + Some(Self { + viewport, + thumb_bounds, + track_bounds, + track_length, + thumb_length, + max_offset, + hitbox, + }) + } +} + /// An overlay scrollbar, rendered over the scrolled surface. #[derive(IntoElement)] #[must_use] @@ -244,13 +336,18 @@ pub struct Scrollbar { impl RenderOnce for Scrollbar { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { - canvas(|_, _, _| {}, { - let handle = self.handle; - let axis = self.axis; - let visibility = self.visibility; - let id = self.id; - move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx) - }) + let axis = self.axis; + let visibility = self.visibility; + let id = self.id; + let measured_handle = self.handle.clone(); + let painted_handle = self.handle; + + canvas( + move |_, window, cx| Metrics::new(measured_handle.as_ref(), axis, window, cx), + move |_, metrics, window, cx| { + Self::paint(&painted_handle, axis, visibility, &id, metrics, window, cx) + }, + ) .absolute() .inset_0() } @@ -327,24 +424,28 @@ impl Scrollbar { axis: Axis, visibility: ScrollbarVisibility, id: &ElementId, + metrics: Option, window: &mut Window, cx: &mut App, ) { + let Some(Metrics { + viewport, + thumb_bounds, + track_bounds, + track_length, + thumb_length, + max_offset, + hitbox, + }) = metrics + else { + return; + }; + let view = window.current_view(); let theme = cx.theme(); let color = theme.colors.scrollbar_thumb; let width = theme.scrollbar.width; - let inset = theme.scrollbar.inset; - let min_thumb = theme.scrollbar.min_thumb; - - let viewport = handle.viewport(); - let viewport_along = axis.viewport_along(&viewport); - let max_offset = axis.along(handle.max_offset()); - - if max_offset <= Pixels::ZERO || viewport_along <= Pixels::ZERO { - return; - } let autohide = match visibility { ScrollbarVisibility::Platform => theme.scrollbar.autohide, @@ -355,51 +456,6 @@ impl Scrollbar { let autohide_state = autohide.then(|| Autohide::new(Self::state_key("autohide", id), window, cx)); - let track_length = viewport_along - inset * 2.0; - let (thumb_length, thumb_travel) = Self::thumb_geometry( - viewport_along, - viewport_along + max_offset, - axis.along(handle.offset()), - track_length, - min_thumb, - ); - - // The track strip is the thumb's rail plus the padding the thumb rides inside. - let (thumb_bounds, track_bounds) = match axis { - Axis::Vertical => { - let thumb_x = viewport.right() - width - inset; - ( - Bounds::from_corners( - point(thumb_x, viewport.top() + inset + thumb_travel), - point( - thumb_x + width, - viewport.top() + inset + thumb_travel + thumb_length, - ), - ), - Bounds::from_corners( - point(viewport.right() - width, viewport.top() + inset), - point(viewport.right(), viewport.top() + inset + track_length), - ), - ) - } - Axis::Horizontal => { - let thumb_y = viewport.bottom() - width - inset; - ( - Bounds::from_corners( - point(viewport.left() + inset + thumb_travel, thumb_y), - point( - viewport.left() + inset + thumb_travel + thumb_length, - thumb_y + width, - ), - ), - Bounds::from_corners( - point(viewport.left() + inset, viewport.bottom() - width), - point(viewport.left() + inset + track_length, viewport.bottom()), - ), - ) - } - }; - let drag = window.use_keyed_state(Self::state_key("thumb-drag", id), cx, |_, _| Drag::None); let dragging = drag.read(cx).is_some(); @@ -433,6 +489,11 @@ impl Scrollbar { return; } + // A covering surface blocks the pointer, so the track is not hovered. + if !hitbox.is_hovered_at(event.position, window) { + return; + } + let in_thumb = thumb_bounds.contains(&event.position); let in_track = !in_thumb && track_bounds.contains(&event.position); diff --git a/crates/ui/src/components/tooltip.rs b/crates/ui/src/components/tooltip.rs index f3b8066..6d71d14 100644 --- a/crates/ui/src/components/tooltip.rs +++ b/crates/ui/src/components/tooltip.rs @@ -1,8 +1,8 @@ //! Renders a small text panel next to a hovered element. //! -//! Most call sites hand [`Tooltip::text`] or [`Tooltip::anchored`] to gpui's -//! `.tooltip(...)` method; [`Tooltip::new`] creates the view for callers that -//! hold the [`gpui::Entity`] themselves. +//! Most call sites hand [`Tooltip::text`] to gpui's `.tooltip(...)` method; +//! [`Tooltip::new`] creates the view for callers that hold the [`gpui::Entity`] +//! themselves. The panel follows the pointer. //! //! # Examples //! @@ -14,22 +14,17 @@ //! ``` use gpui::{ - AnyView, App, AppContext as _, Bounds, Context, ElementId, Entity, InteractiveElement as _, - IntoElement, ParentElement as _, Pixels, Render, Role, SharedString, - StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point, px, + AnyView, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, + ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _, Styled as _, + Window, div, }; -use crate::components::common::{anchor_bounds, floating_panel, record_anchor_bounds}; -use crate::theme::{ - ActiveTheme as _, BORDER_WIDTH, TOOLTIP_ANCHOR_GAP, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET, -}; - -const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds"; +use crate::components::common::floating_panel; +use crate::theme::{ActiveTheme as _, TOOLTIP_MAX_WIDTH}; /// A small text panel gpui shows next to a hovered element. pub struct Tooltip { text: SharedString, - anchor: Option>, } impl Tooltip { @@ -38,34 +33,7 @@ impl Tooltip { where L: Into, { - cx.new(|_| Self { - text: text.into(), - anchor: None, - }) - } - - /// Returns the `.tooltip(...)` closure that pins the panel next to the - /// element identified by `anchor_id`. - /// - /// [`Tooltip::text`] places the panel at the pointer instead. - pub fn anchored( - text: L, - anchor_id: I, - ) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static - where - L: Into, - I: Into, - { - let text = text.into(); - let anchor_id = anchor_id.into(); - move |window, cx| { - let anchor = anchor_bounds(window.window_handle().window_id(), &anchor_id, cx); - cx.new(|_| Self { - text: text.clone(), - anchor, - }) - .into() - } + cx.new(|_| Self { text: text.into() }) } /// Returns the `.tooltip(...)` closure for a plain text tooltip. @@ -79,15 +47,17 @@ impl Tooltip { } impl Render for Tooltip { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - // Copied out: the mutable reads below need `cx` free of this borrow. + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); let surface_foreground = theme.colors.surface_foreground; let radius_sm = theme.radius.sm; let shadows = theme.elevations.popover.shadows(); - let build_panel = || { - floating_panel( + div() + .debug_selector(|| "tooltip-anchor".to_string()) + .pl_2() + .pt_2() + .child(floating_panel( cx, radius_sm, div() @@ -100,53 +70,7 @@ impl Render for Tooltip { .text_sm() .text_color(surface_foreground) .child(self.text.clone()), - shadows.clone(), - ) - }; - - let (wrapper, panel) = match self.anchor { - Some(parent) => { - let origin = window.mouse_position() + point(TOOLTIP_OFFSET, TOOLTIP_OFFSET); - let viewport_height = window.viewport_size().height; - - let height = anchor_bounds( - window.window_handle().window_id(), - &ElementId::from(PANEL_BOUNDS_ID), - cx, - ) - .map(|bounds| bounds.size.height) - .unwrap_or_else(|| window.line_height() + px(8.) + BORDER_WIDTH * 2.0); - - let below = viewport_height - TOOLTIP_ANCHOR_GAP - parent.bottom(); - let above = parent.top() - TOOLTIP_ANCHOR_GAP; - let hang_below = below >= height || below >= above; - - let panel = build_panel() - .ml(parent.left() - origin.x) - .mt(if hang_below { - parent.bottom() + TOOLTIP_ANCHOR_GAP - origin.y - } else { - parent.top() - TOOLTIP_ANCHOR_GAP - height - origin.y - }) - .child( - canvas( - record_anchor_bounds(ElementId::from(PANEL_BOUNDS_ID)), - |_, _, _, _| {}, - ) - .absolute() - .inset_0(), - ); - (div().debug_selector(|| "tooltip-anchor".to_string()), panel) - } - None => { - let wrapper = div() - .debug_selector(|| "tooltip-anchor".to_string()) - .pl_2() - .pt_2(); - (wrapper, build_panel()) - } - }; - - wrapper.child(panel) + shadows, + )) } } diff --git a/crates/ui/src/layout/root.rs b/crates/ui/src/layout/root.rs index d5d2c5e..e53385e 100644 --- a/crates/ui/src/layout/root.rs +++ b/crates/ui/src/layout/root.rs @@ -126,9 +126,18 @@ impl Root { cx.notify(); } - /// Mounts a dialog view above the content. + /// Mounts a dialog view above the content, replacing an open dialog of the same view type. fn mount_dialog(&mut self, view: impl Into, cx: &mut Context) { - self.dialogs.push(view.into()); + let view = view.into(); + if let Some(existing) = self + .dialogs + .iter_mut() + .find(|dialog| dialog.entity_type() == view.entity_type()) + { + *existing = view; + } else { + self.dialogs.push(view); + } cx.notify(); } diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs index c58cc8a..142841d 100644 --- a/crates/ui/src/theme/mod.rs +++ b/crates/ui/src/theme/mod.rs @@ -35,8 +35,6 @@ pub const BORDER_WIDTH: Pixels = px(1.0); pub const OVERLAY_ICON_SIZE: Rems = rems(0.75); /// The draggable width of a resize seam and its panel-row gutter. pub const RESIZE_HANDLE_WIDTH: Pixels = px(8.0); -/// The gap between an anchored tooltip and its anchor. -pub const TOOLTIP_ANCHOR_GAP: Pixels = px(4.0); /// The widest a titlebar tab grows before its label fades. pub const TAB_MAX_WIDTH: Pixels = px(240.0); /// The narrowest a titlebar tab shrinks, keeping short labels clear of the fade. @@ -69,8 +67,6 @@ pub const CODE_LINE_HEIGHT: f32 = 1.5; pub const POPUP_MAX_HEIGHT: Pixels = px(320.0); /// The widest a tooltip may grow. pub const TOOLTIP_MAX_WIDTH: Pixels = px(360.0); -/// How far a tooltip sits from the pointer. -pub const TOOLTIP_OFFSET: Pixels = px(1.0); /// The caret's thickness. pub const CARET_WIDTH: Pixels = px(1.5); /// The IME preedit underline's thickness. diff --git a/crates/ui/tests/popover.rs b/crates/ui/tests/popover.rs new file mode 100644 index 0000000..2ef8352 --- /dev/null +++ b/crates/ui/tests/popover.rs @@ -0,0 +1,112 @@ +//! A popover takes focus on open and gives it back to what held it on close. + +use gpui::{ + Context, FocusHandle, InteractiveElement as _, IntoElement, Modifiers, ParentElement as _, + Render, Styled as _, TestAppContext, VisualTestContext, Window, div, px, size, +}; +use ui::common::v_flex; +use ui::popover::Popover; +use ui::theme::Theme; + +const WINDOW_WIDTH: f32 = 800.0; +const WINDOW_HEIGHT: f32 = 600.0; + +/// A popover over a focusable trigger, with its open state held by the view. +struct PopoverHarness { + open: bool, + trigger_focus: FocusHandle, +} + +impl Render for PopoverHarness { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let harness = cx.entity(); + let trigger_focus = self.trigger_focus.clone(); + + v_flex().size_full().p_4().child( + Popover::new("focus-popover") + .open(self.open) + .on_change(move |open, _window, cx| { + harness.update(cx, |harness, cx| { + harness.open = open; + cx.notify(); + }); + }) + .trigger(move |_, _| { + div() + .w(px(200.)) + .h(px(40.)) + .track_focus(&trigger_focus) + .debug_selector(|| "focus-popover-trigger".to_string()) + .into_any_element() + }) + .content(|_, _| { + div() + .h(px(120.)) + .debug_selector(|| "focus-popover-content".to_string()) + .into_any_element() + }), + ) + } +} + +/// The focused handle, whether it is on screen, and the trigger the popover opened over. +fn focus_state(cx: &mut VisualTestContext) -> Option<(FocusHandle, bool)> { + cx.update(|window, cx| { + window + .focused(cx) + .map(|focused| (focused.clone(), focused.is_rendered(window))) + }) +} + +#[gpui::test] +fn closing_a_popover_restores_the_previous_focus(cx: &mut TestAppContext) { + cx.update(Theme::init); + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, cx| { + PopoverHarness { + open: false, + trigger_focus: cx.focus_handle(), + } + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + + let harness = window.root(&mut cx).expect("harness view"); + let trigger_focus = cx.update(|_, cx| harness.read(cx).trigger_focus.clone()); + let trigger = cx + .debug_bounds("focus-popover-trigger") + .expect("trigger laid out"); + + cx.update(|window, cx| window.focus(&trigger_focus, cx)); + assert_eq!( + focus_state(&mut cx), + Some((trigger_focus.clone(), true)), + "the trigger holds focus before the popover opens" + ); + + cx.simulate_click(trigger.center(), Modifiers::default()); + cx.run_until_parked(); + + assert!( + cx.debug_bounds("popover-panel").is_some(), + "clicking the trigger opens the popover" + ); + let (opened_focus, opened_rendered) = focus_state(&mut cx).expect("the panel takes focus"); + assert!(opened_rendered, "the open panel's focus is on screen"); + assert_ne!( + opened_focus, trigger_focus, + "the panel holds focus while open" + ); + + cx.simulate_keystrokes("escape"); + cx.run_until_parked(); + + assert!( + cx.debug_bounds("popover-panel").is_none(), + "escape closes the popover" + ); + assert_eq!( + focus_state(&mut cx), + Some((trigger_focus, true)), + "focus returns to the trigger" + ); +} diff --git a/crates/ui/tests/scroll_area.rs b/crates/ui/tests/scroll_area.rs new file mode 100644 index 0000000..cbdfc5f --- /dev/null +++ b/crates/ui/tests/scroll_area.rs @@ -0,0 +1,94 @@ +//! A covering overlay swallows scrollbar presses instead of dragging the thumb +//! behind it. + +use gpui::prelude::FluentBuilder as _; +use gpui::{ + Context, InteractiveElement as _, IntoElement, Modifiers, MouseButton, ParentElement as _, + Render, ScrollHandle, Styled as _, TestAppContext, VisualTestContext, Window, div, point, px, + size, +}; +use ui::scroll_area::ScrollArea; +use ui::theme::Theme; + +const WINDOW_WIDTH: f32 = 800.0; +const WINDOW_HEIGHT: f32 = 600.0; +const VIEWPORT_HEIGHT: f32 = 100.0; +const ROW_HEIGHT: f32 = 40.0; +const ROWS: usize = 50; +/// The track's thickness, matching the theme's scrollbar width. +const TRACK_WIDTH: f32 = 8.0; + +/// A scroll area over a full-window cover the test toggles. +struct ScrollHarness { + handle: ScrollHandle, + covered: bool, +} + +impl Render for ScrollHarness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + div() + .relative() + .size_full() + .child( + ScrollArea::new("scroll-test") + .handle(self.handle.clone()) + .w_full() + .h(px(VIEWPORT_HEIGHT)) + .children( + (0..ROWS).map(|row| { + div().w_full().h(px(ROW_HEIGHT)).child(format!("row {row}")) + }), + ), + ) + .when(self.covered, |this| { + this.child(div().absolute().inset_0().occlude()) + }) + } +} + +/// A press and release in the middle of the scrollbar's track. +fn press_track(cx: &mut VisualTestContext) { + let track = point( + px(WINDOW_WIDTH - TRACK_WIDTH / 2.0), + px(VIEWPORT_HEIGHT * 0.8), + ); + cx.simulate_mouse_down(track, MouseButton::Left, Modifiers::default()); + cx.simulate_mouse_up(track, MouseButton::Left, Modifiers::default()); +} + +#[gpui::test] +fn a_covering_overlay_blocks_scrollbar_drags(cx: &mut TestAppContext) { + cx.update(Theme::init); + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| { + ScrollHarness { + handle: ScrollHandle::new(), + covered: true, + } + }); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + + let harness = window.root(&mut cx).expect("harness view"); + let handle = cx.update(|_, cx| harness.read(cx).handle.clone()); + + press_track(&mut cx); + assert_eq!( + handle.offset().y, + px(0.), + "the cover swallows the press on the track behind it" + ); + + cx.update(|_, cx| { + harness.update(cx, |harness, cx| { + harness.covered = false; + cx.notify(); + }); + }); + cx.run_until_parked(); + + press_track(&mut cx); + assert!( + handle.offset().y < px(0.), + "an uncovered press on the track scrolls the content" + ); +}