use makeover_layout::{
Act, Awaiting, Bar, Chart, Fact, Field, FieldKind, Figure, Heading, Meter, ThemeVariant, Token,
Tone, Value,
};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use crate::{Palette, text};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct BadgeStyle {
pub fill: Style,
pub edge: Style,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PieceStyle {
pub focus: Modifier,
pub meter_cells: u16,
pub meter_full: char,
pub meter_empty: char,
pub required_marker: &'static str,
pub badge_edges: [&'static str; 2],
}
impl Default for PieceStyle {
fn default() -> Self {
Self {
focus: Modifier::REVERSED,
meter_cells: 10,
meter_full: '#',
meter_empty: '-',
required_marker: "*",
badge_edges: ["\u{258C}", "\u{2590}"],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Ink {
pub content: Style,
pub secondary: Style,
pub muted: Style,
pub info: Style,
pub success: Style,
pub warning: Style,
pub danger: Style,
pub page: Style,
pub section: Style,
pub subsection: Style,
pub action: Style,
pub filled: Style,
pub sunken: Style,
pub badges: [Option<BadgeStyle>; 5],
pub style: PieceStyle,
}
impl Ink {
#[must_use]
pub fn new(palette: &Palette, style: &PieceStyle) -> Self {
let t = &palette.tones;
let fg = |c: Option<Color>| c.map_or(Style::new(), |c| Style::new().fg(c));
let or = |c: Option<Color>, missing: Modifier| match c {
Some(c) => Style::new().fg(c),
None => Style::new().add_modifier(missing),
};
let badge = |fill: Option<Color>, edge: Option<Color>| {
fill.map(|fill| BadgeStyle {
fill: fg(t.content).bg(fill),
edge: fg(edge),
})
};
Self {
content: fg(t.content),
secondary: fg(t.secondary),
muted: or(t.muted, Modifier::DIM),
info: fg(t.info),
success: fg(t.success),
warning: fg(t.warning),
danger: or(t.danger, Modifier::BOLD),
page: fg(t.action).add_modifier(Modifier::BOLD),
section: fg(t.content).add_modifier(Modifier::BOLD),
subsection: fg(t.secondary),
action: or(t.action, Modifier::UNDERLINED),
filled: match t.action {
Some(action) => fg(t.on_action).bg(action),
None => Style::new().add_modifier(Modifier::REVERSED),
},
sunken: match t.sunken {
Some(sunken) => Style::new().bg(sunken),
None => Style::new().add_modifier(Modifier::DIM),
},
badges: [
badge(t.neutral_surface, t.border),
badge(t.info_surface, t.info),
badge(t.success_surface, t.success),
badge(t.warning_surface, t.warning),
badge(t.danger_surface, t.danger),
],
style: *style,
}
}
#[must_use]
pub const fn tone(&self, tone: Tone) -> Style {
match tone {
Tone::Info => self.info,
Tone::Success => self.success,
Tone::Warning => self.warning,
Tone::Danger => self.danger,
_ => self.content,
}
}
#[must_use]
pub const fn badge(&self, tone: Tone) -> Option<BadgeStyle> {
self.badges[match tone {
Tone::Info => 1,
Tone::Success => 2,
Tone::Warning => 3,
Tone::Danger => 4,
_ => 0,
}]
}
#[must_use]
pub const fn heading(&self, level: Heading) -> Style {
match level {
Heading::Page => self.page,
Heading::Section => self.section,
_ => self.subsection,
}
}
#[must_use]
pub fn focused(&self, focused: bool, style: Style) -> Style {
if focused {
style.add_modifier(self.style.focus)
} else {
style
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Progress {
pub delivered: Option<u64>,
pub elapsed: Option<Duration>,
}
#[must_use]
pub fn activity(lit: bool, ink: &Ink) -> Span<'static> {
if lit {
Span::styled(ink.style.meter_full.to_string(), ink.action)
} else {
Span::styled(ink.style.meter_empty.to_string(), ink.muted)
}
}
#[must_use]
pub fn awaiting(awaiting: Awaiting, progress: Progress, lit: bool, ink: &Ink) -> Line<'static> {
let Some(total) = awaiting.amount else {
return Line::from(vec![activity(lit, ink)]);
};
let Some(done) = progress.delivered else {
return Line::from(vec![
activity(lit, ink),
Span::styled(format!(" {total}"), ink.muted),
]);
};
let cells = u32::from(ink.style.meter_cells);
let filled = u32::try_from(
done.saturating_mul(u64::from(cells))
.checked_div(total)
.unwrap_or(0),
)
.unwrap_or(cells)
.min(cells);
let bar = format!(
"{}{}",
ink.style.meter_full.to_string().repeat(filled as usize),
ink.style
.meter_empty
.to_string()
.repeat((cells - filled) as usize)
);
let reading = match progress.elapsed {
Some(elapsed) => format!(" {done}/{total} {}s", elapsed.as_secs()),
None => format!(" {done}/{total}"),
};
Line::from(vec![
Span::styled(bar, ink.action),
Span::styled(reading, ink.muted),
])
}
#[must_use]
pub fn meter(meter: &Meter<'_>, ink: &Ink) -> Line<'static> {
let cells = usize::from(ink.style.meter_cells);
let filled = meter
.done
.checked_mul(cells)
.and_then(|reached| reached.checked_div(meter.total))
.unwrap_or(0)
.min(cells);
let bar = format!(
"{}{}",
ink.style.meter_full.to_string().repeat(filled),
ink.style.meter_empty.to_string().repeat(cells - filled)
);
let reading = match meter.label {
Some(label) => format!(" {}/{} {label}", meter.done, meter.total),
None => format!(" {}/{}", meter.done, meter.total),
};
Line::from(vec![
Span::styled(bar, ink.tone(meter.tone)),
Span::styled(reading, ink.muted),
])
}
#[must_use]
pub fn token(
label: &str,
kind: Token,
tone: Tone,
latched: bool,
focused: bool,
ink: &Ink,
) -> Line<'static> {
let mark = |painted: Style| {
if latched {
painted.add_modifier(ink.style.focus)
} else {
ink.focused(focused, painted)
}
};
match (kind, ink.badge(tone)) {
(Token::Chip { .. }, _) => {
Line::from(Span::styled(format!("[{label}]"), mark(ink.tone(tone))))
}
(Token::Badge, Some(badge)) => {
let [open, close] = ink.style.badge_edges;
let edge = mark(badge.fill.patch(badge.edge));
Line::from(vec![
Span::styled(open, edge),
Span::styled(label.to_owned(), mark(badge.fill)),
Span::styled(close, edge),
])
}
_ => Line::from(Span::styled(format!("({label})"), mark(ink.tone(tone)))),
}
}
#[must_use]
pub fn act(act: &Act<'_>, focused: bool, ink: &Ink) -> Line<'static> {
let painted = if act.disabled() {
ink.muted
} else if act.leading && act.tone == Tone::Neutral {
ink.focused(focused, ink.filled)
} else {
ink.focused(focused, ink.tone(act.tone))
};
let (open, close) = if act.commits { ("[", "]") } else { ("<", ">") };
let label = match act.key {
Some(key) => format!("{open} {} {close} ({key})", act.label),
None => format!("{open} {} {close}", act.label),
};
Line::from(Span::styled(label, painted))
}
#[must_use]
pub fn act_note(act: &Act<'_>, ink: &Ink) -> Option<Line<'static>> {
act.hint
.map(|hint| Line::from(Span::styled(hint.to_owned(), ink.muted)))
}
#[must_use]
pub fn figure_height(figure: &Figure<'_>, width: u16) -> u16 {
text::height(figure.value, width) + text::height(figure.caption, width)
}
pub fn figure(buf: &mut Buffer, area: Rect, figure: &Figure<'_>, ink: &Ink) -> u16 {
let value = match figure.change {
Some(change) => format!("{} {change}", figure.value),
None => figure.value.to_owned(),
};
let used = text::draw(
&value,
ink.tone(figure.tone).add_modifier(Modifier::BOLD),
area,
buf,
);
used + text::draw(figure.caption, ink.muted, below(area, used), buf)
}
#[must_use]
pub fn facts_height(facts: &[Fact<'_>], width: u16) -> u16 {
let label = label_column(facts, width);
let rest = width.saturating_sub(label).saturating_sub(1);
facts
.iter()
.map(|fact| text::height(fact.value, rest).max(1))
.fold(0, u16::saturating_add)
}
fn label_column(facts: &[Fact<'_>], width: u16) -> u16 {
let longest = facts
.iter()
.map(|fact| u16::try_from(text::cells(fact.label)).unwrap_or(u16::MAX))
.max()
.unwrap_or(0);
longest.min(width / 2)
}
pub fn facts(buf: &mut Buffer, area: Rect, facts: &[Fact<'_>], ink: &Ink) -> u16 {
let column = label_column(facts, area.width);
let mut used = 0;
for fact in facts {
if used >= area.height {
break;
}
let line = below(area, used);
let mut label = String::new();
let mut taken = 0;
for c in fact.label.chars() {
let wide = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
if taken + wide > usize::from(column) {
break;
}
taken += wide;
label.push(c);
}
label.extend(std::iter::repeat_n(
' ',
usize::from(column).saturating_sub(taken),
));
text::draw(&label, ink.muted, line, buf);
let values = Rect {
x: line.x.saturating_add(column).saturating_add(1),
width: line.width.saturating_sub(column).saturating_sub(1),
..line
};
used += text::draw(fact.value, ink.content, values, buf).max(1);
}
used
}
#[must_use]
pub fn field_height(field: &Field<'_>, width: u16, ink: &Ink) -> u16 {
if !field.kind.visible() {
return 0;
}
let label = text::height(&field.marked_label(ink.style.required_marker), width);
let body = match field.kind {
kind if kind.multiline() => 3,
kind if kind.offers_options() => u16::try_from(field.options.len()).unwrap_or(u16::MAX),
kind if kind.offers_themes() => {
let mut variants = 0u16;
let mut open: Option<ThemeVariant> = None;
for theme in field.themes {
if open != Some(theme.variant) {
variants = variants.saturating_add(1);
open = Some(theme.variant);
}
}
let rows = u16::try_from(field.themes.len()).unwrap_or(u16::MAX);
rows.saturating_add(variants)
.saturating_add(u16::from(field.follows.is_some()))
}
_ => 1,
};
let note = message_of(ink, field).map_or(0, |(text, _)| text::height(text, width));
label + body + note
}
pub fn field(
buf: &mut Buffer,
area: Rect,
field: &Field<'_>,
held: Value<'_>,
focused: bool,
ink: &Ink,
) -> u16 {
field_at(buf, area, field, held, focused, None, ink)
}
pub fn field_at(
buf: &mut Buffer,
area: Rect,
field: &Field<'_>,
held: Value<'_>,
focused: bool,
cursor: Option<usize>,
ink: &Ink,
) -> u16 {
if !field.kind.visible() || area.width == 0 || area.height == 0 {
return 0;
}
let mut used = text::draw(
&field.marked_label(ink.style.required_marker),
ink.secondary,
area,
buf,
);
let well = ink.focused(focused, ink.content);
let placeholder = field.placeholder.unwrap_or_default();
used += match field.kind {
FieldKind::Checkbox => text::draw(
if matches!(held, Value::On(true)) {
"[x]"
} else {
"[ ]"
},
well,
below(area, used),
buf,
),
FieldKind::Range if field.bounded() => {
let line = range_line(ink, field, held.as_text(), well);
text::draw_line(&line, below(area, used), buf)
}
FieldKind::Interval => {
let line = interval_line(ink, field, held, well);
text::draw_line(&line, below(area, used), buf)
}
kind if kind.offers_themes() => {
let mut rows = 0;
if let Some(follow) = field.follows {
let chosen = held.as_text() == follow.value;
let (mark, painted) = if chosen {
("(*)", well)
} else {
("( )", ink.secondary)
};
rows += text::draw(
&format!("{mark} {}", follow.label),
painted,
below(area, used + rows),
buf,
);
}
let mut open: Option<ThemeVariant> = None;
for theme in field.themes {
if open != Some(theme.variant) {
rows += text::draw(
theme.variant.heading(),
ink.muted,
below(area, used + rows),
buf,
);
open = Some(theme.variant);
}
let chosen = held.as_text() == theme.id;
let (mark, painted) = if chosen {
("(*)", well)
} else {
("( )", ink.secondary)
};
rows += text::draw(
&format!("{mark} {} [{}]", theme.name, theme.contrast.badge()),
painted,
below(area, used + rows),
buf,
);
}
rows
}
kind if kind.offers_options() => {
let several = kind.takes_several();
let (open, ticked) = if several {
("[ ]", "[x]")
} else {
("( )", "(*)")
};
let walking = focused && cursor.is_some();
let marked = if walking { ink.content } else { well };
let mut rows = 0;
for (index, choice) in field.options.iter().enumerate() {
let chosen = choice.chosen || (!several && held.as_text() == choice.value);
let walked = walking && cursor == Some(index);
let (mark, painted, suffix) = match choice.unavailable {
Some(reason) => (open, ink.muted, format!(": {reason}")),
None if chosen => (ticked, marked, String::new()),
None => (open, ink.secondary, String::new()),
};
rows += text::draw(
&format!("{mark} {}{suffix}", choice.label),
ink.focused(walked, painted),
below(area, used + rows),
buf,
);
if let Some(detail) = choice.detail {
rows += text::draw(detail, ink.muted, indented(area, used + rows), buf);
}
}
rows
}
FieldKind::Secret if !held.as_text().is_empty() => {
let dots = "*".repeat(held.as_text().chars().count());
text::draw(&dots, well, below(area, used), buf).max(1)
}
_ if held.as_text().is_empty() => {
empty_well(ink, placeholder, well, focused, below(area, used), buf)
}
_ => text::draw(
&measured(field, held.as_text()),
well,
below(area, used),
buf,
),
};
match message_of(ink, field) {
Some((text, painted)) => used + text::draw(text, painted, below(area, used), buf),
None => used,
}
}
fn range_line(ink: &Ink, field: &Field<'_>, value: &str, well: Style) -> Line<'static> {
let cells = usize::from(ink.style.meter_cells);
let ends = field
.min
.zip(field.max)
.and_then(|(min, max)| Some((min.parse::<f64>().ok()?, max.parse::<f64>().ok()?)));
let filled = match (ends, value.parse::<f64>()) {
(Some((min, max)), Ok(number)) if max > min => {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "`position_of` returns 0..=1, and the cell count came from a u16"
)]
let reached = (field.curve.position_of(number, min, max) * cells as f64) as usize;
reached.min(cells)
}
_ => 0,
};
let bar = format!(
"{}{}",
ink.style.meter_full.to_string().repeat(filled),
ink.style.meter_empty.to_string().repeat(cells - filled)
);
Line::from(vec![
Span::styled(format!("{} ", field.min.unwrap_or_default()), ink.muted),
Span::styled(bar, well),
Span::styled(format!(" {}", field.max.unwrap_or_default()), ink.muted),
Span::styled(format!(" {}", measured(field, value)), well),
])
}
fn interval_line(ink: &Ink, field: &Field<'_>, held: Value<'_>, well: Style) -> Line<'static> {
let end = |value: &str, fallback: Option<&str>| match (value.is_empty(), fallback) {
(false, _) => Span::styled(measured(field, value), well),
(true, Some(bound)) => Span::styled(measured(field, bound), ink.muted),
(true, None) => Span::styled(String::new(), ink.muted),
};
Line::from(vec![
end(held.as_text(), field.min),
Span::styled(" to ", ink.secondary),
end(held.upper_text(), field.max),
])
}
fn measured(field: &Field<'_>, value: &str) -> String {
match field.shown_unit() {
Some(unit) => format!("{value} {unit}"),
None => value.to_owned(),
}
}
fn message_of<'a>(ink: &Ink, field: &Field<'a>) -> Option<(&'a str, Style)> {
if let Some(error) = field.error {
return Some((error, ink.danger));
}
if let Some((tone, note)) = field.note {
return Some((note, ink.tone(tone)));
}
field.hint.map(|hint| (hint, ink.muted))
}
fn empty_well(
ink: &Ink,
placeholder: &str,
well: Style,
focused: bool,
area: Rect,
buf: &mut Buffer,
) -> u16 {
let used = text::draw(placeholder, ink.muted, area, buf).max(1);
if focused
&& area.height > 0
&& area.width > 0
&& let Some(cell) = buf.cell_mut((area.x, area.y))
{
cell.set_style(well);
}
used
}
fn indented(area: Rect, used: u16) -> Rect {
const MARK: u16 = 4;
let area = below(area, used);
Rect {
x: area.x + MARK.min(area.width),
width: area.width.saturating_sub(MARK),
..area
}
}
fn below(area: Rect, used: u16) -> Rect {
let used = used.min(area.height);
Rect {
x: area.x,
y: area.y + used,
width: area.width,
height: area.height - used,
}
}
#[cfg(test)]
mod tests;
#[must_use]
pub fn chart(chart: &Chart<'_>, bars: &[Bar<'_>], ink: &Ink) -> Vec<Line<'static>> {
let widest = bars
.iter()
.map(|bar| text::cells(bar.at))
.max()
.unwrap_or(0);
bars.iter()
.map(|bar| chart_line(ink, chart, bar, widest))
.collect()
}
fn chart_line(ink: &Ink, chart: &Chart<'_>, bar: &Bar<'_>, widest: usize) -> Line<'static> {
let cells = usize::from(ink.style.meter_cells);
let filled = if chart.most == 0 {
0
} else {
let scaled = (bar.value as u128 * cells as u128).div_ceil(chart.most as u128);
(scaled as usize).min(cells)
};
let mut spans = vec![Span::styled(
format!(
"{}{} ",
bar.at,
" ".repeat(widest.saturating_sub(text::cells(bar.at)))
),
ink.secondary,
)];
spans.push(Span::styled(
format!(
"{}{}",
ink.style.meter_full.to_string().repeat(filled),
ink.style.meter_empty.to_string().repeat(cells - filled)
),
ink.tone(chart.tone),
));
if let Some(reading) = chart_reading(bar) {
spans.push(Span::styled(reading, ink.muted));
}
Line::from(spans)
}
fn chart_reading(bar: &Bar<'_>) -> Option<String> {
match (bar.reading, bar.note) {
(Some(reading), Some(note)) => Some(format!(" {reading} / {note}")),
(Some(only), None) | (None, Some(only)) => Some(format!(" {only}")),
(None, None) => None,
}
}