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