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