| 1 | use std::{borrow::Cow, time::Instant}; |
| 2 | |
| 3 | use concat_string::concat_string; |
| 4 | use ratatui::{ |
| 5 | Frame, |
| 6 | layout::{Constraint, Rect}, |
| 7 | style::Style, |
| 8 | symbols::Marker, |
| 9 | text::{Line, Span}, |
| 10 | widgets::{BorderType, GraphType}, |
| 11 | }; |
| 12 | use timeless::data::ChunkedData; |
| 13 | |
| 14 | use crate::canvas::{components::time_series::*, drawing_utils::widget_block}; |
| 15 | |
| 16 | /// Represents the data required by the [`TimeGraph`]. |
| 17 | /// |
| 18 | /// TODO: We may be able to get rid of this intermediary data structure. |
| 19 | #[derive(Default)] |
| 20 | pub(crate) struct GraphData<'a, F = f64> { |
| 21 | time: &'a [Instant], |
| 22 | values: Option<&'a ChunkedData<F>>, |
| 23 | style: Style, |
| 24 | name: Option<Cow<'a, str>>, |
| 25 | } |
| 26 | |
| 27 | impl<'a, F> GraphData<'a, F> { |
| 28 | pub fn time(mut self, time: &'a [Instant]) -> Self { |
| 29 | self.time = time; |
| 30 | self |
| 31 | } |
| 32 | |
| 33 | pub fn values(mut self, values: &'a ChunkedData<F>) -> Self { |
| 34 | self.values = Some(values); |
| 35 | self |
| 36 | } |
| 37 | |
| 38 | pub fn style(mut self, style: Style) -> Self { |
| 39 | self.style = style; |
| 40 | self |
| 41 | } |
| 42 | |
| 43 | pub fn name(mut self, name: Cow<'a, str>) -> Self { |
| 44 | self.name = Some(name); |
| 45 | self |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | #[derive(Clone, Copy)] |
| 50 | pub struct LegendConstraints { |
| 51 | /// The width legend constraints. |
| 52 | pub width: Constraint, |
| 53 | |
| 54 | /// The height legend constraints. |
| 55 | pub height: Constraint, |
| 56 | } |
| 57 | |
| 58 | pub struct TimeGraph<'a> { |
| 59 | /// The min x value. |
| 60 | pub x_min: f64, |
| 61 | |
| 62 | /// Whether to hide the time/x-labels. |
| 63 | pub hide_x_labels: bool, |
| 64 | |
| 65 | /// The min and max y boundaries. |
| 66 | pub y_bounds: AxisBound, |
| 67 | |
| 68 | /// Any y-labels. |
| 69 | pub y_labels: &'a [Cow<'a, str>], |
| 70 | |
| 71 | /// The graph style. |
| 72 | pub graph_style: Style, |
| 73 | |
| 74 | /// The background colour/styling. |
| 75 | pub general_widget_style: Style, |
| 76 | |
| 77 | /// The border style. |
| 78 | pub border_style: Style, |
| 79 | |
| 80 | /// The border type. |
| 81 | pub border_type: BorderType, |
| 82 | |
| 83 | /// The graph title. |
| 84 | pub title: Cow<'a, str>, |
| 85 | |
| 86 | /// Whether this graph is selected. |
| 87 | pub is_selected: bool, |
| 88 | |
| 89 | /// Whether this graph is expanded. |
| 90 | pub is_expanded: bool, |
| 91 | |
| 92 | /// The title style. |
| 93 | pub title_style: Style, |
| 94 | |
| 95 | /// The legend position. |
| 96 | pub legend_position: Option<LegendPosition>, |
| 97 | |
| 98 | /// Any legend constraints. |
| 99 | pub legend_constraints: Option<LegendConstraints>, |
| 100 | |
| 101 | /// The marker type. Unlike ratatui's native charts, we assume |
| 102 | /// only a single type of marker. |
| 103 | pub marker: Marker, |
| 104 | |
| 105 | /// The chart scaling. |
| 106 | pub scaling: ChartScaling, |
| 107 | } |
| 108 | |
| 109 | impl TimeGraph<'_> { |
| 110 | /// Generates the [`Axis`] for the x-axis. |
| 111 | fn generate_x_axis(&self) -> Axis<'_> { |
| 112 | // Due to how we display things, we need to adjust the time bound values. |
| 113 | let adjusted_x_bounds = AxisBound::Min(self.x_min); |
| 114 | |
| 115 | if self.hide_x_labels { |
| 116 | Axis::default().bounds(adjusted_x_bounds) |
| 117 | } else { |
| 118 | let x_bound_left = ((-self.x_min) as u64 / 1000).to_string(); |
| 119 | let x_bound_right = "0s"; |
| 120 | |
| 121 | let x_labels = vec![ |
| 122 | Span::styled(concat_string!(x_bound_left, "s"), self.graph_style), |
| 123 | Span::styled(x_bound_right, self.graph_style), |
| 124 | ]; |
| 125 | |
| 126 | Axis::default() |
| 127 | .bounds(adjusted_x_bounds) |
| 128 | .labels(x_labels) |
| 129 | .style(self.graph_style) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// Generates the [`Axis`] for the y-axis. |
| 134 | fn generate_y_axis(&self) -> Axis<'_> { |
| 135 | Axis::default() |
| 136 | .bounds(self.y_bounds) |
| 137 | .style(self.graph_style) |
| 138 | .labels( |
| 139 | self.y_labels |
| 140 | .iter() |
| 141 | .map(|label| Span::styled(label.clone(), self.graph_style)) |
| 142 | .collect(), |
| 143 | ) |
| 144 | } |
| 145 | |
| 146 | /// Draws a time graph at [`Rect`] location provided by `draw_loc`. A time |
| 147 | /// graph is used to display data points throughout time in the x-axis. |
| 148 | /// |
| 149 | /// This time graph: |
| 150 | /// - Draws with the higher time value on the left, and lower on the right. |
| 151 | /// - Expects a [`TimeGraph`] to be passed in, which details how to draw the |
| 152 | /// graph. |
| 153 | /// - Expects `graph_data`, which represents *what* data to draw, and |
| 154 | /// various details like style and optional legends. |
| 155 | pub fn draw<F: Copy + Default + Into<f64>>( |
| 156 | &self, f: &mut Frame<'_>, draw_loc: Rect, graph_data: Vec<GraphData<'_, F>>, |
| 157 | ) { |
| 158 | // TODO: (points_rework_v1) can we reduce allocations in the underlying graph by |
| 159 | // saving some sort of state? |
| 160 | |
| 161 | let x_axis = self.generate_x_axis(); |
| 162 | let y_axis = self.generate_y_axis(); |
| 163 | let data = graph_data.into_iter().map(create_dataset).collect(); |
| 164 | |
| 165 | let block = { |
| 166 | let mut b = widget_block( |
| 167 | false, |
| 168 | self.is_selected, |
| 169 | self.border_type, |
| 170 | self.general_widget_style, |
| 171 | ) |
| 172 | .border_style(self.border_style) |
| 173 | .title_top(Line::styled(self.title.as_ref(), self.title_style)); |
| 174 | |
| 175 | if self.is_expanded { |
| 176 | b = b.title_top(Line::styled(" Esc to go back ", self.title_style).right_aligned()) |
| 177 | } |
| 178 | |
| 179 | b |
| 180 | }; |
| 181 | |
| 182 | f.render_widget( |
| 183 | TimeChart::new(data) |
| 184 | .block(block) |
| 185 | .x_axis(x_axis) |
| 186 | .y_axis(y_axis) |
| 187 | .marker(self.marker) |
| 188 | .style(self.general_widget_style) |
| 189 | .legend_style(self.graph_style) |
| 190 | .legend_position(self.legend_position) |
| 191 | .hidden_legend_constraints({ |
| 192 | let constraints = self |
| 193 | .legend_constraints |
| 194 | .unwrap_or(DEFAULT_LEGEND_CONSTRAINTS); |
| 195 | |
| 196 | (constraints.width, constraints.height) |
| 197 | }) |
| 198 | .scaling(self.scaling), |
| 199 | draw_loc, |
| 200 | ) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | /// Creates a new [`Dataset`]. |
| 205 | fn create_dataset<F: Copy + Default + Into<f64>>(data: GraphData<'_, F>) -> Dataset<'_, F> { |
| 206 | let GraphData { |
| 207 | time, |
| 208 | values, |
| 209 | style, |
| 210 | name, |
| 211 | } = data; |
| 212 | |
| 213 | let Some(values) = values else { |
| 214 | return Dataset::default(); |
| 215 | }; |
| 216 | |
| 217 | let dataset = Dataset::default() |
| 218 | .style(style) |
| 219 | .data(time, values) |
| 220 | .graph_type(GraphType::Line); |
| 221 | |
| 222 | if let Some(name) = name { |
| 223 | dataset.name(name) |
| 224 | } else { |
| 225 | dataset |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | #[cfg(test)] |
| 230 | mod test { |
| 231 | use std::borrow::Cow; |
| 232 | |
| 233 | use ratatui::{ |
| 234 | style::{Color, Style}, |
| 235 | symbols::Marker, |
| 236 | text::Span, |
| 237 | widgets::BorderType, |
| 238 | }; |
| 239 | |
| 240 | use super::{AxisBound, ChartScaling, TimeGraph}; |
| 241 | use crate::canvas::components::time_series::Axis; |
| 242 | |
| 243 | const Y_LABELS: [Cow<'static, str>; 3] = [ |
| 244 | Cow::Borrowed("0%"), |
| 245 | Cow::Borrowed("50%"), |
| 246 | Cow::Borrowed("100%"), |
| 247 | ]; |
| 248 | |
| 249 | fn create_time_series() -> TimeGraph<'static> { |
| 250 | TimeGraph { |
| 251 | title: " Network ".into(), |
| 252 | x_min: -15000.0, |
| 253 | hide_x_labels: false, |
| 254 | y_bounds: AxisBound::Max(100.5), |
| 255 | y_labels: &Y_LABELS, |
| 256 | graph_style: Style::default().fg(Color::Red), |
| 257 | general_widget_style: Style::default().bg(Color::Black), |
| 258 | border_style: Style::default().fg(Color::Blue), |
| 259 | border_type: BorderType::Plain, |
| 260 | is_selected: false, |
| 261 | is_expanded: false, |
| 262 | title_style: Style::default().fg(Color::Cyan), |
| 263 | legend_position: None, |
| 264 | legend_constraints: None, |
| 265 | marker: Marker::Braille, |
| 266 | scaling: ChartScaling::Linear, |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn time_series_gen_x_axis() { |
| 272 | let tg = create_time_series(); |
| 273 | let style = Style::default().fg(Color::Red); |
| 274 | let x_axis = tg.generate_x_axis(); |
| 275 | |
| 276 | let actual = Axis::default() |
| 277 | .bounds(AxisBound::Min(-15000.0)) |
| 278 | .labels(vec![Span::styled("15s", style), Span::styled("0s", style)]) |
| 279 | .style(style); |
| 280 | assert_eq!(x_axis.bounds, actual.bounds); |
| 281 | assert_eq!(x_axis.labels, actual.labels); |
| 282 | assert_eq!(x_axis.style, actual.style); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn time_series_gen_y_axis() { |
| 287 | let tg = create_time_series(); |
| 288 | let style = Style::default().fg(Color::Red); |
| 289 | let y_axis = tg.generate_y_axis(); |
| 290 | |
| 291 | let actual = Axis::default() |
| 292 | .bounds(AxisBound::Max(100.5)) |
| 293 | .labels(vec![ |
| 294 | Span::styled("0%", style), |
| 295 | Span::styled("50%", style), |
| 296 | Span::styled("100%", style), |
| 297 | ]) |
| 298 | .style(style); |
| 299 | |
| 300 | assert_eq!(y_axis.bounds, actual.bounds); |
| 301 | assert_eq!(y_axis.labels, actual.labels); |
| 302 | assert_eq!(y_axis.style, actual.style); |
| 303 | } |
| 304 | } |