Skip to main content

mermaid_cli/render/widgets/
input.rs

1use ratatui::{
2    buffer::Buffer,
3    layout::Rect,
4    style::Style,
5    widgets::{Block, Borders, Paragraph, StatefulWidget, Widget},
6};
7use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
8
9use crate::render::theme::Theme;
10
11/// State for the input widget
12#[derive(Debug, Clone)]
13pub struct InputState {
14    /// Cursor position in the input string
15    pub cursor_position: usize,
16}
17
18impl InputState {
19    /// Create a new input state
20    #[must_use]
21    pub fn new() -> Self {
22        Self { cursor_position: 0 }
23    }
24
25    /// Calculate cursor position for wrapped text.
26    ///
27    /// `content_width` is in **display cells**. Returns `(row, col)` where
28    /// `col` is also in display cells — required because `Frame::set_cursor_
29    /// position` is cell-based, not byte-based. CJK / emoji input previously
30    /// mispositioned the cursor because the column was returned in bytes.
31    ///
32    /// Uses the shared `layout_rows` helper so the wrapping decisions match
33    /// `wrap_input_with_prompt` exactly (the two would silently drift
34    /// otherwise — `cursor_and_wrap_agree_on_line_structure` guards this).
35    #[must_use]
36    pub fn calculate_cursor_position(
37        input: &str,
38        cursor_pos: usize,
39        content_width: usize,
40    ) -> (u16, u16) {
41        let cursor_pos = cursor_pos.min(input.len());
42
43        if content_width < 3 || input.is_empty() {
44            return (0, 0);
45        }
46
47        // Available cells per line after the 2-cell prefix ("> " or "  ")
48        let line_width = content_width.saturating_sub(2);
49        if line_width == 0 {
50            return (0, 0);
51        }
52
53        let rows = layout_rows(input, line_width);
54        for (idx, row) in rows.iter().enumerate() {
55            let content_end = row.start + row.len;
56            let gap_end = content_end + row.gap;
57            let is_last = idx + 1 == rows.len();
58
59            // Cursor belongs to this row if it falls within the row chars or
60            // the whitespace/newline gap after it, or if this is the last row.
61            if cursor_pos < gap_end || is_last {
62                // Cap at the row's content so trailing/gap whitespace doesn't
63                // overflow past the visible line.
64                let cursor_byte_in_line = cursor_pos.saturating_sub(row.start).min(row.len);
65                let line_text = &input[row.start..content_end];
66                let col_cells = line_text[..cursor_byte_in_line.min(line_text.len())].width();
67                return (idx as u16, col_cells as u16);
68            }
69        }
70        (0, 0)
71    }
72}
73
74impl Default for InputState {
75    fn default() -> Self {
76        Self::new()
77    }
78}
79
80/// Props for `InputWidget`. The slash-command palette is rendered
81/// separately as `SlashPaletteWidget` in the bottom region (see
82/// `render.rs`); this widget just draws the bordered input box.
83pub struct InputWidget<'a> {
84    pub input: &'a str,
85    /// True when a slash command is in flight (input starts with `/`).
86    /// Drives the warning-yellow border color so the user has a visual
87    /// cue that they're in command-entry mode.
88    pub showing_command_hints: bool,
89    pub theme: &'a Theme,
90    /// Reasoning is currently enabled (any non-`None` level). Drives the
91    /// cyan/sage border color cue.
92    pub reasoning_active: bool,
93    /// A first Ctrl+C armed the exit confirmation; show the second-press
94    /// hint in the box title while the window is open (idle-state surface —
95    /// the busy-state hint lives in the status line).
96    pub exit_armed: bool,
97    /// A first idle Esc armed the double-Esc rewind; show the second-press
98    /// hint in the box title while the window is open. Exit arming wins
99    /// when both are somehow live (quitting is the more consequential act).
100    pub rewind_armed: bool,
101}
102
103impl<'a> StatefulWidget for InputWidget<'a> {
104    type State = InputState;
105
106    fn render(self, area: Rect, buf: &mut Buffer, _state: &mut Self::State) {
107        let input_style = Style::new().fg(self.theme.colors.text_primary.to_color());
108
109        // Manually wrap input text with proper indentation (Claude Code style)
110        // First line: "> text"
111        // Continuation lines: "  text" (2 spaces to align with first line content)
112        // Always show "> " prompt, even when input is empty
113        let input_text = {
114            let width = area.width.saturating_sub(2) as usize; // Account for top/bottom borders
115            wrap_input_with_prompt(self.input, width)
116        };
117
118        // Border color priority: command-entry mode wins (yellow),
119        // then reasoning-enabled (cyan), then default gray.
120        let border_color = if self.showing_command_hints {
121            self.theme.colors.warning.to_color()
122        } else if self.reasoning_active {
123            // Mermaid sage blue - same as the path color in status bar
124            self.theme.colors.info.to_color() // cyan
125        } else {
126            self.theme.colors.border.to_color() // gray
127        };
128
129        let block = if self.showing_command_hints {
130            Block::default()
131                .borders(Borders::TOP | Borders::BOTTOM)
132                .border_style(Style::new().fg(border_color))
133                .title(" Enter Command ")
134        } else if self.exit_armed {
135            Block::default()
136                .borders(Borders::TOP | Borders::BOTTOM)
137                .border_style(Style::new().fg(border_color))
138                .title(" press ctrl+c again to exit ")
139        } else if self.rewind_armed {
140            Block::default()
141                .borders(Borders::TOP | Borders::BOTTOM)
142                .border_style(Style::new().fg(border_color))
143                .title(" esc again to rewind ")
144        } else {
145            Block::default()
146                .borders(Borders::TOP | Borders::BOTTOM)
147                .border_style(Style::new().fg(border_color))
148        };
149
150        let input = Paragraph::new(input_text).style(input_style).block(block);
151
152        input.render(area, buf);
153
154        // Note: Cursor positioning is handled in the main render loop after all widgets are rendered
155        // The Frame::set_cursor_position() is called there with the calculated position
156    }
157}
158
159/// Given a tail of input and a max line width (in **display cells**, not
160/// bytes), return the byte offset where this line should end.
161///
162/// Walks `remaining` char-by-char accumulating `UnicodeWidthChar::width`
163/// so CJK / emoji break at the visual edge instead of after ~1/3 of the
164/// space (the byte length of multi-byte chars exceeds their cell width).
165/// Prefers a whitespace break within the accepted range; falls back to a
166/// hard break at the char boundary if no whitespace exists. Always makes
167/// progress: if even the first character exceeds `line_width`, returns
168/// the byte offset *after* it so the caller can't infinite-loop.
169///
170/// Shared between `InputState::calculate_cursor_position` and
171/// `wrap_input_with_prompt` so both make identical wrapping decisions.
172fn find_line_break(remaining: &str, line_width: usize) -> usize {
173    if remaining.is_empty() {
174        return 0;
175    }
176
177    // Walk chars, accumulating display width, to find the byte offset at
178    // which the running cell-count would exceed `line_width`. If the whole
179    // string fits, we're done.
180    let mut acc_width = 0usize;
181    let mut hard_break = remaining.len();
182    for (byte_idx, ch) in remaining.char_indices() {
183        let ch_width = ch.width().unwrap_or(0);
184        if acc_width + ch_width > line_width {
185            hard_break = byte_idx;
186            break;
187        }
188        acc_width += ch_width;
189    }
190
191    if hard_break == remaining.len() {
192        return remaining.len();
193    }
194
195    // If the very first character is wider than the entire line (e.g. a
196    // double-width emoji on a 1-cell viewport), force progress by taking
197    // exactly one char — otherwise the caller loops forever.
198    if hard_break == 0 {
199        return remaining
200            .char_indices()
201            .nth(1)
202            .map(|(idx, _)| idx)
203            .unwrap_or(remaining.len());
204    }
205
206    // Prefer a whitespace break within the accepted byte range. Advance past
207    // the whitespace char by its UTF-8 length so the returned offset is always
208    // a char boundary — `char::is_whitespace` matches multibyte spaces (NBSP
209    // U+00A0 = 2 bytes, ideographic space U+3000 = 3 bytes, U+2028, …) that a
210    // naive `pos + 1` would split mid-codepoint, panicking the renderer on the
211    // subsequent slice. For 1-byte ASCII whitespace this is identical to the
212    // old `pos + 1`.
213    remaining[..hard_break]
214        .char_indices()
215        .rev()
216        .find(|(_, c)| c.is_whitespace())
217        .map(|(pos, c)| pos + c.len_utf8())
218        .unwrap_or(hard_break)
219}
220
221/// One rendered row's span within the original input, in bytes.
222///
223/// `start..start+len` is the row's visible text. `gap` is the
224/// whitespace/newline consumed after it before the next row begins (trimmed
225/// inter-word whitespace from a soft wrap, plus the `\n` byte of a hard
226/// break). Shared by `wrap_input_with_prompt` and `calculate_cursor_position`
227/// so they never disagree on line structure.
228struct RowSpan {
229    start: usize,
230    len: usize,
231    gap: usize,
232}
233
234/// Lay `input` out into rendered rows at `line_width` (display cells).
235/// Explicit `\n` forces a new row (so pasted/Ctrl+J newlines render as
236/// real lines); each resulting segment is then soft-wrapped on width via
237/// `find_line_break`. A trailing newline yields a final empty row.
238fn layout_rows(input: &str, line_width: usize) -> Vec<RowSpan> {
239    let mut rows: Vec<RowSpan> = Vec::new();
240    if input.is_empty() {
241        return rows;
242    }
243    let total = input.len();
244    let mut seg_start = 0usize;
245    loop {
246        let seg_end = match input[seg_start..].find('\n') {
247            Some(rel) => seg_start + rel,
248            None => total,
249        };
250        let segment = &input[seg_start..seg_end];
251
252        // Soft-wrap this newline-free segment into >=1 rows.
253        let mut local = 0usize;
254        loop {
255            let rem = &segment[local..];
256            let bp = find_line_break(rem, line_width);
257            let after = &rem[bp..];
258            let ws_gap = after.len() - after.trim_start().len();
259            rows.push(RowSpan {
260                start: seg_start + local,
261                len: bp,
262                gap: ws_gap,
263            });
264            local += bp + ws_gap;
265            if local >= segment.len() {
266                break;
267            }
268        }
269
270        if seg_end >= total {
271            break;
272        }
273        // A '\n' follows: count it in the last row's gap so cursor math lands
274        // the caret on the correct side of the break.
275        if let Some(last) = rows.last_mut() {
276            last.gap += 1;
277        }
278        seg_start = seg_end + 1;
279        if seg_start == total {
280            // Trailing newline → a final empty row.
281            rows.push(RowSpan {
282                start: seg_start,
283                len: 0,
284                gap: 0,
285            });
286            break;
287        }
288    }
289    rows
290}
291
292/// Wrap input text with "> " prefix on the first line and "  " on
293/// continuation lines (Claude Code style). Always returns at least "> ",
294/// even when input is empty. Embedded newlines render as real rows.
295fn wrap_input_with_prompt(input: &str, width: usize) -> String {
296    if width < 3 {
297        // Not enough space for "> " prefix
298        return input.to_string();
299    }
300    if input.is_empty() {
301        return String::from("> ");
302    }
303
304    // First line and continuation lines both reserve 2 chars for their
305    // respective prefix ("> " or "  "), so they share the same line width.
306    let line_width = width.saturating_sub(2);
307
308    let mut result = String::new();
309    for (idx, row) in layout_rows(input, line_width).iter().enumerate() {
310        let text = input[row.start..row.start + row.len].trim_end();
311        if idx == 0 {
312            result.push_str("> ");
313        } else {
314            result.push('\n');
315            result.push_str("  ");
316        }
317        result.push_str(text);
318    }
319    result
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    /// Parity: for every byte offset in `input`, `calculate_cursor_position`
327    /// must return a (row, col) that lands in the same visual line emitted
328    /// by `wrap_input_with_prompt`. Catches silent drift between the two
329    /// functions going forward.
330    #[test]
331    fn cursor_and_wrap_agree_on_line_structure() {
332        let inputs = [
333            "hello world",
334            "the quick brown fox jumps over the lazy dog",
335            "nospacesinthislonginputthatmusthardbreak",
336            "mixed short and verylongcontiguoustoken here",
337            "leading  double  spaces  between  words",
338            "",
339            // CJK inputs: each char is 3 bytes / 2 display cells. The wrap
340            // logic must agree on line structure across both functions.
341            "你好世界",
342            "你好 world 世界",
343            "abc你好def世界ghi",
344            // Embedded newlines (pasted / Ctrl+J): hard line breaks.
345            "first line\nsecond line",
346            "para one\n\npara two",
347            "trailing newline\n",
348            "\nleading newline",
349        ];
350        let content_width = 20usize;
351        for input in inputs {
352            let wrapped = wrap_input_with_prompt(input, content_width);
353
354            // Strip prefixes to count content lines (first line "> ",
355            // continuation lines "  "). This yields one vec per rendered
356            // line holding the post-prefix content.
357            let rendered_lines: Vec<String> = wrapped
358                .split('\n')
359                .enumerate()
360                .map(|(i, line)| {
361                    let prefix = if i == 0 { "> " } else { "  " };
362                    line.strip_prefix(prefix).unwrap_or(line).to_string()
363                })
364                .collect();
365
366            // For each byte offset in the input, ask the cursor function
367            // which (row, col) it belongs to, then assert the row index is
368            // in range for the wrapped text.
369            for cursor_pos in 0..=input.len() {
370                if !input.is_char_boundary(cursor_pos) {
371                    continue;
372                }
373                let (row, _col) =
374                    InputState::calculate_cursor_position(input, cursor_pos, content_width);
375                assert!(
376                    (row as usize) < rendered_lines.len().max(1),
377                    "cursor row {} out of wrap range ({} lines) for input {:?} at byte {}",
378                    row,
379                    rendered_lines.len(),
380                    input,
381                    cursor_pos,
382                );
383            }
384        }
385    }
386
387    #[test]
388    fn find_line_break_whitespace_preferred() {
389        assert_eq!(find_line_break("hello world foo", 10), 6);
390    }
391
392    #[test]
393    fn find_line_break_hard_break_without_whitespace() {
394        assert_eq!(find_line_break("abcdefghijklmno", 5), 5);
395    }
396
397    #[test]
398    fn find_line_break_respects_char_boundary() {
399        // 3-byte CJK chars: each is 3 bytes / 2 display cells. With
400        // `line_width = 4` cells we fit exactly two CJK chars (4 cells,
401        // 6 bytes). Old byte-based code returned 3 (only the first char),
402        // wasting half the line.
403        let s = "你好";
404        assert_eq!(find_line_break(s, 4), 6);
405    }
406
407    #[test]
408    fn find_line_break_uses_display_width_for_cjk() {
409        // Cell width of "你好世界abc" = 4*2 + 3 = 11 cells; `line_width=10`
410        // fits "你好世界ab" (10 cells, 14 bytes) and breaks before "c".
411        let s = "你好世界abc";
412        assert_eq!(find_line_break(s, 10), 14);
413    }
414
415    #[test]
416    fn find_line_break_whole_remaining_fits() {
417        assert_eq!(find_line_break("short", 100), "short".len());
418    }
419
420    #[test]
421    fn find_line_break_makes_progress_when_first_char_overflows() {
422        // Double-width char on a 1-cell viewport: must still consume the
423        // char (return offset 3) so the wrap loop can't spin forever.
424        assert_eq!(find_line_break("你hello", 1), 3);
425    }
426
427    #[test]
428    fn find_line_break_multibyte_whitespace_is_char_boundary() {
429        // Regression: `char::is_whitespace` matches multibyte spaces (NBSP
430        // U+00A0 = 2 bytes, ideographic space U+3000 = 3 bytes, U+2028,
431        // U+202F …). A naive `pos + 1` break offset lands mid-codepoint and
432        // the caller's `&rem[bp..]` slice panics the whole renderer. The
433        // break must always be a char boundary, and the full wrap path must
434        // not panic.
435        for s in [
436            "aaaa\u{00A0}bbbbbbbbbbbbbbbb",
437            "\u{3000}\u{3000}wwwwwwwwwwwwwww",
438            "word\u{2028}word\u{202F}wordwordword",
439        ] {
440            for width in 1..=20 {
441                let bp = find_line_break(s, width);
442                assert!(
443                    s.is_char_boundary(bp),
444                    "break {bp} not a char boundary in {s:?} at width {width}",
445                );
446                let _ = &s[bp..]; // must not panic
447            }
448            let _ = wrap_input_with_prompt(s, 8);
449        }
450    }
451
452    #[test]
453    fn wrap_renders_embedded_newlines_as_rows() {
454        // A pasted multi-line block must show as multiple rows, not a single
455        // space-joined paragraph.
456        assert_eq!(wrap_input_with_prompt("a\nb", 20), "> a\n  b");
457        // Consecutive newlines keep the blank line.
458        assert_eq!(wrap_input_with_prompt("a\n\nb", 20), "> a\n  \n  b");
459        // A trailing newline yields an empty continuation row.
460        assert_eq!(wrap_input_with_prompt("a\n", 20), "> a\n  ");
461    }
462
463    #[test]
464    fn cursor_tracks_rows_across_newlines() {
465        // "a\nb": byte 0=before a, 1=after a (on \n), 2=before b, 3=after b.
466        assert_eq!(InputState::calculate_cursor_position("a\nb", 0, 20), (0, 0));
467        assert_eq!(InputState::calculate_cursor_position("a\nb", 1, 20), (0, 1));
468        assert_eq!(InputState::calculate_cursor_position("a\nb", 2, 20), (1, 0));
469        assert_eq!(InputState::calculate_cursor_position("a\nb", 3, 20), (1, 1));
470    }
471}