Skip to main content

waft_widgets/widgets/
autocomplete.rs

1//! Flutter counterpart: `widgets/autocomplete.dart`.
2//!
3//! [`RawAutocompleteState`] keeps the options of the last [`RawAutocomplete::options_builder`]
4//! call and shows them through an [`OverlayPortal`] laid out against the field. The builder's
5//! result arrives in a continuation that runs at the next checkpoint, as Dart's `await` runs
6//! it in a microtask; a continuation whose call id is no longer the latest is dropped, so a
7//! slow older call never replaces the options of a newer one.
8
9use std::any::{Any, TypeId};
10use std::collections::HashMap;
11use std::fmt::{self, Debug, Display};
12use std::rc::Rc;
13
14use waft_embedder::{Offset, TargetPlatform, TextAffinity, TextSelection};
15use waft_foundation::{
16    App, Handle, ListenableObject, Listener, Ref, Task, ValueNotifier, VoidCallback,
17};
18use waft_painting::{AlignmentGeometry, transform_rect};
19use waft_rendering::BoxConstraints;
20use waft_services::{LogicalKeyboardKey, TextEditingValue};
21
22use crate::framework::{
23    BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
24    WidgetRef,
25};
26use crate::widgets::actions::{
27    Action, ActionData, ActionRef, Actions, CallbackAction, DismissIntent, Intent, IntentRef,
28    OnInvokeCallback,
29};
30use crate::widgets::basic::{Align, Builder, ConstrainedBox, SizedBox, Transform};
31use crate::widgets::constants::K_MIN_INTERACTIVE_DIMENSION;
32use crate::widgets::editable_text::{TextEditingController, TextEditingControllerRef};
33use crate::widgets::focus_manager::{FocusNode, FocusNodeLeaf, FocusNodeRef};
34use crate::widgets::focus_scope::ExcludeFocus;
35use crate::widgets::inherited_notifier::{InheritedNotifier, InheritedNotifierKind};
36use crate::widgets::media_query::MediaQuery;
37use crate::widgets::overlay::{OverlayChildLayoutInfo, OverlayPortal, OverlayPortalController};
38use crate::widgets::shortcuts::{ShortcutActivatorRef, ShortcutMap, Shortcuts, SingleActivator};
39use crate::widgets::tap_region::TextFieldTapRegion;
40
41/// The type of the [`RawAutocomplete`] callback which computes the list of optional
42/// completions for the widget's field, based on the text the user has entered so far.
43///
44/// Dart's `FutureOr<Iterable<T>>`: a builder that has its options at hand returns
45/// [`Task::ready`].
46///
47/// See also:
48///
49///   * [`RawAutocomplete::options_builder`], which is of this type.
50pub type AutocompleteOptionsBuilder<T> = Rc<dyn Fn(&mut App, TextEditingValue) -> Task<Vec<T>>>;
51
52/// The type of the callback used by the [`RawAutocomplete`] widget to indicate that the user
53/// has selected an option.
54///
55/// See also:
56///
57///   * [`RawAutocomplete::on_selected`], which is of this type.
58pub type AutocompleteOnSelected<T> = Rc<dyn Fn(&mut App, T)>;
59
60/// The type of the [`RawAutocomplete`] callback which returns a widget that displays the
61/// specified `options` and calls `on_selected` if the user selects an option.
62///
63/// The returned widget from this callback will be wrapped in an
64/// [`AutocompleteHighlightedOption`] inherited widget. This will allow this callback to
65/// determine which option is currently highlighted for keyboard navigation.
66///
67/// See also:
68///
69///   * [`RawAutocomplete::options_view_builder`], which is of this type.
70pub type AutocompleteOptionsViewBuilder<T> =
71    Rc<dyn Fn(&mut App, BuildContext, AutocompleteOnSelected<T>, &[T]) -> WidgetRef>;
72
73/// The type of the Autocomplete callback which returns the widget that contains the input
74/// `TextField` or `TextFormField`.
75///
76/// See also:
77///
78///   * [`RawAutocomplete::field_view_builder`], which is of this type.
79pub type AutocompleteFieldViewBuilder = Rc<
80    dyn Fn(
81        &mut App,
82        BuildContext,
83        TextEditingControllerRef,
84        FocusNodeRef,
85        VoidCallback,
86    ) -> WidgetRef,
87>;
88
89/// The type of the [`RawAutocomplete`] callback that converts an option value to a string
90/// which can be displayed in the widget's options menu.
91///
92/// See also:
93///
94///   * [`RawAutocomplete::display_string_for_option`], which is of this type.
95pub type AutocompleteOptionToString<T> = Rc<dyn Fn(&T) -> String>;
96
97/// A direction in which to open the options-view overlay.
98///
99/// See also:
100///
101///  * [`RawAutocomplete::options_view_open_direction`], which is of this type.
102///  * [`RawAutocomplete::options_view_builder`] to specify how to build the selectable-options
103///    widget.
104///  * [`RawAutocomplete::field_view_builder`] to optionally specify how to build the
105///    corresponding field widget.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107pub enum OptionsViewOpenDirection {
108    /// Open upward.
109    ///
110    /// The bottom edge of the options view will align with the top edge of the text field
111    /// built by [`RawAutocomplete::field_view_builder`].
112    Up,
113
114    /// Open downward.
115    ///
116    /// The top edge of the options view will align with the bottom edge of the text field
117    /// built by [`RawAutocomplete::field_view_builder`].
118    Down,
119
120    /// Open in the direction with the most available space within the overlay.
121    ///
122    /// The available space is calculated as the distance from the field's top edge to the
123    /// overlay's top edge (for upward opening) or from the field's bottom edge to the
124    /// overlay's bottom edge (for downward opening).
125    ///
126    /// If both directions have the same available space, the options view opens downward.
127    MostSpace,
128}
129
130/// A widget for helping the user make a selection by entering some text and choosing from
131/// among a list of options.
132///
133/// The user's text input is received in a field built with the
134/// [`field_view_builder`](Self::field_view_builder) parameter. The options to be displayed are
135/// determined using [`options_builder`](Self::options_builder) and rendered with
136/// [`options_view_builder`](Self::options_view_builder).
137///
138/// The options view opens when the field gains focus or when the field's text changes, as
139/// long as [`options_builder`](Self::options_builder) returns at least one option. The options
140/// view closes when the user selects an option, when there are no matching options, or when
141/// the field loses focus.
142///
143/// This is a core framework widget with very basic UI.
144///
145/// The type parameter `T` represents the type of the options. Most commonly this is a
146/// `String`. However, it's also possible to use another type with a `Display` form, or a
147/// custom [`display_string_for_option`](Self::display_string_for_option). Options will be
148/// compared using `==`.
149///
150/// See also:
151///
152///  * `Autocomplete`, which is a Material-styled implementation that is based on
153///    RawAutocomplete.
154pub struct RawAutocomplete<T: Clone + PartialEq + 'static> {
155    /// See [`StatefulWidget::key`].
156    pub key: Option<KeyRef>,
157
158    /// Builds the field whose input is used to get the options.
159    ///
160    /// Pass the provided [`TextEditingControllerRef`] to the field built here so that
161    /// RawAutocomplete can listen for changes.
162    ///
163    /// If this parameter is `None`, then a [`SizedBox::shrink`] is built instead. For how that
164    /// pattern can be useful, see [`text_editing_controller`](Self::text_editing_controller).
165    pub field_view_builder: Option<AutocompleteFieldViewBuilder>,
166
167    /// The [`FocusNode`] that is used for the text field.
168    ///
169    /// The main purpose of this parameter is to allow the use of a separate text field
170    /// located in another part of the widget tree instead of the text field built by
171    /// [`field_view_builder`](Self::field_view_builder). For example, it may be desirable to
172    /// place the text field in the AppBar and the options below in the main body.
173    ///
174    /// When following this pattern, [`field_view_builder`](Self::field_view_builder) can be
175    /// omitted, so that a text field is not drawn where it would normally be. A separate text
176    /// field can be created elsewhere, and a FocusNode and TextEditingController can be passed
177    /// both to that text field and to RawAutocomplete.
178    ///
179    /// If this parameter is not `None`, then
180    /// [`text_editing_controller`](Self::text_editing_controller) must also be set.
181    pub focus_node: Option<FocusNodeRef>,
182
183    /// Builds the selectable options widgets from a list of options objects.
184    ///
185    /// The options are displayed floating below or above the field inside of an `Overlay`,
186    /// not at the same place in the widget tree as [`RawAutocomplete`]. To control whether it
187    /// opens upward or downward, use
188    /// [`options_view_open_direction`](Self::options_view_open_direction).
189    ///
190    /// In order to track which item is highlighted by keyboard navigation, the resulting
191    /// options will be wrapped in an inherited [`AutocompleteHighlightedOption`] widget.
192    /// Inside this callback, the index of the highlighted option can be obtained from
193    /// [`AutocompleteHighlightedOption::of`] to display the highlighted option with a visual
194    /// highlight to indicate it will be the option selected from the keyboard.
195    pub options_view_builder: AutocompleteOptionsViewBuilder<T>,
196
197    /// Determines the direction in which to open the options view.
198    ///
199    /// Defaults to [`OptionsViewOpenDirection::Down`].
200    pub options_view_open_direction: OptionsViewOpenDirection,
201
202    /// Returns the string to display in the field when the option is selected.
203    ///
204    /// This is useful when using a custom T type and the string to display is different
205    /// than the string to search by.
206    ///
207    /// If not provided, will use the option's `Display` form.
208    pub display_string_for_option: AutocompleteOptionToString<T>,
209
210    /// Called when an option is selected by the user.
211    pub on_selected: Option<AutocompleteOnSelected<T>>,
212
213    /// A function that returns the current selectable options objects given the current
214    /// TextEditingValue.
215    pub options_builder: AutocompleteOptionsBuilder<T>,
216
217    /// The [`TextEditingController`] that is used for the text field.
218    ///
219    /// See [`focus_node`](Self::focus_node) for the split field pattern.
220    ///
221    /// If this parameter is not `None`, then [`focus_node`](Self::focus_node) must also be
222    /// set.
223    pub text_editing_controller: Option<TextEditingControllerRef>,
224
225    /// The initial value to use for the text field.
226    ///
227    /// Setting the initial value does not notify
228    /// [`text_editing_controller`](Self::text_editing_controller)'s listeners, and thus will
229    /// not cause the options UI to appear.
230    ///
231    /// This parameter is ignored if [`text_editing_controller`](Self::text_editing_controller)
232    /// is defined.
233    pub initial_value: Option<TextEditingValue>,
234}
235
236impl<T: Clone + PartialEq + Display + 'static> RawAutocomplete<T> {
237    /// Create an instance of RawAutocomplete.
238    ///
239    /// [`display_string_for_option`](Self::display_string_for_option) defaults to
240    /// [`default_string_for_option`](Self::default_string_for_option), which needs `T`'s
241    /// `Display` form; an option type without one is built with
242    /// [`new_with_display_string`](Self::new_with_display_string).
243    pub fn new(
244        options_view_builder: impl Fn(
245            &mut App,
246            BuildContext,
247            AutocompleteOnSelected<T>,
248            &[T],
249        ) -> WidgetRef
250        + 'static,
251        options_builder: impl Fn(&mut App, TextEditingValue) -> Task<Vec<T>> + 'static,
252    ) -> RawAutocomplete<T> {
253        RawAutocomplete::new_with_display_string(
254            options_view_builder,
255            options_builder,
256            |option: &T| RawAutocomplete::<T>::default_string_for_option(option),
257        )
258    }
259
260    /// The default way to convert an option to a string in
261    /// [`display_string_for_option`](Self::display_string_for_option).
262    ///
263    /// Uses the `Display` form of the given `option`.
264    pub fn default_string_for_option(option: &dyn Display) -> String {
265        option.to_string()
266    }
267}
268
269impl<T: Clone + PartialEq + 'static> RawAutocomplete<T> {
270    /// Create an instance of RawAutocomplete whose options are shown as
271    /// `display_string_for_option` gives them, for an option type with or without a `Display`
272    /// form.
273    pub fn new_with_display_string(
274        options_view_builder: impl Fn(
275            &mut App,
276            BuildContext,
277            AutocompleteOnSelected<T>,
278            &[T],
279        ) -> WidgetRef
280        + 'static,
281        options_builder: impl Fn(&mut App, TextEditingValue) -> Task<Vec<T>> + 'static,
282        display_string_for_option: impl Fn(&T) -> String + 'static,
283    ) -> RawAutocomplete<T> {
284        RawAutocomplete {
285            key: None,
286            field_view_builder: None,
287            focus_node: None,
288            options_view_builder: Rc::new(options_view_builder),
289            options_view_open_direction: OptionsViewOpenDirection::Down,
290            display_string_for_option: Rc::new(display_string_for_option),
291            on_selected: None,
292            options_builder: Rc::new(options_builder),
293            text_editing_controller: None,
294            initial_value: None,
295        }
296    }
297}
298
299impl<T: Clone + PartialEq + 'static> RawAutocomplete<T> {
300    /// Dart `RawAutocomplete(key:)`.
301    pub fn key(mut self, key: KeyRef) -> RawAutocomplete<T> {
302        self.key = Some(key);
303        self
304    }
305
306    /// Dart `RawAutocomplete(optionsViewOpenDirection:)`.
307    pub fn options_view_open_direction(
308        mut self,
309        options_view_open_direction: OptionsViewOpenDirection,
310    ) -> RawAutocomplete<T> {
311        self.options_view_open_direction = options_view_open_direction;
312        self
313    }
314
315    /// Dart `RawAutocomplete(displayStringForOption:)`.
316    pub fn display_string_for_option(
317        mut self,
318        display_string_for_option: impl Fn(&T) -> String + 'static,
319    ) -> RawAutocomplete<T> {
320        self.display_string_for_option = Rc::new(display_string_for_option);
321        self
322    }
323
324    /// Dart `RawAutocomplete(fieldViewBuilder:)`.
325    pub fn field_view_builder(
326        mut self,
327        field_view_builder: impl Fn(
328            &mut App,
329            BuildContext,
330            TextEditingControllerRef,
331            FocusNodeRef,
332            VoidCallback,
333        ) -> WidgetRef
334        + 'static,
335    ) -> RawAutocomplete<T> {
336        self.field_view_builder = Some(Rc::new(field_view_builder));
337        self
338    }
339
340    /// Dart `RawAutocomplete(focusNode:)`.
341    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> RawAutocomplete<T> {
342        self.focus_node = Some(focus_node);
343        self
344    }
345
346    /// Dart `RawAutocomplete(onSelected:)`.
347    pub fn on_selected(
348        mut self,
349        on_selected: impl Fn(&mut App, T) + 'static,
350    ) -> RawAutocomplete<T> {
351        self.on_selected = Some(Rc::new(on_selected));
352        self
353    }
354
355    /// Dart `RawAutocomplete(textEditingController:)`.
356    pub fn text_editing_controller(
357        mut self,
358        text_editing_controller: TextEditingControllerRef,
359    ) -> RawAutocomplete<T> {
360        self.text_editing_controller = Some(text_editing_controller);
361        self
362    }
363
364    /// Dart `RawAutocomplete(initialValue:)`.
365    pub fn initial_value(mut self, initial_value: TextEditingValue) -> RawAutocomplete<T> {
366        self.initial_value = Some(initial_value);
367        self
368    }
369
370    /// Calls [`AutocompleteFieldViewBuilder`]'s `on_field_submitted` callback for the
371    /// RawAutocomplete widget indicated by the given [`GlobalKey`].
372    ///
373    /// This is not typically used unless a custom field is implemented instead of using
374    /// [`field_view_builder`](Self::field_view_builder). In the typical case, the
375    /// `on_field_submitted` callback is passed via the [`AutocompleteFieldViewBuilder`]
376    /// signature. When not using `field_view_builder`, the same callback can be called by
377    /// using this associated function.
378    ///
379    /// See also:
380    ///
381    ///  * [`focus_node`](Self::focus_node) and
382    ///    [`text_editing_controller`](Self::text_editing_controller), which describe how to
383    ///    create a separate field outside of `field_view_builder`.
384    pub fn on_field_submitted(app: &mut App, key: &GlobalKey) {
385        let raw_autocomplete = key
386            .current_state::<RawAutocompleteState<T>>(app)
387            .expect("the key's widget is a mounted RawAutocomplete of this option type");
388        raw_autocomplete.on_field_submitted(app);
389    }
390}
391
392impl<T: Clone + PartialEq + 'static> Debug for RawAutocomplete<T> {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        f.debug_struct("RawAutocomplete")
395            .field(
396                "options_view_open_direction",
397                &self.options_view_open_direction,
398            )
399            .field("focus_node", &self.focus_node)
400            .field("text_editing_controller", &self.text_editing_controller)
401            .field("initial_value", &self.initial_value)
402            .finish_non_exhaustive()
403    }
404}
405
406impl<T: Clone + PartialEq + 'static> StatefulWidget for RawAutocomplete<T> {
407    type State = RawAutocompleteState<T>;
408
409    fn key(&self) -> Option<&KeyRef> {
410        self.key.as_ref()
411    }
412
413    fn debug_check_constructor(&self) {
414        debug_assert!(
415            self.field_view_builder.is_some()
416                || (self.key.is_some()
417                    && self.focus_node.is_some()
418                    && self.text_editing_controller.is_some()),
419            "Pass in a fieldViewBuilder, or otherwise create a separate field and pass in the \
420             FocusNode, TextEditingController, and a key. Use the key with \
421             RawAutocomplete.onFieldSubmitted."
422        );
423        debug_assert!(self.focus_node.is_none() == self.text_editing_controller.is_none());
424        debug_assert!(
425            !(self.text_editing_controller.is_some() && self.initial_value.is_some()),
426            "textEditingController and initialValue cannot be simultaneously defined."
427        );
428    }
429
430    fn create_state(&self) -> RawAutocompleteState<T> {
431        RawAutocompleteState {
432            state: StateData::new(),
433            options_view_controller: None,
434            has_focus: false,
435            selecting: false,
436            internal_text_editing_controller: None,
437            internal_focus_node: None,
438            action_map: None,
439            options: Vec::new(),
440            selection: None,
441            last_field_text: None,
442            highlighted_option_index: None,
443            on_changed_call_id: 0,
444        }
445    }
446}
447
448/// Dart's `_RawAutocompleteState`; public because [`RawAutocomplete`]'s
449/// `StatefulWidget::State` names it.
450pub struct RawAutocompleteState<T: Clone + PartialEq + 'static> {
451    state: StateData<RawAutocomplete<T>>,
452    options_view_controller: Option<Ref<OverlayPortalController>>,
453
454    /// Whether the field currently has focus.
455    ///
456    /// This is used to determine whether the focus state has changed.
457    has_focus: bool,
458
459    /// Whether an option is currently being selected.
460    selecting: bool,
461
462    internal_text_editing_controller: Option<Ref<TextEditingController>>,
463    internal_focus_node: Option<Ref<FocusNode>>,
464    action_map: Option<HashMap<TypeId, ActionRef>>,
465    options: Vec<T>,
466    selection: Option<T>,
467    // Set the initial value to None so when this widget gets focused for the first time it
468    // will try to run the options view builder.
469    last_field_text: Option<String>,
470    highlighted_option_index: Option<Ref<ValueNotifier<usize>>>,
471    // Assigning an ID to every call of on_changed_field is necessary to avoid a situation
472    // where options is updated by an older call when multiple on_changed_field calls are
473    // running simultaneously.
474    on_changed_call_id: u64,
475}
476
477impl<T: Clone + PartialEq + 'static> RawAutocompleteState<T> {
478    // The number of options to scroll by "page", such as when using the page up/down keys.
479    const PAGE_SIZE: i64 = 4;
480
481    // A big enough height for about one item in the default Autocomplete.optionsViewBuilder.
482    // The assumption is that the user likely wants the list of options to move to stay on the
483    // screen rather than get any smaller than this. Allows Autocomplete to work when it has
484    // very little screen height available (as in b/317115348) by positioning itself on top of
485    // the field, while in other cases to size itself based on the height under the field.
486    const MIN_USABLE_HEIGHT: f64 = K_MIN_INTERACTIVE_DIMENSION;
487
488    fn options_view_controller(self: Handle<Self>, app: &App) -> Handle<OverlayPortalController> {
489        app.get(self)
490            .options_view_controller
491            .as_ref()
492            .expect("made in init_state")
493            .handle()
494    }
495
496    fn highlighted_option_index(self: Handle<Self>, app: &App) -> Handle<ValueNotifier<usize>> {
497        app.get(self)
498            .highlighted_option_index
499            .as_ref()
500            .expect("made in init_state")
501            .handle()
502    }
503
504    fn text_editing_controller(self: Handle<Self>, app: &mut App) -> TextEditingControllerRef {
505        if let Some(controller) = &self.widget(app).text_editing_controller {
506            return controller.clone();
507        }
508        if app.get(self).internal_text_editing_controller.is_none() {
509            let controller = TextEditingController::new(app);
510            ListenableObject::add_listener(
511                controller.handle(),
512                app,
513                Listener::handle_method(self, Self::on_changed_field),
514            );
515            app.get_mut(self).internal_text_editing_controller = Some(controller);
516        }
517        app.get(self)
518            .internal_text_editing_controller
519            .as_ref()
520            .expect("made above")
521            .erase()
522    }
523
524    fn focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
525        if let Some(focus_node) = &self.widget(app).focus_node {
526            return focus_node.clone();
527        }
528        if app.get(self).internal_focus_node.is_none() {
529            let focus_node = FocusNode::new(app);
530            let erased: FocusNodeRef = focus_node.erase();
531            erased
532                .handle()
533                .add_listener(app, Listener::handle_method(self, Self::on_focus_change));
534            app.get_mut(self).internal_focus_node = Some(focus_node);
535        }
536        app.get(self)
537            .internal_focus_node
538            .as_ref()
539            .expect("made above")
540            .erase()
541    }
542
543    /// Dart's `late final Map<Type, CallbackAction<Intent>> _actionMap`, made on first read.
544    fn action_map(self: Handle<Self>, app: &mut App) -> HashMap<TypeId, ActionRef> {
545        if app.get(self).action_map.is_none() {
546            let action_map = self.make_action_map(app);
547            app.get_mut(self).action_map = Some(action_map);
548        }
549        app.get(self).action_map.clone().expect("made above")
550    }
551
552    fn make_action_map(self: Handle<Self>, app: &mut App) -> HashMap<TypeId, ActionRef> {
553        let is_enabled_callback: Rc<dyn Fn(&mut App) -> bool> =
554            Rc::new(move |app: &mut App| self.can_show_options_view(app));
555        let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
556        actions.insert(
557            TypeId::of::<AutocompletePreviousOptionIntent>(),
558            AutocompleteCallbackAction::<AutocompletePreviousOptionIntent>::new(
559                app,
560                Rc::new(
561                    move |app: &mut App, intent: &AutocompletePreviousOptionIntent| {
562                        self.highlight_previous_option(app, intent);
563                        None
564                    },
565                ),
566                Rc::clone(&is_enabled_callback),
567            )
568            .into_erased(),
569        );
570        actions.insert(
571            TypeId::of::<AutocompleteNextOptionIntent>(),
572            AutocompleteCallbackAction::<AutocompleteNextOptionIntent>::new(
573                app,
574                Rc::new(
575                    move |app: &mut App, intent: &AutocompleteNextOptionIntent| {
576                        self.highlight_next_option(app, intent);
577                        None
578                    },
579                ),
580                Rc::clone(&is_enabled_callback),
581            )
582            .into_erased(),
583        );
584        actions.insert(
585            TypeId::of::<AutocompleteFirstOptionIntent>(),
586            AutocompleteCallbackAction::<AutocompleteFirstOptionIntent>::new(
587                app,
588                Rc::new(
589                    move |app: &mut App, intent: &AutocompleteFirstOptionIntent| {
590                        self.highlight_first_option(app, intent);
591                        None
592                    },
593                ),
594                Rc::clone(&is_enabled_callback),
595            )
596            .into_erased(),
597        );
598        actions.insert(
599            TypeId::of::<AutocompleteLastOptionIntent>(),
600            AutocompleteCallbackAction::<AutocompleteLastOptionIntent>::new(
601                app,
602                Rc::new(
603                    move |app: &mut App, intent: &AutocompleteLastOptionIntent| {
604                        self.highlight_last_option(app, intent);
605                        None
606                    },
607                ),
608                Rc::clone(&is_enabled_callback),
609            )
610            .into_erased(),
611        );
612        actions.insert(
613            TypeId::of::<AutocompleteNextPageOptionIntent>(),
614            AutocompleteCallbackAction::<AutocompleteNextPageOptionIntent>::new(
615                app,
616                Rc::new(
617                    move |app: &mut App, intent: &AutocompleteNextPageOptionIntent| {
618                        self.highlight_next_page_option(app, intent);
619                        None
620                    },
621                ),
622                Rc::clone(&is_enabled_callback),
623            )
624            .into_erased(),
625        );
626        actions.insert(
627            TypeId::of::<AutocompletePreviousPageOptionIntent>(),
628            AutocompleteCallbackAction::<AutocompletePreviousPageOptionIntent>::new(
629                app,
630                Rc::new(
631                    move |app: &mut App, intent: &AutocompletePreviousPageOptionIntent| {
632                        self.highlight_previous_page_option(app, intent);
633                        None
634                    },
635                ),
636                is_enabled_callback,
637            )
638            .into_erased(),
639        );
640        actions.insert(
641            TypeId::of::<DismissIntent>(),
642            CallbackAction::<DismissIntent>::new(
643                app,
644                Rc::new(move |app: &mut App, intent: &DismissIntent| {
645                    self.hide_options(app, intent)
646                }),
647            )
648            .into_erased(),
649        );
650        actions
651    }
652
653    /// Dart's `_appleShortcuts`.
654    fn apple_shortcuts() -> ShortcutMap {
655        vec![
656            shortcut(
657                SingleActivator::new(LogicalKeyboardKey::ARROW_UP).meta(true),
658                AutocompleteFirstOptionIntent::new(),
659            ),
660            shortcut(
661                SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN).meta(true),
662                AutocompleteLastOptionIntent::new(),
663            ),
664        ]
665    }
666
667    /// Dart's `_nonAppleShortcuts`.
668    fn non_apple_shortcuts() -> ShortcutMap {
669        vec![
670            shortcut(
671                SingleActivator::new(LogicalKeyboardKey::ARROW_UP).control(true),
672                AutocompleteFirstOptionIntent::new(),
673            ),
674            shortcut(
675                SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN).control(true),
676                AutocompleteLastOptionIntent::new(),
677            ),
678        ]
679    }
680
681    /// Dart's `_commonShortcuts`.
682    fn common_shortcuts() -> ShortcutMap {
683        vec![
684            shortcut(
685                SingleActivator::new(LogicalKeyboardKey::ARROW_UP),
686                AutocompletePreviousOptionIntent::new(),
687            ),
688            shortcut(
689                SingleActivator::new(LogicalKeyboardKey::ARROW_DOWN),
690                AutocompleteNextOptionIntent::new(),
691            ),
692            shortcut(
693                SingleActivator::new(LogicalKeyboardKey::PAGE_UP),
694                AutocompletePreviousPageOptionIntent::new(),
695            ),
696            shortcut(
697                SingleActivator::new(LogicalKeyboardKey::PAGE_DOWN),
698                AutocompleteNextPageOptionIntent::new(),
699            ),
700        ]
701    }
702
703    /// Dart's `_shortcuts`.
704    fn shortcuts(app: &App) -> ShortcutMap {
705        let mut shortcuts = Self::common_shortcuts();
706        shortcuts.extend(match app.platform().target_platform() {
707            TargetPlatform::IOS => Self::apple_shortcuts(),
708            TargetPlatform::MacOS => Self::apple_shortcuts(),
709            TargetPlatform::Android => Self::non_apple_shortcuts(),
710            TargetPlatform::Linux => Self::non_apple_shortcuts(),
711            TargetPlatform::Windows => Self::non_apple_shortcuts(),
712            TargetPlatform::Fuchsia => Self::non_apple_shortcuts(),
713        });
714        shortcuts
715    }
716
717    /// The options view is considered eligible to show only while the field has focus and
718    /// there is at least one option to display.
719    fn can_show_options_view(self: Handle<Self>, app: &mut App) -> bool {
720        self.focus_node(app).handle().has_focus(app) && !app.get(self).options.is_empty()
721    }
722
723    fn on_focus_change(self: Handle<Self>, app: &mut App) {
724        let has_focus = self.focus_node(app).handle().has_focus(app);
725        if has_focus != app.get(self).has_focus {
726            app.get_mut(self).has_focus = has_focus;
727            // Gaining focus can open the options view (if there are options). Losing focus
728            // always closes it.
729            self.update_options_view_visibility(app);
730        }
731    }
732
733    /// Shows the options view when the field is focused and there is at least one option to
734    /// display; otherwise hides the options view.
735    fn update_options_view_visibility(self: Handle<Self>, app: &mut App) {
736        if self.can_show_options_view(app) {
737            self.options_view_controller(app).show(app);
738        } else if self.options_view_controller(app).is_showing(app) {
739            self.options_view_controller(app).hide(app);
740        }
741    }
742
743    // Called when text_editing_controller changes. Dart's `Future<void>` is only ever dropped
744    // by the listener list, so the continuation's task is dropped here.
745    fn on_changed_field(self: Handle<Self>, app: &mut App) {
746        // During a selection, changes to the field text should not trigger options update.
747        if app.get(self).selecting {
748            return;
749        }
750        let value = self.text_editing_controller(app).value(app).clone();
751
752        // Makes sure that options change only when content of the field changes.
753        let mut should_update_options = false;
754        if app.get(self).last_field_text.as_deref() != Some(value.text.as_str()) {
755            should_update_options = true;
756            app.get_mut(self).on_changed_call_id += 1;
757        }
758        app.get_mut(self).last_field_text = Some(value.text.clone());
759        let call_id = app.get(self).on_changed_call_id;
760        let options_builder = Rc::clone(&self.widget(app).options_builder);
761        let options = options_builder(app, value.clone());
762
763        drop(app.spawn(async move |cx| {
764            let options = options.await;
765            cx.update(|app| {
766                if !self.mounted(app) {
767                    return;
768                }
769
770                // Makes sure that previous call results do not replace new ones.
771                if call_id != app.get(self).on_changed_call_id || !should_update_options {
772                    return;
773                }
774                app.get_mut(self).options = options;
775                let highlighted = *self.highlighted_option_index(app).value(app) as i64;
776                self.update_highlight(app, highlighted);
777                if let Some(selection) = app.get(self).selection.clone()
778                    && value.text != (self.widget(app).display_string_for_option)(&selection)
779                {
780                    app.get_mut(self).selection = None;
781                }
782
783                self.update_options_view_visibility(app);
784            });
785        }));
786    }
787
788    // Called from field_view_builder when the user submits the field.
789    fn on_field_submitted(self: Handle<Self>, app: &mut App) {
790        if self.options_view_controller(app).is_showing(app) {
791            let index = *self.highlighted_option_index(app).value(app);
792            let option = app.get(self).options[index].clone();
793            self.select(app, option);
794        }
795    }
796
797    // Select the given option and update the widget.
798    fn select(self: Handle<Self>, app: &mut App, next_selection: T) {
799        if Some(&next_selection) == app.get(self).selection.as_ref() {
800            return;
801        }
802        app.get_mut(self).selecting = true;
803        app.get_mut(self).selection = Some(next_selection.clone());
804        let selection_string = (self.widget(app).display_string_for_option)(&next_selection);
805        let selection_length = selection_string.encode_utf16().count() as i32;
806        self.text_editing_controller(app).handle().set_value(
807            app,
808            TextEditingValue::new()
809                .selection(TextSelection::collapsed(
810                    selection_length,
811                    TextAffinity::Downstream,
812                ))
813                .text(selection_string.clone()),
814        );
815        app.get_mut(self).last_field_text = Some(selection_string);
816        if let Some(on_selected) = self.widget(app).on_selected.clone() {
817            on_selected(app, next_selection);
818        }
819        if self.options_view_controller(app).is_showing(app) {
820            // Close the options view after a selection is made.
821            self.options_view_controller(app).hide(app);
822        }
823        app.get_mut(self).selecting = false;
824    }
825
826    fn update_highlight(self: Handle<Self>, app: &mut App, next_index: i64) {
827        let length = app.get(self).options.len();
828        let index = if length == 0 {
829            0
830        } else {
831            next_index.clamp(0, length as i64 - 1) as usize
832        };
833        self.highlighted_option_index(app).set_value(app, index);
834    }
835
836    fn highlight_previous_option(
837        self: Handle<Self>,
838        app: &mut App,
839        _intent: &AutocompletePreviousOptionIntent,
840    ) {
841        let index = *self.highlighted_option_index(app).value(app) as i64;
842        self.highlight_option(app, index - 1);
843    }
844
845    fn highlight_next_option(
846        self: Handle<Self>,
847        app: &mut App,
848        _intent: &AutocompleteNextOptionIntent,
849    ) {
850        let index = *self.highlighted_option_index(app).value(app) as i64;
851        self.highlight_option(app, index + 1);
852    }
853
854    fn highlight_first_option(
855        self: Handle<Self>,
856        app: &mut App,
857        _intent: &AutocompleteFirstOptionIntent,
858    ) {
859        self.highlight_option(app, 0);
860    }
861
862    fn highlight_last_option(
863        self: Handle<Self>,
864        app: &mut App,
865        _intent: &AutocompleteLastOptionIntent,
866    ) {
867        let length = app.get(self).options.len() as i64;
868        self.highlight_option(app, length - 1);
869    }
870
871    fn highlight_next_page_option(
872        self: Handle<Self>,
873        app: &mut App,
874        _intent: &AutocompleteNextPageOptionIntent,
875    ) {
876        let index = *self.highlighted_option_index(app).value(app) as i64;
877        self.highlight_option(app, index + Self::PAGE_SIZE);
878    }
879
880    fn highlight_previous_page_option(
881        self: Handle<Self>,
882        app: &mut App,
883        _intent: &AutocompletePreviousPageOptionIntent,
884    ) {
885        let index = *self.highlighted_option_index(app).value(app) as i64;
886        self.highlight_option(app, index - Self::PAGE_SIZE);
887    }
888
889    fn highlight_option(self: Handle<Self>, app: &mut App, index: i64) {
890        debug_assert!(self.can_show_options_view(app));
891        self.update_options_view_visibility(app);
892        debug_assert!(self.options_view_controller(app).is_showing(app));
893        self.update_highlight(app, index);
894    }
895
896    fn hide_options(
897        self: Handle<Self>,
898        app: &mut App,
899        intent: &DismissIntent,
900    ) -> Option<Rc<dyn Any>> {
901        if self.options_view_controller(app).is_showing(app) {
902            self.options_view_controller(app).hide(app);
903            None
904        } else {
905            let context = self.context(app);
906            Actions::invoke(app, context, intent)
907        }
908    }
909
910    fn build_options_view(
911        self: Handle<Self>,
912        app: &mut App,
913        context: BuildContext,
914        layout_info: OverlayChildLayoutInfo,
915    ) -> WidgetRef {
916        if layout_info.child_paint_transform().determinant() == 0.0 {
917            // The child is not visible.
918            return SizedBox::shrink().into_widget();
919        }
920        let field_size = layout_info.child_size();
921        // Dart's `invert()` leaves a matrix it cannot invert as it is.
922        let invert_transform = layout_info
923            .child_paint_transform()
924            .invert()
925            .unwrap_or(layout_info.child_paint_transform());
926
927        let media_query_padding = MediaQuery::padding_of(app, context);
928        let view_insets = MediaQuery::view_insets_of(app, context);
929
930        let overlay_rect = media_query_padding
931            .deflate_rect(view_insets.deflate_rect(Offset::ZERO & layout_info.overlay_size()));
932
933        // This may not work well if the paint transform has rotation in it.
934        // transform_rect returns the bounding rect of the rotated overlay rect.
935        let overlay_rect_in_field = transform_rect(&invert_transform, overlay_rect);
936
937        let space_above = -overlay_rect_in_field.top;
938        let space_below = overlay_rect_in_field.bottom - field_size.height();
939        let opens_up = match self.widget(app).options_view_open_direction {
940            OptionsViewOpenDirection::Up => true,
941            OptionsViewOpenDirection::Down => false,
942            OptionsViewOpenDirection::MostSpace => space_above > space_below,
943        };
944
945        let options_view_max_height = if opens_up {
946            -overlay_rect_in_field.top
947        } else {
948            overlay_rect_in_field.bottom - field_size.height()
949        };
950
951        let options_view_bounding_box = waft_embedder::Size::new(
952            field_size.width(),
953            options_view_max_height.max(Self::MIN_USABLE_HEIGHT),
954        );
955
956        let origin_y = if opens_up {
957            overlay_rect_in_field.top
958        } else {
959            overlay_rect_in_field.bottom - options_view_bounding_box.height()
960        };
961
962        let transform = layout_info
963            .child_paint_transform()
964            .then(&waft_embedder::Matrix4::translation(0.0, origin_y as f32));
965        let child = Builder::new(move |app, context| {
966            let options_view_builder = Rc::clone(&self.widget(app).options_view_builder);
967            let options = app.get(self).options.clone();
968            let on_selected: AutocompleteOnSelected<T> =
969                Rc::new(move |app: &mut App, option: T| self.select(app, option));
970            options_view_builder(app, context, on_selected, &options)
971        });
972        let highlighted_option_index = app
973            .get(self)
974            .highlighted_option_index
975            .clone()
976            .expect("made in init_state");
977        Transform::new(transform)
978            .child(
979                Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
980                    ConstrainedBox::new(BoxConstraints::tight(options_view_bounding_box)).child(
981                        Align::new()
982                            .alignment(if opens_up {
983                                AlignmentGeometry::BOTTOM_START
984                            } else {
985                                AlignmentGeometry::TOP_START
986                            })
987                            .child(TextFieldTapRegion::new(
988                                AutocompleteHighlightedOption::new(
989                                    highlighted_option_index,
990                                    // Exclude the options overlay from the ambient focus
991                                    // traversal tree. Autocomplete options are navigated by
992                                    // arrow keys (via the widget's own shortcuts) and selected
993                                    // via Enter or tap, so they don't participate in TAB
994                                    // traversal. Without this, TAB from the field would detour
995                                    // into focusable items in the options overlay instead of
996                                    // advancing to the next form field.
997                                    ExcludeFocus::new(child),
998                                )
999                                .into_widget(),
1000                            )),
1001                    ),
1002                ),
1003            )
1004            .into_widget()
1005    }
1006}
1007
1008impl<T: Clone + PartialEq + 'static> State for RawAutocompleteState<T> {
1009    type Widget = RawAutocomplete<T>;
1010    crate::state_accessors!();
1011
1012    fn init_state(self: Handle<Self>, app: &mut App) {
1013        app.get_mut(self).options_view_controller = Some(OverlayPortalController::new(
1014            app,
1015            Some("_RawAutocompleteState".to_string()),
1016        ));
1017        app.get_mut(self).highlighted_option_index = Some(app.create(ValueNotifier::new(0)));
1018        let initial_controller = match self.widget(app).text_editing_controller.clone() {
1019            Some(controller) => controller,
1020            None => {
1021                let initial_value = self.widget(app).initial_value.clone();
1022                let controller = TextEditingController::from_value(app, initial_value);
1023                let erased = controller.erase();
1024                app.get_mut(self).internal_text_editing_controller = Some(controller);
1025                erased
1026            }
1027        };
1028        initial_controller
1029            .handle()
1030            .add_listener(app, Listener::handle_method(self, Self::on_changed_field));
1031        let has_focus = self.focus_node(app).handle().has_focus(app);
1032        app.get_mut(self).has_focus = has_focus;
1033        if let Some(focus_node) = self.widget(app).focus_node.clone() {
1034            focus_node
1035                .handle()
1036                .add_listener(app, Listener::handle_method(self, Self::on_focus_change));
1037        }
1038    }
1039
1040    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RawAutocomplete<T>) {
1041        if old_widget.text_editing_controller != self.widget(app).text_editing_controller {
1042            if let Some(controller) = &old_widget.text_editing_controller {
1043                controller
1044                    .handle()
1045                    .remove_listener(app, &Listener::handle_method(self, Self::on_changed_field));
1046            }
1047            if old_widget.text_editing_controller.is_none()
1048                && let Some(controller) = app.get_mut(self).internal_text_editing_controller.take()
1049            {
1050                controller.dispose(app);
1051            }
1052            if let Some(controller) = self.widget(app).text_editing_controller.clone() {
1053                controller
1054                    .handle()
1055                    .add_listener(app, Listener::handle_method(self, Self::on_changed_field));
1056            }
1057        }
1058        if old_widget.focus_node != self.widget(app).focus_node {
1059            if let Some(focus_node) = &old_widget.focus_node {
1060                focus_node
1061                    .handle()
1062                    .remove_listener(app, &Listener::handle_method(self, Self::on_focus_change));
1063            }
1064            if old_widget.focus_node.is_none()
1065                && let Some(focus_node) = app.get_mut(self).internal_focus_node.take()
1066            {
1067                focus_node.dispose(app);
1068            }
1069            if let Some(focus_node) = self.widget(app).focus_node.clone() {
1070                focus_node
1071                    .handle()
1072                    .add_listener(app, Listener::handle_method(self, Self::on_focus_change));
1073            }
1074            // The new node's focus state may not match the old node's. Update `has_focus`, but
1075            // not the options view visibility, because this runs during build, when the overlay
1076            // portal controller can't show or hide.
1077            let has_focus = self.focus_node(app).handle().has_focus(app);
1078            app.get_mut(self).has_focus = has_focus;
1079        }
1080    }
1081
1082    fn dispose(self: Handle<Self>, app: &mut App) {
1083        if let Some(controller) = self.widget(app).text_editing_controller.clone() {
1084            controller
1085                .handle()
1086                .remove_listener(app, &Listener::handle_method(self, Self::on_changed_field));
1087        }
1088        if let Some(controller) = app.get(self).internal_text_editing_controller.clone() {
1089            controller.dispose(app);
1090        }
1091        if let Some(focus_node) = self.widget(app).focus_node.clone() {
1092            focus_node
1093                .handle()
1094                .remove_listener(app, &Listener::handle_method(self, Self::on_focus_change));
1095        }
1096        if let Some(focus_node) = app.get(self).internal_focus_node.clone() {
1097            focus_node.dispose(app);
1098        }
1099        self.highlighted_option_index(app).dispose(app);
1100    }
1101
1102    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1103        let field_view = match self.widget(app).field_view_builder.clone() {
1104            Some(field_view_builder) => {
1105                let text_editing_controller = self.text_editing_controller(app);
1106                let focus_node = self.focus_node(app);
1107                let on_field_submitted: VoidCallback =
1108                    Rc::new(move |app: &mut App| self.on_field_submitted(app));
1109                field_view_builder(
1110                    app,
1111                    context,
1112                    text_editing_controller,
1113                    focus_node,
1114                    on_field_submitted,
1115                )
1116            }
1117            // Horizontally expand to make sure the options view's width won't be zero.
1118            None => SizedBox::new()
1119                .width(f64::INFINITY)
1120                .height(0.0)
1121                .into_widget(),
1122        };
1123        let controller = app
1124            .get(self)
1125            .options_view_controller
1126            .clone()
1127            .expect("made in init_state");
1128        let action_map = self.action_map(app);
1129        OverlayPortal::overlay_child_layout_builder(controller, move |app, context, layout_info| {
1130            self.build_options_view(app, context, layout_info)
1131        })
1132        .child(TextFieldTapRegion::new(Shortcuts::new(
1133            Self::shortcuts(app),
1134            Actions::new(action_map, field_view),
1135        )))
1136        .into_widget()
1137    }
1138}
1139
1140fn shortcut(activator: SingleActivator, intent: impl Intent) -> (ShortcutActivatorRef, IntentRef) {
1141    (Rc::new(activator), Rc::new(intent))
1142}
1143
1144/// Dart's `_AutocompleteCallbackAction`: a [`CallbackAction`] whose enabled state, and so
1145/// whether it consumes its key, is asked of a callback.
1146struct AutocompleteCallbackAction<I: Intent> {
1147    action: ActionData,
1148    on_invoke: OnInvokeCallback<I>,
1149
1150    // The enabled state determines whether the action will consume the key shortcut or let
1151    // it continue on to the underlying text field. They should only be enabled when the
1152    // options are showing so shortcuts can be used to navigate them.
1153    is_enabled_callback: Rc<dyn Fn(&mut App) -> bool>,
1154}
1155
1156impl<I: Intent> AutocompleteCallbackAction<I> {
1157    fn new(
1158        app: &mut App,
1159        on_invoke: OnInvokeCallback<I>,
1160        is_enabled_callback: Rc<dyn Fn(&mut App) -> bool>,
1161    ) -> Ref<AutocompleteCallbackAction<I>> {
1162        app.create(AutocompleteCallbackAction {
1163            action: ActionData::new(),
1164            on_invoke,
1165            is_enabled_callback,
1166        })
1167    }
1168}
1169
1170impl<I: Intent> Action for AutocompleteCallbackAction<I> {
1171    type Intent = I;
1172    crate::action_accessors!();
1173
1174    fn is_enabled(self: Handle<Self>, app: &mut App, _intent: &I) -> bool {
1175        let is_enabled_callback = Rc::clone(&app.get(self).is_enabled_callback);
1176        is_enabled_callback(app)
1177    }
1178
1179    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &I) -> bool {
1180        self.is_enabled(app, intent)
1181    }
1182
1183    fn invoke(self: Handle<Self>, app: &mut App, intent: &I) -> Option<Rc<dyn Any>> {
1184        let on_invoke = Rc::clone(&app.get(self).on_invoke);
1185        on_invoke(app, intent)
1186    }
1187}
1188
1189/// An [`Intent`] to highlight the previous option in the autocomplete list.
1190#[derive(Clone, Copy, Debug, Default)]
1191pub struct AutocompletePreviousOptionIntent;
1192
1193impl AutocompletePreviousOptionIntent {
1194    /// Creates an instance of AutocompletePreviousOptionIntent.
1195    pub const fn new() -> AutocompletePreviousOptionIntent {
1196        AutocompletePreviousOptionIntent
1197    }
1198}
1199
1200impl Intent for AutocompletePreviousOptionIntent {
1201    fn as_any(&self) -> &dyn Any {
1202        self
1203    }
1204}
1205
1206/// An [`Intent`] to highlight the next option in the autocomplete list.
1207#[derive(Clone, Copy, Debug, Default)]
1208pub struct AutocompleteNextOptionIntent;
1209
1210impl AutocompleteNextOptionIntent {
1211    /// Creates an instance of AutocompleteNextOptionIntent.
1212    pub const fn new() -> AutocompleteNextOptionIntent {
1213        AutocompleteNextOptionIntent
1214    }
1215}
1216
1217impl Intent for AutocompleteNextOptionIntent {
1218    fn as_any(&self) -> &dyn Any {
1219        self
1220    }
1221}
1222
1223/// An [`Intent`] to highlight the first option in the autocomplete list.
1224#[derive(Clone, Copy, Debug, Default)]
1225pub struct AutocompleteFirstOptionIntent;
1226
1227impl AutocompleteFirstOptionIntent {
1228    /// Creates an instance of AutocompleteFirstOptionIntent.
1229    pub const fn new() -> AutocompleteFirstOptionIntent {
1230        AutocompleteFirstOptionIntent
1231    }
1232}
1233
1234impl Intent for AutocompleteFirstOptionIntent {
1235    fn as_any(&self) -> &dyn Any {
1236        self
1237    }
1238}
1239
1240/// An [`Intent`] to highlight the last option in the autocomplete list.
1241#[derive(Clone, Copy, Debug, Default)]
1242pub struct AutocompleteLastOptionIntent;
1243
1244impl AutocompleteLastOptionIntent {
1245    /// Creates an instance of AutocompleteLastOptionIntent.
1246    pub const fn new() -> AutocompleteLastOptionIntent {
1247        AutocompleteLastOptionIntent
1248    }
1249}
1250
1251impl Intent for AutocompleteLastOptionIntent {
1252    fn as_any(&self) -> &dyn Any {
1253        self
1254    }
1255}
1256
1257/// An [`Intent`] to highlight the option one page after the currently highlighted option in
1258/// the autocomplete list.
1259#[derive(Clone, Copy, Debug, Default)]
1260pub struct AutocompleteNextPageOptionIntent;
1261
1262impl AutocompleteNextPageOptionIntent {
1263    /// Creates an instance of AutocompleteNextPageOptionIntent.
1264    pub const fn new() -> AutocompleteNextPageOptionIntent {
1265        AutocompleteNextPageOptionIntent
1266    }
1267}
1268
1269impl Intent for AutocompleteNextPageOptionIntent {
1270    fn as_any(&self) -> &dyn Any {
1271        self
1272    }
1273}
1274
1275/// An [`Intent`] to highlight the option one page before the currently highlighted option in
1276/// the autocomplete list.
1277#[derive(Clone, Copy, Debug, Default)]
1278pub struct AutocompletePreviousPageOptionIntent;
1279
1280impl AutocompletePreviousPageOptionIntent {
1281    /// Creates an instance of AutocompletePreviousPageOptionIntent.
1282    pub const fn new() -> AutocompletePreviousPageOptionIntent {
1283        AutocompletePreviousPageOptionIntent
1284    }
1285}
1286
1287impl Intent for AutocompletePreviousPageOptionIntent {
1288    fn as_any(&self) -> &dyn Any {
1289        self
1290    }
1291}
1292
1293/// An inherited widget used to indicate which autocomplete option should be highlighted for
1294/// keyboard navigation.
1295///
1296/// The [`RawAutocomplete`] widget will wrap the options view generated by the
1297/// `options_view_builder` with this widget to provide the highlighted option's index to the
1298/// builder.
1299///
1300/// In the builder callback the index of the highlighted option can be obtained by using the
1301/// associated function [`of`](Self::of):
1302///
1303/// ```text
1304/// let highlighted_index = AutocompleteHighlightedOption::of(app, context);
1305/// ```
1306///
1307/// which can then be used to tell which option should be given a visual indication that will
1308/// be the option selected with the keyboard.
1309///
1310/// Both [`InheritedWidget`] and [`InheritedNotifier`] offer an `IntoWidget` kind, so this
1311/// widget names the conversion itself ([`into_widget`](Self::into_widget)).
1312#[derive(Debug)]
1313pub struct AutocompleteHighlightedOption {
1314    /// See [`InheritedWidget::key`].
1315    pub key: Option<KeyRef>,
1316    /// Dart's `InheritedNotifier.notifier`: the highlighted option's index.
1317    pub notifier: Ref<ValueNotifier<usize>>,
1318    /// See [`InheritedWidget::child`].
1319    pub child: WidgetRef,
1320}
1321
1322impl AutocompleteHighlightedOption {
1323    /// Create an instance of AutocompleteHighlightedOption inherited widget.
1324    #[cfg_attr(debug_assertions, track_caller)]
1325    pub fn new<K>(
1326        highlight_index_notifier: Ref<ValueNotifier<usize>>,
1327        child: impl IntoWidget<K>,
1328    ) -> AutocompleteHighlightedOption {
1329        AutocompleteHighlightedOption {
1330            key: None,
1331            notifier: highlight_index_notifier,
1332            child: child.into_widget(),
1333        }
1334    }
1335
1336    /// Dart `AutocompleteHighlightedOption(key:)`.
1337    pub fn key(mut self, key: KeyRef) -> AutocompleteHighlightedOption {
1338        self.key = Some(key);
1339        self
1340    }
1341
1342    /// The tree node, as an [`InheritedNotifier`].
1343    pub fn into_widget(self) -> WidgetRef {
1344        IntoWidget::<InheritedNotifierKind>::into_widget(self)
1345    }
1346
1347    /// Returns the index of the highlighted option from the closest
1348    /// [`AutocompleteHighlightedOption`] ancestor.
1349    ///
1350    /// If there is no ancestor, it returns 0.
1351    pub fn of(app: &mut App, context: BuildContext) -> usize {
1352        let Some(widget) =
1353            context.depend_on_inherited_widget_of_exact_type::<AutocompleteHighlightedOption>(app)
1354        else {
1355            return 0;
1356        };
1357        let notifier = widget.notifier.handle();
1358        *notifier.value(app)
1359    }
1360}
1361
1362impl InheritedWidget for AutocompleteHighlightedOption {
1363    crate::inherited_notifier_overrides!();
1364
1365    fn key(&self) -> Option<&KeyRef> {
1366        self.key.as_ref()
1367    }
1368
1369    fn child(&self) -> &WidgetRef {
1370        &self.child
1371    }
1372}
1373
1374impl InheritedNotifier for AutocompleteHighlightedOption {
1375    type Notifier = ValueNotifier<usize>;
1376
1377    fn notifier(&self) -> Option<Handle<ValueNotifier<usize>>> {
1378        Some(self.notifier.handle())
1379    }
1380}
1381
1382#[cfg(test)]
1383mod tests {
1384    use std::cell::{Cell, RefCell};
1385    use std::time::Duration;
1386
1387    use waft_embedder::{Offset, Size, TextDirection, TextInputAction, View, ViewPadding};
1388    use waft_foundation::Completer;
1389    use waft_painting::EdgeInsetsGeometry;
1390    use waft_services::PhysicalKeyboardKey;
1391
1392    use super::*;
1393    use crate::framework::IntoWidget;
1394    use crate::framework::StatelessWidget;
1395    use crate::testing::{
1396        Finder, TestTextField, TestWidgetsApp, WidgetTester, assert_more_or_less_equals,
1397        assert_more_or_less_equals_within, delayed, expect, find, finds_n_widgets, finds_nothing,
1398        finds_one_widget, finds_widgets, test_widgets,
1399    };
1400    use waft_foundation::ChangeNotifier;
1401
1402    use crate::widgets::editable_text::TextEditingControllerLeaf;
1403
1404    use crate::widgets::basic::{
1405        Center, Column, Directionality, Expanded, Padding, Row, SizedBox, StatefulBuilder,
1406    };
1407    use crate::widgets::container::Container;
1408    use crate::widgets::focus_manager::{AnyFocusNode, UnfocusDisposition};
1409    use crate::widgets::focus_scope::Focus;
1410    use crate::widgets::gesture_detector::GestureDetector;
1411    use crate::widgets::placeholder::Placeholder;
1412    use crate::widgets::scroll_view::ListView;
1413    use crate::widgets::text::Text;
1414
1415    // Matches the Material kMinInteractiveDimension (48.0).
1416    const K_MIN_INTERACTIVE_DIMENSION: f64 = 48.0;
1417
1418    const K_OPTIONS: [&str; 14] = [
1419        "aardvark",
1420        "bobcat",
1421        "chameleon",
1422        "dingo",
1423        "elephant",
1424        "flamingo",
1425        "goose",
1426        "hippopotamus",
1427        "iguana",
1428        "jaguar",
1429        "koala",
1430        "lemur",
1431        "mouse",
1432        "northern white rhinoceros",
1433    ];
1434
1435    const OPEN_DIRECTIONS: [OptionsViewOpenDirection; 3] = [
1436        OptionsViewOpenDirection::Up,
1437        OptionsViewOpenDirection::Down,
1438        OptionsViewOpenDirection::MostSpace,
1439    ];
1440
1441    #[derive(Clone, Debug, PartialEq)]
1442    struct User {
1443        email: &'static str,
1444        name: &'static str,
1445    }
1446
1447    impl Display for User {
1448        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1449            write!(f, "{}, {}", self.name, self.email)
1450        }
1451    }
1452
1453    fn k_options_users() -> [User; 3] {
1454        [
1455            User {
1456                name: "Alice",
1457                email: "alice@example.com",
1458            },
1459            User {
1460                name: "Bob",
1461                email: "bob@example.com",
1462            },
1463            User {
1464                name: "Charlie",
1465                email: "charlie123@gmail.com",
1466            },
1467        ]
1468    }
1469
1470    /// Dart's `kOptions.where((option) => option.contains(text.toLowerCase()))`.
1471    fn matching(text: &str) -> Vec<String> {
1472        let query = text.to_lowercase();
1473        K_OPTIONS
1474            .iter()
1475            .filter(|option| option.contains(&query))
1476            .map(|option| option.to_string())
1477            .collect()
1478    }
1479
1480    /// The `optionsBuilder` most cases share: the options containing the field's text.
1481    fn string_options(_app: &mut App, value: TextEditingValue) -> Task<Vec<String>> {
1482        Task::ready(matching(&value.text))
1483    }
1484
1485    /// Dart's `_OptionTile`: a tappable box at least [`K_MIN_INTERACTIVE_DIMENSION`] tall.
1486    #[derive(Debug)]
1487    struct OptionTile {
1488        on_tap: Listener,
1489        child: WidgetRef,
1490    }
1491
1492    impl StatelessWidget for OptionTile {
1493        fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1494            GestureDetector::new()
1495                .on_tap(self.on_tap.clone())
1496                .child(
1497                    ConstrainedBox::new(BoxConstraints::new().min_height(48.0))
1498                        .child(self.child.clone()),
1499                )
1500                .into_widget()
1501        }
1502    }
1503
1504    /// Dart's `TestListTile(title: Text(option))` (`list_tile_tester.dart`).
1505    fn test_list_tile(title: impl Into<String>) -> WidgetRef {
1506        Container::new()
1507            .constraints(BoxConstraints::new().min_height(56.0))
1508            .padding(EdgeInsetsGeometry::symmetric(4.0, 16.0))
1509            .child(Text::new(title))
1510            .into_widget()
1511    }
1512
1513    /// What a case's builders hand out, as Dart's `late` locals capture them.
1514    struct Captured<T> {
1515        focus_node: RefCell<Option<FocusNodeRef>>,
1516        controller: RefCell<Option<TextEditingControllerRef>>,
1517        on_field_submitted: RefCell<Option<VoidCallback>>,
1518        last_options: RefCell<Option<Vec<T>>>,
1519        last_on_selected: RefCell<Option<AutocompleteOnSelected<T>>>,
1520        last_highlighted: Cell<usize>,
1521    }
1522
1523    impl<T> Captured<T> {
1524        fn new() -> Rc<Captured<T>> {
1525            Rc::new(Captured {
1526                focus_node: RefCell::new(None),
1527                controller: RefCell::new(None),
1528                on_field_submitted: RefCell::new(None),
1529                last_options: RefCell::new(None),
1530                last_on_selected: RefCell::new(None),
1531                last_highlighted: Cell::new(0),
1532            })
1533        }
1534
1535        fn focus_node(&self) -> AnyFocusNode {
1536            self.focus_node
1537                .borrow()
1538                .as_ref()
1539                .expect("the field was built")
1540                .handle()
1541        }
1542
1543        fn controller(&self) -> TextEditingControllerRef {
1544            self.controller
1545                .borrow()
1546                .clone()
1547                .expect("the field was built")
1548        }
1549
1550        fn on_selected(&self) -> AutocompleteOnSelected<T> {
1551            self.last_on_selected
1552                .borrow()
1553                .clone()
1554                .expect("the options were built")
1555        }
1556    }
1557
1558    impl<T: Clone> Captured<T> {
1559        fn options(&self) -> Vec<T> {
1560            self.last_options
1561                .borrow()
1562                .clone()
1563                .expect("the options were built")
1564        }
1565    }
1566
1567    /// The `fieldViewBuilder` most cases share: a [`TestTextField`] keyed `field_key` whose
1568    /// controller, focus node and submit callback land in `captured`.
1569    fn field_view<T: 'static>(
1570        captured: &Rc<Captured<T>>,
1571        field_key: &GlobalKey,
1572    ) -> impl Fn(
1573        &mut App,
1574        BuildContext,
1575        TextEditingControllerRef,
1576        FocusNodeRef,
1577        VoidCallback,
1578    ) -> WidgetRef
1579    + 'static {
1580        let captured = Rc::clone(captured);
1581        let field_key = field_key.clone();
1582        move |_app, _context, controller, focus_node, on_field_submitted| {
1583            *captured.focus_node.borrow_mut() = Some(focus_node.clone());
1584            *captured.controller.borrow_mut() = Some(controller.clone());
1585            *captured.on_field_submitted.borrow_mut() = Some(Rc::clone(&on_field_submitted));
1586            TestTextField::new()
1587                .key(&field_key)
1588                .focus_node(focus_node)
1589                .controller(controller)
1590                .on_submitted(move |app, _value| on_field_submitted(app))
1591                .into_widget()
1592        }
1593    }
1594
1595    /// The `optionsViewBuilder` most cases share: a `Container` keyed `options_key`, with the
1596    /// options, the select callback and the highlighted index landing in `captured`.
1597    fn options_view<T: Clone + 'static>(
1598        captured: &Rc<Captured<T>>,
1599        options_key: &GlobalKey,
1600    ) -> impl Fn(&mut App, BuildContext, AutocompleteOnSelected<T>, &[T]) -> WidgetRef + 'static
1601    {
1602        let captured = Rc::clone(captured);
1603        let options_key = options_key.clone();
1604        move |app, context, on_selected, options| {
1605            captured
1606                .last_highlighted
1607                .set(AutocompleteHighlightedOption::of(app, context));
1608            *captured.last_options.borrow_mut() = Some(options.to_vec());
1609            *captured.last_on_selected.borrow_mut() = Some(on_selected);
1610            Container::new()
1611                .key(options_key.clone().into())
1612                .into_widget()
1613        }
1614    }
1615
1616    /// The `RawAutocomplete<String>` most cases build: the shared options, field and options
1617    /// view.
1618    fn string_autocomplete(
1619        captured: &Rc<Captured<String>>,
1620        field_key: &GlobalKey,
1621        options_key: &GlobalKey,
1622    ) -> RawAutocomplete<String> {
1623        RawAutocomplete::new(options_view(captured, options_key), string_options)
1624            .field_view_builder(field_view(captured, field_key))
1625    }
1626
1627    /// Dart's `const TextEditingValue(text: text, selection: TextSelection.collapsed(..))`
1628    /// with the caret at `offset`.
1629    fn value_at(text: &str, offset: i32) -> TextEditingValue {
1630        TextEditingValue::new()
1631            .text(text)
1632            .selection(TextSelection::collapsed(offset, TextAffinity::Downstream))
1633    }
1634
1635    fn send_key(
1636        tester: &mut WidgetTester,
1637        physical: PhysicalKeyboardKey,
1638        logical: LogicalKeyboardKey,
1639    ) {
1640        tester.send_key_event(physical, logical);
1641    }
1642
1643    fn arrow_down(tester: &mut WidgetTester) {
1644        send_key(
1645            tester,
1646            PhysicalKeyboardKey::ARROW_DOWN,
1647            LogicalKeyboardKey::ARROW_DOWN,
1648        );
1649    }
1650
1651    fn arrow_up(tester: &mut WidgetTester) {
1652        send_key(
1653            tester,
1654            PhysicalKeyboardKey::ARROW_UP,
1655            LogicalKeyboardKey::ARROW_UP,
1656        );
1657    }
1658
1659    fn escape(tester: &mut WidgetTester) {
1660        send_key(
1661            tester,
1662            PhysicalKeyboardKey::ESCAPE,
1663            LogicalKeyboardKey::ESCAPE,
1664        );
1665    }
1666
1667    /// Dart's `sendKeyDownEvent(control); sendKeyEvent(key); sendKeyUpEvent(control)`.
1668    fn with_control(
1669        tester: &mut WidgetTester,
1670        physical: PhysicalKeyboardKey,
1671        logical: LogicalKeyboardKey,
1672    ) {
1673        tester.send_key_down_event(
1674            PhysicalKeyboardKey::CONTROL_LEFT,
1675            LogicalKeyboardKey::CONTROL_LEFT,
1676        );
1677        send_key(tester, physical, logical);
1678        tester.send_key_up_event(
1679            PhysicalKeyboardKey::CONTROL_LEFT,
1680            LogicalKeyboardKey::CONTROL_LEFT,
1681        );
1682    }
1683
1684    /// Dart's `textEditingController.text`.
1685    fn text_of(tester: &WidgetTester, controller: &TextEditingControllerRef) -> String {
1686        controller
1687            .handle()
1688            .text_value(&tester.cell.borrow())
1689            .to_string()
1690    }
1691
1692    fn strings(options: &[&str]) -> Vec<String> {
1693        options.iter().map(|option| option.to_string()).collect()
1694    }
1695
1696    #[test]
1697    fn can_filter_and_select_a_list_of_string_options() {
1698        test_widgets(|tester| {
1699            let field_key = GlobalKey::new();
1700            let options_key = GlobalKey::new();
1701            let captured = Captured::<String>::new();
1702            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
1703                &captured,
1704                &field_key,
1705                &options_key,
1706            )));
1707
1708            // The field is always rendered, but the options are not unless needed.
1709            expect(tester, &find::by_global_key(&field_key), finds_one_widget());
1710            expect(tester, &find::by_global_key(&options_key), finds_nothing());
1711
1712            // Focus the empty field. All the options are displayed.
1713            let focus_node = captured.focus_node();
1714            tester.update(|app| focus_node.request_focus(app, None));
1715            tester.pump();
1716            expect(
1717                tester,
1718                &find::by_global_key(&options_key),
1719                finds_one_widget(),
1720            );
1721            assert_eq!(captured.options().len(), K_OPTIONS.len());
1722
1723            // Enter text. The options are filtered by the text.
1724            let controller = captured.controller();
1725            tester.update(|app| controller.handle().set_value(app, value_at("ele", 3)));
1726            tester.pump();
1727            expect(tester, &find::by_global_key(&field_key), finds_one_widget());
1728            expect(
1729                tester,
1730                &find::by_global_key(&options_key),
1731                finds_one_widget(),
1732            );
1733            assert_eq!(captured.options(), strings(&["chameleon", "elephant"]));
1734
1735            // Select an option. The options hide and the field updates to show the selection.
1736            let selection = captured.options()[1].clone();
1737            let on_selected = captured.on_selected();
1738            tester.update(|app| on_selected(app, selection.clone()));
1739            tester.pump();
1740            expect(tester, &find::by_global_key(&field_key), finds_one_widget());
1741            expect(tester, &find::by_global_key(&options_key), finds_nothing());
1742            assert_eq!(text_of(tester, &controller), selection);
1743
1744            // Modify the field text. The options appear again and are filtered.
1745            tester.update(|app| controller.handle().set_value(app, value_at("e", 1)));
1746            tester.pump();
1747            expect(tester, &find::by_global_key(&field_key), finds_one_widget());
1748            expect(
1749                tester,
1750                &find::by_global_key(&options_key),
1751                finds_one_widget(),
1752            );
1753            assert_eq!(
1754                captured.options(),
1755                strings(&[
1756                    "chameleon",
1757                    "elephant",
1758                    "goose",
1759                    "lemur",
1760                    "mouse",
1761                    "northern white rhinoceros"
1762                ])
1763            );
1764        });
1765    }
1766
1767    #[test]
1768    fn options_are_shown_one_frame_after_tapping_in_field() {
1769        test_widgets(|tester| {
1770            let field_key = GlobalKey::new();
1771            let options_key = GlobalKey::new();
1772            let options_key_for_view = options_key.clone();
1773            let captured = Captured::<String>::new();
1774            tester.pump_widget(
1775                TestWidgetsApp::new().home(
1776                    Align::new().alignment(AlignmentGeometry::TOP_CENTER).child(
1777                        RawAutocomplete::new(
1778                            move |_app, _context, _on_selected, options: &[String]| {
1779                                ListView::new()
1780                                    .key(options_key_for_view.clone().into())
1781                                    .children(
1782                                        options
1783                                            .iter()
1784                                            .map(|option| Text::new(option.clone()).into_widget()),
1785                                    )
1786                                    .into_widget()
1787                            },
1788                            string_options,
1789                        )
1790                        .field_view_builder(field_view(&captured, &field_key)),
1791                    ),
1792                ),
1793            );
1794
1795            // Field is shown but not options.
1796            expect(tester, &find::by_global_key(&field_key), finds_one_widget());
1797            expect(tester, &find::by_global_key(&options_key), finds_nothing());
1798            expect(tester, &find::text("aardvark"), finds_nothing());
1799
1800            // Tap to show the options.
1801            tester.tap(find::by_global_key(&field_key));
1802            tester.pump();
1803            expect(tester, &find::by_global_key(&field_key), finds_one_widget());
1804            expect(
1805                tester,
1806                &find::by_global_key(&options_key),
1807                finds_one_widget(),
1808            );
1809            expect(tester, &find::text("aardvark"), finds_one_widget());
1810        });
1811    }
1812
1813    /// The `optionsViewBuilder` of `_OptionTile`s, each padded text selecting its option:
1814    /// `ListView.builder(padding: EdgeInsets.zero, shrinkWrap: true, ..)`.
1815    fn option_tiles(
1816        options_key: &GlobalKey,
1817    ) -> impl Fn(&mut App, BuildContext, AutocompleteOnSelected<String>, &[String]) -> WidgetRef + 'static
1818    {
1819        let options_key = options_key.clone();
1820        move |_app, _context, on_selected, options| {
1821            let options = options.to_vec();
1822            let count = options.len() as i32;
1823            ListView::builder(move |_app, _context, index| {
1824                let option = options[index as usize].clone();
1825                let on_selected = Rc::clone(&on_selected);
1826                let tapped = option.clone();
1827                Some(
1828                    OptionTile {
1829                        on_tap: Listener::new(move |app| on_selected(app, tapped.clone())),
1830                        child: Padding::new(EdgeInsetsGeometry::all(16.0))
1831                            .child(Text::new(option))
1832                            .into_widget(),
1833                    }
1834                    .into_widget(),
1835                )
1836            })
1837            .item_count(count)
1838            .build()
1839            .key(options_key.clone().into())
1840            .padding(EdgeInsetsGeometry::ZERO)
1841            .shrink_wrap(true)
1842            .into_widget()
1843        }
1844    }
1845
1846    /// A `StatefulBuilder`'s `setState`, captured as Dart's `late StateSetter setState`.
1847    type CapturedSetter = Rc<RefCell<Option<crate::widgets::basic::StateSetter>>>;
1848
1849    fn set_state(tester: &mut WidgetTester, setter: &CapturedSetter, mut change: impl FnMut()) {
1850        let setter = setter.borrow().clone().expect("the builder ran");
1851        tester.update(|app| setter(app, &mut |_app| change()));
1852    }
1853
1854    fn by_key(key: &GlobalKey) -> Finder {
1855        find::by_global_key(key)
1856    }
1857
1858    /// A field and its focus node made by the case, as Dart's `TextEditingController()` and
1859    /// `FocusNode()` with `addTearDown(dispose)`.
1860    fn own_field(tester: &WidgetTester) -> (Ref<TextEditingController>, Ref<FocusNode>) {
1861        tester.update(|app| (TextEditingController::new(app), FocusNode::new(app)))
1862    }
1863
1864    fn focus_of(node: &Ref<FocusNode>) -> AnyFocusNode {
1865        let erased: FocusNodeRef = node.erase();
1866        erased.handle()
1867    }
1868
1869    #[test]
1870    fn can_split_the_field_and_options() {
1871        test_widgets(|tester| {
1872            let field_key = GlobalKey::new();
1873            let options_key = GlobalKey::new();
1874            let autocomplete_key = GlobalKey::new();
1875            let captured = Captured::<String>::new();
1876            let (text_editing_controller, focus_node) = own_field(tester);
1877
1878            let submitted_key = autocomplete_key.clone();
1879            let view_key = options_key.clone();
1880            let recorded = Rc::clone(&captured);
1881            tester.pump_widget(
1882                TestWidgetsApp::new().home(
1883                    Column::new().children([
1884                        // The field that is not actually a child of RawAutocomplete.
1885                        TestTextField::new()
1886                            .key(&field_key)
1887                            .controller(text_editing_controller.erase())
1888                            .focus_node(focus_node.erase())
1889                            .on_submitted(move |app, _value| {
1890                                RawAutocomplete::<String>::on_field_submitted(app, &submitted_key)
1891                            })
1892                            .into_widget(),
1893                        Expanded::new(
1894                            Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
1895                                RawAutocomplete::new(
1896                                    move |_app,
1897                                          _context,
1898                                          on_selected: AutocompleteOnSelected<String>,
1899                                          options: &[String]| {
1900                                        *recorded.last_options.borrow_mut() =
1901                                            Some(options.to_vec());
1902                                        *recorded.last_on_selected.borrow_mut() =
1903                                            Some(Rc::clone(&on_selected));
1904                                        ListView::new()
1905                                            .key(view_key.clone().into())
1906                                            .children(options.iter().map(|option| {
1907                                                let on_selected = Rc::clone(&on_selected);
1908                                                let tapped = option.clone();
1909                                                GestureDetector::new()
1910                                                    .on_tap(Listener::new(move |app| {
1911                                                        on_selected(app, tapped.clone())
1912                                                    }))
1913                                                    .child(test_list_tile(option.clone()))
1914                                                    .into_widget()
1915                                            }))
1916                                            .into_widget()
1917                                    },
1918                                    string_options,
1919                                )
1920                                .key(autocomplete_key.clone().into())
1921                                .focus_node(focus_node.erase())
1922                                .text_editing_controller(text_editing_controller.erase()),
1923                            ),
1924                        )
1925                        .into_widget(),
1926                    ]),
1927                ),
1928            );
1929
1930            // The field is always rendered, but the options are not unless needed.
1931            expect(tester, &by_key(&field_key), finds_one_widget());
1932            expect(tester, &by_key(&options_key), finds_nothing());
1933
1934            // Focus the empty field. All the options are displayed.
1935            tester.update(|app| focus_of(&focus_node).request_focus(app, None));
1936            tester.pump();
1937            expect(tester, &by_key(&options_key), finds_one_widget());
1938            assert_eq!(captured.options().len(), K_OPTIONS.len());
1939            assert!(tester.get_size(by_key(&options_key)).width() > 0.0);
1940
1941            // Enter text. The options are filtered by the text.
1942            let controller: TextEditingControllerRef = text_editing_controller.erase();
1943            tester.update(|app| controller.handle().set_value(app, value_at("ele", 3)));
1944            tester.pump();
1945            expect(tester, &by_key(&field_key), finds_one_widget());
1946            expect(tester, &by_key(&options_key), finds_one_widget());
1947            assert_eq!(captured.options(), strings(&["chameleon", "elephant"]));
1948
1949            // Select an option. The options hide and the field updates to show the selection.
1950            let selection = captured.options()[1].clone();
1951            let on_selected = captured.on_selected();
1952            tester.update(|app| on_selected(app, selection.clone()));
1953            tester.pump();
1954            expect(tester, &by_key(&field_key), finds_one_widget());
1955            expect(tester, &by_key(&options_key), finds_nothing());
1956            assert_eq!(text_of(tester, &controller), selection);
1957
1958            // Modify the field text. The options appear again and are filtered.
1959            tester.update(|app| controller.handle().set_value(app, value_at("e", 1)));
1960            tester.pump();
1961            expect(tester, &by_key(&field_key), finds_one_widget());
1962            expect(tester, &by_key(&options_key), finds_one_widget());
1963            assert_eq!(
1964                captured.options(),
1965                strings(&[
1966                    "chameleon",
1967                    "elephant",
1968                    "goose",
1969                    "lemur",
1970                    "mouse",
1971                    "northern white rhinoceros"
1972                ])
1973            );
1974        });
1975    }
1976
1977    #[test]
1978    fn tapping_on_an_option_selects_it_in_each_open_direction() {
1979        for open_direction in OPEN_DIRECTIONS {
1980            test_widgets(|tester| {
1981                let field_key = GlobalKey::new();
1982                let options_key = GlobalKey::new();
1983                let captured = Captured::<String>::new();
1984                let view_key = options_key.clone();
1985                let recorded = Rc::clone(&captured);
1986                tester.pump_widget(
1987                    TestWidgetsApp::new().home(
1988                        Column::new().children([
1989                            SizedBox::new().height(200.0).into_widget(),
1990                            RawAutocomplete::new(
1991                                move |_app,
1992                                      _context,
1993                                      on_selected: AutocompleteOnSelected<String>,
1994                                      options: &[String]| {
1995                                    *recorded.last_options.borrow_mut() = Some(options.to_vec());
1996                                    let options = options.to_vec();
1997                                    let count = options.len() as i32;
1998                                    ListView::builder(move |_app, _context, index| {
1999                                        let option = options[index as usize].clone();
2000                                        let on_selected = Rc::clone(&on_selected);
2001                                        let tapped = option.clone();
2002                                        Some(
2003                                            GestureDetector::new()
2004                                                .on_tap(Listener::new(move |app| {
2005                                                    on_selected(app, tapped.clone())
2006                                                }))
2007                                                .child(test_list_tile(option))
2008                                                .into_widget(),
2009                                        )
2010                                    })
2011                                    .item_count(count)
2012                                    .build()
2013                                    .key(view_key.clone().into())
2014                                    .padding(EdgeInsetsGeometry::all(8.0))
2015                                    .into_widget()
2016                                },
2017                                string_options,
2018                            )
2019                            .options_view_open_direction(open_direction)
2020                            .field_view_builder(field_view(&captured, &field_key))
2021                            .into_widget(),
2022                        ]),
2023                    ),
2024                );
2025
2026                // The field is always rendered, but the options are not unless needed.
2027                expect(tester, &by_key(&field_key), finds_one_widget());
2028                expect(tester, &by_key(&options_key), finds_nothing());
2029
2030                // Tap on the text field to open the options.
2031                tester.tap(by_key(&field_key));
2032                tester.pump();
2033                expect(tester, &by_key(&options_key), finds_one_widget());
2034                assert_eq!(captured.options().len(), K_OPTIONS.len());
2035
2036                tester.tap(find::text(K_OPTIONS[2]));
2037                tester.pump();
2038
2039                expect(tester, &by_key(&options_key), finds_nothing());
2040
2041                assert_eq!(
2042                    text_of(tester, &captured.controller()),
2043                    K_OPTIONS[2],
2044                    "{open_direction:?}"
2045                );
2046            });
2047        }
2048    }
2049
2050    #[test]
2051    fn when_not_enough_room_for_options_options_cover_field_in_each_open_direction() {
2052        for open_direction in OPEN_DIRECTIONS {
2053            test_widgets(|tester| {
2054                const PADDING: f64 = 32.0;
2055                let field_key = GlobalKey::new();
2056                let options_key = GlobalKey::new();
2057                let setter: CapturedSetter = Rc::default();
2058                let alignment = Rc::new(Cell::new(AlignmentGeometry::BOTTOM_CENTER));
2059
2060                let captured = Captured::<String>::new();
2061                let (stored, aligned) = (Rc::clone(&setter), Rc::clone(&alignment));
2062                let (field, options) = (field_key.clone(), options_key.clone());
2063                tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
2064                    move |_app, _context, set_state| {
2065                        *stored.borrow_mut() = Some(set_state);
2066                        Padding::new(EdgeInsetsGeometry::symmetric(0.0, PADDING))
2067                            .child(
2068                                Align::new().alignment(aligned.get()).child(
2069                                    RawAutocomplete::new(option_tiles(&options), string_options)
2070                                        .options_view_open_direction(open_direction)
2071                                        .field_view_builder(field_view(&captured, &field)),
2072                                ),
2073                            )
2074                            .into_widget()
2075                    },
2076                )));
2077
2078                expect(tester, &by_key(&field_key), finds_one_widget());
2079                expect(tester, &by_key(&options_key), finds_nothing());
2080
2081                tester.tap(by_key(&field_key));
2082                tester.pump();
2083
2084                expect(tester, &by_key(&field_key), finds_one_widget());
2085                expect(tester, &by_key(&options_key), finds_one_widget());
2086
2087                tester.enter_text(by_key(&field_key), "go"); // 3 results.
2088                tester.pump();
2089
2090                let tiles = || find::by_type::<OptionTile>();
2091                match open_direction {
2092                    OptionsViewOpenDirection::Up | OptionsViewOpenDirection::MostSpace => {
2093                        // Options are positioned and sized like normal.
2094                        expect(tester, &tiles(), finds_n_widgets(3));
2095                        let option_height = tester.get_size(tiles().first()).height();
2096                        let top_of_field = tester.get_top_left(by_key(&field_key)).dy();
2097                        assert_eq!(
2098                            tester.get_top_left(tiles().first()),
2099                            Offset::new(PADDING, top_of_field - 3.0 * option_height)
2100                        );
2101                        assert_eq!(
2102                            tester.get_bottom_left(tiles().at(2)),
2103                            Offset::new(PADDING, top_of_field)
2104                        );
2105                    }
2106                    OptionsViewOpenDirection::Down => {
2107                        expect(tester, &tiles(), finds_n_widgets(1));
2108                        let options_size = tester.get_size(by_key(&options_key));
2109                        assert_eq!(options_size.height(), K_MIN_INTERACTIVE_DIMENSION);
2110                        // Options are positioned as low as possible while still fitting on
2111                        // screen.
2112                        let bottom_of_field = tester.get_bottom_left(by_key(&options_key)).dy();
2113                        assert_eq!(
2114                            tester.get_top_left(by_key(&options_key)),
2115                            Offset::new(PADDING, bottom_of_field - options_size.height())
2116                        );
2117                    }
2118                }
2119
2120                set_state(tester, &setter, || {
2121                    alignment.set(AlignmentGeometry::TOP_CENTER)
2122                });
2123
2124                tester.pump();
2125
2126                expect(tester, &by_key(&field_key), finds_one_widget());
2127                expect(tester, &by_key(&options_key), finds_one_widget());
2128
2129                match open_direction {
2130                    OptionsViewOpenDirection::Up => {
2131                        // Options are positioned as high as possible while still fitting on
2132                        // the screen.
2133                        expect(tester, &tiles(), finds_n_widgets(1));
2134                        let options_size = tester.get_size(by_key(&options_key));
2135                        assert_eq!(options_size.height(), K_MIN_INTERACTIVE_DIMENSION);
2136                        assert_eq!(
2137                            tester.get_top_left(by_key(&options_key)),
2138                            Offset::new(PADDING, 0.0)
2139                        );
2140                        assert_eq!(
2141                            tester.get_bottom_left(by_key(&options_key)),
2142                            Offset::new(PADDING, options_size.height())
2143                        );
2144                    }
2145                    OptionsViewOpenDirection::Down | OptionsViewOpenDirection::MostSpace => {
2146                        // Options are positioned and sized like normal.
2147                        expect(tester, &tiles(), finds_n_widgets(3));
2148                        let option_height = tester.get_size(tiles().first()).height();
2149                        let bottom_of_field = tester.get_bottom_left(by_key(&field_key)).dy();
2150                        assert_eq!(
2151                            tester.get_top_left(tiles().first()),
2152                            Offset::new(PADDING, bottom_of_field)
2153                        );
2154                        assert_eq!(
2155                            tester.get_bottom_left(tiles().at(2)),
2156                            Offset::new(PADDING, bottom_of_field + 3.0 * option_height)
2157                        );
2158                    }
2159                }
2160            });
2161        }
2162    }
2163
2164    #[test]
2165    fn correct_options_alignment_for_rtl_in_each_open_direction() {
2166        for open_direction in OPEN_DIRECTIONS {
2167            test_widgets(|tester| {
2168                const K_OPTIONS_WIDTH: f64 = 100.0;
2169                let field_key = GlobalKey::new();
2170                let options_key = GlobalKey::new();
2171                let captured = Captured::<String>::new();
2172                let view_key = options_key.clone();
2173                tester.pump_widget(
2174                    TestWidgetsApp::new().home(Directionality::new(
2175                        TextDirection::Rtl,
2176                        Padding::new(EdgeInsetsGeometry::symmetric(0.0, 32.0)).child(
2177                            RawAutocomplete::new(
2178                                move |_app, _context, _on_selected, _options: &[String]| {
2179                                    SizedBox::new()
2180                                        .width(K_OPTIONS_WIDTH)
2181                                        .key(view_key.clone().into())
2182                                        .into_widget()
2183                                },
2184                                string_options,
2185                            )
2186                            .options_view_open_direction(open_direction)
2187                            .field_view_builder(field_view(&captured, &field_key)),
2188                        ),
2189                    )),
2190                );
2191
2192                expect(tester, &by_key(&field_key), finds_one_widget());
2193                expect(tester, &by_key(&options_key), finds_nothing());
2194
2195                tester.tap(find::by_type::<TestTextField>());
2196                tester.pump();
2197
2198                expect(tester, &by_key(&field_key), finds_one_widget());
2199                expect(tester, &by_key(&options_key), finds_one_widget());
2200
2201                assert_eq!(
2202                    tester.get_size(by_key(&options_key)).width(),
2203                    K_OPTIONS_WIDTH
2204                );
2205                assert_eq!(
2206                    tester.get_top_right(by_key(&options_key)).dx(),
2207                    tester.get_top_right(by_key(&field_key)).dx()
2208                );
2209            });
2210        }
2211    }
2212
2213    #[test]
2214    fn options_width_matches_field_width_in_each_open_direction() {
2215        for open_direction in OPEN_DIRECTIONS {
2216            test_widgets(|tester| {
2217                let field_key = GlobalKey::new();
2218                let options_key = GlobalKey::new();
2219                let captured = Captured::<String>::new();
2220                tester.pump_widget(
2221                    TestWidgetsApp::new().home(
2222                        Padding::new(EdgeInsetsGeometry::symmetric(0.0, 32.0)).child(
2223                            Center::new().child(
2224                                string_autocomplete(&captured, &field_key, &options_key)
2225                                    .options_view_open_direction(open_direction),
2226                            ),
2227                        ),
2228                    ),
2229                );
2230
2231                expect(tester, &by_key(&field_key), finds_one_widget());
2232                expect(tester, &by_key(&options_key), finds_nothing());
2233
2234                tester.tap(find::by_type::<TestTextField>());
2235                tester.pump();
2236
2237                expect(tester, &by_key(&field_key), finds_one_widget());
2238                expect(tester, &by_key(&options_key), finds_one_widget());
2239
2240                let field_size = tester.get_size(by_key(&field_key));
2241                let options_size = tester.get_size(by_key(&options_key));
2242                assert_eq!(options_size.width(), field_size.width());
2243                let field_top = tester.get_top_left(by_key(&field_key)).dy();
2244                assert_eq!(
2245                    tester.get_top_left(by_key(&options_key)).dy(),
2246                    match open_direction {
2247                        OptionsViewOpenDirection::Down => field_top + field_size.height(),
2248                        OptionsViewOpenDirection::Up => field_top - options_size.height(),
2249                        OptionsViewOpenDirection::MostSpace => field_top + field_size.height(),
2250                    }
2251                );
2252            });
2253        }
2254    }
2255
2256    /// The options builder of the `User` cases: users whose `Display` form contains the text.
2257    fn user_options(_app: &mut App, value: TextEditingValue) -> Task<Vec<User>> {
2258        let query = value.text.to_lowercase();
2259        Task::ready(
2260            k_options_users()
2261                .into_iter()
2262                .filter(|option| option.to_string().contains(&query))
2263                .collect(),
2264        )
2265    }
2266
2267    #[test]
2268    fn can_filter_and_select_a_list_of_custom_user_options() {
2269        test_widgets(|tester| {
2270            let field_key = GlobalKey::new();
2271            let options_key = GlobalKey::new();
2272            let captured = Captured::<User>::new();
2273            let last_user_selected: Rc<RefCell<Option<User>>> = Rc::default();
2274            let selected = Rc::clone(&last_user_selected);
2275            tester.pump_widget(
2276                TestWidgetsApp::new().home(
2277                    RawAutocomplete::new(options_view(&captured, &options_key), user_options)
2278                        .on_selected(move |_app, user| *selected.borrow_mut() = Some(user))
2279                        .field_view_builder(field_view(&captured, &field_key)),
2280                ),
2281            );
2282
2283            expect(tester, &by_key(&field_key), finds_one_widget());
2284            expect(tester, &by_key(&options_key), finds_nothing());
2285
2286            // Enter text. The options are filtered by the text.
2287            let (focus_node, controller) = (captured.focus_node(), captured.controller());
2288            tester.update(|app| {
2289                focus_node.request_focus(app, None);
2290                controller.handle().set_value(app, value_at("example", 7));
2291            });
2292            tester.pump();
2293            expect(tester, &by_key(&field_key), finds_one_widget());
2294            expect(tester, &by_key(&options_key), finds_one_widget());
2295            let users = k_options_users();
2296            assert_eq!(captured.options(), vec![users[0].clone(), users[1].clone()]);
2297
2298            // Select an option. The options hide and onSelected is called.
2299            let selection = captured.options()[1].clone();
2300            let on_selected = captured.on_selected();
2301            tester.update(|app| on_selected(app, selection.clone()));
2302            tester.pump();
2303            expect(tester, &by_key(&field_key), finds_one_widget());
2304            expect(tester, &by_key(&options_key), finds_nothing());
2305            assert_eq!(last_user_selected.borrow().as_ref(), Some(&selection));
2306            assert_eq!(text_of(tester, &controller), selection.to_string());
2307
2308            // Modify the field text. The options appear again and are filtered, this time by
2309            // name instead of email.
2310            tester.update(|app| controller.handle().set_value(app, value_at("B", 1)));
2311            tester.pump();
2312            expect(tester, &by_key(&field_key), finds_one_widget());
2313            expect(tester, &by_key(&options_key), finds_one_widget());
2314            assert_eq!(captured.options(), vec![users[1].clone()]);
2315        });
2316    }
2317
2318    #[test]
2319    fn can_specify_a_custom_display_string_for_a_list_of_custom_user_options() {
2320        test_widgets(|tester| {
2321            let field_key = GlobalKey::new();
2322            let options_key = GlobalKey::new();
2323            let captured = Captured::<User>::new();
2324            let last_user_selected: Rc<RefCell<Option<User>>> = Rc::default();
2325            let selected = Rc::clone(&last_user_selected);
2326            tester.pump_widget(
2327                TestWidgetsApp::new().home(
2328                    RawAutocomplete::new(options_view(&captured, &options_key), user_options)
2329                        .display_string_for_option(|option: &User| option.name.to_string())
2330                        .on_selected(move |_app, user| *selected.borrow_mut() = Some(user))
2331                        .field_view_builder(field_view(&captured, &field_key)),
2332                ),
2333            );
2334
2335            expect(tester, &by_key(&field_key), finds_one_widget());
2336            expect(tester, &by_key(&options_key), finds_nothing());
2337
2338            // Enter text. The options are filtered by the text.
2339            let (focus_node, controller) = (captured.focus_node(), captured.controller());
2340            tester.update(|app| {
2341                focus_node.request_focus(app, None);
2342                controller.handle().set_value(app, value_at("example", 7));
2343            });
2344            tester.pump();
2345            expect(tester, &by_key(&field_key), finds_one_widget());
2346            expect(tester, &by_key(&options_key), finds_one_widget());
2347            let users = k_options_users();
2348            assert_eq!(captured.options(), vec![users[0].clone(), users[1].clone()]);
2349
2350            // Select an option. The options hide and onSelected is called. The field has its
2351            // text set to the selection's display string.
2352            let selection = captured.options()[1].clone();
2353            let on_selected = captured.on_selected();
2354            tester.update(|app| on_selected(app, selection.clone()));
2355            tester.pump();
2356            expect(tester, &by_key(&field_key), finds_one_widget());
2357            expect(tester, &by_key(&options_key), finds_nothing());
2358            assert_eq!(last_user_selected.borrow().as_ref(), Some(&selection));
2359            assert_eq!(text_of(tester, &controller), selection.name);
2360
2361            // Modify the field text. The options appear again and are filtered, this time by
2362            // name instead of email.
2363            tester.update(|app| controller.handle().set_value(app, value_at("B", 1)));
2364            tester.pump();
2365            expect(tester, &by_key(&field_key), finds_one_widget());
2366            expect(tester, &by_key(&options_key), finds_one_widget());
2367            assert_eq!(captured.options(), vec![users[1].clone()]);
2368        });
2369    }
2370
2371    #[test]
2372    fn on_field_submitted_selects_the_first_option() {
2373        test_widgets(|tester| {
2374            let field_key = GlobalKey::new();
2375            let options_key = GlobalKey::new();
2376            let captured = Captured::<String>::new();
2377            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
2378                &captured,
2379                &field_key,
2380                &options_key,
2381            )));
2382
2383            expect(tester, &by_key(&field_key), finds_one_widget());
2384            expect(tester, &by_key(&options_key), finds_nothing());
2385
2386            // Enter text. The options are filtered by the text.
2387            let (focus_node, controller) = (captured.focus_node(), captured.controller());
2388            tester.update(|app| {
2389                focus_node.request_focus(app, None);
2390                controller.handle().set_value(app, value_at("ele", 3));
2391            });
2392            tester.pump();
2393            expect(tester, &by_key(&field_key), finds_one_widget());
2394            expect(tester, &by_key(&options_key), finds_one_widget());
2395            assert_eq!(captured.options(), strings(&["chameleon", "elephant"]));
2396
2397            // Select the current string, as if the field was submitted. The options hide and
2398            // the field updates to show the selection.
2399            let on_field_submitted = captured.on_field_submitted.borrow().clone().expect("built");
2400            tester.update(|app| on_field_submitted(app));
2401            tester.pump();
2402            expect(tester, &by_key(&field_key), finds_one_widget());
2403            expect(tester, &by_key(&options_key), finds_nothing());
2404            assert_eq!(text_of(tester, &controller), captured.options()[0]);
2405        });
2406    }
2407
2408    /// The `optionsViewOpenDirection` group's autocomplete: one option `a`, shown as a text.
2409    fn one_option_autocomplete() -> RawAutocomplete<String> {
2410        RawAutocomplete::new(
2411            |_app, _context, _on_selected, _options: &[String]| Text::new("a").into_widget(),
2412            |_app, _value| Task::ready(strings(&["a"])),
2413        )
2414        .field_view_builder(
2415            |_app, _context, controller, focus_node, _on_field_submitted| {
2416                TestTextField::new()
2417                    .controller(controller)
2418                    .focus_node(focus_node)
2419                    .into_widget()
2420            },
2421        )
2422    }
2423
2424    #[test]
2425    fn options_view_open_direction_unset_opens_downward() {
2426        test_widgets(|tester| {
2427            tester.pump_widget(
2428                TestWidgetsApp::new().home(Center::new().child(one_option_autocomplete())),
2429            );
2430            tester.show_keyboard(find::by_type::<TestTextField>());
2431            tester.pump();
2432            assert_more_or_less_equals(
2433                tester.get_bottom_left(find::by_type::<TestTextField>()),
2434                tester.get_top_left(find::text("a")),
2435            );
2436        });
2437    }
2438
2439    #[test]
2440    fn options_view_open_direction_down_opens_downward() {
2441        test_widgets(|tester| {
2442            tester.pump_widget(
2443                TestWidgetsApp::new().home(
2444                    Center::new().child(
2445                        one_option_autocomplete()
2446                            .options_view_open_direction(OptionsViewOpenDirection::Down),
2447                    ),
2448                ),
2449            );
2450            tester.show_keyboard(find::by_type::<TestTextField>());
2451            tester.pump();
2452            assert_more_or_less_equals(
2453                tester.get_bottom_left(find::by_type::<TestTextField>()),
2454                tester.get_top_left(find::text("a")),
2455            );
2456        });
2457    }
2458
2459    #[test]
2460    fn options_view_open_direction_up_opens_upward() {
2461        test_widgets(|tester| {
2462            tester.pump_widget(TestWidgetsApp::new().home(Center::new().child(
2463                one_option_autocomplete().options_view_open_direction(OptionsViewOpenDirection::Up),
2464            )));
2465            tester.show_keyboard(find::by_type::<TestTextField>());
2466            tester.pump();
2467            assert_more_or_less_equals(
2468                tester.get_top_left(find::by_type::<TestTextField>()),
2469                tester.get_bottom_left(find::text("a")),
2470            );
2471        });
2472    }
2473
2474    #[test]
2475    fn options_view_open_direction_most_space_opens_in_the_direction_with_more_space() {
2476        test_widgets(|tester| {
2477            let field_key = GlobalKey::new();
2478            let options_key = GlobalKey::new();
2479            let setter: CapturedSetter = Rc::default();
2480            let alignment = Rc::new(Cell::new(AlignmentGeometry::TOP_CENTER));
2481
2482            let (stored, aligned) = (Rc::clone(&setter), Rc::clone(&alignment));
2483            let (field, options) = (field_key.clone(), options_key.clone());
2484            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
2485                move |_app, _context, set_state| {
2486                    *stored.borrow_mut() = Some(set_state);
2487                    let options = options.clone();
2488                    Align::new()
2489                        .alignment(aligned.get())
2490                        .child(
2491                            RawAutocomplete::new(
2492                                move |_app, _context, _on_selected, values: &[String]| {
2493                                    ListView::new()
2494                                        .key(options.clone().into())
2495                                        .children(
2496                                            values.iter().map(|value| {
2497                                                Text::new(value.clone()).into_widget()
2498                                            }),
2499                                        )
2500                                        .into_widget()
2501                                },
2502                                |_app, _value| Task::ready(strings(&["a", "b", "c"])),
2503                            )
2504                            .key(field.clone().into())
2505                            .options_view_open_direction(OptionsViewOpenDirection::MostSpace)
2506                            .field_view_builder(
2507                                |_app, _context, controller, focus_node, _on_field_submitted| {
2508                                    TestTextField::new()
2509                                        .controller(controller)
2510                                        .focus_node(focus_node)
2511                                        .into_widget()
2512                                },
2513                            ),
2514                        )
2515                        .into_widget()
2516                },
2517            )));
2518
2519            // Show the options. It should open downwards since there is more space.
2520            tester.tap(find::by_type::<TestTextField>());
2521            tester.pump();
2522
2523            assert_more_or_less_equals(
2524                tester.get_bottom_left(by_key(&field_key)),
2525                tester.get_top_left(by_key(&options_key)),
2526            );
2527
2528            // Move the field to the bottom.
2529            set_state(tester, &setter, || {
2530                alignment.set(AlignmentGeometry::BOTTOM_CENTER)
2531            });
2532            tester.pump();
2533
2534            // The options should now open upwards, since there is more space above.
2535            assert_more_or_less_equals(
2536                tester.get_top_left(by_key(&field_key)),
2537                tester.get_bottom_left(by_key(&options_key)),
2538            );
2539        });
2540    }
2541
2542    /// The `fieldViewBuilder not passed` cases' autocomplete over the case's own field.
2543    fn split_one_option_autocomplete(
2544        autocomplete_key: &GlobalKey,
2545        controller: &Ref<TextEditingController>,
2546        focus_node: &Ref<FocusNode>,
2547        open_direction: OptionsViewOpenDirection,
2548    ) -> WidgetRef {
2549        RawAutocomplete::new(
2550            |_app, _context, _on_selected, _options: &[String]| Text::new("a").into_widget(),
2551            |_app, _value| Task::ready(strings(&["a"])),
2552        )
2553        .key(autocomplete_key.clone().into())
2554        .text_editing_controller(controller.erase())
2555        .focus_node(focus_node.erase())
2556        .options_view_open_direction(open_direction)
2557        .into_widget()
2558    }
2559
2560    #[test]
2561    fn options_view_open_direction_down_without_a_field_view_builder() {
2562        test_widgets(|tester| {
2563            let autocomplete_key = GlobalKey::new();
2564            let (controller, focus_node) = own_field(tester);
2565            tester.pump_widget(
2566                TestWidgetsApp::new().home(
2567                    Column::new()
2568                        .cross_axis_alignment(waft_rendering::CrossAxisAlignment::Start)
2569                        .children([
2570                            TestTextField::new()
2571                                .controller(controller.erase())
2572                                .focus_node(focus_node.erase())
2573                                .into_widget(),
2574                            split_one_option_autocomplete(
2575                                &autocomplete_key,
2576                                &controller,
2577                                &focus_node,
2578                                OptionsViewOpenDirection::Down,
2579                            ),
2580                        ]),
2581                ),
2582            );
2583            tester.show_keyboard(find::by_type::<TestTextField>());
2584            tester.pump();
2585            assert_more_or_less_equals(
2586                tester.get_bottom_left(by_key(&autocomplete_key)),
2587                tester.get_top_left(find::text("a")),
2588            );
2589        });
2590    }
2591
2592    #[test]
2593    fn options_view_open_direction_up_without_a_field_view_builder() {
2594        test_widgets(|tester| {
2595            let autocomplete_key = GlobalKey::new();
2596            let (controller, focus_node) = own_field(tester);
2597            tester.pump_widget(
2598                TestWidgetsApp::new().home(
2599                    Column::new()
2600                        .main_axis_alignment(waft_rendering::MainAxisAlignment::End)
2601                        .cross_axis_alignment(waft_rendering::CrossAxisAlignment::Start)
2602                        .children([
2603                            split_one_option_autocomplete(
2604                                &autocomplete_key,
2605                                &controller,
2606                                &focus_node,
2607                                OptionsViewOpenDirection::Up,
2608                            ),
2609                            TestTextField::new()
2610                                .controller(controller.erase())
2611                                .focus_node(focus_node.erase())
2612                                .into_widget(),
2613                        ]),
2614                ),
2615            );
2616            tester.show_keyboard(find::by_type::<TestTextField>());
2617            tester.pump();
2618            assert_more_or_less_equals(
2619                tester.get_top_left(by_key(&autocomplete_key)),
2620                tester.get_bottom_left(find::text("a")),
2621            );
2622        });
2623    }
2624
2625    #[test]
2626    fn options_follow_field_when_it_moves() {
2627        test_widgets(|tester| {
2628            let field_key = GlobalKey::new();
2629            let options_key = GlobalKey::new();
2630            let setter: CapturedSetter = Rc::default();
2631            let alignment = Rc::new(Cell::new(AlignmentGeometry::CENTER));
2632            let captured = Captured::<String>::new();
2633
2634            let (stored, aligned, recorded) = (
2635                Rc::clone(&setter),
2636                Rc::clone(&alignment),
2637                Rc::clone(&captured),
2638            );
2639            let (field, options) = (field_key.clone(), options_key.clone());
2640            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
2641                move |_app, _context, set_state| {
2642                    *stored.borrow_mut() = Some(set_state);
2643                    Align::new()
2644                        .alignment(aligned.get())
2645                        .child(string_autocomplete(&recorded, &field, &options))
2646                        .into_widget()
2647                },
2648            )));
2649
2650            // Field is shown but not options.
2651            expect(tester, &by_key(&field_key), finds_one_widget());
2652            expect(tester, &by_key(&options_key), finds_nothing());
2653
2654            // Enter text to show the options.
2655            let (focus_node, controller) = (captured.focus_node(), captured.controller());
2656            tester.update(|app| {
2657                focus_node.request_focus(app, None);
2658                controller.handle().set_value(app, value_at("ele", 3));
2659            });
2660            tester.pump();
2661            expect(tester, &by_key(&field_key), finds_one_widget());
2662            expect(tester, &by_key(&options_key), finds_one_widget());
2663
2664            // Options are just below the field.
2665            let options_top_left = tester.get_top_left(by_key(&options_key));
2666            let field_offset = tester.get_top_left(by_key(&field_key));
2667            let field_size = tester.get_size(by_key(&field_key));
2668            assert_eq!(
2669                options_top_left.dy(),
2670                field_offset.dy() + field_size.height()
2671            );
2672
2673            // Move the field (similar to as if the keyboard opened). The options move to
2674            // follow the field.
2675            set_state(tester, &setter, || {
2676                alignment.set(AlignmentGeometry::TOP_CENTER)
2677            });
2678            tester.pump();
2679            let field_offset_frame1 = tester.get_top_left(by_key(&field_key));
2680            let options_top_left_open_frame1 = tester.get_top_left(by_key(&options_key));
2681
2682            assert!(field_offset_frame1.dy() < field_offset.dy());
2683            assert_ne!(options_top_left_open_frame1.dy(), options_top_left.dy());
2684            assert_eq!(
2685                options_top_left_open_frame1.dy(),
2686                field_offset_frame1.dy() + field_size.height()
2687            );
2688        });
2689    }
2690
2691    #[test]
2692    fn can_prevent_options_from_showing_by_returning_an_empty_iterable() {
2693        test_widgets(|tester| {
2694            let field_key = GlobalKey::new();
2695            let options_key = GlobalKey::new();
2696            let captured = Captured::<String>::new();
2697            tester.pump_widget(
2698                TestWidgetsApp::new().home(
2699                    RawAutocomplete::new(
2700                        options_view(&captured, &options_key),
2701                        |_app, value: TextEditingValue| {
2702                            if value.text.is_empty() {
2703                                return Task::ready(Vec::new());
2704                            }
2705                            Task::ready(matching(&value.text))
2706                        },
2707                    )
2708                    .field_view_builder(field_view(&captured, &field_key)),
2709                ),
2710            );
2711
2712            // The field is always rendered, but the options are not unless needed.
2713            expect(tester, &by_key(&field_key), finds_one_widget());
2714            expect(tester, &by_key(&options_key), finds_nothing());
2715
2716            // Focus the empty field. The options are not displayed because optionsBuilder
2717            // returns nothing for an empty field query.
2718            let (focus_node, controller) = (captured.focus_node(), captured.controller());
2719            tester.update(|app| {
2720                focus_node.request_focus(app, None);
2721                controller.handle().set_value(app, value_at("", 0));
2722            });
2723            tester.pump();
2724            expect(tester, &by_key(&options_key), finds_nothing());
2725
2726            // Enter text. Now the options appear, filtered by the text.
2727            tester.update(|app| controller.handle().set_value(app, value_at("ele", 3)));
2728            tester.pump();
2729            expect(tester, &by_key(&field_key), finds_one_widget());
2730            expect(tester, &by_key(&options_key), finds_one_widget());
2731            assert_eq!(captured.options(), strings(&["chameleon", "elephant"]));
2732        });
2733    }
2734
2735    #[test]
2736    fn can_create_a_field_outside_of_field_view_builder() {
2737        test_widgets(|tester| {
2738            let field_key = GlobalKey::new();
2739            let options_key = GlobalKey::new();
2740            let autocomplete_key = GlobalKey::new();
2741            let captured = Captured::<String>::new();
2742            let (text_editing_controller, focus_node) = own_field(tester);
2743
2744            let submitted_key = autocomplete_key.clone();
2745            tester.pump_widget(
2746                TestWidgetsApp::new().home(
2747                    Column::new().children([
2748                        // This is where the real field is being built.
2749                        TestTextField::new()
2750                            .key(&field_key)
2751                            .controller(text_editing_controller.erase())
2752                            .focus_node(focus_node.erase())
2753                            .on_submitted(move |app, _value| {
2754                                RawAutocomplete::<String>::on_field_submitted(app, &submitted_key)
2755                            })
2756                            .into_widget(),
2757                        Expanded::new(
2758                            RawAutocomplete::new(
2759                                options_view(&captured, &options_key),
2760                                string_options,
2761                            )
2762                            .key(autocomplete_key.clone().into())
2763                            .focus_node(focus_node.erase())
2764                            .text_editing_controller(text_editing_controller.erase()),
2765                        )
2766                        .into_widget(),
2767                    ]),
2768                ),
2769            );
2770
2771            expect(tester, &by_key(&field_key), finds_one_widget());
2772            expect(tester, &by_key(&options_key), finds_nothing());
2773
2774            // Enter text. The options are filtered by the text.
2775            let controller: TextEditingControllerRef = text_editing_controller.erase();
2776            tester.update(|app| {
2777                focus_of(&focus_node).request_focus(app, None);
2778                controller.handle().set_value(app, value_at("ele", 3));
2779            });
2780            tester.pump();
2781            expect(tester, &by_key(&field_key), finds_one_widget());
2782            expect(tester, &by_key(&options_key), finds_one_widget());
2783            assert_eq!(captured.options(), strings(&["chameleon", "elephant"]));
2784
2785            // Submit the field. The options hide and the field updates to show the selection.
2786            tester.show_keyboard(find::by_type::<TestTextField>());
2787            tester
2788                .test_text_input()
2789                .receive_action(TextInputAction::Done);
2790            tester.pump();
2791            expect(tester, &by_key(&field_key), finds_one_widget());
2792            expect(tester, &by_key(&options_key), finds_nothing());
2793            assert_eq!(text_of(tester, &controller), captured.options()[0]);
2794        });
2795    }
2796
2797    #[test]
2798    fn initial_value_sets_initial_text_field_value() {
2799        test_widgets(|tester| {
2800            let field_key = GlobalKey::new();
2801            let options_key = GlobalKey::new();
2802            let captured = Captured::<String>::new();
2803            tester.pump_widget(
2804                TestWidgetsApp::new().home(
2805                    string_autocomplete(&captured, &field_key, &options_key)
2806                        // Should initialize text field with 'lem'.
2807                        .initial_value(TextEditingValue::new().text("lem")),
2808                ),
2809            );
2810
2811            // The field is always rendered, but the options are not unless needed.
2812            expect(tester, &by_key(&field_key), finds_one_widget());
2813            expect(tester, &by_key(&options_key), finds_nothing());
2814            // The text editing controller value starts off with initialized value.
2815            let controller = captured.controller();
2816            assert_eq!(text_of(tester, &controller), "lem");
2817
2818            // Focus the empty field. All the options are displayed.
2819            let focus_node = captured.focus_node();
2820            tester.update(|app| focus_node.request_focus(app, None));
2821            tester.pump();
2822            expect(tester, &by_key(&options_key), finds_one_widget());
2823            assert_eq!(captured.options()[0], "lemur");
2824
2825            // Select an option. The options hide and the field updates to show the selection.
2826            let selection = captured.options()[0].clone();
2827            let on_selected = captured.on_selected();
2828            tester.update(|app| on_selected(app, selection.clone()));
2829            tester.pump();
2830            expect(tester, &by_key(&field_key), finds_one_widget());
2831            expect(tester, &by_key(&options_key), finds_nothing());
2832            assert_eq!(text_of(tester, &controller), selection);
2833        });
2834    }
2835
2836    #[test]
2837    #[should_panic(
2838        expected = "textEditingController and initialValue cannot be simultaneously defined."
2839    )]
2840    fn initial_value_cannot_be_defined_if_text_editing_controller_is_defined() {
2841        test_widgets(|tester| {
2842            let (text_editing_controller, focus_node) = own_field(tester);
2843            let field_controller: TextEditingControllerRef = text_editing_controller.erase();
2844            let field_focus_node: FocusNodeRef = focus_node.erase();
2845            RawAutocomplete::new(
2846                |_app, _context, _on_selected, _options: &[String]| Container::new().into_widget(),
2847                string_options,
2848            )
2849            .focus_node(focus_node.erase())
2850            // Both initialValue and textEditingController cannot be simultaneously defined.
2851            .initial_value(TextEditingValue::new().text("lemur"))
2852            .text_editing_controller(text_editing_controller.erase())
2853            .field_view_builder(
2854                move |_app, _context, _controller, _focus_node, _on_field_submitted| {
2855                    TestTextField::new()
2856                        .focus_node(field_focus_node.clone())
2857                        .controller(field_controller.clone())
2858                        .into_widget()
2859                },
2860            )
2861            .into_widget();
2862        });
2863    }
2864
2865    /// The `optionsBuilder` of the asynchronous cases: the matching options, after `delay`
2866    /// when one is set.
2867    fn delayed_options(
2868        delay: &Rc<Cell<Option<Duration>>>,
2869    ) -> impl Fn(&mut App, TextEditingValue) -> Task<Vec<String>> + 'static {
2870        let delay = Rc::clone(delay);
2871        move |app, value| {
2872            let options = matching(&value.text);
2873            match delay.get() {
2874                None => Task::ready(options),
2875                Some(delay) => delayed(app, delay, options),
2876            }
2877        }
2878    }
2879
2880    fn last_options(captured: &Captured<String>) -> Option<Vec<String>> {
2881        captured.last_options.borrow().clone()
2882    }
2883
2884    #[test]
2885    fn support_asynchronous_options_builder() {
2886        test_widgets(|tester| {
2887            let field_key = GlobalKey::new();
2888            let options_key = GlobalKey::new();
2889            let captured = Captured::<String>::new();
2890            let delay: Rc<Cell<Option<Duration>>> = Rc::default();
2891            tester.pump_widget(
2892                TestWidgetsApp::new().home(
2893                    RawAutocomplete::new(
2894                        options_view(&captured, &options_key),
2895                        delayed_options(&delay),
2896                    )
2897                    .field_view_builder(field_view(&captured, &field_key)),
2898                ),
2899            );
2900
2901            // Enter text to build the options with delay.
2902            let focus_node = captured.focus_node();
2903            tester.update(|app| {
2904                focus_node.request_focus(app, None);
2905                delay.set(Some(Duration::from_millis(500)));
2906            });
2907            tester.enter_text(by_key(&field_key), "go");
2908            tester.pump_and_settle();
2909
2910            // The options have not yet been built.
2911            expect(tester, &by_key(&options_key), finds_nothing());
2912            assert_eq!(last_options(&captured), None);
2913
2914            // Await asynchronous options builder.
2915            tester.pump_and_settle_by(Duration::from_millis(500));
2916            expect(tester, &by_key(&options_key), finds_one_widget());
2917            assert_eq!(
2918                last_options(&captured),
2919                Some(strings(&["dingo", "flamingo", "goose"]))
2920            );
2921
2922            // Enter text to rebuild the options without delay.
2923            delay.set(None);
2924            tester.enter_text(by_key(&field_key), "ngo");
2925            tester.pump();
2926            assert_eq!(
2927                last_options(&captured),
2928                Some(strings(&["dingo", "flamingo"]))
2929            );
2930        });
2931    }
2932
2933    #[test]
2934    fn can_navigate_options_with_the_arrow_keys() {
2935        test_widgets(|tester| {
2936            let field_key = GlobalKey::new();
2937            let options_key = GlobalKey::new();
2938            let captured = Captured::<String>::new();
2939            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
2940                &captured,
2941                &field_key,
2942                &options_key,
2943            )));
2944
2945            // Enter text. The options are filtered by the text.
2946            let (focus_node, controller) = (captured.focus_node(), captured.controller());
2947            tester.update(|app| focus_node.request_focus(app, None));
2948            tester.enter_text(by_key(&field_key), "ele");
2949            tester.pump_and_settle();
2950            expect(tester, &by_key(&field_key), finds_one_widget());
2951            expect(tester, &by_key(&options_key), finds_one_widget());
2952            assert_eq!(captured.options(), strings(&["chameleon", "elephant"]));
2953
2954            // Move the highlighted option to the second item 'elephant' and select it.
2955            arrow_down(tester);
2956            // Can't use the key event for enter to submit to the text field using the test
2957            // framework, so this appears to be the equivalent.
2958            tester
2959                .test_text_input()
2960                .receive_action(TextInputAction::Done);
2961            tester.pump();
2962            expect(tester, &by_key(&field_key), finds_one_widget());
2963            expect(tester, &by_key(&options_key), finds_nothing());
2964            assert_eq!(text_of(tester, &controller), "elephant");
2965
2966            // Modify the field text. The options appear again and are filtered.
2967            tester.update(|app| {
2968                focus_node.request_focus(app, None);
2969                controller.handle().clear(app);
2970            });
2971            tester.enter_text(by_key(&field_key), "e");
2972            tester.pump();
2973            expect(tester, &by_key(&field_key), finds_one_widget());
2974            expect(tester, &by_key(&options_key), finds_one_widget());
2975            assert_eq!(
2976                captured.options(),
2977                strings(&[
2978                    "chameleon",
2979                    "elephant",
2980                    "goose",
2981                    "lemur",
2982                    "mouse",
2983                    "northern white rhinoceros"
2984                ])
2985            );
2986
2987            // Selection does not wrap (going up).
2988            arrow_up(tester);
2989            tester.pump();
2990            assert_eq!(captured.last_highlighted.get(), 0);
2991            arrow_up(tester);
2992            tester.pump();
2993            assert_eq!(captured.last_highlighted.get(), 0);
2994
2995            // Selection does not wrap (going down).
2996            for expected in [1, 2, 3, 4, 5, 5] {
2997                arrow_down(tester);
2998                tester.pump();
2999                assert_eq!(captured.last_highlighted.get(), expected);
3000            }
3001        });
3002    }
3003
3004    #[test]
3005    fn can_jump_to_ends_with_keyboard() {
3006        test_widgets(|tester| {
3007            let field_key = GlobalKey::new();
3008            let options_key = GlobalKey::new();
3009            let captured = Captured::<String>::new();
3010            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
3011                &captured,
3012                &field_key,
3013                &options_key,
3014            )));
3015
3016            // Enter text. The options are filtered by the text.
3017            let (focus_node, controller) = (captured.focus_node(), captured.controller());
3018            tester.update(|app| {
3019                focus_node.request_focus(app, None);
3020                controller.handle().clear(app);
3021            });
3022            tester.enter_text(by_key(&field_key), "e");
3023            tester.pump();
3024            expect(tester, &by_key(&field_key), finds_one_widget());
3025            expect(tester, &by_key(&options_key), finds_one_widget());
3026            assert_eq!(
3027                captured.options(),
3028                strings(&[
3029                    "chameleon",
3030                    "elephant",
3031                    "goose",
3032                    "lemur",
3033                    "mouse",
3034                    "northern white rhinoceros",
3035                ])
3036            );
3037
3038            // Jump to the bottom.
3039            with_control(
3040                tester,
3041                PhysicalKeyboardKey::ARROW_DOWN,
3042                LogicalKeyboardKey::ARROW_DOWN,
3043            );
3044            tester.pump();
3045            assert_eq!(captured.last_highlighted.get(), 5);
3046
3047            // Doesn't wrap down.
3048            with_control(
3049                tester,
3050                PhysicalKeyboardKey::ARROW_DOWN,
3051                LogicalKeyboardKey::ARROW_DOWN,
3052            );
3053            tester.pump();
3054            assert_eq!(captured.last_highlighted.get(), 5);
3055
3056            // Jump to the top.
3057            with_control(
3058                tester,
3059                PhysicalKeyboardKey::ARROW_UP,
3060                LogicalKeyboardKey::ARROW_UP,
3061            );
3062            tester.pump();
3063            assert_eq!(captured.last_highlighted.get(), 0);
3064
3065            // Doesn't wrap up.
3066            with_control(
3067                tester,
3068                PhysicalKeyboardKey::ARROW_UP,
3069                LogicalKeyboardKey::ARROW_UP,
3070            );
3071            tester.pump();
3072            assert_eq!(captured.last_highlighted.get(), 0);
3073        });
3074    }
3075
3076    #[test]
3077    fn can_navigate_with_page_up_down_keys() {
3078        test_widgets(|tester| {
3079            let field_key = GlobalKey::new();
3080            let options_key = GlobalKey::new();
3081            let captured = Captured::<String>::new();
3082            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
3083                &captured,
3084                &field_key,
3085                &options_key,
3086            )));
3087
3088            // Enter text. The options are filtered by the text.
3089            let (focus_node, controller) = (captured.focus_node(), captured.controller());
3090            tester.update(|app| {
3091                focus_node.request_focus(app, None);
3092                controller.handle().clear(app);
3093            });
3094            tester.enter_text(by_key(&field_key), "e");
3095            tester.pump();
3096            expect(tester, &by_key(&field_key), finds_one_widget());
3097            expect(tester, &by_key(&options_key), finds_one_widget());
3098            assert_eq!(
3099                captured.options(),
3100                strings(&[
3101                    "chameleon",
3102                    "elephant",
3103                    "goose",
3104                    "lemur",
3105                    "mouse",
3106                    "northern white rhinoceros",
3107                ])
3108            );
3109
3110            // Jump down. Stops at the bottom and doesn't wrap.
3111            for expected in [4, 5, 5] {
3112                send_key(
3113                    tester,
3114                    PhysicalKeyboardKey::PAGE_DOWN,
3115                    LogicalKeyboardKey::PAGE_DOWN,
3116                );
3117                tester.pump();
3118                assert_eq!(captured.last_highlighted.get(), expected);
3119            }
3120
3121            // Jump to the bottom and then jump up a page.
3122            for expected in [1, 0, 0] {
3123                send_key(
3124                    tester,
3125                    PhysicalKeyboardKey::PAGE_UP,
3126                    LogicalKeyboardKey::PAGE_UP,
3127                );
3128                tester.pump();
3129                assert_eq!(captured.last_highlighted.get(), expected);
3130            }
3131        });
3132    }
3133
3134    #[test]
3135    fn can_hide_and_show_options_with_the_keyboard() {
3136        test_widgets(|tester| {
3137            let field_key = GlobalKey::new();
3138            let options_key = GlobalKey::new();
3139            let captured = Captured::<String>::new();
3140            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
3141                &captured,
3142                &field_key,
3143                &options_key,
3144            )));
3145
3146            // Enter text. The options are filtered by the text.
3147            let (focus_node, controller) = (captured.focus_node(), captured.controller());
3148            tester.update(|app| focus_node.request_focus(app, None));
3149            tester.enter_text(by_key(&field_key), "ele");
3150            tester.pump_and_settle();
3151            expect(tester, &by_key(&field_key), finds_one_widget());
3152            expect(tester, &by_key(&options_key), finds_one_widget());
3153            assert_eq!(captured.options(), strings(&["chameleon", "elephant"]));
3154
3155            // Hide the options.
3156            escape(tester);
3157            tester.pump();
3158            expect(tester, &by_key(&field_key), finds_one_widget());
3159            expect(tester, &by_key(&options_key), finds_nothing());
3160
3161            // Show the options again by pressing arrow keys.
3162            arrow_down(tester);
3163            tester.pump();
3164            expect(tester, &by_key(&options_key), finds_one_widget());
3165            escape(tester);
3166            tester.pump();
3167            expect(tester, &by_key(&options_key), finds_nothing());
3168            arrow_up(tester);
3169            tester.pump();
3170            expect(tester, &by_key(&options_key), finds_one_widget());
3171            escape(tester);
3172            tester.pump();
3173            expect(tester, &by_key(&options_key), finds_nothing());
3174
3175            // Show the options again by re-focusing the field.
3176            tester.update(|app| focus_node.unfocus(app, UnfocusDisposition::Scope));
3177            tester.pump();
3178            expect(tester, &by_key(&options_key), finds_nothing());
3179            tester.update(|app| focus_node.request_focus(app, None));
3180            tester.pump();
3181            expect(tester, &by_key(&options_key), finds_one_widget());
3182            escape(tester);
3183            tester.pump();
3184            expect(tester, &by_key(&options_key), finds_nothing());
3185
3186            // Show the options again by editing the text (but not when selecting text or
3187            // moving the caret).
3188            tester.enter_text(by_key(&field_key), "elep");
3189            tester.pump();
3190            expect(tester, &by_key(&options_key), finds_one_widget());
3191            escape(tester);
3192            tester.pump();
3193            expect(tester, &by_key(&options_key), finds_nothing());
3194            tester.update(|app| {
3195                controller
3196                    .handle()
3197                    .set_selection(app, TextSelection::collapsed(3, TextAffinity::Downstream))
3198            });
3199            tester.pump();
3200            expect(tester, &by_key(&options_key), finds_nothing());
3201        });
3202    }
3203
3204    #[test]
3205    fn re_invokes_dismiss_intent_if_options_not_shown() {
3206        test_widgets(|tester| {
3207            let field_key = GlobalKey::new();
3208            let options_key = GlobalKey::new();
3209            let captured = Captured::<String>::new();
3210            let wrapping_action_invoked = Rc::new(Cell::new(false));
3211            let invoked = Rc::clone(&wrapping_action_invoked);
3212            let dismiss = tester.update(|app| {
3213                CallbackAction::<DismissIntent>::new(
3214                    app,
3215                    Rc::new(move |_app, _intent| {
3216                        invoked.set(true);
3217                        None
3218                    }),
3219                )
3220            });
3221            tester.pump_widget(TestWidgetsApp::new().home(Actions::new(
3222                HashMap::from([(TypeId::of::<DismissIntent>(), dismiss.into_erased())]),
3223                string_autocomplete(&captured, &field_key, &options_key),
3224            )));
3225
3226            // Enter text to show options.
3227            let focus_node = captured.focus_node();
3228            tester.update(|app| focus_node.request_focus(app, None));
3229            tester.enter_text(by_key(&field_key), "ele");
3230            tester.pump_and_settle();
3231            expect(tester, &by_key(&field_key), finds_one_widget());
3232            expect(tester, &by_key(&options_key), finds_one_widget());
3233
3234            // Hide the options.
3235            escape(tester);
3236            tester.pump();
3237            expect(tester, &by_key(&field_key), finds_one_widget());
3238            expect(tester, &by_key(&options_key), finds_nothing());
3239            assert!(!wrapping_action_invoked.get());
3240
3241            // Ensure the wrapping Actions can receive the DismissIntent.
3242            escape(tester);
3243            assert!(wrapping_action_invoked.get());
3244        });
3245    }
3246
3247    #[test]
3248    fn options_view_builders_can_use_autocomplete_highlighted_option_to_highlight_selected_option()
3249    {
3250        test_widgets(|tester| {
3251            let field_key = GlobalKey::new();
3252            let options_key = GlobalKey::new();
3253            let captured = Captured::<String>::new();
3254            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
3255                &captured,
3256                &field_key,
3257                &options_key,
3258            )));
3259
3260            // Enter text. The options are filtered by the text.
3261            let focus_node = captured.focus_node();
3262            tester.update(|app| focus_node.request_focus(app, None));
3263            tester.enter_text(by_key(&field_key), "e");
3264            tester.pump();
3265            expect(tester, &by_key(&field_key), finds_one_widget());
3266            expect(tester, &by_key(&options_key), finds_one_widget());
3267            assert_eq!(
3268                captured.options(),
3269                strings(&[
3270                    "chameleon",
3271                    "elephant",
3272                    "goose",
3273                    "lemur",
3274                    "mouse",
3275                    "northern white rhinoceros",
3276                ])
3277            );
3278
3279            // Move the highlighted option down and check the highlighted index.
3280            assert_eq!(captured.last_highlighted.get(), 0);
3281            for expected in [1, 2, 3, 4, 5] {
3282                arrow_down(tester);
3283                tester.pump();
3284                assert_eq!(captured.last_highlighted.get(), expected);
3285            }
3286
3287            // And move it back up.
3288            for expected in [4, 3, 2, 1, 0] {
3289                arrow_up(tester);
3290                tester.pump();
3291                assert_eq!(captured.last_highlighted.get(), expected);
3292            }
3293
3294            // Arrow keys do not wrap.
3295            arrow_up(tester);
3296            tester.pump();
3297            assert_eq!(captured.last_highlighted.get(), 0);
3298        });
3299    }
3300
3301    #[test]
3302    fn floating_menu_goes_away_on_select() {
3303        // Regression test for https://github.com/flutter/flutter/issues/99749.
3304        test_widgets(|tester| {
3305            let field_key = GlobalKey::new();
3306            let options_key = GlobalKey::new();
3307            let captured = Captured::<String>::new();
3308            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
3309                &captured,
3310                &field_key,
3311                &options_key,
3312            )));
3313
3314            // The field is always rendered, but the options are not unless needed.
3315            expect(tester, &by_key(&field_key), finds_one_widget());
3316            expect(tester, &by_key(&options_key), finds_nothing());
3317
3318            tester.enter_text(by_key(&field_key), K_OPTIONS[0]);
3319            tester.pump_and_settle();
3320            expect(tester, &by_key(&options_key), finds_one_widget());
3321
3322            // Pretend that the only option is selected. This does not change the text in the
3323            // text field.
3324            let on_selected = captured.on_selected();
3325            tester.update(|app| on_selected(app, K_OPTIONS[0].to_string()));
3326            tester.pump();
3327            expect(tester, &by_key(&options_key), finds_nothing());
3328        });
3329    }
3330
3331    #[test]
3332    fn options_width_matches_field_width_after_rebuilding() {
3333        test_widgets(|tester| {
3334            let field_key = GlobalKey::new();
3335            let options_key = GlobalKey::new();
3336            let setter: CapturedSetter = Rc::default();
3337            let width = Rc::new(Cell::new(100.0));
3338            let captured = Captured::<String>::new();
3339
3340            let (stored, sized, recorded) =
3341                (Rc::clone(&setter), Rc::clone(&width), Rc::clone(&captured));
3342            let (field, options) = (field_key.clone(), options_key.clone());
3343            tester.pump_widget(TestWidgetsApp::new().home(
3344                Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
3345                    Padding::new(EdgeInsetsGeometry::symmetric(0.0, 32.0)).child(
3346                        StatefulBuilder::new(move |_app, _context, set_state| {
3347                            *stored.borrow_mut() = Some(set_state);
3348                            SizedBox::new()
3349                                .width(sized.get())
3350                                .child(string_autocomplete(&recorded, &field, &options))
3351                                .into_widget()
3352                        }),
3353                    ),
3354                ),
3355            ));
3356
3357            expect(tester, &by_key(&field_key), finds_one_widget());
3358            expect(tester, &by_key(&options_key), finds_nothing());
3359
3360            assert_eq!(tester.get_size(by_key(&field_key)).width(), 100.0);
3361
3362            tester.tap(find::by_type::<TestTextField>());
3363            tester.pump();
3364
3365            expect(tester, &by_key(&field_key), finds_one_widget());
3366            expect(tester, &by_key(&options_key), finds_one_widget());
3367
3368            assert_eq!(tester.get_size(by_key(&options_key)).width(), 100.0);
3369
3370            set_state(tester, &setter, || width.set(200.0));
3371            tester.pump();
3372
3373            // The options width changes to match the field width.
3374            assert_eq!(tester.get_size(by_key(&field_key)).width(), 200.0);
3375            assert_eq!(tester.get_size(by_key(&options_key)).width(), 200.0);
3376        });
3377    }
3378
3379    #[test]
3380    fn options_width_matches_field_width_after_changing() {
3381        test_widgets(|tester| {
3382            let field_key = GlobalKey::new();
3383            let options_key = GlobalKey::new();
3384            let setter: CapturedSetter = Rc::default();
3385            let width = Rc::new(Cell::new(100.0));
3386            let captured = Captured::<String>::new();
3387
3388            let (stored, sized) = (Rc::clone(&setter), Rc::clone(&width));
3389            let field = field_key.clone();
3390            let autocomplete =
3391                RawAutocomplete::new(options_view(&captured, &options_key), string_options)
3392                    .field_view_builder(
3393                        move |_app, _context, controller, focus_node, _on_submitted| {
3394                            let (stored, sized, field) =
3395                                (Rc::clone(&stored), Rc::clone(&sized), field.clone());
3396                            StatefulBuilder::new(move |_app, _context, set_state| {
3397                                *stored.borrow_mut() = Some(set_state);
3398                                SizedBox::new()
3399                                    .width(sized.get())
3400                                    .child(
3401                                        TestTextField::new()
3402                                            .key(&field)
3403                                            .focus_node(focus_node.clone())
3404                                            .controller(controller.clone()),
3405                                    )
3406                                    .into_widget()
3407                            })
3408                            .into_widget()
3409                        },
3410                    );
3411
3412            tester.pump_widget(TestWidgetsApp::new().home(
3413                Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
3414                    Padding::new(EdgeInsetsGeometry::symmetric(0.0, 32.0)).child(autocomplete),
3415                ),
3416            ));
3417
3418            expect(tester, &by_key(&field_key), finds_one_widget());
3419            expect(tester, &by_key(&options_key), finds_nothing());
3420
3421            assert_eq!(tester.get_size(by_key(&field_key)).width(), 100.0);
3422
3423            tester.tap(find::by_type::<TestTextField>());
3424            tester.pump();
3425
3426            expect(tester, &by_key(&field_key), finds_one_widget());
3427            expect(tester, &by_key(&options_key), finds_one_widget());
3428
3429            assert_eq!(tester.get_size(by_key(&field_key)).width(), 100.0);
3430            assert_eq!(tester.get_size(by_key(&options_key)).width(), 100.0);
3431
3432            set_state(tester, &setter, || width.set(200.0));
3433            tester.pump();
3434
3435            // The options width changes to match the field width.
3436            assert_eq!(tester.get_size(by_key(&field_key)).width(), 200.0);
3437            assert_eq!(tester.get_size(by_key(&options_key)).width(), 200.0);
3438        });
3439    }
3440
3441    /// The `screen size` group's `pumpRawAutocomplete`.
3442    fn pump_raw_autocomplete(
3443        tester: &mut WidgetTester,
3444        field_key: &GlobalKey,
3445        options_key: &GlobalKey,
3446        options_view_open_direction: OptionsViewOpenDirection,
3447        alignment: AlignmentGeometry,
3448    ) {
3449        let field_key = field_key.clone();
3450        tester.pump_widget(
3451            TestWidgetsApp::new().home(
3452                Padding::new(EdgeInsetsGeometry::symmetric(0.0, 32.0)).child(
3453                    Align::new().alignment(alignment).child(
3454                        RawAutocomplete::new(option_tiles(options_key), string_options)
3455                            .options_view_open_direction(options_view_open_direction)
3456                            .field_view_builder(
3457                                move |_app, _context, controller, focus_node, _on_submitted| {
3458                                    TestTextField::new()
3459                                        .key(&field_key)
3460                                        .focus_node(focus_node)
3461                                        .controller(controller)
3462                                        .into_widget()
3463                                },
3464                            ),
3465                    ),
3466                ),
3467            ),
3468        );
3469    }
3470
3471    /// Dart's `tester.view.physicalSize = size; tester.view.devicePixelRatio = 1.0;`.
3472    fn set_window_size(tester: &WidgetTester, size: Size) {
3473        tester.view().set_physical_size(size);
3474        tester.view().set_device_pixel_ratio(1.0);
3475    }
3476
3477    #[test]
3478    fn options_when_screen_changes_landscape_to_portrait() {
3479        test_widgets(|tester| {
3480            // Start with a portrait-sized window, with enough space for all of the options.
3481            let wide_window_size = Size::new(1920.0, 1080.0);
3482            set_window_size(tester, wide_window_size);
3483
3484            let field_key = GlobalKey::new();
3485            let options_key = GlobalKey::new();
3486
3487            pump_raw_autocomplete(
3488                tester,
3489                &field_key,
3490                &options_key,
3491                OptionsViewOpenDirection::Down,
3492                AlignmentGeometry::TOP_LEFT,
3493            );
3494
3495            expect(tester, &by_key(&field_key), finds_one_widget());
3496            expect(tester, &by_key(&options_key), finds_nothing());
3497
3498            tester.tap(find::by_type::<TestTextField>());
3499            tester.pump_and_settle();
3500
3501            expect(tester, &by_key(&field_key), finds_one_widget());
3502            expect(tester, &by_key(&options_key), finds_one_widget());
3503            expect(
3504                tester,
3505                &find::by_type::<OptionTile>(),
3506                finds_n_widgets(K_OPTIONS.len()),
3507            );
3508
3509            let field_size1 = tester.get_size(by_key(&field_key));
3510            let field_top_left1 = tester.get_top_left(by_key(&field_key));
3511            let options_top_left1 = tester.get_top_left(by_key(&options_key));
3512            assert_eq!(
3513                options_top_left1,
3514                Offset::new(
3515                    field_top_left1.dx(),
3516                    field_top_left1.dy() + field_size1.height()
3517                )
3518            );
3519            let options_bottom_right1 = tester.get_bottom_right(by_key(&options_key));
3520            let option_height = tester
3521                .get_size(find::by_type::<OptionTile>().first())
3522                .height();
3523            assert_eq!(
3524                options_bottom_right1,
3525                Offset::new(
3526                    field_top_left1.dx() + field_size1.width(),
3527                    field_top_left1.dy()
3528                        + field_size1.height()
3529                        + option_height * K_OPTIONS.len() as f64
3530                )
3531            );
3532
3533            // Change the screen size to portrait.
3534            let narrow_window_size = Size::new(1070.0, 1770.0);
3535            set_window_size(tester, narrow_window_size);
3536            tester.pump_and_settle();
3537
3538            expect(tester, &by_key(&field_key), finds_one_widget());
3539            expect(
3540                tester,
3541                &find::by_type::<OptionTile>(),
3542                finds_n_widgets(K_OPTIONS.len()),
3543            );
3544            assert_eq!(tester.get_top_left(by_key(&options_key)), options_top_left1);
3545            let field_size2 = tester.get_size(by_key(&field_key));
3546            assert!(field_size1.width() > field_size2.width());
3547            assert_eq!(field_size1.height(), field_size2.height());
3548            let options_bottom_right2 = tester.get_bottom_right(by_key(&options_key));
3549            let field_top_left2 = tester.get_top_left(by_key(&field_key));
3550            assert!(options_bottom_right2.dx() < options_bottom_right1.dx());
3551            assert_eq!(options_bottom_right2.dy(), options_bottom_right1.dy());
3552            assert_eq!(
3553                options_bottom_right2,
3554                Offset::new(
3555                    field_top_left2.dx() + field_size2.width(),
3556                    field_top_left2.dy()
3557                        + field_size2.height()
3558                        + option_height * K_OPTIONS.len() as f64
3559                )
3560            );
3561        });
3562    }
3563
3564    #[test]
3565    fn options_when_screen_changes_portrait_to_landscape_and_overflows() {
3566        test_widgets(|tester| {
3567            // Start with a portrait-sized window, with enough space for all of the options.
3568            let narrow_window_size = Size::new(1070.0, 1770.0);
3569            set_window_size(tester, narrow_window_size);
3570
3571            let field_key = GlobalKey::new();
3572            let options_key = GlobalKey::new();
3573
3574            pump_raw_autocomplete(
3575                tester,
3576                &field_key,
3577                &options_key,
3578                OptionsViewOpenDirection::Down,
3579                AlignmentGeometry::TOP_LEFT,
3580            );
3581
3582            expect(tester, &by_key(&field_key), finds_one_widget());
3583            expect(tester, &by_key(&options_key), finds_nothing());
3584
3585            tester.tap(find::by_type::<TestTextField>());
3586            tester.pump_and_settle();
3587
3588            expect(tester, &by_key(&field_key), finds_one_widget());
3589            expect(tester, &by_key(&options_key), finds_one_widget());
3590            expect(
3591                tester,
3592                &find::by_type::<OptionTile>(),
3593                finds_n_widgets(K_OPTIONS.len()),
3594            );
3595
3596            let field_size1 = tester.get_size(by_key(&field_key));
3597            let field_top_left1 = tester.get_top_left(by_key(&field_key));
3598            let options_top_left1 = tester.get_top_left(by_key(&options_key));
3599            assert_eq!(
3600                options_top_left1,
3601                Offset::new(
3602                    field_top_left1.dx(),
3603                    field_top_left1.dy() + field_size1.height()
3604                )
3605            );
3606            let options_bottom_right1 = tester.get_bottom_right(by_key(&options_key));
3607            let option_height = tester
3608                .get_size(find::by_type::<OptionTile>().first())
3609                .height();
3610            assert_eq!(
3611                options_bottom_right1,
3612                Offset::new(
3613                    field_top_left1.dx() + field_size1.width(),
3614                    field_top_left1.dy()
3615                        + field_size1.height()
3616                        + option_height * K_OPTIONS.len() as f64
3617                )
3618            );
3619
3620            // Change the screen size to landscape where the options can't all fit on the
3621            // screen.
3622            let wide_window_size = Size::new(1920.0, 580.0);
3623            set_window_size(tester, wide_window_size);
3624            tester.pump_and_settle();
3625            expect(tester, &by_key(&field_key), finds_one_widget());
3626
3627            let visible_options = (wide_window_size.height() / option_height).floor() as usize;
3628            assert!(visible_options < K_OPTIONS.len());
3629            expect(
3630                tester,
3631                &find::by_type::<OptionTile>(),
3632                finds_n_widgets(visible_options),
3633            );
3634            assert_eq!(tester.get_top_left(by_key(&options_key)), options_top_left1);
3635            let field_size2 = tester.get_size(by_key(&field_key));
3636            assert!(field_size1.width() < field_size2.width());
3637            assert_eq!(field_size1.height(), field_size2.height());
3638            let options_bottom_right2 = tester.get_bottom_right(by_key(&options_key));
3639            let field_top_left2 = tester.get_top_left(by_key(&field_key));
3640            assert!(options_bottom_right2.dx() > options_bottom_right1.dx());
3641            assert!(options_bottom_right2.dy() < options_bottom_right1.dy());
3642            assert_eq!(
3643                options_bottom_right2,
3644                Offset::new(
3645                    field_top_left2.dx() + field_size2.width(),
3646                    // Options are taking all available space below the field.
3647                    wide_window_size.height()
3648                )
3649            );
3650        });
3651    }
3652
3653    #[test]
3654    fn screen_changes_portrait_to_landscape_and_overflows() {
3655        test_widgets(|tester| {
3656            // Start with a portrait-sized window, with enough space for all of the options.
3657            let narrow_window_size = Size::new(1070.0, 1770.0);
3658            set_window_size(tester, narrow_window_size);
3659
3660            let field_key = GlobalKey::new();
3661            let options_key = GlobalKey::new();
3662
3663            pump_raw_autocomplete(
3664                tester,
3665                &field_key,
3666                &options_key,
3667                OptionsViewOpenDirection::Down,
3668                AlignmentGeometry::TOP_LEFT,
3669            );
3670
3671            expect(tester, &by_key(&field_key), finds_one_widget());
3672            expect(tester, &by_key(&options_key), finds_nothing());
3673
3674            tester.tap(find::by_type::<TestTextField>());
3675            tester.pump_and_settle();
3676            expect(tester, &by_key(&field_key), finds_one_widget());
3677            expect(tester, &by_key(&options_key), finds_one_widget());
3678
3679            let option_height = tester
3680                .get_size(find::by_type::<OptionTile>().first())
3681                .height();
3682            let options_height1 = tester.get_size(by_key(&options_key)).height();
3683            let visible_options1 = (options_height1 / option_height).ceil() as usize;
3684            expect(
3685                tester,
3686                &find::by_type::<OptionTile>(),
3687                finds_n_widgets(visible_options1),
3688            );
3689            let field_size1 = tester.get_size(by_key(&field_key));
3690            let options_top_left1 = tester.get_top_left(by_key(&options_key));
3691            let field_top_left1 = tester.get_top_left(by_key(&field_key));
3692            assert_eq!(
3693                options_top_left1,
3694                Offset::new(
3695                    field_top_left1.dx(),
3696                    field_top_left1.dy() + field_size1.height()
3697                )
3698            );
3699            let options_bottom_right1 = tester.get_bottom_right(by_key(&options_key));
3700            assert_eq!(
3701                options_bottom_right1,
3702                Offset::new(
3703                    field_top_left1.dx() + field_size1.width(),
3704                    field_top_left1.dy() + field_size1.height() + options_height1
3705                )
3706            );
3707
3708            // Change the screen size to landscape where the options can't all fit on the
3709            // screen.
3710            let wide_window_size = Size::new(1920.0, 580.0);
3711            set_window_size(tester, wide_window_size);
3712            tester.pump_and_settle();
3713            expect(tester, &by_key(&field_key), finds_one_widget());
3714
3715            let options_height2 = tester.get_size(by_key(&options_key)).height();
3716            let visible_options2 = (options_height2 / option_height).ceil() as usize;
3717            assert!(visible_options2 < K_OPTIONS.len());
3718            expect(
3719                tester,
3720                &find::by_type::<OptionTile>(),
3721                finds_n_widgets(visible_options2),
3722            );
3723            let options_top_left2 = tester.get_top_left(by_key(&options_key));
3724            assert_eq!(options_top_left2, options_top_left1);
3725            let field_size2 = tester.get_size(by_key(&field_key));
3726            assert!(field_size1.width() < field_size2.width());
3727            assert_eq!(field_size1.height(), field_size2.height());
3728            let options_bottom_right2 = tester.get_bottom_right(by_key(&options_key));
3729            let field_top_left2 = tester.get_top_left(by_key(&field_key));
3730            assert!(options_bottom_right2.dx() > options_bottom_right1.dx());
3731            assert_eq!(
3732                options_bottom_right2,
3733                Offset::new(
3734                    field_top_left2.dx() + field_size2.width(),
3735                    // Options are taking all available space below the field.
3736                    wide_window_size.height()
3737                )
3738            );
3739
3740            // Shrink the screen further so that the options become smaller than
3741            // kMinInteractiveDimension and move to overlap the field.
3742            let short_window_size = Size::new(1920.0, 48.0);
3743            set_window_size(tester, short_window_size);
3744            tester.pump_and_settle();
3745            expect(tester, &by_key(&field_key), finds_one_widget());
3746
3747            const VISIBLE_OPTIONS3: usize = 1;
3748            expect(
3749                tester,
3750                &find::by_type::<OptionTile>(),
3751                finds_n_widgets(VISIBLE_OPTIONS3),
3752            );
3753            let options_top_left3 = tester.get_top_left(by_key(&options_key));
3754            assert_eq!(options_top_left3.dx(), options_top_left1.dx());
3755            // The options have moved up, overlapping the field, to still be able to show
3756            // kMinInteractiveDimension.
3757            assert!(options_top_left3.dy() < options_top_left1.dy());
3758            let field_size3 = tester.get_size(by_key(&field_key));
3759            let field_top_left3 = tester.get_top_left(by_key(&field_key));
3760            assert!(options_top_left3.dy() < field_top_left3.dy() + field_size3.height());
3761            assert_eq!(field_size3.width(), field_size2.width());
3762            assert_eq!(field_size1.height(), field_size3.height());
3763            let options_bottom_right3 = tester.get_bottom_right(by_key(&options_key));
3764            assert!(options_bottom_right3.dx() > options_bottom_right1.dx());
3765            assert_eq!(
3766                options_bottom_right3,
3767                Offset::new(
3768                    field_top_left3.dx() + field_size3.width(),
3769                    short_window_size.height()
3770                )
3771            );
3772        });
3773    }
3774
3775    #[test]
3776    fn when_opening_up_screen_changes_portrait_to_landscape_and_overflows() {
3777        test_widgets(|tester| {
3778            // Start with a portrait-sized window, with enough space for all of the options.
3779            let narrow_window_size = Size::new(1070.0, 1770.0);
3780            set_window_size(tester, narrow_window_size);
3781
3782            let field_key = GlobalKey::new();
3783            let options_key = GlobalKey::new();
3784
3785            pump_raw_autocomplete(
3786                tester,
3787                &field_key,
3788                &options_key,
3789                OptionsViewOpenDirection::Up,
3790                AlignmentGeometry::CENTER,
3791            );
3792
3793            expect(tester, &by_key(&field_key), finds_one_widget());
3794            expect(tester, &by_key(&options_key), finds_nothing());
3795
3796            tester.tap(find::by_type::<TestTextField>());
3797            tester.pump_and_settle();
3798            expect(tester, &by_key(&field_key), finds_one_widget());
3799            expect(tester, &by_key(&options_key), finds_one_widget());
3800
3801            let option_height = tester
3802                .get_size(find::by_type::<OptionTile>().first())
3803                .height();
3804            let options_height1 = tester.get_size(by_key(&options_key)).height();
3805            let visible_options1 = (options_height1 / option_height).ceil() as usize;
3806            expect(
3807                tester,
3808                &find::by_type::<OptionTile>(),
3809                finds_n_widgets(visible_options1),
3810            );
3811            let field_size1 = tester.get_size(by_key(&field_key));
3812            let options_top_left1 = tester.get_top_left(by_key(&options_key));
3813            let field_top_left1 = tester.get_top_left(by_key(&field_key));
3814            assert_eq!(
3815                options_top_left1,
3816                Offset::new(field_top_left1.dx(), field_top_left1.dy() - options_height1)
3817            );
3818            assert!(options_top_left1.dy() > 0.0);
3819            let options_bottom_right1 = tester.get_bottom_right(by_key(&options_key));
3820            assert_eq!(
3821                options_bottom_right1,
3822                Offset::new(
3823                    field_top_left1.dx() + field_size1.width(),
3824                    field_top_left1.dy()
3825                )
3826            );
3827
3828            // Change the screen size to landscape where the options can't all fit on the
3829            // screen.
3830            let wide_window_size = Size::new(1920.0, 580.0);
3831            set_window_size(tester, wide_window_size);
3832            tester.pump_and_settle();
3833            expect(tester, &by_key(&field_key), finds_one_widget());
3834
3835            let options_height2 = tester.get_size(by_key(&options_key)).height();
3836            assert!(options_height2 < options_height1);
3837            let visible_options2 = (options_height2 / option_height).ceil() as usize;
3838            assert!(visible_options2 < visible_options1);
3839            expect(
3840                tester,
3841                &find::by_type::<OptionTile>(),
3842                finds_n_widgets(visible_options2),
3843            );
3844            let options_top_left2 = tester.get_top_left(by_key(&options_key));
3845            let field_top_left2 = tester.get_top_left(by_key(&field_key));
3846            assert_eq!(
3847                options_top_left2,
3848                Offset::new(
3849                    options_top_left1.dx(),
3850                    field_top_left2.dy() - options_height2
3851                )
3852            );
3853            let field_size2 = tester.get_size(by_key(&field_key));
3854            assert!(field_size1.width() < field_size2.width());
3855            assert_eq!(field_size1.height(), field_size2.height());
3856            let options_bottom_right2 = tester.get_bottom_right(by_key(&options_key));
3857            assert!(options_bottom_right2.dx() > options_bottom_right1.dx());
3858            assert_eq!(
3859                options_bottom_right2,
3860                Offset::new(
3861                    field_top_left2.dx() + field_size2.width(),
3862                    field_top_left2.dy()
3863                )
3864            );
3865
3866            // Shrink the screen further so that the options become smaller than
3867            // kMinInteractiveDimension and move to overlap the field.
3868            let short_window_size = Size::new(1920.0, 90.0);
3869            set_window_size(tester, short_window_size);
3870            tester.pump_and_settle();
3871
3872            expect(tester, &by_key(&field_key), finds_one_widget());
3873            const VISIBLE_OPTIONS3: usize = 1;
3874            expect(
3875                tester,
3876                &find::by_type::<OptionTile>(),
3877                finds_n_widgets(VISIBLE_OPTIONS3),
3878            );
3879            let options_top_left3 = tester.get_top_left(by_key(&options_key));
3880            assert_eq!(options_top_left3.dx(), options_top_left1.dx());
3881            // The options have moved down, overlapping the field, to still be able to show
3882            // kMinInteractiveDimension.
3883            assert!(options_top_left3.dy() < options_top_left1.dy());
3884            let field_size3 = tester.get_size(by_key(&field_key));
3885            let field_top_left3 = tester.get_top_left(by_key(&field_key));
3886            assert!(options_top_left3.dy() < field_top_left3.dy() + field_size3.height());
3887            assert_eq!(field_size3.width(), field_size2.width());
3888            assert_eq!(field_size1.height(), field_size3.height());
3889            let options_bottom_right3 = tester.get_bottom_right(by_key(&options_key));
3890            assert!(options_bottom_right3.dx() > options_bottom_right1.dx());
3891            assert!(options_bottom_right3.dy() > field_top_left3.dy());
3892            assert_eq!(
3893                options_bottom_right3.dx(),
3894                field_top_left3.dx() + field_size3.width()
3895            );
3896        });
3897    }
3898
3899    #[test]
3900    fn can_prevent_older_options_builder_results_from_replacing_the_new_ones() {
3901        test_widgets(|tester| {
3902            let field_key = GlobalKey::new();
3903            let options_key = GlobalKey::new();
3904            let captured = Captured::<String>::new();
3905            let delay: Rc<Cell<Option<Duration>>> = Rc::default();
3906            tester.pump_widget(
3907                TestWidgetsApp::new().home(
3908                    RawAutocomplete::new(
3909                        options_view(&captured, &options_key),
3910                        delayed_options(&delay),
3911                    )
3912                    .field_view_builder(field_view(&captured, &field_key)),
3913                ),
3914            );
3915
3916            let long_request_delay = Duration::from_millis(5000);
3917            let short_request_delay = Duration::from_millis(1000);
3918            let focus_node = captured.focus_node();
3919            tester.update(|app| {
3920                focus_node.request_focus(app, None);
3921
3922                // Enter the first letter.
3923                delay.set(Some(long_request_delay));
3924            });
3925            tester.enter_text(by_key(&field_key), "c");
3926            tester.pump();
3927            assert_eq!(last_options(&captured), None);
3928
3929            // Enter the second letter which resolves faster.
3930            delay.set(Some(short_request_delay));
3931            tester.enter_text(by_key(&field_key), "ch");
3932            tester.pump();
3933            assert_eq!(last_options(&captured), None);
3934
3935            // Wait for the short request to resolve.
3936            tester.pump_by(short_request_delay);
3937
3938            // lastOptions must contain results from the last request.
3939            expect(tester, &by_key(&options_key), finds_one_widget());
3940            assert_eq!(last_options(&captured), Some(strings(&["chameleon"])));
3941
3942            // Wait for the last timer to finish.
3943            tester.pump_by(long_request_delay - short_request_delay);
3944            assert_eq!(last_options(&captured), Some(strings(&["chameleon"])));
3945        });
3946    }
3947
3948    #[test]
3949    fn updates_result_only_from_the_last_call_made_to_options_builder() {
3950        test_widgets(|tester| {
3951            let field_key = GlobalKey::new();
3952            let options_key = GlobalKey::new();
3953            let captured = Captured::<String>::new();
3954            let delay: Rc<Cell<Option<Duration>>> = Rc::default();
3955            tester.pump_widget(
3956                TestWidgetsApp::new().home(
3957                    RawAutocomplete::new(
3958                        options_view(&captured, &options_key),
3959                        delayed_options(&delay),
3960                    )
3961                    .field_view_builder(field_view(&captured, &field_key)),
3962                ),
3963            );
3964
3965            let focus_node = captured.focus_node();
3966            let first_request_delay = Duration::from_millis(1000);
3967            let second_request_delay = Duration::from_millis(2000);
3968            let third_request_delay = Duration::from_millis(3000);
3969            tester.update(|app| {
3970                focus_node.request_focus(app, None);
3971
3972                // Enter the first letter.
3973                delay.set(Some(first_request_delay));
3974            });
3975            tester.enter_text(by_key(&field_key), "l");
3976            tester.pump();
3977            assert_eq!(last_options(&captured), None);
3978
3979            // Enter the second letter which resolves slower.
3980            delay.set(Some(second_request_delay));
3981            tester.enter_text(by_key(&field_key), "le");
3982            tester.pump();
3983            assert_eq!(last_options(&captured), None);
3984
3985            // Enter the third letter which resolves the slowest.
3986            delay.set(Some(third_request_delay));
3987            tester.enter_text(by_key(&field_key), "lem");
3988            tester.pump();
3989            assert_eq!(last_options(&captured), None);
3990
3991            // lastOptions should get updated only from the last request.
3992            tester.pump_by(first_request_delay);
3993            expect(tester, &by_key(&options_key), finds_nothing());
3994            assert_eq!(last_options(&captured), None);
3995
3996            tester.pump_by(second_request_delay - first_request_delay);
3997            expect(tester, &by_key(&options_key), finds_nothing());
3998            assert_eq!(last_options(&captured), None);
3999
4000            tester.pump_by(third_request_delay - second_request_delay);
4001            expect(tester, &by_key(&options_key), finds_one_widget());
4002            assert_eq!(last_options(&captured), Some(strings(&["lemur"])));
4003        });
4004    }
4005
4006    #[test]
4007    fn update_options_view_when_field_input_changes_return_to_the_starting_keyword() {
4008        test_widgets(|tester| {
4009            let field_key = GlobalKey::new();
4010            let options_key = GlobalKey::new();
4011            let captured = Captured::<String>::new();
4012            let delay = Duration::from_millis(100);
4013            tester.pump_widget(
4014                TestWidgetsApp::new().home(
4015                    RawAutocomplete::new(
4016                        options_view(&captured, &options_key),
4017                        move |app, value: TextEditingValue| {
4018                            delayed(app, delay, matching(&value.text))
4019                        },
4020                    )
4021                    .field_view_builder(field_view(&captured, &field_key)),
4022                ),
4023            );
4024
4025            // Setup starting point.
4026            tester.enter_text(by_key(&field_key), "ele");
4027            tester.pump_by(delay);
4028            assert_eq!(
4029                last_options(&captured),
4030                Some(strings(&["chameleon", "elephant"]))
4031            );
4032            expect(tester, &by_key(&options_key), finds_one_widget());
4033
4034            // Hide options.
4035            escape(tester);
4036            tester.pump();
4037            expect(tester, &by_key(&options_key), finds_nothing());
4038
4039            // Enter another letter and then immediately erase it.
4040            tester.enter_text(by_key(&field_key), "eleo");
4041            tester.pump();
4042            expect(tester, &by_key(&options_key), finds_nothing());
4043
4044            tester.enter_text(by_key(&field_key), "ele");
4045            tester.pump_by(delay);
4046            assert_eq!(
4047                last_options(&captured),
4048                Some(strings(&["chameleon", "elephant"]))
4049            );
4050
4051            // Options dropdown should be visible after the last optionsBuilder call is
4052            // resolved.
4053            expect(tester, &by_key(&options_key), finds_one_widget());
4054        });
4055    }
4056
4057    #[test]
4058    fn options_builder_does_not_have_to_be_a_pure_function() {
4059        test_widgets(|tester| {
4060            let field_key = GlobalKey::new();
4061            let options_key = GlobalKey::new();
4062            let captured = Captured::<String>::new();
4063            let delay = Duration::from_millis(100);
4064
4065            // This is used to tell optionsBuilder to return something different after being
4066            // called with "ele" the second time. I.e. it is not a pure function.
4067            let times_options_builder_called_with_ele = Rc::new(Cell::new(0));
4068            let alt_ele_options = strings(&["something new and crazy for ele!"]);
4069
4070            let (times, alt) = (
4071                Rc::clone(&times_options_builder_called_with_ele),
4072                alt_ele_options.clone(),
4073            );
4074            tester.pump_widget(
4075                TestWidgetsApp::new().home(
4076                    RawAutocomplete::new(
4077                        options_view(&captured, &options_key),
4078                        move |app, value: TextEditingValue| {
4079                            if value.text == "ele" {
4080                                times.set(times.get() + 1);
4081                                if times.get() > 1 {
4082                                    return delayed(app, delay, alt.clone());
4083                                }
4084                            }
4085                            delayed(app, delay, matching(&value.text))
4086                        },
4087                    )
4088                    .field_view_builder(field_view(&captured, &field_key)),
4089                ),
4090            );
4091
4092            tester.enter_text(by_key(&field_key), "ele");
4093            tester.pump_by(delay);
4094            assert_eq!(
4095                last_options(&captured),
4096                Some(strings(&["chameleon", "elephant"]))
4097            );
4098            expect(tester, &by_key(&options_key), finds_one_widget());
4099
4100            escape(tester);
4101            tester.pump();
4102            expect(tester, &by_key(&options_key), finds_nothing());
4103
4104            tester.enter_text(by_key(&field_key), "eleo");
4105            tester.pump();
4106            expect(tester, &by_key(&options_key), finds_nothing());
4107
4108            tester.enter_text(by_key(&field_key), "ele");
4109            tester.pump_by(delay);
4110            assert_eq!(last_options(&captured), Some(alt_ele_options));
4111            expect(tester, &by_key(&options_key), finds_one_widget());
4112        });
4113    }
4114
4115    #[test]
4116    fn raw_autocomplete_renders_at_zero_area() {
4117        test_widgets(|tester| {
4118            tester.pump_widget(
4119                TestWidgetsApp::new().home(
4120                    Center::new().child(
4121                        SizedBox::shrink().child(
4122                            RawAutocomplete::new(
4123                                |_app, _context, _on_selected, _options: &[String]| {
4124                                    Container::new().into_widget()
4125                                },
4126                                |_app, _value| Task::ready(strings(&["Y"])),
4127                            )
4128                            .initial_value(TextEditingValue::new().text("X"))
4129                            .field_view_builder(
4130                                |_app, _context, controller, _focus_node, _on_submitted| {
4131                                    TestTextField::new().controller(controller).into_widget()
4132                                },
4133                            ),
4134                        ),
4135                    ),
4136                ),
4137            );
4138            let x_text = find::text("X");
4139            assert!(tester.get_size(x_text).is_empty());
4140        });
4141    }
4142
4143    #[test]
4144    fn floating_menu_is_displayed_when_the_field_is_focused_and_already_has_a_selected_value() {
4145        // Regression test for https://github.com/flutter/flutter/issues/177429.
4146        test_widgets(|tester| {
4147            let field_key = GlobalKey::new();
4148            let options_key = GlobalKey::new();
4149            let captured = Captured::<String>::new();
4150            tester.pump_widget(TestWidgetsApp::new().home(string_autocomplete(
4151                &captured,
4152                &field_key,
4153                &options_key,
4154            )));
4155
4156            // The field is always rendered, but the options are not unless needed.
4157            expect(tester, &by_key(&field_key), finds_one_widget());
4158            expect(tester, &by_key(&options_key), finds_nothing());
4159
4160            tester.enter_text(by_key(&field_key), K_OPTIONS[0]);
4161            tester.pump_and_settle();
4162            expect(tester, &by_key(&options_key), finds_one_widget());
4163
4164            let on_selected = captured.on_selected();
4165            tester.update(|app| on_selected(app, K_OPTIONS[0].to_string()));
4166            tester.pump();
4167            expect(tester, &by_key(&options_key), finds_nothing());
4168
4169            let focus_node = captured.focus_node();
4170            tester.update(|app| focus_node.unfocus(app, UnfocusDisposition::Scope));
4171            tester.pump();
4172            tester.update(|app| focus_node.request_focus(app, None));
4173            tester.pump_and_settle();
4174
4175            expect(tester, &by_key(&options_key), finds_one_widget());
4176        });
4177    }
4178
4179    // Regression test for https://github.com/flutter/flutter/issues/170403.
4180    #[test]
4181    fn does_not_crash_when_disposed_during_async_options_builder() {
4182        test_widgets(|tester| {
4183            let options_completer: Completer<Vec<String>> = Completer::new();
4184            let setter: CapturedSetter = Rc::default();
4185            let show_autocomplete = Rc::new(Cell::new(true));
4186
4187            let (stored, shown, completer) = (
4188                Rc::clone(&setter),
4189                Rc::clone(&show_autocomplete),
4190                options_completer.clone(),
4191            );
4192            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
4193                move |_app, _context, set_state| {
4194                    *stored.borrow_mut() = Some(set_state);
4195                    if !shown.get() {
4196                        return SizedBox::shrink().into_widget();
4197                    }
4198                    let completer = completer.clone();
4199                    RawAutocomplete::new(
4200                        |_app, _context, _on_selected, _options: &[String]| {
4201                            Container::new().into_widget()
4202                        },
4203                        move |app, _value| {
4204                            let future = completer.future();
4205                            app.spawn(async move |_cx| future.await)
4206                        },
4207                    )
4208                    .field_view_builder(|_app, _context, controller, focus_node, _on_submitted| {
4209                        TestTextField::new()
4210                            .focus_node(focus_node)
4211                            .controller(controller)
4212                            .into_widget()
4213                    })
4214                    .into_widget()
4215                },
4216            )));
4217
4218            // Focus the field to trigger optionsBuilder.
4219            tester.tap(find::by_type::<TestTextField>());
4220            tester.pump();
4221
4222            // Dispose the widget while optionsBuilder is still pending.
4223            set_state(tester, &setter, || show_autocomplete.set(false));
4224            tester.pump();
4225
4226            tester.update(|app| options_completer.complete(app, strings(&["option1", "option2"])));
4227            tester.pump();
4228        });
4229    }
4230
4231    #[test]
4232    fn options_view_is_constrained_by_media_query_bottom_padding_and_view_insets() {
4233        test_widgets(|tester| {
4234            const PADDING: f64 = 50.0;
4235            const BOTTOM_INSETS: f64 = 70.0;
4236            tester.view().set_device_pixel_ratio(1.0);
4237            tester.pump_widget(
4238                TestWidgetsApp::new().home(
4239                    Column::new().children([
4240                        SizedBox::new().height(200.0).into_widget(),
4241                        RawAutocomplete::new(
4242                            |_app, _context, _on_selected, _options: &[String]| {
4243                                Placeholder::new().into_widget()
4244                            },
4245                            |_app, _value| Task::ready(strings(&["abcd"])),
4246                        )
4247                        .field_view_builder(
4248                            |_app, _context, controller, focus_node, _on_submitted| {
4249                                TestTextField::new()
4250                                    .controller(controller)
4251                                    .focus_node(focus_node)
4252                                    .into_widget()
4253                            },
4254                        )
4255                        .into_widget(),
4256                        SizedBox::new().height(200.0).into_widget(),
4257                    ]),
4258                ),
4259            );
4260
4261            tester.tap(find::by_type::<TestTextField>());
4262            tester.enter_text(find::by_type::<TestTextField>(), "a");
4263            tester.pump();
4264
4265            let initial_size = tester.get_size(find::by_type::<Placeholder>()).height();
4266            tester.view().set_padding(ViewPadding {
4267                bottom: PADDING,
4268                ..ViewPadding::ZERO
4269            });
4270            tester.pump();
4271
4272            // The options view has shrunk to the available height.
4273            assert_eq!(tester.view().metrics().padding.bottom, PADDING);
4274            assert_more_or_less_equals_within(
4275                tester.get_size(find::by_type::<Placeholder>()).height(),
4276                initial_size - PADDING,
4277                0.1,
4278            );
4279
4280            tester.view().set_view_insets(ViewPadding {
4281                bottom: BOTTOM_INSETS,
4282                ..ViewPadding::ZERO
4283            });
4284            tester.pump();
4285
4286            // The options view has shrunk to the available height.
4287            assert_eq!(tester.view().metrics().padding.bottom, PADDING);
4288            assert_eq!(tester.view().metrics().view_insets.bottom, BOTTOM_INSETS);
4289
4290            tester.tap(find::by_type::<TestTextField>());
4291            tester.enter_text(find::by_type::<TestTextField>(), "abc");
4292            tester.pump();
4293
4294            // The options view has shrunk to the available height.
4295            assert_more_or_less_equals_within(
4296                tester.get_size(find::by_type::<Placeholder>()).height(),
4297                initial_size - BOTTOM_INSETS - PADDING,
4298                0.1,
4299            );
4300        });
4301    }
4302
4303    #[test]
4304    fn options_view_is_constrained_by_media_query_top_padding() {
4305        test_widgets(|tester| {
4306            const PADDING: f64 = 100.0;
4307            tester.view().set_device_pixel_ratio(1.0);
4308            tester.pump_widget(
4309                TestWidgetsApp::new().home(
4310                    Column::new().children([
4311                        SizedBox::new().height(200.0).into_widget(),
4312                        RawAutocomplete::new(
4313                            |_app, _context, _on_selected, _options: &[String]| {
4314                                Placeholder::new().into_widget()
4315                            },
4316                            |_app, _value| Task::ready(strings(&["abcd"])),
4317                        )
4318                        .options_view_open_direction(OptionsViewOpenDirection::Up)
4319                        .field_view_builder(
4320                            |_app, _context, controller, focus_node, _on_submitted| {
4321                                TestTextField::new()
4322                                    .controller(controller)
4323                                    .focus_node(focus_node)
4324                                    .into_widget()
4325                            },
4326                        )
4327                        .into_widget(),
4328                        SizedBox::new().height(200.0).into_widget(),
4329                    ]),
4330                ),
4331            );
4332
4333            tester.tap(find::by_type::<TestTextField>());
4334            tester.enter_text(find::by_type::<TestTextField>(), "a");
4335            tester.pump();
4336
4337            let initial_size = tester.get_size(find::by_type::<Placeholder>()).height();
4338            tester.view().set_padding(ViewPadding {
4339                top: PADDING,
4340                ..ViewPadding::ZERO
4341            });
4342            tester.pump();
4343
4344            // The options view has shrunk to the available height.
4345            assert_more_or_less_equals_within(
4346                tester.get_size(find::by_type::<Placeholder>()).height(),
4347                initial_size - PADDING,
4348                0.1,
4349            );
4350        });
4351    }
4352
4353    #[test]
4354    fn raw_autocomplete_does_not_crash_when_hiding_non_displayed_overlay() {
4355        test_widgets(|tester| {
4356            let (controller, focus_node) = own_field(tester);
4357            let autocomplete = |key: &'static str| {
4358                RawAutocomplete::new(
4359                    |_app, _context, _on_selected, _options: &[String]| {
4360                        SizedBox::new().into_widget()
4361                    },
4362                    |_app, _value| Task::ready(Vec::new()),
4363                )
4364                .key(waft_foundation::ValueKey::new(key).into())
4365                .text_editing_controller(controller.erase())
4366                .focus_node(focus_node.erase())
4367                .field_view_builder(
4368                    |_app, _context, controller, focus_node, _on_submitted| {
4369                        TestTextField::new()
4370                            .controller(controller)
4371                            .focus_node(focus_node)
4372                            .into_widget()
4373                    },
4374                )
4375            };
4376
4377            tester.pump_widget(TestWidgetsApp::new().home(autocomplete("initial")));
4378
4379            // Change the key to force the RawAutocomplete to dispose and re-initialize.
4380            tester.pump_widget(TestWidgetsApp::new().home(autocomplete("new-key")));
4381
4382            tester.enter_text(find::by_type::<TestTextField>(), "trigger");
4383            tester.pump();
4384        });
4385    }
4386
4387    #[test]
4388    fn same_option_in_raw_autocomplete_should_be_selectable_again_after_text_is_cleared() {
4389        test_widgets(|tester| {
4390            let (text_ctrl, text_focus) = own_field(tester);
4391            let list_item = strings(&["test", "abc", "dexter"]);
4392
4393            let cleared: TextEditingControllerRef = text_ctrl.erase();
4394            tester.pump_widget(
4395                TestWidgetsApp::new().home(
4396                    Row::new().children([
4397                        Expanded::new(
4398                            RawAutocomplete::new(
4399                                |_app,
4400                                 _context,
4401                                 on_selected: AutocompleteOnSelected<String>,
4402                                 options: &[String]| {
4403                                    let options = options.to_vec();
4404                                    let count = options.len() as i32;
4405                                    ListView::builder(move |_app, _context, index| {
4406                                        let option = options[index as usize].clone();
4407                                        let on_selected = Rc::clone(&on_selected);
4408                                        let tapped = option.clone();
4409                                        Some(
4410                                            GestureDetector::new()
4411                                                .on_tap(Listener::new(move |app| {
4412                                                    on_selected(app, tapped.clone())
4413                                                }))
4414                                                .child(Text::new(option))
4415                                                .into_widget(),
4416                                        )
4417                                    })
4418                                    .item_count(count)
4419                                    .build()
4420                                    .into_widget()
4421                                },
4422                                move |_app, value: TextEditingValue| {
4423                                    Task::ready(
4424                                        list_item
4425                                            .iter()
4426                                            .filter(|e| e.contains(&value.text))
4427                                            .cloned()
4428                                            .collect(),
4429                                    )
4430                                },
4431                            )
4432                            .text_editing_controller(text_ctrl.erase())
4433                            .focus_node(text_focus.erase())
4434                            .field_view_builder(
4435                                |_app, _context, controller, focus_node, _on_submitted| {
4436                                    TestTextField::new()
4437                                        .controller(controller)
4438                                        .focus_node(focus_node)
4439                                        .into_widget()
4440                                },
4441                            ),
4442                        )
4443                        .into_widget(),
4444                        GestureDetector::new()
4445                            .on_tap(Listener::new(move |app| cleared.handle().clear(app)))
4446                            .child(Text::new("Clear"))
4447                            .into_widget(),
4448                    ]),
4449                ),
4450            );
4451
4452            // Open the popup menu.
4453            tester.enter_text(find::by_type::<TestTextField>(), "");
4454            tester.pump_and_settle();
4455            expect(tester, &find::text("test"), finds_one_widget());
4456
4457            // Select option 'test'.
4458            tester.tap(find::text("test"));
4459            tester.pump_and_settle();
4460            let controller: TextEditingControllerRef = text_ctrl.erase();
4461            assert_eq!(text_of(tester, &controller), "test");
4462
4463            // Clear text.
4464            tester.tap(find::text("Clear"));
4465            tester.update(|app| focus_of(&text_focus).unfocus(app, UnfocusDisposition::Scope));
4466            tester.pump_and_settle();
4467            assert_eq!(text_of(tester, &controller), "");
4468
4469            // Select 'test' again.
4470            tester.tap(find::by_type::<TestTextField>());
4471            tester.pump_and_settle();
4472            expect(tester, &find::text("test"), finds_widgets());
4473            tester.tap(find::text("test").last());
4474            tester.pump_and_settle();
4475
4476            // The text field should be updated to 'test'.
4477            assert_eq!(text_of(tester, &controller), "test");
4478        });
4479    }
4480
4481    #[test]
4482    fn tab_from_field_skips_the_options_overlay_and_advances_to_the_next_focusable_sibling() {
4483        // Regression test for https://github.com/flutter/flutter/issues/183456.
4484        test_widgets(|tester| {
4485            let target_focus = tester.update(FocusNode::new);
4486            tester.pump_widget(
4487                TestWidgetsApp::new().home(
4488                    Column::new().children([
4489                        RawAutocomplete::new(
4490                            |_app,
4491                             _context,
4492                             on_selected: AutocompleteOnSelected<String>,
4493                             options: &[String]| {
4494                                let options = options.to_vec();
4495                                let count = options.len() as i32;
4496                                ListView::builder(move |_app, _context, index| {
4497                                    let option = options[index as usize].clone();
4498                                    let on_selected = Rc::clone(&on_selected);
4499                                    let tapped = option.clone();
4500                                    Some(
4501                                        GestureDetector::new()
4502                                            .on_tap(Listener::new(move |app| {
4503                                                on_selected(app, tapped.clone())
4504                                            }))
4505                                            .child(Focus::new(Text::new(option)))
4506                                            .into_widget(),
4507                                    )
4508                                })
4509                                .item_count(count)
4510                                .build()
4511                                .shrink_wrap(true)
4512                                .into_widget()
4513                            },
4514                            string_options,
4515                        )
4516                        .field_view_builder(
4517                            |_app, _context, controller, focus_node, _on_submitted| {
4518                                TestTextField::new()
4519                                    .controller(controller)
4520                                    .focus_node(focus_node)
4521                                    .into_widget()
4522                            },
4523                        )
4524                        .into_widget(),
4525                        ExcludeFocus::new(TestTextField::new()).into_widget(),
4526                        TestTextField::new()
4527                            .focus_node(target_focus.erase())
4528                            .into_widget(),
4529                    ]),
4530                ),
4531            );
4532
4533            // Focus the autocomplete field by tapping it, then TAB.
4534            tester.tap(find::by_type::<TestTextField>().first());
4535            tester.pump_and_settle();
4536            send_key(tester, PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
4537            tester.pump_and_settle();
4538
4539            assert!(tester.update(|app| focus_of(&target_focus).has_focus(app)));
4540        });
4541    }
4542
4543    /// Dart's `focusNode.hasListeners`, on the caller's node.
4544    fn focus_has_listeners(tester: &WidgetTester, node: &Ref<FocusNode>) -> bool {
4545        tester.update(|app| app.get(node).change_notifier_data().has_listeners())
4546    }
4547
4548    /// Dart's `pumpRawAutocomplete` of the case: one autocomplete over `controller` and
4549    /// `focus_node`, with `options` filtered by the field's text and a keyed options view.
4550    fn pump_autocomplete_with_field(
4551        tester: &mut WidgetTester,
4552        options_key: &GlobalKey,
4553        focus_node: &Ref<FocusNode>,
4554        controller: &Ref<TextEditingController>,
4555    ) {
4556        let key = options_key.clone();
4557        tester.pump_widget(
4558            TestWidgetsApp::new().home(
4559                RawAutocomplete::new(
4560                    move |_app,
4561                          _context,
4562                          _on_selected: AutocompleteOnSelected<String>,
4563                          _options: &[String]| {
4564                        SizedBox::new().key(key.clone().into()).into_widget()
4565                    },
4566                    string_options,
4567                )
4568                .focus_node(focus_node.erase())
4569                .text_editing_controller(controller.erase())
4570                .field_view_builder(|_app, _context, controller, focus_node, _on_submitted| {
4571                    TestTextField::new()
4572                        .controller(controller)
4573                        .focus_node(focus_node)
4574                        .into_widget()
4575                })
4576                .into_widget(),
4577            ),
4578        );
4579    }
4580
4581    fn pump_empty(tester: &mut WidgetTester) {
4582        tester.pump_widget(TestWidgetsApp::new().home(SizedBox::shrink()));
4583    }
4584
4585    #[test]
4586    fn removes_the_listener_from_a_caller_provided_focus_node_on_dispose() {
4587        test_widgets(|tester| {
4588            let (controller, focus_node) = own_field(tester);
4589            let options_key = GlobalKey::new();
4590            pump_autocomplete_with_field(tester, &options_key, &focus_node, &controller);
4591            assert!(focus_has_listeners(tester, &focus_node));
4592
4593            // Unmounting the autocomplete removes everything it added to the caller-owned
4594            // focus node, so that it cannot fire on a disposed state.
4595            pump_empty(tester);
4596            assert!(!focus_has_listeners(tester, &focus_node));
4597        });
4598    }
4599
4600    #[test]
4601    fn refreshes_the_internal_focus_state_when_the_focus_node_changes() {
4602        test_widgets(|tester| {
4603            let options_key = GlobalKey::new();
4604            let (controller, focus_node1) = own_field(tester);
4605            let focus_node2 = tester.update(FocusNode::new);
4606
4607            // Focus the field, then enter text that matches no options.
4608            pump_autocomplete_with_field(tester, &options_key, &focus_node1, &controller);
4609            tester.update(|app| focus_of(&focus_node1).request_focus(app, None));
4610            tester.pump();
4611            tester.pump();
4612            expect(tester, &by_key(&options_key), finds_one_widget());
4613            tester.update(|app| {
4614                controller.handle().set_value(app, value_at("xyz", 3));
4615            });
4616            tester.pump();
4617            expect(tester, &by_key(&options_key), finds_nothing());
4618
4619            // Swap in a focus node that, unlike the old one, is unfocused.
4620            pump_autocomplete_with_field(tester, &options_key, &focus_node2, &controller);
4621            tester.pump();
4622            assert!(focus_has_listeners(tester, &focus_node2));
4623            assert!(!tester.update(|app| focus_of(&focus_node2).has_focus(app)));
4624            assert!(!focus_has_listeners(tester, &focus_node1));
4625
4626            // Make options available again, without changing the focus state.
4627            tester.update(|app| controller.handle().set_value(app, value_at("", 0)));
4628            tester.pump();
4629            expect(tester, &by_key(&options_key), finds_nothing());
4630
4631            // Focusing the new node opens the options view: the internal focus state was
4632            // refreshed at the swap, not left stale from the old node.
4633            tester.update(|app| focus_of(&focus_node2).request_focus(app, None));
4634            tester.pump();
4635            tester.pump();
4636            expect(tester, &by_key(&options_key), finds_one_widget());
4637
4638            // The listener that the swap added to the new node is removed on dispose too.
4639            pump_empty(tester);
4640            assert!(!focus_has_listeners(tester, &focus_node2));
4641        });
4642    }
4643
4644    #[test]
4645    fn does_not_update_options_view_visibility_when_the_focus_node_changes() {
4646        test_widgets(|tester| {
4647            let options_key = GlobalKey::new();
4648            let (controller, focus_node1) = own_field(tester);
4649            let focus_node2 = tester.update(FocusNode::new);
4650
4651            pump_autocomplete_with_field(tester, &options_key, &focus_node1, &controller);
4652            tester.update(|app| focus_of(&focus_node1).request_focus(app, None));
4653            tester.pump();
4654            tester.pump();
4655            expect(tester, &by_key(&options_key), finds_one_widget());
4656
4657            // Swap in an unfocused node while the options view is showing. One might expect
4658            // the view to hide, since the new node is unfocused, but the new listener is
4659            // registered during build, when the overlay portal controller can't show or hide.
4660            pump_autocomplete_with_field(tester, &options_key, &focus_node2, &controller);
4661            tester.pump();
4662            assert!(!tester.update(|app| focus_of(&focus_node2).has_focus(app)));
4663            expect(tester, &by_key(&options_key), finds_one_widget());
4664
4665            // The next visibility update, here from a text change, consults the new node's
4666            // focus state and hides the options view.
4667            tester.update(|app| controller.handle().set_value(app, value_at("a", 1)));
4668            tester.pump();
4669            expect(tester, &by_key(&options_key), finds_nothing());
4670        });
4671    }
4672
4673    /// Dart's `pumpRawAutocomplete()` of the swap case: the internal field and controllers
4674    /// unless a node and controller are given, and the field's own focus node recorded.
4675    fn pump_swapping_autocomplete(
4676        tester: &mut WidgetTester,
4677        options_key: &GlobalKey,
4678        field_focus_node: &std::rc::Rc<RefCell<Option<AnyFocusNode>>>,
4679        focus_node: Option<Ref<FocusNode>>,
4680        text_editing_controller: Option<Ref<TextEditingController>>,
4681    ) {
4682        let key = options_key.clone();
4683        let field = std::rc::Rc::clone(field_focus_node);
4684        let mut autocomplete = RawAutocomplete::new(
4685            move |_app,
4686                  _context,
4687                  _on_selected: AutocompleteOnSelected<String>,
4688                  _options: &[String]| {
4689                SizedBox::new().key(key.clone().into()).into_widget()
4690            },
4691            string_options,
4692        )
4693        .field_view_builder(
4694            move |_app, _context, controller, focus_node, _on_submitted| {
4695                *field.borrow_mut() = Some(focus_node.handle());
4696                TestTextField::new()
4697                    .controller(controller)
4698                    .focus_node(focus_node)
4699                    .into_widget()
4700            },
4701        );
4702        if let Some(focus_node) = focus_node {
4703            autocomplete = autocomplete.focus_node(focus_node.erase());
4704        }
4705        if let Some(text_editing_controller) = text_editing_controller {
4706            autocomplete = autocomplete.text_editing_controller(text_editing_controller.erase());
4707        }
4708        tester.pump_widget(TestWidgetsApp::new().home(autocomplete.into_widget()));
4709    }
4710
4711    #[test]
4712    fn keeps_working_when_swapping_between_internal_and_caller_provided_focus_node() {
4713        test_widgets(|tester| {
4714            let options_key = GlobalKey::new();
4715            let custom_focus_node = tester.update(FocusNode::new);
4716            let custom_controller = tester.update(TextEditingController::new);
4717            let field_focus_node: std::rc::Rc<RefCell<Option<AnyFocusNode>>> =
4718                std::rc::Rc::default();
4719
4720            let check_focus_opens_and_closes_options =
4721                |tester: &mut WidgetTester, focus_node: AnyFocusNode| {
4722                    tester.update(|app| focus_node.request_focus(app, None));
4723                    tester.pump();
4724                    tester.pump();
4725                    expect(tester, &by_key(&options_key), finds_one_widget());
4726                    tester.update(|app| focus_node.unfocus(app, UnfocusDisposition::Scope));
4727                    tester.pump();
4728                    tester.pump();
4729                    expect(tester, &by_key(&options_key), finds_nothing());
4730                };
4731
4732            // Start with the internal focus node (no focus node parameter).
4733            pump_swapping_autocomplete(tester, &options_key, &field_focus_node, None, None);
4734            let internal = field_focus_node.borrow().expect("the field was built");
4735            check_focus_opens_and_closes_options(tester, internal);
4736
4737            // Swap internal → caller-provided.
4738            pump_swapping_autocomplete(
4739                tester,
4740                &options_key,
4741                &field_focus_node,
4742                Some(custom_focus_node.clone()),
4743                Some(custom_controller.clone()),
4744            );
4745            check_focus_opens_and_closes_options(tester, focus_of(&custom_focus_node));
4746
4747            // Swap caller-provided → internal.
4748            pump_swapping_autocomplete(tester, &options_key, &field_focus_node, None, None);
4749            let internal = field_focus_node.borrow().expect("the field was built");
4750            check_focus_opens_and_closes_options(tester, internal);
4751        });
4752    }
4753}