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