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