Skip to main content

gpui_component/list/
list_item.rs

1use crate::{ActiveTheme, Disableable, Icon, Selectable, Sizable as _, StyledExt, h_flex};
2use gpui::{
3    AnyElement, App, ClickEvent, Div, ElementId, InteractiveElement, Interactivity, IntoElement,
4    MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, RenderOnce, SharedString, Stateful,
5    StatefulInteractiveElement, StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _,
6};
7use gpui_base::LogicalStyledExt as _;
8use gpui_base::TestSupportExt as _;
9use smallvec::SmallVec;
10use std::collections::HashMap;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13enum ListItemMode {
14    #[default]
15    Entry,
16    Separator,
17}
18
19impl ListItemMode {
20    #[inline]
21    fn is_separator(&self) -> bool {
22        matches!(self, ListItemMode::Separator)
23    }
24}
25
26#[derive(IntoElement)]
27pub struct ListItem {
28    base: Stateful<Div>,
29    mode: ListItemMode,
30    style: StyleRefinement,
31    disabled: bool,
32    selected: bool,
33    secondary_selected: bool,
34    confirmed: bool,
35    check_icon: Option<Icon>,
36    on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
37    on_mouse_down:
38        HashMap<MouseButton, Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static>>,
39    on_mouse_enter: Option<Box<dyn Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static>>,
40    suffix: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyElement + 'static>>,
41    children: SmallVec<[AnyElement; 2]>,
42    accessibility_label: Option<SharedString>,
43}
44
45impl ListItem {
46    pub fn new(id: impl Into<ElementId>) -> Self {
47        let id: ElementId = id.into();
48        Self {
49            mode: ListItemMode::Entry,
50            base: h_flex().id(id),
51            style: StyleRefinement::default(),
52            disabled: false,
53            selected: false,
54            secondary_selected: false,
55            confirmed: false,
56            on_click: None,
57            on_mouse_down: HashMap::new(),
58            on_mouse_enter: None,
59            check_icon: None,
60            suffix: None,
61            children: SmallVec::new(),
62            accessibility_label: None,
63        }
64    }
65
66    /// Set this list item to as a separator, it not able to be selected.
67    pub fn separator(mut self) -> Self {
68        self.mode = ListItemMode::Separator;
69        self
70    }
71
72    /// Set to show check icon, default is None.
73    pub fn check_icon(mut self, icon: impl Into<Icon>) -> Self {
74        self.check_icon = Some(icon.into());
75        self
76    }
77
78    /// Set ListItem as the selected item style.
79    pub fn selected(mut self, selected: bool) -> Self {
80        self.selected = selected;
81        self
82    }
83
84    /// Set ListItem as the confirmed item style, it will show a check icon.
85    pub fn confirmed(mut self, confirmed: bool) -> Self {
86        self.confirmed = confirmed;
87        self
88    }
89
90    /// Set the accessibility label of the list item.
91    ///
92    /// Without this, list rows are exposed to assistive technology without a
93    /// name — the visible children do not become the item's accessible name.
94    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
95        self.accessibility_label = Some(label.into());
96        self
97    }
98
99    pub fn disabled(mut self, disabled: bool) -> Self {
100        self.disabled = disabled;
101        self
102    }
103
104    /// Set the suffix element of the input field, for example a clear button.
105    pub fn suffix<F, E>(mut self, builder: F) -> Self
106    where
107        F: Fn(&mut Window, &mut App) -> E + 'static,
108        E: IntoElement,
109    {
110        self.suffix = Some(Box::new(move |window, cx| {
111            builder(window, cx).into_any_element()
112        }));
113        self
114    }
115
116    pub fn on_click(
117        mut self,
118        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
119    ) -> Self {
120        self.on_click = Some(Box::new(handler));
121        self
122    }
123
124    pub fn on_mouse_down(
125        mut self,
126        button: MouseButton,
127        handler: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
128    ) -> Self {
129        self.on_mouse_down.insert(button, Box::new(handler));
130        self
131    }
132
133    pub fn on_mouse_enter(
134        mut self,
135        handler: impl Fn(&MouseMoveEvent, &mut Window, &mut App) + 'static,
136    ) -> Self {
137        self.on_mouse_enter = Some(Box::new(handler));
138        self
139    }
140}
141
142impl Disableable for ListItem {
143    fn disabled(mut self, disabled: bool) -> Self {
144        self.disabled = disabled;
145        self
146    }
147}
148
149impl Selectable for ListItem {
150    fn selected(mut self, selected: bool) -> Self {
151        self.selected = selected;
152        self
153    }
154
155    fn is_selected(&self) -> bool {
156        self.selected
157    }
158
159    fn secondary_selected(mut self, selected: bool) -> Self {
160        self.secondary_selected = selected;
161        self
162    }
163}
164
165impl Styled for ListItem {
166    fn style(&mut self) -> &mut gpui::StyleRefinement {
167        &mut self.style
168    }
169}
170
171impl ParentElement for ListItem {
172    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
173        self.children.extend(elements);
174    }
175}
176
177/// Note: Listeners registered via these traits are not gated by
178/// `disabled`/`separator`. The hover style is managed internally, use
179/// `on_hover` instead of `.hover()`.
180impl InteractiveElement for ListItem {
181    fn interactivity(&mut self) -> &mut Interactivity {
182        self.base.interactivity()
183    }
184}
185
186impl StatefulInteractiveElement for ListItem {}
187
188impl RenderOnce for ListItem {
189    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
190        let accessibility_label = self.accessibility_label;
191        let is_active = self.confirmed || self.selected || self.secondary_selected;
192
193        let is_selectable = !(self.disabled || self.mode.is_separator());
194
195        // The outline is an absolute child, so it has to repeat the item's own radius.
196        let mut outline_style = StyleRefinement::default();
197        outline_style.corner_radii = self.style.corner_radii.clone();
198
199        self.base
200            .flex_row_dir(cx)
201            .test_support()
202            .relative()
203            .gap_x_1()
204            .py_1()
205            .px_3()
206            .text_base()
207            .text_color(cx.theme().foreground)
208            .relative()
209            .items_center()
210            .justify_between()
211            .refine_style(&self.style)
212            .when_some(accessibility_label, |this, label| this.aria_label(label))
213            .when(is_selectable, |this| {
214                this.when_some(self.on_click, |this, on_click| this.on_click(on_click))
215                    .when_some(self.on_mouse_enter, |this, on_mouse_enter| {
216                        this.on_mouse_move(move |ev, window, cx| (on_mouse_enter)(ev, window, cx))
217                    })
218                    .map(|this| {
219                        self.on_mouse_down
220                            .into_iter()
221                            .fold(this, |this, (button, handler)| {
222                                this.on_mouse_down(button, move |ev, window, cx| {
223                                    handler(ev, window, cx)
224                                })
225                            })
226                    })
227                    // Register `hover` unconditionally, a conditional registration
228                    // leaves a stale hover style behind when the item turns active.
229                    .hover(|this| {
230                        if is_active {
231                            this
232                        } else {
233                            this.bg(cx.theme().tokens.list_hover)
234                        }
235                    })
236            })
237            .when(!is_selectable, |this| {
238                this.text_color(cx.theme().muted_foreground)
239            })
240            .child(
241                h_flex()
242                    .flex_row_dir(cx)
243                    .w_full()
244                    .items_center()
245                    .justify_between()
246                    .gap_x_1()
247                    .child(div().w_full().children(self.children))
248                    .when_some(self.check_icon, |this, icon| {
249                        this.child(
250                            div().w_5().items_center().justify_center().when(
251                                self.confirmed,
252                                |this| {
253                                    this.child(icon.small().text_color(cx.theme().muted_foreground))
254                                },
255                            ),
256                        )
257                    }),
258            )
259            .when_some(self.suffix, |this, suffix| this.child(suffix(window, cx)))
260            .when(is_selectable && self.selected, |this| {
261                if cx.theme().list.active_highlight {
262                    this.bg(cx.theme().list_active)
263                } else {
264                    this.bg(cx.theme().accent)
265                        .text_color(cx.theme().accent_foreground)
266                }
267            })
268            .when(is_selectable && self.secondary_selected, |this| {
269                this.child(
270                    div()
271                        .absolute()
272                        .inset_0()
273                        .border_1()
274                        .border_color(cx.theme().selection)
275                        .refine_style(&outline_style),
276                )
277            })
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use gpui::{AppContext as _, Context, Render};
285
286    struct DragPreview;
287
288    impl Render for DragPreview {
289        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
290            div()
291        }
292    }
293
294    #[gpui::test]
295    fn test_list_item_interactivity(_cx: &mut gpui::TestAppContext) {
296        let mut item = ListItem::new("item")
297            .on_drag(DragPreview, |_, _, _, cx| cx.new(|_| DragPreview))
298            .drag_over::<DragPreview>(|style, _, _, _| style)
299            .on_drop(|_: &DragPreview, _, _| {})
300            .on_hover(|_, _, _| {});
301
302        assert_eq!(item.interactivity().element_id, Some("item".into()));
303    }
304}