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