1use std::any::{Any, TypeId};
9use std::collections::HashMap;
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12use std::time::Duration;
13
14use crate::button_style::ButtonStyle;
15use crate::dropdown_menu_theme::{
16 DropdownMenuTheme, DropdownMenuThemeData, DropdownMenuThemeDataGetters,
17};
18use crate::icon_button::IconButton;
19use crate::icons::Icons;
20use crate::input_border::OutlineInputBorder;
21use crate::input_decorator::{InputDecoration, InputDecorationThemeData};
22use crate::material_localizations::MaterialLocalizations;
23use crate::menu_anchor::{MenuAnchor, MenuItemButton};
24use crate::menu_button_theme::MenuButtonTheme;
25use crate::menu_style::MenuStyle;
26use crate::text_field::TextField;
27use crate::theme::Theme;
28use crate::theme_data::VisualDensity;
29use crate::theme_data_getters::DefaultsContext;
30use waft_animation::Curves;
31use waft_embedder::{
32 Color, Offset, Size, TargetPlatform, TextAffinity, TextEditingValue, TextInputAction,
33 TextInputType, TextSelection,
34};
35use waft_foundation::{
36 App, DiagnosticsNode, Handle, K_IS_WEB, Listener, OptionRetained, Ref, ValueChanged,
37};
38use waft_painting::{
39 AlignmentGeometry, EdgeInsets, EdgeInsetsDirectional, EdgeInsetsGeometry, TextAlign,
40 TextAlignVertical, TextDirection, TextStyle,
41};
42use waft_rendering::{
43 AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, BoxParentData,
44 ContainerBoxParentData, ContainerParentData, ContainerParentDataMixin,
45 ContainerRenderObjectData, ContainerRenderObjectMixin, PaintingContext, ParentData,
46 PipelineOwner, RenderBox, RenderBoxContainerDefaultsMixin, RenderBoxData, RenderHandle,
47 RenderObject, RenderObjectData,
48};
49use waft_scheduler::{FrameCallback, SchedulerBinding};
50use waft_services::{
51 LogicalKeyboardKey, MouseCursorRef, SystemMouseCursors, TextInputFormatterRef,
52};
53use waft_widgets::{
54 Action, ActionRef, Actions, Align, AnyFocusNode, AnyMenuController, AnyTextEditingController,
55 BuildContext, CallbackAction, ConstrainedBox, DefaultTextStyle, Directionality, DismissIntent,
56 DismissMenuAction, ExcludeFocus, ExcludeSemantics, ExtendSelectionByCharacterIntent, Focus,
57 FocusNode, FocusNodeLeaf, FocusNodeRef, GlobalKey, Icon, Intent, IntentRef, IntoWidget, KeyRef,
58 MenuController, MenuControllerRef, MultiChildRenderObjectWidget, Padding, RenderObjectWidget,
59 ScrollPositionAlignmentPolicy, Scrollable, Semantics, ShortcutActivatorRef, ShortcutMap,
60 Shortcuts, SingleActivator, SizedBox, Stack, State, StateData, StatefulWidget, Text,
61 TextEditingController, TextEditingControllerRef, WidgetRef, WidgetState, WidgetStateProperty,
62 WidgetStatePropertyAll, WidgetStatePropertyRef, WidgetStates, WidgetStatesController,
63};
64
65pub type FilterCallback<T> =
70 Rc<dyn Fn(&mut App, &[DropdownMenuEntry<T>], &str) -> Vec<DropdownMenuEntry<T>>>;
71
72pub type SearchCallback<T> = Rc<dyn Fn(&mut App, &[DropdownMenuEntry<T>], &str) -> Option<usize>>;
79
80pub type DropdownMenuDecorationBuilder =
88 Rc<dyn Fn(&mut App, BuildContext, AnyMenuController) -> InputDecoration>;
89
90const K_MINIMUM_WIDTH: f64 = 112.0;
91
92const K_DEFAULT_HORIZONTAL_PADDING: f64 = 12.0;
93
94const K_INPUT_START_GAP: f64 = 4.0;
95
96#[derive(Clone)]
102pub struct DropdownMenuEntry<T> {
103 pub value: T,
107
108 pub label: String,
110
111 pub label_widget: Option<WidgetRef>,
124
125 pub leading_icon: Option<WidgetRef>,
127
128 pub trailing_icon: Option<WidgetRef>,
130
131 pub enabled: bool,
137
138 pub style: Option<ButtonStyle>,
142}
143
144impl<T> DropdownMenuEntry<T> {
145 pub fn new(value: T, label: impl Into<String>) -> DropdownMenuEntry<T> {
147 DropdownMenuEntry {
148 value,
149 label: label.into(),
150 label_widget: None,
151 leading_icon: None,
152 trailing_icon: None,
153 enabled: true,
154 style: None,
155 }
156 }
157
158 #[cfg_attr(debug_assertions, track_caller)]
160 pub fn label_widget<K>(mut self, label_widget: impl IntoWidget<K>) -> DropdownMenuEntry<T> {
161 self.label_widget = Some(label_widget.into_widget());
162 self
163 }
164
165 #[cfg_attr(debug_assertions, track_caller)]
167 pub fn leading_icon<K>(mut self, leading_icon: impl IntoWidget<K>) -> DropdownMenuEntry<T> {
168 self.leading_icon = Some(leading_icon.into_widget());
169 self
170 }
171
172 #[cfg_attr(debug_assertions, track_caller)]
174 pub fn trailing_icon<K>(mut self, trailing_icon: impl IntoWidget<K>) -> DropdownMenuEntry<T> {
175 self.trailing_icon = Some(trailing_icon.into_widget());
176 self
177 }
178
179 pub fn enabled(mut self, enabled: bool) -> DropdownMenuEntry<T> {
181 self.enabled = enabled;
182 self
183 }
184
185 pub fn style(mut self, style: ButtonStyle) -> DropdownMenuEntry<T> {
187 self.style = Some(style);
188 self
189 }
190}
191
192impl<T: Debug> Debug for DropdownMenuEntry<T> {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 f.debug_struct("DropdownMenuEntry")
195 .field("value", &self.value)
196 .field("label", &self.label)
197 .field("enabled", &self.enabled)
198 .finish_non_exhaustive()
199 }
200}
201
202#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
204pub enum DropdownMenuCloseBehavior {
205 All,
207
208 SelfOnly,
210
211 None,
213}
214
215#[derive(Clone)]
241pub struct DropdownMenu<T: 'static> {
242 pub key: Option<KeyRef>,
243
244 pub enabled: bool,
248
249 pub width: Option<f64>,
254
255 pub menu_height: Option<f64>,
259
260 pub leading_icon: Option<WidgetRef>,
265
266 pub trailing_icon: Option<WidgetRef>,
273
274 pub show_trailing_icon: bool,
289
290 pub trailing_icon_focus_node: Option<FocusNodeRef>,
297
298 pub label: Option<WidgetRef>,
307
308 pub hint_text: Option<String>,
312
313 pub helper_text: Option<String>,
327
328 pub error_text: Option<String>,
340
341 pub selected_trailing_icon: Option<WidgetRef>,
346
347 pub enable_filter: bool,
351
352 pub enable_search: bool,
356
357 pub keyboard_type: Option<TextInputType>,
361
362 pub text_style: Option<TextStyle>,
367
368 pub text_align: TextAlign,
372
373 pub input_decoration_theme: Option<InputDecorationThemeData>,
377
378 pub decoration_builder: Option<DropdownMenuDecorationBuilder>,
398
399 pub menu_style: Option<MenuStyle>,
403
404 pub controller: Option<TextEditingControllerRef>,
422
423 pub initial_selection: Option<T>,
441
442 pub on_selected: Option<ValueChanged<Option<T>>>,
451
452 pub focus_node: Option<FocusNodeRef>,
460
461 pub request_focus_on_tap: Option<bool>,
477
478 pub select_only: bool,
495
496 pub dropdown_menu_entries: Rc<[DropdownMenuEntry<T>]>,
504
505 pub expanded_insets: Option<EdgeInsetsGeometry>,
518
519 pub filter_callback: Option<FilterCallback<T>>,
528
529 pub search_callback: Option<SearchCallback<T>>,
536
537 pub input_formatters: Option<Vec<TextInputFormatterRef>>,
544
545 pub alignment_offset: Option<Offset>,
547
548 pub close_behavior: DropdownMenuCloseBehavior,
560
561 pub max_lines: Option<i32>,
580
581 pub text_input_action: Option<TextInputAction>,
583
584 pub cursor_height: Option<f64>,
586
587 pub restoration_id: Option<String>,
589
590 pub menu_controller: Option<MenuControllerRef>,
592
593 pub scroll_padding: EdgeInsets,
595}
596
597impl<T: Clone + PartialEq + 'static> DropdownMenu<T> {
598 pub fn new(dropdown_menu_entries: impl Into<Rc<[DropdownMenuEntry<T>]>>) -> DropdownMenu<T> {
610 DropdownMenu {
611 key: None,
612 enabled: true,
613 width: None,
614 menu_height: None,
615 leading_icon: None,
616 trailing_icon: None,
617 show_trailing_icon: true,
618 trailing_icon_focus_node: None,
619 label: None,
620 hint_text: None,
621 helper_text: None,
622 error_text: None,
623 selected_trailing_icon: None,
624 enable_filter: false,
625 enable_search: true,
626 keyboard_type: None,
627 text_style: None,
628 text_align: TextAlign::Start,
629 input_decoration_theme: None,
630 decoration_builder: None,
631 menu_style: None,
632 controller: None,
633 initial_selection: None,
634 on_selected: None,
635 focus_node: None,
636 request_focus_on_tap: None,
637 select_only: false,
638 dropdown_menu_entries: dropdown_menu_entries.into(),
639 expanded_insets: None,
640 filter_callback: None,
641 search_callback: None,
642 input_formatters: None,
643 alignment_offset: None,
644 close_behavior: DropdownMenuCloseBehavior::All,
645 max_lines: Some(1),
646 text_input_action: None,
647 cursor_height: None,
648 restoration_id: None,
649 menu_controller: None,
650 scroll_padding: EdgeInsets::all(20.0),
651 }
652 }
653
654 pub fn key(mut self, key: KeyRef) -> DropdownMenu<T> {
656 self.key = Some(key);
657 self
658 }
659
660 pub fn enabled(mut self, enabled: bool) -> DropdownMenu<T> {
662 self.enabled = enabled;
663 self
664 }
665
666 pub fn width(mut self, width: f64) -> DropdownMenu<T> {
668 self.width = Some(width);
669 self
670 }
671
672 pub fn menu_height(mut self, menu_height: f64) -> DropdownMenu<T> {
674 self.menu_height = Some(menu_height);
675 self
676 }
677
678 #[cfg_attr(debug_assertions, track_caller)]
680 pub fn leading_icon<K>(mut self, leading_icon: impl IntoWidget<K>) -> DropdownMenu<T> {
681 self.leading_icon = Some(leading_icon.into_widget());
682 self
683 }
684
685 #[cfg_attr(debug_assertions, track_caller)]
687 pub fn trailing_icon<K>(mut self, trailing_icon: impl IntoWidget<K>) -> DropdownMenu<T> {
688 self.trailing_icon = Some(trailing_icon.into_widget());
689 self
690 }
691
692 pub fn show_trailing_icon(mut self, show_trailing_icon: bool) -> DropdownMenu<T> {
694 self.show_trailing_icon = show_trailing_icon;
695 self
696 }
697
698 pub fn trailing_icon_focus_node(
700 mut self,
701 trailing_icon_focus_node: FocusNodeRef,
702 ) -> DropdownMenu<T> {
703 self.trailing_icon_focus_node = Some(trailing_icon_focus_node);
704 self
705 }
706
707 #[cfg_attr(debug_assertions, track_caller)]
709 pub fn label<K>(mut self, label: impl IntoWidget<K>) -> DropdownMenu<T> {
710 self.label = Some(label.into_widget());
711 self
712 }
713
714 pub fn hint_text(mut self, hint_text: impl Into<String>) -> DropdownMenu<T> {
716 self.hint_text = Some(hint_text.into());
717 self
718 }
719
720 pub fn helper_text(mut self, helper_text: impl Into<String>) -> DropdownMenu<T> {
722 self.helper_text = Some(helper_text.into());
723 self
724 }
725
726 pub fn error_text(mut self, error_text: impl Into<String>) -> DropdownMenu<T> {
728 self.error_text = Some(error_text.into());
729 self
730 }
731
732 #[cfg_attr(debug_assertions, track_caller)]
734 pub fn selected_trailing_icon<K>(
735 mut self,
736 selected_trailing_icon: impl IntoWidget<K>,
737 ) -> DropdownMenu<T> {
738 self.selected_trailing_icon = Some(selected_trailing_icon.into_widget());
739 self
740 }
741
742 pub fn enable_filter(mut self, enable_filter: bool) -> DropdownMenu<T> {
744 self.enable_filter = enable_filter;
745 self
746 }
747
748 pub fn enable_search(mut self, enable_search: bool) -> DropdownMenu<T> {
750 self.enable_search = enable_search;
751 self
752 }
753
754 pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> DropdownMenu<T> {
756 self.keyboard_type = Some(keyboard_type);
757 self
758 }
759
760 pub fn text_style(mut self, text_style: TextStyle) -> DropdownMenu<T> {
762 self.text_style = Some(text_style);
763 self
764 }
765
766 pub fn text_align(mut self, text_align: TextAlign) -> DropdownMenu<T> {
768 self.text_align = text_align;
769 self
770 }
771
772 pub fn input_decoration_theme(
774 mut self,
775 input_decoration_theme: impl Into<InputDecorationThemeData>,
776 ) -> DropdownMenu<T> {
777 self.input_decoration_theme = Some(input_decoration_theme.into());
778 self
779 }
780
781 pub fn decoration_builder(
783 mut self,
784 decoration_builder: impl Fn(&mut App, BuildContext, AnyMenuController) -> InputDecoration
785 + 'static,
786 ) -> DropdownMenu<T> {
787 self.decoration_builder = Some(Rc::new(decoration_builder));
788 self
789 }
790
791 pub fn menu_style(mut self, menu_style: MenuStyle) -> DropdownMenu<T> {
793 self.menu_style = Some(menu_style);
794 self
795 }
796
797 pub fn controller(mut self, controller: TextEditingControllerRef) -> DropdownMenu<T> {
799 self.controller = Some(controller);
800 self
801 }
802
803 pub fn initial_selection(mut self, initial_selection: T) -> DropdownMenu<T> {
805 self.initial_selection = Some(initial_selection);
806 self
807 }
808
809 pub fn on_selected(
811 mut self,
812 on_selected: impl Fn(&mut App, Option<T>) + 'static,
813 ) -> DropdownMenu<T> {
814 self.on_selected = Some(Rc::new(on_selected));
815 self
816 }
817
818 pub fn focus_node(mut self, focus_node: FocusNodeRef) -> DropdownMenu<T> {
820 self.focus_node = Some(focus_node);
821 self
822 }
823
824 pub fn request_focus_on_tap(mut self, request_focus_on_tap: bool) -> DropdownMenu<T> {
826 self.request_focus_on_tap = Some(request_focus_on_tap);
827 self
828 }
829
830 pub fn select_only(mut self, select_only: bool) -> DropdownMenu<T> {
832 self.select_only = select_only;
833 self
834 }
835
836 pub fn expanded_insets(
838 mut self,
839 expanded_insets: impl Into<EdgeInsetsGeometry>,
840 ) -> DropdownMenu<T> {
841 self.expanded_insets = Some(expanded_insets.into());
842 self
843 }
844
845 pub fn filter_callback(
847 mut self,
848 filter_callback: impl Fn(&mut App, &[DropdownMenuEntry<T>], &str) -> Vec<DropdownMenuEntry<T>>
849 + 'static,
850 ) -> DropdownMenu<T> {
851 self.filter_callback = Some(Rc::new(filter_callback));
852 self
853 }
854
855 pub fn search_callback(
857 mut self,
858 search_callback: impl Fn(&mut App, &[DropdownMenuEntry<T>], &str) -> Option<usize> + 'static,
859 ) -> DropdownMenu<T> {
860 self.search_callback = Some(Rc::new(search_callback));
861 self
862 }
863
864 pub fn input_formatters(
866 mut self,
867 input_formatters: Vec<TextInputFormatterRef>,
868 ) -> DropdownMenu<T> {
869 self.input_formatters = Some(input_formatters);
870 self
871 }
872
873 pub fn alignment_offset(mut self, alignment_offset: Offset) -> DropdownMenu<T> {
875 self.alignment_offset = Some(alignment_offset);
876 self
877 }
878
879 pub fn close_behavior(mut self, close_behavior: DropdownMenuCloseBehavior) -> DropdownMenu<T> {
881 self.close_behavior = close_behavior;
882 self
883 }
884
885 pub fn max_lines(mut self, max_lines: Option<i32>) -> DropdownMenu<T> {
887 self.max_lines = max_lines;
888 self
889 }
890
891 pub fn text_input_action(mut self, text_input_action: TextInputAction) -> DropdownMenu<T> {
893 self.text_input_action = Some(text_input_action);
894 self
895 }
896
897 pub fn cursor_height(mut self, cursor_height: f64) -> DropdownMenu<T> {
899 self.cursor_height = Some(cursor_height);
900 self
901 }
902
903 pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> DropdownMenu<T> {
905 self.restoration_id = Some(restoration_id.into());
906 self
907 }
908
909 pub fn menu_controller(mut self, menu_controller: MenuControllerRef) -> DropdownMenu<T> {
911 self.menu_controller = Some(menu_controller);
912 self
913 }
914
915 pub fn scroll_padding(mut self, scroll_padding: EdgeInsets) -> DropdownMenu<T> {
917 self.scroll_padding = scroll_padding;
918 self
919 }
920}
921
922impl<T: 'static> Debug for DropdownMenu<T> {
923 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924 f.debug_struct("DropdownMenu")
925 .field("enabled", &self.enabled)
926 .field("width", &self.width)
927 .field("menu_height", &self.menu_height)
928 .field("entries", &self.dropdown_menu_entries.len())
929 .finish_non_exhaustive()
930 }
931}
932
933impl<T: Clone + PartialEq + 'static> StatefulWidget for DropdownMenu<T> {
934 type State = DropdownMenuState<T>;
935
936 fn key(&self) -> Option<&KeyRef> {
937 self.key.as_ref()
938 }
939
940 fn debug_check_constructor(&self) {
941 debug_assert!(self.filter_callback.is_none() || self.enable_filter);
942 debug_assert!(self.trailing_icon_focus_node.is_none() || self.show_trailing_icon);
943 debug_assert!(
944 self.decoration_builder.is_none()
945 || (self.label.is_none()
946 && self.hint_text.is_none()
947 && self.helper_text.is_none()
948 && self.error_text.is_none())
949 );
950 }
951
952 fn create_state(&self) -> DropdownMenuState<T> {
953 DropdownMenuState {
954 state: StateData::new(),
955 anchor_key: GlobalKey::new(),
956 leading_key: GlobalKey::new(),
957 button_item_keys: Vec::new(),
958 controller: None,
959 internal_menu_controller: None,
960 enable_filter: false,
961 enable_search: true,
962 filtered_entries: Rc::from(Vec::new()),
963 initial_menu: None,
964 current_highlight: None,
965 leading_padding: None,
966 menu_has_enabled_item: false,
967 local_text_editing_controller: None,
968 internal_focus_node: None,
969 focus_node_can_request_focus: None,
970 highlighted_item_states_controller: None,
971 local_trailing_icon_button_focus_node: None,
972 }
973 }
974}
975
976pub struct DropdownMenuState<T: Clone + PartialEq + 'static> {
978 state: StateData<DropdownMenu<T>>,
979 anchor_key: GlobalKey,
980 leading_key: GlobalKey,
981 button_item_keys: Vec<GlobalKey>,
982 controller: Option<MenuControllerRef>,
983 internal_menu_controller: Option<Ref<MenuController>>,
986 enable_filter: bool,
987 enable_search: bool,
988 filtered_entries: Rc<[DropdownMenuEntry<T>]>,
989 initial_menu: Option<Vec<WidgetRef>>,
990 current_highlight: Option<usize>,
991 leading_padding: Option<f64>,
992 menu_has_enabled_item: bool,
993 local_text_editing_controller: Option<Ref<TextEditingController>>,
994 internal_focus_node: Option<Ref<FocusNode>>,
995 focus_node_can_request_focus: Option<bool>,
996 highlighted_item_states_controller: Option<Ref<WidgetStatesController>>,
997 local_trailing_icon_button_focus_node: Option<Ref<FocusNode>>,
998}
999
1000fn editable_shortcuts() -> ShortcutMap {
1002 vec![
1003 shortcut(
1004 SingleActivator::new(LogicalKeyboardKey::ARROW_LEFT),
1005 ExtendSelectionByCharacterIntent::new(false, true),
1006 ),
1007 shortcut(
1008 SingleActivator::new(LogicalKeyboardKey::ARROW_RIGHT),
1009 ExtendSelectionByCharacterIntent::new(true, true),
1010 ),
1011 shortcut(
1012 SingleActivator::new(LogicalKeyboardKey::ARROW_UP),
1013 ArrowUpIntent,
1014 ),
1015 shortcut(
1016 SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN),
1017 ArrowDownIntent,
1018 ),
1019 ]
1020}
1021
1022fn select_only_shortcuts() -> ShortcutMap {
1024 vec![
1025 shortcut(
1026 SingleActivator::new(LogicalKeyboardKey::ARROW_UP),
1027 ArrowUpIntent,
1028 ),
1029 shortcut(
1030 SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN),
1031 ArrowDownIntent,
1032 ),
1033 shortcut(SingleActivator::new(LogicalKeyboardKey::ENTER), EnterIntent),
1036 ]
1037}
1038
1039fn unfocused_text_field_shortcuts() -> ShortcutMap {
1042 vec![
1043 shortcut(
1044 SingleActivator::new(LogicalKeyboardKey::ARROW_UP),
1045 ArrowUpIntent,
1046 ),
1047 shortcut(
1048 SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN),
1049 ArrowDownIntent,
1050 ),
1051 shortcut(SingleActivator::new(LogicalKeyboardKey::ENTER), EnterIntent),
1052 shortcut(
1053 SingleActivator::new(LogicalKeyboardKey::ESCAPE),
1054 DismissIntent::new(),
1055 ),
1056 ]
1057}
1058
1059fn shortcut(activator: SingleActivator, intent: impl Intent) -> (ShortcutActivatorRef, IntentRef) {
1060 (Rc::new(activator), Rc::new(intent))
1061}
1062
1063fn text_editing_value_of(label: &str) -> TextEditingValue {
1065 TextEditingValue::new()
1066 .text(label)
1067 .selection(TextSelection::collapsed(
1068 label.encode_utf16().count() as i32,
1069 TextAffinity::Downstream,
1070 ))
1071}
1072
1073fn same_widget(a: &Option<WidgetRef>, b: &Option<WidgetRef>) -> bool {
1075 match (a, b) {
1076 (None, None) => true,
1077 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
1078 _ => false,
1079 }
1080}
1081
1082impl<T: Clone + PartialEq + 'static> DropdownMenuState<T> {
1083 fn effective_text_editing_controller(
1084 self: Handle<Self>,
1085 app: &mut App,
1086 ) -> TextEditingControllerRef {
1087 if let Some(controller) = self.widget(app).controller.clone() {
1088 return controller;
1089 }
1090 if let Some(controller) = app.get(self).local_text_editing_controller.as_ref() {
1091 return controller.erase();
1092 }
1093 let controller = TextEditingController::new(app);
1094 app.get_mut(self).local_text_editing_controller = Some(controller.clone());
1095 controller.into_erased()
1096 }
1097
1098 fn trailing_icon_button_focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
1099 if let Some(focus_node) = self.widget(app).trailing_icon_focus_node.clone() {
1100 return focus_node;
1101 }
1102 if let Some(focus_node) = app.get(self).local_trailing_icon_button_focus_node.as_ref() {
1103 return focus_node.erase();
1104 }
1105 let focus_node = FocusNode::new(app);
1106 app.get_mut(self).local_trailing_icon_button_focus_node = Some(focus_node.clone());
1107 focus_node.into_erased()
1108 }
1109
1110 fn menu_controller(self: Handle<Self>, app: &App) -> &MenuControllerRef {
1111 app.get(self)
1112 .controller
1113 .as_ref()
1114 .expect("init_state sets the menu controller")
1115 }
1116
1117 fn internal_focus_node(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
1118 app.get(self)
1119 .internal_focus_node
1120 .handle()
1121 .expect("init_state makes the internal focus node")
1122 }
1123
1124 fn set_menu_controller(self: Handle<Self>, app: &mut App) {
1126 let controller = match self.widget(app).menu_controller.clone() {
1127 Some(controller) => {
1128 app.get_mut(self).internal_menu_controller = None;
1129 controller
1130 }
1131 None => {
1132 let internal = MenuController::new(app);
1133 app.get_mut(self).internal_menu_controller = Some(internal.clone());
1134 internal.into_erased()
1135 }
1136 };
1137 app.get_mut(self).controller = Some(controller);
1138 }
1139
1140 fn mark_needs_build(self: Handle<Self>, app: &mut App) {
1142 self.set_state(app, |_| {});
1143 }
1144
1145 fn set_button_item_keys(self: Handle<Self>, app: &mut App) {
1146 let count = app.get(self).filtered_entries.len();
1147 app.get_mut(self).button_item_keys = (0..count).map(|_| GlobalKey::new()).collect();
1148 }
1149
1150 fn update_menu_has_enabled_item(self: Handle<Self>, app: &mut App) {
1151 let state = app.get_mut(self);
1152 state.menu_has_enabled_item = state.filtered_entries.iter().any(|entry| entry.enabled);
1153 }
1154
1155 fn show_initial_selection(self: Handle<Self>, app: &mut App) {
1158 let initial_selection = self.widget(app).initial_selection.clone();
1159 let label = app
1160 .get(self)
1161 .filtered_entries
1162 .iter()
1163 .find(|entry| Some(&entry.value) == initial_selection.as_ref())
1164 .map(|entry| entry.label.clone());
1165 if let Some(label) = label {
1166 self.effective_text_editing_controller(app)
1167 .set_value(app, text_editing_value_of(&label));
1168 }
1169 }
1170
1171 fn can_request_focus(self: Handle<Self>, app: &mut App) -> bool {
1172 if let Some(focus_node) = self.widget(app).focus_node.clone() {
1173 return focus_node.can_request_focus(app);
1174 }
1175 if let Some(request_focus_on_tap) = self.widget(app).request_focus_on_tap {
1176 return request_focus_on_tap;
1177 }
1178 let context = self.context(app);
1179 match Theme::of(app, context).platform {
1180 TargetPlatform::IOS | TargetPlatform::Android | TargetPlatform::Fuchsia => false,
1181 TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => true,
1182 }
1183 }
1184
1185 fn select_only(self: Handle<Self>, app: &App) -> bool {
1186 self.widget(app).select_only
1187 }
1188
1189 fn is_button(self: Handle<Self>, app: &mut App) -> bool {
1190 !self.can_request_focus(app) || self.select_only(app)
1191 }
1192
1193 fn refresh_leading_padding(self: Handle<Self>, app: &mut App) {
1194 SchedulerBinding::add_post_frame_callback(
1195 app,
1196 FrameCallback::new(move |app, _duration| {
1197 if !self.mounted(app) {
1198 return;
1199 }
1200 let leading_key = app.get(self).leading_key.clone();
1201 let leading_padding = Self::get_width(app, &leading_key);
1202 self.set_state(app, |state| {
1203 state.leading_padding = leading_padding;
1204 });
1205 }),
1206 None,
1207 );
1208 }
1209
1210 fn scroll_to_highlight(self: Handle<Self>, app: &mut App) {
1211 SchedulerBinding::add_post_frame_callback(
1212 app,
1213 FrameCallback::new(move |app, _duration| {
1214 if !app.contains(self) {
1217 return;
1218 }
1219 let state = app.get(self);
1220 let current_highlight = state
1221 .current_highlight
1222 .expect("a highlight when its scroll was scheduled");
1223 let key = state.button_item_keys[current_highlight].clone();
1224 if let Some(highlight_context) = key.current_context(app) {
1225 let render_object = highlight_context
1226 .find_render_object(app)
1227 .expect("a mounted menu item has a render object");
1228 let position = Scrollable::of(app, highlight_context, None).position(app);
1229 drop(position.ensure_visible(
1230 app,
1231 render_object,
1232 0.0,
1233 Duration::ZERO,
1234 Curves::ease(),
1235 ScrollPositionAlignmentPolicy::Explicit,
1236 None,
1237 ));
1238 }
1239 }),
1240 None,
1241 );
1242 }
1243
1244 fn get_width(app: &App, key: &GlobalKey) -> Option<f64> {
1245 let context = key.current_context(app)?;
1246 let render_box = context
1247 .find_render_object(app)
1248 .and_then(AnyRenderObject::as_box)
1249 .expect("the key's widget builds a render box");
1250 if render_box.has_size(app) {
1251 Some(render_box.size(app).width())
1252 } else {
1253 None
1254 }
1255 }
1256
1257 fn filter(
1258 entries: &[DropdownMenuEntry<T>],
1259 text_editing_controller: AnyTextEditingController,
1260 app: &App,
1261 ) -> Vec<DropdownMenuEntry<T>> {
1262 let filter_text = text_editing_controller.text_value(app).to_lowercase();
1263 entries
1264 .iter()
1265 .filter(|entry| entry.label.to_lowercase().contains(&filter_text))
1266 .cloned()
1267 .collect()
1268 }
1269
1270 fn should_update_current_highlight(
1271 self: Handle<Self>,
1272 app: &mut App,
1273 entries: &[DropdownMenuEntry<T>],
1274 ) -> bool {
1275 let search_text = self
1276 .effective_text_editing_controller(app)
1277 .value(app)
1278 .text
1279 .to_lowercase();
1280 if search_text.is_empty() {
1281 return true;
1282 }
1283
1284 let Some(current_highlight) = app.get(self).current_highlight else {
1286 return true;
1287 };
1288 if current_highlight >= entries.len() {
1289 return true;
1290 }
1291
1292 if entries[current_highlight]
1293 .label
1294 .to_lowercase()
1295 .contains(&search_text)
1296 {
1297 return false;
1298 }
1299
1300 true
1301 }
1302
1303 fn search(
1304 entries: &[DropdownMenuEntry<T>],
1305 text_editing_controller: AnyTextEditingController,
1306 app: &App,
1307 ) -> Option<usize> {
1308 let search_text = text_editing_controller.value(app).text.to_lowercase();
1309 if search_text.is_empty() {
1310 return None;
1311 }
1312
1313 entries
1314 .iter()
1315 .position(|entry| entry.label.to_lowercase().contains(&search_text))
1316 }
1317
1318 fn build_buttons(
1319 self: Handle<Self>,
1320 app: &mut App,
1321 context: BuildContext,
1322 filtered_entries: &[DropdownMenuEntry<T>],
1323 options: BuildButtonsOptions,
1324 ) -> Vec<WidgetRef> {
1325 let effective_input_start_gap = if options.use_material3.unwrap_or(false) {
1326 K_INPUT_START_GAP
1327 } else {
1328 0.0
1329 };
1330 let mut result = Vec::new();
1331 for (i, entry) in filtered_entries.iter().enumerate() {
1332 let padding = if entry.leading_icon.is_none() {
1339 app.get(self)
1340 .leading_padding
1341 .unwrap_or(K_DEFAULT_HORIZONTAL_PADDING)
1342 } else {
1343 K_DEFAULT_HORIZONTAL_PADDING
1344 };
1345 let mut effective_style = entry.style.clone().unwrap_or_else(|| {
1346 MenuItemButton::style_from()
1347 .padding(
1348 EdgeInsetsDirectional::only(
1349 padding,
1350 0.0,
1351 K_DEFAULT_HORIZONTAL_PADDING,
1352 0.0,
1353 )
1354 .into(),
1355 )
1356 .build()
1357 });
1358
1359 let theme_style = MenuButtonTheme::of(app, context).style;
1360
1361 let entry_style = entry.style.as_ref();
1362 let effective_foreground_color = entry_style
1363 .and_then(|style| style.foreground_color.clone())
1364 .or_else(|| {
1365 theme_style
1366 .as_ref()
1367 .and_then(|style| style.foreground_color.clone())
1368 });
1369 let effective_icon_color = entry_style
1370 .and_then(|style| style.icon_color.clone())
1371 .or_else(|| {
1372 theme_style
1373 .as_ref()
1374 .and_then(|style| style.icon_color.clone())
1375 });
1376 let effective_overlay_color = entry_style
1377 .and_then(|style| style.overlay_color.clone())
1378 .or_else(|| {
1379 theme_style
1380 .as_ref()
1381 .and_then(|style| style.overlay_color.clone())
1382 });
1383 let effective_background_color = entry_style
1384 .and_then(|style| style.background_color.clone())
1385 .or_else(|| {
1386 theme_style
1387 .as_ref()
1388 .and_then(|style| style.background_color.clone())
1389 });
1390
1391 let entry_is_selected = entry.enabled && Some(i) == options.focused_index;
1395 if entry_is_selected {
1396 if let Some(replaced) = app.get_mut(self).highlighted_item_states_controller.take()
1397 {
1398 replaced.dispose(app);
1399 }
1400 let focused: WidgetStates = [WidgetState::Focused].into_iter().collect();
1401 let states_controller = WidgetStatesController::new(app, Some(focused.clone()));
1402 app.get_mut(self).highlighted_item_states_controller = Some(states_controller);
1403
1404 let default_style = MenuItemButton::new().default_style_of(app, context);
1408
1409 let resolve_focused_color =
1410 |color_state_property: Option<&WidgetStatePropertyRef<Option<Color>>>| {
1411 color_state_property.and_then(|property| property.resolve(&focused))
1412 };
1413
1414 let focused_foreground_color = resolve_focused_color(Some(
1415 effective_foreground_color
1416 .clone()
1417 .or_else(|| default_style.foreground_color(app))
1418 .as_ref()
1419 .expect("the default style has a foreground color"),
1420 ))
1421 .expect("a focused foreground color");
1422 let focused_icon_color = resolve_focused_color(Some(
1423 effective_icon_color
1424 .clone()
1425 .or_else(|| default_style.icon_color(app))
1426 .as_ref()
1427 .expect("the default style has an icon color"),
1428 ))
1429 .expect("a focused icon color");
1430 let focused_overlay_color = resolve_focused_color(Some(
1431 effective_overlay_color
1432 .clone()
1433 .or_else(|| default_style.overlay_color(app))
1434 .as_ref()
1435 .expect("the default style has an overlay color"),
1436 ))
1437 .expect("a focused overlay color");
1438 #[expect(deprecated, reason = "Dart calls the deprecated `withOpacity`")]
1441 let focused_background_color = resolve_focused_color(
1442 effective_background_color.as_ref(),
1443 )
1444 .unwrap_or_else(|| {
1445 Theme::of(app, context)
1446 .color_scheme
1447 .on_surface()
1448 .with_opacity(0.12)
1449 });
1450
1451 effective_style.background_color = Some(Rc::new(WidgetStatePropertyAll::new(
1452 Some(focused_background_color),
1453 )));
1454 effective_style.foreground_color = Some(Rc::new(WidgetStatePropertyAll::new(
1455 Some(focused_foreground_color),
1456 )));
1457 effective_style.icon_color = Some(Rc::new(WidgetStatePropertyAll::new(Some(
1458 focused_icon_color,
1459 ))));
1460 effective_style.overlay_color = Some(Rc::new(WidgetStatePropertyAll::new(Some(
1461 focused_overlay_color,
1462 ))));
1463 } else {
1464 copy_with_color(
1465 &mut effective_style.background_color,
1466 effective_background_color,
1467 );
1468 copy_with_color(
1469 &mut effective_style.foreground_color,
1470 effective_foreground_color,
1471 );
1472 copy_with_color(&mut effective_style.icon_color, effective_icon_color);
1473 copy_with_color(&mut effective_style.overlay_color, effective_overlay_color);
1474 }
1475
1476 let mut label = entry
1477 .label_widget
1478 .clone()
1479 .unwrap_or_else(|| Text::new(entry.label.clone()).into_widget());
1480 let widget = self.widget(app);
1481 if let Some(width) = widget.width {
1482 let horizontal_padding =
1483 padding + K_DEFAULT_HORIZONTAL_PADDING + effective_input_start_gap;
1484 label = ConstrainedBox::new(
1485 BoxConstraints::new().max_width(width - horizontal_padding),
1486 )
1487 .child(label)
1488 .into_widget();
1489 }
1490
1491 let on_pressed = (entry.enabled && widget.enabled).then(|| {
1492 let entry = entry.clone();
1493 let controller = widget.controller.clone();
1494 let on_selected = widget.on_selected.clone();
1495 Listener::new(move |app| {
1496 self.handle_entry_pressed(app, &entry, i, controller.handle(), &on_selected)
1497 })
1498 });
1499 let mut menu_item_button = MenuItemButton::new()
1500 .style(effective_style)
1501 .close_on_activate(widget.close_behavior == DropdownMenuCloseBehavior::All)
1502 .request_focus_on_hover(false)
1503 .child(
1509 Padding::new(EdgeInsetsDirectional::only(
1510 effective_input_start_gap,
1511 0.0,
1512 0.0,
1513 0.0,
1514 ))
1515 .child(label),
1516 );
1517 if options.enable_scroll_to_highlight {
1518 menu_item_button.key = Some(app.get(self).button_item_keys[i].clone().into());
1519 }
1520 if entry_is_selected {
1521 menu_item_button.states_controller =
1522 app.get(self).highlighted_item_states_controller.clone();
1523 }
1524 menu_item_button.leading_icon = entry.leading_icon.clone();
1525 menu_item_button.trailing_icon = entry.trailing_icon.clone();
1526 menu_item_button.on_pressed = on_pressed;
1527
1528 let menu_item_button = ExcludeFocus::new(
1529 ExcludeSemantics::new()
1530 .excluding(options.exclude_semantics)
1531 .child(menu_item_button),
1532 )
1533 .into_widget();
1534 result.push(menu_item_button);
1535 }
1536
1537 result
1538 }
1539
1540 fn handle_entry_pressed(
1542 self: Handle<Self>,
1543 app: &mut App,
1544 entry: &DropdownMenuEntry<T>,
1545 index: usize,
1546 controller: Option<AnyTextEditingController>,
1547 on_selected: &Option<ValueChanged<Option<T>>>,
1548 ) {
1549 if !self.mounted(app) {
1550 if let Some(controller) = controller {
1554 controller.set_value(app, text_editing_value_of(&entry.label));
1555 }
1556 if let Some(on_selected) = on_selected {
1557 on_selected(app, Some(entry.value.clone()));
1558 }
1559 return;
1560 }
1561 self.effective_text_editing_controller(app)
1562 .set_value(app, text_editing_value_of(&entry.label));
1563 let enable_search = self.widget(app).enable_search;
1564 app.get_mut(self).current_highlight = if enable_search { Some(index) } else { None };
1565 if let Some(on_selected) = self.widget(app).on_selected.clone() {
1566 on_selected(app, Some(entry.value.clone()));
1567 }
1568 app.get_mut(self).enable_filter = false;
1569 if self.widget(app).close_behavior == DropdownMenuCloseBehavior::SelfOnly {
1570 self.menu_controller(app).handle().close(app);
1571 }
1572 }
1573
1574 fn handle_up_key(self: Handle<Self>, app: &mut App) {
1575 self.move_highlight(app, false);
1576 }
1577
1578 fn handle_down_key(self: Handle<Self>, app: &mut App) {
1579 self.move_highlight(app, true);
1580 }
1581
1582 fn move_highlight(self: Handle<Self>, app: &mut App, forward: bool) {
1584 let enabled = self.widget(app).enabled;
1585 let is_open = self.menu_controller(app).handle().is_open(app);
1586 if enabled && app.get(self).menu_has_enabled_item && is_open {
1587 let state = app.get_mut(self);
1588 state.enable_filter = false;
1589 state.enable_search = false;
1590 let length = state.filtered_entries.len() as i64;
1591 let step = if forward { 1 } else { -1 };
1592 let start = state
1593 .current_highlight
1594 .map_or(if forward { -1 } else { 0 }, |highlight| highlight as i64);
1595 let mut current_highlight = (start + step).rem_euclid(length);
1596 while !state.filtered_entries[current_highlight as usize].enabled {
1597 current_highlight = (current_highlight + step).rem_euclid(length);
1598 }
1599 state.current_highlight = Some(current_highlight as usize);
1600 let current_label = state.filtered_entries[current_highlight as usize]
1601 .label
1602 .clone();
1603 self.effective_text_editing_controller(app)
1604 .set_value(app, text_editing_value_of(¤t_label));
1605 }
1606 self.mark_needs_build(app);
1607 }
1608
1609 fn handle_enter_key(self: Handle<Self>, app: &mut App) {
1610 let controller = self.menu_controller(app).handle();
1611 if self.select_only(app) && !controller.is_open(app) {
1612 controller.open(app, None);
1613 return;
1614 }
1615 self.handle_submitted(app);
1616 }
1617
1618 fn handle_pressed(
1619 self: Handle<Self>,
1620 app: &mut App,
1621 controller: AnyMenuController,
1622 focus_for_keyboard: bool,
1623 ) {
1624 if controller.is_open(app) {
1625 app.get_mut(self).current_highlight = None;
1626 controller.close(app);
1627 } else {
1628 let entries = Rc::clone(&self.widget(app).dropdown_menu_entries);
1629 app.get_mut(self).filtered_entries = entries;
1630 if !self
1632 .effective_text_editing_controller(app)
1633 .text_value(app)
1634 .is_empty()
1635 {
1636 app.get_mut(self).enable_filter = false;
1637 }
1638 controller.open(app, None);
1639 if focus_for_keyboard {
1640 let internal_focus_node = FocusNodeLeaf::as_node(self.internal_focus_node(app));
1641 internal_focus_node.request_focus(app, None);
1642 }
1643 }
1644 self.mark_needs_build(app);
1645 }
1646
1647 fn handle_submitted(self: Handle<Self>, app: &mut App) {
1648 let controller = self.menu_controller(app).handle();
1649 if let Some(current_highlight) = app.get(self).current_highlight {
1650 let entry = app.get(self).filtered_entries[current_highlight].clone();
1651 if entry.enabled {
1652 self.effective_text_editing_controller(app)
1653 .set_value(app, text_editing_value_of(&entry.label));
1654 if let Some(on_selected) = self.widget(app).on_selected.clone() {
1655 on_selected(app, Some(entry.value));
1656 }
1657 }
1658 } else if controller.is_open(app)
1659 && let Some(on_selected) = self.widget(app).on_selected.clone()
1660 {
1661 on_selected(app, None);
1662 }
1663 if !self.widget(app).enable_search {
1664 app.get_mut(self).current_highlight = None;
1665 }
1666 controller.close(app);
1667 }
1668
1669 fn build_default_decoration(
1670 self: Handle<Self>,
1671 app: &mut App,
1672 context: BuildContext,
1673 controller: AnyMenuController,
1674 ) -> InputDecoration {
1675 let widget = self.widget(app).clone();
1676 let mut decoration = InputDecoration::new();
1677 decoration.label = widget.label;
1678 decoration.hint_text = widget.hint_text;
1679 decoration.helper_text = widget.helper_text;
1680 decoration.error_text = widget.error_text;
1681 decoration.prefix_icon = widget.leading_icon;
1682 decoration.suffix_icon = self.build_default_suffix_icon(app, context, controller);
1683 decoration
1684 }
1685
1686 fn build_default_suffix_icon(
1687 self: Handle<Self>,
1688 app: &mut App,
1689 _context: BuildContext,
1690 controller: AnyMenuController,
1691 ) -> Option<WidgetRef> {
1692 let widget = self.widget(app).clone();
1693 let is_collapsed = widget
1694 .input_decoration_theme
1695 .as_ref()
1696 .is_some_and(|theme| theme.is_collapsed);
1697 if !widget.show_trailing_icon {
1698 return None;
1699 }
1700 let on_pressed = widget
1701 .enabled
1702 .then(|| Listener::new(move |app| self.handle_pressed(app, controller, true)));
1703 let mut icon_button = IconButton::new(
1704 on_pressed,
1705 widget
1706 .trailing_icon
1707 .clone()
1708 .unwrap_or_else(|| Icon::new(Some(Icons::arrow_drop_down())).into_widget()),
1709 )
1710 .focus_node(self.trailing_icon_button_focus_node(app))
1711 .is_selected(controller.is_open(app))
1712 .selected_icon(
1713 widget
1714 .selected_trailing_icon
1715 .clone()
1716 .unwrap_or_else(|| Icon::new(Some(Icons::arrow_drop_up())).into_widget()),
1717 );
1718 icon_button.constraints = widget
1719 .input_decoration_theme
1720 .as_ref()
1721 .and_then(|theme| theme.suffix_icon_constraints);
1722 if is_collapsed {
1723 icon_button.padding = Some(EdgeInsetsGeometry::ZERO);
1724 }
1725 let is_button = self.is_button(app);
1726 Some(
1727 Padding::new(if is_collapsed {
1728 EdgeInsetsGeometry::ZERO
1729 } else {
1730 EdgeInsetsGeometry::all(4.0)
1731 })
1732 .child(
1733 ExcludeSemantics::new()
1734 .excluding(is_button)
1740 .child(icon_button),
1741 )
1742 .into_widget(),
1743 )
1744 }
1745
1746 fn build_anchor(
1748 self: Handle<Self>,
1749 app: &mut App,
1750 context: BuildContext,
1751 controller: AnyMenuController,
1752 anchor: &AnchorBuildArguments,
1753 ) -> WidgetRef {
1754 debug_assert!(app.get(self).initial_menu.is_some());
1755 let widget = self.widget(app).clone();
1756 let mut decoration = match &widget.decoration_builder {
1757 Some(decoration_builder) => decoration_builder(app, context, controller),
1758 None => self.build_default_decoration(app, context, controller),
1759 };
1760 if decoration.suffix_icon.is_none() {
1762 decoration.suffix_icon = self.build_default_suffix_icon(app, context, controller);
1763 }
1764 let effective_decoration =
1765 decoration.apply_defaults(anchor.effective_input_decoration_theme.clone());
1766 let text_field_decoration = match &effective_decoration.prefix_icon {
1767 None => effective_decoration.clone(),
1768 Some(prefix_icon) => {
1769 let mut decoration = effective_decoration.copy_with();
1770 decoration.prefix_icon = Some(
1771 SizedBox::new()
1772 .key(app.get(self).leading_key.clone().into())
1774 .child(prefix_icon.clone())
1775 .into_widget(),
1776 );
1777 decoration
1778 }
1779 };
1780
1781 let localizations = <dyn MaterialLocalizations>::of(app, context);
1782 let is_button = self.is_button(app);
1783 let can_request_focus = self.can_request_focus(app);
1784 let menu_controller = self.menu_controller(app).handle();
1785 let is_open = menu_controller.is_open(app);
1786 let mut semantics = Semantics::new().button(is_button);
1787 if Theme::of(app, context).platform == TargetPlatform::IOS {
1790 semantics = semantics.hint(if is_open {
1791 localizations.collapsed_hint()
1792 } else {
1793 localizations.expanded_hint()
1794 });
1795 }
1796 semantics = semantics.expanded(is_open);
1797 if !is_open {
1798 semantics = semantics.on_expand(Rc::new(move |app: &mut App| {
1799 menu_controller.open(app, None);
1800 }));
1801 } else {
1802 semantics = semantics.on_collapse(Rc::new(move |app: &mut App| {
1803 menu_controller.close(app);
1804 }));
1805 }
1806
1807 let mut text_field = TextField::new()
1808 .key(app.get(self).anchor_key.clone().into())
1809 .enabled(widget.enabled)
1810 .can_request_focus(can_request_focus)
1811 .enable_interactive_selection(!is_button)
1812 .read_only(is_button)
1813 .text_align(widget.text_align)
1814 .text_align_vertical(TextAlignVertical::CENTER)
1815 .max_lines(widget.max_lines)
1816 .controller(self.effective_text_editing_controller(app))
1817 .on_submitted(move |app, _| self.handle_submitted(app))
1818 .on_changed(move |app, _text| {
1819 controller.open(app, None);
1820 let widget = self.widget(app);
1821 let entries = Rc::clone(&widget.dropdown_menu_entries);
1822 let enable_filter = widget.enable_filter;
1823 let enable_search = widget.enable_search;
1824 self.set_state(app, |state| {
1825 state.filtered_entries = entries;
1826 state.enable_filter = enable_filter;
1827 state.enable_search = enable_search;
1828 });
1829 })
1830 .decoration(Some(text_field_decoration))
1831 .scroll_padding(widget.scroll_padding);
1832 text_field.mouse_cursor = anchor.effective_mouse_cursor.clone();
1833 text_field.focus_node = widget.focus_node.clone();
1834 text_field.keyboard_type = widget.keyboard_type;
1835 text_field.text_input_action = widget.text_input_action;
1836 text_field.cursor_height = widget.cursor_height;
1837 text_field.style = anchor.effective_text_style.clone().map(Into::into);
1838 text_field.on_tap = widget.enabled.then(|| {
1839 Listener::new(move |app| {
1840 let focus_for_keyboard = !self.can_request_focus(app);
1841 self.handle_pressed(app, controller, focus_for_keyboard);
1842 })
1843 });
1844 text_field.input_formatters = widget.input_formatters.clone();
1845 text_field.restoration_id = widget.restoration_id.clone();
1846
1847 let text_field = semantics
1848 .child(
1849 ExcludeSemantics::new()
1850 .excluding(is_button && K_IS_WEB)
1854 .child(text_field),
1855 )
1856 .into_widget();
1857
1858 let effective_label = effective_decoration.label.clone().or_else(|| {
1860 effective_decoration
1861 .label_text
1862 .clone()
1863 .map(|label_text| Text::new(label_text).into_widget())
1864 });
1865
1866 let body = if widget.expanded_insets.is_some() {
1870 text_field
1871 } else {
1872 let mut children = vec![text_field];
1873 children.extend(
1874 app.get(self)
1875 .initial_menu
1876 .clone()
1877 .expect("build made the initial menu"),
1878 );
1879 if let Some(effective_label) = effective_label {
1880 children.push(
1881 ExcludeSemantics::new()
1882 .child(
1883 Padding::new(
1884 EdgeInsetsGeometry::symmetric(0.0, 4.0),
1886 )
1887 .child(DefaultTextStyle::new(
1888 anchor
1889 .effective_text_style
1890 .clone()
1891 .expect("an effective text style with a label"),
1892 effective_label,
1893 )),
1894 )
1895 .into_widget(),
1896 );
1897 }
1898 children.push(
1899 effective_decoration
1900 .suffix_icon
1901 .clone()
1902 .unwrap_or_else(|| SizedBox::shrink().into_widget()),
1903 );
1904 children.push(
1905 Padding::new(
1906 EdgeInsetsGeometry::all(8.0),
1910 )
1911 .child(
1912 effective_decoration
1913 .prefix_icon
1914 .clone()
1915 .unwrap_or_else(|| SizedBox::shrink().into_widget()),
1916 )
1917 .into_widget(),
1918 );
1919 DropdownMenuBody {
1920 width: widget.width,
1921 children,
1932 }
1933 .into_widget()
1934 };
1935
1936 Shortcuts::new(
1937 if self.select_only(app) {
1938 select_only_shortcuts()
1939 } else {
1940 editable_shortcuts()
1941 },
1942 body,
1943 )
1944 .into_widget()
1945 }
1946
1947 fn build_actions(self: Handle<Self>, app: &mut App) -> HashMap<TypeId, ActionRef> {
1949 let up = CallbackAction::<ArrowUpIntent>::new(
1950 app,
1951 Rc::new(move |app: &mut App, _intent: &ArrowUpIntent| {
1952 self.handle_up_key(app);
1953 None
1954 }),
1955 );
1956 let down = CallbackAction::<ArrowDownIntent>::new(
1957 app,
1958 Rc::new(move |app: &mut App, _intent: &ArrowDownIntent| {
1959 self.handle_down_key(app);
1960 None
1961 }),
1962 );
1963 let enter = CallbackAction::<EnterIntent>::new(
1964 app,
1965 Rc::new(move |app: &mut App, _intent: &EnterIntent| {
1966 self.handle_enter_key(app);
1967 None
1968 }),
1969 );
1970 let controller = self.menu_controller(app).clone();
1971 let dismiss = DismissMenuAction::new(app, controller);
1972 let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
1973 actions.insert(TypeId::of::<ArrowUpIntent>(), up.into_erased());
1974 actions.insert(TypeId::of::<ArrowDownIntent>(), down.into_erased());
1975 actions.insert(TypeId::of::<EnterIntent>(), enter.into_erased());
1976 actions.insert(
1977 <DismissMenuAction as Action>::intent_type(),
1978 dismiss.into_erased(),
1979 );
1980 actions
1981 }
1982}
1983
1984fn copy_with_color(
1986 field: &mut Option<WidgetStatePropertyRef<Option<Color>>>,
1987 value: Option<WidgetStatePropertyRef<Option<Color>>>,
1988) {
1989 if value.is_some() {
1990 *field = value;
1991 }
1992}
1993
1994struct BuildButtonsOptions {
1996 #[expect(
1997 dead_code,
1998 reason = "Dart's argument, which `_buildButtons` does not read"
1999 )]
2000 text_direction: TextDirection,
2001 focused_index: Option<usize>,
2002 enable_scroll_to_highlight: bool,
2003 exclude_semantics: bool,
2004 use_material3: Option<bool>,
2005}
2006
2007struct AnchorBuildArguments {
2009 effective_input_decoration_theme: InputDecorationThemeData,
2010 effective_text_style: Option<TextStyle>,
2011 effective_mouse_cursor: Option<MouseCursorRef>,
2012}
2013
2014impl<T: Clone + PartialEq + 'static> State for DropdownMenuState<T> {
2015 type Widget = DropdownMenu<T>;
2016 waft_widgets::state_accessors!();
2017
2018 fn init_state(self: Handle<Self>, app: &mut App) {
2019 let internal_focus_node = FocusNode::new(app);
2020 app.get_mut(self).internal_focus_node = Some(internal_focus_node);
2021 let widget_focus_node = self.widget(app).focus_node.clone();
2022 let focus_node_can_request_focus =
2023 widget_focus_node.map(|focus_node| focus_node.can_request_focus(app));
2024 let widget = self.widget(app);
2025 let enable_search = widget.enable_search;
2026 let entries = Rc::clone(&widget.dropdown_menu_entries);
2027 let state = app.get_mut(self);
2028 state.focus_node_can_request_focus = focus_node_can_request_focus;
2029 state.enable_search = enable_search;
2030 state.filtered_entries = entries;
2031 self.set_button_item_keys(app);
2032 self.update_menu_has_enabled_item(app);
2033 self.show_initial_selection(app);
2034 self.refresh_leading_padding(app);
2035 self.set_menu_controller(app);
2036 }
2037
2038 fn dispose(self: Handle<Self>, app: &mut App) {
2039 if let Some(controller) = app.get_mut(self).local_text_editing_controller.take() {
2040 controller.erase::<AnyTextEditingController>().dispose(app);
2041 }
2042 let internal_focus_node = self.internal_focus_node(app);
2043 FocusNodeLeaf::as_node(internal_focus_node).dispose(app);
2044 if let Some(focus_node) = app
2045 .get_mut(self)
2046 .local_trailing_icon_button_focus_node
2047 .take()
2048 {
2049 focus_node.as_node().dispose(app);
2050 }
2051 if let Some(states_controller) = app.get_mut(self).highlighted_item_states_controller.take()
2052 {
2053 states_controller.dispose(app);
2054 }
2055 }
2056
2057 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &DropdownMenu<T>) {
2058 let widget = self.widget(app).clone();
2059 if old_widget.controller != widget.controller
2060 && let Some(controller) = app.get_mut(self).local_text_editing_controller.take()
2061 {
2062 controller.erase::<AnyTextEditingController>().dispose(app);
2063 }
2064 if old_widget.enable_filter != widget.enable_filter && !widget.enable_filter {
2065 app.get_mut(self).enable_filter = false;
2066 }
2067 if old_widget.enable_search != widget.enable_search && !widget.enable_search {
2068 let state = app.get_mut(self);
2069 state.enable_search = widget.enable_search;
2070 state.current_highlight = None;
2071 }
2072 if !Rc::ptr_eq(
2073 &old_widget.dropdown_menu_entries,
2074 &widget.dropdown_menu_entries,
2075 ) {
2076 let state = app.get_mut(self);
2077 state.current_highlight = None;
2078 state.filtered_entries = Rc::clone(&widget.dropdown_menu_entries);
2079 self.set_button_item_keys(app);
2080 self.update_menu_has_enabled_item(app);
2081 }
2082 if !same_widget(&old_widget.leading_icon, &widget.leading_icon) {
2083 self.refresh_leading_padding(app);
2084 }
2085 if old_widget.initial_selection != widget.initial_selection {
2086 self.show_initial_selection(app);
2087 }
2088 if old_widget.menu_controller != widget.menu_controller {
2089 self.set_menu_controller(app);
2090 }
2091 if widget.focus_node != old_widget.focus_node {
2092 app.get_mut(self).focus_node_can_request_focus = widget
2093 .focus_node
2094 .as_ref()
2095 .map(|focus_node| focus_node.can_request_focus(app));
2096 }
2097 if old_widget.enabled && !widget.enabled {
2098 app.get_mut(self).focus_node_can_request_focus = widget
2099 .focus_node
2100 .as_ref()
2101 .map(|focus_node| focus_node.can_request_focus(app));
2102 }
2103 if !old_widget.enabled
2104 && widget.enabled
2105 && let Some(focus_node) = widget.focus_node.as_ref()
2106 && let Some(can_request_focus) = app.get(self).focus_node_can_request_focus
2107 {
2108 focus_node.set_can_request_focus(app, can_request_focus);
2109 }
2110 }
2111
2112 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2113 let use_material3 = Theme::of(app, context).use_material3;
2114 let text_direction = Directionality::of(app, context);
2115 if app.get(self).initial_menu.is_none() {
2116 let entries = Rc::clone(&self.widget(app).dropdown_menu_entries);
2117 let initial_menu = self.build_buttons(
2118 app,
2119 context,
2120 &entries,
2121 BuildButtonsOptions {
2122 text_direction,
2123 focused_index: None,
2124 enable_scroll_to_highlight: false,
2125 exclude_semantics: true,
2127 use_material3: Some(use_material3),
2128 },
2129 );
2130 app.get_mut(self).initial_menu = Some(initial_menu);
2131 }
2132 let theme = DropdownMenuTheme::of(app, context);
2133 let defaults = DropdownMenuDefaultsM3::new(app, context);
2134 let widget = self.widget(app).clone();
2135
2136 if app.get(self).enable_filter {
2137 let controller = self.effective_text_editing_controller(app);
2138 let filtered_entries = match &widget.filter_callback {
2139 Some(filter_callback) => {
2140 let entries = Rc::clone(&app.get(self).filtered_entries);
2141 let text = controller.text_value(app).to_owned();
2142 filter_callback(app, &entries, &text)
2143 }
2144 None => Self::filter(&widget.dropdown_menu_entries, controller.handle(), app),
2145 };
2146 app.get_mut(self).filtered_entries = Rc::from(filtered_entries);
2147 }
2148 self.update_menu_has_enabled_item(app);
2149
2150 if app.get(self).enable_search {
2151 if let Some(search_callback) = &widget.search_callback {
2152 let entries = Rc::clone(&app.get(self).filtered_entries);
2153 let text = self
2154 .effective_text_editing_controller(app)
2155 .text_value(app)
2156 .to_owned();
2157 app.get_mut(self).current_highlight = search_callback(app, &entries, &text);
2158 } else {
2159 let entries = Rc::clone(&app.get(self).filtered_entries);
2160 let should_update_current_highlight =
2161 self.should_update_current_highlight(app, &entries);
2162 if should_update_current_highlight {
2163 let controller = self.effective_text_editing_controller(app);
2164 app.get_mut(self).current_highlight =
2165 Self::search(&entries, controller.handle(), app);
2166 }
2167 }
2168 if app.get(self).current_highlight.is_some() {
2169 self.scroll_to_highlight(app);
2170 }
2171 }
2172
2173 let filtered_entries = Rc::clone(&app.get(self).filtered_entries);
2174 let current_highlight = app.get(self).current_highlight;
2175 let menu = self.build_buttons(
2176 app,
2177 context,
2178 &filtered_entries,
2179 BuildButtonsOptions {
2180 text_direction,
2181 focused_index: current_highlight,
2182 enable_scroll_to_highlight: true,
2183 exclude_semantics: false,
2184 use_material3: Some(use_material3),
2185 },
2186 );
2187
2188 let base_text_style = widget
2189 .text_style
2190 .clone()
2191 .or_else(|| theme.text_style.clone())
2192 .or_else(|| defaults.text_style(app));
2193 let disabled_color = theme
2194 .disabled_color
2195 .or_else(|| defaults.disabled_color(app));
2196 let effective_text_style = if widget.enabled {
2197 base_text_style
2198 } else {
2199 Some(match base_text_style {
2200 Some(base_text_style) => {
2201 let base_text_style = base_text_style.copy_with();
2202 match disabled_color {
2203 Some(disabled_color) => base_text_style.color(disabled_color),
2204 None => base_text_style,
2205 }
2206 }
2207 None => match disabled_color {
2208 Some(disabled_color) => TextStyle::new().color(disabled_color),
2209 None => TextStyle::new(),
2210 },
2211 })
2212 };
2213
2214 let mut effective_menu_style = widget
2215 .menu_style
2216 .clone()
2217 .or_else(|| theme.menu_style.clone())
2218 .unwrap_or_else(|| {
2219 defaults
2220 .menu_style(app)
2221 .expect("the defaults have a menu style")
2222 });
2223
2224 let final_maximum_size: Option<WidgetStatePropertyRef<Option<Size>>> =
2227 match widget.menu_height {
2228 Some(menu_height) => Some(Rc::new(WidgetStatePropertyAll::new(Some(Size::new(
2229 f64::INFINITY,
2230 menu_height,
2231 ))))),
2232 None => effective_menu_style.maximum_size.clone(),
2233 };
2234 let anchor_key = app.get(self).anchor_key.clone();
2235 let anchor_width = Self::get_width(app, &anchor_key);
2236 let minimum_width = widget.width.or(anchor_width);
2237 if let Some(minimum_width) = minimum_width {
2238 let maximum_size = final_maximum_size.clone();
2239 effective_menu_style.minimum_size = Some(
2240 <dyn WidgetStateProperty<Option<Size>>>::resolve_with(move |states| {
2241 let effective_maximum_width = maximum_size
2242 .as_ref()
2243 .and_then(|maximum_size| maximum_size.resolve(states))
2244 .map(|size| size.width());
2245 Some(Size::new(
2246 minimum_width.min(effective_maximum_width.unwrap_or(minimum_width)),
2247 0.0,
2248 ))
2249 }),
2250 );
2251 }
2252
2253 if widget.menu_height.is_some() {
2254 effective_menu_style.maximum_size = final_maximum_size;
2255 }
2256 let effective_input_decoration_theme = widget
2257 .input_decoration_theme
2258 .clone()
2259 .or_else(|| theme.input_decoration_theme.clone())
2260 .unwrap_or_else(|| {
2261 defaults
2262 .input_decoration_theme(app)
2263 .expect("the defaults have an input decoration theme")
2264 });
2265
2266 let effective_mouse_cursor: Option<MouseCursorRef> = match widget.enabled {
2267 true => Some(if self.is_button(app) {
2268 SystemMouseCursors::CLICK.into()
2269 } else {
2270 SystemMouseCursors::TEXT.into()
2271 }),
2272 false => None,
2273 };
2274
2275 let controller = self.menu_controller(app).clone();
2276 let anchor_arguments = Rc::new(AnchorBuildArguments {
2277 effective_input_decoration_theme,
2278 effective_text_style,
2279 effective_mouse_cursor,
2280 });
2281 let mut menu_anchor = MenuAnchor::new(menu)
2282 .style(effective_menu_style)
2283 .reserved_padding(EdgeInsetsGeometry::ZERO)
2284 .controller(controller)
2285 .cross_axis_unconstrained(false)
2286 .builder(move |app, context, controller, _child| {
2287 self.build_anchor(app, context, controller, &anchor_arguments)
2288 });
2289 menu_anchor.alignment_offset = widget.alignment_offset;
2290 let mut menu_anchor = menu_anchor.into_widget();
2291
2292 if let Some(padding) = widget.expanded_insets {
2293 menu_anchor = Padding::new(
2294 padding.clamp(
2296 &EdgeInsetsGeometry::ZERO,
2297 &EdgeInsetsGeometry::only(f64::INFINITY, 0.0, f64::INFINITY, 0.0).add(
2298 EdgeInsetsDirectional::only(f64::INFINITY, 0.0, f64::INFINITY, 0.0).into(),
2299 ),
2300 ),
2301 )
2302 .child(menu_anchor)
2303 .into_widget();
2304 }
2305
2306 let menu_anchor = Align::new()
2311 .alignment(AlignmentGeometry::TOP_START)
2312 .width_factor(1.0)
2313 .height_factor(1.0)
2314 .child(menu_anchor);
2315
2316 let actions = self.build_actions(app);
2317 let internal_focus_node = app
2318 .get(self)
2319 .internal_focus_node
2320 .as_ref()
2321 .expect("init_state makes the internal focus node")
2322 .erase::<AnyFocusNode>();
2323 Actions::new(
2324 actions,
2325 Stack::new().children([
2326 Shortcuts::new(
2328 unfocused_text_field_shortcuts(),
2329 Focus::new(SizedBox::shrink())
2330 .focus_node(internal_focus_node)
2331 .skip_traversal(true),
2332 )
2333 .into_widget(),
2334 menu_anchor.into_widget(),
2335 ]),
2336 )
2337 .into_widget()
2338 }
2339}
2340
2341impl<T: Clone + PartialEq + 'static> Debug for DropdownMenuState<T> {
2342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2343 f.debug_struct("DropdownMenuState")
2344 .field("current_highlight", &self.current_highlight)
2345 .field("enable_filter", &self.enable_filter)
2346 .field("enable_search", &self.enable_search)
2347 .finish_non_exhaustive()
2348 }
2349}
2350
2351#[derive(Clone, Copy, Debug)]
2360struct ArrowUpIntent;
2361
2362impl Intent for ArrowUpIntent {
2363 fn as_any(&self) -> &dyn Any {
2364 self
2365 }
2366}
2367
2368#[derive(Clone, Copy, Debug)]
2370struct ArrowDownIntent;
2371
2372impl Intent for ArrowDownIntent {
2373 fn as_any(&self) -> &dyn Any {
2374 self
2375 }
2376}
2377
2378#[derive(Clone, Copy, Debug)]
2380struct EnterIntent;
2381
2382impl Intent for EnterIntent {
2383 fn as_any(&self) -> &dyn Any {
2384 self
2385 }
2386}
2387
2388#[derive(Debug)]
2390struct DropdownMenuBody {
2391 children: Vec<WidgetRef>,
2392 width: Option<f64>,
2393}
2394
2395impl RenderObjectWidget for DropdownMenuBody {
2396 type RenderObject = RenderDropdownMenuBody;
2397
2398 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
2399 RenderDropdownMenuBody::new(app, self.width).as_object()
2400 }
2401
2402 fn update_render_object(
2403 &self,
2404 app: &mut App,
2405 _context: BuildContext,
2406 render_object: RenderHandle<RenderDropdownMenuBody>,
2407 ) {
2408 render_object.set_width(app, self.width);
2409 }
2410}
2411
2412impl MultiChildRenderObjectWidget for DropdownMenuBody {
2413 fn children(&self) -> &[WidgetRef] {
2414 &self.children
2415 }
2416}
2417
2418#[derive(Debug, Default)]
2420struct DropdownMenuBodyParentData {
2421 box_parent_data: BoxParentData,
2422 container_parent_data: ContainerParentData<AnyRenderBox>,
2423}
2424
2425impl DropdownMenuBodyParentData {
2426 const fn new() -> DropdownMenuBodyParentData {
2427 DropdownMenuBodyParentData {
2428 box_parent_data: BoxParentData::new(),
2429 container_parent_data: ContainerParentData::new(),
2430 }
2431 }
2432}
2433
2434impl ParentData for DropdownMenuBodyParentData {
2435 fn detach(&mut self) {
2436 ContainerParentDataMixin::detach(self);
2437 }
2438
2439 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
2440 if id == TypeId::of::<DropdownMenuBodyParentData>() {
2441 return Some(self);
2442 }
2443 self.box_parent_data.provide(id)
2444 }
2445
2446 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
2447 if id == TypeId::of::<DropdownMenuBodyParentData>() {
2448 return Some(self);
2449 }
2450 self.box_parent_data.provide_mut(id)
2451 }
2452}
2453
2454impl ContainerParentDataMixin for DropdownMenuBodyParentData {
2455 type ChildType = AnyRenderBox;
2456
2457 fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
2458 &self.container_parent_data
2459 }
2460
2461 fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
2462 &mut self.container_parent_data
2463 }
2464}
2465
2466impl ContainerBoxParentData for DropdownMenuBodyParentData {
2467 fn box_parent_data(&self) -> &BoxParentData {
2468 &self.box_parent_data
2469 }
2470
2471 fn box_parent_data_mut(&mut self) -> &mut BoxParentData {
2472 &mut self.box_parent_data
2473 }
2474}
2475
2476impl fmt::Display for DropdownMenuBodyParentData {
2477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2478 fmt::Display::fmt(&self.box_parent_data, f)
2479 }
2480}
2481
2482struct RenderDropdownMenuBody {
2484 render_object: RenderObjectData,
2485 render_box: RenderBoxData,
2486 container: ContainerRenderObjectData<AnyRenderBox>,
2487 width: Option<f64>,
2488}
2489
2490impl RenderDropdownMenuBody {
2491 fn new(app: &mut App, width: Option<f64>) -> RenderHandle<RenderDropdownMenuBody> {
2492 RenderHandle::new_box(
2493 app,
2494 RenderDropdownMenuBody {
2495 render_object: RenderObjectData::new(),
2496 render_box: RenderBoxData::new(),
2497 container: ContainerRenderObjectData::new(),
2498 width,
2499 },
2500 )
2501 }
2502
2503 fn width(self: RenderHandle<Self>, app: &App) -> Option<f64> {
2504 self.get(app).width
2505 }
2506
2507 fn set_width(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
2508 if self.get(app).width == value {
2509 return;
2510 }
2511 self.get_mut(app).width = value;
2512 self.mark_needs_layout(app);
2513 }
2514
2515 fn inner_constraints(
2517 self: RenderHandle<Self>,
2518 app: &mut App,
2519 constraints: BoxConstraints,
2520 ) -> BoxConstraints {
2521 let intrinsic_width = match self.width(app) {
2522 Some(width) => width,
2523 None => self.get_max_intrinsic_width(app, constraints.max_height),
2524 };
2525 let width_constraint = intrinsic_width.min(constraints.max_width);
2526 BoxConstraints::new()
2527 .max_width(width_constraint)
2528 .max_height(self.get_max_intrinsic_height(app, width_constraint))
2529 }
2530
2531 fn compute_intrinsic_width(
2534 self: RenderHandle<Self>,
2535 app: &mut App,
2536 height: f64,
2537 child_intrinsic_width: fn(AnyRenderBox, &mut App, f64) -> f64,
2538 ) -> f64 {
2539 let first_child = self.first_child(app);
2540 let last_child = self.last_child(app);
2541 let mut child = first_child;
2542 let mut width: f64 = 0.0;
2543 while let Some(current) = child {
2544 if Some(current) == first_child {
2545 child = self.child_after(app, current);
2546 continue;
2547 }
2548 let intrinsic_width = child_intrinsic_width(current, app, height);
2549 if Some(current) == last_child {
2551 width += intrinsic_width;
2552 }
2553 if Some(current) == self.child_before(app, last_child.expect("a last child")) {
2555 width += intrinsic_width;
2556 }
2557 width = width.max(intrinsic_width);
2558 child = self.child_after(app, current);
2559 }
2560
2561 width.max(K_MINIMUM_WIDTH)
2562 }
2563}
2564
2565impl ContainerRenderObjectMixin for RenderDropdownMenuBody {
2566 type ChildType = AnyRenderBox;
2567 type ParentDataType = DropdownMenuBodyParentData;
2568
2569 fn container_data(
2570 self: RenderHandle<Self>,
2571 app: &App,
2572 ) -> &ContainerRenderObjectData<AnyRenderBox> {
2573 &self.get(app).container
2574 }
2575
2576 fn container_data_mut(
2577 self: RenderHandle<Self>,
2578 app: &mut App,
2579 ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
2580 &mut self.get_mut(app).container
2581 }
2582}
2583
2584impl RenderBoxContainerDefaultsMixin for RenderDropdownMenuBody {}
2585
2586impl RenderObject for RenderDropdownMenuBody {
2587 waft_rendering::render_object_accessors!();
2588
2589 fn debug_describe_children(
2590 self: RenderHandle<Self>,
2591 app: &App,
2592 ) -> Vec<Rc<dyn DiagnosticsNode>> {
2593 ContainerRenderObjectMixin::debug_describe_children(self, app)
2594 }
2595
2596 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2597 let constraints = self.constraints(app);
2598 let mut max_width: f64 = 0.0;
2599 let mut max_height: Option<f64> = None;
2600 let first_child = self.first_child(app);
2601 let mut child = first_child;
2602
2603 let inner_constraints = self.inner_constraints(app, constraints);
2604 while let Some(current) = child {
2605 if Some(current) == first_child {
2606 current.layout(app, inner_constraints, true);
2607 max_height.get_or_insert(current.size(app).height());
2608 child = self.child_after(app, current);
2609 continue;
2610 }
2611 current.layout(app, inner_constraints, true);
2612 current
2613 .as_object()
2614 .parent_data_of_mut::<DropdownMenuBodyParentData>(app)
2615 .set_offset(Offset::ZERO);
2616 max_width = max_width.max(current.size(app).width());
2617 max_height.get_or_insert(current.size(app).height());
2618 child = self.child_after(app, current);
2619 }
2620
2621 let max_height = max_height.expect("a dropdown menu body has children");
2622 max_width = max_width.max(K_MINIMUM_WIDTH);
2623 let width = self.width(app).unwrap_or(max_width);
2624 self.set_size(app, constraints.constrain(Size::new(width, max_height)));
2625 }
2626
2627 fn visit_children(
2628 self: RenderHandle<Self>,
2629 app: &App,
2630 visitor: &mut dyn FnMut(AnyRenderObject),
2631 ) {
2632 ContainerRenderObjectMixin::visit_children(self, app, visitor)
2633 }
2634
2635 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
2636 ContainerRenderObjectMixin::did_attach(self, app, owner)
2637 }
2638
2639 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2640 ContainerRenderObjectMixin::did_detach(self, app)
2641 }
2642
2643 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
2644 ContainerRenderObjectMixin::redepth_children(self, app)
2645 }
2646
2647 fn paint(
2648 self: RenderHandle<Self>,
2649 app: &mut App,
2650 context: &mut PaintingContext,
2651 offset: Offset,
2652 ) {
2653 if let Some(child) = self.first_child(app) {
2654 let child_offset = child
2655 .as_object()
2656 .parent_data_of::<DropdownMenuBodyParentData>(app)
2657 .offset();
2658 context.paint_child(app, child.as_object(), offset + child_offset);
2659 }
2660 }
2661}
2662
2663impl RenderBox for RenderDropdownMenuBody {
2664 waft_rendering::render_box_accessors!();
2665
2666 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2667 if !child.parent_data_is::<DropdownMenuBodyParentData>(app) {
2668 child.set_parent_data(app, DropdownMenuBodyParentData::new());
2669 }
2670 }
2671
2672 fn compute_dry_layout(
2673 self: RenderHandle<Self>,
2674 app: &mut App,
2675 constraints: BoxConstraints,
2676 ) -> Size {
2677 let mut max_width: f64 = 0.0;
2678 let mut max_height: Option<f64> = None;
2679 let first_child = self.first_child(app);
2680 let mut child = first_child;
2681 let inner_constraints = self.inner_constraints(app, constraints);
2682
2683 while let Some(current) = child {
2684 let child_size = current.get_dry_layout(app, inner_constraints);
2685
2686 if Some(current) != first_child {
2689 max_width = max_width.max(child_size.width());
2690 }
2691
2692 max_height.get_or_insert(child_size.height());
2693 child = self.child_after(app, current);
2694 }
2695
2696 let max_height = max_height.expect("a dropdown menu body has children");
2697 max_width = max_width.max(K_MINIMUM_WIDTH);
2698 let width = self.width(app).unwrap_or(max_width);
2699 constraints.constrain(Size::new(width, max_height))
2700 }
2701
2702 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2703 self.compute_intrinsic_width(app, height, |child, app, height| {
2704 child.get_min_intrinsic_width(app, height)
2705 })
2706 }
2707
2708 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2709 self.compute_intrinsic_width(app, height, |child, app, height| {
2710 child.get_max_intrinsic_width(app, height)
2711 })
2712 }
2713
2714 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2715 let mut height: f64 = 0.0;
2716 if let Some(child) = self.first_child(app) {
2717 height = height.max(child.get_min_intrinsic_height(app, width));
2718 }
2719 height
2720 }
2721
2722 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2723 let mut height: f64 = 0.0;
2724 if let Some(child) = self.first_child(app) {
2725 height = height.max(child.get_max_intrinsic_height(app, width));
2726 }
2727 height
2728 }
2729
2730 fn hit_test_children(
2731 self: RenderHandle<Self>,
2732 app: &mut App,
2733 result: &mut BoxHitTestResult<'_>,
2734 position: Offset,
2735 ) -> bool {
2736 if let Some(child) = self.first_child(app) {
2737 let offset = child
2738 .as_object()
2739 .parent_data_of::<DropdownMenuBodyParentData>(app)
2740 .offset();
2741 let is_hit =
2742 result.add_with_paint_offset(Some(offset), position, |result, transformed| {
2743 debug_assert_eq!(transformed, position - offset);
2744 child.hit_test(app, result, transformed)
2745 });
2746 if is_hit {
2747 return true;
2748 }
2749 }
2750 false
2751 }
2752}
2753
2754struct DropdownMenuDefaultsM3 {
2757 dropdown_menu_theme_data: DropdownMenuThemeData,
2759 context: DefaultsContext,
2760}
2761
2762impl DropdownMenuDefaultsM3 {
2763 #[expect(deprecated, reason = "Dart calls the deprecated `withOpacity`")]
2764 fn new(app: &mut App, context: BuildContext) -> DropdownMenuDefaultsM3 {
2765 let disabled_color = Theme::of(app, context)
2766 .color_scheme
2767 .on_surface()
2768 .with_opacity(0.38);
2769 DropdownMenuDefaultsM3 {
2770 dropdown_menu_theme_data: DropdownMenuThemeData::new().disabled_color(disabled_color),
2771 context: DefaultsContext::new(context),
2772 }
2773 }
2774}
2775
2776impl DropdownMenuThemeDataGetters for DropdownMenuDefaultsM3 {
2777 fn dropdown_menu_theme_data(&self) -> &DropdownMenuThemeData {
2778 &self.dropdown_menu_theme_data
2779 }
2780
2781 fn text_style(&self, app: &mut App) -> Option<TextStyle> {
2782 self.context.text_theme(app).body_large.clone()
2783 }
2784
2785 fn menu_style(&self, _app: &mut App) -> Option<MenuStyle> {
2786 Some(
2787 MenuStyle::new()
2788 .minimum_size(Rc::new(WidgetStatePropertyAll::new(Some(Size::new(
2789 K_MINIMUM_WIDTH,
2790 0.0,
2791 )))))
2792 .maximum_size(Rc::new(WidgetStatePropertyAll::new(Some(Size::INFINITE))))
2793 .visual_density(VisualDensity::STANDARD),
2794 )
2795 }
2796
2797 fn input_decoration_theme(&self, _app: &mut App) -> Option<InputDecorationThemeData> {
2798 Some(InputDecorationThemeData::new().border(OutlineInputBorder::new()))
2799 }
2800}
2801
2802#[cfg(test)]
2803pub(crate) mod tests {
2804 use waft_embedder::Rect;
2808 use waft_embedder::{Matrix4, TextBaseline};
2809 use waft_rendering::{
2810 RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
2811 };
2812 use waft_services::PhysicalKeyboardKey;
2813 use waft_services::TextInputClient;
2814 use waft_widgets::SingleChildRenderObjectWidget;
2815 use waft_widgets::{AnyElement, EditableText, EditableTextState};
2816
2817 use waft_widgets::testing::{
2818 TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_n_widgets,
2819 finds_nothing, finds_one_widget, test_widgets, test_widgets_variant,
2820 };
2821
2822 use super::*;
2823 use crate::colors::Colors;
2824 use crate::material::Material;
2825 use crate::menu_anchor::MenuPanel;
2826 use crate::scaffold::Scaffold;
2827 use crate::test_support::{PaintInspection, material_app};
2828 use crate::theme_data::ThemeData;
2829 use crate::tooltip::tests::m3;
2830 use waft_widgets::FocusNodeLeaf;
2831
2832 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
2835 pub(crate) enum TestMenu {
2836 MainMenu0,
2837 MainMenu1,
2838 MainMenu2,
2839 MainMenu3,
2840 MainMenu4,
2841 MainMenu5,
2842 }
2843
2844 impl TestMenu {
2845 pub(crate) const VALUES: [TestMenu; 6] = [
2846 TestMenu::MainMenu0,
2847 TestMenu::MainMenu1,
2848 TestMenu::MainMenu2,
2849 TestMenu::MainMenu3,
2850 TestMenu::MainMenu4,
2851 TestMenu::MainMenu5,
2852 ];
2853
2854 pub(crate) fn label(self) -> &'static str {
2855 match self {
2856 TestMenu::MainMenu0 => "Item 0",
2857 TestMenu::MainMenu1 => "Menu 1",
2858 TestMenu::MainMenu2 => "Item 2",
2859 TestMenu::MainMenu3 => "Item 3",
2860 TestMenu::MainMenu4 => "Item 4",
2861 TestMenu::MainMenu5 => "Item 5",
2862 }
2863 }
2864 }
2865
2866 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
2867 enum ShortMenu {
2868 Item0,
2869 Item1,
2870 Item2,
2871 }
2872
2873 impl ShortMenu {
2874 fn label(self) -> &'static str {
2875 match self {
2876 ShortMenu::Item0 => "I0",
2877 ShortMenu::Item1 => "I1",
2878 ShortMenu::Item2 => "I2",
2879 }
2880 }
2881 }
2882
2883 pub(crate) fn menu_children() -> Rc<[DropdownMenuEntry<TestMenu>]> {
2885 TestMenu::VALUES
2886 .iter()
2887 .map(|value| DropdownMenuEntry::new(*value, value.label()))
2888 .collect()
2889 }
2890
2891 fn short_menu_items() -> Rc<[DropdownMenuEntry<ShortMenu>]> {
2892 [ShortMenu::Item0, ShortMenu::Item1, ShortMenu::Item2]
2893 .iter()
2894 .map(|value| DropdownMenuEntry::new(*value, value.label()))
2895 .collect()
2896 }
2897
2898 #[derive(Clone, Default)]
2900 struct BuildTest {
2901 width: Option<f64>,
2902 menu_height: Option<f64>,
2903 leading_icon: Option<WidgetRef>,
2904 label: Option<WidgetRef>,
2905 decoration_theme: Option<InputDecorationThemeData>,
2906 }
2907
2908 impl BuildTest {
2909 fn build<T: Clone + PartialEq + 'static>(
2911 &self,
2912 theme: ThemeData,
2913 entries: Rc<[DropdownMenuEntry<T>]>,
2914 ) -> WidgetRef {
2915 let mut menu = DropdownMenu::new(entries);
2916 menu.label = self.label.clone();
2917 menu.leading_icon = self.leading_icon.clone();
2918 menu.width = self.width;
2919 menu.menu_height = self.menu_height;
2920 menu.input_decoration_theme = self.decoration_theme.clone();
2921 material_app(theme, Scaffold::new().body(menu).into_widget())
2922 }
2923 }
2924
2925 fn only(found: Vec<AnyElement>) -> AnyElement {
2928 assert_eq!(found.len(), 1, "one widget found");
2929 found[0]
2930 }
2931
2932 fn ancestors_of_type<W: 'static>(
2934 tester: &WidgetTester,
2935 element: AnyElement,
2936 ) -> Vec<AnyElement> {
2937 let ancestors = tester.ancestors(element);
2938 let app = tester.cell.borrow();
2939 ancestors
2940 .into_iter()
2941 .filter(|ancestor| {
2942 waft_widgets::downcast_widget::<W>(&**ancestor.widget(&app)).is_some()
2943 })
2944 .collect()
2945 }
2946
2947 fn widgets_with_text<W: 'static>(tester: &WidgetTester, text: &str) -> Vec<AnyElement> {
2949 let texts = find::text(text).evaluate(tester);
2950 find::by_type::<W>()
2951 .evaluate(tester)
2952 .into_iter()
2953 .filter(|widget| {
2954 texts
2955 .iter()
2956 .any(|text| tester.ancestors(*text).contains(widget))
2957 })
2958 .collect()
2959 }
2960
2961 fn widgets_with_icon<W: 'static>(
2963 tester: &WidgetTester,
2964 icon: &waft_widgets::IconData,
2965 ) -> Vec<AnyElement> {
2966 let icons: Vec<AnyElement> = find::by_type::<Icon>()
2967 .evaluate(tester)
2968 .into_iter()
2969 .filter(|element| {
2970 tester.widget(*element, |widget: &Icon| widget.icon.as_ref() == Some(icon))
2971 })
2972 .collect();
2973 find::by_type::<W>()
2974 .evaluate(tester)
2975 .into_iter()
2976 .filter(|widget| {
2977 icons
2978 .iter()
2979 .any(|icon| tester.ancestors(*icon).contains(widget))
2980 })
2981 .collect()
2982 }
2983
2984 fn find_menu_item_button(tester: &WidgetTester, label: &str) -> AnyElement {
2987 *widgets_with_text::<MenuItemButton>(tester, label)
2988 .last()
2989 .expect("a menu item button with that label")
2990 }
2991
2992 fn button_material<R>(
2994 tester: &WidgetTester,
2995 label: &str,
2996 read: impl FnOnce(&Material) -> R,
2997 ) -> R {
2998 let button = find_menu_item_button(tester, label);
2999 let material = only(tester.descendants_of_type::<Material>(button));
3000 tester.widget::<Material, R>(material, read)
3001 }
3002
3003 #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
3005 fn is_item_highlighted(tester: &WidgetTester, theme: &ThemeData, label: &str) -> bool {
3006 let color = button_material(tester, label, |material| material.color);
3007 color == Some(theme.color_scheme.on_surface().with_opacity(0.12))
3008 }
3009
3010 fn menu_material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
3012 let panel = tester.element(find::by_type::<MenuPanel>());
3013 let material = tester.descendants_of_type::<Material>(panel)[0];
3014 tester.widget::<Material, R>(material, read)
3015 }
3016
3017 fn first<W: 'static>(tester: &WidgetTester) -> AnyElement {
3018 find::by_type::<W>().evaluate(tester)[0]
3019 }
3020
3021 fn tap(tester: &mut WidgetTester, element: AnyElement) {
3023 let center = tester.get_rect(element).center();
3024 tester.tap_at(center, 1);
3025 }
3026
3027 fn tap_dropdown_menu<T: 'static>(tester: &mut WidgetTester) {
3029 let menu = dropdown_menu::<T>(tester);
3030 tap(tester, menu);
3031 }
3032
3033 fn tap_first<W: 'static>(tester: &mut WidgetTester) {
3035 let element = first::<W>(tester);
3036 tap(tester, element);
3037 }
3038
3039 fn pump(tester: &mut WidgetTester) {
3040 tester.pump();
3041 }
3042
3043 fn send_key(tester: &mut WidgetTester, logical: LogicalKeyboardKey) {
3045 let physical = match logical {
3046 LogicalKeyboardKey::ARROW_DOWN => PhysicalKeyboardKey::ARROW_DOWN,
3047 LogicalKeyboardKey::ARROW_UP => PhysicalKeyboardKey::ARROW_UP,
3048 LogicalKeyboardKey::ARROW_LEFT => PhysicalKeyboardKey::ARROW_LEFT,
3049 LogicalKeyboardKey::ARROW_RIGHT => PhysicalKeyboardKey::ARROW_RIGHT,
3050 LogicalKeyboardKey::TAB => PhysicalKeyboardKey::TAB,
3051 LogicalKeyboardKey::ESCAPE => PhysicalKeyboardKey::ESCAPE,
3052 LogicalKeyboardKey::ENTER => PhysicalKeyboardKey::ENTER,
3053 LogicalKeyboardKey::SPACE => PhysicalKeyboardKey::SPACE,
3054 _ => panic!("no physical key for {logical:?} in this kit"),
3055 };
3056 tester.send_key_event(physical, logical);
3057 }
3058
3059 fn editable_state(tester: &WidgetTester) -> Handle<EditableTextState> {
3060 first::<EditableText>(tester)
3061 .state_handle::<EditableTextState>(&tester.cell.borrow())
3062 .expect("an EditableText state")
3063 }
3064
3065 fn text_field<R>(tester: &WidgetTester, read: impl FnOnce(&TextField) -> R) -> R {
3066 tester.widget::<TextField, R>(first::<TextField>(tester), read)
3067 }
3068
3069 fn editable<R>(tester: &WidgetTester, read: impl FnOnce(&EditableText) -> R) -> R {
3070 tester.widget::<EditableText, R>(first::<EditableText>(tester), read)
3071 }
3072
3073 fn pump_app(tester: &mut WidgetTester, root: impl FnOnce(&mut App) -> WidgetRef) {
3074 let root = root(&mut tester.cell.borrow_mut());
3075 tester.pump_widget(root);
3076 }
3077
3078 fn theme(tester: &WidgetTester) -> ThemeData {
3079 m3(&tester.cell.borrow())
3080 }
3081
3082 fn the_menu<T: Clone + PartialEq + 'static>(
3083 theme: ThemeData,
3084 menu: DropdownMenu<T>,
3085 ) -> WidgetRef {
3086 material_app(theme, Scaffold::new().body(menu).into_widget())
3087 }
3088
3089 #[test]
3093 fn a_dropdown_menu_takes_its_defaults_from_the_theme() {
3094 test_widgets(|tester| {
3095 let theme = theme(tester);
3096 tester.pump_widget(BuildTest::default().build(theme.clone(), menu_children()));
3097
3098 let body_large = theme.text_theme.body_large.clone().expect("a body large");
3099 editable(tester, |editable| {
3100 assert_eq!(editable.style.color, body_large.color);
3101 assert_eq!(editable.style.background, body_large.background);
3102 assert_eq!(editable.style.shadows, body_large.shadows);
3103 assert_eq!(editable.style.decoration, body_large.decoration);
3104 assert_eq!(editable.style.word_spacing, body_large.word_spacing);
3105 assert_eq!(editable.style.font_size, Some(16.0));
3106 assert_eq!(editable.style.height, Some(1.5));
3107 });
3108 text_field(tester, |text_field| {
3109 let decoration = text_field.decoration.as_ref().expect("a decoration");
3110 assert!(
3111 decoration
3112 .border
3113 .as_ref()
3114 .is_some_and(|border| border.eq_shape(&OutlineInputBorder::new()))
3115 );
3116 let style = text_field.style.as_ref().expect("a style");
3117 assert_eq!(style.font_size, Some(16.0));
3118 assert_eq!(style.height, Some(1.5));
3119 });
3120
3121 let icon_button = widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_down())[0];
3122 tap(tester, icon_button);
3123 pump(tester);
3124 expect(tester, &find::by_type::<MenuAnchor>(), finds_one_widget());
3125
3126 menu_material(tester, |material| {
3127 assert_eq!(material.color, Some(theme.color_scheme.surface_container()));
3128 assert_eq!(material.shadow_color, Some(theme.color_scheme.shadow()));
3129 assert_eq!(material.surface_tint_color, Some(Colors::TRANSPARENT));
3130 assert_eq!(material.elevation, 3.0);
3131 assert!(material.shape.as_ref().is_some_and(|shape| shape.eq_shape(
3132 &waft_painting::RoundedRectangleBorder::new(
3133 waft_painting::BorderSide::NONE,
3134 waft_painting::BorderRadiusGeometry::all(waft_embedder::Radius::circular(
3135 4.0
3136 )),
3137 )
3138 )));
3139 });
3140
3141 button_material(tester, TestMenu::MainMenu0.label(), |material| {
3142 assert_eq!(material.color, Some(Colors::TRANSPARENT));
3143 assert_eq!(material.elevation, 0.0);
3144 assert!(material.shape.as_ref().is_some_and(|shape| {
3145 shape.eq_shape(&waft_painting::RoundedRectangleBorder::default())
3146 }));
3147 let text_style = material.text_style.as_ref().expect("a text style");
3148 assert_eq!(
3149 text_style.color,
3150 Some(theme.color_scheme.on_surface().into())
3151 );
3152 assert_eq!(text_style.font_size, Some(14.0));
3153 assert_eq!(text_style.height, Some(1.43));
3154 });
3155 });
3156 }
3157
3158 const FOCUSED_BACKGROUND_COLOR: Color = Color::new(0xffff0000);
3166 const FOCUSED_FOREGROUND_COLOR: Color = Color::new(0xff00ff00);
3167 const FOCUSED_ICON_COLOR: Color = Color::new(0xff0000ff);
3168 const FOCUSED_OVERLAY_COLOR: Color = Color::new(0xffff00ff);
3169 const DEFAULT_BACKGROUND_COLOR: Color = Color::new(0xff00ffff);
3170 const DEFAULT_FOREGROUND_COLOR: Color = Color::new(0xff000000);
3171 const DEFAULT_ICON_COLOR: Color = Color::new(0xffffffff);
3172 const DEFAULT_OVERLAY_COLOR: Color = Color::new(0xffffff00);
3173
3174 fn focused_or(focused: Color, default: Color) -> WidgetStatePropertyRef<Option<Color>> {
3176 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
3177 if states.contains(&WidgetState::Focused) {
3178 return Some(focused);
3179 }
3180 Some(default)
3181 })
3182 }
3183
3184 fn custom_button_style() -> ButtonStyle {
3186 ButtonStyle::new()
3187 .background_color(focused_or(
3188 FOCUSED_BACKGROUND_COLOR,
3189 DEFAULT_BACKGROUND_COLOR,
3190 ))
3191 .foreground_color(focused_or(
3192 FOCUSED_FOREGROUND_COLOR,
3193 DEFAULT_FOREGROUND_COLOR,
3194 ))
3195 .icon_color(focused_or(FOCUSED_ICON_COLOR, DEFAULT_ICON_COLOR))
3196 .overlay_color(focused_or(FOCUSED_OVERLAY_COLOR, DEFAULT_OVERLAY_COLOR))
3197 }
3198
3199 fn styled_menu_entries(style: &ButtonStyle) -> Rc<[DropdownMenuEntry<TestMenu>]> {
3201 menu_children_with_icons()
3202 .iter()
3203 .cloned()
3204 .map(|entry| entry.style(style.clone()))
3205 .collect()
3206 }
3207
3208 fn item_icon_color(tester: &WidgetTester, key: &KeyRef) -> Option<Color> {
3210 let icon = *find_by_key(tester, key).last().expect("an icon keyed so");
3211 tester.glyph_style(icon).color.as_deref().copied()
3212 }
3213
3214 fn open_styled_menu(
3216 tester: &mut WidgetTester,
3217 theme: ThemeData,
3218 entries: Rc<[DropdownMenuEntry<TestMenu>]>,
3219 selected_item: TestMenu,
3220 ) {
3221 tester.pump_widget(the_menu(
3222 theme,
3223 DropdownMenu::new(entries).initial_selection(selected_item),
3224 ));
3225
3226 tap_dropdown_menu::<TestMenu>(tester);
3228 pump(tester);
3229 }
3230
3231 fn item_colors(
3234 tester: &WidgetTester,
3235 item: TestMenu,
3236 ) -> (Option<Color>, Option<Color>, Option<Color>) {
3237 let (color, text_color) = button_material(tester, item.label(), |material| {
3238 (
3239 material.color,
3240 material
3241 .text_style
3242 .as_ref()
3243 .and_then(|style| style.color.as_deref().copied()),
3244 )
3245 });
3246 (
3247 color,
3248 text_color,
3249 item_icon_color(tester, &leading_icon_key(item)),
3250 )
3251 }
3252
3253 #[test]
3255 #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
3256 fn item_style_defaults_are_correct() {
3257 test_widgets(|tester| {
3258 let selected_item = TestMenu::MainMenu3;
3259 let non_selected_item = TestMenu::MainMenu2;
3260 let theme = theme(tester);
3261 open_styled_menu(
3262 tester,
3263 theme.clone(),
3264 menu_children_with_icons(),
3265 selected_item,
3266 );
3267
3268 let on_surface = theme.color_scheme.on_surface();
3269 let on_surface_variant = theme.color_scheme.on_surface_variant();
3270 assert_eq!(
3271 item_colors(tester, selected_item),
3272 (
3273 Some(on_surface.with_opacity(0.12)),
3274 Some(on_surface),
3275 Some(on_surface_variant)
3276 )
3277 );
3278 assert_eq!(
3279 item_colors(tester, non_selected_item),
3280 (
3281 Some(Colors::TRANSPARENT),
3282 Some(on_surface),
3283 Some(on_surface_variant)
3284 )
3285 );
3286 });
3287 }
3288
3289 fn assert_custom_button_style(tester: &mut WidgetTester) {
3291 let selected_item = TestMenu::MainMenu3;
3292 let non_selected_item = TestMenu::MainMenu2;
3293 assert_eq!(
3294 item_colors(tester, selected_item),
3295 (
3296 Some(FOCUSED_BACKGROUND_COLOR),
3297 Some(FOCUSED_FOREGROUND_COLOR),
3298 Some(FOCUSED_ICON_COLOR)
3299 )
3300 );
3301 assert_eq!(
3302 item_colors(tester, non_selected_item),
3303 (
3304 Some(DEFAULT_BACKGROUND_COLOR),
3305 Some(DEFAULT_FOREGROUND_COLOR),
3306 Some(DEFAULT_ICON_COLOR)
3307 )
3308 );
3309 }
3310
3311 #[test]
3313 fn item_style_can_be_overridden_at_application_theme_level() {
3314 test_widgets(|tester| {
3315 let theme = ThemeData::builder()
3316 .menu_button_theme(
3317 crate::menu_button_theme::MenuButtonThemeData::new()
3318 .style(custom_button_style()),
3319 )
3320 .build(&tester.cell.borrow());
3321 open_styled_menu(
3322 tester,
3323 theme,
3324 menu_children_with_icons(),
3325 TestMenu::MainMenu3,
3326 );
3327 assert_custom_button_style(tester);
3328 });
3329 }
3330
3331 #[test]
3333 fn item_style_can_be_overridden_at_menu_entry_level() {
3334 test_widgets(|tester| {
3335 let theme = theme(tester);
3336 open_styled_menu(
3337 tester,
3338 theme,
3339 styled_menu_entries(&custom_button_style()),
3340 TestMenu::MainMenu3,
3341 );
3342 assert_custom_button_style(tester);
3343 });
3344 }
3345
3346 #[test]
3348 fn item_style_defined_at_menu_entry_level_takes_precedence() {
3349 test_widgets(|tester| {
3350 let lucky_color = Color::new(0xff777777);
3351 let all = |color: Color| -> WidgetStatePropertyRef<Option<Color>> {
3352 Rc::new(WidgetStatePropertyAll::new(Some(color)))
3353 };
3354 let single_color_button_style = ButtonStyle::new()
3355 .background_color(all(lucky_color))
3356 .foreground_color(all(lucky_color))
3357 .icon_color(all(lucky_color))
3358 .overlay_color(all(lucky_color));
3359 let theme = ThemeData::builder()
3360 .menu_button_theme(
3361 crate::menu_button_theme::MenuButtonThemeData::new()
3362 .style(single_color_button_style),
3363 )
3364 .build(&tester.cell.borrow());
3365 open_styled_menu(
3366 tester,
3367 theme,
3368 styled_menu_entries(&custom_button_style()),
3369 TestMenu::MainMenu3,
3370 );
3371 assert_custom_button_style(tester);
3372 });
3373 }
3374
3375 #[test]
3377 fn item_style_defined_at_menu_entry_level_and_application_level_are_merged() {
3378 test_widgets(|tester| {
3379 let selected_item = TestMenu::MainMenu3;
3380 let non_selected_item = TestMenu::MainMenu2;
3381 let lucky_color = Color::new(0xff777777);
3382 let all = |color: Color| -> WidgetStatePropertyRef<Option<Color>> {
3383 Rc::new(WidgetStatePropertyAll::new(Some(color)))
3384 };
3385 let partial_button_style = ButtonStyle::new()
3386 .background_color(all(lucky_color))
3387 .foreground_color(all(lucky_color));
3388 let theme = ThemeData::builder()
3389 .menu_button_theme(
3390 crate::menu_button_theme::MenuButtonThemeData::new()
3391 .style(custom_button_style()),
3392 )
3393 .build(&tester.cell.borrow());
3394 open_styled_menu(
3395 tester,
3396 theme,
3397 styled_menu_entries(&partial_button_style),
3398 selected_item,
3399 );
3400
3401 assert_eq!(
3402 item_colors(tester, selected_item),
3403 (
3404 Some(lucky_color),
3405 Some(lucky_color),
3406 Some(FOCUSED_ICON_COLOR)
3407 )
3408 );
3409 assert_eq!(
3410 item_colors(tester, non_selected_item),
3411 (
3412 Some(lucky_color),
3413 Some(lucky_color),
3414 Some(DEFAULT_ICON_COLOR)
3415 )
3416 );
3417 });
3418 }
3419
3420 #[test]
3423 fn item_style_text_style_is_resolved_when_the_item_is_highlighted() {
3424 test_widgets(|tester| {
3425 let selected_item = TestMenu::MainMenu3;
3426 let non_selected_item = TestMenu::MainMenu2;
3427 let custom_button_style =
3428 ButtonStyle::new().text_style(
3429 <dyn WidgetStateProperty<Option<TextStyle>>>::resolve_with(|states| {
3430 Some(TextStyle::new().font_weight(
3431 if states.contains(&WidgetState::Focused) {
3432 waft_embedder::FontWeight::BOLD
3433 } else {
3434 waft_embedder::FontWeight::NORMAL
3435 },
3436 ))
3437 }),
3438 );
3439 let menu_entries: Rc<[DropdownMenuEntry<TestMenu>]> = menu_children()
3440 .iter()
3441 .cloned()
3442 .map(|entry| entry.style(custom_button_style.clone()))
3443 .collect();
3444 let theme = theme(tester);
3445 open_styled_menu(tester, theme, menu_entries, selected_item);
3446
3447 let item_label_weight = |tester: &WidgetTester, label: &str| {
3448 let button = find_menu_item_button(tester, label);
3449 let text = *find::text(label)
3450 .evaluate(tester)
3451 .iter()
3452 .find(|text| tester.ancestors(**text).contains(&button))
3453 .expect("the item's label");
3454 let render = tester.render_box_of(text);
3455 let app = tester.cell.borrow();
3456 let paragraph = render
3457 .as_object()
3458 .downcast::<waft_rendering::RenderParagraph>(&app)
3459 .expect("a Text renders a paragraph");
3460 paragraph
3461 .text(&app)
3462 .style()
3463 .and_then(|style| style.font_weight)
3464 };
3465 assert_eq!(
3466 item_label_weight(tester, selected_item.label()),
3467 Some(waft_embedder::FontWeight::BOLD)
3468 );
3469 assert_eq!(
3470 item_label_weight(tester, non_selected_item.label()),
3471 Some(waft_embedder::FontWeight::NORMAL)
3472 );
3473 });
3474 }
3475
3476 fn safe_area_menu<T: Clone + PartialEq + 'static>(
3478 theme: ThemeData,
3479 menu: DropdownMenu<T>,
3480 ) -> WidgetRef {
3481 material_app(
3482 theme,
3483 Scaffold::new()
3484 .body(waft_widgets::SafeArea::new(menu))
3485 .into_widget(),
3486 )
3487 }
3488
3489 fn m2(app: &App) -> ThemeData {
3490 ThemeData::builder().use_material3(false).build(app)
3491 }
3492
3493 fn dropdown_menu<T: 'static>(tester: &WidgetTester) -> AnyElement {
3495 tester.element(find::by_type::<DropdownMenu<T>>())
3496 }
3497
3498 fn menu_ancestor<W: 'static>(tester: &WidgetTester) -> AnyElement {
3500 let scroll_view =
3501 find::by_type::<waft_widgets::SingleChildScrollView>().evaluate(tester)[0];
3502 ancestors_of_type::<W>(tester, scroll_view)[0]
3503 }
3504
3505 fn arrow_drop_down_button(tester: &WidgetTester) -> AnyElement {
3506 widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_down())[0]
3507 }
3508
3509 #[test]
3511 fn a_disabled_dropdown_menu_disables_its_text_field_and_opens_no_menu() {
3512 test_widgets(|tester| {
3513 let theme = theme(tester);
3514 tester.pump_widget(safe_area_menu(
3515 theme,
3516 DropdownMenu::new(menu_children()).enabled(false),
3517 ));
3518
3519 text_field(tester, |text_field| {
3520 assert_eq!(text_field.enabled, Some(false))
3521 });
3522 assert!(
3523 find::by_type::<waft_widgets::SingleChildScrollView>()
3524 .evaluate(tester)
3525 .is_empty()
3526 );
3527
3528 tap_first::<TextField>(tester);
3529 pump(tester);
3530 assert!(
3531 find::by_type::<waft_widgets::SingleChildScrollView>()
3532 .evaluate(tester)
3533 .is_empty()
3534 );
3535 });
3536 }
3537
3538 #[test]
3540 fn a_disabled_dropdown_menu_disables_its_trailing_icon_button() {
3541 test_widgets(|tester| {
3542 let theme = theme(tester);
3543 tester.pump_widget(safe_area_menu(
3544 theme,
3545 DropdownMenu::new(menu_children()).enabled(false),
3546 ));
3547
3548 let button = arrow_drop_down_button(tester);
3549 tester.widget(button, |button: &IconButton| {
3550 assert!(button.on_pressed.is_none())
3551 });
3552 });
3553 }
3554
3555 #[test]
3557 fn material2_the_text_field_is_as_wide_as_the_menu() {
3558 test_widgets(|tester| {
3559 let theme = m2(&tester.cell.borrow());
3560 let entries = menu_children();
3561 tester.pump_widget(safe_area_menu(
3562 theme.clone(),
3563 DropdownMenu::new(Rc::clone(&entries)),
3564 ));
3565
3566 assert_eq!(
3567 tester.get_size(first::<TextField>(tester)),
3568 Size::new(180.0, 56.0)
3569 );
3570
3571 tap_dropdown_menu::<TestMenu>(tester);
3572 tester.pump_and_settle();
3573
3574 let menu_material = menu_ancestor::<Material>(tester);
3575 assert_eq!(tester.get_size(menu_material), Size::new(180.0, 304.0));
3576
3577 tester.pump_widget(
3580 BuildTest {
3581 width: Some(200.0),
3582 ..BuildTest::default()
3583 }
3584 .build(theme, entries),
3585 );
3586
3587 let anchor = first::<TextField>(tester);
3588 assert_eq!(tester.get_size(anchor).width(), 200.0);
3589
3590 tap(tester, anchor);
3591 tester.pump_and_settle();
3592
3593 let updated_menu = menu_ancestor::<Material>(tester);
3594 assert_eq!(tester.get_size(updated_menu).width(), 200.0);
3595 });
3596 }
3597
3598 #[test]
3600 fn material3_the_text_field_is_as_wide_as_the_menu() {
3601 test_widgets(|tester| {
3602 let theme = theme(tester);
3603 let entries = menu_children();
3604 tester.pump_widget(safe_area_menu(
3605 theme.clone(),
3606 DropdownMenu::new(Rc::clone(&entries)),
3607 ));
3608
3609 let anchor_width = tester.get_size(first::<TextField>(tester)).width();
3610 assert!((anchor_width - 184.5).abs() < 0.1, "{anchor_width}");
3611
3612 tap_dropdown_menu::<TestMenu>(tester);
3613 tester.pump_and_settle();
3614
3615 let menu_width = tester.get_size(menu_ancestor::<Material>(tester)).width();
3616 assert!((menu_width - 184.5).abs() < 0.1, "{menu_width}");
3617
3618 tester.pump_widget(
3621 BuildTest {
3622 width: Some(200.0),
3623 ..BuildTest::default()
3624 }
3625 .build(theme, entries),
3626 );
3627
3628 let anchor = first::<TextField>(tester);
3629 assert_eq!(tester.get_size(anchor).width(), 200.0);
3630
3631 tap(tester, anchor);
3632 tester.pump_and_settle();
3633
3634 let updated_menu = menu_ancestor::<Material>(tester);
3635 assert_eq!(tester.get_size(updated_menu).width(), 200.0);
3636 });
3637 }
3638
3639 #[test]
3641 fn the_width_property_sets_the_width_of_the_field_and_its_items() {
3642 test_widgets(|tester| {
3643 let theme = theme(tester);
3644 let short_menu_items = short_menu_items();
3645
3646 let custom_big_width = 250.0;
3647 tester.pump_widget(
3648 BuildTest {
3649 width: Some(custom_big_width),
3650 ..BuildTest::default()
3651 }
3652 .build(theme.clone(), Rc::clone(&short_menu_items)),
3653 );
3654 let menu = dropdown_menu::<ShortMenu>(tester);
3655 assert_eq!(tester.get_size(menu).width(), custom_big_width);
3656
3657 tap(tester, menu);
3658 pump(tester);
3659 expect(
3660 tester,
3661 &find::by_type::<MenuItemButton>(),
3662 finds_n_widgets(6),
3663 );
3664 let button = find_menu_item_button(tester, "I0");
3665 assert_eq!(tester.get_size(button).width(), custom_big_width);
3666
3667 tester.pump_widget(SizedBox::new().into_widget());
3669 let custom_small_width = 100.0;
3670 tester.pump_widget(
3671 BuildTest {
3672 width: Some(custom_small_width),
3673 ..BuildTest::default()
3674 }
3675 .build(theme, short_menu_items),
3676 );
3677 let menu = dropdown_menu::<ShortMenu>(tester);
3678 assert_eq!(tester.get_size(menu).width(), custom_small_width);
3679
3680 tap(tester, menu);
3681 pump(tester);
3682 expect(
3683 tester,
3684 &find::by_type::<MenuItemButton>(),
3685 finds_n_widgets(6),
3686 );
3687 let button = find_menu_item_button(tester, "I0");
3688 assert_eq!(tester.get_size(button).width(), custom_small_width);
3689 });
3690 }
3691
3692 #[test]
3694 fn a_new_width_resizes_the_dropdown_menu() {
3695 test_widgets(|tester| {
3696 let theme = theme(tester);
3697 let short_menu_items = short_menu_items();
3698
3699 tester.pump_widget(
3700 BuildTest {
3701 width: Some(250.0),
3702 ..BuildTest::default()
3703 }
3704 .build(theme.clone(), Rc::clone(&short_menu_items)),
3705 );
3706 let menu = dropdown_menu::<ShortMenu>(tester);
3707 assert_eq!(tester.get_size(menu).width(), 250.0);
3708
3709 tester.pump_widget(
3711 BuildTest {
3712 width: Some(400.0),
3713 ..BuildTest::default()
3714 }
3715 .build(theme, short_menu_items),
3716 );
3717 let menu = dropdown_menu::<ShortMenu>(tester);
3718 assert_eq!(tester.get_size(menu).width(), 400.0);
3719 });
3720 }
3721
3722 #[test]
3724 fn without_a_width_the_widest_entry_sets_the_width() {
3725 test_widgets(|tester| {
3726 let theme = theme(tester);
3727 let entry_label_width = 100.0;
3728 tester.pump_widget(the_menu(
3729 theme,
3730 DropdownMenu::new(vec![
3731 DropdownMenuEntry::new(0, "Flutter")
3732 .label_widget(SizedBox::new().width(entry_label_width)),
3733 ]),
3734 ));
3735
3736 let width = tester.get_size(dropdown_menu::<i32>(tester)).width();
3737 let menu_entry_padding = 24.0; let decoration_start_gap = 4.0; let leading_width = 16.0;
3740 let trailing_width = 56.0;
3741
3742 assert_eq!(
3743 width,
3744 entry_label_width
3745 + leading_width
3746 + trailing_width
3747 + menu_entry_padding
3748 + decoration_start_gap
3749 );
3750 });
3751 }
3752
3753 #[test]
3755 fn a_label_wider_than_the_entries_sets_the_width() {
3756 test_widgets(|tester| {
3757 let theme = theme(tester);
3758 let label_width = 120.0;
3759 let entry_label_width = 100.0;
3760 tester.pump_widget(the_menu(
3761 theme,
3762 DropdownMenu::new(vec![
3763 DropdownMenuEntry::new(0, "Flutter")
3764 .label_widget(SizedBox::new().width(entry_label_width)),
3765 ])
3766 .label(SizedBox::new().width(label_width)),
3767 ));
3768
3769 let width = tester.get_size(dropdown_menu::<i32>(tester)).width();
3770 let leading_width = 16.0;
3771 let trailing_width = 56.0;
3772 let label_padding = 8.0; assert_eq!(
3775 width,
3776 label_width + label_padding + leading_width + trailing_width
3777 );
3778 });
3779 }
3780
3781 fn sized_short_menu(
3782 expanded_insets: Option<EdgeInsetsGeometry>,
3783 ) -> impl FnOnce(&mut App) -> WidgetRef {
3784 move |app| {
3785 let mut menu = DropdownMenu::new(short_menu_items_shared());
3786 menu.expanded_insets = expanded_insets;
3787 material_app(
3788 m3(app),
3789 Scaffold::new()
3790 .body(SizedBox::square(Some(500.0)).child(menu))
3791 .into_widget(),
3792 )
3793 }
3794 }
3795
3796 thread_local! {
3797 static SHORT_MENU_ITEMS: Rc<[DropdownMenuEntry<ShortMenu>]> = short_menu_items();
3798 }
3799
3800 fn short_menu_items_shared() -> Rc<[DropdownMenuEntry<ShortMenu>]> {
3802 SHORT_MENU_ITEMS.with(Rc::clone)
3803 }
3804
3805 fn assert_insets_narrow_the_field(tester: &mut WidgetTester, insets: EdgeInsetsGeometry) {
3809 let parent_width = 500.0;
3810 tester.pump_widget(SizedBox::new().into_widget());
3811 pump_app(tester, sized_short_menu(Some(insets)));
3812 let field = first::<TextField>(tester);
3813 assert_eq!(tester.get_size(field).width(), parent_width - 35.0 - 20.0);
3814 let container_rect = tester.get_rect(first::<SizedBox>(tester));
3815 let dropdown_menu_rect = tester.get_rect(field);
3816 assert_eq!(dropdown_menu_rect.top, container_rect.top);
3817
3818 tap(tester, field);
3819 tester.pump_and_settle();
3820
3821 let button = find_menu_item_button(tester, "I0");
3822 assert_eq!(tester.get_size(button).width(), parent_width - 35.0 - 20.0);
3823 }
3824
3825 #[test]
3827 fn expanded_insets_make_the_field_and_its_menu_as_wide_as_the_parent_less_the_insets() {
3828 test_widgets(|tester| {
3829 let parent_width = 500.0;
3830
3831 pump_app(tester, sized_short_menu(None));
3833 let field = first::<TextField>(tester);
3834 assert_eq!(tester.get_size(field).width(), 136.0);
3835
3836 tap(tester, field);
3837 tester.pump_and_settle();
3838 let button = find_menu_item_button(tester, "I0");
3839 assert_eq!(tester.get_size(button).width(), 136.0);
3840
3841 tester.pump_widget(SizedBox::new().into_widget());
3843 pump_app(tester, sized_short_menu(Some(EdgeInsetsGeometry::ZERO)));
3844 let field = first::<TextField>(tester);
3845 assert_eq!(tester.get_size(field).width(), parent_width);
3846
3847 tap(tester, field);
3848 tester.pump_and_settle();
3849 let button = find_menu_item_button(tester, "I0");
3850 assert_eq!(tester.get_size(button).width(), parent_width);
3851
3852 assert_insets_narrow_the_field(tester, EdgeInsetsGeometry::only(35.0, 50.0, 20.0, 0.0));
3856 });
3857 }
3858
3859 #[test]
3861 fn expanded_insets_can_be_directional() {
3862 test_widgets(|tester| {
3863 pump_app(tester, sized_short_menu(None));
3865 let field = first::<TextField>(tester);
3866 assert_eq!(tester.get_size(field).width(), 136.0);
3867 tap(tester, field);
3868 tester.pump_and_settle();
3869 let button = find_menu_item_button(tester, "I0");
3870 assert_eq!(tester.get_size(button).width(), 136.0);
3871
3872 assert_insets_narrow_the_field(tester, EdgeInsetsGeometry::only(35.0, 50.0, 20.0, 0.0));
3873 assert_insets_narrow_the_field(
3875 tester,
3876 EdgeInsetsDirectional::only(35.0, 50.0, 20.0, 0.0).into(),
3877 );
3878 });
3879 }
3880
3881 #[test]
3883 fn zero_expanded_insets_make_the_menu_panel_as_wide_as_the_screen() {
3884 test_widgets(|tester| {
3885 let theme = theme(tester);
3886 tester.pump_widget(the_menu(
3887 theme,
3888 DropdownMenu::new(vec![DropdownMenuEntry::new(0, "Flutter")])
3889 .expanded_insets(EdgeInsetsGeometry::ZERO),
3890 ));
3891
3892 let dropdown_width = tester.get_size(dropdown_menu::<i32>(tester)).width();
3893 assert_eq!(dropdown_width, 800.0);
3894
3895 tap_dropdown_menu::<i32>(tester);
3896 pump(tester);
3897
3898 let menu_width = tester
3899 .get_size(find_menu_item_button(tester, "Flutter"))
3900 .width();
3901 assert_eq!(dropdown_width, menu_width);
3902 });
3903 }
3904
3905 fn items_extent(tester: &WidgetTester) -> f64 {
3907 let first_rect = tester.get_rect(find_menu_item_button(tester, "Item 0"));
3908 let last_rect = tester.get_rect(find_menu_item_button(tester, "Item 5"));
3909 last_rect.bottom - first_rect.top
3910 }
3911
3912 #[test]
3915 fn material2_menu_height_limits_the_menu() {
3916 test_widgets(|tester| {
3917 let theme = m2(&tester.cell.borrow());
3918 let entries = menu_children();
3919 tester.pump_widget(BuildTest::default().build(theme.clone(), Rc::clone(&entries)));
3920
3921 tap_dropdown_menu::<TestMenu>(tester);
3922 tester.pump_and_settle();
3923
3924 assert_eq!(items_extent(tester), 288.0);
3926
3927 let menu_view = menu_ancestor::<Padding>(tester);
3928 assert_eq!(tester.get_size(menu_view), Size::new(180.0, 304.0));
3930
3931 tester.pump_widget(SizedBox::new().into_widget());
3933 tester.pump_widget(
3934 BuildTest {
3935 menu_height: Some(100.0),
3936 ..BuildTest::default()
3937 }
3938 .build(theme, entries),
3939 );
3940 tester.pump_and_settle();
3941
3942 tap_dropdown_menu::<TestMenu>(tester);
3943 tester.pump_and_settle();
3944
3945 let updated_menu = menu_ancestor::<Padding>(tester);
3946 assert_eq!(tester.get_size(updated_menu), Size::new(180.0, 100.0));
3947 });
3948 }
3949
3950 #[test]
3953 fn material3_menu_height_limits_the_menu() {
3954 test_widgets(|tester| {
3955 let theme = theme(tester);
3956 let entries = menu_children();
3957 tester.pump_widget(BuildTest::default().build(theme.clone(), Rc::clone(&entries)));
3958
3959 tap_dropdown_menu::<TestMenu>(tester);
3960 tester.pump_and_settle();
3961
3962 assert_eq!(items_extent(tester), 288.0);
3964
3965 let menu_view = menu_ancestor::<Padding>(tester);
3966 assert_eq!(tester.get_size(menu_view).height(), 304.0);
3968
3969 tester.pump_widget(SizedBox::new().into_widget());
3971 tester.pump_widget(
3972 BuildTest {
3973 menu_height: Some(100.0),
3974 ..BuildTest::default()
3975 }
3976 .build(theme, entries),
3977 );
3978 tester.pump_and_settle();
3979
3980 tap_dropdown_menu::<TestMenu>(tester);
3981 tester.pump_and_settle();
3982
3983 let updated_menu = menu_ancestor::<Padding>(tester);
3984 assert_eq!(tester.get_size(updated_menu).height(), 100.0);
3985 });
3986 }
3987
3988 #[test]
3990 fn the_default_trailing_icon_button_opens_the_menu() {
3991 test_widgets(|tester| {
3992 let theme = theme(tester);
3993 tester.pump_widget(BuildTest::default().build(theme, menu_children()));
3994 pump(tester);
3995
3996 let icon_button = arrow_drop_down_button(tester);
3997 tap(tester, icon_button);
3998 pump(tester);
3999
4000 let button = find_menu_item_button(tester, TestMenu::MainMenu0.label());
4001 assert!(!ancestors_of_type::<Material>(tester, button).is_empty());
4002 });
4003 }
4004
4005 #[test]
4007 fn the_trailing_icon_shows_whether_the_menu_is_open() {
4008 test_widgets(|tester| {
4009 let theme = theme(tester);
4010 tester.pump_widget(
4011 BuildTest {
4012 width: Some(100.0),
4013 menu_height: Some(100.0),
4014 ..BuildTest::default()
4015 }
4016 .build(theme, menu_children()),
4017 );
4018 pump(tester);
4019
4020 assert!(widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_up()).is_empty());
4021 let icon_button = arrow_drop_down_button(tester);
4022
4023 tap(tester, icon_button);
4024 pump(tester);
4025
4026 assert!(!widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_up()).is_empty());
4027 assert!(widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_down()).is_empty());
4028
4029 tester.tap_at(Offset::new(500.0, 500.0), 1);
4031 pump(tester);
4032
4033 assert!(widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_up()).is_empty());
4034 assert!(!widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_down()).is_empty());
4035 });
4036 }
4037
4038 #[test]
4040 fn the_trailing_icon_button_takes_the_suffix_icon_constraints() {
4041 test_widgets(|tester| {
4042 let theme = theme(tester);
4043 let entries = menu_children();
4044
4045 tester.pump_widget(BuildTest::default().build(theme.clone(), Rc::clone(&entries)));
4047 pump(tester);
4048 let icon_button = arrow_drop_down_button(tester);
4049 assert_eq!(tester.get_size(icon_button), Size::new(48.0, 48.0));
4050
4051 tester.pump_widget(
4053 BuildTest {
4054 decoration_theme: Some(
4055 InputDecorationThemeData::new().suffix_icon_constraints(
4056 BoxConstraints::new().min_width(66.0).min_height(62.0),
4057 ),
4058 ),
4059 ..BuildTest::default()
4060 }
4061 .build(theme, entries),
4062 );
4063 pump(tester);
4064 let icon_button = arrow_drop_down_button(tester);
4065 assert_eq!(tester.get_size(icon_button), Size::new(66.0, 62.0));
4066 });
4067 }
4068
4069 #[test]
4071 fn a_collapsed_decoration_theme_reduces_the_height() {
4072 test_widgets(|tester| {
4073 let theme = theme(tester);
4074 let entries = menu_children();
4075
4076 tester.pump_widget(BuildTest::default().build(theme.clone(), Rc::clone(&entries)));
4078 pump(tester);
4079 assert_eq!(tester.get_size(first::<TextField>(tester)).height(), 56.0);
4080
4081 tester.pump_widget(
4083 BuildTest {
4084 decoration_theme: Some(InputDecorationThemeData::new().is_collapsed(true)),
4085 ..BuildTest::default()
4086 }
4087 .build(theme.clone(), Rc::clone(&entries)),
4088 );
4089 pump(tester);
4090 assert_eq!(tester.get_size(first::<TextField>(tester)).height(), 48.0);
4092
4093 tester.pump_widget(
4095 BuildTest {
4096 decoration_theme: Some(
4097 InputDecorationThemeData::new()
4098 .is_collapsed(true)
4099 .suffix_icon_constraints(
4100 BoxConstraints::new().max_width(24.0).max_height(24.0),
4101 ),
4102 ),
4103 ..BuildTest::default()
4104 }
4105 .build(theme, entries),
4106 );
4107 pump(tester);
4108 assert_eq!(tester.get_size(first::<TextField>(tester)).height(), 24.0);
4109 });
4110 }
4111
4112 #[test]
4114 fn resizing_the_window_while_the_menu_opens_does_not_panic() {
4115 test_widgets(|tester| {
4116 let root = material_app(
4117 m3(&tester.cell.borrow()),
4118 Scaffold::new()
4119 .body(waft_widgets::StatefulBuilder::new(
4120 move |app, context, _set_state| {
4121 DropdownMenu::new(menu_children())
4122 .width(waft_widgets::MediaQuery::width_of(app, context))
4123 .into_widget()
4124 },
4125 ))
4126 .into_widget(),
4127 );
4128 tester.pump_widget(root);
4129
4130 let icon_button = widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_down());
4131 assert!(!icon_button.is_empty());
4132 tap(tester, icon_button[0]);
4133 pump(tester);
4134
4135 find_menu_item_button(tester, TestMenu::MainMenu0.label());
4136
4137 tester.view().set_physical_size(Size::new(700.0, 700.0));
4139 pump(tester);
4140
4141 });
4143 }
4144
4145 #[test]
4148 fn removing_the_menu_frees_what_its_state_made() {
4149 test_widgets(|tester| {
4150 let theme = theme(tester);
4151 tester.pump_widget(the_menu(theme.clone(), DropdownMenu::new(menu_children())));
4152 tap_dropdown_menu::<TestMenu>(tester);
4153 pump(tester);
4154 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4155 pump(tester);
4156
4157 let owned: Vec<waft_foundation::HandleId> = {
4158 let menu = dropdown_menu::<TestMenu>(tester);
4159 let app = tester.cell.borrow();
4160 let state = menu
4161 .state_handle::<DropdownMenuState<TestMenu>>(&app)
4162 .expect("the menu's state");
4163 let state = app.get(state);
4164 [
4165 state
4166 .local_text_editing_controller
4167 .as_ref()
4168 .map(|node| node.into()),
4169 state.internal_focus_node.as_ref().map(|node| node.into()),
4170 state
4171 .local_trailing_icon_button_focus_node
4172 .as_ref()
4173 .map(|node| node.into()),
4174 state
4175 .internal_menu_controller
4176 .as_ref()
4177 .map(|node| node.into()),
4178 ]
4179 .into_iter()
4180 .collect::<Option<Vec<_>>>()
4181 .expect("the state made each of them")
4182 };
4183
4184 tester.pump_widget(material_app(theme, SizedBox::shrink().into_widget()));
4185 pump(tester);
4186
4187 let app = tester.cell.borrow();
4188 for handle in owned {
4189 assert!(!app.contains(handle), "{handle:?} is still in the arena");
4190 }
4191 });
4192 }
4193
4194 #[test]
4196 fn a_custom_trailing_icon_opens_the_menu() {
4197 test_widgets(|tester| {
4198 let theme = theme(tester);
4199 tester.pump_widget(the_menu(
4200 theme,
4201 DropdownMenu::new(menu_children()).trailing_icon(Icon::new(Some(Icons::ac_unit()))),
4202 ));
4203 pump(tester);
4204
4205 let icon_button = widgets_with_icon::<IconButton>(tester, &Icons::ac_unit())[0];
4206 tap(tester, icon_button);
4207 pump(tester);
4208
4209 let button = find_menu_item_button(tester, TestMenu::MainMenu0.label());
4210 assert!(!ancestors_of_type::<Material>(tester, button).is_empty());
4211 });
4212 }
4213
4214 #[test]
4216 fn the_down_key_highlights_the_next_item_while_focused() {
4217 test_widgets(|tester| {
4218 let theme = theme(tester);
4219 tester.pump_widget(the_menu(
4220 theme.clone(),
4221 DropdownMenu::new(menu_children())
4222 .request_focus_on_tap(true)
4223 .trailing_icon(Icon::new(Some(Icons::ac_unit()))),
4224 ));
4225
4226 tap_dropdown_menu::<TestMenu>(tester);
4227 pump(tester);
4228
4229 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4230 pump(tester);
4231 assert!(is_item_highlighted(tester, &theme, "Item 0"));
4232
4233 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4235 pump(tester);
4236 assert!(is_item_highlighted(tester, &theme, "Menu 1"));
4237
4238 assert!(!is_item_highlighted(tester, &theme, "Item 0"));
4240 });
4241 }
4242
4243 #[test]
4245 fn the_up_key_highlights_the_previous_item_while_focused() {
4246 test_widgets(|tester| {
4247 let theme = theme(tester);
4248 tester.pump_widget(the_menu(
4249 theme.clone(),
4250 DropdownMenu::new(menu_children()).request_focus_on_tap(true),
4251 ));
4252
4253 tap_dropdown_menu::<TestMenu>(tester);
4254 pump(tester);
4255
4256 send_key(tester, LogicalKeyboardKey::ARROW_UP);
4257 pump(tester);
4258 assert!(is_item_highlighted(tester, &theme, "Item 5"));
4259
4260 send_key(tester, LogicalKeyboardKey::ARROW_UP);
4262 pump(tester);
4263 assert!(is_item_highlighted(tester, &theme, "Item 4"));
4264
4265 assert!(!is_item_highlighted(tester, &theme, "Item 5"));
4267 });
4268 }
4269
4270 fn leading_icon_key(menu_entry: TestMenu) -> KeyRef {
4271 waft_foundation::ValueKey::new(format!("leading-{}", menu_entry.label())).into()
4272 }
4273
4274 fn trailing_icon_key(menu_entry: TestMenu) -> KeyRef {
4275 waft_foundation::ValueKey::new(format!("trailing-{}", menu_entry.label())).into()
4276 }
4277
4278 fn menu_children_with_icons() -> Rc<[DropdownMenuEntry<TestMenu>]> {
4280 TestMenu::VALUES
4281 .iter()
4282 .map(|value| {
4283 DropdownMenuEntry::new(*value, value.label())
4284 .leading_icon(Icon::new(Some(Icons::alarm())).key(leading_icon_key(*value)))
4285 .trailing_icon(Icon::new(Some(Icons::abc())).key(trailing_icon_key(*value)))
4286 })
4287 .collect()
4288 }
4289
4290 fn find_by_key(tester: &WidgetTester, key: &KeyRef) -> Vec<AnyElement> {
4292 let found = tester.elements();
4293 let app = tester.cell.borrow();
4294 found
4295 .into_iter()
4296 .filter(|element| element.widget(&app).key() == Some(key))
4297 .collect()
4298 }
4299
4300 fn directional_menu<T: Clone + PartialEq + 'static>(
4302 theme: ThemeData,
4303 text_direction: TextDirection,
4304 menu: DropdownMenu<T>,
4305 ) -> WidgetRef {
4306 material_app(
4307 theme,
4308 Scaffold::new()
4309 .body(Directionality::new(text_direction, menu))
4310 .into_widget(),
4311 )
4312 }
4313
4314 const LEADING_ICON_TO_INPUT_PADDING: f64 = 4.0;
4315
4316 fn search_icon_box_width(tester: &WidgetTester) -> f64 {
4319 let boxes = widgets_with_icon::<SizedBox>(tester, &Icons::search());
4320 tester.get_size(*boxes.last().expect("a sized box")).width()
4321 }
4322
4323 #[test]
4325 fn the_item_text_lines_up_with_the_field_text_in_ltr() {
4326 test_widgets(|tester| {
4327 let theme = theme(tester);
4328 let entries = menu_children();
4329 tester.pump_widget(
4331 BuildTest {
4332 label: Some(Text::new("label").into_widget()),
4333 ..BuildTest::default()
4334 }
4335 .build(theme.clone(), Rc::clone(&entries)),
4336 );
4337
4338 let label_top_left = tester.get_rect(find::text("label").first()).top_left();
4339 tap_dropdown_menu::<TestMenu>(tester);
4340 tester.pump_and_settle();
4341 let item_text_top_left = tester.get_rect(find::text("Item 0").last()).top_left();
4342 assert_eq!(label_top_left.dx(), item_text_top_left.dx());
4343
4344 tester.pump_widget(SizedBox::new().into_widget());
4346 tester.pump_widget(
4347 BuildTest {
4348 leading_icon: Some(Icon::new(Some(Icons::search())).into_widget()),
4349 label: Some(Text::new("label").into_widget()),
4350 ..BuildTest::default()
4351 }
4352 .build(theme.clone(), Rc::clone(&entries)),
4353 );
4354
4355 let icon_width = search_icon_box_width(tester);
4356 let updated_label_top_left = tester.get_rect(find::text("label").first()).top_left();
4357 tap_dropdown_menu::<TestMenu>(tester);
4358 tester.pump_and_settle();
4359 let updated_item_text_top_left =
4360 tester.get_rect(find::text("Item 0").last()).top_left();
4361 assert_eq!(updated_label_top_left.dx(), updated_item_text_top_left.dx());
4362 assert_eq!(
4363 updated_label_top_left.dx(),
4364 icon_width + LEADING_ICON_TO_INPUT_PADDING
4365 );
4366
4367 tester.pump_widget(SizedBox::new().into_widget());
4369 tester.pump_widget(
4370 BuildTest {
4371 leading_icon: Some(
4372 SizedBox::new()
4373 .width(75.0)
4374 .child(Icon::new(Some(Icons::search())))
4375 .into_widget(),
4376 ),
4377 label: Some(Text::new("label").into_widget()),
4378 ..BuildTest::default()
4379 }
4380 .build(theme, entries),
4381 );
4382
4383 let large_icon_width = search_icon_box_width(tester);
4384 let updated_label_top_left1 = tester.get_rect(find::text("label").first()).top_left();
4385 tap_dropdown_menu::<TestMenu>(tester);
4386 tester.pump_and_settle();
4387 let updated_item_text_top_left1 =
4388 tester.get_rect(find::text("Item 0").last()).top_left();
4389 assert_eq!(
4390 updated_label_top_left1.dx(),
4391 updated_item_text_top_left1.dx()
4392 );
4393 assert_eq!(
4394 updated_label_top_left1.dx(),
4395 large_icon_width + LEADING_ICON_TO_INPUT_PADDING
4396 );
4397 });
4398 }
4399
4400 #[test]
4402 fn the_item_text_lines_up_with_the_field_text_in_rtl() {
4403 test_widgets(|tester| {
4404 let theme = theme(tester);
4405 let entries = menu_children();
4406 tester.pump_widget(directional_menu(
4408 theme.clone(),
4409 TextDirection::Rtl,
4410 DropdownMenu::new(Rc::clone(&entries)).label(Text::new("label")),
4411 ));
4412
4413 let label_top_right = tester.get_rect(find::text("label").first()).top_right();
4414 tap_dropdown_menu::<TestMenu>(tester);
4415 tester.pump_and_settle();
4416 let item_text_top_right = tester.get_rect(find::text("Item 0").last()).top_right();
4417 assert_eq!(label_top_right.dx(), item_text_top_right.dx());
4418
4419 for leading_icon in [
4422 Icon::new(Some(Icons::search())).into_widget(),
4423 SizedBox::new()
4424 .width(75.0)
4425 .child(Icon::new(Some(Icons::search())))
4426 .into_widget(),
4427 ] {
4428 tester.pump_widget(SizedBox::new().into_widget());
4429 tester.pump_widget(directional_menu(
4430 theme.clone(),
4431 TextDirection::Rtl,
4432 DropdownMenu::new(Rc::clone(&entries))
4433 .leading_icon(leading_icon)
4434 .label(Text::new("label")),
4435 ));
4436 pump(tester);
4437
4438 let icon_width = search_icon_box_width(tester);
4439 let dropdown_menu_top_right = tester
4440 .get_rect(dropdown_menu::<TestMenu>(tester))
4441 .top_right();
4442 let updated_label_top_right =
4443 tester.get_rect(find::text("label").first()).top_right();
4444 tap_dropdown_menu::<TestMenu>(tester);
4445 tester.pump_and_settle();
4446 let updated_item_text_top_right =
4447 tester.get_rect(find::text("Item 0").last()).top_right();
4448 assert_eq!(
4449 updated_label_top_right.dx(),
4450 updated_item_text_top_right.dx()
4451 );
4452 assert_eq!(
4453 updated_label_top_right.dx(),
4454 dropdown_menu_top_right.dx() - icon_width - LEADING_ICON_TO_INPUT_PADDING
4455 );
4456 }
4457 });
4458 }
4459
4460 fn field_and_item_icon_rects(
4463 tester: &mut WidgetTester,
4464 text_direction: TextDirection,
4465 ) -> (Rect, Rect) {
4466 let theme = m3(&tester.cell.borrow());
4467 tester.pump_widget(directional_menu(
4468 theme,
4469 text_direction,
4470 DropdownMenu::new(menu_children_with_icons())
4471 .leading_icon(Icon::new(Some(Icons::search())))
4472 .label(Text::new("label")),
4473 ));
4474
4475 let search_icon = tester.element(find::by_icon(&Icons::search()).first());
4476 let dropdown_icon = *tester
4477 .descendants_of_type::<waft_widgets::RichText>(search_icon)
4478 .last()
4479 .expect("the glyph of the search icon");
4480 let dropdown_icon_rect = tester.get_rect(dropdown_icon);
4481
4482 tap_dropdown_menu::<TestMenu>(tester);
4483 tester.pump_and_settle();
4484 let item_leading_icon = *find_by_key(tester, &leading_icon_key(TestMenu::MainMenu0))
4485 .last()
4486 .expect("the first item's leading icon");
4487 (dropdown_icon_rect, tester.get_rect(item_leading_icon))
4488 }
4489
4490 #[test]
4492 fn the_item_icon_lines_up_with_the_field_icon_in_ltr() {
4493 test_widgets(|tester| {
4494 let (field_icon, item_icon) = field_and_item_icon_rects(tester, TextDirection::Ltr);
4495 assert_eq!(field_icon.left, item_icon.left);
4496 });
4497 }
4498
4499 #[test]
4501 fn the_item_icon_lines_up_with_the_field_icon_in_rtl() {
4502 test_widgets(|tester| {
4503 let (field_icon, item_icon) = field_and_item_icon_rects(tester, TextDirection::Rtl);
4504 assert_eq!(field_icon.right, item_icon.right);
4505 });
4506 }
4507
4508 fn controller(tester: &WidgetTester) -> TextEditingControllerRef {
4509 TextEditingController::new(&mut tester.cell.borrow_mut()).into_erased()
4510 }
4511
4512 fn controller_text(tester: &WidgetTester, controller: AnyTextEditingController) -> String {
4513 controller.text_value(&tester.cell.borrow()).to_owned()
4514 }
4515
4516 fn controller_selection(
4517 tester: &WidgetTester,
4518 controller: AnyTextEditingController,
4519 ) -> TextSelection {
4520 controller.selection(&tester.cell.borrow())
4521 }
4522
4523 fn collapsed(offset: i32) -> TextSelection {
4524 TextSelection::collapsed(offset, TextAffinity::Downstream)
4525 }
4526
4527 fn assert_left_and_right_keys_move_the_caret(
4530 tester: &mut WidgetTester,
4531 controller: AnyTextEditingController,
4532 ) {
4533 tap_dropdown_menu::<TestMenu>(tester);
4535 pump(tester);
4536
4537 tester.enter_text(find::by_type::<TextField>().first(), "example");
4538 pump(tester);
4539 assert_eq!(controller_text(tester, controller), "example");
4540 assert_eq!(controller_selection(tester, controller), collapsed(7));
4541
4542 send_key(tester, LogicalKeyboardKey::ARROW_LEFT);
4544 pump(tester);
4545 assert_eq!(controller_selection(tester, controller), collapsed(6));
4546
4547 send_key(tester, LogicalKeyboardKey::ARROW_RIGHT);
4549 pump(tester);
4550 assert_eq!(controller_selection(tester, controller), collapsed(7));
4551 }
4552
4553 fn case_sensitive_filter(
4554 _app: &mut App,
4555 entries: &[DropdownMenuEntry<TestMenu>],
4556 filter: &str,
4557 ) -> Vec<DropdownMenuEntry<TestMenu>> {
4558 entries
4559 .iter()
4560 .filter(|element| element.label.contains(filter))
4561 .cloned()
4562 .collect()
4563 }
4564
4565 #[test]
4567 fn the_left_and_right_keys_move_the_caret() {
4568 test_widgets(|tester| {
4569 let theme = theme(tester);
4570 let controller = controller(tester);
4571 tester.pump_widget(the_menu(
4572 theme,
4573 DropdownMenu::new(menu_children())
4574 .request_focus_on_tap(true)
4575 .enable_filter(true)
4576 .filter_callback(case_sensitive_filter)
4577 .controller(controller.clone()),
4578 ));
4579 assert_left_and_right_keys_move_the_caret(tester, controller.handle());
4580 });
4581 }
4582
4583 #[test]
4585 fn the_left_and_right_keys_move_the_caret_with_expanded_insets() {
4586 test_widgets(|tester| {
4587 let theme = theme(tester);
4588 let controller = controller(tester);
4589 tester.pump_widget(the_menu(
4590 theme,
4591 DropdownMenu::new(menu_children())
4592 .expanded_insets(EdgeInsetsGeometry::ZERO)
4593 .request_focus_on_tap(true)
4594 .enable_filter(true)
4595 .filter_callback(case_sensitive_filter)
4596 .controller(controller.clone()),
4597 ));
4598 assert_left_and_right_keys_move_the_caret(tester, controller.handle());
4599 });
4600 }
4601
4602 #[test]
4604 fn the_up_and_down_keys_highlight_items_with_expanded_insets() {
4605 test_widgets(|tester| {
4606 let theme = theme(tester);
4607 tester.pump_widget(the_menu(
4608 theme.clone(),
4609 DropdownMenu::new(menu_children())
4610 .expanded_insets(EdgeInsetsGeometry::ZERO)
4611 .request_focus_on_tap(true),
4612 ));
4613
4614 tap_dropdown_menu::<TestMenu>(tester);
4615 pump(tester);
4616
4617 send_key(tester, LogicalKeyboardKey::ARROW_UP);
4618 pump(tester);
4619 assert!(is_item_highlighted(tester, &theme, "Item 5"));
4620
4621 send_key(tester, LogicalKeyboardKey::ARROW_UP);
4623 pump(tester);
4624 assert!(is_item_highlighted(tester, &theme, "Item 4"));
4625
4626 assert!(!is_item_highlighted(tester, &theme, "Item 5"));
4628
4629 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4631 pump(tester);
4632 assert!(is_item_highlighted(tester, &theme, "Item 5"));
4633 });
4634 }
4635
4636 fn abc_entries() -> Vec<DropdownMenuEntry<i32>> {
4637 vec![
4638 DropdownMenuEntry::new(0, "ABC"),
4639 DropdownMenuEntry::new(1, "AB"),
4640 DropdownMenuEntry::new(2, "ABCD"),
4641 ]
4642 }
4643
4644 fn assert_navigation_over_nested_labels(tester: &mut WidgetTester, theme: &ThemeData) {
4647 tap_dropdown_menu::<i32>(tester);
4648 pump(tester);
4649
4650 for label in ["ABC", "AB", "ABCD"] {
4652 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4653 pump(tester);
4654 assert!(is_item_highlighted(tester, theme, label), "{label}");
4655 }
4656
4657 for label in ["AB", "ABC"] {
4659 send_key(tester, LogicalKeyboardKey::ARROW_UP);
4660 pump(tester);
4661 assert!(is_item_highlighted(tester, theme, label), "{label}");
4662 }
4663 }
4664
4665 #[test]
4668 fn the_arrow_keys_navigate_labels_that_contain_each_other() {
4669 test_widgets(|tester| {
4670 let theme = theme(tester);
4671 tester.pump_widget(the_menu(
4672 theme.clone(),
4673 DropdownMenu::new(abc_entries()).request_focus_on_tap(true),
4674 ));
4675 assert_navigation_over_nested_labels(tester, &theme);
4676 });
4677 }
4678
4679 #[test]
4681 fn searching_for_a_non_matching_item_does_not_panic() {
4682 test_widgets(|tester| {
4683 let theme = theme(tester);
4684 tester.pump_widget(the_menu(
4685 theme,
4686 DropdownMenu::new(menu_children())
4687 .enable_filter(true)
4688 .request_focus_on_tap(true),
4689 ));
4690
4691 tap_dropdown_menu::<TestMenu>(tester);
4693 pump(tester);
4694 tester.enter_text(find::by_type::<TextField>().first(), "Me");
4695 pump(tester);
4696 tester.enter_text(find::by_type::<TextField>().first(), "Meu");
4697 pump(tester);
4698 });
4699 }
4700
4701 #[test]
4703 fn keyboard_navigation_over_no_matching_entries_does_not_panic() {
4704 test_widgets(|tester| {
4705 let theme = theme(tester);
4706 tester.pump_widget(the_menu(
4707 theme,
4708 DropdownMenu::new(menu_children())
4709 .request_focus_on_tap(true)
4710 .enable_filter(true),
4711 ));
4712 tap_dropdown_menu::<TestMenu>(tester);
4713 pump(tester);
4714 tester.enter_text(find::by_type::<TextField>().first(), "No match");
4715 pump(tester);
4716 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4717 pump(tester);
4718 tester.enter_text(find::by_type::<TextField>().first(), "No match 2");
4719 pump(tester);
4720 });
4721 }
4722
4723 #[test]
4725 fn keyboard_navigation_traverses_only_the_filtered_entries() {
4726 test_widgets(|tester| {
4727 let theme = theme(tester);
4728 let controller = controller(tester);
4729 tester.pump_widget(the_menu(
4730 theme,
4731 DropdownMenu::new(vec![
4732 DropdownMenuEntry::new(TestMenu::MainMenu0, "Good Match 1"),
4733 DropdownMenuEntry::new(TestMenu::MainMenu1, "Bad Match 1"),
4734 DropdownMenuEntry::new(TestMenu::MainMenu2, "Good Match 2"),
4735 DropdownMenuEntry::new(TestMenu::MainMenu3, "Bad Match 2"),
4736 DropdownMenuEntry::new(TestMenu::MainMenu4, "Good Match 3"),
4737 DropdownMenuEntry::new(TestMenu::MainMenu5, "Bad Match 3"),
4738 ])
4739 .request_focus_on_tap(true)
4740 .enable_filter(true)
4741 .controller(controller.clone()),
4742 ));
4743
4744 tap_dropdown_menu::<TestMenu>(tester);
4746 pump(tester);
4747
4748 tester.enter_text(find::by_type::<TextField>().first(), "Good Match");
4750 pump(tester);
4751
4752 for expected in ["Good Match 2", "Good Match 3", "Good Match 1"] {
4755 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4756 pump(tester);
4757 assert_eq!(controller_text(tester, controller.handle()), expected);
4758 }
4759 });
4760 }
4761
4762 #[test]
4764 fn the_default_search_keeps_the_current_highlight_when_it_still_matches() {
4765 test_widgets(|tester| {
4766 let theme = theme(tester);
4767 tester.pump_widget(the_menu(
4768 theme.clone(),
4769 DropdownMenu::new(menu_children()).request_focus_on_tap(true),
4770 ));
4771
4772 let item_label = "Item 2";
4773 tap_dropdown_menu::<TestMenu>(tester);
4775 pump(tester);
4776 tester.enter_text(find::by_type::<TextField>().first(), item_label);
4778 pump(tester);
4779 assert!(is_item_highlighted(tester, &theme, item_label));
4780
4781 tester.enter_text(find::by_type::<TextField>().first(), "Item");
4783 pump(tester);
4784 assert!(is_item_highlighted(tester, &theme, item_label));
4786 });
4787 }
4788
4789 const ALL_PLATFORMS: [TargetPlatform; 6] = [
4790 TargetPlatform::Android,
4791 TargetPlatform::Fuchsia,
4792 TargetPlatform::IOS,
4793 TargetPlatform::Linux,
4794 TargetPlatform::MacOS,
4795 TargetPlatform::Windows,
4796 ];
4797
4798 const MOBILE_PLATFORMS: [TargetPlatform; 3] = [
4799 TargetPlatform::Android,
4800 TargetPlatform::IOS,
4801 TargetPlatform::Fuchsia,
4802 ];
4803
4804 const DESKTOP_PLATFORMS: [TargetPlatform; 3] = [
4805 TargetPlatform::Linux,
4806 TargetPlatform::MacOS,
4807 TargetPlatform::Windows,
4808 ];
4809
4810 fn text_field_shows(tester: &WidgetTester, text: &str) -> bool {
4813 let fields = find::by_type::<TextField>().evaluate(tester);
4814 fields.len() == 1
4815 && editable(tester, |editable| {
4816 editable.controller.text_value(&tester.cell.borrow()) == text
4817 })
4818 }
4819
4820 fn hit_testable(tester: &WidgetTester, element: AnyElement) -> bool {
4823 let render = tester.render_box_of(element);
4824 let center = tester.global_rect(render).center();
4825 let mut app = tester.cell.borrow_mut();
4826 let view_id = app.platform().views()[0].id();
4827 let mut result = waft_gestures::HitTestResult::new();
4828 waft_gestures::GestureBinding::instance(&mut app).hit_test_in_view(
4829 &mut app,
4830 &mut result,
4831 center,
4832 view_id,
4833 );
4834 result.path().iter().any(|entry| {
4835 (entry.target() as &dyn std::any::Any)
4836 .downcast_ref::<waft_rendering::BoxHitTestEntry>()
4837 .is_some_and(|entry| entry.target() == render)
4838 })
4839 }
4840
4841 fn tap_item(tester: &mut WidgetTester, label: &str) {
4842 let item = find_menu_item_button(tester, label);
4843 tap(tester, item);
4844 }
4845
4846 #[test]
4849 fn the_arrow_keys_navigate_labels_that_contain_each_other_with_a_custom_search() {
4850 test_widgets(|tester| {
4851 let theme = theme(tester);
4852 tester.pump_widget(the_menu(
4853 theme.clone(),
4854 DropdownMenu::new(abc_entries())
4855 .request_focus_on_tap(true)
4856 .search_callback(|_app, entries, query| {
4857 if query.is_empty() {
4858 return None;
4859 }
4860 entries.iter().position(|entry| entry.label.contains(query))
4861 }),
4862 ));
4863 assert_navigation_over_nested_labels(tester, &theme);
4864 });
4865 }
4866
4867 #[test]
4869 fn searching_highlights_an_entry_after_keyboard_navigation() {
4870 test_widgets(|tester| {
4871 let theme = theme(tester);
4872 let entries = menu_children();
4873 tester.pump_widget(the_menu(
4874 theme.clone(),
4875 DropdownMenu::new(Rc::clone(&entries)).request_focus_on_tap(true),
4876 ));
4877
4878 tap_dropdown_menu::<TestMenu>(tester);
4880 pump(tester);
4881 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4882 pump(tester);
4883 let searched_label = entries.last().expect("entries").label.clone();
4885 tester.enter_text(find::by_type::<TextField>().first(), &searched_label);
4886 pump(tester);
4887 assert!(is_item_highlighted(tester, &theme, &searched_label));
4889 });
4890 }
4891
4892 #[test]
4895 fn the_down_key_puts_the_highlighted_label_in_the_field() {
4896 test_widgets(|tester| {
4897 let theme = theme(tester);
4898 tester.pump_widget(the_menu(
4899 theme,
4900 DropdownMenu::new(menu_children()).request_focus_on_tap(true),
4901 ));
4902
4903 tap_dropdown_menu::<TestMenu>(tester);
4905 pump(tester);
4906
4907 for label in ["Item 0", "Menu 1", "Item 2"] {
4908 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4909 pump(tester);
4910 assert!(text_field_shows(tester, label), "{label}");
4911 }
4912 });
4913 }
4914
4915 #[test]
4918 fn the_up_key_puts_the_highlighted_label_in_the_field() {
4919 test_widgets(|tester| {
4920 let theme = theme(tester);
4921 tester.pump_widget(the_menu(
4922 theme,
4923 DropdownMenu::new(menu_children()).request_focus_on_tap(true),
4924 ));
4925
4926 tap_dropdown_menu::<TestMenu>(tester);
4928 pump(tester);
4929
4930 for label in ["Item 5", "Item 4", "Item 3"] {
4931 send_key(tester, LogicalKeyboardKey::ARROW_UP);
4932 pump(tester);
4933 assert!(text_field_shows(tester, label), "{label}");
4934 }
4935 });
4936 }
4937
4938 #[test]
4940 fn the_arrow_keys_skip_disabled_items() {
4941 test_widgets(|tester| {
4942 let theme = theme(tester);
4943 tester.pump_widget(the_menu(
4944 theme.clone(),
4945 DropdownMenu::new(vec![
4946 DropdownMenuEntry::new(TestMenu::MainMenu0, "Item 0"),
4947 DropdownMenuEntry::new(TestMenu::MainMenu1, "Item 1").enabled(false),
4948 DropdownMenuEntry::new(TestMenu::MainMenu2, "Item 2").enabled(false),
4949 DropdownMenuEntry::new(TestMenu::MainMenu3, "Item 3"),
4950 DropdownMenuEntry::new(TestMenu::MainMenu4, "Item 4"),
4951 DropdownMenuEntry::new(TestMenu::MainMenu5, "Item 5").enabled(false),
4952 ])
4953 .request_focus_on_tap(true),
4954 ));
4955 pump(tester);
4956
4957 tap_dropdown_menu::<TestMenu>(tester);
4959 tester.pump_and_settle();
4960
4961 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4962 tester.pump_and_settle();
4963
4964 assert!(is_item_highlighted(tester, &theme, "Item 0"));
4966
4967 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
4969 tester.pump_and_settle();
4970 assert!(is_item_highlighted(tester, &theme, "Item 3"));
4971 });
4972 }
4973
4974 #[test]
4976 fn an_initial_selection_is_highlighted_when_the_menu_opens() {
4977 test_widgets(|tester| {
4978 let theme = theme(tester);
4979 tester.pump_widget(the_menu(
4980 theme.clone(),
4981 DropdownMenu::new(menu_children())
4982 .request_focus_on_tap(true)
4983 .initial_selection(TestMenu::MainMenu1),
4984 ));
4985
4986 tap_dropdown_menu::<TestMenu>(tester);
4988 pump(tester);
4989
4990 assert!(is_item_highlighted(tester, &theme, "Menu 1"));
4992 });
4993 }
4994
4995 #[test]
4997 fn the_highlight_moves_from_the_search_result() {
4998 test_widgets(|tester| {
4999 let theme = theme(tester);
5000 tester.pump_widget(the_menu(
5001 theme.clone(),
5002 DropdownMenu::new(menu_children()).request_focus_on_tap(true),
5003 ));
5004
5005 tap_dropdown_menu::<TestMenu>(tester);
5007 pump(tester);
5008 tester.enter_text(find::by_type::<TextField>().first(), "Menu 1");
5009 tester.pump_and_settle();
5010 assert!(is_item_highlighted(tester, &theme, "Menu 1"));
5011
5012 for label in ["Item 0", "Item 5"] {
5014 send_key(tester, LogicalKeyboardKey::ARROW_UP);
5015 tester.pump_and_settle();
5016 assert!(text_field_shows(tester, label), "{label}");
5017 assert!(is_item_highlighted(tester, &theme, label), "{label}");
5018 }
5019 });
5020 }
5021
5022 #[test]
5024 fn filtering_is_off_by_default() {
5025 test_widgets(|tester| {
5026 let theme = theme(tester);
5027 tester.pump_widget(the_menu(
5028 theme,
5029 DropdownMenu::new(menu_children()).request_focus_on_tap(true),
5030 ));
5031
5032 tap_dropdown_menu::<TestMenu>(tester);
5034 pump(tester);
5035
5036 tester.enter_text(find::by_type::<TextField>().first(), "Menu 1");
5037 tester.pump_and_settle();
5038 for menu in TestMenu::VALUES {
5039 assert_eq!(
5041 widgets_with_text::<MenuItemButton>(tester, menu.label()).len(),
5042 2,
5043 "{menu:?}"
5044 );
5045 }
5046 });
5047 }
5048
5049 #[test]
5051 fn enabled_filtering_shows_only_the_matching_items() {
5052 test_widgets(|tester| {
5053 let theme = theme(tester);
5054 tester.pump_widget(the_menu(
5055 theme,
5056 DropdownMenu::new(menu_children())
5057 .request_focus_on_tap(true)
5058 .enable_filter(true),
5059 ));
5060
5061 tap_dropdown_menu::<TestMenu>(tester);
5063 pump(tester);
5064
5065 tester.enter_text(find::by_type::<TextField>().first(), "Menu 1");
5066 tester.pump_and_settle();
5067 for menu in TestMenu::VALUES {
5068 let expected = if menu == TestMenu::MainMenu1 { 2 } else { 1 };
5070 assert_eq!(
5071 widgets_with_text::<MenuItemButton>(tester, menu.label()).len(),
5072 expected,
5073 "{menu:?}"
5074 );
5075 }
5076 });
5077 }
5078
5079 #[test]
5081 fn a_custom_filter_callback_filters_the_items() {
5082 test_widgets(|tester| {
5083 let theme = theme(tester);
5084 let controller = controller(tester);
5085 tester.pump_widget(the_menu(
5086 theme,
5087 DropdownMenu::new(menu_children())
5088 .request_focus_on_tap(true)
5089 .enable_filter(true)
5090 .filter_callback(case_sensitive_filter)
5091 .controller(controller.clone()),
5092 ));
5093
5094 tap_dropdown_menu::<TestMenu>(tester);
5096 pump(tester);
5097
5098 tester.enter_text(find::by_type::<TextField>().first(), "item");
5099 assert_eq!(controller_text(tester, controller.handle()), "item");
5100 tester.pump_and_settle();
5101 for menu in TestMenu::VALUES {
5102 let button = find_menu_item_button(tester, menu.label());
5103 assert!(!hit_testable(tester, button), "{menu:?}");
5104 }
5105
5106 tester.enter_text(find::by_type::<TextField>().first(), "Item");
5107 assert_eq!(controller_text(tester, controller.handle()), "Item");
5108 tester.pump_and_settle();
5109 for (label, shown) in [
5110 ("Item 0", true),
5111 ("Menu 1", false),
5112 ("Item 2", true),
5113 ("Item 3", true),
5114 ("Item 4", true),
5115 ("Item 5", true),
5116 ] {
5117 let button = find_menu_item_button(tester, label);
5118 assert_eq!(hit_testable(tester, button), shown, "{label}");
5119 }
5120 });
5121 }
5122
5123 #[test]
5126 #[should_panic(expected = "self.filter_callback.is_none() || self.enable_filter")]
5127 fn a_filter_callback_without_enabled_filtering_panics() {
5128 let menu = DropdownMenu::new(menu_children())
5129 .request_focus_on_tap(true)
5130 .filter_callback(case_sensitive_filter);
5131 let _ = menu.into_widget();
5132 }
5133
5134 #[test]
5136 fn the_controller_holds_the_text_of_the_field() {
5137 test_widgets(|tester| {
5138 let theme = theme(tester);
5139 let controller = controller(tester);
5140 tester.pump_widget(the_menu(
5141 theme,
5142 DropdownMenu::new(menu_children())
5143 .request_focus_on_tap(true)
5144 .enable_filter(true)
5145 .controller(controller.clone()),
5146 ));
5147
5148 tap_dropdown_menu::<TestMenu>(tester);
5150 pump(tester);
5151 tap_item(tester, "Item 3");
5152 tester.pump_and_settle();
5153
5154 assert_eq!(controller_text(tester, controller.handle()), "Item 3");
5155
5156 tester.enter_text(find::by_type::<TextField>().first(), "New Item");
5157 assert_eq!(controller_text(tester, controller.handle()), "New Item");
5158 });
5159 }
5160
5161 fn menu_controller_is_open(tester: &WidgetTester) -> bool {
5162 let anchor = tester.element(find::by_type::<MenuAnchor>());
5163 let controller = tester.widget(anchor, |anchor: &MenuAnchor| {
5164 anchor.controller.clone().expect("a controller")
5165 });
5166 controller.is_open(&tester.cell.borrow())
5167 }
5168
5169 #[test]
5171 fn completing_the_text_editing_closes_the_menu() {
5172 test_widgets(|tester| {
5173 let theme = theme(tester);
5174 let controller = controller(tester);
5175 tester.pump_widget(the_menu(
5176 theme,
5177 DropdownMenu::new(menu_children())
5178 .request_focus_on_tap(true)
5179 .enable_filter(true)
5180 .controller(controller),
5181 ));
5182
5183 tap_dropdown_menu::<TestMenu>(tester);
5185 tester.pump_and_settle();
5186 assert!(menu_controller_is_open(tester));
5187
5188 tester
5190 .test_text_input()
5191 .receive_action(TextInputAction::Done);
5192 tester.pump_and_settle();
5193 assert!(!menu_controller_is_open(tester));
5194 });
5195 }
5196
5197 #[test]
5199 fn on_selected_is_called_only_when_a_selection_is_made() {
5200 for platform in ALL_PLATFORMS {
5201 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
5202 let theme = theme(tester);
5203 let controller = controller(tester);
5204 let selection_count = Rc::new(std::cell::Cell::new(0));
5205 let count = Rc::clone(&selection_count);
5206 tester.pump_widget(the_menu(
5207 theme.clone(),
5208 DropdownMenu::new(vec![
5209 DropdownMenuEntry::new(TestMenu::MainMenu0, "Item 0"),
5210 DropdownMenuEntry::new(TestMenu::MainMenu1, "Item 1").enabled(false),
5211 DropdownMenuEntry::new(TestMenu::MainMenu2, "Item 2"),
5212 DropdownMenuEntry::new(TestMenu::MainMenu3, "Item 3"),
5213 ])
5214 .controller(controller.clone())
5215 .on_selected(move |_app, _value| count.set(count.get() + 1)),
5216 ));
5217
5218 tap_dropdown_menu::<TestMenu>(tester);
5220 pump(tester);
5221 let is_mobile = MOBILE_PLATFORMS.contains(&theme.platform);
5222 let mut expected_count = 1;
5223
5224 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
5226 tester.pump_and_settle();
5227
5228 if is_mobile {
5232 send_key(tester, LogicalKeyboardKey::ENTER);
5233 } else {
5234 tester
5235 .test_text_input()
5236 .receive_action(TextInputAction::Done);
5237 }
5238 tester.pump_and_settle();
5239 assert_eq!(selection_count.get(), expected_count, "{platform:?}");
5240
5241 tap_dropdown_menu::<TestMenu>(tester);
5243 pump(tester);
5244
5245 tap_item(tester, "Item 1");
5247 tester.pump_and_settle();
5248 assert_eq!(controller_text(tester, controller.handle()), "Item 0");
5249 assert_eq!(selection_count.get(), expected_count, "{platform:?}");
5250
5251 tap_item(tester, "Item 2");
5252 tester.pump_and_settle();
5253 assert_eq!(controller_text(tester, controller.handle()), "Item 2");
5254 expected_count += 1;
5255 assert_eq!(selection_count.get(), expected_count, "{platform:?}");
5256
5257 tap_dropdown_menu::<TestMenu>(tester);
5258 pump(tester);
5259 tap_item(tester, "Item 3");
5260 tester.pump_and_settle();
5261 assert_eq!(controller_text(tester, controller.handle()), "Item 3");
5262 expected_count += 1;
5263 assert_eq!(selection_count.get(), expected_count, "{platform:?}");
5264
5265 if !is_mobile {
5268 tester.enter_text(find::by_type::<TextField>().first(), "New Item");
5269 assert_eq!(controller_text(tester, controller.handle()), "New Item");
5270 assert_eq!(selection_count.get(), expected_count, "{platform:?}");
5271 assert!(text_field_shows(tester, "New Item"));
5272 tester.enter_text(find::by_type::<TextField>().first(), "");
5273 assert_eq!(selection_count.get(), expected_count, "{platform:?}");
5274 assert!(controller_text(tester, controller.handle()).is_empty());
5275 }
5276 });
5277 }
5278 }
5279
5280 #[test]
5282 fn the_initial_selection_fills_the_field_and_highlights_its_item() {
5283 test_widgets(|tester| {
5284 let theme = theme(tester);
5285 let controller = controller(tester);
5286 tester.pump_widget(the_menu(
5287 theme.clone(),
5288 DropdownMenu::new(menu_children())
5289 .initial_selection(TestMenu::MainMenu3)
5290 .controller(controller),
5291 ));
5292
5293 assert!(text_field_shows(tester, "Item 3"));
5294
5295 tap_dropdown_menu::<TestMenu>(tester);
5297 pump(tester);
5298
5299 assert!(is_item_highlighted(tester, &theme, "Item 3"));
5301 });
5302 }
5303
5304 #[test]
5307 fn a_matching_initial_selection_shows_its_label() {
5308 test_widgets(|tester| {
5309 let theme = theme(tester);
5310 let controller = controller(tester);
5311 tester.pump_widget(the_menu(
5312 theme,
5313 DropdownMenu::new(menu_children())
5314 .initial_selection(TestMenu::MainMenu3)
5315 .controller(controller.clone()),
5316 ));
5317 assert_eq!(
5318 controller_text(tester, controller.handle()),
5319 TestMenu::MainMenu3.label()
5320 );
5321 });
5322 }
5323
5324 #[test]
5326 fn an_initial_selection_matching_no_entry_leaves_the_field_empty() {
5327 test_widgets(|tester| {
5328 let theme = theme(tester);
5329 let controller = controller(tester);
5330 tester.pump_widget(the_menu(
5331 theme,
5332 DropdownMenu::new(menu_children()[0..1].to_vec())
5334 .initial_selection(TestMenu::MainMenu3)
5335 .controller(controller.clone()),
5336 ));
5337 assert!(controller_text(tester, controller.handle()).is_empty());
5338 });
5339 }
5340
5341 #[test]
5344 fn an_initial_selection_matching_no_entry_keeps_the_controller_text() {
5345 test_widgets(|tester| {
5346 let theme = theme(tester);
5347 let controller = {
5348 let mut app = tester.cell.borrow_mut();
5349 TextEditingController::new(&mut app)
5350 .text(&mut app, "Flutter")
5351 .into_erased::<waft_widgets::AnyTextEditingController>()
5352 };
5353 tester.pump_widget(the_menu(
5354 theme,
5355 DropdownMenu::new(menu_children()[0..1].to_vec())
5357 .initial_selection(TestMenu::MainMenu3)
5358 .controller(controller.clone()),
5359 ));
5360 assert_eq!(controller_text(tester, controller.handle()), "Flutter");
5361 });
5362 }
5363
5364 fn column_menu(theme: ThemeData, menu: DropdownMenu<TestMenu>) -> WidgetRef {
5365 material_app(
5366 theme,
5367 Scaffold::new()
5368 .body(waft_widgets::Column::new().children(vec![menu.into_widget()]))
5369 .into_widget(),
5370 )
5371 }
5372
5373 #[test]
5376 fn the_text_field_cannot_request_focus_by_default_on_mobile() {
5377 for platform in MOBILE_PLATFORMS {
5378 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
5379 let theme = theme(tester);
5380 tester.pump_widget(column_menu(theme, DropdownMenu::new(menu_children())));
5381 pump(tester);
5382 text_field(tester, |text_field| {
5383 assert!(!text_field.can_request_focus, "{platform:?}");
5384 });
5385 });
5386 }
5387 }
5388
5389 #[test]
5392 fn the_text_field_can_request_focus_by_default_on_desktop() {
5393 for platform in DESKTOP_PLATFORMS {
5394 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
5395 let theme = theme(tester);
5396 tester.pump_widget(column_menu(theme, DropdownMenu::new(menu_children())));
5397 pump(tester);
5398 text_field(tester, |text_field| {
5399 assert!(text_field.can_request_focus, "{platform:?}");
5400 });
5401 });
5402 }
5403 }
5404
5405 #[test]
5408 fn request_focus_on_tap_decides_whether_the_field_can_request_focus() {
5409 for platform in ALL_PLATFORMS {
5410 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
5411 let theme = theme(tester);
5412 let entries = menu_children();
5413
5414 tester.pump_widget(column_menu(
5416 theme.clone(),
5417 DropdownMenu::new(Rc::clone(&entries)).request_focus_on_tap(true),
5418 ));
5419 pump(tester);
5420 text_field(tester, |text_field| {
5421 assert!(text_field.can_request_focus, "{platform:?}");
5422 });
5423 tap_first::<TextField>(tester);
5425 pump(tester);
5426 tap_item(tester, "Item 0");
5428 pump(tester);
5429 assert_eq!(
5430 widgets_with_text::<MenuItemButton>(tester, "Item 0").len(),
5431 1
5432 );
5433
5434 tester.pump_widget(SizedBox::new().into_widget());
5436 tester.pump_widget(column_menu(
5437 theme,
5438 DropdownMenu::new(entries).request_focus_on_tap(false),
5439 ));
5440 tester.pump_and_settle();
5441 text_field(tester, |text_field| {
5442 assert!(!text_field.can_request_focus, "{platform:?}");
5443 });
5444 tap_first::<TextField>(tester);
5446 pump(tester);
5447 tap_item(tester, "Item 0");
5449 pump(tester);
5450 assert!(text_field_shows(tester, "Item 0"), "{platform:?}");
5451 });
5452 }
5453 }
5454
5455 fn mouse_over_the_text_field(tester: &mut WidgetTester) -> TestPointer {
5458 let center = tester.get_rect(first::<TextField>(tester)).center();
5459 let mut mouse = TestPointer::mouse(1, 0);
5460 tester.add_pointer(&mut mouse, center);
5461 mouse
5462 }
5463
5464 fn cursor_is(tester: &WidgetTester, cursor: waft_services::SystemMouseCursor) -> bool {
5465 let expected: MouseCursorRef = cursor.into();
5466 *tester.active_cursor(1) == *expected
5467 }
5468
5469 #[test]
5471 fn a_field_that_cannot_request_focus_shows_the_click_cursor() {
5472 test_widgets(|tester| {
5473 let theme = theme(tester);
5474 tester.pump_widget(column_menu(
5475 theme,
5476 DropdownMenu::new(menu_children()).request_focus_on_tap(false),
5477 ));
5478 tester.pump_and_settle();
5479
5480 text_field(tester, |text_field| assert!(!text_field.can_request_focus));
5481 mouse_over_the_text_field(tester);
5482 assert!(cursor_is(tester, SystemMouseCursors::CLICK));
5483 });
5484 }
5485
5486 #[test]
5488 fn a_disabled_field_defers_the_cursor() {
5489 test_widgets(|tester| {
5490 let theme = theme(tester);
5491 let entries = menu_children();
5492
5493 tester.pump_widget(column_menu(
5495 theme.clone(),
5496 DropdownMenu::new(Rc::clone(&entries))
5497 .enabled(false)
5498 .request_focus_on_tap(true),
5499 ));
5500 tester.pump_and_settle();
5501 text_field(tester, |text_field| assert!(text_field.can_request_focus));
5502 let mouse = mouse_over_the_text_field(tester);
5503 assert!(cursor_is(tester, SystemMouseCursors::BASIC));
5504 tester.send(&mouse, waft_embedder::PointerChange::Remove);
5506
5507 tester.pump_widget(column_menu(
5509 theme.clone(),
5510 DropdownMenu::new(Rc::clone(&entries))
5511 .enabled(false)
5512 .request_focus_on_tap(false),
5513 ));
5514 tester.pump_and_settle();
5515 text_field(tester, |text_field| assert!(!text_field.can_request_focus));
5516 let mouse = mouse_over_the_text_field(tester);
5518 assert!(cursor_is(tester, SystemMouseCursors::BASIC));
5519 tester.send(&mouse, waft_embedder::PointerChange::Remove);
5521
5522 tester.pump_widget(column_menu(
5524 theme,
5525 DropdownMenu::new(entries).request_focus_on_tap(true),
5526 ));
5527 tester.pump_and_settle();
5528 text_field(tester, |text_field| assert!(text_field.can_request_focus));
5529 mouse_over_the_text_field(tester);
5531 assert!(cursor_is(tester, SystemMouseCursors::TEXT));
5532 });
5533 }
5534
5535 fn list_view_menu(menu: DropdownMenu<TestMenu>) -> impl FnOnce(&mut App) -> WidgetRef {
5536 move |app| {
5537 material_app(
5538 m3(app),
5539 Scaffold::new()
5540 .body(waft_widgets::ListView::new().children(vec![menu.into_widget()]))
5541 .into_widget(),
5542 )
5543 }
5544 }
5545
5546 #[test]
5548 fn in_a_list_view_the_menu_is_as_wide_as_the_field() {
5549 test_widgets(|tester| {
5550 let entries = menu_children();
5551 pump_app(
5552 tester,
5553 list_view_menu(DropdownMenu::new(Rc::clone(&entries))),
5554 );
5555
5556 let text_input = tester.get_rect(first::<TextField>(tester));
5557 tap_first::<TextField>(tester);
5558 tester.pump_and_settle();
5559 let menu = tester.get_rect(tester.element(find::by_type::<MenuPanel>()));
5560 assert_eq!(text_input.width(), menu.width());
5561
5562 tester.pump_widget(SizedBox::new().into_widget());
5563 pump_app(
5564 tester,
5565 list_view_menu(DropdownMenu::new(entries).width(200.0)),
5566 );
5567
5568 let text_input1 = tester.get_rect(first::<TextField>(tester));
5569 tap_first::<TextField>(tester);
5570 tester.pump_and_settle();
5571 let menu1 = tester.get_rect(tester.element(find::by_type::<MenuPanel>()));
5572 assert_eq!(text_input1.width(), 200.0);
5573 assert_eq!(menu1.width(), 200.0);
5574 });
5575 }
5576
5577 fn centered_menu(theme: ThemeData, menu: DropdownMenu<TestMenu>) -> WidgetRef {
5578 material_app(
5579 theme,
5580 Scaffold::new()
5581 .body(waft_widgets::Center::new().child(menu))
5582 .into_widget(),
5583 )
5584 }
5585
5586 #[test]
5588 fn an_error_text_hides_the_helper_text() {
5589 test_widgets(|tester| {
5590 let theme = theme(tester);
5591 let entries = menu_children();
5592 let helper_text = "I am helperText";
5593 let error_text = "I am errorText";
5594 let build_frame = |has_error: bool| {
5595 let mut menu = DropdownMenu::new(Rc::clone(&entries)).helper_text(helper_text);
5596 if has_error {
5597 menu = menu.error_text(error_text);
5598 }
5599 centered_menu(theme.clone(), menu)
5600 };
5601
5602 tester.pump_widget(build_frame(false));
5603 expect(tester, &find::text(helper_text), finds_one_widget());
5604 expect(tester, &find::text(error_text), finds_nothing());
5605
5606 tester.pump_widget(build_frame(true));
5607 tester.pump_and_settle();
5608 expect(tester, &find::text(helper_text), finds_nothing());
5609 expect(tester, &find::text(error_text), finds_one_widget());
5610 });
5611 }
5612
5613 #[test]
5615 fn the_helper_text_shows_below_the_field() {
5616 test_widgets(|tester| {
5617 let theme = theme(tester);
5618 let helper_text = "I am helperText";
5619 tester.pump_widget(centered_menu(
5620 theme,
5621 DropdownMenu::new(menu_children()).helper_text(helper_text),
5622 ));
5623 expect(tester, &find::text(helper_text), finds_one_widget());
5624 });
5625 }
5626
5627 #[test]
5629 fn the_error_text_shows_below_the_field() {
5630 test_widgets(|tester| {
5631 let theme = theme(tester);
5632 let error_text = "I am errorText";
5633 tester.pump_widget(centered_menu(
5634 theme,
5635 DropdownMenu::new(menu_children()).error_text(error_text),
5636 ));
5637 expect(tester, &find::text(error_text), finds_one_widget());
5638 });
5639 }
5640
5641 fn text_is_hit_testable(tester: &WidgetTester, text: &str) -> bool {
5643 find::text(text)
5644 .evaluate(tester)
5645 .into_iter()
5646 .filter(|element| hit_testable(tester, *element))
5647 .count()
5648 == 1
5649 }
5650
5651 #[test]
5653 fn the_menu_scrolls_to_the_highlighted_item() {
5654 test_widgets(|tester| {
5655 let theme = theme(tester);
5656 tester.pump_widget(the_menu(
5657 theme,
5658 DropdownMenu::new(menu_children())
5659 .request_focus_on_tap(true)
5660 .menu_height(100.0),
5662 ));
5663 tester.pump_and_settle();
5664
5665 tap_dropdown_menu::<TestMenu>(tester);
5666 tester.pump_and_settle();
5667
5668 assert!(!text_is_hit_testable(tester, "Item 5"));
5669 tester.enter_text(find::by_type::<TextField>().first(), "5");
5670 tester.pump_and_settle();
5671 assert!(text_is_hit_testable(tester, "Item 5"));
5673 });
5674 }
5675
5676 #[test]
5678 fn material3_the_field_takes_body_large_and_the_items_label_large() {
5679 test_widgets(|tester| {
5680 let input_text_theme_style = TextStyle::new()
5681 .font_size(18.5)
5682 .font_style(waft_painting::FontStyle::Italic)
5683 .word_spacing(1.2)
5684 .decoration(waft_painting::TextDecoration::LINE_THROUGH);
5685 let menu_item_text_theme_style = TextStyle::new()
5686 .font_size(20.5)
5687 .font_style(waft_painting::FontStyle::Italic)
5688 .word_spacing(2.1)
5689 .decoration(waft_painting::TextDecoration::UNDERLINE);
5690 let theme = ThemeData::builder()
5691 .text_theme(
5692 crate::text_theme::TextTheme::new()
5693 .body_large(input_text_theme_style.clone())
5694 .label_large(menu_item_text_theme_style.clone()),
5695 )
5696 .build(&tester.cell.borrow());
5697 tester.pump_widget(BuildTest::default().build(theme, menu_children()));
5698
5699 editable(tester, |editable| {
5701 assert_eq!(editable.style.font_size, input_text_theme_style.font_size);
5702 assert_eq!(editable.style.font_style, input_text_theme_style.font_style);
5703 assert_eq!(
5704 editable.style.word_spacing,
5705 input_text_theme_style.word_spacing
5706 );
5707 assert_eq!(editable.style.decoration, input_text_theme_style.decoration);
5708 });
5709
5710 let icon_button = arrow_drop_down_button(tester);
5712 tap(tester, icon_button);
5713 pump(tester);
5714
5715 button_material(tester, TestMenu::MainMenu0.label(), |material| {
5717 let text_style = material.text_style.as_ref().expect("a text style");
5718 assert_eq!(text_style.font_size, menu_item_text_theme_style.font_size);
5719 assert_eq!(text_style.font_style, menu_item_text_theme_style.font_style);
5720 assert_eq!(
5721 text_style.word_spacing,
5722 menu_item_text_theme_style.word_spacing
5723 );
5724 assert_eq!(text_style.decoration, menu_item_text_theme_style.decoration);
5725 });
5726 });
5727 }
5728
5729 #[test]
5731 fn items_with_and_without_a_leading_icon_line_up_with_the_field_text() {
5732 test_widgets(|tester| {
5733 let theme = theme(tester);
5734 tester.pump_widget(the_menu(
5737 theme,
5738 DropdownMenu::new(vec![
5739 DropdownMenuEntry::new(0, "Item 0")
5740 .leading_icon(Icon::new(Some(Icons::alarm()))),
5741 DropdownMenuEntry::new(1, "Item 1"),
5742 ])
5743 .leading_icon(Icon::new(Some(Icons::search())))
5744 .hint_text("Hint"),
5745 ));
5746 tap_dropdown_menu::<i32>(tester);
5747 tester.pump_and_settle();
5748
5749 assert_eq!(tester.get_rect(find::text("Hint").first()).left, 52.0);
5751
5752 assert_eq!(tester.get_rect(find::text("Item 0").last()).left, 52.0);
5754
5755 assert_eq!(tester.get_rect(find::text("Item 1").last()).left, 52.0);
5758 });
5759 }
5760
5761 #[test]
5763 #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
5764 fn a_search_callback_decides_the_highlighted_item() {
5765 test_widgets(|tester| {
5766 let theme = theme(tester);
5767 let entries: Rc<[DropdownMenuEntry<i32>]> = Rc::from(vec![
5768 DropdownMenuEntry::new(0, "All"),
5769 DropdownMenuEntry::new(1, "Unread"),
5770 DropdownMenuEntry::new(2, "Read"),
5771 ]);
5772 let dropdown_menu = |search_callback: Option<SearchCallback<i32>>| {
5773 let mut menu = DropdownMenu::new(Rc::clone(&entries)).request_focus_on_tap(true);
5774 menu.search_callback = search_callback;
5775 the_menu(theme.clone(), menu)
5776 };
5777 let check_expected_highlight =
5778 |tester: &WidgetTester, search_result: Option<&str>, other_items: &[&str]| {
5779 if let Some(search_result) = search_result {
5780 let color =
5781 button_material(tester, search_result, |material| material.color);
5782 assert_eq!(
5783 color,
5784 Some(theme.color_scheme.on_surface().with_opacity(0.12))
5785 );
5786 }
5787 for non_highlight in other_items {
5788 let color =
5789 button_material(tester, non_highlight, |material| material.color);
5790 assert_eq!(color, Some(Colors::TRANSPARENT), "{non_highlight}");
5791 }
5792 };
5793
5794 tester.pump_widget(dropdown_menu(None));
5796 pump(tester);
5797 tap_dropdown_menu::<i32>(tester);
5798 tester.pump_and_settle();
5799
5800 tester.enter_text(find::by_type::<TextField>().first(), "read");
5801 pump(tester);
5802 check_expected_highlight(tester, Some("Unread"), &["All", "Read"]);
5804
5805 tester.pump_widget(dropdown_menu(Some(Rc::new(|_app, _entries, _query| {
5807 Some(0)
5808 }))));
5809 pump(tester);
5810 tester.enter_text(find::by_type::<TextField>().first(), "read");
5811 pump(tester);
5812 check_expected_highlight(tester, Some("All"), &["Unread", "Read"]);
5814
5815 tester.pump_widget(dropdown_menu(Some(Rc::new(
5817 |_app, entries: &[DropdownMenuEntry<i32>], query: &str| {
5818 if query.is_empty() {
5819 return None;
5820 }
5821 entries.iter().position(|entry| entry.label == query)
5822 },
5823 ))));
5824 pump(tester);
5825
5826 tester.enter_text(find::by_type::<TextField>().first(), "read");
5827 pump(tester);
5828 check_expected_highlight(tester, None, &["All", "Unread", "Read"]);
5830 tester.enter_text(find::by_type::<TextField>().first(), "Read");
5831 pump(tester);
5832 check_expected_highlight(tester, Some("Read"), &["All", "Unread"]);
5833 });
5834 }
5835
5836 fn assert_a_nested_selection_calls_on_selected(tester: &mut WidgetTester) {
5839 let theme = theme(tester);
5840 let selection_count = Rc::new(std::cell::Cell::new(0));
5841 let count = Rc::clone(&selection_count);
5842 let dropdown =
5843 DropdownMenu::new(vec![DropdownMenuEntry::new(TestMenu::MainMenu0, "Item 0")])
5844 .on_selected(move |_app, _value| count.set(count.get() + 1));
5845 tester.pump_widget(material_app(
5846 theme,
5847 Scaffold::new()
5848 .body(MenuAnchor::new(vec![dropdown.into_widget()]).builder(
5849 |_app, _context, controller, _child| {
5850 IconButton::new(
5851 Some(Listener::new(move |app| controller.open(app, None))),
5852 Icon::new(Some(Icons::smartphone_rounded())),
5853 )
5854 .into_widget()
5855 },
5856 ))
5857 .into_widget(),
5858 ));
5859
5860 tap_first::<IconButton>(tester);
5862 pump(tester);
5863 tap_dropdown_menu::<TestMenu>(tester);
5865 pump(tester);
5866
5867 tap_item(tester, "Item 0");
5868 tester.pump_and_settle();
5869
5870 assert_eq!(selection_count.get(), 1);
5871 }
5872
5873 #[test]
5875 fn a_selection_in_a_nested_menu_calls_on_selected() {
5876 test_widgets(assert_a_nested_selection_calls_on_selected);
5877 }
5878
5879 #[test]
5882 fn a_selection_that_closes_the_nested_menu_does_not_panic() {
5883 test_widgets(assert_a_nested_selection_calls_on_selected);
5884 }
5885
5886 #[test]
5888 fn a_menu_scrolled_out_of_a_list_does_not_set_state_after_it_unmounts() {
5889 test_widgets(|tester| {
5890 let entries = menu_children();
5891 pump_app(tester, move |app| {
5892 material_app(
5893 m3(app),
5894 Scaffold::new()
5895 .body(
5896 waft_widgets::ListView::builder(move |_app, _context, index| {
5897 Some(if index == 250 {
5898 DropdownMenu::new(Rc::clone(&entries)).into_widget()
5899 } else {
5900 SizedBox::new().height(50.0).into_widget()
5901 })
5902 })
5903 .item_count(500),
5904 )
5905 .into_widget(),
5906 )
5907 });
5908
5909 let list = tester.get_rect(first::<waft_widgets::ListView>(tester));
5910 tester.fling_from(list.center(), Offset::new(0.0, -20000.0), 200000.0, 1);
5911 tester.pump_and_settle();
5912 });
5913 }
5914
5915 #[test]
5917 fn a_menu_taller_than_the_screen_shows_a_scrollbar() {
5918 for platform in ALL_PLATFORMS {
5919 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
5920 let theme = theme(tester);
5921 tester.pump_widget(the_menu(
5922 theme,
5923 DropdownMenu::new(vec![
5924 DropdownMenuEntry::new(TestMenu::MainMenu0, "Item 0").style(
5925 MenuItemButton::style_from()
5926 .minimum_size(Size::from_height(1000.0))
5927 .build(),
5928 ),
5929 ]),
5930 ));
5931
5932 tap_dropdown_menu::<TestMenu>(tester);
5933 tester.pump_and_settle();
5934
5935 expect(
5936 tester,
5937 &find::by_type::<crate::scrollbar::Scrollbar>(),
5938 finds_one_widget(),
5939 );
5940 });
5941 }
5942 }
5943
5944 fn primary_focus_next(tester: &mut WidgetTester) {
5945 let mut app = tester.cell.borrow_mut();
5946 let focus = waft_widgets::primary_focus(&mut app).expect("a primary focus");
5947 focus.next_focus(&mut app);
5948 }
5949
5950 fn paints_rrect_of_color(tester: &WidgetTester, render: AnyRenderBox, color: Color) -> bool {
5953 use waft_embedder::valo::Op;
5954 let expected: waft_embedder::valo::Color = color.into();
5955 let painted: Vec<waft_embedder::valo::Color> = tester
5956 .painted_ops(render.as_object())
5957 .into_iter()
5958 .filter_map(|op| match op {
5959 Op::DrawPath { paint, .. } => Some(paint.color),
5960 _ => None,
5961 })
5962 .collect();
5963 let found = painted.contains(&expected);
5964 if !found {
5965 eprintln!("paths painted in: {painted:?}");
5966 }
5967 found
5968 }
5969
5970 #[test]
5972 fn the_focus_node_can_focus_the_text_input_field() {
5973 test_widgets(|tester| {
5974 let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
5975 let theme = theme(tester);
5976 let entries: Rc<[DropdownMenuEntry<String>]> = Rc::from(vec![
5977 DropdownMenuEntry::new("Yolk".to_owned(), "Yolk"),
5978 DropdownMenuEntry::new("Eggbert".to_owned(), "Eggbert"),
5979 ]);
5980 tester.pump_widget(the_menu(
5981 theme.clone(),
5982 DropdownMenu::new(entries).focus_node(focus_node.erase()),
5983 ));
5984
5985 let decorator =
5986 tester.render_box_of(first::<crate::input_decorator::InputDecorator>(tester));
5987
5988 assert!(paints_rrect_of_color(
5990 tester,
5991 decorator,
5992 theme.color_scheme.outline()
5993 ));
5994
5995 focus_node
5996 .as_node()
5997 .request_focus(&mut tester.cell.borrow_mut(), None);
5998 pump(tester);
5999 tester.pump_by(Duration::from_millis(200));
6001
6002 let decorator =
6003 tester.render_box_of(first::<crate::input_decorator::InputDecorator>(tester));
6004
6005 assert!(paints_rrect_of_color(
6007 tester,
6008 decorator,
6009 theme.color_scheme.primary()
6010 ));
6011 });
6012 }
6013
6014 #[test]
6016 fn focus_traversal_skips_the_invisible_entries() {
6017 test_widgets(|tester| {
6018 let theme = theme(tester);
6019 let (button_focus_node, text_field_focus_node) = {
6020 let mut app = tester.cell.borrow_mut();
6021 (FocusNode::new(&mut app), FocusNode::new(&mut app))
6022 };
6023 tester.pump_widget(material_app(
6024 theme,
6025 Scaffold::new()
6026 .body(waft_widgets::Column::new().children(vec![
6027 DropdownMenu::new(menu_children())
6028 .focus_node(text_field_focus_node.erase())
6029 .into_widget(),
6030 crate::elevated_button::ElevatedButton::new(
6031 Some(Listener::new(|_app| {})),
6032 Some(Text::new("Button")),
6033 )
6034 .focus_node(button_focus_node.erase())
6035 .into_widget(),
6036 ]))
6037 .into_widget(),
6038 ));
6039
6040 primary_focus_next(tester);
6042 pump(tester);
6043 let icon_button = tester.element(find::by_icon(&Icons::arrow_drop_down()).first());
6044 {
6045 let mut app = tester.cell.borrow_mut();
6046 assert!(Focus::of(&mut app, icon_button, false, true).has_focus(&app));
6047 }
6048
6049 primary_focus_next(tester);
6051 pump(tester);
6052 assert!(
6053 text_field_focus_node
6054 .as_node()
6055 .has_focus(&tester.cell.borrow_mut())
6056 );
6057
6058 primary_focus_next(tester);
6060 pump(tester);
6061 assert!(
6062 button_focus_node
6063 .as_node()
6064 .has_focus(&tester.cell.borrow_mut())
6065 );
6066 });
6067 }
6068
6069 #[test]
6071 fn the_input_formatters_format_the_text() {
6072 test_widgets(|tester| {
6073 let theme = theme(tester);
6074 let called = Rc::new(std::cell::Cell::new(0));
6075 let count = Rc::clone(&called);
6076 let formatter = waft_services::TextInputFormatterRef::with_function(Rc::new(
6077 move |_old_value: &TextEditingValue, new_value: &TextEditingValue| {
6078 count.set(count.get() + 1);
6079 new_value.clone()
6080 },
6081 ));
6082 let controller = controller(tester);
6083 tester.pump_widget(the_menu(
6084 theme,
6085 DropdownMenu::new(vec![
6086 DropdownMenuEntry::new("Blue".to_owned(), "Blue"),
6087 DropdownMenuEntry::new("Green".to_owned(), "Green"),
6088 ])
6089 .request_focus_on_tap(true)
6090 .controller(controller.clone())
6091 .input_formatters(vec![
6092 formatter,
6093 waft_services::TextInputFormatterRef(Rc::new(
6094 waft_services::FilteringTextInputFormatter::deny(
6095 waft_services::FilterPattern::Digits,
6096 ),
6097 )),
6098 ]),
6099 ));
6100
6101 let state = editable_state(tester);
6102 for (text, count, expected) in [
6103 ("Blue", 1, "Blue"),
6104 ("Green", 2, "Green"),
6105 ("Green2", 3, "Green"),
6106 ] {
6107 TextInputClient::update_editing_value(
6108 state,
6109 &mut tester.cell.borrow_mut(),
6110 TextEditingValue::new().text(text),
6111 );
6112 assert_eq!(called.get(), count);
6113 assert_eq!(controller_text(tester, controller.handle()), expected);
6114 }
6115 });
6116 }
6117
6118 fn long_label() -> String {
6119 "This is a long text that is multiplied by 4 so it can overflow. ".repeat(4)
6120 }
6121
6122 #[test]
6124 fn a_long_item_opens_without_panicking() {
6125 test_widgets(|tester| {
6126 let theme = theme(tester);
6127 tester.pump_widget(the_menu(
6128 theme,
6129 DropdownMenu::new(vec![DropdownMenuEntry::new(0, long_label())]),
6130 ));
6131 pump(tester);
6132 tap_dropdown_menu::<i32>(tester);
6133 tester.pump_and_settle();
6134 });
6135 }
6136
6137 #[test]
6139 fn the_text_field_keeps_to_its_parent_width() {
6140 test_widgets(|tester| {
6141 let theme = theme(tester);
6142 tester.pump_widget(material_app(
6143 theme,
6144 Scaffold::new()
6145 .body(SizedBox::new().width(300.0).child(DropdownMenu::new(vec![
6146 DropdownMenuEntry::new(0, long_label()),
6147 ])))
6148 .into_widget(),
6149 ));
6150 pump(tester);
6151 assert_eq!(tester.get_size(first::<TextField>(tester)).width(), 300.0);
6152 });
6153 }
6154
6155 #[test]
6157 fn a_field_with_a_large_helper_text_opens_on_a_tap() {
6158 test_widgets(|tester| {
6159 let theme = theme(tester);
6160 let label_text = "MenuEntry 1";
6161 tester.pump_widget(centered_menu_of(
6162 theme,
6163 DropdownMenu::new(vec![DropdownMenuEntry::new(0, label_text)])
6164 .hint_text("Hint text")
6165 .helper_text("Menu Helper text")
6166 .input_decoration_theme(
6167 InputDecorationThemeData::new()
6168 .helper_max_lines(2)
6169 .helper_style(TextStyle::new().font_size(30.0)),
6170 ),
6171 ));
6172 pump(tester);
6173 let hint = tester.get_rect(find::text("Hint text").first()).center();
6174 tester.tap_at(hint, 1);
6175 tester.pump_and_settle();
6176 assert_eq!(
6178 widgets_with_text::<MenuItemButton>(tester, label_text).len(),
6179 2
6180 );
6181 });
6182 }
6183
6184 fn centered_menu_of<T: Clone + PartialEq + 'static>(
6185 theme: ThemeData,
6186 menu: DropdownMenu<T>,
6187 ) -> WidgetRef {
6188 material_app(
6189 theme,
6190 Scaffold::new()
6191 .body(waft_widgets::Center::new().child(menu))
6192 .into_widget(),
6193 )
6194 }
6195
6196 #[test]
6198 fn the_text_align_reaches_the_text_field() {
6199 test_widgets(|tester| {
6200 let theme = theme(tester);
6201 let empty: Vec<DropdownMenuEntry<i32>> = Vec::new();
6202 tester.pump_widget(material_app(
6203 theme,
6204 Scaffold::new()
6205 .body(waft_widgets::Column::new().children(vec![
6206 DropdownMenu::new(empty.clone()).into_widget(),
6207 DropdownMenu::new(empty)
6208 .text_align(TextAlign::Center)
6209 .into_widget(),
6210 ]))
6211 .into_widget(),
6212 ));
6213
6214 let fields = find::by_type::<TextField>().evaluate(tester);
6215 tester.widget(fields[0], |field: &TextField| {
6216 assert_eq!(field.text_align, TextAlign::Start);
6217 });
6218 tester.widget(fields[1], |field: &TextField| {
6219 assert_eq!(field.text_align, TextAlign::Center);
6220 });
6221 });
6222 }
6223
6224 #[test]
6226 fn the_keyboard_type_reaches_the_text_field() {
6227 test_widgets(|tester| {
6228 let theme = theme(tester);
6229 tester.pump_widget(safe_area_menu(
6230 theme,
6231 DropdownMenu::new(menu_children()).keyboard_type(TextInputType::NUMBER),
6232 ));
6233 text_field(tester, |text_field| {
6234 assert_eq!(text_field.effective_keyboard_type(), TextInputType::NUMBER);
6235 });
6236 });
6237 }
6238
6239 #[test]
6241 fn the_keyboard_type_defaults_to_text() {
6242 test_widgets(|tester| {
6243 let theme = theme(tester);
6244 tester.pump_widget(safe_area_menu(theme, DropdownMenu::new(menu_children())));
6245 text_field(tester, |text_field| {
6246 assert_eq!(text_field.effective_keyboard_type(), TextInputType::TEXT);
6247 });
6248 });
6249 }
6250
6251 #[test]
6253 fn the_alignment_offset_reaches_the_menu_anchor() {
6254 test_widgets(|tester| {
6255 let theme = theme(tester);
6256 let alignment_offset = Offset::new(0.0, 16.0);
6257 tester.pump_widget(the_menu(
6258 theme,
6259 DropdownMenu::new(vec![
6260 DropdownMenuEntry::new("1".to_owned(), "One"),
6261 DropdownMenuEntry::new("2".to_owned(), "Two"),
6262 ])
6263 .alignment_offset(alignment_offset),
6264 ));
6265
6266 let anchor = tester.element(find::by_type::<MenuAnchor>());
6267 tester.widget(anchor, |anchor: &MenuAnchor| {
6268 assert_eq!(anchor.alignment_offset, Some(alignment_offset));
6269 });
6270 });
6271 }
6272
6273 fn assert_every_item_is_shown_twice(tester: &WidgetTester) {
6274 for menu in TestMenu::VALUES {
6275 assert_eq!(
6276 widgets_with_text::<MenuItemButton>(tester, menu.label()).len(),
6277 2,
6278 "{menu:?}"
6279 );
6280 }
6281 }
6282
6283 #[test]
6285 fn the_filter_applies_only_after_text_input() {
6286 test_widgets(|tester| {
6287 let theme = theme(tester);
6288 tester.pump_widget(the_menu(
6289 theme,
6290 DropdownMenu::new(menu_children())
6291 .request_focus_on_tap(true)
6292 .enable_filter(true)
6293 .initial_selection(TestMenu::MainMenu0),
6294 ));
6295
6296 tap_dropdown_menu::<TestMenu>(tester);
6297 tester.pump_and_settle();
6298
6299 assert_every_item_is_shown_twice(tester);
6302
6303 tester.enter_text(find::by_type::<TextField>().first(), "Menu 1");
6305 tester.pump_and_settle();
6306 for menu in TestMenu::VALUES {
6307 let expected = if menu == TestMenu::MainMenu1 { 2 } else { 1 };
6309 assert_eq!(
6310 widgets_with_text::<MenuItemButton>(tester, menu.label()).len(),
6311 expected,
6312 "{menu:?}"
6313 );
6314 }
6315
6316 tap_item(tester, "Menu 1");
6318 tester.pump_and_settle();
6319 tap_dropdown_menu::<TestMenu>(tester);
6320 tester.pump_and_settle();
6321 assert_every_item_is_shown_twice(tester);
6322 });
6323 }
6324
6325 #[test]
6327 fn scrolling_to_the_highlight_leaves_the_parent_scroll_view_alone() {
6328 test_widgets(|tester| {
6329 let controller = waft_widgets::ScrollController::new(
6330 &mut tester.cell.borrow_mut(),
6331 0.0,
6332 true,
6333 None,
6334 None,
6335 None,
6336 )
6337 .into_erased::<waft_widgets::AnyScrollController>();
6338 let entries = menu_children();
6339 pump_app(tester, {
6340 let controller = controller.clone();
6341 move |app| {
6342 let last = entries.last().expect("entries").value;
6343 material_app(
6344 m3(app),
6345 Scaffold::new()
6346 .body(
6347 waft_widgets::ListView::new()
6348 .controller(controller.clone())
6349 .children(vec![
6350 waft_widgets::ListView::new()
6351 .shrink_wrap(true)
6352 .children(vec![
6353 DropdownMenu::new(entries)
6354 .initial_selection(last)
6355 .into_widget(),
6356 ])
6357 .into_widget(),
6358 SizedBox::new().height(1000.0).into_widget(),
6359 ]),
6360 )
6361 .into_widget(),
6362 )
6363 }
6364 });
6365
6366 tap_first::<TextField>(tester);
6367 tester.pump_and_settle();
6368 assert_eq!(controller.offset(&tester.cell.borrow()), 0.0);
6369 });
6370 }
6371
6372 #[test]
6374 fn a_menu_with_expanded_insets_follows_its_alignment() {
6375 test_widgets(|tester| {
6376 let entries = menu_children();
6377 for (alignment, expected) in [
6378 (waft_painting::Alignment::TOP_CENTER, Offset::new(16.0, 0.0)),
6379 (waft_painting::Alignment::CENTER, Offset::new(16.0, 272.0)),
6380 (
6381 waft_painting::Alignment::BOTTOM_CENTER,
6382 Offset::new(16.0, 544.0),
6383 ),
6384 ] {
6385 let entries = Rc::clone(&entries);
6386 pump_app(tester, move |app| {
6387 material_app(
6388 m3(app),
6389 Scaffold::new()
6390 .body(waft_widgets::Row::new().children(vec![
6391 waft_widgets::Expanded::new(
6392 Align::new().alignment(alignment.into()).child(
6393 DropdownMenu::new(entries)
6394 .expanded_insets(EdgeInsetsGeometry::all(16.0)),
6395 ),
6396 )
6397 .into_widget(),
6398 ]))
6399 .into_widget(),
6400 )
6401 });
6402 let text_field_position = tester.get_rect(first::<TextField>(tester)).top_left();
6403 assert_eq!(text_field_position, expected);
6404 }
6405 });
6406 }
6407
6408 fn last_menu_anchor_is_open(tester: &WidgetTester) -> bool {
6409 let anchor = *find::by_type::<MenuAnchor>()
6410 .evaluate(tester)
6411 .last()
6412 .expect("a menu anchor");
6413 let controller = tester.widget(anchor, |anchor: &MenuAnchor| {
6414 anchor.controller.clone().expect("a controller")
6415 });
6416 controller.is_open(&tester.cell.borrow())
6417 }
6418
6419 #[test]
6421 fn the_close_behavior_decides_which_menus_a_selection_closes() {
6422 test_widgets(|tester| {
6423 let entries = menu_children();
6424 let build_dropdown_menu = |close_behavior: DropdownMenuCloseBehavior| {
6425 let entries = Rc::clone(&entries);
6426 move |app: &mut App| {
6427 material_app(
6428 m3(app),
6429 Scaffold::new()
6430 .body(
6431 MenuAnchor::new(vec![
6432 DropdownMenu::new(entries)
6433 .close_behavior(close_behavior)
6434 .into_widget(),
6435 ])
6436 .child(Text::new("Open Menu"))
6437 .builder(
6438 |_app, _context, controller, child| {
6439 crate::elevated_button::ElevatedButton::new(
6440 Some(Listener::new(move |app| {
6441 controller.open(app, None)
6442 })),
6443 child.cloned(),
6444 )
6445 .into_widget()
6446 },
6447 ),
6448 )
6449 .into_widget(),
6450 )
6451 }
6452 };
6453 let tap_button = |tester: &mut WidgetTester| {
6454 tap_first::<crate::elevated_button::ElevatedButton>(tester);
6455 tester.pump_and_settle();
6456 };
6457
6458 pump_app(tester, build_dropdown_menu(DropdownMenuCloseBehavior::All));
6460 tap_button(tester);
6462 tap_first::<TextField>(tester);
6464 tester.pump_and_settle();
6465 expect(
6466 tester,
6467 &find::by_type::<DropdownMenu<TestMenu>>(),
6468 finds_one_widget(),
6469 );
6470 assert!(last_menu_anchor_is_open(tester));
6471 tap_item(tester, TestMenu::MainMenu0.label());
6473 tester.pump_and_settle();
6474 expect(
6476 tester,
6477 &find::by_type::<DropdownMenu<TestMenu>>(),
6478 finds_nothing(),
6479 );
6480 expect(tester, &find::by_type::<MenuAnchor>(), finds_one_widget());
6481
6482 for (close_behavior, stays_open) in [
6484 (DropdownMenuCloseBehavior::SelfOnly, false),
6485 (DropdownMenuCloseBehavior::None, true),
6486 ] {
6487 pump_app(tester, build_dropdown_menu(close_behavior));
6488 tap_button(tester);
6490 expect(
6491 tester,
6492 &find::by_type::<DropdownMenu<TestMenu>>(),
6493 finds_one_widget(),
6494 );
6495 tap_first::<TextField>(tester);
6497 tester.pump_and_settle();
6498 let dropdown_menu_anchor = *find::by_type::<MenuAnchor>()
6499 .evaluate(tester)
6500 .last()
6501 .expect("a menu anchor");
6502 let controller = tester.widget(dropdown_menu_anchor, |anchor: &MenuAnchor| {
6503 anchor.controller.clone().expect("a controller")
6504 });
6505 assert!(controller.is_open(&tester.cell.borrow()));
6506 tap_item(tester, TestMenu::MainMenu0.label());
6508 tester.pump_and_settle();
6509 assert_eq!(
6510 controller.is_open(&tester.cell.borrow()),
6511 stays_open,
6512 "{close_behavior:?}"
6513 );
6514 }
6515 });
6516 }
6517
6518 fn assert_the_menu_is_attached_at_the_bottom_of_the_text_field(
6521 tester: &mut WidgetTester,
6522 tight: bool,
6523 expanded_insets: bool,
6524 ) {
6525 let text_field_bottom = 56.0;
6530 pump_app(tester, move |app| {
6531 let mut menu = DropdownMenu::new(menu_children_with_icons())
6532 .initial_selection(TestMenu::MainMenu3);
6533 if expanded_insets {
6534 menu = menu.expanded_insets(EdgeInsetsGeometry::ZERO);
6535 }
6536 let body = if tight {
6537 SizedBox::new()
6538 .width(200.0)
6539 .height(300.0)
6540 .child(menu)
6541 .into_widget()
6542 } else {
6543 menu.into_widget()
6544 };
6545 material_app(m3(app), Scaffold::new().body(body).into_widget())
6546 });
6547
6548 tap_first::<TextField>(tester);
6550 pump(tester);
6551
6552 let panel = tester.element(find::by_type::<MenuPanel>());
6553 let material = tester.descendants_of_type::<Material>(panel)[0];
6554 assert_eq!(tester.get_rect(material).top, text_field_bottom);
6555 }
6556
6557 #[test]
6560 fn the_menu_is_attached_below_the_field_under_loose_constraints_with_expanded_insets() {
6561 test_widgets(|tester| {
6562 assert_the_menu_is_attached_at_the_bottom_of_the_text_field(tester, false, true)
6563 });
6564 }
6565
6566 #[test]
6568 fn the_menu_is_attached_below_the_field_under_tight_constraints_with_expanded_insets() {
6569 test_widgets(|tester| {
6570 assert_the_menu_is_attached_at_the_bottom_of_the_text_field(tester, true, true)
6571 });
6572 }
6573
6574 #[test]
6576 fn the_menu_is_attached_below_the_field_under_loose_constraints() {
6577 test_widgets(|tester| {
6578 assert_the_menu_is_attached_at_the_bottom_of_the_text_field(tester, false, false)
6579 });
6580 }
6581
6582 #[test]
6584 fn the_menu_is_attached_below_the_field_under_tight_constraints() {
6585 test_widgets(|tester| {
6586 assert_the_menu_is_attached_at_the_bottom_of_the_text_field(tester, true, false)
6587 });
6588 }
6589
6590 fn assert_keyboard_navigation_selects(platform: TargetPlatform, with_focus_node: bool) {
6594 let mut tester = WidgetTester::on(platform);
6595 let tester = &mut tester;
6596 let theme = theme(tester);
6597 let selected_menu = Rc::new(std::cell::Cell::new(None));
6598 let selected = Rc::clone(&selected_menu);
6599 let mut menu =
6600 DropdownMenu::new(menu_children()).on_selected(move |_app, menu| selected.set(menu));
6601 if with_focus_node {
6602 menu = menu.focus_node(FocusNode::new(&mut tester.cell.borrow_mut()).erase());
6603 }
6604 tester.pump_widget(material_app(
6605 theme,
6606 Material::new()
6607 .child(waft_widgets::Center::new().child(menu))
6608 .into_widget(),
6609 ));
6610
6611 send_key(tester, LogicalKeyboardKey::TAB);
6614 pump(tester);
6615
6616 let icon_button = tester.element(find::by_icon(&Icons::arrow_drop_down()).first());
6618 {
6619 let mut app = tester.cell.borrow_mut();
6620 assert!(
6621 Focus::of(&mut app, icon_button, false, true).has_primary_focus(&app),
6622 "{platform:?}"
6623 );
6624 }
6625
6626 for key in [
6627 LogicalKeyboardKey::ENTER,
6628 LogicalKeyboardKey::ARROW_DOWN,
6629 LogicalKeyboardKey::ENTER,
6630 ] {
6631 send_key(tester, key);
6632 pump(tester);
6633 }
6634
6635 assert_eq!(
6636 selected_menu.get(),
6637 Some(TestMenu::MainMenu0),
6638 "{platform:?}"
6639 );
6640 }
6641
6642 #[test]
6644 fn the_keyboard_opens_the_menu_and_selects_an_item() {
6645 for platform in ALL_PLATFORMS {
6646 test_widgets(|_| assert_keyboard_navigation_selects(platform, true));
6647 }
6648 }
6649
6650 #[test]
6653 fn the_keyboard_selects_an_item_without_a_focus_node() {
6654 for platform in ALL_PLATFORMS {
6655 test_widgets(|_| assert_keyboard_navigation_selects(platform, false));
6656 }
6657 }
6658
6659 fn material_centered_menu(theme: ThemeData, menu: DropdownMenu<TestMenu>) -> WidgetRef {
6660 material_app(
6661 theme,
6662 Material::new()
6663 .child(waft_widgets::Center::new().child(menu))
6664 .into_widget(),
6665 )
6666 }
6667
6668 fn assert_escape_closes_the_menu(tester: &mut WidgetTester, request_focus_on_tap: bool) {
6671 let theme = theme(tester);
6672 tester.pump_widget(material_centered_menu(
6673 theme,
6674 DropdownMenu::new(menu_children()).request_focus_on_tap(request_focus_on_tap),
6675 ));
6676
6677 tap_first::<TextField>(tester);
6679 pump(tester);
6680 expect(tester, &find::by_type::<MenuPanel>(), finds_one_widget());
6681
6682 send_key(tester, LogicalKeyboardKey::ESCAPE);
6684 pump(tester);
6685 expect(tester, &find::by_type::<MenuPanel>(), finds_nothing());
6686 }
6687
6688 #[test]
6690 fn escape_closes_the_menu_of_a_field_that_cannot_request_focus() {
6691 test_widgets(|tester| assert_escape_closes_the_menu(tester, false));
6692 }
6693
6694 #[test]
6696 fn escape_closes_the_menu_of_a_focusable_field() {
6697 test_widgets(|tester| assert_escape_closes_the_menu(tester, true));
6698 }
6699
6700 #[test]
6702 fn escape_closes_the_menu_after_the_highlight_moves() {
6703 for platform in ALL_PLATFORMS {
6704 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
6705 let theme = theme(tester);
6706 let entries = menu_children();
6707 tester.pump_widget(material_centered_menu(
6708 theme.clone(),
6709 DropdownMenu::new(Rc::clone(&entries)).initial_selection(entries[2].value),
6710 ));
6711
6712 tap_first::<TextField>(tester);
6714 pump(tester);
6715 expect(tester, &find::by_type::<MenuPanel>(), finds_one_widget());
6716
6717 send_key(tester, LogicalKeyboardKey::ARROW_DOWN);
6719 pump(tester);
6720 assert!(
6721 is_item_highlighted(tester, &theme, &entries[3].label),
6722 "{platform:?}"
6723 );
6724
6725 send_key(tester, LogicalKeyboardKey::ESCAPE);
6727 pump(tester);
6728 assert!(
6729 find::by_type::<MenuPanel>().evaluate(tester).is_empty(),
6730 "{platform:?}"
6731 );
6732 });
6733 }
6734 }
6735
6736 #[test]
6738 fn max_lines_reaches_the_text_field() {
6739 test_widgets(|tester| {
6740 let theme = theme(tester);
6741 let entries = menu_children();
6742 for (max_lines, expected) in [
6743 (None, Some(1)),
6744 (Some(None), None),
6745 (Some(Some(2)), Some(2)),
6746 ] {
6747 let mut menu = DropdownMenu::new(Rc::clone(&entries));
6748 if let Some(max_lines) = max_lines {
6749 menu = menu.max_lines(max_lines);
6750 }
6751 tester.pump_widget(the_menu(theme.clone(), menu));
6752 text_field(tester, |text_field| {
6753 assert_eq!(text_field.max_lines, expected)
6754 });
6755 }
6756 });
6757 }
6758
6759 #[test]
6761 fn the_text_input_action_reaches_the_text_field() {
6762 test_widgets(|tester| {
6763 let theme = theme(tester);
6764 let entries = menu_children();
6765 tester.pump_widget(the_menu(
6766 theme.clone(),
6767 DropdownMenu::new(Rc::clone(&entries)),
6768 ));
6769 text_field(tester, |text_field| {
6771 assert_eq!(text_field.text_input_action, None)
6772 });
6773
6774 tester.pump_widget(the_menu(
6775 theme,
6776 DropdownMenu::new(entries).text_input_action(TextInputAction::Next),
6777 ));
6778 text_field(tester, |text_field| {
6779 assert_eq!(text_field.text_input_action, Some(TextInputAction::Next));
6780 });
6781 });
6782 }
6783
6784 #[test]
6786 fn a_tap_focuses_a_field_that_requests_focus_on_tap() {
6787 test_widgets(|tester| {
6788 let theme = theme(tester);
6789 tester.pump_widget(the_menu(
6790 theme,
6791 DropdownMenu::new(menu_children()).request_focus_on_tap(true),
6792 ));
6793 tap_first::<TextField>(tester);
6794 tester.pump_and_settle();
6795 let text_field = first::<TextField>(tester);
6796 let mut app = tester.cell.borrow_mut();
6797 assert!(Focus::of(&mut app, text_field, false, true).has_focus(&app));
6798 });
6799 }
6800
6801 fn maximum_size(width: f64, height: f64) -> MenuStyle {
6802 MenuStyle::new().maximum_size(Rc::new(WidgetStatePropertyAll::new(Some(Size::new(
6803 width, height,
6804 )))))
6805 }
6806
6807 #[test]
6809 fn a_menu_style_maximum_size_narrows_the_items() {
6810 test_widgets(|tester| {
6811 let theme = theme(tester);
6812 let long_label = "This is a long text that it can overflow.";
6813 tester.pump_widget(the_menu(
6814 theme.clone(),
6815 DropdownMenu::new(vec![DropdownMenuEntry::new(0, long_label)])
6816 .menu_style(maximum_size(150.0, 50.0)),
6817 ));
6818 tap_first::<TextField>(tester);
6819 tester.pump_and_settle();
6820 assert_eq!(
6821 tester
6822 .get_size(find_menu_item_button(tester, long_label))
6823 .width(),
6824 150.0
6825 );
6826
6827 let entries = menu_children();
6830 tester.pump_widget(the_menu(
6831 theme.clone(),
6832 DropdownMenu::new(Rc::clone(&entries))
6833 .width(200.0)
6834 .menu_style(maximum_size(150.0, 50.0)),
6835 ));
6836 tap_first::<TextField>(tester);
6837 tester.pump_and_settle();
6838 let first_label = entries[0].label.clone();
6839 assert_eq!(
6840 tester
6841 .get_size(find_menu_item_button(tester, &first_label))
6842 .width(),
6843 150.0
6844 );
6845
6846 tester.pump_widget(the_menu(
6849 theme,
6850 DropdownMenu::new(entries)
6851 .width(200.0)
6852 .menu_style(MenuStyle::new()),
6853 ));
6854 tap_first::<TextField>(tester);
6855 tester.pump_and_settle();
6856 assert_eq!(
6857 tester
6858 .get_size(find_menu_item_button(tester, &first_label))
6859 .width(),
6860 200.0
6861 );
6862 });
6863 }
6864
6865 #[test]
6868 fn without_a_maximum_size_the_items_take_the_width_of_the_menu() {
6869 test_widgets(|tester| {
6870 let theme = theme(tester);
6871 let short_label = "Male";
6872 tester.pump_widget(the_menu(
6873 theme.clone(),
6874 DropdownMenu::new(vec![DropdownMenuEntry::new(0, short_label)])
6875 .width(200.0)
6876 .menu_style(MenuStyle::new()),
6877 ));
6878 tap_first::<TextField>(tester);
6879 tester.pump_and_settle();
6880 assert_eq!(
6881 tester
6882 .get_size(find_menu_item_button(tester, short_label))
6883 .width(),
6884 200.0
6885 );
6886
6887 tester.pump_widget(material_app(
6889 theme,
6890 Scaffold::new()
6891 .body(
6892 SizedBox::new().width(f64::INFINITY).child(
6893 DropdownMenu::new(vec![DropdownMenuEntry::new(0, short_label)])
6894 .expanded_insets(EdgeInsetsGeometry::symmetric(0.0, 20.0))
6895 .menu_style(MenuStyle::new()),
6896 ),
6897 )
6898 .into_widget(),
6899 ));
6900 tap_first::<TextField>(tester);
6901 tester.pump_and_settle();
6902 assert_eq!(
6904 tester
6905 .get_size(find_menu_item_button(tester, short_label))
6906 .width(),
6907 760.0
6908 );
6909 });
6910 }
6911
6912 #[test]
6914 fn the_restoration_id_reaches_the_text_field() {
6915 test_widgets(|tester| {
6916 let theme = theme(tester);
6917 let restoration_id = "dropdown_menu";
6918 tester.pump_widget(the_menu(
6919 theme,
6920 DropdownMenu::new(menu_children())
6921 .request_focus_on_tap(true)
6922 .restoration_id(restoration_id),
6923 ));
6924 expect(tester, &find::by_type::<TextField>(), finds_one_widget());
6925 text_field(tester, |text_field| {
6926 assert_eq!(text_field.restoration_id.as_deref(), Some(restoration_id));
6927 });
6928 });
6929 }
6930
6931 #[test]
6933 fn show_trailing_icon_false_hides_the_default_trailing_icon() {
6934 test_widgets(|tester| {
6935 let theme = theme(tester);
6936 tester.pump_widget(the_menu(
6937 theme,
6938 DropdownMenu::new(menu_children()).show_trailing_icon(false),
6939 ));
6940 pump(tester);
6941 assert!(widgets_with_icon::<IconButton>(tester, &Icons::arrow_drop_down()).is_empty());
6942 });
6943 }
6944
6945 #[test]
6947 fn show_trailing_icon_false_hides_a_given_trailing_icon() {
6948 test_widgets(|tester| {
6949 let theme = theme(tester);
6950 tester.pump_widget(the_menu(
6951 theme,
6952 DropdownMenu::new(menu_children())
6953 .trailing_icon(Icon::new(Some(Icons::ac_unit())))
6954 .show_trailing_icon(false),
6955 ));
6956 pump(tester);
6957 assert!(widgets_with_icon::<IconButton>(tester, &Icons::ac_unit()).is_empty());
6958 });
6959 }
6960
6961 #[test]
6963 fn given_controllers_are_not_disposed_when_replaced() {
6964 test_widgets(|tester| {
6965 let theme = theme(tester);
6966 let controller1 = controller(tester);
6967 let controller2 = controller(tester);
6968 let entries = menu_children();
6969 tester.pump_widget(the_menu(
6970 theme.clone(),
6971 DropdownMenu::new(Rc::clone(&entries)).controller(controller1.clone()),
6972 ));
6973 tester.pump_widget(the_menu(
6974 theme,
6975 DropdownMenu::new(entries).controller(controller2.clone()),
6976 ));
6977 let mut app = tester.cell.borrow_mut();
6978 controller1.dispose(&mut app);
6979 controller2.dispose(&mut app);
6980 });
6981 }
6982
6983 #[test]
6985 #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
6986 fn a_disabled_menu_shows_its_text_in_the_disabled_color() {
6987 test_widgets(|tester| {
6988 let theme = theme(tester);
6989 let disabled_color = theme.color_scheme.on_surface().with_opacity(0.38);
6990 let entries: Rc<[DropdownMenuEntry<String>]> =
6991 Rc::from(vec![DropdownMenuEntry::new("One".to_owned(), "One")]);
6992 let build_dropdown_menu = |is_enabled: bool| {
6993 the_menu(
6994 theme.clone(),
6995 DropdownMenu::new(Rc::clone(&entries))
6996 .width(f64::INFINITY)
6997 .enabled(is_enabled)
6998 .initial_selection("One".to_owned())
6999 .label(Text::new("Choose number")),
7000 )
7001 };
7002
7003 tester.pump_widget(build_dropdown_menu(true));
7004 text_field(tester, |text_field| {
7005 assert_eq!(text_field.enabled, Some(true))
7006 });
7007 editable(tester, |editable| {
7008 assert_ne!(editable.style.color, Some(disabled_color.into()));
7009 });
7010
7011 tester.pump_widget(build_dropdown_menu(false));
7013 text_field(tester, |text_field| {
7014 assert_eq!(text_field.enabled, Some(false))
7015 });
7016 editable(tester, |editable| {
7018 assert_eq!(editable.style.color, Some(disabled_color.into()));
7019 });
7020 });
7021 }
7022
7023 fn assert_traversal_reaches_the_trailing_icon_first(
7026 tester: &mut WidgetTester,
7027 given_trailing_icon_focus_node: bool,
7028 ) {
7029 let theme = theme(tester);
7030 let (text_field_focus_node, trailing_icon_focus_node, button_focus_node) = {
7031 let mut app = tester.cell.borrow_mut();
7032 (
7033 FocusNode::new(&mut app),
7034 FocusNode::new(&mut app),
7035 FocusNode::new(&mut app),
7036 )
7037 };
7038 let mut menu = DropdownMenu::new(menu_children()).focus_node(text_field_focus_node.erase());
7039 if given_trailing_icon_focus_node {
7040 menu = menu.trailing_icon_focus_node(trailing_icon_focus_node.erase());
7041 }
7042 tester.pump_widget(material_app(
7043 theme,
7044 Scaffold::new()
7045 .body(waft_widgets::Column::new().children(vec![
7046 menu.into_widget(),
7047 crate::elevated_button::ElevatedButton::new(
7048 Some(Listener::new(|_app| {})),
7049 Some(Text::new("Button")),
7050 )
7051 .focus_node(button_focus_node.erase())
7052 .into_widget(),
7053 ]))
7054 .into_widget(),
7055 ));
7056
7057 primary_focus_next(tester);
7058 pump(tester);
7059 if given_trailing_icon_focus_node {
7060 assert!(
7062 trailing_icon_focus_node
7063 .as_node()
7064 .has_focus(&tester.cell.borrow_mut())
7065 );
7066 } else {
7067 let icon_button = tester.element(find::by_icon(&Icons::arrow_drop_down()).first());
7070 let mut app = tester.cell.borrow_mut();
7071 assert!(Focus::of(&mut app, icon_button, false, true).has_focus(&app));
7072 }
7073
7074 primary_focus_next(tester);
7076 pump(tester);
7077 assert!(
7078 text_field_focus_node
7079 .as_node()
7080 .has_focus(&tester.cell.borrow_mut())
7081 );
7082
7083 primary_focus_next(tester);
7085 pump(tester);
7086 assert!(
7087 button_focus_node
7088 .as_node()
7089 .has_focus(&tester.cell.borrow_mut())
7090 );
7091 }
7092
7093 #[test]
7095 fn the_trailing_icon_gets_a_focus_node_of_its_own() {
7096 test_widgets(|tester| assert_traversal_reaches_the_trailing_icon_first(tester, false));
7097 }
7098
7099 #[test]
7101 fn the_trailing_icon_uses_a_given_focus_node() {
7102 test_widgets(|tester| assert_traversal_reaches_the_trailing_icon_first(tester, true));
7103 }
7104
7105 #[test]
7108 #[should_panic(expected = "self.trailing_icon_focus_node.is_none() || self.show_trailing_icon")]
7109 fn a_trailing_icon_focus_node_without_a_trailing_icon_panics() {
7110 test_widgets(|tester| {
7111 let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
7112 let _ = DropdownMenu::new(menu_children())
7113 .show_trailing_icon(false)
7114 .trailing_icon_focus_node(focus_node.erase())
7115 .into_widget();
7116 });
7117 }
7118
7119 #[test]
7121 fn the_cursor_height_reaches_the_editable_text() {
7122 test_widgets(|tester| {
7123 let theme = theme(tester);
7124 tester.pump_widget(the_menu(
7125 theme,
7126 DropdownMenu::new(menu_children()).cursor_height(4.0),
7127 ));
7128 editable(tester, |editable| {
7129 assert_eq!(editable.cursor_height, Some(4.0))
7130 });
7131 });
7132 }
7133
7134 #[test]
7136 fn the_scroll_padding_reaches_the_editable_text() {
7137 test_widgets(|tester| {
7138 let theme = theme(tester);
7139 tester.pump_widget(the_menu(
7140 theme,
7141 DropdownMenu::new(menu_children()).scroll_padding(EdgeInsets::all(30.0)),
7142 ));
7143 editable(tester, |editable| {
7144 assert_eq!(editable.scroll_padding, EdgeInsets::all(30.0));
7145 });
7146 });
7147 }
7148
7149 #[test]
7151 fn the_scroll_padding_defaults_to_twenty() {
7152 test_widgets(|tester| {
7153 let theme = theme(tester);
7154 tester.pump_widget(the_menu(theme, DropdownMenu::new(menu_children())));
7155 editable(tester, |editable| {
7156 assert_eq!(editable.scroll_padding, EdgeInsets::all(20.0));
7157 });
7158 });
7159 }
7160
7161 #[test]
7163 fn a_given_menu_controller_opens_and_closes_the_menu() {
7164 test_widgets(|tester| {
7165 let theme = theme(tester);
7166 let menu_controller = MenuController::new(&mut tester.cell.borrow_mut())
7167 .into_erased::<waft_widgets::AnyMenuController>();
7168 tester.pump_widget(the_menu(
7169 theme,
7170 DropdownMenu::new(menu_children()).menu_controller(menu_controller.clone()),
7171 ));
7172 let item_0_is_hit_testable = |tester: &WidgetTester| {
7173 let button = find_menu_item_button(tester, "Item 0");
7174 hit_testable(tester, button)
7175 };
7176 assert!(!item_0_is_hit_testable(tester));
7177 menu_controller.open(&mut tester.cell.borrow_mut(), None);
7178 tester.pump_and_settle();
7179 assert!(item_0_is_hit_testable(tester));
7180 menu_controller.close(&mut tester.cell.borrow_mut());
7181 tester.pump_and_settle();
7182 assert!(!item_0_is_hit_testable(tester));
7183 });
7184 }
7185
7186 const LABEL_TEXT: &str = "labelText";
7189
7190 fn build_decoration_with_suffix_icon(
7191 app: &mut App,
7192 _context: BuildContext,
7193 controller: AnyMenuController,
7194 ) -> InputDecoration {
7195 InputDecoration::new()
7196 .label_text(LABEL_TEXT)
7197 .suffix_icon(Icon::new(Some(if controller.is_open(app) {
7198 Icons::arrow_drop_up()
7199 } else {
7200 Icons::arrow_drop_down()
7201 })))
7202 }
7203
7204 fn build_decoration(
7205 _app: &mut App,
7206 _context: BuildContext,
7207 _controller: AnyMenuController,
7208 ) -> InputDecoration {
7209 InputDecoration::new().label_text(LABEL_TEXT)
7210 }
7211
7212 fn icon_count(tester: &WidgetTester, icon: &waft_widgets::IconData) -> usize {
7214 find::by_type::<Icon>()
7215 .evaluate(tester)
7216 .into_iter()
7217 .filter(|element| {
7218 tester.widget(*element, |widget: &Icon| widget.icon.as_ref() == Some(icon))
7219 })
7220 .count()
7221 }
7222
7223 fn new_menu_controller(tester: &WidgetTester) -> MenuControllerRef {
7224 MenuController::new(&mut tester.cell.borrow_mut()).into_erased()
7225 }
7226
7227 #[test]
7230 fn the_decoration_builder_decorates_the_field() {
7231 test_widgets(|tester| {
7232 let theme = theme(tester);
7233 let menu_controller = new_menu_controller(tester);
7234 tester.pump_widget(the_menu(
7235 theme,
7236 DropdownMenu::new(menu_children())
7237 .menu_controller(menu_controller)
7238 .decoration_builder(|_app, _context, _controller| {
7239 InputDecoration::new()
7240 .label_text(LABEL_TEXT)
7241 .helper_text("helperText")
7242 .hint_text("hintText")
7243 .filled(true)
7244 }),
7245 ));
7246
7247 text_field(tester, |text_field| {
7248 let decoration = text_field.decoration.as_ref().expect("a decoration");
7249 assert_eq!(decoration.label_text.as_deref(), Some(LABEL_TEXT));
7250 assert_eq!(decoration.helper_text.as_deref(), Some("helperText"));
7251 assert_eq!(decoration.hint_text.as_deref(), Some("hintText"));
7252 assert_eq!(decoration.filled, Some(true));
7253 });
7254 });
7255 }
7256
7257 #[test]
7259 fn a_decoration_builder_can_replace_the_trailing_icon_button() {
7260 test_widgets(|tester| {
7261 let theme = theme(tester);
7262 let menu_controller = new_menu_controller(tester);
7263 tester.pump_widget(the_menu(
7264 theme,
7265 DropdownMenu::new(menu_children())
7266 .menu_controller(menu_controller)
7267 .decoration_builder(build_decoration_with_suffix_icon),
7268 ));
7269
7270 assert_eq!(icon_count(tester, &Icons::arrow_drop_down()), 2);
7271 expect(tester, &find::by_type::<IconButton>(), finds_nothing());
7272 });
7273 }
7274
7275 #[test]
7277 fn the_decoration_builder_runs_when_the_menu_opens() {
7278 test_widgets(|tester| {
7279 let theme = theme(tester);
7280 let menu_controller = new_menu_controller(tester);
7281 tester.pump_widget(the_menu(
7282 theme,
7283 DropdownMenu::new(menu_children())
7284 .menu_controller(menu_controller)
7285 .decoration_builder(build_decoration_with_suffix_icon),
7286 ));
7287
7288 assert_eq!(icon_count(tester, &Icons::arrow_drop_down()), 2);
7289 assert_eq!(icon_count(tester, &Icons::arrow_drop_up()), 0);
7290
7291 tap_dropdown_menu::<TestMenu>(tester);
7293 pump(tester);
7294
7295 assert_eq!(icon_count(tester, &Icons::arrow_drop_down()), 0);
7297 assert_eq!(icon_count(tester, &Icons::arrow_drop_up()), 2);
7298 });
7299 }
7300
7301 #[test]
7304 fn a_decoration_without_a_suffix_icon_gets_the_default_icon_button() {
7305 test_widgets(|tester| {
7306 let theme = theme(tester);
7307 let menu_controller = new_menu_controller(tester);
7308 tester.pump_widget(the_menu(
7309 theme,
7310 DropdownMenu::new(menu_children())
7311 .menu_controller(menu_controller)
7312 .decoration_builder(build_decoration),
7313 ));
7314 expect(tester, &find::by_type::<IconButton>(), finds_n_widgets(2));
7315 });
7316 }
7317
7318 #[test]
7320 #[should_panic(expected = "self.decoration_builder.is_none()")]
7321 fn a_label_with_a_decoration_builder_panics() {
7322 let _ = DropdownMenu::new(menu_children())
7323 .label(Text::new("Label"))
7324 .decoration_builder(build_decoration)
7325 .into_widget();
7326 }
7327
7328 #[test]
7330 #[should_panic(expected = "self.decoration_builder.is_none()")]
7331 fn a_hint_text_with_a_decoration_builder_panics() {
7332 let _ = DropdownMenu::new(menu_children())
7333 .hint_text("hintText")
7334 .decoration_builder(build_decoration)
7335 .into_widget();
7336 }
7337
7338 #[test]
7341 #[should_panic(expected = "self.decoration_builder.is_none()")]
7342 fn a_helper_text_with_a_decoration_builder_panics() {
7343 let _ = DropdownMenu::new(menu_children())
7344 .hint_text("hintText")
7345 .decoration_builder(build_decoration)
7346 .into_widget();
7347 }
7348
7349 #[test]
7351 #[should_panic(expected = "self.decoration_builder.is_none()")]
7352 fn an_error_text_with_a_decoration_builder_panics() {
7353 let _ = DropdownMenu::new(menu_children())
7354 .error_text("errorText")
7355 .decoration_builder(build_decoration)
7356 .into_widget();
7357 }
7358
7359 #[test]
7361 fn the_preferred_width_counts_a_decoration_label_text() {
7362 test_widgets(|tester| {
7363 let theme = theme(tester);
7364 tester.pump_widget(the_menu(
7365 theme,
7366 DropdownMenu::new(menu_children()).decoration_builder(
7367 |_app, _context, _controller| {
7368 InputDecoration::new().label_text("Long label text")
7369 },
7370 ),
7371 ));
7372 assert_eq!(tester.get_size(first::<TextField>(tester)).width(), 327.5);
7373 });
7374 }
7375
7376 #[test]
7378 fn the_preferred_width_counts_a_decoration_label() {
7379 test_widgets(|tester| {
7380 let theme = theme(tester);
7381 tester.pump_widget(the_menu(
7382 theme,
7383 DropdownMenu::new(menu_children()).decoration_builder(
7384 |_app, _context, _controller| {
7385 InputDecoration::new().label(SizedBox::new().width(200.0))
7386 },
7387 ),
7388 ));
7389 assert_eq!(tester.get_size(first::<TextField>(tester)).width(), 280.0);
7390 });
7391 }
7392
7393 #[test]
7397 fn select_only_defaults_to_false() {
7398 for platform in ALL_PLATFORMS {
7399 test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
7400 let theme = theme(tester);
7401 tester.pump_widget(the_menu(theme, DropdownMenu::new(menu_children())));
7402 let menu = dropdown_menu::<TestMenu>(tester);
7403 tester.widget(menu, |menu: &DropdownMenu<TestMenu>| {
7404 assert!(!menu.select_only, "{platform:?}");
7405 });
7406 });
7407 }
7408 }
7409
7410 fn select_only_menu(tester: &mut WidgetTester, request_focus_on_tap: bool) {
7411 let theme = theme(tester);
7412 tester.pump_widget(the_menu(
7413 theme,
7414 DropdownMenu::new(menu_children())
7415 .select_only(true)
7416 .request_focus_on_tap(request_focus_on_tap),
7417 ));
7418 }
7419
7420 #[test]
7423 fn select_only_makes_the_field_read_only() {
7424 for request_focus_on_tap in [false, true] {
7425 test_widgets(|tester| {
7426 select_only_menu(tester, request_focus_on_tap);
7427 text_field(tester, |text_field| assert!(text_field.read_only));
7428 });
7429 }
7430 }
7431
7432 #[test]
7435 fn select_only_disables_interactive_selection() {
7436 for request_focus_on_tap in [false, true] {
7437 test_widgets(|tester| {
7438 select_only_menu(tester, request_focus_on_tap);
7439 text_field(tester, |text_field| {
7440 assert_eq!(text_field.enable_interactive_selection, Some(false));
7441 });
7442 });
7443 }
7444 }
7445
7446 fn editable_has_focus(tester: &WidgetTester) -> bool {
7447 let focus_node = editable(tester, |editable| editable.focus_node.clone());
7448 focus_node.has_focus(&tester.cell.borrow_mut())
7449 }
7450
7451 #[test]
7453 fn select_only_without_request_focus_on_tap_keeps_the_field_unfocused() {
7454 test_widgets(|tester| {
7455 select_only_menu(tester, false);
7456 assert!(!editable_has_focus(tester));
7457 tap_first::<TextField>(tester);
7459 pump(tester);
7460 assert!(!editable_has_focus(tester));
7461 });
7462 }
7463
7464 #[test]
7466 fn select_only_with_request_focus_on_tap_focuses_the_field() {
7467 test_widgets(|tester| {
7468 select_only_menu(tester, true);
7469 assert!(!editable_has_focus(tester));
7470 tap_first::<TextField>(tester);
7472 pump(tester);
7473 assert!(editable_has_focus(tester));
7474 });
7475 }
7476
7477 #[test]
7479 fn select_only_opens_the_menu_on_enter() {
7480 test_widgets(|tester| {
7481 let theme = theme(tester);
7482 let menu_controller = new_menu_controller(tester);
7483 let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
7484 tester.pump_widget(the_menu(
7485 theme,
7486 DropdownMenu::new(menu_children())
7487 .menu_controller(menu_controller.clone())
7488 .focus_node(focus_node.erase())
7489 .select_only(true),
7490 ));
7491
7492 assert!(!editable_has_focus(tester));
7494 focus_node
7495 .as_node()
7496 .request_focus(&mut tester.cell.borrow_mut(), None);
7497 pump(tester);
7498 assert!(editable_has_focus(tester));
7499
7500 assert!(!menu_controller.is_open(&tester.cell.borrow()));
7502 send_key(tester, LogicalKeyboardKey::ENTER);
7503 pump(tester);
7504 assert!(menu_controller.is_open(&tester.cell.borrow()));
7505 });
7506 }
7507
7508 #[test]
7510 fn select_only_shows_the_click_cursor() {
7511 test_widgets(|tester| {
7512 let theme = theme(tester);
7513 tester.pump_widget(column_menu(
7514 theme,
7515 DropdownMenu::new(menu_children()).select_only(true),
7516 ));
7517 tester.pump_and_settle();
7518 mouse_over_the_text_field(tester);
7519 assert!(cursor_is(tester, SystemMouseCursors::CLICK));
7520 });
7521 }
7522
7523 #[test]
7525 fn a_selection_from_the_filtered_list_survives_new_entries() {
7526 test_widgets(|tester| {
7527 let controller = controller(tester);
7528 let entries = menu_children();
7529 pump_app(tester, {
7530 let controller = controller.clone();
7531 move |app| {
7532 material_app(
7533 m3(app),
7534 Scaffold::new()
7535 .body(waft_widgets::StatefulBuilder::new(
7536 move |_app, _context, set_state| {
7537 let new_entries: Vec<DropdownMenuEntry<TestMenu>> =
7540 entries.to_vec();
7541 DropdownMenu::new(new_entries)
7542 .controller(controller.clone())
7543 .request_focus_on_tap(true)
7544 .enable_filter(true)
7545 .on_selected(move |app, _value| {
7546 set_state(app, &mut |_app| {});
7547 })
7548 .into_widget()
7549 },
7550 ))
7551 .into_widget(),
7552 )
7553 }
7554 });
7555
7556 tap_dropdown_menu::<TestMenu>(tester);
7558 pump(tester);
7559
7560 tester.enter_text(
7562 find::by_type::<TextField>().first(),
7563 TestMenu::MainMenu1.label(),
7564 );
7565 pump(tester);
7566
7567 tap_item(tester, TestMenu::MainMenu1.label());
7569 tester.pump_and_settle();
7570
7571 assert_eq!(
7572 controller_text(tester, controller.handle()),
7573 TestMenu::MainMenu1.label()
7574 );
7575 });
7576 }
7577
7578 #[test]
7580 fn a_menu_at_zero_area_does_not_panic() {
7581 test_widgets(|tester| {
7582 tester.view().set_physical_size(Size::ZERO);
7583 let controller = {
7584 let mut app = tester.cell.borrow_mut();
7585 TextEditingController::new(&mut app)
7586 .text(&mut app, "I")
7587 .into_erased::<waft_widgets::AnyTextEditingController>()
7588 };
7589 let theme = theme(tester);
7590 tester.pump_widget(centered_menu(
7591 theme,
7592 DropdownMenu::new(menu_children()).controller(controller.clone()),
7593 ));
7594 assert_eq!(
7595 tester.get_size(dropdown_menu::<TestMenu>(tester)),
7596 Size::ZERO
7597 );
7598 controller.set_selection(&mut tester.cell.borrow_mut(), collapsed(0));
7599 pump(tester);
7600 assert!(
7601 !find::by_type::<MenuItemButton>()
7602 .evaluate(tester)
7603 .is_empty()
7604 );
7605 });
7606 }
7607
7608 #[test]
7610 fn each_text_input_action_moves_the_focus_as_the_field_does() {
7611 let action_should_lose_focus = [
7613 (TextInputAction::None, false),
7614 (TextInputAction::Unspecified, false),
7615 (TextInputAction::Done, true),
7616 (TextInputAction::Go, true),
7617 (TextInputAction::Search, true),
7618 (TextInputAction::Send, true),
7619 (TextInputAction::ContinueAction, false),
7620 (TextInputAction::Join, false),
7621 (TextInputAction::Route, false),
7622 (TextInputAction::EmergencyCall, false),
7623 (TextInputAction::Newline, true),
7624 (TextInputAction::Next, true),
7625 (TextInputAction::Previous, true),
7626 ];
7627 for (text_input_action, should_lose_focus) in action_should_lose_focus {
7628 test_widgets(|tester| {
7629 let should_focus_next = text_input_action == TextInputAction::Next;
7630 let should_focus_previous = text_input_action == TextInputAction::Previous;
7631 let theme = theme(tester);
7632 let (previous_focus_node, text_field_focus_node, next_focus_node) = {
7633 let mut app = tester.cell.borrow_mut();
7634 (
7635 FocusNode::new(&mut app),
7636 FocusNode::new(&mut app),
7637 FocusNode::new(&mut app),
7638 )
7639 };
7640 let text_button = |focus_node: Ref<FocusNode>, label: &str| {
7641 crate::text_button::TextButton::new(
7642 Some(Listener::new(|_app| {})),
7643 Some(Text::new(label)),
7644 )
7645 .focus_node(focus_node.erase())
7646 .into_widget()
7647 };
7648 tester.pump_widget(material_app(
7649 theme,
7650 Scaffold::new()
7651 .body(waft_widgets::Column::new().children(vec![
7652 text_button(previous_focus_node.clone(), "Previous"),
7653 DropdownMenu::new(menu_children())
7654 .focus_node(text_field_focus_node.erase())
7655 .text_input_action(text_input_action)
7656 .request_focus_on_tap(true)
7657 .show_trailing_icon(false)
7658 .into_widget(),
7659 text_button(next_focus_node.clone(), "Next"),
7660 ]))
7661 .into_widget(),
7662 ));
7663
7664 let has_focus = |tester: &WidgetTester, node: Handle<FocusNode>| {
7665 FocusNodeLeaf::as_node(node).has_focus(&tester.cell.borrow_mut())
7666 };
7667 assert!(!has_focus(tester, text_field_focus_node.handle()));
7668
7669 tap_dropdown_menu::<TestMenu>(tester);
7671 tester.pump_and_settle();
7672 assert!(has_focus(tester, text_field_focus_node.handle()));
7673
7674 tester.test_text_input().receive_action(text_input_action);
7675 tester.pump_and_settle();
7676
7677 assert_eq!(
7678 has_focus(tester, previous_focus_node.handle()),
7679 should_focus_previous,
7680 "{text_input_action:?}"
7681 );
7682 assert_eq!(
7683 has_focus(tester, text_field_focus_node.handle()),
7684 !should_lose_focus,
7685 "{text_input_action:?}"
7686 );
7687 assert_eq!(
7688 has_focus(tester, next_focus_node.handle()),
7689 should_focus_next,
7690 "{text_input_action:?}"
7691 );
7692 });
7693 }
7694 }
7695
7696 #[test]
7698 fn an_entry_with_a_null_value_can_be_selected() {
7699 test_widgets(|tester| {
7700 let controller = controller(tester);
7701 let select_none_label = "Select none";
7702 let nullable_menu_items: Rc<[DropdownMenuEntry<Option<String>>]> = Rc::from(vec![
7703 DropdownMenuEntry::new(None, select_none_label),
7704 DropdownMenuEntry::new(Some("a".to_owned()), "A"),
7705 DropdownMenuEntry::new(Some("b".to_owned()), "B"),
7706 ]);
7707 pump_app(tester, {
7708 let controller = controller.clone();
7709 move |app| {
7710 material_app(
7711 m3(app),
7712 Scaffold::new()
7713 .body(waft_widgets::StatefulBuilder::new(
7714 move |_app, _context, set_state| {
7715 DropdownMenu::new(Rc::clone(&nullable_menu_items))
7716 .controller(controller.clone())
7717 .request_focus_on_tap(true)
7718 .enable_filter(true)
7719 .on_selected(move |app, _value| {
7720 set_state(app, &mut |_app| {});
7721 })
7722 .into_widget()
7723 },
7724 ))
7725 .into_widget(),
7726 )
7727 }
7728 });
7729
7730 tap_dropdown_menu::<Option<String>>(tester);
7732 pump(tester);
7733
7734 tap_item(tester, select_none_label);
7736 tester.pump_and_settle();
7737
7738 assert_eq!(
7739 controller_text(tester, controller.handle()),
7740 select_none_label
7741 );
7742 });
7743 }
7744
7745 fn menu_with_toggle(
7748 menu: impl Fn(DropdownMenu<i32>) -> DropdownMenu<i32> + 'static,
7749 on_pressed: impl Fn(&mut App) + 'static,
7750 ) -> impl FnOnce(&mut App) -> WidgetRef {
7751 let menu = Rc::new(menu);
7752 let on_pressed: Rc<dyn Fn(&mut App)> = Rc::new(on_pressed);
7753 move |app| {
7754 material_app(
7755 m3(app),
7756 Scaffold::new()
7757 .body(waft_widgets::StatefulBuilder::new(
7758 move |_app, _context, set_state| {
7759 let on_pressed = Rc::clone(&on_pressed);
7760 waft_widgets::Column::new()
7761 .children(vec![
7762 menu(DropdownMenu::new(vec![DropdownMenuEntry::new(1, "One")]))
7763 .into_widget(),
7764 crate::elevated_button::ElevatedButton::new(
7765 Some(Listener::new(move |app| {
7766 let on_pressed = Rc::clone(&on_pressed);
7767 set_state(app, &mut |app| on_pressed(app));
7768 })),
7769 Some(Text::new("Toggle")),
7770 )
7771 .into_widget(),
7772 ])
7773 .into_widget()
7774 },
7775 ))
7776 .into_widget(),
7777 )
7778 }
7779 }
7780
7781 fn press_the_toggle(tester: &mut WidgetTester) {
7782 tap_first::<crate::elevated_button::ElevatedButton>(tester);
7783 pump(tester);
7784 }
7785
7786 #[test]
7788 fn the_field_stays_editable_after_it_is_disabled_and_enabled() {
7789 test_widgets(|tester| {
7790 let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
7791 let is_enabled = Rc::new(std::cell::Cell::new(true));
7792 let enabled = Rc::clone(&is_enabled);
7793 let toggled = Rc::clone(&is_enabled);
7794 pump_app(
7795 tester,
7796 menu_with_toggle(
7797 move |menu| menu.enabled(enabled.get()).focus_node(focus_node.erase()),
7798 move |_app| toggled.set(!toggled.get()),
7799 ),
7800 );
7801
7802 text_field(tester, |text_field| {
7804 assert_eq!(text_field.enabled, Some(true));
7805 assert!(!text_field.read_only);
7806 });
7807
7808 press_the_toggle(tester);
7810 text_field(tester, |text_field| {
7811 assert_eq!(text_field.enabled, Some(false))
7812 });
7813
7814 press_the_toggle(tester);
7816 text_field(tester, |text_field| {
7817 assert_eq!(text_field.enabled, Some(true));
7818 assert!(!text_field.read_only);
7819 });
7820 });
7821 }
7822
7823 #[test]
7825 fn a_new_focus_node_that_cannot_request_focus_makes_the_field_read_only() {
7826 test_widgets(|tester| {
7827 let (focus_node1, focus_node2) = {
7828 let mut app = tester.cell.borrow_mut();
7829 let focus_node2 = FocusNode::new(&mut app);
7830 focus_node2.as_node().set_can_request_focus(&mut app, false);
7831 (FocusNode::new(&mut app), focus_node2)
7832 };
7833 let current_focus_node = Rc::new(std::cell::RefCell::new(
7834 focus_node1.erase::<waft_widgets::AnyFocusNode>(),
7835 ));
7836 let current = Rc::clone(¤t_focus_node);
7837 pump_app(
7838 tester,
7839 menu_with_toggle(
7840 move |menu| menu.focus_node(current.borrow().clone()),
7841 move |_app| *current_focus_node.borrow_mut() = focus_node2.erase(),
7842 ),
7843 );
7844
7845 text_field(tester, |text_field| assert!(!text_field.read_only));
7847
7848 press_the_toggle(tester);
7850
7851 text_field(tester, |text_field| assert!(text_field.read_only));
7853 });
7854 }
7855
7856 #[test]
7858 fn a_focus_node_that_stops_requesting_focus_makes_the_field_read_only() {
7859 test_widgets(|tester| {
7860 let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
7861 pump_app(
7862 tester,
7863 menu_with_toggle(
7864 {
7865 let focus_node = focus_node.clone();
7866 move |menu| menu.focus_node(focus_node.erase())
7867 },
7868 move |app| focus_node.as_node().set_can_request_focus(app, false),
7869 ),
7870 );
7871
7872 text_field(tester, |text_field| assert!(!text_field.read_only));
7874
7875 press_the_toggle(tester);
7877
7878 text_field(tester, |text_field| assert!(text_field.read_only));
7880 });
7881 }
7882
7883 #[test]
7885 fn a_focus_node_can_request_focus_survives_a_rebuild_of_the_menu() {
7886 test_widgets(|tester| {
7887 let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
7888 pump_app(tester, {
7889 let focus_node = focus_node.clone();
7890 move |app| {
7891 material_app(
7892 ThemeData::builder()
7893 .platform(TargetPlatform::MacOS)
7894 .build(app),
7895 Scaffold::new()
7896 .body(
7897 DropdownMenu::new(vec![DropdownMenuEntry::new(1, "One")])
7898 .focus_node(focus_node.erase()),
7899 )
7900 .into_widget(),
7901 )
7902 }
7903 });
7904
7905 focus_node
7907 .as_node()
7908 .set_can_request_focus(&mut tester.cell.borrow_mut(), false);
7909 tap_first::<IconButton>(tester);
7911 pump(tester);
7912
7913 assert!(
7914 !focus_node
7915 .as_node()
7916 .can_request_focus(&tester.cell.borrow_mut())
7917 );
7918 text_field(tester, |text_field| assert!(text_field.read_only));
7919 });
7920 }
7921
7922 const LONG_TEXT: &str = "one two three four five six seven eight nine ten eleven twelve";
7923
7924 fn menu_item_text(tester: &WidgetTester, label: &str) -> AnyElement {
7927 let button = find_menu_item_button(tester, &format!("{label} {LONG_TEXT}"));
7928 *tester
7929 .descendants_of_type::<Text>(button)
7930 .last()
7931 .expect("the item's text")
7932 }
7933
7934 fn long_entries(max_lines: i32) -> Vec<DropdownMenuEntry<TestMenu>> {
7935 TestMenu::VALUES
7936 .iter()
7937 .map(|item| {
7938 let label = format!("{} {LONG_TEXT}", item.label());
7939 DropdownMenuEntry::new(*item, label.clone())
7940 .label_widget(Text::new(label).max_lines(max_lines))
7941 })
7942 .collect()
7943 }
7944
7945 #[test]
7947 fn a_label_widget_with_max_lines_limits_the_item_height() {
7948 test_widgets(|tester| {
7949 let theme = theme(tester);
7950 let controller = controller(tester);
7951 for (max_lines, expected_height) in [(1, 20.0), (2, 40.0)] {
7952 tester.pump_widget(the_menu(
7953 theme.clone(),
7954 DropdownMenu::new(long_entries(max_lines))
7955 .key(waft_foundation::ValueKey::new(max_lines).into())
7956 .controller(controller.clone())
7957 .width(100.0),
7958 ));
7959 tap_dropdown_menu::<TestMenu>(tester);
7960
7961 for label in ["Item 0", "Menu 1", "Item 2", "Item 3"] {
7962 let height = tester.get_size(menu_item_text(tester, label)).height();
7963 assert!(
7964 (height - expected_height).abs() <= 0.05,
7965 "{max_lines} {label}: {height}"
7966 );
7967 }
7968
7969 tap_first::<TextField>(tester);
7971 tester.pump_and_settle();
7972 assert_eq!(controller_text(tester, controller.handle()), ""); }
7974 });
7975 }
7976
7977 #[derive(Debug)]
7980 struct TestDryLayout {
7981 child: WidgetRef,
7982 }
7983
7984 impl RenderObjectWidget for TestDryLayout {
7985 type RenderObject = RenderTestDryLayout;
7986
7987 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
7988 RenderTestDryLayout::new(app).as_object()
7989 }
7990
7991 fn update_render_object(
7992 &self,
7993 _app: &mut App,
7994 _context: BuildContext,
7995 _render_object: RenderHandle<RenderTestDryLayout>,
7996 ) {
7997 }
7998 }
7999
8000 impl SingleChildRenderObjectWidget for TestDryLayout {
8001 fn child(&self) -> Option<&WidgetRef> {
8002 Some(&self.child)
8003 }
8004 }
8005
8006 struct RenderTestDryLayout {
8007 render_object: RenderObjectData,
8008 render_box: RenderBoxData,
8009 child: RenderObjectWithChildData<AnyRenderBox>,
8010 }
8011
8012 impl RenderTestDryLayout {
8013 fn new(app: &mut App) -> RenderHandle<RenderTestDryLayout> {
8014 RenderHandle::new_box(
8015 app,
8016 RenderTestDryLayout {
8017 render_object: RenderObjectData::new(),
8018 render_box: RenderBoxData::new(),
8019 child: RenderObjectWithChildData::new(),
8020 },
8021 )
8022 }
8023 }
8024
8025 impl RenderObjectWithChildMixin for RenderTestDryLayout {
8026 type ChildType = AnyRenderBox;
8027
8028 fn child_data(
8029 self: RenderHandle<Self>,
8030 app: &App,
8031 ) -> &RenderObjectWithChildData<AnyRenderBox> {
8032 &self.get(app).child
8033 }
8034
8035 fn child_data_mut(
8036 self: RenderHandle<Self>,
8037 app: &mut App,
8038 ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
8039 &mut self.get_mut(app).child
8040 }
8041 }
8042
8043 impl RenderProxyBoxMixin for RenderTestDryLayout {}
8044
8045 impl RenderObject for RenderTestDryLayout {
8046 waft_rendering::render_object_accessors!();
8047
8048 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
8049 let constraints = self.constraints(app);
8050 let Some(child) = self.child(app) else {
8051 self.set_size(app, constraints.smallest());
8052 return;
8053 };
8054 child.get_dry_layout(app, constraints);
8055 child.layout(app, constraints, true);
8056 let size = child.size(app);
8057 self.set_size(app, size);
8058 }
8059
8060 fn paint(
8061 self: RenderHandle<Self>,
8062 app: &mut App,
8063 context: &mut PaintingContext,
8064 offset: Offset,
8065 ) {
8066 RenderProxyBoxMixin::paint(self, app, context, offset);
8067 }
8068
8069 fn visit_children(
8070 self: RenderHandle<Self>,
8071 app: &App,
8072 visitor: &mut dyn FnMut(AnyRenderObject),
8073 ) {
8074 if let Some(child) = self.child(app) {
8075 visitor(child.as_object());
8076 }
8077 }
8078 }
8079
8080 impl RenderBox for RenderTestDryLayout {
8081 waft_rendering::render_box_accessors!();
8082
8083 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
8084 RenderProxyBoxMixin::setup_parent_data(self, app, child);
8085 }
8086
8087 fn apply_paint_transform(
8088 self: RenderHandle<Self>,
8089 app: &App,
8090 child: AnyRenderObject,
8091 transform: &mut Matrix4,
8092 ) {
8093 RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
8094 }
8095
8096 fn hit_test_children(
8097 self: RenderHandle<Self>,
8098 app: &mut App,
8099 result: &mut BoxHitTestResult<'_>,
8100 position: Offset,
8101 ) -> bool {
8102 RenderProxyBoxMixin::hit_test_children(self, app, result, position)
8103 }
8104
8105 fn compute_min_intrinsic_width(
8106 self: RenderHandle<Self>,
8107 app: &mut App,
8108 height: f64,
8109 ) -> f64 {
8110 RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
8111 }
8112
8113 fn compute_max_intrinsic_width(
8114 self: RenderHandle<Self>,
8115 app: &mut App,
8116 height: f64,
8117 ) -> f64 {
8118 RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
8119 }
8120
8121 fn compute_min_intrinsic_height(
8122 self: RenderHandle<Self>,
8123 app: &mut App,
8124 width: f64,
8125 ) -> f64 {
8126 RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
8127 }
8128
8129 fn compute_max_intrinsic_height(
8130 self: RenderHandle<Self>,
8131 app: &mut App,
8132 width: f64,
8133 ) -> f64 {
8134 RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
8135 }
8136
8137 fn compute_distance_to_actual_baseline(
8138 self: RenderHandle<Self>,
8139 app: &mut App,
8140 baseline: TextBaseline,
8141 ) -> Option<f64> {
8142 RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
8143 }
8144
8145 fn compute_dry_layout(
8146 self: RenderHandle<Self>,
8147 app: &mut App,
8148 constraints: BoxConstraints,
8149 ) -> Size {
8150 RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
8151 }
8152
8153 fn compute_dry_baseline(
8154 self: RenderHandle<Self>,
8155 app: &mut App,
8156 constraints: BoxConstraints,
8157 baseline: TextBaseline,
8158 ) -> Option<f64> {
8159 RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
8160 }
8161 }
8162
8163 #[test]
8166 fn the_dropdown_menu_body_dry_layout_does_not_access_its_constraints() {
8167 test_widgets(|tester| {
8168 let theme = theme(tester);
8169 let menu = DropdownMenu::new(vec![
8170 DropdownMenuEntry::new(1, "One"),
8171 DropdownMenuEntry::new(2, "Two"),
8172 ]);
8173 let body = waft_widgets::Center::new().child(TestDryLayout {
8174 child: menu.into_widget(),
8175 });
8176 tester.pump_widget(material_app(
8177 theme,
8178 Scaffold::new().body(body).into_widget(),
8179 ));
8180
8181 expect(
8182 tester,
8183 &find::by_type::<DropdownMenu<i32>>(),
8184 finds_one_widget(),
8185 );
8186 });
8187 }
8188
8189 #[test]
8192 fn a_dropdown_menu_body_describes_its_children_in_order() {
8193 use waft_foundation::{AppCell, DiagnosticsNode};
8194 use waft_rendering::{BoxConstraints, RenderConstrainedBox};
8195
8196 let cell = AppCell::new();
8197 let mut app = cell.borrow_mut();
8198 let body = RenderDropdownMenuBody::new(&mut app, None);
8199 let child = |app: &mut App| {
8200 RenderConstrainedBox::new(app, BoxConstraints::tight(Size::new(10.0, 10.0)), None)
8201 .as_box()
8202 };
8203 let first = child(&mut app);
8204 let second = child(&mut app);
8205 body.insert(&mut app, first, None);
8206 body.insert(&mut app, second, None);
8207
8208 let node = body.as_object().to_diagnostics_node(&app, None);
8209 let names: Vec<&str> = node
8210 .children()
8211 .iter()
8212 .filter_map(|child| child.name())
8213 .collect();
8214 assert_eq!(names, ["child 1", "child 2"]);
8215 }
8216}