zaxis/components/
field.rs1use std::{fmt::Display, hash::Hash};
8
9use super::{SemanticStatus, Text, TypographyRole, Ui};
10use crate::{AccessLive, AccessNode, AccessRole, Color, Id, Vec2};
11
12#[derive(Clone, Debug, Default, PartialEq)]
15pub struct Validation {
16 pub status: SemanticStatus,
17 pub message: String,
18}
19
20impl Validation {
21 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
45impl From<SemanticStatus> for Validation {
47 fn from(status: SemanticStatus) -> Self {
48 Self::with(status, String::new())
49 }
50}
51
52impl<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
62pub 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 pub fn hint(mut self, text: impl Into<String>) -> Self {
92 self.hint = text.into();
93 self
94 }
95 pub fn validation(mut self, validation: impl Into<Validation>) -> Self {
97 self.validation = validation.into();
98 self
99 }
100 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 ui.layout.spacing = gap;
125 ui.push_id(("field", id), |ui| {
126 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
169fn 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
192fn 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 if control.description.is_none() {
232 control.description(message);
233 }
234 }
235 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
251fn 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}