Skip to main content

iced_cube/forms/
label.rs

1//! Labels, and fields that stack a label, a control and helper text.
2//!
3//! ```no_run
4//! # #[cfg(feature = "input")]
5//! # fn main() {
6//! use iced_cube::{field, input};
7//!
8//! #[derive(Debug, Clone)]
9//! enum Message { Email(String) }
10//!
11//! let email = "";
12//! let view: iced::Element<'_, Message> = field("Email", input("you@example.com", email).on_input(Message::Email))
13//!     .description("We never share it.")
14//!     .required(true)
15//!     .into();
16//! # }
17//! # #[cfg(not(feature = "input"))]
18//! # fn main() {}
19//! ```
20
21use std::fmt;
22
23use iced::widget::{Column, column, row, text};
24use iced::{Color, Element, Length};
25
26use crate::theme::{Tokens, fade, space, text_size};
27
28/// Tone of a label.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
30pub enum State {
31    #[default]
32    Normal,
33    Disabled,
34    Invalid,
35}
36
37impl State {
38    pub const ALL: [State; 3] = [State::Normal, State::Disabled, State::Invalid];
39}
40
41/// A label builder. Convert it into an [`Element`] to render.
42#[derive(Debug)]
43pub struct Label<'a> {
44    text: text::Fragment<'a>,
45    state: State,
46    required: bool,
47}
48
49/// Creates a label naming a control.
50pub fn label<'a>(text: impl text::IntoFragment<'a>) -> Label<'a> {
51    Label {
52        text: text.into_fragment(),
53        state: State::default(),
54        required: false,
55    }
56}
57
58impl<'a> Label<'a> {
59    pub fn state(mut self, state: State) -> Self {
60        self.state = state;
61        self
62    }
63
64    /// Mutes the label to match a disabled control.
65    pub fn disabled(self, disabled: bool) -> Self {
66        self.toggle(State::Disabled, disabled)
67    }
68
69    /// Colours the label to match an invalid control.
70    pub fn invalid(self, invalid: bool) -> Self {
71        self.toggle(State::Invalid, invalid)
72    }
73
74    /// Appends a required marker.
75    pub fn required(mut self, required: bool) -> Self {
76        self.required = required;
77        self
78    }
79
80    fn toggle(mut self, state: State, on: bool) -> Self {
81        if on {
82            self.state = state;
83        } else if self.state == state {
84            self.state = State::Normal;
85        }
86        self
87    }
88}
89
90impl<'a, Message: 'a> From<Label<'a>> for Element<'a, Message> {
91    fn from(label: Label<'a>) -> Self {
92        let state = label.state;
93        let name = text(label.text)
94            .size(text_size::SM)
95            .style(move |theme| text::Style {
96                color: Some(colour(&Tokens::of(theme), state)),
97            });
98
99        if !label.required {
100            return name.into();
101        }
102
103        let marker = text("*")
104            .size(text_size::SM)
105            .style(move |theme| text::Style {
106                color: Some(required_colour(&Tokens::of(theme), state)),
107            });
108        row![name, marker].spacing(2).into()
109    }
110}
111
112/// A labelled control with optional description and error text.
113pub struct Field<'a, Message> {
114    label: Label<'a>,
115    control: Element<'a, Message>,
116    description: Option<text::Fragment<'a>>,
117    error: Option<text::Fragment<'a>>,
118    width: Length,
119}
120
121impl<Message> fmt::Debug for Field<'_, Message> {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        f.debug_struct("Field")
124            .field("label", &self.label)
125            .field("description", &self.description)
126            .field("error", &self.error)
127            .field("width", &self.width)
128            .finish_non_exhaustive()
129    }
130}
131
132/// Stacks a label above `control`. Add helper text with
133/// [`Field::description`] and [`Field::error`].
134pub fn field<'a, Message>(
135    label_text: impl text::IntoFragment<'a>,
136    control: impl Into<Element<'a, Message>>,
137) -> Field<'a, Message> {
138    Field {
139        label: label(label_text),
140        control: control.into(),
141        description: None,
142        error: None,
143        width: Length::Fill,
144    }
145}
146
147impl<'a, Message> Field<'a, Message> {
148    /// Adds muted helper text below the control.
149    pub fn description(mut self, description: impl text::IntoFragment<'a>) -> Self {
150        self.description = Some(description.into_fragment());
151        self
152    }
153
154    /// Shows an error below the control and colours the label to match.
155    pub fn error(mut self, error: impl text::IntoFragment<'a>) -> Self {
156        self.error = Some(error.into_fragment());
157        self
158    }
159
160    pub fn error_maybe(mut self, error: Option<impl text::IntoFragment<'a>>) -> Self {
161        self.error = error.map(text::IntoFragment::into_fragment);
162        self
163    }
164
165    pub fn required(mut self, required: bool) -> Self {
166        self.label = self.label.required(required);
167        self
168    }
169
170    /// Mutes the label to match a disabled control.
171    pub fn disabled(mut self, disabled: bool) -> Self {
172        self.label = self.label.disabled(disabled);
173        self
174    }
175
176    pub fn width(mut self, width: impl Into<Length>) -> Self {
177        self.width = width.into();
178        self
179    }
180
181    pub fn has_error(&self) -> bool {
182        self.error.is_some()
183    }
184}
185
186impl<'a, Message: 'a> From<Field<'a, Message>> for Element<'a, Message> {
187    fn from(field: Field<'a, Message>) -> Self {
188        let invalid = field.error.is_some();
189        let label = if invalid {
190            field.label.state(State::Invalid)
191        } else {
192            field.label
193        };
194
195        #[cfg(feature = "icedwright")]
196        return described(
197            field.width,
198            label,
199            field.control,
200            field.description,
201            field.error,
202        );
203
204        #[cfg(not(feature = "icedwright"))]
205        {
206            let content: Column<'a, Message> = column![label, field.control]
207                .push(field.description.map(|d| helper(d, description_colour)))
208                .push(field.error.map(|e| helper(e, error_colour)))
209                .spacing(space::SM)
210                .width(field.width);
211            content.into()
212        }
213    }
214}
215
216/// Helper text below a control, in the colour `tone` picks.
217fn helper<'a>(content: text::Fragment<'a>, tone: fn(&Tokens) -> Color) -> text::Text<'a> {
218    text(content)
219        .size(text_size::XS)
220        .style(move |theme| text::Style {
221            color: Some(tone(&Tokens::of(theme))),
222        })
223}
224
225/// Lays out a field with the label naming the control, the helper text
226/// describing it, and the control required or invalid to match.
227#[cfg(feature = "icedwright")]
228fn described<'a, Message: 'a>(
229    width: Length,
230    label: Label<'a>,
231    control: Element<'a, Message>,
232    description: Option<text::Fragment<'a>>,
233    error: Option<text::Fragment<'a>>,
234) -> Element<'a, Message> {
235    use icedwright_probe::{Key, role, semantic};
236
237    const KIND: &str = "iced_cube::field";
238
239    let helper = |content: text::Fragment<'a>, tone: fn(&Tokens) -> Color, key: &Key| {
240        semantic(helper(content.clone(), tone))
241            .role(role::Text)
242            .name(content)
243            .key(key.clone())
244            .component(KIND)
245    };
246
247    let label_key = Key::unique();
248    let control_key = Key::unique();
249    // Named directly, so the required marker stays out of the name.
250    let mut annotated = semantic(control)
251        .name(label.text.clone())
252        .key(control_key.clone())
253        .labelled_by(label_key.clone())
254        .component(KIND);
255    if label.required {
256        annotated = annotated.required(true);
257    }
258    if error.is_some() {
259        annotated = annotated.invalid(true);
260    }
261    let mut helpers = Vec::new();
262    for (content, tone) in [
263        (description, description_colour as fn(&Tokens) -> Color),
264        (error, error_colour),
265    ] {
266        let Some(content) = content else {
267            continue;
268        };
269        let key = Key::unique();
270        annotated = annotated.described_by(key.clone());
271        helpers.push(helper(content, tone, &key));
272    }
273    let name = label.text.clone();
274    let label = semantic(label)
275        .role(role::Text)
276        .name(name)
277        .key(label_key)
278        .label_for(control_key)
279        .component(KIND);
280
281    let mut content: Column<'a, Message> =
282        column![label, annotated].spacing(space::SM).width(width);
283    for helper in helpers {
284        content = content.push(helper);
285    }
286    content.into()
287}
288
289/// Label colour for a state.
290pub fn colour(tokens: &Tokens, state: State) -> Color {
291    match state {
292        State::Normal => tokens.foreground,
293        State::Disabled => fade(tokens.foreground, 0.5),
294        State::Invalid => tokens.destructive_text,
295    }
296}
297
298/// Colour of the required marker.
299pub fn required_colour(tokens: &Tokens, state: State) -> Color {
300    match state {
301        State::Disabled => fade(tokens.destructive_text, 0.5),
302        State::Normal | State::Invalid => tokens.destructive_text,
303    }
304}
305
306/// Colour of a field's description.
307pub fn description_colour(tokens: &Tokens) -> Color {
308    tokens.muted_foreground
309}
310
311/// Colour of a field's error message.
312pub fn error_colour(tokens: &Tokens) -> Color {
313    tokens.destructive_text
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use crate::theme::{dark, light};
320    use iced::widget::Space;
321
322    fn control<'a>() -> Element<'a, ()> {
323        Space::new().into()
324    }
325
326    #[test]
327    fn default_label_is_normal_and_optional() {
328        let l = label("Name");
329        assert_eq!(l.state, State::Normal);
330        assert!(!l.required);
331        assert_eq!(&*l.text, "Name");
332    }
333
334    #[test]
335    fn toggles_set_and_clear_their_own_state() {
336        assert_eq!(label("x").disabled(true).state, State::Disabled);
337        assert_eq!(label("x").invalid(true).state, State::Invalid);
338        assert_eq!(
339            label("x").disabled(true).disabled(false).state,
340            State::Normal
341        );
342        assert_eq!(
343            label("x").invalid(true).disabled(false).state,
344            State::Invalid
345        );
346    }
347
348    #[test]
349    fn states_have_distinct_colours_in_both_themes() {
350        for theme in [light(), dark()] {
351            let tokens = Tokens::of(&theme);
352            let colours = State::ALL.map(|s| colour(&tokens, s));
353            assert_ne!(colours[0], colours[1]);
354            assert_ne!(colours[0], colours[2]);
355            assert_ne!(colours[1], colours[2]);
356            assert!((colours[1].a - colours[0].a * 0.5).abs() < 1e-6);
357        }
358    }
359
360    #[test]
361    fn required_marker_is_destructive_and_fades_when_disabled() {
362        let tokens = Tokens::of(&dark());
363        assert_eq!(
364            required_colour(&tokens, State::Normal),
365            tokens.destructive_text
366        );
367        assert_eq!(
368            required_colour(&tokens, State::Invalid),
369            tokens.destructive_text
370        );
371        assert!(required_colour(&tokens, State::Disabled).a < tokens.destructive_text.a);
372    }
373
374    #[test]
375    fn helper_text_colours_come_from_tokens() {
376        for theme in [light(), dark()] {
377            let tokens = Tokens::of(&theme);
378            assert_eq!(description_colour(&tokens), tokens.muted_foreground);
379            assert_eq!(error_colour(&tokens), tokens.destructive_text);
380        }
381    }
382
383    #[test]
384    fn field_defaults_have_no_helper_text() {
385        let f = field("Email", control());
386        assert!(f.description.is_none());
387        assert!(!f.has_error());
388        assert_eq!(f.width, Length::Fill);
389    }
390
391    #[test]
392    fn field_builder_forwards_to_label() {
393        let f = field("Email", control()).required(true).disabled(true);
394        assert!(f.label.required);
395        assert_eq!(f.label.state, State::Disabled);
396    }
397
398    #[test]
399    fn error_maybe_none_clears_the_error() {
400        let f = field("Email", control())
401            .error("Required")
402            .error_maybe(None::<&str>);
403        assert!(!f.has_error());
404        let f = field("Email", control()).error_maybe(Some("Required"));
405        assert!(f.has_error());
406    }
407}