iced_widget/text_input/
editor.rs
1use crate::text_input::{Cursor, Value};
2
3pub struct Editor<'a> {
4 value: &'a mut Value,
5 cursor: &'a mut Cursor,
6}
7
8impl<'a> Editor<'a> {
9 pub fn new(value: &'a mut Value, cursor: &'a mut Cursor) -> Editor<'a> {
10 Editor { value, cursor }
11 }
12
13 pub fn contents(&self) -> String {
14 self.value.to_string()
15 }
16
17 pub fn insert(&mut self, character: char) {
18 if let Some((left, right)) = self.cursor.selection(self.value) {
19 self.cursor.move_left(self.value);
20 self.value.remove_many(left, right);
21 }
22
23 self.value.insert(self.cursor.end(self.value), character);
24 self.cursor.move_right(self.value);
25 }
26
27 pub fn paste(&mut self, content: Value) {
28 let length = content.len();
29 if let Some((left, right)) = self.cursor.selection(self.value) {
30 self.cursor.move_left(self.value);
31 self.value.remove_many(left, right);
32 }
33
34 self.value.insert_many(self.cursor.end(self.value), content);
35
36 self.cursor.move_right_by_amount(self.value, length);
37 }
38
39 pub fn backspace(&mut self) {
40 match self.cursor.selection(self.value) {
41 Some((start, end)) => {
42 self.cursor.move_left(self.value);
43 self.value.remove_many(start, end);
44 }
45 None => {
46 let start = self.cursor.start(self.value);
47
48 if start > 0 {
49 self.cursor.move_left(self.value);
50 self.value.remove(start - 1);
51 }
52 }
53 }
54 }
55
56 pub fn delete(&mut self) {
57 match self.cursor.selection(self.value) {
58 Some(_) => {
59 self.backspace();
60 }
61 None => {
62 let end = self.cursor.end(self.value);
63
64 if end < self.value.len() {
65 self.value.remove(end);
66 }
67 }
68 }
69 }
70}