Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
ui: Fix context menu selecting first entry on open (#64365)
Finn Evers9183ba4c5579
diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rsindex b2b8179e8f1..a4c9fb6528c 100644--- a/crates/gpui/src/app/test_context.rs+++ b/crates/gpui/src/app/test_context.rs@@ -187,6 +187,11 @@ impl TestAppContext {}}+ /// Disables accessibility for subsequently created test windows.+ pub fn disable_accessibility(&mut self) {+ self.update(|cx| cx.accessibility_force_disabled = true);+ }+/// Skip all drawing operations for the duration of this test.pub fn skip_drawing(&mut self) {self.app.borrow_mut().mode = GpuiMode::Test { skip_drawing: true };diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex b1c9e115502..ae0cca86b8f 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -6771,6 +6771,16 @@ impl Window {self.platform_window.play_system_bell()}+ /// Returns whether accessibility support is enabled for this window.+ ///+ /// This is false when the app was created with [`crate::Application::new_inaccessible`].+ /// Unlike [`Self::is_a11y_active`], this does not depend on whether assistive+ /// technology is currently connected, so it can be used to gate subscriptions+ /// that are only needed for accessibility.+ pub fn is_a11y_enabled(&self) -> bool {+ self.a11y.is_enabled()+ }+/// Returns whether accessibility features are active for this frame,/// i.e. whether assistive technology (such as a screen reader) is/// connected and an accessibility tree is being built.diff --git a/crates/gpui/src/window/a11y.rs b/crates/gpui/src/window/a11y.rsindex 234e7f0acd9..5b63821232a 100644--- a/crates/gpui/src/window/a11y.rs+++ b/crates/gpui/src/window/a11y.rs@@ -210,7 +210,11 @@ impl A11y {/// See the docs for [`Self::active_flag`] and [`Self::active_this_frame`]/// for more commentary.pub(crate) fn sync_active_flag(&mut self) {- self.active_this_frame = !self.force_disabled && self.active_flag.load(Ordering::SeqCst);+ self.active_this_frame = self.is_enabled() && self.active_flag.load(Ordering::SeqCst);+ }++ pub(crate) fn is_enabled(&self) -> bool {+ !self.force_disabled}pub(crate) fn is_active(&self) -> bool {@@ -654,6 +658,19 @@ mod tests {a11y}+ #[test]+ fn accessibility_enabled_is_independent_of_activation() {+ for force_disabled in [false, true] {+ for active in [false, true] {+ let mut a11y = A11y::new(Arc::new(AtomicBool::new(active)), force_disabled, None);+ a11y.sync_active_flag();++ assert_eq!(a11y.is_enabled(), !force_disabled);+ assert_eq!(a11y.is_active(), !force_disabled && active);+ }+ }+ }+#[test]fn active_descendant_honored_when_container_focused() {let mut builder = new_builder();diff --git a/crates/ui/src/components/context_menu.rs b/crates/ui/src/components/context_menu.rsindex 21d5ce3dd32..44c60606928 100644--- a/crates/ui/src/components/context_menu.rs+++ b/crates/ui/src/components/context_menu.rs@@ -239,6 +239,7 @@ pub struct ContextMenu {/// select an item. This prevents a visual flash where a submenu close in/// on_hover(false) returns focus to the main menu and on_focus_in/// re-selects the first item before the next on_hover(true) clears it.+ /// Always true when accessibility support is disabled.suppress_focus_selection: bool,}@@ -328,14 +329,17 @@ impl ContextMenu {);window.refresh();- // See the note in `ContextMenu::new`: select an item when the menu- // opens so screen readers announce it instead of just "menu".- cx.on_focus_in(&focus_handle, window, |this, window, cx| {- if this.selected_index.is_none() {- this.select_toggled_or_first(window, cx);- }- })- .detach();+ if window.is_a11y_enabled() {+ // See the note in `ContextMenu::new_inner`: select an item when the menu+ // opens so screen readers announce it instead of just "menu".+ cx.on_focus_in(&focus_handle, window, |this, window, cx| {+ if this.selected_index.is_none() && !this.suppress_focus_selection {+ this.select_toggled_or_first(window, cx);+ }+ this.suppress_focus_selection = false;+ })+ .detach();+ }(builder.clone())(Self {@@ -361,7 +365,7 @@ impl ContextMenu {submenu_trigger_bounds: Rc::new(Cell::new(None)),submenu_trigger_mouse_down: false,ignore_blur_until: None,- suppress_focus_selection: false,+ suppress_focus_selection: !window.is_a11y_enabled(),},window,cx,@@ -431,7 +435,7 @@ impl ContextMenu {submenu_trigger_bounds: Rc::new(Cell::new(None)),submenu_trigger_mouse_down: false,ignore_blur_until: None,- suppress_focus_selection: false,+ suppress_focus_selection: !window.is_a11y_enabled(),},window,cx,@@ -880,7 +884,7 @@ impl ContextMenu {pub fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {let Some(ix) = self.selected_index else {- return;+ return cx.emit(DismissEvent);};if let Some(ContextMenuItem::Submenu { builder, .. }) = self.items.get(ix) {@@ -1268,7 +1272,7 @@ impl ContextMenu {submenu_trigger_bounds: Rc::new(Cell::new(None)),submenu_trigger_mouse_down: false,ignore_blur_until: None,- suppress_focus_selection: false,+ suppress_focus_selection: !window.is_a11y_enabled(),};menu = (builder)(menu, window, cx);@@ -2138,19 +2142,21 @@ impl ContextMenu {);window.refresh();- // When the menu first receives focus (i.e. when it opens), move the- // selection onto a menu item so assistive technology announces a real- // item rather than the bare menu container. Per the ARIA menu button- // pattern, opening a menu places focus on a menu item; for select-style- // menus we prefer the currently-checked item. We only do this when- // nothing is selected yet so we don't override an existing selection.- cx.on_focus_in(&focus_handle, window, |context_menu, window, cx| {- if context_menu.selected_index.is_none() && !context_menu.suppress_focus_selection {- context_menu.select_toggled_or_first(window, cx);- }- context_menu.suppress_focus_selection = false;- })- .detach();+ if window.is_a11y_enabled() {+ // When the menu first receives focus (i.e. when it opens), move the+ // selection onto a menu item so assistive technology announces a real+ // item rather than the bare menu container. Per the ARIA menu button+ // pattern, opening a menu places focus on a menu item; for select-style+ // menus we prefer the currently-checked item. We only do this when+ // nothing is selected yet so we don't override an existing selection.+ cx.on_focus_in(&focus_handle, window, |context_menu, window, cx| {+ if context_menu.selected_index.is_none() && !context_menu.suppress_focus_selection {+ context_menu.select_toggled_or_first(window, cx);+ }+ context_menu.suppress_focus_selection = false;+ })+ .detach();+ }Self {builder: None,@@ -2175,7 +2181,7 @@ impl ContextMenu {submenu_trigger_bounds: Rc::new(Cell::new(None)),submenu_trigger_mouse_down: false,ignore_blur_until: None,- suppress_focus_selection: false,+ suppress_focus_selection: !window.is_a11y_enabled(),}}}@@ -2444,10 +2450,173 @@ impl Render for ContextMenu {#[cfg(test)]mod tests {- use gpui::TestAppContext;+ use gpui::{TestAppContext, VisualTestContext};use super::*;+ fn focus_menu(menu: &Entity<ContextMenu>, cx: &mut VisualTestContext) {+ cx.update(|window, cx| window.blur(cx));+ cx.run_until_parked();+ cx.update(|window, cx| window.focus(&menu.focus_handle(cx), cx));+ cx.run_until_parked();+ }++ fn assert_focus_selection(cx: &mut TestAppContext, persistent: bool, a11y_enabled: bool) {+ if !a11y_enabled {+ cx.disable_accessibility();+ }+ cx.update(|cx| {+ let settings_store = settings::SettingsStore::test(cx);+ cx.set_global(settings_store);+ theme_settings::init(theme::LoadThemes::JustBase, cx);+ });++ let window = cx+ .update(|cx| {+ cx.open_window(Default::default(), |window, cx| {+ let build_menu =+ |menu: ContextMenu, _: &mut Window, _: &mut Context<ContextMenu>| {+ menu.header("Options")+ .entry("First", None, |_, _| {})+ .separator()+ .item(+ ContextMenuEntry::new("Checked")+ .toggleable(IconPosition::Start, true),+ )+ };+ if persistent {+ ContextMenu::build_persistent(window, cx, build_menu)+ } else {+ ContextMenu::build(window, cx, build_menu)+ }+ })+ })+ .expect("open menu window");+ let menu = window.root(cx).expect("menu root");+ let mut cx = VisualTestContext::from_window(window.into(), cx);+ let focus_events = Rc::new(Cell::new(0));+ cx.update(|window, cx| {+ assert_eq!(window.is_a11y_enabled(), a11y_enabled);+ assert!(!window.is_a11y_active());+ let focus_events = focus_events.clone();+ window+ .on_focus_in(&menu.focus_handle(cx), cx, move |_, _| {+ focus_events.set(focus_events.get() + 1);+ })+ .detach();+ window.activate_window();+ });+ cx.run_until_parked();++ menu.read_with(&cx, |menu, _| {+ assert_eq!(menu.selected_index, None);+ assert_eq!(menu.suppress_focus_selection, !a11y_enabled);+ });+ focus_menu(&menu, &mut cx);+ assert_eq!(focus_events.get(), 1);+ assert_eq!(+ menu.read_with(&cx, |menu, _| menu.selected_index),+ a11y_enabled.then_some(3),+ );++ cx.dispatch_action(SelectNext);+ assert_eq!(+ menu.read_with(&cx, |menu, _| menu.selected_index),+ Some(1),+ "SelectNext right after opening should select the first selectable entry",+ );+ cx.dispatch_action(SelectNext);+ assert_eq!(menu.read_with(&cx, |menu, _| menu.selected_index), Some(3));+ cx.dispatch_action(SelectPrevious);+ assert_eq!(menu.read_with(&cx, |menu, _| menu.selected_index), Some(1));++ focus_menu(&menu, &mut cx);+ assert_eq!(focus_events.get(), 2);+ assert_eq!(menu.read_with(&cx, |menu, _| menu.selected_index), Some(1));++ menu.update(&mut cx, |menu, cx| {+ menu.clear_selected();+ if a11y_enabled {+ menu.suppress_focus_selection = true;+ }+ cx.notify();+ });+ focus_menu(&menu, &mut cx);+ assert_eq!(focus_events.get(), 3);+ menu.read_with(&cx, |menu, _| {+ assert_eq!(menu.selected_index, None);+ assert_eq!(menu.suppress_focus_selection, !a11y_enabled);+ });++ focus_menu(&menu, &mut cx);+ assert_eq!(focus_events.get(), 4);+ assert_eq!(+ menu.read_with(&cx, |menu, _| menu.selected_index),+ a11y_enabled.then_some(3),+ );+ }++ #[gpui::test]+ fn focus_selection_with_accessibility(cx: &mut TestAppContext) {+ assert_focus_selection(cx, false, true);+ }++ #[gpui::test]+ fn focus_selection_without_accessibility(cx: &mut TestAppContext) {+ assert_focus_selection(cx, false, false);+ }++ #[gpui::test]+ fn persistent_focus_selection_with_accessibility(cx: &mut TestAppContext) {+ assert_focus_selection(cx, true, true);+ }++ #[gpui::test]+ fn persistent_focus_selection_without_accessibility(cx: &mut TestAppContext) {+ assert_focus_selection(cx, true, false);+ }++ #[gpui::test]+ fn confirm_without_selection_dismisses(cx: &mut TestAppContext) {+ let cx = cx.add_empty_window();+ let entry_handler_calls = Rc::new(Cell::new(0));+ let context_menu = cx.update(|window, cx| {+ ContextMenu::build(window, cx, {+ let entry_handler_calls = entry_handler_calls.clone();+ move |menu, _, _| {+ menu.header("Header").entry("Entry", None, move |_, _| {+ entry_handler_calls.set(entry_handler_calls.get() + 1);+ })+ }+ })+ });++ let dismiss_events = Rc::new(Cell::new(0));+ let _subscription = cx.update(|_, cx| {+ let dismiss_events = dismiss_events.clone();+ cx.subscribe(&context_menu, move |_, _: &DismissEvent, _| {+ dismiss_events.set(dismiss_events.get() + 1);+ })+ });++ context_menu.update_in(cx, |context_menu, window, cx| {+ assert_eq!(None, context_menu.selected_index);+ context_menu.confirm(&menu::Confirm, window, cx);+ });+ cx.run_until_parked();++ assert_eq!(+ dismiss_events.get(),+ 1,+ "Confirming without a selection should dismiss the menu"+ );+ assert_eq!(+ entry_handler_calls.get(),+ 0,+ "Confirming without a selection should not trigger any entry"+ );+ }+#[gpui::test]fn can_navigate_back_over_headers(cx: &mut TestAppContext) {let cx = cx.add_empty_window();