use std::{cell::RefCell, collections::HashMap, sync::Arc};
use parking_lot::Mutex;
use super::{
FontFamily,
button::{Button, ButtonVariant},
collapsible::opening,
drawer::Drawer,
icon::Icon,
icons,
kbd::{Kbd, KeyPlatform},
menu::{Menu, MenuItem},
names,
part_style::{Length, PartStyle, PartTransition},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{command_held, fading, glyph, pressable},
theme::{Themed, current_theme},
tooltip::Tooltip,
};
use crate::{
animation::Transition,
app::{
component::Component,
ctx::{Ctx, Placement},
events::{KeyboardEvent, MouseButton, MouseEvent},
theme::{
BorderSize, Breakpoint, IconSize, MotionDuration, MotionEasing, OpacityLevel, PaletteColor, RadiusSize, Theme,
TypographyStyle,
},
},
components::{Column, Row, ScrollVertical},
core::{ElementRef, Signal},
layout::{
Alignment,
layout_kind::{Justify, ScrollState},
scrollbar::ScrollBarStyle,
text_style::FontWeight,
},
node::{
CursorIcon, Element, EventHandler, FocusGroup, IntoMouseEventHandler, border::Border as Edge, color::Color,
dimension::Dimension, outline::Outline,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SidebarPart {
Root,
Header,
Body,
Footer,
FooterContent,
Group,
GroupLabel,
GroupText,
GroupCount,
GroupChevron,
GroupAction,
Item,
ItemIcon,
ItemLabel,
ItemCount,
ItemBadge,
ItemShortcut,
ItemChevron,
ItemIndent,
Nested,
NestedContent,
Heading,
HeadingMark,
HeadingText,
HeadingTitle,
HeadingDescription,
HeadingTrailing,
}
names!(SidebarPart {
Root => "root",
Header => "header",
Body => "body",
Footer => "footer",
FooterContent => "footer-content",
Group => "group",
GroupLabel => "group-label",
GroupText => "group-text",
GroupCount => "group-count",
GroupChevron => "group-chevron",
GroupAction => "group-action",
Item => "item",
ItemIcon => "item-icon",
ItemLabel => "item-label",
ItemCount => "item-count",
ItemBadge => "item-badge",
ItemShortcut => "item-shortcut",
ItemChevron => "item-chevron",
ItemIndent => "item-indent",
Nested => "nested",
NestedContent => "nested-content",
Heading => "heading",
HeadingMark => "heading-mark",
HeadingText => "heading-text",
HeadingTitle => "heading-title",
HeadingDescription => "heading-description",
HeadingTrailing => "heading-trailing",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SidebarState {
Collapsed,
Overlay,
Selected,
Disabled,
Open,
Pressable,
}
names!(SidebarState {
Collapsed => "collapsed",
Overlay => "overlay",
Selected => "selected",
Disabled => "disabled",
Open => "open",
Pressable => "pressable",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum SidebarHeadingVariant {
#[default]
Workspace,
Account,
}
names!(SidebarHeadingVariant {
Workspace => "workspace",
Account => "account",
});
pub type SidebarRenderer = Arc<dyn Fn(SidebarView) -> Element + Send + Sync>;
type Handler = Arc<dyn Fn() + Send + Sync>;
fn window_is_narrow() -> bool {
super::current_breakpoint().is_none_or(|breakpoint| breakpoint < Breakpoint::Md)
}
fn plain(event: &KeyboardEvent) -> bool {
!event.ctrl && !event.alt && !event.meta
}
#[derive(Clone)]
pub struct SidebarItem {
label: Arc<str>,
icon: Option<Name>,
badge: Option<Element>,
count: Option<usize>,
shortcut: Option<Arc<str>>,
selected: bool,
disabled: bool,
default_open: Option<bool>,
on_select: Vec<Handler>,
on_open_aside: Vec<Handler>,
href: Option<Arc<str>>,
children: Vec<SidebarItem>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SidebarItem {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
icon: None,
badge: None,
count: None,
shortcut: None,
selected: false,
disabled: false,
default_open: None,
on_select: Vec::new(),
on_open_aside: Vec::new(),
href: None,
children: Vec::new(),
forced: None,
id: None,
key: None,
}
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = Some(name.into());
self
}
pub fn badge(mut self, badge: impl Into<Element>) -> Self {
self.badge = Some(badge.into());
self
}
pub fn count(mut self, count: usize) -> Self {
self.count = Some(count);
self
}
pub fn shortcut(mut self, keys: &str) -> Self {
self.shortcut = Some(Arc::from(keys));
self
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = Some(open);
self
}
pub fn on_select(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn on_open_aside(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_open_aside.push(Arc::new(handler));
self
}
#[cfg(feature = "router")]
pub fn href(mut self, path: &str) -> Self {
self.href = Some(Arc::from(path));
self
}
pub fn child(mut self, child: SidebarItem) -> Self {
self.children.push(child);
self
}
pub fn children(mut self, children: impl IntoIterator<Item = SidebarItem>) -> Self {
self.children.extend(children);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
fn ident(&self) -> &str {
self.key.as_deref().unwrap_or(&self.label)
}
fn holds_selected(&self) -> bool {
self
.children
.iter()
.any(|child| child.selected || child.holds_selected())
}
}
#[derive(Clone)]
pub struct SidebarGroup {
label: Option<Arc<str>>,
count: Option<usize>,
action: Option<Element>,
collapsible: bool,
default_open: bool,
items: Vec<SidebarItem>,
key: Option<Arc<str>>,
}
impl SidebarGroup {
pub fn new(label: &str) -> Self {
Self {
label: (!label.is_empty()).then(|| Arc::from(label)),
count: None,
action: None,
collapsible: false,
default_open: true,
items: Vec::new(),
key: None,
}
}
pub fn count(mut self, count: usize) -> Self {
self.count = Some(count);
self
}
pub fn action(mut self, action: impl Into<Element>) -> Self {
self.action = Some(action.into());
self
}
pub fn collapsible(mut self, collapsible: bool) -> Self {
self.collapsible = collapsible;
self
}
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
}
pub fn item(mut self, item: SidebarItem) -> Self {
self.items.push(item);
self
}
pub fn items(mut self, items: impl IntoIterator<Item = SidebarItem>) -> Self {
self.items.extend(items);
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
fn ident(&self) -> &str {
self.key.as_deref().or(self.label.as_deref()).unwrap_or("")
}
}
#[derive(Clone)]
pub struct Sidebar {
label: Arc<str>,
header: Option<Element>,
header_collapsed: Option<Element>,
footer: Option<Element>,
footer_collapsed: Option<Element>,
groups: Vec<SidebarGroup>,
collapsed: bool,
open: Option<Signal<bool>>,
narrow: Option<bool>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Default for Sidebar {
fn default() -> Self {
Self::new()
}
}
impl Sidebar {
pub fn new() -> Self {
Self {
label: super::current_locale().navigation.sidebar.clone(),
header: None,
header_collapsed: None,
footer: None,
footer_collapsed: None,
groups: Vec::new(),
collapsed: false,
open: None,
narrow: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn label(mut self, label: &str) -> Self {
self.label = Arc::from(label);
self
}
pub fn header(mut self, header: impl Into<Element>) -> Self {
self.header = Some(header.into());
self
}
pub fn header_collapsed(mut self, header: impl Into<Element>) -> Self {
self.header_collapsed = Some(header.into());
self
}
pub fn footer(mut self, footer: impl Into<Element>) -> Self {
self.footer = Some(footer.into());
self
}
pub fn footer_collapsed(mut self, footer: impl Into<Element>) -> Self {
self.footer_collapsed = Some(footer.into());
self
}
pub fn group(mut self, group: SidebarGroup) -> Self {
self.groups.push(group);
self
}
pub fn groups(mut self, groups: impl IntoIterator<Item = SidebarGroup>) -> Self {
self.groups.extend(groups);
self
}
pub fn item(mut self, item: SidebarItem) -> Self {
match self.groups.last_mut() {
Some(group) if group.label.is_none() && group.key.is_none() => group.items.push(item),
_ => self.groups.push(SidebarGroup::new("").item(item)),
}
self
}
pub fn items(self, items: impl IntoIterator<Item = SidebarItem>) -> Self {
items.into_iter().fold(self, Sidebar::item)
}
pub fn collapsed(mut self, collapsed: bool) -> Self {
self.collapsed = collapsed;
self
}
pub fn open(mut self, open: Signal<bool>) -> Self {
self.open = Some(open);
self
}
pub fn narrow(mut self, narrow: bool) -> Self {
self.narrow = Some(narrow);
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
build_sidebar(&self, theme, &SidebarHost::detached(), None, None)
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
ctx.mount::<SidebarHost>(SidebarProps { sidebar: self })
}
}
#[derive(Clone)]
struct SidebarProps {
sidebar: Sidebar,
}
impl PartialEq for SidebarProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for SidebarProps {}
struct SidebarHost {
opened: Mutex<HashMap<Arc<str>, Signal<bool>>>,
menus: Mutex<HashMap<Arc<str>, (ElementRef, Signal<bool>)>>,
open: Signal<bool>,
revealed: Mutex<Option<Option<Arc<str>>>>,
reveal: ElementRef,
scroll: ScrollState,
}
impl Component for SidebarHost {
type Props = SidebarProps;
fn create(ctx: &mut Ctx) -> Self {
Self {
opened: Mutex::new(HashMap::new()),
menus: Mutex::new(HashMap::new()),
open: ctx.signal(false),
revealed: Mutex::new(None),
reveal: ElementRef::new(),
scroll: ScrollState::new(),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let sidebar = ctx.props::<SidebarProps>().sidebar.clone();
#[cfg(feature = "router")]
let navigator = ctx.navigator();
#[cfg(not(feature = "router"))]
let navigator = None;
build_sidebar(&sidebar, ¤t_theme(), self, Some(ctx), navigator)
}
}
impl SidebarHost {
fn detached() -> Self {
Self {
opened: Mutex::new(HashMap::new()),
menus: Mutex::new(HashMap::new()),
open: Signal::new(false),
revealed: Mutex::new(None),
reveal: ElementRef::new(),
scroll: ScrollState::new(),
}
}
}
#[cfg(feature = "router")]
type Navigator = crate::router::Navigator;
#[cfg(not(feature = "router"))]
type Navigator = ();
fn build_sidebar(
sidebar: &Sidebar,
theme: &Theme,
host: &SidebarHost,
ctx: Option<&mut Ctx>,
navigator: Option<Navigator>,
) -> Element {
let theme = theme.clone();
let overlay = sidebar.narrow.unwrap_or_else(window_is_narrow);
let collapsed = !overlay && sidebar.collapsed;
let open = sidebar.open.clone().unwrap_or_else(|| host.open.clone());
let mut reveal = false;
if ctx.is_some() {
let selected = selected_path(sidebar);
let key = selected.as_ref().map(|(_, key)| key.clone());
let before = host.revealed.lock().replace(key.clone());
reveal = key.is_some() && before.as_ref() != Some(&key);
if let Some((lists, _)) = selected.as_ref().filter(|_| reveal && before.is_some()) {
for list in lists {
let signal = host
.opened
.lock()
.entry(list.clone())
.or_insert_with(|| Signal::new(true))
.clone();
if !signal.get_untracked() {
signal.set(true);
}
}
}
}
let owner = theme
.resolve::<Sidebar>(&Case::new(), Some(&sidebar.rules))
.owned_by(sidebar.id.as_ref());
let build = Build {
theme: theme.clone(),
owner,
sidebar,
collapsed,
overlay,
close: overlay.then(|| open.clone()),
host,
navigator,
marked: RefCell::new(None),
};
let mut ctx = ctx;
let groups: Vec<Element> = sidebar
.groups
.iter()
.enumerate()
.map(|(index, group)| build.group(&mut ctx, group, index))
.collect();
if let (true, Some(ctx), Some(marked)) = (reveal, ctx.as_deref_mut(), build.marked.borrow().as_ref()) {
ctx.scroll_into_view(marked);
}
let (header, footer) = if collapsed {
(sidebar.header_collapsed.clone(), sidebar.footer_collapsed.clone())
} else {
(sidebar.header.clone(), sidebar.footer.clone())
};
let width = build
.recipe_in(false, false, &[])
.part(SidebarPart::Root)
.rest()
.width
.and_then(|width| match width.resolve(&theme)? {
Dimension::Px(px) => Some(px),
_ => None,
});
let view = SidebarView {
label: sidebar.label.clone(),
collapsed,
overlay,
header,
footer,
groups,
recipe: build.recipe(&[]),
open,
width,
id: sidebar.id.clone(),
key: sidebar.key.clone(),
scroll: host.scroll.clone(),
};
match theme.renderer::<Sidebar>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
impl From<Sidebar> for Element {
fn from(sidebar: Sidebar) -> Self {
sidebar.build(¤t_theme())
}
}
struct Build<'a> {
theme: Theme,
owner: ResolvedRecipe,
sidebar: &'a Sidebar,
collapsed: bool,
overlay: bool,
close: Option<Signal<bool>>,
host: &'a SidebarHost,
navigator: Option<Navigator>,
marked: RefCell<Option<ElementRef>>,
}
impl Build<'_> {
fn recipe(&self, states: &[(SidebarState, bool)]) -> ResolvedRecipe {
self.recipe_in(self.collapsed, self.overlay, states)
}
fn recipe_in(&self, collapsed: bool, overlay: bool, states: &[(SidebarState, bool)]) -> ResolvedRecipe {
let mut case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.sidebar.states.clone(),
}
.state(SidebarState::Collapsed, collapsed)
.state(SidebarState::Overlay, overlay);
for (state, on) in states {
case = case.state(*state, *on);
}
self
.theme
.resolve::<Sidebar>(&case, Some(&self.sidebar.rules))
.owned_like(&self.owner)
}
fn opened(&self, key: &str, initial: bool) -> Signal<bool> {
self
.host
.opened
.lock()
.entry(Arc::from(key))
.or_insert_with(|| Signal::new(initial))
.clone()
}
fn mark(&self, own: Option<&ElementRef>) -> ElementRef {
let marked = own.cloned().unwrap_or_else(|| self.host.reveal.clone());
*self.marked.borrow_mut() = Some(marked.clone());
marked
}
fn menu_state(&self, key: &str) -> (ElementRef, Signal<bool>) {
self
.host
.menus
.lock()
.entry(Arc::from(key))
.or_insert_with(|| (ElementRef::new(), Signal::new(false)))
.clone()
}
fn choose(&self, item: &SidebarItem) -> Option<Handler> {
if item.disabled {
return None;
}
let handlers = item.on_select.clone();
let go = item.href.clone().zip(self.navigator.clone());
if handlers.is_empty() && go.is_none() {
return None;
}
let close = self.close.clone();
Some(Arc::new(move || {
if let Some(close) = &close {
close.set(false);
}
for handler in &handlers {
handler();
}
#[cfg(feature = "router")]
if let Some((path, navigator)) = &go {
navigator.push(path.to_string());
}
}))
}
fn group(&self, ctx: &mut Option<&mut Ctx>, group: &SidebarGroup, index: usize) -> Element {
let key = format!("{index}:{}", group.ident());
let collapsible = group.collapsible && !self.collapsed;
let open = if collapsible {
self.opened(&key, group.default_open).get()
} else {
true
};
let holds = !open && group.items.iter().any(|item| item.selected || item.holds_selected());
let recipe = self.recipe(&[
(SidebarState::Open, open),
(SidebarState::Pressable, collapsible),
(SidebarState::Selected, holds),
]);
let mut root = Column::new()
.align_items(if self.collapsed {
Alignment::Center
} else {
Alignment::Stretch
})
.overflow_visible()
.part(&recipe.part(SidebarPart::Group))
.describe("a11y_role", "group");
if let Some(label) = &group.label {
root = root.describe("a11y_name", label.clone());
}
if !self.collapsed && (group.label.is_some() || group.count.is_some() || group.action.is_some()) {
root = root.child(self.group_label(group, &recipe, &key, open, collapsible, holds));
}
let level = if collapsible { 2 } else { 1 };
let items: Vec<Element> = group
.items
.iter()
.map(|item| self.item(ctx, item, &format!("{key}/{}", item.ident()), 0, level))
.collect();
if !collapsible {
return root.with_children(items).into();
}
root.child(nested(&recipe, open, group.label.as_deref(), items)).into()
}
fn group_label(
&self,
group: &SidebarGroup,
recipe: &ResolvedRecipe,
key: &str,
open: bool,
collapsible: bool,
holds: bool,
) -> Row {
let part = recipe.part(SidebarPart::GroupLabel);
let text = group.label.as_deref().map(|label| {
let part = recipe.part(SidebarPart::GroupText);
Row::new()
.flex(1.0)
.part(&part)
.child(part.text(&label.to_uppercase()).nowrap())
});
let count = group.count.map(|count| {
let part = recipe.part(SidebarPart::GroupCount);
Row::new().part(&part).child(part.text(&count.to_string()).nowrap())
});
let mut label: Element = if collapsible {
let (signal, toggle) = (
self.opened(key, group.default_open),
self.opened(key, group.default_open),
);
let name = group
.label
.clone()
.unwrap_or_else(|| super::current_locale().navigation.group.clone());
let mut button = pressable(&part, false)
.flex(1.0)
.justify(Justify::Start)
.align_items(Alignment::Center)
.describe("a11y_role", "button")
.describe("a11y_name", name.clone())
.describe("a11y_expanded", if open { "true" } else { "false" })
.focus_label(name)
.focus_level(1)
.focus_expanded(open, move |open| toggle.set(open))
.on_click(move |_| signal.update(|open| *open = !*open));
if holds {
button = button.focus_entry(true).ref_element(self.mark(None));
}
button = button.with_children(text).with_children(count).child(glyph(
&recipe.part(SidebarPart::GroupChevron),
Name::new(if open {
icons::CHEVRON_DOWN
} else {
icons::CHEVRON_RIGHT
}),
false,
));
button.into()
} else {
Row::new()
.flex(1.0)
.align_items(Alignment::Center)
.part(&part)
.with_children(text)
.with_children(count)
.into()
};
if let Some(action) = &group.action {
label = Row::new()
.flex(1.0)
.align_items(Alignment::Center)
.overflow_visible()
.child(label)
.child(
Row::new()
.align_items(Alignment::Center)
.focus_group(FocusGroup::none())
.overflow_visible()
.part(&recipe.part(SidebarPart::GroupAction))
.child(action.clone()),
)
.into();
}
Row::new()
.align_items(Alignment::Stretch)
.overflow_visible()
.child(label)
}
fn item(&self, ctx: &mut Option<&mut Ctx>, item: &SidebarItem, key: &str, depth: usize, level: u32) -> Element {
let has_children = !item.children.is_empty();
let open_signal = (has_children && !self.collapsed)
.then(|| self.opened(key, item.default_open.unwrap_or_else(|| item.holds_selected())));
let open = open_signal.as_ref().is_some_and(Signal::get);
let selected = item.selected || (!open && item.holds_selected());
let recipe = self.recipe(&[
(SidebarState::Selected, selected),
(SidebarState::Disabled, item.disabled),
(SidebarState::Open, open),
])
.item(item.id.as_ref(), SidebarPart::Item);
let part = |name: SidebarPart| recipe.part(name).forced(item.forced);
let mut button = pressable(&part(SidebarPart::Item), item.disabled)
.justify(if self.collapsed {
Justify::Center
} else {
Justify::Start
})
.align_items(Alignment::Center)
.describe("a11y_role", if item.href.is_some() { "link" } else { "button" })
.describe("a11y_name", item.label.clone())
.focus_label(item.label.clone())
.focus_level(level);
if selected {
let current = if item.selected { "page" } else { "location" };
button = button.describe("a11y_current", current).focus_entry(true);
}
if let Some(id) = &item.id {
button = button.id(id.clone());
}
if selected && !(self.collapsed && has_children) {
button = button.ref_element(self.mark(None));
}
let choose = self.choose(item);
let aside: Option<Handler> = (!item.disabled && !item.on_open_aside.is_empty()).then(|| {
let handlers = item.on_open_aside.clone();
Arc::new(move || handlers.iter().for_each(|handler| handler())) as Handler
});
if let Some(aside) = &aside {
let aside = aside.clone();
button = button.on_mouse_click(MouseButton::Middle, move |event: MouseEvent| {
event.stop_propagation();
aside();
});
}
let mut menu = None;
if self.collapsed && has_children {
let (anchor, menu_open) = self.menu_state(key);
if selected {
self.mark(Some(&anchor));
}
button = button
.ref_element(anchor.clone())
.describe("a11y_haspopup", "menu")
.describe("a11y_expanded", if menu_open.get() { "true" } else { "false" });
if !item.disabled {
let (press, right) = (menu_open.clone(), menu_open.clone());
button = button
.on_click(move |_| press.update(|open| *open = !*open))
.on_key_down(move |event: KeyboardEvent| {
if event.focus_within && plain(&event) && event.key == "ArrowRight" {
event.prevent_default();
right.set(true);
}
});
}
menu = Some(self.menu(item, key, anchor, menu_open));
} else if let Some(signal) = &open_signal {
button = button.describe("a11y_expanded", if open { "true" } else { "false" });
if !item.disabled {
let (press, keys) = (signal.clone(), signal.clone());
let (choose, aside) = (choose.clone(), aside.clone());
button = button
.on_click(move |event: MouseEvent| {
if let Some(aside) = aside.as_ref().filter(|_| command_held(&event)) {
return aside();
}
press.update(|open| *open = !*open);
if let Some(choose) = &choose {
choose();
}
})
.focus_expanded(open, move |open| keys.set(open));
}
} else if choose.is_some() || aside.is_some() {
button = button.on_click(move |event: MouseEvent| {
if let Some(aside) = aside.as_ref().filter(|_| command_held(&event)) {
return aside();
}
if let Some(choose) = &choose {
choose();
}
});
}
if !self.collapsed {
for _ in 0..depth {
button = button.child(Row::new().part(&part(SidebarPart::ItemIndent)));
}
if has_children {
let chevron = if open {
icons::CHEVRON_DOWN
} else {
icons::CHEVRON_RIGHT
};
button = button.child(glyph(&part(SidebarPart::ItemChevron), Name::new(chevron), false));
}
}
match item.icon {
Some(icon) => button = button.child(glyph(&part(SidebarPart::ItemIcon), icon, false)),
None if self.collapsed => {
let initial: String = item.label.chars().take(1).collect();
let label = part(SidebarPart::ItemLabel);
button = button.child(Row::new().part(&label).child(label.text(&initial).nowrap()));
}
None => {}
}
if !self.collapsed {
let label = part(SidebarPart::ItemLabel);
button = button.child(
Row::new()
.flex(1.0)
.part(&label)
.child(label.text(&item.label).nowrap()),
);
if let Some(badge) = &item.badge {
button = button.child(
Row::new()
.align_items(Alignment::Center)
.overflow_visible()
.part(&part(SidebarPart::ItemBadge))
.child(badge.clone()),
);
}
if let Some(count) = item.count {
let count_part = part(SidebarPart::ItemCount);
button = button.child(
Row::new()
.part(&count_part)
.child(count_part.text(&count.to_string()).nowrap()),
);
}
if let Some(keys) = &item.shortcut {
button = button.child(
Row::new()
.align_items(Alignment::Center)
.part(&part(SidebarPart::ItemShortcut))
.child(Kbd::shortcut(keys).platform(KeyPlatform::current()).build(&self.theme)),
);
}
}
if self.collapsed {
let element: Element = Row::new()
.align_items(Alignment::Center)
.overflow_visible()
.child(button)
.with_children(menu)
.into();
let mut tooltip = Tooltip::new(&item.label).placement(Placement::Right);
if let Some(keys) = &item.shortcut {
tooltip = tooltip.shortcut(keys);
}
return match ctx.as_deref_mut() {
Some(ctx) => tooltip.mount(ctx, element),
None => element,
};
}
if !has_children {
return button.into();
}
let children: Vec<Element> = item
.children
.iter()
.map(|child| self.item(ctx, child, &format!("{key}/{}", child.ident()), depth + 1, level + 1))
.collect();
Column::new()
.align_items(Alignment::Stretch)
.overflow_visible()
.child(button)
.child(nested(&recipe, open, Some(&item.label), children))
.into()
}
fn menu(&self, item: &SidebarItem, key: &str, anchor: ElementRef, open: Signal<bool>) -> Menu {
let mut menu = Menu::new(open, anchor)
.placement(Placement::RightStart)
.label(&item.label);
for child in &item.children {
menu = menu.item(self.menu_item(child, &format!("{key}/{}", child.ident())));
}
menu
}
fn menu_item(&self, item: &SidebarItem, key: &str) -> MenuItem {
let mut entry = MenuItem::new(&item.label).disabled(item.disabled);
if let Some(id) = &item.id {
entry = entry.id(id.clone());
}
if let Some(icon) = item.icon {
entry = entry.icon(icon);
}
if let Some(keys) = &item.shortcut {
entry = entry.shortcut(keys);
}
if !item.children.is_empty() {
let (anchor, open) = self.menu_state(key);
return entry.submenu(self.menu(item, key, anchor, open));
}
entry = entry.radio(item.selected);
if let Some(choose) = self.choose(item) {
entry = entry.on_select(move || choose());
}
entry
}
}
fn selected_path(sidebar: &Sidebar) -> Option<(Vec<Arc<str>>, Arc<str>)> {
fn find(items: &[SidebarItem], key: &str, path: &mut Vec<Arc<str>>) -> Option<Arc<str>> {
for item in items {
let own: Arc<str> = Arc::from(format!("{key}/{}", item.ident()));
if item.selected {
return Some(own);
}
path.push(own.clone());
if let Some(found) = find(&item.children, &own, path) {
return Some(found);
}
path.pop();
}
None
}
sidebar.groups.iter().enumerate().find_map(|(index, group)| {
let key = format!("{index}:{}", group.ident());
let mut path = vec![Arc::from(key.as_str())];
find(&group.items, &key, &mut path).map(|found| (path, found))
})
}
fn nested(recipe: &ResolvedRecipe, open: bool, label: Option<&str>, children: Vec<Element>) -> Column {
let mut panel = Column::new()
.align_items(Alignment::Stretch)
.clip()
.presence()
.part(&recipe.part(SidebarPart::Nested))
.describe("a11y_role", "group");
if let Some(label) = label {
panel = panel.describe("a11y_name", Arc::<str>::from(label));
}
if open {
panel = panel.child(
Column::new()
.key("content")
.align_items(Alignment::Stretch)
.part(&recipe.part(SidebarPart::NestedContent))
.with_children(children),
);
}
panel
}
pub struct SidebarView {
pub label: Arc<str>,
pub collapsed: bool,
pub overlay: bool,
pub header: Option<Element>,
pub footer: Option<Element>,
pub groups: Vec<Element>,
pub recipe: ResolvedRecipe,
open: Signal<bool>,
width: Option<f32>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
scroll: ScrollState,
}
impl SidebarView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn open(&self) -> &Signal<bool> {
&self.open
}
fn alignment(&self) -> Alignment {
if self.collapsed {
Alignment::Center
} else {
Alignment::Stretch
}
}
pub fn header(&mut self) -> Option<Element> {
let header = self.header.take()?;
Some(
Column::new()
.align_items(self.alignment())
.overflow_visible()
.part(&self.part(SidebarPart::Header))
.child(header)
.into(),
)
}
pub fn footer(&mut self) -> Option<Element> {
let footer = self.footer.take()?;
Some(
Column::new()
.align_items(Alignment::Stretch)
.overflow_visible()
.part(&self.part(SidebarPart::Footer))
.child(
Column::new()
.align_items(self.alignment())
.overflow_visible()
.part(&self.part(SidebarPart::FooterContent))
.child(footer),
)
.into(),
)
}
fn bar_room(&self) -> f32 {
let theme = self.theme();
let rest = self.part(SidebarPart::Body).rest();
let own = rest
.padding_end
.or(rest.padding_x)
.map(|padding| padding.resolve(&theme.spacing(), 0.0))
.unwrap_or(0.0);
let bar = theme.scrollbar();
own.max(bar.width + bar.resolved_edge_inset() * 2.0)
}
pub fn body(&mut self) -> Element {
let mut body = Column::new()
.width(Dimension::Pct(100.0))
.align_items(self.alignment())
.part(&self.part(SidebarPart::Body))
.focus_group(
FocusGroup::vertical()
.one_stop(true)
.typeahead(true)
.nested(!self.collapsed),
)
.with_children(std::mem::take(&mut self.groups));
if !self.collapsed {
body = body.padding_right(self.bar_room());
}
let scroll = ScrollVertical::new(body)
.with_scroll_state(self.scroll.clone())
.width(Dimension::Pct(100.0))
.flex_full(1.0, 1.0, None);
if self.collapsed {
return scroll.scrollbar(ScrollBarStyle::hidden()).into();
}
scroll.into()
}
pub fn root(&self, children: Vec<Element>) -> Column {
let mut root = Column::new()
.align_items(self.alignment())
.part(&self.part(SidebarPart::Root))
.describe("a11y_role", "navigation")
.describe("a11y_name", self.label.clone())
.with_children(children);
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key
&& !self.overlay
{
root = root.key(key.clone());
}
root
}
pub fn render(mut self) -> Element {
let children = [self.header(), Some(self.body()), self.footer()]
.into_iter()
.flatten()
.collect();
let root = self.root(children);
if !self.overlay {
return root.into();
}
let mut drawer = Drawer::new(self.open.clone())
.body_scrolls(false)
.overlay(true)
.label(&self.label)
.child(root);
if let Some(width) = self.width {
drawer = drawer.width(width);
}
if let Some(key) = &self.key {
drawer = drawer.key(key.clone());
}
drawer.build(self.theme())
}
}
#[derive(Clone)]
pub struct SidebarHeading {
title: Arc<str>,
description: Option<Arc<str>>,
icon: Option<Name>,
media: Option<Element>,
trailing: Option<Name>,
variant: Name,
collapsed: bool,
on_click: Vec<EventHandler<MouseEvent>>,
anchor: Option<ElementRef>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SidebarHeading {
pub fn new(title: &str) -> Self {
Self {
title: Arc::from(title),
description: None,
icon: None,
media: None,
trailing: None,
variant: SidebarHeadingVariant::Workspace.into(),
collapsed: false,
on_click: Vec::new(),
anchor: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = Some(name.into());
self
}
pub fn media(mut self, media: impl Into<Element>) -> Self {
self.media = Some(media.into());
self
}
pub fn trailing_icon(mut self, name: impl Into<Name>) -> Self {
self.trailing = Some(name.into());
self
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn collapsed(mut self, collapsed: bool) -> Self {
self.collapsed = collapsed;
self
}
pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_click.push(handler.into_event_handler());
self
}
pub fn anchor(mut self, anchor: ElementRef) -> Self {
self.anchor = Some(anchor);
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let pressed = !self.on_click.is_empty() || self.anchor.is_some();
let case = Case {
variant: Some(self.variant),
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(SidebarState::Collapsed, self.collapsed)
.state(SidebarState::Pressable, pressed);
let recipe = theme
.resolve::<Sidebar>(&case, Some(&self.rules))
.owned_by(None)
.item(self.id.as_ref(), SidebarPart::Heading);
let part = |name: SidebarPart| recipe.part(name);
let mut children: Vec<Element> = Vec::new();
match (self.media, self.icon) {
(Some(media), _) => children.push(media),
(None, Some(icon)) => {
let mark = part(SidebarPart::HeadingMark);
children.push(
Row::new()
.justify(Justify::Center)
.align_items(Alignment::Center)
.part(&mark)
.child(Icon::new(icon).size(Length::Icon(IconSize::Md)).build(theme))
.into(),
);
}
(None, None) => {}
}
if !self.collapsed {
let title = part(SidebarPart::HeadingTitle);
let mut text = Column::new()
.flex(1.0)
.part(&part(SidebarPart::HeadingText))
.child(Row::new().part(&title).child(title.text(&self.title).nowrap()));
if let Some(description) = &self.description {
let line = part(SidebarPart::HeadingDescription);
text = text.child(Row::new().part(&line).child(line.text(description).nowrap()));
}
children.push(text.into());
if let Some(trailing) = self.trailing {
children.push(glyph(&part(SidebarPart::HeadingTrailing), trailing, false));
}
}
let root = part(SidebarPart::Heading);
if !pressed {
let mut row = Row::new()
.align_items(Alignment::Center)
.part(&root)
.with_children(children);
if let Some(id) = self.id {
row = row.id(id);
}
if let Some(key) = self.key {
row = row.key(key);
}
return row.into();
}
let mut button = pressable(&root.forced(self.forced), false)
.justify(if self.collapsed {
Justify::Center
} else {
Justify::Start
})
.align_items(Alignment::Center)
.describe("a11y_role", "button")
.describe("a11y_name", self.title.clone())
.with_children(children);
for handler in self.on_click {
button = button.on_click(handler);
}
if let Some(anchor) = self.anchor {
button = button.ref_element(anchor);
}
if let Some(id) = self.id {
button = button.id(id);
}
if let Some(key) = self.key {
button = button.key(key);
}
button.into()
}
}
impl From<SidebarHeading> for Element {
fn from(heading: SidebarHeading) -> Self {
heading.build(¤t_theme())
}
}
#[derive(Clone)]
pub struct SidebarTrigger {
collapsed: Signal<bool>,
open: Option<Signal<bool>>,
narrow: Option<bool>,
collapse_label: Arc<str>,
expand_label: Arc<str>,
open_label: Arc<str>,
close_label: Arc<str>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SidebarTrigger {
pub fn new(collapsed: Signal<bool>) -> Self {
Self {
collapsed,
open: None,
narrow: None,
collapse_label: super::current_locale().navigation.collapse_sidebar.clone(),
expand_label: super::current_locale().navigation.expand_sidebar.clone(),
open_label: super::current_locale().navigation.open_sidebar.clone(),
close_label: super::current_locale().navigation.close_sidebar.clone(),
forced: None,
id: None,
key: None,
}
}
pub fn open(mut self, open: Signal<bool>) -> Self {
self.open = Some(open);
self
}
pub fn narrow(mut self, narrow: bool) -> Self {
self.narrow = Some(narrow);
self
}
pub fn collapse_label(mut self, label: &str) -> Self {
self.collapse_label = Arc::from(label);
self
}
pub fn expand_label(mut self, label: &str) -> Self {
self.expand_label = Arc::from(label);
self
}
pub fn open_label(mut self, label: &str) -> Self {
self.open_label = Arc::from(label);
self
}
pub fn close_label(mut self, label: &str) -> Self {
self.close_label = Arc::from(label);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let narrow = self.narrow.unwrap_or_else(window_is_narrow);
let (label, turned) = match (&self.open, narrow) {
(Some(open), true) => (
if open.get() { self.close_label } else { self.open_label },
open.clone(),
),
_ => (
if self.collapsed.get() {
self.expand_label
} else {
self.collapse_label
},
self.collapsed.clone(),
),
};
let mut button = Button::new(&label)
.variant(ButtonVariant::Ghost)
.icon(icons::PANEL_LEFT)
.icon_only(true)
.force(self.forced)
.on_click(move |_| turned.update(|on| *on = !*on));
if let Some(id) = self.id {
button = button.id(id);
}
if let Some(key) = self.key {
button = button.key(key);
}
button.build(theme)
}
}
impl From<SidebarTrigger> for Element {
fn from(trigger: SidebarTrigger) -> Self {
trigger.build(¤t_theme())
}
}
impl crate::ui::Styled for Sidebar {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for Sidebar {
const NAME: &'static str = "sidebar";
type Renderer = SidebarRenderer;
fn parts() -> crate::ui::Declared {
SidebarPart::declared()
}
fn states() -> crate::ui::Declared {
SidebarState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::*;
use SidebarHeadingVariant::Account;
use SidebarPart::*;
use SidebarState::{Collapsed, Disabled, Open, Overlay, Pressable, Selected};
let line = || Edge::inside(BorderSize::Sm, PaletteColor::Border);
let none = || Edge::inside(0.0, PaletteColor::Border);
let clear = || Color::new(0, 0, 0, 0);
let ring = || Outline::new(BorderSize::Md, Ring).offset(-2.0);
let recipe = Recipe::new()
.base(Root, |s| {
s.width(260.0)
.height(Length::Fill)
.padding_y(8.0)
.gap(2.0)
.background(PaletteColor::Bar)
.foreground(Foreground)
.end_line(line())
.transition(PartTransition::new(Transition::width(), MotionDuration::Slow).easing(MotionEasing::Standard))
})
.state(Collapsed, Root, |s| s.width(52.0).gap(4.0))
.state(Overlay, Root, |s| {
s.width(Length::Fill)
.background(clear())
.end_line(none())
})
.base(Header, |s| s.gap(2.0).padding_x(8.0))
.state(Collapsed, Header, |s| s.padding_bottom(8.0))
.base(Body, |s| s.gap(2.0).padding_x(8.0))
.state(Collapsed, Body, |s| s.gap(4.0))
.base(Footer, |s| s.padding_x(8.0))
.base(FooterContent, |s| s.gap(2.0).padding_y(2.0).top_line(line()))
.state(Collapsed, FooterContent, |s| s.padding_y(0.0).top_line(none()))
.base(Group, |s| s.gap(2.0))
.state(Collapsed, Group, |s| s.gap(4.0))
.base(GroupLabel, |s| {
s.padding_x(8.0)
.padding_top(10.0)
.padding_bottom(4.0)
.gap(8.0)
.radius(RadiusSize::Md)
})
.state(Pressable, GroupLabel, |s| fading(s.cursor(CursorIcon::Pointer)))
.when(Selector::new().state(Pressable).hovered(), GroupLabel, |s| {
s.background(StateHover)
})
.when(Selector::new().state(Pressable).focus_visible(), GroupLabel, |s| {
s.outline(ring())
})
.base(GroupText, |s| {
s.typography(TypographyStyle::Label)
.font_size(11.0)
.weight(FontWeight::SemiBold)
.letter_spacing(0.6)
.foreground(MutedForeground)
})
.base(GroupCount, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(GroupChevron, |s| s.square(14.0).foreground(MutedForeground))
.state(Selected, GroupText, |s| s.foreground(Foreground))
.state(Selected, GroupChevron, |s| s.foreground(Foreground))
.base(Item, |s| {
fading(
s.height(32.0)
.padding_x(8.0)
.gap(8.0)
.radius(RadiusSize::Md)
.foreground(Foreground)
.cursor(CursorIcon::Pointer),
)
})
.row_density(Selector::new(), Item, 32.0)
.state(Collapsed, Item, |s| s.width(36.0).padding_x(0.0))
.hovered(Item, |s| s.background(StateHover))
.pressed(Item, |s| s.background(StatePressed))
.focus_visible(Item, |s| s.outline(ring()))
.state(Selected, Item, |s| s.background(Background).border(line()))
.when(Selector::new().state(Selected).hovered(), Item, |s| s.background(Background))
.when(Selector::new().state(Selected).pressed(), Item, |s| s.background(Background))
.state(Disabled, Item, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.when(Selector::new().state(Disabled).hovered(), Item, |s| s.background(clear()))
.base(ItemIcon, |s| s.square(16.0).foreground(MutedForeground))
.state(Selected, ItemIcon, |s| s.foreground(Foreground))
.base(ItemLabel, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(Foreground)
})
.state(Selected, ItemLabel, |s| s.weight(FontWeight::Medium))
.base(ItemCount, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(ItemChevron, |s| s.square(14.0).foreground(MutedForeground))
.base(ItemIndent, |s| s.width(10.0).height(1.0))
.base(NestedContent, |s| s.gap(2.0))
.base(Heading, |s| {
s.height(44.0)
.padding_x(8.0)
.gap(10.0)
.radius(RadiusSize::Md)
.foreground(Foreground)
})
.state(Pressable, Heading, |s| fading(s.cursor(CursorIcon::Pointer)))
.when(Selector::new().state(Pressable).hovered(), Heading, |s| {
s.background(StateHover)
})
.when(Selector::new().state(Pressable).focus_visible(), Heading, |s| {
s.outline(ring())
})
.state(Collapsed, Heading, |s| s.height(Length::Auto).padding_x(0.0).gap(0.0))
.base(HeadingMark, |s| {
s.square(28.0)
.radius(RadiusSize::Md)
.background(Primary)
.foreground(PrimaryForeground)
})
.base(HeadingText, |s| s.gap(1.0))
.base(HeadingTitle, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::SemiBold)
.foreground(Foreground)
})
.variant(Account, HeadingTitle, |s| s.weight(FontWeight::Medium))
.base(HeadingDescription, |s| {
s.typography(TypographyStyle::Body)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(HeadingTrailing, |s| s.square(14.0).foreground(MutedForeground))
.variant(Account, HeadingTrailing, |s| s.square(16.0).foreground(Foreground));
opening(recipe, Open.into(), Nested.into(), NestedContent.into())
}
}