gpui-material-components 0.3.0

Material 3 Expressive desktop components for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use std::rc::Rc;

use gpui::{
    AnyElement, App, Bounds, Edges, ElementId, Entity, Hsla, IntoElement, Pixels, SharedString,
    Window,
};
use gpui_base::input::{InputBaseState, InputModeKind};
use gpui_material_foundation::InteractionSource;
use gpui_material_theme::{CornerShape, TypeStyle};

use super::{TextAreaState, TextFieldState};

mod render;

/// Material text field container treatment. The default is Filled.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TextFieldVariant {
    #[default]
    Filled,
    Outlined,
}

/// Position of the visual label. Filled uses Inside and Outlined uses Cutout by default.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextFieldLabelPosition {
    /// The minimized label remains within the container, above the editor.
    Inside,
    /// The minimized label crosses the container's top edge.
    Cutout,
    /// The label is always minimized, with its own row above the container.
    Above,
}

/// Horizontal label alignment. Start and End follow the Material theme direction.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TextFieldLabelAlignment {
    #[default]
    Start,
    Center,
    End,
}

/// Visibility mode for [`TextField::secure`] editors.
///
/// Desktop platforms treat a revealed password as ordinary plain text. `Hidden`
/// masks the editor with Base's fixed bullet (`•`), disables copy/cut, and omits
/// the accessible value, accessible `SetValue`, and character count. `Visible`
/// renders and behaves as plain text.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TextFieldObfuscationMode {
    #[default]
    Hidden,
    Visible,
}

/// Optional colors for a single text field state. An unset role uses the window theme.
#[derive(Clone, Copy, Debug, Default)]
pub struct TextFieldColorOverrides {
    pub container: Option<Hsla>,
    pub text: Option<Hsla>,
    pub label: Option<Hsla>,
    pub placeholder: Option<Hsla>,
    pub leading: Option<Hsla>,
    pub trailing: Option<Hsla>,
    pub prefix: Option<Hsla>,
    pub suffix: Option<Hsla>,
    pub supporting: Option<Hsla>,
    pub indicator: Option<Hsla>,
    pub caret: Option<Hsla>,
    pub selection: Option<Hsla>,
}

/// Per-instance colors. Disabled takes precedence over invalid, then focused.
#[derive(Clone, Copy, Debug, Default)]
pub struct TextFieldColors {
    pub unfocused: TextFieldColorOverrides,
    pub focused: TextFieldColorOverrides,
    pub disabled: TextFieldColorOverrides,
    pub invalid: TextFieldColorOverrides,
    pub hovered_indicator: Option<Hsla>,
}

/// Geometry reported after the retained Base editor lays out the field.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextFieldLayout {
    /// Bounds of the input content area in the window.
    pub editor_bounds: Bounds<Pixels>,
    /// Bounds reported by Base for the laid-out text viewport, when available.
    pub text_bounds: Option<Bounds<Pixels>>,
    /// Number of wrapped visual lines, independent of row limits and scrolling.
    pub line_count: usize,
}

type OnTextLayout = Box<dyn FnOnce(TextFieldLayout, &mut Window, &mut App)>;
type DropdownRequest = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type VisibilityCallback = Rc<dyn Fn(bool, &mut Window, &mut App)>;

struct VisibilityToggle {
    visible: bool,
    on_toggle: VisibilityCallback,
}

struct FieldDescription {
    text: SharedString,
    content: Option<AnyElement>,
}

