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
487impl<'a, T, Message> From<MultiCombobox<'a, T, Message>> for Element<'a, Message>
488where
489 T: Display + 'a,
490 Message: Clone + 'a,
491{
492 fn from(combobox: MultiCombobox<'a, T, Message>) -> Self {
493 let MultiCombobox {
494 state,
495 placeholder,
496 empty,
497 width,
498 size,
499 key,
500 invalid,
501 keymap,
502 shortcuts,
503 on_event,
504 } = combobox;
505 let on_event: Option<Rc<dyn Fn(Event) -> Message + 'a>> = on_event.map(Rc::from);
506 let id = key.clone().map(widget::Id::from);
507
508 let chips = state.chosen.iter().filter_map(|&index| {
509 let option = state.list.option(index)?;
510 let mut chip = chip(option.to_string())
511 .size(chip_size(size))
512 .on_remove_maybe(on_event.as_ref().map(|f| f(Event::Remove(index))));
513 if let Some(key) = &key {
514 chip = chip.id(chip_key(key, index));
515 }
516 Some(Element::from(chip))
517 });
518 let chips: Element<'a, Message> = row(chips)
519 .spacing(CHIP_GAP)
520 .wrap()
521 .vertical_spacing(CHIP_GAP)
522 .into();
523 let has_chips = !state.chosen.is_empty();
524
525 let Some(on_event) = on_event else {
526 let field = field(&placeholder, "", size, id, None, false, invalid);
527 let content = if has_chips {
528 column![chips, field].spacing(GAP)
529 } else {
530 column![field]
531 };
532 return container(content).width(width).into();
533 };
534
535 let open = state.is_open();
536 let list = open.then(|| {
537 suggestions(
538 &state.list,
539 &empty,
540 &|index| state.is_chosen(index),
541 &|event| on_event(list_event(event)),
542 )
543 });
544 let editing = Editing {
545 on_input: {
546 let on_event = Rc::clone(&on_event);
547 Box::new(move |query| on_event(Event::Input(query)))
548 },
549 shortcuts,
550 };
551 let field = field(
552 &placeholder,
553 state.query(),
554 size,
555 id,
556 Some(editing),
557 open,
558 invalid,
559 );
560 let field = anchored(field).on_anchor_press_maybe((!open).then(|| on_event(Event::Open)));
562 let content = if has_chips {
563 column![chips, field].spacing(GAP)
564 } else {
565 column![field]
566 };
567
568 anchored(container(content).width(width))
569 .content(list)
570 .placement(Placement::new(Side::Bottom, Align::Start))
571 .match_width(true)
572 .dismiss_keys([])
573 .dismiss_on_blur(true)
574 .on_dismiss_maybe(open.then(|| on_event(Event::Close)))
575 .on_key(move |key| {
576 keymap
577 .resolve_event(key)
578 .and_then(|action| action.event(state))
579 .map(&*on_event)
580 })
581 .into()
582 }
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588
589 const PEOPLE: [&str; 5] = ["Ada", "Alan", "Grace", "Linus", "Margaret"];
590
591 fn people() -> State<&'static str> {
592 State::new(PEOPLE)
593 }
594
595 fn chosen(state: &State<&'static str>) -> Vec<&'static str> {
596 state.chosen().copied().collect()
597 }
598
599 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
600 let chord: Chord = chord.parse().ok()?;
601 keymap.resolve(chord.key(), chord.modifiers())
602 }
603
604 #[test]
605 fn new_state_is_closed_with_nothing_chosen() {
606 let state = people();
607 assert!(!state.is_open());
608 assert!(chosen(&state).is_empty());
609 assert_eq!(state.query(), "");
610 assert_eq!(state.matches().count(), PEOPLE.len());
611 }
612
613 #[test]
614 fn with_chosen_keeps_order_and_skips_unknowns_and_repeats() {
615 let state = people().with_chosen(&["Linus", "Kiwi", "Ada", "Linus"]);
616 assert_eq!(chosen(&state), ["Linus", "Ada"]);
617 assert_eq!(state.chosen_indices(), [3, 0]);
618 assert!(state.is_chosen(3));
619 assert!(!state.is_chosen(1));
620 }
621
622 #[test]
623 fn choosing_adds_keeps_the_list_open_and_clears_the_query() {
624 let mut state = people();
625 let _ = state.update(Event::Input("gr".into()));
626 assert_eq!(state.highlighted(), Some(&"Grace"));
627 assert_eq!(
628 state.update(Event::ActivateHighlighted),
629 Some(Output::Added("Grace"))
630 );
631 assert!(state.is_open());
632 assert_eq!(state.query(), "");
633 assert_eq!(state.matches().count(), PEOPLE.len());
634 assert_eq!(state.highlighted(), Some(&"Grace"), "highlight stays put");
635 assert_eq!(chosen(&state), ["Grace"]);
636 }
637
638 #[test]
639 fn choosing_a_chosen_option_removes_it() {
640 let mut state = people().with_chosen(&["Ada", "Alan"]);
641 let _ = state.update(Event::Open);
642 assert_eq!(
643 state.update(Event::Activate(0)),
644 Some(Output::Removed("Ada"))
645 );
646 assert_eq!(chosen(&state), ["Alan"]);
647 assert!(state.is_open());
648 }
649
650 #[test]
651 fn values_are_kept_in_the_order_chosen() {
652 let mut state = people();
653 let _ = state.update(Event::Open);
654 let _ = state.update(Event::Activate(4));
655 let _ = state.update(Event::Activate(1));
656 let _ = state.update(Event::Activate(2));
657 assert_eq!(chosen(&state), ["Margaret", "Alan", "Grace"]);
658 }
659
660 #[test]
661 fn remove_takes_out_one_chip_by_option_index() {
662 let mut state = people().with_chosen(&["Ada", "Grace", "Linus"]);
663 assert_eq!(
664 state.update(Event::Remove(2)),
665 Some(Output::Removed("Grace"))
666 );
667 assert_eq!(chosen(&state), ["Ada", "Linus"]);
668 assert_eq!(state.update(Event::Remove(2)), None, "already removed");
669 assert_eq!(state.update(Event::Remove(99)), None);
670 assert!(!state.is_open(), "removing does not open the list");
671 }
672
673 #[test]
674 fn remove_last_takes_the_most_recent_chip() {
675 let mut state = people().with_chosen(&["Linus", "Ada"]);
676 assert_eq!(
677 state.update(Event::RemoveLast),
678 Some(Output::Removed("Ada"))
679 );
680 assert_eq!(
681 state.update(Event::RemoveLast),
682 Some(Output::Removed("Linus"))
683 );
684 assert_eq!(state.update(Event::RemoveLast), None);
685 }
686
687 #[test]
688 fn closed_list_ignores_activate_highlighted() {
689 let mut state = people();
690 assert_eq!(state.update(Event::ActivateHighlighted), None);
691 assert!(chosen(&state).is_empty());
692 }
693
694 #[test]
695 fn arrows_open_then_wrap_round() {
696 let mut state = people();
697 let _ = state.update(Event::Previous);
698 assert!(state.is_open());
699 assert_eq!(state.highlighted(), Some(&"Ada"));
700 let _ = state.update(Event::Previous);
701 assert_eq!(state.highlighted(), Some(&"Margaret"));
702 let _ = state.update(Event::Next);
703 assert_eq!(state.highlighted(), Some(&"Ada"));
704 }
705
706 #[test]
707 fn close_clears_the_query_and_keeps_the_chips() {
708 let mut state = people().with_chosen(&["Ada"]);
709 let _ = state.update(Event::Input("li".into()));
710 let _ = state.update(Event::Close);
711 assert!(!state.is_open());
712 assert_eq!(state.query(), "");
713 assert_eq!(chosen(&state), ["Ada"]);
714 }
715
716 #[test]
717 fn no_match_leaves_nothing_to_choose() {
718 let mut state = people();
719 let _ = state.update(Event::Input("zz".into()));
720 assert!(state.highlighted().is_none());
721 assert_eq!(state.update(Event::ActivateHighlighted), None);
722 }
723
724 #[test]
725 fn highlight_and_scroll_follow_the_combobox() {
726 let mut state = people().with_visible_rows(2);
727 let _ = state.update(Event::Open);
728 let _ = state.update(Event::Highlight(1));
729 assert_eq!(state.highlighted(), Some(&"Alan"));
730 let _ = state.update(Event::Scroll(10));
731 assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [3, 4]);
732 }
733
734 #[test]
735 fn empty_options_are_safe() {
736 let mut state = State::<&str>::new([]);
737 let _ = state.update(Event::Next);
738 assert_eq!(state.update(Event::ActivateHighlighted), None);
739 assert_eq!(state.update(Event::Activate(0)), None);
740 assert_eq!(state.update(Event::RemoveLast), None);
741 }
742
743 #[test]
744 fn default_keymap_overrides_and_unbinding() {
745 let keymap = default_keymap();
746 assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
747 assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
748 assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
749 assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
750 assert_eq!(press(&keymap, "Backspace"), Some(Action::RemoveLast));
751
752 let custom = keymap
753 .bind(Chord::character('n').ctrl(), Action::Next)
754 .unbind(&Chord::named(Named::Backspace));
755 assert_eq!(press(&custom, "ctrl+n"), Some(Action::Next));
756 assert_eq!(press(&custom, "Backspace"), None);
757 }
758
759 #[test]
760 fn actions_map_to_events_only_when_they_apply() {
761 let mut state = people();
762 assert_eq!(Action::Next.event(&state), Some(Event::Next));
763 assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
764 assert_eq!(Action::Activate.event(&state), None);
765 assert_eq!(Action::Close.event(&state), None);
766 assert_eq!(Action::RemoveLast.event(&state), None, "no chips");
767
768 let _ = state.update(Event::Open);
769 let _ = state.update(Event::ActivateHighlighted);
770 assert_eq!(
771 Action::Activate.event(&state),
772 Some(Event::ActivateHighlighted)
773 );
774 assert_eq!(Action::Close.event(&state), Some(Event::Close));
775 assert_eq!(Action::RemoveLast.event(&state), Some(Event::RemoveLast));
776
777 let _ = state.update(Event::Input("a".into()));
778 assert_eq!(
779 Action::RemoveLast.event(&state),
780 None,
781 "Backspace edits the query"
782 );
783 }
784
785 #[test]
786 fn default_builder_is_disabled() {
787 let state = people();
788 let c: MultiCombobox<'_, &str, Event> = multi_combobox(&state);
789 assert!(!c.is_enabled());
790 assert_eq!(c.empty, DEFAULT_EMPTY);
791 assert_eq!(c.width, Length::Fixed(320.0));
792 assert_eq!(c.size, Size::Md);
793 assert_eq!(c.keymap, default_keymap());
794 assert_eq!(c.shortcuts, Shortcuts::all());
795 assert!(c.key.is_none());
796 let c = c
797 .placeholder("Add guests")
798 .empty("Nobody")
799 .size(Size::Sm)
800 .id("guests")
801 .invalid(true)
802 .on_event(|e| e);
803 assert!(c.is_enabled());
804 assert!(c.invalid);
805 assert_eq!(c.key.as_deref(), Some("guests"));
806 assert_eq!(
807 (c.placeholder.as_str(), c.empty.as_str()),
808 ("Add guests", "Nobody")
809 );
810 }
811
812 #[test]
813 fn chip_sizes_follow_the_field() {
814 assert_eq!(chip_size(Size::Sm), chip::Size::Sm);
815 assert_eq!(chip_size(Size::Md), chip::Size::Md);
816 assert_eq!(chip_size(Size::Lg), chip::Size::Md);
817 }
818
819 #[test]
820 fn remove_ids_are_per_combobox_and_option() {
821 assert_eq!(remove_id("guests", 1), remove_id("guests", 1));
822 assert_ne!(remove_id("guests", 1), remove_id("guests", 2));
823 assert_ne!(remove_id("guests", 1), remove_id("members", 1));
824 }
825}