pub(super) mod edit;
mod view;
use super::Flags;
use super::cursor::{self, Mode};
use super::key::Binding;
use super::text::sanitize;
use crate::style::{Color, Style};
use crate::{Cmd, CursorShape, Msg as TeaMsg, batch};
use std::time::Duration;
pub type Msg = cursor::Msg;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum EchoMode {
#[default]
Normal,
Password,
None,
}
pub type ValidateFn = fn(&str) -> Result<(), String>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyMap {
pub character_forward: Binding,
pub character_backward: Binding,
pub word_forward: Binding,
pub word_backward: Binding,
pub delete_word_backward: Binding,
pub delete_word_forward: Binding,
pub delete_after_cursor: Binding,
pub delete_before_cursor: Binding,
pub delete_character_backward: Binding,
pub delete_character_forward: Binding,
pub line_start: Binding,
pub line_end: Binding,
pub paste: Binding,
pub accept_suggestion: Binding,
pub next_suggestion: Binding,
pub prev_suggestion: Binding,
}
impl Default for KeyMap {
fn default() -> Self {
let b = Binding::new;
Self {
character_forward: b(&["right", "ctrl+f"]),
character_backward: b(&["left", "ctrl+b"]),
word_forward: b(&["alt+right", "ctrl+right", "alt+f"]),
word_backward: b(&["alt+left", "ctrl+left", "alt+b"]),
delete_word_backward: b(&["alt+backspace", "ctrl+w", "ctrl+backspace"]),
delete_word_forward: b(&["alt+delete", "alt+d", "ctrl+delete"]),
delete_after_cursor: b(&["ctrl+k"]),
delete_before_cursor: b(&["ctrl+u"]),
delete_character_backward: b(&["backspace", "shift+backspace", "ctrl+h"]),
delete_character_forward: b(&["delete", "ctrl+d"]),
line_start: b(&["home", "ctrl+a"]),
line_end: b(&["end", "ctrl+e"]),
paste: b(&["ctrl+v"]),
accept_suggestion: b(&["tab"]),
next_suggestion: b(&["down", "ctrl+n"]),
prev_suggestion: b(&["up", "ctrl+p"]),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct StyleState {
pub text: Style,
pub placeholder: Style,
pub suggestion: Style,
pub prompt: Style,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CursorStyle {
pub color: Color,
pub shape: CursorShape,
pub blink: bool,
pub blink_speed: Duration,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Styles {
pub focused: StyleState,
pub blurred: StyleState,
pub cursor: CursorStyle,
}
impl Styles {
#[must_use]
pub const fn new(is_dark: bool) -> Self {
let subdued = Style::new().fg(Color::Palette(240));
let prompt = Style::new().fg(Color::Ansi(7));
let state = StyleState {
text: Style::new(),
placeholder: subdued,
suggestion: subdued,
prompt,
};
let blurred_text = if is_dark {
Color::Ansi(7)
} else {
Color::Palette(245)
};
Self {
focused: state,
blurred: StyleState {
text: Style::new().fg(blurred_text),
..state
},
cursor: CursorStyle {
color: Color::Ansi(7),
shape: CursorShape::Block,
blink: true,
blink_speed: Duration::ZERO,
},
}
}
}
const FOCUS: u16 = 1 << 0;
const USE_VIRTUAL_CURSOR: u16 = 1 << 1;
const PASTE_PENDING: u16 = 1 << 2;
#[derive(Debug, Clone)]
pub struct Model {
pub err: Option<String>,
pub prompt: String,
pub placeholder: String,
pub echo_mode: EchoMode,
pub echo_character: char,
pub char_limit: usize,
pub key_map: KeyMap,
pub validate: Option<ValidateFn>,
pub show_suggestions: bool,
styles: Styles,
width: usize,
value: Vec<char>,
pos: usize,
offset: usize,
offset_right: usize,
virtual_cursor: cursor::Model,
suggestions: Vec<Vec<char>>,
matched: Vec<Vec<char>>,
current_suggestion: usize,
flags: Flags,
}
impl Default for Model {
fn default() -> Self {
Self::new()
}
}
impl Model {
#[must_use]
pub fn new() -> Self {
let mut m = Self {
err: None,
prompt: "> ".into(),
placeholder: String::new(),
echo_mode: EchoMode::Normal,
echo_character: '*',
char_limit: 0,
key_map: KeyMap::default(),
validate: None,
show_suggestions: false,
styles: Styles::new(true),
width: 0,
value: Vec::new(),
pos: 0,
offset: 0,
offset_right: 0,
virtual_cursor: cursor::Model::new(),
suggestions: Vec::new(),
matched: Vec::new(),
current_suggestion: 0,
flags: Flags(USE_VIRTUAL_CURSOR),
};
m.update_cursor_style();
m
}
#[must_use]
pub const fn virtual_cursor(&self) -> bool {
self.flags.get(USE_VIRTUAL_CURSOR)
}
pub fn set_virtual_cursor(&mut self, on: bool) {
self.flags.set(USE_VIRTUAL_CURSOR, on);
self.update_cursor_style();
}
#[must_use]
pub const fn styles(&self) -> Styles {
self.styles
}
pub fn set_styles(&mut self, styles: Styles) {
self.styles = styles;
self.update_cursor_style();
}
fn update_cursor_style(&mut self) {
let c = self.styles.cursor;
let mode = if !self.flags.get(USE_VIRTUAL_CURSOR) {
Mode::Hide
} else if c.blink {
Mode::Blink
} else {
Mode::Static
};
if self.flags.get(USE_VIRTUAL_CURSOR) {
self.virtual_cursor.style = Style::new().fg(c.color);
if c.blink && !c.blink_speed.is_zero() {
self.virtual_cursor.blink_speed = c.blink_speed;
}
}
let _ = self.virtual_cursor.set_mode(mode);
}
#[must_use]
pub const fn width(&self) -> usize {
self.width
}
pub const fn set_width(&mut self, columns: usize) {
self.width = columns;
}
pub fn set_value(&mut self, text: &str) {
let chars = sanitize(&text.chars().collect::<Vec<_>>(), " ", " ");
self.err = self.check(&chars);
self.set_value_internal(chars);
self.update_suggestions();
}
#[must_use]
pub fn value(&self) -> String {
self.value.iter().collect()
}
#[must_use]
pub const fn position(&self) -> usize {
self.pos
}
pub fn set_cursor(&mut self, pos: usize) {
self.pos = pos.min(self.value.len());
self.handle_overflow();
}
pub fn cursor_start(&mut self) {
self.set_cursor(0);
}
pub fn cursor_end(&mut self) {
self.set_cursor(self.value.len());
}
#[must_use]
pub const fn focused(&self) -> bool {
self.flags.get(FOCUS)
}
pub fn focus(&mut self) -> Cmd<Msg> {
self.flags.set(FOCUS, true);
self.virtual_cursor.focus()
}
pub const fn blur(&mut self) {
self.flags.set(FOCUS, false);
self.virtual_cursor.blur();
}
pub fn reset(&mut self) {
self.value.clear();
self.set_cursor(0);
}
pub fn set_suggestions(&mut self, suggestions: &[&str]) {
self.suggestions = suggestions.iter().map(|s| s.chars().collect()).collect();
self.update_suggestions();
}
#[must_use]
pub fn available_suggestions(&self) -> Vec<String> {
self.suggestions
.iter()
.map(|s| s.iter().collect())
.collect()
}
#[must_use]
pub fn matched_suggestions(&self) -> Vec<String> {
self.matched.iter().map(|s| s.iter().collect()).collect()
}
#[must_use]
pub const fn current_suggestion_index(&self) -> usize {
self.current_suggestion
}
#[must_use]
pub fn current_suggestion(&self) -> String {
self.matched
.get(self.current_suggestion)
.map(|s| s.iter().collect())
.unwrap_or_default()
}
pub fn update(&mut self, msg: &TeaMsg<Msg>) -> Cmd<Msg> {
if !self.flags.get(FOCUS) {
return Cmd::none();
}
let old = self.pos;
let mut cmds = Vec::new();
match msg {
TeaMsg::KeyPress(key) => cmds.push(self.press(key)),
TeaMsg::Paste(text) => self.insert_from_user(text),
TeaMsg::Clipboard { content, .. } if self.flags.get(PASTE_PENDING) => {
self.flags.set(PASTE_PENDING, false);
self.insert_from_user(content);
}
_ => {}
}
if self.flags.get(USE_VIRTUAL_CURSOR) {
cmds.push(self.virtual_cursor.update(msg));
if old != self.pos && self.virtual_cursor.mode() == Mode::Blink {
self.virtual_cursor.is_blinked = false;
cmds.push(self.virtual_cursor.blink());
}
}
self.handle_overflow();
batch(cmds)
}
fn check(&self, chars: &[char]) -> Option<String> {
let text: String = chars.iter().collect();
self.validate.and_then(|f| f(&text).err())
}
}
#[must_use]
pub fn blink() -> Cmd<Msg> {
cursor::blink()
}
#[cfg(test)]
mod tests;