1use ratatui::buffer::Buffer;
4use ratatui::layout::Rect;
5use ratatui::style::Style;
6
7use crate::markup::{plain, spans};
8use crate::{Role, Theme};
9
10const MIN_WIDTH: u16 = 10;
12
13pub(crate) const HEIGHT: u16 = 2;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct Button<'a> {
19 pub label: &'a str,
20 pub default: bool,
21}
22
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
25pub(crate) struct Look {
26 pub focused: bool,
27 pub pressed: bool,
28}
29
30impl Button<'_> {
31 #[must_use]
33 pub fn width(&self) -> u16 {
34 let label = u16::try_from(plain(self.label).chars().count() + 4).unwrap_or(u16::MAX);
35 label.max(MIN_WIDTH)
36 }
37
38 #[must_use]
41 pub fn face(area: Rect) -> Rect {
42 Rect::new(
43 area.x.saturating_add(1),
44 area.y,
45 area.width.saturating_sub(2),
46 1,
47 )
48 }
49
50 fn faces(&self, theme: &Theme, focused: bool) -> (Style, Style) {
52 let role = match (focused, self.default) {
53 (true, _) => Role::ButtonFocus,
54 (false, true) => Role::ButtonDefault,
55 (false, false) => Role::Button,
56 };
57 let face = theme.style(role);
58 let hot = match theme.style(Role::ButtonHotkey).fg {
59 Some(fg) => face.fg(fg),
60 None => face,
61 };
62 (face, hot)
63 }
64
65 pub(crate) fn render(&self, area: Rect, buf: &mut Buffer, theme: &Theme, look: Look) {
68 if area.width < 3 || area.height < HEIGHT {
69 return;
70 }
71 let (face, hot) = self.faces(theme, look.focused);
72 let shadow = theme.style(Role::ButtonShadow);
73 let last = area.width - 1;
74 let first = if look.pressed { 2 } else { 1 };
75 let mut put = |x: u16, y: u16, symbol: &str, style: Style| {
76 if let Some(cell) = buf.cell_mut((area.x + x, area.y + y)) {
77 cell.set_symbol(symbol);
78 cell.set_style(style);
79 }
80 };
81 for x in 0..area.width {
82 let on_face = x >= first && (look.pressed || x < last);
83 put(x, 0, " ", if on_face { face } else { shadow });
84 let lower = if look.pressed || x < 2 {
85 " "
86 } else {
87 "\u{2580}"
88 };
89 put(x, 1, lower, shadow);
90 }
91 if !look.pressed {
92 put(last, 0, "\u{2584}", shadow);
93 }
94 let text = plain(self.label);
95 let pad = usize::from(last).saturating_sub(text.chars().count() + 1) / 2;
96 let mut x = first + u16::try_from(pad.max(1)).unwrap_or(0);
97 let end = if look.pressed { area.width } else { last };
98 for span in spans(self.label, face, hot) {
99 for symbol in span.content.chars() {
100 if x < end {
101 put(x, 0, symbol.encode_utf8(&mut [0; 4]), span.style);
102 }
103 x += 1;
104 }
105 }
106 }
107}
108
109#[cfg(test)]
110mod tests;