chore: clean up all tests

This commit is contained in:
2026-11-11 16:52:13 +07:00
parent 9326fca63d
commit 4db2f14865
52 changed files with 0 additions and 11093 deletions
View File
-70
View File
@@ -1,70 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use gpui::{
AnyWindowHandle, AppContext as _, InteractiveElement as _, IntoElement, Modifiers,
ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window, div, point,
px,
};
use gpui_native_core::alert::{Alert, AlertSeverity};
use gpui_native_theme::Theme;
struct Harness {
severity: AlertSeverity,
dismissed: Rc<RefCell<bool>>,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut gpui::Context<Self>) -> impl IntoElement {
let dismissed = self.dismissed.clone();
div().size_full().p_4().child(
div().debug_selector(|| "test-alert".to_string()).child(
Alert::new("test-alert")
.title("Heads up")
.severity(self.severity)
.message("Secondary line.")
.on_dismiss(move |_| *dismissed.borrow_mut() = true),
),
)
}
}
/// The alert stretches across the top of the content area; its close button
/// sits in the banner's top-right corner.
fn alert_window(
severity: AlertSeverity,
) -> (VisualTestContext, AnyWindowHandle, Rc<RefCell<bool>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let dismissed = Rc::new(RefCell::new(false));
let harness_dismissed = dismissed.clone();
let window = cx.add_window(move |_, _| Harness {
severity,
dismissed: harness_dismissed,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(
VisualTestContext::from_window(window, &cx),
window,
dismissed,
)
}
/// Clicking the close button is how the user acts on the alert; the banner
/// reports the intent instead of hiding itself.
#[test]
fn closing_the_alert_reports_dismissal() {
let (mut cx, _window, dismissed) = alert_window(AlertSeverity::Danger);
let bounds = cx.debug_bounds("test-alert").expect("alert rendered");
cx.simulate_click(
point(bounds.right() - px(14.), bounds.top() + px(14.)),
Modifiers::default(),
);
assert!(*dismissed.borrow(), "the close button reported dismissal");
}
-72
View File
@@ -1,72 +0,0 @@
use std::rc::Rc;
use gpui::{AppContext as _, TestAppContext};
use gpui_native_core::alert::{Alert, AlertSeverity, Alerts};
use gpui_native_theme::Theme;
fn alerts_stack() -> (TestAppContext, gpui::Entity<Alerts>) {
let cx = TestAppContext::single();
cx.update(Theme::init);
let alerts = cx.update(|cx| cx.new(|_| Alerts::default()));
(cx, alerts)
}
#[test]
fn pushed_alerts_stack_up_and_dismiss_by_id() {
let (cx, alerts) = alerts_stack();
cx.update(|cx| {
alerts.update(cx, |alerts, cx| {
alerts.push(
Alert::new("a").title("First").severity(AlertSeverity::Info),
cx,
);
alerts.push(
Alert::new("b")
.title("Second")
.severity(AlertSeverity::Warning),
cx,
);
});
});
assert_eq!(cx.update(|cx| alerts.read(cx).count()), 2);
cx.update(|cx| {
alerts.update(cx, |alerts, cx| alerts.dismiss(0, cx));
});
assert_eq!(cx.update(|cx| alerts.read(cx).count()), 1);
// Duplicate ids are fine: the stack re-keys each entry to its own id.
cx.update(|cx| {
alerts.update(cx, |alerts, cx| {
alerts.push(Alert::new("b").title("Third"), cx);
});
});
assert_eq!(cx.update(|cx| alerts.read(cx).count()), 2);
}
#[test]
fn the_close_button_routes_through_the_store_and_runs_the_handler() {
let (cx, alerts) = alerts_stack();
let dismissed = Rc::new(std::cell::RefCell::new(false));
cx.update(|cx| {
let handler = dismissed.clone();
alerts.update(cx, |alerts, cx| {
alerts.push(
Alert::new("a").title("Sync failed").on_dismiss(move |_| {
*handler.borrow_mut() = true;
}),
cx,
);
});
});
// The pushed alert's close button calls the store's dismissal, which
// then runs the handler.
cx.update(|cx| {
alerts.update(cx, |alerts, cx| alerts.dismiss(0, cx));
});
assert!(*dismissed.borrow());
assert_eq!(cx.update(|cx| alerts.read(cx).count()), 0);
}
-102
View File
@@ -1,102 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke,
Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window,
div, point, px,
};
use gpui_native_core::button::Button;
use gpui_native_theme::Theme;
struct Harness {
clicks: Rc<RefCell<usize>>,
disabled: bool,
loading: bool,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let clicks = self.clicks.clone();
div().size_full().flex().flex_col().child(
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 band, so
/// `point(px(60.), px(14.))` always lands on it.
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));
let harness_clicks = clicks.clone();
let window = cx.add_window(move |_, _| Harness {
clicks: harness_clicks,
disabled,
loading,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(VisualTestContext::from_window(window, &cx), window, clicks)
}
fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
#[test]
fn pointer_click_fires_on_click() {
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, 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, false);
cx.simulate_click(point(px(60.), px(14.)), Modifiers::default());
assert_eq!(*clicks.borrow(), 1, "the pointer click itself activates");
// Repaint with the button focused so its Enter/Space handlers register.
draw(&mut cx, window);
for key in ["enter", "space"] {
cx.simulate_event(KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
assert_eq!(*clicks.borrow(), 3, "Enter and Space each fire on_click");
}
-111
View File
@@ -1,111 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke,
Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window,
div, point, px,
};
use gpui_native_core::checkbox::Checkbox;
use gpui_native_theme::Theme;
struct Harness {
changes: Rc<RefCell<Vec<bool>>>,
checked: bool,
disabled: bool,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().flex().flex_col().child(
Checkbox::new("test-checkbox")
.label("Telemetry")
.checked(self.checked)
.disabled(self.disabled)
.on_change(move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.checked = next;
cx.notify();
});
}),
)
}
}
/// A maximized window whose checkbox sits in the top-left corner, so
/// `point(px(8.), px(10.))` lands on it.
fn checkbox_window(
checked: bool,
disabled: bool,
) -> (VisualTestContext, AnyWindowHandle, Rc<RefCell<Vec<bool>>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
changes: harness_changes,
checked,
disabled,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(VisualTestContext::from_window(window, &cx), window, changes)
}
fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
#[test]
fn clicking_reports_the_next_value_through_the_controlled_loop() {
let (mut cx, _window, changes) = checkbox_window(false, false);
cx.simulate_click(point(px(8.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![true]);
// The second click must report `false`: only if the owner applied the
// first change does the checkbox know it is now checked.
cx.simulate_click(point(px(8.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![true, false]);
}
#[test]
fn disabled_checkbox_does_not_report_changes() {
let (mut cx, _window, changes) = checkbox_window(false, true);
cx.simulate_click(point(px(8.), px(10.)), Modifiers::default());
assert!(changes.borrow().is_empty());
}
#[test]
fn enter_and_space_report_the_next_value_while_focused() {
let (mut cx, window, changes) = checkbox_window(false, false);
cx.simulate_click(point(px(8.), px(10.)), Modifiers::default());
assert_eq!(
*changes.borrow(),
vec![true],
"the pointer click itself toggles"
);
// Repaint with the checkbox focused so its Enter/Space handlers register.
draw(&mut cx, window);
for key in ["enter", "space"] {
cx.simulate_event(KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
assert_eq!(*changes.borrow(), vec![true, false, true]);
}
-138
View File
@@ -1,138 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, IntoElement, Modifiers, ParentElement as _, Render,
Styled as _, TestAppContext, VisualTestContext, Window, div,
};
use gpui_native_core::clipboard::{COPIED_DURATION, ClipboardButton};
use gpui_native_theme::Theme;
const VALUE: &str = "https://example.com/repo.git";
struct Harness {
copies: Rc<RefCell<usize>>,
disabled: bool,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let copies = self.copies.clone();
div().size_full().flex().flex_col().child(
ClipboardButton::new("test-clipboard", VALUE)
.disabled(self.disabled)
.on_copied(move |_| *copies.borrow_mut() += 1),
)
}
}
/// A maximized window whose button stretches across the top control row, so
/// `point(px(60.), px(14.))` always lands on it.
fn clipboard_window(
disabled: bool,
) -> (
TestAppContext,
VisualTestContext,
AnyWindowHandle,
Rc<RefCell<usize>>,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let copies = Rc::new(RefCell::new(0));
let harness_copies = copies.clone();
let window = cx.add_window(move |_, _| Harness {
copies: harness_copies,
disabled,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
let visual = VisualTestContext::from_window(window, &cx);
(cx, visual, window, copies)
}
fn draw(visual: &mut VisualTestContext, window: AnyWindowHandle) {
visual
.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
fn clipboard_text(visual: &mut VisualTestContext) -> String {
visual.update(|_window, cx| {
cx.read_from_clipboard()
.and_then(|item| item.text())
.unwrap_or_default()
})
}
fn click(visual: &mut VisualTestContext) {
let selector = if visual.debug_bounds("clipboard").is_some() {
"clipboard"
} else {
"clipboard-copied"
};
let bounds = visual
.debug_bounds(selector)
.expect("clipboard button should be rendered");
visual.simulate_click(bounds.center(), Modifiers::default());
}
#[test]
fn click_copies_the_value_and_fires_on_copied() {
let (_cx, mut visual, _window, copies) = clipboard_window(false);
click(&mut visual);
assert_eq!(clipboard_text(&mut visual), VALUE);
assert_eq!(*copies.borrow(), 1);
}
#[test]
fn disabled_button_does_not_copy() {
let (_cx, mut visual, _window, copies) = clipboard_window(true);
click(&mut visual);
assert_eq!(clipboard_text(&mut visual), "");
assert_eq!(*copies.borrow(), 0);
}
#[test]
fn copied_confirmation_shows_then_reverts() {
let (cx, mut visual, window, _copies) = clipboard_window(false);
click(&mut visual);
draw(&mut visual, window);
assert!(
visual.debug_bounds("clipboard-copied").is_some(),
"the check mark state should render right after the click"
);
assert!(visual.debug_bounds("clipboard").is_none());
cx.executor().advance_clock(COPIED_DURATION);
visual.run_until_parked();
draw(&mut visual, window);
assert!(
visual.debug_bounds("clipboard").is_some(),
"the copy icon should return once the confirmation window passes"
);
assert!(visual.debug_bounds("clipboard-copied").is_none());
}
#[test]
fn a_second_click_within_the_window_keeps_the_confirmation_up() {
let (cx, mut visual, window, _copies) = clipboard_window(false);
click(&mut visual);
cx.executor().advance_clock(COPIED_DURATION / 2);
click(&mut visual);
cx.executor().advance_clock(COPIED_DURATION / 2);
visual.run_until_parked();
draw(&mut visual, window);
assert!(
visual.debug_bounds("clipboard-copied").is_some(),
"the first click's stale revert must not clear the second click's confirmation"
);
cx.executor().advance_clock(COPIED_DURATION);
visual.run_until_parked();
draw(&mut visual, window);
assert!(visual.debug_bounds("clipboard").is_some());
}
-367
View File
@@ -1,367 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use gpui::{
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;
fn option(label: &'static str) -> ComboboxOption<SharedString> {
(SharedString::from(label), SharedString::from(label))
}
struct Host {
combobox: Entity<ComboboxState<SharedString>>,
}
impl Render for Host {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().p_4().child(self.combobox.clone())
}
}
type Recorder = Rc<RefCell<Vec<Option<SharedString>>>>;
type CreatedRecorder = Rc<RefCell<Vec<SharedString>>>;
struct ComboHost {
cx: TestAppContext,
state: Entity<ComboboxState<SharedString>>,
changes: Recorder,
created: CreatedRecorder,
visual: VisualTestContext,
}
fn combo_host(keep_unmatched: bool, create: bool) -> ComboHost {
combo_host_with(|builder, created| {
let builder = if keep_unmatched {
builder.keep_unmatched_text()
} else {
builder
};
if create {
builder.on_create(move |text, _, _| created.borrow_mut().push(text))
} else {
builder
}
})
}
/// Builds a host whose combobox the caller configures; the created-recorder
/// is handed over for `on_create` wiring.
fn combo_host_with(
configure: impl FnOnce(Combobox<SharedString>, CreatedRecorder) -> Combobox<SharedString>,
) -> ComboHost {
let cx = TestAppContext::single();
// `init` registers the input bindings and then the combobox's, in the
// load-bearing order.
cx.update(init);
let changes: Recorder = Rc::new(RefCell::new(Vec::new()));
let created: Rc<RefCell<Vec<SharedString>>> = Rc::new(RefCell::new(Vec::new()));
let state_cell: Rc<RefCell<Option<Entity<ComboboxState<SharedString>>>>> =
Rc::new(RefCell::new(None));
let window = cx.update(|cx| {
let changes_for_builder = changes.clone();
let created_for_builder = created.clone();
let cell = state_cell.clone();
cx.open_window(gpui::WindowOptions::default(), |window, cx| {
let builder = configure(
Combobox::new(
"test-combo",
"Fruit",
vec![option("main"), option("maintain"), option("release")],
)
.on_change(move |value, _, _| changes_for_builder.borrow_mut().push(value)),
created_for_builder,
);
let combobox = cx.new(|cx| ComboboxState::new(builder, window, cx));
cell.borrow_mut().replace(combobox.clone());
cx.new(|_| Host { combobox })
})
.unwrap()
});
let state = state_cell.borrow().clone().expect("state captured");
let mut visual = VisualTestContext::from_window(window.into(), &cx);
draw(&mut visual);
ComboHost {
cx,
state,
changes,
created,
visual,
}
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
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| {
state.update(cx, |state, cx| state.focus(window, cx));
});
}
fn type_text(host: &mut ComboHost, text: &str) {
focus(host);
for letter in text.chars() {
host.visual.simulate_keystrokes(&letter.to_string());
}
draw(&mut host.visual);
}
#[test]
fn typing_opens_the_picker_and_filters_the_options() {
let mut host = combo_host(false, false);
type_text(&mut host, "mai");
assert!(host.visual.debug_bounds("test-combo-option-0").is_some());
assert!(host.visual.debug_bounds("test-combo-option-1").is_some());
assert!(
host.visual.debug_bounds("test-combo-option-2").is_none(),
"release must not match \"mai\""
);
}
#[test]
fn enter_commits_the_highlighted_option() {
let mut host = combo_host(false, false);
type_text(&mut host, "mai");
host.visual.simulate_keystrokes("enter");
host.visual.run_until_parked();
draw(&mut host.visual);
assert_eq!(
*host.changes.borrow(),
vec![Some(SharedString::from("main"))],
"the first surviving option starts highlighted"
);
assert!(host.visual.debug_bounds("test-combo-panel").is_none());
let text = host.cx.update(|cx| host.state.read(cx).text(cx));
assert_eq!(text, "main");
}
#[test]
fn typing_clears_the_value() {
let mut host = combo_host(false, false);
type_text(&mut host, "main");
host.visual.simulate_keystrokes("enter");
draw(&mut host.visual);
assert_eq!(
*host.changes.borrow(),
vec![Some(SharedString::from("main"))]
);
// Typing again first clears the value it no longer names.
host.visual.simulate_keystrokes("r");
host.visual.run_until_parked();
draw(&mut host.visual);
assert_eq!(
*host.changes.borrow(),
vec![Some(SharedString::from("main")), None]
);
}
#[test]
fn escape_closes_without_committing() {
let mut host = combo_host(false, false);
type_text(&mut host, "mai");
host.visual.simulate_keystrokes("escape");
draw(&mut host.visual);
assert!(host.visual.debug_bounds("test-combo-panel").is_none());
assert!(host.changes.borrow().is_empty(), "escape must not commit");
}
#[test]
fn blur_reverts_unmatched_text_to_the_empty_selection() {
let mut host = combo_host(false, false);
type_text(&mut host, "nonsense");
assert!(host.changes.borrow().is_empty());
host.visual.update(|window, cx| window.blur(cx));
draw(&mut host.visual);
assert!(host.changes.borrow().is_empty());
let text = host.cx.update(|cx| host.state.read(cx).text(cx));
assert_eq!(text, "", "revert with no value empties the field");
}
#[test]
fn keep_unmatched_leaves_the_text() {
let mut host = combo_host(true, false);
type_text(&mut host, "nonsense");
host.visual.update(|window, cx| window.blur(cx));
draw(&mut host.visual);
let text = host.cx.update(|cx| host.state.read(cx).text(cx));
assert_eq!(text, "nonsense", "keep leaves the text in the field");
// The picker started with no value, so typing cleared nothing and there
// was nothing to report.
assert!(host.changes.borrow().is_empty());
}
#[test]
fn create_hands_unmatched_text_to_the_handler() {
let mut host = combo_host(false, true);
type_text(&mut host, "feature");
host.visual.update(|window, cx| window.blur(cx));
host.visual.run_until_parked();
draw(&mut host.visual);
assert_eq!(
*host.created.borrow(),
vec![SharedString::from("feature")],
"create hands the text over on blur"
);
}
#[test]
fn clicking_a_row_commits_it() {
let mut host = combo_host(false, false);
type_text(&mut host, "rel");
let row = host
.visual
.debug_bounds("test-combo-option-0")
.expect("release row missing");
host.visual
.simulate_click(row.center(), gpui::Modifiers::default());
host.visual.run_until_parked();
draw(&mut host.visual);
assert_eq!(
*host.changes.borrow(),
vec![Some(SharedString::from("release"))]
);
assert!(host.visual.debug_bounds("test-combo-panel").is_none());
}
/// Regression: handlers used to run inside an update of the combobox
/// entity, so a handler that touched its own state re-entered and panicked.
/// Both handlers now run on the executor and may update the state freely.
#[test]
fn handlers_may_update_their_own_combobox() {
let cx = TestAppContext::single();
cx.update(init);
let state_cell: Rc<RefCell<Option<Entity<ComboboxState<SharedString>>>>> =
Rc::new(RefCell::new(None));
let cell = state_cell.clone();
let window = cx.update(|cx| {
cx.open_window(gpui::WindowOptions::default(), |window, cx| {
let builder = Combobox::new(
"self-updating-combo",
"Label",
vec![option("bug"), option("docs")],
)
.on_create(move |text: SharedString, window, cx| {
let state = cell.borrow().clone().expect("state captured");
state.update(cx, |state, cx| {
let mut options = state.options_snapshot();
if !options.iter().any(|(value, _)| value == &text) {
options.push((text.clone(), text.clone()));
state.set_options(options, cx);
}
state.set_selected(Some(text), window, cx);
});
});
let combobox = cx.new(|cx| ComboboxState::new(builder, window, cx));
state_cell.borrow_mut().replace(combobox.clone());
cx.new(|_| Host { combobox })
})
.unwrap()
});
let state = state_cell.borrow().clone().expect("state captured");
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| window.draw(cx).clear(cx));
// Typing an unmatched name and blurring hands it to `on_create`, which
// updates this very combobox — the crash the deferral fixes.
visual.update(|window, cx| {
state.update(cx, |state, cx| state.focus(window, cx));
});
for letter in "feature".chars() {
visual.simulate_keystrokes(&letter.to_string());
}
visual.update(|window, cx| window.blur(cx));
visual.run_until_parked();
visual.update(|window, cx| window.draw(cx).clear(cx));
let selected = cx.update(|cx| state.read(cx).selected().cloned());
assert_eq!(selected, Some(SharedString::from("feature")));
let options = cx.update(|cx| state.read(cx).options_snapshot());
assert!(options.iter().any(|(value, _)| value == "feature"));
}
/// Matches when the query's characters appear in the label in order, so
/// "mn" finds "main" though the substring matcher would find nothing.
fn subsequence(query: &str, _value: &SharedString, label: &SharedString) -> bool {
let label = label.to_lowercase();
let mut letters = label.chars();
query
.to_lowercase()
.chars()
.all(|letter| letters.any(|found| found == letter))
}
#[test]
fn a_custom_filter_decides_which_options_survive() {
let mut host = combo_host_with(|builder, _| builder.filter(subsequence));
// "mn" is no substring of any option, so only the custom matcher finds
// "main" and "maintain"; "release" has no "n" and drops out.
type_text(&mut host, "mn");
assert!(host.visual.debug_bounds("test-combo-option-0").is_some());
assert!(host.visual.debug_bounds("test-combo-option-1").is_some());
assert!(host.visual.debug_bounds("test-combo-option-2").is_none());
}
#[test]
fn replacing_the_options_reruns_the_custom_filter() {
let mut host = combo_host_with(|builder, _| builder.filter(subsequence));
type_text(&mut host, "mn");
host.cx.update(|cx| {
host.state.update(cx, |state, cx| {
state.set_options(vec![option("metro"), option("mainline")], cx)
})
});
draw(&mut host.visual);
// "metro" has no "n" after its "m"; "mainline" survives as the only row.
assert!(host.visual.debug_bounds("test-combo-option-0").is_some());
assert!(host.visual.debug_bounds("test-combo-option-1").is_none());
}
-99
View File
@@ -1,99 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, TestAppContext, Window, div,
};
use gpui_native_core::combobox::{Combobox, ComboboxOption, ComboboxState};
use gpui_native_core::init;
fn option(label: &'static str) -> ComboboxOption<SharedString> {
(SharedString::from(label), SharedString::from(label))
}
struct Host {
combobox: Entity<ComboboxState<SharedString>>,
renders: Rc<RefCell<usize>>,
}
impl Render for Host {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
*self.renders.borrow_mut() += 1;
div().size_full().p_4().child(self.combobox.clone())
}
}
#[test]
fn real_keystrokes_are_not_pathologically_slow() {
let cx = TestAppContext::single();
cx.update(init);
let (state, renders, window) = cx.update(|cx| {
let renders = Rc::new(RefCell::new(0));
let state_cell: Rc<RefCell<Option<Entity<ComboboxState<SharedString>>>>> =
Rc::new(RefCell::new(None));
let renders_for_host = renders.clone();
let cell = state_cell.clone();
let window = cx
.open_window(gpui::WindowOptions::default(), |window, cx| {
let state = cx.new(|cx| {
ComboboxState::new(
Combobox::new(
"bench-combo",
"Fruit",
vec![
option("main"),
option("maintain"),
option("release"),
option("banana"),
],
),
window,
cx,
)
});
let state_for_host = state.clone();
cell.borrow_mut().replace(state.clone());
cx.new(|_| Host {
combobox: state_for_host,
renders: renders_for_host,
})
})
.unwrap();
let state = state_cell.borrow().clone().expect("state captured");
(state, renders, window)
});
let mut visual = gpui::VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
state.update(cx, |state, cx| state.focus(window, cx));
window.draw(cx).clear(cx);
});
// The focused caret must ride executor timers, never frame requests.
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
"an idle focused combobox must not request animation frames"
);
for letter in "abcdefghijklmnopqrstuvwxyz".chars() {
visual.simulate_keystrokes(&letter.to_string());
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
let total_renders = *renders.borrow();
println!(
"26 real keystrokes: {total_renders} host renders ({:.2} per keystroke)",
total_renders as f32 / 26.
);
assert!(
total_renders >= 26,
"every keystroke must redraw the page; got {total_renders} renders"
);
assert!(
total_renders <= 26 * 3,
"typing caused {total_renders} host renders; healthy filtering stays under 3 per keystroke"
);
}
-279
View File
@@ -1,279 +0,0 @@
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,
};
use gpui_native_core::command_palette::{Command, CommandPalette, CommandPaletteState};
use gpui_native_core::init;
fn commands() -> Vec<Command> {
vec![
Command::new("open-file", "Open File").hint("Cmd+O"),
Command::new("close-tab", "Close Tab"),
Command::new("save-all", "Save All").hint("Cmd+Alt+S"),
Command::new("toggle-theme", "Toggle Theme"),
]
}
/// The caller-owned matcher: case-insensitive substring. `reverse` flips the
/// match order, exercising that ranking belongs to the caller.
fn substring_matcher(reverse: bool) -> impl Fn(&str, &[Command]) -> Vec<Command> {
move |query, commands| {
let query = query.to_lowercase();
let matched: Vec<Command> = commands
.iter()
.filter(|command| command.label.to_lowercase().contains(&query))
.cloned()
.collect();
if reverse {
matched.into_iter().rev().collect()
} else {
matched
}
}
}
struct Host {
palette: Entity<CommandPaletteState>,
}
impl Render for Host {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(self.palette.clone())
}
}
type Executed = Rc<RefCell<Vec<SharedString>>>;
struct PaletteHost {
cx: TestAppContext,
state: Entity<CommandPaletteState>,
executed: Executed,
visual: VisualTestContext,
}
fn palette_host(reverse: bool) -> PaletteHost {
let cx = TestAppContext::single();
// `init` registers the input bindings and then the palette's, in the
// load-bearing order.
cx.update(init);
let executed: Executed = Rc::new(RefCell::new(Vec::new()));
let state_cell: Rc<RefCell<Option<Entity<CommandPaletteState>>>> = Rc::new(RefCell::new(None));
let window = cx.update(|cx| {
let executed_for_builder = executed.clone();
let cell = state_cell.clone();
cx.open_window(gpui::WindowOptions::default(), |window, cx| {
let palette =
CommandPalette::new("test-palette", commands(), substring_matcher(reverse))
.on_execute(move |command: &Command, _, _| {
executed_for_builder.borrow_mut().push(command.id.clone())
});
let state = cx.new(|cx| CommandPaletteState::new(palette, window, cx));
cell.borrow_mut().replace(state.clone());
cx.new(|_| Host { palette: state })
})
.unwrap()
});
let state = state_cell.borrow().clone().expect("state captured");
let mut visual = VisualTestContext::from_window(window.into(), &cx);
draw(&mut visual);
PaletteHost {
cx,
state,
executed,
visual,
}
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
fn open(host: &mut PaletteHost) {
let state = host.state.clone();
host.visual.update(|window, cx| {
state.update(cx, |state, cx| state.open(window, cx));
});
}
fn type_text(host: &mut PaletteHost, text: &str) {
for letter in text.chars() {
host.visual.simulate_keystrokes(&letter.to_string());
}
draw(&mut host.visual);
}
#[test]
fn open_lists_the_callers_commands() {
let mut host = palette_host(false);
open(&mut host);
draw(&mut host.visual);
assert!(host.visual.debug_bounds("test-palette-command-0").is_some());
assert!(host.visual.debug_bounds("test-palette-command-3").is_some());
assert!(host.visual.debug_bounds("test-palette-panel").is_some());
assert!(host.cx.update(|cx| host.state.read(cx).is_open()));
}
#[test]
fn enter_runs_the_highlighted_command_and_closes() {
let mut host = palette_host(false);
open(&mut host);
host.visual.simulate_keystrokes("enter");
draw(&mut host.visual);
assert_eq!(
*host.executed.borrow(),
vec![SharedString::from("open-file")],
"the first row starts highlighted"
);
assert!(host.visual.debug_bounds("test-palette-panel").is_none());
}
#[test]
fn rows_follow_the_callers_match_order() {
let mut host = palette_host(true);
open(&mut host);
host.visual.simulate_keystrokes("enter");
draw(&mut host.visual);
assert_eq!(
*host.executed.borrow(),
vec![SharedString::from("toggle-theme")],
"enter runs the first row, and the caller's matcher owns the row order"
);
}
#[test]
fn typing_filters_through_the_caller_matcher() {
let mut host = palette_host(false);
open(&mut host);
type_text(&mut host, "save");
assert!(host.visual.debug_bounds("test-palette-command-0").is_some());
assert!(
host.visual.debug_bounds("test-palette-command-1").is_none(),
"only the matching command stays listed"
);
host.visual.simulate_keystrokes("enter");
draw(&mut host.visual);
assert_eq!(
*host.executed.borrow(),
vec![SharedString::from("save-all")]
);
}
#[test]
fn escape_closes_without_running() {
let mut host = palette_host(false);
open(&mut host);
host.visual.simulate_keystrokes("escape");
draw(&mut host.visual);
assert!(host.visual.debug_bounds("test-palette-panel").is_none());
assert!(host.executed.borrow().is_empty());
assert!(!host.cx.update(|cx| host.state.read(cx).is_open()));
}
#[test]
fn arrow_keys_move_the_highlight() {
let mut host = palette_host(false);
open(&mut host);
host.visual.simulate_keystrokes("down");
host.visual.simulate_keystrokes("enter");
draw(&mut host.visual);
assert_eq!(
*host.executed.borrow(),
vec![SharedString::from("close-tab")]
);
// Up from the top wraps to the last row.
open(&mut host);
host.visual.simulate_keystrokes("up");
host.visual.simulate_keystrokes("enter");
draw(&mut host.visual);
assert_eq!(
*host.executed.borrow(),
vec![
SharedString::from("close-tab"),
SharedString::from("toggle-theme")
]
);
}
#[test]
fn clicking_a_row_runs_it() {
let mut host = palette_host(false);
open(&mut host);
let row = host
.visual
.debug_bounds("test-palette-command-2")
.expect("save-all row missing");
host.visual
.simulate_click(row.center(), gpui::Modifiers::default());
draw(&mut host.visual);
assert_eq!(
*host.executed.borrow(),
vec![SharedString::from("save-all")]
);
assert!(host.visual.debug_bounds("test-palette-panel").is_none());
}
#[test]
fn clicking_the_scrim_closes() {
let mut host = palette_host(false);
open(&mut host);
draw(&mut host.visual);
host.visual.simulate_click(
gpui::point(gpui::px(10.), gpui::px(10.)),
gpui::Modifiers::default(),
);
draw(&mut host.visual);
assert!(host.visual.debug_bounds("test-palette-panel").is_none());
assert!(host.executed.borrow().is_empty());
}
#[test]
fn reopen_starts_from_a_fresh_query() {
let mut host = palette_host(false);
open(&mut host);
type_text(&mut host, "zzzz");
assert!(
host.visual.debug_bounds("test-palette-command-0").is_none(),
"nothing matches nonsense"
);
host.visual.simulate_keystrokes("escape");
open(&mut host);
draw(&mut host.visual);
assert!(
host.visual.debug_bounds("test-palette-command-0").is_some(),
"a fresh open clears the query"
);
}
#[test]
fn set_commands_replaces_the_registry() {
let mut host = palette_host(false);
host.cx.update(|cx| {
host.state.update(cx, |state, cx| {
state.set_commands(vec![Command::new("only", "Only Command")], cx)
});
});
open(&mut host);
draw(&mut host.visual);
assert!(host.visual.debug_bounds("test-palette-command-0").is_some());
assert!(host.visual.debug_bounds("test-palette-command-1").is_none());
host.visual.simulate_keystrokes("enter");
draw(&mut host.visual);
assert_eq!(*host.executed.borrow(), vec![SharedString::from("only")]);
}
-107
View File
@@ -1,107 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, TestAppContext, Window, div,
};
use gpui_native_core::command_palette::{Command, CommandPalette, CommandPaletteState};
use gpui_native_core::init;
fn command(label: &'static str) -> Command {
Command::new(SharedString::from(label), SharedString::from(label))
}
struct Host {
palette: Entity<CommandPaletteState>,
renders: Rc<RefCell<usize>>,
}
impl Render for Host {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
*self.renders.borrow_mut() += 1;
div().size_full().child(self.palette.clone())
}
}
#[test]
fn typing_with_the_palette_open_is_not_pathologically_slow() {
let cx = TestAppContext::single();
cx.update(init);
let (state, renders, window) = cx.update(|cx| {
let renders = Rc::new(RefCell::new(0));
let state_cell: Rc<RefCell<Option<Entity<CommandPaletteState>>>> =
Rc::new(RefCell::new(None));
let renders_for_host = renders.clone();
let cell = state_cell.clone();
let window = cx
.open_window(gpui::WindowOptions::default(), |window, cx| {
let matcher = |query: &str, commands: &[Command]| {
let query = query.to_lowercase();
commands
.iter()
.filter(|command| command.label.to_lowercase().contains(&query))
.cloned()
.collect()
};
let state = cx.new(|cx| {
CommandPaletteState::new(
CommandPalette::new(
"bench-palette",
vec![
command("Open File"),
command("Close Tab"),
command("Save All"),
command("Toggle Theme"),
],
matcher,
),
window,
cx,
)
});
let state_for_host = state.clone();
cell.borrow_mut().replace(state.clone());
cx.new(|_| Host {
palette: state_for_host,
renders: renders_for_host,
})
})
.unwrap();
let state = state_cell.borrow().clone().expect("state captured");
(state, renders, window)
});
let mut visual = gpui::VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
state.update(cx, |state, cx| state.open(window, cx));
window.draw(cx).clear(cx);
});
// The open palette must sit idle on executor timers, never frame requests.
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
"an idle open palette must not request animation frames"
);
for letter in "abcdefghijklmnopqrstuvwxyz".chars() {
visual.simulate_keystrokes(&letter.to_string());
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
let total_renders = *renders.borrow();
println!(
"26 real keystrokes with the palette open: {total_renders} host renders ({:.2} per keystroke)",
total_renders as f32 / 26.
);
assert!(
total_renders >= 26,
"every keystroke must redraw the page; got {total_renders} renders"
);
assert!(
total_renders <= 26 * 3,
"typing caused {total_renders} host renders; healthy filtering stays under 3 per keystroke"
);
}
-134
View File
@@ -1,134 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, IntoElement, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
};
use gpui_native_core::context_menu::ContextMenu;
use gpui_native_core::menu::MenuItem;
use gpui_native_theme::Theme;
type Actions = Rc<RefCell<Vec<&'static str>>>;
struct Harness {
actions: Actions,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let actions = self.actions.clone();
div().size_full().p_4().child(
ContextMenu::new("ctx")
.target(|_, _| div().h(px(40.)).w(px(200.)).child("Row").into_any_element())
.items({
let actions = actions.clone();
move |_, _| {
vec![
MenuItem::new("Rename").handler({
let actions = actions.clone();
move |_, _| actions.borrow_mut().push("rename")
}),
MenuItem::new("Delete").handler({
let actions = actions.clone();
move |_, _| actions.borrow_mut().push("delete")
}),
]
}
}),
)
}
}
/// The target row rides the `p_4` band: `16..216` horizontally, `16..56`
/// vertically, so right-clicks land near `(100, 30)`.
fn context_window() -> (TestAppContext, VisualTestContext, Actions) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let actions = Rc::new(RefCell::new(Vec::new()));
let harness_actions = actions.clone();
let window = cx.add_window(move |_, _| Harness {
actions: harness_actions,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, actions)
}
fn right_click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_down(position, MouseButton::Right, gpui::Modifiers::default());
visual.simulate_mouse_up(position, MouseButton::Right, gpui::Modifiers::default());
}
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());
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
#[test]
fn right_click_opens_the_menu_and_items_activate() {
let (_cx, mut visual, actions) = context_window();
right_click(&mut visual, point(px(100.), px(30.)));
draw(&mut visual);
// A pointer open arms no row, so Enter alone fires nothing.
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*actions.borrow(), Vec::<&str>::new());
// The first down arms Rename; enter fires it and closes the menu.
visual.simulate_keystrokes("down enter");
draw(&mut visual);
assert_eq!(*actions.borrow(), vec!["rename"]);
// The menu closed with the choice, so Enter reports nothing more.
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*actions.borrow(), vec!["rename"]);
// Right-click again reopens; two downs reach the second item.
right_click(&mut visual, point(px(100.), px(30.)));
draw(&mut visual);
visual.simulate_keystrokes("down down");
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*actions.borrow(), vec!["rename", "delete"]);
}
#[test]
fn a_left_click_on_the_target_does_not_open_the_menu() {
let (_cx, mut visual, actions) = context_window();
click(&mut visual, point(px(100.), px(30.)));
draw(&mut visual);
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*actions.borrow(), Vec::<&str>::new());
}
#[test]
fn a_click_outside_closes_the_menu() {
let (_cx, mut visual, actions) = context_window();
right_click(&mut visual, point(px(100.), px(30.)));
draw(&mut visual);
click(&mut visual, point(px(450.), px(300.)));
draw(&mut visual);
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*actions.borrow(), Vec::<&str>::new());
// A right-click outside the target never opens it either.
right_click(&mut visual, point(px(450.), px(300.)));
draw(&mut visual);
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*actions.borrow(), Vec::<&str>::new());
}
-69
View File
@@ -1,69 +0,0 @@
use gpui::{
Entity, InteractiveElement as _, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div,
};
use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::input::{Input, InputState};
use gpui_native_theme::ActiveTheme as _;
use gpui_native_theme::{BORDER_WIDTH, Theme};
struct Harness {
state: Entity<InputState>,
}
impl Render for Harness {
fn render(
&mut self,
_window: &mut Window,
_cx: &mut gpui::Context<Self>,
) -> impl gpui::IntoElement {
div()
.flex()
.flex_col()
.gap_4()
.child(
div().debug_selector(|| "button-wrapper".to_string()).child(
Button::new("cmp-button")
.variant(ButtonVariant::Secondary)
.label("Medium"),
),
)
.child(
div()
.debug_selector(|| "input-wrapper".to_string())
.child(Input::new("cmp-input", self.state.clone())),
)
}
}
/// 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 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();
let window = cx.add_window(move |_, _| Harness {
state: state_for_window,
});
let mut visual = VisualTestContext::from_window(window.into(), cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
let button = visual
.debug_bounds("button-wrapper")
.expect("button rendered");
let input = visual
.debug_bounds("input-wrapper")
.expect("input rendered");
// 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));
}
-183
View File
@@ -1,183 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use gpui::{
Context, IntoElement, Modifiers, MouseButton, ParentElement as _, Render, Styled as _,
TestAppContext, VisualTestContext, Window, div, point, px,
};
use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::dialog::Dialog;
use gpui_native_theme::Theme;
struct Harness {
open: bool,
alert: bool,
changes: Rc<RefCell<Vec<bool>>>,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
let on_change_view = view.clone();
let close_changes = self.changes.clone();
let close_view = view.clone();
div().size_full().child(
Dialog::new("test-dialog")
.open(self.open)
.alert(self.alert)
.title("Delete file?")
.on_change(move |next, _, cx| {
eprintln!("HARNESS on_change: {next}");
changes.borrow_mut().push(next);
on_change_view.update(cx, |harness, cx| {
harness.open = next;
cx.notify();
});
})
.content(|_, _| {
div()
.w(px(300.))
.h(px(80.))
.child("This cannot be undone.")
.into_any_element()
})
.actions(move |_, _| {
vec![
Button::new("dialog-cancel")
.label("Cancel")
.variant(ButtonVariant::Secondary)
.on_click({
let close_changes = close_changes.clone();
let close_view = close_view.clone();
move |_, _, cx| {
close_changes.borrow_mut().push(false);
close_view.update(cx, |harness, cx| {
harness.open = false;
cx.notify();
});
}
})
.into_any_element(),
Button::new("dialog-delete")
.label("Delete")
.variant(ButtonVariant::Destructive)
.on_click({
let close_changes = close_changes.clone();
let close_view = close_view.clone();
move |_, _, cx| {
close_changes.borrow_mut().push(false);
close_view.update(cx, |harness, cx| {
harness.open = false;
cx.notify();
});
}
})
.into_any_element(),
]
}),
)
}
}
/// An open 332px-wide dialog centered in the window: the panel spans
/// roughly `(794..1126, 448..640)`, so `(100, 100)` is on the scrim and
/// the window center is on the panel.
fn dialog_window(
open: bool,
alert: bool,
) -> (TestAppContext, VisualTestContext, Rc<RefCell<Vec<bool>>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
open,
alert,
changes: harness_changes,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, changes)
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
eprintln!("DRAW");
window.draw(cx).clear(cx);
});
}
fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
visual.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
}
#[test]
fn escape_closes_a_modal_dialog_and_stays_closed() {
let (_cx, mut visual, changes) = dialog_window(true, false);
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![false]);
draw(&mut visual);
// Closed: escape on the inert remainder reports nothing further.
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn escape_is_inert_on_an_alert() {
let (_cx, mut visual, changes) = dialog_window(true, true);
visual.simulate_keystrokes("escape");
assert!(changes.borrow().is_empty());
}
#[test]
fn scrim_click_closes_a_modal_but_not_an_alert() {
let (_cx, mut visual, changes) = dialog_window(true, false);
click(&mut visual, point(px(100.), px(100.)));
assert_eq!(*changes.borrow(), vec![false]);
draw(&mut visual);
click(&mut visual, point(px(100.), px(100.)));
assert_eq!(*changes.borrow(), vec![false]);
// The same click on an alert's scrim answers nothing.
let (_cx, mut visual, changes) = dialog_window(true, true);
click(&mut visual, point(px(100.), px(100.)));
assert!(changes.borrow().is_empty());
}
#[test]
fn clicking_the_panel_does_not_dismiss() {
// The window center is where the centered panel sits.
let (_cx, mut visual, changes) = dialog_window(true, false);
click(&mut visual, point(px(960.), px(540.)));
assert!(changes.borrow().is_empty());
}
/// Clicking the close button reports close like escape and the scrim; the
/// panel then unmounts the button with the rest of the dialog.
#[test]
fn the_close_button_reports_close_and_disappears() {
let (_cx, mut visual, changes) = dialog_window(true, false);
let bounds = visual
.debug_bounds("dialog-close")
.expect("the close button rendered");
click(&mut visual, bounds.center());
assert_eq!(*changes.borrow(), vec![false]);
draw(&mut visual);
assert!(visual.debug_bounds("dialog-close").is_none());
}
/// An alert answers only through its actions, so it renders no close button.
#[test]
fn an_alert_hides_the_close_button() {
let (_cx, mut visual, _changes) = dialog_window(true, true);
assert!(visual.debug_bounds("dialog-close").is_none());
}
-457
View File
@@ -1,457 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke,
Modifiers, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
};
use gpui_native_core::button::ButtonVariant;
use gpui_native_core::dropdown_menu::DropdownMenu;
use gpui_native_core::menu::MenuItem;
use gpui_native_theme::Theme;
struct Harness {
open: bool,
split: bool,
disabled: bool,
changes: Rc<RefCell<Vec<bool>>>,
clicks: Rc<RefCell<usize>>,
activated: Rc<RefCell<Vec<&'static str>>>,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let view = cx.entity();
let changes = self.changes.clone();
let clicks = self.clicks.clone();
let activated = self.activated.clone();
let mut trigger = DropdownMenu::new("test-dd")
.label("Save")
.variant(ButtonVariant::Secondary)
.open(self.open)
.on_open_change(move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.open = next;
cx.notify();
});
})
.items(move |_, _| {
vec![
export_item(activated.clone(), "png"),
export_item(activated.clone(), "pdf"),
]
});
if self.disabled {
trigger = trigger.disabled(true);
}
if self.split {
trigger = trigger.on_click(move |_, _, _| *clicks.borrow_mut() += 1);
}
div().size_full().child(trigger)
}
}
fn export_item(activated: Rc<RefCell<Vec<&'static str>>>, format: &'static str) -> MenuItem {
MenuItem::new(format).handler(move |_, _| activated.borrow_mut().push(format))
}
type Changes = Rc<RefCell<Vec<bool>>>;
type Clicks = Rc<RefCell<usize>>;
type Activated = Rc<RefCell<Vec<&'static str>>>;
/// A maximized window whose trigger starts in the top-left corner, so the
/// main zone is under the cursor at the button's usual tap position and the
/// chevron zone is found through its debug bounds.
fn dropdown_window(
split: bool,
disabled: bool,
) -> (
TestAppContext,
VisualTestContext,
AnyWindowHandle,
Changes,
Clicks,
Activated,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let clicks = Rc::new(RefCell::new(0));
let activated = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let harness_clicks = clicks.clone();
let harness_activated = activated.clone();
let window = cx.add_window(move |_, _| Harness {
open: false,
split,
disabled,
changes: harness_changes,
clicks: harness_clicks,
activated: harness_activated,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
let visual = VisualTestContext::from_window(window, &cx);
(cx, visual, window, changes, clicks, activated)
}
fn draw(visual: &mut VisualTestContext, window: AnyWindowHandle) {
visual
.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
visual.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
}
/// The painted center of an element found through its debug selector.
fn center(visual: &mut VisualTestContext, selector: &'static str) -> gpui::Point<gpui::Pixels> {
let bounds = visual
.debug_bounds(selector)
.unwrap_or_else(|| panic!("{selector} should have been laid out"));
point(
bounds.origin.x + bounds.size.width / 2.,
bounds.origin.y + bounds.size.height / 2.,
)
}
/// Split form: clicking the main zone fires the action and the menu stays
/// closed — the button keeps its normal behavior under a child menu.
#[test]
fn action_button_fires_and_does_not_open() {
let (_cx, mut visual, window, changes, clicks, _activated) = dropdown_window(true, false);
click(&mut visual, point(px(30.), px(14.)));
assert_eq!(*clicks.borrow(), 1, "the main zone fires on_click");
assert!(
changes.borrow().is_empty(),
"the menu must stay closed: {:?}",
changes.borrow()
);
draw(&mut visual, window);
assert!(visual.debug_bounds("menu-panel").is_none());
}
/// Split form: only the chevron zone opens the menu, and an activated row
/// closes it.
#[test]
fn chevron_opens_and_row_activation_closes() {
let (_cx, mut visual, window, changes, clicks, activated) = dropdown_window(true, false);
let chevron = center(&mut visual, "test-dd-chevron");
click(&mut visual, chevron);
assert_eq!(*changes.borrow(), vec![true]);
draw(&mut visual, window);
let row = center(&mut visual, "menu-item-0");
click(&mut visual, row);
assert_eq!(*activated.borrow(), vec!["png"]);
assert_eq!(*changes.borrow(), vec![true, false]);
assert_eq!(*clicks.borrow(), 0, "row activation never fires on_click");
}
/// Menu-only form: the whole button opens the menu on click, like a menu
/// button.
#[test]
fn plain_button_activates_the_menu() {
let (_cx, mut visual, _window, changes, clicks, _activated) = dropdown_window(false, false);
click(&mut visual, point(px(30.), px(14.)));
assert_eq!(*changes.borrow(), vec![true]);
assert_eq!(*clicks.borrow(), 0);
}
/// Keyboard focus returns to the trigger when the menu closes, so the down
/// arrow opens it again.
#[test]
fn escape_returns_focus_to_the_trigger() {
let (_cx, mut visual, window, changes, _clicks, _activated) = dropdown_window(true, false);
let chevron = center(&mut visual, "test-dd-chevron");
click(&mut visual, chevron);
draw(&mut visual, window);
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![true, false]);
draw(&mut visual, window);
visual.simulate_keystrokes("down");
assert_eq!(
*changes.borrow(),
vec![true, false, true],
"the focused trigger reopened the menu"
);
}
/// Enter and Space fire the split button's action while it is focused, like
/// any push button.
#[test]
fn enter_and_space_fire_the_action_while_focused() {
let (_cx, mut visual, window, changes, clicks, _activated) = dropdown_window(true, false);
click(&mut visual, point(px(30.), px(14.)));
draw(&mut visual, window);
for key in ["enter", "space"] {
visual.simulate_event(KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
});
visual.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
assert_eq!(*clicks.borrow(), 3, "the pointer click, Enter, and Space");
assert!(changes.borrow().is_empty());
}
/// Enter opens the menu while a menu-only trigger is focused.
#[test]
fn enter_opens_the_menu_only_trigger() {
let (_cx, mut visual, window, changes, _clicks, _activated) = dropdown_window(false, false);
// Opening hands focus to the panel; dismissing hands it back to the
// trigger, whose Enter then reopens the menu.
click(&mut visual, point(px(30.), px(14.)));
draw(&mut visual, window);
visual.simulate_keystrokes("escape");
draw(&mut visual, window);
{
let key = "enter";
visual.simulate_event(KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
});
visual.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
assert_eq!(*changes.borrow(), vec![true, false, true]);
}
/// Action rows sit a half-step apart so the rounded selection highlight
/// reads as its own chip instead of a continuous block.
#[test]
fn action_rows_sit_a_half_step_apart() {
let (_cx, mut visual, window, _changes, _clicks, _activated) = dropdown_window(true, false);
let chevron = center(&mut visual, "test-dd-chevron");
click(&mut visual, chevron);
draw(&mut visual, window);
let first = visual
.debug_bounds("menu-item-0")
.expect("first row should have been laid out");
let second = visual
.debug_bounds("menu-item-1")
.expect("second row should have been laid out");
let gap = second.origin.y - (first.origin.y + first.size.height);
// Painted bounds are snapped to device pixels; allow half a pixel.
assert!(
(gap - px(2.)).abs() <= px(0.5),
"rows should sit 2px apart, got {gap:?}"
);
}
/// A pointer-opened menu arms no row, so enter cannot fire one; the first
/// down arms a row and enter fires it.
#[test]
fn pointer_opens_arm_nothing() {
let (_cx, mut visual, window, changes, _clicks, activated) = dropdown_window(true, false);
let chevron = center(&mut visual, "test-dd-chevron");
click(&mut visual, chevron);
draw(&mut visual, window);
visual.simulate_keystrokes("enter");
assert!(
activated.borrow().is_empty(),
"no row is armed on pointer open"
);
assert_eq!(*changes.borrow(), vec![true], "the menu stays open");
visual.simulate_keystrokes("down enter");
assert_eq!(*activated.borrow(), vec!["png"]);
assert_eq!(*changes.borrow(), vec![true, false]);
}
/// A keyboard-opened menu (down arrow from the focused trigger) arms the
/// first selectable row, so enter fires it right away.
#[test]
fn keyboard_opens_arm_the_first_row() {
let (_cx, mut visual, window, changes, _clicks, activated) = dropdown_window(false, false);
click(&mut visual, point(px(30.), px(14.)));
draw(&mut visual, window);
visual.simulate_keystrokes("escape");
draw(&mut visual, window);
visual.simulate_keystrokes("down");
draw(&mut visual, window);
visual.simulate_keystrokes("enter");
assert_eq!(*activated.borrow(), vec!["png"]);
assert_eq!(*changes.borrow(), vec![true, false, true, false]);
}
/// A disabled trigger ignores both zones.
#[test]
fn disabled_trigger_ignores_clicks() {
let (_cx, mut visual, window, changes, clicks, _activated) = dropdown_window(true, true);
click(&mut visual, point(px(30.), px(14.)));
let chevron = center(&mut visual, "test-dd-chevron");
click(&mut visual, chevron);
draw(&mut visual, window);
assert_eq!(*clicks.borrow(), 0);
assert!(changes.borrow().is_empty());
assert!(visual.debug_bounds("menu-panel").is_none());
}
struct PairHarness {
open_a: bool,
open_b: bool,
changes_a: Changes,
changes_b: Changes,
activated_a: Activated,
activated_b: Activated,
}
impl Render for PairHarness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (changes_a, changes_b) = (self.changes_a.clone(), self.changes_b.clone());
let (activated_a, activated_b) = (self.activated_a.clone(), self.activated_b.clone());
let menu_a = DropdownMenu::new("pair-a")
.label("Alpha")
.variant(ButtonVariant::Secondary)
.open(self.open_a)
.on_open_change({
let view = cx.entity();
let changes = changes_a.clone();
move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.open_a = next;
cx.notify();
});
}
})
.items(move |_, _| {
vec![
MenuItem::new("png").handler({
let activated = activated_a.clone();
move |_, _| activated.borrow_mut().push("png")
}),
MenuItem::new("pdf").handler({
let activated = activated_a.clone();
move |_, _| activated.borrow_mut().push("pdf")
}),
]
});
let menu_b = DropdownMenu::new("pair-b")
.label("Beta")
.variant(ButtonVariant::Secondary)
.open(self.open_b)
.on_open_change({
let view = cx.entity();
let changes = changes_b.clone();
move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.open_b = next;
cx.notify();
});
}
})
.items(move |_, _| {
vec![
MenuItem::new("zip").handler({
let activated = activated_b.clone();
move |_, _| activated.borrow_mut().push("zip")
}),
MenuItem::new("7z").handler({
let activated = activated_b.clone();
move |_, _| activated.borrow_mut().push("7z")
}),
]
});
div().size_full().flex().gap_2().child(menu_a).child(menu_b)
}
}
fn pair_window() -> (
VisualTestContext,
AnyWindowHandle,
Changes,
Changes,
Activated,
Activated,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes_a = Rc::new(RefCell::new(Vec::new()));
let changes_b = Rc::new(RefCell::new(Vec::new()));
let activated_a = Rc::new(RefCell::new(Vec::new()));
let activated_b = Rc::new(RefCell::new(Vec::new()));
let (changes_a_for_window, changes_b_for_window) = (changes_a.clone(), changes_b.clone());
let (activated_a_for_window, activated_b_for_window) =
(activated_a.clone(), activated_b.clone());
let window = cx.add_window(move |_, _| PairHarness {
open_a: false,
open_b: false,
changes_a: changes_a_for_window,
changes_b: changes_b_for_window,
activated_a: activated_a_for_window,
activated_b: activated_b_for_window,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(
VisualTestContext::from_window(window, &cx),
window,
changes_a,
changes_b,
activated_a,
activated_b,
)
}
/// With a closed sibling dropdown on screen, a pointer-opened menu must still
/// arm rows with the keyboard: the menu's open/selection state is per
/// instance, not shared keyed state.
#[test]
fn sibling_dropdowns_keep_independent_menu_state() {
let (mut visual, window, changes_a, changes_b, activated_a, activated_b) = pair_window();
// Menu A sits at the window's top-left; menu B stays closed beside it.
click(&mut visual, point(px(30.), px(14.)));
assert_eq!(*changes_a.borrow(), vec![true]);
draw(&mut visual, window);
visual.simulate_keystrokes("down enter");
assert_eq!(*activated_a.borrow(), vec!["png"]);
assert_eq!(*changes_a.borrow(), vec![true, false]);
assert!(changes_b.borrow().is_empty(), "B must stay closed");
assert!(activated_b.borrow().is_empty());
}
-115
View File
@@ -1,115 +0,0 @@
use gpui::{
AppContext as _, IntoElement, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div,
};
use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::field::{Field, FieldVariant};
use gpui_native_theme::Theme;
struct FieldHost {
variant: FieldVariant,
with_error: bool,
}
impl Render for FieldHost {
fn render(&mut self, _window: &mut Window, _cx: &mut gpui::Context<Self>) -> impl IntoElement {
let mut field = Field::new("test-field", "Server URL")
.description("Where patches are sent.")
.variant(self.variant)
.child(
Button::new("test-field-button")
.label("Edit")
.variant(ButtonVariant::Ghost),
);
if self.with_error {
field = field.error(Some("Required"));
}
div().size_full().p_4().child(field)
}
}
fn field_window(
variant: FieldVariant,
with_error: bool,
) -> (TestAppContext, gpui::AnyWindowHandle) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let window = cx.add_window(move |_, _| FieldHost {
variant,
with_error,
});
let window: gpui::AnyWindowHandle = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(cx, window)
}
#[test]
fn block_stacks_the_label_above_the_control() {
let (cx, window) = field_window(FieldVariant::Block, false);
let mut visual = VisualTestContext::from_window(window, &cx);
let label = visual
.debug_bounds("test-field-label")
.expect("label missing");
let control = visual
.debug_bounds("test-field-control")
.expect("control missing");
assert!(
label.bottom() <= control.top(),
"label must sit above the control: {label:?} vs {control:?}"
);
assert!(
(label.left() - control.left()).abs() < gpui::px(1.),
"label and control must share the left edge"
);
}
#[test]
fn row_leads_with_the_label_and_trails_the_control() {
let (cx, window) = field_window(FieldVariant::Row, false);
let mut visual = VisualTestContext::from_window(window, &cx);
let label = visual
.debug_bounds("test-field-label")
.expect("label missing");
let control = visual
.debug_bounds("test-field-control")
.expect("control missing");
assert!(
control.left() >= label.right(),
"the control must trail the label: {label:?} vs {control:?}"
);
let label_center = (label.top() + label.bottom()) / 2.;
let control_center = (control.top() + control.bottom()) / 2.;
assert!(
(label_center - control_center).abs() < gpui::px(1.5),
"the control must center on the title line: {label:?} vs {control:?}"
);
}
#[test]
fn the_error_renders_under_the_control_only_when_set() {
let (cx, window) = field_window(FieldVariant::Block, false);
let mut visual = VisualTestContext::from_window(window, &cx);
assert!(
visual.debug_bounds("test-field-error").is_none(),
"no error must render when none is set"
);
let (cx, window) = field_window(FieldVariant::Block, true);
let mut visual = VisualTestContext::from_window(window, &cx);
let error = visual
.debug_bounds("test-field-error")
.expect("error missing");
let control = visual
.debug_bounds("test-field-control")
.expect("control missing");
assert!(
error.top() >= control.bottom(),
"the error must sit under the control: {control:?} vs {error:?}"
);
}
-108
View File
@@ -1,108 +0,0 @@
use std::{cell::Cell, rc::Rc, time::Duration};
use gpui::{
AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString,
Styled as _, TestAppContext, VisualTestContext, Window, div,
};
use gpui_native_core::common::v_flex;
use gpui_native_core::field::Field;
use gpui_native_core::init;
use gpui_native_core::input::{Input, InputState};
struct FieldHost {
url: Entity<InputState>,
renders: Rc<Cell<usize>>,
}
impl Render for FieldHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
let url_error = self
.url
.read(cx)
.value()
.is_empty()
.then_some("Required")
.map(SharedString::from);
div().size_full().p_4().child(
v_flex().gap_3().child(
Field::new("bench-url", "Server URL")
.description("Where your patches are sent.")
.error(url_error)
.child(Input::new("bench-url-input", self.url.clone())),
),
)
}
}
/// 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,
Rc<Cell<usize>>,
) {
let cx = TestAppContext::single();
cx.update(init);
let renders = Rc::new(Cell::new(0));
let renders_for_host = renders.clone();
let (url, window) = cx.update(|cx| {
let url = InputState::new(cx);
let url_for_host = url.clone();
let window = cx
.open_window(gpui::WindowOptions::default(), |_, cx| {
cx.new(|_| FieldHost {
url: url_for_host,
renders: renders_for_host.clone(),
})
})
.unwrap();
(url, window)
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
if focus {
let focus = url.read(cx).focus_handle();
window.focus(&focus, cx);
}
window.draw(cx).clear(cx);
});
(cx, url, visual, renders)
}
#[test]
fn an_idle_field_page_schedules_no_frames() {
let (_cx, _url, mut visual, _renders) = field_host(false);
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
"an idle unfocused field page must not request animation frames"
);
}
/// The caret blink is fps-capped: it must never demand a next frame, and its
/// redraws arrive on the executor timer at the blink cadence.
#[test]
fn a_focused_field_blink_is_fps_capped_and_still_redraws() {
let (cx, _url, mut visual, renders) = field_host(true);
let renders_after_focus = renders.get();
let frames = visual.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(
frames, 0,
"the blink must be fps-capped, not per-frame scheduled"
);
// The blink redraws through the executor timer (4 fps cap).
cx.executor().advance_clock(Duration::from_millis(251));
cx.run_until_parked();
visual.update(|window, cx| window.draw(cx).clear(cx));
assert!(
renders.get() > renders_after_focus,
"the capped blink must still redraw its page"
);
}
File diff suppressed because it is too large Load Diff
-133
View File
@@ -1,133 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, InputEvent as _, IntoElement, KeyDownEvent,
KeyUpEvent, Keystroke, Modifiers, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
};
use gpui_native_core::link::Link;
use gpui_native_theme::Theme;
struct Harness {
clicks: Rc<RefCell<usize>>,
disabled: bool,
with_override: bool,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let clicks = self.clicks.clone();
div().size_full().flex().flex_col().gap_2().child({
let mut link = Link::new("test-link-href")
.label("Release notes")
.href("https://example.com/release-notes");
if self.with_override {
link = link.on_click(move |_, _, _| {
*clicks.borrow_mut() += 1;
});
}
link.disabled(self.disabled)
})
}
}
/// A maximized window with two link rows at the top-left; row 1 spans
/// roughly y 0..21, row 2 y 29..50.
fn link_window(
with_override: bool,
disabled: bool,
) -> (TestAppContext, AnyWindowHandle, Rc<RefCell<usize>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let clicks = Rc::new(RefCell::new(0usize));
let harness_clicks = clicks.clone();
let window = cx.add_window(move |_, _| Harness {
clicks: harness_clicks,
disabled,
with_override,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(cx, window, clicks)
}
fn draw(cx: &mut TestAppContext, window: AnyWindowHandle) {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
#[test]
fn clicking_a_link_with_href_opens_it_through_the_platform() {
let (cx, window, clicks) = link_window(false, false);
let mut visual = VisualTestContext::from_window(window, &cx);
visual.simulate_click(point(px(20.), px(10.)), Modifiers::default());
assert_eq!(
visual.opened_url().as_deref(),
Some("https://example.com/release-notes")
);
assert_eq!(*clicks.borrow(), 0);
}
#[test]
fn on_click_replaces_the_href_opening() {
let (cx, window, clicks) = link_window(true, false);
let mut visual = VisualTestContext::from_window(window, &cx);
visual.simulate_click(point(px(20.), px(10.)), Modifiers::default());
assert_eq!(*clicks.borrow(), 1);
assert_eq!(visual.opened_url(), None, "the handler replaces the href");
}
#[test]
fn disabled_link_does_nothing() {
let (cx, window, clicks) = link_window(false, true);
let mut visual = VisualTestContext::from_window(window, &cx);
visual.simulate_click(point(px(20.), px(10.)), Modifiers::default());
assert_eq!(visual.opened_url(), None);
assert_eq!(*clicks.borrow(), 0);
}
#[test]
fn enter_opens_the_href_while_focused() {
let (mut cx, window, clicks) = link_window(false, false);
let mut visual = VisualTestContext::from_window(window, &cx);
visual.simulate_click(point(px(20.), px(10.)), Modifiers::default());
assert_eq!(
visual.opened_url().as_deref(),
Some("https://example.com/release-notes"),
"the pointer click itself opens"
);
// Repaint with the link focused so its Enter/Space handlers register.
draw(&mut cx, window);
cx.update_window(window, |_, window, cx| {
window.dispatch_event(
KeyDownEvent {
keystroke: Keystroke::parse("enter").unwrap(),
is_held: false,
prefer_character_input: false,
}
.to_platform_input(),
cx,
);
window.dispatch_event(
KeyUpEvent {
keystroke: Keystroke::parse("enter").unwrap(),
}
.to_platform_input(),
cx,
);
})
.unwrap();
assert_eq!(*clicks.borrow(), 0, "Enter re-opens through the platform");
assert_eq!(
visual.opened_url().as_deref(),
Some("https://example.com/release-notes")
);
}
-523
View File
@@ -1,523 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, DefiniteLength, IntoElement, Modifiers, MouseButton, ParentElement as _, Render,
Styled as _, TestAppContext, VisualTestContext, Window, WindowHandle, div, point, px,
};
use gpui_native_core::menu::{Menu, MenuItem};
use gpui_native_theme::Theme;
struct Harness {
open: bool,
min_width: Option<DefiniteLength>,
changes: Rc<RefCell<Vec<bool>>>,
activated: Rc<RefCell<Vec<&'static str>>>,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
let activated = self.activated.clone();
let mut menu = Menu::new("test-menu")
.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()
.w(px(100.))
.h(px(32.))
.bg(gpui::black())
.into_any_element()
})
.items(move |_, _| {
vec![
cut_item(activated.clone()),
MenuItem::separator(),
copy_item(activated.clone()),
MenuItem::new("Unavailable").disabled(true).handler({
let activated = activated.clone();
move |_, _| record(&activated, "unavailable")
}),
delete_item(activated.clone()),
]
});
if let Some(width) = self.min_width {
menu = menu.min_width(width);
}
div().size_full().child(menu)
}
}
fn cut_item(activated: Rc<RefCell<Vec<&'static str>>>) -> MenuItem {
MenuItem::new("Cut")
.shortcut("cmd-x")
.handler(move |_, _| record(&activated, "cut"))
}
fn copy_item(activated: Rc<RefCell<Vec<&'static str>>>) -> MenuItem {
MenuItem::new("Copy").handler(move |_, _| record(&activated, "copy"))
}
fn delete_item(activated: Rc<RefCell<Vec<&'static str>>>) -> MenuItem {
MenuItem::new("Delete")
.destructive(true)
.handler(move |_, _| record(&activated, "delete"))
}
fn action_item(
label: &'static str,
key: &'static str,
activated: Rc<RefCell<Vec<&'static str>>>,
) -> MenuItem {
MenuItem::new(label).handler(move |_, _| record(&activated, key))
}
fn submenu_item(activated: Rc<RefCell<Vec<&'static str>>>) -> MenuItem {
MenuItem::new("Export").submenu(vec![
action_item("PNG", "png", activated.clone()),
action_item("PDF", "pdf", activated.clone()),
])
}
/// A menu with an Export row whose flyout holds PNG and PDF actions.
struct SubmenuHarness {
open: bool,
changes: Rc<RefCell<Vec<bool>>>,
activated: Rc<RefCell<Vec<&'static str>>>,
}
impl Render for SubmenuHarness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
let activated = self.activated.clone();
div().size_full().child(
Menu::new("test-submenu")
.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()
.w(px(100.))
.h(px(32.))
.bg(gpui::black())
.into_any_element()
})
.items(move |_, _| {
vec![
action_item("Cut", "cut", activated.clone()),
submenu_item(activated.clone()),
action_item("Delete", "delete", activated.clone()),
]
}),
)
}
}
fn record(sink: &Rc<RefCell<Vec<&'static str>>>, what: &'static str) {
sink.borrow_mut().push(what);
}
type Changes = Rc<RefCell<Vec<bool>>>;
type Activated = Rc<RefCell<Vec<&'static str>>>;
fn menu_window(
open: bool,
) -> (
TestAppContext,
VisualTestContext,
WindowHandle<Harness>,
Changes,
Activated,
) {
menu_window_with(open, None)
}
fn menu_window_with(
open: bool,
min_width: Option<DefiniteLength>,
) -> (
TestAppContext,
VisualTestContext,
WindowHandle<Harness>,
Changes,
Activated,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let activated = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let harness_activated = activated.clone();
let window = cx.add_window(move |_, _| Harness {
open,
min_width,
changes: harness_changes,
activated: harness_activated,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, window, changes, activated)
}
fn submenu_window(open: bool) -> (TestAppContext, VisualTestContext, Changes, Activated) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let activated = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let harness_activated = activated.clone();
let window = cx.add_window(move |_, _| SubmenuHarness {
open,
changes: harness_changes,
activated: harness_activated,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, changes, activated)
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
visual.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
}
fn hover(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_move(position, None, Modifiers::default());
}
fn center(bounds: gpui::Bounds<gpui::Pixels>) -> gpui::Point<gpui::Pixels> {
point(
bounds.origin.x + bounds.size.width / 2.,
bounds.origin.y + bounds.size.height / 2.,
)
}
/// 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);
// Nothing is highlighted when the menu opens; down arms the first
// selectable item, the next down crosses the separator to Copy, and
// enter activates it, closing the menu.
visual.simulate_keystrokes("down down enter");
draw(&mut visual);
assert_eq!(*activated.borrow(), vec!["copy"]);
assert_eq!(*changes.borrow(), vec![false]);
// Reopen: pointer opens highlight nothing again, and end jumps straight
// to the last selectable item, over the separator and the disabled row.
click(&mut visual, point(px(10.), px(16.)));
draw(&mut visual);
visual.simulate_keystrokes("end");
visual.simulate_keystrokes("enter");
assert_eq!(*activated.borrow(), vec!["copy", "delete"]);
assert_eq!(*changes.borrow(), vec![false, true, false]);
}
#[test]
fn enter_without_navigation_activates_nothing() {
let (_cx, mut visual, _window, changes, activated) = menu_window(true);
// A pointer-opened menu arms no row, so enter cannot fire one and the
// menu stays open.
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert!(activated.borrow().is_empty());
assert!(changes.borrow().is_empty(), "the menu stays open");
}
#[test]
fn escape_dismisses_without_activating() {
let (_cx, mut visual, _window, changes, activated) = menu_window(true);
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![false]);
assert!(activated.borrow().is_empty());
// A closed menu is inert.
draw(&mut visual);
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn clicking_outside_dismisses_and_swallows_the_click() {
let (_cx, mut visual, _window, changes, activated) = menu_window(true);
click(&mut visual, point(px(600.), px(600.)));
assert_eq!(*changes.borrow(), vec![false]);
assert!(activated.borrow().is_empty());
draw(&mut visual);
click(&mut visual, point(px(600.), px(600.)));
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn clicking_an_item_activates_and_closes() {
let (_cx, mut visual, _window, changes, activated) = menu_window(true);
// The first row hangs just below the trigger's panel padding.
click(&mut visual, point(px(60.), px(50.)));
assert_eq!(*activated.borrow(), vec!["cut"]);
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn right_arrow_opens_the_submenu_and_enter_within_activates_through() {
let (_cx, mut visual, changes, activated) = submenu_window(true);
// down arms Cut, the next down reaches Export, right opens its flyout
// with the first row armed.
visual.simulate_keystrokes("down down right");
draw(&mut visual);
assert!(visual.debug_bounds("submenu-item-0").is_some());
assert!(changes.borrow().is_empty(), "the menu stays open");
assert!(activated.borrow().is_empty());
// Enter inside the flyout fires PNG and closes the whole menu.
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*activated.borrow(), vec!["png"]);
assert_eq!(*changes.borrow(), vec![false]);
assert!(visual.debug_bounds("submenu-item-0").is_none());
}
#[test]
fn enter_on_a_submenu_row_opens_it_and_navigates_within() {
let (_cx, mut visual, changes, activated) = submenu_window(true);
visual.simulate_keystrokes("down down enter");
draw(&mut visual);
assert!(visual.debug_bounds("submenu-item-0").is_some());
assert!(
changes.borrow().is_empty(),
"enter opens, it does not close"
);
// The flyout armed PNG; down reaches PDF and enter fires it.
visual.simulate_keystrokes("down enter");
draw(&mut visual);
assert_eq!(*activated.borrow(), vec!["pdf"]);
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn left_closes_the_submenu_and_returns_to_the_menu() {
let (_cx, mut visual, changes, activated) = submenu_window(true);
visual.simulate_keystrokes("down down right");
draw(&mut visual);
visual.simulate_keystrokes("left");
draw(&mut visual);
assert!(visual.debug_bounds("submenu-item-0").is_none());
assert!(changes.borrow().is_empty(), "the menu stays open");
assert!(activated.borrow().is_empty());
// Navigation resumes in the parent: down reaches Delete, enter fires it.
visual.simulate_keystrokes("down enter");
draw(&mut visual);
assert_eq!(*activated.borrow(), vec!["delete"]);
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn escape_closes_the_submenu_then_the_menu() {
let (_cx, mut visual, changes, activated) = submenu_window(true);
visual.simulate_keystrokes("down down right");
draw(&mut visual);
visual.simulate_keystrokes("escape");
draw(&mut visual);
assert!(visual.debug_bounds("submenu-item-0").is_none());
assert!(
changes.borrow().is_empty(),
"the first escape only closes the flyout"
);
visual.simulate_keystrokes("escape");
draw(&mut visual);
assert_eq!(*changes.borrow(), vec![false]);
assert!(activated.borrow().is_empty());
}
#[test]
fn clicking_a_submenu_row_opens_the_flyout_and_a_flyout_action_closes_the_menu() {
let (_cx, mut visual, changes, activated) = submenu_window(true);
let row = visual
.debug_bounds("menu-item-1")
.unwrap_or_else(|| panic!("the Export row should have been laid out"));
click(
&mut visual,
point(
row.origin.x + row.size.width / 2.,
row.origin.y + row.size.height / 2.,
),
);
draw(&mut visual);
assert!(visual.debug_bounds("submenu-item-0").is_some());
assert!(changes.borrow().is_empty());
let png = visual
.debug_bounds("submenu-item-0")
.unwrap_or_else(|| panic!("the PNG row should have been laid out"));
click(
&mut visual,
point(
png.origin.x + png.size.width / 2.,
png.origin.y + png.size.height / 2.,
),
);
draw(&mut visual);
assert_eq!(*activated.borrow(), vec!["png"]);
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn a_click_inside_the_flyout_padding_does_not_dismiss_the_menu() {
let (_cx, mut visual, changes, _activated) = submenu_window(true);
let row = visual.debug_bounds("menu-item-1").unwrap();
click(
&mut visual,
point(
row.origin.x + row.size.width / 2.,
row.origin.y + row.size.height / 2.,
),
);
draw(&mut visual);
// The flyout's own padding belongs to the flyout, not to the dismissal
// listener of the panel behind it.
let panel = visual.debug_bounds("submenu-panel").unwrap();
click(
&mut visual,
point(
panel.origin.x + px(4.),
panel.size.height + panel.origin.y - px(2.),
),
);
draw(&mut visual);
assert!(changes.borrow().is_empty(), "the flyout stays open");
assert!(visual.debug_bounds("submenu-item-0").is_some());
// A click outside everything still closes the whole menu.
click(&mut visual, point(px(600.), px(600.)));
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn hovering_a_submenu_row_opens_its_flyout_and_an_action_row_closes_it() {
let (_cx, mut visual, changes, _activated) = submenu_window(true);
let export = visual.debug_bounds("menu-item-1").unwrap();
hover(&mut visual, center(export));
draw(&mut visual);
assert!(
visual.debug_bounds("submenu-item-0").is_some(),
"hover opens the flyout"
);
assert!(changes.borrow().is_empty(), "the menu stays open");
let cut = visual.debug_bounds("menu-item-0").unwrap();
hover(&mut visual, center(cut));
draw(&mut visual);
assert!(
visual.debug_bounds("submenu-item-0").is_none(),
"hovering an action row closes the flyout"
);
assert!(changes.borrow().is_empty(), "the menu stays open");
}
#[test]
fn the_flyout_overlaps_the_parent_from_the_rows_right_edge() {
let (_cx, mut visual, _changes, _activated) = submenu_window(true);
let export = visual.debug_bounds("menu-item-1").unwrap();
hover(&mut visual, center(export));
draw(&mut visual);
let parent = visual.debug_bounds("menu-panel").unwrap();
let flyout = visual.debug_bounds("submenu-panel").unwrap();
let parent_right = parent.origin.x + parent.size.width;
let row_right = export.origin.x + export.size.width;
// macOS style: the flyout covers the parent's trailing padding, starting
// at the row's right edge.
assert!(
flyout.origin.x < parent_right - px(1.),
"the flyout starts at {:?}, inside the parent edge at {:?}",
flyout.origin.x,
parent_right
);
assert!(
flyout.origin.x >= row_right - px(1.),
"the flyout starts at {:?}, at or after the row's right edge {:?}",
flyout.origin.x,
row_right
);
}
#[test]
fn a_custom_min_width_overrides_the_default_panel_width() {
let (_cx, mut visual, _window, _changes, _activated) = menu_window(true);
let default_width = visual.debug_bounds("menu-panel").unwrap().size.width;
let (_cx, mut visual, _window, _changes, _activated) =
menu_window_with(true, Some(px(320.).into()));
let width = visual.debug_bounds("menu-panel").unwrap().size.width;
// Painted bounds are snapped to device pixels; allow half a pixel.
assert!(
(width - px(320.)).abs() <= px(0.5),
"the panel is {width:?} wide, expected the 320px minimum"
);
assert!(
width > default_width,
"the default panel is {:?} wide and should be narrower",
default_width
);
}
-212
View File
@@ -1,212 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, InteractiveElement as _, IntoElement, Modifiers, MouseButton, ParentElement as _,
Render, StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext,
Window, WindowHandle, div, point, px,
};
use gpui_native_core::popover::Popover;
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(
div().absolute().left(px(400.)).top(px(300.)).child(
div()
.id("popover-target")
.size(px(40.))
.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.))
.into_any_element()
})
.content(|_, _| {
div()
.w(px(200.))
.h(px(80.))
.child("Popover content")
.into_any_element()
}),
)
}
}
/// A window whose popover trigger sits in the top-left corner: the panel
/// 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.
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, target_clicks)
}
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
visual.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
}
#[test]
fn clicking_outside_dismisses_and_reports_closed() {
let (_cx, mut visual, _window, changes, _clicks) = popover_window(true);
click(&mut visual, point(px(600.), px(600.)));
assert_eq!(*changes.borrow(), vec![false]);
// The dismissal swallowed the click and the owner closed the popover:
// the redraw renders without a panel, and nothing further fires.
draw(&mut visual);
click(&mut visual, point(px(600.), px(600.)));
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn clicking_the_trigger_toggles_and_clicking_the_panel_does_nothing() {
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.)));
assert_eq!(*changes.borrow(), vec![false]);
// On the panel itself: nothing.
click(&mut visual, point(px(100.), px(70.)));
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn clicking_the_trigger_opens_a_closed_popover() {
let (_cx, mut visual, _window, changes, _clicks) = popover_window(false);
click(&mut visual, point(px(10.), px(16.)));
assert_eq!(*changes.borrow(), vec![true]);
}
#[test]
fn escape_dismisses_while_the_panel_holds_focus() {
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.
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![false]);
// A closed popover is inert: no further dismissal events.
draw(&mut visual);
visual.simulate_keystrokes("escape");
assert_eq!(*changes.borrow(), vec![false]);
}
#[test]
fn the_controlled_loop_reopens_from_the_app_side() {
let (mut cx, mut visual, window, changes, _clicks) = popover_window(true);
// Dismiss once.
click(&mut visual, point(px(600.), px(600.)));
assert_eq!(*changes.borrow(), vec![false]);
draw(&mut visual);
// Reopen through the harness view: the app-driven half of the loop
// reports no event of its own.
window
.update(&mut cx, |harness, _, cx| {
harness.open = true;
cx.notify();
})
.unwrap();
draw(&mut visual);
// The panel is back and holds focus again: escape dismisses once more.
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:?}"
);
}
-121
View File
@@ -1,121 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke,
Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window,
div, point, px,
};
use gpui_native_core::radio::{Radio, RadioGroup};
use gpui_native_theme::Theme;
struct Harness {
changes: Rc<RefCell<Vec<&'static str>>>,
selected: Option<&'static str>,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().flex().flex_col().child(
RadioGroup::new("test-group")
.selected(self.selected)
.on_change(move |value, _, cx| {
changes.borrow_mut().push(value);
view.update(cx, |harness, cx| {
harness.selected = Some(value);
cx.notify();
});
})
.child(Radio::new("radio-a", "a").label("Option A"))
.child(Radio::new("radio-b", "b").label("Option B"))
.child(
Radio::new("radio-off", "c")
.label("Disabled")
.disabled(true),
),
)
}
}
/// A maximized window whose radio rows sit at the top-left: row 1 spans
/// roughly y 0..21, row 2 y 29..50, so `(8, 10)` and `(8, 40)` hit them.
fn group_window(
selected: Option<&'static str>,
) -> (
VisualTestContext,
AnyWindowHandle,
Rc<RefCell<Vec<&'static str>>>,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
changes: harness_changes,
selected,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(VisualTestContext::from_window(window, &cx), window, changes)
}
fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
#[test]
fn clicking_reports_values_through_the_controlled_loop() {
let (mut cx, _window, changes) = group_window(None);
cx.simulate_click(point(px(8.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec!["a"]);
cx.simulate_click(point(px(8.), px(40.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec!["a", "b"]);
}
#[test]
fn clicking_the_selected_radio_never_unchecks_it() {
let (mut cx, _window, changes) = group_window(Some("a"));
cx.simulate_click(point(px(8.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec!["a"], "re-reports the same value");
}
#[test]
fn disabled_radio_does_not_report_changes() {
let (mut cx, _window, changes) = group_window(None);
cx.simulate_click(point(px(8.), px(70.)), Modifiers::default());
assert!(changes.borrow().is_empty());
}
#[test]
fn enter_and_space_report_the_focused_radio_value() {
let (mut cx, window, changes) = group_window(None);
cx.simulate_click(point(px(8.), px(10.)), Modifiers::default());
assert_eq!(
*changes.borrow(),
vec!["a"],
"the pointer click itself selects"
);
// Repaint with the first radio focused so its Enter/Space handlers register.
draw(&mut cx, window);
for key in ["enter", "space"] {
cx.simulate_event(KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
assert_eq!(*changes.borrow(), vec!["a", "a", "a"]);
}
-190
View File
@@ -1,190 +0,0 @@
use gpui::{
Context, InteractiveElement as _, IntoElement, Modifiers, ParentElement as _, Render,
ScrollDelta, ScrollEvent, ScrollHandle, SharedString, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
};
use gpui_native_core::scroll_area::ScrollArea;
use gpui_native_theme::Theme;
struct Harness {
scroll: ScrollHandle,
rows: usize,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
ScrollArea::new("test-scroll")
.handle(self.scroll.clone())
.h(px(200.))
.w(px(300.))
.child(div().flex().flex_col().children((0..self.rows).map(|row| {
div()
.h(px(20.))
.child(SharedString::from(format!("row {row}")))
}))),
)
}
}
/// A 300×200 scroll area over `rows` 20px rows, with the handle the test
/// can inspect directly.
fn scroll_area_window(rows: usize) -> (TestAppContext, VisualTestContext, ScrollHandle) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let handle = ScrollHandle::new();
let handle_for_view = handle.clone();
let window = cx.add_window(move |_, _| Harness {
scroll: handle_for_view,
rows,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, handle)
}
#[test]
fn wheel_scrolling_moves_the_offset_and_stays_inside_the_content() {
let (_cx, mut visual, handle) = scroll_area_window(30);
// 30 rows × 20px = 600px of content in a 200px viewport.
visual.simulate_event(ScrollEvent {
position: point(px(100.), px(100.)),
delta: ScrollDelta::Pixels(point(px(0.), px(-60.))),
modifiers: Modifiers::default(),
..Default::default()
});
let offset = handle.offset().y;
assert_eq!(offset, px(-60.));
// Wheeling far past the end clamps to the content.
for _ in 0..10 {
visual.simulate_event(ScrollEvent {
position: point(px(100.), px(100.)),
delta: ScrollDelta::Pixels(point(px(0.), px(-60.))),
modifiers: Modifiers::default(),
..Default::default()
});
}
// max_offset = 600 - 200 = 400.
assert_eq!(handle.offset().y, px(-400.));
}
#[test]
fn the_content_starts_unscrolled_and_horizontal_axes_scroll_x() {
let (_cx, mut visual, handle) = scroll_area_window(30);
assert_eq!(handle.offset(), gpui::point(px(0.), px(0.)));
// A vertical-only area ignores horizontal wheel deltas.
visual.simulate_event(ScrollEvent {
position: point(px(100.), px(100.)),
delta: ScrollDelta::Pixels(point(px(-60.), px(0.))),
modifiers: Modifiers::default(),
..Default::default()
});
assert_eq!(handle.offset().x, 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 {
scroll: ScrollHandle,
}
impl Render for GalleryShell {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
ScrollArea::new("gallery-scroll")
.handle(self.scroll.clone())
.size_full()
.child(
div()
.p_6()
.flex()
.flex_col()
.gap_5()
.children((0..12).map(|section| {
div()
.h(px(220.))
.child(SharedString::from(format!("section {section}")))
})),
),
)
}
}
/// A window-filling scroll area with `p_4`, over one full-width row.
struct PaddedShell {
scroll: ScrollHandle,
}
impl Render for PaddedShell {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.debug_selector(|| "padded-root".to_string())
.child(
ScrollArea::new("padded-scroll")
.handle(self.scroll.clone())
.size_full()
.p_4()
.child(
div()
.debug_selector(|| "padded-row".to_string())
.h(px(20.))
.w_full(),
),
)
}
}
#[test]
fn padding_insets_the_content_exactly_once() {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let handle = ScrollHandle::new();
let handle_for_view = handle.clone();
let window = cx.add_window(move |_, _| PaddedShell {
scroll: handle_for_view,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
let root = visual.debug_bounds("padded-root").expect("root rendered");
let row = visual.debug_bounds("padded-row").expect("row rendered");
// p_4 = 16px: the padding reaches only the wrapper, so the content is
// inset once, not once per wrapper and scroll pane.
assert_eq!(row.origin.x - root.origin.x, px(16.));
assert_eq!(root.size.width - row.size.width, px(32.));
}
#[test]
fn a_gallery_style_window_fill_scroll_area_scrolls_tall_flex_content() {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let handle = ScrollHandle::new();
let handle_for_view = handle.clone();
let window = cx.add_window(move |_, _| GalleryShell {
scroll: handle_for_view,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
// 12 sections × 220px + padding towers past the window; a wheel event
// over the middle of the viewport must scroll the root area.
visual.simulate_event(ScrollEvent {
position: point(px(300.), px(300.)),
delta: ScrollDelta::Pixels(point(px(0.), px(-60.))),
modifiers: Modifiers::default(),
..Default::default()
});
assert_eq!(handle.offset().y, px(-60.));
assert!(handle.max_offset().y > px(1000.));
}
-369
View File
@@ -1,369 +0,0 @@
use gpui::{
Bounds, Context, IntoElement, ListAlignment, ListState, MouseButton, MouseDownEvent,
MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, Render, Styled as _,
TestAppContext, UniformListScrollHandle, VisualTestContext, Window, div, list, point, px,
uniform_list,
};
use gpui_native_core::init;
use gpui_native_core::scrollbar::{Scrollbar, ScrollbarHandle};
use gpui_native_theme::ActiveTheme as _;
use std::cell::RefCell;
use std::rc::Rc;
const ROWS: usize = 50;
const ROW_HEIGHT: f32 = 24.;
const VIEWPORT_HEIGHT: f32 = 300.;
struct UniformShell {
rows: usize,
handle: UniformListScrollHandle,
renders: Rc<RefCell<usize>>,
}
impl Render for UniformShell {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
*self.renders.borrow_mut() += 1;
div().size_full().child(
div()
.relative()
.h(px(VIEWPORT_HEIGHT))
.w(px(400.))
.child(
uniform_list("rows", self.rows, |range, _, _| {
range
.map(|ix| div().h(px(ROW_HEIGHT)).child(format!("row {ix}")))
.collect()
})
.track_scroll(&self.handle)
.h_full()
.w_full(),
)
.child(Scrollbar::vertical("rows", self.handle.clone())),
)
}
}
struct ListShell {
state: ListState,
}
impl Render for ListShell {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
div()
.relative()
.h(px(VIEWPORT_HEIGHT))
.w(px(400.))
.child(
list(self.state.clone(), |ix, _, _| {
div()
.h(px(ROW_HEIGHT))
.child(format!("row {ix}"))
.into_any_element()
})
.h_full()
.w_full(),
)
.child(Scrollbar::vertical("rows", self.state.clone())),
)
}
}
fn uniform_shell(
rows: usize,
) -> (
TestAppContext,
VisualTestContext,
UniformListScrollHandle,
Rc<RefCell<usize>>,
) {
let mut cx = TestAppContext::single();
cx.update(init);
let handle = UniformListScrollHandle::new();
let handle_for_view = handle.clone();
let renders = Rc::new(RefCell::new(0));
let renders_for_view = renders.clone();
let window = cx.add_window(move |_, _| UniformShell {
rows,
handle: handle_for_view,
renders: renders_for_view,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, handle, renders)
}
fn list_shell() -> (TestAppContext, VisualTestContext, ListState) {
let mut cx = TestAppContext::single();
cx.update(init);
let state =
ListState::new(ROWS, ListAlignment::Top, px(400.)).with_uniform_item_height(px(ROW_HEIGHT));
let state_for_view = state.clone();
let window = cx.add_window(move |_, _| ListShell {
state: state_for_view,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, state)
}
/// The scrollbar geometry the tests need, straight from the handle and the
/// theme the component reads.
struct Metrics {
viewport: Bounds<Pixels>,
max_offset: Pixels,
width: Pixels,
inset: Pixels,
min_thumb: Pixels,
}
impl Metrics {
fn measure(cx: &TestAppContext, handle: &impl ScrollbarHandle) -> Self {
cx.update(|cx| {
let theme = cx.theme();
Self {
viewport: handle.viewport(),
max_offset: handle.max_offset().y,
width: theme.scrollbar.width,
inset: theme.scrollbar.inset,
min_thumb: theme.scrollbar.min_thumb,
}
})
}
fn track_length(&self) -> Pixels {
self.viewport.size.height - self.inset * 2.0
}
fn thumb_length(&self) -> Pixels {
let content = self.viewport.size.height + self.max_offset;
(self.viewport.size.height / content * self.track_length())
.max(self.min_thumb)
.min(self.track_length())
}
fn thumb_center(&self) -> Point<Pixels> {
point(
self.viewport.right() - self.inset - self.width / 2.0,
self.viewport.top() + self.inset + self.thumb_length() / 2.0,
)
}
fn track_near_bottom(&self) -> Point<Pixels> {
point(
self.viewport.right() - self.inset - self.width / 2.0,
self.viewport.top() + self.inset + self.track_length() - px(1.),
)
}
fn full_drag_target(&self) -> Point<Pixels> {
point(
self.thumb_center().x,
self.thumb_center().y + (self.track_length() - self.thumb_length()),
)
}
}
fn press(visual: &mut VisualTestContext, position: Point<Pixels>) {
visual.simulate_event(MouseDownEvent {
button: MouseButton::Left,
position,
..Default::default()
});
}
fn drag_to(visual: &mut VisualTestContext, position: Point<Pixels>) {
visual.simulate_event(MouseMoveEvent {
position,
pressed_button: Some(MouseButton::Left),
..Default::default()
});
}
fn release(visual: &mut VisualTestContext, position: Point<Pixels>) {
visual.simulate_event(MouseUpEvent {
button: MouseButton::Left,
position,
..Default::default()
});
}
#[test]
fn dragging_the_thumb_scrolls_the_uniform_list() {
let (cx, mut visual, handle, renders) = uniform_shell(ROWS);
let metrics = Metrics::measure(&cx, &handle);
assert!(
metrics.max_offset > px(0.),
"50 24px rows overflow a 300px viewport"
);
press(&mut visual, metrics.thumb_center());
let renders_after_press = *renders.borrow();
drag_to(&mut visual, metrics.full_drag_target());
let renders_after_move = *renders.borrow();
release(&mut visual, metrics.full_drag_target());
let offset = handle.offset().y;
assert!(
(offset.abs() - metrics.max_offset).abs() < px(0.5),
"a full drag reaches the end, got {offset}"
);
assert!(
renders_after_move > renders_after_press,
"dragging must repaint the owning view, or the scroll never shows"
);
}
#[test]
fn clicking_the_track_jumps_to_the_position() {
let (cx, mut visual, handle, _) = uniform_shell(ROWS);
let metrics = Metrics::measure(&cx, &handle);
press(&mut visual, metrics.track_near_bottom());
release(&mut visual, metrics.track_near_bottom());
let offset = handle.offset().y;
assert!(
(offset.abs() - metrics.max_offset).abs() < px(0.5),
"a track click near the bottom jumps to the end, got {offset}"
);
}
#[test]
fn a_fitted_list_ignores_the_scrollbar() {
let (cx, mut visual, handle, _) = uniform_shell(5);
let metrics = Metrics::measure(&cx, &handle);
assert_eq!(metrics.max_offset, px(0.), "5 rows fit the viewport");
press(&mut visual, metrics.track_near_bottom());
drag_to(&mut visual, metrics.full_drag_target());
release(&mut visual, metrics.full_drag_target());
assert_eq!(handle.offset().y, px(0.), "nothing scrolled");
}
#[test]
fn dragging_the_thumb_drives_a_list_state_and_reports_the_drag() {
let (cx, mut visual, state) = list_shell();
let metrics = Metrics::measure(&cx, &state);
assert!(metrics.max_offset > px(0.));
press(&mut visual, metrics.thumb_center());
assert!(
state.is_scrollbar_dragging(),
"the drag freezes the list's measured height"
);
drag_to(&mut visual, metrics.full_drag_target());
let offset = state.offset().y;
assert!(
(offset.abs() - metrics.max_offset).abs() < px(0.5),
"a full drag reaches the end, got {offset}"
);
release(&mut visual, metrics.full_drag_target());
assert!(
!state.is_scrollbar_dragging(),
"the drag ends with the mouse"
);
}
struct TwoShell {
left: UniformListScrollHandle,
right: UniformListScrollHandle,
}
impl Render for TwoShell {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.flex_row()
.child(
div()
.relative()
.h(px(VIEWPORT_HEIGHT))
.w(px(300.))
.child(
uniform_list("left-rows", ROWS, |range, _, _| {
range
.map(|ix| div().h(px(ROW_HEIGHT)).child(format!("row {ix}")))
.collect()
})
.track_scroll(&self.left)
.h_full()
.w_full(),
)
.child(Scrollbar::vertical("left", self.left.clone())),
)
.child(
div()
.relative()
.h(px(VIEWPORT_HEIGHT))
.w(px(300.))
.child(
uniform_list("right-rows", ROWS, |range, _, _| {
range
.map(|ix| div().h(px(ROW_HEIGHT)).child(format!("row {ix}")))
.collect()
})
.track_scroll(&self.right)
.h_full()
.w_full(),
)
.child(Scrollbar::vertical("right", self.right.clone())),
)
}
}
fn two_shell() -> (
TestAppContext,
VisualTestContext,
UniformListScrollHandle,
UniformListScrollHandle,
) {
let mut cx = TestAppContext::single();
cx.update(init);
let (left, right) = (
UniformListScrollHandle::new(),
UniformListScrollHandle::new(),
);
let (left_for_view, right_for_view) = (left.clone(), right.clone());
let window = cx.add_window(move |_, _| TwoShell {
left: left_for_view,
right: right_for_view,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, left, right)
}
/// Dragging one scrollbar's thumb must never move a sibling scrollbar: the
/// drag state is keyed per scrollbar id, not shared across instances.
#[test]
fn sibling_scrollbars_drag_independently() {
let (cx, mut visual, left, right) = two_shell();
let metrics = Metrics::measure(&cx, &left);
assert!(metrics.max_offset > px(0.));
press(&mut visual, metrics.thumb_center());
drag_to(&mut visual, metrics.full_drag_target());
release(&mut visual, metrics.full_drag_target());
let offset = left.offset().y;
assert!(
(offset.abs() - metrics.max_offset).abs() < px(0.5),
"the left drag reaches the end, got {offset}"
);
assert_eq!(
right.offset().y,
px(0.),
"the left drag leaked into the right scrollbar"
);
}
-123
View File
@@ -1,123 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, IntoElement, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
};
use gpui_native_core::segmented::Segmented;
use gpui_native_theme::Theme;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Filter {
All,
Popular,
Recent,
}
const FILTERS: [(Filter, &str); 3] = [
(Filter::All, "All"),
(Filter::Popular, "Popular"),
(Filter::Recent, "Recent"),
];
type Changes = Rc<RefCell<Vec<Filter>>>;
struct Harness {
filter: Filter,
changes: Changes,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().p_4().child(
Segmented::new("filter", self.filter)
.options(FILTERS)
.on_change(move |next, _window, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.filter = next;
cx.notify();
});
}),
)
}
}
fn filter_window() -> (TestAppContext, VisualTestContext, Changes) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
filter: Filter::All,
changes: harness_changes,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, changes)
}
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());
}
/// The strip hugs its labels in the `p_4` band: the three segments span
/// roughly `18..142` horizontally and `17.6..33.9` vertically (macOS's 13 pt
/// root font), so clicks land near `32` (All), `70` (Popular), and `118`
/// (Recent).
#[test]
fn clicking_a_segment_reports_it() {
let (_cx, mut visual, changes) = filter_window();
click(&mut visual, point(px(70.), px(27.)));
assert_eq!(*changes.borrow(), vec![Filter::Popular]);
click(&mut visual, point(px(118.), px(27.)));
assert_eq!(*changes.borrow(), vec![Filter::Popular, Filter::Recent]);
}
#[test]
fn re_clicking_the_selected_segment_reports_nothing() {
let (_cx, mut visual, changes) = filter_window();
click(&mut visual, point(px(70.), px(27.)));
assert_eq!(*changes.borrow(), vec![Filter::Popular]);
click(&mut visual, point(px(70.), px(27.)));
assert_eq!(*changes.borrow(), vec![Filter::Popular]);
}
#[test]
fn arrows_move_the_selection_when_the_strip_has_focus() {
let (_cx, mut visual, changes) = filter_window();
// Clicking a segment hands the strip the keyboard, like the list.
click(&mut visual, point(px(32.), px(27.)));
visual.simulate_keystrokes("right");
assert_eq!(*changes.borrow(), vec![Filter::Popular]);
visual.simulate_keystrokes("right");
assert_eq!(*changes.borrow(), vec![Filter::Popular, Filter::Recent]);
// The strip never wraps: right on the last segment reports nothing.
visual.simulate_keystrokes("right");
assert_eq!(*changes.borrow(), vec![Filter::Popular, Filter::Recent]);
// Home and end jump to the ends.
visual.simulate_keystrokes("home");
assert_eq!(
*changes.borrow(),
vec![Filter::Popular, Filter::Recent, Filter::All]
);
visual.simulate_keystrokes("end");
assert_eq!(
*changes.borrow(),
vec![Filter::Popular, Filter::Recent, Filter::All, Filter::Recent]
);
}
-286
View File
@@ -1,286 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
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::{ActiveTheme as _, BORDER_WIDTH, Theme};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Strategy {
Curated,
Uncensored,
}
const STRATEGIES: [(Strategy, &str); 2] = [
(Strategy::Curated, "Curated"),
(Strategy::Uncensored, "Uncensored"),
];
type Changes = Rc<RefCell<Vec<Option<Strategy>>>>;
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
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());
}
struct Harness {
strategy: Option<Strategy>,
changes: Changes,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().p_4().child(
Select::new("strategy")
.options(STRATEGIES)
.selected(self.strategy)
.on_change(move |next, _window, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.strategy = next;
cx.notify();
});
}),
)
}
}
/// One select: trigger band is `16..46` vertically (`p_4` + the 30 px field).
fn select_window() -> (TestAppContext, VisualTestContext, Changes) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
strategy: None,
changes: harness_changes,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
draw(&mut visual);
(cx, visual, changes)
}
struct Pair {
first: Option<Strategy>,
second: Option<Strategy>,
first_changes: Changes,
second_changes: Changes,
}
impl Render for Pair {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let view = cx.entity();
let first_changes = self.first_changes.clone();
let second_changes = self.second_changes.clone();
let first_view = view.clone();
let second_view = view.clone();
div().size_full().p_4().child(
div()
.flex()
.flex_col()
.gap_2()
.child(
Select::new("first")
.options(STRATEGIES)
.selected(self.first)
.on_change(move |next, _window, cx| {
first_changes.borrow_mut().push(next);
first_view.update(cx, |pair, cx| {
pair.first = next;
cx.notify();
});
}),
)
.child(
Select::new("second")
.options(STRATEGIES)
.selected(self.second)
.on_change(move |next, _window, cx| {
second_changes.borrow_mut().push(next);
second_view.update(cx, |pair, cx| {
pair.second = next;
cx.notify();
});
}),
),
)
}
}
/// Two selects: bands `16..46` and `54..84` (the 8 px gap between).
fn pair_window() -> (TestAppContext, VisualTestContext, Changes, Changes) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let first_changes = Rc::new(RefCell::new(Vec::new()));
let second_changes = Rc::new(RefCell::new(Vec::new()));
let first = first_changes.clone();
let second = second_changes.clone();
let window = cx.add_window(move |_, _| Pair {
first: None,
second: None,
first_changes: first,
second_changes: second,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
draw(&mut visual);
(cx, visual, first_changes, second_changes)
}
#[test]
fn choosing_an_option_reports_the_value_and_closes() {
let (_cx, mut visual, changes) = select_window();
// The trigger opens the popup; with no value yet nothing is armed, so
// the first Enter does nothing and the next Down arms the first option.
click(&mut visual, point(px(100.), px(31.)));
draw(&mut visual);
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*changes.borrow(), Vec::<Option<Strategy>>::new());
visual.simulate_keystrokes("down enter");
draw(&mut visual);
assert_eq!(*changes.borrow(), vec![Some(Strategy::Curated)]);
// The popup closed with the choice, so another Enter reports nothing.
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(*changes.borrow(), vec![Some(Strategy::Curated)]);
// The trigger reopens with the chosen value armed; the next option is
// one Down away.
click(&mut visual, point(px(100.), px(31.)));
draw(&mut visual);
visual.simulate_keystrokes("down");
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(
*changes.borrow(),
vec![Some(Strategy::Curated), Some(Strategy::Uncensored)]
);
}
#[test]
fn the_controlled_value_round_trips_through_the_owner() {
let (_cx, mut visual, changes) = select_window();
click(&mut visual, point(px(100.), px(31.)));
draw(&mut visual);
visual.simulate_keystrokes("down down");
visual.simulate_keystrokes("enter");
draw(&mut visual);
// The harness stored the reported value, so the select now holds it;
// reopening arms it and Enter reports it straight back.
click(&mut visual, point(px(100.), px(31.)));
draw(&mut visual);
visual.simulate_keystrokes("enter");
draw(&mut visual);
assert_eq!(
*changes.borrow(),
vec![Some(Strategy::Uncensored), Some(Strategy::Uncensored)]
);
}
#[test]
fn two_selects_keep_their_popups_independent() {
let (_cx, mut visual, first_changes, second_changes) = pair_window();
// Opening the second select never touches the first.
click(&mut visual, point(px(100.), px(69.)));
draw(&mut visual);
visual.simulate_keystrokes("down enter");
draw(&mut visual);
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("down 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));
}
-118
View File
@@ -1,118 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, IntoElement, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
};
use gpui_native_core::select::Select;
use gpui_native_theme::Theme;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Level {
Low,
Mid,
High,
}
const LEVELS: [(Level, &str); 3] = [
(Level::Low, "Low"),
(Level::Mid, "Mid"),
(Level::High, "High"),
];
type Changes = Rc<RefCell<Vec<Option<Level>>>>;
struct Harness {
value: Option<Level>,
changes: Changes,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().p_4().child(
Select::new("level")
.options(LEVELS)
.selected(self.value)
.on_change(move |next, _window, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.value = next;
cx.notify();
});
}),
)
}
}
fn level_window() -> (TestAppContext, VisualTestContext, Changes) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
value: None,
changes: harness_changes,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, changes)
}
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());
}
/// 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();
// 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, centers[index]);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
assert_eq!(
changes.borrow().last(),
Some(&Some(value)),
"pressing {value:?}'s row must choose it"
);
}
}
-61
View File
@@ -1,61 +0,0 @@
use gpui::{
AppContext as _, Context, IntoElement, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, px,
};
use gpui_native_core::separator::{Separator, SeparatorOrientation};
use gpui_native_theme::{BORDER_WIDTH, Theme};
struct Harness {
orientation: SeparatorOrientation,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let separator = Separator::horizontal()
.orientation(self.orientation)
.debug_selector(|| "test-separator".to_string());
if self.orientation == SeparatorOrientation::Horizontal {
div()
.w(px(200.))
.h(px(50.))
.flex()
.flex_col()
.child(separator)
} else {
div().w(px(200.)).h(px(50.)).flex().child(separator)
}
}
}
fn separator_window(orientation: SeparatorOrientation) -> (TestAppContext, VisualTestContext) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let window = cx.add_window(move |_, _| Harness { orientation });
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
let visual = VisualTestContext::from_window(window, &cx);
(cx, visual)
}
#[test]
fn the_horizontal_rule_spans_its_container_at_hairline_height() {
let (_cx, mut visual) = separator_window(SeparatorOrientation::Horizontal);
let bounds = visual
.debug_bounds("test-separator")
.expect("horizontal separator rendered");
assert_eq!(bounds.size.width, px(200.));
assert_eq!(bounds.size.height, BORDER_WIDTH);
}
#[test]
fn the_vertical_rule_spans_its_container_at_hairline_width() {
let (_cx, mut visual) = separator_window(SeparatorOrientation::Vertical);
let bounds = visual
.debug_bounds("test-separator")
.expect("vertical separator rendered");
assert_eq!(bounds.size.width, BORDER_WIDTH);
assert_eq!(bounds.size.height, px(50.));
}
-284
View File
@@ -1,284 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, InputEvent as _, IntoElement, KeyDownEvent,
Keystroke, Modifiers, MouseButton, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, point, px,
};
use gpui_native_core::slider::Slider;
use gpui_native_theme::Theme;
struct Harness {
changes: Rc<RefCell<Vec<f32>>>,
value: f32,
disabled: bool,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().flex().flex_col().child(
div().w(px(200.)).child(
Slider::new("test-slider", self.value)
.min(0.0)
.max(100.0)
.step(10.0)
.disabled(self.disabled)
.on_change(move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.value = next;
cx.notify();
});
}),
),
)
}
}
/// A maximized window holding a 200px slider over 0..=100 stepped by 10 in
/// the top-left corner: `x` maps to `round(x / 200 * 10) * 10`.
fn slider_window(disabled: bool) -> (VisualTestContext, AnyWindowHandle, Rc<RefCell<Vec<f32>>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
changes: harness_changes,
value: 0.0,
disabled,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(VisualTestContext::from_window(window, &cx), window, changes)
}
fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
#[test]
fn clicking_the_track_sets_the_snapped_value() {
let (mut cx, _window, changes) = slider_window(false);
cx.simulate_click(point(px(100.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![50.0]);
cx.simulate_click(point(px(40.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![50.0, 20.0]);
}
#[test]
fn dragging_reports_values_until_release() {
let (mut cx, _window, changes) = slider_window(false);
cx.simulate_mouse_down(
point(px(40.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_move(
point(px(120.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_up(
point(px(120.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
assert_eq!(*changes.borrow(), vec![20.0, 60.0]);
// Moving after release must not change the value.
cx.simulate_mouse_move(
point(px(180.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
assert_eq!(*changes.borrow(), vec![20.0, 60.0]);
}
#[test]
fn drag_clamps_to_the_range_ends() {
let (mut cx, _window, changes) = slider_window(false);
cx.simulate_mouse_down(
point(px(100.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
// The drag captures the pointer: it keeps reporting past the track's
// right edge, clamped to the top of the range.
cx.simulate_mouse_move(
point(px(400.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
assert_eq!(*changes.borrow(), vec![50.0, 100.0]);
}
#[test]
fn disabled_slider_does_not_report_changes() {
let (mut cx, _window, changes) = slider_window(true);
cx.simulate_click(point(px(100.), px(10.)), Modifiers::default());
assert!(changes.borrow().is_empty());
}
#[test]
fn arrow_keys_step_the_value_while_focused() {
let (mut cx, window, changes) = slider_window(false);
// The click focuses the slider and sets the snapped value at that point.
cx.simulate_click(point(px(2.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![0.0]);
draw(&mut cx, window);
for key in ["right", "right", "left"] {
cx.update_window(window, |_, window, cx| {
window.dispatch_event(
KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
}
.to_platform_input(),
cx,
);
})
.unwrap();
}
assert_eq!(*changes.borrow(), vec![0.0, 10.0, 20.0, 10.0]);
}
struct TwoSliders {
changes_a: Rc<RefCell<Vec<f32>>>,
changes_b: Rc<RefCell<Vec<f32>>>,
value_a: f32,
value_b: f32,
}
impl Render for TwoSliders {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (changes_a, changes_b) = (self.changes_a.clone(), self.changes_b.clone());
div()
.size_full()
.child(
div().absolute().top_0().left_0().w(px(200.)).child(
Slider::new("slider-a", self.value_a)
.min(0.0)
.max(100.0)
.step(10.0)
.on_change({
let view = cx.entity();
let changes_a = changes_a.clone();
move |next, _, cx| {
changes_a.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.value_a = next;
cx.notify();
});
}
}),
),
)
.child(
div().absolute().top(px(40.)).left_0().w(px(200.)).child(
Slider::new("slider-b", self.value_b)
.min(0.0)
.max(100.0)
.step(10.0)
.on_change({
let view = cx.entity();
move |next, _, cx| {
changes_b.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.value_b = next;
cx.notify();
});
}
}),
),
)
}
}
#[allow(clippy::type_complexity)]
fn two_slider_window() -> (
VisualTestContext,
Rc<RefCell<Vec<f32>>>,
Rc<RefCell<Vec<f32>>>,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes_a = Rc::new(RefCell::new(Vec::new()));
let changes_b = Rc::new(RefCell::new(Vec::new()));
let (changes_a_for_window, changes_b_for_window) = (changes_a.clone(), changes_b.clone());
let window = cx.add_window(move |_, _| TwoSliders {
changes_a: changes_a_for_window,
changes_b: changes_b_for_window,
value_a: 0.0,
value_b: 0.0,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(
VisualTestContext::from_window(window, &cx),
changes_a,
changes_b,
)
}
/// Dragging one slider must never drive a sibling slider: the drag flag is
/// per instance, not shared keyed state.
#[test]
fn two_sliders_drag_independently() {
let (mut cx, changes_a, changes_b) = two_slider_window();
// Slider A occupies y 0..16, slider B starts at y 40.
cx.simulate_mouse_down(
point(px(100.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_move(
point(px(120.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_up(
point(px(120.), px(10.)),
MouseButton::Left,
Modifiers::default(),
);
assert_eq!(*changes_a.borrow(), vec![50.0, 60.0]);
assert!(changes_b.borrow().is_empty(), "A's drag leaked into B");
cx.simulate_mouse_down(
point(px(100.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_move(
point(px(40.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
cx.simulate_mouse_up(
point(px(40.), px(50.)),
MouseButton::Left,
Modifiers::default(),
);
assert_eq!(*changes_b.borrow(), vec![50.0, 20.0]);
assert_eq!(
*changes_a.borrow(),
vec![50.0, 60.0],
"B's drag leaked into A"
);
}
-282
View File
@@ -1,282 +0,0 @@
#![cfg(feature = "speech")]
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
use gpui::{App, AppContext as _, Entity, SharedString, Subscription, TestAppContext};
use gpui_native_core::speech::{
AudioFormat, AudioInput, AudioSink, RecognitionSession, SpeechError, SpeechEvent,
SpeechRecognizer, SpeechSink, SpeechState, SpeechStatus,
};
type EventLog = Rc<RefCell<Vec<SpeechEvent>>>;
type Harness = (
Entity<SpeechState>,
EventLog,
Rc<RefCell<Option<SpeechSink>>>,
Rc<RefCell<usize>>,
);
struct FakeRecognizer {
available: bool,
finish_reports: bool,
sink: Rc<RefCell<Option<SpeechSink>>>,
received: Rc<RefCell<usize>>,
}
impl SpeechRecognizer for FakeRecognizer {
fn is_available(&self, _cx: &App) -> bool {
self.available
}
fn start(
&self,
sink: SpeechSink,
cx: &mut App,
) -> Result<Box<dyn RecognitionSession>, SpeechError> {
*self.sink.borrow_mut() = Some(sink.clone());
sink.ready(cx);
Ok(Box::new(FakeSession {
sink,
finish_reports: self.finish_reports,
received: self.received.clone(),
}))
}
}
struct FakeSession {
sink: SpeechSink,
finish_reports: bool,
received: Rc<RefCell<usize>>,
}
impl RecognitionSession for FakeSession {
fn push_audio(&mut self, samples: &[i16], _cx: &mut App) {
*self.received.borrow_mut() += samples.len();
}
fn finish(&mut self, cx: &mut App) {
if self.finish_reports {
self.sink.finish(cx);
}
}
}
/// Delivers one silent second, 16 kHz mono, in 100 ms chunks.
struct FakeInput;
impl AudioInput for FakeInput {
fn start(
&self,
format: AudioFormat,
sink: AudioSink,
cx: &mut App,
) -> Result<Subscription, SpeechError> {
let chunk_len = (format.sample_rate() / 10) as usize * format.channels() as usize;
let task = cx.spawn(async move |cx| {
for _ in 0..10 {
cx.background_executor()
.timer(Duration::from_millis(100))
.await;
cx.update(|cx| sink.push(vec![0; chunk_len], cx));
}
});
Ok(Subscription::new(move || drop(task)))
}
}
fn harness(cx: &mut TestAppContext, available: bool, finish_reports: bool) -> Harness {
let sink_slot: Rc<RefCell<Option<SpeechSink>>> = Rc::new(RefCell::new(None));
let received = Rc::new(RefCell::new(0));
let log: EventLog = Rc::new(RefCell::new(Vec::new()));
let record = log.clone();
let speech = cx.update(|cx| {
let speech = cx.new(|cx| {
SpeechState::new(cx)
.recognizer(FakeRecognizer {
available,
finish_reports,
sink: sink_slot.clone(),
received: received.clone(),
})
.input(FakeInput)
.stop_timeout(Duration::from_secs(2))
});
cx.subscribe(&speech, move |_, event, _| {
record.borrow_mut().push(event.clone())
})
.detach();
speech
});
(speech, log, sink_slot, received)
}
fn start(speech: &Entity<SpeechState>, cx: &mut TestAppContext) {
cx.update(|cx| speech.update(cx, |state, cx| state.start(cx)));
cx.run_until_parked();
}
#[test]
fn a_session_starts_reads_and_finalizes() {
let mut cx = TestAppContext::single();
let (speech, events, sink_slot, _) = harness(&mut cx, true, true);
start(&speech, &mut cx);
cx.update(|cx| assert_eq!(speech.read(cx).status(), SpeechStatus::Recording));
assert_eq!(*events.borrow(), vec![SpeechEvent::Started]);
let sink = sink_slot.borrow().clone().expect("session opened");
cx.update(|cx| sink.hypothesis("hel", cx));
cx.run_until_parked();
cx.update(|cx| {
sink.phrase("hello ", cx);
sink.hypothesis("wor", cx);
});
cx.run_until_parked();
cx.update(|cx| {
assert_eq!(
speech.read(cx).transcript(),
SharedString::from("hello wor")
);
});
cx.update(|cx| speech.update(cx, |state, cx| state.stop(cx)));
cx.run_until_parked();
cx.update(|cx| assert_eq!(speech.read(cx).status(), SpeechStatus::Idle));
let events = events.borrow();
assert!(
matches!(events.last(), Some(SpeechEvent::Final(text)) if text.as_ref() == "hello wor")
);
assert!(matches!(
events.get(events.len() - 2),
Some(SpeechEvent::Partial(text)) if text.as_ref() == "hello wor"
));
}
#[test]
fn starting_twice_runs_a_single_session() {
let mut cx = TestAppContext::single();
let (speech, events, _, _) = harness(&mut cx, true, true);
start(&speech, &mut cx);
start(&speech, &mut cx);
assert_eq!(*events.borrow(), vec![SpeechEvent::Started]);
}
#[test]
fn cancel_discards_the_transcript_and_ignores_late_reports() {
let mut cx = TestAppContext::single();
let (speech, events, sink_slot, _) = harness(&mut cx, true, true);
start(&speech, &mut cx);
let sink = sink_slot.borrow().clone().expect("session opened");
cx.update(|cx| sink.phrase("hello", cx));
cx.run_until_parked();
cx.update(|cx| speech.update(cx, |state, cx| state.cancel(cx)));
cx.run_until_parked();
cx.update(|cx| {
let state = speech.read(cx);
assert_eq!(state.status(), SpeechStatus::Idle);
assert_eq!(state.transcript(), SharedString::from(""));
});
assert!(matches!(
events.borrow().last(),
Some(SpeechEvent::Cancelled)
));
cx.update(|cx| sink.finish(cx));
cx.run_until_parked();
assert!(
!events
.borrow()
.iter()
.any(|event| matches!(event, SpeechEvent::Final(_)))
);
}
#[test]
fn starting_without_a_recognizer_fails() {
let mut cx = TestAppContext::single();
let log: EventLog = Rc::new(RefCell::new(Vec::new()));
let record = log.clone();
let speech = cx.update(|cx| {
let speech = cx.new(|cx| SpeechState::new(cx).input(FakeInput));
cx.subscribe(&speech, move |_, event, _| {
record.borrow_mut().push(event.clone())
})
.detach();
speech
});
cx.update(|cx| assert!(!speech.read(cx).has_recognizer()));
start(&speech, &mut cx);
cx.update(|cx| assert_eq!(speech.read(cx).status(), SpeechStatus::Idle));
assert!(matches!(events_last(&log), Some(SpeechEvent::Error(_))));
}
#[test]
fn starting_an_unavailable_recognizer_fails() {
let mut cx = TestAppContext::single();
let (speech, events, _, _) = harness(&mut cx, false, true);
start(&speech, &mut cx);
cx.update(|cx| assert_eq!(speech.read(cx).status(), SpeechStatus::Idle));
assert!(matches!(
events.borrow().last(),
Some(SpeechEvent::Error(_))
));
}
#[test]
fn the_stop_timeout_finalizes_with_the_transcript_so_far() {
let mut cx = TestAppContext::single();
let (speech, events, sink_slot, _) = harness(&mut cx, true, false);
start(&speech, &mut cx);
let sink = sink_slot.borrow().clone().expect("session opened");
cx.update(|cx| sink.phrase("hello", cx));
cx.run_until_parked();
cx.update(|cx| speech.update(cx, |state, cx| state.stop(cx)));
cx.run_until_parked();
cx.update(|cx| assert_eq!(speech.read(cx).status(), SpeechStatus::Stopping));
cx.executor().advance_clock(Duration::from_secs(2));
cx.run_until_parked();
cx.update(|cx| assert_eq!(speech.read(cx).status(), SpeechStatus::Idle));
assert!(
matches!(events.borrow().last(), Some(SpeechEvent::Final(text)) if text.as_ref() == "hello")
);
}
#[test]
fn captured_audio_reaches_the_session_and_the_levels() {
let mut cx = TestAppContext::single();
let (speech, _, _, received) = harness(&mut cx, true, true);
start(&speech, &mut cx);
cx.executor().advance_clock(Duration::from_secs(1));
cx.run_until_parked();
cx.update(|cx| {
let state = speech.read(cx);
assert_eq!(*received.borrow(), 16_000);
// One level per 80 ms bucket of the one-second capture.
let levels = state.levels();
assert_eq!(levels.len(), 12);
assert!(levels.iter().all(|level| *level == 0.0));
});
cx.update(|cx| speech.update(cx, |state, cx| state.stop(cx)));
cx.run_until_parked();
cx.update(|cx| assert!(speech.read(cx).levels().is_empty()));
}
fn events_last(log: &EventLog) -> Option<SpeechEvent> {
log.borrow().last().cloned()
}
-104
View File
@@ -1,104 +0,0 @@
use std::{cell::RefCell, rc::Rc, time::Duration};
use gpui::prelude::FluentBuilder as _;
use gpui::{
Context, IntoElement, ParentElement as _, Render, Styled as _, TestAppContext, Window, div,
};
use gpui_native_core::spinner::{Spinner, SpinnerVariant};
use gpui_native_theme::Theme;
struct SpinnerHost {
variant: SpinnerVariant,
determinate: bool,
renders: Rc<RefCell<usize>>,
}
impl Render for SpinnerHost {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
*self.renders.borrow_mut() += 1;
let spinner = Spinner::new("test-spinner")
.variant(self.variant)
.when(self.determinate, |spinner| spinner.value(0.4));
div().size_full().child(spinner)
}
}
fn host_window(
variant: SpinnerVariant,
determinate: bool,
reduce_motion: bool,
) -> (TestAppContext, Rc<RefCell<usize>>) {
let mut cx = TestAppContext::single();
cx.update(|cx| {
Theme::init(cx);
if reduce_motion {
cx.set_reduce_motion(true);
}
});
let renders = Rc::new(RefCell::new(0));
let host_renders = renders.clone();
cx.add_window(move |_, _| SpinnerHost {
variant,
determinate,
renders: host_renders,
});
cx.run_until_parked();
(cx, renders)
}
#[test]
fn spinning_repaints_on_the_animation_clock() {
let (cx, renders) = host_window(SpinnerVariant::Ring, false, false);
assert_eq!(*renders.borrow(), 1);
// The 60fps cap drives re-renders with timers, not frame callbacks.
cx.executor().advance_clock(Duration::from_millis(100));
cx.run_until_parked();
assert!(
*renders.borrow() > 1,
"the spinner must repaint while spinning"
);
}
#[test]
fn determinate_paints_one_static_frame() {
let (cx, renders) = host_window(SpinnerVariant::Ring, true, false);
assert_eq!(*renders.borrow(), 1);
cx.executor().advance_clock(Duration::from_millis(200));
cx.run_until_parked();
assert_eq!(*renders.borrow(), 1, "a determinate ring holds still");
}
#[test]
fn reduce_motion_paints_one_static_frame() {
let (cx, renders) = host_window(SpinnerVariant::Ring, false, true);
assert_eq!(*renders.borrow(), 1);
cx.executor().advance_clock(Duration::from_millis(200));
cx.run_until_parked();
assert_eq!(*renders.borrow(), 1, "reduced motion must freeze the spin");
}
#[test]
fn the_icon_variant_repaints_while_spinning() {
let (cx, renders) = host_window(SpinnerVariant::Icon, false, false);
assert_eq!(*renders.borrow(), 1);
cx.executor().advance_clock(Duration::from_millis(100));
cx.run_until_parked();
assert!(
*renders.borrow() > 1,
"the icon must repaint while spinning"
);
}
#[test]
fn the_icon_variant_holds_still_when_determinate() {
let (cx, renders) = host_window(SpinnerVariant::Icon, true, false);
assert_eq!(*renders.borrow(), 1);
cx.executor().advance_clock(Duration::from_millis(200));
cx.run_until_parked();
assert_eq!(*renders.borrow(), 1, "a held icon must not animate");
}
-47
View File
@@ -1,47 +0,0 @@
use gpui::{
AppContext as _, IntoElement, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div,
};
use gpui_native_core::status_dot::{StatusDot, StatusDotVariant};
use gpui_native_theme::{ActiveTheme as _, Theme};
struct DotHost;
impl Render for DotHost {
fn render(&mut self, _window: &mut Window, _cx: &mut gpui::Context<Self>) -> impl IntoElement {
div().size_full().p_4().child(
StatusDot::new("test-dot")
.variant(StatusDotVariant::Success)
.label("Synced"),
)
}
}
fn dot_window() -> (TestAppContext, gpui::AnyWindowHandle) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let window = cx.add_window(|_, _| DotHost);
let window: gpui::AnyWindowHandle = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(cx, window)
}
/// A medium dot is half the theme's icon size — big enough to read a state
/// from, small enough to sit beside row text. The label must not grow it.
#[test]
fn the_dot_is_half_the_icon_size() {
let (cx, window) = dot_window();
let mut visual = VisualTestContext::from_window(window, &cx);
let dot = visual.debug_bounds("test-dot").expect("dot missing");
let side = cx.update(|cx| cx.theme().sizes.medium.icon_size) / 2.;
assert!(
((dot.size.width - side).abs() <= gpui::px(0.5))
&& ((dot.size.height - side).abs() <= gpui::px(0.5)),
"the dot must be {side:?} wide, got {:?}",
dot.size
);
}
-135
View File
@@ -1,135 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke,
Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window,
div, point, px,
};
use gpui_native_core::switch::Switch;
use gpui_native_theme::Theme;
struct Harness {
changes: Rc<RefCell<Vec<bool>>>,
checked: bool,
disabled: bool,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().flex().flex_col().child(
Switch::new("test-switch")
.label("Wi-Fi")
.checked(self.checked)
.disabled(self.disabled)
.on_change(move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.checked = next;
cx.notify();
});
}),
)
}
}
/// A maximized window whose switch track sits in the top-left corner, so
/// `point(px(10.), px(10.))` lands on it.
fn switch_window(
checked: bool,
disabled: bool,
) -> (VisualTestContext, AnyWindowHandle, Rc<RefCell<Vec<bool>>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
changes: harness_changes,
checked,
disabled,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(VisualTestContext::from_window(window, &cx), window, changes)
}
fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
#[test]
fn clicking_reports_the_next_value_through_the_controlled_loop() {
let (mut cx, _window, changes) = switch_window(false, false);
cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![true]);
// The second click must report `false`: only if the owner applied the
// first change does the switch know it is now checked.
cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![true, false]);
}
#[test]
fn disabled_switch_does_not_report_changes() {
let (mut cx, _window, changes) = switch_window(false, true);
cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
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);
cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
assert_eq!(
*changes.borrow(),
vec![true],
"the pointer click itself toggles"
);
// Repaint with the switch focused so its Enter/Space handlers register.
draw(&mut cx, window);
for key in ["enter", "space"] {
cx.simulate_event(KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
assert_eq!(*changes.borrow(), vec![true, false, true]);
}
-158
View File
@@ -1,158 +0,0 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
use gpui::{AppContext as _, TestAppContext};
use gpui_native_core::toast::{Toast, ToastAction, Toasts};
use gpui_native_theme::Theme;
fn toasts_store() -> (TestAppContext, gpui::Entity<Toasts>) {
let cx = TestAppContext::single();
cx.update(Theme::init);
let toasts = cx.update(|cx| cx.new(|_| Toasts::default()));
(cx, toasts)
}
#[test]
fn push_raises_a_toast_and_the_timer_fades_it_out() {
let (cx, toasts) = toasts_store();
let id = cx.update(|cx| toasts.update(cx, |toasts, cx| toasts.push(Toast::new("Saved"), cx)));
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 1);
// The default lifetime is five seconds; the fade-out follows it.
cx.executor().advance_clock(Toast::DURATION);
cx.run_until_parked();
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 1, "fading out");
cx.executor()
.advance_clock(std::time::Duration::from_secs(1));
cx.run_until_parked();
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 0);
let _ = id;
}
#[test]
fn pushing_replaces_the_toast_on_screen() {
let (cx, toasts) = toasts_store();
cx.update(|cx| {
toasts.update(cx, |toasts, cx| toasts.push(Toast::new("first"), cx));
});
cx.update(|cx| {
toasts.update(cx, |toasts, cx| toasts.push(Toast::new("second"), cx));
});
// One showing, one fading out: never two current toasts.
let (current, total) = cx.update(|cx| {
toasts.read_with(cx, |toasts, _| {
(toasts.current().map(|entry| entry.id), toasts.count())
})
});
assert_eq!(current, Some(1));
assert_eq!(total, 2);
cx.executor()
.advance_clock(std::time::Duration::from_secs(6));
cx.run_until_parked();
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 0);
}
#[test]
fn sticky_toasts_ignore_the_timer_until_dismissed() {
let (cx, toasts) = toasts_store();
let id = cx.update(|cx| {
toasts.update(cx, |toasts, cx| {
toasts.push(Toast::new("Sticky").duration(Duration::ZERO), cx)
})
});
cx.executor().advance_clock(Toast::DURATION * 4);
cx.run_until_parked();
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 1);
cx.update(|cx| {
toasts.update(cx, |toasts, cx| toasts.dismiss(id, cx));
});
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 1, "fading out");
cx.executor()
.advance_clock(std::time::Duration::from_secs(1));
cx.run_until_parked();
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 0);
}
#[test]
fn dismiss_runs_the_handler_only_after_the_fade_completes() {
let (cx, toasts) = toasts_store();
let dismissed = Rc::new(std::cell::RefCell::new(Vec::<&'static str>::new()));
cx.update(|cx| {
let first = dismissed.clone();
toasts.update(cx, |toasts, cx| {
toasts.push(
Toast::new("first").on_dismiss(move |_| record(&first, "first")),
cx,
);
});
});
cx.update(|cx| {
toasts.update(cx, |toasts, cx| toasts.dismiss(0, cx));
});
assert!(
dismissed.borrow().is_empty(),
"the handler waits out the fade"
);
cx.executor()
.advance_clock(std::time::Duration::from_secs(1));
cx.run_until_parked();
assert_eq!(*dismissed.borrow(), vec!["first"]);
cx.update(|cx| {
toasts.update(cx, |toasts, cx| toasts.clear(cx));
});
cx.executor()
.advance_clock(std::time::Duration::from_secs(1));
cx.run_until_parked();
assert_eq!(cx.update(|cx| toasts.read(cx).count()), 0);
fn record(sink: &Rc<RefCell<Vec<&'static str>>>, what: &'static str) {
sink.borrow_mut().push(what);
}
}
/// Dismissing by any other path never runs the action: only a click on the
/// action itself does (the view wires the two together).
#[test]
fn dismissal_does_not_run_the_action() {
let (cx, toasts) = toasts_store();
let ran = Rc::new(std::cell::RefCell::new(false));
let dismissed = Rc::new(std::cell::RefCell::new(false));
cx.update(|cx| {
let action_ran = ran.clone();
let toast_dismissed = dismissed.clone();
toasts.update(cx, |toasts, cx| {
toasts.push(
Toast::new("Draft deleted")
.action(ToastAction::new("Undo", move |_| {
*action_ran.borrow_mut() = true;
}))
.on_dismiss(move |_| *toast_dismissed.borrow_mut() = true),
cx,
);
});
});
cx.update(|cx| {
toasts.update(cx, |toasts, cx| toasts.dismiss(0, cx));
});
assert!(!*ran.borrow(), "dismiss is not the action");
cx.executor()
.advance_clock(std::time::Duration::from_secs(1));
cx.run_until_parked();
assert!(
*dismissed.borrow(),
"on_dismiss still reports the dismissal"
);
}
-111
View File
@@ -1,111 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
AnyWindowHandle, AppContext as _, Context, IntoElement, KeyDownEvent, KeyUpEvent, Keystroke,
Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window,
div, point, px,
};
use gpui_native_core::toggle::Toggle;
use gpui_native_theme::Theme;
struct Harness {
changes: Rc<RefCell<Vec<bool>>>,
pressed: bool,
disabled: bool,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
let view = cx.entity();
div().size_full().flex().flex_col().child(
Toggle::new("test-toggle")
.label("Bold")
.pressed(self.pressed)
.disabled(self.disabled)
.on_change(move |next, _, cx| {
changes.borrow_mut().push(next);
view.update(cx, |harness, cx| {
harness.pressed = next;
cx.notify();
});
}),
)
}
}
/// A maximized window whose toggle sits in the top-left corner, so
/// `point(px(20.), px(14.))` lands on it.
fn toggle_window(
pressed: bool,
disabled: bool,
) -> (VisualTestContext, AnyWindowHandle, Rc<RefCell<Vec<bool>>>) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let changes = Rc::new(RefCell::new(Vec::new()));
let harness_changes = changes.clone();
let window = cx.add_window(move |_, _| Harness {
changes: harness_changes,
pressed,
disabled,
});
let window = window.into();
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
(VisualTestContext::from_window(window, &cx), window, changes)
}
fn draw(cx: &mut VisualTestContext, window: AnyWindowHandle) {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
}
#[test]
fn clicking_reports_the_next_pressed_state_through_the_controlled_loop() {
let (mut cx, _window, changes) = toggle_window(false, false);
cx.simulate_click(point(px(20.), px(14.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![true]);
// The second click must report `false`: only if the owner applied the
// first change does the toggle know it is pressed.
cx.simulate_click(point(px(20.), px(14.)), Modifiers::default());
assert_eq!(*changes.borrow(), vec![true, false]);
}
#[test]
fn disabled_toggle_does_not_report_changes() {
let (mut cx, _window, changes) = toggle_window(false, true);
cx.simulate_click(point(px(20.), px(14.)), Modifiers::default());
assert!(changes.borrow().is_empty());
}
#[test]
fn enter_and_space_report_the_next_pressed_state_while_focused() {
let (mut cx, window, changes) = toggle_window(false, false);
cx.simulate_click(point(px(20.), px(14.)), Modifiers::default());
assert_eq!(
*changes.borrow(),
vec![true],
"the pointer click itself presses"
);
// Repaint with the toggle focused so its Enter/Space handlers register.
draw(&mut cx, window);
for key in ["enter", "space"] {
cx.simulate_event(KeyDownEvent {
keystroke: Keystroke::parse(key).unwrap(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent {
keystroke: Keystroke::parse(key).unwrap(),
});
}
assert_eq!(*changes.borrow(), vec![true, false, true]);
}
-209
View File
@@ -1,209 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use gpui::{
Context, InteractiveElement as _, IntoElement, Modifiers, MouseMoveEvent, ParentElement as _,
Render, StatefulInteractiveElement as _, Styled as _, TestAppContext, VisualTestContext,
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. 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>>>,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
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())
.child(
canvas(record_anchor_bounds("hover-target".into()), |_, _, _, _| {})
.absolute()
.inset_0(),
)
.tooltip(move |window, cx| {
calls.borrow_mut().push("target");
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 |window, cx| {
button_calls.borrow_mut().push("button");
Tooltip::anchored("Button tooltip", "hover-button")(window, cx)
});
div()
.size_full()
.child(target)
.child(div().mt_12().child(button))
}
}
fn tooltip_window() -> (
TestAppContext,
VisualTestContext,
Rc<RefCell<Vec<&'static str>>>,
) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let calls = Rc::new(RefCell::new(Vec::new()));
let harness_calls = calls.clone();
let window = cx.add_window(move |_, _| Harness {
calls: harness_calls,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, calls)
}
fn hover(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
visual.simulate_event(MouseMoveEvent {
position,
pressed_button: None,
modifiers: Modifiers::default(),
});
}
/// gpui's hover delay before deploying a tooltip.
const SHOW_DELAY: std::time::Duration = std::time::Duration::from_millis(500);
fn draw(visual: &mut VisualTestContext) {
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
}
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();
hover(&mut visual, point(px(50.), px(20.)));
assert!(
calls.borrow().is_empty(),
"builder runs only after the delay"
);
cx.executor().advance_clock(SHOW_DELAY);
visual.run_until_parked();
draw(&mut visual);
assert_eq!(*calls.borrow(), vec!["target"]);
}
#[test]
fn hovering_elsewhere_deploys_nothing() {
let (cx, mut visual, calls) = tooltip_window();
hover(&mut visual, point(px(800.), px(600.)));
cx.executor().advance_clock(SHOW_DELAY);
visual.run_until_parked();
draw(&mut visual);
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_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);
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"
);
}