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>, disabled: bool, } impl Render for Harness { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { let clicks = self.clicks.clone(); div().size_full().flex().flex_col().child( Button::new("test-button") .label("Save") .disabled(self.disabled) .on_click(move |_, _, _| *clicks.borrow_mut() += 1), ) } } /// A maximized window whose button stretches across the top 28px, so /// `point(px(60.), px(14.))` always lands on it. fn button_window(disabled: bool) -> (VisualTestContext, AnyWindowHandle, Rc>) { 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, }); 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); 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); 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); 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"); }