1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/// UTF-8-safe text input with cursor tracking at valid char boundaries.
#[derive(Debug, Clone, Default)]
pub struct TextInput {
    buf: String,
    cursor: usize,
}

impl TextInput {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_value(value: impl Into<String>) -> Self {
        let buf: String = value.into();
        let cursor = buf.len();
        Self { buf, cursor }
    }

    pub fn value(&self) -> &str {
        &self.buf
    }

    pub fn cursor(&self) -> usize {
        self.cursor
    }

    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    pub fn len(&self) -> usize {
        self.buf.len()
    }

    pub fn split_at_cursor(&self) -> (&str, &str) {
        let pos = self.cursor.min(self.buf.len());
        (&self.buf[..pos], &self.buf[pos..])
    }

    /// Windowed split for display in a fixed-width area (scrolls around cursor).
    pub fn split_at_cursor_windowed(&self, max_width: usize) -> (String, String) {
        if self.buf.len() <= max_width {
            let (b, a) = self.split_at_cursor();
            return (b.to_owned(), a.to_owned());
        }
        let cursor = self.cursor.min(self.buf.len());
        let half = max_width / 2;
        let mut start = cursor.saturating_sub(half);
        while start > 0 && !self.buf.is_char_boundary(start) {
            start -= 1;
        }
        let mut end = (start + max_width).min(self.buf.len());
        while end < self.buf.len() && !self.buf.is_char_boundary(end) {
            end += 1;
        }
        if end == self.buf.len() {
            start = end.saturating_sub(max_width);
            while start > 0 && !self.buf.is_char_boundary(start) {
                start -= 1;
            }
        }
        let window = &self.buf[start..end];
        let cursor_in_window = cursor - start;
        (
            window[..cursor_in_window].to_owned(),
            window[cursor_in_window..].to_owned(),
        )
    }

    pub fn insert(&mut self, c: char) {
        cursor_insert(&mut self.buf, &mut self.cursor, c);
    }

    pub fn backspace(&mut self) {
        cursor_backspace(&mut self.buf, &mut self.cursor);
    }

    pub fn delete(&mut self) {
        cursor_delete(&mut self.buf, &mut self.cursor);
    }

    pub fn move_left(&mut self) {
        cursor_move_left(&self.buf, &mut self.cursor);
    }

    pub fn move_right(&mut self) {
        cursor_move_right(&self.buf, &mut self.cursor);
    }

    pub fn move_home(&mut self) {
        cursor_move_home(&mut self.cursor);
    }

    pub fn move_end(&mut self) {
        cursor_move_end(&self.buf, &mut self.cursor);
    }
}

// Free functions for the shared-cursor pattern in InputMode forms,
// where one `cursor: usize` is reused across whichever field is active.

pub fn cursor_insert(buf: &mut String, cursor: &mut usize, c: char) {
    let pos = (*cursor).min(buf.len());
    buf.insert(pos, c);
    *cursor = pos + c.len_utf8();
}

pub fn cursor_backspace(buf: &mut String, cursor: &mut usize) {
    if *cursor == 0 {
        return;
    }
    let prev = prev_char_boundary(buf, *cursor);
    buf.drain(prev..*cursor);
    *cursor = prev;
}

pub fn cursor_delete(buf: &mut String, cursor: &mut usize) {
    if *cursor >= buf.len() {
        return;
    }
    let next = next_char_boundary(buf, *cursor);
    buf.drain(*cursor..next);
}

pub fn cursor_move_left(buf: &str, cursor: &mut usize) {
    if *cursor > 0 {
        *cursor = prev_char_boundary(buf, *cursor);
    }
}

pub fn cursor_move_right(buf: &str, cursor: &mut usize) {
    if *cursor < buf.len() {
        *cursor = next_char_boundary(buf, *cursor);
    }
}

pub fn cursor_move_home(cursor: &mut usize) {
    *cursor = 0;
}

pub fn cursor_move_end(buf: &str, cursor: &mut usize) {
    *cursor = buf.len();
}