/// A Material presentation for a caller-owned Base text editing entity.
///
/// Keep the entity across renders. It owns selection, undo, composition, focus,
/// and text. Subscribe to [`super::TextFieldEvent`] on the entity to observe user
/// edits. Set disabled and read-only on the entity before rendering.
#[derive(IntoElement)]
pub struct TextField {
    id: ElementId,
    label: SharedString,
    editor: Editor,
    variant: TextFieldVariant,
    obfuscation_mode: TextFieldObfuscationMode,
    label_content: Option<AnyElement>,
    label_position: Option<TextFieldLabelPosition>,
    label_minimized: bool,
    expanded_alignment: TextFieldLabelAlignment,
    minimized_alignment: TextFieldLabelAlignment,
    placeholder: Option<(SharedString, AnyElement)>,
    supporting: Option<FieldDescription>,
    error: Option<SharedString>,
    invalid: bool,
    required: bool,
    character_count: Option<usize>,
    leading: Option<AnyElement>,
    trailing: Option<AnyElement>,
    clearable: bool,
    clear_label: Option<SharedString>,
    visibility_toggle: Option<VisibilityToggle>,
    visibility_labels: Option<(SharedString, SharedString)>,
    prefix: Option<AnyElement>,
    suffix: Option<AnyElement>,
    dropdown_editor: bool,
    expanded: Option<bool>,
    dropdown_request: Option<DropdownRequest>,
    font_scale: f32,
    text_style: Option<TypeStyle>,
    shape: Option<CornerShape>,
    content_padding: Option<Edges<Pixels>>,
    colors: TextFieldColors,
    on_text_layout: Option<OnTextLayout>,
    interaction_source: Option<Entity<InteractionSource>>,
}

#[derive(Clone)]
enum Editor {
    Single(Entity<TextFieldState>),
    Multiple(Entity<TextAreaState>),
    Secure(Entity<TextFieldState>),
}

impl Editor {
    fn layout(&self, cx: &App) -> TextFieldLayout {
        fn snapshot(state: &InputBaseState<impl InputModeKind>) -> TextFieldLayout {
            TextFieldLayout {
                editor_bounds: state.input_bounds(),
                text_bounds: state.text_bounds(),
                line_count: state.display_map().wrap_row_count(),
            }
        }
        match self {
            Self::Single(state) | Self::Secure(state) => snapshot(state.read(cx)),
            Self::Multiple(state) => snapshot(state.read(cx)),
        }
    }

    fn replace_all(&self, value: SharedString, window: &mut Window, cx: &mut App) {
        fn apply<M: InputModeKind>(
            state: &Entity<InputBaseState<M>>,
            value: SharedString,
            window: &mut Window,
            cx: &mut App,
        ) {
            state.update(cx, |state, cx| {
                if state.is_editable() {
                    state.replace_all(value, window, cx);
                }
            });
        }
        match self {
            Self::Single(state) | Self::Secure(state) => apply(state, value, window, cx),
            Self::Multiple(state) => apply(state, value, window, cx),
        }
    }
}

