Lines
98.28 %
Functions
100 %
Branches
//! Dialog buttons: the two-row Turbo Vision button, a face and a half-block shadow.
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Style;
use crate::markup::{plain, spans};
use crate::{Role, Theme};
/// The width of a button whose label is shorter than this less 4.
const MIN_WIDTH: u16 = 10;
/// Rows of a button: the face and the shadow under it.
pub(crate) const HEIGHT: u16 = 2;
/// A dialog button; the `default` one is the one Enter presses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Button<'a> {
pub label: &'a str,
pub default: bool,
}
/// How a button is drawn besides its own flags.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Look {
pub focused: bool,
pub pressed: bool,
impl Button<'_> {
/// Columns, the shadow included: 10, or the label and 4 when that is more.
#[must_use]
pub fn width(&self) -> u16 {
let label = u16::try_from(plain(self.label).chars().count() + 4).unwrap_or(u16::MAX);
label.max(MIN_WIDTH)
/// The part of the button in `area` a click presses: the face row without its blank first
/// column and its shadow column, as in Turbo Vision.
pub fn face(area: Rect) -> Rect {
Rect::new(
area.x.saturating_add(1),
area.y,
area.width.saturating_sub(2),
1,
)
/// The face style and the style of the hotkey letter.
fn faces(&self, theme: &Theme, focused: bool) -> (Style, Style) {
let role = match (focused, self.default) {
(true, _) => Role::ButtonFocus,
(false, true) => Role::ButtonDefault,
(false, false) => Role::Button,
};
let face = theme.style(role);
let hot = match theme.style(Role::ButtonHotkey).fg {
Some(fg) => face.fg(fg),
None => face,
(face, hot)
/// Draws the button into `area`, `HEIGHT` rows; the pressed one has no shadow and its face
/// and label sit a column to the right.
pub(crate) fn render(&self, area: Rect, buf: &mut Buffer, theme: &Theme, look: Look) {
if area.width < 3 || area.height < HEIGHT {
return;
let (face, hot) = self.faces(theme, look.focused);
let shadow = theme.style(Role::ButtonShadow);
let last = area.width - 1;
let first = if look.pressed { 2 } else { 1 };
let mut put = |x: u16, y: u16, symbol: &str, style: Style| {
if let Some(cell) = buf.cell_mut((area.x + x, area.y + y)) {
cell.set_symbol(symbol);
cell.set_style(style);
for x in 0..area.width {
let on_face = x >= first && (look.pressed || x < last);
put(x, 0, " ", if on_face { face } else { shadow });
let lower = if look.pressed || x < 2 {
" "
} else {
"\u{2580}"
put(x, 1, lower, shadow);
if !look.pressed {
put(last, 0, "\u{2584}", shadow);
let text = plain(self.label);
let pad = usize::from(last).saturating_sub(text.chars().count() + 1) / 2;
let mut x = first + u16::try_from(pad.max(1)).unwrap_or(0);
let end = if look.pressed { area.width } else { last };
for span in spans(self.label, face, hot) {
for symbol in span.content.chars() {
if x < end {
put(x, 0, symbol.encode_utf8(&mut [0; 4]), span.style);
x += 1;
#[cfg(test)]
mod tests;