//! A [`ratatui::widgets::Chart`] but slightly more specialized to show //! right-aligned time_series data. //! //! Generally should be updated to be in sync with [`chart.rs`](https://github.com/ratatui-org/ratatui/blob/main/src/widgets/chart.rs); //! the specializations are factored out to `time_series/points.rs`. mod canvas; mod grid; mod points; use std::{ cmp::{max, min}, str::FromStr, time::Instant, }; use canvas::*; use ratatui::{ buffer::Buffer, layout::{Alignment, Constraint, Flex, Layout, Rect}, style::{Color, Style, Styled}, symbols::{self, Marker}, text::{Line, Span}, widgets::{Block, BlockExt, Borders, GraphType, Widget}, }; use timeless::data::ChunkedData; use unicode_width::UnicodeWidthStr; use crate::{ canvas::components::time_series::LegendConstraints, utils::general::{saturating_log2, saturating_log10}, utils::strings::truncate_str, }; pub const DEFAULT_LEGEND_CONSTRAINTS: LegendConstraints = LegendConstraints { width: Constraint::Ratio(1, 4), height: Constraint::Length(4), }; /// A single graph point. pub type Point = (f64, f64); /// An axis bound type. Allows us to save a f64 since we know that we are /// usually bound from some values [0.0, a], or [-b, 0.0]. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub enum AxisBound { /// Just 0. #[default] Zero, /// Bound by a minimum value to 0. Min(f64), /// Bound by 0 and a max value. Max(f64), } impl AxisBound { fn get_bounds(&self) -> [f64; 2] { match self { AxisBound::Zero => [0.0, 0.0], AxisBound::Min(min) => [*min, 0.0], AxisBound::Max(max) => [0.0, *max], } } } /// An X or Y axis for the [`TimeChart`] widget #[derive(Debug, Default, Clone, PartialEq)] pub struct Axis<'a> { /// Title displayed next to axis end pub(crate) title: Option>, /// Bounds for the axis (all data points outside these limits will not be /// represented) pub(crate) bounds: AxisBound, /// A list of labels to put to the left or below the axis pub(crate) labels: Option>>, /// The style used to draw the axis itself pub(crate) style: Style, /// The alignment of the labels of the Axis pub(crate) labels_alignment: Alignment, } impl<'a> Axis<'a> { /// Sets the axis title /// /// It will be displayed at the end of the axis. For an X axis this is the /// right, for a Y axis, this is the top. #[must_use = "method moves the value of self and returns the modified value"] #[cfg_attr(not(test), expect(dead_code))] pub fn title(mut self, title: T) -> Axis<'a> where T: Into>, { self.title = Some(title.into()); self } /// Sets the bounds of this axis. #[must_use = "method moves the value of self and returns the modified value"] pub fn bounds(mut self, bounds: AxisBound) -> Axis<'a> { self.bounds = bounds; self } /// Sets the axis labels /// /// - For the X axis, the labels are displayed left to right. /// - For the Y axis, the labels are displayed bottom to top. #[must_use = "method moves the value of self and returns the modified value"] pub fn labels(mut self, labels: Vec>) -> Axis<'a> { self.labels = Some(labels); self } /// Sets the axis style. #[must_use = "method moves the value of self and returns the modified value"] pub fn style>(mut self, style: S) -> Axis<'a> { self.style = style.into(); self } /// Sets the labels alignment of the axis /// /// The alignment behaves differently based on the axis: /// - Y axis: The labels are aligned within the area on the left of the axis /// - X axis: The first X-axis label is aligned relative to the Y-axis /// /// On the X axis, this parameter only affects the first label. #[must_use = "method moves the value of self and returns the modified value"] #[expect(dead_code)] pub fn labels_alignment(mut self, alignment: Alignment) -> Axis<'a> { self.labels_alignment = alignment; self } } /// Allow users to specify the position of a legend in a [`TimeChart`] /// /// See [`TimeChart::legend_position`] #[derive(Debug, Default, Clone, Copy, Eq, PartialEq)] pub enum LegendPosition { /// Legend is centered on top Top, /// Legend is in the top-right corner. This is the **default**. #[default] TopRight, /// Legend is in the top-left corner TopLeft, /// Legend is centered on the left Left, /// Legend is centered on the right Right, /// Legend is centered on the bottom Bottom, /// Legend is in the bottom-right corner BottomRight, /// Legend is in the bottom-left corner BottomLeft, } impl LegendPosition { fn layout( &self, area: Rect, legend_width: u16, legend_height: u16, x_title_width: u16, y_title_width: u16, ) -> Option { let mut height_margin = (area.height - legend_height) as i32; if x_title_width != 0 { height_margin -= 1; } if y_title_width != 0 { height_margin -= 1; } if height_margin < 0 { return None; }; let (x, y) = match self { Self::TopRight => { if legend_width + y_title_width > area.width { (area.right() - legend_width, area.top() + 1) } else { (area.right() - legend_width, area.top()) } } Self::TopLeft => { if y_title_width != 0 { (area.left(), area.top() + 1) } else { (area.left(), area.top()) } } Self::Top => { let x = (area.width - legend_width) / 2; if area.left() + y_title_width > x { (area.left() + x, area.top() + 1) } else { (area.left() + x, area.top()) } } Self::Left => { let mut y = (area.height - legend_height) / 2; if y_title_width != 0 { y += 1; } if x_title_width != 0 { y = y.saturating_sub(1); } (area.left(), area.top() + y) } Self::Right => { let mut y = (area.height - legend_height) / 2; if y_title_width != 0 { y += 1; } if x_title_width != 0 { y = y.saturating_sub(1); } (area.right() - legend_width, area.top() + y) } Self::BottomLeft => { if x_title_width + legend_width > area.width { (area.left(), area.bottom() - legend_height - 1) } else { (area.left(), area.bottom() - legend_height) } } Self::BottomRight => { if x_title_width != 0 { ( area.right() - legend_width, area.bottom() - legend_height - 1, ) } else { (area.right() - legend_width, area.bottom() - legend_height) } } Self::Bottom => { let x = area.left() + (area.width - legend_width) / 2; if x + legend_width > area.right() - x_title_width { (x, area.bottom() - legend_height - 1) } else { (x, area.bottom() - legend_height) } } }; Some(Rect::new(x, y, legend_width, legend_height)) } } #[derive(Debug, PartialEq)] pub struct ParseLegendPositionError; impl FromStr for LegendPosition { type Err = ParseLegendPositionError; fn from_str(s: &str) -> Result { match s { "top" => Ok(Self::Top), "top-left" => Ok(Self::TopLeft), "top-right" => Ok(Self::TopRight), "left" => Ok(Self::Left), "right" => Ok(Self::Right), "bottom-left" => Ok(Self::BottomLeft), "bottom" => Ok(Self::Bottom), "bottom-right" => Ok(Self::BottomRight), _ => Err(ParseLegendPositionError), } } } #[derive(Debug, Default, Clone)] enum Data<'a, F> { Some { times: &'a [Instant], values: &'a ChunkedData, }, #[default] None, } /// A group of data points /// /// This is the main element composing a [`TimeChart`]. /// /// A dataset can be [named](Dataset::name). Only named datasets will be /// rendered in the legend. #[derive(Debug, Default, Clone)] pub struct Dataset<'a, F: Copy + Default + Into = f64> { /// Name of the dataset (used in the legend if shown) name: Option>, /// A reference to data. data: Data<'a, F>, /// Symbol used for each points of this dataset marker: symbols::Marker, /// Determines graph type used for drawing points graph_type: GraphType, /// Style used to plot this dataset style: Style, } impl<'a, F: Copy + Default + Into> Dataset<'a, F> { /// Sets the name of the dataset. #[must_use = "method moves the value of self and returns the modified value"] pub fn name(mut self, name: S) -> Dataset<'a, F> where S: Into>, { self.name = Some(name.into()); self } /// Sets the data points of this dataset /// /// Points will then either be rendered as scattered points or with lines /// between them depending on [`Dataset::graph_type`]. /// /// Data consist in an array of `f64` tuples (`(f64, f64)`), the first /// element being X and the second Y. It's also worth noting that, /// unlike the [`Rect`], here the Y axis is bottom to top, as in math. #[must_use = "method moves the value of self and returns the modified value"] pub fn data(mut self, times: &'a [Instant], values: &'a ChunkedData) -> Dataset<'a, F> { self.data = Data::Some { times, values }; self } /// Sets the kind of character to use to display this dataset /// /// You can use dots (`•`), blocks (`█`), bars (`▄`), braille (`⠓`, `⣇`, /// `⣿`) or half-blocks (`█`, `▄`, and `▀`). See [symbols::Marker] for /// more details. /// /// Note [`Marker::Braille`] requires a font that supports Unicode Braille /// Patterns. #[must_use = "method moves the value of self and returns the modified value"] #[expect(dead_code)] pub fn marker(mut self, marker: symbols::Marker) -> Dataset<'a, F> { self.marker = marker; self } /// Sets how the dataset should be drawn /// /// [`TimeChart`] can draw either a [scatter](GraphType::Scatter) or /// [line](GraphType::Line) charts. A scatter will draw only the points /// in the dataset while a line will also draw a line between them. See /// [`GraphType`] for more details #[must_use = "method moves the value of self and returns the modified value"] pub fn graph_type(mut self, graph_type: GraphType) -> Dataset<'a, F> { self.graph_type = graph_type; self } /// Sets the style of this dataset /// /// The given style will be used to draw the legend and the data points. /// Currently the legend will use the entire style whereas the data /// points will only use the foreground. /// /// `style` accepts any type that is convertible to [`Style`] (e.g. /// [`Style`], [`Color`], or your own type that implements /// [`Into