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