1use crate::theme::{self, Theme};
4use crate::util::{format_tick, nice_ticks};
5use ratatui::{
6 buffer::Buffer,
7 layout::Rect,
8 style::{Color, Style},
9 widgets::Block,
10};
11
12#[derive(Debug, Clone, PartialEq)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15pub struct Task {
16 pub label: String,
18 pub start: f64,
20 pub end: f64,
22 pub progress: f64,
24 pub color: Option<Color>,
26}
27
28impl Task {
29 pub fn new(label: impl Into<String>, start: f64, end: f64) -> Self {
31 Self {
32 label: label.into(),
33 start,
34 end,
35 progress: 0.0,
36 color: None,
37 }
38 }
39
40 pub fn progress(mut self, p: f64) -> Self {
42 self.progress = if p.is_finite() {
43 p.clamp(0.0, 1.0)
44 } else {
45 0.0
46 };
47 self
48 }
49
50 opt_setter!(
51 color: Color
53 );
54}
55
56#[derive(Debug, Clone)]
58pub struct Gantt {
59 tasks: Vec<Task>,
60 palette: Option<Vec<Color>>,
61 theme: Option<Theme>,
62 base: Option<Style>,
63 today: Option<f64>,
64 range: Option<(f64, f64)>,
65 block: Option<Block<'static>>,
66}
67
68impl Gantt {
69 pub fn new(tasks: impl IntoIterator<Item = Task>) -> Self {
71 Self {
72 tasks: tasks.into_iter().collect(),
73 palette: None,
74 theme: None,
75 base: None,
76 today: None,
77 range: None,
78 block: None,
79 }
80 }
81
82 opt_setter!(
83 today: f64
85 );
86
87 pub fn range(mut self, start: f64, end: f64) -> Self {
89 self.range = Some((start, end));
90 self
91 }
92
93 pub fn palette(mut self, p: Vec<Color>) -> Self {
95 if !p.is_empty() {
96 self.palette = Some(p);
97 }
98 self
99 }
100
101 theme_setter!(
102 theme
106 );
107
108 base_style_setter!(base);
109
110 fn task_color(&self, i: usize) -> Color {
111 if let Some(p) = &self.palette {
112 return p[i % p.len()];
113 }
114 match &self.theme {
115 Some(t) => t.color(i),
116 None => [
117 Color::Cyan,
118 Color::Green,
119 Color::Yellow,
120 Color::Magenta,
121 Color::LightBlue,
122 ][i % 5],
123 }
124 }
125
126 block_setter!(block, 'static);
127
128 fn time_range(&self) -> (f64, f64) {
129 if let Some((a, b)) = self.range {
130 if a.is_finite() && b.is_finite() && b > a {
131 return (a, b);
132 }
133 }
134 let mut lo = f64::INFINITY;
135 let mut hi = f64::NEG_INFINITY;
136 for t in self
137 .tasks
138 .iter()
139 .filter(|t| t.start.is_finite() && t.end.is_finite())
140 {
141 lo = lo.min(t.start.min(t.end));
142 hi = hi.max(t.start.max(t.end));
143 }
144 if !lo.is_finite() {
145 (0.0, 1.0)
146 } else if hi <= lo {
147 (lo, lo + 1.0)
148 } else {
149 (lo, hi)
150 }
151 }
152}
153
154fn put_str(buf: &mut Buffer, x: u16, y: u16, max_x: u16, s: &str, style: Style) {
155 for (i, ch) in s.chars().enumerate() {
156 let cx = x as u32 + i as u32;
157 if cx >= max_x as u32 {
158 break;
159 }
160 buf[(cx as u16, y)].set_char(ch).set_style(style);
161 }
162}
163
164impl Gantt {
165 fn render_into(&self, area: Rect, buf: &mut Buffer) {
166 let area = area.intersection(buf.area);
167 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
168 if inner.width < 4 || inner.height < 2 || self.tasks.is_empty() {
169 return;
170 }
171 let gw = self
172 .tasks
173 .iter()
174 .map(|t| t.label.chars().count())
175 .max()
176 .unwrap_or(0) as u16;
177 let gutter = (gw + 1).min(inner.width / 3);
178 let plot = Rect::new(
179 inner.x + gutter,
180 inner.y,
181 inner.width - gutter,
182 inner.height - 1,
183 );
184 if plot.width == 0 || plot.height == 0 {
185 return;
186 }
187 let (lo, hi) = self.time_range();
188 let col = |t: f64| -> u16 {
189 let f = ((t - lo) / (hi - lo)).clamp(0.0, 1.0);
190 plot.x + (f * (plot.width - 1) as f64).round() as u16
191 };
192 let dim = Style::default().fg(self.theme.as_ref().map_or(Color::DarkGray, |t| t.grid));
193 let text = self
194 .theme
195 .as_ref()
196 .map_or(Style::default(), |t| t.label_style());
197
198 let ticks = nice_ticks(lo, hi, (plot.width as usize / 10).max(2));
200 let step = if ticks.len() >= 2 {
201 ticks[1] - ticks[0]
202 } else {
203 1.0
204 };
205 let ay = inner.bottom() - 1;
206 for v in &ticks {
207 let x = col(*v);
208 for y in plot.y..plot.bottom() {
209 buf[(x, y)].set_char('┊').set_style(dim);
210 }
211 put_str(buf, x, ay, inner.right(), &format_tick(*v, step), dim);
212 }
213
214 for (i, t) in self.tasks.iter().enumerate().take(plot.height as usize) {
215 let y = plot.y + i as u16;
216 let l: String = t
217 .label
218 .chars()
219 .take(gutter.saturating_sub(1) as usize)
220 .collect();
221 put_str(buf, inner.x, y, plot.x, &l, text);
222 if !t.start.is_finite() || !t.end.is_finite() {
223 continue;
224 }
225 let color = t.color.unwrap_or_else(|| self.task_color(i));
226 let (a, b) = (col(t.start.min(t.end)), col(t.start.max(t.end)));
227 let len = (b - a + 1) as f64;
228 let done = (t.progress.clamp(0.0, 1.0) * len).round() as u16;
229 for (k, x) in (a..=b).enumerate() {
230 let (ch, st) = if (k as u16) < done {
231 ('█', Style::default().fg(color))
232 } else {
233 ('░', Style::default().fg(color))
234 };
235 buf[(x, y)].set_char(ch).set_style(st);
236 }
237 }
238
239 if let Some(t) = self.today.filter(|t| t.is_finite() && *t >= lo && *t <= hi) {
240 let x = col(t);
241 let st = Style::default().fg(self.theme.as_ref().map_or(Color::Red, |t| t.bear));
242 for y in plot.y..plot.bottom() {
243 buf[(x, y)].set_char('┃').set_style(st);
244 }
245 put_str(buf, x, ay, inner.right(), "▲", st);
246 }
247 }
248}
249
250widget_impls!(Gantt);
251
252#[cfg(feature = "theme")]
253impl tui_nuances::Themed for Gantt {
254 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
255 self.theme(theme)
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262 use ratatui::widgets::Widget;
263
264 fn render(g: &Gantt, w: u16, h: u16) -> Buffer {
265 let area = Rect::new(0, 0, w, h);
266 let mut buf = Buffer::empty(area);
267 g.render(area, &mut buf);
268 buf
269 }
270
271 fn count(b: &Buffer, s: &str) -> usize {
272 b.content().iter().filter(|c| c.symbol() == s).count()
273 }
274
275 #[test]
276 fn progress_fill() {
277 let g = Gantt::new([Task::new("a", 0.0, 10.0).progress(0.5)]);
278 let b = render(&g, 30, 4);
279 assert!(count(&b, "█") > 0 && count(&b, "░") > 0);
280 let full = render(
281 &Gantt::new([Task::new("a", 0.0, 10.0).progress(1.0)]),
282 30,
283 4,
284 );
285 assert_eq!(count(&full, "░"), 0);
286 }
287
288 #[test]
289 fn today_marker_and_labels() {
290 let g =
291 Gantt::new([Task::new("design", 0.0, 5.0), Task::new("build", 5.0, 10.0)]).today(5.0);
292 let b = render(&g, 40, 5);
293 assert!(count(&b, "┃") >= 2);
294 let row0: String = (0..40).map(|x| b[(x, 0)].symbol().to_string()).collect();
295 assert!(row0.starts_with("design"));
296 }
297
298 #[cfg(feature = "theme")]
299 #[test]
300 fn theme_colors_and_override() {
301 let t = Theme::gruvbox();
302 let g = Gantt::new([
303 Task::new("a", 0.0, 5.0),
304 Task::new("b", 5.0, 10.0).color(Color::Red),
305 ])
306 .today(5.0)
307 .theme(&t);
308 let b = render(&g, 40, 5);
309 let fg = |c: Color| b.content().iter().any(|x| x.symbol() == "░" && x.fg == c);
310 assert!(fg(t.color(0)));
311 assert!(fg(Color::Red));
312 assert!(!fg(t.color(1)));
313 assert!(b
314 .content()
315 .iter()
316 .any(|x| x.symbol() == "┃" && x.fg == t.bear));
317 assert_eq!(b[(39, 0)].bg, t.background.unwrap());
318 }
319
320 #[test]
321 fn tiny_and_nan_no_panic() {
322 let g = Gantt::new([
323 Task::new("x", f64::NAN, 1.0),
324 Task::new("y", 3.0, 3.0).progress(f64::NAN),
325 ])
326 .today(3.0)
327 .block(Block::bordered());
328 for w in 0..8 {
329 for h in 0..6 {
330 render(&g, w, h);
331 }
332 }
333 render(&Gantt::new([]), 10, 5);
334 }
335}