Skip to main content

icedwright_types/
state.rs

1//! Node states as trees, YAML, selector strings and the wire name them.
2//!
3//! [`StateName`] lists every state a semantic node can carry, printed with the names the YAML
4//! writer and the selector grammar share. [`StateValue`] is what an annotation or a selector
5//! says about one, and [`Checked`] is the tri-state value of a checkable role.
6
7use core::fmt;
8use core::str::FromStr;
9
10use crate::suggest;
11
12macro_rules! state_names {
13    ($($(#[doc = $doc:literal])+ $variant:ident => $name:literal,)+) => {
14        /// A state a semantic node can carry.
15        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
16        #[non_exhaustive]
17        pub enum StateName {
18            $($(#[doc = $doc])+ $variant,)+
19        }
20
21        impl StateName {
22            /// Every state, in the order the YAML writer and the selector printer use.
23            pub const ALL: &'static [StateName] = &[$(StateName::$variant),+];
24
25            /// The name written in YAML and selector strings.
26            #[must_use]
27            pub const fn name(self) -> &'static str {
28                match self {
29                    $(StateName::$variant => $name,)+
30                }
31            }
32        }
33    };
34}
35
36state_names! {
37    /// The node takes no input.
38    Disabled => "disabled",
39    /// The node shows a value that cannot be changed.
40    Readonly => "readonly",
41    /// Checked, unchecked or mixed.
42    Checked => "checked",
43    /// A toggle button is pressed.
44    Pressed => "pressed",
45    /// The node's content or popup is shown.
46    Expanded => "expanded",
47    /// An item is selected in its container.
48    Selected => "selected",
49    /// The node has keyboard focus.
50    Focused => "focused",
51    /// The current item in a set, such as the open page in a sidebar.
52    Current => "current",
53    /// The node is loading or updating.
54    Busy => "busy",
55    /// A form control must be filled in.
56    Required => "required",
57    /// A form control's value is rejected.
58    Invalid => "invalid",
59    /// A text box takes more than one line.
60    Multiline => "multiline",
61    /// A container allows more than one selected item.
62    Multiselectable => "multiselectable",
63    /// Everything outside the node is inert while it is shown.
64    Modal => "modal",
65    /// The node can take keyboard focus.
66    Focusable => "focusable",
67    /// The node is not shown.
68    Hidden => "hidden",
69    /// The node has size but is clipped out of view.
70    Offscreen => "offscreen",
71    /// The node is outside the topmost modal.
72    Inert => "inert",
73}
74
75impl fmt::Display for StateName {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.write_str(self.name())
78    }
79}
80
81/// A string that names no state.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct ParseStateError {
84    name: String,
85    suggestions: Vec<&'static str>,
86}
87
88impl ParseStateError {
89    /// The name that was not recognised.
90    #[must_use]
91    pub fn name(&self) -> &str {
92        &self.name
93    }
94
95    /// The nearest state names, nearest first.
96    #[must_use]
97    pub fn suggestions(&self) -> &[&'static str] {
98        &self.suggestions
99    }
100}
101
102impl fmt::Display for ParseStateError {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        write!(
105            f,
106            "unknown state `{}`{}",
107            self.name,
108            suggest::did_you_mean(&self.suggestions)
109        )
110    }
111}
112
113impl std::error::Error for ParseStateError {}
114
115impl FromStr for StateName {
116    type Err = ParseStateError;
117
118    fn from_str(name: &str) -> Result<Self, ParseStateError> {
119        if let Some(state) = StateName::ALL.iter().copied().find(|s| s.name() == name) {
120            return Ok(state);
121        }
122        Err(ParseStateError {
123            name: name.to_owned(),
124            suggestions: suggest::nearest(name, StateName::ALL.iter().map(|s| s.name())),
125        })
126    }
127}
128
129/// The checked state of a checkable role.
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
131pub enum Checked {
132    /// Checked.
133    True,
134    /// Not checked.
135    #[default]
136    False,
137    /// Partly checked, such as a parent whose children disagree.
138    Mixed,
139}
140
141impl From<bool> for Checked {
142    fn from(on: bool) -> Self {
143        if on { Checked::True } else { Checked::False }
144    }
145}
146
147impl fmt::Display for Checked {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        StateValue::from(*self).fmt(f)
150    }
151}
152
153/// What a source or a selector says about one state.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
155pub enum StateValue {
156    /// On or off.
157    Bool(bool),
158    /// Partly on, for [`StateName::Checked`] only.
159    Mixed,
160}
161
162impl StateValue {
163    /// The value as a [`Checked`].
164    #[must_use]
165    pub const fn as_checked(self) -> Checked {
166        match self {
167            StateValue::Bool(true) => Checked::True,
168            StateValue::Bool(false) => Checked::False,
169            StateValue::Mixed => Checked::Mixed,
170        }
171    }
172
173    /// The value as a flag, or `None` for [`StateValue::Mixed`].
174    #[must_use]
175    pub const fn as_bool(self) -> Option<bool> {
176        match self {
177            StateValue::Bool(on) => Some(on),
178            StateValue::Mixed => None,
179        }
180    }
181}
182
183impl From<bool> for StateValue {
184    fn from(on: bool) -> Self {
185        StateValue::Bool(on)
186    }
187}
188
189impl From<Checked> for StateValue {
190    fn from(checked: Checked) -> Self {
191        match checked {
192            Checked::True => StateValue::Bool(true),
193            Checked::False => StateValue::Bool(false),
194            Checked::Mixed => StateValue::Mixed,
195        }
196    }
197}
198
199impl fmt::Display for StateValue {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        f.write_str(match self {
202            StateValue::Bool(true) => "true",
203            StateValue::Bool(false) => "false",
204            StateValue::Mixed => "mixed",
205        })
206    }
207}
208
209/// A string that is not `true`, `false` or `mixed`.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct ParseStateValueError(String);
212
213impl fmt::Display for ParseStateValueError {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        write!(
216            f,
217            "unknown state value `{}`; expected `true`, `false` or `mixed`",
218            self.0
219        )
220    }
221}
222
223impl std::error::Error for ParseStateValueError {}
224
225impl FromStr for StateValue {
226    type Err = ParseStateValueError;
227
228    fn from_str(text: &str) -> Result<Self, ParseStateValueError> {
229        match text {
230            "true" => Ok(StateValue::Bool(true)),
231            "false" => Ok(StateValue::Bool(false)),
232            "mixed" => Ok(StateValue::Mixed),
233            other => Err(ParseStateValueError(other.to_owned())),
234        }
235    }
236}
237
238/// The kind of mouse cursor a widget was handed for its last mouse event this frame.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
241#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
242pub enum CursorSeen {
243    /// The cursor was available at a position.
244    Available,
245    /// The cursor was levitating under a higher `stack` layer.
246    Levitating,
247    /// The cursor was unavailable, under an overlay.
248    Unavailable,
249}
250
251#[cfg(feature = "serde")]
252mod serde_impls {
253    use super::{Checked, StateName, StateValue};
254
255    macro_rules! by_display {
256        ($ty:ty, $what:literal) => {
257            impl serde::Serialize for $ty {
258                fn serialize<S: serde::Serializer>(
259                    &self,
260                    serializer: S,
261                ) -> Result<S::Ok, S::Error> {
262                    serializer.collect_str(self)
263                }
264            }
265
266            impl<'de> serde::Deserialize<'de> for $ty {
267                fn deserialize<D: serde::Deserializer<'de>>(
268                    deserializer: D,
269                ) -> Result<Self, D::Error> {
270                    let text = <::std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
271                    text.parse::<$ty>().map_err(|_| {
272                        serde::de::Error::invalid_value(serde::de::Unexpected::Str(&text), &$what)
273                    })
274                }
275            }
276        };
277    }
278
279    by_display!(StateName, "a state name");
280    by_display!(StateValue, "`true`, `false` or `mixed`");
281
282    impl serde::Serialize for Checked {
283        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
284            StateValue::from(*self).serialize(serializer)
285        }
286    }
287
288    impl<'de> serde::Deserialize<'de> for Checked {
289        fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
290            StateValue::deserialize(deserializer).map(StateValue::as_checked)
291        }
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn state_names_round_trip_and_are_unique() {
301        for (i, state) in StateName::ALL.iter().enumerate() {
302            assert_eq!(state.name().parse::<StateName>(), Ok(*state));
303            for other in &StateName::ALL[i + 1..] {
304                assert_ne!(state.name(), other.name());
305            }
306        }
307    }
308
309    #[test]
310    fn unknown_state_suggests_the_nearest() {
311        let error = "expandd".parse::<StateName>().err();
312        assert_eq!(
313            error.map(|e| e.to_string()),
314            Some("unknown state `expandd`; did you mean `expanded`?".to_owned())
315        );
316    }
317
318    #[test]
319    fn values_round_trip_and_convert() {
320        for value in [
321            StateValue::Bool(true),
322            StateValue::Bool(false),
323            StateValue::Mixed,
324        ] {
325            assert_eq!(value.to_string().parse::<StateValue>(), Ok(value));
326            assert_eq!(StateValue::from(value.as_checked()), value);
327        }
328        assert_eq!(Checked::from(true), Checked::True);
329        assert_eq!(StateValue::Mixed.as_bool(), None);
330        assert!("yes".parse::<StateValue>().is_err());
331    }
332
333    #[cfg(feature = "serde")]
334    #[test]
335    fn serde_uses_the_names() -> Result<(), serde_json::Error> {
336        assert_eq!(serde_json::to_string(&StateName::Expanded)?, "\"expanded\"");
337        assert_eq!(serde_json::to_string(&Checked::Mixed)?, "\"mixed\"");
338        assert_eq!(
339            serde_json::from_str::<StateValue>("\"false\"")?,
340            StateValue::Bool(false)
341        );
342        assert_eq!(
343            serde_json::to_string(&CursorSeen::Levitating)?,
344            "\"levitating\""
345        );
346        assert!(serde_json::from_str::<StateName>("\"nope\"").is_err());
347        Ok(())
348    }
349}