iced-cube 0.0.23

Themeable application components for the iced GUI library, with Lucide icons
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Labels, and fields that stack a label, a control and helper text.
//!
//! ```no_run
//! # #[cfg(feature = "input")]
//! # fn main() {
//! use iced_cube::{field, input};
//!
//! #[derive(Debug, Clone)]
//! enum Message { Email(String) }
//!
//! let email = "";
//! let view: iced::Element<'_, Message> = field("Email", input("you@example.com", email).on_input(Message::Email))
//!     .description("We never share it.")
//!     .required(true)
//!     .into();
//! # }
//! # #[cfg(not(feature = "input"))]
//! # fn main() {}
//! ```

use std::fmt;

use iced::widget::{Column, column, row, text};
use iced::{Color, Element, Length};

use crate::theme::{Tokens, fade, space, text_size};

/// Tone of a label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum State {
    #[default]
    Normal,
    Disabled,
    Invalid,
}

impl State {
    pub const ALL: [State; 3] = [State::Normal, State::Disabled, State::Invalid];
}

/// A label builder. Convert it into an [`Element`] to render.
#[derive(Debug)]
pub struct Label<'a> {
    text: text::Fragment<'a>,
    state: State,
    required: bool,
}

/// Creates a label naming a control.
pub fn label<'a>(text: impl text::IntoFragment<'a>) -> Label<'a> {
    Label {
        text: text.into_fragment(),
        state: State::default(),
        required: false,
    }
}

impl<'a> Label<'a> {
    pub fn state(mut self, state: State) -> Self {
        self.state = state;
        self
    }

    /// Mutes the label to match a disabled control.
    pub fn disabled(self, disabled: bool) -> Self {
        self.toggle(State::Disabled, disabled)
    }

    /// Colours the label to match an invalid control.
    pub fn invalid(self, invalid: bool) -> Self {
        self.toggle(State::Invalid, invalid)
    }

    /// Appends a required marker.
    pub fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    fn toggle(mut self, state: State, on: bool) -> Self {
        if on {
            self.state = state;
        } else if self.state == state {
            self.state = State::Normal;
        }
        self
    }
}

impl<'a, Message: 'a> From<Label<'a>> for Element<'a, Message> {
    fn from(label: Label<'a>) -> Self {
        let state = label.state;
        let name = text(label.text)
            .size(text_size::SM)
            .style(move |theme| text::Style {
                color: Some(colour(&Tokens::of(theme), state)),
            });

        if !label.required {
            return name.into();
        }

        let marker = text("*")
            .size(text_size::SM)
            .style(move |theme| text::Style {
                color: Some(required_colour(&Tokens::of(theme), state)),
            });
        row![name, marker].spacing(2).into()
    }
}

/// A labelled control with optional description and error text.
pub struct Field<'a, Message> {
    label: Label<'a>,
    control: Element<'a, Message>,
    description: Option<text::Fragment<'a>>,
    error: Option<text::Fragment<'a>>,
    width: Length,
}

impl<Message> fmt::Debug for Field<'_, Message> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Field")
            .field("label", &self.label)
            .field("description", &self.description)
            .field("error", &self.error)
            .field("width", &self.width)
            .finish_non_exhaustive()
    }
}

/// Stacks a label above `control`. Add helper text with
/// [`Field::description`] and [`Field::error`].
pub fn field<'a, Message>(
    label_text: impl text::IntoFragment<'a>,
    control: impl Into<Element<'a, Message>>,
) -> Field<'a, Message> {
    Field {
        label: label(label_text),
        control: control.into(),
        description: None,
        error: None,
        width: Length::Fill,
    }
}

impl<'a, Message> Field<'a, Message> {
    /// Adds muted helper text below the control.
    pub fn description(mut self, description: impl text::IntoFragment<'a>) -> Self {
        self.description = Some(description.into_fragment());
        self
    }

    /// Shows an error below the control and colours the label to match.
    pub fn error(mut self, error: impl text::IntoFragment<'a>) -> Self {
        self.error = Some(error.into_fragment());
        self
    }

    pub fn error_maybe(mut self, error: Option<impl text::IntoFragment<'a>>) -> Self {
        self.error = error.map(text::IntoFragment::into_fragment);
        self
    }

    pub fn required(mut self, required: bool) -> Self {
        self.label = self.label.required(required);
        self
    }

    /// Mutes the label to match a disabled control.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.label = self.label.disabled(disabled);
        self
    }

    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.width = width.into();
        self
    }

    pub fn has_error(&self) -> bool {
        self.error.is_some()
    }
}

impl<'a, Message: 'a> From<Field<'a, Message>> for Element<'a, Message> {
    fn from(field: Field<'a, Message>) -> Self {
        let invalid = field.error.is_some();
        let label = if invalid {
            field.label.state(State::Invalid)
        } else {
            field.label
        };

        #[cfg(feature = "icedwright")]
        return described(
            field.width,
            label,
            field.control,
            field.description,
            field.error,
        );

        #[cfg(not(feature = "icedwright"))]
        {
            let content: Column<'a, Message> = column![label, field.control]
                .push(field.description.map(|d| helper(d, description_colour)))
                .push(field.error.map(|e| helper(e, error_colour)))
                .spacing(space::SM)
                .width(field.width);
            content.into()
        }
    }
}

