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 Default for CommandHelper {
54    fn default() -> Self {
55        Self::new()
56    }
57}
58
59impl CommandHelper {
60    /// Create a `CommandHelper` with no command data (no completions or hints).
61    pub fn new() -> Self {
62        Self {
63            completer: CommandCompleter {
64                command_names: Vec::new(),
65                subcommands: HashMap::new(),
66            },
67            hinter: CommandHinter {
68                command_names: Vec::new(),
69                subcommands: HashMap::new(),
70            },
71            highlighter: CommandHighlighter,
72        }
73    }
74
75    /// Create a `CommandHelper` populated with command names and subcommand
76    /// completions, typically sourced from the binary's `CommandRegistry`.
77    ///
78    /// - `command_names`: all slash-command names (primary + aliases), e.g. `"/help"`, `"/quit"`.
79    /// - `subcommands`: mapping from command name to its argument completions,
80    ///   e.g. `"/mode" → ["agent", "casual", "planning"]`.
81    pub fn with_commands(
82        command_names: Vec<String>,
83        subcommands: HashMap<String, Vec<String>>,
84    ) -> Self {
85        Self {
86            completer: CommandCompleter {
87                command_names: command_names.clone(),
88                subcommands: subcommands.clone(),
89            },
90            hinter: CommandHinter {
91                command_names,
92                subcommands,
93            },
94            highlighter: CommandHighlighter,
95        }
96    }
97}
98
99pub struct CommandCompleter {
100    command_names: Vec<String>,
101    subcommands: HashMap<String, Vec<String>>,
102}
103
104impl Completer for CommandCompleter {
105    type Candidate = String;
106
107    fn complete(
108        &self,
109        line: &str,
110        pos: usize,
111        _ctx: &rustyline::Context<'_>,
112    ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
113        if !line.starts_with('/') || pos == 0 {
114            return Ok((0, vec![]));
115        }
116
117        let prefix = &line[..pos];
118
119        // Check if we're completing a subcommand argument
120        if let Some(space_pos) = prefix.find(' ') {
121            let cmd = &prefix[..space_pos].to_lowercase();
122            let sub_prefix = prefix[space_pos + 1..].trim_start().to_lowercase();
123            let subs = self
124                .subcommands
125                .get(cmd)
126                .map(|s| s.as_slice())
127                .unwrap_or(&[]);
128
129            if !subs.is_empty() {
130                let matches: Vec<String> = subs
131                    .iter()
132                    .filter(|s| s.starts_with(&sub_prefix))
133                    .take(5)
134                    .map(|s| format!("{} {}", cmd, s))
135                    .collect();
136
137                if matches.is_empty() {
138                    return Ok((0, vec![]));
139                }
140
141                // Return the completion starting from the beginning of the line
142                return Ok((0, matches));
143            }
144        }
145
146        // Top-level command completion
147        let cmd_prefix = prefix.to_lowercase();
148        let matches: Vec<String> = self
149            .command_names
150            .iter()
151            .filter(|name| name.to_lowercase().starts_with(&cmd_prefix))
152            .take(3)
153            .cloned()
154            .collect();
155
156        if matches.is_empty() {
157            return Ok((0, vec![]));
158        }
159
160        Ok((0, matches))
161    }
162}
163
164pub struct CommandHinter {
165    command_names: Vec<String>,
166    subcommands: HashMap<String, Vec<String>>,
167}
168
169impl Hinter for CommandHinter {
170    type Hint = String;
171
172    fn hint(&self, line: &str, pos: usize, _ctx: &rustyline::Context<'_>) -> Option<Self::Hint> {
173        if !line.starts_with('/') || pos == 0 || line.len() != pos {
174            return None;
175        }
176
177        // Check if we're hinting a subcommand
178        if let Some(space_pos) = line.find(' ') {
179            let cmd = &line[..space_pos].to_lowercase();
180            let sub_prefix = line[space_pos + 1..].trim_start().to_lowercase();
181            let subs = self
182                .subcommands
183                .get(cmd)
184                .map(|s| s.as_slice())
185                .unwrap_or(&[]);
186
187            if !subs.is_empty() {
188                let matches: Vec<&String> = subs
189                    .iter()
190                    .filter(|s| s.starts_with(&sub_prefix))
191                    .take(5)
192                    .collect();
193
194                if matches.is_empty() {
195                    return None;
196                }
197
198                if matches.len() == 1 && sub_prefix.is_empty() {
199                    // Single exact match and no prefix typed yet — show the subcommand
200                    return Some(format!(" {}", matches[0]));
201                }
202
203                if matches.len() == 1 && sub_prefix == *matches[0] {
204                    // Exact match completed — no hint needed
205                    return None;
206                }
207
208                // Multiple matches or partial match — show options
209                let suggestions: Vec<&str> = matches.iter().map(|s| s.as_str()).collect();
210                return Some(format!("  ({})", suggestions.join(" | ")));
211            }
212        }
213
214        // Top-level command hinting
215        let prefix = line.to_lowercase();
216        let matches: Vec<&str> = self
217            .command_names
218            .iter()
219            .filter(|name| name.to_lowercase().starts_with(&prefix))
220            .take(3)
221            .map(|s| s.as_str())
222            .collect();
223
224        if matches.is_empty() {
225            return None;
226        }
227
228        if matches.len() == 1 {
229            let hint = matches[0][pos..].to_string();
230            if !hint.is_empty() {
231                return Some(hint);
232            }
233        }
234
235        let suggestions = matches.join("  ");
236        Some(format!("  ({})", suggestions))
237    }
238}
239
240pub struct CommandHighlighter;
241
242impl Highlighter for CommandHighlighter {
243    fn highlight<'l>(&self, line: &'l str, _pos: usize) -> std::borrow::Cow<'l, str> {
244        if line.starts_with('/') {
245            std::borrow::Cow::Owned(format!("{}{}{}", TITLE_COLOR, line, RESET))
246        } else {
247            std::borrow::Cow::Borrowed(line)
248        }
249    }
250
251    fn highlight_hint<'l>(&self, hint: &'l str) -> std::borrow::Cow<'l, str> {
252        std::borrow::Cow::Owned(format!("{}{}{}", GRAY, hint, RESET))
253    }
254
255    fn highlight_candidate<'l>(
256        &self,
257        candidate: &'l str,
258        _completion: rustyline::CompletionType,
259    ) -> std::borrow::Cow<'l, str> {
260        std::borrow::Cow::Owned(format!("{}{}{}", TITLE_COLOR, candidate, RESET))
261    }
262}