use ratatui::{
buffer::{Buffer, Cell},
layout::Rect,
style::{Color, Modifier, Style},
symbols::border,
text::Span,
widgets::{Block, Borders},
};
use crate::gradient::{GRAD_TL, GRAD_TR, lerp_rgb, rgb_color};
use crate::theme::Theme;
use crate::theme::{Tones, tones};
pub const ROW_BAR: &str = "\u{258e}";
pub const MATCH_AMBER: (u8, u8, u8) = (0xe0, 0xb0, 0x4a);
const MATCH_SOFT: f32 = 0.30;
const MATCH_ACTIVE: f32 = 0.50;
const MATCH_MIN_CONTRAST: f64 = 4.5;
const MATCH_EASE_STEP: f32 = 0.05;
pub fn match_style(style: Style, t: Tones, theme: Theme, active: bool) -> Style {
use crate::theme::contrast_ratio;
let base = cell_rgb(style.bg.unwrap_or(Color::Reset), theme, t.canvas);
let own = style.fg.map(|c| cell_rgb(c, theme, t.text));
let mut mix = if active { MATCH_ACTIVE } else { MATCH_SOFT };
loop {
let fill = lerp_rgb(base, MATCH_AMBER, mix);
if let Some(fg) = own
&& contrast_ratio(fg, fill) >= MATCH_MIN_CONTRAST
{
return style.bg(rgb_color(fill)).fg(rgb_color(fg));
}
if mix <= 0.0 || contrast_ratio(t.strong, fill) >= MATCH_MIN_CONTRAST {
return style.bg(rgb_color(fill)).fg(t.strong());
}
mix -= MATCH_EASE_STEP;
}
}
const LEGIBLE_STEPS: u8 = 10;
pub fn legible_ink(fg: (u8, u8, u8), bg: (u8, u8, u8), t: Tones) -> (u8, u8, u8) {
use crate::theme::contrast_ratio;
let mut ink = fg;
for step in 1..=LEGIBLE_STEPS {
if contrast_ratio(ink, bg) >= MATCH_MIN_CONTRAST {
break;
}
ink = lerp_rgb(fg, t.strong, f32::from(step) / f32::from(LEGIBLE_STEPS));
}
ink
}
pub fn paint_selected_row(
buf: &mut Buffer,
row: Rect,
t: Tones,
base: (u8, u8, u8),
focused: bool,
) {
let row = row.intersection(buf.area);
if row.width == 0 || row.height == 0 {
return;
}
let band = rgb_color(selected_row_fill(t, base, focused));
buf.set_style(row, Style::default().bg(band));
if focused {
for y in row.top()..row.bottom() {
let cell = &mut buf[(row.x, y)];
cell.set_symbol(ROW_BAR);
cell.set_fg(t.accent());
cell.set_bg(band);
}
}
}
pub fn selected_row_fill(t: Tones, base: (u8, u8, u8), focused: bool) -> (u8, u8, u8) {
if focused {
lerp_rgb(base, t.accent, 0.24)
} else {
lerp_rgb(base, t.lift, 0.07)
}
}
pub fn keycap_spans(hint: &str, t: Tones, row: Color, selected: bool) -> Vec<Span<'static>> {
let cap = Style::default()
.bg(t.keycap_on(row))
.fg(if selected { t.text() } else { t.muted() });
let sep = Style::default().fg(t.muted()).bg(row);
let mut out = Vec::new();
for (i, chord) in hint.split(' ').filter(|c| !c.is_empty()).enumerate() {
if i > 0 {
out.push(Span::styled(" ", sep));
}
for (j, key) in chord_keys(chord).into_iter().enumerate() {
if j > 0 {
out.push(Span::styled("+", sep));
}
out.push(Span::styled(format!(" {key} "), cap));
}
}
out
}
fn chord_key_iter(chord: &str) -> impl Iterator<Item = &str> {
let mut rest = chord;
std::iter::from_fn(move || {
let first = rest.chars().next()?;
let skip = first.len_utf8();
match rest[skip..].find('+') {
Some(k) => {
let key = &rest[..skip + k];
rest = &rest[skip + k + 1..];
Some(key)
}
None => {
let key = rest;
rest = "";
Some(key)
}
}
})
}
pub fn chord_keys(chord: &str) -> Vec<&str> {
chord_key_iter(chord).collect()
}
pub fn keycap_width(hint: &str) -> u16 {
let mut width = 0usize;
for (i, chord) in hint.split(' ').filter(|c| !c.is_empty()).enumerate() {
if i > 0 {
width += 1;
}
for (j, key) in chord_key_iter(chord).enumerate() {
if j > 0 {
width += 1;
}
width += unicode_width::UnicodeWidthStr::width(key) + 2;
}
}
width as u16
}
pub fn paint_keycaps(
buf: &mut Buffer,
x: u16,
y: u16,
hint: &str,
t: Tones,
row: Color,
selected: bool,
) {
if y < buf.area.top() || y >= buf.area.bottom() {
return;
}
let cap = Style::default()
.bg(t.keycap_on(row))
.fg(if selected { t.text() } else { t.muted() });
let sep = Style::default().fg(t.muted()).bg(row);
let right = buf.area.right();
let mut cx = x;
let mut put = |s: &str, style: Style| {
if cx < right {
let (nx, _) = buf.set_stringn(cx, y, s, usize::from(right - cx), style);
cx = nx;
}
};
for (i, chord) in hint.split(' ').filter(|c| !c.is_empty()).enumerate() {
if i > 0 {
put(" ", sep);
}
for (j, key) in chord_key_iter(chord).enumerate() {
if j > 0 {
put("+", sep);
}
put(" ", cap);
put(key, cap);
put(" ", cap);
}
}
}
fn cell_rgb(c: Color, theme: Theme, fallback: (u8, u8, u8)) -> (u8, u8, u8) {
known_rgb(c, theme).unwrap_or(fallback)
}
fn known_rgb(c: Color, theme: Theme) -> Option<(u8, u8, u8)> {
let ansi = theme.ansi();
Some(match c {
Color::Rgb(r, g, b) => (r, g, b),
Color::Black => ansi[0],
Color::Red => ansi[1],
Color::Green => ansi[2],
Color::Yellow => ansi[3],
Color::Blue => ansi[4],
Color::Magenta => ansi[5],
Color::Cyan => ansi[6],
Color::Gray => ansi[7],
Color::DarkGray => ansi[8],
Color::LightRed => ansi[9],
Color::LightGreen => ansi[10],
Color::LightYellow => ansi[11],
Color::LightBlue => ansi[12],
Color::LightMagenta => ansi[13],
Color::LightCyan => ansi[14],
Color::White => ansi[15],
Color::Indexed(i) if i < 16 => ansi[usize::from(i)],
_ => return None,
})
}
pub fn dim_backdrop(buf: &mut Buffer, keep: Rect, theme: Theme) {
let Some(t) = tones(theme) else {
return;
};
let area = buf.area;
let sink = if theme.is_light() { 0.0 } else { 0.30 };
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
if keep.contains(ratatui::layout::Position { x, y }) {
continue;
}
let cell = &mut buf[(x, y)];
let bg = cell_rgb(cell.bg, theme, t.canvas);
let fg = cell_rgb(cell.fg, theme, t.text);
let bg2 = lerp_rgb(bg, (0, 0, 0), sink);
cell.set_fg(rgb_color(lerp_rgb(fg, bg2, 0.58)));
if let Some(under) = known_rgb(cell.underline_color, theme) {
cell.underline_color = rgb_color(lerp_rgb(under, bg2, 0.58));
}
cell.set_bg(rgb_color(bg2));
cell.modifier.remove(Modifier::BOLD);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Edge {
Top,
Bottom,
Left,
Right,
}
impl Edge {
fn glyph(self) -> &'static str {
match self {
Edge::Top => "\u{2594}",
Edge::Bottom => "\u{2581}",
Edge::Left => "\u{258f}",
Edge::Right => "\u{2595}",
}
}
}
pub const HAIRLINE: border::Set = border::Set {
top_left: "\u{2594}",
top_right: "\u{2594}",
bottom_left: "\u{2581}",
bottom_right: "\u{2581}",
vertical_left: "\u{258f}",
vertical_right: "\u{2595}",
horizontal_top: "\u{2594}",
horizontal_bottom: "\u{2581}",
};
pub fn section_block<'a>(theme: Theme, borders: Borders, style: Style) -> Block<'a> {
match theme.surfaces() {
Some(s) => Block::default()
.borders(borders)
.border_set(HAIRLINE)
.border_style(Style::default().fg(s.hairline())),
None => Block::default().borders(borders).border_style(style),
}
}
pub const CHEVRON_FOLDED: char = '\u{eab6}';
pub const CHEVRON_UNFOLDED: char = '\u{eab4}';
pub fn chevron(theme: Theme, open: bool) -> char {
match (theme.surfaces().is_some(), open) {
(true, true) => CHEVRON_UNFOLDED,
(true, false) => CHEVRON_FOLDED,
(false, true) => crate::icons::CHEVRON_OPEN,
(false, false) => crate::icons::CHEVRON_CLOSED,
}
}
const SECTION_DIM: Color = Color::Rgb(0x60, 0x68, 0x78);
const SECTION_LABEL: Color = Color::Rgb(0xE8, 0xEE, 0xF8);
pub fn paint_section_header(
buf: &mut Buffer,
row: Rect,
theme: Theme,
open: bool,
label: &str,
tail: Vec<Span<'static>>,
hovered: bool,
) {
use ratatui::text::Line;
use ratatui::widgets::{Paragraph, Widget};
let row = row.intersection(buf.area);
if row.width == 0 || row.height == 0 {
return;
}
let chev = chevron(theme, open);
let Some(t) = tones(theme) else {
let mut spans = vec![
Span::styled(
format!("{chev} "),
Style::default().fg(theme.ui(SECTION_DIM)),
),
Span::styled(
label.to_string(),
Style::default()
.fg(theme.ui(SECTION_LABEL))
.add_modifier(Modifier::BOLD),
),
];
spans.extend(tail);
Paragraph::new(Line::from(spans)).render(row, buf);
return;
};
if hovered {
let lift = Rect {
width: row.width.saturating_sub(1).max(1),
..row
};
buf.set_style(lift, Style::default().bg(t.hover_on(t.chrome)));
}
let label_fg = if hovered {
t.strong()
} else if open {
t.text()
} else {
t.muted()
};
let mut spans = vec![
Span::styled(
format!("{chev} "),
Style::default().fg(if hovered { t.text() } else { t.muted() }),
),
Span::styled(
label.to_string(),
Style::default().fg(label_fg).add_modifier(Modifier::BOLD),
),
];
spans.extend(tail);
buf.set_line(row.x, row.y, &Line::from(spans), row.width);
}
pub fn paint_field(buf: &mut Buffer, rect: Rect, t: Tones, edge: Color) {
if rect.width < 2 || rect.height < 2 || rect.intersection(buf.area) != rect {
return;
}
let inner = Rect::new(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
buf.set_style(inner, Style::default().bg(t.raised()));
let (right, bottom) = (rect.right() - 1, rect.bottom() - 1);
for x in rect.x..=right {
let corner = x == rect.x || x == right;
for (y, glyph) in [(rect.y, "\u{2581}"), (bottom, "\u{2594}")] {
let cell = &mut buf[(x, y)];
cell.set_symbol(if corner { " " } else { glyph });
cell.set_fg(edge);
}
}
for y in inner.top()..inner.bottom() {
for (x, glyph) in [(rect.x, "\u{2595}"), (right, "\u{258f}")] {
let cell = &mut buf[(x, y)];
cell.set_symbol(glyph);
cell.set_fg(edge);
}
}
}
pub fn paint_soft_button(
buf: &mut Buffer,
area: Rect,
fill: Color,
round_left: bool,
round_right: bool,
) -> Rect {
let area = area.intersection(buf.area);
if area.width == 0 || area.height == 0 {
return Rect::default();
}
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
buf[(x, y)].set_symbol(" ");
}
}
let (left, right) = (u16::from(round_left), u16::from(round_right));
let (left, right) = if area.width > left + right {
(left, right)
} else {
(0, 0)
};
let y = area.y + area.height / 2;
let face = Rect::new(area.x + left, y, area.width - left - right, 1);
buf.set_style(face, Style::default().bg(fill));
if left > 0 {
buf[(area.x, y)].set_symbol("\u{2590}").set_fg(fill);
}
if right > 0 {
buf[(area.right() - 1, y)]
.set_symbol("\u{258c}")
.set_fg(fill);
}
face
}
pub fn pane_block<'a>(fill: Color) -> Block<'a> {
Block::default()
.borders(Borders::ALL)
.border_set(border::EMPTY)
.style(Style::default().bg(fill))
}
pub fn pane_fill(theme: Theme, chrome: bool) -> Color {
match theme.surfaces() {
Some(s) if chrome => s.chrome(),
_ => theme.editor_bg(),
}
}
pub fn view_block<'a>(theme: Theme, chrome: bool, border_style: Style) -> Block<'a> {
match theme.surfaces() {
Some(_) => pane_block(pane_fill(theme, chrome)),
None => Block::default()
.borders(Borders::ALL)
.border_style(border_style),
}
}
pub fn paint_view_focus(
buf: &mut Buffer,
area: Rect,
theme: Theme,
focused: bool,
focus_gradient: bool,
) -> bool {
if !focused {
return false;
}
if theme.surfaces().is_some() {
paint_focus_rule(buf, area, theme);
false
} else if focus_gradient {
crate::gradient::paint_gradient_box(buf, area);
true
} else {
false
}
}
fn is_frame_cell(cell: &Cell) -> bool {
matches!(
cell.symbol(),
" " | "\u{2500}"
| "\u{2502}"
| "\u{250c}"
| "\u{2510}"
| "\u{2514}"
| "\u{2518}"
| "\u{256d}"
| "\u{256e}"
| "\u{2570}"
| "\u{256f}"
| "\u{2581}"
| "\u{2594}"
| "\u{258f}"
| "\u{2595}"
)
}
fn paint_edge_row(
buf: &mut Buffer,
x: u16,
y: u16,
width: u16,
glyph: &str,
color: impl Fn(u16) -> Color,
) {
let frame_at = |buf: &Buffer, i: u16| i < width && is_frame_cell(&buf[(x + i, y)]);
let mut left = false;
let mut here = frame_at(buf, 0);
for i in 0..width {
let right = frame_at(buf, i + 1);
let word_gap = i > 0 && i + 1 < width && !left && !right && buf[(x + i, y)].symbol() == " ";
if here && !word_gap {
let cell = &mut buf[(x + i, y)];
cell.set_symbol(glyph);
cell.set_fg(color(i));
}
left = here;
here = right;
}
}
pub fn paint_glyph(buf: &mut Buffer, x: u16, y: u16, glyph: char, style: Style) {
if let Some(cell) = buf.cell_mut((x, y)) {
cell.set_style(style);
cell.set_char(glyph);
}
}
pub fn paint_seam(buf: &mut Buffer, rect: Rect, edge: Edge, color: Color) {
let rect = rect.intersection(buf.area);
for y in rect.top()..rect.bottom() {
paint_edge_row(buf, rect.x, y, rect.width, edge.glyph(), |_| color);
}
}
#[allow(dead_code)]
fn rule_color(theme: Theme, i: u16, n: u16) -> Color {
if theme.gradient() {
let t = if n > 1 {
f32::from(i) / f32::from(n - 1)
} else {
0.0
};
rgb_color(lerp_rgb(GRAD_TL, GRAD_TR, t))
} else {
theme.accent()
}
}
fn lip_color(accent: (u8, u8, u8), rest: (u8, u8, u8), i: u16, n: u16) -> Color {
let span = (f32::from(n) * 0.4).max(6.0);
let t = (f32::from(i) / span).clamp(0.0, 1.0);
let eased = t * t * (3.0 - 2.0 * t);
rgb_color(lerp_rgb(accent, rest, eased))
}
pub fn paint_focus_rule(buf: &mut Buffer, area: Rect, theme: Theme) {
let area = area.intersection(buf.area);
if area.height < 2 {
return;
}
let Some(t) = tones(theme) else {
paint_edge_row(buf, area.x, area.y, area.width, Edge::Top.glyph(), |i| {
rule_color(theme, i, area.width)
});
return;
};
paint_edge_row(buf, area.x, area.y, area.width, Edge::Top.glyph(), |i| {
lip_color(t.accent, t.hairline, i, area.width)
});
}
pub fn paint_pane_top(buf: &mut Buffer, area: Rect, theme: Theme, focused: bool) {
let Some(t) = tones(theme) else {
return;
};
let area = area.intersection(buf.area);
if area.height < 2 {
return;
}
if focused {
paint_focus_rule(buf, area, theme);
} else {
paint_edge_row(buf, area.x, area.y, area.width, Edge::Top.glyph(), |_| {
t.hairline()
});
}
}
fn shade(c: Color, theme: Theme) -> Color {
let (r, g, b) = match c {
Color::Rgb(r, g, b) => (r, g, b),
_ => theme.editor_bg_rgb(),
};
rgb_color(lerp_rgb((r, g, b), (0, 0, 0), 0.55))
}
pub fn paint_overlay_frame(buf: &mut Buffer, rect: Rect, theme: Theme) {
let Some(t) = tones(theme) else {
crate::gradient::paint_gradient_box(buf, rect);
return;
};
paint_card_edge(buf, rect, theme, Some(t.accent), None);
}
pub fn paint_anchored_frame(
buf: &mut Buffer,
rect: Rect,
theme: Theme,
anchor_row: u16,
quiet: bool,
) {
let Some(t) = tones(theme) else {
crate::gradient::paint_gradient_box(buf, rect);
return;
};
let lip = (!quiet).then_some(t.accent);
paint_card_edge(buf, rect, theme, lip, Some(anchor_row));
}
pub fn paint_quiet_frame(buf: &mut Buffer, rect: Rect, theme: Theme) {
if tones(theme).is_none() {
crate::gradient::paint_gradient_box(buf, rect);
return;
}
paint_card_edge(buf, rect, theme, None, None);
}
pub fn paint_tinted_frame(buf: &mut Buffer, rect: Rect, theme: Theme, tint: (u8, u8, u8)) {
if tones(theme).is_none() {
crate::gradient::paint_gradient_box(buf, rect);
return;
}
paint_card_edge(buf, rect, theme, Some(tint), None);
}
fn paint_card_edge(
buf: &mut Buffer,
rect: Rect,
theme: Theme,
lip: Option<(u8, u8, u8)>,
spare_row: Option<u16>,
) {
let Some(t) = tones(theme) else {
return;
};
let area = buf.area;
if rect.width < 2 || rect.height < 2 || rect.intersection(area) != rect {
return;
}
let (right, bottom) = (rect.right() - 1, rect.bottom() - 1);
let unseen = |cell: &Cell| match cell.bg {
Color::Rgb(..) => cell.bg,
_ => t.raised(),
};
paint_edge_row(buf, rect.x, rect.y, rect.width, Edge::Top.glyph(), |_| {
t.raised()
});
paint_edge_row(
buf,
rect.x,
bottom,
rect.width,
Edge::Bottom.glyph(),
|_| t.raised(),
);
for x in rect.x..=right {
for (y, top) in [(rect.y, true), (bottom, false)] {
let cell = &mut buf[(x, y)];
let glyph = if top { Edge::Top } else { Edge::Bottom }.glyph();
if cell.symbol() != glyph {
continue;
}
let fg = match lip {
Some(a) if top => {
let rest = match unseen(cell) {
Color::Rgb(r, g, b) => (r, g, b),
_ => t.raised,
};
lip_color(a, rest, x - rect.x, rect.width)
}
_ => unseen(cell),
};
cell.set_fg(fg);
}
}
for y in rect.y + 1..bottom {
for (x, edge) in [(rect.x, Edge::Left), (right, Edge::Right)] {
let cell = &mut buf[(x, y)];
if is_frame_cell(cell) {
let fg = unseen(cell);
cell.set_symbol(edge.glyph());
cell.set_fg(fg);
}
}
}
let shadow = |cell: &mut Cell| {
let (fg, bg) = (shade(cell.fg, theme), shade(cell.bg, theme));
cell.set_fg(fg);
cell.set_bg(bg);
};
if rect.right() < area.right() {
for y in (rect.y + 1..=bottom).filter(|&y| Some(y) != spare_row) {
shadow(&mut buf[(rect.right(), y)]);
}
}
if rect.bottom() < area.bottom() && Some(rect.bottom()) != spare_row {
for x in rect.x + 1..=rect.right().min(area.right() - 1) {
shadow(&mut buf[(x, rect.bottom())]);
}
}
}
pub fn put_clipped(buf: &mut Buffer, x: u16, y: u16, right: u16, s: &str, style: Style) -> u16 {
if x >= right {
return x;
}
let budget = (right - x) as usize;
let clipped: String = s.chars().take(budget).collect();
let drawn = clipped.chars().count() as u16;
buf.set_string(x, y, &clipped, style);
x + drawn
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::widgets::Widget;
fn loch() -> Theme {
Theme::from_id("loch")
}
#[test]
fn a_pane_block_keeps_the_bordered_inset() {
let area = Rect::new(2, 1, 20, 8);
let boxed = Block::default().borders(Borders::ALL).inner(area);
assert_eq!(pane_block(Color::Black).inner(area), boxed);
}
#[test]
fn a_pane_block_paints_padding_in_its_fill() {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 4));
let fill = Color::Rgb(0x0e, 0x10, 0x11);
pane_block(fill).render(buf.area, &mut buf);
for y in 0..4 {
for x in 0..10 {
assert_eq!(buf[(x, y)].symbol(), " ", "({x},{y}) is padding");
assert_eq!(buf[(x, y)].bg, fill);
}
}
}
#[test]
fn the_focus_rule_eases_from_the_accent_into_the_hairline_and_spares_the_title() {
let mut buf = Buffer::empty(Rect::new(0, 0, 24, 3));
buf.set_string(1, 0, "EX", Style::default());
let area = buf.area;
paint_focus_rule(&mut buf, area, loch());
let t = tones(loch()).unwrap();
assert_eq!(buf[(0, 0)].symbol(), "\u{2594}");
assert_eq!(buf[(0, 0)].fg, t.accent(), "the lip starts at the accent");
assert_eq!(buf[(23, 0)].fg, t.hairline(), "and settles on the hairline");
assert_eq!(buf[(1, 0)].symbol(), "E", "the title keeps its cells");
assert_eq!(buf[(5, 1)].symbol(), " ", "only the top row is touched");
}
#[test]
fn an_unfocused_pane_top_is_the_hairline() {
let mut buf = Buffer::empty(Rect::new(0, 0, 10, 3));
let area = buf.area;
paint_pane_top(&mut buf, area, loch(), false);
let t = tones(loch()).unwrap();
for x in 0..10 {
assert_eq!(buf[(x, 0)].symbol(), "\u{2594}");
assert_eq!(buf[(x, 0)].fg, t.hairline());
}
let mut boxed = Buffer::empty(Rect::new(0, 0, 10, 3));
paint_pane_top(&mut boxed, area, Theme::BLACK, true);
assert_eq!(boxed, Buffer::empty(area), "a boxed theme draws nothing");
}
#[test]
fn a_legible_ink_lifts_only_as_far_as_it_must() {
use crate::theme::contrast_ratio;
let t = tones(loch()).unwrap();
let tint = (0x54, 0x1c, 0x19);
let keyword = (0xc3, 0xa6, 0xf2);
assert_eq!(legible_ink(keyword, tint, t), keyword, "already reads");
let comment = (0x6a, 0x7a, 0x78);
assert!(contrast_ratio(comment, tint) < 4.5);
let lifted = legible_ink(comment, tint, t);
assert!(contrast_ratio(lifted, tint) >= 4.5);
assert_ne!(lifted, t.strong, "keeps some of its hue");
assert_eq!(legible_ink(comment, (0xc0, 0xc0, 0xc0), t), t.strong);
}
#[test]
fn loch_tones_rank_text_above_muted_above_faint() {
let t = tones(loch()).unwrap();
let l = |c: (u8, u8, u8)| u32::from(c.0) + u32::from(c.1) + u32::from(c.2);
assert!(l(t.strong) > l(t.text));
assert!(l(t.text) > l(t.muted));
assert!(l(t.muted) > l(t.faint));
assert!(l(t.faint) > l(t.canvas));
assert!(
l(t.rim) > l(t.raised),
"the rim reads against the card body"
);
assert!(tones(Theme::BLACK).is_none());
}
#[test]
fn a_selected_row_is_a_band_with_the_accent_bar_only_while_focused() {
let t = tones(loch()).unwrap();
let mut buf = Buffer::empty(Rect::new(0, 0, 8, 2));
buf.set_string(1, 0, "ab", Style::default().fg(Color::Red));
paint_selected_row(&mut buf, Rect::new(0, 0, 8, 1), t, t.raised, true);
assert_eq!(buf[(0, 0)].symbol(), ROW_BAR);
assert_eq!(buf[(0, 0)].fg, t.accent());
assert_eq!(buf[(1, 0)].bg, t.band());
assert_eq!(buf[(1, 0)].fg, Color::Red, "text keeps its colour");
assert_eq!(buf[(0, 1)].symbol(), " ", "only the row is touched");
paint_selected_row(&mut buf, Rect::new(0, 1, 8, 1), t, t.raised, false);
assert_eq!(buf[(0, 1)].symbol(), " ", "no bar without focus");
assert_ne!(buf[(3, 1)].bg, t.band());
}
#[test]
fn keycaps_put_each_key_of_a_chord_in_a_chip() {
let t = tones(loch()).unwrap();
let spans = keycap_spans("Ctrl+K Z", t, t.raised(), false);
let text: Vec<&str> = spans.iter().map(|s| s.content.as_ref()).collect();
assert_eq!(text, [" Ctrl ", "+", " K ", " ", " Z "]);
assert_eq!(spans[0].style.bg, Some(t.keycap_on(t.raised())));
assert_eq!(spans[1].style.fg, Some(t.muted()));
assert_eq!(chord_keys("Ctrl++"), ["Ctrl", "+"]);
}
#[test]
fn paint_keycaps_matches_keycap_spans_without_allocating() {
let t = tones(loch()).unwrap();
let area = Rect::new(0, 0, 32, 1);
for hint in ["Ctrl+K Z", "Ctrl++", "Cmd+Shift+P", ""] {
let line = ratatui::text::Line::from(keycap_spans(hint, t, t.raised(), false));
assert_eq!(keycap_width(hint) as usize, line.width(), "{hint}");
let mut expected = Buffer::empty(area);
expected.set_line(0, 0, &line, area.width);
let mut actual = Buffer::empty(area);
let ((), made) = crate::alloc_count::allocations_in(|| {
let _ = keycap_width(hint);
paint_keycaps(&mut actual, 0, 0, hint, t, t.raised(), false);
});
assert_eq!(made, 0, "{hint} should paint without allocating");
assert_eq!(actual, expected, "{hint} cell-for-cell match");
}
}
#[test]
fn a_selected_rows_keycaps_read_as_chords_on_the_band() {
use crate::theme::contrast_ratio;
let t = tones(loch()).unwrap();
let rgb = |c: Option<Color>| match c {
Some(Color::Rgb(r, g, b)) => (r, g, b),
other => panic!("not an RGB colour: {other:?}"),
};
for (row, selected) in [(t.band(), true), (t.raised(), false)] {
let spans = keycap_spans("Ctrl+K Ctrl+L", t, row, selected);
let text: Vec<&str> = spans.iter().map(|s| s.content.as_ref()).collect();
assert_eq!(text, [" Ctrl ", "+", " K ", " ", " Ctrl ", "+", " L "]);
let plus = &spans[1].style;
assert_eq!(plus.fg, Some(t.muted()), "the `+` is muted");
assert_eq!(plus.bg, Some(row));
let ratio = contrast_ratio(rgb(plus.fg), rgb(plus.bg));
assert!(ratio >= 3.0, "`+` at {ratio:.2}:1 (selected {selected})");
if selected {
let cap = &spans[0].style;
assert_eq!(cap.fg, Some(t.text()), "the label in body ink");
let ratio = contrast_ratio(rgb(cap.fg), rgb(cap.bg));
assert!(ratio >= 4.5, "label at {ratio:.2}:1");
}
}
}
#[test]
fn the_backdrop_sinks_everything_but_the_card() {
let t = tones(loch()).unwrap();
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 3));
buf.set_style(buf.area, Style::default().fg(t.text()).bg(t.chrome()));
dim_backdrop(&mut buf, Rect::new(2, 1, 2, 1), loch());
assert_eq!(buf[(2, 1)].fg, t.text(), "the card keeps its contrast");
assert_ne!(buf[(0, 0)].fg, t.text());
assert_ne!(buf[(0, 0)].bg, t.chrome());
let mut boxed = Buffer::empty(Rect::new(0, 0, 6, 3));
let before = boxed.clone();
dim_backdrop(&mut boxed, Rect::new(2, 1, 2, 1), Theme::BLACK);
assert_eq!(boxed, before);
}
#[test]
fn the_backdrop_sinks_a_coloured_underline_with_the_text() {
let t = tones(loch()).unwrap();
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 3));
buf.set_style(
buf.area,
Style::default()
.fg(t.accent())
.bg(t.chrome())
.underline_color(t.accent())
.add_modifier(Modifier::UNDERLINED),
);
buf[(5, 2)].underline_color = Color::Reset;
buf[(4, 2)].underline_color = Color::Cyan;
dim_backdrop(&mut buf, Rect::new(2, 1, 2, 1), loch());
let outside = &buf[(0, 0)];
assert_ne!(outside.underline_color, t.accent(), "the teal recedes");
assert_eq!(
outside.underline_color, outside.fg,
"the underline sinks as far as the ink it shares"
);
assert_eq!(buf[(2, 1)].underline_color, t.accent(), "the card keeps it");
assert_eq!(buf[(5, 2)].underline_color, Color::Reset);
let cyan = rgb_color(lerp_rgb(
loch().ansi()[6],
cell_rgb(buf[(4, 2)].bg, loch(), t.canvas),
0.58,
));
assert_eq!(buf[(4, 2)].underline_color, cyan, "a palette colour sinks");
let mut boxed = Buffer::empty(Rect::new(0, 0, 6, 3));
boxed.set_style(
boxed.area,
Style::default().underline_color(Color::Rgb(0x4f, 0xb1, 0xa6)),
);
let before = boxed.clone();
dim_backdrop(&mut boxed, Rect::new(2, 1, 2, 1), Theme::BLACK);
assert_eq!(boxed, before);
}
#[test]
fn the_focus_rule_keeps_the_space_between_a_titles_words() {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 3));
buf.set_string(1, 0, " REMOTE EXPLORER ", Style::default());
let area = buf.area;
paint_focus_rule(&mut buf, area, loch());
assert_eq!(buf[(8, 0)].symbol(), " ", "the word gap stays a space");
assert_eq!(
buf[(1, 0)].symbol(),
"\u{2594}",
"the title's padding takes the rule"
);
assert_eq!(buf[(19, 0)].symbol(), "\u{2594}");
}
#[test]
fn a_seam_draws_over_padding_and_frame_lines_only() {
let mut buf = Buffer::empty(Rect::new(0, 0, 4, 3));
buf.set_string(3, 1, "x", Style::default());
buf.set_string(3, 2, "\u{2500}", Style::default());
let hair = Color::Rgb(0x23, 0x28, 0x2a);
paint_seam(&mut buf, Rect::new(3, 0, 1, 3), Edge::Right, hair);
assert_eq!(buf[(3, 0)].symbol(), "\u{2595}");
assert_eq!(buf[(3, 0)].fg, hair);
assert_eq!(buf[(3, 1)].symbol(), "x");
assert_eq!(buf[(3, 2)].symbol(), "\u{2595}");
}
#[test]
fn a_seam_along_a_row_keeps_the_space_between_words() {
let mut buf = Buffer::empty(Rect::new(0, 0, 20, 1));
buf.set_string(1, 0, " 2/5 \u{b7} old.py ", Style::default());
let hair = Color::Rgb(0x23, 0x28, 0x2a);
let area = buf.area;
paint_seam(&mut buf, area, Edge::Bottom, hair);
let row: String = (0..20).map(|x| buf[(x, 0)].symbol()).collect();
let seam = Edge::Bottom.glyph();
assert_eq!(
row,
format!("{seam}{seam}2/5 \u{b7} old.py{}", seam.repeat(6))
);
}
#[test]
fn an_overlay_on_a_surfaces_theme_is_a_card_with_a_shadow() {
let theme = loch();
let s = theme.surfaces().unwrap();
let mut buf = Buffer::empty(Rect::new(0, 0, 12, 6));
buf.set_style(buf.area, Style::default().bg(s.chrome()));
let card = Rect::new(1, 1, 8, 3);
Block::default()
.borders(Borders::ALL)
.title("Hi")
.render(card, &mut buf);
paint_overlay_frame(&mut buf, card, theme);
assert_eq!(buf[(1, 1)].symbol(), "\u{2594}", "top edge");
assert_eq!(buf[(2, 1)].symbol(), "H", "the title survives");
assert_eq!(buf[(1, 3)].symbol(), "\u{2581}", "bottom edge");
assert_eq!(buf[(1, 2)].symbol(), "\u{258f}", "left edge");
assert_eq!(buf[(8, 2)].symbol(), "\u{2595}", "right edge");
for (x, y) in [(1, 3), (1, 2), (8, 2), (8, 3)] {
assert_eq!(buf[(x, y)].fg, buf[(x, y)].bg, "({x}, {y}) is unseen");
}
let shaded = shade(s.chrome(), theme);
assert_eq!(buf[(9, 2)].bg, shaded);
assert_eq!(buf[(9, 4)].bg, shaded);
assert_eq!(buf[(2, 4)].bg, shaded);
assert_eq!(buf[(9, 1)].bg, s.chrome());
assert_eq!(buf[(1, 4)].bg, s.chrome());
}
#[test]
fn an_anchored_card_never_shadows_its_anchor_row() {
let theme = loch();
let s = theme.surfaces().unwrap();
let fresh = || {
let mut buf = Buffer::empty(Rect::new(0, 0, 12, 6));
buf.set_style(buf.area, Style::default().bg(s.chrome()));
buf
};
let card = Rect::new(1, 1, 8, 3);
let mut buf = fresh();
paint_anchored_frame(&mut buf, card, theme, 4, true);
let shaded = shade(s.chrome(), theme);
for x in 0..12 {
assert_eq!(buf[(x, 4)].bg, s.chrome(), "({x}, 4) is the anchor row");
}
assert_eq!(buf[(9, 2)].bg, shaded, "the right shadow still falls");
assert_eq!(buf[(9, 3)].bg, shaded);
assert_eq!(
buf[(1, 1)].fg,
buf[(1, 1)].bg,
"quiet: no accent lip, no edge"
);
let mut free = fresh();
paint_anchored_frame(&mut free, card, theme, 0, false);
let mut plain = fresh();
paint_overlay_frame(&mut plain, card, theme);
assert_eq!(free, plain);
let mut boxed = Buffer::empty(Rect::new(0, 0, 12, 6));
let mut gradient = boxed.clone();
paint_anchored_frame(&mut boxed, card, Theme::BLACK, 4, true);
crate::gradient::paint_gradient_box(&mut gradient, card);
assert_eq!(boxed, gradient, "a boxed theme keeps the gradient box");
}
#[test]
fn an_overlay_on_a_boxed_brand_theme_keeps_the_gradient_box() {
let mut ours = Buffer::empty(Rect::new(0, 0, 10, 5));
let mut theirs = ours.clone();
let card = Rect::new(1, 1, 6, 3);
paint_overlay_frame(&mut ours, card, Theme::BLACK);
crate::gradient::paint_gradient_box(&mut theirs, card);
assert_eq!(ours, theirs);
}
#[test]
fn a_boxed_section_header_is_the_dim_triangle_and_bold_label() {
use ratatui::text::Line;
use ratatui::widgets::{Paragraph, Widget};
let theme = Theme::BLACK;
let row = Rect::new(1, 0, 20, 1);
let mut ours = Buffer::empty(Rect::new(0, 0, 22, 1));
paint_section_header(&mut ours, row, theme, false, "OUTLINE", Vec::new(), true);
let mut theirs = Buffer::empty(Rect::new(0, 0, 22, 1));
Paragraph::new(Line::from(vec![
Span::styled(
format!("{} ", crate::icons::CHEVRON_CLOSED),
Style::default().fg(theme.ui(SECTION_DIM)),
),
Span::styled(
"OUTLINE",
Style::default()
.fg(theme.ui(SECTION_LABEL))
.add_modifier(Modifier::BOLD),
),
]))
.render(row, &mut theirs);
assert_eq!(ours, theirs);
}
#[test]
fn a_croft_loch_section_header_is_calm_and_lifts_under_the_pointer() {
let theme = loch();
let t = tones(theme).unwrap();
let row = Rect::new(1, 0, 20, 1);
let paint = |open: bool, hovered: bool| {
let mut buf = Buffer::empty(Rect::new(0, 0, 22, 1));
buf.set_style(buf.area, Style::default().bg(t.chrome()));
paint_section_header(&mut buf, row, theme, open, "OUTLINE", Vec::new(), hovered);
buf
};
let folded = paint(false, false);
assert_eq!(folded[(1, 0)].symbol(), CHEVRON_FOLDED.to_string());
assert_eq!(folded[(1, 0)].fg, t.muted());
assert_eq!(folded[(3, 0)].fg, t.muted(), "a folded label is muted");
assert_eq!(folded[(3, 0)].bg, t.chrome());
let open = paint(true, false);
assert_eq!(open[(1, 0)].symbol(), CHEVRON_UNFOLDED.to_string());
assert_eq!(open[(3, 0)].fg, t.text());
let hovered = paint(true, true);
assert_eq!(hovered[(3, 0)].fg, t.strong());
assert_eq!(hovered[(3, 0)].bg, t.hover_on(t.chrome));
assert_eq!(hovered[(20, 0)].bg, t.chrome(), "the padding stays chrome");
}
#[test]
fn a_field_is_a_raised_well_inside_an_eighth_block_edge() {
let t = tones(loch()).unwrap();
let mut buf = Buffer::empty(Rect::new(0, 0, 6, 3));
let area = buf.area;
paint_field(&mut buf, area, t, t.rim());
let rows: Vec<String> = (0..3)
.map(|y| (0..6).map(|x| buf[(x, y)].symbol()).collect())
.collect();
assert_eq!(rows[0], " \u{2581}\u{2581}\u{2581}\u{2581} ");
assert_eq!(rows[1], "\u{2595} \u{258f}");
assert_eq!(rows[2], " \u{2594}\u{2594}\u{2594}\u{2594} ");
assert_eq!(buf[(2, 1)].bg, t.raised());
assert_eq!(buf[(0, 1)].fg, t.rim());
}
#[test]
fn a_soft_button_is_a_one_row_pill_with_half_block_caps() {
let fill = Color::Rgb(0x0e, 0x7e, 0x76);
let mut buf = Buffer::empty(Rect::new(0, 0, 5, 3));
let area = buf.area;
let face = paint_soft_button(&mut buf, area, fill, true, false);
assert_eq!(face, Rect::new(1, 1, 4, 1), "the cells between the caps");
let rows: Vec<String> = (0..3)
.map(|y| (0..5).map(|x| buf[(x, y)].symbol()).collect())
.collect();
assert_eq!(rows, [" ", "\u{2590} ", " "]);
for x in 0..5 {
for y in [0, 2] {
assert_eq!(buf[(x, y)].bg, Color::Reset, "plain surface at ({x}, {y})");
}
}
assert_eq!(buf[(0, 1)].fg, fill);
assert_eq!(
buf[(0, 1)].bg,
Color::Reset,
"the cap keeps what is under it"
);
assert_eq!(buf[(4, 1)].bg, fill, "an unrounded end runs to the edge");
let mut buf = Buffer::empty(Rect::new(0, 0, 5, 3));
let face = paint_soft_button(&mut buf, area, fill, true, true);
assert_eq!(face, Rect::new(1, 1, 3, 1));
assert_eq!(buf[(4, 1)].symbol(), "\u{258c}");
assert_eq!(buf[(4, 1)].bg, Color::Reset);
}
#[test]
fn a_find_match_is_an_amber_tint_that_keeps_a_legible_ink() {
use crate::theme::contrast_ratio;
let theme = loch();
let t = tones(theme).unwrap();
let syn = crate::theme::SyntaxPalette::LOCH;
let on_canvas = |fg: (u8, u8, u8), active: bool| {
match_style(
Style::default().fg(rgb_color(fg)).bg(t.canvas()),
t,
theme,
active,
)
};
let soft = on_canvas(syn.keyword, false);
assert_eq!(
soft.bg,
Some(rgb_color(lerp_rgb(t.canvas, MATCH_AMBER, MATCH_SOFT)))
);
assert_ne!(soft.bg, Some(Color::Rgb(0xff, 0xd7, 0x4a)));
assert_eq!(soft.fg, Some(rgb_color(syn.keyword)), "the ink is kept");
assert!(!soft.add_modifier.contains(Modifier::BOLD));
assert_eq!(
on_canvas(syn.comment, false).fg,
Some(t.strong()),
"a comment would not read on the tint, so it lifts"
);
let lum = |c: Option<Color>| match c {
Some(Color::Rgb(r, g, b)) => contrast_ratio((r, g, b), (0, 0, 0)),
_ => 0.0,
};
assert!(
lum(on_canvas(syn.keyword, true).bg) > lum(soft.bg) + 0.5,
"the current match is a clearly stronger tint"
);
}
#[test]
fn every_find_match_reads_at_four_and_a_half_to_one() {
use crate::theme::contrast_ratio;
let theme = loch();
let t = tones(theme).unwrap();
let syn = crate::theme::SyntaxPalette::LOCH;
let inks = [
t.text,
t.strong,
t.muted,
t.faint,
syn.comment,
syn.keyword,
syn.string,
syn.constant,
syn.function,
syn.type_,
syn.tag,
syn.fg,
];
let bases = [
t.canvas,
t.chrome,
t.raised,
lerp_rgb(t.chrome, t.lift, 0.055),
(0x26, 0x4f, 0x4a),
selected_row_fill(t, t.chrome, true),
selected_row_fill(t, t.chrome, false),
];
for base in bases {
for ink in inks {
for active in [false, true] {
let s = match_style(
Style::default().fg(rgb_color(ink)).bg(rgb_color(base)),
t,
theme,
active,
);
let (Some(Color::Rgb(fr, fg, fb)), Some(Color::Rgb(br, bg, bb))) = (s.fg, s.bg)
else {
panic!("RGB inks for {ink:?} on {base:?}");
};
let ratio = contrast_ratio((fr, fg, fb), (br, bg, bb));
assert!(
ratio >= 4.5,
"{ink:?} on {base:?} (active {active}) reads at {ratio:.2}"
);
assert_ne!(s.bg, Some(rgb_color(base)), "the match is marked");
}
}
}
}
#[test]
fn selected_row_fill_is_the_band_paint_selected_row_lays() {
let t = tones(loch()).unwrap();
for focused in [true, false] {
let mut buf = Buffer::empty(Rect::new(0, 0, 4, 1));
paint_selected_row(&mut buf, Rect::new(0, 0, 4, 1), t, t.chrome, focused);
assert_eq!(
buf[(2, 0)].bg,
rgb_color(selected_row_fill(t, t.chrome, focused))
);
}
assert_eq!(rgb_color(selected_row_fill(t, t.raised, true)), t.band());
}
#[test]
fn pane_fill_is_chrome_only_for_surfaces_side_bars() {
let s = loch().surfaces().unwrap();
assert_eq!(pane_fill(loch(), true), s.chrome());
assert_eq!(pane_fill(loch(), false), loch().editor_bg());
assert_eq!(pane_fill(Theme::BLACK, true), Theme::BLACK.editor_bg());
}
}