use arc_motion::{
CubicBezier, ScalarTween, TweenEase, is_reduced_motion, motion_now,
path::{PathPoint, PolylinePath},
};
use arc_tokens::ActiveArcTheme as _;
use gpui_kit::{
App, ElementId, FocusHandle, Hsla, IntoElement, ParentElement, RenderOnce, Role, SharedString,
Styled, TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, div,
point, prelude::*, px, svg,
};
use std::{cell::RefCell, collections::BTreeSet, rc::Rc};
#[derive(Clone, Debug)]
pub struct BranchedMenuItem {
pub value: SharedString,
pub label: SharedString,
pub icon: Option<IconName>,
pub children: Option<Vec<BranchedMenuItem>>,
}
impl BranchedMenuItem {
pub fn leaf(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
value: value.into(),
label: label.into(),
icon: None,
children: None,
}
}
pub fn section(
label: impl Into<SharedString>,
children: impl IntoIterator<Item = Self>,
) -> Self {
Self {
value: "".into(),
label: label.into(),
icon: None,
children: Some(children.into_iter().collect()),
}
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
fn leaf_value(&self) -> SharedString {
if self.value.is_empty() {
self.label.clone()
} else {
self.value.clone()
}
}
}
#[derive(Clone, Debug)]
pub struct BranchedMenuConfig {
pub color: Option<Hsla>,
pub accent_color: Option<Hsla>,
pub line_color: Option<Hsla>,
pub width: f32,
pub row_height: f32,
pub indent: f32,
pub trunk: f32,
pub radius: f32,
pub line_width: f32,
pub font_size: f32,
pub draw_duration: f32,
pub fold_duration: f32,
}
impl Default for BranchedMenuConfig {
fn default() -> Self {
Self {
color: None,
accent_color: None,
line_color: None,
width: 240.,
row_height: 36.,
indent: 40.,
trunk: 14.,
radius: 10.,
line_width: 1.5,
font_size: 14.,
draw_duration: 400.,
fold_duration: 300.,
}
}
}
impl BranchedMenuConfig {
fn normalized(&self) -> Self {
let mut c = self.clone();
let d = Self::default();
macro_rules! norm {
($f:ident,$lo:expr,$hi:expr) => {
c.$f = if c.$f.is_finite() {
c.$f.clamp($lo, $hi)
} else {
d.$f
};
};
}
norm!(width, 32., 2000.);
norm!(row_height, 12., 160.);
norm!(indent, 12., 300.);
norm!(trunk, 0., 280.);
c.indent = c.indent.max(c.trunk + 8.);
c.trunk = c.trunk.min(c.indent - 8.);
norm!(radius, 0., 80.);
c.radius = c
.radius
.min((c.row_height / 2. - 2.).max(0.))
.min((c.indent - 8. - c.trunk).max(0.));
norm!(line_width, 0.1, 12.);
norm!(font_size, 8., 60.);
norm!(draw_duration, 0., 5000.);
norm!(fold_duration, 0., 5000.);
c
}
}
#[derive(Clone, Debug)]
pub struct BranchedMenuSelection {
pub value: SharedString,
pub item: BranchedMenuItem,
}
#[derive(Clone, Copy, Debug)]
pub struct BranchedMenuToggle {
pub index: usize,
pub open: bool,
}
type SelectHandler = Rc<dyn Fn(&BranchedMenuSelection, &mut Window, &mut App)>;
type ToggleHandler = Rc<dyn Fn(&BranchedMenuToggle, &mut Window, &mut App)>;
struct SectionMotion {
fold: ScalarTween,
lines: ScalarTween,
reaches: Vec<ScalarTween>,
}
struct State {
open: BTreeSet<usize>,
active: SharedString,
shape: Vec<(SharedString, Option<Vec<SharedString>>)>,
motion: Vec<SectionMotion>,
focus: Vec<Vec<FocusHandle>>,
marker: ScalarTween,
marker_alpha: ScalarTween,
marker_section: Option<usize>,
measured_width: f32,
}
fn curve() -> TweenEase {
TweenEase::CubicBezier(CubicBezier::new(0.23, 1., 0.32, 1.))
}
fn initial_active(items: &[BranchedMenuItem], open: &BTreeSet<usize>) -> SharedString {
items
.iter()
.enumerate()
.find_map(|(i, item)| {
if open.contains(&i) {
item.children
.as_ref()
.and_then(|v| v.first())
.map(|v| v.value.clone())
} else {
None
}
})
.unwrap_or_default()
}
fn reach(c: &BranchedMenuConfig, k: usize, full: bool) -> PolylinePath {
let y = 6. + k as f32 * c.row_height + c.row_height / 2.;
let r = c.radius;
let mut pts = vec![PathPoint::new(c.trunk, if full { 0. } else { y - r })];
pts.push(PathPoint::new(c.trunk, y - r));
for j in 1..=24 {
let a = j as f32 / 24. * std::f32::consts::FRAC_PI_2;
pts.push(PathPoint::new(
c.trunk + r - r * a.cos(),
y - r + r * a.sin(),
));
}
pts.push(PathPoint::new(c.indent - 8., y));
PolylinePath::new(pts)
}
fn paint_path(
path: &PolylinePath,
origin: gpui_kit::Point<gpui_kit::Pixels>,
width: f32,
color: Hsla,
window: &mut Window,
) {
if let Some(builder) = path.to_stroke_builder(origin.x, origin.y, px(width))
&& let Ok(p) = builder.build()
{
window.paint_path(p, color);
}
for p in [path.points.first(), path.points.last()]
.into_iter()
.flatten()
{
window.paint_quad(
gpui_kit::fill(
gpui_kit::Bounds::new(
origin + point(px(p.x - width / 2.), px(p.y - width / 2.)),
gpui_kit::size(px(width), px(width)),
),
color,
)
.corner_radii(px(width / 2.)),
);
}
}
#[derive(IntoElement)]
pub struct BranchedMenu {
id: ElementId,
items: Vec<BranchedMenuItem>,
config: BranchedMenuConfig,
default_open: Vec<usize>,
default_active: SharedString,
open: Option<Vec<usize>>,
active: Option<SharedString>,
on_select: Option<SelectHandler>,
on_toggle: Option<ToggleHandler>,
}
impl BranchedMenu {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
items: default_items(),
config: Default::default(),
default_open: vec![0],
default_active: "".into(),
open: None,
active: None,
on_select: None,
on_toggle: None,
}
}
pub fn items(mut self, items: impl IntoIterator<Item = BranchedMenuItem>) -> Self {
self.items = items.into_iter().collect();
self
}
pub fn config(mut self, c: BranchedMenuConfig) -> Self {
self.config = c;
self
}
pub fn default_open(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
self.default_open = indices.into_iter().collect();
self
}
pub fn default_active(mut self, value: impl Into<SharedString>) -> Self {
self.default_active = value.into();
self
}
pub fn open(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
self.open = Some(indices.into_iter().collect());
self
}
pub fn active(mut self, value: impl Into<SharedString>) -> Self {
self.active = Some(value.into());
self
}
pub fn on_select(
mut self,
cb: impl Fn(&BranchedMenuSelection, &mut Window, &mut App) + 'static,
) -> Self {
self.on_select = Some(Rc::new(cb));
self
}
pub fn on_toggle(
mut self,
cb: impl Fn(&BranchedMenuToggle, &mut Window, &mut App) + 'static,
) -> Self {
self.on_toggle = Some(Rc::new(cb));
self
}
}
pub fn default_items() -> Vec<BranchedMenuItem> {
vec![
BranchedMenuItem::section(
"Getting started",
[
BranchedMenuItem::leaf("install", "Installation"),
BranchedMenuItem::leaf("quick", "Quick start"),
BranchedMenuItem::leaf("config", "Configuration"),
BranchedMenuItem::leaf("theming", "Theming"),
],
),
BranchedMenuItem::section(
"Components",
[
BranchedMenuItem::leaf("buttons", "Buttons"),
BranchedMenuItem::leaf("typography", "Typography"),
BranchedMenuItem::leaf("overlays", "Overlays"),
BranchedMenuItem::leaf("toasts", "Toasts"),
],
),
]
}
impl RenderOnce for BranchedMenu {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let c = self.config.normalized();
let now = motion_now(cx);
let reduced = is_reduced_motion(cx);
let colors = cx.arc_theme().colors;
let ink = c.color.unwrap_or(colors.foreground);
let accent = c.accent_color.unwrap_or(ink);
let line = c.line_color.unwrap_or(colors.border_strong);
let state = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "state".into()),
cx,
|_, _| {
let open = self
.default_open
.iter()
.copied()
.filter(|&i| self.items.get(i).is_some_and(|v| v.children.is_some()))
.collect();
let active = if self.default_active.is_empty() {
initial_active(&self.items, &open)
} else {
self.default_active.clone()
};
Rc::new(RefCell::new(State {
open,
active,
shape: Vec::new(),
motion: Vec::new(),
focus: Vec::new(),
marker: ScalarTween::new(0.),
marker_alpha: ScalarTween::new(0.),
marker_section: None,
measured_width: c.width,
}))
},
)
.read(cx)
.clone();
let mut s = state.borrow_mut();
if let Some(open) = &self.open {
s.open = open.iter().copied().collect();
}
if let Some(active) = &self.active {
s.active = active.clone();
}
s.open
.retain(|&i| self.items.get(i).is_some_and(|v| v.children.is_some()));
let shape = self
.items
.iter()
.map(|v| {
(
v.leaf_value(),
v.children
.as_ref()
.map(|v| v.iter().map(|v| v.value.clone()).collect()),
)
})
.collect::<Vec<_>>();
if s.shape != shape {
s.motion = self
.items
.iter()
.enumerate()
.map(|(i, item)| {
let open = s.open.contains(&i);
SectionMotion {
fold: ScalarTween::new(if open { 1. } else { 0. }),
lines: ScalarTween::new(if open { 1. } else { 0. }),
reaches: item
.children
.iter()
.flatten()
.map(|v| ScalarTween::new(if v.value == s.active { 1. } else { 0. }))
.collect(),
}
})
.collect();
s.focus = self
.items
.iter()
.map(|v| {
(0..1 + v.children.as_ref().map_or(0, Vec::len))
.map(|_| cx.focus_handle().tab_index(0).tab_stop(true))
.collect()
})
.collect();
s.shape = shape;
}
let active_section = self.items.iter().position(|item| {
item.children
.as_ref()
.is_some_and(|v| v.iter().any(|v| v.value == s.active))
});
let header_h = (c.font_size + 1.) * 1.2 + 18.;
let mut y = 0.;
let mut marker_y = 0.;
let active = s.active.clone();
let open = s.open.clone();
let mut moving = false;
for (i, item) in self.items.iter().enumerate() {
let on = open.contains(&i);
let m = &mut s.motion[i];
m.fold.retarget(
if on { 1. } else { 0. },
now,
c.fold_duration / 1000.,
0.,
curve(),
reduced,
);
m.lines.retarget(
if on { 1. } else { 0. },
now,
if on { 0.25 } else { 0.2 },
if on { 0.1 } else { 0. },
TweenEase::CubicBezier(CubicBezier::new(0.25, 0.1, 0.25, 1.)),
reduced,
);
for (k, kid) in item.children.iter().flatten().enumerate() {
m.reaches[k].retarget(
if kid.value == active { 1. } else { 0. },
now,
c.draw_duration / 1000.,
0.,
curve(),
reduced,
);
}
moving |= !m.fold.settled(now)
|| !m.lines.settled(now)
|| m.reaches.iter().any(|v| !v.settled(now));
if active_section == Some(i) {
marker_y = y + (header_h - 16.) / 2.;
}
y += header_h
+ item
.children
.as_ref()
.map_or(0., |v| 12. + v.len() as f32 * c.row_height)
* m.fold.sample(now);
}
let shown = active_section.is_some_and(|i| open.contains(&i));
if active_section == s.marker_section && (s.marker.target() - marker_y).abs() > 0.01 {
s.marker = ScalarTween::new(marker_y);
} else {
s.marker.retarget(marker_y, now, 0.22, 0., curve(), reduced);
s.marker_section = active_section;
}
s.marker_alpha.retarget(
if shown { 1. } else { 0. },
now,
0.15,
0.,
TweenEase::CubicBezier(CubicBezier::new(0.25, 0.1, 0.25, 1.)),
reduced,
);
moving |= !s.marker.settled(now) || !s.marker_alpha.settled(now);
let marker = (s.marker.sample(now), s.marker_alpha.sample(now));
let family = window.text_style().font_family.clone();
let mut width: f32 = 14.;
for item in &self.items {
let measure = |label: &str, size: f32| {
cx.svg_renderer()
.measure_text_width(
label,
&gpui_kit::SvgTextFont {
family: &family,
size,
weight: "500",
style: "normal",
},
)
.unwrap_or(size * label.chars().count() as f32 * 0.6)
};
width = width.max(14. + measure(&item.label, c.font_size + 1.));
for kid in item.children.iter().flatten() {
width = width.max(
14. + c.indent
+ measure(&kid.label, c.font_size)
+ if kid.icon.is_some() { 24. } else { 0. },
);
}
}
s.measured_width = width.min(c.width);
let width = s.measured_width;
let focus = s.focus.clone();
for (i, handles) in focus.iter().enumerate() {
let on = open.contains(&i);
for handle in handles.iter().skip(1) {
let _ = handle.clone().tab_stop(on);
}
if !on && handles.iter().skip(1).any(|h| h.is_focused(window)) {
window.focus(&handles[0], cx);
}
}
let samples = s
.motion
.iter()
.map(|m| {
(
m.fold.sample(now),
m.lines.sample(now),
m.reaches.iter().map(|v| v.sample(now)).collect::<Vec<_>>(),
)
})
.collect::<Vec<_>>();
drop(s);
if moving {
window.request_animation_frame();
}
let mut root = div()
.id(self.id.clone())
.test_support()
.role(Role::Navigation)
.aria_label("Branched menu")
.relative()
.w(px(width))
.max_w_full()
.min_w_0()
.pl(px(14.))
.flex()
.flex_col()
.text_size(px(c.font_size))
.text_color(ink);
root = root.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
let h = bounds.size.height.as_f32();
if h > 8. {
window.paint_quad(gpui_kit::fill(
gpui_kit::Bounds::new(
bounds.origin + point(px(0.), px(8.)),
gpui_kit::size(px(2.), px(h - 8.)),
),
gpui_kit::linear_gradient(
180.,
gpui_kit::linear_color_stop(line, 0.55),
gpui_kit::linear_color_stop(line.opacity(0.), 1.),
),
));
}
window.paint_quad(
gpui_kit::fill(
gpui_kit::Bounds::new(
bounds.origin + point(px(0.), px(marker.0)),
gpui_kit::size(px(2.), px(16.)),
),
accent.opacity(marker.1),
)
.corner_radii(px(1.)),
);
},
)
.absolute()
.inset_0(),
);
for (i, item) in self.items.iter().enumerate() {
let on = open.contains(&i);
let is_section = item.children.is_some();
let head_active = !is_section && item.leaf_value() == active;
let st = state.clone();
let cb = self.on_toggle.clone();
let select = self.on_select.clone();
let controlled_open = self.open.is_some();
let controlled_active = self.active.is_some();
let entry = item.clone();
let handles = focus[i].clone();
let head_focus = focus[i][0].clone();
let mouse_focus = head_focus.clone();
let mut head = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("head-{i}").into(),
))
.test_support()
.role(Role::Button)
.aria_label(item.label.clone())
.track_focus(&head_focus)
.tab_stop(true)
.tab_index(0)
.h(px(header_h))
.flex_shrink_0()
.flex()
.items_center()
.cursor_pointer()
.text_size(px(c.font_size + 1.))
.font_medium()
.text_color(if on || head_active {
ink
} else {
ink.opacity(0.55)
})
.hover(move |style| style.text_color(ink))
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
window.focus(&mouse_focus, cx)
})
.on_click(move |_, window, cx| {
if is_section {
let next = !st.borrow().open.contains(&i);
if !next && handles.iter().skip(1).any(|h| h.is_focused(window)) {
window.focus(&handles[0], cx);
}
if !controlled_open {
if next {
st.borrow_mut().open.insert(i);
} else {
st.borrow_mut().open.remove(&i);
}
}
if let Some(cb) = &cb {
cb(
&BranchedMenuToggle {
index: i,
open: next,
},
window,
cx,
);
}
} else {
let value = entry.leaf_value();
if !controlled_active {
st.borrow_mut().active = value.clone();
}
if let Some(cb) = &select {
cb(
&BranchedMenuSelection {
value,
item: entry.clone(),
},
window,
cx,
);
}
}
window.refresh();
})
.child(item.label.clone());
if is_section {
head = head.aria_expanded(on);
} else {
head = head.aria_selected(head_active);
}
if head_focus.is_focused(window) {
head = head
.bg(colors.accent.opacity(0.1))
.border_1()
.border_color(colors.accent);
}
let mut section = div().flex().flex_col().min_w_0().child(head);
if let Some(kids) = &item.children {
let height = 12. + kids.len() as f32 * c.row_height;
let sample = &samples[i];
let reaches = sample.2.clone();
let opacity = sample.1;
let config = c.clone();
let count = kids.len();
let mut body = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("body-{i}").into(),
))
.test_support()
.h(px(height * sample.0))
.flex_shrink_0()
.overflow_hidden()
.relative();
let mut tree = div()
.h(px(height))
.relative()
.pt(px(6.))
.pb(px(6.))
.flex()
.flex_col()
.child(
canvas(
|_, _, _| (),
move |bounds, _, window, _| {
if count == 0 {
return;
}
let trunk_end = 6.
+ (count - 1) as f32 * config.row_height
+ config.row_height / 2.
- config.radius;
paint_path(
&PolylinePath::new(vec![
PathPoint::new(config.trunk, 0.),
PathPoint::new(config.trunk, trunk_end),
]),
bounds.origin,
config.line_width,
line.opacity(opacity),
window,
);
for k in 0..count {
paint_path(
&reach(&config, k, false),
bounds.origin,
config.line_width,
line.opacity(opacity),
window,
);
}
for (k, p) in reaches.iter().enumerate() {
if *p > 0. {
paint_path(
&reach(&config, k, true).slice(0., *p),
bounds.origin,
config.line_width,
accent.opacity(opacity),
window,
);
}
}
},
)
.absolute()
.inset_0(),
);
for (k, kid) in kids.iter().enumerate() {
let f = focus[i][k + 1].clone();
let mf = f.clone();
let selected = kid.value == active;
let st = state.clone();
let cb = self.on_select.clone();
let entry = kid.clone();
let controlled = self.active.is_some();
let mut row = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("item-{i}-{k}").into(),
))
.test_support()
.role(Role::Button)
.aria_label(kid.label.clone())
.aria_selected(selected)
.track_focus(&f)
.tab_stop(on)
.tab_index(0)
.h(px(c.row_height))
.flex_shrink_0()
.pl(px(c.indent))
.flex()
.items_center()
.gap(px(8.))
.overflow_hidden()
.text_color(if selected { accent } else { ink.opacity(0.55) });
if selected {
row = row.font_medium();
}
if on {
row = row
.cursor_pointer()
.hover(move |style| style.text_color(ink))
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
window.focus(&mf, cx)
})
.on_click(move |_, window, cx| {
if !controlled {
st.borrow_mut().active = entry.value.clone();
}
if let Some(cb) = &cb {
cb(
&BranchedMenuSelection {
value: entry.value.clone(),
item: entry.clone(),
},
window,
cx,
);
}
window.refresh();
});
}
if f.is_focused(window) && on {
row = row
.bg(colors.accent.opacity(0.1))
.border_1()
.border_color(colors.accent);
}
if let Some(icon) = kid.icon {
row = row.child(svg().path(icon.path()).size(px(16.)).flex_shrink_0());
}
tree =
tree.child(row.child(div().whitespace_nowrap().child(kid.label.clone())));
}
body = body.child(tree);
section = section.child(body);
}
root = root.child(section);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
struct Host {
config: BranchedMenuConfig,
selected: Vec<SharedString>,
toggles: Vec<(usize, bool)>,
controlled: bool,
empty: bool,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut items = default_items();
items.push(BranchedMenuItem::leaf("about", "About"));
items.push(BranchedMenuItem::section("Empty", []));
let mut menu = BranchedMenu::new("bm-test")
.items(if self.empty { vec![] } else { items })
.config(self.config.clone())
.default_open([0, 1])
.default_active("quick")
.on_select(cx.listener(|this, e: &BranchedMenuSelection, _, cx| {
this.selected.push(e.value.clone());
cx.notify();
}))
.on_toggle(cx.listener(|this, e: &BranchedMenuToggle, _, cx| {
this.toggles.push((e.index, e.open));
cx.notify();
}));
if self.controlled {
menu = menu.open([0]).active("install");
}
div().w(px(300.)).child(menu)
}
}
fn id(v: &str) -> ElementId {
ElementId::NamedChild(ElementId::from("bm-test").into(), v.to_owned().into())
}
#[gpui_kit::test]
fn branched_menu_selection_toggle_keyboard_and_controlled(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
selected: vec![],
toggles: vec![],
controlled: false,
empty: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
assert_eq!(w.find("bm-test").role(), Some(Role::Navigation));
assert!(w.find(id("body-0")).bounds().size.height > px(0.));
assert!(w.find(id("body-1")).bounds().size.height > px(0.));
w.click(id("item-0-0"), cx);
w.render_frame(cx);
assert_eq!(view.read(cx).selected.len(), 1);
w.press("enter", cx);
w.render_frame(cx);
assert_eq!(view.read(cx).selected.len(), 2);
w.press("space", cx);
w.render_frame(cx);
assert_eq!(view.read(cx).selected.len(), 3);
w.click(id("head-0"), cx);
w.render_frame(cx);
assert_eq!(view.read(cx).toggles, vec![(0, false)]);
assert_eq!(w.find(id("body-0")).bounds().size.height, px(0.));
w.click(id("item-1-2"), cx);
w.render_frame(cx);
assert_eq!(view.read(cx).selected.last().unwrap().as_ref(), "overlays");
w.click(id("head-2"), cx);
w.render_frame(cx);
assert_eq!(view.read(cx).selected.last().unwrap().as_ref(), "about");
view.update(cx, |v, cx| {
v.controlled = true;
cx.notify();
});
w.render_frame(cx);
w.click(id("head-0"), cx);
w.render_frame(cx);
assert!(w.find(id("body-0")).bounds().size.height > px(0.));
w.click(id("item-0-1"), cx);
w.render_frame(cx);
assert_eq!(view.read(cx).selected.last().unwrap().as_ref(), "quick");
w.click(id("head-3"), cx);
w.render_frame(cx);
view.update(cx, |v, cx| {
v.empty = true;
cx.notify();
});
w.render_frame(cx);
assert!(w.find("bm-test").bounds().size.width <= px(300.));
});
}
#[gpui_kit::test]
fn branched_menu_folded_children_leave_focus_order(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
});
let (view, cx) = cx.add_window_view(|_, _| Host {
config: Default::default(),
selected: vec![],
toggles: vec![],
controlled: false,
empty: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
w.click(id("head-0"), cx);
w.render_frame(cx);
w.focus_next(cx);
w.render_frame(cx);
});
cx.update(|w, cx| {
w.press("enter", cx);
w.render_frame(cx);
assert_eq!(view.read(cx).toggles, vec![(0, false), (1, false)]);
assert!(view.read(cx).selected.is_empty());
install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
w.render_frame(cx);
});
}
#[test]
fn branched_menu_geometry_and_defaults() {
let c = BranchedMenuConfig::default().normalized();
let p = reach(&c, 2, true);
let y = 6. + 2. * 36. + 18.;
let expected = y - 10. + std::f32::consts::FRAC_PI_2 * 10. + (32. - 14. - 10.);
assert!((p.total_length() - expected).abs() < 0.01);
assert_eq!(p.points.last(), Some(&PathPoint::new(32., y)));
let half = p.slice(0., 0.5);
assert!((half.total_length() - p.total_length() * 0.5).abs() < 0.01);
let items = default_items();
assert_eq!(
initial_active(&items, &BTreeSet::from([1])).as_ref(),
"buttons"
);
assert!(initial_active(&items, &BTreeSet::new()).is_empty());
let bad = BranchedMenuConfig {
radius: 99.,
row_height: 12.,
indent: 12.,
trunk: 88.,
width: f32::NAN,
..c
}
.normalized();
assert_eq!(bad.width, 240.);
assert!(bad.radius <= 4.);
assert!(bad.indent - 8. >= bad.trunk + bad.radius);
}
#[test]
fn branched_menu_interruption_and_reduced() {
let mut t = ScalarTween::new(0.);
t.retarget(1., 0., 0.3, 0., curve(), false);
let p = t.sample(0.1);
assert!(p > 0. && p < 1.);
t.retarget(0., 0.1, 0.3, 0., curve(), false);
assert_eq!(t.sample(0.1), p);
assert_eq!(t.sample(0.5), 0.);
t.retarget(1., 0.5, 0.3, 0., curve(), true);
assert_eq!(t.sample(0.5), 1.);
}
}