Skip to main content

egui_pop_model/
field.rs

1//! A field's state, one model for every input (text fields, numbers,
2//! paths, sliders): whether it is modified, required, invalid, disabled
3//! (and why), read-only or pending.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! The state is data: a widget draws it (an edge, a marker and an icon
9//! per state, never colour alone), gives it to assistive technologies and
10//! reports it to agents. Which states a field has comes from the
11//! application (validation, what the field depends on); [`FieldState`]
12//! only says how they combine.
13//!
14//! ```
15//! use egui_pop_model::field::{Baseline, FieldState, Mark};
16//!
17//! let state = FieldState::new()
18//!     .required()
19//!     .modified(Baseline::Default)
20//!     .invalid("Give a name");
21//! assert!(state.is_editable());
22//! assert_eq!(state.edge(), Some(Mark::Invalid));
23//! assert_eq!(state.marks(), vec![Mark::Invalid, Mark::Modified, Mark::Required]);
24//!
25//! let off = FieldState::new().disabled("Needs an open image");
26//! assert!(!off.is_focusable());
27//! assert_eq!(off.disabled_reason(), Some("Needs an open image"));
28//! ```
29
30use serde::Serialize;
31
32/// What a modified field differs from.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
34#[serde(rename_all = "lowercase")]
35pub enum Baseline {
36    /// The value last saved (a document, a settings file).
37    Saved,
38    /// The value's default.
39    Default,
40}
41
42impl Baseline {
43    pub fn name(self) -> &'static str {
44        match self {
45            Baseline::Saved => "saved",
46            Baseline::Default => "default",
47        }
48    }
49}
50
51/// How a field is modified.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
53pub struct Modified {
54    /// What it differs from.
55    pub against: Baseline,
56    /// The field offers "reset to default" (only when it differs from
57    /// its default, and it is editable).
58    pub resettable: bool,
59}
60
61/// One state a field shows, for its marker and icon. The order of the
62/// variants is the order of precedence: the first state a field has
63/// gives its edge.
64#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
65#[serde(rename_all = "kebab-case")]
66pub enum Mark {
67    /// Cannot be focused nor changed, for a reason.
68    Disabled,
69    /// The value is refused, with a message.
70    Invalid,
71    /// The value is being checked (an asynchronous validation).
72    Pending,
73    /// Differs from the saved or default value.
74    Modified,
75    /// Must be given.
76    Required,
77    /// Can be focused, selected and copied, not changed.
78    ReadOnly,
79}
80
81impl Mark {
82    /// Every mark, in order of precedence.
83    pub const ALL: [Mark; 6] = [
84        Mark::Disabled,
85        Mark::Invalid,
86        Mark::Pending,
87        Mark::Modified,
88        Mark::Required,
89        Mark::ReadOnly,
90    ];
91
92    pub fn name(self) -> &'static str {
93        match self {
94            Mark::Disabled => "disabled",
95            Mark::Invalid => "invalid",
96            Mark::Pending => "pending",
97            Mark::Modified => "modified",
98            Mark::Required => "required",
99            Mark::ReadOnly => "read-only",
100        }
101    }
102}
103
104/// A field's state. The default is a plain field: editable, optional,
105/// valid, unchanged.
106#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
107pub struct FieldState {
108    /// Differs from its saved or default value.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub modified: Option<Modified>,
111    /// Must be given.
112    #[serde(skip_serializing_if = "std::ops::Not::not")]
113    pub required: bool,
114    /// Refused, and why.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub invalid: Option<String>,
117    /// Cannot be focused nor changed, and why ("Needs an open image").
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub disabled: Option<String>,
120    /// Can be focused, selected and copied, not changed.
121    #[serde(skip_serializing_if = "std::ops::Not::not")]
122    pub read_only: bool,
123    /// Being checked.
124    #[serde(skip_serializing_if = "std::ops::Not::not")]
125    pub pending: bool,
126}
127
128impl FieldState {
129    pub fn new() -> Self {
130        Self::default()
131    }
132
133    /// Modified against a baseline; resettable when the baseline is the
134    /// default.
135    pub fn modified(mut self, against: Baseline) -> Self {
136        self.modified = Some(Modified {
137            against,
138            resettable: against == Baseline::Default,
139        });
140        self
141    }
142
143    /// Modified or not, from a comparison: differs from `saved` (when
144    /// given) or else from `default`. Resettable when it differs from
145    /// the default.
146    pub fn compare<T: PartialEq>(mut self, value: &T, saved: Option<&T>, default: &T) -> Self {
147        let off_default = value != default;
148        self.modified = match saved {
149            Some(s) if value != s => Some(Modified {
150                against: Baseline::Saved,
151                resettable: off_default,
152            }),
153            Some(_) => None,
154            None => off_default.then_some(Modified {
155                against: Baseline::Default,
156                resettable: true,
157            }),
158        };
159        self
160    }
161
162    pub fn required(mut self) -> Self {
163        self.required = true;
164        self
165    }
166
167    /// Refused, with the message to show.
168    pub fn invalid(mut self, message: impl Into<String>) -> Self {
169        self.invalid = Some(message.into());
170        self
171    }
172
173    /// Refused when `message` is some (a validation's result).
174    pub fn validated(mut self, message: Option<String>) -> Self {
175        self.invalid = message;
176        self
177    }
178
179    /// Disabled, with the reason given to the user and to agents.
180    pub fn disabled(mut self, reason: impl Into<String>) -> Self {
181        self.disabled = Some(reason.into());
182        self
183    }
184
185    pub fn read_only(mut self) -> Self {
186        self.read_only = true;
187        self
188    }
189
190    pub fn pending(mut self) -> Self {
191        self.pending = true;
192        self
193    }
194
195    /// The disabled field's reason.
196    pub fn disabled_reason(&self) -> Option<&str> {
197        self.disabled.as_deref()
198    }
199
200    /// The invalid field's message.
201    pub fn message(&self) -> Option<&str> {
202        self.invalid.as_deref()
203    }
204
205    pub fn is_disabled(&self) -> bool {
206        self.disabled.is_some()
207    }
208
209    /// It takes the keyboard focus (and has a place in the Tab order):
210    /// everything but a disabled field. A read-only field does.
211    pub fn is_focusable(&self) -> bool {
212        !self.is_disabled()
213    }
214
215    /// Its value can be changed: neither disabled nor read-only.
216    pub fn is_editable(&self) -> bool {
217        !self.is_disabled() && !self.read_only
218    }
219
220    /// "Reset to default" is offered.
221    pub fn is_resettable(&self) -> bool {
222        self.is_editable() && self.modified.is_some_and(|m| m.resettable)
223    }
224
225    /// Whether the field has a mark.
226    pub fn has(&self, mark: Mark) -> bool {
227        match mark {
228            Mark::Disabled => self.is_disabled(),
229            Mark::Invalid => self.invalid.is_some(),
230            Mark::Pending => self.pending,
231            Mark::Modified => self.modified.is_some(),
232            Mark::Required => self.required,
233            Mark::ReadOnly => self.read_only,
234        }
235    }
236
237    /// The marks the field has, in order of precedence.
238    pub fn marks(&self) -> Vec<Mark> {
239        Mark::ALL.into_iter().filter(|m| self.has(*m)).collect()
240    }
241
242    /// The mark that colours the field's edge: the first in order of
243    /// precedence. A required field shows its marker beside the label,
244    /// not on the edge, and a read-only one has no edge colour: both
245    /// leave the edge to the others.
246    pub fn edge(&self) -> Option<Mark> {
247        self.marks()
248            .into_iter()
249            .find(|m| !matches!(m, Mark::Required | Mark::ReadOnly))
250    }
251
252    /// Nothing to show.
253    pub fn is_plain(&self) -> bool {
254        self.marks().is_empty()
255    }
256
257    /// The state as agents read it: every mark, the reason and the
258    /// message.
259    pub fn describe(&self) -> serde_json::Value {
260        serde_json::json!({
261            "marks": self.marks().iter().map(|m| m.name()).collect::<Vec<_>>(),
262            "focusable": self.is_focusable(),
263            "editable": self.is_editable(),
264            "resettable": self.is_resettable(),
265            "modified_against": self.modified.map(|m| m.against.name()),
266            "required": self.required,
267            "invalid": self.invalid,
268            "disabled_reason": self.disabled,
269            "read_only": self.read_only,
270            "pending": self.pending,
271        })
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[test]
280    fn a_plain_field_has_no_marks() {
281        let s = FieldState::new();
282        assert!(s.is_plain() && s.is_editable() && s.is_focusable());
283        assert_eq!(s.edge(), None);
284        assert!(!s.is_resettable());
285    }
286
287    #[test]
288    fn disabled_is_skipped_and_read_only_is_not() {
289        let d = FieldState::new().disabled("Needs an open image");
290        assert!(!d.is_focusable() && !d.is_editable());
291        assert_eq!(d.edge(), Some(Mark::Disabled));
292        let r = FieldState::new().read_only();
293        assert!(r.is_focusable() && !r.is_editable());
294        assert_eq!(r.edge(), None);
295        assert_eq!(r.marks(), vec![Mark::ReadOnly]);
296    }
297
298    #[test]
299    fn modified_compares_with_the_saved_value_first() {
300        let s = FieldState::new().compare(&3, Some(&2), &1);
301        assert_eq!(s.modified.unwrap().against, Baseline::Saved);
302        assert!(s.is_resettable(), "off its default");
303        let s = FieldState::new().compare(&1, Some(&2), &1);
304        assert_eq!(s.modified.unwrap().against, Baseline::Saved);
305        assert!(!s.is_resettable(), "already the default");
306        assert!(
307            FieldState::new()
308                .compare(&2, Some(&2), &1)
309                .modified
310                .is_none()
311        );
312        let s = FieldState::new().compare(&2, None, &1);
313        assert_eq!(s.modified.unwrap().against, Baseline::Default);
314        assert!(FieldState::new().compare(&1, None, &1).modified.is_none());
315    }
316
317    #[test]
318    fn a_read_only_field_offers_no_reset() {
319        let s = FieldState::new().modified(Baseline::Default).read_only();
320        assert!(!s.is_resettable());
321    }
322
323    #[test]
324    fn the_edge_follows_precedence() {
325        let s = FieldState::new()
326            .required()
327            .pending()
328            .modified(Baseline::Saved);
329        assert_eq!(s.edge(), Some(Mark::Pending));
330        assert_eq!(FieldState::new().required().edge(), None);
331    }
332
333    #[test]
334    fn agents_read_the_reason_and_the_message() {
335        let s = FieldState::new()
336            .disabled("Needs an open image")
337            .invalid("Too long");
338        let d = s.describe();
339        assert_eq!(d["disabled_reason"], "Needs an open image");
340        assert_eq!(d["invalid"], "Too long");
341        assert_eq!(d["marks"][0], "disabled");
342        assert_eq!(d["focusable"], false);
343    }
344}