use std::fmt::{self, Debug};
use waft_foundation::{App, DiagnosticsProperty};
use waft_widgets::{
BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
WidgetStatePropertyRef,
};
use crate::menu_style::MenuStyle;
use crate::theme::Theme;
#[derive(Clone, Default)]
pub struct MenuThemeData {
pub style: Option<MenuStyle>,
pub submenu_icon: Option<WidgetStatePropertyRef<Option<WidgetRef>>>,
}
impl MenuThemeData {
pub fn new() -> MenuThemeData {
MenuThemeData::default()
}
pub fn style(mut self, style: MenuStyle) -> MenuThemeData {
self.style = Some(style);
self
}
pub fn submenu_icon(
mut self,
submenu_icon: WidgetStatePropertyRef<Option<WidgetRef>>,
) -> MenuThemeData {
self.submenu_icon = Some(submenu_icon);
self
}
pub fn lerp(
a: Option<&MenuThemeData>,
b: Option<&MenuThemeData>,
t: f64,
) -> Option<MenuThemeData> {
match (a, b) {
(None, None) => return None,
(Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
_ => {}
}
Some(MenuThemeData {
style: MenuStyle::lerp(
a.and_then(|a| a.style.as_ref()),
b.and_then(|b| b.style.as_ref()),
t,
),
submenu_icon: if t < 0.5 {
a.and_then(|a| a.submenu_icon.clone())
} else {
b.and_then(|b| b.submenu_icon.clone())
},
})
}
}
impl PartialEq for MenuThemeData {
fn eq(&self, other: &MenuThemeData) -> bool {
if std::ptr::eq(self, other) {
return true;
}
other.style == self.style && other.submenu_icon == self.submenu_icon
}
}
impl Debug for MenuThemeData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut properties = f.debug_struct("MenuThemeData");
if let Some(style) = &self.style {
properties.field("style", style);
}
if let Some(submenu_icon) = &self.submenu_icon {
properties.field("submenuIcon", submenu_icon);
}
properties.finish()
}
}
#[derive(Debug)]
pub struct MenuTheme {
pub key: Option<KeyRef>,
pub data: MenuThemeData,
pub child: WidgetRef,
}
impl MenuTheme {
#[cfg_attr(debug_assertions, track_caller)]
pub fn new<K>(data: MenuThemeData, child: impl IntoWidget<K>) -> MenuTheme {
MenuTheme {
key: None,
data,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> MenuTheme {
self.key = Some(key);
self
}
pub fn of(app: &mut App, context: BuildContext) -> MenuThemeData {
match context.depend_on_inherited_widget_of_exact_type::<MenuTheme>(app) {
Some(menu_theme) => menu_theme.data.clone(),
None => Theme::of(app, context).menu_theme.clone(),
}
}
}
impl InheritedTheme for MenuTheme {
fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
MenuTheme::new(self.data.clone(), child).into_widget()
}
}
impl InheritedWidget for MenuTheme {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &MenuTheme) -> bool {
self.data != old_widget.data
}
fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
Some(self)
}
}
impl waft_foundation::Diagnosticable for MenuThemeData {
fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
properties.add(
DiagnosticsProperty::<MenuStyle>::new("style", self.style.clone()).default_value(None),
);
properties.add(
DiagnosticsProperty::<String>::new(
"submenuIcon",
self.submenu_icon
.as_deref()
.map(|property| property.to_string()),
)
.default_value(None),
);
}
}
impl std::fmt::Display for MenuThemeData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&waft_foundation::Diagnosticable::to_string(self))
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::rc::Rc;
use waft_embedder::{Color, Rect};
use waft_painting::{
BeveledRectangleBorder, EdgeInsetsGeometry, OutlinedBorderRef, ShapeBorder, StadiumBorder,
};
use waft_rendering::BoxConstraints;
use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
use waft_widgets::{
Axis, Builder, Column, ConstrainedBox, DefaultTextStyle, Expanded, Icon, Text, WidgetState,
WidgetStateProperty, WidgetStatePropertyAll, WidgetStates,
};
use waft_widgets::testing::{
Finder, TestPointer, WidgetTester, expect, find, finds_one_widget, test_widgets,
};
use super::*;
use crate::button_style::ButtonStyle;
use crate::colors::Colors;
use crate::icons::Icons;
use crate::material::Material;
use crate::menu_anchor::{MenuBar, MenuItemButton, MenuPanel, SubmenuButton};
use crate::menu_bar_theme::{MenuBarTheme, MenuBarThemeData};
use crate::test_support::material_app;
use crate::text_button::TextButton;
use crate::theme_data::ThemeData;
use crate::tooltip::tests::m2;
pub(crate) mod test_menu {
pub(crate) const MAIN_MENU_0: &str = "Menu 0";
pub(crate) const MAIN_MENU_1: &str = "Menu 1";
pub(crate) const MAIN_MENU_2: &str = "Menu 2";
pub(crate) const SUB_MENU_00: &str = "Sub Menu 00";
pub(crate) const SUB_MENU_10: &str = "Sub Menu 10";
pub(crate) const SUB_MENU_11: &str = "Sub Menu 11";
pub(crate) const SUB_MENU_12: &str = "Sub Menu 12";
pub(crate) const SUB_MENU_20: &str = "Sub Menu 20";
pub(crate) const SUB_SUB_MENU_110: &str = "Sub Sub Menu 110";
pub(crate) const SUB_SUB_MENU_111: &str = "Sub Sub Menu 111";
pub(crate) const SUB_SUB_MENU_112: &str = "Sub Sub Menu 112";
pub(crate) const SUB_SUB_MENU_113: &str = "Sub Sub Menu 113";
}
#[derive(Default)]
pub(crate) struct ThemeTestMenus {
pub(crate) item_overlay: Option<Color>,
pub(crate) item_background: Option<Color>,
pub(crate) item_foreground: Option<Color>,
pub(crate) item_padding: Option<EdgeInsetsGeometry>,
pub(crate) menu_background: Option<Color>,
pub(crate) menu_padding: Option<EdgeInsetsGeometry>,
pub(crate) menu_shape: Option<OutlinedBorderRef>,
pub(crate) menu_elevation: Option<f64>,
pub(crate) item_shape: Option<OutlinedBorderRef>,
}
fn all<T: Clone + std::fmt::Debug + PartialEq + 'static>(
value: T,
) -> WidgetStatePropertyRef<Option<T>> {
Rc::new(WidgetStatePropertyAll::new(Some(value)))
}
pub(crate) fn theme_test_menus(options: ThemeTestMenus) -> Vec<WidgetRef> {
use test_menu::*;
let mut menu_style = MenuStyle::new();
menu_style.padding = options.menu_padding.map(all);
menu_style.background_color = options.menu_background.map(all);
menu_style.elevation = options.menu_elevation.map(all);
menu_style.shape = options.menu_shape.map(all);
let mut item_style = ButtonStyle::new();
item_style.padding = options.item_padding.map(all);
item_style.shape = options.item_shape.map(all);
item_style.foreground_color = options.item_foreground.map(all);
item_style.background_color = options.item_background.map(all);
item_style.overlay_color = options.item_overlay.map(all);
let item = |label: &str| {
MenuItemButton::new()
.on_pressed(waft_foundation::Listener::new(|_app| {}))
.child(Text::new(label))
.into_widget()
};
vec![
SubmenuButton::new(vec![item(SUB_MENU_00)], Some(Text::new(MAIN_MENU_0))).into_widget(),
SubmenuButton::new(
vec![
MenuItemButton::new()
.on_pressed(waft_foundation::Listener::new(|_app| {}))
.style(item_style)
.child(Text::new(SUB_MENU_10))
.into_widget(),
SubmenuButton::new(
vec![
item(SUB_SUB_MENU_110),
item(SUB_SUB_MENU_111),
item(SUB_SUB_MENU_112),
item(SUB_SUB_MENU_113),
],
Some(Text::new(SUB_MENU_11)),
)
.into_widget(),
item(SUB_MENU_12),
],
Some(Text::new(MAIN_MENU_1)),
)
.menu_style(menu_style)
.into_widget(),
SubmenuButton::new(
vec![
MenuItemButton::new()
.child(Text::new(SUB_MENU_20))
.into_widget(),
],
Some(Text::new(MAIN_MENU_2)),
)
.into_widget(),
]
}
pub(crate) fn menu_panels(orientation: Axis) -> Finder {
find::by_widget_predicate("a _MenuPanel of the orientation", move |_app, widget| {
waft_widgets::downcast_widget::<MenuPanel>(widget)
.is_some_and(|panel| panel.orientation == orientation)
})
}
pub(crate) fn panel_material<R>(
tester: &WidgetTester,
orientation: Axis,
read: impl FnOnce(&Material) -> R,
) -> R {
let material = find::descendant(
menu_panels(orientation).first(),
find::by_type::<Material>(),
)
.first();
tester.widget(material, read)
}
fn shape_is(material: &Material, expected: &dyn ShapeBorder) -> bool {
material
.shape
.as_ref()
.is_some_and(|shape| shape.eq_shape(expected))
}
fn pump_themed_bar(
tester: &mut WidgetTester,
bar_theme: MenuBarThemeData,
menu_theme: MenuThemeData,
bar: impl Fn() -> WidgetRef + 'static,
) {
let root = {
let app = tester.cell.borrow();
material_app(
m2(&app),
Material::new()
.child(Builder::new(move |_app, _context| {
MenuBarTheme::new(
bar_theme.clone(),
MenuTheme::new(
menu_theme.clone(),
Column::new().children(vec![
bar(),
Expanded::new(ConstrainedBox::new(BoxConstraints::expand(
None, None,
)))
.into_widget(),
]),
),
)
.into_widget()
}))
.into_widget(),
)
};
tester.pump_widget(root);
}
pub(crate) fn red_stadium_menu_style() -> MenuStyle {
MenuStyle::new()
.background_color(all(Colors::RED.primary()))
.elevation(all(15.0))
.shape(all(OutlinedBorderRef::new(StadiumBorder::default())))
.padding(all(EdgeInsetsGeometry::directional(10.0, 10.0, 10.0, 10.0)))
}
pub(crate) fn green_menu_style() -> MenuStyle {
MenuStyle::new()
.background_color(all(Colors::GREEN.primary()))
.elevation(all(20.0))
}
pub(crate) fn overriding_bar() -> WidgetRef {
MenuBar::new(theme_test_menus(ThemeTestMenus {
menu_background: Some(Colors::CYAN.primary()),
menu_elevation: Some(18.0),
menu_padding: Some(EdgeInsetsGeometry::directional(14.0, 14.0, 14.0, 14.0)),
menu_shape: Some(OutlinedBorderRef::new(BeveledRectangleBorder::default())),
item_background: Some(Colors::AMBER.primary()),
item_foreground: Some(Colors::GREY.primary()),
item_overlay: Some(Colors::BLUE_GREY.primary()),
item_padding: Some(EdgeInsetsGeometry::directional(11.0, 11.0, 11.0, 11.0)),
item_shape: Some(OutlinedBorderRef::new(StadiumBorder::default())),
}))
.style(
MenuStyle::new()
.background_color(all(Colors::BLUE.primary()))
.elevation(all(10.0))
.padding(all(EdgeInsetsGeometry::directional(12.0, 12.0, 12.0, 12.0))),
)
.into_widget()
}
pub(crate) fn assert_constructor_parameters_override_theme_parameters(tester: &WidgetTester) {
use test_menu::*;
assert_eq!(
tester.get_rect(menu_panels(Axis::Horizontal).first()),
Rect::from_ltrb(226.0, 0.0, 574.0, 72.0)
);
panel_material(tester, Axis::Horizontal, |material| {
assert_eq!(material.elevation, 10.0);
assert_eq!(material.color, Some(Colors::BLUE.primary()));
});
assert_eq!(
tester.get_rect(menu_panels(Axis::Vertical)),
Rect::from_ltrb(332.0, 60.0, 574.0, 232.0)
);
panel_material(tester, Axis::Vertical, |material| {
assert_eq!(material.elevation, 18.0);
assert_eq!(material.color, Some(Colors::CYAN.primary()));
assert!(shape_is(material, &BeveledRectangleBorder::default()));
});
let menu_item = find::descendant(
menu_panels(Axis::Vertical).last(),
find::by_type::<MenuItemButton>(),
)
.first();
assert_eq!(
tester.get_rect(menu_item),
Rect::from_ltrb(346.0, 74.0, 560.0, 122.0)
);
let menu_item_material =
find::ancestor(find::text(SUB_MENU_10), find::by_type::<Material>()).first();
tester.widget(menu_item_material, |material: &Material| {
assert_eq!(material.color, Some(Colors::AMBER.primary()));
assert_eq!(material.elevation, 0.0);
assert!(shape_is(material, &StadiumBorder::default()));
});
let label_style =
find::ancestor(find::text(SUB_MENU_10), find::by_type::<DefaultTextStyle>()).first();
tester.widget(label_style, |style: &DefaultTextStyle| {
assert_eq!(style.style.color, Some(Colors::GREY.primary().into()));
});
let text_button =
find::ancestor(find::text(SUB_MENU_10), find::by_type::<TextButton>()).first();
let overlay = tester.widget(text_button, |button: &TextButton| {
crate::button_style_button::ButtonStyleButton::button_style_button_data(button)
.style
.as_ref()
.and_then(|style| style.overlay_color.clone())
});
let hovered: WidgetStates = [WidgetState::Hovered].into_iter().collect();
assert_eq!(
overlay.and_then(|overlay| overlay.resolve(&hovered)),
Some(Colors::BLUE_GREY.primary())
);
}
#[test]
fn a_new_menu_theme_data_sets_nothing() {
let menu_theme_data = MenuThemeData::new();
assert!(menu_theme_data.style.is_none());
assert!(menu_theme_data.submenu_icon.is_none());
}
#[test]
fn lerp_of_nothing_is_nothing_and_of_one_theme_with_itself_is_that_theme() {
assert!(MenuThemeData::lerp(None, None, 0.0).is_none());
let data = MenuThemeData::new();
assert_eq!(
MenuThemeData::lerp(Some(&data), Some(&data), 0.5),
Some(data)
);
}
#[test]
fn a_menu_theme_styles_the_submenus_and_a_menu_bar_theme_the_bar() {
test_widgets(|tester| {
pump_themed_bar(
tester,
MenuBarThemeData::new().style(green_menu_style()),
MenuThemeData::new().style(red_stadium_menu_style()),
|| MenuBar::new(theme_test_menus(ThemeTestMenus::default())).into_widget(),
);
tester.tap(find::text(test_menu::MAIN_MENU_1));
tester.pump();
assert_eq!(
tester.get_rect(menu_panels(Axis::Horizontal).first()),
Rect::from_ltrb(234.0, 0.0, 566.0, 48.0)
);
panel_material(tester, Axis::Horizontal, |material| {
assert_eq!(material.elevation, 20.0);
assert_eq!(material.color, Some(Colors::GREEN.primary()));
});
assert_eq!(
tester.get_rect(menu_panels(Axis::Vertical)),
Rect::from_ltrb(336.0, 48.0, 570.0, 212.0)
);
panel_material(tester, Axis::Vertical, |material| {
assert_eq!(material.elevation, 15.0);
assert_eq!(material.color, Some(Colors::RED.primary()));
});
});
}
#[test]
fn a_menu_bars_and_its_buttons_own_styles_override_the_themes() {
test_widgets(|tester| {
pump_themed_bar(
tester,
MenuBarThemeData::new().style(green_menu_style()),
MenuThemeData::new().style(red_stadium_menu_style()),
overriding_bar,
);
tester.tap(find::text(test_menu::MAIN_MENU_1));
tester.pump();
assert_constructor_parameters_override_theme_parameters(tester);
});
}
fn send_arrow_down(tester: &mut WidgetTester) {
tester.send_key_event(
PhysicalKeyboardKey::ARROW_DOWN,
LogicalKeyboardKey::ARROW_DOWN,
);
}
#[test]
fn a_menu_themes_submenu_icon_resolves_against_the_buttons_states() {
test_widgets(|tester| {
use test_menu::*;
let controller = waft_widgets::MenuController::new(&mut tester.cell.borrow_mut())
.into_erased::<waft_widgets::AnyMenuController>();
let disabled_icon = Icons::close_fullscreen();
let hovered_icon = Icons::ac_unit();
let focused_icon = Icons::zoom_out();
let default_icon = Icons::minimize();
let icons = (
disabled_icon.clone(),
hovered_icon.clone(),
focused_icon.clone(),
default_icon.clone(),
);
let submenu_icon: WidgetStatePropertyRef<Option<WidgetRef>> =
<dyn WidgetStateProperty<Option<WidgetRef>>>::resolve_with(move |states| {
let (disabled, hovered, focused, default) = icons.clone();
if states.contains(&WidgetState::Disabled) {
return Some(Icon::new(Some(disabled)).into_widget());
}
if states.contains(&WidgetState::Hovered) {
return Some(Icon::new(Some(hovered)).into_widget());
}
if states.contains(&WidgetState::Focused) {
return Some(Icon::new(Some(focused)).into_widget());
}
Some(Icon::new(Some(default)).into_widget())
});
let build_menu = |tester: &mut WidgetTester,
icon: Option<WidgetStatePropertyRef<Option<WidgetRef>>>,
enabled: bool| {
let root = {
let app = tester.cell.borrow();
let mut menu_theme = MenuThemeData::new();
menu_theme.submenu_icon = icon;
let menu_children = if enabled {
vec![
MenuItemButton::new()
.child(Text::new(MAIN_MENU_0))
.into_widget(),
]
} else {
Vec::new()
};
material_app(
ThemeData::builder().menu_theme(menu_theme).build(&app),
Material::new()
.child(
MenuBar::new(vec![
SubmenuButton::new(
vec![
SubmenuButton::new(
menu_children,
Some(Text::new(SUB_SUB_MENU_110)),
)
.into_widget(),
],
Some(Text::new(SUB_MENU_00)),
)
.into_widget(),
])
.controller(controller.clone()),
)
.into_widget(),
)
};
tester.pump_widget(root);
};
build_menu(tester, None, true);
tester.tap(find::text(SUB_MENU_00));
tester.pump();
expect(
tester,
&find::by_icon(&Icons::arrow_right()),
finds_one_widget(),
);
controller.close(&mut tester.cell.borrow_mut());
tester.pump();
build_menu(tester, Some(Rc::clone(&submenu_icon)), true);
tester.pump_and_settle();
tester.tap(find::text(SUB_MENU_00));
tester.pump();
expect(tester, &find::by_icon(&default_icon), finds_one_widget());
send_arrow_down(tester);
tester.pump();
expect(tester, &find::by_icon(&focused_icon), finds_one_widget());
controller.close(&mut tester.cell.borrow_mut());
tester.pump();
tester.tap(find::text(SUB_MENU_00));
tester.pump();
let at = tester.get_center(find::text(SUB_SUB_MENU_110));
let mut mouse = TestPointer::mouse(1, 0);
tester.add_pointer(&mut mouse, waft_embedder::Offset::ZERO);
tester.move_to(&mut mouse, at, false);
tester.pump_and_settle();
tester.pump();
expect(tester, &find::by_icon(&hovered_icon), finds_one_widget());
controller.close(&mut tester.cell.borrow_mut());
tester.pump();
build_menu(tester, Some(submenu_icon), false);
tester.tap(find::text(SUB_MENU_00));
tester.pump();
expect(tester, &find::by_icon(&disabled_icon), finds_one_widget());
});
}
#[test]
fn a_menu_theme_data_describes_nothing_by_default() {
assert_eq!(
waft_widgets::testing::describe_properties(|properties| {
waft_foundation::Diagnosticable::debug_fill_properties(
&MenuThemeData::new(),
properties,
)
}),
Vec::<String>::new()
);
}
}