tabled/features/height/
cell_height_increase.rs

1use papergrid::{
2    records::{Records, RecordsMut},
3    width::CfgWidthFunction,
4    Entity,
5};
6
7use crate::{measurment::Measurment, peaker::Peaker, CellOption, Height, Table, TableOption};
8
9use super::TableHeightIncrease;
10
11/// A modification for cell/table to increase its height.
12///
13/// If used for a [`Table`] [`PriorityNone`] is used.
14///
15/// [`PriorityNone`]: crate::peaker::PriorityNone
16#[derive(Debug)]
17pub struct CellHeightIncrease<W = usize> {
18    height: W,
19}
20
21impl<W> CellHeightIncrease<W> {
22    /// Creates a new object of the structure.
23    pub fn new(height: W) -> Self
24    where
25        W: Measurment<Height>,
26    {
27        Self { height }
28    }
29
30    /// The priority makes scence only for table, so the function
31    /// converts it to [`TableHeightIncrease`] with a given priority.
32    pub fn priority<P>(self) -> TableHeightIncrease<W, P>
33    where
34        P: Peaker,
35        W: Measurment<Height>,
36    {
37        TableHeightIncrease::new(self.height).priority::<P>()
38    }
39}
40
41impl<W, R> CellOption<R> for CellHeightIncrease<W>
42where
43    W: Measurment<Height>,
44    R: Records + RecordsMut<String>,
45{
46    fn change_cell(&mut self, table: &mut Table<R>, entity: Entity) {
47        let height = self.height.measure(table.get_records(), table.get_config());
48
49        let (count_rows, count_cols) = table.shape();
50        for pos in entity.iter(count_rows, count_cols) {
51            let records = table.get_records();
52            let cell_height = records.count_lines(pos);
53            if cell_height >= height {
54                continue;
55            }
56
57            let content = records.get_text(pos);
58            let content = add_lines(content, height - cell_height);
59            let ctrl = CfgWidthFunction::from_cfg(table.get_config());
60            table.get_records_mut().set(pos, content, &ctrl);
61        }
62
63        table.destroy_height_cache();
64    }
65}
66
67fn add_lines(s: &str, n: usize) -> String {
68    let mut text = String::with_capacity(s.len() + n);
69    text.push_str(s);
70    text.extend(std::iter::repeat('\n').take(n));
71
72    text
73}
74
75impl<W, R> TableOption<R> for CellHeightIncrease<W>
76where
77    W: Measurment<Height>,
78    R: Records,
79{
80    fn change(&mut self, table: &mut Table<R>) {
81        TableHeightIncrease::new(self.height.measure(table.get_records(), table.get_config()))
82            .change(table)
83    }
84}