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/// Optional colors for a single text field state. An unset role uses the window theme.
44#[derive(Clone, Copy, Debug, Default)]
45pub struct TextFieldColorOverrides {
46    pub container: Option<Hsla>,
47    pub text: Option<Hsla>,
48    pub label: Option<Hsla>,
49    pub placeholder: Option<Hsla>,
50    pub leading: Option<Hsla>,
51    pub trailing: Option<Hsla>,
52    pub prefix: Option<Hsla>,
53    pub suffix: Option<Hsla>,
54    pub supporting: Option<Hsla>,
55    pub indicator: Option<Hsla>,
56    pub caret: Option<Hsla>,
57    pub selection: Option<Hsla>,
58}
59
60/// Per-instance colors. Disabled takes precedence over invalid, then focused.
61#[derive(Clone, Copy, Debug, Default)]
62pub struct TextFieldColors {
63    pub unfocused: TextFieldColorOverrides,
64    pub focused: TextFieldColorOverrides,
65    pub disabled: TextFieldColorOverrides,
66    pub invalid: TextFieldColorOverrides,
67    pub hovered_indicator: Option<Hsla>,
68}
69
70/// Geometry reported after the retained Base editor lays out the field.
71#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct TextFieldLayout {
73    /// Bounds of the input content area in the window.
74    pub editor_bounds: Bounds<Pixels>,
75    /// Bounds reported by Base for the laid-out text viewport, when available.
76    pub text_bounds: Option<Bounds<Pixels>>,
77    /// Number of wrapped visual lines, independent of row limits and scrolling.
78    pub line_count: usize,
79}
80
81type OnTextLayout = Box<dyn FnOnce(TextFieldLayout, &mut Window, &mut App)>;
82type DropdownRequest = Rc<dyn Fn(bool, &mut Window, &mut App)>;
83
84struct FieldDescription {
85    text: SharedString,
86    content: Option<AnyElement>,
87}
88
89/// A Material presentation for a caller-owned Base text editing entity.
90///
91/// Keep the entity across renders. It owns selection, undo, composition, focus,
92/// and text. Subscribe to [`super::TextFieldEvent`] on the entity to observe user
93/// edits. Set disabled and read-only on the entity before rendering.
94#[derive(IntoElement)]
95pub struct TextField {
96    id: ElementId,
97    label: SharedString,
98    editor: Editor,
99    variant: TextFieldVariant,
100    label_content: Option<AnyElement>,
101    label_position: Option<TextFieldLabelPosition>,
102    label_minimized: bool,
103    expanded_alignment: TextFieldLabelAlignment,
104    minimized_alignment: TextFieldLabelAlignment,
105    placeholder: Option<(SharedString, AnyElement)>,
106    supporting: Option<FieldDescription>,
107    error: Option<SharedString>,
108    invalid: bool,
109    required: bool,
110    character_count: Option<usize>,
111    leading: Option<AnyElement>,
112    trailing: Option<AnyElement>,
113    prefix: Option<AnyElement>,
114    suffix: Option<AnyElement>,
115    dropdown_editor: bool,
116    expanded: Option<bool>,
117    dropdown_request: Option<DropdownRequest>,
118    font_scale: f32,
119    text_style: Option<TypeStyle>,
120    shape: Option<CornerShape>,
121    content_padding: Option<Edges<Pixels>>,
122    colors: TextFieldColors,
123    on_text_layout: Option<OnTextLayout>,
124    interaction_source: Option<Entity<InteractionSource>>,
125}
126
127#[derive(Clone)]
128enum Editor {
129    Single(Entity<TextFieldState>),
130    Multiple(Entity<TextAreaState>),
131    Secure(Entity<TextFieldState>),
132}
133
134impl Editor {
135    fn layout(&self, cx: &App) -> TextFieldLayout {
136        fn snapshot(state: &InputBaseState<impl InputModeKind>) -> TextFieldLayout {
137            TextFieldLayout {
138                editor_bounds: state.input_bounds(),
139                text_bounds: state.text_bounds(),
140                line_count: state.display_map().wrap_row_count(),
141            }
142        }
143        match self {
144            Self::Single(state) | Self::Secure(state) => snapshot(state.read(cx)),
145            Self::Multiple(state) => snapshot(state.read(cx)),
146        }
147    }
148}
149
150impl TextField {
151    /// Renders a single-line editor.
152    pub fn new(
153        id: impl Into<ElementId>,
154        label: impl Into<SharedString>,
155        state: &Entity<TextFieldState>,
156    ) -> Self {
157        Self::with_editor(id, label, Editor::Single(state.clone()))
158    }
159
160    /// Renders a multi-line editor using the row policy configured in its state.
161    pub fn multiline(
162        id: impl Into<ElementId>,
163        label: impl Into<SharedString>,
164        state: &Entity<TextAreaState>,
165    ) -> Self {
166        Self::with_editor(id, label, Editor::Multiple(state.clone()))
167    }
168
169    /// Always masks the editor and suppresses its value from accessibility.
170    /// Use a dedicated entity initialized with `TextFieldState::masked(true)`
171    /// so the text is protected even before this field is first rendered.
172    pub fn secure(
173        id: impl Into<ElementId>,
174        label: impl Into<SharedString>,
175        state: &Entity<TextFieldState>,
176    ) -> Self {
177        Self::with_editor(id, label, Editor::Secure(state.clone()))
178    }
179
180    fn with_editor(
181        id: impl Into<ElementId>,
182        label: impl Into<SharedString>,
183        editor: Editor,
184    ) -> Self {
185        Self {
186            id: id.into(),
187            label: label.into(),
188            editor,
189            variant: TextFieldVariant::Filled,
190            label_content: None,
191            label_position: None,
192            label_minimized: false,
193            expanded_alignment: TextFieldLabelAlignment::Start,
194            minimized_alignment: TextFieldLabelAlignment::Start,
195            placeholder: None,
196            supporting: None,
197            error: None,
198            invalid: false,
199            required: false,
200            character_count: None,
201            leading: None,
202            trailing: None,
203            prefix: None,
204            suffix: None,
205            dropdown_editor: false,
206            expanded: None,
207            dropdown_request: None,
208            font_scale: 1.,
209            text_style: None,
210            shape: None,
211            content_padding: None,
212            colors: TextFieldColors::default(),
213            on_text_layout: None,
214            interaction_source: None,
215        }
216    }
217
218    pub fn variant(mut self, variant: TextFieldVariant) -> Self {
219        self.variant = variant;
220        self
221    }
222
223    /// Applies the caller's user text scale to the editor, label, and supporting text.
224    pub fn font_scale(mut self, scale: f32) -> Self {
225        self.font_scale = scale;
226        self
227    }
228
229    /// Overrides the Material type metrics for input, hint, and affixes before applying font scale.
230    pub fn text_style(mut self, style: TypeStyle) -> Self {
231        self.text_style = Some(style);
232        self
233    }
234
235    /// Overrides the container's logical corner shape. Full uses the laid-out bounds.
236    pub fn shape(mut self, shape: CornerShape) -> Self {
237        self.shape = Some(shape);
238        self
239    }
240
241    /// Sets physical editor insets. An Inside label reserves additional height above the editor.
242    pub fn content_padding(mut self, padding: Edges<Pixels>) -> Self {
243        self.content_padding = Some(padding);
244        self
245    }
246
247    /// Applies per-state color overrides while preserving theme defaults for unset colors.
248    pub fn colors(mut self, colors: TextFieldColors) -> Self {
249        self.colors = colors;
250        self
251    }
252
253    /// Called after paint when the editor's reported layout changes. Subscribe to the Base entity
254    /// for text changes that do not affect layout.
255    pub fn on_text_layout(
256        mut self,
257        listener: impl FnOnce(TextFieldLayout, &mut Window, &mut App) + 'static,
258    ) -> Self {
259        self.on_text_layout = Some(Box::new(listener));
260        self
261    }
262
263    /// Observes hover, keyboard-visible focus, and disabled state through a shared source.
264    /// Editing and selection stay with the Base entity.
265    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
266        self.interaction_source = Some(source.clone());
267        self
268    }
269
270    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
271        self.supporting = Some(FieldDescription {
272            text: text.into(),
273            content: None,
274        });
275        self
276    }
277
278    /// Replaces the visible label. The constructor label remains the accessible name.
279    pub fn label_content(mut self, element: impl IntoElement) -> Self {
280        self.label_content = Some(element.into_any_element());
281        self
282    }
283
284    pub fn label_position(mut self, position: TextFieldLabelPosition) -> Self {
285        self.label_position = Some(position);
286        self
287    }
288
289    /// Keeps an Inside or Cutout label minimized so affixes and hints can remain visible.
290    pub fn label_always_minimized(mut self, minimized: bool) -> Self {
291        self.label_minimized = minimized;
292        self
293    }
294
295    /// Configures the alignment in each label state. Above uses `minimized`.
296    pub fn label_alignment(
297        mut self,
298        expanded: TextFieldLabelAlignment,
299        minimized: TextFieldLabelAlignment,
300    ) -> Self {
301        self.expanded_alignment = expanded;
302        self.minimized_alignment = minimized;
303        self
304    }
305
306    /// Replaces the Base placeholder's presentation. `hint` is the accessible placeholder.
307    pub fn placeholder_content(
308        mut self,
309        hint: impl Into<SharedString>,
310        element: impl IntoElement,
311    ) -> Self {
312        self.placeholder = Some((hint.into(), element.into_any_element()));
313        self
314    }
315
316    /// Supplies custom supporting content and the field's plain-text accessible description.
317    pub fn supporting_content(
318        mut self,
319        description: impl Into<SharedString>,
320        element: impl IntoElement,
321    ) -> Self {
322        self.supporting = Some(FieldDescription {
323            text: description.into(),
324            content: Some(element.into_any_element()),
325        });
326        self
327    }
328
329    /// Displays an error message in place of the supporting text.
330    pub fn error(mut self, message: impl Into<SharedString>) -> Self {
331        self.error = Some(message.into());
332        self.invalid = true;
333        self
334    }
335
336    /// Sets the invalid visual and accessibility state independently of the supporting content.
337    pub fn invalid(mut self, invalid: bool) -> Self {
338        self.invalid = invalid;
339        self
340    }
341
342    /// Displays a required mark and reports the required state to assistive technology.
343    pub fn required(mut self, required: bool) -> Self {
344        self.required = required;
345        self
346    }
347
348    /// Shows a Unicode scalar count and the supplied limit. Base still owns validation.
349    /// The count is omitted for secure or masked fields.
350    pub fn character_count(mut self, limit: usize) -> Self {
351        self.character_count = Some(limit);
352        self
353    }
354
355    /// Places an adornment in the 48 dp leading icon slot.
356    pub fn leading(mut self, element: impl IntoElement) -> Self {
357        self.leading = Some(element.into_any_element());
358        self
359    }
360
361    /// Places an addon at the logical end of the editing region.
362    pub fn trailing(mut self, element: impl IntoElement) -> Self {
363        self.trailing = Some(element.into_any_element());
364        self
365    }
366
367    /// Places an element before the value while the label is minimized.
368    pub fn prefix(mut self, element: impl IntoElement) -> Self {
369        self.prefix = Some(element.into_any_element());
370        self
371    }
372
373    /// Places an element after the value while the label is minimized.
374    pub fn suffix(mut self, element: impl IntoElement) -> Self {
375        self.suffix = Some(element.into_any_element());
376        self
377    }
378
379    pub(super) fn dropdown(mut self, open: bool, request: Option<DropdownRequest>) -> Self {
380        self.dropdown_editor = true;
381        self.expanded = request.is_some().then_some(open);
382        self.dropdown_request = request;
383        self
384    }
385}