ailloli_ui_widgets/controls/
select.rs

1//! Typed select and action-menu dropdown controls with retained popups.
2//!
3//! Selects expose controlled single selection and optional signal writes;
4//! dropdowns run per-item actions without retaining a selection. Both skip
5//! disabled rows, support cyclic keyboard navigation, and scroll tall popups.
6
7use std::rc::Rc;
8
9use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
10use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
11use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey, WheelDelta};
12use ailloli_ui_core::geometry::{Constraints, Rect, Size};
13use ailloli_ui_core::scroll::{ScrollAxes, ScrollMetrics, ScrollState};
14use ailloli_ui_core::style::{
15    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Length, Radius,
16};
17use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
18use ailloli_ui_runtime::component::{
19    Binding, ComponentNode, Context, IntoView, Memo, Signal, View, Widget,
20};
21use ailloli_ui_runtime::input::{
22    ActivationPolicy, ClickAction, EventCtx, FocusPolicy, HoverCursorRole, IntoClickAction,
23};
24use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
25use ailloli_ui_runtime::popup::{PopupContent, PopupDismissReason, PopupId};
26use ailloli_ui_runtime::scene::PaintCtx;
27use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect};
28use ailloli_ui_text::TextSystem;
29use lucide_icons::Icon;
30
31use super::popup::{
32    apply_border_opacity, apply_opacity, listbox_popup_semantics, max_border_width, measure_text,
33    menu_popup_semantics, paint_popup_border, paint_popup_row, paint_popup_shell,
34    paint_text_in_rect, popup_rect_for_bounds, scroll_popup, union_rect, PopupPlacement,
35    PopupPortalBridge, PopupRowState,
36};
37
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39/// Density preset used to derive [`SelectStyle`].
40///
41/// # Examples
42///
43/// ```
44/// use ailloli_ui_widgets::controls::SelectSize;
45/// assert_eq!(SelectSize::default(), SelectSize::Default);
46/// assert_ne!(SelectSize::Compact, SelectSize::Default);
47/// ```
48pub enum SelectSize {
49    /// 180-by-30 trigger with 28-pixel rows.
50    Compact,
51    #[default]
52    /// 220-by-36 trigger with 32-pixel rows.
53    Default,
54}
55
56#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
57/// Density preset used to derive [`DropdownStyle`].
58///
59/// # Examples
60///
61/// ```
62/// use ailloli_ui_widgets::controls::DropdownSize;
63/// assert_eq!(DropdownSize::default(), DropdownSize::Default);
64/// assert_ne!(DropdownSize::Compact, DropdownSize::Default);
65/// ```
66pub enum DropdownSize {
67    /// 180-by-30 trigger with 28-pixel rows.
68    Compact,
69    #[default]
70    /// 220-by-36 trigger with 32-pixel rows.
71    Default,
72}
73
74#[derive(Clone, Debug, PartialEq)]
75/// Trigger, popup, row, typography, and focus appearance shared by both controls.
76///
77/// Dimensions are logical pixels and opacity is a multiplier. Public fields are
78/// used as supplied without validation. The default is the default theme's
79/// regular select preset.
80///
81/// # Examples
82///
83/// ```
84/// use ailloli_ui_widgets::controls::SelectStyle;
85/// let style = SelectStyle::default();
86/// assert_eq!((style.width, style.height, style.option_height), (220.0, 36.0, 32.0));
87/// assert_eq!(style.popup_max_height, 220.0);
88/// ```
89pub struct SelectStyle {
90    /// Resting trigger fill.
91    pub trigger_background: Color,
92    /// Hovered enabled trigger fill.
93    pub trigger_background_hovered: Color,
94    /// Pressed enabled trigger fill.
95    pub trigger_background_pressed: Color,
96    /// Popup surface fill.
97    pub popup_background: Color,
98    /// Reserved hovered row fill token.
99    pub option_hovered: Color,
100    /// Keyboard/pointer-active row fill.
101    pub option_active: Color,
102    /// Selected row fill.
103    pub option_selected: Color,
104    /// Resting trigger border.
105    pub border: Border,
106    /// Popup border.
107    pub popup_border: Border,
108    /// Focus ring border.
109    pub focus_ring: Border,
110    /// Popup shadows painted in order.
111    pub shadows: Vec<BoxShadow>,
112    /// Enabled trigger and row text.
113    pub text: TextStyle,
114    /// No-selection placeholder text.
115    pub placeholder_text: TextStyle,
116    /// Disabled row and trigger text.
117    pub disabled_text: TextStyle,
118    /// Enabled leading/trailing icon tint.
119    pub icon_tint: Color,
120    /// Selected checkmark tint.
121    pub selected_icon_tint: Color,
122    /// Disabled icon tint before opacity multiplication.
123    pub disabled_icon_tint: Color,
124    /// Minimum intrinsic trigger/popup width in logical pixels.
125    pub width: f32,
126    /// Preferred trigger height in logical pixels.
127    pub height: f32,
128    /// Popup row height in logical pixels.
129    pub option_height: f32,
130    /// Maximum popup height in logical pixels.
131    pub popup_max_height: f32,
132    /// Trigger-to-popup gap in logical pixels.
133    pub popup_gap: f32,
134    /// Trigger and popup corner radii.
135    pub radius: Radius,
136    /// Horizontal content padding in logical pixels.
137    pub padding_x: f32,
138    /// Option and chevron icon size in logical pixels.
139    pub icon_size: f32,
140    /// Horizontal icon/text gap in logical pixels.
141    pub icon_gap: f32,
142    /// Focus ring distance beyond trigger bounds in logical pixels.
143    pub focus_ring_offset: f32,
144    /// Disabled alpha multiplier.
145    pub disabled_opacity: f32,
146}
147
148/// Style alias used by [`Dropdown`].
149///
150/// # Examples
151///
152/// ```
153/// use ailloli_ui_widgets::controls::{DropdownStyle, SelectStyle};
154/// let style: DropdownStyle = SelectStyle::default();
155/// assert_eq!(style.height, 36.0);
156/// ```
157pub type DropdownStyle = SelectStyle;
158
159impl Default for SelectStyle {
160    fn default() -> Self {
161        Self::from_theme(Theme::default(), SelectSize::Default)
162    }
163}
164
165impl SelectStyle {
166    /// Derives a select style from `theme` and density.
167    ///
168    /// Compact uses `180 x 30` with 28-pixel rows and 12-pixel text; default
169    /// uses `220 x 36` with 32-pixel rows and 13-pixel text.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use ailloli_ui_core::Theme;
175    /// use ailloli_ui_widgets::controls::{SelectSize, SelectStyle};
176    /// let style = SelectStyle::from_theme(Theme::default(), SelectSize::Compact);
177    /// assert_eq!((style.width, style.height, style.option_height), (180.0, 30.0, 28.0));
178    /// ```
179    pub fn from_theme(theme: Theme, size: SelectSize) -> Self {
180        let palette = theme.palette();
181        let (width, height, option_height, padding_x, icon_size, text_size) = match size {
182            SelectSize::Compact => (180.0, 30.0, 28.0, 10.0, 14.0, 12),
183            SelectSize::Default => (220.0, 36.0, 32.0, 12.0, 16.0, 13),
184        };
185        let text = TextStyle::new(FontId::Ui, text_size, palette.text);
186        Self {
187            trigger_background: palette.surface_elevated,
188            trigger_background_hovered: Color::hex_rgb(0x20252A),
189            trigger_background_pressed: Color::hex_rgb(0x15191D),
190            popup_background: palette.surface_elevated,
191            option_hovered: Color::hex_rgb(0x20252A),
192            option_active: palette.accent.with_alpha(0.20),
193            option_selected: palette.accent.with_alpha(0.16),
194            border: Border::new(1.0, palette.border),
195            popup_border: Border::new(1.0, palette.border),
196            focus_ring: Border::new(2.0, palette.focus),
197            shadows: vec![theme.shadows().md],
198            text,
199            placeholder_text: TextStyle::new(FontId::Ui, text_size, palette.text_muted),
200            disabled_text: TextStyle::new(
201                FontId::Ui,
202                text_size,
203                palette.text_muted.with_alpha(0.70),
204            ),
205            icon_tint: palette.text_muted,
206            selected_icon_tint: palette.accent,
207            disabled_icon_tint: palette.text_muted.with_alpha(0.62),
208            width,
209            height,
210            option_height,
211            popup_max_height: 220.0,
212            popup_gap: 4.0,
213            radius: Radius::uniform(theme.radius().md),
214            padding_x,
215            icon_size,
216            icon_gap: 6.0,
217            focus_ring_offset: 3.0,
218            disabled_opacity: 0.45,
219        }
220    }
221
222    /// Derives dropdown style by mapping dropdown density to select density.
223    ///
224    /// # Examples
225    ///
226    /// ```
227    /// use ailloli_ui_core::Theme;
228    /// use ailloli_ui_widgets::controls::{DropdownSize, DropdownStyle};
229    /// let style = DropdownStyle::from_dropdown_theme(Theme::default(), DropdownSize::Compact);
230    /// assert_eq!((style.width, style.height), (180.0, 30.0));
231    /// ```
232    pub fn from_dropdown_theme(theme: Theme, size: DropdownSize) -> Self {
233        Self::from_theme(
234            theme,
235            match size {
236                DropdownSize::Compact => SelectSize::Compact,
237                DropdownSize::Default => SelectSize::Default,
238            },
239        )
240    }
241
242    /// Expands `rect` to include a visible focus ring and its offset.
243    ///
244    /// The union preserves the original rectangle; invisible focus rings add
245    /// nothing.
246    ///
247    /// # Examples
248    ///
249    /// ```
250    /// use ailloli_ui_widgets::controls::{Select, SelectStyle};
251    /// let select: Select<i32> = Select::new().select_style(SelectStyle::default());
252    /// let _ = select;
253    /// ```
254    pub(crate) fn visual_bounds(&self, rect: Rect) -> Rect {
255        let mut out = rect;
256        if self.focus_ring.is_visible() {
257            let inflate = self.focus_ring_offset + max_border_width(self.focus_ring);
258            out = union_rect(out, rect.inflate(inflate, inflate));
259        }
260        out
261    }
262}
263
264#[derive(Clone)]
265/// Typed select choice with a label, optional icon, and reactive availability.
266///
267/// Duplicate values and labels are allowed. Selection lookup uses the first
268/// equal value; a disabled option cannot be activated.
269///
270/// # Examples
271///
272/// ```
273/// use ailloli_ui_widgets::controls::SelectOption;
274/// let option = SelectOption::new(1, "One").disabled(false);
275/// let _ = option;
276/// ```
277pub struct SelectOption<T> {
278    /// Typed value written or emitted on activation.
279    value: T,
280    /// Visible label.
281    label: String,
282    /// Static or reactive disabled state.
283    disabled: Binding<bool>,
284    /// Optional leading icon.
285    icon: Option<IconId>,
286}
287
288impl<T> SelectOption<T> {
289    /// Creates an enabled, iconless option and stores its label unchanged.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use ailloli_ui_widgets::controls::SelectOption;
295    /// let option = SelectOption::new("id", "Visible label");
296    /// let _ = option;
297    /// ```
298    pub fn new(value: T, label: impl Into<String>) -> Self {
299        Self {
300            value,
301            label: label.into(),
302            disabled: Binding::Static(false),
303            icon: None,
304        }
305    }
306
307    /// Replaces the option's static or reactive disabled binding.
308    ///
309    /// # Examples
310    ///
311    /// ```
312    /// use ailloli_ui_widgets::controls::SelectOption;
313    /// let option = SelectOption::new(1, "One").disabled(true);
314    /// let _ = option;
315    /// ```
316    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
317        self.disabled = disabled.into();
318        self
319    }
320
321    /// Uses a memo as the reactive disabled binding.
322    ///
323    /// # Examples
324    ///
325    /// ```
326    /// use ailloli_ui_runtime::component::Memo;
327    /// use ailloli_ui_widgets::controls::SelectOption;
328    /// let option = SelectOption::new(1, "One").disabled_signal(Memo::new(|| false));
329    /// let _ = option;
330    /// ```
331    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
332        self.disabled(disabled)
333    }
334
335    /// Sets the leading icon, replacing any previous one.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// use ailloli_ui_core::IconId;
341    /// use ailloli_ui_widgets::controls::SelectOption;
342    /// let option = SelectOption::new(1, "History").leading_icon(IconId::History);
343    /// let _ = option;
344    /// ```
345    pub fn leading_icon(mut self, icon: IconId) -> Self {
346        self.icon = Some(icon);
347        self
348    }
349}
350
351/// Shared context-aware callback for a newly selected typed value.
352type SelectChangeHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
353
354/// Controlled single-selection trigger over typed values.
355///
356/// Selecting an enabled option updates a signal installed by [`Self::bind`] and
357/// invokes the callback only when its value differs from the current one.
358/// [`Self::selected`] is read-only configuration and is not mutated internally.
359///
360/// # Examples
361///
362/// ```
363/// use ailloli_ui_widgets::controls::Select;
364/// let select: Select<i32> = Select::new().option(1, "One").selected(1);
365/// let _ = select;
366/// ```
367pub struct Select<T, A = ()> {
368    /// Trigger layout configured by builder methods.
369    pub(crate) layout: LayoutStyle,
370    /// Flex-parent participation.
371    pub(crate) flex_item: FlexItemStyle,
372    /// No-selection trigger label.
373    placeholder: Binding<String>,
374    /// Options in popup order.
375    options: Vec<SelectOption<T>>,
376    /// Optional static/reactive selected value.
377    selected: Option<Binding<T>>,
378    /// Writable selected signal when bound through [`Self::bind`].
379    bound: Option<Signal<T>>,
380    /// Whole-control disabled binding.
381    disabled: Binding<bool>,
382    /// Changed-selection callback.
383    on_change: Option<SelectChangeHandler<T, A>>,
384    /// Trigger and popup appearance.
385    style: SelectStyle,
386    /// Preferred vertical popup side.
387    popup_placement: PopupPlacement,
388    /// Initial popup visibility.
389    default_open: bool,
390}
391
392impl<T: Clone + PartialEq + 'static, A: 'static> Default for Select<T, A> {
393    fn default() -> Self {
394        Self::new()
395    }
396}
397
398impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for Select<T, A> {
399    fn layout_mut(&mut self) -> &mut LayoutStyle {
400        &mut self.layout
401    }
402}
403
404impl<T: Clone + PartialEq + 'static, A: 'static> Select<T, A> {
405    /// Creates an enabled empty select with `Select option` placeholder.
406    ///
407    /// It has no selection or callback, prefers bottom placement, and starts
408    /// closed.
409    ///
410    /// # Examples
411    ///
412    /// ```
413    /// use ailloli_ui_widgets::controls::Select;
414    /// let select: Select<&'static str> = Select::new();
415    /// let _ = select;
416    /// ```
417    pub fn new() -> Self {
418        Self {
419            layout: LayoutStyle::default(),
420            flex_item: FlexItemStyle::default(),
421            placeholder: Binding::Static("Select option".to_string()),
422            options: Vec::new(),
423            selected: None,
424            bound: None,
425            disabled: Binding::Static(false),
426            on_change: None,
427            style: SelectStyle::default(),
428            popup_placement: PopupPlacement::Bottom,
429            default_open: false,
430        }
431    }
432
433    /// Replaces the static or reactive no-selection label.
434    ///
435    /// # Examples
436    ///
437    /// ```
438    /// use ailloli_ui_widgets::controls::Select;
439    /// let select: Select<i32> = Select::new().placeholder("Choose...");
440    /// let _ = select;
441    /// ```
442    pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
443        self.placeholder = placeholder.into();
444        self
445    }
446
447    /// Appends an enabled, iconless option.
448    ///
449    /// # Examples
450    ///
451    /// ```
452    /// use ailloli_ui_widgets::controls::Select;
453    /// let select: Select<i32> = Select::new().option(1, "One").option(2, "Two");
454    /// let _ = select;
455    /// ```
456    pub fn option(mut self, value: T, label: impl Into<String>) -> Self {
457        self.options.push(SelectOption::new(value, label));
458        self
459    }
460
461    /// Appends a fully configured option.
462    ///
463    /// # Examples
464    ///
465    /// ```
466    /// use ailloli_ui_widgets::controls::{Select, SelectOption};
467    /// let select: Select<i32> = Select::new()
468    ///     .select_option(SelectOption::new(1, "One").disabled(true));
469    /// let _ = select;
470    /// ```
471    pub fn select_option(mut self, option: SelectOption<T>) -> Self {
472        self.options.push(option);
473        self
474    }
475
476    /// Sets a read-only static or reactive selection and clears writable binding.
477    ///
478    /// Activating another value may emit the callback but cannot mutate this
479    /// selection. Duplicate values resolve to the first equal option.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use ailloli_ui_widgets::controls::Select;
485    /// let select: Select<i32> = Select::new().option(1, "One").selected(1);
486    /// let _ = select;
487    /// ```
488    pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
489        self.selected = Some(selected.into());
490        self.bound = None;
491        self
492    }
493
494    /// Binds a writable selection signal.
495    ///
496    /// Activating a different enabled option writes the signal before invoking
497    /// the change callback.
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// use ailloli_ui_runtime::component::State;
503    /// use ailloli_ui_widgets::controls::Select;
504    /// let select: Select<i32> = Select::new().option(1, "One").bind(State::new(1));
505    /// let _ = select;
506    /// ```
507    pub fn bind(mut self, selected: impl Into<Signal<T>>) -> Self {
508        let signal = selected.into();
509        self.selected = Some(Binding::Signal(signal.clone()));
510        self.bound = Some(signal);
511        self
512    }
513
514    /// Sets static or reactive whole-control disabled state.
515    ///
516    /// Disabled selects are not focusable, ignore events, and close an open popup
517    /// during layout.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use ailloli_ui_widgets::controls::Select;
523    /// let select: Select<i32> = Select::new().disabled(true);
524    /// let _ = select;
525    /// ```
526    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
527        self.disabled = disabled.into();
528        self
529    }
530
531    /// Uses a memo as the reactive whole-control disabled binding.
532    ///
533    /// # Examples
534    ///
535    /// ```
536    /// use ailloli_ui_runtime::component::Memo;
537    /// use ailloli_ui_widgets::controls::Select;
538    /// let select: Select<i32> = Select::new().disabled_signal(Memo::new(|| false));
539    /// let _ = select;
540    /// ```
541    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
542        self.disabled(disabled)
543    }
544
545    /// Sets only the retained popup's initial open state.
546    ///
547    /// # Examples
548    ///
549    /// ```
550    /// use ailloli_ui_widgets::controls::Select;
551    /// let select: Select<i32> = Select::new().default_open(true);
552    /// let _ = select;
553    /// ```
554    pub fn default_open(mut self, open: bool) -> Self {
555        self.default_open = open;
556        self
557    }
558
559    /// Sets the preferred [`PopupPlacement::Top`] or [`PopupPlacement::Bottom`] side.
560    ///
561    /// Runtime geometry may clamp the resulting rectangle; this builder does not
562    /// enable automatic side flipping.
563    ///
564    /// # Examples
565    ///
566    /// ```
567    /// use ailloli_ui_widgets::controls::{PopupPlacement, Select};
568    /// let select: Select<i32> = Select::new().popup_placement(PopupPlacement::Top);
569    /// let _ = select;
570    /// ```
571    pub fn popup_placement(mut self, placement: PopupPlacement) -> Self {
572        self.popup_placement = placement;
573        self
574    }
575
576    /// Replaces trigger and popup style without altering explicit layout values.
577    ///
578    /// # Examples
579    ///
580    /// ```
581    /// use ailloli_ui_widgets::controls::{Select, SelectStyle};
582    /// let select: Select<i32> = Select::new().select_style(SelectStyle::default());
583    /// let _ = select;
584    /// ```
585    pub fn select_style(mut self, style: SelectStyle) -> Self {
586        self.style = style;
587        self
588    }
589
590    /// Re-derives style from the default theme and requested density.
591    ///
592    /// This overwrites every previous select-style customization.
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// use ailloli_ui_widgets::controls::{Select, SelectSize};
598    /// let select: Select<i32> = Select::new().select_size(SelectSize::Compact);
599    /// let _ = select;
600    /// ```
601    pub fn select_size(mut self, size: SelectSize) -> Self {
602        self.style = SelectStyle::from_theme(Theme::default(), size);
603        self
604    }
605
606    /// Dispatches the application action returned for a changed selection.
607    ///
608    /// Equal values, disabled rows, and out-of-range indices emit nothing.
609    ///
610    /// # Examples
611    ///
612    /// ```
613    /// use ailloli_ui_widgets::controls::Select;
614    /// let select: Select<i32, i32> = Select::new().on_change(|value| value);
615    /// let _ = select;
616    /// ```
617    pub fn on_change(mut self, f: impl Fn(T) -> A + 'static) -> Self {
618        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
619        self
620    }
621
622    /// Handles a changed selection with direct event-context access.
623    ///
624    /// # Examples
625    ///
626    /// ```
627    /// use ailloli_ui_widgets::controls::Select;
628    /// let select: Select<i32> = Select::new().on_change_ctx(|_ctx, _value| {});
629    /// let _ = select;
630    /// ```
631    pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
632        self.on_change = Some(Rc::new(f));
633        self
634    }
635
636    /// Sets trigger layout width in logical pixels or another [`Length`].
637    ///
638    /// # Examples
639    ///
640    /// ```
641    /// use ailloli_ui_widgets::controls::Select;
642    /// let select: Select<i32> = Select::new().width(240.0);
643    /// let _ = select;
644    /// ```
645    pub fn width(mut self, value: impl Into<Length>) -> Self {
646        self.layout.width = value.into();
647        self
648    }
649
650    /// Sets trigger layout height in logical pixels or another [`Length`].
651    ///
652    /// # Examples
653    ///
654    /// ```
655    /// use ailloli_ui_widgets::controls::Select;
656    /// let select: Select<i32> = Select::new().height(40.0);
657    /// let _ = select;
658    /// ```
659    pub fn height(mut self, value: impl Into<Length>) -> Self {
660        self.layout.height = value.into();
661        self
662    }
663
664    /// Sets minimum trigger width in logical pixels or another [`Length`].
665    ///
666    /// # Examples
667    ///
668    /// ```
669    /// use ailloli_ui_widgets::controls::Select;
670    /// let select: Select<i32> = Select::new().min_width(120.0);
671    /// let _ = select;
672    /// ```
673    pub fn min_width(mut self, value: impl Into<Length>) -> Self {
674        self.layout.min_width = value.into();
675        self
676    }
677
678    /// Sets maximum trigger width in logical pixels or another [`Length`].
679    ///
680    /// # Examples
681    ///
682    /// ```
683    /// use ailloli_ui_widgets::controls::Select;
684    /// let select: Select<i32> = Select::new().max_width(360.0);
685    /// let _ = select;
686    /// ```
687    pub fn max_width(mut self, value: impl Into<Length>) -> Self {
688        self.layout.max_width = value.into();
689        self
690    }
691
692    /// Makes the trigger fill available horizontal layout space.
693    ///
694    /// # Examples
695    ///
696    /// ```
697    /// use ailloli_ui_widgets::controls::Select;
698    /// let select: Select<i32> = Select::new().fill_width();
699    /// let _ = select;
700    /// ```
701    pub fn fill_width(mut self) -> Self {
702        self.layout.width = Length::Fill;
703        self
704    }
705
706    /// Sets flex-grow factor to `1.0` without changing layout width.
707    ///
708    /// # Examples
709    ///
710    /// ```
711    /// use ailloli_ui_widgets::controls::Select;
712    /// let select: Select<i32> = Select::new().flex_grow();
713    /// let _ = select;
714    /// ```
715    pub fn flex_grow(mut self) -> Self {
716        self.flex_item = self.flex_item.flex_grow(1.0);
717        self
718    }
719}
720
721/// Component that allocates navigation/scroll state and retained listbox content.
722struct SelectComponent<T, A> {
723    /// Trigger layout snapshot.
724    layout: LayoutStyle,
725    /// No-selection label.
726    placeholder: Binding<String>,
727    /// Typed options.
728    options: Vec<SelectOption<T>>,
729    /// Readable selected value.
730    selected: Option<Binding<T>>,
731    /// Optional writable selected value.
732    bound: Option<Signal<T>>,
733    /// Whole-control disabled binding.
734    disabled: Binding<bool>,
735    /// Changed-selection callback.
736    on_change: Option<SelectChangeHandler<T, A>>,
737    /// Shared trigger/popup style.
738    style: SelectStyle,
739    /// Preferred popup side.
740    popup_placement: PopupPlacement,
741    /// Initial popup visibility.
742    default_open: bool,
743}
744
745impl<T: Clone + PartialEq + 'static, A: 'static> ComponentNode<A> for SelectComponent<T, A> {
746    /// Allocates active/scroll signals and connects retained popup content.
747    fn build(&self, context: &mut Context<A>) -> View<A> {
748        let active_index = context.signal(None);
749        let scroll = context.signal(ScrollState::new());
750        let popup_id = context
751            .runtime()
752            .popup_id_for_element(context.element_id())
753            .ok();
754        let popup_content = select_popup_content(RetainedSelectPopup {
755            options: self.options.clone(),
756            selected: self.selected.clone(),
757            bound: self.bound.clone(),
758            disabled: self.disabled.clone(),
759            on_change: self.on_change.clone(),
760            style: self.style.clone(),
761            active_index: active_index.clone(),
762            scroll: scroll.clone(),
763            popup_id,
764        });
765        View::leaf(SelectWidget {
766            layout: self.layout,
767            placeholder: self.placeholder.clone(),
768            options: self.options.clone(),
769            selected: self.selected.clone(),
770            bound: self.bound.clone(),
771            disabled: self.disabled.clone(),
772            on_change: self.on_change.clone(),
773            style: self.style.clone(),
774            popup_placement: self.popup_placement,
775            active_index,
776            popup: PopupPortalBridge::new_retained_with_content(
777                context,
778                listbox_popup_semantics(),
779                self.default_open,
780                popup_content,
781            ),
782        })
783    }
784}
785
786impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for Select<T, A> {
787    /// Converts configuration into a sized reactive component view.
788    fn into_view(self) -> View<A> {
789        finish_view_sized(
790            View::component(SelectComponent {
791                layout: self.layout,
792                placeholder: self.placeholder,
793                options: self.options,
794                selected: self.selected,
795                bound: self.bound,
796                disabled: self.disabled,
797                on_change: self.on_change,
798                style: self.style,
799                popup_placement: self.popup_placement,
800                default_open: self.default_open,
801            }),
802            self.flex_item,
803            LayoutSizeHint::from_layout(self.layout),
804        )
805    }
806}
807
808/// Retained select trigger with controlled selection and popup navigation.
809struct SelectWidget<T, A> {
810    /// Runtime trigger layout.
811    layout: LayoutStyle,
812    /// No-selection label.
813    placeholder: Binding<String>,
814    /// Typed options in display order.
815    options: Vec<SelectOption<T>>,
816    /// Readable selected value.
817    selected: Option<Binding<T>>,
818    /// Optional writable selected value.
819    bound: Option<Signal<T>>,
820    /// Whole-control disabled binding.
821    disabled: Binding<bool>,
822    /// Changed-selection callback.
823    on_change: Option<SelectChangeHandler<T, A>>,
824    /// Shared style.
825    style: SelectStyle,
826    /// Preferred popup side.
827    popup_placement: PopupPlacement,
828    /// Active option index.
829    active_index: Signal<Option<usize>>,
830    /// Runtime retained-popup bridge.
831    popup: PopupPortalBridge<A>,
832}
833
834impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for SelectWidget<T, A> {
835    /// Returns the stable diagnostic name.
836    fn debug_name(&self) -> &'static str {
837        "Select"
838    }
839
840    /// Measures intrinsic label width, applies constraints, and closes if disabled.
841    fn layout(
842        &self,
843        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
844        ctx: &mut LayoutCtx<'_>,
845        _children: &mut [LayoutChild],
846        constraints: Constraints,
847    ) -> LayoutResult {
848        let intrinsic = Size::new(
849            select_intrinsic_width(&self.options, &self.style, ctx.text_system.as_deref_mut()),
850            self.style.height,
851        );
852        let size = apply_layout_size(intrinsic, self.layout, constraints);
853        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
854        if self.disabled.read() {
855            self.popup.close(PopupDismissReason::Programmatic);
856        }
857
858        LayoutResult {
859            size,
860            children: Vec::new(),
861            paint_bounds,
862            visual_bounds: self.style.visual_bounds(paint_bounds),
863            overlay_hit_bounds: Vec::new(),
864            clip: None,
865            is_window_root_clip: false,
866            artifact: None,
867        }
868    }
869
870    /// Paints trigger state and refreshes open popup geometry.
871    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
872        paint_trigger(
873            ctx,
874            bounds,
875            self.current_label().as_deref(),
876            &self.placeholder.read(),
877            self.disabled.read(),
878            &self.style,
879        );
880        if self.popup.is_open() && !self.disabled.read() {
881            self.popup
882                .open_without_event(bounds, self.popup_rect(bounds));
883        }
884    }
885
886    /// Routes blur, pointer release, and keyboard popup navigation.
887    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
888        if self.disabled.read() {
889            return;
890        }
891
892        match event {
893            Event::Focus(focus) if !focus.focused && self.popup.is_open() => {
894                self.close(PopupDismissReason::OutsidePress);
895                ctx.request_repaint();
896            }
897            Event::Pointer(PointerEvent::Button {
898                pos,
899                button: MouseButton::Left,
900                pressed: false,
901                ..
902            }) if bounds.contains(pos.x, pos.y) => {
903                self.toggle_open(ctx, bounds);
904                ctx.request_repaint();
905                ctx.stop_propagation();
906            }
907            Event::Keyboard(key) if key.state == KeyState::Pressed => {
908                self.handle_keyboard(ctx, &key.key, bounds);
909            }
910            _ => {}
911        }
912    }
913
914    /// Makes only enabled selects focusable.
915    fn focus_policy(&self) -> FocusPolicy {
916        if self.disabled.read() {
917            FocusPolicy::NotFocusable
918        } else {
919            FocusPolicy::Focusable
920        }
921    }
922}
923
924impl<T: Clone + PartialEq + 'static, A: 'static> SelectWidget<T, A> {
925    /// Clones the configured selected value, if any.
926    fn selected_value(&self) -> Option<T> {
927        self.selected.as_ref().map(Binding::read)
928    }
929
930    /// Finds the first option equal to the controlled value.
931    fn selected_index(&self) -> Option<usize> {
932        let selected = self.selected_value()?;
933        self.options
934            .iter()
935            .position(|option| option.value == selected)
936    }
937
938    /// Clones the first selected option's label.
939    fn current_label(&self) -> Option<String> {
940        let idx = self.selected_index()?;
941        Some(self.options[idx].label.clone())
942    }
943
944    /// Measures popup content width with the trigger width as a floor.
945    fn popup_width(&self, trigger_width: f32, text_system: Option<&mut TextSystem>) -> f32 {
946        popup_content_width(&self.options, &self.style, text_system).max(trigger_width)
947    }
948
949    /// Returns row-derived popup height capped by `popup_max_height`.
950    fn popup_height(&self) -> f32 {
951        (self.options.len() as f32 * self.style.option_height).min(self.style.popup_max_height)
952    }
953
954    /// Positions popup on the configured vertical side of the trigger.
955    fn popup_rect(&self, bounds: Rect) -> Rect {
956        popup_rect_for_bounds(
957            bounds,
958            self.popup_width(bounds.w, None),
959            self.popup_height(),
960            self.style.popup_gap,
961            self.popup_placement,
962        )
963    }
964
965    /// Activates selected or first enabled option and opens the popup.
966    fn open(&self, ctx: &EventCtx<A>, bounds: Rect) {
967        self.active_index
968            .set(self.selected_index().or_else(|| self.first_enabled_index()));
969        self.popup.open(ctx, bounds, self.popup_rect(bounds));
970    }
971
972    /// Clears active navigation and dismisses the runtime popup.
973    fn close(&self, reason: PopupDismissReason) {
974        self.active_index.set(None);
975        self.popup.close(reason);
976    }
977
978    /// Programmatically closes an open popup or opens a closed one.
979    fn toggle_open(&self, ctx: &EventCtx<A>, bounds: Rect) {
980        if self.popup.is_open() {
981            self.close(PopupDismissReason::Programmatic);
982        } else {
983            self.open(ctx, bounds);
984        }
985    }
986
987    /// Commits an enabled option when changed and always closes it.
988    fn select_index(&self, ctx: &mut EventCtx<A>, index: usize) {
989        let Some(option) = self.options.get(index) else {
990            return;
991        };
992        if option.disabled.read() {
993            return;
994        }
995
996        let changed = self
997            .selected_value()
998            .as_ref()
999            .is_none_or(|value| value != &option.value);
1000        if changed {
1001            let next = option.value.clone();
1002            if let Some(bound) = &self.bound {
1003                bound.set(next.clone());
1004            }
1005            if let Some(on_change) = &self.on_change {
1006                on_change(ctx, next);
1007            }
1008        }
1009
1010        self.close(PopupDismissReason::Programmatic);
1011        ctx.request_repaint();
1012        ctx.stop_propagation();
1013    }
1014
1015    /// Opens on activation/navigation keys or routes open-popup keys.
1016    fn handle_keyboard(&self, ctx: &mut EventCtx<A>, key: &Key, bounds: Rect) {
1017        if !self.popup.is_open() {
1018            if matches!(
1019                key,
1020                Key::Named(NamedKey::Enter)
1021                    | Key::Named(NamedKey::Space)
1022                    | Key::Named(NamedKey::ArrowDown)
1023                    | Key::Named(NamedKey::ArrowUp)
1024            ) {
1025                self.open(ctx, bounds);
1026                ctx.request_repaint();
1027                ctx.stop_propagation();
1028            }
1029            return;
1030        }
1031
1032        match key {
1033            Key::Named(NamedKey::Escape) => {
1034                self.close(PopupDismissReason::Escape);
1035                ctx.request_repaint();
1036                ctx.stop_propagation();
1037            }
1038            Key::Named(NamedKey::ArrowDown) => self.move_active(ctx, Direction::Next),
1039            Key::Named(NamedKey::ArrowUp) => self.move_active(ctx, Direction::Previous),
1040            Key::Named(NamedKey::Home) => self.set_active(ctx, self.first_enabled_index()),
1041            Key::Named(NamedKey::End) => self.set_active(ctx, self.last_enabled_index()),
1042            Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1043                if let Some(index) = self
1044                    .active_index
1045                    .read()
1046                    .or_else(|| self.first_enabled_index())
1047                {
1048                    self.select_index(ctx, index);
1049                }
1050            }
1051            _ => {}
1052        }
1053    }
1054
1055    /// Moves cyclically to another enabled option.
1056    fn move_active(&self, ctx: &mut EventCtx<A>, direction: Direction) {
1057        let next = match direction {
1058            Direction::Next => self.next_enabled_index(self.active_index.read()),
1059            Direction::Previous => self.previous_enabled_index(self.active_index.read()),
1060        };
1061        self.set_active(ctx, next);
1062    }
1063
1064    /// Updates active index, repaints on change, and consumes the event.
1065    fn set_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
1066        if self.active_index.read() != next {
1067            self.active_index.set(next);
1068            ctx.request_repaint();
1069        }
1070        ctx.stop_propagation();
1071    }
1072
1073    /// Finds the first enabled option.
1074    fn first_enabled_index(&self) -> Option<usize> {
1075        self.options
1076            .iter()
1077            .enumerate()
1078            .find_map(|(idx, option)| (!option.disabled.read()).then_some(idx))
1079    }
1080
1081    /// Finds the last enabled option.
1082    fn last_enabled_index(&self) -> Option<usize> {
1083        self.options
1084            .iter()
1085            .enumerate()
1086            .rev()
1087            .find_map(|(idx, option)| (!option.disabled.read()).then_some(idx))
1088    }
1089
1090    /// Finds the cyclic next enabled option.
1091    fn next_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1092        let len = self.options.len();
1093        if len == 0 {
1094            return None;
1095        }
1096        let start = current.unwrap_or(len - 1);
1097        (1..=len)
1098            .map(|offset| (start + offset) % len)
1099            .find(|idx| !self.options[*idx].disabled.read())
1100    }
1101
1102    /// Finds the cyclic previous enabled option.
1103    fn previous_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1104        let len = self.options.len();
1105        if len == 0 {
1106            return None;
1107        }
1108        let start = current.unwrap_or(0);
1109        (1..=len)
1110            .map(|offset| (start + len - offset) % len)
1111            .find(|idx| !self.options[*idx].disabled.read())
1112    }
1113}
1114
1115/// One action-menu row with optional action, icon, and reactive availability.
1116///
1117/// Empty and duplicate labels are allowed. Activating an enabled item without an
1118/// action still closes the dropdown.
1119///
1120/// # Examples
1121///
1122/// ```
1123/// use ailloli_ui_widgets::controls::DropdownItem;
1124/// let item: DropdownItem<()> = DropdownItem::new("Refresh").on_select(());
1125/// let _ = item;
1126/// ```
1127pub struct DropdownItem<A = ()> {
1128    /// Visible row label.
1129    label: String,
1130    /// Optional action run on activation.
1131    action: Option<Rc<ClickAction<A>>>,
1132    /// Static or reactive disabled state.
1133    disabled: Binding<bool>,
1134    /// Optional leading icon.
1135    icon: Option<IconId>,
1136}
1137
1138impl<A> Clone for DropdownItem<A> {
1139    /// Clones label/icon values and shares action and binding handles.
1140    fn clone(&self) -> Self {
1141        Self {
1142            label: self.label.clone(),
1143            action: self.action.clone(),
1144            disabled: self.disabled.clone(),
1145            icon: self.icon.clone(),
1146        }
1147    }
1148}
1149
1150impl<A: 'static> DropdownItem<A> {
1151    /// Creates an enabled, iconless item with no action.
1152    ///
1153    /// # Examples
1154    ///
1155    /// ```
1156    /// use ailloli_ui_widgets::controls::DropdownItem;
1157    /// let item: DropdownItem<()> = DropdownItem::new("Refresh");
1158    /// let _ = item;
1159    /// ```
1160    pub fn new(label: impl Into<String>) -> Self {
1161        Self {
1162            label: label.into(),
1163            action: None,
1164            disabled: Binding::Static(false),
1165            icon: None,
1166        }
1167    }
1168
1169    /// Sets the activation action, replacing any previous action.
1170    ///
1171    /// # Examples
1172    ///
1173    /// ```
1174    /// use ailloli_ui_widgets::controls::DropdownItem;
1175    /// #[derive(Clone)]
1176    /// enum Action { Refresh }
1177    /// let item = DropdownItem::new("Refresh").on_select(Action::Refresh);
1178    /// let _ = item;
1179    /// ```
1180    pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self {
1181        self.action = Some(Rc::new(action.into_click_action()));
1182        self
1183    }
1184
1185    /// Replaces the item's static or reactive disabled binding.
1186    ///
1187    /// # Examples
1188    ///
1189    /// ```
1190    /// use ailloli_ui_widgets::controls::DropdownItem;
1191    /// let item: DropdownItem<()> = DropdownItem::new("Unavailable").disabled(true);
1192    /// let _ = item;
1193    /// ```
1194    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1195        self.disabled = disabled.into();
1196        self
1197    }
1198
1199    /// Uses a memo as the reactive disabled binding.
1200    ///
1201    /// # Examples
1202    ///
1203    /// ```
1204    /// use ailloli_ui_runtime::component::Memo;
1205    /// use ailloli_ui_widgets::controls::DropdownItem;
1206    /// let item: DropdownItem<()> = DropdownItem::new("Refresh")
1207    ///     .disabled_signal(Memo::new(|| false));
1208    /// let _ = item;
1209    /// ```
1210    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1211        self.disabled(disabled)
1212    }
1213
1214    /// Sets the leading icon, replacing any previous one.
1215    ///
1216    /// # Examples
1217    ///
1218    /// ```
1219    /// use ailloli_ui_core::IconId;
1220    /// use ailloli_ui_widgets::controls::DropdownItem;
1221    /// let item: DropdownItem<()> = DropdownItem::new("History").leading_icon(IconId::History);
1222    /// let _ = item;
1223    /// ```
1224    pub fn leading_icon(mut self, icon: IconId) -> Self {
1225        self.icon = Some(icon);
1226        self
1227    }
1228}
1229
1230/// Button-like trigger opening a non-focus-trapping action menu.
1231///
1232/// `A` is the application action type accepted by item actions. The dropdown
1233/// itself retains no selected item; activation runs the row action, if present,
1234/// and closes the popup.
1235///
1236/// # Examples
1237///
1238/// ```
1239/// use ailloli_ui_widgets::controls::Dropdown;
1240/// let dropdown: Dropdown<()> = Dropdown::new("Actions").item("Refresh", ());
1241/// let _ = dropdown;
1242/// ```
1243pub struct Dropdown<A = ()> {
1244    /// Trigger layout configured by generated builders.
1245    pub(crate) layout: LayoutStyle,
1246    /// Flex-parent participation configured by generated builders.
1247    pub(crate) flex_item: FlexItemStyle,
1248    /// Static or reactive trigger label.
1249    label: Binding<String>,
1250    /// Menu rows in display order.
1251    items: Vec<DropdownItem<A>>,
1252    /// Whole-control disabled binding.
1253    disabled: Binding<bool>,
1254    /// Trigger and popup appearance.
1255    style: DropdownStyle,
1256    /// Initial popup visibility.
1257    default_open: bool,
1258}
1259
1260crate::impl_layout_builders!(Dropdown);
1261
1262impl<A: 'static> Default for Dropdown<A> {
1263    fn default() -> Self {
1264        Self::new("Dropdown")
1265    }
1266}
1267
1268impl<A: 'static> Dropdown<A> {
1269    /// Creates an enabled dropdown with the supplied static or reactive label.
1270    ///
1271    /// It starts closed with no items and uses the default theme's regular menu
1272    /// style.
1273    ///
1274    /// # Examples
1275    ///
1276    /// ```
1277    /// use ailloli_ui_widgets::controls::Dropdown;
1278    /// let dropdown: Dropdown<()> = Dropdown::new("More");
1279    /// let _ = dropdown;
1280    /// ```
1281    pub fn new(label: impl Into<Binding<String>>) -> Self {
1282        Self {
1283            layout: LayoutStyle::default(),
1284            flex_item: FlexItemStyle::default(),
1285            label: label.into(),
1286            items: Vec::new(),
1287            disabled: Binding::Static(false),
1288            style: DropdownStyle::from_dropdown_theme(Theme::default(), DropdownSize::Default),
1289            default_open: false,
1290        }
1291    }
1292
1293    /// Appends an enabled, iconless item with an action.
1294    ///
1295    /// # Examples
1296    ///
1297    /// ```
1298    /// use ailloli_ui_widgets::controls::Dropdown;
1299    /// #[derive(Clone)]
1300    /// enum Action { Refresh }
1301    /// let dropdown = Dropdown::new("Actions").item("Refresh", Action::Refresh);
1302    /// let _ = dropdown;
1303    /// ```
1304    pub fn item(mut self, label: impl Into<String>, action: impl IntoClickAction<A>) -> Self {
1305        self.items.push(DropdownItem::new(label).on_select(action));
1306        self
1307    }
1308
1309    /// Appends a fully configured menu item.
1310    ///
1311    /// # Examples
1312    ///
1313    /// ```
1314    /// use ailloli_ui_widgets::controls::{Dropdown, DropdownItem};
1315    /// let dropdown: Dropdown<()> = Dropdown::new("Actions")
1316    ///     .dropdown_item(DropdownItem::new("Unavailable").disabled(true));
1317    /// let _ = dropdown;
1318    /// ```
1319    pub fn dropdown_item(mut self, item: DropdownItem<A>) -> Self {
1320        self.items.push(item);
1321        self
1322    }
1323
1324    /// Sets static or reactive whole-control disabled state.
1325    ///
1326    /// Disabled dropdowns are not focusable, ignore events, and close an open
1327    /// popup during layout.
1328    ///
1329    /// # Examples
1330    ///
1331    /// ```
1332    /// use ailloli_ui_widgets::controls::Dropdown;
1333    /// let dropdown: Dropdown<()> = Dropdown::new("Actions").disabled(true);
1334    /// let _ = dropdown;
1335    /// ```
1336    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1337        self.disabled = disabled.into();
1338        self
1339    }
1340
1341    /// Uses a memo as the reactive whole-control disabled binding.
1342    ///
1343    /// # Examples
1344    ///
1345    /// ```
1346    /// use ailloli_ui_runtime::component::Memo;
1347    /// use ailloli_ui_widgets::controls::Dropdown;
1348    /// let dropdown: Dropdown<()> = Dropdown::new("Actions")
1349    ///     .disabled_signal(Memo::new(|| false));
1350    /// let _ = dropdown;
1351    /// ```
1352    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1353        self.disabled(disabled)
1354    }
1355
1356    /// Sets only the retained menu popup's initial open state.
1357    ///
1358    /// # Examples
1359    ///
1360    /// ```
1361    /// use ailloli_ui_widgets::controls::Dropdown;
1362    /// let dropdown: Dropdown<()> = Dropdown::new("Actions").default_open(true);
1363    /// let _ = dropdown;
1364    /// ```
1365    pub fn default_open(mut self, open: bool) -> Self {
1366        self.default_open = open;
1367        self
1368    }
1369
1370    /// Replaces trigger and popup style without altering explicit layout values.
1371    ///
1372    /// # Examples
1373    ///
1374    /// ```
1375    /// use ailloli_ui_widgets::controls::{Dropdown, DropdownStyle};
1376    /// let dropdown: Dropdown<()> = Dropdown::new("Actions")
1377    ///     .dropdown_style(DropdownStyle::default());
1378    /// let _ = dropdown;
1379    /// ```
1380    pub fn dropdown_style(mut self, style: DropdownStyle) -> Self {
1381        self.style = style;
1382        self
1383    }
1384
1385    /// Re-derives style from the default theme and requested density.
1386    ///
1387    /// This overwrites every previous dropdown-style customization.
1388    ///
1389    /// # Examples
1390    ///
1391    /// ```
1392    /// use ailloli_ui_widgets::controls::{Dropdown, DropdownSize};
1393    /// let dropdown: Dropdown<()> = Dropdown::new("Actions")
1394    ///     .dropdown_size(DropdownSize::Compact);
1395    /// let _ = dropdown;
1396    /// ```
1397    pub fn dropdown_size(mut self, size: DropdownSize) -> Self {
1398        self.style = DropdownStyle::from_dropdown_theme(Theme::default(), size);
1399        self
1400    }
1401}
1402
1403/// Component that allocates navigation/scroll state and retained menu content.
1404struct DropdownComponent<A> {
1405    /// Trigger layout snapshot.
1406    layout: LayoutStyle,
1407    /// Trigger label.
1408    label: Binding<String>,
1409    /// Action rows.
1410    items: Vec<DropdownItem<A>>,
1411    /// Whole-control disabled binding.
1412    disabled: Binding<bool>,
1413    /// Shared trigger/popup style.
1414    style: DropdownStyle,
1415    /// Initial popup visibility.
1416    default_open: bool,
1417}
1418
1419impl<A: 'static> ComponentNode<A> for DropdownComponent<A> {
1420    /// Allocates active/scroll signals and connects retained menu content.
1421    fn build(&self, context: &mut Context<A>) -> View<A> {
1422        let active_index = context.signal(None);
1423        let scroll = context.signal(ScrollState::new());
1424        let popup_id = context
1425            .runtime()
1426            .popup_id_for_element(context.element_id())
1427            .ok();
1428        let popup_content = dropdown_popup_content(RetainedDropdownPopup {
1429            items: self.items.clone(),
1430            disabled: self.disabled.clone(),
1431            style: self.style.clone(),
1432            active_index: active_index.clone(),
1433            scroll,
1434            popup_id,
1435        });
1436        View::leaf(DropdownWidget {
1437            layout: self.layout,
1438            label: self.label.clone(),
1439            items: self.items.clone(),
1440            disabled: self.disabled.clone(),
1441            style: self.style.clone(),
1442            active_index,
1443            popup: PopupPortalBridge::new_retained_with_content(
1444                context,
1445                menu_popup_semantics(false),
1446                self.default_open,
1447                popup_content,
1448            ),
1449        })
1450    }
1451}
1452
1453impl<A: 'static> IntoView<A> for Dropdown<A> {
1454    /// Converts configuration into a sized reactive component view.
1455    fn into_view(self) -> View<A> {
1456        finish_view_sized(
1457            View::component(DropdownComponent {
1458                layout: self.layout,
1459                label: self.label,
1460                items: self.items,
1461                disabled: self.disabled,
1462                style: self.style,
1463                default_open: self.default_open,
1464            }),
1465            self.flex_item,
1466            LayoutSizeHint::from_layout(self.layout),
1467        )
1468    }
1469}
1470
1471/// Retained dropdown trigger with popup navigation and action dispatch.
1472struct DropdownWidget<A> {
1473    /// Runtime trigger layout.
1474    layout: LayoutStyle,
1475    /// Trigger label.
1476    label: Binding<String>,
1477    /// Menu rows in display order.
1478    items: Vec<DropdownItem<A>>,
1479    /// Whole-control disabled binding.
1480    disabled: Binding<bool>,
1481    /// Shared style.
1482    style: DropdownStyle,
1483    /// Active menu item index.
1484    active_index: Signal<Option<usize>>,
1485    /// Runtime retained-popup bridge.
1486    popup: PopupPortalBridge<A>,
1487}
1488
1489impl<A: 'static> Widget<A> for DropdownWidget<A> {
1490    /// Returns the stable diagnostic name.
1491    fn debug_name(&self) -> &'static str {
1492        "Dropdown"
1493    }
1494
1495    /// Measures trigger/item labels, applies constraints, and closes if disabled.
1496    fn layout(
1497        &self,
1498        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1499        ctx: &mut LayoutCtx<'_>,
1500        _children: &mut [LayoutChild],
1501        constraints: Constraints,
1502    ) -> LayoutResult {
1503        let intrinsic = Size::new(
1504            dropdown_intrinsic_width(
1505                &self.label.read(),
1506                &self.items,
1507                &self.style,
1508                ctx.text_system.as_deref_mut(),
1509            ),
1510            self.style.height,
1511        );
1512        let size = apply_layout_size(intrinsic, self.layout, constraints);
1513        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1514        if self.disabled.read() {
1515            self.popup.close(PopupDismissReason::Programmatic);
1516        }
1517        LayoutResult {
1518            size,
1519            children: Vec::new(),
1520            paint_bounds,
1521            visual_bounds: self.style.visual_bounds(paint_bounds),
1522            overlay_hit_bounds: Vec::new(),
1523            clip: None,
1524            is_window_root_clip: false,
1525            artifact: None,
1526        }
1527    }
1528
1529    /// Paints trigger state and refreshes open menu geometry.
1530    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1531        paint_trigger(
1532            ctx,
1533            bounds,
1534            Some(&self.label.read()),
1535            "",
1536            self.disabled.read(),
1537            &self.style,
1538        );
1539        if self.popup.is_open() && !self.disabled.read() {
1540            self.popup
1541                .open_without_event(bounds, self.popup_rect(bounds));
1542        }
1543    }
1544
1545    /// Routes blur, pointer release, and keyboard menu navigation.
1546    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1547        if self.disabled.read() {
1548            return;
1549        }
1550
1551        match event {
1552            Event::Focus(focus) if !focus.focused && self.popup.is_open() => {
1553                self.close(PopupDismissReason::OutsidePress);
1554                ctx.request_repaint();
1555            }
1556            Event::Pointer(PointerEvent::Button {
1557                pos,
1558                button: MouseButton::Left,
1559                pressed: false,
1560                ..
1561            }) if bounds.contains(pos.x, pos.y) => {
1562                self.toggle_open(ctx, bounds);
1563                ctx.request_repaint();
1564                ctx.stop_propagation();
1565            }
1566            Event::Keyboard(key) if key.state == KeyState::Pressed => {
1567                self.handle_keyboard(ctx, &key.key, bounds);
1568            }
1569            _ => {}
1570        }
1571    }
1572
1573    /// Makes only enabled dropdowns focusable.
1574    fn focus_policy(&self) -> FocusPolicy {
1575        if self.disabled.read() {
1576            FocusPolicy::NotFocusable
1577        } else {
1578            FocusPolicy::Focusable
1579        }
1580    }
1581}
1582
1583impl<A: 'static> DropdownWidget<A> {
1584    /// Measures popup content width with trigger width as a floor.
1585    fn popup_width(&self, trigger_width: f32, text_system: Option<&mut TextSystem>) -> f32 {
1586        dropdown_popup_content_width(&self.items, &self.style, text_system).max(trigger_width)
1587    }
1588
1589    /// Returns row-derived popup height capped by `popup_max_height`.
1590    fn popup_height(&self) -> f32 {
1591        (self.items.len() as f32 * self.style.option_height).min(self.style.popup_max_height)
1592    }
1593
1594    /// Places the menu below the trigger without placement flipping.
1595    fn popup_rect(&self, bounds: Rect) -> Rect {
1596        Rect::new(
1597            bounds.x,
1598            bounds.bottom() + self.style.popup_gap,
1599            self.popup_width(bounds.w, None),
1600            self.popup_height(),
1601        )
1602    }
1603
1604    /// Activates the first enabled item and opens the popup.
1605    fn open(&self, ctx: &EventCtx<A>, bounds: Rect) {
1606        self.active_index.set(self.first_enabled_index());
1607        self.popup.open(ctx, bounds, self.popup_rect(bounds));
1608    }
1609
1610    /// Clears active navigation and dismisses the runtime popup.
1611    fn close(&self, reason: PopupDismissReason) {
1612        self.active_index.set(None);
1613        self.popup.close(reason);
1614    }
1615
1616    /// Programmatically closes an open menu or opens a closed one.
1617    fn toggle_open(&self, ctx: &EventCtx<A>, bounds: Rect) {
1618        if self.popup.is_open() {
1619            self.close(PopupDismissReason::Programmatic);
1620        } else {
1621            self.open(ctx, bounds);
1622        }
1623    }
1624
1625    /// Runs an enabled item's optional action and closes the menu.
1626    fn activate_item(&self, ctx: &mut EventCtx<A>, index: usize) {
1627        let Some(item) = self.items.get(index) else {
1628            return;
1629        };
1630        if item.disabled.read() {
1631            return;
1632        }
1633        if let Some(action) = &item.action {
1634            action.run(ctx);
1635        }
1636        self.close(PopupDismissReason::Programmatic);
1637        ctx.request_repaint();
1638        ctx.stop_propagation();
1639    }
1640
1641    /// Opens on activation/navigation keys or routes open-menu keys.
1642    fn handle_keyboard(&self, ctx: &mut EventCtx<A>, key: &Key, bounds: Rect) {
1643        if !self.popup.is_open() {
1644            if matches!(
1645                key,
1646                Key::Named(NamedKey::Enter)
1647                    | Key::Named(NamedKey::Space)
1648                    | Key::Named(NamedKey::ArrowDown)
1649                    | Key::Named(NamedKey::ArrowUp)
1650            ) {
1651                self.open(ctx, bounds);
1652                ctx.request_repaint();
1653                ctx.stop_propagation();
1654            }
1655            return;
1656        }
1657
1658        match key {
1659            Key::Named(NamedKey::Escape) => {
1660                self.close(PopupDismissReason::Escape);
1661                ctx.request_repaint();
1662                ctx.stop_propagation();
1663            }
1664            Key::Named(NamedKey::ArrowDown) => self.move_active(ctx, Direction::Next),
1665            Key::Named(NamedKey::ArrowUp) => self.move_active(ctx, Direction::Previous),
1666            Key::Named(NamedKey::Home) => self.set_active(ctx, self.first_enabled_index()),
1667            Key::Named(NamedKey::End) => self.set_active(ctx, self.last_enabled_index()),
1668            Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1669                if let Some(index) = self
1670                    .active_index
1671                    .read()
1672                    .or_else(|| self.first_enabled_index())
1673                {
1674                    self.activate_item(ctx, index);
1675                }
1676            }
1677            _ => {}
1678        }
1679    }
1680
1681    /// Moves cyclically to another enabled item.
1682    fn move_active(&self, ctx: &mut EventCtx<A>, direction: Direction) {
1683        let next = match direction {
1684            Direction::Next => self.next_enabled_index(self.active_index.read()),
1685            Direction::Previous => self.previous_enabled_index(self.active_index.read()),
1686        };
1687        self.set_active(ctx, next);
1688    }
1689
1690    /// Updates active index, repaints on change, and consumes the event.
1691    fn set_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
1692        if self.active_index.read() != next {
1693            self.active_index.set(next);
1694            ctx.request_repaint();
1695        }
1696        ctx.stop_propagation();
1697    }
1698
1699    /// Finds the first enabled menu item.
1700    fn first_enabled_index(&self) -> Option<usize> {
1701        self.items
1702            .iter()
1703            .enumerate()
1704            .find_map(|(idx, item)| (!item.disabled.read()).then_some(idx))
1705    }
1706
1707    /// Finds the last enabled menu item.
1708    fn last_enabled_index(&self) -> Option<usize> {
1709        self.items
1710            .iter()
1711            .enumerate()
1712            .rev()
1713            .find_map(|(idx, item)| (!item.disabled.read()).then_some(idx))
1714    }
1715
1716    /// Finds the cyclic next enabled menu item.
1717    fn next_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1718        let len = self.items.len();
1719        if len == 0 {
1720            return None;
1721        }
1722        let start = current.unwrap_or(len - 1);
1723        (1..=len)
1724            .map(|offset| (start + offset) % len)
1725            .find(|idx| !self.items[*idx].disabled.read())
1726    }
1727
1728    /// Finds the cyclic previous enabled menu item.
1729    fn previous_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1730        let len = self.items.len();
1731        if len == 0 {
1732            return None;
1733        }
1734        let start = current.unwrap_or(0);
1735        (1..=len)
1736            .map(|offset| (start + len - offset) % len)
1737            .find(|idx| !self.items[*idx].disabled.read())
1738    }
1739}
1740
1741/// Popup-owned select state rendered in the overlay presentation tree.
1742struct RetainedSelectPopup<T, A> {
1743    /// Typed options.
1744    options: Vec<SelectOption<T>>,
1745    /// Readable selection.
1746    selected: Option<Binding<T>>,
1747    /// Optional writable selection.
1748    bound: Option<Signal<T>>,
1749    /// Whole-control disabled binding.
1750    disabled: Binding<bool>,
1751    /// Changed-selection callback.
1752    on_change: Option<SelectChangeHandler<T, A>>,
1753    /// Shared style.
1754    style: SelectStyle,
1755    /// Active option index.
1756    active_index: Signal<Option<usize>>,
1757    /// Popup-local vertical scroll.
1758    scroll: Signal<ScrollState>,
1759    /// Runtime ID used for dismissal.
1760    popup_id: Option<PopupId>,
1761}
1762
1763impl<T: Clone, A> Clone for RetainedSelectPopup<T, A> {
1764    /// Clones values and shares binding, signal, callback, and popup handles.
1765    fn clone(&self) -> Self {
1766        Self {
1767            options: self.options.clone(),
1768            selected: self.selected.clone(),
1769            bound: self.bound.clone(),
1770            disabled: self.disabled.clone(),
1771            on_change: self.on_change.clone(),
1772            style: self.style.clone(),
1773            active_index: self.active_index.clone(),
1774            scroll: self.scroll.clone(),
1775            popup_id: self.popup_id,
1776        }
1777    }
1778}
1779
1780impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for RetainedSelectPopup<T, A> {
1781    /// Returns the stable popup diagnostic name.
1782    fn debug_name(&self) -> &'static str {
1783        "SelectPopup"
1784    }
1785
1786    /// Sizes by rows and clamps retained vertical scroll.
1787    fn layout(
1788        &self,
1789        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1790        _ctx: &mut LayoutCtx<'_>,
1791        _children: &mut [LayoutChild],
1792        constraints: Constraints,
1793    ) -> LayoutResult {
1794        let size = retained_popup_size(
1795            constraints,
1796            self.style.width,
1797            self.options.len(),
1798            &self.style,
1799        );
1800        clamp_retained_popup_scroll(&self.scroll, size, self.options.len(), &self.style);
1801        retained_popup_layout(size)
1802    }
1803
1804    /// Paints visible rows with selection, active state, and scroll offset.
1805    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1806        paint_select_popup(
1807            ctx,
1808            bounds,
1809            &self.options,
1810            self.selected_index(),
1811            self.active_index.read(),
1812            self.scroll.read().offset.y,
1813            &self.style,
1814        );
1815    }
1816
1817    /// Routes hover, release selection, wheel scroll, and cancellation.
1818    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1819        if self.disabled.read() {
1820            self.close(ctx, PopupDismissReason::Programmatic);
1821            return;
1822        }
1823
1824        match event {
1825            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
1826                let next = retained_popup_index_at(
1827                    bounds,
1828                    *pos,
1829                    self.scroll.read().offset.y,
1830                    self.style.option_height,
1831                    self.options.len(),
1832                )
1833                .filter(|index| !self.options[*index].disabled.read());
1834                if self.active_index.read() != next {
1835                    self.active_index.set(next);
1836                    ctx.request_repaint();
1837                }
1838            }
1839            Event::Pointer(PointerEvent::Button {
1840                pos,
1841                button: MouseButton::Left,
1842                pressed: false,
1843                ..
1844            }) => {
1845                if let Some(index) = retained_popup_index_at(
1846                    bounds,
1847                    *pos,
1848                    self.scroll.read().offset.y,
1849                    self.style.option_height,
1850                    self.options.len(),
1851                ) {
1852                    self.select_index(ctx, index);
1853                }
1854                ctx.stop_propagation();
1855            }
1856            Event::Pointer(PointerEvent::Wheel {
1857                delta, modifiers, ..
1858            }) => {
1859                scroll_retained_popup(
1860                    ctx,
1861                    &self.scroll,
1862                    *delta,
1863                    *modifiers,
1864                    Size::new(bounds.w, bounds.h),
1865                    self.options.len(),
1866                    &self.style,
1867                );
1868            }
1869            Event::Pointer(PointerEvent::Cancelled { .. }) => {
1870                self.set_active(None, ctx);
1871            }
1872            _ => {}
1873        }
1874    }
1875
1876    /// Keeps overlay rows outside the focus chain.
1877    fn focus_policy(&self) -> FocusPolicy {
1878        FocusPolicy::NotFocusable
1879    }
1880
1881    /// Suppresses activation synthesized solely from focus changes.
1882    fn activation_policy(&self) -> ActivationPolicy {
1883        ActivationPolicy::SuppressOnFocusOnly
1884    }
1885
1886    /// Uses a pointer cursor only over enabled rows.
1887    fn hover_cursor_role_at(
1888        &self,
1889        bounds: Rect,
1890        _layout: &LayoutResult,
1891        pos: ailloli_ui_core::Point,
1892    ) -> HoverCursorRole {
1893        retained_popup_index_at(
1894            bounds,
1895            pos,
1896            self.scroll.read().offset.y,
1897            self.style.option_height,
1898            self.options.len(),
1899        )
1900        .filter(|index| !self.options[*index].disabled.read())
1901        .map_or(HoverCursorRole::Default, |_| HoverCursorRole::Pointer)
1902    }
1903}
1904
1905impl<T: Clone + PartialEq + 'static, A: 'static> RetainedSelectPopup<T, A> {
1906    /// Clones the configured selection, if any.
1907    fn selected_value(&self) -> Option<T> {
1908        self.selected.as_ref().map(Binding::read)
1909    }
1910
1911    /// Finds the first option equal to the selected value.
1912    fn selected_index(&self) -> Option<usize> {
1913        let selected = self.selected_value()?;
1914        self.options
1915            .iter()
1916            .position(|option| option.value == selected)
1917    }
1918
1919    /// Commits an enabled changed option and dismisses the popup.
1920    fn select_index(&self, ctx: &mut EventCtx<A>, index: usize) {
1921        let Some(option) = self.options.get(index) else {
1922            return;
1923        };
1924        if option.disabled.read() {
1925            return;
1926        }
1927        let changed = self
1928            .selected_value()
1929            .as_ref()
1930            .is_none_or(|value| value != &option.value);
1931        if changed {
1932            let next = option.value.clone();
1933            if let Some(bound) = &self.bound {
1934                bound.set(next.clone());
1935            }
1936            if let Some(on_change) = &self.on_change {
1937                on_change(ctx, next);
1938            }
1939        }
1940        self.close(ctx, PopupDismissReason::Programmatic);
1941    }
1942
1943    /// Updates active option and repaints only when it changes.
1944    fn set_active(&self, next: Option<usize>, ctx: &mut EventCtx<A>) {
1945        if self.active_index.read() != next {
1946            self.active_index.set(next);
1947            ctx.request_repaint();
1948        }
1949    }
1950
1951    /// Clears active state, closes when registered, repaints, and consumes input.
1952    fn close(&self, ctx: &mut EventCtx<A>, reason: PopupDismissReason) {
1953        self.active_index.set(None);
1954        if let Some(popup_id) = self.popup_id {
1955            ctx.runtime().close_popup(popup_id, reason);
1956        }
1957        ctx.request_repaint();
1958        ctx.stop_propagation();
1959    }
1960}
1961
1962/// Popup-owned dropdown menu state rendered in the overlay presentation tree.
1963struct RetainedDropdownPopup<A> {
1964    /// Action rows.
1965    items: Vec<DropdownItem<A>>,
1966    /// Whole-control disabled binding.
1967    disabled: Binding<bool>,
1968    /// Shared style.
1969    style: DropdownStyle,
1970    /// Active item index.
1971    active_index: Signal<Option<usize>>,
1972    /// Popup-local vertical scroll.
1973    scroll: Signal<ScrollState>,
1974    /// Runtime ID used for dismissal.
1975    popup_id: Option<PopupId>,
1976}
1977
1978impl<A> Clone for RetainedDropdownPopup<A> {
1979    /// Clones item values and shares binding, signal, action, and popup handles.
1980    fn clone(&self) -> Self {
1981        Self {
1982            items: self.items.clone(),
1983            disabled: self.disabled.clone(),
1984            style: self.style.clone(),
1985            active_index: self.active_index.clone(),
1986            scroll: self.scroll.clone(),
1987            popup_id: self.popup_id,
1988        }
1989    }
1990}
1991
1992impl<A: 'static> Widget<A> for RetainedDropdownPopup<A> {
1993    /// Returns the stable popup diagnostic name.
1994    fn debug_name(&self) -> &'static str {
1995        "DropdownPopup"
1996    }
1997
1998    /// Sizes by rows and clamps retained vertical scroll.
1999    fn layout(
2000        &self,
2001        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
2002        _ctx: &mut LayoutCtx<'_>,
2003        _children: &mut [LayoutChild],
2004        constraints: Constraints,
2005    ) -> LayoutResult {
2006        let size =
2007            retained_popup_size(constraints, self.style.width, self.items.len(), &self.style);
2008        clamp_retained_popup_scroll(&self.scroll, size, self.items.len(), &self.style);
2009        retained_popup_layout(size)
2010    }
2011
2012    /// Paints visible rows with active state and scroll offset.
2013    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
2014        paint_dropdown_popup(
2015            ctx,
2016            bounds,
2017            &self.items,
2018            self.active_index.read(),
2019            self.scroll.read().offset.y,
2020            &self.style,
2021        );
2022    }
2023
2024    /// Routes hover, release activation, wheel scroll, and cancellation.
2025    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
2026        if self.disabled.read() {
2027            self.close(ctx, PopupDismissReason::Programmatic);
2028            return;
2029        }
2030
2031        match event {
2032            Event::Pointer(PointerEvent::Moved { pos, .. }) => {
2033                let next = retained_popup_index_at(
2034                    bounds,
2035                    *pos,
2036                    self.scroll.read().offset.y,
2037                    self.style.option_height,
2038                    self.items.len(),
2039                )
2040                .filter(|index| !self.items[*index].disabled.read());
2041                if self.active_index.read() != next {
2042                    self.active_index.set(next);
2043                    ctx.request_repaint();
2044                }
2045            }
2046            Event::Pointer(PointerEvent::Button {
2047                pos,
2048                button: MouseButton::Left,
2049                pressed: false,
2050                ..
2051            }) => {
2052                if let Some(index) = retained_popup_index_at(
2053                    bounds,
2054                    *pos,
2055                    self.scroll.read().offset.y,
2056                    self.style.option_height,
2057                    self.items.len(),
2058                ) {
2059                    self.activate_item(ctx, index);
2060                }
2061                ctx.stop_propagation();
2062            }
2063            Event::Pointer(PointerEvent::Wheel {
2064                delta, modifiers, ..
2065            }) => {
2066                scroll_retained_popup(
2067                    ctx,
2068                    &self.scroll,
2069                    *delta,
2070                    *modifiers,
2071                    Size::new(bounds.w, bounds.h),
2072                    self.items.len(),
2073                    &self.style,
2074                );
2075            }
2076            Event::Pointer(PointerEvent::Cancelled { .. }) => {
2077                self.set_active(None, ctx);
2078            }
2079            _ => {}
2080        }
2081    }
2082
2083    /// Keeps overlay rows outside the focus chain.
2084    fn focus_policy(&self) -> FocusPolicy {
2085        FocusPolicy::NotFocusable
2086    }
2087
2088    /// Suppresses activation synthesized solely from focus changes.
2089    fn activation_policy(&self) -> ActivationPolicy {
2090        ActivationPolicy::SuppressOnFocusOnly
2091    }
2092
2093    /// Uses a pointer cursor only over enabled rows.
2094    fn hover_cursor_role_at(
2095        &self,
2096        bounds: Rect,
2097        _layout: &LayoutResult,
2098        pos: ailloli_ui_core::Point,
2099    ) -> HoverCursorRole {
2100        retained_popup_index_at(
2101            bounds,
2102            pos,
2103            self.scroll.read().offset.y,
2104            self.style.option_height,
2105            self.items.len(),
2106        )
2107        .filter(|index| !self.items[*index].disabled.read())
2108        .map_or(HoverCursorRole::Default, |_| HoverCursorRole::Pointer)
2109    }
2110}
2111
2112impl<A: 'static> RetainedDropdownPopup<A> {
2113    /// Runs an enabled item's optional action and dismisses the popup.
2114    fn activate_item(&self, ctx: &mut EventCtx<A>, index: usize) {
2115        let Some(item) = self.items.get(index) else {
2116            return;
2117        };
2118        if item.disabled.read() {
2119            return;
2120        }
2121        if let Some(action) = &item.action {
2122            action.run(ctx);
2123        }
2124        self.close(ctx, PopupDismissReason::Programmatic);
2125    }
2126
2127    /// Updates active item and repaints only when it changes.
2128    fn set_active(&self, next: Option<usize>, ctx: &mut EventCtx<A>) {
2129        if self.active_index.read() != next {
2130            self.active_index.set(next);
2131            ctx.request_repaint();
2132        }
2133    }
2134
2135    /// Clears active state, closes when registered, repaints, and consumes input.
2136    fn close(&self, ctx: &mut EventCtx<A>, reason: PopupDismissReason) {
2137        self.active_index.set(None);
2138        if let Some(popup_id) = self.popup_id {
2139            ctx.runtime().close_popup(popup_id, reason);
2140        }
2141        ctx.request_repaint();
2142        ctx.stop_propagation();
2143    }
2144}
2145
2146/// Wraps clonable select popup state in a retained content factory.
2147fn select_popup_content<T: Clone + PartialEq + 'static, A: 'static>(
2148    popup: RetainedSelectPopup<T, A>,
2149) -> PopupContent<A> {
2150    PopupContent::new(move || View::leaf(popup.clone()))
2151}
2152
2153/// Wraps clonable dropdown popup state in a retained content factory.
2154fn dropdown_popup_content<A: 'static>(popup: RetainedDropdownPopup<A>) -> PopupContent<A> {
2155    PopupContent::new(move || View::leaf(popup.clone()))
2156}
2157
2158/// Constrains requested width and capped row height to popup constraints.
2159fn retained_popup_size(
2160    constraints: Constraints,
2161    width: f32,
2162    rows: usize,
2163    style: &SelectStyle,
2164) -> Size {
2165    constraints.constrain(Size::new(
2166        width,
2167        (rows as f32 * style.option_height).min(style.popup_max_height),
2168    ))
2169}
2170
2171/// Creates a leaf layout clipped exactly to popup-local bounds.
2172fn retained_popup_layout(size: Size) -> LayoutResult {
2173    let bounds = Rect::new(0.0, 0.0, size.w, size.h);
2174    LayoutResult {
2175        size,
2176        children: Vec::new(),
2177        paint_bounds: bounds,
2178        visual_bounds: bounds,
2179        overlay_hit_bounds: Vec::new(),
2180        clip: Some(ailloli_ui_core::ClipShape::Rect(bounds)),
2181        is_window_root_clip: false,
2182        artifact: None,
2183    }
2184}
2185
2186/// Converts a contained point and scroll offset to a row index.
2187///
2188/// Returns `None` outside bounds, for nonpositive row height, or after `rows`.
2189fn retained_popup_index_at(
2190    bounds: Rect,
2191    pos: ailloli_ui_core::Point,
2192    scroll_y: f32,
2193    row_height: f32,
2194    rows: usize,
2195) -> Option<usize> {
2196    if !bounds.contains(pos.x, pos.y) || row_height <= 0.0 {
2197        return None;
2198    }
2199    let index = ((pos.y - bounds.y + scroll_y) / row_height).floor() as usize;
2200    (index < rows).then_some(index)
2201}
2202
2203/// Clamps vertical scroll to the current row-derived content extent.
2204fn clamp_retained_popup_scroll(
2205    scroll: &Signal<ScrollState>,
2206    viewport: Size,
2207    rows: usize,
2208    style: &SelectStyle,
2209) {
2210    let content = Size::new(viewport.w, rows as f32 * style.option_height);
2211    let state = scroll.read();
2212    let outcome = state.clamp_to(ScrollMetrics::new(viewport, content), ScrollAxes::VERTICAL);
2213    if outcome.changed {
2214        scroll.set(outcome.state());
2215    }
2216}
2217
2218/// Applies wheel scrolling in row-height line units.
2219///
2220/// The event is consumed only when the retained offset actually changes, so a
2221/// popup already at its limit can bubble the wheel gesture to an ancestor.
2222fn scroll_retained_popup<A: 'static>(
2223    ctx: &mut EventCtx<A>,
2224    scroll: &Signal<ScrollState>,
2225    delta: WheelDelta,
2226    modifiers: ailloli_ui_core::event::Modifiers,
2227    viewport: Size,
2228    rows: usize,
2229    style: &SelectStyle,
2230) {
2231    let outcome = scroll_popup(
2232        &scroll.read(),
2233        delta,
2234        modifiers,
2235        viewport,
2236        Size::new(viewport.w, rows as f32 * style.option_height),
2237        style.option_height,
2238        ScrollAxes::VERTICAL,
2239    );
2240    if outcome.changed {
2241        scroll.set(outcome.state());
2242        ctx.request_repaint();
2243        ctx.stop_propagation();
2244    }
2245}
2246
2247#[derive(Debug, Clone, Copy)]
2248/// Cyclic keyboard-navigation direction.
2249enum Direction {
2250    /// Move toward later rows.
2251    Next,
2252    /// Move toward earlier rows.
2253    Previous,
2254}
2255
2256/// Returns measured option width with configured style width as a floor.
2257fn select_intrinsic_width<T>(
2258    options: &[SelectOption<T>],
2259    style: &SelectStyle,
2260    text_system: Option<&mut TextSystem>,
2261) -> f32 {
2262    popup_content_width(options, style, text_system).max(style.width)
2263}
2264
2265/// Returns the maximum of trigger label, item content, and configured width.
2266fn dropdown_intrinsic_width<A>(
2267    label: &str,
2268    items: &[DropdownItem<A>],
2269    style: &DropdownStyle,
2270    mut text_system: Option<&mut TextSystem>,
2271) -> f32 {
2272    let trigger = measure_text(text_system.as_deref_mut(), label, style.text).w
2273        + style.padding_x * 2.0
2274        + style.icon_size
2275        + style.icon_gap;
2276    trigger
2277        .max(dropdown_popup_content_width(items, style, text_system))
2278        .max(style.width)
2279}
2280
2281/// Measures option labels/icons plus padding and reserved checkmark space.
2282fn popup_content_width<T>(
2283    options: &[SelectOption<T>],
2284    style: &SelectStyle,
2285    mut text_system: Option<&mut TextSystem>,
2286) -> f32 {
2287    options
2288        .iter()
2289        .map(|option| {
2290            let label = measure_text(text_system.as_deref_mut(), &option.label, style.text).w;
2291            let icon = option
2292                .icon
2293                .as_ref()
2294                .map(|_| style.icon_size + style.icon_gap)
2295                .unwrap_or(0.0);
2296            label + icon + style.padding_x * 2.0 + style.icon_size + style.icon_gap
2297        })
2298        .fold(style.width, f32::max)
2299        .ceil()
2300}
2301
2302/// Measures menu item labels/icons plus horizontal padding.
2303fn dropdown_popup_content_width<A>(
2304    items: &[DropdownItem<A>],
2305    style: &DropdownStyle,
2306    mut text_system: Option<&mut TextSystem>,
2307) -> f32 {
2308    items
2309        .iter()
2310        .map(|item| {
2311            let label = measure_text(text_system.as_deref_mut(), &item.label, style.text).w;
2312            let icon = item
2313                .icon
2314                .as_ref()
2315                .map(|_| style.icon_size + style.icon_gap)
2316                .unwrap_or(0.0);
2317            label + icon + style.padding_x * 2.0
2318        })
2319        .fold(style.width, f32::max)
2320        .ceil()
2321}
2322
2323/// Paints interaction/disabled trigger state, clipped text, chevron, and focus ring.
2324fn paint_trigger(
2325    ctx: &mut PaintCtx<'_>,
2326    bounds: Rect,
2327    label: Option<&str>,
2328    placeholder: &str,
2329    disabled: bool,
2330    style: &SelectStyle,
2331) {
2332    let interaction = ctx.interaction();
2333    let opacity = if disabled {
2334        style.disabled_opacity
2335    } else {
2336        1.0
2337    };
2338    let background = if interaction.pressed {
2339        style.trigger_background_pressed
2340    } else if interaction.hovered {
2341        style.trigger_background_hovered
2342    } else {
2343        style.trigger_background
2344    };
2345
2346    ctx.push(DrawCmd::RRect(DrawRRect {
2347        rect: bounds,
2348        radius: style.radius.tl,
2349        color: apply_opacity(background, opacity),
2350    }));
2351
2352    if style.border.is_visible() {
2353        ctx.push(DrawCmd::Border(DrawBorder {
2354            rect: bounds,
2355            radius: style.radius,
2356            border: apply_border_opacity(style.border, opacity),
2357        }));
2358    }
2359
2360    let chevron = Rect::new(
2361        bounds.right() - style.padding_x - style.icon_size,
2362        bounds.y + (bounds.h - style.icon_size) * 0.5,
2363        style.icon_size,
2364        style.icon_size,
2365    );
2366    let text_rect = Rect::new(
2367        bounds.x + style.padding_x,
2368        bounds.y,
2369        (chevron.x - bounds.x - style.padding_x - style.icon_gap).max(0.0),
2370        bounds.h,
2371    );
2372    let (content, text_style) = match label {
2373        Some(label) => (
2374            label,
2375            if disabled {
2376                style.disabled_text
2377            } else {
2378                style.text
2379            },
2380        ),
2381        None => (
2382            placeholder,
2383            if disabled {
2384                style.disabled_text
2385            } else {
2386                style.placeholder_text
2387            },
2388        ),
2389    };
2390    ctx.with_clip(text_rect, |ctx| {
2391        paint_text_in_rect(ctx, content, text_style, text_rect, opacity);
2392    });
2393    ctx.push(DrawCmd::Image(DrawImage {
2394        rect: chevron,
2395        icon: IconId::Lucide(Icon::ChevronDown),
2396        tint: apply_opacity(
2397            if disabled {
2398                style.disabled_icon_tint
2399            } else {
2400                style.icon_tint
2401            },
2402            opacity,
2403        ),
2404        rotation_rad: 0.0,
2405    }));
2406
2407    if interaction.focused && !disabled && style.focus_ring.is_visible() {
2408        ctx.push(DrawCmd::Border(DrawBorder {
2409            rect: bounds.inflate(style.focus_ring_offset, style.focus_ring_offset),
2410            radius: Radius::uniform(style.radius.tl + style.focus_ring_offset),
2411            border: style.focus_ring,
2412        }));
2413    }
2414}
2415
2416/// Paints visible select rows, selected checkmark, shell, and final border.
2417fn paint_select_popup<T>(
2418    ctx: &mut PaintCtx<'_>,
2419    popup: Rect,
2420    options: &[SelectOption<T>],
2421    selected: Option<usize>,
2422    active: Option<usize>,
2423    scroll_y: f32,
2424    style: &SelectStyle,
2425) {
2426    paint_popup_shell(ctx, popup, style);
2427    ctx.with_overlay_clip(popup, |ctx| {
2428        for (idx, option) in options.iter().enumerate() {
2429            let row = Rect::new(
2430                popup.x,
2431                popup.y - scroll_y + idx as f32 * style.option_height,
2432                popup.w,
2433                style.option_height,
2434            );
2435            if row.bottom() < popup.y || row.y > popup.bottom() {
2436                continue;
2437            }
2438            paint_popup_row(
2439                ctx,
2440                row,
2441                &option.label,
2442                option.icon.as_ref(),
2443                PopupRowState {
2444                    disabled: option.disabled.read(),
2445                    selected: selected == Some(idx),
2446                    active: active == Some(idx),
2447                },
2448                style,
2449            );
2450            if selected == Some(idx) {
2451                let check = Rect::new(
2452                    row.right() - style.padding_x - style.icon_size,
2453                    row.y + (row.h - style.icon_size) * 0.5,
2454                    style.icon_size,
2455                    style.icon_size,
2456                );
2457                ctx.push_overlay(DrawCmd::Image(DrawImage {
2458                    rect: check,
2459                    icon: IconId::Check,
2460                    tint: style.selected_icon_tint,
2461                    rotation_rad: 0.0,
2462                }));
2463            }
2464        }
2465    });
2466    paint_popup_border(ctx, popup, style);
2467}
2468
2469/// Paints visible action rows, shell, and final border.
2470fn paint_dropdown_popup<A>(
2471    ctx: &mut PaintCtx<'_>,
2472    popup: Rect,
2473    items: &[DropdownItem<A>],
2474    active: Option<usize>,
2475    scroll_y: f32,
2476    style: &DropdownStyle,
2477) {
2478    paint_popup_shell(ctx, popup, style);
2479    ctx.with_overlay_clip(popup, |ctx| {
2480        for (idx, item) in items.iter().enumerate() {
2481            let row = Rect::new(
2482                popup.x,
2483                popup.y - scroll_y + idx as f32 * style.option_height,
2484                popup.w,
2485                style.option_height,
2486            );
2487            if row.bottom() < popup.y || row.y > popup.bottom() {
2488                continue;
2489            }
2490            paint_popup_row(
2491                ctx,
2492                row,
2493                &item.label,
2494                item.icon.as_ref(),
2495                PopupRowState {
2496                    disabled: item.disabled.read(),
2497                    selected: false,
2498                    active: active == Some(idx),
2499                },
2500                style,
2501            );
2502        }
2503    });
2504    paint_popup_border(ctx, popup, style);
2505}