Skip to main content

subspace_core/
palette.rs

1//! Command palette logic: command matching, match highlighting and the
2//! recent items list.
3
4use crate::search::{fold, tokenize};
5
6const FIRST_LABEL_WORD_PREFIX_SCORE: u32 = 10;
7const LABEL_WORD_PREFIX_SCORE: u32 = 8;
8const KEYWORD_PREFIX_SCORE: u32 = 5;
9const LABEL_SUBSTRING_SCORE: u32 = 3;
10
11/// How well `query` matches a command's label and keywords; 0 is no match.
12///
13/// Every query word must match: a prefix of the label's first word scores
14/// highest, then a prefix of another label word, then a keyword prefix, then
15/// a substring of the label. A query that fails falls back to a subsequence of
16/// the label.
17pub fn command_score(label: &str, keywords: &str, query: &str) -> u32 {
18    let query = query.to_lowercase();
19    let words: Vec<&str> = query.split_whitespace().collect();
20    if words.is_empty() {
21        return 1;
22    }
23    let label = label.to_lowercase();
24    let label_words: Vec<&str> = label
25        .split(|c: char| !(c.is_alphanumeric() || matches!(c, '@' | '`' | '?')))
26        .filter(|word| !word.is_empty())
27        .collect();
28    let keywords = keywords.to_lowercase();
29
30    let mut total = 0;
31    for word in &words {
32        let best = score_word(&label_words, &keywords, &label, word);
33        if best == 0 {
34            total = 0;
35            break;
36        }
37        total += best;
38    }
39    if total > 0 {
40        return total;
41    }
42    let needle: String = words.concat();
43    u32::from(is_subsequence(&needle, &label))
44}
45
46fn score_word(label_words: &[&str], keywords: &str, label: &str, word: &str) -> u32 {
47    if label_words.first().is_some_and(|w| w.starts_with(word)) {
48        FIRST_LABEL_WORD_PREFIX_SCORE
49    } else if label_words.iter().any(|w| w.starts_with(word)) {
50        LABEL_WORD_PREFIX_SCORE
51    } else if keywords.split_whitespace().any(|w| w.starts_with(word)) {
52        KEYWORD_PREFIX_SCORE
53    } else if label.contains(word) {
54        LABEL_SUBSTRING_SCORE
55    } else {
56        0
57    }
58}
59
60fn is_subsequence(needle: &str, haystack: &str) -> bool {
61    let mut wanted = needle.chars().peekable();
62    for c in haystack.chars() {
63        if wanted.peek() == Some(&c) {
64            wanted.next();
65        }
66    }
67    !needle.is_empty() && wanted.peek().is_none()
68}
69
70/// The positions of the commands that match `query`, best first; ties keep
71/// the given order. `fields` gives a command's label and keywords.
72pub fn filter_commands<T>(
73    commands: &[T],
74    query: &str,
75    fields: impl Fn(&T) -> (&str, &str),
76) -> Vec<usize> {
77    let mut scored: Vec<(usize, u32)> = commands
78        .iter()
79        .enumerate()
80        .map(|(index, command)| {
81            let (label, keywords) = fields(command);
82            (index, command_score(label, keywords, query))
83        })
84        .filter(|(_, score)| *score > 0)
85        .collect();
86    scored.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
87    scored.into_iter().map(|(index, _)| index).collect()
88}
89
90/// A piece of text, marked where it matches the query.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Run {
93    pub text: String,
94    pub hit: bool,
95}
96
97/// Splits `text` into plain and matched runs: a word is matched where it
98/// starts with a query word.
99pub fn highlight_runs(text: &str, query: &str) -> Vec<Run> {
100    let words = tokenize(query);
101    if words.is_empty() {
102        return vec![Run {
103            text: text.to_string(),
104            hit: false,
105        }];
106    }
107    let mut runs: Vec<Run> = Vec::new();
108    let mut push = |part: &str, hit: bool| {
109        if part.is_empty() {
110            return;
111        }
112        match runs.last_mut() {
113            Some(last) if last.hit == hit => last.text.push_str(part),
114            _ => runs.push(Run {
115                text: part.to_string(),
116                hit,
117            }),
118        }
119    };
120    for part in split_words(text) {
121        let folded = fold(part);
122        let length = words
123            .iter()
124            .filter(|word| folded.starts_with(word.as_str()))
125            .map(|word| word.chars().count())
126            .max()
127            .unwrap_or(0);
128        let chars = part.chars().count();
129        // Accents fold to the same length for common Latin text; else mark
130        // the whole word.
131        let cut = if folded.chars().count() == chars {
132            length
133        } else if length > 0 {
134            chars
135        } else {
136            0
137        };
138        let at = part.char_indices().nth(cut).map_or(part.len(), |(i, _)| i);
139        push(&part[..at], true);
140        push(&part[at..], false);
141    }
142    runs
143}
144
145/// `text` cut into alternating runs of letters and digits and of anything
146/// else, in order.
147fn split_words(text: &str) -> Vec<&str> {
148    let mut parts = Vec::new();
149    let mut start = 0;
150    let mut word = None;
151    for (i, c) in text.char_indices() {
152        let is_word = c.is_alphanumeric();
153        if word.is_some_and(|w| w != is_word) {
154            parts.push(&text[start..i]);
155            start = i;
156        }
157        word = Some(is_word);
158    }
159    if start < text.len() {
160        parts.push(&text[start..]);
161    }
162    parts
163}
164
165/// Most recent first, no duplicates, at most `max`.
166pub fn push_recent<T: PartialEq + Clone>(list: &[T], item: T, max: usize) -> Vec<T> {
167    std::iter::once(item.clone())
168        .chain(list.iter().filter(|x| **x != item).cloned())
169        .take(max)
170        .collect()
171}
172
173#[cfg(test)]
174mod tests {
175    use super::{Run, command_score, filter_commands, highlight_runs, push_recent};
176
177    const COMMANDS: &[(&str, &str)] = &[
178        ("Switch to board layout", "view layout v"),
179        ("Show everyone (all)", "filter people me team m"),
180        ("Change state…", "status s"),
181        ("Change sprint…", "iteration"),
182        ("Wrap titles", "truncate lines w"),
183    ];
184
185    fn labels(query: &str) -> Vec<&'static str> {
186        filter_commands(COMMANDS, query, |(label, keywords)| (label, keywords))
187            .into_iter()
188            .map(|i| COMMANDS[i].0)
189            .collect()
190    }
191
192    fn run(text: &str, hit: bool) -> Run {
193        Run {
194            text: text.into(),
195            hit,
196        }
197    }
198
199    #[test]
200    fn a_label_word_prefix_beats_a_keyword_match() {
201        assert_eq!(labels("board")[0], "Switch to board layout");
202        assert_eq!(labels("change"), ["Change state…", "Change sprint…"]);
203        assert_eq!(labels("iter"), ["Change sprint…"]);
204    }
205
206    #[test]
207    fn command_score_keeps_match_precedence_and_weights() {
208        assert_eq!(command_score("Board view", "board-keyword", "boa"), 10);
209        assert_eq!(command_score("Switch board", "switch-keyword", "boa"), 8);
210        assert_eq!(command_score("Switch view", "board-keyword", "boa"), 5);
211        assert_eq!(command_score("Dashboard", "", "boa"), 3);
212    }
213
214    #[test]
215    fn every_word_must_match_and_a_subsequence_is_the_fallback() {
216        assert_eq!(labels("change sp"), ["Change sprint…"]);
217        assert_eq!(labels("chsta"), ["Change state…"]);
218        assert_eq!(command_score("Reload", "", "xyz"), 0);
219        assert_eq!(labels("").len(), COMMANDS.len());
220    }
221
222    #[test]
223    fn highlight_marks_word_prefixes_that_match_the_query() {
224        assert_eq!(
225            highlight_runs("Automate Team onboarding", "onbo team"),
226            [
227                run("Automate ", false),
228                run("Team", true),
229                run(" ", false),
230                run("onbo", true),
231                run("arding", false),
232            ]
233        );
234        assert_eq!(highlight_runs("plain", ""), [run("plain", false)]);
235        assert_eq!(
236            highlight_runs("Café crème", "cafe"),
237            [run("Café", true), run(" crème", false)]
238        );
239    }
240
241    #[test]
242    fn recent_items_are_newest_first_unique_and_capped() {
243        assert_eq!(push_recent(&[3, 2, 1], 2, 8), [2, 3, 1]);
244        assert_eq!(push_recent(&[1, 2, 3], 4, 3), [4, 1, 2]);
245    }
246}