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                .disabled(false)
782                .component("iced_cube::combobox")
783                .into();
784            row
785        })
786        .collect();
787
788    let body: Element<'a, Message> = if rows.is_empty() {
789        menu::empty(empty)
790    } else {
791        Column::from_vec(rows).width(Length::Fill).into()
792    };
793
794    let down = on_event(ListEvent::Scroll(1));
795    let up = on_event(ListEvent::Scroll(-1));
796    mouse_area(menu::surface(body).width(Length::Fill))
797        .on_scroll(move |delta| match delta {
798            ScrollDelta::Lines { y, .. } | ScrollDelta::Pixels { y, .. } if y < 0.0 => down.clone(),
799            _ => up.clone(),
800        })
801        .into()
802}
803
804#[cfg(feature = "icedwright")]
805const KIND: &str = "iced_cube::combobox";
806
807/// What a combobox field reports: its value, placeholder and whether its
808/// list is open.
809#[cfg(feature = "icedwright")]
810pub(crate) struct Report {
811    pub(crate) value: String,
812    pub(crate) placeholder: String,
813    pub(crate) open: bool,
814    pub(crate) enabled: bool,
815    pub(crate) invalid: bool,
816    /// The key of the open list, which the field owns.
817    pub(crate) list: Option<icedwright_probe::Key>,
818}
819
820/// Reports a combobox field.
821#[cfg(feature = "icedwright")]
822pub(crate) fn annotate_field<'a, Message: 'a>(
823    element: Element<'a, Message>,
824    report: Report,
825    kind: &'static str,
826) -> Element<'a, Message> {
827    use icedwright_probe::{role, semantic};
828    let mut annotated = semantic(element)
829        .role(role::ComboBox)
830        .value(report.value)
831        .expanded(report.open)
832        .disabled(!report.enabled)
833        .component(kind);
834    if !report.placeholder.is_empty() {
835        annotated = annotated.placeholder(report.placeholder);
836    }
837    if report.invalid {
838        annotated = annotated.invalid(true);
839    }
840    if let Some(list) = report.list {
841        annotated = annotated.controls(list.clone()).owns(list);
842    }
843    annotated.into()
844}
845
846/// Reports an open list as a list box with `key`.
847#[cfg(feature = "icedwright")]
848pub(crate) fn annotate_list<'a, Message: 'a>(
849    element: Element<'a, Message>,
850    key: icedwright_probe::Key,
851    kind: &'static str,
852) -> Element<'a, Message> {
853    icedwright_probe::semantic(element)
854        .role(icedwright_probe::role::ListBox)
855        .key(key)
856        .component(kind)
857        .into()
858}
859
860/// The field style: the input style, drawn focused while the list is open
861/// and with the destructive border while `invalid`.
862pub fn style(tokens: &Tokens, status: Status, open: bool, invalid: bool) -> text_input::Style {
863    let status = match status {
864        Status::Active if open => Status::Focused { is_hovered: false },
865        Status::Hovered if open => Status::Focused { is_hovered: true },
866        status => status,
867    };
868    input::style(tokens, status, invalid)
869}
870
871/// Wraps the field and moves its caret to the end whenever the list closes
872/// or the selection changes, so a picked value reads from its end rather
873/// than from wherever the caret was in the query.
874struct CaretToEnd<'a, Message> {
875    content: Element<'a, Message>,
876    /// Whether the list is open, and the selected option.
877    watch: (bool, Option<usize>),
878}
879
880/// The caret goes to the end once the list is closed, if it just closed or
881/// the selection changed.
882fn moves_caret(before: Option<(bool, Option<usize>)>, now: (bool, Option<usize>)) -> bool {
883    let Some(before) = before else {
884        return false;
885    };
886    let (open, selected) = now;
887    !open && (before.0 || before.1 != selected)
888}
889
890struct MoveCaretToEnd;
891
892impl Operation for MoveCaretToEnd {
893    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
894        operate(self);
895    }
896
897    fn text_input(
898        &mut self,
899        _id: Option<&widget::Id>,
900        _bounds: iced::Rectangle,
901        state: &mut dyn operation::TextInput,
902    ) {
903        state.move_cursor_to_end();
904    }
905}
906
907impl<Message> Widget<Message, Theme, Renderer> for CaretToEnd<'_, Message> {
908    fn size(&self) -> iced::Size<Length> {
909        self.content.as_widget().size()
910    }
911
912    fn size_hint(&self) -> iced::Size<Length> {
913        self.content.as_widget().size_hint()
914    }
915
916    fn tag(&self) -> tree::Tag {
917        tree::Tag::of::<Option<(bool, Option<usize>)>>()
918    }
919
920    fn state(&self) -> tree::State {
921        tree::State::new(None::<(bool, Option<usize>)>)
922    }
923
924    fn children(&self) -> Vec<Tree> {
925        vec![Tree::new(&self.content)]
926    }
927
928    fn diff(&self, tree: &mut Tree) {
929        tree.diff_children(std::slice::from_ref(&self.content));
930    }
931
932    // Layout runs after every change to the view, before the next draw, so
933    // the caret moves without waiting for another event.
934    fn layout(
935        &mut self,
936        tree: &mut Tree,
937        renderer: &Renderer,
938        limits: &layout::Limits,
939    ) -> layout::Node {
940        let node = self
941            .content
942            .as_widget_mut()
943            .layout(&mut tree.children[0], renderer, limits);
944        let seen = tree.state.downcast_mut::<Option<(bool, Option<usize>)>>();
945        let before = seen.replace(self.watch);
946        if moves_caret(before, self.watch) {
947            self.content.as_widget_mut().operate(
948                &mut tree.children[0],
949                Layout::new(&node),
950                renderer,
951                &mut MoveCaretToEnd,
952            );
953        }
954        node
955    }
956
957    fn draw(
958        &self,
959        tree: &Tree,
960        renderer: &mut Renderer,
961        theme: &Theme,
962        style: &renderer::Style,
963        layout: Layout<'_>,
964        cursor: mouse::Cursor,
965        viewport: &iced::Rectangle,
966    ) {
967        self.content.as_widget().draw(
968            &tree.children[0],
969            renderer,
970            theme,
971            style,
972            layout,
973            cursor,
974            viewport,
975        );
976    }
977
978    fn operate(
979        &mut self,
980        tree: &mut Tree,
981        layout: Layout<'_>,
982        renderer: &Renderer,
983        operation: &mut dyn Operation,
984    ) {
985        self.content
986            .as_widget_mut()
987            .operate(&mut tree.children[0], layout, renderer, operation);
988    }
989
990    fn update(
991        &mut self,
992        tree: &mut Tree,
993        event: &iced::Event,
994        layout: Layout<'_>,
995        cursor: mouse::Cursor,
996        renderer: &Renderer,
997        clipboard: &mut dyn Clipboard,
998        shell: &mut Shell<'_, Message>,
999        viewport: &iced::Rectangle,
1000    ) {
1001        self.content.as_widget_mut().update(
1002            &mut tree.children[0],
1003            event,
1004            layout,
1005            cursor,
1006            renderer,
1007            clipboard,
1008            shell,
1009            viewport,
1010        );
1011    }
1012
1013    fn mouse_interaction(
1014        &self,
1015        tree: &Tree,
1016        layout: Layout<'_>,
1017        cursor: mouse::Cursor,
1018        viewport: &iced::Rectangle,
1019        renderer: &Renderer,
1020    ) -> mouse::Interaction {
1021        self.content.as_widget().mouse_interaction(
1022            &tree.children[0],
1023            layout,
1024            cursor,
1025            viewport,
1026            renderer,
1027        )
1028    }
1029
1030    fn overlay<'b>(
1031        &'b mut self,
1032        tree: &'b mut Tree,
1033        layout: Layout<'b>,
1034        renderer: &Renderer,
1035        viewport: &iced::Rectangle,
1036        translation: iced::Vector,
1037    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1038        self.content.as_widget_mut().overlay(
1039            &mut tree.children[0],
1040            layout,
1041            renderer,
1042            viewport,
1043            translation,
1044        )
1045    }
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050    use super::*;
1051    use crate::theme::{dark, light};
1052
1053    const FRUITS: [&str; 5] = ["Apple", "Banana", "Blueberry", "Cherry", "Grape"];
1054
1055    fn fruits() -> State<&'static str> {
1056        State::new(FRUITS)
1057    }
1058
1059    fn matches(state: &State<&'static str>) -> Vec<&'static str> {
1060        state.matches().copied().collect()
1061    }
1062
1063    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1064        let chord: Chord = chord.parse().unwrap();
1065        keymap.resolve(chord.key(), chord.modifiers())
1066    }
1067
1068    #[test]
1069    fn new_state_is_closed_with_every_option() {
1070        let state = fruits();
1071        assert!(!state.is_open());
1072        assert!(state.selected().is_none());
1073        assert_eq!(state.query(), "");
1074        assert_eq!(matches(&state), FRUITS);
1075        assert_eq!(state.visible().count(), 5);
1076    }
1077
1078    #[test]
1079    fn with_selected_ignores_unknown_values() {
1080        assert_eq!(
1081            fruits().with_selected(&"Cherry").selected(),
1082            Some(&"Cherry")
1083        );
1084        assert!(fruits().with_selected(&"Kiwi").selected().is_none());
1085    }
1086
1087    #[test]
1088    fn typing_filters_case_insensitively_and_keeps_order() {
1089        let mut state = fruits();
1090        assert!(state.update(Event::Input("B".into())).is_none());
1091        assert!(state.is_open());
1092        assert_eq!(matches(&state), ["Banana", "Blueberry"]);
1093        assert_eq!(state.highlighted(), Some(&"Banana"));
1094
1095        let _ = state.update(Event::Input("  ERR ".into()));
1096        assert_eq!(matches(&state), ["Blueberry", "Cherry"]);
1097    }
1098
1099    #[test]
1100    fn no_match_leaves_nothing_highlighted() {
1101        let mut state = fruits();
1102        let _ = state.update(Event::Input("kiwi".into()));
1103        assert!(state.matches().next().is_none());
1104        assert!(state.highlighted().is_none());
1105        assert!(state.update(Event::ActivateHighlighted).is_none());
1106        let _ = state.update(Event::Next);
1107        assert!(state.highlighted().is_none());
1108    }
1109
1110    #[test]
1111    fn arrows_open_then_wrap_round() {
1112        let mut state = fruits();
1113        let _ = state.update(Event::Next);
1114        assert!(state.is_open());
1115        assert_eq!(state.highlighted(), Some(&"Apple"));
1116
1117        let _ = state.update(Event::Previous);
1118        assert_eq!(state.highlighted(), Some(&"Grape"));
1119        let _ = state.update(Event::Next);
1120        assert_eq!(state.highlighted(), Some(&"Apple"));
1121    }
1122
1123    #[test]
1124    fn opening_highlights_the_selection() {
1125        let mut state = fruits().with_selected(&"Cherry");
1126        let _ = state.update(Event::Open);
1127        assert_eq!(state.highlighted(), Some(&"Cherry"));
1128    }
1129
1130    #[test]
1131    fn confirm_chooses_closes_and_clears_the_query() {
1132        let mut state = fruits();
1133        let _ = state.update(Event::Input("an".into()));
1134        assert_eq!(state.update(Event::ActivateHighlighted), Some("Banana"));
1135        assert!(!state.is_open());
1136        assert_eq!(state.query(), "");
1137        assert_eq!(state.selected(), Some(&"Banana"));
1138        assert_eq!(matches(&state).len(), FRUITS.len());
1139    }
1140
1141    #[test]
1142    fn confirm_does_nothing_while_closed() {
1143        let mut state = fruits();
1144        assert!(state.update(Event::ActivateHighlighted).is_none());
1145        assert!(state.selected().is_none());
1146    }
1147
1148    #[test]
1149    fn pick_and_highlight_use_option_indices() {
1150        let mut state = fruits();
1151        let _ = state.update(Event::Input("berry".into()));
1152        let _ = state.update(Event::Highlight(2));
1153        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1154        // Highlighting an option that does not match is ignored.
1155        let _ = state.update(Event::Highlight(0));
1156        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1157
1158        assert_eq!(state.update(Event::Activate(3)), Some("Cherry"));
1159        assert!(state.update(Event::Activate(99)).is_none());
1160        assert_eq!(state.selected(), Some(&"Cherry"));
1161    }
1162
1163    #[test]
1164    fn close_keeps_the_selection() {
1165        let mut state = fruits().with_selected(&"Apple");
1166        let _ = state.update(Event::Input("gr".into()));
1167        let _ = state.update(Event::Close);
1168        assert!(!state.is_open());
1169        assert_eq!(state.query(), "");
1170        assert_eq!(state.selected(), Some(&"Apple"));
1171    }
1172
1173    #[test]
1174    fn the_window_follows_the_highlight() {
1175        let mut state = fruits().with_visible_rows(2);
1176        let _ = state.update(Event::Open);
1177        let visible = |state: &State<&'static str>| -> Vec<&str> {
1178            state.visible().map(|(_, fruit)| *fruit).collect()
1179        };
1180        assert_eq!(visible(&state), ["Apple", "Banana"]);
1181
1182        let _ = state.update(Event::Next);
1183        let _ = state.update(Event::Next);
1184        assert_eq!(state.highlighted(), Some(&"Blueberry"));
1185        assert_eq!(visible(&state), ["Banana", "Blueberry"]);
1186
1187        let _ = state.update(Event::Previous);
1188        let _ = state.update(Event::Previous);
1189        let _ = state.update(Event::Previous);
1190        assert_eq!(state.highlighted(), Some(&"Grape"));
1191        assert_eq!(visible(&state), ["Cherry", "Grape"]);
1192    }
1193
1194    #[test]
1195    fn scrolling_stays_within_the_matches() {
1196        let mut state = fruits().with_visible_rows(2);
1197        let _ = state.update(Event::Open);
1198        let _ = state.update(Event::Scroll(10));
1199        assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [3, 4]);
1200        let _ = state.update(Event::Scroll(-10));
1201        assert_eq!(state.visible().map(|(i, _)| i).collect::<Vec<_>>(), [0, 1]);
1202        assert_eq!(State::<&str>::new([]).with_visible_rows(0).list.rows, 1);
1203    }
1204
1205    #[test]
1206    fn empty_options_are_safe() {
1207        let mut state = State::<&str>::new([]);
1208        let _ = state.update(Event::Next);
1209        let _ = state.update(Event::Previous);
1210        let _ = state.update(Event::Scroll(3));
1211        assert!(state.update(Event::ActivateHighlighted).is_none());
1212        assert!(state.highlighted().is_none());
1213    }
1214
1215    #[test]
1216    fn default_keymap_and_overrides() {
1217        let keymap = default_keymap();
1218        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
1219        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
1220        assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
1221        assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
1222
1223        let custom = keymap
1224            .bind("Ctrl+N".parse().unwrap(), Action::Next)
1225            .unbind(&Chord::named(Named::Escape));
1226        assert_eq!(press(&custom, "ctrl+n"), Some(Action::Next));
1227        assert_eq!(press(&custom, "Escape"), None);
1228    }
1229
1230    #[test]
1231    fn actions_map_to_events_only_when_they_apply() {
1232        let mut state = fruits();
1233        assert_eq!(Action::Next.event(&state), Some(Event::Next));
1234        assert_eq!(Action::Previous.event(&state), Some(Event::Previous));
1235        assert_eq!(Action::Activate.event(&state), None);
1236        assert_eq!(Action::Close.event(&state), None);
1237
1238        let _ = state.update(Event::Open);
1239        assert_eq!(
1240            Action::Activate.event(&state),
1241            Some(Event::ActivateHighlighted)
1242        );
1243        assert_eq!(Action::Close.event(&state), Some(Event::Close));
1244    }
1245
1246    #[test]
1247    fn default_builder_is_disabled_with_the_default_empty_text() {
1248        let state = fruits();
1249        let c: Combobox<'_, &str, Event> = combobox(&state);
1250        assert!(!c.is_enabled());
1251        assert_eq!(c.empty, DEFAULT_EMPTY);
1252        assert_eq!(c.width, Length::Fixed(240.0));
1253        assert_eq!(c.size, Size::Md);
1254        assert_eq!(c.keymap, default_keymap());
1255        assert!(!c.invalid);
1256        let c = c
1257            .placeholder("Pick")
1258            .empty("None")
1259            .size(Size::Sm)
1260            .invalid(true)
1261            .on_event(|e| e);
1262        assert_eq!(c.size, Size::Sm);
1263        assert!(c.invalid);
1264        assert!(c.is_enabled());
1265        assert_eq!((c.placeholder.as_str(), c.empty.as_str()), ("Pick", "None"));
1266    }
1267
1268    const STATES: [Status; 5] = [
1269        Status::Active,
1270        Status::Hovered,
1271        Status::Focused { is_hovered: false },
1272        Status::Focused { is_hovered: true },
1273        Status::Disabled,
1274    ];
1275
1276    #[test]
1277    fn open_field_draws_the_focused_border() {
1278        for theme in [light(), dark()] {
1279            let tokens = Tokens::of(&theme);
1280            let focused = input::style(&tokens, Status::Focused { is_hovered: false }, false);
1281            for status in STATES {
1282                let closed = style(&tokens, status, false, false);
1283                assert_eq!(closed, input::style(&tokens, status, false), "{status:?}");
1284                let open = style(&tokens, status, true, false);
1285                if status != Status::Disabled {
1286                    assert_eq!(open.border.color, focused.border.color, "{status:?}");
1287                }
1288            }
1289        }
1290    }
1291
1292    #[test]
1293    fn disabled_field_uses_the_shared_disabled_background() {
1294        for theme in [light(), dark()] {
1295            let tokens = Tokens::of(&theme);
1296            for open in [false, true] {
1297                let disabled = style(&tokens, Status::Disabled, open, false);
1298                assert_eq!(
1299                    disabled.background,
1300                    iced::Background::Color(tokens.disabled_field())
1301                );
1302            }
1303        }
1304    }
1305
1306    #[test]
1307    fn invalid_field_uses_the_input_invalid_style() {
1308        for theme in [light(), dark()] {
1309            let tokens = Tokens::of(&theme);
1310            for status in STATES {
1311                assert_eq!(
1312                    style(&tokens, status, false, true),
1313                    input::style(&tokens, status, true),
1314                    "{status:?}"
1315                );
1316                let valid = style(&tokens, status, false, false);
1317                if status != Status::Disabled {
1318                    assert_ne!(
1319                        style(&tokens, status, false, true).border.color,
1320                        valid.border.color,
1321                        "{status:?}"
1322                    );
1323                }
1324            }
1325        }
1326    }
1327
1328    #[test]
1329    fn the_caret_moves_to_the_end_when_the_list_closes_or_the_pick_changes() {
1330        assert!(
1331            !moves_caret(None, (false, None)),
1332            "nothing to move on first layout"
1333        );
1334        assert!(moves_caret(Some((true, None)), (false, Some(2))), "a pick");
1335        assert!(
1336            moves_caret(Some((true, Some(2))), (false, Some(2))),
1337            "Escape"
1338        );
1339        assert!(
1340            moves_caret(Some((false, Some(1))), (false, Some(2))),
1341            "set by the app"
1342        );
1343        assert!(!moves_caret(Some((false, Some(2))), (false, Some(2))));
1344        assert!(!moves_caret(Some((false, None)), (true, None)), "opening");
1345        assert!(!moves_caret(Some((true, None)), (true, None)), "typing");
1346    }
1347}