1use std::fmt::{self, Debug, Display};
4use std::hash::Hash;
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::Curves;
9use waft_foundation::{App, Handle, Listener, Ref, Task, ValueKey, VoidCallback};
10use waft_painting::EdgeInsetsGeometry;
11use waft_rendering::BoxConstraints;
12use waft_scheduler::{FrameCallback, SchedulerBinding};
13use waft_services::TextEditingValue;
14use waft_widgets::{
15 AutocompleteFieldViewBuilder, AutocompleteHighlightedOption, AutocompleteOnSelected,
16 AutocompleteOptionToString, AutocompleteOptionsBuilder, AutocompleteOptionsViewBuilder,
17 BuildContext, Builder, ConstrainedBox, Container, FocusNodeRef, GlobalKey, IntoWidget, KeyRef,
18 ListView, OptionsViewOpenDirection, RawAutocomplete, ScrollController, ScrollControllerLeaf,
19 ScrollPositionAlignmentPolicy, Scrollable, Semantics, State, StateData, StatefulWidget,
20 StatelessWidget, Text, TextEditingControllerRef, WidgetRef,
21};
22
23use crate::ink_well::InkWell;
24use crate::material::Material;
25use crate::text_form_field::TextFormField;
26use crate::theme::Theme;
27
28pub struct Autocomplete<T: Clone + PartialEq + Hash + Debug + 'static> {
47 pub key: Option<KeyRef>,
48
49 pub display_string_for_option: AutocompleteOptionToString<T>,
56
57 pub field_view_builder: AutocompleteFieldViewBuilder,
64
65 pub focus_node: Option<FocusNodeRef>,
72
73 pub on_selected: Option<AutocompleteOnSelected<T>>,
75
76 pub options_builder: AutocompleteOptionsBuilder<T>,
79
80 pub options_view_builder: Option<AutocompleteOptionsViewBuilder<T>>,
89
90 pub options_view_open_direction: OptionsViewOpenDirection,
94
95 pub options_max_height: f64,
102
103 pub text_editing_controller: Option<TextEditingControllerRef>,
110
111 pub initial_value: Option<TextEditingValue>,
120}
121
122impl<T: Clone + PartialEq + Hash + Debug + Display + 'static> Autocomplete<T> {
123 pub fn new(
129 options_builder: impl Fn(&mut App, TextEditingValue) -> Task<Vec<T>> + 'static,
130 ) -> Autocomplete<T> {
131 Autocomplete::new_with_display_string(options_builder, |option: &T| {
132 RawAutocomplete::<T>::default_string_for_option(option)
133 })
134 }
135}
136
137impl<T: Clone + PartialEq + Hash + Debug + 'static> Autocomplete<T> {
138 pub fn new_with_display_string(
142 options_builder: impl Fn(&mut App, TextEditingValue) -> Task<Vec<T>> + 'static,
143 display_string_for_option: impl Fn(&T) -> String + 'static,
144 ) -> Autocomplete<T> {
145 Autocomplete {
146 key: None,
147 display_string_for_option: Rc::new(display_string_for_option),
148 field_view_builder: Rc::new(Self::default_field_view_builder),
149 focus_node: None,
150 on_selected: None,
151 options_builder: Rc::new(options_builder),
152 options_view_builder: None,
153 options_view_open_direction: OptionsViewOpenDirection::Down,
154 options_max_height: 200.0,
155 text_editing_controller: None,
156 initial_value: None,
157 }
158 }
159
160 pub fn key(mut self, key: KeyRef) -> Autocomplete<T> {
162 self.key = Some(key);
163 self
164 }
165
166 pub fn display_string_for_option(
168 mut self,
169 display_string_for_option: impl Fn(&T) -> String + 'static,
170 ) -> Autocomplete<T> {
171 self.display_string_for_option = Rc::new(display_string_for_option);
172 self
173 }
174
175 pub fn field_view_builder(
177 mut self,
178 field_view_builder: impl Fn(
179 &mut App,
180 BuildContext,
181 TextEditingControllerRef,
182 FocusNodeRef,
183 VoidCallback,
184 ) -> WidgetRef
185 + 'static,
186 ) -> Autocomplete<T> {
187 self.field_view_builder = Rc::new(field_view_builder);
188 self
189 }
190
191 pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Autocomplete<T> {
193 self.focus_node = Some(focus_node);
194 self
195 }
196
197 pub fn on_selected(mut self, on_selected: impl Fn(&mut App, T) + 'static) -> Autocomplete<T> {
199 self.on_selected = Some(Rc::new(on_selected));
200 self
201 }
202
203 pub fn options_view_builder(
205 mut self,
206 options_view_builder: impl Fn(
207 &mut App,
208 BuildContext,
209 AutocompleteOnSelected<T>,
210 &[T],
211 ) -> WidgetRef
212 + 'static,
213 ) -> Autocomplete<T> {
214 self.options_view_builder = Some(Rc::new(options_view_builder));
215 self
216 }
217
218 pub fn options_view_open_direction(
220 mut self,
221 options_view_open_direction: OptionsViewOpenDirection,
222 ) -> Autocomplete<T> {
223 self.options_view_open_direction = options_view_open_direction;
224 self
225 }
226
227 pub fn options_max_height(mut self, options_max_height: f64) -> Autocomplete<T> {
229 self.options_max_height = options_max_height;
230 self
231 }
232
233 pub fn text_editing_controller(
235 mut self,
236 text_editing_controller: TextEditingControllerRef,
237 ) -> Autocomplete<T> {
238 self.text_editing_controller = Some(text_editing_controller);
239 self
240 }
241
242 pub fn initial_value(mut self, initial_value: TextEditingValue) -> Autocomplete<T> {
244 self.initial_value = Some(initial_value);
245 self
246 }
247
248 fn default_field_view_builder(
249 _app: &mut App,
250 _context: BuildContext,
251 text_editing_controller: TextEditingControllerRef,
252 focus_node: FocusNodeRef,
253 on_field_submitted: VoidCallback,
254 ) -> WidgetRef {
255 AutocompleteField {
256 focus_node,
257 text_editing_controller,
258 on_field_submitted,
259 }
260 .into_widget()
261 }
262}
263
264impl<T: Clone + PartialEq + Hash + Debug + 'static> Debug for Autocomplete<T> {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 f.debug_struct("Autocomplete")
267 .field(
268 "options_view_open_direction",
269 &self.options_view_open_direction,
270 )
271 .field("options_max_height", &self.options_max_height)
272 .field("focus_node", &self.focus_node)
273 .field("text_editing_controller", &self.text_editing_controller)
274 .field("initial_value", &self.initial_value)
275 .finish_non_exhaustive()
276 }
277}
278
279impl<T: Clone + PartialEq + Hash + Debug + 'static> StatelessWidget for Autocomplete<T> {
280 fn key(&self) -> Option<&KeyRef> {
281 self.key.as_ref()
282 }
283
284 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
285 let display_string_for_option = Rc::clone(&self.display_string_for_option);
286 let field_view_builder = Rc::clone(&self.field_view_builder);
287 let options_builder = Rc::clone(&self.options_builder);
288 let options_view_open_direction = self.options_view_open_direction;
289 let options_max_height = self.options_max_height;
290 let options_view_builder: AutocompleteOptionsViewBuilder<T> =
291 match self.options_view_builder.clone() {
292 Some(options_view_builder) => options_view_builder,
293 None => {
294 let display_string_for_option = Rc::clone(&display_string_for_option);
295 Rc::new(move |_app, _context, on_selected, options| {
296 AutocompleteOptions {
297 display_string_for_option: Rc::clone(&display_string_for_option),
298 on_selected,
299 open_direction: options_view_open_direction,
300 options: options.to_vec(),
301 options_max_height,
302 }
303 .into_widget()
304 })
305 }
306 };
307 let mut raw_autocomplete = RawAutocomplete::<T>::new_with_display_string(
308 move |app, context, on_selected, options| {
309 options_view_builder(app, context, on_selected, options)
310 },
311 move |app, text_editing_value| options_builder(app, text_editing_value),
312 move |option| display_string_for_option(option),
313 )
314 .field_view_builder(
315 move |app, context, text_editing_controller, focus_node, on_field_submitted| {
316 field_view_builder(
317 app,
318 context,
319 text_editing_controller,
320 focus_node,
321 on_field_submitted,
322 )
323 },
324 )
325 .options_view_open_direction(options_view_open_direction);
326 if let Some(focus_node) = self.focus_node.clone() {
327 raw_autocomplete = raw_autocomplete.focus_node(focus_node);
328 }
329 if let Some(text_editing_controller) = self.text_editing_controller.clone() {
330 raw_autocomplete = raw_autocomplete.text_editing_controller(text_editing_controller);
331 }
332 if let Some(initial_value) = self.initial_value.clone() {
333 raw_autocomplete = raw_autocomplete.initial_value(initial_value);
334 }
335 if let Some(on_selected) = self.on_selected.clone() {
336 raw_autocomplete = raw_autocomplete.on_selected(move |app, option| {
337 on_selected(app, option);
338 });
339 }
340 raw_autocomplete.into_widget()
341 }
342}
343
344struct AutocompleteField {
346 focus_node: FocusNodeRef,
347 on_field_submitted: VoidCallback,
348 text_editing_controller: TextEditingControllerRef,
349}
350
351impl Debug for AutocompleteField {
352 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353 f.debug_struct("AutocompleteField")
354 .field("focus_node", &self.focus_node)
355 .field("text_editing_controller", &self.text_editing_controller)
356 .finish_non_exhaustive()
357 }
358}
359
360impl StatelessWidget for AutocompleteField {
361 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
362 let on_field_submitted = Rc::clone(&self.on_field_submitted);
363 TextFormField::new()
364 .controller(self.text_editing_controller.clone())
365 .focus_node(self.focus_node.clone())
366 .on_field_submitted(move |app, _value| {
367 on_field_submitted(app);
368 })
369 .into_widget()
370 }
371}
372
373struct AutocompleteOptions<T: Clone + PartialEq + Hash + Debug + 'static> {
375 display_string_for_option: AutocompleteOptionToString<T>,
376 on_selected: AutocompleteOnSelected<T>,
377 open_direction: OptionsViewOpenDirection,
378 options: Vec<T>,
379 options_max_height: f64,
380}
381
382impl<T: Clone + PartialEq + Hash + Debug + 'static> Debug for AutocompleteOptions<T> {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 f.debug_struct("AutocompleteOptions")
385 .field("open_direction", &self.open_direction)
386 .field("options", &self.options)
387 .field("options_max_height", &self.options_max_height)
388 .finish_non_exhaustive()
389 }
390}
391
392impl<T: Clone + PartialEq + Hash + Debug + 'static> StatelessWidget for AutocompleteOptions<T> {
393 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
394 let highlighted_index = AutocompleteHighlightedOption::of(app, context);
395
396 Material::new()
397 .elevation(4.0)
398 .child(
399 ConstrainedBox::new(BoxConstraints::new().max_height(self.options_max_height))
400 .child(AutocompleteOptionsList {
401 display_string_for_option: Rc::clone(&self.display_string_for_option),
402 highlighted_index,
403 on_selected: Rc::clone(&self.on_selected),
404 options: self.options.clone(),
405 }),
406 )
407 .into_widget()
408 }
409}
410
411struct AutocompleteOptionsList<T: Clone + PartialEq + Hash + Debug + 'static> {
413 display_string_for_option: AutocompleteOptionToString<T>,
414 highlighted_index: usize,
415 on_selected: AutocompleteOnSelected<T>,
416 options: Vec<T>,
417}
418
419impl<T: Clone + PartialEq + Hash + Debug + 'static> Debug for AutocompleteOptionsList<T> {
420 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421 f.debug_struct("AutocompleteOptionsList")
422 .field("highlighted_index", &self.highlighted_index)
423 .field("options", &self.options)
424 .finish_non_exhaustive()
425 }
426}
427
428impl<T: Clone + PartialEq + Hash + Debug + 'static> StatefulWidget for AutocompleteOptionsList<T> {
429 type State = AutocompleteOptionsListState<T>;
430
431 fn create_state(&self) -> AutocompleteOptionsListState<T> {
432 AutocompleteOptionsListState {
433 state: StateData::new(),
434 scroll_controller: None,
435 }
436 }
437}
438
439struct AutocompleteOptionsListState<T: Clone + PartialEq + Hash + Debug + 'static> {
441 state: StateData<AutocompleteOptionsList<T>>,
442 scroll_controller: Option<Ref<ScrollController>>,
445}
446
447impl<T: Clone + PartialEq + Hash + Debug + 'static> AutocompleteOptionsListState<T> {
448 fn scroll_controller(self: Handle<Self>, app: &App) -> Ref<ScrollController> {
449 app.get(self)
450 .scroll_controller
451 .clone()
452 .expect("made in init_state")
453 }
454
455 fn option_key(option: &T) -> GlobalKey {
458 GlobalKey::wrapping(Rc::new(ValueKey::new(option.clone())))
459 }
460}
461
462impl<T: Clone + PartialEq + Hash + Debug + 'static> State for AutocompleteOptionsListState<T> {
463 type Widget = AutocompleteOptionsList<T>;
464 waft_widgets::state_accessors!();
465
466 fn init_state(self: Handle<Self>, app: &mut App) {
467 let scroll_controller = ScrollController::default(app);
468 app.get_mut(self).scroll_controller = Some(scroll_controller);
469 }
470
471 fn did_update_widget(
472 self: Handle<Self>,
473 app: &mut App,
474 old_widget: &AutocompleteOptionsList<T>,
475 ) {
476 if self.widget(app).highlighted_index != old_widget.highlighted_index {
477 SchedulerBinding::add_post_frame_callback(
478 app,
479 FrameCallback::new(move |app, _time_stamp| {
480 if !self.mounted(app) {
481 return;
482 }
483 let widget = self.widget(app);
484 let highlighted_index = widget.highlighted_index;
485 let highlighted_key = Self::option_key(&widget.options[highlighted_index]);
486 match highlighted_key.current_context(app) {
487 None => {
488 let scroll_controller = self.scroll_controller(app).handle();
489 let offset = if highlighted_index == 0 {
490 0.0
491 } else {
492 scroll_controller.position(app).max_scroll_extent(app)
493 };
494 scroll_controller.jump_to(app, offset);
495 }
496 Some(highlighted_context) => {
497 drop(Scrollable::ensure_visible(
498 app,
499 highlighted_context,
500 0.5,
501 Duration::ZERO,
502 Curves::ease(),
503 ScrollPositionAlignmentPolicy::Explicit,
504 ));
505 }
506 }
507 }),
508 None,
509 );
510 }
511 }
512
513 fn dispose(self: Handle<Self>, app: &mut App) {
514 self.scroll_controller(app).dispose(app);
515 }
516
517 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
518 let highlighted_index = AutocompleteHighlightedOption::of(app, context);
519 let item_count = self.widget(app).options.len();
520 let scroll_controller = self.scroll_controller(app).erase();
521
522 ListView::builder(move |app, _context, index| {
523 let option = self.widget(app).options[index as usize].clone();
524 let highlight = highlighted_index == index as usize;
525 Some(
526 Semantics::new()
527 .button(true)
528 .selected(highlight)
529 .child(
530 InkWell::new()
531 .key(Self::option_key(&option).into())
532 .on_tap({
533 let option = option.clone();
534 Listener::new(move |app| {
535 let on_selected = Rc::clone(&self.widget(app).on_selected);
536 on_selected(app, option.clone());
537 })
538 })
539 .child(Builder::new(move |app, context| {
540 let display_string_for_option =
541 Rc::clone(&self.widget(app).display_string_for_option);
542 let mut container = Container::new()
543 .padding(EdgeInsetsGeometry::all(16.0))
544 .child(Text::new(display_string_for_option(&option)));
545 if highlight {
546 container =
547 container.color(Theme::of(app, context).focus_color);
548 }
549 container.into_widget()
550 })),
551 )
552 .into_widget(),
553 )
554 })
555 .item_count(item_count as i32)
556 .build()
557 .padding(EdgeInsetsGeometry::ZERO)
558 .shrink_wrap(true)
559 .controller(scroll_controller)
560 .into_widget()
561 }
562}
563
564#[cfg(test)]
565mod tests {
566 use std::cell::{Cell, RefCell};
567
568 use waft_embedder::{Color, Size, TextAffinity, TextSelection};
569 use waft_rendering::testing::{CanvasMethod, PaintCall, assert_paints, count_calls};
570 use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
571 use waft_widgets::testing::{
572 WidgetTester, assert_f32_equals, assert_more_or_less_equals, expect, find, finds_nothing,
573 finds_one_widget, test_widgets,
574 };
575 use waft_widgets::{
576 Align, AlignmentGeometry, Center, Column, EditableText, Expanded, FocusNode, Icon,
577 ScrollView, SizedBox, StatefulBuilder, TextEditingController, UnfocusDisposition,
578 };
579
580 use super::*;
581 use crate::icon_button::IconButton;
582 use crate::icons::Icons;
583 use crate::list_tile::ListTile;
584 use crate::scaffold::Scaffold;
585 use crate::test_support::{PaintInspection, material_app};
586 use crate::text_field::TextField;
587 use crate::theme_data::ThemeData;
588
589 const K_OPTIONS: [&str; 14] = [
590 "aardvark",
591 "bobcat",
592 "chameleon",
593 "dingo",
594 "elephant",
595 "flamingo",
596 "goose",
597 "hippopotamus",
598 "iguana",
599 "jaguar",
600 "koala",
601 "lemur",
602 "mouse",
603 "northern white rhinoceros",
604 ];
605
606 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
607 struct User {
608 email: &'static str,
609 name: &'static str,
610 }
611
612 impl Display for User {
613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 write!(f, "{}, {}", self.name, self.email)
615 }
616 }
617
618 const K_OPTIONS_USERS: [User; 3] = [
619 User {
620 name: "Alice",
621 email: "alice@example.com",
622 },
623 User {
624 name: "Bob",
625 email: "bob@example.com",
626 },
627 User {
628 name: "Charlie",
629 email: "charlie123@gmail.com",
630 },
631 ];
632
633 const HIGHLIGHT_COLOR: Color = Color::new(0xFF112233);
634
635 fn matching(text: &str) -> Vec<String> {
637 let query = text.to_lowercase();
638 K_OPTIONS
639 .iter()
640 .filter(|option| option.contains(&query))
641 .map(|option| option.to_string())
642 .collect()
643 }
644
645 fn string_options(_app: &mut App, value: TextEditingValue) -> Task<Vec<String>> {
646 Task::ready(matching(&value.text))
647 }
648
649 fn user_options(_app: &mut App, value: TextEditingValue) -> Task<Vec<User>> {
650 let query = value.text.to_lowercase();
651 Task::ready(
652 K_OPTIONS_USERS
653 .iter()
654 .filter(|option| option.to_string().contains(&query))
655 .cloned()
656 .collect(),
657 )
658 }
659
660 fn string_autocomplete() -> Autocomplete<String> {
661 Autocomplete::new(string_options)
662 }
663
664 fn scaffold_app<K>(
666 tester: &WidgetTester,
667 theme: ThemeData,
668 body: impl IntoWidget<K>,
669 ) -> WidgetRef {
670 let _ = tester;
671 material_app(theme, Scaffold::new().body(body).into_widget())
672 }
673
674 fn default_theme(tester: &WidgetTester) -> ThemeData {
675 ThemeData::new(&tester.cell.borrow())
676 }
677
678 fn highlight_theme(tester: &WidgetTester) -> ThemeData {
679 ThemeData::builder()
680 .focus_color(HIGHLIGHT_COLOR)
681 .build(&tester.cell.borrow())
682 }
683
684 fn pump_in_scaffold<K>(tester: &mut WidgetTester, body: impl IntoWidget<K>) {
685 let app = scaffold_app(tester, default_theme(tester), body);
686 tester.pump_widget(app);
687 }
688
689 fn pump_in_highlight_scaffold<K>(tester: &mut WidgetTester, body: impl IntoWidget<K>) {
690 let app = scaffold_app(tester, highlight_theme(tester), body);
691 tester.pump_widget(app);
692 }
693
694 fn arrow_down(tester: &mut WidgetTester) {
695 tester.send_key_event(
696 PhysicalKeyboardKey::ARROW_DOWN,
697 LogicalKeyboardKey::ARROW_DOWN,
698 );
699 }
700
701 fn with_control(
703 tester: &mut WidgetTester,
704 physical: PhysicalKeyboardKey,
705 logical: LogicalKeyboardKey,
706 ) {
707 tester.send_key_down_event(
708 PhysicalKeyboardKey::CONTROL_LEFT,
709 LogicalKeyboardKey::CONTROL_LEFT,
710 );
711 tester.send_key_event(physical, logical);
712 tester.send_key_up_event(
713 PhysicalKeyboardKey::CONTROL_LEFT,
714 LogicalKeyboardKey::CONTROL_LEFT,
715 );
716 }
717
718 fn field_controller(tester: &WidgetTester) -> TextEditingControllerRef {
721 tester.widget(find::by_type::<TextFormField>(), |field: &TextFormField| {
722 field
723 .controller
724 .clone()
725 .expect("the field has a controller")
726 })
727 }
728
729 fn field_text(tester: &WidgetTester) -> String {
731 controller_text(tester, &field_controller(tester))
732 }
733
734 fn controller_text(tester: &WidgetTester, controller: &TextEditingControllerRef) -> String {
735 controller
736 .handle()
737 .text_value(&tester.cell.borrow())
738 .to_string()
739 }
740
741 fn semantic_child_count(tester: &WidgetTester) -> i32 {
743 tester.widget(find::by_type::<ListView>(), |list: &ListView| {
744 list.scroll_view_data()
745 .semantic_child_count
746 .expect("a builder list has a semantic child count")
747 })
748 }
749
750 fn options_height(tester: &WidgetTester) -> f64 {
752 tester.get_size(find::by_type::<ListView>()).height()
753 }
754
755 fn check_option_highlight(tester: &WidgetTester, label: &str, color: Option<Color>) {
758 let container = find::ancestor(find::text(label), find::by_type::<Container>());
759 let ops = tester.painted_ops(tester.render_object(container));
760 match color {
761 Some(color) => assert_paints(&ops, &[PaintCall::rect(Some(color))]),
762 None => {
763 assert_eq!(count_calls(&ops, CanvasMethod::DrawRect), 0);
764 assert_paints(&ops, &[PaintCall::Paragraph]);
765 }
766 }
767 }
768
769 fn hit_testable(tester: &WidgetTester, finder: waft_widgets::testing::Finder) -> bool {
772 let render = tester.render_object(finder.clone());
773 let render = render.as_box().expect("a render box");
774 let center = tester.get_rect(finder).center();
775 let mut app = tester.cell.borrow_mut();
776 let view_id = app.platform().views()[0].id();
777 let mut result = waft_gestures::HitTestResult::new();
778 waft_gestures::GestureBinding::instance(&mut app).hit_test_in_view(
779 &mut app,
780 &mut result,
781 center,
782 view_id,
783 );
784 result.path().iter().any(|entry| {
785 (entry.target() as &dyn std::any::Any)
786 .downcast_ref::<waft_rendering::BoxHitTestEntry>()
787 .is_some_and(|entry| entry.target() == render)
788 })
789 }
790
791 #[test]
792 fn can_filter_and_select_a_list_of_string_options() {
793 test_widgets(|tester| {
794 let last_selection = Rc::new(RefCell::new(String::new()));
795 let selected = Rc::clone(&last_selection);
796 pump_in_scaffold(
797 tester,
798 string_autocomplete().on_selected(move |_app, selection| {
799 *selected.borrow_mut() = selection;
800 }),
801 );
802
803 expect(
805 tester,
806 &find::by_type::<TextFormField>(),
807 finds_one_widget(),
808 );
809 expect(tester, &find::by_type::<ListView>(), finds_nothing());
810
811 tester.tap(find::by_type::<TextFormField>());
813 tester.pump();
814 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
815 assert_eq!(semantic_child_count(tester), K_OPTIONS.len() as i32);
816
817 tester.enter_text(find::by_type::<TextFormField>(), "ele");
819 tester.pump();
820 expect(
821 tester,
822 &find::by_type::<TextFormField>(),
823 finds_one_widget(),
824 );
825 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
826 assert_eq!(semantic_child_count(tester), 2);
828
829 tester.tap(find::by_type::<InkWell>().first());
831 tester.pump();
832 expect(
833 tester,
834 &find::by_type::<TextFormField>(),
835 finds_one_widget(),
836 );
837 expect(tester, &find::by_type::<ListView>(), finds_nothing());
838 assert_eq!(field_text(tester), "chameleon");
839 assert_eq!(*last_selection.borrow(), "chameleon");
840
841 tester.enter_text(find::by_type::<TextFormField>(), "e");
843 tester.pump();
844 expect(
845 tester,
846 &find::by_type::<TextFormField>(),
847 finds_one_widget(),
848 );
849 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
850 assert_eq!(semantic_child_count(tester), 6);
853 });
854 }
855
856 #[test]
857 fn can_filter_and_select_a_list_of_custom_user_options() {
858 test_widgets(|tester| {
859 pump_in_scaffold(tester, Autocomplete::<User>::new(user_options));
860
861 expect(
863 tester,
864 &find::by_type::<TextFormField>(),
865 finds_one_widget(),
866 );
867 expect(tester, &find::by_type::<ListView>(), finds_nothing());
868
869 tester.tap(find::by_type::<TextFormField>());
871 tester.pump();
872 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
873 assert_eq!(semantic_child_count(tester), K_OPTIONS_USERS.len() as i32);
874
875 tester.enter_text(find::by_type::<TextFormField>(), "example");
877 tester.pump();
878 expect(
879 tester,
880 &find::by_type::<TextFormField>(),
881 finds_one_widget(),
882 );
883 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
884 assert_eq!(semantic_child_count(tester), 2);
886
887 tester.tap(find::by_type::<InkWell>().first());
889 tester.pump();
890 expect(
891 tester,
892 &find::by_type::<TextFormField>(),
893 finds_one_widget(),
894 );
895 expect(tester, &find::by_type::<ListView>(), finds_nothing());
896 assert_eq!(field_text(tester), "Alice, alice@example.com");
897
898 tester.enter_text(find::by_type::<TextFormField>(), "B");
900 tester.pump();
901 expect(
902 tester,
903 &find::by_type::<TextFormField>(),
904 finds_one_widget(),
905 );
906 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
907 assert_eq!(semantic_child_count(tester), 1);
909 });
910 }
911
912 #[test]
913 fn display_string_for_option_is_displayed_in_the_options() {
914 test_widgets(|tester| {
915 pump_in_scaffold(
916 tester,
917 Autocomplete::<User>::new(user_options)
918 .display_string_for_option(|option: &User| option.name.to_string()),
919 );
920
921 expect(
923 tester,
924 &find::by_type::<TextFormField>(),
925 finds_one_widget(),
926 );
927 expect(tester, &find::by_type::<ListView>(), finds_nothing());
928
929 tester.tap(find::by_type::<TextFormField>());
932 tester.pump();
933 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
934 assert_eq!(semantic_child_count(tester), K_OPTIONS_USERS.len() as i32);
935 for user in &K_OPTIONS_USERS {
936 expect(tester, &find::text(user.name), finds_one_widget());
937 }
938
939 tester.tap(find::by_type::<InkWell>().first());
942 tester.pump();
943 expect(
944 tester,
945 &find::by_type::<TextFormField>(),
946 finds_one_widget(),
947 );
948 expect(tester, &find::by_type::<ListView>(), finds_nothing());
949 assert_eq!(field_text(tester), K_OPTIONS_USERS[0].name);
950 });
951 }
952
953 #[test]
956 fn an_option_type_without_display_is_shown_by_its_display_string() {
957 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
958 struct Animal(&'static str);
959
960 test_widgets(|tester| {
961 pump_in_scaffold(
962 tester,
963 Autocomplete::new_with_display_string(
964 |_app, _value| Task::ready(vec![Animal("aardvark"), Animal("bobcat")]),
965 |animal: &Animal| animal.0.to_uppercase(),
966 ),
967 );
968
969 tester.tap(find::by_type::<TextFormField>());
970 tester.pump();
971 expect(tester, &find::text("AARDVARK"), finds_one_widget());
972 expect(tester, &find::text("BOBCAT"), finds_one_widget());
973
974 tester.tap(find::by_type::<InkWell>().first());
975 tester.pump();
976 assert_eq!(field_text(tester), "AARDVARK");
977 });
978 }
979
980 #[test]
981 fn can_build_a_custom_field() {
982 test_widgets(|tester| {
983 let field_key = GlobalKey::new();
984 let key = field_key.clone();
985 pump_in_scaffold(
986 tester,
987 string_autocomplete().field_view_builder(move |_app, _context, _c, _f, _s| {
988 Container::new().key(key.clone().into()).into_widget()
989 }),
990 );
991
992 expect(tester, &find::by_global_key(&field_key), finds_one_widget());
994 expect(tester, &find::by_type::<TextFormField>(), finds_nothing());
995 });
996 }
997
998 #[test]
999 fn can_build_custom_options() {
1000 test_widgets(|tester| {
1001 let options_key = GlobalKey::new();
1002 let key = options_key.clone();
1003 pump_in_scaffold(
1004 tester,
1005 string_autocomplete().options_view_builder(
1006 move |_app, _context, _on_selected, _options| {
1007 Container::new().key(key.clone().into()).into_widget()
1008 },
1009 ),
1010 );
1011
1012 expect(tester, &find::by_global_key(&options_key), finds_nothing());
1014 expect(
1015 tester,
1016 &find::by_type::<TextFormField>(),
1017 finds_one_widget(),
1018 );
1019
1020 tester.tap(find::by_type::<TextFormField>());
1022 tester.pump();
1023 expect(
1024 tester,
1025 &find::by_global_key(&options_key),
1026 finds_one_widget(),
1027 );
1028 });
1029 }
1030
1031 #[test]
1032 fn the_default_autocomplete_options_widget_has_a_maximum_height_of_200() {
1033 test_widgets(|tester| {
1034 pump_in_scaffold(tester, string_autocomplete());
1035
1036 tester.tap(find::by_type::<TextFormField>());
1037 tester.enter_text(find::by_type::<TextFormField>(), "");
1038 tester.pump();
1039 assert_f32_equals(options_height(tester), 200.0);
1040 });
1041 }
1042
1043 #[test]
1044 fn the_options_height_restricts_to_max_desired_height() {
1045 test_widgets(|tester| {
1046 const DESIRED_HEIGHT: f64 = 150.0;
1047 pump_in_scaffold(
1048 tester,
1049 string_autocomplete().options_max_height(DESIRED_HEIGHT),
1050 );
1051
1052 tester.tap(find::by_type::<TextFormField>());
1055 tester.enter_text(find::by_type::<TextFormField>(), "a");
1056 tester.pump();
1057 assert_f32_equals(options_height(tester), DESIRED_HEIGHT);
1058 });
1059 }
1060
1061 #[test]
1062 fn the_height_of_options_shrinks_to_height_of_resulting_items_if_less_than_max_height() {
1063 test_widgets(|tester| {
1064 fn default_options_height(tester: &mut WidgetTester, entered_text: &str) -> f64 {
1067 let controller = field_controller(tester);
1068 tester.update(|app| controller.handle().clear(app));
1069 tester.tap(find::by_type::<TextFormField>());
1070 tester.enter_text(find::by_type::<TextFormField>(), entered_text);
1071 tester.pump();
1072 options_height(tester)
1073 }
1074
1075 const MAX_OPTIONS_HEIGHT: f64 = 250.0;
1076 pump_in_scaffold(
1077 tester,
1078 string_autocomplete().options_max_height(MAX_OPTIONS_HEIGHT),
1079 );
1080
1081 expect(tester, &find::by_type::<ListView>(), finds_nothing());
1082
1083 let nine_items_height = default_options_height(tester, "a");
1086 assert_f32_equals(nine_items_height, MAX_OPTIONS_HEIGHT);
1087
1088 let two_items_height = default_options_height(tester, "el");
1091 assert!(two_items_height < MAX_OPTIONS_HEIGHT);
1092
1093 let one_items_height = default_options_height(tester, "elep");
1096 assert!(one_items_height < two_items_height);
1097 });
1098 }
1099
1100 #[test]
1101 fn initial_value_sets_initial_text_field_value() {
1102 test_widgets(|tester| {
1103 let last_selection = Rc::new(RefCell::new(String::new()));
1104 let selected = Rc::clone(&last_selection);
1105 pump_in_scaffold(
1106 tester,
1107 string_autocomplete()
1108 .initial_value(TextEditingValue::new().text("lem"))
1109 .on_selected(move |_app, selection| {
1110 *selected.borrow_mut() = selection;
1111 }),
1112 );
1113
1114 expect(
1116 tester,
1117 &find::by_type::<TextFormField>(),
1118 finds_one_widget(),
1119 );
1120 expect(tester, &find::by_type::<ListView>(), finds_nothing());
1121 assert_eq!(field_text(tester), "lem");
1122
1123 tester.tap(find::by_type::<TextFormField>());
1125 tester.pump();
1126 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
1127 assert_eq!(semantic_child_count(tester), 1);
1129
1130 tester.tap(find::by_type::<InkWell>().first());
1132 tester.pump();
1133 expect(
1134 tester,
1135 &find::by_type::<TextFormField>(),
1136 finds_one_widget(),
1137 );
1138 expect(tester, &find::by_type::<ListView>(), finds_nothing());
1139 assert_eq!(field_text(tester), "lemur");
1140 assert_eq!(*last_selection.borrow(), "lemur");
1141 });
1142 }
1143
1144 #[test]
1145 fn keyboard_navigation_of_the_options_properly_highlights_the_option() {
1146 test_widgets(|tester| {
1147 pump_in_highlight_scaffold(tester, string_autocomplete());
1148
1149 tester.tap(find::by_type::<TextFormField>());
1150 tester.enter_text(find::by_type::<TextFormField>(), "el");
1151 tester.pump();
1152 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
1153 assert_eq!(semantic_child_count(tester), 2);
1154
1155 check_option_highlight(tester, "chameleon", Some(HIGHLIGHT_COLOR));
1157 check_option_highlight(tester, "elephant", None);
1158
1159 arrow_down(tester);
1161 tester.pump();
1162
1163 check_option_highlight(tester, "chameleon", None);
1165 check_option_highlight(tester, "elephant", Some(HIGHLIGHT_COLOR));
1166 });
1167 }
1168
1169 #[test]
1170 fn keyboard_navigation_keeps_the_highlighted_option_scrolled_into_view() {
1171 test_widgets(|tester| {
1172 pump_in_highlight_scaffold(tester, string_autocomplete());
1173
1174 tester.tap(find::by_type::<TextFormField>());
1175 tester.enter_text(find::by_type::<TextFormField>(), "e");
1176 tester.pump();
1177 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
1178 assert_eq!(semantic_child_count(tester), 6);
1179
1180 let options_group_rect = tester.get_rect(find::by_type::<ListView>());
1181 const OPTIONS_GROUP_PADDING: f64 = 16.0;
1182
1183 check_option_highlight(tester, "chameleon", Some(HIGHLIGHT_COLOR));
1185 assert_f32_equals(
1186 tester.get_top_left(find::text("chameleon")).dy(),
1187 options_group_rect.top + OPTIONS_GROUP_PADDING,
1188 );
1189
1190 arrow_down(tester); tester.pump_and_settle();
1193 arrow_down(tester); tester.pump_and_settle();
1195 arrow_down(tester); tester.pump_and_settle();
1197
1198 check_option_highlight(tester, "lemur", Some(HIGHLIGHT_COLOR));
1200 assert_f32_equals(
1201 tester.get_center(find::text("lemur")).dy(),
1202 options_group_rect.center().dy(),
1203 );
1204
1205 arrow_down(tester); tester.pump_and_settle();
1207
1208 check_option_highlight(tester, "mouse", Some(HIGHLIGHT_COLOR));
1209
1210 expect(tester, &find::text("chameleon"), finds_nothing());
1212
1213 check_option_highlight(tester, "goose", None);
1215 check_option_highlight(tester, "lemur", None);
1216 check_option_highlight(tester, "northern white rhinoceros", None);
1217 });
1218 }
1219
1220 fn one_option_autocomplete(option: &'static str) -> Autocomplete<String> {
1221 Autocomplete::new(move |_app, _value| Task::ready(vec![option.to_string()]))
1222 }
1223
1224 fn raw_open_direction(tester: &WidgetTester) -> OptionsViewOpenDirection {
1225 tester.widget(
1226 find::by_type::<RawAutocomplete<String>>(),
1227 |raw: &RawAutocomplete<String>| raw.options_view_open_direction,
1228 )
1229 }
1230
1231 #[test]
1232 fn options_view_open_direction_default_down() {
1233 test_widgets(|tester| {
1234 pump_in_scaffold(tester, one_option_autocomplete("a"));
1235 assert_eq!(raw_open_direction(tester), OptionsViewOpenDirection::Down);
1236 });
1237 }
1238
1239 #[test]
1240 fn options_view_open_direction_down() {
1241 test_widgets(|tester| {
1242 pump_in_scaffold(
1243 tester,
1244 one_option_autocomplete("a")
1245 .options_view_open_direction(OptionsViewOpenDirection::Down),
1246 );
1247 assert_eq!(raw_open_direction(tester), OptionsViewOpenDirection::Down);
1248 });
1249 }
1250
1251 #[test]
1252 fn options_view_open_direction_up() {
1253 test_widgets(|tester| {
1254 pump_in_scaffold(
1255 tester,
1256 Center::new().child(
1257 one_option_autocomplete("aa")
1258 .options_view_open_direction(OptionsViewOpenDirection::Up),
1259 ),
1260 );
1261 assert_eq!(raw_open_direction(tester), OptionsViewOpenDirection::Up);
1262
1263 tester.tap(find::by_type::<RawAutocomplete<String>>());
1264 tester.enter_text(find::by_type::<TextFormField>(), "a");
1265 tester.pump();
1266 expect(tester, &find::text("aa"), finds_one_widget());
1267 assert!(hit_testable(tester, find::text("aa")));
1268 });
1269 }
1270
1271 #[test]
1272 fn options_view_open_direction_automatic_opens_in_the_direction_with_more_space() {
1273 test_widgets(|tester| {
1274 let field_key = GlobalKey::new();
1275 let options_key = GlobalKey::new();
1276 let set_state: Rc<RefCell<Option<waft_widgets::StateSetter>>> = Rc::default();
1277 let alignment = Rc::new(Cell::new(AlignmentGeometry::TOP_CENTER));
1278
1279 let (stored, aligned) = (Rc::clone(&set_state), Rc::clone(&alignment));
1280 let (field, options) = (field_key.clone(), options_key.clone());
1281 pump_in_scaffold(
1282 tester,
1283 StatefulBuilder::new(move |_app, _context, setter| {
1284 *stored.borrow_mut() = Some(setter);
1285 let (field, options) = (field.clone(), options.clone());
1286 Align::new()
1287 .alignment(aligned.get())
1288 .child(
1289 Autocomplete::<String>::new(|_app, _value| {
1290 Task::ready(vec!["a".to_string(), "b".to_string(), "c".to_string()])
1291 })
1292 .options_view_open_direction(OptionsViewOpenDirection::MostSpace)
1293 .field_view_builder(
1294 move |_app, _context, controller, focus_node, _on_submitted| {
1295 TextField::new()
1296 .key(field.clone().into())
1297 .controller(controller)
1298 .focus_node(focus_node)
1299 .into_widget()
1300 },
1301 )
1302 .options_view_builder(
1303 move |_app, _context, _on_selected, options_list: &[String]| {
1304 Material::new()
1305 .child(
1306 ListView::new().key(options.clone().into()).children(
1307 options_list.iter().map(|option| {
1308 Text::new(option.clone()).into_widget()
1309 }),
1310 ),
1311 )
1312 .into_widget()
1313 },
1314 ),
1315 )
1316 .into_widget()
1317 }),
1318 );
1319 let change_alignment = |tester: &mut WidgetTester, to: AlignmentGeometry| {
1320 let setter = set_state.borrow().clone().expect("the builder ran");
1321 tester.update(|app| setter(app, &mut |_app| alignment.set(to)));
1322 tester.pump();
1323 };
1324
1325 tester.tap(find::by_global_key(&field_key));
1327 tester.pump();
1328
1329 assert_more_or_less_equals(
1330 tester.get_bottom_left(find::by_global_key(&field_key)),
1331 tester.get_top_left(find::by_global_key(&options_key)),
1332 );
1333
1334 change_alignment(tester, AlignmentGeometry::BOTTOM_CENTER);
1336
1337 assert_more_or_less_equals(
1339 tester.get_top_left(find::by_global_key(&field_key)),
1340 tester.get_bottom_left(find::by_global_key(&options_key)),
1341 );
1342
1343 change_alignment(tester, AlignmentGeometry::CENTER);
1345
1346 assert_more_or_less_equals(
1348 tester.get_bottom_left(find::by_global_key(&field_key)),
1349 tester.get_top_left(find::by_global_key(&options_key)),
1350 );
1351 });
1352 }
1353
1354 #[test]
1355 fn can_jump_to_options_that_are_not_yet_built() {
1356 test_widgets(|tester| {
1357 pump_in_highlight_scaffold(tester, string_autocomplete());
1358
1359 tester.tap(find::by_type::<TextFormField>());
1360 tester.pump();
1361 expect(tester, &find::by_type::<ListView>(), finds_one_widget());
1362 assert_eq!(semantic_child_count(tester), K_OPTIONS.len() as i32);
1363
1364 let option_finder = |index: usize| {
1365 find::ancestor(find::text(K_OPTIONS[index]), find::by_type::<Container>())
1366 };
1367
1368 expect(tester, &option_finder(0), finds_one_widget());
1369 expect(tester, &option_finder(K_OPTIONS.len() - 1), finds_nothing());
1370
1371 with_control(
1373 tester,
1374 PhysicalKeyboardKey::ARROW_DOWN,
1375 LogicalKeyboardKey::ARROW_DOWN,
1376 );
1377 tester.pump_and_settle();
1378 expect(tester, &option_finder(0), finds_nothing());
1379 expect(
1380 tester,
1381 &option_finder(K_OPTIONS.len() - 1),
1382 finds_one_widget(),
1383 );
1384 check_option_highlight(
1385 tester,
1386 K_OPTIONS[K_OPTIONS.len() - 1],
1387 Some(HIGHLIGHT_COLOR),
1388 );
1389
1390 with_control(
1392 tester,
1393 PhysicalKeyboardKey::ARROW_UP,
1394 LogicalKeyboardKey::ARROW_UP,
1395 );
1396 tester.pump_and_settle();
1397 expect(tester, &option_finder(0), finds_one_widget());
1398 expect(tester, &option_finder(K_OPTIONS.len() - 1), finds_nothing());
1399 check_option_highlight(tester, K_OPTIONS[0], Some(HIGHLIGHT_COLOR));
1400 });
1401 }
1402
1403 #[test]
1404 fn passes_text_editing_controller_focus_node_to_raw_autocomplete() {
1405 test_widgets(|tester| {
1406 let (text_editing_controller, focus_node) =
1407 tester.update(|app| (TextEditingController::new(app), FocusNode::new(app)));
1408 let controller: TextEditingControllerRef = text_editing_controller.erase();
1409 let node: FocusNodeRef = focus_node.erase();
1410
1411 let home = Material::new()
1412 .child(
1413 Center::new().child(
1414 Autocomplete::<String>::new(|_app, _value| Task::ready(vec!["a".into()]))
1415 .focus_node(node.clone())
1416 .text_editing_controller(controller.clone()),
1417 ),
1418 )
1419 .into_widget();
1420 let app = material_app(default_theme(tester), home);
1421 tester.pump_widget(app);
1422
1423 let (raw_controller, raw_focus_node) = tester.widget(
1424 find::by_type::<RawAutocomplete<String>>(),
1425 |raw: &RawAutocomplete<String>| {
1426 (raw.text_editing_controller.clone(), raw.focus_node.clone())
1427 },
1428 );
1429 assert_eq!(raw_controller, Some(controller));
1430 assert_eq!(raw_focus_node, Some(node));
1431 });
1432 }
1433
1434 #[test]
1435 fn when_field_scrolled_offscreen_reshown_selected_value_when_scrolled_back() {
1436 test_widgets(|tester| {
1437 let (scroll_controller, text_editing_controller, focus_node) = tester.update(|app| {
1438 (
1439 ScrollController::default(app),
1440 TextEditingController::new(app),
1441 FocusNode::new(app),
1442 )
1443 });
1444 let node: FocusNodeRef = focus_node.erase();
1445 let controller: TextEditingControllerRef = text_editing_controller.erase();
1446
1447 pump_in_scaffold(
1448 tester,
1449 ListView::new()
1450 .controller(scroll_controller.erase())
1451 .children([
1452 string_autocomplete()
1453 .focus_node(node.clone())
1454 .text_editing_controller(controller.clone())
1455 .into_widget(),
1456 SizedBox::new().height(1000.0).into_widget(),
1457 ]),
1458 );
1459
1460 tester.tap(find::by_type::<TextField>());
1462 tester.pump();
1463 const TEXT_SELECTION: &str = "chameleon";
1464 tester.tap(find::text(TEXT_SELECTION));
1465
1466 tester.update(|app| {
1468 node.handle().unfocus(app, UnfocusDisposition::Scope);
1469 scroll_controller.handle().jump_to(app, 2000.0);
1470 });
1471 tester.pump_and_settle();
1472
1473 tester.update(|app| scroll_controller.handle().jump_to(app, 0.0));
1475 tester.pump_and_settle();
1476
1477 assert_eq!(controller_text(tester, &controller), TEXT_SELECTION);
1479 });
1480 }
1481
1482 #[test]
1483 fn suggestions_are_hit_tested_before_list_tiles() {
1484 test_widgets(|tester| {
1485 let tiles: Vec<WidgetRef> = (0..3)
1486 .map(|i| {
1487 ListTile::new()
1488 .title(Text::new(format!("Item {i}")))
1489 .on_tap(Listener::new(|_app| {}))
1490 .into_widget()
1491 })
1492 .collect();
1493 let mut children: Vec<WidgetRef> = vec![
1494 Autocomplete::<String>::new(|_app, value| {
1495 Task::ready(
1496 ["Apple", "Banana", "Cherry"]
1497 .iter()
1498 .filter(|option| option.to_lowercase().contains(&value.text))
1499 .map(|option| option.to_string())
1500 .collect(),
1501 )
1502 })
1503 .into_widget(),
1504 ];
1505 children.extend(tiles);
1506 pump_in_scaffold(tester, Column::new().children(children));
1507
1508 tester.tap(find::by_type::<TextField>());
1509 tester.pump();
1510
1511 let cherry_finder = find::text("Cherry");
1512 expect(tester, &cherry_finder, finds_one_widget());
1513
1514 tester.tap(cherry_finder);
1515 tester.pump();
1516
1517 expect(
1518 tester,
1519 &find::widget_with_text::<TextField>("Cherry"),
1520 finds_one_widget(),
1521 );
1522 });
1523 }
1524
1525 #[test]
1526 fn renders_at_zero_area() {
1527 test_widgets(|tester| {
1528 let app = material_app(
1529 default_theme(tester),
1530 Center::new()
1531 .child(
1532 SizedBox::shrink().child(
1533 Scaffold::new().body(
1534 Autocomplete::<String>::new(|_app, _value| {
1535 Task::ready(vec!["Y".to_string()])
1536 })
1537 .initial_value(TextEditingValue::new().text("X")),
1538 ),
1539 ),
1540 )
1541 .into_widget(),
1542 );
1543 tester.pump_widget(app);
1544 let x_text = find::text("X");
1545 assert_eq!(tester.get_size(x_text), Size::ZERO);
1546 });
1547 }
1548
1549 #[test]
1550 fn same_option_should_be_selectable_again_after_text_is_cleared() {
1551 test_widgets(|tester| {
1552 let (text_ctrl, text_focus) =
1553 tester.update(|app| (TextEditingController::new(app), FocusNode::new(app)));
1554 let controller: TextEditingControllerRef = text_ctrl.erase();
1555 let focus: FocusNodeRef = text_focus.erase();
1556 let list_item = ["test", "abc", "dexter"];
1557 let clear_key: KeyRef = ValueKey::new("clear".to_string()).into();
1558
1559 let clearing = controller.clone();
1560 pump_in_scaffold(
1561 tester,
1562 waft_widgets::Row::new().children([
1563 Expanded::new(
1564 Autocomplete::<String>::new(move |_app, value| {
1565 Task::ready(
1566 list_item
1567 .iter()
1568 .filter(|e| {
1569 e.to_lowercase().contains(&value.text.to_lowercase())
1570 })
1571 .map(|e| e.to_string())
1572 .collect(),
1573 )
1574 })
1575 .text_editing_controller(controller.clone())
1576 .focus_node(focus.clone()),
1577 )
1578 .into_widget(),
1579 IconButton::new(
1580 Some(Listener::new(move |app| clearing.handle().clear(app))),
1581 Icon::new(Some(Icons::add())),
1582 )
1583 .key(clear_key.clone())
1584 .into_widget(),
1585 ]),
1586 );
1587
1588 tester.show_keyboard(find::by_type::<EditableText>());
1590 tester.test_text_input().update_editing_value(
1591 TextEditingValue::new()
1592 .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
1593 );
1594 tester.pump_and_settle();
1595 expect(tester, &find::text("test"), finds_one_widget());
1596
1597 tester.tap(find::text("test"));
1599 tester.pump_and_settle();
1600 assert_eq!(controller_text(tester, &controller), "test");
1601
1602 tester.tap(find::by_key(clear_key));
1604 tester.update(|app| focus.handle().unfocus(app, UnfocusDisposition::Scope));
1605 tester.pump_and_settle();
1606 assert_eq!(controller_text(tester, &controller), "");
1607
1608 tester.tap(find::by_type::<TextField>());
1610 tester.pump_and_settle();
1611 expect(
1612 tester,
1613 &find::text("test"),
1614 waft_widgets::testing::finds_widgets(),
1615 );
1616 tester.tap(find::text("test").last());
1617 tester.pump_and_settle();
1618
1619 assert_eq!(controller_text(tester, &controller), "test");
1621 });
1622 }
1623}