Skip to main content

waft_material/
search.rs

1//! Flutter counterpart: material_ui's `search.dart`.
2//!
3//! A full-screen search page: [`ShowSearch`] pushes it, and a [`SearchDelegate`] says what its
4//! app bar, suggestions and results are. The route and the page share the delegate, so the state
5//! Dart keeps in the delegate's private fields lives in [`SearchDelegateData`], which every
6//! delegate holds and answers from [`SearchDelegate::search_delegate_data`].
7
8use std::cell::Cell;
9use std::fmt;
10use std::rc::Rc;
11use std::time::Duration;
12
13use waft_animation::{
14    AnimationRef, AnimationStatus, AnimationStatusListener, ProxyAnimation,
15    k_always_dismissed_animation,
16};
17use waft_embedder::{
18    SemanticsInputType, SystemUiOverlayStyle, TextAffinity, TextEditingValue, TextInputAction,
19    TextInputType, TextSelection,
20};
21use waft_foundation::{
22    App, CompleterFuture, Handle, ListenableObject, Listener, Ref, ValueKey, ValueNotifier,
23};
24use waft_painting::TextStyle;
25use waft_services::{KeyEvent, LogicalKeyboardKey};
26use waft_widgets::{
27    AnimatedSwitcher, AnyFocusNode, AnyRoute, BuildContext, FadeTransition, FocusNode,
28    FocusNodeLeaf, IntoWidget, KeyEventResult, KeyedSubtree, LocalHistoryRoute,
29    LocalHistoryRouteData, ModalRoute, ModalRouteData, Navigator, OverlayRoute, OverlayRouteData,
30    PageRoute, PageRouteData, PredictiveBackRoute, PreferredSizeWidgetRef, Route, RouteData,
31    RouteResult, Semantics, State, StateData, StatefulWidget, TextEditingController,
32    TextEditingControllerLeaf, TransitionRoute, TransitionRouteBase, TransitionRouteData,
33    UnfocusDisposition, WidgetRef,
34};
35
36use crate::app_bar::AppBar;
37use crate::app_bar_theme::AppBarThemeData;
38use crate::colors::Colors;
39use crate::debug::debug_check_has_material_localizations;
40use crate::input_border::InputBorderRef;
41use crate::input_decorator::{InputDecoration, InputDecorationThemeData};
42use crate::material_localizations::MaterialLocalizations;
43use crate::scaffold::Scaffold;
44use crate::text_field::TextField;
45use crate::theme::Theme;
46use crate::theme_data::ThemeData;
47
48/// Shows a full screen search page and returns the search result selected by the user when the
49/// page is closed.
50///
51/// The search page consists of an app bar with a search field and a body which can either show
52/// suggested search queries or the search results.
53///
54/// The appearance of the search page is determined by the provided `delegate`. The initial query
55/// string is given by `query`; Dart's default is the empty string, `Some("")`. When `query` is
56/// `None`, `delegate.query` will be used as the initial query.
57///
58/// The `use_root_navigator` argument is used to determine whether to push the search page to the
59/// [`Navigator`] furthest from or nearest to the given `context`. By default, `use_root_navigator`
60/// is `false` and the search page route created by this method is pushed to the nearest
61/// navigator to the given `context`. It can not be `None`.
62///
63/// The `maintain_state` argument is used to determine whether the route should remain in memory
64/// when it is inactive. By default, `maintain_state` is `false`.
65///
66/// The delegate's [`SearchDelegate::build_results`] method result is given back to the caller
67/// through the future this function returns, when the page is closed with
68/// [`SearchDelegate::close`].
69pub struct ShowSearch {
70    delegate: Rc<dyn SearchDelegate>,
71    query: Option<String>,
72    use_root_navigator: bool,
73    maintain_state: bool,
74}
75
76impl ShowSearch {
77    /// Creates a builder for a full screen search page; Dart's `showSearch` required argument is
78    /// the delegate, and every other argument is a setter.
79    pub fn new(delegate: Rc<dyn SearchDelegate>) -> ShowSearch {
80        ShowSearch {
81            delegate,
82            query: Some(String::new()),
83            use_root_navigator: false,
84            maintain_state: false,
85        }
86    }
87
88    /// The initial query; Dart's `Some(String::new())` by default, and `None` keeps the
89    /// delegate's current query.
90    pub fn query(mut self, query: Option<String>) -> ShowSearch {
91        self.query = query;
92        self
93    }
94
95    /// Whether to push the search page to the root navigator. Defaults to `false`.
96    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowSearch {
97        self.use_root_navigator = use_root_navigator;
98        self
99    }
100
101    /// Whether the route should remain in memory when it is inactive. Defaults to `false`.
102    pub fn maintain_state(mut self, maintain_state: bool) -> ShowSearch {
103        self.maintain_state = maintain_state;
104        self
105    }
106
107    /// Shows the search page and returns the result selected by the user.
108    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
109        let ShowSearch {
110            delegate,
111            query,
112            use_root_navigator,
113            maintain_state,
114        } = self;
115        let data = delegate.search_delegate_data();
116        delegate.set_query(app, query.unwrap_or_else(|| delegate.query(app)));
117        data.current_body_notifier
118            .handle()
119            .set_value(app, Some(SearchBody::Suggestions));
120        let route = SearchPageRoute::new(app, delegate, maintain_state);
121        Navigator::of(app, context, use_root_navigator).push(app, route.into_erased())
122    }
123}
124
125/// Which of the delegate's two bodies the page shows.
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
127enum SearchBody {
128    /// Suggested queries, [`SearchDelegate::build_suggestions`].
129    Suggestions,
130
131    /// The results of the query, [`SearchDelegate::build_results`].
132    Results,
133}
134
135/// The state of a [`SearchDelegate`] that Dart keeps in the delegate's fields: every delegate
136/// holds one, and answers it from [`SearchDelegate::search_delegate_data`].
137///
138/// The fields Dart gives as constructor arguments are plain fields; the setters
139/// ([`automatically_imply_leading`](Self::automatically_imply_leading),
140/// [`leading_width`](Self::leading_width)) are for what Dart leaves mutable.
141pub struct SearchDelegateData {
142    /// The hint text shown in the search field when it is empty.
143    ///
144    /// If this value is set to `None`, the value of
145    /// [`MaterialLocalizations::search_field_label`] will be used instead.
146    pub search_field_label: Option<String>,
147
148    /// The style of the [`search_field_label`](Self::search_field_label).
149    ///
150    /// If this value is set to `None`, the value of the ambient [`Theme`]'s
151    /// `InputDecorationThemeData.hint_style` will be used instead.
152    ///
153    /// Only one of [`search_field_style`](Self::search_field_style) or
154    /// [`search_field_decoration_theme`](Self::search_field_decoration_theme) can be non-`None`.
155    pub search_field_style: Option<TextStyle>,
156
157    /// The [`InputDecorationThemeData`] used to configure the search field's visuals.
158    ///
159    /// Only one of [`search_field_style`](Self::search_field_style) or
160    /// [`search_field_decoration_theme`](Self::search_field_decoration_theme) can be non-`None`.
161    pub search_field_decoration_theme: Option<InputDecorationThemeData>,
162
163    /// The type of action button to use for the keyboard.
164    ///
165    /// Defaults to the default value specified in [`TextField`].
166    pub keyboard_type: Option<TextInputType>,
167
168    /// The text input action configuring the soft keyboard to a particular action button.
169    ///
170    /// Defaults to [`TextInputAction::Search`].
171    pub text_input_action: TextInputAction,
172
173    /// Whether to enable autocorrection in the search field. Defaults to true.
174    pub autocorrect: bool,
175
176    /// Whether to show input suggestions as the user types in the search field. Defaults to true.
177    pub enable_suggestions: bool,
178
179    automatically_imply_leading: Cell<Option<bool>>,
180    leading_width: Cell<Option<f64>>,
181
182    /// The focus node to use for manipulating focus on the search page. This is managed, owned,
183    /// and set by the [`SearchPageRoute`] using this delegate.
184    focus_node: Cell<Option<Handle<FocusNode>>>,
185    query_text_controller: Ref<TextEditingController>,
186    proxy_animation: Ref<ProxyAnimation>,
187    current_body_notifier: Ref<ValueNotifier<Option<SearchBody>>>,
188    route: Cell<Option<Handle<SearchPageRoute>>>,
189}
190
191impl SearchDelegateData {
192    /// Creates the state of a delegate; Dart's `SearchDelegate({searchFieldLabel,
193    /// searchFieldStyle, searchFieldDecorationTheme, keyboardType, textInputAction, autocorrect,
194    /// enableSuggestions})` arguments are the setters.
195    pub fn new(app: &mut App) -> SearchDelegateData {
196        let always_dismissed = k_always_dismissed_animation(app);
197        SearchDelegateData {
198            search_field_label: None,
199            search_field_style: None,
200            search_field_decoration_theme: None,
201            keyboard_type: None,
202            text_input_action: TextInputAction::Search,
203            autocorrect: true,
204            enable_suggestions: true,
205            automatically_imply_leading: Cell::new(None),
206            leading_width: Cell::new(None),
207            focus_node: Cell::new(None),
208            query_text_controller: TextEditingController::new(app),
209            proxy_animation: ProxyAnimation::new(app, Some(always_dismissed)),
210            current_body_notifier: app.create(ValueNotifier::new(None)),
211            route: Cell::new(None),
212        }
213    }
214
215    /// Dart `SearchDelegate(searchFieldLabel:)`.
216    pub fn search_field_label(
217        mut self,
218        search_field_label: impl Into<String>,
219    ) -> SearchDelegateData {
220        self.search_field_label = Some(search_field_label.into());
221        self
222    }
223
224    /// Dart `SearchDelegate(searchFieldStyle:)`.
225    pub fn search_field_style(mut self, search_field_style: TextStyle) -> SearchDelegateData {
226        self.search_field_style = Some(search_field_style);
227        debug_assert!(self.search_field_decoration_theme.is_none());
228        self
229    }
230
231    /// Dart `SearchDelegate(searchFieldDecorationTheme:)`.
232    pub fn search_field_decoration_theme(
233        mut self,
234        search_field_decoration_theme: InputDecorationThemeData,
235    ) -> SearchDelegateData {
236        self.search_field_decoration_theme = Some(search_field_decoration_theme);
237        debug_assert!(self.search_field_style.is_none());
238        self
239    }
240
241    /// Dart `SearchDelegate(keyboardType:)`.
242    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> SearchDelegateData {
243        self.keyboard_type = Some(keyboard_type);
244        self
245    }
246
247    /// Dart `SearchDelegate(textInputAction:)`.
248    pub fn text_input_action(mut self, text_input_action: TextInputAction) -> SearchDelegateData {
249        self.text_input_action = text_input_action;
250        self
251    }
252
253    /// Dart `SearchDelegate(autocorrect:)`.
254    pub fn autocorrect(mut self, autocorrect: bool) -> SearchDelegateData {
255        self.autocorrect = autocorrect;
256        self
257    }
258
259    /// Dart `SearchDelegate(enableSuggestions:)`.
260    pub fn enable_suggestions(mut self, enable_suggestions: bool) -> SearchDelegateData {
261        self.enable_suggestions = enable_suggestions;
262        self
263    }
264
265    /// Dart's `SearchDelegate.automaticallyImplyLeading`: whether the app bar of the search page
266    /// implies a leading widget. When `None`, it is true.
267    pub fn automatically_imply_leading(&self) -> Option<bool> {
268        self.automatically_imply_leading.get()
269    }
270
271    /// Sets [`automatically_imply_leading`](Self::automatically_imply_leading).
272    pub fn set_automatically_imply_leading(&self, value: Option<bool>) {
273        self.automatically_imply_leading.set(value);
274    }
275
276    /// Dart's `SearchDelegate.leadingWidth`: the width of the app bar's leading widget.
277    pub fn leading_width(&self) -> Option<f64> {
278        self.leading_width.get()
279    }
280
281    /// Sets [`leading_width`](Self::leading_width).
282    pub fn set_leading_width(&self, value: Option<f64>) {
283        self.leading_width.set(value);
284    }
285}
286
287/// Delegate for [`ShowSearch`] to define the content of the search page.
288///
289/// The search page always shows an [`AppBar`] at the top where users can enter their search
290/// queries. The buttons shown before and after the search query text field can be customized via
291/// [`build_leading`](Self::build_leading) and [`build_actions`](Self::build_actions). Additionally,
292/// a widget can be placed across the bottom of the [`AppBar`] via
293/// [`build_bottom`](Self::build_bottom).
294///
295/// The body below the [`AppBar`] can either show suggested queries
296/// ([`build_suggestions`](Self::build_suggestions)) or, once the user has submitted a search,
297/// the results of the search as returned by [`build_results`](Self::build_results).
298///
299/// [`query`](Self::query) always contains the current query entered by the user and should be
300/// used to build the suggestions and results.
301///
302/// The results can be brought on screen by calling [`show_results`](Self::show_results) and you
303/// can go back to showing the suggestions by calling [`show_suggestions`](Self::show_suggestions).
304///
305/// Once the user has selected a search result, [`close`](Self::close) should be called to remove
306/// the search page from the screen and to return the selected search result back to the caller of
307/// [`ShowSearch`].
308///
309/// A delegate in use by [`ShowSearch`] is shared with the route, so what Dart keeps in the
310/// delegate's fields is read through [`search_delegate_data`](Self::search_delegate_data).
311pub trait SearchDelegate: 'static {
312    /// The state this delegate shares with its route and page.
313    fn search_delegate_data(&self) -> &SearchDelegateData;
314
315    /// Suggestions shown in the body of the search page while the user types a query into the
316    /// search field.
317    ///
318    /// The delegate method will be called whenever the content of [`query`](Self::query) changes.
319    /// The suggestions should be based on the current [`query`](Self::query) string. If the query
320    /// string is empty, it is good practice to show suggested queries based on past queries or the
321    /// current context.
322    ///
323    /// Usually, this method will return a [`ListView`](waft_widgets::ListView) with one
324    /// [`ListTile`](crate::ListTile) per suggestion. When [`ListTile::on_tap`] is called,
325    /// [`query`](Self::query) should be updated with the corresponding suggestion and the results
326    /// page should be shown by calling [`show_results`](Self::show_results).
327    fn build_suggestions(&self, app: &mut App, context: BuildContext) -> WidgetRef;
328
329    /// The results shown after the user submits a search from the search page.
330    ///
331    /// The current value of [`query`](Self::query) can be used to determine what the user searched
332    /// for.
333    ///
334    /// This method might be applied more than once to the same query. If your method is
335    /// computationally expensive, you may want to cache the search results for one or more queries.
336    ///
337    /// Typically, this method returns a [`ListView`](waft_widgets::ListView) with the search
338    /// results. When the user taps on a particular search result, [`close`](Self::close) should be
339    /// called with the selected result as argument. This will close the search page and communicate
340    /// the result back to the initial caller of [`ShowSearch`].
341    fn build_results(&self, app: &mut App, context: BuildContext) -> WidgetRef;
342
343    /// A widget to display before the current query in the [`AppBar`].
344    ///
345    /// Typically an [`IconButton`](crate::IconButton) configured with a
346    /// [`BackButtonIcon`](crate::BackButtonIcon) that exits the search with
347    /// [`close`](Self::close). One can also use an [`AnimatedIcon`](waft_widgets::AnimatedIcon)
348    /// driven by [`transition_animation`](Self::transition_animation), which animates from e.g. a
349    /// hamburger menu to the back button as the search overlay fades in.
350    ///
351    /// Returns `None` if no widget should be shown.
352    fn build_leading(&self, app: &mut App, context: BuildContext) -> Option<WidgetRef>;
353
354    /// Widgets to display after the search query in the [`AppBar`].
355    ///
356    /// If the [`query`](Self::query) is not empty, this should typically contain a button to clear
357    /// the query and show the suggestions again (via [`show_suggestions`](Self::show_suggestions))
358    /// if the results are currently shown.
359    ///
360    /// Returns `None` if no widget should be shown.
361    fn build_actions(&self, app: &mut App, context: BuildContext) -> Option<Vec<WidgetRef>>;
362
363    /// Widget to display across the bottom of the [`AppBar`].
364    ///
365    /// Typically a [`PreferredSize`](waft_widgets::PreferredSize) widget containing a widget that
366    /// provides additional information for the current search.
367    ///
368    /// Returns `None` by default, i.e. a bottom widget is not included.
369    fn build_bottom(&self, app: &mut App, context: BuildContext) -> Option<PreferredSizeWidgetRef> {
370        let _ = (app, context);
371        None
372    }
373
374    /// Widget to display behind the current query in the [`AppBar`].
375    ///
376    /// Returns `None` by default, i.e. a flexible space widget is not included.
377    fn build_flexible_space(&self, app: &mut App, context: BuildContext) -> Option<WidgetRef> {
378        let _ = (app, context);
379        None
380    }
381
382    /// The theme used to style the [`AppBar`].
383    ///
384    /// By default, a white theme is used.
385    ///
386    /// If [`SearchDelegateData::search_field_decoration_theme`] is set, it will be used to
387    /// override [`ThemeData::input_decoration_theme`]. Otherwise a theme whose hint style is
388    /// [`SearchDelegateData::search_field_style`] (or the ambient hint style) and whose border is
389    /// none is used.
390    fn app_bar_theme(&self, app: &mut App, context: BuildContext) -> ThemeData {
391        default_app_bar_theme(self.search_delegate_data(), app, context)
392    }
393
394    /// The current query string shown in the [`AppBar`].
395    ///
396    /// The user manipulates this string via the keyboard.
397    ///
398    /// If the user taps on a suggestion provided by
399    /// [`build_suggestions`](Self::build_suggestions) this string should be updated to that
400    /// suggestion via the setter.
401    fn query(&self, app: &App) -> String {
402        self.search_delegate_data()
403            .query_text_controller
404            .handle()
405            .value(app)
406            .text
407            .clone()
408    }
409
410    /// Changes the current query string.
411    ///
412    /// Setting the query string programmatically moves the cursor to the end of the text field.
413    fn set_query(&self, app: &mut App, value: String) {
414        let offset = value.chars().count();
415        self.search_delegate_data()
416            .query_text_controller
417            .handle()
418            .set_value(
419                app,
420                TextEditingValue {
421                    text: value,
422                    selection: TextSelection::collapsed(offset as i32, TextAffinity::Downstream),
423                    ..TextEditingValue::default()
424                },
425            );
426    }
427
428    /// Transition from the suggestions returned by [`build_suggestions`](Self::build_suggestions)
429    /// to the `query` results returned by [`build_results`](Self::build_results).
430    ///
431    /// If the user taps on a suggestion provided by
432    /// [`build_suggestions`](Self::build_suggestions) the existing search page will be
433    /// transformed to show the results of the suggestion.
434    fn show_results(&self, app: &mut App, context: BuildContext) {
435        let _ = context;
436        let data = self.search_delegate_data();
437        if let Some(focus_node) = data.focus_node.get() {
438            focus_node.unfocus(app, UnfocusDisposition::Scope);
439        }
440        data.current_body_notifier
441            .handle()
442            .set_value(app, Some(SearchBody::Results));
443    }
444
445    /// Transition from showing the results returned by
446    /// [`build_results`](Self::build_results) to showing the suggestions returned by
447    /// [`build_suggestions`](Self::build_suggestions).
448    ///
449    /// Calling this method will also put the input focus back into the search field of the
450    /// [`AppBar`].
451    ///
452    /// If the results are currently shown this method can be used to go back to showing the
453    /// search suggestions.
454    fn show_suggestions(&self, app: &mut App, context: BuildContext) {
455        let _ = context;
456        let data = self.search_delegate_data();
457        let focus_node = data
458            .focus_node
459            .get()
460            .expect("_focusNode must be set by route before showSuggestions is called.");
461        focus_node.request_focus(app, None);
462        data.current_body_notifier
463            .handle()
464            .set_value(app, Some(SearchBody::Suggestions));
465    }
466
467    /// Closes the search page and returns `result` to the caller of [`ShowSearch`].
468    ///
469    /// Might be called when the user taps on a search result shown by
470    /// [`build_results`](Self::build_results).
471    fn close(&self, app: &mut App, context: BuildContext, result: RouteResult) {
472        let data = self.search_delegate_data();
473        data.current_body_notifier.handle().set_value(app, None);
474        if let Some(focus_node) = data.focus_node.get() {
475            focus_node.unfocus(app, UnfocusDisposition::Scope);
476        }
477        pop_until_route_then_pop(app, context, data.route.get(), result);
478    }
479
480    /// The animation that drives the route's transition and the support for changing the current
481    /// body.
482    fn transition_animation(&self) -> AnimationRef<f64> {
483        self.search_delegate_data().proxy_animation.erase()
484    }
485
486    /// Releases the resources of this delegate.
487    ///
488    /// Call this when the delegate is no longer used.
489    fn dispose(&self, app: &mut App) {
490        let data = self.search_delegate_data();
491        data.current_body_notifier.handle().dispose(app);
492        if let Some(focus_node) = data.focus_node.get() {
493            focus_node.dispose(app);
494        }
495        data.query_text_controller.handle().dispose(app);
496        data.proxy_animation.handle().set_parent(app, None);
497    }
498}
499
500/// [`SearchDelegate::app_bar_theme`]'s default, which a delegate that overrides the method
501/// reaches as Dart's `super.appBarTheme(context)`.
502pub fn default_app_bar_theme(
503    data: &SearchDelegateData,
504    app: &mut App,
505    context: BuildContext,
506) -> ThemeData {
507    let theme = Theme::of(app, context);
508    let color_scheme = &theme.color_scheme;
509    let dark = color_scheme.brightness() == waft_embedder::Brightness::Dark;
510    let input_decoration_theme = data
511        .search_field_decoration_theme
512        .clone()
513        .unwrap_or_else(|| {
514            let hint_style = data
515                .search_field_style
516                .clone()
517                .map(waft_painting::AnyTextStyle::from)
518                .or_else(|| theme.input_decoration_theme.hint_style.clone());
519            let mut decoration_theme =
520                InputDecorationThemeData::new().border(InputBorderRef::none());
521            if let Some(hint_style) = hint_style {
522                decoration_theme = decoration_theme.hint_style(hint_style);
523            }
524            decoration_theme
525        });
526    let mut app_bar_theme = AppBarThemeData::new()
527        .system_overlay_style(if dark {
528            SystemUiOverlayStyle::LIGHT
529        } else {
530            SystemUiOverlayStyle::DARK
531        })
532        .background_color(if dark {
533            Colors::GREY.shade900()
534        } else {
535            Colors::WHITE
536        })
537        .icon_theme(
538            theme
539                .primary_icon_theme
540                .copy_with()
541                .color(Colors::GREY.primary()),
542        );
543    if let Some(title_large) = theme.text_theme.title_large.clone() {
544        app_bar_theme = app_bar_theme.title_text_style(title_large);
545    }
546    if let Some(body_medium) = theme.text_theme.body_medium.clone() {
547        app_bar_theme = app_bar_theme.toolbar_text_style(body_medium);
548    }
549    theme
550        .copy_with()
551        .app_bar_theme(app_bar_theme)
552        .input_decoration_theme(input_decoration_theme)
553        .build()
554}
555
556/// Dart's `Navigator.of(context)..popUntil((route) => route == _route)..pop(result)`.
557fn pop_until_route_then_pop(
558    app: &mut App,
559    context: BuildContext,
560    route: Option<Handle<SearchPageRoute>>,
561    result: RouteResult,
562) {
563    let navigator = Navigator::of(app, context, false);
564    navigator.pop_until(
565        app,
566        Rc::new(move |_app, candidate: AnyRoute| {
567            route.is_some_and(|route| candidate.id() == route.id())
568        }),
569    );
570    navigator.pop(app, result);
571}
572
573/// Dart's `_pop`: the escape key's close, which answers no result.
574fn pop_search(delegate: &dyn SearchDelegate, app: &mut App, context: BuildContext) {
575    let data = delegate.search_delegate_data();
576    data.current_body_notifier.handle().set_value(app, None);
577    if let Some(focus_node) = data.focus_node.get() {
578        focus_node.unfocus(app, UnfocusDisposition::Scope);
579    }
580    pop_until_route_then_pop(app, context, data.route.get(), None);
581}
582
583/// Dart's `_SearchPageRoute`.
584pub struct SearchPageRoute {
585    route: RouteData,
586    overlay_route: OverlayRouteData,
587    transition_route: TransitionRouteData,
588    local_history: LocalHistoryRouteData,
589    modal_route: ModalRouteData,
590    page_route: PageRouteData,
591    delegate: Rc<dyn SearchDelegate>,
592    maintain_state: bool,
593}
594
595impl SearchPageRoute {
596    fn new(
597        app: &mut App,
598        delegate: Rc<dyn SearchDelegate>,
599        maintain_state: bool,
600    ) -> Ref<SearchPageRoute> {
601        let route = RouteData::new(app, None, None);
602        let transition_route = TransitionRouteData::new(app);
603        let modal_route = ModalRouteData::new(app);
604        let this = app.create(SearchPageRoute {
605            route,
606            overlay_route: OverlayRouteData::new(),
607            transition_route,
608            local_history: LocalHistoryRouteData::new(),
609            modal_route,
610            page_route: PageRouteData::new(),
611            delegate: Rc::clone(&delegate),
612            maintain_state,
613        });
614        assert!(
615            delegate.search_delegate_data().route.get().is_none(),
616            "The delegate instance is currently used by another active search. Please close that \
617             search by calling close() on the SearchDelegate before opening another search with \
618             the same delegate instance."
619        );
620        delegate
621            .search_delegate_data()
622            .route
623            .set(Some(this.handle()));
624        this
625    }
626}
627
628impl Route for SearchPageRoute {
629    waft_widgets::page_route_overrides!();
630
631    fn did_complete(self: Handle<Self>, app: &mut App, result: RouteResult) {
632        waft_widgets::RouteBase::did_complete(self, app, result);
633        let delegate = Rc::clone(&app.get(self).delegate);
634        let data = delegate.search_delegate_data();
635        debug_assert!(
636            data.route
637                .get()
638                .is_some_and(|route| route.id() == self.id())
639        );
640        data.route.set(None);
641        data.current_body_notifier.handle().set_value(app, None);
642    }
643}
644
645impl OverlayRoute for SearchPageRoute {
646    waft_widgets::modal_overlay_route_overrides!();
647}
648
649impl PredictiveBackRoute for SearchPageRoute {
650    waft_widgets::page_predictive_back_route_overrides!();
651}
652
653impl TransitionRoute for SearchPageRoute {
654    waft_widgets::page_transition_route_overrides!();
655
656    fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
657        let _ = app;
658        Duration::from_millis(300)
659    }
660
661    fn opaque(self: Handle<Self>, app: &App) -> bool {
662        PageRoute::opaque(self, app)
663    }
664
665    fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
666        // Dart's `super.createAnimation()`: the trait's default body.
667        let animation = TransitionRouteBase::create_animation(self, app);
668        let delegate = Rc::clone(&app.get(self).delegate);
669        delegate
670            .search_delegate_data()
671            .proxy_animation
672            .handle()
673            .set_parent(app, Some(animation.clone()));
674        animation
675    }
676}
677
678impl LocalHistoryRoute for SearchPageRoute {
679    waft_widgets::local_history_route_accessors!();
680}
681
682impl ModalRoute for SearchPageRoute {
683    waft_widgets::modal_route_accessors!();
684
685    fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
686        PageRoute::barrier_dismissible(self, app)
687    }
688
689    fn barrier_color(self: Handle<Self>, app: &App) -> Option<waft_painting::Color> {
690        let _ = app;
691        None
692    }
693
694    fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
695        let _ = app;
696        None
697    }
698
699    fn maintain_state(self: Handle<Self>, app: &App) -> bool {
700        app.get(self).maintain_state
701    }
702
703    fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
704        PageRoute::fullscreen_dialog(self, app)
705    }
706
707    fn build_page(
708        self: Handle<Self>,
709        app: &mut App,
710        context: BuildContext,
711        animation: AnimationRef<f64>,
712        secondary_animation: AnimationRef<f64>,
713    ) -> WidgetRef {
714        let _ = (context, secondary_animation);
715        SearchPage {
716            delegate: Rc::clone(&app.get(self).delegate),
717            animation,
718        }
719        .into_widget()
720    }
721
722    fn build_transitions(
723        self: Handle<Self>,
724        app: &mut App,
725        context: BuildContext,
726        animation: AnimationRef<f64>,
727        secondary_animation: AnimationRef<f64>,
728        child: WidgetRef,
729    ) -> WidgetRef {
730        let _ = (app, context, secondary_animation);
731        FadeTransition::new(animation).child(child).into_widget()
732    }
733}
734
735impl PageRoute for SearchPageRoute {
736    waft_widgets::page_route_accessors!();
737}
738
739/// Dart's `_SearchPage`.
740struct SearchPage {
741    delegate: Rc<dyn SearchDelegate>,
742    animation: AnimationRef<f64>,
743}
744
745impl fmt::Debug for SearchPage {
746    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
747        f.debug_struct("SearchPage").finish_non_exhaustive()
748    }
749}
750
751impl StatefulWidget for SearchPage {
752    type State = SearchPageState;
753
754    fn create_state(&self) -> SearchPageState {
755        SearchPageState {
756            state: StateData::new(),
757            focus_node: None,
758        }
759    }
760}
761
762/// Dart's `_SearchPageState`.
763struct SearchPageState {
764    state: StateData<SearchPage>,
765    /// This node is owned, but not hosted by, the search page. Hosting is done by the text
766    /// field.
767    focus_node: Option<Ref<FocusNode>>,
768}
769
770impl SearchPageState {
771    fn on_query_changed(self: Handle<Self>, app: &mut App) {
772        self.set_state(app, |_| {});
773    }
774
775    fn on_search_body_changed(self: Handle<Self>, app: &mut App) {
776        self.set_state(app, |_| {});
777    }
778
779    fn on_focus_changed(self: Handle<Self>, app: &mut App) {
780        let focus_node = self.focus_node(app);
781        let delegate = Rc::clone(&self.widget(app).delegate);
782        let current_body = *delegate
783            .search_delegate_data()
784            .current_body_notifier
785            .handle()
786            .value(app);
787        if focus_node.has_focus(app) && current_body != Some(SearchBody::Suggestions) {
788            delegate.show_suggestions(app, self.context(app));
789        }
790    }
791
792    fn on_animation_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
793        if !status.is_completed() {
794            return;
795        }
796        let animation = self.widget(app).animation.clone();
797        animation.remove_status_listener(app, &self.status_listener());
798        let delegate = Rc::clone(&self.widget(app).delegate);
799        let current_body = *delegate
800            .search_delegate_data()
801            .current_body_notifier
802            .handle()
803            .value(app);
804        if current_body == Some(SearchBody::Suggestions) {
805            self.focus_node(app).request_focus(app, None);
806        }
807    }
808
809    fn status_listener(self: Handle<Self>) -> AnimationStatusListener {
810        AnimationStatusListener::handle_method(self, Self::on_animation_status_changed)
811    }
812
813    fn query_listener(self: Handle<Self>) -> Listener {
814        Listener::handle_method(self, Self::on_query_changed)
815    }
816
817    fn body_listener(self: Handle<Self>) -> Listener {
818        Listener::handle_method(self, Self::on_search_body_changed)
819    }
820
821    fn focus_listener(self: Handle<Self>) -> Listener {
822        Listener::handle_method(self, Self::on_focus_changed)
823    }
824
825    fn focus_node(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
826        app.get(self)
827            .focus_node
828            .as_ref()
829            .expect("initState made it")
830            .handle()
831    }
832}
833
834impl State for SearchPageState {
835    type Widget = SearchPage;
836    waft_widgets::state_accessors!();
837
838    fn init_state(self: Handle<Self>, app: &mut App) {
839        let delegate = Rc::clone(&self.widget(app).delegate);
840        let focus_node = FocusNode::new(app);
841        {
842            let handle = self;
843            focus_node.handle().set_on_key_event(
844                app,
845                Some(Rc::new(
846                    move |app, _node: AnyFocusNode, event: &KeyEvent| {
847                        // When the user presses the escape key, close the search page.
848                        if matches!(event, KeyEvent::Down(_))
849                            && event.logical_key() == LogicalKeyboardKey::ESCAPE
850                        {
851                            let delegate = Rc::clone(&handle.widget(app).delegate);
852                            let context = handle.context(app);
853                            pop_search(&*delegate, app, context);
854                            return KeyEventResult::Handled;
855                        }
856                        KeyEventResult::Ignored
857                    },
858                )),
859            );
860        }
861        app.get_mut(self).focus_node = Some(focus_node);
862        let data = delegate.search_delegate_data();
863        data.query_text_controller
864            .handle()
865            .add_listener(app, self.query_listener());
866        let animation = self.widget(app).animation.clone();
867        animation.add_status_listener(app, self.status_listener());
868        data.current_body_notifier
869            .handle()
870            .add_listener(app, self.body_listener());
871        self.focus_node(app)
872            .add_listener(app, self.focus_listener());
873        data.focus_node.set(Some(self.focus_node(app)));
874    }
875
876    fn dispose(self: Handle<Self>, app: &mut App) {
877        let delegate = Rc::clone(&self.widget(app).delegate);
878        let data = delegate.search_delegate_data();
879        data.query_text_controller
880            .handle()
881            .remove_listener(app, &self.query_listener());
882        let animation = self.widget(app).animation.clone();
883        animation.remove_status_listener(app, &self.status_listener());
884        data.current_body_notifier
885            .handle()
886            .remove_listener(app, &self.body_listener());
887        data.focus_node.set(None);
888        self.focus_node(app).dispose(app);
889    }
890
891    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SearchPage) {
892        let delegate = Rc::clone(&self.widget(app).delegate);
893        if !Rc::ptr_eq(&delegate, &old_widget.delegate) {
894            let old = old_widget.delegate.search_delegate_data();
895            let new = delegate.search_delegate_data();
896            old.query_text_controller
897                .handle()
898                .remove_listener(app, &self.query_listener());
899            new.query_text_controller
900                .handle()
901                .add_listener(app, self.query_listener());
902            old.current_body_notifier
903                .handle()
904                .remove_listener(app, &self.body_listener());
905            new.current_body_notifier
906                .handle()
907                .add_listener(app, self.body_listener());
908            old.focus_node.set(None);
909            new.focus_node.set(Some(self.focus_node(app)));
910        }
911    }
912
913    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
914        debug_assert!(debug_check_has_material_localizations(app, context));
915        let delegate = Rc::clone(&self.widget(app).delegate);
916        let data = delegate.search_delegate_data();
917        let theme = Rc::new(delegate.app_bar_theme(app, context));
918        let search_field_label = data
919            .search_field_label
920            .clone()
921            .unwrap_or_else(|| <dyn MaterialLocalizations>::of(app, context).search_field_label());
922        let body = match *data.current_body_notifier.handle().value(app) {
923            Some(SearchBody::Suggestions) => Some(
924                KeyedSubtree::new(delegate.build_suggestions(app, context))
925                    .key(ValueKey::new(SearchBody::Suggestions).into())
926                    .into_widget(),
927            ),
928            Some(SearchBody::Results) => Some(
929                KeyedSubtree::new(delegate.build_results(app, context))
930                    .key(ValueKey::new(SearchBody::Results).into())
931                    .into_widget(),
932            ),
933            None => None,
934        };
935
936        let route_name = match theme.platform {
937            waft_embedder::TargetPlatform::IOS | waft_embedder::TargetPlatform::MacOS => {
938                String::new()
939            }
940            _ => search_field_label.clone(),
941        };
942
943        let delegate_for_submit = Rc::clone(&delegate);
944        let text_field = TextField::new()
945            .controller(data.query_text_controller.erase())
946            .focus_node(
947                app.get(self)
948                    .focus_node
949                    .clone()
950                    .expect("initState made it")
951                    .into_erased(),
952            )
953            .text_input_action(data.text_input_action)
954            .autocorrect(data.autocorrect)
955            .enable_suggestions(data.enable_suggestions)
956            .on_submitted(move |app, _| {
957                delegate_for_submit.show_results(app, context);
958            })
959            .decoration(Some(InputDecoration::new().hint_text(search_field_label)));
960        let text_field = match data
961            .search_field_style
962            .clone()
963            .or_else(|| theme.text_theme.title_large.clone())
964        {
965            Some(style) => text_field.style(style),
966            None => text_field,
967        };
968        let text_field = match data.keyboard_type {
969            Some(keyboard_type) => text_field.keyboard_type(keyboard_type),
970            None => text_field,
971        };
972
973        let mut app_bar = AppBar::new()
974            .automatically_imply_leading(data.automatically_imply_leading().unwrap_or(true))
975            .title(
976                Semantics::new()
977                    .input_type(SemanticsInputType::Search)
978                    .child(text_field),
979            );
980        if let Some(leading_width) = data.leading_width() {
981            app_bar = app_bar.leading_width(leading_width);
982        }
983        if let Some(leading) = delegate.build_leading(app, context) {
984            app_bar = app_bar.leading(leading);
985        }
986        if let Some(flexible_space) = delegate.build_flexible_space(app, context) {
987            app_bar = app_bar.flexible_space(flexible_space);
988        }
989        if let Some(actions) = delegate.build_actions(app, context) {
990            app_bar = app_bar.actions(actions);
991        }
992        if let Some(bottom) = delegate.build_bottom(app, context) {
993            app_bar = app_bar.bottom(bottom);
994        }
995
996        let mut switcher = AnimatedSwitcher::new(Duration::from_millis(300));
997        if let Some(body) = body {
998            switcher = switcher.child(body);
999        }
1000        Semantics::new()
1001            .explicit_child_nodes(true)
1002            .scopes_route(true)
1003            .names_route(true)
1004            .label(route_name)
1005            .child(Theme::new(
1006                theme,
1007                Scaffold::new()
1008                    .app_bar(PreferredSizeWidgetRef::new(app_bar))
1009                    .body(switcher),
1010            ))
1011            .into_widget()
1012    }
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use std::cell::{Cell, RefCell};
1018
1019    use waft_animation::AnimationStatus;
1020    use waft_embedder::{Color, Offset, Size};
1021    use waft_foundation::Retained;
1022    use waft_services::PhysicalKeyboardKey;
1023    use waft_test::{MockClipboard, TestPlatform};
1024    use waft_widgets::testing::{
1025        WidgetTester, expect, find, finds_nothing, finds_one_widget, finds_widgets, test_widgets,
1026    };
1027    use waft_widgets::{EditableText, PreferredSize, RouteSettingsRef, Text, WidgetsBinding};
1028
1029    use super::*;
1030    use crate::elevated_button::ElevatedButton;
1031    use crate::icon_button::IconButton;
1032    use crate::icons::Icons;
1033    use crate::test_support::material_app;
1034    use crate::tooltip::tests::m3;
1035
1036    /// The constructor arguments of Dart's `_TestSearchDelegate` that are not the base class's.
1037    struct Options {
1038        suggestions: &'static str,
1039        result: &'static str,
1040        actions: Vec<WidgetRef>,
1041        flexible_space: Option<WidgetRef>,
1042        default_app_bar_theme: bool,
1043    }
1044
1045    impl Default for Options {
1046        fn default() -> Options {
1047            Options {
1048                suggestions: "Suggestions",
1049                result: "Result",
1050                actions: Vec::new(),
1051                flexible_space: None,
1052                default_app_bar_theme: false,
1053            }
1054        }
1055    }
1056
1057    /// Dart's `_TestSearchDelegate`.
1058    struct TestSearchDelegate {
1059        me: std::rc::Weak<TestSearchDelegate>,
1060        data: SearchDelegateData,
1061        options: Options,
1062        queries_for_suggestions: RefCell<Vec<String>>,
1063        queries_for_results: RefCell<Vec<String>>,
1064    }
1065
1066    impl TestSearchDelegate {
1067        fn new(
1068            app: &mut App,
1069            data: impl FnOnce(SearchDelegateData) -> SearchDelegateData,
1070        ) -> Rc<TestSearchDelegate> {
1071            TestSearchDelegate::with_options(app, data, Options::default())
1072        }
1073
1074        fn with_options(
1075            app: &mut App,
1076            data: impl FnOnce(SearchDelegateData) -> SearchDelegateData,
1077            options: Options,
1078        ) -> Rc<TestSearchDelegate> {
1079            let data = data(SearchDelegateData::new(app));
1080            Rc::new_cyclic(|me| TestSearchDelegate {
1081                me: me.clone(),
1082                data,
1083                options,
1084                queries_for_suggestions: RefCell::default(),
1085                queries_for_results: RefCell::default(),
1086            })
1087        }
1088
1089        fn this(&self) -> Rc<TestSearchDelegate> {
1090            self.me.upgrade().expect("the delegate is alive")
1091        }
1092    }
1093
1094    impl SearchDelegate for TestSearchDelegate {
1095        fn search_delegate_data(&self) -> &SearchDelegateData {
1096            &self.data
1097        }
1098
1099        fn app_bar_theme(&self, app: &mut App, context: BuildContext) -> ThemeData {
1100            if self.options.default_app_bar_theme {
1101                return default_app_bar_theme(&self.data, app, context);
1102            }
1103            let theme = Theme::of(app, context);
1104            let decoration_theme = self
1105                .data
1106                .search_field_decoration_theme
1107                .clone()
1108                .unwrap_or_else(|| {
1109                    InputDecorationThemeData::new().hint_style(
1110                        self.data
1111                            .search_field_style
1112                            .clone()
1113                            .unwrap_or_else(|| TextStyle::new().color(hint_text_color())),
1114                    )
1115                });
1116            theme
1117                .copy_with()
1118                .input_decoration_theme(decoration_theme)
1119                .build()
1120        }
1121
1122        fn build_leading(&self, _app: &mut App, context: BuildContext) -> Option<WidgetRef> {
1123            let delegate = self.this();
1124            Some(
1125                IconButton::new(
1126                    Some(Listener::new(move |app: &mut App| {
1127                        delegate.close(
1128                            app,
1129                            context,
1130                            Some(Rc::new(delegate.options.result.to_owned())),
1131                        );
1132                    })),
1133                    waft_widgets::Icon::new(Some(Icons::arrow_back())),
1134                )
1135                .tooltip("Back")
1136                .into_widget(),
1137            )
1138        }
1139
1140        fn build_suggestions(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1141            let query = self.query(app);
1142            self.queries_for_suggestions.borrow_mut().push(query);
1143            let delegate = self.this();
1144            ElevatedButton::new(
1145                Some(Listener::new(move |app: &mut App| {
1146                    delegate.show_results(app, context);
1147                })),
1148                Some(Text::new(self.options.suggestions)),
1149            )
1150            .into_widget()
1151        }
1152
1153        fn build_results(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
1154            let query = self.query(app);
1155            self.queries_for_results.borrow_mut().push(query);
1156            Text::new("Results").into_widget()
1157        }
1158
1159        fn build_actions(&self, _app: &mut App, _context: BuildContext) -> Option<Vec<WidgetRef>> {
1160            Some(self.options.actions.clone())
1161        }
1162
1163        fn build_flexible_space(
1164            &self,
1165            _app: &mut App,
1166            _context: BuildContext,
1167        ) -> Option<WidgetRef> {
1168            self.options.flexible_space.clone()
1169        }
1170
1171        fn build_bottom(
1172            &self,
1173            _app: &mut App,
1174            _context: BuildContext,
1175        ) -> Option<PreferredSizeWidgetRef> {
1176            Some(PreferredSizeWidgetRef::new(PreferredSize::new(
1177                Size::new(f64::INFINITY, 56.0),
1178                Text::new("Bottom"),
1179            )))
1180        }
1181    }
1182
1183    /// Dart's `_TestSearchDelegate.hintTextColor`.
1184    fn hint_text_color() -> Color {
1185        Colors::GREEN.primary()
1186    }
1187
1188    /// Dart's `_TestEmptySearchDelegate`: no leading, no actions, and a `Close` button as the
1189    /// bottom.
1190    struct EmptySearchDelegate {
1191        me: std::rc::Weak<EmptySearchDelegate>,
1192        data: SearchDelegateData,
1193    }
1194
1195    impl EmptySearchDelegate {
1196        fn new(app: &mut App) -> Rc<EmptySearchDelegate> {
1197            let data = SearchDelegateData::new(app);
1198            Rc::new_cyclic(|me| EmptySearchDelegate {
1199                me: me.clone(),
1200                data,
1201            })
1202        }
1203    }
1204
1205    impl SearchDelegate for EmptySearchDelegate {
1206        fn search_delegate_data(&self) -> &SearchDelegateData {
1207            &self.data
1208        }
1209
1210        fn build_leading(&self, _app: &mut App, _context: BuildContext) -> Option<WidgetRef> {
1211            None
1212        }
1213
1214        fn build_actions(&self, _app: &mut App, _context: BuildContext) -> Option<Vec<WidgetRef>> {
1215            None
1216        }
1217
1218        fn build_suggestions(&self, _app: &mut App, context: BuildContext) -> WidgetRef {
1219            let delegate = self.me.upgrade().expect("the delegate is alive");
1220            ElevatedButton::new(
1221                Some(Listener::new(move |app: &mut App| {
1222                    delegate.show_results(app, context);
1223                })),
1224                Some(Text::new("Suggestions")),
1225            )
1226            .into_widget()
1227        }
1228
1229        fn build_results(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1230            Text::new("Results").into_widget()
1231        }
1232
1233        fn build_bottom(
1234            &self,
1235            _app: &mut App,
1236            context: BuildContext,
1237        ) -> Option<PreferredSizeWidgetRef> {
1238            let delegate = self.me.upgrade().expect("the delegate is alive");
1239            Some(PreferredSizeWidgetRef::new(PreferredSize::new(
1240                Size::new(f64::INFINITY, 56.0),
1241                IconButton::new(
1242                    Some(Listener::new(move |app: &mut App| {
1243                        delegate.close(app, context, Some(Rc::new("Result".to_owned())));
1244                    })),
1245                    waft_widgets::Icon::new(Some(Icons::arrow_back())),
1246                )
1247                .tooltip("Close"),
1248            )))
1249        }
1250    }
1251
1252    /// The arguments of Dart's `TestHomePage` besides the delegate and the results.
1253    #[derive(Default)]
1254    struct HomeOptions {
1255        pass_in_initial_query: bool,
1256        initial_query: Option<&'static str>,
1257        theme: Option<ThemeData>,
1258        use_root_navigator: bool,
1259        maintain_state: bool,
1260    }
1261
1262    type Results = Rc<RefCell<Vec<Option<String>>>>;
1263
1264    /// Dart's `TestHomePage`.
1265    fn home_page_with(
1266        tester: &mut WidgetTester,
1267        delegate: Rc<dyn SearchDelegate>,
1268        results: &Results,
1269        options: HomeOptions,
1270    ) {
1271        let results = Rc::clone(results);
1272        let theme = options
1273            .theme
1274            .clone()
1275            .unwrap_or_else(|| m3(&tester.cell.borrow()));
1276        let HomeOptions {
1277            pass_in_initial_query,
1278            initial_query,
1279            use_root_navigator,
1280            maintain_state,
1281            ..
1282        } = options;
1283        tester.pump_widget(material_app(
1284            theme,
1285            waft_widgets::Builder::new(move |_app, _context| {
1286                let delegate = Rc::clone(&delegate);
1287                let results = Rc::clone(&results);
1288                Scaffold::new()
1289                    .app_bar(PreferredSizeWidgetRef::new(
1290                        AppBar::new().title(Text::new("HomeTitle")).actions(vec![
1291                            waft_widgets::Builder::new(move |_app, context| {
1292                                let delegate = Rc::clone(&delegate);
1293                                let results = Rc::clone(&results);
1294                                IconButton::new(
1295                                    Some(Listener::new(move |app: &mut App| {
1296                                        let results = Rc::clone(&results);
1297                                        {
1298                                            let mut show = ShowSearch::new(Rc::clone(&delegate))
1299                                                .use_root_navigator(use_root_navigator)
1300                                                .maintain_state(maintain_state);
1301                                            // Dart's `query` argument defaults to `''`.
1302                                            if pass_in_initial_query {
1303                                                show = show.query(initial_query.map(str::to_owned));
1304                                            }
1305                                            show.show(app, context)
1306                                        }
1307                                        .then(
1308                                            app,
1309                                            move |_app, result| {
1310                                                results.borrow_mut().push(result.and_then(|r| {
1311                                                    r.downcast_ref::<String>().cloned()
1312                                                }));
1313                                            },
1314                                        );
1315                                    })),
1316                                    waft_widgets::Icon::new(Some(Icons::search())),
1317                                )
1318                                .tooltip("Search")
1319                                .into_widget()
1320                            })
1321                            .into_widget(),
1322                        ]),
1323                    ))
1324                    .body(Text::new("HomeBody"))
1325                    .into_widget()
1326            })
1327            .into_widget(),
1328        ));
1329    }
1330
1331    /// Dart's `TestHomePage(delegate:, results:)`.
1332    fn home_page(
1333        tester: &mut WidgetTester,
1334        delegate: &Rc<TestSearchDelegate>,
1335        results: &Results,
1336        initial_query: Option<&'static str>,
1337    ) {
1338        home_page_with(
1339            tester,
1340            Rc::clone(delegate) as Rc<dyn SearchDelegate>,
1341            results,
1342            HomeOptions {
1343                pass_in_initial_query: initial_query.is_some(),
1344                initial_query,
1345                ..HomeOptions::default()
1346            },
1347        );
1348    }
1349
1350    fn open_search(tester: &mut WidgetTester) {
1351        tester.tap(find::by_tooltip("Search"));
1352        tester.pump_and_settle();
1353    }
1354
1355    fn text_present(tester: &WidgetTester, text: &str) -> bool {
1356        !find::text(text).evaluate(tester).is_empty()
1357    }
1358
1359    fn field_has_focus(tester: &WidgetTester) -> bool {
1360        let focus_node = tester.widget(find::by_type::<TextField>(), |field: &TextField| {
1361            field.focus_node.clone().expect("a focus node")
1362        });
1363        focus_node.handle().has_focus(&tester.cell.borrow_mut())
1364    }
1365
1366    #[test]
1367    fn changing_query_moves_cursor_to_the_end_of_query() {
1368        test_widgets(|tester| {
1369            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1370            let results = Rc::default();
1371            home_page(tester, &delegate, &results, None);
1372            tester.tap(find::by_tooltip("Search"));
1373            tester.pump();
1374            tester.pump_by(Duration::from_millis(300));
1375
1376            delegate.set_query(&mut tester.cell.borrow_mut(), "Foo".to_owned());
1377            let selection = delegate
1378                .search_delegate_data()
1379                .query_text_controller
1380                .handle()
1381                .value(&tester.cell.borrow())
1382                .selection;
1383            assert_eq!(selection.base_offset, "Foo".len() as i32);
1384            assert_eq!(selection.extent_offset, "Foo".len() as i32);
1385
1386            delegate.set_query(&mut tester.cell.borrow_mut(), String::new());
1387            let selection = delegate
1388                .search_delegate_data()
1389                .query_text_controller
1390                .handle()
1391                .value(&tester.cell.borrow())
1392                .selection;
1393            assert_eq!((selection.base_offset, selection.extent_offset), (0, 0));
1394        });
1395    }
1396
1397    #[test]
1398    fn can_open_and_close_search() {
1399        test_widgets(|tester| {
1400            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1401            let results = Rc::default();
1402            home_page(tester, &delegate, &results, None);
1403
1404            expect(tester, &find::text("HomeBody"), finds_one_widget());
1405            expect(tester, &find::text("HomeTitle"), finds_one_widget());
1406            expect(tester, &find::text("Suggestions"), finds_nothing());
1407
1408            open_search(tester);
1409            expect(tester, &find::text("HomeBody"), finds_nothing());
1410            expect(tester, &find::text("HomeTitle"), finds_nothing());
1411            expect(tester, &find::text("Suggestions"), finds_one_widget());
1412            assert!(results.borrow().is_empty());
1413            assert!(field_has_focus(tester));
1414
1415            tester.tap(find::by_tooltip("Back"));
1416            tester.pump_and_settle();
1417            expect(tester, &find::text("HomeBody"), finds_one_widget());
1418            expect(tester, &find::text("HomeTitle"), finds_one_widget());
1419            expect(tester, &find::text("Suggestions"), finds_nothing());
1420            assert_eq!(*results.borrow(), vec![Some("Result".to_owned())]);
1421        });
1422    }
1423
1424    #[test]
1425    fn requests_suggestions() {
1426        test_widgets(|tester| {
1427            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1428            let results = Rc::default();
1429            home_page(tester, &delegate, &results, None);
1430            open_search(tester);
1431            assert_eq!(delegate.query(&tester.cell.borrow()), "");
1432            assert_eq!(
1433                delegate
1434                    .queries_for_suggestions
1435                    .borrow()
1436                    .last()
1437                    .map(String::as_str),
1438                Some("")
1439            );
1440            assert!(delegate.queries_for_results.borrow().is_empty());
1441
1442            delegate.queries_for_suggestions.borrow_mut().clear();
1443            for typed in ["W", "Wo", "Wow"] {
1444                tester.enter_text(find::by_type::<EditableText>(), typed);
1445                tester.pump_and_settle();
1446                assert_eq!(delegate.query(&tester.cell.borrow()), typed);
1447            }
1448            assert_eq!(
1449                *delegate.queries_for_suggestions.borrow(),
1450                vec!["W", "Wo", "Wow"]
1451            );
1452            assert!(delegate.queries_for_results.borrow().is_empty());
1453        });
1454    }
1455
1456    #[test]
1457    fn shows_results_and_closes_search() {
1458        test_widgets(|tester| {
1459            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1460            let results = Rc::default();
1461            home_page(tester, &delegate, &results, None);
1462            open_search(tester);
1463            tester.enter_text(find::by_type::<EditableText>(), "Wow");
1464            tester.pump_and_settle();
1465            tester.tap(find::text("Suggestions"));
1466            tester.pump_and_settle();
1467
1468            expect(tester, &find::text("HomeBody"), finds_nothing());
1469            expect(tester, &find::text("HomeTitle"), finds_nothing());
1470            expect(tester, &find::text("Suggestions"), finds_nothing());
1471            expect(tester, &find::text("Results"), finds_one_widget());
1472            assert!(!field_has_focus(tester));
1473            assert_eq!(*delegate.queries_for_results.borrow(), vec!["Wow"]);
1474
1475            tester.tap(find::by_tooltip("Back"));
1476            tester.pump_and_settle();
1477            expect(tester, &find::text("HomeBody"), finds_one_widget());
1478            expect(tester, &find::text("HomeTitle"), finds_one_widget());
1479            expect(tester, &find::text("Results"), finds_nothing());
1480            assert_eq!(*results.borrow(), vec![Some("Result".to_owned())]);
1481        });
1482    }
1483
1484    #[test]
1485    fn can_switch_between_results_and_suggestions() {
1486        test_widgets(|tester| {
1487            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1488            let results = Rc::default();
1489            home_page(tester, &delegate, &results, None);
1490            open_search(tester);
1491            expect(tester, &find::text("Suggestions"), finds_one_widget());
1492            expect(tester, &find::text("Results"), finds_nothing());
1493
1494            delegate.queries_for_suggestions.borrow_mut().clear();
1495            tester.enter_text(find::by_type::<EditableText>(), "Wow");
1496            tester.pump_and_settle();
1497            assert_eq!(*delegate.queries_for_suggestions.borrow(), vec!["Wow"]);
1498            assert!(delegate.queries_for_results.borrow().is_empty());
1499
1500            tester.tap(find::text("Suggestions"));
1501            tester.pump_and_settle();
1502            expect(tester, &find::text("Suggestions"), finds_nothing());
1503            expect(tester, &find::text("Results"), finds_one_widget());
1504            assert_eq!(*delegate.queries_for_suggestions.borrow(), vec!["Wow"]);
1505            assert_eq!(*delegate.queries_for_results.borrow(), vec!["Wow"]);
1506            assert!(!field_has_focus(tester));
1507
1508            tester.tap(find::by_type::<TextField>());
1509            tester.pump_and_settle();
1510            assert!(field_has_focus(tester));
1511            expect(tester, &find::text("Suggestions"), finds_one_widget());
1512            expect(tester, &find::text("Results"), finds_nothing());
1513            assert_eq!(
1514                *delegate.queries_for_suggestions.borrow(),
1515                vec!["Wow", "Wow"]
1516            );
1517            assert_eq!(*delegate.queries_for_results.borrow(), vec!["Wow"]);
1518
1519            tester.enter_text(find::by_type::<EditableText>(), "Foo");
1520            tester.pump_and_settle();
1521            assert_eq!(delegate.query(&tester.cell.borrow()), "Foo");
1522            assert_eq!(
1523                *delegate.queries_for_suggestions.borrow(),
1524                vec!["Wow", "Wow", "Foo"]
1525            );
1526
1527            tester.tap(find::text("Suggestions"));
1528            tester.pump_and_settle();
1529            expect(tester, &find::text("Results"), finds_one_widget());
1530            assert_eq!(*delegate.queries_for_results.borrow(), vec!["Wow", "Foo"]);
1531            assert!(!field_has_focus(tester));
1532        });
1533    }
1534
1535    #[test]
1536    fn fresh_search_always_starts_with_empty_query() {
1537        test_widgets(|tester| {
1538            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1539            let results = Rc::default();
1540            home_page(tester, &delegate, &results, None);
1541            open_search(tester);
1542            assert_eq!(delegate.query(&tester.cell.borrow()), "");
1543            delegate.set_query(&mut tester.cell.borrow_mut(), "Foo".to_owned());
1544
1545            tester.tap(find::by_tooltip("Back"));
1546            tester.pump_and_settle();
1547            open_search(tester);
1548            assert_eq!(delegate.query(&tester.cell.borrow()), "");
1549        });
1550    }
1551
1552    #[test]
1553    fn initial_queries_are_honored() {
1554        test_widgets(|tester| {
1555            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1556            let results = Rc::default();
1557            assert_eq!(delegate.query(&tester.cell.borrow()), "");
1558            home_page(tester, &delegate, &results, Some("Foo"));
1559            open_search(tester);
1560            assert_eq!(delegate.query(&tester.cell.borrow()), "Foo");
1561        });
1562    }
1563
1564    #[test]
1565    fn changing_query_shows_up_in_search_field() {
1566        test_widgets(|tester| {
1567            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1568            let results = Rc::default();
1569            home_page(tester, &delegate, &results, None);
1570            open_search(tester);
1571
1572            delegate.set_query(&mut tester.cell.borrow_mut(), "Foo".to_owned());
1573            assert!(text_present(tester, "Foo"));
1574            assert!(!text_present(tester, "Bar"));
1575
1576            delegate.set_query(&mut tester.cell.borrow_mut(), "Bar".to_owned());
1577            assert!(!text_present(tester, "Foo"));
1578            assert!(text_present(tester, "Bar"));
1579        });
1580    }
1581
1582    #[test]
1583    fn transition_animation_runs_while_search_fades_in_and_out() {
1584        test_widgets(|tester| {
1585            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1586            let results = Rc::default();
1587            home_page(tester, &delegate, &results, None);
1588            let status = |tester: &WidgetTester| {
1589                delegate
1590                    .transition_animation()
1591                    .status(&tester.cell.borrow())
1592            };
1593
1594            assert_eq!(status(tester), AnimationStatus::Dismissed);
1595            tester.tap(find::by_tooltip("Search"));
1596            assert_eq!(status(tester), AnimationStatus::Forward);
1597            tester.pump_and_settle();
1598            assert_eq!(status(tester), AnimationStatus::Completed);
1599
1600            tester.tap(find::text("Suggestions"));
1601            assert_eq!(status(tester), AnimationStatus::Completed);
1602            tester.pump_and_settle();
1603            assert_eq!(status(tester), AnimationStatus::Completed);
1604
1605            tester.tap(find::by_tooltip("Back"));
1606            assert_eq!(status(tester), AnimationStatus::Reverse);
1607            tester.pump_and_settle();
1608            assert_eq!(status(tester), AnimationStatus::Dismissed);
1609        });
1610    }
1611
1612    #[test]
1613    fn custom_and_default_search_field_labels() {
1614        test_widgets(|tester| {
1615            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| {
1616                d.search_field_label("Enter search terms")
1617            });
1618            let results = Rc::default();
1619            home_page(tester, &delegate, &results, None);
1620            open_search(tester);
1621            expect(
1622                tester,
1623                &find::text("Enter search terms"),
1624                finds_one_widget(),
1625            );
1626            expect(tester, &find::text("Search"), finds_nothing());
1627        });
1628        test_widgets(|tester| {
1629            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1630            let results = Rc::default();
1631            home_page(tester, &delegate, &results, None);
1632            open_search(tester);
1633            expect(tester, &find::text("Search"), finds_one_widget());
1634        });
1635    }
1636
1637    #[test]
1638    fn custom_and_default_autocorrect_and_enable_suggestions() {
1639        test_widgets(|tester| {
1640            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1641            let results = Rc::default();
1642            home_page(tester, &delegate, &results, None);
1643            open_search(tester);
1644            tester.widget(find::by_type::<TextField>(), |field: &TextField| {
1645                assert_eq!(field.autocorrect, Some(true));
1646                assert!(field.enable_suggestions);
1647            });
1648        });
1649        test_widgets(|tester| {
1650            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| {
1651                d.autocorrect(false).enable_suggestions(false)
1652            });
1653            let results = Rc::default();
1654            home_page(tester, &delegate, &results, None);
1655            open_search(tester);
1656            tester.widget(find::by_type::<TextField>(), |field: &TextField| {
1657                assert_eq!(field.autocorrect, Some(false));
1658                assert!(!field.enable_suggestions);
1659            });
1660        });
1661    }
1662
1663    #[test]
1664    fn can_close_search_with_escape_button_and_return_null() {
1665        test_widgets(|tester| {
1666            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1667            let results = Rc::default();
1668            home_page(tester, &delegate, &results, None);
1669            open_search(tester);
1670            expect(tester, &find::text("Suggestions"), finds_one_widget());
1671
1672            tester.send_key_event(PhysicalKeyboardKey::ESCAPE, LogicalKeyboardKey::ESCAPE);
1673            tester.pump_and_settle();
1674            assert_eq!(*results.borrow(), vec![None]);
1675            expect(tester, &find::text("HomeBody"), finds_one_widget());
1676            expect(tester, &find::text("Suggestions"), finds_nothing());
1677
1678            open_search(tester);
1679            expect(tester, &find::text("Suggestions"), finds_one_widget());
1680        });
1681    }
1682
1683    #[test]
1684    fn leading_width_size_is_16() {
1685        test_widgets(|tester| {
1686            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1687            delegate
1688                .search_delegate_data()
1689                .set_leading_width(Some(16.0));
1690            let results = Rc::default();
1691            home_page(tester, &delegate, &results, None);
1692
1693            // Open the search page with check leading width smaller than 16.
1694            open_search(tester);
1695            tester.tap_at(Offset::new(16.0, 16.0), 1);
1696            expect(tester, &find::text("Suggestions"), finds_one_widget());
1697            tester.widget(find::by_type::<AppBar>(), |app_bar: &AppBar| {
1698                assert_eq!(app_bar.leading_width, Some(16.0));
1699            });
1700            tester.tap_at(Offset::new(8.0, 16.0), 1);
1701            tester.pump_and_settle();
1702            expect(tester, &find::text("Suggestions"), finds_nothing());
1703            expect(tester, &find::text("HomeBody"), finds_one_widget());
1704        });
1705    }
1706
1707    /// Dart's `_MyNavigatorObserver`: the routes pushed but the root and `nested` ones, and the
1708    /// `maintainState` of the last search route.
1709    #[derive(Default)]
1710    struct CountingObserver {
1711        navigator_observer: waft_widgets::NavigatorObserverData,
1712        push_count: Cell<u32>,
1713        maintain_state: Cell<bool>,
1714    }
1715
1716    impl waft_widgets::NavigatorObserver for CountingObserver {
1717        waft_widgets::navigator_observer_accessors!();
1718
1719        fn did_push(
1720            self: Handle<Self>,
1721            app: &mut App,
1722            route: AnyRoute,
1723            _previous: Option<AnyRoute>,
1724        ) {
1725            // Don't count the root route.
1726            if matches!(route.settings(app).name(), Some("nested" | "/")) {
1727                return;
1728            }
1729            if let Some(search_route) = route.downcast::<SearchPageRoute>(app) {
1730                let maintain_state = ModalRoute::maintain_state(search_route, app);
1731                app.get(self).maintain_state.set(maintain_state);
1732            }
1733            let count = &app.get(self).push_count;
1734            count.set(count.get() + 1);
1735        }
1736    }
1737
1738    fn observer(tester: &WidgetTester) -> Retained<Handle<CountingObserver>> {
1739        tester.update(|app| app.create(CountingObserver::default()))
1740    }
1741
1742    fn push_count(tester: &WidgetTester, observer: &Retained<Handle<CountingObserver>>) -> u32 {
1743        tester.cell.borrow().get(observer).push_count.get()
1744    }
1745
1746    /// An action that runs `on_pressed` with the button's own context, as Dart's
1747    /// `Builder(builder: (context) => IconButton(tooltip:, icon:, onPressed:))`.
1748    fn action(
1749        tooltip: &'static str,
1750        icon: waft_widgets::IconData,
1751        on_pressed: impl Fn(&mut App, BuildContext) + 'static,
1752    ) -> WidgetRef {
1753        let on_pressed = Rc::new(on_pressed);
1754        waft_widgets::Builder::new(move |_app, context| {
1755            let on_pressed = Rc::clone(&on_pressed);
1756            IconButton::new(
1757                Some(Listener::new(move |app: &mut App| on_pressed(app, context))),
1758                waft_widgets::Icon::new(Some(icon.clone())),
1759            )
1760            .tooltip(tooltip)
1761            .into_widget()
1762        })
1763        .into_widget()
1764    }
1765
1766    /// Dart's `showSearch(context:, delegate:)` whose result is added to `results`.
1767    fn show_search_into(
1768        app: &mut App,
1769        context: BuildContext,
1770        delegate: &Rc<TestSearchDelegate>,
1771        results: &Results,
1772    ) {
1773        let results = Rc::clone(results);
1774        ShowSearch::new(Rc::clone(delegate) as Rc<dyn SearchDelegate>)
1775            .show(app, context)
1776            .then(app, move |_app, result| {
1777                results
1778                    .borrow_mut()
1779                    .push(result.and_then(|r| r.downcast_ref::<String>().cloned()));
1780            });
1781    }
1782
1783    /// The engine's `popRoute` on `flutter/navigation`.
1784    fn pop_route(tester: &WidgetTester) {
1785        let mut app = tester.cell.borrow_mut();
1786        let view = app.platform().views().first().expect("a view").id();
1787        WidgetsBinding::instance(&mut app).handle_pop_route(&mut app, view);
1788        app.drain_microtasks();
1789    }
1790
1791    /// Dart's `tester.showKeyboard(find.byType(TextField))`: what the text input was configured
1792    /// with.
1793    fn keyboard_input_action(tester: &mut WidgetTester) -> TextInputAction {
1794        tester.show_keyboard(find::by_type::<EditableText>());
1795        tester
1796            .view()
1797            .test_host()
1798            .text_input_calls()
1799            .into_iter()
1800            .rev()
1801            .find_map(|call| match call {
1802                waft_test::TextInputCall::SetClient(configuration) => {
1803                    Some(configuration.input_action)
1804                }
1805                _ => None,
1806            })
1807            .expect("the text input was given a client")
1808    }
1809
1810    #[test]
1811    fn can_close_search_with_system_back_button_to_return_null() {
1812        // Regression test for https://github.com/flutter/flutter/issues/18145
1813        test_widgets(|tester| {
1814            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1815            let results = Rc::default();
1816            home_page(tester, &delegate, &results, None);
1817
1818            // We are on the homepage.
1819            expect(tester, &find::text("HomeBody"), finds_one_widget());
1820            expect(tester, &find::text("HomeTitle"), finds_one_widget());
1821            expect(tester, &find::text("Suggestions"), finds_nothing());
1822
1823            open_search(tester);
1824            expect(tester, &find::text("HomeBody"), finds_nothing());
1825            expect(tester, &find::text("HomeTitle"), finds_nothing());
1826            expect(tester, &find::text("Suggestions"), finds_one_widget());
1827            expect(tester, &find::text("Bottom"), finds_one_widget());
1828
1829            // Simulate system back button.
1830            pop_route(tester);
1831            tester.pump_and_settle();
1832            assert_eq!(*results.borrow(), vec![None]);
1833
1834            // We are on the homepage again.
1835            expect(tester, &find::text("HomeBody"), finds_one_widget());
1836            expect(tester, &find::text("HomeTitle"), finds_one_widget());
1837            expect(tester, &find::text("Suggestions"), finds_nothing());
1838
1839            // Open search again.
1840            open_search(tester);
1841            expect(tester, &find::text("HomeBody"), finds_nothing());
1842            expect(tester, &find::text("HomeTitle"), finds_nothing());
1843            expect(tester, &find::text("Suggestions"), finds_one_widget());
1844        });
1845    }
1846
1847    #[test]
1848    fn hint_text_color_overridden() {
1849        test_widgets(|tester| {
1850            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| {
1851                d.search_field_label("Enter search terms")
1852            });
1853            home_page(tester, &delegate, &Results::default(), None);
1854            open_search(tester);
1855
1856            let color = tester.widget(find::text("Enter search terms"), |text: &Text| {
1857                text.style.as_ref().and_then(|style| style.color.clone())
1858            });
1859            assert_eq!(color.map(|color| color.color()), Some(hint_text_color()));
1860        });
1861    }
1862
1863    #[test]
1864    fn initial_query_null_reuses_previous_query() {
1865        test_widgets(|tester| {
1866            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
1867            delegate.set_query(&mut tester.cell.borrow_mut(), "Foo".to_owned());
1868            home_page_with(
1869                tester,
1870                Rc::clone(&delegate) as Rc<dyn SearchDelegate>,
1871                &Results::default(),
1872                HomeOptions {
1873                    pass_in_initial_query: true,
1874                    ..HomeOptions::default()
1875                },
1876            );
1877            open_search(tester);
1878            assert_eq!(delegate.query(&tester.cell.borrow()), "Foo");
1879        });
1880    }
1881
1882    #[test]
1883    fn closing_nested_search_returns_to_search() {
1884        test_widgets(|tester| {
1885            let nested_results = Results::default();
1886            let nested = TestSearchDelegate::with_options(
1887                &mut tester.cell.borrow_mut(),
1888                |d| d,
1889                Options {
1890                    suggestions: "Nested Suggestions",
1891                    result: "Nested Result",
1892                    ..Options::default()
1893                },
1894            );
1895            let delegate = TestSearchDelegate::with_options(
1896                &mut tester.cell.borrow_mut(),
1897                |d| d,
1898                Options {
1899                    actions: vec![action("Nested Search", Icons::search(), {
1900                        let nested = Rc::clone(&nested);
1901                        let nested_results = Rc::clone(&nested_results);
1902                        move |app, context| show_search_into(app, context, &nested, &nested_results)
1903                    })],
1904                    ..Options::default()
1905                },
1906            );
1907            let results = Results::default();
1908            home_page(tester, &delegate, &results, None);
1909            expect(tester, &find::text("HomeBody"), finds_one_widget());
1910            open_search(tester);
1911
1912            expect(tester, &find::text("HomeBody"), finds_nothing());
1913            expect(tester, &find::text("Suggestions"), finds_one_widget());
1914            expect(tester, &find::text("Nested Suggestions"), finds_nothing());
1915
1916            tester.tap(find::by_tooltip("Nested Search"));
1917            tester.pump_and_settle();
1918            expect(tester, &find::text("HomeBody"), finds_nothing());
1919            expect(tester, &find::text("Suggestions"), finds_nothing());
1920            expect(
1921                tester,
1922                &find::text("Nested Suggestions"),
1923                finds_one_widget(),
1924            );
1925
1926            tester.tap(find::by_tooltip("Back"));
1927            tester.pump_and_settle();
1928            assert_eq!(
1929                *nested_results.borrow(),
1930                vec![Some("Nested Result".to_owned())]
1931            );
1932            expect(tester, &find::text("HomeBody"), finds_nothing());
1933            expect(tester, &find::text("Suggestions"), finds_one_widget());
1934            expect(tester, &find::text("Nested Suggestions"), finds_nothing());
1935
1936            tester.tap(find::by_tooltip("Back"));
1937            tester.pump_and_settle();
1938            expect(tester, &find::text("HomeBody"), finds_one_widget());
1939            expect(tester, &find::text("Suggestions"), finds_nothing());
1940            expect(tester, &find::text("Nested Suggestions"), finds_nothing());
1941            assert_eq!(*results.borrow(), vec![Some("Result".to_owned())]);
1942        });
1943    }
1944
1945    #[test]
1946    fn closing_search_with_nested_search_shown_goes_back_to_the_underlying_route() {
1947        test_widgets(|tester| {
1948            let delegate: Rc<RefCell<Option<Rc<TestSearchDelegate>>>> = Rc::default();
1949            let nested_results = Results::default();
1950            let nested = TestSearchDelegate::with_options(
1951                &mut tester.cell.borrow_mut(),
1952                |d| d,
1953                Options {
1954                    suggestions: "Nested Suggestions",
1955                    result: "Nested Result",
1956                    actions: vec![action("Close Search", Icons::close(), {
1957                        let delegate = Rc::clone(&delegate);
1958                        move |app, context| {
1959                            let delegate = delegate.borrow().clone().expect("the delegate");
1960                            delegate.close(app, context, Some(Rc::new("Result Foo".to_owned())));
1961                        }
1962                    })],
1963                    ..Options::default()
1964                },
1965            );
1966            *delegate.borrow_mut() = Some(TestSearchDelegate::with_options(
1967                &mut tester.cell.borrow_mut(),
1968                |d| d,
1969                Options {
1970                    actions: vec![action("Nested Search", Icons::search(), {
1971                        let nested = Rc::clone(&nested);
1972                        let nested_results = Rc::clone(&nested_results);
1973                        move |app, context| show_search_into(app, context, &nested, &nested_results)
1974                    })],
1975                    ..Options::default()
1976                },
1977            ));
1978            let outer = delegate.borrow().clone().expect("the delegate");
1979            let results = Results::default();
1980            home_page(tester, &outer, &results, None);
1981
1982            expect(tester, &find::text("HomeBody"), finds_one_widget());
1983            open_search(tester);
1984            expect(tester, &find::text("HomeBody"), finds_nothing());
1985            expect(tester, &find::text("Suggestions"), finds_one_widget());
1986            expect(tester, &find::text("Nested Suggestions"), finds_nothing());
1987
1988            tester.tap(find::by_tooltip("Nested Search"));
1989            tester.pump_and_settle();
1990            expect(tester, &find::text("HomeBody"), finds_nothing());
1991            expect(tester, &find::text("Suggestions"), finds_nothing());
1992            expect(
1993                tester,
1994                &find::text("Nested Suggestions"),
1995                finds_one_widget(),
1996            );
1997
1998            tester.tap(find::by_tooltip("Close Search"));
1999            tester.pump_and_settle();
2000            expect(tester, &find::text("HomeBody"), finds_one_widget());
2001            expect(tester, &find::text("Suggestions"), finds_nothing());
2002            expect(tester, &find::text("Nested Suggestions"), finds_nothing());
2003            assert_eq!(*nested_results.borrow(), vec![None]);
2004            assert_eq!(*results.borrow(), vec![Some("Result Foo".to_owned())]);
2005        });
2006    }
2007
2008    #[test]
2009    fn custom_search_field_style_value() {
2010        test_widgets(|tester| {
2011            let style = TextStyle::new().color(Colors::RED.primary()).font_size(3.0);
2012            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), {
2013                let style = style.clone();
2014                |d| {
2015                    d.search_field_label("Enter search terms")
2016                        .search_field_style(style)
2017                }
2018            });
2019            home_page(tester, &delegate, &Results::default(), None);
2020            open_search(tester);
2021
2022            let hint = tester.widget(find::text("Enter search terms"), |text: &Text| {
2023                text.style.clone()
2024            });
2025            let field_style = tester.widget(find::by_type::<TextField>(), |field: &TextField| {
2026                field.style.clone().map(|style| style.value().clone())
2027            });
2028            for actual in [hint, field_style] {
2029                let actual = actual.expect("a style");
2030                assert_eq!(
2031                    actual.color.map(|color| color.color()),
2032                    Some(Colors::RED.primary())
2033                );
2034                assert_eq!(actual.font_size, Some(3.0));
2035            }
2036        });
2037    }
2038
2039    #[test]
2040    fn keyboard_shows_the_search_button_by_default() {
2041        test_widgets(|tester| {
2042            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
2043            home_page(tester, &delegate, &Results::default(), None);
2044            open_search(tester);
2045            assert_eq!(keyboard_input_action(tester), TextInputAction::Search);
2046        });
2047    }
2048
2049    #[test]
2050    fn custom_text_input_action_results_in_keyboard_with_the_corresponding_button() {
2051        test_widgets(|tester| {
2052            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| {
2053                d.text_input_action(TextInputAction::Done)
2054            });
2055            home_page(tester, &delegate, &Results::default(), None);
2056            open_search(tester);
2057            assert_eq!(keyboard_input_action(tester), TextInputAction::Done);
2058        });
2059    }
2060
2061    #[test]
2062    fn custom_flexible_space_value() {
2063        test_widgets(|tester| {
2064            let flexible_space = Text::new("custom flexibleSpace").into_widget();
2065            let delegate = TestSearchDelegate::with_options(
2066                &mut tester.cell.borrow_mut(),
2067                |d| d,
2068                Options {
2069                    flexible_space: Some(flexible_space.clone()),
2070                    ..Options::default()
2071                },
2072            );
2073            home_page(tester, &delegate, &Results::default(), None);
2074            open_search(tester);
2075            expect(
2076                tester,
2077                &find::by_widget(&flexible_space),
2078                finds_one_widget(),
2079            );
2080        });
2081    }
2082
2083    #[test]
2084    fn custom_search_field_decoration_theme_value() {
2085        test_widgets(|tester| {
2086            let decoration_theme = InputDecorationThemeData::new()
2087                .hint_style(TextStyle::new().color(hint_text_color()));
2088            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), {
2089                let decoration_theme = decoration_theme.clone();
2090                |d| d.search_field_decoration_theme(decoration_theme)
2091            });
2092            home_page(tester, &delegate, &Results::default(), None);
2093            open_search(tester);
2094
2095            let text_field = tester.element(find::by_type::<TextField>());
2096            let theme = Theme::of(&mut tester.cell.borrow_mut(), text_field);
2097            assert_eq!(theme.input_decoration_theme, decoration_theme);
2098        });
2099    }
2100
2101    /// Dart's 'text in search bar contrasts background' cases, which differ in the theme only.
2102    fn text_in_search_bar_contrasts_background(
2103        tester: &mut WidgetTester,
2104        theme: ThemeData,
2105        background: Color,
2106    ) {
2107        let delegate = TestSearchDelegate::with_options(
2108            &mut tester.cell.borrow_mut(),
2109            |d| d,
2110            Options {
2111                default_app_bar_theme: true,
2112                ..Options::default()
2113            },
2114        );
2115        home_page_with(
2116            tester,
2117            Rc::clone(&delegate) as Rc<dyn SearchDelegate>,
2118            &Results::default(),
2119            HomeOptions {
2120                pass_in_initial_query: true,
2121                initial_query: Some("search query"),
2122                theme: Some(theme.clone()),
2123                ..HomeOptions::default()
2124            },
2125        );
2126        open_search(tester);
2127
2128        let app_bar_background = find::descendant(
2129            find::by_type::<AppBar>(),
2130            find::by_type::<crate::material::Material>(),
2131        )
2132        .first();
2133        let color = tester.widget(
2134            app_bar_background,
2135            |material: &crate::material::Material| material.color,
2136        );
2137        assert_eq!(color, Some(background));
2138
2139        let text_color = tester
2140            .widget(find::by_type::<TextField>(), |field: &TextField| {
2141                field.style.clone().map(|style| style.value().clone())
2142            })
2143            .expect("a style")
2144            .color
2145            .map(|color| color.color());
2146        let body_large_color = theme
2147            .text_theme
2148            .body_large
2149            .as_ref()
2150            .and_then(|style| style.color.clone())
2151            .map(|color| color.color());
2152        assert_eq!(text_color, body_large_color);
2153        assert_ne!(text_color, Some(background));
2154    }
2155
2156    // Regression test for https://github.com/flutter/flutter/issues/66781
2157    #[test]
2158    fn text_in_search_bar_contrasts_background_light_mode() {
2159        test_widgets(|tester| {
2160            let theme = ThemeData::builder()
2161                .use_material3(false)
2162                .build(&tester.cell.borrow());
2163            text_in_search_bar_contrasts_background(tester, theme, Colors::WHITE);
2164        });
2165    }
2166
2167    // Regression test for https://github.com/flutter/flutter/issues/66781
2168    #[test]
2169    fn text_in_search_bar_contrasts_background_dark_mode() {
2170        test_widgets(|tester| {
2171            let theme = ThemeData::dark(&tester.cell.borrow(), Some(false));
2172            let primary = theme.primary_color;
2173            text_in_search_bar_contrasts_background(tester, theme, primary);
2174        });
2175    }
2176
2177    // Regression test for https://github.com/flutter/flutter/issues/78144
2178    #[test]
2179    fn leading_actions_and_flexible_space_nullable_test() {
2180        test_widgets(|tester| {
2181            // The search delegate page is displayed with no issues even with `None` return
2182            // values for `build_leading`, `build_actions` and `build_flexible_space`.
2183            let delegate = EmptySearchDelegate::new(&mut tester.cell.borrow_mut());
2184            let results = Results::default();
2185            home_page_with(tester, delegate, &results, HomeOptions::default());
2186
2187            expect(tester, &find::text("HomeBody"), finds_one_widget());
2188            expect(tester, &find::text("HomeTitle"), finds_one_widget());
2189            expect(tester, &find::text("Suggestions"), finds_nothing());
2190
2191            open_search(tester);
2192            expect(tester, &find::text("HomeBody"), finds_nothing());
2193            expect(tester, &find::text("HomeTitle"), finds_nothing());
2194            expect(tester, &find::text("Suggestions"), finds_one_widget());
2195            assert!(results.borrow().is_empty());
2196            assert!(field_has_focus(tester));
2197
2198            tester.tap(find::by_tooltip("Close"));
2199            tester.pump_and_settle();
2200            expect(tester, &find::text("HomeBody"), finds_one_widget());
2201            expect(tester, &find::text("HomeTitle"), finds_one_widget());
2202            expect(tester, &find::text("Suggestions"), finds_nothing());
2203            assert_eq!(*results.borrow(), vec![Some("Result".to_owned())]);
2204        });
2205    }
2206
2207    #[test]
2208    fn show_search_with_use_root_navigator() {
2209        test_widgets(|tester| {
2210            let root_observer = observer(tester);
2211            let local_observer = observer(tester);
2212            let delegate = EmptySearchDelegate::new(&mut tester.cell.borrow_mut());
2213
2214            let button_delegate = Rc::clone(&delegate);
2215            let search_button = move |label: &'static str, use_root_navigator: bool| {
2216                let delegate = Rc::clone(&button_delegate);
2217                waft_widgets::Builder::new(move |_app, context| {
2218                    let delegate = Rc::clone(&delegate);
2219                    crate::text_button::TextButton::new(
2220                        Some(Listener::new(move |app: &mut App| {
2221                            drop(
2222                                ShowSearch::new(Rc::clone(&delegate) as Rc<dyn SearchDelegate>)
2223                                    .use_root_navigator(use_root_navigator)
2224                                    .show(app, context),
2225                            );
2226                        })),
2227                        Some(Text::new(label)),
2228                    )
2229                    .into_widget()
2230                })
2231                .into_widget()
2232            };
2233            let theme = m3(&tester.cell.borrow());
2234            let home = {
2235                let local = local_observer.erase::<waft_widgets::AnyNavigatorObserver>();
2236                waft_widgets::Navigator::new()
2237                    .observers([local])
2238                    .initial_route("nested")
2239                    .on_generate_route(move |app, settings| {
2240                        let name = settings.name.clone();
2241                        if name.as_deref() != Some("nested") {
2242                            panic!("only the nested route is generated");
2243                        }
2244                        let showers = (
2245                            search_button("showSearchRootNavigator", true),
2246                            search_button("showSearchLocalNavigator", false),
2247                        );
2248                        let route = crate::page::MaterialPageRoute::new(
2249                            app,
2250                            Rc::new(move |_app, _context| {
2251                                waft_widgets::Column::new()
2252                                    .main_axis_alignment(waft_rendering::MainAxisAlignment::Center)
2253                                    .children(vec![showers.0.clone(), showers.1.clone()])
2254                                    .into_widget()
2255                            }),
2256                        )
2257                        .settings(app, RouteSettingsRef::Settings(settings.clone()));
2258                        Some(route.erase())
2259                    })
2260            };
2261            tester.pump_widget(
2262                crate::app::MaterialApp::new()
2263                    .theme(theme)
2264                    .navigator_observers([
2265                        root_observer.erase::<waft_widgets::AnyNavigatorObserver>()
2266                    ])
2267                    .home(home)
2268                    .into_widget(),
2269            );
2270
2271            assert_eq!(push_count(tester, &root_observer), 0);
2272            assert_eq!(push_count(tester, &local_observer), 0);
2273
2274            // showSearch normal and back.
2275            tester.tap(find::text("showSearchLocalNavigator"));
2276            tester.pump_and_settle();
2277            expect(
2278                tester,
2279                &find::by_type::<crate::action_buttons::BackButton>(),
2280                finds_widgets(),
2281            );
2282            tester.tap(find::by_tooltip("Close"));
2283            tester.pump_and_settle();
2284            assert_eq!(push_count(tester, &root_observer), 0);
2285            assert_eq!(push_count(tester, &local_observer), 1);
2286
2287            // showSearch with rootNavigator.
2288            tester.tap(find::text("showSearchRootNavigator"));
2289            tester.pump_and_settle();
2290            tester.tap(find::by_tooltip("Close"));
2291            tester.pump_and_settle();
2292
2293            // showSearch without back button.
2294            delegate
2295                .search_delegate_data()
2296                .set_automatically_imply_leading(Some(false));
2297            tester.tap(find::text("showSearchRootNavigator"));
2298            tester.pump_and_settle();
2299            tester.widget(find::by_type::<AppBar>(), |app_bar: &AppBar| {
2300                assert!(!app_bar.automatically_imply_leading);
2301            });
2302            expect(tester, &find::by_tooltip("Back"), finds_nothing());
2303            tester.tap(find::by_tooltip("Close"));
2304            tester.pump_and_settle();
2305            assert_eq!(push_count(tester, &root_observer), 2);
2306            assert_eq!(push_count(tester, &local_observer), 1);
2307        });
2308    }
2309
2310    // Regression test for https://github.com/flutter/flutter/issues/95588
2311    #[test]
2312    fn query_text_field_shows_toolbar_initially() {
2313        test_widgets(|_| {
2314            let clipboard = MockClipboard::new();
2315            let mut tester = WidgetTester::with_platform(
2316                TestPlatform::new().with_clipboard(Rc::new(clipboard.clone())),
2317            );
2318            let tester = &mut tester;
2319            let delegate = TestSearchDelegate::new(&mut tester.cell.borrow_mut(), |d| d);
2320            home_page(tester, &delegate, &Results::default(), None);
2321            open_search(tester);
2322
2323            assert_eq!(delegate.query(&tester.cell.borrow()).len(), 0);
2324            clipboard.set_clipboard_data(Some("pasteablestring".to_owned()));
2325
2326            // Long press shows toolbar.
2327            tester.long_press(find::by_type::<TextField>());
2328            tester.pump();
2329            expect(tester, &find::text("Paste"), finds_one_widget());
2330
2331            tester.tap(find::text("Paste"));
2332            tester.pump();
2333            assert_eq!(delegate.query(&tester.cell.borrow()).len(), 15);
2334        });
2335    }
2336
2337    #[test]
2338    fn show_search_with_maintain_state_on_the_route() {
2339        test_widgets(|tester| {
2340            let navigation_observer = observer(tester);
2341            let delegate = EmptySearchDelegate::new(&mut tester.cell.borrow_mut());
2342            let search_button = |label: &'static str, maintain_state: bool| {
2343                let delegate = Rc::clone(&delegate);
2344                waft_widgets::Builder::new(move |_app, context| {
2345                    let delegate = Rc::clone(&delegate);
2346                    crate::text_button::TextButton::new(
2347                        Some(Listener::new(move |app: &mut App| {
2348                            drop(
2349                                ShowSearch::new(Rc::clone(&delegate) as Rc<dyn SearchDelegate>)
2350                                    .maintain_state(maintain_state)
2351                                    .show(app, context),
2352                            );
2353                        })),
2354                        Some(Text::new(label)),
2355                    )
2356                    .into_widget()
2357                })
2358                .into_widget()
2359            };
2360            let theme = m3(&tester.cell.borrow());
2361            tester.pump_widget(
2362                crate::app::MaterialApp::new()
2363                    .theme(theme)
2364                    .navigator_observers([
2365                        navigation_observer.erase::<waft_widgets::AnyNavigatorObserver>()
2366                    ])
2367                    .home(
2368                        waft_widgets::Column::new()
2369                            .main_axis_alignment(waft_rendering::MainAxisAlignment::Center)
2370                            .children(vec![
2371                                search_button("showSearch", false),
2372                                search_button("showSearchWithMaintainState", true),
2373                            ]),
2374                    )
2375                    .into_widget(),
2376            );
2377
2378            let maintain_state = |tester: &WidgetTester| {
2379                tester
2380                    .cell
2381                    .borrow()
2382                    .get(&navigation_observer)
2383                    .maintain_state
2384                    .get()
2385            };
2386            assert_eq!(push_count(tester, &navigation_observer), 0);
2387            assert!(!maintain_state(tester));
2388
2389            // showSearch normal and back.
2390            tester.tap(find::text("showSearch"));
2391            tester.pump_and_settle();
2392            expect(
2393                tester,
2394                &find::by_type::<crate::action_buttons::BackButton>(),
2395                finds_widgets(),
2396            );
2397            tester.tap(find::by_tooltip("Close"));
2398            tester.pump_and_settle();
2399            assert_eq!(push_count(tester, &navigation_observer), 1);
2400            assert!(!maintain_state(tester));
2401
2402            // showSearch with maintainState.
2403            tester.tap(find::text("showSearchWithMaintainState"));
2404            tester.pump_and_settle();
2405            expect(
2406                tester,
2407                &find::by_type::<crate::action_buttons::BackButton>(),
2408                finds_widgets(),
2409            );
2410            tester.tap(find::by_tooltip("Close"));
2411            tester.pump_and_settle();
2412            assert_eq!(push_count(tester, &navigation_observer), 2);
2413            assert!(maintain_state(tester));
2414        });
2415    }
2416}