From e58aabe37e19dd37fefb784635d33d16920273ca Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 11 Nov 2026 22:16:54 +0000 Subject: [PATCH] Focus returns to where it came from: the drawer to Edit Toolbar, the last toast to the stop before the stack (K17) A layer opened from a recorded opener returns focus to that opener's stop. ToolRailOutput::edit_toolbar carries the button's response and ToolbarDrawer::opened_by takes it; the drawer still hangs from the rail. The toast layer is a non-trapping scope (FocusPolicy::TAB_LAYER) whose opener is the stop focus entered it from, so the last card's end returns focus there; an earlier card's end hands it to the next card. --- .../ui-contract/src/contract/overlay/host.rs | 6 ++- .../ui-contract/src/contract/overlay/props.rs | 5 ++- crates/ui-contract/src/runtime/focus.rs | 3 +- crates/ui-contract/src/runtime/focus/nav.rs | 21 +++++++++ .../ui-contract/src/runtime/focus/policy.rs | 6 ++- crates/ui-panels/src/rails/drawer.rs | 23 ++++++++-- crates/ui-panels/src/rails/tool.rs | 13 +++--- crates/ui-panels/src/rails/tool/stories.rs | 2 +- crates/ui-panels/tests/it/rails/drawer.rs | 34 ++++++++++++++ crates/ui-shell/tests/it/notices.rs | 44 +++++++++++++++++++ 10 files changed, 141 insertions(+), 16 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index a19315d4b..c1cbffc84 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -164,11 +164,13 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U // The opener of the layer's scope is the stop focused when the layer first appears: egui's modal gate takes focus // from the widgets below a modal layer by the first pass that shows the layer. A dropdown that keeps its anchor's key // focus belongs to the component that opened it: a press moves the key focus onto that component only at the end of - // the frame that opens the layer, so the stop focused then is the previous one. + // the frame that opens the layer, so the stop focused then is the previous one. A layer the app opens from a recorded + // opener (a button whose click the app answers) returns focus to that opener's stop. let opener = *memory.opener_stop.get_or_insert_with(|| { let owned = (overlay.focus.initial == focus::Initial::KeepAnchor).then(|| focus::stop_rec(ctx, (layer.owner, None))).flatten(); let pressed = overlay.opener.as_ref().filter(|first| first.fired && first.pressed).and_then(|_| focus::pressed_stop(ctx)); - owned.map(|rec| rec.stop.key()).or(pressed).or_else(|| focus::focused_stop(ctx)) + let recorded = overlay.opener.as_ref().and_then(|first| focus::stop_rec(ctx, (first.id, None))).map(|rec| rec.stop.key()); + owned.map(|rec| rec.stop.key()).or(pressed).or(recorded).or_else(|| focus::focused_stop(ctx)) }); overlay::begin_layer(ctx, layer.id, layer.exiting); let shown = areas::show_layer(ctx, &spec, |ui| { diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index c35485dd5..d66f9a7d4 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -250,10 +250,11 @@ impl Overlay { overlay } - /// A toast stack: the viewport's bottom end corner. + /// A toast stack: the viewport's bottom end corner. Tab reaches its cards, and focus returns from them to where it came + /// from when the last one ends. pub fn toast() -> Overlay { let place = Place::anchored(Anchor::Viewport(Align2::RIGHT_BOTTOM), Side::Above, Align::End); - let mut overlay = Overlay::base(Rank::Toast, place, OverlayFit::ContentCapped(NOTE_SHARE), OwnerClass::Widget, FocusPolicy::NONE); + let mut overlay = Overlay::base(Rank::Toast, place, OverlayFit::ContentCapped(NOTE_SHARE), OwnerClass::Widget, FocusPolicy::TAB_LAYER); overlay.dismiss = Dismiss::new().outside(Outside::Keep); overlay } diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 817427dc5..4394ab7b8 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -52,7 +52,8 @@ pub(crate) struct ScopeRec { pub(crate) policy: FocusPolicy, pub(crate) parent: Option, pub(crate) label: Option>, - /// The stop that held focus when the scope was first pushed, which `restore` returns to. + /// The stop that held focus when the scope was first pushed, or for a scope that does not trap the stop focus last + /// entered it from, which `restore` returns to. pub(crate) opener: Option, /// The scope's layer is playing its exit: focus inside it already returns to the opener. pub(crate) closing: bool, diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index 8b6fda125..2eed10b00 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -147,6 +147,7 @@ impl State { /// Moves focus to `rec`: the egui widget is its root, and the stop is recorded under that root. pub(super) fn focus_stop(&mut self, rec: StopRec) -> Vec { + self.note_entry(&rec); let stop = &rec.stop; let roving = stop.group.is_some(); let keys = stop.keys; @@ -167,6 +168,26 @@ impl State { vec![Act::Focus(stop.root, filter)] } + /// Focus moving to `rec` from outside a scope that traps nothing and restores focus (a layer that Tab reaches, such as + /// the toasts) makes the stop it comes from that scope's opener: when the scope goes away with focus inside, focus + /// returns there. + fn note_entry(&mut self, rec: &StopRec) { + let Some(from) = self.stop_of_focus() else { return }; + let mut at = rec.scope; + while let Some(id) = at { + let Some(scope) = self.scopes.get(&id).or_else(|| self.last_scopes.get(&id)) else { return }; + let (policy, parent) = (scope.policy, scope.parent); + if policy.restore && !policy.trap && !self.in_scope(from.scope, Some(id)) { + for scopes in [&mut self.scopes, &mut self.last_scopes] { + if let Some(scope) = scopes.get_mut(&id) { + scope.opener = Some(from.stop.key()); + } + } + } + at = parent; + } + } + fn in_scope(&self, scope: Option, root: Option) -> bool { let Some(root) = root else { return true }; let mut at = scope; diff --git a/crates/ui-contract/src/runtime/focus/policy.rs b/crates/ui-contract/src/runtime/focus/policy.rs index ddb0d0dc9..075ce4a79 100644 --- a/crates/ui-contract/src/runtime/focus/policy.rs +++ b/crates/ui-contract/src/runtime/focus/policy.rs @@ -39,7 +39,8 @@ pub struct FocusPolicy { pub kind: ScopeKind, /// Tab wraps inside the scope and cannot leave it. pub trap: bool, - /// Focus returns to the opener when the scope disappears. + /// Focus returns to the opener when the scope disappears. In a scope that does not trap, the opener is the stop + /// focus entered the scope from. pub restore: bool, /// Where focus goes when the scope first appears. pub initial: Initial, @@ -86,6 +87,9 @@ impl FocusPolicy { }; /// A menu: like a popup. pub const MENU: FocusPolicy = FocusPolicy { kind: ScopeKind::Menu, ..FocusPolicy::POPUP }; + /// A layer that only Tab reaches, such as the toasts: it traps nothing and takes no focus on its own, and when it + /// goes away with focus inside, focus returns to the stop it came from. + pub const TAB_LAYER: FocusPolicy = FocusPolicy { restore: true, ..FocusPolicy::NONE }; /// Whether Tab wraps inside the scope. pub const fn trap(mut self, on: bool) -> Self { diff --git a/crates/ui-panels/src/rails/drawer.rs b/crates/ui-panels/src/rails/drawer.rs index aa7756b63..2da9ecbd5 100644 --- a/crates/ui-panels/src/rails/drawer.rs +++ b/crates/ui-panels/src/rails/drawer.rs @@ -124,6 +124,7 @@ impl Outcome for ToolbarDrawerOutput { /// edit. /// - **Closing.** Escape, the close button or a press outside the drawer and the rail closes it: `closed` is set and /// the host stops showing it. A press on the rail is the start of a drag or a pick there, so it leaves the drawer open. +/// The focus then returns to the drawer's [opener](ToolbarDrawer::opened_by), the rail's Edit Toolbar button. #[must_use = "show the drawer with `show`"] #[derive(crate::contract::Pattern, crate::contract::Props)] #[pattern(probe(ToolbarDrawer<'static, u8>))] @@ -135,13 +136,22 @@ pub struct ToolbarDrawer<'a, T: Value + 'static> { #[prop] opens: Side, dropped: Option, + opener: Option, } impl<'a, T: Value + 'static> ToolbarDrawer<'a, T> { /// A drawer beside `rail` (the rail's rect), listing `groups`, over a toolbar of `toolbar` slots. `dropped` is the /// drag the rail took in this pass (`ToolRailOutput::dropped`); the drawer turns it into an edit. pub fn new(rail: Rect, groups: &'a [DrawerGroup], toolbar: &'a [ToolSlot], dropped: Option) -> Self { - ToolbarDrawer { rail, groups, toolbar, opens: Side::End, dropped } + ToolbarDrawer { rail, groups, toolbar, opens: Side::End, dropped, opener: None } + } + + /// The control that opened the drawer, the rail's Edit Toolbar button (`ToolRailOutput::edit_toolbar`): the focus + /// returns to it when the drawer closes. The drawer still hangs from the rail. + #[must_use] + pub fn opened_by(mut self, opener: &Response) -> Self { + self.opener = Some(opener.clone()); + self } } @@ -207,7 +217,7 @@ fn on_toolbar(toolbar: &[ToolSlot], id: &T) -> bool { impl ToolbarDrawer<'_, T> { /// Shows the drawer and reports what the user changed. pub fn show(self, ui: &mut Ui) -> ToolbarDrawerOutput { - let ToolbarDrawer { rail, groups, toolbar, opens, dropped } = self; + let ToolbarDrawer { rail, groups, toolbar, opens, dropped, opener } = self; let env = Env::of(ui); let words = env.words::(); let os = os_of(ui.ctx()); @@ -222,9 +232,16 @@ impl ToolbarDrawer<'_, T> { let layout = env.view().keyboard_layout(); let chord_of = |command: &ResolvedCommand| command.chord.as_ref().map(|chord| chord.display_for(os, layout)); - let popover = Popover::new(words.drawer_title.clone(), Bind::bound(&mut open)) + let mut popover = Popover::new(words.drawer_title.clone(), Bind::bound(&mut open)); + if let Some(opener) = &opener { + popover = popover.opened_by(opener); + } + let popover = popover .overlay(|overlay| { let mut overlay = overlay.place(Place::anchored(Anchor::Rect(rail), opens, Align::Start)); + if overlay.opener.is_some() { + overlay = overlay.opener_anchor(Anchor::Rect(rail)); + } overlay.fit = Overlay::dialog().fit; overlay }) diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 1480ad48d..6a5ef8d68 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -65,8 +65,9 @@ pub struct ToolRailOutput { pub double_clicked: Option, /// The column toggle was clicked; the host flips its column count. pub toggle_columns: bool, - /// The Edit Toolbar button was clicked. - pub edit_toolbar: bool, + /// The Edit Toolbar button's response while the rail shows it: a click on it opens the drawer, and the drawer + /// takes it as its opener ([`ToolbarDrawer::opened_by`](crate::rails::ToolbarDrawer::opened_by)). + pub edit_toolbar: Option, /// The slot whose flyout is open. pub flyout: Option, /// A tool dropped on a slot while the toolbar is edited, and where it goes. @@ -87,14 +88,14 @@ impl Outcome for ToolRailOutput { struct Collected { select: Option, double_clicked: Option, - edit_toolbar: bool, + edit_toolbar: Option, flyout: Option, dropped: Option, } impl Default for Collected { fn default() -> Self { - Collected { select: None, double_clicked: None, edit_toolbar: false, flyout: None, dropped: None } + Collected { select: None, double_clicked: None, edit_toolbar: None, flyout: None, dropped: None } } } @@ -232,7 +233,7 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> { None => { let label = edit_label.clone().unwrap_or(Label::Empty); let more = IconButton::new(IconId::new("more")).id_salt("edit-toolbar").label(label).show(ui); - collected.edit_toolbar |= clicked(&more); + collected.edit_toolbar = Some(more.response); } } } @@ -280,7 +281,7 @@ impl Component for ToolRail<'_, T> { select: None, double_clicked: None, toggle_columns: self.toggled, - edit_toolbar: false, + edit_toolbar: None, flyout: None, dropped: None, last_used: None, diff --git a/crates/ui-panels/src/rails/tool/stories.rs b/crates/ui-panels/src/rails/tool/stories.rs index 2f02c7cdc..3ca755d99 100644 --- a/crates/ui-panels/src/rails/tool/stories.rs +++ b/crates/ui-panels/src/rails/tool/stories.rs @@ -60,7 +60,7 @@ fn tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { *note = format!("double clicked {tool}"); } else if out.toggle_columns { *note = "toggle columns".to_owned(); - } else if out.edit_toolbar { + } else if out.edit_toolbar.as_ref().is_some_and(crate::contract::clicked) { *note = "edit toolbar".to_owned(); } let flyout = out.flyout.map_or_else(|| "closed".to_owned(), |slot| format!("of slot {slot} open")); diff --git a/crates/ui-panels/tests/it/rails/drawer.rs b/crates/ui-panels/tests/it/rails/drawer.rs index d6fb09f34..ee2531a64 100644 --- a/crates/ui-panels/tests/it/rails/drawer.rs +++ b/crates/ui-panels/tests/it/rails/drawer.rs @@ -33,3 +33,37 @@ fn a_tool_moved_down_its_own_slot_lands_at_the_index_after_it_leaves() { let edit = ToolbarEdit::move_to(UNDO, DropAt::into_slot(0, 3)); assert_eq!(layout(&apply_toolbar_edit(&slots, &edit, &[])), [(0, vec![REDO, CUT, UNDO])], "the removal shifts the index"); } + +// The drawer opened from the rail's Edit Toolbar button gives the focus back to that button when it closes. +#[trial] +fn closing_the_drawer_returns_the_focus_to_the_rails_edit_toolbar_button() { + use craft_ui::rails::{DrawerGroup, LastUsed, ToolRail, ToolbarDrawer}; + use craft_ui::testing::Fixture; + use egui::{Key, Modifiers}; + use std::cell::Cell; + use std::rc::Rc; + + let open = Rc::new(Cell::new(false)); + let shown = open.clone(); + let mut fixture = Fixture::new(move |ui| { + let slots = [slot(0, &[UNDO]), slot(1, &[REDO])]; + let groups = [DrawerGroup::new("Edit", vec![tool(UNDO), tool(REDO), tool(CUT)])]; + let last = LastUsed::default(); + let rail = ToolRail::new("Tools", &slots, &UNDO, &last).edit_toolbar("Customize").show_rail(ui, |_, _| {}); + let opener = rail.edit_toolbar.expect("the rail shows its Edit Toolbar button"); + if craft_ui::contract::clicked(&opener) { + shown.set(true); + } + if shown.get() && ToolbarDrawer::new(rail.response.rect, &groups, &slots, None).opened_by(&opener).show(ui).closed { + shown.set(false); + } + }); + fixture.idle(30); + let customize = fixture.by_label("Customize").expect("the rail shows its Edit Toolbar button"); + fixture.click(&customize).idle(6); + assert!(open.get(), "the button opened the drawer"); + fixture.key(Key::Escape, Modifiers::NONE).idle(6); + assert!(!open.get(), "Escape closed the drawer"); + let focused = craft_ui::testing::access::focused_key(fixture.tree()); + assert!(fixture.by_label("Customize").is_some_and(|button| button.node == focused), "the focus is back on Edit Toolbar"); +} diff --git a/crates/ui-shell/tests/it/notices.rs b/crates/ui-shell/tests/it/notices.rs index 14e98751e..3b3cc5820 100644 --- a/crates/ui-shell/tests/it/notices.rs +++ b/crates/ui-shell/tests/it/notices.rs @@ -43,3 +43,47 @@ fn a_toast_stack_in_a_shell_body_opens_its_layer_once_per_pass() { fixture.settle(); assert!(!fixture.texts().is_empty(), "the toast card shows"); } + +/// Dismissing the focused toast hands the focus to the next card, and the last one back to where it came from. +#[trial] +fn a_dismissed_toast_hands_the_focus_on_and_the_last_returns_it() { + use craft_ui::buttons::Button; + use craft_ui::contract::Show as _; + use egui::{Key, Modifiers}; + + let mut posted = false; + let mut fixture = Fixture::new(move |ui| { + let ctx = ui.ctx().clone(); + if !posted { + toast::post(&ctx, Toast::new("poster.png was saved.")); + toast::post(&ctx, Toast::new("flyer.png was saved.")); + posted = true; + } + AppShell::embedded(WindowKey::new("toast-focus-shell")) + .body(|ui, _, _| { + Button::new("Before").show(ui); + ToastStack::show(ui); + }) + .show(ui, &mut ()); + }); + fixture.settle(); + let focused_name = |fixture: &Fixture| { + let tree = fixture.tree(); + tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned) + }; + for _ in 0..6 { + if focused_name(&fixture).as_deref() == Some("Before") { + break; + } + fixture.key(Key::Tab, Modifiers::NONE).idle(2); + } + assert_eq!(focused_name(&fixture).as_deref(), Some("Before"), "Tab reaches the body's button"); + fixture.key(Key::Tab, Modifiers::NONE).idle(2); + assert_eq!(focused_name(&fixture).as_deref(), Some("Dismiss"), "Tab reaches the first card's Dismiss"); + fixture.key(Key::Enter, Modifiers::NONE).idle(4); + assert_eq!(toast::cards(fixture.ctx()).len(), 1, "one card ended"); + assert_eq!(focused_name(&fixture).as_deref(), Some("Dismiss"), "the focus moved to the other card's Dismiss"); + fixture.key(Key::Enter, Modifiers::NONE).idle(4); + assert!(toast::cards(fixture.ctx()).is_empty(), "both cards ended"); + assert_eq!(focused_name(&fixture).as_deref(), Some("Before"), "the focus is back where it came from"); +}