gpui-material-components 0.3.2

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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
use std::rc::Rc;

use gpui::{
    AnyElement, App, Axis, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
    ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Window,
    accesskit::Toggled, div, prelude::FluentBuilder, px,
};
use gpui_base::TestSupportExt;
use gpui_material_foundation::{InteractionSource, current_material_theme, move_roving_focus};
use gpui_material_theme::{CornerRole, CornerShape};

use crate::{SemanticTone, SwipeToDismiss, SwipeToDismissState, action::Activate};

mod long_press;
mod render;
mod style;

pub use style::{
    ListItemAlignment, ListItemColors, ListItemElevations, ListItemPadding, ListItemShapes,
    ListItemStateColors,
};

/// Layout and corner-grouping style for [`List`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ListVariant {
    /// Contiguous rectangular rows without inter-row gaps (default).
    #[default]
    Standard,
    /// Expressive segmented rows separated by a 2 px gap with rounded outer corners and 4 px inner corners.
    Segmented,
}

type ValueChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type SwipeConfig = Box<dyn FnOnce(SwipeToDismiss) -> SwipeToDismiss>;

enum Slot {
    Text(SharedString),
    Custom(AnyElement),
}

impl Slot {
    fn has_line_break(&self) -> bool {
        matches!(self, Self::Text(value) if value.contains('\n'))
    }
}

struct Expansion {
    expanded: bool,
    content: AnyElement,
}

struct SecondaryAction {
    label: SharedString,
    handler: Activate,
}

struct RowSwipe {
    state: Entity<SwipeToDismissState>,
    configure: SwipeConfig,
}

/// A Standard or Segmented list row. Values and data changes belong to the caller.
#[derive(IntoElement)]
pub struct ListItem {
    id: ElementId,
    label: SharedString,
    content: Option<AnyElement>,
    supporting: Option<Slot>,
    overline: Option<Slot>,
    leading: Option<AnyElement>,
    trailing: Option<AnyElement>,
    activation: Option<Activate>,
    checked_change: Option<ValueChange>,
    expanded_change: Option<ValueChange>,
    long_press: Option<SecondaryAction>,
    long_press_button: Option<ElementId>,
    expansion: Option<Expansion>,
    swipe: Option<RowSwipe>,
    checked: Option<Toggled>,
    checked_role: Role,
    checked_selects_row: bool,
    invalid: bool,
    footer: Option<AnyElement>,
    aria_description: Option<SharedString>,
    #[cfg(feature = "feedback")]
    menu_trigger: Option<(bool, Activate)>,
    selected: bool,
    disabled: bool,
    dragged: bool,
    focus: Option<(FocusHandle, bool)>,
    tone: SemanticTone,
    shapes: ListItemShapes,
    colors: ListItemColors,
    elevations: ListItemElevations,
    alignment: ListItemAlignment,
    padding: Option<ListItemPadding>,
    source: Option<Entity<InteractionSource>>,
}

