From dba0f0d3fac09125e259029bd4e56023ff7752ed Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 11 Nov 2026 22:16:45 +0000 Subject: [PATCH] Dialog focus: the first field on open, the new tab stop after Set, the password field after reveal (K17) A dialog opens on its first text or number field, else its default button, else nothing (Initial::FirstField, the DIALOG policy's default). The per-dialog first-pass focus requests in Markers, Slice options and Page Setup go: the rule gives the same field. focus::request reports whether it took effect, so a pending request outlives a measuring run. --- crates/draw/src/ui/slice/dialogs.rs | 8 +----- crates/pages/src/ui/setup.rs | 24 ++++++---------- crates/text/src/ui/tabs_dialog.rs | 10 ++++++- crates/text/tests/it/main.rs | 1 + crates/text/tests/it/tabs.rs | 28 +++++++++++++++++++ crates/timeline/src/ui/markers/dialog.rs | 9 ++---- crates/ui-contract/src/runtime/focus.rs | 10 ++++--- crates/ui-contract/src/runtime/focus/nav.rs | 1 + .../ui-contract/src/runtime/focus/policy.rs | 4 ++- crates/ui-panels/src/dialog/trials.rs | 25 +++++++++++++++++ .../src/patterns/form_dialogs/password.rs | 15 +++++++--- .../ui-patterns/tests/it/form_dialogs/mod.rs | 1 + .../tests/it/form_dialogs/password.rs | 22 +++++++++++++++ 13 files changed, 118 insertions(+), 40 deletions(-) create mode 100644 crates/text/tests/it/tabs.rs create mode 100644 crates/ui-patterns/tests/it/form_dialogs/password.rs diff --git a/crates/draw/src/ui/slice/dialogs.rs b/crates/draw/src/ui/slice/dialogs.rs index fb62d5774..32d64862d 100644 --- a/crates/draw/src/ui/slice/dialogs.rs +++ b/crates/draw/src/ui/slice/dialogs.rs @@ -12,7 +12,6 @@ use craft_ui::layout_components::Row; use craft_ui::patterns::form_dialogs::{FormDialog, HostRequests}; use craft_ui::pickers::Select; use craft_ui::runtime::env::{Env, UnitKind}; -use craft_ui::runtime::focus::{self, FocusTarget}; use craft_ui::runtime::requests::{ColorRequest, HostAnswer}; use craft_ui::text::{NumberField, TextField}; use egui::Ui; @@ -136,18 +135,13 @@ impl StackDialog for SliceOptionsDialog { options.background = Some(color); } } - let first = form.first(); FieldGroup::new(words.options_title.clone()).show(ui, |ui, _| { Field::new(words.kind.clone()).show(ui, |ui, _| { if let Some(kind) = Select::new(words.kind.clone(), Bind::given(options.kind), &kinds).show(ui).value().copied() { options.kind = kind; } }); - let name = Field::new(words.name.clone()) - .show(ui, |ui, _| TextField::new(words.name.clone(), Bind::bound(&mut options.name)).show(ui).response.id); - if first && let Some(id) = name.inner { - focus::request(ui.ctx(), FocusTarget::Id(id)); - } + Field::new(words.name.clone()).show(ui, |ui, _| TextField::new(words.name.clone(), Bind::bound(&mut options.name)).show(ui)); for (label, value) in [(&words.url, &mut options.url), (&words.target, &mut options.target), (&words.message, &mut options.message)] { Field::new(label.clone()).show(ui, |ui, _| { TextField::new(label.clone(), Bind::bound(value)).show(ui); diff --git a/crates/pages/src/ui/setup.rs b/crates/pages/src/ui/setup.rs index 69697d098..94402fad7 100644 --- a/crates/pages/src/ui/setup.rs +++ b/crates/pages/src/ui/setup.rs @@ -24,7 +24,6 @@ use craft_ui::notices::{Notice, NoticeLayout}; use craft_ui::patterns::form_dialogs::{FormCx, FormDialog, FormOutput}; use craft_ui::pickers::Select; use craft_ui::runtime::env::{Env, Label, UnitKind, Units}; -use craft_ui::runtime::focus::{self, FocusTarget}; use craft_ui::text::NumberField; use egui::{Response, Ui}; @@ -202,7 +201,6 @@ struct Length { get: fn(&PageSetup) -> f64, set: fn(&mut PageSetup, f64), range: RangeInclusive, - first: bool, } /// Runs the events of a number field of the dialog in order: `write` puts their values into the setup. A `Begin` @@ -235,7 +233,7 @@ impl Rows<'_> { /// that rounds to what the field showed changes nothing, so an untouched length keeps its exact value. `false` /// while the field's text is not a number. fn length(&self, ui: &mut Ui, form: &mut FormCx<'_, '_>, setup: &mut PageSetup, length: Length) -> bool { - let Length { key, label, get, set, range, first } = length; + let Length { key, label, get, set, range } = length; let unit = self.unit; let places = *unit.decimals().end(); let exact = get(setup); @@ -253,9 +251,6 @@ impl Rows<'_> { }) .inner; let Some(field) = field else { return true }; - if first && form.first() { - focus::request(ui.ctx(), FocusTarget::Id(field.response.id)); - } apply(form, setup, &field.edit, |next, value| { let points = if rounded(value, places) == shown { exact } else { to_points(unit, value).clamp(*range.start(), *range.end()) }; set(next, points); @@ -278,16 +273,15 @@ impl Rows<'_> { key: &'static str, label: Label, get: fn(&PageSetup) -> f64, - set: fn(&mut PageSetup, f64), - first: bool| { - valid &= self.length(ui, form, setup, Length { key, label, get, set, range: side.clone(), first }); + set: fn(&mut PageSetup, f64)| { + valid &= self.length(ui, form, setup, Length { key, label, get, set, range: side.clone() }); }; - side_row(ui, form, setup, "top", words.top.clone(), |s| s.margins.top, |s, v| s.margins.top = v, true); - side_row(ui, form, setup, "bottom", words.bottom.clone(), |s| s.margins.bottom, |s, v| s.margins.bottom = v, false); - side_row(ui, form, setup, "left", left.clone(), |s| s.margins.left, |s, v| s.margins.left = v, false); - side_row(ui, form, setup, "right", right.clone(), |s| s.margins.right, |s, v| s.margins.right = v, false); + side_row(ui, form, setup, "top", words.top.clone(), |s| s.margins.top, |s, v| s.margins.top = v); + side_row(ui, form, setup, "bottom", words.bottom.clone(), |s| s.margins.bottom, |s, v| s.margins.bottom = v); + side_row(ui, form, setup, "left", left.clone(), |s| s.margins.left, |s, v| s.margins.left = v); + side_row(ui, form, setup, "right", right.clone(), |s| s.margins.right, |s, v| s.margins.right = v); if !document_setup { - side_row(ui, form, setup, "gutter", words.gutter.clone(), |s| s.gutter, |s, v| s.gutter = v, false); + side_row(ui, form, setup, "gutter", words.gutter.clone(), |s| s.gutter, |s, v| s.gutter = v); } valid }) @@ -391,7 +385,6 @@ impl Rows<'_> { get: |s| s.width, set: |s, v| s.set_size(v, s.height), range: sides.clone(), - first: false, }; let height = Length { key: "height", @@ -399,7 +392,6 @@ impl Rows<'_> { get: |s| s.height, set: |s, v| s.set_size(s.width, v), range: sides, - first: false, }; let wide = self.length(ui, form, setup, width); self.length(ui, form, setup, height) && wide diff --git a/crates/text/src/ui/tabs_dialog.rs b/crates/text/src/ui/tabs_dialog.rs index e038c0153..87bfbad4f 100644 --- a/crates/text/src/ui/tabs_dialog.rs +++ b/crates/text/src/ui/tabs_dialog.rs @@ -22,6 +22,7 @@ use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::ListRow; use craft_ui::pickers::Select; use craft_ui::runtime::env::{Env, Units}; +use craft_ui::runtime::focus::{self, FocusTarget}; use craft_ui::runtime::words::CommonWords; use craft_ui::sections::{DialogRole, FooterButton}; use craft_ui::table::Table; @@ -99,6 +100,8 @@ pub struct TabStopsDialog { unit: DocUnit, /// The row and position an in-place position edit began from, for Escape. draft: Option<(usize, f32)>, + /// The selected stop's Position field takes the focus the next time it shows: Set moves into the new stop. + to_edit: bool, } impl TabStopsDialog { @@ -106,7 +109,7 @@ impl TabStopsDialog { pub fn new(mut stops: Vec, default_interval: f32) -> Self { stops.retain(|stop| stop.position.is_finite()); stops.truncate(MAX_STOPS); - TabStopsDialog { stops, cleared: Vec::new(), default_interval, selected: None, edited: None, unit: DocUnit::default(), draft: None } + TabStopsDialog { stops, cleared: Vec::new(), default_interval, selected: None, edited: None, unit: DocUnit::default(), draft: None, to_edit: false } } /// Sets the unit the position fields show. @@ -138,6 +141,7 @@ impl TabStopsDialog { self.stops.sort_by(|a, b| a.position.total_cmp(&b.position)); self.selected = self.stops.iter().position(|stop| (stop.position - position).abs() < SAME_POSITION); self.edited = None; + self.to_edit = self.selected.is_some(); } /// Position order after in-place edits, merging stops within [`SAME_POSITION`] (the edited @@ -330,11 +334,15 @@ impl TabStopsDialog { let aligns: Vec> = TabAlign::ALL.into_iter().map(|align| Entry::new(align, align_text(words, align))).collect(); let leaders: Vec> = TabLeader::ALL.into_iter().map(|leader| Entry::new(leader, leader_text(words, leader))).collect(); let mut edits = Vec::new(); + let to_edit = &mut self.to_edit; Row::new().show(ui, |ui, _| { let range = -f64::from(MAX_POSITION)..=f64::from(MAX_POSITION); let field = Field::new(words.position.clone()) .show(ui, |ui, _| length_field(unit, words.position.clone(), Mixed::Same(Some(f64::from(stop.position))), range.clone()).show(ui)) .inner; + if let Some(field) = field.as_ref().filter(|_| *to_edit) { + *to_edit = !focus::request(ui.ctx(), FocusTarget::Id(field.response.id)); + } edits.extend(field.into_iter().flat_map(|field| field.edit.events).map(CellEdit::Position)); let align = Select::new(words.alignment.clone(), Bind::given(stop.align), &aligns).show(ui); edits.extend(align.value().copied().map(CellEdit::Align)); diff --git a/crates/text/tests/it/main.rs b/crates/text/tests/it/main.rs index 3221cc34b..0cccfe9ea 100644 --- a/crates/text/tests/it/main.rs +++ b/crates/text/tests/it/main.rs @@ -2,3 +2,4 @@ mod editor; mod notes; +mod tabs; diff --git a/crates/text/tests/it/tabs.rs b/crates/text/tests/it/tabs.rs new file mode 100644 index 000000000..7d677589d --- /dev/null +++ b/crates/text/tests/it/tabs.rs @@ -0,0 +1,28 @@ +//! The Tabs dialog's focus: it opens on the default interval, and Set moves into the new stop. + +use craft_text::ui::tabs_dialog::TabStopsDialog; +use craft_ui::dialog::{DialogStack, StackDialog as _}; +use craft_ui::testing::{Fixture, trial}; +use std::cell::RefCell; +use std::rc::Rc; + +/// Which of `labels` holds the focus. +fn focused<'a>(fixture: &Fixture, labels: &[&'a str]) -> Option<&'a str> { + let focused = craft_ui::testing::access::focused_key(fixture.tree()); + labels.iter().copied().find(|label| fixture.by_label(label).is_some_and(|target| target.node == focused)) +} + +#[trial] +fn the_dialog_opens_on_the_default_interval_and_set_moves_into_the_new_stop() { + let dialog = Rc::new(RefCell::new(TabStopsDialog::new(Vec::new(), 36.0))); + let shown = dialog.clone(); + let mut fixture = Fixture::new(move |ui| { + let _ = shown.borrow_mut().show(ui, &DialogStack::default()); + }); + fixture.idle(30); + let labels = ["Default tab stops:", "Tab stop position:", "Set"]; + assert_eq!(focused(&fixture, &labels), Some("Default tab stops:"), "the dialog opens on its first field"); + let set = fixture.by_label("Set").expect("Set is shown"); + fixture.click(&set).idle(4); + assert_eq!(focused(&fixture, &labels), Some("Tab stop position:"), "Set moves the focus into the new stop's position"); +} diff --git a/crates/timeline/src/ui/markers/dialog.rs b/crates/timeline/src/ui/markers/dialog.rs index 089c6929b..012232d3f 100644 --- a/crates/timeline/src/ui/markers/dialog.rs +++ b/crates/timeline/src/ui/markers/dialog.rs @@ -1,13 +1,12 @@ //! The Marker dialog: the draft it edits, its result and the dialog itself. use craft_ui::choice::{RadioGroup, Swatch}; -use craft_ui::contract::{Bind, Outcome as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::Row; use craft_ui::patterns::form_dialogs::FormDialog; use craft_ui::runtime::env::Env; -use craft_ui::runtime::focus::{self, FocusTarget}; use craft_ui::sections::{DialogRole, FooterButton}; use craft_ui::text::TextField; use egui::{Color32, Ui}; @@ -116,15 +115,11 @@ impl StackDialog for MarkerDialog { .extra_buttons(extras.iter().map(|(_, label)| FooterButton::new((*label).clone(), DialogRole::Other))) .shaped(|dialog| dialog.side_buttons(true)) .show(ui, |ui, form, draft| { - let first = form.first(); let timeline_words = Env::of(ui).words::(); let palette = label_palette(&form.env); FieldGroup::new(words.title.clone()).show(ui, |ui, _| { Field::new(words.name.clone()).show(ui, |ui, _| { - let field = TextField::new(words.name.clone(), Bind::bound(&mut draft.name)).show(ui); - if first { - focus::request(ui.ctx(), FocusTarget::Id(field.response().id)); - } + TextField::new(words.name.clone(), Bind::bound(&mut draft.name)).show(ui); }); Field::new(words.time.clone()).show(ui, |ui, _| { TextField::with_codec(words.time.clone(), Bind::bound(&mut draft.start), TimecodeCodec::new(format)).show(ui); diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index c22ea33a7..817427dc5 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -418,17 +418,19 @@ pub(crate) fn register_doc(ctx: &Context, key: DocKey, id: Id) { /// Moves focus to `target`, leaves modality unchanged and asks the enclosing scroll owner to reveal it. Called /// while a pass runs, it moves focus in that pass, so the rest of the pass reads the new focus; called between -/// passes, it moves focus at the next pass's begin hook. The one public path to programmatic focus. -pub fn request(ctx: &Context, target: FocusTarget) { +/// passes, it moves focus at the next pass's begin hook. The one public path to programmatic focus. `false` in a measuring +/// run, which moves nothing: a caller that keeps a pending request keeps it until a run takes it. +pub fn request(ctx: &Context, target: FocusTarget) -> bool { if !crate::runtime::measure::effect(ctx, "focus::request") { - return; + return false; } if crate::runtime::frame::in_pass(ctx) { request_now(ctx, target); - return; + return true; } with(ctx, |state| state.pending = Some(target)); crate::runtime::egui::repaint::request_of(ctx, crate::runtime::egui::pass::current_viewport(ctx)); + true } /// Applies `target` now, for an AccessKit `Focus` action, which moves focus in the pass that carries it. diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index a33ca8a47..8b6fda125 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -467,6 +467,7 @@ pub(super) fn initial_focus(state: &mut State, frame: u64) -> Vec { let pick = match policy.initial { Initial::First => stops.first(), Initial::Default => stops.iter().find(|rec| rec.stop.default).or_else(|| stops.first()), + Initial::FirstField => stops.iter().find(|rec| rec.stop.text).or_else(|| stops.iter().find(|rec| rec.stop.default)), Initial::Key(name) => stops.iter().find(|rec| rec.stop.name == Some(name)), _ => None, }; diff --git a/crates/ui-contract/src/runtime/focus/policy.rs b/crates/ui-contract/src/runtime/focus/policy.rs index 5b452892a..ddb0d0dc9 100644 --- a/crates/ui-contract/src/runtime/focus/policy.rs +++ b/crates/ui-contract/src/runtime/focus/policy.rs @@ -12,6 +12,8 @@ pub enum Initial { Keep, /// The scope's first stop. First, + /// The scope's first text or number field, else its default stop, else nothing: a dialog's default. + FirstField, /// The stop registered as the default. Default, /// The stop registered under this name. @@ -67,7 +69,7 @@ impl FocusPolicy { kind: ScopeKind::Dialog, trap: true, restore: true, - initial: Initial::First, + initial: Initial::FirstField, enter: EnterRule::Submit, cancel: CancelRule::Close, pages: false, diff --git a/crates/ui-panels/src/dialog/trials.rs b/crates/ui-panels/src/dialog/trials.rs index d8a5860b5..a595ce0ee 100644 --- a/crates/ui-panels/src/dialog/trials.rs +++ b/crates/ui-panels/src/dialog/trials.rs @@ -145,3 +145,28 @@ fn side_buttons_stand_in_one_column_beside_the_body() { assert!((ok.min.y - body.min.y).abs() < 4.0, "the column starts at the body's top: {ok:?} {body:?}"); assert!(preview.min.y >= other.max.y, "the footer content sits under the buttons"); } + +#[trial] +fn a_dialog_opens_on_its_first_field_else_its_default_button() { + let focus_on_open = |field: bool, buttons: bool| { + let mut fixture = Fixture::new(move |ui| { + let (mut open, mut name, mut on) = (true, String::new(), false); + let mut dialog = Dialog::new("Options").opened(Bind::bound(&mut open)); + if buttons { + dialog = dialog.buttons([FooterButton::new("OK", DialogRole::Accept), FooterButton::new("Cancel", DialogRole::Cancel)]); + } + dialog.show(ui, |ui, _| { + Checkbox::new(Bind::bound(&mut on)).label("Snap").show(ui); + if field { + TextField::new("Name", Bind::bound(&mut name)).show(ui); + } + }); + }); + fixture.idle(30); + let focused = crate::testing::access::focused_key(fixture.tree()); + ["Name", "OK", "Snap"].into_iter().find(|label| fixture.by_label(label).is_some_and(|target| target.node == focused)) + }; + assert_eq!(focus_on_open(true, true), Some("Name"), "the first field takes the focus though a check box comes first"); + assert_eq!(focus_on_open(false, true), Some("OK"), "without a field the default button takes it"); + assert_eq!(focus_on_open(false, false), None, "without either nothing takes it"); +} diff --git a/crates/ui-patterns/src/patterns/form_dialogs/password.rs b/crates/ui-patterns/src/patterns/form_dialogs/password.rs index 66c4f0307..fd597fc4d 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/password.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/password.rs @@ -1,13 +1,14 @@ //! `PasswordDialog`: the password for a protected file, a permissions password, or a new password with its strength. use crate::buttons::ToggleButton; -use crate::contract::{Bind, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _}; +use crate::contract::{Bind, NoValue, Outcome, Props as _, clicked, Remember as _, Show as _, ShowContainer as _}; use crate::dialog::{Dialog, DialogOutput}; use crate::display::{Icon, Progress, Text}; use crate::form::{Field, FieldGroup, Help}; use crate::layout_components::{Row, Stack}; use crate::primitives::IconSpec; use crate::runtime::env::{Env, Label}; +use crate::runtime::focus::{self, FocusTarget}; use crate::runtime::overlay::CloseReason; use crate::runtime::words::CommonWords; use crate::sections::{DialogRole, FooterButton}; @@ -224,7 +225,8 @@ impl Entries { /// field and the strength of the first entry. /// /// - Keys: Enter submits only when the entries are valid; Escape and the close action cancel. The reveal button -/// beside the first field shows or hides the text, and its name says what it does. +/// beside the first field shows or hides the text, and its name says what it does. The first field takes the focus +/// back after a press on the reveal button and whenever nothing has it, so typing goes on. /// - A wrong password: the app opens the dialog again with `error`; the field starts empty. /// - The password comes back in the output's answer, the pass the dialog closed as OK. #[must_use = "show the dialog with `show`"] @@ -307,9 +309,14 @@ impl<'a> PasswordDialog<'a> { if !entries.reveal { text = text.masked(); } - text.show(ui); + let text = text.show(ui); let name = if entries.reveal { words.hide.clone() } else { words.show.clone() }; - ToggleButton::new(name, Bind::bound(&mut entries.reveal)).icon(IconId::new("eye")).icon_only().show(ui); + let reveal = ToggleButton::new(name, Bind::bound(&mut entries.reveal)).icon(IconId::new("eye")).icon_only().show(ui); + // Typing goes on in the field: the reveal button hands the focus back, as does a press that left + // nothing focused. + if clicked(reveal.response()) || focus::focused_rec(ui.ctx()).is_none() { + focus::request(ui.ctx(), FocusTarget::Id(text.response().id)); + } }); }); if setting { diff --git a/crates/ui-patterns/tests/it/form_dialogs/mod.rs b/crates/ui-patterns/tests/it/form_dialogs/mod.rs index 0dc6c0864..7c99107e8 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/mod.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/mod.rs @@ -4,5 +4,6 @@ mod dialog; mod export; mod params; +mod password; mod preview; mod size_model; diff --git a/crates/ui-patterns/tests/it/form_dialogs/password.rs b/crates/ui-patterns/tests/it/form_dialogs/password.rs new file mode 100644 index 000000000..879563c88 --- /dev/null +++ b/crates/ui-patterns/tests/it/form_dialogs/password.rs @@ -0,0 +1,22 @@ +//! The password dialog keeps the keyboard in its field. + +use craft_ui::patterns::form_dialogs::{PasswordDialog, PasswordPurpose}; +use craft_ui::testing::{Fixture, trial}; + +fn focused_on(fixture: &Fixture, label: &str) -> bool { + let focused = craft_ui::testing::access::focused_key(fixture.tree()); + fixture.by_label(label).is_some_and(|target| target.node == focused) +} + +#[trial] +fn the_reveal_button_hands_the_focus_back_to_the_field() { + let mut fixture = Fixture::new(|ui| { + let _ = PasswordDialog::new(PasswordPurpose::open("poster.pdf")).show(ui); + }); + fixture.idle(30); + assert!(focused_on(&fixture, "Password"), "the dialog opens on the field"); + let reveal = fixture.by_label("Show password").expect("the reveal button is shown"); + fixture.click(&reveal).idle(4); + assert!(fixture.by_label("Hide password").is_some(), "the press revealed the text"); + assert!(focused_on(&fixture, "Password"), "the field has the focus back, so typing goes on"); +}