Skip to main content

tui_chart/
gantt.rs

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