Skip to main content

qframe/widgets/
field.rs

1//! Form fields: a label, a control, and a hint or an error.
2
3use 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
10/// Cells between the label column and the control when labels sit beside controls.
11const LABEL_GAP: u16 = 2;
12
13/// The narrowest control a field keeps beside its label; below it the label moves above.
14const MIN_CONTROL: u16 = 16;
15
16/// The width a control is measured in to learn how wide it wants to be. One that answers with all
17/// of it fills whatever it is given.
18const UNBOUNDED: u16 = 4096;
19
20/// A labelled control: the label, the control the application adds inside, and under it a
21/// faint hint or, when there is one, the error in the danger colour with a marker.
22///
23/// The field only lays things out. The application owns the value and its error, and marks the
24/// control itself as invalid (`TextInput::invalid`). The label brightens while the control has
25/// focus. Required fields show a faint word after the label; nothing is starred.
26///
27/// Labels sit above the control by default. With [`Field::label_width`] they take a column of
28/// that width beside the control whenever the field is wide enough, and move above it again on
29/// narrow screens. A control that asks for more than the room beside the label (an input with a
30/// long placeholder) puts its label above as well and takes the whole row instead of being cut.
31/// The column is at least as wide as the required word of the active language.
32///
33/// Style keys: `field-label` (`fg`, `bold`) with states `focus` and `disabled`;
34/// `field-required`, `field-hint` and `field-error` (`fg`). The required word is
35/// `quvyta.form.required`; the error marker is the `error` icon.
36pub 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    /// A field labelled `label`. Add its control with
48    /// [`View::add_with`](crate::widget::View::add_with) or [`FormFields::field`](super::FormFields::field).
49    #[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    /// Faint help under the control, shown while there is no error.
63    #[must_use]
64    pub fn hint(mut self, hint: impl Into<String>) -> Self {
65        self.hint = Some(hint.into());
66        self
67    }
68
69    /// The error under the control; `None` shows the hint instead. Pass
70    /// [`FormErrors::get`](super::FormErrors::get) straight in.
71    #[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    /// Shows the faint "required" word after the label.
78    #[must_use]
79    pub fn required(mut self, required: bool) -> Self {
80        self.required = required;
81        self
82    }
83
84    /// Greys the label out; disable the control as well.
85    #[must_use]
86    pub fn disabled(mut self, disabled: bool) -> Self {
87        self.disabled = disabled;
88        self
89    }
90
91    /// Puts the label in a column `cells` wide beside the control when the field is at least
92    /// that wide plus room for a control; otherwise the label stays above.
93    #[must_use]
94    pub fn label_width(mut self, cells: u16) -> Self {
95        self.label_width = Some(cells);
96        self
97    }
98
99    /// The label column width when the label fits beside the control in `width` cells.
100    ///
101    /// `natural` is the width the control asks for with no limit. A control wider than the room
102    /// beside the label would be cut there, so its label goes above and it gets the whole row; a
103    /// control that takes whatever it is given stays beside.
104    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    /// Whether the required word, too wide for the label column `column`, goes under the control
112    /// instead, on its own line before the hint. Growing the column would take room from every
113    /// control of the form, and cutting the word would lose it.
114    fn required_under_control(&self, column: u16, word: &str) -> bool {
115        self.required && text::width(word) > column
116    }
117
118    /// The hint or error lines at `width`, and whether they are an error.
119    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
136/// Where the parts of a field go inside its area.
137struct 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        // The control is painted first so the label can tell whether focus is inside it.
222        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        // The hint starts under the required word when the word sits under the control.
242        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}