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 #[cfg(feature = "icedwright")]
368 let report = Report {
369 value: label.clone().unwrap_or_default(),
370 placeholder: placeholder.clone().unwrap_or_default(),
371 };
372 let editable = editable.then(|| Editable {
373 label: label.clone().unwrap_or_default(),
374 placeholder: placeholder.clone().unwrap_or_default(),
375 shortcuts,
376 width,
377 });
378
379 let text_colour = move |theme: &Theme| {
380 let style = style(&Tokens::of(theme), Status::Active, enabled);
381 if has_value {
382 style.text_color
383 } else {
384 style.placeholder_color
385 }
386 };
387 let chevron = themed(
388 crate::lucide!(ChevronDown),
389 CHEVRON_SIZE,
390 opacity(enabled),
391 move |theme| style(&Tokens::of(theme), Status::Active, enabled).handle_color,
392 );
393 let selected_leading = selected.as_ref().and_then(leading_of);
394 let field = row![]
396 .push(selected_leading)
397 .push(ellipsis(label.or(placeholder).unwrap_or_default()).colour(text_colour))
398 .push(chevron)
399 .spacing(space::SM)
400 .align_y(Alignment::Center)
401 .padding([(HEIGHT - LINE_HEIGHT) / 2.0, space::MD])
402 .width(width)
403 .height(HEIGHT);
404
405 let rows = options
406 .iter()
407 .map(|option| {
408 let is_selected = selected.as_ref() == Some(option);
409 let label = option.to_string();
410 let row = option_row(&label, leading_of(option), is_selected);
411 #[cfg(feature = "icedwright")]
412 let row = icedwright_probe::semantic(row)
413 .role(icedwright_probe::role::ListOption)
414 .name(label)
415 .selected(is_selected)
416 .disabled(!enabled)
417 .component(KIND)
418 .into();
419 row
420 })
421 .collect();
422 let choices = options
423 .iter()
424 .map(|option| {
425 on_select
426 .as_deref()
427 .map(|on_select| on_select(option.clone()))
428 })
429 .collect();
430 let search = (searchable || on_custom.is_some() || editable.is_some()).then(|| {
431 let placeholder = search_placeholder
432 .unwrap_or_else(|| if searchable { "Search" } else { "Type a value" }.to_owned());
433 Search {
434 filters: searchable,
435 on_custom,
436 placeholder,
437 shortcuts,
438 on_anchor: editable.is_some(),
439 prefer_custom,
440 commit_on_leave,
441 }
442 });
443 let max_rows = scrollable.then_some(max_rows);
444 let list = List {
445 rows,
446 labels: matching::lowercase(&options),
447 choices,
448 selected: selected
449 .as_ref()
450 .and_then(|value| options.iter().position(|option| option == value)),
451 max_rows,
452 search,
453 pause: type_ahead_pause,
454 empty: NO_OPTIONS.to_owned(),
455 no_results: empty,
456 not_valid,
457 };
458 let list: Element<'a, Message> =
459 menu::surface(Element::new(list)).width(Length::Fill).into();
460 #[cfg(feature = "icedwright")]
461 let list = icedwright_probe::semantic(list)
462 .role(icedwright_probe::role::ListBox)
463 .component(KIND)
464 .into();
465
466 Element::new(Picker {
467 field: field.into(),
468 list,
469 enabled,
470 behaviour: Behaviour {
471 placement: Placement::new(Side::Bottom, Align::Start),
472 match_width: true,
473 fit_height: max_rows.is_some(),
474 closes_itself: true,
475 pass_through,
476 #[cfg(feature = "icedwright")]
477 kind: KIND,
478 ..Behaviour::default()
479 },
480 editable,
481 #[cfg(feature = "icedwright")]
482 report,
483 })
484 }
485}
486
487fn option_row<'a, Message: 'a>(
490 label: &str,
491 leading: Option<Element<'a, Message>>,
492 selected: bool,
493) -> Element<'a, Message> {
494 let trailing = if selected {
495 Trailing::Check
496 } else {
497 Trailing::None
498 };
499 let parts = Parts {
500 trailing,
501 ..Parts::label(label)
502 };
503 let content = menu::content(parts, RowStatus::Idle, false);
504 let content = match leading {
505 Some(leading) => row![leading, content]
506 .spacing(space::SM)
507 .align_y(Alignment::Center),
508 None => content,
509 };
510 menu::inset(container(content).padding(ROW_PADDING).width(Length::Fill))
511}
512
513struct Editable {
515 label: String,
516 placeholder: String,
517 shortcuts: Shortcuts,
518 width: Length,
519}
520
521impl Editable {
522 fn field(&self, text: &str, rejected: bool, enabled: bool) -> Element<'static, String> {
525 let vertical = (HEIGHT - LINE_HEIGHT) / 2.0;
526 let field = iced::widget::text_input(&self.placeholder, text)
527 .size(text_size::SM)
528 .line_height(LineHeight::Absolute(Pixels(LINE_HEIGHT)))
529 .padding(Padding {
530 top: vertical,
531 bottom: vertical,
532 left: space::MD,
533 right: space::SM,
534 })
535 .width(Length::Fill)
536 .style(move |theme, _status| list::field_style(&Tokens::of(theme), rejected, enabled));
537 let on_input =
538 enabled.then(|| Box::new(|value: String| value) as Box<dyn Fn(String) -> String>);
539 let field = input::with_shortcuts(
540 field,
541 text,
542 false,
543 on_input,
544 input::default_keymap(),
545 self.shortcuts,
546 );
547 let chevron = themed(
548 crate::lucide!(ChevronDown),
549 CHEVRON_SIZE,
550 opacity(enabled),
551 move |theme| style(&Tokens::of(theme), Status::Active, enabled).handle_color,
552 );
553 row![field, chevron]
554 .align_y(Alignment::Center)
555 .padding(Padding::ZERO.right(space::MD))
556 .width(self.width)
557 .height(HEIGHT)
558 .into()
559 }
560}
561
562fn on_chevron(bounds: Rectangle, x: f32) -> bool {
564 x >= bounds.x + bounds.width - (CHEVRON_SIZE + space::MD + space::SM)
565}
566
567#[derive(Default)]
569struct HasFocus(bool);
570
571impl Operation for HasFocus {
572 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
573 operate(self);
574 }
575
576 fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Focusable) {
577 self.0 |= state.is_focused();
578 }
579}
580
581struct SelectAll;
583
584impl Operation for SelectAll {
585 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
586 operate(self);
587 }
588
589 fn text_input(&mut self, _id: Option<&Id>, _bounds: Rectangle, state: &mut dyn TextInput) {
590 state.select_all();
591 }
592}
593
594fn has_focus(
595 field: &mut Element<'static, String>,
596 tree: &mut Tree,
597 layout: Layout<'_>,
598 renderer: &Renderer,
599) -> bool {
600 let mut find = HasFocus::default();
601 field
602 .as_widget_mut()
603 .operate(tree, layout, renderer, &mut find);
604 find.0
605}
606
607fn is_press(event: &Event) -> bool {
608 matches!(
609 event,
610 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
611 | Event::Touch(touch::Event::FingerPressed { .. })
612 )
613}
614
615fn is_tab(event: &Event) -> bool {
616 matches!(
617 event,
618 Event::Keyboard(keyboard::Event::KeyPressed {
619 key: keyboard::Key::Named(Named::Tab),
620 ..
621 })
622 )
623}
624
625struct Picker<'a, Message> {
627 field: Element<'a, Message>,
628 list: Element<'a, Message>,
629 enabled: bool,
630 behaviour: Behaviour<'a, Message>,
631 editable: Option<Editable>,
632 #[cfg(feature = "icedwright")]
633 report: Report,
634}
635
636#[cfg(feature = "icedwright")]
638struct Report {
639 value: String,
640 placeholder: String,
641}
642
643#[cfg(feature = "icedwright")]
644const KIND: &str = "iced_cube::select";
645
646#[cfg(feature = "icedwright")]
647impl Report {
648 fn annotation(
649 &self,
650 open: bool,
651 enabled: bool,
652 list: icedwright_probe::Key,
653 ) -> icedwright_probe::Annotation<'static, icedwright_probe::role::ComboBox> {
654 use icedwright_probe::{Annotation, role};
655 let mut annotation = Annotation::new()
656 .role(role::ComboBox)
657 .value(self.value.clone())
658 .expanded(open)
659 .disabled(!enabled)
660 .component(KIND);
661 if !self.placeholder.is_empty() {
662 annotation = annotation.placeholder(self.placeholder.clone());
663 }
664 if open {
666 annotation = annotation.controls(list.clone()).owns(list);
667 }
668 annotation
669 }
670}
671
672#[derive(Debug, Default)]
673struct PickerState {
674 panel: anchored::State,
675 hovered: bool,
676 focus: focus::State,
677 field_focused: bool,
679}
680
681fn opens_list(key: Named) -> bool {
683 matches!(key, Named::Space | Named::Enter | Named::ArrowDown)
684}
685
686fn chooses(key: Named) -> bool {
688 matches!(key, Named::Space | Named::Enter)
689}
690
691impl<Message> Picker<'_, Message> {
692 fn operate_control(
695 &mut self,
696 tree: &mut Tree,
697 layout: Layout<'_>,
698 renderer: &Renderer,
699 operation: &mut dyn Operation,
700 ) {
701 if let Some(mut field) = self.editable_field(tree) {
702 let Some(field_tree) = tree.children.first_mut() else {
703 return;
704 };
705 field
706 .as_widget_mut()
707 .operate(field_tree, layout, renderer, operation);
708 let focused = has_focus(&mut field, field_tree, layout, renderer);
709 let state = tree.state.downcast_mut::<PickerState>();
710 if focused && !state.field_focused {
713 field
714 .as_widget_mut()
715 .operate(field_tree, layout, renderer, &mut SelectAll);
716 }
717 state.field_focused = focused;
718 return;
719 }
720 let Some(field_tree) = tree.children.first_mut() else {
721 return;
722 };
723 let field = &mut self.field;
724 if !self.enabled {
725 field
726 .as_widget_mut()
727 .operate(field_tree, layout, renderer, operation);
728 return;
729 }
730 let state = tree.state.downcast_mut::<PickerState>();
731 focus::report(operation, None, layout.bounds(), &mut state.focus);
732 #[cfg(feature = "icedwright")]
735 operation.traverse(&mut |operation| {
736 field
737 .as_widget_mut()
738 .operate(field_tree, layout, renderer, operation);
739 });
740 #[cfg(not(feature = "icedwright"))]
741 field
742 .as_widget_mut()
743 .operate(field_tree, layout, renderer, operation);
744 }
745
746 fn open(&self, tree: &mut Tree) {
748 if let Some(list) = tree.children.get_mut(1) {
749 *list = Tree::new(&self.list);
750 }
751 let panel = &mut tree.state.downcast_mut::<PickerState>().panel;
752 panel.open = true;
753 panel.side = None;
754 }
755
756 fn close(tree: &mut Tree, shell: &mut Shell<'_, Message>) {
759 tree.state.downcast_mut::<PickerState>().panel.open = false;
760 shell.invalidate_layout();
761 shell.request_redraw();
762 }
763
764 fn open_list(tree: &Tree) -> Option<&ListState> {
766 let open = tree.state.downcast_ref::<PickerState>().panel.open;
767 tree.children
768 .get(1)
769 .filter(|_| open)
770 .and_then(list::state_ref)
771 }
772
773 fn editable_field(&self, tree: &Tree) -> Option<Element<'static, String>> {
776 let editable = self.editable.as_ref()?;
777 let list = Self::open_list(tree);
778 let text = list
779 .and_then(ListState::edited_query)
780 .unwrap_or(&editable.label);
781 let rejected = list.is_some_and(ListState::is_rejected);
782 Some(editable.field(text, rejected, self.enabled))
783 }
784
785 #[allow(clippy::too_many_arguments)]
788 fn update_editable(
789 &mut self,
790 tree: &mut Tree,
791 event: &Event,
792 layout: Layout<'_>,
793 cursor: mouse::Cursor,
794 renderer: &Renderer,
795 clipboard: &mut dyn Clipboard,
796 shell: &mut Shell<'_, Message>,
797 viewport: &Rectangle,
798 ) {
799 let bounds = layout.bounds();
800 let state = tree.state.downcast_mut::<PickerState>();
801 let open = state.panel.open;
802 let over = cursor.is_over(bounds);
803 if over != state.hovered {
804 state.hovered = over;
805 shell.request_redraw();
806 }
807 if open && (is_tab(event) || focus::named_press(event) == Some(Named::Enter)) {
810 Self::close(tree, shell);
811 return;
812 }
813 if !open && state.field_focused && focus::named_press(event) == Some(Named::ArrowDown) {
814 self.open(tree);
815 shell.capture_event();
816 shell.request_redraw();
817 return;
818 }
819 let press = is_press(event)
820 .then(|| cursor.position_over(bounds))
821 .flatten();
822 if open && press.is_some_and(|position| on_chevron(bounds, position.x)) {
823 Self::close(tree, shell);
824 shell.capture_event();
825 return;
826 }
827
828 let (Some(mut field), Some(field_tree)) =
829 (self.editable_field(tree), tree.children.first_mut())
830 else {
831 return;
832 };
833 let mut typed = Vec::new();
834 let mut inner = Shell::new(&mut typed);
835 field.as_widget_mut().update(
836 field_tree, event, layout, cursor, renderer, clipboard, &mut inner, viewport,
837 );
838 list::relay(shell, &inner);
839 let focused = has_focus(&mut field, field_tree, layout, renderer);
840
841 let state = tree.state.downcast_mut::<PickerState>();
842 if focused != state.field_focused {
843 state.field_focused = focused;
844 shell.request_redraw();
845 }
846 let mut is_open = state.panel.open;
847 if press.is_some() && !is_open {
848 self.open(tree);
849 is_open = true;
850 shell.capture_event();
851 shell.request_redraw();
852 }
853 if let Some(text) = typed.pop() {
854 if !is_open {
855 self.open(tree);
856 is_open = true;
857 }
858 if let Some(list) = tree.children.get_mut(1).and_then(list::state_mut) {
859 list.edit(text);
860 }
861 shell.invalidate_layout();
862 shell.request_redraw();
863 }
864 if is_open && matches!(event, Event::Keyboard(keyboard::Event::KeyPressed { .. })) {
866 shell.capture_event();
867 }
868 }
869}
870
871impl<Message: Clone> Widget<Message, Theme, Renderer> for Picker<'_, Message> {
872 fn tag(&self) -> tree::Tag {
873 tree::Tag::of::<PickerState>()
874 }
875
876 fn state(&self) -> tree::State {
877 tree::State::new(PickerState::default())
878 }
879
880 fn children(&self) -> Vec<Tree> {
881 let field = match &self.editable {
882 Some(editable) => Tree::new(editable.field(&editable.label, false, self.enabled)),
883 None => Tree::new(&self.field),
884 };
885 vec![field, Tree::new(&self.list)]
886 }
887
888 fn diff(&self, tree: &mut Tree) {
889 let Some(field) = self.editable_field(tree) else {
890 tree.diff_children(&[&self.field, &self.list]);
891 return;
892 };
893 let [field_tree, list_tree] = tree.children.as_mut_slice() else {
894 tree.children = vec![Tree::new(&field), Tree::new(&self.list)];
895 return;
896 };
897 field_tree.diff(&field);
898 list_tree.diff(&self.list);
899 }
900
901 fn size(&self) -> Size<Length> {
902 self.field.as_widget().size()
903 }
904
905 fn layout(
906 &mut self,
907 tree: &mut Tree,
908 renderer: &Renderer,
909 limits: &layout::Limits,
910 ) -> layout::Node {
911 if let Some(mut field) = self.editable_field(tree) {
912 return field
913 .as_widget_mut()
914 .layout(&mut tree.children[0], renderer, limits);
915 }
916 self.field
917 .as_widget_mut()
918 .layout(&mut tree.children[0], renderer, limits)
919 }
920
921 fn draw(
922 &self,
923 tree: &Tree,
924 renderer: &mut Renderer,
925 theme: &Theme,
926 style: &renderer::Style,
927 layout: Layout<'_>,
928 cursor: mouse::Cursor,
929 viewport: &Rectangle,
930 ) {
931 let state = tree.state.downcast_ref::<PickerState>();
932 let bounds = layout.bounds();
933 let hovered = self.enabled && cursor.is_over(bounds);
934 let status = field_status(state.panel.open || state.field_focused, hovered);
935 let tokens = Tokens::of(theme);
936 let mut field = self::style(&tokens, status, self.enabled);
937 if Self::open_list(tree).is_some_and(ListState::is_rejected) && self.editable.is_some() {
938 field.border.color = tokens.destructive;
939 }
940 <Renderer as renderer::Renderer>::fill_quad(
941 renderer,
942 renderer::Quad {
943 bounds,
944 border: field.border,
945 ..renderer::Quad::default()
946 },
947 field.background,
948 );
949 if let Some(field) = self.editable_field(tree) {
950 field.as_widget().draw(
951 &tree.children[0],
952 renderer,
953 theme,
954 style,
955 layout,
956 cursor,
957 viewport,
958 );
959 return;
960 }
961 self.field.as_widget().draw(
962 &tree.children[0],
963 renderer,
964 theme,
965 style,
966 layout,
967 cursor,
968 viewport,
969 );
970 if self.enabled && state.focus.is_focused() {
971 focus::draw_ring(renderer, theme, bounds, radius::MD);
972 }
973 }
974
975 fn operate(
976 &mut self,
977 tree: &mut Tree,
978 layout: Layout<'_>,
979 renderer: &Renderer,
980 operation: &mut dyn Operation,
981 ) {
982 #[cfg(feature = "icedwright")]
983 {
984 let panel = &mut tree.state.downcast_mut::<PickerState>().panel;
985 let open = panel.open;
986 let list = panel.key();
987 icedwright_probe::report(operation, layout.bounds(), || {
988 self.report.annotation(open, self.enabled, list)
989 });
990 operation.traverse(&mut |operation| {
991 self.operate_control(tree, layout, renderer, operation);
992 });
993 }
994 #[cfg(not(feature = "icedwright"))]
995 self.operate_control(tree, layout, renderer, operation);
996 }
997
998 fn update(
999 &mut self,
1000 tree: &mut Tree,
1001 event: &Event,
1002 layout: Layout<'_>,
1003 cursor: mouse::Cursor,
1004 renderer: &Renderer,
1005 clipboard: &mut dyn Clipboard,
1006 shell: &mut Shell<'_, Message>,
1007 viewport: &Rectangle,
1008 ) {
1009 if !self.enabled {
1010 return;
1011 }
1012 if self.editable.is_some() {
1013 self.update_editable(
1014 tree, event, layout, cursor, renderer, clipboard, shell, viewport,
1015 );
1016 return;
1017 }
1018 let state = tree.state.downcast_mut::<PickerState>();
1019 if state.focus.update(event) {
1020 shell.request_redraw();
1021 }
1022 if let Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) = event
1027 && state.panel.open
1028 {
1029 if *key == keyboard::Key::Named(Named::Tab) {
1030 state.panel.open = false;
1031 shell.request_redraw();
1032 return;
1033 }
1034 if focus::named_press(event).is_some_and(chooses) {
1035 state.panel.open = false;
1036 shell.request_redraw();
1037 }
1038 shell.capture_event();
1039 return;
1040 }
1041 if state.focus.is_focused() && focus::named_press(event).is_some_and(opens_list) {
1042 self.open(tree);
1043 shell.capture_event();
1044 shell.request_redraw();
1045 return;
1046 }
1047 let over = cursor.is_over(layout.bounds());
1048 if over != state.hovered {
1049 state.hovered = over;
1050 shell.request_redraw();
1051 }
1052 let pressed = matches!(
1053 event,
1054 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
1055 | Event::Touch(touch::Event::FingerPressed { .. })
1056 );
1057 if !pressed || !over {
1058 return;
1059 }
1060 if state.panel.open {
1061 state.panel.open = false;
1062 } else {
1063 self.open(tree);
1064 }
1065 shell.capture_event();
1066 shell.request_redraw();
1067 }
1068
1069 fn mouse_interaction(
1070 &self,
1071 _tree: &Tree,
1072 layout: Layout<'_>,
1073 cursor: mouse::Cursor,
1074 _viewport: &Rectangle,
1075 _renderer: &Renderer,
1076 ) -> mouse::Interaction {
1077 let bounds = layout.bounds();
1078 let Some(position) = cursor.position_over(bounds).filter(|_| self.enabled) else {
1079 return mouse::Interaction::default();
1080 };
1081 if self.editable.is_some() && !on_chevron(bounds, position.x) {
1082 return mouse::Interaction::Text;
1083 }
1084 mouse::Interaction::Pointer
1085 }
1086
1087 fn overlay<'b>(
1088 &'b mut self,
1089 tree: &'b mut Tree,
1090 layout: Layout<'b>,
1091 _renderer: &Renderer,
1092 _viewport: &Rectangle,
1093 translation: Vector,
1094 ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1095 let Tree {
1096 state, children, ..
1097 } = tree;
1098 let state = state.downcast_mut::<PickerState>();
1099 if !self.enabled || !state.panel.open {
1100 return None;
1101 }
1102 let list_tree = children.get_mut(1)?;
1103 if let Some(list) = list::state_mut(list_tree) {
1104 list.set_anchor(layout.bounds() + translation);
1105 }
1106 Some(anchored::floating(
1107 &mut self.list,
1108 list_tree,
1109 &mut state.panel,
1110 &self.behaviour,
1111 layout.bounds() + translation,
1112 ))
1113 }
1114}
1115
1116fn field_status(open: bool, hovered: bool) -> Status {
1119 match (open, hovered) {
1120 (true, is_hovered) => Status::Opened { is_hovered },
1121 (false, true) => Status::Hovered,
1122 (false, false) => Status::Active,
1123 }
1124}
1125
1126pub fn style(tokens: &Tokens, status: Status, enabled: bool) -> pick_list::Style {
1128 let border = match status {
1129 Status::Active => tokens.border,
1130 Status::Hovered => mix(tokens.border, tokens.foreground, 0.3),
1131 Status::Opened { .. } => mix(tokens.border, tokens.foreground, 0.6),
1132 };
1133 let style = pick_list::Style {
1134 text_color: tokens.foreground,
1135 placeholder_color: tokens.muted_foreground,
1136 handle_color: tokens.muted_foreground,
1137 background: Background::Color(Color::TRANSPARENT),
1139 border: Border {
1140 color: border,
1141 width: 1.0,
1142 radius: radius::MD.into(),
1143 },
1144 };
1145
1146 if enabled {
1147 return style;
1148 }
1149 pick_list::Style {
1150 text_color: fade(tokens.foreground, 0.5),
1151 placeholder_color: fade(tokens.muted_foreground, 0.5),
1152 handle_color: fade(tokens.muted_foreground, 0.5),
1153 background: Background::Color(tokens.disabled_field()),
1154 border: Border {
1155 color: fade(tokens.border, 0.5),
1156 ..style.border
1157 },
1158 }
1159}
1160
1161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1163pub enum Action {
1164 Next,
1165 Previous,
1166}
1167
1168impl Action {
1169 pub fn apply<T: PartialEq + Clone>(self, options: &[T], selected: Option<&T>) -> Option<T> {
1174 let current = selected.and_then(|value| options.iter().position(|option| option == value));
1175 let target = match (self, current) {
1176 (Action::Next, None) => 0,
1177 (Action::Previous, None) => options.len().checked_sub(1)?,
1178 (Action::Next, Some(index)) => index + 1,
1179 (Action::Previous, Some(index)) => index.checked_sub(1)?,
1180 };
1181 options.get(target).cloned()
1182 }
1183}
1184
1185impl keys::Action for Action {
1186 const ALL: &'static [Self] = &[Action::Next, Action::Previous];
1187
1188 fn defaults() -> Keymap<Self> {
1189 default_keymap()
1190 }
1191
1192 fn name(self) -> &'static str {
1193 match self {
1194 Action::Next => "Next",
1195 Action::Previous => "Previous",
1196 }
1197 }
1198
1199 fn description(self) -> &'static str {
1200 match self {
1201 Action::Next => "Selects the next option, stopping at the last.",
1202 Action::Previous => "Selects the previous option, stopping at the first.",
1203 }
1204 }
1205}
1206
1207pub fn default_keymap() -> Keymap<Action> {
1219 Keymap::new()
1220 .bind(Chord::named(Named::ArrowDown), Action::Next)
1221 .bind(Chord::named(Named::ArrowUp), Action::Previous)
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226 use super::*;
1227 use crate::theme::{dark, light};
1228
1229 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1230 let chord: Chord = chord.parse().unwrap();
1231 keymap.resolve(chord.key(), chord.modifiers())
1232 }
1233
1234 #[test]
1235 fn default_keymap_and_overrides() {
1236 let keymap = default_keymap();
1237 assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
1238 assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
1239 let custom = keymap
1240 .bind("J".parse().unwrap(), Action::Next)
1241 .unbind(&"ArrowDown".parse().unwrap());
1242 assert_eq!(press(&custom, "j"), Some(Action::Next));
1243 assert_eq!(press(&custom, "ArrowDown"), None);
1244 }
1245
1246 #[test]
1247 fn next_and_previous_stop_at_the_ends() {
1248 let options = ["a", "b", "c"];
1249 assert_eq!(Action::Next.apply(&options, Some(&"a")), Some("b"));
1250 assert_eq!(Action::Next.apply(&options, Some(&"c")), None);
1251 assert_eq!(Action::Previous.apply(&options, Some(&"b")), Some("a"));
1252 assert_eq!(Action::Previous.apply(&options, Some(&"a")), None);
1253 }
1254
1255 #[test]
1256 fn without_a_selection_next_and_previous_pick_an_end() {
1257 let options = ["a", "b", "c"];
1258 assert_eq!(Action::Next.apply(&options, None), Some("a"));
1259 assert_eq!(Action::Previous.apply(&options, None), Some("c"));
1260 assert_eq!(Action::Next.apply(&options, Some(&"z")), Some("a"));
1261 let empty: [&str; 0] = [];
1262 assert_eq!(Action::Next.apply(&empty, None), None);
1263 assert_eq!(Action::Previous.apply(&empty, None), None);
1264 }
1265
1266 const STATES: [Status; 4] = [
1267 Status::Active,
1268 Status::Hovered,
1269 Status::Opened { is_hovered: false },
1270 Status::Opened { is_hovered: true },
1271 ];
1272
1273 #[test]
1274 fn default_builder_has_no_selection_and_is_disabled() {
1275 let s: Select<'_, &str, ()> = select(vec!["a", "b"], None);
1276 assert_eq!(s.options.len(), 2);
1277 assert!(s.selected.is_none());
1278 assert!(s.placeholder.is_none());
1279 assert_eq!(s.width, Length::Fixed(200.0));
1280 assert!(!s.is_enabled());
1281 assert!(s.leading.is_none());
1282 }
1283
1284 #[test]
1285 fn leading_is_asked_per_option() {
1286 let s: Select<'_, &str, ()> = select(vec!["red", "plain"], None).leading(|option| {
1287 (*option == "red")
1288 .then(|| crate::theme::swatch_color(Color::from_rgb(1.0, 0.0, 0.0)).into())
1289 });
1290 let Some(leading) = s.leading.as_ref() else {
1291 panic!("leading is set");
1292 };
1293 assert!(leading(&"red").is_some());
1294 assert!(leading(&"plain").is_none());
1295 }
1296
1297 #[test]
1298 fn builder_sets_placeholder_and_message() {
1299 const OPTIONS: &[u8] = &[1, 2, 3];
1300 let s: Select<'_, u8, u8> = select(OPTIONS, Some(2))
1301 .placeholder("Pick a number")
1302 .on_select(|v| v);
1303 assert_eq!(s.placeholder.as_deref(), Some("Pick a number"));
1304 assert!(s.is_enabled());
1305 assert!(matches!(s.options, Cow::Borrowed(_)));
1306 }
1307
1308 #[test]
1309 fn on_select_maybe_enables_only_with_a_message() {
1310 let enabled: Select<'_, u8, u8> = select(vec![1, 2], None).on_select_maybe(Some(|v| v));
1311 assert!(enabled.is_enabled());
1312 let disabled: Select<'_, u8, u8> =
1313 select(vec![1, 2], None).on_select_maybe(None::<fn(u8) -> u8>);
1314 assert!(!disabled.is_enabled());
1315 }
1316
1317 #[test]
1318 fn hover_and_open_strengthen_the_border() {
1319 for theme in [light(), dark()] {
1320 let tokens = Tokens::of(&theme);
1321 let borders = STATES.map(|status| style(&tokens, status, true).border.color);
1322 assert_ne!(borders[0], borders[1]);
1323 assert_ne!(borders[1], borders[2]);
1324 assert_eq!(borders[2], borders[3]);
1325 }
1326 }
1327
1328 #[test]
1329 fn placeholder_is_muted() {
1330 for theme in [light(), dark()] {
1331 let tokens = Tokens::of(&theme);
1332 let style = style(&tokens, Status::Active, true);
1333 assert_eq!(style.placeholder_color, tokens.muted_foreground);
1334 assert_ne!(style.placeholder_color, style.text_color);
1335 }
1336 }
1337
1338 #[test]
1339 fn disabled_fades_text_and_uses_the_disabled_field_background() {
1340 for theme in [light(), dark()] {
1341 let tokens = Tokens::of(&theme);
1342 for status in STATES {
1343 let disabled = style(&tokens, status, false);
1344 assert!((disabled.text_color.a - tokens.foreground.a * 0.5).abs() < 1e-6);
1345 assert_eq!(
1346 disabled.background,
1347 Background::Color(tokens.disabled_field())
1348 );
1349 }
1350 }
1351 }
1352
1353 #[test]
1354 fn an_enabled_trigger_takes_the_colour_of_its_surface() {
1355 for theme in [light(), dark()] {
1356 let tokens = Tokens::of(&theme);
1357 for status in STATES {
1358 let enabled = style(&tokens, status, true);
1359 assert_eq!(enabled.background, Background::Color(Color::TRANSPARENT));
1360 }
1361 }
1362 }
1363
1364 #[test]
1365 fn long_lists_scroll_by_default_and_search_and_custom_values_are_off() {
1366 let s: Select<'_, &str, ()> = select(vec!["a", "b"], None);
1367 assert_eq!(s.max_rows, MAX_VISIBLE_ROWS);
1368 assert!(s.scrollable);
1369 assert!(!s.searchable);
1370 assert!(s.on_custom.is_none());
1371 assert_eq!(s.shortcuts, Shortcuts::all());
1372 assert_eq!(s.empty, DEFAULT_EMPTY);
1373 assert_eq!(s.not_valid, DEFAULT_NOT_VALID);
1374 assert_eq!(s.type_ahead_pause, TYPE_AHEAD_PAUSE);
1375 assert!(!s.prefer_custom && !s.commit_on_leave);
1376 assert!(!s.pass_through && !s.editable);
1377 }
1378
1379 #[test]
1380 fn typed_value_options_are_set_by_the_builder() {
1381 let s: Select<'_, &str, ()> = select(vec!["a"], None)
1382 .prefer_custom(true)
1383 .commit_on_leave(true)
1384 .pass_through(true)
1385 .editable(true);
1386 assert!(s.prefer_custom && s.commit_on_leave);
1387 assert!(s.pass_through && s.editable);
1388 }
1389
1390 #[test]
1391 fn the_chevron_takes_the_right_end_of_an_editable_field() {
1392 let bounds = Rectangle::new(iced::Point::ORIGIN, Size::new(200.0, HEIGHT));
1393 assert!(on_chevron(bounds, 190.0));
1394 assert!(on_chevron(bounds, 200.0 - CHEVRON_SIZE - space::MD));
1395 assert!(!on_chevron(bounds, 40.0));
1396 }
1397
1398 #[test]
1399 fn the_row_limit_and_scrolling_are_set_in_any_order() {
1400 let s: Select<'_, &str, ()> = select(vec!["a"], None).max_visible_rows(0);
1401 assert_eq!(s.max_rows, 1, "at least one row");
1402 let s: Select<'_, &str, ()> = select(vec!["a"], None)
1403 .scrollable(false)
1404 .max_visible_rows(5);
1405 assert!(!s.scrollable, "a row limit does not turn scrolling back on");
1406 let s: Select<'_, &str, ()> = select(vec!["a"], None)
1407 .max_visible_rows(5)
1408 .scrollable(false)
1409 .scrollable(true);
1410 assert_eq!(s.max_rows, 5, "the limit is kept");
1411 assert!(s.scrollable);
1412 }
1413
1414 #[test]
1415 fn search_and_custom_values_are_set_by_the_builder() {
1416 let s: Select<'_, &str, String> = select(vec!["a"], None)
1417 .searchable(true)
1418 .on_custom(|text| (!text.is_empty()).then_some(text))
1419 .search_placeholder("Find a time")
1420 .empty("Nothing")
1421 .not_valid("Use hh:mm")
1422 .shortcuts(Shortcuts::none())
1423 .type_ahead_pause(Duration::from_millis(500));
1424 assert!(s.searchable);
1425 assert_eq!(s.search_placeholder.as_deref(), Some("Find a time"));
1426 assert_eq!(s.empty, "Nothing");
1427 assert_eq!(s.not_valid, "Use hh:mm");
1428 assert_eq!(s.shortcuts, Shortcuts::none());
1429 assert_eq!(s.type_ahead_pause, Duration::from_millis(500));
1430 let Some(on_custom) = s.on_custom.as_ref() else {
1431 panic!("on_custom is set");
1432 };
1433 assert_eq!(on_custom("x".to_owned()), Some("x".to_owned()));
1434 assert_eq!(on_custom(String::new()), None);
1435 }
1436
1437 #[test]
1438 fn keys_that_open_and_choose() {
1439 for key in [Named::Space, Named::Enter, Named::ArrowDown] {
1440 assert!(opens_list(key), "{key:?}");
1441 }
1442 assert!(!opens_list(Named::ArrowUp));
1443 assert!(!opens_list(Named::Escape));
1444 assert!(chooses(Named::Space) && chooses(Named::Enter));
1445 assert!(!chooses(Named::ArrowDown));
1446 }
1447
1448 #[test]
1449 fn field_status_follows_the_list_and_the_pointer() {
1450 assert_eq!(field_status(false, false), Status::Active);
1451 assert_eq!(field_status(false, true), Status::Hovered);
1452 assert_eq!(
1453 field_status(true, false),
1454 Status::Opened { is_hovered: false }
1455 );
1456 assert_eq!(
1457 field_status(true, true),
1458 Status::Opened { is_hovered: true }
1459 );
1460 }
1461}