Skip to main content

plotlars_core/components/
cell.rs

1use crate::components::Rgb;
2
3/// A structure representing cell formatting for tables.
4///
5/// The `Cell` struct allows customization of table cells including height,
6/// alignment, and fill color.
7///
8/// # Example
9///
10/// ```rust
11/// use plotlars::{Table, Cell, Plot, Text, Rgb};
12/// use polars::prelude::*;
13///
14/// let dataset = df![
15///     "product" => &["Laptop", "Mouse", "Keyboard", "Monitor"],
16///     "price" => &[999.99, 29.99, 79.99, 299.99],
17///     "stock" => &[15, 250, 87, 42]
18/// ]
19/// .unwrap();
20///
21/// let cell = Cell::new()
22///     .height(30.0)
23///     .align("left")
24///     .fill(Rgb(240, 240, 240));
25///
26/// Table::builder()
27///     .data(&dataset)
28///     .columns(vec!["product", "price", "stock"])
29///     .cell(&cell)
30///     .plot_title(Text::from("Product Inventory"))
31///     .build()
32///     .plot();
33/// ```
34///
35/// ![Example](https://imgur.com/FYYcWRH.png)
36#[derive(Clone, Default)]
37pub struct Cell {
38    pub height: Option<f64>,
39    pub align: Option<String>,
40    pub fill: Option<Rgb>,
41}
42
43impl Cell {
44    /// Creates a new `Cell` instance with default values.
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Sets the height of the cells.
50    ///
51    /// # Argument
52    ///
53    /// * `height` - A `f64` value specifying the cell height.
54    pub fn height(mut self, height: f64) -> Self {
55        self.height = Some(height);
56        self
57    }
58
59    /// Sets the alignment of the cell text.
60    ///
61    /// # Argument
62    ///
63    /// * `align` - A string specifying the alignment (left, center, right).
64    pub fn align(mut self, align: impl Into<String>) -> Self {
65        self.align = Some(align.into());
66        self
67    }
68
69    /// Sets the fill color of the cells.
70    ///
71    /// # Argument
72    ///
73    /// * `fill` - An `Rgb` value specifying the background color.
74    pub fn fill(mut self, fill: Rgb) -> Self {
75        self.fill = Some(fill);
76        self
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn test_default() {
86        let cell = Cell::new();
87        assert!(cell.height.is_none());
88        assert!(cell.align.is_none());
89        assert!(cell.fill.is_none());
90    }
91
92    #[test]
93    fn test_height() {
94        let cell = Cell::new().height(25.0);
95        assert!((cell.height.unwrap() - 25.0).abs() < 1e-6);
96    }
97
98    #[test]
99    fn test_align() {
100        let cell = Cell::new().align("right");
101        assert_eq!(cell.align, Some("right".to_string()));
102    }
103
104    #[test]
105    fn test_fill() {
106        let cell = Cell::new().fill(Rgb(240, 240, 240));
107        let fill = cell.fill.unwrap();
108        assert_eq!(fill.0, 240);
109        assert_eq!(fill.1, 240);
110        assert_eq!(fill.2, 240);
111    }
112}