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