1use std::borrow::Cow;
37
38use iced::advanced::layout;
39use iced::advanced::widget::operation::{Focusable, TextInput};
40use iced::advanced::widget::{Id, Operation, Tree, Widget, tree};
41use iced::advanced::{Clipboard, Layout, Shell, overlay, renderer};
42use iced::keyboard::{self, key::Named};
43use iced::time::Duration;
44use iced::widget::pick_list::{self, Status};
45use iced::widget::text::LineHeight;
46use iced::widget::{container, row};
47use iced::{
48 Alignment, Background, Border, Color, Element, Event, Length, Padding, Pixels, Rectangle,
49 Renderer, Size, Theme, Vector, mouse, touch,
50};
51
52use crate::data::ellipsis::ellipsis;
53use crate::focus;
54use crate::forms::matching;
55use crate::icon::{opacity, themed};
56use crate::keys::{self, Chord, Keymap};
57use crate::overlay::anchored::{self, Align, Behaviour, Placement, Side};
58use crate::overlay::menu::{self, Parts, ROW_PADDING, RowStatus, Trailing};
59use crate::primitives::input;
60pub use crate::primitives::input::{Shortcut, Shortcuts};
61use crate::theme::{Tokens, fade, mix, radius, space, text_size};
62
63mod list;
64mod navigate;
65
66use list::{List, ListState, Search};
67pub use list::{list_id, search_id};
68
69pub const HEIGHT: f32 = 36.0;
71
72pub const MAX_VISIBLE_ROWS: usize = 8;
75
76pub const TYPE_AHEAD_PAUSE: Duration = Duration::from_secs(1);
78
79pub const NO_OPTIONS: &str = "No options";
81
82pub const DEFAULT_EMPTY: &str = "No results found.";
84
85pub const DEFAULT_NOT_VALID: &str = "Not valid";
87
88const CHEVRON_SIZE: f32 = 16.0;
89const LINE_HEIGHT: f32 = 20.0;
90
91pub struct Select<'a, T: Clone, Message> {
95 options: Cow<'a, [T]>,
96 selected: Option<T>,
97 placeholder: Option<String>,
98 width: Length,
99 on_select: Option<Box<dyn Fn(T) -> Message + 'a>>,
100 leading: Option<Leading<'a, T, Message>>,
101 max_rows: usize,
102 scrollable: bool,
103 searchable: bool,
104 on_custom: Option<OnCustom<'a, Message>>,
105 search_placeholder: Option<String>,
106 shortcuts: Shortcuts,
107 empty: String,
108 not_valid: String,
109 type_ahead_pause: Duration,
110 prefer_custom: bool,
111 commit_on_leave: bool,
112 pass_through: bool,
113 editable: bool,
114}
115
116type Leading<'a, T, Message> = Box<dyn Fn(&T) -> Option<Element<'a, Message>> + 'a>;
117type OnCustom<'a, Message> = Box<dyn Fn(String) -> Option<Message> + 'a>;
118
119impl<T: Clone + std::fmt::Debug, Message> std::fmt::Debug for Select<'_, T, Message> {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 f.debug_struct("Select")
122 .field("options", &self.options)
123 .field("selected", &self.selected)
124 .field("placeholder", &self.placeholder)
125 .field("enabled", &self.on_select.is_some())
126 .field("leading", &self.leading.is_some())
127 .field("max_rows", &self.max_rows)
128 .field("scrollable", &self.scrollable)
129 .field("searchable", &self.searchable)
130 .field("shortcuts", &self.shortcuts)
131 .field("custom", &self.on_custom.is_some())
132 .field("prefer_custom", &self.prefer_custom)
133 .field("commit_on_leave", &self.commit_on_leave)
134 .field("pass_through", &self.pass_through)
135 .field("editable", &self.editable)
136 .finish_non_exhaustive()
137 }
138}
139
140pub fn select<'a, T, Message>(
145 options: impl Into<Cow<'a, [T]>>,
146 selected: Option<T>,
147) -> Select<'a, T, Message>
148where
149 T: ToString + PartialEq + Clone,
150{
151 Select {
152 options: options.into(),
153 selected,
154 placeholder: None,
155 width: Length::Fixed(200.0),
156 on_select: None,
157 leading: None,
158 max_rows: MAX_VISIBLE_ROWS,
159 scrollable: true,
160 searchable: false,
161 on_custom: None,
162 search_placeholder: None,
163 shortcuts: Shortcuts::all(),
164 empty: DEFAULT_EMPTY.to_owned(),
165 not_valid: DEFAULT_NOT_VALID.to_owned(),
166 type_ahead_pause: TYPE_AHEAD_PAUSE,
167 prefer_custom: false,
168 commit_on_leave: false,
169 pass_through: false,
170 editable: false,
171 }
172}
173
174impl<'a, T: Clone, Message> Select<'a, T, Message> {
175 pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
177 self.placeholder = Some(placeholder.into());
178 self
179 }
180
181 pub fn width(mut self, width: impl Into<Length>) -> Self {
182 self.width = width.into();
183 self
184 }
185
186 pub fn on_select(mut self, on_select: impl Fn(T) -> Message + 'a) -> Self {
188 self.on_select = Some(Box::new(on_select));
189 self
190 }
191
192 pub fn on_select_maybe(mut self, on_select: Option<impl Fn(T) -> Message + 'a>) -> Self {
195 self.on_select = on_select.map(|f| Box::new(f) as Box<dyn Fn(T) -> Message + 'a>);
196 self
197 }
198
199 pub fn leading(mut self, leading: impl Fn(&T) -> Option<Element<'a, Message>> + 'a) -> Self {
204 self.leading = Some(Box::new(leading));
205 self
206 }
207
208 pub fn max_visible_rows(mut self, rows: usize) -> Self {
211 self.max_rows = rows.max(1);
212 self
213 }
214
215 pub fn scrollable(mut self, scrollable: bool) -> Self {
218 self.scrollable = scrollable;
219 self
220 }
221
222 pub fn searchable(mut self, searchable: bool) -> Self {
226 self.searchable = searchable;
227 self
228 }
229
230 pub fn on_custom(mut self, on_custom: impl Fn(String) -> Option<Message> + 'a) -> Self {
242 self.on_custom = Some(Box::new(on_custom));
243 self
244 }
245
246 pub fn prefer_custom(mut self, prefer: bool) -> Self {
256 self.prefer_custom = prefer;
257 self
258 }
259
260 pub fn commit_on_leave(mut self, commit: bool) -> Self {
268 self.commit_on_leave = commit;
269 self
270 }
271
272 pub fn pass_through(mut self, pass_through: bool) -> Self {
276 self.pass_through = pass_through;
277 self
278 }
279
280 pub fn editable(mut self, editable: bool) -> Self {
290 self.editable = editable;
291 self
292 }
293
294 pub fn search_placeholder(mut self, placeholder: impl Into<String>) -> Self {
297 self.search_placeholder = Some(placeholder.into());
298 self
299 }
300
301 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
305 self.shortcuts = shortcuts;
306 self
307 }
308
309 pub fn empty(mut self, empty: impl Into<String>) -> Self {
312 self.empty = empty.into();
313 self
314 }
315
316 pub fn not_valid(mut self, text: impl Into<String>) -> Self {
320 self.not_valid = text.into();
321 self
322 }
323
324 pub fn type_ahead_pause(mut self, pause: Duration) -> Self {
327 self.type_ahead_pause = pause;
328 self
329 }
330
331 pub fn is_enabled(&self) -> bool {
332 self.on_select.is_some()
333 }
334}
335
336impl<'a, T, Message> From<Select<'a, T, Message>> for Element<'a, Message>
337where
338 T: ToString + PartialEq + Clone + 'a,
339 Message: Clone + 'a,
340{
341 fn from(select: Select<'a, T, Message>) -> Self {
342 let Select {
343 options,
344 selected,
345 placeholder,
346 width,
347 on_select,
348 leading,
349 max_rows,
350 scrollable,
351 searchable,
352 on_custom,
353 search_placeholder,
354 shortcuts,
355 empty,
356 not_valid,
357 type_ahead_pause,
358 prefer_custom,
359 commit_on_leave,
360 pass_through,
361 editable,
362 } = select;
363 let enabled = on_select.is_some();
364 let leading_of = |option: &T| leading.as_ref().and_then(|leading| leading(option));
365 let label = selected.as_ref().map(ToString::to_string);
366 let has_value = label.is_some();
367 let editable = editable.then(|| Editable {
368 label: label.clone().unwrap_or_default(),
369 placeholder: placeholder.clone().unwrap_or_default(),
370 shortcuts,
371 width,
372 });
373
374 let text_colour = move |theme: &Theme| {
375 let style = style(&Tokens::of(theme), Status::Active, enabled);
376 if has_value {
377 style.text_color
378 } else {
379 style.placeholder_color
380 }
381 };
382 let chevron = themed(
383 crate::lucide!(ChevronDown),
384 CHEVRON_SIZE,
385 opacity(enabled),
386 move |theme| style(&Tokens::of(theme), Status::Active, enabled).handle_color,
387 );
388 let selected_leading = selected.as_ref().and_then(leading_of);
389 let field = row![]
391 .push(selected_leading)
392 .push(ellipsis(label.or(placeholder).unwrap_or_default()).colour(text_colour))
393 .push(chevron)
394 .spacing(space::SM)
395 .align_y(Alignment::Center)
396 .padding([(HEIGHT - LINE_HEIGHT) / 2.0, space::MD])
397 .width(width)
398 .height(HEIGHT);
399
400 let rows = options
401 .iter()
402 .map(|option| {
403 let is_selected = selected.as_ref() == Some(option);
404 option_row(&option.to_string(), leading_of(option), is_selected)
405 })
406 .collect();
407 let choices = options
408 .iter()
409 .map(|option| {
410 on_select
411 .as_deref()
412 .map(|on_select| on_select(option.clone()))
413 })
414 .collect();
415 let search = (searchable || on_custom.is_some() || editable.is_some()).then(|| {
416 let placeholder = search_placeholder
417 .unwrap_or_else(|| if searchable { "Search" } else { "Type a value" }.to_owned());
418 Search {
419 filters: searchable,
420 on_custom,
421 placeholder,
422 shortcuts,
423 on_anchor: editable.is_some(),
424 prefer_custom,
425 commit_on_leave,
426 }
427 });
428 let max_rows = scrollable.then_some(max_rows);
429 let list = List {
430 rows,
431 labels: matching::lowercase(&options),
432 choices,
433 selected: selected
434 .as_ref()
435 .and_then(|value| options.iter().position(|option| option == value)),
436 max_rows,
437 search,
438 pause: type_ahead_pause,
439 empty: NO_OPTIONS.to_owned(),
440 no_results: empty,
441 not_valid,
442 };
443 let list = menu::surface(Element::new(list)).width(Length::Fill).into();
444
445 Element::new(Picker {
446 field: field.into(),
447 list,
448 enabled,
449 behaviour: Behaviour {
450 placement: Placement::new(Side::Bottom, Align::Start),
451 match_width: true,
452 fit_height: max_rows.is_some(),
453 closes_itself: true,
454 pass_through,
455 ..Behaviour::default()
456 },
457 editable,
458 })
459 }
460}
461
462fn option_row<'a, Message: 'a>(
465 label: &str,
466 leading: Option<Element<'a, Message>>,
467 selected: bool,
468) -> Element<'a, Message> {
469 let trailing = if selected {
470 Trailing::Check
471 } else {
472 Trailing::None
473 };
474 let parts = Parts {
475 trailing,
476 ..Parts::label(label)
477 };
478 let content = menu::content(parts, RowStatus::Idle, false);
479 let content = match leading {
480 Some(leading) => row![leading, content]
481 .spacing(space::SM)
482 .align_y(Alignment::Center),
483 None => content,
484 };
485 menu::inset(container(content).padding(ROW_PADDING).width(Length::Fill))
486}
487
488struct Editable {
490 label: String,
491 placeholder: String,
492 shortcuts: Shortcuts,
493 width: Length,
494}
495
496impl Editable {
497 fn field(&self, text: &str, rejected: bool, enabled: bool) -> Element<'static, String> {
500 let vertical = (HEIGHT - LINE_HEIGHT) / 2.0;
501 let field = iced::widget::text_input(&self.placeholder, text)
502 .size(text_size::SM)
503 .line_height(LineHeight::Absolute(Pixels(LINE_HEIGHT)))
504 .padding(Padding {
505 top: vertical,
506 bottom: vertical,
507 left: space::MD,
508 right: space::SM,
509 })
510 .width(Length::Fill)
511 .style(move |theme, _status| list::field_style(&Tokens::of(theme), rejected, enabled));
512 let on_input =
513 enabled.then(|| Box::new(|value: String| value) as Box<dyn Fn(String) -> String>);
514 let field = input::with_shortcuts(
515 field,
516 text,
517 false,
518 on_input,
519 input::default_keymap(),
520 self.shortcuts,
521 );
522 let chevron = themed(
523 crate::lucide!(ChevronDown),
524 CHEVRON_SIZE,
525 opacity(enabled),
526 move |theme| style(&Tokens::of(theme), Status::Active, enabled).handle_color,
527 );
528 row![field, chevron]
529 .align_y(Alignment::Center)
530 .padding(Padding::ZERO.right(space::MD))
531 .width(self.width)
532 .height(HEIGHT)
533 .into()
534 }
535}
536
537fn on_chevron(bounds: Rectangle, x: f32) -> bool {
539 x >= bounds.x + bounds.width - (CHEVRON_SIZE + space::MD + space::SM)
540}
541
542#[derive(Default)]
544struct HasFocus(bool);
545
546impl Operation for HasFocus {
547 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
548 operate(self);
549 }
550
551 fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) {
552 self.0 |= state.is_focused();
553 }
554}
555
556struct SelectAll;
558
559impl Operation for SelectAll {
560 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
561 operate(self);
562 }
563
564 fn text_input(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) {
565 state.select_all();
566 }
567}
568
569fn has_focus(
570 field: &mut Element<'static, String>,
571 tree: &mut Tree,
572 layout: Layout<'_>,
573 renderer: &Renderer,
574) -> bool {
575 let mut find = HasFocus::default();
576 field
577 .as_widget_mut()
578 .operate(tree, layout, renderer, &mut find);
579 find.0
580}
581
582fn is_press(event: &Event) -> bool {
583 matches!(
584 event,
585 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
586 | Event::Touch(touch::Event::FingerPressed { .. })
587 )
588}
589
590fn is_tab(event: &Event) -> bool {
591 matches!(
592 event,
593 Event::Keyboard(keyboard::Event::KeyPressed {
594 key: keyboard::Key::Named(Named::Tab),
595 ..
596 })
597 )
598}
599
600struct Picker<'a, Message> {
602 field: Element<'a, Message>,
603 list: Element<'a, Message>,
604 enabled: bool,
605 behaviour: Behaviour<'a, Message>,
606 editable: Option<Editable>,
607}
608
609#[derive(Debug, Default)]
610struct PickerState {
611 panel: anchored::State,
612 hovered: bool,
613 focus: focus::State,
614 field_focused: bool,
616}
617
618fn opens_list(key: Named) -> bool {
620 matches!(key, Named::Space | Named::Enter | Named::ArrowDown)
621}
622
623fn chooses(key: Named) -> bool {
625 matches!(key, Named::Space | Named::Enter)
626}
627
628impl<Message> Picker<'_, Message> {
629 fn open(&self, tree: &mut Tree) {
631 if let Some(list) = tree.children.get_mut(1) {
632 *list = Tree::new(&self.list);
633 }
634 let panel = &mut tree.state.downcast_mut::<PickerState>().panel;
635 panel.open = true;
636 panel.side = None;
637 }
638
639 fn close(tree: &mut Tree, shell: &mut Shell<'_, Message>) {
642 tree.state.downcast_mut::<PickerState>().panel.open = false;
643 shell.invalidate_layout();
644 shell.request_redraw();
645 }
646
647 fn open_list(tree: &Tree) -> Option<&ListState> {
649 let open = tree.state.downcast_ref::<PickerState>().panel.open;
650 tree.children
651 .get(1)
652 .filter(|_| open)
653 .and_then(list::state_ref)
654 }
655
656 fn editable_field(&self, tree: &Tree) -> Option<Element<'static, String>> {
659 let editable = self.editable.as_ref()?;
660 let list = Self::open_list(tree);
661 let text = list
662 .and_then(ListState::edited_query)
663 .unwrap_or(&editable.label);
664 let rejected = list.is_some_and(ListState::is_rejected);
665 Some(editable.field(text, rejected, self.enabled))
666 }
667
668 #[allow(clippy::too_many_arguments)]
671 fn update_editable(
672 &mut self,
673 tree: &mut Tree,
674 event: &Event,
675 layout: Layout<'_>,
676 cursor: mouse::Cursor,
677 renderer: &Renderer,
678 clipboard: &mut dyn Clipboard,
679 shell: &mut Shell<'_, Message>,
680 viewport: &Rectangle,
681 ) {
682 let bounds = layout.bounds();
683 let state = tree.state.downcast_mut::<PickerState>();
684 let open = state.panel.open;
685 let over = cursor.is_over(bounds);
686 if over != state.hovered {
687 state.hovered = over;
688 shell.request_redraw();
689 }
690 if open && (is_tab(event) || focus::named_press(event) == Some(Named::Enter)) {
693 Self::close(tree, shell);
694 return;
695 }
696 if !open && state.field_focused && focus::named_press(event) == Some(Named::ArrowDown) {
697 self.open(tree);
698 shell.capture_event();
699 shell.request_redraw();
700 return;
701 }
702 let press = is_press(event)
703 .then(|| cursor.position_over(bounds))
704 .flatten();
705 if open && press.is_some_and(|position| on_chevron(bounds, position.x)) {
706 Self::close(tree, shell);
707 shell.capture_event();
708 return;
709 }
710
711 let (Some(mut field), Some(field_tree)) =
712 (self.editable_field(tree), tree.children.first_mut())
713 else {
714 return;
715 };
716 let mut typed = Vec::new();
717 let mut inner = Shell::new(&mut typed);
718 field.as_widget_mut().update(
719 field_tree, event, layout, cursor, renderer, clipboard, &mut inner, viewport,
720 );
721 list::relay(shell, &inner);
722 let focused = has_focus(&mut field, field_tree, layout, renderer);
723
724 let state = tree.state.downcast_mut::<PickerState>();
725 if focused != state.field_focused {
726 state.field_focused = focused;
727 shell.request_redraw();
728 }
729 let mut is_open = state.panel.open;
730 if press.is_some() && !is_open {
731 self.open(tree);
732 is_open = true;
733 shell.capture_event();
734 shell.request_redraw();
735 }
736 if let Some(text) = typed.pop() {
737 if !is_open {
738 self.open(tree);
739 is_open = true;
740 }
741 if let Some(list) = tree.children.get_mut(1).and_then(list::state_mut) {
742 list.edit(text);
743 }
744 shell.invalidate_layout();
745 shell.request_redraw();
746 }
747 if is_open && matches!(event, Event::Keyboard(keyboard::Event::KeyPressed { .. })) {
749 shell.capture_event();
750 }
751 }
752}
753
754impl<Message: Clone> Widget<Message, Theme, Renderer> for Picker<'_, Message> {
755 fn tag(&self) -> tree::Tag {
756 tree::Tag::of::<PickerState>()
757 }
758
759 fn state(&self) -> tree::State {
760 tree::State::new(PickerState::default())
761 }
762
763 fn children(&self) -> Vec<Tree> {
764 let field = match &self.editable {
765 Some(editable) => Tree::new(editable.field(&editable.label, false, self.enabled)),
766 None => Tree::new(&self.field),
767 };
768 vec![field, Tree::new(&self.list)]
769 }
770
771 fn diff(&self, tree: &mut Tree) {
772 let Some(field) = self.editable_field(tree) else {
773 tree.diff_children(&[&self.field, &self.list]);
774 return;
775 };
776 let [field_tree, list_tree] = tree.children.as_mut_slice() else {
777 tree.children = vec![Tree::new(&field), Tree::new(&self.list)];
778 return;
779 };
780 field_tree.diff(&field);
781 list_tree.diff(&self.list);
782 }
783
784 fn size(&self) -> Size<Length> {
785 self.field.as_widget().size()
786 }
787
788 fn layout(
789 &mut self,
790 tree: &mut Tree,
791 renderer: &Renderer,
792 limits: &layout::Limits,
793 ) -> layout::Node {
794 if let Some(mut field) = self.editable_field(tree) {
795 return field
796 .as_widget_mut()
797 .layout(&mut tree.children[0], renderer, limits);
798 }
799 self.field
800 .as_widget_mut()
801 .layout(&mut tree.children[0], renderer, limits)
802 }
803
804 fn draw(
805 &self,
806 tree: &Tree,
807 renderer: &mut Renderer,
808 theme: &Theme,
809 style: &renderer::Style,
810 layout: Layout<'_>,
811 cursor: mouse::Cursor,
812 viewport: &Rectangle,
813 ) {
814 let state = tree.state.downcast_ref::<PickerState>();
815 let bounds = layout.bounds();
816 let hovered = self.enabled && cursor.is_over(bounds);
817 let status = field_status(state.panel.open || state.field_focused, hovered);
818 let tokens = Tokens::of(theme);
819 let mut field = self::style(&tokens, status, self.enabled);
820 if Self::open_list(tree).is_some_and(ListState::is_rejected) && self.editable.is_some() {
821 field.border.color = tokens.destructive;
822 }
823 <Renderer as renderer::Renderer>::fill_quad(
824 renderer,
825 renderer::Quad {
826 bounds,
827 border: field.border,
828 ..renderer::Quad::default()
829 },
830 field.background,
831 );
832 if let Some(field) = self.editable_field(tree) {
833 field.as_widget().draw(
834 &tree.children[0],
835 renderer,
836 theme,
837 style,
838 layout,
839 cursor,
840 viewport,
841 );
842 return;
843 }
844 self.field.as_widget().draw(
845 &tree.children[0],
846 renderer,
847 theme,
848 style,
849 layout,
850 cursor,
851 viewport,
852 );
853 if self.enabled && state.focus.is_focused() {
854 focus::draw_ring(renderer, theme, bounds, radius::MD);
855 }
856 }
857
858 fn operate(
859 &mut self,
860 tree: &mut Tree,
861 layout: Layout<'_>,
862 renderer: &Renderer,
863 operation: &mut dyn Operation,
864 ) {
865 if let Some(mut field) = self.editable_field(tree) {
866 let Some(field_tree) = tree.children.first_mut() else {
867 return;
868 };
869 field
870 .as_widget_mut()
871 .operate(field_tree, layout, renderer, operation);
872 let focused = has_focus(&mut field, field_tree, layout, renderer);
873 let state = tree.state.downcast_mut::<PickerState>();
874 if focused && !state.field_focused {
877 field
878 .as_widget_mut()
879 .operate(field_tree, layout, renderer, &mut SelectAll);
880 }
881 state.field_focused = focused;
882 return;
883 }
884 if self.enabled {
885 let state = tree.state.downcast_mut::<PickerState>();
886 focus::report(operation, None, layout.bounds(), &mut state.focus);
887 }
888 self.field
889 .as_widget_mut()
890 .operate(&mut tree.children[0], layout, renderer, operation);
891 }
892
893 fn update(
894 &mut self,
895 tree: &mut Tree,
896 event: &Event,
897 layout: Layout<'_>,
898 cursor: mouse::Cursor,
899 renderer: &Renderer,
900 clipboard: &mut dyn Clipboard,
901 shell: &mut Shell<'_, Message>,
902 viewport: &Rectangle,
903 ) {
904 if !self.enabled {
905 return;
906 }
907 if self.editable.is_some() {
908 self.update_editable(
909 tree, event, layout, cursor, renderer, clipboard, shell, viewport,
910 );
911 return;
912 }
913 let state = tree.state.downcast_mut::<PickerState>();
914 if state.focus.update(event) {
915 shell.request_redraw();
916 }
917 if let Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) = event
922 && state.panel.open
923 {
924 if *key == keyboard::Key::Named(Named::Tab) {
925 state.panel.open = false;
926 shell.request_redraw();
927 return;
928 }
929 if focus::named_press(event).is_some_and(chooses) {
930 state.panel.open = false;
931 shell.request_redraw();
932 }
933 shell.capture_event();
934 return;
935 }
936 if state.focus.is_focused() && focus::named_press(event).is_some_and(opens_list) {
937 self.open(tree);
938 shell.capture_event();
939 shell.request_redraw();
940 return;
941 }
942 let over = cursor.is_over(layout.bounds());
943 if over != state.hovered {
944 state.hovered = over;
945 shell.request_redraw();
946 }
947 let pressed = matches!(
948 event,
949 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
950 | Event::Touch(touch::Event::FingerPressed { .. })
951 );
952 if !pressed || !over {
953 return;
954 }
955 if state.panel.open {
956 state.panel.open = false;
957 } else {
958 self.open(tree);
959 }
960 shell.capture_event();
961 shell.request_redraw();
962 }
963
964 fn mouse_interaction(
965 &self,
966 _tree: &Tree,
967 layout: Layout<'_>,
968 cursor: mouse::Cursor,
969 _viewport: &Rectangle,
970 _renderer: &Renderer,
971 ) -> mouse::Interaction {
972 let bounds = layout.bounds();
973 let Some(position) = cursor.position_over(bounds).filter(|_| self.enabled) else {
974 return mouse::Interaction::default();
975 };
976 if self.editable.is_some() && !on_chevron(bounds, position.x) {
977 return mouse::Interaction::Text;
978 }
979 mouse::Interaction::Pointer
980 }
981
982 fn overlay<'b>(
983 &'b mut self,
984 tree: &'b mut Tree,
985 layout: Layout<'b>,
986 _renderer: &Renderer,
987 _viewport: &Rectangle,
988 translation: Vector,
989 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
990 let Tree {
991 state, children, ..
992 } = tree;
993 let state = state.downcast_mut::<PickerState>();
994 if !self.enabled || !state.panel.open {
995 return None;
996 }
997 let list_tree = children.get_mut(1)?;
998 if let Some(list) = list::state_mut(list_tree) {
999 list.set_anchor(layout.bounds() + translation);
1000 }
1001 Some(anchored::floating(
1002 &mut self.list,
1003 list_tree,
1004 &mut state.panel,
1005 &self.behaviour,
1006 layout.bounds() + translation,
1007 ))
1008 }
1009}
1010
1011fn field_status(open: bool, hovered: bool) -> Status {
1014 match (open, hovered) {
1015 (true, is_hovered) => Status::Opened { is_hovered },
1016 (false, true) => Status::Hovered,
1017 (false, false) => Status::Active,
1018 }
1019}
1020
1021pub fn style(tokens: &Tokens, status: Status, enabled: bool) -> pick_list::Style {
1023 let border = match status {
1024 Status::Active => tokens.border,
1025 Status::Hovered => mix(tokens.border, tokens.foreground, 0.3),
1026 Status::Opened { .. } => mix(tokens.border, tokens.foreground, 0.6),
1027 };
1028 let style = pick_list::Style {
1029 text_color: tokens.foreground,
1030 placeholder_color: tokens.muted_foreground,
1031 handle_color: tokens.muted_foreground,
1032 background: Background::Color(Color::TRANSPARENT),
1034 border: Border {
1035 color: border,
1036 width: 1.0,
1037 radius: radius::MD.into(),
1038 },
1039 };
1040
1041 if enabled {
1042 return style;
1043 }
1044 pick_list::Style {
1045 text_color: fade(tokens.foreground, 0.5),
1046 placeholder_color: fade(tokens.muted_foreground, 0.5),
1047 handle_color: fade(tokens.muted_foreground, 0.5),
1048 background: Background::Color(tokens.disabled_field()),
1049 border: Border {
1050 color: fade(tokens.border, 0.5),
1051 ..style.border
1052 },
1053 }
1054}
1055
1056#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1058pub enum Action {
1059 Next,
1060 Previous,
1061}
1062
1063impl Action {
1064 pub fn apply<T: PartialEq + Clone>(self, options: &[T], selected: Option<&T>) -> Option<T> {
1069 let current = selected.and_then(|value| options.iter().position(|option| option == value));
1070 let target = match (self, current) {
1071 (Action::Next, None) => 0,
1072 (Action::Previous, None) => options.len().checked_sub(1)?,
1073 (Action::Next, Some(index)) => index + 1,
1074 (Action::Previous, Some(index)) => index.checked_sub(1)?,
1075 };
1076 options.get(target).cloned()
1077 }
1078}
1079
1080impl keys::Action for Action {
1081 const ALL: &'static [Self] = &[Action::Next, Action::Previous];
1082
1083 fn defaults() -> Keymap<Self> {
1084 default_keymap()
1085 }
1086
1087 fn name(self) -> &'static str {
1088 match self {
1089 Action::Next => "Next",
1090 Action::Previous => "Previous",
1091 }
1092 }
1093
1094 fn description(self) -> &'static str {
1095 match self {
1096 Action::Next => "Selects the next option, stopping at the last.",
1097 Action::Previous => "Selects the previous option, stopping at the first.",
1098 }
1099 }
1100}
1101
1102pub fn default_keymap() -> Keymap<Action> {
1114 Keymap::new()
1115 .bind(Chord::named(Named::ArrowDown), Action::Next)
1116 .bind(Chord::named(Named::ArrowUp), Action::Previous)
1117}
1118
1119#[cfg(test)]
1120mod tests {
1121 use super::*;
1122 use crate::theme::{dark, light};
1123
1124 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1125 let chord: Chord = chord.parse().unwrap();
1126 keymap.resolve(chord.key(), chord.modifiers())
1127 }
1128
1129 #[test]
1130 fn default_keymap_and_overrides() {
1131 let keymap = default_keymap();
1132 assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
1133 assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
1134 let custom = keymap
1135 .bind("J".parse().unwrap(), Action::Next)
1136 .unbind(&"ArrowDown".parse().unwrap());
1137 assert_eq!(press(&custom, "j"), Some(Action::Next));
1138 assert_eq!(press(&custom, "ArrowDown"), None);
1139 }
1140
1141 #[test]
1142 fn next_and_previous_stop_at_the_ends() {
1143 let options = ["a", "b", "c"];
1144 assert_eq!(Action::Next.apply(&options, Some(&"a")), Some("b"));
1145 assert_eq!(Action::Next.apply(&options, Some(&"c")), None);
1146 assert_eq!(Action::Previous.apply(&options, Some(&"b")), Some("a"));
1147 assert_eq!(Action::Previous.apply(&options, Some(&"a")), None);
1148 }
1149
1150 #[test]
1151 fn without_a_selection_next_and_previous_pick_an_end() {
1152 let options = ["a", "b", "c"];
1153 assert_eq!(Action::Next.apply(&options, None), Some("a"));
1154 assert_eq!(Action::Previous.apply(&options, None), Some("c"));
1155 assert_eq!(Action::Next.apply(&options, Some(&"z")), Some("a"));
1156 let empty: [&str; 0] = [];
1157 assert_eq!(Action::Next.apply(&empty, None), None);
1158 assert_eq!(Action::Previous.apply(&empty, None), None);
1159 }
1160
1161 const STATES: [Status; 4] = [
1162 Status::Active,
1163 Status::Hovered,
1164 Status::Opened { is_hovered: false },
1165 Status::Opened { is_hovered: true },
1166 ];
1167
1168 #[test]
1169 fn default_builder_has_no_selection_and_is_disabled() {
1170 let s: Select<'_, &str, ()> = select(vec!["a", "b"], None);
1171 assert_eq!(s.options.len(), 2);
1172 assert!(s.selected.is_none());
1173 assert!(s.placeholder.is_none());
1174 assert_eq!(s.width, Length::Fixed(200.0));
1175 assert!(!s.is_enabled());
1176 assert!(s.leading.is_none());
1177 }
1178
1179 #[test]
1180 fn leading_is_asked_per_option() {
1181 let s: Select<'_, &str, ()> = select(vec!["red", "plain"], None).leading(|option| {
1182 (*option == "red")
1183 .then(|| crate::theme::swatch_color(Color::from_rgb(1.0, 0.0, 0.0)).into())
1184 });
1185 let Some(leading) = s.leading.as_ref() else {
1186 panic!("leading is set");
1187 };
1188 assert!(leading(&"red").is_some());
1189 assert!(leading(&"plain").is_none());
1190 }
1191
1192 #[test]
1193 fn builder_sets_placeholder_and_message() {
1194 const OPTIONS: &[u8] = &[1, 2, 3];
1195 let s: Select<'_, u8, u8> = select(OPTIONS, Some(2))
1196 .placeholder("Pick a number")
1197 .on_select(|v| v);
1198 assert_eq!(s.placeholder.as_deref(), Some("Pick a number"));
1199 assert!(s.is_enabled());
1200 assert!(matches!(s.options, Cow::Borrowed(_)));
1201 }
1202
1203 #[test]
1204 fn on_select_maybe_enables_only_with_a_message() {
1205 let enabled: Select<'_, u8, u8> = select(vec![1, 2], None).on_select_maybe(Some(|v| v));
1206 assert!(enabled.is_enabled());
1207 let disabled: Select<'_, u8, u8> =
1208 select(vec![1, 2], None).on_select_maybe(None::<fn(u8) -> u8>);
1209 assert!(!disabled.is_enabled());
1210 }
1211
1212 #[test]
1213 fn hover_and_open_strengthen_the_border() {
1214 for theme in [light(), dark()] {
1215 let tokens = Tokens::of(&theme);
1216 let borders = STATES.map(|status| style(&tokens, status, true).border.color);
1217 assert_ne!(borders[0], borders[1]);
1218 assert_ne!(borders[1], borders[2]);
1219 assert_eq!(borders[2], borders[3]);
1220 }
1221 }
1222
1223 #[test]
1224 fn placeholder_is_muted() {
1225 for theme in [light(), dark()] {
1226 let tokens = Tokens::of(&theme);
1227 let style = style(&tokens, Status::Active, true);
1228 assert_eq!(style.placeholder_color, tokens.muted_foreground);
1229 assert_ne!(style.placeholder_color, style.text_color);
1230 }
1231 }
1232
1233 #[test]
1234 fn disabled_fades_text_and_uses_the_disabled_field_background() {
1235 for theme in [light(), dark()] {
1236 let tokens = Tokens::of(&theme);
1237 for status in STATES {
1238 let disabled = style(&tokens, status, false);
1239 assert!((disabled.text_color.a - tokens.foreground.a * 0.5).abs() < 1e-6);
1240 assert_eq!(
1241 disabled.background,
1242 Background::Color(tokens.disabled_field())
1243 );
1244 }
1245 }
1246 }
1247
1248 #[test]
1249 fn an_enabled_trigger_takes_the_colour_of_its_surface() {
1250 for theme in [light(), dark()] {
1251 let tokens = Tokens::of(&theme);
1252 for status in STATES {
1253 let enabled = style(&tokens, status, true);
1254 assert_eq!(enabled.background, Background::Color(Color::TRANSPARENT));
1255 }
1256 }
1257 }
1258
1259 #[test]
1260 fn long_lists_scroll_by_default_and_search_and_custom_values_are_off() {
1261 let s: Select<'_, &str, ()> = select(vec!["a", "b"], None);
1262 assert_eq!(s.max_rows, MAX_VISIBLE_ROWS);
1263 assert!(s.scrollable);
1264 assert!(!s.searchable);
1265 assert!(s.on_custom.is_none());
1266 assert_eq!(s.shortcuts, Shortcuts::all());
1267 assert_eq!(s.empty, DEFAULT_EMPTY);
1268 assert_eq!(s.not_valid, DEFAULT_NOT_VALID);
1269 assert_eq!(s.type_ahead_pause, TYPE_AHEAD_PAUSE);
1270 assert!(!s.prefer_custom && !s.commit_on_leave);
1271 assert!(!s.pass_through && !s.editable);
1272 }
1273
1274 #[test]
1275 fn typed_value_options_are_set_by_the_builder() {
1276 let s: Select<'_, &str, ()> = select(vec!["a"], None)
1277 .prefer_custom(true)
1278 .commit_on_leave(true)
1279 .pass_through(true)
1280 .editable(true);
1281 assert!(s.prefer_custom && s.commit_on_leave);
1282 assert!(s.pass_through && s.editable);
1283 }
1284
1285 #[test]
1286 fn the_chevron_takes_the_right_end_of_an_editable_field() {
1287 let bounds = Rectangle::new(iced::Point::ORIGIN, Size::new(200.0, HEIGHT));
1288 assert!(on_chevron(bounds, 190.0));
1289 assert!(on_chevron(bounds, 200.0 - CHEVRON_SIZE - space::MD));
1290 assert!(!on_chevron(bounds, 40.0));
1291 }
1292
1293 #[test]
1294 fn the_row_limit_and_scrolling_are_set_in_any_order() {
1295 let s: Select<'_, &str, ()> = select(vec!["a"], None).max_visible_rows(0);
1296 assert_eq!(s.max_rows, 1, "at least one row");
1297 let s: Select<'_, &str, ()> = select(vec!["a"], None)
1298 .scrollable(false)
1299 .max_visible_rows(5);
1300 assert!(!s.scrollable, "a row limit does not turn scrolling back on");
1301 let s: Select<'_, &str, ()> = select(vec!["a"], None)
1302 .max_visible_rows(5)
1303 .scrollable(false)
1304 .scrollable(true);
1305 assert_eq!(s.max_rows, 5, "the limit is kept");
1306 assert!(s.scrollable);
1307 }
1308
1309 #[test]
1310 fn search_and_custom_values_are_set_by_the_builder() {
1311 let s: Select<'_, &str, String> = select(vec!["a"], None)
1312 .searchable(true)
1313 .on_custom(|text| (!text.is_empty()).then_some(text))
1314 .search_placeholder("Find a time")
1315 .empty("Nothing")
1316 .not_valid("Use hh:mm")
1317 .shortcuts(Shortcuts::none())
1318 .type_ahead_pause(Duration::from_millis(500));
1319 assert!(s.searchable);
1320 assert_eq!(s.search_placeholder.as_deref(), Some("Find a time"));
1321 assert_eq!(s.empty, "Nothing");
1322 assert_eq!(s.not_valid, "Use hh:mm");
1323 assert_eq!(s.shortcuts, Shortcuts::none());
1324 assert_eq!(s.type_ahead_pause, Duration::from_millis(500));
1325 let Some(on_custom) = s.on_custom.as_ref() else {
1326 panic!("on_custom is set");
1327 };
1328 assert_eq!(on_custom("x".to_owned()), Some("x".to_owned()));
1329 assert_eq!(on_custom(String::new()), None);
1330 }
1331
1332 #[test]
1333 fn keys_that_open_and_choose() {
1334 for key in [Named::Space, Named::Enter, Named::ArrowDown] {
1335 assert!(opens_list(key), "{key:?}");
1336 }
1337 assert!(!opens_list(Named::ArrowUp));
1338 assert!(!opens_list(Named::Escape));
1339 assert!(chooses(Named::Space) && chooses(Named::Enter));
1340 assert!(!chooses(Named::ArrowDown));
1341 }
1342
1343 #[test]
1344 fn field_status_follows_the_list_and_the_pointer() {
1345 assert_eq!(field_status(false, false), Status::Active);
1346 assert_eq!(field_status(false, true), Status::Hovered);
1347 assert_eq!(
1348 field_status(true, false),
1349 Status::Opened { is_hovered: false }
1350 );
1351 assert_eq!(
1352 field_status(true, true),
1353 Status::Opened { is_hovered: true }
1354 );
1355 }
1356}