Skip to main content

iced_cube/navigation/
command.rs

1//! A searchable list of actions: a search field over grouped results.
2//!
3//! [`State`] holds the groups of [`Item`]s, the query and the highlighted
4//! row. Typing ranks the items with [`score`], a case-insensitive fuzzy
5//! match that prefers prefixes and word starts, and checks each item's
6//! keywords too. [`State::update`] returns an [`Output`] when an item is
7//! activated or the query changes.
8//!
9//! While the search field has focus, the list handles its own keys through
10//! a [`Keymap`] of [`Action`]s, before anything around it sees them; see
11//! [`default_keymap`]. Inside a dialog or popover, Escape first clears the
12//! query, and only then returns [`Output::Closed`] for the app to close
13//! whatever holds the list. Rows use the shared
14//! [menu look](crate::overlay::menu).
15//!
16//! Results can also arrive from background work. [`subscription`] owns a
17//! bounded channel and emits [`Event::Ready`] with its [`Sender`] first.
18//! When the query changes, `update` returns [`Output::Search`]; hand the
19//! query and a sender clone to a producer, which sends [`Results`] tagged
20//! with that query. Results for an older query are dropped.
21//!
22//! ```no_run
23//! use iced::{Element, Subscription};
24//! use iced_cube::lucide;
25//! use iced_cube::navigation::command::{self, Output, command, group, item};
26//!
27//! #[derive(Debug, Clone)]
28//! enum Message {
29//!     Command(command::Event<&'static str>),
30//! }
31//!
32//! struct App {
33//!     command: command::State<&'static str>,
34//! }
35//!
36//! impl App {
37//!     fn new() -> Self {
38//!         let command = command::State::new([group(
39//!             "Suggestions",
40//!             [
41//!                 item("calendar", "Calendar").icon(lucide!(Calendar)),
42//!                 item("settings", "Settings").shortcut("Ctrl+S"),
43//!             ],
44//!         )]);
45//!         Self { command }
46//!     }
47//!
48//!     fn update(&mut self, message: Message) {
49//!         let Message::Command(event) = message;
50//!         if let Some(Output::Activated(id)) = self.command.update(event) {
51//!             println!("Run {id}");
52//!         }
53//!     }
54//!
55//!     fn view(&self) -> Element<'_, Message> {
56//!         command(&self.command).on_event(Message::Command).into()
57//!     }
58//! }
59//! ```
60
61use std::fmt;
62use std::rc::Rc;
63
64use iced::futures::channel::mpsc;
65use iced::futures::{Stream, StreamExt, stream};
66use iced::keyboard::key::Named;
67use iced::mouse::ScrollDelta;
68use iced::widget::text::LineHeight;
69use iced::widget::text_input::{self, Status};
70use iced::widget::{self, Column, column, container, mouse_area, stack, text};
71use iced::{Alignment, Background, Border, Color, Element, Length, Padding, Subscription, Theme};
72
73use crate::icon::{Glyph, opacity, themed};
74use crate::keys::{self, Chord, Keymap};
75use crate::overlay::anchored::{anchored, surface_style};
76use crate::overlay::menu::{self, Parts, ROW_PADDING, RowStatus};
77use crate::primitives::input::{self, Shortcuts};
78use crate::theme::{Tokens, fade, space, text_size};
79
80/// How many result batches a producer can send before it has to wait.
81pub const CHANNEL_CAPACITY: usize = 64;
82/// The most result batches delivered in one [`Event::Received`].
83pub const BATCH_SIZE: usize = 32;
84/// How many rows show at once unless the state sets its own number.
85pub const VISIBLE_ROWS: usize = 8;
86/// Shown when nothing matches the query, unless the builder sets its own.
87pub const DEFAULT_EMPTY: &str = "No results found.";
88/// Shown while [`Command::loading`] is set.
89pub const SEARCHING: &str = "Searching...";
90
91const SEARCH_HEIGHT: f32 = 44.0;
92const ICON_SIZE: f32 = 16.0;
93const LINE_HEIGHT: f32 = 1.3;
94
95const EXACT: u32 = 5000;
96const PREFIX: u32 = 4000;
97const WORD: u32 = 3000;
98const CONTAINS: u32 = 2000;
99const FUZZY: u32 = 1000;
100const WORD_START: u32 = 10;
101const CONSECUTIVE: u32 = 5;
102/// Keyword matches rank just below the same kind of label match.
103const KEYWORD_PENALTY: u32 = 500;
104
105/// How well `query` matches `text`, ignoring case, or `None` when it does
106/// not match. Higher is better, and an empty query matches everything
107/// with 0.
108///
109/// An exact match ranks first, then a prefix, then the query at the start
110/// of a later word, then anywhere inside a word. Otherwise the letters must
111/// appear in order, and runs of letters and word starts score more. Within
112/// the first four kinds, shorter texts rank higher.
113///
114/// ```
115/// use iced_cube::navigation::command::score;
116///
117/// assert!(score("set", "Settings") > score("set", "Reset view"));
118/// assert!(score("nf", "New file").is_some());
119/// assert!(score("xyz", "Settings").is_none());
120/// ```
121pub fn score(query: &str, text: &str) -> Option<u32> {
122    let query: Vec<char> = query.trim().chars().flat_map(char::to_lowercase).collect();
123    if query.is_empty() {
124        return Some(0);
125    }
126    let folded = fold(text);
127    let chars: Vec<char> = folded.iter().map(|(c, _)| *c).collect();
128    let extra = chars.len().checked_sub(query.len())?;
129    let closeness = 999 - extra.min(999) as u32;
130
131    if extra == 0 && chars == query {
132        return Some(EXACT);
133    }
134    if chars.starts_with(&query) {
135        return Some(PREFIX + closeness);
136    }
137    let starts: Vec<usize> = chars
138        .windows(query.len())
139        .enumerate()
140        .filter(|(_, window)| *window == query.as_slice())
141        .map(|(start, _)| start)
142        .collect();
143    if starts.iter().any(|&start| folded[start].1) {
144        return Some(WORD + closeness);
145    }
146    if !starts.is_empty() {
147        return Some(CONTAINS + closeness);
148    }
149    fuzzy(&query, &folded).map(|bonus| FUZZY + bonus.min(999))
150}
151
152/// Lower-cased characters, each marked when it starts a word.
153fn fold(text: &str) -> Vec<(char, bool)> {
154    let mut folded = Vec::with_capacity(text.len());
155    let mut previous: Option<char> = None;
156    for c in text.chars() {
157        let starts_word = match previous {
158            None => true,
159            Some(p) => {
160                !p.is_alphanumeric() && c.is_alphanumeric() || p.is_lowercase() && c.is_uppercase()
161            }
162        };
163        for (n, lower) in c.to_lowercase().enumerate() {
164            folded.push((lower, starts_word && n == 0));
165        }
166        previous = Some(c);
167    }
168    folded
169}
170
171/// The best in-order match of every query letter, or `None` if there is
172/// none. Each matched letter scores 1, or more at a word start, plus a
173/// bonus when it follows the previous match directly.
174fn fuzzy(query: &[char], text: &[(char, bool)]) -> Option<u32> {
175    let mut previous: Vec<Option<u32>> = Vec::new();
176    for (i, &wanted) in query.iter().enumerate() {
177        let mut current = vec![None; text.len()];
178        let mut best_before: Option<u32> = None;
179        for (j, &(c, starts_word)) in text.iter().enumerate() {
180            if i > 0 && j >= 2 {
181                best_before = best_before.max(previous[j - 2]);
182            }
183            if c != wanted {
184                continue;
185            }
186            let letter = if starts_word { WORD_START } else { 1 };
187            let before = if i == 0 {
188                Some(0)
189            } else {
190                let adjacent = j
191                    .checked_sub(1)
192                    .and_then(|k| previous[k])
193                    .map(|score| score + CONSECUTIVE);
194                adjacent.max(best_before)
195            };
196            current[j] = before.map(|score| score + letter);
197        }
198        previous = current;
199    }
200    previous.into_iter().flatten().max()
201}
202
203/// One action in a [`Group`].
204#[derive(Debug, Clone, PartialEq)]
205pub struct Item<Id> {
206    pub id: Id,
207    pub label: String,
208    pub icon: Option<Glyph>,
209    /// A hint such as `Ctrl+S`, shown at the end of the row.
210    pub shortcut: Option<String>,
211    /// Other words that find this item.
212    pub keywords: Vec<String>,
213    pub disabled: bool,
214    pub destructive: bool,
215}
216
217/// Creates an enabled item.
218pub fn item<Id>(id: Id, label: impl Into<String>) -> Item<Id> {
219    Item {
220        id,
221        label: label.into(),
222        icon: None,
223        shortcut: None,
224        keywords: Vec::new(),
225        disabled: false,
226        destructive: false,
227    }
228}
229
230impl<Id> Item<Id> {
231    pub fn icon(mut self, glyph: Glyph) -> Self {
232        self.icon = Some(glyph);
233        self
234    }
235
236    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
237        self.shortcut = Some(shortcut.into());
238        self
239    }
240
241    pub fn keywords<S: Into<String>>(mut self, keywords: impl IntoIterator<Item = S>) -> Self {
242        self.keywords = keywords.into_iter().map(Into::into).collect();
243        self
244    }
245
246    /// Shows the item muted, skipped by the keyboard and not clickable.
247    pub fn disabled(mut self, disabled: bool) -> Self {
248        self.disabled = disabled;
249        self
250    }
251
252    /// Colours the label as a destructive action.
253    pub fn destructive(mut self, destructive: bool) -> Self {
254        self.destructive = destructive;
255        self
256    }
257
258    /// How well `query` matches the label or, ranked a little lower, a
259    /// keyword. See [`score`].
260    pub fn score(&self, query: &str) -> Option<u32> {
261        let keyword = self
262            .keywords
263            .iter()
264            .filter_map(|keyword| score(query, keyword))
265            .max()
266            .map(|score| score.saturating_sub(KEYWORD_PENALTY));
267        score(query, &self.label).max(keyword)
268    }
269}
270
271/// Items under a label. An empty label shows no heading.
272#[derive(Debug, Clone, PartialEq)]
273pub struct Group<Id> {
274    pub label: String,
275    pub items: Vec<Item<Id>>,
276}
277
278pub fn group<Id>(label: impl Into<String>, items: impl IntoIterator<Item = Item<Id>>) -> Group<Id> {
279    Group {
280        label: label.into(),
281        items: items.into_iter().collect(),
282    }
283}
284
285/// Items a producer found for a query, shown under `group` after the
286/// built-in groups. They are shown in the order they arrive, unranked.
287#[derive(Debug, Clone, PartialEq)]
288pub struct Results<Id> {
289    pub query: String,
290    pub group: String,
291    pub items: Vec<Item<Id>>,
292}
293
294pub fn results<Id>(
295    query: impl Into<String>,
296    group: impl Into<String>,
297    items: impl IntoIterator<Item = Item<Id>>,
298) -> Results<Id> {
299    Results {
300        query: query.into(),
301        group: group.into(),
302        items: items.into_iter().collect(),
303    }
304}
305
306/// The sending half of the results channel. Clone it for each producer.
307pub type Sender<Id> = mpsc::Sender<Results<Id>>;
308
309/// Everything that changes a command list.
310#[derive(Debug, Clone)]
311pub enum Event<Id> {
312    /// The channel is open. Keep the sender and hand clones to producers.
313    Ready(Sender<Id>),
314    /// Results from the channel, oldest first.
315    Received(Vec<Results<Id>>),
316    /// The query was edited.
317    Input(String),
318    /// Highlights the next enabled row, wrapping round.
319    Next,
320    /// Highlights the previous enabled row, wrapping round.
321    Previous,
322    First,
323    Last,
324    /// Activates the highlighted row.
325    ActivateHighlighted,
326    /// Clears the query, or closes the list when it is already empty.
327    Close,
328    /// Highlights a row, by its position in [`State::results`].
329    Highlight(usize),
330    /// Activates a row, by its position in [`State::results`].
331    Activate(usize),
332    /// Scrolls the list by a number of rows, down when positive.
333    Scroll(i32),
334    /// The search field gained or lost focus. The widget sends this itself.
335    Focus(bool),
336}
337
338/// What the app may need to act on after an [`Event`].
339#[derive(Debug, Clone)]
340pub enum Output<Id> {
341    Ready(Sender<Id>),
342    /// The query changed. Start any background search for it here.
343    Search(String),
344    /// An item was chosen.
345    Activated(Id),
346    /// Close was pressed with an empty query: close whatever holds the
347    /// list, such as a dialog.
348    Closed,
349}
350
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352struct Entry {
353    remote: bool,
354    group: usize,
355    item: usize,
356}
357
358/// The groups, the query, the ranked results and the highlighted row.
359#[derive(Debug, Clone, PartialEq)]
360pub struct State<Id> {
361    groups: Vec<Group<Id>>,
362    remote: Vec<Group<Id>>,
363    query: String,
364    entries: Vec<Entry>,
365    highlighted: Option<usize>,
366    offset: usize,
367    rows: usize,
368    focused: bool,
369    navigated: bool,
370}
371
372impl<Id> State<Id> {
373    /// Lists every item and highlights the first enabled one. The highlight
374    /// shows once the field has focus or the user moves it.
375    pub fn new(groups: impl IntoIterator<Item = Group<Id>>) -> Self {
376        let mut state = Self {
377            groups: groups.into_iter().collect(),
378            remote: Vec::new(),
379            query: String::new(),
380            entries: Vec::new(),
381            highlighted: None,
382            offset: 0,
383            rows: VISIBLE_ROWS,
384            focused: false,
385            navigated: false,
386        };
387        state.rank(false);
388        state
389    }
390
391    /// Sets how many rows show at once. At least one does.
392    pub fn with_visible_rows(mut self, rows: usize) -> Self {
393        self.rows = rows.max(1);
394        self.reveal();
395        self
396    }
397
398    pub fn query(&self) -> &str {
399        &self.query
400    }
401
402    pub fn groups(&self) -> &[Group<Id>] {
403        &self.groups
404    }
405
406    /// Every result in display order, with its group label.
407    pub fn results(&self) -> impl Iterator<Item = (&str, &Item<Id>)> {
408        self.entries.iter().filter_map(|&entry| {
409            let group = self.group(entry)?;
410            Some((group.label.as_str(), group.items.get(entry.item)?))
411        })
412    }
413
414    pub fn len(&self) -> usize {
415        self.entries.len()
416    }
417
418    pub fn is_empty(&self) -> bool {
419        self.entries.is_empty()
420    }
421
422    /// The highlighted item, if any result is enabled.
423    pub fn highlighted(&self) -> Option<&Item<Id>> {
424        self.highlighted.and_then(|position| self.item_at(position))
425    }
426
427    /// Position in [`State::results`] of the highlighted row.
428    pub fn highlighted_position(&self) -> Option<usize> {
429        self.highlighted
430    }
431
432    /// Whether the highlighted row is drawn highlighted: while the search
433    /// field has focus, or once the user has moved the highlight. An idle
434    /// inline list shows no highlight, though Enter still has a target.
435    pub fn shows_highlight(&self) -> bool {
436        self.focused || self.navigated
437    }
438
439    /// Whether the search field has focus.
440    pub fn is_focused(&self) -> bool {
441        self.focused
442    }
443
444    fn group(&self, entry: Entry) -> Option<&Group<Id>> {
445        let groups = if entry.remote {
446            &self.remote
447        } else {
448            &self.groups
449        };
450        groups.get(entry.group)
451    }
452
453    fn item_at(&self, position: usize) -> Option<&Item<Id>> {
454        let entry = *self.entries.get(position)?;
455        self.group(entry)?.items.get(entry.item)
456    }
457
458    fn is_enabled(&self, position: usize) -> bool {
459        self.item_at(position).is_some_and(|item| !item.disabled)
460    }
461
462    fn has_enabled(&self) -> bool {
463        (0..self.entries.len()).any(|position| self.is_enabled(position))
464    }
465
466    /// Applies an event and returns what the app may need to act on.
467    pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>>
468    where
469        Id: Clone,
470    {
471        if matches!(
472            event,
473            Event::Next
474                | Event::Previous
475                | Event::First
476                | Event::Last
477                | Event::Highlight(_)
478                | Event::Activate(_)
479        ) {
480            self.navigated = true;
481        }
482        match event {
483            Event::Ready(sender) => return Some(Output::Ready(sender)),
484            Event::Received(batch) => self.receive(batch),
485            Event::Input(query) => return self.search(query),
486            Event::Next => self.step(true),
487            Event::Previous => self.step(false),
488            Event::First => {
489                let first = (0..self.entries.len()).find(|&p| self.is_enabled(p));
490                self.highlight(first);
491            }
492            Event::Last => {
493                let last = (0..self.entries.len()).rev().find(|&p| self.is_enabled(p));
494                self.highlight(last);
495            }
496            Event::Focus(focused) => {
497                self.focused = focused;
498                if !focused {
499                    self.navigated = false;
500                }
501            }
502            Event::ActivateHighlighted => {
503                let id = self.highlighted()?.id.clone();
504                return Some(Output::Activated(id));
505            }
506            Event::Close if self.query.is_empty() => return Some(Output::Closed),
507            Event::Close => return self.search(String::new()),
508            Event::Highlight(position) => {
509                if self.is_enabled(position) {
510                    self.highlighted = Some(position);
511                }
512            }
513            Event::Activate(position) => {
514                if !self.is_enabled(position) {
515                    return None;
516                }
517                self.highlighted = Some(position);
518                let id = self.item_at(position)?.id.clone();
519                return Some(Output::Activated(id));
520            }
521            Event::Scroll(rows) => {
522                let last = self.entries.len().saturating_sub(self.rows);
523                let offset = (self.offset as i64).saturating_add(rows.into());
524                self.offset = offset.clamp(0, last as i64) as usize;
525            }
526        }
527        None
528    }
529
530    fn search(&mut self, query: String) -> Option<Output<Id>> {
531        if query == self.query {
532            return None;
533        }
534        self.query = query;
535        self.remote.clear();
536        self.rank(false);
537        Some(Output::Search(self.query.clone()))
538    }
539
540    fn receive(&mut self, batch: Vec<Results<Id>>) {
541        let mut changed = false;
542        for results in batch {
543            if results.query != self.query || results.items.is_empty() {
544                continue;
545            }
546            changed = true;
547            match self.remote.iter_mut().find(|g| g.label == results.group) {
548                Some(group) => group.items.extend(results.items),
549                None => self.remote.push(group(results.group, results.items)),
550            }
551        }
552        if changed {
553            self.rank(true);
554        }
555    }
556
557    /// Rebuilds the result list. Built-in groups are filtered and sorted
558    /// by score, results from producers are kept as they arrived.
559    fn rank(&mut self, keep_highlight: bool) {
560        let kept = keep_highlight
561            .then(|| self.highlighted.and_then(|p| self.entries.get(p).copied()))
562            .flatten();
563
564        let mut entries = Vec::new();
565        // The best enabled match in any group, as (score, position).
566        let mut best: Option<(u32, usize)> = None;
567        for (index, group) in self.groups.iter().enumerate() {
568            let mut scored: Vec<(u32, usize)> = group
569                .items
570                .iter()
571                .enumerate()
572                .filter_map(|(index, item)| item.score(&self.query).map(|score| (score, index)))
573                .collect();
574            scored.sort_by_key(|&(score, _)| std::cmp::Reverse(score));
575            for (score, item) in scored {
576                let enabled = group.items.get(item).is_some_and(|item| !item.disabled);
577                if enabled && best.is_none_or(|(top, _)| score > top) {
578                    best = Some((score, entries.len()));
579                }
580                entries.push(Entry {
581                    remote: false,
582                    group: index,
583                    item,
584                });
585            }
586        }
587        // Groups keep their order, but typing highlights the best match in
588        // any of them, so Enter runs what was typed for.
589        let best = best
590            .filter(|_| !self.query.trim().is_empty())
591            .map(|(_, position)| position);
592        for (index, group) in self.remote.iter().enumerate() {
593            entries.extend((0..group.items.len()).map(|item| Entry {
594                remote: true,
595                group: index,
596                item,
597            }));
598        }
599        self.entries = entries;
600
601        let kept = kept.and_then(|entry| self.entries.iter().position(|e| *e == entry));
602        if kept.is_none() {
603            self.offset = 0;
604        }
605        let first = kept
606            .or(best)
607            .or_else(|| (0..self.entries.len()).find(|&p| self.is_enabled(p)));
608        self.highlight(first);
609    }
610
611    /// The nearest enabled row in one direction, wrapping round.
612    fn step(&mut self, forward: bool) {
613        let len = self.entries.len();
614        if len == 0 {
615            return;
616        }
617        let start = self
618            .highlighted
619            .unwrap_or(if forward { len - 1 } else { 0 });
620        let offset = if forward { 1 } else { len - 1 };
621        let target = (1..=len)
622            .map(|n| (start + offset * n) % len)
623            .find(|&position| self.is_enabled(position));
624        if target.is_some() {
625            self.highlight(target);
626        }
627    }
628
629    fn highlight(&mut self, position: Option<usize>) {
630        self.highlighted = position;
631        self.reveal();
632    }
633
634    /// Moves the window so the highlighted row is in view.
635    fn reveal(&mut self) {
636        if let Some(position) = self.highlighted {
637            if position < self.offset {
638                self.offset = position;
639            } else if position >= self.offset + self.rows {
640                self.offset = position + 1 - self.rows;
641            }
642        }
643        self.offset = self
644            .offset
645            .min(self.entries.len().saturating_sub(self.rows));
646    }
647
648    /// Positions in [`State::results`] of the rows in view.
649    pub fn visible(&self) -> std::ops::Range<usize> {
650        let end = (self.offset + self.rows).min(self.entries.len());
651        self.offset.min(end)..end
652    }
653}
654
655/// What a command keyboard shortcut does.
656#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
657pub enum Action {
658    Next,
659    Previous,
660    First,
661    Last,
662    Activate,
663    Close,
664}
665
666impl Action {
667    /// The [`Event`] this action sends to `state`, or `None` when it would
668    /// do nothing, so the key can reach the search field instead.
669    pub fn event<Id>(self, state: &State<Id>) -> Option<Event<Id>> {
670        let movable = state.has_enabled();
671        match self {
672            Action::Next => movable.then_some(Event::Next),
673            Action::Previous => movable.then_some(Event::Previous),
674            Action::First => movable.then_some(Event::First),
675            Action::Last => movable.then_some(Event::Last),
676            Action::Activate => state
677                .highlighted
678                .is_some()
679                .then_some(Event::ActivateHighlighted),
680            Action::Close => Some(Event::Close),
681        }
682    }
683}
684
685impl keys::Action for Action {
686    const ALL: &'static [Self] = &[
687        Action::Next,
688        Action::Previous,
689        Action::First,
690        Action::Last,
691        Action::Activate,
692        Action::Close,
693    ];
694
695    fn defaults() -> Keymap<Self> {
696        default_keymap()
697    }
698
699    fn name(self) -> &'static str {
700        match self {
701            Action::Next => "Next",
702            Action::Previous => "Previous",
703            Action::First => "First",
704            Action::Last => "Last",
705            Action::Activate => "Activate",
706            Action::Close => "Close",
707        }
708    }
709
710    fn description(self) -> &'static str {
711        match self {
712            Action::Next => "Highlights the next enabled result, wrapping at the end.",
713            Action::Previous => "Highlights the previous enabled result, wrapping at the start.",
714            Action::First => "Highlights the first enabled result.",
715            Action::Last => "Highlights the last enabled result.",
716            Action::Activate => "Activates the highlighted result.",
717            Action::Close => "Clears the query, or closes the list when the query is empty.",
718        }
719    }
720}
721
722/// The default command shortcuts:
723///
724/// | Keys | Action |
725/// | --- | --- |
726/// | `ArrowDown` | [`Action::Next`] |
727/// | `ArrowUp` | [`Action::Previous`] |
728/// | `Home` | [`Action::First`] |
729/// | `End` | [`Action::Last`] |
730/// | `Enter` | [`Action::Activate`] |
731/// | `Escape` | [`Action::Close`] |
732///
733/// The list handles these itself while its search field has focus, so
734/// Home and End move the highlight rather than the text cursor. Pass a
735/// changed keymap with [`Command::keymap`]. To use them without focus,
736/// resolve presses from [`keys::subscription`] and send
737/// [`Action::event`] to the state.
738pub fn default_keymap() -> Keymap<Action> {
739    Keymap::new()
740        .bind(Chord::named(Named::ArrowDown), Action::Next)
741        .bind(Chord::named(Named::ArrowUp), Action::Previous)
742        .bind(Chord::named(Named::Home), Action::First)
743        .bind(Chord::named(Named::End), Action::Last)
744        .bind(Chord::named(Named::Enter), Action::Activate)
745        .bind(Chord::named(Named::Escape), Action::Close)
746}
747
748/// Owns the results channel. Emits [`Event::Ready`] first, then batches.
749pub fn subscription<Id: Send + 'static>() -> Subscription<Event<Id>> {
750    Subscription::run(stream::<Id>)
751}
752
753/// The stream behind [`subscription`], for driving it without a runtime.
754pub fn stream<Id: Send + 'static>() -> impl Stream<Item = Event<Id>> {
755    let (sender, receiver) = mpsc::channel(CHANNEL_CAPACITY);
756    stream::once(async move { Event::Ready(sender) }).chain(batches(receiver).map(Event::Received))
757}
758
759/// Groups whatever is already waiting in the channel into one batch.
760pub fn batches<T>(receiver: impl Stream<Item = T>) -> impl Stream<Item = Vec<T>> {
761    receiver.ready_chunks(BATCH_SIZE)
762}
763
764/// A command list builder. Convert it into an [`Element`] to render.
765///
766/// A command list without [`on_event`](Command::on_event) is rendered
767/// disabled.
768pub struct Command<'a, Id, Message> {
769    state: &'a State<Id>,
770    placeholder: String,
771    empty: String,
772    loading: bool,
773    width: Length,
774    height: Length,
775    max_height: f32,
776    id: Option<widget::Id>,
777    keymap: Keymap<Action>,
778    shortcuts: Shortcuts,
779    on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
780}
781
782/// Renders the search field and results of `state`.
783pub fn command<'a, Id, Message>(state: &'a State<Id>) -> Command<'a, Id, Message> {
784    Command {
785        state,
786        placeholder: "Type a command or search...".to_owned(),
787        empty: DEFAULT_EMPTY.to_owned(),
788        loading: false,
789        width: Length::Fill,
790        height: Length::Shrink,
791        max_height: f32::INFINITY,
792        id: None,
793        keymap: default_keymap(),
794        shortcuts: Shortcuts::all(),
795        on_event: None,
796    }
797}
798
799impl<Id: fmt::Debug, Message> fmt::Debug for Command<'_, Id, Message> {
800    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801        f.debug_struct("Command")
802            .field("state", self.state)
803            .field("placeholder", &self.placeholder)
804            .field("empty", &self.empty)
805            .field("loading", &self.loading)
806            .field("shortcuts", &self.shortcuts)
807            .field("enabled", &self.on_event.is_some())
808            .finish_non_exhaustive()
809    }
810}
811
812impl<'a, Id, Message> Command<'a, Id, Message> {
813    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
814        self.placeholder = placeholder.into();
815        self
816    }
817
818    /// Text shown when nothing matches the query.
819    pub fn empty(mut self, empty: impl Into<String>) -> Self {
820        self.empty = empty.into();
821        self
822    }
823
824    /// Shows that a background search is still running.
825    pub fn loading(mut self, loading: bool) -> Self {
826        self.loading = loading;
827        self
828    }
829
830    /// Overrides the width. Fills the available width by default.
831    pub fn width(mut self, width: impl Into<Length>) -> Self {
832        self.width = width.into();
833        self
834    }
835
836    /// Overrides the height. Fits the results by default; a fixed height
837    /// stops the list resizing as the results change.
838    pub fn height(mut self, height: impl Into<Length>) -> Self {
839        self.height = height.into();
840        self
841    }
842
843    /// Caps the height in pixels while the list still shrinks to fit a
844    /// few results. Rows past the cap are clipped, so keep
845    /// [`State::with_visible_rows`] within it.
846    pub fn max_height(mut self, max_height: f32) -> Self {
847        self.max_height = max_height;
848        self
849    }
850
851    /// Sets the widget id of the search field, to focus it or find it in
852    /// tests.
853    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
854        self.id = Some(id.into());
855        self
856    }
857
858    /// Replaces the [`default_keymap`].
859    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
860        self.keymap = keymap;
861        self
862    }
863
864    /// Sets which editing [`Shortcut`](input::Shortcut)s the search field
865    /// handles, as [`Input::shortcuts`](input::Input::shortcuts) does. All of
866    /// them by default.
867    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
868        self.shortcuts = shortcuts;
869        self
870    }
871
872    pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
873        self.on_event = Some(Box::new(on_event));
874        self
875    }
876
877    pub fn is_enabled(&self) -> bool {
878        self.on_event.is_some()
879    }
880}
881
882impl<'a, Id, Message> From<Command<'a, Id, Message>> for Element<'a, Message>
883where
884    Id: 'a,
885    Message: Clone + 'a,
886{
887    fn from(command: Command<'a, Id, Message>) -> Self {
888        let Command {
889            state,
890            placeholder,
891            empty,
892            loading,
893            width,
894            height,
895            max_height,
896            id,
897            keymap,
898            shortcuts,
899            on_event,
900        } = command;
901
902        let on_event: Option<Rc<dyn Fn(Event<Id>) -> Message + 'a>> = on_event.map(Rc::from);
903        let list = list(state, &empty, loading, on_event.as_deref());
904        #[cfg(feature = "icedwright")]
905        let key = icedwright_probe::Key::unique();
906        #[cfg(feature = "icedwright")]
907        let list: Element<'a, Message> = icedwright_probe::semantic(list)
908            .role(icedwright_probe::role::ListBox)
909            .key(key.clone())
910            .component("iced_cube::command")
911            .into();
912        let list = container(list).height(if height == Length::Shrink {
913            Length::Shrink
914        } else {
915            Length::Fill
916        });
917        let on_input = on_event.clone().map(|on_event| {
918            Box::new(move |query| on_event(Event::Input(query)))
919                as Box<dyn Fn(String) -> Message + 'a>
920        });
921
922        let search = search_field(&placeholder, &state.query, id, on_input, shortcuts);
923        #[cfg(feature = "icedwright")]
924        let search: Element<'a, Message> = icedwright_probe::semantic(search)
925            .role(icedwright_probe::role::ComboBox)
926            .name(placeholder.clone())
927            .placeholder(placeholder.clone())
928            .value(state.query.as_str())
929            .expanded(true)
930            .controls(key)
931            .component("iced_cube::command")
932            .into();
933        let surface = container(column![
934            search,
935            container(widget::space())
936                .width(Length::Fill)
937                .height(1)
938                .style(|theme| divider_style(&Tokens::of(theme))),
939            list,
940        ])
941        .width(width)
942        .height(height)
943        .max_height(max_height)
944        .clip(true)
945        .style(|theme| surface_style(&Tokens::of(theme)));
946
947        let Some(on_event) = on_event else {
948            return surface.into();
949        };
950        let on_focus = on_event.clone();
951        anchored(surface)
952            .kind("iced_cube::command")
953            .dismiss_keys([])
954            .on_focus(move |focused| on_focus(Event::Focus(focused)))
955            .on_key(move |key| {
956                keymap
957                    .resolve_event(key)
958                    .and_then(|action| action.event(state))
959                    .map(&*on_event)
960            })
961            .into()
962    }
963}
964
965fn search_field<'a, Message: Clone + 'a>(
966    placeholder: &str,
967    value: &str,
968    id: Option<widget::Id>,
969    on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
970    shortcuts: Shortcuts,
971) -> Element<'a, Message> {
972    let enabled = on_input.is_some();
973    let vertical = (SEARCH_HEIGHT - text_size::SM * LINE_HEIGHT) / 2.0;
974    let mut text = widget::text_input(placeholder, value)
975        .size(text_size::SM)
976        .line_height(LineHeight::Relative(LINE_HEIGHT))
977        .padding(Padding {
978            top: vertical,
979            bottom: vertical,
980            left: space::MD + ICON_SIZE + space::SM,
981            right: space::MD,
982        })
983        .width(Length::Fill)
984        .style(|theme, status| search_style(&Tokens::of(theme), status));
985    if let Some(id) = id {
986        text = text.id(id);
987    }
988    let keymap = input::default_keymap();
989    let input = input::with_shortcuts(text, value, false, on_input, keymap, shortcuts);
990
991    let icon = themed(
992        crate::lucide!(Search),
993        menu::ICON_SIZE,
994        opacity(enabled),
995        |theme| Tokens::of(theme).muted_foreground,
996    );
997
998    stack![
999        input,
1000        container(icon)
1001            .height(Length::Fill)
1002            .align_y(Alignment::Center)
1003            .padding(Padding::ZERO.left(space::MD)),
1004    ]
1005    .into()
1006}
1007
1008fn list<'a, Id, Message: Clone + 'a>(
1009    state: &'a State<Id>,
1010    empty: &str,
1011    loading: bool,
1012    on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
1013) -> Element<'a, Message> {
1014    let mut children: Vec<Element<'a, Message>> = Vec::new();
1015    let mut previous: Option<(bool, usize)> = None;
1016
1017    for position in state.visible() {
1018        let Some(&entry) = state.entries.get(position) else {
1019            continue;
1020        };
1021        let Some(group) = state.group(entry) else {
1022            continue;
1023        };
1024        let Some(item) = group.items.get(entry.item) else {
1025            continue;
1026        };
1027
1028        let key = (entry.remote, entry.group);
1029        if previous != Some(key) {
1030            if previous.is_some() {
1031                children.push(menu::separator());
1032            }
1033            if !group.label.is_empty() {
1034                children.push(menu::group_label(&group.label, false));
1035            }
1036            previous = Some(key);
1037        }
1038
1039        let enabled = on_event.is_some() && !item.disabled;
1040        let status = if !enabled {
1041            RowStatus::Disabled
1042        } else if state.shows_highlight() && state.highlighted == Some(position) {
1043            RowStatus::Highlighted
1044        } else {
1045            RowStatus::Idle
1046        };
1047        let messages = on_event.filter(|_| enabled).map(|on_event| {
1048            (
1049                on_event(Event::Highlight(position)),
1050                on_event(Event::Activate(position)),
1051            )
1052        });
1053        let parts = Parts {
1054            icon: item.icon,
1055            hint: item.shortcut.as_deref(),
1056            ..Parts::label(&item.label)
1057        };
1058        let row = menu::item(parts, status, item.destructive, messages);
1059        #[cfg(feature = "icedwright")]
1060        let row = {
1061            let annotated = icedwright_probe::semantic(row)
1062                .role(icedwright_probe::role::ListOption)
1063                .name(item.label.as_str())
1064                .selected(status == RowStatus::Highlighted)
1065                .component("iced_cube::command");
1066            if enabled {
1067                annotated.into()
1068            } else {
1069                annotated.disabled(true).into()
1070            }
1071        };
1072        children.push(row);
1073    }
1074
1075    if children.is_empty() {
1076        return menu::empty(if loading { SEARCHING } else { empty });
1077    }
1078    if loading {
1079        children.push(menu::inset(
1080            container(muted(SEARCHING.to_owned(), text_size::SM)).padding(ROW_PADDING),
1081        ));
1082    }
1083
1084    let rows = Column::from_vec(children)
1085        .padding([space::XS, 0.0])
1086        .width(Length::Fill);
1087    let Some(on_event) = on_event else {
1088        return rows.into();
1089    };
1090    let down = on_event(Event::Scroll(1));
1091    let up = on_event(Event::Scroll(-1));
1092    mouse_area(rows)
1093        .on_scroll(move |delta| match delta {
1094            ScrollDelta::Lines { y, .. } | ScrollDelta::Pixels { y, .. } if y < 0.0 => down.clone(),
1095            _ => up.clone(),
1096        })
1097        .into()
1098}
1099
1100fn muted<'a, Message: 'a>(content: String, size: f32) -> Element<'a, Message> {
1101    text(content)
1102        .size(size)
1103        .line_height(LineHeight::Absolute(menu::LINE_HEIGHT.into()))
1104        .style(|theme: &Theme| text::Style {
1105            color: Some(Tokens::of(theme).muted_foreground),
1106        })
1107        .into()
1108}
1109
1110/// The search field: borderless and transparent, inside the surface.
1111pub fn search_style(tokens: &Tokens, status: Status) -> text_input::Style {
1112    let style = text_input::Style {
1113        background: Background::Color(Color::TRANSPARENT),
1114        border: Border::default(),
1115        icon: tokens.muted_foreground,
1116        placeholder: tokens.muted_foreground,
1117        value: tokens.foreground,
1118        selection: fade(tokens.primary, 0.25),
1119    };
1120    if status != Status::Disabled {
1121        return style;
1122    }
1123    text_input::Style {
1124        placeholder: fade(style.placeholder, 0.5),
1125        value: fade(style.value, 0.5),
1126        icon: fade(style.icon, 0.5),
1127        selection: Color::TRANSPARENT,
1128        ..style
1129    }
1130}
1131
1132/// The line under the search field and between groups.
1133pub fn divider_style(tokens: &Tokens) -> container::Style {
1134    container::Style {
1135        background: Some(Background::Color(tokens.border)),
1136        ..container::Style::default()
1137    }
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142    use super::*;
1143    use crate::theme::{dark, light};
1144    use futures::SinkExt;
1145    use futures::executor::block_on;
1146
1147    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1148        let chord: Chord = chord.parse().unwrap();
1149        keymap.resolve(chord.key(), chord.modifiers())
1150    }
1151
1152    fn sample() -> State<&'static str> {
1153        State::new([
1154            group(
1155                "Suggestions",
1156                [
1157                    item("calendar", "Calendar"),
1158                    item("emoji", "Search emoji").keywords(["smiley"]),
1159                    item("calculator", "Calculator").disabled(true),
1160                ],
1161            ),
1162            group(
1163                "Settings",
1164                [
1165                    item("profile", "Profile").shortcut("Ctrl+P"),
1166                    item("billing", "Billing"),
1167                    item("settings", "Settings"),
1168                ],
1169            ),
1170        ])
1171    }
1172
1173    fn ids(state: &State<&'static str>) -> Vec<&'static str> {
1174        state.results().map(|(_, item)| item.id).collect()
1175    }
1176
1177    fn highlighted(state: &State<&'static str>) -> Option<&'static str> {
1178        state.highlighted().map(|item| item.id)
1179    }
1180
1181    #[test]
1182    fn empty_query_matches_everything_equally() {
1183        assert_eq!(score("", "Anything"), Some(0));
1184        assert_eq!(score("   ", "Anything"), Some(0));
1185    }
1186
1187    #[test]
1188    fn matching_ignores_case() {
1189        assert_eq!(score("SET", "settings"), score("set", "Settings"));
1190        assert!(score("cAl", "CALENDAR").is_some());
1191    }
1192
1193    #[test]
1194    fn match_kinds_rank_in_order() {
1195        let exact = score("set", "Set");
1196        let prefix = score("set", "Settings");
1197        let word = score("set", "Reset settings");
1198        let contains = score("set", "Asset");
1199        let fuzzy = score("set", "Sheet editor");
1200        assert!(exact > prefix, "{exact:?} {prefix:?}");
1201        assert!(prefix > word, "{prefix:?} {word:?}");
1202        assert!(word > contains, "{word:?} {contains:?}");
1203        assert!(contains > fuzzy, "{contains:?} {fuzzy:?}");
1204        assert!(fuzzy.is_some());
1205    }
1206
1207    #[test]
1208    fn letters_must_appear_in_order() {
1209        assert!(score("tes", "Settings").is_none());
1210        assert!(score("xyz", "Settings").is_none());
1211        assert!(score("settings!", "Settings").is_none());
1212    }
1213
1214    #[test]
1215    fn shorter_texts_win_within_a_kind() {
1216        assert!(score("set", "Settings") > score("set", "Settings and privacy"));
1217    }
1218
1219    #[test]
1220    fn fuzzy_prefers_word_starts_and_runs() {
1221        assert!(score("ts", "Toggle sidebar") > score("ts", "Tabs list"));
1222        assert!(score("nf", "newFile") > score("nf", "notify"));
1223        assert!(score("sba", "Show bar") > score("sba", "Toggle sidebar"));
1224        assert!(score("ogl", "toggle") > score("ogl", "tobgaly"));
1225    }
1226
1227    #[test]
1228    fn keywords_find_items_but_rank_below_labels() {
1229        let emoji = item("emoji", "Search emoji").keywords(["smiley"]);
1230        assert!(emoji.score("smil").is_some());
1231        let smiley = item("smiley", "Smiley");
1232        assert!(smiley.score("smil") > emoji.score("smil"));
1233        assert!(item("x", "Plain").score("smil").is_none());
1234    }
1235
1236    #[test]
1237    fn new_state_lists_every_item_and_highlights_the_first() {
1238        let state = sample();
1239        assert_eq!(state.len(), 6);
1240        assert_eq!(highlighted(&state), Some("calendar"));
1241        assert_eq!(state.query(), "");
1242        assert!(State::<u8>::new([]).is_empty());
1243        assert!(State::<u8>::new([]).highlighted().is_none());
1244    }
1245
1246    #[test]
1247    fn the_highlight_shows_only_while_focused_or_after_navigating() {
1248        let mut state = sample();
1249        assert!(!state.shows_highlight());
1250        assert!(!state.is_focused());
1251
1252        let _ = state.update(Event::Focus(true));
1253        assert!(state.shows_highlight() && state.is_focused());
1254        let _ = state.update(Event::Focus(false));
1255        assert!(!state.shows_highlight());
1256
1257        for event in [
1258            Event::Next,
1259            Event::Previous,
1260            Event::First,
1261            Event::Last,
1262            Event::Highlight(0),
1263        ] {
1264            let mut state = sample();
1265            let _ = state.update(event);
1266            assert!(state.shows_highlight());
1267            let _ = state.update(Event::Focus(true));
1268            let _ = state.update(Event::Focus(false));
1269            assert!(!state.shows_highlight(), "leaving the field hides it again");
1270        }
1271    }
1272
1273    #[test]
1274    fn typing_or_scrolling_alone_does_not_show_the_highlight() {
1275        let mut state = sample();
1276        let _ = state.update(Event::Input("set".into()));
1277        let _ = state.update(Event::Scroll(1));
1278        assert!(!state.shows_highlight());
1279        assert!(state.highlighted().is_some(), "Enter still has a target");
1280    }
1281
1282    #[test]
1283    fn typing_filters_ranks_and_asks_for_a_search() {
1284        let mut state = sample();
1285        let output = state.update(Event::Input("cal".into()));
1286        assert!(matches!(output, Some(Output::Search(query)) if query == "cal"));
1287        assert_eq!(ids(&state), ["calendar", "calculator"]);
1288        assert_eq!(highlighted(&state), Some("calendar"));
1289
1290        // Calculator is the closer match now, but it is disabled.
1291        let _ = state.update(Event::Input("calc".into()));
1292        assert_eq!(ids(&state), ["calculator"]);
1293        assert!(state.highlighted().is_none());
1294
1295        let _ = state.update(Event::Input("set".into()));
1296        assert_eq!(ids(&state), ["settings"]);
1297        let groups: Vec<_> = state.results().map(|(group, _)| group).collect();
1298        assert_eq!(groups, ["Settings"]);
1299
1300        assert!(state.update(Event::Input("set".into())).is_none());
1301    }
1302
1303    #[test]
1304    fn nothing_matching_leaves_nothing_highlighted() {
1305        let mut state = sample();
1306        let _ = state.update(Event::Input("zzz".into()));
1307        assert!(state.is_empty());
1308        assert!(state.highlighted().is_none());
1309        assert!(state.update(Event::ActivateHighlighted).is_none());
1310        let _ = state.update(Event::Next);
1311        assert!(state.highlighted().is_none());
1312    }
1313
1314    #[test]
1315    fn arrows_wrap_and_skip_disabled_items() {
1316        let mut state = sample();
1317        let _ = state.update(Event::Next);
1318        assert_eq!(highlighted(&state), Some("emoji"));
1319        let _ = state.update(Event::Next);
1320        assert_eq!(highlighted(&state), Some("profile"));
1321        let _ = state.update(Event::Previous);
1322        let _ = state.update(Event::Previous);
1323        let _ = state.update(Event::Previous);
1324        assert_eq!(highlighted(&state), Some("settings"));
1325        let _ = state.update(Event::Next);
1326        assert_eq!(highlighted(&state), Some("calendar"));
1327    }
1328
1329    #[test]
1330    fn typing_highlights_the_best_match_in_any_group() {
1331        let mut state = State::new([
1332            group(
1333                "Actions",
1334                [
1335                    item("retry", "Retry failed jobs"),
1336                    item("clear", "Clear finished jobs").destructive(true),
1337                ],
1338            ),
1339            group(
1340                "Open job",
1341                [
1342                    item("ledger", "ledger-reconcile"),
1343                    item("lead", "lead-import").disabled(true),
1344                ],
1345            ),
1346        ]);
1347        let _ = state.update(Event::Input("led".into()));
1348        assert_eq!(
1349            ids(&state)[..2],
1350            ["retry", "clear"],
1351            "groups keep their order"
1352        );
1353        assert_eq!(highlighted(&state), Some("ledger"));
1354
1355        let _ = state.update(Event::Input(String::new()));
1356        assert_eq!(highlighted(&state), Some("retry"), "no query, first row");
1357    }
1358
1359    #[test]
1360    fn home_and_end_jump_to_enabled_ends() {
1361        let mut state = State::new([group(
1362            "",
1363            [
1364                item(1, "One").disabled(true),
1365                item(2, "Two"),
1366                item(3, "Three"),
1367                item(4, "Four").disabled(true),
1368            ],
1369        )]);
1370        let _ = state.update(Event::Last);
1371        assert_eq!(state.highlighted().map(|i| i.id), Some(3));
1372        let _ = state.update(Event::First);
1373        assert_eq!(state.highlighted().map(|i| i.id), Some(2));
1374    }
1375
1376    #[test]
1377    fn run_and_activate_return_the_id() {
1378        let mut state = sample();
1379        let _ = state.update(Event::Next);
1380        assert!(matches!(
1381            state.update(Event::ActivateHighlighted),
1382            Some(Output::Activated("emoji"))
1383        ));
1384
1385        assert!(matches!(
1386            state.update(Event::Activate(4)),
1387            Some(Output::Activated("billing"))
1388        ));
1389        assert_eq!(highlighted(&state), Some("billing"));
1390        assert!(state.update(Event::Activate(2)).is_none());
1391        assert!(state.update(Event::Activate(99)).is_none());
1392    }
1393
1394    #[test]
1395    fn hovering_a_disabled_row_keeps_the_highlight() {
1396        let mut state = sample();
1397        let _ = state.update(Event::Highlight(2));
1398        assert_eq!(highlighted(&state), Some("calendar"));
1399        let _ = state.update(Event::Highlight(3));
1400        assert_eq!(highlighted(&state), Some("profile"));
1401    }
1402
1403    #[test]
1404    fn clear_empties_the_query_then_dismisses() {
1405        let mut state = sample();
1406        let _ = state.update(Event::Input("bill".into()));
1407        let output = state.update(Event::Close);
1408        assert!(matches!(output, Some(Output::Search(query)) if query.is_empty()));
1409        assert_eq!(state.len(), 6);
1410        assert!(matches!(state.update(Event::Close), Some(Output::Closed)));
1411    }
1412
1413    #[test]
1414    fn results_for_the_current_query_join_a_remote_group() {
1415        let mut state = sample();
1416        let _ = state.update(Event::Input("rep".into()));
1417        assert!(state.is_empty());
1418
1419        let _ = state.update(Event::Received(vec![
1420            results("rep", "Files", [item("a", "report.pdf")]),
1421            results("rep", "Files", [item("b", "reply.txt")]),
1422        ]));
1423        assert_eq!(ids(&state), ["a", "b"]);
1424        assert!(state.results().all(|(group, _)| group == "Files"));
1425        assert_eq!(highlighted(&state), Some("a"));
1426    }
1427
1428    #[test]
1429    fn stale_results_are_dropped() {
1430        let mut state = sample();
1431        let _ = state.update(Event::Input("re".into()));
1432        let _ = state.update(Event::Input("rep".into()));
1433        let _ = state.update(Event::Received(vec![results(
1434            "re",
1435            "Files",
1436            [item("old", "readme.md")],
1437        )]));
1438        assert!(state.is_empty());
1439    }
1440
1441    #[test]
1442    fn a_new_query_clears_remote_results() {
1443        let mut state = sample();
1444        let files = |state: &State<&'static str>| {
1445            state
1446                .results()
1447                .filter(|(group, _)| *group == "Files")
1448                .count()
1449        };
1450        let _ = state.update(Event::Input("re".into()));
1451        let _ = state.update(Event::Received(vec![results(
1452            "re",
1453            "Files",
1454            [item("old", "readme.md")],
1455        )]));
1456        assert_eq!(files(&state), 1);
1457        let _ = state.update(Event::Input("rea".into()));
1458        assert_eq!(files(&state), 0);
1459    }
1460
1461    #[test]
1462    fn arriving_results_keep_the_highlight() {
1463        let mut state = sample();
1464        let _ = state.update(Event::Input("s".into()));
1465        let _ = state.update(Event::Next);
1466        let before = highlighted(&state);
1467        let _ = state.update(Event::Received(vec![results(
1468            "s",
1469            "Files",
1470            [item("f", "styles.css")],
1471        )]));
1472        assert_eq!(highlighted(&state), before);
1473        assert_eq!(state.results().last().map(|(_, item)| item.id), Some("f"));
1474    }
1475
1476    #[test]
1477    fn remote_results_are_not_filtered_again() {
1478        let mut state = sample();
1479        let _ = state.update(Event::Input("q".into()));
1480        let _ = state.update(Event::Received(vec![results(
1481            "q",
1482            "Files",
1483            [item("x", "unrelated.txt")],
1484        )]));
1485        assert_eq!(ids(&state), ["x"]);
1486    }
1487
1488    #[test]
1489    fn the_window_follows_the_highlight_and_scrolls() {
1490        let mut state = sample().with_visible_rows(3);
1491        assert_eq!(state.visible(), 0..3);
1492        let _ = state.update(Event::Last);
1493        assert_eq!(state.visible(), 3..6);
1494        let _ = state.update(Event::Next);
1495        assert_eq!(state.visible(), 0..3);
1496        let _ = state.update(Event::Scroll(10));
1497        assert_eq!(state.visible(), 3..6);
1498        let _ = state.update(Event::Scroll(-1));
1499        assert_eq!(state.visible(), 2..5);
1500        assert_eq!(State::<u8>::new([]).with_visible_rows(0).rows, 1);
1501        assert_eq!(State::<u8>::new([]).visible(), 0..0);
1502    }
1503
1504    #[test]
1505    fn ready_hands_the_sender_back() {
1506        let (sender, _receiver) = mpsc::channel(1);
1507        let output = sample().update(Event::Ready(sender));
1508        assert!(matches!(output, Some(Output::Ready(_))));
1509    }
1510
1511    #[test]
1512    fn default_keymap_and_overrides() {
1513        let keymap = default_keymap();
1514        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
1515        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
1516        assert_eq!(press(&keymap, "Home"), Some(Action::First));
1517        assert_eq!(press(&keymap, "End"), Some(Action::Last));
1518        assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
1519        assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
1520
1521        let custom = keymap
1522            .bind("Ctrl+N".parse().unwrap(), Action::Next)
1523            .unbind(&Chord::named(Named::Home));
1524        assert_eq!(press(&custom, "ctrl+n"), Some(Action::Next));
1525        assert_eq!(press(&custom, "Home"), None);
1526        assert!(default_keymap().clear().is_empty());
1527    }
1528
1529    #[test]
1530    fn actions_map_to_events_only_when_they_apply() {
1531        let mut state = sample();
1532        for action in [Action::Next, Action::Previous, Action::First, Action::Last] {
1533            assert!(action.event(&state).is_some(), "{action:?}");
1534        }
1535        assert!(matches!(
1536            Action::Activate.event(&state),
1537            Some(Event::ActivateHighlighted)
1538        ));
1539        assert!(matches!(Action::Close.event(&state), Some(Event::Close)));
1540
1541        let _ = state.update(Event::Input("zzz".into()));
1542        for action in [
1543            Action::Next,
1544            Action::Previous,
1545            Action::First,
1546            Action::Last,
1547            Action::Activate,
1548        ] {
1549            assert!(action.event(&state).is_none(), "{action:?}");
1550        }
1551        assert!(matches!(Action::Close.event(&state), Some(Event::Close)));
1552    }
1553
1554    #[test]
1555    fn stream_emits_ready_first_then_batches() {
1556        let mut events = Box::pin(stream::<&'static str>());
1557        let Some(Event::Ready(mut sender)) = block_on(events.next()) else {
1558            panic!("first event must be Ready");
1559        };
1560        block_on(async {
1561            for name in ["a", "b", "c"] {
1562                sender
1563                    .send(results("q", "Files", [item(name, name)]))
1564                    .await
1565                    .ok();
1566            }
1567        });
1568        let Some(Event::Received(batch)) = block_on(events.next()) else {
1569            panic!("expected a batch");
1570        };
1571        let names: Vec<_> = batch.iter().map(|r| r.items[0].id).collect();
1572        assert_eq!(names, ["a", "b", "c"]);
1573    }
1574
1575    #[test]
1576    fn batches_split_bursts_at_batch_size() {
1577        let items = stream::iter(0..BATCH_SIZE + 3);
1578        let sizes: Vec<_> = block_on(batches(items).map(|batch| batch.len()).collect());
1579        assert_eq!(sizes, [BATCH_SIZE, 3]);
1580    }
1581
1582    #[test]
1583    fn default_builder_is_disabled() {
1584        let state = sample();
1585        let c: Command<'_, &str, ()> = command(&state);
1586        assert!(!c.is_enabled());
1587        assert_eq!(c.empty, DEFAULT_EMPTY);
1588        assert!(!c.loading);
1589        assert_eq!((c.width, c.height), (Length::Fill, Length::Shrink));
1590        assert_eq!(c.max_height, f32::INFINITY);
1591        let c = c
1592            .loading(true)
1593            .height(320)
1594            .max_height(400.0)
1595            .on_event(|_| ());
1596        assert!(c.is_enabled() && c.loading);
1597        assert_eq!(c.height, Length::Fixed(320.0));
1598        assert_eq!(c.max_height, 400.0);
1599    }
1600
1601    const STATES: [Status; 5] = [
1602        Status::Active,
1603        Status::Hovered,
1604        Status::Focused { is_hovered: false },
1605        Status::Focused { is_hovered: true },
1606        Status::Disabled,
1607    ];
1608
1609    #[test]
1610    fn search_field_is_borderless_and_fades_when_disabled() {
1611        for theme in [light(), dark()] {
1612            let tokens = Tokens::of(&theme);
1613            for status in STATES {
1614                let style = search_style(&tokens, status);
1615                assert_eq!(style.border.width, 0.0);
1616                assert_eq!(style.background, Background::Color(Color::TRANSPARENT));
1617                let expected = if status == Status::Disabled {
1618                    fade(tokens.foreground, 0.5)
1619                } else {
1620                    tokens.foreground
1621                };
1622                assert_eq!(style.value, expected, "{status:?}");
1623            }
1624        }
1625    }
1626
1627    #[test]
1628    fn dividers_use_the_border_token() {
1629        for theme in [light(), dark()] {
1630            let tokens = Tokens::of(&theme);
1631            assert_eq!(
1632                divider_style(&tokens).background,
1633                Some(Background::Color(tokens.border))
1634            );
1635        }
1636    }
1637}