use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Span;
use ratatui::widgets::{Block, BorderType, Borders, Clear, Widget};
use crate::gradient::{lerp_rgb, rgb_color};
use crate::theme::Theme;
pub const WIDTH: u16 = 46;
pub const MIN_WIDTH: u16 = 42;
const INSET: u16 = 3;
const GRID_INDENT: u16 = 2;
pub const PACKAGE_GLYPH: char = '\u{eb29}';
pub const ERROR_GLYPH: char = '\u{ea87}';
pub const READY_GLYPH: char = '\u{ebb3}';
pub const NOTES_GLYPH: char = '\u{eaa4}';
pub const LOG_GLYPH: char = '\u{eb9d}';
const CAP_L: &str = "\u{e0b6}";
const CAP_R: &str = "\u{e0b4}";
pub const HALF_CAP_L: &str = "\u{2590}";
pub const HALF_CAP_R: &str = "\u{258c}";
pub struct Card<A> {
pub glyph: char,
pub glyph_color: Color,
pub title: String,
pub rows: Vec<(&'static str, String)>,
pub message: Option<String>,
pub buttons: Vec<(String, A)>,
pub link: Option<(char, String, A)>,
}
struct Palette {
bg: Color,
title: Color,
label: Color,
value: Color,
divider: Color,
secondary: Color,
secondary_hover: Color,
secondary_fg: Color,
primary: Color,
primary_hover: Color,
primary_fg: Color,
link: Color,
}
impl Palette {
fn of(theme: Theme) -> Self {
let primary = theme.button();
if let Some(t) = crate::theme::tones(theme) {
let secondary = t.keycap_on(t.raised());
return Palette {
bg: t.raised(),
title: t.strong(),
label: t.muted(),
value: t.text(),
divider: t.rim(),
secondary,
secondary_hover: lift(secondary, theme),
secondary_fg: t.text(),
primary,
primary_hover: lift(primary, theme),
primary_fg: t.strong(),
link: t.accent(),
};
}
Palette {
bg: theme.ui(Color::Rgb(0x16, 0x18, 0x1f)),
title: theme.ui(Color::White),
label: match theme.surfaces() {
Some(s) => s.muted(),
None => theme.ui(Color::Rgb(0x8e, 0x95, 0xa4)),
},
value: theme.ui(Color::Rgb(0xcc, 0xcc, 0xcc)),
divider: theme.ui(Color::Rgb(0x3b, 0x42, 0x52)),
secondary: theme.ui(Color::Rgb(0x3a, 0x40, 0x52)),
secondary_hover: theme.ui(Color::Rgb(0x4a, 0x51, 0x66)),
secondary_fg: theme.ui(Color::Rgb(0xe5, 0xe9, 0xf0)),
primary,
primary_hover: lift(primary, theme),
primary_fg: Color::White,
link: theme.accent(),
}
}
}
fn lift(c: Color, theme: Theme) -> Color {
let Color::Rgb(r, g, b) = c else {
return c;
};
let toward = if theme.is_light() {
(0x00, 0x00, 0x00)
} else {
(0xff, 0xff, 0xff)
};
rgb_color(lerp_rgb((r, g, b), toward, 0.18))
}
pub fn pill_spans(label: &str, fill: Color, fg: Color) -> [Span<'static>; 3] {
[
Span::styled(CAP_L, Style::default().fg(fill)),
Span::styled(
format!(" {label} "),
Style::default()
.fg(fg)
.bg(fill)
.add_modifier(Modifier::BOLD),
),
Span::styled(CAP_R, Style::default().fg(fill)),
]
}
fn card_pill_spans(theme: Theme, label: &str, fill: Color, fg: Color) -> [Span<'static>; 3] {
if crate::theme::tones(theme).is_none() {
return pill_spans(label, fill, fg);
}
[
Span::styled(HALF_CAP_L, Style::default().fg(fill)),
Span::styled(format!(" {label} "), Style::default().fg(fg).bg(fill)),
Span::styled(HALF_CAP_R, Style::default().fg(fill)),
]
}
pub fn pill_fill(theme: Theme, hovered: bool) -> Color {
let fill = theme.button();
if hovered { lift(fill, theme) } else { fill }
}
fn wrap(text: &str, width: usize) -> Vec<String> {
let mut lines = Vec::new();
let mut line = String::new();
for word in text.split_whitespace() {
let len = line.chars().count();
if len > 0 && len + 1 + word.chars().count() > width {
lines.push(std::mem::take(&mut line));
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
if !line.is_empty() {
lines.push(line);
}
lines
}
fn pill_width(label: &str) -> u16 {
label.chars().count() as u16 + 4
}
impl<A: Copy> Card<A> {
fn message_lines(&self, width: u16) -> Vec<String> {
let room = width.saturating_sub(2 * INSET) as usize;
self.message
.as_deref()
.map(|m| wrap(m, room))
.unwrap_or_default()
}
pub fn height(&self, width: u16) -> u16 {
let grid = self.rows.len() as u16;
let message = self.message_lines(width).len() as u16;
let between = u16::from(grid > 0 && message > 0);
let footer = if self.link.is_some() { 2 } else { 0 };
1 + 2 + grid + between + message + 2 + footer + 1
}
pub fn render(
&self,
buf: &mut Buffer,
rect: Rect,
theme: Theme,
pointer: Option<(u16, u16)>,
) -> Vec<(Rect, A)> {
let rect = rect.intersection(buf.area);
if rect.width < 2 * INSET + 2 || rect.height < self.height(rect.width) {
return Vec::new();
}
let p = Palette::of(theme);
Clear.render(rect, buf);
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(theme.accent()))
.style(Style::default().bg(p.bg))
.render(rect, buf);
if theme.framed_overlays() {
crate::widgets::surface::paint_overlay_frame(buf, rect, theme);
}
let x = rect.x + INSET;
let w = rect.width - 2 * INSET;
let right = x + w;
let mut y = rect.y + 1;
let mut hits = Vec::new();
buf.set_stringn(
x,
y,
self.glyph.to_string(),
1,
Style::default().fg(self.glyph_color),
);
buf.set_stringn(
x + 2,
y,
&self.title,
w.saturating_sub(2) as usize,
Style::default().fg(p.title).add_modifier(Modifier::BOLD),
);
y += 2;
let label_w = self
.rows
.iter()
.map(|(l, _)| l.chars().count() as u16 + 1)
.max()
.unwrap_or(0);
for (label, value) in &self.rows {
let text = format!("{label}:");
let lx = x + GRID_INDENT + label_w - text.chars().count() as u16;
buf.set_stringn(lx, y, &text, w as usize, Style::default().fg(p.label));
let vx = x + GRID_INDENT + label_w + 2;
if vx < right {
buf.set_stringn(
vx,
y,
value,
(right - vx) as usize,
Style::default().fg(p.value),
);
}
y += 1;
}
let message = self.message_lines(rect.width);
if !self.rows.is_empty() && !message.is_empty() {
y += 1;
}
for line in &message {
buf.set_stringn(x, y, line, w as usize, Style::default().fg(p.value));
y += 1;
}
y += 1;
let mut bx = x;
let last = self.buttons.len().saturating_sub(1);
for (i, (label, action)) in self.buttons.iter().enumerate() {
let pw = pill_width(label);
let primary = i == last;
if primary {
bx = bx.max(right.saturating_sub(pw));
}
if bx + pw > right {
break;
}
let hit = Rect::new(bx, y, pw, 1);
let hovered = crate::widgets::hover::contains(hit, pointer);
let (fill, fg) = match (primary, hovered) {
(true, false) => (p.primary, p.primary_fg),
(true, true) => (p.primary_hover, p.primary_fg),
(false, false) => (p.secondary, p.secondary_fg),
(false, true) => (p.secondary_hover, p.secondary_fg),
};
let mut cx = bx;
for span in card_pill_spans(theme, label, fill, fg) {
let (end, _) = buf.set_span(cx, y, &span, pw);
cx = end;
}
hits.push((hit, *action));
bx += pw + 1;
}
y += 1;
if let Some((glyph, label, action)) = &self.link {
let surfaces = crate::theme::tones(theme).is_some();
let span = if surfaces {
rect.x..rect.right()
} else {
rect.x + 1..rect.right() - 1
};
for dx in span {
buf[(dx, y)].set_symbol("\u{2500}").set_fg(p.divider);
}
for (sx, tee) in [(rect.x, "\u{251c}"), (rect.right() - 1, "\u{2524}")] {
let cell = &mut buf[(sx, y)];
if cell.symbol() == "\u{2502}" {
cell.set_symbol(tee);
}
}
y += 1;
let hit = Rect::new(rect.x + 1, y, rect.width - 2, 1);
let hovered = crate::widgets::hover::contains(hit, pointer);
let glyph_fg = if surfaces && !hovered {
p.label
} else {
p.link
};
buf.set_stringn(x, y, glyph.to_string(), 1, Style::default().fg(glyph_fg));
let style = if hovered {
Style::default()
.fg(p.link)
.add_modifier(Modifier::UNDERLINED)
} else {
Style::default().fg(p.value)
};
buf.set_stringn(x + 2, y, label, w.saturating_sub(4) as usize, style);
buf.set_stringn(
right - 1,
y,
"\u{2197}",
1,
Style::default().fg(if hovered { p.link } else { p.label }),
);
hits.push((hit, *action));
}
hits
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Act {
Skip,
Later,
Update,
Notes,
}
fn card() -> Card<Act> {
Card {
glyph: PACKAGE_GLYPH,
glyph_color: Color::Cyan,
title: String::from("Update Available"),
rows: vec![
("Version", String::from("v0.2.90")),
("Installed", String::from("v0.2.84")),
("Released", String::from("Mar 3, 2026")),
],
message: None,
buttons: vec![
(String::from("Skip"), Act::Skip),
(String::from("Later"), Act::Later),
(String::from("Update"), Act::Update),
],
link: Some((
NOTES_GLYPH,
String::from("What's New in v0.2.90"),
Act::Notes,
)),
}
}
fn row(buf: &Buffer, y: u16) -> String {
(buf.area.x..buf.area.right())
.map(|x| buf[(x, y)].symbol())
.collect()
}
#[test]
fn the_card_lays_out_title_grid_buttons_and_link() {
let c = card();
let h = c.height(WIDTH);
assert_eq!(h, 1 + 2 + 3 + 2 + 2 + 1);
let area = Rect::new(0, 0, WIDTH, h);
let mut buf = Buffer::empty(area);
let hits = c.render(&mut buf, area, Theme::DARK_BLUE, None);
assert!(row(&buf, 1).contains("Update Available"));
let version = row(&buf, 3);
let released = row(&buf, 5);
assert_eq!(version.find("v0.2.90"), released.find("Mar 3, 2026"));
assert_eq!(version.find(':'), released.find(':'));
let acts: Vec<Act> = hits.iter().map(|(_, a)| *a).collect();
assert_eq!(acts, [Act::Skip, Act::Later, Act::Update, Act::Notes]);
let update = hits[2].0;
assert_eq!(update.right(), WIDTH - INSET, "the primary is flush right");
assert!(hits[1].0.right() < update.x);
assert_eq!(buf[(update.x, update.y)].symbol(), CAP_L);
assert_eq!(buf[(update.x + 2, update.y)].symbol(), "U");
assert_eq!(buf[(update.x + 2, update.y)].bg, Theme::DARK_BLUE.button());
assert_eq!(buf[(0, h - 3)].symbol(), "\u{251c}");
assert_eq!(buf[(WIDTH - 1, h - 3)].symbol(), "\u{2524}");
assert!(row(&buf, h - 2).contains("What's New in v0.2.90"));
assert_eq!(hits[3].0, Rect::new(1, h - 2, WIDTH - 2, 1));
}
#[test]
fn the_pointer_lifts_the_control_it_rests_on() {
let c = card();
let area = Rect::new(0, 0, WIDTH, c.height(WIDTH));
let mut buf = Buffer::empty(area);
let hits = c.render(&mut buf, area, Theme::BLACK, None);
let later = hits[1].0;
let idle = buf[(later.x + 2, later.y)].bg;
let mut buf = Buffer::empty(area);
c.render(&mut buf, area, Theme::BLACK, Some((later.x + 3, later.y)));
assert_ne!(buf[(later.x + 2, later.y)].bg, idle, "Later lifts");
let notes = hits[3].0;
assert!(
!buf[(notes.x + 4, notes.y)]
.modifier
.contains(Modifier::UNDERLINED)
);
let mut buf = Buffer::empty(area);
c.render(&mut buf, area, Theme::BLACK, Some((notes.x + 20, notes.y)));
assert!(
buf[(notes.x + 4, notes.y)]
.modifier
.contains(Modifier::UNDERLINED),
"the link underlines"
);
}
#[test]
fn a_message_wraps_to_the_card_and_grows_it() {
let mut c = card();
c.rows.truncate(1);
c.message = Some(String::from(
"Not installed: cargo was not found, and this install has no release binary to fetch.",
));
let lines = c.message_lines(WIDTH);
assert!(lines.len() > 1, "{lines:?}");
assert!(
lines
.iter()
.all(|l| l.chars().count() <= (WIDTH - 2 * INSET) as usize)
);
assert_eq!(
c.height(WIDTH),
1 + 2 + 1 + 1 + lines.len() as u16 + 2 + 2 + 1
);
let area = Rect::new(0, 0, WIDTH, c.height(WIDTH));
let mut buf = Buffer::empty(area);
c.render(&mut buf, area, Theme::BLACK, None);
let text: String = (0..buf.area.height).map(|y| row(&buf, y)).collect();
for line in &lines {
assert!(text.contains(line.as_str()), "{line:?} in {text}");
}
}
#[test]
fn a_narrow_card_keeps_every_control_inside_its_border() {
let mut c = card();
c.buttons[2].0 = String::from("Copy Command");
let w = MIN_WIDTH;
let area = Rect::new(0, 0, w, c.height(w));
let mut buf = Buffer::empty(area);
let hits = c.render(&mut buf, area, Theme::DARK_BLUE, None);
for (r, _) in &hits {
assert!(r.right() < w, "{r:?} stays inside the border");
}
assert!(hits.iter().any(|(_, a)| *a == Act::Update));
}
#[test]
fn a_rect_too_short_for_the_card_paints_nothing() {
let c = card();
let area = Rect::new(0, 0, WIDTH, c.height(WIDTH) - 1);
let mut buf = Buffer::empty(area);
assert!(c.render(&mut buf, area, Theme::BLACK, None).is_empty());
assert_eq!(buf, Buffer::empty(area));
}
#[test]
fn wrap_breaks_between_words() {
assert_eq!(wrap("one two three", 7), ["one two", "three"]);
assert_eq!(wrap(" ", 7), Vec::<String>::new());
assert_eq!(wrap("unbreakable", 4), ["unbreakable"]);
}
#[test]
fn croft_loch_pills_use_half_block_caps_and_the_divider_spans_the_card() {
let theme = Theme::from_id("loch");
let t = crate::theme::tones(theme).unwrap();
let c = card();
let h = c.height(WIDTH);
let area = Rect::new(0, 0, WIDTH, h);
let mut buf = Buffer::empty(area);
let hits = c.render(&mut buf, area, theme, None);
let update = hits[2].0;
assert_eq!(update.right(), WIDTH - INSET, "the primary is flush right");
assert_eq!(buf[(update.x, update.y)].symbol(), HALF_CAP_L);
assert_eq!(buf[(update.right() - 1, update.y)].symbol(), HALF_CAP_R);
assert_eq!(buf[(update.x, update.y)].fg, theme.button());
assert!(
!buf[(update.x + 2, update.y)]
.modifier
.contains(Modifier::BOLD)
);
let skip = hits[0].0;
assert_eq!(buf[(skip.x + 2, skip.y)].bg, t.keycap_on(t.raised()));
for x in 0..WIDTH {
assert_eq!(buf[(x, h - 3)].symbol(), "\u{2500}", "({x}) on the rule");
assert_eq!(buf[(x, h - 3)].fg, t.rim());
}
assert_eq!(buf[(INSET, h - 2)].fg, t.muted(), "the link glyph rests");
assert_eq!(buf[(INSET + 2, 1)].fg, t.strong(), "the title");
}
}