diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 845890f0df..0605417b82 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -150,6 +150,13 @@ impl PaintUi<'_> { self.child_with(id, rect, child, None, None) } + /// Makes the child shown with `key` the one a click on the composite's label focuses, in place of the composite's + /// first stop, such as the number field of a row whose slider comes first in Tab order. A child with no stop this + /// pass leaves the first stop. + pub fn label_target(&mut self, key: impl Hash + Debug) { + access::scope::label_target(self.ui.ctx(), self.id, self.id.with(key)); + } + /// Shows a child with rich tooltip content. pub fn child_with_tip(&mut self, key: impl Hash + Debug, rect: Rect, child: C, tip: impl FnOnce(&mut Ui)) -> C::Output { self.child_with(self.id.with(key), rect, child, Some(Box::new(tip)), None) diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index fe785b0555..16825da699 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -181,6 +181,8 @@ struct Open { stops: usize, /// The nodes that registered inside it and in no node component inside it. held: Vec, + /// The child whose stop a click on the label focuses, in place of the first stop inside it (`label_target`). + label_target: Option, } /// A control that reported its node in a scope: the name and description its node got at its own report. @@ -193,7 +195,8 @@ pub(crate) struct ScopeNode { pub description: Option, /// The missing-name finding of a node that may still be named by the scope: reported when it is not. pub unnamed: Option, - /// The first focus stop inside a control that has none of its own: where a click on its label moves focus. + /// The first focus stop inside a control that has none of its own, or the stop of the child it named + /// (`label_target`): where a click on its label moves focus. pub inner_stop: Option, /// The control takes key focus, at its own stop or at a part's (a segmented control's segments). pub focusable: bool, @@ -271,7 +274,17 @@ pub(crate) fn field_label(ctx: &Context) -> Option { pub(crate) fn enter(ctx: &Context, id: Id) { pass_state::with::(ctx, |stack| { if let Some(scope) = stack.0.last_mut() { - scope.open.push(Open { id, stops: crate::runtime::focus::stop_count(ctx), held: Vec::new() }); + scope.open.push(Open { id, stops: crate::runtime::focus::stop_count(ctx), held: Vec::new(), label_target: None }); + } + }); +} + +/// Names `child` as the component whose stop a click on the label of the node component `id` focuses, in place of +/// the first stop inside `id`. Read at `id`'s step 16; a child with no stop this pass leaves the first stop. +pub(crate) fn label_target(ctx: &Context, id: Id, child: Id) { + pass_state::with::(ctx, |stack| { + if let Some(open) = stack.0.iter_mut().rev().find_map(|scope| scope.open.iter_mut().rfind(|open| open.id == id)) { + open.label_target = Some(child); } }); } @@ -284,7 +297,7 @@ pub(crate) fn register(ctx: &Context, mut node: ScopeNode) { let Some(scope) = stack.0.last_mut() else { return node.unnamed.take().into_iter().collect() }; let mut unnamed = Vec::new(); if let Some(at) = scope.open.iter().rposition(|open| open.id == node.id) { - node.inner_stop = crate::runtime::focus::first_stop_inside(ctx, node.id, scope.open[at].stops); + node.inner_stop = crate::runtime::focus::first_stop_inside(ctx, node.id, scope.open[at].stops, scope.open[at].label_target); // What the node held sits inside it: none of it is a control of the scope. unnamed.extend(scope.open.drain(at..).flat_map(|open| open.held).filter_map(|held| held.unnamed)); } diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 077f3540d9..9c9b66baa7 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -545,14 +545,16 @@ pub(crate) fn has_reachable_stop(ctx: &Context, id: Id) -> bool { } /// Where a request for the component `id` goes when it has no stop of its own: the first stop registered since -/// `from` (a `stop_count`), which a component inside it holds. -pub(crate) fn first_stop_inside(ctx: &Context, id: Id, from: usize) -> Option { +/// `from` (a `stop_count`) that the component `prefer` holds, else the first stop registered since `from`, which a +/// component inside it holds. +pub(crate) fn first_stop_inside(ctx: &Context, id: Id, from: usize, prefer: Option) -> Option { take_app_widgets(ctx, None); with(ctx, |state| { if state.stop_ids.contains(&id) { return None; } - state.stops.get(from..)?.first().map(target_of) + let stops = state.stops.get(from..)?; + prefer.and_then(|child| stops.iter().find(|rec| rec.stop.id == child)).or_else(|| stops.first()).map(target_of) }) } diff --git a/crates/ui-contract/src/testing/replay_trials.rs b/crates/ui-contract/src/testing/replay_trials.rs index 2f3e2741c9..222c7f5007 100644 --- a/crates/ui-contract/src/testing/replay_trials.rs +++ b/crates/ui-contract/src/testing/replay_trials.rs @@ -120,8 +120,8 @@ fn replayed_focus_stops_keep_their_own_target() { let ctx = ui.ctx(); let from = focus::stop_count(ctx); focus::replay(ctx, &recorded.focus); - assert_eq!(focus::first_stop_inside(ctx, parent, from), Some(focus::FocusTarget::Id(child))); - assert_eq!(focus::first_stop_inside(ctx, child, from), None); + assert_eq!(focus::first_stop_inside(ctx, parent, from, None), Some(focus::FocusTarget::Id(child))); + assert_eq!(focus::first_stop_inside(ctx, child, from, None), None); }); } diff --git a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs index 41aff4c562..9fc8a985c7 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/dialog.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/dialog.rs @@ -933,8 +933,13 @@ fn a_typed_value_past_a_rows_range_is_clamped_and_the_host_takes_one_range_alert let mut fixture = host_fixture(&host, &twice); host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "light", DialogFields::new(), light)); fixture.idle(6); + // The number field named `label`: a range row's slider, before it on the line, carries the same name. let enter = |fixture: &mut Fixture, label: &str, text: &str| { - let field = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} field")); + let field = fixture + .by_role(Role::SPIN_BUTTON) + .into_iter() + .find(|target| fixture.tree().name_of(target.node) == Some(label)) + .unwrap_or_else(|| panic!("the {label} field")); fixture.click(&field).settle(); fixture.key(Key::A, Modifiers::COMMAND).type_text(text); fixture.key(Key::Tab, Modifiers::NONE).settle(); diff --git a/crates/ui-widgets/src/form/slider_field.rs b/crates/ui-widgets/src/form/slider_field.rs index 9ee3a89690..54435985fc 100644 --- a/crates/ui-widgets/src/form/slider_field.rs +++ b/crates/ui-widgets/src/form/slider_field.rs @@ -53,7 +53,9 @@ pub struct SliderFieldStyle { /// The step moves the slider's keys and wheel and the field's keys, wheel and scrub; typed values snap to it unless /// `typed_decimals` sets their independent precision. Without a step the field steps by a hundredth on a range 10 wide /// or less and by 1 on a longer one, and by default rounds typed values to the places that step needs. The field and -/// then the slider are Tab stops. A log or power scale curves the +/// the slider are Tab stops in the order they are read: the field and then the slider when stacked, the slider and then +/// the field when inline. A click on the row's label focuses the number field in either layout. A log or power scale +/// curves the /// slider's track only: the field, typing and steps stay linear. #[derive(crate::contract::Component, crate::contract::Props)] pub struct SliderField<'a> { @@ -61,8 +63,8 @@ pub struct SliderField<'a> { common: Common, value: Bind<'a, f64>, range: RangeInclusive, - /// Whether the caption and the number field share a line over the slider, or the number field comes first on the - /// slider's line for a row labelled by an enclosing `Field`. + /// Whether the caption and the number field share a line over the slider, or the slider and then the number field + /// share one line for a row labelled by an enclosing `Field`. #[prop] layout: SliderFieldLayout, /// How positions along the slider's track map to values. @@ -404,27 +406,43 @@ impl Component for SliderField<'_> { }; let flow = Flow::new(cx.rect, cx.env.direction().is_rtl()); let place = |logical: Rect| flow.to_physical(logical.translate(cx.rect.min.to_vec2())); - // The field is shown first, so it is the first Tab stop. + // The parts are shown in the order they are read, which is their Tab order: the field's line comes first when + // stacked, and the slider comes before the field on the inline line. // The group has no stop, so its tooltip, and with it the reason it is disabled, is carried by the first stop. let face = self.track_face.take(); let bind = self.value.reborrow(); let field_view = look.field(&name, shown, Some(bind.check_of())); - let field_view = match cx.resolved.tooltip { - Some(tooltip) => field_view.tooltip(tooltip.clone()), - None => field_view, - }; - let typed = match self.layout { - // The label step puts the caption at the line's start and the field in the number cell at its end. - SliderFieldLayout::Stacked => { - ui.labelled("field", place(field), name.clone(), SideLabel::new().layout(FieldLayout::Line).scrub(true), field_view) - } - SliderFieldLayout::Inline => ui.child("field", place(field), field_view), - }; - self.out_of_range = typed.out_of_range.clone(); // A read-only field's track is read-only too: no press on it edits the value, whatever `track_press` is, and an // inert composite arms no first-Down gesture in its child for a later writable release. let slider = look.slider(&name, shown, Some(bind.check_of()), face).read_only(cx.resolved.read_only); - let dragged = ui.child("slider", place(track), slider); + let (typed, dragged) = match self.layout { + // The label step puts the caption at the line's start and the field in the number cell at its end. + SliderFieldLayout::Stacked => { + let field_view = match cx.resolved.tooltip { + Some(tooltip) => field_view.tooltip(tooltip.clone()), + None => field_view, + }; + let typed = ui.labelled("field", place(field), name.clone(), SideLabel::new().layout(FieldLayout::Line).scrub(true), field_view); + (typed, ui.child("slider", place(track), slider)) + } + SliderFieldLayout::Inline => { + let slider = match cx.resolved.tooltip { + Some(tooltip) => slider.tooltip(tooltip.clone()), + None => slider, + }; + // The number field the label focuses shows the tooltip too while enabled. Disabled, the slider alone + // carries the reason and stays the one Tab stop. + let field_view = match cx.resolved.tooltip { + Some(tooltip) if cx.resolved.enabled => field_view.tooltip(tooltip.clone()), + _ => field_view, + }; + let dragged = ui.child("slider", place(track), slider); + // A click on the enclosing field's label focuses the number field, the part that takes typing. + ui.label_target("field"); + (ui.child("field", place(field), field_view), dragged) + } + }; + self.out_of_range = typed.out_of_range.clone(); let start = *self.range.start(); cx.adopt(&typed, &start, |value, mine| { if let Some(value) = value { diff --git a/crates/ui-widgets/tests/it/form.rs b/crates/ui-widgets/tests/it/form.rs new file mode 100644 index 0000000000..205f1801d8 --- /dev/null +++ b/crates/ui-widgets/tests/it/form.rs @@ -0,0 +1,152 @@ +//! `SliderField`: Tab visits its slider and its number field in the order a reader meets them on the row. + +use craft_ui::contract::{Bind, Props as _, Role, Show as _, ShowContainer as _, TooltipSpec}; +use craft_ui::form::{Field, SliderField, SliderFieldLayout}; +use craft_ui::layout_components::Row; +use craft_ui::runtime::env::Direction; +use craft_ui::testing::focus::AccessActionKind; +use craft_ui::testing::{Fixture, Target, trial}; +use craft_ui::text::NumberField; +use egui::{Key, Modifiers}; + +/// A focused control: its role and its name. +type Stop = (Option, Option); + +/// The control keyboard focus is on. +fn focused(fixture: &Fixture) -> Stop { + let tree = fixture.tree(); + let key = tree.focused_key(); + (tree.role_of(key), tree.name_of(key).map(str::to_owned)) +} + +/// A row that holds a number field, a slider field laid out as `layout` and another number field, under `direction`. +/// A disabled slider field carries a reason, so its first part stays a Tab stop. +fn row(layout: SliderFieldLayout, direction: Direction, enabled: bool) -> Fixture { + let mut fixture = Fixture::new(move |ui| { + Row::new().show(ui, |ui, _| { + let mut before = Some(1.0); + let mut size = 20.0; + let mut after = Some(2.0); + NumberField::new("Before", Bind::bound(&mut before)).range(0.0..=10.0).show(ui); + SliderField::new("Size", Bind::bound(&mut size), 0.0..=100.0) + .layout(layout) + .enabled(enabled) + .tooltip(TooltipSpec::new("The brush size").disabled_text("Pick a brush first")) + .show(ui); + NumberField::new("After", Bind::bound(&mut after)).range(0.0..=10.0).show(ui); + }); + }); + fixture.direction(direction).settle(); + fixture +} + +/// The controls `count` presses of Tab reach from the start of `fixture`, then those `count - 1` presses of Shift-Tab +/// reach back from the last one. +fn tabs(fixture: &mut Fixture, count: usize) -> (Vec, Vec) { + let mut forward = Vec::new(); + for _ in 0..count { + fixture.key(Key::Tab, Modifiers::NONE).settle(); + forward.push(focused(fixture)); + } + let mut back = vec![focused(fixture)]; + for _ in 1..count { + fixture.key(Key::Tab, Modifiers::SHIFT).settle(); + back.push(focused(fixture)); + } + (forward, back) +} + +/// A part of the slider field. +fn size(role: Role) -> Stop { + (Some(role), Some("Size".to_owned())) +} + +/// The number field `name` beside the slider field. +fn other(name: &str) -> Stop { + (Some(Role::SPIN_BUTTON), Some(name.to_owned())) +} + +/// In both directions, Tab goes from the field before the slider field to its slider, then its number field, then the +/// field after it; Shift-Tab goes back the same way. In the inline layout the slider comes first on the line; in the +/// stacked one the number field is on the caption line above the slider. +#[trial] +fn tab_visits_a_slider_fields_parts_in_reading_order() { + for (layout, [first, second]) in [ + (SliderFieldLayout::Inline, [size(Role::SLIDER), size(Role::SPIN_BUTTON)]), + (SliderFieldLayout::Stacked, [size(Role::SPIN_BUTTON), size(Role::SLIDER)]), + ] { + let order = vec![other("Before"), first, second, other("After")]; + let reversed: Vec = order.iter().rev().cloned().collect(); + for direction in [Direction::Ltr, Direction::Rtl] { + let (forward, back) = tabs(&mut row(layout, direction, true), order.len()); + assert_eq!(forward, order, "Tab order of a {layout:?} slider field under {direction:?}"); + assert_eq!(back, reversed, "Shift-Tab order of a {layout:?} slider field under {direction:?}"); + } + } +} + +/// A slider field laid out as `layout` under `direction`: inline in a `Field` row that labels it, stacked under its own +/// caption. +fn labelled(layout: SliderFieldLayout, direction: Direction) -> Fixture { + let mut fixture = Fixture::new(move |ui| { + let mut size = 20.0; + if matches!(layout, SliderFieldLayout::Inline) { + Field::new("Size").show(ui, |ui, _| SliderField::new("Size", Bind::bound(&mut size), 0.0..=100.0).layout(layout).show(ui)); + } else { + SliderField::new("Size", Bind::bound(&mut size), 0.0..=100.0).layout(layout).show(ui); + } + }); + fixture.direction(direction).settle(); + fixture +} + +/// The label that names the slider field: the "Size" label node. +fn label(fixture: &Fixture) -> Target { + let tree = fixture.tree(); + let key = tree.keys().into_iter().find(|key| tree.name_of(*key) == Some("Size") && tree.role_of(*key) == Some(Role::LABEL)); + key.and_then(|key| fixture.target(key)).unwrap_or_else(|| panic!("no label names the slider field")) +} + +/// A click on the label of a slider field focuses its number field, the part that takes typing, whichever part Tab +/// reaches first: inline, where the slider is the first stop, and stacked, under its own caption, in both directions. +/// A pointer click and an accessibility click both go there. +#[trial] +fn a_click_on_a_slider_fields_label_focuses_its_number_field() { + for layout in [SliderFieldLayout::Inline, SliderFieldLayout::Stacked] { + for direction in [Direction::Ltr, Direction::Rtl] { + let mut fixture = labelled(layout, direction); + let caption = label(&fixture); + fixture.click(&caption).settle(); + assert_eq!(focused(&fixture), size(Role::SPIN_BUTTON), "a click on a {layout:?} slider field's label under {direction:?}"); + + let mut fixture = labelled(layout, direction); + let caption = label(&fixture); + fixture.access(AccessActionKind::Click, &caption).settle(); + assert_eq!(focused(&fixture), size(Role::SPIN_BUTTON), "an access click on a {layout:?} slider field's label under {direction:?}"); + } + } +} + +/// An enabled inline slider field's tooltip describes both its parts: the slider Tab reaches first and the number field +/// a click on the row's label focuses. +#[trial] +fn an_inline_slider_fields_tooltip_describes_both_its_parts() { + let fixture = row(SliderFieldLayout::Inline, Direction::Ltr, true); + let tree = fixture.tree(); + for role in [Role::SLIDER, Role::SPIN_BUTTON] { + let part = tree.with_role(role).into_iter().find(|key| tree.name_of(*key) == Some("Size")); + let description = part.and_then(|key| tree.description_of(key)); + assert_eq!(description, Some("The brush size"), "the {role:?} of an inline slider field"); + } +} + +/// A disabled slider field's reason is carried by the part read first, which stays the one Tab stop of the field: the +/// slider on the inline line, the number field when stacked. +#[trial] +fn a_disabled_slider_fields_reason_is_on_the_part_read_first() { + for (layout, first) in [(SliderFieldLayout::Inline, size(Role::SLIDER)), (SliderFieldLayout::Stacked, size(Role::SPIN_BUTTON))] { + let order = vec![other("Before"), first, other("After")]; + let (forward, _) = tabs(&mut row(layout, Direction::Ltr, false), order.len()); + assert_eq!(forward, order, "Tab order of a disabled {layout:?} slider field"); + } +} diff --git a/crates/ui-widgets/tests/it/main.rs b/crates/ui-widgets/tests/it/main.rs index c54922f773..82d153f715 100644 --- a/crates/ui-widgets/tests/it/main.rs +++ b/crates/ui-widgets/tests/it/main.rs @@ -13,6 +13,7 @@ pub(crate) mod contract; pub(crate) mod disabled_fade; pub(crate) mod field_text_centred; pub(crate) mod focus_ring; +pub(crate) mod form; pub(crate) mod keys; pub(crate) mod label; pub(crate) mod layer; diff --git a/crates/ui-widgets/tests/it/value_drag/primary_down.rs b/crates/ui-widgets/tests/it/value_drag/primary_down.rs index c38fdf316a..e49fe3ea60 100644 --- a/crates/ui-widgets/tests/it/value_drag/primary_down.rs +++ b/crates/ui-widgets/tests/it/value_drag/primary_down.rs @@ -140,7 +140,8 @@ impl Rig { Self { fixture, state, fields } } fn geometry(&mut self, row: usize) -> Geometry { - for _ in 0..((row + 1) * if self.fields { 2 } else { 1 }) { + // An inline slider field's slider is its first stop, before its number field. + for _ in 0..(if self.fields { row * 2 + 1 } else { row + 1 }) { self.fixture.key(Key::Tab, Modifiers::NONE).settle(); } let owner = self.fixture.focused_stop().expect("naturally focused real Slider child").0;