1mod placement;
16mod suggestion_item;
17
18use super::flyout::shadow::PopupShadow;
19use super::text_control::TextControl;
20use crate::*;
21use placement::{SuggestionListLayout, SuggestionListPosition, SuggestionsPosition};
22use std::{fmt, rc::Rc, time::Duration};
23use suggestion_item::SuggestionItem;
24use waft_embedder::{Color, Offset, Rect, TextAffinity, TextSelection};
25use waft_foundation::{App, Handle, Listenable, Listener, OptionRetained, Ref, Timer};
26use waft_painting::{EdgeInsetsGeometry, transform_rect};
27use waft_rendering::BoxConstraints;
28use waft_scheduler::FrameCallback;
29use waft_services::{KeyEvent, LogicalKeyboardKey, TextEditingValue};
30use waft_widgets::*;
31
32const TEXT_CHANGED_EVENT_DELAY: Duration = Duration::from_millis(150);
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum AutoSuggestionBoxTextChangeReason {
38 UserInput,
40 ProgrammaticChange,
42 SuggestionChosen,
44}
45
46struct TextChangedCounter {
48 value: u64,
49}
50
51#[derive(Clone, Copy, Debug)]
53pub struct AutoSuggestBoxTextChangedEventArgs {
54 reason: AutoSuggestionBoxTextChangeReason,
55 counter: u64,
56 owner: Handle<TextChangedCounter>,
57}
58
59impl AutoSuggestBoxTextChangedEventArgs {
60 pub fn reason(&self) -> AutoSuggestionBoxTextChangeReason {
62 self.reason
63 }
64
65 pub fn check_current(&self, app: &App) -> bool {
68 app.contains(self.owner) && app.get(self.owner).value == self.counter
69 }
70}
71
72impl fmt::Debug for TextChangedCounter {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 f.debug_struct("TextChangedCounter")
75 .field("value", &self.value)
76 .finish()
77 }
78}
79
80struct ChosenItem<T> {
83 items: Rc<[T]>,
84 index: usize,
85}
86
87impl<T> Clone for ChosenItem<T> {
88 fn clone(&self) -> Self {
89 Self {
90 items: self.items.clone(),
91 index: self.index,
92 }
93 }
94}
95
96impl<T> ChosenItem<T> {
97 fn get(&self) -> &T {
98 &self.items[self.index]
99 }
100}
101
102pub struct AutoSuggestBoxSuggestionChosenEventArgs<T> {
104 selected: ChosenItem<T>,
105}
106
107impl<T> AutoSuggestBoxSuggestionChosenEventArgs<T> {
108 pub fn selected_item(&self) -> &T {
110 self.selected.get()
111 }
112}
113
114pub struct AutoSuggestBoxQuerySubmittedEventArgs<T> {
116 query_text: String,
117 chosen: Option<ChosenItem<T>>,
118}
119
120impl<T> AutoSuggestBoxQuerySubmittedEventArgs<T> {
121 pub fn query_text(&self) -> &str {
123 &self.query_text
124 }
125
126 pub fn chosen_suggestion(&self) -> Option<&T> {
129 self.chosen.as_ref().map(ChosenItem::get)
130 }
131}
132
133pub type AutoSuggestBoxTextMember<T> = Rc<dyn Fn(&T) -> String>;
135
136pub type AutoSuggestBoxItemTemplate<T> = Rc<dyn Fn(&mut App, BuildContext, &T) -> WidgetRef>;
138
139pub type AutoSuggestBoxOpenChangedHandler = Rc<dyn Fn(&mut App, bool)>;
141
142pub type AutoSuggestBoxTextChangedHandler =
144 Rc<dyn Fn(&mut App, &AutoSuggestBoxTextChangedEventArgs)>;
145
146pub type AutoSuggestBoxSuggestionChosenHandler<T> =
148 Rc<dyn Fn(&mut App, &AutoSuggestBoxSuggestionChosenEventArgs<T>)>;
149
150pub type AutoSuggestBoxQuerySubmittedHandler<T> =
152 Rc<dyn Fn(&mut App, &AutoSuggestBoxQuerySubmittedEventArgs<T>)>;
153
154pub struct AutoSuggestBox<T: fmt::Display + 'static> {
157 pub controller: TextEditingControllerRef,
159 pub items_source: Rc<[T]>,
161 pub text_member_path: Option<AutoSuggestBoxTextMember<T>>,
164 pub item_template: Option<AutoSuggestBoxItemTemplate<T>>,
166 pub placeholder_text: String,
168 pub header: Option<WidgetRef>,
170 pub description: Option<WidgetRef>,
172 pub query_icon: Option<WidgetRef>,
175 pub max_suggestion_list_height: f64,
177 pub is_suggestion_list_open: Option<bool>,
179 pub is_suggestion_list_open_changed: Option<AutoSuggestBoxOpenChangedHandler>,
180 pub update_text_on_select: bool,
182 pub auto_maximize_suggestion_area: bool,
185 pub text_changed: Option<AutoSuggestBoxTextChangedHandler>,
187 pub suggestion_chosen: Option<AutoSuggestBoxSuggestionChosenHandler<T>>,
189 pub query_submitted: Option<AutoSuggestBoxQuerySubmittedHandler<T>>,
191 pub key: Option<KeyRef>,
193}
194
195impl<T: fmt::Display + 'static> AutoSuggestBox<T> {
196 pub fn new(controller: TextEditingControllerRef) -> Self {
198 Self {
199 controller,
200 items_source: Rc::from(Vec::new()),
201 text_member_path: None,
202 item_template: None,
203 placeholder_text: String::new(),
204 header: None,
205 description: None,
206 query_icon: None,
207 max_suggestion_list_height: f64::INFINITY,
208 is_suggestion_list_open: None,
209 is_suggestion_list_open_changed: None,
210 update_text_on_select: true,
211 auto_maximize_suggestion_area: true,
212 text_changed: None,
213 suggestion_chosen: None,
214 query_submitted: None,
215 key: None,
216 }
217 }
218
219 pub fn items_source(mut self, items: Vec<T>) -> Self {
221 self.items_source = Rc::from(items);
222 self
223 }
224
225 pub fn text_member_path(mut self, text: impl Fn(&T) -> String + 'static) -> Self {
227 self.text_member_path = Some(Rc::new(text));
228 self
229 }
230
231 pub fn item_template(
233 mut self,
234 template: impl Fn(&mut App, BuildContext, &T) -> WidgetRef + 'static,
235 ) -> Self {
236 self.item_template = Some(Rc::new(template));
237 self
238 }
239
240 pub fn placeholder_text(mut self, value: impl Into<String>) -> Self {
242 self.placeholder_text = value.into();
243 self
244 }
245
246 #[cfg_attr(debug_assertions, track_caller)]
248 pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
249 self.header = Some(value.into_widget());
250 self
251 }
252
253 #[cfg_attr(debug_assertions, track_caller)]
255 pub fn description<K>(mut self, value: impl IntoWidget<K>) -> Self {
256 self.description = Some(value.into_widget());
257 self
258 }
259
260 #[cfg_attr(debug_assertions, track_caller)]
262 pub fn query_icon<K>(mut self, value: impl IntoWidget<K>) -> Self {
263 self.query_icon = Some(value.into_widget());
264 self
265 }
266
267 pub fn max_suggestion_list_height(mut self, value: f64) -> Self {
269 self.max_suggestion_list_height = value;
270 self
271 }
272
273 pub fn is_suggestion_list_open(
276 mut self,
277 open: bool,
278 changed: impl Fn(&mut App, bool) + 'static,
279 ) -> Self {
280 self.is_suggestion_list_open = Some(open);
281 self.is_suggestion_list_open_changed = Some(Rc::new(changed));
282 self
283 }
284
285 pub fn update_text_on_select(mut self, value: bool) -> Self {
287 self.update_text_on_select = value;
288 self
289 }
290
291 pub fn auto_maximize_suggestion_area(mut self, value: bool) -> Self {
293 self.auto_maximize_suggestion_area = value;
294 self
295 }
296
297 pub fn text_changed(
299 mut self,
300 handler: impl Fn(&mut App, &AutoSuggestBoxTextChangedEventArgs) + 'static,
301 ) -> Self {
302 self.text_changed = Some(Rc::new(handler));
303 self
304 }
305
306 pub fn suggestion_chosen(
308 mut self,
309 handler: impl Fn(&mut App, &AutoSuggestBoxSuggestionChosenEventArgs<T>) + 'static,
310 ) -> Self {
311 self.suggestion_chosen = Some(Rc::new(handler));
312 self
313 }
314
315 pub fn query_submitted(
317 mut self,
318 handler: impl Fn(&mut App, &AutoSuggestBoxQuerySubmittedEventArgs<T>) + 'static,
319 ) -> Self {
320 self.query_submitted = Some(Rc::new(handler));
321 self
322 }
323
324 pub fn key(mut self, key: KeyRef) -> Self {
326 self.key = Some(key);
327 self
328 }
329
330 fn text_of(&self, item: &T) -> String {
332 match &self.text_member_path {
333 Some(text) => text(item),
334 None => item.to_string(),
335 }
336 }
337}
338
339impl<T: fmt::Display + 'static> Clone for AutoSuggestBox<T> {
340 fn clone(&self) -> Self {
341 Self {
342 controller: self.controller.clone(),
343 items_source: self.items_source.clone(),
344 text_member_path: self.text_member_path.clone(),
345 item_template: self.item_template.clone(),
346 placeholder_text: self.placeholder_text.clone(),
347 header: self.header.clone(),
348 description: self.description.clone(),
349 query_icon: self.query_icon.clone(),
350 max_suggestion_list_height: self.max_suggestion_list_height,
351 is_suggestion_list_open: self.is_suggestion_list_open,
352 is_suggestion_list_open_changed: self.is_suggestion_list_open_changed.clone(),
353 update_text_on_select: self.update_text_on_select,
354 auto_maximize_suggestion_area: self.auto_maximize_suggestion_area,
355 text_changed: self.text_changed.clone(),
356 suggestion_chosen: self.suggestion_chosen.clone(),
357 query_submitted: self.query_submitted.clone(),
358 key: self.key.clone(),
359 }
360 }
361}
362
363impl<T: fmt::Display + 'static> fmt::Debug for AutoSuggestBox<T> {
364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365 f.debug_struct("AutoSuggestBox")
366 .field("items", &self.items_source.len())
367 .field("placeholder_text", &self.placeholder_text)
368 .field(
369 "max_suggestion_list_height",
370 &self.max_suggestion_list_height,
371 )
372 .field("is_suggestion_list_open", &self.is_suggestion_list_open)
373 .field("update_text_on_select", &self.update_text_on_select)
374 .field(
375 "auto_maximize_suggestion_area",
376 &self.auto_maximize_suggestion_area,
377 )
378 .finish_non_exhaustive()
379 }
380}
381
382#[derive(Clone)]
386pub(super) struct AutoSuggestBoxTextBoxStyle {
387 pub(super) corner_radius: [f64; 4],
389 pub(super) query_button: Option<QueryButton>,
391 pub(super) border_element: Rc<dyn Fn(WidgetRef) -> WidgetRef>,
393}
394
395#[derive(Clone)]
397pub(super) struct QueryButton {
398 pub(super) icon: WidgetRef,
399 pub(super) click: Listener,
400}
401
402impl fmt::Debug for AutoSuggestBoxTextBoxStyle {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.debug_struct("AutoSuggestBoxTextBoxStyle")
405 .field("corner_radius", &self.corner_radius)
406 .field("query_button", &self.query_button.is_some())
407 .finish_non_exhaustive()
408 }
409}
410
411const QUERY_BUTTON_SIZE: (f64, f64) = (32.0, 28.0);
413const QUERY_BUTTON_MARGIN: [f64; 4] = [2.0, 0.0, 0.0, 0.0];
414
415impl AutoSuggestBoxTextBoxStyle {
416 pub(super) const DELETE_BUTTON_WIDTH: f64 = 32.0;
418
419 pub(super) fn trailing_columns(r: &ThemeResources) -> [ColumnDefinition; 2] {
421 [
422 ColumnDefinition::new(GridLength::AUTO),
423 ColumnDefinition::new(GridLength::pixel(r.auto_suggest_box_right_button_margin)),
424 ]
425 }
426
427 pub(super) fn query_button(
431 &self,
432 enabled: bool,
433 text_box_focused: bool,
434 text_box_foreground: Color,
435 ) -> Option<WidgetRef> {
436 let button = self.query_button.clone()?;
437 let corner_radius = self.corner_radius;
438 let icon = button.icon.clone();
439 let button = CommonStates::new(button.click, move |app, context, states| {
440 let r = ThemeResources::of(app, context);
441 let (background, border, foreground) = match states.common {
442 CommonState::PointerOver => (
443 r.text_control_button_background_pointer_over,
444 r.text_control_button_border_brush_pointer_over,
445 r.text_control_button_foreground_pointer_over,
446 ),
447 CommonState::Pressed => (
448 r.text_control_button_background_pressed,
449 r.text_control_button_border_brush_pressed,
450 r.text_control_button_foreground_pressed,
451 ),
452 _ if text_box_focused => (
453 r.text_control_button_background,
454 r.text_control_button_border_brush,
455 r.text_control_button_foreground,
456 ),
457 _ => (
458 r.text_control_button_background,
459 r.text_control_button_border_brush,
460 text_box_foreground,
461 ),
462 };
463 let presenter = ControlBorder::new(Brush::Solid(background), Brush::Solid(border))
464 .border_thickness_ltrb(r.text_control_border_theme_thickness)
465 .corner_radius_corners(corner_radius)
466 .child(Margin::new(
467 r.helper_button_theme_padding,
468 Center::new().child(DefaultTextStyle::new(
469 control_text_style(
470 &r,
471 r.auto_suggest_box_icon_font_size,
472 waft_embedder::FontWeight::NORMAL,
473 foreground,
474 ),
475 icon.clone(),
476 )),
477 ));
478 Opacity::new(if states.common == CommonState::Disabled {
479 0.0
480 } else {
481 1.0
482 })
483 .child(
484 SizedBox::new()
485 .width(QUERY_BUTTON_SIZE.0)
486 .height(QUERY_BUTTON_SIZE.1)
487 .child(Margin::new(
488 r.auto_suggest_box_inner_button_margin,
489 presenter,
490 )),
491 )
492 .into_widget()
493 })
494 .is_enabled(enabled)
495 .is_tab_stop(false);
496 Some(
497 Margin::new(
498 QUERY_BUTTON_MARGIN,
499 Center::new().width_factor(1.0).child(button),
500 )
501 .into_widget(),
502 )
503 }
504}
505
506impl<T: fmt::Display + 'static> StatefulWidget for AutoSuggestBox<T> {
507 type State = AutoSuggestBoxState<T>;
508
509 fn key(&self) -> Option<&KeyRef> {
510 self.key.as_ref()
511 }
512
513 fn create_state(&self) -> AutoSuggestBoxState<T> {
514 AutoSuggestBoxState {
515 state: StateData::new(),
516 text_box_key: GlobalKey::new(),
517 text_focus: None,
518 popup: None,
519 scroll: None,
520 counter: None,
521 controller: None,
522 text: String::new(),
523 item_texts: Vec::new(),
524 focused: false,
525 open: false,
526 pending_open: None,
527 building: false,
528 selected: None,
529 position: SuggestionListPosition::Below,
530 container_max_height: f64::INFINITY,
531 opened_down: None,
532 item_heights: Vec::new(),
533 user_typed_text: String::new(),
534 text_change_reason: None,
535 text_changed_args: None,
536 text_changed_timer: None,
537 ignore_text_changes: false,
538 ignore_selection_changes: false,
539 suppress_suggestion_list_visibility: false,
540 }
541 }
542}
543
544pub struct AutoSuggestBoxState<T: fmt::Display + 'static> {
546 state: StateData<AutoSuggestBox<T>>,
547
548 text_box_key: GlobalKey,
550
551 text_focus: Option<Ref<FocusNode>>,
553
554 popup: Option<Ref<OverlayPortalController>>,
556
557 scroll: Option<Ref<ScrollViewportController>>,
559
560 counter: Option<Ref<TextChangedCounter>>,
562
563 controller: Option<TextEditingControllerRef>,
565
566 text: String,
568
569 item_texts: Vec<String>,
571
572 focused: bool,
574
575 open: bool,
577
578 pending_open: Option<bool>,
580
581 building: bool,
583
584 selected: Option<usize>,
586
587 position: SuggestionListPosition,
589
590 container_max_height: f64,
592
593 opened_down: Option<bool>,
595
596 item_heights: Vec<Option<f64>>,
598
599 user_typed_text: String,
601
602 text_change_reason: Option<AutoSuggestionBoxTextChangeReason>,
604
605 text_changed_args: Option<AutoSuggestBoxTextChangedEventArgs>,
607
608 text_changed_timer: Option<Timer>,
610
611 ignore_text_changes: bool,
613
614 ignore_selection_changes: bool,
616
617 suppress_suggestion_list_visibility: bool,
620}
621
622impl<T: fmt::Display + 'static> AutoSuggestBoxState<T> {
623 fn alive(self: Handle<Self>, app: &App) -> bool {
624 app.contains(self) && self.mounted(app)
625 }
626
627 fn view(self: Handle<Self>, app: &App) -> Option<waft_embedder::ViewId> {
628 View::maybe_id_of(app, self.context(app))
629 }
630
631 fn after_frame(self: Handle<Self>, app: &mut App, work: impl Fn(&mut App) + 'static) {
633 let view = self.view(app);
634 after_next_frame(
635 app,
636 view,
637 FrameCallback::new(move |app, _| {
638 if self.alive(app) {
639 work(app);
640 }
641 }),
642 );
643 }
644
645 fn text_focus(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
646 app.get(self)
647 .text_focus
648 .handle()
649 .expect("an initialized AutoSuggestBox")
650 }
651
652 fn controller(self: Handle<Self>, app: &App) -> TextEditingControllerRef {
653 self.widget(app).controller.clone()
654 }
655
656 fn item_count(self: Handle<Self>, app: &App) -> usize {
657 self.widget(app).items_source.len()
658 }
659
660 fn item_at(self: Handle<Self>, app: &App, index: usize) -> ChosenItem<T> {
663 let items = self.widget(app).items_source.clone();
664 let index = match app.get(self).position {
665 SuggestionListPosition::Below => index,
666 SuggestionListPosition::Above => items.len() - 1 - index,
667 };
668 ChosenItem { items, index }
669 }
670
671 fn text_did_change(self: Handle<Self>, app: &mut App) {
677 let text = self.controller(app).text_value(app).to_owned();
678 if app.get(self).text == text {
679 return;
680 }
681 app.get_mut(self).text = text;
682 let counter = app
683 .get(self)
684 .counter
685 .handle()
686 .expect("an initialized AutoSuggestBox");
687 app.get_mut(counter).value += 1;
688 let reason = app
689 .get_mut(self)
690 .text_change_reason
691 .take()
692 .unwrap_or(AutoSuggestionBoxTextChangeReason::ProgrammaticChange);
693 app.get_mut(self).text_changed_args = Some(AutoSuggestBoxTextChangedEventArgs {
694 reason,
695 counter: app.get(counter).value,
696 owner: counter,
697 });
698 self.restart_text_changed_timer(app);
699 if !app.get(self).ignore_text_changes {
700 self.deselect_ignoring_selection_change(app);
701 }
702 }
703
704 fn text_box_user_input(self: Handle<Self>, app: &mut App, text: String) {
707 if let Some(args) = &mut app.get_mut(self).text_changed_args {
708 args.reason = AutoSuggestionBoxTextChangeReason::UserInput;
709 }
710 if !app.get(self).ignore_text_changes {
711 app.get_mut(self).user_typed_text = text;
712 self.update_suggestion_list_visibility(app);
713 }
714 }
715
716 fn restart_text_changed_timer(self: Handle<Self>, app: &mut App) {
717 if let Some(timer) = app.get_mut(self).text_changed_timer.take() {
718 timer.cancel(app);
719 }
720 let timer = Timer::new(
721 app,
722 TEXT_CHANGED_EVENT_DELAY,
723 Listener::new(move |app| {
724 if self.alive(app) {
725 self.on_text_changed_event_timer_tick(app);
726 }
727 }),
728 );
729 app.get_mut(self).text_changed_timer = Some(timer);
730 }
731
732 fn on_text_changed_event_timer_tick(self: Handle<Self>, app: &mut App) {
734 app.get_mut(self).text_changed_timer = None;
735 let args = app.get(self).text_changed_args;
736 if let (Some(args), Some(handler)) = (args, self.widget(app).text_changed.clone()) {
737 handler(app, &args);
738 }
739 }
740
741 fn update_text_box_text(
743 self: Handle<Self>,
744 app: &mut App,
745 value: &str,
746 reason: AutoSuggestionBoxTextChangeReason,
747 ) {
748 let controller = self.controller(app);
749 if controller.text_value(app) == value {
750 return;
751 }
752 app.get_mut(self).text_change_reason = Some(reason);
753 let end = value.encode_utf16().count() as i32;
754 controller.set_value(
755 app,
756 TextEditingValue::new()
757 .text(value)
758 .selection(TextSelection::collapsed(end, TextAffinity::Downstream)),
759 );
760 app.get_mut(self).text_change_reason = None;
761 }
762
763 fn restore_user_typed_text(self: Handle<Self>, app: &mut App) {
765 let text = app.get(self).user_typed_text.clone();
766 self.update_text_box_text(
767 app,
768 &text,
769 AutoSuggestionBoxTextChangeReason::ProgrammaticChange,
770 );
771 }
772
773 fn select(self: Handle<Self>, app: &mut App, index: Option<usize>) {
777 if app.get(self).selected == index {
778 return;
779 }
780 app.get_mut(self).selected = index;
781 self.on_suggestion_selection_changed(app);
782 self.set_state(app, |_| {});
783 }
784
785 fn deselect_ignoring_selection_change(self: Handle<Self>, app: &mut App) {
787 app.get_mut(self).ignore_selection_changes = true;
788 self.select(app, None);
789 app.get_mut(self).ignore_selection_changes = false;
790 }
791
792 fn on_suggestion_selection_changed(self: Handle<Self>, app: &mut App) {
796 let selected = app.get(self).selected;
797 if self.item_count(app) > 0 {
798 self.scroll_into_view(app, selected.unwrap_or(0));
799 }
800 if app.get(self).ignore_selection_changes {
801 return;
802 }
803 app.get_mut(self).ignore_text_changes = true;
804 if let Some(index) = selected {
805 let chosen = self.item_at(app, index);
806 if self.widget(app).update_text_on_select {
807 let text = self.widget(app).text_of(chosen.get());
808 self.update_text_box_text(
809 app,
810 &text,
811 AutoSuggestionBoxTextChangeReason::SuggestionChosen,
812 );
813 }
814 if let Some(handler) = self.widget(app).suggestion_chosen.clone() {
815 handler(
816 app,
817 &AutoSuggestBoxSuggestionChosenEventArgs { selected: chosen },
818 );
819 }
820 }
821 app.get_mut(self).ignore_text_changes = false;
822 }
823
824 fn move_selection(self: Handle<Self>, app: &mut App, forward: bool) {
827 let count = self.item_count(app);
828 if count == 0 {
829 return;
830 }
831 let last = count - 1;
832 let selected = app.get(self).selected;
833 if selected == Some(0) && last == 0 {
834 return;
835 }
836 match selected {
837 None => self.select(app, Some(if forward { 0 } else { last })),
838 Some(index) if (index == 0 && !forward) || (index == last && forward) => {
839 self.restore_user_typed_text(app);
840 self.select(app, None);
841 }
842 Some(index) => self.select(app, Some(if forward { index + 1 } else { index - 1 })),
843 }
844 }
845
846 fn submit_query(self: Handle<Self>, app: &mut App, chosen: Option<ChosenItem<T>>) {
850 let query_text = self.controller(app).text_value(app).to_owned();
851 if let Some(handler) = self.widget(app).query_submitted.clone() {
852 handler(
853 app,
854 &AutoSuggestBoxQuerySubmittedEventArgs { query_text, chosen },
855 );
856 }
857 self.put_is_suggestion_list_open(app, false);
858 }
859
860 fn programmatic_submit_query(self: Handle<Self>, app: &mut App) {
862 self.deselect_ignoring_selection_change(app);
863 self.submit_query(app, None);
864 }
865
866 fn item_clicked(self: Handle<Self>, app: &mut App, index: usize) {
869 if index >= self.item_count(app) {
870 return;
871 }
872 let chosen = self.item_at(app, index);
873 self.select(app, Some(index));
874 self.submit_query(app, Some(chosen));
875 }
876
877 fn update_suggestion_list_visibility(self: Handle<Self>, app: &mut App) {
882 let open = self.item_count(app) > 0 && app.get(self).container_max_height > 0.0;
883 self.put_is_suggestion_list_open(app, open);
884 }
885
886 fn put_is_suggestion_list_open(self: Handle<Self>, app: &mut App, open: bool) {
890 if app.get(self).building {
891 self.after_frame(app, move |app| self.put_is_suggestion_list_open(app, open));
892 return;
893 }
894 if app.get(self).open == open {
895 return;
896 }
897 if let Some(changed) = self.widget(app).is_suggestion_list_open_changed.clone() {
898 changed(app, open);
899 }
900 self.set_suggestion_list_open(app, open);
901 }
902
903 fn set_suggestion_list_open(self: Handle<Self>, app: &mut App, open: bool) {
906 if app.get(self).open == open {
907 return;
908 }
909 app.get_mut(self).open = open;
910 let popup = app
911 .get(self)
912 .popup
913 .handle()
914 .expect("an initialized AutoSuggestBox");
915 if open {
916 let scroll = ScrollViewportController::new(app);
917 let state = app.get_mut(self);
918 state.scroll = Some(scroll);
919 state.item_heights.clear();
920 popup.show(app);
921 } else {
922 popup.hide(app);
923 self.retire_scroll(app);
924 let state = app.get_mut(self);
925 state.opened_down = None;
926 state.suppress_suggestion_list_visibility = true;
927 self.deselect_ignoring_selection_change(app);
928 }
929 self.set_state(app, |_| {});
930 }
931
932 fn retire_scroll(self: Handle<Self>, app: &mut App) {
934 let Some(scroll) = app.get_mut(self).scroll.take() else {
935 return;
936 };
937 let view = self.view(app);
938 after_next_frame(
939 app,
940 view,
941 FrameCallback::new(move |app, _| scroll.dispose(app)),
942 );
943 }
944
945 fn settle_suggestion_list_open(self: Handle<Self>, app: &mut App) {
948 let Some(open) = self.widget(app).is_suggestion_list_open else {
949 return;
950 };
951 if open == app.get(self).open || app.get(self).pending_open == Some(open) {
952 return;
953 }
954 app.get_mut(self).pending_open = Some(open);
955 self.after_frame(app, move |app| {
956 app.get_mut(self).pending_open = None;
957 if self.widget(app).is_suggestion_list_open != Some(open) {
958 return;
959 }
960 self.set_suggestion_list_open(app, open);
961 if open {
962 self.text_focus(app).request_focus(app, None);
963 }
964 });
965 }
966
967 fn on_items_changed(self: Handle<Self>, app: &mut App) {
970 app.get_mut(self).selected = None;
971 app.get_mut(self).item_heights.clear();
972 if app.get(self).focused {
973 self.update_suggestion_list_visibility(app);
974 }
975 }
976
977 fn text_focus_changed(self: Handle<Self>, app: &mut App) {
980 let focused = self.text_focus(app).has_focus(app);
981 if app.get(self).focused == focused {
982 return;
983 }
984 app.get_mut(self).focused = focused;
985 if focused {
986 self.on_got_focus(app);
987 } else {
988 self.put_is_suggestion_list_open(app, false);
990 }
991 }
992
993 fn on_got_focus(self: Handle<Self>, app: &mut App) {
995 let has_text = !self.controller(app).text_value(app).is_empty();
996 if has_text && !app.get(self).suppress_suggestion_list_visibility {
997 self.update_suggestion_list_visibility(app);
998 app.get_mut(self).suppress_suggestion_list_visibility = false;
999 }
1000 }
1001
1002 fn on_key_down(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
1005 if matches!(event, KeyEvent::Up(_)) {
1006 return KeyEventResult::Ignored;
1007 }
1008 let key = event.logical_key();
1009 let open = app.get(self).open;
1010 if key == LogicalKeyboardKey::ARROW_UP || key == LogicalKeyboardKey::ARROW_DOWN {
1011 if !open {
1012 return KeyEventResult::Ignored;
1013 }
1014 self.move_selection(app, key == LogicalKeyboardKey::ARROW_DOWN);
1015 KeyEventResult::Handled
1016 } else if key == LogicalKeyboardKey::ESCAPE || (key == LogicalKeyboardKey::TAB && open) {
1017 self.restore_user_typed_text(app);
1018 self.put_is_suggestion_list_open(app, false);
1019 self.text_focus(app).request_focus(app, None);
1020 if key == LogicalKeyboardKey::TAB {
1022 KeyEventResult::Ignored
1023 } else {
1024 KeyEventResult::Handled
1025 }
1026 } else if key == LogicalKeyboardKey::ENTER || key == LogicalKeyboardKey::NUMPAD_ENTER {
1027 let chosen = app.get(self).selected.map(|index| self.item_at(app, index));
1028 self.submit_query(app, chosen);
1029 self.put_is_suggestion_list_open(app, false);
1030 KeyEventResult::Handled
1031 } else {
1032 KeyEventResult::Ignored
1033 }
1034 }
1035
1036 fn scroll_into_view(self: Handle<Self>, app: &mut App, index: usize) {
1040 let Some(scroll) = app.get(self).scroll.handle() else {
1041 return;
1042 };
1043 let metrics = scroll.metrics(app);
1044 if metrics.viewport_length <= 0.0 {
1045 return;
1046 }
1047 let estimate = ThemeResources::of(app, self.context(app)).list_view_item_min_height;
1048 let heights = &app.get(self).item_heights;
1049 let height_of = |index: usize| heights.get(index).copied().flatten().unwrap_or(estimate);
1050 let top: f64 = (0..index).map(height_of).sum();
1051 let bottom = top + height_of(index);
1052 let target = if top < metrics.offset {
1053 top
1054 } else if bottom > metrics.offset + metrics.viewport_length {
1055 bottom - metrics.viewport_length
1056 } else {
1057 return;
1058 };
1059 scroll.change_view(app, target, true);
1060 }
1061
1062 fn scroll_last_item_into_view(self: Handle<Self>, app: &mut App) {
1064 let count = self.item_count(app);
1065 if count > 1 {
1066 self.scroll_into_view(app, count - 1);
1067 }
1068 }
1069
1070 fn item_measured(self: Handle<Self>, app: &mut App, index: usize, height: f64) {
1071 let heights = &mut app.get_mut(self).item_heights;
1072 if heights.len() <= index {
1073 heights.resize(index + 1, None);
1074 }
1075 heights[index] = Some(height);
1076 }
1077
1078 fn text_box_corner_radius(self: Handle<Self>, app: &App, r: &ThemeResources) -> [f64; 4] {
1082 let radius = r.control_corner_radius;
1083 match app.get(self).opened_down {
1084 Some(true) => [radius[0], radius[1], 0.0, 0.0],
1085 Some(false) => [0.0, 0.0, radius[2], radius[3]],
1086 None => radius,
1087 }
1088 }
1089
1090 fn text_box_bounds(self: Handle<Self>, app: &mut App) -> Option<Rect> {
1092 let text_box = app
1093 .get(self)
1094 .text_box_key
1095 .clone()
1096 .current_context(app)?
1097 .find_render_object(app)?
1098 .as_box()?;
1099 let overlay = Overlay::of(app, self.context(app), true);
1100 let root = overlay.context(app).find_render_object(app)?.as_box()?;
1101 let transform = text_box
1102 .as_object()
1103 .get_transform_to(app, Some(root.as_object()));
1104 Some(transform_rect(
1105 &transform,
1106 Offset::ZERO & text_box.size(app),
1107 ))
1108 }
1109
1110 fn suggestions_popup(
1113 self: Handle<Self>,
1114 app: &mut App,
1115 context: BuildContext,
1116 info: OverlayChildLayoutInfo,
1117 ) -> WidgetRef {
1118 let r = ThemeResources::of(app, context);
1119 let border_element = transform_rect(
1120 &info.child_paint_transform(),
1121 Offset::ZERO & info.child_size(),
1122 );
1123 let text_box = self.text_box_bounds(app).unwrap_or(border_element);
1124 let thickness = r.text_control_border_theme_thickness;
1126 let content_element = Rect::from_ltrb(
1127 border_element.left + thickness[0],
1128 border_element.top + thickness[1],
1129 border_element.right - thickness[2],
1130 border_element.bottom - thickness[3],
1131 );
1132 let layout = placement::arrange(
1133 text_box,
1134 content_element,
1135 info.overlay_size(),
1136 self.widget(app).max_suggestion_list_height,
1137 );
1138 self.take_layout(app, layout);
1139 let container = self.suggestions_container(app, context, layout.position);
1140 CustomSingleChildLayout::new(Rc::new(SuggestionsPosition(layout)))
1141 .child(TextFieldTapRegion::new(container))
1142 .into_widget()
1143 }
1144
1145 fn take_layout(self: Handle<Self>, app: &mut App, layout: SuggestionListLayout) {
1149 app.get_mut(self).container_max_height = layout.max_height;
1150 let position = layout.position;
1151 if app.get(self).position != position {
1152 app.get_mut(self).position = position;
1153 app.get_mut(self).item_heights.clear();
1154 self.after_frame(app, move |app| {
1155 self.deselect_ignoring_selection_change(app);
1156 if position == SuggestionListPosition::Above {
1157 self.scroll_last_item_into_view(app);
1158 }
1159 });
1160 }
1161 let down = position == SuggestionListPosition::Below;
1162 if app
1163 .get(self)
1164 .opened_down
1165 .is_some_and(|opened| opened == down)
1166 {
1167 return;
1168 }
1169 self.after_frame(app, move |app| {
1170 if app.get(self).open {
1171 self.set_state(app, |state| state.opened_down = Some(down));
1172 }
1173 });
1174 }
1175
1176 fn suggestions_container(
1179 self: Handle<Self>,
1180 app: &mut App,
1181 context: BuildContext,
1182 position: SuggestionListPosition,
1183 ) -> WidgetRef {
1184 let r = ThemeResources::of(app, context);
1185 let Some(scroll) = app.get(self).scroll.clone() else {
1186 return SizedBox::shrink().into_widget();
1187 };
1188 let overlay = r.overlay_corner_radius;
1189 let corner_radius = match position {
1190 SuggestionListPosition::Below => [0.0, 0.0, overlay[2], overlay[3]],
1191 SuggestionListPosition::Above => [overlay[0], overlay[1], 0.0, 0.0],
1192 };
1193 let list = ListView::builder(move |app, _, index| self.suggestion(app, index as usize))
1194 .item_count(self.item_count(app) as i32)
1195 .build()
1196 .controller(scroll.native_controller(app))
1197 .shrink_wrap(true)
1198 .padding(EdgeInsetsGeometry::ZERO);
1199 let suggestions_list = Margin::new(
1200 r.auto_suggest_list_padding,
1201 ConstrainedBox::new(BoxConstraints::new().max_height(r.auto_suggest_list_max_height))
1202 .child(ScrollBarViewport::scroller(scroll, list)),
1203 );
1204 let border = ControlBorder::new(
1205 Brush::Acrylic(r.auto_suggest_box_suggestions_list_background),
1206 Brush::Solid(r.auto_suggest_box_suggestions_list_border_brush),
1207 )
1208 .border_thickness_ltrb(r.auto_suggest_list_border_theme_thickness)
1209 .corner_radius_corners(corner_radius)
1210 .background_sizing(BackgroundSizing::InnerBorderEdge)
1211 .padding(r.auto_suggest_list_margin)
1212 .child(suggestions_list);
1213 CustomPaint::new()
1214 .painter(PopupShadow::for_anchored_popup(r.theme, corner_radius))
1215 .child(border)
1216 .into_widget()
1217 }
1218
1219 fn suggestion(self: Handle<Self>, app: &mut App, index: usize) -> Option<WidgetRef> {
1221 if index >= self.item_count(app) {
1222 return None;
1223 }
1224 let chosen = self.item_at(app, index);
1225 let widget = self.widget(app);
1226 let content = match widget.item_template.clone() {
1227 Some(template) => template(app, self.context(app), chosen.get()),
1228 None => Text::new(chosen.get().to_string())
1229 .soft_wrap(false)
1230 .into_widget(),
1231 };
1232 let item = SuggestionItem {
1233 content,
1234 selected: app.get(self).selected == Some(index),
1235 clicked: Listener::new(move |app| self.item_clicked(app, index)),
1236 };
1237 Some(
1238 SizeObserver::new(
1239 item,
1240 Rc::new(move |app, _, size| {
1241 if self.alive(app) {
1242 self.item_measured(app, index, size.height());
1243 }
1244 }),
1245 )
1246 .into_widget(),
1247 )
1248 }
1249
1250 fn sync_controller(self: Handle<Self>, app: &mut App) {
1252 let controller = self.controller(app);
1253 if app.get(self).controller.handle() == Some(controller.handle()) {
1254 return;
1255 }
1256 if let Some(old) = app.get_mut(self).controller.take() {
1257 old.remove_listener(app, &Listener::handle_method(self, Self::text_did_change));
1258 }
1259 controller.add_listener(app, Listener::handle_method(self, Self::text_did_change));
1260 let text = controller.text_value(app).to_owned();
1261 let state = app.get_mut(self);
1262 state.text = text;
1263 state.controller = Some(controller);
1264 }
1265
1266 fn item_texts(self: Handle<Self>, app: &App) -> Vec<String> {
1268 self.widget(app)
1269 .items_source
1270 .iter()
1271 .map(ToString::to_string)
1272 .collect()
1273 }
1274}
1275
1276impl<T: fmt::Display + 'static> State for AutoSuggestBoxState<T> {
1277 type Widget = AutoSuggestBox<T>;
1278 waft_widgets::state_accessors!();
1279
1280 fn init_state(self: Handle<Self>, app: &mut App) {
1281 let text_focus = FocusNode::new(app);
1282 text_focus.as_node().set_on_key_event(
1283 app,
1284 Some(Rc::new(move |app, _, event| self.on_key_down(app, event))),
1285 );
1286 text_focus.add_listener(app, Listener::handle_method(self, Self::text_focus_changed));
1287 let popup =
1288 OverlayPortalController::new(app, Some("AutoSuggestBox SuggestionsPopup".into()));
1289 let counter = app.create(TextChangedCounter { value: 0 });
1290 let item_texts = self.item_texts(app);
1291 let state = app.get_mut(self);
1292 state.text_focus = Some(text_focus);
1293 state.popup = Some(popup);
1294 state.counter = Some(counter);
1295 state.item_texts = item_texts;
1296 self.sync_controller(app);
1297 }
1298
1299 fn did_update_widget(self: Handle<Self>, app: &mut App, _old: &AutoSuggestBox<T>) {
1300 app.get_mut(self).building = true;
1301 self.sync_controller(app);
1302 let item_texts = self.item_texts(app);
1303 if app.get(self).item_texts != item_texts {
1304 app.get_mut(self).item_texts = item_texts;
1305 self.on_items_changed(app);
1306 }
1307 app.get_mut(self).building = false;
1308 }
1309
1310 fn dispose(self: Handle<Self>, app: &mut App) {
1311 if let Some(timer) = app.get_mut(self).text_changed_timer.take() {
1312 timer.cancel(app);
1313 }
1314 if let Some(controller) = app.get_mut(self).controller.take() {
1315 controller.remove_listener(app, &Listener::handle_method(self, Self::text_did_change));
1316 }
1317 let state = app.get_mut(self);
1318 let text_focus = state
1319 .text_focus
1320 .take()
1321 .expect("an initialized AutoSuggestBox");
1322 let popup = state.popup.take();
1323 let scroll = state.scroll.take();
1324 text_focus.remove_listener(
1325 app,
1326 &Listener::handle_method(self, Self::text_focus_changed),
1327 );
1328 text_focus.dispose(app);
1329 drop(popup);
1330 if let Some(scroll) = scroll {
1331 scroll.dispose(app);
1332 }
1333 }
1334
1335 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1336 self.settle_suggestion_list_open(app);
1337 let widget = self.widget(app).clone();
1338 let r = ThemeResources::of(app, context);
1339 let popup = app
1340 .get(self)
1341 .popup
1342 .clone()
1343 .expect("an initialized AutoSuggestBox");
1344 let mut config = TextBox::new(widget.controller.clone())
1345 .focus_node(
1346 app.get(self)
1347 .text_focus
1348 .as_ref()
1349 .expect("an initialized AutoSuggestBox")
1350 .erase(),
1351 )
1352 .placeholder_text(widget.placeholder_text.clone())
1353 .text_changed(move |app, text| self.text_box_user_input(app, text));
1354 if let Some(header) = widget.header.clone() {
1355 config = config.header(header);
1356 }
1357 if let Some(description) = widget.description.clone() {
1358 config = config.description(description);
1359 }
1360 let style = AutoSuggestBoxTextBoxStyle {
1361 corner_radius: self.text_box_corner_radius(app, &r),
1362 query_button: widget.query_icon.clone().map(|icon| QueryButton {
1363 icon,
1364 click: Listener::new(move |app| self.programmatic_submit_query(app)),
1365 }),
1366 border_element: Rc::new(move |border| {
1367 OverlayPortal::overlay_child_layout_builder(
1368 popup.clone(),
1369 move |app, context, info| self.suggestions_popup(app, context, info),
1370 )
1371 .overlay_location(OverlayChildLocation::RootOverlay)
1372 .child(border)
1373 .into_widget()
1374 }),
1375 };
1376 KeyedSubtree::new(TextControl::new(config, None).auto_suggest_box_style(style))
1377 .key(app.get(self).text_box_key.clone().into())
1378 .into_widget()
1379 }
1380}