list_item.rs

  1use std::sync::Arc;
  2
  3use component::{Component, ComponentScope, example_group_with_title, single_example};
  4use gpui::{AnyElement, AnyView, ClickEvent, MouseButton, MouseDownEvent, Pixels, px};
  5use smallvec::SmallVec;
  6
  7use crate::{Disclosure, GradientFade, prelude::*};
  8
  9#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
 10pub enum ListItemSpacing {
 11    #[default]
 12    Dense,
 13    ExtraDense,
 14    Sparse,
 15}
 16
 17#[derive(IntoElement, RegisterComponent)]
 18pub struct ListItem {
 19    id: ElementId,
 20    group_name: Option<SharedString>,
 21    disabled: bool,
 22    selected: bool,
 23    spacing: ListItemSpacing,
 24    indent_level: usize,
 25    indent_step_size: Pixels,
 26    /// A slot for content that appears before the children, like an icon or avatar.
 27    start_slot: Option<AnyElement>,
 28    /// A slot for content that appears after the children, usually on the other side of the header.
 29    /// This might be a button, a disclosure arrow, a face pile, etc.
 30    end_slot: Option<AnyElement>,
 31    /// A slot for content that appears on hover after the children
 32    /// It will obscure the `end_slot` when visible.
 33    end_hover_slot: Option<AnyElement>,
 34    toggle: Option<bool>,
 35    inset: bool,
 36    on_click: Option<Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
 37    on_hover: Option<Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>>,
 38    on_toggle: Option<Arc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>>,
 39    tooltip: Option<Box<dyn Fn(&mut Window, &mut App) -> AnyView + 'static>>,
 40    on_secondary_mouse_down: Option<Box<dyn Fn(&MouseDownEvent, &mut Window, &mut App) + 'static>>,
 41    children: SmallVec<[AnyElement; 2]>,
 42    selectable: bool,
 43    always_show_disclosure_icon: bool,
 44    outlined: bool,
 45    rounded: bool,
 46    overflow_x: bool,
 47    focused: Option<bool>,
 48}
 49
 50impl ListItem {
 51    pub fn new(id: impl Into<ElementId>) -> Self {
 52        Self {
 53            id: id.into(),
 54            group_name: None,
 55            disabled: false,
 56            selected: false,
 57            spacing: ListItemSpacing::Dense,
 58            indent_level: 0,
 59            indent_step_size: px(12.),
 60            start_slot: None,
 61            end_slot: None,
 62            end_hover_slot: None,
 63            toggle: None,
 64            inset: false,
 65            on_click: None,
 66            on_secondary_mouse_down: None,
 67            on_toggle: None,
 68            on_hover: None,
 69            tooltip: None,
 70            children: SmallVec::new(),
 71            selectable: true,
 72            always_show_disclosure_icon: false,
 73            outlined: false,
 74            rounded: false,
 75            overflow_x: false,
 76            focused: None,
 77        }
 78    }
 79
 80    pub fn group_name(mut self, group_name: impl Into<SharedString>) -> Self {
 81        self.group_name = Some(group_name.into());
 82        self
 83    }
 84
 85    pub fn spacing(mut self, spacing: ListItemSpacing) -> Self {
 86        self.spacing = spacing;
 87        self
 88    }
 89
 90    pub fn selectable(mut self, has_hover: bool) -> Self {
 91        self.selectable = has_hover;
 92        self
 93    }
 94
 95    pub fn always_show_disclosure_icon(mut self, show: bool) -> Self {
 96        self.always_show_disclosure_icon = show;
 97        self
 98    }
 99
100    pub fn on_click(
101        mut self,
102        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
103    ) -> Self {
104        self.on_click = Some(Box::new(handler));
105        self
106    }
107
108    pub fn on_hover(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
109        self.on_hover = Some(Box::new(handler));
110        self
111    }
112
113    pub fn on_secondary_mouse_down(
114        mut self,
115        handler: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
116    ) -> Self {
117        self.on_secondary_mouse_down = Some(Box::new(handler));
118        self
119    }
120
121    pub fn tooltip(mut self, tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static) -> Self {
122        self.tooltip = Some(Box::new(tooltip));
123        self
124    }
125
126    pub fn inset(mut self, inset: bool) -> Self {
127        self.inset = inset;
128        self
129    }
130
131    pub fn indent_level(mut self, indent_level: usize) -> Self {
132        self.indent_level = indent_level;
133        self
134    }
135
136    pub fn indent_step_size(mut self, indent_step_size: Pixels) -> Self {
137        self.indent_step_size = indent_step_size;
138        self
139    }
140
141    pub fn toggle(mut self, toggle: impl Into<Option<bool>>) -> Self {
142        self.toggle = toggle.into();
143        self
144    }
145
146    pub fn on_toggle(
147        mut self,
148        on_toggle: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
149    ) -> Self {
150        self.on_toggle = Some(Arc::new(on_toggle));
151        self
152    }
153
154    pub fn start_slot<E: IntoElement>(mut self, start_slot: impl Into<Option<E>>) -> Self {
155        self.start_slot = start_slot.into().map(IntoElement::into_any_element);
156        self
157    }
158
159    pub fn end_slot<E: IntoElement>(mut self, end_slot: impl Into<Option<E>>) -> Self {
160        self.end_slot = end_slot.into().map(IntoElement::into_any_element);
161        self
162    }
163
164    pub fn end_hover_slot<E: IntoElement>(mut self, end_hover_slot: impl Into<Option<E>>) -> Self {
165        self.end_hover_slot = end_hover_slot.into().map(IntoElement::into_any_element);
166        self
167    }
168
169    pub fn outlined(mut self) -> Self {
170        self.outlined = true;
171        self
172    }
173
174    pub fn rounded(mut self) -> Self {
175        self.rounded = true;
176        self
177    }
178
179    pub fn overflow_x(mut self) -> Self {
180        self.overflow_x = true;
181        self
182    }
183
184    pub fn focused(mut self, focused: bool) -> Self {
185        self.focused = Some(focused);
186        self
187    }
188}
189
190impl Disableable for ListItem {
191    fn disabled(mut self, disabled: bool) -> Self {
192        self.disabled = disabled;
193        self
194    }
195}
196
197impl Toggleable for ListItem {
198    fn toggle_state(mut self, selected: bool) -> Self {
199        self.selected = selected;
200        self
201    }
202}
203
204impl ParentElement for ListItem {
205    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
206        self.children.extend(elements)
207    }
208}
209
210impl RenderOnce for ListItem {
211    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
212        let color = cx.theme().colors();
213
214        let base_bg = if self.selected {
215            color.element_active
216        } else {
217            color.panel_background
218        };
219
220        let end_hover_gradient_overlay =
221            GradientFade::new(base_bg, color.element_hover, color.element_active)
222                .width(px(96.0))
223                .when_some(self.group_name.clone(), |fade, group| {
224                    fade.group_name(group)
225                });
226
227        h_flex()
228            .id(self.id)
229            .when_some(self.group_name, |this, group| this.group(group))
230            .w_full()
231            .relative()
232            // When an item is inset draw the indent spacing outside of the item
233            .when(self.inset, |this| {
234                this.ml(self.indent_level as f32 * self.indent_step_size)
235                    .px(DynamicSpacing::Base04.rems(cx))
236            })
237            .when(!self.inset && !self.disabled, |this| {
238                this.when_some(self.focused, |this, focused| {
239                    if focused {
240                        this.border_1()
241                            .border_color(cx.theme().colors().border_focused)
242                    } else {
243                        this.border_1()
244                    }
245                })
246                .when(self.selectable, |this| {
247                    this.hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
248                        .active(|style| style.bg(cx.theme().colors().ghost_element_active))
249                        .when(self.outlined, |this| this.rounded_sm())
250                        .when(self.selected, |this| {
251                            this.bg(cx.theme().colors().ghost_element_selected)
252                        })
253                })
254            })
255            .when(self.rounded, |this| this.rounded_sm())
256            .when_some(self.on_hover, |this, on_hover| this.on_hover(on_hover))
257            .child(
258                h_flex()
259                    .id("inner_list_item")
260                    .group("list_item")
261                    .w_full()
262                    .relative()
263                    .gap_1()
264                    .px(DynamicSpacing::Base06.rems(cx))
265                    .map(|this| match self.spacing {
266                        ListItemSpacing::Dense => this,
267                        ListItemSpacing::ExtraDense => this.py_neg_px(),
268                        ListItemSpacing::Sparse => this.py_1(),
269                    })
270                    .when(self.inset && !self.disabled, |this| {
271                        this
272                            // TODO: Add focus state
273                            //.when(self.state == InteractionState::Focused, |this| {
274                            .when_some(self.focused, |this, focused| {
275                                if focused {
276                                    this.border_1()
277                                        .border_color(cx.theme().colors().border_focused)
278                                } else {
279                                    this.border_1()
280                                }
281                            })
282                            .when(self.selectable, |this| {
283                                this.hover(|style| {
284                                    style.bg(cx.theme().colors().ghost_element_hover)
285                                })
286                                .active(|style| style.bg(cx.theme().colors().ghost_element_active))
287                                .when(self.selected, |this| {
288                                    this.bg(cx.theme().colors().ghost_element_selected)
289                                })
290                            })
291                    })
292                    .when_some(
293                        self.on_click.filter(|_| !self.disabled),
294                        |this, on_click| this.cursor_pointer().on_click(on_click),
295                    )
296                    .when(self.outlined, |this| {
297                        this.border_1()
298                            .border_color(cx.theme().colors().border)
299                            .rounded_sm()
300                            .overflow_hidden()
301                    })
302                    .when_some(self.on_secondary_mouse_down, |this, on_mouse_down| {
303                        this.on_mouse_down(MouseButton::Right, move |event, window, cx| {
304                            (on_mouse_down)(event, window, cx)
305                        })
306                    })
307                    .when_some(self.tooltip, |this, tooltip| this.tooltip(tooltip))
308                    .map(|this| {
309                        if self.inset {
310                            this.rounded_sm()
311                        } else {
312                            // When an item is not inset draw the indent spacing inside of the item
313                            this.ml(self.indent_level as f32 * self.indent_step_size)
314                        }
315                    })
316                    .children(self.toggle.map(|is_open| {
317                        div()
318                            .flex()
319                            .absolute()
320                            .left(rems(-1.))
321                            .when(is_open && !self.always_show_disclosure_icon, |this| {
322                                this.visible_on_hover("")
323                            })
324                            .child(
325                                Disclosure::new("toggle", is_open)
326                                    .on_toggle_expanded(self.on_toggle),
327                            )
328                    }))
329                    .child(
330                        h_flex()
331                            .flex_grow()
332                            .flex_shrink_0()
333                            .flex_basis(relative(0.25))
334                            .gap(DynamicSpacing::Base06.rems(cx))
335                            .map(|list_content| {
336                                if self.overflow_x {
337                                    list_content
338                                } else {
339                                    list_content.overflow_hidden()
340                                }
341                            })
342                            .children(self.start_slot)
343                            .children(self.children),
344                    )
345                    .when_some(self.end_slot, |this, end_slot| {
346                        this.justify_between().child(
347                            h_flex()
348                                .flex_shrink()
349                                .overflow_hidden()
350                                .when(self.end_hover_slot.is_some(), |this| {
351                                    this.visible()
352                                        .group_hover("list_item", |this| this.invisible())
353                                })
354                                .child(end_slot),
355                        )
356                    })
357                    .when_some(self.end_hover_slot, |this, end_hover_slot| {
358                        this.child(
359                            h_flex()
360                                .h_full()
361                                .absolute()
362                                .right(DynamicSpacing::Base06.rems(cx))
363                                .top_0()
364                                .visible_on_hover("list_item")
365                                .child(end_hover_gradient_overlay)
366                                .child(end_hover_slot),
367                        )
368                    }),
369            )
370    }
371}
372
373impl Component for ListItem {
374    fn scope() -> ComponentScope {
375        ComponentScope::DataDisplay
376    }
377
378    fn description() -> Option<&'static str> {
379        Some(
380            "A flexible list item component with support for icons, actions, disclosure toggles, and hierarchical display.",
381        )
382    }
383
384    fn preview(_window: &mut Window, _cx: &mut App) -> Option<AnyElement> {
385        Some(
386            v_flex()
387                .gap_6()
388                .children(vec![
389                    example_group_with_title(
390                        "Basic List Items",
391                        vec![
392                            single_example(
393                                "Simple",
394                                ListItem::new("simple")
395                                    .child(Label::new("Simple list item"))
396                                    .into_any_element(),
397                            ),
398                            single_example(
399                                "With Icon",
400                                ListItem::new("with_icon")
401                                    .start_slot(Icon::new(IconName::File))
402                                    .child(Label::new("List item with icon"))
403                                    .into_any_element(),
404                            ),
405                            single_example(
406                                "Selected",
407                                ListItem::new("selected")
408                                    .toggle_state(true)
409                                    .start_slot(Icon::new(IconName::Check))
410                                    .child(Label::new("Selected item"))
411                                    .into_any_element(),
412                            ),
413                        ],
414                    ),
415                    example_group_with_title(
416                        "List Item Spacing",
417                        vec![
418                            single_example(
419                                "Dense",
420                                ListItem::new("dense")
421                                    .spacing(ListItemSpacing::Dense)
422                                    .child(Label::new("Dense spacing"))
423                                    .into_any_element(),
424                            ),
425                            single_example(
426                                "Extra Dense",
427                                ListItem::new("extra_dense")
428                                    .spacing(ListItemSpacing::ExtraDense)
429                                    .child(Label::new("Extra dense spacing"))
430                                    .into_any_element(),
431                            ),
432                            single_example(
433                                "Sparse",
434                                ListItem::new("sparse")
435                                    .spacing(ListItemSpacing::Sparse)
436                                    .child(Label::new("Sparse spacing"))
437                                    .into_any_element(),
438                            ),
439                        ],
440                    ),
441                    example_group_with_title(
442                        "With Slots",
443                        vec![
444                            single_example(
445                                "End Slot",
446                                ListItem::new("end_slot")
447                                    .child(Label::new("Item with end slot"))
448                                    .end_slot(Icon::new(IconName::ChevronRight))
449                                    .into_any_element(),
450                            ),
451                            single_example(
452                                "With Toggle",
453                                ListItem::new("with_toggle")
454                                    .toggle(Some(true))
455                                    .child(Label::new("Expandable item"))
456                                    .into_any_element(),
457                            ),
458                        ],
459                    ),
460                    example_group_with_title(
461                        "States",
462                        vec![
463                            single_example(
464                                "Disabled",
465                                ListItem::new("disabled")
466                                    .disabled(true)
467                                    .child(Label::new("Disabled item"))
468                                    .into_any_element(),
469                            ),
470                            single_example(
471                                "Non-selectable",
472                                ListItem::new("non_selectable")
473                                    .selectable(false)
474                                    .child(Label::new("Non-selectable item"))
475                                    .into_any_element(),
476                            ),
477                        ],
478                    ),
479                ])
480                .into_any_element(),
481        )
482    }
483}