iced-yoda/native/src/widget/text_input/editor.rs

71 lines
1.9 KiB
Rust
Raw Normal View History

use crate::widget::text_input::{Cursor, Value};
pub struct Editor<'a> {
value: &'a mut Value,
cursor: &'a mut Cursor,
}
impl<'a> Editor<'a> {
pub fn new(value: &'a mut Value, cursor: &'a mut Cursor) -> Editor<'a> {
Editor { value, cursor }
}
pub fn contents(&self) -> String {
self.value.to_string()
}
pub fn insert(&mut self, character: char) {
2022-07-04 01:17:29 +02:00
if let Some((left, right)) = self.cursor.selection(self.value) {
self.cursor.move_left(self.value);
self.value.remove_many(left, right);
}
2020-03-25 14:07:32 +01:00
self.value.insert(self.cursor.end(self.value), character);
self.cursor.move_right(self.value);
}
pub fn paste(&mut self, content: Value) {
let length = content.len();
2022-07-04 01:17:29 +02:00
if let Some((left, right)) = self.cursor.selection(self.value) {
self.cursor.move_left(self.value);
self.value.remove_many(left, right);
}
2020-03-25 14:07:32 +01:00
self.value.insert_many(self.cursor.end(self.value), content);
2020-03-25 14:07:32 +01:00
self.cursor.move_right_by_amount(self.value, length);
}
pub fn backspace(&mut self) {
2020-07-10 23:59:49 +02:00
match self.cursor.selection(self.value) {
Some((start, end)) => {
2020-07-10 23:59:49 +02:00
self.cursor.move_left(self.value);
self.value.remove_many(start, end);
}
None => {
2020-03-25 14:07:32 +01:00
let start = self.cursor.start(self.value);
if start > 0 {
2020-03-25 14:07:32 +01:00
self.cursor.move_left(self.value);
2020-03-28 15:25:55 -07:00
self.value.remove(start - 1);
}
}
}
}
pub fn delete(&mut self) {
2020-07-10 23:59:49 +02:00
match self.cursor.selection(self.value) {
2020-03-24 20:57:03 +01:00
Some(_) => {
self.backspace();
}
None => {
2020-03-25 14:07:32 +01:00
let end = self.cursor.end(self.value);
if end < self.value.len() {
2020-03-28 15:25:55 -07:00
self.value.remove(end);
}
}
}
}
}