From aa4a53c392a85e635c2bc73630b2c31d209c4eb6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 12 Nov 2026 03:58:10 +0000 Subject: [PATCH] Menu bar keys: opening Help focuses its search field, which drives the menu (Up, Down, Home, End move the active row, Enter runs it or the first enabled match); a shortcut pressed while the bar holds the focus matches in the scopes of the stop the bar took it from and gives the focus back --- .../ui-contract/src/runtime/commands/board.rs | 24 +++++++++++-- crates/ui-contract/src/runtime/focus.rs | 6 ++++ crates/ui-widgets/src/menu/bar.rs | 35 ++++++++++++++----- crates/ui-widgets/src/menu/level.rs | 32 +++++++++++++++++ crates/ui-widgets/src/menu/popup.rs | 18 +++++++++- crates/ui-widgets/tests/it/menu/pick_focus.rs | 24 +++++++++++++ 6 files changed, 127 insertions(+), 12 deletions(-) diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 952f8bd01..7fd54ca97 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -66,6 +66,9 @@ pub(crate) struct Board { instances: Vec, /// The focused component of each viewport's last step 12 and the instances around it. chains: HashMap, + /// The focused component and its chain before the one in `chains`, per viewport: the stop a menu bar took the + /// focus from, whose scopes a shortcut pressed on the bar matches in. + before: HashMap, /// The instances around the component that holds key focus, per viewport, as the viewport's begin hook read them. focused: Vec<(ViewportId, Vec)>, /// The chain of the last pass in which any component held key focus. @@ -413,7 +416,11 @@ pub(crate) fn register_instance(ctx: &Context, scope: CommandScope, id: Id) { pub(crate) fn note_focus(ctx: &Context, id: Id, chain: &CommandChain) { let viewport = pass::current_viewport(ctx); with(ctx, |board| { - board.chains.insert(viewport, (id, chain.clone())); + if let Some(old) = board.chains.insert(viewport, (id, chain.clone())) + && old.0 != id + { + board.before.insert(viewport, old); + } }); } @@ -623,10 +630,17 @@ pub(crate) fn begin(ctx: &Context) { let shortcuts = keys::take_shortcuts(ctx); let now = pass::now(ctx); let held_open = sampler::held_canvas(ctx); + // A shortcut pressed while a menu bar holds the focus (F10, then Ctrl+S) leaves the bar: it matches in the scopes + // of the stop the bar took the focus from, and a hit gives the focus back to that stop. + let returning = focused.filter(|_| !shortcuts.keys.is_empty()).and_then(|focused| focus::bar_return_of(ctx, focused)); let taken = with(ctx, |board| { board.held_open = held_open; - let chain: Vec = - board.chains.get(&viewport).filter(|(id, _)| Some(*id) == focused).map(|(_, chain)| chain.ids().collect()).unwrap_or_default(); + let returned = returning + .and_then(|held| [board.before.get(&viewport), board.chains.get(&viewport)].into_iter().flatten().find(|(id, _)| *id == held)) + .map(|(_, chain)| chain.ids().collect()); + let chain: Vec = returned.unwrap_or_else(|| { + board.chains.get(&viewport).filter(|(id, _)| Some(*id) == focused).map(|(_, chain)| chain.ids().collect()).unwrap_or_default() + }); // Nothing focused inside a modal: the modal's root takes the commands, as a plain Enter goes to its default button. let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.iter().find(|(of, _)| *of == viewport)) { (true, Some((_, root))) => vec![*root], @@ -707,6 +721,9 @@ pub(crate) fn begin(ctx: &Context) { } } with(ctx, |board| board.matcher = matcher); + if returning.is_some() && fired.iter().any(|fired| fired.phase == FirePhase::Press) { + focus::give_back_bar(ctx); + } for fired in fired { queue(ctx, fired); } @@ -723,6 +740,7 @@ pub(crate) fn end(ctx: &Context) { board.queue.retain(|fired| fired.target.is_some_and(|id| ids.contains(&id))); board.held.retain(|held| held.target.is_none_or(|id| ids.contains(&id))); board.chains.retain(|viewport, _| live.contains(viewport)); + board.before.retain(|viewport, _| live.contains(viewport)); board.focused.retain(|(viewport, _)| live.contains(viewport)); }); } diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 7adda8f79..94ee1bd47 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -388,6 +388,12 @@ pub fn give_back_bar(ctx: &Context) -> bool { true } +/// The stop a menu bar took the focus from, while the bar's stop `focused` holds it: where a shortcut pressed on the +/// bar matches and goes. +pub(crate) fn bar_return_of(ctx: &Context, focused: Id) -> Option { + with(ctx, |state| state.bar_return.as_ref().filter(|(bar, _)| *bar == focused).map(|(_, (id, _))| *id)) +} + /// Forgets the stop a menu bar took focus from: focus left the bar by other means, so a later Escape has nowhere /// to return to. #[doc(hidden)] diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index d14fcb8e9..9ae4777d4 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -203,9 +203,9 @@ struct BarState { hover: Option, } -/// The help field's text. +/// The help field's text, the passes the Help menu has been open, and whether the field has taken the key focus. #[derive(Clone, Debug, Default)] -struct Query(String); +struct Query(String, u32, bool); /// What the bar published for `is_open` and `is_focused`. #[derive(Clone, Copy, Debug)] @@ -519,15 +519,34 @@ impl Component for MenuBar<'_> { let titles = &mut self.titles; let step = ui.show(popup, layer, |ui, _| { Menu::inline(Label::from(name.clone())) - .show(ui, |ui, _| match slot { + .show(ui, |ui, menu| match slot { Open::Title(at) => { if let (Some(help), Some(rows)) = (help.filter(|help| help.menu == *at), help_rows.as_ref()) { // The field sits in a padded frame: its edge lines up with the row labels and it keeps clear of the first row. - Stack::new().pad(Pad::Regular).fill_width().show(ui, |ui, _| { - TextField::search(words.bar_search.as_str().to_owned(), Bind::bound(&mut query.0)) - .placeholder(words.bar_search.as_str().to_owned()) - .show(ui); - }); + // The field drives the menu: Up, Down, Home and End move its active row and Enter runs + // it, or the first enabled match, while typing stays in the field. + let drives = menu.resolved.id; + let field = Stack::new() + .pad(Pad::Regular) + .fill_width() + .show(ui, |ui, _| { + TextField::search(words.bar_search.as_str().to_owned(), Bind::bound(&mut query.0)) + .placeholder(words.bar_search.as_str().to_owned()) + .drives(drives) + .show(ui) + .response + }) + .inner; + // Opening Help puts the key focus in its field, from the pass after the menu opened, once + // the layer has recorded where focus returns to. + if let Some(field) = field { + if field.has_focus() { + query.2 = true; + } else if !query.2 && query.1 > 0 { + focus::request(ui.ctx(), FocusTarget::Id(field.id)); + } + } + query.1 = query.1.saturating_add(1); let refs: Vec<[&str; 3]> = rows.iter().map(|[label, english, path]| [label.as_str(), english.as_str(), path.as_str()]).collect(); let mut seen: Vec<&CommandRef> = Vec::new(); diff --git a/crates/ui-widgets/src/menu/level.rs b/crates/ui-widgets/src/menu/level.rs index 9a161145e..28ff4e341 100644 --- a/crates/ui-widgets/src/menu/level.rs +++ b/crates/ui-widgets/src/menu/level.rs @@ -3,6 +3,7 @@ use super::popup::MenuStep; use crate::contract::{Component, Cx, Remember as _}; use crate::runtime::env::{AppValues, EnvValue}; +use craft_behavior::NavMove; use craft_keymap::mnemonic; use egui::{Id, Pos2, Rect, pos2}; use std::sync::{Arc, Mutex, PoisonError}; @@ -285,6 +286,37 @@ impl MenuLevel { self.with(|state| state.active) } + /// Moves the active row by `mv` among the enabled rows as the user last saw them, without moving the focus (the + /// keys of a field that drives the menu): Up and Down wrap, Home and Page Up go to the first, End and Page Down to + /// the last. Returns whether it moved. + pub(super) fn step_active(&self, mv: NavMove) -> bool { + self.with(|state| { + let rows: Vec = state.shown.iter().filter(|row| row.enabled).map(|row| row.id).collect(); + let n = rows.len(); + if n == 0 { + return false; + } + let at = state.active.and_then(|active| rows.iter().position(|id| *id == active)); + let to = match mv { + NavMove::Down | NavMove::Forward => at.map_or(0, |at| (at + 1) % n), + NavMove::Up | NavMove::Back => at.map_or(n - 1, |at| (at + n - 1) % n), + NavMove::Start | NavMove::PageUp => 0, + NavMove::End | NavMove::PageDown => n - 1, + _ => return false, + }; + state.active = Some(rows[to]); + true + }) + } + + /// The row an activation of the menu runs: the active row while it is enabled, else the first enabled row. + pub(super) fn active_or_first(&self) -> Option { + self.with(|state| { + let enabled = |id: Id| state.shown.iter().any(|row| row.id == id && row.enabled); + state.active.filter(|active| enabled(*active)).or_else(|| state.shown.iter().find(|row| row.enabled).map(|row| row.id)) + }) + } + pub(crate) fn has_active(&self) -> bool { self.with(|state| state.active.is_some()) } diff --git a/crates/ui-widgets/src/menu/popup.rs b/crates/ui-widgets/src/menu/popup.rs index 04d5e9d03..27fff5990 100644 --- a/crates/ui-widgets/src/menu/popup.rs +++ b/crates/ui-widgets/src/menu/popup.rs @@ -13,7 +13,7 @@ use crate::runtime::focus::{FocusPolicy, Initial}; use crate::runtime::frame; use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; -use craft_behavior::{Arrows, Metrics, NavShape, Roving, Sense, Value}; +use craft_behavior::{Arrows, Intent, Metrics, NavShape, Roving, Sense, Value}; use egui::{Response, Ui}; /// The style of a menu: the surface comes from the container. @@ -280,6 +280,8 @@ impl Component for Menu<'_> { const ROLE: Role = Role::MENU; const PARTS: bool = false; const STOPS: bool = false; + /// The moves a field that drives the menu routes to it. + const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(Self::INPUT).with_moves(); type Style = MenuStyle; type Output = MenuOutput; @@ -296,9 +298,23 @@ impl Component for Menu<'_> { /// the first key enters it at an end. The active row is the lead, so the first key after the pointer lit a row /// moves from that row; a row lit in this pass leads from the next, so only a key in the same frame as the pointer /// move that lit it starts from the row lit before. + /// + /// A field that drives the menu (Help's search) hands it Up, Down, Page keys, Home and End, which move the active + /// row, and Enter, which runs the active row, or else the first enabled one; the focus stays in the field. fn update(&mut self, cx: &mut Cx<'_, Self>) { let level = MenuLevel::of(cx.memory::()); level.resume(cx.core.ctx.cumulative_pass_nr()); + while let Some((mv, _)) = cx.intents().take_move() { + if level.step_active(mv) { + frame::request_repaint(&cx.core.ctx); + } + } + if cx.intents().take(Intent::Activate) + && let Some(row) = level.active_or_first() + { + level.run(row); + frame::request_repaint(&cx.core.ctx); + } let keyboard = crate::runtime::focus::keyboard_in_menu(&cx.core.ctx); self.props.roving = self.props.roving.map(|roving| roving.no_lead(!keyboard && !level.has_active())); if let Some(row) = level.active() { diff --git a/crates/ui-widgets/tests/it/menu/pick_focus.rs b/crates/ui-widgets/tests/it/menu/pick_focus.rs index 2cec0644d..9afe26e45 100644 --- a/crates/ui-widgets/tests/it/menu/pick_focus.rs +++ b/crates/ui-widgets/tests/it/menu/pick_focus.rs @@ -74,3 +74,27 @@ fn undo_picked_from_the_edit_menu_undoes_in_the_field_that_held_focus() { rig.click("Undo"); rig.assert_undone_in_the_field("Edit › Undo"); } + +#[trial] +fn opening_help_focuses_its_search_and_down_then_enter_runs_the_first_match() { + let mut rig = rig(); + rig.click("Help"); + rig.fixture.type_text("und"); + rig.fixture.settle(); + assert_eq!(*rig.text.borrow(), "helloabc", "the typed text lands in the search field, not the text field"); + rig.fixture.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + rig.fixture.key(egui::Key::Enter, egui::Modifiers::NONE); + rig.fixture.settle(); + rig.assert_undone_in_the_field("Help › und, Down, Enter"); +} + +#[trial] +fn a_shortcut_pressed_on_the_focused_bar_runs_once_where_focus_was_and_gives_focus_back() { + let mut rig = rig(); + rig.fixture.key(egui::Key::F10, egui::Modifiers::NONE); + rig.fixture.settle(); + assert_ne!(rig.fixture.focused_stop().map(|(id, _)| id), rig.field.get(), "F10 takes the focus to the bar"); + rig.fixture.key(egui::Key::Z, egui::Modifiers::COMMAND); + rig.fixture.settle(); + rig.assert_undone_in_the_field("F10, then the Undo shortcut"); +}