Site navigation links whose triggers open content panels on hover or click.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::navigation_menu::{NavigationMenu, NavigationMenuItem, NavigationMenuLink};
const COMPONENTS: [(&str, &str); 4] = [
("Alert Dialog", "A modal that interrupts the user with important content."),
("Hover Card", "Preview the content behind a link when the pointer rests on it."),
("Progress", "Shows how far a task has completed, like a progress bar."),
("Tabs", "Layered sections of content shown one panel at a time."),
];
#[derive(Default)]
pub struct SiteNav {
open: Option<usize>,
}
impl Render for SiteNav {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (muted, muted_fg) = (theme.muted, theme.muted_foreground);
let getting_started = div()
.flex()
.gap_2()
.child(
div()
.w(px(150.0))
.flex_none()
.flex()
.flex_col()
.justify_end()
.gap_2()
.p_4()
.rounded(px(6.0))
.bg(muted)
.child(div().text_lg().font_weight(FontWeight::MEDIUM).child("hyuskui"))
.child(div().text_color(muted_fg).child("Components for GPUI that you copy and own.")),
)
.child(
div()
.flex_1()
.flex()
.flex_col()
.child(NavigationMenuLink::new("intro", "Introduction").description("Why copy-and-own components."))
.child(NavigationMenuLink::new("install", "Installation").description("Add the theme and a first component."))
.child(NavigationMenuLink::new("typography", "Typography").description("Headings, paragraphs and lists.")),
);
let components = div().flex().flex_wrap().children(COMPONENTS.iter().enumerate().map(|(ix, (title, description))| {
div()
.w_1_2()
.child(NavigationMenuLink::new(("component", ix), *title).description(*description))
}));
// Top-aligned so the panels have room to open downward in the preview.
div().h(px(300.0)).flex().items_start().child(
NavigationMenu::new("site-nav", self.open)
.on_open_change(cx.listener(|this, open: &Option<usize>, _, cx| {
this.open = *open;
cx.notify();
}))
.item(NavigationMenuItem::new("Getting started").width(px(440.0)).content(getting_started))
.item(NavigationMenuItem::new("Components").width(px(480.0)).content(components))
.item(NavigationMenuItem::new("Docs").on_click(|_, _, _| println!("open docs"))),
)
}
}Installation
Copies src/ui/navigation_menu.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/navigation_menu.rs.src/ui/navigation_menu.rs use std::{f32::consts::PI, rc::Rc, time::Duration}; use gpui::{ anchored, deferred, div, prelude::*, px, radians, svg, AnyElement, App, Bounds, ClickEvent, ElementId, Entity, FocusHandle, FontWeight, Pixels, SharedString, Task, Transformation, Window, }; use crate::theme::ActiveTheme; use crate::ui::popover::{animate_overlay, ease, focus_when_mounted, placement, Align, Presence, Side, Transition}; use crate::icons::CHEVRON_DOWN; /// Radix's defaults: a resting pointer opens a panel, and a short trip off the menu (such as /// crossing the gap between a trigger and its panel) doesn't close it. const OPEN_DELAY: Duration = Duration::from_millis(200); const CLOSE_DELAY: Duration = Duration::from_millis(300); /// shadcn's viewport-less panels: `fade-in-0 zoom-in-95` / `fade-out-0 zoom-out-95`, `duration-200`. const PANEL_TRANSITION: Transition = Transition { enter: Duration::from_millis(200), exit: Duration::from_millis(200), easing: ease, }; type OpenChangeHandler = Rc<dyn Fn(&Option<usize>, &mut Window, &mut App) + 'static>; type ClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; /// A top-level entry: either a trigger that opens a content panel, or a plain link. pub struct NavigationMenuItem { label: SharedString, content: Option<AnyElement>, width: Pixels, on_click: Option<ClickHandler>, } impl NavigationMenuItem { pub fn new(label: impl Into<SharedString>) -> Self { Self { label: label.into(), content: None, width: px(400.0), on_click: None, } } /// The panel shown below the trigger. Without content the item is a plain link. pub fn content(mut self, content: impl IntoElement) -> Self { self.content = Some(content.into_any_element()); self } /// Panel width. pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = width.into(); self } /// Runs when a link item is clicked. Items with content toggle their panel instead. pub fn on_click(mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self { self.on_click = Some(Rc::new(handler)); self } } /// A row of site navigation links whose triggers open content panels on hover or click. /// The parent view owns which panel is open. #[derive(IntoElement)] pub struct NavigationMenu { id: ElementId, open: Option<usize>, items: Vec<NavigationMenuItem>, on_open_change: Option<OpenChangeHandler>, } /// Kept across frames: trigger bounds are only known after layout and the panel attaches to /// them; the hover-intent timer has to be cancellable when the pointer comes back; the focus /// handle has to outlive a frame for Escape to reach the panel. struct NavigationMenuState { trigger_bounds: Vec<Bounds<Pixels>>, focus: FocusHandle, pending: Option<Task<()>>, was_open: Option<usize>, /// The latest open value, including one asked for earlier in the same event. open: Option<usize>, /// Which items have a panel; the others are plain links. has_content: Vec<bool>, /// GPUI reports leaving one trigger and entering the next in either order, so hover is /// recorded first and acted on from the combined state. hovered_trigger: Option<usize>, content_hovered: bool, /// One per item, so a panel being left fades out while the next fades in. presences: Vec<Presence>, } /// Decides what the pointer's position means for the open panel. fn sync(state: &Entity<NavigationMenuState>, emit: &OpenChangeHandler, window: &mut Window, cx: &mut App) { let (open, hovered, content_hovered, has_content) = { let state = state.read(cx); let has_content = state.hovered_trigger.is_some_and(|ix| state.has_content.get(ix) == Some(&true)); (state.open, state.hovered_trigger, state.content_hovered, has_content) }; match hovered { Some(ix) if has_content && open == Some(ix) => cancel(state, cx), // Already browsing: switch panels without waiting. Some(ix) if has_content && open.is_some() => request(state, emit, Some(ix), window, cx), Some(ix) if has_content => schedule(state, emit, Some(ix), OPEN_DELAY, window, cx), _ if content_hovered => cancel(state, cx), // On a plain link or off the menu: close after a grace period. _ if open.is_some() => schedule(state, emit, None, CLOSE_DELAY, window, cx), _ => cancel(state, cx), } } /// Asks for `next` now, dropping any pending change. fn request( state: &Entity<NavigationMenuState>, emit: &OpenChangeHandler, next: Option<usize>, window: &mut Window, cx: &mut App, ) { state.update(cx, |state, _| { state.pending = None; state.open = next; }); emit(&next, window, cx); } /// Asks for `next` after `delay`. Replacing the pending task drops, and so cancels, the last one. fn schedule( state: &Entity<NavigationMenuState>, emit: &OpenChangeHandler, next: Option<usize>, delay: Duration, window: &mut Window, cx: &mut App, ) { let emit = emit.clone(); let task_state = state.clone(); let task = window.spawn(cx, async move |cx| { cx.background_executor().timer(delay).await; cx.update(|window, cx| request(&task_state, &emit, next, window, cx)).ok(); }); state.update(cx, |state, _| state.pending = Some(task)); } fn cancel(state: &Entity<NavigationMenuState>, cx: &mut App) { state.update(cx, |state, _| state.pending = None); } impl NavigationMenu { pub fn new(id: impl Into<ElementId>, open: Option<usize>) -> Self { Self { id: id.into(), open, items: Vec::new(), on_open_change: None, } } pub fn item(mut self, item: NavigationMenuItem) -> Self { self.items.push(item); self } /// Receives the index of the panel to open next, or `None` to close. pub fn on_open_change( mut self, handler: impl Fn(&Option<usize>, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Rc::new(handler)); self } } impl RenderOnce for NavigationMenu { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let open = self.open; let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| NavigationMenuState { trigger_bounds: Vec::new(), focus: cx.focus_handle(), pending: None, was_open: None, open: None, has_content: Vec::new(), hovered_trigger: None, content_hovered: false, presences: Vec::new(), }); let has_content: Vec<bool> = self.items.iter().map(|item| item.content.is_some()).collect(); let item_count = self.items.len(); let (trigger_bounds, focus, just_opened, frames) = state.update(cx, |state, cx| { let just_opened = open.is_some() && state.was_open.is_none(); state.was_open = open; state.open = open; state.has_content = has_content; // A panel that closed under the pointer never reports the pointer leaving it. if open.is_none() { state.content_hovered = false; } state.presences.resize(item_count, Presence::default()); let frames: Vec<_> = state .presences .iter_mut() .enumerate() .map(|(ix, presence)| presence.update(open == Some(ix), PANEL_TRANSITION, window, cx)) .collect(); (state.trigger_bounds.clone(), state.focus.clone(), just_opened, frames) }); if just_opened { focus_when_mounted(focus.clone(), window); } let theme = cx.theme(); let (accent, accent_fg, bg, fg, border, radius) = ( theme.accent, theme.accent_foreground, theme.background, theme.foreground, theme.border, theme.radius, ); let emit = self.on_open_change; let mut panels = Vec::new(); let mut triggers = Vec::with_capacity(self.items.len()); for (ix, item) in self.items.into_iter().enumerate() { let is_open = open == Some(ix); let has_content = item.content.is_some(); let trigger = div() .id(("nav-trigger", ix)) .flex() .items_center() .gap_1() .h(px(36.0)) .px_4() .rounded(px(6.0)) .text_sm() .font_weight(FontWeight::MEDIUM) .cursor_pointer() .when(is_open, |this| this.bg(accent.opacity(0.5))) .hover(move |style| style.bg(accent).text_color(accent_fg)) .child(item.label) .when(has_content, |this| { this.child( svg() .data(CHEVRON_DOWN) .size(px(12.0)) .text_color(fg) .when(is_open, |this| this.with_transformation(Transformation::rotate(radians(PI)))), ) }) .when_some(emit.clone(), |this, emit| { let state = state.clone(); this.on_hover(move |hovered, window, cx| { state.update(cx, |state, _| { if *hovered { state.hovered_trigger = Some(ix); } else if state.hovered_trigger == Some(ix) { state.hovered_trigger = None; } }); sync(&state, &emit, window, cx); }) }) .map(|this| { let emit = emit.clone(); let state = state.clone(); let on_click = item.on_click.clone(); this.on_click(move |event, window, cx| { cancel(&state, cx); if !has_content { if let Some(on_click) = &on_click { on_click(event, window, cx); } } let next = (has_content && !is_open).then_some(ix); if let Some(emit) = emit.as_ref().filter(|_| next != open) { request(&state, emit, next, window, cx); } }) }); triggers.push(trigger); let frame = frames[ix]; if let (true, Some(content), Some(bounds)) = (frame.visible(), item.content, trigger_bounds.get(ix).copied()) { let (anchor, corner, offset) = placement(Side::Bottom, Align::Start); let all_triggers = trigger_bounds.clone(); let hover_state = state.clone(); let hover_emit = emit.clone(); let outside_emit = emit.clone(); let escape_emit = emit.clone(); // Only the open panel takes focus and the pointer; one animating out is inert, or // it would report hover it can never take back once unmounted. let content = div() .id(("nav-content", ix)) .when(is_open, |this| this.occlude().track_focus(&focus)) .w(item.width) .p_2() .rounded(radius) .border_1() .border_color(border) .bg(bg) .text_color(fg) .text_sm() .shadow_md() .when(is_open, |this| { this.on_hover(move |hovered, window, cx| { hover_state.update(cx, |state, _| state.content_hovered = *hovered); if let Some(emit) = &hover_emit { sync(&hover_state, emit, window, cx); } }) // A mousedown on a trigger is left to its click handler, or it would close // here and reopen on mouseup. .on_mouse_down_out(move |event, window, cx| { if !all_triggers.iter().any(|b| b.contains(&event.position)) { if let Some(emit) = &outside_emit { emit(&None, window, cx); } } }) .on_key_down(move |event, window, cx| { if event.keystroke.key == "escape" { if let Some(emit) = &escape_emit { emit(&None, window, cx); } cx.stop_propagation(); } }) }) .child(content); let content = animate_overlay(content, Side::Bottom, frame, px(0.0)); panels.push( deferred( anchored() .attach(bounds, corner) .anchor(anchor) .offset(offset) .snap_to_window_with_margin(px(8.0)) .child(content), ) .with_priority(1), ); } } div() .id(self.id) .flex() .child( div() .flex() .items_center() .gap_1() .on_children_prepainted(move |bounds, _, cx| { state.update(cx, |state, cx| { if state.trigger_bounds != bounds { state.trigger_bounds = bounds; cx.notify(); } }); }) .children(triggers), ) .children(panels) } } /// A link inside a panel: a title with an optional one-line description, like shadcn's `ListItem`. #[derive(IntoElement)] pub struct NavigationMenuLink { id: ElementId, title: SharedString, description: Option<SharedString>, on_click: Option<ClickHandler>, } impl NavigationMenuLink { pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self { Self { id: id.into(), title: title.into(), description: None, on_click: None, } } pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } pub fn on_click(mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static) -> Self { self.on_click = Some(Rc::new(handler)); self } } impl RenderOnce for NavigationMenuLink { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let (accent, accent_fg, muted_fg) = (theme.accent, theme.accent_foreground, theme.muted_foreground); div() .id(self.id) .flex() .flex_col() .gap_1() .p_2() .rounded(px(4.0)) .text_sm() .cursor_pointer() .hover(move |style| style.bg(accent).text_color(accent_fg)) .when_some(self.on_click, |this, handler| { this.on_click(move |event, window, cx| handler(event, window, cx)) }) .child(div().font_weight(FontWeight::MEDIUM).line_height(px(16.0)).child(self.title)) .when_some(self.description, |this, description| { this.child(div().text_color(muted_fg).line_height(px(20.0)).child(description)) }) } }Register the module
// src/ui/mod.rs pub mod navigation_menu;
Usage
use crate::ui::navigation_menu::*;API Reference
NavigationMenuItem
A top-level entry: either a trigger that opens a content panel, or a plain link.
NavigationMenuItem::new(label: impl Into<SharedString>) -> Self.content(content: impl IntoElement)The panel shown below the trigger. Without content the item is a plain link.
.width(width: impl Into<Pixels>)Panel width.
.on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)Runs when a link item is clicked. Items with content toggle their panel instead.
NavigationMenu
A row of site navigation links whose triggers open content panels on hover or click. The parent view owns which panel is open.
NavigationMenu::new(id: impl Into<ElementId>, open: Option<usize>) -> Self.item(item: NavigationMenuItem).on_open_change(handler: impl Fn(&Option<usize>, &mut Window, &mut App) + 'static)Receives the index of the panel to open next, or None to close.
NavigationMenuLink
A link inside a panel: a title with an optional one-line description, like shadcn's ListItem.
NavigationMenuLink::new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self.description(description: impl Into<SharedString>).on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)