1use std::fmt::{self, Display};
53use std::rc::Rc;
54
55use iced::keyboard::key::Named;
56use iced::widget::{self, column, container, row};
57use iced::{Element, Length};
58
59use crate::feedback::chip::{self, chip};
60use crate::forms::combobox::{DEFAULT_EMPTY, Editing, ListEvent, Suggestions, field, suggestions};
61use crate::keys::{self, Chord, Keymap};
62use crate::overlay::anchored::{Align, Placement, Side, anchored};
63use crate::primitives::input::{Shortcuts, Size};
64
65pub use crate::forms::combobox::VISIBLE_ROWS;
66
67const CHIP_GAP: f32 = 4.0;
69const GAP: f32 = 6.0;
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum Event {
75 Input(String),
77 Open,
78 Close,
80 Next,
82 Previous,
84 ActivateHighlighted,
86 Highlight(usize),
88 Activate(usize),
91 Scroll(i32),
93 Remove(usize),
95 RemoveLast,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum Output<T> {
102 Added(T),
103 Removed(T),
104}
105
106#[derive(Debug, Clone, PartialEq)]
108pub struct State<T> {
109 list: Suggestions<T>,
110 chosen: Vec<usize>,
112}
113
114impl<T: Display> State<T> {
115 pub fn new(options: impl IntoIterator<Item = T>) -> Self {
118 Self {
119 list: Suggestions::new(options),
120 chosen: Vec::new(),
121 }
122 }
123}
124
125impl<T: PartialEq> State<T> {
126 pub fn with_chosen<'v>(mut self, values: impl IntoIterator<Item = &'v T>) -> Self
129 where
130 T: 'v,
131 {
132 for value in values {
133 let Some(index) = self.list.position(value) else {
134 continue;
135 };
136 if !self.chosen.contains(&index) {
137 self.chosen.push(index);
138 }
139 }
140 self
141 }
142}
143
144impl<T> State<T> {
145 pub fn with_visible_rows(mut self, rows: usize) -> Self {
147 self.list.set_rows(rows);
148 self
149 }
150
151 pub fn options(&self) -> &[T] {
152 self.list.options()
153 }
154
155 pub fn chosen(&self) -> impl Iterator<Item = &T> {
157 self.chosen
158 .iter()
159 .filter_map(|&index| self.list.option(index))
160 }
161
162 pub fn chosen_indices(&self) -> &[usize] {
165 &self.chosen
166 }
167
168 pub fn is_chosen(&self, index: usize) -> bool {
170 self.chosen.contains(&index)
171 }
172
173 pub fn query(&self) -> &str {
174 self.list.query()
175 }
176
177 pub fn is_open(&self) -> bool {
178 self.list.is_open()
179 }
180
181 pub fn matches(&self) -> impl Iterator<Item = &T> {
184 self.list.matches()
185 }
186
187 pub fn highlighted(&self) -> Option<&T> {
189 self.list.highlighted()
190 }
191
192 pub fn visible(&self) -> impl Iterator<Item = (usize, &T)> {
194 self.list.visible()
195 }
196
197 pub fn update(&mut self, event: Event) -> Option<Output<T>>
199 where
200 T: Clone,
201 {
202 match event {
203 Event::Input(query) => self.list.input(query),
204 Event::Open => self.list.open(None),
205 Event::Close => self.list.close(),
206 Event::Next | Event::Previous if !self.list.is_open() => self.list.open(None),
207 Event::Next => self.list.step(1),
208 Event::Previous => self.list.step(-1),
209 Event::ActivateHighlighted => {
210 if !self.list.is_open() {
211 return None;
212 }
213 let index = self.list.highlighted_index()?;
214 return self.toggle(index);
215 }
216 Event::Activate(index) => return self.toggle(index),
217 Event::Highlight(index) => self.list.highlight_option(index),
218 Event::Scroll(rows) => self.list.scroll(rows),
219 Event::Remove(index) => {
220 let position = self.chosen.iter().position(|&i| i == index)?;
221 return self.remove_at(position);
222 }
223 Event::RemoveLast => {
224 let position = self.chosen.len().checked_sub(1)?;
225 return self.remove_at(position);
226 }
227 }
228 None
229 }
230
231 fn toggle(&mut self, index: usize) -> Option<Output<T>>
232 where
233 T: Clone,
234 {
235 let value = self.list.option(index)?.clone();
236 self.list.clear_query();
237 if let Some(position) = self.chosen.iter().position(|&i| i == index) {
238 self.chosen.remove(position);
239 return Some(Output::Removed(value));
240 }
241 self.chosen.push(index);
242 Some(Output::Added(value))
243 }
244
245 fn remove_at(&mut self, position: usize) -> Option<Output<T>>
246 where
247 T: Clone,
248 {
249 let index = self.chosen.remove(position);
250 self.list.option(index).cloned().map(Output::Removed)
251 }
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
256pub enum Action {
257 Next,
258 Previous,
259 Activate,
260 Close,
261 RemoveLast,
262}
263
264impl Action {
265 pub fn event<T>(self, state: &State<T>) -> Option<Event> {
268 match self {
269 Action::Next => Some(Event::Next),
270 Action::Previous => Some(Event::Previous),
271 Action::Activate => state.is_open().then_some(Event::ActivateHighlighted),
272 Action::Close => state.is_open().then_some(Event::Close),
273 Action::RemoveLast => {
274 (state.query().is_empty() && !state.chosen.is_empty()).then_some(Event::RemoveLast)
275 }
276 }
277 }
278}
279
280impl keys::Action for Action {
281 const ALL: &'static [Self] = &[
282 Action::Next,
283 Action::Previous,
284 Action::Activate,
285 Action::Close,
286 Action::RemoveLast,
287 ];
288
289 fn defaults() -> Keymap<Self> {
290 default_keymap()
291 }
292
293 fn name(self) -> &'static str {
294 match self {
295 Action::Next => "Next",
296 Action::Previous => "Previous",
297 Action::Activate => "Activate",
298 Action::Close => "Close",
299 Action::RemoveLast => "Remove last",
300 }
301 }
302
303 fn description(self) -> &'static str {
304 match self {
305 Action::Next => "Highlights the next suggestion, opening the list if it is closed.",
306 Action::Previous => {
307 "Highlights the previous suggestion, opening the list if it is closed."
308 }
309 Action::Activate => {
310 "Adds the highlighted suggestion, or removes it if it is already chosen. The list stays open."
311 }
312 Action::Close => "Closes the list and clears the query.",
313 Action::RemoveLast => "Removes the last chip while the field is empty.",
314 }
315 }
316}
317
318pub fn default_keymap() -> Keymap<Action> {
333 Keymap::new()
334 .bind(Chord::named(Named::ArrowDown), Action::Next)
335 .bind(Chord::named(Named::ArrowUp), Action::Previous)
336 .bind(Chord::named(Named::Enter), Action::Activate)
337 .bind(Chord::named(Named::Escape), Action::Close)
338 .bind(Chord::named(Named::Backspace), Action::RemoveLast)
339}
340
341pub fn remove_id(key: &str, index: usize) -> widget::Id {
345 chip::remove_id(&chip_key(key, index))
346}
347
348fn chip_key(key: &str, index: usize) -> String {
349 format!("{key}-{index}")
350}
351
352pub fn chip_size(size: Size) -> chip::Size {
354 match size {
355 Size::Sm => chip::Size::Sm,
356 Size::Md | Size::Lg => chip::Size::Md,
357 }
358}
359
360pub struct MultiCombobox<'a, T, Message> {
366 state: &'a State<T>,
367 placeholder: String,
368 empty: String,
369 width: Length,
370 size: Size,
371 key: Option<String>,
372 invalid: bool,
373 keymap: Keymap<Action>,
374 shortcuts: Shortcuts,
375 on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
376}
377
378pub fn multi_combobox<'a, T, Message>(state: &'a State<T>) -> MultiCombobox<'a, T, Message> {
381 MultiCombobox {
382 state,
383 placeholder: String::new(),
384 empty: DEFAULT_EMPTY.to_owned(),
385 width: Length::Fixed(320.0),
386 size: Size::default(),
387 key: None,
388 invalid: false,
389 keymap: default_keymap(),
390 shortcuts: Shortcuts::all(),
391 on_event: None,
392 }
393}
394
395impl<T: fmt::Debug, Message> fmt::Debug for MultiCombobox<'_, T, Message> {
396 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397 f.debug_struct("MultiCombobox")
398 .field("state", self.state)
399 .field("placeholder", &self.placeholder)
400 .field("empty", &self.empty)
401 .field("width", &self.width)
402 .field("size", &self.size)
403 .field("key", &self.key)
404 .field("invalid", &self.invalid)
405 .field("shortcuts", &self.shortcuts)
406 .field("enabled", &self.on_event.is_some())
407 .finish_non_exhaustive()
408 }
409}
410
411impl<'a, T, Message> MultiCombobox<'a, T, Message> {
412 pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
414 self.placeholder = placeholder.into();
415 self
416 }
417
418 pub fn empty(mut self, empty: impl Into<String>) -> Self {
420 self.empty = empty.into();
421 self
422 }
423
424 pub fn width(mut self, width: impl Into<Length>) -> Self {
426 self.width = width.into();
427 self
428 }
429
430 pub fn size(mut self, size: Size) -> Self {
434 self.size = size;
435 self
436 }
437
438 pub fn id(mut self, key: impl Into<String>) -> Self {
442 self.key = Some(key.into());
443 self
444 }
445
446 pub fn invalid(mut self, invalid: bool) -> Self {
449 self.invalid = invalid;
450 self
451 }
452
453 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
455 self.keymap = keymap;
456 self
457 }
458
459 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
464 self.shortcuts = shortcuts;
465 self
466 }
467
468 pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
470 self.on_event = Some(Box::new(on_event));
471 self
472 }
473
474 pub fn is_enabled(&self) -> bool {
475 self.on_event.is_some()
476 }
477}
478
479fn list_event(event: ListEvent) -> Event {
480 match event {
481 ListEvent::Highlight(index) => Event::Highlight(index),
482 ListEvent::Activate(index) => Event::Activate(index),
483 ListEvent::Scroll(rows) => Event::Scroll(rows),
484 }
485}
486
487#[cfg(feature = "icedwright")]
488const KIND: &str = "iced_cube::multi_combobox";
489
490#[cfg(feature = "icedwright")]
491use crate::forms::combobox::{Report, annotate_field, annotate_list};
492
493impl<'a, T, Message> From<MultiCombobox<'a, T, Message>> for Element<'a, Message>
494where
495 T: Display + 'a,
496 Message: Clone + 'a,
497{
498 fn from(combobox: MultiCombobox<'a, T, Message>) -> Self {
499 let MultiCombobox {
500 state,
501 placeholder,
502 empty,
503 width,
504 size,
505 key,
506 invalid,
507 keymap,
508 shortcuts,
509 on_event,
510 } = combobox;
511 let on_event: Option<Rc<dyn Fn(Event) -> Message + 'a>> = on_event.map(Rc::from);
512 let id = key.clone().map(widget::Id::from);
513
514 let chips = state.chosen.iter().filter_map(|&index| {
515 let option = state.list.option(index)?;
516 let mut chip = chip(option.to_string())
517 .size(chip_size(size))
518 .on_remove_maybe(on_event.as_ref().map(|f| f(Event::Remove(index))));
519 if let Some(key) = &key {
520 chip = chip.id(chip_key(key, index));
521 }
522 Some(Element::from(chip))
523 });
524 let chips: Element<'a, Message> = row(chips)
525 .spacing(CHIP_GAP)
526 .wrap()
527 .vertical_spacing(CHIP_GAP)
528 .into();
529 let has_chips = !state.chosen.is_empty();
530
531 let Some(on_event) = on_event else {
532 let field = field(&placeholder, "", size, id, None, false, invalid);
533 let content = if has_chips {
534 column![chips, field].spacing(GAP)
535 } else {
536 column![field]
537 };
538 let element: Element<'a, Message> = container(content).width(width).into();
539 #[cfg(feature = "icedwright")]
540 let element = annotate_field(
541 element,
542 Report {
543 value: String::new(),
544 placeholder,
545 open: false,
546 enabled: false,
547 invalid,
548 list: None,
549 },
550 KIND,
551 );
552 return element;
553 };
554
555 let open = state.is_open();
556 #[cfg(feature = "icedwright")]
557 let list_key = open.then(icedwright_probe::Key::unique);
558 let list = open.then(|| {
559 suggestions(
560 &state.list,
561 &empty,
562 &|index| state.is_chosen(index),
563 &|event| on_event(list_event(event)),
564 )
565 });
566 #[cfg(feature = "icedwright")]
567 let list = list.map(|list| match &list_key {
568 Some(key) => annotate_list(list, key.clone(), KIND),
569 None => list,
570 });
571 #[cfg(feature = "icedwright")]
572 let report = Report {
573 value: state.query().to_owned(),
574 placeholder: placeholder.clone(),
575 open,
576 enabled: true,
577 invalid,
578 list: list_key,
579 };
580 let editing = Editing {
581 on_input: {
582 let on_event = Rc::clone(&on_event);
583 Box::new(move |query| on_event(Event::Input(query)))
584 },
585 shortcuts,
586 };
587 let field = field(
588 &placeholder,
589 state.query(),
590 size,
591 id,
592 Some(editing),
593 open,
594 invalid,
595 );
596 let field = anchored(field).on_anchor_press_maybe((!open).then(|| on_event(Event::Open)));
598 let content = if has_chips {
599 column![chips, field].spacing(GAP)
600 } else {
601 column![field]
602 };
603 let content: Element<'a, Message> = container(content).width(width).into();
604 #[cfg(feature = "icedwright")]
605 let content = annotate_field(content, report, KIND);
606
607 anchored(content)
608 .kind("iced_cube::multi_combobox")
609 .content(list)
610 .placement(Placement::new(Side::Bottom, Align::Start))
611 .match_width(true)
612 .dismiss_keys([])
613 .dismiss_on_blur(true)
614 .on_dismiss_maybe(open.then(|| on_event(Event::Close)))
615 .on_key(move |key| {
616 keymap
617 .resolve_event(key)
618 .and_then(|action| action.event(state))
619 .map(&*on_event)
620 })
621 .into()
622 }
623}
624
625#[cfg(test)]
626mod tests {
627 use super::*;
628
629 const PEOPLE: [&str; 5] = ["Ada", "Alan", "Grace", "Linus", "Margaret"];
630
631 fn people() -> State<&'static str> {
632 State::new(PEOPLE)
633 }
634
635 fn chosen(state: &State<&'static str>) -> Vec<&'static str> {
636 state.chosen().copied().collect()
637 }
638
639 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
640 let chord: Chord = chord.parse().ok()?;
641 keymap.resolve(chord.key(), chord.modifiers())
642 }
643
644 #[test]
645 fn new_state_is_closed_with_nothing_chosen() {
646 let state = people();
647 assert!(!state.is_open());
648 assert!(chosen(&state).is_empty());
649 assert_eq!(state.query(), "");
650 assert_eq!(state.matches().count(), PEOPLE.len());
651 }
652
653 #[test]
654 fn with_chosen_keeps_order_and_skips_unknowns_and_repeats() {
655 let state = people().with_chosen(&["Linus", "Kiwi", "Ada", "Linus"]);
656 assert_eq!(chosen(&state), ["Linus", "Ada"]);
657 assert_eq!(state.chosen_indices(), [3, 0]);
658 assert!(state.is_chosen(3));
659 assert!(!state.is_chosen(1));
660 }
661
662 #[test]
663 fn choosing_adds_keeps_the_list_open_and_clears_the_query() {
664 let mut state = people();
665 let _ = state.update(Event::Input("gr".into()));
666 assert_eq!(state.highlighted(), Some(&"Grace"));
667 assert_eq!(
668 state.update(Event::ActivateHighlighted),
669 Some(Output::Added("Grace"))
670 );
671 assert!(state.is_open());
672 assert_eq!(state.query(), "");
673 assert_eq!(state.matches().count(), PEOPLE.len());
674 assert_eq!(state.highlighted(), Some(&"Grace"), "highlight stays put");
675 assert_eq!(chosen(&state), ["Grace"]);
676 }
677
678 #[test]
679 fn choosing_a_chosen_option_removes_it() {
680 let mut state = people().with_chosen(&["Ada", "Alan"]);
681 let _ = state.update(Event::Open);
682 assert_eq!(
683 state.update(Event::Activate(0)),
684 Some(Output::Removed("Ada"))
685 );
686 assert_eq!(chosen(&state), ["Alan"]);
687 assert!(state.is_open());
688 }
689
690 #[test]
691 fn values_are_kept_in_the_order_chosen() {
692 let mut state = people();
693 let _ = state.update(Event::Open);
694 let _ = state.update(Event::Activate(4));
695 let _ = state.update(Event::Activate(1));
696 let _ = state.update(Event::Activate(2));
697 assert_eq!(chosen(&state), ["Margaret", "Alan", "Grace"]);
698 }
699
700 #[test]
701 fn remove_takes_out_one_chip_by_option_index() {
702 let mut state = people().with_chosen(&["Ada", "Grace", "Linus"]);
703 assert_eq!(
704 state.update(Event::Remove(2)),
705 Some(Output::Removed("Grace"))
706 );
707 assert_eq!(chosen(&state), ["Ada", "Linus"]);
708 assert_eq!(state.update(Event::Remove(2)), None, "already removed");
709 assert_eq!(state.update(Event::Remove(99)), None);
710 assert!(!state.is_open(), "removing does not open the list");
711 }
712
713 #[test]
714 fn remove_last_takes_the_most_recent_chip() {
715 let mut state = people().with_chosen(&["Linus", "Ada"]);
716 assert_eq!(
717 state.update(Event::RemoveLast),
718 Some(Output::Removed("Ada"))
719 );
720 assert_eq!(
721 state.update(Event::RemoveLast),
722 Some(Output::Removed("Linus"))
723 );
724 assert_eq!(state.update(Event::RemoveLast), None);
725 }
726
727 #[test]
728 fn closed_list_ignores_activate_highlighted() {
729 let mut state = people();
730 assert_eq!(state.update(Event::ActivateHighlighted), None);
731 assert!(chosen(&state).is_empty());
732 }
733
734 #[test]
735 fn arrows_open_then_wrap_round() {
736 let mut state = people();
737 let _ = state.update(Event::Previous);
738 assert!(state.is_open());
739 assert_eq!(state.highlighted(), Some(&"Ada"));
740 let _ = state.update(Event::Previous);
741 assert_eq!(state.highlighted(), Some(&"Margaret"));
742 let _ = state.update(Event::Next);
743 assert_eq!(state.highlighted(), Some(&"Ada"));
744 }
745
746 #[test]
747 fn close_clears_the_query_and_keeps_the_chips() {
748 let mut state = people().with_chosen(&["Ada"]);
749 let _ = state.update(Event::Input("li".into()));
750 let _ = state.update(Event::Close);
751 assert!(!state.is_open());
752 assert_eq!(state.query(), "");
753 assert_eq!(chosen(&state), ["Ada"]);
754 }
755
756 #[test]
757 fn no_match_leaves_nothing_to_choose() {
758 let mut state = people();
759 let _ = state.update(Event::Input("zz".into()));
760 assert!(state.highlighted().is_none());
761 assert_eq!(state.update(Event::ActivateHighlighted), None);
762 }
763
764 #[test]
765 fn highlight_and_scroll_follow_the_combobox() {
766 let mut state = people().with_visible_rows(2);
767 let _ = state.update(Event::Open);
768 let _ = state.update(Event::Highlight(1));
769 assert_eq!(state.highlighted(), Some(&"Alan"));
770 let _ = state.update(Event::Scroll(10));
771 assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [3, 4]);
772 }
773
774 #[test]
775 fn empty_options_are_safe() {
776 let mut state = State::<&str>::new([]);
777 let _ = state.update(Event::Next);
778 assert_eq!(state.update(Event::ActivateHighlighted), None);
779 assert_eq!(state.update(Event::Activate(0)), None);
780 assert_eq!(state.update(Event::RemoveLast), None);
781 }
782
783 #[test]
784 fn default_keymap_overrides_and_unbinding() {
785 let keymap = default_keymap();
786 assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
787 assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
788 assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
789 assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
790 assert_eq!(press(&keymap, "Backspace"), Some(Action::RemoveLast));
791
792 let custom = keymap
793 .bind(Chord::character('n').ctrl(), Action::Next)
794 .unbind(&Chord::named(Named::Backspace));
795 assert_eq!(press(&custom, "ctrl+n"), Some(Action::Next));
796 assert_eq!(press(&custom, "Backspace"), None);
797 }
798
799 #[test]
800 fn actions_map_to_events_only_when_they_apply() {
801 let mut state = people();
802 assert_eq!(Action::Next.event(&state), Some(Event::Next));
803 assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
804 assert_eq!(Action::Activate.event(&state), None);
805 assert_eq!(Action::Close.event(&state), None);
806 assert_eq!(Action::RemoveLast.event(&state), None, "no chips");
807
808 let _ = state.update(Event::Open);
809 let _ = state.update(Event::ActivateHighlighted);
810 assert_eq!(
811 Action::Activate.event(&state),
812 Some(Event::ActivateHighlighted)
813 );
814 assert_eq!(Action::Close.event(&state), Some(Event::Close));
815 assert_eq!(Action::RemoveLast.event(&state), Some(Event::RemoveLast));
816
817 let _ = state.update(Event::Input("a".into()));
818 assert_eq!(
819 Action::RemoveLast.event(&state),
820 None,
821 "Backspace edits the query"
822 );
823 }
824
825 #[test]
826 fn default_builder_is_disabled() {
827 let state = people();
828 let c: MultiCombobox<'_, &str, Event> = multi_combobox(&state);
829 assert!(!c.is_enabled());
830 assert_eq!(c.empty, DEFAULT_EMPTY);
831 assert_eq!(c.width, Length::Fixed(320.0));
832 assert_eq!(c.size, Size::Md);
833 assert_eq!(c.keymap, default_keymap());
834 assert_eq!(c.shortcuts, Shortcuts::all());
835 assert!(c.key.is_none());
836 let c = c
837 .placeholder("Add guests")
838 .empty("Nobody")
839 .size(Size::Sm)
840 .id("guests")
841 .invalid(true)
842 .on_event(|e| e);
843 assert!(c.is_enabled());
844 assert!(c.invalid);
845 assert_eq!(c.key.as_deref(), Some("guests"));
846 assert_eq!(
847 (c.placeholder.as_str(), c.empty.as_str()),
848 ("Add guests", "Nobody")
849 );
850 }
851
852 #[test]
853 fn chip_sizes_follow_the_field() {
854 assert_eq!(chip_size(Size::Sm), chip::Size::Sm);
855 assert_eq!(chip_size(Size::Md), chip::Size::Md);
856 assert_eq!(chip_size(Size::Lg), chip::Size::Md);
857 }
858
859 #[test]
860 fn remove_ids_are_per_combobox_and_option() {
861 assert_eq!(remove_id("guests", 1), remove_id("guests", 1));
862 assert_ne!(remove_id("guests", 1), remove_id("guests", 2));
863 assert_ne!(remove_id("guests", 1), remove_id("members", 1));
864 }
865}