context_menu.rs

 1use crate::{prelude::*, ListItemVariant};
 2use crate::{v_stack, Label, List, ListEntry, ListItem, ListSeparator, ListSubHeader};
 3
 4pub enum ContextMenuItem {
 5    Header(SharedString),
 6    Entry(Label),
 7    Separator,
 8}
 9
10impl ContextMenuItem {
11    fn to_list_item<V: 'static>(self) -> ListItem<V> {
12        match self {
13            ContextMenuItem::Header(label) => ListSubHeader::new(label).into(),
14            ContextMenuItem::Entry(label) => {
15                ListEntry::new(label).variant(ListItemVariant::Inset).into()
16            }
17            ContextMenuItem::Separator => ListSeparator::new().into(),
18        }
19    }
20
21    pub fn header(label: impl Into<SharedString>) -> Self {
22        Self::Header(label.into())
23    }
24
25    pub fn separator() -> Self {
26        Self::Separator
27    }
28
29    pub fn entry(label: Label) -> Self {
30        Self::Entry(label)
31    }
32}
33
34#[derive(Component)]
35pub struct ContextMenu {
36    items: Vec<ContextMenuItem>,
37}
38
39impl ContextMenu {
40    pub fn new(items: impl IntoIterator<Item = ContextMenuItem>) -> Self {
41        Self {
42            items: items.into_iter().collect(),
43        }
44    }
45
46    fn render<V: 'static>(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
47        v_stack()
48            .flex()
49            .bg(cx.theme().colors().elevated_surface)
50            .border()
51            .border_color(cx.theme().colors().border)
52            .child(
53                List::new(
54                    self.items
55                        .into_iter()
56                        .map(ContextMenuItem::to_list_item)
57                        .collect(),
58                )
59                .toggle(ToggleState::Toggled),
60            )
61    }
62}
63
64#[cfg(feature = "stories")]
65pub use stories::*;
66
67#[cfg(feature = "stories")]
68mod stories {
69    use super::*;
70    use crate::story::Story;
71    use gpui2::{Div, Render};
72
73    pub struct ContextMenuStory;
74
75    impl Render for ContextMenuStory {
76        type Element = Div<Self>;
77
78        fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
79            Story::container(cx)
80                .child(Story::title_for::<_, ContextMenu>(cx))
81                .child(Story::label(cx, "Default"))
82                .child(ContextMenu::new([
83                    ContextMenuItem::header("Section header"),
84                    ContextMenuItem::Separator,
85                    ContextMenuItem::entry(Label::new("Some entry")),
86                ]))
87        }
88    }
89}