Skip to main content

iced_cube/forms/
combobox.rs

1//! A text field with a list of suggestions that filters as you type.
2//!
3//! [`State`] holds the options, the query, the highlighted suggestion and
4//! the selected value. The app owns it and passes every [`Event`] to
5//! [`State::update`], which returns the value when one is chosen.
6//!
7//! While the field has focus or the list is open, the combobox handles its
8//! own keys through a [`Keymap`] of [`Action`]s: arrows move the highlight,
9//! Enter chooses and Escape closes. See [`default_keymap`]. The list is
10//! drawn in the shared [menu look](crate::overlay::menu) on the
11//! [anchored layer](crate::overlay::anchored), so a click outside closes
12//! only the list, even inside a dialog or popover.
13//!
14//! ```no_run
15//! use iced::Element;
16//! use iced_cube::forms::combobox::{self, combobox};
17//!
18//! #[derive(Debug, Clone)]
19//! enum Message {
20//!     Fruit(combobox::Event),
21//! }
22//!
23//! struct App {
24//!     fruit: combobox::State<&'static str>,
25//! }
26//!
27//! impl App {
28//!     fn update(&mut self, message: Message) {
29//!         let Message::Fruit(event) = message;
30//!         if let Some(fruit) = self.fruit.update(event) {
31//!             println!("Chose {fruit}");
32//!         }
33//!     }
34//!
35//!     fn view(&self) -> Element<'_, Message> {
36//!         combobox(&self.fruit)
37//!             .placeholder("Search fruit...")
38//!             .on_event(Message::Fruit)
39//!             .into()
40//!     }
41//! }
42//! ```
43
44use std::fmt::{self, Display};
45use std::rc::Rc;
46
47use iced::advanced::layout::{self, Layout};
48use iced::advanced::widget::{Operation, Tree, Widget, operation, tree};
49use iced::advanced::{Clipboard, Shell, overlay, renderer};
50use iced::keyboard::key::Named;
51use iced::mouse::{self, ScrollDelta};
52use iced::widget::text::LineHeight;
53use iced::widget::text_input::{self, Status};
54use iced::widget::{self, Column, container, mouse_area, stack};
55use iced::{Alignment, Element, Length, Padding, Renderer, Theme};
56
57use crate::icon::{opacity, themed};
58use crate::keys::{self, Chord, Keymap};
59use crate::overlay::anchored::{Align, Placement, Side, anchored};
60use crate::overlay::menu::{self, Parts, RowStatus, Trailing};
61use crate::primitives::input::{self, Shortcuts, Size};
62use crate::theme::{Tokens, space};
63
64/// How many suggestions show at once unless the state sets its own number.
65pub const VISIBLE_ROWS: usize = 6;
66/// Shown when no option matches the query, unless the builder sets its own.
67pub const DEFAULT_EMPTY: &str = "No results found.";
68
69// Matches the line height `input` uses, so the field is the same height.
70const LINE_HEIGHT: f32 = 1.3;
71
72/// Everything that changes a combobox.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum Event {
75    /// The query was edited. Opens the list and highlights the first match.
76    Input(String),
77    Open,
78    /// Closes the list and clears the query.
79    Close,
80    /// Highlights the next match, wrapping round. Opens a closed list.
81    Next,
82    /// Highlights the previous match, wrapping round. Opens a closed list.
83    Previous,
84    /// Chooses the highlighted match.
85    ActivateHighlighted,
86    /// Highlights an option, by its index in [`State::options`].
87    Highlight(usize),
88    /// Chooses an option, by its index in [`State::options`].
89    Activate(usize),
90    /// Scrolls the list by a number of rows, down when positive.
91    Scroll(i32),
92}
93
94/// The options, the query and what is highlighted and selected.
95#[derive(Debug, Clone, PartialEq)]
96pub struct State<T> {
97    list: Suggestions<T>,
98    selected: Option<usize>,
99}
100
101impl<T: Display> State<T> {
102    /// Creates a closed combobox with nothing selected. Options are
103    /// labelled with their `Display` text.
104    pub fn new(options: impl IntoIterator<Item = T>) -> Self {
105        Self {
106            list: Suggestions::new(options),
107            selected: None,
108        }
109    }
110}
111
112impl<T: PartialEq> State<T> {
113    /// Starts with `value` selected, when it is one of the options.
114    pub fn with_selected(mut self, value: &T) -> Self {
115        self.selected = self.list.position(value);
116        self
117    }
118}
119
120impl<T> State<T> {
121    /// Sets how many suggestions show at once. At least one does.
122    pub fn with_visible_rows(mut self, rows: usize) -> Self {
123        self.list.set_rows(rows);
124        self
125    }
126
127    pub fn options(&self) -> &[T] {
128        self.list.options()
129    }
130
131    pub fn selected(&self) -> Option<&T> {
132        self.selected.and_then(|index| self.list.option(index))
133    }
134
135    pub fn query(&self) -> &str {
136        self.list.query()
137    }
138
139    pub fn is_open(&self) -> bool {
140        self.list.is_open()
141    }
142
143    /// The options that match the query, in their original order.
144    pub fn matches(&self) -> impl Iterator<Item = &T> {
145        self.list.matches()
146    }
147
148    /// The highlighted option, if any option matches.
149    pub fn highlighted(&self) -> Option<&T> {
150        self.list.highlighted()
151    }
152
153    /// The matches in view, with their index in [`State::options`].
154    pub fn visible(&self) -> impl Iterator<Item = (usize, &T)> {
155        self.list.visible()
156    }
157
158    /// Applies an event and returns the chosen value, if one was chosen.
159    pub fn update(&mut self, event: Event) -> Option<T>
160    where
161        T: Clone,
162    {
163        match event {
164            Event::Input(query) => self.list.input(query),
165            Event::Open => self.list.open(self.selected),
166            Event::Close => self.list.close(),
167            Event::Next | Event::Previous if !self.list.is_open() => self.list.open(self.selected),
168            Event::Next => self.list.step(1),
169            Event::Previous => self.list.step(-1),
170            Event::ActivateHighlighted => {
171                if !self.list.is_open() {
172                    return None;
173                }
174                let index = self.list.highlighted_index()?;
175                return self.choose(index);
176            }
177            Event::Activate(index) => return self.choose(index),
178            Event::Highlight(index) => self.list.highlight_option(index),
179            Event::Scroll(rows) => self.list.scroll(rows),
180        }
181        None
182    }
183
184    fn choose(&mut self, index: usize) -> Option<T>
185    where
186        T: Clone,
187    {
188        let value = self.list.option(index)?.clone();
189        self.selected = Some(index);
190        self.list.close();
191        Some(value)
192    }
193}
194
195/// What a row of the shared suggestion list sends.
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub(crate) enum ListEvent {
198    Highlight(usize),
199    Activate(usize),
200    Scroll(i32),
201}
202
203/// The options, query, matches, highlight and window shared by the single
204/// and multiple choice comboboxes.
205#[derive(Debug, Clone, PartialEq)]
206pub(crate) struct Suggestions<T> {
207    options: Vec<T>,
208    labels: Vec<String>,
209    query: String,
210    /// Indices into `options` of the options that match `query`.
211    matches: Vec<usize>,
212    /// Position in `matches`.
213    highlighted: usize,
214    /// Position in `matches` of the first visible row.
215    offset: usize,
216    open: bool,
217    rows: usize,
218}
219
220impl<T: Display> Suggestions<T> {
221    pub(crate) fn new(options: impl IntoIterator<Item = T>) -> Self {
222        let options: Vec<T> = options.into_iter().collect();
223        let labels = options
224            .iter()
225            .map(|option| option.to_string().to_lowercase())
226            .collect();
227        let matches = (0..options.len()).collect();
228        Self {
229            options,
230            labels,
231            query: String::new(),
232            matches,
233            highlighted: 0,
234            offset: 0,
235            open: false,
236            rows: VISIBLE_ROWS,
237        }
238    }
239}
240
241impl<T: PartialEq> Suggestions<T> {
242    /// The index of `value` in the options.
243    pub(crate) fn position(&self, value: &T) -> Option<usize> {
244        self.options.iter().position(|option| option == value)
245    }
246}
247
248impl<T> Suggestions<T> {
249    pub(crate) fn set_rows(&mut self, rows: usize) {
250        self.rows = rows.max(1);
251        self.reveal();
252    }
253
254    pub(crate) fn options(&self) -> &[T] {
255        &self.options
256    }
257
258    pub(crate) fn option(&self, index: usize) -> Option<&T> {
259        self.options.get(index)
260    }
261
262    pub(crate) fn query(&self) -> &str {
263        &self.query
264    }
265
266    pub(crate) fn is_open(&self) -> bool {
267        self.open
268    }
269
270    pub(crate) fn matches(&self) -> impl Iterator<Item = &T> {
271        self.matches
272            .iter()
273            .filter_map(|&index| self.options.get(index))
274    }
275
276    pub(crate) fn highlighted(&self) -> Option<&T> {
277        self.highlighted_index()
278            .and_then(|index| self.options.get(index))
279    }
280
281    /// The highlighted option's index in the options.
282    pub(crate) fn highlighted_index(&self) -> Option<usize> {
283        self.matches.get(self.highlighted).copied()
284    }
285
286    pub(crate) fn visible(&self) -> impl Iterator<Item = (usize, &T)> {
287        self.matches
288            .iter()
289            .skip(self.offset)
290            .take(self.rows)
291            .filter_map(|&index| self.options.get(index).map(|option| (index, option)))
292    }
293
294    pub(crate) fn is_highlighted(&self, index: usize) -> bool {
295        self.matches.get(self.highlighted) == Some(&index)
296    }
297
298    /// Sets the query, opens the list and highlights the first match.
299    pub(crate) fn input(&mut self, query: String) {
300        self.query = query;
301        self.open = true;
302        self.filter();
303        self.highlight(0);
304    }
305
306    /// Highlights an option by its index, if it matches the query.
307    pub(crate) fn highlight_option(&mut self, index: usize) {
308        if let Some(position) = self.matches.iter().position(|&i| i == index) {
309            self.highlight(position);
310        }
311    }
312
313    pub(crate) fn scroll(&mut self, rows: i32) {
314        let last = self.matches.len().saturating_sub(self.rows);
315        let offset = (self.offset as i64).saturating_add(rows.into());
316        self.offset = offset.clamp(0, last as i64) as usize;
317    }
318
319    /// Clears the query and shows every option again, keeping the
320    /// highlighted option highlighted.
321    #[cfg(feature = "multi-combobox")]
322    pub(crate) fn clear_query(&mut self) {
323        let highlighted = self.highlighted_index();
324        self.query.clear();
325        self.filter();
326        let position = highlighted
327            .and_then(|index| self.matches.iter().position(|&i| i == index))
328            .unwrap_or(0);
329        self.highlight(position);
330    }
331
332    fn filter(&mut self) {
333        let query = self.query.trim().to_lowercase();
334        self.matches = self
335            .labels
336            .iter()
337            .enumerate()
338            .filter(|(_, label)| label.contains(&query))
339            .map(|(index, _)| index)
340            .collect();
341    }
342
343    /// Opens the list with every option showing, highlighting `preferred`
344    /// (an option index) or else the first option.
345    pub(crate) fn open(&mut self, preferred: Option<usize>) {
346        self.open = true;
347        self.query.clear();
348        self.filter();
349        let position = preferred.and_then(|index| self.matches.iter().position(|&i| i == index));
350        self.offset = 0;
351        self.highlight(position.unwrap_or(0));
352    }
353
354    pub(crate) fn close(&mut self) {
355        self.open = false;
356        self.query.clear();
357        self.filter();
358        self.offset = 0;
359    }
360
361    pub(crate) fn step(&mut self, delta: isize) {
362        let len = self.matches.len() as isize;
363        if len == 0 {
364            return;
365        }
366        let next = (self.highlighted as isize + delta).rem_euclid(len);
367        self.highlight(next as usize);
368    }
369
370    fn highlight(&mut self, position: usize) {
371        self.highlighted = position.min(self.matches.len().saturating_sub(1));
372        self.reveal();
373    }
374
375    /// Moves the window so the highlighted row is in view.
376    fn reveal(&mut self) {
377        if self.highlighted < self.offset {
378            self.offset = self.highlighted;
379        } else if self.highlighted >= self.offset + self.rows {
380            self.offset = self.highlighted + 1 - self.rows;
381        }
382        self.offset = self
383            .offset
384            .min(self.matches.len().saturating_sub(self.rows));
385    }
386}
387
388/// What a combobox keyboard shortcut does.
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
390pub enum Action {
391    Next,
392    Previous,
393    Activate,
394    Close,
395}
396
397impl Action {
398    /// The [`Event`] this action sends to `state`, or `None` when it would
399    /// do nothing, so the key can reach the text field instead.
400    pub fn event<T>(self, state: &State<T>) -> Option<Event> {
401        match self {
402            Action::Next => Some(Event::Next),
403            Action::Previous => Some(Event::Previous),
404            Action::Activate => state.is_open().then_some(Event::ActivateHighlighted),
405            Action::Close => state.is_open().then_some(Event::Close),
406        }
407    }
408}
409
410impl keys::Action for Action {
411    const ALL: &'static [Self] = &[
412        Action::Next,
413        Action::Previous,
414        Action::Activate,
415        Action::Close,
416    ];
417
418    fn defaults() -> Keymap<Self> {
419        default_keymap()
420    }
421
422    fn name(self) -> &'static str {
423        match self {
424            Action::Next => "Next",
425            Action::Previous => "Previous",
426            Action::Activate => "Activate",
427            Action::Close => "Close",
428        }
429    }
430
431    fn description(self) -> &'static str {
432        match self {
433            Action::Next => "Highlights the next suggestion, opening the list if it is closed.",
434            Action::Previous => {
435                "Highlights the previous suggestion, opening the list if it is closed."
436            }
437            Action::Activate => "Chooses the highlighted suggestion and closes the list.",
438            Action::Close => "Closes the list and clears the query.",
439        }
440    }
441}
442
443/// The default combobox shortcuts:
444///
445/// | Keys | Action |
446/// | --- | --- |
447/// | `ArrowDown` | [`Action::Next`] |
448/// | `ArrowUp` | [`Action::Previous`] |
449/// | `Enter` | [`Action::Activate`] |
450/// | `Escape` | [`Action::Close`] |
451///
452/// The combobox handles these itself while its field has focus or its list
453/// is open, so the app does not need to subscribe to key presses. Pass a
454/// changed keymap with [`Combobox::keymap`].
455pub fn default_keymap() -> Keymap<Action> {
456    Keymap::new()
457        .bind(Chord::named(Named::ArrowDown), Action::Next)
458        .bind(Chord::named(Named::ArrowUp), Action::Previous)
459        .bind(Chord::named(Named::Enter), Action::Activate)
460        .bind(Chord::named(Named::Escape), Action::Close)
461}
462
463/// A combobox builder. Convert it into an [`Element`] to render.
464///
465/// A combobox without [`on_event`](Combobox::on_event) is rendered disabled.
466pub struct Combobox<'a, T, Message> {
467    state: &'a State<T>,
468    placeholder: String,
469    empty: String,
470    width: Length,
471    size: Size,
472    id: Option<widget::Id>,
473    invalid: bool,
474    keymap: Keymap<Action>,
475    shortcuts: Shortcuts,
476    on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
477}
478
479/// Renders the field and, while it is open, the suggestions of `state`.
480pub fn combobox<'a, T, Message>(state: &'a State<T>) -> Combobox<'a, T, Message> {
481    Combobox {
482        state,
483        placeholder: String::new(),
484        empty: DEFAULT_EMPTY.to_owned(),
485        width: Length::Fixed(240.0),
486        size: Size::default(),
487        id: None,
488        invalid: false,
489        keymap: default_keymap(),
490        shortcuts: Shortcuts::all(),
491        on_event: None,
492    }
493}
494
495impl<T: fmt::Debug, Message> fmt::Debug for Combobox<'_, T, Message> {
496    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497        f.debug_struct("Combobox")
498            .field("state", self.state)
499            .field("placeholder", &self.placeholder)
500            .field("empty", &self.empty)
501            .field("width", &self.width)
502            .field("size", &self.size)
503            .field("invalid", &self.invalid)
504            .field("shortcuts", &self.shortcuts)
505            .field("enabled", &self.on_event.is_some())
506            .finish_non_exhaustive()
507    }
508}
509
510impl<'a, T, Message> Combobox<'a, T, Message> {
511    /// Text shown while the field is empty and nothing is selected.
512    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
513        self.placeholder = placeholder.into();
514        self
515    }
516
517    /// Text shown in the list when no option matches the query.
518    pub fn empty(mut self, empty: impl Into<String>) -> Self {
519        self.empty = empty.into();
520        self
521    }
522
523    /// Overrides the width. Defaults to 240 pixels.
524    pub fn width(mut self, width: impl Into<Length>) -> Self {
525        self.width = width.into();
526        self
527    }
528
529    /// The field's height, padding and text size, shared with
530    /// [`input`](fn@crate::primitives::input). Defaults to [`Size::Md`].
531    pub fn size(mut self, size: Size) -> Self {
532        self.size = size;
533        self
534    }
535
536    /// Sets the widget id of the text field, to focus it or find it in tests.
537    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
538        self.id = Some(id.into());
539        self
540    }
541
542    /// Draws the field with the destructive border, as
543    /// [`input`](fn@crate::primitives::input) does, for example when a required
544    /// value is missing.
545    pub fn invalid(mut self, invalid: bool) -> Self {
546        self.invalid = invalid;
547        self
548    }
549
550    /// Replaces the [`default_keymap`].
551    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
552        self.keymap = keymap;
553        self
554    }
555
556    /// Sets which editing [`Shortcut`](input::Shortcut)s the field handles,
557    /// as [`Input::shortcuts`](input::Input::shortcuts) does. All of them by
558    /// default.
559    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
560        self.shortcuts = shortcuts;
561        self
562    }
563
564    /// Maps combobox events to your message. Without it the combobox is
565    /// disabled.
566    pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
567        self.on_event = Some(Box::new(on_event));
568        self
569    }
570
571    pub fn is_enabled(&self) -> bool {
572        self.on_event.is_some()
573    }
574}
575
576impl<'a, T, Message> From<Combobox<'a, T, Message>> for Element<'a, Message>
577where
578    T: Display + 'a,
579    Message: Clone + 'a,
580{
581    fn from(combobox: Combobox<'a, T, Message>) -> Self {
582        let Combobox {
583            state,
584            placeholder,
585            empty,
586            width,
587            size,
588            id,
589            invalid,
590            keymap,
591            shortcuts,
592            on_event,
593        } = combobox;
594        let selected = state.selected().map(ToString::to_string);
595
596        let Some(on_event) = on_event else {
597            let value = selected.unwrap_or_default();
598            let field = field(&placeholder, &value, size, id, None, false, invalid);
599            return container(field).width(width).into();
600        };
601        let on_event: Rc<dyn Fn(Event) -> Message + 'a> = Rc::from(on_event);
602
603        let open = state.is_open();
604        let (value, hint) = if open {
605            (state.query().to_owned(), selected.unwrap_or(placeholder))
606        } else {
607            (selected.unwrap_or_default(), placeholder)
608        };
609
610        let list = open.then(|| {
611            let chosen = state.selected;
612            suggestions(
613                &state.list,
614                &empty,
615                &move |index| chosen == Some(index),
616                &|event| on_event(list_event(event)),
617            )
618        });
619        let on_anchor_press = (!open).then(|| on_event(Event::Open));
620        let on_dismiss = open.then(|| on_event(Event::Close));
621        let editing = Editing {
622            on_input: {
623                let on_event = Rc::clone(&on_event);
624                Box::new(move |query| on_event(Event::Input(query)))
625            },
626            shortcuts,
627        };
628        let field =
629            container(field(&hint, &value, size, id, Some(editing), open, invalid)).width(width);
630        let field = CaretToEnd {
631            content: field.into(),
632            watch: (open, state.selected),
633        };
634
635        anchored(Element::new(field))
636            .content(list)
637            .placement(Placement::new(Side::Bottom, Align::Start))
638            .match_width(true)
639            .dismiss_keys([])
640            .dismiss_on_blur(true)
641            .on_dismiss_maybe(on_dismiss)
642            .on_anchor_press_maybe(on_anchor_press)
643            .on_key(move |key| {
644                keymap
645                    .resolve_event(key)
646                    .and_then(|action| action.event(state))
647                    .map(&*on_event)
648            })
649            .into()
650    }
651}
652
653/// What an enabled field does with edits.
654pub(crate) struct Editing<'a, Message> {
655    pub(crate) on_input: Box<dyn Fn(String) -> Message + 'a>,
656    pub(crate) shortcuts: Shortcuts,
657}
658
659/// The text field with its chevron, built with the shared input shortcuts.
660pub(crate) fn field<'a, Message: Clone + 'a>(
661    placeholder: &str,
662    value: &str,
663    size: Size,
664    id: Option<widget::Id>,
665    editing: Option<Editing<'a, Message>>,
666    open: bool,
667    invalid: bool,
668) -> Element<'a, Message> {
669    let enabled = editing.is_some();
670    let metrics = size.metrics();
671    let mut padding = metrics.padding(false);
672    padding.right += metrics.icon + space::SM;
673
674    let mut text = widget::text_input(placeholder, value)
675        .size(metrics.text)
676        .line_height(LineHeight::Relative(LINE_HEIGHT))
677        .padding(padding)
678        .width(Length::Fill)
679        .style(move |theme, status| style(&Tokens::of(theme), status, open, invalid));
680    if let Some(id) = id {
681        text = text.id(id);
682    }
683    let (on_input, shortcuts) = match editing {
684        Some(Editing {
685            on_input,
686            shortcuts,
687        }) => (Some(on_input), shortcuts),
688        None => (None, Shortcuts::none()),
689    };
690    let keymap = input::default_keymap();
691    let input = input::with_shortcuts(text, value, false, on_input, keymap, shortcuts);
692
693    let chevron = themed(
694        crate::lucide!(ChevronsUpDown),
695        metrics.icon,
696        opacity(enabled),
697        |theme| Tokens::of(theme).muted_foreground,
698    );
699
700    stack![
701        input,
702        container(chevron)
703            .width(Length::Fill)
704            .height(Length::Fill)
705            .align_x(Alignment::End)
706            .align_y(Alignment::Center)
707            .padding(Padding::ZERO.right(metrics.padding_x)),
708    ]
709    .into()
710}
711
712fn list_event(event: ListEvent) -> Event {
713    match event {
714        ListEvent::Highlight(index) => Event::Highlight(index),
715        ListEvent::Activate(index) => Event::Activate(index),
716        ListEvent::Scroll(rows) => Event::Scroll(rows),
717    }
718}
719
720/// The floating list of `list`'s visible matches, with a tick on the
721/// options for which `ticked` holds.
722pub(crate) fn suggestions<'a, T: Display, Message: Clone + 'a>(
723    list: &'a Suggestions<T>,
724    empty: &str,
725    ticked: &dyn Fn(usize) -> bool,
726    on_event: &dyn Fn(ListEvent) -> Message,
727) -> Element<'a, Message> {
728    let rows: Vec<Element<'a, Message>> = list
729        .visible()
730        .map(|(index, option)| {
731            let status = if list.is_highlighted(index) {
732                RowStatus::Highlighted
733            } else {
734                RowStatus::Idle
735            };
736            let label = option.to_string();
737            let trailing = if ticked(index) {
738                Trailing::Check
739            } else {
740                Trailing::None
741            };
742            let parts = Parts {
743                trailing,
744                ..Parts::label(&label)
745            };
746            let messages = (
747                on_event(ListEvent::Highlight(index)),
748                on_event(ListEvent::Activate(index)),
749            );
750            menu::item(parts, status, false, Some(messages))
751        })
752        .collect();
753
754    let body: Element<'a, Message> = if rows.is_empty() {
755        menu::empty(empty)
756    } else {
757        Column::from_vec(rows).width(Length::Fill).into()
758    };
759
760    let down = on_event(ListEvent::Scroll(1));
761    let up = on_event(ListEvent::Scroll(-1));
762    mouse_area(menu::surface(body).width(Length::Fill))
763        .on_scroll(move |delta| match delta {
764            ScrollDelta::Lines { y, .. } | ScrollDelta::Pixels { y, .. } if y < 0.0 => down.clone(),
765            _ => up.clone(),
766        })
767        .into()
768}
769
770/// The field style: the input style, drawn focused while the list is open
771/// and with the destructive border while `invalid`.
772pub fn style(tokens: &Tokens, status: Status, open: bool, invalid: bool) -> text_input::Style {
773    let status = match status {
774        Status::Active if open => Status::Focused { is_hovered: false },
775        Status::Hovered if open => Status::Focused { is_hovered: true },
776        status => status,
777    };
778    input::style(tokens, status, invalid)
779}
780
781/// Wraps the field and moves its caret to the end whenever the list closes
782/// or the selection changes, so a picked value reads from its end rather
783/// than from wherever the caret was in the query.
784struct CaretToEnd<'a, Message> {
785    content: Element<'a, Message>,
786    /// Whether the list is open, and the selected option.
787    watch: (bool, Option<usize>),
788}
789
790/// The caret goes to the end once the list is closed, if it just closed or
791/// the selection changed.
792fn moves_caret(before: Option<(bool, Option<usize>)>, now: (bool, Option<usize>)) -> bool {
793    let Some(before) = before else {
794        return false;
795    };
796    let (open, selected) = now;
797    !open && (before.0 || before.1 != selected)
798}
799
800struct MoveCaretToEnd;
801
802impl Operation for MoveCaretToEnd {
803    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
804        operate(self);
805    }
806
807    fn text_input(
808        &mut self,
809        _id: Option<&widget::Id>,
810        _bounds: iced::Rectangle,
811        state: &mut dyn operation::TextInput,
812    ) {
813        state.move_cursor_to_end();
814    }
815}
816
817impl<Message> Widget<Message, Theme, Renderer> for CaretToEnd<'_, Message> {
818    fn size(&self) -> iced::Size<Length> {
819        self.content.as_widget().size()
820    }
821
822    fn size_hint(&self) -> iced::Size<Length> {
823        self.content.as_widget().size_hint()
824    }
825
826    fn tag(&self) -> tree::Tag {
827        tree::Tag::of::<Option<(bool, Option<usize>)>>()
828    }
829
830    fn state(&self) -> tree::State {
831        tree::State::new(None::<(bool, Option<usize>)>)
832    }
833
834    fn children(&self) -> Vec<Tree> {
835        vec![Tree::new(&self.content)]
836    }
837
838    fn diff(&self, tree: &mut Tree) {
839        tree.diff_children(std::slice::from_ref(&self.content));
840    }
841
842    // Layout runs after every change to the view, before the next draw, so
843    // the caret moves without waiting for another event.
844    fn layout(
845        &mut self,
846        tree: &mut Tree,
847        renderer: &Renderer,
848        limits: &layout::Limits,
849    ) -> layout::Node {
850        let node = self
851            .content
852            .as_widget_mut()
853            .layout(&mut tree.children[0], renderer, limits);
854        let seen = tree.state.downcast_mut::<Option<(bool, Option<usize>)>>();
855        let before = seen.replace(self.watch);
856        if moves_caret(before, self.watch) {
857            self.content.as_widget_mut().operate(
858                &mut tree.children[0],
859                Layout::new(&node),
860                renderer,
861                &mut MoveCaretToEnd,
862            );
863        }
864        node
865    }
866
867    fn draw(
868        &self,
869        tree: &Tree,
870        renderer: &mut Renderer,
871        theme: &Theme,
872        style: &renderer::Style,
873        layout: Layout<'_>,
874        cursor: mouse::Cursor,
875        viewport: &iced::Rectangle,
876    ) {
877        self.content.as_widget().draw(
878            &tree.children[0],
879            renderer,
880            theme,
881            style,
882            layout,
883            cursor,
884            viewport,
885        );
886    }
887
888    fn operate(
889        &mut self,
890        tree: &mut Tree,
891        layout: Layout<'_>,
892        renderer: &Renderer,
893        operation: &mut dyn Operation,
894    ) {
895        self.content
896            .as_widget_mut()
897            .operate(&mut tree.children[0], layout, renderer, operation);
898    }
899
900    fn update(
901        &mut self,
902        tree: &mut Tree,
903        event: &iced::Event,
904        layout: Layout<'_>,
905        cursor: mouse::Cursor,
906        renderer: &Renderer,
907        clipboard: &mut dyn Clipboard,
908        shell: &mut Shell<'_, Message>,
909        viewport: &iced::Rectangle,
910    ) {
911        self.content.as_widget_mut().update(
912            &mut tree.children[0],
913            event,
914            layout,
915            cursor,
916            renderer,
917            clipboard,
918            shell,
919            viewport,
920        );
921    }
922
923    fn mouse_interaction(
924        &self,
925        tree: &Tree,
926        layout: Layout<'_>,
927        cursor: mouse::Cursor,
928        viewport: &iced::Rectangle,
929        renderer: &Renderer,
930    ) -> mouse::Interaction {
931        self.content.as_widget().mouse_interaction(
932            &tree.children[0],
933            layout,
934            cursor,
935            viewport,
936            renderer,
937        )
938    }
939
940    fn overlay<'b>(
941        &'b mut self,
942        tree: &'b mut Tree,
943        layout: Layout<'b>,
944        renderer: &Renderer,
945        viewport: &iced::Rectangle,
946        translation: iced::Vector,
947    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
948        self.content.as_widget_mut().overlay(
949            &mut tree.children[0],
950            layout,
951            renderer,
952            viewport,
953            translation,
954        )
955    }
956}
957
958#[cfg(test)]
959mod tests {
960    use super::*;
961    use crate::theme::{dark, light};
962
963    const FRUITS: [&str; 5] = ["Apple", "Banana", "Blueberry", "Cherry", "Grape"];
964
965    fn fruits() -> State<&'static str> {
966        State::new(FRUITS)
967    }
968
969    fn matches(state: &State<&'static str>) -> Vec<&'static str> {
970        state.matches().copied().collect()
971    }
972
973    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
974        let chord: Chord = chord.parse().unwrap();
975        keymap.resolve(chord.key(), chord.modifiers())
976    }
977
978    #[test]
979    fn new_state_is_closed_with_every_option() {
980        let state = fruits();
981        assert!(!state.is_open());
982        assert!(state.selected().is_none());
983        assert_eq!(state.query(), "");
984        assert_eq!(matches(&state), FRUITS);
985        assert_eq!(state.visible().count(), 5);
986    }
987
988    #[test]
989    fn with_selected_ignores_unknown_values() {
990        assert_eq!(
991            fruits().with_selected(&"Cherry").selected(),
992            Some(&"Cherry")
993        );
994        assert!(fruits().with_selected(&"Kiwi").selected().is_none());
995    }
996
997    #[test]
998    fn typing_filters_case_insensitively_and_keeps_order() {
999        let mut state = fruits();
1000        assert!(state.update(Event::Input("B".into())).is_none());
1001        assert!(state.is_open());
1002        assert_eq!(matches(&state), ["Banana", "Blueberry"]);
1003        assert_eq!(state.highlighted(), Some(&"Banana"));
1004
1005        let _ = state.update(Event::Input("  ERR ".into()));
1006        assert_eq!(matches(&state), ["Blueberry", "Cherry"]);
1007    }
1008
1009    #[test]
1010    fn no_match_leaves_nothing_highlighted() {
1011        let mut state = fruits();
1012        let _ = state.update(Event::Input("kiwi".into()));
1013        assert!(state.matches().next().is_none());
1014        assert!(state.highlighted().is_none());
1015        assert!(state.update(Event::ActivateHighlighted).is_none());
1016        let _ = state.update(Event::Next);
1017        assert!(state.highlighted().is_none());
1018    }
1019
1020    #[test]
1021    fn arrows_open_then_wrap_round() {
1022        let mut state = fruits();
1023        let _ = state.update(Event::Next);
1024        assert!(state.is_open());
1025        assert_eq!(state.highlighted(), Some(&"Apple"));
1026
1027        let _ = state.update(Event::Previous);
1028        assert_eq!(state.highlighted(), Some(&"Grape"));
1029        let _ = state.update(Event::Next);
1030        assert_eq!(state.highlighted(), Some(&"Apple"));
1031    }
1032
1033    #[test]
1034    fn opening_highlights_the_selection() {
1035        let mut state = fruits().with_selected(&"Cherry");
1036        let _ = state.update(Event::Open);
1037        assert_eq!(state.highlighted(), Some(&"Cherry"));
1038    }
1039
1040    #[test]
1041    fn confirm_chooses_closes_and_clears_the_query() {
1042        let mut state = fruits();
1043        let _ = state.update(Event::Input("an".into()));
1044        assert_eq!(state.update(Event::ActivateHighlighted), Some("Banana"));
1045        assert!(!state.is_open());
1046        assert_eq!(state.query(), "");
1047        assert_eq!(state.selected(), Some(&"Banana"));
1048        assert_eq!(matches(&state).len(), FRUITS.len());
1049    }
1050
1051    #[test]
1052    fn confirm_does_nothing_while_closed() {
1053        let mut state = fruits();
1054        assert!(state.update(Event::ActivateHighlighted).is_none());
1055        assert!(state.selected().is_none());
1056    }
1057
1058    #[test]
1059    fn pick_and_highlight_use_option_indices() {
1060        let mut state = fruits();
1061        let _ = state.update(Event::Input("berry".into()));
1062        let _ = state.update(Event::Highlight(2));
1063        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1064        // Highlighting an option that does not match is ignored.
1065        let _ = state.update(Event::Highlight(0));
1066        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1067
1068        assert_eq!(state.update(Event::Activate(3)), Some("Cherry"));
1069        assert!(state.update(Event::Activate(99)).is_none());
1070        assert_eq!(state.selected(), Some(&"Cherry"));
1071    }
1072
1073    #[test]
1074    fn close_keeps_the_selection() {
1075        let mut state = fruits().with_selected(&"Apple");
1076        let _ = state.update(Event::Input("gr".into()));
1077        let _ = state.update(Event::Close);
1078        assert!(!state.is_open());
1079        assert_eq!(state.query(), "");
1080        assert_eq!(state.selected(), Some(&"Apple"));
1081    }
1082
1083    #[test]
1084    fn the_window_follows_the_highlight() {
1085        let mut state = fruits().with_visible_rows(2);
1086        let _ = state.update(Event::Open);
1087        let visible = |state: &State<&'static str>| -> Vec<&str> {
1088            state.visible().map(|(_, fruit)| *fruit).collect()
1089        };
1090        assert_eq!(visible(&state), ["Apple", "Banana"]);
1091
1092        let _ = state.update(Event::Next);
1093        let _ = state.update(Event::Next);
1094        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1095        assert_eq!(visible(&state), ["Banana", "Blueberry"]);
1096
1097        let _ = state.update(Event::Previous);
1098        let _ = state.update(Event::Previous);
1099        let _ = state.update(Event::Previous);
1100        assert_eq!(state.highlighted(), Some(&"Grape"));
1101        assert_eq!(visible(&state), ["Cherry", "Grape"]);
1102    }
1103
1104    #[test]
1105    fn scrolling_stays_within_the_matches() {
1106        let mut state = fruits().with_visible_rows(2);
1107        let _ = state.update(Event::Open);
1108        let _ = state.update(Event::Scroll(10));
1109        assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [3, 4]);
1110        let _ = state.update(Event::Scroll(-10));
1111        assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [0, 1]);
1112        assert_eq!(State::<&str>::new([]).with_visible_rows(0).list.rows, 1);
1113    }
1114
1115    #[test]
1116    fn empty_options_are_safe() {
1117        let mut state = State::<&str>::new([]);
1118        let _ = state.update(Event::Next);
1119        let _ = state.update(Event::Previous);
1120        let _ = state.update(Event::Scroll(3));
1121        assert!(state.update(Event::ActivateHighlighted).is_none());
1122        assert!(state.highlighted().is_none());
1123    }
1124
1125    #[test]
1126    fn default_keymap_and_overrides() {
1127        let keymap = default_keymap();
1128        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
1129        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
1130        assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
1131        assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
1132
1133        let custom = keymap
1134            .bind("Ctrl+N".parse().unwrap(), Action::Next)
1135            .unbind(&Chord::named(Named::Escape));
1136        assert_eq!(press(&custom, "ctrl+n"), Some(Action::Next));
1137        assert_eq!(press(&custom, "Escape"), None);
1138    }
1139
1140    #[test]
1141    fn actions_map_to_events_only_when_they_apply() {
1142        let mut state = fruits();
1143        assert_eq!(Action::Next.event(&state), Some(Event::Next));
1144        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
1145        assert_eq!(Action::Activate.event(&state), None);
1146        assert_eq!(Action::Close.event(&state), None);
1147
1148        let _ = state.update(Event::Open);
1149        assert_eq!(
1150            Action::Activate.event(&state),
1151            Some(Event::ActivateHighlighted)
1152        );
1153        assert_eq!(Action::Close.event(&state), Some(Event::Close));
1154    }
1155
1156    #[test]
1157    fn default_builder_is_disabled_with_the_default_empty_text() {
1158        let state = fruits();
1159        let c: Combobox<'_, &str, Event> = combobox(&state);
1160        assert!(!c.is_enabled());
1161        assert_eq!(c.empty, DEFAULT_EMPTY);
1162        assert_eq!(c.width, Length::Fixed(240.0));
1163        assert_eq!(c.size, Size::Md);
1164        assert_eq!(c.keymap, default_keymap());
1165        assert!(!c.invalid);
1166        let c = c
1167            .placeholder("Pick")
1168            .empty("None")
1169            .size(Size::Sm)
1170            .invalid(true)
1171            .on_event(|e| e);
1172        assert_eq!(c.size, Size::Sm);
1173        assert!(c.invalid);
1174        assert!(c.is_enabled());
1175        assert_eq!((c.placeholder.as_str(), c.empty.as_str()), ("Pick", "None"));
1176    }
1177
1178    const STATES: [Status; 5] = [
1179        Status::Active,
1180        Status::Hovered,
1181        Status::Focused { is_hovered: false },
1182        Status::Focused { is_hovered: true },
1183        Status::Disabled,
1184    ];
1185
1186    #[test]
1187    fn open_field_draws_the_focused_border() {
1188        for theme in [light(), dark()] {
1189            let tokens = Tokens::of(&theme);
1190            let focused = input::style(&tokens, Status::Focused { is_hovered: false }, false);
1191            for status in STATES {
1192                let closed = style(&tokens, status, false, false);
1193                assert_eq!(closed, input::style(&tokens, status, false), "{status:?}");
1194                let open = style(&tokens, status, true, false);
1195                if status != Status::Disabled {
1196                    assert_eq!(open.border.color, focused.border.color, "{status:?}");
1197                }
1198            }
1199        }
1200    }
1201
1202    #[test]
1203    fn disabled_field_uses_the_shared_disabled_background() {
1204        for theme in [light(), dark()] {
1205            let tokens = Tokens::of(&theme);
1206            for open in [false, true] {
1207                let disabled = style(&tokens, Status::Disabled, open, false);
1208                assert_eq!(
1209                    disabled.background,
1210                    iced::Background::Color(tokens.disabled_field())
1211                );
1212            }
1213        }
1214    }
1215
1216    #[test]
1217    fn invalid_field_uses_the_input_invalid_style() {
1218        for theme in [light(), dark()] {
1219            let tokens = Tokens::of(&theme);
1220            for status in STATES {
1221                assert_eq!(
1222                    style(&tokens, status, false, true),
1223                    input::style(&tokens, status, true),
1224                    "{status:?}"
1225                );
1226                let valid = style(&tokens, status, false, false);
1227                if status != Status::Disabled {
1228                    assert_ne!(
1229                        style(&tokens, status, false, true).border.color,
1230                        valid.border.color,
1231                        "{status:?}"
1232                    );
1233                }
1234            }
1235        }
1236    }
1237
1238    #[test]
1239    fn the_caret_moves_to_the_end_when_the_list_closes_or_the_pick_changes() {
1240        assert!(
1241            !moves_caret(None, (false, None)),
1242            "nothing to move on first layout"
1243        );
1244        assert!(moves_caret(Some((true, None)), (false, Some(2))), "a pick");
1245        assert!(
1246            moves_caret(Some((true, Some(2))), (false, Some(2))),
1247            "Escape"
1248        );
1249        assert!(
1250            moves_caret(Some((false, Some(1))), (false, Some(2))),
1251            "set by the app"
1252        );
1253        assert!(!moves_caret(Some((false, Some(2))), (false, Some(2))));
1254        assert!(!moves_caret(Some((false, None)), (true, None)), "opening");
1255        assert!(!moves_caret(Some((true, None)), (true, None)), "typing");
1256    }
1257}