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,
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    label_content: Option<AnyElement>,
121    label_position: Option<TextFieldLabelPosition>,
122    label_minimized: bool,
123    expanded_alignment: TextFieldLabelAlignment,
124    minimized_alignment: TextFieldLabelAlignment,
125    placeholder: Option<(SharedString, AnyElement)>,
126    supporting: Option<FieldDescription>,
127    error: Option<SharedString>,
128    invalid: bool,
129    required: bool,
130    character_count: Option<usize>,
131    leading: Option<AnyElement>,
132    trailing: Option<AnyElement>,
133    clearable: bool,
134    clear_label: Option<SharedString>,
135    visibility_toggle: Option<VisibilityToggle>,
136    visibility_labels: Option<(SharedString, SharedString)>,
137    prefix: Option<AnyElement>,
138    suffix: Option<AnyElement>,
139    dropdown_editor: bool,
140    expanded: Option<bool>,
141    dropdown_request: Option<DropdownRequest>,
142    font_scale: f32,
143    text_style: Option<TypeStyle>,
144    shape: Option<CornerShape>,
145    content_padding: Option<Edges<Pixels>>,
146    colors: TextFieldColors,
147    on_text_layout: Option<OnTextLayout>,
148    interaction_source: Option<Entity<InteractionSource>>,
149}
150
151#[derive(Clone)]
152enum Editor {
153    Single(Entity<TextFieldState>),
154    Multiple(Entity<TextAreaState>),
155    Secure(Entity<TextFieldState>),
156}
157
158impl Editor {
159    fn layout(&self, cx: &App) -> TextFieldLayout {
160        fn snapshot(state: &InputBaseState<impl InputModeKind>) -> TextFieldLayout {
161            TextFieldLayout {
162                editor_bounds: state.input_bounds(),
163                text_bounds: state.text_bounds(),
164                line_count: state.display_map().wrap_row_count(),
165            }
166        }
167        match self {
168            Self::Single(state) | Self::Secure(state) => snapshot(state.read(cx)),
169            Self::Multiple(state) => snapshot(state.read(cx)),
170        }
171    }
172
173    fn replace_all(&self, value: SharedString, window: &mut Window, cx: &mut App) {
174        fn apply<M: InputModeKind>(
175            state: &Entity<InputBaseState<M>>,
176            value: SharedString,
177            window: &mut Window,
178            cx: &mut App,
179        ) {
180            state.update(cx, |state, cx| {
181                if state.is_editable() {
182                    state.replace_all(value, window, cx);
183                }
184            });
185        }
186        match self {
187            Self::Single(state) | Self::Secure(state) => apply(state, value, window, cx),
188            Self::Multiple(state) => apply(state, value, window, cx),
189        }
190    }
191}
192
193impl TextField {
194    /// Renders a single-line editor.
195    pub fn new(
196        id: impl Into<ElementId>,
197        label: impl Into<SharedString>,
198        state: &Entity<TextFieldState>,
199    ) -> Self {
200        Self::with_editor(id, label, Editor::Single(state.clone()))
201    }
202
203    /// Renders a Filled single-line editor.
204    pub fn filled(
205        id: impl Into<ElementId>,
206        label: impl Into<SharedString>,
207        state: &Entity<TextFieldState>,
208    ) -> Self {
209        Self::new(id, label, state).variant(TextFieldVariant::Filled)
210    }
211
212    /// Renders an Outlined single-line editor.
213    pub fn outlined(
214        id: impl Into<ElementId>,
215        label: impl Into<SharedString>,
216        state: &Entity<TextFieldState>,
217    ) -> Self {
218        Self::new(id, label, state).variant(TextFieldVariant::Outlined)
219    }
220
221    /// Renders a multi-line editor using the row policy configured in its state.
222    pub fn multiline(
223        id: impl Into<ElementId>,
224        label: impl Into<SharedString>,
225        state: &Entity<TextAreaState>,
226    ) -> Self {
227        Self::with_editor(id, label, Editor::Multiple(state.clone()))
228    }
229
230    /// Renders a secure password editor. Defaults to [`TextFieldObfuscationMode::Hidden`],
231    /// masking the value with `•`, blocking copy/cut, and suppressing the accessible value
232    /// and character count. Call [`Self::obfuscation_mode`] with
233    /// [`TextFieldObfuscationMode::Visible`] to reveal plain text.
234    ///
235    /// Use a dedicated entity initialized with `TextFieldState::masked(true)`
236    /// so the text is protected even before this field is first rendered.
237    pub fn secure(
238        id: impl Into<ElementId>,
239        label: impl Into<SharedString>,
240        state: &Entity<TextFieldState>,
241    ) -> Self {
242        Self::with_editor(id, label, Editor::Secure(state.clone()))
243    }
244
245    fn with_editor(
246        id: impl Into<ElementId>,
247        label: impl Into<SharedString>,
248        editor: Editor,
249    ) -> Self {
250        Self {
251            id: id.into(),
252            label: label.into(),
253            editor,
254            variant: TextFieldVariant::Filled,
255            obfuscation_mode: TextFieldObfuscationMode::Hidden,
256            label_content: None,
257            label_position: None,
258            label_minimized: false,
259            expanded_alignment: TextFieldLabelAlignment::Start,
260            minimized_alignment: TextFieldLabelAlignment::Start,
261            placeholder: None,
262            supporting: None,
263            error: None,
264            invalid: false,
265            required: false,
266            character_count: None,
267            leading: None,
268            trailing: None,
269            clearable: false,
270            clear_label: None,
271            visibility_toggle: None,
272            visibility_labels: None,
273            prefix: None,
274            suffix: None,
275            dropdown_editor: false,
276            expanded: None,
277            dropdown_request: None,
278            font_scale: 1.,
279            text_style: None,
280            shape: None,
281            content_padding: None,
282            colors: TextFieldColors::default(),
283            on_text_layout: None,
284            interaction_source: None,
285        }
286    }
287
288    pub fn variant(mut self, variant: TextFieldVariant) -> Self {
289        self.variant = variant;
290        self
291    }
292
293    /// Sets whether a [`TextField::secure`] editor is masked (`Hidden`) or revealed (`Visible`).
294    /// Ignored for non-secure fields.
295    pub fn obfuscation_mode(mut self, mode: TextFieldObfuscationMode) -> Self {
296        self.obfuscation_mode = mode;
297        self
298    }
299
300    /// Displays a trailing clear button when the editor is editable and non-empty.
301    ///
302    /// Activating the button clears the Base state via `replace_all("")` and keeps focus on the
303    /// editor. When combined with `.visibility_toggle(...)` or `.trailing(...)`, built-in controls
304    /// render in logical order before custom trailing content.
305    pub fn clearable(mut self, clearable: bool) -> Self {
306        self.clearable = clearable;
307        self
308    }
309
310    /// Overrides the accessible label of the `.clearable(true)` button (default `"Clear"`).
311    pub fn clear_label(mut self, label: impl Into<SharedString>) -> Self {
312        self.clear_label = Some(label.into());
313        self
314    }
315
316    /// Adds a controlled password reveal toggle on [`TextField::secure`] editors and syncs
317    /// [`Self::obfuscation_mode`] automatically (`Visible` when `visible` is `true`, `Hidden`
318    /// otherwise). Ignored for non-secure fields.
319    pub fn visibility_toggle(
320        mut self,
321        visible: bool,
322        on_toggle: impl Fn(bool, &mut Window, &mut App) + 'static,
323    ) -> Self {
324        self.obfuscation_mode = if visible {
325            TextFieldObfuscationMode::Visible
326        } else {
327            TextFieldObfuscationMode::Hidden
328        };
329        self.visibility_toggle = Some(VisibilityToggle {
330            visible,
331            on_toggle: Rc::new(on_toggle),
332        });
333        self
334    }
335
336    /// Overrides the accessible labels of the `.visibility_toggle(...)` button
337    /// (defaults to `"Show password"` and `"Hide password"`).
338    pub fn visibility_labels(
339        mut self,
340        show: impl Into<SharedString>,
341        hide: impl Into<SharedString>,
342    ) -> Self {
343        self.visibility_labels = Some((show.into(), hide.into()));
344        self
345    }
346
347    /// Applies the caller's user text scale to the editor, label, and supporting text.
348    pub fn font_scale(mut self, scale: f32) -> Self {
349        self.font_scale = scale;
350        self
351    }
352
353    /// Overrides the Material type metrics for input, hint, and affixes before applying font scale.
354    pub fn text_style(mut self, style: TypeStyle) -> Self {
355        self.text_style = Some(style);
356        self
357    }
358
359    /// Overrides the container's logical corner shape. Full uses the laid-out bounds.
360    pub fn shape(mut self, shape: CornerShape) -> Self {
361        self.shape = Some(shape);
362        self
363    }
364
365    /// Sets physical editor insets. An Inside label reserves additional height above the editor.
366    pub fn content_padding(mut self, padding: Edges<Pixels>) -> Self {
367        self.content_padding = Some(padding);
368        self
369    }
370
371    /// Applies per-state color overrides while preserving theme defaults for unset colors.
372    pub fn colors(mut self, colors: TextFieldColors) -> Self {
373        self.colors = colors;
374        self
375    }
376
377    /// Called after paint when the editor's reported layout changes. Subscribe to the Base entity
378    /// for text changes that do not affect layout.
379    pub fn on_text_layout(
380        mut self,
381        listener: impl FnOnce(TextFieldLayout, &mut Window, &mut App) + 'static,
382    ) -> Self {
383        self.on_text_layout = Some(Box::new(listener));
384        self
385    }
386
387    /// Observes hover, keyboard-visible focus, and disabled state through a shared source.
388    /// Editing and selection stay with the Base entity.
389    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
390        self.interaction_source = Some(source.clone());
391        self
392    }
393
394    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
395        self.supporting = Some(FieldDescription {
396            text: text.into(),
397            content: None,
398        });
399        self
400    }
401
402    /// Replaces the visible label. The constructor label remains the accessible name.
403    pub fn label_content(mut self, element: impl IntoElement) -> Self {
404        self.label_content = Some(element.into_any_element());
405        self
406    }
407
408    pub fn label_position(mut self, position: TextFieldLabelPosition) -> Self {
409        self.label_position = Some(position);
410        self
411    }
412
413    /// Keeps an Inside or Cutout label minimized so affixes and hints can remain visible.
414    pub fn label_always_minimized(mut self, minimized: bool) -> Self {
415        self.label_minimized = minimized;
416        self
417    }
418
419    /// Configures the alignment in each label state. Above uses `minimized`.
420    pub fn label_alignment(
421        mut self,
422        expanded: TextFieldLabelAlignment,
423        minimized: TextFieldLabelAlignment,
424    ) -> Self {
425        self.expanded_alignment = expanded;
426        self.minimized_alignment = minimized;
427        self
428    }
429
430    /// Replaces the Base placeholder's presentation. `hint` is the accessible placeholder.
431    pub fn placeholder_content(
432        mut self,
433        hint: impl Into<SharedString>,
434        element: impl IntoElement,
435    ) -> Self {
436        self.placeholder = Some((hint.into(), element.into_any_element()));
437        self
438    }
439
440    /// Supplies custom supporting content and the field's plain-text accessible description.
441    pub fn supporting_content(
442        mut self,
443        description: impl Into<SharedString>,
444        element: impl IntoElement,
445    ) -> Self {
446        self.supporting = Some(FieldDescription {
447            text: description.into(),
448            content: Some(element.into_any_element()),
449        });
450        self
451    }
452
453    /// Displays an error message in place of the supporting text.
454    pub fn error(mut self, message: impl Into<SharedString>) -> Self {
455        self.error = Some(message.into());
456        self.invalid = true;
457        self
458    }
459
460    /// Sets the invalid visual and accessibility state independently of the supporting content.
461    pub fn invalid(mut self, invalid: bool) -> Self {
462        self.invalid = invalid;
463        self
464    }
465
466    /// Displays a required mark and reports the required state to assistive technology.
467    pub fn required(mut self, required: bool) -> Self {
468        self.required = required;
469        self
470    }
471
472    /// Shows a Unicode scalar count and the supplied limit. Base still owns validation.
473    /// The count is omitted for secure or masked fields.
474    pub fn character_count(mut self, limit: usize) -> Self {
475        self.character_count = Some(limit);
476        self
477    }
478
479    /// Places an adornment in the 48 dp leading icon slot.
480    pub fn leading(mut self, element: impl IntoElement) -> Self {
481        self.leading = Some(element.into_any_element());
482        self
483    }
484
485    /// Places an addon at the logical end of the editing region.
486    pub fn trailing(mut self, element: impl IntoElement) -> Self {
487        self.trailing = Some(element.into_any_element());
488        self
489    }
490
491    /// Places an element before the value while the label is minimized.
492    pub fn prefix(mut self, element: impl IntoElement) -> Self {
493        self.prefix = Some(element.into_any_element());
494        self
495    }
496
497    /// Places an element after the value while the label is minimized.
498    pub fn suffix(mut self, element: impl IntoElement) -> Self {
499        self.suffix = Some(element.into_any_element());
500        self
501    }
502
503    pub(super) fn dropdown(mut self, open: bool, request: Option<DropdownRequest>) -> Self {
504        self.dropdown_editor = true;
505        self.expanded = request.is_some().then_some(open);
506        self.dropdown_request = request;
507        self
508    }
509}