An app sidebar with a header, labelled groups of menu buttons and a footer that collapses to icons.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::separator::Separator;
use crate::ui::sidebar::{Sidebar, SidebarGroup, SidebarMenuButton, SidebarMenuButtonSize, SidebarTrigger};
use crate::icons::{CALENDAR, GALLERY_VERTICAL_END, HOUSE, INBOX, USER};
const PAGES: [(&str, &[u8]); 3] = [("Home", HOUSE), ("Inbox", INBOX), ("Calendar", CALENDAR)];
#[derive(Default)]
pub struct AppShell {
collapsed: bool,
page: usize,
}
impl Render for AppShell {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (border, muted) = (theme.border, theme.muted);
let mut pages = SidebarGroup::new().label("Application");
for (ix, (label, icon)) in PAGES.into_iter().enumerate() {
pages = pages.button(
SidebarMenuButton::new(("page", ix), label)
.icon(icon)
.active(ix == self.page)
.on_click(cx.listener(move |this, _, _, cx| {
this.page = ix;
cx.notify();
})),
);
}
let sidebar = Sidebar::new("app-sidebar", self.collapsed)
.header(
SidebarMenuButton::new("team", "Acme Inc")
.icon(GALLERY_VERTICAL_END)
.description("Enterprise")
.size(SidebarMenuButtonSize::Lg),
)
.group(pages)
.footer(
SidebarMenuButton::new("account", "Ada Lovelace")
.icon(USER)
.description("ada@hyuskui.com")
.size(SidebarMenuButtonSize::Lg),
);
let placeholder = || div().rounded(px(12.0)).bg(muted.opacity(0.5));
let main = div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.child(
div()
.flex()
.items_center()
.gap_2()
.h(px(48.0))
.px_4()
.border_b_1()
.border_color(border)
.child(SidebarTrigger::new("toggle-sidebar").on_click(cx.listener(|this, _, _, cx| {
this.collapsed = !this.collapsed;
cx.notify();
})))
.child(div().h(px(16.0)).child(Separator::vertical()))
.child(div().text_sm().font_weight(FontWeight::MEDIUM).child(PAGES[self.page].0)),
)
.child(
div()
.flex_1()
.flex()
.flex_col()
.gap_4()
.p_4()
.child(div().flex().gap_4().h(px(88.0)).children((0..3).map(|_| placeholder().flex_1())))
.child(placeholder().flex_1()),
);
div()
.flex()
.w(px(672.0))
.h(px(312.0))
.rounded(px(10.0))
.border_1()
.border_color(border)
.overflow_hidden()
.child(sidebar)
.child(main)
}
}Installation
Copies src/ui/sidebar.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/sidebar.rs.src/ui/sidebar.rs use std::{f32::consts::FRAC_PI_2, rc::Rc, sync::Arc}; use gpui::{ canvas, div, point, prelude::*, px, svg, AnimationExt, AnyElement, App, ClickEvent, ElementId, Entity, FontWeight, Hsla, PathBuilder, Pixels, SharedString, SpringAnimation, SpringConfig, Window, }; use crate::theme::ActiveTheme; use crate::ui::popover::Side; use crate::ui::scroll_area::ScrollArea; use crate::ui::tooltip::Tooltip; use crate::icons::PANEL_LEFT; /// shadcn's `--sidebar-width` and `--sidebar-width-icon`. const WIDTH: Pixels = px(256.0); const WIDTH_ICON: Pixels = px(48.0); /// The height of a group label, which slides up by as much as it fades out on collapse. const GROUP_LABEL_HEIGHT: Pixels = px(32.0); /// Stands in for shadcn's `transition-[width] duration-200`: critically damped (damping = /// 2 * sqrt(stiffness)), so the width settles in ~200ms without overshooting, and a toggle /// mid-animation turns around smoothly. const COLLAPSE_SPRING: SpringConfig = SpringConfig::new(625.0, 50.0, 1.0); /// Opening a submenu or a collapsible group, and turning its chevron. const OPEN_SPRING: SpringConfig = SpringConfig::new(400.0, 40.0, 1.0); type ClickHandler = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>; /// How the sidebar sits in the window, as shadcn's `variant` prop. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum SidebarVariant { /// Full height against the window edge, with a border on its inner side. #[default] Sidebar, /// A rounded, bordered panel inset from the window edges. Floating, /// Borderless, on the sidebar color; put the page in a rounded panel beside it (see /// [`SidebarInset`]). Inset, } /// What collapsing does, as shadcn's `collapsible` prop. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum SidebarCollapsible { /// Shrinks to a rail of icons; labels move into tooltips. #[default] Icon, /// Slides fully out of view. Offcanvas, } /// Which edge of the window the sidebar is on. Only changes where its border goes. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub enum SidebarSide { #[default] Left, Right, } #[derive(Clone, Copy, Default, PartialEq)] pub enum SidebarMenuButtonSize { #[default] Default, /// Taller, with the icon on a filled tile: for the app switcher in the header or the /// account row in the footer. Lg, } /// One row of the sidebar: an icon, a label and an optional second line. /// When the sidebar is collapsed only the icon shows, and the label moves into a tooltip. /// /// Rows can carry a submenu (`.item(...)`), shown under them on an indented guide line. With /// `.collapsible(default_open)` the row opens and closes its submenu, with a turning chevron. pub struct SidebarMenuButton { id: ElementId, label: SharedString, description: Option<SharedString>, icon: Option<&'static [u8]>, active: bool, size: SidebarMenuButtonSize, badge: Option<SharedString>, trailing: Option<AnyElement>, items: Vec<SidebarMenuButton>, collapsible: Option<bool>, on_click: Option<ClickHandler>, } impl SidebarMenuButton { pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self { Self { id: id.into(), label: label.into(), description: None, icon: None, active: false, size: SidebarMenuButtonSize::default(), badge: None, trailing: None, items: Vec::new(), collapsible: None, on_click: None, } } /// SVG bytes, drawn at 16px and tinted with the text color. pub fn icon(mut self, svg: &'static [u8]) -> Self { self.icon = Some(svg); self } /// A smaller second line under the label, such as a plan name or an email address. pub fn description(mut self, description: impl Into<SharedString>) -> Self { self.description = Some(description.into()); self } /// Marks the row for the current page. pub fn active(mut self, active: bool) -> Self { self.active = active; self } pub fn size(mut self, size: SidebarMenuButtonSize) -> Self { self.size = size; self } /// A count or short tag at the right end of the row, like shadcn's `SidebarMenuBadge`. pub fn badge(mut self, badge: impl Into<SharedString>) -> Self { self.badge = Some(badge.into()); self } /// Anything at the right end of the row, such as a chevrons-up-down icon on a switcher. pub fn trailing(mut self, element: impl IntoElement) -> Self { self.trailing = Some(element.into_any_element()); self } /// Adds a row to this row's submenu. pub fn item(mut self, item: SidebarMenuButton) -> Self { self.items.push(item); self } /// Lets the row open and close its submenu. `default_open` is how it starts. pub fn collapsible(mut self, default_open: bool) -> Self { self.collapsible = Some(default_open); 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 } fn render(self, collapsed: bool, window: &mut Window, cx: &mut App) -> AnyElement { let theme = cx.theme(); let (accent, accent_fg, fg, muted_fg, primary, primary_fg, border) = ( theme.accent, theme.accent_foreground, theme.foreground, theme.muted_foreground, theme.primary, theme.primary_foreground, theme.border, ); let lg = self.size == SidebarMenuButtonSize::Lg; let text = if self.active { accent_fg } else { fg }; // A collapsible row keeps whether it's open between frames. let open_state = self.collapsible.filter(|_| !self.items.is_empty()).map(|default_open| { window.use_keyed_state( ElementId::NamedChild(Arc::new(self.id.clone()), "open".into()), cx, move |_, _| default_open, ) }); let open = open_state.as_ref().map_or(true, |state| *state.read(cx)); let icon = self.icon.map(|data| { let glyph = svg().data(data).flex_none().size(px(16.0)); if lg { div() .flex() .flex_none() .items_center() .justify_center() .size(px(32.0)) .rounded(px(8.0)) .bg(primary) .child(glyph.text_color(primary_fg)) .into_any_element() } else { glyph.text_color(text).into_any_element() } }); let label = SharedString::clone(&self.label); let id = self.id.clone(); let chevron = open_state.as_ref().map(|_| { div().flex_none().size(px(16.0)).ml_auto().with_spring( ElementId::NamedChild(Arc::new(id.clone()), "chevron".into()), SpringAnimation::new(OPEN_SPRING).to(open), move |this, phase| this.child(chevron_right(text, phase.interpolate_clamped(0.0, FRAC_PI_2))), ) }); let on_click = self.on_click; let toggle = open_state.clone(); let button = div() .id(self.id.clone()) .flex() .flex_none() .items_center() .gap_2() .overflow_hidden() .rounded(px(6.0)) .text_sm() .text_color(text) .cursor_pointer() .map(|this| match (collapsed, lg) { // The icon-only square; a large button's 32px tile already fills it. (true, true) => this.size(px(32.0)), (true, false) => this.size(px(32.0)).justify_center(), (false, true) => this.w_full().h(px(48.0)).p_2(), (false, false) => this.w_full().h(px(32.0)).p_2(), }) .when(self.active, |this| this.bg(accent).font_weight(FontWeight::MEDIUM)) .hover(move |style| style.bg(accent).text_color(accent_fg)) .when(on_click.is_some() || toggle.is_some(), |this| { this.on_click(move |event, window, cx| { if let Some(state) = &toggle { state.update(cx, |open, cx| { *open = !*open; cx.notify(); }); } if let Some(handler) = &on_click { handler(event, window, cx); } }) }) .children(icon) .when(!collapsed, |this| { this.child( div() .flex() .flex_col() .flex_1() .min_w_0() .child( div() .truncate() .when(lg, |this| this.font_weight(FontWeight::SEMIBOLD)) .child(self.label), ) .when_some(self.description, |this, description| { this.child(div().truncate().text_xs().text_color(muted_fg).child(description)) }), ) .when_some(self.badge, |this, badge| { this.child(div().flex_none().text_xs().font_weight(FontWeight::MEDIUM).text_color(text).child(badge)) }) .when_some(self.trailing, |this, trailing| this.child(div().flex_none().ml_auto().child(trailing))) .children(chevron) }); let button = if collapsed { Tooltip::new(self.id.clone(), label).side(Side::Right).trigger(button).into_any_element() } else { button.into_any_element() }; // A submenu never shows on the icon rail; the row's tooltip names it instead. if self.items.is_empty() || collapsed { return button; } let items: Vec<AnyElement> = self.items.into_iter().map(|item| item.render_sub(window, cx)).collect(); // shadcn's SidebarMenuSub: indented under the parent's icon, on a guide line. let sub = div() .flex() .flex_col() .gap_1() .mx(px(14.0)) .px(px(10.0)) .py(px(2.0)) .border_l_1() .border_color(border) .children(items); let panel = match open_state { Some(_) => expand(ElementId::NamedChild(Arc::new(self.id), "panel".into()), open, sub, window, cx), None => sub.into_any_element(), }; div().flex().flex_col().gap_1().child(button).child(panel).into_any_element() } /// A submenu row: label only, a little shorter than a top-level row. fn render_sub(self, _window: &mut Window, cx: &mut App) -> AnyElement { let theme = cx.theme(); let (accent, accent_fg, fg) = (theme.accent, theme.accent_foreground, theme.foreground); let on_click = self.on_click; div() .id(self.id) .flex() .flex_none() .items_center() .gap_2() .h(px(28.0)) .px_2() .rounded(px(6.0)) .text_sm() .text_color(if self.active { accent_fg } else { fg }) .cursor_pointer() .when(self.active, |this| this.bg(accent).font_weight(FontWeight::MEDIUM)) .hover(move |style| style.bg(accent).text_color(accent_fg)) .when_some(on_click, |this, handler| this.on_click(move |event, window, cx| handler(event, window, cx))) .when_some(self.icon, |this, icon| this.child(svg().data(icon).flex_none().size(px(16.0)).text_color(fg))) .child(div().flex_1().min_w_0().truncate().child(self.label)) .when_some(self.badge, |this, badge| this.child(div().flex_none().text_xs().child(badge))) .into_any_element() } } /// A labelled list of menu buttons, optionally with free-form content under them. pub struct SidebarGroup { label: Option<SharedString>, buttons: Vec<SidebarMenuButton>, children: Vec<AnyElement>, collapsible: Option<bool>, } impl SidebarGroup { pub fn new() -> Self { Self { label: None, buttons: Vec::new(), children: Vec::new(), collapsible: None } } /// A small heading, hidden while the sidebar is collapsed. pub fn label(mut self, label: impl Into<SharedString>) -> Self { self.label = Some(label.into()); self } pub fn button(mut self, button: SidebarMenuButton) -> Self { self.buttons.push(button); self } /// Anything else in the group: a calendar, a file tree, a search field. pub fn child(mut self, element: impl IntoElement) -> Self { self.children.push(element.into_any_element()); self } /// Makes the label a toggle that opens and closes the group. Needs a label. pub fn collapsible(mut self, default_open: bool) -> Self { self.collapsible = Some(default_open); self } } impl Default for SidebarGroup { fn default() -> Self { Self::new() } } /// shadcn's app sidebar: a header, scrolling groups of menu buttons, and a footer. The parent /// view owns `collapsed` and which button is active; collapsing shrinks the sidebar to its icons. /// The parts are typed rather than free-form children so the sidebar can hand `collapsed` down; /// `header_child` and `footer_child` take anything for switchers, search fields and cards. #[derive(IntoElement)] pub struct Sidebar { id: ElementId, collapsed: bool, variant: SidebarVariant, side: SidebarSide, collapsible: SidebarCollapsible, header: Vec<SidebarMenuButton>, header_children: Vec<AnyElement>, groups: Vec<SidebarGroup>, footer: Vec<SidebarMenuButton>, footer_children: Vec<AnyElement>, } impl Sidebar { pub fn new(id: impl Into<ElementId>, collapsed: bool) -> Self { Self { id: id.into(), collapsed, variant: SidebarVariant::default(), side: SidebarSide::default(), collapsible: SidebarCollapsible::default(), header: Vec::new(), header_children: Vec::new(), groups: Vec::new(), footer: Vec::new(), footer_children: Vec::new(), } } pub fn variant(mut self, variant: SidebarVariant) -> Self { self.variant = variant; self } pub fn side(mut self, side: SidebarSide) -> Self { self.side = side; self } /// What `collapsed` does: shrink to icons (the default) or slide out of view. pub fn collapsible(mut self, collapsible: SidebarCollapsible) -> Self { self.collapsible = collapsible; self } /// A button pinned above the groups, usually the app or team switcher. pub fn header(mut self, button: SidebarMenuButton) -> Self { self.header.push(button); self } /// Anything pinned above the groups, after the header buttons, such as a search field. pub fn header_child(mut self, element: impl IntoElement) -> Self { self.header_children.push(element.into_any_element()); self } pub fn group(mut self, group: SidebarGroup) -> Self { self.groups.push(group); self } /// A button pinned below the groups, usually the signed-in account. pub fn footer(mut self, button: SidebarMenuButton) -> Self { self.footer.push(button); self } /// Anything pinned below the groups, after the footer buttons, such as the account menu. pub fn footer_child(mut self, element: impl IntoElement) -> Self { self.footer_children.push(element.into_any_element()); self } } impl RenderOnce for Sidebar { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { // Off canvas, the sidebar keeps its full layout while it slides away; only the icon // rail redraws its rows as icons. let offcanvas = self.collapsible == SidebarCollapsible::Offcanvas; let hidden = self.collapsed; let collapsed = self.collapsed && !offcanvas; let sidebar_id = self.id.clone(); let child_id = |name: String| ElementId::NamedChild(Arc::new(sidebar_id.clone()), name.into()); let theme = cx.theme(); // shadcn's `--sidebar` sits a step off the page background; half of `muted` lands there // in both themes without a dedicated token. let (bg, border, muted_fg, fg) = (theme.muted.opacity(0.5), theme.border, theme.muted_foreground, theme.foreground); let stack = |buttons: Vec<SidebarMenuButton>, window: &mut Window, cx: &mut App| { let rows: Vec<AnyElement> = buttons.into_iter().map(|button| button.render(collapsed, window, cx)).collect(); div().flex().flex_col().gap_1().children(rows) }; let header = (!self.header.is_empty() || !self.header_children.is_empty()).then(|| { div() .flex() .flex_col() .gap_2() .p_2() .child(stack(self.header, window, cx)) .children(self.header_children) }); let footer = (!self.footer.is_empty() || !self.footer_children.is_empty()).then(|| { div() .flex() .flex_col() .gap_2() .p_2() .child(stack(self.footer, window, cx)) .children(self.footer_children) }); let mut groups: Vec<AnyElement> = Vec::new(); for (ix, group) in self.groups.into_iter().enumerate() { let open_state = group.collapsible.filter(|_| group.label.is_some()).map(|default_open| { window.use_keyed_state(child_id(format!("group-open-{ix}")), cx, move |_, _| default_open) }); let open = open_state.as_ref().map_or(true, |state| *state.read(cx)); let body = div() .flex() .flex_col() .gap_1() .child(stack(group.buttons, window, cx)) .children(group.children); let body = match &open_state { Some(_) if !collapsed => expand(child_id(format!("group-panel-{ix}")), open, body, window, cx), _ => body.into_any_element(), }; groups.push( div() .flex() .flex_col() .p_2() .when_some(group.label, |this, label| { // Like shadcn's `transition-[margin,opacity]`, the label slides up under // the group above and fades out, rather than disappearing at once. this.child( group_label(label, muted_fg, fg, open_state, open, child_id(format!("group-chevron-{ix}"))) .with_spring( child_id(format!("group-label-{ix}")), SpringAnimation::new(COLLAPSE_SPRING).to(collapsed), |this, phase| { let phase = phase.interpolate_clamped(0.0, 1.0); this.mt(-GROUP_LABEL_HEIGHT * phase).opacity(1.0 - phase) }, ), ) }) .child(body) .into_any_element(), ); } let floating = self.variant == SidebarVariant::Floating; let panel = div() .flex() .flex_col() .h_full() // Off canvas the panel keeps its width while the outer box shrinks around it. .when(offcanvas, |this| this.w(WIDTH - if floating { px(16.0) } else { px(0.0) }).flex_none()) .when(!offcanvas, |this| this.w_full()) .overflow_hidden() .bg(bg) .when(floating, |this| this.rounded(px(8.0)).border_1().border_color(border).shadow_sm()) .children(header) .child( ScrollArea::new(child_id("content".into())) .flex_1() .min_h_0() .child(div().flex().flex_col().children(groups)), ) .children(footer); let width_id = child_id("width".into()); div() .id(self.id.clone()) .flex() .flex_col() .flex_none() .h_full() // Clips the expanded layout while the width is still catching up to it. .overflow_hidden() .map(|this| match (self.variant, self.side) { (SidebarVariant::Sidebar, SidebarSide::Left) => this.border_r_1().border_color(border), (SidebarVariant::Sidebar, SidebarSide::Right) => this.border_l_1().border_color(border), (SidebarVariant::Floating, _) => this.p_2(), (SidebarVariant::Inset, _) => this, }) .child(panel) // A freshly mounted spring starts at its target, so the sidebar doesn't animate in. .with_spring( width_id, SpringAnimation::new(COLLAPSE_SPRING).to(hidden), move |this, phase| { // A floating sidebar's padding sits outside the panel's own width. let pad = if floating { px(16.0) } else { px(0.0) }; let shut = if offcanvas { px(0.0) } else { WIDTH_ICON + pad }; this.w(phase.interpolate_clamped(WIDTH, shut)) .when(offcanvas, |this| this.border_color(border.opacity(1.0 - phase.interpolate_clamped(0.0, 1.0)))) }, ) } } /// A group heading; a collapsible group's heading toggles it and shows a turning chevron. fn group_label( label: SharedString, color: Hsla, hover_color: Hsla, open_state: Option<Entity<bool>>, open: bool, chevron_id: ElementId, ) -> gpui::Stateful<gpui::Div> { let toggle = open_state.is_some(); div() .id(chevron_id.clone()) .flex() .flex_none() .items_center() .h(GROUP_LABEL_HEIGHT) .px_2() .rounded(px(6.0)) .text_xs() .font_weight(FontWeight::MEDIUM) .text_color(color) .whitespace_nowrap() .child(div().flex_1().child(label)) .when_some(open_state, |this, state| { this.cursor_pointer() .hover(move |style| style.text_color(hover_color)) .on_click(move |_, _, cx| { state.update(cx, |open, cx| { *open = !*open; cx.notify(); }) }) }) .when(toggle, |this| { this.child(div().flex_none().size(px(16.0)).with_spring( ElementId::NamedChild(Arc::new(chevron_id), "turn".into()), SpringAnimation::new(OPEN_SPRING).to(open), move |this, phase| this.child(chevron_right(color, phase.interpolate_clamped(0.0, FRAC_PI_2))), )) }) } /// Grows `content` open or shut on a spring, measuring its natural height the first time it /// lays out. Unmeasured, an open panel shows at its natural height and a shut one hides. fn expand(id: ElementId, open: bool, content: impl IntoElement, window: &mut Window, cx: &mut App) -> AnyElement { let height = window.use_keyed_state(ElementId::NamedChild(Arc::new(id.clone()), "height".into()), cx, |_, _| None::<Pixels>); let measured = *height.read(cx); div() .flex() .flex_col() .overflow_hidden() .on_children_prepainted(move |bounds, _, cx| { let natural = bounds.first().map(|b| b.size.height); height.update(cx, |height, cx| { if *height != natural { *height = natural; cx.notify(); } }); }) .child(div().flex_none().child(content)) .with_spring(id, SpringAnimation::new(OPEN_SPRING).to(open), move |this, phase| match measured { Some(full) => this.h(phase.interpolate_clamped(px(0.0), full)).opacity(phase.interpolate_clamped(0.0, 1.0)), None if open => this, None => this.h(px(0.0)), }) .into_any_element() } /// Lucide's `chevron-right`, turned by `angle` (a quarter turn points it down). fn chevron_right(color: Hsla, angle: f32) -> impl IntoElement { canvas( |_, _, _| {}, move |bounds, _, window, _| { let center = bounds.center(); let unit = bounds.size.width / 24.0; let (sin, cos) = angle.sin_cos(); let at = |x: f32, y: f32| { // Lucide paths live on a 24x24 grid centered on (12, 12). let (dx, dy) = (x - 12.0, y - 12.0); point(center.x + unit * (dx * cos - dy * sin), center.y + unit * (dx * sin + dy * cos)) }; let mut path = PathBuilder::stroke(unit * 2.0); path.move_to(at(9.0, 6.0)); path.line_to(at(15.0, 12.0)); path.line_to(at(9.0, 18.0)); if let Ok(path) = path.build() { window.paint_path(path, color); } }, ) .size_full() } /// The page beside an inset sidebar: a rounded panel on the page background, set off from the /// sidebar color around it, like shadcn's `SidebarInset`. #[derive(IntoElement)] pub struct SidebarInset { children: Vec<AnyElement>, } impl SidebarInset { pub fn new() -> Self { Self { children: Vec::new() } } } impl Default for SidebarInset { fn default() -> Self { Self::new() } } impl ParentElement for SidebarInset { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for SidebarInset { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); div() .flex_1() .min_w_0() .flex() .flex_col() .m_2() .ml_0() .overflow_hidden() .rounded(px(12.0)) .bg(theme.background) .shadow_sm() .children(self.children) } } /// The button that collapses and expands the sidebar, usually placed in the page header. #[derive(IntoElement)] pub struct SidebarTrigger { id: ElementId, on_click: Option<ClickHandler>, } impl SidebarTrigger { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), on_click: None } } 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 SidebarTrigger { fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { let theme = cx.theme(); let (accent, fg) = (theme.accent, theme.foreground); div() .id(self.id) .flex() .flex_none() .items_center() .justify_center() .size(px(28.0)) .rounded(px(6.0)) .cursor_pointer() .hover(move |style| style.bg(accent)) .when_some(self.on_click, |this, handler| { this.on_click(move |event, window, cx| handler(event, window, cx)) }) .child(svg().data(PANEL_LEFT).size(px(16.0)).text_color(fg)) } }Register the module
// src/ui/mod.rs pub mod sidebar;
Usage
use crate::ui::sidebar::*;API Reference
SidebarVariant
How the sidebar sits in the window, as shadcn's variant prop.
SidebarVariant::SidebarFull height against the window edge, with a border on its inner side.
SidebarVariant::FloatingA rounded, bordered panel inset from the window edges.
SidebarVariant::InsetBorderless, on the sidebar color; put the page in a rounded panel beside it (see [SidebarInset]).
SidebarCollapsible
What collapsing does, as shadcn's collapsible prop.
SidebarCollapsible::IconShrinks to a rail of icons; labels move into tooltips.
SidebarCollapsible::OffcanvasSlides fully out of view.
SidebarSide
Which edge of the window the sidebar is on. Only changes where its border goes.
SidebarSide::LeftSidebarSide::RightSidebarMenuButtonSize
SidebarMenuButtonSize::DefaultSidebarMenuButtonSize::LgTaller, with the icon on a filled tile: for the app switcher in the header or the account row in the footer.
SidebarMenuButton
One row of the sidebar: an icon, a label and an optional second line. When the sidebar is collapsed only the icon shows, and the label moves into a tooltip. Rows can carry a submenu (.item(...)), shown under them on an indented guide line. With .collapsible(default_open) the row opens and closes its submenu, with a turning chevron.
SidebarMenuButton::new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self.icon(svg: &'static [u8])SVG bytes, drawn at 16px and tinted with the text color.
.description(description: impl Into<SharedString>)A smaller second line under the label, such as a plan name or an email address.
.active(active: bool)Marks the row for the current page.
.size(size: SidebarMenuButtonSize).badge(badge: impl Into<SharedString>)A count or short tag at the right end of the row, like shadcn's SidebarMenuBadge.
.trailing(element: impl IntoElement)Anything at the right end of the row, such as a chevrons-up-down icon on a switcher.
.item(item: SidebarMenuButton)Adds a row to this row's submenu.
.collapsible(default_open: bool)Lets the row open and close its submenu. default_open is how it starts.
.on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)SidebarGroup
A labelled list of menu buttons, optionally with free-form content under them.
SidebarGroup::new() -> Self.label(label: impl Into<SharedString>)A small heading, hidden while the sidebar is collapsed.
.button(button: SidebarMenuButton).child(element: impl IntoElement)Anything else in the group: a calendar, a file tree, a search field.
.collapsible(default_open: bool)Makes the label a toggle that opens and closes the group. Needs a label.
Sidebar
shadcn's app sidebar: a header, scrolling groups of menu buttons, and a footer. The parent view owns collapsed and which button is active; collapsing shrinks the sidebar to its icons. The parts are typed rather than free-form children so the sidebar can hand collapsed down; header_child and footer_child take anything for switchers, search fields and cards.
Sidebar::new(id: impl Into<ElementId>, collapsed: bool) -> Self.variant(variant: SidebarVariant).side(side: SidebarSide).collapsible(collapsible: SidebarCollapsible)What collapsed does: shrink to icons (the default) or slide out of view.
.header(button: SidebarMenuButton)A button pinned above the groups, usually the app or team switcher.
.header_child(element: impl IntoElement)Anything pinned above the groups, after the header buttons, such as a search field.
.group(group: SidebarGroup).footer(button: SidebarMenuButton)A button pinned below the groups, usually the signed-in account.
.footer_child(element: impl IntoElement)Anything pinned below the groups, after the footer buttons, such as the account menu.
SidebarInset
The page beside an inset sidebar: a rounded panel on the page background, set off from the sidebar color around it, like shadcn's SidebarInset.
SidebarInset::new() -> SelfSidebarTrigger
The button that collapses and expands the sidebar, usually placed in the page header.
SidebarTrigger::new(id: impl Into<ElementId>) -> Self.on_click(handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static)