ailloli_ui_widgets/controls/
combo_box.rs

1//! Editable combo-box and free-text autocomplete controls.
2//!
3//! Both controls filter labels with a trimmed, ASCII-case-insensitive substring
4//! query, skip disabled rows during keyboard navigation, and mount their lists
5//! as retained listbox popups. A combo box selects typed values; autocomplete
6//! keeps arbitrary text and optionally commits a suggestion label.
7
8use 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)]
46/// Density preset used to derive [`ComboBoxStyle`].
47///
48/// # Examples
49///
50/// ```
51/// use ailloli_ui_widgets::controls::ComboBoxSize;
52/// assert_eq!(ComboBoxSize::default(), ComboBoxSize::Default);
53/// assert_ne!(ComboBoxSize::Compact, ComboBoxSize::Default);
54/// ```
55pub enum ComboBoxSize {
56    /// 180-by-30-logical-pixel compact preset.
57    Compact,
58    #[default]
59    /// 220-by-36-logical-pixel regular preset.
60    Default,
61}
62
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
64/// Density preset used to derive [`AutocompleteStyle`].
65///
66/// # Examples
67///
68/// ```
69/// use ailloli_ui_widgets::controls::AutocompleteSize;
70/// assert_eq!(AutocompleteSize::default(), AutocompleteSize::Default);
71/// assert_ne!(AutocompleteSize::Compact, AutocompleteSize::Default);
72/// ```
73pub enum AutocompleteSize {
74    /// 180-by-30-logical-pixel compact preset.
75    Compact,
76    #[default]
77    /// 220-by-36-logical-pixel regular preset.
78    Default,
79}
80
81#[derive(Clone, Debug)]
82/// Input, popup, geometry, and disabled appearance shared by both controls.
83///
84/// Dimensions are logical pixels. The default style is derived from the default
85/// theme and [`ComboBoxSize::Default`]; no public field is clamped or validated.
86///
87/// # Examples
88///
89/// ```
90/// use ailloli_ui_widgets::controls::ComboBoxStyle;
91/// let style = ComboBoxStyle::default();
92/// assert_eq!((style.width, style.height), (220.0, 36.0));
93/// assert_eq!(style.disabled_opacity, style.popup.disabled_opacity);
94/// ```
95pub struct ComboBoxStyle {
96    /// Editable trigger's text-input style.
97    pub input: TextInputStyle,
98    /// Retained listbox popup style.
99    pub popup: SelectStyle,
100    /// Preferred trigger width in logical pixels.
101    pub width: f32,
102    /// Preferred trigger height in logical pixels.
103    pub height: f32,
104    /// Trailing chevron and option icon size in logical pixels.
105    pub icon_size: f32,
106    /// Horizontal separation around icons in logical pixels.
107    pub icon_gap: f32,
108    /// Opacity multiplier applied while the whole control is disabled.
109    pub disabled_opacity: f32,
110}
111
112/// Style alias used by [`Autocomplete`].
113///
114/// # Examples
115///
116/// ```
117/// use ailloli_ui_widgets::controls::{AutocompleteStyle, ComboBoxStyle};
118/// let style: AutocompleteStyle = ComboBoxStyle::default();
119/// assert_eq!(style.width, 220.0);
120/// ```
121pub 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    /// Derives a combo-box style from `theme` and a density preset.
131    ///
132    /// `Compact` produces `180 x 30`; `Default` produces `220 x 36`, all in
133    /// logical pixels.
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use ailloli_ui_core::Theme;
139    /// use ailloli_ui_widgets::controls::{ComboBoxSize, ComboBoxStyle};
140    /// let compact = ComboBoxStyle::from_theme(Theme::default(), ComboBoxSize::Compact);
141    /// assert_eq!((compact.width, compact.height), (180.0, 30.0));
142    /// ```
143    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    /// Derives an autocomplete style by mapping its density to combo-box density.
175    ///
176    /// # Examples
177    ///
178    /// ```
179    /// use ailloli_ui_core::Theme;
180    /// use ailloli_ui_widgets::controls::{AutocompleteSize, AutocompleteStyle};
181    /// let style = AutocompleteStyle::from_autocomplete_theme(Theme::default(), AutocompleteSize::Default);
182    /// assert_eq!((style.width, style.height), (220.0, 36.0));
183    /// ```
184    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    /// Expands `rect` to include the popup style's focus ring and shadow.
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use ailloli_ui_widgets::controls::{ComboBox, ComboBoxStyle};
200    /// let combo: ComboBox<i32> = ComboBox::new().combo_style(ComboBoxStyle::default());
201    /// let _ = combo;
202    /// ```
203    pub(crate) fn visual_bounds(&self, rect: Rect) -> Rect {
204        self.popup.visual_bounds(rect)
205    }
206}
207
208#[derive(Clone)]
209/// Typed combo-box choice with a label, optional icon, and reactive availability.
210///
211/// Duplicate values and labels are allowed. Selection lookup uses the first
212/// equal value; a disabled option cannot be activated.
213///
214/// # Examples
215///
216/// ```
217/// use ailloli_ui_widgets::controls::ComboBoxOption;
218/// let option = ComboBoxOption::new(7, "Seven").disabled(false);
219/// let _ = option;
220/// ```
221pub struct ComboBoxOption<T> {
222    /// Typed value written or emitted on activation.
223    value: T,
224    /// Visible label used for filtering.
225    label: String,
226    /// Static or reactive disabled state.
227    disabled: Binding<bool>,
228    /// Optional leading icon.
229    icon: Option<IconId>,
230}
231
232impl<T> ComboBoxOption<T> {
233    /// Creates an enabled, iconless option and stores the label unchanged.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// use ailloli_ui_widgets::controls::ComboBoxOption;
239    /// let option = ComboBoxOption::new("id", "Visible label");
240    /// let _ = option;
241    /// ```
242    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    /// Replaces the option's static or reactive disabled binding.
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// use ailloli_ui_widgets::controls::ComboBoxOption;
257    /// let option = ComboBoxOption::new(1, "One").disabled(true);
258    /// let _ = option;
259    /// ```
260    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
261        self.disabled = disabled.into();
262        self
263    }
264
265    /// Uses a memo as the reactive disabled binding.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use ailloli_ui_runtime::component::Memo;
271    /// use ailloli_ui_widgets::controls::ComboBoxOption;
272    /// let option = ComboBoxOption::new(1, "One").disabled_signal(Memo::new(|| false));
273    /// let _ = option;
274    /// ```
275    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
276        self.disabled(disabled)
277    }
278
279    /// Sets the leading icon, replacing any previous one.
280    ///
281    /// # Examples
282    ///
283    /// ```
284    /// use ailloli_ui_core::IconId;
285    /// use ailloli_ui_widgets::controls::ComboBoxOption;
286    /// let option = ComboBoxOption::new(1, "History").leading_icon(IconId::History);
287    /// let _ = option;
288    /// ```
289    pub fn leading_icon(mut self, icon: IconId) -> Self {
290        self.icon = Some(icon);
291        self
292    }
293}
294
295/// Shared context-aware callback for a newly selected typed value.
296type ComboChangeHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
297
298/// Editable, filtered single-selection control over typed values.
299///
300/// Selecting an enabled option updates a signal installed by [`Self::bind`] and
301/// invokes the change callback only when its value differs from the current one.
302/// [`Self::selected`] is read-only configuration and is not mutated internally.
303///
304/// # Examples
305///
306/// ```
307/// use ailloli_ui_widgets::controls::ComboBox;
308/// let combo: ComboBox<i32> = ComboBox::new().option(1, "One").selected(1);
309/// let _ = combo;
310/// ```
311pub struct ComboBox<T, A = ()> {
312    /// Trigger layout configured by the builder methods.
313    pub(crate) layout: LayoutStyle,
314    /// Flex-parent participation.
315    pub(crate) flex_item: FlexItemStyle,
316    /// Placeholder shown when the editable query is empty.
317    placeholder: Binding<String>,
318    /// Options in popup and filtering order.
319    options: Vec<ComboBoxOption<T>>,
320    /// Optional static/reactive selected value.
321    selected: Option<Binding<T>>,
322    /// Writable selection signal when bound through [`Self::bind`].
323    bound: Option<Signal<T>>,
324    /// Static or reactive whole-control disabled state.
325    disabled: Binding<bool>,
326    /// Optional typed selection callback.
327    on_change: Option<ComboChangeHandler<T, A>>,
328    /// Input and popup appearance.
329    style: ComboBoxStyle,
330    /// Initial query override; empty derives the selected option label.
331    default_query: String,
332    /// Whether the retained popup starts open.
333    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    /// Creates an enabled empty combo box with `Search...` placeholder.
350    ///
351    /// It has no selection, no callback, an empty initial query, and a closed
352    /// default popup.
353    ///
354    /// # Examples
355    ///
356    /// ```
357    /// use ailloli_ui_widgets::controls::ComboBox;
358    /// let combo: ComboBox<&'static str> = ComboBox::new();
359    /// let _ = combo;
360    /// ```
361    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    /// Replaces the static or reactive empty-query placeholder.
378    ///
379    /// # Examples
380    ///
381    /// ```
382    /// use ailloli_ui_widgets::controls::ComboBox;
383    /// let combo: ComboBox<i32> = ComboBox::new().placeholder("Choose...");
384    /// let _ = combo;
385    /// ```
386    pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
387        self.placeholder = placeholder.into();
388        self
389    }
390
391    /// Appends an enabled, iconless option.
392    ///
393    /// # Examples
394    ///
395    /// ```
396    /// use ailloli_ui_widgets::controls::ComboBox;
397    /// let combo: ComboBox<i32> = ComboBox::new().option(1, "One").option(2, "Two");
398    /// let _ = combo;
399    /// ```
400    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    /// Appends a fully configured option.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use ailloli_ui_widgets::controls::{ComboBox, ComboBoxOption};
411    /// let combo: ComboBox<i32> = ComboBox::new()
412    ///     .combo_option(ComboBoxOption::new(1, "One").disabled(true));
413    /// let _ = combo;
414    /// ```
415    pub fn combo_option(mut self, option: ComboBoxOption<T>) -> Self {
416        self.options.push(option);
417        self
418    }
419
420    /// Sets a read-only static or reactive selection and clears writable binding.
421    ///
422    /// Activating another option can still emit `on_change`, but cannot mutate
423    /// this selection. If duplicate values exist, the first equal option labels it.
424    ///
425    /// # Examples
426    ///
427    /// ```
428    /// use ailloli_ui_widgets::controls::ComboBox;
429    /// let combo: ComboBox<i32> = ComboBox::new().option(1, "One").selected(1);
430    /// let _ = combo;
431    /// ```
432    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    /// Binds a writable selection signal.
439    ///
440    /// Activating a different enabled option writes the signal before invoking
441    /// the change callback.
442    ///
443    /// # Examples
444    ///
445    /// ```
446    /// use ailloli_ui_runtime::component::State;
447    /// use ailloli_ui_widgets::controls::ComboBox;
448    /// let selected = State::new(1);
449    /// let combo: ComboBox<i32> = ComboBox::new().option(1, "One").bind(selected);
450    /// let _ = combo;
451    /// ```
452    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    /// Sets the static or reactive whole-control disabled state.
460    ///
461    /// Disabled combo boxes are not focusable, ignore events, and close an open
462    /// popup during layout.
463    ///
464    /// # Examples
465    ///
466    /// ```
467    /// use ailloli_ui_widgets::controls::ComboBox;
468    /// let combo: ComboBox<i32> = ComboBox::new().disabled(true);
469    /// let _ = combo;
470    /// ```
471    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
472        self.disabled = disabled.into();
473        self
474    }
475
476    /// Uses a memo as the reactive whole-control disabled binding.
477    ///
478    /// # Examples
479    ///
480    /// ```
481    /// use ailloli_ui_runtime::component::Memo;
482    /// use ailloli_ui_widgets::controls::ComboBox;
483    /// let combo: ComboBox<i32> = ComboBox::new().disabled_signal(Memo::new(|| false));
484    /// let _ = combo;
485    /// ```
486    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
487        self.disabled(disabled)
488    }
489
490    /// Sets the initial editable query, stored unchanged.
491    ///
492    /// An empty value derives the initial query from the selected option label;
493    /// a nonempty value takes precedence. Filtering trims and ASCII-lowercases it.
494    ///
495    /// # Examples
496    ///
497    /// ```
498    /// use ailloli_ui_widgets::controls::ComboBox;
499    /// let combo: ComboBox<i32> = ComboBox::new().option(1, "Apple").default_query("app");
500    /// let _ = combo;
501    /// ```
502    pub fn default_query(mut self, query: impl Into<String>) -> Self {
503        self.default_query = query.into();
504        self
505    }
506
507    /// Sets only the popup's initial open state.
508    ///
509    /// # Examples
510    ///
511    /// ```
512    /// use ailloli_ui_widgets::controls::ComboBox;
513    /// let combo: ComboBox<i32> = ComboBox::new().default_open(true);
514    /// let _ = combo;
515    /// ```
516    pub fn default_open(mut self, open: bool) -> Self {
517        self.default_open = open;
518        self
519    }
520
521    /// Replaces the input and popup style without altering explicit layout values.
522    ///
523    /// # Examples
524    ///
525    /// ```
526    /// use ailloli_ui_widgets::controls::{ComboBox, ComboBoxStyle};
527    /// let combo: ComboBox<i32> = ComboBox::new().combo_style(ComboBoxStyle::default());
528    /// let _ = combo;
529    /// ```
530    pub fn combo_style(mut self, style: ComboBoxStyle) -> Self {
531        self.style = style;
532        self
533    }
534
535    /// Re-derives the style from the default theme and requested density.
536    ///
537    /// This overwrites every prior style customization.
538    ///
539    /// # Examples
540    ///
541    /// ```
542    /// use ailloli_ui_widgets::controls::{ComboBox, ComboBoxSize};
543    /// let combo: ComboBox<i32> = ComboBox::new().combo_size(ComboBoxSize::Compact);
544    /// let _ = combo;
545    /// ```
546    pub fn combo_size(mut self, size: ComboBoxSize) -> Self {
547        self.style = ComboBoxStyle::from_theme(Theme::default(), size);
548        self
549    }
550
551    /// Dispatches the application action returned for a changed selection.
552    ///
553    /// Reselecting an equal value, selecting a disabled row, or activating an
554    /// out-of-range row emits nothing.
555    ///
556    /// # Examples
557    ///
558    /// ```
559    /// use ailloli_ui_widgets::controls::ComboBox;
560    /// let combo: ComboBox<i32, i32> = ComboBox::new().on_change(|value| value);
561    /// let _ = combo;
562    /// ```
563    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    /// Handles a changed selection with direct event-context access.
569    ///
570    /// # Examples
571    ///
572    /// ```
573    /// use ailloli_ui_widgets::controls::ComboBox;
574    /// let combo: ComboBox<i32> = ComboBox::new().on_change_ctx(|_ctx, _value| {});
575    /// let _ = combo;
576    /// ```
577    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    /// Sets the trigger layout width in logical pixels or another [`Length`].
583    ///
584    /// # Examples
585    ///
586    /// ```
587    /// use ailloli_ui_widgets::controls::ComboBox;
588    /// let combo: ComboBox<i32> = ComboBox::new().width(240.0);
589    /// let _ = combo;
590    /// ```
591    pub fn width(mut self, value: impl Into<Length>) -> Self {
592        self.layout.width = value.into();
593        self
594    }
595
596    /// Sets the trigger layout height in logical pixels or another [`Length`].
597    ///
598    /// # Examples
599    ///
600    /// ```
601    /// use ailloli_ui_widgets::controls::ComboBox;
602    /// let combo: ComboBox<i32> = ComboBox::new().height(40.0);
603    /// let _ = combo;
604    /// ```
605    pub fn height(mut self, value: impl Into<Length>) -> Self {
606        self.layout.height = value.into();
607        self
608    }
609
610    /// Makes the trigger fill its available horizontal layout space.
611    ///
612    /// # Examples
613    ///
614    /// ```
615    /// use ailloli_ui_widgets::controls::ComboBox;
616    /// let combo: ComboBox<i32> = ComboBox::new().fill_width();
617    /// let _ = combo;
618    /// ```
619    pub fn fill_width(mut self) -> Self {
620        self.layout.width = Length::Fill;
621        self
622    }
623
624    /// Sets the flex-grow factor to `1.0` without changing layout width.
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// use ailloli_ui_widgets::controls::ComboBox;
630    /// let combo: ComboBox<i32> = ComboBox::new().flex_grow();
631    /// let _ = combo;
632    /// ```
633    pub fn flex_grow(mut self) -> Self {
634        self.flex_item = self.flex_item.flex_grow(1.0);
635        self
636    }
637}
638
639/// Component that allocates editable state and the retained combo-box popup.
640struct ComboBoxComponent<T, A> {
641    /// Trigger layout snapshot.
642    layout: LayoutStyle,
643    /// Empty-query placeholder.
644    placeholder: Binding<String>,
645    /// Typed choices in source order.
646    options: Vec<ComboBoxOption<T>>,
647    /// Readable selection binding.
648    selected: Option<Binding<T>>,
649    /// Optional writable selection signal.
650    bound: Option<Signal<T>>,
651    /// Whole-control disabled binding.
652    disabled: Binding<bool>,
653    /// Selection callback.
654    on_change: Option<ComboChangeHandler<T, A>>,
655    /// Shared input and popup style.
656    style: ComboBoxStyle,
657    /// Initial query override.
658    default_query: String,
659    /// Initial popup visibility.
660    default_open: bool,
661}
662
663impl<T: Clone + PartialEq + 'static, A: 'static> ComponentNode<A> for ComboBoxComponent<T, A> {
664    /// Allocates query/edit/navigation signals and connects the retained popup.
665    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    /// Converts configuration into a sized reactive component view.
723    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
743/// Retained editable trigger that owns query, caret, navigation, and popup state.
744struct ComboBoxWidget<T, A> {
745    /// Runtime layout behavior.
746    layout: LayoutStyle,
747    /// Empty-query placeholder.
748    placeholder: Binding<String>,
749    /// Typed options.
750    options: Vec<ComboBoxOption<T>>,
751    /// Readable selected value.
752    selected: Option<Binding<T>>,
753    /// Optional writable selected value.
754    bound: Option<Signal<T>>,
755    /// Whole-control disabled binding.
756    disabled: Binding<bool>,
757    /// Changed-selection callback.
758    on_change: Option<ComboChangeHandler<T, A>>,
759    /// Shared input and popup style.
760    style: ComboBoxStyle,
761    /// Active source option index, not filtered-row index.
762    active_index: Signal<Option<usize>>,
763    /// Vertical retained-popup scroll state.
764    scroll: Signal<ScrollState>,
765    /// Editable query text.
766    query: Signal<String>,
767    /// Text-engine buffer synchronized with `query`.
768    buffer: Signal<TextBuffer>,
769    /// Caret and selection state synchronized with the buffer.
770    edit: Signal<TextEditState>,
771    /// Disabled-state close staged for the exact authoritative layout attempt.
772    pending_portal_close: Cell<Option<TransactionalLayoutPending<bool>>>,
773    /// Runtime portal bridge for the retained popup.
774    popup: PopupPortalBridge<A>,
775}
776
777impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for ComboBoxWidget<T, A> {
778    /// Returns the stable diagnostic name.
779    fn debug_name(&self) -> &'static str {
780        "ComboBox"
781    }
782
783    /// Measures editing text and stages a disabled-state portal close.
784    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    /// Applies a disabled-state close only after its exact layout commits.
822    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    /// Paints the trigger and refreshes an open popup's desired rectangle.
834    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    /// Routes focus, pointer, keyboard, and IME events into editing or navigation.
843    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    /// Makes enabled controls focusable and disabled controls non-focusable.
903    fn focus_policy(&self) -> FocusPolicy {
904        if self.disabled.read() {
905            FocusPolicy::NotFocusable
906        } else {
907            FocusPolicy::Focusable
908        }
909    }
910
911    /// Prevents focus-only activation from opening the popup.
912    fn activation_policy(&self) -> ActivationPolicy {
913        ActivationPolicy::SuppressOnFocusOnly
914    }
915
916    /// Advertises single-line text input to platform IME integration.
917    fn input_role(&self) -> InputRole {
918        InputRole::TextSingleLine
919    }
920
921    /// Returns the current caret rectangle within icon-reserved edit bounds.
922    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    /// Returns input styling with disabled opacity applied to visible colors.
936    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    /// Clones the currently configured selection, if any.
952    fn selected_value(&self) -> Option<T> {
953        self.selected.as_ref().map(Binding::read)
954    }
955
956    /// Finds the first option whose value equals the current selection.
957    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    /// Returns source indices whose labels contain the normalized query.
965    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    /// Measures an integral popup width covering every option and the trigger.
973    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    /// Returns at least one row of height, capped by popup maximum height.
1004    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    /// Places the desired popup below the trigger before viewport resolution.
1010    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    /// Activates the first enabled filtered row and opens the popup.
1020    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    /// Closes and restores the first selected label, or empty text when unselected.
1026    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    /// Closes while preserving the current query and caret state.
1041    fn close_keep_query(&self, reason: PopupDismissReason) {
1042        self.active_index.set(None);
1043        self.popup.close(reason);
1044    }
1045
1046    /// Commits an enabled source option and closes while showing its label.
1047    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    /// Routes popup navigation keys or delegates remaining input editing keys.
1079    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    /// Reopens and resets popup scrolling after a handled query change.
1155    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    /// Moves active selection cyclically to another enabled filtered option.
1164    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    /// Updates the active source index, repaints on change, and consumes the event.
1173    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    /// Finds the first enabled source index in filtered order.
1182    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    /// Finds the last enabled source index in filtered order.
1189    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    /// Finds the cyclic next enabled source index.
1197    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    /// Finds the cyclic previous enabled source index.
1203    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)]
1210/// Autocomplete suggestion with optional icon and reactive availability.
1211///
1212/// The label is both visible text and the exact value committed on activation.
1213/// Duplicate and empty labels are allowed.
1214///
1215/// # Examples
1216///
1217/// ```
1218/// use ailloli_ui_widgets::controls::AutocompleteItem;
1219/// let item = AutocompleteItem::new("Apricot").disabled(false);
1220/// let _ = item;
1221/// ```
1222pub struct AutocompleteItem {
1223    /// Visible, filterable, and committed text.
1224    label: String,
1225    /// Static or reactive disabled state.
1226    disabled: Binding<bool>,
1227    /// Optional leading icon.
1228    icon: Option<IconId>,
1229}
1230
1231impl AutocompleteItem {
1232    /// Creates an enabled, iconless item and stores its label unchanged.
1233    ///
1234    /// # Examples
1235    ///
1236    /// ```
1237    /// use ailloli_ui_widgets::controls::AutocompleteItem;
1238    /// let item = AutocompleteItem::new("Apple");
1239    /// let _ = item;
1240    /// ```
1241    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    /// Replaces the item's static or reactive disabled binding.
1250    ///
1251    /// # Examples
1252    ///
1253    /// ```
1254    /// use ailloli_ui_widgets::controls::AutocompleteItem;
1255    /// let item = AutocompleteItem::new("Unavailable").disabled(true);
1256    /// let _ = item;
1257    /// ```
1258    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1259        self.disabled = disabled.into();
1260        self
1261    }
1262
1263    /// Uses a memo as the reactive disabled binding.
1264    ///
1265    /// # Examples
1266    ///
1267    /// ```
1268    /// use ailloli_ui_runtime::component::Memo;
1269    /// use ailloli_ui_widgets::controls::AutocompleteItem;
1270    /// let item = AutocompleteItem::new("Apple").disabled_signal(Memo::new(|| false));
1271    /// let _ = item;
1272    /// ```
1273    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1274        self.disabled(disabled)
1275    }
1276
1277    /// Sets the leading icon, replacing any previous one.
1278    ///
1279    /// # Examples
1280    ///
1281    /// ```
1282    /// use ailloli_ui_core::IconId;
1283    /// use ailloli_ui_widgets::controls::AutocompleteItem;
1284    /// let item = AutocompleteItem::new("History").leading_icon(IconId::History);
1285    /// let _ = item;
1286    /// ```
1287    pub fn leading_icon(mut self, icon: IconId) -> Self {
1288        self.icon = Some(icon);
1289        self
1290    }
1291}
1292
1293/// Shared context-aware callback for an activated suggestion label.
1294type AutocompleteSelectHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, String)>;
1295
1296/// Editable free-text field with a filtered suggestion popup.
1297///
1298/// Typing always updates the bound text signal. Activating an enabled suggestion
1299/// replaces it with the suggestion label and invokes `on_select`; arbitrary text
1300/// remains valid and need not match an item.
1301///
1302/// # Examples
1303///
1304/// ```
1305/// use ailloli_ui_runtime::component::State;
1306/// use ailloli_ui_widgets::controls::Autocomplete;
1307/// let value = State::new(String::new());
1308/// let autocomplete: Autocomplete<()> = Autocomplete::new().bind(value).suggestion("Apple");
1309/// let _ = autocomplete;
1310/// ```
1311pub struct Autocomplete<A = ()> {
1312    /// Trigger layout configured by the builder methods.
1313    pub(crate) layout: LayoutStyle,
1314    /// Flex-parent participation.
1315    pub(crate) flex_item: FlexItemStyle,
1316    /// Optional externally writable text; internal state is allocated when absent.
1317    value: Option<Signal<String>>,
1318    /// Placeholder shown for empty text.
1319    placeholder: Binding<String>,
1320    /// Suggestions in filtering and popup order.
1321    items: Vec<AutocompleteItem>,
1322    /// Static or reactive whole-control disabled state.
1323    disabled: Binding<bool>,
1324    /// Optional suggestion activation callback.
1325    on_select: Option<AutocompleteSelectHandler<A>>,
1326    /// Input and popup appearance.
1327    style: AutocompleteStyle,
1328    /// Whether the retained popup starts open.
1329    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    /// Creates an enabled, unbound autocomplete with no suggestions.
1346    ///
1347    /// The placeholder is `Type to search...`, the popup starts closed, and an
1348    /// internal empty text signal is allocated when the component builds.
1349    ///
1350    /// # Examples
1351    ///
1352    /// ```
1353    /// use ailloli_ui_widgets::controls::Autocomplete;
1354    /// let autocomplete: Autocomplete<()> = Autocomplete::new();
1355    /// let _ = autocomplete;
1356    /// ```
1357    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    /// Binds the editable text to a writable signal.
1375    ///
1376    /// Both free typing and suggestion activation update this signal.
1377    ///
1378    /// # Examples
1379    ///
1380    /// ```
1381    /// use ailloli_ui_runtime::component::State;
1382    /// use ailloli_ui_widgets::controls::Autocomplete;
1383    /// let autocomplete: Autocomplete<()> = Autocomplete::new().bind(State::new("ap".to_string()));
1384    /// let _ = autocomplete;
1385    /// ```
1386    pub fn bind(mut self, value: impl Into<Signal<String>>) -> Self {
1387        self.value = Some(value.into());
1388        self
1389    }
1390
1391    /// Replaces the static or reactive empty-text placeholder.
1392    ///
1393    /// # Examples
1394    ///
1395    /// ```
1396    /// use ailloli_ui_widgets::controls::Autocomplete;
1397    /// let autocomplete: Autocomplete<()> = Autocomplete::new().placeholder("Find fruit...");
1398    /// let _ = autocomplete;
1399    /// ```
1400    pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
1401        self.placeholder = placeholder.into();
1402        self
1403    }
1404
1405    /// Appends an enabled, iconless suggestion.
1406    ///
1407    /// # Examples
1408    ///
1409    /// ```
1410    /// use ailloli_ui_widgets::controls::Autocomplete;
1411    /// let autocomplete: Autocomplete<()> = Autocomplete::new().suggestion("Apple");
1412    /// let _ = autocomplete;
1413    /// ```
1414    pub fn suggestion(mut self, label: impl Into<String>) -> Self {
1415        self.items.push(AutocompleteItem::new(label));
1416        self
1417    }
1418
1419    /// Appends a fully configured suggestion.
1420    ///
1421    /// # Examples
1422    ///
1423    /// ```
1424    /// use ailloli_ui_widgets::controls::{Autocomplete, AutocompleteItem};
1425    /// let autocomplete: Autocomplete<()> = Autocomplete::new()
1426    ///     .autocomplete_item(AutocompleteItem::new("Apple").disabled(true));
1427    /// let _ = autocomplete;
1428    /// ```
1429    pub fn autocomplete_item(mut self, item: AutocompleteItem) -> Self {
1430        self.items.push(item);
1431        self
1432    }
1433
1434    /// Sets the static or reactive whole-control disabled state.
1435    ///
1436    /// Disabled autocomplete fields are not focusable, ignore events, and close
1437    /// an open popup during layout.
1438    ///
1439    /// # Examples
1440    ///
1441    /// ```
1442    /// use ailloli_ui_widgets::controls::Autocomplete;
1443    /// let autocomplete: Autocomplete<()> = Autocomplete::new().disabled(true);
1444    /// let _ = autocomplete;
1445    /// ```
1446    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1447        self.disabled = disabled.into();
1448        self
1449    }
1450
1451    /// Uses a memo as the reactive whole-control disabled binding.
1452    ///
1453    /// # Examples
1454    ///
1455    /// ```
1456    /// use ailloli_ui_runtime::component::Memo;
1457    /// use ailloli_ui_widgets::controls::Autocomplete;
1458    /// let autocomplete: Autocomplete<()> = Autocomplete::new().disabled_signal(Memo::new(|| false));
1459    /// let _ = autocomplete;
1460    /// ```
1461    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1462        self.disabled(disabled)
1463    }
1464
1465    /// Sets only the popup's initial open state.
1466    ///
1467    /// # Examples
1468    ///
1469    /// ```
1470    /// use ailloli_ui_widgets::controls::Autocomplete;
1471    /// let autocomplete: Autocomplete<()> = Autocomplete::new().default_open(true);
1472    /// let _ = autocomplete;
1473    /// ```
1474    pub fn default_open(mut self, open: bool) -> Self {
1475        self.default_open = open;
1476        self
1477    }
1478
1479    /// Replaces the input and popup style without altering explicit layout values.
1480    ///
1481    /// # Examples
1482    ///
1483    /// ```
1484    /// use ailloli_ui_widgets::controls::{Autocomplete, AutocompleteStyle};
1485    /// let autocomplete: Autocomplete<()> = Autocomplete::new()
1486    ///     .autocomplete_style(AutocompleteStyle::default());
1487    /// let _ = autocomplete;
1488    /// ```
1489    pub fn autocomplete_style(mut self, style: AutocompleteStyle) -> Self {
1490        self.style = style;
1491        self
1492    }
1493
1494    /// Re-derives the style from the default theme and requested density.
1495    ///
1496    /// This overwrites every prior style customization.
1497    ///
1498    /// # Examples
1499    ///
1500    /// ```
1501    /// use ailloli_ui_widgets::controls::{Autocomplete, AutocompleteSize};
1502    /// let autocomplete: Autocomplete<()> = Autocomplete::new()
1503    ///     .autocomplete_size(AutocompleteSize::Compact);
1504    /// let _ = autocomplete;
1505    /// ```
1506    pub fn autocomplete_size(mut self, size: AutocompleteSize) -> Self {
1507        self.style = AutocompleteStyle::from_autocomplete_theme(Theme::default(), size);
1508        self
1509    }
1510
1511    /// Dispatches the application action returned for an activated suggestion.
1512    ///
1513    /// The exact label is written to the bound signal before this callback. Free
1514    /// typing does not invoke it.
1515    ///
1516    /// # Examples
1517    ///
1518    /// ```
1519    /// use ailloli_ui_widgets::controls::Autocomplete;
1520    /// let autocomplete: Autocomplete<String> = Autocomplete::new().on_select(|label| label);
1521    /// let _ = autocomplete;
1522    /// ```
1523    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    /// Handles an activated suggestion with direct event-context access.
1529    ///
1530    /// # Examples
1531    ///
1532    /// ```
1533    /// use ailloli_ui_widgets::controls::Autocomplete;
1534    /// let autocomplete: Autocomplete<()> = Autocomplete::new()
1535    ///     .on_select_ctx(|_ctx, _label| {});
1536    /// let _ = autocomplete;
1537    /// ```
1538    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    /// Sets the trigger layout width in logical pixels or another [`Length`].
1544    ///
1545    /// # Examples
1546    ///
1547    /// ```
1548    /// use ailloli_ui_widgets::controls::Autocomplete;
1549    /// let autocomplete: Autocomplete<()> = Autocomplete::new().width(260.0);
1550    /// let _ = autocomplete;
1551    /// ```
1552    pub fn width(mut self, value: impl Into<Length>) -> Self {
1553        self.layout.width = value.into();
1554        self
1555    }
1556
1557    /// Sets the trigger layout height in logical pixels or another [`Length`].
1558    ///
1559    /// # Examples
1560    ///
1561    /// ```
1562    /// use ailloli_ui_widgets::controls::Autocomplete;
1563    /// let autocomplete: Autocomplete<()> = Autocomplete::new().height(40.0);
1564    /// let _ = autocomplete;
1565    /// ```
1566    pub fn height(mut self, value: impl Into<Length>) -> Self {
1567        self.layout.height = value.into();
1568        self
1569    }
1570
1571    /// Makes the trigger fill its available horizontal layout space.
1572    ///
1573    /// # Examples
1574    ///
1575    /// ```
1576    /// use ailloli_ui_widgets::controls::Autocomplete;
1577    /// let autocomplete: Autocomplete<()> = Autocomplete::new().fill_width();
1578    /// let _ = autocomplete;
1579    /// ```
1580    pub fn fill_width(mut self) -> Self {
1581        self.layout.width = Length::Fill;
1582        self
1583    }
1584
1585    /// Sets the flex-grow factor to `1.0` without changing layout width.
1586    ///
1587    /// # Examples
1588    ///
1589    /// ```
1590    /// use ailloli_ui_widgets::controls::Autocomplete;
1591    /// let autocomplete: Autocomplete<()> = Autocomplete::new().flex_grow();
1592    /// let _ = autocomplete;
1593    /// ```
1594    pub fn flex_grow(mut self) -> Self {
1595        self.flex_item = self.flex_item.flex_grow(1.0);
1596        self
1597    }
1598}
1599
1600/// Component that allocates free-text edit state and the retained suggestion popup.
1601struct AutocompleteComponent<A> {
1602    /// Trigger layout snapshot.
1603    layout: LayoutStyle,
1604    /// Optional externally owned text signal.
1605    value: Option<Signal<String>>,
1606    /// Empty-text placeholder.
1607    placeholder: Binding<String>,
1608    /// Suggestions in source order.
1609    items: Vec<AutocompleteItem>,
1610    /// Whole-control disabled binding.
1611    disabled: Binding<bool>,
1612    /// Suggestion activation callback.
1613    on_select: Option<AutocompleteSelectHandler<A>>,
1614    /// Shared input and popup style.
1615    style: AutocompleteStyle,
1616    /// Initial popup visibility.
1617    default_open: bool,
1618}
1619
1620impl<A: 'static> ComponentNode<A> for AutocompleteComponent<A> {
1621    /// Allocates missing text/edit/navigation signals and connects the popup.
1622    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(&current));
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    /// Converts configuration into a sized reactive component view.
1674    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
1692/// Retained free-text trigger with caret, navigation, scroll, and popup state.
1693struct AutocompleteWidget<A> {
1694    /// Runtime layout behavior.
1695    layout: LayoutStyle,
1696    /// Editable text signal.
1697    value: Signal<String>,
1698    /// Empty-text placeholder.
1699    placeholder: Binding<String>,
1700    /// Suggestions in source order.
1701    items: Vec<AutocompleteItem>,
1702    /// Whole-control disabled binding.
1703    disabled: Binding<bool>,
1704    /// Suggestion activation callback.
1705    on_select: Option<AutocompleteSelectHandler<A>>,
1706    /// Shared input and popup style.
1707    style: AutocompleteStyle,
1708    /// Active source item index, not filtered-row index.
1709    active_index: Signal<Option<usize>>,
1710    /// Vertical retained-popup scroll state.
1711    scroll: Signal<ScrollState>,
1712    /// Text-engine buffer synchronized with `value`.
1713    buffer: Signal<TextBuffer>,
1714    /// Caret and selection state synchronized with the buffer.
1715    edit: Signal<TextEditState>,
1716    /// Disabled-state close staged for the exact authoritative layout attempt.
1717    pending_portal_close: Cell<Option<TransactionalLayoutPending<bool>>>,
1718    /// Runtime portal bridge for the retained popup.
1719    popup: PopupPortalBridge<A>,
1720}
1721
1722impl<A: 'static> Widget<A> for AutocompleteWidget<A> {
1723    /// Returns the stable diagnostic name.
1724    fn debug_name(&self) -> &'static str {
1725        "Autocomplete"
1726    }
1727
1728    /// Measures editing text and stages a disabled-state portal close.
1729    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    /// Applies a disabled-state close only after its exact layout commits.
1767    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    /// Paints the free-text trigger and refreshes an open popup rectangle.
1779    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    /// Routes focus, pointer, keyboard, and IME events into editing or navigation.
1788    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    /// Makes enabled controls focusable and disabled controls non-focusable.
1848    fn focus_policy(&self) -> FocusPolicy {
1849        if self.disabled.read() {
1850            FocusPolicy::NotFocusable
1851        } else {
1852            FocusPolicy::Focusable
1853        }
1854    }
1855
1856    /// Prevents focus-only activation from opening the popup.
1857    fn activation_policy(&self) -> ActivationPolicy {
1858        ActivationPolicy::SuppressOnFocusOnly
1859    }
1860
1861    /// Advertises single-line text input to platform IME integration.
1862    fn input_role(&self) -> InputRole {
1863        InputRole::TextSingleLine
1864    }
1865
1866    /// Returns the current caret rectangle across the full trigger bounds.
1867    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    /// Returns input styling with disabled opacity applied to visible colors.
1881    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    /// Returns source indices whose labels contain the normalized free text.
1897    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    /// Measures an integral popup width covering every suggestion and trigger.
1905    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    /// Returns at least one row of height, capped by popup maximum height.
1932    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    /// Places the desired popup below the trigger before viewport resolution.
1938    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    /// Activates the first enabled filtered suggestion and opens the popup.
1948    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    /// Clears active navigation state and dismisses the popup.
1954    fn close(&self, reason: PopupDismissReason) {
1955        self.active_index.set(None);
1956        self.popup.close(reason);
1957    }
1958
1959    /// Commits an enabled suggestion label and invokes the callback.
1960    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    /// Routes popup navigation keys or delegates remaining text editing keys.
1979    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    /// Reopens and resets popup scrolling after a handled text change.
2055    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    /// Moves active selection cyclically to another enabled filtered suggestion.
2064    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    /// Updates the active source index, repaints on change, and consumes the event.
2073    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    /// Finds the first enabled source index in filtered order.
2082    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    /// Finds the last enabled source index in filtered order.
2089    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    /// Finds the cyclic next enabled source index.
2097    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    /// Finds the cyclic previous enabled source index.
2103    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
2109/// Popup-owned combo-box state rendered in the overlay presentation tree.
2110struct RetainedComboBoxPopup<T, A> {
2111    /// Typed options in source order.
2112    options: Vec<ComboBoxOption<T>>,
2113    /// Readable selected value.
2114    selected: Option<Binding<T>>,
2115    /// Optional writable selected value.
2116    bound: Option<Signal<T>>,
2117    /// Whole-control disabled binding.
2118    disabled: Binding<bool>,
2119    /// Changed-selection callback.
2120    on_change: Option<ComboChangeHandler<T, A>>,
2121    /// Shared style.
2122    style: ComboBoxStyle,
2123    /// Active source option index.
2124    active_index: Signal<Option<usize>>,
2125    /// Popup-local vertical scroll.
2126    scroll: Signal<ScrollState>,
2127    /// Editable trigger query.
2128    query: Signal<String>,
2129    /// Trigger text buffer synchronized on selection.
2130    buffer: Signal<TextBuffer>,
2131    /// Trigger caret state synchronized on selection.
2132    edit: Signal<TextEditState>,
2133    /// Runtime ID used to close the mounted popup.
2134    popup_id: Option<PopupId>,
2135    /// Scroll clamp staged for the exact authoritative layout attempt.
2136    pending_scroll: Cell<Option<TransactionalLayoutPending<Option<ScrollState>>>>,
2137}
2138
2139impl<T: Clone, A> Clone for RetainedComboBoxPopup<T, A> {
2140    /// Clones values and shares all binding, signal, callback, and popup handles.
2141    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    /// Returns the stable popup diagnostic name.
2162    fn debug_name(&self) -> &'static str {
2163        "ComboBoxPopup"
2164    }
2165
2166    /// Sizes by filtered rows and clamps the retained scroll offset.
2167    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    /// Publishes only the clamp computed by this exact successful attempt.
2186    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    /// Paints the popup shell, visible rows, selection mark, and border.
2198    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
2199        self.paint_popup(ctx, bounds);
2200    }
2201
2202    /// Routes hover, release selection, wheel scroll, and cancellation events.
2203    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    /// Keeps overlay popup rows outside the focus chain.
2246    fn focus_policy(&self) -> FocusPolicy {
2247        FocusPolicy::NotFocusable
2248    }
2249
2250    /// Suppresses activation synthesized solely from focus changes.
2251    fn activation_policy(&self) -> ActivationPolicy {
2252        ActivationPolicy::SuppressOnFocusOnly
2253    }
2254
2255    /// Uses a pointer cursor only over enabled filtered rows.
2256    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    /// Returns source option indices matching the normalized query.
2270    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    /// Maps a popup point and scroll offset to a source option index.
2278    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    /// Clones the currently configured selected value.
2289    fn selected_value(&self) -> Option<T> {
2290        self.selected.as_ref().map(Binding::read)
2291    }
2292
2293    /// Finds the first option equal to the current selection.
2294    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    /// Paints visible filtered rows or the one-row `No results` sentinel.
2302    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    /// Commits an enabled option, synchronizes trigger editing, and closes.
2363    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    /// Updates the active source index and repaints only when it changes.
2393    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    /// Clears navigation, closes the runtime popup when registered, and consumes input.
2401    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
2411/// Popup-owned autocomplete state rendered in the overlay presentation tree.
2412struct RetainedAutocompletePopup<A> {
2413    /// Editable trigger value.
2414    value: Signal<String>,
2415    /// Suggestions in source order.
2416    items: Vec<AutocompleteItem>,
2417    /// Whole-control disabled binding.
2418    disabled: Binding<bool>,
2419    /// Suggestion activation callback.
2420    on_select: Option<AutocompleteSelectHandler<A>>,
2421    /// Shared style.
2422    style: AutocompleteStyle,
2423    /// Active source item index.
2424    active_index: Signal<Option<usize>>,
2425    /// Popup-local vertical scroll.
2426    scroll: Signal<ScrollState>,
2427    /// Trigger text buffer synchronized on selection.
2428    buffer: Signal<TextBuffer>,
2429    /// Trigger caret state synchronized on selection.
2430    edit: Signal<TextEditState>,
2431    /// Runtime ID used to close the mounted popup.
2432    popup_id: Option<PopupId>,
2433    /// Scroll clamp staged for the exact authoritative layout attempt.
2434    pending_scroll: Cell<Option<TransactionalLayoutPending<Option<ScrollState>>>>,
2435}
2436
2437impl<A> Clone for RetainedAutocompletePopup<A> {
2438    /// Clones item values and shares all binding, signal, callback, and popup handles.
2439    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    /// Returns the stable popup diagnostic name.
2458    fn debug_name(&self) -> &'static str {
2459        "AutocompletePopup"
2460    }
2461
2462    /// Sizes by filtered rows and clamps the retained scroll offset.
2463    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    /// Publishes only the clamp computed by this exact successful attempt.
2482    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    /// Paints the popup shell, visible suggestions, and border.
2494    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
2495        self.paint_popup(ctx, bounds);
2496    }
2497
2498    /// Routes hover, release selection, wheel scroll, and cancellation events.
2499    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    /// Keeps overlay popup rows outside the focus chain.
2542    fn focus_policy(&self) -> FocusPolicy {
2543        FocusPolicy::NotFocusable
2544    }
2545
2546    /// Suppresses activation synthesized solely from focus changes.
2547    fn activation_policy(&self) -> ActivationPolicy {
2548        ActivationPolicy::SuppressOnFocusOnly
2549    }
2550
2551    /// Uses a pointer cursor only over enabled filtered suggestions.
2552    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    /// Returns source item indices matching the normalized free text.
2566    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    /// Maps a popup point and scroll offset to a source suggestion index.
2574    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    /// Paints visible filtered suggestions or the one-row `No results` sentinel.
2585    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    /// Commits an enabled suggestion, invokes its callback, and closes.
2631    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    /// Updates the active source index and repaints only when it changes.
2648    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    /// Clears navigation, closes the runtime popup when registered, and consumes input.
2656    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
2666/// Wraps clonable combo-box popup state in a retained popup factory.
2667fn 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
2673/// Wraps clonable autocomplete popup state in a retained popup factory.
2674fn autocomplete_popup_content<A: 'static>(popup: RetainedAutocompletePopup<A>) -> PopupContent<A> {
2675    PopupContent::new(move || View::leaf(popup.clone()))
2676}
2677
2678/// Constrains requested width and capped row height to popup constraints.
2679fn 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
2691/// Creates a leaf layout clipped exactly to its popup-local bounds.
2692fn 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
2706/// Converts a contained point to a filtered source index.
2707///
2708/// Returns `None` outside `bounds`, for nonpositive row height, or past the last
2709/// filtered row.
2710fn 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
2724/// Returns a changed vertical popup scroll clamped to row-derived content.
2725fn 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
2736/// Applies wheel scrolling in row-height line units.
2737///
2738/// The event is consumed only when the retained offset actually changes, so a
2739/// popup already at its limit can bubble the wheel gesture to an ancestor.
2740fn 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)]
2766/// Cyclic keyboard-navigation direction.
2767enum Direction {
2768    /// Move toward later filtered rows.
2769    Next,
2770    /// Move toward earlier filtered rows.
2771    Previous,
2772}
2773
2774/// Creates collapsed caret state at the UTF-8 byte end of `text`.
2775fn 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
2782/// Returns the first option label equal to a readable selection.
2783fn 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
2794/// Filters labels by a trimmed ASCII-case-insensitive substring query.
2795///
2796/// Empty-after-trimming queries retain every source index in original order.
2797fn 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
2807/// Finds the next enabled source index cyclically within filtered order.
2808///
2809/// With no current filtered index, traversal considers the first row first.
2810fn 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
2826/// Finds the previous enabled source index cyclically within filtered order.
2827///
2828/// With no current filtered index, traversal considers the last row first.
2829fn 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
2845/// Reserves nonnegative horizontal room for a trailing icon when present.
2846fn 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
2854/// Paints the input fill and a one-pixel focused or regular border.
2855fn 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
2875/// Paints combo-box editing state and its optional trailing chevron.
2876fn 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
2921/// Paints autocomplete editing state without a trailing icon.
2922fn 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
2944/// Applies a symmetric horizontal inset and floors the resulting width at zero.
2945fn 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    //! Transactional retained-popup scroll publication.
2957
2958    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    /// Creates a standalone signal for direct retained-popup construction.
2969    fn signal<T: 'static>(value: T) -> Signal<T> {
2970        Signal::new(Rc::new(RefCell::new(value)), Rc::new(|| {}))
2971    }
2972
2973    /// Lays out the popup child before optionally abandoning the outer attempt.
2974    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    /// Relayouts one child twice with independently selected viewport heights.
3017    struct RelayoutPopup {
3018        /// Viewport used by the first child layout call.
3019        first_height: f32,
3020        /// Viewport used by the authoritative final child layout call.
3021        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}