impl TextField {
    /// Renders a single-line editor.
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        state: &Entity<TextFieldState>,
    ) -> Self {
        Self::with_editor(id, label, Editor::Single(state.clone()))
    }

    /// Renders a Filled single-line editor.
    pub fn filled(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        state: &Entity<TextFieldState>,
    ) -> Self {
        Self::new(id, label, state).variant(TextFieldVariant::Filled)
    }

    /// Renders an Outlined single-line editor.
    pub fn outlined(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        state: &Entity<TextFieldState>,
    ) -> Self {
        Self::new(id, label, state).variant(TextFieldVariant::Outlined)
    }

    /// Renders a multi-line editor using the row policy configured in its state.
    pub fn multiline(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        state: &Entity<TextAreaState>,
    ) -> Self {
        Self::with_editor(id, label, Editor::Multiple(state.clone()))
    }

    /// Renders a secure password editor. Defaults to [`TextFieldObfuscationMode::Hidden`],
    /// masking the value with `•`, blocking copy/cut, and suppressing the accessible value
    /// and character count. Call [`Self::obfuscation_mode`] with
    /// [`TextFieldObfuscationMode::Visible`] to reveal plain text.
    ///
    /// Use a dedicated entity initialized with `TextFieldState::masked(true)`
    /// so the text is protected even before this field is first rendered.
    pub fn secure(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        state: &Entity<TextFieldState>,
    ) -> Self {
        Self::with_editor(id, label, Editor::Secure(state.clone()))
    }

    fn with_editor(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        editor: Editor,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            editor,
            variant: TextFieldVariant::Filled,
            obfuscation_mode: TextFieldObfuscationMode::Hidden,
            label_content: None,
            label_position: None,
            label_minimized: false,
            expanded_alignment: TextFieldLabelAlignment::Start,
            minimized_alignment: TextFieldLabelAlignment::Start,
            placeholder: None,
            supporting: None,
            error: None,
            invalid: false,
            required: false,
            character_count: None,
            leading: None,
            trailing: None,
            clearable: false,
            clear_label: None,
            visibility_toggle: None,
            visibility_labels: None,
            prefix: None,
            suffix: None,
            dropdown_editor: false,
            expanded: None,
            dropdown_request: None,
            font_scale: 1.,
            text_style: None,
            shape: None,
            content_padding: None,
            colors: TextFieldColors::default(),
            on_text_layout: None,
            interaction_source: None,
        }
    }

    pub fn variant(mut self, variant: TextFieldVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Sets whether a [`TextField::secure`] editor is masked (`Hidden`) or revealed (`Visible`).
    /// Ignored for non-secure fields.
    pub fn obfuscation_mode(mut self, mode: TextFieldObfuscationMode) -> Self {
        self.obfuscation_mode = mode;
        self
    }

    /// Displays a trailing clear button when the editor is editable and non-empty.
    ///
    /// Activating the button clears the Base state via `replace_all("")` and keeps focus on the
    /// editor. When combined with `.visibility_toggle(...)` or `.trailing(...)`, built-in controls
    /// render in logical order before custom trailing content.
    pub fn clearable(mut self, clearable: bool) -> Self {
        self.clearable = clearable;
        self
    }

    /// Overrides the accessible label of the `.clearable(true)` button (default `"Clear"`).
    pub fn clear_label(mut self, label: impl Into<SharedString>) -> Self {
        self.clear_label = Some(label.into());
        self
    }

    /// Adds a controlled password reveal toggle on [`TextField::secure`] editors and syncs
    /// [`Self::obfuscation_mode`] automatically (`Visible` when `visible` is `true`, `Hidden`
    /// otherwise). Ignored for non-secure fields.
    pub fn visibility_toggle(
        mut self,
        visible: bool,
        on_toggle: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.obfuscation_mode = if visible {
            TextFieldObfuscationMode::Visible
        } else {
            TextFieldObfuscationMode::Hidden
        };
        self.visibility_toggle = Some(VisibilityToggle {
            visible,
            on_toggle: Rc::new(on_toggle),
        });
        self
    }

    /// Overrides the accessible labels of the `.visibility_toggle(...)` button
    /// (defaults to `"Show password"` and `"Hide password"`).
    pub fn visibility_labels(
        mut self,
        show: impl Into<SharedString>,
        hide: impl Into<SharedString>,
    ) -> Self {
        self.visibility_labels = Some((show.into(), hide.into()));
        self
    }

    /// Applies the caller's user text scale to the editor, label, and supporting text.
    pub fn font_scale(mut self, scale: f32) -> Self {
        self.font_scale = scale;
        self
    }

    /// Overrides the Material type metrics for input, hint, and affixes before applying font scale.
    pub fn text_style(mut self, style: TypeStyle) -> Self {
        self.text_style = Some(style);
        self
    }

    /// Overrides the container's logical corner shape. Full uses the laid-out bounds.
    pub fn shape(mut self, shape: CornerShape) -> Self {
        self.shape = Some(shape);
        self
    }

    /// Sets physical editor insets. An Inside label reserves additional height above the editor.
    pub fn content_padding(mut self, padding: Edges<Pixels>) -> Self {
        self.content_padding = Some(padding);
        self
    }

    /// Applies per-state color overrides while preserving theme defaults for unset colors.
    pub fn colors(mut self, colors: TextFieldColors) -> Self {
        self.colors = colors;
        self
    }

    /// Called after paint when the editor's reported layout changes. Subscribe to the Base entity
    /// for text changes that do not affect layout.
    pub fn on_text_layout(
        mut self,
        listener: impl FnOnce(TextFieldLayout, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_text_layout = Some(Box::new(listener));
        self
    }

    /// Observes hover, keyboard-visible focus, and disabled state through a shared source.
    /// Editing and selection stay with the Base entity.
    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.interaction_source = Some(source.clone());
        self
    }

    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
        self.supporting = Some(FieldDescription {
            text: text.into(),
            content: None,
        });
        self
    }

    /// Replaces the visible label. The constructor label remains the accessible name.
    pub fn label_content(mut self, element: impl IntoElement) -> Self {
        self.label_content = Some(element.into_any_element());
        self
    }

    pub fn label_position(mut self, position: TextFieldLabelPosition) -> Self {
        self.label_position = Some(position);
        self
    }

    /// Keeps an Inside or Cutout label minimized so affixes and hints can remain visible.
    pub fn label_always_minimized(mut self, minimized: bool) -> Self {
        self.label_minimized = minimized;
        self
    }

    /// Configures the alignment in each label state. Above uses `minimized`.
    pub fn label_alignment(
        mut self,
        expanded: TextFieldLabelAlignment,
        minimized: TextFieldLabelAlignment,
    ) -> Self {
        self.expanded_alignment = expanded;
        self.minimized_alignment = minimized;
        self
    }

    /// Replaces the Base placeholder's presentation. `hint` is the accessible placeholder.
    pub fn placeholder_content(
        mut self,
        hint: impl Into<SharedString>,
        element: impl IntoElement,
    ) -> Self {
        self.placeholder = Some((hint.into(), element.into_any_element()));
        self
    }

    /// Supplies custom supporting content and the field's plain-text accessible description.
    pub fn supporting_content(
        mut self,
        description: impl Into<SharedString>,
        element: impl IntoElement,
    ) -> Self {
        self.supporting = Some(FieldDescription {
            text: description.into(),
            content: Some(element.into_any_element()),
        });
        self
    }

    /// Displays an error message in place of the supporting text.
    pub fn error(mut self, message: impl Into<SharedString>) -> Self {
        self.error = Some(message.into());
        self.invalid = true;
        self
    }

    /// Sets the invalid visual and accessibility state independently of the supporting content.
    pub fn invalid(mut self, invalid: bool) -> Self {
        self.invalid = invalid;
        self
    }

    /// Displays a required mark and reports the required state to assistive technology.
    pub fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    /// Shows a Unicode scalar count and the supplied limit. Base still owns validation.
    /// The count is omitted for secure or masked fields.
    pub fn character_count(mut self, limit: usize) -> Self {
        self.character_count = Some(limit);
        self
    }

    /// Places an adornment in the 48 dp leading icon slot.
    pub fn leading(mut self, element: impl IntoElement) -> Self {
        self.leading = Some(element.into_any_element());
        self
    }

    /// Places an addon at the logical end of the editing region.
    pub fn trailing(mut self, element: impl IntoElement) -> Self {
        self.trailing = Some(element.into_any_element());
        self
    }

    /// Places an element before the value while the label is minimized.
    pub fn prefix(mut self, element: impl IntoElement) -> Self {
        self.prefix = Some(element.into_any_element());
        self
    }

    /// Places an element after the value while the label is minimized.
    pub fn suffix(mut self, element: impl IntoElement) -> Self {
        self.suffix = Some(element.into_any_element());
        self
    }

    pub(super) fn dropdown(mut self, open: bool, request: Option<DropdownRequest>) -> Self {
        self.dropdown_editor = true;
        self.expanded = request.is_some().then_some(open);
        self.dropdown_request = request;
        self
    }
}