diff --git a/crates/ui-contract/src/contract/overlay.rs b/crates/ui-contract/src/contract/overlay.rs index 516fafe177..edf0752691 100644 --- a/crates/ui-contract/src/contract/overlay.rs +++ b/crates/ui-contract/src/contract/overlay.rs @@ -28,7 +28,7 @@ pub(crate) use placement::{measuring_room, region_for, resolve_anchor, screen_fo pub(crate) use popups::dwell; pub use popups::{HOLD, Overlays, PopupHandle}; pub(crate) use popups::{apply_closes, begin_owner, note_layer_closed, open_map, popup_layer_open, popup_shown, popups_shown, write_open}; -pub use props::{Dismiss, Outside, Overlay, PlacementChange, PlacementKind}; +pub use props::{Dismiss, OpenerEscape, Outside, Overlay, PlacementChange, PlacementKind}; pub(crate) use toggles::{ToggleDecl, drive_toggles, has_toggle_nodes}; pub(crate) use ui::OverlayOwner; pub use ui::OverlayUi; diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index 627f6a5e87..f7733a8bb4 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -1,7 +1,7 @@ //! When a layer closes by itself (15.4): presses outside, Escape, and activations that keep it open. use super::host::{Layer, LayerMemory}; -use super::props::Outside; +use super::props::{OpenerEscape, Outside}; use crate::contract::{Component, Cx}; use crate::runtime::commands::FireSource; use crate::runtime::egui::pass; @@ -22,7 +22,7 @@ pub(super) fn dismissal( memory: &mut LayerMemory, ) -> Option { let dismiss = layer.overlay.dismiss; - // Both the Escape rule and the focus rule read the same fact: whether the focus is in the layer. + // Both start from actual layer membership; any opt-in opener Escape eligibility is handled separately. let inside = focus::focus_in_layer(ctx, layer.id); let was_inside = memory.focus_inside; if let Some(now) = inside { @@ -121,7 +121,17 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option, inside: // below): its card may have nothing to focus. So does a popup, whose body may have nothing to focus, and a // keep-anchor popup, which leaves the focus where it was. let owns_loose = layer.overlay.rank.is_modal() || layer.overlay.rank == Rank::Popup || policy.initial == Initial::KeepAnchor; - if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) { + // An opt-in opener rule is an Escape eligibility decision, not focus-scope membership. Match only the + // actual registered root of the explicit active opener, not a mutable scope-restoration opener or parent. + let opener = if layer.overlay.rank == Rank::Popup && layer.overlay.dismiss.opener_escape != OpenerEscape::Default { + layer.overlay.opener.as_ref().and_then(|first| { + let (opener, _) = first.active(ctx, None); + opener.enabled.then(|| focus::stop_rec(ctx, (opener.id, None))).flatten().filter(|rec| focus::focused_stop(ctx) == Some(rec.stop.key())) + }) + } else { + None + }; + if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) && opener.is_none() { return None; } // The focus may be in no record of the layer's host: the Escape is read from the events of the frame. @@ -140,7 +150,15 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option, inside: } else { keys::scope_escape(ctx, policy.cancel, pointer::press_captured(ctx), false)? }; - matches!(step, craft_behavior::focus::EscapeStep::CloseScope).then_some(CloseReason::Escape) + if !matches!(step, craft_behavior::focus::EscapeStep::CloseScope) { + return None; + } + if layer.overlay.dismiss.opener_escape == OpenerEscape::CloseAndBlur + && let Some(opener) = opener + { + focus::surrender_stop(ctx, opener.stop.key()); + } + Some(CloseReason::Escape) } impl Cx<'_, C> { diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 6357f13eba..863072eaef 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -28,6 +28,26 @@ pub enum Outside { Absorb, } +/// What an untaken Escape at a popup's explicit registered opener does. This does not make the opener a member +/// of the popup's focus scope or change its Tab order; the focus policy's `CancelRule::Ignore` still wins. +/// +/// `Default` is the focus policy's own eligibility: an untaken Escape reaches the top layer while the focus is in its +/// scope, in no layer at all, or on the opener of a scope that opens with `Initial::KeepAnchor` +/// (`focus::focus_in_layer` counts that opener). [`Overlay::popover`] normally opens with `Initial::First`. If a +/// popover opts into `Initial::Keep` and leaves focus on its opener in another layer, `Default` does not make that +/// opener eligible for dismissal. `Close` and `CloseAndBlur` opt into dismissal from that opener. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum OpenerEscape { + /// Use the existing focus-policy eligibility; no additional opener rule. + #[default] + Default, + /// Close from the exact registered opener, without an extra focus change. + Close, + /// Close from that opener and leave its key focus, without focusing or clearing any other stop. + CloseAndBlur, +} + /// When a layer closes by itself. Escape goes through the focus policy's `CancelRule`. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -38,6 +58,8 @@ pub struct Dismiss { pub enter: bool, /// Focus moved out of the layer's scope. pub focus_left: bool, + /// Additional Escape eligibility at the exact registered opener of a popup; unchanged by default. + pub opener_escape: OpenerEscape, /// A component inside was activated. An opener whose activation toggled its popup (a trigger, `Popup::toggle`) and /// a row that keeps the chain open (`Cx::keep_open`) do not count. pub on_activate: bool, @@ -52,7 +74,16 @@ pub struct Dismiss { impl Dismiss { /// An outside press or a command closes; nothing else does. pub const fn new() -> Self { - Dismiss { outside: Outside::Close, enter: false, focus_left: false, on_activate: false, anchor_gone: true, commands: true, timeout: None } + Dismiss { + outside: Outside::Close, + enter: false, + focus_left: false, + opener_escape: OpenerEscape::Default, + on_activate: false, + anchor_gone: true, + commands: true, + timeout: None, + } } /// Sets what an outside press does. @@ -73,6 +104,13 @@ impl Dismiss { self } + /// Chooses what an untaken Escape at a popup's explicit registered opener does, independently of traversal + /// and the usual restoration policy. Only that exact root stop qualifies, never another stop of its parent. + pub const fn opener_escape(mut self, policy: OpenerEscape) -> Self { + self.opener_escape = policy; + self + } + /// Closes when a component inside is activated, except an opener toggling its popup. pub const fn on_activate(mut self, on: bool) -> Self { self.on_activate = on; diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 553c8754e3..44e38d6e20 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -968,6 +968,14 @@ pub fn focused_rec(ctx: &Context) -> Option { }) } +/// Gives up the focus of this exact registered stop only if it still holds it. The overlay's explicit +/// opener-Escape blur uses the focus service's usual action path; it cannot clear another member of an arena. +pub(crate) fn surrender_stop(ctx: &Context, key: StopKey) { + if let Some(rec) = focused_rec(ctx).filter(|rec| rec.stop.key() == key) { + apply(ctx, vec![Act::Surrender(rec.stop.root)]); + } +} + /// Whether the focus stop is a child of a collection row's roving group. pub(crate) fn in_row_child(ctx: &Context) -> bool { with(ctx, |state| { diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 07a4687220..ac3e6ff5de 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -411,12 +411,22 @@ impl State { self.last_scope_order.iter().rev().find(|id| self.last_scopes.get(id).is_some_and(|scope| scope.policy.trap)).copied() } + /// A stop's place in last pass's Tab order: its index among the stops Tab and the arrows move over, the order the + /// entries keep. + fn place(&self, rec: &StopRec) -> usize { + self.last_stops.iter().position(|stop| stop.stop.key() == rec.stop.key()).unwrap_or(usize::MAX) + } + /// A Tab move. In a dialog's trap with `dialog_tab` at `Fields`, only text stops are entries, whatever the /// window's rule: a roving group whose arrival member holds no text is skipped too. pub(super) fn tab(&mut self, forward: bool, all_controls: bool, dialog_tab: TabReach) -> Vec { - let (current, entries) = self.tab_entries(all_controls, dialog_tab); + let (current, entries, after) = self.tab_entries(all_controls, dialog_tab); let top = current.as_ref().and_then(|rec| rec.stop.group).map(|group| self.last().outermost(group)); - let Some(next) = cycle(&entries, current.as_ref(), top, forward) else { return Vec::new() }; + let Some(mut next) = cycle(&entries, current.as_ref(), top, forward) else { return Vec::new() }; + if let Some(after) = after { + let count = entries.len(); + next = if forward { after % count } else { (after + count - 1) % count }; + } let arrival = entries[next].arrival().clone(); self.focus_stop(arrival) } @@ -424,18 +434,75 @@ impl State { /// The Tab entries this pass moves over, from the stop the focus is on (a row's child tabs on from its collection, /// a dropdown's content from its anchor). They are last pass's entries: what `tab` cycles, and what a Tab that /// landed on a stop this pass does not show goes on through. - fn tab_entries(&self, all_controls: bool, dialog_tab: TabReach) -> (Option, Vec) { + fn tab_entries(&self, all_controls: bool, dialog_tab: TabReach) -> (Option, Vec, Option) { let current = self.stop_of_focus().map(|rec| { let owner = rec.stop.group.and_then(|group| self.group(group)).filter(|group| group.row).and_then(|group| self.row_owner(&group)); let rec = owner.unwrap_or(rec); self.anchored_layer(rec.scope).and_then(|opener| self.find_stop(opener)).unwrap_or(rec) }); - let trap = self.trap_of(current.as_ref()); + // Tab out of a menu that lets it leave (`Menu::tab_exits`) goes on from the menu's opener, either way, as if the + // menu were part of it: the menu's own rows are no entries, so Shift+Tab reaches the stop before the opener. + let exits = current.as_ref().and_then(|rec| self.tab_exit_menu(rec.scope)); + // the trap is read before the exit swaps the focus for the menu's opener: a trapping submenu's trap must still + // hold, and its opener sits outside it + let trap_of_focus = self.trap_of(current.as_ref()); + let current = exits.and_then(|menu| self.return_stop(menu)).or(current); + let trap = trap_of_focus.or_else(|| self.trap_of(current.as_ref())); let in_dialog = trap.and_then(|id| self.last_scopes.get(&id)).is_some_and(|scope| scope.policy.kind == ScopeKind::Dialog); let fields = in_dialog && dialog_tab == TabReach::Fields; let mut entries = self.entries(trap, all_controls && !fields); - entries.retain(|entry| self.anchored_layer(entry.arrival().scope).is_none() && (!fields || entry.arrival().stop.text)); - (current, entries) + // A layer playing its exit takes no focus (`exiting`): an Escape that closed a menu leaves it no Tab entry for the + // fade's frames, so the next Tab does not land in it and have the closed menu hand the focus back to its opener. + entries.retain(|entry| { + let scope = entry.arrival().scope; + self.anchored_layer(scope).is_none() + && !self.exiting(scope) + && exits.is_none_or(|menu| !self.within(scope, menu)) + && (!fields || entry.arrival().stop.text) + }); + // The opener a `tab_exits` menu hands Tab to is no entry itself where only some stops are (a non-text opener in a + // dialog that tabs through fields): it keeps its place in the order, so Tab takes the entry after that place and + // Shift+Tab the one before, and the neighbour stays the one beside the opener. + let missing_opener = current.as_ref().filter(|opener| { + exits.is_some() && !entries.iter().any(|entry| entry.holds(opener, opener.stop.group.map(|group| self.last().outermost(group)))) + }); + let after = missing_opener.map(|opener| { + let place = self.place(opener); + entries.iter().filter(|entry| self.place(entry.arrival()) < place).count() + }); + (current, entries, after) + } + + /// The menu around `scope` that Tab leaves (`Menu::tab_exits`): a menu scope that traps nothing. The walk stops at a + /// dialog: a dialog shown from inside such a menu records it as the scope around it, and its trap keeps Tab inside + /// it until it closes. + fn tab_exit_menu(&self, scope: Option) -> Option { + let mut at = scope; + while let Some(id) = at { + let rec = self.last_scopes.get(&id)?; + // The first scope that traps ends the walk, whatever it is: a dialog shown from inside such a menu, or a + // submenu that traps its own keys. Its trap keeps Tab inside it until it closes. + if rec.policy.trap { + return None; + } + if rec.policy.kind == ScopeKind::Menu { + return Some(id); + } + at = rec.parent; + } + None + } + + /// Whether the scope `scope`, or one around it, is a layer playing its exit, by this pass's record or else the last. + fn exiting(&self, scope: Option) -> bool { + let mut at = scope; + while let Some(rec) = at.and_then(|id| self.scopes.get(&id).or_else(|| self.last_scopes.get(&id))) { + if rec.closing { + return true; + } + at = rec.parent; + } + false } /// F6: the first stop of the next pane, with its label as the announcement. Inside a trapping scope (a modal @@ -639,7 +706,7 @@ impl State { if !arrived { return None; } - let (current, entries) = self.tab_entries(self.tab_all_controls, self.dialog_tab); + let (current, entries, _) = self.tab_entries(self.tab_all_controls, self.dialog_tab); let current = current?; let top = current.stop.group.map(|group| self.last().outermost(group)); let at = entries.iter().position(|entry| entry.holds(¤t, top))?; diff --git a/crates/ui-widgets/src/menu/popup.rs b/crates/ui-widgets/src/menu/popup.rs index 9026af1fd9..70d23a2110 100644 --- a/crates/ui-widgets/src/menu/popup.rs +++ b/crates/ui-widgets/src/menu/popup.rs @@ -262,6 +262,17 @@ impl<'a> Menu<'a> { .label(label) } + /// Tab leaves this anchored menu in the opener's tab order instead of wrapping in the menu. + /// Arrow keys still navigate rows. A focus move out closes it without running a row. + #[must_use] + pub fn tab_exits(self) -> Self { + self.with_layer(|mut layer| { + layer.focus = layer.focus.trap(false); + layer.dismiss = layer.dismiss.focus_left(true); + layer + }) + } + /// Marks the menu as a value menu: every row is a radio item, whether or not an entry is checked, and the checked /// entry holds the lead when the menu opens. #[must_use] diff --git a/crates/ui-widgets/tests/it/menu/mod.rs b/crates/ui-widgets/tests/it/menu/mod.rs index fc32c6587e..9bd67d1e72 100644 --- a/crates/ui-widgets/tests/it/menu/mod.rs +++ b/crates/ui-widgets/tests/it/menu/mod.rs @@ -28,6 +28,8 @@ pub(crate) mod search; pub(crate) mod submenus; +pub(crate) mod tab_exits; + use craft_behavior::IconId; use craft_ui::contract::{Show as _, ShowContainer as _}; use craft_ui::layout_components::Stack; diff --git a/crates/ui-widgets/tests/it/menu/tab_exits.rs b/crates/ui-widgets/tests/it/menu/tab_exits.rs new file mode 100644 index 0000000000..9c66e4f59e --- /dev/null +++ b/crates/ui-widgets/tests/it/menu/tab_exits.rs @@ -0,0 +1,286 @@ +//! `Menu::tab_exits`: Tab in an anchored menu leaves it for the next stop after its opener and closes it without +//! running a row; without it, Tab stays in the menu. + +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Overlay, Role, Show as _, ShowContainer as _, Trigger}; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::popover::Popover; +use craft_ui::runtime::focus::{self, FocusTarget, TabReach}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::TextField; +use egui::{Id, Key, Modifiers}; +use std::cell::Cell; +use std::rc::Rc; + +/// "Before", a "Preset" button opening a menu of two presets, and "After"; the menu opened from the keyboard. +struct Rig { + fixture: Fixture, + ran: Rc>, + before: Rc>>, + opener: Rc>>, + after: Rc>>, +} + +fn rig(exits: bool) -> Rig { + rig_with_offer(exits, false) +} + +fn rig_with_offer(exits: bool, offer: bool) -> Rig { + let transient = Cell::new(None); + let ran = Rc::new(Cell::new(0)); + let before = Rc::new(Cell::new(None)); + let after = Rc::new(Cell::new(None)); + let opener = Rc::new(Cell::new(None)); + let (shown_ran, shown_before, shown_after, shown_opener) = (ran.clone(), before.clone(), after.clone(), opener.clone()); + let mut fixture = Fixture::new(move |ui| { + shown_before.set(Some(Button::new("Before").show(ui).id)); + let preset = Button::new("Preset").show(ui); + shown_opener.set(Some(preset.id)); + let menu = Menu::new("Presets").opened_by(&preset, Trigger::Press); + let menu = if exits { menu.tab_exits() } else { menu }; + menu.show(ui, |ui, _| { + if MenuItem::new("Linear").show(ui).ran { + shown_ran.set(shown_ran.get() + 1); + } + if MenuItem::new("Strong").show(ui).ran { + shown_ran.set(shown_ran.get() + 1); + } + }); + if offer && !focus::focused_rec(ui.ctx()).is_some_and(|rec| Some(rec.stop.id) == transient.get()) { + transient.set(Some(Button::new("Offer").show(ui).id)); + } + shown_after.set(Some(Button::new("After").show(ui).id)); + }); + fixture.settle(); + focus::request(fixture.ctx(), FocusTarget::Id(opener.get().expect("the opener ran"))); + fixture.settle(); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + assert!(fixture.by_label("Linear").is_some(), "Enter on the focused opener opens the menu"); + Rig { fixture, ran, before, opener, after } +} + +impl Rig { + fn menu_open(&self) -> bool { + !self.fixture.by_role(Role::MENU).is_empty() + } + + fn tab(&mut self) { + self.fixture.key(Key::Tab, Modifiers::NONE); + self.fixture.settle(); + } + + fn focused(&self) -> Option { + self.fixture.focused_stop().map(|(id, _)| id) + } +} + +#[trial] +fn tab_stays_in_a_menu_by_default() { + let mut rig = rig(false); + rig.tab(); + assert!(rig.menu_open(), "the menu stays open"); + assert_ne!(rig.fixture.focused_stop().map(|(id, _)| id), rig.after.get(), "the focus stays in the menu"); +} + +/// The outer menu lets Tab leave, but the default submenu keeps both traversal directions inside itself. +#[trial] +fn tab_stays_in_a_trapping_submenu_of_a_tab_exits_menu() { + let nested_first = Rc::new(Cell::new(None)); + let nested_last = Rc::new(Cell::new(None)); + let (first, last) = (nested_first.clone(), nested_last.clone()); + let mut fixture = Fixture::new(move |ui| { + Button::new("Before presets").show(ui); + let opener = Button::new("Choose preset").show(ui); + Menu::new("Presets").opened_by(&opener, Trigger::Click).tab_exits().show(ui, |ui, _| { + Menu::submenu_row(ui, "Built-in presets", |ui, _| { + first.set(Some(MenuItem::new("Soft preset").show(ui).response.id)); + last.set(Some(MenuItem::new("Strong preset").show(ui).response.id)); + }); + }); + Button::new("After presets").show(ui); + }); + fixture.settle(); + let opener = fixture.by_label("Choose preset").expect("the outer menu's opener"); + fixture.click(&opener).settle(); + let row = fixture.by_label("Built-in presets").expect("the outer menu shows its submenu row"); + fixture.frame(vec![craft_ui::testing::pointer::moved(row.center())]).settle(); + assert!(fixture.by_label("Soft preset").is_some(), "the real submenu is open"); + let first = nested_first.get().expect("the first submenu stop was shown"); + let last = nested_last.get().expect("the last submenu stop was shown"); + for (start, modifiers) in [(last, Modifiers::NONE), (first, Modifiers::SHIFT)] { + focus::request(fixture.ctx(), FocusTarget::Id(start)); + fixture.settle(); + assert_eq!(fixture.focused_stop().map(|(id, _)| id), Some(start), "traversal starts inside the submenu"); + fixture.key(Key::Tab, modifiers).settle(); + assert!(fixture.focused_stop().is_some_and(|(id, _)| id == first || id == last), "the inner trap keeps focus for {modifiers:?}"); + assert!(fixture.by_label("Soft preset").is_some(), "the submenu stays open for {modifiers:?}"); + } +} + +/// A dialog mounted by an exiting menu owns traversal, even though its parent would let Tab leave. +/// Window rank keeps the parent popup open without changing the dialog focus trap. +#[trial] +fn tab_stays_in_a_dialog_opened_inside_a_tab_exits_menu() { + let open = Rc::new(Cell::new(false)); + let first = Rc::new(Cell::new(None)); + let last = Rc::new(Cell::new(None)); + let (shown_open, shown_first, shown_last) = (open.clone(), first.clone(), last.clone()); + let mut fixture = Fixture::new(move |ui| { + Button::new("Before options").show(ui); + let opener = Button::new("Options").show(ui); + Menu::new("Options menu").opened_by(&opener, Trigger::Click).tab_exits().show(ui, |ui, _| { + MenuItem::new("Menu option").show(ui); + let mut dialog_open = shown_open.get(); + Popover::new("Option details", Bind::bound(&mut dialog_open)) + .overlay(|_| Overlay::dialog().modeless()) + .initial_focus(focus::Initial::First) + .show(ui, |ui, _| { + shown_first.set(Some(Button::new("First dialog control").show(ui).id)); + shown_last.set(Some(Button::new("Last dialog control").show(ui).id)); + }); + shown_open.set(dialog_open); + }); + Button::new("After options").show(ui); + }); + fixture.settle(); + let opener = fixture.by_label("Options").expect("the menu's opener"); + fixture.click(&opener).settle(); + assert!(fixture.by_label("Menu option").is_some(), "the exiting menu is open before its dialog is mounted"); + open.set(true); + fixture.settle(); + let first = first.get().expect("the dialog's first control"); + let last = last.get().expect("the dialog's last control"); + assert!(open.get() && fixture.by_label("First dialog control").is_some(), "the nested dialog is shown"); + assert!(fixture.by_label("Menu option").is_some(), "the parent menu remains open"); + assert_eq!(fixture.focused_stop().map(|(id, _)| id), Some(first), "traversal starts inside the dialog"); + for (end, modifiers) in [(last, Modifiers::SHIFT), (first, Modifiers::NONE)] { + fixture.key(Key::Tab, modifiers).settle(); + assert_eq!(fixture.focused_stop().map(|(id, _)| id), Some(end), "Tab wraps inside the dialog for {modifiers:?}"); + assert!(open.get(), "the dialog stays open for {modifiers:?}"); + } +} + +#[trial] +fn tab_leaves_a_tab_exits_menu_for_the_stop_after_its_opener() { + let mut rig = rig(true); + rig.tab(); + assert!(!rig.menu_open(), "the menu closes"); + assert_eq!(rig.ran.get(), 0, "no row runs"); + assert_eq!(rig.fixture.focused_stop().map(|(id, _)| id), rig.after.get(), "the focus moves to the stop after the opener"); +} + +#[trial] +fn tab_leaves_the_menu_and_continues_past_a_stop_gone_on_arrival() { + let mut rig = rig_with_offer(true, true); + assert!(rig.fixture.by_label("Offer").is_some(), "the transient stop is the next entry after the opener"); + rig.tab(); + assert!(!rig.menu_open(), "the menu closes even though the first Tab destination went away"); + assert_eq!(rig.ran.get(), 0, "no row runs"); + assert_eq!(rig.focused(), rig.after.get(), "focus advances to the next still-shown entry"); +} + +#[trial] +fn arrows_still_move_through_a_tab_exits_menu() { + let mut rig = rig(true); + rig.fixture.key(Key::ArrowDown, Modifiers::NONE); + rig.fixture.settle(); + assert!(rig.menu_open(), "an arrow key keeps the menu open"); + rig.fixture.key(Key::Enter, Modifiers::NONE); + rig.fixture.settle(); + assert_eq!(rig.ran.get(), 1, "Enter runs the row the arrows reached"); +} + +#[trial] +fn shift_tab_leaves_a_tab_exits_menu_for_the_stop_before_its_opener() { + let mut rig = rig(true); + rig.fixture.key(Key::ArrowDown, Modifiers::NONE); + rig.fixture.key(Key::Tab, Modifiers::SHIFT); + rig.fixture.settle(); + assert!(!rig.menu_open(), "the menu closes"); + assert_eq!(rig.ran.get(), 0, "no row runs"); + assert_eq!(rig.focused(), rig.before.get(), "the focus moves to the stop before the opener, not back to the opener"); +} + +/// An Escape closes the menu and gives the focus back to its opener; a Tab pressed while the menu still plays its exit +/// goes on to the stop after the opener, and the closing menu does not take the focus back. +#[trial] +fn tab_right_after_escape_goes_on_from_the_opener_of_a_tab_exits_menu() { + let mut rig = rig(true); + rig.fixture.key(Key::ArrowDown, Modifiers::NONE); + rig.fixture.key(Key::Escape, Modifiers::NONE); + assert_eq!(rig.focused(), rig.opener.get(), "Escape gives the focus back to the opener"); + rig.fixture.key(Key::Tab, Modifiers::NONE); + rig.fixture.settle(); + assert!(!rig.menu_open(), "the menu is closed"); + assert_eq!(rig.ran.get(), 0, "no row runs"); + assert_eq!(rig.focused(), rig.after.get(), "the focus goes on to the stop after the opener and stays there"); +} + +/// Where Tab reaches only text fields (a Mac's default), a `tab_exits` menu's non-text opener is no Tab entry itself: it +/// still holds its place in the order, so Tab goes on to the field after it and Shift+Tab to the one before. +#[trial] +fn tab_that_reaches_only_fields_leaves_a_tab_exits_menu_for_the_field_beside_its_opener() { + let before = Rc::new(Cell::new(None)); + let after = Rc::new(Cell::new(None)); + let opener = Rc::new(Cell::new(None)); + let (shown_before, shown_after, shown_opener) = (before.clone(), after.clone(), opener.clone()); + let mut text = (String::new(), String::new()); + let mut fixture = Fixture::new(move |ui| { + let mut first = std::mem::take(&mut text.0); + shown_before.set(Some(craft_ui::text::TextField::new("Before", craft_ui::contract::Bind::bound(&mut first)).show(ui).response.id)); + text.0 = first; + let preset = Button::new("Preset").show(ui); + shown_opener.set(Some(preset.id)); + Menu::new("Presets").opened_by(&preset, Trigger::Press).tab_exits().show(ui, |ui, _| { + MenuItem::new("Linear").show(ui); + }); + let mut second = std::mem::take(&mut text.1); + shown_after.set(Some(craft_ui::text::TextField::new("After", craft_ui::contract::Bind::bound(&mut second)).show(ui).response.id)); + text.1 = second; + }); + fixture.os(craft_host::target::Os::Mac); + let mut root = craft_ui::runtime::env::RootEnv::default(); + root.tab_all_controls = false; + fixture.root(root); + fixture.settle(); + focus::request(fixture.ctx(), FocusTarget::Id(opener.get().expect("the opener ran"))); + fixture.settle(); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + assert!(fixture.by_label("Linear").is_some(), "Enter on the focused opener opens the menu"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + assert!(fixture.by_label("Linear").is_none(), "Tab leaves the menu"); + assert_eq!(fixture.focused_stop().map(|(id, _)| id), after.get(), "Tab goes on to the field after the opener"); +} + +/// In a fields-only dialog the opener is not a Tab entry; reverse Tab must still use its place between fields. +#[trial] +fn shift_tab_in_a_fields_only_dialog_leaves_the_menu_for_the_field_before_its_opener() { + let before = Rc::new(Cell::new(None)); + let opener = Rc::new(Cell::new(None)); + let (shown_before, shown_opener) = (before.clone(), opener.clone()); + let mut names = (String::new(), String::new()); + let mut fixture = Fixture::new(move |ui| { + Popover::new("Preset options", Bind::given(true)).overlay(|_| Overlay::dialog()).show(ui, |ui, _| { + shown_before.set(Some(TextField::new("Preset name", Bind::bound(&mut names.0)).show(ui).response.id)); + let pick = Button::new("Choose effect").show(ui); + shown_opener.set(Some(pick.id)); + Menu::new("Effects").opened_by(&pick, Trigger::Press).tab_exits().show(ui, |ui, _| { + MenuItem::new("Smooth").show(ui); + }); + TextField::new("Preset notes", Bind::bound(&mut names.1)).show(ui); + }); + }); + let mut root = craft_ui::runtime::env::RootEnv::default(); + root.dialog_tab = TabReach::Fields; + fixture.root(root).settle(); + focus::request(fixture.ctx(), FocusTarget::Id(opener.get().expect("the dialog's menu opener"))); + fixture.settle(); + fixture.key(Key::Enter, Modifiers::NONE).settle(); + assert!(fixture.by_label("Smooth").is_some(), "the menu is open inside the dialog"); + fixture.key(Key::Tab, Modifiers::SHIFT).settle(); + assert!(fixture.by_label("Smooth").is_none(), "Shift+Tab closes the menu"); + assert_eq!(fixture.focused_stop().map(|(id, _)| id), before.get(), "Shift+Tab lands on the field before the non-field opener"); +} diff --git a/crates/ui-widgets/tests/it/popover/mod.rs b/crates/ui-widgets/tests/it/popover/mod.rs index 5e0ea49bad..0bba594fbc 100644 --- a/crates/ui-widgets/tests/it/popover/mod.rs +++ b/crates/ui-widgets/tests/it/popover/mod.rs @@ -2,4 +2,5 @@ pub(crate) mod commands; pub(crate) mod one_at_a_time; +pub(crate) mod opener_escape; pub(crate) mod popup; diff --git a/crates/ui-widgets/tests/it/popover/opener_escape.rs b/crates/ui-widgets/tests/it/popover/opener_escape.rs new file mode 100644 index 0000000000..e88f7d907f --- /dev/null +++ b/crates/ui-widgets/tests/it/popover/opener_escape.rs @@ -0,0 +1,128 @@ +//! A popover that leaves the focus on its opener (`Initial::Keep`, no focus trap) and hangs from an opener inside +//! another layer (a dialog's or a popover's button) closes on an Escape at that opener only when its dismissal asks for +//! it (`Dismiss::opener_escape`): with the focus in the outer layer, the inner popover is the top layer but holds no +//! focus, so without the rule the Escape closes nothing. `Close` keeps the opener focused; `CloseAndBlur` also gives +//! up the opener's focus. An opener in the window (no layer) needs no rule: a popup already takes an Escape while the +//! focus is in no layer. + +use craft_ui::buttons::Button; +use craft_ui::contract::overlay::OpenerEscape; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _, clicked}; +use craft_ui::popover::Popover; +use craft_ui::runtime::focus::{self, FocusTarget, Initial}; +use craft_ui::testing::{Fixture, trial}; +use egui::{Id, Key, Modifiers, Ui}; +use std::cell::Cell; +use std::rc::Rc; + +/// The group choices popover hanging from a "Group" button, which keeps the focus while the popover is open. +fn choices(ui: &mut Ui, open: &Cell, opener: &Cell>, rule: OpenerEscape) { + let picker = Button::new("Group").show(ui); + opener.set(Some(picker.id)); + let mut is_open = open.get(); + if clicked(&picker) { + is_open = !is_open; + } + Popover::new("Groups", Bind::bound(&mut is_open)) + .opened_by(&picker) + .initial_focus(Initial::Keep) + .overlay(|mut overlay| { + overlay.focus = overlay.focus.trap(false); + overlay.dismiss = overlay.dismiss.focus_left(false).opener_escape(rule); + overlay + }) + .show(ui, |ui, _| { + Button::new("Portraits").show(ui); + Button::new("Landscapes").show(ui); + }); + open.set(is_open); +} + +struct Rig { + fixture: Fixture, + open: Rc>, + /// The outer popover's open state, kept outside the fixture: a settle pass cannot reopen it and hide a wrong close. + outer: Rc>, + opener: Rc>>, +} + +/// The choices, with their opener inside an outer popover ("Save effect") when `nested`, else in the window. +fn rig(rule: OpenerEscape, nested: bool) -> Rig { + let open = Rc::new(Cell::new(false)); + let opener = Rc::new(Cell::new(None)); + let outer_open = Rc::new(Cell::new(true)); + let (shown_open, shown_opener, shown_outer) = (open.clone(), opener.clone(), outer_open.clone()); + let mut fixture = Fixture::new(move |ui| { + let save = Button::new("Save effect").show(ui); + if nested { + let mut outer = shown_outer.get(); + Popover::new("Save effect", Bind::bound(&mut outer)).opened_by(&save).show(ui, |ui, _| { + Button::new("Name").show(ui); + choices(ui, &shown_open, &shown_opener, rule); + }); + shown_outer.set(outer); + } else { + choices(ui, &shown_open, &shown_opener, rule); + } + }); + fixture.settle(); + let id = opener.get().expect("the opener ran"); + focus::request(fixture.ctx(), FocusTarget::Id(id)); + fixture.settle(); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + assert!(open.get(), "Enter on the focused opener opens the popover"); + assert!(fixture.by_label("Portraits").is_some(), "the popover shows its choices"); + assert_eq!(fixture.focused_stop().map(|(id, _)| id), Some(id), "the opener keeps the focus (Initial::Keep)"); + Rig { fixture, open, outer: outer_open, opener } +} + +impl Rig { + fn escape(&mut self) { + self.fixture.key(Key::Escape, Modifiers::NONE); + self.fixture.settle(); + } + + fn opener_focused(&self) -> bool { + self.fixture.focused_stop().map(|(id, _)| id) == self.opener.get() + } + + fn outer_open(&self) -> bool { + self.outer.get() && self.fixture.by_label("Name").is_some() + } +} + +#[trial] +fn escape_at_an_opener_in_another_layer_leaves_the_popover_open_by_default() { + let mut rig = rig(OpenerEscape::Default, true); + rig.escape(); + assert!(rig.open.get() && rig.fixture.by_label("Portraits").is_some(), "without the rule the popover stays open"); + assert!(rig.outer_open(), "and so does the layer around the opener"); +} + +#[trial] +fn opener_escape_close_closes_the_popover_and_keeps_the_opener_focused() { + let mut rig = rig(OpenerEscape::Close, true); + rig.escape(); + assert!(!rig.open.get(), "the Escape at the opener closes the popover"); + assert!(rig.fixture.by_label("Portraits").is_none(), "the choices are gone"); + assert!(rig.outer_open(), "the layer around the opener stays open"); + assert!(rig.opener_focused(), "the opener keeps the focus"); +} + +#[trial] +fn opener_escape_close_and_blur_closes_the_popover_and_leaves_the_opener() { + let mut rig = rig(OpenerEscape::CloseAndBlur, true); + rig.escape(); + assert!(!rig.open.get(), "the Escape at the opener closes the popover"); + assert!(rig.outer_open(), "the layer around the opener stays open"); + assert!(!rig.opener_focused(), "the opener gives up the focus"); +} + +#[trial] +fn escape_at_an_opener_in_the_window_closes_the_popover_without_the_rule() { + let mut rig = rig(OpenerEscape::Default, false); + rig.escape(); + assert!(!rig.open.get(), "a popup takes the Escape while the focus is in no layer"); + assert!(rig.opener_focused(), "and the opener keeps the focus"); +}