Skip to main content

tui_chart/
stack.rs

1//! Layout helper that splits an area into linked chart panes.
2
3use ratatui::layout::Rect;
4
5/// Direction in which panes are stacked.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum StackDirection {
9    /// Panes stacked top to bottom (shared x axis, e.g. price + volume + indicator).
10    #[default]
11    Vertical,
12    /// Panes placed left to right.
13    Horizontal,
14}
15
16/// Splits an area into panes sized by ratio weights.
17///
18/// ```
19/// use ratatui::layout::Rect;
20/// use tui_chart::ChartStack;
21///
22/// let panes = ChartStack::vertical().weights([3, 1]).gap(1).split(Rect::new(0, 0, 40, 21));
23/// assert_eq!(panes.len(), 2);
24/// assert_eq!(panes[0].height, 15);
25/// assert_eq!(panes[1].height, 5);
26/// ```
27#[derive(Debug, Clone, Default)]
28pub struct ChartStack {
29    direction: StackDirection,
30    weights: Vec<u16>,
31    gap: u16,
32}
33
34impl ChartStack {
35    /// New stack in the given direction; add panes with [`pane`](Self::pane).
36    pub fn new(direction: StackDirection) -> Self {
37        Self {
38            direction,
39            ..Default::default()
40        }
41    }
42
43    /// Vertical stack (panes top to bottom).
44    pub fn vertical() -> Self {
45        Self::new(StackDirection::Vertical)
46    }
47
48    /// Horizontal stack (panes left to right).
49    pub fn horizontal() -> Self {
50        Self::new(StackDirection::Horizontal)
51    }
52
53    /// Append a pane with a ratio weight (0 is treated as 1).
54    pub fn pane(mut self, weight: u16) -> Self {
55        self.weights.push(weight.max(1));
56        self
57    }
58
59    /// Replace all panes with the given weights.
60    pub fn weights(mut self, weights: impl IntoIterator<Item = u16>) -> Self {
61        self.weights = weights.into_iter().map(|w| w.max(1)).collect();
62        self
63    }
64
65    setter!(
66        /// Empty cells between panes (default 0).
67        gap: u16
68    );
69
70    /// Number of panes.
71    pub fn len(&self) -> usize {
72        self.weights.len()
73    }
74
75    /// True when no panes are configured.
76    pub fn is_empty(&self) -> bool {
77        self.weights.is_empty()
78    }
79
80    /// Split `area` into one rect per pane. Sizes are proportional to the weights
81    /// (largest-remainder rounding, so they always fill the area exactly); when the
82    /// area is too small, trailing panes become zero-sized instead of panicking.
83    pub fn split(&self, area: Rect) -> Vec<Rect> {
84        let n = self.weights.len();
85        if n == 0 {
86            return vec![];
87        }
88        let total_len = match self.direction {
89            StackDirection::Vertical => area.height,
90            StackDirection::Horizontal => area.width,
91        } as u32;
92        let gaps = (self.gap as u32)
93            .saturating_mul(n as u32 - 1)
94            .min(total_len);
95        let avail = total_len - gaps;
96        let wsum: u32 = self.weights.iter().map(|&w| w as u32).sum();
97        let mut sizes: Vec<u32> = self
98            .weights
99            .iter()
100            .map(|&w| avail * w as u32 / wsum)
101            .collect();
102        let rest = avail - sizes.iter().sum::<u32>();
103        let mut order: Vec<usize> = (0..n).collect();
104        order.sort_by_key(|&i| std::cmp::Reverse(avail * self.weights[i] as u32 % wsum));
105        for &i in order.iter().cycle().take(rest as usize) {
106            sizes[i] += 1;
107        }
108        let mut pos = 0u32;
109        sizes
110            .iter()
111            .enumerate()
112            .map(|(i, &sz)| {
113                let g = if i + 1 < n { self.gap as u32 } else { 0 };
114                let r = match self.direction {
115                    StackDirection::Vertical => Rect::new(
116                        area.x,
117                        area.y + pos.min(area.height as u32) as u16,
118                        area.width,
119                        sz as u16,
120                    ),
121                    StackDirection::Horizontal => Rect::new(
122                        area.x + pos.min(area.width as u32) as u16,
123                        area.y,
124                        sz as u16,
125                        area.height,
126                    ),
127                };
128                pos += sz + g;
129                r
130            })
131            .collect()
132    }
133
134    /// Like [`split`](Self::split) but each pane is divided into
135    /// `(label_gutter, content)` where the gutter is the left `gutter` columns
136    /// (clamped to the pane width). Rendering every chart into its `content` rect
137    /// with y-axis labels drawn in a matching gutter keeps plot areas x-aligned
138    /// across panes. Use [`shared_gutter`] to compute the width.
139    pub fn split_aligned(&self, area: Rect, gutter: u16) -> Vec<(Rect, Rect)> {
140        self.split(area)
141            .into_iter()
142            .map(|r| {
143                let g = gutter.min(r.width);
144                (
145                    Rect::new(r.x, r.y, g, r.height),
146                    Rect::new(r.x + g, r.y, r.width - g, r.height),
147                )
148            })
149            .collect()
150    }
151}
152
153/// Shared gutter width for x-aligned panes: the widest of the given label widths.
154pub fn shared_gutter(widths: impl IntoIterator<Item = u16>) -> u16 {
155    widths.into_iter().max().unwrap_or(0)
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn fills_area_exactly() {
164        for h in 0..60u16 {
165            let r = ChartStack::vertical()
166                .weights([3, 2, 1])
167                .gap(1)
168                .split(Rect::new(2, 3, 10, h));
169            assert_eq!(r.len(), 3);
170            let used: u32 = r.iter().map(|r| r.height as u32).sum();
171            let gaps = 2.min(h as u32);
172            assert_eq!(used + gaps, h as u32, "h={h}");
173            for r in &r {
174                assert!(r.bottom() <= 3 + h);
175            }
176            assert!(r.windows(2).all(|w| w[0].bottom() <= w[1].y));
177        }
178    }
179
180    #[test]
181    fn proportions() {
182        let r = ChartStack::vertical()
183            .pane(3)
184            .pane(1)
185            .split(Rect::new(0, 0, 5, 20));
186        assert_eq!((r[0].height, r[1].height), (15, 5));
187        assert_eq!(r[1].y, 15);
188    }
189
190    #[test]
191    fn horizontal_and_gap() {
192        let r = ChartStack::horizontal()
193            .weights([1, 1])
194            .gap(2)
195            .split(Rect::new(0, 0, 22, 4));
196        assert_eq!(r[0], Rect::new(0, 0, 10, 4));
197        assert_eq!(r[1], Rect::new(12, 0, 10, 4));
198    }
199
200    #[test]
201    fn empty_and_tiny() {
202        assert!(
203            ChartStack::vertical()
204                .split(Rect::new(0, 0, 5, 5))
205                .is_empty()
206        );
207        assert!(ChartStack::vertical().is_empty());
208        let r = ChartStack::vertical()
209            .weights([1, 1, 1])
210            .gap(5)
211            .split(Rect::new(0, 0, 0, 0));
212        assert!(r.iter().all(|r| r.area() == 0));
213        let r = ChartStack::vertical()
214            .weights([0, u16::MAX])
215            .split(Rect::new(0, 0, 3, 7));
216        assert_eq!(r.iter().map(|r| r.height).sum::<u16>(), 7);
217    }
218
219    #[test]
220    fn aligned_gutter() {
221        let s = ChartStack::vertical().weights([2, 1]);
222        let g = shared_gutter([4, 7, 5]);
223        assert_eq!(g, 7);
224        let p = s.split_aligned(Rect::new(0, 0, 30, 12), g);
225        assert!(
226            p.iter()
227                .all(|(l, c)| l.width == 7 && c.x == 7 && c.width == 23)
228        );
229        let p = s.split_aligned(Rect::new(0, 0, 3, 12), g);
230        assert_eq!(p[0].1.width, 0);
231        assert_eq!(shared_gutter([]), 0);
232    }
233}