Skip to main content

tvui/
text_view.rs

1//! A multi-line text box: fixed-size window onto lines of text, scrolled on both axes.
2
3use ratatui::buffer::Buffer;
4use ratatui::layout::{Position, Rect};
5use ratatui::style::Style;
6use ratatui::widgets::StatefulWidget;
7
8use crate::input_line::{index_at_column, join_to_previous, shown, width_of};
9use crate::{Role, RowWindow, Theme};
10
11/// The first line and first display column shown in the box.
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13pub struct Viewport {
14    pub top: usize,
15    pub left: usize,
16}
17
18/// The lines of a text and the cursor in them as (line, character index). Rendering scrolls
19/// the [`Viewport`] state the least that keeps the character under the cursor in view, then
20/// draws through it; the terminal cursor itself is placed by the caller at [`TextView::cursor`].
21pub struct TextView<'a> {
22    theme: &'a Theme,
23    lines: &'a [&'a str],
24    cursor: (usize, usize),
25    focused: bool,
26}
27
28/// The display column of the character index `cursor` of `line`.
29pub(crate) fn column(line: &str, cursor: usize) -> usize {
30    line.chars()
31        .take(cursor)
32        .map(|ch| usize::from(width_of(ch)))
33        .sum()
34}
35
36/// `start` moved the least that brings `span` cells from `at` into `size` cells from it; a span
37/// wider than `size` is shown from its start.
38pub(crate) fn follow(start: usize, at: usize, span: usize, size: u16) -> usize {
39    let size = usize::from(size).max(1);
40    let end = at.saturating_add(span.clamp(1, size));
41    if at < start {
42        at
43    } else if end > start.saturating_add(size) {
44        end - size
45    } else {
46        start
47    }
48}
49
50fn scroll_offset(at: usize) -> u16 {
51    u16::try_from(at).unwrap_or(u16::MAX)
52}
53
54/// `previous` scrolled the least that keeps the `cursor` of `lines` inside `area`.
55fn follow_cursor(
56    area: Rect,
57    lines: &[&str],
58    cursor: (usize, usize),
59    previous: Viewport,
60) -> Viewport {
61    let (row, col) = cursor;
62    let line = lines.get(row).copied().unwrap_or("");
63    let under = line
64        .chars()
65        .nth(col)
66        .map_or(1, |ch| usize::from(width_of(ch)));
67    let last_top = RowWindow::last_top(lines.len(), usize::from(area.height));
68    Viewport {
69        top: follow(previous.top.min(last_top), row, 1, area.height),
70        left: follow(previous.left, column(line, col), under, area.width),
71    }
72}
73
74impl<'a> TextView<'a> {
75    #[must_use]
76    pub fn new(
77        theme: &'a Theme,
78        lines: &'a [&'a str],
79        cursor: (usize, usize),
80        focused: bool,
81    ) -> Self {
82        TextView {
83            theme,
84            lines,
85            cursor,
86            focused,
87        }
88    }
89
90    /// The screen cell of the `cursor` of `lines` drawn in `area` through `viewport`.
91    #[must_use]
92    pub fn cursor(
93        area: Rect,
94        lines: &[&str],
95        cursor: (usize, usize),
96        viewport: Viewport,
97    ) -> Position {
98        let (row, col) = cursor;
99        let at = lines.get(row).map_or(0, |line| column(line, col));
100        let x = at.saturating_sub(viewport.left);
101        let y = row.saturating_sub(viewport.top);
102        Position::new(
103            area.x.saturating_add(scroll_offset(x)),
104            area.y.saturating_add(scroll_offset(y)),
105        )
106    }
107
108    /// The (line, character index) a click at `point` lands on in `lines` drawn in `area`
109    /// through `viewport`: the inverse of [`TextView::cursor`]. A click below the text lands on
110    /// the last line and one past a line's end at its end.
111    #[must_use]
112    pub fn position_at(
113        area: Rect,
114        lines: &[&str],
115        viewport: Viewport,
116        point: Position,
117    ) -> (usize, usize) {
118        let row = viewport
119            .top
120            .saturating_add(usize::from(point.y.saturating_sub(area.y)))
121            .min(lines.len().saturating_sub(1));
122        let dx = usize::from(point.x.saturating_sub(area.x));
123        let line = lines.get(row).copied().unwrap_or("");
124        (row, index_at_column(line, viewport.left.saturating_add(dx)))
125    }
126}
127
128/// One line drawn into the row `y` of `area`, its first `left` columns scrolled off; a wide
129/// character cut by either edge is left out.
130pub(crate) fn draw_row(
131    buf: &mut Buffer,
132    area: Rect,
133    y: u16,
134    line: &str,
135    left: usize,
136    style: Style,
137) {
138    let mut col = 0;
139    let mut last = None;
140    for ch in line.chars() {
141        let width = usize::from(width_of(ch));
142        if width == 0 {
143            if col > left {
144                join_to_previous(buf, last, ch);
145            }
146            continue;
147        }
148        let start = col;
149        col += width;
150        if start < left {
151            continue;
152        }
153        let x = scroll_offset(start - left);
154        if x.saturating_add(scroll_offset(width)) > area.width {
155            break;
156        }
157        let at = Position::new(area.x + x, y);
158        buf[at].set_char(shown(ch)).set_style(style);
159        last = Some(at);
160    }
161}
162
163impl StatefulWidget for TextView<'_> {
164    type State = Viewport;
165
166    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Viewport) {
167        *state = follow_cursor(area, self.lines, self.cursor, *state);
168        let area = area.intersection(buf.area);
169        let role = if self.focused {
170            Role::InputFocused
171        } else {
172            Role::Input
173        };
174        let style = self.theme.style(role);
175        buf.set_style(area, style);
176        let shown = self.lines.iter().skip(state.top);
177        for (y, line) in (area.y..area.bottom()).zip(shown) {
178            draw_row(buf, area, y, line, state.left, style);
179        }
180    }
181}
182
183#[cfg(test)]
184mod tests;