impl ListItem {
    /// Creates a list row with a stable element ID and primary headline label.
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            content: None,
            supporting: None,
            overline: None,
            leading: None,
            trailing: None,
            activation: None,
            checked_change: None,
            expanded_change: None,
            long_press: None,
            long_press_button: None,
            expansion: None,
            swipe: None,
            checked: None,
            checked_role: Role::CheckBox,
            checked_selects_row: true,
            invalid: false,
            footer: None,
            aria_description: None,
            #[cfg(feature = "feedback")]
            menu_trigger: None,
            selected: false,
            disabled: false,
            dragged: false,
            focus: None,
            tone: SemanticTone::Default,
            shapes: ListItemShapes::default(),
            colors: ListItemColors::default(),
            elevations: ListItemElevations::default(),
            alignment: ListItemAlignment::Auto,
            padding: None,
            source: None,
        }
    }

    /// Replaces the visual headline. The constructor's label still names the row action.
    pub fn content(mut self, content: impl IntoElement) -> Self {
        self.content = Some(content.into_any_element());
        self
    }

    /// Sets secondary supporting text displayed below the headline.
    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
        self.supporting = Some(Slot::Text(text.into()));
        self
    }

    /// Sets custom supporting content displayed below the headline.
    pub fn supporting_content(mut self, content: impl IntoElement) -> Self {
        self.supporting = Some(Slot::Custom(content.into_any_element()));
        self
    }

    /// Sets overline text displayed above the headline.
    pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
        self.overline = Some(Slot::Text(text.into()));
        self
    }

    /// Sets custom overline content displayed above the headline.
    pub fn overline_content(mut self, content: impl IntoElement) -> Self {
        self.overline = Some(Slot::Custom(content.into_any_element()));
        self
    }

    /// Sets content in the leading slot (such as an icon, avatar, or selection control).
    pub fn leading(mut self, leading: impl IntoElement) -> Self {
        self.leading = Some(leading.into_any_element());
        self
    }

    /// Sets content in the trailing slot (such as metadata text, an icon, or a switch).
    pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
        self.trailing = Some(trailing.into_any_element());
        self
    }

    /// Sets whether the row is visually highlighted as selected.
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    /// The controlled checked value, separate from the row's selection state.
    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = Some(if checked {
            Toggled::True
        } else {
            Toggled::False
        });
        self
    }

    /// Requests the opposite checked value on activation. The current value defaults to false.
    pub fn on_checked_change(
        mut self,
        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.checked.get_or_insert(Toggled::False);
        self.checked_change = Some(Rc::new(handler));
        self
    }

    /// Supplies controlled disclosure content. It is mounted below the row while expanded.
    pub fn expanded_content(mut self, expanded: bool, content: impl IntoElement) -> Self {
        self.expansion = Some(Expansion {
            expanded,
            content: content.into_any_element(),
        });
        self
    }

    /// Invoked with the requested next expanded state when the row is activated.
    pub fn on_expanded_change(
        mut self,
        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.expanded_change = Some(Rc::new(handler));
        self
    }

    /// Names the secondary command invoked by a pointer hold, secondary click,
    /// `Shift+F10`, or `ContextMenu` key.
    pub fn on_long_press(
        mut self,
        label: impl Into<SharedString>,
        handler: impl Fn(&mut Window, &mut App) + 'static,
    ) -> Self {
        self.long_press = Some(SecondaryAction {
            label: label.into(),
            handler: Rc::new(handler),
        });
        self
    }

    /// Adds a visible button for the named secondary command in the trailing area.
    pub fn long_press_button(mut self, id: impl Into<ElementId>) -> Self {
        self.long_press_button = Some(id.into());
        self
    }

    /// Composes the row with a retained SwipeToDismiss instance. Use its configuration
    /// callback for direction, background and dismissal, keeping the state's owner unchanged.
    pub fn swipe_to_dismiss(
        mut self,
        state: &Entity<SwipeToDismissState>,
        configure: impl FnOnce(SwipeToDismiss) -> SwipeToDismiss + 'static,
    ) -> Self {
        self.swipe = Some(RowSwipe {
            state: state.clone(),
            configure: Box::new(configure),
        });
        self
    }

    /// Disables row activation, focus, long-press, and interactive state layers when `true`.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Invoked when the row's primary action is activated via pointer, keyboard, or assistive technology.
    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.activation = Some(Rc::new(handler));
        self
    }

    /// Overrides logical corner shapes per interaction state.
    pub fn shapes(mut self, shapes: ListItemShapes) -> Self {
        self.shapes = shapes;
        self
    }

    /// Applies a Material 3 semantic tone to label, leading, and trailing roles
    /// while preserving disabled appearance and explicit [`ListItemColors`] precedence.
    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.tone = tone;
        self
    }

    /// Overrides container and slot pigments per state.
    pub fn colors(mut self, colors: ListItemColors) -> Self {
        self.colors = colors;
        self
    }

    /// Overrides drop-shadow elevation levels per interaction state.
    pub fn elevations(mut self, elevations: ListItemElevations) -> Self {
        self.elevations = elevations;
        self
    }

    /// Sets vertical alignment of leading, body, and trailing slots. Defaults to [`ListItemAlignment::Auto`].
    pub fn vertical_alignment(mut self, alignment: ListItemAlignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Overrides the row's logical inner padding.
    pub fn content_padding(mut self, padding: ListItemPadding) -> Self {
        self.padding = Some(padding);
        self
    }

    /// Reports a caller-owned drag. Clear the flag after completion or cancellation.
    pub fn dragged(mut self, dragged: bool) -> Self {
        self.dragged = dragged;
        self
    }

    /// Reports hover, focus, press, drag, and disabled states through a caller-owned source.
    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.source = Some(source.clone());
        self
    }

    /// Uses a retained focus handle and roving tab stop supplied by a virtual
    /// collection. The collection owns navigation across unrendered rows.
    pub fn track_focus(mut self, focus: &FocusHandle, tab_stop: bool) -> Self {
        self.focus = Some((focus.clone(), tab_stop));
        self
    }

    #[cfg(feature = "selection")]
    pub(crate) fn checked_role(mut self, role: Role) -> Self {
        self.checked_role = role;
        self
    }

    #[cfg(feature = "selection")]
    pub(crate) fn checked_toggled(mut self, state: Toggled) -> Self {
        self.checked = Some(state);
        self
    }

    #[cfg(feature = "selection")]
    pub(crate) fn checked_selects_row(mut self, selects: bool) -> Self {
        self.checked_selects_row = selects;
        self
    }

    #[cfg(feature = "selection")]
    pub(crate) fn invalid(mut self, invalid: bool) -> Self {
        self.invalid = invalid;
        self
    }

    #[cfg(feature = "selection")]
    pub(crate) fn footer(mut self, footer: impl IntoElement) -> Self {
        self.footer = Some(footer.into_any_element());
        self
    }

    #[cfg(feature = "feedback")]
    pub(crate) fn menu_trigger(mut self, open: bool, a11y_toggle: Activate) -> Self {
        self.menu_trigger = Some((open, a11y_toggle));
        self
    }

    #[cfg(feature = "feedback")]
    pub(crate) fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
        self.aria_description = Some(description.into());
        self
    }

    pub(crate) fn custom_focus(&self) -> Option<FocusHandle> {
        self.focus.as_ref().map(|(focus, _)| focus.clone())
    }

    pub(crate) fn id(&self) -> &ElementId {
        &self.id
    }

    pub(crate) fn is_selected(&self) -> bool {
        self.selected
    }

    fn has_primary_action(&self) -> bool {
        self.activation.is_some()
            || self.checked_change.is_some()
            || self.expansion.is_some() && self.expanded_change.is_some()
    }

    fn has_menu_trigger(&self) -> bool {
        #[cfg(feature = "feedback")]
        {
            self.menu_trigger.is_some()
        }
        #[cfg(not(feature = "feedback"))]
        {
            false
        }
    }

    pub(crate) fn takes_focus(&self, cx: &App) -> bool {
        !self.disabled
            && (self.has_primary_action() || self.has_menu_trigger() || self.long_press.is_some())
            && self
                .swipe
                .as_ref()
                .is_none_or(|swipe| swipe.state.read(cx).shows_foreground())
    }

    fn primary_action(&self) -> Option<Activate> {
        if !self.has_primary_action() {
            return None;
        }
        let action = self.activation.clone();
        let check = self.checked.zip(self.checked_change.clone());
        let expansion = self
            .expansion
            .as_ref()
            .map(|expansion| expansion.expanded)
            .zip(self.expanded_change.clone());
        Some(Rc::new(move |window, cx| {
            if let Some((checked, change)) = &check {
                change(*checked != Toggled::True, window, cx);
            }
            if let Some((expanded, change)) = &expansion {
                change(!expanded, window, cx);
            }
            if let Some(action) = &action {
                action(window, cx);
            }
        }))
    }

    pub(crate) fn row(
        self,
        resting: CornerShape,
        selected_shape: CornerShape,
        focus: Option<(FocusHandle, bool)>,
        window: &mut Window,
        cx: &mut App,
    ) -> AnyElement {
        window.with_element_namespace((self.id.clone(), "material-list-row"), |window| {
            self.render_row(resting, selected_shape, focus, window, cx)
        })
    }
}

