1use std::fmt::{self, Debug};
4
5use waft_embedder::Color;
6use waft_foundation::{App, DiagnosticsProperty};
7use waft_painting::{ColorProperty, TextStyle};
8use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
9
10use crate::input_decorator::InputDecorationThemeData;
11use crate::menu_style::MenuStyle;
12use crate::theme::Theme;
13
14#[derive(Clone, Default)]
27pub struct DropdownMenuThemeData {
28 pub text_style: Option<TextStyle>,
30
31 pub input_decoration_theme: Option<InputDecorationThemeData>,
35
36 pub menu_style: Option<MenuStyle>,
40
41 pub disabled_color: Option<Color>,
45}
46
47crate::theme_data_getters::theme_data_getters! {
48 pub trait DropdownMenuThemeDataGetters for DropdownMenuThemeData, fields: dropdown_menu_theme_data {
52 text_style: Option<TextStyle>,
53 input_decoration_theme: Option<InputDecorationThemeData>,
54 menu_style: Option<MenuStyle>,
55 disabled_color: Option<Color>,
56 }
57}
58
59impl DropdownMenuThemeData {
60 pub fn new() -> DropdownMenuThemeData {
63 DropdownMenuThemeData::default()
64 }
65
66 pub fn text_style(mut self, text_style: TextStyle) -> DropdownMenuThemeData {
68 self.text_style = Some(text_style);
69 self
70 }
71
72 pub fn input_decoration_theme(
74 mut self,
75 input_decoration_theme: impl Into<InputDecorationThemeData>,
76 ) -> DropdownMenuThemeData {
77 self.input_decoration_theme = Some(input_decoration_theme.into());
78 self
79 }
80
81 pub fn menu_style(mut self, menu_style: MenuStyle) -> DropdownMenuThemeData {
83 self.menu_style = Some(menu_style);
84 self
85 }
86
87 pub fn disabled_color(mut self, disabled_color: Color) -> DropdownMenuThemeData {
89 self.disabled_color = Some(disabled_color);
90 self
91 }
92
93 pub fn copy_with(&self) -> DropdownMenuThemeData {
95 self.clone()
96 }
97
98 pub fn lerp(
100 a: Option<&DropdownMenuThemeData>,
101 b: Option<&DropdownMenuThemeData>,
102 t: f64,
103 ) -> DropdownMenuThemeData {
104 if let (Some(a), Some(b)) = (a, b)
105 && std::ptr::eq(a, b)
106 {
107 return a.clone();
108 }
109 DropdownMenuThemeData {
110 text_style: TextStyle::lerp(
111 a.and_then(|a| a.text_style.as_ref()),
112 b.and_then(|b| b.text_style.as_ref()),
113 t,
114 ),
115 input_decoration_theme: if t < 0.5 {
116 a.and_then(|a| a.input_decoration_theme.clone())
117 } else {
118 b.and_then(|b| b.input_decoration_theme.clone())
119 },
120 menu_style: MenuStyle::lerp(
121 a.and_then(|a| a.menu_style.as_ref()),
122 b.and_then(|b| b.menu_style.as_ref()),
123 t,
124 ),
125 disabled_color: Color::lerp(
126 a.and_then(|a| a.disabled_color),
127 b.and_then(|b| b.disabled_color),
128 t,
129 ),
130 }
131 }
132}
133
134impl PartialEq for DropdownMenuThemeData {
135 fn eq(&self, other: &DropdownMenuThemeData) -> bool {
136 if std::ptr::eq(self, other) {
137 return true;
138 }
139 other.text_style == self.text_style
140 && other.input_decoration_theme == self.input_decoration_theme
141 && other.menu_style == self.menu_style
142 && other.disabled_color == self.disabled_color
143 }
144}
145
146impl Debug for DropdownMenuThemeData {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 let mut properties = f.debug_struct("DropdownMenuThemeData");
149 if let Some(text_style) = &self.text_style {
150 properties.field("textStyle", text_style);
151 }
152 if self.input_decoration_theme.is_some() {
153 properties.field("inputDecorationThemeData", &"InputDecorationThemeData");
154 }
155 if let Some(menu_style) = &self.menu_style {
156 properties.field("menuStyle", menu_style);
157 }
158 if let Some(disabled_color) = &self.disabled_color {
159 properties.field("disabledColor", disabled_color);
160 }
161 properties.finish()
162 }
163}
164
165#[derive(Debug)]
171pub struct DropdownMenuTheme {
172 pub key: Option<KeyRef>,
173 pub data: DropdownMenuThemeData,
175 pub child: WidgetRef,
176}
177
178impl DropdownMenuTheme {
179 #[cfg_attr(debug_assertions, track_caller)]
182 pub fn new<K>(data: DropdownMenuThemeData, child: impl IntoWidget<K>) -> DropdownMenuTheme {
183 DropdownMenuTheme {
184 key: None,
185 data,
186 child: child.into_widget(),
187 }
188 }
189
190 pub fn key(mut self, key: KeyRef) -> DropdownMenuTheme {
192 self.key = Some(key);
193 self
194 }
195
196 pub fn of(app: &mut App, context: BuildContext) -> DropdownMenuThemeData {
208 DropdownMenuTheme::maybe_of(app, context)
209 .unwrap_or_else(|| Theme::of(app, context).dropdown_menu_theme.clone())
210 }
211
212 pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<DropdownMenuThemeData> {
230 context
231 .depend_on_inherited_widget_of_exact_type::<DropdownMenuTheme>(app)
232 .map(|theme| theme.data.clone())
233 }
234}
235
236impl InheritedTheme for DropdownMenuTheme {
237 fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
238 DropdownMenuTheme::new(self.data.clone(), child).into_widget()
239 }
240}
241
242impl InheritedWidget for DropdownMenuTheme {
243 fn key(&self) -> Option<&KeyRef> {
244 self.key.as_ref()
245 }
246
247 fn child(&self) -> &WidgetRef {
248 &self.child
249 }
250
251 fn update_should_notify(&self, old_widget: &DropdownMenuTheme) -> bool {
252 self.data != old_widget.data
253 }
254
255 fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
256 Some(self)
257 }
258}
259
260impl waft_foundation::Diagnosticable for DropdownMenuThemeData {
261 fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
262 properties.add(
263 DiagnosticsProperty::<TextStyle>::new("textStyle", self.text_style.clone())
264 .default_value(None),
265 );
266 properties.add(
267 DiagnosticsProperty::<InputDecorationThemeData>::new(
268 "inputDecorationThemeData",
269 self.input_decoration_theme.clone(),
270 )
271 .default_value(None),
272 );
273 properties.add(
274 DiagnosticsProperty::<MenuStyle>::new("menuStyle", self.menu_style.clone())
275 .default_value(None),
276 );
277 properties
278 .add(ColorProperty::new("disabledColor", self.disabled_color).default_value(None));
279 }
280}
281
282impl std::fmt::Display for DropdownMenuThemeData {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 f.write_str(&waft_foundation::Diagnosticable::to_string(self))
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use std::rc::Rc;
291
292 use waft_widgets::WidgetStatePropertyAll;
293
294 use waft_widgets::testing::{WidgetTester, expect, find, finds_one_widget, test_widgets};
295
296 use super::*;
297 use crate::colors::Colors;
298 use crate::input_decorator::InputDecorationTheme;
299
300 #[test]
302 fn a_copy_equals_its_original_and_a_copy_with_every_field_equals_a_theme_made_with_them() {
303 assert_eq!(
304 DropdownMenuThemeData::new(),
305 DropdownMenuThemeData::new().copy_with()
306 );
307
308 let custom =
309 DropdownMenuThemeData::new()
310 .menu_style(MenuStyle::new().background_color(Rc::new(
311 WidgetStatePropertyAll::new(Some(Colors::GREEN.primary())),
312 )))
313 .input_decoration_theme(InputDecorationTheme::new().with_filled(true))
314 .text_style(TextStyle::new().font_size(25.0));
315 let copy = DropdownMenuThemeData::new()
316 .copy_with()
317 .menu_style(custom.menu_style.clone().expect("set above"))
318 .input_decoration_theme(custom.input_decoration_theme.clone().expect("set above"))
319 .text_style(custom.text_style.clone().expect("set above"));
320 assert_eq!(copy, custom);
321 }
322
323 #[test]
326 fn lerp_of_nothing_is_the_empty_theme_and_of_one_theme_with_itself_is_that_theme() {
327 assert_eq!(
328 DropdownMenuThemeData::lerp(None, None, 0.0),
329 DropdownMenuThemeData::new()
330 );
331 let data = DropdownMenuThemeData::new();
332 assert_eq!(
333 DropdownMenuThemeData::lerp(Some(&data), Some(&data), 0.5),
334 data
335 );
336 }
337
338 use waft_embedder::{Color, Radius};
341 use waft_painting::{
342 BorderRadiusGeometry, BorderSide, OutlinedBorderRef, RoundedRectangleBorder, Shadow,
343 ShapeBorder, TextDecoration,
344 };
345 use waft_widgets::{AnyElement, EditableText};
346
347 use crate::dropdown_menu::{DropdownMenu, DropdownMenuEntry};
348 use crate::icon_button::IconButton;
349 use crate::icons::Icons;
350 use crate::material::Material;
351 use crate::menu_anchor::{MenuAnchor, MenuItemButton, MenuPanel};
352 use crate::scaffold::Scaffold;
353 use crate::shadows::k_elevation_to_shadow;
354 use crate::test_support::material_app;
355 use crate::text_field::TextField;
356 use crate::theme_data::ThemeData;
357
358 fn entries() -> Vec<DropdownMenuEntry<i32>> {
359 vec![
360 DropdownMenuEntry::new(0, "Item 0"),
361 DropdownMenuEntry::new(1, "Item 1"),
362 DropdownMenuEntry::new(2, "Item 2"),
363 ]
364 }
365
366 fn shadows(elevation: i32) -> Vec<Shadow> {
367 k_elevation_to_shadow(elevation)
368 .expect("a defined elevation")
369 .iter()
370 .copied()
371 .map(Shadow::from)
372 .collect()
373 }
374
375 fn rounded(radius: f64) -> RoundedRectangleBorder {
376 RoundedRectangleBorder::new(
377 BorderSide::NONE,
378 BorderRadiusGeometry::all(Radius::circular(radius)),
379 )
380 }
381
382 fn all<T: Clone + std::fmt::Debug + 'static>(
383 value: T,
384 ) -> Rc<WidgetStatePropertyAll<Option<T>>> {
385 Rc::new(WidgetStatePropertyAll::new(Some(value)))
386 }
387
388 struct Styles {
391 text_style: TextStyle,
392 menu_style: MenuStyle,
393 input_decoration_theme: InputDecorationThemeData,
394 }
395
396 #[derive(Clone)]
398 struct Expected {
399 color: waft_painting::AnyColor,
400 background_color: waft_painting::AnyColor,
401 font_size: f64,
402 elevation_shadows: i32,
403 decoration: TextDecoration,
404 word_spacing: f64,
405 menu_background: Color,
406 menu_shadow: Color,
407 menu_surface_tint: Color,
408 menu_elevation: f64,
409 menu_radius: f64,
410 fill_color: waft_painting::AnyColor,
411 }
412
413 impl Expected {
414 fn styles(&self) -> Styles {
415 let shape: OutlinedBorderRef = OutlinedBorderRef::new(rounded(self.menu_radius));
416 Styles {
417 text_style: TextStyle::new()
418 .color(self.color.clone())
419 .background_color(self.background_color.clone())
420 .font_size(self.font_size)
421 .shadows(shadows(self.elevation_shadows))
422 .decoration(self.decoration)
423 .word_spacing(self.word_spacing),
424 menu_style: MenuStyle::new()
425 .background_color(all(self.menu_background))
426 .shadow_color(all(self.menu_shadow))
427 .surface_tint_color(all(self.menu_surface_tint))
428 .elevation(all(self.menu_elevation))
429 .shape(all(shape)),
430 input_decoration_theme: InputDecorationTheme::new()
431 .with_filled(true)
432 .with_fill_color(self.fill_color.clone())
433 .into(),
434 }
435 }
436
437 fn theme_data(&self) -> DropdownMenuThemeData {
438 let styles = self.styles();
439 DropdownMenuThemeData::new()
440 .text_style(styles.text_style)
441 .menu_style(styles.menu_style)
442 .input_decoration_theme(styles.input_decoration_theme)
443 }
444 }
445
446 fn global() -> Expected {
448 Expected {
449 color: Colors::ORANGE.into(),
450 background_color: Colors::INDIGO.into(),
451 font_size: 30.0,
452 elevation_shadows: 1,
453 decoration: TextDecoration::UNDERLINE,
454 word_spacing: 2.0,
455 menu_background: Colors::GREY.primary(),
456 menu_shadow: Colors::BROWN.primary(),
457 menu_surface_tint: Colors::AMBER_ACCENT.primary(),
458 menu_elevation: 10.0,
459 menu_radius: 10.0,
460 fill_color: Colors::LIGHT_GREEN.into(),
461 }
462 }
463
464 fn local() -> Expected {
466 Expected {
467 color: Colors::RED.into(),
468 background_color: Colors::ORANGE.into(),
469 font_size: 27.0,
470 elevation_shadows: 2,
471 decoration: TextDecoration::LINE_THROUGH,
472 word_spacing: 5.0,
473 menu_background: Colors::YELLOW.primary(),
474 menu_shadow: Colors::GREEN.primary(),
475 menu_surface_tint: Colors::TEAL.primary(),
476 menu_elevation: 15.0,
477 menu_radius: 8.0,
478 fill_color: Colors::BLUE.into(),
479 }
480 }
481
482 fn parameters() -> Expected {
484 Expected {
485 color: Colors::PINK.into(),
486 background_color: Colors::CYAN.into(),
487 font_size: 32.0,
488 elevation_shadows: 3,
489 decoration: TextDecoration::OVERLINE,
490 word_spacing: 3.0,
491 menu_background: Colors::LIME_ACCENT.primary(),
492 menu_shadow: Colors::DEEP_ORANGE_ACCENT.primary(),
493 menu_surface_tint: Colors::LIGHT_BLUE.primary(),
494 menu_elevation: 21.0,
495 menu_radius: 15.0,
496 fill_color: Colors::DEEP_PURPLE.into(),
497 }
498 }
499
500 fn only(found: Vec<AnyElement>) -> AnyElement {
501 assert_eq!(found.len(), 1, "one widget found");
502 found[0]
503 }
504
505 fn arrow_drop_down_button(tester: &WidgetTester) -> AnyElement {
507 let icon = tester.element(find::by_icon(&Icons::arrow_drop_down()).first());
508 tester.ancestor_of_type::<IconButton>(icon)
509 }
510
511 fn menu_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
513 let panel = tester.element(find::by_type::<MenuPanel>());
514 let material = tester.descendants_of_type::<Material>(panel)[0];
515 tester.widget::<Material, R>(material, read)
516 }
517
518 fn button_material<R>(
520 tester: &WidgetTester,
521 label: &str,
522 read: impl FnOnce(&Material) -> R,
523 ) -> R {
524 let text = *find::text(label)
525 .evaluate(tester)
526 .last()
527 .expect("the label");
528 let button = tester.ancestor_of_type::<MenuItemButton>(text);
529 let material = only(tester.descendants_of_type::<Material>(button));
530 tester.widget::<Material, R>(material, read)
531 }
532
533 fn shape_is(material: &Material, expected: &dyn ShapeBorder) -> bool {
534 material
535 .shape
536 .as_ref()
537 .is_some_and(|shape| shape.eq_shape(expected))
538 }
539
540 fn tap(tester: &mut WidgetTester, element: AnyElement) {
541 let render = tester.render_box_of(element);
542 let center = tester.get_rect(render).center();
543 tester.tap_at(center, 1);
544 }
545
546 fn assert_the_menu_shows(tester: &mut WidgetTester, theme: &ThemeData, expected: &Expected) {
548 let editable = tester.element(find::by_type::<EditableText>());
549 tester.widget(editable, |editable: &EditableText| {
550 assert_eq!(editable.style.color, Some(expected.color.clone()));
551 assert_eq!(
552 editable.style.background_color,
553 Some(expected.background_color.clone())
554 );
555 assert_eq!(editable.style.font_size, Some(expected.font_size));
556 assert_eq!(
557 editable.style.shadows,
558 Some(shadows(expected.elevation_shadows))
559 );
560 assert_eq!(editable.style.decoration, Some(expected.decoration));
561 assert_eq!(editable.style.word_spacing, Some(expected.word_spacing));
562 });
563
564 let text_field = tester.element(find::by_type::<TextField>());
565 tester.widget(text_field, |text_field: &TextField| {
566 let decoration = text_field.decoration.as_ref().expect("a decoration");
567 assert_eq!(decoration.filled, Some(true));
568 assert_eq!(decoration.fill_color, Some(expected.fill_color.clone()));
569 });
570
571 let button = arrow_drop_down_button(tester);
572 tap(tester, button);
573 tester.pump_by(std::time::Duration::ZERO);
574 expect(tester, &find::by_type::<MenuAnchor>(), finds_one_widget());
575
576 menu_material(tester, |material| {
577 assert_eq!(material.color, Some(expected.menu_background));
578 assert_eq!(material.shadow_color, Some(expected.menu_shadow));
579 assert_eq!(
580 material.surface_tint_color,
581 Some(expected.menu_surface_tint)
582 );
583 assert_eq!(material.elevation, expected.menu_elevation);
584 assert!(shape_is(material, &rounded(expected.menu_radius)));
585 });
586
587 button_material(tester, "Item 0", |material| {
588 assert_eq!(material.color, Some(Colors::TRANSPARENT));
589 assert_eq!(material.elevation, 0.0);
590 assert!(shape_is(material, &RoundedRectangleBorder::default()));
591 let text_style = material.text_style.as_ref().expect("a text style");
592 assert_eq!(
593 text_style.color,
594 Some(theme.color_scheme.on_surface().into())
595 );
596 });
597 }
598
599 fn centered(menu: DropdownMenu<i32>) -> WidgetRef {
600 Scaffold::new()
601 .body(waft_widgets::Center::new().child(menu))
602 .into_widget()
603 }
604
605 #[test]
607 fn with_no_other_configuration_the_defaults_are_used() {
608 test_widgets(|tester| {
609 let theme = ThemeData::new(&tester.cell.borrow());
610 tester.pump_widget(material_app(
611 theme.clone(),
612 centered(DropdownMenu::new(entries())),
613 ));
614
615 let label_large = theme.text_theme.label_large.clone().expect("a label large");
616 let editable = tester.element(find::by_type::<EditableText>());
617 tester.widget(editable, |editable: &EditableText| {
618 assert_eq!(editable.style.color, label_large.color);
619 assert_eq!(editable.style.background, label_large.background);
620 assert_eq!(editable.style.shadows, label_large.shadows);
621 assert_eq!(editable.style.decoration, label_large.decoration);
622 assert_eq!(editable.style.word_spacing, label_large.word_spacing);
623 });
624
625 let text_field = tester.element(find::by_type::<TextField>());
626 tester.widget(text_field, |text_field: &TextField| {
627 let decoration = text_field.decoration.as_ref().expect("a decoration");
628 assert!(decoration.border.as_ref().is_some_and(|border| {
629 border.eq_shape(&crate::input_border::OutlineInputBorder::new())
630 }));
631 });
632
633 let button = arrow_drop_down_button(tester);
634 tap(tester, button);
635 tester.pump_by(std::time::Duration::ZERO);
636 expect(tester, &find::by_type::<MenuAnchor>(), finds_one_widget());
637
638 menu_material(tester, |material| {
639 assert_eq!(material.color, Some(theme.color_scheme.surface_container()));
640 assert_eq!(material.shadow_color, Some(theme.color_scheme.shadow()));
641 assert_eq!(material.surface_tint_color, Some(Colors::TRANSPARENT));
642 assert_eq!(material.elevation, 3.0);
643 assert!(shape_is(material, &rounded(4.0)));
644 });
645
646 button_material(tester, "Item 0", |material| {
647 assert_eq!(material.color, Some(Colors::TRANSPARENT));
648 assert_eq!(material.elevation, 0.0);
649 assert!(shape_is(material, &RoundedRectangleBorder::default()));
650 let text_style = material.text_style.as_ref().expect("a text style");
651 assert_eq!(
652 text_style.color,
653 Some(theme.color_scheme.on_surface().into())
654 );
655 });
656 });
657 }
658
659 #[test]
661 fn the_theme_data_dropdown_menu_theme_overrides_the_defaults() {
662 test_widgets(|tester| {
663 let expected = global();
664 let theme = ThemeData::builder()
665 .dropdown_menu_theme(expected.theme_data())
666 .build(&tester.cell.borrow());
667 tester.pump_widget(material_app(
668 theme.clone(),
669 centered(DropdownMenu::new(entries())),
670 ));
671 assert_the_menu_shows(tester, &theme, &expected);
672 });
673 }
674
675 #[test]
677 fn a_dropdown_menu_theme_overrides_the_theme_data_and_the_defaults() {
678 test_widgets(|tester| {
679 let expected = local();
680 let theme = ThemeData::builder()
681 .dropdown_menu_theme(global().theme_data())
682 .build(&tester.cell.borrow());
683 tester.pump_widget(material_app(
684 theme.clone(),
685 DropdownMenuTheme::new(
686 expected.theme_data(),
687 centered(DropdownMenu::new(entries())),
688 )
689 .into_widget(),
690 ));
691 assert_the_menu_shows(tester, &theme, &expected);
692 });
693 }
694
695 #[test]
698 fn the_widget_parameters_override_the_themes_and_the_defaults() {
699 test_widgets(|tester| {
700 let expected = parameters();
701 let theme = ThemeData::builder()
702 .dropdown_menu_theme(global().theme_data())
703 .build(&tester.cell.borrow());
704 let styles = expected.styles();
705 tester.pump_widget(material_app(
706 theme.clone(),
707 DropdownMenuTheme::new(
708 local().theme_data(),
709 centered(
710 DropdownMenu::new(entries())
711 .text_style(styles.text_style)
712 .menu_style(styles.menu_style)
713 .input_decoration_theme(styles.input_decoration_theme),
714 ),
715 )
716 .into_widget(),
717 ));
718 assert_the_menu_shows(tester, &theme, &expected);
719 });
720 }
721
722 #[test]
725 fn the_theme_disabled_color_colours_a_disabled_menu() {
726 test_widgets(|tester| {
727 let theme = ThemeData::builder()
728 .dropdown_menu_theme(
729 DropdownMenuThemeData::new().disabled_color(Colors::GREY.primary()),
730 )
731 .build(&tester.cell.borrow());
732 tester.pump_widget(material_app(
733 theme,
734 centered(
735 DropdownMenu::new(entries())
736 .enabled(false)
737 .initial_selection(0),
738 ),
739 ));
740
741 let editable = tester.element(find::by_type::<EditableText>());
743 tester.widget(editable, |editable: &EditableText| {
744 assert_eq!(editable.style.color, Some(Colors::GREY.primary().into()));
745 });
746 });
747 }
748 #[test]
750 fn a_dropdown_menu_theme_data_describes_nothing_by_default() {
751 assert_eq!(
752 waft_widgets::testing::describe_properties(|properties| {
753 waft_foundation::Diagnosticable::debug_fill_properties(
754 &DropdownMenuThemeData::new(),
755 properties,
756 )
757 }),
758 Vec::<String>::new()
759 );
760 }
761}