1use 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)]
39pub enum SelectSize {
49 Compact,
51 #[default]
52 Default,
54}
55
56#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
57pub enum DropdownSize {
67 Compact,
69 #[default]
70 Default,
72}
73
74#[derive(Clone, Debug, PartialEq)]
75pub struct SelectStyle {
90 pub trigger_background: Color,
92 pub trigger_background_hovered: Color,
94 pub trigger_background_pressed: Color,
96 pub popup_background: Color,
98 pub option_hovered: Color,
100 pub option_active: Color,
102 pub option_selected: Color,
104 pub border: Border,
106 pub popup_border: Border,
108 pub focus_ring: Border,
110 pub shadows: Vec<BoxShadow>,
112 pub text: TextStyle,
114 pub placeholder_text: TextStyle,
116 pub disabled_text: TextStyle,
118 pub icon_tint: Color,
120 pub selected_icon_tint: Color,
122 pub disabled_icon_tint: Color,
124 pub width: f32,
126 pub height: f32,
128 pub option_height: f32,
130 pub popup_max_height: f32,
132 pub popup_gap: f32,
134 pub radius: Radius,
136 pub padding_x: f32,
138 pub icon_size: f32,
140 pub icon_gap: f32,
142 pub focus_ring_offset: f32,
144 pub disabled_opacity: f32,
146}
147
148pub 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 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 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 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)]
265pub struct SelectOption<T> {
278 value: T,
280 label: String,
282 disabled: Binding<bool>,
284 icon: Option<IconId>,
286}
287
288impl<T> SelectOption<T> {
289 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 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
317 self.disabled = disabled.into();
318 self
319 }
320
321 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
332 self.disabled(disabled)
333 }
334
335 pub fn leading_icon(mut self, icon: IconId) -> Self {
346 self.icon = Some(icon);
347 self
348 }
349}
350
351type SelectChangeHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
353
354pub struct Select<T, A = ()> {
368 pub(crate) layout: LayoutStyle,
370 pub(crate) flex_item: FlexItemStyle,
372 placeholder: Binding<String>,
374 options: Vec<SelectOption<T>>,
376 selected: Option<Binding<T>>,
378 bound: Option<Signal<T>>,
380 disabled: Binding<bool>,
382 on_change: Option<SelectChangeHandler<T, A>>,
384 style: SelectStyle,
386 popup_placement: PopupPlacement,
388 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 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 pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
443 self.placeholder = placeholder.into();
444 self
445 }
446
447 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 pub fn select_option(mut self, option: SelectOption<T>) -> Self {
472 self.options.push(option);
473 self
474 }
475
476 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 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 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
527 self.disabled = disabled.into();
528 self
529 }
530
531 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
542 self.disabled(disabled)
543 }
544
545 pub fn default_open(mut self, open: bool) -> Self {
555 self.default_open = open;
556 self
557 }
558
559 pub fn popup_placement(mut self, placement: PopupPlacement) -> Self {
572 self.popup_placement = placement;
573 self
574 }
575
576 pub fn select_style(mut self, style: SelectStyle) -> Self {
586 self.style = style;
587 self
588 }
589
590 pub fn select_size(mut self, size: SelectSize) -> Self {
602 self.style = SelectStyle::from_theme(Theme::default(), size);
603 self
604 }
605
606 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 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 pub fn width(mut self, value: impl Into<Length>) -> Self {
646 self.layout.width = value.into();
647 self
648 }
649
650 pub fn height(mut self, value: impl Into<Length>) -> Self {
660 self.layout.height = value.into();
661 self
662 }
663
664 pub fn min_width(mut self, value: impl Into<Length>) -> Self {
674 self.layout.min_width = value.into();
675 self
676 }
677
678 pub fn max_width(mut self, value: impl Into<Length>) -> Self {
688 self.layout.max_width = value.into();
689 self
690 }
691
692 pub fn fill_width(mut self) -> Self {
702 self.layout.width = Length::Fill;
703 self
704 }
705
706 pub fn flex_grow(mut self) -> Self {
716 self.flex_item = self.flex_item.flex_grow(1.0);
717 self
718 }
719}
720
721struct SelectComponent<T, A> {
723 layout: LayoutStyle,
725 placeholder: Binding<String>,
727 options: Vec<SelectOption<T>>,
729 selected: Option<Binding<T>>,
731 bound: Option<Signal<T>>,
733 disabled: Binding<bool>,
735 on_change: Option<SelectChangeHandler<T, A>>,
737 style: SelectStyle,
739 popup_placement: PopupPlacement,
741 default_open: bool,
743}
744
745impl<T: Clone + PartialEq + 'static, A: 'static> ComponentNode<A> for SelectComponent<T, A> {
746 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 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
808struct SelectWidget<T, A> {
810 layout: LayoutStyle,
812 placeholder: Binding<String>,
814 options: Vec<SelectOption<T>>,
816 selected: Option<Binding<T>>,
818 bound: Option<Signal<T>>,
820 disabled: Binding<bool>,
822 on_change: Option<SelectChangeHandler<T, A>>,
824 style: SelectStyle,
826 popup_placement: PopupPlacement,
828 active_index: Signal<Option<usize>>,
830 popup: PopupPortalBridge<A>,
832}
833
834impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for SelectWidget<T, A> {
835 fn debug_name(&self) -> &'static str {
837 "Select"
838 }
839
840 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 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 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 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 fn selected_value(&self) -> Option<T> {
927 self.selected.as_ref().map(Binding::read)
928 }
929
930 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 fn current_label(&self) -> Option<String> {
940 let idx = self.selected_index()?;
941 Some(self.options[idx].label.clone())
942 }
943
944 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 fn popup_height(&self) -> f32 {
951 (self.options.len() as f32 * self.style.option_height).min(self.style.popup_max_height)
952 }
953
954 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 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 fn close(&self, reason: PopupDismissReason) {
974 self.active_index.set(None);
975 self.popup.close(reason);
976 }
977
978 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 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 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 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 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 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 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 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 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
1115pub struct DropdownItem<A = ()> {
1128 label: String,
1130 action: Option<Rc<ClickAction<A>>>,
1132 disabled: Binding<bool>,
1134 icon: Option<IconId>,
1136}
1137
1138impl<A> Clone for DropdownItem<A> {
1139 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 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 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 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1195 self.disabled = disabled.into();
1196 self
1197 }
1198
1199 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1211 self.disabled(disabled)
1212 }
1213
1214 pub fn leading_icon(mut self, icon: IconId) -> Self {
1225 self.icon = Some(icon);
1226 self
1227 }
1228}
1229
1230pub struct Dropdown<A = ()> {
1244 pub(crate) layout: LayoutStyle,
1246 pub(crate) flex_item: FlexItemStyle,
1248 label: Binding<String>,
1250 items: Vec<DropdownItem<A>>,
1252 disabled: Binding<bool>,
1254 style: DropdownStyle,
1256 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 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 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 pub fn dropdown_item(mut self, item: DropdownItem<A>) -> Self {
1320 self.items.push(item);
1321 self
1322 }
1323
1324 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1337 self.disabled = disabled.into();
1338 self
1339 }
1340
1341 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
1353 self.disabled(disabled)
1354 }
1355
1356 pub fn default_open(mut self, open: bool) -> Self {
1366 self.default_open = open;
1367 self
1368 }
1369
1370 pub fn dropdown_style(mut self, style: DropdownStyle) -> Self {
1381 self.style = style;
1382 self
1383 }
1384
1385 pub fn dropdown_size(mut self, size: DropdownSize) -> Self {
1398 self.style = DropdownStyle::from_dropdown_theme(Theme::default(), size);
1399 self
1400 }
1401}
1402
1403struct DropdownComponent<A> {
1405 layout: LayoutStyle,
1407 label: Binding<String>,
1409 items: Vec<DropdownItem<A>>,
1411 disabled: Binding<bool>,
1413 style: DropdownStyle,
1415 default_open: bool,
1417}
1418
1419impl<A: 'static> ComponentNode<A> for DropdownComponent<A> {
1420 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 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
1471struct DropdownWidget<A> {
1473 layout: LayoutStyle,
1475 label: Binding<String>,
1477 items: Vec<DropdownItem<A>>,
1479 disabled: Binding<bool>,
1481 style: DropdownStyle,
1483 active_index: Signal<Option<usize>>,
1485 popup: PopupPortalBridge<A>,
1487}
1488
1489impl<A: 'static> Widget<A> for DropdownWidget<A> {
1490 fn debug_name(&self) -> &'static str {
1492 "Dropdown"
1493 }
1494
1495 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 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 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 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 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 fn popup_height(&self) -> f32 {
1591 (self.items.len() as f32 * self.style.option_height).min(self.style.popup_max_height)
1592 }
1593
1594 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 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 fn close(&self, reason: PopupDismissReason) {
1612 self.active_index.set(None);
1613 self.popup.close(reason);
1614 }
1615
1616 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 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 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 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 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 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 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 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 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
1741struct RetainedSelectPopup<T, A> {
1743 options: Vec<SelectOption<T>>,
1745 selected: Option<Binding<T>>,
1747 bound: Option<Signal<T>>,
1749 disabled: Binding<bool>,
1751 on_change: Option<SelectChangeHandler<T, A>>,
1753 style: SelectStyle,
1755 active_index: Signal<Option<usize>>,
1757 scroll: Signal<ScrollState>,
1759 popup_id: Option<PopupId>,
1761}
1762
1763impl<T: Clone, A> Clone for RetainedSelectPopup<T, A> {
1764 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 fn debug_name(&self) -> &'static str {
1783 "SelectPopup"
1784 }
1785
1786 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 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 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 fn focus_policy(&self) -> FocusPolicy {
1878 FocusPolicy::NotFocusable
1879 }
1880
1881 fn activation_policy(&self) -> ActivationPolicy {
1883 ActivationPolicy::SuppressOnFocusOnly
1884 }
1885
1886 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 fn selected_value(&self) -> Option<T> {
1908 self.selected.as_ref().map(Binding::read)
1909 }
1910
1911 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 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 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 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
1962struct RetainedDropdownPopup<A> {
1964 items: Vec<DropdownItem<A>>,
1966 disabled: Binding<bool>,
1968 style: DropdownStyle,
1970 active_index: Signal<Option<usize>>,
1972 scroll: Signal<ScrollState>,
1974 popup_id: Option<PopupId>,
1976}
1977
1978impl<A> Clone for RetainedDropdownPopup<A> {
1979 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 fn debug_name(&self) -> &'static str {
1995 "DropdownPopup"
1996 }
1997
1998 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 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 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 fn focus_policy(&self) -> FocusPolicy {
2085 FocusPolicy::NotFocusable
2086 }
2087
2088 fn activation_policy(&self) -> ActivationPolicy {
2090 ActivationPolicy::SuppressOnFocusOnly
2091 }
2092
2093 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 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 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 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
2146fn 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
2153fn dropdown_popup_content<A: 'static>(popup: RetainedDropdownPopup<A>) -> PopupContent<A> {
2155 PopupContent::new(move || View::leaf(popup.clone()))
2156}
2157
2158fn 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
2171fn 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
2186fn 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
2203fn 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
2218fn 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)]
2248enum Direction {
2250 Next,
2252 Previous,
2254}
2255
2256fn 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
2265fn 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
2281fn 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
2302fn 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
2323fn 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
2416fn 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
2469fn 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}