use std::{sync::Arc, time::Duration};
use parking_lot::Mutex;
use super::{
icons,
menu::{Menu, MenuItem},
names,
part_style::{PartAnimation, PartStyle, TransitionDuration},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{FADE_IN, FADE_OUT, fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::{CollisionStrategy, Ctx, OutsidePress, Placement, Timeout},
events::{KeyboardEvent, MouseEvent},
theme::{
BorderSize, IconSize, MotionDuration, MotionEasing, OpacityLevel, PaletteColor, RadiusSize, ShadowStyle, Theme,
TypographyStyle,
},
},
components::{self, Column, Popup, Row},
core::{ElementRef, Signal, WatchHandle},
layout::{
Alignment,
layout_kind::{Justify, ShrinkLimit},
text_style::FontWeight,
},
node::{
CursorIcon, Element, FocusGroup, HitTestBehavior, NodeUpdate, border::Border, color::Color, dimension::Dimension,
},
};
type Handler = Arc<dyn Fn() + Send + Sync>;
pub(crate) type OpenHandler = Arc<dyn Fn(Option<usize>) + Send + Sync>;
#[cfg(feature = "router")]
type Navigator = crate::router::Navigator;
#[cfg(not(feature = "router"))]
type Navigator = ();
fn plain(event: &KeyboardEvent) -> bool {
!event.ctrl && !event.alt && !event.meta
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NavigationMenuPart {
Bar,
Item,
ItemIcon,
Label,
Chevron,
Viewport,
Panel,
Column,
Featured,
Link,
LinkIcon,
LinkText,
LinkTitle,
LinkDescription,
}
names!(NavigationMenuPart {
Bar => "bar",
Item => "item",
ItemIcon => "item_icon",
Label => "label",
Chevron => "chevron",
Viewport => "viewport",
Panel => "panel",
Column => "column",
Featured => "featured",
Link => "link",
LinkIcon => "link_icon",
LinkText => "link_text",
LinkTitle => "link_title",
LinkDescription => "link_description",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NavigationMenuState {
Open,
Current,
Disabled,
}
names!(NavigationMenuState {
Open => "open",
Current => "current",
Disabled => "disabled",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NavigationMenuVariant {
#[default]
Menu,
Links,
}
names!(NavigationMenuVariant {
Menu => "menu",
Links => "links",
});
pub type NavigationMenuRenderer = Arc<dyn Fn(NavigationMenuView) -> Element + Send + Sync>;
#[derive(Clone)]
pub struct NavLink {
pub(crate) title: Arc<str>,
pub(crate) description: Option<Arc<str>>,
pub(crate) icon: Option<Name>,
pub(crate) href: Option<Arc<str>>,
pub(crate) on_select: Vec<Handler>,
pub(crate) current: bool,
pub(crate) disabled: bool,
pub(crate) id: Option<Arc<str>>,
pub(crate) key: Option<Arc<str>>,
}
impl NavLink {
pub fn new(title: &str) -> Self {
Self {
title: Arc::from(title),
description: None,
icon: None,
href: None,
on_select: Vec::new(),
current: false,
disabled: false,
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 href(mut self, path: &str) -> Self {
self.href = Some(Arc::from(path));
self
}
pub fn on_select(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn current(mut self, current: bool) -> Self {
self.current = current;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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
}
}
#[derive(Clone)]
pub struct NavPanel {
pub(crate) links: Vec<NavLink>,
pub(crate) columns: usize,
pub(crate) featured: Option<Element>,
}
impl Default for NavPanel {
fn default() -> Self {
Self::new()
}
}
impl NavPanel {
pub fn new() -> Self {
Self {
links: Vec::new(),
columns: 1,
featured: None,
}
}
pub fn link(mut self, link: NavLink) -> Self {
self.links.push(link);
self
}
pub fn links(mut self, links: impl IntoIterator<Item = NavLink>) -> Self {
self.links.extend(links);
self
}
pub fn columns(mut self, columns: usize) -> Self {
self.columns = columns.max(1);
self
}
pub fn featured(mut self, featured: impl Into<Element>) -> Self {
self.featured = Some(featured.into());
self
}
}
#[derive(Clone)]
pub struct NavItem {
pub(crate) label: Arc<str>,
pub(crate) href: Option<Arc<str>>,
pub(crate) on_select: Vec<Handler>,
pub(crate) current: bool,
pub(crate) icon: Option<Name>,
pub(crate) disabled: bool,
pub(crate) panel: Option<NavPanel>,
pub(crate) id: Option<Arc<str>>,
pub(crate) key: Option<Arc<str>>,
}
impl NavItem {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
href: None,
on_select: Vec::new(),
current: false,
icon: None,
disabled: false,
panel: None,
id: None,
key: None,
}
}
pub fn href(mut self, path: &str) -> Self {
self.href = Some(Arc::from(path));
self
}
pub fn on_select(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn current(mut self, current: bool) -> Self {
self.current = current;
self
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = Some(name.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn panel(mut self, panel: NavPanel) -> Self {
self.panel = Some(panel);
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(crate) fn holds_current(&self) -> bool {
self.current
|| self
.panel
.as_ref()
.is_some_and(|panel| panel.links.iter().any(|link| link.current))
}
}
#[derive(Clone)]
pub struct NavigationMenu {
pub(crate) label: Arc<str>,
pub(crate) more_label: Arc<str>,
pub(crate) items: Vec<NavItem>,
pub(crate) open: Option<Signal<Option<usize>>>,
pub(crate) on_open_change: Vec<OpenHandler>,
pub(crate) variant: Name,
pub(crate) open_delay: TransitionDuration,
pub(crate) close_delay: TransitionDuration,
pub(crate) disabled: bool,
pub(crate) landmark: bool,
pub(crate) states: Vec<Name>,
pub(crate) rules: Recipe,
pub(crate) forced: Option<Interaction>,
pub(crate) id: Option<Arc<str>>,
pub(crate) key: Option<Arc<str>>,
}
impl Default for NavigationMenu {
fn default() -> Self {
Self::new()
}
}
impl NavigationMenu {
pub fn new() -> Self {
Self {
label: super::current_locale().navigation.main.clone(),
more_label: super::current_locale().common.more.clone(),
items: Vec::new(),
open: None,
on_open_change: Vec::new(),
variant: Name::from(NavigationMenuVariant::Menu),
open_delay: TransitionDuration::Role(MotionDuration::Base),
close_delay: TransitionDuration::Role(MotionDuration::Slow),
disabled: false,
landmark: true,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn label(mut self, label: &str) -> Self {
self.label = Arc::from(label);
self
}
pub fn item(mut self, item: NavItem) -> Self {
self.items.push(item);
self
}
pub fn items(mut self, items: impl IntoIterator<Item = NavItem>) -> Self {
self.items.extend(items);
self
}
pub fn open(mut self, open: Signal<Option<usize>>) -> Self {
self.open = Some(open);
self
}
pub fn on_open_change(mut self, handler: impl Fn(Option<usize>) + Send + Sync + 'static) -> Self {
self.on_open_change.push(Arc::new(handler));
self
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn open_delay(mut self, delay: impl Into<TransitionDuration>) -> Self {
self.open_delay = delay.into();
self
}
pub fn close_delay(mut self, delay: impl Into<TransitionDuration>) -> Self {
self.close_delay = delay.into();
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub(crate) fn landmark(mut self, landmark: bool) -> Self {
self.landmark = landmark;
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 more_label(mut self, label: &str) -> Self {
self.more_label = Arc::from(label);
self
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
ctx.mount::<NavigationMenuHost>(NavigationMenuProps { menu: self })
}
fn resolve(&self, theme: &Theme, case: &Case) -> ResolvedRecipe {
theme.resolve::<NavigationMenu>(case, Some(&self.rules))
}
}
impl From<NavigationMenu> for Element {
fn from(menu: NavigationMenu) -> Self {
let own = Signal::new(None);
let shared = Arc::new(Shared::new());
build(&menu, &shared, &own, None, None, None)
}
}
#[derive(Clone)]
struct NavigationMenuProps {
menu: NavigationMenu,
}
impl PartialEq for NavigationMenuProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for NavigationMenuProps {}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Opened {
#[default]
Pointer,
Press,
Key,
}
#[derive(Default)]
struct Pointer {
on_item: Option<usize>,
on_panel: bool,
}
#[derive(Clone)]
struct Kept {
open: Signal<bool>,
anchor: ElementRef,
panel: ElementRef,
first: ElementRef,
slot: ElementRef,
}
#[derive(Default)]
struct Watches {
bound: Option<usize>,
_leads: Option<WatchHandle<Option<usize>>>,
_follows: Vec<WatchHandle<bool>>,
}
struct Shared {
app: Arc<Mutex<Option<Signal<Option<usize>>>>>,
heard: Arc<Mutex<Vec<OpenHandler>>>,
panels: Arc<Mutex<Vec<Kept>>>,
watches: Mutex<Watches>,
opened: Mutex<Opened>,
pointer: Mutex<Pointer>,
pending: Mutex<Option<usize>>,
focus_first: Mutex<Option<usize>>,
nudge: Signal<u64>,
held: Mutex<Option<usize>>,
shown: Mutex<Option<usize>>,
dropped: Signal<Vec<bool>>,
more_open: Signal<bool>,
more: ElementRef,
}
impl Shared {
fn new() -> Self {
Self {
app: Arc::new(Mutex::new(None)),
heard: Arc::new(Mutex::new(Vec::new())),
panels: Arc::new(Mutex::new(Vec::new())),
watches: Mutex::new(Watches::default()),
opened: Mutex::new(Opened::Pointer),
pointer: Mutex::new(Pointer::default()),
pending: Mutex::new(None),
focus_first: Mutex::new(None),
nudge: Signal::new(0),
held: Mutex::new(None),
shown: Mutex::new(None),
dropped: Signal::new(Vec::new()),
more_open: Signal::new(false),
more: ElementRef::new(),
}
}
fn slot(&self, index: usize) -> ElementRef {
let slot = ElementRef::new();
let (dropped, app, more_open) = (self.dropped.clone(), self.app.clone(), self.more_open.clone());
slot.observe_rect_before_paint(move |rect| {
let now = rect.width <= 0.0 && rect.height <= 0.0;
if dropped.get_untracked().get(index).copied().unwrap_or(false) == now {
return;
}
dropped.update(|dropped| {
if dropped.len() <= index {
dropped.resize(index + 1, false);
}
dropped[index] = now;
});
if now {
let app = app.lock().clone();
if let Some(app) = app
&& app.get_untracked() == Some(index)
{
app.set(None);
}
} else if more_open.get_untracked() && !dropped.get_untracked().contains(&true) {
more_open.set(false);
}
});
slot
}
fn app(&self) -> Option<Signal<Option<usize>>> {
self.app.lock().clone()
}
fn now(&self) -> Option<usize> {
self.app().and_then(|app| app.get_untracked())
}
fn opened(&self) -> Opened {
*self.opened.lock()
}
fn kept(&self, index: usize) -> Option<Kept> {
self.panels.lock().get(index).cloned()
}
fn open(&self, index: usize, how: Opened) {
*self.opened.lock() = how;
*self.held.lock() = None;
if let Some(app) = self.app()
&& app.get_untracked() != Some(index)
{
app.set(Some(index));
}
}
fn close(&self) {
if let Some(app) = self.app()
&& app.get_untracked().is_some()
{
app.set(None);
}
}
fn bind(&self, app: &Signal<Option<usize>>, count: usize) {
let mut watches = self.watches.lock();
if watches.bound != Some(app.id()) {
*self.app.lock() = Some(app.clone());
watches.bound = Some(app.id());
let panels = self.panels.lock().clone();
for (index, kept) in panels.iter().enumerate() {
let want = app.get_untracked() == Some(index);
if kept.open.get_untracked() != want {
kept.open.set(want);
}
}
watches._follows = panels
.iter()
.enumerate()
.map(|(index, kept)| follow(app, &kept.open, index))
.collect();
watches._leads = Some(lead(app, &self.panels, &self.heard));
}
let mut panels = self.panels.lock();
while panels.len() < count {
let index = panels.len();
let open = Signal::new(app.get_untracked() == Some(index));
watches._follows.push(follow(app, &open, index));
panels.push(Kept {
open,
anchor: ElementRef::new(),
panel: ElementRef::new(),
first: ElementRef::new(),
slot: self.slot(index),
});
}
}
}
fn follow(app: &Signal<Option<usize>>, open: &Signal<bool>, index: usize) -> WatchHandle<bool> {
let (own, app) = (open.clone(), app.clone());
open.watch(move || {
let (on, now) = (own.get_untracked(), app.get_untracked());
if on && now != Some(index) {
app.set(Some(index));
} else if !on && now == Some(index) {
app.set(None);
}
})
}
fn lead(
app: &Signal<Option<usize>>,
panels: &Arc<Mutex<Vec<Kept>>>,
heard: &Arc<Mutex<Vec<OpenHandler>>>,
) -> WatchHandle<Option<usize>> {
let (signal, panels, heard) = (app.clone(), panels.clone(), heard.clone());
app.watch(move || {
let now = signal.get_untracked();
let opens: Vec<Signal<bool>> = panels.lock().iter().map(|kept| kept.open.clone()).collect();
for (index, open) in opens.iter().enumerate() {
let want = now == Some(index);
if open.get_untracked() != want {
open.set(want);
}
}
let heard = heard.lock().clone();
for handler in heard {
handler(now);
}
})
}
#[derive(Clone)]
struct Timers {
opening: Timeout,
closing: Timeout,
leaving: Timeout,
instant: bool,
}
struct NavigationMenuHost {
own: Signal<Option<usize>>,
shared: Arc<Shared>,
timers: Timers,
}
fn length(duration: TransitionDuration, theme: &Theme) -> Duration {
match duration {
TransitionDuration::Role(role) => theme.durations().try_get(role).unwrap_or_default(),
TransitionDuration::Set(duration) => duration,
}
}
impl Component for NavigationMenuHost {
type Props = NavigationMenuProps;
fn create(ctx: &mut Ctx) -> Self {
let shared = Arc::new(Shared::new());
let opening = {
let shared = shared.clone();
ctx.create_timeout(Duration::ZERO, move || {
let pending = shared.pending.lock().take();
let on = shared.pointer.lock().on_item;
if let Some(index) = pending
&& on == Some(index)
{
shared.open(index, Opened::Pointer);
}
})
};
let closing = {
let shared = shared.clone();
ctx.create_timeout(Duration::ZERO, move || {
let gone = {
let pointer = shared.pointer.lock();
pointer.on_item.is_none() && !pointer.on_panel
};
if gone && shared.opened() != Opened::Key {
shared.close();
}
})
};
let leaving = {
let shared = shared.clone();
ctx.create_timeout(Duration::ZERO, move || {
let Some(open) = shared.now() else {
return;
};
if *shared.held.lock() != Some(open) {
return;
}
let Some(kept) = shared.kept(open) else {
return;
};
let within = kept.anchor.focus_visible_within_signal().get_untracked()
|| kept.panel.focus_visible_within_signal().get_untracked();
if !within {
*shared.held.lock() = None;
shared.close();
}
})
};
Self {
own: ctx.signal(None),
shared,
timers: Timers {
opening,
closing,
leaving,
instant: false,
},
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let menu = ctx.props::<NavigationMenuProps>().menu.clone();
let theme = current_theme();
let open_delay = length(menu.open_delay, &theme);
self.timers.opening.set_duration(open_delay);
self.timers.closing.set_duration(length(menu.close_delay, &theme));
let timers = Timers {
instant: open_delay.is_zero(),
..self.timers.clone()
};
#[cfg(feature = "router")]
let navigator = ctx.navigator();
#[cfg(not(feature = "router"))]
let navigator = None;
build(&menu, &self.shared, &self.own, Some(&timers), Some(ctx), navigator)
}
}
fn build(
menu: &NavigationMenu,
shared: &Arc<Shared>,
own: &Signal<Option<usize>>,
timers: Option<&Timers>,
ctx: Option<&mut Ctx>,
navigator: Option<Navigator>,
) -> Element {
let theme = current_theme();
let app = menu.open.clone().unwrap_or_else(|| own.clone());
*shared.heard.lock() = menu.on_open_change.clone();
shared.bind(&app, menu.items.len());
let open = app.get().filter(|_| !menu.disabled);
let _ = shared.nudge.get();
let mut dropped = shared.dropped.get();
dropped.resize(menu.items.len(), false);
if std::mem::replace(&mut *shared.shown.lock(), open) != open {
shared.pointer.lock().on_panel = false;
}
if let Some(open) = open
&& let Some(kept) = shared.kept(open)
{
let within = kept.anchor.focus_visible_within() || kept.panel.focus_visible_within();
let mut held = shared.held.lock();
if within {
*held = Some(open);
} else if *held == Some(open)
&& let Some(timers) = timers
{
timers.leaving.restart();
}
drop(held);
let first = shared.focus_first.lock().take();
if first == Some(open)
&& let Some(ctx) = &ctx
{
ctx.focus(&kept.first);
}
}
let case = Case {
variant: Some(menu.variant.clone()),
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: menu.states.clone(),
}
.state(NavigationMenuState::Disabled, menu.disabled);
let view = NavigationMenuView {
label: menu.label.clone(),
more_label: menu.more_label.clone(),
items: menu.items.clone(),
dropped,
open,
disabled: menu.disabled,
recipe: menu.resolve(&theme, &case).owned_by(menu.id.as_ref()),
case,
rules: menu.rules.clone(),
forced: menu.forced,
landmark: menu.landmark,
shared: shared.clone(),
timers: timers.cloned(),
navigator,
id: menu.id.clone(),
key: menu.key.clone(),
};
match theme.renderer::<NavigationMenu>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
pub struct NavigationMenuView {
pub label: Arc<str>,
pub more_label: Arc<str>,
pub items: Vec<NavItem>,
pub dropped: Vec<bool>,
pub open: Option<usize>,
pub disabled: bool,
pub recipe: ResolvedRecipe,
case: Case,
rules: Recipe,
forced: Option<Interaction>,
landmark: bool,
shared: Arc<Shared>,
timers: Option<Timers>,
navigator: Option<Navigator>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl NavigationMenuView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn is_disabled(&self, index: usize) -> bool {
self.disabled || self.items.get(index).is_some_and(|item| item.disabled)
}
fn recipe_in(&self, states: &[(NavigationMenuState, bool)]) -> ResolvedRecipe {
let mut case = self.case.clone();
for (state, on) in states {
case = case.state(*state, *on);
}
self
.theme()
.resolve::<NavigationMenu>(&case, Some(&self.rules))
.owned_like(&self.recipe)
}
pub fn item_part(&self, index: usize, part: impl Into<Name>) -> ResolvedPart {
let current = self.items.get(index).is_some_and(NavItem::holds_current);
self
.recipe_in(&[
(NavigationMenuState::Open, self.open == Some(index)),
(NavigationMenuState::Current, current),
(NavigationMenuState::Disabled, self.is_disabled(index)),
])
.item(self.item_id(index).as_ref(), NavigationMenuPart::Item)
.part(part)
.forced(self.forced)
}
fn item_id(&self, index: usize) -> Option<Arc<str>> {
let own = self.items.get(index).and_then(|item| item.id.clone());
own.or_else(|| self.id.as_ref().map(|id| Arc::from(format!("{id}-{index}"))))
}
fn panel_id(&self, index: usize) -> Arc<str> {
match &self.id {
Some(id) => Arc::from(format!("{id}-{index}-panel")),
None => Arc::from(format!(
"navigation-menu-{:x}-{index}-panel",
Arc::as_ptr(&self.shared) as usize
)),
}
}
pub fn bar(&self) -> Row {
let mut bar = Row::new()
.align_items(Alignment::Center)
.overflow_visible()
.max_width(Dimension::Pct(100.0))
.min_width(Dimension::Px(0.0))
.flex_shrink(1.0)
.part(&self.part(NavigationMenuPart::Bar))
.focus_group(FocusGroup::horizontal().panel_row(true))
.describe("a11y_role", if self.landmark { "navigation" } else { "list" });
if self.landmark {
bar = bar.describe("a11y_name", self.label.clone());
}
if let Some(id) = &self.id {
bar = bar.id(id.clone());
}
if let Some(key) = &self.key {
bar = bar.key(key.clone());
}
bar
}
fn choose(&self, on_select: &[Handler], href: Option<&Arc<str>>) -> impl Fn(MouseEvent) + Send + Sync + 'static {
let chosen = self.chosen(on_select, href);
move |_: MouseEvent| chosen()
}
fn chosen(&self, on_select: &[Handler], href: Option<&Arc<str>>) -> impl Fn() + Send + Sync + 'static {
let handlers = on_select.to_vec();
#[cfg(feature = "router")]
let go = href.cloned().zip(self.navigator.clone());
#[cfg(not(feature = "router"))]
let _ = href;
let shared = self.shared.clone();
move || {
shared.close();
for handler in &handlers {
handler();
}
#[cfg(feature = "router")]
if let Some((path, navigator)) = &go {
navigator.push(path.to_string());
}
}
}
pub fn item(&self, index: usize) -> components::Button {
let Some(item) = self.items.get(index) else {
return components::Button::empty();
};
let disabled = self.is_disabled(index);
let open = self.open == Some(index);
let mut button = pressable(&self.item_part(index, NavigationMenuPart::Item), disabled)
.align_items(Alignment::Center)
.describe("a11y_name", item.label.clone())
.focus_label(item.label.clone());
if let Some(id) = self.item_id(index) {
button = button.id(id);
}
if let Some(key) = &item.key {
button = button.key(key.clone());
}
if item.panel.is_none() {
button = button.describe("a11y_role", "link");
if item.current {
button = button.describe("a11y_current", "page");
}
if !disabled {
button = button.on_click(self.choose(&item.on_select, item.href.as_ref()));
}
return button;
}
let anchor = self.shared.kept(index).map_or_else(ElementRef::new, |kept| kept.anchor);
button = button
.ref_element(anchor)
.describe("a11y_role", "button")
.describe("a11y_expanded", if open { "true" } else { "false" })
.describe("a11y_controls", self.panel_id(index));
if disabled {
return button;
}
let shared = &self.shared;
let (press, asked, keys) = (shared.clone(), shared.clone(), shared.clone());
let timers = self.timers.clone();
button = button
.on_click(move |event: MouseEvent| {
if let Some(timers) = &timers {
timers.opening.cancel();
}
if press.now() != Some(index) {
press.open(index, if event.from_keyboard { Opened::Key } else { Opened::Press });
} else if press.opened() == Opened::Pointer && !event.from_keyboard {
*press.opened.lock() = Opened::Press;
} else {
press.close();
}
})
.focus_expanded(open, move |want| {
if want {
asked.open(index, Opened::Key);
} else {
asked.close();
}
})
.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || !plain(&event) || event.key != "ArrowDown" {
return;
}
event.prevent_default();
if keys.now() == Some(index) {
*keys.opened.lock() = Opened::Key;
*keys.focus_first.lock() = Some(index);
keys.nudge.update(|nudge| *nudge += 1);
} else {
keys.open(index, Opened::Key);
}
});
if let Some(timers) = &self.timers {
let (enter, leave) = ((shared.clone(), timers.clone()), (shared.clone(), timers.clone()));
button = button
.on_mouse_enter(move || {
let (shared, timers) = &enter;
shared.pointer.lock().on_item = Some(index);
timers.closing.cancel();
match shared.now() {
Some(open) if open == index => {}
Some(_) => {
timers.opening.cancel();
shared.open(index, Opened::Pointer);
}
None if timers.instant => shared.open(index, Opened::Pointer),
None => {
*shared.pending.lock() = Some(index);
timers.opening.restart();
}
}
})
.on_mouse_leave(move || {
let (shared, timers) = &leave;
{
let mut pointer = shared.pointer.lock();
if pointer.on_item == Some(index) {
pointer.on_item = None;
}
}
timers.opening.cancel();
if shared.now().is_some() && shared.opened() != Opened::Key {
timers.closing.restart();
}
});
}
button
}
pub fn item_icon(&self, index: usize) -> Option<Element> {
let name = self.items.get(index)?.icon?;
Some(glyph(&self.item_part(index, NavigationMenuPart::ItemIcon), name, false))
}
pub fn label(&self, index: usize) -> Element {
let part = self.item_part(index, NavigationMenuPart::Label);
let label = self.items.get(index).map(|item| item.label.clone()).unwrap_or_default();
Row::new().part(&part).child(part.text(&label).nowrap()).into()
}
pub fn chevron(&self, index: usize) -> Option<Element> {
self.items.get(index)?.panel.as_ref()?;
let name = if self.open == Some(index) {
icons::CHEVRON_UP
} else {
icons::CHEVRON_DOWN
};
Some(glyph(
&self.item_part(index, NavigationMenuPart::Chevron),
Name::new(name),
false,
))
}
fn link(&self, index: usize, at: usize, link: &NavLink, first: Option<&ElementRef>) -> Element {
let id = link
.id
.clone()
.or_else(|| self.id.as_ref().map(|id| Arc::from(format!("{id}-{index}-{at}"))));
let recipe = self
.recipe_in(&[
(NavigationMenuState::Current, link.current),
(NavigationMenuState::Disabled, link.disabled),
])
.item(id.as_ref(), NavigationMenuPart::Link);
let part = |name: NavigationMenuPart| recipe.part(name).forced(self.forced);
let fill = Dimension::Pct(100.0);
let mut button = pressable(&part(NavigationMenuPart::Link), link.disabled)
.width(fill)
.justify(Justify::Start)
.align_items(Alignment::Start)
.describe("a11y_role", "link")
.describe("a11y_name", link.title.clone())
.focus_label(link.title.clone());
if let Some(description) = &link.description {
button = button.describe("a11y_description", description.clone());
}
if link.current {
button = button.describe("a11y_current", "page");
}
if let Some(first) = first {
button = button.ref_element(first.clone()).autofocus(true);
}
if let Some(id) = id {
button = button.id(id);
}
if let Some(key) = &link.key {
button = button.key(key.clone());
}
if !link.disabled {
button = button.on_click(self.choose(&link.on_select, link.href.as_ref()));
}
if let Some(icon) = link.icon {
button = button.child(glyph(&part(NavigationMenuPart::LinkIcon), icon, false));
}
let wrapping = |name: NavigationMenuPart, content: &str| {
let style = part(name);
Column::new()
.width(fill)
.min_width(Dimension::Px(0.0))
.part(&style)
.child(style.text(content).width(fill))
};
let mut text = Column::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.align_items(Alignment::Stretch)
.part(&part(NavigationMenuPart::LinkText))
.child(wrapping(NavigationMenuPart::LinkTitle, &link.title));
if let Some(description) = &link.description {
text = text.child(wrapping(NavigationMenuPart::LinkDescription, description));
}
button.child(text).into()
}
pub fn panel_content(&mut self, index: usize) -> Option<Row> {
let panel = self.items.get_mut(index)?.panel.as_mut()?;
let featured = panel.featured.take();
let panel = panel.clone();
let first_at = panel.links.iter().position(|link| !link.disabled);
let first = self.shared.kept(index).map(|kept| kept.first);
let fill = Dimension::Pct(100.0);
let named = self.id.as_ref().map(|_| self.panel_id(index));
let inner = self.recipe.item(named.as_ref(), NavigationMenuPart::Panel);
let inner = |part: NavigationMenuPart| inner.part(part).forced(self.forced);
let mut row = Row::new()
.wrap()
.max_width(fill)
.align_items(Alignment::Stretch)
.part(&self.part(NavigationMenuPart::Panel))
.focus_group(FocusGroup::vertical())
.describe("a11y_role", "group")
.id(self.panel_id(index));
if let Some(featured) = featured {
row = row.child(
Column::new()
.align_items(Alignment::Stretch)
.part(&inner(NavigationMenuPart::Featured))
.max_width(fill)
.focus_group(FocusGroup::none())
.child(featured),
);
}
let per = panel.links.len().div_ceil(panel.columns).max(1);
for (column_at, links) in panel.links.chunks(per).enumerate() {
let mut column = Column::new()
.align_items(Alignment::Stretch)
.overflow_visible()
.part(&inner(NavigationMenuPart::Column))
.max_width(fill);
for (in_column, link) in links.iter().enumerate() {
let at = column_at * per + in_column;
let first = first.as_ref().filter(|_| Some(at) == first_at);
column = column.child(self.link(index, at, link, first));
}
row = row.child(column);
}
if let Some(item) = self.items.get(index) {
row = row.describe("a11y_name", item.label.clone());
}
if let Some(kept) = self.shared.kept(index) {
row = row.ref_element(kept.panel);
}
Some(row)
}
pub fn panel(&mut self, index: usize) -> Option<Element> {
let content = self.panel_content(index)?;
let kept = self.shared.kept(index)?;
let mut viewport = Column::new()
.align_items(Alignment::Start)
.overflow_visible()
.part(&self.part(NavigationMenuPart::Viewport))
.child(content);
if let Some(timers) = &self.timers {
let (enter, leave) = (
(self.shared.clone(), timers.clone()),
(self.shared.clone(), timers.clone()),
);
viewport = viewport
.on_mouse_enter(move || {
let (shared, timers) = &enter;
shared.pointer.lock().on_panel = true;
timers.closing.cancel();
})
.on_mouse_leave(move || {
let (shared, timers) = &leave;
shared.pointer.lock().on_panel = false;
if shared.opened() != Opened::Key {
timers.closing.restart();
}
});
}
let keyed = self.open == Some(index) && self.shared.opened() == Opened::Key;
let popup = Popup::new(kept.anchor, viewport)
.open(kept.open)
.placement(Placement::BottomStart)
.collision(CollisionStrategy::FlipThenClamp)
.hit_test(HitTestBehavior::Auto)
.outside_press(OutsidePress::PassThrough);
let popup = if keyed {
popup.takes_focus(true)
} else {
popup.tab_after_anchor(true)
};
Some(popup.into())
}
pub fn slot(&self, index: usize, element: impl Into<Element>) -> Element {
let mut element = element.into();
NodeUpdate::flex_shrink(&mut *element.node, 1.0);
NodeUpdate::shrink_limit(&mut *element.node, ShrinkLimit::Drop);
if let Some(kept) = self.shared.kept(index) {
NodeUpdate::ref_element(&mut *element.node, kept.slot);
}
element
}
fn more_item(
label: &str,
icon: Option<Name>,
disabled: bool,
id: Option<Arc<str>>,
chosen: impl Fn() + Send + Sync + 'static,
) -> MenuItem {
let mut item = MenuItem::new(label).disabled(disabled).on_select(chosen);
if let Some(icon) = icon {
item = item.icon(icon);
}
if let Some(id) = id {
item = item.id(format!("{id}-item"));
}
item
}
pub fn more(&self) -> Option<Element> {
if self.items.is_empty() {
return None;
}
let shared = &self.shared;
let open = shared.more_open.get();
let went = |index: &usize| self.dropped.get(*index).copied().unwrap_or(false);
let current = (0..self.items.len())
.filter(went)
.any(|index| self.items[index].holds_current());
let more_id = self.id.as_ref().map(|id| Arc::<str>::from(format!("{id}-more")));
let recipe = self
.recipe_in(&[
(NavigationMenuState::Open, open),
(NavigationMenuState::Current, current),
(NavigationMenuState::Disabled, self.disabled),
])
.item(more_id.as_ref(), NavigationMenuPart::Item);
let label = recipe.part(NavigationMenuPart::Label);
let (press, keys) = (shared.more_open.clone(), shared.more_open.clone());
let mut button = pressable(&recipe.part(NavigationMenuPart::Item), self.disabled)
.align_items(Alignment::Center)
.ref_element(shared.more.clone())
.describe("a11y_role", "button")
.describe("a11y_name", self.more_label.clone())
.describe("a11y_haspopup", "menu")
.describe("a11y_expanded", if open { "true" } else { "false" })
.focus_label(self.more_label.clone())
.on_click(move |_| press.update(|open| *open = !*open))
.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || !plain(&event) || event.key != "ArrowDown" {
return;
}
event.prevent_default();
if !keys.get_untracked() {
keys.set(true);
}
})
.child(Row::new().part(&label).child(label.text(&self.more_label).nowrap()))
.child(glyph(
&recipe.part(NavigationMenuPart::Chevron),
Name::new(if open { icons::CHEVRON_UP } else { icons::CHEVRON_DOWN }),
false,
));
if let Some(id) = more_id {
button = button.id(id);
}
let mut menu = Menu::new(shared.more_open.clone(), shared.more.clone())
.label(&self.more_label)
.placement(Placement::BottomEnd);
if let Some(id) = &self.id {
menu = menu.id(format!("{id}-more-menu"));
}
let mut any = false;
for (index, item) in self.items.iter().enumerate().filter(|(index, _)| went(index)) {
let disabled = self.is_disabled(index);
match &item.panel {
None => {
menu = menu.item(
Self::more_item(
&item.label,
item.icon,
disabled,
self.item_id(index),
self.chosen(&item.on_select, item.href.as_ref()),
)
.checked(item.current),
);
}
Some(panel) => {
if any {
menu = menu.separator();
}
menu = menu.heading(&item.label);
for (at, link) in panel.links.iter().enumerate() {
let id = link
.id
.clone()
.or_else(|| self.id.as_ref().map(|id| Arc::from(format!("{id}-{index}-{at}"))));
menu = menu.item(
Self::more_item(
&link.title,
link.icon,
disabled || link.disabled,
id,
self.chosen(&link.on_select, link.href.as_ref()),
)
.checked(link.current),
);
}
if (index + 1..self.items.len()).any(|next| went(&next) && self.items[next].panel.is_none()) {
menu = menu.separator();
}
}
}
any = true;
}
Some(
Row::new()
.overflow_visible()
.drop_marker(true)
.child(button)
.child(menu.build(self.theme()))
.into(),
)
}
pub fn render(mut self) -> Element {
let mut bar = self.bar();
for index in 0..self.items.len() {
let item = self
.item(index)
.with_children(self.item_icon(index))
.child(self.label(index))
.with_children(self.chevron(index));
let element: Element = match self.panel(index) {
Some(panel) => Row::new().overflow_visible().child(item).child(panel).into(),
None => item.into(),
};
bar = bar.child(self.slot(index, element));
}
bar.with_children(self.more()).into()
}
}
impl crate::ui::Styled for NavigationMenu {
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 NavigationMenu {
const NAME: &'static str = "navigation-menu";
const ROOT: &'static str = "bar";
type Renderer = NavigationMenuRenderer;
fn parts() -> crate::ui::Declared {
NavigationMenuPart::declared()
}
fn states() -> crate::ui::Declared {
NavigationMenuState::declared()
}
fn recipe() -> Recipe {
use NavigationMenuPart::*;
use NavigationMenuState::{Current, Disabled, Open};
use NavigationMenuVariant::Links;
use PaletteColor::{
Border as Edge, Foreground, Highlight, Muted, MutedForeground, Popover as Fill, PopoverForeground,
};
let clear = || Color::new(0, 0, 0, 0);
let links = || Selector::new().variant(Links);
Recipe::new()
.base(Bar, |s| s.gap(4.0))
.base(Item, |s| {
fading(
s.height(36.0)
.padding_x(12.0)
.gap(6.0)
.radius(RadiusSize::Md)
.foreground(Foreground)
.cursor(CursorIcon::Pointer),
)
})
.base(ItemIcon, |s| s.square(IconSize::Md))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
})
.base(Chevron, |s| s.square(IconSize::Sm).foreground(MutedForeground))
.hovered(Item, |s| s.background(Highlight))
.focus_visible(Item, |s| s.background(Highlight))
.state(Open, Item, |s| s.background(Highlight))
.state(Current, Item, |s| s.background(Muted))
.state(Disabled, Item, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.base(Viewport, |s| s.padding_top(6.0))
.base(Panel, |s| {
s.padding_x(8.0)
.padding_y(8.0)
.gap(8.0)
.radius(RadiusSize::Lg)
.background(Fill)
.foreground(PopoverForeground)
.border(Border::inside(BorderSize::Sm, Edge))
.shadow(ShadowStyle::Md)
.enter(PartAnimation::new(FADE_IN, MotionDuration::Base, MotionEasing::Enter))
.exit(PartAnimation::new(FADE_OUT, MotionDuration::Fast, MotionEasing::Exit))
})
.base(Column, |s| s.width(208.0).gap(4.0))
.base(Featured, |s| s.width(208.0).radius(RadiusSize::Md))
.base(Link, |s| {
fading(
s.padding_x(12.0)
.padding_y(12.0)
.gap(12.0)
.radius(RadiusSize::Md)
.cursor(CursorIcon::Pointer),
)
})
.base(LinkIcon, |s| {
s.square(IconSize::Md)
.padding_top(2.0)
.foreground(MutedForeground)
})
.base(LinkText, |s| s.gap(4.0))
.base(LinkTitle, |s| {
s.typography(TypographyStyle::Body)
.font_size(14.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(LinkDescription, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.line_height(1.4)
.foreground(MutedForeground)
})
.hovered(Link, |s| s.background(Highlight))
.focus_visible(Link, |s| s.background(Highlight))
.state(Current, Link, |s| s.background(Muted))
.state(Disabled, Link, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.when(links(), Bar, |s| s.gap(20.0))
.when(links(), Item, |s| {
s.height(32.0)
.padding_x(0.0)
.gap(6.0)
.radius(RadiusSize::Sm)
.foreground(MutedForeground)
})
.when(links().hovered(), Item, |s| s.background(clear()).foreground(Foreground))
.when(links().focus_visible(), Item, |s| {
s.background(clear()).foreground(Foreground).focus_ring()
})
.when(links().state(Open), Item, |s| s.background(clear()).foreground(Foreground))
.when(links().state(Current), Item, |s| s.background(clear()).foreground(Foreground))
.when(links(), Viewport, |s| s.padding_top(18.0))
}
}