mermaid_cli/tui/state/
input.rs1use std::collections::VecDeque;
6
7pub struct InputBuffer {
13 pub content: String,
15 pub cursor_position: usize,
17 pub history: VecDeque<String>,
19 pub history_index: Option<usize>,
21 pub history_buffer: String,
23}
24
25impl InputBuffer {
26 pub fn new() -> Self {
28 Self {
29 content: String::new(),
30 cursor_position: 0,
31 history: VecDeque::new(),
32 history_index: None,
33 history_buffer: String::new(),
34 }
35 }
36
37 pub fn load_history(&mut self, history: VecDeque<String>) {
39 self.history = history;
40 }
41
42 pub fn clear(&mut self) {
44 self.content.clear();
45 self.cursor_position = 0;
46 }
47
48 pub fn is_empty(&self) -> bool {
50 self.content.is_empty()
51 }
52
53 pub fn get(&self) -> &str {
55 &self.content
56 }
57
58 pub fn set(&mut self, content: impl Into<String>) {
60 self.content = content.into();
61 self.cursor_position = self.content.len();
62 }
63
64 pub fn insert(&mut self, c: char) {
66 self.content.insert(self.cursor_position, c);
67 self.cursor_position += c.len_utf8();
68 }
69
70 pub fn insert_str(&mut self, s: &str) {
72 self.content.insert_str(self.cursor_position, s);
73 self.cursor_position += s.len();
74 }
75
76 pub fn backspace(&mut self) -> bool {
78 if self.cursor_position > 0 {
79 let prev_boundary = self.content[..self.cursor_position]
81 .char_indices()
82 .next_back()
83 .map(|(idx, _)| idx)
84 .unwrap_or(0);
85 self.content.remove(prev_boundary);
86 self.cursor_position = prev_boundary;
87 true
88 } else {
89 false
90 }
91 }
92
93 pub fn delete(&mut self) -> bool {
95 if self.cursor_position < self.content.len() {
96 self.content.remove(self.cursor_position);
97 true
98 } else {
99 false
100 }
101 }
102
103 pub fn move_left(&mut self) {
105 if self.cursor_position > 0 {
106 self.cursor_position = self.content[..self.cursor_position]
108 .char_indices()
109 .next_back()
110 .map(|(idx, _)| idx)
111 .unwrap_or(0);
112 }
113 }
114
115 pub fn move_right(&mut self) {
117 if self.cursor_position < self.content.len() {
118 self.cursor_position = self.content[self.cursor_position..]
120 .char_indices()
121 .nth(1)
122 .map(|(idx, _)| self.cursor_position + idx)
123 .unwrap_or(self.content.len());
124 }
125 }
126
127 pub fn move_home(&mut self) {
129 self.cursor_position = 0;
130 }
131
132 pub fn move_end(&mut self) {
134 self.cursor_position = self.content.len();
135 }
136}
137
138impl Default for InputBuffer {
139 fn default() -> Self {
140 Self::new()
141 }
142}