Skip to main content

tvui/
input_line.rs

1//! A one-row text field as Turbo Vision draws it: the text starts one cell in, and a `◄` or `►`
2//! in the outer cells says that text is scrolled off that side.
3
4use ratatui::buffer::Buffer;
5use ratatui::layout::{Margin, Position, Rect};
6use ratatui::style::Style;
7use ratatui::text::Span;
8use ratatui::widgets::StatefulWidget;
9
10use crate::text_view::{column, draw_row, follow};
11use crate::{Role, Theme, Viewport};
12
13/// The text of a field and the cursor as a character index. Rendering scrolls the
14/// [`Viewport`] state the least that keeps the character under the cursor between the arrow
15/// cells, as [`TextView`](crate::TextView) does; the terminal cursor itself is placed by the
16/// caller at [`InputLine::cursor`].
17pub struct InputLine<'a> {
18    theme: &'a Theme,
19    text: &'a str,
20    cursor: usize,
21    focused: bool,
22}
23
24/// The cells an input line keeps at its two ends for the scroll arrows.
25pub const ARROW_CELLS: u16 = 2;
26
27const LEFT_ARROW: char = '\u{25c4}';
28const RIGHT_ARROW: char = '\u{25ba}';
29
30/// The part of `area` the text is drawn in: a field too narrow for text between two arrow cells
31/// has no arrows.
32fn text_area(area: Rect) -> Rect {
33    let margin = u16::from(area.width >= 3);
34    area.inner(Margin::new(margin, 0))
35}
36
37/// The cells `ch` takes; a control character is drawn as one blank, see [`shown`].
38pub(crate) fn width_of(ch: char) -> u16 {
39    if ch.is_control() {
40        return 1;
41    }
42    let mut buf = [0; 4];
43    u16::try_from(Span::raw(&*ch.encode_utf8(&mut buf)).width()).unwrap_or(u16::MAX)
44}
45
46/// The character put in a cell for `ch`: control characters must not reach the terminal.
47pub(crate) fn shown(ch: char) -> char {
48    if ch.is_control() { ' ' } else { ch }
49}
50
51/// The index of the character of `text` that covers display column `target`, counted from the
52/// start of the text; the character count when `target` is past the end.
53pub(crate) fn index_at_column(text: &str, target: usize) -> usize {
54    let mut col = 0;
55    for (index, ch) in text.chars().enumerate() {
56        let width = usize::from(width_of(ch));
57        if width > 0 && target < col + width {
58            return index;
59        }
60        col += width;
61    }
62    text.chars().count()
63}
64
65/// A zero-width character such as a combining mark joins the symbol of the cell before it.
66pub(crate) fn join_to_previous(buf: &mut Buffer, last: Option<Position>, ch: char) {
67    if let Some(at) = last {
68        let joined = format!("{}{ch}", buf[at].symbol());
69        buf[at].set_symbol(&joined);
70    }
71}
72
73impl<'a> InputLine<'a> {
74    #[must_use]
75    pub fn new(theme: &'a Theme, text: &'a str, cursor: usize, focused: bool) -> Self {
76        InputLine {
77            theme,
78            text,
79            cursor,
80            focused,
81        }
82    }
83
84    /// The screen cell of the cursor of `text` drawn in `area` through `viewport`.
85    #[must_use]
86    pub fn cursor(area: Rect, text: &str, cursor: usize, viewport: Viewport) -> Position {
87        let x = column(text, cursor).saturating_sub(viewport.left);
88        Position::new(
89            text_area(area)
90                .x
91                .saturating_add(u16::try_from(x).unwrap_or(u16::MAX)),
92            area.y,
93        )
94    }
95
96    /// The character index a click at `point` lands on in `text` drawn in `area` through
97    /// `viewport`: the inverse of [`InputLine::cursor`]. A click past the end lands at the end.
98    #[must_use]
99    pub fn position_at(area: Rect, text: &str, viewport: Viewport, point: Position) -> usize {
100        let dx = usize::from(point.x.saturating_sub(text_area(area).x));
101        index_at_column(text, viewport.left.saturating_add(dx))
102    }
103}
104
105impl InputLine<'_> {
106    fn draw_arrows(&self, area: Rect, buf: &mut Buffer, left: usize, style: Style) {
107        let arrow = self
108            .theme
109            .style(Role::InputArrow)
110            .fg
111            .map_or(style, |fg| style.fg(fg));
112        let shown = [
113            (left > 0, area.x, LEFT_ARROW),
114            (
115                column(self.text, usize::MAX)
116                    > left.saturating_add(usize::from(text_area(area).width)),
117                area.right().saturating_sub(1),
118                RIGHT_ARROW,
119            ),
120        ];
121        for (_, x, glyph) in shown.into_iter().filter(|(on, ..)| *on) {
122            if let Some(cell) = buf.cell_mut((x, area.y)) {
123                cell.set_char(glyph).set_style(arrow);
124            }
125        }
126    }
127}
128
129impl StatefulWidget for InputLine<'_> {
130    type State = Viewport;
131
132    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Viewport) {
133        let inner = text_area(area);
134        let reach = area.right().saturating_sub(inner.x);
135        let under = self
136            .text
137            .chars()
138            .nth(self.cursor)
139            .map_or(1, |ch| usize::from(width_of(ch)));
140        let size = if under > 1 { inner.width } else { reach };
141        let filled = column(self.text, usize::MAX)
142            .saturating_add(1)
143            .saturating_sub(usize::from(reach));
144        state.left = follow(
145            state.left.min(filled),
146            column(self.text, self.cursor),
147            under,
148            size,
149        );
150        let role = if self.focused {
151            Role::InputFocused
152        } else {
153            Role::Input
154        };
155        let style = self.theme.style(role);
156        let visible = area.intersection(buf.area);
157        buf.set_style(visible, style);
158        if visible.is_empty() {
159            return;
160        }
161        let text = inner.intersection(buf.area);
162        draw_row(buf, text, text.y, self.text, state.left, style);
163        if area.width >= 3 {
164            self.draw_arrows(area, buf, state.left, style);
165        }
166    }
167}
168
169#[cfg(test)]
170mod tests;