Skip to main content

gpui_material_components/input/
text_field.rs

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