Skip to main content

gpui_material_components/input/
text_field.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, BorderStyle, Bounds, ContentMask, ElementId, Entity,
5    InteractiveElement, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
6    StatefulInteractiveElement, Styled, TextAlign, Window, canvas, div, point,
7    prelude::FluentBuilder, px, quad,
8};
9use gpui_base::{
10    TestSupportExt,
11    input::{InputAccessibility, InputBaseState, InputEditorStyle, InputModeKind},
12};
13use gpui_material_foundation::{animate, color, font_for_style, window_material_theme};
14use gpui_material_theme::{
15    ColorRole, CornerRole, Direction, LayoutPolicy, MotionKind, MotionSpeed, TypeRole,
16    TypographyEmphasis,
17};
18
19use super::{TextAreaState, TextFieldState};
20
21/// Material text field container treatment. The default is Filled.
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
23pub enum TextFieldVariant {
24    #[default]
25    Filled,
26    Outlined,
27}
28
29/// A Material presentation for a caller-owned Base text editing entity.
30///
31/// Keep the entity across renders. It owns selection, undo, composition, focus,
32/// and text. Subscribe to [`super::TextFieldEvent`] on the entity to observe user
33/// edits. Set disabled and read-only on the entity before rendering.
34#[derive(IntoElement)]
35pub struct TextField {
36    id: ElementId,
37    label: SharedString,
38    editor: Editor,
39    variant: TextFieldVariant,
40    supporting_text: Option<SharedString>,
41    error: Option<SharedString>,
42    trailing: Option<AnyElement>,
43    expanded: Option<bool>,
44    font_scale: f32,
45}
46
47enum Editor {
48    Single(Entity<TextFieldState>),
49    Multiple(Entity<TextAreaState>),
50    Secure(Entity<TextFieldState>),
51}
52
53impl TextField {
54    /// Renders a single-line editor.
55    pub fn new(
56        id: impl Into<ElementId>,
57        label: impl Into<SharedString>,
58        state: &Entity<TextFieldState>,
59    ) -> Self {
60        Self::with_editor(id, label, Editor::Single(state.clone()))
61    }
62
63    /// Renders a multi-line editor using the row policy configured in its state.
64    pub fn multiline(
65        id: impl Into<ElementId>,
66        label: impl Into<SharedString>,
67        state: &Entity<TextAreaState>,
68    ) -> Self {
69        Self::with_editor(id, label, Editor::Multiple(state.clone()))
70    }
71
72    /// Always masks the editor and suppresses its value from accessibility.
73    /// Use a dedicated entity initialized with `TextFieldState::masked(true)`
74    /// so the text is protected even before this field is first rendered.
75    pub fn secure(
76        id: impl Into<ElementId>,
77        label: impl Into<SharedString>,
78        state: &Entity<TextFieldState>,
79    ) -> Self {
80        Self::with_editor(id, label, Editor::Secure(state.clone()))
81    }
82
83    fn with_editor(
84        id: impl Into<ElementId>,
85        label: impl Into<SharedString>,
86        editor: Editor,
87    ) -> Self {
88        Self {
89            id: id.into(),
90            label: label.into(),
91            editor,
92            variant: TextFieldVariant::Filled,
93            supporting_text: None,
94            error: None,
95            trailing: None,
96            expanded: None,
97            font_scale: 1.,
98        }
99    }
100
101    pub fn variant(mut self, variant: TextFieldVariant) -> Self {
102        self.variant = variant;
103        self
104    }
105
106    /// Applies the caller's user text scale to the editor, label, and supporting text.
107    pub fn font_scale(mut self, scale: f32) -> Self {
108        self.font_scale = scale;
109        self
110    }
111
112    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
113        self.supporting_text = Some(text.into());
114        self
115    }
116
117    /// Displays an error message in place of the supporting text.
118    pub fn error(mut self, message: impl Into<SharedString>) -> Self {
119        self.error = Some(message.into());
120        self
121    }
122
123    /// Places an addon at the logical end of the editing region.
124    pub fn trailing(mut self, element: impl IntoElement) -> Self {
125        self.trailing = Some(element.into_any_element());
126        self
127    }
128
129    pub(super) fn expanded(mut self, expanded: bool) -> Self {
130        self.expanded = Some(expanded);
131        self
132    }
133}
134
135fn configure_editor<M: InputModeKind>(state: &mut InputBaseState<M>, style: InputEditorStyle) {
136    // The surrounding element exposes one semantic node for the Base focus
137    // handle. Base still owns text layout, key dispatch, and input handling.
138    state.set_accessibility(InputAccessibility::new(None).with_value_exposed(false));
139    state.set_editor_style(style);
140}
141
142type SetValue = Box<dyn Fn(SharedString, &mut Window, &mut App)>;
143
144fn edit_handler<M: InputModeKind>(state: Entity<InputBaseState<M>>) -> SetValue {
145    Box::new(move |value, window, cx| {
146        state.update(cx, |state, cx| {
147            if state.is_editable() {
148                state.replace_all(value, window, cx);
149            }
150        });
151    })
152}
153
154impl RenderOnce for TextField {
155    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
156        use ColorRole::*;
157
158        let theme = window_material_theme(window, cx).clone();
159        let tone = |role| color(theme.colors.color(role));
160        let direction = theme.layout.direction;
161        let presentation = match &self.editor {
162            Editor::Single(state) | Editor::Secure(state) => state.read(cx).presentation(),
163            Editor::Multiple(state) => state.read(cx).presentation(),
164        };
165        let disabled = presentation.is_disabled();
166        let readonly = presentation.is_readonly();
167        let focus = presentation.focus_handle().clone();
168        let focused = !disabled && focus.is_focused(window);
169        let filled = self.variant == TextFieldVariant::Filled;
170        let error = self.error.is_some();
171        let indicator = match (disabled, error, focused) {
172            (true, _, _) => tone(OnSurface).opacity(0.12),
173            (_, true, _) => tone(Error),
174            (_, _, true) => tone(Primary),
175            _ if filled => tone(OnSurfaceVariant),
176            _ => tone(Outline),
177        };
178        let foreground = if disabled {
179            tone(OnSurface).opacity(0.38)
180        } else {
181            tone(OnSurface)
182        };
183        let secondary = if disabled {
184            foreground
185        } else {
186            tone(OnSurfaceVariant)
187        };
188        let label_color = if !disabled && (focused || error) {
189            indicator
190        } else {
191            secondary
192        };
193        let background = if disabled {
194            tone(OnSurface).opacity(0.04)
195        } else {
196            tone(SurfaceContainerHighest)
197        };
198        let radius = px(CornerRole::ExtraSmall.shape().radii(56., 56., direction)[0]);
199        let type_style = LayoutPolicy::scale_text(
200            TypeRole::BodyLarge.style(TypographyEmphasis::Baseline),
201            self.font_scale,
202        );
203        let caption_style = LayoutPolicy::scale_text(
204            TypeRole::BodySmall.style(TypographyEmphasis::Baseline),
205            self.font_scale,
206        );
207        let font = font_for_style(&theme.typography, type_style, cx).family;
208        let has_text = match &self.editor {
209            Editor::Single(state) | Editor::Secure(state) => !state.read(cx).value().is_empty(),
210            Editor::Multiple(state) => !state.read(cx).value().is_empty(),
211        };
212        let effects = theme
213            .motion
214            .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion());
215        let floating = animate(
216            (self.id.clone(), "floating-label"),
217            f32::from(focused || has_text),
218            theme
219                .motion
220                .spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion()),
221            window,
222            cx,
223        )
224        .clamp(0., 1.);
225        let focus_amount = animate(
226            (self.id.clone(), "focus-indicator"),
227            f32::from(focused),
228            effects,
229            window,
230            cx,
231        )
232        .clamp(0., 1.);
233        let error_amount = animate(
234            (self.id.clone(), "error-indicator"),
235            f32::from(error && !disabled),
236            effects,
237            window,
238            cx,
239        )
240        .clamp(0., 1.);
241        let indicator = if disabled {
242            indicator
243        } else {
244            let idle = tone(if filled { OnSurfaceVariant } else { Outline });
245            let active = crate::motion::mix(idle, tone(Primary), focus_amount);
246            crate::motion::mix(active, tone(Error), error_amount)
247        };
248        let label_color = if disabled {
249            label_color
250        } else {
251            let active = crate::motion::mix(secondary, tone(Primary), focus_amount);
252            crate::motion::mix(active, tone(Error), error_amount)
253        };
254        let style = InputEditorStyle {
255            foreground,
256            // Base resolves unset palette fields against its application theme.
257            // Supply every palette field so editor decorations also stay local
258            // when another window uses a different Material appearance.
259            background: tone(SurfaceContainer),
260            border: tone(OutlineVariant),
261            muted_foreground: if has_text {
262                secondary
263            } else {
264                // Base treats exactly transparent ink as an unset palette override.
265                secondary.opacity(floating.max(f32::EPSILON))
266            },
267            caret: if self.expanded.is_some() && readonly {
268                // Base treats zero alpha as unset. A negligible nonzero alpha
269                // hides the caret while the combobox retains focus.
270                tone(Primary).opacity(f32::EPSILON)
271            } else {
272                tone(if error { Error } else { Primary })
273            },
274            selection: tone(Primary).opacity(0.3),
275            ..Default::default()
276        };
277        let label = self.label;
278        let accessible_id = self.id.to_string();
279        let align = if direction == Direction::Rtl {
280            TextAlign::Right
281        } else {
282            TextAlign::Left
283        };
284        let (editor, role, value, set_value): (_, _, _, Option<SetValue>) = match self.editor {
285            Editor::Single(state) => {
286                let role = if presentation.is_masked() {
287                    Role::PasswordInput
288                } else {
289                    Role::TextInput
290                };
291                state.update(cx, |state, cx| {
292                    state.set_text_align(align, cx);
293                    configure_editor(state, style);
294                });
295                let value = (role != Role::PasswordInput).then(|| state.read(cx).value());
296                let set_value = (!readonly && !disabled && role != Role::PasswordInput)
297                    .then(|| edit_handler(state.clone()));
298                (state.into_any_element(), role, value, set_value)
299            }
300            Editor::Multiple(state) => {
301                state.update(cx, |state, cx| {
302                    state.set_text_align(align, cx);
303                    configure_editor(state, style);
304                });
305                let value = state.read(cx).value();
306                let set_value = (!readonly && !disabled).then(|| edit_handler(state.clone()));
307                (
308                    state.into_any_element(),
309                    Role::MultilineTextInput,
310                    Some(value),
311                    set_value,
312                )
313            }
314            Editor::Secure(state) => {
315                state.update(cx, |state, cx| {
316                    if !presentation.is_masked() {
317                        state.set_masked(true, window, cx);
318                    }
319                    state.set_text_align(align, cx);
320                    configure_editor(state, style);
321                });
322                (state.into_any_element(), Role::PasswordInput, None, None)
323            }
324        };
325        let support = self.error.or(self.supporting_text);
326        let label_size = type_style.size + (caption_style.size - type_style.size) * floating;
327        let label_height = type_style.line_height
328            + (caption_style.line_height - type_style.line_height) * floating;
329        let resting_top = (56. - type_style.line_height) * 0.5;
330        let floating_top = if filled {
331            8.
332        } else {
333            -caption_style.line_height * 0.5
334        };
335        let cutout = Rc::new(Cell::new(None::<Bounds<gpui::Pixels>>));
336        let measure_cutout = cutout.clone();
337        let label_top = resting_top + (floating_top - resting_top) * floating;
338        let outline_width = px(1. + focus_amount);
339        let hover = window
340            .use_keyed_state((self.id.clone(), "field-hover"), cx, |_, _| {
341                Rc::new(Cell::new(false))
342            })
343            .read(cx)
344            .clone();
345        let outline_tint = if hover.get() && !disabled && !error {
346            crate::motion::mix(foreground, tone(Primary), focus_amount)
347        } else {
348            indicator
349        };
350        let outline_canvas = (!filled).then(|| {
351            canvas(
352                |_, _, _| (),
353                move |bounds, _, window, _| {
354                    let border = quad(
355                        bounds,
356                        radius,
357                        gpui::transparent_black(),
358                        outline_width,
359                        outline_tint,
360                        BorderStyle::Solid,
361                    );
362                    // The outer edge and stroke width each snap independently.
363                    // Account for their combined rounding when opening the notch.
364                    let device_pixel = px(1. / window.scale_factor());
365                    let Some(label_bounds) = cutout.get().filter(|label| {
366                        label.top() < bounds.top() + outline_width + device_pixel
367                            && label.bottom() > bounds.top() - device_pixel
368                    }) else {
369                        window.paint_quad(border);
370                        return;
371                    };
372                    // The missing stroke must clear the complete label in each
373                    // frame that overlaps it, including when focus is leaving.
374                    let left = label_bounds.left().max(bounds.left());
375                    let right = label_bounds.right().min(bounds.right());
376                    for (min, max) in [
377                        (bounds.origin, point(left, bounds.bottom())),
378                        (point(right, bounds.top()), bounds.bottom_right()),
379                        // Only the bottom edge must be restored between the two
380                        // side masks. Start in the interior, so outward clip
381                        // rounding cannot expose a snapped top-stroke pixel.
382                        (
383                            point(left, bounds.center().y),
384                            point(right, bounds.bottom()),
385                        ),
386                    ] {
387                        window.with_content_mask(
388                            Some(ContentMask {
389                                bounds: Bounds::from_corners(min, max),
390                            }),
391                            |window| window.paint_quad(border.clone()),
392                        );
393                    }
394                },
395            )
396            .absolute()
397            .inset_0()
398        });
399        let label_container = div()
400            .id("label")
401            .test_support()
402            .absolute()
403            .top(px(label_top))
404            .left(px(if filled { 16. } else { 12. }))
405            .right(px(if filled { 16. } else { 12. }))
406            .text_size(px(label_size))
407            .line_height(px(label_height))
408            .text_color(label_color)
409            .flex()
410            .when(direction == Direction::Rtl, Styled::justify_end)
411            .child(
412                div()
413                    .id("label-text")
414                    .test_support()
415                    .min_w_0()
416                    .max_w_full()
417                    .relative()
418                    .truncate()
419                    .when(!filled, |label| label.px(px(4.)))
420                    .child(label.clone())
421                    .when(!filled, |label| {
422                        label.child(
423                            canvas(
424                                move |bounds, _, _| measure_cutout.set(Some(bounds)),
425                                |_, _, _, _| {},
426                            )
427                            .absolute()
428                            .inset_0(),
429                        )
430                    }),
431            )
432            .when(!disabled, |label| {
433                let focus = focus.clone();
434                label.on_mouse_down(MouseButton::Left, move |_, window, cx| {
435                    focus.focus(window, cx);
436                })
437            });
438        div()
439            .id(self.id)
440            .test_support()
441            .w_full()
442            .min_w_0()
443            .flex()
444            .flex_col()
445            .gap(px(4.))
446            .font_family(font)
447            .role(match (self.expanded, readonly) {
448                (Some(_), true) => Role::ComboBox,
449                (Some(_), false) => Role::EditableComboBox,
450                _ => role,
451            })
452            .aria_label(label)
453            .accessibility_id(accessible_id)
454            .aria_placeholder(presentation.placeholder().clone())
455            .when_some(self.expanded, |field, expanded| {
456                field.aria_expanded(expanded)
457            })
458            .when(!disabled, |field| field.track_focus(&focus).tab_stop(false))
459            .when_some(value, |field, value| field.aria_value(value))
460            .when_some(set_value, |field, set_value| {
461                field.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
462                    if let Some(gpui::accesskit::ActionData::Value(value)) = data {
463                        set_value(value.to_string().into(), window, cx);
464                    }
465                })
466            })
467            .when_some(support.clone(), |field, text| field.aria_description(text))
468            .a11y_synthetic_children(move |tree| {
469                let node = tree.parent_node();
470                if error {
471                    node.set_invalid(gpui::accesskit::Invalid::True);
472                }
473                if disabled {
474                    node.set_disabled();
475                }
476                if readonly || disabled {
477                    node.set_read_only();
478                }
479            })
480            .child(
481                div()
482                    .id("container")
483                    .relative()
484                    .flex()
485                    .flex_col()
486                    .when_else(
487                        filled || presentation.is_multi_line(),
488                        Styled::justify_end,
489                        Styled::justify_center,
490                    )
491                    .min_h(px(56.).max(px(type_style.line_height
492                        + if filled {
493                            caption_style.line_height + 16.
494                        } else {
495                            16.
496                        })))
497                    .rounded(radius)
498                    .border_color(indicator)
499                    .px(px(16.))
500                    .py(px(4.))
501                    .when(filled, |mut field| {
502                        // Compose reserves 8 dp above the minimized label and below
503                        // the editor; larger text grows the container instead of overlapping.
504                        field = field
505                            .pt(px(caption_style.line_height + 8.))
506                            .pb(px(8.) - outline_width);
507                        field.style().border_widths.bottom = Some(outline_width.into());
508                        field
509                            .bg(background)
510                            .rounded_b_none()
511                            .when(!disabled && !focused && !error, |field| {
512                                field.hover(|style| style.border_color(foreground))
513                            })
514                    })
515                    .when(!filled && !disabled, |field| {
516                        field.on_hover(move |hovering, window, _| {
517                            if hover.replace(*hovering) != *hovering {
518                                window.refresh();
519                            }
520                        })
521                    })
522                    .children(outline_canvas)
523                    .when(direction == Direction::Rtl, |field| {
524                        field.text_align(TextAlign::Right)
525                    })
526                    .child(
527                        div()
528                            .flex()
529                            .items_center()
530                            .gap(px(8.))
531                            .min_w_0()
532                            .text_size(px(type_style.size))
533                            .line_height(px(type_style.line_height))
534                            .when(direction == Direction::Rtl, |row| row.flex_row_reverse())
535                            .child(div().flex_1().min_w_0().child(editor))
536                            .children(self.trailing),
537                    )
538                    .child(label_container),
539            )
540            .when_some(support, |field, text| {
541                field.child(
542                    div()
543                        .px(px(16.))
544                        .text_size(px(caption_style.size))
545                        .line_height(px(caption_style.line_height))
546                        .text_color(if error && !disabled {
547                            indicator
548                        } else {
549                            secondary
550                        })
551                        .child(text),
552                )
553            })
554    }
555}