added text edit history / undo (ctrl-z)

This commit is contained in:
2025-11-22 20:37:37 -05:00
parent 90c579d734
commit 2aa5719166
4 changed files with 34 additions and 56 deletions

View File

@@ -11,6 +11,7 @@ use winit::{
pub struct TextEdit {
pub(super) view: TextView,
pub(super) selection: TextSelection,
pub(super) history: Vec<(String, TextSelection)>,
}
impl TextEdit {
@@ -180,6 +181,13 @@ impl<'a> TextEditCtx<'a> {
text
}
pub fn set(&mut self, text: &str) {
self.text
.buf
.set_text(self.font_system, text, &Attrs::new(), SHAPING, None);
self.text.selection.clear();
}
pub fn motion(&mut self, motion: Motion) {
if let TextSelection::Pos(cursor) = self.text.selection
&& let Some(cursor) = self.buf_motion(cursor, motion)
@@ -372,6 +380,24 @@ impl<'a> TextEditCtx<'a> {
}
pub fn apply_event(&mut self, event: &KeyEvent, modifiers: &Modifiers) -> TextInputResult {
let old = (self.text.content(), self.text.selection);
let mut undo = false;
let res = self.apply_event_inner(event, modifiers, &mut undo);
if undo && let Some((old, selection)) = self.text.history.pop() {
self.set(&old);
self.text.selection = selection;
} else if self.text.content() != old.0 {
self.text.history.push(old);
}
res
}
fn apply_event_inner(
&mut self,
event: &KeyEvent,
modifiers: &Modifiers,
undo: &mut bool,
) -> TextInputResult {
match &event.logical_key {
Key::Named(named) => match named {
NamedKey::Backspace => self.backspace(modifiers.control),
@@ -429,6 +455,9 @@ impl<'a> TextEditCtx<'a> {
};
}
}
"z" => {
*undo = true;
}
_ => self.insert(text),
}
} else {
@@ -463,7 +492,7 @@ pub enum TextInputResult {
Paste,
}
#[derive(Debug, Default)]
#[derive(Debug, Default, Clone, Copy)]
pub enum TextSelection {
#[default]
None,