Skip to main content

waft_material/
search_anchor.rs

1//! Flutter counterpart: material_ui's `search_anchor.dart`.
2
3use std::fmt::{self, Debug};
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_animation::{
8    Animation, AnimationRef, Curve, CurvedAnimation, Curves, Interval, RectTween,
9};
10use waft_embedder::{
11    Brightness, Clip, Color, Offset, Rect, SemanticsInputType, Size, SmartDashesType,
12    SmartQuotesType, TextCapitalization, TextDirection, TextEditingValue, TextInputAction,
13    TextInputType, clamp_double, lerp_double,
14};
15use waft_foundation::{
16    App, ChangeNotifier, ChangeNotifierData, Handle, ListenableObject, Listener, OptionRetained,
17    Ref, Task, Timer, ValueChanged,
18};
19use waft_painting::{
20    AlignmentGeometry, AnyBorderSide, BorderSide, EdgeInsets, EdgeInsetsGeometry,
21    OutlinedBorderRef, TextStyle,
22};
23use waft_rendering::{BoxConstraints, CrossAxisAlignment, MainAxisSize, OverflowBoxFit};
24use waft_scheduler::{FrameCallback, SchedulerBinding, TickerFuture};
25use waft_widgets::{
26    Align, AnimatedBuilder, AnimatedOpacity, AnyRoute, BuildContext, CapturedThemes, Column,
27    ConstrainedBox, Directionality, EditableTextContextMenuBuilder, EditableTextState, Expanded,
28    FadeTransition, FlexFit, Flexible, FocusNode, FocusNodeLeaf, FocusNodeRef, FocusScope,
29    GestureDetector, GlobalKey, Icon, IconTheme, IconThemeData, IgnorePointer, InheritedTheme,
30    IntoWidget, KeyRef, LayoutBuilder, ListView, LocalHistoryRoute, LocalHistoryRouteData,
31    MediaQuery, ModalRoute, ModalRouteData, Navigator, Opacity, OverflowBox, OverlayRoute,
32    OverlayRouteData, Padding, PopupRoute, PredictiveBackRoute, Route, RouteData, RouteResult, Row,
33    SafeArea, Semantics, State, StateData, StatefulWidget, SystemContextMenu, TapRegionCallback,
34    TextEditingControllerData, TextEditingControllerLeaf, TextEditingControllerRef, Transform,
35    TransitionRoute, TransitionRouteData, UnfocusDisposition, WidgetRef, WidgetStatePropertyAll,
36    WidgetStatePropertyRef, WidgetStatesController,
37};
38
39use crate::action_buttons::BackButton;
40use crate::adaptive_text_selection_toolbar::AdaptiveTextSelectionToolbar;
41use crate::button_style::ButtonStyle;
42use crate::colors::Colors;
43use crate::constants::{K_DEFAULT_ICON_DARK_COLOR, K_DEFAULT_ICON_LIGHT_COLOR};
44use crate::divider::Divider;
45use crate::divider_theme::DividerTheme;
46use crate::generated::search_bar_defaults_m3::SearchBarDefaultsM3;
47use crate::generated::search_view_defaults_m3::SearchViewDefaultsM3;
48use crate::icon_button::IconButton;
49use crate::icons::Icons;
50use crate::ink_well::InkWell;
51use crate::input_border::InputBorderRef;
52use crate::input_decorator::{InputDecoration, InputDecorationThemeData};
53use crate::material::Material;
54use crate::material_localizations::MaterialLocalizations;
55use crate::search_bar_theme::{SearchBarTheme, SearchBarThemeDataGetters};
56use crate::search_view_theme::{SearchViewTheme, SearchViewThemeData, SearchViewThemeDataGetters};
57use crate::text_field::TextField;
58use crate::theme::Theme;
59use crate::theme_data::MaterialTapTargetSize;
60
61const K_OPEN_VIEW_MILLISECONDS: u64 = 600;
62const K_OPEN_VIEW_DURATION: Duration = Duration::from_millis(K_OPEN_VIEW_MILLISECONDS);
63const K_ANCHOR_FADE_DURATION: Duration = Duration::from_millis(150);
64const K_DISABLE_SEARCH_BAR_OPACITY: f64 = 0.38;
65
66fn k_view_fade_on_interval() -> Rc<dyn Curve> {
67    Rc::new(Interval::new(0.0, 1.0 / 2.0, Curves::linear()))
68}
69
70fn k_view_icons_fade_on_interval() -> Rc<dyn Curve> {
71    Rc::new(Interval::new(1.0 / 6.0, 2.0 / 6.0, Curves::linear()))
72}
73
74fn k_view_divider_fade_on_interval() -> Rc<dyn Curve> {
75    Rc::new(Interval::new(0.0, 1.0 / 6.0, Curves::linear()))
76}
77
78fn k_view_list_fade_on_interval() -> Rc<dyn Curve> {
79    Rc::new(Interval::new(
80        133.0 / K_OPEN_VIEW_MILLISECONDS as f64,
81        233.0 / K_OPEN_VIEW_MILLISECONDS as f64,
82        Curves::linear(),
83    ))
84}
85
86/// Signature for a function that creates a [`WidgetRef`] to build the child of a
87/// [`SearchAnchor`].
88///
89/// Used by [`SearchAnchor::builder`].
90pub type SearchAnchorChildBuilder =
91    Rc<dyn Fn(&mut App, BuildContext, Handle<SearchController>) -> WidgetRef>;
92
93/// Signature for a function that creates a list of suggestion widgets for the search view
94/// of a [`SearchAnchor`].
95///
96/// Dart's `FutureOr<Iterable<Widget>>` is a [`Task`]: a builder with its suggestions at hand
97/// answers [`Task::ready`], which reaches the view at the next checkpoint, as Dart's `await` of
98/// a plain value resumes from the microtask queue.
99///
100/// Used by [`SearchAnchor::suggestions_builder`].
101pub type SuggestionsBuilder =
102    Rc<dyn Fn(&mut App, BuildContext, Handle<SearchController>) -> Task<Vec<WidgetRef>>>;
103
104/// Signature for a function that creates a [`WidgetRef`] to build the suggestion list
105/// of a [`SearchAnchor`] in its search view.
106///
107/// Used by [`SearchAnchor::view_builder`].
108pub type ViewBuilder = Rc<dyn Fn(&mut App, Vec<WidgetRef>) -> WidgetRef>;
109
110/// Creates a search bar that when focused opens a search view to input a search query.
111///
112/// This widget is the anchor of a search view: the search view is shown over the anchor, and
113/// closes back to it. The [`builder`](Self::builder) creates the anchor and the
114/// [`suggestions_builder`](Self::suggestions_builder) creates the suggestions in the search
115/// view. A [`SearchController`] opens and closes the view and holds what is typed in it.
116///
117/// See also:
118///
119///  * [`SearchBar`], a widget that defines a search bar.
120///  * [`SearchBarTheme`], a widget that overrides the default configuration of a search bar.
121///  * [`SearchViewTheme`], a widget that overrides the default configuration of a search
122///    view.
123#[derive(Clone)]
124pub struct SearchAnchor {
125    pub key: Option<KeyRef>,
126
127    /// Whether the search view grows to fill the entire screen when the [`SearchBar`] is
128    /// tapped.
129    ///
130    /// By default, the search view is full-screen on mobile devices. On other platforms, the
131    /// search view only grows to a specific size that is determined by the anchor and the
132    /// default size.
133    pub is_full_screen: Option<bool>,
134
135    /// An optional controller that allows opening and closing of the search view from other
136    /// widgets.
137    ///
138    /// If this is null, one internal search controller is created automatically. It can
139    /// be accessed through [`SearchAnchorChildBuilder`] or [`SuggestionsBuilder`].
140    pub search_controller: Option<Ref<SearchController>>,
141
142    /// Optional callback to obtain a widget to lay out the suggestion list of the search
143    /// view.
144    ///
145    /// Default view uses a [`ListView`] with a vertical scroll direction.
146    pub view_builder: Option<ViewBuilder>,
147
148    /// An optional widget to display before the text input field when the search view is
149    /// open.
150    ///
151    /// Typically the [`view_leading`](Self::view_leading) widget is an [`Icon`] or an
152    /// [`IconButton`].
153    ///
154    /// Defaults to a back button which pops the view.
155    pub view_leading: Option<WidgetRef>,
156
157    /// An optional widget list to display after the text input field when the search view is
158    /// open.
159    ///
160    /// Typically the [`view_trailing`](Self::view_trailing) widget list is a list of
161    /// [`Icon`]s or [`IconButton`]s.
162    ///
163    /// Defaults to an icon button which clears the text in the input field.
164    pub view_trailing: Option<Vec<WidgetRef>>,
165
166    /// Text that is displayed when the search bar's input field is empty.
167    pub view_hint_text: Option<String>,
168
169    /// The search view's background fill color.
170    ///
171    /// If null, the value of [`SearchViewThemeData::background_color`] will be used. If this
172    /// is also null, then the default value is `ColorScheme::surface_container_high`.
173    pub view_background_color: Option<Color>,
174
175    /// The elevation of the search view's [`Material`].
176    ///
177    /// If null, the value of [`SearchViewThemeData::elevation`] will be used. If this is also
178    /// null, then default value is 6.0.
179    pub view_elevation: Option<f64>,
180
181    /// The surface tint color of the search view's [`Material`].
182    ///
183    /// If null, the value of [`SearchViewThemeData::surface_tint_color`] will be used. If this
184    /// is also null, then the default value is `Colors::TRANSPARENT`.
185    pub view_surface_tint_color: Option<Color>,
186
187    /// The color and weight of the search view's outline.
188    ///
189    /// This value is combined with [`view_shape`](Self::view_shape) to create a shape
190    /// decorated with an outline.
191    ///
192    /// If null, the value of [`SearchViewThemeData::side`] will be used. If this is also null,
193    /// the search view doesn't have a side by default.
194    pub view_side: Option<AnyBorderSide>,
195
196    /// The shape of the search view's underlying [`Material`].
197    ///
198    /// This shape is combined with [`view_side`](Self::view_side) to create a shape
199    /// decorated with an outline.
200    ///
201    /// If null, the value of [`SearchViewThemeData::shape`] will be used. If this is also
202    /// null, then the default value is a rectangle shape for full-screen mode and a
203    /// [`RoundedRectangleBorder`](waft_painting::RoundedRectangleBorder) shape with a 28.0
204    /// radius otherwise.
205    pub view_shape: Option<OutlinedBorderRef>,
206
207    /// The padding to use for the search view's search bar.
208    ///
209    /// If null, the value of [`SearchViewThemeData::bar_padding`] will be used. If this is
210    /// also null, then the default value is `EdgeInsets::symmetric(0.0, 8.0)`.
211    pub view_bar_padding: Option<EdgeInsetsGeometry>,
212
213    /// The height of the search field on the search view.
214    ///
215    /// If null, the value of [`SearchViewThemeData::header_height`] will be used. If this is
216    /// also null, the default value is 56.0.
217    pub header_height: Option<f64>,
218
219    /// The style to use for the text being edited on the search view.
220    ///
221    /// If null, defaults to the `bodyLarge` text style from the current [`Theme`]. The default
222    /// text color is `ColorScheme::on_surface`.
223    pub header_text_style: Option<TextStyle>,
224
225    /// The style to use for the [`view_hint_text`](Self::view_hint_text) on the search view.
226    ///
227    /// If null, the value of [`SearchViewThemeData::header_hint_style`] will be used. If this
228    /// is also null, the value of `header_text_style` will be used, and then `bodyLarge`.
229    pub header_hint_style: Option<TextStyle>,
230
231    /// The color of the divider on the search view.
232    ///
233    /// If this property is null, then [`SearchViewThemeData::divider_color`] is used. If that
234    /// is also null, the default value is `ColorScheme::outline`.
235    pub divider_color: Option<Color>,
236
237    /// Optional size constraints for the search view.
238    ///
239    /// By default, the search view has the same width as the anchor and is 2/3 the height of
240    /// the screen. If the width and height of the view are within the range of constraints,
241    /// the view will keep the default size.
242    ///
243    /// If null, the value of [`SearchViewThemeData::constraints`] will be used. If that is
244    /// also null, the default constraints are `BoxConstraints { min_width: 360.0, min_height:
245    /// 240.0, .. }`.
246    pub view_constraints: Option<BoxConstraints>,
247
248    /// The padding to use for the search view.
249    ///
250    /// Has no effect if the search view is full-screen.
251    pub view_padding: Option<EdgeInsetsGeometry>,
252
253    /// Whether the search view should shrink-wrap its contents.
254    ///
255    /// Has no effect if the search view is full-screen.
256    pub shrink_wrap: Option<bool>,
257
258    /// Configures how the platform keyboard will select an uppercase or lowercase keyboard.
259    ///
260    /// Only supports text keyboards, other keyboard types will ignore this configuration.
261    /// Capitalization is locale-aware.
262    ///
263    /// Defaults to [`TextCapitalization::None`].
264    pub text_capitalization: Option<TextCapitalization>,
265
266    /// Called each time the user modifies the search view's text field.
267    pub view_on_changed: Option<ValueChanged<String>>,
268
269    /// Called when the user indicates that they are done editing the text in the field.
270    pub view_on_submitted: Option<ValueChanged<String>>,
271
272    /// Called when the search view is closed.
273    pub view_on_close: Option<Listener>,
274
275    /// Called when the search view is opened.
276    pub view_on_open: Option<Listener>,
277
278    /// Called to create a widget which can open a search view route when it is tapped.
279    ///
280    /// The widget returned by this builder is faded out when it is tapped. At the same time a
281    /// search view route is faded in.
282    pub builder: SearchAnchorChildBuilder,
283
284    /// Called to get the suggestion list for the search view.
285    ///
286    /// By default, the list returned by this builder is laid out in a [`ListView`]. To get a
287    /// different layout, use [`view_builder`](Self::view_builder) to override.
288    pub suggestions_builder: SuggestionsBuilder,
289
290    /// The type of action button to use for the keyboard.
291    ///
292    /// Defaults to the default value specified in [`TextField`].
293    pub text_input_action: Option<TextInputAction>,
294
295    /// The type of action button to use for the keyboard.
296    ///
297    /// Defaults to the default value specified in [`TextField`].
298    pub keyboard_type: Option<TextInputType>,
299
300    /// Whether or not this widget is currently interactive.
301    ///
302    /// When false, the widget will ignore taps and appear dimmed.
303    pub enabled: bool,
304
305    /// Whether to allow the platform to automatically format dashes.
306    ///
307    /// This flag is only meaningful on an iOS device.
308    pub smart_dashes_type: Option<SmartDashesType>,
309
310    /// Whether to allow the platform to automatically format quotes.
311    ///
312    /// This flag is only meaningful on an iOS device.
313    pub smart_quotes_type: Option<SmartQuotesType>,
314
315    /// Whether the anchor opens the search view when it is tapped.
316    ///
317    /// [`SearchAnchor::bar`] sets this to false because its search bar opens the view itself.
318    pub enable_tap_handling: bool,
319}
320
321impl SearchAnchor {
322    /// Creates a const [`SearchAnchor`].
323    ///
324    /// The [`builder`](Self::builder) and [`suggestions_builder`](Self::suggestions_builder)
325    /// arguments are required.
326    pub fn new(
327        builder: impl Fn(&mut App, BuildContext, Handle<SearchController>) -> WidgetRef + 'static,
328        suggestions_builder: impl Fn(
329            &mut App,
330            BuildContext,
331            Handle<SearchController>,
332        ) -> Task<Vec<WidgetRef>>
333        + 'static,
334    ) -> SearchAnchor {
335        SearchAnchor {
336            key: None,
337            is_full_screen: None,
338            search_controller: None,
339            view_builder: None,
340            view_leading: None,
341            view_trailing: None,
342            view_hint_text: None,
343            view_background_color: None,
344            view_elevation: None,
345            view_surface_tint_color: None,
346            view_side: None,
347            view_shape: None,
348            view_bar_padding: None,
349            header_height: None,
350            header_text_style: None,
351            header_hint_style: None,
352            divider_color: None,
353            view_constraints: None,
354            view_padding: None,
355            shrink_wrap: None,
356            text_capitalization: None,
357            view_on_changed: None,
358            view_on_submitted: None,
359            view_on_close: None,
360            view_on_open: None,
361            builder: Rc::new(builder),
362            suggestions_builder: Rc::new(suggestions_builder),
363            text_input_action: None,
364            keyboard_type: None,
365            enabled: true,
366            smart_dashes_type: None,
367            smart_quotes_type: None,
368            enable_tap_handling: true,
369        }
370    }
371
372    /// Creates a search anchor that is a [`SearchBar`] when the search view is closed.
373    ///
374    /// Dart's `SearchAnchor.bar` factory, which has about forty named arguments; here it is
375    /// [`SearchAnchorWithSearchBar`], whose setters are those arguments and whose
376    /// [`into_widget`](IntoWidget::into_widget) builds the [`SearchAnchor`].
377    pub fn bar(
378        suggestions_builder: impl Fn(
379            &mut App,
380            BuildContext,
381            Handle<SearchController>,
382        ) -> Task<Vec<WidgetRef>>
383        + 'static,
384    ) -> SearchAnchorWithSearchBar {
385        SearchAnchorWithSearchBar::new(suggestions_builder)
386    }
387
388    /// Dart `SearchAnchor(key:)`.
389    pub fn key(mut self, key: KeyRef) -> SearchAnchor {
390        self.key = Some(key);
391        self
392    }
393
394    /// Dart `SearchAnchor(isFullScreen:)`.
395    pub fn is_full_screen(mut self, is_full_screen: bool) -> SearchAnchor {
396        self.is_full_screen = Some(is_full_screen);
397        self
398    }
399
400    /// Dart `SearchAnchor(searchController:)`.
401    pub fn search_controller(mut self, search_controller: Ref<SearchController>) -> SearchAnchor {
402        self.search_controller = Some(search_controller);
403        self
404    }
405
406    /// Dart `SearchAnchor(viewBuilder:)`.
407    pub fn view_builder(
408        mut self,
409        view_builder: impl Fn(&mut App, Vec<WidgetRef>) -> WidgetRef + 'static,
410    ) -> SearchAnchor {
411        self.view_builder = Some(Rc::new(view_builder));
412        self
413    }
414
415    /// Dart `SearchAnchor(viewLeading:)`.
416    #[cfg_attr(debug_assertions, track_caller)]
417    pub fn view_leading<K>(mut self, view_leading: impl IntoWidget<K>) -> SearchAnchor {
418        self.view_leading = Some(view_leading.into_widget());
419        self
420    }
421
422    /// Dart `SearchAnchor(viewTrailing:)`.
423    pub fn view_trailing(mut self, view_trailing: Vec<WidgetRef>) -> SearchAnchor {
424        self.view_trailing = Some(view_trailing);
425        self
426    }
427
428    /// Dart `SearchAnchor(viewHintText:)`.
429    pub fn view_hint_text(mut self, view_hint_text: impl Into<String>) -> SearchAnchor {
430        self.view_hint_text = Some(view_hint_text.into());
431        self
432    }
433
434    /// Dart `SearchAnchor(viewBackgroundColor:)`.
435    pub fn view_background_color(mut self, view_background_color: Color) -> SearchAnchor {
436        self.view_background_color = Some(view_background_color);
437        self
438    }
439
440    /// Dart `SearchAnchor(viewElevation:)`.
441    pub fn view_elevation(mut self, view_elevation: f64) -> SearchAnchor {
442        self.view_elevation = Some(view_elevation);
443        self
444    }
445
446    /// Dart `SearchAnchor(viewSurfaceTintColor:)`.
447    pub fn view_surface_tint_color(mut self, view_surface_tint_color: Color) -> SearchAnchor {
448        self.view_surface_tint_color = Some(view_surface_tint_color);
449        self
450    }
451
452    /// Dart `SearchAnchor(viewSide:)`.
453    pub fn view_side(mut self, view_side: impl Into<AnyBorderSide>) -> SearchAnchor {
454        self.view_side = Some(view_side.into());
455        self
456    }
457
458    /// Dart `SearchAnchor(viewShape:)`.
459    pub fn view_shape(mut self, view_shape: impl Into<OutlinedBorderRef>) -> SearchAnchor {
460        self.view_shape = Some(view_shape.into());
461        self
462    }
463
464    /// Dart `SearchAnchor(viewBarPadding:)`.
465    pub fn view_bar_padding(
466        mut self,
467        view_bar_padding: impl Into<EdgeInsetsGeometry>,
468    ) -> SearchAnchor {
469        self.view_bar_padding = Some(view_bar_padding.into());
470        self
471    }
472
473    /// Dart `SearchAnchor(headerHeight:)`.
474    pub fn header_height(mut self, header_height: f64) -> SearchAnchor {
475        self.header_height = Some(header_height);
476        self
477    }
478
479    /// Dart `SearchAnchor(headerTextStyle:)`.
480    pub fn header_text_style(mut self, header_text_style: TextStyle) -> SearchAnchor {
481        self.header_text_style = Some(header_text_style);
482        self
483    }
484
485    /// Dart `SearchAnchor(headerHintStyle:)`.
486    pub fn header_hint_style(mut self, header_hint_style: TextStyle) -> SearchAnchor {
487        self.header_hint_style = Some(header_hint_style);
488        self
489    }
490
491    /// Dart `SearchAnchor(dividerColor:)`.
492    pub fn divider_color(mut self, divider_color: Color) -> SearchAnchor {
493        self.divider_color = Some(divider_color);
494        self
495    }
496
497    /// Dart `SearchAnchor(viewConstraints:)`.
498    pub fn view_constraints(mut self, view_constraints: BoxConstraints) -> SearchAnchor {
499        self.view_constraints = Some(view_constraints);
500        self
501    }
502
503    /// Dart `SearchAnchor(viewPadding:)`.
504    pub fn view_padding(mut self, view_padding: impl Into<EdgeInsetsGeometry>) -> SearchAnchor {
505        self.view_padding = Some(view_padding.into());
506        self
507    }
508
509    /// Dart `SearchAnchor(shrinkWrap:)`.
510    pub fn shrink_wrap(mut self, shrink_wrap: bool) -> SearchAnchor {
511        self.shrink_wrap = Some(shrink_wrap);
512        self
513    }
514
515    /// Dart `SearchAnchor(textCapitalization:)`.
516    pub fn text_capitalization(mut self, text_capitalization: TextCapitalization) -> SearchAnchor {
517        self.text_capitalization = Some(text_capitalization);
518        self
519    }
520
521    /// Dart `SearchAnchor(viewOnChanged:)`.
522    pub fn view_on_changed(
523        mut self,
524        view_on_changed: impl Fn(&mut App, String) + 'static,
525    ) -> SearchAnchor {
526        self.view_on_changed = Some(Rc::new(view_on_changed));
527        self
528    }
529
530    /// Dart `SearchAnchor(viewOnSubmitted:)`.
531    pub fn view_on_submitted(
532        mut self,
533        view_on_submitted: impl Fn(&mut App, String) + 'static,
534    ) -> SearchAnchor {
535        self.view_on_submitted = Some(Rc::new(view_on_submitted));
536        self
537    }
538
539    /// Dart `SearchAnchor(viewOnClose:)`.
540    pub fn view_on_close(mut self, view_on_close: Listener) -> SearchAnchor {
541        self.view_on_close = Some(view_on_close);
542        self
543    }
544
545    /// Dart `SearchAnchor(viewOnOpen:)`.
546    pub fn view_on_open(mut self, view_on_open: Listener) -> SearchAnchor {
547        self.view_on_open = Some(view_on_open);
548        self
549    }
550
551    /// Dart `SearchAnchor(textInputAction:)`.
552    pub fn text_input_action(mut self, text_input_action: TextInputAction) -> SearchAnchor {
553        self.text_input_action = Some(text_input_action);
554        self
555    }
556
557    /// Dart `SearchAnchor(keyboardType:)`.
558    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> SearchAnchor {
559        self.keyboard_type = Some(keyboard_type);
560        self
561    }
562
563    /// Dart `SearchAnchor(enabled:)`.
564    pub fn enabled(mut self, enabled: bool) -> SearchAnchor {
565        self.enabled = enabled;
566        self
567    }
568
569    /// Dart `SearchAnchor(smartDashesType:)`.
570    pub fn smart_dashes_type(mut self, smart_dashes_type: SmartDashesType) -> SearchAnchor {
571        self.smart_dashes_type = Some(smart_dashes_type);
572        self
573    }
574
575    /// Dart `SearchAnchor(smartQuotesType:)`.
576    pub fn smart_quotes_type(mut self, smart_quotes_type: SmartQuotesType) -> SearchAnchor {
577        self.smart_quotes_type = Some(smart_quotes_type);
578        self
579    }
580
581    /// Dart `SearchAnchor(enableTapHandling:)`.
582    pub fn enable_tap_handling(mut self, enable_tap_handling: bool) -> SearchAnchor {
583        self.enable_tap_handling = enable_tap_handling;
584        self
585    }
586}
587
588impl Debug for SearchAnchor {
589    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590        f.debug_struct("SearchAnchor")
591            .field("is_full_screen", &self.is_full_screen)
592            .field("view_hint_text", &self.view_hint_text)
593            .field("enabled", &self.enabled)
594            .field("enable_tap_handling", &self.enable_tap_handling)
595            .finish_non_exhaustive()
596    }
597}
598
599impl StatefulWidget for SearchAnchor {
600    type State = SearchAnchorState;
601
602    fn key(&self) -> Option<&KeyRef> {
603        self.key.as_ref()
604    }
605
606    fn create_state(&self) -> SearchAnchorState {
607        SearchAnchorState {
608            state: StateData::new(),
609            screen_size: None,
610            anchor_is_visible: true,
611            anchor_key: GlobalKey::new(),
612            internal_search_controller: None,
613            route: None,
614        }
615    }
616}
617
618/// Dart's `_SearchAnchorState`.
619pub struct SearchAnchorState {
620    state: StateData<SearchAnchor>,
621    screen_size: Option<Size>,
622    anchor_is_visible: bool,
623    anchor_key: GlobalKey,
624    internal_search_controller: Option<Ref<SearchController>>,
625    route: Option<Ref<SearchViewRoute>>,
626}
627
628impl SearchAnchorState {
629    /// Dart's `_viewIsOpen`.
630    fn view_is_open(self: Handle<Self>, app: &App) -> bool {
631        !app.get(self).anchor_is_visible
632    }
633
634    /// Dart's `_searchController`.
635    fn search_controller(self: Handle<Self>, app: &mut App) -> Handle<SearchController> {
636        if let Some(search_controller) = &self.widget(app).search_controller {
637            return search_controller.handle();
638        }
639        if app.get(self).internal_search_controller.is_none() {
640            let internal = SearchController::new(app);
641            app.get_mut(self).internal_search_controller = Some(internal);
642        }
643        app.get(self)
644            .internal_search_controller
645            .as_ref()
646            .expect("created above")
647            .handle()
648    }
649
650    fn open_view(self: Handle<Self>, app: &mut App) {
651        let context = self.context(app);
652        let navigator = Navigator::of(app, context, false);
653        let widget = self.widget(app).clone();
654        let search_controller = self.search_controller(app);
655        let show_full_screen_view = self.get_show_full_screen_view(app);
656        let text_direction = Directionality::of(app, context);
657        let captured_themes =
658            <dyn InheritedTheme>::capture(app, context, Some(navigator.context(app)));
659        let anchor_key = app.get(self).anchor_key.clone();
660        let route = SearchViewRoute::new(
661            app,
662            SearchViewRouteArguments {
663                view_on_changed: widget.view_on_changed.clone(),
664                view_on_submitted: widget.view_on_submitted.clone(),
665                view_on_close: widget.view_on_close.clone(),
666                view_on_open: widget.view_on_open.clone(),
667                view_leading: widget.view_leading.clone(),
668                view_trailing: widget.view_trailing.clone(),
669                view_hint_text: widget.view_hint_text.clone(),
670                view_background_color: widget.view_background_color,
671                view_elevation: widget.view_elevation,
672                view_surface_tint_color: widget.view_surface_tint_color,
673                view_side: widget.view_side.clone(),
674                view_shape: widget.view_shape.clone(),
675                view_bar_padding: widget.view_bar_padding,
676                view_header_height: widget.header_height,
677                view_header_text_style: widget.header_text_style.clone(),
678                view_header_hint_style: widget.header_hint_style.clone(),
679                divider_color: widget.divider_color,
680                view_constraints: widget.view_constraints,
681                view_padding: widget.view_padding,
682                shrink_wrap: widget.shrink_wrap,
683                show_full_screen_view,
684                toggle_visibility: Some(Rc::new(move |app: &mut App| self.toggle_visibility(app))),
685                text_direction: Some(text_direction),
686                view_builder: widget.view_builder.clone(),
687                anchor_key,
688                search_controller: search_controller.keep(app),
689                suggestions_builder: Rc::clone(&widget.suggestions_builder),
690                text_capitalization: widget.text_capitalization,
691                captured_themes: Rc::new(captured_themes),
692                text_input_action: widget.text_input_action,
693                keyboard_type: widget.keyboard_type,
694                smart_dashes_type: widget.smart_dashes_type,
695                smart_quotes_type: widget.smart_quotes_type,
696            },
697        );
698        app.get_mut(self).route = Some(route.clone());
699        navigator.push(app, route.into_erased());
700    }
701
702    fn close_view(self: Handle<Self>, app: &mut App, selected_text: Option<String>) {
703        if let Some(selected_text) = selected_text {
704            let search_controller = self.search_controller(app);
705            search_controller.set_value(app, TextEditingValue::new().text(selected_text));
706        }
707        let context = self.context(app);
708        Navigator::pop(app, context, None);
709    }
710
711    fn toggle_visibility(self: Handle<Self>, app: &mut App) -> bool {
712        self.set_state(app, |state| {
713            state.anchor_is_visible = !state.anchor_is_visible;
714        });
715        app.get(self).anchor_is_visible
716    }
717
718    fn get_show_full_screen_view(self: Handle<Self>, app: &mut App) -> bool {
719        use waft_embedder::TargetPlatform;
720        if let Some(is_full_screen) = self.widget(app).is_full_screen {
721            return is_full_screen;
722        }
723        let context = self.context(app);
724        match Theme::of(app, context).platform {
725            TargetPlatform::IOS | TargetPlatform::Android | TargetPlatform::Fuchsia => true,
726            TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => false,
727        }
728    }
729
730    fn get_opacity(self: Handle<Self>, app: &App) -> f64 {
731        if self.widget(app).enabled {
732            return if app.get(self).anchor_is_visible {
733                1.0
734            } else {
735                0.0
736            };
737        }
738        K_DISABLE_SEARCH_BAR_OPACITY
739    }
740}
741
742impl State for SearchAnchorState {
743    type Widget = SearchAnchor;
744    waft_widgets::state_accessors!();
745
746    fn init_state(self: Handle<Self>, app: &mut App) {
747        let search_controller = self.search_controller(app);
748        search_controller.attach(app, self);
749    }
750
751    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
752        let context = self.context(app);
753        let updated_screen_size = MediaQuery::of(app, context).size;
754        if let Some(screen_size) = app.get(self).screen_size
755            && screen_size != updated_screen_size
756        {
757            let search_controller = self.search_controller(app);
758            if search_controller.is_open(app) && !self.get_show_full_screen_view(app) {
759                self.close_view(app, None);
760            }
761        }
762        app.get_mut(self).screen_size = Some(updated_screen_size);
763    }
764
765    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SearchAnchor) {
766        let widget = self.widget(app);
767        let (old, new) = (
768            old_widget.search_controller.as_ref().map(Ref::handle),
769            widget.search_controller.as_ref().map(Ref::handle),
770        );
771        if old != new {
772            if let Some(old) = old {
773                old.detach(app, self);
774            }
775            let search_controller = self.search_controller(app);
776            search_controller.attach(app, self);
777        }
778    }
779
780    fn dispose(self: Handle<Self>, app: &mut App) {
781        if let Some(search_controller) = self.widget(app).search_controller.clone() {
782            search_controller.handle().detach(app, self);
783        }
784        if let Some(internal) = app.get(self).internal_search_controller.clone() {
785            internal.handle().detach(app, self);
786        }
787        let using_external_controller = self.widget(app).search_controller.is_some();
788        let route = app.get(self).route.clone();
789        let route_is_in_navigator = route
790            .as_ref()
791            .is_some_and(|route| route.handle().navigator(app).is_some());
792        if route_is_in_navigator {
793            if let Some(route) = route {
794                route.handle().dismiss(app, !using_external_controller);
795            }
796            if using_external_controller
797                && let Some(internal) = app.get(self).internal_search_controller.clone()
798            {
799                ChangeNotifierData::dispose(app, internal.handle());
800            }
801        } else if let Some(internal) = app.get(self).internal_search_controller.clone() {
802            ChangeNotifierData::dispose(app, internal.handle());
803        }
804    }
805
806    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
807        let widget = self.widget(app).clone();
808        let search_controller = self.search_controller(app);
809        let mut child = (widget.builder)(app, context, search_controller);
810        if widget.enable_tap_handling {
811            child = GestureDetector::new()
812                .on_tap(Listener::handle_method(self, SearchAnchorState::open_view))
813                .child(child)
814                .into_widget();
815        }
816        let anchor_key = app.get(self).anchor_key.clone();
817        AnimatedOpacity::new(self.get_opacity(app), K_ANCHOR_FADE_DURATION)
818            .key(anchor_key.into())
819            .child(IgnorePointer::new().ignoring(!widget.enabled).child(child))
820            .into_widget()
821    }
822}
823
824/// Dart's `ValueGetter<bool>` the anchor hands its route: toggles the anchor's visibility and
825/// answers the new one.
826type ToggleVisibility = Rc<dyn Fn(&mut App) -> bool>;
827
828/// The arguments of a [`SearchViewRoute`], Dart's `_SearchViewRoute(..)` named arguments.
829pub(crate) struct SearchViewRouteArguments {
830    view_on_changed: Option<ValueChanged<String>>,
831    view_on_submitted: Option<ValueChanged<String>>,
832    view_on_close: Option<Listener>,
833    view_on_open: Option<Listener>,
834    view_leading: Option<WidgetRef>,
835    view_trailing: Option<Vec<WidgetRef>>,
836    view_hint_text: Option<String>,
837    view_background_color: Option<Color>,
838    view_elevation: Option<f64>,
839    view_surface_tint_color: Option<Color>,
840    view_side: Option<AnyBorderSide>,
841    view_shape: Option<OutlinedBorderRef>,
842    view_bar_padding: Option<EdgeInsetsGeometry>,
843    view_header_height: Option<f64>,
844    view_header_text_style: Option<TextStyle>,
845    view_header_hint_style: Option<TextStyle>,
846    divider_color: Option<Color>,
847    view_constraints: Option<BoxConstraints>,
848    view_padding: Option<EdgeInsetsGeometry>,
849    shrink_wrap: Option<bool>,
850    show_full_screen_view: bool,
851    toggle_visibility: Option<ToggleVisibility>,
852    text_direction: Option<TextDirection>,
853    view_builder: Option<ViewBuilder>,
854    anchor_key: GlobalKey,
855    search_controller: Ref<SearchController>,
856    suggestions_builder: SuggestionsBuilder,
857    text_capitalization: Option<TextCapitalization>,
858    captured_themes: Rc<CapturedThemes>,
859    text_input_action: Option<TextInputAction>,
860    keyboard_type: Option<TextInputType>,
861    smart_dashes_type: Option<SmartDashesType>,
862    smart_quotes_type: Option<SmartQuotesType>,
863}
864
865/// Dart's `_SearchViewRoute`.
866pub(crate) struct SearchViewRoute {
867    route: RouteData,
868    overlay_route: OverlayRouteData,
869    transition_route: TransitionRouteData,
870    local_history: LocalHistoryRouteData,
871    modal_route: ModalRouteData,
872    arguments: SearchViewRouteArguments,
873    curved_animation: Option<Ref<CurvedAnimation>>,
874    view_fade_on_interval_curve: Option<Ref<CurvedAnimation>>,
875    will_dispose_search_controller: bool,
876    view_defaults: Option<SearchViewDefaultsM3>,
877    view_theme: Option<SearchViewThemeData>,
878    rect_tween: Ref<RectTween>,
879}
880
881impl SearchViewRoute {
882    fn new(app: &mut App, arguments: SearchViewRouteArguments) -> Ref<SearchViewRoute> {
883        let route = RouteData::new(app, None, None);
884        let transition_route = TransitionRouteData::new(app);
885        let modal_route = ModalRouteData::new(app);
886        let rect_tween = RectTween::new(app, None, None);
887        app.create(SearchViewRoute {
888            route,
889            overlay_route: OverlayRouteData::new(),
890            transition_route,
891            local_history: LocalHistoryRouteData::new(),
892            modal_route,
893            arguments,
894            curved_animation: None,
895            view_fade_on_interval_curve: None,
896            will_dispose_search_controller: false,
897            view_defaults: None,
898            view_theme: None,
899            rect_tween,
900        })
901    }
902
903    fn get_rect(self: Handle<Self>, app: &mut App) -> Option<Rect> {
904        let anchor_key = app.get(self).arguments.anchor_key.clone();
905        let context = anchor_key.current_context(app)?;
906        let search_bar_box = context
907            .find_render_object(app)
908            .expect("a mounted anchor")
909            .as_box()
910            .expect("a box");
911        let box_size = search_bar_box.size(app);
912        let navigator = Navigator::of(app, context, false);
913        let ancestor = navigator.context(app).find_render_object(app);
914        let box_location = search_bar_box.local_to_global(app, Offset::ZERO, ancestor);
915        Some(Rect::from_ltwh(
916            box_location.dx(),
917            box_location.dy(),
918            box_size.width(),
919            box_size.height(),
920        ))
921    }
922
923    fn dismiss(self: Handle<Self>, app: &mut App, dispose_controller: bool) {
924        app.get_mut(self).will_dispose_search_controller = dispose_controller;
925        if self.as_route().is_active(app) {
926            let navigator = self.as_route().navigator(app);
927            if let Some(navigator) = navigator {
928                navigator.remove_route(app, self.as_route(), None);
929            }
930        }
931    }
932
933    fn update_view_config(self: Handle<Self>, app: &mut App, context: BuildContext) {
934        let show_full_screen_view = app.get(self).arguments.show_full_screen_view;
935        let view_theme = SearchViewTheme::of(app, context);
936        let route = app.get_mut(self);
937        route.view_defaults = Some(SearchViewDefaultsM3::new(context, show_full_screen_view));
938        route.view_theme = Some(view_theme);
939    }
940
941    fn update_tweens(self: Handle<Self>, app: &mut App, context: BuildContext) {
942        let navigator_box = Navigator::of(app, context, false)
943            .context(app)
944            .find_render_object(app)
945            .expect("a navigator render object")
946            .as_box()
947            .expect("a box");
948        let screen_size = navigator_box.size(app);
949        let anchor_rect = self.get_rect(app).unwrap_or(Rect::ZERO);
950
951        let view_constraints = app.get(self).arguments.view_constraints;
952        let theme_constraints = app
953            .get(self)
954            .view_theme
955            .as_ref()
956            .and_then(|view_theme| view_theme.constraints);
957        let effective_constraints = view_constraints
958            .or(theme_constraints)
959            .or_else(|| {
960                // `viewDefaults.constraints!`.
961                let defaults = app
962                    .get_mut(self)
963                    .view_defaults
964                    .take()
965                    .expect("set by update_view_config");
966                let constraints = defaults.constraints(app);
967                app.get_mut(self).view_defaults = Some(defaults);
968                constraints
969            })
970            .expect("viewDefaults.constraints!");
971        app.get_mut(&app.get(self).rect_tween.clone()).begin = Some(anchor_rect);
972
973        let view_width = clamp_double(
974            anchor_rect.width(),
975            effective_constraints.min_width,
976            effective_constraints.max_width,
977        );
978        let view_height = clamp_double(
979            screen_size.height() * 2.0 / 3.0,
980            effective_constraints.min_height,
981            effective_constraints.max_height,
982        );
983
984        let show_full_screen_view = app.get(self).arguments.show_full_screen_view;
985        let text_direction = app
986            .get(self)
987            .arguments
988            .text_direction
989            .unwrap_or(TextDirection::Ltr);
990        let end = match text_direction {
991            TextDirection::Ltr => {
992                let view_left_to_screen_right = screen_size.width() - anchor_rect.left;
993                let view_top_to_screen_bottom = screen_size.height() - anchor_rect.top;
994
995                // Make sure the search view doesn't go off the screen. If the search view
996                // doesn't fit, move the top-left corner of the view to fit the window.
997                // If the window is smaller than the view, then we resize the view to fit the
998                // window.
999                let mut top_left = anchor_rect.top_left();
1000                if view_left_to_screen_right < view_width {
1001                    top_left = Offset::new(
1002                        screen_size.width() - view_width.min(screen_size.width()),
1003                        top_left.dy(),
1004                    );
1005                }
1006                if view_top_to_screen_bottom < view_height {
1007                    top_left = Offset::new(
1008                        top_left.dx(),
1009                        screen_size.height() - view_height.min(screen_size.height()),
1010                    );
1011                }
1012                let end_size = Size::new(view_width, view_height);
1013                if show_full_screen_view {
1014                    Rect::from_ltwh(0.0, 0.0, screen_size.width(), screen_size.height())
1015                } else {
1016                    Rect::from_ltwh(
1017                        top_left.dx(),
1018                        top_left.dy(),
1019                        end_size.width(),
1020                        end_size.height(),
1021                    )
1022                }
1023            }
1024            TextDirection::Rtl => {
1025                let view_right_to_screen_left = anchor_rect.right;
1026                let view_top_to_screen_bottom = screen_size.height() - anchor_rect.top;
1027
1028                // Make sure the search view doesn't go off the screen.
1029                let mut top_left =
1030                    Offset::new((anchor_rect.right - view_width).max(0.0), anchor_rect.top);
1031                if view_right_to_screen_left < view_width {
1032                    top_left = Offset::new(0.0, top_left.dy());
1033                }
1034                if view_top_to_screen_bottom < view_height {
1035                    top_left = Offset::new(
1036                        top_left.dx(),
1037                        screen_size.height() - view_height.min(screen_size.height()),
1038                    );
1039                }
1040                let end_size = Size::new(view_width, view_height);
1041                if show_full_screen_view {
1042                    Rect::from_ltwh(0.0, 0.0, screen_size.width(), screen_size.height())
1043                } else {
1044                    Rect::from_ltwh(
1045                        top_left.dx(),
1046                        top_left.dy(),
1047                        end_size.width(),
1048                        end_size.height(),
1049                    )
1050                }
1051            }
1052        };
1053        let rect_tween = app.get(self).rect_tween.clone();
1054        app.get_mut(&rect_tween).end = Some(end);
1055    }
1056}
1057
1058impl Route for SearchViewRoute {
1059    waft_widgets::route_accessors!();
1060
1061    fn as_transition_route(self: Handle<Self>) -> Option<waft_widgets::AnyTransitionRoute> {
1062        Some(TransitionRoute::as_transition_route(self))
1063    }
1064
1065    fn as_modal_route(self: Handle<Self>) -> Option<waft_widgets::AnyModalRoute> {
1066        Some(ModalRoute::as_modal_route(self))
1067    }
1068
1069    fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<waft_widgets::OverlayEntry>> {
1070        OverlayRoute::overlay_entries(self, app)
1071    }
1072
1073    fn install(self: Handle<Self>, app: &mut App) {
1074        ModalRoute::install(self, app)
1075    }
1076
1077    fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
1078        let anchor_key = app.get(self).arguments.anchor_key.clone();
1079        let context = anchor_key
1080            .current_context(app)
1081            .expect("the anchor is mounted");
1082        self.update_view_config(app, context);
1083        self.update_tweens(app, context);
1084        if let Some(toggle_visibility) = app.get(self).arguments.toggle_visibility.clone() {
1085            toggle_visibility(app);
1086        }
1087        if let Some(view_on_open) = app.get(self).arguments.view_on_open.clone() {
1088            view_on_open.call(app);
1089        }
1090        ModalRoute::did_push(self, app)
1091    }
1092
1093    fn did_add(self: Handle<Self>, app: &mut App) {
1094        ModalRoute::did_add(self, app)
1095    }
1096
1097    fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<AnyRoute>) {
1098        TransitionRoute::did_replace(self, app, old_route)
1099    }
1100
1101    fn will_pop(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
1102        LocalHistoryRoute::will_pop(self, app)
1103    }
1104
1105    fn pop_disposition(self: Handle<Self>, app: &mut App) -> waft_widgets::RoutePopDisposition {
1106        ModalRoute::pop_disposition(self, app)
1107    }
1108
1109    fn on_pop_invoked_with_result(
1110        self: Handle<Self>,
1111        app: &mut App,
1112        did_pop: bool,
1113        result: RouteResult,
1114    ) {
1115        ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
1116    }
1117
1118    fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
1119        LocalHistoryRoute::will_handle_pop_internally(self, app)
1120    }
1121
1122    fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
1123        let anchor_key = app.get(self).arguments.anchor_key.clone();
1124        let context = anchor_key
1125            .current_context(app)
1126            .expect("the anchor is mounted");
1127        self.update_tweens(app, context);
1128        if let Some(toggle_visibility) = app.get(self).arguments.toggle_visibility.clone() {
1129            toggle_visibility(app);
1130        }
1131        if let Some(view_on_close) = app.get(self).arguments.view_on_close.clone() {
1132            view_on_close.call(app);
1133        }
1134        // Unfocus the anchor to prevent the Enter key from triggering unwanted
1135        // actions (like route pops) when the view closes and focus returns to
1136        // the anchor's search bar.
1137        SchedulerBinding::add_post_frame_callback(
1138            app,
1139            FrameCallback::new(move |app, _| {
1140                if let Some(context) = anchor_key.current_context(app) {
1141                    FocusScope::of(app, context, false).unfocus(app, UnfocusDisposition::Scope);
1142                }
1143            }),
1144            None,
1145        );
1146        LocalHistoryRoute::did_pop(self, app, result)
1147    }
1148
1149    fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
1150        ModalRoute::did_pop_next(self, app, next_route)
1151    }
1152
1153    fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
1154        ModalRoute::did_change_next(self, app, next_route)
1155    }
1156
1157    fn did_change_previous(self: Handle<Self>, app: &mut App, previous_route: Option<AnyRoute>) {
1158        ModalRoute::did_change_previous(self, app, previous_route)
1159    }
1160
1161    fn changed_internal_state(self: Handle<Self>, app: &mut App) {
1162        ModalRoute::changed_internal_state(self, app)
1163    }
1164
1165    fn changed_external_state(self: Handle<Self>, app: &mut App) {
1166        ModalRoute::changed_external_state(self, app)
1167    }
1168
1169    fn dispose(self: Handle<Self>, app: &mut App) {
1170        if let Some(curved_animation) = app.get(self).curved_animation.handle() {
1171            curved_animation.dispose(app);
1172        }
1173        if let Some(curve) = app.get(self).view_fade_on_interval_curve.handle() {
1174            curve.dispose(app);
1175        }
1176        if app.get(self).will_dispose_search_controller {
1177            let search_controller = app.get(self).arguments.search_controller.handle();
1178            ChangeNotifierData::dispose(app, search_controller);
1179        }
1180        TransitionRoute::dispose(self, app)
1181    }
1182}
1183
1184impl OverlayRoute for SearchViewRoute {
1185    waft_widgets::modal_overlay_route_overrides!();
1186}
1187
1188impl PredictiveBackRoute for SearchViewRoute {
1189    waft_widgets::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
1190}
1191
1192impl TransitionRoute for SearchViewRoute {
1193    waft_widgets::modal_transition_route_overrides!();
1194
1195    fn opaque(self: Handle<Self>, app: &App) -> bool {
1196        PopupRoute::opaque(self, app)
1197    }
1198
1199    fn transition_duration(self: Handle<Self>, _app: &mut App) -> Duration {
1200        K_OPEN_VIEW_DURATION
1201    }
1202}
1203
1204impl LocalHistoryRoute for SearchViewRoute {
1205    waft_widgets::local_history_route_accessors!();
1206}
1207
1208impl ModalRoute for SearchViewRoute {
1209    waft_widgets::modal_route_accessors!();
1210
1211    fn barrier_color(self: Handle<Self>, _app: &App) -> Option<Color> {
1212        Some(Colors::TRANSPARENT)
1213    }
1214
1215    fn barrier_dismissible(self: Handle<Self>, _app: &App) -> bool {
1216        true
1217    }
1218
1219    fn barrier_label(self: Handle<Self>, _app: &App) -> Option<String> {
1220        Some("Dismiss".to_string())
1221    }
1222
1223    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
1224        PopupRoute::maintain_state(self, app)
1225    }
1226
1227    fn build_page(
1228        self: Handle<Self>,
1229        app: &mut App,
1230        context: BuildContext,
1231        animation: AnimationRef<f64>,
1232        secondary_animation: AnimationRef<f64>,
1233    ) -> WidgetRef {
1234        let _ = (context, secondary_animation);
1235        let text_direction = app
1236            .get(self)
1237            .arguments
1238            .text_direction
1239            .unwrap_or(TextDirection::Ltr);
1240        let listenable = animation.clone();
1241        Directionality::new(
1242            text_direction,
1243            AnimatedBuilder::new(Rc::new(listenable), move |app, context, _child| {
1244                if app.get(self).curved_animation.is_none() {
1245                    let curve = Curves::ease_in_out_cubic_emphasized();
1246                    let curved = CurvedAnimation::new(
1247                        app,
1248                        animation.clone(),
1249                        Rc::clone(&curve),
1250                        Some(Rc::new(curve.flipped())),
1251                    );
1252                    app.get_mut(self).curved_animation = Some(curved);
1253                }
1254                let curved_animation = app
1255                    .get(self)
1256                    .curved_animation
1257                    .as_ref()
1258                    .expect("created above")
1259                    .clone();
1260                let rect_tween = app.get(self).rect_tween.clone();
1261                let view_rect = rect_tween
1262                    .handle()
1263                    .lerp(app, curved_animation.handle().value(app))
1264                    .expect("both ends of the tween are set");
1265                let show_full_screen_view = app.get(self).arguments.show_full_screen_view;
1266                let top_padding = if show_full_screen_view {
1267                    lerp_double(
1268                        Some(0.0),
1269                        Some(MediaQuery::padding_of(app, context).top),
1270                        curved_animation.handle().value(app),
1271                    )
1272                    .expect("both ends are given")
1273                } else {
1274                    0.0
1275                };
1276
1277                if app.get(self).view_fade_on_interval_curve.is_none() {
1278                    let curve = k_view_fade_on_interval();
1279                    let curved = CurvedAnimation::new(
1280                        app,
1281                        animation.clone(),
1282                        Rc::clone(&curve),
1283                        Some(Rc::new(curve.flipped())),
1284                    );
1285                    app.get_mut(self).view_fade_on_interval_curve = Some(curved);
1286                }
1287                let fade = app
1288                    .get(self)
1289                    .view_fade_on_interval_curve
1290                    .as_ref()
1291                    .expect("created above")
1292                    .erase();
1293                let view_max_width = app
1294                    .get(&rect_tween)
1295                    .end
1296                    .expect("both ends of the tween are set")
1297                    .width();
1298                let arguments = &app.get(self).arguments;
1299                let content = ViewContent {
1300                    key: None,
1301                    view_on_changed: arguments.view_on_changed.clone(),
1302                    view_on_submitted: arguments.view_on_submitted.clone(),
1303                    view_builder: arguments.view_builder.clone(),
1304                    view_leading: arguments.view_leading.clone(),
1305                    view_trailing: arguments.view_trailing.clone(),
1306                    view_hint_text: arguments.view_hint_text.clone(),
1307                    view_background_color: arguments.view_background_color,
1308                    view_elevation: arguments.view_elevation,
1309                    view_surface_tint_color: arguments.view_surface_tint_color,
1310                    view_side: arguments.view_side.clone(),
1311                    view_shape: arguments.view_shape.clone(),
1312                    view_bar_padding: arguments.view_bar_padding,
1313                    view_header_height: arguments.view_header_height,
1314                    view_header_text_style: arguments.view_header_text_style.clone(),
1315                    view_header_hint_style: arguments.view_header_hint_style.clone(),
1316                    divider_color: arguments.divider_color,
1317                    view_constraints: arguments.view_constraints,
1318                    view_padding: arguments.view_padding,
1319                    shrink_wrap: arguments.shrink_wrap,
1320                    text_capitalization: arguments.text_capitalization,
1321                    show_full_screen_view: arguments.show_full_screen_view,
1322                    top_padding,
1323                    animation: curved_animation.erase(),
1324                    view_max_width,
1325                    view_rect,
1326                    search_controller: arguments.search_controller.clone(),
1327                    suggestions_builder: Rc::clone(&arguments.suggestions_builder),
1328                    text_input_action: arguments.text_input_action,
1329                    keyboard_type: arguments.keyboard_type,
1330                    smart_dashes_type: arguments.smart_dashes_type,
1331                    smart_quotes_type: arguments.smart_quotes_type,
1332                };
1333                let captured_themes = arguments.captured_themes.clone();
1334                FadeTransition::new(fade)
1335                    .child(captured_themes.wrap(content.into_widget()))
1336                    .into_widget()
1337            }),
1338        )
1339        .into_widget()
1340    }
1341}
1342
1343impl PopupRoute for SearchViewRoute {}
1344
1345/// Dart's `_ViewContent`.
1346#[derive(Clone)]
1347pub(crate) struct ViewContent {
1348    key: Option<KeyRef>,
1349    view_on_changed: Option<ValueChanged<String>>,
1350    view_on_submitted: Option<ValueChanged<String>>,
1351    view_builder: Option<ViewBuilder>,
1352    view_leading: Option<WidgetRef>,
1353    view_trailing: Option<Vec<WidgetRef>>,
1354    view_hint_text: Option<String>,
1355    view_background_color: Option<Color>,
1356    view_elevation: Option<f64>,
1357    view_surface_tint_color: Option<Color>,
1358    view_side: Option<AnyBorderSide>,
1359    view_shape: Option<OutlinedBorderRef>,
1360    view_bar_padding: Option<EdgeInsetsGeometry>,
1361    view_header_height: Option<f64>,
1362    view_header_text_style: Option<TextStyle>,
1363    view_header_hint_style: Option<TextStyle>,
1364    divider_color: Option<Color>,
1365    view_constraints: Option<BoxConstraints>,
1366    view_padding: Option<EdgeInsetsGeometry>,
1367    shrink_wrap: Option<bool>,
1368    text_capitalization: Option<TextCapitalization>,
1369    show_full_screen_view: bool,
1370    top_padding: f64,
1371    animation: AnimationRef<f64>,
1372    view_max_width: f64,
1373    view_rect: Rect,
1374    search_controller: Ref<SearchController>,
1375    suggestions_builder: SuggestionsBuilder,
1376    text_input_action: Option<TextInputAction>,
1377    keyboard_type: Option<TextInputType>,
1378    smart_dashes_type: Option<SmartDashesType>,
1379    smart_quotes_type: Option<SmartQuotesType>,
1380}
1381
1382impl Debug for ViewContent {
1383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1384        f.debug_struct("_ViewContent")
1385            .field("show_full_screen_view", &self.show_full_screen_view)
1386            .field("view_rect", &self.view_rect)
1387            .finish_non_exhaustive()
1388    }
1389}
1390
1391impl StatefulWidget for ViewContent {
1392    type State = ViewContentState;
1393
1394    fn key(&self) -> Option<&KeyRef> {
1395        self.key.as_ref()
1396    }
1397
1398    fn create_state(&self) -> ViewContentState {
1399        ViewContentState {
1400            state: StateData::new(),
1401            screen_size: None,
1402            view_rect: self.view_rect,
1403            view_icons_fade_curve: None,
1404            view_divider_fade_curve: None,
1405            view_list_fade_on_interval_curve: None,
1406            result: Vec::new(),
1407            search_value: None,
1408            timer: None,
1409            suggestions_call_id: 0,
1410        }
1411    }
1412}
1413
1414/// Dart's `_ViewContentState`.
1415pub(crate) struct ViewContentState {
1416    state: StateData<ViewContent>,
1417    screen_size: Option<Size>,
1418    view_rect: Rect,
1419    /// Dart's `late CurvedAnimation`s, created in `init_state` because arena objects need the
1420    /// [`App`].
1421    view_icons_fade_curve: Option<Ref<CurvedAnimation>>,
1422    view_divider_fade_curve: Option<Ref<CurvedAnimation>>,
1423    view_list_fade_on_interval_curve: Option<Ref<CurvedAnimation>>,
1424    result: Vec<WidgetRef>,
1425    search_value: Option<String>,
1426    timer: Option<Timer>,
1427    /// Identifies the latest call so that older async results cannot replace newer ones.
1428    suggestions_call_id: i32,
1429}
1430
1431impl ViewContentState {
1432    fn setup_animations(self: Handle<Self>, app: &mut App) {
1433        let animation = self.widget(app).animation.clone();
1434        let icons = CurvedAnimation::new(
1435            app,
1436            animation.clone(),
1437            k_view_icons_fade_on_interval(),
1438            Some(Rc::new(k_view_icons_fade_on_interval().flipped())),
1439        );
1440        let divider = CurvedAnimation::new(
1441            app,
1442            animation.clone(),
1443            k_view_divider_fade_on_interval(),
1444            Some(Rc::new(k_view_fade_on_interval().flipped())),
1445        );
1446        let list = CurvedAnimation::new(
1447            app,
1448            animation,
1449            k_view_list_fade_on_interval(),
1450            Some(Rc::new(k_view_list_fade_on_interval().flipped())),
1451        );
1452        let state = app.get_mut(self);
1453        state.view_icons_fade_curve = Some(icons);
1454        state.view_divider_fade_curve = Some(divider);
1455        state.view_list_fade_on_interval_curve = Some(list);
1456    }
1457
1458    fn dispose_animations(self: Handle<Self>, app: &mut App) {
1459        for curve in [
1460            app.get(self).view_icons_fade_curve.clone(),
1461            app.get(self).view_divider_fade_curve.clone(),
1462            app.get(self).view_list_fade_on_interval_curve.clone(),
1463        ]
1464        .into_iter()
1465        .flatten()
1466        {
1467            curve.handle().dispose(app);
1468        }
1469    }
1470
1471    fn controller(self: Handle<Self>, app: &App) -> Handle<SearchController> {
1472        self.widget(app).search_controller.handle()
1473    }
1474
1475    /// Dart's `updateSuggestions`.
1476    fn update_suggestions(self: Handle<Self>, app: &mut App) {
1477        let controller = self.controller(app);
1478        let text = controller.text_value(app).to_string();
1479        if app.get(self).search_value.as_deref() != Some(text.as_str()) {
1480            app.get_mut(self).search_value = Some(text);
1481            drop(self.build_suggestions(app));
1482        }
1483    }
1484
1485    /// Dart's `_buildSuggestions`.
1486    fn build_suggestions(self: Handle<Self>, app: &mut App) -> Task<()> {
1487        let call_id = {
1488            let state = app.get_mut(self);
1489            state.suggestions_call_id += 1;
1490            state.suggestions_call_id
1491        };
1492        let context = self.context(app);
1493        let controller = self.controller(app);
1494        let suggestions_builder = Rc::clone(&self.widget(app).suggestions_builder);
1495        let suggestions = suggestions_builder(app, context, controller);
1496        app.spawn(async move |cx| {
1497            let suggestions = suggestions.await;
1498            cx.update(|app| {
1499                if !self.mounted(app) || call_id != app.get(self).suggestions_call_id {
1500                    return;
1501                }
1502                self.set_state(app, |state| {
1503                    state.result = suggestions;
1504                });
1505            });
1506        })
1507    }
1508
1509    /// The body of the timer `did_change_dependencies` starts: Dart's closure, which clears the
1510    /// timer once the suggestions are built.
1511    fn run_suggestions_timer(self: Handle<Self>, app: &mut App) {
1512        let controller = self.controller(app);
1513        app.get_mut(self).search_value = Some(controller.text_value(app).to_string());
1514        let built = self.build_suggestions(app);
1515        drop(app.spawn(async move |cx| {
1516            built.await;
1517            cx.update(|app| {
1518                // `dispose` has cancelled and cleared the timer of a state no longer mounted.
1519                if !self.mounted(app) {
1520                    return;
1521                }
1522                if let Some(timer) = app.get_mut(self).timer.take() {
1523                    timer.cancel(app);
1524                }
1525            });
1526        }));
1527    }
1528}
1529
1530impl State for ViewContentState {
1531    type Widget = ViewContent;
1532    waft_widgets::state_accessors!();
1533
1534    fn init_state(self: Handle<Self>, app: &mut App) {
1535        let view_rect = self.widget(app).view_rect;
1536        app.get_mut(self).view_rect = view_rect;
1537        let controller = self.controller(app);
1538        controller.add_listener(
1539            app,
1540            Listener::handle_method(self, ViewContentState::update_suggestions),
1541        );
1542        self.setup_animations(app);
1543    }
1544
1545    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ViewContent) {
1546        let view_rect = self.widget(app).view_rect;
1547        if view_rect != old_widget.view_rect {
1548            self.set_state(app, |state| {
1549                state.view_rect = view_rect;
1550            });
1551        }
1552    }
1553
1554    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1555        let context = self.context(app);
1556        let updated_screen_size = MediaQuery::of(app, context).size;
1557
1558        if app.get(self).screen_size != Some(updated_screen_size) {
1559            app.get_mut(self).screen_size = Some(updated_screen_size);
1560            if self.widget(app).show_full_screen_view {
1561                app.get_mut(self).view_rect = Rect::from_ltwh(
1562                    0.0,
1563                    0.0,
1564                    updated_screen_size.width(),
1565                    updated_screen_size.height(),
1566                );
1567            }
1568        }
1569
1570        let controller = self.controller(app);
1571        if app.get(self).search_value.as_deref() != Some(controller.text_value(app)) {
1572            if let Some(timer) = app.get_mut(self).timer.take() {
1573                timer.cancel(app);
1574            }
1575            let timer = Timer::new(
1576                app,
1577                Duration::ZERO,
1578                Listener::handle_method(self, ViewContentState::run_suggestions_timer),
1579            );
1580            app.get_mut(self).timer = Some(timer);
1581        }
1582    }
1583
1584    fn dispose(self: Handle<Self>, app: &mut App) {
1585        let controller = self.controller(app);
1586        controller.remove_listener(
1587            app,
1588            &Listener::handle_method(self, ViewContentState::update_suggestions),
1589        );
1590        self.dispose_animations(app);
1591        if let Some(timer) = app.get_mut(self).timer.take() {
1592            timer.cancel(app);
1593        }
1594    }
1595
1596    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1597        let widget = self.widget(app).clone();
1598        let controller = self.controller(app);
1599        let default_leading = BackButton::new()
1600            .style(ButtonStyle::new().tap_target_size(MaterialTapTargetSize::ShrinkWrap))
1601            .on_pressed(Listener::new(move |app: &mut App| {
1602                Navigator::pop(app, context, None);
1603            }))
1604            .into_widget();
1605
1606        let mut default_trailing = Vec::new();
1607        if !controller.text_value(app).is_empty() {
1608            default_trailing.push(
1609                IconButton::new(
1610                    Some(Listener::new(move |app: &mut App| {
1611                        controller.clear(app);
1612                    })),
1613                    Icon::new(Some(Icons::close())),
1614                )
1615                .tooltip(<dyn MaterialLocalizations>::of(app, context).clear_button_tooltip())
1616                .into_widget(),
1617            );
1618        }
1619
1620        let view_defaults = SearchViewDefaultsM3::new(context, widget.show_full_screen_view);
1621        let view_theme = SearchViewTheme::of(app, context);
1622        let divider_theme = DividerTheme::of(app, context);
1623
1624        let effective_background_color = widget
1625            .view_background_color
1626            .or(view_theme.background_color)
1627            .or_else(|| view_defaults.background_color(app))
1628            .expect("viewDefaults.backgroundColor!");
1629        let effective_surface_tint = widget
1630            .view_surface_tint_color
1631            .or(view_theme.surface_tint_color)
1632            .or_else(|| view_defaults.surface_tint_color(app))
1633            .expect("viewDefaults.surfaceTintColor!");
1634        let effective_elevation = widget
1635            .view_elevation
1636            .or(view_theme.elevation)
1637            .or_else(|| view_defaults.elevation(app))
1638            .expect("viewDefaults.elevation!");
1639        let effective_side = widget
1640            .view_side
1641            .clone()
1642            .or_else(|| view_theme.side.clone())
1643            .or_else(|| view_defaults.side(app));
1644        let mut effective_shape = widget
1645            .view_shape
1646            .clone()
1647            .or_else(|| view_theme.shape.clone())
1648            .or_else(|| view_defaults.shape(app))
1649            .expect("viewDefaults.shape!");
1650        if let Some(effective_side) = &effective_side {
1651            effective_shape = effective_shape.copy_with(Some(**effective_side));
1652        }
1653        let effective_divider_color = widget
1654            .divider_color
1655            .or(view_theme.divider_color)
1656            .or(divider_theme.color)
1657            .or_else(|| view_defaults.divider_color(app))
1658            .expect("viewDefaults.dividerColor!");
1659        let effective_header_height = widget.view_header_height.or(view_theme.header_height);
1660        let header_constraints =
1661            effective_header_height.map(|height| BoxConstraints::tight_for(None, Some(height)));
1662        let effective_text_style = widget
1663            .view_header_text_style
1664            .clone()
1665            .or_else(|| view_theme.header_text_style.clone())
1666            .or_else(|| view_defaults.header_text_style(app));
1667        let effective_hint_style = widget
1668            .view_header_hint_style
1669            .clone()
1670            .or_else(|| view_theme.header_hint_style.clone())
1671            .or_else(|| widget.view_header_text_style.clone())
1672            .or_else(|| view_theme.header_text_style.clone())
1673            .or_else(|| view_defaults.header_hint_style(app));
1674        let effective_padding = widget
1675            .view_padding
1676            .or(view_theme.padding)
1677            .or_else(|| view_defaults.padding(app));
1678        let effective_bar_padding = widget
1679            .view_bar_padding
1680            .or(view_theme.bar_padding)
1681            .or_else(|| view_defaults.bar_padding(app));
1682
1683        let effective_constraints = widget
1684            .view_constraints
1685            .or(view_theme.constraints)
1686            .or_else(|| view_defaults.constraints(app))
1687            .expect("viewDefaults.constraints!");
1688        let view_rect = app.get(self).view_rect;
1689        let min_width = effective_constraints.min_width.min(view_rect.width());
1690        let min_height = effective_constraints.min_height.min(view_rect.height());
1691
1692        let effective_shrink_wrap = widget
1693            .shrink_wrap
1694            .or(view_theme.shrink_wrap)
1695            .or_else(|| view_defaults.shrink_wrap(app))
1696            .expect("viewDefaults.shrinkWrap!");
1697
1698        let view_divider = DividerTheme::new(
1699            divider_theme.copy_with().color(effective_divider_color),
1700            Divider::new().height(1.0),
1701        )
1702        .into_widget();
1703
1704        let view_icons_fade_curve: AnimationRef<f64> = app
1705            .get(self)
1706            .view_icons_fade_curve
1707            .as_ref()
1708            .expect("created in init_state")
1709            .erase();
1710        let view_divider_fade_curve: AnimationRef<f64> = app
1711            .get(self)
1712            .view_divider_fade_curve
1713            .as_ref()
1714            .expect("created in init_state")
1715            .erase();
1716        let view_list_fade_on_interval_curve: AnimationRef<f64> = app
1717            .get(self)
1718            .view_list_fade_on_interval_curve
1719            .as_ref()
1720            .expect("created in init_state")
1721            .erase();
1722        let result = app.get(self).result.clone();
1723        let show_full_screen_view = widget.show_full_screen_view;
1724
1725        LayoutBuilder::new(move |app, context, constraints| {
1726            let view_icons_fade_curve = view_icons_fade_curve.clone();
1727            let mut search_bar = SearchBar::new()
1728                .auto_focus(true)
1729                .padding(Rc::new(WidgetStatePropertyAll::new(effective_bar_padding)))
1730                .leading(
1731                    widget
1732                        .view_leading
1733                        .clone()
1734                        .unwrap_or_else(|| default_leading.clone()),
1735                )
1736                .trailing(
1737                    widget
1738                        .view_trailing
1739                        .clone()
1740                        .unwrap_or_else(|| default_trailing.clone()),
1741                )
1742                .background_color(Rc::new(WidgetStatePropertyAll::new(Some(
1743                    Colors::TRANSPARENT,
1744                ))))
1745                .overlay_color(Rc::new(WidgetStatePropertyAll::new(Some(
1746                    Colors::TRANSPARENT,
1747                ))))
1748                .elevation(Rc::new(WidgetStatePropertyAll::new(Some(0.0))))
1749                .text_style(Rc::new(WidgetStatePropertyAll::new(
1750                    effective_text_style.clone(),
1751                )))
1752                .hint_style(Rc::new(WidgetStatePropertyAll::new(
1753                    effective_hint_style.clone(),
1754                )))
1755                .controller(controller.as_controller().keep(app))
1756                .on_changed({
1757                    let view_on_changed = widget.view_on_changed.clone();
1758                    move |app, value| {
1759                        if let Some(view_on_changed) = &view_on_changed {
1760                            view_on_changed(app, value);
1761                        }
1762                        self.update_suggestions(app);
1763                    }
1764                });
1765            search_bar.constraints = header_constraints.or(if show_full_screen_view {
1766                Some(BoxConstraints {
1767                    min_height: SearchViewDefaultsM3::FULL_SCREEN_BAR_HEIGHT,
1768                    ..BoxConstraints::new()
1769                })
1770            } else {
1771                None
1772            });
1773            search_bar.hint_text = widget.view_hint_text.clone();
1774            search_bar.on_submitted = widget.view_on_submitted.clone();
1775            search_bar.text_capitalization = widget.text_capitalization;
1776            search_bar.text_input_action = widget.text_input_action;
1777            search_bar.keyboard_type = widget.keyboard_type;
1778            search_bar.smart_dashes_type = widget.smart_dashes_type;
1779            search_bar.smart_quotes_type = widget.smart_quotes_type;
1780            let header_bar = SafeArea::new(search_bar).top(false).bottom(false);
1781
1782            let mut children = vec![
1783                Padding::new(EdgeInsetsGeometry::from(EdgeInsets::only(
1784                    0.0,
1785                    widget.top_padding,
1786                    0.0,
1787                    0.0,
1788                )))
1789                .child(header_bar)
1790                .into_widget(),
1791            ];
1792            if !effective_shrink_wrap
1793                || min_height > 0.0
1794                || show_full_screen_view
1795                || !result.is_empty()
1796            {
1797                children.push(
1798                    FadeTransition::new(view_divider_fade_curve.clone())
1799                        .child(view_divider.clone())
1800                        .into_widget(),
1801                );
1802                let view_insets_bottom = MediaQuery::view_insets_of(app, context).bottom;
1803                let list = match &widget.view_builder {
1804                    None => MediaQuery::remove_padding(
1805                        app,
1806                        context,
1807                        false,
1808                        true,
1809                        false,
1810                        false,
1811                        ListView::new()
1812                            .padding(EdgeInsetsGeometry::from(EdgeInsets::only(
1813                                0.0,
1814                                0.0,
1815                                0.0,
1816                                view_insets_bottom,
1817                            )))
1818                            .shrink_wrap(effective_shrink_wrap)
1819                            .children(result.clone()),
1820                    )
1821                    .into_widget(),
1822                    Some(view_builder) => view_builder(app, result.clone()),
1823                };
1824                children.push(
1825                    Flexible::new(
1826                        FadeTransition::new(view_list_fade_on_interval_curve.clone()).child(list),
1827                    )
1828                    .fit(if effective_shrink_wrap && !show_full_screen_view {
1829                        FlexFit::Loose
1830                    } else {
1831                        FlexFit::Tight
1832                    })
1833                    .into_widget(),
1834                );
1835            }
1836
1837            Align::new()
1838                .alignment(AlignmentGeometry::TOP_LEFT)
1839                .child(
1840                    Transform::translate(view_rect.top_left()).child(
1841                        ConstrainedBox::new(BoxConstraints {
1842                            min_width,
1843                            max_width: if show_full_screen_view {
1844                                constraints.max_width.max(min_width)
1845                            } else {
1846                                view_rect.width()
1847                            },
1848                            min_height,
1849                            max_height: if show_full_screen_view {
1850                                constraints.max_height.max(min_height)
1851                            } else {
1852                                view_rect.height()
1853                            },
1854                        })
1855                        .child(
1856                            Padding::new(if show_full_screen_view {
1857                                EdgeInsetsGeometry::from(EdgeInsets::ZERO)
1858                            } else {
1859                                effective_padding
1860                                    .unwrap_or(EdgeInsetsGeometry::from(EdgeInsets::ZERO))
1861                            })
1862                            .child(
1863                                Material::new()
1864                                    .clip_behavior(Clip::AntiAlias)
1865                                    .shape(effective_shape.clone())
1866                                    .color(effective_background_color)
1867                                    .surface_tint_color(effective_surface_tint)
1868                                    .elevation(effective_elevation)
1869                                    .child(
1870                                        OverflowBox::new()
1871                                            .alignment(AlignmentGeometry::TOP_LEFT)
1872                                            .max_width(if show_full_screen_view {
1873                                                constraints.max_width
1874                                            } else {
1875                                                widget.view_max_width.min(constraints.max_width)
1876                                            })
1877                                            .min_width(0.0)
1878                                            .fit(OverflowBoxFit::DeferToChild)
1879                                            .child(
1880                                                FadeTransition::new(view_icons_fade_curve).child(
1881                                                    Column::new()
1882                                                        .main_axis_size(MainAxisSize::Min)
1883                                                        .cross_axis_alignment(
1884                                                            CrossAxisAlignment::Stretch,
1885                                                        )
1886                                                        .children(children),
1887                                                ),
1888                                            ),
1889                                    ),
1890                            ),
1891                        ),
1892                    ),
1893                )
1894                .into_widget()
1895        })
1896        .into_widget()
1897    }
1898}
1899
1900/// Dart's `_SearchAnchorWithSearchBar`, the object `SearchAnchor.bar(..)` makes: a
1901/// [`SearchAnchor`] whose anchor is a [`SearchBar`] that opens the search view itself.
1902///
1903/// The setters are the named arguments of `SearchAnchor.bar`. [`into_widget`](IntoWidget)
1904/// builds the [`SearchAnchor`] (with `enable_tap_handling` false) the factory's `super(..)`
1905/// call makes, whose `builder` makes the [`SearchBar`].
1906pub struct SearchAnchorWithSearchBar {
1907    pub bar_leading: Option<WidgetRef>,
1908    pub bar_trailing: Option<Vec<WidgetRef>>,
1909    pub bar_hint_text: Option<String>,
1910    pub on_tap: Option<Listener>,
1911    pub bar_elevation: Option<WidgetStatePropertyRef<Option<f64>>>,
1912    pub bar_background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
1913    pub bar_overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
1914    pub bar_side: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
1915    pub bar_shape: Option<WidgetStatePropertyRef<Option<OutlinedBorderRef>>>,
1916    pub bar_padding: Option<WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>>,
1917    pub bar_text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
1918    pub bar_hint_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
1919    pub constraints: Option<BoxConstraints>,
1920    pub scroll_padding: EdgeInsets,
1921    pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
1922    pub bar_focus_node: Option<FocusNodeRef>,
1923    pub on_changed: Option<ValueChanged<String>>,
1924    pub on_submitted: Option<ValueChanged<String>>,
1925    pub on_close: Option<Listener>,
1926    pub on_open: Option<Listener>,
1927    pub view_hint_text: Option<String>,
1928    pub view_header_height: Option<f64>,
1929    pub view_header_text_style: Option<TextStyle>,
1930    pub view_header_hint_style: Option<TextStyle>,
1931    pub anchor: SearchAnchor,
1932}
1933
1934impl SearchAnchorWithSearchBar {
1935    fn new(
1936        suggestions_builder: impl Fn(
1937            &mut App,
1938            BuildContext,
1939            Handle<SearchController>,
1940        ) -> Task<Vec<WidgetRef>>
1941        + 'static,
1942    ) -> SearchAnchorWithSearchBar {
1943        SearchAnchorWithSearchBar {
1944            bar_leading: None,
1945            bar_trailing: None,
1946            bar_hint_text: None,
1947            on_tap: None,
1948            bar_elevation: None,
1949            bar_background_color: None,
1950            bar_overlay_color: None,
1951            bar_side: None,
1952            bar_shape: None,
1953            bar_padding: None,
1954            bar_text_style: None,
1955            bar_hint_style: None,
1956            constraints: None,
1957            scroll_padding: EdgeInsets::all(20.0),
1958            context_menu_builder: Some(Rc::new(SearchBar::default_context_menu_builder)),
1959            bar_focus_node: None,
1960            on_changed: None,
1961            on_submitted: None,
1962            on_close: None,
1963            on_open: None,
1964            view_hint_text: None,
1965            view_header_height: None,
1966            view_header_text_style: None,
1967            view_header_hint_style: None,
1968            anchor: SearchAnchor::new(
1969                |_app, _context, _controller| unreachable!("replaced in into_widget"),
1970                suggestions_builder,
1971            ),
1972        }
1973    }
1974
1975    /// Dart `SearchAnchor.bar(key:)`.
1976    pub fn key(mut self, key: KeyRef) -> SearchAnchorWithSearchBar {
1977        self.anchor.key = Some(key);
1978        self
1979    }
1980
1981    /// Dart `SearchAnchor.bar(barLeading:)`.
1982    #[cfg_attr(debug_assertions, track_caller)]
1983    pub fn bar_leading<K>(mut self, bar_leading: impl IntoWidget<K>) -> SearchAnchorWithSearchBar {
1984        self.bar_leading = Some(bar_leading.into_widget());
1985        self
1986    }
1987
1988    /// Dart `SearchAnchor.bar(barTrailing:)`.
1989    pub fn bar_trailing(mut self, bar_trailing: Vec<WidgetRef>) -> SearchAnchorWithSearchBar {
1990        self.bar_trailing = Some(bar_trailing);
1991        self
1992    }
1993
1994    /// Dart `SearchAnchor.bar(barHintText:)`.
1995    pub fn bar_hint_text(mut self, bar_hint_text: impl Into<String>) -> SearchAnchorWithSearchBar {
1996        self.bar_hint_text = Some(bar_hint_text.into());
1997        self
1998    }
1999
2000    /// Dart `SearchAnchor.bar(onTap:)`.
2001    pub fn on_tap(mut self, on_tap: Listener) -> SearchAnchorWithSearchBar {
2002        self.on_tap = Some(on_tap);
2003        self
2004    }
2005
2006    /// Dart `SearchAnchor.bar(onSubmitted:)`.
2007    pub fn on_submitted(
2008        mut self,
2009        on_submitted: impl Fn(&mut App, String) + 'static,
2010    ) -> SearchAnchorWithSearchBar {
2011        self.on_submitted = Some(Rc::new(on_submitted));
2012        self
2013    }
2014
2015    /// Dart `SearchAnchor.bar(onChanged:)`.
2016    pub fn on_changed(
2017        mut self,
2018        on_changed: impl Fn(&mut App, String) + 'static,
2019    ) -> SearchAnchorWithSearchBar {
2020        self.on_changed = Some(Rc::new(on_changed));
2021        self
2022    }
2023
2024    /// Dart `SearchAnchor.bar(onClose:)`.
2025    pub fn on_close(mut self, on_close: Listener) -> SearchAnchorWithSearchBar {
2026        self.on_close = Some(on_close);
2027        self
2028    }
2029
2030    /// Dart `SearchAnchor.bar(onOpen:)`.
2031    pub fn on_open(mut self, on_open: Listener) -> SearchAnchorWithSearchBar {
2032        self.on_open = Some(on_open);
2033        self
2034    }
2035
2036    /// Dart `SearchAnchor.bar(barElevation:)`.
2037    pub fn bar_elevation(
2038        mut self,
2039        bar_elevation: WidgetStatePropertyRef<Option<f64>>,
2040    ) -> SearchAnchorWithSearchBar {
2041        self.bar_elevation = Some(bar_elevation);
2042        self
2043    }
2044
2045    /// Dart `SearchAnchor.bar(barBackgroundColor:)`.
2046    pub fn bar_background_color(
2047        mut self,
2048        bar_background_color: WidgetStatePropertyRef<Option<Color>>,
2049    ) -> SearchAnchorWithSearchBar {
2050        self.bar_background_color = Some(bar_background_color);
2051        self
2052    }
2053
2054    /// Dart `SearchAnchor.bar(barOverlayColor:)`.
2055    pub fn bar_overlay_color(
2056        mut self,
2057        bar_overlay_color: WidgetStatePropertyRef<Option<Color>>,
2058    ) -> SearchAnchorWithSearchBar {
2059        self.bar_overlay_color = Some(bar_overlay_color);
2060        self
2061    }
2062
2063    /// Dart `SearchAnchor.bar(barSide:)`.
2064    pub fn bar_side(
2065        mut self,
2066        bar_side: WidgetStatePropertyRef<Option<BorderSide>>,
2067    ) -> SearchAnchorWithSearchBar {
2068        self.bar_side = Some(bar_side);
2069        self
2070    }
2071
2072    /// Dart `SearchAnchor.bar(barShape:)`.
2073    pub fn bar_shape(
2074        mut self,
2075        bar_shape: WidgetStatePropertyRef<Option<OutlinedBorderRef>>,
2076    ) -> SearchAnchorWithSearchBar {
2077        self.bar_shape = Some(bar_shape);
2078        self
2079    }
2080
2081    /// Dart `SearchAnchor.bar(barPadding:)`.
2082    pub fn bar_padding(
2083        mut self,
2084        bar_padding: WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>,
2085    ) -> SearchAnchorWithSearchBar {
2086        self.bar_padding = Some(bar_padding);
2087        self
2088    }
2089
2090    /// Dart `SearchAnchor.bar(viewBarPadding:)`.
2091    pub fn view_bar_padding(
2092        mut self,
2093        view_bar_padding: impl Into<EdgeInsetsGeometry>,
2094    ) -> SearchAnchorWithSearchBar {
2095        self.anchor.view_bar_padding = Some(view_bar_padding.into());
2096        self
2097    }
2098
2099    /// Dart `SearchAnchor.bar(barTextStyle:)`.
2100    pub fn bar_text_style(
2101        mut self,
2102        bar_text_style: WidgetStatePropertyRef<Option<TextStyle>>,
2103    ) -> SearchAnchorWithSearchBar {
2104        self.bar_text_style = Some(bar_text_style);
2105        self
2106    }
2107
2108    /// Dart `SearchAnchor.bar(barHintStyle:)`.
2109    pub fn bar_hint_style(
2110        mut self,
2111        bar_hint_style: WidgetStatePropertyRef<Option<TextStyle>>,
2112    ) -> SearchAnchorWithSearchBar {
2113        self.bar_hint_style = Some(bar_hint_style);
2114        self
2115    }
2116
2117    /// Dart `SearchAnchor.bar(viewBuilder:)`.
2118    pub fn view_builder(
2119        mut self,
2120        view_builder: impl Fn(&mut App, Vec<WidgetRef>) -> WidgetRef + 'static,
2121    ) -> SearchAnchorWithSearchBar {
2122        self.anchor.view_builder = Some(Rc::new(view_builder));
2123        self
2124    }
2125
2126    /// Dart `SearchAnchor.bar(viewLeading:)`.
2127    #[cfg_attr(debug_assertions, track_caller)]
2128    pub fn view_leading<K>(
2129        mut self,
2130        view_leading: impl IntoWidget<K>,
2131    ) -> SearchAnchorWithSearchBar {
2132        self.anchor.view_leading = Some(view_leading.into_widget());
2133        self
2134    }
2135
2136    /// Dart `SearchAnchor.bar(viewTrailing:)`.
2137    pub fn view_trailing(mut self, view_trailing: Vec<WidgetRef>) -> SearchAnchorWithSearchBar {
2138        self.anchor.view_trailing = Some(view_trailing);
2139        self
2140    }
2141
2142    /// Dart `SearchAnchor.bar(viewHintText:)`.
2143    pub fn view_hint_text(
2144        mut self,
2145        view_hint_text: impl Into<String>,
2146    ) -> SearchAnchorWithSearchBar {
2147        self.view_hint_text = Some(view_hint_text.into());
2148        self
2149    }
2150
2151    /// Dart `SearchAnchor.bar(viewBackgroundColor:)`.
2152    pub fn view_background_color(
2153        mut self,
2154        view_background_color: Color,
2155    ) -> SearchAnchorWithSearchBar {
2156        self.anchor.view_background_color = Some(view_background_color);
2157        self
2158    }
2159
2160    /// Dart `SearchAnchor.bar(viewElevation:)`.
2161    pub fn view_elevation(mut self, view_elevation: f64) -> SearchAnchorWithSearchBar {
2162        self.anchor.view_elevation = Some(view_elevation);
2163        self
2164    }
2165
2166    /// Dart `SearchAnchor.bar(viewSide:)`.
2167    pub fn view_side(mut self, view_side: impl Into<AnyBorderSide>) -> SearchAnchorWithSearchBar {
2168        self.anchor.view_side = Some(view_side.into());
2169        self
2170    }
2171
2172    /// Dart `SearchAnchor.bar(viewShape:)`.
2173    pub fn view_shape(
2174        mut self,
2175        view_shape: impl Into<OutlinedBorderRef>,
2176    ) -> SearchAnchorWithSearchBar {
2177        self.anchor.view_shape = Some(view_shape.into());
2178        self
2179    }
2180
2181    /// Dart `SearchAnchor.bar(viewHeaderHeight:)`.
2182    pub fn view_header_height(mut self, view_header_height: f64) -> SearchAnchorWithSearchBar {
2183        self.view_header_height = Some(view_header_height);
2184        self
2185    }
2186
2187    /// Dart `SearchAnchor.bar(viewHeaderTextStyle:)`.
2188    pub fn view_header_text_style(
2189        mut self,
2190        view_header_text_style: TextStyle,
2191    ) -> SearchAnchorWithSearchBar {
2192        self.view_header_text_style = Some(view_header_text_style);
2193        self
2194    }
2195
2196    /// Dart `SearchAnchor.bar(viewHeaderHintStyle:)`.
2197    pub fn view_header_hint_style(
2198        mut self,
2199        view_header_hint_style: TextStyle,
2200    ) -> SearchAnchorWithSearchBar {
2201        self.view_header_hint_style = Some(view_header_hint_style);
2202        self
2203    }
2204
2205    /// Dart `SearchAnchor.bar(dividerColor:)`.
2206    pub fn divider_color(mut self, divider_color: Color) -> SearchAnchorWithSearchBar {
2207        self.anchor.divider_color = Some(divider_color);
2208        self
2209    }
2210
2211    /// Dart `SearchAnchor.bar(constraints:)`.
2212    pub fn constraints(mut self, constraints: BoxConstraints) -> SearchAnchorWithSearchBar {
2213        self.constraints = Some(constraints);
2214        self
2215    }
2216
2217    /// Dart `SearchAnchor.bar(viewConstraints:)`.
2218    pub fn view_constraints(
2219        mut self,
2220        view_constraints: BoxConstraints,
2221    ) -> SearchAnchorWithSearchBar {
2222        self.anchor.view_constraints = Some(view_constraints);
2223        self
2224    }
2225
2226    /// Dart `SearchAnchor.bar(viewPadding:)`.
2227    pub fn view_padding(
2228        mut self,
2229        view_padding: impl Into<EdgeInsetsGeometry>,
2230    ) -> SearchAnchorWithSearchBar {
2231        self.anchor.view_padding = Some(view_padding.into());
2232        self
2233    }
2234
2235    /// Dart `SearchAnchor.bar(shrinkWrap:)`.
2236    pub fn shrink_wrap(mut self, shrink_wrap: bool) -> SearchAnchorWithSearchBar {
2237        self.anchor.shrink_wrap = Some(shrink_wrap);
2238        self
2239    }
2240
2241    /// Dart `SearchAnchor.bar(isFullScreen:)`.
2242    pub fn is_full_screen(mut self, is_full_screen: bool) -> SearchAnchorWithSearchBar {
2243        self.anchor.is_full_screen = Some(is_full_screen);
2244        self
2245    }
2246
2247    /// Dart `SearchAnchor.bar(searchController:)`.
2248    pub fn search_controller(
2249        mut self,
2250        search_controller: Ref<SearchController>,
2251    ) -> SearchAnchorWithSearchBar {
2252        self.anchor.search_controller = Some(search_controller);
2253        self
2254    }
2255
2256    /// Dart `SearchAnchor.bar(textCapitalization:)`.
2257    pub fn text_capitalization(
2258        mut self,
2259        text_capitalization: TextCapitalization,
2260    ) -> SearchAnchorWithSearchBar {
2261        self.anchor.text_capitalization = Some(text_capitalization);
2262        self
2263    }
2264
2265    /// Dart `SearchAnchor.bar(textInputAction:)`.
2266    pub fn text_input_action(
2267        mut self,
2268        text_input_action: TextInputAction,
2269    ) -> SearchAnchorWithSearchBar {
2270        self.anchor.text_input_action = Some(text_input_action);
2271        self
2272    }
2273
2274    /// Dart `SearchAnchor.bar(keyboardType:)`.
2275    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> SearchAnchorWithSearchBar {
2276        self.anchor.keyboard_type = Some(keyboard_type);
2277        self
2278    }
2279
2280    /// Dart `SearchAnchor.bar(scrollPadding:)`.
2281    pub fn scroll_padding(mut self, scroll_padding: EdgeInsets) -> SearchAnchorWithSearchBar {
2282        self.scroll_padding = scroll_padding;
2283        self
2284    }
2285
2286    /// Dart `SearchAnchor.bar(contextMenuBuilder:)`.
2287    pub fn context_menu_builder(
2288        mut self,
2289        context_menu_builder: EditableTextContextMenuBuilder,
2290    ) -> SearchAnchorWithSearchBar {
2291        self.context_menu_builder = Some(context_menu_builder);
2292        self
2293    }
2294
2295    /// Dart `SearchAnchor.bar(enabled:)`.
2296    pub fn enabled(mut self, enabled: bool) -> SearchAnchorWithSearchBar {
2297        self.anchor.enabled = enabled;
2298        self
2299    }
2300
2301    /// Dart `SearchAnchor.bar(smartDashesType:)`.
2302    pub fn smart_dashes_type(
2303        mut self,
2304        smart_dashes_type: SmartDashesType,
2305    ) -> SearchAnchorWithSearchBar {
2306        self.anchor.smart_dashes_type = Some(smart_dashes_type);
2307        self
2308    }
2309
2310    /// Dart `SearchAnchor.bar(smartQuotesType:)`.
2311    pub fn smart_quotes_type(
2312        mut self,
2313        smart_quotes_type: SmartQuotesType,
2314    ) -> SearchAnchorWithSearchBar {
2315        self.anchor.smart_quotes_type = Some(smart_quotes_type);
2316        self
2317    }
2318
2319    /// Dart `SearchAnchor.bar(barFocusNode:)`.
2320    pub fn bar_focus_node(mut self, bar_focus_node: FocusNodeRef) -> SearchAnchorWithSearchBar {
2321        self.bar_focus_node = Some(bar_focus_node);
2322        self
2323    }
2324
2325    /// The [`SearchAnchor`] the factory's `super(..)` call makes.
2326    #[cfg_attr(debug_assertions, track_caller)]
2327    pub fn into_search_anchor(self) -> SearchAnchor {
2328        let SearchAnchorWithSearchBar {
2329            bar_leading,
2330            bar_trailing,
2331            bar_hint_text,
2332            on_tap,
2333            bar_elevation,
2334            bar_background_color,
2335            bar_overlay_color,
2336            bar_side,
2337            bar_shape,
2338            bar_padding,
2339            bar_text_style,
2340            bar_hint_style,
2341            constraints,
2342            scroll_padding,
2343            context_menu_builder,
2344            bar_focus_node,
2345            on_changed,
2346            on_submitted,
2347            on_close,
2348            on_open,
2349            view_hint_text,
2350            view_header_height,
2351            view_header_text_style,
2352            view_header_hint_style,
2353            mut anchor,
2354        } = self;
2355        anchor.enable_tap_handling = false;
2356        anchor.view_hint_text = view_hint_text.or_else(|| bar_hint_text.clone());
2357        anchor.header_height = view_header_height;
2358        anchor.header_text_style = view_header_text_style;
2359        anchor.header_hint_style = view_header_hint_style;
2360        anchor.view_on_submitted = on_submitted.clone();
2361        anchor.view_on_changed = on_changed;
2362        anchor.view_on_close = on_close;
2363        anchor.view_on_open = on_open;
2364        let text_capitalization = anchor.text_capitalization;
2365        let text_input_action = anchor.text_input_action;
2366        let keyboard_type = anchor.keyboard_type;
2367        let smart_dashes_type = anchor.smart_dashes_type;
2368        let smart_quotes_type = anchor.smart_quotes_type;
2369        anchor.builder = Rc::new(move |app, context, controller| {
2370            let mut search_bar = SearchBar::new()
2371                .controller(controller.as_controller().keep(app))
2372                .on_tap(Listener::new({
2373                    let on_tap = on_tap.clone();
2374                    move |app: &mut App| {
2375                        controller.open_view(app);
2376                        if let Some(on_tap) = &on_tap {
2377                            on_tap.call(app);
2378                        }
2379                    }
2380                }))
2381                .on_changed(move |app, _value| {
2382                    controller.open_view(app);
2383                })
2384                .padding(
2385                    bar_padding
2386                        .clone()
2387                        .or_else(|| SearchBarTheme::of(app, context).padding)
2388                        .unwrap_or_else(|| {
2389                            Rc::new(WidgetStatePropertyAll::new(Some(EdgeInsetsGeometry::from(
2390                                EdgeInsets::symmetric(0.0, 16.0),
2391                            ))))
2392                        }),
2393                )
2394                .leading(
2395                    bar_leading
2396                        .clone()
2397                        .unwrap_or_else(|| Icon::new(Some(Icons::search())).into_widget()),
2398                )
2399                .scroll_padding(scroll_padding);
2400            search_bar.constraints = constraints;
2401            search_bar.focus_node = bar_focus_node.clone();
2402            search_bar.on_submitted = on_submitted.clone();
2403            search_bar.hint_text = bar_hint_text.clone();
2404            search_bar.hint_style = bar_hint_style.clone();
2405            search_bar.text_style = bar_text_style.clone();
2406            search_bar.elevation = bar_elevation.clone();
2407            search_bar.background_color = bar_background_color.clone();
2408            search_bar.overlay_color = bar_overlay_color.clone();
2409            search_bar.side = bar_side.clone();
2410            search_bar.shape = bar_shape.clone();
2411            search_bar.trailing = bar_trailing.clone();
2412            search_bar.text_capitalization = text_capitalization;
2413            search_bar.text_input_action = text_input_action;
2414            search_bar.keyboard_type = keyboard_type;
2415            search_bar.smart_dashes_type = smart_dashes_type;
2416            search_bar.smart_quotes_type = smart_quotes_type;
2417            search_bar.context_menu_builder = context_menu_builder.clone();
2418            search_bar.into_widget()
2419        });
2420        anchor
2421    }
2422}
2423
2424impl<K> IntoWidget<K> for SearchAnchorWithSearchBar {
2425    #[cfg_attr(debug_assertions, track_caller)]
2426    fn into_widget(self) -> WidgetRef {
2427        self.into_search_anchor().into_widget()
2428    }
2429}
2430
2431/// A controller to manage a search view created by [`SearchAnchor`].
2432///
2433/// A [`SearchController`] is used to control a menu after it has been created, with methods
2434/// such as [`open_view`](Self::open_view) and [`close_view`](Self::close_view). It can also
2435/// be used to read the text the user has typed, and to set that text, as any other
2436/// [`TextEditingControllerLeaf`].
2437pub struct SearchController {
2438    change_notifier: ChangeNotifierData,
2439    text_editing_controller: TextEditingControllerData,
2440    /// The anchor that this controller controls.
2441    ///
2442    /// This is set automatically when a [`SearchController`] is given to the anchor it
2443    /// controls.
2444    anchor: Option<Handle<SearchAnchorState>>,
2445}
2446
2447impl SearchController {
2448    /// Creates a controller for a [`SearchAnchor`].
2449    pub fn new(app: &mut App) -> Ref<SearchController> {
2450        app.create(SearchController {
2451            change_notifier: ChangeNotifierData::new(),
2452            text_editing_controller: TextEditingControllerData::new(TextEditingValue::new()),
2453            anchor: None,
2454        })
2455    }
2456
2457    fn attach(self: Handle<Self>, app: &mut App, anchor: Handle<SearchAnchorState>) {
2458        app.get_mut(self).anchor = Some(anchor);
2459    }
2460
2461    fn detach(self: Handle<Self>, app: &mut App, anchor: Handle<SearchAnchorState>) {
2462        if app.get(self).anchor == Some(anchor) {
2463            app.get_mut(self).anchor = None;
2464        }
2465    }
2466
2467    /// Whether this controller has been attached to a [`SearchAnchor`].
2468    pub fn is_attached(self: Handle<Self>, app: &App) -> bool {
2469        app.get(self).anchor.is_some()
2470    }
2471
2472    /// Whether this controller's search view is open.
2473    ///
2474    /// The controller must be attached to a [`SearchAnchor`].
2475    pub fn is_open(self: Handle<Self>, app: &App) -> bool {
2476        let anchor = app.get(self).anchor;
2477        assert!(
2478            anchor.is_some(),
2479            "the controller is not attached to an anchor"
2480        );
2481        anchor.expect("attached").view_is_open(app)
2482    }
2483
2484    /// Opens the search view.
2485    ///
2486    /// The controller must be attached to a [`SearchAnchor`].
2487    pub fn open_view(self: Handle<Self>, app: &mut App) {
2488        let anchor = app.get(self).anchor;
2489        assert!(
2490            anchor.is_some(),
2491            "the controller is not attached to an anchor"
2492        );
2493        anchor.expect("attached").open_view(app);
2494    }
2495
2496    /// Close the search view that was opened by this controller.
2497    ///
2498    /// If `selected_text` is given, it is the new text of the search controller, which a
2499    /// search view writes when the user selects a suggestion.
2500    pub fn close_view(self: Handle<Self>, app: &mut App, selected_text: Option<String>) {
2501        let anchor = app.get(self).anchor;
2502        assert!(
2503            anchor.is_some(),
2504            "the controller is not attached to an anchor"
2505        );
2506        anchor.expect("attached").close_view(app, selected_text);
2507    }
2508}
2509
2510impl Debug for SearchController {
2511    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2512        f.debug_struct("SearchController")
2513            .field("anchor", &self.anchor)
2514            .finish_non_exhaustive()
2515    }
2516}
2517
2518impl ChangeNotifier for SearchController {
2519    fn change_notifier_data(&self) -> &ChangeNotifierData {
2520        &self.change_notifier
2521    }
2522
2523    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2524        &mut self.change_notifier
2525    }
2526}
2527
2528impl TextEditingControllerLeaf for SearchController {
2529    waft_widgets::text_editing_controller_accessors!();
2530}
2531
2532/// A Material Design search bar.
2533///
2534/// A [`SearchBar`] looks like a [`TextField`]. Pressing the [`SearchBar`] typically shows a
2535/// search view route. Users can type the search query in the search view.
2536///
2537/// See also:
2538///
2539///  * [`SearchAnchor`], a widget that typically shows a [`SearchBar`] and, when tapped,
2540///    displays a search view.
2541///  * [`SearchBarTheme`], a widget that overrides the default configuration of a search bar.
2542///  * [`SearchViewTheme`], a widget that overrides the default configuration of a search
2543///    view.
2544#[derive(Clone)]
2545pub struct SearchBar {
2546    pub key: Option<KeyRef>,
2547
2548    /// Controls the text being edited in the search bar's text field.
2549    pub controller: Option<TextEditingControllerRef>,
2550
2551    /// Defines the keyboard focus for this widget.
2552    pub focus_node: Option<FocusNodeRef>,
2553
2554    /// Text that suggests what sort of input the field accepts.
2555    ///
2556    /// Displayed at the same location on the screen where text may be entered when the input
2557    /// is empty.
2558    pub hint_text: Option<String>,
2559
2560    /// A widget to display before the text input field.
2561    ///
2562    /// Typically the [`leading`](Self::leading) widget is an [`Icon`] or an [`IconButton`].
2563    pub leading: Option<WidgetRef>,
2564
2565    /// A list of widgets to display in a row after the text field.
2566    ///
2567    /// Typically these actions can represent additional modes of searching (like voice
2568    /// search), an avatar, or an overflow menu. There should not be more than two trailing
2569    /// actions.
2570    pub trailing: Option<Vec<WidgetRef>>,
2571
2572    /// Called when the user taps this search bar.
2573    pub on_tap: Option<Listener>,
2574
2575    /// Called when the user taps outside the search bar's text field.
2576    pub on_tap_outside: Option<TapRegionCallback>,
2577
2578    /// Invoked upon user input.
2579    pub on_changed: Option<ValueChanged<String>>,
2580
2581    /// Called when the user indicates that they are done editing the text in the field.
2582    pub on_submitted: Option<ValueChanged<String>>,
2583
2584    /// Optional size constraints for the search bar.
2585    ///
2586    /// If null, the value of [`SearchBarThemeData::constraints`] will be used. If that is
2587    /// also null, then the constraints defaults to:
2588    /// `BoxConstraints { min_width: 360.0, max_width: 800.0, min_height: 56.0, .. }`.
2589    pub constraints: Option<BoxConstraints>,
2590
2591    /// The elevation of the search bar's [`Material`].
2592    ///
2593    /// If null, the value of [`SearchBarThemeData::elevation`] will be used. If that is also
2594    /// null, then default value is 6.0.
2595    pub elevation: Option<WidgetStatePropertyRef<Option<f64>>>,
2596
2597    /// The search bar's background fill color.
2598    ///
2599    /// If null, the value of [`SearchBarThemeData::background_color`] will be used. If that
2600    /// is also null, then the default value is `ColorScheme::surface_container_high`.
2601    pub background_color: Option<WidgetStatePropertyRef<Option<Color>>>,
2602
2603    /// The shadow color of the search bar's [`Material`].
2604    ///
2605    /// If null, the value of [`SearchBarThemeData::shadow_color`] will be used. If that is
2606    /// also null, then the default value is `ColorScheme::shadow`.
2607    pub shadow_color: Option<WidgetStatePropertyRef<Option<Color>>>,
2608
2609    /// The surface tint color of the search bar's [`Material`].
2610    ///
2611    /// If null, the value of [`SearchBarThemeData::surface_tint_color`] will be used. If that
2612    /// is also null, then the default value is `Colors::TRANSPARENT`.
2613    pub surface_tint_color: Option<WidgetStatePropertyRef<Option<Color>>>,
2614
2615    /// The highlight color that's typically used to indicate that the search bar is focused,
2616    /// hovered, or pressed.
2617    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
2618
2619    /// The color and weight of the search bar's outline.
2620    ///
2621    /// This value is combined with [`shape`](Self::shape) to create a shape decorated with an
2622    /// outline.
2623    pub side: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
2624
2625    /// The shape of the search bar's underlying [`Material`].
2626    ///
2627    /// This shape is combined with [`side`](Self::side) to create a shape decorated with an
2628    /// outline.
2629    pub shape: Option<WidgetStatePropertyRef<Option<OutlinedBorderRef>>>,
2630
2631    /// The padding between the search bar's boundary and its contents.
2632    ///
2633    /// If null, the value of [`SearchBarThemeData::padding`] will be used. If that is also
2634    /// null, then the default value is 8.0 horizontally.
2635    pub padding: Option<WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>>,
2636
2637    /// The style to use for the text being edited.
2638    ///
2639    /// If null, defaults to the `bodyLarge` text style from the current [`Theme`]. The
2640    /// default text color is `ColorScheme::on_surface`.
2641    pub text_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
2642
2643    /// The style to use for the [`hint_text`](Self::hint_text).
2644    ///
2645    /// If null, the value of [`SearchBarThemeData::hint_style`] will be used. If that is also
2646    /// null, the value of [`text_style`](Self::text_style) will be used, and then
2647    /// `bodyLarge`.
2648    pub hint_style: Option<WidgetStatePropertyRef<Option<TextStyle>>>,
2649
2650    /// Configures how the platform keyboard will select an uppercase or lowercase keyboard.
2651    ///
2652    /// Defaults to [`TextCapitalization::None`].
2653    pub text_capitalization: Option<TextCapitalization>,
2654
2655    /// If false the text field is "disabled": it ignores taps and its decoration is rendered
2656    /// in grey.
2657    pub enabled: bool,
2658
2659    /// Whether this text field should focus itself if nothing else is already focused.
2660    pub auto_focus: bool,
2661
2662    /// The type of action button to use for the keyboard.
2663    pub text_input_action: Option<TextInputAction>,
2664
2665    /// The type of action button to use for the keyboard.
2666    pub keyboard_type: Option<TextInputType>,
2667
2668    /// Configures padding to edges surrounding a [`Scrollable`](waft_widgets::Scrollable) when
2669    /// the text field scrolls into view.
2670    pub scroll_padding: EdgeInsets,
2671
2672    /// Builds the text selection toolbar when requested by the user.
2673    ///
2674    /// See also:
2675    ///  * [`SearchBar::default_context_menu_builder`], which is the default context menu
2676    ///    builder.
2677    pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
2678
2679    /// Whether this text field is read only.
2680    pub read_only: bool,
2681
2682    /// Whether to allow the platform to automatically format dashes.
2683    pub smart_dashes_type: Option<SmartDashesType>,
2684
2685    /// Whether to allow the platform to automatically format quotes.
2686    pub smart_quotes_type: Option<SmartQuotesType>,
2687}
2688
2689impl SearchBar {
2690    /// Creates a Material Design search bar.
2691    pub fn new() -> SearchBar {
2692        SearchBar {
2693            key: None,
2694            controller: None,
2695            focus_node: None,
2696            hint_text: None,
2697            leading: None,
2698            trailing: None,
2699            on_tap: None,
2700            on_tap_outside: None,
2701            on_changed: None,
2702            on_submitted: None,
2703            constraints: None,
2704            elevation: None,
2705            background_color: None,
2706            shadow_color: None,
2707            surface_tint_color: None,
2708            overlay_color: None,
2709            side: None,
2710            shape: None,
2711            padding: None,
2712            text_style: None,
2713            hint_style: None,
2714            text_capitalization: None,
2715            enabled: true,
2716            auto_focus: false,
2717            text_input_action: None,
2718            keyboard_type: None,
2719            scroll_padding: EdgeInsets::all(20.0),
2720            context_menu_builder: Some(Rc::new(SearchBar::default_context_menu_builder)),
2721            read_only: false,
2722            smart_dashes_type: None,
2723            smart_quotes_type: None,
2724        }
2725    }
2726
2727    /// Dart `SearchBar(key:)`.
2728    pub fn key(mut self, key: KeyRef) -> SearchBar {
2729        self.key = Some(key);
2730        self
2731    }
2732
2733    /// Dart `SearchBar(controller:)`.
2734    pub fn controller(mut self, controller: TextEditingControllerRef) -> SearchBar {
2735        self.controller = Some(controller);
2736        self
2737    }
2738
2739    /// Dart `SearchBar(focusNode:)`.
2740    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> SearchBar {
2741        self.focus_node = Some(focus_node);
2742        self
2743    }
2744
2745    /// Dart `SearchBar(hintText:)`.
2746    pub fn hint_text(mut self, hint_text: impl Into<String>) -> SearchBar {
2747        self.hint_text = Some(hint_text.into());
2748        self
2749    }
2750
2751    /// Dart `SearchBar(leading:)`.
2752    #[cfg_attr(debug_assertions, track_caller)]
2753    pub fn leading<K>(mut self, leading: impl IntoWidget<K>) -> SearchBar {
2754        self.leading = Some(leading.into_widget());
2755        self
2756    }
2757
2758    /// Dart `SearchBar(trailing:)`.
2759    pub fn trailing(mut self, trailing: Vec<WidgetRef>) -> SearchBar {
2760        self.trailing = Some(trailing);
2761        self
2762    }
2763
2764    /// Dart `SearchBar(onTap:)`.
2765    pub fn on_tap(mut self, on_tap: Listener) -> SearchBar {
2766        self.on_tap = Some(on_tap);
2767        self
2768    }
2769
2770    /// Dart `SearchBar(onTapOutside:)`.
2771    pub fn on_tap_outside(mut self, on_tap_outside: TapRegionCallback) -> SearchBar {
2772        self.on_tap_outside = Some(on_tap_outside);
2773        self
2774    }
2775
2776    /// Dart `SearchBar(onChanged:)`.
2777    pub fn on_changed(mut self, on_changed: impl Fn(&mut App, String) + 'static) -> SearchBar {
2778        self.on_changed = Some(Rc::new(on_changed));
2779        self
2780    }
2781
2782    /// Dart `SearchBar(onSubmitted:)`.
2783    pub fn on_submitted(mut self, on_submitted: impl Fn(&mut App, String) + 'static) -> SearchBar {
2784        self.on_submitted = Some(Rc::new(on_submitted));
2785        self
2786    }
2787
2788    /// Dart `SearchBar(constraints:)`.
2789    pub fn constraints(mut self, constraints: BoxConstraints) -> SearchBar {
2790        self.constraints = Some(constraints);
2791        self
2792    }
2793
2794    /// Dart `SearchBar(elevation:)`.
2795    pub fn elevation(mut self, elevation: WidgetStatePropertyRef<Option<f64>>) -> SearchBar {
2796        self.elevation = Some(elevation);
2797        self
2798    }
2799
2800    /// Dart `SearchBar(backgroundColor:)`.
2801    pub fn background_color(
2802        mut self,
2803        background_color: WidgetStatePropertyRef<Option<Color>>,
2804    ) -> SearchBar {
2805        self.background_color = Some(background_color);
2806        self
2807    }
2808
2809    /// Dart `SearchBar(shadowColor:)`.
2810    pub fn shadow_color(
2811        mut self,
2812        shadow_color: WidgetStatePropertyRef<Option<Color>>,
2813    ) -> SearchBar {
2814        self.shadow_color = Some(shadow_color);
2815        self
2816    }
2817
2818    /// Dart `SearchBar(surfaceTintColor:)`.
2819    pub fn surface_tint_color(
2820        mut self,
2821        surface_tint_color: WidgetStatePropertyRef<Option<Color>>,
2822    ) -> SearchBar {
2823        self.surface_tint_color = Some(surface_tint_color);
2824        self
2825    }
2826
2827    /// Dart `SearchBar(overlayColor:)`.
2828    pub fn overlay_color(
2829        mut self,
2830        overlay_color: WidgetStatePropertyRef<Option<Color>>,
2831    ) -> SearchBar {
2832        self.overlay_color = Some(overlay_color);
2833        self
2834    }
2835
2836    /// Dart `SearchBar(side:)`.
2837    pub fn side(mut self, side: WidgetStatePropertyRef<Option<BorderSide>>) -> SearchBar {
2838        self.side = Some(side);
2839        self
2840    }
2841
2842    /// Dart `SearchBar(shape:)`.
2843    pub fn shape(mut self, shape: WidgetStatePropertyRef<Option<OutlinedBorderRef>>) -> SearchBar {
2844        self.shape = Some(shape);
2845        self
2846    }
2847
2848    /// Dart `SearchBar(padding:)`.
2849    pub fn padding(
2850        mut self,
2851        padding: WidgetStatePropertyRef<Option<EdgeInsetsGeometry>>,
2852    ) -> SearchBar {
2853        self.padding = Some(padding);
2854        self
2855    }
2856
2857    /// Dart `SearchBar(textStyle:)`.
2858    pub fn text_style(
2859        mut self,
2860        text_style: WidgetStatePropertyRef<Option<TextStyle>>,
2861    ) -> SearchBar {
2862        self.text_style = Some(text_style);
2863        self
2864    }
2865
2866    /// Dart `SearchBar(hintStyle:)`.
2867    pub fn hint_style(
2868        mut self,
2869        hint_style: WidgetStatePropertyRef<Option<TextStyle>>,
2870    ) -> SearchBar {
2871        self.hint_style = Some(hint_style);
2872        self
2873    }
2874
2875    /// Dart `SearchBar(textCapitalization:)`.
2876    pub fn text_capitalization(mut self, text_capitalization: TextCapitalization) -> SearchBar {
2877        self.text_capitalization = Some(text_capitalization);
2878        self
2879    }
2880
2881    /// Dart `SearchBar(enabled:)`.
2882    pub fn enabled(mut self, enabled: bool) -> SearchBar {
2883        self.enabled = enabled;
2884        self
2885    }
2886
2887    /// Dart `SearchBar(autoFocus:)`.
2888    pub fn auto_focus(mut self, auto_focus: bool) -> SearchBar {
2889        self.auto_focus = auto_focus;
2890        self
2891    }
2892
2893    /// Dart `SearchBar(textInputAction:)`.
2894    pub fn text_input_action(mut self, text_input_action: TextInputAction) -> SearchBar {
2895        self.text_input_action = Some(text_input_action);
2896        self
2897    }
2898
2899    /// Dart `SearchBar(keyboardType:)`.
2900    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> SearchBar {
2901        self.keyboard_type = Some(keyboard_type);
2902        self
2903    }
2904
2905    /// Dart `SearchBar(scrollPadding:)`.
2906    pub fn scroll_padding(mut self, scroll_padding: EdgeInsets) -> SearchBar {
2907        self.scroll_padding = scroll_padding;
2908        self
2909    }
2910
2911    /// Dart `SearchBar(contextMenuBuilder:)`.
2912    pub fn context_menu_builder(
2913        mut self,
2914        context_menu_builder: Option<EditableTextContextMenuBuilder>,
2915    ) -> SearchBar {
2916        self.context_menu_builder = context_menu_builder;
2917        self
2918    }
2919
2920    /// Dart `SearchBar(readOnly:)`.
2921    pub fn read_only(mut self, read_only: bool) -> SearchBar {
2922        self.read_only = read_only;
2923        self
2924    }
2925
2926    /// Dart `SearchBar(smartDashesType:)`.
2927    pub fn smart_dashes_type(mut self, smart_dashes_type: SmartDashesType) -> SearchBar {
2928        self.smart_dashes_type = Some(smart_dashes_type);
2929        self
2930    }
2931
2932    /// Dart `SearchBar(smartQuotesType:)`.
2933    pub fn smart_quotes_type(mut self, smart_quotes_type: SmartQuotesType) -> SearchBar {
2934        self.smart_quotes_type = Some(smart_quotes_type);
2935        self
2936    }
2937
2938    /// Dart's `_defaultContextMenuBuilder`.
2939    pub fn default_context_menu_builder(
2940        app: &mut App,
2941        _context: BuildContext,
2942        editable_text_state: Handle<EditableTextState>,
2943    ) -> WidgetRef {
2944        if SystemContextMenu::is_supported_by_field(app, editable_text_state) {
2945            return SystemContextMenu::editable_text(app, editable_text_state).into_widget();
2946        }
2947        AdaptiveTextSelectionToolbar::editable_text(app, editable_text_state).into_widget()
2948    }
2949}
2950
2951impl Default for SearchBar {
2952    fn default() -> SearchBar {
2953        SearchBar::new()
2954    }
2955}
2956
2957impl Debug for SearchBar {
2958    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2959        f.debug_struct("SearchBar")
2960            .field("hint_text", &self.hint_text)
2961            .field("enabled", &self.enabled)
2962            .field("auto_focus", &self.auto_focus)
2963            .field("read_only", &self.read_only)
2964            .finish_non_exhaustive()
2965    }
2966}
2967
2968impl StatefulWidget for SearchBar {
2969    type State = SearchBarState;
2970
2971    fn key(&self) -> Option<&KeyRef> {
2972        self.key.as_ref()
2973    }
2974
2975    fn create_state(&self) -> SearchBarState {
2976        SearchBarState {
2977            state: StateData::new(),
2978            internal_states_controller: None,
2979            internal_focus_node: None,
2980        }
2981    }
2982}
2983
2984/// Dart's `_SearchBarState`.
2985pub struct SearchBarState {
2986    state: StateData<SearchBar>,
2987    /// Dart's `late final MaterialStatesController _internalStatesController`, created in
2988    /// `init_state` because an arena object needs the [`App`].
2989    internal_states_controller: Option<Ref<WidgetStatesController>>,
2990    internal_focus_node: Option<Ref<FocusNode>>,
2991}
2992
2993impl SearchBarState {
2994    fn states_controller(self: Handle<Self>, app: &App) -> Handle<WidgetStatesController> {
2995        app.get(self)
2996            .internal_states_controller
2997            .as_ref()
2998            .expect("created in init_state")
2999            .handle()
3000    }
3001
3002    /// Dart's `_focusNode`.
3003    fn focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
3004        if let Some(focus_node) = &self.widget(app).focus_node {
3005            return focus_node.clone();
3006        }
3007        if app.get(self).internal_focus_node.is_none() {
3008            let focus_node = FocusNode::new(app);
3009            app.get_mut(self).internal_focus_node = Some(focus_node);
3010        }
3011        app.get(self)
3012            .internal_focus_node
3013            .as_ref()
3014            .expect("created above")
3015            .erase()
3016    }
3017
3018    fn handle_states_changed(self: Handle<Self>, app: &mut App) {
3019        self.set_state(app, |_| {});
3020    }
3021
3022    fn handle_tap(self: Handle<Self>, app: &mut App) {
3023        if let Some(on_tap) = self.widget(app).on_tap.clone() {
3024            on_tap.call(app);
3025        }
3026        let focus_node = self.focus_node(app);
3027        if !focus_node.has_focus(app) {
3028            focus_node.request_focus(app, None);
3029        }
3030    }
3031}
3032
3033/// Dart's local `resolve<T>(widgetValue, themeValue, defaultValue)`.
3034fn resolve_search_bar_property<T: Clone + 'static>(
3035    states: &waft_widgets::WidgetStates,
3036    widget_value: &Option<WidgetStatePropertyRef<Option<T>>>,
3037    theme_value: &Option<WidgetStatePropertyRef<Option<T>>>,
3038    default_value: &Option<WidgetStatePropertyRef<Option<T>>>,
3039) -> Option<T> {
3040    widget_value
3041        .as_ref()
3042        .and_then(|value| value.resolve(states))
3043        .or_else(|| theme_value.as_ref().and_then(|value| value.resolve(states)))
3044        .or_else(|| {
3045            default_value
3046                .as_ref()
3047                .and_then(|value| value.resolve(states))
3048        })
3049}
3050
3051impl State for SearchBarState {
3052    type Widget = SearchBar;
3053    waft_widgets::state_accessors!();
3054
3055    fn init_state(self: Handle<Self>, app: &mut App) {
3056        let controller = WidgetStatesController::new(app, None);
3057        controller.add_listener(
3058            app,
3059            Listener::handle_method(self, SearchBarState::handle_states_changed),
3060        );
3061        app.get_mut(self).internal_states_controller = Some(controller);
3062    }
3063
3064    fn dispose(self: Handle<Self>, app: &mut App) {
3065        let controller = self.states_controller(app);
3066        ChangeNotifierData::dispose(app, controller);
3067        if let Some(focus_node) = app.get(self).internal_focus_node.clone() {
3068            ChangeNotifierData::dispose(app, focus_node.handle());
3069        }
3070    }
3071
3072    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3073        let widget = self.widget(app).clone();
3074        let text_direction = Directionality::of(app, context);
3075        let color_scheme = Theme::of(app, context).color_scheme.clone();
3076        let search_bar_theme = SearchBarTheme::of(app, context);
3077        let defaults = SearchBarDefaultsM3::new(context);
3078        let states = app.get(self.states_controller(app)).value().clone();
3079
3080        let default_text_style = defaults.text_style(app);
3081        let default_elevation = defaults.elevation(app);
3082        let default_shadow_color = defaults.shadow_color(app);
3083        let default_background_color = defaults.background_color(app);
3084        let default_surface_tint_color = defaults.surface_tint_color(app);
3085        let default_shape = defaults.shape(app);
3086        let default_side = defaults.side(app);
3087        let default_padding = defaults.padding(app);
3088
3089        let effective_text_style = resolve_search_bar_property(
3090            &states,
3091            &widget.text_style,
3092            &search_bar_theme.text_style,
3093            &default_text_style,
3094        );
3095        let effective_elevation = resolve_search_bar_property(
3096            &states,
3097            &widget.elevation,
3098            &search_bar_theme.elevation,
3099            &default_elevation,
3100        );
3101        let effective_shadow_color = resolve_search_bar_property(
3102            &states,
3103            &widget.shadow_color,
3104            &search_bar_theme.shadow_color,
3105            &default_shadow_color,
3106        );
3107        let effective_background_color = resolve_search_bar_property(
3108            &states,
3109            &widget.background_color,
3110            &search_bar_theme.background_color,
3111            &default_background_color,
3112        );
3113        let effective_surface_tint_color = resolve_search_bar_property(
3114            &states,
3115            &widget.surface_tint_color,
3116            &search_bar_theme.surface_tint_color,
3117            &default_surface_tint_color,
3118        );
3119        let effective_shape = resolve_search_bar_property(
3120            &states,
3121            &widget.shape,
3122            &search_bar_theme.shape,
3123            &default_shape,
3124        );
3125        let effective_side = resolve_search_bar_property(
3126            &states,
3127            &widget.side,
3128            &search_bar_theme.side,
3129            &default_side,
3130        );
3131        let effective_padding = resolve_search_bar_property(
3132            &states,
3133            &widget.padding,
3134            &search_bar_theme.padding,
3135            &default_padding,
3136        );
3137        let effective_overlay_color = widget
3138            .overlay_color
3139            .clone()
3140            .or_else(|| search_bar_theme.overlay_color.clone())
3141            .or_else(|| defaults.overlay_color(app));
3142        let effective_text_capitalization = widget
3143            .text_capitalization
3144            .or(search_bar_theme.text_capitalization)
3145            .or_else(|| defaults.text_capitalization(app))
3146            .expect("defaults.textCapitalization!");
3147
3148        let effective_hint_style = widget
3149            .hint_style
3150            .as_ref()
3151            .and_then(|hint_style| hint_style.resolve(&states))
3152            .or_else(|| {
3153                search_bar_theme
3154                    .hint_style
3155                    .as_ref()
3156                    .and_then(|hint_style| hint_style.resolve(&states))
3157            })
3158            .or_else(|| {
3159                widget
3160                    .text_style
3161                    .as_ref()
3162                    .and_then(|text_style| text_style.resolve(&states))
3163            })
3164            .or_else(|| {
3165                search_bar_theme
3166                    .text_style
3167                    .as_ref()
3168                    .and_then(|text_style| text_style.resolve(&states))
3169            })
3170            .or_else(|| {
3171                defaults
3172                    .hint_style(app)
3173                    .and_then(|hint_style| hint_style.resolve(&states))
3174            });
3175
3176        let default_color = match color_scheme.brightness() {
3177            Brightness::Light => K_DEFAULT_ICON_DARK_COLOR,
3178            Brightness::Dark => K_DEFAULT_ICON_LIGHT_COLOR,
3179        };
3180        let icon_theme = IconTheme::of(app, context);
3181        let custom_theme =
3182            if icon_theme.color.as_ref().map(|color| color.color()) != Some(default_color) {
3183                Some(icon_theme)
3184            } else {
3185                None
3186            };
3187
3188        let leading = widget.leading.clone().map(|leading| {
3189            IconTheme::merge(
3190                None,
3191                custom_theme
3192                    .clone()
3193                    .unwrap_or_else(|| IconThemeData::new().color(color_scheme.on_surface())),
3194                leading,
3195            )
3196            .into_widget()
3197        });
3198
3199        let trailing: Option<Vec<WidgetRef>> = widget.trailing.as_ref().map(|trailing| {
3200            trailing
3201                .iter()
3202                .map(|trailing| {
3203                    IconTheme::merge(
3204                        None,
3205                        custom_theme.clone().unwrap_or_else(|| {
3206                            IconThemeData::new().color(color_scheme.on_surface_variant())
3207                        }),
3208                        trailing.clone(),
3209                    )
3210                    .into_widget()
3211                })
3212                .collect()
3213        });
3214
3215        let effective_shape_with_side = effective_shape
3216            .as_ref()
3217            .map(|shape| shape.copy_with(effective_side));
3218        let effective_padding = effective_padding.expect("effectivePadding!");
3219        let focus_node = self.focus_node(app);
3220        let states_controller = app
3221            .get(self)
3222            .internal_states_controller
3223            .clone()
3224            .expect("created in init_state");
3225        let bar_constraints = widget
3226            .constraints
3227            .or(search_bar_theme.constraints)
3228            .or_else(|| defaults.constraints(app))
3229            .expect("defaults.constraints!");
3230
3231        let mut input_decoration_theme = InputDecorationThemeData::new();
3232        if let Some(effective_hint_style) = effective_hint_style {
3233            input_decoration_theme = input_decoration_theme.hint_style(effective_hint_style);
3234        }
3235        let input_decoration_theme = input_decoration_theme
3236            // The configuration below is to make sure that the text field
3237            // in `SearchBar` will not be overridden by the overall
3238            // `InputDecorationThemeData`
3239            .enabled_border(InputBorderRef::none())
3240            .border(InputBorderRef::none())
3241            .focused_border(InputBorderRef::none())
3242            .content_padding(EdgeInsetsGeometry::from(EdgeInsets::ZERO))
3243            // Setting `isDense` to true to allow the text field height to be
3244            // smaller than 48.0
3245            .is_dense(true);
3246        let mut text_field = TextField::new()
3247            .read_only(widget.read_only)
3248            .autofocus(widget.auto_focus)
3249            .on_tap_always_called(true)
3250            .focus_node(focus_node)
3251            .enabled(widget.enabled)
3252            .decoration(Some(
3253                hint_decoration(widget.hint_text.clone()).apply_defaults(input_decoration_theme),
3254            ))
3255            .text_capitalization(effective_text_capitalization)
3256            .scroll_padding(widget.scroll_padding)
3257            .context_menu_builder(widget.context_menu_builder.clone());
3258        if let Some(on_tap) = widget.on_tap.clone() {
3259            text_field = text_field.on_tap(on_tap);
3260        }
3261        if let Some(on_tap_outside) = widget.on_tap_outside.clone() {
3262            text_field = text_field.on_tap_outside(move |app, event| on_tap_outside(app, event));
3263        }
3264        if let Some(on_changed) = widget.on_changed.clone() {
3265            text_field = text_field.on_changed(move |app, value| on_changed(app, value));
3266        }
3267        if let Some(on_submitted) = widget.on_submitted.clone() {
3268            text_field = text_field.on_submitted(move |app, value| on_submitted(app, value));
3269        }
3270        if let Some(controller) = widget.controller.clone() {
3271            text_field = text_field.controller(controller);
3272        }
3273        if let Some(style) = effective_text_style {
3274            text_field = text_field.style(style);
3275        }
3276        if let Some(text_input_action) = widget.text_input_action {
3277            text_field = text_field.text_input_action(text_input_action);
3278        }
3279        if let Some(keyboard_type) = widget.keyboard_type {
3280            text_field = text_field.keyboard_type(keyboard_type);
3281        }
3282        if let Some(smart_dashes_type) = widget.smart_dashes_type {
3283            text_field = text_field.smart_dashes_type(smart_dashes_type);
3284        }
3285        if let Some(smart_quotes_type) = widget.smart_quotes_type {
3286            text_field = text_field.smart_quotes_type(smart_quotes_type);
3287        }
3288
3289        let mut row_children = Vec::new();
3290        row_children.extend(leading);
3291        row_children.push(
3292            Expanded::new(
3293                Padding::new(effective_padding).child(
3294                    Semantics::new()
3295                        .input_type(SemanticsInputType::Search)
3296                        .child(text_field),
3297                ),
3298            )
3299            .into_widget(),
3300        );
3301        row_children.extend(trailing.into_iter().flatten());
3302
3303        let mut material =
3304            Material::new().elevation(effective_elevation.expect("effectiveElevation!"));
3305        if let Some(shadow_color) = effective_shadow_color {
3306            material = material.shadow_color(shadow_color);
3307        }
3308        if let Some(color) = effective_background_color {
3309            material = material.color(color);
3310        }
3311        if let Some(surface_tint_color) = effective_surface_tint_color {
3312            material = material.surface_tint_color(surface_tint_color);
3313        }
3314        if let Some(shape) = effective_shape_with_side.clone() {
3315            material = material.shape(shape);
3316        }
3317        let mut ink_well = InkWell::new()
3318            // Avoid creating a redundant focus stop and focusable/tappable
3319            // semantics node on the InkWell, since the inner TextField
3320            // already handles focus and semantics for the SearchBar.
3321            .can_request_focus(false)
3322            .exclude_from_semantics(true)
3323            .on_tap(Listener::handle_method(self, SearchBarState::handle_tap))
3324            .states_controller(states_controller)
3325            .child(
3326                Padding::new(effective_padding).child(
3327                    Row::new()
3328                        .text_direction(text_direction)
3329                        .children(row_children),
3330                ),
3331            );
3332        if let Some(overlay_color) = effective_overlay_color {
3333            ink_well = ink_well.overlay_color(overlay_color);
3334        }
3335        if let Some(shape) = effective_shape_with_side {
3336            ink_well = ink_well.custom_border(shape);
3337        }
3338
3339        ConstrainedBox::new(bar_constraints)
3340            .child(
3341                Opacity::new(if widget.enabled {
3342                    1.0
3343                } else {
3344                    K_DISABLE_SEARCH_BAR_OPACITY
3345                })
3346                .child(
3347                    material.child(
3348                        IgnorePointer::new()
3349                            .ignoring(!widget.enabled)
3350                            .child(ink_well),
3351                    ),
3352                ),
3353            )
3354            .into_widget()
3355    }
3356}
3357
3358/// Dart's `InputDecoration(hintText: hintText)`.
3359fn hint_decoration(hint_text: Option<String>) -> InputDecoration {
3360    match hint_text {
3361        Some(hint_text) => InputDecoration::new().hint_text(hint_text),
3362        None => InputDecoration::new(),
3363    }
3364}
3365
3366#[cfg(test)]
3367mod tests {
3368    use std::cell::{Cell, RefCell};
3369    use std::collections::HashMap;
3370    use std::rc::Rc;
3371
3372    use waft_embedder::{FontWeight, TargetPlatform, TextAffinity, TextSelection};
3373    use waft_foundation::Completer;
3374    use waft_painting::{Border, BoxDecoration, StadiumBorder};
3375    use waft_widgets::testing::{
3376        WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
3377    };
3378    use waft_widgets::{Center, Container, EditableText, FocusNode, Text, TextEditingController};
3379
3380    use super::*;
3381    use crate::icon_button::IconButton;
3382    use crate::icons::Icons;
3383    use crate::list_tile::ListTile;
3384    use crate::material::Material;
3385    use crate::scaffold::Scaffold;
3386    use crate::test_support::material_app;
3387    use crate::theme_data::ThemeData;
3388
3389    fn m3(tester: &WidgetTester) -> ThemeData {
3390        ThemeData::new(&tester.cell.borrow())
3391    }
3392
3393    fn pump_material_home(tester: &mut WidgetTester, theme: Option<ThemeData>, home: WidgetRef) {
3394        let theme = theme.unwrap_or_else(|| m3(tester));
3395        tester.pump_widget(material_app(theme, home));
3396    }
3397
3398    fn search_bar_material(tester: &WidgetTester) -> Material {
3399        let finder = find::descendant(find::by_type::<SearchBar>(), find::by_type::<Material>());
3400        tester.widget(finder, |material: &Material| material.clone())
3401    }
3402
3403    /// Dart's `checkSearchBarDefaults`.
3404    fn check_search_bar_defaults(
3405        tester: &mut WidgetTester,
3406        color_scheme: &ColorScheme,
3407        material: &Material,
3408    ) {
3409        assert_eq!(material.animation_duration, Duration::from_millis(200));
3410        assert!(material.border_on_foreground);
3411        assert_eq!(material.border_radius, None);
3412        assert_eq!(material.clip_behavior, Clip::None);
3413        assert_eq!(material.color, Some(color_scheme.surface_container_high()));
3414        assert_eq!(material.elevation, 6.0);
3415        assert_eq!(material.shadow_color, Some(color_scheme.shadow()));
3416        assert_eq!(material.surface_tint_color, Some(Colors::TRANSPARENT));
3417        assert_eq!(
3418            material.shape,
3419            Some(StadiumBorder::new(BorderSide::NONE).into())
3420        );
3421
3422        let hint_style = tester.widget(find::text("hint text"), |text: &Text| text.style.clone());
3423        let hint_style = hint_style.expect("a hint style");
3424        assert_eq!(
3425            hint_style.color.as_ref().map(|color| color.color()),
3426            Some(color_scheme.on_surface_variant())
3427        );
3428        assert_eq!(hint_style.font_size, Some(16.0));
3429        assert_eq!(hint_style.font_family.as_deref(), Some("Roboto"));
3430        assert_eq!(hint_style.font_weight, Some(FontWeight::W400));
3431
3432        let input = "entered text";
3433        tester.enter_text(find::by_type::<SearchBar>(), input);
3434        let input_style =
3435            tester.widget(find::text(input), |text: &EditableText| text.style.clone());
3436        assert_eq!(
3437            input_style.color.as_ref().map(|color| color.color()),
3438            Some(color_scheme.on_surface())
3439        );
3440        assert_eq!(input_style.font_size, Some(16.0));
3441        assert_eq!(input_style.font_weight, Some(FontWeight::W400));
3442    }
3443
3444    // search_anchor_test.dart 'SearchBar defaults'.
3445    #[test]
3446    fn search_bar_defaults() {
3447        test_widgets(|tester| {
3448            let theme = m3(tester);
3449            let color_scheme = theme.color_scheme.clone();
3450            pump_material_home(
3451                tester,
3452                Some(theme),
3453                Material::new()
3454                    .child(SearchBar::new().hint_text("hint text"))
3455                    .into_widget(),
3456            );
3457
3458            let material = search_bar_material(tester);
3459            check_search_bar_defaults(tester, &color_scheme, &material);
3460        });
3461    }
3462
3463    // search_anchor_test.dart 'SearchBar respects controller property'.
3464    #[test]
3465    fn search_bar_respects_controller_property() {
3466        test_widgets(|tester| {
3467            let default_text = "default text";
3468            let controller = {
3469                let mut app = tester.cell.borrow_mut();
3470                TextEditingController::new(&mut app).text(&mut app, default_text)
3471            };
3472            pump_material_home(
3473                tester,
3474                None,
3475                Material::new()
3476                    .child(SearchBar::new().controller(controller.erase()))
3477                    .into_widget(),
3478            );
3479
3480            assert_eq!(
3481                controller.handle().text_value(&tester.cell.borrow()),
3482                default_text
3483            );
3484            expect(tester, &find::text(default_text), finds_one_widget());
3485
3486            let updated_text = "updated text";
3487            tester.enter_text(find::by_type::<SearchBar>(), updated_text);
3488            assert_eq!(
3489                controller.handle().text_value(&tester.cell.borrow()),
3490                updated_text
3491            );
3492            expect(tester, &find::text(default_text), finds_nothing());
3493            expect(tester, &find::text(updated_text), finds_one_widget());
3494        });
3495    }
3496
3497    // search_anchor_test.dart 'SearchBar respects focusNode property'.
3498    #[test]
3499    fn search_bar_respects_focus_node_property() {
3500        test_widgets(|tester| {
3501            let node = FocusNode::new(&mut tester.cell.borrow_mut());
3502            pump_material_home(
3503                tester,
3504                None,
3505                Material::new()
3506                    .child(SearchBar::new().focus_node(node.erase()))
3507                    .into_widget(),
3508            );
3509
3510            assert!(!node.handle().has_focus(&mut tester.cell.borrow_mut()));
3511
3512            node.handle()
3513                .request_focus(&mut tester.cell.borrow_mut(), None);
3514            tester.pump();
3515            assert!(node.handle().has_focus(&mut tester.cell.borrow_mut()));
3516
3517            node.handle()
3518                .unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
3519            tester.pump();
3520            assert!(!node.handle().has_focus(&mut tester.cell.borrow_mut()));
3521        });
3522    }
3523
3524    // search_anchor_test.dart 'SearchBar has correct default layout and padding LTR'.
3525    #[test]
3526    fn search_bar_has_correct_default_layout_and_padding_ltr() {
3527        test_widgets(|tester| {
3528            pump_material_home(tester, None, layout_bar());
3529
3530            let bar_rect = tester.get_rect(find::by_type::<SearchBar>());
3531            assert_eq!(bar_rect.size(), Size::new(800.0, 56.0));
3532            assert_eq!(bar_rect, Rect::from_ltrb(0.0, 272.0, 800.0, 328.0));
3533
3534            let leading_icon =
3535                tester.get_rect(find::widget_with_icon::<IconButton>(&Icons::search()));
3536            // Default left padding is 8.0, and icon button has 8.0 padding, so in total the
3537            // padding between the edge of the bar and the icon of the button is 16.0, which
3538            // matches the spec.
3539            assert_eq!(leading_icon.left, bar_rect.left + 8.0);
3540
3541            let text_field = tester.get_rect(find::by_type::<TextField>());
3542            assert_eq!(text_field.left, leading_icon.right + 8.0);
3543
3544            let trailing_icon =
3545                tester.get_rect(find::widget_with_icon::<IconButton>(&Icons::menu()));
3546            assert_eq!(trailing_icon.left, text_field.right + 8.0);
3547            assert_eq!(trailing_icon.right, bar_rect.right - 8.0);
3548        });
3549    }
3550
3551    fn layout_bar() -> WidgetRef {
3552        Center::new()
3553            .child(
3554                SearchBar::new()
3555                    .leading(IconButton::new(
3556                        Some(Listener::new(|_| {})),
3557                        Icon::new(Some(Icons::search())),
3558                    ))
3559                    .trailing(vec![
3560                        IconButton::new(
3561                            Some(Listener::new(|_| {})),
3562                            Icon::new(Some(Icons::menu())),
3563                        )
3564                        .into_widget(),
3565                    ]),
3566            )
3567            .into_widget()
3568    }
3569
3570    // search_anchor_test.dart 'SearchBar has correct default layout and padding - RTL'.
3571    #[test]
3572    fn search_bar_has_correct_default_layout_and_padding_rtl() {
3573        test_widgets(|tester| {
3574            pump_material_home(
3575                tester,
3576                None,
3577                Directionality::new(TextDirection::Rtl, layout_bar()).into_widget(),
3578            );
3579
3580            let bar_rect = tester.get_rect(find::by_type::<SearchBar>());
3581            assert_eq!(bar_rect.size(), Size::new(800.0, 56.0));
3582            assert_eq!(bar_rect, Rect::from_ltrb(0.0, 272.0, 800.0, 328.0));
3583
3584            // The default padding is set to 8.0 so the distance between the icon of the
3585            // button and the edge of the bar is 16.0, which matches the spec.
3586            let leading_icon =
3587                tester.get_rect(find::widget_with_icon::<IconButton>(&Icons::search()));
3588            assert_eq!(leading_icon.right, bar_rect.right - 8.0);
3589
3590            let text_field = tester.get_rect(find::by_type::<TextField>());
3591            assert_eq!(text_field.right, leading_icon.left - 8.0);
3592
3593            let trailing_icon =
3594                tester.get_rect(find::widget_with_icon::<IconButton>(&Icons::menu()));
3595            assert_eq!(trailing_icon.right, text_field.left - 8.0);
3596            assert_eq!(trailing_icon.left, bar_rect.left + 8.0);
3597        });
3598    }
3599
3600    // search_anchor_test.dart 'SearchBar respects hintText property'.
3601    #[test]
3602    fn search_bar_respects_hint_text_property() {
3603        test_widgets(|tester| {
3604            pump_material_home(
3605                tester,
3606                None,
3607                Material::new()
3608                    .child(SearchBar::new().hint_text("hint text"))
3609                    .into_widget(),
3610            );
3611            expect(tester, &find::text("hint text"), finds_one_widget());
3612        });
3613    }
3614
3615    // search_anchor_test.dart 'SearchBar respects onTap property'.
3616    #[test]
3617    fn search_bar_respects_on_tap_property() {
3618        test_widgets(|tester| {
3619            let tap_count = Rc::new(Cell::new(0));
3620            pump_material_home(
3621                tester,
3622                None,
3623                Material::new()
3624                    .child(SearchBar::new().on_tap(Listener::new({
3625                        let tap_count = Rc::clone(&tap_count);
3626                        move |_| tap_count.set(tap_count.get() + 1)
3627                    })))
3628                    .into_widget(),
3629            );
3630            assert_eq!(tap_count.get(), 0);
3631            tester.tap(find::by_type::<SearchBar>());
3632            assert_eq!(tap_count.get(), 1);
3633            tester.tap(find::by_type::<SearchBar>());
3634            assert_eq!(tap_count.get(), 2);
3635        });
3636    }
3637
3638    // search_anchor_test.dart 'SearchBar respects onChanged property'.
3639    #[test]
3640    fn search_bar_respects_on_changed_property() {
3641        test_widgets(|tester| {
3642            let change_count = Rc::new(Cell::new(0));
3643            pump_material_home(
3644                tester,
3645                None,
3646                Material::new()
3647                    .child(SearchBar::new().on_changed({
3648                        let change_count = Rc::clone(&change_count);
3649                        move |_, _| change_count.set(change_count.get() + 1)
3650                    }))
3651                    .into_widget(),
3652            );
3653            assert_eq!(change_count.get(), 0);
3654            tester.enter_text(find::by_type::<SearchBar>(), "a");
3655            assert_eq!(change_count.get(), 1);
3656            tester.enter_text(find::by_type::<SearchBar>(), "b");
3657            assert_eq!(change_count.get(), 2);
3658        });
3659    }
3660
3661    // search_anchor_test.dart 'SearchBar respects onSubmitted property'.
3662    #[test]
3663    fn search_bar_respects_on_submitted_property() {
3664        test_widgets(|tester| {
3665            let submitted_query = Rc::new(RefCell::new(String::new()));
3666            pump_material_home(
3667                tester,
3668                None,
3669                Material::new()
3670                    .child(SearchBar::new().on_submitted({
3671                        let submitted_query = Rc::clone(&submitted_query);
3672                        move |_, text| *submitted_query.borrow_mut() = text
3673                    }))
3674                    .into_widget(),
3675            );
3676            tester.enter_text(find::by_type::<SearchBar>(), "query");
3677            tester
3678                .test_text_input()
3679                .receive_action(TextInputAction::Done);
3680            assert_eq!(*submitted_query.borrow(), "query");
3681        });
3682    }
3683
3684    fn view_content() -> waft_widgets::testing::Finder {
3685        find::by_type::<ViewContent>()
3686    }
3687
3688    fn search_view_material(tester: &WidgetTester) -> Material {
3689        let finder = find::descendant(view_content(), find::by_type::<Material>()).first();
3690        tester.widget(finder, |material: &Material| material.clone())
3691    }
3692
3693    fn search_view_size(tester: &WidgetTester) -> Size {
3694        tester.get_size(find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first())
3695    }
3696
3697    fn search_icon_anchor() -> SearchAnchor {
3698        SearchAnchor::new(
3699            |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
3700            |_app, _context, _controller| Task::ready(Vec::new()),
3701        )
3702    }
3703
3704    fn button_anchor() -> SearchAnchor {
3705        SearchAnchor::new(
3706            |_app, _context, _controller| {
3707                IconButton::new(
3708                    Some(Listener::new(|_| {})),
3709                    Icon::new(Some(Icons::search())),
3710                )
3711                .into_widget()
3712            },
3713            |_app, _context, _controller| Task::ready(Vec::new()),
3714        )
3715    }
3716
3717    // search_anchor_test.dart 'The search view defaults'.
3718    #[test]
3719    fn the_search_view_defaults() {
3720        test_widgets(|tester| {
3721            let theme = m3(tester);
3722            let color_scheme = theme.color_scheme.clone();
3723            pump_material_home(
3724                tester,
3725                Some(theme),
3726                Scaffold::new()
3727                    .body(
3728                        Material::new().child(
3729                            Align::new()
3730                                .alignment(AlignmentGeometry::TOP_LEFT)
3731                                .child(search_icon_anchor().view_hint_text("hint text")),
3732                        ),
3733                    )
3734                    .into_widget(),
3735            );
3736
3737            tester.tap(find::by_icon(&Icons::search()));
3738            tester.pump_and_settle();
3739            let material = search_view_material(tester);
3740            assert_eq!(material.elevation, 6.0);
3741            assert_eq!(material.color, Some(color_scheme.surface_container_high()));
3742            assert_eq!(material.surface_tint_color, Some(Colors::TRANSPARENT));
3743            assert_eq!(material.clip_behavior, Clip::AntiAlias);
3744
3745            // Default search view has a leading back button on the start of the header.
3746            expect(tester, &find::by_type::<BackButton>(), finds_one_widget());
3747
3748            let divider_color = tester.widget(
3749                find::descendant(find::by_type::<Divider>(), find::by_type::<Container>()).first(),
3750                |container: &Container| {
3751                    container
3752                        .decoration
3753                        .as_ref()
3754                        .expect("the container has a decoration")
3755                        .as_any()
3756                        .downcast_ref::<BoxDecoration>()
3757                        .expect("a BoxDecoration")
3758                        .border
3759                        .as_ref()
3760                        .expect("the decoration has a border")
3761                        .as_any()
3762                        .downcast_ref::<Border>()
3763                        .expect("a Border")
3764                        .bottom
3765                        .color
3766                },
3767            );
3768            assert_eq!(divider_color, color_scheme.outline());
3769
3770            let hint_style = tester
3771                .widget(find::text("hint text"), |text: &Text| text.style.clone())
3772                .expect("a hint style");
3773            assert_eq!(
3774                hint_style.color.as_ref().map(|color| color.color()),
3775                Some(color_scheme.on_surface_variant())
3776            );
3777            assert_eq!(hint_style.font_size, Some(16.0));
3778            assert_eq!(hint_style.font_family.as_deref(), Some("Roboto"));
3779            assert_eq!(hint_style.font_weight, Some(FontWeight::W400));
3780
3781            let input = "entered text";
3782            tester.enter_text(find::by_type::<SearchBar>(), input);
3783            let input_style =
3784                tester.widget(find::text(input), |text: &EditableText| text.style.clone());
3785            assert_eq!(
3786                input_style.color.as_ref().map(|color| color.color()),
3787                Some(color_scheme.on_surface())
3788            );
3789            assert_eq!(input_style.font_size, Some(16.0));
3790            assert_eq!(input_style.font_family.as_deref(), Some("Roboto"));
3791            assert_eq!(input_style.font_weight, Some(FontWeight::W400));
3792        });
3793    }
3794
3795    fn pump_platform_anchor(
3796        tester: &mut WidgetTester,
3797        platform: TargetPlatform,
3798        full_screen: Option<bool>,
3799    ) {
3800        let theme = ThemeData::builder()
3801            .platform(platform)
3802            .build(&tester.cell.borrow());
3803        let mut anchor = search_icon_anchor();
3804        anchor.is_full_screen = full_screen;
3805        pump_material_home(
3806            tester,
3807            Some(theme),
3808            Scaffold::new()
3809                .body(SafeArea::new(
3810                    Material::new().child(
3811                        Align::new()
3812                            .alignment(AlignmentGeometry::TOP_LEFT)
3813                            .child(anchor),
3814                    ),
3815                ))
3816                .into_widget(),
3817        );
3818    }
3819
3820    // search_anchor_test.dart 'The search view default size on different platforms'.
3821    #[test]
3822    fn the_search_view_default_size_on_different_platforms() {
3823        test_widgets(|tester| {
3824            // The search view should be is full-screen on mobile platforms, and have a size
3825            // of (360, 2/3 screen height) on other platforms.
3826            for platform in [
3827                TargetPlatform::IOS,
3828                TargetPlatform::Android,
3829                TargetPlatform::Fuchsia,
3830            ] {
3831                tester.pump_widget(Container::new().into_widget());
3832                pump_platform_anchor(tester, platform, None);
3833                tester.tap(find::by_icon(&Icons::search()));
3834                tester.pump_and_settle();
3835                let size = search_view_size(tester);
3836                assert_eq!(size.width(), 800.0);
3837                assert_eq!(size.height(), 600.0);
3838            }
3839
3840            for platform in [TargetPlatform::Linux, TargetPlatform::Windows] {
3841                tester.pump_widget(Container::new().into_widget());
3842                pump_platform_anchor(tester, platform, None);
3843                tester.tap(find::by_icon(&Icons::search()));
3844                tester.pump_and_settle();
3845                let size = search_view_size(tester);
3846                assert_eq!(size.width(), 360.0);
3847                assert_eq!(size.height(), 400.0);
3848            }
3849        });
3850    }
3851
3852    // search_anchor_test.dart 'SearchAnchor respects isFullScreen property'.
3853    #[test]
3854    fn search_anchor_respects_is_full_screen_property() {
3855        test_widgets(|tester| {
3856            for platform in [TargetPlatform::Linux, TargetPlatform::Windows] {
3857                tester.pump_widget(Container::new().into_widget());
3858                pump_platform_anchor(tester, platform, Some(true));
3859                tester.tap(find::by_icon(&Icons::search()));
3860                tester.pump_and_settle();
3861                let size = search_view_size(tester);
3862                assert_eq!(size.width(), 800.0);
3863                assert_eq!(size.height(), 600.0);
3864            }
3865        });
3866    }
3867
3868    // search_anchor_test.dart 'SearchAnchor respects controller property'.
3869    #[test]
3870    fn search_anchor_respects_controller_property() {
3871        test_widgets(|tester| {
3872            let default_text = "initial text";
3873            let controller = SearchController::new(&mut tester.cell.borrow_mut());
3874            controller
3875                .handle()
3876                .set_text(&mut tester.cell.borrow_mut(), default_text);
3877
3878            let anchor = SearchAnchor::new(
3879                |_app, _context, controller| {
3880                    IconButton::new(
3881                        Some(Listener::new(move |app: &mut App| {
3882                            controller.open_view(app)
3883                        })),
3884                        Icon::new(Some(Icons::search())),
3885                    )
3886                    .into_widget()
3887                },
3888                |_app, _context, _controller| Task::ready(Vec::new()),
3889            )
3890            .search_controller(controller.clone());
3891            pump_material_home(tester, None, Material::new().child(anchor).into_widget());
3892
3893            tester.tap(find::widget_with_icon::<IconButton>(&Icons::search()));
3894            tester.pump_and_settle();
3895            assert_eq!(
3896                controller.handle().text_value(&tester.cell.borrow()),
3897                default_text
3898            );
3899            expect(tester, &find::text(default_text), finds_one_widget());
3900
3901            let updated_text = "updated text";
3902            tester.enter_text(find::by_type::<SearchBar>(), updated_text);
3903            assert_eq!(
3904                controller.handle().text_value(&tester.cell.borrow()),
3905                updated_text
3906            );
3907            expect(tester, &find::text(default_text), finds_nothing());
3908            expect(tester, &find::text(updated_text), finds_one_widget());
3909        });
3910    }
3911
3912    // search_anchor_test.dart 'SearchAnchor attaches and detaches controllers property'.
3913    #[test]
3914    fn search_anchor_attaches_and_detaches_controllers_property() {
3915        test_widgets(|tester| {
3916            let anchor = |controller: Option<&Ref<SearchController>>| {
3917                let mut anchor = SearchAnchor::new(
3918                    |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
3919                    |_app, _context, _controller| Task::ready(Vec::new()),
3920                );
3921                anchor.search_controller = controller.cloned();
3922                Material::new().child(anchor).into_widget()
3923            };
3924            let is_attached = |tester: &WidgetTester, controller: &Ref<SearchController>| {
3925                controller.handle().is_attached(&tester.cell.borrow())
3926            };
3927
3928            let controller1 = SearchController::new(&mut tester.cell.borrow_mut());
3929            assert!(!is_attached(tester, &controller1));
3930
3931            pump_material_home(tester, None, anchor(Some(&controller1)));
3932            assert!(is_attached(tester, &controller1));
3933
3934            pump_material_home(tester, None, anchor(None));
3935            assert!(!is_attached(tester, &controller1));
3936
3937            let controller2 = SearchController::new(&mut tester.cell.borrow_mut());
3938            assert!(!is_attached(tester, &controller2));
3939
3940            pump_material_home(tester, None, anchor(Some(&controller2)));
3941            assert!(!is_attached(tester, &controller1));
3942            assert!(is_attached(tester, &controller2));
3943
3944            pump_material_home(tester, None, anchor(None));
3945            assert!(!is_attached(tester, &controller1));
3946            assert!(!is_attached(tester, &controller2));
3947        });
3948    }
3949
3950    // search_anchor_test.dart 'SearchAnchor respects suggestionsBuilder property'.
3951    #[test]
3952    fn search_anchor_respects_suggestions_builder_property() {
3953        test_widgets(|tester| {
3954            let controller = SearchController::new(&mut tester.cell.borrow_mut());
3955            let suggestion = "suggestion text";
3956            let anchor = SearchAnchor::new(
3957                |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
3958                move |_app, _context, controller| {
3959                    Task::ready(vec![
3960                        ListTile::new()
3961                            .title(Text::new(suggestion))
3962                            .on_tap(Listener::new(move |app: &mut App| {
3963                                controller.close_view(app, Some(suggestion.to_string()))
3964                            }))
3965                            .into_widget(),
3966                    ])
3967                },
3968            )
3969            .search_controller(controller.clone());
3970            pump_material_home(
3971                tester,
3972                None,
3973                Material::new()
3974                    .child(
3975                        Align::new()
3976                            .alignment(AlignmentGeometry::TOP_CENTER)
3977                            .child(anchor),
3978                    )
3979                    .into_widget(),
3980            );
3981            tester.tap(find::by_icon(&Icons::search()));
3982            tester.pump_and_settle();
3983
3984            let list_tile = find::widget_with_text::<ListTile>(suggestion);
3985            expect(tester, &list_tile, finds_one_widget());
3986            tester.tap(list_tile);
3987            tester.pump_and_settle();
3988
3989            assert!(!controller.handle().is_open(&tester.cell.borrow()));
3990            assert_eq!(
3991                controller.handle().text_value(&tester.cell.borrow()),
3992                suggestion
3993            );
3994        });
3995    }
3996
3997    // search_anchor_test.dart 'SearchController can open/close view'.
3998    #[test]
3999    fn search_controller_can_open_and_close_view() {
4000        test_widgets(|tester| {
4001            let controller = SearchController::new(&mut tester.cell.borrow_mut());
4002            let anchor = SearchAnchor::bar(|_app, _context, controller| {
4003                Task::ready(vec![
4004                    ListTile::new()
4005                        .title(Text::new("item 0"))
4006                        .on_tap(Listener::new(move |app: &mut App| {
4007                            controller.close_view(app, Some("item 0".to_string()))
4008                        }))
4009                        .into_widget(),
4010                ])
4011            })
4012            .search_controller(controller.clone())
4013            .is_full_screen(false);
4014            pump_material_home(
4015                tester,
4016                None,
4017                Material::new()
4018                    .child(anchor.into_search_anchor())
4019                    .into_widget(),
4020            );
4021
4022            let is_open =
4023                |tester: &WidgetTester| controller.handle().is_open(&tester.cell.borrow());
4024            assert!(!is_open(tester));
4025            tester.tap(find::by_type::<SearchBar>());
4026            tester.pump_and_settle();
4027
4028            assert!(is_open(tester));
4029            tester.tap(find::widget_with_text::<ListTile>("item 0"));
4030            tester.pump_and_settle();
4031            assert!(!is_open(tester));
4032            controller.handle().open_view(&mut tester.cell.borrow_mut());
4033            assert!(is_open(tester));
4034        });
4035    }
4036
4037    // search_anchor_test.dart 'Search view does not go off the screen - LTR'.
4038    #[test]
4039    fn search_view_does_not_go_off_the_screen_ltr() {
4040        test_widgets(|tester| {
4041            let mut anchor = button_anchor();
4042            anchor.is_full_screen = Some(false);
4043            anchor.builder = Rc::new(|_app, _context, controller| {
4044                IconButton::new(
4045                    Some(Listener::new(move |app: &mut App| {
4046                        controller.open_view(app)
4047                    })),
4048                    Icon::new(Some(Icons::search())),
4049                )
4050                .into_widget()
4051            });
4052            pump_material_home(
4053                tester,
4054                None,
4055                Material::new()
4056                    .child(
4057                        // Put the search anchor on the bottom-right corner of the screen to test
4058                        // if the search view goes off the window.
4059                        Align::new()
4060                            .alignment(AlignmentGeometry::BOTTOM_RIGHT)
4061                            .child(anchor),
4062                    )
4063                    .into_widget(),
4064            );
4065
4066            let icon_button =
4067                tester.get_rect(find::widget_with_icon::<IconButton>(&Icons::search()));
4068            // Icon button has a size of (48.0, 48.0) and the screen size is (800.0, 600.0).
4069            assert_eq!(icon_button, Rect::from_ltrb(752.0, 552.0, 800.0, 600.0));
4070
4071            tester.tap(find::by_icon(&Icons::search()));
4072            tester.pump_and_settle();
4073
4074            let search_view_rect = tester.get_rect(
4075                find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
4076            );
4077            assert_eq!(
4078                search_view_rect,
4079                Rect::from_ltrb(440.0, 200.0, 800.0, 600.0)
4080            );
4081        });
4082    }
4083
4084    // search_anchor_test.dart 'SearchAnchor should update suggestions on changes to search
4085    // controller'.
4086    #[test]
4087    fn search_anchor_updates_suggestions_on_changes_to_search_controller() {
4088        test_widgets(|tester| {
4089            let controller = SearchController::new(&mut tester.cell.borrow_mut());
4090            let suggestions = ["foo", "far", "bim"];
4091            let anchor = SearchAnchor::new(
4092                |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
4093                move |app, _context, controller| {
4094                    let search_text = controller.text_value(app).to_lowercase();
4095                    if search_text.is_empty() {
4096                        return Task::ready(vec![
4097                            Center::new().child(Text::new("No Search")).into_widget(),
4098                        ]);
4099                    }
4100                    Task::ready(
4101                        suggestions
4102                            .iter()
4103                            .filter(|suggestion| suggestion.to_lowercase().contains(&search_text))
4104                            .map(|suggestion| {
4105                                let suggestion = *suggestion;
4106                                ListTile::new()
4107                                    .title(Text::new(suggestion))
4108                                    .trailing(IconButton::new(
4109                                        Some(Listener::new(move |app: &mut App| {
4110                                            controller.set_text(app, suggestion)
4111                                        })),
4112                                        Icon::new(Some(Icons::call_missed())),
4113                                    ))
4114                                    .on_tap(Listener::new(move |app: &mut App| {
4115                                        controller.close_view(app, Some(suggestion.to_string()))
4116                                    }))
4117                                    .into_widget()
4118                            })
4119                            .collect(),
4120                    )
4121                },
4122            )
4123            .search_controller(controller.clone());
4124            pump_material_home(
4125                tester,
4126                None,
4127                Material::new()
4128                    .child(
4129                        Align::new()
4130                            .alignment(AlignmentGeometry::TOP_CENTER)
4131                            .child(anchor),
4132                    )
4133                    .into_widget(),
4134            );
4135
4136            tester.tap(find::by_icon(&Icons::search()));
4137            tester.pump_and_settle();
4138
4139            let list_tile1 = || find::widget_with_text::<ListTile>("foo");
4140            let list_tile2 = || find::widget_with_text::<ListTile>("far");
4141            let list_tile3 = || find::widget_with_text::<ListTile>("bim");
4142            let text_widget = || find::widget_with_text::<Center>("No Search");
4143            let icon_in_list_tile1 =
4144                find::descendant(list_tile1(), find::by_icon(&Icons::call_missed()));
4145
4146            expect(tester, &text_widget(), finds_one_widget());
4147            expect(tester, &list_tile1(), finds_nothing());
4148            expect(tester, &list_tile2(), finds_nothing());
4149            expect(tester, &list_tile3(), finds_nothing());
4150
4151            tester.enter_text(find::by_type::<SearchBar>(), "f");
4152            tester.pump_and_settle();
4153            expect(tester, &text_widget(), finds_nothing());
4154            expect(tester, &list_tile1(), finds_one_widget());
4155            expect(tester, &list_tile2(), finds_one_widget());
4156            expect(tester, &list_tile3(), finds_nothing());
4157
4158            tester.tap(icon_in_list_tile1);
4159            tester.pump_and_settle();
4160            assert_eq!(controller.handle().text_value(&tester.cell.borrow()), "foo");
4161            expect(tester, &text_widget(), finds_nothing());
4162            expect(tester, &list_tile1(), finds_one_widget());
4163            expect(tester, &list_tile2(), finds_nothing());
4164            expect(tester, &list_tile3(), finds_nothing());
4165
4166            tester.tap(list_tile1());
4167            tester.pump_and_settle();
4168            assert!(!controller.handle().is_open(&tester.cell.borrow()));
4169            assert_eq!(controller.handle().text_value(&tester.cell.borrow()), "foo");
4170            expect(tester, &text_widget(), finds_nothing());
4171            expect(tester, &list_tile1(), finds_nothing());
4172            expect(tester, &list_tile2(), finds_nothing());
4173            expect(tester, &list_tile3(), finds_nothing());
4174        });
4175    }
4176
4177    // search_anchor_test.dart 'SearchAnchor suggestionsBuilder property could be async'.
4178    #[test]
4179    fn search_anchor_suggestions_builder_could_be_async() {
4180        test_widgets(|tester| {
4181            let controller = SearchController::new(&mut tester.cell.borrow_mut());
4182            let suggestion = "suggestion text";
4183            let anchor = SearchAnchor::new(
4184                |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
4185                move |app, _context, controller| {
4186                    let completer = Completer::new();
4187                    let future = completer.future();
4188                    let list_tile = ListTile::new()
4189                        .title(Text::new(suggestion))
4190                        .on_tap(Listener::new(move |app: &mut App| {
4191                            controller.close_view(app, Some(suggestion.to_string()))
4192                        }))
4193                        .into_widget();
4194                    completer.complete(app, vec![list_tile]);
4195                    app.spawn(async move |_cx| future.await)
4196                },
4197            )
4198            .search_controller(controller.clone());
4199            pump_material_home(
4200                tester,
4201                None,
4202                Material::new()
4203                    .child(
4204                        Align::new()
4205                            .alignment(AlignmentGeometry::TOP_CENTER)
4206                            .child(anchor),
4207                    )
4208                    .into_widget(),
4209            );
4210            tester.tap(find::by_icon(&Icons::search()));
4211            tester.pump_and_settle();
4212
4213            expect(tester, &find::text(suggestion), finds_one_widget());
4214            tester.tap(find::text(suggestion));
4215            tester.pump_and_settle();
4216
4217            assert!(!controller.handle().is_open(&tester.cell.borrow()));
4218            assert_eq!(
4219                controller.handle().text_value(&tester.cell.borrow()),
4220                suggestion
4221            );
4222        });
4223    }
4224
4225    // search_anchor_test.dart 'SearchAnchor ignores out-of-order async suggestions'.
4226    #[test]
4227    fn search_anchor_ignores_out_of_order_async_suggestions() {
4228        test_widgets(|tester| {
4229            type Request = Completer<Vec<WidgetRef>>;
4230            let requests: Rc<RefCell<HashMap<String, Request>>> = Rc::default();
4231            let anchor = SearchAnchor::new(
4232                |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
4233                {
4234                    let requests = Rc::clone(&requests);
4235                    move |app, _context, controller| {
4236                        let query = controller.text_value(app).to_string();
4237                        if query.is_empty() {
4238                            return Task::ready(Vec::new());
4239                        }
4240                        let request = Completer::new();
4241                        let future = request.future();
4242                        requests.borrow_mut().insert(query, request);
4243                        app.spawn(async move |_cx| future.await)
4244                    }
4245                },
4246            );
4247            pump_material_home(tester, None, anchor.into_widget());
4248
4249            tester.tap(find::by_icon(&Icons::search()));
4250            tester.pump_and_settle();
4251
4252            let text_field =
4253                || find::descendant(find::by_type::<SearchBar>(), find::by_type::<TextField>());
4254            tester.enter_text(text_field(), "a");
4255            tester.pump();
4256            tester.enter_text(text_field(), "ab");
4257            tester.pump();
4258
4259            let complete = |tester: &mut WidgetTester, query: &str, text: &str| {
4260                let request = requests.borrow_mut().remove(query).expect("a request");
4261                request.complete(
4262                    &mut tester.cell.borrow_mut(),
4263                    vec![Text::new(text).into_widget()],
4264                );
4265                tester.cell.checkpoint();
4266                tester.pump_and_settle();
4267            };
4268            complete(tester, "ab", "ab-result");
4269            expect(tester, &find::text("ab-result"), finds_one_widget());
4270
4271            complete(tester, "a", "a-result");
4272            expect(tester, &find::text("ab-result"), finds_one_widget());
4273            expect(tester, &find::text("a-result"), finds_nothing());
4274        });
4275    }
4276
4277    // search_anchor_test.dart 'SearchAnchor.bar has a default search bar as the anchor'.
4278    #[test]
4279    fn search_anchor_bar_has_a_default_search_bar_as_the_anchor() {
4280        test_widgets(|tester| {
4281            let anchor = SearchAnchor::bar(|_app, _context, _controller| Task::ready(Vec::new()))
4282                .is_full_screen(false)
4283                .into_search_anchor();
4284            pump_material_home(
4285                tester,
4286                None,
4287                Material::new()
4288                    .child(
4289                        Align::new()
4290                            .alignment(AlignmentGeometry::TOP_LEFT)
4291                            .child(anchor),
4292                    )
4293                    .into_widget(),
4294            );
4295
4296            expect(tester, &find::by_type::<SearchBar>(), finds_one_widget());
4297            let anchor_rect = tester.get_rect(find::by_type::<SearchBar>());
4298            assert_eq!(anchor_rect.size(), Size::new(800.0, 56.0));
4299            assert_eq!(anchor_rect, Rect::from_ltrb(0.0, 0.0, 800.0, 56.0));
4300
4301            tester.tap(find::by_icon(&Icons::search()));
4302            tester.pump_and_settle();
4303
4304            let search_view_rect = tester.get_rect(
4305                find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
4306            );
4307            assert_eq!(search_view_rect, Rect::from_ltrb(0.0, 0.0, 800.0, 400.0));
4308
4309            // Search view has same width with the default anchor(search bar).
4310            assert_eq!(search_view_rect.width(), anchor_rect.width());
4311        });
4312    }
4313
4314    // search_anchor_test.dart 'SearchAnchor viewOnClose function test'.
4315    #[test]
4316    fn search_anchor_view_on_close_function_test() {
4317        test_widgets(|tester| {
4318            let name = Rc::new(RefCell::new("silva".to_string()));
4319            let mut anchor = button_anchor_opening_view();
4320            anchor.view_on_close = Some(Listener::new({
4321                let name = Rc::clone(&name);
4322                move |_| *name.borrow_mut() = "Pedro".to_string()
4323            }));
4324            pump_material_home(
4325                tester,
4326                None,
4327                Material::new()
4328                    .child(Center::new().child(anchor))
4329                    .into_widget(),
4330            );
4331
4332            // Open search view
4333            tester.tap(find::by_icon(&Icons::search()));
4334            tester.pump_and_settle();
4335            assert_eq!(*name.borrow(), "silva");
4336
4337            // Pop search view route
4338            tester.tap(find::by_type::<BackButton>());
4339            tester.pump_and_settle();
4340            assert_eq!(*name.borrow(), "Pedro");
4341        });
4342    }
4343
4344    // search_anchor_test.dart 'SearchAnchor viewOnOpen is called when the search view is
4345    // opened'.
4346    #[test]
4347    fn search_anchor_view_on_open_is_called_when_the_search_view_is_opened() {
4348        test_widgets(|tester| {
4349            let opened = Rc::new(Cell::new(0));
4350            let mut anchor = button_anchor_opening_view();
4351            anchor.view_on_open = Some(Listener::new({
4352                let opened = Rc::clone(&opened);
4353                move |_| opened.set(opened.get() + 1)
4354            }));
4355            pump_material_home(
4356                tester,
4357                None,
4358                Material::new()
4359                    .child(Center::new().child(anchor))
4360                    .into_widget(),
4361            );
4362
4363            assert_eq!(opened.get(), 0);
4364            tester.tap(find::by_icon(&Icons::search()));
4365            tester.pump_and_settle();
4366            assert_eq!(opened.get(), 1);
4367        });
4368    }
4369
4370    fn button_anchor_opening_view() -> SearchAnchor {
4371        SearchAnchor::new(
4372            |_app, _context, controller| {
4373                IconButton::new(
4374                    Some(Listener::new(move |app: &mut App| {
4375                        controller.open_view(app)
4376                    })),
4377                    Icon::new(Some(Icons::search())),
4378                )
4379                .into_widget()
4380            },
4381            |_app, _context, _controller| {
4382                Task::ready(
4383                    (0..5)
4384                        .map(|index| {
4385                            ListTile::new()
4386                                .leading(Icon::new(Some(Icons::history())))
4387                                .title(Text::new(format!("item {index}")))
4388                                .trailing(Icon::new(Some(Icons::chevron_right())))
4389                                .on_tap(Listener::new(|_| {}))
4390                                .into_widget()
4391                        })
4392                        .collect(),
4393                )
4394            },
4395        )
4396    }
4397
4398    // search_anchor_test.dart 'Check SearchBar opacity when disabled'.
4399    #[test]
4400    fn search_bar_is_dimmed_when_disabled() {
4401        test_widgets(|tester| {
4402            pump_material_home(
4403                tester,
4404                None,
4405                Material::new()
4406                    .child(Center::new().child(SearchBar::new().enabled(false)))
4407                    .into_widget(),
4408            );
4409
4410            expect(tester, &find::by_type::<SearchBar>(), finds_one_widget());
4411            let opacity_finder =
4412                find::descendant(find::by_type::<SearchBar>(), find::by_type::<Opacity>());
4413            expect(tester, &opacity_finder, finds_one_widget());
4414            let opacity = tester.widget(opacity_finder, |opacity: &Opacity| opacity.opacity);
4415            assert_eq!(opacity, 0.38);
4416        });
4417    }
4418
4419    // search_anchor_test.dart 'Check SearchAnchor opacity when disabled'.
4420    #[test]
4421    fn search_anchor_is_dimmed_when_disabled() {
4422        test_widgets(|tester| {
4423            pump_material_home(
4424                tester,
4425                None,
4426                Center::new()
4427                    .child(Material::new().child(search_icon_anchor().enabled(false)))
4428                    .into_widget(),
4429            );
4430
4431            expect(tester, &find::by_type::<SearchAnchor>(), finds_one_widget());
4432            let opacity_finder = find::descendant(
4433                find::by_type::<SearchAnchor>(),
4434                find::by_type::<AnimatedOpacity>(),
4435            );
4436            expect(tester, &opacity_finder, finds_one_widget());
4437            let opacity =
4438                tester.widget(opacity_finder, |opacity: &AnimatedOpacity| opacity.opacity);
4439            assert_eq!(opacity, 0.38);
4440        });
4441    }
4442
4443    use crate::card::Card;
4444    use crate::card_theme::CardThemeData;
4445    use crate::color_scheme::ColorScheme;
4446    use crate::icon_button_theme::IconButtonThemeData;
4447    use crate::list_tile::ListTileTitleAlignment;
4448    use crate::page::MaterialPageRoute;
4449    use crate::test_support::PaintInspection;
4450    use waft_painting::{
4451        BorderRadiusGeometry, CircleBorder, ContinuousRectangleBorder, RoundedRectangleBorder,
4452        ShapeBorderRef,
4453    };
4454    use waft_rendering::RenderBox;
4455    use waft_rendering::testing::{PaintCall, assert_paints};
4456    use waft_widgets::SizedBox;
4457    use waft_widgets::testing::TestPointer;
4458    use waft_widgets::{GridView, WidgetState, WidgetStateProperty, WidgetStates};
4459
4460    #[derive(Clone, Copy, Debug, PartialEq)]
4461    enum Probe {
4462        Hovered,
4463        Pressed,
4464        Focused,
4465    }
4466
4467    fn pressed_color() -> Color {
4468        Colors::RED.primary()
4469    }
4470    fn hovered_color() -> Color {
4471        Colors::ORANGE.primary()
4472    }
4473    fn focused_color() -> Color {
4474        Colors::YELLOW.primary()
4475    }
4476    fn default_color() -> Color {
4477        Colors::GREEN.primary()
4478    }
4479
4480    /// Dart's `_getColor`.
4481    fn get_color(states: &WidgetStates) -> Color {
4482        if states.contains(&WidgetState::Pressed) {
4483            pressed_color()
4484        } else if states.contains(&WidgetState::Hovered) {
4485            hovered_color()
4486        } else if states.contains(&WidgetState::Focused) {
4487            focused_color()
4488        } else {
4489            default_color()
4490        }
4491    }
4492
4493    fn color_property() -> WidgetStatePropertyRef<Option<Color>> {
4494        <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| Some(get_color(states)))
4495    }
4496
4497    /// Dart's `_getTextStyle`, over `bodyLarge` of the default theme.
4498    fn text_style_property(tester: &WidgetTester) -> WidgetStatePropertyRef<Option<TextStyle>> {
4499        let body_large = m3(tester)
4500            .text_theme
4501            .body_large
4502            .clone()
4503            .expect("a bodyLarge");
4504        <dyn WidgetStateProperty<Option<TextStyle>>>::resolve_with(move |states| {
4505            if states.contains(&WidgetState::Pressed) {
4506                Some(body_large.copy_with().color(pressed_color()))
4507            } else if states.contains(&WidgetState::Hovered) {
4508                Some(body_large.copy_with().color(hovered_color()))
4509            } else if states.contains(&WidgetState::Focused) {
4510                Some(body_large.copy_with().color(focused_color()))
4511            } else {
4512                None
4513            }
4514        })
4515    }
4516
4517    /// Dart's `_pointGestureToSearchBar`: a mouse hovering the middle of the bar.
4518    fn point_gesture_to_search_bar(tester: &mut WidgetTester) -> TestPointer {
4519        let center = tester.get_center(find::by_type::<SearchBar>());
4520        let mut gesture = TestPointer::mouse(tester.next_pointer(), 1);
4521        tester.add_pointer(&mut gesture, center);
4522        tester.move_to(&mut gesture, center, false);
4523        gesture
4524    }
4525
4526    /// The hover, press and focus steps every state-driven SearchBar property case walks;
4527    /// `settle` is where Dart pumps until settled instead of once.
4528    fn walk_states(
4529        tester: &mut WidgetTester,
4530        settle: bool,
4531        mut check: impl FnMut(&mut WidgetTester, Probe),
4532    ) {
4533        let mut gesture = point_gesture_to_search_bar(tester);
4534        if settle {
4535            tester.pump_and_settle();
4536        } else {
4537            tester.pump();
4538        }
4539        check(tester, Probe::Hovered);
4540
4541        let center = tester.get_center(find::by_type::<SearchBar>());
4542        tester.down(&mut gesture, center);
4543        tester.pump_and_settle();
4544        check(tester, Probe::Pressed);
4545
4546        tester.up(&gesture);
4547        if settle {
4548            tester.pump_and_settle();
4549        } else {
4550            tester.pump();
4551        }
4552        tester.remove_pointer(&gesture);
4553        tester.pump();
4554        check(tester, Probe::Focused);
4555    }
4556
4557    fn pump_centered_bar(tester: &mut WidgetTester, bar: SearchBar) {
4558        pump_material_home(
4559            tester,
4560            None,
4561            Center::new()
4562                .child(Material::new().child(bar))
4563                .into_widget(),
4564        );
4565    }
4566
4567    fn pick<T>(probe: Probe, pressed: T, hovered: T, focused: T) -> T {
4568        match probe {
4569            Probe::Pressed => pressed,
4570            Probe::Hovered => hovered,
4571            Probe::Focused => focused,
4572        }
4573    }
4574
4575    // 'SearchBar focusNode is hot swappable'.
4576    #[test]
4577    fn search_bar_focus_node_is_hot_swappable() {
4578        test_widgets(|tester| {
4579            let has_focus = |tester: &WidgetTester, node: &Ref<FocusNode>| {
4580                node.handle().has_focus(&mut tester.cell.borrow_mut())
4581            };
4582            let node1 = FocusNode::new(&mut tester.cell.borrow_mut());
4583            pump_material_home(
4584                tester,
4585                None,
4586                Material::new()
4587                    .child(SearchBar::new().focus_node(node1.erase()))
4588                    .into_widget(),
4589            );
4590            assert!(!has_focus(tester, &node1));
4591            node1
4592                .handle()
4593                .request_focus(&mut tester.cell.borrow_mut(), None);
4594            tester.pump();
4595            assert!(has_focus(tester, &node1));
4596            node1
4597                .handle()
4598                .unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
4599            tester.pump();
4600            assert!(!has_focus(tester, &node1));
4601
4602            let node2 = FocusNode::new(&mut tester.cell.borrow_mut());
4603            pump_material_home(
4604                tester,
4605                None,
4606                Material::new()
4607                    .child(SearchBar::new().focus_node(node2.erase()))
4608                    .into_widget(),
4609            );
4610            assert!(!has_focus(tester, &node1));
4611            assert!(!has_focus(tester, &node2));
4612            node2
4613                .handle()
4614                .request_focus(&mut tester.cell.borrow_mut(), None);
4615            tester.pump();
4616            assert!(!has_focus(tester, &node1));
4617            assert!(has_focus(tester, &node2));
4618            node2
4619                .handle()
4620                .unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
4621            tester.pump();
4622            assert!(!has_focus(tester, &node1));
4623            assert!(!has_focus(tester, &node2));
4624
4625            pump_material_home(
4626                tester,
4627                None,
4628                Material::new().child(SearchBar::new()).into_widget(),
4629            );
4630            assert!(!has_focus(tester, &node1));
4631            assert!(!has_focus(tester, &node2));
4632            tester.tap(find::by_type::<SearchBar>());
4633            tester.pump();
4634            assert!(!has_focus(tester, &node1));
4635            assert!(!has_focus(tester, &node2));
4636        });
4637    }
4638
4639    // 'SearchBar respects leading property'.
4640    #[test]
4641    fn search_bar_respects_leading_property() {
4642        test_widgets(|tester| {
4643            let color_scheme = m3(tester).color_scheme.clone();
4644            pump_material_home(
4645                tester,
4646                None,
4647                Material::new()
4648                    .child(SearchBar::new().leading(IconButton::new(
4649                        Some(Listener::new(|_| {})),
4650                        Icon::new(Some(Icons::search())),
4651                    )))
4652                    .into_widget(),
4653            );
4654            expect(
4655                tester,
4656                &find::widget_with_icon::<IconButton>(&Icons::search()),
4657                finds_one_widget(),
4658            );
4659            let icon = tester.element(find::by_icon(&Icons::search()));
4660            let color = tester.glyph_style(icon).color.map(|color| color.color());
4661            assert_eq!(color, Some(color_scheme.on_surface()));
4662        });
4663    }
4664
4665    // 'SearchBar respects trailing property'.
4666    #[test]
4667    fn search_bar_respects_trailing_property() {
4668        test_widgets(|tester| {
4669            let color_scheme = m3(tester).color_scheme.clone();
4670            pump_material_home(
4671                tester,
4672                None,
4673                Material::new()
4674                    .child(SearchBar::new().trailing(vec![
4675                        IconButton::new(
4676                            Some(Listener::new(|_| {})),
4677                            Icon::new(Some(Icons::menu())),
4678                        )
4679                        .into_widget(),
4680                    ]))
4681                    .into_widget(),
4682            );
4683            expect(
4684                tester,
4685                &find::widget_with_icon::<IconButton>(&Icons::menu()),
4686                finds_one_widget(),
4687            );
4688            let icon = tester.element(find::by_icon(&Icons::menu()));
4689            let color = tester.glyph_style(icon).color.map(|color| color.color());
4690            assert_eq!(color, Some(color_scheme.on_surface_variant()));
4691        });
4692    }
4693
4694    // 'SearchBar respects constraints property'.
4695    #[test]
4696    fn search_bar_respects_constraints_property() {
4697        test_widgets(|tester| {
4698            let mut constraints = BoxConstraints::new();
4699            constraints.max_width = 350.0;
4700            constraints.min_height = 80.0;
4701            pump_centered_bar(tester, SearchBar::new().constraints(constraints));
4702            let bar_rect = tester.get_rect(find::by_type::<SearchBar>());
4703            assert_eq!(bar_rect.size(), Size::new(350.0, 80.0));
4704        });
4705    }
4706
4707    // 'SearchBar respects elevation property'.
4708    #[test]
4709    fn search_bar_respects_elevation_property() {
4710        test_widgets(|tester| {
4711            pump_centered_bar(
4712                tester,
4713                SearchBar::new().elevation(<dyn WidgetStateProperty<Option<f64>>>::resolve_with(
4714                    |states| {
4715                        Some(if states.contains(&WidgetState::Pressed) {
4716                            0.0
4717                        } else if states.contains(&WidgetState::Hovered) {
4718                            1.0
4719                        } else if states.contains(&WidgetState::Focused) {
4720                            2.0
4721                        } else {
4722                            3.0
4723                        })
4724                    },
4725                )),
4726            );
4727            walk_states(tester, false, |tester, probe| {
4728                assert_eq!(
4729                    search_bar_material(tester).elevation,
4730                    pick(probe, 0.0, 1.0, 2.0)
4731                );
4732            });
4733        });
4734    }
4735
4736    // 'SearchBar respects backgroundColor property'.
4737    #[test]
4738    fn search_bar_respects_background_color_property() {
4739        test_widgets(|tester| {
4740            pump_centered_bar(tester, SearchBar::new().background_color(color_property()));
4741            walk_states(tester, false, |tester, probe| {
4742                assert_eq!(
4743                    search_bar_material(tester).color,
4744                    Some(pick(
4745                        probe,
4746                        pressed_color(),
4747                        hovered_color(),
4748                        focused_color()
4749                    ))
4750                );
4751            });
4752        });
4753    }
4754
4755    // 'SearchBar respects shadowColor property'.
4756    #[test]
4757    fn search_bar_respects_shadow_color_property() {
4758        test_widgets(|tester| {
4759            pump_centered_bar(tester, SearchBar::new().shadow_color(color_property()));
4760            walk_states(tester, false, |tester, probe| {
4761                assert_eq!(
4762                    search_bar_material(tester).shadow_color,
4763                    Some(pick(
4764                        probe,
4765                        pressed_color(),
4766                        hovered_color(),
4767                        focused_color()
4768                    ))
4769                );
4770            });
4771        });
4772    }
4773
4774    // 'SearchBar respects surfaceTintColor property'.
4775    #[test]
4776    fn search_bar_respects_surface_tint_color_property() {
4777        test_widgets(|tester| {
4778            pump_centered_bar(
4779                tester,
4780                SearchBar::new().surface_tint_color(color_property()),
4781            );
4782            walk_states(tester, false, |tester, probe| {
4783                assert_eq!(
4784                    search_bar_material(tester).surface_tint_color,
4785                    Some(pick(
4786                        probe,
4787                        pressed_color(),
4788                        hovered_color(),
4789                        focused_color()
4790                    ))
4791                );
4792            });
4793        });
4794    }
4795
4796    // 'SearchBar respects overlayColor property'.
4797    #[test]
4798    fn search_bar_respects_overlay_color_property() {
4799        test_widgets(|tester| {
4800            let node = FocusNode::new(&mut tester.cell.borrow_mut());
4801            pump_centered_bar(
4802                tester,
4803                SearchBar::new()
4804                    .focus_node(node.erase())
4805                    .overlay_color(color_property()),
4806            );
4807            let ink_ops = |tester: &WidgetTester| {
4808                let ink_features = tester.first::<crate::material::RenderInkFeatures>();
4809                tester.painted_ops_deep(ink_features.as_object())
4810            };
4811            walk_states(tester, true, |tester, probe| {
4812                let color = pick(probe, pressed_color(), hovered_color(), focused_color());
4813                let ops = ink_ops(tester);
4814                match probe {
4815                    Probe::Hovered => assert_paints(&ops, &[PaintCall::rect(Some(color))]),
4816                    _ => {
4817                        assert_paints(&ops, &[PaintCall::rect(None), PaintCall::rect(Some(color))])
4818                    }
4819                }
4820            });
4821        });
4822    }
4823
4824    // 'SearchBar respects side and shape properties'.
4825    #[test]
4826    fn search_bar_respects_side_and_shape_properties() {
4827        test_widgets(|tester| {
4828            let side = |width: f64| BorderSide {
4829                width,
4830                ..BorderSide::default()
4831            };
4832            let pressed_shape = |side| {
4833                ShapeBorderRef::new(RoundedRectangleBorder::new(
4834                    side,
4835                    BorderRadiusGeometry::ZERO,
4836                ))
4837            };
4838            let hovered_shape = |side| {
4839                ShapeBorderRef::new(ContinuousRectangleBorder::new(
4840                    side,
4841                    BorderRadiusGeometry::ZERO,
4842                ))
4843            };
4844            let focused_shape = |side| ShapeBorderRef::new(CircleBorder::new(side, 0.0));
4845            pump_centered_bar(
4846                tester,
4847                SearchBar::new()
4848                    .side(<dyn WidgetStateProperty<Option<BorderSide>>>::resolve_with(
4849                        move |states| {
4850                            Some(if states.contains(&WidgetState::Pressed) {
4851                                side(2.0)
4852                            } else if states.contains(&WidgetState::Hovered) {
4853                                side(3.0)
4854                            } else if states.contains(&WidgetState::Focused) {
4855                                side(4.0)
4856                            } else {
4857                                side(5.0)
4858                            })
4859                        },
4860                    ))
4861                    .shape(
4862                        <dyn WidgetStateProperty<Option<OutlinedBorderRef>>>::resolve_with(
4863                            |states| {
4864                                Some(if states.contains(&WidgetState::Pressed) {
4865                                    RoundedRectangleBorder::default().into()
4866                                } else if states.contains(&WidgetState::Hovered) {
4867                                    ContinuousRectangleBorder::default().into()
4868                                } else if states.contains(&WidgetState::Focused) {
4869                                    CircleBorder::default().into()
4870                                } else {
4871                                    StadiumBorder::default().into()
4872                                })
4873                            },
4874                        ),
4875                    ),
4876            );
4877            walk_states(tester, false, |tester, probe| {
4878                let expected = match probe {
4879                    Probe::Pressed => pressed_shape(side(2.0)),
4880                    Probe::Hovered => hovered_shape(side(3.0)),
4881                    Probe::Focused => focused_shape(side(4.0)),
4882                };
4883                assert_eq!(search_bar_material(tester).shape, Some(expected));
4884            });
4885        });
4886    }
4887
4888    // 'SearchBar respects padding property'.
4889    #[test]
4890    fn search_bar_respects_padding_property() {
4891        test_widgets(|tester| {
4892            pump_centered_bar(
4893                tester,
4894                SearchBar::new()
4895                    .leading(Icon::new(Some(Icons::search())))
4896                    .padding(<dyn WidgetStateProperty<Option<EdgeInsetsGeometry>>>::all(
4897                        Some(EdgeInsets::all(16.0).into()),
4898                    ))
4899                    .trailing(vec![Icon::new(Some(Icons::menu())).into_widget()]),
4900            );
4901            let bar_rect = tester.get_rect(find::by_type::<SearchBar>());
4902            let leading_rect = tester.get_rect(find::by_icon(&Icons::search()));
4903            let text_field_rect = tester.get_rect(find::by_type::<TextField>());
4904            let trailing_rect = tester.get_rect(find::by_icon(&Icons::menu()));
4905            assert_eq!(bar_rect.left, leading_rect.left - 16.0);
4906            assert_eq!(leading_rect.right, text_field_rect.left - 16.0);
4907            assert_eq!(text_field_rect.right, trailing_rect.left - 16.0);
4908            assert_eq!(trailing_rect.right, bar_rect.right - 16.0);
4909        });
4910    }
4911
4912    // 'SearchBar respects hintStyle property'.
4913    #[test]
4914    fn search_bar_respects_hint_style_property() {
4915        test_widgets(|tester| {
4916            let style = text_style_property(tester);
4917            pump_centered_bar(
4918                tester,
4919                SearchBar::new().hint_text("hint text").hint_style(style),
4920            );
4921            walk_states(tester, false, |tester, probe| {
4922                let color = tester
4923                    .widget(find::text("hint text"), |text: &Text| text.style.clone())
4924                    .and_then(|style| style.color)
4925                    .map(|color| color.color());
4926                assert_eq!(
4927                    color,
4928                    Some(pick(
4929                        probe,
4930                        pressed_color(),
4931                        hovered_color(),
4932                        focused_color()
4933                    ))
4934                );
4935            });
4936        });
4937    }
4938
4939    // 'SearchBar respects textStyle property'.
4940    #[test]
4941    fn search_bar_respects_text_style_property() {
4942        test_widgets(|tester| {
4943            let controller = {
4944                let mut app = tester.cell.borrow_mut();
4945                TextEditingController::new(&mut app).text(&mut app, "input text")
4946            };
4947            let style = text_style_property(tester);
4948            pump_centered_bar(
4949                tester,
4950                SearchBar::new()
4951                    .controller(controller.erase())
4952                    .text_style(style),
4953            );
4954            walk_states(tester, false, |tester, probe| {
4955                let color = tester
4956                    .widget(find::text("input text"), |text: &EditableText| {
4957                        text.style.clone()
4958                    })
4959                    .color
4960                    .map(|color| color.color());
4961                assert_eq!(
4962                    color,
4963                    Some(pick(
4964                        probe,
4965                        pressed_color(),
4966                        hovered_color(),
4967                        focused_color()
4968                    ))
4969                );
4970            });
4971        });
4972    }
4973
4974    fn empty_suggestions()
4975    -> impl Fn(&mut App, BuildContext, Handle<SearchController>) -> Task<Vec<WidgetRef>> {
4976        |_app, _context, _controller| Task::ready(Vec::new())
4977    }
4978
4979    fn text_field_in_view() -> waft_widgets::testing::Finder {
4980        find::descendant(view_content(), find::by_type::<TextField>())
4981    }
4982
4983    fn text_field_focus_node(
4984        tester: &WidgetTester,
4985        finder: waft_widgets::testing::Finder,
4986    ) -> FocusNodeRef {
4987        tester
4988            .widget(finder, |field: &TextField| field.focus_node.clone())
4989            .expect("the text field has a focus node")
4990    }
4991
4992    // 'SearchAnchor respects viewOnChanged and viewOnSubmitted properties'.
4993    #[test]
4994    fn search_anchor_respects_view_on_changed_and_view_on_submitted_properties() {
4995        test_widgets(|tester| {
4996            let controller = SearchController::new(&mut tester.cell.borrow_mut());
4997            let handle = controller.handle();
4998            let changed = Rc::new(Cell::new(0));
4999            let submitted = Rc::new(Cell::new(0));
5000            let anchor = SearchAnchor::new(
5001                |_app, _context, controller| {
5002                    SearchBar::new()
5003                        .on_tap(Listener::new(move |app: &mut App| {
5004                            if !controller.is_open(app) {
5005                                controller.open_view(app);
5006                            }
5007                        }))
5008                        .into_widget()
5009                },
5010                empty_suggestions(),
5011            )
5012            .search_controller(controller.clone())
5013            .view_on_changed({
5014                let changed = Rc::clone(&changed);
5015                move |_, _| changed.set(changed.get() + 1)
5016            })
5017            .view_on_submitted({
5018                let submitted = Rc::clone(&submitted);
5019                move |app: &mut App, value| {
5020                    submitted.set(submitted.get() + 1);
5021                    handle.close_view(app, Some(value));
5022                }
5023            });
5024            pump_centered_material(tester, anchor);
5025            tester.tap(find::by_type::<SearchBar>());
5026            tester.pump_and_settle();
5027            assert!(controller.handle().is_open(&tester.cell.borrow()));
5028
5029            tester.enter_text(text_field_in_view(), "a");
5030            assert_eq!(changed.get(), 1);
5031            tester.enter_text(text_field_in_view(), "abc");
5032            assert_eq!(changed.get(), 2);
5033
5034            tester
5035                .test_text_input()
5036                .receive_action(TextInputAction::Done);
5037            assert_eq!(submitted.get(), 1);
5038            assert!(!controller.handle().is_open(&tester.cell.borrow()));
5039        });
5040    }
5041
5042    fn pump_centered_material<K>(tester: &mut WidgetTester, child: impl IntoWidget<K>) {
5043        pump_material_home(
5044            tester,
5045            None,
5046            Center::new()
5047                .child(Material::new().child(child))
5048                .into_widget(),
5049        );
5050    }
5051
5052    // 'SearchAnchor.bar respects onChanged and onSubmitted properties'.
5053    #[test]
5054    fn search_anchor_bar_respects_on_changed_and_on_submitted_properties() {
5055        test_widgets(|tester| {
5056            let controller = SearchController::new(&mut tester.cell.borrow_mut());
5057            let handle = controller.handle();
5058            let changed = Rc::new(Cell::new(0));
5059            let submitted = Rc::new(Cell::new(0));
5060            let anchor = SearchAnchor::bar(empty_suggestions())
5061                .search_controller(controller.clone())
5062                .on_submitted({
5063                    let submitted = Rc::clone(&submitted);
5064                    move |app: &mut App, value| {
5065                        submitted.set(submitted.get() + 1);
5066                        handle.close_view(app, Some(value));
5067                    }
5068                })
5069                .on_changed({
5070                    let changed = Rc::clone(&changed);
5071                    move |_, _| changed.set(changed.get() + 1)
5072                });
5073            pump_centered_material(tester, anchor.into_search_anchor());
5074            tester.tap(find::by_type::<SearchBar>());
5075            tester.pump_and_settle();
5076            assert!(controller.handle().is_open(&tester.cell.borrow()));
5077
5078            tester.enter_text(text_field_in_view(), "a");
5079            assert_eq!(changed.get(), 1);
5080            tester.enter_text(text_field_in_view(), "abc");
5081            assert_eq!(changed.get(), 2);
5082
5083            tester
5084                .test_text_input()
5085                .receive_action(TextInputAction::Done);
5086            assert_eq!(submitted.get(), 1);
5087            assert!(!controller.handle().is_open(&tester.cell.borrow()));
5088        });
5089    }
5090
5091    // 'SearchAnchor.bar anchor loses focus after view closes'.
5092    #[test]
5093    fn search_anchor_bar_anchor_loses_focus_after_view_closes() {
5094        test_widgets(|tester| {
5095            let controller = SearchController::new(&mut tester.cell.borrow_mut());
5096            let handle = controller.handle();
5097            let submitted = Rc::new(Cell::new(0));
5098            let anchor = SearchAnchor::bar(empty_suggestions())
5099                .search_controller(controller.clone())
5100                .on_submitted({
5101                    let submitted = Rc::clone(&submitted);
5102                    move |app: &mut App, value| {
5103                        submitted.set(submitted.get() + 1);
5104                        handle.close_view(app, Some(value));
5105                    }
5106                });
5107            pump_centered_material(tester, anchor.into_search_anchor());
5108            tester.tap(find::by_type::<SearchBar>());
5109            tester.pump_and_settle();
5110            assert!(controller.handle().is_open(&tester.cell.borrow()));
5111
5112            let anchor_text_field = find::descendant(
5113                find::by_type::<SearchBar>().first(),
5114                find::by_type::<TextField>(),
5115            );
5116            let view_node = text_field_focus_node(tester, text_field_in_view());
5117            assert!(view_node.handle().has_focus(&tester.cell.borrow_mut()));
5118
5119            tester
5120                .test_text_input()
5121                .receive_action(TextInputAction::Done);
5122            tester.pump_and_settle();
5123            assert_eq!(submitted.get(), 1);
5124            assert!(!controller.handle().is_open(&tester.cell.borrow()));
5125
5126            let anchor_node = text_field_focus_node(tester, anchor_text_field);
5127            assert!(!anchor_node.handle().has_focus(&tester.cell.borrow_mut()));
5128        });
5129    }
5130
5131    // 'hintStyle can override textStyle for hintText'.
5132    #[test]
5133    fn hint_style_can_override_text_style_for_hint_text() {
5134        test_widgets(|tester| {
5135            let style = text_style_property(tester);
5136            pump_centered_bar(
5137                tester,
5138                SearchBar::new()
5139                    .hint_text("hint text")
5140                    .hint_style(style)
5141                    .text_style(<dyn WidgetStateProperty<Option<TextStyle>>>::all(Some(
5142                        TextStyle::new().color(Colors::PINK.primary()),
5143                    ))),
5144            );
5145            walk_states(tester, false, |tester, probe| {
5146                let color = tester
5147                    .widget(find::text("hint text"), |text: &Text| text.style.clone())
5148                    .and_then(|style| style.color)
5149                    .map(|color| color.color());
5150                assert_eq!(
5151                    color,
5152                    Some(pick(
5153                        probe,
5154                        pressed_color(),
5155                        hovered_color(),
5156                        focused_color()
5157                    ))
5158                );
5159            });
5160        });
5161    }
5162
5163    // 'The text is still centered when SearchBar text field is smaller than 48'.
5164    #[test]
5165    fn the_text_is_still_centered_when_the_search_bar_text_field_is_smaller_than_48() {
5166        test_widgets(|tester| {
5167            let mut constraints = BoxConstraints::new();
5168            constraints.min_height = 35.0;
5169            constraints.max_height = 35.0;
5170            pump_centered_bar(tester, SearchBar::new().constraints(constraints));
5171            tester.enter_text(find::by_type::<TextField>(), "input text");
5172            let text_center_y = tester.get_center(find::text("input text")).dy();
5173            let search_bar_center_y = tester.get_center(find::by_type::<SearchBar>()).dy();
5174            assert_eq!(text_center_y, search_bar_center_y);
5175        });
5176    }
5177
5178    /// The anchor most view cases build: an icon button that opens the view, with no suggestions.
5179    fn view_anchor() -> SearchAnchor {
5180        SearchAnchor::new(
5181            |_app, _context, controller| {
5182                IconButton::new(
5183                    Some(Listener::new(move |app: &mut App| {
5184                        controller.open_view(app)
5185                    })),
5186                    Icon::new(Some(Icons::search())),
5187                )
5188                .into_widget()
5189            },
5190            empty_suggestions(),
5191        )
5192    }
5193
5194    fn open_view_of(tester: &mut WidgetTester, anchor: SearchAnchor) {
5195        pump_material_home(tester, None, Material::new().child(anchor).into_widget());
5196        tester.tap(find::widget_with_icon::<IconButton>(&Icons::search()));
5197        tester.pump_and_settle();
5198    }
5199
5200    fn view_divider_color(tester: &WidgetTester) -> Color {
5201        tester.widget(
5202            find::descendant(find::by_type::<Divider>(), find::by_type::<Container>()).first(),
5203            |container: &Container| {
5204                container
5205                    .decoration
5206                    .as_ref()
5207                    .expect("the container has a decoration")
5208                    .as_any()
5209                    .downcast_ref::<BoxDecoration>()
5210                    .expect("a BoxDecoration")
5211                    .border
5212                    .as_ref()
5213                    .expect("the decoration has a border")
5214                    .as_any()
5215                    .downcast_ref::<Border>()
5216                    .expect("a Border")
5217                    .bottom
5218                    .color
5219            },
5220        )
5221    }
5222
5223    fn first_view_padding(tester: &WidgetTester) -> EdgeInsetsGeometry {
5224        tester.widget(
5225            find::descendant(view_content(), find::by_type::<Padding>()).first(),
5226            |padding: &Padding| padding.padding,
5227        )
5228    }
5229
5230    // 'SearchAnchor respects viewBuilder property'.
5231    #[test]
5232    fn search_anchor_respects_view_builder_property() {
5233        test_widgets(|tester| {
5234            open_view_of(tester, view_anchor());
5235            // Default is a ListView.
5236            expect(tester, &find::by_type::<ListView>(), finds_one_widget());
5237
5238            tester.pump_widget(Container::new());
5239            open_view_of(
5240                tester,
5241                view_anchor().view_builder(|_app, suggestions| {
5242                    GridView::count(5).children(suggestions).into_widget()
5243                }),
5244            );
5245            expect(tester, &find::by_type::<ListView>(), finds_nothing());
5246            expect(tester, &find::by_type::<GridView>(), finds_one_widget());
5247        });
5248    }
5249
5250    // 'SearchAnchor.bar respects viewBuilder property'.
5251    #[test]
5252    fn search_anchor_bar_respects_view_builder_property() {
5253        test_widgets(|tester| {
5254            pump_material_home(
5255                tester,
5256                None,
5257                Material::new()
5258                    .child(SearchAnchor::bar(empty_suggestions()).into_search_anchor())
5259                    .into_widget(),
5260            );
5261            tester.tap(find::by_icon(&Icons::search()));
5262            tester.pump_and_settle();
5263            expect(tester, &find::by_type::<ListView>(), finds_one_widget());
5264
5265            tester.pump_widget(Container::new());
5266            pump_material_home(
5267                tester,
5268                None,
5269                Material::new()
5270                    .child(
5271                        SearchAnchor::bar(empty_suggestions())
5272                            .view_builder(|_app, suggestions| {
5273                                GridView::count(5).children(suggestions).into_widget()
5274                            })
5275                            .into_search_anchor(),
5276                    )
5277                    .into_widget(),
5278            );
5279            tester.tap(find::by_icon(&Icons::search()));
5280            tester.pump_and_settle();
5281            expect(tester, &find::by_type::<ListView>(), finds_nothing());
5282            expect(tester, &find::by_type::<GridView>(), finds_one_widget());
5283        });
5284    }
5285
5286    // 'SearchAnchor respects viewLeading property'.
5287    #[test]
5288    fn search_anchor_respects_view_leading_property() {
5289        test_widgets(|tester| {
5290            open_view_of(tester, view_anchor());
5291            // Default is an icon button with arrow_back.
5292            expect(tester, &find::by_type::<BackButton>(), finds_one_widget());
5293
5294            tester.pump_widget(Container::new());
5295            open_view_of(
5296                tester,
5297                view_anchor().view_leading(Icon::new(Some(Icons::history()))),
5298            );
5299            expect(tester, &find::by_type::<BackButton>(), finds_nothing());
5300            expect(
5301                tester,
5302                &find::by_icon(&Icons::history()),
5303                finds_one_widget(),
5304            );
5305        });
5306    }
5307
5308    // 'SearchAnchor respects viewTrailing property'.
5309    #[test]
5310    fn search_anchor_respects_view_trailing_property() {
5311        test_widgets(|tester| {
5312            open_view_of(tester, view_anchor());
5313            // Default is an icon button with a close icon when the input is not empty.
5314            tester.enter_text(find::by_type::<TextField>(), "a");
5315            tester.pump();
5316            expect(
5317                tester,
5318                &find::widget_with_icon::<IconButton>(&Icons::close()),
5319                finds_one_widget(),
5320            );
5321
5322            tester.pump_widget(Container::new());
5323            open_view_of(
5324                tester,
5325                view_anchor().view_trailing(vec![Icon::new(Some(Icons::history())).into_widget()]),
5326            );
5327            expect(tester, &find::by_icon(&Icons::close()), finds_nothing());
5328            expect(
5329                tester,
5330                &find::by_icon(&Icons::history()),
5331                finds_one_widget(),
5332            );
5333        });
5334    }
5335
5336    // 'SearchAnchor respects viewHintText property'.
5337    #[test]
5338    fn search_anchor_respects_view_hint_text_property() {
5339        test_widgets(|tester| {
5340            open_view_of(tester, view_anchor().view_hint_text("hint text"));
5341            expect(tester, &find::text("hint text"), finds_one_widget());
5342        });
5343    }
5344
5345    // 'SearchAnchor respects viewBackgroundColor property'.
5346    #[test]
5347    fn search_anchor_respects_view_background_color_property() {
5348        test_widgets(|tester| {
5349            open_view_of(
5350                tester,
5351                view_anchor().view_background_color(Colors::PURPLE.primary()),
5352            );
5353            assert_eq!(
5354                search_view_material(tester).color,
5355                Some(Colors::PURPLE.primary())
5356            );
5357        });
5358    }
5359
5360    // 'SearchAnchor respects viewElevation property'.
5361    #[test]
5362    fn search_anchor_respects_view_elevation_property() {
5363        test_widgets(|tester| {
5364            open_view_of(tester, view_anchor().view_elevation(3.0));
5365            assert_eq!(search_view_material(tester).elevation, 3.0);
5366        });
5367    }
5368
5369    // 'SearchAnchor respects viewSurfaceTint property'.
5370    #[test]
5371    fn search_anchor_respects_view_surface_tint_property() {
5372        test_widgets(|tester| {
5373            open_view_of(
5374                tester,
5375                view_anchor().view_surface_tint_color(Colors::PURPLE.primary()),
5376            );
5377            assert_eq!(
5378                search_view_material(tester).surface_tint_color,
5379                Some(Colors::PURPLE.primary())
5380            );
5381        });
5382    }
5383
5384    // 'SearchAnchor respects viewSide property'.
5385    #[test]
5386    fn search_anchor_respects_view_side_property() {
5387        test_widgets(|tester| {
5388            let side = BorderSide {
5389                color: Colors::PURPLE.primary(),
5390                width: 5.0,
5391                ..BorderSide::default()
5392            };
5393            open_view_of(tester, view_anchor().is_full_screen(false).view_side(side));
5394            assert_eq!(
5395                search_view_material(tester).shape,
5396                Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
5397                    side,
5398                    BorderRadiusGeometry::circular(28.0),
5399                )))
5400            );
5401        });
5402    }
5403
5404    // 'SearchAnchor respects viewShape property'.
5405    #[test]
5406    fn search_anchor_respects_view_shape_property() {
5407        test_widgets(|tester| {
5408            let side = BorderSide {
5409                color: Colors::PURPLE.primary(),
5410                width: 5.0,
5411                ..BorderSide::default()
5412            };
5413            let shape = StadiumBorder::new(side);
5414            open_view_of(
5415                tester,
5416                view_anchor().is_full_screen(false).view_shape(shape),
5417            );
5418            assert_eq!(
5419                search_view_material(tester).shape,
5420                Some(ShapeBorderRef::new(shape))
5421            );
5422        });
5423    }
5424
5425    // 'SearchAnchor respects headerTextStyle property'.
5426    #[test]
5427    fn search_anchor_respects_header_text_style_property() {
5428        test_widgets(|tester| {
5429            let body_large = m3(tester).text_theme.body_large.clone().expect("bodyLarge");
5430            open_view_of(
5431                tester,
5432                view_anchor()
5433                    .header_text_style(body_large.copy_with().color(Colors::RED.primary())),
5434            );
5435            tester.enter_text(find::by_type::<SearchBar>(), "input text");
5436            tester.pump_and_settle();
5437            let style = tester.widget(find::text("input text"), |text: &EditableText| {
5438                text.style.clone()
5439            });
5440            assert_eq!(
5441                style.color.map(|color| color.color()),
5442                Some(Colors::RED.primary())
5443            );
5444        });
5445    }
5446
5447    // 'SearchAnchor respects headerHintStyle property'.
5448    #[test]
5449    fn search_anchor_respects_header_hint_style_property() {
5450        test_widgets(|tester| {
5451            let body_large = m3(tester).text_theme.body_large.clone().expect("bodyLarge");
5452            open_view_of(
5453                tester,
5454                view_anchor()
5455                    .view_hint_text("hint text")
5456                    .header_hint_style(body_large.copy_with().color(Colors::ORANGE.primary())),
5457            );
5458            let style = tester
5459                .widget(find::text("hint text"), |text: &Text| text.style.clone())
5460                .expect("a style");
5461            assert_eq!(
5462                style.color.map(|color| color.color()),
5463                Some(Colors::ORANGE.primary())
5464            );
5465        });
5466    }
5467
5468    // 'SearchAnchor respects viewPadding property'.
5469    #[test]
5470    fn search_anchor_respects_view_padding_property() {
5471        test_widgets(|tester| {
5472            open_view_of(
5473                tester,
5474                view_anchor()
5475                    .is_full_screen(false)
5476                    .view_padding(EdgeInsets::all(16.0)),
5477            );
5478            assert_eq!(first_view_padding(tester), EdgeInsets::all(16.0).into());
5479        });
5480    }
5481
5482    // 'SearchAnchor ignores viewPadding property if full screen'.
5483    #[test]
5484    fn search_anchor_ignores_view_padding_property_if_full_screen() {
5485        test_widgets(|tester| {
5486            open_view_of(
5487                tester,
5488                view_anchor()
5489                    .is_full_screen(true)
5490                    .view_padding(EdgeInsets::all(16.0)),
5491            );
5492            assert_eq!(first_view_padding(tester), EdgeInsets::ZERO.into());
5493        });
5494    }
5495
5496    // 'SearchAnchor respects shrinkWrap property'.
5497    #[test]
5498    fn search_anchor_respects_shrink_wrap_property() {
5499        test_widgets(|tester| {
5500            let anchor = SearchAnchor::new(
5501                |_app, _context, controller| {
5502                    IconButton::new(
5503                        Some(Listener::new(move |app: &mut App| {
5504                            controller.open_view(app)
5505                        })),
5506                        Icon::new(Some(Icons::search())),
5507                    )
5508                    .into_widget()
5509                },
5510                |app, _context, controller| {
5511                    let length = controller.text_value(app).chars().count();
5512                    Task::ready(
5513                        (0..length)
5514                            .map(|index| {
5515                                ListTile::new()
5516                                    .title(Text::new(format!("Item {index}")))
5517                                    .into_widget()
5518                            })
5519                            .collect(),
5520                    )
5521                },
5522            )
5523            .is_full_screen(false)
5524            .shrink_wrap(true)
5525            .view_constraints(BoxConstraints::new());
5526            open_view_of(tester, anchor);
5527
5528            let divider = find::descendant(view_content(), find::by_type::<Divider>());
5529            // The divider is not shown if there are no suggestions.
5530            expect(tester, &divider, finds_nothing());
5531            let material = find::descendant(view_content(), find::by_type::<Material>()).first();
5532            assert_eq!(
5533                tester.get_rect(material.clone()),
5534                Rect::from_ltrb(0.0, 0.0, 800.0, 56.0)
5535            );
5536
5537            tester.enter_text(find::by_type::<SearchBar>(), "a");
5538            tester.pump_and_settle();
5539            expect(tester, &divider, finds_one_widget());
5540            assert_eq!(
5541                tester.get_rect(material),
5542                Rect::from_ltrb(0.0, 0.0, 800.0, 113.0)
5543            );
5544        });
5545    }
5546
5547    // 'SearchAnchor respects dividerColor property'.
5548    #[test]
5549    fn search_anchor_respects_divider_color_property() {
5550        test_widgets(|tester| {
5551            open_view_of(tester, view_anchor().divider_color(Colors::RED.primary()));
5552            assert_eq!(view_divider_color(tester), Colors::RED.primary());
5553        });
5554    }
5555
5556    // 'SearchAnchor respects viewConstraints property'.
5557    #[test]
5558    fn search_anchor_respects_view_constraints_property() {
5559        test_widgets(|tester| {
5560            pump_material_home(
5561                tester,
5562                None,
5563                Material::new()
5564                    .child(
5565                        Center::new().child(
5566                            view_anchor()
5567                                .is_full_screen(false)
5568                                .view_constraints(BoxConstraints::tight(Size::new(280.0, 390.0))),
5569                        ),
5570                    )
5571                    .into_widget(),
5572            );
5573            tester.tap(find::widget_with_icon::<IconButton>(&Icons::search()));
5574            tester.pump_and_settle();
5575            let size = search_view_size(tester);
5576            assert_eq!(size.width(), 280.0);
5577            assert_eq!(size.height(), 390.0);
5578        });
5579    }
5580
5581    // 'SearchAnchor respects viewBarPadding property'.
5582    #[test]
5583    fn search_anchor_respects_view_bar_padding_property() {
5584        test_widgets(|tester| {
5585            pump_material_home(
5586                tester,
5587                None,
5588                Material::new()
5589                    .child(
5590                        Center::new().child(
5591                            view_anchor().view_bar_padding(EdgeInsets::symmetric(0.0, 16.0)),
5592                        ),
5593                    )
5594                    .into_widget(),
5595            );
5596            tester.tap(find::widget_with_icon::<IconButton>(&Icons::search()));
5597            tester.pump_and_settle();
5598            let search_bar = find::descendant(view_content(), find::by_type::<SearchBar>()).first();
5599            let padding = tester.widget(
5600                find::descendant(search_bar, find::by_type::<Padding>()).first(),
5601                |padding: &Padding| padding.padding,
5602            );
5603            assert_eq!(padding, EdgeInsets::symmetric(0.0, 16.0).into());
5604        });
5605    }
5606
5607    fn top_center_anchor(direction: TextDirection) -> WidgetRef {
5608        Directionality::new(
5609            direction,
5610            Material::new().child(
5611                Align::new().alignment(AlignmentGeometry::TOP_CENTER).child(
5612                    SearchAnchor::new(
5613                        |_app, _context, _controller| {
5614                            Icon::new(Some(Icons::search())).into_widget()
5615                        },
5616                        empty_suggestions(),
5617                    )
5618                    .is_full_screen(false),
5619                ),
5620            ),
5621        )
5622        .into_widget()
5623    }
5624
5625    // 'SearchAnchor respects builder property - LTR'.
5626    #[test]
5627    fn search_anchor_respects_builder_property_ltr() {
5628        test_widgets(|tester| {
5629            pump_material_home(tester, None, top_center_anchor(TextDirection::Ltr));
5630            let anchor_rect = tester.get_rect(find::by_icon(&Icons::search()));
5631            assert_eq!(anchor_rect.size(), Size::new(24.0, 24.0));
5632            assert_eq!(anchor_rect, Rect::from_ltrb(388.0, 0.0, 412.0, 24.0));
5633
5634            tester.tap(find::by_icon(&Icons::search()));
5635            tester.pump_and_settle();
5636            let search_view_rect = tester.get_rect(
5637                find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
5638            );
5639            assert_eq!(search_view_rect, Rect::from_ltrb(388.0, 0.0, 748.0, 400.0));
5640            // The search view's top left is the anchor's.
5641            assert_eq!(search_view_rect.top_left(), anchor_rect.top_left());
5642        });
5643    }
5644
5645    // 'SearchAnchor respects builder property - RTL'.
5646    #[test]
5647    fn search_anchor_respects_builder_property_rtl() {
5648        test_widgets(|tester| {
5649            pump_material_home(tester, None, top_center_anchor(TextDirection::Rtl));
5650            let anchor_rect = tester.get_rect(find::by_icon(&Icons::search()));
5651            assert_eq!(anchor_rect.size(), Size::new(24.0, 24.0));
5652            assert_eq!(anchor_rect, Rect::from_ltrb(388.0, 0.0, 412.0, 24.0));
5653
5654            tester.tap(find::by_icon(&Icons::search()));
5655            tester.pump_and_settle();
5656            let search_view_rect = tester.get_rect(
5657                find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
5658            );
5659            assert_eq!(search_view_rect, Rect::from_ltrb(52.0, 0.0, 412.0, 400.0));
5660            // The search view's top right is the anchor's.
5661            assert_eq!(search_view_rect.top_right(), anchor_rect.top_right());
5662        });
5663    }
5664
5665    fn set_view_size(tester: &WidgetTester, width: f64, height: f64) {
5666        tester.view().set_physical_size(Size::new(width, height));
5667        tester.view().set_device_pixel_ratio(1.0);
5668    }
5669
5670    fn bottom_corner_anchor(
5671        alignment: AlignmentGeometry,
5672        direction: TextDirection,
5673        is_full_screen: bool,
5674    ) -> WidgetRef {
5675        Directionality::new(
5676            direction,
5677            Material::new().child(
5678                Align::new()
5679                    .alignment(alignment)
5680                    .child(view_anchor().is_full_screen(is_full_screen)),
5681            ),
5682        )
5683        .into_widget()
5684    }
5685
5686    // 'Search view does not go off the screen - RTL'.
5687    #[test]
5688    fn search_view_does_not_go_off_the_screen_rtl() {
5689        test_widgets(|tester| {
5690            pump_material_home(
5691                tester,
5692                None,
5693                bottom_corner_anchor(AlignmentGeometry::BOTTOM_LEFT, TextDirection::Rtl, false),
5694            );
5695            let find_icon_button = find::widget_with_icon::<IconButton>(&Icons::search());
5696            assert_eq!(
5697                tester.get_rect(find_icon_button),
5698                Rect::from_ltrb(0.0, 552.0, 48.0, 600.0)
5699            );
5700            tester.tap(find::by_icon(&Icons::search()));
5701            tester.pump_and_settle();
5702            let search_view_rect = tester.get_rect(
5703                find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
5704            );
5705            assert_eq!(search_view_rect, Rect::from_ltrb(0.0, 200.0, 360.0, 600.0));
5706        });
5707    }
5708
5709    fn smaller_window_anchor(direction: TextDirection) -> WidgetRef {
5710        Directionality::new(
5711            direction,
5712            Material::new().child(
5713                SearchAnchor::new(
5714                    |_app, _context, controller| {
5715                        Align::new()
5716                            .alignment(AlignmentGeometry::BOTTOM_RIGHT)
5717                            .child(IconButton::new(
5718                                Some(Listener::new(move |app: &mut App| {
5719                                    controller.open_view(app)
5720                                })),
5721                                Icon::new(Some(Icons::search())),
5722                            ))
5723                            .into_widget()
5724                    },
5725                    empty_suggestions(),
5726                )
5727                .is_full_screen(false),
5728            ),
5729        )
5730        .into_widget()
5731    }
5732
5733    // 'Search view becomes smaller if the window size is smaller than the view size'.
5734    #[test]
5735    fn search_view_becomes_smaller_if_the_window_size_is_smaller_than_the_view_size() {
5736        test_widgets(|tester| {
5737            set_view_size(tester, 200.0, 200.0);
5738            for direction in [TextDirection::Ltr, TextDirection::Rtl] {
5739                if direction == TextDirection::Rtl {
5740                    tester.pump_widget(Container::new());
5741                }
5742                pump_material_home(tester, None, smaller_window_anchor(direction));
5743                // The icon button size is (48.0, 48.0), and the screen size is (200.0, 200.0).
5744                assert_eq!(
5745                    tester.get_rect(find::widget_with_icon::<IconButton>(&Icons::search())),
5746                    Rect::from_ltrb(152.0, 152.0, 200.0, 200.0)
5747                );
5748                tester.tap(find::by_icon(&Icons::search()));
5749                tester.pump_and_settle();
5750                let search_view_rect = tester.get_rect(
5751                    find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
5752                );
5753                assert_eq!(search_view_rect, Rect::from_ltrb(0.0, 0.0, 200.0, 200.0));
5754            }
5755        });
5756    }
5757
5758    fn window_size_change_anchor(is_full_screen: bool) -> WidgetRef {
5759        Material::new()
5760            .child(
5761                SearchAnchor::new(
5762                    |_app, _context, controller| {
5763                        Align::new()
5764                            .alignment(AlignmentGeometry::BOTTOM_RIGHT)
5765                            .child(IconButton::new(
5766                                Some(Listener::new(move |app: &mut App| {
5767                                    controller.open_view(app)
5768                                })),
5769                                Icon::new(Some(Icons::search())),
5770                            ))
5771                            .into_widget()
5772                    },
5773                    empty_suggestions(),
5774                )
5775                .is_full_screen(is_full_screen),
5776            )
5777            .into_widget()
5778    }
5779
5780    // 'Docked search view route is popped if the window size changes'.
5781    #[test]
5782    fn docked_search_view_route_is_popped_if_the_window_size_changes() {
5783        test_widgets(|tester| {
5784            set_view_size(tester, 500.0, 600.0);
5785            pump_material_home(tester, None, window_size_change_anchor(false));
5786            tester.tap(find::by_icon(&Icons::search()));
5787            tester.pump_and_settle();
5788            expect(tester, &find::by_type::<BackButton>(), finds_one_widget());
5789
5790            set_view_size(tester, 250.0, 200.0);
5791            tester.pump_and_settle();
5792            expect(tester, &find::by_type::<BackButton>(), finds_nothing());
5793        });
5794    }
5795
5796    // 'Full-screen search view route should stay if the window size changes'.
5797    #[test]
5798    fn full_screen_search_view_route_should_stay_if_the_window_size_changes() {
5799        test_widgets(|tester| {
5800            set_view_size(tester, 500.0, 600.0);
5801            pump_material_home(tester, None, window_size_change_anchor(true));
5802            tester.tap(find::by_icon(&Icons::search()));
5803            tester.pump_and_settle();
5804            expect(tester, &find::by_type::<BackButton>(), finds_one_widget());
5805
5806            set_view_size(tester, 250.0, 200.0);
5807            tester.pump_and_settle();
5808            expect(tester, &find::by_type::<BackButton>(), finds_one_widget());
5809        });
5810    }
5811
5812    // 'Search view route does not throw exception during pop animation'.
5813    #[test]
5814    fn search_view_route_does_not_throw_exception_during_pop_animation() {
5815        test_widgets(|tester| {
5816            let anchor = SearchAnchor::new(
5817                |_app, _context, controller| {
5818                    IconButton::new(
5819                        Some(Listener::new(move |app: &mut App| {
5820                            controller.open_view(app)
5821                        })),
5822                        Icon::new(Some(Icons::search())),
5823                    )
5824                    .into_widget()
5825                },
5826                |_app, _context, _controller| {
5827                    Task::ready(
5828                        (0..5)
5829                            .map(|index| {
5830                                ListTile::new()
5831                                    .leading(Icon::new(Some(Icons::history())))
5832                                    .title(Text::new(format!("item {index}")))
5833                                    .trailing(Icon::new(Some(Icons::chevron_right())))
5834                                    .on_tap(Listener::new(|_| {}))
5835                                    .into_widget()
5836                            })
5837                            .collect(),
5838                    )
5839                },
5840            );
5841            pump_material_home(
5842                tester,
5843                None,
5844                Material::new()
5845                    .child(Center::new().child(anchor))
5846                    .into_widget(),
5847            );
5848            tester.tap(find::by_icon(&Icons::search()));
5849            tester.pump_and_settle();
5850            tester.tap(find::by_type::<BackButton>());
5851            tester.pump_and_settle();
5852        });
5853    }
5854
5855    fn pump_padded_navigator_anchor(
5856        tester: &mut WidgetTester,
5857        alignment: Option<AlignmentGeometry>,
5858    ) {
5859        let theme = m3(tester);
5860        let mut anchor: WidgetRef = view_anchor().is_full_screen(false).into_widget();
5861        if let Some(alignment) = alignment {
5862            anchor = Align::new()
5863                .alignment(alignment)
5864                .child(anchor)
5865                .into_widget();
5866        }
5867        tester.pump_widget(
5868            crate::app::MaterialApp::new()
5869                .theme(theme)
5870                .builder(|_app, _context, child| {
5871                    Scaffold::new()
5872                        .body(
5873                            Padding::new(EdgeInsetsGeometry::from(EdgeInsets::all(100.0)))
5874                                .child(child.expect("the navigator").clone()),
5875                        )
5876                        .into_widget()
5877                })
5878                .home(Material::new().child(anchor).into_widget()),
5879        );
5880    }
5881
5882    // 'Docked search should position itself correctly based on closest navigator'.
5883    #[test]
5884    fn docked_search_should_position_itself_correctly_based_on_closest_navigator() {
5885        test_widgets(|tester| {
5886            pump_padded_navigator_anchor(tester, None);
5887            tester.tap(find::by_icon(&Icons::search()));
5888            tester.pump_and_settle();
5889            let search_view_rect = tester.get_rect(
5890                find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
5891            );
5892            assert_eq!(search_view_rect.top_left(), Offset::new(100.0, 100.0));
5893        });
5894    }
5895
5896    // 'Docked search view with nested navigator does not go off the screen'.
5897    #[test]
5898    fn docked_search_view_with_nested_navigator_does_not_go_off_the_screen() {
5899        test_widgets(|tester| {
5900            set_view_size(tester, 400.0, 400.0);
5901            pump_padded_navigator_anchor(tester, Some(AlignmentGeometry::BOTTOM_RIGHT));
5902            tester.tap(find::by_icon(&Icons::search()));
5903            tester.pump_and_settle();
5904            let search_view_rect = tester.get_rect(
5905                find::descendant(view_content(), find::by_type::<ConstrainedBox>()).first(),
5906            );
5907            assert_eq!(search_view_rect.bottom_right(), Offset::new(300.0, 300.0));
5908        });
5909    }
5910
5911    /// Dart's `findTextField()`.
5912    fn find_text_field() -> waft_widgets::testing::Finder {
5913        find::descendant(find::by_type::<SearchBar>(), find::by_type::<TextField>())
5914    }
5915
5916    fn is_hit_testable(tester: &WidgetTester, finder: waft_widgets::testing::Finder) -> bool {
5917        let element = tester.element(finder);
5918        let center = tester.get_center(element);
5919        let target = tester.render_box_of(element).as_object().id();
5920        let mut app = tester.cell.borrow_mut();
5921        let view_id = app.platform().views()[0].id();
5922        let mut result = waft_gestures::HitTestResult::new();
5923        waft_gestures::GestureBinding::instance(&mut app).hit_test_in_view(
5924            &mut app,
5925            &mut result,
5926            center,
5927            view_id,
5928        );
5929        result
5930            .path()
5931            .iter()
5932            .any(|entry| entry.shared_target().arena_id() == Some(target))
5933    }
5934
5935    fn decoration_theme() -> InputDecorationThemeData {
5936        InputDecorationThemeData::new()
5937            .focus_color(Colors::GREEN.primary())
5938            .hover_color(Colors::BLUE.primary())
5939            .outline_border(BorderSide {
5940                color: Colors::PINK.primary(),
5941                width: 10.0,
5942                ..BorderSide::default()
5943            })
5944            .is_dense(true)
5945            .content_padding(EdgeInsetsGeometry::from(EdgeInsets::symmetric(0.0, 20.0)))
5946            .hint_style(TextStyle::new().color(Colors::PURPLE_ACCENT.primary()))
5947            .fill_color(Colors::TEAL_ACCENT.primary())
5948            .filled(true)
5949            .is_collapsed(true)
5950            .border(crate::input_border::OutlineInputBorder::default())
5951            .focused_border(crate::input_border::UnderlineInputBorder::default())
5952            .enabled_border(crate::input_border::UnderlineInputBorder::default())
5953            .error_border(crate::input_border::UnderlineInputBorder::default())
5954            .focused_error_border(crate::input_border::UnderlineInputBorder::default())
5955            .disabled_border(crate::input_border::UnderlineInputBorder::default())
5956            .constraints({
5957                let mut constraints = BoxConstraints::new();
5958                constraints.max_width = 300.0;
5959                constraints
5960            })
5961    }
5962
5963    fn check_decoration_in_search_bar(tester: &WidgetTester, color_scheme: &ColorScheme) {
5964        let decoration = tester
5965            .widget(find_text_field(), |field: &TextField| {
5966                field.decoration.clone()
5967            })
5968            .expect("a decoration");
5969        assert_eq!(decoration.border, Some(InputBorderRef::none()));
5970        assert_eq!(decoration.focused_border, Some(InputBorderRef::none()));
5971        assert_eq!(decoration.enabled_border, Some(InputBorderRef::none()));
5972        assert_eq!(decoration.error_border, None);
5973        assert_eq!(decoration.focused_error_border, None);
5974        assert_eq!(decoration.disabled_border, None);
5975        assert_eq!(decoration.constraints, None);
5976        assert_eq!(decoration.is_collapsed, Some(false));
5977        assert_eq!(decoration.filled, Some(false));
5978        assert!(decoration.fill_color.is_none());
5979        assert_eq!(decoration.focus_color, None);
5980        assert_eq!(decoration.hover_color, None);
5981        assert_eq!(decoration.content_padding, Some(EdgeInsets::ZERO.into()));
5982        assert_eq!(
5983            decoration.hint_style.and_then(|style| style
5984                .value()
5985                .color
5986                .as_ref()
5987                .map(|color| color.color())),
5988            Some(color_scheme.on_surface_variant())
5989        );
5990    }
5991
5992    // 'Overall InputDecorationThemeData does not override text field style in SearchBar'.
5993    #[test]
5994    fn overall_input_decoration_theme_data_does_not_override_text_field_style_in_search_bar() {
5995        test_widgets(|tester| {
5996            let theme = ThemeData::builder()
5997                .input_decoration_theme(decoration_theme())
5998                .build(&tester.cell.borrow());
5999            let color_scheme = theme.color_scheme.clone();
6000            pump_material_home(
6001                tester,
6002                Some(theme),
6003                Center::new()
6004                    .child(Material::new().child(SearchBar::new().hint_text("hint text")))
6005                    .into_widget(),
6006            );
6007            check_decoration_in_search_bar(tester, &color_scheme);
6008            let material = search_bar_material(tester);
6009            check_search_bar_defaults(tester, &color_scheme, &material);
6010        });
6011    }
6012
6013    // 'Overall InputDecorationThemeData does not override text field style in the search view
6014    // route'.
6015    #[test]
6016    fn overall_input_decoration_theme_data_does_not_override_text_field_style_in_the_search_view_route()
6017     {
6018        test_widgets(|tester| {
6019            let theme = ThemeData::builder()
6020                .input_decoration_theme(decoration_theme())
6021                .build(&tester.cell.borrow());
6022            let color_scheme = theme.color_scheme.clone();
6023            pump_material_home(
6024                tester,
6025                Some(theme),
6026                Scaffold::new()
6027                    .body(
6028                        Material::new().child(
6029                            Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
6030                                SearchAnchor::new(
6031                                    |_app, _context, _controller| {
6032                                        Icon::new(Some(Icons::search())).into_widget()
6033                                    },
6034                                    empty_suggestions(),
6035                                )
6036                                .view_hint_text("hint text"),
6037                            ),
6038                        ),
6039                    )
6040                    .into_widget(),
6041            );
6042            tester.tap(find::by_icon(&Icons::search()));
6043            tester.pump_and_settle();
6044            check_decoration_in_search_bar(tester, &color_scheme);
6045
6046            let view_bar = find::descendant(view_content(), find::by_type::<SearchBar>());
6047            let material = tester.widget(
6048                find::descendant(view_bar, find::by_type::<Material>()).first(),
6049                |m: &Material| m.clone(),
6050            );
6051            assert_eq!(material.color, Some(Colors::TRANSPARENT));
6052            assert_eq!(material.elevation, 0.0);
6053            let hint_color = tester
6054                .widget(find::text("hint text"), |text: &Text| text.style.clone())
6055                .and_then(|style| style.color)
6056                .map(|color| color.color());
6057            assert_eq!(hint_color, Some(color_scheme.on_surface_variant()));
6058            let input = "entered text";
6059            tester.enter_text(find::by_type::<SearchBar>(), input);
6060            let input_color = tester
6061                .widget(find::text(input), |text: &EditableText| text.style.clone())
6062                .color
6063                .map(|color| color.color());
6064            assert_eq!(input_color, Some(color_scheme.on_surface()));
6065        });
6066    }
6067
6068    // 'SearchAnchor view respects theme brightness'.
6069    #[test]
6070    fn search_anchor_view_respects_theme_brightness() {
6071        test_widgets(|tester| {
6072            let build = |theme: ThemeData| {
6073                material_app(
6074                    theme,
6075                    Center::new()
6076                        .child(Material::new().child(SearchAnchor::new(
6077                            |_app, _context, controller| {
6078                                IconButton::new(
6079                                    Some(Listener::new(move |app: &mut App| {
6080                                        controller.open_view(app)
6081                                    })),
6082                                    Icon::new(Some(Icons::ac_unit())),
6083                                )
6084                                .into_widget()
6085                            },
6086                            empty_suggestions(),
6087                        )))
6088                        .into_widget(),
6089                )
6090            };
6091            let light = ThemeData::builder()
6092                .brightness(Brightness::Light)
6093                .build(&tester.cell.borrow());
6094            tester.pump_widget(build(light.clone()));
6095            tester.tap(find::widget_with_icon::<IconButton>(&Icons::ac_unit()));
6096            tester.pump_and_settle();
6097            assert_eq!(
6098                search_view_material(tester).color,
6099                Some(light.color_scheme.surface_container_high())
6100            );
6101
6102            let dark = ThemeData::builder()
6103                .brightness(Brightness::Dark)
6104                .build(&tester.cell.borrow());
6105            tester.pump_widget(build(dark.clone()));
6106            tester.pump_and_settle();
6107            assert_eq!(
6108                search_view_material(tester).color,
6109                Some(dark.color_scheme.surface_container_high())
6110            );
6111        });
6112    }
6113
6114    // 'SearchAnchor.bar respects barFocusNode property'.
6115    #[test]
6116    fn search_anchor_bar_respects_bar_focus_node_property() {
6117        test_widgets(|tester| {
6118            let node = FocusNode::new(&mut tester.cell.borrow_mut());
6119            pump_centered_material(
6120                tester,
6121                SearchAnchor::bar(empty_suggestions())
6122                    .bar_focus_node(node.erase())
6123                    .into_search_anchor(),
6124            );
6125            let field_node = text_field_focus_node(tester, find::by_type::<TextField>());
6126            let expected: FocusNodeRef = node.erase();
6127            assert_eq!(field_node.handle().id(), expected.handle().id());
6128        });
6129    }
6130
6131    // 'SearchAnchor.bar barFocusNode can be used to control focus'.
6132    #[test]
6133    fn search_anchor_bar_bar_focus_node_can_be_used_to_control_focus() {
6134        test_widgets(|tester| {
6135            let node = FocusNode::new(&mut tester.cell.borrow_mut());
6136            pump_centered_material(
6137                tester,
6138                SearchAnchor::bar(empty_suggestions())
6139                    .bar_focus_node(node.erase())
6140                    .into_search_anchor(),
6141            );
6142            let has_focus =
6143                |tester: &WidgetTester| node.handle().has_focus(&mut tester.cell.borrow_mut());
6144            assert!(!has_focus(tester));
6145            node.handle()
6146                .request_focus(&mut tester.cell.borrow_mut(), None);
6147            tester.pump();
6148            assert!(has_focus(tester));
6149            node.handle()
6150                .unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
6151            tester.pump();
6152            assert!(!has_focus(tester));
6153        });
6154    }
6155
6156    // 'SearchAnchor tap failed when disabled'.
6157    #[test]
6158    fn search_anchor_tap_failed_when_disabled() {
6159        test_widgets(|tester| {
6160            pump_material_home(
6161                tester,
6162                None,
6163                Center::new()
6164                    .child(Material::new().child(search_icon_anchor().enabled(false)))
6165                    .into_widget(),
6166            );
6167            expect(tester, &find::by_type::<SearchAnchor>(), finds_one_widget());
6168            assert!(!is_hit_testable(tester, find::by_type::<SearchAnchor>()));
6169        });
6170    }
6171
6172    // 'SearchAnchor respects headerHeight'.
6173    #[test]
6174    fn search_anchor_respects_header_height() {
6175        test_widgets(|tester| {
6176            pump_material_home(
6177                tester,
6178                None,
6179                Center::new()
6180                    .child(
6181                        Material::new().child(
6182                            search_icon_anchor()
6183                                .is_full_screen(true)
6184                                .header_height(32.0),
6185                        ),
6186                    )
6187                    .into_widget(),
6188            );
6189            tester.pump();
6190            tester.tap(find::by_icon(&Icons::search()));
6191            tester.pump_and_settle();
6192            let header = find::descendant(view_content(), find::by_type::<SearchBar>());
6193            assert_eq!(tester.get_size(header).height(), 32.0);
6194        });
6195    }
6196
6197    // 'SearchAnchor.bar respects viewHeaderHeight'.
6198    #[test]
6199    fn search_anchor_bar_respects_view_header_height() {
6200        test_widgets(|tester| {
6201            pump_centered_material(
6202                tester,
6203                SearchAnchor::bar(empty_suggestions())
6204                    .is_full_screen(true)
6205                    .view_header_height(32.0)
6206                    .into_search_anchor(),
6207            );
6208            tester.pump();
6209            tester.tap(find::by_type::<SearchBar>());
6210            tester.pump_and_settle();
6211            let header = find::descendant(view_content(), find::by_type::<SearchBar>());
6212            assert_eq!(tester.get_size(header).height(), 32.0);
6213        });
6214    }
6215
6216    // 'The default clear button only shows when text input is not empty on the search view'.
6217    #[test]
6218    fn the_default_clear_button_only_shows_when_text_input_is_not_empty_on_the_search_view() {
6219        test_widgets(|tester| {
6220            pump_centered_material(tester, search_icon_anchor());
6221            tester.pump();
6222            tester.tap(find::by_icon(&Icons::search()));
6223            tester.pump_and_settle();
6224            let close = find::widget_with_icon::<IconButton>(&Icons::close());
6225            expect(tester, &close, finds_nothing());
6226
6227            tester.enter_text(find_text_field(), "a");
6228            tester.pump();
6229            expect(tester, &close, finds_one_widget());
6230
6231            tester.enter_text(find_text_field(), "");
6232            tester.pump();
6233            expect(tester, &close, finds_nothing());
6234        });
6235    }
6236
6237    // 'Tapping outside searchbar should unfocus the searchbar on mobile'.
6238    #[test]
6239    fn tapping_outside_search_bar_should_unfocus_the_search_bar_on_mobile() {
6240        waft_widgets::testing::test_widgets_variant(
6241            waft_widgets::testing::TargetPlatformVariant::mobile(),
6242            |tester| {
6243                let node = FocusNode::new(&mut tester.cell.borrow_mut());
6244                let focus_node: FocusNodeRef = node.erase();
6245                let anchor = SearchAnchor::new(
6246                    {
6247                        let focus_node = focus_node.clone();
6248                        move |app, _context, controller| {
6249                            let unfocus_node = focus_node.clone();
6250                            let tap_controller = controller;
6251                            let change_controller = controller;
6252                            SearchBar::new()
6253                                .controller(controller.as_controller().keep(app))
6254                                .on_tap(Listener::new(move |app: &mut App| {
6255                                    tap_controller.open_view(app)
6256                                }))
6257                                .on_tap_outside(Rc::new(move |app: &mut App, _event| {
6258                                    unfocus_node
6259                                        .handle()
6260                                        .unfocus(app, UnfocusDisposition::Scope)
6261                                }))
6262                                .on_changed(move |app: &mut App, _| {
6263                                    change_controller.open_view(app)
6264                                })
6265                                .auto_focus(true)
6266                                .focus_node(focus_node.clone())
6267                                .into_widget()
6268                        }
6269                    },
6270                    |_app, _context, _controller| {
6271                        Task::ready(
6272                            (0..5)
6273                                .map(|index| {
6274                                    ListTile::new()
6275                                        .title(Text::new(format!("item {index}")))
6276                                        .into_widget()
6277                                })
6278                                .collect(),
6279                        )
6280                    },
6281                );
6282                pump_material_home(tester, None, Scaffold::new().body(anchor).into_widget());
6283                tester.pump();
6284                assert!(focus_node.handle().has_primary_focus(&tester.cell.borrow()));
6285                tester.tap_at(Offset::new(50.0, 50.0), 1);
6286                tester.pump();
6287                assert!(!focus_node.handle().has_primary_focus(&tester.cell.borrow()));
6288            },
6289        );
6290    }
6291
6292    // 'Search view widgets can inherit local themes'.
6293    #[test]
6294    fn search_view_widgets_can_inherit_local_themes() {
6295        test_widgets(|tester| {
6296            let global_theme = ThemeData::builder()
6297                .color_scheme_seed(Colors::RED.primary())
6298                .build(&tester.cell.borrow());
6299            let local_theme = ThemeData::builder()
6300                .color_scheme_seed(Colors::GREEN.primary())
6301                .icon_button_theme(
6302                    IconButtonThemeData::new().style(
6303                        IconButton::style_from()
6304                            .background_color(Color::new(0xffffff00))
6305                            .build(),
6306                    ),
6307                )
6308                .card_theme(CardThemeData::new().color(Color::new(0xff00ffff)))
6309                .build(&tester.cell.borrow());
6310            let local_surface = local_theme.color_scheme.surface_container_high();
6311            pump_material_home(
6312                tester,
6313                Some(global_theme),
6314                Center::new()
6315                    .child(Theme::new(
6316                        local_theme,
6317                        Material::new().child(
6318                            SearchAnchor::bar(|_app, _context, _controller| {
6319                                Task::ready(vec![
6320                                    Card::new()
6321                                        .child(
6322                                            ListTile::new()
6323                                                .on_tap(Listener::new(|_| {}))
6324                                                .title(Text::new("Item 1")),
6325                                        )
6326                                        .into_widget(),
6327                                ])
6328                            })
6329                            .into_search_anchor(),
6330                        ),
6331                    ))
6332                    .into_widget(),
6333            );
6334            tester.tap(find::by_type::<SearchBar>());
6335            tester.pump_and_settle();
6336
6337            // The search view background color.
6338            assert_eq!(search_view_material(tester).color, Some(local_surface));
6339            // The search view icons' background color.
6340            let icon_button_material = tester.widget(
6341                find::descendant(find::by_type::<IconButton>(), find::by_type::<Material>())
6342                    .first(),
6343                |material: &Material| material.clone(),
6344            );
6345            assert_eq!(icon_button_material.color, Some(Color::new(0xffffff00)));
6346            // The suggestion card color.
6347            let suggestion_material = tester.widget(
6348                find::descendant(find::by_type::<Card>(), find::by_type::<Material>()).first(),
6349                |material: &Material| material.clone(),
6350            );
6351            assert_eq!(suggestion_material.color, Some(Color::new(0xff00ffff)));
6352        });
6353    }
6354
6355    // 'Block entering text on disabled widget'.
6356    #[test]
6357    fn block_entering_text_on_disabled_widget() {
6358        test_widgets(|tester| {
6359            let controller = {
6360                let mut app = tester.cell.borrow_mut();
6361                TextEditingController::new(&mut app).text(&mut app, "init")
6362            };
6363            pump_material_home(
6364                tester,
6365                None,
6366                Material::new()
6367                    .child(
6368                        Center::new().child(
6369                            SearchBar::new()
6370                                .controller(controller.erase())
6371                                .enabled(false),
6372                        ),
6373                    )
6374                    .into_widget(),
6375            );
6376            tester.enter_text(find::by_type::<SearchBar>(), "abcdefghi");
6377            assert_eq!(
6378                controller.handle().text_value(&tester.cell.borrow()),
6379                "init"
6380            );
6381        });
6382    }
6383
6384    fn set_keyboard_insets(tester: &WidgetTester) {
6385        tester.view().set_view_insets(waft_embedder::ViewPadding {
6386            bottom: 500.0,
6387            ..waft_embedder::ViewPadding::ZERO
6388        });
6389    }
6390
6391    // 'suggestionsBuilder is not called when the search value does not change'.
6392    #[test]
6393    fn suggestions_builder_is_not_called_when_the_search_value_does_not_change() {
6394        test_widgets(|tester| {
6395            let called = Rc::new(Cell::new(0));
6396            let anchor = SearchAnchor::new(
6397                |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
6398                {
6399                    let called = Rc::clone(&called);
6400                    move |_app, _context, _controller| {
6401                        called.set(called.get() + 1);
6402                        Task::ready(Vec::new())
6403                    }
6404                },
6405            );
6406            pump_material_home(
6407                tester,
6408                None,
6409                Scaffold::new()
6410                    .body(Center::new().child(anchor))
6411                    .into_widget(),
6412            );
6413            tester.pump();
6414            tester.tap(find::by_icon(&Icons::search()));
6415            tester.pump_and_settle();
6416
6417            // Simulate the keyboard opening resizing the view.
6418            set_keyboard_insets(tester);
6419            tester.show_keyboard(find::by_type::<TextField>());
6420            tester.pump_and_settle();
6421            assert_eq!(called.get(), 2);
6422
6423            // Remove the view insets, as if the keyboard were hidden, and hide the keyboard.
6424            tester.view().reset_view_insets();
6425            tester
6426                .test_text_input()
6427                .receive_action(TextInputAction::Done);
6428            tester.pump_and_settle();
6429            assert_eq!(called.get(), 2);
6430        });
6431    }
6432
6433    // 'Suggestions gets refreshed after long API call'.
6434    #[test]
6435    fn suggestions_gets_refreshed_after_long_api_call() {
6436        test_widgets(|tester| {
6437            let api_call_duration = Duration::from_secs(1);
6438            let debounce_timer: Rc<RefCell<Option<Timer>>> = Rc::default();
6439            let anchor = SearchAnchor::new(
6440                |_app, _context, _controller| Icon::new(Some(Icons::search())).into_widget(),
6441                {
6442                    let debounce_timer = Rc::clone(&debounce_timer);
6443                    move |app, _context, _controller| {
6444                        let completer = Completer::new();
6445                        let future = completer.future();
6446                        if let Some(timer) = debounce_timer.borrow_mut().take() {
6447                            timer.cancel(app);
6448                        }
6449                        let timer = Timer::new(
6450                            app,
6451                            api_call_duration,
6452                            Listener::new(move |app: &mut App| {
6453                                completer.complete(
6454                                    app,
6455                                    (0..10)
6456                                        .map(|index| {
6457                                            ListTile::new()
6458                                                .title(Text::new(format!("Item - {index}")))
6459                                                .into_widget()
6460                                        })
6461                                        .collect(),
6462                                );
6463                            }),
6464                        );
6465                        *debounce_timer.borrow_mut() = Some(timer);
6466                        app.spawn(async move |_cx| future.await)
6467                    }
6468                },
6469            );
6470            pump_material_home(
6471                tester,
6472                None,
6473                Scaffold::new()
6474                    .body(Center::new().child(anchor))
6475                    .into_widget(),
6476            );
6477            tester.tap(find::by_icon(&Icons::search()));
6478            tester.pump_and_settle();
6479
6480            // Simulate the keyboard opening resizing the view, and show the keyboard.
6481            set_keyboard_insets(tester);
6482            tester.show_keyboard(find::by_type::<TextField>());
6483            tester.pump_and_settle_by(api_call_duration);
6484            expect(tester, &find::text("Item - 1"), finds_one_widget());
6485        });
6486    }
6487
6488    // 'SearchAnchor does not dispose external SearchController'.
6489    #[test]
6490    fn search_anchor_does_not_dispose_external_search_controller() {
6491        test_widgets(|tester| {
6492            let controller = SearchController::new(&mut tester.cell.borrow_mut());
6493            pump_material_home(
6494                tester,
6495                None,
6496                Material::new()
6497                    .child(view_anchor().search_controller(controller.clone()))
6498                    .into_widget(),
6499            );
6500            tester.tap(find::by_icon(&Icons::search()));
6501            tester.pump_and_settle();
6502            pump_material_home(
6503                tester,
6504                None,
6505                Material::new().child(Text::new("disposed")).into_widget(),
6506            );
6507            // The controller is still alive: reading it does not panic.
6508            let _ = controller.handle().text_value(&tester.cell.borrow());
6509        });
6510    }
6511
6512    // 'SearchAnchor gracefully closes its search view when disposed'.
6513    #[test]
6514    fn search_anchor_gracefully_closes_its_search_view_when_disposed() {
6515        test_widgets(|tester| {
6516            let disposed = Rc::new(Cell::new(false));
6517            let set_state: Rc<RefCell<Option<waft_widgets::StateSetter>>> = Rc::default();
6518            pump_material_home(
6519                tester,
6520                None,
6521                Material::new()
6522                    .child(waft_widgets::StatefulBuilder::new({
6523                        let disposed = Rc::clone(&disposed);
6524                        let set_state = Rc::clone(&set_state);
6525                        move |_app, _context, state_setter| {
6526                            *set_state.borrow_mut() = Some(state_setter);
6527                            if disposed.get() {
6528                                return Text::new("disposed").into_widget();
6529                            }
6530                            SearchAnchor::new(
6531                                |_app, _context, controller| {
6532                                    IconButton::new(
6533                                        Some(Listener::new(move |app: &mut App| {
6534                                            controller.open_view(app)
6535                                        })),
6536                                        Icon::new(Some(Icons::search())),
6537                                    )
6538                                    .into_widget()
6539                                },
6540                                |_app, _context, _controller| {
6541                                    Task::ready(vec![Text::new("suggestion").into_widget()])
6542                                },
6543                            )
6544                            .into_widget()
6545                        }
6546                    }))
6547                    .into_widget(),
6548            );
6549            tester.tap(find::by_icon(&Icons::search()));
6550            tester.pump_and_settle();
6551
6552            let state_setter = set_state.borrow().clone().expect("a state setter");
6553            tester.update(|app| {
6554                state_setter(app, &mut |_| disposed.set(true));
6555            });
6556            tester.cell.checkpoint();
6557            tester.pump();
6558            // The search view starts to close but is not disposed yet.
6559            expect(tester, &find::by_type::<EditableText>(), finds_one_widget());
6560            tester.pump_and_settle();
6561            // The search view and its internal search controller are now disposed.
6562            expect(tester, &find::by_type::<TextField>(), finds_nothing());
6563        });
6564    }
6565
6566    // 'disposing SearchAnchor during search view exit animation does not crash'.
6567    #[test]
6568    fn disposing_search_anchor_during_search_view_exit_animation_does_not_crash() {
6569        test_widgets(|tester| {
6570            let key = GlobalKey::new();
6571            let theme = m3(tester);
6572            let build = {
6573                let key = key.clone();
6574                move |home: WidgetRef| {
6575                    crate::app::MaterialApp::new()
6576                        .theme(theme.clone())
6577                        .navigator_key(key.clone())
6578                        .home(home)
6579                        .into_widget()
6580                }
6581            };
6582            tester.pump_widget(build(Material::new().child(view_anchor()).into_widget()));
6583            tester.tap(find::by_icon(&Icons::search()));
6584            tester.pump_and_settle();
6585            let navigator = key
6586                .current_state::<waft_widgets::NavigatorState>(&tester.cell.borrow())
6587                .expect("a navigator");
6588            navigator.pop(&mut tester.cell.borrow_mut(), None);
6589            tester.cell.checkpoint();
6590            tester.pump();
6591            tester.pump_widget(build(
6592                Material::new().child(Text::new("disposed")).into_widget(),
6593            ));
6594            tester.pump();
6595        });
6596    }
6597
6598    // 'SearchAnchor.bar viewOnClose function test'.
6599    #[test]
6600    fn search_anchor_bar_view_on_close_function_test() {
6601        test_widgets(|tester| {
6602            let name = Rc::new(RefCell::new("silva".to_string()));
6603            let anchor = SearchAnchor::bar(|_app, _context, controller| {
6604                Task::ready(vec![
6605                    ListTile::new()
6606                        .title(Text::new("item 0"))
6607                        .on_tap(Listener::new(move |app: &mut App| {
6608                            controller.close_view(app, Some("item 0".to_string()))
6609                        }))
6610                        .into_widget(),
6611                ])
6612            })
6613            .on_close({
6614                let name = Rc::clone(&name);
6615                Listener::new(move |_| *name.borrow_mut() = "Pedro".to_string())
6616            });
6617            pump_material_home(
6618                tester,
6619                None,
6620                Material::new()
6621                    .child(anchor.into_search_anchor())
6622                    .into_widget(),
6623            );
6624            // Open search view.
6625            tester.tap(find::by_type::<SearchBar>());
6626            tester.pump_and_settle();
6627            assert_eq!(*name.borrow(), "silva");
6628            // Pop search view route.
6629            tester.tap(find::by_type::<BackButton>());
6630            tester.pump_and_settle();
6631            assert_eq!(*name.borrow(), "Pedro");
6632        });
6633    }
6634
6635    // 'SearchAnchor.bar onOpen is called when the search view is opened'.
6636    #[test]
6637    fn search_anchor_bar_on_open_is_called_when_the_search_view_is_opened() {
6638        test_widgets(|tester| {
6639            let state = Rc::new(RefCell::new("Idle"));
6640            let anchor = SearchAnchor::bar(|_app, _context, _controller| {
6641                Task::ready(
6642                    (0..5)
6643                        .map(|index| {
6644                            ListTile::new()
6645                                .leading(Icon::new(Some(Icons::history())))
6646                                .title(Text::new(format!("item {index}")))
6647                                .trailing(Icon::new(Some(Icons::chevron_right())))
6648                                .on_tap(Listener::new(|_| {}))
6649                                .into_widget()
6650                        })
6651                        .collect(),
6652                )
6653            })
6654            .on_close({
6655                let state = Rc::clone(&state);
6656                Listener::new(move |_| *state.borrow_mut() = "Closed")
6657            })
6658            .on_open({
6659                let state = Rc::clone(&state);
6660                Listener::new(move |_| *state.borrow_mut() = "Opened")
6661            });
6662            pump_centered_material(tester, anchor.into_search_anchor());
6663            expect(tester, &find::by_icon(&Icons::search()), finds_one_widget());
6664            // Open search view.
6665            tester.tap(find::by_icon(&Icons::search()));
6666            tester.pump();
6667            assert_eq!(*state.borrow(), "Opened");
6668            // Pop search view route.
6669            tester.tap(find::by_type::<BackButton>());
6670            tester.pump();
6671            assert_eq!(*state.borrow(), "Closed");
6672        });
6673    }
6674
6675    // 'The last element of the suggestion list should be visible when scrolling to the end of
6676    // list'.
6677    #[test]
6678    fn the_last_element_of_the_suggestion_list_should_be_visible_when_scrolling_to_the_end() {
6679        test_widgets(|tester| {
6680            pump_material_home(
6681                tester,
6682                None,
6683                SearchAnchor::bar(|_app, _context, _controller| {
6684                    Task::ready(
6685                        (0..30)
6686                            .map(|index| {
6687                                ListTile::new()
6688                                    .title_alignment(ListTileTitleAlignment::Center)
6689                                    .title(Text::new(format!("Item {index}")))
6690                                    .into_widget()
6691                            })
6692                            .collect(),
6693                    )
6694                })
6695                .into_search_anchor()
6696                .into_widget(),
6697            );
6698            // Open search view.
6699            tester.tap(find::by_icon(&Icons::search()));
6700            tester.pump_and_settle();
6701
6702            let fake_keyboard_height = 500.0;
6703            let physical_bottom_padding = fake_keyboard_height * tester.device_pixel_ratio();
6704            // Simulate the keyboard opening resizing the view.
6705            tester.view().set_view_insets(waft_embedder::ViewPadding {
6706                bottom: physical_bottom_padding,
6707                ..waft_embedder::ViewPadding::ZERO
6708            });
6709            // Scroll down to the end of the list.
6710            expect(tester, &find::by_type::<ListView>(), finds_one_widget());
6711            tester.fling(
6712                find::by_type::<ListView>(),
6713                Offset::new(0.0, -5000.0),
6714                5000.0,
6715            );
6716            tester.pump_and_settle();
6717
6718            // The last item should not be hidden by the keyboard.
6719            let last_item_bottom = tester.get_rect(find::text("Item 29")).bottom;
6720            let fake_keyboard_top = tester
6721                .get_size(find::by_type::<crate::app::MaterialApp>())
6722                .height()
6723                - fake_keyboard_height;
6724            assert!(last_item_bottom <= fake_keyboard_top);
6725        });
6726    }
6727
6728    // 'SearchAnchor.bar respects SearchBarThemeData.padding'.
6729    #[test]
6730    fn search_anchor_bar_respects_search_bar_theme_data_padding() {
6731        test_widgets(|tester| {
6732            let custom_padding: EdgeInsetsGeometry = EdgeInsets::all(32.0).into();
6733            pump_material_home(
6734                tester,
6735                None,
6736                Scaffold::new()
6737                    .body(crate::search_bar_theme::SearchBarTheme::new(
6738                        crate::search_bar_theme::SearchBarThemeData::new().padding(
6739                            <dyn WidgetStateProperty<Option<EdgeInsetsGeometry>>>::all(Some(
6740                                custom_padding,
6741                            )),
6742                        ),
6743                        SearchAnchor::bar(empty_suggestions()).into_search_anchor(),
6744                    ))
6745                    .into_widget(),
6746            );
6747            let padding = tester.widget(
6748                find::descendant(find::by_type::<SearchBar>(), find::by_type::<Padding>()).first(),
6749                |padding: &Padding| padding.padding,
6750            );
6751            assert_eq!(padding, custom_padding);
6752        });
6753    }
6754
6755    // 'SearchAnchor does not crash at zero area'.
6756    #[test]
6757    fn search_anchor_does_not_crash_at_zero_area() {
6758        test_widgets(|tester| {
6759            tester.view().set_physical_size(Size::ZERO);
6760            let controller = SearchController::new(&mut tester.cell.borrow_mut());
6761            pump_material_home(
6762                tester,
6763                None,
6764                Center::new()
6765                    .child(
6766                        SearchAnchor::new(
6767                            |_app, _context, _controller| Text::new("X").into_widget(),
6768                            |_app, _context, _controller| {
6769                                Task::ready(vec![Text::new("Y").into_widget()])
6770                            },
6771                        )
6772                        .search_controller(controller.clone()),
6773                    )
6774                    .into_widget(),
6775            );
6776            assert_eq!(tester.get_size(find::by_type::<SearchAnchor>()), Size::ZERO);
6777            controller.handle().set_selection(
6778                &mut tester.cell.borrow_mut(),
6779                TextSelection::collapsed(0, TextAffinity::Downstream),
6780            );
6781            tester.pump();
6782            assert!(
6783                !find::by_type::<Text>()
6784                    .skip_offstage(false)
6785                    .evaluate(tester)
6786                    .is_empty()
6787            );
6788        });
6789    }
6790
6791    // 'SearchBar does not crash at zero area'.
6792    #[test]
6793    fn search_bar_does_not_crash_at_zero_area() {
6794        test_widgets(|tester| {
6795            tester.view().set_physical_size(Size::ZERO);
6796            let controller = {
6797                let mut app = tester.cell.borrow_mut();
6798                TextEditingController::new(&mut app).text(&mut app, "X")
6799            };
6800            pump_material_home(
6801                tester,
6802                None,
6803                Center::new()
6804                    .child(SearchBar::new().controller(controller.erase()))
6805                    .into_widget(),
6806            );
6807            assert_eq!(tester.get_size(find::by_type::<SearchBar>()), Size::ZERO);
6808            controller.handle().set_selection(
6809                &mut tester.cell.borrow_mut(),
6810                TextSelection::collapsed(0, TextAffinity::Downstream),
6811            );
6812            tester.pump();
6813            expect(tester, &find::text("X"), finds_one_widget());
6814        });
6815    }
6816
6817    // 'SearchAnchor full-screen view expands to fit screen when rotated'.
6818    #[test]
6819    fn search_anchor_full_screen_view_expands_to_fit_screen_when_rotated() {
6820        test_widgets(|tester| {
6821            // Start in portrait mode.
6822            set_view_size(tester, 360.0, 800.0);
6823            pump_material_home(
6824                tester,
6825                None,
6826                Center::new()
6827                    .child(view_anchor().is_full_screen(true))
6828                    .into_widget(),
6829            );
6830            tester.tap(find::by_icon(&Icons::search()));
6831            tester.pump_and_settle();
6832            let starting_size = search_view_size(tester);
6833            assert_eq!(starting_size.width(), 360.0);
6834            assert_eq!(starting_size.height(), 800.0);
6835
6836            // Rotate to landscape mode.
6837            tester.view().set_physical_size(Size::new(800.0, 360.0));
6838            tester.pump_and_settle();
6839            let rotated_size = search_view_size(tester);
6840            assert_eq!(rotated_size.width(), 800.0);
6841            assert_eq!(rotated_size.height(), 360.0);
6842        });
6843    }
6844
6845    // 'SearchAnchor resizes itself to match Navigator parent'.
6846    #[test]
6847    fn search_anchor_resizes_itself_to_match_navigator_parent() {
6848        test_widgets(|tester| {
6849            let parent_size = Rc::new(Cell::new(Size::new(600.0, 400.0)));
6850            let set_state: Rc<RefCell<Option<waft_widgets::StateSetter>>> = Rc::default();
6851            pump_material_home(
6852                tester,
6853                None,
6854                Scaffold::new()
6855                    .body(waft_widgets::StatefulBuilder::new({
6856                        let parent_size = Rc::clone(&parent_size);
6857                        let set_state = Rc::clone(&set_state);
6858                        move |_app, _context, state_setter| {
6859                            *set_state.borrow_mut() = Some(state_setter);
6860                            let size = parent_size.get();
6861                            SizedBox::new()
6862                                .width(size.width())
6863                                .height(size.height())
6864                                .child(waft_widgets::Navigator::new().on_generate_route(
6865                                    |app, settings| {
6866                                        let route = MaterialPageRoute::new(
6867                                            app,
6868                                            Rc::new(|_app, _context| {
6869                                                Scaffold::new()
6870                                                    .body(view_anchor().is_full_screen(true))
6871                                                    .into_widget()
6872                                            }),
6873                                        );
6874                                        route.clone().settings(
6875                                            app,
6876                                            waft_widgets::RouteSettingsRef::Settings(
6877                                                settings.clone(),
6878                                            ),
6879                                        );
6880                                        Some(route.erase())
6881                                    },
6882                                ))
6883                                .into_widget()
6884                        }
6885                    }))
6886                    .into_widget(),
6887            );
6888            tester.tap(find::by_icon(&Icons::search()));
6889            tester.pump_and_settle();
6890            let size = search_view_size(tester);
6891            assert_eq!(size.height(), 400.0);
6892            assert_eq!(size.width(), 600.0);
6893
6894            let resize = |tester: &mut WidgetTester, width: f64, height: f64| {
6895                parent_size.set(Size::new(width, height));
6896                let state_setter = set_state.borrow().clone().expect("a state setter");
6897                tester.update(|app| state_setter(app, &mut |_| {}));
6898                tester.cell.checkpoint();
6899                tester.pump_and_settle();
6900            };
6901            // Resize the parent container larger.
6902            resize(tester, 700.0, 500.0);
6903            let size = search_view_size(tester);
6904            assert_eq!(size.height(), 500.0);
6905            assert_eq!(size.width(), 700.0);
6906            // Resize the parent container smaller.
6907            resize(tester, 400.0, 300.0);
6908            let size = search_view_size(tester);
6909            assert_eq!(size.height(), 300.0);
6910            assert_eq!(size.width(), 400.0);
6911        });
6912    }
6913
6914    fn render_editable_at(
6915        tester: &WidgetTester,
6916        index: usize,
6917    ) -> waft_rendering::RenderHandle<waft_rendering::RenderEditable> {
6918        tester.all::<waft_rendering::RenderEditable>()[index]
6919    }
6920
6921    /// Dart's `textOffsetToPosition(tester, offset, index:)`.
6922    fn text_offset_to_position(tester: &WidgetTester, offset: i32, index: usize) -> Offset {
6923        let editable = render_editable_at(tester, index);
6924        let mut app = tester.cell.borrow_mut();
6925        let endpoints = editable.get_endpoints_for_selection(
6926            &mut app,
6927            TextSelection::collapsed(offset, TextAffinity::Downstream),
6928        );
6929        assert_eq!(endpoints.len(), 1);
6930        editable
6931            .as_box()
6932            .local_to_global(&app, endpoints[0].point, None)
6933            + Offset::new(0.0, -2.0)
6934    }
6935
6936    fn pump_selection_anchor(tester: &mut WidgetTester) -> Ref<SearchController> {
6937        let controller = SearchController::new(&mut tester.cell.borrow_mut());
6938        controller
6939            .handle()
6940            .set_text(&mut tester.cell.borrow_mut(), "initial text");
6941        pump_material_home(
6942            tester,
6943            None,
6944            Material::new()
6945                .child(
6946                    SearchAnchor::bar(empty_suggestions())
6947                        .search_controller(controller.clone())
6948                        .into_search_anchor(),
6949                )
6950                .into_widget(),
6951        );
6952        expect(tester, &find::text("initial text"), finds_one_widget());
6953        controller
6954    }
6955
6956    fn selection_of(tester: &WidgetTester, controller: &Ref<SearchController>) -> TextSelection {
6957        controller.handle().selection(&tester.cell.borrow())
6958    }
6959
6960    // 'SearchAnchor text selection: can right-click to select word'.
6961    #[test]
6962    fn search_anchor_text_selection_can_right_click_to_select_word() {
6963        waft_widgets::testing::test_widgets_variant(
6964            waft_widgets::testing::TargetPlatformVariant::only(TargetPlatform::MacOS),
6965            |tester| {
6966                let controller = pump_selection_anchor(tester);
6967                let mut gesture = TestPointer::mouse(
6968                    tester.next_pointer(),
6969                    waft_gestures::K_SECONDARY_MOUSE_BUTTON,
6970                );
6971                let at = text_offset_to_position(tester, 4, 0) + Offset::new(0.0, -9.0);
6972                tester.down(&mut gesture, at);
6973                tester.pump();
6974                tester.up(&gesture);
6975                tester.pump_and_settle();
6976                assert_eq!(selection_of(tester, &controller), TextSelection::new(0, 7));
6977                tester.remove_pointer(&gesture);
6978            },
6979        );
6980    }
6981
6982    // 'SearchAnchor text selection: can click to set position'.
6983    #[test]
6984    fn search_anchor_text_selection_can_click_to_set_position() {
6985        waft_widgets::testing::test_widgets_variant(
6986            waft_widgets::testing::TargetPlatformVariant::desktop(),
6987            |tester| {
6988                let controller = pump_selection_anchor(tester);
6989                let mut gesture = point_gesture_to_search_bar(tester);
6990                let at = text_offset_to_position(tester, 2, 0) + Offset::new(0.0, -9.0);
6991                tester.down(&mut gesture, at);
6992                tester.pump();
6993                tester.up(&gesture);
6994                tester.pump_and_settle_by(waft_gestures::K_DOUBLE_TAP_TIMEOUT);
6995                assert_eq!(
6996                    selection_of(tester, &controller),
6997                    TextSelection::collapsed(2, TextAffinity::Downstream)
6998                );
6999
7000                let at = text_offset_to_position(tester, 9, 1) + Offset::new(0.0, -9.0);
7001                tester.down(&mut gesture, at);
7002                tester.pump();
7003                tester.up(&gesture);
7004                tester.pump_and_settle();
7005                assert_eq!(
7006                    selection_of(tester, &controller),
7007                    TextSelection::collapsed(9, TextAffinity::Downstream)
7008                );
7009                tester.remove_pointer(&gesture);
7010            },
7011        );
7012    }
7013
7014    /// The clicks the double- and triple-click cases make after the first one opened the view.
7015    fn click_after_view_opened(
7016        tester: &mut WidgetTester,
7017        gesture: &mut TestPointer,
7018        at: Offset,
7019        settle: bool,
7020    ) {
7021        tester.down(gesture, at);
7022        if settle {
7023            tester.pump_and_settle();
7024        } else {
7025            tester.pump();
7026        }
7027        tester.up(gesture);
7028        tester.pump();
7029    }
7030
7031    // 'SearchAnchor text selection: can double-click to select word'.
7032    #[test]
7033    fn search_anchor_text_selection_can_double_click_to_select_word() {
7034        waft_widgets::testing::test_widgets_variant(
7035            waft_widgets::testing::TargetPlatformVariant::desktop(),
7036            |tester| {
7037                let controller = pump_selection_anchor(tester);
7038                let mut gesture = point_gesture_to_search_bar(tester);
7039                let at = text_offset_to_position(tester, 4, 0) + Offset::new(0.0, -9.0);
7040                tester.down(&mut gesture, at);
7041                tester.pump();
7042                tester.up(&gesture);
7043                tester.pump_and_settle_by(waft_gestures::K_DOUBLE_TAP_TIMEOUT);
7044
7045                let after_open = text_offset_to_position(tester, 4, 1) + Offset::new(0.0, -9.0);
7046                click_after_view_opened(tester, &mut gesture, after_open, true);
7047                click_after_view_opened(tester, &mut gesture, after_open, false);
7048                assert_eq!(selection_of(tester, &controller), TextSelection::new(0, 7));
7049                tester.remove_pointer(&gesture);
7050            },
7051        );
7052    }
7053
7054    // 'SearchAnchor text selection: can triple-click to select field'.
7055    #[test]
7056    fn search_anchor_text_selection_can_triple_click_to_select_field() {
7057        waft_widgets::testing::test_widgets_variant(
7058            waft_widgets::testing::TargetPlatformVariant::desktop(),
7059            |tester| {
7060                let controller = pump_selection_anchor(tester);
7061                let mut gesture = point_gesture_to_search_bar(tester);
7062                let at = text_offset_to_position(tester, 4, 0) + Offset::new(0.0, -9.0);
7063                tester.down(&mut gesture, at);
7064                tester.pump();
7065                tester.up(&gesture);
7066                tester.pump_and_settle_by(waft_gestures::K_DOUBLE_TAP_TIMEOUT);
7067
7068                let after_open = text_offset_to_position(tester, 4, 1) + Offset::new(0.0, -9.0);
7069                click_after_view_opened(tester, &mut gesture, after_open, false);
7070                click_after_view_opened(tester, &mut gesture, after_open, false);
7071                tester.down(&mut gesture, after_open);
7072                tester.pump();
7073                tester.up(&gesture);
7074                tester.pump_and_settle();
7075                assert_eq!(selection_of(tester, &controller), TextSelection::new(0, 12));
7076                tester.remove_pointer(&gesture);
7077            },
7078        );
7079    }
7080
7081    // 'SearchAnchor with enableTapHandling: false does not build GestureDetector'.
7082    #[test]
7083    fn search_anchor_with_enable_tap_handling_false_does_not_build_gesture_detector() {
7084        test_widgets(|tester| {
7085            pump_material_home(
7086                tester,
7087                None,
7088                Scaffold::new()
7089                    .body(search_icon_anchor().enable_tap_handling(false))
7090                    .into_widget(),
7091            );
7092            expect(
7093                tester,
7094                &find::descendant(
7095                    find::by_type::<SearchAnchor>(),
7096                    find::by_type::<waft_widgets::GestureDetector>(),
7097                ),
7098                finds_nothing(),
7099            );
7100        });
7101    }
7102}