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