Skip to main content

mach/
text_input.rs

1//! A one-line editor. Every text field in mach is built from it —
2//! the title, the due date, category names, the command line, the search
3//! box, and each block of a task's description. Cursor and selection indices are
4//! Unicode grapheme clusters; display geometry is still measured in cells.
5//!
6//! Selection follows macOS: Shift extends, Option jumps by word, and
7//! Shift+Option+W selects the word under the cursor.
8
9use unicode_segmentation::UnicodeSegmentation;
10use unicode_width::UnicodeWidthStr;
11
12#[derive(Debug, Default, Clone, PartialEq, Eq)]
13pub struct TextInput {
14    /// Extended grapheme clusters. A visible user-perceived character is
15    /// never split by cursor movement, selection, or deletion.
16    chars: Vec<String>,
17    cursor: usize,
18    /// Other end of the selection; `None` means a caret only.
19    sel_anchor: Option<usize>,
20    scroll: usize,
21    max_len: usize,
22    max_bytes: usize,
23}
24
25/// What [`TextInput::visible`] hands the UI: text, caret column, and an
26/// optional selection span in display columns within that text.
27#[derive(Debug, Clone)]
28pub struct View {
29    pub text: String,
30    pub cursor_col: u16,
31    /// Inclusive start, exclusive end, in display columns of `text`.
32    pub sel_cols: Option<(u16, u16)>,
33}
34
35/// One visual row of a soft-wrapped field.
36#[derive(Debug, Clone)]
37pub struct WrappedLine {
38    pub text: String,
39    pub sel_cols: Option<(u16, u16)>,
40    /// Grapheme range into the full buffer covered by this row.
41    pub start: usize,
42    pub end: usize,
43}
44
45/// Soft-wrapped layout for multi-line description painting.
46#[derive(Debug, Clone)]
47pub struct WrappedView {
48    pub lines: Vec<WrappedLine>,
49    /// Cursor row within `lines`, and column within that row.
50    pub cursor_row: u16,
51    pub cursor_col: u16,
52}
53
54/// Soft-wrap graphemes into `(start, end)` ranges of at most `width`
55/// display columns. Prefers breaking after a space; otherwise hard-breaks.
56pub fn wrap_breaks(chars: &[String], width: usize) -> Vec<(usize, usize)> {
57    if chars.is_empty() {
58        return vec![(0, 0)];
59    }
60    let width = width.max(1);
61    let mut lines = Vec::new();
62    let mut start = 0usize;
63    let mut col = 0usize;
64    let mut last_ws: Option<usize> = None;
65    let mut i = 0usize;
66
67    while i < chars.len() {
68        let w = chars[i].width();
69        if w > width {
70            // Lone character wider than the field — own row.
71            if i > start {
72                lines.push((start, i));
73            }
74            lines.push((i, i + 1));
75            i += 1;
76            start = i;
77            col = 0;
78            last_ws = None;
79            continue;
80        }
81        if col + w > width && i > start {
82            // Prefer the last space so words stay intact when they fit.
83            let end = last_ws
84                .filter(|&ws| ws >= start)
85                .map(|ws| ws + 1)
86                .unwrap_or(i);
87            let end = end.max(start + 1);
88            lines.push((start, end));
89            start = end;
90            i = start;
91            col = 0;
92            last_ws = None;
93            continue;
94        }
95        if is_whitespace(&chars[i]) {
96            last_ws = Some(i);
97        }
98        col += w;
99        i += 1;
100    }
101    if start < chars.len() {
102        lines.push((start, chars.len()));
103    }
104    lines
105}
106
107fn is_whitespace(grapheme: &str) -> bool {
108    !grapheme.is_empty() && grapheme.chars().all(char::is_whitespace)
109}
110
111impl TextInput {
112    pub fn new(initial: &str, max_len: usize) -> Self {
113        let max_bytes = crate::model::text_byte_limit(max_len);
114        let chars = bounded_graphemes(initial, max_len, max_bytes);
115        let cursor = chars.len();
116        Self {
117            chars,
118            cursor,
119            sel_anchor: None,
120            scroll: 0,
121            max_len,
122            max_bytes,
123        }
124    }
125
126    pub fn value(&self) -> String {
127        self.chars.concat()
128    }
129
130    pub fn is_empty(&self) -> bool {
131        self.chars.is_empty()
132    }
133
134    pub fn cursor(&self) -> usize {
135        self.cursor
136    }
137
138    pub fn len(&self) -> usize {
139        self.chars.len()
140    }
141
142    pub fn slice(&self, start: usize, end: usize) -> String {
143        let start = start.min(self.chars.len());
144        let end = end.max(start).min(self.chars.len());
145        self.chars[start..end].concat()
146    }
147
148    pub fn clear_selection(&mut self) {
149        self.sel_anchor = None;
150    }
151
152    pub fn has_selection(&self) -> bool {
153        self.selection_range().is_some()
154    }
155
156    /// Inclusive start and exclusive end of the selection, if any.
157    pub fn selection_range(&self) -> Option<(usize, usize)> {
158        let a = self.sel_anchor?;
159        let (lo, hi) = if a <= self.cursor {
160            (a, self.cursor)
161        } else {
162            (self.cursor, a)
163        };
164        (lo < hi).then_some((lo, hi))
165    }
166
167    pub fn selected_text(&self) -> Option<String> {
168        let (lo, hi) = self.selection_range()?;
169        Some(self.chars[lo..hi].concat())
170    }
171
172    /// Removes the selected range. Returns true when something was deleted.
173    pub fn delete_selection(&mut self) -> bool {
174        let Some((lo, hi)) = self.selection_range() else {
175            return false;
176        };
177        self.replace_range(lo, hi, "");
178        true
179    }
180
181    /// Select the word under (or beside) the cursor — macOS Select Word.
182    pub fn select_word(&mut self) {
183        if self.chars.is_empty() {
184            self.sel_anchor = None;
185            return;
186        }
187        let n = self.chars.len();
188        let i = self.cursor.min(n);
189        // Prefer the word containing the caret; if on a boundary, the
190        // word to the left; if mid-whitespace, the next word to the right.
191        let (mut start, mut end) = if i < n && !is_whitespace(&self.chars[i]) {
192            (i, i + 1)
193        } else if i > 0 && !is_whitespace(&self.chars[i - 1]) {
194            (i - 1, i)
195        } else {
196            let mut next = i;
197            while next < n && is_whitespace(&self.chars[next]) {
198                next += 1;
199            }
200            if next < n {
201                (next, next + 1)
202            } else {
203                let mut previous = i;
204                while previous > 0 && is_whitespace(&self.chars[previous - 1]) {
205                    previous -= 1;
206                }
207                if previous == 0 {
208                    self.sel_anchor = None;
209                    return;
210                }
211                (previous - 1, previous)
212            }
213        };
214        while start > 0 && !is_whitespace(&self.chars[start - 1]) {
215            start -= 1;
216        }
217        while end < n && !is_whitespace(&self.chars[end]) {
218            end += 1;
219        }
220        self.sel_anchor = Some(start);
221        self.cursor = end;
222    }
223
224    pub fn set_cursor(&mut self, cursor: usize) {
225        self.clear_selection();
226        self.cursor = cursor.min(self.chars.len());
227    }
228
229    /// Places the cursor at a display column of the visible window, as
230    /// produced by [`TextInput::visible`]. Past the end of the text the
231    /// cursor lands at the end.
232    pub fn set_cursor_from_col(&mut self, col: usize) {
233        self.clear_selection();
234        let mut used = 0;
235        let mut cursor = self.scroll;
236        for c in &self.chars[self.scroll.min(self.chars.len())..] {
237            let w = c.width();
238            if used + w > col {
239                break;
240            }
241            used += w;
242            cursor += 1;
243        }
244        self.cursor = cursor.min(self.chars.len());
245    }
246
247    pub fn at_start(&self) -> bool {
248        self.cursor == 0
249    }
250
251    pub fn at_end(&self) -> bool {
252        self.cursor == self.chars.len()
253    }
254
255    /// Cuts everything after the cursor into a new input.
256    pub fn split_off_at_cursor(&mut self) -> Self {
257        self.clear_selection();
258        let tail: Vec<String> = self.chars.split_off(self.cursor);
259        Self {
260            chars: tail,
261            cursor: 0,
262            sel_anchor: None,
263            scroll: 0,
264            max_len: self.max_len,
265            max_bytes: self.max_bytes,
266        }
267    }
268
269    /// Appends another input's text, leaving the cursor at the join. Returns
270    /// `false` without changing either input when the full join would exceed
271    /// this field's grapheme or byte limit.
272    pub fn append(&mut self, other: &Self) -> bool {
273        let cursor = self.chars.len();
274        let left = self.value();
275        let right = other.value();
276        if left.len().saturating_add(right.len()) > self.max_bytes {
277            return false;
278        }
279        let joined = left + &right;
280        let chars: Vec<String> = joined.graphemes(true).map(str::to_string).collect();
281        if chars.len() > self.max_len {
282            return false;
283        }
284        self.clear_selection();
285        self.chars = chars;
286        self.cursor = cursor.min(self.chars.len());
287        self.scroll = self.scroll.min(self.cursor);
288        true
289    }
290
291    fn replace_range(&mut self, lo: usize, hi: usize, replacement: &str) {
292        let lo = lo.min(self.chars.len());
293        let hi = hi.max(lo).min(self.chars.len());
294        let prefix = self.chars[..lo].concat();
295        let suffix = self.chars[hi..].concat();
296        let before_cursor = format!("{prefix}{replacement}");
297        let cursor = before_cursor.graphemes(true).count();
298        let joined = before_cursor + &suffix;
299        self.chars = joined.graphemes(true).map(str::to_string).collect();
300        self.cursor = cursor.min(self.chars.len());
301        self.sel_anchor = None;
302        self.scroll = self.scroll.min(self.cursor);
303    }
304
305    pub fn insert(&mut self, c: char) {
306        self.insert_str(&c.to_string());
307    }
308
309    /// Inserts a run of text at the cursor. Tab/newline separators are
310    /// flattened, while terminal control bytes are discarded at the input
311    /// boundary so they can never reach the renderer.
312    pub fn insert_str(&mut self, text: &str) {
313        let (lo, hi) = self.selection_range().unwrap_or((self.cursor, self.cursor));
314        let prefix = self.chars[..lo].concat();
315        let suffix = self.chars[hi..].concat();
316        let available = self
317            .max_bytes
318            .saturating_sub(prefix.len().saturating_add(suffix.len()));
319        let mut flattened = String::with_capacity(text.len().min(available));
320        for character in text.chars().filter_map(|character| match character {
321            '\t' | '\n' | '\r' => Some(' '),
322            character if character.is_control() => None,
323            _ => Some(character),
324        }) {
325            if flattened.len().saturating_add(character.len_utf8()) > available {
326                break;
327            }
328            flattened.push(character);
329        }
330        if flattened.is_empty() {
331            return;
332        }
333        let joined = format!("{prefix}{flattened}{suffix}");
334        let accepted = if joined.graphemes(true).count() <= self.max_len {
335            flattened
336        } else {
337            // A candidate can merge with graphemes on either side (combining
338            // marks and ZWJ sequences), so preserve exact boundary behavior
339            // while finding the longest valid prefix.
340            let mut accepted = String::new();
341            for grapheme in flattened.graphemes(true) {
342                let candidate = format!("{prefix}{accepted}{grapheme}{suffix}");
343                if candidate.graphemes(true).count() > self.max_len {
344                    break;
345                }
346                accepted.push_str(grapheme);
347            }
348            accepted
349        };
350        if !accepted.is_empty() {
351            self.replace_range(lo, hi, &accepted);
352        }
353    }
354
355    pub fn backspace(&mut self) {
356        if self.delete_selection() {
357            return;
358        }
359        if self.cursor > 0 {
360            self.replace_range(self.cursor - 1, self.cursor, "");
361        }
362    }
363
364    pub fn delete(&mut self) {
365        if self.delete_selection() {
366            return;
367        }
368        if self.cursor < self.chars.len() {
369            self.replace_range(self.cursor, self.cursor + 1, "");
370        }
371    }
372
373    pub fn delete_to_start(&mut self) {
374        if self.delete_selection() {
375            return;
376        }
377        self.replace_range(0, self.cursor, "");
378    }
379
380    pub fn delete_to_end(&mut self) {
381        if self.delete_selection() {
382            return;
383        }
384        self.replace_range(self.cursor, self.chars.len(), "");
385    }
386
387    pub fn delete_word_left(&mut self) {
388        if self.delete_selection() {
389            return;
390        }
391        let target = self.word_left_index();
392        self.replace_range(target, self.cursor, "");
393    }
394
395    fn move_to(&mut self, pos: usize, extend: bool) {
396        if extend {
397            if self.sel_anchor.is_none() {
398                self.sel_anchor = Some(self.cursor);
399            }
400        } else {
401            self.sel_anchor = None;
402        }
403        self.cursor = pos.min(self.chars.len());
404    }
405
406    pub fn left(&mut self) {
407        self.move_to(self.cursor.saturating_sub(1), false);
408    }
409
410    pub fn right(&mut self) {
411        self.move_to((self.cursor + 1).min(self.chars.len()), false);
412    }
413
414    pub fn select_left(&mut self) {
415        self.move_to(self.cursor.saturating_sub(1), true);
416    }
417
418    pub fn select_right(&mut self) {
419        self.move_to((self.cursor + 1).min(self.chars.len()), true);
420    }
421
422    pub fn word_left(&mut self) {
423        self.move_to(self.word_left_index(), false);
424    }
425
426    pub fn word_right(&mut self) {
427        self.move_to(self.word_right_index(), false);
428    }
429
430    pub fn select_word_left(&mut self) {
431        self.move_to(self.word_left_index(), true);
432    }
433
434    pub fn select_word_right(&mut self) {
435        self.move_to(self.word_right_index(), true);
436    }
437
438    pub fn home(&mut self) {
439        self.move_to(0, false);
440    }
441
442    pub fn end(&mut self) {
443        self.move_to(self.chars.len(), false);
444    }
445
446    pub fn select_home(&mut self) {
447        self.move_to(0, true);
448    }
449
450    pub fn select_end(&mut self) {
451        self.move_to(self.chars.len(), true);
452    }
453
454    /// Where the caret lands moving one word left; the description editor uses
455    /// this to extend a selection across block boundaries.
456    pub fn word_left_index(&self) -> usize {
457        let mut i = self.cursor;
458        while i > 0 && is_whitespace(&self.chars[i - 1]) {
459            i -= 1;
460        }
461        while i > 0 && !is_whitespace(&self.chars[i - 1]) {
462            i -= 1;
463        }
464        i
465    }
466
467    /// Where the caret lands moving one word right.
468    pub fn word_right_index(&self) -> usize {
469        let mut i = self.cursor;
470        let n = self.chars.len();
471        while i < n && is_whitespace(&self.chars[i]) {
472            i += 1;
473        }
474        while i < n && !is_whitespace(&self.chars[i]) {
475            i += 1;
476        }
477        i
478    }
479
480    /// Soft-wrap into visual rows of at most `width` columns. Prefers
481    /// breaking after whitespace; hard-breaks when a single word is wider
482    /// than the field. Empty text yields one empty row.
483    pub fn wrap_breaks(&self, width: usize) -> Vec<(usize, usize)> {
484        wrap_breaks(&self.chars, width)
485    }
486
487    /// How many visual rows the text needs at `width` (at least 1).
488    pub fn wrap_height(&self, width: usize) -> usize {
489        self.wrap_breaks(width).len()
490    }
491
492    /// Cursor as `(visual_row, column)` from precomputed wrap breaks.
493    pub fn wrap_cursor_from_breaks(&self, breaks: &[(usize, usize)]) -> (usize, u16) {
494        for (row, &(start, end)) in breaks.iter().enumerate() {
495            if self.cursor < end || (self.cursor == end && row + 1 == breaks.len()) {
496                let col: usize = self.chars[start..self.cursor.min(end)]
497                    .iter()
498                    .map(|c| c.width())
499                    .sum();
500                // When the caret sits exactly at a soft-break and another
501                // row follows, show it at the start of the next row.
502                if self.cursor == end && row + 1 < breaks.len() && end < self.chars.len() {
503                    return (row + 1, 0);
504                }
505                return (row, col as u16);
506            }
507        }
508        let last = breaks.len().saturating_sub(1);
509        (last, 0)
510    }
511
512    /// Cursor as `(visual_row, column)` for a wrapped layout.
513    pub fn wrap_cursor(&self, width: usize) -> (usize, u16) {
514        self.wrap_cursor_from_breaks(&self.wrap_breaks(width))
515    }
516
517    /// Place the caret from a click on a wrapped row.
518    pub fn set_cursor_from_wrap(&mut self, width: usize, row: usize, col: usize) {
519        self.clear_selection();
520        let breaks = self.wrap_breaks(width);
521        let row = row.min(breaks.len() - 1);
522        let (start, end) = breaks[row];
523        let mut used = 0usize;
524        let mut cursor = start;
525        for c in &self.chars[start..end] {
526            let w = c.width();
527            if used + w > col {
528                break;
529            }
530            used += w;
531            cursor += 1;
532        }
533        self.cursor = cursor.min(self.chars.len());
534    }
535
536    /// Move the caret up one visual row. Returns false when already on
537    /// the first row (caller may leave the block).
538    pub fn wrap_up(&mut self, width: usize, prefer_col: u16) -> bool {
539        let (row, col) = self.wrap_cursor(width);
540        let prefer = if prefer_col == u16::MAX {
541            col
542        } else {
543            prefer_col
544        };
545        if row == 0 {
546            return false;
547        }
548        self.set_cursor_from_wrap(width, row - 1, prefer as usize);
549        true
550    }
551
552    /// Move the caret down one visual row. Returns false when already on
553    /// the last row (caller may leave the block).
554    pub fn wrap_down(&mut self, width: usize, prefer_col: u16) -> bool {
555        let (row, col) = self.wrap_cursor(width);
556        let prefer = if prefer_col == u16::MAX {
557            col
558        } else {
559            prefer_col
560        };
561        let height = self.wrap_height(width);
562        if row + 1 >= height {
563            return false;
564        }
565        self.set_cursor_from_wrap(width, row + 1, prefer as usize);
566        true
567    }
568
569    /// Full soft-wrapped view for painting a multi-line field.
570    pub fn wrapped(&self, width: usize) -> WrappedView {
571        self.wrapped_with_sel(width, self.selection_range())
572    }
573
574    /// Like [`Self::wrapped`], but uses an explicit grapheme-range selection
575    /// (for description-level multi-line selections).
576    pub fn wrapped_with_sel(&self, width: usize, sel: Option<(usize, usize)>) -> WrappedView {
577        self.wrapped_from_breaks(&self.wrap_breaks(width), sel)
578    }
579
580    /// Soft-wrapped view from precomputed breaks (one wrap pass per paint).
581    pub fn wrapped_from_breaks(
582        &self,
583        breaks: &[(usize, usize)],
584        sel: Option<(usize, usize)>,
585    ) -> WrappedView {
586        let (cursor_row, cursor_col) = self.wrap_cursor_from_breaks(breaks);
587        let lines = breaks
588            .iter()
589            .map(|&(start, end)| {
590                let text = self.chars[start..end].concat();
591                let sel_cols = sel.and_then(|(lo, hi)| {
592                    let vis_lo = lo.max(start);
593                    let vis_hi = hi.min(end);
594                    if vis_lo >= vis_hi {
595                        return None;
596                    }
597                    let col = |idx: usize| -> u16 {
598                        self.chars[start..idx]
599                            .iter()
600                            .map(|c| c.width())
601                            .sum::<usize>() as u16
602                    };
603                    Some((col(vis_lo), col(vis_hi)))
604                });
605                WrappedLine {
606                    text,
607                    sel_cols,
608                    start,
609                    end,
610                }
611            })
612            .collect();
613        WrappedView {
614            lines,
615            cursor_row: cursor_row as u16,
616            cursor_col,
617        }
618    }
619
620    /// Move the caret and drop this line's own selection: when the description
621    /// editor drives the caret, the multi-line selection is its to own.
622    pub fn place_cursor(&mut self, cursor: usize) {
623        self.cursor = cursor.min(self.chars.len());
624        self.sel_anchor = None;
625    }
626
627    /// Text to draw in a field `width` columns wide, the cursor's column
628    /// within that field, and the selection's column span when it overlaps.
629    /// Single-row fields (title, status) use this; description uses [`Self::wrapped`].
630    pub fn visible(&mut self, width: usize) -> View {
631        if width == 0 {
632            return View {
633                text: String::new(),
634                cursor_col: 0,
635                sel_cols: None,
636            };
637        }
638        if self.cursor < self.scroll {
639            self.scroll = self.cursor;
640        }
641        // Scroll forward until the cursor fits; it may rest on the column
642        // just past the field, right after the last character typed.
643        let mut cursor_width: usize = self.chars[self.scroll..self.cursor]
644            .iter()
645            .map(|c| c.width())
646            .sum();
647        while cursor_width > width && self.scroll < self.cursor {
648            cursor_width = cursor_width.saturating_sub(self.chars[self.scroll].width());
649            self.scroll += 1;
650        }
651        let mut text = String::new();
652        let mut used = 0usize;
653        let mut end_idx = self.scroll;
654        for c in &self.chars[self.scroll..] {
655            let w = c.width();
656            if used + w > width {
657                break;
658            }
659            used += w;
660            text.push_str(c);
661            end_idx += 1;
662        }
663        let sel_cols = self.selection_range().and_then(|(lo, hi)| {
664            let vis_lo = lo.max(self.scroll);
665            let vis_hi = hi.min(end_idx);
666            if vis_lo >= vis_hi {
667                return None;
668            }
669            let col = |idx: usize| -> u16 {
670                self.chars[self.scroll..idx]
671                    .iter()
672                    .map(|c| c.width())
673                    .sum::<usize>() as u16
674            };
675            Some((col(vis_lo), col(vis_hi)))
676        });
677
678        View {
679            text,
680            cursor_col: cursor_width.min(width) as u16,
681            sel_cols,
682        }
683    }
684}
685
686fn bounded_graphemes(value: &str, max_len: usize, max_bytes: usize) -> Vec<String> {
687    let mut result = Vec::with_capacity(value.len().min(max_len));
688    let mut bytes = 0usize;
689    for grapheme in value.graphemes(true).take(max_len) {
690        if bytes.saturating_add(grapheme.len()) > max_bytes {
691            break;
692        }
693        bytes += grapheme.len();
694        result.push(grapheme.to_string());
695    }
696    result
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702
703    fn input(text: &str) -> TextInput {
704        TextInput::new(text, 256)
705    }
706
707    #[test]
708    fn edits_at_the_cursor() {
709        let mut i = input("hello");
710        i.left();
711        i.insert('!');
712        assert_eq!(i.value(), "hell!o");
713        i.backspace();
714        assert_eq!(i.value(), "hello");
715        i.delete();
716        assert_eq!(i.value(), "hell");
717    }
718
719    #[test]
720    fn moves_and_deletes_by_word() {
721        let mut i = input("one two three");
722        i.word_left();
723        assert_eq!(i.cursor, 8);
724        i.word_left();
725        assert_eq!(i.cursor, 4);
726        i.delete_word_left();
727        assert_eq!(i.value(), "two three");
728        i.end();
729        i.delete_to_start();
730        assert!(i.is_empty());
731    }
732
733    #[test]
734    fn honours_the_length_limit() {
735        let mut i = TextInput::new("ab", 2);
736        i.insert('c');
737        assert_eq!(i.value(), "ab");
738    }
739
740    #[test]
741    fn combining_sequences_cannot_bypass_the_byte_limit() {
742        let mut typed = TextInput::new("", 1);
743        typed.insert('e');
744        for _ in 0..1_000 {
745            typed.insert('\u{301}');
746        }
747        assert_eq!(typed.len(), 1);
748        assert!(typed.value().len() <= crate::model::text_byte_limit(1));
749
750        let pasted = format!("e{}", "\u{301}".repeat(1_000));
751        let pasted = TextInput::new(&pasted, 1);
752        assert!(pasted.value().len() <= crate::model::text_byte_limit(1));
753    }
754
755    #[test]
756    fn appending_inputs_preserves_the_same_limits_as_typing() {
757        let mut input = TextInput::new("a", 1);
758        assert!(!input.append(&TextInput::new("b", 1)));
759        assert_eq!(input.value(), "a");
760    }
761
762    #[test]
763    fn scrolls_to_keep_the_cursor_in_view() {
764        let mut i = input("abcdefghij");
765        let view = i.visible(4);
766        assert_eq!(view.text, "ghij");
767        assert_eq!(view.cursor_col, 4);
768        i.home();
769        let view = i.visible(4);
770        assert_eq!(view.text, "abcd");
771        assert_eq!(view.cursor_col, 0);
772    }
773
774    #[test]
775    fn measures_wide_characters_in_columns() {
776        let mut i = input("买菜");
777        let view = i.visible(4);
778        assert_eq!(view.text, "买菜");
779        assert_eq!(view.cursor_col, 4);
780    }
781
782    #[test]
783    fn cursor_and_deletion_treat_combining_sequences_as_one_grapheme() {
784        let mut i = input("e\u{301}x");
785        assert_eq!(i.len(), 2);
786        i.left();
787        i.backspace();
788        assert_eq!(i.value(), "x");
789        assert_eq!(i.cursor(), 0);
790    }
791
792    #[test]
793    fn cursor_and_selection_do_not_split_zwj_emoji() {
794        let family = "👨‍👩‍👧‍👦";
795        let mut i = input(&format!("{family}!"));
796        assert_eq!(i.len(), 2);
797        i.home();
798        i.select_right();
799        assert_eq!(i.selected_text().as_deref(), Some(family));
800        i.delete_selection();
801        assert_eq!(i.value(), "!");
802    }
803
804    #[test]
805    fn paste_keeps_graphemes_but_strips_terminal_controls() {
806        let family = "👨‍👩‍👧‍👦";
807        let mut i = TextInput::new("", 64);
808        i.insert_str(&format!("e\u{301}\t{family}\u{1b}\u{7f}\u{85}!"));
809
810        assert_eq!(i.value(), format!("e\u{301} {family}!"));
811        assert_eq!(i.len(), 4);
812        assert!(!i.value().chars().any(char::is_control));
813    }
814
815    #[test]
816    fn separately_typed_combining_marks_merge_with_the_previous_grapheme() {
817        let mut i = TextInput::new("", 1);
818        i.insert('e');
819        i.insert('\u{301}');
820
821        assert_eq!(i.value(), "e\u{301}");
822        assert_eq!(i.len(), 1);
823    }
824
825    #[test]
826    fn select_word_picks_the_word_under_the_cursor() {
827        let mut i = input("one two three");
828        i.home();
829        i.word_right(); // after "one "
830        i.right(); // on 't' of two
831        i.select_word();
832        assert_eq!(i.selected_text().as_deref(), Some("two"));
833        assert_eq!(i.selection_range(), Some((4, 7)));
834    }
835
836    #[test]
837    fn shift_arrows_extend_the_selection() {
838        let mut i = input("hello");
839        i.home();
840        i.select_right();
841        i.select_right();
842        assert_eq!(i.selected_text().as_deref(), Some("he"));
843        i.delete_selection();
844        assert_eq!(i.value(), "llo");
845    }
846
847    #[test]
848    fn typing_replaces_the_selection() {
849        let mut i = input("hello");
850        i.home();
851        i.select_word();
852        i.insert('x');
853        assert_eq!(i.value(), "x");
854    }
855
856    #[test]
857    fn wraps_on_spaces_then_hard_breaks() {
858        let s: Vec<String> = "one two three"
859            .graphemes(true)
860            .map(str::to_string)
861            .collect();
862        let breaks = wrap_breaks(&s, 8);
863        let parts: Vec<String> = breaks.iter().map(|&(a, b)| s[a..b].concat()).collect();
864        // width 8 fits "one two " then "three"
865        assert!(parts.len() >= 2);
866        assert!(parts[0].starts_with("one"));
867        assert!(parts.iter().any(|p| p.contains("three")));
868    }
869
870    #[test]
871    fn wrap_ranges_preserve_every_space_and_accept_every_caret_position() {
872        let mut input = input("word   next");
873        let breaks = input.wrap_breaks(5);
874        assert_eq!(breaks.first().map(|range| range.0), Some(0));
875        assert_eq!(breaks.last().map(|range| range.1), Some(input.len()));
876        assert!(breaks.windows(2).all(|pair| pair[0].1 == pair[1].0));
877        assert_eq!(
878            breaks
879                .iter()
880                .map(|&(start, end)| input.slice(start, end))
881                .collect::<String>(),
882            input.value()
883        );
884
885        for cursor in 0..=input.len() {
886            input.set_cursor(cursor);
887            let _ = input.wrap_cursor_from_breaks(&breaks);
888        }
889    }
890
891    #[test]
892    fn wrap_height_is_at_least_one() {
893        let i = input("");
894        assert_eq!(i.wrap_height(10), 1);
895        let i = input("hello world again");
896        assert!(i.wrap_height(6) >= 2);
897    }
898
899    #[test]
900    fn wrap_cursor_tracks_rows() {
901        let mut i = input("aaaa bbbb cccc");
902        i.home();
903        // width 5 → "aaaa " then "bbbb " then "cccc"
904        let (row, col) = i.wrap_cursor(5);
905        assert_eq!((row, col), (0, 0));
906        i.end();
907        let (row, _) = i.wrap_cursor(5);
908        assert!(row >= 1);
909    }
910}