Skip to main content

xrack_layout/
edit.rs

1use crate::{Interaction, Target};
2use std::{ops::Range, time::Duration};
3use unicode_segmentation::UnicodeSegmentation;
4use xrack_runtime::{KeyModifiers, Node, TextCommand, spin_editable};
5
6#[derive(Clone, Debug, Default)]
7pub struct TextEdit {
8    caret: usize,
9    anchor: usize,
10    trailing: bool,
11    preferred_x: Option<f32>,
12    composition: Option<(u64, TextEditContext)>,
13    selection_drag: Option<SelectionDrag>,
14    horizontal_drag_scroll: Option<f32>,
15    pub(crate) password_echo: Option<crate::password::PasswordEcho>,
16    pub preedit: String,
17    pub preedit_cursor: Option<usize>,
18}
19
20/// Clamp a drag hit to the visible edge and advance the viewport toward it.
21#[doc(hidden)]
22pub fn selection_drag_axis(
23    pointer: f32,
24    start: f32,
25    size: f32,
26    offset: f32,
27    limit: f32,
28    elapsed: Duration,
29) -> (f32, f32, bool) {
30    if size <= 0.0 {
31        return (start, offset, false);
32    }
33    let end = start + size;
34    let outside = pointer - pointer.clamp(start, end);
35    let speed = (70.0 + outside.abs() * 9.0).min(1600.0) * outside.signum();
36    let offset = if outside == 0.0 {
37        offset
38    } else {
39        (offset + speed * elapsed.as_secs_f32()).clamp(0.0, limit)
40    };
41    let pending = (outside < 0.0 && offset > 0.0) || (outside > 0.0 && offset < limit);
42    (
43        pointer.clamp(start, end.next_down().max(start)),
44        offset,
45        pending,
46    )
47}
48
49#[derive(Clone, Debug)]
50struct SelectionDrag {
51    unit: SelectionUnit,
52    value: String,
53    anchor: Range<usize>,
54}
55
56#[derive(Clone, Copy, Debug)]
57enum SelectionUnit {
58    Word,
59    Paragraph,
60}
61
62impl SelectionUnit {
63    fn range(self, text: &str, position: TextPosition, password: bool) -> Range<usize> {
64        if password {
65            return 0..text.len();
66        }
67        match self {
68            Self::Word => TextEdit::word_at(text, position, false),
69            Self::Paragraph => {
70                let offset = boundary(text, position.offset);
71                let index = if position.trailing {
72                    text[..offset]
73                        .grapheme_indices(true)
74                        .next_back()
75                        .map_or(0, |(index, _)| index)
76                } else {
77                    offset
78                };
79                let separator = |c| matches!(c, '\n' | '\r' | '\u{2029}');
80                let start = text[..index]
81                    .char_indices()
82                    .rfind(|(_, character)| separator(*character))
83                    .map_or(0, |(index, character)| index + character.len_utf8());
84                let end = text[index..]
85                    .find(separator)
86                    .map_or(text.len(), |end| index + end);
87                start..end
88            }
89        }
90    }
91}
92
93/// A logical offset with affinity to the preceding grapheme at a bidi or wrap boundary.
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95pub struct TextPosition {
96    pub offset: usize,
97    pub trailing: bool,
98}
99
100#[derive(Clone, Copy, Debug)]
101pub enum EditAction<'a> {
102    Insert(&'a str),
103    ReplaceAll(&'a str),
104    ReplaceRange { start: i64, end: i64, text: &'a str },
105    Backspace,
106    Delete,
107    BackspaceWord,
108    DeleteWord,
109    Left(bool),
110    Right(bool),
111    WordLeft(bool),
112    WordRight(bool),
113    Home(bool),
114    End(bool),
115    SelectAll,
116}
117
118impl EditAction<'_> {
119    #[doc(hidden)]
120    pub fn word_shortcut(key: &str, modifiers: KeyModifiers, macos: bool) -> Option<Self> {
121        let word = if macos {
122            modifiers.alt && !modifiers.control
123        } else {
124            modifiers.control && !modifiers.alt
125        };
126        if !word || modifiers.meta {
127            return None;
128        }
129        Some(match key {
130            "ArrowLeft" => Self::WordLeft(modifiers.shift),
131            "ArrowRight" => Self::WordRight(modifiers.shift),
132            "Backspace" => Self::BackspaceWord,
133            "Delete" => Self::DeleteWord,
134            _ => return None,
135        })
136    }
137
138    pub(crate) fn changes_text(self) -> bool {
139        matches!(
140            self,
141            Self::Insert(_)
142                | Self::ReplaceAll(_)
143                | Self::ReplaceRange { .. }
144                | Self::Backspace
145                | Self::Delete
146                | Self::BackspaceWord
147                | Self::DeleteWord
148        )
149    }
150}
151
152pub(crate) fn word_ranges(text: &str) -> impl DoubleEndedIterator<Item = Range<usize>> + '_ {
153    text.split_word_bound_indices()
154        .filter(|(_, word)| {
155            word.chars()
156                .any(|ch| !ch.is_whitespace() && !ch.is_control())
157        })
158        .map(|(index, word)| index..index + word.len())
159}
160
161pub(crate) struct AppliedEdit {
162    pub text: String,
163    pub start: usize,
164    pub removed: String,
165    pub inserted: String,
166}
167
168impl AppliedEdit {
169    pub(crate) fn replace_text(self, original: &str, text: String) -> Self {
170        if self.text == text {
171            return self;
172        }
173        let start = original
174            .graphemes(true)
175            .zip(text.graphemes(true))
176            .take_while(|(old, new)| old == new)
177            .map(|(grapheme, _)| grapheme.len())
178            .sum::<usize>();
179        let end = original[start..]
180            .graphemes(true)
181            .rev()
182            .zip(text[start..].graphemes(true).rev())
183            .take_while(|(old, new)| old == new)
184            .map(|(grapheme, _)| grapheme.len())
185            .sum::<usize>();
186        Self {
187            removed: original[start..original.len() - end].to_owned(),
188            inserted: text[start..text.len() - end].to_owned(),
189            text,
190            start,
191        }
192    }
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub(crate) struct SelectionState {
197    caret: TextPosition,
198    anchor: usize,
199}
200
201impl SelectionState {
202    pub(crate) fn collapsed(self) -> bool {
203        self.caret.offset == self.anchor
204    }
205}
206
207fn boundary(text: &str, position: usize) -> usize {
208    if position >= text.len() {
209        return text.len();
210    }
211    text.grapheme_indices(true)
212        .take_while(|(index, _)| *index <= position)
213        .last()
214        .map_or(0, |(index, _)| index)
215}
216
217impl TextEdit {
218    pub(crate) fn is_composing(&self) -> bool {
219        self.composition.is_some() || !self.preedit.is_empty()
220    }
221
222    pub fn at_end(text: &str) -> Self {
223        Self {
224            caret: text.len(),
225            anchor: text.len(),
226            ..Self::default()
227        }
228    }
229
230    pub fn caret(&self, text: &str) -> usize {
231        boundary(text, self.caret)
232    }
233
234    pub fn anchor(&self, text: &str) -> usize {
235        boundary(text, self.anchor)
236    }
237
238    pub fn position(&self, text: &str) -> TextPosition {
239        TextPosition {
240            offset: self.caret(text),
241            trailing: self.trailing,
242        }
243    }
244
245    pub fn place_caret(&mut self, text: &str, position: TextPosition, selecting: bool) {
246        self.set_preedit(String::new(), None);
247        self.selection_drag = None;
248        self.caret = boundary(text, position.offset);
249        self.trailing = position.trailing;
250        self.preferred_x = None;
251        if !selecting {
252            self.anchor = self.caret;
253        }
254    }
255
256    pub fn set_selection(&mut self, text: &str, anchor: usize, focus: TextPosition) {
257        self.place_caret(text, focus, false);
258        self.anchor = boundary(text, anchor);
259    }
260
261    #[doc(hidden)]
262    pub fn has_committed_suggestion(&self, text: &str) -> bool {
263        !self.preedit.is_empty() && text[self.selection(text)] == self.preedit
264    }
265
266    pub(crate) fn word_at(text: &str, position: TextPosition, password: bool) -> Range<usize> {
267        if password {
268            return 0..text.len();
269        }
270        let offset = boundary(text, position.offset);
271        let index = if position.trailing || offset == text.len() {
272            text[..offset]
273                .grapheme_indices(true)
274                .next_back()
275                .map_or(0, |(index, _)| index)
276        } else {
277            offset
278        };
279        text.split_word_bound_indices()
280            .find(|(offset, word)| *offset <= index && index < *offset + word.len())
281            .map_or(index..index, |(offset, word)| {
282                let end = text
283                    .grapheme_indices(true)
284                    .find(|(index, _)| *index >= offset + word.len())
285                    .map_or(text.len(), |(index, _)| index);
286                boundary(text, offset)..end
287            })
288    }
289
290    #[doc(hidden)]
291    pub fn start_word_drag(
292        &mut self,
293        text: &str,
294        position: TextPosition,
295        password: bool,
296        select_word: bool,
297    ) {
298        self.start_selection_drag(text, position, password, SelectionUnit::Word, select_word);
299    }
300
301    #[doc(hidden)]
302    pub fn start_paragraph_drag(&mut self, text: &str, position: TextPosition, password: bool) {
303        self.start_selection_drag(text, position, password, SelectionUnit::Paragraph, true);
304    }
305
306    fn start_selection_drag(
307        &mut self,
308        text: &str,
309        position: TextPosition,
310        password: bool,
311        unit: SelectionUnit,
312        select: bool,
313    ) {
314        let anchor = unit.range(text, position, password);
315        if select {
316            self.set_selection(
317                text,
318                anchor.start,
319                TextPosition {
320                    offset: anchor.end,
321                    trailing: true,
322                },
323            );
324        } else {
325            self.place_caret(text, position, false);
326        }
327        self.selection_drag = Some(SelectionDrag {
328            unit,
329            value: text.to_owned(),
330            anchor,
331        });
332    }
333
334    #[doc(hidden)]
335    pub fn extend_selection_drag(&mut self, text: &str, position: TextPosition) -> bool {
336        let Some(drag) = self.selection_drag.take().filter(|drag| drag.value == text) else {
337            return false;
338        };
339        let range = drag.unit.range(text, position, false);
340        let (anchor, caret, trailing) = if range.start < drag.anchor.start {
341            (drag.anchor.end, range.start, false)
342        } else {
343            (drag.anchor.start, drag.anchor.end.max(range.end), true)
344        };
345        self.set_selection(
346            text,
347            anchor,
348            TextPosition {
349                offset: caret,
350                trailing,
351            },
352        );
353        self.selection_drag = Some(drag);
354        true
355    }
356
357    pub(crate) fn preferred_x(&self) -> Option<f32> {
358        self.preferred_x
359    }
360
361    pub(crate) fn set_preferred_x(&mut self, x: f32) {
362        self.preferred_x = Some(x);
363    }
364
365    pub fn selection(&self, text: &str) -> Range<usize> {
366        let caret = self.caret(text);
367        let anchor = self.anchor(text);
368        caret.min(anchor)..caret.max(anchor)
369    }
370
371    pub(crate) fn selection_state(&self, text: &str) -> SelectionState {
372        SelectionState {
373            caret: self.position(text),
374            anchor: self.anchor(text),
375        }
376    }
377
378    pub(crate) fn restore_selection(&mut self, text: &str, state: SelectionState) {
379        self.set_selection(text, state.anchor, state.caret);
380    }
381
382    pub fn set_preedit(&mut self, value: String, cursor: Option<(usize, usize)>) {
383        self.composition = None;
384        self.update_preedit(value, cursor);
385    }
386
387    fn update_preedit(&mut self, value: String, cursor: Option<(usize, usize)>) {
388        self.password_echo = None;
389        self.horizontal_drag_scroll = None;
390        self.preedit_cursor = cursor.map(|(start, _)| boundary(&value, start));
391        self.preedit = value;
392    }
393
394    #[doc(hidden)]
395    pub fn horizontal_drag_scroll(&self) -> Option<f32> {
396        self.horizontal_drag_scroll
397    }
398
399    #[doc(hidden)]
400    pub fn set_horizontal_drag_scroll(&mut self, offset: Option<f32>) {
401        self.horizontal_drag_scroll = offset;
402    }
403
404    /// Return a replacement value for actions that change the committed text.
405    pub fn apply(&mut self, text: &str, action: EditAction<'_>) -> Option<String> {
406        self.apply_mode(text, action, false, false)
407            .map(|edit| edit.text)
408    }
409
410    pub fn apply_multiline(&mut self, text: &str, action: EditAction<'_>) -> Option<String> {
411        self.apply_mode(text, action, true, false)
412            .map(|edit| edit.text)
413    }
414
415    pub(crate) fn apply_mode(
416        &mut self,
417        text: &str,
418        action: EditAction<'_>,
419        multiline: bool,
420        overwrite: bool,
421    ) -> Option<AppliedEdit> {
422        self.set_preedit(String::new(), None);
423        self.selection_drag = None;
424        self.preferred_x = None;
425        self.trailing = matches!(
426            action,
427            EditAction::Right(_) | EditAction::WordRight(_) | EditAction::End(_)
428        );
429        let caret = self.caret(text);
430        let selection = self.selection(text);
431        let left = || {
432            text[..caret]
433                .grapheme_indices(true)
434                .next_back()
435                .map_or(0, |(index, _)| index)
436        };
437        let right = || {
438            text[caret..]
439                .graphemes(true)
440                .next()
441                .map_or(caret, |g| caret + g.len())
442        };
443        let previous_word = || {
444            word_ranges(text)
445                .rev()
446                .find(|word| word.start < caret)
447                .map_or(0, |word| boundary(text, word.start))
448        };
449        let next_word = || {
450            word_ranges(text)
451                .find(|word| word.end > caret)
452                .map_or(text.len(), |word| {
453                    text.grapheme_indices(true)
454                        .find(|(index, _)| *index >= word.end)
455                        .map_or(text.len(), |(index, _)| index)
456                })
457        };
458        let mut move_caret = |next: usize, selecting: bool| {
459            self.caret = next;
460            if !selecting {
461                self.anchor = next;
462            }
463        };
464        let (range, replacement) = match action {
465            EditAction::Left(selecting) | EditAction::WordLeft(selecting) => {
466                move_caret(
467                    if !selecting && !selection.is_empty() {
468                        selection.start
469                    } else if matches!(action, EditAction::WordLeft(_)) {
470                        previous_word()
471                    } else {
472                        left()
473                    },
474                    selecting,
475                );
476                return None;
477            }
478            EditAction::Right(selecting) | EditAction::WordRight(selecting) => {
479                move_caret(
480                    if !selecting && !selection.is_empty() {
481                        selection.end
482                    } else if matches!(action, EditAction::WordRight(_)) {
483                        next_word()
484                    } else {
485                        right()
486                    },
487                    selecting,
488                );
489                return None;
490            }
491            EditAction::Home(selecting) => {
492                move_caret(0, selecting);
493                return None;
494            }
495            EditAction::End(selecting) => {
496                move_caret(text.len(), selecting);
497                return None;
498            }
499            EditAction::SelectAll => {
500                self.anchor = 0;
501                self.caret = text.len();
502                return None;
503            }
504            EditAction::Backspace if selection.is_empty() => (left()..caret, String::new()),
505            EditAction::Delete if selection.is_empty() => (caret..right(), String::new()),
506            EditAction::BackspaceWord if selection.is_empty() => {
507                (previous_word()..caret, String::new())
508            }
509            EditAction::DeleteWord if selection.is_empty() => (caret..next_word(), String::new()),
510            EditAction::Backspace
511            | EditAction::Delete
512            | EditAction::BackspaceWord
513            | EditAction::DeleteWord => (selection, String::new()),
514            EditAction::Insert(value)
515            | EditAction::ReplaceAll(value)
516            | EditAction::ReplaceRange { text: value, .. } => {
517                let normalized;
518                let value = if multiline {
519                    normalized = value.replace("\r\n", "\n").replace('\r', "\n");
520                    normalized.as_str()
521                } else {
522                    value
523                };
524                let filtered = value
525                    .chars()
526                    .filter(|ch| !ch.is_control() || (multiline && *ch == '\n'))
527                    .collect::<String>();
528                let explicit = match action {
529                    EditAction::ReplaceAll(_) => Some(0..text.len()),
530                    EditAction::ReplaceRange { start, end, .. } => {
531                        let offset = |byte: i64| {
532                            boundary(text, usize::try_from(byte.max(0)).unwrap_or(text.len()))
533                        };
534                        let (start, end) = (offset(start), offset(end));
535                        Some(start.min(end)..start.max(end))
536                    }
537                    _ => None,
538                };
539                if filtered.is_empty() && !(explicit.is_some() && value.is_empty()) {
540                    return None;
541                }
542                if let Some(range) = explicit {
543                    (range, filtered)
544                } else if overwrite && selection.is_empty() {
545                    let end = overwrite_end(text, caret, &filtered);
546                    (caret..end, filtered)
547                } else {
548                    (selection, filtered)
549                }
550            }
551        };
552        if range.is_empty() && replacement.is_empty() {
553            return None;
554        }
555        let next = range.start + replacement.len();
556        let mut result = text.to_owned();
557        result.replace_range(range.clone(), &replacement);
558        self.caret = if next == result.len() {
559            next
560        } else {
561            result
562                .grapheme_indices(true)
563                .map(|(index, _)| index)
564                .find(|&index| index >= next)
565                .unwrap_or(result.len())
566        };
567        self.anchor = self.caret;
568        self.trailing = !replacement.is_empty();
569        Some(AppliedEdit {
570            text: result,
571            start: range.start,
572            removed: text[range].to_owned(),
573            inserted: replacement,
574        })
575    }
576}
577
578fn overwrite_end(text: &str, caret: usize, inserted: &str) -> usize {
579    // Segment with the preceding grapheme so a combining mark does not consume the next one.
580    let previous = text[..caret]
581        .graphemes(true)
582        .next_back()
583        .unwrap_or_default();
584    let combined = [previous, inserted].concat();
585    let line_break = |cluster: &str| cluster.contains(['\r', '\n']);
586    let count = combined
587        .grapheme_indices(true)
588        .filter(|(offset, _)| *offset >= previous.len())
589        .take_while(|(_, cluster)| !line_break(cluster))
590        .count();
591    caret
592        + text[caret..]
593            .graphemes(true)
594            .take(count)
595            .take_while(|cluster| !line_break(cluster))
596            .map(str::len)
597            .sum::<usize>()
598}
599
600/// The focused editor and selection at the start of an asynchronous edit.
601#[derive(Clone, Debug)]
602pub struct TextEditContext {
603    target: Target,
604    text: String,
605    selection: Range<usize>,
606    caret: TextPosition,
607    password: bool,
608}
609
610impl TextEditContext {
611    #[doc(hidden)]
612    pub fn clipboard_allowed(node: &Node, command: TextCommand, selected: bool) -> bool {
613        match command {
614            TextCommand::Copy => selected && !node.is_password(),
615            TextCommand::Cut => selected && !node.is_password() && !node.text_read_only(),
616            TextCommand::Paste => !node.text_read_only(),
617            _ => false,
618        }
619    }
620
621    pub fn for_clipboard(input: &Interaction, scene: &Node, command: TextCommand) -> Option<Self> {
622        let node = scene.interactive_at_path(&input.focused.as_ref()?.path)?;
623        if !Self::clipboard_allowed(node, command, true) {
624            return None;
625        }
626        let context = Self::capture(input, scene)?;
627        Self::clipboard_allowed(node, command, !context.selection().is_empty()).then_some(context)
628    }
629
630    pub fn capture(input: &Interaction, scene: &Node) -> Option<Self> {
631        let editor = input.editor.as_ref()?;
632        if editor.is_composing() {
633            return None;
634        }
635        let (target, text, selection, caret) = current(input, scene)?;
636        Some(Self {
637            target: target.clone(),
638            text: text.into_owned(),
639            selection,
640            caret,
641            password: scene.at_path(&target.path)?.is_password(),
642        })
643    }
644
645    pub fn selection(&self) -> &str {
646        &self.text[self.selection.clone()]
647    }
648
649    pub fn is_current(&self, input: &Interaction, scene: &Node) -> bool {
650        input
651            .editor
652            .as_ref()
653            .is_some_and(|editor| !editor.is_composing())
654            && self.matches(input, scene)
655    }
656
657    fn matches(&self, input: &Interaction, scene: &Node) -> bool {
658        current(input, scene).is_some_and(|(target, text, selection, caret)| {
659            self.target == *target
660                && scene
661                    .at_path(&target.path)
662                    .is_some_and(|node| node.is_password() == self.password)
663                && self.text == text
664                && self.selection == selection
665                && self.caret == caret
666        })
667    }
668}
669
670impl Interaction {
671    pub fn begin_text_composition(&mut self, scene: &Node, id: u64) -> bool {
672        let cancelled = self.cancel_text_composition(None);
673        if let Some(focus) = self.list_typeahead_focus(scene).cloned() {
674            self.cancel_shortcut_sequence();
675            self.list_composition = Some((id, focus));
676            return true;
677        }
678        let Some(context) = TextEditContext::capture(self, scene)
679            .filter(|context| !self.menu_open() && context.can_compose(self, scene))
680        else {
681            return cancelled;
682        };
683        self.cancel_shortcut_sequence();
684        self.dismiss_choice();
685        self.break_text_edit_group();
686        if let Some(editor) = &mut self.editor {
687            editor.password_echo = None;
688            editor.composition = Some((id, context));
689        }
690        true
691    }
692
693    pub fn update_text_composition(&mut self, scene: &Node, id: u64, text: String) -> bool {
694        let (current_id, valid) = match self.text_composition(scene) {
695            Some(composition) => composition,
696            None => return false,
697        };
698        if id != current_id {
699            return false;
700        }
701        if !valid {
702            return self.cancel_text_composition(Some(id));
703        }
704        if let Some(editor) = &mut self.editor {
705            let end = text.len();
706            editor.update_preedit(text, Some((end, end)));
707        }
708        true
709    }
710
711    pub fn finish_text_composition(&mut self, scene: &Node, id: u64) -> (bool, bool) {
712        let commit = self.text_composition(scene) == Some((id, true));
713        let ended = self.cancel_text_composition(Some(id));
714        (ended, commit)
715    }
716
717    pub fn cancel_text_composition(&mut self, id: Option<u64>) -> bool {
718        if self
719            .list_composition
720            .as_ref()
721            .is_some_and(|(current_id, _)| id.is_none_or(|id| id == *current_id))
722        {
723            self.list_composition = None;
724            return true;
725        }
726        if let Some(editor) = &mut self.editor
727            && let Some((current_id, _)) = &editor.composition
728            && id.is_none_or(|id| id == *current_id)
729        {
730            editor.set_preedit(String::new(), None);
731            return true;
732        }
733        false
734    }
735
736    pub(crate) fn reconcile_text_composition(&mut self, scene: &Node) {
737        if let Some((id, false)) = self.text_composition(scene) {
738            self.cancel_text_composition(Some(id));
739        }
740    }
741
742    fn text_composition(&self, scene: &Node) -> Option<(u64, bool)> {
743        if let Some((id, focus)) = &self.list_composition {
744            return Some((*id, self.list_typeahead_focus(scene) == Some(focus)));
745        }
746        let (id, context) = self.editor.as_ref()?.composition.as_ref()?;
747        Some((*id, !self.menu_open() && context.can_compose(self, scene)))
748    }
749}
750
751impl TextEditContext {
752    fn can_compose(&self, input: &Interaction, scene: &Node) -> bool {
753        self.matches(input, scene)
754            && scene
755                .interactive_at_path(&self.target.path)
756                .is_some_and(|node| !node.text_read_only())
757    }
758}
759
760fn current<'a>(
761    input: &'a Interaction,
762    scene: &'a Node,
763) -> Option<(
764    &'a Target,
765    std::borrow::Cow<'a, str>,
766    Range<usize>,
767    TextPosition,
768)> {
769    let target = input.focused.as_ref()?;
770    let node = scene
771        .interactive_at_path(&target.path)
772        .filter(|node| input.is_text_editor(node, target) || spin_editable(node))?;
773    if !target.matches_node(node) || scene.row_key_at(&target.path) != target.row_key {
774        return None;
775    }
776    let editor = input.editor.as_ref()?;
777    let text = input.editor_value(node);
778    let selection = editor.selection(&text);
779    let caret = editor.position(&text);
780    Some((target, text, selection, caret))
781}
782
783#[cfg(test)]
784mod word_tests {
785    use super::*;
786
787    #[test]
788    fn word_boundaries_keep_combining_sequences_and_joined_emoji_intact() {
789        let text = "e\u{301}clair  👩‍💻 猫";
790        let emoji = text.find('👩').unwrap();
791        let mut editor = TextEdit::at_end(text);
792        editor.apply(text, EditAction::WordLeft(false));
793        assert_eq!(&text[editor.caret(text)..], "猫");
794        editor.apply(text, EditAction::WordLeft(false));
795        assert_eq!(editor.caret(text), emoji);
796        editor.apply(text, EditAction::WordRight(true));
797        assert_eq!(&text[editor.selection(text)], "👩‍💻");
798        assert_eq!(
799            editor.apply(text, EditAction::DeleteWord).as_deref(),
800            Some("e\u{301}clair   猫")
801        );
802
803        let word = "first, second";
804        let mut editor = TextEdit::at_end(word);
805        assert_eq!(
806            editor.apply(word, EditAction::BackspaceWord).as_deref(),
807            Some("first, ")
808        );
809        assert_eq!(
810            editor
811                .apply("first, ", EditAction::BackspaceWord)
812                .as_deref(),
813            Some("first")
814        );
815    }
816
817    #[test]
818    fn overwrite_counts_new_graphemes_and_respects_line_boundaries() {
819        let mut editor = TextEdit::default();
820        let text = "e\u{301}👩‍💻\r\n猫";
821        let result = editor
822            .apply_mode(text, EditAction::Insert("ABC"), true, true)
823            .unwrap();
824        assert_eq!(result.text, "ABC\r\n猫");
825        assert_eq!(result.removed, "e\u{301}👩‍💻");
826
827        editor.place_caret(
828            "e猫",
829            TextPosition {
830                offset: 1,
831                trailing: true,
832            },
833            false,
834        );
835        let edit = editor
836            .apply_mode("e猫", EditAction::Insert("\u{301}"), false, true)
837            .unwrap();
838        assert_eq!(edit.text, "e\u{301}猫");
839        assert!(edit.removed.is_empty());
840
841        editor.place_caret(text, TextPosition::default(), false);
842        let edit = editor
843            .apply_mode(text, EditAction::Insert("\n"), true, true)
844            .unwrap();
845        assert_eq!(edit.text, format!("\n{text}"));
846
847        editor.set_selection(
848            text,
849            0,
850            TextPosition {
851                offset: "e\u{301}".len(),
852                trailing: true,
853            },
854        );
855        let edit = editor
856            .apply_mode(text, EditAction::Insert("AB"), true, true)
857            .unwrap();
858        assert_eq!(edit.text, "AB👩‍💻\r\n猫");
859    }
860
861    #[test]
862    fn pointer_paragraph_drag_keeps_paragraph_boundaries_in_both_directions() {
863        let text = "左端\r\nsecond e\u{301} 👩‍💻\u{2029}last line";
864        let second = text.find("second").unwrap();
865        let third = text.find("last").unwrap();
866        let position = |offset| TextPosition {
867            offset,
868            trailing: false,
869        };
870        let mut edit = TextEdit::default();
871        edit.start_paragraph_drag(text, position(second + 2), false);
872        assert_eq!(&text[edit.selection(text)], "second e\u{301} 👩‍💻");
873
874        assert!(edit.extend_selection_drag(text, position(third + 1)));
875        assert_eq!(
876            &text[edit.selection(text)],
877            "second e\u{301} 👩‍💻\u{2029}last line"
878        );
879        assert!(edit.extend_selection_drag(text, position(0)));
880        assert_eq!(&text[edit.selection(text)], "左端\r\nsecond e\u{301} 👩‍💻");
881        assert!(edit.extend_selection_drag(text, position(second)));
882        assert_eq!(&text[edit.selection(text)], "second e\u{301} 👩‍💻");
883
884        edit.start_paragraph_drag(text, position(0), true);
885        assert_eq!(edit.selection(text), 0..text.len());
886    }
887
888    #[test]
889    fn pointer_word_drag_keeps_its_anchor_when_extending_and_reversing() {
890        let text = "alpha e\u{301}clair 👩‍💻 猫";
891        let selected = text.find('e').unwrap();
892        let after_word = text.find('👩').unwrap() - 1;
893        let mut editor = TextEdit::at_end(text);
894        editor.start_word_drag(
895            text,
896            TextPosition {
897                offset: after_word,
898                trailing: true,
899            },
900            false,
901            true,
902        );
903        assert_eq!(&text[editor.selection(text)], "e\u{301}clair");
904        assert!(editor.extend_selection_drag(
905            text,
906            TextPosition {
907                offset: text.len(),
908                trailing: true
909            }
910        ));
911        assert_eq!(&text[editor.selection(text)], "e\u{301}clair 👩‍💻 猫");
912        assert!(editor.extend_selection_drag(text, TextPosition::default()));
913        assert_eq!(&text[editor.selection(text)], "alpha e\u{301}clair");
914        assert!(editor.extend_selection_drag(
915            text,
916            TextPosition {
917                offset: selected,
918                trailing: false
919            }
920        ));
921        assert_eq!(&text[editor.selection(text)], "e\u{301}clair");
922        assert!(!editor.extend_selection_drag("replacement", TextPosition::default()));
923
924        editor.start_word_drag(text, TextPosition::default(), true, true);
925        assert_eq!(editor.selection(text), 0..text.len());
926
927        let position = TextPosition {
928            offset: 2,
929            trailing: true,
930        };
931        editor.start_word_drag(text, position, false, false);
932        assert_eq!(editor.selection(text), 2..2);
933        assert!(editor.extend_selection_drag(
934            text,
935            TextPosition {
936                offset: 3,
937                trailing: true
938            }
939        ));
940        assert_eq!(&text[editor.selection(text)], "alpha");
941    }
942
943    #[test]
944    fn word_shortcuts_respect_the_keyboard_platform_and_alt_graph() {
945        let option = KeyModifiers {
946            alt: true,
947            shift: true,
948            ..Default::default()
949        };
950        let control = KeyModifiers {
951            control: true,
952            ..Default::default()
953        };
954        assert!(matches!(
955            EditAction::word_shortcut("ArrowLeft", option, true),
956            Some(EditAction::WordLeft(true))
957        ));
958        assert!(EditAction::word_shortcut("ArrowLeft", option, false).is_none());
959        assert!(matches!(
960            EditAction::word_shortcut("Backspace", control, false),
961            Some(EditAction::BackspaceWord)
962        ));
963        assert!(EditAction::word_shortcut("Backspace", control, true).is_none());
964        let both = KeyModifiers {
965            alt: true,
966            ..control
967        };
968        assert!(EditAction::word_shortcut("Delete", both, true).is_none());
969        assert!(EditAction::word_shortcut("Delete", both, false).is_none());
970    }
971}