Skip to main content

glory_render/
spinbutton.rs

1//! Numeric accessibility coordinates for an editable text spinbutton.
2//! Applications may retain an exact decimal model and put its exact text in
3//! value_text; these finite f64 fields are not the business arithmetic domain.
4use crate::{Error, KeyboardInput, RangeCommand};
5
6#[derive(Clone, Debug, PartialEq)]
7pub struct SpinValue {
8    pub min: Option<f64>,
9    pub max: Option<f64>,
10    pub value: Option<f64>,
11    pub step: f64,
12    pub page_step: f64,
13    pub value_text: Option<String>,
14    pub can_increase: bool,
15    pub can_decrease: bool,
16}
17impl RangeCommand {
18    /// Only hosts that have already identified the focused single-line Spin
19    /// input may call this branch. Text editing remains enabled on that input.
20    pub fn spin_key(has_min: bool, has_max: bool, input: KeyboardInput<'_>) -> Option<Self> {
21        if input.composing || input.control || input.meta || input.alt || input.shift {
22            return None;
23        }
24        match input.key {
25            "ArrowUp" => Some(Self::Increase),
26            "ArrowDown" => Some(Self::Decrease),
27            "PageUp" => Some(Self::PageIncrease),
28            "PageDown" => Some(Self::PageDecrease),
29            "Home" if has_min => Some(Self::Minimum),
30            "End" if has_max => Some(Self::Maximum),
31            _ => None,
32        }
33    }
34}
35impl Default for SpinValue {
36    fn default() -> Self {
37        Self {
38            min: None,
39            max: None,
40            value: None,
41            step: 1.,
42            page_step: 10.,
43            value_text: None,
44            can_increase: true,
45            can_decrease: true,
46        }
47    }
48}
49impl SpinValue {
50    pub fn validate(&self) -> Result<(), Error> {
51        if [self.min, self.max, self.value]
52            .into_iter()
53            .flatten()
54            .any(|v| !v.is_finite())
55            || !self.step.is_finite()
56            || self.step <= 0.
57            || !self.page_step.is_finite()
58            || self.page_step <= 0.
59            || self.min.zip(self.max).is_some_and(|(min, max)| min > max)
60        {
61            return Err(Error::InvalidProps(
62                "spinbutton coordinates and positive steps must be finite with ordered bounds",
63            ));
64        }
65        if self
66            .value_text
67            .as_ref()
68            .is_some_and(|v| v.len() > 1024 || v.contains('\0'))
69        {
70            return Err(Error::InvalidProps(
71                "spinbutton value text must be within 1024 bytes without NUL",
72            ));
73        }
74        Ok(())
75    }
76    pub fn validate_command(&self, command: RangeCommand) -> Result<(), Error> {
77        self.validate()?;
78        if matches!(command,RangeCommand::Set(v) if !v.is_finite()) {
79            return Err(Error::InvalidEvent("spinbutton set value must be finite"));
80        }
81        if matches!(command, RangeCommand::Minimum) && self.min.is_none()
82            || matches!(command, RangeCommand::Maximum) && self.max.is_none()
83        {
84            return Err(Error::InvalidEvent(
85                "spinbutton endpoint command requires a known bound",
86            ));
87        }
88        Ok(())
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    #[test]
96    fn empty_and_outside_values_are_distinct_and_finite_metadata_is_validated() {
97        let mut value = SpinValue::default();
98        assert!(value.validate().is_ok());
99        value.min = Some(0.);
100        value.max = Some(10.);
101        value.value = Some(20.);
102        assert!(
103            value.validate().is_ok(),
104            "outside values can remain visible with separate invalid metadata"
105        );
106        for nonfinite in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
107            value.value = Some(nonfinite);
108            assert!(value.validate().is_err())
109        }
110        value.value = None;
111        value.min = Some(11.);
112        assert!(value.validate().is_err());
113        value.min = Some(0.);
114        value.step = 0.;
115        assert!(value.validate().is_err());
116    }
117    #[test]
118    fn endpoint_commands_require_bounds_and_set_values_are_finite() {
119        let mut value = SpinValue::default();
120        assert!(value.validate_command(RangeCommand::Minimum).is_err());
121        assert!(value.validate_command(RangeCommand::Maximum).is_err());
122        assert!(value.validate_command(RangeCommand::Set(f64::NAN)).is_err());
123        value.min = Some(0.);
124        assert!(value.validate_command(RangeCommand::Minimum).is_ok());
125        value.value_text = Some("x".repeat(1025));
126        assert!(value.validate().is_err());
127    }
128    #[test]
129    fn spin_keys_allow_editable_origins_and_respect_caret_composition_and_modifier_keys() {
130        let mut input = KeyboardInput {
131            key: "ArrowUp",
132            control: false,
133            meta: false,
134            alt: false,
135            shift: false,
136            repeat: false,
137            composing: false,
138            editable: true,
139        };
140        assert_eq!(
141            RangeCommand::spin_key(false, false, input),
142            Some(RangeCommand::Increase)
143        );
144        for key in [
145            "ArrowLeft",
146            "ArrowRight",
147            "Delete",
148            "Backspace",
149            "Home",
150            "End",
151        ] {
152            input.key = key;
153            assert_eq!(RangeCommand::spin_key(false, false, input), None);
154        }
155        input.key = "Home";
156        assert_eq!(
157            RangeCommand::spin_key(true, false, input),
158            Some(RangeCommand::Minimum)
159        );
160        input.key = "End";
161        assert_eq!(
162            RangeCommand::spin_key(false, true, input),
163            Some(RangeCommand::Maximum)
164        );
165        input.key = "ArrowUp";
166        input.composing = true;
167        assert_eq!(RangeCommand::spin_key(true, true, input), None);
168        input.composing = false;
169        input.shift = true;
170        assert_eq!(RangeCommand::spin_key(true, true, input), None);
171    }
172}