use std::path::PathBuf;
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Clear, Paragraph, Widget},
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputPurpose {
CloneUrl,
RenameBranch,
CreateBranchFrom {
base: String,
},
AddRemoteName,
AddRemoteUrl {
name: String,
},
CreateTag,
McpConsent {
command_id: String,
},
McpArg {
command_id: String,
},
ExtensionUninstall {
id: String,
},
TreeDelete {
paths: Vec<PathBuf>,
},
ReloadConflict {
paths: Vec<PathBuf>,
},
AskNavigator {
file: String,
range: (usize, usize),
selection: String,
},
}
pub struct InputPrompt {
pub purpose: InputPurpose,
pub title: String,
pub placeholder: String,
pub value: String,
pub cursor: usize,
pub last_rect: Rect,
}
impl InputPrompt {
pub fn new(
purpose: InputPurpose,
title: impl Into<String>,
placeholder: impl Into<String>,
) -> Self {
Self {
purpose,
title: title.into(),
placeholder: placeholder.into(),
value: String::new(),
cursor: 0,
last_rect: Rect::default(),
}
}
pub fn with_value(mut self, value: impl Into<String>) -> Self {
self.value = value.into();
self.cursor = self.value.chars().count();
self
}
fn char_count(&self) -> usize {
self.value.chars().count()
}
fn byte_offset(&self, char_idx: usize) -> usize {
self.value
.char_indices()
.nth(char_idx)
.map(|(b, _)| b)
.unwrap_or(self.value.len())
}
pub fn push_char(&mut self, c: char) {
if c == '\n' || c == '\r' {
return;
}
let at = self.byte_offset(self.cursor);
self.value.insert(at, c);
self.cursor += 1;
}
pub fn pop_char(&mut self) {
if self.cursor == 0 {
return;
}
let at = self.byte_offset(self.cursor - 1);
self.value.remove(at);
self.cursor -= 1;
}
pub fn delete_char(&mut self) {
if self.cursor >= self.char_count() {
return;
}
let at = self.byte_offset(self.cursor);
self.value.remove(at);
}
pub fn move_cursor_left(&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
pub fn move_cursor_right(&mut self) {
self.cursor = (self.cursor + 1).min(self.char_count());
}
pub fn move_cursor_home(&mut self) {
self.cursor = 0;
}
pub fn move_cursor_end(&mut self) {
self.cursor = self.char_count();
}
pub fn submit_value(&self) -> Option<String> {
let v = self.value.trim();
(!v.is_empty()).then(|| v.to_string())
}
}
pub fn render_input_prompt(
prompt: &mut InputPrompt,
screen: Rect,
buf: &mut Buffer,
gradient: bool,
) {
let width = (screen.width.saturating_mul(6) / 10).clamp(30, 90.min(screen.width));
let height: u16 = 5;
let rect = Rect {
x: screen.x + (screen.width.saturating_sub(width)) / 2,
y: screen.y + (screen.height.saturating_sub(height)) / 3,
width,
height: height.min(screen.height),
};
prompt.last_rect = rect;
Widget::render(Clear, rect, buf);
let title = Span::styled(
format!(" {} ", prompt.title),
Style::default()
.fg(Color::Rgb(0xff, 0xff, 0xff))
.add_modifier(Modifier::BOLD),
);
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::Rgb(0x4e, 0x9a, 0xff)))
.title(title.clone())
.style(Style::default().bg(Color::Rgb(0x16, 0x18, 0x1f)));
let inner = Rect {
x: rect.x + 2,
y: rect.y + 1,
width: rect.width.saturating_sub(4),
height: rect.height.saturating_sub(2),
};
Widget::render(block, rect, buf);
if gradient {
crate::gradient::paint_gradient_box(buf, rect);
buf.set_span(rect.x + 1, rect.y, &title, title.width() as u16);
}
if inner.width == 0 || inner.height == 0 {
return;
}
let value_y = inner.y;
if prompt.value.is_empty() {
buf.set_stringn(
inner.x,
value_y,
&prompt.placeholder,
inner.width as usize,
Style::default()
.fg(Color::Rgb(0x6c, 0x7d, 0x9c))
.add_modifier(Modifier::ITALIC),
);
} else {
let cursor = prompt.cursor.min(prompt.value.chars().count());
let before: String = prompt.value.chars().take(cursor).collect();
let at: String = prompt.value.chars().skip(cursor).take(1).collect();
let after: String = prompt.value.chars().skip(cursor + 1).collect();
let caret = if at.is_empty() { " ".to_string() } else { at };
let value_style = Style::default().fg(Color::Rgb(0xec, 0xef, 0xf4));
let caret_style = Style::default()
.fg(Color::Rgb(0x16, 0x18, 0x1f))
.bg(Color::Rgb(0xec, 0xef, 0xf4))
.add_modifier(Modifier::SLOW_BLINK);
let line = Line::from(vec![
Span::styled(before, value_style),
Span::styled(caret, caret_style),
Span::styled(after, value_style),
]);
Widget::render(
Paragraph::new(line),
Rect {
x: inner.x,
y: value_y,
width: inner.width,
height: 1,
},
buf,
);
}
if inner.height >= 3 {
buf.set_string(
inner.x,
inner.y + 2,
"Enter to confirm ยท Esc to cancel",
Style::default().fg(Color::Rgb(0x7a, 0x82, 0x90)),
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn submit_value_trims_and_rejects_blank() {
let mut p = InputPrompt::new(InputPurpose::CreateTag, "Tag", "name");
assert_eq!(p.submit_value(), None);
for c in " v1 ".chars() {
p.push_char(c);
}
assert_eq!(p.submit_value().as_deref(), Some("v1"));
}
#[test]
fn with_value_seeds_text_and_caret_at_end() {
let p =
InputPrompt::new(InputPurpose::RenameBranch, "Rename", "new name").with_value("main");
assert_eq!(p.value, "main");
assert_eq!(p.cursor, 4);
}
#[test]
fn cursor_edits_mid_string() {
let mut p = InputPrompt::new(InputPurpose::CloneUrl, "Clone", "url");
for c in "abc".chars() {
p.push_char(c);
}
p.move_cursor_left();
p.push_char('X');
assert_eq!((p.value.as_str(), p.cursor), ("abXc", 3));
p.pop_char();
assert_eq!((p.value.as_str(), p.cursor), ("abc", 2));
p.delete_char();
assert_eq!(p.value.as_str(), "ab");
}
}