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

            
4
use ratatui::buffer::Buffer;
5
use ratatui::layout::{Margin, Position, Rect};
6
use ratatui::style::Style;
7
use ratatui::text::Span;
8
use ratatui::widgets::StatefulWidget;
9

            
10
use crate::text_view::{column, draw_row, follow};
11
use 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`].
17
pub 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.
25
pub const ARROW_CELLS: u16 = 2;
26

            
27
const LEFT_ARROW: char = '\u{25c4}';
28
const 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.
32
16603
fn text_area(area: Rect) -> Rect {
33
16603
    let margin = u16::from(area.width >= 3);
34
16603
    area.inner(Margin::new(margin, 0))
35
16603
}
36

            
37
/// The cells `ch` takes; a control character is drawn as one blank, see [`shown`].
38
748522
pub(crate) fn width_of(ch: char) -> u16 {
39
748522
    if ch.is_control() {
40
21
        return 1;
41
748501
    }
42
748501
    let mut buf = [0; 4];
43
748501
    u16::try_from(Span::raw(&*ch.encode_utf8(&mut buf)).width()).unwrap_or(u16::MAX)
44
748522
}
45

            
46
/// The character put in a cell for `ch`: control characters must not reach the terminal.
47
80458
pub(crate) fn shown(ch: char) -> char {
48
80458
    if ch.is_control() { ' ' } else { ch }
49
80458
}
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.
53
292
pub(crate) fn index_at_column(text: &str, target: usize) -> usize {
54
292
    let mut col = 0;
55
292
    for (index, ch) in text.chars().enumerate() {
56
2835
        let width = usize::from(width_of(ch));
57
2835
        if width > 0 && target < col + width {
58
232
            return index;
59
2603
        }
60
2603
        col += width;
61
    }
62
60
    text.chars().count()
63
292
}
64

            
65
/// A zero-width character such as a combining mark joins the symbol of the cell before it.
66
2
pub(crate) fn join_to_previous(buf: &mut Buffer, last: Option<Position>, ch: char) {
67
2
    if let Some(at) = last {
68
2
        let joined = format!("{}{ch}", buf[at].symbol());
69
2
        buf[at].set_symbol(&joined);
70
    }
71
2
}
72

            
73
impl<'a> InputLine<'a> {
74
    #[must_use]
75
7606
    pub fn new(theme: &'a Theme, text: &'a str, cursor: usize, focused: bool) -> Self {
76
7606
        InputLine {
77
7606
            theme,
78
7606
            text,
79
7606
            cursor,
80
7606
            focused,
81
7606
        }
82
7606
    }
83

            
84
    /// The screen cell of the cursor of `text` drawn in `area` through `viewport`.
85
    #[must_use]
86
1237
    pub fn cursor(area: Rect, text: &str, cursor: usize, viewport: Viewport) -> Position {
87
1237
        let x = column(text, cursor).saturating_sub(viewport.left);
88
1237
        Position::new(
89
1237
            text_area(area)
90
1237
                .x
91
1237
                .saturating_add(u16::try_from(x).unwrap_or(u16::MAX)),
92
1237
            area.y,
93
1237
        )
94
1237
    }
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
237
    pub fn position_at(area: Rect, text: &str, viewport: Viewport, point: Position) -> usize {
100
237
        let dx = usize::from(point.x.saturating_sub(text_area(area).x));
101
237
        index_at_column(text, viewport.left.saturating_add(dx))
102
237
    }
103
}
104

            
105
impl InputLine<'_> {
106
7523
    fn draw_arrows(&self, area: Rect, buf: &mut Buffer, left: usize, style: Style) {
107
7523
        let arrow = self
108
7523
            .theme
109
7523
            .style(Role::InputArrow)
110
7523
            .fg
111
7523
            .map_or(style, |fg| style.fg(fg));
112
7523
        let shown = [
113
7523
            (left > 0, area.x, LEFT_ARROW),
114
7523
            (
115
7523
                column(self.text, usize::MAX)
116
7523
                    > left.saturating_add(usize::from(text_area(area).width)),
117
7523
                area.right().saturating_sub(1),
118
7523
                RIGHT_ARROW,
119
7523
            ),
120
7523
        ];
121
15046
        for (_, x, glyph) in shown.into_iter().filter(|(on, ..)| *on) {
122
308
            if let Some(cell) = buf.cell_mut((x, area.y)) {
123
308
                cell.set_char(glyph).set_style(arrow);
124
            }
125
        }
126
7523
    }
127
}
128

            
129
impl StatefulWidget for InputLine<'_> {
130
    type State = Viewport;
131

            
132
7606
    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Viewport) {
133
7606
        let inner = text_area(area);
134
7606
        let reach = area.right().saturating_sub(inner.x);
135
7606
        let under = self
136
7606
            .text
137
7606
            .chars()
138
7606
            .nth(self.cursor)
139
7606
            .map_or(1, |ch| usize::from(width_of(ch)));
140
7606
        let size = if under > 1 { inner.width } else { reach };
141
7606
        let filled = column(self.text, usize::MAX)
142
7606
            .saturating_add(1)
143
7606
            .saturating_sub(usize::from(reach));
144
7606
        state.left = follow(
145
7606
            state.left.min(filled),
146
7606
            column(self.text, self.cursor),
147
7606
            under,
148
7606
            size,
149
7606
        );
150
7606
        let role = if self.focused {
151
1253
            Role::InputFocused
152
        } else {
153
6353
            Role::Input
154
        };
155
7606
        let style = self.theme.style(role);
156
7606
        let visible = area.intersection(buf.area);
157
7606
        buf.set_style(visible, style);
158
7606
        if visible.is_empty() {
159
2
            return;
160
7604
        }
161
7604
        let text = inner.intersection(buf.area);
162
7604
        draw_row(buf, text, text.y, self.text, state.left, style);
163
7604
        if area.width >= 3 {
164
7523
            self.draw_arrows(area, buf, state.left, style);
165
81
        }
166
7606
    }
167
}
168

            
169
#[cfg(test)]
170
mod tests;