Skip to main content

fc_ui/capabilities/navigation/
navigation_menu.rs

1//! Navigation menu component - Hierarchical navigation with expand/collapse state.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::collections::HashSet;
5use std::hash::Hash;
6use std::sync::Arc;
7
8use crate::capabilities::foundation::theme::use_theme;
9use crate::capabilities::primitives::icon::Icon;
10use crate::capabilities::primitives::icon_source::IconSource;
11use crate::capabilities::primitives::text::{Text, TextVariant};
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
14pub enum NavigationMenuOrientation {
15    #[default]
16    Horizontal,
17    Vertical,
18}
19
20#[derive(Clone)]
21pub struct NavigationMenuItem<T: Clone = SharedString> {
22    pub id: T,
23    pub label: SharedString,
24    pub icon: Option<IconSource>,
25    pub disabled: bool,
26    pub children: Vec<NavigationMenuItem<T>>,
27}
28
29impl<T: Clone> NavigationMenuItem<T> {
30    pub fn new(id: T, label: impl Into<SharedString>) -> Self {
31        Self {
32            id,
33            label: label.into(),
34            icon: None,
35            disabled: false,
36            children: Vec::new(),
37        }
38    }
39
40    pub fn with_icon(mut self, icon: impl Into<IconSource>) -> Self {
41        self.icon = Some(icon.into());
42        self
43    }
44
45    pub fn disabled(mut self, disabled: bool) -> Self {
46        self.disabled = disabled;
47        self
48    }
49
50    pub fn with_children(mut self, children: Vec<NavigationMenuItem<T>>) -> Self {
51        self.children = children;
52        self
53    }
54
55    pub fn has_children(&self) -> bool {
56        !self.children.is_empty()
57    }
58}
59
60#[derive(IntoElement)]
61pub struct NavigationMenu<T: Clone + PartialEq + Eq + Hash + 'static> {
62    orientation: NavigationMenuOrientation,
63    items: Vec<NavigationMenuItem<T>>,
64    selected_id: Option<T>,
65    expanded_ids: Vec<T>,
66    on_select: Option<Arc<dyn Fn(&T, &mut Window, &mut App) + Send + Sync + 'static>>,
67    on_toggle: Option<Arc<dyn Fn(&T, bool, &mut Window, &mut App) + Send + Sync + 'static>>,
68    style: StyleRefinement,
69}
70
71impl<T: Clone + PartialEq + Eq + Hash + 'static> NavigationMenu<T> {
72    /// Create a new navigation menu
73    pub fn new() -> Self {
74        Self {
75            orientation: NavigationMenuOrientation::default(),
76            items: Vec::new(),
77            selected_id: None,
78            expanded_ids: Vec::new(),
79            on_select: None,
80            on_toggle: None,
81            style: StyleRefinement::default(),
82        }
83    }
84
85    /// Set the menu orientation
86    pub fn orientation(mut self, orientation: NavigationMenuOrientation) -> Self {
87        self.orientation = orientation;
88        self
89    }
90
91    /// Add a menu item
92    pub fn item(mut self, item: NavigationMenuItem<T>) -> Self {
93        self.items.push(item);
94        self
95    }
96
97    /// Add multiple menu items
98    pub fn items(mut self, items: Vec<NavigationMenuItem<T>>) -> Self {
99        self.items = items;
100        self
101    }
102
103    /// Set the selected item ID
104    pub fn selected_id(mut self, id: T) -> Self {
105        self.selected_id = Some(id);
106        self
107    }
108
109    /// Set the expanded item IDs
110    pub fn expanded_ids(mut self, ids: Vec<T>) -> Self {
111        self.expanded_ids = ids;
112        self
113    }
114
115    /// Set the selection handler
116    pub fn on_select<F>(mut self, f: F) -> Self
117    where
118        F: Fn(&T, &mut Window, &mut App) + Send + Sync + 'static,
119    {
120        self.on_select = Some(Arc::new(f));
121        self
122    }
123
124    /// Set the toggle (expand/collapse) handler
125    pub fn on_toggle<F>(mut self, f: F) -> Self
126    where
127        F: Fn(&T, bool, &mut Window, &mut App) + Send + Sync + 'static,
128    {
129        self.on_toggle = Some(Arc::new(f));
130        self
131    }
132}
133
134impl<T: Clone + PartialEq + Eq + Hash + 'static> Default for NavigationMenu<T> {
135    fn default() -> Self {
136        Self::new()
137    }
138}
139
140impl<T: Clone + PartialEq + Eq + Hash + 'static> Styled for NavigationMenu<T> {
141    fn style(&mut self) -> &mut StyleRefinement {
142        &mut self.style
143    }
144}
145
146impl<T: Clone + PartialEq + Eq + Hash + 'static> RenderOnce for NavigationMenu<T> {
147    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
148        let theme = use_theme(cx);
149        let orientation = self.orientation;
150
151        let expanded_set: HashSet<T> = self.expanded_ids.into_iter().collect();
152        let selected_id = self.selected_id;
153        let on_select = self.on_select;
154        let on_toggle = self.on_toggle;
155        let user_style = self.style;
156
157        div()
158            .flex()
159            .when(
160                orientation == NavigationMenuOrientation::Horizontal,
161                |this: Div| this.flex_row().items_center().gap(px(4.0)),
162            )
163            .when(
164                orientation == NavigationMenuOrientation::Vertical,
165                |this: Div| this.flex_col().gap(px(2.0)),
166            )
167            .children(self.items.into_iter().map(move |item| {
168                render_menu_item(
169                    item,
170                    orientation,
171                    &theme,
172                    0,
173                    &expanded_set,
174                    &selected_id,
175                    &on_select,
176                    &on_toggle,
177                )
178            }))
179            .map(|this| {
180                let mut div = this;
181                div.style().refine(&user_style);
182                div
183            })
184    }
185}
186
187/// Render a single menu item recursively
188fn render_menu_item<T: Clone + PartialEq + Eq + Hash + 'static>(
189    item: NavigationMenuItem<T>,
190    orientation: NavigationMenuOrientation,
191    theme: &crate::capabilities::foundation::theme::Theme,
192    depth: usize,
193    expanded_set: &HashSet<T>,
194    selected_id: &Option<T>,
195    on_select: &Option<Arc<dyn Fn(&T, &mut Window, &mut App) + Send + Sync + 'static>>,
196    on_toggle: &Option<Arc<dyn Fn(&T, bool, &mut Window, &mut App) + Send + Sync + 'static>>,
197) -> impl IntoElement {
198    let has_children = item.has_children();
199    let disabled = item.disabled;
200    let is_expanded = expanded_set.contains(&item.id);
201    let is_selected = selected_id.as_ref() == Some(&item.id);
202    let indent = px(depth as f32 * 16.0);
203
204    div()
205        .flex()
206        .flex_col()
207        .child(
208            div()
209                .flex()
210                .items_center()
211                .gap(px(4.0))
212                .px(px(8.0))
213                .py(px(8.0))
214                .pl(when(
215                    orientation == NavigationMenuOrientation::Vertical && depth > 0,
216                    indent + px(8.0),
217                    px(8.0),
218                ))
219                .rounded(theme.tokens.radius_sm)
220                .text_size(px(14.0))
221                .when(is_selected, |this: Div| this.bg(theme.tokens.accent))
222                .when(!is_selected && !disabled, |this: Div| {
223                    this.hover(|style| style.bg(theme.tokens.accent.opacity(0.1)))
224                })
225                .when(has_children, |this: Div| {
226                    let item_id = item.id.clone();
227                    let on_toggle = on_toggle.clone();
228                    let is_expanded_copy = is_expanded;
229
230                    this.child(
231                        div()
232                            .flex()
233                            .items_center()
234                            .justify_center()
235                            .w(px(20.0))
236                            .h(px(20.0))
237                            .rounded(px(4.0))
238                            .cursor(if disabled {
239                                CursorStyle::Arrow
240                            } else {
241                                CursorStyle::PointingHand
242                            })
243                            .when(!disabled && !is_selected, |this: Div| {
244                                this.hover(|style| style.bg(theme.tokens.muted.opacity(0.3)))
245                            })
246                            .when(!disabled && on_toggle.is_some(), |this: Div| {
247                                let on_toggle = on_toggle.unwrap();
248                                this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
249                                    on_toggle(&item_id, !is_expanded_copy, window, cx);
250                                })
251                            })
252                            .child(
253                                Icon::new(if is_expanded {
254                                    "arrow-down"
255                                } else {
256                                    "arrow-right"
257                                })
258                                .size(px(12.0))
259                                .color(if is_selected {
260                                    theme.tokens.accent_foreground
261                                } else {
262                                    theme.tokens.muted_foreground
263                                }),
264                            ),
265                    )
266                })
267                .when(!has_children, |this: Div| this.child(div().w(px(20.0))))
268                .child(
269                    div()
270                        .flex()
271                        .flex_1()
272                        .items_center()
273                        .gap(px(8.0))
274                        .cursor(if disabled {
275                            CursorStyle::Arrow
276                        } else {
277                            CursorStyle::PointingHand
278                        })
279                        .when(!disabled, |this: Div| {
280                            let item_id = item.id.clone();
281                            let on_select = on_select.clone();
282
283                            this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
284                                if let Some(on_select) = on_select.as_ref() {
285                                    on_select(&item_id, window, cx);
286                                }
287                            })
288                        })
289                        .when_some(item.icon.clone(), |this: Div, icon| {
290                            this.child(Icon::new(icon).size(px(16.0)).color(if is_selected {
291                                theme.tokens.accent_foreground
292                            } else if disabled {
293                                theme.tokens.muted_foreground
294                            } else {
295                                theme.tokens.foreground
296                            }))
297                        })
298                        .child(
299                            div()
300                                .flex_1()
301                                .when(disabled, |this: Div| this.opacity(0.5))
302                                .child(
303                                    Text::new(item.label.clone())
304                                        .variant(TextVariant::Body)
305                                        .weight(if is_selected {
306                                            FontWeight::SEMIBOLD
307                                        } else {
308                                            FontWeight::NORMAL
309                                        })
310                                        .color(if is_selected {
311                                            theme.tokens.accent_foreground
312                                        } else if disabled {
313                                            theme.tokens.muted_foreground
314                                        } else {
315                                            theme.tokens.foreground
316                                        }),
317                                ),
318                        ),
319                ),
320        )
321        .when(has_children && is_expanded, |this: Div| {
322            this.child(
323                div()
324                    .flex()
325                    .flex_col()
326                    .gap(px(2.0))
327                    .when(
328                        orientation == NavigationMenuOrientation::Horizontal,
329                        |this: Div| {
330                            this.absolute()
331                                .top_full()
332                                .left_0()
333                                .mt(px(4.0))
334                                .min_w(px(200.0))
335                                .bg(theme.tokens.popover)
336                                .border_1()
337                                .border_color(theme.tokens.border)
338                                .rounded(theme.tokens.radius_md)
339                                .shadow(smallvec::smallvec![BoxShadow {
340                                    color: hsla(0.0, 0.0, 0.0, 0.1),
341                                    offset: point(px(0.0), px(2.0)),
342                                    blur_radius: px(8.0),
343                                    spread_radius: px(0.0),
344                                    inset: false,
345                                }])
346                                .p(px(4.0))
347                        },
348                    )
349                    .when(
350                        orientation == NavigationMenuOrientation::Vertical,
351                        |this: Div| this.mt(px(2.0)),
352                    )
353                    .children(item.children.into_iter().map(|child| {
354                        render_menu_item(
355                            child,
356                            orientation,
357                            theme,
358                            depth + 1,
359                            expanded_set,
360                            selected_id,
361                            on_select,
362                            on_toggle,
363                        )
364                    })),
365            )
366        })
367}
368
369/// Helper function for conditional values
370fn when<T>(condition: bool, true_value: T, false_value: T) -> T {
371    if condition {
372        true_value
373    } else {
374        false_value
375    }
376}