From a50bf4a94cb56a8893fef3483d7f5731acc12c0b Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Mon, 16 Nov 2026 18:37:09 -0800 Subject: [PATCH] craft-ui: a combo box cut short shows its selected text in full on hover (#1207) --- crates/keymap/src/ui/view.rs | 2 +- crates/ui/src/combo.rs | 57 +++++++++++++---- crates/ui/src/combo/tests.rs | 116 ++++++++++++++++++++++++++++++++++- 3 files changed, 162 insertions(+), 13 deletions(-) diff --git a/crates/keymap/src/ui/view.rs b/crates/keymap/src/ui/view.rs index 6922d0aca..53ce22a85 100644 --- a/crates/keymap/src/ui/view.rs +++ b/crates/keymap/src/ui/view.rs @@ -426,7 +426,7 @@ impl Draw<'_, '_> { .inner .labelled_by(label.id); self.tag(|| format!("shortcuts.{salt}"), r.rect, title); - if natural > width { r.on_hover_text(full) } else { r } + r } fn filter_combo(&mut self, ui: &mut Ui) { diff --git a/crates/ui/src/combo.rs b/crates/ui/src/combo.rs index 91d70f52b..564875eb7 100644 --- a/crates/ui/src/combo.rs +++ b/crates/ui/src/combo.rs @@ -16,8 +16,8 @@ use std::ops::Range; use egui::{ Align, Align2, AsIdSalt, Atom, AtomExt as _, Atoms, Context, Direction, Frame, Id, IdSalt, InnerResponse, IntoAtoms, LayerId, NumExt as _, Order, - Painter, Popup, PopupCloseBehavior, Rect, RectAlign, Response, Role, ScrollArea, Sense, Shape, TextStyle, TextWrapMode, Ui, Vec2, WidgetAtom, - WidgetInfo, + Painter, Popup, PopupCloseBehavior, Rect, RectAlign, Response, Role, ScrollArea, Sense, Shape, SizedAtomKind, SizedContainerAtom, TextStyle, + TextWrapMode, Ui, Vec2, WidgetAtom, WidgetInfo, class::{ClassName, Classes, HasClasses}, style::{StyleModifier, WidgetVisuals}, vec2, @@ -28,10 +28,12 @@ pub use egui::IconPainter; /// egui's [`egui::ComboBox`] with a menu that grows when its contents do. /// -/// The builder, the button and what the methods return are egui 0.37's. The one difference is -/// the menu: its scroll area is offered the full [`Self::height`] on every pass instead of the +/// The builder, the button's look and what the methods return are egui 0.37's. It differs in two +/// ways. The menu's scroll area is offered the full [`Self::height`] on every pass instead of the /// menu's height on the previous pass, so a menu whose contents shrink and grow again while it -/// is open (a filtered list) grows back. It adds [`Self::show_ui_with_header`] and +/// is open (a filtered list) grows back. When the button cuts the selected text short, hovering +/// it shows the full text in a tooltip, as a truncated [`egui::Label`] does (see +/// [`Self::show_tooltip_when_elided`]). It adds [`Self::show_ui_with_header`] and /// [`Self::show_rows_with_header`] for menus with a search field. /// /// ``` @@ -49,6 +51,7 @@ pub struct ComboBox<'a> { height: Option, icon: Option, wrap_mode: Option, + show_tooltip_when_elided: bool, close_behavior: Option, popup_style: StyleModifier, classes: Classes, @@ -72,6 +75,7 @@ impl<'a> ComboBox<'a> { height: None, icon: None, wrap_mode: None, + show_tooltip_when_elided: true, close_behavior: None, popup_style: StyleModifier::default(), classes: Classes::default(), @@ -146,6 +150,15 @@ impl<'a> ComboBox<'a> { self } + /// Whether hovering the button shows the full selected text in a tooltip when the button cuts + /// it short, as [`egui::Label::show_tooltip_when_elided`] does. Default: `true`. A caller that + /// puts its own tooltip on the button can turn this off so the two do not stack. + #[inline] + pub fn show_tooltip_when_elided(mut self, show: bool) -> Self { + self.show_tooltip_when_elided = show; + self + } + /// When the menu closes. Default: [`PopupCloseBehavior::CloseOnClick`]. #[inline] pub fn close_behavior(mut self, close_behavior: PopupCloseBehavior) -> Self { @@ -268,7 +281,7 @@ fn show(ui: &mut Ui, button_id: Id, mut combo: ComboBox<'_>, open: impl FnOnc let wrap_mode = combo.wrap_mode.unwrap_or_else(|| ui.wrap_mode()); let close_behavior = combo.close_behavior.unwrap_or(PopupCloseBehavior::CloseOnClick); combo.set_class(ComboBox::CLASS_OPEN, is_popup_open); - let ComboBox { label, selected_text, width, height, icon, popup_style, classes, .. } = combo; + let ComboBox { label, selected_text, width, height, icon, show_tooltip_when_elided, popup_style, classes, .. } = combo; // Built from the same atoms and style as a `Button`, so the two line up when put side by side. let ButtonStyle { atom_layout: atom_layout_style } = ui.widget_style(button_id, &classes); @@ -311,16 +324,33 @@ fn show(ui: &mut Ui, button_id: Id, mut combo: ComboBox<'_>, open: impl FnOnc ) .min_size(min_size); - let (button_response, label_response) = match label { + let (button_response, label_response, elided) = match label { Some(label) => { let label_text = label.text().map(String::from).unwrap_or_default(); - let outer_response = - WidgetAtom::new((Atom::widget(button), label)).gap(ui.spacing().item_spacing.x).direction(direction).show(ui).response; + let outer = + WidgetAtom::new((Atom::widget(button), label)).gap(ui.spacing().item_spacing.x).direction(direction).measure(ui, ui.available_size()); + let elided = outer.container.iter_kinds().any(|kind| matches!(kind, SizedAtomKind::Widget(button) if cut_short(&button.container))); + let outer_response = outer.allocate(ui).paint(ui).response; outer_response.widget_info(|| WidgetInfo::labeled(Role::Label, ui.is_enabled(), &label_text)); let button_response = ui.ctx().read_response(button_id).unwrap_or_else(|| outer_response.clone()); - (button_response, Some((outer_response, !label_text.is_empty()))) + (button_response, Some((outer_response, !label_text.is_empty())), elided) } - None => (button.show(ui).response, None), + None => { + let button = button.measure(ui, ui.available_size()); + let elided = cut_short(&button.container); + (button.allocate(ui).paint(ui).response, None, elided) + } + }; + // A selected text cut short shows in full on hover, as a truncated `Label`'s does: all of + // its text atoms, as screen readers receive them. `on_hover_ui` rather than `on_hover_text`, + // which would also make the text the button's accessible name and description. + let button_response = if show_tooltip_when_elided && elided { + button_response.on_hover_ui(|ui| { + ui.set_max_width(ui.spacing().tooltip_width); + ui.add(egui::Label::new(accessible_text.as_str()).wrap()); + }) + } else { + button_response }; button_response.widget_info(|| { @@ -348,6 +378,11 @@ fn show(ui: &mut Ui, button_id: Id, mut combo: ComboBox<'_>, open: impl FnOnc } } +/// Whether the button cut any of its selected text short. +fn cut_short(button: &SizedContainerAtom<'_>) -> bool { + button.iter_texts().any(|galley| galley.elided) +} + fn paint_default_icon(painter: &Painter, rect: Rect, visuals: &WidgetVisuals) { let rect = Rect::from_center_size(rect.center(), vec2(rect.width() * 0.7, rect.height() * 0.45)); painter.add(Shape::rotated_triangle(rect, 0.0, visuals.fg_stroke.color)); diff --git a/crates/ui/src/combo/tests.rs b/crates/ui/src/combo/tests.rs index fbef2413a..8cc754f2d 100644 --- a/crates/ui/src/combo/tests.rs +++ b/crates/ui/src/combo/tests.rs @@ -1,4 +1,7 @@ -use egui_kittest::{Harness, kittest::Queryable as _}; +use egui_kittest::{ + Harness, + kittest::{NodeT as _, Queryable as _}, +}; use super::ComboBox; @@ -142,6 +145,117 @@ fn show_index_picks_a_choice_and_marks_the_response_changed() { assert!(h.query_by_label("Medium").is_none(), "picking closes the menu"); } +const LONG_NAME: &str = "Artboard 12, back cover with the bleed and the fold marks"; + +/// A combo box with `LONG_NAME` selected, in room `width` wide, built by `combo`. +fn long_name_with(labeled: bool, width: f32, combo: impl Fn(ComboBox<'static>) -> ComboBox<'static> + 'static) -> Harness<'static> { + let mut h = Harness::builder().with_size(egui::vec2(600.0, 200.0)).with_accessibility_check(false).build_ui(move |ui| { + ui.set_max_width(width); + let plain = if labeled { ComboBox::new("board", "Board") } else { ComboBox::from_id_salt("board") }; + let _ = combo(plain.selected_text(LONG_NAME).width(100.0)).show_ui(ui, |ui| ui.label(LONG_NAME)); + }); + h.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + h.run(); + h +} + +/// A truncating combo box with `LONG_NAME` selected, in room `width` wide. +fn long_name(labeled: bool, width: f32) -> Harness<'static> { + long_name_with(labeled, width, ComboBox::truncate) +} + +/// Whether a tooltip shows `LONG_NAME` in full. +fn shows_in_full(h: &Harness<'_>) -> bool { + h.query_all_by_role(egui::Role::Label).any(|node| node.accesskit_node().value().as_deref() == Some(LONG_NAME)) +} + +#[test] +fn a_selected_text_cut_short_shows_in_full_on_hover() { + for labeled in [true, false] { + for (width, cut) in [(200.0, true), (600.0, false)] { + let mut h = long_name(labeled, width); + assert!(!shows_in_full(&h), "labeled {labeled}, {width}: no tooltip before the hover"); + h.get_by_role(egui::Role::ComboBox).hover(); + h.run(); + assert_eq!(shows_in_full(&h), cut, "labeled {labeled}, {width}: a tooltip shows the full text only when it is cut short"); + let node = h.get_by_role(egui::Role::ComboBox); + let node = node.accesskit_node(); + assert_eq!(node.value().as_deref(), Some(LONG_NAME), "labeled {labeled}, {width}: screen readers receive the full text"); + assert_eq!(node.description(), None, "labeled {labeled}, {width}: the tooltip does not describe the combo box"); + if !labeled { + assert_eq!(node.label(), None, "{width}: the tooltip does not name an unlabeled combo box"); + } + } + } +} + +#[test] +fn a_selected_text_cut_short_by_the_uis_wrap_mode_shows_in_full_on_hover() { + let text = [LONG_NAME; 3].join(", "); + let shown = text.clone(); + let mut h = Harness::builder().with_size(egui::vec2(600.0, 300.0)).with_accessibility_check(false).build_ui(move |ui| { + ui.set_max_width(200.0); + let _ = ComboBox::new("board", "Board").selected_text(shown.as_str()).width(100.0).show_ui(ui, |ui| ui.label("Other")); + }); + h.ctx.all_styles_mut(|style| { + style.interaction.tooltip_delay = 0.0; + style.wrap_mode = Some(egui::TextWrapMode::Truncate); + }); + h.run(); + h.get_by_role(egui::Role::ComboBox).hover(); + h.run(); + let button = h.get_by_role(egui::Role::ComboBox).rect(); + let tooltip = h.query_all_by_role(egui::Role::Label).find(|node| node.accesskit_node().value().as_deref() == Some(text.as_str())); + let tooltip = tooltip.map(|node| node.rect()); + assert!(tooltip.is_some(), "a combo box in a truncating Ui shows its cut text on hover"); + assert!( + tooltip.is_some_and(|rect| rect.height() > button.height()), + "the tooltip wraps the text onto several lines rather than cutting it short again: {tooltip:?}, button {button:?}" + ); +} + +#[test] +fn the_tooltip_for_a_cut_selected_text_can_be_turned_off() { + let mut h = long_name_with(false, 200.0, |combo| combo.truncate().show_tooltip_when_elided(false)); + h.get_by_role(egui::Role::ComboBox).hover(); + h.run(); + assert!(!shows_in_full(&h), "no tooltip when it is turned off"); +} + +#[test] +fn a_callers_tooltip_still_names_and_describes_a_cut_combo_box() { + let mut h = Harness::builder().with_size(egui::vec2(600.0, 200.0)).with_accessibility_check(false).build_ui(|ui| { + ui.set_max_width(200.0); + let combo = ComboBox::from_id_salt("board").selected_text(LONG_NAME).width(100.0).truncate().show_ui(ui, |ui| ui.label(LONG_NAME)); + let _ = combo.response.on_hover_text("Artboard"); + }); + h.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + h.run(); + h.get_by_role(egui::Role::ComboBox).hover(); + h.run(); + let node = h.get_by_role(egui::Role::ComboBox); + let node = node.accesskit_node(); + assert_eq!(node.label().as_deref(), Some("Artboard"), "the caller's tooltip names the combo box"); + assert_eq!(node.description().as_deref(), Some("Artboard"), "the caller's tooltip describes the combo box"); +} + +#[test] +fn a_selected_text_of_several_atoms_shows_all_of_them_on_hover() { + let mut h = Harness::builder().with_size(egui::vec2(600.0, 200.0)).build_ui(|ui| { + ui.set_max_width(200.0); + let _ = ComboBox::new("board", "Board").selected_text(("12", LONG_NAME)).width(100.0).truncate().show_ui(ui, |ui| ui.label(LONG_NAME)); + }); + h.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + h.run(); + h.get_by_role(egui::Role::ComboBox).hover(); + h.run(); + let full = format!("12 {LONG_NAME}"); + assert!( + h.query_all_by_role(egui::Role::Label).any(|node| node.accesskit_node().value().as_deref() == Some(full.as_str())), + "the tooltip shows {full:?}" + ); +} + fn sizes(ui: &mut egui::Ui, rows: usize) { for n in 0..rows { let size = SIZES.get(n).map_or_else(|| format!("Row {n}"), |s| (*s).to_owned());