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            let element: Element<'a, Message> = container(field).width(width).into();
590            #[cfg(feature = "icedwright")]
591            let element = annotate_field(
592                element,
593                Report {
594                    value,
595                    placeholder,
596                    open: false,
597                    enabled: false,
598                    invalid,
599                    list: None,
600                },
601                KIND,
602            );
603            return element;
604        };
605        let on_event: Rc<dyn Fn(Event) -> Message + 'a> = Rc::from(on_event);
606
607        let open = state.is_open();
608        let (value, hint) = if open {
609            (state.query().to_owned(), selected.unwrap_or(placeholder))
610        } else {
611            (selected.unwrap_or_default(), placeholder)
612        };
613
614        #[cfg(feature = "icedwright")]
615        let list_key = open.then(icedwright_probe::Key::unique);
616        let list = open.then(|| {
617            let chosen = state.selected;
618            suggestions(
619                &state.list,
620                &empty,
621                &move |index| chosen == Some(index),
622                &|event| on_event(list_event(event)),
623            )
624        });
625        #[cfg(feature = "icedwright")]
626        let list = list.map(|list| match &list_key {
627            Some(key) => annotate_list(list, key.clone(), KIND),
628            None => list,
629        });
630        let on_anchor_press = (!open).then(|| on_event(Event::Open));
631        let on_dismiss = open.then(|| on_event(Event::Close));
632        let editing = Editing {
633            on_input: {
634                let on_event = Rc::clone(&on_event);
635                Box::new(move |query| on_event(Event::Input(query)))
636            },
637            shortcuts,
638        };
639        let field =
640            container(field(&hint, &value, size, id, Some(editing), open, invalid)).width(width);
641        let field = Element::new(CaretToEnd {
642            content: field.into(),
643            watch: (open, state.selected),
644        });
645        #[cfg(feature = "icedwright")]
646        let field = annotate_field(
647            field,
648            Report {
649                value,
650                placeholder: hint,
651                open,
652                enabled: true,
653                invalid,
654                list: list_key,
655            },
656            KIND,
657        );
658
659        anchored(field)
660            .kind("iced_cube::combobox")
661            .content(list)
662            .placement(Placement::new(Side::Bottom, Align::Start))
663            .match_width(true)
664            .dismiss_keys([])
665            .dismiss_on_blur(true)
666            .on_dismiss_maybe(on_dismiss)
667            .on_anchor_press_maybe(on_anchor_press)
668            .on_key(move |key| {
669                keymap
670                    .resolve_event(key)
671                    .and_then(|action| action.event(state))
672                    .map(&*on_event)
673            })
674            .into()
675    }
676}
677
678/// What an enabled field does with edits.
679pub(crate) struct Editing<'a, Message> {
680    pub(crate) on_input: Box<dyn Fn(String) -> Message + 'a>,
681    pub(crate) shortcuts: Shortcuts,
682}
683
684/// The text field with its chevron, built with the shared input shortcuts.
685pub(crate) fn field<'a, Message: Clone + 'a>(
686    placeholder: &str,
687    value: &str,
688    size: Size,
689    id: Option<widget::Id>,
690    editing: Option<Editing<'a, Message>>,
691    open: bool,
692    invalid: bool,
693) -> Element<'a, Message> {
694    let enabled = editing.is_some();
695    let metrics = size.metrics();
696    let mut padding = metrics.padding(false);
697    padding.right += metrics.icon + space::SM;
698
699    let mut text = widget::text_input(placeholder, value)
700        .size(metrics.text)
701        .line_height(LineHeight::Relative(LINE_HEIGHT))
702        .padding(padding)
703        .width(Length::Fill)
704        .style(move |theme, status| style(&Tokens::of(theme), status, open, invalid));
705    if let Some(id) = id {
706        text = text.id(id);
707    }
708    let (on_input, shortcuts) = match editing {
709        Some(Editing {
710            on_input,
711            shortcuts,
712        }) => (Some(on_input), shortcuts),
713        None => (None, Shortcuts::none()),
714    };
715    let keymap = input::default_keymap();
716    let input = input::with_shortcuts(text, value, false, on_input, keymap, shortcuts);
717
718    let chevron = themed(
719        crate::lucide!(ChevronsUpDown),
720        metrics.icon,
721        opacity(enabled),
722        |theme| Tokens::of(theme).muted_foreground,
723    );
724
725    stack![
726        input,
727        container(chevron)
728            .width(Length::Fill)
729            .height(Length::Fill)
730            .align_x(Alignment::End)
731            .align_y(Alignment::Center)
732            .padding(Padding::ZERO.right(metrics.padding_x)),
733    ]
734    .into()
735}
736
737fn list_event(event: ListEvent) -> Event {
738    match event {
739        ListEvent::Highlight(index) => Event::Highlight(index),
740        ListEvent::Activate(index) => Event::Activate(index),
741        ListEvent::Scroll(rows) => Event::Scroll(rows),
742    }
743}
744
745/// The floating list of `list`'s visible matches, with a tick on the
746/// options for which `ticked` holds.
747pub(crate) fn suggestions<'a, T: Display, Message: Clone + 'a>(
748    list: &'a Suggestions<T>,
749    empty: &str,
750    ticked: &dyn Fn(usize) -> bool,
751    on_event: &dyn Fn(ListEvent) -> Message,
752) -> Element<'a, Message> {
753    let rows: Vec<Element<'a, Message>> = list
754        .visible()
755        .map(|(index, option)| {
756            let status = if list.is_highlighted(index) {
757                RowStatus::Highlighted
758            } else {
759                RowStatus::Idle
760            };
761            let label = option.to_string();
762            let trailing = if ticked(index) {
763                Trailing::Check
764            } else {
765                Trailing::None
766            };
767            let parts = Parts {
768                trailing,
769                ..Parts::label(&label)
770            };
771            let messages = (
772                on_event(ListEvent::Highlight(index)),
773                on_event(ListEvent::Activate(index)),
774            );
775            let row = menu::item(parts, status, false, Some(messages));
776            #[cfg(feature = "icedwright")]
777            let row = icedwright_probe::semantic(row)
778                .role(icedwright_probe::role::ListOption)
779                .name(label)
780                .selected(ticked(index))
781                .component("iced_cube::combobox")
782                .into();
783            row
784        })
785        .collect();
786
787    let body: Element<'a, Message> = if rows.is_empty() {
788        menu::empty(empty)
789    } else {
790        Column::from_vec(rows).width(Length::Fill).into()
791    };
792
793    let down = on_event(ListEvent::Scroll(1));
794    let up = on_event(ListEvent::Scroll(-1));
795    mouse_area(menu::surface(body).width(Length::Fill))
796        .on_scroll(move |delta| match delta {
797            ScrollDelta::Lines { y, .. } | ScrollDelta::Pixels { y, .. } if y < 0.0 => down.clone(),
798            _ => up.clone(),
799        })
800        .into()
801}
802
803#[cfg(feature = "icedwright")]
804const KIND: &str = "iced_cube::combobox";
805
806/// What a combobox field reports: its value, placeholder and whether its
807/// list is open.
808#[cfg(feature = "icedwright")]
809pub(crate) struct Report {
810    pub(crate) value: String,
811    pub(crate) placeholder: String,
812    pub(crate) open: bool,
813    pub(crate) enabled: bool,
814    pub(crate) invalid: bool,
815    /// The key of the open list, which the field owns.
816    pub(crate) list: Option<icedwright_probe::Key>,
817}
818
819/// Reports a combobox field.
820#[cfg(feature = "icedwright")]
821pub(crate) fn annotate_field<'a, Message: 'a>(
822    element: Element<'a, Message>,
823    report: Report,
824    kind: &'static str,
825) -> Element<'a, Message> {
826    use icedwright_probe::{role, semantic};
827    let mut annotated = semantic(element)
828        .role(role::ComboBox)
829        .value(report.value)
830        .expanded(report.open)
831        .component(kind);
832    if !report.placeholder.is_empty() {
833        annotated = annotated.placeholder(report.placeholder);
834    }
835    if !report.enabled {
836        annotated = annotated.disabled(true);
837    }
838    if report.invalid {
839        annotated = annotated.invalid(true);
840    }
841    if let Some(list) = report.list {
842        annotated = annotated.controls(list.clone()).owns(list);
843    }
844    annotated.into()
845}
846
847/// Reports an open list as a list box with `key`.
848#[cfg(feature = "icedwright")]
849pub(crate) fn annotate_list<'a, Message: 'a>(
850    element: Element<'a, Message>,
851    key: icedwright_probe::Key,
852    kind: &'static str,
853) -> Element<'a, Message> {
854    icedwright_probe::semantic(element)
855        .role(icedwright_probe::role::ListBox)
856        .key(key)
857        .component(kind)
858        .into()
859}
860
861/// The field style: the input style, drawn focused while the list is open
862/// and with the destructive border while `invalid`.
863pub fn style(tokens: &Tokens, status: Status, open: bool, invalid: bool) -> text_input::Style {
864    let status = match status {
865        Status::Active if open => Status::Focused { is_hovered: false },
866        Status::Hovered if open => Status::Focused { is_hovered: true },
867        status => status,
868    };
869    input::style(tokens, status, invalid)
870}
871
872/// Wraps the field and moves its caret to the end whenever the list closes
873/// or the selection changes, so a picked value reads from its end rather
874/// than from wherever the caret was in the query.
875struct CaretToEnd<'a, Message> {
876    content: Element<'a, Message>,
877    /// Whether the list is open, and the selected option.
878    watch: (bool, Option<usize>),
879}
880
881/// The caret goes to the end once the list is closed, if it just closed or
882/// the selection changed.
883fn moves_caret(before: Option<(bool, Option<usize>)>, now: (bool, Option<usize>)) -> bool {
884    let Some(before) = before else {
885        return false;
886    };
887    let (open, selected) = now;
888    !open && (before.0 || before.1 != selected)
889}
890
891struct MoveCaretToEnd;
892
893impl Operation for MoveCaretToEnd {
894    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
895        operate(self);
896    }
897
898    fn text_input(
899        &mut self,
900        _id: Option<&widget::Id>,
901        _bounds: iced::Rectangle,
902        state: &mut dyn operation::TextInput,
903    ) {
904        state.move_cursor_to_end();
905    }
906}
907
908impl<Message> Widget<Message, Theme, Renderer> for CaretToEnd<'_, Message> {
909    fn size(&self) -> iced::Size<Length> {
910        self.content.as_widget().size()
911    }
912
913    fn size_hint(&self) -> iced::Size<Length> {
914        self.content.as_widget().size_hint()
915    }
916
917    fn tag(&self) -> tree::Tag {
918        tree::Tag::of::<Option<(bool, Option<usize>)>>()
919    }
920
921    fn state(&self) -> tree::State {
922        tree::State::new(None::<(bool, Option<usize>)>)
923    }
924
925    fn children(&self) -> Vec<Tree> {
926        vec![Tree::new(&self.content)]
927    }
928
929    fn diff(&self, tree: &mut Tree) {
930        tree.diff_children(std::slice::from_ref(&self.content));
931    }
932
933    // Layout runs after every change to the view, before the next draw, so
934    // the caret moves without waiting for another event.
935    fn layout(
936        &mut self,
937        tree: &mut Tree,
938        renderer: &Renderer,
939        limits: &layout::Limits,
940    ) -> layout::Node {
941        let node = self
942            .content
943            .as_widget_mut()
944            .layout(&mut tree.children[0], renderer, limits);
945        let seen = tree.state.downcast_mut::<Option<(bool, Option<usize>)>>();
946        let before = seen.replace(self.watch);
947        if moves_caret(before, self.watch) {
948            self.content.as_widget_mut().operate(
949                &mut tree.children[0],
950                Layout::new(&node),
951                renderer,
952                &mut MoveCaretToEnd,
953            );
954        }
955        node
956    }
957
958    fn draw(
959        &self,
960        tree: &Tree,
961        renderer: &mut Renderer,
962        theme: &Theme,
963        style: &renderer::Style,
964        layout: Layout<'_>,
965        cursor: mouse::Cursor,
966        viewport: &iced::Rectangle,
967    ) {
968        self.content.as_widget().draw(
969            &tree.children[0],
970            renderer,
971            theme,
972            style,
973            layout,
974            cursor,
975            viewport,
976        );
977    }
978
979    fn operate(
980        &mut self,
981        tree: &mut Tree,
982        layout: Layout<'_>,
983        renderer: &Renderer,
984        operation: &mut dyn Operation,
985    ) {
986        self.content
987            .as_widget_mut()
988            .operate(&mut tree.children[0], layout, renderer, operation);
989    }
990
991    fn update(
992        &mut self,
993        tree: &mut Tree,
994        event: &iced::Event,
995        layout: Layout<'_>,
996        cursor: mouse::Cursor,
997        renderer: &Renderer,
998        clipboard: &mut dyn Clipboard,
999        shell: &mut Shell<'_, Message>,
1000        viewport: &iced::Rectangle,
1001    ) {
1002        self.content.as_widget_mut().update(
1003            &mut tree.children[0],
1004            event,
1005            layout,
1006            cursor,
1007            renderer,
1008            clipboard,
1009            shell,
1010            viewport,
1011        );
1012    }
1013
1014    fn mouse_interaction(
1015        &self,
1016        tree: &Tree,
1017        layout: Layout<'_>,
1018        cursor: mouse::Cursor,
1019        viewport: &iced::Rectangle,
1020        renderer: &Renderer,
1021    ) -> mouse::Interaction {
1022        self.content.as_widget().mouse_interaction(
1023            &tree.children[0],
1024            layout,
1025            cursor,
1026            viewport,
1027            renderer,
1028        )
1029    }
1030
1031    fn overlay<'b>(
1032        &'b mut self,
1033        tree: &'b mut Tree,
1034        layout: Layout<'b>,
1035        renderer: &Renderer,
1036        viewport: &iced::Rectangle,
1037        translation: iced::Vector,
1038    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1039        self.content.as_widget_mut().overlay(
1040            &mut tree.children[0],
1041            layout,
1042            renderer,
1043            viewport,
1044            translation,
1045        )
1046    }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051    use super::*;
1052    use crate::theme::{dark, light};
1053
1054    const FRUITS: [&str; 5] = ["Apple", "Banana", "Blueberry", "Cherry", "Grape"];
1055
1056    fn fruits() -> State<&'static str> {
1057        State::new(FRUITS)
1058    }
1059
1060    fn matches(state: &State<&'static str>) -> Vec<&'static str> {
1061        state.matches().copied().collect()
1062    }
1063
1064    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1065        let chord: Chord = chord.parse().unwrap();
1066        keymap.resolve(chord.key(), chord.modifiers())
1067    }
1068
1069    #[test]
1070    fn new_state_is_closed_with_every_option() {
1071        let state = fruits();
1072        assert!(!state.is_open());
1073        assert!(state.selected().is_none());
1074        assert_eq!(state.query(), "");
1075        assert_eq!(matches(&state), FRUITS);
1076        assert_eq!(state.visible().count(), 5);
1077    }
1078
1079    #[test]
1080    fn with_selected_ignores_unknown_values() {
1081        assert_eq!(
1082            fruits().with_selected(&"Cherry").selected(),
1083            Some(&"Cherry")
1084        );
1085        assert!(fruits().with_selected(&"Kiwi").selected().is_none());
1086    }
1087
1088    #[test]
1089    fn typing_filters_case_insensitively_and_keeps_order() {
1090        let mut state = fruits();
1091        assert!(state.update(Event::Input("B".into())).is_none());
1092        assert!(state.is_open());
1093        assert_eq!(matches(&state), ["Banana", "Blueberry"]);
1094        assert_eq!(state.highlighted(), Some(&"Banana"));
1095
1096        let _ = state.update(Event::Input("  ERR ".into()));
1097        assert_eq!(matches(&state), ["Blueberry", "Cherry"]);
1098    }
1099
1100    #[test]
1101    fn no_match_leaves_nothing_highlighted() {
1102        let mut state = fruits();
1103        let _ = state.update(Event::Input("kiwi".into()));
1104        assert!(state.matches().next().is_none());
1105        assert!(state.highlighted().is_none());
1106        assert!(state.update(Event::ActivateHighlighted).is_none());
1107        let _ = state.update(Event::Next);
1108        assert!(state.highlighted().is_none());
1109    }
1110
1111    #[test]
1112    fn arrows_open_then_wrap_round() {
1113        let mut state = fruits();
1114        let _ = state.update(Event::Next);
1115        assert!(state.is_open());
1116        assert_eq!(state.highlighted(), Some(&"Apple"));
1117
1118        let _ = state.update(Event::Previous);
1119        assert_eq!(state.highlighted(), Some(&"Grape"));
1120        let _ = state.update(Event::Next);
1121        assert_eq!(state.highlighted(), Some(&"Apple"));
1122    }
1123
1124    #[test]
1125    fn opening_highlights_the_selection() {
1126        let mut state = fruits().with_selected(&"Cherry");
1127        let _ = state.update(Event::Open);
1128        assert_eq!(state.highlighted(), Some(&"Cherry"));
1129    }
1130
1131    #[test]
1132    fn confirm_chooses_closes_and_clears_the_query() {
1133        let mut state = fruits();
1134        let _ = state.update(Event::Input("an".into()));
1135        assert_eq!(state.update(Event::ActivateHighlighted), Some("Banana"));
1136        assert!(!state.is_open());
1137        assert_eq!(state.query(), "");
1138        assert_eq!(state.selected(), Some(&"Banana"));
1139        assert_eq!(matches(&state).len(), FRUITS.len());
1140    }
1141
1142    #[test]
1143    fn confirm_does_nothing_while_closed() {
1144        let mut state = fruits();
1145        assert!(state.update(Event::ActivateHighlighted).is_none());
1146        assert!(state.selected().is_none());
1147    }
1148
1149    #[test]
1150    fn pick_and_highlight_use_option_indices() {
1151        let mut state = fruits();
1152        let _ = state.update(Event::Input("berry".into()));
1153        let _ = state.update(Event::Highlight(2));
1154        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1155        // Highlighting an option that does not match is ignored.
1156        let _ = state.update(Event::Highlight(0));
1157        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1158
1159        assert_eq!(state.update(Event::Activate(3)), Some("Cherry"));
1160        assert!(state.update(Event::Activate(99)).is_none());
1161        assert_eq!(state.selected(), Some(&"Cherry"));
1162    }
1163
1164    #[test]
1165    fn close_keeps_the_selection() {
1166        let mut state = fruits().with_selected(&"Apple");
1167        let _ = state.update(Event::Input("gr".into()));
1168        let _ = state.update(Event::Close);
1169        assert!(!state.is_open());
1170        assert_eq!(state.query(), "");
1171        assert_eq!(state.selected(), Some(&"Apple"));
1172    }
1173
1174    #[test]
1175    fn the_window_follows_the_highlight() {
1176        let mut state = fruits().with_visible_rows(2);
1177        let _ = state.update(Event::Open);
1178        let visible = |state: &State<&'static str>| -> Vec<&str> {
1179            state.visible().map(|(_, fruit)| *fruit).collect()
1180        };
1181        assert_eq!(visible(&state), ["Apple", "Banana"]);
1182
1183        let _ = state.update(Event::Next);
1184        let _ = state.update(Event::Next);
1185        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1186        assert_eq!(visible(&state), ["Banana", "Blueberry"]);
1187
1188        let _ = state.update(Event::Previous);
1189        let _ = state.update(Event::Previous);
1190        let _ = state.update(Event::Previous);
1191        assert_eq!(state.highlighted(), Some(&"Grape"));
1192        assert_eq!(visible(&state), ["Cherry", "Grape"]);
1193    }
1194
1195    #[test]
1196    fn scrolling_stays_within_the_matches() {
1197        let mut state = fruits().with_visible_rows(2);
1198        let _ = state.update(Event::Open);
1199        let _ = state.update(Event::Scroll(10));
1200        assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [3, 4]);
1201        let _ = state.update(Event::Scroll(-10));
1202        assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [0, 1]);
1203        assert_eq!(State::<&str>::new([]).with_visible_rows(0).list.rows, 1);
1204    }
1205
1206    #[test]
1207    fn empty_options_are_safe() {
1208        let mut state = State::<&str>::new([]);
1209        let _ = state.update(Event::Next);
1210        let _ = state.update(Event::Previous);
1211        let _ = state.update(Event::Scroll(3));
1212        assert!(state.update(Event::ActivateHighlighted).is_none());
1213        assert!(state.highlighted().is_none());
1214    }
1215
1216    #[test]
1217    fn default_keymap_and_overrides() {
1218        let keymap = default_keymap();
1219        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
1220        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
1221        assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
1222        assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
1223
1224        let custom = keymap
1225            .bind("Ctrl+N".parse().unwrap(), Action::Next)
1226            .unbind(&Chord::named(Named::Escape));
1227        assert_eq!(press(&custom, "ctrl+n"), Some(Action::Next));
1228        assert_eq!(press(&custom, "Escape"), None);
1229    }
1230
1231    #[test]
1232    fn actions_map_to_events_only_when_they_apply() {
1233        let mut state = fruits();
1234        assert_eq!(Action::Next.event(&state), Some(Event::Next));
1235        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
1236        assert_eq!(Action::Activate.event(&state), None);
1237        assert_eq!(Action::Close.event(&state), None);
1238
1239        let _ = state.update(Event::Open);
1240        assert_eq!(
1241            Action::Activate.event(&state),
1242            Some(Event::ActivateHighlighted)
1243        );
1244        assert_eq!(Action::Close.event(&state), Some(Event::Close));
1245    }
1246
1247    #[test]
1248    fn default_builder_is_disabled_with_the_default_empty_text() {
1249        let state = fruits();
1250        let c: Combobox<'_, &str, Event> = combobox(&state);
1251        assert!(!c.is_enabled());
1252        assert_eq!(c.empty, DEFAULT_EMPTY);
1253        assert_eq!(c.width, Length::Fixed(240.0));
1254        assert_eq!(c.size, Size::Md);
1255        assert_eq!(c.keymap, default_keymap());
1256        assert!(!c.invalid);
1257        let c = c
1258            .placeholder("Pick")
1259            .empty("None")
1260            .size(Size::Sm)
1261            .invalid(true)
1262            .on_event(|e| e);
1263        assert_eq!(c.size, Size::Sm);
1264        assert!(c.invalid);
1265        assert!(c.is_enabled());
1266        assert_eq!((c.placeholder.as_str(), c.empty.as_str()), ("Pick", "None"));
1267    }
1268
1269    const STATES: [Status; 5] = [
1270        Status::Active,
1271        Status::Hovered,
1272        Status::Focused { is_hovered: false },
1273        Status::Focused { is_hovered: true },
1274        Status::Disabled,
1275    ];
1276
1277    #[test]
1278    fn open_field_draws_the_focused_border() {
1279        for theme in [light(), dark()] {
1280            let tokens = Tokens::of(&theme);
1281            let focused = input::style(&tokens, Status::Focused { is_hovered: false }, false);
1282            for status in STATES {
1283                let closed = style(&tokens, status, false, false);
1284                assert_eq!(closed, input::style(&tokens, status, false), "{status:?}");
1285                let open = style(&tokens, status, true, false);
1286                if status != Status::Disabled {
1287                    assert_eq!(open.border.color, focused.border.color, "{status:?}");
1288                }
1289            }
1290        }
1291    }
1292
1293    #[test]
1294    fn disabled_field_uses_the_shared_disabled_background() {
1295        for theme in [light(), dark()] {
1296            let tokens = Tokens::of(&theme);
1297            for open in [false, true] {
1298                let disabled = style(&tokens, Status::Disabled, open, false);
1299                assert_eq!(
1300                    disabled.background,
1301                    iced::Background::Color(tokens.disabled_field())
1302                );
1303            }
1304        }
1305    }
1306
1307    #[test]
1308    fn invalid_field_uses_the_input_invalid_style() {
1309        for theme in [light(), dark()] {
1310            let tokens = Tokens::of(&theme);
1311            for status in STATES {
1312                assert_eq!(
1313                    style(&tokens, status, false, true),
1314                    input::style(&tokens, status, true),
1315                    "{status:?}"
1316                );
1317                let valid = style(&tokens, status, false, false);
1318                if status != Status::Disabled {
1319                    assert_ne!(
1320                        style(&tokens, status, false, true).border.color,
1321                        valid.border.color,
1322                        "{status:?}"
1323                    );
1324                }
1325            }
1326        }
1327    }
1328
1329    #[test]
1330    fn the_caret_moves_to_the_end_when_the_list_closes_or_the_pick_changes() {
1331        assert!(
1332            !moves_caret(None, (false, None)),
1333            "nothing to move on first layout"
1334        );
1335        assert!(moves_caret(Some((true, None)), (false, Some(2))), "a pick");
1336        assert!(
1337            moves_caret(Some((true, Some(2))), (false, Some(2))),
1338            "Escape"
1339        );
1340        assert!(
1341            moves_caret(Some((false, Some(1))), (false, Some(2))),
1342            "set by the app"
1343        );
1344        assert!(!moves_caret(Some((false, Some(2))), (false, Some(2))));
1345        assert!(!moves_caret(Some((false, None)), (true, None)), "opening");
1346        assert!(!moves_caret(Some((true, None)), (true, None)), "typing");
1347    }
1348}