Debian Codegraph @

src/utils/input.rs

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