Skip to main content

tui/
palette.rs

1//! `:`-driven command palette. Parses a typed command string into
2//! (path, args), looks the path up in the shared [`cli_core`] command
3//! tree, and returns the runnable leaf the event layer should execute.
4//!
5//! Grammar (matches the TUI's prior single-pane mode so automation and
6//! interactive grammar agree):
7//!
8//! ```text
9//! word (word)* (key=value)*
10//! ```
11//!
12//! `word` tokens identify the path (e.g. `reports balance`). `key=value`
13//! tokens become arguments. Values with embedded spaces are not
14//! currently supported — this matches the existing CLI grammar.
15
16use cli_core::{CommandNode, command_tree, find_leaf};
17
18/// One line per command of the tree: `account create|list|…`.
19#[must_use]
20pub fn command_lines() -> Vec<String> {
21    let line = |node: &CommandNode| match node.subcommands.is_empty() {
22        true => format!("  {}", node.name),
23        false => {
24            let subs: Vec<&str> = node
25                .subcommands
26                .iter()
27                .map(|sub| sub.name.as_str())
28                .collect();
29            format!("  {} {}", node.name, subs.join("|"))
30        }
31    };
32    command_tree().iter().map(line).collect()
33}
34
35#[derive(Debug, PartialEq, Eq)]
36pub struct PaletteQuery {
37    pub path: Vec<String>,
38    pub args: Vec<(String, String)>,
39}
40
41/// Parse `input` into (path, args). Empty input yields an empty query.
42#[must_use]
43pub fn parse(input: &str) -> PaletteQuery {
44    let mut path = Vec::new();
45    let mut args = Vec::new();
46    for token in input.split_whitespace() {
47        if let Some((k, v)) = token.split_once('=') {
48            args.push((k.to_string(), v.to_string()));
49        } else {
50            path.push(token.to_string());
51        }
52    }
53    PaletteQuery { path, args }
54}
55
56/// Resolve a parsed query against the command tree. Returns the leaf
57/// node's name and its argument list if the path is complete, or
58/// `None` when the path refers to a group without a runnable command.
59#[must_use]
60pub fn resolve<'a>(tree: &'a [CommandNode], query: &PaletteQuery) -> Option<&'a CommandNode> {
61    let path_refs: Vec<&str> = query.path.iter().map(String::as_str).collect();
62    find_leaf(tree, &path_refs)
63}
64
65/// Return the longest string that is a common prefix of all `candidates`.
66/// Returns an empty string when `candidates` is empty or contains no common prefix.
67#[must_use]
68pub fn longest_common_prefix(candidates: &[String]) -> String {
69    match candidates {
70        [] => String::new(),
71        [one] => one.clone(),
72        [first, rest @ ..] => {
73            let len = rest.iter().fold(first.len(), |n, s| {
74                first
75                    .bytes()
76                    .zip(s.bytes())
77                    .take_while(|(a, b)| a == b)
78                    .count()
79                    .min(n)
80            });
81            first[..len].to_string()
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use cli_core::command_tree;
90
91    #[test]
92    fn parses_empty_input_to_empty_query() {
93        let q = parse("");
94        assert!(q.path.is_empty());
95        assert!(q.args.is_empty());
96    }
97
98    #[test]
99    fn parses_single_word_path() {
100        let q = parse("version");
101        assert_eq!(q.path, vec!["version"]);
102        assert!(q.args.is_empty());
103    }
104
105    #[test]
106    fn parses_nested_path() {
107        let q = parse("reports balance");
108        assert_eq!(q.path, vec!["reports", "balance"]);
109    }
110
111    #[test]
112    fn parses_key_value_arguments() {
113        let q = parse("reports balance from=2026-01-01 to=2026-04-30 tag=food");
114        assert_eq!(q.path, vec!["reports", "balance"]);
115        assert_eq!(q.args.len(), 3);
116        assert_eq!(q.args[0], ("from".to_string(), "2026-01-01".to_string()));
117        assert_eq!(q.args[2], ("tag".to_string(), "food".to_string()));
118    }
119
120    #[test]
121    fn command_lines_name_each_top_level_command_with_its_subcommands() {
122        let lines = command_lines();
123        assert_eq!(lines.len(), command_tree().len());
124        assert!(lines.contains(&"  version".to_string()));
125        assert!(lines.contains(&"  reports balance|activity|breakdown".to_string()));
126    }
127
128    #[test]
129    fn resolves_version_leaf() {
130        let tree = command_tree();
131        let q = parse("version");
132        let leaf = resolve(&tree, &q).expect("version resolves");
133        assert_eq!(leaf.name, "version");
134        assert!(leaf.is_leaf);
135    }
136
137    #[test]
138    fn resolves_reports_balance_leaf() {
139        let tree = command_tree();
140        let q = parse("reports balance from=2026-01-01");
141        let leaf = resolve(&tree, &q).expect("reports balance resolves");
142        assert_eq!(leaf.name, "balance");
143        assert!(leaf.is_leaf);
144    }
145
146    #[test]
147    fn rejects_unknown_path() {
148        let tree = command_tree();
149        let q = parse("nope");
150        assert!(resolve(&tree, &q).is_none());
151    }
152
153    #[test]
154    fn rejects_group_without_command() {
155        let tree = command_tree();
156        let q = parse("reports");
157        assert!(resolve(&tree, &q).is_none());
158    }
159
160    #[test]
161    fn lcp_empty_candidates_returns_empty() {
162        assert_eq!(longest_common_prefix(&[]), "");
163    }
164
165    #[test]
166    fn lcp_single_candidate_returns_it() {
167        assert_eq!(longest_common_prefix(&["account".to_string()]), "account");
168    }
169
170    #[test]
171    fn lcp_shared_prefix() {
172        let cands = vec!["create".to_string(), "commodity".to_string()];
173        assert_eq!(longest_common_prefix(&cands), "c");
174    }
175
176    #[test]
177    fn lcp_no_shared_prefix() {
178        let cands = vec!["account".to_string(), "transaction".to_string()];
179        assert_eq!(longest_common_prefix(&cands), "");
180    }
181
182    #[test]
183    fn lcp_identical_candidates() {
184        let cands = vec!["list".to_string(), "list".to_string()];
185        assert_eq!(longest_common_prefix(&cands), "list");
186    }
187}