kimun-notes 0.19.0

A terminal-based notes application
Documentation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Reusable single-line text input.
//!
//! Used by the editor find bar, dialogs (rename, move, quick-note), the sidebar
//! / note-browser search boxes, and the settings workspace name field. The
//! widget owns its value and char cursor; callers add titles, hints, validation
//! visuals, and submit/cancel semantics on top.
//!
//! `handle_key` returns [`InputOutcome`] so callers can branch on Submit /
//! Cancel / textual mutation without re-matching the raw key.

use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::{Position, Rect};
use ratatui::style::Style;
use ratatui::widgets::Paragraph;
use unicode_width::UnicodeWidthStr;

/// Outcome of [`SingleLineInput::handle_key`] — lets callers branch without
/// re-parsing the key event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputOutcome {
    /// Key was consumed but the value did not change (cursor move, no-op).
    Consumed,
    /// Value (and possibly cursor) changed.
    Changed,
    /// User pressed Enter.
    Submit,
    /// User pressed Esc.
    Cancel,
    /// Key was not recognised by the widget.
    NotConsumed,
}

#[derive(Default)]
pub struct SingleLineInput {
    value: String,
    /// Byte offset into `value`.
    cursor: usize,
    /// Caret screen position (col, row), cached after the most recent
    /// `render` call. Used by overlays anchored on the caret (e.g. the
    /// hashtag autocomplete popup). `None` until the first render.
    last_caret_pos: Option<(u16, u16)>,
    /// Horizontal scroll offset in display columns, updated on render so the
    /// caret stays inside the visible window when the value overflows the
    /// rect. Kept across renders so the cursor can move within the window
    /// without the text shifting under it.
    scroll_x: u16,
}

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

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

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

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

    /// Current cursor position as a byte offset.
    pub fn cursor_byte(&self) -> usize {
        self.cursor
    }

    /// Caret screen position from the last `render` call, or `None` if
    /// the widget has not been rendered yet (or was rendered unfocused).
    pub fn last_caret_pos(&self) -> Option<(u16, u16)> {
        self.last_caret_pos
    }

    /// Overwrite a byte `range` of the value with `new_text`, then place
    /// the cursor at byte offset `new_cursor_byte` in the updated value.
    /// Used by the hashtag autocomplete to apply an `AcceptAction`. All
    /// three positions must be on char boundaries; the controller
    /// computes them off `value` so this holds in practice — checked
    /// via debug_assert.
    pub fn replace_range_bytes(
        &mut self,
        range: std::ops::Range<usize>,
        new_text: &str,
        new_cursor_byte: usize,
    ) {
        debug_assert!(self.value.is_char_boundary(range.start));
        debug_assert!(self.value.is_char_boundary(range.end));
        self.value.replace_range(range, new_text);
        let clamped = new_cursor_byte.min(self.value.len());
        debug_assert!(
            self.value.is_char_boundary(clamped),
            "new_cursor_byte must land on a char boundary"
        );
        self.cursor = clamped;
    }

    /// Replace the value; cursor jumps to end.
    pub fn set_value(&mut self, value: impl Into<String>) {
        self.value = value.into();
        self.cursor = self.value.len();
    }

    pub fn clear(&mut self) {
        self.value.clear();
        self.cursor = 0;
    }

    /// Codepoint count to the left of the cursor. Test-only: callers must use
    /// [`cursor_display_col`](Self::cursor_display_col) for caret placement,
    /// since codepoint count differs from display width for CJK / emoji.
    #[cfg(test)]
    pub(crate) fn cursor_char_offset(&self) -> usize {
        self.value[..self.cursor].chars().count()
    }

    /// Display column to the left of the cursor — accounts for wide (CJK,
    /// emoji) characters via `unicode-width`. Use this for caret placement.
    pub fn cursor_display_col(&self) -> usize {
        self.value[..self.cursor].width()
    }

    /// Total display width of the value — accounts for wide characters.
    pub fn display_width(&self) -> usize {
        self.value.width()
    }

    pub fn handle_key(&mut self, key: &KeyEvent) -> InputOutcome {
        match (key.modifiers, key.code) {
            (_, KeyCode::Enter) => InputOutcome::Submit,
            (_, KeyCode::Esc) => InputOutcome::Cancel,
            (_, KeyCode::Backspace) => {
                if self.cursor == 0 {
                    return InputOutcome::Consumed;
                }
                let prev = prev_char_boundary(&self.value, self.cursor);
                self.value.drain(prev..self.cursor);
                self.cursor = prev;
                InputOutcome::Changed
            }
            (_, KeyCode::Delete) => {
                if self.cursor >= self.value.len() {
                    return InputOutcome::Consumed;
                }
                let next = next_char_boundary(&self.value, self.cursor);
                self.value.drain(self.cursor..next);
                InputOutcome::Changed
            }
            (_, KeyCode::Left) => {
                if self.cursor == 0 {
                    return InputOutcome::Consumed;
                }
                self.cursor = prev_char_boundary(&self.value, self.cursor);
                InputOutcome::Consumed
            }
            (_, KeyCode::Right) => {
                if self.cursor >= self.value.len() {
                    return InputOutcome::Consumed;
                }
                self.cursor = next_char_boundary(&self.value, self.cursor);
                InputOutcome::Consumed
            }
            (_, KeyCode::Home) => {
                self.cursor = 0;
                InputOutcome::Consumed
            }
            (_, KeyCode::End) => {
                self.cursor = self.value.len();
                InputOutcome::Consumed
            }
            // Accept only plain or Shift-modified chars; Ctrl/Alt combos are
            // not text input and must bubble up to the caller for shortcuts.
            (m, KeyCode::Char(c)) if !m.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => {
                self.value.insert(self.cursor, c);
                self.cursor += c.len_utf8();
                InputOutcome::Changed
            }
            _ => InputOutcome::NotConsumed,
        }
    }

    /// Render the value text at `rect` using `style`. Caller is responsible for
    /// any surrounding chrome (borders, prompt prefix, validation glyphs).
    /// Place the terminal cursor when `focused`. `value_offset_x` is the
    /// display-column offset within `rect` where the value text starts (e.g.
    /// when the caller renders a "Find: " prefix separately, pass its
    /// display width via `UnicodeWidthStr::width`).
    pub fn render(
        &mut self,
        f: &mut Frame,
        rect: Rect,
        style: Style,
        value_offset_x: u16,
        focused: bool,
    ) {
        let inner = Rect {
            x: rect.x.saturating_add(value_offset_x),
            width: rect.width.saturating_sub(value_offset_x),
            ..rect
        };
        let scroll_x = self.scroll_into_view(inner.width);
        f.render_widget(
            Paragraph::new(self.value.as_str())
                .style(style)
                .scroll((0, scroll_x)),
            inner,
        );
        self.place_caret(f, inner, focused);
    }

    /// Like [`Self::render`], but with a pre-styled line (e.g. the query
    /// highlighter's output). The line must render the same text as the
    /// input's value, so caret math stays valid.
    pub fn render_line(
        &mut self,
        f: &mut Frame,
        rect: Rect,
        line: ratatui::text::Line<'static>,
        base_style: Style,
        value_offset_x: u16,
        focused: bool,
    ) {
        let inner = Rect {
            x: rect.x.saturating_add(value_offset_x),
            width: rect.width.saturating_sub(value_offset_x),
            ..rect
        };
        let scroll_x = self.scroll_into_view(inner.width);
        f.render_widget(
            Paragraph::new(line).style(base_style).scroll((0, scroll_x)),
            inner,
        );
        self.place_caret(f, inner, focused);
    }

    /// Adjust the horizontal scroll so the caret falls inside a window of
    /// `width` display columns, and return the resulting offset. Scrolls only
    /// when the caret crosses a window edge, so cursor movement inside the
    /// window leaves the text in place.
    fn scroll_into_view(&mut self, width: u16) -> u16 {
        if width == 0 {
            self.scroll_x = 0;
            return 0;
        }
        // The caret can sit one column past the last char, so the maximum
        // useful offset keeps that extra cell — not just the last char —
        // inside the window. Also clamps stale offsets after the value shrank.
        let total = u16::try_from(self.display_width()).unwrap_or(u16::MAX);
        let max_scroll = total.saturating_add(1).saturating_sub(width);
        self.scroll_x = self.scroll_x.min(max_scroll);
        let cursor_col = u16::try_from(self.cursor_display_col()).unwrap_or(u16::MAX);
        if cursor_col < self.scroll_x {
            self.scroll_x = cursor_col;
        } else if cursor_col >= self.scroll_x.saturating_add(width) {
            self.scroll_x = cursor_col - (width - 1);
        }
        self.scroll_x
    }

    /// Shared caret placement for both render paths.
    fn place_caret(&mut self, f: &mut Frame, inner: Rect, focused: bool) {
        self.last_caret_pos = None;
        if focused {
            let caret_x = inner
                .x
                .saturating_add((self.cursor_display_col() as u16).saturating_sub(self.scroll_x))
                .min(inner.x + inner.width.saturating_sub(1));
            f.set_cursor_position(Position {
                x: caret_x,
                y: inner.y,
            });
            self.last_caret_pos = Some((caret_x, inner.y));
        }
    }
}

