Skip to main content

gpui_material_components/input/
text_field.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, Bounds, Edges, ElementId, Entity, Hsla, IntoElement, Pixels, SharedString,
5    Window, px,
6};
7use gpui_base::input::{InputBaseState, InputModeKind};
8use gpui_material_foundation::InteractionSource;
9use gpui_material_theme::{CornerShape, TypeStyle};
10
11use super::{TextAreaState, TextFieldState};
12
13mod render;
14
15/// Material text field container treatment. The default is Filled.
16#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
17pub enum TextFieldVariant {
18    #[default]
19    Filled,
20    Outlined,
21}
22
23/// Position of the visual label. Filled uses Inside and Outlined uses Cutout by default.
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub enum TextFieldLabelPosition {
26    /// The minimized label remains within the container, above the editor.
27    Inside,
28    /// The minimized label crosses the container's top edge.
29    Cutout,
30    /// The label is always minimized, with its own row above the container.
31    Above,
32}
33
34/// Horizontal label alignment. Start and End follow the Material theme direction.
35#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
36pub enum TextFieldLabelAlignment {
37    #[default]
38    Start,
39    Center,
40    End,
41}
42
43/// Visibility mode for [`TextField::secure`] editors.
44///
45/// Desktop platforms treat a revealed password as ordinary plain text. `Hidden`
46/// masks the editor with Base's fixed bullet (`•`), disables copy/cut, and omits
47/// the accessible value, accessible `SetValue`, and character count. `Visible`
48/// renders and behaves as plain text.
49#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
50pub enum TextFieldObfuscationMode {
51    #[default]
52    Hidden,
53    Visible,
54}
55
56/// Optional colors for a single text field state. An unset role uses the window theme.
57#[derive(Clone, Copy, Debug, Default)]
58pub struct TextFieldColorOverrides {
59    pub container: Option<Hsla>,
60    pub text: Option<Hsla>,
61    pub label: Option<Hsla>,
62    pub placeholder: Option<Hsla>,
63    pub leading: Option<Hsla>,
64    pub trailing: Option<Hsla>,
65    pub prefix: Option<Hsla>,
66    pub suffix: Option<Hsla>,
67    pub supporting: Option<Hsla>,
68    pub indicator: Option<Hsla>,
69    pub caret: Option<Hsla>,
70    pub selection: Option<Hsla>,
71}
72
73/// Per-instance colors. Disabled takes precedence over invalid, then focused.
74#[derive(Clone, Copy, Debug, Default)]
75pub struct TextFieldColors {
76    pub unfocused: TextFieldColorOverrides,
77    pub focused: TextFieldColorOverrides,
78    pub disabled: TextFieldColorOverrides,
79    pub invalid: TextFieldColorOverrides,
80    pub hovered_indicator: Option<Hsla>,
81}
82
83/// Geometry reported after the retained Base editor lays out the field.
84#[derive(Clone, Copy, Debug, PartialEq)]
85pub struct TextFieldLayout {
86    /// Bounds of the input content area in the window.
87    pub editor_bounds: Bounds<Pixels>,
88    /// Bounds reported by Base for the laid-out text viewport, when available.
89    pub text_bounds: Option<Bounds<Pixels>>,
90    /// Number of wrapped visual lines, independent of row limits and scrolling.
91    pub line_count: usize,
92}
93
94type OnTextLayout = Box<dyn FnOnce(TextFieldLayout, &mut Window, &mut App)>;
95type DropdownRequest = Rc<dyn Fn(bool, &mut Window, &mut App)>;
96type VisibilityCallback = Rc<dyn Fn(bool, &mut Window, &mut App)>;
97
98struct VisibilityToggle {
99    visible: bool,
100    on_toggle: VisibilityCallback,
101}
102
103struct FieldDescription {
104    text: SharedString,
105    content: Option<AnyElement>,
106}
107
108/// A Material presentation for a caller-owned Base text editing entity.
109///
110/// Keep the entity across renders. It owns selection, undo, composition, focus,
111/// and text. Subscribe to [`super::TextFieldEvent`] on the entity to observe user
112/// edits. Set disabled and read-only on the entity before rendering.
113#[derive(IntoElement)]
114pub struct TextField {
115    id: ElementId,
116    label: SharedString,
117    editor: Editor,
118    variant: TextFieldVariant,
119    obfuscation_mode: TextFieldObfuscationMode,
120    show_label: bool,
121    label_content: Option<AnyElement>,
122    label_position: Option<TextFieldLabelPosition>,
123    label_minimized: bool,
124    expanded_alignment: TextFieldLabelAlignment,
125    minimized_alignment: TextFieldLabelAlignment,
126    placeholder: Option<(SharedString, AnyElement)>,
127    supporting: Option<FieldDescription>,
128    error: Option<SharedString>,
129    invalid: bool,
130    required: bool,
131    character_count: Option<usize>,
132    leading: Option<AnyElement>,
133    trailing: Option<AnyElement>,
134    clearable: bool,
135    clear_label: Option<SharedString>,
136    visibility_toggle: Option<VisibilityToggle>,
137    visibility_labels: Option<(SharedString, SharedString)>,
138    prefix: Option<AnyElement>,
139    suffix: Option<AnyElement>,
140    dropdown_editor: bool,
141    expanded: Option<bool>,
142    dropdown_request: Option<DropdownRequest>,
143    font_scale: f32,
144    text_style: Option<TypeStyle>,
145    shape: Option<CornerShape>,
146    content_padding: Option<Edges<Pixels>>,
147    min_height: Option<Pixels>,
148    indicator_width: (Pixels, Pixels),
149    colors: TextFieldColors,
150    on_text_layout: Option<OnTextLayout>,
151    interaction_source: Option<Entity<InteractionSource>>,
152}
153
154#[derive(Clone)]
155enum Editor {
156    Single(Entity<TextFieldState>),
157    Multiple(Entity<TextAreaState>),
158    Secure(Entity<TextFieldState>),
159}
160
161impl Editor {
162    fn layout(&self, cx: &App) -> TextFieldLayout {
163        fn snapshot(state: &InputBaseState<impl InputModeKind>) -> TextFieldLayout {
164            TextFieldLayout {
165                editor_bounds: state.input_bounds(),
166                text_bounds: state.text_bounds(),
167                line_count: state.display_map().wrap_row_count(),
168            }
169        }
170        match self {
171            Self::Single(state) | Self::Secure(state) => snapshot(state.read(cx)),
172            Self::Multiple(state) => snapshot(state.read(cx)),
173        }
174    }
175
176    fn replace_all(&self, value: SharedString, window: &mut Window, cx: &mut App) {
177        fn apply<M: InputModeKind>(
178            state: &Entity<InputBaseState<M>>,
179            value: SharedString,
180            window: &mut Window,
181            cx: &mut App,
182        ) {
183            state.update(cx, |state, cx| {
184                if state.is_editable() {
185                    state.replace_all(value, window, cx);
186                }
187            });
188        }
189        match self {
190            Self::Single(state) | Self::Secure(state) => apply(state, value, window, cx),
191            Self::Multiple(state) => apply(state, value, window, cx),
192        }
193    }
194}
195
196impl TextField {
197    /// Renders a single-line editor.
198    pub fn new(
199        id: impl Into<ElementId>,
200        label: impl Into<SharedString>,
201        state: &Entity<TextFieldState>,
202    ) -> Self {
203        Self::with_editor(id, label, Editor::Single(state.clone()))
204    }
205
206    /// Renders a Filled single-line editor.
207    pub fn filled(
208        id: impl Into<ElementId>,
209        label: impl Into<SharedString>,
210        state: &Entity<TextFieldState>,
211    ) -> Self {
212        Self::new(id, label, state).variant(TextFieldVariant::Filled)
213    }
214
215    /// Renders an Outlined single-line editor.
216    pub fn outlined(
217        id: impl Into<ElementId>,
218        label: impl Into<SharedString>,
219        state: &Entity<TextFieldState>,
220    ) -> Self {
221        Self::new(id, label, state).variant(TextFieldVariant::Outlined)
222    }
223
224    /// Renders a multi-line editor using the row policy configured in its state.
225    pub fn multiline(
226        id: impl Into<ElementId>,
227        label: impl Into<SharedString>,
228        state: &Entity<TextAreaState>,
229    ) -> Self {
230        Self::with_editor(id, label, Editor::Multiple(state.clone()))
231    }
232
233    /// Renders a secure password editor. Defaults to [`TextFieldObfuscationMode::Hidden`],
234    /// masking the value with `•`, blocking copy/cut, and suppressing the accessible value
235    /// and character count. Call [`Self::obfuscation_mode`] with
236    /// [`TextFieldObfuscationMode::Visible`] to reveal plain text.
237    ///
238    /// Use a dedicated entity initialized with `TextFieldState::masked(true)`
239    /// so the text is protected even before this field is first rendered.
240    pub fn secure(
241        id: impl Into<ElementId>,
242        label: impl Into<SharedString>,
243        state: &Entity<TextFieldState>,
244    ) -> Self {
245        Self::with_editor(id, label, Editor::Secure(state.clone()))
246    }
247
248    fn with_editor(
249        id: impl Into<ElementId>,
250        label: impl Into<SharedString>,
251        editor: Editor,
252    ) -> Self {
253        Self {
254            id: id.into(),
255            label: label.into(),
256            editor,
257            variant: TextFieldVariant::Filled,
258            obfuscation_mode: TextFieldObfuscationMode::Hidden,
259            show_label: true,
260            label_content: None,
261            label_position: None,
262            label_minimized: false,
263            expanded_alignment: TextFieldLabelAlignment::Start,
264            minimized_alignment: TextFieldLabelAlignment::Start,
265            placeholder: None,
266            supporting: None,
267            error: None,
268            invalid: false,
269            required: false,
270            character_count: None,
271            leading: None,
272            trailing: None,
273            clearable: false,
274            clear_label: None,
275            visibility_toggle: None,
276            visibility_labels: None,
277            prefix: None,
278            suffix: None,
279            dropdown_editor: false,
280            expanded: None,
281            dropdown_request: None,
282            font_scale: 1.,
283            text_style: None,
284            shape: None,
285            content_padding: None,
286            min_height: None,
287            indicator_width: (px(1.), px(2.)),
288            colors: TextFieldColors::default(),
289            on_text_layout: None,
290            interaction_source: None,
291        }
292    }
293
294    pub fn variant(mut self, variant: TextFieldVariant) -> Self {
295        self.variant = variant;
296        self
297    }
298
299    /// Sets whether a [`TextField::secure`] editor is masked (`Hidden`) or revealed (`Visible`).
300    /// Ignored for non-secure fields.
301    pub fn obfuscation_mode(mut self, mode: TextFieldObfuscationMode) -> Self {
302        self.obfuscation_mode = mode;
303        self
304    }
305
306    /// Displays a trailing clear button when the editor is editable and non-empty.
307    ///
308    /// Activating the button clears the Base state via `replace_all("")` and keeps focus on the
309    /// editor. When combined with `.visibility_toggle(...)` or `.trailing(...)`, built-in controls
310    /// render in logical order before custom trailing content.
311    pub fn clearable(mut self, clearable: bool) -> Self {
312        self.clearable = clearable;
313        self
314    }
315
316    /// Overrides the accessible label of the `.clearable(true)` button (default `"Clear"`).
317    pub fn clear_label(mut self, label: impl Into<SharedString>) -> Self {
318        self.clear_label = Some(label.into());
319        self
320    }
321
322    /// Adds a controlled password reveal toggle on [`TextField::secure`] editors and syncs
323    /// [`Self::obfuscation_mode`] automatically (`Visible` when `visible` is `true`, `Hidden`
324    /// otherwise). Ignored for non-secure fields.
325    pub fn visibility_toggle(
326        mut self,
327        visible: bool,
328        on_toggle: impl Fn(bool, &mut Window, &mut App) + 'static,
329    ) -> Self {
330        self.obfuscation_mode = if visible {
331            TextFieldObfuscationMode::Visible
332        } else {
333            TextFieldObfuscationMode::Hidden
334        };
335        self.visibility_toggle = Some(VisibilityToggle {
336            visible,
337            on_toggle: Rc::new(on_toggle),
338        });
339        self
340    }
341
342    /// Overrides the accessible labels of the `.visibility_toggle(...)` button
343    /// (defaults to `"Show password"` and `"Hide password"`).
344    pub fn visibility_labels(
345        mut self,
346        show: impl Into<SharedString>,
347        hide: impl Into<SharedString>,
348    ) -> Self {
349        self.visibility_labels = Some((show.into(), hide.into()));
350        self
351    }
352
353    /// Applies the caller's user text scale to the editor, label, and supporting text.
354    pub fn font_scale(mut self, scale: f32) -> Self {
355        self.font_scale = scale;
356        self
357    }
358
359    /// Overrides the Material type metrics for input, hint, and affixes before applying font scale.
360    pub fn text_style(mut self, style: TypeStyle) -> Self {
361        self.text_style = Some(style);
362        self
363    }
364
365    /// Overrides the container's logical corner shape. Full uses the laid-out bounds.
366    pub fn shape(mut self, shape: CornerShape) -> Self {
367        self.shape = Some(shape);
368        self
369    }
370
371    /// Sets physical editor insets. An Inside label reserves additional height above the editor.
372    pub fn content_padding(mut self, padding: Edges<Pixels>) -> Self {
373        self.content_padding = Some(padding);
374        self
375    }
376
377    /// Overrides the container's minimum height in logical pixels.
378    ///
379    /// Negative or non-finite values are ignored and keep the density-aware default (`52 dp`
380    /// Compact, `56 dp` Standard, `60 dp` Comfortable). The container still expands to fit its
381    /// text line height, vertical padding, and any inside label reserve.
382    pub fn min_height(mut self, height: Pixels) -> Self {
383        let value = f32::from(height);
384        if value.is_finite() && value >= 0. {
385            self.min_height = Some(height);
386        }
387        self
388    }
389
390    /// Sets the indicator thickness for unfocused and focused states (defaults to `1 px` and `2 px`).
391    ///
392    /// Controls the Filled bottom indicator or the Outlined container border. Pass `px(0.)` to
393    /// omit the indicator or border cleanly. Negative or non-finite values are ignored.
394    pub fn indicator_width(mut self, unfocused: Pixels, focused: Pixels) -> Self {
395        let unfocused_value = f32::from(unfocused);
396        if unfocused_value.is_finite() && unfocused_value >= 0. {
397            self.indicator_width.0 = unfocused;
398        }
399        let focused_value = f32::from(focused);
400        if focused_value.is_finite() && focused_value >= 0. {
401            self.indicator_width.1 = focused;
402        }
403        self
404    }
405
406    /// Applies per-state color overrides while preserving theme defaults for unset colors.
407    pub fn colors(mut self, colors: TextFieldColors) -> Self {
408        self.colors = colors;
409        self
410    }
411
412    /// Called after paint when the editor's reported layout changes. Subscribe to the Base entity
413    /// for text changes that do not affect layout.
414    pub fn on_text_layout(
415        mut self,
416        listener: impl FnOnce(TextFieldLayout, &mut Window, &mut App) + 'static,
417    ) -> Self {
418        self.on_text_layout = Some(Box::new(listener));
419        self
420    }
421
422    /// Observes hover, keyboard-visible focus, and disabled state through a shared source.
423    /// Editing and selection stay with the Base entity.
424    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
425        self.interaction_source = Some(source.clone());
426        self
427    }
428
429    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
430        self.supporting = Some(FieldDescription {
431            text: text.into(),
432            content: None,
433        });
434        self
435    }
436
437    /// Controls whether the visual label is rendered. Defaults to `true`.
438    ///
439    /// When `false`, the constructor's label remains the accessible name (`aria_label`), vertical
440    /// label space is omitted, and placeholders, prefixes, and suffixes stay immediately visible.
441    pub fn show_label(mut self, show: bool) -> Self {
442        self.show_label = show;
443        self
444    }
445
446    /// Replaces the visible label. The constructor label remains the accessible name.
447    pub fn label_content(mut self, element: impl IntoElement) -> Self {
448        self.label_content = Some(element.into_any_element());
449        self
450    }
451
452    pub fn label_position(mut self, position: TextFieldLabelPosition) -> Self {
453        self.label_position = Some(position);
454        self
455    }
456
457    /// Keeps an Inside or Cutout label minimized so affixes and hints can remain visible.
458    pub fn label_always_minimized(mut self, minimized: bool) -> Self {
459        self.label_minimized = minimized;
460        self
461    }
462
463    /// Configures the alignment in each label state. Above uses `minimized`.
464    pub fn label_alignment(
465        mut self,
466        expanded: TextFieldLabelAlignment,
467        minimized: TextFieldLabelAlignment,
468    ) -> Self {
469        self.expanded_alignment = expanded;
470        self.minimized_alignment = minimized;
471        self
472    }
473
474    /// Replaces the Base placeholder's presentation. `hint` is the accessible placeholder.
475    pub fn placeholder_content(
476        mut self,
477        hint: impl Into<SharedString>,
478        element: impl IntoElement,
479    ) -> Self {
480        self.placeholder = Some((hint.into(), element.into_any_element()));
481        self
482    }
483
484    /// Supplies custom supporting content and the field's plain-text accessible description.
485    pub fn supporting_content(
486        mut self,
487        description: impl Into<SharedString>,
488        element: impl IntoElement,
489    ) -> Self {
490        self.supporting = Some(FieldDescription {
491            text: description.into(),
492            content: Some(element.into_any_element()),
493        });
494        self
495    }
496
497    /// Displays an error message in place of the supporting text.
498    pub fn error(mut self, message: impl Into<SharedString>) -> Self {
499        self.error = Some(message.into());
500        self.invalid = true;
501        self
502    }
503
504    /// Sets the invalid visual and accessibility state independently of the supporting content.
505    pub fn invalid(mut self, invalid: bool) -> Self {
506        self.invalid = invalid;
507        self
508    }
509
510    /// Displays a required mark and reports the required state to assistive technology.
511    pub fn required(mut self, required: bool) -> Self {
512        self.required = required;
513        self
514    }
515
516    /// Shows a Unicode scalar count and the supplied limit. Base still owns validation.
517    /// The count is omitted for secure or masked fields.
518    pub fn character_count(mut self, limit: usize) -> Self {
519        self.character_count = Some(limit);
520        self
521    }
522
523    /// Places an adornment in the 48 dp leading icon slot.
524    pub fn leading(mut self, element: impl IntoElement) -> Self {
525        self.leading = Some(element.into_any_element());
526        self
527    }
528
529    /// Places an addon at the logical end of the editing region.
530    pub fn trailing(mut self, element: impl IntoElement) -> Self {
531        self.trailing = Some(element.into_any_element());
532        self
533    }
534
535    /// Places an element before the value while the label is minimized.
536    pub fn prefix(mut self, element: impl IntoElement) -> Self {
537        self.prefix = Some(element.into_any_element());
538        self
539    }
540
541    /// Places an element after the value while the label is minimized.
542    pub fn suffix(mut self, element: impl IntoElement) -> Self {
543        self.suffix = Some(element.into_any_element());
544        self
545    }
546
547    pub(super) fn dropdown(mut self, open: bool, request: Option<DropdownRequest>) -> Self {
548        self.dropdown_editor = true;
549        self.expanded = request.is_some().then_some(open);
550        self.dropdown_request = request;
551        self
552    }
553}