mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:59:56 +01:00
ui-widgets: let a slider step through a value ladder
Keep the track's mapping and snapping when a caller supplies custom steps for the keyboard, wheel and accessibility actions. Report each available direction without advertising a fixed increment.
This commit is contained in:
1 parent
ea14416aaf
commit
cb820a84ae
5 files changed
+162
-18
No files matched your search
@@ -293,6 +293,7 @@ pub struct Access {
|
||||
pub(crate) unit: Option<String>,
|
||||
pub(crate) color: Option<Srgba>,
|
||||
pub(crate) numeric: Option<Numeric>,
|
||||
pub(crate) variable_steps: Option<(bool, bool)>,
|
||||
pub(crate) expanded: Option<bool>,
|
||||
pub(crate) has_popup: Option<PopupKind>,
|
||||
pub(crate) level: Option<usize>,
|
||||
@@ -363,6 +364,12 @@ impl Access {
|
||||
self
|
||||
}
|
||||
|
||||
/// Offers the available Increment and Decrement actions for a numeric value with no fixed step size.
|
||||
pub fn variable_steps(&mut self, increment: bool, decrement: bool) -> &mut Self {
|
||||
self.variable_steps = Some((increment, decrement));
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether a disclosure is open, when no flag says it.
|
||||
pub fn expanded(&mut self, on: bool) -> &mut Self {
|
||||
self.expanded = Some(on);
|
||||
|
||||
@@ -161,7 +161,14 @@ fn write_position(spec: &mut NodeSpec, position: Option<SetPosition>, level: Opt
|
||||
}
|
||||
|
||||
/// The actions the interaction and the numeric facts declare.
|
||||
fn declare_actions(spec: &mut NodeSpec, focusable: bool, clickable: bool, context_menu: bool, numeric: Option<&Numeric>) {
|
||||
fn declare_actions(
|
||||
spec: &mut NodeSpec,
|
||||
focusable: bool,
|
||||
clickable: bool,
|
||||
context_menu: bool,
|
||||
numeric: Option<&Numeric>,
|
||||
variable_steps: Option<(bool, bool)>,
|
||||
) {
|
||||
// A read-only value offers no action that would change it.
|
||||
let numeric = numeric.filter(|_| !spec.read_only);
|
||||
if focusable {
|
||||
@@ -173,17 +180,22 @@ fn declare_actions(spec: &mut NodeSpec, focusable: bool, clickable: bool, contex
|
||||
if context_menu {
|
||||
spec.actions.push(NodeAction::ContextMenu);
|
||||
}
|
||||
if let Some(numeric) = numeric.filter(|numeric| numeric.step.is_some()) {
|
||||
if let Some(numeric) = numeric {
|
||||
// A step that cannot move the value is not offered: no Increment at the range's end, unless the value wraps.
|
||||
let stuck = |at_end: bool| at_end && !numeric.wraps;
|
||||
if !stuck(numeric.value.is_some_and(|value| value >= *numeric.range.end())) {
|
||||
let (increment, decrement) = variable_steps.unwrap_or_else(|| {
|
||||
let has_step = numeric.step.is_some();
|
||||
(
|
||||
has_step && !stuck(numeric.value.is_some_and(|value| value >= *numeric.range.end())),
|
||||
has_step && !stuck(numeric.value.is_some_and(|value| value <= *numeric.range.start())),
|
||||
)
|
||||
});
|
||||
if increment {
|
||||
spec.actions.push(NodeAction::Increment);
|
||||
}
|
||||
if !stuck(numeric.value.is_some_and(|value| value <= *numeric.range.start())) {
|
||||
if decrement {
|
||||
spec.actions.push(NodeAction::Decrement);
|
||||
}
|
||||
}
|
||||
if numeric.is_some() {
|
||||
spec.actions.push(NodeAction::SetValue);
|
||||
}
|
||||
}
|
||||
@@ -308,7 +320,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) {
|
||||
if let Some(expanded) = expanded {
|
||||
spec.actions.push(if expanded { NodeAction::Collapse } else { NodeAction::Expand });
|
||||
}
|
||||
declare_actions(&mut spec, own.focusable, own.clickable, own.context_menu, numeric);
|
||||
declare_actions(&mut spec, own.focusable, own.clickable, own.context_menu, numeric, access.variable_steps);
|
||||
declare_scroll_actions(&mut spec, (own.scrolls.0 || access.pans.0, own.scrolls.1 || access.pans.1));
|
||||
custom_actions(&mut spec, &access.custom_actions);
|
||||
write_node(ctx, own.id, &spec);
|
||||
@@ -404,7 +416,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
|
||||
spec.sort = node.sort;
|
||||
spec.sortable = node.sortable;
|
||||
write_states(&mut spec, flags, None, decl.enabled, false);
|
||||
declare_actions(&mut spec, decl.focusable, decl.clickable, false, numeric);
|
||||
declare_actions(&mut spec, decl.focusable, decl.clickable, false, numeric, None);
|
||||
if node.steps && numeric.is_none() {
|
||||
spec.actions.extend([NodeAction::Increment, NodeAction::Decrement]);
|
||||
}
|
||||
|
||||
@@ -8,8 +8,7 @@ use std::borrow::Cow;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// The value one step from a value in a direction: the up arrow, the wheel and the Page keys of a field whose values
|
||||
/// lie on a ladder instead of a grid (`NumberField::stepper`). The direction is `1` up and `-1` down.
|
||||
/// A custom step for a number field or slider whose values lie on a ladder instead of a grid.
|
||||
pub struct NumberStepper<'a>(Box<dyn Fn(f64, i32, f64) -> f64 + 'a>);
|
||||
|
||||
impl<'a> NumberStepper<'a> {
|
||||
@@ -19,7 +18,7 @@ impl<'a> NumberStepper<'a> {
|
||||
NumberStepper(Box::new(next))
|
||||
}
|
||||
|
||||
pub(super) fn next(&self, from: f64, direction: i32, scale: f64) -> f64 {
|
||||
pub(crate) fn next(&self, from: f64, direction: i32, scale: f64) -> f64 {
|
||||
(self.0)(from, direction, scale)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ use crate::contract::{
|
||||
use crate::runtime::env::Label;
|
||||
use crate::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
|
||||
use crate::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, SurfaceStyle, TextLook, TrackLook};
|
||||
use crate::text::NumberStepper;
|
||||
use craft_behavior::intent::{MoveMods, NavMove};
|
||||
use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps, step_value};
|
||||
use craft_behavior::{Flow, HitLevel, HitPriority, Metrics, PartKey, PressPhase, Proposal, Sense, WheelPhase};
|
||||
use craft_theme::Stateful;
|
||||
use egui::{Pos2, Rect, Vec2};
|
||||
@@ -70,6 +73,13 @@ pub struct Slider<'a> {
|
||||
/// no stops.
|
||||
#[prop(quantity = "step")]
|
||||
step: Option<f64>,
|
||||
/// Where keys, accessibility actions and the wheel step from the current value. The direction is 1 or -1;
|
||||
/// the magnitude counts steps. A ladder steps in that direction without wrapping. The callback is also
|
||||
/// queried for the available accessibility actions.
|
||||
/// It takes precedence over the fixed key and wheel steps. Pointer placement, including snapping,
|
||||
/// still uses the track's scale.
|
||||
#[prop(func = "Fn(f64, i32, f64) -> f64")]
|
||||
stepper: Option<NumberStepper<'a>>,
|
||||
/// How positions along the track map to values.
|
||||
#[prop]
|
||||
scale: SliderScale,
|
||||
@@ -82,7 +92,7 @@ pub struct Slider<'a> {
|
||||
marks: Marks,
|
||||
/// The change of one wheel notch where it is coarser than the step (an offset of 0.0001 steps that wants 0.01 a
|
||||
/// notch); the step by default. Shift and Alt scale it as they scale the step. A logarithmic track with no step
|
||||
/// moves along the track and ignores it.
|
||||
/// moves along the track and ignores it. A custom stepper also overrides it.
|
||||
#[prop(quantity = "step")]
|
||||
wheel_step: Option<f64>,
|
||||
/// When a press on the track sets the value: on its release or drag (the default), or as the primary button goes
|
||||
@@ -90,8 +100,8 @@ pub struct Slider<'a> {
|
||||
#[prop]
|
||||
track_press: TrackPress,
|
||||
/// The value as the caller words it ("50 %"), in place of the slider's own value text: the number in the step's
|
||||
/// decimals, or in one decimal without a step. Assistive technology reads it, and so does a viewer that
|
||||
/// shows the value beside the slider.
|
||||
/// decimals, in one decimal without a step, or at the local step's precision with a custom stepper. Assistive
|
||||
/// technology reads it, and so does a viewer that shows the value beside the slider.
|
||||
#[prop(into)]
|
||||
value_text: Option<Label>,
|
||||
/// Paints the groove with `face`, a component shown as the look of the track (a colour gradient). The fill is not
|
||||
@@ -143,6 +153,7 @@ impl<'a> Slider<'a> {
|
||||
value,
|
||||
range,
|
||||
step: None,
|
||||
stepper: None,
|
||||
scale: SliderScale::Linear,
|
||||
fill: true,
|
||||
thumb: SliderThumb::Round,
|
||||
@@ -189,6 +200,21 @@ impl<'a> Slider<'a> {
|
||||
Scale::new(&self.range, self.step, self.scale)
|
||||
}
|
||||
|
||||
fn key_value(&self, from: Option<f64>, scale: &Scale, movement: NavMove, mods: MoveMods) -> Option<f64> {
|
||||
let Some(stepper) = self.stepper.as_ref() else {
|
||||
return scale.stepped(from.unwrap_or_else(|| scale.middle()), (scale.min, scale.max), movement, mods);
|
||||
};
|
||||
let StepResult::Set(steps) = step_value(&ladder_steps(), ValueAxes::Both, movement, mods) else {
|
||||
return None;
|
||||
};
|
||||
let next = match movement {
|
||||
NavMove::Start => Some(scale.min),
|
||||
NavMove::End => Some(scale.max),
|
||||
_ => ladder_value(stepper, scale, from, steps),
|
||||
};
|
||||
next.filter(|next| from != Some(*next))
|
||||
}
|
||||
|
||||
/// Where the track face paints: the faced groove, or a colour band under a triangle pointer.
|
||||
fn face_rect(&self, style: &SliderStyle, along: Along) -> Rect {
|
||||
match self.thumb {
|
||||
@@ -362,7 +388,7 @@ impl Component for Slider<'_> {
|
||||
if cx.in_wheel_run() {
|
||||
cx.commit();
|
||||
}
|
||||
if let Some(next) = scale.stepped(current(&*cx), bounds, mv, mods) {
|
||||
if let Some(next) = self.key_value(cx.value().copied(), &scale, mv, mods) {
|
||||
cx.set(next);
|
||||
}
|
||||
}
|
||||
@@ -374,7 +400,16 @@ impl Component for Slider<'_> {
|
||||
}
|
||||
if let Some(wheel) = wheel {
|
||||
// The end share carries no scroll: it closes the run.
|
||||
let next = if wheel.phase == WheelPhase::End { None } else { scale.wheeled(current(&*cx), bounds, &wheel, rtl, self.wheel_step) };
|
||||
let next = if wheel.phase == WheelPhase::End {
|
||||
None
|
||||
} else if let Some(stepper) = self.stepper.as_ref() {
|
||||
match craft_behavior::wheel_step(&ladder_steps(), ValueAxes::Both, &wheel, rtl) {
|
||||
StepResult::Set(steps) => ladder_value(stepper, &scale, cx.value().copied(), steps),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
scale.wheeled(current(&*cx), bounds, &wheel, rtl, self.wheel_step)
|
||||
};
|
||||
cx.wheel_run(wheel.phase, next);
|
||||
}
|
||||
}
|
||||
@@ -386,7 +421,12 @@ impl Component for Slider<'_> {
|
||||
Some(value) => Numeric::new(*value, range),
|
||||
None => Numeric::empty(range),
|
||||
};
|
||||
access.numeric(numeric.step(scale.small()));
|
||||
if let Some(stepper) = &self.stepper {
|
||||
let can_step = |steps| ladder_value(stepper, &scale, cx.value().copied(), steps).is_some();
|
||||
access.numeric(numeric).variable_steps(can_step(1.0), can_step(-1.0));
|
||||
} else {
|
||||
access.numeric(numeric.step(scale.small()));
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's words for the shown value when it gives them, else the value as the slider words it.
|
||||
@@ -399,7 +439,27 @@ impl Component for Slider<'_> {
|
||||
}
|
||||
|
||||
fn word_value(&self, value: &f64, cx: &Cx<'_, Self>) -> Option<String> {
|
||||
Some(self.track_scale().text(&cx.env.units(), *value))
|
||||
let scale = self.track_scale();
|
||||
let units = cx.env.units();
|
||||
let Some(stepper) = &self.stepper else { return Some(scale.text(&units, *value)) };
|
||||
let step = [1.0, -1.0]
|
||||
.into_iter()
|
||||
.filter_map(|steps| ladder_value(stepper, &scale, Some(*value), steps))
|
||||
.map(|next| (next - *value).abs())
|
||||
.filter(|step| step.is_finite() && *step > 0.0)
|
||||
.reduce(f64::min);
|
||||
Some(if let Some(step) = step {
|
||||
// Keep simple fractional stops even when the ladder strides by whole units.
|
||||
// A widened f32 echo does not need its tail of rounding digits.
|
||||
let current_places = craft_behavior::decimals_for_step(*value).min(7);
|
||||
let step_places = (1.0 - step.log10().floor()).max(0.0) as usize;
|
||||
let nonzero_places = if *value != 0.0 { (-value.abs().log10().floor()).max(0.0) as usize } else { 0 };
|
||||
units.number(*value, 0..=current_places.max(step_places).max(nonzero_places))
|
||||
} else {
|
||||
let decimal = value.to_string();
|
||||
let places = decimal.split_once('.').map_or(0, |(_, fraction)| fraction.len());
|
||||
cx.env.format().number(*value, places)
|
||||
})
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
@@ -453,3 +513,16 @@ impl Component for Slider<'_> {
|
||||
cx.edit_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// Read keys and the wheel in steps from zero, independently of the model's scale or snap grid.
|
||||
fn ladder_steps() -> ValueSteps {
|
||||
ValueSteps::new(0.0, f64::NEG_INFINITY, f64::INFINITY, 1.0, LARGE_STEPS)
|
||||
}
|
||||
|
||||
fn ladder_value(stepper: &NumberStepper<'_>, scale: &Scale, from: Option<f64>, steps: f64) -> Option<f64> {
|
||||
let start = scale.place(from.unwrap_or_else(|| scale.middle()));
|
||||
let direction = if steps > 0.0 { 1 } else { -1 };
|
||||
let next = stepper.next(start, direction, steps.abs()).clamp(scale.min, scale.max);
|
||||
let direction_matches = from.filter(|value| value.is_finite()).is_none_or(|value| if direction > 0 { next > value } else { next < value });
|
||||
(!next.is_nan() && direction_matches).then_some(next)
|
||||
}
|
||||
@@ -94,6 +94,59 @@ fn dragged(slide: &Slide, offset: f32, travel: f32) -> f64 {
|
||||
slide.value()
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_log_slider_steps_in_the_callers_values() {
|
||||
use craft_ui::testing::access::Declared;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
|
||||
let value = Rc::new(RefCell::new(0.01));
|
||||
let shown = value.clone();
|
||||
let events = Rc::new(RefCell::new(Vec::new()));
|
||||
let reported = events.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let slider = Slider::new(Bind::bound(&mut *shown.borrow_mut()), 0.01..=20.0)
|
||||
.label("Distance")
|
||||
.scale(SliderScale::Log)
|
||||
.stepper(|from, direction, steps| {
|
||||
let unit = if from < 0.1 || from == 0.1 && direction < 0 { 1.0 } else { 10.0 };
|
||||
let next = (from * 100.0 + f64::from(direction) * steps * unit).round() / 100.0;
|
||||
if direction > 0 { next.min(0.12).max(from) } else { next }
|
||||
})
|
||||
.show_at(ui, FIELD);
|
||||
reported.borrow_mut().extend(slider.events);
|
||||
});
|
||||
fixture.motion(MotionMode::Off).settle();
|
||||
let slider = fixture.by_label("Distance").expect("accessible slider");
|
||||
let original_text = fixture.tree().value_of(slider.node).unwrap().to_owned();
|
||||
assert_eq!(fixture.tree().numeric_of(slider.node).unwrap().step, None);
|
||||
assert!(fixture.tree().declares_key(slider.node, Declared::Increment));
|
||||
assert!(!fixture.tree().declares_key(slider.node, Declared::Decrement));
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE);
|
||||
assert_eq!(*value.borrow(), 0.02);
|
||||
assert_ne!(fixture.tree().value_of(slider.node), Some(original_text.as_str()), "a fine step changes the reported value");
|
||||
assert!(fixture.tree().declares_key(slider.node, Declared::Decrement));
|
||||
fixture.frame(vec![pointer::moved(FIELD.center())]);
|
||||
fixture.frame(vec![pointer::wheel_lines(-1.0)]);
|
||||
assert_eq!(*value.borrow(), 0.01);
|
||||
fixture.access(AccessActionKind::Increment, &slider).settle();
|
||||
assert_eq!(*value.borrow(), 0.02);
|
||||
fixture.access(AccessActionKind::Decrement, &slider).settle();
|
||||
assert_eq!(*value.borrow(), 0.01);
|
||||
fixture.key(Key::ArrowUp, Modifiers::SHIFT);
|
||||
assert_eq!(*value.borrow(), 0.11);
|
||||
fixture.key(Key::ArrowUp, Modifiers::NONE);
|
||||
assert_eq!(*value.borrow(), 0.12);
|
||||
assert!(!fixture.tree().declares_key(slider.node, Declared::Increment), "the ladder ends before the slider's range");
|
||||
events.borrow_mut().clear();
|
||||
fixture.key(Key::ArrowUp, Modifiers::NONE);
|
||||
fixture.frame(vec![pointer::wheel_lines(1.0)]);
|
||||
fixture.settle();
|
||||
assert!(events.borrow().is_empty(), "a step at the end of the ladder makes no edit");
|
||||
fixture.key(Key::End, Modifiers::NONE);
|
||||
assert_eq!(*value.borrow(), 20.0);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_grabbed_slider_thumb_moves_by_the_pointer_travel_and_a_click_on_it_changes_nothing() {
|
||||
let centred = dragged_from(0.0, 10.0);
|
||||
|
||||
Reference in new issue
Block a user