chore: audit all components (#2)

Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
2026-11-08 06:27:12 +00:00
parent 0ad5c3fe90
commit 11b29dc91a
51 changed files with 2096 additions and 958 deletions
-43
View File
@@ -54,32 +54,6 @@ fn alert_window(
)
}
/// A banner with only a message paints, so the title stays optional.
#[test]
fn a_message_only_alert_renders() {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let window = cx.add_window(|_, _| MessageOnlyHarness);
let window = window.into();
let mut cx = VisualTestContext::from_window(window, &cx);
cx.update(|window, cx| {
window.draw(cx).clear(cx);
});
assert!(cx.debug_bounds("message-only-alert").is_some());
}
struct MessageOnlyHarness;
impl Render for MessageOnlyHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut gpui::Context<Self>) -> impl IntoElement {
div().size_full().p_4().child(
div()
.debug_selector(|| "message-only-alert".to_string())
.child(Alert::new("message-only").message("Only line.")),
)
}
}
/// Clicking the close button is how the user acts on the alert; the banner
/// reports the intent instead of hiding itself.
#[test]
@@ -94,20 +68,3 @@ fn closing_the_alert_reports_dismissal() {
assert!(*dismissed.borrow(), "the close button reported dismissal");
}
/// Every severity paints a banner.
#[test]
fn every_severity_renders_a_banner() {
for severity in [
AlertSeverity::Info,
AlertSeverity::Success,
AlertSeverity::Warning,
AlertSeverity::Danger,
] {
let (mut cx, _window, _dismissed) = alert_window(severity);
assert!(
cx.debug_bounds("test-alert").is_some(),
"{severity:?} alert rendered"
);
}
}
+18 -5
View File
@@ -11,6 +11,7 @@ use gpui_native_theme::Theme;
struct Harness {
clicks: Rc<RefCell<usize>>,
disabled: bool,
loading: bool,
}
impl Render for Harness {
@@ -20,14 +21,18 @@ impl Render for Harness {
Button::new("test-button")
.label("Save")
.disabled(self.disabled)
.loading(self.loading)
.on_click(move |_, _, _| *clicks.borrow_mut() += 1),
)
}
}
/// A maximized window whose button stretches across the top 28px, so
/// A maximized window whose button stretches across the top band, so
/// `point(px(60.), px(14.))` always lands on it.
fn button_window(disabled: bool) -> (VisualTestContext, AnyWindowHandle, Rc<RefCell<usize>>) {
fn button_window(
disabled: bool,
loading: bool,
) -> (VisualTestContext, AnyWindowHandle, Rc<RefCell<usize>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let clicks = Rc::new(RefCell::new(0));
@@ -35,6 +40,7 @@ fn button_window(disabled: bool) -> (VisualTestContext, AnyWindowHandle, Rc<RefC
let window = cx.add_window(move |_, _| Harness {
clicks: harness_clicks,
disabled,
loading,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
@@ -53,21 +59,28 @@ fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) {
#[test]
fn pointer_click_fires_on_click() {
let (mut cx, _window, clicks) = button_window(false);
let (mut cx, _window, clicks) = button_window(false, false);
cx.simulate_click(point(px(60.), px(14.)), Modifiers::default());
assert_eq!(*clicks.borrow(), 1);
}
#[test]
fn disabled_button_ignores_clicks() {
let (mut cx, _window, clicks) = button_window(true);
let (mut cx, _window, clicks) = button_window(true, false);
cx.simulate_click(point(px(60.), px(14.)), Modifiers::default());
assert_eq!(*clicks.borrow(), 0);
}
#[test]
fn loading_button_ignores_clicks() {
let (mut cx, _window, clicks) = button_window(false, true);
cx.simulate_click(point(px(60.), px(14.)), Modifiers::default());
assert_eq!(*clicks.borrow(), 0);
}
#[test]
fn enter_and_space_fire_on_click_while_focused() {
let (mut cx, window, clicks) = button_window(false);
let (mut cx, window, clicks) = button_window(false, false);
cx.simulate_click(point(px(60.), px(14.)), Modifiers::default());
assert_eq!(*clicks.borrow(), 1, "the pointer click itself activates");
+27 -2
View File
@@ -2,8 +2,8 @@ use std::cell::RefCell;
use std::rc::Rc;
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, TestAppContext, VisualTestContext, Window, div,
AppContext as _, Context, Entity, IntoElement, MouseButton, ParentElement as _, Render,
SharedString, Styled as _, TestAppContext, VisualTestContext, Window, div, point, px,
};
use gpui_native_core::combobox::{Combobox, ComboboxOption, ComboboxState};
use gpui_native_core::init;
@@ -99,6 +99,31 @@ fn draw(visual: &mut VisualTestContext) {
});
}
fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_down(position, MouseButton::Left, gpui::Modifiers::default());
visual.simulate_mouse_up(position, MouseButton::Left, gpui::Modifiers::default());
}
/// Clicking into a valueless combobox field opens the options right away:
/// no keystroke is needed to see the choices.
#[test]
fn clicking_the_empty_field_opens_the_popup() {
let mut host = combo_host(false, false);
// Inside the field, which sits at the top of the padded host.
click(&mut host.visual, point(px(100.), px(27.)));
draw(&mut host.visual);
assert!(
host.state.read_with(&host.cx, |state, _| state.is_open()),
"clicking the empty field should show the options"
);
assert!(
host.visual.debug_bounds("test-combo-panel").is_some(),
"the options panel should be rendered"
);
}
fn focus(host: &mut ComboHost) {
let state = host.state.clone();
host.visual.update(|window, cx| {
+11 -8
View File
@@ -5,7 +5,7 @@ use gpui::{
use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::input::{Input, InputState};
use gpui_native_theme::ActiveTheme as _;
use gpui_native_theme::Theme;
use gpui_native_theme::{BORDER_WIDTH, Theme};
struct Harness {
state: Entity<InputState>,
@@ -36,10 +36,12 @@ impl Render for Harness {
}
}
/// A medium input is exactly `input_height`, and sits taller than the
/// medium button: native text fields are a touch taller than push buttons.
/// The medium input and button render at the stated height plus the
/// hairline border sized outside it, so the two match wherever the platform
/// states equal values (macOS, Windows, GNOME) and stay equal to each other
/// on every platform.
#[gpui::test]
fn medium_input_is_taller_than_the_button(cx: &mut TestAppContext) {
fn controls_render_at_the_stated_heights(cx: &mut TestAppContext) {
cx.update(Theme::init);
let state = cx.update(|cx| InputState::new_with_text("", cx));
let state_for_window = state.clone();
@@ -58,9 +60,10 @@ fn medium_input_is_taller_than_the_button(cx: &mut TestAppContext) {
.debug_bounds("input-wrapper")
.expect("input rendered");
// The input's height is the theme table's (platform-stated) field height;
// both bounds are snapped to device pixels, so allow half a pixel.
let input_height = cx.update(|cx| cx.theme().sizes.medium.input_height);
assert!(input.size.height > button.size.height);
// Both bounds are snapped to device pixels, so allow half a pixel. The
// stated height is the interior; the border sizes outside it.
let input_height = cx.update(|cx| cx.theme().sizes.medium.input_height) + BORDER_WIDTH * 2.0;
let button_height = cx.update(|cx| cx.theme().sizes.medium.control_height) + BORDER_WIDTH * 2.0;
assert!((input.size.height - input_height).abs() <= gpui::px(0.5));
assert!((button.size.height - button_height).abs() <= gpui::px(0.5));
}
-8
View File
@@ -158,11 +158,3 @@ fn clicking_the_panel_does_not_dismiss() {
click(&mut visual, point(px(960.), px(540.)));
assert!(changes.borrow().is_empty());
}
#[test]
fn a_closed_dialog_is_inert() {
let (_cx, mut visual, changes) = dialog_window(false, false);
visual.simulate_keystrokes("escape");
click(&mut visual, point(px(100.), px(100.)));
assert!(changes.borrow().is_empty());
}
+18 -52
View File
@@ -1,7 +1,3 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Instant;
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, TestAppContext, VisualTestContext, Window, div,
@@ -13,12 +9,10 @@ use gpui_native_core::input::{Input, InputState};
struct FieldHost {
url: Entity<InputState>,
renders: Rc<RefCell<usize>>,
}
impl Render for FieldHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
*self.renders.borrow_mut() += 1;
let url_error = self
.url
.read(cx)
@@ -38,76 +32,48 @@ impl Render for FieldHost {
}
}
/// A field page in a real window, with the url input focused.
fn field_host() -> (
TestAppContext,
Entity<InputState>,
Rc<RefCell<usize>>,
VisualTestContext,
) {
/// A field page in a real window; the url input is focused unless
/// `focus` is false, which leaves the page truly idle.
fn field_host(focus: bool) -> (TestAppContext, Entity<InputState>, VisualTestContext) {
let cx = TestAppContext::single();
cx.update(init);
let (url, renders, window) = cx.update(|cx| {
let renders = Rc::new(RefCell::new(0));
let (url, window) = cx.update(|cx| {
let url = InputState::new(cx);
let url_for_host = url.clone();
let renders_for_host = renders.clone();
let window = cx
.open_window(gpui::WindowOptions::default(), |_, cx| {
cx.new(|_| FieldHost {
url: url_for_host,
renders: renders_for_host,
})
cx.new(|_| FieldHost { url: url_for_host })
})
.unwrap();
(url, renders, window)
(url, window)
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
let focus = url.read(cx).focus_handle();
window.focus(&focus, cx);
if focus {
let focus = url.read(cx).focus_handle();
window.focus(&focus, cx);
}
window.draw(cx).clear(cx);
});
(cx, url, renders, visual)
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
fn type_and_time(visual: &mut VisualTestContext, text: &str) -> std::time::Duration {
let started = Instant::now();
for letter in text.chars() {
visual.simulate_keystrokes(&letter.to_string());
draw(visual);
}
let elapsed = started.elapsed();
println!(
"{} keystrokes: {elapsed:?} ({:.2} ms per keystroke)",
text.chars().count(),
elapsed.as_secs_f64() / text.chars().count() as f64 * 1000.
);
elapsed
(cx, url, visual)
}
#[test]
fn an_idle_field_page_schedules_no_frames() {
let (_cx, _url, _renders, mut visual) = field_host();
let (_cx, _url, mut visual) = field_host(false);
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
"an idle field page must not request animation frames"
"an idle unfocused field page must not request animation frames"
);
}
#[test]
fn field_typing_frame_cost() {
let (_cx, _url, _renders, mut visual) = field_host();
let elapsed = type_and_time(&mut visual, "dsdsadsadadadada");
fn a_focused_field_page_schedules_frames_for_its_blink() {
let (_cx, _url, mut visual) = field_host(true);
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert!(
elapsed.as_millis() < 1000,
"typing 16 characters took {elapsed:?}"
frames > 0,
"the focused caret's blink needs frames to redraw at the blink cadence"
);
}
+190 -64
View File
@@ -3,12 +3,15 @@ use gpui::{
MouseUpEvent, ParentElement as _, Render, ScrollDelta, ScrollEvent, Styled as _,
TestAppContext, VisualTestContext, Window, div, point, px,
};
use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::common::Sizable as _;
use gpui_native_core::input::{
INPUT_CONTEXT, Input, InputBindings, InputState, InputStateEvent, Submit, SubmitOn,
bind_input_keys,
};
use gpui_native_theme::Theme;
use std::cell::RefCell;
use gpui_native_icons::IconRole;
use gpui_native_theme::{BORDER_WIDTH, Size, Theme};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;
@@ -266,42 +269,45 @@ fn read_only_refuses_edits_but_keeps_selection_and_copy() {
assert_eq!(clipboard, "lo");
// The caret is suppressed entirely while read-only.
let caret = cx.update(|cx| state.update(cx, |state, cx| state.caret_visible(true, cx)));
let caret = cx.update(|cx| state.update(cx, |state, _| state.caret_visible(true)));
assert!(!caret);
}
#[test]
fn caret_blinks_while_focused_and_holds_solid_while_typing() {
fn the_caret_visibility_is_pure_time_math_against_the_epoch() {
let (cx, state, mut visual) = input_window("", false);
focus(&mut visual, &state);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
visual.run_until_parked();
let caret = || cx.update(|cx| state.update(cx, |state, _| state.caret_visible(true)));
let caret = || cx.update(|cx| state.update(cx, |state, cx| state.caret_visible(true, cx)));
// The caret shows on focus, hides after one interval, and reappears
// after another.
assert!(caret());
cx.executor().advance_clock(Duration::from_millis(500));
visual.run_until_parked();
assert!(!caret());
cx.executor().advance_clock(Duration::from_millis(500));
visual.run_until_parked();
// Fresh focus starts a new epoch: the caret shows solid — the elapsed
// time since the epoch began is microseconds, far under one interval.
assert!(caret());
// Typing holds the caret solid and restarts the cycle.
// Typing restarts the epoch, so the caret stays solid through edits.
visual.simulate_keystrokes("a");
assert!(caret());
cx.executor().advance_clock(Duration::from_millis(500));
visual.run_until_parked();
assert!(!caret());
// An unfocused field reports no caret.
let caret_unfocused =
cx.update(|cx| state.update(cx, |state, cx| state.caret_visible(false, cx)));
assert!(!caret_unfocused);
// The blink cadence itself: hidden in the second half of the cycle.
let hidden = cx.update(|cx| {
state.update(cx, |state, _| {
state.caret_blink_visible_at(true, Duration::from_millis(700))
})
});
assert!(!hidden);
let visible = cx.update(|cx| {
state.update(cx, |state, _| {
state.caret_blink_visible_at(true, Duration::from_millis(300))
})
});
assert!(visible);
// An unfocused field reports no caret, at any point in the cycle.
let unfocused = cx.update(|cx| {
state.update(cx, |state, _| {
state.caret_blink_visible_at(false, Duration::from_millis(100))
})
});
assert!(!unfocused);
}
#[test]
@@ -459,15 +465,6 @@ fn disabled_input_ignores_typing_and_clicks() {
assert_eq!(value(&cx, &state), "");
}
#[test]
fn set_value_replaces_the_buffer() {
let (cx, state, mut visual) = input_window("", false);
visual.update(|window, cx| {
state.update(cx, |state, cx| state.set_value("preset", window, cx));
});
assert_eq!(value(&cx, &state), "preset");
}
/// Subscribes to `state`'s events, recording each variant into a sink that
/// lives for the rest of the test. The returned `Subscription` must stay
/// bound for the same lifetime — dropping it unsubscribes.
@@ -536,26 +533,6 @@ fn set_value_silent_updates_without_emitting() {
assert_eq!(count(&sink, &InputStateEvent::TextChanged), 0);
}
#[test]
fn focus_and_blur_emit_events() {
let (mut cx, state, mut visual) = input_window("", false);
let (sink, _subscription) = record_events(&mut cx, &state);
focus(&mut visual, &state);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
visual.run_until_parked();
assert_eq!(count(&sink, &InputStateEvent::Focused), 1);
visual.update(|window, cx| window.blur(cx));
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
visual.run_until_parked();
assert_eq!(count(&sink, &InputStateEvent::Blurred), 1);
}
#[test]
fn pasted_newlines_become_spaces() {
let (cx, state, mut visual) = input_window("", false);
@@ -568,15 +545,6 @@ fn pasted_newlines_become_spaces() {
assert_eq!(value(&cx, &state), "a bc");
}
#[test]
fn set_value_sanitizes_newlines() {
let (cx, state, mut visual) = input_window("", false);
visual.update(|window, cx| {
state.update(cx, |state, cx| state.set_value("a\nb", window, cx));
});
assert_eq!(value(&cx, &state), "a b");
}
#[test]
fn enter_emits_submitted() {
let (mut cx, state, mut visual) = input_window("draft", false);
@@ -763,6 +731,36 @@ fn the_reveal_toggle_flips_masking() {
assert!(!revealed, "the toggle should mask the field again");
}
/// The reveal pill sits with equal insets on its three free sides; the
/// small control metric must stay whole-pixel or snapping skews it.
#[test]
fn the_reveal_pill_insets_equally() {
let (cx, _state, mut visual) = reveal_window();
let field = visual.debug_bounds("input-field").expect("field missing");
let pill = visual
.debug_bounds("input-reveal-button")
.expect("reveal pill missing");
cx.update(|cx| {
let theme = Theme::global(cx);
let small = theme.sizes.resolve(Size::Small);
let border = BORDER_WIDTH;
let docked = small.control_height + border * 2.0;
let inset = ((field.size.height - border * 2.0 - docked) / 2.0).max(px(0.));
let top_gap = pill.top() - (field.top() + border);
let bottom_gap = (field.bottom() - border) - pill.bottom();
let right_gap = (field.right() - border) - pill.right();
assert!(
(top_gap - inset).abs() < px(0.01)
&& (bottom_gap - inset).abs() < px(0.01)
&& (right_gap - inset).abs() < px(0.01),
"pill gaps top {top_gap:?} bottom {bottom_gap:?} right {right_gap:?} vs inset {inset:?}"
);
});
}
#[test]
fn the_caret_can_rest_on_a_line_break() {
let (cx, state, mut visual) = multiline_window("ab\ncdef");
@@ -906,3 +904,131 @@ fn vertical_scroll_keeps_the_caret_in_view() {
.unwrap_or_default();
assert!(first_row_top < px(0.), "first row top: {first_row_top:?}");
}
struct EdgeHarness {
state: Entity<InputState>,
clicked: Rc<Cell<bool>>,
}
impl Render for EdgeHarness {
fn render(
&mut self,
_window: &mut Window,
_cx: &mut gpui::Context<Self>,
) -> impl gpui::IntoElement {
let clicked = self.clicked.clone();
div().w(px(400.)).p_4().child(
Input::new("edge-input", self.state.clone())
.placeholder("Search")
.prefix(
Button::new("edge-input-prefix-button")
.icon(IconRole::Search)
.variant(ButtonVariant::Ghost)
.small(),
)
.suffix(
Button::new("edge-input-suffix-button")
.debug_selector(|| "edge-suffix-button".to_string())
.icon(IconRole::Plus)
.variant(ButtonVariant::Ghost)
.small()
.on_click(move |_, _, _| clicked.set(true)),
),
)
}
}
fn edge_input_window(
initial: &str,
) -> (
TestAppContext,
Entity<InputState>,
VisualTestContext,
Rc<Cell<bool>>,
) {
let clicked = Rc::new(Cell::new(false));
let clicked_for_window = clicked.clone();
let mut cx = TestAppContext::single();
cx.update(|cx| {
Theme::init(cx);
bind_input_keys(cx, InputBindings::default());
});
let state = cx.update(|cx| InputState::new_with_text(initial, cx));
let state_for_window = state.clone();
let window = cx.add_window(move |_, _| EdgeHarness {
state: state_for_window,
clicked: clicked_for_window,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, state, visual, clicked)
}
/// Prefix and suffix dock flush inside the field, prefix leading, and a
/// small button in a zone centers with equal insets like the reveal pill.
#[test]
fn prefix_and_suffix_dock_inside_the_field() {
let (cx, _state, mut visual, _clicked) = edge_input_window("abc");
let field = visual.debug_bounds("input-field").expect("field missing");
let prefix = visual
.debug_bounds("input-prefix")
.expect("prefix zone missing");
let suffix = visual
.debug_bounds("input-suffix")
.expect("suffix zone missing");
let pill = visual
.debug_bounds("edge-suffix-button")
.expect("suffix button missing");
assert!(prefix.left() >= field.left());
assert!(prefix.right() <= suffix.left());
assert!(suffix.right() <= field.right());
cx.update(|cx| {
let theme = Theme::global(cx);
let small = theme.sizes.resolve(Size::Small);
let border = BORDER_WIDTH;
let docked = small.control_height + border * 2.0;
let inset = ((field.size.height - border * 2.0 - docked) / 2.0).max(px(0.));
let top_gap = pill.top() - (field.top() + border);
let bottom_gap = (field.bottom() - border) - pill.bottom();
let right_gap = (field.right() - border) - pill.right();
assert!(
(top_gap - inset).abs() < px(0.01)
&& (bottom_gap - inset).abs() < px(0.01)
&& (right_gap - inset).abs() < px(0.01),
"suffix pill gaps top {top_gap:?} bottom {bottom_gap:?} right {right_gap:?} vs inset {inset:?}"
);
});
}
/// A click on a docked control activates it without running the field's
/// caret handler underneath.
#[test]
fn a_suffix_click_activates_without_focusing_the_field() {
let (cx, state, mut visual, clicked) = edge_input_window("abc");
let bounds = visual
.debug_bounds("input-suffix")
.expect("suffix zone missing");
click(
&mut visual,
point(
bounds.left() + bounds.size.width / 2.0,
bounds.top() + bounds.size.height / 2.0,
),
);
assert!(clicked.get(), "the suffix button should activate");
let focused = visual.update(|window, cx| state.read(cx).focus_handle().is_focused(window));
assert!(!focused, "the suffix click must not focus the field");
// The zone must not swallow text interaction either.
focus(&mut visual, &state);
visual.simulate_keystrokes("x");
assert_eq!(value(&cx, &state), "abcx");
}
+22 -17
View File
@@ -112,6 +112,28 @@ fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
}
/// Every action row renders at the platform's stated menu row height,
/// whatever its content — the metric is the whole row, not a floor under
/// padding. Item 1 of the harness menu is a separator, so it is skipped.
#[test]
fn rows_render_at_the_stated_menu_row_height() {
let (cx, mut visual, _window, _changes, _activated) = menu_window(true);
let stated = cx.update(|cx| Theme::global(cx).sizes.medium.menu_item_height);
for index in [0, 2, 3, 4] {
let selector: &'static str = Box::leak(format!("menu-item-{index}").into_boxed_str());
let row = visual
.debug_bounds(selector)
.unwrap_or_else(|| panic!("row {index} should have been laid out"));
// Painted bounds are snapped to device pixels; allow half a pixel.
assert!(
(row.size.height - stated).abs() <= px(0.5),
"row {index} is {:?} tall, stated menu row height is {stated:?}",
row.size.height
);
}
}
#[test]
fn arrow_navigation_skips_separators_and_disabled_items() {
let (_cx, mut visual, _window, changes, activated) = menu_window(true);
@@ -163,14 +185,6 @@ fn clicking_outside_dismisses_and_swallows_the_click() {
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn clicking_the_trigger_toggles() {
let (_cx, mut visual, _window, changes, _activated) = menu_window(false);
click(&mut visual, point(px(10.), px(16.)));
assert_eq!(*changes.borrow(), vec![true]);
}
#[test]
fn clicking_an_item_activates_and_closes() {
let (_cx, mut visual, _window, changes, activated) = menu_window(true);
@@ -180,12 +194,3 @@ fn clicking_an_item_activates_and_closes() {
assert_eq!(*activated.borrow(), vec!["cut"]);
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn enter_activates_the_selected_item_and_closes() {
let (_cx, mut visual, _window, changes, activated) = menu_window(true);
visual.simulate_keystrokes("enter");
assert_eq!(*activated.borrow(), vec!["cut"]);
assert_eq!(*changes.borrow(), vec![false]);
}
+92 -35
View File
@@ -1,8 +1,9 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, IntoElement, Modifiers, MouseButton, ParentElement as _, Render, Styled as _,
TestAppContext, VisualTestContext, Window, WindowHandle, div, point, px, rgba,
Context, InteractiveElement as _, IntoElement, Modifiers, MouseButton, ParentElement as _,
Render, StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext,
Window, WindowHandle, div, point, px, rgba,
};
use gpui_native_core::popover::Popover;
use gpui_native_theme::Theme;
@@ -10,37 +11,54 @@ use gpui_native_theme::Theme;
struct Harness {
open: bool,
changes: Rc<RefCell<Vec<bool>>>,
target_clicks: Rc<RefCell<usize>>,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let target_clicks = self.target_clicks.clone();
let view = cx.entity();
div().size_full().child(
Popover::new("test-popover")
.open(self.open)
.on_change(move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.open = next;
cx.notify();
});
})
.trigger(|_, _| {
div()
.size_full()
.child(
div().absolute().left(px(400.)).top(px(300.)).child(
div()
.w(px(100.))
.h(px(32.))
.id("popover-target")
.size(px(40.))
.bg(rgba(0x000000ff))
.into_any_element()
})
.content(|_, _| {
div()
.w(px(200.))
.h(px(80.))
.child("Popover content")
.into_any_element()
}),
)
.on_click(move |_, _, cx| {
*target_clicks.borrow_mut() += 1;
cx.stop_propagation();
}),
),
)
.child(
Popover::new("test-popover")
.open(self.open)
.on_change(move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.open = next;
cx.notify();
});
})
.trigger(|_, _| {
div()
.debug_selector(|| "popover-trigger".to_string())
.w(px(100.))
.h(px(32.))
.bg(rgba(0x000000ff))
.into_any_element()
})
.content(|_, _| {
div()
.w(px(200.))
.h(px(80.))
.child("Popover content")
.into_any_element()
}),
)
}
}
@@ -48,27 +66,31 @@ impl Render for Harness {
/// hangs below it around `(0..200, 36..116)`, so clicks at `(10, 16)` land
/// on the trigger, `(100, 70)` on the panel, and anything past `(300, 300)`
/// is outside both.
fn popover_window(
open: bool,
) -> (
type PopoverWindow = (
TestAppContext,
VisualTestContext,
WindowHandle<Harness>,
Rc<RefCell<Vec<bool>>>,
) {
Rc<RefCell<usize>>,
);
fn popover_window(open: bool) -> PopoverWindow {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let target_clicks = Rc::new(RefCell::new(0));
let harness_clicks = target_clicks.clone();
let window = cx.add_window(move |_, _| Harness {
open,
changes: harness_changes,
target_clicks: harness_clicks,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, window, changes)
(cx, visual, window, changes, target_clicks)
}
fn draw(visual: &mut VisualTestContext) {
@@ -84,7 +106,7 @@ fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
#[test]
fn clicking_outside_dismisses_and_reports_closed() {
let (_cx, mut visual, _window, changes) = popover_window(true);
let (_cx, mut visual, _window, changes, _clicks) = popover_window(true);
click(&mut visual, point(px(600.), px(600.)));
assert_eq!(*changes.borrow(), vec![false]);
@@ -98,7 +120,7 @@ fn clicking_outside_dismisses_and_reports_closed() {
#[test]
fn clicking_the_trigger_toggles_and_clicking_the_panel_does_nothing() {
let (_cx, mut visual, _window, changes) = popover_window(true);
let (_cx, mut visual, _window, changes, _clicks) = popover_window(true);
// On the open panel's trigger: toggles closed.
click(&mut visual, point(px(10.), px(16.)));
@@ -111,7 +133,7 @@ fn clicking_the_trigger_toggles_and_clicking_the_panel_does_nothing() {
#[test]
fn clicking_the_trigger_opens_a_closed_popover() {
let (_cx, mut visual, _window, changes) = popover_window(false);
let (_cx, mut visual, _window, changes, _clicks) = popover_window(false);
click(&mut visual, point(px(10.), px(16.)));
assert_eq!(*changes.borrow(), vec![true]);
@@ -119,7 +141,7 @@ fn clicking_the_trigger_opens_a_closed_popover() {
#[test]
fn escape_dismisses_while_the_panel_holds_focus() {
let (_cx, mut visual, _window, changes) = popover_window(true);
let (_cx, mut visual, _window, changes, _clicks) = popover_window(true);
draw(&mut visual);
// The panel claims focus on open, so escape reaches its key listener.
@@ -134,7 +156,7 @@ fn escape_dismisses_while_the_panel_holds_focus() {
#[test]
fn the_controlled_loop_reopens_from_the_app_side() {
let (mut cx, mut visual, window, changes) = popover_window(true);
let (mut cx, mut visual, window, changes, _clicks) = popover_window(true);
// Dismiss once.
click(&mut visual, point(px(600.), px(600.)));
@@ -155,3 +177,38 @@ fn the_controlled_loop_reopens_from_the_app_side() {
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![false, false]);
}
/// Clicking another control while the popover is open dismisses it and still
/// acts on that control: dismissing does not claim the event.
#[test]
fn clicking_another_control_dismisses_and_reaches_it() {
let (_cx, mut visual, _window, changes, clicks) = popover_window(true);
click(&mut visual, point(px(420.), px(320.)));
assert_eq!(*changes.borrow(), vec![false]);
assert_eq!(*clicks.borrow(), 1);
}
/// The panel hangs one spacing unit below the trigger: the anchor gap is
/// theme-owned, and rides the anchored element so the window-edge clamp
/// stays intact.
#[test]
fn the_panel_hangs_one_spacing_unit_below_the_trigger() {
let (cx, mut visual, _window, _changes, _clicks) = popover_window(true);
let trigger = visual
.debug_bounds("popover-trigger")
.expect("trigger rendered");
let panel = visual
.debug_bounds("popover-panel")
.expect("panel rendered");
let expected = cx.update(|cx| Theme::global(cx).spacing.unit);
let gap = panel.top() - trigger.bottom();
// Painted bounds are snapped to device pixels; allow half a pixel.
assert!(
(gap - expected).abs() <= px(0.5),
"the anchor gap is {gap:?}, expected {expected:?}"
);
}
-36
View File
@@ -1,36 +0,0 @@
use gpui::{ParentElement as _, Render, Styled as _, TestAppContext, Window, div};
use gpui_native_core::progress::Progress;
use gpui_native_theme::Theme;
struct Harness;
impl Render for Harness {
fn render(
&mut self,
_window: &mut Window,
_cx: &mut gpui::Context<Self>,
) -> impl gpui::IntoElement {
div()
.size_full()
.flex()
.flex_col()
.gap_2()
.child(Progress::new("test-progress", 0.6).accessibility_label("Upload"))
.child(
Progress::new("test-progress-indeterminate", 0.0)
.indeterminate(true)
.accessibility_label("Working"),
)
}
}
#[gpui::test]
fn determinate_and_indeterminate_bars_draw_headlessly(cx: &mut TestAppContext) {
cx.update(Theme::init);
let (view, visual) = cx.add_window_view(|_, _| Harness);
let _ = view;
visual.run_until_parked();
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
-7
View File
@@ -88,13 +88,6 @@ fn the_content_starts_unscrolled_and_horizontal_axes_scroll_x() {
assert_eq!(handle.offset().x, px(0.));
}
#[test]
fn the_thumb_paints_when_the_content_overflows() {
let (_cx, _visual, handle) = scroll_area_window(30);
// 30 rows × 20px in a 200px viewport: the thumb has something to report.
assert!(handle.max_offset().y > px(0.));
}
/// The gallery's exact shell: a window-filling root, a window-filling scroll
/// area over padded flex-column content that towers past the viewport.
struct GalleryShell {
-25
View File
@@ -121,28 +121,3 @@ fn arrows_move_the_selection_when_the_strip_has_focus() {
vec![Filter::Popular, Filter::Recent, Filter::All, Filter::Recent]
);
}
/// The selected plate exists after a choice and settles on the chosen
/// segment's slot; without it the active background disappears entirely.
#[test]
fn the_plate_settles_on_the_chosen_segment() {
let (_cx, mut visual, changes) = filter_window();
click(&mut visual, point(px(70.), px(27.)));
assert_eq!(*changes.borrow(), vec![Filter::Popular]);
// Let the spring settle in real time (it steps on Instant::now()), then
// check the plate landed in Popular's slot (~58..124).
std::thread::sleep(std::time::Duration::from_millis(600));
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
let plate = visual
.debug_bounds("segmented-plate")
.expect("plate missing");
assert!(
plate.left() >= px(44.) && plate.left() <= px(94.),
"plate settled at x {:?}",
plate.origin
);
}
+81 -3
View File
@@ -1,11 +1,12 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, IntoElement, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
Context, Entity, IntoElement, MouseButton, ParentElement as _, Render, Styled as _,
TestAppContext, VisualTestContext, Window, div, point, px,
};
use gpui_native_core::input::{Input, InputState};
use gpui_native_core::select::Select;
use gpui_native_theme::Theme;
use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, Theme};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Strategy {
@@ -200,3 +201,80 @@ fn two_selects_keep_their_popups_independent() {
assert_eq!(*first_changes.borrow(), vec![]);
assert_eq!(*second_changes.borrow(), vec![Some(Strategy::Curated)]);
}
#[test]
fn a_click_outside_closes_the_popup() {
let (_cx, mut visual, changes) = select_window();
click(&mut visual, point(px(100.), px(31.)));
draw(&mut visual);
click(&mut visual, point(px(100.), px(300.)));
draw(&mut visual);
// The popup held keyboard focus while open; a keystroke after the outside
// click answers nothing if the popup really closed.
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*changes.borrow(), Vec::<Option<Strategy>>::new());
}
/// Clicking another control while the popup is open dismisses it and still
/// acts on the control: dismissing does not claim the event.
#[test]
fn a_click_on_another_control_dismisses_and_reaches_it() {
let (_cx, mut visual, first_changes, second_changes) = pair_window();
click(&mut visual, point(px(100.), px(31.)));
draw(&mut visual);
// The second select's trigger, below the first — at x=300, past the first
// popup's 182px-wide panel: this click must close the first popup AND open
// the second.
click(&mut visual, point(px(300.), px(69.)));
draw(&mut visual);
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*first_changes.borrow(), Vec::<Option<Strategy>>::new());
assert_eq!(*second_changes.borrow(), vec![Some(Strategy::Curated)]);
}
struct HeightsHarness {
state: Entity<InputState>,
}
impl Render for HeightsHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.gap_4()
.child(Select::new("heights").options(STRATEGIES))
.child(Input::new("heights-field", self.state.clone()))
}
}
/// The trigger renders at the same height as the input field: the stated
/// metric plus the always-painted hairline border, whatever the platform.
#[test]
fn the_trigger_matches_the_input_height() {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let state = cx.update(InputState::new);
let state_for_window = state.clone();
let window = cx.add_window(move |_, _| HeightsHarness {
state: state_for_window,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
draw(&mut visual);
let trigger = visual
.debug_bounds("select-trigger")
.expect("trigger rendered");
let field = visual.debug_bounds("input-field").expect("input rendered");
// Snapped bounds: allow half a pixel.
assert!((trigger.size.height - field.size.height).abs() <= px(0.5));
let expected = cx.update(|cx| cx.theme().sizes.medium.input_height) + BORDER_WIDTH * 2.0;
assert!((trigger.size.height - expected).abs() <= px(0.5));
}
+31 -11
View File
@@ -67,25 +67,45 @@ fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_up(position, MouseButton::Left, gpui::Modifiers::default());
}
/// The trigger band is `16..46`; the panel hangs 4 px below it with a 4 px
/// inner padding, so the three rows ride `~58..90`, `~90..122`, `~122..154`.
/// Every option must answer a pointer press — a popup that clips its last
/// item never does.
/// The three option rows must answer a pointer press wherever they were laid
/// out — a popup that clips its last item never does. Row positions come from
/// the rendered bounds, so the stated menu row metric can change freely.
#[test]
fn every_option_row_answers_the_pointer() {
let (_cx, mut visual, changes) = level_window();
let expected = [
(px(74.), Level::Low),
(px(106.), Level::Mid),
(px(138.), Level::High),
];
for (y, value) in expected {
// Open once to measure where the rows were actually drawn.
click(&mut visual, point(px(100.), px(31.)));
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
let centers: Vec<gpui::Point<gpui::Pixels>> = (0..3)
.map(|index| {
let selector: &'static str = Box::leak(format!("menu-item-{index}").into_boxed_str());
let row = visual
.debug_bounds(selector)
.unwrap_or_else(|| panic!("row {index} should have been laid out"));
point(
row.left() + row.size.width / 2.0,
row.top() + row.size.height / 2.0,
)
})
.collect();
// Close again; each iteration below opens the popup fresh.
click(&mut visual, point(px(100.), px(31.)));
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
let expected = [(Level::Low, 0), (Level::Mid, 1), (Level::High, 2)];
for (value, index) in expected {
// Choosing the previous row closed the popup; reopen it.
click(&mut visual, point(px(100.), px(31.)));
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
click(&mut visual, point(px(100.), y));
click(&mut visual, centers[index]);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
-13
View File
@@ -45,16 +45,3 @@ fn the_dot_is_half_the_icon_size() {
dot.size
);
}
#[test]
fn the_dot_keeps_a_square_footprint() {
let (cx, window) = dot_window();
let mut visual = VisualTestContext::from_window(window, &cx);
let dot = visual.debug_bounds("test-dot").expect("dot missing");
assert!(
(dot.size.width - dot.size.height).abs() <= gpui::px(0.5),
"the dot must stay circular: {:?}",
dot.size
);
}
+24
View File
@@ -83,6 +83,30 @@ fn disabled_switch_does_not_report_changes() {
assert!(changes.borrow().is_empty());
}
/// The track renders at the platform's stated switch dims, not the generic
/// control height — the stated metric is the whole chrome.
#[test]
fn track_renders_at_the_stated_switch_dims() {
let (mut cx, _window, _changes) = switch_window(false, false);
let (width, height) = cx.update(|_window, cx| {
let metrics = Theme::global(cx).sizes.medium;
(metrics.switch_width, metrics.switch_height)
});
let track = cx
.debug_bounds("test-switch-track")
.expect("the switch track should have been laid out");
assert!(
(track.size.width - width).abs() <= px(0.5),
"track is {:?} wide, stated switch width is {width:?}",
track.size.width
);
assert!(
(track.size.height - height).abs() <= px(0.5),
"track is {:?} tall, stated switch height is {height:?}",
track.size.height
);
}
#[test]
fn enter_and_space_report_the_next_value_while_focused() {
let (mut cx, window, changes) = switch_window(false, false);
+105 -12
View File
@@ -1,17 +1,18 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, InteractiveElement as _, IntoElement, Modifiers, MouseMoveEvent, ParentElement as _,
Render, StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext,
Window, div, point, px,
Window, WindowHandle, canvas, div, point, px,
};
use gpui_native_core::button::Button;
use gpui_native_core::tooltip::Tooltip;
use gpui_native_theme::Theme;
use gpui_native_utils::record_anchor_bounds;
/// Hover target at the top-left with a tooltip whose builder records every
/// invocation.
/// invocation. The tooltip anchors to the target itself, so it hangs below
/// the target's bottom edge instead of at the cursor.
struct Harness {
calls: Rc<RefCell<Vec<&'static str>>>,
}
@@ -21,20 +22,26 @@ impl Render for Harness {
let calls = self.calls.clone();
let target = div()
.id("hover-target")
.debug_selector(|| "hover-target".to_string())
.w(px(100.))
.h(px(40.))
.bg(gpui::black())
.tooltip(move |_, cx| {
.child(
canvas(record_anchor_bounds("hover-target".into()), |_, _, _, _| {})
.absolute()
.inset_0(),
)
.tooltip(move |window, cx| {
calls.borrow_mut().push("target");
Tooltip::new("Target tooltip", cx).into()
Tooltip::anchored("Target tooltip", "hover-target")(window, cx)
});
let button_calls = self.calls.clone();
let button = Button::new("hover-button")
.label("Hover me")
.tooltip(move |_, cx| {
.tooltip(move |window, cx| {
button_calls.borrow_mut().push("button");
Tooltip::new("Button tooltip", cx).into()
Tooltip::anchored("Button tooltip", "hover-button")(window, cx)
});
div()
@@ -80,6 +87,40 @@ fn draw(visual: &mut VisualTestContext) {
});
}
struct LowHarness;
impl Render for LowHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
// The target is pinned to the window's bottom edge: the space below it
// is nil, so the tooltip must flip above the parent.
div().size_full().flex().flex_col().justify_end().child(
div()
.id("low-target")
.debug_selector(|| "low-target".to_string())
.w(px(100.))
.h(px(40.))
.bg(gpui::black())
.child(
canvas(record_anchor_bounds("low-target".into()), |_, _, _, _| {})
.absolute()
.inset_0(),
)
.tooltip(Tooltip::anchored("Low tooltip", "low-target")),
)
}
}
fn low_tooltip_window() -> (TestAppContext, VisualTestContext, WindowHandle<LowHarness>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let window = cx.add_window(move |_, _| LowHarness);
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, window)
}
#[test]
fn hovering_the_target_deploys_the_tooltip_after_the_delay() {
let (cx, mut visual, calls) = tooltip_window();
@@ -109,12 +150,64 @@ fn hovering_elsewhere_deploys_nothing() {
assert!(calls.borrow().is_empty());
}
/// An anchored tooltip hangs below the hovered parent's bottom edge with the
/// spacing gap: it never covers the parent, wherever the cursor is inside it.
#[test]
fn the_button_passthrough_deploys_the_tooltip() {
let (cx, mut visual, calls) = tooltip_window();
hover(&mut visual, point(px(50.), px(100.)));
fn the_anchored_panel_hangs_below_the_parent_without_overlapping() {
let (cx, mut visual, _calls) = tooltip_window();
hover(&mut visual, point(px(50.), px(20.)));
cx.executor().advance_clock(SHOW_DELAY);
visual.run_until_parked();
draw(&mut visual);
assert_eq!(*calls.borrow(), vec!["button"]);
let target = visual
.debug_bounds("hover-target")
.expect("target laid out");
let panel = visual
.debug_bounds("tooltip-panel")
.expect("panel rendered");
let unit = cx.update(|cx| Theme::global(cx).spacing.unit);
assert!(
(panel.top() - target.bottom() - unit).abs() <= px(0.5),
"the panel hangs {gap:?} below the target",
gap = panel.top() - target.bottom()
);
assert!((panel.left() - target.left()).abs() <= px(0.5));
assert!(
panel.top() >= target.bottom(),
"the panel must never overlap the hovered parent"
);
}
/// A parent pinned to the window's bottom edge leaves no room below: the
/// panel flips above the parent's top edge instead.
#[test]
fn an_anchored_tooltip_flips_above_a_low_parent() {
let (mut cx, mut visual, window) = low_tooltip_window();
let window_height = window
.update(&mut cx, |_, window, _cx| window.viewport_size().height)
.expect("window alive");
hover(&mut visual, point(px(50.), window_height - px(20.)));
cx.executor().advance_clock(SHOW_DELAY);
visual.run_until_parked();
draw(&mut visual);
let target = visual.debug_bounds("low-target").expect("target laid out");
let panel = visual
.debug_bounds("tooltip-panel")
.expect("panel rendered");
// The flip hangs the panel above the parent's top edge.
assert!(
panel.bottom() <= target.top(),
"the panel must not cover the parent: panel bottom {:?}, parent top {:?}",
panel.bottom(),
target.top()
);
assert!(
panel.top() >= px(0.),
"the flipped panel must stay inside the window"
);
}