Skip to main content

crisol_plot/plot/
grid.rs

1//! A grid of plots sharing one state and one view.
2
3use egui::Ui;
4
5use super::{Plot, PlotResponse, PlotState};
6use crisol_ui_kit::Icons;
7
8/// A rows × columns grid of plots. Every plot shares the same [`PlotState`], so pan,
9/// zoom, hidden series, and selection stay linked.
10pub struct PlotGrid<'a> {
11    columns: usize,
12    plots: Vec<Plot<'a>>,
13    cell_height: f32,
14    spacing: f32,
15}
16
17impl<'a> PlotGrid<'a> {
18    /// A grid with `columns` columns.
19    pub fn new(columns: usize) -> Self {
20        Self {
21            columns: columns.max(1),
22            plots: Vec::new(),
23            cell_height: 240.0,
24            spacing: 8.0,
25        }
26    }
27
28    /// Add a plot, left to right and top to bottom.
29    pub fn plot(mut self, plot: Plot<'a>) -> Self {
30        self.plots.push(plot);
31        self
32    }
33
34    /// Set the height of each cell.
35    pub fn cell_height(mut self, height: f32) -> Self {
36        self.cell_height = height.max(80.0);
37        self
38    }
39
40    /// Set the spacing between cells.
41    pub fn spacing(mut self, spacing: f32) -> Self {
42        self.spacing = spacing.max(0.0);
43        self
44    }
45
46    /// Show every plot and return their responses in order.
47    pub fn show(self, ui: &mut Ui, icons: &mut Icons, state: &mut PlotState) -> Vec<PlotResponse> {
48        let mut responses = Vec::with_capacity(self.plots.len());
49        let width = ((ui.available_width() - self.spacing * (self.columns.saturating_sub(1) as f32))
50            / self.columns as f32)
51            .max(120.0);
52        for row in self.plots.chunks(self.columns) {
53            ui.horizontal(|ui| {
54                for plot in row {
55                    let response = plot
56                        .clone()
57                        .width(width)
58                        .height(self.cell_height)
59                        .show(ui, icons, state);
60                    responses.push(response);
61                }
62            });
63            ui.add_space(self.spacing);
64        }
65        responses
66    }
67}