From a8cc821ff960d686ed868008d578d52c162e524f Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 12 Nov 2026 00:58:29 +0000 Subject: [PATCH] Dropdowns close when the focus leaves their anchor, and Tab in an open Select chooses the row the keys reached Overlay::dropdown dismisses on focus left (the tree picker and font rows keep it with their own Dismiss). CloseReason::FocusLeft carries what moved the focus (FocusMove: keyboard navigation, or a press or code), recorded where the focus service applies Tab, Shift+Tab and F6. OverlayUi::closing tells the opener why its popup closes this pass: Select commits its proposal on a keyboard focus move, cancels on Escape and on any other focus move. A dropdown's content is no Tab entry, and Tab from inside it goes on from its anchor. --- crates/font-manager/src/picker/rows.rs | 2 +- crates/menu/src/shortcuts/mod.rs | 2 +- .../src/contract/overlay/dismissal.rs | 2 +- .../ui-contract/src/contract/overlay/props.rs | 4 +-- crates/ui-contract/src/contract/overlay/ui.rs | 6 ++++ crates/ui-contract/src/runtime/focus.rs | 15 ++++++++++ crates/ui-contract/src/runtime/focus/nav.rs | 25 ++++++++++++++-- crates/ui-contract/src/runtime/focus/press.rs | 3 ++ crates/ui-contract/src/runtime/overlay.rs | 4 +-- crates/ui-widgets/src/pickers/select.rs | 13 +++++++- crates/ui-widgets/src/pickers/tree_picker.rs | 2 +- .../tests/it/pickers/select_list.rs | 30 +++++++++++++++++-- 12 files changed, 94 insertions(+), 14 deletions(-) diff --git a/crates/font-manager/src/picker/rows.rs b/crates/font-manager/src/picker/rows.rs index 13e90e94b..d96de9110 100644 --- a/crates/font-manager/src/picker/rows.rs +++ b/crates/font-manager/src/picker/rows.rs @@ -183,7 +183,7 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx: } let name = words.list.clone(); let mut stars: Vec<(String, bool)> = Vec::new(); - let events = ui.show(popup, Overlay::dropdown().dismiss(Dismiss::new()), |ui, _| { + let events = ui.show(popup, Overlay::dropdown().dismiss(Dismiss::new().focus_left(true)), |ui, _| { let mut events = Vec::new(); Stack::new().show(ui, |ui, _| { if let Some(filters) = filters.as_mut() { diff --git a/crates/menu/src/shortcuts/mod.rs b/crates/menu/src/shortcuts/mod.rs index bffe2ff89..3f768296f 100644 --- a/crates/menu/src/shortcuts/mod.rs +++ b/crates/menu/src/shortcuts/mod.rs @@ -554,7 +554,7 @@ fn frame(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) -> ShortcutsOu } match closed { Some(CloseReason::Escape) => state.escape(env), - Some(CloseReason::Requested | CloseReason::Outside | CloseReason::FocusLeft) => state.cancel(env), + Some(CloseReason::Requested | CloseReason::Outside | CloseReason::FocusLeft(_)) => state.cancel(env), _ => {} } state.sync_set(env); diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index 866f9ee8a..0e4de919e 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -59,7 +59,7 @@ pub(super) fn dismissal( && inside == Some(false) && overlay::is_open(ctx, layer.id) { - return Some(CloseReason::FocusLeft); + return Some(CloseReason::FocusLeft(focus::move_this_pass(ctx))); } if let Some(timeout) = dismiss.timeout { let now = frame::clock(ctx); diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index d66f9a7d4..fdc49cf0d 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -184,11 +184,11 @@ impl Overlay { } /// A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - /// closes when a row is activated. + /// closes when a row is activated or the focus leaves the anchor. pub fn dropdown() -> Overlay { let focus = FocusPolicy::POPUP.trap(false).restore(false).initial(Initial::KeepAnchor); let mut overlay = Overlay::base(Rank::Popup, Overlay::below(), OverlayFit::ContentCapped(DROPDOWN_SHARE), OwnerClass::PassivePopup, focus); - overlay.dismiss = Dismiss::new().on_activate(true); + overlay.dismiss = Dismiss::new().on_activate(true).focus_left(true); overlay.min_width = MinWidth::Anchor; overlay.popup = PopupKind::Listbox; overlay diff --git a/crates/ui-contract/src/contract/overlay/ui.rs b/crates/ui-contract/src/contract/overlay/ui.rs index 44d8cd40b..a5eec7e7e 100644 --- a/crates/ui-contract/src/contract/overlay/ui.rs +++ b/crates/ui-contract/src/contract/overlay/ui.rs @@ -53,6 +53,12 @@ impl<'a> OverlayUi<'a> { OverlayUi { ctx, owner: id, anchor, to_screen, resolved, env, open, closed: Vec::new(), parts } } + /// Why `popup` closes at the end of this pass, as its `show` decided (its dismissal, or a close its body asked for); + /// `None` while it stays open. The component that opened it reads this to settle what the popup was proposing. + pub fn closing(&self, popup: PopupHandle) -> Option { + self.closed.iter().find(|(id, _)| *id == popup.id).map(|(_, reason)| *reason) + } + /// The anchor at the rect of the toggling part `part` of the owner. The layer's placement mirrors the side and /// alignment of an anchor in a right-to-left layout, so the same call serves both directions. pub fn anchor_part(&self, part: impl Into) -> Anchor { diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 20d9e77f2..fd2bc012b 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -545,6 +545,21 @@ pub(crate) fn commit_now(ctx: &Context) -> Option { with(ctx, |state| state.press.commit_now) } +/// What moved the key focus. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum FocusMove { + /// Keyboard navigation: Tab, Shift+Tab or F6. + Keys, + /// A press elsewhere, or code. + Other, +} + +/// What moved the focus in this pass: `Keys` when Tab, Shift+Tab or F6 moved it. +pub(crate) fn move_this_pass(ctx: &Context) -> FocusMove { + if with(ctx, |state| state.press.by_keys) { FocusMove::Keys } else { FocusMove::Other } +} + /// Whether a Tab (`Some(true)`) or Shift+Tab (`Some(false)`) moved focus off the widget `widget` in this pass. pub(crate) fn tabbed_off(ctx: &Context, widget: Id) -> Option { with(ctx, |state| state.press.tabbed_from.filter(|(from, _)| *from == widget).map(|(_, forward)| forward)) diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index abc42ca6a..549ce68df 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -200,6 +200,20 @@ impl State { false } + /// The stop that opened the innermost scope around `scope` that keeps the focus on its anchor (`Initial::KeepAnchor`, + /// a dropdown's layer); `None` outside every such scope. + fn anchored_layer(&self, scope: Option) -> Option { + let mut at = scope; + while let Some(id) = at { + let rec = self.last_scopes.get(&id)?; + if rec.policy.initial == Initial::KeepAnchor { + return rec.opener; + } + at = rec.parent; + } + None + } + /// The arrival member of a roving group of last pass: its selected member, else the first. fn arrival(&self, group: &super::Group) -> Option { self.last().arrival(group) @@ -248,12 +262,15 @@ impl State { } pub(super) fn tab(&mut self, forward: bool, all_controls: bool) -> Vec { - // A child of a collection row tabs on from its collection: the row groups are no Tab entries. + // A child of a collection row tabs on from its collection: the row groups are no Tab entries. The content of a + // layer that keeps the focus on its anchor (a dropdown) is no Tab entry either: Tab goes on from the anchor. 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)); - owner.unwrap_or(rec) + let rec = owner.unwrap_or(rec); + self.anchored_layer(rec.scope).and_then(|opener| self.find_stop(opener)).unwrap_or(rec) }); - let entries = self.entries(self.trap_of(current.as_ref()), all_controls); + let mut entries = self.entries(self.trap_of(current.as_ref()), all_controls); + entries.retain(|entry| self.anchored_layer(entry.arrival().scope).is_none()); let Some(next) = cycle(&entries, current.as_ref(), forward) else { return Vec::new() }; let arrival = entries[next].arrival().clone(); self.focus_stop(arrival) @@ -520,6 +537,7 @@ pub(super) fn begin(state: &mut State, input: BeginIn) -> (Vec, Vec } for forward in input.nav.tabs { let moved = state.tab(forward, input.tab_all_controls); + state.press.by_keys |= !moved.is_empty(); if let Some(from) = input.focused.filter(|_| !moved.is_empty()) { state.press.tabbed_from = Some((from, forward)); } @@ -527,6 +545,7 @@ pub(super) fn begin(state: &mut State, input: BeginIn) -> (Vec, Vec } for forward in input.nav.panes { let (moved, said) = state.pane(forward, input.tab_all_controls); + state.press.by_keys |= !moved.is_empty(); acts.extend(moved); announcements.extend(said); } diff --git a/crates/ui-contract/src/runtime/focus/press.rs b/crates/ui-contract/src/runtime/focus/press.rs index e5ce6b166..12ef5baf2 100644 --- a/crates/ui-contract/src/runtime/focus/press.rs +++ b/crates/ui-contract/src/runtime/focus/press.rs @@ -45,6 +45,8 @@ pub(crate) struct PressState { pub(super) commit_now: Option, /// The widget a Tab or Shift+Tab moved focus off this pass, and whether the move was forward. pub(super) tabbed_from: Option<(Id, bool)>, + /// Tab, Shift+Tab or F6 moved focus this pass. + pub(super) by_keys: bool, focus_at_begin: Option, } @@ -53,6 +55,7 @@ impl PressState { self.plan = None; self.commit_now = None; self.tabbed_from = None; + self.by_keys = false; self.focus_at_begin = focused; } } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 87bec44e3..28d89ae34 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -95,8 +95,8 @@ pub enum CloseReason { Escape, /// A press landed outside the layer and its anchor. Outside, - /// Focus left the layer. - FocusLeft, + /// Focus left the layer, or the anchor of a layer that keeps the focus on its anchor; the move says what moved it. + FocusLeft(crate::runtime::focus::FocusMove), /// A component inside was activated. Activated, /// Enter was pressed inside. diff --git a/crates/ui-widgets/src/pickers/select.rs b/crates/ui-widgets/src/pickers/select.rs index d805a77b0..990b1d863 100644 --- a/crates/ui-widgets/src/pickers/select.rs +++ b/crates/ui-widgets/src/pickers/select.rs @@ -18,7 +18,8 @@ use crate::contract::{ use crate::list::{List, ListRow}; use crate::menu::Menu; use crate::runtime::env::Label; -use crate::runtime::focus::{self, FocusTarget}; +use crate::runtime::focus::{self, FocusMove, FocusTarget}; +use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, Ink, StyleCx, SurfaceLook, TextLook, TypeRole}; use crate::text::TextField; use craft_behavior::nav::{StepResult, ValueAxes, ValueSteps}; @@ -296,6 +297,16 @@ impl Component for Select<'_, T> { cx.commit(); popup.close(cx); } + // Tab and Shift+Tab choose the row the keys reached and move on; Escape and any other focus move put the value + // back. A press outside cancels in `update` once the list has closed. + if matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) { + match ui.closing(popup) { + Some(CloseReason::FocusLeft(FocusMove::Keys)) => cx.commit(), + Some(CloseReason::FocusLeft(_)) => cx.cancel(CancelReason::Blur), + Some(CloseReason::Escape) => cx.cancel(CancelReason::Escape), + _ => {} + } + } } fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { diff --git a/crates/ui-widgets/src/pickers/tree_picker.rs b/crates/ui-widgets/src/pickers/tree_picker.rs index ca1118c93..feff2d47a 100644 --- a/crates/ui-widgets/src/pickers/tree_picker.rs +++ b/crates/ui-widgets/src/pickers/tree_picker.rs @@ -289,7 +289,7 @@ impl Component for TreePicker<'_, K> { let reasons: Vec> = entries.iter().map(|entry| entry.blocked.as_ref().map(|reason| cx.env.resolve(reason))).collect(); let name = cx.label(); // Folders open and close inside the popup, so activating one must not close it: a pick closes it below. - let overlay = Overlay::dropdown().dismiss(Dismiss::new()); + let overlay = Overlay::dropdown().dismiss(Dismiss::new().focus_left(true)); let events = ui.show(popup, overlay, |ui, _| { let fresh = Popup::opening(popup, cx); if fresh { diff --git a/crates/ui-widgets/tests/it/pickers/select_list.rs b/crates/ui-widgets/tests/it/pickers/select_list.rs index 6678d07c3..4e323dfab 100644 --- a/crates/ui-widgets/tests/it/pickers/select_list.rs +++ b/crates/ui-widgets/tests/it/pickers/select_list.rs @@ -1,6 +1,7 @@ -//! The open list of a Select is one gesture: the rows the keys reach are the value until Escape puts it back, and -//! typing on the closed field opens the list on the first match. +//! The open list of a Select is one gesture: the rows the keys reach are the value until Escape puts it back or Tab +//! chooses it, and typing on the closed field opens the list on the first match. +use craft_ui::buttons::Button; use craft_ui::contract::{Bind, Entry, Role, Show as _}; use craft_ui::pickers::Select; use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial}; @@ -12,6 +13,13 @@ fn select(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { Select::new("Pick", Bind::bound(data.value("value", 1u8)), &entries).show(ui).into() } +/// The select with a button after it, which Tab reaches next. +fn select_then_button(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let out = select(ui, data); + Button::new("Next").show(ui); + out +} + /// A fixture with the select focused and holding One. fn focused() -> Fixture { let mut fixture = Fixture::story(&Story::new("select_list", select)); @@ -52,3 +60,21 @@ fn typing_on_the_closed_select_opens_the_list_on_the_first_match() { assert!(list_open(&mut fixture), "a typed letter opens the list"); assert_eq!(value(&mut fixture), 2, "on the first entry it begins, after the held one"); } + +#[trial] +fn tab_in_the_open_list_chooses_the_row_the_keys_reached_and_moves_on() { + let mut fixture = Fixture::story(&Story::new("select_then_button", select_then_button)); + fixture.settle(); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + let on_select = fixture.focused_stop(); + fixture.key(Key::ArrowDown, Modifiers::ALT); + fixture.settle(); + fixture.key(Key::ArrowDown, Modifiers::NONE); + fixture.settle(); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + assert!(!list_open(&mut fixture), "Tab closes the list"); + assert_eq!(value(&mut fixture), 2, "and keeps the row the keys reached"); + assert_ne!(fixture.focused_stop(), on_select, "and the focus moved on"); +}