1use 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#[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#[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
39pub struct DropDown<'a> {
43 theme: &'a Theme,
44 items: &'a [String],
45}
46
47impl<'a> DropDown<'a> {
48 #[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 #[must_use]
57 pub fn rows(area: Rect) -> Rect {
58 Block::bordered().inner(area)
59 }
60
61 #[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;