use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Paragraph, Widget};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextEdit {
Insert(char),
Backspace,
Delete,
DeleteWordBack,
Clear,
Left,
Right,
Home,
End,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextInput {
value: String,
cursor: usize,
}
impl TextInput {
pub fn new() -> Self {
TextInput::default()
}
pub fn with_value(value: impl Into<String>) -> Self {
let value = value.into();
let cursor = value.len();
TextInput { value, cursor }
}
pub fn value(&self) -> &str {
&self.value
}
pub fn cursor(&self) -> usize {
self.cursor
}
pub fn cursor_column(&self) -> u16 {
use unicode_width::UnicodeWidthStr;
self.value[..self.cursor].width() as u16
}
pub fn is_empty(&self) -> bool {
self.value.is_empty()
}
pub fn apply(&mut self, edit: TextEdit) {
match edit {
TextEdit::Insert(c) => {
self.value.insert(self.cursor, c);
self.cursor += c.len_utf8();
}
TextEdit::Backspace => {
if let Some(prev) = self.prev_boundary() {
self.value.replace_range(prev..self.cursor, "");
self.cursor = prev;
}
}
TextEdit::Delete => {
if let Some(next) = self.next_boundary() {
self.value.replace_range(self.cursor..next, "");
}
}
TextEdit::DeleteWordBack => {
let start = self.word_start();
self.value.replace_range(start..self.cursor, "");
self.cursor = start;
}
TextEdit::Clear => {
self.value.clear();
self.cursor = 0;
}
TextEdit::Left => {
if let Some(prev) = self.prev_boundary() {
self.cursor = prev;
}
}
TextEdit::Right => {
if let Some(next) = self.next_boundary() {
self.cursor = next;
}
}
TextEdit::Home => self.cursor = 0,
TextEdit::End => self.cursor = self.value.len(),
}
}
fn prev_boundary(&self) -> Option<usize> {
self.value[..self.cursor]
.char_indices()
.next_back()
.map(|(at, _)| at)
}
fn next_boundary(&self) -> Option<usize> {
self.value[self.cursor..]
.chars()
.next()
.map(|c| self.cursor + c.len_utf8())
}
fn word_start(&self) -> usize {
let before = &self.value[..self.cursor];
let trimmed = before.trim_end();
match trimmed.rfind(|c: char| c.is_whitespace() || c == '/') {
Some(at) => at + 1,
None => 0,
}
}
}
pub struct PromptLine<'a> {
input: &'a TextInput,
prefix: &'a str,
style: Style,
cursor_style: Style,
}
impl<'a> PromptLine<'a> {
pub fn new(input: &'a TextInput, prefix: &'a str, style: Style, cursor_style: Style) -> Self {
PromptLine {
input,
prefix,
style,
cursor_style,
}
}
}
impl Widget for PromptLine<'_> {
fn render(self, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let value = self.input.value();
let at = self.input.cursor();
let under = value[at..].chars().next();
let (head, tail) = value.split_at(at);
let tail = under.map_or(tail, |c| &tail[c.len_utf8()..]);
let mut spans = vec![
Span::styled(self.prefix.to_string(), self.style),
Span::styled(head.to_string(), self.style),
Span::styled(under.unwrap_or(' ').to_string(), self.cursor_style),
];
if !tail.is_empty() {
spans.push(Span::styled(tail.to_string(), self.style));
}
Paragraph::new(Line::from(spans))
.style(self.style)
.render(area, buf);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn input(value: &str) -> TextInput {
TextInput::with_value(value)
}
#[test]
fn typing_inserts_at_the_cursor() {
let mut text = TextInput::new();
for c in "docs".chars() {
text.apply(TextEdit::Insert(c));
}
assert_eq!(text.value(), "docs");
text.apply(TextEdit::Home);
text.apply(TextEdit::Insert('/'));
assert_eq!(text.value(), "/docs");
assert_eq!(text.cursor(), 1);
}
#[test]
fn backspace_at_the_start_does_nothing() {
let mut text = input("a");
text.apply(TextEdit::Home);
text.apply(TextEdit::Backspace);
assert_eq!(text.value(), "a");
}
#[test]
fn editing_a_multibyte_line_stays_on_character_boundaries() {
let mut text = input("ışık");
text.apply(TextEdit::Backspace);
assert_eq!(text.value(), "ışı");
text.apply(TextEdit::Left);
text.apply(TextEdit::Delete);
assert_eq!(text.value(), "ış");
text.apply(TextEdit::Home);
text.apply(TextEdit::Right);
assert_eq!(text.cursor(), "ı".len());
}
#[test]
fn ctrl_w_deletes_a_word_and_its_trailing_space() {
let mut text = input("open docs ");
text.apply(TextEdit::DeleteWordBack);
assert_eq!(text.value(), "open ");
text.apply(TextEdit::DeleteWordBack);
assert_eq!(text.value(), "");
}
#[test]
fn ctrl_w_stops_at_a_path_separator() {
let mut text = input("docs/api/auth");
text.apply(TextEdit::DeleteWordBack);
assert_eq!(text.value(), "docs/api/");
}
#[test]
fn ctrl_u_clears_the_line() {
let mut text = input("a long query");
text.apply(TextEdit::Clear);
assert!(text.is_empty());
assert_eq!(text.cursor(), 0);
}
#[test]
fn the_cursor_column_counts_display_width() {
let text = input("日本");
assert_eq!(text.cursor_column(), 4);
}
}