Skip to main content

fc_ui/capabilities/navigation/
menu.rs

1//! Menu system for dropdown and context menus.
2
3use crate::capabilities::foundation::theme::{use_theme, Theme};
4use crate::capabilities::primitives::icon::Icon;
5use crate::capabilities::primitives::icon_source::IconSource;
6use crate::capabilities::primitives::text::{body, caption};
7use gpui::{prelude::FluentBuilder as _, InteractiveElement, *};
8use std::rc::Rc;
9
10#[derive(Clone, Debug)]
11pub enum MenuItemKind {
12    Action,
13    Checkbox { checked: bool },
14    Radio { checked: bool },
15    Submenu,
16    Separator,
17}
18
19#[derive(Clone)]
20pub struct MenuItem {
21    pub id: SharedString,
22    pub label: SharedString,
23    pub icon: Option<IconSource>,
24    pub shortcut: Option<SharedString>,
25    pub kind: MenuItemKind,
26    pub disabled: bool,
27    pub on_click: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
28    pub children: Vec<MenuItem>,
29}
30
31impl MenuItem {
32    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
33        Self {
34            id: id.into(),
35            label: label.into(),
36            icon: None,
37            shortcut: None,
38            kind: MenuItemKind::Action,
39            disabled: false,
40            on_click: None,
41            children: Vec::new(),
42        }
43    }
44
45    pub fn separator() -> Self {
46        Self {
47            id: SharedString::from("separator"),
48            label: SharedString::from(""),
49            icon: None,
50            shortcut: None,
51            kind: MenuItemKind::Separator,
52            disabled: false,
53            on_click: None,
54            children: Vec::new(),
55        }
56    }
57
58    pub fn checkbox(
59        id: impl Into<SharedString>,
60        label: impl Into<SharedString>,
61        checked: bool,
62    ) -> Self {
63        Self {
64            id: id.into(),
65            label: label.into(),
66            icon: None,
67            shortcut: None,
68            kind: MenuItemKind::Checkbox { checked },
69            disabled: false,
70            on_click: None,
71            children: Vec::new(),
72        }
73    }
74
75    pub fn submenu(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
76        Self {
77            id: id.into(),
78            label: label.into(),
79            icon: None,
80            shortcut: None,
81            kind: MenuItemKind::Submenu,
82            disabled: false,
83            on_click: None,
84            children: Vec::new(),
85        }
86    }
87
88    pub fn with_icon(mut self, icon: impl Into<IconSource>) -> Self {
89        self.icon = Some(icon.into());
90        self
91    }
92
93    pub fn with_shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
94        self.shortcut = Some(shortcut.into());
95        self
96    }
97
98    pub fn disabled(mut self, disabled: bool) -> Self {
99        self.disabled = disabled;
100        self
101    }
102
103    pub fn on_click<F>(mut self, handler: F) -> Self
104    where
105        F: Fn(&mut Window, &mut App) + 'static,
106    {
107        self.on_click = Some(Rc::new(handler));
108        self
109    }
110
111    pub fn with_children(mut self, children: Vec<MenuItem>) -> Self {
112        self.children = children;
113        self
114    }
115}
116
117#[derive(IntoElement)]
118pub struct Menu {
119    items: Vec<MenuItem>,
120    min_width: Pixels,
121    max_height: Option<Pixels>,
122    style: StyleRefinement,
123}
124
125impl Menu {
126    pub fn new(items: Vec<MenuItem>) -> Self {
127        Self {
128            items,
129            min_width: px(200.0),
130            max_height: Some(px(400.0)),
131            style: StyleRefinement::default(),
132        }
133    }
134
135    pub fn min_width(mut self, width: Pixels) -> Self {
136        self.min_width = width;
137        self
138    }
139
140    pub fn max_height(mut self, height: Option<Pixels>) -> Self {
141        self.max_height = height;
142        self
143    }
144}
145
146impl Styled for Menu {
147    fn style(&mut self) -> &mut StyleRefinement {
148        &mut self.style
149    }
150}
151
152impl RenderOnce for Menu {
153    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
154        let theme = use_theme(cx);
155        let user_style = self.style;
156
157        div()
158            .min_w(self.min_width)
159            .when_some(self.max_height, |div, h| div.max_h(h))
160            .flex()
161            .flex_col()
162            .bg(theme.tokens.popover)
163            .border_1()
164            .border_color(theme.tokens.border)
165            .rounded(theme.tokens.radius_md)
166            .shadow_lg()
167            .p(px(4.0))
168            .children(
169                self.items
170                    .into_iter()
171                    .map(|item| render_menu_item(item, theme.clone())),
172            )
173            .map(|this| {
174                let mut div = this;
175                div.style().refine(&user_style);
176                div
177            })
178    }
179}
180
181fn render_menu_item(item: MenuItem, theme: Theme) -> impl IntoElement {
182    match item.kind {
183        MenuItemKind::Separator => div()
184            .h(px(1.0))
185            .bg(theme.tokens.border)
186            .my(px(4.0))
187            .mx(px(8.0)),
188        _ => {
189            let is_checked = matches!(
190                item.kind,
191                MenuItemKind::Checkbox { checked: true } | MenuItemKind::Radio { checked: true }
192            );
193            let has_submenu = matches!(item.kind, MenuItemKind::Submenu);
194
195            div()
196                .flex()
197                .items_center()
198                .gap(px(12.0))
199                .px(px(12.0))
200                .py(px(8.0))
201                .rounded(theme.tokens.radius_sm)
202                .cursor(if item.disabled {
203                    CursorStyle::Arrow
204                } else {
205                    CursorStyle::PointingHand
206                })
207                .when(item.disabled, |div| div.opacity(0.5))
208                .when(!item.disabled, |div| {
209                    div.hover(|style| style.bg(theme.tokens.accent))
210                })
211                .when_some(item.on_click.filter(|_| !item.disabled), |div, handler| {
212                    div.on_mouse_down(MouseButton::Left, move |_event, window, cx| {
213                        handler(window, cx);
214                    })
215                })
216                .child(
217                    div()
218                        .w(px(16.0))
219                        .h(px(16.0))
220                        .flex()
221                        .items_center()
222                        .justify_center()
223                        .when(is_checked, |div| {
224                            div.child(
225                                Icon::new("check")
226                                    .size(px(12.0))
227                                    .color(theme.tokens.foreground),
228                            )
229                        }),
230                )
231                .when_some(item.icon, |div, icon| {
232                    div.child(Icon::new(icon).size(px(16.0)).color(if item.disabled {
233                        theme.tokens.muted_foreground
234                    } else {
235                        theme.tokens.foreground
236                    }))
237                })
238                .child(
239                    div()
240                        .flex_1()
241                        .child(body(item.label).color(if item.disabled {
242                            theme.tokens.muted_foreground
243                        } else {
244                            theme.tokens.foreground
245                        })),
246                )
247                .when_some(item.shortcut, |div, shortcut| {
248                    div.child(
249                        caption(shortcut)
250                            .color(theme.tokens.muted_foreground)
251                            .no_wrap(),
252                    )
253                })
254                .when(has_submenu, |div| {
255                    div.child(
256                        Icon::new("chevron-right")
257                            .size(px(14.0))
258                            .color(theme.tokens.muted_foreground),
259                    )
260                })
261        }
262    }
263}
264
265#[derive(Clone)]
266pub struct MenuBarItem {
267    pub id: SharedString,
268    pub label: SharedString,
269    pub menu_items: Vec<MenuItem>,
270}
271
272impl MenuBarItem {
273    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
274        Self {
275            id: id.into(),
276            label: label.into(),
277            menu_items: Vec::new(),
278        }
279    }
280
281    pub fn with_items(mut self, items: Vec<MenuItem>) -> Self {
282        self.menu_items = items;
283        self
284    }
285}
286
287actions!(menu, [DismissMenu]);
288
289pub struct MenuBar {
290    items: Vec<MenuBarItem>,
291    active_menu: Option<usize>,
292    item_bounds: Vec<Option<Bounds<Pixels>>>,
293    focus_handle: Option<FocusHandle>,
294}
295
296impl MenuBar {
297    pub fn new(items: Vec<MenuBarItem>) -> Self {
298        let item_bounds = items.iter().map(|_| None).collect();
299        Self {
300            items,
301            active_menu: None,
302            item_bounds,
303            focus_handle: None,
304        }
305    }
306}
307
308impl Render for MenuBar {
309    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
310        let theme = use_theme(cx);
311        let focus_handle = self
312            .focus_handle
313            .get_or_insert_with(|| cx.focus_handle())
314            .clone();
315
316        div()
317            .key_context("MenuBar")
318            .track_focus(&focus_handle)
319            .on_mouse_down_out(cx.listener(|this, _, _, cx| {
320                if this.active_menu.is_some() {
321                    this.active_menu = None;
322                    cx.notify();
323                }
324            }))
325            .when(self.active_menu.is_some(), |this| {
326                this.on_action(cx.listener(|this, _: &DismissMenu, _window, cx| {
327                    this.active_menu = None;
328                    cx.notify();
329                }))
330            })
331            .flex()
332            .items_center()
333            .h(px(40.0))
334            .px(px(8.0))
335            .gap(px(2.0))
336            .bg(theme.tokens.background)
337            .border_b_1()
338            .border_color(theme.tokens.border)
339            .children(self.items.iter().enumerate().map(|(idx, item)| {
340                let is_active = self.active_menu == Some(idx);
341                let label = item.label.clone();
342                let focus_handle = focus_handle.clone();
343                let entity = cx.entity().clone();
344
345                let dropdown = if is_active {
346                    self.item_bounds.get(idx).copied().flatten().map(|bounds| {
347                        deferred(
348                            anchored()
349                                .snap_to_window_with_margin(px(8.0))
350                                .position(point(bounds.left(), bounds.bottom()))
351                                .child(div().occlude().child(Menu::new(item.menu_items.clone()))),
352                        )
353                        .with_priority(1)
354                        .into_any_element()
355                    })
356                } else {
357                    None
358                };
359
360                div()
361                    .relative()
362                    .px(px(12.0))
363                    .py(px(6.0))
364                    .rounded(theme.tokens.radius_sm)
365                    .cursor(CursorStyle::PointingHand)
366                    .when(is_active, |div| div.bg(theme.tokens.accent))
367                    .when(!is_active, |div| {
368                        div.hover(|style| style.bg(theme.tokens.muted))
369                    })
370                    .on_mouse_down(
371                        MouseButton::Left,
372                        cx.listener(move |this, _event, window, cx| {
373                            let opening = this.active_menu != Some(idx);
374                            this.active_menu = if opening { Some(idx) } else { None };
375                            if opening {
376                                window.focus(&focus_handle);
377                            }
378                            cx.notify();
379                        }),
380                    )
381                    .child(body(label).color(theme.tokens.foreground))
382                    .child(
383                        canvas(
384                            move |bounds, _window, cx| {
385                                entity.update(cx, |this, _| {
386                                    if let Some(slot) = this.item_bounds.get_mut(idx) {
387                                        *slot = Some(bounds);
388                                    }
389                                });
390                            },
391                            |_bounds, _, _window, _cx| {},
392                        )
393                        .absolute()
394                        .inset_0(),
395                    )
396                    .children(dropdown)
397            }))
398    }
399}
400
401pub fn init_menu_bar(cx: &mut App) {
402    if !crate::capabilities::foundation::initialization::begin(cx, "menu-bar") {
403        return;
404    }
405    cx.bind_keys([KeyBinding::new("escape", DismissMenu, Some("MenuBar"))]);
406}
407
408#[derive(IntoElement)]
409pub struct ContextMenu {
410    items: Vec<MenuItem>,
411    position: Point<Pixels>,
412}
413
414impl ContextMenu {
415    pub fn new(items: Vec<MenuItem>, position: Point<Pixels>) -> Self {
416        Self { items, position }
417    }
418}
419
420impl RenderOnce for ContextMenu {
421    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
422        let theme = use_theme(cx);
423
424        anchored()
425            .snap_to_window_with_margin(px(8.0))
426            .anchor(Corner::TopLeft)
427            .position(self.position)
428            .child(
429                div()
430                    .min_w(px(200.0))
431                    .max_h(px(400.0))
432                    .flex()
433                    .flex_col()
434                    .bg(theme.tokens.popover)
435                    .border_1()
436                    .border_color(theme.tokens.border)
437                    .rounded(theme.tokens.radius_md)
438                    .shadow_lg()
439                    .p(px(4.0))
440                    .children(
441                        self.items
442                            .into_iter()
443                            .map(|item| render_menu_item(item, theme.clone())),
444                    ),
445            )
446    }
447}