Skip to main content

tvui/
dropdown.rs

1//! The drop-down list box of a select: a framed list under its field, with a shadow.
2
3use ratatui::buffer::Buffer;
4use ratatui::layout::Rect;
5use ratatui::widgets::{Block, Clear, List, ListState, StatefulWidget, Widget};
6
7use crate::frame::{list_box, shadow};
8use crate::{Role, RowWindow, Theme, render_scrollbar};
9
10/// The rows in the list colours with the selected one in the `list-selected` role.
11#[must_use]
12pub(crate) fn list(theme: &Theme, items: &[String]) -> List<'static> {
13    let rows = items.iter().map(|item| format!(" {item}"));
14    List::new(rows)
15        .style(theme.style(Role::List))
16        .highlight_style(theme.style(Role::ListSelected))
17}
18
19/// The box of `rows` list rows with its border, `anchor` wide and left-aligned with it: on the
20/// row below `anchor`, or above it when there is no room below and more above, cut to fit the
21/// side chosen. Moved left to stay inside `screen`.
22#[must_use]
23pub fn dropdown_area(anchor: Rect, rows: u16, screen: Rect) -> Rect {
24    let height = rows.saturating_add(2);
25    let width = anchor.width.min(screen.width);
26    let x = anchor
27        .x
28        .min(screen.right().saturating_sub(width))
29        .max(screen.x);
30    let below = screen.bottom().saturating_sub(anchor.bottom());
31    let above = anchor.y.saturating_sub(screen.y);
32    if height <= below || below >= above {
33        return Rect::new(x, anchor.bottom(), width, height.min(below));
34    }
35    let height = height.min(above);
36    Rect::new(x, anchor.y - height, width, height)
37}
38
39/// A framed `list` with a shadow and a scrollbar when the items exceed the box, rendered in
40/// the area [`dropdown_area`] gives. The caller owns the [`ListState`]: the window stays put
41/// while the selection moves inside it and scrolls by the minimum past its edges.
42pub struct DropDown<'a> {
43    theme: &'a Theme,
44    items: &'a [String],
45}
46
47impl<'a> DropDown<'a> {
48    /// The width of the box that shows the widest of `items` whole.
49    #[must_use]
50    pub fn width(items: &[String]) -> u16 {
51        let widest = items.iter().map(|item| item.chars().count()).max();
52        u16::try_from(widest.unwrap_or(0) + 3).unwrap_or(u16::MAX)
53    }
54
55    /// The rows of the box drawn in `area`, inside its border.
56    #[must_use]
57    pub fn rows(area: Rect) -> Rect {
58        Block::bordered().inner(area)
59    }
60
61    /// The area of each option row on screen in the box drawn in `area`, with the option's index
62    /// among `len` options when the list is scrolled to `top`.
63    #[must_use]
64    pub fn option_rows(area: Rect, top: usize, len: usize) -> Vec<(usize, Rect)> {
65        let rows = Self::rows(area);
66        let shown = len.saturating_sub(top).min(usize::from(rows.height));
67        (0..shown)
68            .filter_map(|n| {
69                let y = rows.y.checked_add(u16::try_from(n).ok()?)?;
70                Some((top.saturating_add(n), Rect::new(rows.x, y, rows.width, 1)))
71            })
72            .collect()
73    }
74
75    #[must_use]
76    pub fn new(theme: &'a Theme, items: &'a [String]) -> Self {
77        DropDown { theme, items }
78    }
79}
80
81impl StatefulWidget for DropDown<'_> {
82    type State = ListState;
83
84    fn render(self, area: Rect, buf: &mut Buffer, state: &mut ListState) {
85        let outer = area.intersection(buf.area);
86        Clear.render(outer, buf);
87        let inner = Self::rows(outer);
88        list_box(self.theme).render(outer, buf);
89        let view = usize::from(inner.height);
90        *state.offset_mut() = state
91            .offset()
92            .min(RowWindow::last_top(self.items.len(), view));
93        StatefulWidget::render(list(self.theme, self.items), inner, buf, state);
94        let top = state.offset();
95        render_scrollbar(self.theme, outer, buf, (self.items.len(), view, top));
96        shadow(buf, outer, self.theme);
97    }
98}
99
100#[cfg(test)]
101mod tests;