gpui-material-components 0.1.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
use std::{cell::Cell, rc::Rc};

use gpui::{
    AccessibleAction, AnyElement, App, BorderStyle, Bounds, ContentMask, ElementId, Entity,
    InteractiveElement, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
    StatefulInteractiveElement, Styled, TextAlign, Window, canvas, div, point,
    prelude::FluentBuilder, px, quad,
};
use gpui_base::{
    TestSupportExt,
    input::{InputAccessibility, InputBaseState, InputEditorStyle, InputModeKind},
};
use gpui_material_foundation::{animate, color, font_for_style, window_material_theme};
use gpui_material_theme::{
    ColorRole, CornerRole, Direction, LayoutPolicy, MotionKind, MotionSpeed, TypeRole,
    TypographyEmphasis,
};

use super::{TextAreaState, TextFieldState};

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

/// 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,
    supporting_text: Option<SharedString>,
    error: Option<SharedString>,
    trailing: Option<AnyElement>,
    expanded: Option<bool>,
    font_scale: f32,
}

enum Editor {
    Single(Entity<TextFieldState>),
    Multiple(Entity<TextAreaState>),
    Secure(Entity<TextFieldState>),
}

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 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()))
    }

    /// Always masks the editor and suppresses its value from accessibility.
    /// 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,
            supporting_text: None,
            error: None,
            trailing: None,
            expanded: None,
            font_scale: 1.,
        }
    }

    pub fn variant(mut self, variant: TextFieldVariant) -> Self {
        self.variant = variant;
        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
    }

    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
        self.supporting_text = Some(text.into());
        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
    }

    /// 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
    }

    pub(super) fn expanded(mut self, expanded: bool) -> Self {
        self.expanded = Some(expanded);
        self
    }
}

fn configure_editor<M: InputModeKind>(state: &mut InputBaseState<M>, style: InputEditorStyle) {
    // The surrounding element exposes one semantic node for the Base focus
    // handle. Base still owns text layout, key dispatch, and input handling.
    state.set_accessibility(InputAccessibility::new(None).with_value_exposed(false));
    state.set_editor_style(style);
}

type SetValue = Box<dyn Fn(SharedString, &mut Window, &mut App)>;

fn edit_handler<M: InputModeKind>(state: Entity<InputBaseState<M>>) -> SetValue {
    Box::new(move |value, window, cx| {
        state.update(cx, |state, cx| {
            if state.is_editable() {
                state.replace_all(value, window, cx);
            }
        });
    })
}

impl RenderOnce for TextField {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        use ColorRole::*;

