Skip to main content

gpui_material_components/overlay/menu/
item.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, SharedString,
5    Styled, Window, div,
6};
7use gpui_base::TestSupportExt;
8use gpui_material_theme::{CornerShape, TypeRole, TypographyEmphasis};
9
10use crate::menu_appearance::{MenuItemStyle, MenuSurfaceStyle, Paint};
11use crate::{Icon, IconName, SemanticTone};
12
13pub(super) type Action = Rc<dyn Fn(&mut Window, &mut App)>;
14pub(super) type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
15pub(super) type ItemContent = Rc<dyn Fn() -> AnyElement>;
16pub(super) type ComposedTrigger = Box<dyn FnOnce(bool, Action) -> AnyElement>;
17pub(super) type LazyItems = Box<dyn FnOnce(&mut Window, &mut App) -> Vec<MenuItem>>;
18
19pub(super) enum MenuItems {
20    Eager(Vec<MenuItem>),
21    Lazy(LazyItems),
22}
23
24impl MenuItems {
25    pub(super) fn resolve(self, window: &mut Window, cx: &mut App) -> Vec<MenuItem> {
26        match self {
27            Self::Eager(items) => items,
28            Self::Lazy(build) => build(window, cx),
29        }
30    }
31}
32
33/// An item in a Material menu. Callers retain command and selection state.
34pub struct MenuItem {
35    pub(super) id: ElementId,
36    pub(super) label: SharedString,
37    pub(super) disabled: bool,
38    pub(super) kind: Kind,
39    pub(super) slots: ItemSlots,
40    pub(super) on_checked_change: Option<Change>,
41    pub(super) tone: SemanticTone,
42    pub(super) style: MenuItemStyle,
43}
44
45pub(super) enum Kind {
46    Action(Option<Action>),
47    Check(bool, Option<Action>),
48    Select(bool, Option<Action>),
49    Heading,
50    Divider,
51    Section {
52        rows: Vec<MenuItem>,
53        style: MenuSurfaceStyle,
54        inactive_shape: Option<CornerShape>,
55    },
56    Submenu(Vec<MenuItem>),
57}
58
59#[derive(Clone, Default)]
60pub(super) struct ItemSlots {
61    pub(super) content: Option<ItemContent>,
62    pub(super) leading: Option<ItemContent>,
63    pub(super) supporting: Option<ItemContent>,
64    pub(super) trailing: Option<ItemContent>,
65    pub(super) shortcut: Option<SharedString>,
66    pub(super) selection_icon: Option<ItemContent>,
67}
68
69impl ItemSlots {
70    pub(super) fn label(&self, label: SharedString) -> AnyElement {
71        self.content
72            .as_ref()
73            .map_or_else(|| label.into_any_element(), |content| content())
74    }
75
76    pub(super) fn children(
77        &self,
78        label: SharedString,
79        marked: bool,
80        submenu: bool,
81        paint: Paint<'_>,
82        (supporting_color, shortcut_color): (Hsla, Hsla),
83        active: bool,
84    ) -> Vec<AnyElement> {
85        let motion = paint.motion;
86        let icon_size = motion.px(18.);
87        let leading = if marked {
88            Some(self.selection_icon.as_ref().map_or_else(
89                || {
90                    Icon::new(IconName::Check)
91                        .size(icon_size)
92                        .into_any_element()
93                },
94                |icon| icon(),
95            ))
96        } else {
97            self.leading.as_ref().map(|icon| icon())
98        };
99        let supporting_scale = paint.theme.typography.text_scale();
100        let body = div()
101            .flex_1()
102            .min_w_0()
103            .overflow_hidden()
104            .child(div().truncate().child(self.label(label)))
105            .children(self.supporting.as_ref().map(|supporting| {
106                div()
107                    .text_size(motion.px(12. * supporting_scale))
108                    .line_height(motion.px(16. * supporting_scale))
109                    .text_color(supporting_color)
110                    .child(supporting())
111            }));
112        let mut children = vec![
113            div()
114                .min_w(icon_size)
115                .flex_none()
116                .children(leading)
117                .into_any_element(),
118            body.into_any_element(),
119        ];
120        if let Some(trailing) = self.trailing.as_ref() {
121            children.push(trailing());
122        } else if let Some(shortcut) = self.shortcut.as_ref().filter(|text| !text.is_empty()) {
123            let label_small = paint
124                .theme
125                .typography
126                .scale_style(TypeRole::LabelSmall.style(TypographyEmphasis::Baseline));
127            let hint = div()
128                .flex_none()
129                .text_size(motion.px(label_small.size))
130                .line_height(motion.px(label_small.line_height))
131                .text_color(shortcut_color)
132                .child(shortcut.clone());
133            children.push(if active {
134                hint.id("shortcut").test_support().into_any_element()
135            } else {
136                hint.into_any_element()
137            });
138        }
139        children.extend(submenu.then(|| {
140            Icon::new(IconName::ChevronRight)
141                .size(icon_size)
142                .mirror_in_rtl(true)
143                .into_any_element()
144        }));
145        children
146    }
147}
148
149impl MenuItem {
150    /// Creates a standard action menu item with the given element ID and label.
151    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
152        Self {
153            id: id.into(),
154            label: label.into(),
155            disabled: false,
156            kind: Kind::Action(None),
157            slots: ItemSlots::default(),
158            on_checked_change: None,
159            tone: SemanticTone::Default,
160            style: MenuItemStyle::default(),
161        }
162    }
163
164    /// Creates a non-interactive section heading row that is skipped by keyboard navigation.
165    pub fn group(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
166        Self {
167            kind: Kind::Heading,
168            ..Self::new(id, title)
169        }
170    }
171
172    /// Creates a non-interactive horizontal divider row inside a menu that is
173    /// skipped by keyboard navigation.
174    pub fn divider(id: impl Into<ElementId>) -> Self {
175        Self {
176            kind: Kind::Divider,
177            ..Self::new(id, "")
178        }
179    }
180
181    /// Creates a surfaced group with rows in the owning menu's navigation order.
182    pub fn section(
183        id: impl Into<ElementId>,
184        name: impl Into<SharedString>,
185        rows: impl IntoIterator<Item = MenuItem>,
186    ) -> Self {
187        Self {
188            kind: Kind::Section {
189                rows: rows.into_iter().collect(),
190                style: MenuSurfaceStyle::default(),
191                inactive_shape: None,
192            },
193            ..Self::new(id, name)
194        }
195    }
196
197    /// Sets the styled section's surface appearance.
198    pub fn group_appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
199        if let Kind::Section { style, .. } = &mut self.kind {
200            *style = appearance;
201        }
202        self
203    }
204
205    /// Sets the section shape used after the pointer leaves the section.
206    pub fn inactive_shape(mut self, shape: CornerShape) -> Self {
207        if let Kind::Section { inactive_shape, .. } = &mut self.kind {
208            *inactive_shape = Some(shape);
209        }
210        self
211    }
212
213    /// Configures the appearance of an action, checked or selected row.
214    pub fn appearance(mut self, style: MenuItemStyle) -> Self {
215        self.style = style;
216        self
217    }
218
219    /// Applies a Material 3 semantic tone to this row's foreground and selected roles.
220    /// Explicit [`MenuItemStyle`] overrides and disabled styling still take precedence.
221    pub fn tone(mut self, tone: SemanticTone) -> Self {
222        self.tone = tone;
223        self
224    }
225
226    /// Shorthand for `.tone(SemanticTone::Danger)` on destructive menu commands.
227    pub fn destructive(self) -> Self {
228        self.tone(SemanticTone::Danger)
229    }
230
231    /// Renders a desktop shortcut hint in the trailing slot using `LabelSmall`
232    /// and `OnSurfaceVariant` (or disabled color when disabled), unless an
233    /// explicit `.trailing(...)` overrides it.
234    pub fn shortcut(mut self, text: impl Into<SharedString>) -> Self {
235        self.slots.shortcut = Some(text.into());
236        self
237    }
238
239    /// Turns this row into a submenu trigger containing the given child items.
240    pub fn submenu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
241        self.kind = Kind::Submenu(items.into_iter().collect());
242        self
243    }
244
245    /// Marks the item as disabled, preventing activation and applying disabled styling.
246    pub fn disabled(mut self, disabled: bool) -> Self {
247        self.disabled = disabled;
248        self
249    }
250
251    /// Turns this row into a checkable menu item with the given caller-owned checked state.
252    pub fn checked(mut self, checked: bool) -> Self {
253        self.kind = Kind::Check(checked, self.action());
254        self
255    }
256
257    /// Turns this row into a selectable menu item with the given caller-owned selected state.
258    pub fn selected(mut self, selected: bool) -> Self {
259        self.kind = Kind::Select(selected, self.action());
260        self
261    }
262
263    /// Replaces the visible label while retaining the name passed to `new`.
264    /// Supply a repeatable factory so the content also appears during exit.
265    pub fn content<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
266        self.slots.content = Some(Rc::new(move || build().into_any_element()));
267        self
268    }
269
270    /// Supplies a decorative element at the logical start of an unmarked row.
271    pub fn leading<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
272        self.slots.leading = Some(Rc::new(move || build().into_any_element()));
273        self
274    }
275
276    /// Supplies additional visual content below the label.
277    pub fn supporting<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
278        self.slots.supporting = Some(Rc::new(move || build().into_any_element()));
279        self
280    }
281
282    /// Supplies decorative content at the logical end of the row.
283    pub fn trailing<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
284        self.slots.trailing = Some(Rc::new(move || build().into_any_element()));
285        self
286    }
287
288    /// Replaces the leading check mark of a checked or selected row.
289    pub fn selection_icon<E: IntoElement>(mut self, build: impl Fn() -> E + 'static) -> Self {
290        self.slots.selection_icon = Some(Rc::new(move || build().into_any_element()));
291        self
292    }
293
294    /// Requests the inverse of the supplied checked value on activation.
295    /// The checked callback takes precedence over `on_activate` on checked rows.
296    pub fn on_checked_change(
297        mut self,
298        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
299    ) -> Self {
300        self.on_checked_change = Some(Rc::new(callback));
301        self
302    }
303
304    fn action(&self) -> Option<Action> {
305        match &self.kind {
306            Kind::Action(action) | Kind::Check(_, action) | Kind::Select(_, action) => {
307                action.clone()
308            }
309            _ => None,
310        }
311    }
312
313    pub(super) fn activation(&self) -> Option<Action> {
314        if let Kind::Check(checked, _) = self.kind
315            && let Some(callback) = &self.on_checked_change
316        {
317            let callback = callback.clone();
318            return Some(Rc::new(move |window, cx| callback(!checked, window, cx)));
319        }
320        self.action()
321    }
322
323    /// Registers a callback invoked when an action, checked, or selected row is activated.
324    pub fn on_activate(mut self, action: impl Fn(&mut Window, &mut App) + 'static) -> Self {
325        match &mut self.kind {
326            Kind::Action(handler) | Kind::Check(_, handler) | Kind::Select(_, handler) => {
327                *handler = Some(Rc::new(action));
328            }
329            _ => {}
330        }
331        self
332    }
333}