1use crate::geometry::{Rect, Size, clamp_u16};
4use crate::text;
5use crate::theme::State;
6use crate::widget::{Axis, Container, Flex, Length, MeasureCx, Node, PaintCx, Widget};
7
8use super::cells;
9
10const LABEL_GAP: u16 = 2;
12
13const MIN_CONTROL: u16 = 16;
15
16const UNBOUNDED: u16 = 4096;
19
20pub struct Field<Msg> {
37 label: String,
38 hint: Option<String>,
39 error: Option<String>,
40 required: bool,
41 disabled: bool,
42 pub(super) label_width: Option<u16>,
43 body: Vec<Node<Msg>>,
44}
45
46impl<Msg: 'static> Field<Msg> {
47 #[must_use]
50 pub fn new(label: impl Into<String>) -> Self {
51 Self {
52 label: label.into(),
53 hint: None,
54 error: None,
55 required: false,
56 disabled: false,
57 label_width: None,
58 body: vec![Node::new(Flex::new(Axis::Column, Vec::new()), 0)],
59 }
60 }
61
62 #[must_use]
64 pub fn hint(mut self, hint: impl Into<String>) -> Self {
65 self.hint = Some(hint.into());
66 self
67 }
68
69 #[must_use]
72 pub fn error<S: Into<String>>(mut self, error: Option<S>) -> Self {
73 self.error = error.map(Into::into);
74 self
75 }
76
77 #[must_use]
79 pub fn required(mut self, required: bool) -> Self {
80 self.required = required;
81 self
82 }
83
84 #[must_use]
86 pub fn disabled(mut self, disabled: bool) -> Self {
87 self.disabled = disabled;
88 self
89 }
90
91 #[must_use]
94 pub fn label_width(mut self, cells: u16) -> Self {
95 self.label_width = Some(cells);
96 self
97 }
98
99 fn beside(&self, width: u16, natural: u16) -> Option<u16> {
105 self.label_width.filter(|label| {
106 let room = width.saturating_sub(cells::sum([*label, LABEL_GAP]));
107 room >= MIN_CONTROL && (natural <= room || natural >= UNBOUNDED)
108 })
109 }
110
111 fn required_under_control(&self, column: u16, word: &str) -> bool {
115 self.required && text::width(word) > column
116 }
117
118 fn message_lines(&self, width: u16, marker_width: u16) -> (Vec<String>, bool) {
120 match (&self.error, &self.hint) {
121 (Some(error), _) => (text::wrap(error, width.saturating_sub(marker_width + 1)), true),
122 (None, Some(hint)) => (text::wrap(hint, width), false),
123 (None, None) => (Vec::new(), false),
124 }
125 }
126}
127
128impl<Msg: 'static> Container<Msg> for Field<Msg> {
129 fn set_children(&mut self, children: Vec<Node<Msg>>) {
130 let mut column = Node::new(Flex::new(Axis::Column, children), 0);
131 column.layout.width = Length::Fill(1);
132 self.body = vec![column];
133 }
134}
135
136struct Parts {
138 label: Rect,
139 required: Option<Rect>,
140 control: Rect,
141 message_x: i32,
142 message_width: u16,
143}
144
145fn required_word() -> String {
146 crate::t!("quvyta.form.required")
147}
148
149impl<Msg: 'static> Widget<Msg> for Field<Msg> {
150 fn measure(&self, cx: &mut MeasureCx<'_>, available: Size) -> Size {
151 let marker = text::width(&cx.env().icons().glyph("error"));
152 let label_width = text::width(&self.label);
153 let required = if self.required { text::width(&required_word()) } else { 0 };
154 let Some(body) = self.body.first() else {
155 return Size::default();
156 };
157 let natural = cx.measure_child(body, Size::new(UNBOUNDED, available.height)).width;
158 if let Some(column) = self.beside(available.width, natural) {
159 let control_width = available.width - column - LABEL_GAP;
160 let control = cx.measure_child(body, Size::new(control_width, available.height));
161 let (lines, _) = self.message_lines(control_width, marker);
162 let below = self.required_under_control(column, &required_word());
163 let label_rows = 1 + u16::from(self.required && !below);
164 let messages = clamp_u16(i32::try_from(lines.len()).unwrap_or(i32::MAX)).saturating_add(u16::from(below));
165 let right = control.height.saturating_add(messages);
166 return Size::new(available.width, label_rows.max(right)).min(available);
167 }
168 let control = cx.measure_child(body, Size::new(available.width, available.height.saturating_sub(1)));
169 let (lines, error) = self.message_lines(available.width, marker);
170 let widest_line = lines.iter().map(|line| text::width(line)).max().unwrap_or(0).saturating_add(if error {
171 marker.saturating_add(1)
172 } else {
173 0
174 });
175 let label_line = label_width.saturating_add(if self.required { required.saturating_add(2) } else { 0 });
176 let height = cells::sum([1, control.height, clamp_u16(i32::try_from(lines.len()).unwrap_or(i32::MAX))]);
177 Size::new(label_line.max(control.width).max(widest_line), height).min(available)
178 }
179
180 fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
181 let Some(body) = self.body.first() else {
182 return;
183 };
184 let marker = cx.env().icons().glyph("error").into_owned();
185 let marker_width = text::width(&marker);
186 let required = required_word();
187 let natural = cx.measure_child(body, Size::new(UNBOUNDED, area.height)).width;
188 let parts = match self.beside(area.width, natural) {
189 Some(column) => {
190 let control_x = area.x + i32::from(column + LABEL_GAP);
191 let control_width = area.width - column - LABEL_GAP;
192 let height = cx.measure_child(body, Size::new(control_width, area.height)).height;
193 let required = if self.required_under_control(column, &required) {
194 Rect::new(control_x, area.y + i32::from(height), control_width, 1)
195 } else {
196 Rect::new(area.x, area.y + 1, column, 1)
197 };
198 Parts {
199 label: Rect::new(area.x, area.y, column, 1),
200 required: self.required.then_some(required),
201 control: Rect::new(control_x, area.y, control_width, height),
202 message_x: control_x,
203 message_width: control_width,
204 }
205 }
206 None => {
207 let label_width = text::width(&self.label).min(area.width);
208 let height = cx.measure_child(body, Size::new(area.width, area.height.saturating_sub(1))).height;
209 let required_x = area.x + i32::from(label_width) + 2;
210 Parts {
211 label: Rect::new(area.x, area.y, label_width, 1),
212 required: self
213 .required
214 .then(|| Rect::new(required_x, area.y, clamp_u16(area.right() - required_x), 1)),
215 control: Rect::new(area.x, area.y + 1, area.width, height),
216 message_x: area.x,
217 message_width: area.width,
218 }
219 }
220 };
221 cx.paint_child(body, parts.control);
223
224 let mut states = Vec::new();
225 if cx.has_focus_within() {
226 states.push(State::Focus);
227 }
228 if self.disabled {
229 states.push(State::Disabled);
230 }
231 let label_style = cx.style("field-label", None, &states).text();
232 let label = text::truncate(&self.label, parts.label.width).into_owned();
233 cx.text(parts.label.x, parts.label.y, &label, label_style, parts.label.width);
234 if let Some(rect) = parts.required {
235 let style = cx.style("field-required", None, &states).text();
236 let word = text::truncate(&required, rect.width).into_owned();
237 cx.text(rect.x, rect.y, &word, style, rect.width);
238 }
239
240 let (lines, error) = self.message_lines(parts.message_width, marker_width);
241 let top = match parts.required {
243 Some(rect) if rect.x == parts.control.x && rect.y >= parts.control.bottom() => rect.bottom(),
244 _ => parts.control.bottom(),
245 };
246 let indent = if error { i32::from(marker_width) + 1 } else { 0 };
247 let style = cx.style(if error { "field-error" } else { "field-hint" }, None, &states).text();
248 if error {
249 cx.text(parts.message_x, top, &marker, style, marker_width);
250 }
251 let width = clamp_u16(i32::from(parts.message_width) - indent);
252 for (y, line) in (top..).zip(lines) {
253 cx.text(parts.message_x + indent, y, &line, style, width);
254 }
255 }
256
257 fn children(&self) -> &[Node<Msg>] {
258 &self.body
259 }
260
261 fn children_mut(&mut self) -> &mut [Node<Msg>] {
262 &mut self.body
263 }
264}