Skip to main content

iced_cube/editing/
mod.rs

1//! Undo, redo, word deletion and Escape for the library's text fields.
2//!
3//! iced's fields already handle select all, copy, cut, paste, moving by word
4//! and Home and End. This adds the rest as a wrapper widget that resolves a
5//! [`Keymap`] of [`Shortcut`]s while the field inside it has focus, and keeps
6//! the undo history in the widget tree, so apps get it without storing
7//! anything.
8
9mod history;
10mod limit;
11
12use std::cell::Cell;
13use std::fmt;
14use std::rc::Rc;
15
16use iced::advanced::layout::{self, Layout};
17use iced::advanced::widget::{Operation, Tree, Widget, tree};
18use iced::advanced::{Clipboard, Shell, input_method, overlay, renderer};
19use iced::keyboard::{self, Key, Modifiers, key::Named};
20use iced::widget::text_input::{self, Value};
21use iced::{Element, Event, Length, Rectangle, Renderer, Size, Theme, Vector, mouse};
22
23use crate::keys::{self, Chord, Keymap};
24
25pub(crate) use history::{Edit, History, Restore};
26pub(crate) use limit::Limit;
27
28/// A shortcut that inputs, textareas and the search fields inside other
29/// components add to iced's own editing keys. Each can be switched off in a
30/// [`Shortcuts`] set.
31///
32/// The formatting shortcuts, from [`Bold`](Shortcut::Bold) on, only apply
33/// to the rich text editor; plain fields leave their keys alone and
34/// [`default_keymap`] does not bind them.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum Shortcut {
37    Undo,
38    Redo,
39    DeleteWordBackward,
40    DeleteWordForward,
41    /// Escape removes focus from the field and goes no further, so a dialog
42    /// around it stays open. Switched off, the field ignores Escape and
43    /// leaves it to the app.
44    EscapeUnfocus,
45    Bold,
46    Italic,
47    Underline,
48    Strikethrough,
49    BulletedList,
50    NumberedList,
51    /// Asks the app for a link address for the selection.
52    Link,
53    ClearFormatting,
54}
55
56impl Shortcut {
57    const fn bit(self) -> u16 {
58        1 << self as u16
59    }
60
61    /// Whether the shortcut formats rich text rather than editing plain text.
62    pub const fn is_formatting(self) -> bool {
63        matches!(
64            self,
65            Shortcut::Bold
66                | Shortcut::Italic
67                | Shortcut::Underline
68                | Shortcut::Strikethrough
69                | Shortcut::BulletedList
70                | Shortcut::NumberedList
71                | Shortcut::Link
72                | Shortcut::ClearFormatting
73        )
74    }
75}
76
77impl keys::Action for Shortcut {
78    const ALL: &'static [Self] = &[
79        Shortcut::Undo,
80        Shortcut::Redo,
81        Shortcut::DeleteWordBackward,
82        Shortcut::DeleteWordForward,
83        Shortcut::EscapeUnfocus,
84        Shortcut::Bold,
85        Shortcut::Italic,
86        Shortcut::Underline,
87        Shortcut::Strikethrough,
88        Shortcut::BulletedList,
89        Shortcut::NumberedList,
90        Shortcut::Link,
91        Shortcut::ClearFormatting,
92    ];
93
94    fn defaults() -> Keymap<Self> {
95        default_keymap()
96    }
97
98    fn name(self) -> &'static str {
99        match self {
100            Shortcut::Undo => "Undo",
101            Shortcut::Redo => "Redo",
102            Shortcut::DeleteWordBackward => "Delete word backward",
103            Shortcut::DeleteWordForward => "Delete word forward",
104            Shortcut::EscapeUnfocus => "Unfocus",
105            Shortcut::Bold => "Bold",
106            Shortcut::Italic => "Italic",
107            Shortcut::Underline => "Underline",
108            Shortcut::Strikethrough => "Strikethrough",
109            Shortcut::BulletedList => "Bulleted list",
110            Shortcut::NumberedList => "Numbered list",
111            Shortcut::Link => "Link",
112            Shortcut::ClearFormatting => "Clear formatting",
113        }
114    }
115
116    fn description(self) -> &'static str {
117        match self {
118            Shortcut::Undo => "Undoes the last word typed, deletion, paste or cut.",
119            Shortcut::Redo => "Redoes what undo took back.",
120            Shortcut::DeleteWordBackward => {
121                "Deletes back to the start of the word, or the selection if there is one."
122            }
123            Shortcut::DeleteWordForward => {
124                "Deletes forward to the end of the word, or the selection if there is one."
125            }
126            Shortcut::EscapeUnfocus => {
127                "Removes focus from the field without closing a dialog around it."
128            }
129            Shortcut::Bold => "Makes the selection bold, or plain again if it all is.",
130            Shortcut::Italic => "Makes the selection italic, or upright again if it all is.",
131            Shortcut::Underline => "Underlines the selection, or removes the underline.",
132            Shortcut::Strikethrough => "Strikes through the selection, or removes the line.",
133            Shortcut::BulletedList => "Turns the selected lines into a bulleted list, or back.",
134            Shortcut::NumberedList => "Turns the selected lines into a numbered list, or back.",
135            Shortcut::Link => "Asks for an address to link the selection to.",
136            Shortcut::ClearFormatting => {
137                "Removes bold, italic, underline, strikethrough, sizes and links from the selection."
138            }
139        }
140    }
141}
142
143/// The set of [`Shortcut`]s a text field handles. Every shortcut is on by
144/// default. A shortcut that is off is ignored by the field, so its keys
145/// reach the app instead.
146///
147/// ```
148/// use iced_cube::primitives::input::{Shortcut, Shortcuts};
149///
150/// let no_undo = Shortcuts::all().without(Shortcut::Undo).without(Shortcut::Redo);
151/// assert!(!no_undo.contains(Shortcut::Undo));
152/// assert!(no_undo.contains(Shortcut::EscapeUnfocus));
153/// assert!(Shortcuts::none().with(Shortcut::Undo).contains(Shortcut::Undo));
154/// ```
155#[derive(Clone, Copy, PartialEq, Eq, Hash)]
156pub struct Shortcuts(u16);
157
158impl Shortcuts {
159    /// Every shortcut, the default.
160    pub fn all() -> Self {
161        <Shortcut as keys::Action>::ALL
162            .iter()
163            .fold(Self::none(), |set, shortcut| set.with(*shortcut))
164    }
165
166    /// No shortcuts: the field behaves as iced's plain widget.
167    pub const fn none() -> Self {
168        Self(0)
169    }
170
171    pub const fn with(self, shortcut: Shortcut) -> Self {
172        Self(self.0 | shortcut.bit())
173    }
174
175    pub const fn without(self, shortcut: Shortcut) -> Self {
176        Self(self.0 & !shortcut.bit())
177    }
178
179    pub const fn contains(self, shortcut: Shortcut) -> bool {
180        self.0 & shortcut.bit() != 0
181    }
182
183    pub const fn is_empty(self) -> bool {
184        self.0 == 0
185    }
186
187    /// The shortcuts in the set, in the order of [`Shortcut`].
188    pub fn iter(self) -> impl Iterator<Item = Shortcut> {
189        <Shortcut as keys::Action>::ALL
190            .iter()
191            .copied()
192            .filter(move |shortcut| self.contains(*shortcut))
193    }
194
195    /// Whether edits need recording for undo and redo.
196    fn has_history(self) -> bool {
197        self.contains(Shortcut::Undo) || self.contains(Shortcut::Redo)
198    }
199}
200
201impl Default for Shortcuts {
202    fn default() -> Self {
203        Self::all()
204    }
205}
206
207impl fmt::Debug for Shortcuts {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        f.debug_set().entries(self.iter()).finish()
210    }
211}
212
213impl FromIterator<Shortcut> for Shortcuts {
214    fn from_iter<I: IntoIterator<Item = Shortcut>>(shortcuts: I) -> Self {
215        shortcuts
216            .into_iter()
217            .fold(Self::none(), |set, shortcut| set.with(shortcut))
218    }
219}
220
221/// The default shortcut keys. Mod is Cmd on macOS and Ctrl elsewhere;
222/// words are deleted with Alt on macOS.
223///
224/// | Keys | Shortcut |
225/// | --- | --- |
226/// | `Mod+Z` | [`Shortcut::Undo`] |
227/// | `Mod+Shift+Z`, `Mod+Y` | [`Shortcut::Redo`] |
228/// | `Ctrl+Backspace` | [`Shortcut::DeleteWordBackward`] |
229/// | `Ctrl+Delete` | [`Shortcut::DeleteWordForward`] |
230/// | `Escape` | [`Shortcut::EscapeUnfocus`] |
231pub fn default_keymap() -> Keymap<Shortcut> {
232    Keymap::new()
233        .bind(Chord::character('z').command(), Shortcut::Undo)
234        .bind(Chord::character('z').command().shift(), Shortcut::Redo)
235        .bind(Chord::character('y').command(), Shortcut::Redo)
236        .bind(word(Named::Backspace), Shortcut::DeleteWordBackward)
237        .bind(word(Named::Delete), Shortcut::DeleteWordForward)
238        .bind(Chord::named(Named::Escape), Shortcut::EscapeUnfocus)
239}
240
241/// The [`default_keymap`] plus the formatting shortcuts, for rich text.
242///
243/// | Keys | Shortcut |
244/// | --- | --- |
245/// | `Mod+B` | [`Shortcut::Bold`] |
246/// | `Mod+I` | [`Shortcut::Italic`] |
247/// | `Mod+U` | [`Shortcut::Underline`] |
248/// | `Mod+Shift+X` | [`Shortcut::Strikethrough`] |
249/// | `Mod+Shift+8` | [`Shortcut::BulletedList`] |
250/// | `Mod+Shift+7` | [`Shortcut::NumberedList`] |
251/// | `Mod+K` | [`Shortcut::Link`] |
252/// | `Mod+\` | [`Shortcut::ClearFormatting`] |
253#[cfg(feature = "rich-text-editor")]
254pub fn formatting_keymap() -> Keymap<Shortcut> {
255    default_keymap()
256        .bind(Chord::character('b').command(), Shortcut::Bold)
257        .bind(Chord::character('i').command(), Shortcut::Italic)
258        .bind(Chord::character('u').command(), Shortcut::Underline)
259        .bind(
260            Chord::character('x').command().shift(),
261            Shortcut::Strikethrough,
262        )
263        .bind(
264            Chord::character('8').command().shift(),
265            Shortcut::BulletedList,
266        )
267        .bind(
268            Chord::character('7').command().shift(),
269            Shortcut::NumberedList,
270        )
271        .bind(Chord::character('k').command(), Shortcut::Link)
272        .bind(Chord::character('\\').command(), Shortcut::ClearFormatting)
273}
274
275fn word(key: Named) -> Chord {
276    let chord = Chord::named(key);
277    if cfg!(target_os = "macos") {
278        chord.alt()
279    } else {
280        chord.ctrl()
281    }
282}
283
284/// Which way a word is deleted.
285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
286pub(crate) enum Direction {
287    Backward,
288    Forward,
289}
290
291/// The editing widget an [`Editing`] wraps.
292pub(crate) trait Field<Message> {
293    /// The text as the app last provided it.
294    fn text(&self) -> String;
295
296    /// Whether the field is focused. `tree` is the wrapped widget's tree.
297    fn is_focused(&self, tree: &Tree) -> bool;
298
299    fn has_selection(&self, tree: &Tree) -> bool;
300
301    /// Asks the app to show `restore`.
302    fn restore(&self, tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>);
303
304    /// Deletes a word or the selection. Returns whether anything was asked of the app.
305    fn delete_word(
306        &self,
307        tree: &mut Tree,
308        direction: Direction,
309        shell: &mut Shell<'_, Message>,
310    ) -> bool;
311
312    fn unfocus(&self, tree: &mut Tree);
313
314    /// Runs before the wrapped widget sees an event.
315    fn before_event(&self, _tree: &Tree) {}
316
317    /// Runs after the wrapped widget has handled an event.
318    fn after_event(&self, _tree: &mut Tree) {}
319}
320
321/// Wraps a field to add the enabled [`Shortcut`]s of `keymap` and an undo
322/// history. `edited` must be set by the field's message closure whenever it
323/// reports an edit.
324pub(crate) struct Editing<'a, Message, F> {
325    content: Element<'a, Message>,
326    field: F,
327    keymap: Keymap<Shortcut>,
328    shortcuts: Shortcuts,
329    edited: Rc<Cell<bool>>,
330}
331
332impl<'a, Message, F> Editing<'a, Message, F> {
333    pub fn new(
334        content: impl Into<Element<'a, Message>>,
335        field: F,
336        keymap: Keymap<Shortcut>,
337        shortcuts: Shortcuts,
338        edited: Rc<Cell<bool>>,
339    ) -> Self {
340        Self {
341            content: content.into(),
342            field,
343            keymap,
344            shortcuts,
345            edited,
346        }
347    }
348}
349
350/// The shortcut bound to a key press. Letters also match by their Latin
351/// equivalent, so Ctrl+Z works on other keyboard layouts.
352pub(crate) fn resolve(
353    keymap: &Keymap<Shortcut>,
354    key: &Key,
355    physical_key: keyboard::key::Physical,
356    modifiers: Modifiers,
357) -> Option<Shortcut> {
358    let by_character = |c: char| keymap.resolve(&Key::Character(c.to_string().into()), modifiers);
359    keymap
360        .resolve(key, modifiers)
361        .or_else(|| by_character(key.to_latin(physical_key)?))
362        // Some platforms report Shift+8 as `*`, so digits also match by key position.
363        .or_else(|| by_character(digit(physical_key)?))
364}
365
366fn digit(physical_key: keyboard::key::Physical) -> Option<char> {
367    use keyboard::key::{Code, Physical};
368
369    let Physical::Code(code) = physical_key else {
370        return None;
371    };
372    let digit = match code {
373        Code::Digit0 => '0',
374        Code::Digit1 => '1',
375        Code::Digit2 => '2',
376        Code::Digit3 => '3',
377        Code::Digit4 => '4',
378        Code::Digit5 => '5',
379        Code::Digit6 => '6',
380        Code::Digit7 => '7',
381        Code::Digit8 => '8',
382        Code::Digit9 => '9',
383        _ => return None,
384    };
385    Some(digit)
386}
387
388/// A key pressed with Ctrl or Cmd is a shortcut, but some platforms still
389/// attach its text, which iced would type. Returns the press without it.
390/// Ctrl+Alt is AltGr on Windows, so it keeps its text.
391pub(crate) fn without_shortcut_text(event: &Event) -> Option<Event> {
392    let Event::Keyboard(keyboard::Event::KeyPressed {
393        key,
394        modified_key,
395        physical_key,
396        location,
397        modifiers,
398        repeat,
399        text: Some(text),
400    }) = event
401    else {
402        return None;
403    };
404    if !modifiers.command() || modifiers.alt() || text.chars().any(char::is_control) {
405        return None;
406    }
407    Some(Event::Keyboard(keyboard::Event::KeyPressed {
408        key: key.clone(),
409        modified_key: modified_key.clone(),
410        physical_key: *physical_key,
411        location: *location,
412        modifiers: *modifiers,
413        repeat: *repeat,
414        text: None,
415    }))
416}
417
418/// Whether a captured event that edited nothing may have moved the caret.
419/// iced's text input captures the release of V even after typing a plain v,
420/// so key releases never count.
421fn moves_caret(event: &Event) -> bool {
422    !matches!(event, Event::Keyboard(keyboard::Event::KeyReleased { .. }))
423}
424
425/// How an event that produced an edit groups in the history.
426pub(crate) fn classify(event: &Event) -> Edit {
427    match event {
428        Event::Keyboard(keyboard::Event::KeyPressed {
429            key,
430            modifiers,
431            text,
432            ..
433        }) => match key.as_ref() {
434            Key::Named(Named::Enter) => Edit::Insert("\n".into()),
435            Key::Named(Named::Backspace | Named::Delete)
436                if !modifiers.control() && !modifiers.alt() && !modifiers.logo() =>
437            {
438                Edit::Delete
439            }
440            _ => match text {
441                Some(text) if !text.chars().any(char::is_control) => Edit::Insert(text.to_string()),
442                _ => Edit::Other,
443            },
444        },
445        Event::InputMethod(input_method::Event::Commit(text)) => Edit::Insert(text.clone()),
446        _ => Edit::Other,
447    }
448}
449
450impl<Message, F: Field<Message>> Widget<Message, Theme, Renderer> for Editing<'_, Message, F> {
451    fn tag(&self) -> tree::Tag {
452        tree::Tag::of::<History>()
453    }
454
455    fn state(&self) -> tree::State {
456        tree::State::new(History::default())
457    }
458
459    fn children(&self) -> Vec<Tree> {
460        vec![Tree::new(&self.content)]
461    }
462
463    fn diff(&self, tree: &mut Tree) {
464        tree.diff_children(std::slice::from_ref(&self.content));
465        let history = tree.state.downcast_mut::<History>();
466        if self.shortcuts.has_history() {
467            history.settle(|| self.field.text());
468        } else {
469            *history = History::default();
470        }
471    }
472
473    fn size(&self) -> Size<Length> {
474        self.content.as_widget().size()
475    }
476
477    fn size_hint(&self) -> Size<Length> {
478        self.content.as_widget().size_hint()
479    }
480
481    fn layout(
482        &mut self,
483        tree: &mut Tree,
484        renderer: &Renderer,
485        limits: &layout::Limits,
486    ) -> layout::Node {
487        self.content
488            .as_widget_mut()
489            .layout(&mut tree.children[0], renderer, limits)
490    }
491
492    fn draw(
493        &self,
494        tree: &Tree,
495        renderer: &mut Renderer,
496        theme: &Theme,
497        style: &renderer::Style,
498        layout: Layout<'_>,
499        cursor: mouse::Cursor,
500        viewport: &Rectangle,
501    ) {
502        self.content.as_widget().draw(
503            &tree.children[0],
504            renderer,
505            theme,
506            style,
507            layout,
508            cursor,
509            viewport,
510        );
511    }
512
513    fn operate(
514        &mut self,
515        tree: &mut Tree,
516        layout: Layout<'_>,
517        renderer: &Renderer,
518        operation: &mut dyn Operation,
519    ) {
520        self.content
521            .as_widget_mut()
522            .operate(&mut tree.children[0], layout, renderer, operation);
523    }
524
525    fn update(
526        &mut self,
527        tree: &mut Tree,
528        event: &Event,
529        layout: Layout<'_>,
530        cursor: mouse::Cursor,
531        renderer: &Renderer,
532        clipboard: &mut dyn Clipboard,
533        shell: &mut Shell<'_, Message>,
534        viewport: &Rectangle,
535    ) {
536        let focused = self.field.is_focused(&tree.children[0]);
537        if focused
538            && !shell.is_event_captured()
539            && let Event::Keyboard(keyboard::Event::KeyPressed {
540                key,
541                physical_key,
542                modifiers,
543                ..
544            }) = event
545            && let Some(shortcut) = resolve(&self.keymap, key, *physical_key, *modifiers)
546                .filter(|shortcut| !shortcut.is_formatting())
547        {
548            // A shortcut that is off is left to the app: the field does not
549            // act on its keys either.
550            if self.shortcuts.contains(shortcut) {
551                self.perform(tree, shortcut, shell);
552                shell.capture_event();
553            }
554            return;
555        }
556
557        let stripped = focused.then(|| without_shortcut_text(event)).flatten();
558        let event = stripped.as_ref().unwrap_or(event);
559        let replacing = focused && self.field.has_selection(&tree.children[0]);
560        let captured = shell.is_event_captured();
561        self.edited.set(false);
562        self.field.before_event(&tree.children[0]);
563        self.content.as_widget_mut().update(
564            &mut tree.children[0],
565            event,
566            layout,
567            cursor,
568            renderer,
569            clipboard,
570            shell,
571            viewport,
572        );
573        self.field.after_event(&mut tree.children[0]);
574
575        if !self.shortcuts.has_history() {
576            return;
577        }
578        let history = tree.state.downcast_mut::<History>();
579        if self.edited.replace(false) {
580            history.record(classify(event), replacing, || self.field.text());
581        } else if !captured && shell.is_event_captured() && moves_caret(event) {
582            history.interrupt();
583        }
584    }
585
586    fn mouse_interaction(
587        &self,
588        tree: &Tree,
589        layout: Layout<'_>,
590        cursor: mouse::Cursor,
591        viewport: &Rectangle,
592        renderer: &Renderer,
593    ) -> mouse::Interaction {
594        self.content.as_widget().mouse_interaction(
595            &tree.children[0],
596            layout,
597            cursor,
598            viewport,
599            renderer,
600        )
601    }
602
603    fn overlay<'b>(
604        &'b mut self,
605        tree: &'b mut Tree,
606        layout: Layout<'b>,
607        renderer: &Renderer,
608        viewport: &Rectangle,
609        translation: Vector,
610    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
611        self.content.as_widget_mut().overlay(
612            &mut tree.children[0],
613            layout,
614            renderer,
615            viewport,
616            translation,
617        )
618    }
619}
620
621impl<Message, F: Field<Message>> Editing<'_, Message, F> {
622    fn perform(&self, tree: &mut Tree, shortcut: Shortcut, shell: &mut Shell<'_, Message>) {
623        let (state, children) = (&mut tree.state, &mut tree.children);
624        let history = state.downcast_mut::<History>();
625        let Some(child) = children.first_mut() else {
626            return;
627        };
628        let direction = match shortcut {
629            Shortcut::Undo | Shortcut::Redo => {
630                let text = self.field.text();
631                let restore = if shortcut == Shortcut::Undo {
632                    history.undo(text)
633                } else {
634                    history.redo(text)
635                };
636                if let Some(restore) = restore {
637                    self.field.restore(child, restore, shell);
638                }
639                return;
640            }
641            Shortcut::EscapeUnfocus => {
642                self.field.unfocus(child);
643                history.interrupt();
644                shell.request_redraw();
645                return;
646            }
647            Shortcut::DeleteWordBackward => Direction::Backward,
648            Shortcut::DeleteWordForward => Direction::Forward,
649            // Plain fields have nothing to format.
650            _ => return,
651        };
652        if self.field.delete_word(child, direction, shell) && self.shortcuts.has_history() {
653            history.record(Edit::Other, true, || self.field.text());
654        }
655    }
656}
657
658impl<'a, Message: 'a, F: Field<Message> + 'a> From<Editing<'a, Message, F>>
659    for Element<'a, Message>
660{
661    fn from(editing: Editing<'a, Message, F>) -> Self {
662        Element::new(editing)
663    }
664}
665
666type InputState = text_input::State<<Renderer as iced::advanced::text::Renderer>::Paragraph>;
667
668/// A single-line iced text input.
669pub(crate) struct Input<'a, Message> {
670    value: String,
671    secure: bool,
672    on_input: Rc<dyn Fn(String) -> Message + 'a>,
673    limit: Option<Rc<Limit>>,
674}
675
676impl<'a, Message> Input<'a, Message> {
677    pub fn new(value: &str, secure: bool, on_input: Rc<dyn Fn(String) -> Message + 'a>) -> Self {
678        Self {
679            value: value.to_owned(),
680            secure,
681            on_input,
682            limit: None,
683        }
684    }
685
686    /// Keeps the field within a [`Limit`], which its message closure must
687    /// also apply.
688    pub fn limit(mut self, limit: Option<Rc<Limit>>) -> Self {
689        self.limit = limit;
690        self
691    }
692}
693
694fn input_state(tree: &Tree) -> Option<&InputState> {
695    match &tree.state {
696        tree::State::Some(state) => state.downcast_ref::<InputState>(),
697        tree::State::None => None,
698    }
699}
700
701fn input_state_mut(tree: &mut Tree) -> Option<&mut InputState> {
702    match &mut tree.state {
703        tree::State::Some(state) => state.downcast_mut::<InputState>(),
704        tree::State::None => None,
705    }
706}
707
708impl<Message> Field<Message> for Input<'_, Message> {
709    fn text(&self) -> String {
710        self.value.clone()
711    }
712
713    fn is_focused(&self, tree: &Tree) -> bool {
714        input_state(tree).is_some_and(InputState::is_focused)
715    }
716
717    fn has_selection(&self, tree: &Tree) -> bool {
718        input_state(tree)
719            .is_some_and(|state| state.cursor().selection(&Value::new(&self.value)).is_some())
720    }
721
722    fn restore(&self, tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>) {
723        let text = match &self.limit {
724            Some(limit) => limit.truncate(restore.text),
725            None => restore.text,
726        };
727        let caret = text
728            .get(..restore.caret.min(text.len()))
729            .map_or(0, |head| Value::new(head).len());
730        shell.publish((self.on_input)(text));
731        if let Some(state) = input_state_mut(tree) {
732            state.move_cursor_to(caret);
733        }
734    }
735
736    fn delete_word(
737        &self,
738        tree: &mut Tree,
739        direction: Direction,
740        shell: &mut Shell<'_, Message>,
741    ) -> bool {
742        let Some(state) = input_state_mut(tree) else {
743            return false;
744        };
745        let value = Value::new(&self.value);
746        let (start, end) = state
747            .cursor()
748            .selection(&value)
749            .unwrap_or_else(|| word_range(&value, caret(state, &value), direction, self.secure));
750        if start == end {
751            return false;
752        }
753        let kept = format!(
754            "{}{}",
755            value.select(0, start),
756            value.select(end, value.len())
757        );
758        shell.publish((self.on_input)(kept));
759        state.move_cursor_to(start);
760        true
761    }
762
763    fn unfocus(&self, tree: &mut Tree) {
764        if let Some(state) = input_state_mut(tree) {
765            state.unfocus();
766        }
767    }
768
769    fn before_event(&self, tree: &Tree) {
770        let Some(limit) = &self.limit else {
771            return;
772        };
773        let Some(state) = input_state(tree).filter(|state| state.is_focused()) else {
774            return;
775        };
776        let value = Value::new(&self.value);
777        let (start, end) = state.cursor().selection(&value).unwrap_or_else(|| {
778            let caret = caret(state, &value);
779            (caret, caret)
780        });
781        limit.replacing(start, end);
782    }
783
784    fn after_event(&self, tree: &mut Tree) {
785        let Some(caret) = self.limit.as_ref().and_then(|limit| limit.take_caret()) else {
786            return;
787        };
788        if let Some(state) = input_state_mut(tree) {
789            state.move_cursor_to(caret);
790        }
791    }
792}
793
794fn caret(state: &InputState, value: &Value) -> usize {
795    match state.cursor().state(value) {
796        text_input::cursor::State::Index(index) => index,
797        text_input::cursor::State::Selection { end, .. } => end,
798    }
799}
800
801/// The graphemes a word deletion removes from `caret`. A secure field
802/// hides its words, so it deletes to the start or end instead.
803fn word_range(value: &Value, caret: usize, direction: Direction, secure: bool) -> (usize, usize) {
804    match (direction, secure) {
805        (Direction::Backward, true) => (0, caret),
806        (Direction::Backward, false) => (value.previous_start_of_word(caret), caret),
807        (Direction::Forward, true) => (caret, value.len()),
808        (Direction::Forward, false) => (caret, value.next_end_of_word(caret)),
809    }
810}
811
812#[cfg(test)]
813mod tests {
814    use super::*;
815    use iced::keyboard::key::{NativeCode, Physical};
816
817    fn press(chord: &str) -> Option<Shortcut> {
818        let chord: Chord = chord.parse().ok()?;
819        default_keymap().resolve(chord.key(), chord.modifiers())
820    }
821
822    fn key_press(key: Key, modifiers: Modifiers, text: Option<&str>) -> Event {
823        Event::Keyboard(keyboard::Event::KeyPressed {
824            key: key.clone(),
825            modified_key: key,
826            physical_key: Physical::Unidentified(NativeCode::Unidentified),
827            location: keyboard::Location::Standard,
828            modifiers,
829            repeat: false,
830            text: text.map(Into::into),
831        })
832    }
833
834    #[test]
835    fn default_keymap_binds_undo_redo_and_word_deletion() {
836        assert_eq!(press("Mod+Z"), Some(Shortcut::Undo));
837        assert_eq!(press("Mod+Shift+Z"), Some(Shortcut::Redo));
838        assert_eq!(press("Mod+Y"), Some(Shortcut::Redo));
839        let word = if cfg!(target_os = "macos") {
840            "Alt"
841        } else {
842            "Ctrl"
843        };
844        assert_eq!(
845            press(&format!("{word}+Backspace")),
846            Some(Shortcut::DeleteWordBackward)
847        );
848        assert_eq!(
849            press(&format!("{word}+Delete")),
850            Some(Shortcut::DeleteWordForward)
851        );
852        assert_eq!(press("Escape"), Some(Shortcut::EscapeUnfocus));
853        assert_eq!(press("Z"), None);
854        assert_eq!(press("Backspace"), None);
855    }
856
857    #[test]
858    fn every_editing_shortcut_has_a_default_chord_and_formatting_has_none() {
859        let keymap = default_keymap();
860        for shortcut in <Shortcut as keys::Action>::ALL {
861            assert_eq!(
862                keymap.chords(shortcut).is_empty(),
863                shortcut.is_formatting(),
864                "{shortcut:?}"
865            );
866        }
867    }
868
869    #[cfg(feature = "rich-text-editor")]
870    #[test]
871    fn the_formatting_keymap_binds_every_shortcut() {
872        let keymap = formatting_keymap();
873        for shortcut in <Shortcut as keys::Action>::ALL {
874            assert!(!keymap.chords(shortcut).is_empty(), "{shortcut:?}");
875        }
876        let physical = Physical::Unidentified(NativeCode::Unidentified);
877        let b = Key::Character("b".into());
878        assert_eq!(
879            resolve(&keymap, &b, physical, Modifiers::COMMAND),
880            Some(Shortcut::Bold)
881        );
882        assert_eq!(
883            resolve(&default_keymap(), &b, physical, Modifiers::COMMAND),
884            None
885        );
886    }
887
888    #[cfg(feature = "rich-text-editor")]
889    #[test]
890    fn shifted_digits_match_by_key_position() {
891        let star = Key::Character("*".into());
892        let eight = Physical::Code(keyboard::key::Code::Digit8);
893        assert_eq!(
894            resolve(
895                &formatting_keymap(),
896                &star,
897                eight,
898                Modifiers::COMMAND | Modifiers::SHIFT
899            ),
900            Some(Shortcut::BulletedList)
901        );
902    }
903
904    #[test]
905    fn shortcut_sets() {
906        let all = Shortcuts::all();
907        assert_eq!(Shortcuts::default(), all);
908        assert_eq!(all.iter().count(), <Shortcut as keys::Action>::ALL.len());
909        assert!(Shortcuts::none().is_empty());
910        assert_eq!(Shortcuts::none().iter().count(), 0);
911
912        let no_undo = all.without(Shortcut::Undo);
913        assert!(!no_undo.contains(Shortcut::Undo));
914        assert!(no_undo.contains(Shortcut::Redo));
915        assert_eq!(no_undo.with(Shortcut::Undo), all);
916        assert_eq!(all.without(Shortcut::Undo).without(Shortcut::Undo), no_undo);
917
918        let picked: Shortcuts = [Shortcut::EscapeUnfocus].into_iter().collect();
919        assert_eq!(picked, Shortcuts::none().with(Shortcut::EscapeUnfocus));
920        assert!(!picked.has_history());
921        assert!(Shortcuts::none().with(Shortcut::Redo).has_history());
922        assert_eq!(format!("{picked:?}"), "{EscapeUnfocus}");
923    }
924
925    #[test]
926    fn keymap_overrides_and_unbinding() {
927        let keymap = default_keymap()
928            .unbind_action(&Shortcut::Redo)
929            .bind(Chord::named(Named::F4), Shortcut::Redo);
930        let physical = Physical::Unidentified(NativeCode::Unidentified);
931        let y = Key::Character("y".into());
932        assert_eq!(resolve(&keymap, &y, physical, Modifiers::COMMAND), None);
933        assert_eq!(
934            resolve(
935                &keymap,
936                &Key::Named(Named::F4),
937                physical,
938                Modifiers::empty()
939            ),
940            Some(Shortcut::Redo)
941        );
942        assert_eq!(
943            resolve(&Keymap::new(), &y, physical, Modifiers::COMMAND),
944            None
945        );
946    }
947
948    #[test]
949    fn shift_with_a_capital_letter_still_matches() {
950        let physical = Physical::Unidentified(NativeCode::Unidentified);
951        let z = Key::Character("Z".into());
952        assert_eq!(
953            resolve(
954                &default_keymap(),
955                &z,
956                physical,
957                Modifiers::COMMAND | Modifiers::SHIFT
958            ),
959            Some(Shortcut::Redo)
960        );
961    }
962
963    #[test]
964    fn letters_match_by_their_latin_key_on_other_layouts() {
965        let physical = Physical::Code(keyboard::key::Code::KeyZ);
966        let cyrillic = Key::Character("я".into());
967        assert_eq!(
968            resolve(&default_keymap(), &cyrillic, physical, Modifiers::COMMAND),
969            Some(Shortcut::Undo)
970        );
971    }
972
973    #[test]
974    fn classify_groups_typing_and_deletion() {
975        let a = Key::Character("a".into());
976        assert_eq!(
977            classify(&key_press(a.clone(), Modifiers::empty(), Some("a"))),
978            Edit::Insert("a".into())
979        );
980        assert_eq!(
981            classify(&key_press(a, Modifiers::CTRL, Some("\u{1}"))),
982            Edit::Other
983        );
984        assert_eq!(
985            classify(&key_press(
986                Key::Named(Named::Enter),
987                Modifiers::empty(),
988                Some("\r")
989            )),
990            Edit::Insert("\n".into())
991        );
992        assert_eq!(
993            classify(&key_press(
994                Key::Named(Named::Backspace),
995                Modifiers::empty(),
996                None
997            )),
998            Edit::Delete
999        );
1000        assert_eq!(
1001            classify(&key_press(
1002                Key::Named(Named::Backspace),
1003                Modifiers::CTRL,
1004                None
1005            )),
1006            Edit::Other
1007        );
1008        assert_eq!(
1009            classify(&Event::InputMethod(input_method::Event::Commit(
1010                "word".into()
1011            ))),
1012            Edit::Insert("word".into())
1013        );
1014    }
1015
1016    #[test]
1017    fn shortcut_text_is_dropped_but_altgr_and_plain_typing_keep_it() {
1018        let one = Key::Character("1".into());
1019        let Some(Event::Keyboard(keyboard::Event::KeyPressed { text, .. })) =
1020            without_shortcut_text(&key_press(one.clone(), Modifiers::COMMAND, Some("1")))
1021        else {
1022            panic!("Ctrl+1 loses its text");
1023        };
1024        assert_eq!(text, None);
1025        assert_eq!(
1026            without_shortcut_text(&key_press(
1027                Key::Character("@".into()),
1028                Modifiers::CTRL | Modifiers::ALT,
1029                Some("@")
1030            )),
1031            None
1032        );
1033        assert_eq!(
1034            without_shortcut_text(&key_press(one, Modifiers::empty(), Some("1"))),
1035            None
1036        );
1037    }
1038
1039    #[test]
1040    fn word_ranges_follow_the_caret() {
1041        let value = Value::new("one two");
1042        assert_eq!(word_range(&value, 7, Direction::Backward, false), (4, 7));
1043        assert_eq!(word_range(&value, 0, Direction::Forward, false), (0, 3));
1044        assert_eq!(word_range(&value, 7, Direction::Backward, true), (0, 7));
1045        assert_eq!(word_range(&value, 2, Direction::Forward, true), (2, 7));
1046    }
1047}