1use ratatui::layout::Rect;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum StackDirection {
9 #[default]
11 Vertical,
12 Horizontal,
14}
15
16#[derive(Debug, Clone, Default)]
28pub struct ChartStack {
29 direction: StackDirection,
30 weights: Vec<u16>,
31 gap: u16,
32}
33
34impl ChartStack {
35 pub fn new(direction: StackDirection) -> Self {
37 Self {
38 direction,
39 ..Default::default()
40 }
41 }
42
43 pub fn vertical() -> Self {
45 Self::new(StackDirection::Vertical)
46 }
47
48 pub fn horizontal() -> Self {
50 Self::new(StackDirection::Horizontal)
51 }
52
53 pub fn pane(mut self, weight: u16) -> Self {
55 self.weights.push(weight.max(1));
56 self
57 }
58
59 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 gap: u16
68 );
69
70 pub fn len(&self) -> usize {
72 self.weights.len()
73 }
74
75 pub fn is_empty(&self) -> bool {
77 self.weights.is_empty()
78 }
79
80 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 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
153pub 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!(ChartStack::vertical()
203 .split(Rect::new(0, 0, 5, 5))
204 .is_empty());
205 assert!(ChartStack::vertical().is_empty());
206 let r = ChartStack::vertical()
207 .weights([1, 1, 1])
208 .gap(5)
209 .split(Rect::new(0, 0, 0, 0));
210 assert!(r.iter().all(|r| r.area() == 0));
211 let r = ChartStack::vertical()
212 .weights([0, u16::MAX])
213 .split(Rect::new(0, 0, 3, 7));
214 assert_eq!(r.iter().map(|r| r.height).sum::<u16>(), 7);
215 }
216
217 #[test]
218 fn aligned_gutter() {
219 let s = ChartStack::vertical().weights([2, 1]);
220 let g = shared_gutter([4, 7, 5]);
221 assert_eq!(g, 7);
222 let p = s.split_aligned(Rect::new(0, 0, 30, 12), g);
223 assert!(p
224 .iter()
225 .all(|(l, c)| l.width == 7 && c.x == 7 && c.width == 23));
226 let p = s.split_aligned(Rect::new(0, 0, 3, 12), g);
227 assert_eq!(p[0].1.width, 0);
228 assert_eq!(shared_gutter([]), 0);
229 }
230}