/// Defensively splits at cursor, snapping to a char boundary if needed.
pub fn cursor_split_at(buf: &str, cursor: usize) -> (&str, &str) {
    let mut pos = cursor.min(buf.len());
    while pos > 0 && !buf.is_char_boundary(pos) {
        pos -= 1;
    }
    (&buf[..pos], &buf[pos..])
}

fn prev_char_boundary(s: &str, pos: usize) -> usize {
    let mut i = pos.saturating_sub(1);
    while i > 0 && !s.is_char_boundary(i) {
        i -= 1;
    }
    i
}

fn next_char_boundary(s: &str, pos: usize) -> usize {
    let mut i = pos + 1;
    while i < s.len() && !s.is_char_boundary(i) {
        i += 1;
    }
    i
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ascii_roundtrip() {
        let mut input = TextInput::new();
        for c in "hello".chars() {
            input.insert(c);
        }
        assert_eq!(input.value(), "hello");
        assert_eq!(input.cursor(), 5);

        input.move_left();
        input.move_left();
        input.backspace();
        assert_eq!(input.value(), "helo");
        assert_eq!(input.cursor(), 2);

        input.move_home();
        input.delete();
        assert_eq!(input.value(), "elo");

        input.move_end();
        assert_eq!(input.cursor(), 3);
    }

    #[test]
    fn multibyte_navigation_and_editing() {
        let mut input = TextInput::new();
        for c in "café".chars() {
            input.insert(c);
        }
        assert_eq!(input.value(), "café");
        assert_eq!(input.cursor(), 5); // é is 2 bytes

        input.move_left();
        assert_eq!(input.cursor(), 3);
        assert_eq!(input.split_at_cursor(), ("caf", "é"));

        input.backspace();
        assert_eq!(input.value(), "caé");

        input.move_right();
        assert_eq!(input.cursor(), 4);

        input.delete();
        assert_eq!(input.value(), "caé");
    }

    #[test]
    fn cjk_and_emoji() {
        let mut input = TextInput::new();
        input.insert('');
        input.insert('🎉');
        input.insert('');
        assert_eq!(input.value(), "漢🎉字");
        assert_eq!(input.cursor(), 10); // 3 + 4 + 3

        input.move_left(); // before '字'
        assert_eq!(input.cursor(), 7);
        input.backspace(); // removes '🎉' (4 bytes)
        assert_eq!(input.value(), "漢字");
        assert_eq!(input.cursor(), 3);
    }

    #[test]
    fn insert_in_middle_of_multibyte() {
        let mut input = TextInput::with_value("aöb");
        input.move_home();
        input.move_right(); // past 'a', cursor = 1
        input.move_right(); // past 'ö', cursor = 3
        input.insert('x');
        assert_eq!(input.value(), "aöxb");
        assert_eq!(input.cursor(), 4);
    }

    #[test]
    fn boundary_nops() {
        let mut input = TextInput::with_value("x");
        input.move_home();
        input.move_left(); // already at 0
        assert_eq!(input.cursor(), 0);
        input.backspace(); // nothing to delete
        assert_eq!(input.value(), "x");

        input.move_end();
        input.move_right(); // already at end
        assert_eq!(input.cursor(), 1);
        input.delete(); // nothing to delete
        assert_eq!(input.value(), "x");

        let empty = TextInput::new();
        assert!(empty.is_empty());
        assert_eq!(empty.split_at_cursor(), ("", ""));
    }

    // Free function tests — these exercise the shared-cursor code path
    // used by InputMode forms, not the TextInput struct.

    #[test]
    fn cursor_fns_multibyte() {
        let mut buf = String::from("aéb");
        let mut cur = 0;

        cursor_move_right(&buf, &mut cur);
        assert_eq!(cur, 1); // past 'a'
        cursor_move_right(&buf, &mut cur);
        assert_eq!(cur, 3); // past 'é'

        cursor_insert(&mut buf, &mut cur, 'x');
        assert_eq!(buf, "aéxb");
        assert_eq!(cur, 4);

        cursor_backspace(&mut buf, &mut cur);
        assert_eq!(buf, "aéb");
        assert_eq!(cur, 3);

        cursor_move_left(&buf, &mut cur);
        assert_eq!(cur, 1); // back before 'é'
        cursor_delete(&mut buf, &mut cur);
        assert_eq!(buf, "ab");
        assert_eq!(cur, 1);

        cursor_move_end(&buf, &mut cur);
        assert_eq!(cur, 2);
        cursor_move_home(&mut cur);
        assert_eq!(cur, 0);
    }

    #[test]
    fn cursor_split_at_clamps() {
        let buf = "héllo";
        assert_eq!(cursor_split_at(buf, 0), ("", "héllo"));
        assert_eq!(cursor_split_at(buf, 3), ("", "llo"));
        assert_eq!(cursor_split_at(buf, 100), ("héllo", ""));
    }

    #[test]
    fn windowed_split() {
        let long = "a".repeat(50);

        // Cursor at end: window shows the last 10 chars
        let input = TextInput::with_value(&long);
        let (before, after) = input.split_at_cursor_windowed(10);
        assert_eq!(before, "a".repeat(10));
        assert!(after.is_empty());

        // Cursor in middle: both sides of the split are non-empty
        let mut input = TextInput::with_value(&long);
        input.move_home();
        for _ in 0..25 {
            input.move_right();
        }
        let (before, after) = input.split_at_cursor_windowed(10);
        assert!(!before.is_empty());
        assert!(!after.is_empty());
        assert_eq!(before.len() + after.len(), 10);

        // Short string: no windowing, returns full content
        let short = TextInput::with_value("hi");
        assert_eq!(
            short.split_at_cursor_windowed(40),
            ("hi".to_owned(), String::new())
        );

        // Multibyte: window boundaries snap to char boundaries
        let s: String = "é".repeat(30); // 60 bytes, 30 two-byte chars
        let mut input = TextInput::with_value(&s);
        input.move_home();
        for _ in 0..15 {
            input.move_right();
        }
        let (before, after) = input.split_at_cursor_windowed(20);
        let window = format!("{before}{after}");
        assert!(window.len() >= 20);
        assert!(window.chars().all(|c| c == 'é'));
    }

    // Fuzz: random operations on random Unicode should never panic or
    // leave the cursor at an invalid char boundary.
    #[test]
    fn fuzz_random_operations() {
        use proptest::{
            prelude::*,
            test_runner::{Config, TestRunner},
        };

        let config = Config::with_cases(500);
        let mut runner = TestRunner::new(config);
        runner
            .run(
                &proptest::collection::vec(
                    prop_oneof![
                        any::<char>().prop_map(Op::Insert),
                        Just(Op::Backspace),
                        Just(Op::Delete),
                        Just(Op::Left),
                        Just(Op::Right),
                        Just(Op::Home),
                        Just(Op::End),
                    ],
                    1..100,
                ),
                |ops| {
                    let mut input = TextInput::new();
                    for op in ops {
                        match op {
                            Op::Insert(c) => input.insert(c),
                            Op::Backspace => input.backspace(),
                            Op::Delete => input.delete(),
                            Op::Left => input.move_left(),
                            Op::Right => input.move_right(),
                            Op::Home => input.move_home(),
                            Op::End => input.move_end(),
                        }
                        // Invariant: cursor is always at a valid char boundary
                        assert!(
                            input.buf.is_char_boundary(input.cursor),
                            "cursor {} not a char boundary in {:?}",
                            input.cursor,
                            input.buf
                        );
                        // Invariant: split_at_cursor doesn't panic
                        let _ = input.split_at_cursor();
                    }
                    Ok(())
                },
            )
            .unwrap();
    }

    #[derive(Debug, Clone)]
    enum Op {
        Insert(char),
        Backspace,
        Delete,
        Left,
        Right,
        Home,
        End,
    }
}