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