chore: stabilize element ids and overlay focus tracking
Rust / build (macos-latest, stable) (push) Canceled after 0s
Rust / build (ubuntu-latest, stable) (push) Canceled after 0s
Rust / build (windows-latest, stable) (push) Canceled after 0s

This commit is contained in:
2026-11-24 19:41:45 +07:00
parent 4979eff1f1
commit 0fd8ea12fb
24 changed files with 638 additions and 404 deletions
+11 -10
View File
@@ -7,7 +7,7 @@ use gpui::{
ParentElement as _, Render, Styled as _, Subscription, WeakEntity, Window, div, ParentElement as _, Render, Styled as _, Subscription, WeakEntity, Window, div,
}; };
use helpers::apply_appearance_mode; use helpers::apply_appearance_mode;
use settings::SettingsStore; use settings::{AppearanceMode, SettingsStore};
use signed_state::{Backend, BackendEvent}; use signed_state::{Backend, BackendEvent};
use ui::common::{h_flex, v_flex}; use ui::common::{h_flex, v_flex};
use ui::icons::IconRole; use ui::icons::IconRole;
@@ -28,7 +28,7 @@ use crate::titlebar::{
pub struct AppRoot { pub struct AppRoot {
panels: Entity<PanelStack>, panels: Entity<PanelStack>,
titlebar: Entity<TitlebarView>, titlebar: Entity<TitlebarView>,
passphrase: Option<Entity<PassphraseDialog>>, appearance: AppearanceMode,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
@@ -66,9 +66,12 @@ impl AppRoot {
}, },
)); ));
subscriptions.push(cx.observe(&settings, |_this, store, cx| { subscriptions.push(cx.observe(&settings, |this, store, cx| {
let settings = store.read(cx).settings().clone(); let appearance = store.read(cx).settings().appearance;
apply_appearance_mode(settings.appearance, cx); if appearance != this.appearance {
this.appearance = appearance;
apply_appearance_mode(appearance, cx);
}
})); }));
window.defer(cx, move |window, cx| { window.defer(cx, move |window, cx| {
@@ -78,20 +81,18 @@ impl AppRoot {
Self::reset_to_explore(&app, window, cx); Self::reset_to_explore(&app, window, cx);
}); });
let appearance = settings.read(cx).settings().appearance;
Self { Self {
panels, panels,
titlebar, titlebar,
passphrase: None, appearance,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
fn open_passphrase(&mut self, cx: &mut Context<Self>) { fn open_passphrase(&mut self, cx: &mut Context<Self>) {
if self.passphrase.is_some() {
return;
}
let dialog = PassphraseDialog::new(cx); let dialog = PassphraseDialog::new(cx);
self.passphrase = Some(dialog.clone());
cx.open_dialog(dialog); cx.open_dialog(dialog);
} }
+2 -2
View File
@@ -65,7 +65,6 @@ impl RepoFilter {
} }
pub(super) fn render_card( pub(super) fn render_card(
ix: usize,
announcement: &Announcement, announcement: &Announcement,
last_activity: Option<Timestamp>, last_activity: Option<Timestamp>,
announcements: &[Announcement], announcements: &[Announcement],
@@ -98,7 +97,7 @@ pub(super) fn render_card(
}); });
v_flex() v_flex()
.id(ix) .id(SharedString::from(format!("repo-card:{}", announcement.id)))
.flex_1() .flex_1()
.h_full() .h_full()
.min_w_0() .min_w_0()
@@ -113,6 +112,7 @@ pub(super) fn render_card(
.gap_2() .gap_2()
.child( .child(
div() div()
.flex_1()
.min_w_0() .min_w_0()
.text_sm() .text_sm()
.font_semibold() .font_semibold()
-1
View File
@@ -294,7 +294,6 @@ impl Render for ExploreView {
}; };
let activity = last_activity.get(&announcement.addr()).copied(); let activity = last_activity.get(&announcement.addr()).copied();
cards.push(render_card( cards.push(render_card(
ix,
announcement, announcement,
activity, activity,
&announcements, &announcements,
+9 -1
View File
@@ -127,7 +127,15 @@ pub(crate) fn sidebar_section(
.picture(profile.picture()) .picture(profile.picture())
.small(), .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() .into_any_element()
})), })),
) )
+2 -3
View File
@@ -182,8 +182,7 @@ impl Render for IssuesView {
let rows = visible_issues let rows = visible_issues
.iter() .iter()
.enumerate() .filter_map(|&issue_ix| {
.filter_map(|(ix, &issue_ix)| {
// The store re-read per frame can shrink below a captured index. // The store re-read per frame can shrink below a captured index.
let issue = store.read(cx).issues.get(issue_ix)?; let issue = store.read(cx).issues.get(issue_ix)?;
let profile = directory.read(cx).profile(&issue.pubkey, cx); let profile = directory.read(cx).profile(&issue.pubkey, cx);
@@ -210,7 +209,7 @@ impl Render for IssuesView {
}; };
Some(EventRow { Some(EventRow {
id: ix.into(), id: SharedString::from(format!("issue:{id_hex}")).into(),
status, status,
title: issue.activity_subject().into(), title: issue.activity_subject().into(),
author: profile.name(), author: profile.name(),
+2 -3
View File
@@ -295,8 +295,7 @@ impl Render for PullRequestsView {
let rows = visible let rows = visible
.iter() .iter()
.enumerate() .filter_map(|&pr_ix| {
.filter_map(|(ix, &pr_ix)| {
// The store re-read per frame can shrink below a captured index. // The store re-read per frame can shrink below a captured index.
let pr = store.read(cx).pull_requests.get(pr_ix)?; let pr = store.read(cx).pull_requests.get(pr_ix)?;
let profile = directory.read(cx).profile(&pr.pubkey, cx); let profile = directory.read(cx).profile(&pr.pubkey, cx);
@@ -332,7 +331,7 @@ impl Render for PullRequestsView {
}; };
Some(EventRow { Some(EventRow {
id: ix.into(), id: SharedString::from(format!("pr:{id_hex}")).into(),
status, status,
title: pr.activity_subject().into(), title: pr.activity_subject().into(),
author: profile.name(), author: profile.name(),
+7 -5
View File
@@ -559,11 +559,9 @@ fn render_pane_row(
impl Render for DiffPane { impl Render for DiffPane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
if self.diff.is_none() { let Some(diff) = self.diff.as_ref() else {
return EmptyState::centered("No changes"); return EmptyState::centered("No changes");
} };
let diff = self.diff.as_ref().expect("diff checked above");
if diff.files.is_empty() { if diff.files.is_empty() {
return EmptyState::centered("No files changed"); return EmptyState::centered("No files changed");
@@ -822,7 +820,9 @@ impl CommitDiffView {
h_flex() h_flex()
.gap_2() .gap_2()
.child(Avatar::new(name.clone()).name(name.clone()).small()) .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(), .into_any_element(),
) )
}) })
@@ -849,6 +849,7 @@ impl CommitDiffView {
.gap_2() .gap_2()
.child( .child(
div() div()
.min_w_0()
.text_ellipsis() .text_ellipsis()
.truncate() .truncate()
.child(SharedString::from(commit.id.clone())), .child(SharedString::from(commit.id.clone())),
@@ -863,6 +864,7 @@ impl CommitDiffView {
.gap_2() .gap_2()
.child( .child(
div() div()
.min_w_0()
.text_ellipsis() .text_ellipsis()
.truncate() .truncate()
.child(SharedString::from(parent.clone())), .child(SharedString::from(parent.clone())),
+1
View File
@@ -340,6 +340,7 @@ impl RepoFilesView {
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.child( .child(
div() div()
.min_w_0()
.text_xs() .text_xs()
.font_medium() .font_medium()
.text_ellipsis() .text_ellipsis()
+7 -1
View File
@@ -211,7 +211,13 @@ pub(super) fn fork_row(
.text_base() .text_base()
.text_color(cx.theme().colors.muted_foreground) .text_color(cx.theme().colors.muted_foreground)
.child(Icon::named(IconRole::GitBranch).small()) .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 { Some(if clickable {
row.id("fork-upstream") row.id("fork-upstream")
+21 -9
View File
@@ -390,7 +390,7 @@ impl RepoDetailView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
return; return;
} }
@@ -509,7 +509,7 @@ impl RepoDetailView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn apply_repo_data(&mut self, data: RepoData, window: &mut Window, cx: &mut Context<Self>) { fn apply_repo_data(&mut self, data: RepoData, window: &mut Window, cx: &mut Context<Self>) {
@@ -609,7 +609,7 @@ impl RepoDetailView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn switch_ref<T>(&mut self, kind: RefKind, name: T, window: &mut Window, cx: &mut Context<Self>) fn switch_ref<T>(&mut self, kind: RefKind, name: T, window: &mut Window, cx: &mut Context<Self>)
@@ -684,7 +684,7 @@ impl RepoDetailView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn reload_worktree(&mut self, cx: &mut Context<Self>) { fn reload_worktree(&mut self, cx: &mut Context<Self>) {
@@ -727,7 +727,7 @@ impl RepoDetailView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
/// Refresh the file explorer and previews after the mirror caught up with the remote. /// Refresh the file explorer and previews after the mirror caught up with the remote.
@@ -758,6 +758,12 @@ impl RepoDetailView {
Ok(()) Ok(())
}); });
self.push_task(task);
}
/// Reaps finished tasks, then queues another.
fn push_task(&mut self, task: Task<Result<(), Error>>) {
self.tasks.retain(|task| !task.is_ready());
self.tasks.push(task); self.tasks.push(task);
} }
@@ -766,7 +772,7 @@ impl RepoDetailView {
cx.notify(); cx.notify();
let task = self.store.update(cx, |store, cx| store.push_repository(cx)); 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 { fn sync_notification_tag(addr: &RepoAddr) -> SharedString {
@@ -866,7 +872,7 @@ impl RepoDetailView {
Ok(()) Ok(())
}); });
self.tasks.push(task); self.push_task(task);
} }
fn reset_remote(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn reset_remote(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -932,7 +938,7 @@ impl RepoDetailView {
let task = self let task = self
.store .store
.update(cx, |store, cx| store.delete_repository(cx)); .update(cx, |store, cx| store.delete_repository(cx));
self.tasks.push(task); self.push_task(task);
} }
fn render_files_tab(&self, cx: &App) -> AnyElement { fn render_files_tab(&self, cx: &App) -> AnyElement {
@@ -1122,7 +1128,13 @@ impl RepoDetailView {
.text_sm() .text_sm()
.font_semibold() .font_semibold()
.child(avatar) .child(avatar)
.child(name), .child(
div()
.min_w_0()
.whitespace_nowrap()
.text_ellipsis()
.child(name),
),
) )
.child( .child(
div() div()
+1 -3
View File
@@ -226,7 +226,6 @@ pub fn commit_list(
let on_click = on_click.clone(); let on_click = on_click.clone();
let row_commit = commit.clone(); let row_commit = commit.clone();
commit_row( commit_row(
ix,
&commit, &commit,
action, action,
move |window, cx| on_click(&row_commit, window, cx), 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. /// One copyable commit summary row: id, subject, author, and age.
pub(crate) fn commit_row( pub(crate) fn commit_row(
ix: usize,
commit: &FileCommit, commit: &FileCommit,
action: Option<AnyElement>, action: Option<AnyElement>,
on_click: impl Fn(&mut Window, &mut gpui::App) + 'static, on_click: impl Fn(&mut Window, &mut gpui::App) + 'static,
cx: &gpui::App, cx: &gpui::App,
) -> gpui::AnyElement { ) -> gpui::AnyElement {
h_flex() h_flex()
.id(ix) .id(commit.id.clone())
.px_4() .px_4()
.h(px(COMMIT_ROW_HEIGHT)) .h(px(COMMIT_ROW_HEIGHT))
.w_full() .w_full()
@@ -211,7 +211,7 @@ impl Render for RepositorySwitcher {
Some( Some(
h_flex() h_flex()
.id(("repo-switcher-entry", index)) .id(entry.key.clone())
.role(Role::MenuItem) .role(Role::MenuItem)
.w_full() .w_full()
.h(row_height) .h(row_height)
+2 -9
View File
@@ -17,12 +17,10 @@ use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
AnyElement, AnyView, App, ClickEvent, ElementId, Hsla, InteractiveElement as _, IntoElement, AnyElement, AnyView, App, ClickEvent, ElementId, Hsla, InteractiveElement as _, IntoElement,
ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, 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::{ use crate::components::common::{ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex};
ControlSizing, Sizable, StyledExt as _, focus_ring, h_flex, record_anchor_bounds,
};
use crate::components::spinner::Spinner; use crate::components::spinner::Spinner;
use crate::icons::Icon; use crate::icons::Icon;
use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; 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(self.disabled, |button| button.opacity(DISABLED_OPACITY))
.when_some(self.tooltip, |button, tooltip| { .when_some(self.tooltip, |button, tooltip| {
button.tooltip(move |window, cx| tooltip(window, cx)) button.tooltip(move |window, cx| tooltip(window, cx))
+9 -10
View File
@@ -15,7 +15,7 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ 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, SharedString, StyleRefinement, Styled as _, Task, Window, div,
}; };
@@ -108,18 +108,17 @@ impl Sizable for ClipboardButton {
/// The transient copied marker keyed per button. /// The transient copied marker keyed per button.
struct CopiedState { struct CopiedState {
generation: u64, generation: u64,
tasks: Vec<Task<()>>, task: Option<Task<()>>,
} }
impl RenderOnce for ClipboardButton { impl RenderOnce for ClipboardButton {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let copied: Entity<CopiedState> = let copied = window.use_keyed_state((self.id.clone(), "clipboard-copied"), cx, |_, _| {
window.use_keyed_state((self.id.clone(), "clipboard-copied"), cx, |_, _| { CopiedState {
CopiedState { generation: 0,
generation: 0, task: None,
tasks: Vec::new(), }
} });
});
let is_copied = copied.read(cx).generation != 0; let is_copied = copied.read(cx).generation != 0;
let selector = if is_copied { let selector = if is_copied {
@@ -172,7 +171,7 @@ impl RenderOnce for ClipboardButton {
}); });
copied.update(cx, |state, _| { copied.update(cx, |state, _| {
state.tasks.push(task); state.task = Some(task);
}); });
// Invoke the callback after copying // Invoke the callback after copying
+43 -34
View File
@@ -10,13 +10,11 @@
//! let column = v_flex().gap_2().child(row); //! let column = v_flex().gap_2().child(row);
//! ``` //! ```
use std::collections::HashMap;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
App, Bounds, BoxShadow, Div, ElementId, FocusHandle, FontWeight, Global, Hsla, IntoElement, App, BoxShadow, Div, ElementId, FocusHandle, FontWeight, Hsla, IntoElement, Pixels,
Pixels, Refineable as _, Rems, StatefulInteractiveElement, StyleRefinement, Styled, Window, Refineable as _, Rems, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
WindowId, div, px, rems, Window, div, px, rems,
}; };
use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD, Size}; 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. /// A handler told to clean up after a dismissed surface.
pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>; pub type DismissHandler = std::rc::Rc<dyn Fn(&mut gpui::App)>;
/// The painted bounds of elements that tooltips anchor to, per window and element id.
#[derive(Default)]
struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds<Pixels>>);
impl Global for AnchorBoundsRegistry {}
impl AnchorBoundsRegistry {
fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds<Pixels>) {
self.0.insert((window, id), bounds);
}
fn get(&self, window: WindowId, id: &ElementId) -> Option<Bounds<Pixels>> {
self.0.get(&(window, id.clone())).copied()
}
}
/// A row whose children center on the cross axis. /// A row whose children center on the cross axis.
#[must_use] #[must_use]
pub fn h_flex() -> Div { pub fn h_flex() -> Div {
@@ -112,20 +94,47 @@ pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusH
.clone() .clone()
} }
/// The last bounds an element painted at, in the given window. /// Saves the focused handle while an overlay is open and restores it when the
pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option<Bounds<Pixels>> { /// overlay closes, unless another surface already took focus.
cx.try_global::<AnchorBoundsRegistry>() pub(crate) fn track_overlay_focus(
.and_then(|registry| registry.get(window, id)) 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::<FocusHandle>,
);
/// A canvas prepaint closure recording the element's painted bounds. let was_open_now = *was_open.read(cx);
pub fn record_anchor_bounds( if open && !was_open_now {
id: ElementId, let focused = window.focused(cx);
) -> impl Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static { previous.update(cx, |previous, _| *previous = focused);
move |bounds, window, cx| { was_open.update(cx, |was_open, _| *was_open = true);
let window_id = window.window_handle().window_id(); } else if !open && was_open_now {
cx.default_global::<AnchorBoundsRegistry>() was_open.update(cx, |was_open, _| *was_open = false);
.record(window_id, id.clone(), bounds); 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);
}
});
} }
} }
+148 -144
View File
@@ -34,7 +34,8 @@ use gpui::{
use crate::components::button::{Button, ButtonVariant}; use crate::components::button::{Button, ButtonVariant};
use crate::components::common::{ 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::grain::grain;
use crate::components::scroll_area::ScrollArea; use crate::components::scroll_area::ScrollArea;
@@ -254,6 +255,10 @@ impl RenderOnce for Dialog {
.as_ref() .as_ref()
.map_or(self.open, DialogHandle::is_open); .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 { if !open {
return root.into_any_element(); return root.into_any_element();
} }
@@ -296,163 +301,162 @@ impl RenderOnce for Dialog {
let close_on_backdrop = self.close_on_backdrop; let close_on_backdrop = self.close_on_backdrop;
let show_close = !alert && on_change.is_some() && (close_on_escape || 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 content = self.content.map(|build| build(window, cx));
let actions = self.actions.map(|build| build(window, cx)); let actions = self.actions.map(|build| build(window, cx));
let height = self.height; let height = self.height;
let scroll = window 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) .read(cx)
.clone(); .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( deferred(
root.flex() root.flex()
.items_center() .items_center()
.justify_center() .justify_center()
.p_4() .p_4()
.refine_style(&self.style) .refine_style(&self.style)
.child(scrim.with_animation( .child(
"dialog-scrim-enter", div()
Animation::new(enter_duration).with_easing(ease_out_quint()), .absolute()
|scrim, delta| scrim.opacity(delta), .inset_0()
)) .bg(scrim_color)
.child(panel.with_animation( .occlude()
"dialog-enter", .when(self.grain, |scrim| scrim.child(grain()))
Animation::new(enter_duration).with_easing(ease_out_quint()), .when(!alert && close_on_backdrop, |scrim| {
|panel, delta| panel.opacity(delta), 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) .with_priority(DIALOG_LAYER)
.into_any_element() .into_any_element()
+4 -1
View File
@@ -33,7 +33,7 @@ use gpui::{
}; };
use crate::components::common::{ 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, wrapping_adjacent_selectable,
}; };
use crate::components::scroll_area::{ScrollArea, ScrollAxes}; use crate::components::scroll_area::{ScrollArea, ScrollAxes};
@@ -557,6 +557,9 @@ impl RenderOnce for Menu {
let trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None)); let trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>> = Rc::new(RefCell::new(None));
let on_change = self.on_change.clone(); 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 let fallback_label = self
.a11y_label .a11y_label
.clone() .clone()
+7 -2
View File
@@ -29,7 +29,9 @@ use gpui::{
StyleRefinement, Styled as _, Window, div, 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::{ use crate::components::menu::{
ChangeHandler, TriggerBoundsCell, anchored_overlay, focus_capture, trigger_toggle, 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)); 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 let fallback_label = self
.a11y_label .a11y_label
.clone() .clone()
@@ -153,7 +159,6 @@ impl RenderOnce for Popover {
.when(self.open, |wrapper| { .when(self.open, |wrapper| {
let on_change = self.on_change; let on_change = self.on_change;
let label = fallback_label.clone(); 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)); let content = self.content.map(|content| content(window, cx));
wrapper.child(anchored_overlay( wrapper.child(anchored_overlay(
+127 -66
View File
@@ -18,10 +18,10 @@ use std::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use gpui::{ use gpui::{
App, Bounds, DispatchPhase, ElementId, Entity, EntityId, IntoElement, ListState, MouseButton, App, Bounds, DispatchPhase, ElementId, Entity, EntityId, Hitbox, HitboxBehavior, IntoElement,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, RenderOnce, ScrollEvent, ListState, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point,
ScrollHandle, SharedString, Styled as _, Task, UniformListScrollHandle, Window, canvas, fill, RenderOnce, ScrollEvent, ScrollHandle, SharedString, Styled as _, Task,
point, UniformListScrollHandle, Window, canvas, fill, point,
}; };
use crate::components::common::ResultLogErr as _; 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<Pixels>,
thumb_bounds: Bounds<Pixels>,
track_bounds: Bounds<Pixels>,
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<Self> {
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. /// An overlay scrollbar, rendered over the scrolled surface.
#[derive(IntoElement)] #[derive(IntoElement)]
#[must_use] #[must_use]
@@ -244,13 +336,18 @@ pub struct Scrollbar {
impl RenderOnce for Scrollbar { impl RenderOnce for Scrollbar {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
canvas(|_, _, _| {}, { let axis = self.axis;
let handle = self.handle; let visibility = self.visibility;
let axis = self.axis; let id = self.id;
let visibility = self.visibility; let measured_handle = self.handle.clone();
let id = self.id; let painted_handle = self.handle;
move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx)
}) 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() .absolute()
.inset_0() .inset_0()
} }
@@ -327,24 +424,28 @@ impl Scrollbar {
axis: Axis, axis: Axis,
visibility: ScrollbarVisibility, visibility: ScrollbarVisibility,
id: &ElementId, id: &ElementId,
metrics: Option<Metrics>,
window: &mut Window, window: &mut Window,
cx: &mut App, 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 view = window.current_view();
let theme = cx.theme(); let theme = cx.theme();
let color = theme.colors.scrollbar_thumb; let color = theme.colors.scrollbar_thumb;
let width = theme.scrollbar.width; 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 { let autohide = match visibility {
ScrollbarVisibility::Platform => theme.scrollbar.autohide, ScrollbarVisibility::Platform => theme.scrollbar.autohide,
@@ -355,51 +456,6 @@ impl Scrollbar {
let autohide_state = let autohide_state =
autohide.then(|| Autohide::new(Self::state_key("autohide", id), window, cx)); 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 drag = window.use_keyed_state(Self::state_key("thumb-drag", id), cx, |_, _| Drag::None);
let dragging = drag.read(cx).is_some(); let dragging = drag.read(cx).is_some();
@@ -433,6 +489,11 @@ impl Scrollbar {
return; 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_thumb = thumb_bounds.contains(&event.position);
let in_track = !in_thumb && track_bounds.contains(&event.position); let in_track = !in_thumb && track_bounds.contains(&event.position);
+17 -93
View File
@@ -1,8 +1,8 @@
//! Renders a small text panel next to a hovered element. //! Renders a small text panel next to a hovered element.
//! //!
//! Most call sites hand [`Tooltip::text`] or [`Tooltip::anchored`] to gpui's //! Most call sites hand [`Tooltip::text`] to gpui's `.tooltip(...)` method;
//! `.tooltip(...)` method; [`Tooltip::new`] creates the view for callers that //! [`Tooltip::new`] creates the view for callers that hold the [`gpui::Entity`]
//! hold the [`gpui::Entity`] themselves. //! themselves. The panel follows the pointer.
//! //!
//! # Examples //! # Examples
//! //!
@@ -14,22 +14,17 @@
//! ``` //! ```
use gpui::{ use gpui::{
AnyView, App, AppContext as _, Bounds, Context, ElementId, Entity, InteractiveElement as _, AnyView, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
IntoElement, ParentElement as _, Pixels, Render, Role, SharedString, ParentElement as _, Render, Role, SharedString, StatefulInteractiveElement as _, Styled as _,
StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point, px, Window, div,
}; };
use crate::components::common::{anchor_bounds, floating_panel, record_anchor_bounds}; use crate::components::common::floating_panel;
use crate::theme::{ use crate::theme::{ActiveTheme as _, TOOLTIP_MAX_WIDTH};
ActiveTheme as _, BORDER_WIDTH, TOOLTIP_ANCHOR_GAP, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET,
};
const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds";
/// A small text panel gpui shows next to a hovered element. /// A small text panel gpui shows next to a hovered element.
pub struct Tooltip { pub struct Tooltip {
text: SharedString, text: SharedString,
anchor: Option<Bounds<Pixels>>,
} }
impl Tooltip { impl Tooltip {
@@ -38,34 +33,7 @@ impl Tooltip {
where where
L: Into<SharedString>, L: Into<SharedString>,
{ {
cx.new(|_| Self { cx.new(|_| Self { text: text.into() })
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<L, I>(
text: L,
anchor_id: I,
) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static
where
L: Into<SharedString>,
I: Into<ElementId>,
{
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()
}
} }
/// Returns the `.tooltip(...)` closure for a plain text tooltip. /// Returns the `.tooltip(...)` closure for a plain text tooltip.
@@ -79,15 +47,17 @@ impl Tooltip {
} }
impl Render for Tooltip { impl Render for Tooltip {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// Copied out: the mutable reads below need `cx` free of this borrow.
let theme = cx.theme(); let theme = cx.theme();
let surface_foreground = theme.colors.surface_foreground; let surface_foreground = theme.colors.surface_foreground;
let radius_sm = theme.radius.sm; let radius_sm = theme.radius.sm;
let shadows = theme.elevations.popover.shadows(); let shadows = theme.elevations.popover.shadows();
let build_panel = || { div()
floating_panel( .debug_selector(|| "tooltip-anchor".to_string())
.pl_2()
.pt_2()
.child(floating_panel(
cx, cx,
radius_sm, radius_sm,
div() div()
@@ -100,53 +70,7 @@ impl Render for Tooltip {
.text_sm() .text_sm()
.text_color(surface_foreground) .text_color(surface_foreground)
.child(self.text.clone()), .child(self.text.clone()),
shadows.clone(), shadows,
) ))
};
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)
} }
} }
+11 -2
View File
@@ -126,9 +126,18 @@ impl Root {
cx.notify(); 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<AnyView>, cx: &mut Context<Self>) { fn mount_dialog(&mut self, view: impl Into<AnyView>, cx: &mut Context<Self>) {
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(); cx.notify();
} }
-4
View File
@@ -35,8 +35,6 @@ pub const BORDER_WIDTH: Pixels = px(1.0);
pub const OVERLAY_ICON_SIZE: Rems = rems(0.75); pub const OVERLAY_ICON_SIZE: Rems = rems(0.75);
/// The draggable width of a resize seam and its panel-row gutter. /// The draggable width of a resize seam and its panel-row gutter.
pub const RESIZE_HANDLE_WIDTH: Pixels = px(8.0); 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. /// The widest a titlebar tab grows before its label fades.
pub const TAB_MAX_WIDTH: Pixels = px(240.0); pub const TAB_MAX_WIDTH: Pixels = px(240.0);
/// The narrowest a titlebar tab shrinks, keeping short labels clear of the fade. /// 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); pub const POPUP_MAX_HEIGHT: Pixels = px(320.0);
/// The widest a tooltip may grow. /// The widest a tooltip may grow.
pub const TOOLTIP_MAX_WIDTH: Pixels = px(360.0); 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. /// The caret's thickness.
pub const CARET_WIDTH: Pixels = px(1.5); pub const CARET_WIDTH: Pixels = px(1.5);
/// The IME preedit underline's thickness. /// The IME preedit underline's thickness.
+112
View File
@@ -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<Self>) -> 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"
);
}
+94
View File
@@ -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<Self>) -> 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"
);
}