Skip to main content

tvui/
panel.rs

1//! A Dos Navigator file panel: the window frame, column dividers joined to it, and an info
2//! line in the bottom border. Rows are the caller's; it lays them out through [`Panel::columns`].
3
4use std::ops::Range;
5
6use ratatui::buffer::Buffer;
7use ratatui::layout::{Constraint, Layout, Margin, Rect};
8use ratatui::text::{Line, Span};
9use ratatui::widgets::Widget;
10
11use crate::{Chrome, FrameMode, FrameState, Role, Theme, grow_area, inner};
12
13/// The cells the two arrows of a scrollbar take; a track no taller draws no bar.
14const ARROWS: usize = 2;
15
16/// The space between two columns, taken by their divider.
17const SPACING: u16 = 1;
18
19pub struct Panel<'a> {
20    theme: &'a Theme,
21    title: &'a str,
22    state: FrameState,
23    widths: &'a [Constraint],
24}
25
26impl<'a> Panel<'a> {
27    #[must_use]
28    pub fn new(theme: &'a Theme, title: &'a str, state: FrameState) -> Self {
29        Self {
30            theme,
31            title,
32            state,
33            widths: &[],
34        }
35    }
36
37    /// The column widths; a divider is drawn between neighbours.
38    #[must_use]
39    pub fn widths(mut self, widths: &'a [Constraint]) -> Self {
40        self.widths = widths;
41        self
42    }
43
44    /// The area inside the frame.
45    #[must_use]
46    pub fn inner(area: Rect) -> Rect {
47        inner(area)
48    }
49
50    /// The data rows of a panel drawn in `area`: inside the frame, below the header line.
51    #[must_use]
52    pub fn rows(area: Rect) -> Rect {
53        let inner = Self::inner(area);
54        Rect {
55            y: inner.y.saturating_add(1),
56            height: inner.height.saturating_sub(1),
57            ..inner
58        }
59    }
60
61    /// The columns of a panel drawn in `area`, a divider cell between each two.
62    #[must_use]
63    pub fn columns(&self, area: Rect) -> Vec<Rect> {
64        Layout::horizontal(self.widths)
65            .spacing(SPACING)
66            .split(Self::inner(area))
67            .to_vec()
68    }
69
70    /// A divider through the column gap at `x`, joined to the frame where the frame is a line.
71    fn divide(&self, buf: &mut Buffer, area: Rect, x: u16, cursor: Option<u16>) {
72        let (line, down, up) = match self.state.mode {
73            FrameMode::Active => ("\u{2550}", "\u{2564}", "\u{2567}"),
74            _ => ("\u{2500}", "\u{252C}", "\u{2534}"),
75        };
76        let style = self.theme.style(self.state.frame_role());
77        let last = area.bottom().saturating_sub(1);
78        for y in area.top()..area.bottom() {
79            let Some(cell) = buf.cell_mut((x, y)) else {
80                continue;
81            };
82            let symbol = match y {
83                y if y == area.top() && cell.symbol() == line => down,
84                y if y == last && cell.symbol() == line => up,
85                y if y != area.top() && y != last => "\u{2502}",
86                _ => continue,
87            };
88            cell.set_symbol(symbol);
89            if cursor != Some(y) {
90                cell.set_style(style);
91            }
92        }
93    }
94}
95
96impl Panel<'_> {
97    /// The frame lines and fill; draw the rows, then [`Panel::render_dividers`].
98    pub fn render_frame(&self, area: Rect, buf: &mut Buffer) {
99        self.chrome().render_frame(area, buf);
100    }
101
102    fn chrome(&self) -> Chrome<'_> {
103        Chrome::new(self.theme, self.title, self.state)
104    }
105
106    /// The dividers joined to the frame lines, then the frame's number, title and icons over
107    /// them; the cursor row at screen row `cursor` keeps its own style, so its bar runs unbroken.
108    pub fn render_dividers(&self, area: Rect, buf: &mut Buffer, cursor: Option<u16>) {
109        let inner = Self::inner(area);
110        let columns = self.columns(area);
111        let gaps = columns.split_last().map_or(&[][..], |(_, rest)| rest);
112        for x in gaps
113            .iter()
114            .copied()
115            .map(Rect::right)
116            .filter(|x| *x < inner.right())
117        {
118            self.divide(buf, area, x, cursor);
119        }
120        self.chrome().render_labels(area, buf);
121    }
122}
123
124impl Widget for Panel<'_> {
125    fn render(self, area: Rect, buf: &mut Buffer) {
126        self.render_frame(area, buf);
127        self.render_dividers(area, buf, None);
128    }
129}
130
131/// Writes `info` right-aligned into the bottom border of `area`, clipped inside the corners and
132/// short of the resize mark, in the header role.
133pub fn render_info(theme: &Theme, area: Rect, buf: &mut Buffer, state: FrameState, info: &str) {
134    let right = grow_area(area, state).map_or(area.right().saturating_sub(1), |grow| grow.x);
135    let left = area.x.saturating_add(1);
136    if info.is_empty() || area.height < 2 || right <= left {
137        return;
138    }
139    let row = Rect::new(left, area.bottom() - 1, right - left, 1);
140    Line::from(Span::styled(
141        format!(" {info} "),
142        theme.style(Role::PanelHeader),
143    ))
144    .right_aligned()
145    .render(row, buf);
146}
147
148/// `n–m of total` for the rows `shown` of `total`, counted from zero; nothing without rows.
149#[must_use]
150pub fn range_text(shown: Range<usize>, total: usize) -> Option<String> {
151    (!shown.is_empty()).then(|| format!("{}\u{2013}{} of {total}", shown.start + 1, shown.end))
152}
153
154/// The cells of `area`'s right border a scrollbar runs along, inside the corners.
155#[must_use]
156pub fn scrollbar_track(area: Rect) -> Rect {
157    let track = area.inner(Margin::new(0, 1));
158    Rect {
159        x: track.right().saturating_sub(1),
160        width: track.width.min(1),
161        ..track
162    }
163}
164
165/// Draws a scrollbar on the right border of `area` in the TurboVision symbols and the scrollbar
166/// roles, for `rows` rows with `view` of them shown from row `top`; nothing when they all fit.
167pub fn render_scrollbar(
168    theme: &Theme,
169    area: Rect,
170    buf: &mut Buffer,
171    (rows, view, top): (usize, usize, usize),
172) {
173    for (cells, part) in scrollbar_parts(area, (rows, view, top)) {
174        let (symbol, role) = match part {
175            BarPart::Up => ("\u{25B2}", Role::Scrollbar),
176            BarPart::Down => ("\u{25BC}", Role::Scrollbar),
177            BarPart::PageUp | BarPart::PageDown => ("\u{2592}", Role::Scrollbar),
178            BarPart::Thumb => ("\u{25A0}", Role::ScrollbarThumb),
179        };
180        let style = theme.style(role);
181        for position in cells.intersection(buf.area).positions() {
182            buf[position].set_symbol(symbol).set_style(style);
183        }
184    }
185}
186
187/// A part of a scrollbar a click can land on.
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum BarPart {
190    Up,
191    PageUp,
192    Thumb,
193    PageDown,
194    Down,
195}
196
197/// The parts of the bar [`render_scrollbar`] draws for the same `area` and rows, each with the
198/// cells it covers, top to bottom; nothing when the rows all fit.
199#[must_use]
200pub fn scrollbar_parts(
201    area: Rect,
202    (rows, view, top): (usize, usize, usize),
203) -> Vec<(Rect, BarPart)> {
204    let track = scrollbar_track(area);
205    let height = usize::from(track.height);
206    if rows <= view || height <= ARROWS {
207        return Vec::new();
208    }
209    let (before, thumb, after) = thumb_lengths(height, (rows, view, top));
210    let parts = [
211        (1, BarPart::Up),
212        (before, BarPart::PageUp),
213        (thumb, BarPart::Thumb),
214        (after, BarPart::PageDown),
215        (1, BarPart::Down),
216    ];
217    let mut y = track.y;
218    let mut cells = Vec::with_capacity(parts.len());
219    for (len, part) in parts {
220        let len = u16::try_from(len).unwrap_or(u16::MAX);
221        let cell = Rect::new(track.x, y, track.width, len).intersection(track);
222        y = y.saturating_add(len);
223        cells.push((cell, part));
224    }
225    cells.retain(|(cell, _)| !cell.is_empty());
226    cells
227}
228
229/// The cells of the track between the arrows before, in and after the thumb for a track
230/// `height` cells tall, more than the arrows: the thumb is the share of the track the view is
231/// of the rows, rounded, at least one cell.
232fn thumb_lengths(height: usize, (rows, view, top): (usize, usize, usize)) -> (usize, usize, usize) {
233    let track = height - ARROWS;
234    let round_div = |n: usize, d: usize| n.saturating_add(d / 2) / d;
235    let viewport = if view == 0 { height } else { view };
236    let last = rows - view;
237    let total = last.saturating_add(viewport);
238    let thumb = round_div(viewport.saturating_mul(track), total).clamp(1, track);
239    let start = round_div(top.min(last).saturating_mul(track), total).min(track - thumb);
240    (start, thumb, track - start - thumb)
241}
242
243#[cfg(test)]
244mod tests;