summaryrefslogtreecommitdiffstats
path: root/widget/src/text_input/editor.rs
diff options
context:
space:
mode:
authorLibravatar Héctor Ramón <hector0193@gmail.com>2023-05-11 16:45:08 +0200
committerLibravatar GitHub <noreply@github.com>2023-05-11 16:45:08 +0200
commit669f7cc74b2e7918e86a8197916f503f2d3d9b93 (patch)
treeacb365358235be6ce115b50db9404d890b6e77a6 /widget/src/text_input/editor.rs
parentbc62013b6cde52174bf4c4286939cf170bfa7760 (diff)
parent63d3fc6996b848e10e77e6924bfebdf6ba82852e (diff)
downloadiced-669f7cc74b2e7918e86a8197916f503f2d3d9b93.tar.gz
iced-669f7cc74b2e7918e86a8197916f503f2d3d9b93.tar.bz2
iced-669f7cc74b2e7918e86a8197916f503f2d3d9b93.zip
Merge pull request #1830 from iced-rs/advanced-text
Advanced text
Diffstat (limited to 'widget/src/text_input/editor.rs')
-rw-r--r--widget/src/text_input/editor.rs70
1 files changed, 70 insertions, 0 deletions
diff --git a/widget/src/text_input/editor.rs b/widget/src/text_input/editor.rs
new file mode 100644
index 00000000..f1fd641f
--- /dev/null
+++ b/widget/src/text_input/editor.rs
@@ -0,0 +1,70 @@
+use crate::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) {
+ if let Some((left, right)) = self.cursor.selection(self.value) {
+ self.cursor.move_left(self.value);
+ self.value.remove_many(left, right);
+ }
+
+ 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();
+ if let Some((left, right)) = self.cursor.selection(self.value) {
+ self.cursor.move_left(self.value);
+ self.value.remove_many(left, right);
+ }
+
+ self.value.insert_many(self.cursor.end(self.value), content);
+
+ self.cursor.move_right_by_amount(self.value, length);
+ }
+
+ pub fn backspace(&mut self) {
+ match self.cursor.selection(self.value) {
+ Some((start, end)) => {
+ self.cursor.move_left(self.value);
+ self.value.remove_many(start, end);
+ }
+ None => {
+ let start = self.cursor.start(self.value);
+
+ if start > 0 {
+ self.cursor.move_left(self.value);
+ self.value.remove(start - 1);
+ }
+ }
+ }
+ }
+
+ pub fn delete(&mut self) {
+ match self.cursor.selection(self.value) {
+ Some(_) => {
+ self.backspace();
+ }
+ None => {
+ let end = self.cursor.end(self.value);
+
+ if end < self.value.len() {
+ self.value.remove(end);
+ }
+ }
+ }
+ }
+}