1use std::fmt::{self, Debug};
4
5use waft_foundation::{App, DiagnosticsProperty};
6use waft_widgets::{
7 BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
8 WidgetStatePropertyRef,
9};
10
11use crate::menu_style::MenuStyle;
12use crate::theme::Theme;
13
14#[derive(Clone, Default)]
33pub struct MenuThemeData {
34 pub style: Option<MenuStyle>,
39
40 pub submenu_icon: Option<WidgetStatePropertyRef<Option<WidgetRef>>>,
47}
48
49impl MenuThemeData {
50 pub fn new() -> MenuThemeData {
52 MenuThemeData::default()
53 }
54
55 pub fn style(mut self, style: MenuStyle) -> MenuThemeData {
57 self.style = Some(style);
58 self
59 }
60
61 pub fn submenu_icon(
63 mut self,
64 submenu_icon: WidgetStatePropertyRef<Option<WidgetRef>>,
65 ) -> MenuThemeData {
66 self.submenu_icon = Some(submenu_icon);
67 self
68 }
69
70 pub fn lerp(
72 a: Option<&MenuThemeData>,
73 b: Option<&MenuThemeData>,
74 t: f64,
75 ) -> Option<MenuThemeData> {
76 match (a, b) {
77 (None, None) => return None,
78 (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
79 _ => {}
80 }
81 Some(MenuThemeData {
82 style: MenuStyle::lerp(
83 a.and_then(|a| a.style.as_ref()),
84 b.and_then(|b| b.style.as_ref()),
85 t,
86 ),
87 submenu_icon: if t < 0.5 {
88 a.and_then(|a| a.submenu_icon.clone())
89 } else {
90 b.and_then(|b| b.submenu_icon.clone())
91 },
92 })
93 }
94}
95
96impl PartialEq for MenuThemeData {
97 fn eq(&self, other: &MenuThemeData) -> bool {
98 if std::ptr::eq(self, other) {
99 return true;
100 }
101 other.style == self.style && other.submenu_icon == self.submenu_icon
102 }
103}
104
105impl Debug for MenuThemeData {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 let mut properties = f.debug_struct("MenuThemeData");
108 if let Some(style) = &self.style {
109 properties.field("style", style);
110 }
111 if let Some(submenu_icon) = &self.submenu_icon {
112 properties.field("submenuIcon", submenu_icon);
113 }
114 properties.finish()
115 }
116}
117
118#[derive(Debug)]
136pub struct MenuTheme {
137 pub key: Option<KeyRef>,
138 pub data: MenuThemeData,
141 pub child: WidgetRef,
142}
143
144impl MenuTheme {
145 #[cfg_attr(debug_assertions, track_caller)]
148 pub fn new<K>(data: MenuThemeData, child: impl IntoWidget<K>) -> MenuTheme {
149 MenuTheme {
150 key: None,
151 data,
152 child: child.into_widget(),
153 }
154 }
155
156 pub fn key(mut self, key: KeyRef) -> MenuTheme {
158 self.key = Some(key);
159 self
160 }
161
162 pub fn of(app: &mut App, context: BuildContext) -> MenuThemeData {
172 match context.depend_on_inherited_widget_of_exact_type::<MenuTheme>(app) {
173 Some(menu_theme) => menu_theme.data.clone(),
174 None => Theme::of(app, context).menu_theme.clone(),
175 }
176 }
177}
178
179impl InheritedTheme for MenuTheme {
180 fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
181 MenuTheme::new(self.data.clone(), child).into_widget()
182 }
183}
184
185impl InheritedWidget for MenuTheme {
186 fn key(&self) -> Option<&KeyRef> {
187 self.key.as_ref()
188 }
189
190 fn child(&self) -> &WidgetRef {
191 &self.child
192 }
193
194 fn update_should_notify(&self, old_widget: &MenuTheme) -> bool {
195 self.data != old_widget.data
196 }
197
198 fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
199 Some(self)
200 }
201}
202
203impl waft_foundation::Diagnosticable for MenuThemeData {
204 fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
205 properties.add(
206 DiagnosticsProperty::<MenuStyle>::new("style", self.style.clone()).default_value(None),
207 );
208 properties.add(
209 DiagnosticsProperty::<String>::new(
210 "submenuIcon",
211 self.submenu_icon
212 .as_deref()
213 .map(|property| property.to_string()),
214 )
215 .default_value(None),
216 );
217 }
218}
219
220impl std::fmt::Display for MenuThemeData {
221 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222 f.write_str(&waft_foundation::Diagnosticable::to_string(self))
223 }
224}
225
226#[cfg(test)]
227pub(crate) mod tests {
228 use std::rc::Rc;
229
230 use waft_embedder::{Color, Rect};
231 use waft_painting::{
232 BeveledRectangleBorder, EdgeInsetsGeometry, OutlinedBorderRef, ShapeBorder, StadiumBorder,
233 };
234 use waft_rendering::BoxConstraints;
235 use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
236 use waft_widgets::{
237 Axis, Builder, Column, ConstrainedBox, DefaultTextStyle, Expanded, Icon, Text, WidgetState,
238 WidgetStateProperty, WidgetStatePropertyAll, WidgetStates,
239 };
240
241 use waft_widgets::testing::{
242 Finder, TestPointer, WidgetTester, expect, find, finds_one_widget, test_widgets,
243 };
244
245 use super::*;
246 use crate::button_style::ButtonStyle;
247 use crate::colors::Colors;
248 use crate::icons::Icons;
249 use crate::material::Material;
250 use crate::menu_anchor::{MenuBar, MenuItemButton, MenuPanel, SubmenuButton};
251 use crate::menu_bar_theme::{MenuBarTheme, MenuBarThemeData};
252 use crate::test_support::material_app;
253 use crate::text_button::TextButton;
254 use crate::theme_data::ThemeData;
255 use crate::tooltip::tests::m2;
256
257 pub(crate) mod test_menu {
260 pub(crate) const MAIN_MENU_0: &str = "Menu 0";
261 pub(crate) const MAIN_MENU_1: &str = "Menu 1";
262 pub(crate) const MAIN_MENU_2: &str = "Menu 2";
263 pub(crate) const SUB_MENU_00: &str = "Sub Menu 00";
264 pub(crate) const SUB_MENU_10: &str = "Sub Menu 10";
265 pub(crate) const SUB_MENU_11: &str = "Sub Menu 11";
266 pub(crate) const SUB_MENU_12: &str = "Sub Menu 12";
267 pub(crate) const SUB_MENU_20: &str = "Sub Menu 20";
268 pub(crate) const SUB_SUB_MENU_110: &str = "Sub Sub Menu 110";
269 pub(crate) const SUB_SUB_MENU_111: &str = "Sub Sub Menu 111";
270 pub(crate) const SUB_SUB_MENU_112: &str = "Sub Sub Menu 112";
271 pub(crate) const SUB_SUB_MENU_113: &str = "Sub Sub Menu 113";
272 }
273
274 #[derive(Default)]
276 pub(crate) struct ThemeTestMenus {
277 pub(crate) item_overlay: Option<Color>,
278 pub(crate) item_background: Option<Color>,
279 pub(crate) item_foreground: Option<Color>,
280 pub(crate) item_padding: Option<EdgeInsetsGeometry>,
281 pub(crate) menu_background: Option<Color>,
282 pub(crate) menu_padding: Option<EdgeInsetsGeometry>,
283 pub(crate) menu_shape: Option<OutlinedBorderRef>,
284 pub(crate) menu_elevation: Option<f64>,
285 pub(crate) item_shape: Option<OutlinedBorderRef>,
286 }
287
288 fn all<T: Clone + std::fmt::Debug + PartialEq + 'static>(
289 value: T,
290 ) -> WidgetStatePropertyRef<Option<T>> {
291 Rc::new(WidgetStatePropertyAll::new(Some(value)))
292 }
293
294 pub(crate) fn theme_test_menus(options: ThemeTestMenus) -> Vec<WidgetRef> {
297 use test_menu::*;
298 let mut menu_style = MenuStyle::new();
299 menu_style.padding = options.menu_padding.map(all);
300 menu_style.background_color = options.menu_background.map(all);
301 menu_style.elevation = options.menu_elevation.map(all);
302 menu_style.shape = options.menu_shape.map(all);
303 let mut item_style = ButtonStyle::new();
304 item_style.padding = options.item_padding.map(all);
305 item_style.shape = options.item_shape.map(all);
306 item_style.foreground_color = options.item_foreground.map(all);
307 item_style.background_color = options.item_background.map(all);
308 item_style.overlay_color = options.item_overlay.map(all);
309 let item = |label: &str| {
310 MenuItemButton::new()
311 .on_pressed(waft_foundation::Listener::new(|_app| {}))
312 .child(Text::new(label))
313 .into_widget()
314 };
315 vec![
316 SubmenuButton::new(vec![item(SUB_MENU_00)], Some(Text::new(MAIN_MENU_0))).into_widget(),
317 SubmenuButton::new(
318 vec![
319 MenuItemButton::new()
320 .on_pressed(waft_foundation::Listener::new(|_app| {}))
321 .style(item_style)
322 .child(Text::new(SUB_MENU_10))
323 .into_widget(),
324 SubmenuButton::new(
325 vec![
326 item(SUB_SUB_MENU_110),
327 item(SUB_SUB_MENU_111),
328 item(SUB_SUB_MENU_112),
329 item(SUB_SUB_MENU_113),
330 ],
331 Some(Text::new(SUB_MENU_11)),
332 )
333 .into_widget(),
334 item(SUB_MENU_12),
335 ],
336 Some(Text::new(MAIN_MENU_1)),
337 )
338 .menu_style(menu_style)
339 .into_widget(),
340 SubmenuButton::new(
341 vec![
343 MenuItemButton::new()
344 .child(Text::new(SUB_MENU_20))
345 .into_widget(),
346 ],
347 Some(Text::new(MAIN_MENU_2)),
348 )
349 .into_widget(),
350 ]
351 }
352
353 pub(crate) fn menu_panels(orientation: Axis) -> Finder {
355 find::by_widget_predicate("a _MenuPanel of the orientation", move |_app, widget| {
356 waft_widgets::downcast_widget::<MenuPanel>(widget)
357 .is_some_and(|panel| panel.orientation == orientation)
358 })
359 }
360
361 pub(crate) fn panel_material<R>(
363 tester: &WidgetTester,
364 orientation: Axis,
365 read: impl FnOnce(&Material) -> R,
366 ) -> R {
367 let material = find::descendant(
368 menu_panels(orientation).first(),
369 find::by_type::<Material>(),
370 )
371 .first();
372 tester.widget(material, read)
373 }
374
375 fn shape_is(material: &Material, expected: &dyn ShapeBorder) -> bool {
376 material
377 .shape
378 .as_ref()
379 .is_some_and(|shape| shape.eq_shape(expected))
380 }
381
382 fn pump_themed_bar(
385 tester: &mut WidgetTester,
386 bar_theme: MenuBarThemeData,
387 menu_theme: MenuThemeData,
388 bar: impl Fn() -> WidgetRef + 'static,
389 ) {
390 let root = {
391 let app = tester.cell.borrow();
392 material_app(
393 m2(&app),
394 Material::new()
395 .child(Builder::new(move |_app, _context| {
396 MenuBarTheme::new(
397 bar_theme.clone(),
398 MenuTheme::new(
399 menu_theme.clone(),
400 Column::new().children(vec![
401 bar(),
402 Expanded::new(ConstrainedBox::new(BoxConstraints::expand(
403 None, None,
404 )))
405 .into_widget(),
406 ]),
407 ),
408 )
409 .into_widget()
410 }))
411 .into_widget(),
412 )
413 };
414 tester.pump_widget(root);
415 }
416
417 pub(crate) fn red_stadium_menu_style() -> MenuStyle {
419 MenuStyle::new()
420 .background_color(all(Colors::RED.primary()))
421 .elevation(all(15.0))
422 .shape(all(OutlinedBorderRef::new(StadiumBorder::default())))
423 .padding(all(EdgeInsetsGeometry::directional(10.0, 10.0, 10.0, 10.0)))
424 }
425
426 pub(crate) fn green_menu_style() -> MenuStyle {
428 MenuStyle::new()
429 .background_color(all(Colors::GREEN.primary()))
430 .elevation(all(20.0))
431 }
432
433 pub(crate) fn overriding_bar() -> WidgetRef {
435 MenuBar::new(theme_test_menus(ThemeTestMenus {
436 menu_background: Some(Colors::CYAN.primary()),
437 menu_elevation: Some(18.0),
438 menu_padding: Some(EdgeInsetsGeometry::directional(14.0, 14.0, 14.0, 14.0)),
439 menu_shape: Some(OutlinedBorderRef::new(BeveledRectangleBorder::default())),
440 item_background: Some(Colors::AMBER.primary()),
441 item_foreground: Some(Colors::GREY.primary()),
442 item_overlay: Some(Colors::BLUE_GREY.primary()),
443 item_padding: Some(EdgeInsetsGeometry::directional(11.0, 11.0, 11.0, 11.0)),
444 item_shape: Some(OutlinedBorderRef::new(StadiumBorder::default())),
445 }))
446 .style(
447 MenuStyle::new()
448 .background_color(all(Colors::BLUE.primary()))
449 .elevation(all(10.0))
450 .padding(all(EdgeInsetsGeometry::directional(12.0, 12.0, 12.0, 12.0))),
451 )
452 .into_widget()
453 }
454
455 pub(crate) fn assert_constructor_parameters_override_theme_parameters(tester: &WidgetTester) {
457 use test_menu::*;
458 assert_eq!(
459 tester.get_rect(menu_panels(Axis::Horizontal).first()),
460 Rect::from_ltrb(226.0, 0.0, 574.0, 72.0)
461 );
462 panel_material(tester, Axis::Horizontal, |material| {
463 assert_eq!(material.elevation, 10.0);
464 assert_eq!(material.color, Some(Colors::BLUE.primary()));
465 });
466
467 assert_eq!(
468 tester.get_rect(menu_panels(Axis::Vertical)),
469 Rect::from_ltrb(332.0, 60.0, 574.0, 232.0)
470 );
471 panel_material(tester, Axis::Vertical, |material| {
472 assert_eq!(material.elevation, 18.0);
473 assert_eq!(material.color, Some(Colors::CYAN.primary()));
474 assert!(shape_is(material, &BeveledRectangleBorder::default()));
475 });
476
477 let menu_item = find::descendant(
478 menu_panels(Axis::Vertical).last(),
479 find::by_type::<MenuItemButton>(),
480 )
481 .first();
482 assert_eq!(
483 tester.get_rect(menu_item),
484 Rect::from_ltrb(346.0, 74.0, 560.0, 122.0)
485 );
486 let menu_item_material =
487 find::ancestor(find::text(SUB_MENU_10), find::by_type::<Material>()).first();
488 tester.widget(menu_item_material, |material: &Material| {
489 assert_eq!(material.color, Some(Colors::AMBER.primary()));
490 assert_eq!(material.elevation, 0.0);
491 assert!(shape_is(material, &StadiumBorder::default()));
492 });
493 let label_style =
494 find::ancestor(find::text(SUB_MENU_10), find::by_type::<DefaultTextStyle>()).first();
495 tester.widget(label_style, |style: &DefaultTextStyle| {
496 assert_eq!(style.style.color, Some(Colors::GREY.primary().into()));
497 });
498 let text_button =
499 find::ancestor(find::text(SUB_MENU_10), find::by_type::<TextButton>()).first();
500 let overlay = tester.widget(text_button, |button: &TextButton| {
501 crate::button_style_button::ButtonStyleButton::button_style_button_data(button)
502 .style
503 .as_ref()
504 .and_then(|style| style.overlay_color.clone())
505 });
506 let hovered: WidgetStates = [WidgetState::Hovered].into_iter().collect();
507 assert_eq!(
508 overlay.and_then(|overlay| overlay.resolve(&hovered)),
509 Some(Colors::BLUE_GREY.primary())
510 );
511 }
512
513 #[test]
515 fn a_new_menu_theme_data_sets_nothing() {
516 let menu_theme_data = MenuThemeData::new();
517 assert!(menu_theme_data.style.is_none());
518 assert!(menu_theme_data.submenu_icon.is_none());
519 }
520
521 #[test]
523 fn lerp_of_nothing_is_nothing_and_of_one_theme_with_itself_is_that_theme() {
524 assert!(MenuThemeData::lerp(None, None, 0.0).is_none());
525 let data = MenuThemeData::new();
526 assert_eq!(
527 MenuThemeData::lerp(Some(&data), Some(&data), 0.5),
528 Some(data)
529 );
530 }
531
532 #[test]
534 fn a_menu_theme_styles_the_submenus_and_a_menu_bar_theme_the_bar() {
535 test_widgets(|tester| {
536 pump_themed_bar(
537 tester,
538 MenuBarThemeData::new().style(green_menu_style()),
539 MenuThemeData::new().style(red_stadium_menu_style()),
540 || MenuBar::new(theme_test_menus(ThemeTestMenus::default())).into_widget(),
541 );
542
543 tester.tap(find::text(test_menu::MAIN_MENU_1));
545 tester.pump();
546 assert_eq!(
547 tester.get_rect(menu_panels(Axis::Horizontal).first()),
548 Rect::from_ltrb(234.0, 0.0, 566.0, 48.0)
549 );
550 panel_material(tester, Axis::Horizontal, |material| {
551 assert_eq!(material.elevation, 20.0);
552 assert_eq!(material.color, Some(Colors::GREEN.primary()));
553 });
554
555 assert_eq!(
556 tester.get_rect(menu_panels(Axis::Vertical)),
557 Rect::from_ltrb(336.0, 48.0, 570.0, 212.0)
558 );
559 panel_material(tester, Axis::Vertical, |material| {
560 assert_eq!(material.elevation, 15.0);
561 assert_eq!(material.color, Some(Colors::RED.primary()));
562 });
563 });
564 }
565
566 #[test]
568 fn a_menu_bars_and_its_buttons_own_styles_override_the_themes() {
569 test_widgets(|tester| {
570 pump_themed_bar(
571 tester,
572 MenuBarThemeData::new().style(green_menu_style()),
573 MenuThemeData::new().style(red_stadium_menu_style()),
574 overriding_bar,
575 );
576
577 tester.tap(find::text(test_menu::MAIN_MENU_1));
579 tester.pump();
580
581 assert_constructor_parameters_override_theme_parameters(tester);
582 });
583 }
584
585 fn send_arrow_down(tester: &mut WidgetTester) {
587 tester.send_key_event(
588 PhysicalKeyboardKey::ARROW_DOWN,
589 LogicalKeyboardKey::ARROW_DOWN,
590 );
591 }
592
593 #[test]
595 fn a_menu_themes_submenu_icon_resolves_against_the_buttons_states() {
596 test_widgets(|tester| {
597 use test_menu::*;
598 let controller = waft_widgets::MenuController::new(&mut tester.cell.borrow_mut())
599 .into_erased::<waft_widgets::AnyMenuController>();
600 let disabled_icon = Icons::close_fullscreen();
601 let hovered_icon = Icons::ac_unit();
602 let focused_icon = Icons::zoom_out();
603 let default_icon = Icons::minimize();
604 let icons = (
605 disabled_icon.clone(),
606 hovered_icon.clone(),
607 focused_icon.clone(),
608 default_icon.clone(),
609 );
610 let submenu_icon: WidgetStatePropertyRef<Option<WidgetRef>> =
611 <dyn WidgetStateProperty<Option<WidgetRef>>>::resolve_with(move |states| {
612 let (disabled, hovered, focused, default) = icons.clone();
613 if states.contains(&WidgetState::Disabled) {
614 return Some(Icon::new(Some(disabled)).into_widget());
615 }
616 if states.contains(&WidgetState::Hovered) {
617 return Some(Icon::new(Some(hovered)).into_widget());
618 }
619 if states.contains(&WidgetState::Focused) {
620 return Some(Icon::new(Some(focused)).into_widget());
621 }
622 Some(Icon::new(Some(default)).into_widget())
623 });
624
625 let build_menu = |tester: &mut WidgetTester,
626 icon: Option<WidgetStatePropertyRef<Option<WidgetRef>>>,
627 enabled: bool| {
628 let root = {
629 let app = tester.cell.borrow();
630 let mut menu_theme = MenuThemeData::new();
631 menu_theme.submenu_icon = icon;
632 let menu_children = if enabled {
633 vec![
634 MenuItemButton::new()
635 .child(Text::new(MAIN_MENU_0))
636 .into_widget(),
637 ]
638 } else {
639 Vec::new()
640 };
641 material_app(
642 ThemeData::builder().menu_theme(menu_theme).build(&app),
643 Material::new()
644 .child(
645 MenuBar::new(vec![
646 SubmenuButton::new(
647 vec![
648 SubmenuButton::new(
649 menu_children,
650 Some(Text::new(SUB_SUB_MENU_110)),
651 )
652 .into_widget(),
653 ],
654 Some(Text::new(SUB_MENU_00)),
655 )
656 .into_widget(),
657 ])
658 .controller(controller.clone()),
659 )
660 .into_widget(),
661 )
662 };
663 tester.pump_widget(root);
664 };
665
666 build_menu(tester, None, true);
667 tester.tap(find::text(SUB_MENU_00));
668 tester.pump();
669
670 expect(
671 tester,
672 &find::by_icon(&Icons::arrow_right()),
673 finds_one_widget(),
674 );
675
676 controller.close(&mut tester.cell.borrow_mut());
677 tester.pump();
678
679 build_menu(tester, Some(Rc::clone(&submenu_icon)), true);
680 tester.pump_and_settle();
681
682 tester.tap(find::text(SUB_MENU_00));
683 tester.pump();
684 expect(tester, &find::by_icon(&default_icon), finds_one_widget());
685
686 send_arrow_down(tester);
687 tester.pump();
688 expect(tester, &find::by_icon(&focused_icon), finds_one_widget());
689
690 controller.close(&mut tester.cell.borrow_mut());
691 tester.pump();
692
693 tester.tap(find::text(SUB_MENU_00));
694 tester.pump();
695 let at = tester.get_center(find::text(SUB_SUB_MENU_110));
697 let mut mouse = TestPointer::mouse(1, 0);
698 tester.add_pointer(&mut mouse, waft_embedder::Offset::ZERO);
699 tester.move_to(&mut mouse, at, false);
700 tester.pump_and_settle();
701 tester.pump();
702 expect(tester, &find::by_icon(&hovered_icon), finds_one_widget());
703
704 controller.close(&mut tester.cell.borrow_mut());
705 tester.pump();
706
707 build_menu(tester, Some(submenu_icon), false);
708 tester.tap(find::text(SUB_MENU_00));
709 tester.pump();
710 expect(tester, &find::by_icon(&disabled_icon), finds_one_widget());
711 });
712 }
713 #[test]
715 fn a_menu_theme_data_describes_nothing_by_default() {
716 assert_eq!(
717 waft_widgets::testing::describe_properties(|properties| {
718 waft_foundation::Diagnosticable::debug_fill_properties(
719 &MenuThemeData::new(),
720 properties,
721 )
722 }),
723 Vec::<String>::new()
724 );
725 }
726}