From 65bf96beae49960fc9f5e7d71874a973db36bd74 Mon Sep 17 00:00:00 2001 From: Emil Ernerfeldt Date: Mon, 21 Sep 2026 14:17:58 +0200 Subject: [PATCH] Add `Response::accessible_name` (#8604) Useful for adding an accessibility name to a widget --------- Co-authored-by: Claude Fable 5.1 --- crates/egui/src/context.rs | 7 +++++-- crates/egui/src/response.rs | 19 +++++++++++++++++++ .../egui_kittest/tests/accessibility_check.rs | 10 ++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/egui/src/context.rs b/crates/egui/src/context.rs index 38024b1a..c4fb901f 100644 --- a/crates/egui/src/context.rs +++ b/crates/egui/src/context.rs @@ -4083,8 +4083,11 @@ impl Context { self.write(|ctx| ctx.accesskit_node_builder(id).map(writer)) } - /// Does the widget already have an accessibility node this pass? - pub(crate) fn has_accesskit_node(&self, id: Id) -> bool { + /// Does the widget with this id have a node in the accessibility tree this pass? + /// + /// Only widgets that report [`WidgetInfo`](crate::WidgetInfo) do; a plain + /// [`Ui::allocate_rect`](crate::Ui::allocate_rect) does not. + pub fn has_accesskit_node(&self, id: Id) -> bool { self.write(|ctx| { ctx.viewport() .this_pass diff --git a/crates/egui/src/response.rs b/crates/egui/src/response.rs index db69937b..c9528c23 100644 --- a/crates/egui/src/response.rs +++ b/crates/egui/src/response.rs @@ -1083,6 +1083,25 @@ impl Response { self } + /// Name the widget in the accessibility tree when nothing visible names it, + /// e.g. an icon-only button or a text field without a label next to it. + /// + /// Prefer [`Self::labelled_by`] when a visible label sits next to the widget. + /// + /// ``` + /// # egui::__run_test_ui(|ui| { + /// # let mut text = String::new(); + /// ui.text_edit_singleline(&mut text).accessible_name("Search"); + /// # }); + /// ``` + pub fn accessible_name(self, name: impl Into) -> Self { + let name = name.into(); + self.ctx.accesskit_node_builder(self.id, |builder| { + builder.set_label(name); + }); + self + } + /// Response to secondary clicks (right-clicks) by showing the given menu. /// /// Make sure the widget senses clicks (e.g. [`crate::Button`] does, [`crate::Label`] does not). diff --git a/crates/egui_kittest/tests/accessibility_check.rs b/crates/egui_kittest/tests/accessibility_check.rs index 0df7962e..7354c60f 100644 --- a/crates/egui_kittest/tests/accessibility_check.rs +++ b/crates/egui_kittest/tests/accessibility_check.rs @@ -115,3 +115,13 @@ fn labelled_by_wins_over_drag_value_suffix() { [Some("Width".to_owned()), Some("x: px".to_owned())] ); } + +#[test] +fn accessible_name_names_a_widget_without_a_label() { + let mut text = String::new(); + let mut harness = Harness::new_ui(|ui| { + ui.text_edit_singleline(&mut text).accessible_name("Search"); + }); + harness.run(); + harness.get_by_label("Search"); +}