Skip to main content

gpui_material_components/
list.rs

1use std::{cell::Cell, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Axis, BorderStyle, ClickEvent, Corners, ElementId, Entity,
5    FocusHandle, Hsla, InteractiveElement, IntoElement, ParentElement, RenderOnce, Role,
6    SharedString, StatefulInteractiveElement, Styled, Window, accesskit::Toggled, canvas, div,
7    prelude::FluentBuilder, px, quad,
8};
9use gpui_base::TestSupportExt;
10use gpui_material_foundation::{
11    InteractionFeedback, InteractionSource, Shape, animate, color, elevation_shadows,
12    move_roving_focus, window_material_theme,
13};
14use gpui_material_theme::{
15    ColorRole, CornerRole, CornerShape, Direction, MotionKind, MotionSpec, MotionSpeed, TypeRole,
16};
17
18use crate::{
19    Button, ButtonVariant, ControlSize, SwipeToDismiss, SwipeToDismissState, Text,
20    action::{Activate, activate_feedback, feedback_target, ripple_state},
21    button_style::finite_length,
22};
23
24mod long_press;
25mod style;
26
27use long_press::LongPress;
28pub use style::{
29    ListItemAlignment, ListItemColors, ListItemElevations, ListItemPadding, ListItemShapes,
30    ListItemStateColors,
31};
32
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
34pub enum ListVariant {
35    #[default]
36    Standard,
37    Segmented,
38}
39
40type ValueChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
41type SwipeConfig = Box<dyn FnOnce(SwipeToDismiss) -> SwipeToDismiss>;
42
43enum Slot {
44    Text(SharedString),
45    Custom(AnyElement),
46}
47
48impl Slot {
49    fn render(self, id: &'static str, role: TypeRole, tint: Hsla, wrap: bool) -> AnyElement {
50        let content = match self {
51            Self::Text(value) => Text::new(value)
52                .id(id)
53                .role(role)
54                .when(wrap, Text::wrap)
55                .into_any_element(),
56            Self::Custom(element) => element,
57        };
58        inherit_color((ElementId::from(id), "slot"), content, Some(tint))
59    }
60
61    fn has_line_break(&self) -> bool {
62        matches!(self, Self::Text(value) if value.contains('\n'))
63    }
64}
65
66struct Expansion {
67    expanded: bool,
68    content: AnyElement,
69}
70
71struct SecondaryAction {
72    label: SharedString,
73    handler: Activate,
74}
75
76struct RowSwipe {
77    state: Entity<SwipeToDismissState>,
78    configure: SwipeConfig,
79}
80
81/// A Standard or Segmented list row. Values and data changes belong to the caller.
82#[derive(IntoElement)]
83pub struct ListItem {
84    id: ElementId,
85    label: SharedString,
86    content: Option<AnyElement>,
87    supporting: Option<Slot>,
88    overline: Option<Slot>,
89    leading: Option<AnyElement>,
90    trailing: Option<AnyElement>,
91    activation: Option<Activate>,
92    checked_change: Option<ValueChange>,
93    expanded_change: Option<ValueChange>,
94    long_press: Option<SecondaryAction>,
95    long_press_button: Option<ElementId>,
96    expansion: Option<Expansion>,
97    swipe: Option<RowSwipe>,
98    checked: Option<bool>,
99    selected: bool,
100    disabled: bool,
101    dragged: bool,
102    focus: Option<(FocusHandle, bool)>,
103    shapes: ListItemShapes,
104    colors: ListItemColors,
105    elevations: ListItemElevations,
106    alignment: ListItemAlignment,
107    padding: Option<ListItemPadding>,
108    source: Option<Entity<InteractionSource>>,
109}
110
111impl ListItem {
112    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
113        Self {
114            id: id.into(),
115            label: label.into(),
116            content: None,
117            supporting: None,
118            overline: None,
119            leading: None,
120            trailing: None,
121            activation: None,
122            checked_change: None,
123            expanded_change: None,
124            long_press: None,
125            long_press_button: None,
126            expansion: None,
127            swipe: None,
128            checked: None,
129            selected: false,
130            disabled: false,
131            dragged: false,
132            focus: None,
133            shapes: ListItemShapes::default(),
134            colors: ListItemColors::default(),
135            elevations: ListItemElevations::default(),
136            alignment: ListItemAlignment::Auto,
137            padding: None,
138            source: None,
139        }
140    }
141
142    /// Replaces the visual headline. The constructor's label still names the row action.
143    pub fn content(mut self, content: impl IntoElement) -> Self {
144        self.content = Some(content.into_any_element());
145        self
146    }
147
148    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
149        self.supporting = Some(Slot::Text(text.into()));
150        self
151    }
152
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    pub fn overline(mut self, text: impl Into<SharedString>) -> Self {
159        self.overline = Some(Slot::Text(text.into()));
160        self
161    }
162
163    pub fn overline_content(mut self, content: impl IntoElement) -> Self {
164        self.overline = Some(Slot::Custom(content.into_any_element()));
165        self
166    }
167
168    pub fn leading(mut self, leading: impl IntoElement) -> Self {
169        self.leading = Some(leading.into_any_element());
170        self
171    }
172
173    pub fn trailing(mut self, trailing: impl IntoElement) -> Self {
174        self.trailing = Some(trailing.into_any_element());
175        self
176    }
177
178    pub fn selected(mut self, selected: bool) -> Self {
179        self.selected = selected;
180        self
181    }
182
183    /// The controlled checked value, separate from the row's selection state.
184    pub fn checked(mut self, checked: bool) -> Self {
185        self.checked = Some(checked);
186        self
187    }
188
189    /// Requests the opposite checked value on activation. The current value defaults to false.
190    pub fn on_checked_change(
191        mut self,
192        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
193    ) -> Self {
194        self.checked.get_or_insert(false);
195        self.checked_change = Some(Rc::new(handler));
196        self
197    }
198
199    /// Supplies controlled disclosure content. It is mounted below the row while expanded.
200    pub fn expanded_content(mut self, expanded: bool, content: impl IntoElement) -> Self {
201        self.expansion = Some(Expansion {
202            expanded,
203            content: content.into_any_element(),
204        });
205        self
206    }
207
208    pub fn on_expanded_change(
209        mut self,
210        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
211    ) -> Self {
212        self.expanded_change = Some(Rc::new(handler));
213        self
214    }
215
216    /// Names the secondary command invoked by a pointer hold or Shift+F10.
217    pub fn on_long_press(
218        mut self,
219        label: impl Into<SharedString>,
220        handler: impl Fn(&mut Window, &mut App) + 'static,
221    ) -> Self {
222        self.long_press = Some(SecondaryAction {
223            label: label.into(),
224            handler: Rc::new(handler),
225        });
226        self
227    }
228
229    /// Adds a visible button for the named secondary command in the trailing area.
230    pub fn long_press_button(mut self, id: impl Into<ElementId>) -> Self {
231        self.long_press_button = Some(id.into());
232        self
233    }
234
235    /// Composes the row with a retained SwipeToDismiss instance. Use its configuration
236    /// callback for direction, background and dismissal, keeping the state's owner unchanged.
237    pub fn swipe_to_dismiss(
238        mut self,
239        state: &Entity<SwipeToDismissState>,
240        configure: impl FnOnce(SwipeToDismiss) -> SwipeToDismiss + 'static,
241    ) -> Self {
242        self.swipe = Some(RowSwipe {
243            state: state.clone(),
244            configure: Box::new(configure),
245        });
246        self
247    }
248
249    pub fn disabled(mut self, disabled: bool) -> Self {
250        self.disabled = disabled;
251        self
252    }
253
254    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
255        self.activation = Some(Rc::new(handler));
256        self
257    }
258
259    pub fn shapes(mut self, shapes: ListItemShapes) -> Self {
260        self.shapes = shapes;
261        self
262    }
263
264    pub fn colors(mut self, colors: ListItemColors) -> Self {
265        self.colors = colors;
266        self
267    }
268
269    pub fn elevations(mut self, elevations: ListItemElevations) -> Self {
270        self.elevations = elevations;
271        self
272    }
273
274    pub fn vertical_alignment(mut self, alignment: ListItemAlignment) -> Self {
275        self.alignment = alignment;
276        self
277    }
278
279    pub fn content_padding(mut self, padding: ListItemPadding) -> Self {
280        self.padding = Some(padding);
281        self
282    }
283
284    /// Reports a caller-owned drag. Clear the flag after completion or cancellation.
285    pub fn dragged(mut self, dragged: bool) -> Self {
286        self.dragged = dragged;
287        self
288    }
289
290    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
291        self.source = Some(source.clone());
292        self
293    }
294
295    /// Uses a retained focus handle and roving tab stop supplied by a virtual
296    /// collection. The collection owns navigation across unrendered rows.
297    pub fn track_focus(mut self, focus: &FocusHandle, tab_stop: bool) -> Self {
298        self.focus = Some((focus.clone(), tab_stop));
299        self
300    }
301
302    fn has_primary_action(&self) -> bool {
303        self.activation.is_some()
304            || self.checked_change.is_some()
305            || self.expansion.is_some() && self.expanded_change.is_some()
306    }
307
308    fn takes_focus(&self, cx: &App) -> bool {
309        !self.disabled
310            && (self.has_primary_action() || self.long_press.is_some())
311            && self
312                .swipe
313                .as_ref()
314                .is_none_or(|swipe| swipe.state.read(cx).shows_foreground())
315    }
316
317    fn primary_action(&self) -> Option<Activate> {
318        if !self.has_primary_action() {
319            return None;
320        }
321        let action = self.activation.clone();
322        let check = self.checked.zip(self.checked_change.clone());
323        let expansion = self
324            .expansion
325            .as_ref()
326            .map(|expansion| expansion.expanded)
327            .zip(self.expanded_change.clone());
328        Some(Rc::new(move |window, cx| {
329            if let Some((checked, change)) = &check {
330                change(!checked, window, cx);
331            }
332            if let Some((expanded, change)) = &expansion {
333                change(!expanded, window, cx);
334            }
335            if let Some(action) = &action {
336                action(window, cx);
337            }
338        }))
339    }
340
341    fn row(
342        self,
343        resting: CornerShape,
344        selected_shape: CornerShape,
345        focus: Option<(FocusHandle, bool)>,
346        window: &mut Window,
347        cx: &mut App,
348    ) -> AnyElement {
349        window.with_element_namespace((self.id.clone(), "material-list-row"), |window| {
350            self.render_row(resting, selected_shape, focus, window, cx)
351        })
352    }
353
354    fn render_row(
355        self,
356        resting: CornerShape,
357        selected_shape: CornerShape,
358        focus: Option<(FocusHandle, bool)>,
359        window: &mut Window,
360        cx: &mut App,
361    ) -> AnyElement {
362        let (focus, tab_stop) = focus.unwrap_or_else(|| {
363            let focus = window
364                .use_keyed_state("focus", cx, |_, cx| cx.focus_handle())
365                .read(cx)
366                .clone();
367            (focus, true)
368        });
369        let primary = self.primary_action();
370        let interactive = primary.is_some() || self.long_press.is_some();
371        let visible = self
372            .swipe
373            .as_ref()
374            .is_none_or(|swipe| swipe.state.read(cx).shows_foreground());
375        let enabled = !self.disabled && visible;
376        let dragged = enabled
377            && (self.dragged
378                || self
379                    .swipe
380                    .as_ref()
381                    .is_some_and(|swipe| swipe.state.read(cx).is_dragging()));
382        let feedback = ripple_state(&self.id, interactive && enabled, window, cx);
383        let tracker = self
384            .source
385            .as_ref()
386            .filter(|_| visible)
387            .map(|source| InteractionSource::track(source, &self.id, window, cx));
388        let interaction = {
389            let mut feedback = feedback.borrow_mut();
390            feedback.set_dragged(dragged);
391            feedback.track(enabled, &focus, tracker, window, cx)
392        };
393
394        let long_press = self.long_press.as_ref().map(|long_press| {
395            LongPress::mount(
396                (enabled && !dragged).then(|| long_press.handler.clone()),
397                window,
398                cx,
399            )
400        });
401        let theme = window_material_theme(window, cx);
402        let layout = theme.layout;
403        let direction = layout.direction;
404        let motion = theme.motion;
405        let reduced = cx.reduce_motion();
406        let selected = self.selected || self.checked == Some(true);
407        let shape = self
408            .shapes
409            .resolve(resting, selected_shape, selected, interaction);
410        let effects = motion.spec(MotionKind::Effects, MotionSpeed::Default, reduced);
411        let spatial = motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
412        let selection =
413            animate("selection", f32::from(selected), effects, window, cx).clamp(0., 1.);
414        let scheme = &window_material_theme(window, cx).colors;
415        let tone = |role| color(scheme.color(role));
416        let ring = tone(ColorRole::Secondary);
417        let shadow = tone(ColorRole::Shadow);
418        let colors = self.colors.resolve(selected, selection, interaction, tone);
419        let layer = animate(
420            "opacity",
421            interaction
422                .layer_with_ripple(reduced)
423                .map_or(0., |layer| layer.opacity()),
424            if enabled {
425                effects
426            } else {
427                MotionSpec::Instant
428            },
429            window,
430            cx,
431        )
432        .clamp(0., 1.);
433        let elevation = animate(
434            "elevation",
435            self.elevations.resolve(interaction).dp(),
436            if enabled {
437                spatial
438            } else {
439                MotionSpec::Instant
440            },
441            window,
442            cx,
443        )
444        .max(0.);
445        let text_height = window
446            .use_keyed_state("text-height", cx, |_, _| Rc::new(Cell::new(px(0.))))
447            .read(cx)
448            .clone();
449        let three_lines = self.overline.is_some() && self.supporting.is_some()
450            || self.supporting.as_ref().is_some_and(Slot::has_line_break)
451            || text_height.get() > px(44.);
452        let height = match (self.overline.is_some(), self.supporting.is_some()) {
453            _ if three_lines => 88.,
454            (false, false) => 56.,
455            _ => 72.,
456        };
457        let radii = match shape {
458            CornerShape::Radii(radii) => radii,
459            CornerShape::Full => [height * 0.5; 4],
460        };
461        // Include the measured pill extent separately so the final shape follows
462        // custom content that raises the row above its minimum height.
463        let full = animate(
464            "full",
465            f32::from(shape == CornerShape::Full),
466            spatial,
467            window,
468            cx,
469        )
470        .clamp(0., 1.);
471        let radii = std::array::from_fn(|ix| {
472            animate(["ts", "te", "be", "bs"][ix], radii[ix], spatial, window, cx).max(0.)
473        });
474        let geometry = feedback.clone();
475        let ink = feedback.clone();
476        let visual = canvas(
477            move |bounds, _, _| {
478                let extent = f32::from(bounds.size.width.min(bounds.size.height)) * 0.5;
479                let shape =
480                    CornerShape::Radii(radii.map(|radius| radius + (extent - radius) * full));
481                let [top_left, top_right, bottom_right, bottom_left] = shape
482                    .radii(
483                        bounds.size.width.into(),
484                        bounds.size.height.into(),
485                        direction,
486                    )
487                    .map(px);
488                geometry.borrow_mut().shape = enabled
489                    .then(|| Shape::rounded(bounds, shape, direction))
490                    .flatten();
491                Corners {
492                    top_left,
493                    top_right,
494                    bottom_right,
495                    bottom_left,
496                }
497            },
498            move |bounds, corners, window, cx| {
499                if elevation > 0. {
500                    window.paint_drop_shadows(
501                        bounds,
502                        corners,
503                        &elevation_shadows(elevation, 1., shadow),
504                    );
505                }
506                window.paint_quad(quad(
507                    bounds,
508                    corners,
509                    colors.container,
510                    px(0.),
511                    gpui::transparent_black(),
512                    BorderStyle::Solid,
513                ));
514                let feedback = ink.borrow();
515                if let Some(shape) = &feedback.shape {
516                    // Base's outer ring keeps the existing list focus geometry.
517                    let mut visual_interaction = interaction;
518                    visual_interaction.focus_visible = false;
519                    InteractionFeedback::new(visual_interaction, colors.content, ring)
520                        .paint_with_opacity(
521                            shape,
522                            feedback.ripple.as_ref(),
523                            layer,
524                            cx.background_executor().now(),
525                            reduced,
526                            window,
527                        );
528                }
529            },
530        )
531        .absolute()
532        .inset_0();
533
534        let content = div()
535            .relative()
536            .flex()
537            .flex_col()
538            .flex_1()
539            .min_w_0()
540            .overflow_hidden()
541            .text_color(colors.content)
542            .children(
543                self.overline.map(|slot| {
544                    slot.render("overline", TypeRole::LabelSmall, colors.overline, false)
545                }),
546            )
547            .child(div().id("headline-slot").child(
548                self.content.unwrap_or_else(|| {
549                    Text::new(self.label.clone()).id("label").into_any_element()
550                }),
551            ))
552            .children(self.supporting.map(|slot| {
553                slot.render("supporting", TypeRole::BodyMedium, colors.supporting, true)
554            }))
555            .children(
556                long_press
557                    .as_ref()
558                    .filter(|_| enabled && !dragged)
559                    .map(|press| press.target()),
560            )
561            .child(
562                canvas(
563                    move |bounds, window, _| {
564                        if text_height.replace(bounds.size.height) != bounds.size.height {
565                            window.refresh();
566                        }
567                    },
568                    |_, _, _, _| {},
569                )
570                .absolute()
571                .inset_0(),
572            );
573
574        let padding = self.padding.unwrap_or_else(|| {
575            let vertical = px(if three_lines { 12. } else { 10. });
576            ListItemPadding {
577                top: vertical,
578                bottom: vertical,
579                ..ListItemPadding::default()
580            }
581        });
582        let (left, right) =
583            layout.horizontal(finite_length(padding.start), finite_length(padding.end));
584        let press_button =
585            self.long_press
586                .as_ref()
587                .zip(self.long_press_button)
588                .map(|(press, id)| {
589                    let invoke = press.handler.clone();
590                    Button::new(id, press.label.clone())
591                        .variant(ButtonVariant::Text)
592                        .size(ControlSize::ExtraSmall)
593                        .disabled(!enabled || dragged)
594                        .on_activate(move |window, cx| invoke(window, cx))
595                });
596        let alignment = if self.alignment == ListItemAlignment::Auto {
597            if three_lines {
598                ListItemAlignment::Start
599            } else {
600                ListItemAlignment::Center
601            }
602        } else {
603            self.alignment
604        };
605        let surface = div()
606            .id("list-surface")
607            .relative()
608            .min_h(px(height))
609            .w_full()
610            .flex()
611            .map(|row| match alignment {
612                ListItemAlignment::Start => row.items_start(),
613                ListItemAlignment::End => row.items_end(),
614                _ => row.items_center(),
615            })
616            .gap(px(12.))
617            .pl(left)
618            .pr(right)
619            .pt(finite_length(padding.top))
620            .pb(finite_length(padding.bottom))
621            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
622            .child(visual)
623            .children(
624                self.leading
625                    .map(|element| inherit_color("leading-slot", element, colors.leading)),
626            )
627            .child(content)
628            .children(
629                self.trailing
630                    .map(|element| inherit_color("trailing-slot", element, colors.trailing)),
631            )
632            .children(press_button.map(|button| div().id("long-press-slot").child(button)));
633
634        let expanded = self.expansion.as_ref().map(|expansion| expansion.expanded);
635        let checked = self.checked.map(|checked| {
636            if checked {
637                Toggled::True
638            } else {
639                Toggled::False
640            }
641        });
642        let expanded_content = self.expansion.and_then(|expansion| {
643            let scope = window
644                .use_keyed_state("disclosure-focus", cx, |_, cx| {
645                    cx.focus_handle().tab_stop(false)
646                })
647                .read(cx)
648                .clone();
649            if !expansion.expanded && interactive && enabled && scope.contains_focused(window, cx) {
650                focus.focus(window, cx);
651            }
652            expansion.expanded.then(|| {
653                div()
654                    .id("list-expanded-content")
655                    .track_focus(&scope)
656                    .child(expansion.content)
657            })
658        });
659        let row = if interactive {
660            let activate = feedback.clone();
661            let mut control = gpui_base::Button::new((self.id.clone(), "activate"))
662                .track_focus(&focus)
663                .tab_stop(tab_stop)
664                .w_full()
665                .accessibility_label(self.label.clone())
666                .disabled(!enabled)
667                .selected(self.selected)
668                .when_some(checked, |control, checked| {
669                    control.role(Role::CheckBox).aria_toggled(checked)
670                })
671                .when_some(expanded, |control, expanded| {
672                    control.aria_expanded(expanded)
673                })
674                .border_2()
675                .border_color(gpui::transparent_black())
676                .rounded_md()
677                .focus_visible(move |style| style.border_color(ring))
678                .when(enabled && !dragged, |control| {
679                    feedback_target(control, feedback, true, Some(focus.clone()))
680                });
681            if let Some(primary) = primary.filter(|_| enabled && !dragged) {
682                let invoke = primary.clone();
683                let hold = long_press.clone();
684                control = control
685                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
686                        invoke(window, cx)
687                    })
688                    .on_click(move |event, window, cx| {
689                        cx.stop_propagation();
690                        let native_drag =
691                            matches!(event, ClickEvent::Mouse(_)) && cx.has_active_drag();
692                        let allowed = !native_drag
693                            && !activate.borrow().blocks_activation(event)
694                            && !hold
695                                .as_ref()
696                                .is_some_and(|hold| hold.blocks_activation(event));
697                        if allowed || matches!(event, ClickEvent::Mouse(_)) {
698                            activate_feedback(event, &activate, window, cx);
699                        }
700                        if allowed {
701                            primary(window, cx);
702                        }
703                    });
704            }
705            if let Some((expanded, change)) = expanded
706                .zip(self.expanded_change)
707                .filter(|_| enabled && !dragged)
708            {
709                control = control.on_a11y_action(
710                    if expanded {
711                        AccessibleAction::Collapse
712                    } else {
713                        AccessibleAction::Expand
714                    },
715                    move |_, window, cx| change(!expanded, window, cx),
716                );
717            }
718            if let Some((secondary, hold)) = self
719                .long_press
720                .zip(long_press)
721                .filter(|_| enabled && !dragged)
722            {
723                let invoke = secondary.handler.clone();
724                control = control
725                    .aria_description(secondary.label)
726                    .on_a11y_action(AccessibleAction::ShowContextMenu, move |_, window, cx| {
727                        invoke(window, cx)
728                    })
729                    .on_key_down(move |event, window, cx| {
730                        if !focus.is_focused(window) {
731                            return;
732                        }
733                        if event.keystroke.key == "escape" {
734                            hold.cancel();
735                        }
736                        if is_long_press_shortcut(&event.keystroke) {
737                            cx.stop_propagation();
738                            if !event.is_held {
739                                (secondary.handler)(window, cx);
740                            }
741                        }
742                    });
743            }
744            control.child(surface).into_any_element()
745        } else {
746            surface
747                .when_some(checked, |row, checked| {
748                    row.role(Role::CheckBox).aria_toggled(checked)
749                })
750                .when_some(expanded, |row, expanded| {
751                    row.when(checked.is_none(), |row| row.role(Role::Group))
752                        .aria_expanded(expanded)
753                })
754                .when(
755                    self.disabled && (checked.is_some() || expanded.is_some()),
756                    |row| row.a11y_synthetic_children(|tree| tree.parent_node().set_disabled()),
757                )
758                .into_any_element()
759        };
760        let id = self.id;
761        let row = div()
762            .id(id.clone())
763            .role(Role::ListItem)
764            .test_support()
765            .aria_selected(self.selected)
766            .when(!interactive, |row| row.aria_label(self.label))
767            .flex()
768            .flex_col()
769            .w_full()
770            .child(row)
771            .children(expanded_content);
772        match self.swipe {
773            Some(swipe) => (swipe.configure)(SwipeToDismiss::new((id, "swipe"), &swipe.state, row))
774                .when(self.disabled, |swipe| swipe.gestures_enabled(false))
775                .into_any_element(),
776            None => row.into_any_element(),
777        }
778    }
779}
780
781fn inherit_color(id: impl Into<ElementId>, element: AnyElement, color: Option<Hsla>) -> AnyElement {
782    // Each slot owns a separate identity scope, including elements that use
783    // implicit IDs such as Text and Icon.
784    div()
785        .id(id)
786        .when_some(color, Styled::text_color)
787        .child(element)
788        .into_any_element()
789}
790
791fn is_long_press_shortcut(keystroke: &gpui::Keystroke) -> bool {
792    let modifiers = keystroke.modifiers;
793    keystroke.key == "f10"
794        && modifiers.shift
795        && !modifiers.control
796        && !modifiers.alt
797        && !modifiers.platform
798}
799
800impl RenderOnce for ListItem {
801    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
802        let focus = self.focus.clone();
803        self.row(
804            CornerRole::None.shape(),
805            CornerRole::None.shape(),
806            focus,
807            window,
808            cx,
809        )
810    }
811}
812
813/// A list of identified rows. Applications can supply a visible window of rows
814/// from their own virtualized collection.
815#[derive(IntoElement)]
816pub struct List {
817    id: ElementId,
818    items: Vec<ListItem>,
819    variant: ListVariant,
820}
821
822impl List {
823    pub fn new(id: impl Into<ElementId>) -> Self {
824        Self {
825            id: id.into(),
826            items: Vec::new(),
827            variant: ListVariant::default(),
828        }
829    }
830
831    pub fn variant(mut self, variant: ListVariant) -> Self {
832        self.variant = variant;
833        self
834    }
835
836    pub fn items(mut self, items: impl IntoIterator<Item = ListItem>) -> Self {
837        self.items.extend(items);
838        self
839    }
840}
841
842impl RenderOnce for List {
843    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
844        window.with_element_namespace((self.id.clone(), "material-list"), |window| {
845            let last = self.items.len().saturating_sub(1);
846            let direction = window_material_theme(window, cx).layout.direction;
847            let focus: Vec<_> = self
848                .items
849                .iter()
850                .map(|item| {
851                    window
852                        .use_keyed_state((item.id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
853                        .read(cx)
854                        .clone()
855                })
856                .collect();
857            let enabled: Vec<_> = self.items.iter().map(|item| item.takes_focus(cx)).collect();
858            let tab_stop = focus
859                .iter()
860                .enumerate()
861                .position(|(ix, focus)| enabled[ix] && focus.is_focused(window))
862                .or_else(|| {
863                    self.items
864                        .iter()
865                        .enumerate()
866                        .position(|(ix, item)| enabled[ix] && item.selected)
867                })
868                .or_else(|| enabled.iter().position(|enabled| *enabled));
869            let navigation = focus.clone();
870            div()
871                .id(self.id)
872                .role(Role::List)
873                .test_support()
874                .flex()
875                .flex_col()
876                .w_full()
877                .on_key_down(move |event, window, cx| {
878                    // Nested controls keep their own arrow-key behavior.
879                    if !navigation.iter().any(|focus| focus.is_focused(window)) {
880                        return;
881                    }
882                    let items: Vec<_> = navigation
883                        .iter()
884                        .zip(&enabled)
885                        .map(|(focus, enabled)| (focus, *enabled))
886                        .collect();
887                    if move_roving_focus(
888                        &items,
889                        &event.keystroke.key,
890                        Axis::Vertical,
891                        direction,
892                        window,
893                        cx,
894                    )
895                    .is_some()
896                    {
897                        cx.stop_propagation();
898                        window.refresh();
899                    }
900                })
901                .when(self.variant == ListVariant::Segmented, |list| {
902                    list.gap(px(2.))
903                })
904                .children(self.items.into_iter().enumerate().map(|(ix, item)| {
905                    let (resting, selected) = match self.variant {
906                        ListVariant::Standard => {
907                            (CornerRole::None.shape(), CornerRole::None.shape())
908                        }
909                        ListVariant::Segmented => {
910                            let top = if ix == 0 { 16. } else { 4. };
911                            let bottom = if ix == last { 16. } else { 4. };
912                            (
913                                CornerShape::Radii([top, top, bottom, bottom]),
914                                CornerRole::Large.shape(),
915                            )
916                        }
917                    };
918                    item.row(
919                        resting,
920                        selected,
921                        Some((focus[ix].clone(), Some(ix) == tab_stop)),
922                        window,
923                        cx,
924                    )
925                }))
926        })
927    }
928}