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