1use 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
80pub const CHANNEL_CAPACITY: usize = 64;
82pub const BATCH_SIZE: usize = 32;
84pub const VISIBLE_ROWS: usize = 8;
86pub const DEFAULT_EMPTY: &str = "No results found.";
88pub 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;
102const KEYWORD_PENALTY: u32 = 500;
104
105pub 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
152fn 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
171fn 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#[derive(Debug, Clone, PartialEq)]
205pub struct Item<Id> {
206 pub id: Id,
207 pub label: String,
208 pub icon: Option<Glyph>,
209 pub shortcut: Option<String>,
211 pub keywords: Vec<String>,
213 pub disabled: bool,
214 pub destructive: bool,
215}
216
217pub 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 pub fn disabled(mut self, disabled: bool) -> Self {
248 self.disabled = disabled;
249 self
250 }
251
252 pub fn destructive(mut self, destructive: bool) -> Self {
254 self.destructive = destructive;
255 self
256 }
257
258 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#[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#[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
306pub type Sender<Id> = mpsc::Sender<Results<Id>>;
308
309#[derive(Debug, Clone)]
311pub enum Event<Id> {
312 Ready(Sender<Id>),
314 Received(Vec<Results<Id>>),
316 Input(String),
318 Next,
320 Previous,
322 First,
323 Last,
324 ActivateHighlighted,
326 Close,
328 Highlight(usize),
330 Activate(usize),
332 Scroll(i32),
334 Focus(bool),
336}
337
338#[derive(Debug, Clone)]
340pub enum Output<Id> {
341 Ready(Sender<Id>),
342 Search(String),
344 Activated(Id),
346 Closed,
349}
350
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352struct Entry {
353 remote: bool,
354 group: usize,
355 item: usize,
356}
357
358#[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 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 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 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 pub fn highlighted(&self) -> Option<&Item<Id>> {
424 self.highlighted.and_then(|position| self.item_at(position))
425 }
426
427 pub fn highlighted_position(&self) -> Option<usize> {
429 self.highlighted
430 }
431
432 pub fn shows_highlight(&self) -> bool {
436 self.focused || self.navigated
437 }
438
439 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 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 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 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 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 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 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 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#[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 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
722pub 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
748pub fn subscription<Id: Send + 'static>() -> Subscription<Event<Id>> {
750 Subscription::run(stream::<Id>)
751}
752
753pub 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
759pub fn batches<T>(receiver: impl Stream<Item = T>) -> impl Stream<Item = Vec<T>> {
761 receiver.ready_chunks(BATCH_SIZE)
762}
763
764pub 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
782pub 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 pub fn empty(mut self, empty: impl Into<String>) -> Self {
820 self.empty = empty.into();
821 self
822 }
823
824 pub fn loading(mut self, loading: bool) -> Self {
826 self.loading = loading;
827 self
828 }
829
830 pub fn width(mut self, width: impl Into<Length>) -> Self {
832 self.width = width.into();
833 self
834 }
835
836 pub fn height(mut self, height: impl Into<Length>) -> Self {
839 self.height = height.into();
840 self
841 }
842
843 pub fn max_height(mut self, max_height: f32) -> Self {
847 self.max_height = max_height;
848 self
849 }
850
851 pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
854 self.id = Some(id.into());
855 self
856 }
857
858 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
860 self.keymap = keymap;
861 self
862 }
863
864 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 let list = container(list).height(if height == Length::Shrink {
905 Length::Shrink
906 } else {
907 Length::Fill
908 });
909 let on_input = on_event.clone().map(|on_event| {
910 Box::new(move |query| on_event(Event::Input(query)))
911 as Box<dyn Fn(String) -> Message + 'a>
912 });
913
914 let surface = container(column![
915 search_field(&placeholder, &state.query, id, on_input, shortcuts),
916 container(widget::space())
917 .width(Length::Fill)
918 .height(1)
919 .style(|theme| divider_style(&Tokens::of(theme))),
920 list,
921 ])
922 .width(width)
923 .height(height)
924 .max_height(max_height)
925 .clip(true)
926 .style(|theme| surface_style(&Tokens::of(theme)));
927
928 let Some(on_event) = on_event else {
929 return surface.into();
930 };
931 let on_focus = on_event.clone();
932 anchored(surface)
933 .dismiss_keys([])
934 .on_focus(move |focused| on_focus(Event::Focus(focused)))
935 .on_key(move |key| {
936 keymap
937 .resolve_event(key)
938 .and_then(|action| action.event(state))
939 .map(&*on_event)
940 })
941 .into()
942 }
943}
944
945fn search_field<'a, Message: Clone + 'a>(
946 placeholder: &str,
947 value: &str,
948 id: Option<widget::Id>,
949 on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
950 shortcuts: Shortcuts,
951) -> Element<'a, Message> {
952 let enabled = on_input.is_some();
953 let vertical = (SEARCH_HEIGHT - text_size::SM * LINE_HEIGHT) / 2.0;
954 let mut text = widget::text_input(placeholder, value)
955 .size(text_size::SM)
956 .line_height(LineHeight::Relative(LINE_HEIGHT))
957 .padding(Padding {
958 top: vertical,
959 bottom: vertical,
960 left: space::MD + ICON_SIZE + space::SM,
961 right: space::MD,
962 })
963 .width(Length::Fill)
964 .style(|theme, status| search_style(&Tokens::of(theme), status));
965 if let Some(id) = id {
966 text = text.id(id);
967 }
968 let keymap = input::default_keymap();
969 let input = input::with_shortcuts(text, value, false, on_input, keymap, shortcuts);
970
971 let icon = themed(
972 crate::lucide!(Search),
973 menu::ICON_SIZE,
974 opacity(enabled),
975 |theme| Tokens::of(theme).muted_foreground,
976 );
977
978 stack![
979 input,
980 container(icon)
981 .height(Length::Fill)
982 .align_y(Alignment::Center)
983 .padding(Padding::ZERO.left(space::MD)),
984 ]
985 .into()
986}
987
988fn list<'a, Id, Message: Clone + 'a>(
989 state: &'a State<Id>,
990 empty: &str,
991 loading: bool,
992 on_event: Option<&(dyn Fn(Event<Id>) -> Message + 'a)>,
993) -> Element<'a, Message> {
994 let mut children: Vec<Element<'a, Message>> = Vec::new();
995 let mut previous: Option<(bool, usize)> = None;
996
997 for position in state.visible() {
998 let Some(&entry) = state.entries.get(position) else {
999 continue;
1000 };
1001 let Some(group) = state.group(entry) else {
1002 continue;
1003 };
1004 let Some(item) = group.items.get(entry.item) else {
1005 continue;
1006 };
1007
1008 let key = (entry.remote, entry.group);
1009 if previous != Some(key) {
1010 if previous.is_some() {
1011 children.push(menu::separator());
1012 }
1013 if !group.label.is_empty() {
1014 children.push(menu::group_label(&group.label, false));
1015 }
1016 previous = Some(key);
1017 }
1018
1019 let enabled = on_event.is_some() && !item.disabled;
1020 let status = if !enabled {
1021 RowStatus::Disabled
1022 } else if state.shows_highlight() && state.highlighted == Some(position) {
1023 RowStatus::Highlighted
1024 } else {
1025 RowStatus::Idle
1026 };
1027 let messages = on_event.filter(|_| enabled).map(|on_event| {
1028 (
1029 on_event(Event::Highlight(position)),
1030 on_event(Event::Activate(position)),
1031 )
1032 });
1033 let parts = Parts {
1034 icon: item.icon,
1035 hint: item.shortcut.as_deref(),
1036 ..Parts::label(&item.label)
1037 };
1038 children.push(menu::item(parts, status, item.destructive, messages));
1039 }
1040
1041 if children.is_empty() {
1042 return menu::empty(if loading { SEARCHING } else { empty });
1043 }
1044 if loading {
1045 children.push(menu::inset(
1046 container(muted(SEARCHING.to_owned(), text_size::SM)).padding(ROW_PADDING),
1047 ));
1048 }
1049
1050 let rows = Column::from_vec(children)
1051 .padding([space::XS, 0.0])
1052 .width(Length::Fill);
1053 let Some(on_event) = on_event else {
1054 return rows.into();
1055 };
1056 let down = on_event(Event::Scroll(1));
1057 let up = on_event(Event::Scroll(-1));
1058 mouse_area(rows)
1059 .on_scroll(move |delta| match delta {
1060 ScrollDelta::Lines { y, .. } | ScrollDelta::Pixels { y, .. } if y < 0.0 => down.clone(),
1061 _ => up.clone(),
1062 })
1063 .into()
1064}
1065
1066fn muted<'a, Message: 'a>(content: String, size: f32) -> Element<'a, Message> {
1067 text(content)
1068 .size(size)
1069 .line_height(LineHeight::Absolute(menu::LINE_HEIGHT.into()))
1070 .style(|theme: &Theme| text::Style {
1071 color: Some(Tokens::of(theme).muted_foreground),
1072 })
1073 .into()
1074}
1075
1076pub fn search_style(tokens: &Tokens, status: Status) -> text_input::Style {
1078 let style = text_input::Style {
1079 background: Background::Color(Color::TRANSPARENT),
1080 border: Border::default(),
1081 icon: tokens.muted_foreground,
1082 placeholder: tokens.muted_foreground,
1083 value: tokens.foreground,
1084 selection: fade(tokens.primary, 0.25),
1085 };
1086 if status != Status::Disabled {
1087 return style;
1088 }
1089 text_input::Style {
1090 placeholder: fade(style.placeholder, 0.5),
1091 value: fade(style.value, 0.5),
1092 icon: fade(style.icon, 0.5),
1093 selection: Color::TRANSPARENT,
1094 ..style
1095 }
1096}
1097
1098pub fn divider_style(tokens: &Tokens) -> container::Style {
1100 container::Style {
1101 background: Some(Background::Color(tokens.border)),
1102 ..container::Style::default()
1103 }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108 use super::*;
1109 use crate::theme::{dark, light};
1110 use futures::SinkExt;
1111 use futures::executor::block_on;
1112
1113 fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
1114 let chord: Chord = chord.parse().unwrap();
1115 keymap.resolve(chord.key(), chord.modifiers())
1116 }
1117
1118 fn sample() -> State<&'static str> {
1119 State::new([
1120 group(
1121 "Suggestions",
1122 [
1123 item("calendar", "Calendar"),
1124 item("emoji", "Search emoji").keywords(["smiley"]),
1125 item("calculator", "Calculator").disabled(true),
1126 ],
1127 ),
1128 group(
1129 "Settings",
1130 [
1131 item("profile", "Profile").shortcut("Ctrl+P"),
1132 item("billing", "Billing"),
1133 item("settings", "Settings"),
1134 ],
1135 ),
1136 ])
1137 }
1138
1139 fn ids(state: &State<&'static str>) -> Vec<&'static str> {
1140 state.results().map(|(_, item)| item.id).collect()
1141 }
1142
1143 fn highlighted(state: &State<&'static str>) -> Option<&'static str> {
1144 state.highlighted().map(|item| item.id)
1145 }
1146
1147 #[test]
1148 fn empty_query_matches_everything_equally() {
1149 assert_eq!(score("", "Anything"), Some(0));
1150 assert_eq!(score(" ", "Anything"), Some(0));
1151 }
1152
1153 #[test]
1154 fn matching_ignores_case() {
1155 assert_eq!(score("SET", "settings"), score("set", "Settings"));
1156 assert!(score("cAl", "CALENDAR").is_some());
1157 }
1158
1159 #[test]
1160 fn match_kinds_rank_in_order() {
1161 let exact = score("set", "Set");
1162 let prefix = score("set", "Settings");
1163 let word = score("set", "Reset settings");
1164 let contains = score("set", "Asset");
1165 let fuzzy = score("set", "Sheet editor");
1166 assert!(exact > prefix, "{exact:?} {prefix:?}");
1167 assert!(prefix > word, "{prefix:?} {word:?}");
1168 assert!(word > contains, "{word:?} {contains:?}");
1169 assert!(contains > fuzzy, "{contains:?} {fuzzy:?}");
1170 assert!(fuzzy.is_some());
1171 }
1172
1173 #[test]
1174 fn letters_must_appear_in_order() {
1175 assert!(score("tes", "Settings").is_none());
1176 assert!(score("xyz", "Settings").is_none());
1177 assert!(score("settings!", "Settings").is_none());
1178 }
1179
1180 #[test]
1181 fn shorter_texts_win_within_a_kind() {
1182 assert!(score("set", "Settings") > score("set", "Settings and privacy"));
1183 }
1184
1185 #[test]
1186 fn fuzzy_prefers_word_starts_and_runs() {
1187 assert!(score("ts", "Toggle sidebar") > score("ts", "Tabs list"));
1188 assert!(score("nf", "newFile") > score("nf", "notify"));
1189 assert!(score("sba", "Show bar") > score("sba", "Toggle sidebar"));
1190 assert!(score("ogl", "toggle") > score("ogl", "tobgaly"));
1191 }
1192
1193 #[test]
1194 fn keywords_find_items_but_rank_below_labels() {
1195 let emoji = item("emoji", "Search emoji").keywords(["smiley"]);
1196 assert!(emoji.score("smil").is_some());
1197 let smiley = item("smiley", "Smiley");
1198 assert!(smiley.score("smil") > emoji.score("smil"));
1199 assert!(item("x", "Plain").score("smil").is_none());
1200 }
1201
1202 #[test]
1203 fn new_state_lists_every_item_and_highlights_the_first() {
1204 let state = sample();
1205 assert_eq!(state.len(), 6);
1206 assert_eq!(highlighted(&state), Some("calendar"));
1207 assert_eq!(state.query(), "");
1208 assert!(State::<u8>::new([]).is_empty());
1209 assert!(State::<u8>::new([]).highlighted().is_none());
1210 }
1211
1212 #[test]
1213 fn the_highlight_shows_only_while_focused_or_after_navigating() {
1214 let mut state = sample();
1215 assert!(!state.shows_highlight());
1216 assert!(!state.is_focused());
1217
1218 let _ = state.update(Event::Focus(true));
1219 assert!(state.shows_highlight() && state.is_focused());
1220 let _ = state.update(Event::Focus(false));
1221 assert!(!state.shows_highlight());
1222
1223 for event in [
1224 Event::Next,
1225 Event::Previous,
1226 Event::First,
1227 Event::Last,
1228 Event::Highlight(0),
1229 ] {
1230 let mut state = sample();
1231 let _ = state.update(event);
1232 assert!(state.shows_highlight());
1233 let _ = state.update(Event::Focus(true));
1234 let _ = state.update(Event::Focus(false));
1235 assert!(!state.shows_highlight(), "leaving the field hides it again");
1236 }
1237 }
1238
1239 #[test]
1240 fn typing_or_scrolling_alone_does_not_show_the_highlight() {
1241 let mut state = sample();
1242 let _ = state.update(Event::Input("set".into()));
1243 let _ = state.update(Event::Scroll(1));
1244 assert!(!state.shows_highlight());
1245 assert!(state.highlighted().is_some(), "Enter still has a target");
1246 }
1247
1248 #[test]
1249 fn typing_filters_ranks_and_asks_for_a_search() {
1250 let mut state = sample();
1251 let output = state.update(Event::Input("cal".into()));
1252 assert!(matches!(output, Some(Output::Search(query)) if query == "cal"));
1253 assert_eq!(ids(&state), ["calendar", "calculator"]);
1254 assert_eq!(highlighted(&state), Some("calendar"));
1255
1256 let _ = state.update(Event::Input("calc".into()));
1258 assert_eq!(ids(&state), ["calculator"]);
1259 assert!(state.highlighted().is_none());
1260
1261 let _ = state.update(Event::Input("set".into()));
1262 assert_eq!(ids(&state), ["settings"]);
1263 let groups: Vec<_> = state.results().map(|(group, _)| group).collect();
1264 assert_eq!(groups, ["Settings"]);
1265
1266 assert!(state.update(Event::Input("set".into())).is_none());
1267 }
1268
1269 #[test]
1270 fn nothing_matching_leaves_nothing_highlighted() {
1271 let mut state = sample();
1272 let _ = state.update(Event::Input("zzz".into()));
1273 assert!(state.is_empty());
1274 assert!(state.highlighted().is_none());
1275 assert!(state.update(Event::ActivateHighlighted).is_none());
1276 let _ = state.update(Event::Next);
1277 assert!(state.highlighted().is_none());
1278 }
1279
1280 #[test]
1281 fn arrows_wrap_and_skip_disabled_items() {
1282 let mut state = sample();
1283 let _ = state.update(Event::Next);
1284 assert_eq!(highlighted(&state), Some("emoji"));
1285 let _ = state.update(Event::Next);
1286 assert_eq!(highlighted(&state), Some("profile"));
1287 let _ = state.update(Event::Previous);
1288 let _ = state.update(Event::Previous);
1289 let _ = state.update(Event::Previous);
1290 assert_eq!(highlighted(&state), Some("settings"));
1291 let _ = state.update(Event::Next);
1292 assert_eq!(highlighted(&state), Some("calendar"));
1293 }
1294
1295 #[test]
1296 fn typing_highlights_the_best_match_in_any_group() {
1297 let mut state = State::new([
1298 group(
1299 "Actions",
1300 [
1301 item("retry", "Retry failed jobs"),
1302 item("clear", "Clear finished jobs").destructive(true),
1303 ],
1304 ),
1305 group(
1306 "Open job",
1307 [
1308 item("ledger", "ledger-reconcile"),
1309 item("lead", "lead-import").disabled(true),
1310 ],
1311 ),
1312 ]);
1313 let _ = state.update(Event::Input("led".into()));
1314 assert_eq!(
1315 ids(&state)[..2],
1316 ["retry", "clear"],
1317 "groups keep their order"
1318 );
1319 assert_eq!(highlighted(&state), Some("ledger"));
1320
1321 let _ = state.update(Event::Input(String::new()));
1322 assert_eq!(highlighted(&state), Some("retry"), "no query, first row");
1323 }
1324
1325 #[test]
1326 fn home_and_end_jump_to_enabled_ends() {
1327 let mut state = State::new([group(
1328 "",
1329 [
1330 item(1, "One").disabled(true),
1331 item(2, "Two"),
1332 item(3, "Three"),
1333 item(4, "Four").disabled(true),
1334 ],
1335 )]);
1336 let _ = state.update(Event::Last);
1337 assert_eq!(state.highlighted().map(|i| i.id), Some(3));
1338 let _ = state.update(Event::First);
1339 assert_eq!(state.highlighted().map(|i| i.id), Some(2));
1340 }
1341
1342 #[test]
1343 fn run_and_activate_return_the_id() {
1344 let mut state = sample();
1345 let _ = state.update(Event::Next);
1346 assert!(matches!(
1347 state.update(Event::ActivateHighlighted),
1348 Some(Output::Activated("emoji"))
1349 ));
1350
1351 assert!(matches!(
1352 state.update(Event::Activate(4)),
1353 Some(Output::Activated("billing"))
1354 ));
1355 assert_eq!(highlighted(&state), Some("billing"));
1356 assert!(state.update(Event::Activate(2)).is_none());
1357 assert!(state.update(Event::Activate(99)).is_none());
1358 }
1359
1360 #[test]
1361 fn hovering_a_disabled_row_keeps_the_highlight() {
1362 let mut state = sample();
1363 let _ = state.update(Event::Highlight(2));
1364 assert_eq!(highlighted(&state), Some("calendar"));
1365 let _ = state.update(Event::Highlight(3));
1366 assert_eq!(highlighted(&state), Some("profile"));
1367 }
1368
1369 #[test]
1370 fn clear_empties_the_query_then_dismisses() {
1371 let mut state = sample();
1372 let _ = state.update(Event::Input("bill".into()));
1373 let output = state.update(Event::Close);
1374 assert!(matches!(output, Some(Output::Search(query)) if query.is_empty()));
1375 assert_eq!(state.len(), 6);
1376 assert!(matches!(state.update(Event::Close), Some(Output::Closed)));
1377 }
1378
1379 #[test]
1380 fn results_for_the_current_query_join_a_remote_group() {
1381 let mut state = sample();
1382 let _ = state.update(Event::Input("rep".into()));
1383 assert!(state.is_empty());
1384
1385 let _ = state.update(Event::Received(vec![
1386 results("rep", "Files", [item("a", "report.pdf")]),
1387 results("rep", "Files", [item("b", "reply.txt")]),
1388 ]));
1389 assert_eq!(ids(&state), ["a", "b"]);
1390 assert!(state.results().all(|(group, _)| group == "Files"));
1391 assert_eq!(highlighted(&state), Some("a"));
1392 }
1393
1394 #[test]
1395 fn stale_results_are_dropped() {
1396 let mut state = sample();
1397 let _ = state.update(Event::Input("re".into()));
1398 let _ = state.update(Event::Input("rep".into()));
1399 let _ = state.update(Event::Received(vec![results(
1400 "re",
1401 "Files",
1402 [item("old", "readme.md")],
1403 )]));
1404 assert!(state.is_empty());
1405 }
1406
1407 #[test]
1408 fn a_new_query_clears_remote_results() {
1409 let mut state = sample();
1410 let files = |state: &State<&'static str>| {
1411 state
1412 .results()
1413 .filter(|(group, _)| *group == "Files")
1414 .count()
1415 };
1416 let _ = state.update(Event::Input("re".into()));
1417 let _ = state.update(Event::Received(vec![results(
1418 "re",
1419 "Files",
1420 [item("old", "readme.md")],
1421 )]));
1422 assert_eq!(files(&state), 1);
1423 let _ = state.update(Event::Input("rea".into()));
1424 assert_eq!(files(&state), 0);
1425 }
1426
1427 #[test]
1428 fn arriving_results_keep_the_highlight() {
1429 let mut state = sample();
1430 let _ = state.update(Event::Input("s".into()));
1431 let _ = state.update(Event::Next);
1432 let before = highlighted(&state);
1433 let _ = state.update(Event::Received(vec![results(
1434 "s",
1435 "Files",
1436 [item("f", "styles.css")],
1437 )]));
1438 assert_eq!(highlighted(&state), before);
1439 assert_eq!(state.results().last().map(|(_, item)| item.id), Some("f"));
1440 }
1441
1442 #[test]
1443 fn remote_results_are_not_filtered_again() {
1444 let mut state = sample();
1445 let _ = state.update(Event::Input("q".into()));
1446 let _ = state.update(Event::Received(vec![results(
1447 "q",
1448 "Files",
1449 [item("x", "unrelated.txt")],
1450 )]));
1451 assert_eq!(ids(&state), ["x"]);
1452 }
1453
1454 #[test]
1455 fn the_window_follows_the_highlight_and_scrolls() {
1456 let mut state = sample().with_visible_rows(3);
1457 assert_eq!(state.visible(), 0..3);
1458 let _ = state.update(Event::Last);
1459 assert_eq!(state.visible(), 3..6);
1460 let _ = state.update(Event::Next);
1461 assert_eq!(state.visible(), 0..3);
1462 let _ = state.update(Event::Scroll(10));
1463 assert_eq!(state.visible(), 3..6);
1464 let _ = state.update(Event::Scroll(-1));
1465 assert_eq!(state.visible(), 2..5);
1466 assert_eq!(State::<u8>::new([]).with_visible_rows(0).rows, 1);
1467 assert_eq!(State::<u8>::new([]).visible(), 0..0);
1468 }
1469
1470 #[test]
1471 fn ready_hands_the_sender_back() {
1472 let (sender, _receiver) = mpsc::channel(1);
1473 let output = sample().update(Event::Ready(sender));
1474 assert!(matches!(output, Some(Output::Ready(_))));
1475 }
1476
1477 #[test]
1478 fn default_keymap_and_overrides() {
1479 let keymap = default_keymap();
1480 assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
1481 assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
1482 assert_eq!(press(&keymap, "Home"), Some(Action::First));
1483 assert_eq!(press(&keymap, "End"), Some(Action::Last));
1484 assert_eq!(press(&keymap, "Enter"), Some(Action::Activate));
1485 assert_eq!(press(&keymap, "Escape"), Some(Action::Close));
1486
1487 let custom = keymap
1488 .bind("Ctrl+N".parse().unwrap(), Action::Next)
1489 .unbind(&Chord::named(Named::Home));
1490 assert_eq!(press(&custom, "ctrl+n"), Some(Action::Next));
1491 assert_eq!(press(&custom, "Home"), None);
1492 assert!(default_keymap().clear().is_empty());
1493 }
1494
1495 #[test]
1496 fn actions_map_to_events_only_when_they_apply() {
1497 let mut state = sample();
1498 for action in [Action::Next, Action::Previous, Action::First, Action::Last] {
1499 assert!(action.event(&state).is_some(), "{action:?}");
1500 }
1501 assert!(matches!(
1502 Action::Activate.event(&state),
1503 Some(Event::ActivateHighlighted)
1504 ));
1505 assert!(matches!(Action::Close.event(&state), Some(Event::Close)));
1506
1507 let _ = state.update(Event::Input("zzz".into()));
1508 for action in [
1509 Action::Next,
1510 Action::Previous,
1511 Action::First,
1512 Action::Last,
1513 Action::Activate,
1514 ] {
1515 assert!(action.event(&state).is_none(), "{action:?}");
1516 }
1517 assert!(matches!(Action::Close.event(&state), Some(Event::Close)));
1518 }
1519
1520 #[test]
1521 fn stream_emits_ready_first_then_batches() {
1522 let mut events = Box::pin(stream::<&'static str>());
1523 let Some(Event::Ready(mut sender)) = block_on(events.next()) else {
1524 panic!("first event must be Ready");
1525 };
1526 block_on(async {
1527 for name in ["a", "b", "c"] {
1528 sender
1529 .send(results("q", "Files", [item(name, name)]))
1530 .await
1531 .ok();
1532 }
1533 });
1534 let Some(Event::Received(batch)) = block_on(events.next()) else {
1535 panic!("expected a batch");
1536 };
1537 let names: Vec<_> = batch.iter().map(|r| r.items[0].id).collect();
1538 assert_eq!(names, ["a", "b", "c"]);
1539 }
1540
1541 #[test]
1542 fn batches_split_bursts_at_batch_size() {
1543 let items = stream::iter(0..BATCH_SIZE + 3);
1544 let sizes: Vec<_> = block_on(batches(items).map(|batch| batch.len()).collect());
1545 assert_eq!(sizes, [BATCH_SIZE, 3]);
1546 }
1547
1548 #[test]
1549 fn default_builder_is_disabled() {
1550 let state = sample();
1551 let c: Command<'_, &str, ()> = command(&state);
1552 assert!(!c.is_enabled());
1553 assert_eq!(c.empty, DEFAULT_EMPTY);
1554 assert!(!c.loading);
1555 assert_eq!((c.width, c.height), (Length::Fill, Length::Shrink));
1556 assert_eq!(c.max_height, f32::INFINITY);
1557 let c = c
1558 .loading(true)
1559 .height(320)
1560 .max_height(400.0)
1561 .on_event(|_| ());
1562 assert!(c.is_enabled() && c.loading);
1563 assert_eq!(c.height, Length::Fixed(320.0));
1564 assert_eq!(c.max_height, 400.0);
1565 }
1566
1567 const STATES: [Status; 5] = [
1568 Status::Active,
1569 Status::Hovered,
1570 Status::Focused { is_hovered: false },
1571 Status::Focused { is_hovered: true },
1572 Status::Disabled,
1573 ];
1574
1575 #[test]
1576 fn search_field_is_borderless_and_fades_when_disabled() {
1577 for theme in [light(), dark()] {
1578 let tokens = Tokens::of(&theme);
1579 for status in STATES {
1580 let style = search_style(&tokens, status);
1581 assert_eq!(style.border.width, 0.0);
1582 assert_eq!(style.background, Background::Color(Color::TRANSPARENT));
1583 let expected = if status == Status::Disabled {
1584 fade(tokens.foreground, 0.5)
1585 } else {
1586 tokens.foreground
1587 };
1588 assert_eq!(style.value, expected, "{status:?}");
1589 }
1590 }
1591 }
1592
1593 #[test]
1594 fn dividers_use_the_border_token() {
1595 for theme in [light(), dark()] {
1596 let tokens = Tokens::of(&theme);
1597 assert_eq!(
1598 divider_style(&tokens).background,
1599 Some(Background::Color(tokens.border))
1600 );
1601 }
1602 }
1603}