use super::button::{Button, ButtonSize, ButtonVariant};
use super::overlay::{self, Callback, OpenChange, rem};
use crate::{
icons::{CarbonIcon, Icon, IconSize},
motion::{self, Curve, Motion, Speed},
theme::color,
tokens::{ColorRole, TypeStyle},
typography::TypeStyled as _,
};
use gpui_kit::{
AnyElement, App, CursorStyle, ElementId, FontWeight, Hsla, InteractiveElement, IntoElement,
ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, Styled, Window, div,
prelude::FluentBuilder as _, px,
};
use std::rc::Rc;
pub const ITEM_MOTION: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast02);
pub const SLIDE_MOTION: Motion = Motion::new(Curve::ProductiveExit, Speed::Fast02).spatial(true);
pub const WIDTH: f32 = 256.;
pub const COLLAPSED_OFFSET: f32 = WIDTH;
#[derive(Clone)]
pub struct SideNavItem {
label: SharedString,
icon: Option<Icon>,
active: bool,
expanded: bool,
divider: bool,
items: Vec<SideNavItem>,
on_click: Option<Callback>,
}
impl SideNavItem {
pub fn link(label: impl Into<SharedString>) -> Self {
Self {
label: label.into(),
icon: None,
active: false,
expanded: false,
divider: false,
items: Vec::new(),
on_click: None,
}
}
pub fn menu(
label: impl Into<SharedString>,
items: impl IntoIterator<Item = SideNavItem>,
) -> Self {
Self {
items: items.into_iter().collect(),
..Self::link(label)
}
}
pub fn divider() -> Self {
Self {
divider: true,
..Self::link("")
}
}
pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn active(mut self, active: bool) -> Self {
self.active = active;
self
}
pub fn expanded(mut self, expanded: bool) -> Self {
self.expanded = expanded;
self
}
pub fn on_click(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_click = Some(Rc::new(f));
self
}
}
pub fn item_colors(current: bool, hovered: bool) -> (Hsla, Hsla, Hsla) {
use ColorRole::*;
if current {
let bg = if hovered {
BackgroundSelectedHover
} else {
BackgroundSelected
};
(color(bg), color(TextPrimary), color(IconPrimary))
} else if hovered {
(
color(BackgroundHover),
color(TextPrimary),
color(IconPrimary),
)
} else {
(
Hsla::transparent_black(),
color(TextSecondary),
color(IconSecondary),
)
}
}
pub fn nav_background() -> Hsla {
color(ColorRole::Background)
}
#[derive(IntoElement)]
pub struct Sidebar {
id: ElementId,
items: Vec<SideNavItem>,
label: SharedString,
expanded: bool,
header: Option<AnyElement>,
footer: Option<AnyElement>,
visible: bool,
}
impl Sidebar {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: Vec::new(),
label: SharedString::default(),
expanded: true,
header: None,
footer: None,
visible: true,
}
}
pub fn item(mut self, item: SideNavItem) -> Self {
self.items.push(item);
self
}
pub fn items(mut self, items: impl IntoIterator<Item = SideNavItem>) -> Self {
self.items.extend(items);
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = label.into();
self
}
pub fn expanded(mut self, expanded: bool) -> Self {
self.expanded = expanded;
self
}
pub fn header(mut self, header: impl IntoElement) -> Self {
self.header = Some(header.into_any_element());
self
}
pub fn footer(mut self, footer: impl IntoElement) -> Self {
self.footer = Some(footer.into_any_element());
self
}
fn visible(mut self, visible: bool) -> Self {
self.visible = visible;
self
}
}
#[allow(clippy::too_many_arguments)]
fn row(
id: ElementId,
label: SharedString,
icon: Option<Icon>,
current: bool,
heading: bool,
indent: f32,
trailing: Option<AnyElement>,
on_click: Callback,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let hover = window.use_keyed_state((id.clone(), "hover"), cx, |_, _| false);
let focus = window
.use_keyed_state((id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
.read(cx)
.clone();
let focused = focus.is_focused(window);
let (bg, text, icon_color) = item_colors(current, *hover.read(cx));
let bg = motion::animate_color((id.clone(), "bg"), bg, ITEM_MOTION, window, cx);
let text = motion::animate_color((id.clone(), "text"), text, ITEM_MOTION, window, cx);
gpui_kit::base::Button::new(id)
.track_focus(&focus)
.accessibility_label(label.clone())
.relative()
.w_full()
.h(rem(32.))
.flex_shrink_0()
.flex()
.flex_row()
.items_center()
.justify_start()
.pl(rem(16. + indent))
.pr(rem(16.))
.bg(bg)
.text_color(text)
.map(|this| {
if heading || current || indent == 0. {
this.type_style(TypeStyle::HeadingCompact01)
} else {
this.type_style(TypeStyle::BodyCompact01)
.font_weight(FontWeight::NORMAL)
}
})
.cursor(CursorStyle::PointingHand)
.on_hover(move |h, _, cx| {
hover.update(cx, |v, cx| {
*v = *h;
cx.notify();
})
})
.on_click(move |_, window, cx| on_click(window, cx))
.when_some(icon, |this, icon| {
this.child(
div()
.flex_shrink_0()
.mr(rem(24.))
.child(icon.size(IconSize::S16).color(icon_color)),
)
})
.child(
div()
.flex_1()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.children(trailing)
.when(current, |this| {
this.child(
div()
.absolute()
.top_0()
.bottom_0()
.left_0()
.w(px(3.))
.bg(color(ColorRole::BorderInteractive)),
)
})
.when(focused, |this| {
this.child(
div()
.absolute()
.top_0()
.left_0()
.size_full()
.border_2()
.border_color(color(ColorRole::Focus)),
)
})
.into_any_element()
}
impl RenderOnce for Sidebar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let target = if self.expanded { 0. } else { COLLAPSED_OFFSET };
let offset = motion::animate((id.clone(), "slide"), target, SLIDE_MOTION, window, cx);
let slot = div()
.id(id.clone())
.flex_shrink_0()
.h_full()
.min_h(rem(320.));
if !self.visible {
return slot.into_any_element();
}
let slot = slot.relative().w(rem(WIDTH)).overflow_hidden();
if offset >= COLLAPSED_OFFSET {
return slot.into_any_element();
}
let mut list = div()
.id((id.clone(), "items"))
.flex_1()
.min_h_0()
.overflow_y_scroll()
.pt(rem(16.))
.flex()
.flex_col();
for (index, item) in self.items.into_iter().enumerate() {
let item_id = ElementId::NamedChild(
std::sync::Arc::new(id.clone()),
SharedString::from(format!("item-{index}")),
);
if item.divider {
list = list.child(
div()
.flex_shrink_0()
.my(rem(8.))
.mx(rem(16.))
.h(px(1.))
.bg(color(ColorRole::BorderSubtle01)),
);
continue;
}
if item.items.is_empty() {
let on_click = item.on_click.clone();
list = list.child(row(
item_id,
item.label,
item.icon,
item.active,
false,
0.,
None,
Rc::new(move |window, cx| {
if let Some(f) = &on_click {
f(window, cx)
}
}),
window,
cx,
));
continue;
}
let default = item.expanded;
let openness = overlay::openness(&item_id, None, default, None, window, cx);
let open = openness.open;
let set_open = openness.setter();
let rotation = motion::chevron_rotation((item_id.clone(), "chevron"), open, window, cx);
let child_active = item.items.iter().any(|i| i.active);
let has_icon = item.icon.is_some();
let chevron = Some(
div()
.flex_1()
.flex()
.justify_end()
.child(
Icon::carbon(CarbonIcon::ChevronDown)
.size(IconSize::S16)
.color(color(ColorRole::IconSecondary))
.rotate(gpui_kit::radians(rotation)),
)
.into_any_element(),
);
list = list.child(row(
(item_id.clone(), "heading").into(),
item.label.clone(),
item.icon.clone(),
(item.active || child_active) && !open,
true,
0.,
chevron,
Rc::new(move |window, cx| set_open(!open, window, cx)),
window,
cx,
));
if open {
let mut links = div().flex().flex_col();
for (i, link) in item.items.into_iter().enumerate() {
let on_click = link.on_click.clone();
links = links.child(row(
ElementId::NamedChild(
std::sync::Arc::new(item_id.clone()),
SharedString::from(format!("link-{i}")),
),
link.label,
None,
link.active,
false,
if has_icon { 56. } else { 16. },
None,
Rc::new(move |window, cx| {
if let Some(f) = &on_click {
f(window, cx)
}
}),
window,
cx,
));
}
list = list.child(links);
}
}
slot.child(
div()
.absolute()
.top_0()
.left(rem(-offset))
.w(rem(WIDTH))
.h_full()
.bg(nav_background())
.child(
div()
.size_full()
.flex()
.flex_col()
.when_some(self.header, |this, header| {
this.child(
div()
.flex_shrink_0()
.p(rem(16.))
.type_style(TypeStyle::HeadingCompact01)
.text_color(color(ColorRole::TextPrimary))
.border_b_1()
.border_color(color(ColorRole::BorderSubtle01))
.child(header),
)
})
.child(list)
.when_some(self.footer, |this, footer| {
this.child(
div()
.flex_shrink_0()
.p(rem(16.))
.border_t_1()
.border_color(color(ColorRole::BorderSubtle01))
.child(footer),
)
}),
),
)
.into_any_element()
}
}
#[derive(IntoElement)]
pub struct SidebarProvider {
id: ElementId,
sidebar: Option<Sidebar>,
open: Option<bool>,
default_open: bool,
on_open_change: Option<OpenChange>,
children: Vec<AnyElement>,
open_label: SharedString,
close_label: SharedString,
show_trigger: bool,
}
impl SidebarProvider {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
sidebar: None,
open: None,
default_open: true,
on_open_change: None,
children: Vec::new(),
open_label: "Open menu".into(),
close_label: "Close menu".into(),
show_trigger: true,
}
}
pub fn sidebar(mut self, sidebar: Sidebar) -> Self {
self.sidebar = Some(sidebar);
self
}
pub fn open(mut self, open: bool) -> Self {
self.open = Some(open);
self
}
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
}
pub fn on_open_change(mut self, f: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
self.on_open_change = Some(Rc::new(f));
self
}
pub fn show_trigger(mut self, show: bool) -> Self {
self.show_trigger = show;
self
}
pub fn trigger_labels(
mut self,
open: impl Into<SharedString>,
close: impl Into<SharedString>,
) -> Self {
self.open_label = open.into();
self.close_label = close.into();
self
}
}
impl ParentElement for SidebarProvider {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
pub struct SidebarTrigger;
impl SidebarTrigger {
pub fn button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Button {
Button::new(id, label)
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Md)
.icon(CarbonIcon::Menu)
.icon_only(true)
}
}
impl RenderOnce for SidebarProvider {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id.clone();
let openness = overlay::openness(
&id,
self.open,
self.default_open,
self.on_open_change.clone(),
window,
cx,
);
let open = openness.open;
let set_open = openness.setter();
let trigger = SidebarTrigger::button(
(id.clone(), "trigger"),
if open {
self.close_label.clone()
} else {
self.open_label.clone()
},
)
.on_click(move |_, window, cx| set_open(!open, window, cx));
div()
.flex()
.flex_row()
.size_full()
.children(self.sidebar.map(|s| s.visible(open)))
.child(
div()
.flex_1()
.min_w_0()
.p(rem(16.))
.flex()
.flex_col()
.items_start()
.when(self.show_trigger, |this| this.child(trigger))
.children(self.children),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tokens::CarbonTheme;
fn hex(c: Hsla) -> String {
let c = c.to_rgb();
let b = |v: f32| (v * 255.).round() as u8;
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
}
#[test]
fn colors_follow_side_nav_css() {
crate::theme::tests_set(CarbonTheme::White);
let (bg, text, icon) = item_colors(false, false);
assert_eq!(
(bg.a, hex(text), hex(icon)),
(0., "#525252".into(), "#525252".into())
);
let (_, text, _) = item_colors(false, true);
assert_eq!(hex(text), "#161616");
let (bg, text, _) = item_colors(true, false);
assert_eq!(bg, color(ColorRole::BackgroundSelected));
assert_eq!(hex(text), "#161616");
}
#[test]
fn nav_panel_is_background_without_border() {
crate::theme::tests_set(CarbonTheme::White);
assert_eq!(hex(nav_background()), "#ffffff");
let src = include_str!("sidebar.rs");
let panel = src.split("slot.child(").nth(1).unwrap();
let panel = panel.split(".when_some(self.header").next().unwrap();
assert!(!panel.contains("border_r"));
}
#[test]
fn widths_and_motion() {
assert_eq!((WIDTH, COLLAPSED_OFFSET), (256., 256.));
assert_eq!(SLIDE_MOTION.speed.millis(), 110);
assert_eq!(SLIDE_MOTION.curve.points(), (0.2, 0., 1., 0.9));
}
}