fn prev_char_boundary(s: &str, from: usize) -> usize {
    s[..from]
        .char_indices()
        .next_back()
        .map(|(i, _)| i)
        .unwrap_or(0)
}

fn next_char_boundary(s: &str, from: usize) -> usize {
    s[from..]
        .char_indices()
        .nth(1)
        .map(|(i, _)| from + i)
        .unwrap_or(s.len())
}

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

    fn k(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn new_is_empty_cursor_zero() {
        let i = SingleLineInput::new();
        assert!(i.is_empty());
        assert_eq!(i.cursor_char_offset(), 0);
    }

    #[test]
    fn with_value_places_cursor_at_end() {
        let i = SingleLineInput::with_value("hello");
        assert_eq!(i.value(), "hello");
        assert_eq!(i.cursor_char_offset(), 5);
    }

    #[test]
    fn typing_chars_appends_and_advances_cursor() {
        let mut i = SingleLineInput::new();
        assert_eq!(i.handle_key(&k(KeyCode::Char('a'))), InputOutcome::Changed);
        assert_eq!(i.handle_key(&k(KeyCode::Char('b'))), InputOutcome::Changed);
        assert_eq!(i.value(), "ab");
        assert_eq!(i.cursor_char_offset(), 2);
    }

    #[test]
    fn left_then_insert_inserts_mid_string() {
        let mut i = SingleLineInput::with_value("ac");
        i.handle_key(&k(KeyCode::Left));
        assert_eq!(i.cursor_char_offset(), 1);
        i.handle_key(&k(KeyCode::Char('b')));
        assert_eq!(i.value(), "abc");
        assert_eq!(i.cursor_char_offset(), 2);
    }

    #[test]
    fn backspace_at_start_is_noop() {
        let mut i = SingleLineInput::with_value("abc");
        i.handle_key(&k(KeyCode::Home));
        assert_eq!(i.handle_key(&k(KeyCode::Backspace)), InputOutcome::Consumed);
        assert_eq!(i.value(), "abc");
    }

    #[test]
    fn delete_at_end_is_noop() {
        let mut i = SingleLineInput::with_value("abc");
        assert_eq!(i.handle_key(&k(KeyCode::Delete)), InputOutcome::Consumed);
        assert_eq!(i.value(), "abc");
    }

    #[test]
    fn home_end_jump_cursor() {
        let mut i = SingleLineInput::with_value("abc");
        i.handle_key(&k(KeyCode::Home));
        assert_eq!(i.cursor_char_offset(), 0);
        i.handle_key(&k(KeyCode::End));
        assert_eq!(i.cursor_char_offset(), 3);
    }

    #[test]
    fn unicode_chars_count_by_codepoint_not_bytes() {
        let mut i = SingleLineInput::new();
        i.handle_key(&k(KeyCode::Char('')));
        i.handle_key(&k(KeyCode::Char('')));
        assert_eq!(i.value(), "あい");
        assert_eq!(i.cursor_char_offset(), 2);
        i.handle_key(&k(KeyCode::Left));
        assert_eq!(i.cursor_char_offset(), 1);
        i.handle_key(&k(KeyCode::Backspace));
        assert_eq!(i.value(), "");
    }

    #[test]
    fn enter_returns_submit_esc_returns_cancel() {
        let mut i = SingleLineInput::with_value("x");
        assert_eq!(i.handle_key(&k(KeyCode::Enter)), InputOutcome::Submit);
        assert_eq!(i.handle_key(&k(KeyCode::Esc)), InputOutcome::Cancel);
    }

    #[test]
    fn ctrl_char_is_not_consumed_as_text() {
        let mut i = SingleLineInput::new();
        let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL);
        assert_eq!(i.handle_key(&key), InputOutcome::NotConsumed);
        assert!(i.is_empty());
    }

    #[test]
    fn alt_char_is_not_consumed_as_text() {
        let mut i = SingleLineInput::new();
        let key = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::ALT);
        assert_eq!(i.handle_key(&key), InputOutcome::NotConsumed);
        assert!(i.is_empty());
    }

    #[test]
    fn cjk_chars_count_two_display_cols_per_char() {
        let mut i = SingleLineInput::new();
        i.handle_key(&k(KeyCode::Char('')));
        i.handle_key(&k(KeyCode::Char('')));
        // 2 codepoints, but each is 2 cells wide.
        assert_eq!(i.cursor_char_offset(), 2);
        assert_eq!(i.cursor_display_col(), 4);
        assert_eq!(i.display_width(), 4);
    }

    #[test]
    fn mixed_ascii_and_cjk_caret_column() {
        let mut i = SingleLineInput::with_value("ab猫");
        // Caret at end of "ab猫" → 1+1+2 display cols.
        assert_eq!(i.cursor_display_col(), 4);
        i.handle_key(&k(KeyCode::Left));
        // Caret moved before 猫 → 2 cells.
        assert_eq!(i.cursor_display_col(), 2);
    }

    #[test]
    fn shift_char_inserts() {
        let mut i = SingleLineInput::new();
        let key = KeyEvent::new(KeyCode::Char('A'), KeyModifiers::SHIFT);
        assert_eq!(i.handle_key(&key), InputOutcome::Changed);
        assert_eq!(i.value(), "A");
    }

    #[test]
    fn set_value_resets_cursor_to_end() {
        let mut i = SingleLineInput::with_value("abc");
        i.handle_key(&k(KeyCode::Home));
        i.set_value("xyz!");
        assert_eq!(i.value(), "xyz!");
        assert_eq!(i.cursor_char_offset(), 4);
    }

    #[test]
    fn clear_resets_both() {
        let mut i = SingleLineInput::with_value("abc");
        i.clear();
        assert!(i.is_empty());
        assert_eq!(i.cursor_char_offset(), 0);
    }

    mod rendering {
        use super::*;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        fn draw(
            i: &mut SingleLineInput,
            width: u16,
        ) -> (Terminal<TestBackend>, Option<(u16, u16)>) {
            let mut terminal = Terminal::new(TestBackend::new(width, 1)).unwrap();
            terminal
                .draw(|f| {
                    i.render(f, Rect::new(0, 0, width, 1), Style::default(), 0, true);
                })
                .unwrap();
            let caret = i.last_caret_pos();
            (terminal, caret)
        }

        fn row(terminal: &Terminal<TestBackend>, width: u16) -> String {
            let buf = terminal.backend().buffer();
            (0..width).map(|x| buf[(x, 0)].symbol()).collect()
        }

        #[test]
        fn short_value_renders_from_start() {
            let mut i = SingleLineInput::with_value("abc");
            let (t, caret) = draw(&mut i, 10);
            assert_eq!(row(&t, 10), "abc       ");
            assert_eq!(caret, Some((3, 0)));
        }

        #[test]
        fn long_value_scrolls_to_keep_caret_visible() {
            // 15 chars in a 10-wide rect, cursor at end: scroll 6 cols so the
            // caret cell after the last char is the rightmost column.
            let mut i = SingleLineInput::with_value("abcdefghijklmno");
            let (t, caret) = draw(&mut i, 10);
            assert_eq!(row(&t, 10), "ghijklmno ");
            assert_eq!(caret, Some((9, 0)));
        }

        #[test]
        fn cursor_moves_inside_window_without_scrolling() {
            let mut i = SingleLineInput::with_value("abcdefghijklmno");
            draw(&mut i, 10); // establishes scroll = 6
            for _ in 0..3 {
                i.handle_key(&k(KeyCode::Left));
            }
            // Cursor col 12 still inside [6, 16) — window must not move.
            let (t, caret) = draw(&mut i, 10);
            assert_eq!(row(&t, 10), "ghijklmno ");
            assert_eq!(caret, Some((6, 0)));
        }

        #[test]
        fn cursor_past_left_edge_scrolls_back() {
            let mut i = SingleLineInput::with_value("abcdefghijklmno");
            draw(&mut i, 10); // scroll = 6
            i.handle_key(&k(KeyCode::Home));
            let (t, caret) = draw(&mut i, 10);
            assert_eq!(row(&t, 10), "abcdefghij");
            assert_eq!(caret, Some((0, 0)));
        }

        #[test]
        fn shrinking_value_clamps_scroll() {
            let mut i = SingleLineInput::with_value("abcdefghijklmno");
            draw(&mut i, 10); // scroll = 6
            i.set_value("abc");
            let (t, caret) = draw(&mut i, 10);
            assert_eq!(row(&t, 10), "abc       ");
            assert_eq!(caret, Some((3, 0)));
        }
    }
}