Debian Codegraph @

src/utils/input.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 //! Generalized input logic, to make it easier to reuse logic like unicode
2 //! handling and cursor movement.
3
4 use std::ops::Range;
5
6 use concat_string::concat_string;
7 use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete, UnicodeSegmentation};
8
•9 use crate::{app::CursorDirection, utils::{int_hash::IntIndexMap, strings::str_width}};
10
11 /// An input field's state.
12 pub struct InputFieldState {
13 /// The search query itself, what is shown.
14 current_query: String,
15
16 /// The internal grapheme cursor to track the current location.
17 grapheme_cursor: GraphemeCursor,
18
19 /// The direction the cursor is heading at the moment. Modified
20 /// by user actions, e.g. adding text moves it right, deleting
21 /// text moves it left, the user scrolling changes it based
22 /// on where they scroll, etc.
23 cursor_direction: CursorDirection,
24
25 /// Determines where we start _displaying_ the search based on
26 /// the user's scroll. For example, if they move the cursor 5
27 /// units to the right from 0, the index should be 5.
28 display_start_index: usize,
29
30 /// Used for internal tracking of _byte_ indices to the widths
31 /// of the graphemes they represent. This is mostly used to cache
32 /// and avoid having to re-calculate widths each time it needs to
33 /// be accessed.
34 ///
35 /// Should always be updated after the search query updates in any way.
36 size_mappings: IntIndexMap<usize, Range<usize>>,
37 }
38
39 impl Default for InputFieldState {
40 fn default() -> Self {
41 Self {
42 current_query: String::default(),
43 grapheme_cursor: GraphemeCursor::new(0, 0, true),
44 cursor_direction: CursorDirection::Right,
45 display_start_index: 0,
46 size_mappings: IntIndexMap::default(),
47 }
48 }
49 }
50
51 impl InputFieldState {
52 /// Get a reference to the current query.
53 #[inline]
54 pub(crate) fn current_query(&self) -> &str {
55 &self.current_query
56 }
57
58 /// Get the current cursor index.
59 #[inline]
60 pub(crate) fn cursor_index(&self) -> usize {
61 self.grapheme_cursor.cur_cursor()
62 }
63
64 /// Get the display start index.
65 #[inline]
66 pub(crate) fn display_start_index(&self) -> usize {
67 self.display_start_index
68 }
69
70 /// Sets the starting grapheme index to draw from.
71 ///
72 /// TODO: This is kinda weird, we might want to decouple this in some way
73 /// such that this is clear this only matters for drawing... but it also
74 /// changes states...
75 pub(crate) fn get_start_position(&mut self, available_width: usize, is_force_redraw: bool) {
76 // Remember - the number of columns != the number of grapheme slots/sizes, you
77 // cannot use index to determine this reliably!
78
79 let start_index = if is_force_redraw {
80 0
81 } else {
82 self.display_start_index
83 };
84 let cursor_index = self.cursor_index();
85
86 if let Some(start_range) = self.size_mappings.get(&start_index) {
87 let cursor_range = self
88 .size_mappings
89 .get(&cursor_index)
90 .cloned()
91 .unwrap_or_else(|| {
92 self.size_mappings
93 .last()
94 .map(|(_, r)| r.end..(r.end + 1))
95 .unwrap_or(start_range.end..(start_range.end + 1))
96 });
97
98 // Cases to handle in both cases:
99 // - The current start index can show the cursor's word.
100 // - The current start index cannot show the cursor's word.
101 //
102 // What differs is how we "scroll" based on the cursor movement direction.
103
104 self.display_start_index = match self.cursor_direction {
105 CursorDirection::Right => {
106 if start_range.start + available_width >= cursor_range.end {
107 // Use the current index.
108 start_index
109 } else if cursor_range.end >= available_width {
110 // If the current position is past the last visible element, skip until we
111 // see it.
112
113 let mut index = 0;
114 for i in 0..(cursor_index + 1) {
115 if let Some(r) = self.size_mappings.get(&i)
116 && r.start + available_width >= cursor_range.end
117 {
118 index = i;
119 break;
120 }
121 }
122
123 index
124 } else {
125 0
126 }
127 }
128 CursorDirection::Left => {
129 if cursor_range.start < start_range.end {
130 let mut index = 0;
131 for i in cursor_index..(self.current_query.len()) {
132 if let Some(r) = self.size_mappings.get(&i)
133 && r.start + available_width >= cursor_range.end
134 {
135 index = i;
136 break;
137 }
138 }
139 index
140 } else {
141 start_index
142 }
143 }
144 };
145 } else {
146 // If we fail here somehow, just reset to 0 index + scroll left.
147 self.display_start_index = 0;
148 self.cursor_direction = CursorDirection::Left;
149 };
150 }
151
152 /// Move the cursor one _grapheme_ forward.
153 fn walk_forward(&mut self) {
154 let start_position = self.cursor_index();
155 let chunk = &self.current_query[start_position..];
156
157 match self.grapheme_cursor.next_boundary(chunk, start_position) {
158 Ok(_) => {}
159 Err(err) => match err {
160 GraphemeIncomplete::PreContext(ctx) => {
161 // Provide the entire string as context. Not efficient but should resolve
162 // failures.
163 self.grapheme_cursor
164 .provide_context(&self.current_query[0..ctx], 0);
165
166 self.grapheme_cursor
167 .next_boundary(chunk, start_position)
168 .expect("another grapheme boundary should exist after the cursor with the provided context");
169 }
170 _ => panic!("{err:?}"),
171 },
172 }
173 }
174
175 /// Move the cursor one _grapheme_ backward.
176 fn walk_backward(&mut self) {
177 let start_position = self.cursor_index();
178 let chunk = &self.current_query[..start_position];
179
180 match self.grapheme_cursor.prev_boundary(chunk, 0) {
181 Ok(_) => {}
182 Err(err) => match err {
183 GraphemeIncomplete::PreContext(ctx) => {
184 // Provide the entire string as context. Not efficient but should resolve
185 // failures.
186 self.grapheme_cursor
187 .provide_context(&self.current_query[0..ctx], 0);
188
189 self.grapheme_cursor
190 .prev_boundary(chunk, 0)
191 .expect("another grapheme boundary should exist before the cursor with the provided context");
192 }
193 _ => panic!("{err:?}"),
194 },
195 }
196 }
197
198 /// Update the size mappings (mapping of index to the display width range)
199 /// after the query has been updated in any way. This should be called
200 /// whenever the query is updated.
201 ///
202 /// TODO: This might be a bit expensive, maybe we could update this a bit
203 /// more iteratively?
204 fn update_sizes(&mut self) {
205 self.size_mappings.clear();
206 let mut curr_offset = 0;
207 for (index, grapheme) in
208 UnicodeSegmentation::grapheme_indices(self.current_query.as_str(), true)
209 {
•210 let width = str_width(grapheme);
211 let end = curr_offset + width;
212
213 self.size_mappings.insert(index, curr_offset..end);
214
215 curr_offset = end;
216 }
217 }
218
219 /// Delete whatever the cursor is currently highlighting, if anything. This
220 /// is analogous to pressing `Delete`.
221 pub(crate) fn delete_at_cursor(&mut self) {
222 let current_cursor = self.cursor_index();
223 if current_cursor < self.current_query.len() {
224 self.walk_forward();
225 let new_cursor = self.cursor_index();
226
227 let _ = self.current_query.drain(current_cursor..new_cursor);
228
229 self.grapheme_cursor =
230 GraphemeCursor::new(current_cursor, self.current_query.len(), true);
231
232 self.update_sizes();
233 }
234 }
235
236 /// Delete what is _behind_ the cursor. This is analogous to pressing
237 /// `Backspace`.
238 pub(crate) fn delete_behind_cursor(&mut self) {
239 let current_cursor = self.cursor_index();
240
241 if current_cursor > 0 {
242 self.walk_backward();
243 let new_cursor = self.cursor_index();
244
245 // Remove the indices in between.
246 let _ = self.current_query.drain(new_cursor..current_cursor);
247
248 self.grapheme_cursor = GraphemeCursor::new(new_cursor, self.current_query.len(), true);
249
250 self.cursor_direction = CursorDirection::Left;
251
252 self.update_sizes();
253 }
254 }
255
256 /// Move the cursor left one unit if possible.
257 pub(crate) fn move_left(&mut self) {
258 let current_cursor = self.cursor_index();
259 self.walk_backward();
260 if self.cursor_index() < current_cursor {
261 self.cursor_direction = CursorDirection::Left;
262 }
263 }
264
265 /// Move the cursor right one unit if possible.
266 pub(crate) fn move_right(&mut self) {
267 let current_cursor = self.cursor_index();
268 self.walk_forward();
269 if self.cursor_index() > current_cursor {
270 self.cursor_direction = CursorDirection::Right;
271 }
272 }
273
274 /// Move the cursor to the start.
275 pub(crate) fn skip_to_beginning(&mut self) {
276 self.grapheme_cursor = GraphemeCursor::new(0, self.current_query.len(), true);
277 self.cursor_direction = CursorDirection::Left;
278 }
279
280 /// Move the cursor to the end.
281 pub(crate) fn skip_to_end(&mut self) {
282 let query_len = self.current_query.len();
283 self.grapheme_cursor = GraphemeCursor::new(query_len, query_len, true);
284 self.cursor_direction = CursorDirection::Right;
285 }
286
287 /// Delete the previous "word".
288 pub(crate) fn delete_previous_word(&mut self) {
289 // Traverse backwards from the current cursor location until you hit
290 // non-whitespace characters, then continue to traverse (and
291 // delete) backwards until you hit a whitespace character. Halt.
292
293 // So... first, let's get our current cursor position in terms of char
294 // indices. This is the "end" index we care about.
295 let current_cursor = self.cursor_index();
296
297 // Then, let's crawl backwards until we hit our location, and store the
298 // "head"...
299 let query = self.current_query();
300 let mut start_index = 0;
301 let mut saw_non_whitespace = false;
302
303 for (itx, c) in query[..current_cursor].char_indices().rev() {
304 if c.is_whitespace() {
305 if saw_non_whitespace {
306 start_index = itx + c.len_utf8();
307 break;
308 }
309 } else {
310 saw_non_whitespace = true;
311 }
312 }
313
314 let _ = self.current_query.drain(start_index..current_cursor);
315
316 self.grapheme_cursor = GraphemeCursor::new(start_index, self.current_query.len(), true);
317
318 self.cursor_direction = CursorDirection::Left;
319
320 self.update_sizes();
321 }
322
323 /// Insert a single [`char`].
324 pub(crate) fn insert_char(&mut self, ch: char) {
325 self.current_query.insert(self.cursor_index(), ch);
326
327 self.grapheme_cursor =
328 GraphemeCursor::new(self.cursor_index(), self.current_query.len(), true);
329
330 self.walk_forward();
331 self.cursor_direction = CursorDirection::Right;
332
333 self.update_sizes();
334 }
335
336 /// Insert a [`String`].
337 pub(crate) fn insert_string(&mut self, s: String) {
338 let left_bound = self.cursor_index();
339
340 let current_query = &mut self.current_query;
341 let (left, right) = current_query.split_at(left_bound);
342 let num_runes = UnicodeSegmentation::graphemes(s.as_str(), true).count();
343
344 *current_query = concat_string!(left, s, right);
345
346 self.grapheme_cursor = GraphemeCursor::new(left_bound, current_query.len(), true);
347
348 for _ in 0..num_runes {
349 self.walk_forward();
350 }
351
352 self.cursor_direction = CursorDirection::Right;
353
354 self.update_sizes();
355 }
356
357 /// Returns an iterator over graphemes with the byte index + display-width
358 /// range.
359 pub(crate) fn graphemes_with_ranges(
360 &self,
361 ) -> impl Iterator<Item = (usize, &str, &Range<usize>)> {
362 let query = self.current_query();
363 let mut iter = self.size_mappings.iter().peekable();
364
365 std::iter::from_fn(move || {
366 let (&start, lengths) = iter.next()?;
367 let end = iter.peek().map(|&(&next, _)| next).unwrap_or(query.len());
368 let grapheme = &query[start..end];
369
370 Some((start, grapheme, lengths))
371 })
372 }
373 }
374
375 #[cfg(test)]
376 mod tests {
377 use super::*;
378
379 /// Tests that inserting ASCII chars appends them to the query and advances
380 /// the cursor by 1 byte each.
381 #[test]
382 fn insert_char_ascii() {
383 let mut state = InputFieldState::default();
384
385 state.insert_char('H');
386 assert_eq!(state.current_query(), "H");
387 assert_eq!(state.cursor_index(), 1);
388
389 state.insert_char('i');
390 assert_eq!(state.current_query(), "Hi");
391 assert_eq!(state.cursor_index(), 2);
392 }
393
394 /// Tests that inserting multi-byte Unicode chars (e.g. CJK) advances the
395 /// cursor by the correct byte width.
396 #[test]
397 fn insert_char_unicode() {
398 let mut state = InputFieldState::default();
399
400 state.insert_char('你'); // 3-byte UTF-8
401 assert_eq!(state.current_query(), "你");
402 assert_eq!(state.cursor_index(), 3);
403
404 state.insert_char('好');
405 assert_eq!(state.current_query(), "你好");
406 assert_eq!(state.cursor_index(), 6);
407 }
408
409 /// Tests that inserting a 4-byte emoji advances the cursor to byte offset
410 /// 4.
411 #[test]
412 fn insert_char_emoji() {
413 let mut state = InputFieldState::default();
414
415 state.insert_char('🦀'); // 4-byte UTF-8
416 assert_eq!(state.current_query(), "🦀");
417 assert_eq!(state.cursor_index(), 4);
418 }
419
420 /// Tests that inserting a char at a mid-string cursor position shifts the
421 /// rest of the string right and places the cursor immediately after the
422 /// newly inserted char.
423 #[test]
424 fn insert_char_at_middle() {
425 let mut state = InputFieldState::default();
426 state.insert_char('H');
427 state.insert_char('i');
428 state.insert_char('!');
429
430 // Move back to before '!'
431 state.move_left();
432 assert_eq!(state.cursor_index(), 2);
433
434 state.insert_char(' ');
435 assert_eq!(state.current_query(), "Hi !");
436 assert_eq!(state.cursor_index(), 3);
437 }
438
439 /// Tests that inserting an ASCII string at once places the entire string in
440 /// the query and lands the cursor at the end.
441 #[test]
442 fn insert_string_ascii() {
443 let mut state = InputFieldState::default();
444 state.insert_string("Hello".to_string());
445 assert_eq!(state.current_query(), "Hello");
446 assert_eq!(state.cursor_index(), 5);
447 }
448
449 /// Tests that inserting a mixed multi-byte + emoji string reflects the
450 /// correct total byte length in the cursor position.
451 #[test]
452 fn insert_string_unicode() {
453 let mut state = InputFieldState::default();
454 state.insert_string("你好🇨🇦🦀".to_string());
455 assert_eq!(state.current_query(), "你好🇨🇦🦀");
456 // '你'=3, '好'=3, '🦀'=4, '🇨🇦'=8, so 18 bytes
457 assert_eq!(state.cursor_index(), 18);
458 }
459
460 /// Tests that inserting a string at position 0 prepends it, leaving the
461 /// cursor after the inserted portion and the rest of the original
462 /// string intact.
463 #[test]
464 fn insert_string_at_middle() {
465 let mut state = InputFieldState::default();
466 state.insert_string("Hello".to_string());
467 state.skip_to_beginning();
468 state.insert_string("Say ".to_string());
469 assert_eq!(state.current_query(), "Say Hello");
470 assert_eq!(state.cursor_index(), 4);
471 }
472
473 /// Tests that [`InputFieldState::delete_at_cursor`] removes the grapheme
474 /// under the cursor without moving the cursor position.
475 #[test]
476 fn delete_at_cursor_basic() {
477 let mut state = InputFieldState::default();
478 state.insert_string("Hello".to_string());
479 state.skip_to_beginning();
480
481 state.delete_at_cursor(); // removes 'H'
482 assert_eq!(state.current_query(), "ello");
483 assert_eq!(state.cursor_index(), 0);
484
485 state.delete_at_cursor(); // removes 'e'
486 assert_eq!(state.current_query(), "llo");
487 assert_eq!(state.cursor_index(), 0);
488 }
489
490 /// Tests that [`InputFieldState::delete_at_cursor`] is a no-op when the
491 /// cursor is already at the end of the string.
492 #[test]
493 fn delete_at_cursor_at_end_is_noop() {
494 let mut state = InputFieldState::default();
495 state.insert_string("Hi".to_string());
496 // cursor is already at end after inserting
497
498 state.delete_at_cursor();
499 assert_eq!(state.current_query(), "Hi");
500 assert_eq!(state.cursor_index(), 2);
501 }
502
503 /// Tests that [`InputFieldState::delete_at_cursor`] correctly removes a
504 /// full multi-byte grapheme cluster in one operation.
505 #[test]
506 fn delete_at_cursor_unicode() {
507 let mut state = InputFieldState::default();
508 state.insert_string("你好".to_string());
509 state.skip_to_beginning();
510
511 state.delete_at_cursor(); // removes '你' (3 bytes)
512 assert_eq!(state.current_query(), "好");
513 assert_eq!(state.cursor_index(), 0);
514 }
515
516 /// Tests that [`InputFieldState::delete_behind_cursor`] removes the
517 /// grapheme immediately before the cursor and moves the cursor back
518 /// accordingly.
519 #[test]
520 fn delete_behind_cursor_basic() {
521 let mut state = InputFieldState::default();
522 state.insert_string("Hello".to_string());
523
524 state.delete_behind_cursor(); // removes 'o'
525 assert_eq!(state.current_query(), "Hell");
526 assert_eq!(state.cursor_index(), 4);
527
528 state.delete_behind_cursor(); // removes 'l'
529 assert_eq!(state.current_query(), "Hel");
530 assert_eq!(state.cursor_index(), 3);
531 }
532
533 /// Tests that [`InputFieldState::delete_behind_cursor`] is a no-op when the
534 /// cursor is at position 0.
535 #[test]
536 fn delete_behind_cursor_at_start_is_noop() {
537 let mut state = InputFieldState::default();
538 state.insert_string("Hi".to_string());
539 state.skip_to_beginning();
540
541 state.delete_behind_cursor();
542 assert_eq!(state.current_query(), "Hi");
543 assert_eq!(state.cursor_index(), 0);
544 }
545
546 /// Tests that [`InputFieldState::delete_behind_cursor`] correctly removes
547 /// multi-byte grapheme clusters one at a time, adjusting the byte
548 /// cursor each time.
549 #[test]
550 fn delete_behind_cursor_unicode() {
551 let mut state = InputFieldState::default();
552 state.insert_string("你好".to_string());
553
554 state.delete_behind_cursor(); // removes '好' (3 bytes)
555 assert_eq!(state.current_query(), "你");
556 assert_eq!(state.cursor_index(), 3);
557
558 state.delete_behind_cursor(); // removes '你' (3 bytes)
559 assert_eq!(state.current_query(), "");
560 assert_eq!(state.cursor_index(), 0);
561 }
562
563 /// Tests that [`InputFieldState::move_left`] and
564 /// [`InputFieldState::move_right`] step one byte per ASCII grapheme and
565 /// are clamped at both ends of the string.
566 #[test]
567 fn move_left_right_ascii() {
568 let mut state = InputFieldState::default();
569 state.insert_string("abc".to_string());
570 assert_eq!(state.cursor_index(), 3);
571
572 state.move_left();
573 assert_eq!(state.cursor_index(), 2);
574 state.move_left();
575 assert_eq!(state.cursor_index(), 1);
576 state.move_left();
577 assert_eq!(state.cursor_index(), 0);
578
579 // At the start - no further movement
580 state.move_left();
581 assert_eq!(state.cursor_index(), 0);
582
583 state.move_right();
584 assert_eq!(state.cursor_index(), 1);
585 state.move_right();
586 assert_eq!(state.cursor_index(), 2);
587 state.move_right();
588 assert_eq!(state.cursor_index(), 3);
589
590 // At the end - no further movement
591 state.move_right();
592 assert_eq!(state.cursor_index(), 3);
593 }
594
595 /// Tests that [`InputFieldState::move_left`] and
596 /// [`InputFieldState::move_right`] jump the full byte width of each
597 /// grapheme, including multi-byte CJK characters.
598 #[test]
599 fn move_left_right_unicode() {
600 let mut state = InputFieldState::default();
601 state.insert_string("a你b".to_string()); // 1 + 3 + 1 = 5 bytes
602 assert_eq!(state.cursor_index(), 5);
603
604 state.move_left(); // over 'b' (1 byte)
605 assert_eq!(state.cursor_index(), 4);
606
607 state.move_left(); // over '你' (3 bytes)
608 assert_eq!(state.cursor_index(), 1);
609
610 state.move_left(); // over 'a' (1 byte)
611 assert_eq!(state.cursor_index(), 0);
612 }
613
614 /// Tests that [`InputFieldState::skip_to_beginning`] moves the cursor to
615 /// byte 0 and [`InputFieldState::skip_to_end`] moves it past the last
616 /// byte.
617 #[test]
618 fn skip_to_beginning_and_end() {
619 let mut state = InputFieldState::default();
620 state.insert_string("Hello".to_string());
621
622 state.skip_to_beginning();
623 assert_eq!(state.cursor_index(), 0);
624
625 state.skip_to_end();
626 assert_eq!(state.cursor_index(), 5);
627 }
628
629 /// Tests that [`InputFieldState::skip_to_beginning`] sets the cursor
630 /// direction to [`CursorDirection::Left`] so that scrolling logic
631 /// behaves correctly.
632 #[test]
633 fn skip_to_beginning_sets_direction_left() {
634 let mut state = InputFieldState::default();
635 state.insert_string("Hello".to_string());
636 state.skip_to_beginning();
637 assert!(matches!(state.cursor_direction, CursorDirection::Left));
638 }
639
640 /// Tests that [`InputFieldState::skip_to_end`] sets the cursor direction to
641 /// [`CursorDirection::Right`] so that scrolling logic behaves correctly.
642 #[test]
643 fn skip_to_end_sets_direction_right() {
644 let mut state = InputFieldState::default();
645 state.insert_string("Hello".to_string());
646 state.skip_to_beginning();
647 state.skip_to_end();
648 assert!(matches!(state.cursor_direction, CursorDirection::Right));
649 }
650
651 /// Tests that [`InputFieldState::delete_previous_word`] removes a single
652 /// word with no preceding whitespace, leaving an empty query.
653 #[test]
654 fn delete_previous_word_single_word() {
655 let mut state = InputFieldState::default();
656 state.insert_string("Hello".to_string());
657
658 state.delete_previous_word();
659 assert_eq!(state.current_query(), "");
660 assert_eq!(state.cursor_index(), 0);
661 }
662
663 /// Tests that [`InputFieldState::delete_previous_word`] removes exactly one
664 /// word per call when the query contains multiple words separated by a
665 /// space.
666 #[test]
667 fn delete_previous_word_two_words() {
668 let mut state = InputFieldState::default();
669 state.insert_string("Hello World".to_string());
670
671 state.delete_previous_word(); // deletes "World"
672 assert_eq!(state.current_query(), "Hello ");
673 assert_eq!(state.cursor_index(), 6);
674
675 state.delete_previous_word(); // deletes "Hello "
676 assert_eq!(state.current_query(), "");
677 assert_eq!(state.cursor_index(), 0);
678 }
679
680 /// Tests that [`InputFieldState::delete_previous_word`] skips trailing
681 /// whitespace before deleting the preceding non-whitespace word.
682 #[test]
683 fn delete_previous_word_trailing_spaces() {
684 let mut state = InputFieldState::default();
685 state.insert_string("Hello ".to_string()); // trailing spaces
686
687 // Should skip spaces first, then delete "Hello"
688 state.delete_previous_word();
689 assert_eq!(state.current_query(), "");
690 assert_eq!(state.cursor_index(), 0);
691 }
692
693 /// Tests that [`InputFieldState::delete_previous_word`] only removes the
694 /// portion of a word that lies behind the cursor when the cursor is
695 /// mid-word.
696 #[test]
697 fn delete_previous_word_from_middle() {
698 let mut state = InputFieldState::default();
699 state.insert_string("Hello World".to_string());
700 state.skip_to_beginning();
701 // Advance 3 chars ('H','e','l')
702 state.move_right();
703 state.move_right();
704 state.move_right();
705 assert_eq!(state.cursor_index(), 3);
706
707 state.delete_previous_word(); // deletes "Hel"
708 assert_eq!(state.current_query(), "lo World");
709 assert_eq!(state.cursor_index(), 0);
710 }
711
712 /// Tests that [`InputFieldState::delete_previous_word`] correctly handles
713 /// multibyte characters. The char/byte index mismatch bug would cause
714 /// `.skip(query.len() - current_cursor)` to skip the wrong number of
715 /// chars and `query.len() - itx` to land on a non-char-boundary, either
716 /// producing the wrong result or panicking.
717 #[test]
718 fn delete_previous_word_unicode() {
719 // "你好 world" - '你'=3 bytes, '好'=3 bytes, ' '=1, "world"=5, so 12 bytes
720 // total
721 let mut state = InputFieldState::default();
722 state.insert_string("你好 world".to_string());
723
724 // Cursor is at the end (byte 12). Deleting the previous word should remove
725 // "world", leaving "你好 " (7 bytes).
726 state.delete_previous_word();
727 assert_eq!(state.current_query(), "你好 ");
728 assert_eq!(state.cursor_index(), 7);
729
730 // Deleting again skips the trailing space then removes "你好", leaving "".
731 state.delete_previous_word();
732 assert_eq!(state.current_query(), "");
733 assert_eq!(state.cursor_index(), 0);
734 }
735
736 /// Test that [`InputFieldState::graphemes_with_ranges`] returns the correct
737 /// graphemes along with their byte indices and display width ranges.
738 #[test]
739 fn test_graphemes_with_ranges() {
740 let query = "Test你🇨🇦".to_string();
741 let query_len = query.len();
742
743 assert_eq!(query_len, 15); // 4 + 3 + 8
744
745 let mut state = InputFieldState::default();
746 state.insert_string(query);
747
748 let graphemes: Vec<(usize, &str, &Range<usize>)> = state.graphemes_with_ranges().collect();
749 assert_eq!(graphemes.len(), 6);
750
751 assert_eq!(graphemes[0], (0, "T", &(0..1)));
752 assert_eq!(graphemes[1], (1, "e", &(1..2)));
753 assert_eq!(graphemes[2], (2, "s", &(2..3)));
754 assert_eq!(graphemes[3], (3, "t", &(3..4)));
755 assert_eq!(
756 graphemes[4],
757 (4, "你", &(4..6)),
758 "你 is 3 bytes long, total grapheme is 2-wide"
759 );
760 assert_eq!(
761 graphemes[5],
762 (7, "🇨🇦", &(6..8)),
763 "🇨🇦 is 8 bytes long, total grapheme is 2-wide"
764 );
765
766 assert_eq!(
767 query_len - graphemes[5].0,
768 8,
769 "flag grapheme is 8 bytes long"
770 );
771 }
772
773 /// Tests that the cursor moves correctly when moving left and right, as
774 /// well as things work correctly around updating the display start
775 /// index.
776 #[test]
777 fn search_cursor_moves() {
778 let mut state = InputFieldState::default();
779 state.insert_string("Hi, 你好! 🇨🇦".to_string());
780 state.skip_to_beginning();
781
782 // Moving right.
783 state.get_start_position(4, false);
784 assert_eq!(state.grapheme_cursor.cur_cursor(), 0);
785 assert_eq!(state.display_start_index, 0);
786
787 state.move_right();
788 state.get_start_position(4, false);
789 assert_eq!(state.grapheme_cursor.cur_cursor(), 1);
790 assert_eq!(state.display_start_index, 0);
791
792 state.move_right();
793 state.get_start_position(4, false);
794 assert_eq!(state.grapheme_cursor.cur_cursor(), 2);
795 assert_eq!(state.display_start_index, 0);
796
797 state.move_right();
798 state.get_start_position(4, false);
799 assert_eq!(state.grapheme_cursor.cur_cursor(), 3);
800 assert_eq!(state.display_start_index, 0);
801
802 state.move_right();
803 state.get_start_position(4, false);
804 assert_eq!(state.grapheme_cursor.cur_cursor(), 4);
805 assert_eq!(state.display_start_index, 2);
806
807 state.move_right();
808 state.get_start_position(4, false);
809 assert_eq!(state.grapheme_cursor.cur_cursor(), 7);
810 assert_eq!(state.display_start_index, 4);
811
812 state.move_right();
813 state.get_start_position(4, false);
814 assert_eq!(state.grapheme_cursor.cur_cursor(), 10);
815 assert_eq!(state.display_start_index, 7);
816
817 state.move_right();
818 state.move_right();
819 state.get_start_position(4, false);
820 assert_eq!(state.grapheme_cursor.cur_cursor(), 12);
821 assert_eq!(state.display_start_index, 10);
822
823 // Move past the flag emoji (🇨🇦 = 8 bytes) to the end of string (byte 20).
824 state.move_right();
825 state.get_start_position(4, false);
826 assert_eq!(state.grapheme_cursor.cur_cursor(), 20);
827 assert_eq!(state.display_start_index, 11);
828
829 // Clamped at the end - no further movement.
830 state.move_right();
831 state.get_start_position(4, false);
832 assert_eq!(state.grapheme_cursor.cur_cursor(), 20);
833 assert_eq!(state.display_start_index, 11);
834
835 // Moving left - back over the flag emoji.
836 state.move_left();
837 state.get_start_position(4, false);
838 assert_eq!(state.grapheme_cursor.cur_cursor(), 12);
839 assert_eq!(state.display_start_index, 11);
840
841 state.move_left();
842 state.get_start_position(4, false);
843 assert_eq!(state.grapheme_cursor.cur_cursor(), 11);
844 assert_eq!(state.display_start_index, 11);
845
846 state.move_left();
847 state.move_left();
848 state.get_start_position(4, false);
849 assert_eq!(state.grapheme_cursor.cur_cursor(), 7);
850 assert_eq!(state.display_start_index, 7);
851
852 state.move_left();
853 state.move_left();
854 state.move_left();
855 state.move_left();
856 state.get_start_position(4, false);
857 assert_eq!(state.grapheme_cursor.cur_cursor(), 1);
858 assert_eq!(state.display_start_index, 1);
859
860 state.move_left();
861 state.get_start_position(4, false);
862 assert_eq!(state.grapheme_cursor.cur_cursor(), 0);
863 assert_eq!(state.display_start_index, 0);
864 }
865 }