1use std::{cell::Cell, rc::Rc};
9
10use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
11use crate::transactional_layout::TransactionalLayoutPending;
12use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
13use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey, WheelDelta};
14use ailloli_ui_core::geometry::{Constraints, Rect, Size};
15use ailloli_ui_core::scroll::{ScrollAxes, ScrollMetrics, ScrollState};
16use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle, Length, Radius};
17use ailloli_ui_core::{FontId, IconId, TextStyle, Theme};
18use ailloli_ui_runtime::app::Invalidation;
19use ailloli_ui_runtime::component::reactive::with_untracked_reads;
20use ailloli_ui_runtime::component::{
21 Binding, ComponentNode, Context, IntoView, Memo, Signal, View, Widget,
22};
23use ailloli_ui_runtime::input::{
24 ActivationPolicy, EventCtx, FocusPolicy, HoverCursorRole, InputRole,
25};
26use ailloli_ui_runtime::layout::{LayoutArtifact, LayoutChild, LayoutCtx, LayoutResult};
27use ailloli_ui_runtime::popup::{PopupContent, PopupDismissReason, PopupId};
28use ailloli_ui_runtime::scene::PaintCtx;
29use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect};
30use ailloli_ui_text::{TextBuffer, TextEditState};
31use lucide_icons::Icon;
32
33use super::popup::{
34 apply_opacity, listbox_popup_semantics, measure_text, paint_overlay_text_in_rect,
35 paint_popup_border, paint_popup_row, paint_popup_shell, scroll_popup, PopupPortalBridge,
36 PopupRowState,
37};
38use super::select::{SelectSize, SelectStyle};
39use super::text_field_core::{
40 handle_single_line_text_event, ime_cursor_rect, layout_single_line_text,
41 paint_committed_single_line_text, TextFieldEventOptions,
42};
43use super::text_input::TextInputStyle;
44
45#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
46pub enum ComboBoxSize {
56 Compact,
58 #[default]
59 Default,
61}
62
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
64pub enum AutocompleteSize {
74 Compact,
76 #[default]
77 Default,
79}
80
81#[derive(Clone, Debug)]
82pub struct ComboBoxStyle {
96 pub input: TextInputStyle,
98 pub popup: SelectStyle,
100 pub width: f32,
102 pub height: f32,
104 pub icon_size: f32,
106 pub icon_gap: f32,
108 pub disabled_opacity: f32,
110}
111
112pub type AutocompleteStyle = ComboBoxStyle;
122
123impl Default for ComboBoxStyle {
124 fn default() -> Self {
125 Self::from_theme(Theme::default(), ComboBoxSize::Default)
126 }
127}
128
129impl ComboBoxStyle {
130 pub fn from_theme(theme: Theme, size: ComboBoxSize) -> Self {
144 let popup = SelectStyle::from_theme(
145 theme,
146 match size {
147 ComboBoxSize::Compact => SelectSize::Compact,
148 ComboBoxSize::Default => SelectSize::Default,
149 },
150 );
151 let palette = theme.palette();
152 let mut input = TextInputStyle::from_theme(theme);
153 input.bg = popup.trigger_background;
154 input.border = palette.border;
155 input.border_focused = palette.focus;
156 input.placeholder = palette.text_muted;
157 input.selection_bg = palette.accent.with_alpha(0.34);
158 input.text = TextStyle::new(FontId::Ui, popup.text.px_size, palette.text);
159 input.radius = popup.radius.tl;
160 input.pad_x = popup.padding_x;
161 input.pad_y = ((popup.height - input.text.px_size as f32 * 1.2) * 0.5).max(4.0);
162
163 Self {
164 width: popup.width,
165 height: popup.height,
166 icon_size: popup.icon_size,
167 icon_gap: popup.icon_gap,
168 disabled_opacity: popup.disabled_opacity,
169 input,
170 popup,
171 }
172 }
173
174 pub fn from_autocomplete_theme(theme: Theme, size: AutocompleteSize) -> Self {
185 Self::from_theme(
186 theme,
187 match size {
188 AutocompleteSize::Compact => ComboBoxSize::Compact,
189 AutocompleteSize::Default => ComboBoxSize::Default,
190 },
191 )
192 }
193
194 pub(crate) fn visual_bounds(&self, rect: Rect) -> Rect {
204 self.popup.visual_bounds(rect)
205 }
206}
207
208#[derive(Clone)]
209pub struct ComboBoxOption<T> {
222 value: T,
224 label: String,
226 disabled: Binding<bool>,
228 icon: Option<IconId>,
230}
231
232impl<T> ComboBoxOption<T> {
233 pub fn new(value: T, label: impl Into<String>) -> Self {
243 Self {
244 value,
245 label: label.into(),
246 disabled: Binding::Static(false),
247 icon: None,
248 }
249 }
250
251 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
261 self.disabled = disabled.into();
262 self
263 }
264
265 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
276 self.disabled(disabled)
277 }
278
279 pub fn leading_icon(mut self, icon: IconId) -> Self {
290 self.icon = Some(icon);
291 self
292 }
293}
294
295type ComboChangeHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
297
298pub struct ComboBox<T, A = ()> {
312 pub(crate) layout: LayoutStyle,
314 pub(crate) flex_item: FlexItemStyle,
316 placeholder: Binding<String>,
318 options: Vec<ComboBoxOption<T>>,
320 selected: Option<Binding<T>>,
322 bound: Option<Signal<T>>,
324 disabled: Binding<bool>,
326 on_change: Option<ComboChangeHandler<T, A>>,
328 style: ComboBoxStyle,
330 default_query: String,
332 default_open: bool,
334}
335
336impl<T: Clone + PartialEq + 'static, A: 'static> Default for ComboBox<T, A> {
337 fn default() -> Self {
338 Self::new()
339 }
340}
341
342impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for ComboBox<T, A> {
343 fn layout_mut(&mut self) -> &mut LayoutStyle {
344 &mut self.layout
345 }
346}
347
348impl<T: Clone + PartialEq + 'static, A: 'static> ComboBox<T, A> {
349 pub fn new() -> Self {
362 Self {
363 layout: LayoutStyle::default(),
364 flex_item: FlexItemStyle::default(),
365 placeholder: Binding::Static("Search...".to_string()),
366 options: Vec::new(),
367 selected: None,
368 bound: None,
369 disabled: Binding::Static(false),
370 on_change: None,
371 style: ComboBoxStyle::default(),
372 default_query: String::new(),
373 default_open: false,
374 }
375 }
376
377 pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
387 self.placeholder = placeholder.into();
388 self
389 }
390
391 pub fn option(mut self, value: T, label: impl Into<String>) -> Self {
401 self.options.push(ComboBoxOption::new(value, label));
402 self
403 }
404
405 pub fn combo_option(mut self, option: ComboBoxOption<T>) -> Self {
416 self.options.push(option);
417 self
418 }
419
420 pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
433 self.selected = Some(selected.into());
434 self.bound = None;
435 self
436 }
437
438 pub fn bind(mut self, selected: impl Into<Signal<T>>) -> Self {
453 let signal = selected.into();
454 self.selected = Some(Binding::Signal(signal.clone()));
455 self.bound = Some(signal);
456 self
457 }
458
459 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
472 self.disabled = disabled.into();
473 self
474 }
475
476 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
487 self.disabled(disabled)
488 }
489
490 pub fn default_query(mut self, query: impl Into<String>) -> Self {
503 self.default_query = query.into();
504 self
505 }
506
507 pub fn default_open(mut self, open: bool) -> Self {
517 self.default_open = open;
518 self
519 }
520
521 pub fn combo_style(mut self, style: ComboBoxStyle) -> Self {
531 self.style = style;
532 self
533 }
534
535 pub fn combo_size(mut self, size: ComboBoxSize) -> Self {
547 self.style = ComboBoxStyle::from_theme(Theme::default(), size);
548 self
549 }
550
551 pub fn on_change(mut self, f: impl Fn(T) -> A + 'static) -> Self {
564 self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
565 self
566 }
567
568 pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
578 self.on_change = Some(Rc::new(f));
579 self
580 }
581
582 pub fn width(mut self, value: impl Into<Length>) -> Self {
592 self.layout.width = value.into();
593 self
594 }
595
596 pub fn height(mut self, value: impl Into<Length>) -> Self {
606 self.layout.height = value.into();
607 self
608 }
609
610 pub fn fill_width(mut self) -> Self {
620 self.layout.width = Length::Fill;
621 self
622 }
623
624 pub fn flex_grow(mut self) -> Self {
634 self.flex_item = self.flex_item.flex_grow(1.0);
635 self
636 }
637}
638
639struct ComboBoxComponent<T, A> {
641 layout: LayoutStyle,
643 placeholder: Binding<String>,
645 options: Vec<ComboBoxOption<T>>,
647 selected: Option<Binding<T>>,
649 bound: Option<Signal<T>>,
651 disabled: Binding<bool>,
653 on_change: Option<ComboChangeHandler<T, A>>,
655 style: ComboBoxStyle,
657 default_query: String,
659 default_open: bool,
661}
662
663impl<T: Clone + PartialEq + 'static, A: 'static> ComponentNode<A> for ComboBoxComponent<T, A> {
664 fn build(&self, context: &mut Context<A>) -> View<A> {
666 let query_text = if self.default_query.is_empty() {
667 selected_label(&self.options, self.selected.as_ref()).unwrap_or_default()
668 } else {
669 self.default_query.clone()
670 };
671 let query = context.signal(query_text.clone());
672 let buffer = context.signal(TextBuffer::from_string(query_text.clone()));
673 let edit = context.signal(edit_at_end(&query_text));
674 let active_index = context.signal(None);
675 let scroll = context.signal_with_invalidation(ScrollState::new(), Invalidation::Paint);
676 let popup_id = context
677 .runtime()
678 .popup_id_for_element(context.element_id())
679 .ok();
680 let popup_content = combo_box_popup_content(RetainedComboBoxPopup {
681 options: self.options.clone(),
682 selected: self.selected.clone(),
683 bound: self.bound.clone(),
684 disabled: self.disabled.clone(),
685 on_change: self.on_change.clone(),
686 style: self.style.clone(),
687 active_index: active_index.clone(),
688 scroll: scroll.clone(),
689 query: query.clone(),
690 buffer: buffer.clone(),
691 edit: edit.clone(),
692 popup_id,
693 pending_scroll: Cell::new(None),
694 });
695
696 View::leaf(ComboBoxWidget {
697 layout: self.layout,
698 placeholder: self.placeholder.clone(),
699 options: self.options.clone(),
700 selected: self.selected.clone(),
701 bound: self.bound.clone(),
702 disabled: self.disabled.clone(),
703 on_change: self.on_change.clone(),
704 style: self.style.clone(),
705 active_index,
706 scroll,
707 query,
708 buffer,
709 edit,
710 pending_portal_close: Cell::new(None),
711 popup: PopupPortalBridge::new_retained_with_content(
712 context,
713 listbox_popup_semantics(),
714 self.default_open,
715 popup_content,
716 ),
717 })
718 }
719}
720
721impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for ComboBox<T, A> {
722 fn into_view(self) -> View<A> {
724 finish_view_sized(
725 View::component(ComboBoxComponent {
726 layout: self.layout,
727 placeholder: self.placeholder,
728 options: self.options,
729 selected: self.selected,
730 bound: self.bound,
731 disabled: self.disabled,
732 on_change: self.on_change,
733 style: self.style,
734 default_query: self.default_query,
735 default_open: self.default_open,
736 }),
737 self.flex_item,
738 LayoutSizeHint::from_layout(self.layout),
739 )
740 }
741}
742
743struct ComboBoxWidget<T, A> {
745 layout: LayoutStyle,
747 placeholder: Binding<String>,
749 options: Vec<ComboBoxOption<T>>,
751 selected: Option<Binding<T>>,
753 bound: Option<Signal<T>>,
755 disabled: Binding<bool>,
757 on_change: Option<ComboChangeHandler<T, A>>,
759 style: ComboBoxStyle,
761 active_index: Signal<Option<usize>>,
763 scroll: Signal<ScrollState>,
765 query: Signal<String>,
767 buffer: Signal<TextBuffer>,
769 edit: Signal<TextEditState>,
771 pending_portal_close: Cell<Option<TransactionalLayoutPending<bool>>>,
773 popup: PopupPortalBridge<A>,
775}
776
777impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for ComboBoxWidget<T, A> {
778 fn debug_name(&self) -> &'static str {
780 "ComboBox"
781 }
782
783 fn layout(
785 &self,
786 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
787 ctx: &mut LayoutCtx<'_>,
788 _children: &mut [LayoutChild],
789 constraints: Constraints,
790 ) -> LayoutResult {
791 let intrinsic = Size::new(self.style.width, self.style.height);
792 let size = apply_layout_size(intrinsic, self.layout, constraints);
793 let (_, text_layout) = layout_single_line_text(
794 ctx,
795 constraints,
796 self.layout,
797 &self.query,
798 &self.buffer,
799 &self.edit,
800 Some(self.placeholder.read()),
801 self.text_style(),
802 );
803 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
804 if ctx.layout_pass().is_committed() {
805 self.pending_portal_close
806 .set(TransactionalLayoutPending::new(ctx, self.disabled.read()));
807 }
808
809 LayoutResult {
810 size,
811 children: Vec::new(),
812 paint_bounds,
813 visual_bounds: self.style.visual_bounds(paint_bounds),
814 overlay_hit_bounds: Vec::new(),
815 clip: None,
816 is_window_root_clip: false,
817 artifact: text_layout.map(LayoutArtifact::Text),
818 }
819 }
820
821 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
823 if self
824 .pending_portal_close
825 .take()
826 .and_then(|pending| pending.into_committed(ctx))
827 == Some(true)
828 {
829 self.popup.close(PopupDismissReason::Programmatic);
830 }
831 }
832
833 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
835 paint_combo_input(ctx, bounds, layout, self, true);
836 if self.popup.is_open() && !self.disabled.read() {
837 self.popup
838 .open_without_event(bounds, self.popup_rect(bounds));
839 }
840 }
841
842 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
844 if self.disabled.read() {
845 return;
846 }
847
848 match event {
849 Event::Focus(focus) if !focus.focused && self.popup.is_open() => {
850 self.close_restore(PopupDismissReason::OutsidePress);
851 ctx.request_repaint();
852 }
853 Event::Pointer(PointerEvent::Button {
854 pos,
855 button: MouseButton::Left,
856 pressed,
857 ..
858 }) if bounds.contains(pos.x, pos.y) => {
859 if *pressed {
860 self.open(ctx, bounds);
861 }
862 let _ = handle_single_line_text_event(
863 ctx,
864 event,
865 text_edit_bounds(bounds, &self.style, true),
866 layout,
867 &self.query,
868 &self.buffer,
869 &self.edit,
870 self.text_style(),
871 TextFieldEventOptions {
872 consume_handled_events: true,
873 },
874 );
875 ctx.request_repaint();
876 ctx.stop_propagation();
877 }
878 Event::Keyboard(key) if key.state == KeyState::Pressed => {
879 self.handle_keyboard(ctx, &key.key, event, bounds, layout);
880 }
881 Event::Ime(_) => {
882 let before = self.query.read();
883 let handled = handle_single_line_text_event(
884 ctx,
885 event,
886 text_edit_bounds(bounds, &self.style, true),
887 layout,
888 &self.query,
889 &self.buffer,
890 &self.edit,
891 self.text_style(),
892 TextFieldEventOptions {
893 consume_handled_events: true,
894 },
895 );
896 self.after_text_event(ctx, before, handled, bounds);
897 }
898 _ => {}
899 }
900 }
901
902 fn focus_policy(&self) -> FocusPolicy {
904 if self.disabled.read() {
905 FocusPolicy::NotFocusable
906 } else {
907 FocusPolicy::Focusable
908 }
909 }
910
911 fn activation_policy(&self) -> ActivationPolicy {
913 ActivationPolicy::SuppressOnFocusOnly
914 }
915
916 fn input_role(&self) -> InputRole {
918 InputRole::TextSingleLine
919 }
920
921 fn ime_cursor_rect(&self, bounds: Rect, layout: &LayoutResult) -> Option<Rect> {
923 ime_cursor_rect(
924 text_edit_bounds(bounds, &self.style, true),
925 layout,
926 &self.query,
927 &self.buffer,
928 &self.edit,
929 self.text_style(),
930 )
931 }
932}
933
934impl<T: Clone + PartialEq + 'static, A: 'static> ComboBoxWidget<T, A> {
935 fn text_style(&self) -> TextInputStyle {
937 if self.disabled.read() {
938 let opacity = self.style.disabled_opacity;
939 let mut input = self.style.input;
940 input.bg = apply_opacity(input.bg, opacity);
941 input.border = apply_opacity(input.border, opacity);
942 input.border_focused = apply_opacity(input.border_focused, opacity);
943 input.placeholder = apply_opacity(input.placeholder, opacity);
944 input.text.color = apply_opacity(input.text.color, opacity);
945 input
946 } else {
947 self.style.input
948 }
949 }
950
951 fn selected_value(&self) -> Option<T> {
953 self.selected.as_ref().map(Binding::read)
954 }
955
956 fn selected_index(&self) -> Option<usize> {
958 let selected = self.selected_value()?;
959 self.options
960 .iter()
961 .position(|option| option.value == selected)
962 }
963
964 fn filtered_indices(&self) -> Vec<usize> {
966 filtered_indices(
967 &self.query.read(),
968 self.options.iter().map(|option| &option.label),
969 )
970 }
971
972 fn popup_width(
974 &self,
975 trigger_width: f32,
976 mut text_system: Option<&mut ailloli_ui_text::TextSystem>,
977 ) -> f32 {
978 self.options
979 .iter()
980 .map(|option| {
981 let label = measure_text(
982 text_system.as_deref_mut(),
983 &option.label,
984 self.style.popup.text,
985 )
986 .w;
987 let icon = option
988 .icon
989 .as_ref()
990 .map(|_| self.style.popup.icon_size + self.style.popup.icon_gap)
991 .unwrap_or(0.0);
992 label
993 + icon
994 + self.style.popup.padding_x * 2.0
995 + self.style.popup.icon_size
996 + self.style.popup.icon_gap
997 })
998 .fold(self.style.width, f32::max)
999 .max(trigger_width)
1000 .ceil()
1001 }
1002
1003 fn popup_height(&self) -> f32 {
1005 let rows = self.filtered_indices().len().max(1);
1006 (rows as f32 * self.style.popup.option_height).min(self.style.popup.popup_max_height)
1007 }
1008
1009 fn popup_rect(&self, bounds: Rect) -> Rect {
1011 Rect::new(
1012 bounds.x,
1013 bounds.bottom() + self.style.popup.popup_gap,
1014 self.popup_width(bounds.w, None),
1015 self.popup_height(),
1016 )
1017 }
1018
1019 fn open(&self, ctx: &EventCtx<A>, bounds: Rect) {
1021 self.active_index.set(self.first_enabled_index());
1022 self.popup.open(ctx, bounds, self.popup_rect(bounds));
1023 }
1024
1025 fn close_restore(&self, reason: PopupDismissReason) {
1027 self.active_index.set(None);
1028 self.popup.close(reason);
1029 let restored = self
1030 .selected_index()
1031 .map(|idx| self.options[idx].label.clone())
1032 .unwrap_or_default();
1033 if self.query.read() != restored {
1034 self.query.set(restored.clone());
1035 self.buffer.set(TextBuffer::from_string(restored.clone()));
1036 self.edit.set(edit_at_end(&restored));
1037 }
1038 }
1039
1040 fn close_keep_query(&self, reason: PopupDismissReason) {
1042 self.active_index.set(None);
1043 self.popup.close(reason);
1044 }
1045
1046 fn select_index(&self, ctx: &mut EventCtx<A>, index: usize) {
1048 let Some(option) = self.options.get(index) else {
1049 return;
1050 };
1051 if option.disabled.read() {
1052 return;
1053 }
1054
1055 let changed = self
1056 .selected_value()
1057 .as_ref()
1058 .is_none_or(|value| value != &option.value);
1059 if changed {
1060 let next = option.value.clone();
1061 if let Some(bound) = &self.bound {
1062 bound.set(next.clone());
1063 }
1064 if let Some(on_change) = &self.on_change {
1065 on_change(ctx, next);
1066 }
1067 }
1068
1069 self.query.set(option.label.clone());
1070 self.buffer
1071 .set(TextBuffer::from_string(option.label.clone()));
1072 self.edit.set(edit_at_end(&option.label));
1073 self.close_keep_query(PopupDismissReason::Programmatic);
1074 ctx.request_repaint();
1075 ctx.stop_propagation();
1076 }
1077
1078 fn handle_keyboard(
1080 &self,
1081 ctx: &mut EventCtx<A>,
1082 key: &Key,
1083 event: &Event,
1084 bounds: Rect,
1085 layout: &LayoutResult,
1086 ) {
1087 if !self.popup.is_open() {
1088 if matches!(
1089 key,
1090 Key::Named(NamedKey::Enter)
1091 | Key::Named(NamedKey::ArrowDown)
1092 | Key::Named(NamedKey::ArrowUp)
1093 ) {
1094 self.open(ctx, bounds);
1095 ctx.request_repaint();
1096 ctx.stop_propagation();
1097 return;
1098 }
1099 } else {
1100 match key {
1101 Key::Named(NamedKey::Escape) => {
1102 self.close_restore(PopupDismissReason::Escape);
1103 ctx.request_repaint();
1104 ctx.stop_propagation();
1105 return;
1106 }
1107 Key::Named(NamedKey::ArrowDown) => {
1108 self.move_active(ctx, Direction::Next);
1109 return;
1110 }
1111 Key::Named(NamedKey::ArrowUp) => {
1112 self.move_active(ctx, Direction::Previous);
1113 return;
1114 }
1115 Key::Named(NamedKey::Home) => {
1116 self.set_active(ctx, self.first_enabled_index());
1117 return;
1118 }
1119 Key::Named(NamedKey::End) => {
1120 self.set_active(ctx, self.last_enabled_index());
1121 return;
1122 }
1123 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1124 if let Some(index) = self
1125 .active_index
1126 .read()
1127 .or_else(|| self.first_enabled_index())
1128 {
1129 self.select_index(ctx, index);
1130 }
1131 return;
1132 }
1133 _ => {}
1134 }
1135 }
1136
1137 let before = self.query.read();
1138 let handled = handle_single_line_text_event(
1139 ctx,
1140 event,
1141 text_edit_bounds(bounds, &self.style, true),
1142 layout,
1143 &self.query,
1144 &self.buffer,
1145 &self.edit,
1146 self.text_style(),
1147 TextFieldEventOptions {
1148 consume_handled_events: true,
1149 },
1150 );
1151 self.after_text_event(ctx, before, handled, bounds);
1152 }
1153
1154 fn after_text_event(&self, ctx: &mut EventCtx<A>, before: String, handled: bool, bounds: Rect) {
1156 if handled && self.query.read() != before {
1157 self.open(ctx, bounds);
1158 self.scroll.set(ScrollState::new());
1159 ctx.request_repaint();
1160 }
1161 }
1162
1163 fn move_active(&self, ctx: &mut EventCtx<A>, direction: Direction) {
1165 let next = match direction {
1166 Direction::Next => self.next_enabled_index(self.active_index.read()),
1167 Direction::Previous => self.previous_enabled_index(self.active_index.read()),
1168 };
1169 self.set_active(ctx, next);
1170 }
1171
1172 fn set_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
1174 if self.active_index.read() != next {
1175 self.active_index.set(next);
1176 ctx.request_repaint();
1177 }
1178 ctx.stop_propagation();
1179 }
1180
1181 fn first_enabled_index(&self) -> Option<usize> {
1183 self.filtered_indices()
1184 .into_iter()
1185 .find(|idx| !self.options[*idx].disabled.read())
1186 }
1187
1188 fn last_enabled_index(&self) -> Option<usize> {
1190 self.filtered_indices()
1191 .into_iter()
1192 .rev()
1193 .find(|idx| !self.options[*idx].disabled.read())
1194 }
1195
1196 fn next_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1198 let filtered = self.filtered_indices();
1199 next_enabled(&filtered, current, |idx| !self.options[idx].disabled.read())
1200 }
1201
1202 fn previous_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1204 let filtered = self.filtered_indices();
1205 previous_enabled(&filtered, current, |idx| !self.options[idx].disabled.read())
1206 }
1207}
1208
1209#[derive(Clone)]
1210pub struct AutocompleteItem {
1223 label: String,
1225 disabled: Binding<bool>,
1227 icon: Option<IconId>,
1229}
1230
1231impl AutocompleteItem {
1232 pub fn new(label: impl Into<String>) -> Self {
1242 Self {
1243 label: label.into(),
1244 disabled: Binding::Static(false),
1245 icon: None,
1246 }
1247 }
1248
1249 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1259 self.disabled = disabled.into();
1260 self
1261 }
1262
1263 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1274 self.disabled(disabled)
1275 }
1276
1277 pub fn leading_icon(mut self, icon: IconId) -> Self {
1288 self.icon = Some(icon);
1289 self
1290 }
1291}
1292
1293type AutocompleteSelectHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, String)>;
1295
1296pub struct Autocomplete<A = ()> {
1312 pub(crate) layout: LayoutStyle,
1314 pub(crate) flex_item: FlexItemStyle,
1316 value: Option<Signal<String>>,
1318 placeholder: Binding<String>,
1320 items: Vec<AutocompleteItem>,
1322 disabled: Binding<bool>,
1324 on_select: Option<AutocompleteSelectHandler<A>>,
1326 style: AutocompleteStyle,
1328 default_open: bool,
1330}
1331
1332impl<A: 'static> Default for Autocomplete<A> {
1333 fn default() -> Self {
1334 Self::new()
1335 }
1336}
1337
1338impl<A: 'static> LayoutExt for Autocomplete<A> {
1339 fn layout_mut(&mut self) -> &mut LayoutStyle {
1340 &mut self.layout
1341 }
1342}
1343
1344impl<A: 'static> Autocomplete<A> {
1345 pub fn new() -> Self {
1358 Self {
1359 layout: LayoutStyle::default(),
1360 flex_item: FlexItemStyle::default(),
1361 value: None,
1362 placeholder: Binding::Static("Type to search...".to_string()),
1363 items: Vec::new(),
1364 disabled: Binding::Static(false),
1365 on_select: None,
1366 style: AutocompleteStyle::from_autocomplete_theme(
1367 Theme::default(),
1368 AutocompleteSize::Default,
1369 ),
1370 default_open: false,
1371 }
1372 }
1373
1374 pub fn bind(mut self, value: impl Into<Signal<String>>) -> Self {
1387 self.value = Some(value.into());
1388 self
1389 }
1390
1391 pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
1401 self.placeholder = placeholder.into();
1402 self
1403 }
1404
1405 pub fn suggestion(mut self, label: impl Into<String>) -> Self {
1415 self.items.push(AutocompleteItem::new(label));
1416 self
1417 }
1418
1419 pub fn autocomplete_item(mut self, item: AutocompleteItem) -> Self {
1430 self.items.push(item);
1431 self
1432 }
1433
1434 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1447 self.disabled = disabled.into();
1448 self
1449 }
1450
1451 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1462 self.disabled(disabled)
1463 }
1464
1465 pub fn default_open(mut self, open: bool) -> Self {
1475 self.default_open = open;
1476 self
1477 }
1478
1479 pub fn autocomplete_style(mut self, style: AutocompleteStyle) -> Self {
1490 self.style = style;
1491 self
1492 }
1493
1494 pub fn autocomplete_size(mut self, size: AutocompleteSize) -> Self {
1507 self.style = AutocompleteStyle::from_autocomplete_theme(Theme::default(), size);
1508 self
1509 }
1510
1511 pub fn on_select(mut self, f: impl Fn(String) -> A + 'static) -> Self {
1524 self.on_select = Some(Rc::new(move |ctx, value| ctx.dispatch(f(value))));
1525 self
1526 }
1527
1528 pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String) + 'static) -> Self {
1539 self.on_select = Some(Rc::new(f));
1540 self
1541 }
1542
1543 pub fn width(mut self, value: impl Into<Length>) -> Self {
1553 self.layout.width = value.into();
1554 self
1555 }
1556
1557 pub fn height(mut self, value: impl Into<Length>) -> Self {
1567 self.layout.height = value.into();
1568 self
1569 }
1570
1571 pub fn fill_width(mut self) -> Self {
1581 self.layout.width = Length::Fill;
1582 self
1583 }
1584
1585 pub fn flex_grow(mut self) -> Self {
1595 self.flex_item = self.flex_item.flex_grow(1.0);
1596 self
1597 }
1598}
1599
1600struct AutocompleteComponent<A> {
1602 layout: LayoutStyle,
1604 value: Option<Signal<String>>,
1606 placeholder: Binding<String>,
1608 items: Vec<AutocompleteItem>,
1610 disabled: Binding<bool>,
1612 on_select: Option<AutocompleteSelectHandler<A>>,
1614 style: AutocompleteStyle,
1616 default_open: bool,
1618}
1619
1620impl<A: 'static> ComponentNode<A> for AutocompleteComponent<A> {
1621 fn build(&self, context: &mut Context<A>) -> View<A> {
1623 let value = self
1624 .value
1625 .clone()
1626 .unwrap_or_else(|| context.signal(String::new()));
1627 let current = value.read();
1628 let buffer = context.signal(TextBuffer::from_string(current.clone()));
1629 let edit = context.signal(edit_at_end(¤t));
1630 let active_index = context.signal(None);
1631 let scroll = context.signal_with_invalidation(ScrollState::new(), Invalidation::Paint);
1632 let popup_id = context
1633 .runtime()
1634 .popup_id_for_element(context.element_id())
1635 .ok();
1636 let popup_content = autocomplete_popup_content(RetainedAutocompletePopup {
1637 value: value.clone(),
1638 items: self.items.clone(),
1639 disabled: self.disabled.clone(),
1640 on_select: self.on_select.clone(),
1641 style: self.style.clone(),
1642 active_index: active_index.clone(),
1643 scroll: scroll.clone(),
1644 buffer: buffer.clone(),
1645 edit: edit.clone(),
1646 popup_id,
1647 pending_scroll: Cell::new(None),
1648 });
1649 View::leaf(AutocompleteWidget {
1650 layout: self.layout,
1651 value: value.clone(),
1652 placeholder: self.placeholder.clone(),
1653 items: self.items.clone(),
1654 disabled: self.disabled.clone(),
1655 on_select: self.on_select.clone(),
1656 style: self.style.clone(),
1657 active_index,
1658 scroll,
1659 buffer,
1660 edit,
1661 pending_portal_close: Cell::new(None),
1662 popup: PopupPortalBridge::new_retained_with_content(
1663 context,
1664 listbox_popup_semantics(),
1665 self.default_open,
1666 popup_content,
1667 ),
1668 })
1669 }
1670}
1671
1672impl<A: 'static> IntoView<A> for Autocomplete<A> {
1673 fn into_view(self) -> View<A> {
1675 finish_view_sized(
1676 View::component(AutocompleteComponent {
1677 layout: self.layout,
1678 value: self.value,
1679 placeholder: self.placeholder,
1680 items: self.items,
1681 disabled: self.disabled,
1682 on_select: self.on_select,
1683 style: self.style,
1684 default_open: self.default_open,
1685 }),
1686 self.flex_item,
1687 LayoutSizeHint::from_layout(self.layout),
1688 )
1689 }
1690}
1691
1692struct AutocompleteWidget<A> {
1694 layout: LayoutStyle,
1696 value: Signal<String>,
1698 placeholder: Binding<String>,
1700 items: Vec<AutocompleteItem>,
1702 disabled: Binding<bool>,
1704 on_select: Option<AutocompleteSelectHandler<A>>,
1706 style: AutocompleteStyle,
1708 active_index: Signal<Option<usize>>,
1710 scroll: Signal<ScrollState>,
1712 buffer: Signal<TextBuffer>,
1714 edit: Signal<TextEditState>,
1716 pending_portal_close: Cell<Option<TransactionalLayoutPending<bool>>>,
1718 popup: PopupPortalBridge<A>,
1720}
1721
1722impl<A: 'static> Widget<A> for AutocompleteWidget<A> {
1723 fn debug_name(&self) -> &'static str {
1725 "Autocomplete"
1726 }
1727
1728 fn layout(
1730 &self,
1731 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1732 ctx: &mut LayoutCtx<'_>,
1733 _children: &mut [LayoutChild],
1734 constraints: Constraints,
1735 ) -> LayoutResult {
1736 let intrinsic = Size::new(self.style.width, self.style.height);
1737 let size = apply_layout_size(intrinsic, self.layout, constraints);
1738 let (_, text_layout) = layout_single_line_text(
1739 ctx,
1740 constraints,
1741 self.layout,
1742 &self.value,
1743 &self.buffer,
1744 &self.edit,
1745 Some(self.placeholder.read()),
1746 self.text_style(),
1747 );
1748 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1749 if ctx.layout_pass().is_committed() {
1750 self.pending_portal_close
1751 .set(TransactionalLayoutPending::new(ctx, self.disabled.read()));
1752 }
1753
1754 LayoutResult {
1755 size,
1756 children: Vec::new(),
1757 paint_bounds,
1758 visual_bounds: self.style.visual_bounds(paint_bounds),
1759 overlay_hit_bounds: Vec::new(),
1760 clip: None,
1761 is_window_root_clip: false,
1762 artifact: text_layout.map(LayoutArtifact::Text),
1763 }
1764 }
1765
1766 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
1768 if self
1769 .pending_portal_close
1770 .take()
1771 .and_then(|pending| pending.into_committed(ctx))
1772 == Some(true)
1773 {
1774 self.popup.close(PopupDismissReason::Programmatic);
1775 }
1776 }
1777
1778 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
1780 paint_autocomplete_input(ctx, bounds, layout, self);
1781 if self.popup.is_open() && !self.disabled.read() {
1782 self.popup
1783 .open_without_event(bounds, self.popup_rect(bounds));
1784 }
1785 }
1786
1787 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
1789 if self.disabled.read() {
1790 return;
1791 }
1792
1793 match event {
1794 Event::Focus(focus) if !focus.focused && self.popup.is_open() => {
1795 self.close(PopupDismissReason::OutsidePress);
1796 ctx.request_repaint();
1797 }
1798 Event::Pointer(PointerEvent::Button {
1799 pos,
1800 button: MouseButton::Left,
1801 pressed,
1802 ..
1803 }) if bounds.contains(pos.x, pos.y) => {
1804 if *pressed {
1805 self.open(ctx, bounds);
1806 }
1807 let _ = handle_single_line_text_event(
1808 ctx,
1809 event,
1810 bounds,
1811 layout,
1812 &self.value,
1813 &self.buffer,
1814 &self.edit,
1815 self.text_style(),
1816 TextFieldEventOptions {
1817 consume_handled_events: true,
1818 },
1819 );
1820 ctx.request_repaint();
1821 ctx.stop_propagation();
1822 }
1823 Event::Keyboard(key) if key.state == KeyState::Pressed => {
1824 self.handle_keyboard(ctx, &key.key, event, bounds, layout);
1825 }
1826 Event::Ime(_) => {
1827 let before = self.value.read();
1828 let handled = handle_single_line_text_event(
1829 ctx,
1830 event,
1831 bounds,
1832 layout,
1833 &self.value,
1834 &self.buffer,
1835 &self.edit,
1836 self.text_style(),
1837 TextFieldEventOptions {
1838 consume_handled_events: true,
1839 },
1840 );
1841 self.after_text_event(ctx, before, handled, bounds);
1842 }
1843 _ => {}
1844 }
1845 }
1846
1847 fn focus_policy(&self) -> FocusPolicy {
1849 if self.disabled.read() {
1850 FocusPolicy::NotFocusable
1851 } else {
1852 FocusPolicy::Focusable
1853 }
1854 }
1855
1856 fn activation_policy(&self) -> ActivationPolicy {
1858 ActivationPolicy::SuppressOnFocusOnly
1859 }
1860
1861 fn input_role(&self) -> InputRole {
1863 InputRole::TextSingleLine
1864 }
1865
1866 fn ime_cursor_rect(&self, bounds: Rect, layout: &LayoutResult) -> Option<Rect> {
1868 ime_cursor_rect(
1869 bounds,
1870 layout,
1871 &self.value,
1872 &self.buffer,
1873 &self.edit,
1874 self.text_style(),
1875 )
1876 }
1877}
1878
1879impl<A: 'static> AutocompleteWidget<A> {
1880 fn text_style(&self) -> TextInputStyle {
1882 if self.disabled.read() {
1883 let opacity = self.style.disabled_opacity;
1884 let mut input = self.style.input;
1885 input.bg = apply_opacity(input.bg, opacity);
1886 input.border = apply_opacity(input.border, opacity);
1887 input.border_focused = apply_opacity(input.border_focused, opacity);
1888 input.placeholder = apply_opacity(input.placeholder, opacity);
1889 input.text.color = apply_opacity(input.text.color, opacity);
1890 input
1891 } else {
1892 self.style.input
1893 }
1894 }
1895
1896 fn filtered_indices(&self) -> Vec<usize> {
1898 filtered_indices(
1899 &self.value.read(),
1900 self.items.iter().map(|item| &item.label),
1901 )
1902 }
1903
1904 fn popup_width(
1906 &self,
1907 trigger_width: f32,
1908 mut text_system: Option<&mut ailloli_ui_text::TextSystem>,
1909 ) -> f32 {
1910 self.items
1911 .iter()
1912 .map(|item| {
1913 let label = measure_text(
1914 text_system.as_deref_mut(),
1915 &item.label,
1916 self.style.popup.text,
1917 )
1918 .w;
1919 let icon = item
1920 .icon
1921 .as_ref()
1922 .map(|_| self.style.popup.icon_size + self.style.popup.icon_gap)
1923 .unwrap_or(0.0);
1924 label + icon + self.style.popup.padding_x * 2.0
1925 })
1926 .fold(self.style.width, f32::max)
1927 .max(trigger_width)
1928 .ceil()
1929 }
1930
1931 fn popup_height(&self) -> f32 {
1933 let rows = self.filtered_indices().len().max(1);
1934 (rows as f32 * self.style.popup.option_height).min(self.style.popup.popup_max_height)
1935 }
1936
1937 fn popup_rect(&self, bounds: Rect) -> Rect {
1939 Rect::new(
1940 bounds.x,
1941 bounds.bottom() + self.style.popup.popup_gap,
1942 self.popup_width(bounds.w, None),
1943 self.popup_height(),
1944 )
1945 }
1946
1947 fn open(&self, ctx: &EventCtx<A>, bounds: Rect) {
1949 self.active_index.set(self.first_enabled_index());
1950 self.popup.open(ctx, bounds, self.popup_rect(bounds));
1951 }
1952
1953 fn close(&self, reason: PopupDismissReason) {
1955 self.active_index.set(None);
1956 self.popup.close(reason);
1957 }
1958
1959 fn select_item(&self, ctx: &mut EventCtx<A>, index: usize) {
1961 let Some(item) = self.items.get(index) else {
1962 return;
1963 };
1964 if item.disabled.read() {
1965 return;
1966 }
1967 self.value.set(item.label.clone());
1968 self.buffer.set(TextBuffer::from_string(item.label.clone()));
1969 self.edit.set(edit_at_end(&item.label));
1970 if let Some(on_select) = &self.on_select {
1971 on_select(ctx, item.label.clone());
1972 }
1973 self.close(PopupDismissReason::Programmatic);
1974 ctx.request_repaint();
1975 ctx.stop_propagation();
1976 }
1977
1978 fn handle_keyboard(
1980 &self,
1981 ctx: &mut EventCtx<A>,
1982 key: &Key,
1983 event: &Event,
1984 bounds: Rect,
1985 layout: &LayoutResult,
1986 ) {
1987 if !self.popup.is_open() {
1988 if matches!(
1989 key,
1990 Key::Named(NamedKey::Enter)
1991 | Key::Named(NamedKey::ArrowDown)
1992 | Key::Named(NamedKey::ArrowUp)
1993 ) {
1994 self.open(ctx, bounds);
1995 ctx.request_repaint();
1996 ctx.stop_propagation();
1997 return;
1998 }
1999 } else {
2000 match key {
2001 Key::Named(NamedKey::Escape) => {
2002 self.close(PopupDismissReason::Escape);
2003 ctx.request_repaint();
2004 ctx.stop_propagation();
2005 return;
2006 }
2007 Key::Named(NamedKey::ArrowDown) => {
2008 self.move_active(ctx, Direction::Next);
2009 return;
2010 }
2011 Key::Named(NamedKey::ArrowUp) => {
2012 self.move_active(ctx, Direction::Previous);
2013 return;
2014 }
2015 Key::Named(NamedKey::Home) => {
2016 self.set_active(ctx, self.first_enabled_index());
2017 return;
2018 }
2019 Key::Named(NamedKey::End) => {
2020 self.set_active(ctx, self.last_enabled_index());
2021 return;
2022 }
2023 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
2024 if let Some(index) = self
2025 .active_index
2026 .read()
2027 .or_else(|| self.first_enabled_index())
2028 {
2029 self.select_item(ctx, index);
2030 }
2031 return;
2032 }
2033 _ => {}
2034 }
2035 }
2036
2037 let before = self.value.read();
2038 let handled = handle_single_line_text_event(
2039 ctx,
2040 event,
2041 bounds,
2042 layout,
2043 &self.value,
2044 &self.buffer,
2045 &self.edit,
2046 self.text_style(),
2047 TextFieldEventOptions {
2048 consume_handled_events: true,
2049 },
2050 );
2051 self.after_text_event(ctx, before, handled, bounds);
2052 }
2053
2054 fn after_text_event(&self, ctx: &mut EventCtx<A>, before: String, handled: bool, bounds: Rect) {
2056 if handled && self.value.read() != before {
2057 self.open(ctx, bounds);
2058 self.scroll.set(ScrollState::new());
2059 ctx.request_repaint();
2060 }
2061 }
2062
2063 fn move_active(&self, ctx: &mut EventCtx<A>, direction: Direction) {
2065 let next = match direction {
2066 Direction::Next => self.next_enabled_index(self.active_index.read()),
2067 Direction::Previous => self.previous_enabled_index(self.active_index.read()),
2068 };
2069 self.set_active(ctx, next);
2070 }
2071
2072 fn set_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
2074 if self.active_index.read() != next {
2075 self.active_index.set(next);
2076 ctx.request_repaint();
2077 }
2078 ctx.stop_propagation();
2079 }
2080
2081 fn first_enabled_index(&self) -> Option<usize> {
2083 self.filtered_indices()
2084 .into_iter()
2085 .find(|idx| !self.items[*idx].disabled.read())
2086 }
2087
2088 fn last_enabled_index(&self) -> Option<usize> {
2090 self.filtered_indices()
2091 .into_iter()
2092 .rev()
2093 .find(|idx| !self.items[*idx].disabled.read())
2094 }
2095
2096 fn next_enabled_index(&self, current: Option<usize>) -> Option<usize> {
2098 let filtered = self.filtered_indices();
2099 next_enabled(&filtered, current, |idx| !self.items[idx].disabled.read())
2100 }
2101
2102 fn previous_enabled_index(&self, current: Option<usize>) -> Option<usize> {
2104 let filtered = self.filtered_indices();
2105 previous_enabled(&filtered, current, |idx| !self.items[idx].disabled.read())
2106 }
2107}
2108
2109struct RetainedComboBoxPopup<T, A> {
2111 options: Vec<ComboBoxOption<T>>,
2113 selected: Option<Binding<T>>,
2115 bound: Option<Signal<T>>,
2117 disabled: Binding<bool>,
2119 on_change: Option<ComboChangeHandler<T, A>>,
2121 style: ComboBoxStyle,
2123 active_index: Signal<Option<usize>>,
2125 scroll: Signal<ScrollState>,
2127 query: Signal<String>,
2129 buffer: Signal<TextBuffer>,
2131 edit: Signal<TextEditState>,
2133 popup_id: Option<PopupId>,
2135 pending_scroll: Cell<Option<TransactionalLayoutPending<Option<ScrollState>>>>,
2137}
2138
2139impl<T: Clone, A> Clone for RetainedComboBoxPopup<T, A> {
2140 fn clone(&self) -> Self {
2142 Self {
2143 options: self.options.clone(),
2144 selected: self.selected.clone(),
2145 bound: self.bound.clone(),
2146 disabled: self.disabled.clone(),
2147 on_change: self.on_change.clone(),
2148 style: self.style.clone(),
2149 active_index: self.active_index.clone(),
2150 scroll: self.scroll.clone(),
2151 query: self.query.clone(),
2152 buffer: self.buffer.clone(),
2153 edit: self.edit.clone(),
2154 popup_id: self.popup_id,
2155 pending_scroll: Cell::new(None),
2156 }
2157 }
2158}
2159
2160impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for RetainedComboBoxPopup<T, A> {
2161 fn debug_name(&self) -> &'static str {
2163 "ComboBoxPopup"
2164 }
2165
2166 fn layout(
2168 &self,
2169 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
2170 ctx: &mut LayoutCtx<'_>,
2171 _children: &mut [LayoutChild],
2172 constraints: Constraints,
2173 ) -> LayoutResult {
2174 let rows = self.filtered_indices().len().max(1);
2175 let size = retained_popup_size(constraints, self.style.width, rows, &self.style.popup);
2176 if ctx.layout_pass().is_committed() {
2177 let retained = with_untracked_reads(|| self.scroll.read());
2178 let state = clamped_retained_popup_scroll(retained, size, rows, &self.style.popup);
2179 self.pending_scroll
2180 .set(TransactionalLayoutPending::new(ctx, state));
2181 }
2182 retained_popup_layout(size)
2183 }
2184
2185 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
2187 if let Some(state) = self
2188 .pending_scroll
2189 .take()
2190 .and_then(|pending| pending.into_committed(ctx))
2191 .flatten()
2192 {
2193 self.scroll.set(state);
2194 }
2195 }
2196
2197 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
2199 self.paint_popup(ctx, bounds);
2200 }
2201
2202 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
2204 if self.disabled.read() {
2205 self.close(ctx, PopupDismissReason::Programmatic);
2206 return;
2207 }
2208
2209 match event {
2210 Event::Pointer(PointerEvent::Moved { pos, .. }) => {
2211 let next = self
2212 .option_index_at(bounds, *pos)
2213 .filter(|index| !self.options[*index].disabled.read());
2214 self.set_active(next, ctx);
2215 }
2216 Event::Pointer(PointerEvent::Button {
2217 pos,
2218 button: MouseButton::Left,
2219 pressed: false,
2220 ..
2221 }) => {
2222 if let Some(index) = self.option_index_at(bounds, *pos) {
2223 self.select_index(ctx, index);
2224 }
2225 ctx.stop_propagation();
2226 }
2227 Event::Pointer(PointerEvent::Wheel {
2228 delta, modifiers, ..
2229 }) => {
2230 scroll_retained_popup(
2231 ctx,
2232 &self.scroll,
2233 *delta,
2234 *modifiers,
2235 Size::new(bounds.w, bounds.h),
2236 self.filtered_indices().len().max(1),
2237 &self.style.popup,
2238 );
2239 }
2240 Event::Pointer(PointerEvent::Cancelled { .. }) => self.set_active(None, ctx),
2241 _ => {}
2242 }
2243 }
2244
2245 fn focus_policy(&self) -> FocusPolicy {
2247 FocusPolicy::NotFocusable
2248 }
2249
2250 fn activation_policy(&self) -> ActivationPolicy {
2252 ActivationPolicy::SuppressOnFocusOnly
2253 }
2254
2255 fn hover_cursor_role_at(
2257 &self,
2258 bounds: Rect,
2259 _layout: &LayoutResult,
2260 pos: ailloli_ui_core::Point,
2261 ) -> HoverCursorRole {
2262 self.option_index_at(bounds, pos)
2263 .filter(|index| !self.options[*index].disabled.read())
2264 .map_or(HoverCursorRole::Default, |_| HoverCursorRole::Pointer)
2265 }
2266}
2267
2268impl<T: Clone + PartialEq + 'static, A: 'static> RetainedComboBoxPopup<T, A> {
2269 fn filtered_indices(&self) -> Vec<usize> {
2271 filtered_indices(
2272 &self.query.read(),
2273 self.options.iter().map(|option| &option.label),
2274 )
2275 }
2276
2277 fn option_index_at(&self, bounds: Rect, pos: ailloli_ui_core::Point) -> Option<usize> {
2279 retained_filtered_index_at(
2280 bounds,
2281 pos,
2282 self.scroll.read().offset.y,
2283 self.style.popup.option_height,
2284 &self.filtered_indices(),
2285 )
2286 }
2287
2288 fn selected_value(&self) -> Option<T> {
2290 self.selected.as_ref().map(Binding::read)
2291 }
2292
2293 fn selected_index(&self) -> Option<usize> {
2295 let selected = self.selected_value()?;
2296 self.options
2297 .iter()
2298 .position(|option| option.value == selected)
2299 }
2300
2301 fn paint_popup(&self, ctx: &mut PaintCtx<'_>, popup: Rect) {
2303 let filtered = self.filtered_indices();
2304 let selected = self.selected_index();
2305 paint_popup_shell(ctx, popup, &self.style.popup);
2306 ctx.with_overlay_clip(popup, |ctx| {
2307 if filtered.is_empty() {
2308 let row = Rect::new(popup.x, popup.y, popup.w, self.style.popup.option_height);
2309 paint_overlay_text_in_rect(
2310 ctx,
2311 "No results",
2312 self.style.popup.disabled_text,
2313 inset_rect_x(row, self.style.popup.padding_x),
2314 self.style.popup.disabled_opacity,
2315 );
2316 return;
2317 }
2318
2319 for (row_idx, option_idx) in filtered.iter().copied().enumerate() {
2320 let option = &self.options[option_idx];
2321 let row = Rect::new(
2322 popup.x,
2323 popup.y - self.scroll.read().offset.y
2324 + row_idx as f32 * self.style.popup.option_height,
2325 popup.w,
2326 self.style.popup.option_height,
2327 );
2328 if row.bottom() < popup.y || row.y > popup.bottom() {
2329 continue;
2330 }
2331 paint_popup_row(
2332 ctx,
2333 row,
2334 &option.label,
2335 option.icon.as_ref(),
2336 PopupRowState {
2337 disabled: option.disabled.read(),
2338 selected: selected == Some(option_idx),
2339 active: self.active_index.read() == Some(option_idx),
2340 },
2341 &self.style.popup,
2342 );
2343 if selected == Some(option_idx) {
2344 let check = Rect::new(
2345 row.right() - self.style.popup.padding_x - self.style.popup.icon_size,
2346 row.y + (row.h - self.style.popup.icon_size) * 0.5,
2347 self.style.popup.icon_size,
2348 self.style.popup.icon_size,
2349 );
2350 ctx.push_overlay(DrawCmd::Image(DrawImage {
2351 rect: check,
2352 icon: IconId::Check,
2353 tint: self.style.popup.selected_icon_tint,
2354 rotation_rad: 0.0,
2355 }));
2356 }
2357 }
2358 });
2359 paint_popup_border(ctx, popup, &self.style.popup);
2360 }
2361
2362 fn select_index(&self, ctx: &mut EventCtx<A>, index: usize) {
2364 let Some(option) = self.options.get(index) else {
2365 return;
2366 };
2367 if option.disabled.read() {
2368 return;
2369 }
2370
2371 let changed = self
2372 .selected_value()
2373 .as_ref()
2374 .is_none_or(|value| value != &option.value);
2375 if changed {
2376 let next = option.value.clone();
2377 if let Some(bound) = &self.bound {
2378 bound.set(next.clone());
2379 }
2380 if let Some(on_change) = &self.on_change {
2381 on_change(ctx, next);
2382 }
2383 }
2384
2385 self.query.set(option.label.clone());
2386 self.buffer
2387 .set(TextBuffer::from_string(option.label.clone()));
2388 self.edit.set(edit_at_end(&option.label));
2389 self.close(ctx, PopupDismissReason::Programmatic);
2390 }
2391
2392 fn set_active(&self, next: Option<usize>, ctx: &mut EventCtx<A>) {
2394 if self.active_index.read() != next {
2395 self.active_index.set(next);
2396 ctx.request_repaint();
2397 }
2398 }
2399
2400 fn close(&self, ctx: &mut EventCtx<A>, reason: PopupDismissReason) {
2402 self.active_index.set(None);
2403 if let Some(popup_id) = self.popup_id {
2404 ctx.runtime().close_popup(popup_id, reason);
2405 }
2406 ctx.request_repaint();
2407 ctx.stop_propagation();
2408 }
2409}
2410
2411struct RetainedAutocompletePopup<A> {
2413 value: Signal<String>,
2415 items: Vec<AutocompleteItem>,
2417 disabled: Binding<bool>,
2419 on_select: Option<AutocompleteSelectHandler<A>>,
2421 style: AutocompleteStyle,
2423 active_index: Signal<Option<usize>>,
2425 scroll: Signal<ScrollState>,
2427 buffer: Signal<TextBuffer>,
2429 edit: Signal<TextEditState>,
2431 popup_id: Option<PopupId>,
2433 pending_scroll: Cell<Option<TransactionalLayoutPending<Option<ScrollState>>>>,
2435}
2436
2437impl<A> Clone for RetainedAutocompletePopup<A> {
2438 fn clone(&self) -> Self {
2440 Self {
2441 value: self.value.clone(),
2442 items: self.items.clone(),
2443 disabled: self.disabled.clone(),
2444 on_select: self.on_select.clone(),
2445 style: self.style.clone(),
2446 active_index: self.active_index.clone(),
2447 scroll: self.scroll.clone(),
2448 buffer: self.buffer.clone(),
2449 edit: self.edit.clone(),
2450 popup_id: self.popup_id,
2451 pending_scroll: Cell::new(None),
2452 }
2453 }
2454}
2455
2456impl<A: 'static> Widget<A> for RetainedAutocompletePopup<A> {
2457 fn debug_name(&self) -> &'static str {
2459 "AutocompletePopup"
2460 }
2461
2462 fn layout(
2464 &self,
2465 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
2466 ctx: &mut LayoutCtx<'_>,
2467 _children: &mut [LayoutChild],
2468 constraints: Constraints,
2469 ) -> LayoutResult {
2470 let rows = self.filtered_indices().len().max(1);
2471 let size = retained_popup_size(constraints, self.style.width, rows, &self.style.popup);
2472 if ctx.layout_pass().is_committed() {
2473 let retained = with_untracked_reads(|| self.scroll.read());
2474 let state = clamped_retained_popup_scroll(retained, size, rows, &self.style.popup);
2475 self.pending_scroll
2476 .set(TransactionalLayoutPending::new(ctx, state));
2477 }
2478 retained_popup_layout(size)
2479 }
2480
2481 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
2483 if let Some(state) = self
2484 .pending_scroll
2485 .take()
2486 .and_then(|pending| pending.into_committed(ctx))
2487 .flatten()
2488 {
2489 self.scroll.set(state);
2490 }
2491 }
2492
2493 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
2495 self.paint_popup(ctx, bounds);
2496 }
2497
2498 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
2500 if self.disabled.read() {
2501 self.close(ctx, PopupDismissReason::Programmatic);
2502 return;
2503 }
2504
2505 match event {
2506 Event::Pointer(PointerEvent::Moved { pos, .. }) => {
2507 let next = self
2508 .item_index_at(bounds, *pos)
2509 .filter(|index| !self.items[*index].disabled.read());
2510 self.set_active(next, ctx);
2511 }
2512 Event::Pointer(PointerEvent::Button {
2513 pos,
2514 button: MouseButton::Left,
2515 pressed: false,
2516 ..
2517 }) => {
2518 if let Some(index) = self.item_index_at(bounds, *pos) {
2519 self.select_item(ctx, index);
2520 }
2521 ctx.stop_propagation();
2522 }
2523 Event::Pointer(PointerEvent::Wheel {
2524 delta, modifiers, ..
2525 }) => {
2526 scroll_retained_popup(
2527 ctx,
2528 &self.scroll,
2529 *delta,
2530 *modifiers,
2531 Size::new(bounds.w, bounds.h),
2532 self.filtered_indices().len().max(1),
2533 &self.style.popup,
2534 );
2535 }
2536 Event::Pointer(PointerEvent::Cancelled { .. }) => self.set_active(None, ctx),
2537 _ => {}
2538 }
2539 }
2540
2541 fn focus_policy(&self) -> FocusPolicy {
2543 FocusPolicy::NotFocusable
2544 }
2545
2546 fn activation_policy(&self) -> ActivationPolicy {
2548 ActivationPolicy::SuppressOnFocusOnly
2549 }
2550
2551 fn hover_cursor_role_at(
2553 &self,
2554 bounds: Rect,
2555 _layout: &LayoutResult,
2556 pos: ailloli_ui_core::Point,
2557 ) -> HoverCursorRole {
2558 self.item_index_at(bounds, pos)
2559 .filter(|index| !self.items[*index].disabled.read())
2560 .map_or(HoverCursorRole::Default, |_| HoverCursorRole::Pointer)
2561 }
2562}
2563
2564impl<A: 'static> RetainedAutocompletePopup<A> {
2565 fn filtered_indices(&self) -> Vec<usize> {
2567 filtered_indices(
2568 &self.value.read(),
2569 self.items.iter().map(|item| &item.label),
2570 )
2571 }
2572
2573 fn item_index_at(&self, bounds: Rect, pos: ailloli_ui_core::Point) -> Option<usize> {
2575 retained_filtered_index_at(
2576 bounds,
2577 pos,
2578 self.scroll.read().offset.y,
2579 self.style.popup.option_height,
2580 &self.filtered_indices(),
2581 )
2582 }
2583
2584 fn paint_popup(&self, ctx: &mut PaintCtx<'_>, popup: Rect) {
2586 let filtered = self.filtered_indices();
2587 paint_popup_shell(ctx, popup, &self.style.popup);
2588 ctx.with_overlay_clip(popup, |ctx| {
2589 if filtered.is_empty() {
2590 let row = Rect::new(popup.x, popup.y, popup.w, self.style.popup.option_height);
2591 paint_overlay_text_in_rect(
2592 ctx,
2593 "No results",
2594 self.style.popup.disabled_text,
2595 inset_rect_x(row, self.style.popup.padding_x),
2596 self.style.popup.disabled_opacity,
2597 );
2598 return;
2599 }
2600
2601 for (row_idx, item_idx) in filtered.iter().copied().enumerate() {
2602 let item = &self.items[item_idx];
2603 let row = Rect::new(
2604 popup.x,
2605 popup.y - self.scroll.read().offset.y
2606 + row_idx as f32 * self.style.popup.option_height,
2607 popup.w,
2608 self.style.popup.option_height,
2609 );
2610 if row.bottom() < popup.y || row.y > popup.bottom() {
2611 continue;
2612 }
2613 paint_popup_row(
2614 ctx,
2615 row,
2616 &item.label,
2617 item.icon.as_ref(),
2618 PopupRowState {
2619 disabled: item.disabled.read(),
2620 selected: false,
2621 active: self.active_index.read() == Some(item_idx),
2622 },
2623 &self.style.popup,
2624 );
2625 }
2626 });
2627 paint_popup_border(ctx, popup, &self.style.popup);
2628 }
2629
2630 fn select_item(&self, ctx: &mut EventCtx<A>, index: usize) {
2632 let Some(item) = self.items.get(index) else {
2633 return;
2634 };
2635 if item.disabled.read() {
2636 return;
2637 }
2638 self.value.set(item.label.clone());
2639 self.buffer.set(TextBuffer::from_string(item.label.clone()));
2640 self.edit.set(edit_at_end(&item.label));
2641 if let Some(on_select) = &self.on_select {
2642 on_select(ctx, item.label.clone());
2643 }
2644 self.close(ctx, PopupDismissReason::Programmatic);
2645 }
2646
2647 fn set_active(&self, next: Option<usize>, ctx: &mut EventCtx<A>) {
2649 if self.active_index.read() != next {
2650 self.active_index.set(next);
2651 ctx.request_repaint();
2652 }
2653 }
2654
2655 fn close(&self, ctx: &mut EventCtx<A>, reason: PopupDismissReason) {
2657 self.active_index.set(None);
2658 if let Some(popup_id) = self.popup_id {
2659 ctx.runtime().close_popup(popup_id, reason);
2660 }
2661 ctx.request_repaint();
2662 ctx.stop_propagation();
2663 }
2664}
2665
2666fn combo_box_popup_content<T: Clone + PartialEq + 'static, A: 'static>(
2668 popup: RetainedComboBoxPopup<T, A>,
2669) -> PopupContent<A> {
2670 PopupContent::new(move || View::leaf(popup.clone()))
2671}
2672
2673fn autocomplete_popup_content<A: 'static>(popup: RetainedAutocompletePopup<A>) -> PopupContent<A> {
2675 PopupContent::new(move || View::leaf(popup.clone()))
2676}
2677
2678fn retained_popup_size(
2680 constraints: Constraints,
2681 width: f32,
2682 rows: usize,
2683 style: &SelectStyle,
2684) -> Size {
2685 constraints.constrain(Size::new(
2686 width,
2687 (rows as f32 * style.option_height).min(style.popup_max_height),
2688 ))
2689}
2690
2691fn retained_popup_layout(size: Size) -> LayoutResult {
2693 let bounds = Rect::new(0.0, 0.0, size.w, size.h);
2694 LayoutResult {
2695 size,
2696 children: Vec::new(),
2697 paint_bounds: bounds,
2698 visual_bounds: bounds,
2699 overlay_hit_bounds: Vec::new(),
2700 clip: Some(ailloli_ui_core::ClipShape::Rect(bounds)),
2701 is_window_root_clip: false,
2702 artifact: None,
2703 }
2704}
2705
2706fn retained_filtered_index_at(
2711 bounds: Rect,
2712 pos: ailloli_ui_core::Point,
2713 scroll_y: f32,
2714 row_height: f32,
2715 filtered: &[usize],
2716) -> Option<usize> {
2717 if !bounds.contains(pos.x, pos.y) || row_height <= 0.0 {
2718 return None;
2719 }
2720 let row = ((pos.y - bounds.y + scroll_y) / row_height).floor() as usize;
2721 filtered.get(row).copied()
2722}
2723
2724fn clamped_retained_popup_scroll(
2726 scroll: ScrollState,
2727 viewport: Size,
2728 rows: usize,
2729 style: &SelectStyle,
2730) -> Option<ScrollState> {
2731 let content = Size::new(viewport.w, rows as f32 * style.option_height);
2732 let outcome = scroll.clamp_to(ScrollMetrics::new(viewport, content), ScrollAxes::VERTICAL);
2733 outcome.changed.then_some(outcome.state())
2734}
2735
2736fn scroll_retained_popup<A: 'static>(
2741 ctx: &mut EventCtx<A>,
2742 scroll: &Signal<ScrollState>,
2743 delta: WheelDelta,
2744 modifiers: ailloli_ui_core::event::Modifiers,
2745 viewport: Size,
2746 rows: usize,
2747 style: &SelectStyle,
2748) {
2749 let outcome = scroll_popup(
2750 &scroll.read(),
2751 delta,
2752 modifiers,
2753 viewport,
2754 Size::new(viewport.w, rows as f32 * style.option_height),
2755 style.option_height,
2756 ScrollAxes::VERTICAL,
2757 );
2758 if outcome.changed {
2759 scroll.set(outcome.state());
2760 ctx.request_repaint();
2761 ctx.stop_propagation();
2762 }
2763}
2764
2765#[derive(Debug, Clone, Copy)]
2766enum Direction {
2768 Next,
2770 Previous,
2772}
2773
2774fn edit_at_end(text: &str) -> TextEditState {
2776 let mut edit = TextEditState::new();
2777 let buffer = TextBuffer::from_string(text.to_string());
2778 edit.set_caret(&buffer, text.len(), false);
2779 edit
2780}
2781
2782fn selected_label<T: Clone + PartialEq>(
2784 options: &[ComboBoxOption<T>],
2785 selected: Option<&Binding<T>>,
2786) -> Option<String> {
2787 let selected = selected.map(Binding::read)?;
2788 options
2789 .iter()
2790 .find(|option| option.value == selected)
2791 .map(|option| option.label.clone())
2792}
2793
2794fn filtered_indices<'a>(query: &str, labels: impl Iterator<Item = &'a String>) -> Vec<usize> {
2798 let query = query.trim().to_ascii_lowercase();
2799 labels
2800 .enumerate()
2801 .filter_map(|(idx, label)| {
2802 (query.is_empty() || label.to_ascii_lowercase().contains(&query)).then_some(idx)
2803 })
2804 .collect()
2805}
2806
2807fn next_enabled(
2811 filtered: &[usize],
2812 current: Option<usize>,
2813 enabled: impl Fn(usize) -> bool,
2814) -> Option<usize> {
2815 if filtered.is_empty() {
2816 return None;
2817 }
2818 let start = current
2819 .and_then(|current| filtered.iter().position(|idx| *idx == current))
2820 .unwrap_or(filtered.len().saturating_sub(1));
2821 (1..=filtered.len())
2822 .map(|offset| filtered[(start + offset) % filtered.len()])
2823 .find(|idx| enabled(*idx))
2824}
2825
2826fn previous_enabled(
2830 filtered: &[usize],
2831 current: Option<usize>,
2832 enabled: impl Fn(usize) -> bool,
2833) -> Option<usize> {
2834 if filtered.is_empty() {
2835 return None;
2836 }
2837 let start = current
2838 .and_then(|current| filtered.iter().position(|idx| *idx == current))
2839 .unwrap_or(0);
2840 (1..=filtered.len())
2841 .map(|offset| filtered[(start + filtered.len() - offset) % filtered.len()])
2842 .find(|idx| enabled(*idx))
2843}
2844
2845fn text_edit_bounds(bounds: Rect, style: &ComboBoxStyle, has_trailing_icon: bool) -> Rect {
2847 if !has_trailing_icon {
2848 return bounds;
2849 }
2850 let reserve = style.input.pad_x + style.icon_size + style.icon_gap;
2851 Rect::new(bounds.x, bounds.y, (bounds.w - reserve).max(0.0), bounds.h)
2852}
2853
2854fn paint_input_frame(ctx: &mut PaintCtx<'_>, bounds: Rect, style: TextInputStyle, focused: bool) {
2856 ctx.push(DrawCmd::RRect(DrawRRect {
2857 rect: bounds,
2858 radius: style.radius,
2859 color: style.bg,
2860 }));
2861 ctx.push(DrawCmd::Border(DrawBorder {
2862 rect: bounds,
2863 radius: Radius::uniform(style.radius),
2864 border: ailloli_ui_core::style::Border::new(
2865 1.0,
2866 if focused {
2867 style.border_focused
2868 } else {
2869 style.border
2870 },
2871 ),
2872 }));
2873}
2874
2875fn paint_combo_input<T: Clone + PartialEq + 'static, A: 'static>(
2877 ctx: &mut PaintCtx<'_>,
2878 bounds: Rect,
2879 layout: &LayoutResult,
2880 widget: &ComboBoxWidget<T, A>,
2881 has_trailing_icon: bool,
2882) {
2883 let focused = ctx.is_focused();
2884 let style = widget.text_style();
2885 paint_input_frame(ctx, bounds, style, focused);
2886 paint_committed_single_line_text(
2887 ctx,
2888 text_edit_bounds(bounds, &widget.style, has_trailing_icon),
2889 layout,
2890 &widget.query,
2891 &widget.buffer,
2892 &widget.edit,
2893 Some(widget.placeholder.read()),
2894 style,
2895 focused,
2896 );
2897
2898 if has_trailing_icon {
2899 let icon = Rect::new(
2900 bounds.right() - widget.style.input.pad_x - widget.style.icon_size,
2901 bounds.y + (bounds.h - widget.style.icon_size) * 0.5,
2902 widget.style.icon_size,
2903 widget.style.icon_size,
2904 );
2905 ctx.push(DrawCmd::Image(DrawImage {
2906 rect: icon,
2907 icon: IconId::Lucide(Icon::ChevronDown),
2908 tint: if widget.disabled.read() {
2909 apply_opacity(
2910 widget.style.popup.disabled_icon_tint,
2911 widget.style.disabled_opacity,
2912 )
2913 } else {
2914 widget.style.popup.icon_tint
2915 },
2916 rotation_rad: 0.0,
2917 }));
2918 }
2919}
2920
2921fn paint_autocomplete_input<A: 'static>(
2923 ctx: &mut PaintCtx<'_>,
2924 bounds: Rect,
2925 layout: &LayoutResult,
2926 widget: &AutocompleteWidget<A>,
2927) {
2928 let focused = ctx.is_focused();
2929 let style = widget.text_style();
2930 paint_input_frame(ctx, bounds, style, focused);
2931 paint_committed_single_line_text(
2932 ctx,
2933 bounds,
2934 layout,
2935 &widget.value,
2936 &widget.buffer,
2937 &widget.edit,
2938 Some(widget.placeholder.read()),
2939 style,
2940 focused,
2941 );
2942}
2943
2944fn inset_rect_x(rect: Rect, inset: f32) -> Rect {
2946 Rect::new(
2947 rect.x + inset,
2948 rect.y,
2949 (rect.w - inset * 2.0).max(0.0),
2950 rect.h,
2951 )
2952}
2953
2954#[cfg(test)]
2955mod tests {
2956 use std::cell::RefCell;
2959 use std::panic::{catch_unwind, AssertUnwindSafe};
2960
2961 use super::*;
2962 use ailloli_ui_core::{Offset, Scale};
2963 use ailloli_ui_runtime::app::{Runtime, RuntimeHandle};
2964 use ailloli_ui_runtime::component::State;
2965 use ailloli_ui_runtime::layout::{ChildLayout, LayoutEngine};
2966 use ailloli_ui_text::TextSystem;
2967
2968 fn signal<T: 'static>(value: T) -> Signal<T> {
2970 Signal::new(Rc::new(RefCell::new(value)), Rc::new(|| {}))
2971 }
2972
2973 struct PanicAfterPopup {
2975 panic_now: State<bool>,
2976 }
2977
2978 impl Widget<()> for PanicAfterPopup {
2979 fn debug_name(&self) -> &'static str {
2980 "PanicAfterPopup"
2981 }
2982
2983 fn layout(
2984 &self,
2985 engine: &mut LayoutEngine<'_, ()>,
2986 ctx: &mut LayoutCtx<'_>,
2987 children: &mut [LayoutChild],
2988 constraints: Constraints,
2989 ) -> LayoutResult {
2990 let child = children.first_mut().expect("popup child").layout(
2991 engine,
2992 ctx,
2993 Constraints::tight(220.0, 64.0),
2994 );
2995 assert!(!self.panic_now.read(), "intentional outer layout panic");
2996 LayoutResult {
2997 size: constraints.max_size(),
2998 children: vec![ChildLayout {
2999 offset: Offset::new(7.0, 11.0),
3000 size: child.size,
3001 paint_bounds: child.paint_bounds,
3002 visual_bounds: child.visual_bounds,
3003 }],
3004 paint_bounds: Rect::new(0.0, 0.0, constraints.max_w, constraints.max_h),
3005 visual_bounds: Rect::new(0.0, 0.0, constraints.max_w, constraints.max_h),
3006 overlay_hit_bounds: Vec::new(),
3007 clip: None,
3008 is_window_root_clip: false,
3009 artifact: None,
3010 }
3011 }
3012
3013 fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
3014 }
3015
3016 struct RelayoutPopup {
3018 first_height: f32,
3020 final_height: f32,
3022 }
3023
3024 impl Widget<()> for RelayoutPopup {
3025 fn debug_name(&self) -> &'static str {
3026 "RelayoutPopup"
3027 }
3028
3029 fn layout(
3030 &self,
3031 engine: &mut LayoutEngine<'_, ()>,
3032 ctx: &mut LayoutCtx<'_>,
3033 children: &mut [LayoutChild],
3034 constraints: Constraints,
3035 ) -> LayoutResult {
3036 let child = children.first_mut().expect("popup child");
3037 let _ = child.layout(engine, ctx, Constraints::tight(220.0, self.first_height));
3038 let child = child.layout(engine, ctx, Constraints::tight(220.0, self.final_height));
3039 LayoutResult {
3040 size: constraints.max_size(),
3041 children: vec![ChildLayout {
3042 offset: Offset::new(9.0, 13.0),
3043 size: child.size,
3044 paint_bounds: child.paint_bounds,
3045 visual_bounds: child.visual_bounds,
3046 }],
3047 paint_bounds: Rect::new(0.0, 0.0, constraints.max_w, constraints.max_h),
3048 visual_bounds: Rect::new(0.0, 0.0, constraints.max_w, constraints.max_h),
3049 overlay_hit_bounds: Vec::new(),
3050 clip: None,
3051 is_window_root_clip: false,
3052 artifact: None,
3053 }
3054 }
3055
3056 fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
3057 }
3058
3059 #[test]
3060 fn abandoned_popup_layout_does_not_publish_a_nonzero_scroll_clamp() {
3061 let scroll = signal(ScrollState::with_offset(Offset::new(0.0, 400.0)));
3062 let popup: RetainedComboBoxPopup<(), ()> = RetainedComboBoxPopup {
3063 options: vec![ComboBoxOption::new((), "Only row")],
3064 selected: None,
3065 bound: None,
3066 disabled: Binding::Static(false),
3067 on_change: None,
3068 style: ComboBoxStyle::default(),
3069 active_index: signal(None),
3070 scroll: scroll.clone(),
3071 query: signal(String::new()),
3072 buffer: signal(TextBuffer::from_string(String::new())),
3073 edit: signal(edit_at_end("")),
3074 popup_id: None,
3075 pending_scroll: Cell::new(None),
3076 };
3077 let panic_now = State::new(true);
3078 let mut runtime = Runtime::new(RuntimeHandle::new());
3079 runtime.reconcile(View::node(
3080 PanicAfterPopup {
3081 panic_now: panic_now.clone(),
3082 },
3083 vec![View::leaf(popup)],
3084 ));
3085 let mut text_system = TextSystem::new();
3086
3087 let abandoned = catch_unwind(AssertUnwindSafe(|| {
3088 runtime.layout(
3089 Constraints::tight(240.0, 80.0),
3090 Scale::new(1.0),
3091 &mut text_system,
3092 );
3093 }));
3094 assert!(abandoned.is_err());
3095 assert_eq!(
3096 scroll.read().offset.y,
3097 400.0,
3098 "an abandoned attempt must not publish its staged clamp"
3099 );
3100
3101 panic_now.set(false);
3102 runtime.layout(
3103 Constraints::tight(240.0, 80.0),
3104 Scale::new(1.0),
3105 &mut text_system,
3106 );
3107 assert_eq!(
3108 scroll.read().offset.y,
3109 0.0,
3110 "the matching successful commit must publish the clamp"
3111 );
3112 }
3113
3114 #[test]
3115 fn final_same_attempt_popup_layout_cancels_an_earlier_clamp() {
3116 let scroll = signal(ScrollState::with_offset(Offset::new(0.0, 20.0)));
3117 let options = (0..10)
3118 .map(|index| ComboBoxOption::new(index, format!("Row {index}")))
3119 .collect();
3120 let popup: RetainedComboBoxPopup<usize, ()> = RetainedComboBoxPopup {
3121 options,
3122 selected: None,
3123 bound: None,
3124 disabled: Binding::Static(false),
3125 on_change: None,
3126 style: ComboBoxStyle::default(),
3127 active_index: signal(None),
3128 scroll: scroll.clone(),
3129 query: signal(String::new()),
3130 buffer: signal(TextBuffer::from_string(String::new())),
3131 edit: signal(edit_at_end("")),
3132 popup_id: None,
3133 pending_scroll: Cell::new(None),
3134 };
3135 let mut runtime = Runtime::new(RuntimeHandle::new());
3136 runtime.reconcile(View::node(
3137 RelayoutPopup {
3138 first_height: 400.0,
3139 final_height: 64.0,
3140 },
3141 vec![View::leaf(popup)],
3142 ));
3143 let mut text_system = TextSystem::new();
3144
3145 runtime.layout(
3146 Constraints::tight(240.0, 440.0),
3147 Scale::new(1.0),
3148 &mut text_system,
3149 );
3150
3151 assert_eq!(
3152 scroll.read().offset.y,
3153 20.0,
3154 "the final small viewport keeps the valid offset and cancels the earlier clamp"
3155 );
3156 }
3157
3158 #[test]
3159 fn final_same_attempt_popup_layout_publishes_a_late_clamp() {
3160 let scroll = signal(ScrollState::with_offset(Offset::new(0.0, 20.0)));
3161 let options = (0..10)
3162 .map(|index| ComboBoxOption::new(index, format!("Row {index}")))
3163 .collect();
3164 let popup: RetainedComboBoxPopup<usize, ()> = RetainedComboBoxPopup {
3165 options,
3166 selected: None,
3167 bound: None,
3168 disabled: Binding::Static(false),
3169 on_change: None,
3170 style: ComboBoxStyle::default(),
3171 active_index: signal(None),
3172 scroll: scroll.clone(),
3173 query: signal(String::new()),
3174 buffer: signal(TextBuffer::from_string(String::new())),
3175 edit: signal(edit_at_end("")),
3176 popup_id: None,
3177 pending_scroll: Cell::new(None),
3178 };
3179 let mut runtime = Runtime::new(RuntimeHandle::new());
3180 runtime.reconcile(View::node(
3181 RelayoutPopup {
3182 first_height: 64.0,
3183 final_height: 400.0,
3184 },
3185 vec![View::leaf(popup)],
3186 ));
3187 let mut text_system = TextSystem::new();
3188
3189 runtime.layout(
3190 Constraints::tight(240.0, 440.0),
3191 Scale::new(1.0),
3192 &mut text_system,
3193 );
3194
3195 assert_eq!(
3196 scroll.read().offset.y,
3197 0.0,
3198 "the final large viewport must publish its clamp after an earlier no-op"
3199 );
3200 }
3201
3202 #[test]
3203 fn abandoned_disabled_trigger_layout_does_not_close_its_popup() {
3204 let runtime_handle = RuntimeHandle::new();
3205 let mut runtime = Runtime::new(runtime_handle.clone());
3206 let panic_now = State::new(true);
3207 runtime.reconcile(View::node(
3208 PanicAfterPopup {
3209 panic_now: panic_now.clone(),
3210 },
3211 vec![ComboBox::<()>::new()
3212 .disabled(true)
3213 .default_open(true)
3214 .option((), "Only row")
3215 .into_view()],
3216 ));
3217 let popup_id = runtime_handle
3218 .popup_portal()
3219 .borrow()
3220 .topmost()
3221 .expect("default-open popup");
3222 assert!(runtime_handle.popup_is_open(popup_id));
3223 let mut text_system = TextSystem::new();
3224
3225 let abandoned = catch_unwind(AssertUnwindSafe(|| {
3226 runtime.layout(
3227 Constraints::tight(240.0, 80.0),
3228 Scale::new(1.0),
3229 &mut text_system,
3230 );
3231 }));
3232 assert!(abandoned.is_err());
3233 assert!(
3234 runtime_handle.popup_is_open(popup_id),
3235 "an abandoned disabled layout must not leak its close effect"
3236 );
3237
3238 panic_now.set(false);
3239 runtime.layout(
3240 Constraints::tight(240.0, 80.0),
3241 Scale::new(1.0),
3242 &mut text_system,
3243 );
3244 assert!(
3245 !runtime_handle.popup_is_open(popup_id),
3246 "the matching committed disabled layout must close the popup"
3247 );
3248 }
3249}