Skip to main content

tinyharness_ui/ui/
input.rs

1use std::collections::HashMap;
2
3use rustyline::{
4    Completer, Helper, Highlighter, Hinter,
5    completion::Completer,
6    highlight::Highlighter,
7    hint::Hinter,
8    validate::{ValidationContext, ValidationResult, Validator},
9};
10
11use crate::style::*;
12
13#[derive(Completer, Helper, Highlighter, Hinter)]
14pub struct CommandHelper {
15    #[rustyline(Completer)]
16    completer: CommandCompleter,
17    #[rustyline(Hinter)]
18    hinter: CommandHinter,
19    #[rustyline(Highlighter)]
20    highlighter: CommandHighlighter,
21}
22
23impl Validator for CommandHelper {
24    fn validate(&self, ctx: &mut ValidationContext<'_>) -> rustyline::Result<ValidationResult> {
25        let input = ctx.input();
26
27        // Check if input ends with backslash (continuation character)
28        let trimmed = input.trim_end();
29        if trimmed.ends_with('\\') {
30            // Incomplete - needs more input
31            return Ok(ValidationResult::Incomplete);
32        }
33
34        // Check for unclosed code fences (```)
35        let fence_count = input.matches("```").count();
36        if fence_count % 2 == 1 {
37            // Unclosed code fence - needs more input
38            return Ok(ValidationResult::Incomplete);
39        }
40
41        // Check for unclosed backtick code spans
42        let backtick_count = input.matches('`').count();
43        if backtick_count % 2 == 1 {
44            // Unclosed backtick - needs more input
45            return Ok(ValidationResult::Incomplete);
46        }
47
48        // Input is complete
49        Ok(ValidationResult::Valid(None))
50    }
51}
52
53impl CommandHelper {
54    /// Create a `CommandHelper` with no command data (no completions or hints).
55    pub fn new() -> Self {
56        Self {
57            completer: CommandCompleter {
58                command_names: Vec::new(),
59                subcommands: HashMap::new(),
60            },
61            hinter: CommandHinter {
62                command_names: Vec::new(),
63                subcommands: HashMap::new(),
64            },
65            highlighter: CommandHighlighter,
66        }
67    }
68
69    /// Create a `CommandHelper` populated with command names and subcommand
70    /// completions, typically sourced from the binary's `CommandRegistry`.
71    ///
72    /// - `command_names`: all slash-command names (primary + aliases), e.g. `"/help"`, `"/quit"`.
73    /// - `subcommands`: mapping from command name to its argument completions,
74    ///   e.g. `"/mode" → ["agent", "casual", "planning", "research"]`.
75    pub fn with_commands(
76        command_names: Vec<String>,
77        subcommands: HashMap<String, Vec<String>>,
78    ) -> Self {
79        Self {
80            completer: CommandCompleter {
81                command_names: command_names.clone(),
82                subcommands: subcommands.clone(),
83            },
84            hinter: CommandHinter {
85                command_names,
86                subcommands,
87            },
88            highlighter: CommandHighlighter,
89        }
90    }
91}
92
93pub struct CommandCompleter {
94    command_names: Vec<String>,
95    subcommands: HashMap<String, Vec<String>>,
96}
97
98impl Completer for CommandCompleter {
99    type Candidate = String;
100
101    fn complete(
102        &self,
103        line: &str,
104        pos: usize,
105        _ctx: &rustyline::Context<'_>,
106    ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
107        if !line.starts_with('/') || pos == 0 {
108            return Ok((0, vec![]));
109        }
110
111        let prefix = &line[..pos];
112
113        // Check if we're completing a subcommand argument
114        if let Some(space_pos) = prefix.find(' ') {
115            let cmd = &prefix[..space_pos].to_lowercase();
116            let sub_prefix = prefix[space_pos + 1..].trim_start().to_lowercase();
117            let subs = self
118                .subcommands
119                .get(cmd)
120                .map(|s| s.as_slice())
121                .unwrap_or(&[]);
122
123            if !subs.is_empty() {
124                let matches: Vec<String> = subs
125                    .iter()
126                    .filter(|s| s.starts_with(&sub_prefix))
127                    .take(5)
128                    .map(|s| format!("{} {}", cmd, s))
129                    .collect();
130
131                if matches.is_empty() {
132                    return Ok((0, vec![]));
133                }
134
135                // Return the completion starting from the beginning of the line
136                return Ok((0, matches));
137            }
138        }
139
140        // Top-level command completion
141        let cmd_prefix = prefix.to_lowercase();
142        let matches: Vec<String> = self
143            .command_names
144            .iter()
145            .filter(|name| name.to_lowercase().starts_with(&cmd_prefix))
146            .take(3)
147            .cloned()
148            .collect();
149
150        if matches.is_empty() {
151            return Ok((0, vec![]));
152        }
153
154        Ok((0, matches))
155    }
156}
157
158pub struct CommandHinter {
159    command_names: Vec<String>,
160    subcommands: HashMap<String, Vec<String>>,
161}
162
163impl Hinter for CommandHinter {
164    type Hint = String;
165
166    fn hint(&self, line: &str, pos: usize, _ctx: &rustyline::Context<'_>) -> Option<Self::Hint> {
167        if !line.starts_with('/') || pos == 0 || line.len() != pos {
168            return None;
169        }
170
171        // Check if we're hinting a subcommand
172        if let Some(space_pos) = line.find(' ') {
173            let cmd = &line[..space_pos].to_lowercase();
174            let sub_prefix = line[space_pos + 1..].trim_start().to_lowercase();
175            let subs = self
176                .subcommands
177                .get(cmd)
178                .map(|s| s.as_slice())
179                .unwrap_or(&[]);
180
181            if !subs.is_empty() {
182                let matches: Vec<&String> = subs
183                    .iter()
184                    .filter(|s| s.starts_with(&sub_prefix))
185                    .take(5)
186                    .collect();
187
188                if matches.is_empty() {
189                    return None;
190                }
191
192                if matches.len() == 1 && sub_prefix.is_empty() {
193                    // Single exact match and no prefix typed yet — show the subcommand
194                    return Some(format!(" {}", matches[0]));
195                }
196
197                if matches.len() == 1 && sub_prefix == *matches[0] {
198                    // Exact match completed — no hint needed
199                    return None;
200                }
201
202                // Multiple matches or partial match — show options
203                let suggestions: Vec<&str> = matches.iter().map(|s| s.as_str()).collect();
204                return Some(format!("  ({})", suggestions.join(" | ")));
205            }
206        }
207
208        // Top-level command hinting
209        let prefix = line.to_lowercase();
210        let matches: Vec<&str> = self
211            .command_names
212            .iter()
213            .filter(|name| name.to_lowercase().starts_with(&prefix))
214            .take(3)
215            .map(|s| s.as_str())
216            .collect();
217
218        if matches.is_empty() {
219            return None;
220        }
221
222        if matches.len() == 1 {
223            let hint = matches[0][pos..].to_string();
224            if !hint.is_empty() {
225                return Some(hint);
226            }
227        }
228
229        let suggestions = matches.join("  ");
230        Some(format!("  ({})", suggestions))
231    }
232}
233
234pub struct CommandHighlighter;
235
236impl Highlighter for CommandHighlighter {
237    fn highlight<'l>(&self, line: &'l str, _pos: usize) -> std::borrow::Cow<'l, str> {
238        if line.starts_with('/') {
239            std::borrow::Cow::Owned(format!("{}{}{}", TITLE_COLOR, line, RESET))
240        } else {
241            std::borrow::Cow::Borrowed(line)
242        }
243    }
244
245    fn highlight_hint<'l>(&self, hint: &'l str) -> std::borrow::Cow<'l, str> {
246        std::borrow::Cow::Owned(format!("{}{}{}", GRAY, hint, RESET))
247    }
248
249    fn highlight_candidate<'l>(
250        &self,
251        candidate: &'l str,
252        _completion: rustyline::CompletionType,
253    ) -> std::borrow::Cow<'l, str> {
254        std::borrow::Cow::Owned(format!("{}{}{}", TITLE_COLOR, candidate, RESET))
255    }
256}