Skip to main content

iced_cube/application/
command_palette.rs

1//! The global searchable launcher: a [command list](mod@crate::navigation::command)
2//! in a [dialog](mod@crate::overlay::dialog), opened from anywhere with Ctrl+K
3//! or Ctrl+Shift+P.
4//!
5//! [`State`] owns whether the palette is open, its groups of commands, any
6//! nested [`Page`]s and the recently run commands, which it lists first
7//! while the query is empty. Choosing an item whose id names a page, such
8//! as "Change theme...", opens that page's list instead of running it;
9//! Backspace on an empty query, Escape or the Back button returns to the
10//! page before.
11//!
12//! The app routes key presses from [`keys::subscription`] through
13//! [`State::key_event`] so the toggle chords open the palette anywhere.
14//! While it is open, the palette resolves its own keys: the command
15//! list's first, then Back and the toggle chords, then the dialog's. Async
16//! results arrive through the command list's channel: [`subscription`]
17//! wraps [`command::subscription`], and [`Output::Search`] asks the app to
18//! search the current page for a query.
19//!
20//! ```no_run
21//! use iced::{Element, Subscription};
22//! use iced::widget::text;
23//! use iced_cube::command_palette::{self, Output, command_palette, page};
24//! use iced_cube::keys;
25//! use iced_cube::navigation::command::{group, item};
26//!
27//! #[derive(Debug, Clone)]
28//! enum Message {
29//!     Palette(command_palette::Event<&'static str>),
30//!     Key(keys::Event),
31//! }
32//!
33//! struct App {
34//!     palette: command_palette::State<&'static str>,
35//! }
36//!
37//! impl App {
38//!     fn new() -> Self {
39//!         let palette = command_palette::State::new([group(
40//!             "Actions",
41//!             [item("new", "New file"), item("theme", "Change theme...")],
42//!         )])
43//!         .with_page(page("theme", "Theme", [group("", [item("dark", "Dark"), item("light", "Light")])]));
44//!         Self { palette }
45//!     }
46//!
47//!     fn update(&mut self, message: Message) {
48//!         let event = match message {
49//!             Message::Palette(event) => Some(event),
50//!             Message::Key(key) => self
51//!                 .palette
52//!                 .key_event(&command_palette::default_keymap(), &key),
53//!         };
54//!         if let Some(Output::Activated(id)) = event.and_then(|event| self.palette.update(event)) {
55//!             println!("Run {id}");
56//!         }
57//!     }
58//!
59//!     fn view(&self) -> Element<'_, Message> {
60//!         command_palette(&self.palette, text("Press Ctrl+K"))
61//!             .on_event(Message::Palette)
62//!             .into()
63//!     }
64//!
65//!     fn subscription(&self) -> Subscription<Message> {
66//!         keys::subscription().map(Message::Key)
67//!     }
68//! }
69//! ```
70
71use std::rc::Rc;
72
73use iced::keyboard::key::Named;
74use iced::widget;
75use iced::{Element, Subscription};
76
77use crate::keys::{self, Chord, Keymap};
78use crate::navigation::command::{self, Group, Item, command, group};
79use crate::overlay::anchored::anchored;
80use crate::overlay::dialog::{self, dialog};
81use crate::primitives::button::{self, Variant, button};
82use crate::primitives::input::Shortcuts;
83
84/// The widget id of the search field, to focus it or find it in tests.
85pub const SEARCH_ID: widget::Id = widget::Id::new("iced-cube-command-palette-search");
86/// The widget id of the dialog surface, which scopes its focus.
87pub const DIALOG_ID: widget::Id = widget::Id::new("iced-cube-command-palette");
88/// How many recent commands are kept unless the state sets its own number.
89pub const RECENT_LIMIT: usize = 5;
90/// The heading over the recent commands.
91pub const RECENT_LABEL: &str = "Recent";
92/// How many rows show at once unless the state sets its own number.
93pub const VISIBLE_ROWS: usize = 8;
94/// The dialog title on the first page unless the builder sets its own.
95pub const DEFAULT_TITLE: &str = "Command palette";
96
97/// A nested list, opened by choosing the item with the page's id.
98#[derive(Debug, Clone, PartialEq)]
99pub struct Page<Id> {
100    pub id: Id,
101    /// Shown as the dialog title while the page is open.
102    pub title: String,
103    /// Replaces the search field's placeholder while the page is open.
104    pub placeholder: Option<String>,
105    pub groups: Vec<Group<Id>>,
106}
107
108/// A page listing `groups`, opened by the item whose id is `id`.
109pub fn page<Id>(
110    id: Id,
111    title: impl Into<String>,
112    groups: impl IntoIterator<Item = Group<Id>>,
113) -> Page<Id> {
114    Page {
115        id,
116        title: title.into(),
117        placeholder: None,
118        groups: groups.into_iter().collect(),
119    }
120}
121
122impl<Id> Page<Id> {
123    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
124        self.placeholder = Some(placeholder.into());
125        self
126    }
127}
128
129/// Changes to a command palette.
130#[derive(Debug, Clone)]
131pub enum Event<Id> {
132    /// Opens on the first page with an empty query.
133    Open,
134    Close,
135    Toggle,
136    /// Returns to the page before, if a nested page is open.
137    Back,
138    /// An event for the command list inside.
139    Command(command::Event<Id>),
140}
141
142/// What the app may need to act on after an [`Event`].
143#[derive(Debug, Clone)]
144pub enum Output<Id> {
145    /// The results channel is open. Keep the sender for producers.
146    Ready(command::Sender<Id>),
147    /// The query changed. Search [`State::page_id`] for it in the
148    /// background, if anything is searched that way.
149    Search(String),
150    /// A command was chosen. The palette has closed and noted it as recent.
151    Activated(Id),
152}
153
154/// Whether the palette is open, its pages, the recent commands and the
155/// command list on show.
156#[derive(Debug, Clone, PartialEq)]
157pub struct State<Id> {
158    open: bool,
159    root: Vec<Group<Id>>,
160    pages: Vec<Page<Id>>,
161    stack: Vec<Id>,
162    recent: Vec<Id>,
163    recent_limit: usize,
164    rows: usize,
165    command: command::State<Id>,
166}
167
168impl<Id: Clone + PartialEq> State<Id> {
169    /// A closed palette listing `groups` on its first page.
170    pub fn new(groups: impl IntoIterator<Item = Group<Id>>) -> Self {
171        let mut state = Self {
172            open: false,
173            root: groups.into_iter().collect(),
174            pages: Vec::new(),
175            stack: Vec::new(),
176            recent: Vec::new(),
177            recent_limit: RECENT_LIMIT,
178            rows: VISIBLE_ROWS,
179            command: command::State::new([]),
180        };
181        state.rebuild(String::new());
182        state
183    }
184
185    /// Adds a nested page. Choosing the item with the page's id opens it.
186    pub fn with_page(mut self, page: Page<Id>) -> Self {
187        self.pages.push(page);
188        self
189    }
190
191    /// Starts with these recent commands, newest first.
192    pub fn with_recent(mut self, ids: impl IntoIterator<Item = Id>) -> Self {
193        self.recent = ids.into_iter().take(self.recent_limit).collect();
194        self.rebuild(String::new());
195        self
196    }
197
198    /// How many recent commands to keep. Zero turns the recent group off.
199    pub fn with_recent_limit(mut self, limit: usize) -> Self {
200        self.recent_limit = limit;
201        self.recent.truncate(limit);
202        self.rebuild(String::new());
203        self
204    }
205
206    /// How many rows show at once. At least one does.
207    pub fn with_visible_rows(mut self, rows: usize) -> Self {
208        self.rows = rows.max(1);
209        self.rebuild(String::new());
210        self
211    }
212
213    pub fn is_open(&self) -> bool {
214        self.open
215    }
216
217    /// The nested page on show, or `None` on the first page.
218    pub fn page(&self) -> Option<&Page<Id>> {
219        let id = self.stack.last()?;
220        self.pages.iter().find(|page| page.id == *id)
221    }
222
223    /// The id of the nested page on show.
224    pub fn page_id(&self) -> Option<&Id> {
225        self.stack.last()
226    }
227
228    /// How many nested pages are open.
229    pub fn depth(&self) -> usize {
230        self.stack.len()
231    }
232
233    /// Recent commands, newest first.
234    pub fn recent(&self) -> &[Id] {
235        &self.recent
236    }
237
238    /// The command list on show, with its query, results and highlight.
239    pub fn command(&self) -> &command::State<Id> {
240        &self.command
241    }
242
243    pub fn query(&self) -> &str {
244        self.command.query()
245    }
246
247    /// Replaces the first page's groups, such as when a label changes.
248    pub fn set_groups(&mut self, groups: impl IntoIterator<Item = Group<Id>>) {
249        self.root = groups.into_iter().collect();
250        if self.stack.is_empty() {
251            self.rebuild(self.command.query().to_owned());
252        }
253    }
254
255    /// Applies an event and returns what the app may need to act on.
256    pub fn update(&mut self, event: Event<Id>) -> Option<Output<Id>> {
257        match event {
258            Event::Open => self.open(),
259            Event::Close => {
260                self.open = false;
261                None
262            }
263            Event::Toggle if self.open => {
264                self.open = false;
265                None
266            }
267            Event::Toggle => self.open(),
268            Event::Back => self.back(),
269            Event::Command(command::Event::Input(query)) => self.input(query),
270            Event::Command(event) => match self.command.update(event)? {
271                command::Output::Ready(sender) => Some(Output::Ready(sender)),
272                command::Output::Search(query) => Some(Output::Search(query)),
273                command::Output::Activated(id) => self.activate(id),
274                command::Output::Closed if self.stack.is_empty() => {
275                    self.open = false;
276                    None
277                }
278                command::Output::Closed => self.back(),
279            },
280        }
281    }
282
283    /// Turns a key press into an event: a toggle chord at any time, and
284    /// Back only while a nested page is open with an empty query, so
285    /// Backspace still deletes text.
286    pub fn key_event(&self, keymap: &Keymap<Action>, key: &keys::Event) -> Option<Event<Id>> {
287        keymap
288            .resolve_event(key)
289            .and_then(|action| action.event(self))
290    }
291
292    fn open(&mut self) -> Option<Output<Id>> {
293        let had_query = !self.command.query().is_empty();
294        self.open = true;
295        self.stack.clear();
296        self.rebuild(String::new());
297        had_query.then(|| Output::Search(String::new()))
298    }
299
300    fn back(&mut self) -> Option<Output<Id>> {
301        self.stack.pop()?;
302        let had_query = !self.command.query().is_empty();
303        self.rebuild(String::new());
304        had_query.then(|| Output::Search(String::new()))
305    }
306
307    fn input(&mut self, query: String) -> Option<Output<Id>> {
308        let shows_recent = self.stack.is_empty() && !self.recent.is_empty();
309        let was_empty = self.command.query().is_empty();
310        if shows_recent && was_empty != query.is_empty() {
311            self.rebuild(query.clone());
312            return Some(Output::Search(query));
313        }
314        match self.command.update(command::Event::Input(query))? {
315            command::Output::Search(query) => Some(Output::Search(query)),
316            _ => None,
317        }
318    }
319
320    fn activate(&mut self, id: Id) -> Option<Output<Id>> {
321        if self.pages.iter().any(|page| page.id == id) {
322            self.stack.push(id);
323            self.rebuild(String::new());
324            return None;
325        }
326        self.remember(id.clone());
327        self.open = false;
328        Some(Output::Activated(id))
329    }
330
331    /// Puts `id` first among the recent commands.
332    fn remember(&mut self, id: Id) {
333        self.recent.retain(|recent| *recent != id);
334        self.recent.insert(0, id);
335        self.recent.truncate(self.recent_limit);
336    }
337
338    /// The groups the list shows for the page on show: with the recent
339    /// commands first on the first page while the query is empty.
340    fn groups(&self, query: &str) -> Vec<Group<Id>> {
341        let Some(id) = self.stack.last() else {
342            let mut groups = Vec::with_capacity(self.root.len() + 1);
343            let recent: Vec<Item<Id>> = self
344                .recent
345                .iter()
346                .filter_map(|id| self.find(id).cloned())
347                .collect();
348            if query.is_empty() && !recent.is_empty() {
349                groups.push(group(RECENT_LABEL, recent));
350            }
351            groups.extend(self.root.iter().cloned());
352            return groups;
353        };
354        self.pages
355            .iter()
356            .find(|page| page.id == *id)
357            .map(|page| page.groups.clone())
358            .unwrap_or_default()
359    }
360
361    /// The first item with `id` on any page.
362    fn find(&self, id: &Id) -> Option<&Item<Id>> {
363        self.root
364            .iter()
365            .chain(self.pages.iter().flat_map(|page| &page.groups))
366            .flat_map(|group| &group.items)
367            .find(|item| item.id == *id)
368    }
369
370    /// Replaces the command list with the page on show, keeping focus.
371    fn rebuild(&mut self, query: String) {
372        let focused = self.command.is_focused();
373        self.command = command::State::new(self.groups(&query)).with_visible_rows(self.rows);
374        if !query.is_empty() {
375            let _ = self.command.update(command::Event::Input(query));
376        }
377        if focused {
378            let _ = self.command.update(command::Event::Focus(true));
379        }
380    }
381}
382
383/// Owns the command list's results channel. Emits [`command::Event::Ready`]
384/// first, then batches, wrapped in [`Event::Command`].
385pub fn subscription<Id: Send + 'static>() -> Subscription<Event<Id>> {
386    command::subscription().map(Event::Command)
387}
388
389/// What a command palette keyboard shortcut does.
390#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
391pub enum Action {
392    /// Opens the palette, or closes it while it is open.
393    Toggle,
394    /// Returns to the page before.
395    Back,
396}
397
398impl Action {
399    /// The [`Event`] this action sends to `state`, or `None` when it would
400    /// do nothing, so the key reaches the search field instead.
401    pub fn event<Id: Clone + PartialEq>(self, state: &State<Id>) -> Option<Event<Id>> {
402        match self {
403            Action::Toggle => Some(Event::Toggle),
404            Action::Back => {
405                let back = state.open && !state.stack.is_empty() && state.query().is_empty();
406                back.then_some(Event::Back)
407            }
408        }
409    }
410}
411
412impl keys::Action for Action {
413    const ALL: &'static [Self] = &[Action::Toggle, Action::Back];
414
415    fn defaults() -> Keymap<Self> {
416        default_keymap()
417    }
418
419    fn name(self) -> &'static str {
420        match self {
421            Action::Toggle => "Toggle",
422            Action::Back => "Back",
423        }
424    }
425
426    fn description(self) -> &'static str {
427        match self {
428            Action::Toggle => "Opens the palette from anywhere, or closes it.",
429            Action::Back => "Returns to the page before, while the query is empty.",
430        }
431    }
432}
433
434/// The default command palette shortcuts:
435///
436/// | Keys | Action |
437/// | --- | --- |
438/// | `Ctrl+K`, `Ctrl+Shift+P` | [`Action::Toggle`] |
439/// | `Backspace` | [`Action::Back`] |
440///
441/// Ctrl is Cmd on macOS. Route presses from [`keys::subscription`] through
442/// [`State::key_event`] so the toggle works anywhere; the open dialog lets
443/// the toggle chords through to the app. Back only claims Backspace on a
444/// nested page with an empty query. The command list inside keeps its own
445/// keys (arrows, Enter and Escape) through [`CommandPalette::command_keymap`].
446pub fn default_keymap() -> Keymap<Action> {
447    Keymap::new()
448        .bind(Chord::character('k').command(), Action::Toggle)
449        .bind(Chord::character('p').command().shift(), Action::Toggle)
450        .bind(Chord::named(Named::Backspace), Action::Back)
451}
452
453type OnEvent<'a, Id, Message> = Rc<dyn Fn(Event<Id>) -> Message + 'a>;
454
455/// A command palette builder. Convert it into an [`Element`] to render.
456pub struct CommandPalette<'a, Id, Message> {
457    state: &'a State<Id>,
458    base: Element<'a, Message>,
459    title: String,
460    placeholder: String,
461    empty: Option<String>,
462    loading: bool,
463    max_height: f32,
464    size: dialog::Size,
465    keymap: Keymap<Action>,
466    command_keymap: Keymap<command::Action>,
467    dialog_keymap: Keymap<dialog::Action>,
468    shortcuts: Shortcuts,
469    on_event: Option<Box<dyn Fn(Event<Id>) -> Message + 'a>>,
470}
471
472impl<Id: std::fmt::Debug, Message> std::fmt::Debug for CommandPalette<'_, Id, Message> {
473    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474        f.debug_struct("CommandPalette")
475            .field("state", self.state)
476            .field("title", &self.title)
477            .field("placeholder", &self.placeholder)
478            .field("loading", &self.loading)
479            .field("max_height", &self.max_height)
480            .field("size", &self.size)
481            .finish_non_exhaustive()
482    }
483}
484
485/// Wraps `base`, the app the palette opens over. Without
486/// [`on_event`](CommandPalette::on_event) the list renders disabled.
487pub fn command_palette<'a, Id, Message>(
488    state: &'a State<Id>,
489    base: impl Into<Element<'a, Message>>,
490) -> CommandPalette<'a, Id, Message> {
491    CommandPalette {
492        state,
493        base: base.into(),
494        title: DEFAULT_TITLE.to_owned(),
495        placeholder: "Type a command or search...".to_owned(),
496        empty: None,
497        loading: false,
498        max_height: 400.0,
499        size: dialog::Size::Md,
500        keymap: default_keymap(),
501        command_keymap: command::default_keymap(),
502        dialog_keymap: dialog::default_keymap(),
503        shortcuts: Shortcuts::all(),
504        on_event: None,
505    }
506}
507
508impl<'a, Id, Message> CommandPalette<'a, Id, Message> {
509    /// The dialog title on the first page. Nested pages show their own.
510    pub fn title(mut self, title: impl Into<String>) -> Self {
511        self.title = title.into();
512        self
513    }
514
515    /// The search field's placeholder, unless the page sets its own.
516    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
517        self.placeholder = placeholder.into();
518        self
519    }
520
521    /// Text shown when nothing matches the query.
522    pub fn empty(mut self, empty: impl Into<String>) -> Self {
523        self.empty = Some(empty.into());
524        self
525    }
526
527    /// Shows that a background search is still running.
528    pub fn loading(mut self, loading: bool) -> Self {
529        self.loading = loading;
530        self
531    }
532
533    /// Caps the list's height in pixels. It shrinks around a few results.
534    pub fn max_height(mut self, max_height: f32) -> Self {
535        self.max_height = max_height;
536        self
537    }
538
539    /// The dialog's maximum width. Defaults to [`dialog::Size::Md`].
540    pub fn size(mut self, size: dialog::Size) -> Self {
541        self.size = size;
542        self
543    }
544
545    /// Replaces the [`default_keymap`]: the toggle chords and Back.
546    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
547        self.keymap = keymap;
548        self
549    }
550
551    /// Replaces the [command list keys](command::default_keymap).
552    pub fn command_keymap(mut self, keymap: Keymap<command::Action>) -> Self {
553        self.command_keymap = keymap;
554        self
555    }
556
557    /// Sets which editing [`Shortcut`](crate::primitives::input::Shortcut)s
558    /// the search field handles. All of them by default.
559    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
560        self.shortcuts = shortcuts;
561        self
562    }
563
564    /// Replaces the [dialog keys](dialog::default_keymap).
565    pub fn dialog_keymap(mut self, keymap: Keymap<dialog::Action>) -> Self {
566        self.dialog_keymap = keymap;
567        self
568    }
569
570    pub fn on_event(mut self, on_event: impl Fn(Event<Id>) -> Message + 'a) -> Self {
571        self.on_event = Some(Box::new(on_event));
572        self
573    }
574}
575
576impl<'a, Id, Message> From<CommandPalette<'a, Id, Message>> for Element<'a, Message>
577where
578    Id: Clone + PartialEq + 'a,
579    Message: Clone + 'a,
580{
581    fn from(palette: CommandPalette<'a, Id, Message>) -> Self {
582        let CommandPalette {
583            state,
584            base,
585            title,
586            placeholder,
587            empty,
588            loading,
589            max_height,
590            size,
591            keymap,
592            command_keymap,
593            dialog_keymap,
594            shortcuts,
595            on_event,
596        } = palette;
597        let on_event: Option<OnEvent<'a, Id, Message>> = on_event.map(Rc::from);
598        let page = state.page();
599        let title = page.map_or(title, |page| page.title.clone());
600        let placeholder = page
601            .and_then(|page| page.placeholder.clone())
602            .unwrap_or(placeholder);
603        let toggles: Vec<Chord> = keymap
604            .chords(&Action::Toggle)
605            .into_iter()
606            .cloned()
607            .collect();
608
609        let mut list = command(&state.command)
610            .placeholder(placeholder)
611            .loading(loading)
612            .max_height(max_height)
613            .id(SEARCH_ID)
614            .keymap(command_keymap)
615            .shortcuts(shortcuts);
616        if let Some(empty) = empty {
617            list = list.empty(empty);
618        }
619
620        let mut palette = dialog(base)
621            .open(state.open)
622            .title(title)
623            .size(size)
624            .close_button(false)
625            .id(DIALOG_ID)
626            .keymap(dialog_keymap)
627            .pass_through(toggles);
628        let Some(on_event) = on_event else {
629            return palette.body(list).into();
630        };
631
632        if !state.stack.is_empty() {
633            palette = palette.action(
634                button("Back")
635                    .icon(crate::lucide!(ChevronLeft))
636                    .variant(Variant::Ghost)
637                    .size(button::Size::Sm)
638                    .on_press(on_event(Event::Back)),
639            );
640        }
641        let on_list = on_event.clone();
642        let on_key = on_event.clone();
643        let body = anchored(list.on_event(move |event| on_list(Event::Command(event))))
644            .dismiss_keys([])
645            .on_key(move |key| state.key_event(&keymap, key).map(&*on_key));
646        palette.body(body).on_dismiss(on_event(Event::Close)).into()
647    }
648}
649
650#[cfg(test)]
651mod tests {
652    use super::*;
653    use crate::navigation::command::item;
654    use iced::keyboard::{Key, Modifiers};
655
656    fn state() -> State<&'static str> {
657        State::new([
658            group(
659                "Files",
660                [item("new", "New file"), item("open", "Open file")],
661            ),
662            group(
663                "Preferences",
664                [
665                    item("theme", "Change theme..."),
666                    item("settings", "Settings"),
667                ],
668            ),
669        ])
670        .with_page(
671            page(
672                "theme",
673                "Theme",
674                [group("", [item("light", "Light"), item("dark", "Dark")])],
675            )
676            .placeholder("Pick a theme..."),
677        )
678    }
679
680    fn opened() -> State<&'static str> {
681        let mut state = state();
682        let _ = state.update(Event::Open);
683        state
684    }
685
686    fn labels(state: &State<&'static str>) -> Vec<(String, String)> {
687        state
688            .command()
689            .results()
690            .map(|(group, item)| (group.to_owned(), item.label.clone()))
691            .collect()
692    }
693
694    fn run(state: &mut State<&'static str>, id: &'static str) -> Option<Output<&'static str>> {
695        let position = state
696            .command()
697            .results()
698            .position(|(_, item)| item.id == id)
699            .expect("the item is listed");
700        state.update(Event::Command(command::Event::Activate(position)))
701    }
702
703    #[test]
704    fn starts_closed_on_the_first_page_with_nothing_recent() {
705        let state = state();
706        assert!(!state.is_open());
707        assert_eq!(state.depth(), 0);
708        assert!(state.page().is_none() && state.page_id().is_none());
709        assert!(state.recent().is_empty());
710        assert_eq!(state.command().len(), 4);
711        assert_eq!(state.query(), "");
712    }
713
714    #[test]
715    fn open_close_and_toggle() {
716        let mut state = state();
717        assert!(state.update(Event::Open).is_none());
718        assert!(state.is_open());
719        let _ = state.update(Event::Close);
720        assert!(!state.is_open());
721        let _ = state.update(Event::Toggle);
722        assert!(state.is_open());
723        let _ = state.update(Event::Toggle);
724        assert!(!state.is_open());
725    }
726
727    #[test]
728    fn running_a_command_closes_and_remembers_it() {
729        let mut state = opened();
730        assert!(matches!(
731            run(&mut state, "settings"),
732            Some(Output::Activated("settings"))
733        ));
734        assert!(!state.is_open());
735        assert_eq!(state.recent(), ["settings"]);
736
737        let _ = state.update(Event::Open);
738        let first = labels(&state).into_iter().next();
739        assert_eq!(first, Some(("Recent".into(), "Settings".into())));
740    }
741
742    #[test]
743    fn recent_commands_are_newest_first_unique_and_capped() {
744        let mut state = state().with_recent_limit(2);
745        for id in ["new", "open", "new", "settings"] {
746            let _ = state.update(Event::Open);
747            let _ = run(&mut state, id);
748        }
749        assert_eq!(state.recent(), ["settings", "new"]);
750
751        let off = self::state().with_recent_limit(0).with_recent(["new"]);
752        assert!(off.recent().is_empty());
753    }
754
755    #[test]
756    fn recent_items_from_nested_pages_are_found() {
757        let state = state().with_recent(["dark", "missing"]);
758        let recent: Vec<_> = labels(&state)
759            .into_iter()
760            .filter(|(group, _)| group == RECENT_LABEL)
761            .map(|(_, label)| label)
762            .collect();
763        assert_eq!(recent, ["Dark"], "unknown ids are skipped");
764    }
765
766    #[test]
767    fn typing_hides_the_recent_group_and_clearing_brings_it_back() {
768        let mut state = state().with_recent(["open"]);
769        let _ = state.update(Event::Open);
770        let output = state.update(Event::Command(command::Event::Input("fi".into())));
771        assert!(matches!(output, Some(Output::Search(query)) if query == "fi"));
772        assert!(
773            labels(&state)
774                .iter()
775                .all(|(group, _)| group != RECENT_LABEL)
776        );
777        assert_eq!(state.query(), "fi");
778
779        let output = state.update(Event::Command(command::Event::Input("fil".into())));
780        assert!(matches!(output, Some(Output::Search(query)) if query == "fil"));
781
782        let output = state.update(Event::Command(command::Event::Input(String::new())));
783        assert!(matches!(output, Some(Output::Search(query)) if query.is_empty()));
784        assert_eq!(labels(&state)[0].0, RECENT_LABEL);
785    }
786
787    #[test]
788    fn a_page_item_opens_its_page_instead_of_running() {
789        let mut state = opened();
790        assert!(run(&mut state, "theme").is_none());
791        assert!(state.is_open());
792        assert_eq!(state.depth(), 1);
793        assert_eq!(state.page_id(), Some(&"theme"));
794        assert_eq!(state.page().map(|page| page.title.as_str()), Some("Theme"));
795        let items: Vec<_> = labels(&state).into_iter().map(|(_, label)| label).collect();
796        assert_eq!(items, ["Light", "Dark"]);
797
798        assert!(matches!(
799            run(&mut state, "dark"),
800            Some(Output::Activated("dark"))
801        ));
802        assert!(!state.is_open());
803        assert_eq!(state.recent(), ["dark"], "the page itself is not recent");
804    }
805
806    #[test]
807    fn back_returns_to_the_page_before() {
808        let mut state = opened();
809        let _ = run(&mut state, "theme");
810        assert!(state.update(Event::Back).is_none());
811        assert_eq!(state.depth(), 0);
812        assert_eq!(state.command().len(), 4);
813        assert!(state.update(Event::Back).is_none(), "nothing to go back to");
814        assert!(state.is_open());
815    }
816
817    #[test]
818    fn going_back_with_a_query_clears_it() {
819        let mut state = opened();
820        let _ = run(&mut state, "theme");
821        let _ = state.update(Event::Command(command::Event::Input("da".into())));
822        let output = state.update(Event::Back);
823        assert!(matches!(output, Some(Output::Search(query)) if query.is_empty()));
824        assert_eq!(state.query(), "");
825    }
826
827    #[test]
828    fn escape_on_an_empty_query_goes_back_then_closes() {
829        let mut state = opened();
830        let _ = run(&mut state, "theme");
831        let _ = state.update(Event::Command(command::Event::Close));
832        assert_eq!(state.depth(), 0);
833        assert!(state.is_open());
834        let _ = state.update(Event::Command(command::Event::Close));
835        assert!(!state.is_open());
836    }
837
838    #[test]
839    fn opening_again_starts_on_the_first_page() {
840        let mut state = opened();
841        let _ = run(&mut state, "theme");
842        let _ = state.update(Event::Command(command::Event::Input("li".into())));
843        let _ = state.update(Event::Close);
844        let output = state.update(Event::Open);
845        assert!(matches!(output, Some(Output::Search(query)) if query.is_empty()));
846        assert_eq!(state.depth(), 0);
847        assert_eq!(state.query(), "");
848    }
849
850    #[test]
851    fn focus_survives_a_page_change() {
852        let mut state = opened();
853        let _ = state.update(Event::Command(command::Event::Focus(true)));
854        let _ = run(&mut state, "theme");
855        assert!(state.command().is_focused());
856        assert!(state.command().shows_highlight());
857    }
858
859    #[test]
860    fn set_groups_replaces_the_first_page() {
861        let mut state = opened();
862        state.set_groups([group("Only", [item("one", "One")])]);
863        assert_eq!(labels(&state), [("Only".into(), "One".into())]);
864
865        let _ = state.update(Event::Open);
866        state.set_groups([group("Only", [item("theme", "Change theme...")])]);
867        let _ = run(&mut state, "theme");
868        state.set_groups([group("Other", [item("two", "Two")])]);
869        assert_eq!(state.depth(), 1, "a nested page stays on show");
870    }
871
872    #[test]
873    fn channel_events_pass_through() {
874        let mut state = opened();
875        let (sender, _receiver) = iced::futures::channel::mpsc::channel(1);
876        let output = state.update(Event::Command(command::Event::Ready(sender)));
877        assert!(matches!(output, Some(Output::Ready(_))));
878
879        let _ = state.update(Event::Command(command::Event::Input("xyz".into())));
880        let _ = state.update(Event::Command(command::Event::Received(vec![
881            command::results("xyz", "Files", [item("remote", "xyz.txt")]),
882        ])));
883        assert!(labels(&state).contains(&("Files".into(), "xyz.txt".into())));
884    }
885
886    fn key(key: Key, modifiers: Modifiers) -> keys::Event {
887        keys::Event { key, modifiers }
888    }
889
890    #[test]
891    fn toggle_chords_work_anywhere_and_back_only_on_a_nested_empty_page() {
892        let keymap = default_keymap();
893        let mut state = state();
894        let ctrl_k = key(Key::Character("k".into()), Modifiers::COMMAND);
895        let ctrl_shift_p = key(
896            Key::Character("P".into()),
897            Modifiers::COMMAND | Modifiers::SHIFT,
898        );
899        let backspace = key(Key::Named(Named::Backspace), Modifiers::empty());
900        assert!(matches!(
901            state.key_event(&keymap, &ctrl_k),
902            Some(Event::Toggle)
903        ));
904        assert!(matches!(
905            state.key_event(&keymap, &ctrl_shift_p),
906            Some(Event::Toggle)
907        ));
908        assert!(state.key_event(&keymap, &backspace).is_none());
909
910        let _ = state.update(Event::Open);
911        assert!(state.key_event(&keymap, &backspace).is_none(), "first page");
912        let _ = run(&mut state, "theme");
913        assert!(matches!(
914            state.key_event(&keymap, &backspace),
915            Some(Event::Back)
916        ));
917        let _ = state.update(Event::Command(command::Event::Input("d".into())));
918        assert!(
919            state.key_event(&keymap, &backspace).is_none(),
920            "Backspace deletes text"
921        );
922    }
923
924    #[test]
925    fn default_keymap_covers_every_action() {
926        let keymap = default_keymap();
927        assert_eq!(keymap.chords(&Action::Toggle).len(), 2);
928        assert_eq!(
929            keymap.chords(&Action::Back),
930            [&Chord::named(Named::Backspace)]
931        );
932        assert_eq!(Keymap::<Action>::defaults(), keymap);
933        for &action in <Action as keys::Action>::ALL {
934            assert!(!keys::Action::name(action).is_empty());
935            assert!(keys::Action::description(action).ends_with('.'));
936        }
937    }
938
939    #[test]
940    fn keymap_overrides_and_unbinding() {
941        let keymap = default_keymap()
942            .unbind_action(&Action::Back)
943            .bind(Chord::named(Named::F1), Action::Toggle);
944        let mut state = opened();
945        let _ = run(&mut state, "theme");
946        let backspace = key(Key::Named(Named::Backspace), Modifiers::empty());
947        let f1 = key(Key::Named(Named::F1), Modifiers::empty());
948        assert!(state.key_event(&keymap, &backspace).is_none());
949        assert!(matches!(state.key_event(&keymap, &f1), Some(Event::Toggle)));
950    }
951
952    #[test]
953    fn builder_defaults_and_overrides() {
954        let state = state();
955        let palette: CommandPalette<'_, &str, ()> = command_palette(&state, widget::text("App"));
956        assert_eq!(palette.title, DEFAULT_TITLE);
957        assert!(palette.empty.is_none());
958        assert!(!palette.loading);
959        assert_eq!(palette.size, dialog::Size::Md);
960        assert_eq!(palette.keymap, default_keymap());
961        assert_eq!(palette.command_keymap, command::default_keymap());
962        assert_eq!(palette.dialog_keymap, dialog::default_keymap());
963        assert!(palette.on_event.is_none());
964
965        let palette: CommandPalette<'_, &str, ()> = command_palette(&state, widget::text("App"))
966            .title("Go to")
967            .placeholder("Search...")
968            .empty("Nothing here.")
969            .loading(true)
970            .max_height(200.0)
971            .size(dialog::Size::Lg)
972            .keymap(Keymap::new())
973            .command_keymap(Keymap::new())
974            .dialog_keymap(Keymap::new())
975            .on_event(|_| ());
976        assert_eq!(palette.title, "Go to");
977        assert_eq!(palette.placeholder, "Search...");
978        assert_eq!(palette.empty.as_deref(), Some("Nothing here."));
979        assert!(palette.loading);
980        assert_eq!(palette.max_height, 200.0);
981        assert_eq!(palette.size, dialog::Size::Lg);
982        assert!(palette.keymap.is_empty() && palette.command_keymap.is_empty());
983        assert!(palette.dialog_keymap.is_empty() && palette.on_event.is_some());
984    }
985}