From 45ebb7b8980168656553ae1783516758d6da1c66 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 24 Nov 2026 00:10:14 +0100 Subject: [PATCH 01/18] Value editing: scalar row keys, drag modifiers, number codecs, custom slider scales and a directional wheel Pieces a ported app's value rows need, each opt-in with defaults unchanged: - ScalarKeyPolicy (Slider::key_policy, SliderField::key_policy): Up and Down nudge a slider row by its own amount, Shift by shift_factor, snapped to model_step, from the row's caption, track or field, without moving focus; AccessKit increment and decrement use the same amount. - DragModifiers (Slider, SliderField, NumberField::pointer_modifiers): which modifier makes a pointer drag or scrub fine or coarse. pointer_model_step snaps pointer values on a slider to a zero-origin grid without changing keys or wheel. - NumberCodec::parse_with: a reader that owns the whole input, for a domain grammar. SliderField::number_codec passes a codec to its number field. - SliderScale::Custom: a caller's monotonic projection between values and track positions; text, steps, wheel and accessibility stay in model units. - WheelScope::Directional: value controls edit on a horizontal swipe or Shift-wheel under the pointer, and on a vertical wheel only after a press, until the pointer leaves; keyboard focus does not re-arm it. --- crates/behavior/src/codec.rs | 28 +- crates/behavior/src/lib.rs | 6 +- crates/behavior/src/value_drag.rs | 111 +- crates/behavior/src/wheel.rs | 82 +- crates/behavior/tests/codec_override.rs | 67 ++ crates/behavior/tests/main.rs | 1 + .../ui-contract/src/contract/steps/sense.rs | 5 +- .../ui-contract/src/runtime/env/overrides.rs | 5 + crates/ui-contract/src/runtime/keys.rs | 11 +- .../ui-contract/src/runtime/keys/intents.rs | 15 + crates/ui-contract/src/runtime/keys/route.rs | 111 +- crates/ui-contract/src/runtime/keys/scalar.rs | 183 +++ crates/ui-widgets/src/form/slider_field.rs | 88 +- crates/ui-widgets/src/text/number.rs | 20 +- crates/ui-widgets/src/value_drag/mod.rs | 2 + crates/ui-widgets/src/value_drag/slider.rs | 83 +- crates/ui-widgets/src/value_drag/track.rs | 57 +- crates/ui-widgets/tests/it/value_drag.rs | 55 + .../tests/it/value_drag/codec_override.rs | 57 + .../tests/it/value_drag/custom_scale.rs | 176 +++ .../tests/it/value_drag/scalar_contracts.rs | 192 +++ .../tests/it/value_drag/scalar_key_policy.rs | 1028 +++++++++++++++++ 22 files changed, 2332 insertions(+), 51 deletions(-) create mode 100644 crates/behavior/tests/codec_override.rs create mode 100644 crates/ui-contract/src/runtime/keys/scalar.rs create mode 100644 crates/ui-widgets/tests/it/value_drag/codec_override.rs create mode 100644 crates/ui-widgets/tests/it/value_drag/custom_scale.rs create mode 100644 crates/ui-widgets/tests/it/value_drag/scalar_contracts.rs create mode 100644 crates/ui-widgets/tests/it/value_drag/scalar_key_policy.rs diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 0aa23ef1bf..2ea4d5a628 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -145,10 +145,10 @@ impl Codec for PlainText { } } -/// A reader a caller adds for words that stand for numbers. +/// A caller's text-to-number reader. type Custom = Arc Option + Send + Sync>; -/// An optional number: empty text is `None`; anything else reads through a [`Reader`]. +/// An optional number: empty text is `None`; anything else reads through a [`Reader`] unless overridden with [`NumberCodec::parse_with`]. #[derive(Clone)] pub struct NumberCodec { reader: Reader, @@ -156,6 +156,8 @@ pub struct NumberCodec { /// Every decimal place is written, trailing zeros included. fixed: bool, custom: Option, + /// An authoritative reader for the complete, trimmed, non-empty input. + primary: Option, /// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]). zoom: bool, signed_zoom: bool, @@ -170,6 +172,7 @@ impl fmt::Debug for NumberCodec { .field("zoom", &self.zoom) .field("signed_zoom", &self.signed_zoom) .field("custom", &self.custom.is_some()) + .field("primary", &self.primary.is_some()) .finish() } } @@ -181,12 +184,18 @@ impl PartialEq for NumberCodec { (Some(a), Some(b)) => Arc::ptr_eq(a, b), _ => false, }; + let same_primary = match (&self.primary, &other.primary) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + }; self.reader == other.reader && self.decimals == other.decimals && self.fixed == other.fixed && self.zoom == other.zoom && self.signed_zoom == other.signed_zoom && same_custom + && same_primary } } @@ -220,7 +229,7 @@ const NUMBER_SAMPLE: &str = "0000.00"; impl NumberCodec { /// A codec reading with `reader` and writing at most `decimals` decimal places. pub fn new(reader: Reader, decimals: usize) -> Self { - NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, signed_zoom: false } + NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, signed_zoom: false } } /// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown @@ -282,6 +291,16 @@ impl NumberCodec { self } + /// The same codec with an authoritative reader for the complete, trimmed, non-empty input. It replaces the + /// reader's expressions/relative input, zoom parsing and `or_parse`: `None` or a non-finite result rejects the + /// input without fallback. Empty text still means `None`. Formatting and the character filter are unchanged. + /// + /// Use this when a domain's existing grammar must own the whole value, rather than adding a word with `or_parse`. + pub fn parse_with(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self { + self.primary = Some(Arc::new(parse)); + self + } + /// The widest text the codec writes for a number in `range`: the longest of each end and the number one place of /// the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized /// for any value it shows in it. @@ -346,6 +365,9 @@ impl Codec for NumberCodec { if trimmed.is_empty() { return Ok((None, ParseNote::default())); } + if let Some(parse) = &self.primary { + return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue); + } if self.zoom { return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note)); } diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 2ca15409c8..cdc453d45c 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -115,10 +115,10 @@ pub use sense::Sense; pub use sizing::{ControlMetrics, Metrics, Proposal}; pub use typing::{EditRun, Ended, EscapeRule, Escaped, Typed, TypingRun}; pub use value::{ - Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GestureNote, GesturePhase, Mixed, Preview, Validity, Value, - same_in_f32, same_in_f32_at, + Applied, CancelReason, EditEvent, EditEvents, EditPolicy, Gesture, GestureId, GestureNote, GesturePhase, Mixed, Preview, + Validity, Value, same_in_f32, same_in_f32_at, }; -pub use value_drag::{DragWarp, ValueDrag, wrap_value}; +pub use value_drag::{DragModifier, DragModifiers, DragWarp, ValueDrag, wrap_value}; pub use wheel::{GESTURE_GAP, Wheel, WheelEase, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit}; #[cfg(test)] diff --git a/crates/behavior/src/value_drag.rs b/crates/behavior/src/value_drag.rs index 4a69c6a4e0..e2968b7285 100644 --- a/crates/behavior/src/value_drag.rs +++ b/crates/behavior/src/value_drag.rs @@ -5,6 +5,52 @@ use crate::press::{PressPhase, PressState}; use emath::{Pos2, Rect, Vec2}; use std::ops::{Range, RangeInclusive}; +/// A modifier that changes continuous pointer-drag sensitivity. It does not remap input or keys. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum DragModifier { + /// Alt (Option). + Alt, + /// Shift. + Shift, + /// Control. + Control, + /// The platform's command modifier. + Command, +} + +impl DragModifier { + fn held(self, press: &PressState) -> bool { + match self { + Self::Alt => press.mods.alt, + Self::Shift => press.mods.shift, + Self::Control => press.mods.ctrl, + Self::Command => press.mods.cmd, + } + } +} + +/// The pointer-only fine/coarse bindings of a continuous drag. Fine wins when both bindings match. +/// Unbound modifiers leave travel normal. Defaults retain Alt fine, Shift coarse. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DragModifiers { + fine: Option, + coarse: Option, +} + +impl DragModifiers { + /// Selects the fine and coarse bindings; `None` disables that binding. + pub const fn new(fine: Option, coarse: Option) -> Self { + Self { fine, coarse } + } +} + +impl Default for DragModifiers { + fn default() -> Self { + Self::new(Some(DragModifier::Alt), Some(DragModifier::Shift)) + } +} + /// How the pointer's position along the axis becomes a value. #[derive(Clone, Debug, PartialEq)] enum Mapping { @@ -24,6 +70,7 @@ pub struct ValueDrag { hide_cursor: bool, fine: f64, coarse: Option, + modifiers: DragModifiers, } /// The factor Alt (Option) applies to travel when a drag sets none. @@ -40,12 +87,30 @@ impl ValueDrag { /// A track whose `start` lies after its `end` runs backwards, as a vertical slider's does, and a range whose start /// exceeds its end maps the track the other way; the value stays within the range either way. pub fn absolute(track: Range, range: RangeInclusive) -> Self { - ValueDrag { mapping: Mapping::Absolute { track }, axis: Axis::X, range, warp: false, hide_cursor: false, fine: FINE, coarse: None } + ValueDrag { + mapping: Mapping::Absolute { track }, + axis: Axis::X, + range, + warp: false, + hide_cursor: false, + fine: FINE, + coarse: None, + modifiers: DragModifiers::default(), + } } /// The value changes by `rate` units per point of travel from the press. Vertical travel upwards increases it. pub fn relative(rate: f64, range: RangeInclusive) -> Self { - ValueDrag { mapping: Mapping::Relative { rate }, axis: Axis::X, range, warp: false, hide_cursor: false, fine: FINE, coarse: None } + ValueDrag { + mapping: Mapping::Relative { rate }, + axis: Axis::X, + range, + warp: false, + hide_cursor: false, + fine: FINE, + coarse: None, + modifiers: DragModifiers::default(), + } } /// The axis the pointer travels on; the default is horizontal. @@ -67,6 +132,12 @@ impl ValueDrag { self } + /// Selects pointer fine/coarse bindings without changing keyboard or wheel behavior. + pub const fn modifiers(mut self, modifiers: DragModifiers) -> Self { + self.modifiers = modifiers; + self + } + /// Warps the pointer to the other side of the window when the drag reaches an edge, so the drag has no end /// ([`ValueDrag::warp_by`], [`DragWarp`]). It sets no wrap of the value. pub const fn warp(mut self, on: bool) -> Self { @@ -129,9 +200,9 @@ impl ValueDrag { _ => return None, }; let pos = pos - shift; - let fine = if press.mods.alt { + let fine = if self.modifiers.fine.is_some_and(|binding| binding.held(press)) { self.fine - } else if press.mods.shift { + } else if self.modifiers.coarse.is_some_and(|binding| binding.held(press)) { self.coarse.unwrap_or(1.0) } else { 1.0 @@ -236,6 +307,38 @@ mod tests { use craft_keymap::Mods; use emath::{Vec2, pos2}; + #[test] + fn pointer_modifier_policy_preserves_defaults_and_raw_modifiers() { + let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0); + let mut both = Mods::ALT; + both.shift = true; + for (mods, expected) in [(Mods::NONE, 20.0), (Mods::SHIFT, 200.0), (Mods::ALT, 2.0), (both, 2.0)] { + let press = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), mods); + assert_eq!(base.value(0.0, &press, false), Some(expected)); + assert_eq!(press.mods, mods); + } + } + + #[test] + fn pointer_modifier_policy_selects_shift_fine_and_alt_normal() { + let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0).modifiers(DragModifiers::new(Some(DragModifier::Shift), None)); + let mut both = Mods::ALT; + both.shift = true; + for (mods, expected) in [(Mods::NONE, 20.0), (Mods::SHIFT, 2.0), (Mods::ALT, 20.0), (both, 2.0)] { + let press = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), mods); + assert_eq!(base.value(0.0, &press, false), Some(expected)); + assert_eq!(press.mods, mods); + } + } + + #[test] + fn pointer_modifier_policy_unbound_and_overlapping_bindings_are_explicit() { + let base = ValueDrag::relative(1.0, -1000.0..=1000.0).coarse(10.0); + let shift = drag(pos2(0.0, 0.0), pos2(20.0, 0.0), Mods::SHIFT); + assert_eq!(base.clone().modifiers(DragModifiers::new(None, None)).value(0.0, &shift, false), Some(20.0)); + assert_eq!(base.modifiers(DragModifiers::new(Some(DragModifier::Shift), Some(DragModifier::Shift))).value(0.0, &shift, false), Some(2.0)); + } + fn drag(from: Pos2, to: Pos2, mods: Mods) -> PressState { let start = PressStart::new(from, PointerButton::Primary, 0.0, 1); PressState::new(PressPhase::Drag { start, pos: to, delta: Vec2::ZERO }).mods(mods) diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index a5826e2826..8189757571 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -334,6 +334,10 @@ pub struct WheelTaker { /// It takes any axis (scroll or zoom) only while focused or armed: a value control, unless its scope frees it, /// or any taker inside a gated scope. pub gated: bool, + /// Directional value editing: dominant horizontal (or Shift) scroll edits under the pointer; + /// vertical scroll requires explicit arming, not keyboard focus. The existing arming lifecycle + /// disarms on leaving the control, without changing keyboard focus. + pub directional: bool, /// A scroll region (a scrolling body or collection): Shift turns the vertical wheel sideways over it. pub scrolls: bool, /// The distance of one wheel line. @@ -402,6 +406,7 @@ impl WheelTaker { vertical: false, zoom: false, gated: false, + directional: false, scrolls: false, notch: WheelNotch::DEFAULT, room: None, @@ -469,6 +474,14 @@ impl WheelTaker { self } + /// Opts a value control into directional editing, without changing the default focus gate. + /// The caller registers both scroll axes and keeps the taker gated so presses can arm it. + #[must_use] + pub const fn directional(mut self, on: bool) -> Self { + self.directional = on; + self + } + /// The distance of one wheel line. pub const fn notch(mut self, notch: WheelNotch) -> Self { self.notch = notch; @@ -594,7 +607,7 @@ pub fn split( if !running { *gesture = WheelGesture::default(); } - let field = focus.taker.filter(|focused| !focus.by_position && takers.iter().any(|taker| taker.field && taker.owner == *focused)); + let field = focus.taker.filter(|focused| !focus.by_position && takers.iter().any(|taker| taker.field && !taker.directional && taker.owner == *focused)); let app_field = focus.app_field && !focus.by_position; // A value control keeps its gesture only while the pointer is over it: once the pointer leaves, the gesture goes // on by position as a running one (value controls excluded) and the control hears its end now, so its edit run @@ -653,9 +666,19 @@ fn split_at( // Takers register outer first, so among equal areas the later one is the deeper (or the upper) and goes first. let mut under: Vec<&WheelTaker> = takers.iter().rev().filter(|taker| taker.rect.contains(at)).collect(); under.sort_by(|a, b| a.rect.area().total_cmp(&b.rect.area())); - // A trackpad steps a value control only while it is focused or armed: over anything else it scrolls the panel. + // Read intent without changing anyone's input: a running panel gesture can cross a + // directional control without that control becoming an eligible recipient. + let sideways = wheel.scroll.x.abs() > wheel.scroll.y.abs() + || (wheel.mods.shift && wheel.scroll.x == 0.0 && wheel.scroll.y != 0.0); + // A trackpad otherwise steps a value control only while it is focused or armed. let fingers = wheel.source.fingers(); - let open = |taker: &WheelTaker| (!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner); + let open = |taker: &WheelTaker| { + if taker.directional { + !(wheel.mods.alt || wheel.mods.cmd || wheel.mods.ctrl) && (sideways || armed == Some(taker.owner)) + } else { + (!taker.gated && !(fingers && taker.value)) || armed == Some(taker.owner) || focused == Some(taker.owner) + } + }; // The running gesture's owner, while it is registered and open; it takes its axes wherever the pointer is. A // focused field holds the wheel by the field rule alone, so a wheel with Alt or Cmd/Ctrl still reaches the view. let held: Option<&WheelTaker> = latch @@ -664,6 +687,17 @@ fn split_at( // Who takes a scroll axis by position: any open taker for a new gesture; during a running one no value control, // so a control the pointer passes over does not take the scroll over. let free = |taker: &WheelTaker| open(taker) && (latch.is_none() || !taker.value); + let horizontal_recipient = held.filter(|taker| taker.horizontal) + .or_else(|| under.iter().copied().find(|taker| taker.horizontal && free(taker) && taker.has_room(false, wheel.scroll.x))); + let wheel = if sideways && horizontal_recipient.is_some_and(|taker| taker.directional) { + // Only the selected directional recipient reads a normalized dominant-axis share. + // Another owner, including a latched panel or a command-chord recipient, keeps the + // device's original components unchanged. + let (along, lines) = if wheel.scroll.x == 0.0 { (wheel.scroll.y, wheel.lines.y) } else { (wheel.scroll.x, wheel.lines.x) }; + Wheel { scroll: Vec2::new(along, 0.0), lines: Vec2::new(lines, 0.0), ..wheel } + } else { + wheel + }; let zone = (wheel.scroll.y != 0.0).then(|| under.iter().position(|t| (t.vertical || t.zooms_view) && open(t))).flatten(); let zone_view = zone.filter(|&at| !under[at].vertical).and_then(|at| under[at + 1..].iter().find(|t| t.zoom && open(t))).map(|t| t.owner); // A running gesture zooms a view by the zone only when it is that view's gesture. @@ -811,4 +845,46 @@ mod tests { assert!(notch(&mut ease, -NOTCH, 2.0 + 11.0 * 0.02) < -NOTCH - 1.0, "precondition: the run is fast again"); assert!(near(notch(&mut ease, -NOTCH, 5.0), -NOTCH), "an idle gap starts again at one notch"); } + + #[test] + fn directional_value_wheel_keeps_plain_defaults_and_requires_arming_only_for_vertical() { + let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true); + let control = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true).value(true).gated(true); + let at = pos2(10.0, 10.0); + let shares = |control, wheel, focus, armed| split(&[panel, control], at, wheel, WheelFocus::new(focus), armed, &mut WheelGesture::default(), 0.0); + assert_eq!(shares(control, wheel(0.0, 6.0), Some(2), None)[0].0, 2, "default focus gate is unchanged"); + assert_eq!(shares(control, wheel(6.0, 0.0), None, None)[0].0, 1, "default unfocused sideways scroll stays with the panel"); + let directional = control.directional(true); + assert_eq!(shares(directional, wheel(0.0, 6.0), Some(2), None)[0].0, 1, "focus alone does not rearm vertical editing"); + assert_eq!(shares(directional, wheel(0.0, 6.0), Some(2), Some(2))[0].0, 2, "an explicit press arms vertical editing"); + let horizontal = shares(directional, wheel(6.0, 0.0).source(WheelSource::Trackpad), None, None); + assert_eq!((horizontal[0].0, horizontal[0].1.scroll), (2, Vec2::new(6.0, 0.0)), "an unselected horizontal trackpad swipe edits"); + let diagonal_right = shares(directional, wheel(12.0, -3.0), None, None); + assert_eq!((diagonal_right[0].0, diagonal_right[0].1.scroll), (2, Vec2::new(12.0, 0.0)), "horizontal-dominant intent keeps its sign"); + let shifted = shares(directional, Wheel { mods: Mods::SHIFT, ..wheel(0.0, 6.0) }, None, None); + assert_eq!((shifted[0].0, shifted[0].1.scroll), (2, Vec2::new(6.0, 0.0)), "Shift-wheel is explicitly sideways"); + let diagonal = shares(directional, wheel(3.0, -12.0), Some(2), None); + assert!(diagonal.iter().all(|(owner, _)| *owner == 1), "a vertical-dominant swipe stays with the panel despite focus"); + assert_eq!(diagonal[0].1.scroll.y, -12.0, "vertical scrolling remains available"); + for mods in [Mods::CTRL, Mods::ALT, Mods::CMD, Mods { shift: true, ..Mods::CTRL }] { + let chord = shares(directional, Wheel { mods, ..wheel(12.0, -3.0) }, None, None); + assert_eq!((chord[0].0, chord[0].1.scroll), (1, Vec2::new(12.0, -3.0)), "command chords keep both original panel components: {mods:?}"); + } + } + + #[test] + fn directional_control_under_a_running_panel_scroll_must_not_strip_its_vertical_share() { + let panel = WheelTaker::new(1u8, rect(300.0)).horizontal(true).vertical(true).scrolls(true); + let directional = WheelTaker::new(2u8, rect(100.0)).horizontal(true).vertical(true) + .value(true).gated(true).directional(true); + let mut gesture = WheelGesture::default(); + let first = split(&[panel, directional], pos2(200.0, 200.0), wheel(12.0, -3.0), + WheelFocus::new(None), None, &mut gesture, 0.0); + assert_eq!((first[0].0, first[0].1.scroll), (1, Vec2::new(12.0, -3.0))); + // The existing panel-owned gesture crosses an opted-in slider. Values are excluded while + // another owner holds the gesture, so the untouched panel must retain BOTH scroll axes. + let crossing = split(&[panel, directional], pos2(10.0, 10.0), wheel(12.0, -3.0), + WheelFocus::new(None), None, &mut gesture, 0.001); + assert_eq!((crossing[0].0, crossing[0].1.scroll), (1, Vec2::new(12.0, -3.0))); + } } diff --git a/crates/behavior/tests/codec_override.rs b/crates/behavior/tests/codec_override.rs new file mode 100644 index 0000000000..dc809c7f41 --- /dev/null +++ b/crates/behavior/tests/codec_override.rs @@ -0,0 +1,67 @@ +//! An opt-in primary numeric grammar never falls through to expression, relative or fallback parsing. + +use craft_behavior::{Codec, NotAValue, NumberCodec, ParseNote, Reader}; + +fn absolute(text: &str) -> Option { + text.parse().ok() +} + +#[test] +fn codec_override_reads_complete_trimmed_values_absolutely() { + let codec = NumberCodec::default().parse_with(|text| { + assert_eq!(text, text.trim()); + absolute(text) + }); + assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(12.0))); + assert_eq!(codec.parse("-12", &Some(50.0)), Ok(Some(-12.0))); + assert_eq!(codec.parse(" ", &Some(50.0)), Ok(None), "the existing empty-value convention stays intact"); + assert_eq!(codec.parse_tagged("12", &Some(50.0)), Ok((Some(12.0), ParseNote::default()))); + for text in ["1+2", "*2", "1.2.3", "12 widgets", "1 2", "1,2.3"] { + assert_eq!(codec.parse(text, &Some(50.0)), Err(NotAValue), "reject the entire input {text:?}"); + } +} + +#[test] +fn codec_override_rejection_never_falls_through_to_other_readers() { + let codec = NumberCodec::new(Reader::new().unit("widgets", 2.0), 2) + .or_parse(|_| Some(999.0)) + .zoom_typing() + .parse_with(absolute); + for text in ["1+2", "8/4", "2 widgets", "Auto", "1.2.3"] { + assert_eq!(codec.parse(text, &Some(50.0)), Err(NotAValue), "no secondary reader may accept {text:?}"); + } + assert_eq!(codec.parse("+12", &Some(50.0)), Ok(Some(12.0))); + // Setter order does not silently replace the authoritative reader with the fallback reader. + let codec = NumberCodec::default().parse_with(absolute).or_parse(|_| Some(999.0)); + assert_eq!(codec.parse("Auto", &None), Err(NotAValue)); +} + +#[test] +fn codec_override_rejects_nonfinite_callback_results() { + let codec = NumberCodec::default().parse_with(absolute); + for text in ["NaN", "inf", "-inf", "1e9999"] { + assert_eq!(codec.parse(text, &None), Err(NotAValue), "non-finite {text:?}"); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let codec = NumberCodec::default().parse_with(move |_| Some(value)); + assert_eq!(codec.parse("anything", &None), Err(NotAValue)); + } +} + +#[test] +fn codec_override_preserves_formatting_filter_equality_and_all_default_grammars() { + let original = NumberCodec::new(Reader::new().decimal(','), 2).fixed().zoom_typing(); + let custom = original.clone().parse_with(absolute); + assert_eq!(original.format(&Some(12.5)), custom.format(&Some(12.5))); + assert_eq!(custom.format(&Some(12.5)), "12,50"); + for c in ['1', ',', '/', '+', '-', '*', 'w'] { + assert_eq!(original.filter(c), custom.filter(c), "filter {c}"); + } + assert_eq!(custom, custom.clone()); + assert_ne!(original, custom); + let default = NumberCodec::default(); + assert_eq!(default.parse("+12", &Some(50.0)), Ok(Some(62.0))); + assert_eq!(default.parse("1+2", &Some(50.0)), Ok(Some(3.0))); + assert_eq!(default.clone().or_parse(|text| (text == "Auto").then_some(99.0)).parse("Auto", &None), Ok(Some(99.0))); + assert_eq!(default.zoom_typing().parse("8/4", &None), Ok(Some(200.0))); +} diff --git a/crates/behavior/tests/main.rs b/crates/behavior/tests/main.rs index 905ddbbe0f..6cb08f2b42 100644 --- a/crates/behavior/tests/main.rs +++ b/crates/behavior/tests/main.rs @@ -2,6 +2,7 @@ mod canvas_view; mod cells; +mod codec_override; mod digit_keys; mod dock; mod dock_apply; diff --git a/crates/ui-contract/src/contract/steps/sense.rs b/crates/ui-contract/src/contract/steps/sense.rs index 84fb52ff8e..b62685d339 100644 --- a/crates/ui-contract/src/contract/steps/sense.rs +++ b/crates/ui-contract/src/contract/steps/sense.rs @@ -26,6 +26,7 @@ pub(crate) fn register_wheel( scope: WheelScope, ) { let free = sensed.is_some() && scope == WheelScope::Free; + let directional = sensed.is_some() && value_control && scope == WheelScope::Directional; let zone = sensed.is_some_and(|taker| taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom)); let taker = sensed.or_else(|| value_control.then(|| craft_behavior::WheelTaker::new(id, rect).vertical(true))); if let Some(taker) = taker { @@ -34,7 +35,9 @@ pub(crate) fn register_wheel( taker .value(value_control) .field(value_control && text && sensed.is_some()) - .gated(scope == WheelScope::Gated || (value_control && !free && !zone)), + .gated(scope == WheelScope::Gated || (value_control && !free && !zone)) + .horizontal(taker.horizontal || directional) + .directional(directional), ); } } diff --git a/crates/ui-contract/src/runtime/env/overrides.rs b/crates/ui-contract/src/runtime/env/overrides.rs index 2d43b3aecd..390c03094b 100644 --- a/crates/ui-contract/src/runtime/env/overrides.rs +++ b/crates/ui-contract/src/runtime/env/overrides.rs @@ -107,6 +107,11 @@ pub enum WheelScope { /// Every taker takes the wheel only while focused or armed: a card in a scrolling overview. Wins over a `Free` set /// inside it, so a scroll of the overview never stops on a story's slider. Gated, + /// Value controls that sense the wheel edit on a dominant horizontal swipe or Shift-wheel + /// under the pointer. Vertical scrolling edits only after an explicit press and only until + /// the pointer leaves; keyboard focus survives but never rearms wheel editing. Other takers + /// are unchanged. An outer `Gated` scope still wins. + Directional, } /// Changes to the inherited values for a stretch of code. diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index 570758c0b6..b96bb712bb 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -15,6 +15,11 @@ mod input; mod intents; mod nodes; mod route; +mod scalar; + +pub use scalar::{ScalarKeyPolicy, ScalarKeyTrigger}; +#[doc(hidden)] +pub use scalar::{ScalarRow, register_scalar}; #[doc(hidden)] pub use claims::capture; @@ -28,7 +33,6 @@ pub use craft_behavior::{AccessRequest, Intent, MoveMods, NavMove, PartRef}; pub(crate) use input::{claims_press, count_sent, input_hook, keys_state, queue_nav, sent, take_menu_keys, take_nav}; #[doc(hidden)] pub use input::{down, keyed}; -pub use intents::Intents; #[doc(hidden)] pub use intents::intents_of; #[cfg(feature = "suite")] @@ -37,6 +41,7 @@ pub(crate) use intents::lent_taken; pub use intents::settle; #[doc(hidden)] pub use intents::take_submit; +pub use intents::Intents; pub(crate) use intents::{ Lent, context_part, context_request, context_requests, give_back, lend, request_context, route_whole_reset, scope_escape, take_cancel, take_every_escape, take_window_cancel, @@ -207,6 +212,8 @@ struct Item { #[derive(Clone, Default)] struct Routed { items: Vec, + /// Scalar-row moves selected by the canonical router, distinct from ordinary focused navigation. + scalar_moves: Vec<(NavMove, MoveMods)>, nudge: Option<(Vec2, Mods)>, /// The chords a recorder stop's presses spell this pass. chords: Vec, @@ -251,6 +258,8 @@ pub(crate) struct Stage { layout: Layout, nodes: HashMap, last_nodes: HashMap, + /// Opt-in real rows declared this pass; taken at the next begin, so unmounted rows cannot accumulate. + scalar_rows: Vec, activated: IdMap, alt: AltTrack, /// The keys down now, as the input hook read them before it withheld any press. diff --git a/crates/ui-contract/src/runtime/keys/intents.rs b/crates/ui-contract/src/runtime/keys/intents.rs index d6350c138b..0958f76905 100644 --- a/crates/ui-contract/src/runtime/keys/intents.rs +++ b/crates/ui-contract/src/runtime/keys/intents.rs @@ -17,6 +17,8 @@ pub struct Intents { /// read by index, so an item pushed without one has none. places: Vec>, took_arrows: Vec, + scalar_moves: Vec<((NavMove, MoveMods), bool)>, + scalar_at: usize, nudge: Option<(Vec2, Mods)>, chords: Vec, set_value: Option<(Option, f64)>, @@ -82,6 +84,15 @@ impl Intents { } } + /// Takes one scalar-row move selected by the canonical router, independently of ordinary focused navigation. + #[doc(hidden)] + pub fn take_scalar_move(&mut self) -> Option<(NavMove, MoveMods)> { + let item = self.scalar_moves.get_mut(self.scalar_at)?; + self.scalar_at += 1; + item.1 = true; + Some(item.0) + } + /// Takes the next move, whichever it is: for a component that acts on every move. A move taken is the component's, /// so the Page Up, Page Down, Home and End it takes never reach the scroll owner around it (a page view under a /// focused page part); a component that acts on some moves takes those with [`take_move_where`](Self::take_move_where) @@ -266,6 +277,8 @@ pub fn intents_of(ctx: &Context, id: Option, rtl: bool) -> Intents { items, places, took_arrows: Vec::new(), + scalar_moves: routed.scalar_moves.into_iter().map(|movement| (movement, false)).collect(), + scalar_at: 0, nudge: routed.nudge, chords: routed.chords, set_value: routed.set_value, @@ -427,6 +440,8 @@ pub fn settle(ctx: &Context, id: Option, intents: &Intents) { let Some(routed) = stage.routed.get_mut(&id) else { return }; let mut taken = intents.items.iter().map(|(_, taken)| *taken); routed.items.retain(|_| !taken.next().unwrap_or(false)); + let mut scalar_taken = intents.scalar_moves.iter().map(|(_, taken)| *taken); + routed.scalar_moves.retain(|_| !scalar_taken.next().unwrap_or(false)); if intents.nudge.is_none() { routed.nudge = None; } diff --git a/crates/ui-contract/src/runtime/keys/route.rs b/crates/ui-contract/src/runtime/keys/route.rs index 9abd1a09bf..d9bf0ce265 100644 --- a/crates/ui-contract/src/runtime/keys/route.rs +++ b/crates/ui-contract/src/runtime/keys/route.rs @@ -1,7 +1,7 @@ //! The begin hook's routing: key presses, shortcuts and AccessKit requests to the intents of their owners. use super::input::chrome_toggle_of; -use super::{Batch, Item, MenuKey, Node, Press, Routed, Shortcuts, Taken, current, with}; +use super::{Batch, Item, MenuKey, Node, Press, Routed, Shortcuts, Taken, current, scalar, with}; use crate::runtime::commands::{self, ClipContent, FirePhase}; use crate::runtime::egui::input::{Action, ActionKind}; use crate::runtime::focus::{self, StopRec}; @@ -22,7 +22,7 @@ use std::sync::Arc; pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { let os = crate::runtime::windows::os_of(ctx); let target = focus::focused_rec(ctx); - let (batch, nodes, captures, held_claims, fired_claims, hover_deletes) = current(ctx, |stage| { + let (batch, nodes, captures, held_claims, fired_claims, hover_deletes, scalar_rows) = current(ctx, |stage| { stage.routed.clear(); stage.contexts.clear(); stage.claimed.clear(); @@ -39,6 +39,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { held_claims, fired, std::mem::take(&mut stage.hover_deletes), + std::mem::take(&mut stage.scalar_rows), ) }); let modal = overlay::any_open(ctx, overlay::OpenFilter::Modal); @@ -74,6 +75,24 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { let mut routed: HashMap, Routed> = HashMap::new(); let mut activated = IdMap::default(); let mut consumed = vec![Taken::No; batch.presses.len()]; + // Interest comes from real components in last pass's draw order, never from a synthetic focus stop. + let mut scalar_owned = if scalar_rows.is_empty() { Vec::new() } else { vec![false; batch.presses.len()] }; + if let Some(row) = scalar::choose(ctx, &scalar_rows, target.as_ref(), press_captured) { + for (at, press) in batch.presses.iter().enumerate() { + let movement = match press.key { + Key::Up => NavMove::Up, + Key::Down => NavMove::Down, + _ => continue, + }; + if press.canvas || !(press.mods.is_none() || press.mods == Mods::SHIFT) || batch.claimed.contains(&Chord::new(press.mods, press.key)) { + continue; + } + let modifiers = MoveMods::new(press.mods == Mods::SHIFT, false, MoveMods::PLAIN.by); + routed.entry(Some(row.owner)).or_default().scalar_moves.push((movement, modifiers)); + scalar_owned[at] = true; + consumed[at] = Taken::Yes; + } + } let driven = target.as_ref().and_then(|rec| Driven::of(ctx, rec)); let field_list = target.as_ref().filter(|_| driven.is_none()).and_then(|rec| list_of_field(ctx, rec)); // Whether a component took each text of the pass, as typing, type-ahead or digits; and whether the framework took @@ -81,7 +100,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { let mut taken_texts = vec![false; batch.texts.len()]; let mut withdrawn_texts: Vec = batch.texts.iter().enumerate().filter(|(_, typed)| typed.claimed).map(|(at, _)| at).collect(); if let Some(rec) = &target { - for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, _)| !press.canvas) { + for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, taken)| !press.canvas && **taken == Taken::No) { *taken = if let Some(id) = hover_delete.filter(|id| Some(*id) != target.as_ref().map(|rec| rec.stop.id)) && press.mods.is_none() && matches!(press.key, Key::Delete | Key::Backspace) @@ -124,7 +143,7 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { // canvas takes is its alone, as while it has the focus: the app's shortcuts do not run with it too. It takes the // arrows with the modifiers it acts on (`KeyUse::nudge_mods`); the others are the app's. let declared = |mods: Mods| canvas.as_ref().is_none_or(|canvas| canvas.stop.keys.nudge_mods.contains(mods)); - for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, _)| !press.canvas) { + for (press, taken) in batch.presses.iter().zip(&mut consumed).filter(|(press, taken)| !press.canvas && **taken == Taken::No) { if let Some(id) = hover_delete && press.mods.is_none() && matches!(press.key, Key::Delete | Key::Backspace) @@ -163,10 +182,10 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { for command in queued { push(&mut routed, focused, Intent::Edit(command), false); } - let (shortcuts, held) = owned_shortcuts(ctx, target.as_ref(), &batch, &consumed, &taken_texts); + let (shortcuts, held) = owned_shortcuts(ctx, target.as_ref(), &batch, &consumed, &taken_texts, &scalar_owned); // The app's own widget, focused or the window's canvas, reads its keys from egui. let host = target.as_ref().or(canvas.as_ref()).is_some_and(|rec| rec.stop.host); - withdraw_taken(ctx, host, &batch, &held, &withdrawn_texts); + withdraw_taken(ctx, host, &batch, &held, &withdrawn_texts, &scalar_owned); let pasted = batch.paste.clone().zip(focused).map(|(content, id)| (id, content)); let escapes = craft_behavior::focus::route_escapes(batch.escapes, press_captured); for _ in 0..escapes.to_components { @@ -203,9 +222,11 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting { } } for request in &batch.access { - route_access(ctx, request, &nodes, &mut routed, &mut activated); + route_access(ctx, request, &nodes, &mut routed, &mut activated, &scalar_rows, press_captured); } current(ctx, |stage| { + stage.scalar_rows = scalar_rows; + stage.scalar_rows.clear(); stage.routed = routed; stage.claimed = claimed; stage.activated = activated; @@ -280,7 +301,14 @@ pub(crate) fn focus_in_modal_dialog(ctx: &Context) -> bool { /// focus; inside a layer its `Overlay.keys` class ranks with the component's. A `Recorder` keeps every key and a `Menu` /// its navigation keys (`keeps_key`); a text field keeps the text its presses typed. `consumed` is what /// routing did with each press and `taken_texts` whether a component took each text of the pass. -fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consumed: &[Taken], taken_texts: &[bool]) -> (Shortcuts, Vec) { +fn owned_shortcuts( + ctx: &Context, + target: Option<&StopRec>, + batch: &Batch, + consumed: &[Taken], + taken_texts: &[bool], + scalar_owned: &[bool], +) -> (Shortcuts, Vec) { let scopes = target.map(|rec| focus::scope_chain(ctx, rec)).unwrap_or_default(); let owner = owner_at(ctx, target, &scopes, None); let own = target.map(|rec| rec.stop.keys.owner); @@ -292,12 +320,25 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu .iter() .zip(consumed) // The canvas's Space is never the focused stop's; a press the unfocused window's canvas took is the canvas's. - .map(|(press, taken)| { - !press.canvas - && (matches!(*taken, Taken::Canvas | Taken::Hover) - || holds_press(owner, target, press, *taken == Taken::Yes, press.text.is_some_and(|at| taken_texts[at]))) + .enumerate() + .map(|(at, (press, taken))| { + scalar_owned.get(at).copied().unwrap_or(false) + || (!press.canvas + && (matches!(*taken, Taken::Canvas | Taken::Hover) + || holds_press(owner, target, press, *taken == Taken::Yes, press.text.is_some_and(|at| taken_texts[at])))) }) .collect(); + // Only Up/Down are scalar presses. Summarize paired releases once rather than scanning all presses per shortcut. + let scalar_releases = batch.presses.iter().zip(scalar_owned).fold([false; 2], |mut held, (press, owned)| { + if *owned { + match press.release { + Some(Key::Up) => held[0] = true, + Some(Key::Down) => held[1] = true, + _ => {} + } + } + held + }); // A shortcut without a press of its own (a release, or the clipboard event that stands for ⌘C) follows the owner by // its modifiers, as its press would. let keys = batch @@ -305,7 +346,14 @@ fn owned_shortcuts(ctx: &Context, target: Option<&StopRec>, batch: &Batch, consu .iter() .filter(|shortcut| { let key = shortcut.input.typed.or(shortcut.input.physical); - !keeps_key(owner, key, shortcut.input.mods) && !shortcut.press.is_some_and(|at| held[at]) + // A release in the same batch belongs to its scalar press too; later releases are withheld by the strip. + let scalar_release = shortcut.phase == FirePhase::Release + && match key { + Some(Key::Up) => scalar_releases[0], + Some(Key::Down) => scalar_releases[1], + _ => false, + }; + !scalar_release && !keeps_key(owner, key, shortcut.input.mods) && !shortcut.press.is_some_and(|at| held[at]) }) .copied() .collect(); @@ -416,11 +464,18 @@ pub fn focus_holds(ctx: &Context, chord: Chord) -> bool { /// Takes what the framework handed to one taker out of the running pass's egui input, where the app and egui's text /// widgets read their keys: one press, one action, and one text, one reader. `held` marks the presses the focused /// component (or the unfocused window's canvas) holds; the app's own widget (`Stop::host`, `host`) reads its keys from -/// egui, so its presses stay. `texts` are the places in `Batch::texts` of the texts a claim or a framework taker took. -/// A held press whose release has not come yet leaves its release to the strip. -fn withdraw_taken(ctx: &Context, host: bool, batch: &Batch, held: &[bool], texts: &[usize]) { - let presses: Vec<&Press> = - batch.presses.iter().zip(held).filter(|(press, held)| !host && **held && press.in_egui.is_some()).map(|(press, _)| press).collect(); +/// egui, so its presses stay, except the scalar-row presses (`scalar_owned`) the framework routed. `texts` are the +/// places in `Batch::texts` of the texts a claim or a framework taker took. A held press whose release has not come yet +/// leaves its release to the strip. +fn withdraw_taken(ctx: &Context, host: bool, batch: &Batch, held: &[bool], texts: &[usize], scalar_owned: &[bool]) { + let presses: Vec<&Press> = batch + .presses + .iter() + .zip(held) + .enumerate() + .filter(|(at, (press, held))| (!host || scalar_owned.get(*at).copied().unwrap_or(false)) && **held && press.in_egui.is_some()) + .map(|(_, (press, _))| press) + .collect(); if presses.is_empty() && texts.is_empty() { return; } @@ -723,7 +778,15 @@ fn nudge_of(key: Key, mods: Mods) -> Option<(Vec2, Mods)> { } /// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2). -fn route_access(ctx: &Context, request: &Action, nodes: &HashMap, routed: &mut HashMap, Routed>, activated: &mut IdMap) { +fn route_access( + ctx: &Context, + request: &Action, + nodes: &HashMap, + routed: &mut HashMap, Routed>, + activated: &mut IdMap, + scalar_rows: &[scalar::ScalarRow], + press_captured: bool, +) { let Some(node) = nodes.get(&request.node()).copied() else { return }; let owner = Some(node.owner); // A request that only scrolls (a screen reader's Scroll Into View) shows the node and leaves focus where it is. @@ -731,6 +794,16 @@ fn route_access(ctx: &Context, request: &Action, nodes: &HashMap, rou let target = node.part.map_or(focus::FocusTarget::Id(node.owner), |part| focus::FocusTarget::Part(node.owner, part)); focus::request_now(ctx, target); } + if matches!(request.kind(), ActionKind::Increment | ActionKind::Decrement) + && (node.part.is_none() || node.focusable) + && let Some(row) = scalar_rows.iter().find(|row| node.owner == row.slider || Some(node.owner) == row.editor) + { + if !scalar::captured(ctx, press_captured) && scalar::allowed(ctx, row) { + let movement = if matches!(request.kind(), ActionKind::Increment) { NavMove::Forward } else { NavMove::Back }; + routed.entry(Some(row.owner)).or_default().scalar_moves.push((movement, MoveMods::PLAIN)); + } + return; + } match request.kind() { ActionKind::Focus if node.focusable => {} ActionKind::Expand | ActionKind::Collapse if node.expanded.is_some() => { diff --git a/crates/ui-contract/src/runtime/keys/scalar.rs b/crates/ui-contract/src/runtime/keys/scalar.rs new file mode 100644 index 0000000000..d0c6e16291 --- /dev/null +++ b/crates/ui-contract/src/runtime/keys/scalar.rs @@ -0,0 +1,183 @@ +//! Optional scalar-row key interest. Geometry and real stops come from the ordinary component pass. + +use super::{current, route}; +use crate::runtime::egui::areas; +use crate::runtime::focus::{self, StopRec}; +use crate::runtime::pointer; +use craft_behavior::{KeyOwner, MoveMods, NavMove, OwnerClass}; +use egui::{Context, Id, LayerId, Rect}; + +/// Which real scalar row can take a vertical arrow, without moving keyboard focus. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum ScalarKeyTrigger { + /// Only the row whose slider has keyboard focus. + #[default] + Focused, + /// The first drawn eligible row: its slider has focus, or its clipped whole row is hovered. + HoveredOrFocused, +} + +/// Opt-in additive model-unit vertical-key and accessibility nudges. +/// +/// Pointer, typed-value and wheel quantization keep their original steps. The widget snaps the result of the +/// addition to its original value grid, not a new grid based on `nudge`. A policy is optional: omitting it keeps +/// the existing slider behavior. Non-positive or non-finite amounts make the policy inactive. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScalarKeyPolicy { + nudge: f64, + shift_factor: f64, + trigger: ScalarKeyTrigger, + model_step: Option, +} + +impl ScalarKeyPolicy { + /// A focused-row policy, with Shift multiplying the additive nudge by five. + pub const fn new(nudge: f64) -> Self { + Self { nudge, shift_factor: 5.0, trigger: ScalarKeyTrigger::Focused, model_step: None } + } + + /// Chooses whether whole-row hover also makes a row eligible. This never changes focus. + pub const fn trigger(mut self, trigger: ScalarKeyTrigger) -> Self { + self.trigger = trigger; + self + } + + /// Sets the multiplier used by Shift. This does not change any global or wheel step multiplier. + pub const fn shift_factor(mut self, factor: f64) -> Self { + self.shift_factor = factor; + self + } + + /// Selects an explicit zero-origin model grid for scalar keys and accessibility actions only. + /// The final value is rounded to a multiple of `step`, then clamped to the slider bounds, before any edit event. + /// This does not change the additive nudge or pointer, wheel, horizontal-key, or numeric-editor quantization. + /// By default no model grid is selected: the original track grid and its on-grid bit preservation stay unchanged. + /// Non-positive or non-finite steps make this optional scalar policy inactive. + pub const fn model_step(mut self, step: f64) -> Self { + self.model_step = Some(step); + self + } + + /// The optional model grid used by the SDK component's scalar landing, not its input routing or other paths. + #[doc(hidden)] + pub const fn model_quantum(self) -> Option { + self.model_step + } + + /// Whether the amounts and any selected model step describe usable, finite positive changes. + pub fn is_valid(self) -> bool { + self.nudge.is_finite() + && self.nudge > 0.0 + && self.shift_factor.is_finite() + && self.shift_factor > 0.0 + && (self.nudge * self.shift_factor).is_finite() + && self.nudge * self.shift_factor > 0.0 + && self.model_step.is_none_or(|step| step.is_finite() && step > 0.0) + } + + /// The unmodified model-unit accessibility increment. + pub fn amount(self) -> Option { + self.is_valid().then_some(self.nudge) + } + + /// An additive offset for vertical keys or accessibility increment/decrement (Forward/Back). + pub fn offset(self, movement: NavMove, modifiers: MoveMods) -> Option { + let direction = match movement { + NavMove::Up | NavMove::Forward => 1.0, + NavMove::Down | NavMove::Back => -1.0, + _ => return None, + }; + self.amount().map(|amount| direction * amount * if modifiers.extend { self.shift_factor } else { 1.0 }) + } +} + +/// SDK component metadata for one real scalar row. It creates no widget or focus stop. +#[doc(hidden)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScalarRow { + pub(super) owner: Id, + pub(super) slider: Id, + pub(super) editor: Option, + rect: Rect, + layer: LayerId, + policy: ScalarKeyPolicy, +} + +impl crate::runtime::Shift for ScalarRow { + fn shifted(&self, by: &egui::RecordShift) -> Self { + ScalarRow { rect: by.rect(self.rect), ..*self } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + ScalarRow { rect: self.rect.snapped(&to.rect, within), ..*self } + } +} + +impl ScalarRow { + /// Uses the component's clipped allocated rect and the actual slider stop's owner. + pub fn new(owner: Id, slider: Id, policy: ScalarKeyPolicy, rect: Rect, layer: LayerId) -> Self { + Self { owner, slider, editor: None, rect, layer, policy } + } + + /// Associates the real numeric child for accessibility increment/decrement; focused typing keeps its keys. + pub fn editor(mut self, editor: Id) -> Self { + self.editor = Some(editor); + self + } +} + +/// Records opt-in interest in component draw order, exactly like the ordinary stop/node records. +#[doc(hidden)] +pub fn register_scalar(ctx: &Context, row: ScalarRow) { + if crate::runtime::measure::active(ctx) || !row.policy.is_valid() || !row.rect.is_positive() { + return; + } + crate::runtime::replay::journal(ctx, || row, |ctx, row| register_scalar(ctx, *row)); + current(ctx, |stage| stage.scalar_rows.push(row)); +} + +/// A captured gesture wins even over a different row; no raw pointer/key path bypasses that ownership. +pub(super) fn captured(ctx: &Context, press_captured: bool) -> bool { + press_captured || pointer::with_pass_pointer(ctx, |pointer| pointer.primary_down) +} + +/// Only rows whose real stop is allowed by the canonical popup/modal owner can act. +pub(super) fn allowed(ctx: &Context, row: &ScalarRow) -> bool { + focus::stop_rec(ctx, (row.slider, None)).is_some_and(|record| { + matches!( + route::owner_at(ctx, Some(&record), &focus::scope_chain(ctx, &record), None), + KeyOwner::Class(OwnerClass::Widget | OwnerClass::Dialog) + ) + }) +} + +/// Source order, not focus-first or hover-first, resolves conflicting eligible rows. +pub(super) fn choose(ctx: &Context, rows: &[ScalarRow], focused: Option<&StopRec>, press_captured: bool) -> Option { + if rows.is_empty() || captured(ctx, press_captured) + // A real native editor/widget without a framework stop still owns its focused editing keys. + || (focused.is_none() && crate::runtime::egui::focus::focused(ctx).is_some()) + || focused.is_some_and(|record| { + record.stop.text || !matches!(route::owner_at(ctx, Some(record), &focus::scope_chain(ctx, record), None), + KeyOwner::Class(OwnerClass::Widget | OwnerClass::Dialog | OwnerClass::App)) + || crate::runtime::ime::composing(ctx, record.stop.root) + }) + { + return None; + } + let pointer = pointer::with_pass_pointer(ctx, |pointer| pointer.hover); + rows.iter() + .find(|row| { + let focused = focused.is_some_and(|record| record.stop.id == row.slider || record.stop.root == row.slider); + let hovered = row.policy.trigger == ScalarKeyTrigger::HoveredOrFocused + && pointer.is_some_and(|point| { + let local = areas::layer_map(ctx, row.layer).map_or(point, |map| map.to_layer(point)); + row.rect.contains(local) + && pointer::with_hover(ctx, crate::runtime::egui::pass::current_viewport(ctx), |under, _| { + under.is_some_and(|under| under.contains(row.owner)) + }) + }); + (focused || hovered) && allowed(ctx, row) + }) + .copied() +} diff --git a/crates/ui-widgets/src/form/slider_field.rs b/crates/ui-widgets/src/form/slider_field.rs index 017690f342..598ce1b7f7 100644 --- a/crates/ui-widgets/src/form/slider_field.rs +++ b/crates/ui-widgets/src/form/slider_field.rs @@ -4,14 +4,15 @@ pub(crate) mod stories; use crate::contract::{ - Bind, BindCheck, BindMut, Common, Component, Cx, Edit as _, EditResponse, FieldLayout, MeasureCx, Outcome, PaintUi, Props as _, Role, SideLabel, + Bind, BindCheck, BindMut, Common, Component, Cx, Edit as _, EditResponse, FieldLayout, Focus as _, MeasureCx, Outcome, PaintUi, Props as _, Role, SideLabel, Sizing, Validity, WordSetCx as _, }; use crate::runtime::env::{Label, UnitKind}; +use crate::runtime::keys::{ScalarKeyPolicy, ScalarRow, register_scalar}; use crate::style::{ComponentStyle, StyleCx}; use crate::text::{NumberField, RangeAlert}; use crate::value_drag::{Slider, SliderScale, SliderThumb, TrackFace}; -use craft_behavior::{Flow, Metrics, Mixed, Proposal, Sense, decimals_for_step}; +use craft_behavior::{Flow, Metrics, Mixed, NumberCodec, Proposal, Sense, decimals_for_step}; use egui::{Rect, Response, Vec2, pos2}; use std::ops::{Deref, RangeInclusive}; @@ -53,8 +54,8 @@ 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 -/// slider's track only: the field, typing and steps stay linear. +/// then the slider are Tab stops. A log, power or custom scale curves the slider's track only: the field and typing +/// stay in model units, as do explicitly set steps. #[derive(crate::contract::Component, crate::contract::Props)] pub struct SliderField<'a> { #[common] @@ -68,6 +69,10 @@ pub struct SliderField<'a> { /// How positions along the slider's track map to values. #[prop] scale: SliderScale, + /// The number field's codec. Without one it reads and writes using the environment's locale and unit kind. + /// Range limits, typed-value snapping and model-unit steps still belong to this slider field. + #[prop] + number_codec: Option, /// The change of one arrow press, wheel notch or label scrub point, and by default the grid typed values snap to. #[prop(quantity = "step")] step: Option, @@ -77,6 +82,17 @@ pub struct SliderField<'a> { /// The change of one wheel notch over the slider where it is coarser than the step. #[prop(quantity = "step")] wheel_step: Option, + /// Optional independent vertical-key and accessibility nudges for the full clipped row, including its caption. + /// Its focused numeric child keeps the normal editor precedence and its original typing/wheel properties. + #[prop] + key_policy: Option, + /// Pointer sensitivity bindings forwarded to the real slider and numeric/label scrub; not key/wheel policy. + #[prop] + pointer_modifiers: craft_behavior::DragModifiers, + /// Optional zero-origin model grid for this field's real slider pointer values, not its numeric/label editor. + /// None preserves original pointer snapping. Keys, wheel and accessibility keep their independent policies. + #[prop] + pointer_model_step: Option, /// What the number counts: the field shows its unit and reads its spellings. #[prop] unit_kind: Option, @@ -146,9 +162,13 @@ impl<'a> SliderField<'a> { range, layout: SliderFieldLayout::Stacked, scale: SliderScale::Linear, + number_codec: None, step: None, typed_decimals: None, wheel_step: None, + key_policy: None, + pointer_modifiers: craft_behavior::DragModifiers::default(), + pointer_model_step: None, unit_kind: None, unit: None, fill: true, @@ -167,9 +187,13 @@ impl<'a> SliderField<'a> { Look { range: self.range.clone(), scale: self.scale, + number_codec: self.number_codec.clone(), step: self.step, typed_decimals: self.typed_decimals, wheel_step: self.wheel_step, + key_policy: self.key_policy, + pointer_modifiers: self.pointer_modifiers, + pointer_model_step: self.pointer_model_step, unit_kind: self.unit_kind, unit: self.unit.clone(), fill: self.fill, @@ -185,9 +209,13 @@ impl<'a> SliderField<'a> { struct Look { range: RangeInclusive, scale: SliderScale, + number_codec: Option, step: Option, typed_decimals: Option, wheel_step: Option, + key_policy: Option, + pointer_modifiers: craft_behavior::DragModifiers, + pointer_model_step: Option, unit_kind: Option, unit: Option