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.
This commit is contained in:
aiongg
2026-11-12 14:32:43 +00:00
parent 9777ba9c83
commit a8cc821ff9
12 changed files with 94 additions and 14 deletions
+1 -1
View File
@@ -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() {
+1 -1
View File
@@ -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);
@@ -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);
@@ -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
@@ -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<CloseReason> {
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<PartRef>) -> Anchor {
+15
View File
@@ -545,6 +545,21 @@ pub(crate) fn commit_now(ctx: &Context) -> Option<Id> {
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<bool> {
with(ctx, |state| state.press.tabbed_from.filter(|(from, _)| *from == widget).map(|(_, forward)| forward))
+22 -3
View File
@@ -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<Id>) -> Option<StopKey> {
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<StopRec> {
self.last().arrival(group)
@@ -248,12 +262,15 @@ impl State {
}
pub(super) fn tab(&mut self, forward: bool, all_controls: bool) -> Vec<Act> {
// 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<Act>, Vec<String>
}
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<Act>, Vec<String>
}
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);
}
@@ -45,6 +45,8 @@ pub(crate) struct PressState {
pub(super) commit_now: Option<Id>,
/// 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<Id>,
}
@@ -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;
}
}
+2 -2
View File
@@ -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.
+12 -1
View File
@@ -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<T: Value + 'static> 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>) {
+1 -1
View File
@@ -289,7 +289,7 @@ impl<K: Value + Eq + Hash + 'static> Component for TreePicker<'_, K> {
let reasons: Vec<Option<Label>> = 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 {
@@ -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");
}