use std::{
collections::HashMap,
sync::{
Arc, LazyLock, Mutex, Weak,
atomic::{AtomicBool, Ordering},
},
};
use super::{
menu::{Menu, MenuEntry},
names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{fading, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
events::KeyboardEvent,
theme::{BorderSize, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{self, Column, Row},
core::{ElementRef, Signal, WatchHandle},
layout::{
Alignment,
text_style::{FontWeight, TextUnderline},
},
node::{CursorIcon, Element, FocusGroup, border::Border},
};
fn plain(event: &KeyboardEvent) -> bool {
!event.ctrl && !event.alt && !event.meta
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MenubarPart {
Bar,
Item,
Label,
}
names!(MenubarPart {
Bar => "bar",
Item => "item",
Label => "label",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MenubarState {
Open,
Disabled,
}
names!(MenubarState {
Open => "open",
Disabled => "disabled",
});
pub type MenubarRenderer = Arc<dyn Fn(MenubarView) -> Element + Send + Sync>;
pub struct MenubarMenu {
pub title: Arc<str>,
pub entries: Vec<MenuEntry>,
pub disabled: bool,
pub id: Option<Arc<str>>,
pub key: Option<Arc<str>>,
}
impl MenubarMenu {
pub fn new(title: &str, entries: impl IntoIterator<Item = impl Into<MenuEntry>>) -> Self {
Self {
title: Arc::from(title),
entries: entries.into_iter().map(Into::into).collect(),
disabled: false,
id: None,
key: None,
}
}
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
}
}
pub struct Menubar {
open: Signal<Option<usize>>,
menus: Vec<MenubarMenu>,
disabled: bool,
label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Menubar {
pub fn new(open: Signal<Option<usize>>) -> Self {
Self {
open,
menus: Vec::new(),
disabled: false,
label: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn menu(mut self, menu: MenubarMenu) -> Self {
self.menus.push(menu);
self
}
pub fn menus(mut self, menus: impl IntoIterator<Item = MenubarMenu>) -> Self {
self.menus.extend(menus);
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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(super::PartStyle) -> super::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 case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(MenubarState::Disabled, self.disabled);
let kept = kept(&self.open, self.menus.len());
let open = self.open.get();
let mnemonics =
!self.disabled && (kept.held.get() || (kept.stay.get() && (kept.bar.focus_visible_within() || open.is_some())));
let view = MenubarView {
menus: self.menus,
disabled: self.disabled,
label: self.label,
open: open.filter(|_| !self.disabled),
mnemonics,
recipe: theme
.resolve::<Menubar>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
case,
rules: self.rules,
forced: self.forced,
kept,
id: self.id,
key: self.key,
};
match theme.renderer::<Menubar>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Menubar> for Element {
fn from(bar: Menubar) -> Self {
bar.build(¤t_theme())
}
}
struct Kept {
state: State,
_follows: Vec<WatchHandle<bool>>,
_leads: WatchHandle<Option<usize>>,
alive: Weak<()>,
}
#[derive(Clone)]
struct State {
open: Signal<Option<usize>>,
menus: Arc<Mutex<Vec<(Signal<bool>, ElementRef)>>>,
from_end: Arc<AtomicBool>,
held: Signal<bool>,
stay: Signal<bool>,
alone: Arc<AtomicBool>,
bar: ElementRef,
}
#[derive(Clone)]
struct Shared {
state: State,
alive: Arc<()>,
}
impl std::ops::Deref for Shared {
type Target = State;
fn deref(&self) -> &State {
&self.state
}
}
impl State {
fn menu(&self, index: usize) -> Option<(Signal<bool>, ElementRef)> {
self.menus.lock().unwrap().get(index).cloned()
}
fn open_at(&self, index: usize, from_end: bool) {
self.from_end.store(from_end, Ordering::Relaxed);
if self.open.get_untracked() != Some(index) {
self.open.set(Some(index));
}
}
}
static KEPT: LazyLock<Mutex<HashMap<usize, Kept>>> = LazyLock::new(Default::default);
fn kept(open: &Signal<Option<usize>>, count: usize) -> Shared {
let mut all = KEPT.lock().unwrap();
all.retain(|_, kept| kept.alive.strong_count() > 0);
let held = all
.get(&open.id())
.and_then(|kept| Some((kept.alive.upgrade()?, kept.state.clone())));
let (alive, state) = match held {
Some(held) => held,
None => {
let state = State {
open: open.clone(),
menus: Arc::new(Mutex::new(Vec::new())),
from_end: Arc::new(AtomicBool::new(false)),
held: Signal::new(false),
stay: Signal::new(false),
alone: Arc::new(AtomicBool::new(false)),
bar: ElementRef::new(),
};
let (menus, from_end, app) = (state.menus.clone(), state.from_end.clone(), open.clone());
let leads = open.watch(move || {
let now = app.get_untracked();
if now.is_none() {
from_end.store(false, Ordering::Relaxed);
}
let menus = menus.lock().unwrap().clone();
for (index, (menu, _)) in menus.iter().enumerate() {
let want = now == Some(index);
if menu.get_untracked() != want {
menu.set(want);
}
}
});
let alive = Arc::new(());
all.insert(
open.id(),
Kept {
state: state.clone(),
_follows: Vec::new(),
_leads: leads,
alive: Arc::downgrade(&alive),
},
);
(alive, state)
}
};
let kept = all.get_mut(&open.id()).expect("kept above");
let mut menus = state.menus.lock().unwrap();
while menus.len() < count {
let index = menus.len();
let menu = Signal::new(open.get_untracked() == Some(index));
let (own, app) = (menu.clone(), open.clone());
kept._follows.push(menu.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);
}
}));
menus.push((menu, ElementRef::new()));
}
drop(menus);
Shared { state, alive }
}
pub struct MenubarView {
pub menus: Vec<MenubarMenu>,
pub disabled: bool,
pub label: Option<Arc<str>>,
pub open: Option<usize>,
pub mnemonics: bool,
pub recipe: ResolvedRecipe,
case: Case,
rules: Recipe,
forced: Option<Interaction>,
kept: Shared,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl MenubarView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn entry(&self) -> Option<usize> {
(0..self.menus.len()).find(|&index| !self.is_disabled(index))
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn is_disabled(&self, index: usize) -> bool {
self.disabled || self.menus.get(index).is_some_and(|menu| menu.disabled)
}
pub fn item_part(&self, index: usize, part: impl Into<Name>) -> ResolvedPart {
let case = self
.case
.clone()
.state(MenubarState::Open, self.open == Some(index))
.state(MenubarState::Disabled, self.is_disabled(index));
self
.theme()
.resolve::<Menubar>(&case, Some(&self.rules))
.owned_like(&self.recipe)
.item(
self.menus.get(index).and_then(|menu| menu.id.as_ref()),
MenubarPart::Item,
)
.part(part)
.forced(self.forced.filter(|_| self.entry() == Some(index)))
}
fn anchor(&self, index: usize) -> ElementRef {
self.kept.menu(index).map_or_else(ElementRef::new, |(_, anchor)| anchor)
}
pub fn bar(&self) -> Row {
let mut bar = Row::new()
.align_items(Alignment::Center)
.part(&self.part(MenubarPart::Bar))
.ref_element(self.kept.bar.clone())
.focus_group(
FocusGroup::horizontal()
.one_stop(true)
.typeahead(true)
.follow_pointer(true)
.menu_row(true),
)
.describe("a11y_role", "menubar");
if let Some(label) = &self.label {
bar = bar.describe("a11y_name", label.clone());
}
{
let (down, up) = (self.kept.clone(), self.kept.clone());
bar = bar
.on_key_down(move |event: KeyboardEvent| {
let kept = &down;
if event.key == "Alt" && !event.ctrl && !event.meta {
kept.alone.store(true, Ordering::Relaxed);
if !kept.held.get_untracked() {
kept.held.set(true);
}
} else {
kept.alone.store(false, Ordering::Relaxed);
if !event.focus_within && kept.open.get_untracked().is_none() && kept.stay.get_untracked() {
kept.stay.set(false);
}
}
})
.on_key_up(move |event: KeyboardEvent| {
let kept = &up;
if event.key != "Alt" {
return;
}
if kept.held.get_untracked() {
kept.held.set(false);
}
if kept.alone.swap(false, Ordering::Relaxed) && !kept.stay.get_untracked() {
kept.stay.set(true);
}
});
}
if let Some(id) = &self.id {
bar = bar.id(id.clone());
}
if let Some(key) = &self.key {
bar = bar.key(key.clone());
}
bar
}
pub fn item(&self, index: usize) -> components::Button {
let Some(menu) = self.menus.get(index) else {
return components::Button::empty();
};
let disabled = self.is_disabled(index);
let open = self.open == Some(index);
let mut title = pressable(&self.item_part(index, MenubarPart::Item), disabled)
.ref_element(self.anchor(index))
.describe("a11y_role", "menuitem")
.describe("a11y_name", menu.title.clone())
.describe("a11y_haspopup", "menu")
.describe("a11y_expanded", if open { "true" } else { "false" })
.focus_label(menu.title.clone());
if !disabled {
let (press, enter, keys) = (self.kept.clone(), self.kept.clone(), self.kept.clone());
title = title
.on_click(move |_| {
let _alive = &press.alive;
if press.open.get_untracked() == Some(index) {
press.open.set(None);
} else {
press.open_at(index, false);
}
})
.on_mouse_enter(move || {
if enter.open.get_untracked().is_some_and(|open| open != index) {
enter.open_at(index, false);
}
})
.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || !plain(&event) {
return;
}
let from_end = match event.key.as_str() {
"ArrowDown" => false,
"ArrowUp" => true,
_ => return,
};
event.prevent_default();
keys.open_at(index, from_end);
});
}
match (&menu.id, &self.id) {
(Some(id), _) => title = title.id(id.clone()),
(None, Some(id)) => title = title.id(format!("{id}-{index}")),
(None, None) => {}
}
if let Some(key) = &menu.key {
title = title.key(key.clone());
}
title
}
pub fn label(&self, index: usize) -> Element {
let part = self.item_part(index, MenubarPart::Label);
let title = self.menus.get(index).map(|menu| menu.title.clone()).unwrap_or_default();
let mut letters = title.chars();
let first = letters.next();
let row = Row::new().part(&part);
match first {
Some(first) if self.mnemonics && !self.is_disabled(index) => row
.child(
part
.text(&first.to_string())
.nowrap()
.underline(TextUnderline::default()),
)
.child(part.text(letters.as_str()).nowrap())
.into(),
_ => row.child(part.text(&title).nowrap()).into(),
}
}
pub fn menu(&mut self, index: usize) -> Element {
let Some((signal, anchor)) = self.kept.menu(index) else {
return Row::new().into();
};
let Some(menu) = self.menus.get_mut(index) else {
return Row::new().into();
};
let entries = std::mem::take(&mut menu.entries);
let last = (self.open == Some(index) && self.kept.from_end.load(Ordering::Relaxed))
.then(|| {
entries
.iter()
.rposition(|entry| matches!(entry, MenuEntry::Item(item) if !item.is_disabled()))
})
.flatten();
let mut built = Menu::new(signal, anchor);
for (at, entry) in entries.into_iter().enumerate() {
built = match entry {
MenuEntry::Item(item) => built.item(item.autofocus(Some(at) == last)),
MenuEntry::Separator => built.separator(),
MenuEntry::Heading(heading) => built.heading(&heading),
};
}
let titled = self.menus.get(index).map(|menu| menu.title.clone());
if let Some(title) = titled {
built = built.label(&title);
}
match (self.menus.get(index).and_then(|menu| menu.id.clone()), &self.id) {
(Some(id), _) => built = built.id(format!("{id}-menu")),
(None, Some(id)) => built = built.id(format!("{id}-{index}-menu")),
(None, None) => {}
}
built.build(self.theme())
}
pub fn render(mut self) -> Element {
let mut bar = self.bar();
for index in 0..self.menus.len() {
let title = self.item(index).child(self.label(index));
let menu = self.menu(index);
bar = bar.child(Column::new().child(title).child(menu));
}
bar.into()
}
}
impl crate::ui::Styled for Menubar {
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 Menubar {
const NAME: &'static str = "menubar";
const ROOT: &'static str = "bar";
type Renderer = MenubarRenderer;
fn parts() -> crate::ui::Declared {
MenubarPart::declared()
}
fn states() -> crate::ui::Declared {
MenubarState::declared()
}
fn recipe() -> Recipe {
use MenubarPart::{Bar, Item, Label};
use PaletteColor::{Background, Foreground, Highlight};
Recipe::new()
.base(Bar, |s| {
s.height(36.0)
.padding_x(4.0)
.padding_y(4.0)
.gap(2.0)
.radius(RadiusSize::Md)
.background(Background)
.border(Border::inside(BorderSize::Sm, PaletteColor::Border))
})
.base(Item, |s| {
fading(
s.height(28.0)
.padding_x(10.0)
.radius(RadiusSize::Sm)
.cursor(CursorIcon::Pointer),
)
})
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.hovered(Item, |s| s.background(Highlight))
.focus_visible(Item, |s| s.background(Highlight))
.state(MenubarState::Open, Item, |s| s.background(Highlight))
.state(MenubarState::Disabled, Item, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
}
}