use super::cells;
use crate::geometry::{Rect, Size};
use crate::text;
use crate::widget::{MeasureCx, PaintCx, Widget};
const SWATCH: u16 = 2;
const GAP: u16 = 1;
const SPACING: u16 = 2;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Legend {
names: Vec<String>,
tones: Vec<usize>,
vertical: bool,
}
impl Legend {
#[must_use]
pub fn new(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self { names: names.into_iter().map(Into::into).collect(), tones: Vec::new(), vertical: false }
}
#[must_use]
pub fn tones(mut self, tones: impl IntoIterator<Item = usize>) -> Self {
self.tones = tones.into_iter().collect();
self
}
#[must_use]
pub fn vertical(mut self) -> Self {
self.vertical = true;
self
}
fn tone_index(&self, position: usize) -> usize {
self.tones.get(position).copied().unwrap_or(position)
}
fn item_width(name: &str) -> u16 {
cells::sum([SWATCH, GAP, text::width(name)])
}
fn places(&self, width: u16) -> Vec<(u16, u16)> {
let mut places = Vec::with_capacity(self.names.len());
let (mut x, mut y): (u16, u16) = (0, 0);
for name in &self.names {
let item = Self::item_width(name);
if self.vertical {
places.push((0, y));
y = y.saturating_add(1);
continue;
}
if x > 0 && cells::sum([x, item]) > width {
x = 0;
y = y.saturating_add(1);
}
places.push((x, y));
x = cells::sum([x, item, SPACING]);
}
places
}
}
impl<Msg: 'static> Widget<Msg> for Legend {
fn measure(&self, _cx: &mut MeasureCx<'_>, available: Size) -> Size {
if self.names.is_empty() {
return Size::default();
}
let places = self.places(available.width);
let rows = places.last().map_or(0, |(_, y)| y.saturating_add(1));
let width = places
.iter()
.zip(&self.names)
.map(|((x, _), name)| cells::sum([*x, Self::item_width(name)]))
.max()
.unwrap_or(0);
Size::new(width, rows).min(available)
}
fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
if area.is_empty() || self.names.is_empty() {
return;
}
let mut style = cx.style("legend", None, &[]).text();
style.bg = None;
let tones: Vec<crate::color::Rgb> =
(0..self.names.len()).map(|index| cx.env().theme().series_color(self.tone_index(index))).collect();
for ((x, y), (name, tone)) in self.places(area.width).into_iter().zip(self.names.iter().zip(tones)) {
if i32::from(y) >= i32::from(area.height) {
break;
}
let row = area.y + i32::from(y);
let left = area.x + i32::from(x);
let swatch = SWATCH.min(area.width.saturating_sub(x));
cx.fill(Rect::new(left, row, swatch, 1), tone);
let text_x = left + i32::from(swatch) + i32::from(GAP);
let room = area.right().saturating_sub(text_x);
let Ok(room) = u16::try_from(room) else {
continue;
};
if room == 0 {
continue;
}
let shown = text::truncate(name, room);
cx.text(text_x, row, &shown, style, room);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::icons::GlyphMode;
use crate::runtime::{App, Command, Harness};
use crate::widget::{Length, View};
struct Demo(Legend);
impl App for Demo {
type Msg = ();
fn update(&mut self, _: ()) -> Command<()> {
Command::none()
}
fn view(&self, ui: &mut View<'_, ()>) {
ui.add(self.0.clone()).width(Length::Fill(1)).height(Length::Fill(1));
}
}
fn harness(legend: Legend, width: u16, height: u16) -> Harness<Demo> {
Harness::new(Demo(legend), width, height)
}
#[test]
fn names_sit_after_their_series_tone() {
let h = harness(Legend::new(["Rust", "Docs", "Review"]), 40, 1);
assert_eq!(h.screen(), " Rust Docs Review\n");
let theme = h.env().theme();
assert_eq!(h.bg(0, 0), Some(theme.series_color(0)), "the first swatch is the first series tone");
assert_eq!(h.bg(1, 0), Some(theme.series_color(0)), "the swatch is two cells wide");
assert_eq!(h.bg(9, 0), Some(theme.series_color(1)));
assert_eq!(h.bg(18, 0), Some(theme.series_color(2)));
assert_ne!(theme.series_color(0), theme.series_color(1));
}
#[test]
fn a_narrow_area_wraps_and_then_cuts() {
let h = harness(Legend::new(["Rust", "Docs", "Review"]), 18, 3);
assert_eq!(h.screen(), " Rust Docs\n Review\n\n");
let narrow = harness(Legend::new(["Rust", "Docs"]), 10, 2);
assert_eq!(narrow.screen(), " Rust\n Docs\n", "one name a row when only one fits");
let cut = harness(Legend::new(["Refactoring"]), 8, 1);
assert_eq!(cut.screen(), " Refa…\n");
}
#[test]
fn vertical_puts_one_name_on_each_row() {
let h = harness(Legend::new(["Rust", "Docs"]).vertical(), 20, 2);
assert_eq!(h.screen(), " Rust\n Docs\n");
let theme = h.env().theme();
assert_eq!(h.bg(0, 1), Some(theme.series_color(1)));
}
#[test]
fn the_swatch_is_colour_in_every_glyph_mode() {
for mode in [GlyphMode::Nerd, GlyphMode::Unicode, GlyphMode::Ascii] {
let mut h = harness(Legend::new(["Rust"]), 12, 1);
h.set_glyph_mode(mode);
assert_eq!(h.screen(), " Rust\n", "{mode:?}");
assert_eq!(h.bg(0, 0), Some(h.env().theme().series_color(0)), "{mode:?}");
}
}
#[test]
fn pinned_tones_follow_the_category_not_the_position() {
let h = harness(Legend::new(["Docs", "Review"]).tones([1, 2]), 40, 1);
let theme = h.env().theme();
assert_eq!(h.screen(), " Docs Review\n", "the names sit exactly where they always do");
assert_eq!(h.bg(0, 0), Some(theme.series_color(1)), "Docs keeps its own tone without Rust beside it");
assert_eq!(h.bg(9, 0), Some(theme.series_color(2)));
let short = harness(Legend::new(["Docs", "Review"]).tones([4]), 40, 1);
assert_eq!(short.bg(0, 0), Some(theme.series_color(4)));
assert_eq!(short.bg(9, 0), Some(theme.series_color(1)), "a name past the tones keeps its position's tone");
}
#[test]
fn tones_that_match_the_positions_draw_the_same_legend() {
for (width, height) in [(40, 1), (18, 3), (8, 1)] {
let plain = harness(Legend::new(["Rust", "Docs", "Review"]), width, height);
let pinned = harness(Legend::new(["Rust", "Docs", "Review"]).tones([0, 1, 2]), width, height);
assert_eq!(plain.buffer(), pinned.buffer(), "{width}×{height}");
}
}
#[test]
fn nothing_to_name_draws_nothing_and_tiny_areas_survive() {
let empty = harness(Legend::new(Vec::<String>::new()), 10, 1);
assert_eq!(empty.screen(), "\n");
for (width, height) in [(1, 1), (2, 1), (3, 1), (4, 2)] {
let h = harness(Legend::new(["Rust", "Docs"]), width, height);
assert_eq!(h.screen().lines().count(), usize::from(height), "{width}×{height}");
}
}
}