/// Helper text below a control, in the colour `tone` picks.
fn helper<'a>(content: text::Fragment<'a>, tone: fn(&Tokens) -> Color) -> text::Text<'a> {
    text(content)
        .size(text_size::XS)
        .style(move |theme| text::Style {
            color: Some(tone(&Tokens::of(theme))),
        })
}

/// Lays out a field with the label naming the control, the helper text
/// describing it, and the control required or invalid to match.
#[cfg(feature = "icedwright")]
fn described<'a, Message: 'a>(
    width: Length,
    label: Label<'a>,
    control: Element<'a, Message>,
    description: Option<text::Fragment<'a>>,
    error: Option<text::Fragment<'a>>,
) -> Element<'a, Message> {
    use icedwright_probe::{Key, role, semantic};

    const KIND: &str = "iced_cube::field";

    let helper = |content: text::Fragment<'a>, tone: fn(&Tokens) -> Color, key: &Key| {
        semantic(helper(content.clone(), tone))
            .role(role::Text)
            .name(content)
            .key(key.clone())
            .component(KIND)
    };

    let label_key = Key::unique();
    let control_key = Key::unique();
    // Named directly, so the required marker stays out of the name.
    let mut annotated = semantic(control)
        .name(label.text.clone())
        .key(control_key.clone())
        .labelled_by(label_key.clone())
        .component(KIND);
    if label.required {
        annotated = annotated.required(true);
    }
    if error.is_some() {
        annotated = annotated.invalid(true);
    }
    let mut helpers = Vec::new();
    for (content, tone) in [
        (description, description_colour as fn(&Tokens) -> Color),
        (error, error_colour),
    ] {
        let Some(content) = content else {
            continue;
        };
        let key = Key::unique();
        annotated = annotated.described_by(key.clone());
        helpers.push(helper(content, tone, &key));
    }
    let name = label.text.clone();
    let label = semantic(label)
        .role(role::Text)
        .name(name)
        .key(label_key)
        .label_for(control_key)
        .component(KIND);

    let mut content: Column<'a, Message> =
        column![label, annotated].spacing(space::SM).width(width);
    for helper in helpers {
        content = content.push(helper);
    }
    content.into()
}

/// Label colour for a state.
pub fn colour(tokens: &Tokens, state: State) -> Color {
    match state {
        State::Normal => tokens.foreground,
        State::Disabled => fade(tokens.foreground, 0.5),
        State::Invalid => tokens.destructive_text,
    }
}

/// Colour of the required marker.
pub fn required_colour(tokens: &Tokens, state: State) -> Color {
    match state {
        State::Disabled => fade(tokens.destructive_text, 0.5),
        State::Normal | State::Invalid => tokens.destructive_text,
    }
}

/// Colour of a field's description.
pub fn description_colour(tokens: &Tokens) -> Color {
    tokens.muted_foreground
}

/// Colour of a field's error message.
pub fn error_colour(tokens: &Tokens) -> Color {
    tokens.destructive_text
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::{dark, light};
    use iced::widget::Space;

    fn control<'a>() -> Element<'a, ()> {
        Space::new().into()
    }

    #[test]
    fn default_label_is_normal_and_optional() {
        let l = label("Name");
        assert_eq!(l.state, State::Normal);
        assert!(!l.required);
        assert_eq!(&*l.text, "Name");
    }

    #[test]
    fn toggles_set_and_clear_their_own_state() {
        assert_eq!(label("x").disabled(true).state, State::Disabled);
        assert_eq!(label("x").invalid(true).state, State::Invalid);
        assert_eq!(
            label("x").disabled(true).disabled(false).state,
            State::Normal
        );
        assert_eq!(
            label("x").invalid(true).disabled(false).state,
            State::Invalid
        );
    }

    #[test]
    fn states_have_distinct_colours_in_both_themes() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            let colours = State::ALL.map(|s| colour(&tokens, s));
            assert_ne!(colours[0], colours[1]);
            assert_ne!(colours[0], colours[2]);
            assert_ne!(colours[1], colours[2]);
            assert!((colours[1].a - colours[0].a * 0.5).abs() < 1e-6);
        }
    }

    #[test]
    fn required_marker_is_destructive_and_fades_when_disabled() {
        let tokens = Tokens::of(&dark());
        assert_eq!(
            required_colour(&tokens, State::Normal),
            tokens.destructive_text
        );
        assert_eq!(
            required_colour(&tokens, State::Invalid),
            tokens.destructive_text
        );
        assert!(required_colour(&tokens, State::Disabled).a < tokens.destructive_text.a);
    }

    #[test]
    fn helper_text_colours_come_from_tokens() {
        for theme in [light(), dark()] {
            let tokens = Tokens::of(&theme);
            assert_eq!(description_colour(&tokens), tokens.muted_foreground);
            assert_eq!(error_colour(&tokens), tokens.destructive_text);
        }
    }

    #[test]
    fn field_defaults_have_no_helper_text() {
        let f = field("Email", control());
        assert!(f.description.is_none());
        assert!(!f.has_error());
        assert_eq!(f.width, Length::Fill);
    }

    #[test]
    fn field_builder_forwards_to_label() {
        let f = field("Email", control()).required(true).disabled(true);
        assert!(f.label.required);
        assert_eq!(f.label.state, State::Disabled);
    }

    #[test]
    fn error_maybe_none_clears_the_error() {
        let f = field("Email", control())
            .error("Required")
            .error_maybe(None::<&str>);
        assert!(!f.has_error());
        let f = field("Email", control()).error_maybe(Some("Required"));
        assert!(f.has_error());
    }
}