        let theme = window_material_theme(window, cx).clone();
        let tone = |role| color(theme.colors.color(role));
        let direction = theme.layout.direction;
        let presentation = match &self.editor {
            Editor::Single(state) | Editor::Secure(state) => state.read(cx).presentation(),
            Editor::Multiple(state) => state.read(cx).presentation(),
        };
        let disabled = presentation.is_disabled();
        let readonly = presentation.is_readonly();
        let focus = presentation.focus_handle().clone();
        let focused = !disabled && focus.is_focused(window);
        let filled = self.variant == TextFieldVariant::Filled;
        let error = self.error.is_some();
        let indicator = match (disabled, error, focused) {
            (true, _, _) => tone(OnSurface).opacity(0.12),
            (_, true, _) => tone(Error),
            (_, _, true) => tone(Primary),
            _ if filled => tone(OnSurfaceVariant),
            _ => tone(Outline),
        };
        let foreground = if disabled {
            tone(OnSurface).opacity(0.38)
        } else {
            tone(OnSurface)
        };
        let secondary = if disabled {
            foreground
        } else {
            tone(OnSurfaceVariant)
        };
        let label_color = if !disabled && (focused || error) {
            indicator
        } else {
            secondary
        };
        let background = if disabled {
            tone(OnSurface).opacity(0.04)
        } else {
            tone(SurfaceContainerHighest)
        };
        let radius = px(CornerRole::ExtraSmall.shape().radii(56., 56., direction)[0]);
        let type_style = LayoutPolicy::scale_text(
            TypeRole::BodyLarge.style(TypographyEmphasis::Baseline),
            self.font_scale,
        );
        let caption_style = LayoutPolicy::scale_text(
            TypeRole::BodySmall.style(TypographyEmphasis::Baseline),
            self.font_scale,
        );
        let font = font_for_style(&theme.typography, type_style, cx).family;
        let has_text = match &self.editor {
            Editor::Single(state) | Editor::Secure(state) => !state.read(cx).value().is_empty(),
            Editor::Multiple(state) => !state.read(cx).value().is_empty(),
        };
        let effects = theme
            .motion
            .spec(MotionKind::Effects, MotionSpeed::Fast, cx.reduce_motion());
        let floating = animate(
            (self.id.clone(), "floating-label"),
            f32::from(focused || has_text),
            theme
                .motion
                .spec(MotionKind::Spatial, MotionSpeed::Fast, cx.reduce_motion()),
            window,
            cx,
        )
        .clamp(0., 1.);
        let focus_amount = animate(
            (self.id.clone(), "focus-indicator"),
            f32::from(focused),
            effects,
            window,
            cx,
        )
        .clamp(0., 1.);
        let error_amount = animate(
            (self.id.clone(), "error-indicator"),
            f32::from(error && !disabled),
            effects,
            window,
            cx,
        )
        .clamp(0., 1.);
        let indicator = if disabled {
            indicator
        } else {
            let idle = tone(if filled { OnSurfaceVariant } else { Outline });
            let active = crate::motion::mix(idle, tone(Primary), focus_amount);
            crate::motion::mix(active, tone(Error), error_amount)
        };
        let label_color = if disabled {
            label_color
        } else {
            let active = crate::motion::mix(secondary, tone(Primary), focus_amount);
            crate::motion::mix(active, tone(Error), error_amount)
        };
        let style = InputEditorStyle {
            foreground,
            // Base resolves unset palette fields against its application theme.
            // Supply every palette field so editor decorations also stay local
            // when another window uses a different Material appearance.
            background: tone(SurfaceContainer),
            border: tone(OutlineVariant),
            muted_foreground: if has_text {
                secondary
            } else {
                // Base treats exactly transparent ink as an unset palette override.
                secondary.opacity(floating.max(f32::EPSILON))
            },
            caret: if self.expanded.is_some() && readonly {
                // Base treats zero alpha as unset. A negligible nonzero alpha
                // hides the caret while the combobox retains focus.
                tone(Primary).opacity(f32::EPSILON)
            } else {
                tone(if error { Error } else { Primary })
            },
            selection: tone(Primary).opacity(0.3),
            ..Default::default()
        };
        let label = self.label;
        let accessible_id = self.id.to_string();
        let align = if direction == Direction::Rtl {
            TextAlign::Right
        } else {
            TextAlign::Left
        };
        let (editor, role, value, set_value): (_, _, _, Option<SetValue>) = match self.editor {
            Editor::Single(state) => {
                let role = if presentation.is_masked() {
                    Role::PasswordInput
                } else {
                    Role::TextInput
                };
                state.update(cx, |state, cx| {
                    state.set_text_align(align, cx);
                    configure_editor(state, style);
                });
                let value = (role != Role::PasswordInput).then(|| state.read(cx).value());
                let set_value = (!readonly && !disabled && role != Role::PasswordInput)
                    .then(|| edit_handler(state.clone()));
                (state.into_any_element(), role, value, set_value)
            }
            Editor::Multiple(state) => {
                state.update(cx, |state, cx| {
                    state.set_text_align(align, cx);
                    configure_editor(state, style);
                });
                let value = state.read(cx).value();
                let set_value = (!readonly && !disabled).then(|| edit_handler(state.clone()));
                (
                    state.into_any_element(),
                    Role::MultilineTextInput,
                    Some(value),
                    set_value,
                )
            }
            Editor::Secure(state) => {
                state.update(cx, |state, cx| {
                    if !presentation.is_masked() {
                        state.set_masked(true, window, cx);
                    }
                    state.set_text_align(align, cx);
                    configure_editor(state, style);
                });
                (state.into_any_element(), Role::PasswordInput, None, None)
            }
        };
        let support = self.error.or(self.supporting_text);
        let label_size = type_style.size + (caption_style.size - type_style.size) * floating;
        let label_height = type_style.line_height
            + (caption_style.line_height - type_style.line_height) * floating;
        let resting_top = (56. - type_style.line_height) * 0.5;
        let floating_top = if filled {
            8.
        } else {
            -caption_style.line_height * 0.5
        };
        let cutout = Rc::new(Cell::new(None::<Bounds<gpui::Pixels>>));
        let measure_cutout = cutout.clone();
        let label_top = resting_top + (floating_top - resting_top) * floating;
        let outline_width = px(1. + focus_amount);
        let hover = window
            .use_keyed_state((self.id.clone(), "field-hover"), cx, |_, _| {
                Rc::new(Cell::new(false))
            })
            .read(cx)
            .clone();
        let outline_tint = if hover.get() && !disabled && !error {
            crate::motion::mix(foreground, tone(Primary), focus_amount)
        } else {
            indicator
        };
        let outline_canvas = (!filled).then(|| {
            canvas(
                |_, _, _| (),
                move |bounds, _, window, _| {
                    let border = quad(
                        bounds,
                        radius,
                        gpui::transparent_black(),
                        outline_width,
                        outline_tint,
                        BorderStyle::Solid,
                    );
                    // The outer edge and stroke width each snap independently.
                    // Account for their combined rounding when opening the notch.
                    let device_pixel = px(1. / window.scale_factor());
                    let Some(label_bounds) = cutout.get().filter(|label| {
                        label.top() < bounds.top() + outline_width + device_pixel
                            && label.bottom() > bounds.top() - device_pixel
                    }) else {
                        window.paint_quad(border);
                        return;
                    };
                    // The missing stroke must clear the complete label in each
                    // frame that overlaps it, including when focus is leaving.
                    let left = label_bounds.left().max(bounds.left());
                    let right = label_bounds.right().min(bounds.right());
                    for (min, max) in [
                        (bounds.origin, point(left, bounds.bottom())),
                        (point(right, bounds.top()), bounds.bottom_right()),
                        // Only the bottom edge must be restored between the two
                        // side masks. Start in the interior, so outward clip
                        // rounding cannot expose a snapped top-stroke pixel.
                        (
                            point(left, bounds.center().y),
                            point(right, bounds.bottom()),
                        ),
                    ] {
                        window.with_content_mask(
                            Some(ContentMask {
                                bounds: Bounds::from_corners(min, max),
                            }),
                            |window| window.paint_quad(border.clone()),
                        );
                    }
                },
            )
            .absolute()
            .inset_0()
        });
        let label_container = div()
            .id("label")
            .test_support()
            .absolute()
            .top(px(label_top))
            .left(px(if filled { 16. } else { 12. }))
            .right(px(if filled { 16. } else { 12. }))
            .text_size(px(label_size))
            .line_height(px(label_height))
            .text_color(label_color)
            .flex()
            .when(direction == Direction::Rtl, Styled::justify_end)
            .child(
                div()
                    .id("label-text")
                    .test_support()
                    .min_w_0()
                    .max_w_full()
                    .relative()
                    .truncate()
                    .when(!filled, |label| label.px(px(4.)))
                    .child(label.clone())
                    .when(!filled, |label| {
                        label.child(
                            canvas(
                                move |bounds, _, _| measure_cutout.set(Some(bounds)),
                                |_, _, _, _| {},
                            )
                            .absolute()
                            .inset_0(),
                        )
                    }),
            )
            .when(!disabled, |label| {
                let focus = focus.clone();
                label.on_mouse_down(MouseButton::Left, move |_, window, cx| {
                    focus.focus(window, cx);
                })
            });
        div()
            .id(self.id)
            .test_support()
            .w_full()
            .min_w_0()
            .flex()
            .flex_col()
            .gap(px(4.))
            .font_family(font)
            .role(match (self.expanded, readonly) {
                (Some(_), true) => Role::ComboBox,
                (Some(_), false) => Role::EditableComboBox,
                _ => role,
            })
            .aria_label(label)
            .accessibility_id(accessible_id)
            .aria_placeholder(presentation.placeholder().clone())
            .when_some(self.expanded, |field, expanded| {
                field.aria_expanded(expanded)
            })
            .when(!disabled, |field| field.track_focus(&focus).tab_stop(false))
            .when_some(value, |field, value| field.aria_value(value))
            .when_some(set_value, |field, set_value| {
                field.on_a11y_action(AccessibleAction::SetValue, move |data, window, cx| {
                    if let Some(gpui::accesskit::ActionData::Value(value)) = data {
                        set_value(value.to_string().into(), window, cx);
                    }
                })
            })
            .when_some(support.clone(), |field, text| field.aria_description(text))
            .a11y_synthetic_children(move |tree| {
                let node = tree.parent_node();
                if error {
                    node.set_invalid(gpui::accesskit::Invalid::True);
                }
                if disabled {
                    node.set_disabled();
                }
                if readonly || disabled {
                    node.set_read_only();
                }
            })
            .child(
                div()
                    .id("container")
                    .relative()
                    .flex()
                    .flex_col()
                    .when_else(
                        filled || presentation.is_multi_line(),
                        Styled::justify_end,
                        Styled::justify_center,
                    )
                    .min_h(px(56.).max(px(type_style.line_height
                        + if filled {
                            caption_style.line_height + 16.
                        } else {
                            16.
                        })))
                    .rounded(radius)
                    .border_color(indicator)
                    .px(px(16.))
                    .py(px(4.))
                    .when(filled, |mut field| {
                        // Compose reserves 8 dp above the minimized label and below
                        // the editor; larger text grows the container instead of overlapping.
                        field = field
                            .pt(px(caption_style.line_height + 8.))
                            .pb(px(8.) - outline_width);
                        field.style().border_widths.bottom = Some(outline_width.into());
                        field
                            .bg(background)
                            .rounded_b_none()
                            .when(!disabled && !focused && !error, |field| {
                                field.hover(|style| style.border_color(foreground))
                            })
                    })
                    .when(!filled && !disabled, |field| {
                        field.on_hover(move |hovering, window, _| {
                            if hover.replace(*hovering) != *hovering {
                                window.refresh();
                            }
                        })
                    })
                    .children(outline_canvas)
                    .when(direction == Direction::Rtl, |field| {
                        field.text_align(TextAlign::Right)
                    })
                    .child(
                        div()
                            .flex()
                            .items_center()
                            .gap(px(8.))
                            .min_w_0()
                            .text_size(px(type_style.size))
                            .line_height(px(type_style.line_height))
                            .when(direction == Direction::Rtl, |row| row.flex_row_reverse())
                            .child(div().flex_1().min_w_0().child(editor))
                            .children(self.trailing),
                    )
                    .child(label_container),
            )
            .when_some(support, |field, text| {
                field.child(
                    div()
                        .px(px(16.))
                        .text_size(px(caption_style.size))
                        .line_height(px(caption_style.line_height))
                        .text_color(if error && !disabled {
                            indicator
                        } else {
                            secondary
                        })
                        .child(text),
                )
            })
    }
}