Skip to main content

zaxis/components/
field.rs

1//! Field validation state and the compact `Field` layout: label, control, message.
2//!
3//! The library validates nothing and stores no rules. The application computes a
4//! [`Validation`] every pass and hands it to a [`Field`] (or marks one control
5//! with `.status(..)`); a changing message never requests frames by itself.
6
7use std::{fmt::Display, hash::Hash};
8
9use super::{SemanticStatus, Text, TypographyRole, Ui};
10use crate::{AccessLive, AccessNode, AccessRole, Color, Id, Vec2};
11
12/// Outcome of the application's validation of one value: a status and the text
13/// to show under the control. The default is "nothing to say".
14#[derive(Clone, Debug, Default, PartialEq)]
15pub struct Validation {
16    pub status: SemanticStatus,
17    pub message: String,
18}
19
20impl Validation {
21    /// No status and no message.
22    pub const fn ok() -> Self {
23        Self {
24            status: SemanticStatus::Normal,
25            message: String::new(),
26        }
27    }
28    pub fn error(message: impl Into<String>) -> Self {
29        Self::with(SemanticStatus::Error, message)
30    }
31    pub fn warning(message: impl Into<String>) -> Self {
32        Self::with(SemanticStatus::Warning, message)
33    }
34    pub fn success(message: impl Into<String>) -> Self {
35        Self::with(SemanticStatus::Success, message)
36    }
37    pub fn with(status: SemanticStatus, message: impl Into<String>) -> Self {
38        Self {
39            status,
40            message: message.into(),
41        }
42    }
43}
44
45/// A status without a message.
46impl From<SemanticStatus> for Validation {
47    fn from(status: SemanticStatus) -> Self {
48        Self::with(status, String::new())
49    }
50}
51
52/// `Err` becomes an error carrying the error's text; `Ok` is [`Validation::ok`].
53impl<T, E: Display> From<&Result<T, E>> for Validation {
54    fn from(result: &Result<T, E>) -> Self {
55        match result {
56            Ok(_) => Self::ok(),
57            Err(error) => Self::error(error.to_string()),
58        }
59    }
60}
61
62/// A label, one or more controls, and a hint or validation message below them.
63///
64/// Every field-like control inside (text edit, numbers, combo box, checkbox,
65/// switch, slider) takes the field's status unless it sets its own. The message
66/// line exists only while there is something to say, so it adds its height and
67/// nothing more to the layout; [`Field::reserve_message`] keeps the line instead.
68pub struct Field {
69    label: String,
70    hint: String,
71    validation: Validation,
72    id: Option<Id>,
73    reserve: bool,
74}
75
76impl Field {
77    pub fn new(label: impl Into<String>) -> Self {
78        Self {
79            label: label.into(),
80            hint: String::new(),
81            validation: Validation::ok(),
82            id: None,
83            reserve: false,
84        }
85    }
86    pub fn id_source(mut self, source: impl Hash) -> Self {
87        self.id = Some(Id::new(source));
88        self
89    }
90    /// Shown while the validation has no message.
91    pub fn hint(mut self, text: impl Into<String>) -> Self {
92        self.hint = text.into();
93        self
94    }
95    /// The result of the application's own check for this pass.
96    pub fn validation(mut self, validation: impl Into<Validation>) -> Self {
97        self.validation = validation.into();
98        self
99    }
100    /// Always keep one line free under the control, so a message appearing or
101    /// disappearing moves nothing.
102    pub fn reserve_message(mut self, reserve: bool) -> Self {
103        self.reserve = reserve;
104        self
105    }
106
107    pub fn show<R>(self, ui: &mut Ui<'_>, build: impl FnOnce(&mut Ui<'_>) -> R) -> R {
108        let id = self.id.unwrap_or_else(|| Id::new(&self.label));
109        let style = ui.style().clone();
110        let gap = (style.spacing * 0.5).max(0.0);
111        let message = if self.validation.message.is_empty() {
112            self.hint.as_str()
113        } else {
114            self.validation.message.as_str()
115        };
116        let color = status_text(
117            &style,
118            self.validation.status,
119            !self.validation.message.is_empty(),
120        );
121        let status = self.validation.status;
122        ui.vertical(|ui| {
123            // The layout spacing is the gap between label, control and message.
124            ui.layout.spacing = gap;
125            ui.push_id(("field", id), |ui| {
126                // Where this pass's nodes of the label, the controls and the message begin.
127                let mut nodes = [None; 3];
128                if !self.label.is_empty() {
129                    nodes[0] = Some(ui.context.a11y_len());
130                    ui.add(
131                        Text::new(self.label.clone())
132                            .typography(TypographyRole::Small)
133                            .color(style.text_color),
134                    );
135                }
136                let previous = std::mem::replace(&mut ui.context.field_status, status);
137                nodes[1] = Some(ui.context.a11y_len());
138                let result = build(ui);
139                ui.context.field_status = previous;
140                if !message.is_empty() {
141                    nodes[2] = Some(ui.context.a11y_len());
142                    ui.add(
143                        Text::new(message.to_owned())
144                            .typography(TypographyRole::Small)
145                            .color(color),
146                    );
147                } else if self.reserve {
148                    let line = ui
149                        .context
150                        .measure_text(
151                            "Ag",
152                            style.typography.small,
153                            style.typography.weights.small,
154                            f32::INFINITY,
155                        )
156                        .y;
157                    ui.allocate_space(Vec2::new(0.0, line));
158                }
159                if ui.context.a11y_on() {
160                    let validated = !self.validation.message.is_empty();
161                    describe(ui, nodes, message, status, validated);
162                }
163                result
164            })
165        })
166    }
167}
168
169/// Roles a field's label names: the first node of one of them built inside the field is
170/// its control.
171fn is_control(role: AccessRole) -> bool {
172    matches!(
173        role,
174        AccessRole::Button
175            | AccessRole::CheckBox
176            | AccessRole::Switch
177            | AccessRole::RadioGroup
178            | AccessRole::RadioButton
179            | AccessRole::Slider
180            | AccessRole::SpinButton
181            | AccessRole::TextInput
182            | AccessRole::MultilineTextInput
183            | AccessRole::ComboBox
184            | AccessRole::ListBox
185            | AccessRole::ColorWell
186            | AccessRole::Tree
187            | AccessRole::Table
188            | AccessRole::Grid
189    )
190}
191
192/// Tie the field together for assistive technology: its first control is named by the label
193/// and described by the message, which is the control's error when the status says so. A
194/// validation message is a live region, so it is spoken when it appears or changes.
195fn describe(
196    ui: &mut Ui<'_>,
197    [label, controls, text]: [Option<usize>; 3],
198    message: &str,
199    status: SemanticStatus,
200    validated: bool,
201) {
202    let mut id_of = |index: Option<usize>| Some(ui.context.a11y_node_mut(index?)?.id);
203    let (label, message_id) = (id_of(label), id_of(text));
204    let error = status == SemanticStatus::Error;
205    if let Some(node) = text.and_then(|index| ui.context.a11y_node_mut(index)) {
206        if validated {
207            node.live(if error {
208                AccessLive::Assertive
209            } else {
210                AccessLive::Polite
211            });
212        }
213    }
214    let control = controls.and_then(|start| ui.context.a11y_find(start, |n| is_control(n.role)));
215    let Some(control) = control else {
216        return;
217    };
218    let id = control.id;
219    if let Some(label) = label {
220        control.labelled_by(label);
221    }
222    if error {
223        control.invalid(true);
224    }
225    if let Some(text) = message_id {
226        control.described_by(text);
227        if error && validated {
228            control.error_message(text);
229        }
230        // Not every platform follows the relation; all of them speak a description.
231        if control.description.is_none() {
232            control.description(message);
233        }
234    }
235    // A part named after its control (the text field of a number input) is not named
236    // through the control's own relation: it takes the label as well.
237    let Some(label) = label else {
238        return;
239    };
240    for index in controls.unwrap_or(0)..ui.context.a11y_len() {
241        let named = |node: &&mut AccessNode| {
242            let more = node.more.as_ref();
243            more.is_some_and(|more| more.labelled_by.contains(&id))
244        };
245        if let Some(node) = ui.context.a11y_node_mut(index).filter(named) {
246            node.labelled_by(label);
247        }
248    }
249}
250
251/// Hints are muted; a status message takes its status color.
252fn status_text(style: &crate::Style, status: SemanticStatus, has_message: bool) -> Color {
253    match status {
254        _ if !has_message => style.muted_text,
255        SemanticStatus::Normal => style.muted_text,
256        SemanticStatus::Success => style.success,
257        SemanticStatus::Warning => style.warning,
258        SemanticStatus::Error => style.error,
259    }
260}