impl RenderOnce for ListItem {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let focus = self.focus.clone();
        self.row(
            CornerRole::None.shape(),
            CornerRole::None.shape(),
            focus,
            window,
            cx,
        )
    }
}

/// A list of identified rows. Applications can supply a visible window of rows
/// from their own virtualized collection.
#[derive(IntoElement)]
pub struct List {
    id: ElementId,
    items: Vec<ListItem>,
    variant: ListVariant,
    accessible_label: Option<SharedString>,
}

impl List {
    /// Creates an empty [`ListVariant::Standard`] list container with the given element ID.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            items: Vec::new(),
            variant: ListVariant::default(),
            accessible_label: None,
        }
    }

    /// Sets the list layout variant (`Standard` or `Segmented`).
    pub fn variant(mut self, variant: ListVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Names the list container (`Role::List`) for assistive technology.
    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
        self.accessible_label = Some(label.into());
        self
    }

    /// Appends a single [`ListItem`] row.
    pub fn item(mut self, item: ListItem) -> Self {
        self.items.push(item);
        self
    }

    /// Appends multiple [`ListItem`] rows from an iterator.
    pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
        self.items.extend(items);
        self
    }
}

impl RenderOnce for List {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        window.with_element_namespace((self.id.clone(), "material-list"), |window| {
            let last = self.items.len().saturating_sub(1);
            let direction = current_material_theme(window, cx).layout.direction;
            let focus: Vec<_> = self
                .items
                .iter()
                .map(|item| {
                    item.custom_focus().unwrap_or_else(|| {
                        window
                            .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| {
                                cx.focus_handle()
                            })
                            .read(cx)
                            .clone()
                    })
                })
                .collect();
            let enabled: Vec<_> = self.items.iter().map(|item| item.takes_focus(cx)).collect();
            let tab_stop = focus
                .iter()
                .enumerate()
                .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
                .or_else(|| {
                    self.items
                        .iter()
                        .enumerate()
                        .position(|(ix, item)| enabled[ix] && item.selected)
                })
                .or_else(|| enabled.iter().position(|enabled| *enabled));
            let navigation = focus.clone();
            div()
                .id(self.id)
                .role(Role::List)
                .when_some(self.accessible_label, |list, label| list.aria_label(label))
                .test_support()
                .flex()
                .flex_col()
                .w_full()
                .on_key_down(move |event, window, cx| {
                    // Nested controls keep their own arrow-key behavior.
                    if !navigation.iter().any(|focus| focus.is_focused(window)) {
                        return;
                    }
                    let items: Vec<_> = navigation
                        .iter()
                        .zip(&enabled)
                        .map(|(focus, enabled)| (focus, *enabled))
                        .collect();
                    if move_roving_focus(
                        &items,
                        &event.keystroke.key,
                        Axis::Vertical,
                        direction,
                        window,
                        cx,
                    )
                    .is_some()
                    {
                        cx.stop_propagation();
                        window.refresh();
                    }
                })
                .when(self.variant == ListVariant::Segmented, |list| {
                    list.gap(px(2.))
                })
                .children(self.items.into_iter().zip(focus).enumerate().map(
                    |(ix, (item, focus))| {
                        let (resting, selected) = match self.variant {
                            ListVariant::Standard => {
                                (CornerRole::None.shape(), CornerRole::None.shape())
                            }
                            ListVariant::Segmented => {
                                let top = if ix == 0 { 16. } else { 4. };
                                let bottom = if ix == last { 16. } else { 4. };
                                (
                                    CornerShape::Radii([top, top, bottom, bottom]),
                                    CornerRole::Large.shape(),
                                )
                            }
                        };
                        item.row(
                            resting,
                            selected,
                            Some((focus, Some(ix) == tab_stop)),
                            window,
                            cx,
                        )
                    },
                ))
        })
    }
}