use super::{Frame, Rect};
use crate::block::Block;
use crate::layout::Code;
use crate::style::palette::{BERRY, BLUSH, LINE, MUTED, PETAL, ROSE, SHINE, SOFT, TEXT, TRACK};
use crate::style::{Line, RAMP, Rgb, bold, gradient, mix, paint, paint_on, sample};
use crate::table::Table;
use crate::text;
use crate::tree::Tree;
use crate::widgets::{Card, noise};
const GLINT_FPS: u32 = 20;
pub(super) const BUSY_FPS: u32 = 30;
pub(super) const SPARKLE_FPS: u32 = 15;
pub trait Widget {
fn render(&self, area: Rect, frame: &mut Frame);
fn size(&self) -> Option<(usize, usize)> {
None
}
fn inner(&self, area: Rect) -> Rect {
area
}
}
impl<W: Widget + ?Sized> Widget for &W {
fn render(&self, area: Rect, frame: &mut Frame) {
(**self).render(area, frame)
}
fn inner(&self, area: Rect) -> Rect {
(**self).inner(area)
}
fn size(&self) -> Option<(usize, usize)> {
(**self).size()
}
}
impl<W: Widget + ?Sized> Widget for Box<W> {
fn render(&self, area: Rect, frame: &mut Frame) {
(**self).render(area, frame)
}
fn inner(&self, area: Rect) -> Rect {
(**self).inner(area)
}
fn size(&self) -> Option<(usize, usize)> {
(**self).size()
}
}
impl Widget for str {
fn render(&self, area: Rect, frame: &mut Frame) {
for (row, line) in wrap(self, area.width).into_iter().take(area.height).enumerate() {
frame.print(area, row, &line);
}
}
fn size(&self) -> Option<(usize, usize)> {
let lines = self.split('\n');
Some((lines.clone().map(text::width).max().unwrap_or(0), lines.count()))
}
}
pub(super) fn wrap(s: &str, cols: usize) -> Vec<String> {
let mut w = Wrap {
cols: cols.max(1),
..Wrap::default()
};
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\x1b' => {
let mut seq = String::from(c);
match chars.next() {
Some('[') => {
seq.push('[');
for c in chars.by_ref() {
seq.push(c);
if ('@'..='~').contains(&c) {
break;
}
}
}
Some(']') => {
seq.push(']');
while let Some(c) = chars.next() {
seq.push(c);
if c == '\x07' {
break;
}
if c == '\x1b' && chars.next_if_eq(&'\\').is_some() {
seq.push('\\');
break;
}
}
}
Some(c) => seq.push(c),
None => {}
}
w.escape(&seq);
}
'\n' => {
w.end_word();
w.end_line();
w.line.clone_from(&w.style);
}
' ' => {
w.end_word();
w.space = true;
}
c => w.char(c),
}
}
w.end_word();
w.end_line();
w.lines
}
#[derive(Default)]
struct Wrap {
cols: usize,
lines: Vec<String>,
line: String,
line_w: usize,
word: String,
word_w: usize,
style: String,
word_style: String,
space: bool,
}
impl Wrap {
fn begin_word(&mut self) {
if self.word.is_empty() {
self.word_style.clone_from(&self.style);
}
}
fn escape(&mut self, seq: &str) {
self.begin_word();
self.word.push_str(seq);
if let Some(params) = seq.strip_prefix("\x1b[").and_then(|p| p.strip_suffix('m')) {
if params.is_empty() || params == "0" {
self.style.clear();
} else {
self.style.push_str(seq);
}
}
}
fn char(&mut self, c: char) {
let cw = text::char_width(c);
if self.word_w > 0 && self.word_w + cw > self.cols {
self.end_word();
}
self.begin_word();
self.word.push(c);
self.word_w += cw;
}
fn end_word(&mut self) {
if self.word.is_empty() {
return;
}
if self.word_w > 0 {
let gap = (self.space && self.line_w > 0) as usize;
if self.line_w > 0 && self.line_w + gap + self.word_w > self.cols {
self.end_line();
self.line.clone_from(&self.word_style);
} else if gap == 1 {
self.line.push(' ');
self.line_w += 1;
}
self.space = false;
}
self.line.push_str(&self.word);
self.line_w += self.word_w;
self.word.clear();
self.word_w = 0;
}
fn end_line(&mut self) {
self.lines.push(std::mem::take(&mut self.line));
self.line_w = 0;
self.space = false;
}
}
impl Widget for String {
fn render(&self, area: Rect, frame: &mut Frame) {
self.as_str().render(area, frame)
}
fn size(&self) -> Option<(usize, usize)> {
self.as_str().size()
}
}
impl Widget for Line {
fn render(&self, area: Rect, frame: &mut Frame) {
frame.print(area, 0, &self.to_string());
}
fn size(&self) -> Option<(usize, usize)> {
Some((self.width(), 1))
}
}
impl Widget for Block {
fn render(&self, area: Rect, frame: &mut Frame) {
let margin = margin(self);
for (row, line) in self.lines().iter().take(area.height).enumerate() {
frame.print(area, row, &drop_columns(line, margin));
}
}
fn size(&self) -> Option<(usize, usize)> {
let margin = margin(self);
let widest = self.lines().iter().map(|l| text::width(l)).max().unwrap_or(0);
Some((widest.saturating_sub(margin), self.len()))
}
}
fn margin(block: &Block) -> usize {
block
.lines()
.iter()
.map(|l| text::strip_ansi(l))
.filter(|l| !l.trim().is_empty())
.map(|l| l.len() - l.trim_start_matches(' ').len())
.min()
.unwrap_or(0)
}
fn drop_columns(line: &str, mut n: usize) -> String {
let mut out = String::with_capacity(line.len());
let mut chars = line.chars();
while n > 0 {
match chars.next() {
Some(' ') => n -= 1,
Some('\x1b') => {
out.push('\x1b');
for c in chars.by_ref() {
out.push(c);
if c != '[' && ('@'..='~').contains(&c) {
break;
}
}
}
Some(c) => {
out.push(c);
break;
}
None => break,
}
}
out.extend(chars);
out
}
fn clip(s: &str, cols: usize) -> String {
if text::width(s) <= cols {
return s.to_string();
}
if !s.contains('\x1b') {
return text::truncate(s, cols);
}
let mut out = String::with_capacity(s.len());
let mut used = 0;
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\x1b' {
out.push(c);
for c in chars.by_ref() {
out.push(c);
if c != '[' && ('@'..='~').contains(&c) {
break;
}
}
continue;
}
let w = text::char_width(c);
if used + w + 1 > cols {
break;
}
out.push(c);
used += w;
}
if cols > 0 {
out.push('…');
}
out + "\x1b[0m"
}
macro_rules! via_lines {
($($ty:ty),*) => {$(
impl Widget for $ty {
fn render(&self, area: Rect, frame: &mut Frame) {
self.lines().render(area, frame)
}
fn size(&self) -> Option<(usize, usize)> {
self.lines().size()
}
}
)*};
}
via_lines!(Table, Tree, Code);
impl Widget for Card {
fn render(&self, area: Rect, frame: &mut Frame) {
frame.lines(area, &self.boxed(self.fixed_width().unwrap_or(area.width)));
}
fn size(&self) -> Option<(usize, usize)> {
let w = self.fixed_width()?;
Some((w, self.boxed(w).len()))
}
}
pub struct Panel<'a> {
title: String,
count: String,
status: String,
footer: String,
body: Option<Box<dyn Widget + 'a>>,
focused: bool,
padding: (usize, usize),
background: Option<Rgb>,
}
impl std::fmt::Debug for Panel<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Panel")
.field("title", &self.title)
.field("count", &self.count)
.field("status", &self.status)
.field("footer", &self.footer)
.field("focused", &self.focused)
.field("padding", &self.padding)
.field("background", &self.background)
.finish_non_exhaustive()
}
}
impl<'a> Panel<'a> {
pub fn new(title: impl Into<String>) -> Self {
Panel {
title: title.into(),
count: String::new(),
status: String::new(),
footer: String::new(),
body: None,
focused: false,
padding: (1, 0),
background: None,
}
}
#[must_use]
pub fn body(mut self, widget: impl Widget + 'a) -> Self {
self.body = Some(Box::new(widget));
self
}
#[must_use]
pub fn count(mut self, count: impl std::fmt::Display) -> Self {
self.count = count.to_string();
self
}
#[must_use]
pub fn status(mut self, text: impl Into<String>) -> Self {
self.status = text.into();
self
}
#[must_use]
pub fn footer(mut self, text: impl Into<String>) -> Self {
self.footer = text.into();
self
}
#[must_use]
pub fn focused(mut self, focused: bool) -> Self {
self.focused = focused;
self
}
#[must_use]
pub fn padding(mut self, x: usize, y: usize) -> Self {
self.padding = (x, y);
self
}
#[must_use]
pub fn background(mut self, color: Rgb) -> Self {
self.background = Some(color);
self
}
pub fn inner(&self, area: Rect) -> Rect {
area.shrink(1, 1).shrink(self.padding.0, self.padding.1)
}
}
impl Widget for Panel<'_> {
fn render(&self, area: Rect, frame: &mut Frame) {
if area.width < 2 || area.height < 2 {
return;
}
frame.clear(area);
if let Some(bg) = self.background {
frame.tint(area, bg);
}
let (w, h, t) = (area.width, area.height, frame.ambient_time());
if self.focused {
frame.animate_at(GLINT_FPS);
}
let perimeter = 2 * (w - 1) + 2 * (h - 1);
let glint = (t * 18.0).rem_euclid(perimeter as f64) as f32;
let color = |i: usize| {
if !self.focused {
return LINE;
}
let d = (i as f32 - glint).abs();
let d = d.min(perimeter as f32 - d);
mix(ROSE, PETAL, (-(d * d) / 30.0).exp())
};
let mut title = Line::new().push(LINE, " ");
if self.focused {
let b = (crate::widgets::turn(t, 2.6).sin() + 1.0) / 2.0;
title = title.push(sample(&[BERRY, ROSE, SHINE], b * b), "✦ ");
}
let pill = if self.count.is_empty() {
String::new()
} else if crate::style::color_mode() == crate::style::ColorMode::None {
format!(" {}", self.count)
} else {
let (fg, bg) = if self.focused {
(PETAL, mix(TRACK, ROSE, 0.35))
} else {
(SOFT, mix(TRACK, LINE, 0.4))
};
format!(" {}", paint_on(fg, bg, &format!(" {} ", self.count)))
};
let pill_w = text::width(&pill);
let room = w.saturating_sub(6 + title.width());
let (name, pill) = if text::width(&self.title) + pill_w <= room {
(self.title.clone(), pill)
} else if w >= 5 + title.width() {
(clip(&self.title, room.max(1)), String::new())
} else {
(String::new(), String::new())
};
let styled = self.title.contains('\x1b');
let title = if name.is_empty() {
Line::new()
} else if self.focused {
let name = if styled {
bold(&name)
} else {
bold(&paint(PETAL, &name))
};
title.raw(&name).raw(&pill).push(LINE, " ")
} else if styled {
title.raw(&name).raw(&pill).push(LINE, " ")
} else {
title.push(SOFT, &name).raw(&pill).push(LINE, " ")
};
let mut top = Line::new().push(color(0), "╭");
if w > 2 {
top = top.push(color(1), "─").append(title.clone());
}
let spare = (w - 1).saturating_sub(top.width() + 4);
let status = match text::width(&self.status) {
0 => String::new(),
n if n <= spare => self.status.clone(),
_ if spare >= 6 => clip(&self.status, spare),
_ => String::new(),
};
let status_at = (w - 1).saturating_sub(text::width(&status) + 3);
while top.width() < w - 1 {
let x = top.width();
if !status.is_empty() && x == status_at {
let status = if status.contains('\x1b') {
status.clone()
} else {
paint(MUTED, &status)
};
top = top.push(LINE, " ").raw(&status).push(LINE, " ");
} else {
top = top.push(color(x), "─");
}
}
frame.print(area, 0, &top.push(color(w - 1), "╮").to_string());
for y in 1..h - 1 {
frame.print(area.row(y), 0, &paint(color(perimeter - y), "│"));
frame.print(
Rect::new(area.x + w - 1, area.y + y, 1, 1),
0,
&paint(color(w - 1 + y), "│"),
);
}
let footer = if w >= 8 {
text::truncate(&self.footer, w - 6)
} else {
String::new()
};
let footer_w = if footer.is_empty() { 0 } else { text::width(&footer) + 2 };
let bottom_at = |x: usize| (w - 1) + (h - 1) + (w - 1 - x);
let mut bottom = Line::new().push(color(bottom_at(0)), "╰");
for x in 1..w - 2 - footer_w {
bottom = bottom.push(color(bottom_at(x)), "─");
}
if footer_w > 0 {
bottom = bottom.push(MUTED, &format!(" {footer} "));
}
let bottom = bottom
.push(color(bottom_at(w - 2)), "─")
.push(color(bottom_at(w - 1)), "╯");
frame.print(area.row(h - 1), 0, &bottom.to_string());
if let Some(body) = &self.body {
body.render(self.inner(area), frame);
}
}
fn inner(&self, area: Rect) -> Rect {
Panel::inner(self, area)
}
fn size(&self) -> Option<(usize, usize)> {
let (w, h) = match &self.body {
Some(body) => body.size()?,
None => (0, 0),
};
let count = if self.count.is_empty() {
0
} else {
text::width(&self.count) + 3
};
let status = if self.status.is_empty() {
0
} else {
text::width(&self.status) + 3
};
let title = text::width(&self.title) + count + status + if self.focused { 9 } else { 7 };
let (px, py) = self.padding;
Some(((w + 2 + 2 * px).max(title), h + 2 + 2 * py))
}
}
#[derive(Clone, Debug)]
pub struct List {
items: Vec<String>,
selected: Option<usize>,
}
impl List {
pub fn new<S: Into<String>>(items: impl IntoIterator<Item = S>) -> Self {
List {
items: items.into_iter().map(Into::into).collect(),
selected: None,
}
}
#[must_use]
pub fn selected(mut self, index: usize) -> Self {
self.selected = Some(index);
self
}
}
impl Widget for List {
fn render(&self, area: Rect, frame: &mut Frame) {
let (n, h) = (self.items.len(), area.height);
if area.is_empty() {
return;
}
if n == 0 {
frame.print(area, 0, &paint(MUTED, "nothing here yet"));
return;
}
let chosen = self.selected.map(|s| s.min(n - 1));
let start = if n <= h {
0
} else {
chosen.unwrap_or(0).saturating_sub(h / 2).min(n - h)
};
let overflow = n > h;
let text_w = area.width.saturating_sub(overflow as usize);
for (row, i) in (start..n).take(h).enumerate() {
let line = area.row(row);
let line = Rect::new(line.x, line.y, text_w, line.height);
if Some(i) == chosen {
frame.print(
line,
0,
&format!("{} {}", paint(ROSE, "›"), bold(&paint(TEXT, &self.items[i]))),
);
frame.tint(line, mix(TRACK, BERRY, 0.35));
} else {
frame.print(line, 0, &format!(" {}", paint(SOFT, &self.items[i])));
}
}
if overflow && area.width > 0 {
scrollbar(frame, Rect::new(area.x + area.width - 1, area.y, 1, h), start, n);
}
}
fn size(&self) -> Option<(usize, usize)> {
let widest = self.items.iter().map(|i| text::width(i)).max().unwrap_or(16);
Some((widest + 2, self.items.len().max(1)))
}
}
pub(super) fn centered(frame: &mut Frame, area: Rect, line: &str) {
if area.is_empty() {
return;
}
let w = text::width(line).min(area.width);
let at = Rect::new(area.x + (area.width - w) / 2, area.y + (area.height - 1) / 2, w, 1);
frame.print(at, 0, line);
}
pub(super) fn scrollbar(frame: &mut Frame, bar: Rect, start: usize, total: usize) {
frame.render(bar, Scrollbar::new(start, total));
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Scrollbar {
top: usize,
total: usize,
color: Option<Rgb>,
track: bool,
}
impl Scrollbar {
pub fn new(top: usize, total: usize) -> Self {
Scrollbar {
top,
total,
color: None,
track: true,
}
}
#[must_use]
pub fn color(mut self, color: Rgb) -> Self {
self.color = Some(color);
self
}
#[must_use]
pub fn track(mut self, track: bool) -> Self {
self.track = track;
self
}
fn thumb(&self, height: usize) -> Option<std::ops::Range<usize>> {
if height == 0 || self.total <= height {
return None;
}
let size = (height * height / self.total).max(1);
let at = self.top.min(self.total - height) * (height - size) / (self.total - height);
Some(at..at + size)
}
}
impl Widget for Scrollbar {
fn render(&self, area: Rect, frame: &mut Frame) {
let Some(thumb) = self.thumb(area.height) else { return };
let color = self.color.unwrap_or(ROSE);
let glyph = if self.track { "┃" } else { "▐" };
for row in 0..area.height {
if thumb.contains(&row) {
frame.print(area, row, &paint(color, glyph));
} else if self.track {
frame.print(area, row, &paint(TRACK, "│"));
}
}
}
fn size(&self) -> Option<(usize, usize)> {
Some((1, self.total))
}
}
#[derive(Clone, Debug)]
pub struct Tabs {
tabs: Vec<Tab>,
selected: usize,
}
#[derive(Clone, Debug)]
struct Tab {
title: String,
color: Option<Rgb>,
badge: Option<(String, Rgb)>,
}
impl Tab {
fn width(&self) -> usize {
let badge = self.badge.as_ref().map_or(0, |(b, _)| text::width(b) + 1);
text::width(&self.title) + badge + 2
}
}
impl Tabs {
pub fn new<S: Into<String>>(titles: impl IntoIterator<Item = S>) -> Self {
Tabs {
tabs: titles
.into_iter()
.map(|t| Tab {
title: t.into(),
color: None,
badge: None,
})
.collect(),
selected: 0,
}
}
#[must_use]
pub fn selected(mut self, index: usize) -> Self {
self.selected = index;
self
}
#[must_use]
pub fn color(mut self, index: usize, color: Rgb) -> Self {
if let Some(tab) = self.tabs.get_mut(index) {
tab.color = Some(color);
}
self
}
#[must_use]
pub fn badge(mut self, index: usize, color: Rgb, text: impl Into<String>) -> Self {
if let Some(tab) = self.tabs.get_mut(index) {
tab.badge = Some((text.into(), color));
}
self
}
pub fn at(&self, area: Rect, x: usize, y: usize) -> Option<usize> {
if y != area.y || x < area.x {
return None;
}
let mut left = area.x;
for (i, tab) in self.tabs.iter().enumerate() {
let right = left + tab.width();
if (left..right).contains(&x) {
return Some(i);
}
left = right + 1;
}
None
}
}
impl Widget for Tabs {
fn render(&self, area: Rect, frame: &mut Frame) {
let line = self.tabs.iter().enumerate().fold(Line::new(), |line, (i, tab)| {
let line = if i > 0 { line.space(1) } else { line };
let chosen = i == self.selected;
let fg = tab.color.unwrap_or(if chosen { PETAL } else { MUTED });
let mut label = paint(fg, &format!(" {}", tab.title));
if let Some((badge, color)) = &tab.badge {
label += &format!(" {}", paint(*color, badge));
}
label.push(' ');
if chosen {
line.raw(&crate::style::paint_bg(mix(TRACK, ROSE, 0.32), &label))
} else {
line.raw(&label)
}
});
line.render(area, frame);
}
}
#[derive(Clone, Debug)]
pub struct Plot {
values: Vec<f64>,
range: Option<(f64, f64)>,
color: Option<Rgb>,
}
impl Plot {
pub fn new(values: &[f64]) -> Self {
Plot {
values: values.to_vec(),
range: None,
color: None,
}
}
#[must_use]
pub fn range(mut self, low: f64, high: f64) -> Self {
self.range = Some((low, high));
self
}
#[must_use]
pub fn color(mut self, color: Rgb) -> Self {
self.color = Some(color);
self
}
}
const LEVELS: [&str; 8] = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
impl Widget for Plot {
fn render(&self, area: Rect, frame: &mut Frame) {
let shown = &self.values[self.values.len().saturating_sub(area.width)..];
let (lo, hi) = self.range.unwrap_or_else(|| {
let lo = shown.iter().copied().fold(0.0, f64::min);
(lo, shown.iter().copied().fold(lo, f64::max))
});
let span = (hi - lo).max(f64::EPSILON);
let h = area.height;
let left = area.x + area.width - shown.len();
for row in 0..h {
let t = (h - 1 - row) as f32 / h.saturating_sub(1).max(1) as f32;
let color = match self.color {
Some(c) => mix(mix(TRACK, c, 0.45), c, t),
None => sample(RAMP, t),
};
let mut line = String::new();
for &v in shown {
let eighths = (((v - lo) / span).clamp(0.0, 1.0) * (h * 8) as f64).round() as usize;
let here = eighths.saturating_sub((h - 1 - row) * 8).min(8);
line.push_str(if here == 0 { " " } else { LEVELS[here - 1] });
}
frame.print(Rect::new(left, area.y, shown.len(), h), row, &paint(color, &line));
}
}
}
#[derive(Clone, Debug)]
pub struct Stat {
label: String,
value: String,
note: Option<(String, Rgb)>,
}
impl Stat {
pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
Stat {
label: label.into(),
value: value.into(),
note: None,
}
}
#[must_use]
pub fn note(mut self, color: Rgb, text: impl Into<String>) -> Self {
self.note = Some((text.into(), color));
self
}
}
impl Widget for Stat {
fn render(&self, area: Rect, frame: &mut Frame) {
frame.print(area, 0, &paint(MUTED, &self.label));
let large = big(&self.value);
let roomy = area.height > 3 + self.note.is_some() as usize
&& large.lines().iter().all(|l| text::width(l) <= area.width);
let note_row = if roomy {
large.render(Rect::new(area.x, area.y + 1, area.width, 3), frame);
4
} else {
frame.print(area, 1, &bold(&gradient(&self.value, RAMP, 0.0)));
2
};
if let Some((note, color)) = &self.note {
frame.print(area, note_row, &paint(*color, note));
}
}
}
pub fn big(text: &str) -> Block {
let mut rows = [String::new(), String::new(), String::new()];
for (i, c) in text.chars().enumerate() {
let glyph = match c {
'0' => ["╭─╮", "│ │", "╰─╯"],
'1' => ["╶┐ ", " │ ", "╶┴╴"],
'2' => ["╶─╮", "╭─╯", "╰─╴"],
'3' => ["╶─╮", " ─┤", "╶─╯"],
'4' => ["╷ ╷", "╰─┤", " ╵"],
'5' => ["╭─╴", "╰─╮", "╶─╯"],
'6' => ["╭─╴", "├─╮", "╰─╯"],
'7' => ["╶─┐", " │", " ╵"],
'8' => ["╭─╮", "├─┤", "╰─╯"],
'9' => ["╭─╮", "╰─┤", "╶─╯"],
'.' => [" ", " ", "•"],
',' => [" ", " ", ","],
':' => [" ", "•", "•"],
'-' => [" ", "╶╴", " "],
'+' => [" ", "╶┼╴", " "],
'%' => ["◦ ╱", " ╱ ", "╱ ◦"],
'/' => [" ╱", " ╱ ", "╱ "],
' ' => [" ", " ", " "],
_ => ["", "", ""],
};
let small;
let glyph = if glyph[0].is_empty() && c != ' ' {
let pad = " ".repeat(text::char_width(c));
small = c.to_string();
[pad.clone(), pad, small]
} else {
glyph.map(String::from)
};
let gap = i > 0;
for (row, part) in rows.iter_mut().zip(glyph) {
if gap {
row.push(' ');
}
row.push_str(&part);
}
}
rows.iter().map(|r| gradient(r, RAMP, 0.0)).collect()
}
#[derive(Clone, Debug)]
pub struct Loading {
label: String,
detail: String,
progress: Option<(f32, String)>,
spinner: crate::Spinner,
centered: bool,
}
impl Loading {
pub fn new(label: impl Into<String>) -> Self {
Loading {
label: label.into(),
detail: String::new(),
progress: None,
spinner: crate::Spinner::default(),
centered: false,
}
}
#[must_use]
pub fn detail(mut self, text: impl Into<String>) -> Self {
self.detail = text.into();
self
}
#[must_use]
pub fn progress(mut self, fraction: f32, text: impl Into<String>) -> Self {
self.progress = Some((crate::widgets::fraction(fraction), text.into()));
self
}
#[must_use]
pub fn spinner(mut self, spinner: crate::Spinner) -> Self {
self.spinner = spinner;
self
}
#[must_use]
pub fn centered(mut self) -> Self {
self.centered = true;
self
}
fn lines(&self, t: f64, width: usize) -> Vec<String> {
let mark = self.spinner.frame(t);
let indent = " ".repeat(mark.width() + 1);
let mut lines = vec![format!("{mark} {}", crate::anim::shimmer(&self.label, t))];
if let Some((p, text)) = &self.progress {
let room = width.saturating_sub(indent.len() + 2 + text::width(text) + 6);
let bar = crate::anim::bar(*p, room.clamp(8, 30), t);
let stats = format!("{:>3.0}% {text}", p * 100.0);
lines.push(format!("{indent}{bar} {}", paint(SOFT, stats.trim_end())));
} else if !self.detail.is_empty() {
lines.push(format!("{indent}{}", paint(MUTED, &self.detail)));
}
lines
}
}
impl Widget for Loading {
fn render(&self, area: Rect, frame: &mut Frame) {
if area.is_empty() {
return;
}
frame.animate_at(BUSY_FPS);
let lines = self.lines(frame.ambient_time(), area.width);
if !self.centered {
for (row, line) in lines.iter().enumerate() {
frame.print(area, row, line);
}
return;
}
let w = lines.iter().map(|l| text::width(l)).max().unwrap_or(0).min(area.width);
let h = lines.len().min(area.height);
let at = Rect::new(area.x + (area.width - w) / 2, area.y + (area.height - h) / 2, w, h);
for (row, line) in lines.iter().enumerate() {
frame.print(at, row, line);
}
}
fn size(&self) -> Option<(usize, usize)> {
let lines = self.lines(0.0, 60);
let widest = lines.iter().map(|l| text::width(l)).max().unwrap_or(0);
Some((widest, lines.len()))
}
}
impl Widget for crate::Spinner {
fn render(&self, area: Rect, frame: &mut Frame) {
if area.is_empty() {
return;
}
frame.animate_at(BUSY_FPS);
frame.print(area, 0, &self.frame(frame.ambient_time()).to_string());
}
fn size(&self) -> Option<(usize, usize)> {
Some((self.frame(0.0).width(), 1))
}
}
pub fn hints(keys: &[(&str, &str)]) -> Line {
keys.iter().enumerate().fold(Line::new(), |line, (i, (key, what))| {
let line = if i > 0 { line.push(TRACK, " · ") } else { line };
line.push(BLUSH, key).space(1).push(MUTED, what)
})
}
#[derive(Clone, Debug, Default)]
pub struct Footer {
groups: Vec<Vec<(String, String)>>,
status: String,
}
impl Footer {
pub fn new() -> Self {
Footer::default()
}
#[must_use]
pub fn keys(mut self, keys: &[(&str, &str)]) -> Self {
self.groups
.push(keys.iter().map(|(k, w)| (k.to_string(), w.to_string())).collect());
self
}
#[must_use]
pub fn status(mut self, status: impl Into<String>) -> Self {
self.status = status.into();
self
}
fn fit(&self, room: usize) -> Line {
let mut line = Line::new();
for group in &self.groups {
for (i, (key, what)) in group.iter().enumerate() {
let gap = if line.width() == 0 { 0 } else { 3 };
let hint = text::width(key) + 1 + text::width(what);
if line.width() + gap + hint > room {
return line;
}
line = if gap == 0 {
line
} else if i == 0 {
line.space(gap)
} else {
line.push(TRACK, " · ")
};
line = line.push(BLUSH, key).space(1).push(MUTED, what);
}
}
line
}
}
impl Widget for Footer {
fn render(&self, area: Rect, frame: &mut Frame) {
if area.is_empty() {
return;
}
let status = clip(&self.status, area.width);
let status_w = text::width(&status);
frame.print(
Rect::new(area.x + area.width - status_w, area.y, status_w, 1),
0,
&paint(MUTED, &status),
);
let room = area.width.saturating_sub(status_w + 2 * (status_w > 0) as usize);
frame.print(area, 0, &self.fit(room).to_string());
}
fn size(&self) -> Option<(usize, usize)> {
let keys = self.fit(usize::MAX).width();
let gap = if keys > 0 && !self.status.is_empty() { 2 } else { 0 };
Some((keys + gap + text::width(&self.status), 1))
}
}
#[derive(Clone, Copy, Debug)]
pub struct Sparkles {
density: f32,
wander: bool,
}
impl Sparkles {
pub fn new() -> Self {
Sparkles {
density: 0.025,
wander: false,
}
}
#[must_use]
pub fn wandering(mut self) -> Self {
self.wander = true;
self
}
#[must_use]
pub fn density(mut self, density: f32) -> Self {
self.density = density.clamp(0.0, 1.0);
self
}
}
impl Default for Sparkles {
fn default() -> Self {
Sparkles::new()
}
}
fn wander(density: f32, area: Rect, frame: &mut Frame, t: f64) {
if area.width == 0 || area.height == 0 {
return;
}
let count = ((area.width * area.height) as f32 * density).round() as u32;
for star in 0..count {
let life = 2.5 + 3.5 * noise(star, 11) as f64;
let age = t / life + noise(star, 12) as f64;
let (lived, p) = (age.floor() as u64 as u32, age.fract() as f32);
let b = (p * std::f32::consts::PI).sin().powi(3);
if b < 0.08 {
continue;
}
let place = star.wrapping_mul(7919) ^ lived.wrapping_mul(104_729);
let col = ((noise(place, 13) * area.width as f32) as usize).min(area.width - 1);
let row = ((noise(place, 14) * area.height as f32) as usize).min(area.height - 1);
let glyph = ["⋆", "✧", "✦"][((b * 3.0) as usize).min(2)];
let shine = paint(sample(&[BERRY, ROSE, SHINE], b), glyph);
frame.print(Rect::new(area.x + col, area.y + row, 1, 1), 0, &shine);
}
}
impl Widget for Sparkles {
fn render(&self, area: Rect, frame: &mut Frame) {
const STARS: [&str; 4] = ["·", "⋆", "✧", "✦"];
if area.is_empty() {
return;
}
frame.animate_at(SPARKLE_FPS);
let t = frame.ambient_time();
if self.wander {
return wander(self.density, area, frame, t);
}
for row in 0..area.height {
for col in 0..area.width {
let cell = ((area.y + row) * 4093 + area.x + col) as u32;
if noise(cell, 0) >= self.density {
continue;
}
let speed = 0.6 + 1.8 * noise(cell, 1) as f64;
let b = ((crate::widgets::turn(t, speed) + noise(cell, 2) * 6.3).sin() + 1.0) / 2.0;
let b = b * b * b;
let star = paint(
sample(&[TRACK, BERRY, ROSE, SHINE], b),
STARS[((b * 4.0) as usize).min(3)],
);
frame.print(Rect::new(area.x + col, area.y + row, 1, 1), 0, &star);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_panel_with_a_background_fills_it_under_its_border_and_body() {
crate::with_color_mode(crate::ColorMode::TrueColor, || {
let mut f = Frame::new(12, 3);
f.render(f.area(), Panel::new("x").body("hi").background(Rgb(44, 33, 51)));
let html = f.html_pre();
let spans: Vec<&str> = html.split("<span style=\"").skip(1).collect();
assert!(!spans.is_empty() && html.contains("hi"));
for span in spans {
assert!(span.split('"').next().unwrap().contains("background:"), "{html}");
}
});
}
#[test]
fn a_scrollbar_runs_from_top_to_bottom_and_can_go_without_a_track() {
crate::set_color_mode(crate::ColorMode::None);
let drawn = |bar: Scrollbar| {
let mut f = Frame::new(1, 5);
f.render(f.area(), bar);
f.snapshot().plain().replace('\n', "")
};
assert_eq!(drawn(Scrollbar::new(0, 20)), "┃││││");
assert_eq!(drawn(Scrollbar::new(15, 20)), "││││┃");
assert_eq!(drawn(Scrollbar::new(99, 20)), "││││┃", "past the end is the end");
assert_eq!(drawn(Scrollbar::new(0, 5)), "", "everything fits");
assert_eq!(drawn(Scrollbar::new(0, 10).track(false).color(Rgb(1, 2, 3))), "▐▐");
assert_eq!(Scrollbar::new(0, 9).size(), Some((1, 9)));
}
#[test]
fn animated_widgets_ask_for_frames_and_still_ones_dont() {
let asks = |w: &dyn Widget| {
let mut f = Frame::new(20, 5).at(1.0);
w.render(f.area(), &mut f);
f.wants_redraw()
};
assert!(asks(&Panel::new("hi").focused(true)));
assert!(!asks(&Panel::new("hi")));
assert!(asks(&Loading::new("busy")));
assert!(asks(&Sparkles::new()));
assert!(asks(&crate::Spinner::Arc));
assert!(!asks(&List::new(["a", "b"])));
}
#[test]
fn wandering_stars_go_out_and_come_back_elsewhere() {
crate::set_color_mode(crate::ColorMode::None);
let drawn = |t: f64| {
let mut f = Frame::new(60, 20).at(t);
f.render(f.area(), Sparkles::new().density(0.02).wandering());
f.snapshot().plain()
};
let stars = |s: &str| s.chars().filter(|c| "⋆✧✦".contains(*c)).count();
let now = drawn(1.0);
assert!(stars(&now) <= 24 && !now.contains('·'), "no faint dots left behind");
let later = drawn(40.0);
assert_ne!(now, later, "they've moved on");
}
#[test]
fn loading_says_what_its_waiting_for_then_how_far_it_is() {
crate::set_color_mode(crate::ColorMode::None);
let drawn = |loading: Loading, w, h| {
let mut f = Frame::new(w, h).at(1.0);
f.render(f.area(), loading);
f.snapshot().plain()
};
let waiting = drawn(Loading::new("fetching").detail("from eu-west"), 24, 2);
assert_eq!(
waiting.lines().map(|l| &l[l.find(' ').unwrap()..]).collect::<Vec<_>>(),
[" fetching", " from eu-west"]
);
let mut lines = drawn(Loading::new("saving").progress(1.5, ""), 30, 2)
.lines()
.map(String::from)
.collect::<Vec<_>>();
assert!(
lines.remove(1).trim_end().ends_with("100%"),
"clamped, and no trailing gap"
);
let middle = drawn(
Loading::new("ab")
.spinner(crate::Spinner::Arc)
.progress(0.5, "x")
.centered(),
30,
4,
);
let rows: Vec<&str> = middle.lines().collect();
assert!(
rows[0].trim().is_empty() && rows[1].contains("ab") && rows[2].contains("50% x"),
"{middle}"
);
assert_eq!(
rows[1].find(|c: char| c != ' '),
rows[2].find(|c: char| c != ' ').map(|i| i - 2),
"{middle}"
);
assert_eq!(drawn(Loading::new("x"), 0, 0), "");
assert_eq!(Loading::new("fetching").size(), Some((12, 1)));
assert_eq!(Loading::new("x").detail("y").size().map(|s| s.1), Some(2));
}
#[test]
fn blocks_lose_their_margin() {
crate::set_color_mode(crate::ColorMode::None);
let mut f = Frame::new(10, 2);
f.render(f.area(), Block::from(vec![" a".to_string(), " b".to_string()]));
assert_eq!(f.snapshot().plain(), "a\n b");
assert_eq!(drop_columns("\x1b[1m x", 2), "\x1b[1mx");
}
#[test]
fn cards_fit_the_area_they_are_drawn_in() {
crate::set_color_mode(crate::ColorMode::None);
let mut f = Frame::new(30, 3);
f.render(Rect::new(0, 0, 14, 3), Card::success("done"));
assert_eq!(f.snapshot().plain(), "╭────────────╮\n│ ● done │\n╰────────────╯");
}
#[test]
fn wrapping_carries_styles_and_measures_columns() {
assert_eq!(wrap("the quick brown fox", 9), ["the quick", "brown fox"]);
assert_eq!(wrap("a\n\nb", 5), ["a", "", "b"]);
assert_eq!(
wrap("\x1b[31maa bb cc\x1b[39m", 2),
["\x1b[31maa", "\x1b[31mbb", "\x1b[31mcc\x1b[39m"]
);
assert_eq!(
wrap("\x1b[38;2;1;2;3mabcdef", 3),
["\x1b[38;2;1;2;3mabc", "\x1b[38;2;1;2;3mdef"]
);
assert_eq!(wrap("日本語です", 4), ["日本", "語で", "す"]);
assert_eq!(wrap("\x1b[1mbold\x1b[0m plain", 5), ["\x1b[1mbold\x1b[0m", "plain"]);
}
fn drawn(w: usize, h: usize, widget: impl Widget) -> String {
crate::set_color_mode(crate::ColorMode::None);
let mut f = Frame::new(w, h);
f.render(f.area(), widget);
f.snapshot().plain()
}
#[test]
fn stats_go_big_when_there_is_room() {
let stat = Stat::new("p95", "12").note(crate::palette::SOFT, "ms");
assert_eq!(drawn(10, 5, &stat), "p95\n╶┐ ╶─╮\n │ ╭─╯\n╶┴╴ ╰─╴\nms");
assert_eq!(drawn(4, 5, &stat), "p95\n12\nms\n\n");
assert_eq!(drawn(10, 4, Stat::new("n", "7")), "n\n╶─┐\n │\n ╵");
}
#[test]
fn big_draws_punctuation_and_falls_back_for_letters() {
crate::set_color_mode(crate::ColorMode::None);
let rows = |s: &str| big(s).plain();
assert_eq!(rows("3:4"), "╶─╮ ╷ ╷\n ─┤ • ╰─┤\n╶─╯ • ╵");
assert_eq!(rows("-+"), " \n╶╴ ╶┼╴\n ");
assert_eq!(rows("5%"), "╭─╴ ◦ ╱\n╰─╮ ╱ \n╶─╯ ╱ ◦");
assert_eq!(rows("6/8,9 0"), big("6/8,9 0").plain());
assert_eq!(rows("1k"), "╶┐ \n │ \n╶┴╴ k");
assert_eq!(rows("日"), " \n \n日");
}
#[test]
fn plots_take_a_range_and_a_colour_and_keep_the_latest_values() {
let values = [10.0, 0.0, 5.0];
assert_eq!(drawn(3, 1, Plot::new(&values).range(0.0, 10.0)), "█ ▄");
assert_eq!(drawn(3, 1, Plot::new(&values).range(5.0, 10.0)), "█");
assert_eq!(drawn(2, 1, Plot::new(&values).color(crate::palette::SAGE)), " █");
assert_eq!(drawn(5, 1, Plot::new(&[1.0])), " █");
assert_eq!(drawn(3, 1, Plot::new(&[-1.0, 1.0])), " █");
}
#[test]
fn sparkles_scatter_stars_and_leave_the_rest_alone() {
let all = drawn(4, 2, Sparkles::new().density(1.0));
assert_eq!(all.chars().filter(|c| !c.is_whitespace()).count(), 8);
assert_eq!(drawn(4, 2, Sparkles::default().density(0.0)), "\n");
assert_eq!(Sparkles::new().density(7.0).density, 1.0);
}
#[test]
fn panels_pad_title_and_focus() {
let panel = Panel::new("t").body("x").padding(2, 1).focused(true);
assert_eq!(panel.inner(Rect::new(0, 0, 10, 5)), Rect::new(3, 2, 4, 1));
assert_eq!(
drawn(10, 5, panel),
"╭─ ✦ t ──╮\n│ │\n│ x │\n│ │\n╰────────╯"
);
assert_eq!(drawn(6, 2, Panel::new("").footer("too long")), "╭────╮\n╰────╯");
assert_eq!(drawn(1, 1, Panel::new("tiny")), "");
}
#[test]
fn counts_give_way_to_titles_and_footers_drop_keys_before_status() {
assert_eq!(
drawn(16, 2, Panel::new("services").count(12)).lines().next(),
Some("╭─ services ───╮")
);
assert_eq!(
drawn(18, 2, Panel::new("services").count(12)).lines().next(),
Some("╭─ services 12 ──╮")
);
assert_eq!(
drawn(14, 2, Panel::new("services").count(12)).lines().next(),
Some("╭─ servic… ──╮")
);
assert_eq!(Panel::new("ab").count(3).focused(true).size(), Some((15, 2)));
let footer = Footer::new().keys(&[("q", "quit")]).keys(&[("?", "help")]).status("ok");
assert_eq!(drawn(16, 1, &footer), "q quit ok");
assert_eq!(drawn(20, 1, &footer), "q quit ? help ok");
assert_eq!(footer.size(), Some((19, 1)));
assert_eq!(drawn(19, 1, &footer), "q quit ? help ok");
assert_eq!(drawn(0, 0, &footer), "");
}
#[test]
fn statuses_sit_top_right_and_give_way_first() {
let top = |w: usize, panel: Panel| drawn(w, 2, panel).lines().next().unwrap().to_string();
let panel = || Panel::new("services").count(12).status("staging · read now");
assert_eq!(top(40, panel()), "╭─ services 12 ─── staging · read now ─╮");
assert_eq!(top(30, panel()), "╭─ services 12 ─ staging ·… ─╮");
assert_eq!(top(24, panel()), "╭─ services 12 ────────╮");
assert_eq!(top(14, panel()), "╭─ servic… ──╮");
assert_eq!(top(9, panel()), "╭─ s… ──╮");
assert_eq!(top(8, panel()), "╭─ … ──╮");
assert_eq!(top(6, panel()), "╭─ … ╮");
assert_eq!(top(5, panel()), "╭───╮");
assert_eq!(top(20, Panel::new("").status("live")), "╭─────────── live ─╮");
for w in 2..48 {
for panel in [panel(), panel().focused(true)] {
let line = top(w, panel);
assert_eq!(text::width(&line), w, "{line}");
assert!(line.starts_with('╭') && line.ends_with('╮'), "{line}");
}
}
assert_eq!(Panel::new("ab").status("ok").size(), Some((14, 2)));
}
#[test]
fn styled_text_is_clipped_without_breaking_its_codes() {
assert_eq!(clip("plain text", 6), "plain…");
assert_eq!(clip("\x1b[31mred\x1b[39m", 5), "\x1b[31mred\x1b[39m");
assert_eq!(clip("\x1b[31mredder\x1b[39m", 4), "\x1b[31mred…\x1b[0m");
assert_eq!(text::strip_ansi(&clip("\x1b[1m日本語", 4)), "日…");
}
#[test]
fn footers_drop_whole_hints_and_keep_the_status() {
let footer = Footer::new()
.keys(&[("↑↓", "move"), ("enter", "open"), ("/", "filter")])
.keys(&[("r", "refresh")])
.status("staging · 3s ago");
let keys = |w: usize| {
let shown = drawn(w, 1, &footer);
assert!(shown.ends_with("staging · 3s ago"), "{w}: {shown:?}");
assert!(text::width(&shown) <= w);
shown[..shown.len() - "staging · 3s ago".len()].trim_end().to_string()
};
assert_eq!(keys(61), "↑↓ move · enter open · / filter r refresh");
assert_eq!(keys(60), "↑↓ move · enter open · / filter");
assert_eq!(keys(49), "↑↓ move · enter open · / filter");
assert_eq!(keys(48), "↑↓ move · enter open");
assert_eq!(keys(38), "↑↓ move · enter open");
assert_eq!(keys(37), "↑↓ move");
assert_eq!(keys(25), "↑↓ move");
assert_eq!(keys(24), "");
assert_eq!(keys(16), "");
assert_eq!(drawn(10, 1, &footer), "staging ·…");
let footer = Footer::new()
.keys(&[("enter", "open the thing")])
.keys(&[("q", "quit")]);
assert_eq!(drawn(12, 1, &footer), "");
for w in 0..80 {
let shown = drawn(w, 1, Footer::new().keys(&[("a", "bb"), ("c", "dd")]).status("ok"));
assert!(text::width(&shown) <= w);
assert!(shown.ends_with("ok") || w < 2, "{w}: {shown:?}");
let keys = shown.trim_end_matches(['o', 'k', '…']).trim_end();
assert!(["", "a bb", "a bb · c dd"].contains(&keys), "{w}: {shown:?}");
}
assert_eq!(Footer::new().keys(&[("q", "quit")]).size(), Some((6, 1)));
}
#[test]
fn tabs_with_badges_are_wider_and_clicks_follow() {
let tabs = Tabs::new(["a", "bb", "c"])
.badge(0, crate::palette::RED, "12")
.color(2, crate::palette::RED)
.badge(9, crate::palette::RED, "ignored")
.color(9, crate::palette::RED)
.selected(2);
assert_eq!(drawn(20, 1, &tabs), " a 12 bb c");
let area = Rect::new(0, 0, 20, 1);
let hits: Vec<_> = (0..15).map(|x| tabs.at(area, x, 0)).collect();
let (a, b, c) = (Some(0), Some(1), Some(2));
assert_eq!(hits, [a, a, a, a, a, a, None, b, b, b, b, None, c, c, c]);
}
#[test]
fn tabs_find_what_was_clicked() {
let tabs = Tabs::new(["a", "bb"]);
let area = Rect::new(2, 1, 20, 1);
assert_eq!(tabs.at(area, 2, 1), Some(0));
assert_eq!(tabs.at(area, 5, 1), None); assert_eq!(tabs.at(area, 6, 1), Some(1));
assert_eq!(tabs.at(area, 10, 1), None);
assert_eq!(tabs.at(area, 2, 0), None);
assert_eq!(tabs.at(area, 1, 1), None);
assert_eq!(drawn(10, 1, tabs), " a bb");
}
#[test]
fn everything_printable_is_a_widget() {
assert_eq!(drawn(4, 1, String::from("hi")), "hi");
assert_eq!(drawn(4, 1, Line::new().push(TEXT, "ok")), "ok");
assert_eq!(drawn(9, 2, Box::new("boxed up") as Box<dyn Widget>), "boxed up\n");
assert_eq!(
drawn(12, 2, Table::new(["a", "b"]).row(["1", "2"])).lines().next(),
Some("a b")
);
assert_eq!(drawn(6, 2, Tree::new("root").leaf("x")).lines().next(), Some("root"));
assert!(drawn(12, 1, Code::new("let x = 1;")).contains("let x"));
assert_eq!(drawn(12, 1, List::new(Vec::<String>::new())), "nothing here");
assert_eq!(drawn(10, 1, hints(&[("q", "quit")])), "q quit");
}
#[test]
fn long_lists_scroll_to_the_selection() {
crate::set_color_mode(crate::ColorMode::None);
let items: Vec<String> = (0..20).map(|i| format!("item {i}")).collect();
let mut f = Frame::new(10, 4);
f.render(f.area(), List::new(items).selected(19));
let shown = f.snapshot().plain();
assert!(shown.contains("› item 19") && !shown.contains("item 15"), "{shown}");
assert!(shown.lines().last().unwrap().ends_with('┃'));
}
#[test]
fn lists_in_panels_too_short_for_them_draw_nothing() {
crate::set_color_mode(crate::ColorMode::None);
let mut f = Frame::new(10, 2);
f.render(f.area(), Panel::new("x").body(List::new(["a", "b"]).selected(1)));
assert_eq!(f.snapshot().plain(), "╭─ x ────╮\n╰────────╯");
}
#[test]
fn wrapping_keeps_every_kind_of_escape_whole() {
let osc = "\x1b]8;;https://x.y\x1b\\link\x1b]8;;\x07";
assert_eq!(wrap(&format!("{osc} b"), 10), [format!("{osc} b")]);
assert_eq!(wrap("a\x1bc b", 10), ["a\x1bc b"]);
assert_eq!(wrap("cut\x1b", 10), ["cut\x1b"]);
assert_eq!(wrap("\x1b[1m \x1b[0m x", 10), ["\x1b[1m\x1b[0mx"]);
}
#[test]
fn widgets_know_their_size() {
crate::set_color_mode(crate::ColorMode::None);
assert_eq!(String::from("ab\ncde").size(), Some((3, 2)));
assert_eq!(Line::new().push(TEXT, "abcd").size(), Some((4, 1)));
assert_eq!(
Block::from(vec![" ab".to_string(), " abc".to_string()]).size(),
Some((3, 2))
);
assert_eq!(Table::new(["n"]).row(["1"]).size(), Some((1, 3)));
assert_eq!(Card::success("x").size(), None);
assert_eq!(Card::success("x").width(20).size().map(|s| s.0), Some(20));
assert_eq!(List::new(["a", "bcd"]).size(), Some((5, 2)));
assert_eq!(List::new(Vec::<String>::new()).size(), Some((18, 1)));
}
#[test]
fn dropping_columns_stops_at_text() {
assert_eq!(drop_columns(" x y", 3), "x y");
assert_eq!(drop_columns(" ", 4), "");
}
#[test]
fn clipping_to_nothing_leaves_no_ellipsis() {
assert_eq!(clip("\x1b[1mbold\x1b[0m", 0), "\x1b[1m\x1b[0m");
}
#[test]
fn panel_counts_are_pills_in_colour() {
let drawn = |focused: bool, title: &str| {
let mut f = Frame::new(30, 3);
let panel = Panel::new(title).count(7).focused(focused);
crate::style::with_color_mode(crate::ColorMode::TrueColor, || f.render(f.area(), panel));
f.snapshot().to_string()
};
assert_ne!(drawn(true, "jobs"), drawn(false, "jobs"));
assert!(drawn(true, "jobs").contains(" 7 "));
let styled = crate::style::with_color_mode(crate::ColorMode::TrueColor, || paint(crate::palette::SAGE, "ok"));
assert!(crate::text::strip_ansi(&drawn(true, &styled)).contains("ok"));
}
#[test]
fn nothing_is_centred_or_scrolled_in_no_room() {
let mut f = Frame::new(4, 2);
centered(&mut f, Rect::new(0, 0, 0, 0), "x");
scrollbar(&mut f, Rect::new(0, 0, 1, 0), 0, 10);
assert_eq!(f.snapshot().plain(), "\n");
assert_eq!(big("1.5").plain().lines().last().map(|l| l.contains('•')), Some(true));
}
#[test]
fn panels_carry_a_status_and_a_footer() {
let styled = crate::style::with_color_mode(crate::ColorMode::TrueColor, || paint(crate::palette::SAGE, "jobs"));
let running =
crate::style::with_color_mode(crate::ColorMode::TrueColor, || paint(crate::palette::ROSE, "2 running"));
let panel = Panel::new(styled).status(running).footer("q quit").focused(false);
let mut f = Frame::new(40, 4);
crate::style::with_color_mode(crate::ColorMode::TrueColor, || f.render(f.area(), panel));
let shown = f.snapshot().plain();
assert!(
shown.contains("jobs") && shown.contains("2 running") && shown.contains("q quit"),
"{shown}"
);
}
#[test]
fn a_short_list_needs_no_scrollbar() {
crate::set_color_mode(crate::ColorMode::None);
let mut f = Frame::new(10, 4);
f.render(f.area(), List::new(["a", "b"]).selected(1));
assert_eq!(f.snapshot().plain(), " a\n› b\n\n");
}
}