use super::{DEFAULT_FULL_CHAR_HALF_BLOCK, Model, blend, clamp_percent};
use crate::style::{Color, Style, round_clamped, to_f64, width};
impl Model {
#[must_use]
pub fn view(&self) -> String {
self.view_as(self.shown)
}
#[must_use]
pub fn view_as(&self, percent: f64) -> String {
let percent = clamp_percent(percent);
let label = self.percentage_view(percent);
self.bar_view(percent, width(&label)) + &label
}
fn bar_view(&self, percent: f64, label: usize) -> String {
let total = self.width.saturating_sub(label);
let filled = round_clamped(to_f64(total) * percent, total);
let half = self.full == DEFAULT_FULL_CHAR_HALF_BLOCK;
let mut out = if let Some(f) = &self.color_fn {
colored_cells(self.full, filled, total, half, |t| f(percent, t))
} else if self.blend.is_empty() {
Style::new()
.foreground(self.full_color)
.paint(&self.full.to_string().repeat(filled))
} else {
self.blend_cells(filled, total, half)
};
let empty = self.empty.to_string().repeat(total - filled);
out += &Style::new().foreground(self.empty_color).paint(&empty);
out
}
fn blend_cells(&self, filled: usize, total: usize, half: bool) -> String {
let per = if half { 2 } else { 1 };
let span = if self.scale_blend { filled } else { total };
let colors = blend::blend_1d(span * per, &self.blend);
let full = self.full.to_string();
(0..filled)
.map(|i| {
let style = Style::new().foreground(colors[i * per]);
let style = if half {
style.background(colors[i * per + 1])
} else {
style
};
style.paint(&full)
})
.collect()
}
fn percentage_view(&self, percent: f64) -> String {
if !self.show_percentage {
return String::new();
}
self.percentage_style
.paint(&(self.percent_format)(percent * 100.0))
}
}
fn colored_cells(
full: char,
filled: usize,
total: usize,
half: bool,
color: impl Fn(f64) -> Color,
) -> String {
let step = 0.5 / to_f64(total);
(0..filled)
.map(|i| {
let current = to_f64(i) / to_f64(total);
let style = Style::new().foreground(color(current));
let style = if half {
style.background(color((current + step).min(1.0)))
} else {
style
};
style.paint(&full.to_string())
})
.collect()
}
impl std::fmt::Debug for Model {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Model")
.field("full", &self.full)
.field("full_color", &self.full_color)
.field("empty", &self.empty)
.field("empty_color", &self.empty_color)
.field("show_percentage", &self.show_percentage)
.field("percent_format", &super::super::Opaque)
.field("percentage_style", &self.percentage_style)
.field("id", &self.id)
.field("tag", &self.tag)
.field("width", &self.width)
.field("spring", &self.spring)
.field("shown", &self.shown)
.field("target", &self.target)
.field("velocity", &self.velocity)
.field("blend", &self.blend)
.field("scale_blend", &self.scale_blend)
.field("color_fn", &super::super::opaque(self.color_fn.as_ref()))
.finish()
}
}