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