Skip to main content

bhoo/systems/material/
text_field.rs

1use crate::*;
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4pub enum FieldAffordance {
5    #[default]
6    Arrow,
7    Calendar,
8    Clock,
9}
10
11impl Frame<'_> {
12    pub fn select_field(&mut self, id: u64, label: &str, value: &str, filled: bool) -> Response {
13        self.popup_field(id, label, value, filled, FieldAffordance::Arrow)
14    }
15    /// Expose the text portion of a calendar field to an editing backend.
16    pub fn date_range_field(
17        &mut self,
18        id: u64,
19        label: &str,
20        value: &str,
21        open: bool,
22    ) -> (Response, Response) {
23        let (response, toggle) = self.popup_field_inner(
24            id,
25            label,
26            value,
27            true,
28            FieldAffordance::Calendar,
29            Some((id + 1, open)),
30        );
31        (response, toggle.expect("calendar toggle"))
32    }
33    pub fn popup_field(
34        &mut self,
35        id: u64,
36        label: &str,
37        value: &str,
38        filled: bool,
39        icon: FieldAffordance,
40    ) -> Response {
41        self.popup_field_inner(id, label, value, filled, icon, None)
42            .0
43    }
44    fn popup_field_inner(
45        &mut self,
46        id: u64,
47        label: &str,
48        value: &str,
49        filled: bool,
50        icon: FieldAffordance,
51        calendar: Option<(u64, bool)>,
52    ) -> (Response, Option<Response>) {
53        let r = self.text_field_inner(
54            id,
55            label,
56            56.0,
57            !value.is_empty(),
58            false,
59            filled,
60            false,
61            if calendar.is_some() { 48.0 } else { 0.0 },
62            40.0,
63        );
64        if let Some(node) = self.ui.semantics.last_mut() {
65            node.role = if calendar.is_some() {
66                Role::TextField
67            } else {
68                Role::Button
69            };
70            if calendar.is_some() {
71                node.bounds.width = (node.bounds.width - 48.0).max(0.0);
72            }
73        }
74        if !value.is_empty() {
75            self.styled_text(
76                Rect {
77                    y: r.bounds.y + if filled { 16.0 } else { 0.0 },
78                    height: if filled { 40.0 } else { 56.0 },
79                    width: (r.bounds.width - 40.0).max(0.0),
80                    ..r.bounds
81                },
82                value,
83                self.ui
84                    .theme
85                    .text
86                    .opacity(if r.enabled { 1.0 } else { 0.38 }),
87                TextStyle {
88                    padding: 16.0,
89                    ..TextStyle::default()
90                },
91            );
92        }
93        let center = [r.bounds.x + r.bounds.width - 20.0, r.bounds.y + 28.0];
94        let color = self
95            .ui
96            .theme
97            .on_surface_variant
98            .opacity(if r.enabled { 1.0 } else { 0.38 });
99        let toggle = calendar.map(|(toggle_id, open)| {
100            let bounds = Rect {
101                x: center[0] - 20.0,
102                y: center[1] - 20.0,
103                width: 40.0,
104                height: 40.0,
105            };
106            let button = self.target(toggle_id, bounds, "Open calendar", true, Role::Button);
107            let tint = if open {
108                self.ui.theme.primary
109            } else {
110                self.ui.theme.on_surface_variant
111            };
112            let alpha = if button.pressed || button.focused && self.ui.keyboard_focus {
113                0.12
114            } else if button.hovered {
115                0.08
116            } else {
117                0.0
118            };
119            if button.enabled && alpha > 0.0 {
120                self.rect(bounds, 20.0, tint.opacity(alpha));
121            }
122            self.ink(button, 20.0, tint);
123            button
124        });
125        let color = if calendar.is_some_and(|(_, open)| open) {
126            self.ui
127                .theme
128                .primary
129                .opacity(if r.enabled { 1.0 } else { 0.38 })
130        } else {
131            color
132        };
133        if icon == FieldAffordance::Calendar {
134            let b = Rect {
135                x: center[0] - 9.0,
136                y: center[1] - 8.0,
137                width: 18.0,
138                height: 18.0,
139            };
140            for rect in [
141                Rect { height: 5.0, ..b },
142                Rect {
143                    x: b.x,
144                    y: b.y + 5.0,
145                    width: 2.0,
146                    height: 13.0,
147                },
148                Rect {
149                    x: b.x + 16.0,
150                    y: b.y + 5.0,
151                    width: 2.0,
152                    height: 13.0,
153                },
154                Rect {
155                    x: b.x,
156                    y: b.y + 16.0,
157                    width: 18.0,
158                    height: 2.0,
159                },
160            ] {
161                self.rect(rect, 0.0, color);
162            }
163            for x in [b.x + 4.0, b.x + 12.0] {
164                self.rect(
165                    Rect {
166                        x,
167                        y: b.y - 2.0,
168                        width: 2.0,
169                        height: 5.0,
170                    },
171                    0.0,
172                    color,
173                );
174            }
175            self.rect(
176                Rect {
177                    x: b.x + 4.0,
178                    y: b.y + 7.0,
179                    width: 4.0,
180                    height: 4.0,
181                },
182                0.0,
183                color,
184            );
185        } else if icon == FieldAffordance::Clock {
186            let b = Rect {
187                x: center[0] - 10.0,
188                y: center[1] - 10.0,
189                width: 20.0,
190                height: 20.0,
191            };
192            self.rect(b, 10.0, color);
193            self.rect(
194                b.inset(2.0),
195                8.0,
196                if filled {
197                    self.ui.theme.surface_variant
198                } else {
199                    self.ui.theme.background
200                },
201            );
202            self.paint_line([center[0], center[1] - 6.0], center, 1.5, color);
203            self.paint_line(center, [center[0] + 4.0, center[1] + 2.5], 1.5, color);
204        } else {
205            let x = center[0] - 6.0;
206            let y = center[1];
207            self.paint_line([x - 4.0, y - 2.0], [x, y + 2.0], 2.0, color);
208            self.paint_line([x, y + 2.0], [x + 4.0, y - 2.0], 2.0, color);
209        }
210        (r, toggle)
211    }
212    /// Draws an editable-field boundary. Text editing/IME belongs to the host adapter.
213    pub fn edit_boundary(&mut self, id: u64, label: &str, height: f32, invalid: bool) -> Response {
214        let b = self.allocate(height);
215        let r = self.interact(id, b, true);
216        let t = self.ui.theme;
217        self.rect(
218            b,
219            4.0,
220            if invalid {
221                t.error
222            } else if r.focused {
223                t.primary
224            } else {
225                t.outline
226            }
227            .opacity(if r.enabled { 1.0 } else { 0.38 }),
228        );
229        self.rect(b.inset(1.0), 3.0, t.background);
230        self.semantic(r, Role::TextField, label, false, None, None, None);
231        r
232    }
233    /// Labeled Material field geometry. Editing/IME remains a backend adapter responsibility.
234    pub fn text_field(
235        &mut self,
236        id: u64,
237        label: &str,
238        height: f32,
239        has_value: bool,
240        invalid: bool,
241        filled: bool,
242    ) -> Response {
243        self.text_field_required(id, label, height, has_value, invalid, filled, false)
244    }
245    /// Labeled field with an optional required marker and semantic required state.
246    #[allow(clippy::too_many_arguments)]
247    pub fn text_field_required(
248        &mut self,
249        id: u64,
250        label: &str,
251        height: f32,
252        has_value: bool,
253        invalid: bool,
254        filled: bool,
255        required: bool,
256    ) -> Response {
257        self.text_field_inner(id, label, height, has_value, invalid, filled, required, 0.0, 0.0)
258    }
259    #[allow(clippy::too_many_arguments)]
260    fn text_field_inner(
261        &mut self,
262        id: u64,
263        label: &str,
264        height: f32,
265        has_value: bool,
266        invalid: bool,
267        filled: bool,
268        required: bool,
269        trailing: f32,
270        label_trailing: f32,
271    ) -> Response {
272        let total = self.allocate(height + 20.0);
273        let b = Rect { height, ..total };
274        let mut r = self.interact(
275            id,
276            Rect {
277                width: (b.width - trailing).max(0.0),
278                ..b
279            },
280            true,
281        );
282        r.bounds = b;
283        if trailing > 0.0 {
284            r.hovered =
285                r.enabled && self.pointer_in(b) && self.input.pointer_kind != PointerKind::Touch;
286        }
287        let t = self.ui.theme;
288        use crate::timing::{Easing, TweenSpec};
289        let curve = Easing::Cubic([0.4, 0.0, 0.2, 1.0]);
290        let label_spec = TweenSpec::new(0.150, curve);
291        let floating = has_value || r.focused;
292        let target = f32::from(floating);
293        let amount = self
294            .ui
295            .motion
296            .css_tween(id, 60, target, target, label_spec, label_spec);
297        let label_target = if !r.enabled {
298            t.text.opacity(0.38)
299        } else if invalid {
300            t.error
301        } else if r.focused {
302            t.primary
303        } else if r.hovered && !filled {
304            t.text
305        } else {
306            t.on_surface_variant
307        };
308        let target_channels = [
309            label_target.0,
310            label_target.1,
311            label_target.2,
312            label_target.3,
313        ];
314        let mut channels = [0u8; 4];
315        for (index, value) in target_channels.into_iter().enumerate() {
316            let target = f32::from(value) / 255.0;
317            let sample = self.ui.motion.css_tween(
318                id,
319                61 + index as u8,
320                target,
321                target,
322                label_spec,
323                label_spec,
324            );
325            channels[index] = (sample * 255.0).round() as u8;
326        }
327        let foreground = Color(channels[0], channels[1], channels[2], channels[3]);
328        let edge = if !r.enabled {
329            t.text.opacity(0.12)
330        } else if invalid {
331            t.error
332        } else if r.focused {
333            t.primary
334        } else if r.hovered {
335            t.text
336        } else {
337            t.outline
338        };
339        if filled {
340            self.rect(
341                b,
342                4.0,
343                if r.enabled {
344                    t.surface_variant
345                } else {
346                    t.text.opacity(0.04)
347                },
348            );
349            if r.enabled && r.hovered && !r.focused {
350                self.rect(b, 4.0, t.text.opacity(0.08));
351            }
352            let base = if !r.enabled {
353                t.text.opacity(0.38)
354            } else if invalid {
355                t.error
356            } else if r.hovered && !r.focused {
357                t.text
358            } else {
359                t.on_surface_variant
360            };
361            self.rect(
362                Rect {
363                    y: b.y + b.height - 1.0,
364                    height: 1.0,
365                    ..b
366                },
367                0.0,
368                base,
369            );
370            let line_spec = TweenSpec::new(0.180, curve);
371            let focus = f32::from(r.focused && r.enabled);
372            let line_alpha = self
373                .ui
374                .motion
375                .css_tween(id, 65, focus, focus, line_spec, line_spec);
376            let scale_target = f32::from(focus > 0.0 || line_alpha > 0.0);
377            let line_scale =
378                self.ui
379                    .motion
380                    .css_tween(id, 66, scale_target, scale_target, line_spec, line_spec);
381            if line_alpha > 0.0 && line_scale > 0.0 {
382                let width = b.width * line_scale;
383                self.rect(
384                    Rect {
385                        x: b.x + (b.width - width) / 2.0,
386                        y: b.y + b.height - 2.0,
387                        width,
388                        height: 2.0,
389                    },
390                    0.0,
391                    if invalid {
392                        t.error.opacity(line_alpha)
393                    } else {
394                        t.primary.opacity(line_alpha)
395                    },
396                );
397            }
398        } else {
399            let stroke = if r.focused { 2.0 } else { 1.0 };
400            self.rect(b, 4.0, edge);
401            self.rect(b.inset(stroke), (4.0 - stroke).max(0.0), t.background);
402            if floating {
403                let style = TextStyle {
404                    size: 12.0,
405                    letter_spacing: 0.375,
406                    ..TextStyle::default()
407                };
408                let width = (self.text_width(label, style)
409                    + if required {
410                        self.text_width("*", style) + 1.0
411                    } else {
412                        0.0
413                    }
414                    + 8.0).min((b.width - 24.0 - label_trailing).max(0.0));
415                self.rect(
416                    Rect {
417                        x: b.x + 12.0,
418                        y: b.y - 8.0,
419                        width,
420                        height: 16.0,
421                    },
422                    0.0,
423                    t.background,
424                );
425            }
426        }
427        // Angular's floating label keeps the 56px label origin even for a textarea.
428        // The transformed 16px label scales to 12px while moving to the notch.
429        let label_bounds = Rect {
430            x: b.x + 16.0,
431            y: b.y
432                + if filled {
433                    6.05 * amount
434                } else {
435                    1.0 - 9.0 * amount
436                },
437            width: (b.width - 32.0 - label_trailing).max(0.0),
438            height: 56.0 - 40.0 * amount,
439        };
440        let style = TextStyle {
441            size: 16.0 - 4.0 * amount,
442            letter_spacing: 0.5 * (1.0 - 0.25 * amount),
443            ..TextStyle::default()
444        };
445        self.styled_text(label_bounds, label, foreground, style);
446        if required {
447            let marker_x = label_bounds.x + self.text_width(label, style) + (1.0 - 0.25 * amount);
448            self.styled_text(
449                Rect {
450                    x: marker_x,
451                    width: (label_bounds.x + label_bounds.width - marker_x).max(0.0),
452                    ..label_bounds
453                },
454                "*",
455                foreground,
456                style,
457            );
458        }
459        self.semantic(r, Role::TextField, label, false, None, None, None);
460        if let Some(node) = self.ui.semantics.last_mut() {
461            node.invalid = invalid;
462            node.filled = filled;
463            node.required = required;
464        }
465        r
466    }
467
468    /// Labeled Material field rendered at caller-supplied `bounds` that also paints `value` text.
469    #[allow(clippy::too_many_arguments)]
470    pub fn text_field_at(
471        &mut self,
472        id: u64,
473        bounds: Rect,
474        label: &str,
475        value: &str,
476        invalid: bool,
477        filled: bool,
478    ) -> Response {
479        let mut resp = Response::default();
480        let field_h = (bounds.height - 1.0).max(40.0);
481        self.within(bounds, |f| {
482            resp = f.text_field(id, label, field_h, !value.is_empty(), invalid, filled);
483            if !value.is_empty() {
484                let text_top = if filled { bounds.y + 23.0 } else { bounds.y + 14.0 };
485                f.paragraph(
486                    Rect {
487                        x: bounds.x + 16.0,
488                        y: text_top,
489                        width: (bounds.width - 32.0).max(0.0),
490                        height: (bounds.y + bounds.height - text_top - 4.0).max(16.0),
491                    },
492                    value,
493                    f.theme().text.opacity(if resp.enabled { 1.0 } else { 0.38 }),
494                    TextStyle { size: 16.0, ..TextStyle::default() },
495                    22.0,
496                );
497            }
498        });
499        resp
500    }
501
502    /// Material text field paired with supporting hint/error subscript line and optional character counter.
503    #[allow(clippy::too_many_arguments)]
504    pub fn text_field_with_subscript(
505        &mut self,
506        id: u64,
507        label: &str,
508        value: &str,
509        filled: bool,
510        invalid: bool,
511        required: bool,
512        supporting: &str,
513        max_chars: Option<usize>,
514    ) -> Response {
515        let r = self.text_field_required(id, label, 56.0, !value.is_empty(), invalid, filled, required);
516        let t = self.theme();
517        let sub = self.reserve(20.0);
518        let color = if invalid { t.error } else { t.on_surface_variant };
519        let style = TextStyle { size: 12.0, padding: 16.0, ..TextStyle::default() };
520        if !supporting.is_empty() {
521            let w = if max_chars.is_some() { (sub.width - 72.0).max(0.0) } else { sub.width };
522            self.styled_text(Rect { width: w, ..sub }, supporting, color, style);
523        }
524        if let Some(limit) = max_chars {
525            let count = value.chars().count();
526            let counter = format!("{count}/{limit}");
527            self.styled_text(
528                sub,
529                &counter,
530                if count > limit || invalid { t.error } else { t.on_surface_variant },
531                TextStyle { align: 2, ..style },
532            );
533        }
534        r
535    }
536}
537
538#[cfg(test)]
539#[path = "text_field.spec.rs"]
540mod tests;