Debian Codegraph @

src/canvas/components/time_series/vendored.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //! A [`ratatui::widgets::Chart`] but slightly more specialized to show
2 //! right-aligned time_series data.
3 //!
4 //! Generally should be updated to be in sync with [`chart.rs`](https://github.com/ratatui-org/ratatui/blob/main/src/widgets/chart.rs);
5 //! the specializations are factored out to `time_series/points.rs`.
6
7 mod canvas;
8 mod grid;
9 mod points;
10
11 use std::{
12 cmp::{max, min},
13 str::FromStr,
14 time::Instant,
15 };
16
17 use canvas::*;
18 use ratatui::{
19 buffer::Buffer,
20 layout::{Alignment, Constraint, Flex, Layout, Rect},
21 style::{Color, Style, Styled},
22 symbols::{self, Marker},
23 text::{Line, Span},
24 widgets::{Block, BlockExt, Borders, GraphType, Widget},
25 };
26 use timeless::data::ChunkedData;
27 use unicode_width::UnicodeWidthStr;
28
29 use crate::{
30 canvas::components::time_series::LegendConstraints,
31 utils::general::{saturating_log2, saturating_log10},
32 };
33
34 pub const DEFAULT_LEGEND_CONSTRAINTS: LegendConstraints = LegendConstraints {
35 width: Constraint::Ratio(1, 4),
36 height: Constraint::Length(4),
37 };
38
39 /// A single graph point.
40 pub type Point = (f64, f64);
41
42 /// An axis bound type. Allows us to save a f64 since we know that we are
43 /// usually bound from some values [0.0, a], or [-b, 0.0].
44 #[derive(Debug, Default, Clone, Copy, PartialEq)]
45 pub enum AxisBound {
46 /// Just 0.
47 #[default]
48 Zero,
49 /// Bound by a minimum value to 0.
50 Min(f64),
51 /// Bound by 0 and a max value.
52 Max(f64),
53 }
54
55 impl AxisBound {
56 fn get_bounds(&self) -> [f64; 2] {
57 match self {
58 AxisBound::Zero => [0.0, 0.0],
59 AxisBound::Min(min) => [*min, 0.0],
60 AxisBound::Max(max) => [0.0, *max],
61 }
62 }
63 }
64
65 /// An X or Y axis for the [`TimeChart`] widget
66 #[derive(Debug, Default, Clone, PartialEq)]
67 pub struct Axis<'a> {
68 /// Title displayed next to axis end
69 pub(crate) title: Option<Line<'a>>,
70 /// Bounds for the axis (all data points outside these limits will not be
71 /// represented)
72 pub(crate) bounds: AxisBound,
73 /// A list of labels to put to the left or below the axis
74 pub(crate) labels: Option<Vec<Span<'a>>>,
75 /// The style used to draw the axis itself
76 pub(crate) style: Style,
77 /// The alignment of the labels of the Axis
78 pub(crate) labels_alignment: Alignment,
79 }
80
81 impl<'a> Axis<'a> {
82 /// Sets the axis title
83 ///
84 /// It will be displayed at the end of the axis. For an X axis this is the
85 /// right, for a Y axis, this is the top.
86 #[must_use = "method moves the value of self and returns the modified value"]
87 #[cfg_attr(not(test), expect(dead_code))]
88 pub fn title<T>(mut self, title: T) -> Axis<'a>
89 where
90 T: Into<Line<'a>>,
91 {
92 self.title = Some(title.into());
93 self
94 }
95
96 /// Sets the bounds of this axis.
97 #[must_use = "method moves the value of self and returns the modified value"]
98 pub fn bounds(mut self, bounds: AxisBound) -> Axis<'a> {
99 self.bounds = bounds;
100 self
101 }
102
103 /// Sets the axis labels
104 ///
105 /// - For the X axis, the labels are displayed left to right.
106 /// - For the Y axis, the labels are displayed bottom to top.
107 #[must_use = "method moves the value of self and returns the modified value"]
108 pub fn labels(mut self, labels: Vec<Span<'a>>) -> Axis<'a> {
109 self.labels = Some(labels);
110 self
111 }
112
113 /// Sets the axis style.
114 #[must_use = "method moves the value of self and returns the modified value"]
115 pub fn style<S: Into<Style>>(mut self, style: S) -> Axis<'a> {
116 self.style = style.into();
117 self
118 }
119
120 /// Sets the labels alignment of the axis
121 ///
122 /// The alignment behaves differently based on the axis:
123 /// - Y axis: The labels are aligned within the area on the left of the axis
124 /// - X axis: The first X-axis label is aligned relative to the Y-axis
125 ///
126 /// On the X axis, this parameter only affects the first label.
127 #[must_use = "method moves the value of self and returns the modified value"]
128 #[expect(dead_code)]
129 pub fn labels_alignment(mut self, alignment: Alignment) -> Axis<'a> {
130 self.labels_alignment = alignment;
131 self
132 }
133 }
134
135 /// Allow users to specify the position of a legend in a [`TimeChart`]
136 ///
137 /// See [`TimeChart::legend_position`]
138 #[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
139 pub enum LegendPosition {
140 /// Legend is centered on top
141 Top,
142 /// Legend is in the top-right corner. This is the **default**.
143 #[default]
144 TopRight,
145 /// Legend is in the top-left corner
146 TopLeft,
147 /// Legend is centered on the left
148 Left,
149 /// Legend is centered on the right
150 Right,
151 /// Legend is centered on the bottom
152 Bottom,
153 /// Legend is in the bottom-right corner
154 BottomRight,
155 /// Legend is in the bottom-left corner
156 BottomLeft,
157 }
158
159 impl LegendPosition {
160 fn layout(
161 &self, area: Rect, legend_width: u16, legend_height: u16, x_title_width: u16,
162 y_title_width: u16,
163 ) -> Option<Rect> {
164 let mut height_margin = (area.height - legend_height) as i32;
165 if x_title_width != 0 {
166 height_margin -= 1;
167 }
168 if y_title_width != 0 {
169 height_margin -= 1;
170 }
171 if height_margin < 0 {
172 return None;
173 };
174
175 let (x, y) = match self {
176 Self::TopRight => {
177 if legend_width + y_title_width > area.width {
178 (area.right() - legend_width, area.top() + 1)
179 } else {
180 (area.right() - legend_width, area.top())
181 }
182 }
183 Self::TopLeft => {
184 if y_title_width != 0 {
185 (area.left(), area.top() + 1)
186 } else {
187 (area.left(), area.top())
188 }
189 }
190 Self::Top => {
191 let x = (area.width - legend_width) / 2;
192 if area.left() + y_title_width > x {
193 (area.left() + x, area.top() + 1)
194 } else {
195 (area.left() + x, area.top())
196 }
197 }
198 Self::Left => {
199 let mut y = (area.height - legend_height) / 2;
200 if y_title_width != 0 {
201 y += 1;
202 }
203 if x_title_width != 0 {
204 y = y.saturating_sub(1);
205 }
206 (area.left(), area.top() + y)
207 }
208 Self::Right => {
209 let mut y = (area.height - legend_height) / 2;
210 if y_title_width != 0 {
211 y += 1;
212 }
213 if x_title_width != 0 {
214 y = y.saturating_sub(1);
215 }
216 (area.right() - legend_width, area.top() + y)
217 }
218 Self::BottomLeft => {
219 if x_title_width + legend_width > area.width {
220 (area.left(), area.bottom() - legend_height - 1)
221 } else {
222 (area.left(), area.bottom() - legend_height)
223 }
224 }
225 Self::BottomRight => {
226 if x_title_width != 0 {
227 (
228 area.right() - legend_width,
229 area.bottom() - legend_height - 1,
230 )
231 } else {
232 (area.right() - legend_width, area.bottom() - legend_height)
233 }
234 }
235 Self::Bottom => {
236 let x = area.left() + (area.width - legend_width) / 2;
237 if x + legend_width > area.right() - x_title_width {
238 (x, area.bottom() - legend_height - 1)
239 } else {
240 (x, area.bottom() - legend_height)
241 }
242 }
243 };
244
245 Some(Rect::new(x, y, legend_width, legend_height))
246 }
247 }
248
249 #[derive(Debug, PartialEq)]
250 pub struct ParseLegendPositionError;
251
252 impl FromStr for LegendPosition {
253 type Err = ParseLegendPositionError;
254
255 fn from_str(s: &str) -> Result<Self, Self::Err> {
256 match s {
257 "top" => Ok(Self::Top),
258 "top-left" => Ok(Self::TopLeft),
259 "top-right" => Ok(Self::TopRight),
260 "left" => Ok(Self::Left),
261 "right" => Ok(Self::Right),
262 "bottom-left" => Ok(Self::BottomLeft),
263 "bottom" => Ok(Self::Bottom),
264 "bottom-right" => Ok(Self::BottomRight),
265 _ => Err(ParseLegendPositionError),
266 }
267 }
268 }
269
270 #[derive(Debug, Default, Clone)]
271 enum Data<'a, F> {
272 Some {
273 times: &'a [Instant],
274 values: &'a ChunkedData<F>,
275 },
276 #[default]
277 None,
278 }
279
280 /// A group of data points
281 ///
282 /// This is the main element composing a [`TimeChart`].
283 ///
284 /// A dataset can be [named](Dataset::name). Only named datasets will be
285 /// rendered in the legend.
286 #[derive(Debug, Default, Clone)]
287 pub struct Dataset<'a, F: Copy + Default + Into<f64> = f64> {
288 /// Name of the dataset (used in the legend if shown)
289 name: Option<Line<'a>>,
290 /// A reference to data.
291 data: Data<'a, F>,
292 /// Symbol used for each points of this dataset
293 marker: symbols::Marker,
294 /// Determines graph type used for drawing points
295 graph_type: GraphType,
296 /// Style used to plot this dataset
297 style: Style,
298 }
299
300 impl<'a, F: Copy + Default + Into<f64>> Dataset<'a, F> {
301 /// Sets the name of the dataset.
302 #[must_use = "method moves the value of self and returns the modified value"]
303 pub fn name<S>(mut self, name: S) -> Dataset<'a, F>
304 where
305 S: Into<Line<'a>>,
306 {
307 self.name = Some(name.into());
308 self
309 }
310
311 /// Sets the data points of this dataset
312 ///
313 /// Points will then either be rendered as scattered points or with lines
314 /// between them depending on [`Dataset::graph_type`].
315 ///
316 /// Data consist in an array of `f64` tuples (`(f64, f64)`), the first
317 /// element being X and the second Y. It's also worth noting that,
318 /// unlike the [`Rect`], here the Y axis is bottom to top, as in math.
319 #[must_use = "method moves the value of self and returns the modified value"]
320 pub fn data(mut self, times: &'a [Instant], values: &'a ChunkedData<F>) -> Dataset<'a, F> {
321 self.data = Data::Some { times, values };
322 self
323 }
324
325 /// Sets the kind of character to use to display this dataset
326 ///
327 /// You can use dots (`•`), blocks (`█`), bars (`▄`), braille (`⠓`, `⣇`,
328 /// `⣿`) or half-blocks (`█`, `▄`, and `▀`). See [symbols::Marker] for
329 /// more details.
330 ///
331 /// Note [`Marker::Braille`] requires a font that supports Unicode Braille
332 /// Patterns.
333 #[must_use = "method moves the value of self and returns the modified value"]
334 #[expect(dead_code)]
335 pub fn marker(mut self, marker: symbols::Marker) -> Dataset<'a, F> {
336 self.marker = marker;
337 self
338 }
339
340 /// Sets how the dataset should be drawn
341 ///
342 /// [`TimeChart`] can draw either a [scatter](GraphType::Scatter) or
343 /// [line](GraphType::Line) charts. A scatter will draw only the points
344 /// in the dataset while a line will also draw a line between them. See
345 /// [`GraphType`] for more details
346 #[must_use = "method moves the value of self and returns the modified value"]
347 pub fn graph_type(mut self, graph_type: GraphType) -> Dataset<'a, F> {
348 self.graph_type = graph_type;
349 self
350 }
351
352 /// Sets the style of this dataset
353 ///
354 /// The given style will be used to draw the legend and the data points.
355 /// Currently the legend will use the entire style whereas the data
356 /// points will only use the foreground.
357 ///
358 /// `style` accepts any type that is convertible to [`Style`] (e.g.
359 /// [`Style`], [`Color`], or your own type that implements
360 /// [`Into<Style>`]).
361 #[must_use = "method moves the value of self and returns the modified value"]
362 pub fn style<S: Into<Style>>(mut self, style: S) -> Dataset<'a, F> {
363 self.style = style.into();
364 self
365 }
366 }
367
368 /// A container that holds all the infos about where to display each elements of
369 /// the chart (axis, labels, legend, ...).
370 #[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
371 struct ChartLayout {
372 /// Location of the title of the x axis
373 title_x: Option<(u16, u16)>,
374 /// Location of the title of the y axis
375 title_y: Option<(u16, u16)>,
376 /// Location of the first label of the x axis
377 label_x: Option<u16>,
378 /// Location of the first label of the y axis
379 label_y: Option<u16>,
380 /// Y coordinate of the horizontal axis
381 axis_x: Option<u16>,
382 /// X coordinate of the vertical axis
383 axis_y: Option<u16>,
384 /// Area of the legend
385 legend_area: Option<Rect>,
386 /// Area of the graph
387 graph_area: Rect,
388 }
389
390 /// Whether to additionally scale all values before displaying them. Defaults to
391 /// none.
392 #[derive(Default, Debug, Clone, Copy)]
393 pub(crate) enum ChartScaling {
394 #[default]
395 Linear,
396 Log10,
397 Log2,
398 }
399
400 impl ChartScaling {
401 /// Scale a value.
402 pub(super) fn scale(&self, value: f64) -> f64 {
403 // Remember to do saturating log checks as otherwise 0.0 becomes inf, and you
404 // get gaps!
405 match self {
406 ChartScaling::Linear => value,
407 ChartScaling::Log10 => saturating_log10(value),
408 ChartScaling::Log2 => saturating_log2(value),
409 }
410 }
411 }
412
413 /// A "custom" chart, just a slightly tweaked [`ratatui::widgets::Chart`] from
414 /// ratatui, but with greater control over the legend, and built with the idea
415 /// of drawing data points relative to a time-based x-axis.
416 ///
417 /// Main changes:
418 /// - Styling option for the legend box
419 /// - Automatically trimming out redundant draws in the x-bounds.
420 /// - Automatic interpolation to points that fall *just* outside of the screen.
421 #[derive(Debug, Default, Clone)]
422 pub(super) struct TimeChart<'a, F: Copy + Default + Into<f64> = f64> {
423 /// A block to display around the widget eventually
424 block: Option<Block<'a>>,
425 /// The horizontal axis
426 x_axis: Axis<'a>,
427 /// The vertical axis
428 y_axis: Axis<'a>,
429 /// A reference to the datasets
430 datasets: Vec<Dataset<'a, F>>,
431 /// The widget base style
432 style: Style,
433 /// The legend's style.
434 legend_style: Style,
435 /// Constraints used to determine whether the legend should be shown or not.
436 hidden_legend_constraints: (Constraint, Constraint),
437 /// The position determining whether the length is shown or hidden,
438 /// regardless of `hidden_legend_constraints`
439 legend_position: Option<LegendPosition>,
440 /// The marker type.
441 marker: Marker,
442 /// Whether to scale the values differently.
443 scaling: ChartScaling,
444 }
445
446 impl<'a, F: Copy + Default + Into<f64>> TimeChart<'a, F> {
447 /// Creates a chart with the given [datasets](Dataset).
448 pub fn new(datasets: Vec<Dataset<'a, F>>) -> TimeChart<'a, F> {
449 TimeChart {
450 block: None,
451 x_axis: Axis::default(),
452 y_axis: Axis::default(),
453 style: Style::default(),
454 legend_style: Style::default(),
455 datasets,
456 hidden_legend_constraints: (Constraint::Ratio(1, 4), Constraint::Ratio(1, 4)),
457 legend_position: Some(LegendPosition::default()),
458 marker: Marker::Braille,
459 scaling: ChartScaling::default(),
460 }
461 }
462
463 /// Wraps the chart with the given [`Block`]
464 #[must_use = "method moves the value of self and returns the modified value"]
465 pub fn block(mut self, block: Block<'a>) -> TimeChart<'a, F> {
466 self.block = Some(block);
467 self
468 }
469
470 /// Sets the style of the entire chart
471 ///
472 /// `style` accepts any type that is convertible to [`Style`] (e.g.
473 /// [`Style`], [`Color`], or your own type that implements
474 /// [`Into<Style>`]).
475 ///
476 /// Styles of [`Axis`] and [`Dataset`] will have priority over this style.
477 #[must_use = "method moves the value of self and returns the modified value"]
478 pub fn style<S: Into<Style>>(mut self, style: S) -> TimeChart<'a, F> {
479 self.style = style.into();
480 self
481 }
482
483 /// Sets the legend's style.
484 #[must_use = "method moves the value of self and returns the modified value"]
485 pub fn legend_style(mut self, legend_style: Style) -> TimeChart<'a, F> {
486 self.legend_style = legend_style;
487 self
488 }
489
490 /// Sets the X [`Axis`]
491 ///
492 /// The default is an empty [`Axis`], i.e. only a line.
493 #[must_use = "method moves the value of self and returns the modified value"]
494 pub fn x_axis(mut self, axis: Axis<'a>) -> TimeChart<'a, F> {
495 self.x_axis = axis;
496 self
497 }
498
499 /// Sets the Y [`Axis`]
500 ///
501 /// The default is an empty [`Axis`], i.e. only a line.
502 #[must_use = "method moves the value of self and returns the modified value"]
503 pub fn y_axis(mut self, axis: Axis<'a>) -> TimeChart<'a, F> {
504 self.y_axis = axis;
505 self
506 }
507
508 /// Sets the marker type.
509 #[must_use = "method moves the value of self and returns the modified value"]
510 pub fn marker(mut self, marker: Marker) -> TimeChart<'a, F> {
511 self.marker = marker;
512 self
513 }
514
515 /// Sets the constraints used to determine whether the legend should be
516 /// shown or not.
517 ///
518 /// The tuple's first constraint is used for the width and the second for
519 /// the height. If the legend takes more space than what is allowed by
520 /// any constraint, the legend is hidden. [`Constraint::Min`] is an
521 /// exception and will always show the legend.
522 ///
523 /// If this is not set, the default behavior is to hide the legend if it is
524 /// greater than 25% of the chart, either horizontally or vertically.
525 #[must_use = "method moves the value of self and returns the modified value"]
526 pub fn hidden_legend_constraints(
527 mut self, constraints: (Constraint, Constraint),
528 ) -> TimeChart<'a, F> {
529 self.hidden_legend_constraints = constraints;
530 self
531 }
532
533 /// Sets the position of a legend or hide it.
534 ///
535 /// The default is [`LegendPosition::TopRight`].
536 ///
537 /// If [`None`] is given, hide the legend even if
538 /// [`hidden_legend_constraints`] determines it should be shown. In
539 /// contrast, if `Some(...)` is given, [`hidden_legend_constraints`] might
540 /// still decide whether to show the legend or not.
541 ///
542 /// See [`LegendPosition`] for all available positions.
543 ///
544 /// [`hidden_legend_constraints`]: Self::hidden_legend_constraints
545 #[must_use = "method moves the value of self and returns the modified value"]
546 pub fn legend_position(mut self, position: Option<LegendPosition>) -> TimeChart<'a, F> {
547 self.legend_position = position;
548 self
549 }
550
551 /// Set chart scaling.
552 #[must_use = "method moves the value of self and returns the modified value"]
553 pub fn scaling(mut self, scaling: ChartScaling) -> TimeChart<'a, F> {
554 self.scaling = scaling;
555 self
556 }
557
558 /// Compute the internal layout of the chart given the area. If the area is
559 /// too small some elements may be automatically hidden
560 fn layout(&self, area: Rect) -> ChartLayout {
561 let mut layout = ChartLayout::default();
562 if area.height == 0 || area.width == 0 {
563 return layout;
564 }
565 let mut x = area.left();
566 let mut y = area.bottom() - 1;
567
568 if self.x_axis.labels.is_some() && y > area.top() {
569 layout.label_x = Some(y);
570 y -= 1;
571 }
572
573 layout.label_y = self.y_axis.labels.as_ref().and(Some(x));
574 x += self.max_width_of_labels_left_of_y_axis(area, self.y_axis.labels.is_some());
575
576 if self.x_axis.labels.is_some() && y > area.top() {
577 layout.axis_x = Some(y);
578 y -= 1;
579 }
580
581 if self.y_axis.labels.is_some() && x + 1 < area.right() {
582 layout.axis_y = Some(x);
583 x += 1;
584 }
585
586 if x < area.right() && y > 1 {
587 layout.graph_area = Rect::new(x, area.top(), area.right() - x, y - area.top() + 1);
588 }
589
590 if let Some(ref title) = self.x_axis.title {
591 let w = title.width() as u16;
592 if w < layout.graph_area.width && layout.graph_area.height > 2 {
593 layout.title_x = Some((x + layout.graph_area.width - w, y));
594 }
595 }
596
597 if let Some(ref title) = self.y_axis.title {
598 let w = title.width() as u16;
599 if w + 1 < layout.graph_area.width && layout.graph_area.height > 2 {
600 layout.title_y = Some((x, area.top()));
601 }
602 }
603
604 if let Some(legend_position) = self.legend_position {
605 let entry_widths: Vec<u16> = self
606 .datasets
607 .iter()
608 .filter_map(|d| Some(d.name.as_ref()?.width() as u16))
609 .collect();
610
611 let entry_count = entry_widths.len() as u16;
612
613 if entry_count > 0 {
614 let [max_legend_width] = Layout::horizontal([self.hidden_legend_constraints.0])
615 .flex(Flex::Start)
616 .areas(layout.graph_area);
617
618 let [max_legend_height] = Layout::vertical([self.hidden_legend_constraints.1])
619 .flex(Flex::Start)
620 .areas(layout.graph_area);
621
622 let max_entries = min(entry_count, max_legend_height.height.saturating_sub(2));
623 let visible = &entry_widths[..max_entries as usize];
624
625 if let Some(&max_width) = visible.iter().max() {
626 let min_width = visible.iter().copied().min().unwrap_or(0);
627 let min_required_width = min_width + 2;
628
629 let legend_width = max_width + 2;
630 let legend_height = max_entries + 2;
631
632 if max_width > 0
633 && max_legend_width.width >= min_required_width
634 && max_entries > 0
635 {
636 layout.legend_area = legend_position.layout(
637 layout.graph_area,
638 min(legend_width, max_legend_width.width),
639 legend_height,
640 layout
641 .title_x
642 .and(self.x_axis.title.as_ref())
643 .map(|t| t.width() as u16)
644 .unwrap_or_default(),
645 layout
646 .title_y
647 .and(self.y_axis.title.as_ref())
648 .map(|t| t.width() as u16)
649 .unwrap_or_default(),
650 );
651 }
652 }
653 }
654 }
655 layout
656 }
657
658 fn max_width_of_labels_left_of_y_axis(&self, area: Rect, has_y_axis: bool) -> u16 {
659 let mut max_width = self
660 .y_axis
661 .labels
662 .as_ref()
663 .map(|l| l.iter().map(Span::width).max().unwrap_or_default() as u16)
664 .unwrap_or_default();
665
666 if let Some(first_x_label) = self
667 .x_axis
668 .labels
669 .as_ref()
670 .and_then(|labels| labels.first())
671 {
672 let first_label_width = first_x_label.content.width() as u16;
673 let width_left_of_y_axis = match self.x_axis.labels_alignment {
674 Alignment::Left => {
675 // The last character of the label should be below the Y-Axis when it exists,
676 // not on its left
677 let y_axis_offset = u16::from(has_y_axis);
678 first_label_width.saturating_sub(y_axis_offset)
679 }
680 Alignment::Center => first_label_width / 2,
681 Alignment::Right => 0,
682 };
683 max_width = max(max_width, width_left_of_y_axis);
684 }
685 // labels of y axis and first label of x axis can take at most 1/3rd of the
686 // total width
687 max_width.min(area.width / 3)
688 }
689
690 fn render_x_labels(
691 &self, buf: &mut Buffer, layout: &ChartLayout, chart_area: Rect, graph_area: Rect,
692 ) {
693 let Some(y) = layout.label_x else { return };
694 let Some(labels) = self.x_axis.labels.as_ref() else {
695 return;
696 };
697 let labels_len = labels.len() as u16;
698 if labels_len < 2 {
699 return;
700 }
701
702 let first_label = labels.first().expect("must have at least 2 labels");
703 let last_label = labels.last().expect("must have at least 2 labels");
704
705 let width_between_ticks = graph_area.width / labels_len;
706
707 let label_area = self.first_x_label_area(
708 y,
709 first_label.width() as u16,
710 width_between_ticks,
711 chart_area,
712 graph_area,
713 );
714
715 let label_alignment = match self.x_axis.labels_alignment {
716 Alignment::Left => Alignment::Right,
717 Alignment::Center => Alignment::Center,
718 Alignment::Right => Alignment::Left,
719 };
720
721 Self::render_label(buf, first_label, label_area, label_alignment);
722
723 for (i, label) in labels[1..labels.len() - 1].iter().enumerate() {
724 // We add 1 to x (and width-1 below) to leave at least one space before each
725 // intermediate labels
726 let x = graph_area.left() + (i + 1) as u16 * width_between_ticks + 1;
727 let label_area = Rect::new(x, y, width_between_ticks.saturating_sub(1), 1);
728
729 Self::render_label(buf, label, label_area, Alignment::Center);
730 }
731
732 let x = graph_area.right() - width_between_ticks;
733 let label_area = Rect::new(x, y, width_between_ticks, 1);
734 // The last label should be aligned Right to be at the edge of the graph area
735 Self::render_label(buf, last_label, label_area, Alignment::Right);
736 }
737
738 fn first_x_label_area(
739 &self, y: u16, label_width: u16, max_width_after_y_axis: u16, chart_area: Rect,
740 graph_area: Rect,
741 ) -> Rect {
742 let (min_x, max_x) = match self.x_axis.labels_alignment {
743 Alignment::Left => (chart_area.left(), graph_area.left()),
744 Alignment::Center => (
745 chart_area.left(),
746 graph_area.left() + max_width_after_y_axis.min(label_width),
747 ),
748 Alignment::Right => (
749 graph_area.left().saturating_sub(1),
750 graph_area.left() + max_width_after_y_axis,
751 ),
752 };
753
754 Rect::new(min_x, y, max_x - min_x, 1)
755 }
756
757 fn render_label(buf: &mut Buffer, label: &Span<'_>, label_area: Rect, alignment: Alignment) {
758 let label_width = label.width() as u16;
759 let bounded_label_width = label_area.width.min(label_width);
760
761 let x = match alignment {
762 Alignment::Left => label_area.left(),
763 Alignment::Center => label_area.left() + label_area.width / 2 - bounded_label_width / 2,
764 Alignment::Right => label_area.right() - bounded_label_width,
765 };
766
767 buf.set_span(x, label_area.top(), label, bounded_label_width);
768 }
769
770 fn render_y_labels(
771 &self, buf: &mut Buffer, layout: &ChartLayout, chart_area: Rect, graph_area: Rect,
772 ) {
773 // FIXME: Control how many y-axis labels are rendered based on height.
774
775 let Some(x) = layout.label_y else { return };
776 let Some(labels) = self.y_axis.labels.as_ref() else {
777 return;
778 };
779 let labels_len = labels.len() as u16;
780
781 for (i, label) in labels.iter().enumerate() {
782 let dy = i as u16 * (graph_area.height - 1) / (labels_len - 1);
783 if dy < graph_area.bottom() {
784 let label_area = Rect::new(
785 x,
786 graph_area.bottom().saturating_sub(1) - dy,
787 (graph_area.left() - chart_area.left()).saturating_sub(1),
788 1,
789 );
790 Self::render_label(buf, label, label_area, self.y_axis.labels_alignment);
791 }
792 }
793 }
794 }
795
796 impl<F: Copy + Default + Into<f64>> Widget for TimeChart<'_, F> {
797 fn render(self, area: Rect, buf: &mut Buffer) {
798 buf.set_style(area, self.style);
799
800 self.block.as_ref().render(area, buf);
801 let chart_area = self.block.inner_if_some(area);
802 if chart_area.is_empty() {
803 return;
804 }
805
806 // Sample the style of the entire widget. This sample will be used to reset the
807 // style of the cells that are part of the components put on top of the
808 // graph area (i.e legend and axis names).
809 let Some(original_style) = buf.cell((area.left(), area.top())).map(|cell| cell.style())
810 else {
811 return;
812 };
813
814 let layout = self.layout(chart_area);
815 let graph_area = layout.graph_area;
816 if graph_area.width < 1 || graph_area.height < 1 {
817 return;
818 }
819
820 self.render_x_labels(buf, &layout, chart_area, graph_area);
821 self.render_y_labels(buf, &layout, chart_area, graph_area);
822
823 if let Some(y) = layout.axis_x {
824 for x in graph_area.left()..graph_area.right() {
825 if let Some(cell) = buf.cell_mut((x, y)) {
826 cell.set_symbol(symbols::line::HORIZONTAL)
827 .set_style(self.x_axis.style);
828 }
829 }
830 }
831
832 if let Some(x) = layout.axis_y {
833 for y in graph_area.top()..graph_area.bottom() {
834 if let Some(cell) = buf.cell_mut((x, y)) {
835 cell.set_symbol(symbols::line::VERTICAL)
836 .set_style(self.y_axis.style);
837 }
838 }
839 }
840
841 if let Some(y) = layout.axis_x
842 && let Some(x) = layout.axis_y
843 && let Some(cell) = buf.cell_mut((x, y))
844 {
845 cell.set_symbol(symbols::line::BOTTOM_LEFT)
846 .set_style(self.x_axis.style);
847 }
848
849 let x_bounds = self.x_axis.bounds.get_bounds();
850 let y_bounds = self.y_axis.bounds.get_bounds();
851
852 Canvas::default()
853 .background_color(self.style.bg.unwrap_or(Color::Reset))
854 .x_bounds(x_bounds)
855 .y_bounds(y_bounds)
856 .marker(self.marker)
857 .paint(|ctx| {
858 self.draw_points(ctx);
859 })
860 .render(graph_area, buf);
861
862 if let Some((x, y)) = layout.title_x
863 && let Some(title) = self.x_axis.title.as_ref()
864 {
865 let width = graph_area
866 .right()
867 .saturating_sub(x)
868 .min(title.width() as u16);
869 buf.set_style(
870 Rect {
871 x,
872 y,
873 width,
874 height: 1,
875 },
876 original_style,
877 );
878 buf.set_line(x, y, title, width);
879 }
880
881 if let Some((x, y)) = layout.title_y
882 && let Some(title) = self.y_axis.title.as_ref()
883 {
884 let width = graph_area
885 .right()
886 .saturating_sub(x)
887 .min(title.width() as u16);
888 buf.set_style(
889 Rect {
890 x,
891 y,
892 width,
893 height: 1,
894 },
895 original_style,
896 );
897 buf.set_line(x, y, title, width);
898 }
899
900 if let Some(legend_area) = layout.legend_area {
901 buf.set_style(legend_area, original_style);
902
903 let block = Block::default()
904 .borders(Borders::ALL)
905 .border_style(self.legend_style);
906
907 for pos in block.inner(legend_area).positions() {
908 if let Some(cell) = buf.cell_mut(pos) {
909 cell.set_symbol(" ");
910 }
911 }
912
913 block.render(legend_area, buf);
914
915 let max_width = legend_area.width - 2;
916
917 for (i, (dataset_name, dataset_style)) in self
918 .datasets
919 .iter()
920 .filter_map(|ds| Some((ds.name.as_ref()?, ds.style())))
921 .enumerate()
922 .take((legend_area.height - 2) as usize)
923 {
924 let line = if dataset_name.width() as u16 <= max_width {
925 dataset_name.clone()
926 } else {
927 let inner = dataset_name.to_string();
928 let truncated = unicode_ellipsis::truncate_str(&inner, max_width as usize);
929
930 Line::from(truncated.to_string())
931 };
932
933 let name = line.patch_style(dataset_style);
934 name.render(
935 Rect {
936 x: legend_area.x + 1,
937 y: legend_area.y + 1 + i as u16,
938 width: max_width,
939 height: 1,
940 },
941 buf,
942 );
943 }
944 }
945 }
946 }
947
948 impl<'a> Styled for Axis<'a> {
949 type Item = Axis<'a>;
950
951 fn style(&self) -> Style {
952 self.style
953 }
954
955 fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
956 self.style(style)
957 }
958 }
959
960 impl<'a, F: Copy + Default + Into<f64>> Styled for Dataset<'a, F> {
961 type Item = Dataset<'a, F>;
962
963 fn style(&self) -> Style {
964 self.style
965 }
966
967 fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
968 self.style(style)
969 }
970 }
971
972 impl<'a, F: Copy + Default + Into<f64>> Styled for TimeChart<'a, F> {
973 type Item = TimeChart<'a, F>;
974
975 fn style(&self) -> Style {
976 self.style
977 }
978
979 fn set_style<S: Into<Style>>(self, style: S) -> Self::Item {
980 self.style(style)
981 }
982 }
983
984 /// Tests taken from ratatui.
985 #[cfg(test)]
986 mod tests {
987 macro_rules! assert_buffer_eq {
988 ($actual_expr:expr, $expected_expr:expr) => {
989 match (&$actual_expr, &$expected_expr) {
990 (actual, expected) => {
991 if actual.area != expected.area {
992 panic!(
993 "buffer areas not equal - expected: {expected:?} - actual: {actual:?}",
994 );
995 }
996 let diff = expected.diff(&actual);
997 if !diff.is_empty() {
998 let nice_diff = diff
999 .iter()
1000 .enumerate()
1001 .map(|(i, (x, y, cell))| {
1002 let expected_cell = expected.cell((*x, *y)).unwrap();
1003 indoc::formatdoc! {"
1004 {i}: at ({x}, {y})
1005 expected: {expected_cell:?}
1006 actual: {cell:?}
1007 "}
1008 })
1009 .collect::<Vec<String>>()
1010 .join("\n");
1011 panic!(
1012 indoc::indoc!(
1013 "
1014 buffer contents not equal
1015 expected: {:?}
1016 actual: {:?}
1017 diff:
1018 {}"
1019 ),
1020 expected, actual, nice_diff
1021 );
1022 }
1023 // shouldn't get here, but this guards against future behavior
1024 // that changes equality but not area or content
1025 assert_eq!(actual, expected, "buffers not equal");
1026 }
1027 }
1028 };
1029 }
1030
1031 use std::time::Duration;
1032
1033 use ratatui::style::{Modifier, Stylize};
1034
1035 use super::*;
1036 use crate::app::data::Values;
1037
1038 struct LegendTestCase {
1039 chart_area: Rect,
1040 hidden_legend_constraints: (Constraint, Constraint),
1041 legend_area: Option<Rect>,
1042 }
1043
1044 #[test]
1045 fn it_should_hide_the_legend() {
1046 let now = Instant::now();
1047 let times = [
1048 now,
1049 now.checked_add(Duration::from_secs(1)).unwrap(),
1050 now.checked_add(Duration::from_secs(2)).unwrap(),
1051 ];
1052 let mut values = Values::default();
1053 values.push(5.0);
1054 values.push(6.0);
1055 values.push(7.0);
1056
1057 let cases = [
1058 LegendTestCase {
1059 chart_area: Rect::new(0, 0, 100, 100),
1060 hidden_legend_constraints: (Constraint::Ratio(1, 4), Constraint::Ratio(1, 4)),
1061 legend_area: Some(Rect::new(88, 0, 12, 12)),
1062 },
1063 LegendTestCase {
1064 chart_area: Rect::new(0, 0, 100, 100),
1065 hidden_legend_constraints: (Constraint::Ratio(1, 10), Constraint::Ratio(1, 4)),
1066 legend_area: None,
1067 },
1068 ];
1069 for case in &cases {
1070 let datasets = (0..10)
1071 .map(|i| {
1072 let name = format!("Dataset #{i}");
1073 Dataset::default().name(name).data(&times, &values)
1074 })
1075 .collect::<Vec<_>>();
1076 let chart = TimeChart::new(datasets)
1077 .x_axis(Axis::default().title("X axis"))
1078 .y_axis(Axis::default().title("Y axis"))
1079 .hidden_legend_constraints(case.hidden_legend_constraints);
1080 let layout = chart.layout(case.chart_area);
1081 assert_eq!(layout.legend_area, case.legend_area);
1082 }
1083 }
1084
1085 #[test]
1086 fn axis_can_be_stylized() {
1087 assert_eq!(
1088 Axis::default().black().on_white().bold().not_dim().style,
1089 Style::default()
1090 .fg(Color::Black)
1091 .bg(Color::White)
1092 .add_modifier(Modifier::BOLD)
1093 .remove_modifier(Modifier::DIM)
1094 )
1095 }
1096
1097 #[test]
1098 fn dataset_can_be_stylized() {
1099 assert_eq!(
1100 Dataset::<f64>::default()
1101 .black()
1102 .on_white()
1103 .bold()
1104 .not_dim()
1105 .style,
1106 Style::default()
1107 .fg(Color::Black)
1108 .bg(Color::White)
1109 .add_modifier(Modifier::BOLD)
1110 .remove_modifier(Modifier::DIM)
1111 )
1112 }
1113
1114 #[test]
1115 fn chart_can_be_stylized() {
1116 assert_eq!(
1117 TimeChart::<f64>::new(vec![])
1118 .black()
1119 .on_white()
1120 .bold()
1121 .not_dim()
1122 .style,
1123 Style::default()
1124 .fg(Color::Black)
1125 .bg(Color::White)
1126 .add_modifier(Modifier::BOLD)
1127 .remove_modifier(Modifier::DIM)
1128 )
1129 }
1130
1131 #[test]
1132 fn graph_type_to_string() {
1133 assert_eq!(GraphType::Scatter.to_string(), "Scatter");
1134 assert_eq!(GraphType::Line.to_string(), "Line");
1135 }
1136
1137 #[test]
1138 fn graph_type_from_str() {
1139 assert_eq!("Scatter".parse::<GraphType>(), Ok(GraphType::Scatter));
1140 assert_eq!("Line".parse::<GraphType>(), Ok(GraphType::Line));
1141 assert!("".parse::<GraphType>().is_err());
1142 }
1143
1144 #[test]
1145 fn it_does_not_panic_if_title_is_wider_than_buffer() {
1146 let widget = TimeChart::<f64>::default()
1147 .y_axis(Axis::default().title("xxxxxxxxxxxxxxxx"))
1148 .x_axis(Axis::default().title("xxxxxxxxxxxxxxxx"));
1149 let mut buffer = Buffer::empty(Rect::new(0, 0, 8, 4));
1150 widget.render(buffer.area, &mut buffer);
1151
1152 assert_eq!(buffer, Buffer::with_lines(vec![" ".repeat(8); 4]))
1153 }
1154
1155 #[test]
1156 fn datasets_without_name_do_not_contribute_to_legend_height() {
1157 let data_named_1 = Dataset::default().name("data1"); // must occupy a row in legend
1158 let data_named_2 = Dataset::default().name(""); // must occupy a row in legend, even if name is empty
1159 let data_unnamed = Dataset::default(); // must not occupy a row in legend
1160 let widget = TimeChart::<f64>::new(vec![data_named_1, data_unnamed, data_named_2]);
1161 let buffer = Buffer::empty(Rect::new(0, 0, 50, 25));
1162 let layout = widget.layout(buffer.area);
1163
1164 assert!(layout.legend_area.is_some());
1165 assert_eq!(layout.legend_area.unwrap().height, 4); // 2 for borders, 2
1166 // for rows
1167 }
1168
1169 #[test]
1170 fn no_legend_if_no_named_datasets() {
1171 let dataset = Dataset::<f64>::default();
1172 let widget = TimeChart::new(vec![dataset; 3]);
1173 let buffer = Buffer::empty(Rect::new(0, 0, 50, 25));
1174 let layout = widget.layout(buffer.area);
1175
1176 assert!(layout.legend_area.is_none());
1177 }
1178
1179 #[test]
1180 fn dataset_legend_style_is_patched() {
1181 let long_dataset_name = Dataset::<f64>::default().name("Very long name");
1182 let short_dataset =
1183 Dataset::default().name(Line::from("Short name").alignment(Alignment::Right));
1184 let widget = TimeChart::new(vec![long_dataset_name, short_dataset])
1185 .hidden_legend_constraints((100.into(), 100.into()));
1186 let mut buffer = Buffer::empty(Rect::new(0, 0, 20, 5));
1187
1188 widget.render(buffer.area, &mut buffer);
1189
1190 let expected = Buffer::with_lines(vec![
1191 " ┌──────────────┐",
1192 " │Very long name│",
1193 " │ Short name│",
1194 " └──────────────┘",
1195 " ",
1196 ]);
1197 assert_buffer_eq!(buffer, expected);
1198 }
1199
1200 #[test]
1201 fn test_chart_have_a_topleft_legend() {
1202 let chart = TimeChart::<f64>::new(vec![Dataset::default().name("Ds1")])
1203 .legend_position(Some(LegendPosition::TopLeft));
1204
1205 let area = Rect::new(0, 0, 30, 20);
1206 let mut buffer = Buffer::empty(area);
1207
1208 chart.render(buffer.area, &mut buffer);
1209
1210 let expected = Buffer::with_lines(vec![
1211 "┌───┐ ",
1212 "│Ds1│ ",
1213 "└───┘ ",
1214 " ",
1215 " ",
1216 " ",
1217 " ",
1218 " ",
1219 " ",
1220 " ",
1221 " ",
1222 " ",
1223 " ",
1224 " ",
1225 " ",
1226 " ",
1227 " ",
1228 " ",
1229 " ",
1230 " ",
1231 ]);
1232
1233 assert_eq!(buffer, expected);
1234 }
1235
1236 #[test]
1237 fn test_chart_have_a_long_y_axis_title_overlapping_legend() {
1238 let chart = TimeChart::<f64>::new(vec![Dataset::default().name("Ds1")])
1239 .y_axis(Axis::default().title("The title overlap a legend."));
1240
1241 let area = Rect::new(0, 0, 30, 20);
1242 let mut buffer = Buffer::empty(area);
1243
1244 chart.render(buffer.area, &mut buffer);
1245
1246 let expected = Buffer::with_lines(vec![
1247 "The title overlap a legend. ",
1248 " ┌───┐",
1249 " │Ds1│",
1250 " └───┘",
1251 " ",
1252 " ",
1253 " ",
1254 " ",
1255 " ",
1256 " ",
1257 " ",
1258 " ",
1259 " ",
1260 " ",
1261 " ",
1262 " ",
1263 " ",
1264 " ",
1265 " ",
1266 " ",
1267 ]);
1268
1269 assert_eq!(buffer, expected);
1270 }
1271
1272 #[test]
1273 fn test_chart_have_overflowed_y_axis() {
1274 let chart = TimeChart::<f64>::new(vec![Dataset::default().name("Ds1")])
1275 .y_axis(Axis::default().title("The title overlap a legend."));
1276
1277 let area = Rect::new(0, 0, 10, 10);
1278 let mut buffer = Buffer::empty(area);
1279
1280 chart.render(buffer.area, &mut buffer);
1281
1282 let expected = Buffer::with_lines(vec![
1283 " ",
1284 " ",
1285 " ",
1286 " ",
1287 " ",
1288 " ",
1289 " ",
1290 " ",
1291 " ",
1292 " ",
1293 ]);
1294
1295 assert_eq!(buffer, expected);
1296 }
1297
1298 #[test]
1299 fn test_legend_area_can_fit_same_chart_area() {
1300 let name = "Data";
1301 let chart = TimeChart::<f64>::new(vec![Dataset::default().name(name)])
1302 .hidden_legend_constraints((Constraint::Percentage(100), Constraint::Percentage(100)));
1303
1304 let area = Rect::new(0, 0, name.len() as u16 + 2, 3);
1305 let mut buffer = Buffer::empty(area);
1306
1307 let expected = Buffer::with_lines(vec!["┌────┐", "│Data│", "└────┘"]);
1308
1309 [
1310 LegendPosition::TopLeft,
1311 LegendPosition::Top,
1312 LegendPosition::TopRight,
1313 LegendPosition::Left,
1314 LegendPosition::Right,
1315 LegendPosition::Bottom,
1316 LegendPosition::BottomLeft,
1317 LegendPosition::BottomRight,
1318 ]
1319 .iter()
1320 .for_each(|&position| {
1321 let chart = chart.clone().legend_position(Some(position));
1322 buffer.reset();
1323 chart.render(buffer.area, &mut buffer);
1324 assert_eq!(buffer, expected);
1325 });
1326 }
1327
1328 #[test]
1329 fn test_legend_of_chart_have_odd_margin_size() {
1330 let name = "Data";
1331 let base_chart = TimeChart::<f64>::new(vec![Dataset::default().name(name)])
1332 .hidden_legend_constraints((Constraint::Percentage(100), Constraint::Percentage(100)));
1333
1334 let area = Rect::new(0, 0, name.len() as u16 + 2 + 3, 3 + 3);
1335 let mut buffer = Buffer::empty(area);
1336
1337 let chart = base_chart
1338 .clone()
1339 .legend_position(Some(LegendPosition::TopLeft));
1340 buffer.reset();
1341 chart.render(buffer.area, &mut buffer);
1342 assert_eq!(
1343 buffer,
1344 Buffer::with_lines(vec![
1345 "┌────┐ ",
1346 "│Data│ ",
1347 "└────┘ ",
1348 " ",
1349 " ",
1350 " ",
1351 ])
1352 );
1353 buffer.reset();
1354
1355 let chart = base_chart
1356 .clone()
1357 .legend_position(Some(LegendPosition::Top));
1358 buffer.reset();
1359 chart.render(buffer.area, &mut buffer);
1360 assert_eq!(
1361 buffer,
1362 Buffer::with_lines(vec![
1363 " ┌────┐ ",
1364 " │Data│ ",
1365 " └────┘ ",
1366 " ",
1367 " ",
1368 " ",
1369 ])
1370 );
1371
1372 let chart = base_chart
1373 .clone()
1374 .legend_position(Some(LegendPosition::TopRight));
1375 buffer.reset();
1376 chart.render(buffer.area, &mut buffer);
1377 assert_eq!(
1378 buffer,
1379 Buffer::with_lines(vec![
1380 " ┌────┐",
1381 " │Data│",
1382 " └────┘",
1383 " ",
1384 " ",
1385 " ",
1386 ])
1387 );
1388
1389 let chart = base_chart
1390 .clone()
1391 .legend_position(Some(LegendPosition::Left));
1392 buffer.reset();
1393 chart.render(buffer.area, &mut buffer);
1394 assert_eq!(
1395 buffer,
1396 Buffer::with_lines(vec![
1397 " ",
1398 "┌────┐ ",
1399 "│Data│ ",
1400 "└────┘ ",
1401 " ",
1402 " ",
1403 ])
1404 );
1405 buffer.reset();
1406
1407 let chart = base_chart
1408 .clone()
1409 .legend_position(Some(LegendPosition::Right));
1410 buffer.reset();
1411 chart.render(buffer.area, &mut buffer);
1412 assert_eq!(
1413 buffer,
1414 Buffer::with_lines(vec![
1415 " ",
1416 " ┌────┐",
1417 " │Data│",
1418 " └────┘",
1419 " ",
1420 " ",
1421 ])
1422 );
1423
1424 let chart = base_chart
1425 .clone()
1426 .legend_position(Some(LegendPosition::BottomLeft));
1427 buffer.reset();
1428 chart.render(buffer.area, &mut buffer);
1429 assert_eq!(
1430 buffer,
1431 Buffer::with_lines(vec![
1432 " ",
1433 " ",
1434 " ",
1435 "┌────┐ ",
1436 "│Data│ ",
1437 "└────┘ ",
1438 ])
1439 );
1440
1441 let chart = base_chart
1442 .clone()
1443 .legend_position(Some(LegendPosition::Bottom));
1444 buffer.reset();
1445 chart.render(buffer.area, &mut buffer);
1446 assert_eq!(
1447 buffer,
1448 Buffer::with_lines(vec![
1449 " ",
1450 " ",
1451 " ",
1452 " ┌────┐ ",
1453 " │Data│ ",
1454 " └────┘ ",
1455 ])
1456 );
1457
1458 let chart = base_chart
1459 .clone()
1460 .legend_position(Some(LegendPosition::BottomRight));
1461 buffer.reset();
1462 chart.render(buffer.area, &mut buffer);
1463 assert_eq!(
1464 buffer,
1465 Buffer::with_lines(vec![
1466 " ",
1467 " ",
1468 " ",
1469 " ┌────┐",
1470 " │Data│",
1471 " └────┘",
1472 ])
1473 );
1474
1475 let chart = base_chart.clone().legend_position(None);
1476 buffer.reset();
1477 chart.render(buffer.area, &mut buffer);
1478 assert_eq!(
1479 buffer,
1480 Buffer::with_lines(vec![
1481 " ",
1482 " ",
1483 " ",
1484 " ",
1485 " ",
1486 " ",
1487 ])
1488 );
1489 }
1490
1491 #[test]
1492 fn legend_truncates_entries_by_height() {
1493 // 5 datasets but only room for 3 entries in the legend (height=5, so 5-2=3
1494 // entries).
1495 let datasets: Vec<_> = (0..5)
1496 .map(|i| Dataset::default().name(format!("D{i}")))
1497 .collect();
1498 let chart = TimeChart::<f64>::new(datasets)
1499 .hidden_legend_constraints((Constraint::Percentage(100), Constraint::Percentage(100)));
1500
1501 // Height 5 means room for 3 entries (5 - 2 borders).
1502 let area = Rect::new(0, 0, 20, 5);
1503 let layout = chart.layout(area);
1504
1505 assert!(layout.legend_area.is_some());
1506 let legend = layout.legend_area.unwrap();
1507 assert_eq!(legend.height, 5); // 3 entries + 2 borders
1508 }
1509
1510 #[test]
1511 fn legend_truncates_entries_renders_only_visible() {
1512 // 5 datasets but height only fits 2 entries.
1513 let datasets: Vec<_> = (0..5)
1514 .map(|i| Dataset::default().name(format!("D{i}")))
1515 .collect();
1516 let chart = TimeChart::<f64>::new(datasets)
1517 .hidden_legend_constraints((Constraint::Percentage(100), Constraint::Percentage(100)));
1518
1519 let area = Rect::new(0, 0, 20, 4); // 4 - 2 = 2 entries
1520 let mut buffer = Buffer::empty(area);
1521 chart.render(buffer.area, &mut buffer);
1522
1523 let expected = Buffer::with_lines(vec![
1524 " ┌──┐",
1525 " │D0│",
1526 " │D1│",
1527 " └──┘",
1528 ]);
1529 assert_buffer_eq!(buffer, expected);
1530 }
1531
1532 #[test]
1533 fn legend_width_capped_to_constraint() {
1534 let datasets = vec![
1535 Dataset::default().name("Short"),
1536 Dataset::default().name("A very long dataset name"),
1537 ];
1538 let chart = TimeChart::<f64>::new(datasets)
1539 .hidden_legend_constraints((Constraint::Percentage(100), Constraint::Percentage(100)));
1540
1541 // Width 12 means legend_width capped to 12, inner width = 10.
1542 let area = Rect::new(0, 0, 12, 10);
1543 let layout = chart.layout(area);
1544
1545 assert!(layout.legend_area.is_some());
1546 let legend = layout.legend_area.unwrap();
1547 assert_eq!(legend.width, 12); // capped to area width
1548 }
1549
1550 #[test]
1551 fn legend_width_truncates_long_names_with_ellipsis() {
1552 // Short entry fits untruncated (satisfies min_required_width), but the
1553 // long entry exceeds the capped legend width and gets an ellipsis.
1554 let datasets = vec![
1555 Dataset::default().name("AB"),
1556 Dataset::default().name("Very long name here"),
1557 ];
1558 let chart = TimeChart::<f64>::new(datasets)
1559 .hidden_legend_constraints((Constraint::Percentage(100), Constraint::Percentage(100)));
1560
1561 // Width 8, legend box capped to 8, inner is 6, long name truncated.
1562 let area = Rect::new(0, 0, 8, 4);
1563 let mut buffer = Buffer::empty(area);
1564 chart.render(buffer.area, &mut buffer);
1565
1566 #[rustfmt::skip]
1567 let expected = Buffer::with_lines(vec![
1568 "┌──────┐",
1569 "│AB │",
1570 "│Very …│",
1571 "└──────┘",
1572 ]);
1573 assert_buffer_eq!(buffer, expected);
1574 }
1575
1576 #[test]
1577 fn legend_width_uses_only_visible_entries() {
1578 // First 2 entries have short names, last entry has a very long name.
1579 // With height=4 (2 visible entries), the legend width should be based
1580 // on the short names only, not the long hidden one.
1581 let datasets = vec![
1582 Dataset::default().name("AB"),
1583 Dataset::default().name("CD"),
1584 Dataset::default().name("A very long dataset name"),
1585 ];
1586 let chart = TimeChart::<f64>::new(datasets)
1587 .hidden_legend_constraints((Constraint::Percentage(100), Constraint::Percentage(100)));
1588
1589 let area = Rect::new(0, 0, 30, 4); // height 4 → 2 visible entries
1590 let layout = chart.layout(area);
1591
1592 assert!(layout.legend_area.is_some());
1593 let legend = layout.legend_area.unwrap();
1594 // Width should be based on "AB"/"CD" (2 chars) + 2 borders = 4, not the long
1595 // name.
1596 assert_eq!(legend.width, 4);
1597 }
1598 }