1use super::cells;
4use crate::geometry::{Rect, Size};
5use crate::text;
6use crate::widget::{MeasureCx, PaintCx, Widget};
7
8const SWATCH: u16 = 2;
10
11const GAP: u16 = 1;
13
14const SPACING: u16 = 2;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Legend {
38 names: Vec<String>,
39 tones: Vec<usize>,
40 vertical: bool,
41}
42
43impl Legend {
44 #[must_use]
46 pub fn new(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
47 Self { names: names.into_iter().map(Into::into).collect(), tones: Vec::new(), vertical: false }
48 }
49
50 #[must_use]
54 pub fn tones(mut self, tones: impl IntoIterator<Item = usize>) -> Self {
55 self.tones = tones.into_iter().collect();
56 self
57 }
58
59 #[must_use]
61 pub fn vertical(mut self) -> Self {
62 self.vertical = true;
63 self
64 }
65
66 fn tone_index(&self, position: usize) -> usize {
68 self.tones.get(position).copied().unwrap_or(position)
69 }
70
71 fn item_width(name: &str) -> u16 {
73 cells::sum([SWATCH, GAP, text::width(name)])
74 }
75
76 fn places(&self, width: u16) -> Vec<(u16, u16)> {
81 let mut places = Vec::with_capacity(self.names.len());
82 let (mut x, mut y): (u16, u16) = (0, 0);
83 for name in &self.names {
84 let item = Self::item_width(name);
85 if self.vertical {
86 places.push((0, y));
87 y = y.saturating_add(1);
88 continue;
89 }
90 if x > 0 && cells::sum([x, item]) > width {
91 x = 0;
92 y = y.saturating_add(1);
93 }
94 places.push((x, y));
95 x = cells::sum([x, item, SPACING]);
96 }
97 places
98 }
99}
100
101impl<Msg: 'static> Widget<Msg> for Legend {
102 fn measure(&self, _cx: &mut MeasureCx<'_>, available: Size) -> Size {
103 if self.names.is_empty() {
104 return Size::default();
105 }
106 let places = self.places(available.width);
107 let rows = places.last().map_or(0, |(_, y)| y.saturating_add(1));
108 let width = places
109 .iter()
110 .zip(&self.names)
111 .map(|((x, _), name)| cells::sum([*x, Self::item_width(name)]))
112 .max()
113 .unwrap_or(0);
114 Size::new(width, rows).min(available)
115 }
116
117 fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
118 if area.is_empty() || self.names.is_empty() {
119 return;
120 }
121 let mut style = cx.style("legend", None, &[]).text();
122 style.bg = None;
123 let tones: Vec<crate::color::Rgb> =
124 (0..self.names.len()).map(|index| cx.env().theme().series_color(self.tone_index(index))).collect();
125 for ((x, y), (name, tone)) in self.places(area.width).into_iter().zip(self.names.iter().zip(tones)) {
126 if i32::from(y) >= i32::from(area.height) {
127 break;
128 }
129 let row = area.y + i32::from(y);
130 let left = area.x + i32::from(x);
131 let swatch = SWATCH.min(area.width.saturating_sub(x));
132 cx.fill(Rect::new(left, row, swatch, 1), tone);
133 let text_x = left + i32::from(swatch) + i32::from(GAP);
134 let room = area.right().saturating_sub(text_x);
135 let Ok(room) = u16::try_from(room) else {
136 continue;
137 };
138 if room == 0 {
139 continue;
140 }
141 let shown = text::truncate(name, room);
142 cx.text(text_x, row, &shown, style, room);
143 }
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use crate::icons::GlyphMode;
151 use crate::runtime::{App, Command, Harness};
152 use crate::widget::{Length, View};
153
154 struct Demo(Legend);
155
156 impl App for Demo {
157 type Msg = ();
158 fn update(&mut self, _: ()) -> Command<()> {
159 Command::none()
160 }
161 fn view(&self, ui: &mut View<'_, ()>) {
162 ui.add(self.0.clone()).width(Length::Fill(1)).height(Length::Fill(1));
163 }
164 }
165
166 fn harness(legend: Legend, width: u16, height: u16) -> Harness<Demo> {
167 Harness::new(Demo(legend), width, height)
168 }
169
170 #[test]
171 fn names_sit_after_their_series_tone() {
172 let h = harness(Legend::new(["Rust", "Docs", "Review"]), 40, 1);
173 assert_eq!(h.screen(), " Rust Docs Review\n");
174 let theme = h.env().theme();
175 assert_eq!(h.bg(0, 0), Some(theme.series_color(0)), "the first swatch is the first series tone");
176 assert_eq!(h.bg(1, 0), Some(theme.series_color(0)), "the swatch is two cells wide");
177 assert_eq!(h.bg(9, 0), Some(theme.series_color(1)));
178 assert_eq!(h.bg(18, 0), Some(theme.series_color(2)));
179 assert_ne!(theme.series_color(0), theme.series_color(1));
180 }
181
182 #[test]
183 fn a_narrow_area_wraps_and_then_cuts() {
184 let h = harness(Legend::new(["Rust", "Docs", "Review"]), 18, 3);
185 assert_eq!(h.screen(), " Rust Docs\n Review\n\n");
186 let narrow = harness(Legend::new(["Rust", "Docs"]), 10, 2);
187 assert_eq!(narrow.screen(), " Rust\n Docs\n", "one name a row when only one fits");
188 let cut = harness(Legend::new(["Refactoring"]), 8, 1);
189 assert_eq!(cut.screen(), " Refa…\n");
190 }
191
192 #[test]
193 fn vertical_puts_one_name_on_each_row() {
194 let h = harness(Legend::new(["Rust", "Docs"]).vertical(), 20, 2);
195 assert_eq!(h.screen(), " Rust\n Docs\n");
196 let theme = h.env().theme();
197 assert_eq!(h.bg(0, 1), Some(theme.series_color(1)));
198 }
199
200 #[test]
201 fn the_swatch_is_colour_in_every_glyph_mode() {
202 for mode in [GlyphMode::Nerd, GlyphMode::Unicode, GlyphMode::Ascii] {
203 let mut h = harness(Legend::new(["Rust"]), 12, 1);
204 h.set_glyph_mode(mode);
205 assert_eq!(h.screen(), " Rust\n", "{mode:?}");
206 assert_eq!(h.bg(0, 0), Some(h.env().theme().series_color(0)), "{mode:?}");
207 }
208 }
209
210 #[test]
211 fn pinned_tones_follow_the_category_not_the_position() {
212 let h = harness(Legend::new(["Docs", "Review"]).tones([1, 2]), 40, 1);
213 let theme = h.env().theme();
214 assert_eq!(h.screen(), " Docs Review\n", "the names sit exactly where they always do");
215 assert_eq!(h.bg(0, 0), Some(theme.series_color(1)), "Docs keeps its own tone without Rust beside it");
216 assert_eq!(h.bg(9, 0), Some(theme.series_color(2)));
217 let short = harness(Legend::new(["Docs", "Review"]).tones([4]), 40, 1);
218 assert_eq!(short.bg(0, 0), Some(theme.series_color(4)));
219 assert_eq!(short.bg(9, 0), Some(theme.series_color(1)), "a name past the tones keeps its position's tone");
220 }
221
222 #[test]
223 fn tones_that_match_the_positions_draw_the_same_legend() {
224 for (width, height) in [(40, 1), (18, 3), (8, 1)] {
225 let plain = harness(Legend::new(["Rust", "Docs", "Review"]), width, height);
226 let pinned = harness(Legend::new(["Rust", "Docs", "Review"]).tones([0, 1, 2]), width, height);
227 assert_eq!(plain.buffer(), pinned.buffer(), "{width}×{height}");
228 }
229 }
230
231 #[test]
232 fn nothing_to_name_draws_nothing_and_tiny_areas_survive() {
233 let empty = harness(Legend::new(Vec::<String>::new()), 10, 1);
234 assert_eq!(empty.screen(), "\n");
235 for (width, height) in [(1, 1), (2, 1), (3, 1), (4, 2)] {
236 let h = harness(Legend::new(["Rust", "Docs"]), width, height);
237 assert_eq!(h.screen().lines().count(), usize::from(height), "{width}×{height}");
238 }
239 }
240}