//! Menus with submenus: container surface, radius 16, one shadow, rows 36 px with a radius 8 tint. They open by //! growing from 0.92 at the anchor with their rows fading in, submenus open after a 180 ms rest (or at once on click or //! Right), and keyboard works: arrows, Enter, Escape. They stay inside the window, flipping up or left when needed, and //! scroll when longer than it. use crate::app::Act; use crate::fonts; use crate::motion::{spring, spring_from}; use crate::theme::{Theme, alpha}; use crate::tokens::spring::{DEFAULT, EFFECT}; use crate::tokens::{radius, size, space, state, text, time}; use crate::ui::controls::keycap; use crate::widgets::{cr, feel, floating_shadow, icon, icon_filled, line, ring}; use eframe::egui::{self, Align2, Color32, Id, Order, Pos2, Rect, Sense, pos2, vec2}; #[derive(Clone, Debug, Default)] pub struct Item { pub glyph: &'static str, pub label: String, pub keys: String, /// Shown at the right in place of keys (a current value). pub detail: String, pub check: Option, pub act: Option, pub sub: Vec, pub enabled: bool, pub divider: bool, pub heading: bool, } impl Item { pub fn new(glyph: &'static str, label: impl Into, act: Act) -> Item { Item { glyph, label: label.into(), act: Some(act), enabled: true, ..Item::default() } } pub fn sub(glyph: &'static str, label: impl Into, sub: Vec) -> Item { let enabled = !sub.is_empty(); Item { glyph, label: label.into(), sub, enabled, ..Item::default() } } pub fn divider() -> Item { Item { divider: true, ..Item::default() } } pub fn heading(label: impl Into) -> Item { Item { heading: true, label: label.into(), ..Item::default() } } pub fn keys(mut self, k: &str) -> Item { self.keys = k.into(); self } pub fn detail(mut self, d: impl Into) -> Item { self.detail = d.into(); self } pub fn check(mut self, on: bool) -> Item { self.check = Some(on); self } pub fn enabled(mut self, on: bool) -> Item { self.enabled = on; self } fn height(&self) -> f32 { if self.divider { space::L + 1.0 } else if self.heading { 32.0 } else { size::ROW + space::XS } } fn clickable(&self) -> bool { !self.divider && !self.heading && self.enabled } } #[derive(Clone, Debug)] pub struct Menu { pub id: Id, pub anchor: Pos2, /// Opens above the anchor (for buttons at the bottom of the window). pub above: bool, /// Open submenus: index of the row at each depth. path: Vec, /// Row under the pointer and since when, per depth. rest: Option<(usize, usize, f64)>, focus: Option<(usize, usize)>, scroll: Vec, pub closing: bool, rows: Vec>, frames: Vec, } impl Menu { pub fn new(name: &str, anchor: Pos2, above: bool) -> Menu { Menu { id: Id::new(("menu", name, anchor.x as i32, anchor.y as i32)), anchor, above, path: vec![], rest: None, focus: None, scroll: vec![], closing: false, rows: vec![], frames: vec![] } } /// True if `p` is over any open level. pub fn contains(&self, p: Pos2) -> bool { self.frames.iter().any(|r| r.contains(p)) } } fn level_items<'a>(items: &'a [Item], path: &[usize]) -> Vec<&'a [Item]> { let mut out = vec![items]; let mut cur = items; for &i in path { match cur.get(i) { Some(it) if !it.sub.is_empty() => { cur = &it.sub; out.push(cur); } _ => break, } } out } /// Draws the menu and returns what was chosen. `None` from `open` means it closed by itself (click outside, Escape). pub fn show(ctx: &egui::Context, t: &Theme, m: &mut Menu, items: &[Item], open: &mut bool) -> Option { let screen = ctx.content_rect().shrink(space::S); let now = ctx.input(|i| i.time); let mut chosen = None; // Keep the path valid if the items changed under it. let levels_len = level_items(items, &m.path).len(); m.path.truncate(levels_len - 1); let levels = level_items(items, &m.path); m.rows.resize(levels.len(), vec![]); m.frames.resize(levels.len(), Rect::NOTHING); m.scroll.resize(levels.len(), 0.0); // keyboard if !m.closing { let (up, down, left, right, enter, esc) = ctx.input(|i| { ( i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowLeft), i.key_pressed(egui::Key::ArrowRight), i.key_pressed(egui::Key::Enter) || i.key_pressed(egui::Key::Space), i.key_pressed(egui::Key::Escape), ) }); let depth = levels.len() - 1; let list = levels[depth]; let clickable: Vec = (0..list.len()).filter(|&i| list[i].clickable()).collect(); let cur = m.focus.filter(|f| f.0 == depth).map(|f| f.1); if (up || down) && !clickable.is_empty() { let pos = cur.and_then(|c| clickable.iter().position(|&i| i == c)); let next = match (pos, down) { (None, true) => 0, (None, false) => clickable.len() - 1, (Some(p), true) => (p + 1) % clickable.len(), (Some(p), false) => (p + clickable.len() - 1) % clickable.len(), }; m.focus = Some((depth, clickable[next])); } if right && let Some(c) = cur && !list[c].sub.is_empty() { m.path.push(c); m.focus = list[c].sub.iter().position(|i| i.clickable()).map(|i| (depth + 1, i)); } if (left && depth > 0) || (esc && depth > 0) { let back = m.path.pop(); m.focus = back.map(|b| (depth - 1, b)); } else if esc { m.closing = true; } if enter && let Some(c) = cur { let it = &list[c]; if !it.sub.is_empty() { m.path.push(c); m.focus = it.sub.iter().position(|i| i.clickable()).map(|i| (depth + 1, i)); } else if let Some(a) = &it.act { chosen = Some(a.clone()); m.closing = true; } } } let levels = level_items(items, &m.path); let mut new_path: Option> = None; let mut any_hovered = false; for (d, list) in levels.iter().enumerate() { // size let p = ctx.layer_painter(egui::LayerId::new(Order::Foreground, m.id.with(d))); let mut w: f32 = size::MENU_MIN; for it in list.iter() { if it.divider { continue; } let g = p.layout_no_wrap(it.label.clone(), fonts::ui(text::BODY), t.on_surface); let right = if !it.sub.is_empty() { 28.0 } else { 0.0 } + if it.keys.is_empty() { 0.0 } else { 24.0 * it.keys.split('+').count() as f32 + 12.0 * it.keys.len() as f32 / 2.0 } + if it.detail.is_empty() { 0.0 } else { p.layout_no_wrap(it.detail.clone(), fonts::ui(text::BODY), t.on_variant).size().x + space::M }; w = w.max(space::M + 20.0 + space::M + g.size().x + space::L + right + space::M + 2.0 * space::S); } let w = w.min(size::MENU_MAX + 64.0).min(screen.width()); let content_h: f32 = list.iter().map(|i| i.height()).sum::() + 2.0 * space::S; let h = content_h.min(screen.height()); // place let origin = if d == 0 { m.anchor } else { let parent = m.rows[d - 1].get(m.path[d - 1]).copied().unwrap_or(Rect::from_min_size(m.anchor, vec2(1.0, 1.0))); pos2(parent.right() + space::XS, parent.top() - space::S) }; let mut x = origin.x; let mut y = if d == 0 && m.above { origin.y - h } else { origin.y }; if x + w > screen.right() { x = if d == 0 { (screen.right() - w).max(screen.left()) } else { let parent = m.frames[d - 1]; (parent.left() - w - space::XS).max(screen.left()) }; } if y + h > screen.bottom() { y = if d == 0 && !m.above && origin.y - h > screen.top() { origin.y - h } else { (screen.bottom() - h).max(screen.top()) }; } if y < screen.top() { y = screen.top(); } let frame = Rect::from_min_size(pos2(x, y), vec2(w, h)); m.frames[d] = frame; // open animation: grow from 0.92 at the anchor's side and fade in let key = (m.id, d, m.path.get(..d).map(|p| p.to_vec()).unwrap_or_default()); let grow = spring_from((key.clone(), "grow"), 0.92, if m.closing { 0.96 } else { 1.0 }, DEFAULT); let fade = spring_from((key, "fade"), 0.0, if m.closing { 0.0 } else { 1.0 }, EFFECT).clamp(0.0, 1.0); let pivot = pos2(if x < origin.x - 1.0 { frame.right() } else { frame.left() }, if y < origin.y - 1.0 { frame.bottom() } else { frame.top() }); let shown = Rect::from_min_max(pivot + (frame.min - pivot) * grow, pivot + (frame.max - pivot) * grow); if fade < 0.01 && m.closing { continue; } let area = egui::Area::new(m.id.with(("area", d))).order(Order::Foreground).fixed_pos(frame.min).constrain(false); area.show(ctx, |ui| { ui.set_min_size(frame.size()); let mut p = ui.painter().clone(); p.set_opacity(fade); floating_shadow(&p, shown, cr(radius::L), t.dark); p.rect_filled(shown, cr(radius::L), t.container); let clip = shown.shrink(1.0); let p = p.with_clip_rect(clip); // scroll when longer than the window let overflow = (content_h - h).max(0.0); if overflow > 0.0 && ui.rect_contains_pointer(frame) { let d_y = crate::widgets::wheel(ui).y; m.scroll[d] = (m.scroll[d] - d_y).clamp(0.0, overflow); } let off = spring((m.id, "scroll", d), m.scroll[d], EFFECT); let mut ry = frame.top() + space::S - off; let mut rects = Vec::with_capacity(list.len()); for (i, it) in list.iter().enumerate() { let rh = it.height(); let rr = Rect::from_min_size(pos2(frame.left() + space::S, ry), vec2(w - 2.0 * space::S, rh)); ry += rh; rects.push(rr); if it.divider { p.rect_filled(Rect::from_center_size(rr.center(), vec2(rr.width(), 1.0)), 0.0, t.outline_variant); continue; } if it.heading { p.text(pos2(rr.left() + space::M, rr.center().y + 2.0), Align2::LEFT_CENTER, &it.label, fonts::med(text::LABEL), t.primary); continue; } let row = Rect::from_center_size(rr.center(), vec2(rr.width(), size::ROW)); if !clip.intersects(row) { continue; } let resp = ui.interact(row.intersect(clip), m.id.with(("row", d, i, m.path.get(..d).map(|p| p.to_vec()))), Sense::click()); let live = it.enabled && !m.closing; let f = feel(&resp, live); let open_here = m.path.get(d) == Some(&i); let focused = m.focus == Some((d, i)); let tint = if open_here { state::HOVER.max(f.tint) } else { f.tint }; if tint > 0.001 { p.rect_filled(row, cr(radius::S), alpha(t.on_surface, tint)); } if focused && !resp.hovered() { ring(&p, t, row.shrink(2.0), cr(radius::S)); } let ink = if live { t.on_surface } else { alpha(t.on_surface, state::DISABLED) }; let soft = if live { t.on_variant } else { alpha(t.on_surface, state::DISABLED) }; let mut lx = row.left() + space::M; let ic = pos2(lx + 10.0, row.center().y); match it.check { Some(true) => icon_filled(&p, ic, 20.0, crate::ui::glyphs::CHECK, if live { t.primary } else { ink }), Some(false) if it.glyph.is_empty() => {} _ if !it.glyph.is_empty() => icon(&p, ic, 20.0, it.glyph, soft), _ => {} } lx += 20.0 + space::M; let mut right = row.right() - space::M; if !it.sub.is_empty() { icon(&p, pos2(right - 10.0, row.center().y), 20.0, crate::ui::glyphs::CHEVRON_RIGHT, soft); right -= 20.0 + space::S; } if !it.keys.is_empty() { let kw = keycap(&p, t, pos2(right, row.center().y), &it.keys); right -= kw + space::S; } else if !it.detail.is_empty() { let g = line(&p, &it.detail, fonts::ui(text::BODY), soft, 160.0); p.galley(pos2(right - g.size().x, row.center().y - g.size().y / 2.0), g.clone(), soft); right -= g.size().x + space::M; } let g = line(&p, &it.label, fonts::ui(text::BODY), ink, right - lx); p.galley(pos2(lx, row.center().y - g.size().y / 2.0), g, ink); if !live { continue; } if resp.hovered() { any_hovered = true; m.focus = Some((d, i)); match m.rest { Some((rd, ri, since)) if rd == d && ri == i => { let rested = now - since >= time::SUBMENU; let want: Vec = m.path[..d.min(m.path.len())].iter().copied().chain((!it.sub.is_empty()).then_some(i)).collect(); if rested && want != m.path { new_path = Some(want); } else if !rested { ctx.request_repaint_after(std::time::Duration::from_secs_f64(time::SUBMENU - (now - since) + 0.01)); } } _ => m.rest = Some((d, i, now)), } } if resp.clicked() { if !it.sub.is_empty() { let mut want: Vec = m.path[..d.min(m.path.len())].to_vec(); want.push(i); new_path = Some(want); } else if let Some(a) = &it.act { chosen = Some(a.clone()); m.closing = true; } } } m.rows[d] = rects; let _ = Color32::TRANSPARENT; }); } if let Some(p) = new_path { m.path = p; } if !any_hovered { m.rest = None; } // A click outside every level closes it. let pressed_outside = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !m.frames.iter().any(|f| f.contains(p)))); if pressed_outside && !m.closing { m.closing = true; } if m.closing { let still = spring_from(((m.id, 0usize, Vec::::new()), "fade"), 0.0, 0.0, EFFECT); if still < 0.01 { *open = false; } } chosen }