Skip to main content

gpui_material_components/
list.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, Axis, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5    ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Window,
6    accesskit::Toggled, div, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{InteractionSource, current_material_theme, move_roving_focus};
10use gpui_material_theme::{CornerRole, CornerShape};
11
12use crate::{SemanticTone, SwipeToDismiss, SwipeToDismissState, action::Activate};
13
14mod long_press;
15mod render;
16mod style;
17
18pub use style::{
19    ListItemAlignment, ListItemColors, ListItemElevations, ListItemPadding, ListItemShapes,
20    ListItemStateColors,
21};
22
23/// Layout and corner-grouping style for [`List`].
24#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
25pub enum ListVariant {
26    /// Contiguous rectangular rows without inter-row gaps (default).
27    #[default]
28    Standard,
29    /// Expressive segmented rows separated by a 2 px gap with rounded outer corners and 4 px inner corners.
30    Segmented,
31}
32
33type ValueChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
34type SwipeConfig = Box<dyn FnOnce(SwipeToDismiss) -> SwipeToDismiss>;
35
36enum Slot {
37    Text(SharedString),
38    Custom(AnyElement),
39}
40
41impl Slot {
42    fn has_line_break(&self) -> bool {
43        matches!(self, Self::Text(value) if value.contains('\n'))
44    }
45}
46
47struct Expansion {
48    expanded: bool,
49    content: AnyElement,
50}
51
52struct SecondaryAction {
53    label: SharedString,
54    handler: Activate,
55}
56
57struct RowSwipe {
58    state: Entity<SwipeToDismissState>,
59    configure: SwipeConfig,
60}
61
62/// A Standard or Segmented list row. Values and data changes belong to the caller.
63#[derive(IntoElement)]
64pub struct ListItem {
65    id: ElementId,
66    label: SharedString,
67    content: Option<AnyElement>,
68    supporting: Option<Slot>,
69    overline: Option<Slot>,
70    leading: Option<AnyElement>,
71    trailing: Option<AnyElement>,
72    activation: Option<Activate>,
73    checked_change: Option<ValueChange>,
74    expanded_change: Option<ValueChange>,
75    long_press: Option<SecondaryAction>,
76    long_press_button: Option<ElementId>,
77    expansion: Option<Expansion>,
78    swipe: Option<RowSwipe>,
79    checked: Option<Toggled>,
80    checked_role: Role,
81    checked_selects_row: bool,
82    invalid: bool,
83    footer: Option<AnyElement>,
84    aria_description: Option<SharedString>,
85    #[cfg(feature = "feedback")]
86    menu_trigger: Option<(bool, Activate)>,
87    selected: bool,
88    disabled: bool,
89    dragged: bool,
90    focus: Option<(FocusHandle, bool)>,
91    tone: SemanticTone,
92    shapes: ListItemShapes,
93    colors: ListItemColors,
94    elevations: ListItemElevations,
95    alignment: ListItemAlignment,
96    padding: Option<ListItemPadding>,
97    source: Option<Entity<InteractionSource>>,
98}
99
100impl ListItem {
101    /// Creates a list row with a stable element ID and primary headline label.
102    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
103        Self {
104            id: id.into(),
105            label: label.into(),
106            content: None,
107            supporting: None,
108            overline: None,
109            leading: None,
110            trailing: None,
111            activation: None,
112            checked_change: None,
113            expanded_change: None,
114            long_press: None,
115            long_press_button: None,
116            expansion: None,
117            swipe: None,
118            checked: None,
119            checked_role: Role::CheckBox,
120            checked_selects_row: true,
121            invalid: false,
122            footer: None,
123            aria_description: None,
124            #[cfg(feature = "feedback")]
125            menu_trigger: None,
126            selected: false,
127            disabled: false,
128            dragged: false,
129            focus: None,
130            tone: SemanticTone::Default,
131            shapes: ListItemShapes::default(),
132            colors: ListItemColors::default(),
133            elevations: ListItemElevations::default(),
134            alignment: ListItemAlignment::Auto,
135            padding: None,
136            source: None,
137        }
138    }
139
140    /// Replaces the visual headline. The constructor's label still names the row action.
141    pub fn content(mut self, content: impl IntoElement) -> Self {
142        self.content = Some(content.into_any_element());
143        self
144    }
145
146    /// Sets secondary supporting text displayed below the headline.
147    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
148        self.supporting = Some(Slot::Text(text.into()));
149        self
150    }
151
152    /// Sets custom supporting content displayed below the headline.
153    pub fn supporting_content(mut self, content: impl IntoElement) -> Self {
154        self.supporting = Some(Slot::Custom(content.into_any_element()));
155        self
156    }
157
158    /// Sets overline text displayed above the headline.
159    pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
160        self.overline = Some(Slot::Text(text.into()));
161        self
162    }
163
164    /// Sets custom overline content displayed above the headline.
165    pub fn overline_content(mut self, content: impl IntoElement) -> Self {
166        self.overline = Some(Slot::Custom(content.into_any_element()));
167        self
168    }
169
170    /// Sets content in the leading slot (such as an icon, avatar, or selection control).
171    pub fn leading(mut self, leading: impl IntoElement) -> Self {
172        self.leading = Some(leading.into_any_element());
173        self
174    }
175
176    /// Sets content in the trailing slot (such as metadata text, an icon, or a switch).
177    pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
178        self.trailing = Some(trailing.into_any_element());
179        self
180    }
181
182    /// Sets whether the row is visually highlighted as selected.
183    pub fn selected(mut self, selected: bool) -> Self {
184        self.selected = selected;
185        self
186    }
187
188    /// The controlled checked value, separate from the row's selection state.
189    pub fn checked(mut self, checked: bool) -> Self {
190        self.checked = Some(if checked {
191            Toggled::True
192        } else {
193            Toggled::False
194        });
195        self
196    }
197
198    /// Requests the opposite checked value on activation. The current value defaults to false.
199    pub fn on_checked_change(
200        mut self,
201        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
202    ) -> Self {
203        self.checked.get_or_insert(Toggled::False);
204        self.checked_change = Some(Rc::new(handler));
205        self
206    }
207
208    /// Supplies controlled disclosure content. It is mounted below the row while expanded.
209    pub fn expanded_content(mut self, expanded: bool, content: impl IntoElement) -> Self {
210        self.expansion = Some(Expansion {
211            expanded,
212            content: content.into_any_element(),
213        });
214        self
215    }
216
217    /// Invoked with the requested next expanded state when the row is activated.
218    pub fn on_expanded_change(
219        mut self,
220        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
221    ) -> Self {
222        self.expanded_change = Some(Rc::new(handler));
223        self
224    }
225
226    /// Names the secondary command invoked by a pointer hold, secondary click,
227    /// `Shift+F10`, or `ContextMenu` key.
228    pub fn on_long_press(
229        mut self,
230        label: impl Into<SharedString>,
231        handler: impl Fn(&mut Window, &mut App) + 'static,
232    ) -> Self {
233        self.long_press = Some(SecondaryAction {
234            label: label.into(),
235            handler: Rc::new(handler),
236        });
237        self
238    }
239
240    /// Adds a visible button for the named secondary command in the trailing area.
241    pub fn long_press_button(mut self, id: impl Into<ElementId>) -> Self {
242        self.long_press_button = Some(id.into());
243        self
244    }
245
246    /// Composes the row with a retained SwipeToDismiss instance. Use its configuration
247    /// callback for direction, background and dismissal, keeping the state's owner unchanged.
248    pub fn swipe_to_dismiss(
249        mut self,
250        state: &Entity<SwipeToDismissState>,
251        configure: impl FnOnce(SwipeToDismiss) -> SwipeToDismiss + 'static,
252    ) -> Self {
253        self.swipe = Some(RowSwipe {
254            state: state.clone(),
255            configure: Box::new(configure),
256        });
257        self
258    }
259
260    /// Disables row activation, focus, long-press, and interactive state layers when `true`.
261    pub fn disabled(mut self, disabled: bool) -> Self {
262        self.disabled = disabled;
263        self
264    }
265
266    /// Invoked when the row's primary action is activated via pointer, keyboard, or assistive technology.
267    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
268        self.activation = Some(Rc::new(handler));
269        self
270    }
271
272    /// Overrides logical corner shapes per interaction state.
273    pub fn shapes(mut self, shapes: ListItemShapes) -> Self {
274        self.shapes = shapes;
275        self
276    }
277
278    /// Applies a Material 3 semantic tone to label, leading, and trailing roles
279    /// while preserving disabled appearance and explicit [`ListItemColors`] precedence.
280    pub fn tone(mut self, tone: SemanticTone) -> Self {
281        self.tone = tone;
282        self
283    }
284
285    /// Overrides container and slot pigments per state.
286    pub fn colors(mut self, colors: ListItemColors) -> Self {
287        self.colors = colors;
288        self
289    }
290
291    /// Overrides drop-shadow elevation levels per interaction state.
292    pub fn elevations(mut self, elevations: ListItemElevations) -> Self {
293        self.elevations = elevations;
294        self
295    }
296
297    /// Sets vertical alignment of leading, body, and trailing slots. Defaults to [`ListItemAlignment::Auto`].
298    pub fn vertical_alignment(mut self, alignment: ListItemAlignment) -> Self {
299        self.alignment = alignment;
300        self
301    }
302
303    /// Overrides the row's logical inner padding.
304    pub fn content_padding(mut self, padding: ListItemPadding) -> Self {
305        self.padding = Some(padding);
306        self
307    }
308
309    /// Reports a caller-owned drag. Clear the flag after completion or cancellation.
310    pub fn dragged(mut self, dragged: bool) -> Self {
311        self.dragged = dragged;
312        self
313    }
314
315    /// Reports hover, focus, press, drag, and disabled states through a caller-owned source.
316    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
317        self.source = Some(source.clone());
318        self
319    }
320
321    /// Uses a retained focus handle and roving tab stop supplied by a virtual
322    /// collection. The collection owns navigation across unrendered rows.
323    pub fn track_focus(mut self, focus: &FocusHandle, tab_stop: bool) -> Self {
324        self.focus = Some((focus.clone(), tab_stop));
325        self
326    }
327
328    #[cfg(feature = "selection")]
329    pub(crate) fn checked_role(mut self, role: Role) -> Self {
330        self.checked_role = role;
331        self
332    }
333
334    #[cfg(feature = "selection")]
335    pub(crate) fn checked_toggled(mut self, state: Toggled) -> Self {
336        self.checked = Some(state);
337        self
338    }
339
340    #[cfg(feature = "selection")]
341    pub(crate) fn checked_selects_row(mut self, selects: bool) -> Self {
342        self.checked_selects_row = selects;
343        self
344    }
345
346    #[cfg(feature = "selection")]
347    pub(crate) fn invalid(mut self, invalid: bool) -> Self {
348        self.invalid = invalid;
349        self
350    }
351
352    #[cfg(feature = "selection")]
353    pub(crate) fn footer(mut self, footer: impl IntoElement) -> Self {
354        self.footer = Some(footer.into_any_element());
355        self
356    }
357
358    #[cfg(feature = "feedback")]
359    pub(crate) fn menu_trigger(mut self, open: bool, a11y_toggle: Activate) -> Self {
360        self.menu_trigger = Some((open, a11y_toggle));
361        self
362    }
363
364    #[cfg(feature = "feedback")]
365    pub(crate) fn aria_description(mut self, description: impl Into<SharedString>) -> Self {
366        self.aria_description = Some(description.into());
367        self
368    }
369
370    pub(crate) fn custom_focus(&self) -> Option<FocusHandle> {
371        self.focus.as_ref().map(|(focus, _)| focus.clone())
372    }
373
374    pub(crate) fn id(&self) -> &ElementId {
375        &self.id
376    }
377
378    pub(crate) fn is_selected(&self) -> bool {
379        self.selected
380    }
381
382    fn has_primary_action(&self) -> bool {
383        self.activation.is_some()
384            || self.checked_change.is_some()
385            || self.expansion.is_some() && self.expanded_change.is_some()
386    }
387
388    fn has_menu_trigger(&self) -> bool {
389        #[cfg(feature = "feedback")]
390        {
391            self.menu_trigger.is_some()
392        }
393        #[cfg(not(feature = "feedback"))]
394        {
395            false
396        }
397    }
398
399    pub(crate) fn takes_focus(&self, cx: &App) -> bool {
400        !self.disabled
401            && (self.has_primary_action() || self.has_menu_trigger() || self.long_press.is_some())
402            && self
403                .swipe
404                .as_ref()
405                .is_none_or(|swipe| swipe.state.read(cx).shows_foreground())
406    }
407
408    fn primary_action(&self) -> Option<Activate> {
409        if !self.has_primary_action() {
410            return None;
411        }
412        let action = self.activation.clone();
413        let check = self.checked.zip(self.checked_change.clone());
414        let expansion = self
415            .expansion
416            .as_ref()
417            .map(|expansion| expansion.expanded)
418            .zip(self.expanded_change.clone());
419        Some(Rc::new(move |window, cx| {
420            if let Some((checked, change)) = &check {
421                change(*checked != Toggled::True, window, cx);
422            }
423            if let Some((expanded, change)) = &expansion {
424                change(!expanded, window, cx);
425            }
426            if let Some(action) = &action {
427                action(window, cx);
428            }
429        }))
430    }
431
432    pub(crate) fn row(
433        self,
434        resting: CornerShape,
435        selected_shape: CornerShape,
436        focus: Option<(FocusHandle, bool)>,
437        window: &mut Window,
438        cx: &mut App,
439    ) -> AnyElement {
440        window.with_element_namespace((self.id.clone(), "material-list-row"), |window| {
441            self.render_row(resting, selected_shape, focus, window, cx)
442        })
443    }
444}
445
446impl RenderOnce for ListItem {
447    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
448        let focus = self.focus.clone();
449        self.row(
450            CornerRole::None.shape(),
451            CornerRole::None.shape(),
452            focus,
453            window,
454            cx,
455        )
456    }
457}
458
459/// A list of identified rows. Applications can supply a visible window of rows
460/// from their own virtualized collection.
461#[derive(IntoElement)]
462pub struct List {
463    id: ElementId,
464    items: Vec<ListItem>,
465    variant: ListVariant,
466    accessible_label: Option<SharedString>,
467}
468
469impl List {
470    /// Creates an empty [`ListVariant::Standard`] list container with the given element ID.
471    pub fn new(id: impl Into<ElementId>) -> Self {
472        Self {
473            id: id.into(),
474            items: Vec::new(),
475            variant: ListVariant::default(),
476            accessible_label: None,
477        }
478    }
479
480    /// Sets the list layout variant (`Standard` or `Segmented`).
481    pub fn variant(mut self, variant: ListVariant) -> Self {
482        self.variant = variant;
483        self
484    }
485
486    /// Names the list container (`Role::List`) for assistive technology.
487    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
488        self.accessible_label = Some(label.into());
489        self
490    }
491
492    /// Appends a single [`ListItem`] row.
493    pub fn item(mut self, item: ListItem) -> Self {
494        self.items.push(item);
495        self
496    }
497
498    /// Appends multiple [`ListItem`] rows from an iterator.
499    pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
500        self.items.extend(items);
501        self
502    }
503}
504
505impl RenderOnce for List {
506    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
507        window.with_element_namespace((self.id.clone(), "material-list"), |window| {
508            let last = self.items.len().saturating_sub(1);
509            let direction = current_material_theme(window, cx).layout.direction;
510            let focus: Vec<_> = self
511                .items
512                .iter()
513                .map(|item| {
514                    item.custom_focus().unwrap_or_else(|| {
515                        window
516                            .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| {
517                                cx.focus_handle()
518                            })
519                            .read(cx)
520                            .clone()
521                    })
522                })
523                .collect();
524            let enabled: Vec<_> = self.items.iter().map(|item| item.takes_focus(cx)).collect();
525            let tab_stop = focus
526                .iter()
527                .enumerate()
528                .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
529                .or_else(|| {
530                    self.items
531                        .iter()
532                        .enumerate()
533                        .position(|(ix, item)| enabled[ix] && item.selected)
534                })
535                .or_else(|| enabled.iter().position(|enabled| *enabled));
536            let navigation = focus.clone();
537            div()
538                .id(self.id)
539                .role(Role::List)
540                .when_some(self.accessible_label, |list, label| list.aria_label(label))
541                .test_support()
542                .flex()
543                .flex_col()
544                .w_full()
545                .on_key_down(move |event, window, cx| {
546                    // Nested controls keep their own arrow-key behavior.
547                    if !navigation.iter().any(|focus| focus.is_focused(window)) {
548                        return;
549                    }
550                    let items: Vec<_> = navigation
551                        .iter()
552                        .zip(&enabled)
553                        .map(|(focus, enabled)| (focus, *enabled))
554                        .collect();
555                    if move_roving_focus(
556                        &items,
557                        &event.keystroke.key,
558                        Axis::Vertical,
559                        direction,
560                        window,
561                        cx,
562                    )
563                    .is_some()
564                    {
565                        cx.stop_propagation();
566                        window.refresh();
567                    }
568                })
569                .when(self.variant == ListVariant::Segmented, |list| {
570                    list.gap(px(2.))
571                })
572                .children(self.items.into_iter().zip(focus).enumerate().map(
573                    |(ix, (item, focus))| {
574                        let (resting, selected) = match self.variant {
575                            ListVariant::Standard => {
576                                (CornerRole::None.shape(), CornerRole::None.shape())
577                            }
578                            ListVariant::Segmented => {
579                                let top = if ix == 0 { 16. } else { 4. };
580                                let bottom = if ix == last { 16. } else { 4. };
581                                (
582                                    CornerShape::Radii([top, top, bottom, bottom]),
583                                    CornerRole::Large.shape(),
584                                )
585                            }
586                        };
587                        item.row(
588                            resting,
589                            selected,
590                            Some((focus, Some(ix) == tab_stop)),
591                            window,
592                            cx,
593                        )
594                    },
595                ))
596        })
597    }
598}