1use crate::annotation::{draw_annotations, Annotation};
4use crate::axis::Axis;
5use crate::canvas::{Canvas, Marker};
6use crate::crosshair::{self, nearest_point, Crosshair, NearestPoint};
7use crate::heatmap::Gradient;
8use crate::layout::{self, text_width};
9use crate::theme::{self, Theme};
10use crate::util::{format_compact, format_tick, nice_bounds};
11use crate::PALETTE;
12use ratatui::{
13 buffer::Buffer,
14 layout::Rect,
15 style::{Color, Style},
16 widgets::Block,
17};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub enum LineMode {
23 #[default]
25 Line,
26 Step,
28 Area,
30 Scatter,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37pub enum LegendPosition {
38 None,
40 TopLeft,
42 #[default]
44 TopRight,
45 BottomLeft,
47 BottomRight,
49}
50
51#[derive(Debug, Clone, Default)]
53pub struct Series {
54 pub(crate) name: String,
55 pub(crate) data: Vec<(f64, f64)>,
56 pub(crate) color: Option<Color>,
57 pub(crate) mode: Option<LineMode>,
58 pub(crate) y_err: Vec<f64>,
59 pub(crate) band: Vec<(f64, f64)>,
60 pub(crate) smooth: bool,
61 pub(crate) secondary: bool,
62 pub(crate) fill_gradient: Option<Gradient>,
63}
64
65impl Series {
66 pub fn new(name: impl Into<String>) -> Self {
68 Self {
69 name: name.into(),
70 ..Default::default()
71 }
72 }
73
74 pub fn data(mut self, data: impl IntoIterator<Item = (f64, f64)>) -> Self {
76 self.data = data.into_iter().collect();
77 self
78 }
79
80 pub fn values(mut self, values: impl IntoIterator<Item = f64>) -> Self {
82 self.data = values
83 .into_iter()
84 .enumerate()
85 .map(|(i, v)| (i as f64, v))
86 .collect();
87 self
88 }
89
90 opt_setter!(
91 color: Color
93 );
94
95 opt_setter!(
96 fill_gradient: Gradient
98 );
99
100 opt_setter!(
101 mode: LineMode
103 );
104
105 pub fn y_err(mut self, err: impl IntoIterator<Item = f64>) -> Self {
107 self.y_err = err.into_iter().collect();
108 self
109 }
110
111 pub fn band(mut self, band: impl IntoIterator<Item = (f64, f64)>) -> Self {
113 self.band = band.into_iter().collect();
114 self
115 }
116
117 setter!(
118 smooth: bool
120 );
121
122 setter!(
123 secondary_axis => secondary: bool
125 );
126
127 pub fn name(&self) -> &str {
129 &self.name
130 }
131
132 pub fn len(&self) -> usize {
134 self.data.len()
135 }
136
137 pub fn is_empty(&self) -> bool {
139 self.data.is_empty()
140 }
141
142 fn y_values(&self) -> impl Iterator<Item = f64> + '_ {
144 self.data
145 .iter()
146 .enumerate()
147 .filter(|(_, (x, y))| x.is_finite() && y.is_finite())
148 .flat_map(|(i, &(_, y))| {
149 let mut v = vec![y];
150 if let Some(e) = self.y_err.get(i).filter(|e| e.is_finite()) {
151 v.push(y - e.abs());
152 v.push(y + e.abs());
153 }
154 if let Some(&(lo, hi)) = self.band.get(i) {
155 v.push(lo);
156 v.push(hi);
157 }
158 v
159 })
160 .filter(|v| v.is_finite())
161 }
162}
163
164#[derive(Debug, Clone, Copy)]
166struct Scale {
167 lo: f64,
168 hi: f64,
169 log: bool,
170}
171
172impl Scale {
173 fn frac(&self, v: f64) -> Option<f64> {
174 if !v.is_finite() {
175 return None;
176 }
177 if self.log {
178 if v <= 0.0 || self.lo <= 0.0 {
179 return None;
180 }
181 let (l0, l1) = (self.lo.log10(), self.hi.log10());
182 Some((v.log10() - l0) / (l1 - l0))
183 } else {
184 Some((v - self.lo) / (self.hi - self.lo))
185 }
186 }
187}
188
189fn log_bounds(raw: Option<(f64, f64)>) -> (f64, f64) {
191 match raw {
192 None => (1.0, 10.0),
193 Some((a, b)) => {
194 let lo = 10f64.powf(a.log10().floor());
195 let mut hi = 10f64.powf(b.log10().ceil());
196 if hi <= lo {
197 hi = lo * 10.0;
198 }
199 (lo, hi)
200 }
201 }
202}
203
204fn decade_label(k: i32) -> String {
205 if (0..=5).contains(&k) {
206 format!("{}", 10u64.pow(k as u32))
207 } else if (-3..0).contains(&k) {
208 let v = 10f64.powi(k);
209 format_tick(v, v)
210 } else {
211 format!("1e{k}")
212 }
213}
214
215#[derive(Debug, Clone, Default)]
217pub struct LineChart {
218 series: Vec<Series>,
219 x_axis: Axis,
220 y_axis: Axis,
221 y2_axis: Axis,
222 y_log: bool,
223 smooth: bool,
224 annotations: Vec<Annotation>,
225 crosshair: Option<Crosshair>,
226 block: Option<Block<'static>>,
227 marker: Marker,
228 mode: LineMode,
229 legend: LegendPosition,
230 legend_style: Option<Style>,
231 theme: Option<Theme>,
232 style: Option<Style>,
233}
234
235impl LineChart {
236 pub fn new(series: Vec<Series>) -> Self {
238 Self {
239 series,
240 ..Default::default()
241 }
242 }
243
244 setter!(
245 series: Vec<Series>
247 );
248
249 pub fn x_axis(mut self, axis: Axis) -> Self {
251 self.x_axis = axis;
252 if let Some(t) = &self.theme {
253 self.x_axis.theme_in_place(t);
254 }
255 self
256 }
257
258 pub fn y_axis(mut self, axis: Axis) -> Self {
260 self.y_axis = axis;
261 if let Some(t) = &self.theme {
262 self.y_axis.theme_in_place(t);
263 }
264 self
265 }
266
267 pub fn y2_axis(mut self, axis: Axis) -> Self {
269 self.y2_axis = axis;
270 if let Some(t) = &self.theme {
271 self.y2_axis.theme_in_place(t);
272 }
273 self
274 }
275
276 setter!(
277 y_log: bool
280 );
281
282 setter!(
283 smooth: bool
285 );
286
287 pub fn annotation(mut self, annotation: Annotation) -> Self {
289 self.annotations.push(annotation);
290 self
291 }
292
293 setter!(
294 crosshair: Option<Crosshair>
296 );
297
298 block_setter!(block, 'static);
299
300 setter!(
301 marker: Marker
303 );
304
305 setter!(
306 mode: LineMode
308 );
309
310 #[cfg(feature = "theme")]
313 pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
314 let t = theme.into();
315 self.x_axis.theme_in_place(&t);
316 self.y_axis.theme_in_place(&t);
317 self.y2_axis.theme_in_place(&t);
318 self.theme = Some(t);
319 self
320 }
321
322 base_style_setter!(style);
323
324 opt_setter!(
325 legend_style: Style
327 );
328
329 fn series_color(&self, i: usize, s: &Series) -> Color {
330 s.color.unwrap_or_else(|| match &self.theme {
331 Some(t) => t.color(i),
332 None => PALETTE[i % PALETTE.len()],
333 })
334 }
335
336 setter!(
337 legend: LegendPosition
339 );
340
341 fn has_secondary(&self) -> bool {
342 self.series.iter().any(|s| s.secondary && !s.is_empty())
343 }
344
345 fn y_range(&self, secondary: bool, positive_only: bool) -> Option<(f64, f64)> {
347 let mut r: Option<(f64, f64)> = None;
348 for v in self
349 .series
350 .iter()
351 .filter(|s| s.secondary == secondary)
352 .flat_map(|s| s.y_values())
353 .filter(|v| !positive_only || *v > 0.0)
354 {
355 r = Some(r.map_or((v, v), |(a, b)| (a.min(v), b.max(v))));
356 }
357 r
358 }
359
360 pub fn bounds(&self) -> ((f64, f64), (f64, f64)) {
362 let mut xs = (f64::INFINITY, f64::NEG_INFINITY);
363 for &(x, _) in self
364 .series
365 .iter()
366 .flat_map(|s| s.data.iter())
367 .filter(|(x, y)| x.is_finite() && y.is_finite())
368 {
369 xs = (xs.0.min(x), xs.1.max(x));
370 }
371 let x = self.x_axis.bounds.unwrap_or_else(|| {
372 if xs.0.is_finite() {
373 if xs.1 <= xs.0 {
374 (xs.0 - 1.0, xs.1 + 1.0)
375 } else {
376 xs
377 }
378 } else {
379 (0.0, 1.0)
380 }
381 });
382 let y = if self.y_log {
383 match self.y_axis.bounds {
384 Some((a, b)) if a > 0.0 && b > a => (a, b),
385 _ => log_bounds(self.y_range(false, true)),
386 }
387 } else {
388 self.y_axis.bounds.unwrap_or_else(|| {
389 self.y_range(false, false)
390 .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y_axis.ticks))
391 })
392 };
393 (x, y)
394 }
395
396 pub fn y2_bounds(&self) -> Option<(f64, f64)> {
398 if !self.has_secondary() {
399 return None;
400 }
401 Some(self.y2_axis.bounds.unwrap_or_else(|| {
402 self.y_range(true, false)
403 .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y2_axis.ticks))
404 }))
405 }
406
407 fn scales(&self) -> (Scale, Scale, Option<Scale>) {
408 let (xb, yb) = self.bounds();
409 (
410 Scale {
411 lo: xb.0,
412 hi: xb.1,
413 log: false,
414 },
415 Scale {
416 lo: yb.0,
417 hi: yb.1,
418 log: self.y_log,
419 },
420 self.y2_bounds().map(|b| Scale {
421 lo: b.0,
422 hi: b.1,
423 log: false,
424 }),
425 )
426 }
427
428 pub fn nearest(&self, x: f64, y: f64) -> Option<NearestPoint> {
432 let (sx, sy, sy2) = self.scales();
433 let target = (sx.frac(x)?, sy.frac(y)?);
434 let mut best: Option<(f64, NearestPoint)> = None;
435 for (si, s) in self.series.iter().enumerate() {
436 let ys = if s.secondary { sy2.unwrap_or(sy) } else { sy };
437 let pts = s
438 .data
439 .iter()
440 .map(|&(px, py)| match (sx.frac(px), ys.frac(py)) {
441 (Some(a), Some(b)) => (a, b),
442 _ => (f64::NAN, f64::NAN),
443 });
444 if let Some((i, d)) = nearest_point(pts, target, (1.0, 1.0)) {
445 if best.is_none_or(|(bd, _)| d < bd) {
446 let (px, py) = s.data[i];
447 best = Some((
448 d,
449 NearestPoint {
450 series: si,
451 index: i,
452 x: px,
453 y: py,
454 },
455 ));
456 }
457 }
458 }
459 best.map(|b| b.1)
460 }
461
462 fn y_marks(&self, b: (f64, f64)) -> Vec<(f64, String)> {
463 if !self.y_log || self.y_axis.labels.is_some() {
464 return self.y_axis.tick_marks(b);
465 }
466 let (l0, l1) = (b.0.log10(), b.1.log10());
467 if l1.is_nan() || l1 <= l0 {
468 return vec![];
469 }
470 let (k0, k1) = ((l0 - 1e-9).ceil() as i32, (l1 + 1e-9).floor() as i32);
471 let n = (i64::from(k1) - i64::from(k0) + 1).max(0) as usize;
472 let stride = n.div_ceil(self.y_axis.ticks.max(2)).max(1);
473 (k0..=k1)
474 .step_by(stride)
475 .map(|k| {
476 let label = match self.y_axis.format(10f64.powi(k)) {
477 Some(l) => l,
478 None => decade_label(k),
479 };
480 (f64::from(k) - l0, label)
481 })
482 .map(|(d, l)| (d / (l1 - l0), l))
483 .collect()
484 }
485
486 fn render_inner(&self, area: Rect, buf: &mut Buffer) {
487 let inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
488 let (xb, yb) = self.bounds();
489 if xb.1 <= xb.0 || yb.1 <= yb.0 {
490 return;
491 }
492 let (sx, sy, sy2) = self.scales();
493 let y_marks = self.y_marks(yb);
494 let x_marks = self.x_axis.tick_marks(xb);
495 let y2_marks = match (&sy2, self.y2_bounds()) {
496 (Some(_), Some(b)) if b.1 > b.0 => self.y2_axis.tick_marks(b),
497 _ => vec![],
498 };
499 let y2_reserve = if sy2.is_some() {
500 y2_marks
501 .iter()
502 .map(|(_, l)| text_width(l))
503 .max()
504 .unwrap_or(0)
505 + 1
506 } else {
507 0
508 };
509 let inner = Rect {
510 width: inner.width.saturating_sub(y2_reserve),
511 ..inner
512 };
513 let yw = y_marks
514 .iter()
515 .map(|(_, l)| text_width(l))
516 .max()
517 .unwrap_or(0);
518 let Some(a) = layout::compute(
519 inner,
520 yw,
521 !x_marks.is_empty(),
522 self.x_axis.title.is_some(),
523 self.y_axis.title.is_some(),
524 ) else {
525 return;
526 };
527 let (rx, ry) = self.marker.resolution();
528 let plot = a.plot;
529 let y_ticks: Vec<(u16, String)> = y_marks
530 .iter()
531 .map(|(f, l)| (layout::frac_row(*f, plot.height, ry), l.clone()))
532 .collect();
533 let x_ticks: Vec<(u16, String)> = x_marks
534 .iter()
535 .map(|(f, l)| (layout::frac_col(*f, plot.width, rx), l.clone()))
536 .collect();
537
538 let grid_rows: Vec<u16> = if self.y_axis.grid {
539 y_ticks.iter().map(|t| t.0).collect()
540 } else {
541 vec![]
542 };
543 let grid_cols: Vec<u16> = if self.x_axis.grid {
544 x_ticks.iter().map(|t| t.0).collect()
545 } else {
546 vec![]
547 };
548 layout::draw_grid(
549 buf,
550 plot,
551 &grid_cols,
552 &grid_rows,
553 self.x_axis.grid_style,
554 self.x_axis.grid_kind,
555 );
556
557 let clampi = |v: f64| v.round().clamp(-20_000.0, 20_000.0) as i32;
559 let (nw, nh) = (
560 (plot.width as f64 * rx as f64 - 1.0).max(0.0),
561 (plot.height as f64 * ry as f64 - 1.0).max(0.0),
562 );
563 let x_cell = |x: f64| sx.frac(x).map(|f| clampi(f * nw).div_euclid(rx as i32));
564 let y_cell = |y: f64| {
565 sy.frac(y)
566 .map(|f| clampi((1.0 - f) * nh).div_euclid(ry as i32))
567 };
568 draw_annotations(buf, plot, &self.annotations, &x_cell, &y_cell);
569
570 let mut canvas = Canvas::new(plot.width, plot.height, self.marker);
571 let (pw, ph) = (canvas.px_w(), canvas.px_h());
572 let proj = |x: f64, y: f64, sec: bool| -> Option<(i32, i32)> {
573 let ys = if sec { sy2.as_ref()? } else { &sy };
574 let (fx, fy) = (sx.frac(x)?, ys.frac(y)?);
575 Some((
576 clampi(fx * (pw - 1) as f64),
577 clampi((1.0 - fy) * (ph - 1) as f64),
578 ))
579 };
580 for (i, s) in self.series.iter().enumerate() {
581 let color = self.series_color(i, s);
582 let mode = s.mode.unwrap_or(self.mode);
583 let sec = s.secondary && sy2.is_some();
584 let mut pts: Vec<(i32, i32)> = Vec::with_capacity(s.data.len());
585 let mut band: Vec<(i32, i32, i32)> = Vec::new();
586 for (k, &(x, y)) in s.data.iter().enumerate() {
587 if !x.is_finite() || !y.is_finite() {
588 continue;
589 }
590 let Some(p) = proj(x, y, sec) else { continue };
591 pts.push(p);
592 if let Some(&(lo, hi)) = s.band.get(k) {
593 let lo_p = proj(x, lo, sec).map_or(ph - 1, |q| q.1);
594 let hi_p = proj(x, hi, sec).map_or(ph - 1, |q| q.1);
595 band.push((p.0, lo_p, hi_p));
596 }
597 if let Some(e) = s.y_err.get(k).filter(|e| e.is_finite()) {
598 let e = e.abs();
599 let lo_p = proj(x, y - e, sec).map_or(ph - 1, |q| q.1);
600 let hi_p = proj(x, y + e, sec).map_or(ph - 1, |q| q.1);
601 canvas.line(p.0, lo_p, p.0, hi_p, color);
602 canvas.line(p.0 - 2, lo_p, p.0 + 2, lo_p, color);
603 canvas.line(p.0 - 2, hi_p, p.0 + 2, hi_p, color);
604 }
605 }
606 fill_band(&mut canvas, &band, color);
607 if (s.smooth || self.smooth) && matches!(mode, LineMode::Line | LineMode::Area) {
608 pts = catmull_rom(&pts);
609 }
610 draw_series(&mut canvas, &pts, mode, color, s.fill_gradient.as_ref());
611 }
612 canvas.render(buf, plot);
613
614 if let Some(ch) = &self.crosshair {
615 if let (Some(c), Some(r)) = (x_cell(ch.x), y_cell(ch.y)) {
616 let themed = self.theme.as_ref().map(|t| ch.with_theme(t));
617 let ch = themed.as_ref().unwrap_or(ch);
618 crosshair::draw(buf, plot, ch, c, r, &self.tooltip_lines(ch));
619 }
620 }
621
622 layout::draw_axes(buf, &a, self.x_axis.style, self.y_axis.style);
623 layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.y_axis.label_style);
624 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.x_axis.label_style);
625 if y2_reserve > 0 {
626 for y in plot.y..a.axis_row {
627 buf.set_string(plot.right(), y, "│", self.y2_axis.style);
628 }
629 buf.set_string(plot.right(), a.axis_row, "┘", self.x_axis.style);
630 let mut last: Option<u16> = None;
631 for (f, label) in &y2_marks {
632 let row = layout::frac_row(*f, plot.height, ry);
633 if last == Some(row) {
634 continue;
635 }
636 last = Some(row);
637 buf.set_stringn(
638 plot.right() + 1,
639 plot.y + row,
640 label,
641 (y2_reserve - 1) as usize,
642 self.y2_axis.label_style,
643 );
644 }
645 }
646 layout::draw_titles(
647 buf,
648 inner,
649 &a,
650 self.x_axis
651 .title
652 .as_deref()
653 .map(|t| (t, self.x_axis.label_style)),
654 self.y_axis
655 .title
656 .as_deref()
657 .map(|t| (t, self.y_axis.label_style)),
658 );
659 self.draw_legend(buf, plot);
660 }
661
662 fn tooltip_lines(&self, ch: &Crosshair) -> Vec<String> {
663 let mut lines = vec![
664 format!("x {}", format_compact(ch.x)),
665 format!("y {}", format_compact(ch.y)),
666 ];
667 for s in self.series.iter().filter(|s| !s.name.is_empty()) {
668 if let Some((i, _)) =
669 nearest_point(s.data.iter().copied(), (ch.x, 0.0), (1.0, f64::INFINITY))
670 {
671 lines.push(format!("{} {}", s.name, format_compact(s.data[i].1)));
672 }
673 }
674 lines
675 }
676
677 fn draw_legend(&self, buf: &mut Buffer, plot: Rect) {
678 if self.legend == LegendPosition::None {
679 return;
680 }
681 let entries: Vec<(&str, Color)> = self
682 .series
683 .iter()
684 .enumerate()
685 .filter(|(_, s)| !s.name.is_empty())
686 .map(|(i, s)| (s.name.as_str(), self.series_color(i, s)))
687 .collect();
688 let w = entries
689 .iter()
690 .map(|(n, _)| text_width(n) + 2)
691 .max()
692 .unwrap_or(0);
693 if w == 0 || w > plot.width {
694 return;
695 }
696 let x = match self.legend {
697 LegendPosition::TopLeft | LegendPosition::BottomLeft => plot.x,
698 _ => plot.right() - w,
699 };
700 let label = self.legend_style.unwrap_or_else(|| {
701 Style::default().fg(self.theme.as_ref().map_or(Color::Gray, |t| t.muted))
702 });
703 for (i, (name, color)) in entries.iter().enumerate() {
704 let row = i as u16;
705 if row >= plot.height {
706 break;
707 }
708 let y = match self.legend {
709 LegendPosition::BottomLeft | LegendPosition::BottomRight => {
710 plot.bottom() - 1 - (entries.len() as u16 - 1 - row).min(plot.height - 1)
711 }
712 _ => plot.y + row,
713 };
714 buf.set_string(x, y, "●", Style::default().fg(*color));
715 buf.set_string(x + 2, y, name, label);
716 }
717 }
718}
719
720fn catmull_rom(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
722 if pts.len() < 3 {
723 return pts.to_vec();
724 }
725 let n = pts.len();
726 let mut out = Vec::with_capacity(n * 4);
727 for i in 0..n - 1 {
728 let p0 = pts[i.saturating_sub(1)];
729 let (p1, p2) = (pts[i], pts[i + 1]);
730 let p3 = pts[(i + 2).min(n - 1)];
731 out.push(p1);
732 let span = (p2.0 - p1.0).abs().max((p2.1 - p1.1).abs());
733 let steps = (span / 2).clamp(1, 64);
734 for k in 1..steps {
735 let t = k as f64 / steps as f64;
736 let (t2, t3) = (t * t, t * t * t);
737 let f = |a: i32, b: i32, c: i32, d: i32| {
738 let (a, b, c, d) = (a as f64, b as f64, c as f64, d as f64);
739 (0.5 * (2.0 * b
740 + (c - a) * t
741 + (2.0 * a - 5.0 * b + 4.0 * c - d) * t2
742 + (3.0 * b - a - 3.0 * c + d) * t3))
743 .round()
744 .clamp(-20_000.0, 20_000.0) as i32
745 };
746 out.push((f(p0.0, p1.0, p2.0, p3.0), f(p0.1, p1.1, p2.1, p3.1)));
747 }
748 }
749 out.push(pts[n - 1]);
750 out
751}
752
753fn fill_band(canvas: &mut Canvas, band: &[(i32, i32, i32)], color: Color) {
755 let (pw, ph) = (canvas.px_w(), canvas.px_h());
756 let column = |px: i32, a: i32, b: i32, canvas: &mut Canvas| {
757 if !(0..pw).contains(&px) {
758 return;
759 }
760 for py in a.min(b).max(0)..=a.max(b).min(ph - 1) {
761 if (px + py) % 2 == 0 {
762 canvas.set(px, py, color);
763 }
764 }
765 };
766 if band.len() == 1 {
767 column(band[0].0, band[0].1, band[0].2, canvas);
768 }
769 for w in band.windows(2) {
770 let (l, r) = if w[0].0 <= w[1].0 {
771 (w[0], w[1])
772 } else {
773 (w[1], w[0])
774 };
775 for px in l.0.max(0)..=r.0.min(pw - 1) {
776 let t = if r.0 == l.0 {
777 0.0
778 } else {
779 (px - l.0) as f64 / (r.0 - l.0) as f64
780 };
781 let lerp = |a: i32, b: i32| (a as f64 + t * (b - a) as f64).round() as i32;
782 column(px, lerp(l.1, r.1), lerp(l.2, r.2), canvas);
783 }
784 }
785}
786
787fn draw_series(
788 canvas: &mut Canvas,
789 pts: &[(i32, i32)],
790 mode: LineMode,
791 color: Color,
792 grad: Option<&Gradient>,
793) {
794 let bottom = canvas.px_h() - 1;
795 match mode {
796 LineMode::Scatter => {
797 for &(x, y) in pts {
798 canvas.blob(x, y, color);
799 }
800 }
801 LineMode::Line | LineMode::Area | LineMode::Step => {
802 if mode == LineMode::Area {
803 for w in pts.windows(2) {
804 fill_segment(canvas, w[0], w[1], bottom, color, grad);
805 }
806 }
807 if pts.len() == 1 {
808 canvas.set(pts[0].0, pts[0].1, color);
809 }
810 for w in pts.windows(2) {
811 let ((x0, y0), (x1, y1)) = (w[0], w[1]);
812 if mode == LineMode::Step {
813 canvas.line(x0, y0, x1, y0, color);
814 canvas.line(x1, y0, x1, y1, color);
815 } else {
816 canvas.line(x0, y0, x1, y1, color);
817 }
818 }
819 }
820 }
821}
822
823fn fill_segment(
824 canvas: &mut Canvas,
825 a: (i32, i32),
826 b: (i32, i32),
827 bottom: i32,
828 color: Color,
829 grad: Option<&Gradient>,
830) {
831 let (lo, hi) = if a.0 <= b.0 { (a, b) } else { (b, a) };
832 let start = lo.0.max(0);
833 let end = hi.0.min(canvas.px_w() - 1);
834 let (rx, ry) = canvas.marker().resolution();
836 let (sx, sy) = (if rx > 1 { 2 } else { 1 }, if ry > 1 { 2 } else { 1 });
837 for px in start..=end {
838 let t = if hi.0 == lo.0 {
839 0.0
840 } else {
841 (px - lo.0) as f64 / (hi.0 - lo.0) as f64
842 };
843 let py = (lo.1 as f64 + t * (hi.1 - lo.1) as f64).round() as i32;
844 for yy in py.max(0)..=bottom {
845 if px % sx == 0 && yy % sy == 0 {
846 let c = match grad {
847 Some(g) if bottom > 0 => g.color_at((bottom - yy) as f64 / bottom as f64),
848 _ => color,
849 };
850 canvas.set(px, yy, c);
851 }
852 }
853 }
854}
855
856impl LineChart {
857 fn render_into(&self, area: Rect, buf: &mut Buffer) {
858 self.render_inner(area, buf);
859 }
860}
861
862widget_impls!(LineChart);
863
864#[cfg(feature = "theme")]
865impl tui_nuances::Themed for LineChart {
866 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
867 self.theme(theme)
868 }
869}
870
871#[cfg(test)]
872mod tests {
873 use super::*;
874 use ratatui::widgets::Widget;
875
876 fn chart() -> LineChart {
877 LineChart::new(vec![
878 Series::new("a").values([1.0, 3.0, 2.0, 5.0]),
879 Series::new("b").data([(0.0, 0.0), (3.0, 4.0)]),
880 ])
881 }
882
883 #[test]
884 fn bounds_auto() {
885 let ((x0, x1), (y0, y1)) = chart().bounds();
886 assert_eq!((x0, x1), (0.0, 3.0));
887 assert!(y0 <= 0.0 && y1 >= 5.0);
888 }
889
890 #[test]
891 fn bounds_fixed_and_empty() {
892 let c = LineChart::default().x_axis(Axis::new().bounds(2.0, 4.0));
893 assert_eq!(c.bounds().0, (2.0, 4.0));
894 assert_eq!(c.bounds().1, (0.0, 1.0));
895 }
896
897 #[test]
898 fn bounds_single_point_padded() {
899 let c = LineChart::new(vec![Series::new("p").data([(1.0, 1.0)])]);
900 let ((x0, x1), (y0, y1)) = c.bounds();
901 assert!(x1 > x0 && y1 > y0);
902 }
903
904 #[test]
905 fn nan_points_ignored() {
906 let c = LineChart::new(vec![Series::new("p").data([
907 (f64::NAN, 1.0),
908 (1.0, 2.0),
909 (2.0, 4.0),
910 ])]);
911 assert_eq!(c.bounds().0, (1.0, 2.0));
912 }
913
914 #[test]
915 fn series_helpers() {
916 let s = Series::new("x")
917 .values([1.0, 2.0])
918 .color(Color::Red)
919 .mode(LineMode::Step);
920 assert_eq!(s.name(), "x");
921 assert_eq!(s.len(), 2);
922 assert!(!s.is_empty());
923 assert!(Series::new("e").is_empty());
924 }
925
926 #[test]
927 fn renders_without_panic_all_modes() {
928 for mode in [
929 LineMode::Line,
930 LineMode::Step,
931 LineMode::Area,
932 LineMode::Scatter,
933 ] {
934 for marker in [
935 Marker::Braille,
936 Marker::HalfBlock,
937 Marker::Block,
938 Marker::Dot,
939 ] {
940 let area = Rect::new(0, 0, 50, 14);
941 let mut buf = Buffer::empty(area);
942 chart()
943 .mode(mode)
944 .marker(marker)
945 .x_axis(Axis::new().title("x").grid(true))
946 .y_axis(Axis::new().title("y").grid(true))
947 .block(Block::bordered().title("t"))
948 .render(area, &mut buf);
949 }
950 }
951 }
952
953 #[test]
954 fn tiny_area_is_safe() {
955 for (w, h) in [(0, 0), (1, 1), (5, 3), (9, 4)] {
956 let area = Rect::new(0, 0, w, h);
957 let mut buf = Buffer::empty(area);
958 chart().render(area, &mut buf);
959 }
960 }
961
962 #[test]
963 fn draws_data_and_legend() {
964 let area = Rect::new(0, 0, 40, 12);
965 let mut buf = Buffer::empty(area);
966 chart().render(area, &mut buf);
967 let text: String = (0..12)
968 .flat_map(|y| (0..40).map(move |x| (x, y)))
969 .map(|p| buf[p].symbol().to_string())
970 .collect();
971 assert!(text.chars().any(|c| ('\u{2801}'..='\u{28ff}').contains(&c)));
972 assert!(text.contains('●'));
973 assert!(text.contains('└'));
974 }
975
976 #[test]
977 fn legend_none_hides() {
978 let area = Rect::new(0, 0, 40, 12);
979 let mut buf = Buffer::empty(area);
980 chart().legend(LegendPosition::None).render(area, &mut buf);
981 let text: String = (0..12)
982 .flat_map(|y| (0..40).map(move |x| (x, y)))
983 .map(|p| buf[p].symbol().to_string())
984 .collect();
985 assert!(!text.contains('●'));
986 }
987
988 fn text_of(buf: &Buffer, w: u16, h: u16) -> String {
989 (0..h)
990 .flat_map(|y| (0..w).map(move |x| (x, y)))
991 .map(|p| buf[p].symbol().to_string())
992 .collect()
993 }
994
995 #[test]
996 fn log_bounds_decades_and_labels() {
997 let c = LineChart::new(vec![Series::new("a").data([
998 (0.0, 3.0),
999 (1.0, 4500.0),
1000 (2.0, -1.0),
1001 ])])
1002 .y_log(true);
1003 assert_eq!(c.bounds().1, (1.0, 10_000.0));
1004 let m = c.y_marks((1.0, 10_000.0));
1005 assert_eq!(m.first().unwrap().1, "1");
1006 assert_eq!(m.last().unwrap().1, "10000");
1007 assert!((m[2].0 - 0.5).abs() < 1e-9);
1008 assert_eq!(LineChart::default().y_log(true).bounds().1, (1.0, 10.0));
1009 }
1010
1011 #[test]
1012 fn secondary_axis_bounds_and_render() {
1013 let c = LineChart::new(vec![
1014 Series::new("a").values([1.0, 2.0]),
1015 Series::new("b").values([100.0, 900.0]).secondary_axis(true),
1016 ]);
1017 assert!(c.bounds().1 .1 < 10.0);
1018 let b2 = c.y2_bounds().unwrap();
1019 assert!(b2.1 >= 900.0);
1020 let area = Rect::new(0, 0, 40, 10);
1021 let mut buf = Buffer::empty(area);
1022 c.render(area, &mut buf);
1023 assert!(text_of(&buf, 40, 10).contains('┘'));
1024 assert!(LineChart::default().y2_bounds().is_none());
1025 }
1026
1027 #[test]
1028 fn err_band_extend_bounds() {
1029 let c = LineChart::new(vec![Series::new("a")
1030 .values([1.0, 2.0])
1031 .y_err([10.0, 10.0])]);
1032 assert!(c.bounds().1 .1 >= 12.0);
1033 let c = LineChart::new(vec![Series::new("a")
1034 .values([1.0, 2.0])
1035 .band([(-5.0, 1.0), (0.0, 3.0)])]);
1036 assert!(c.bounds().1 .0 <= -5.0);
1037 }
1038
1039 #[test]
1040 fn catmull_densifies() {
1041 let p = catmull_rom(&[(0, 0), (20, 10), (40, 0), (60, 10)]);
1042 assert!(p.len() > 4);
1043 assert_eq!(p[0], (0, 0));
1044 assert_eq!(*p.last().unwrap(), (60, 10));
1045 assert_eq!(catmull_rom(&[(1, 1)]), vec![(1, 1)]);
1046 }
1047
1048 #[test]
1049 fn nearest_finds_point() {
1050 let n = chart().nearest(3.0, 4.0).unwrap();
1051 assert_eq!((n.series, n.index), (1, 1));
1052 assert!(LineChart::default().nearest(0.0, 0.0).is_none());
1053 }
1054
1055 #[test]
1056 fn features_render_safely_everywhere() {
1057 let c = LineChart::new(vec![
1058 Series::new("a")
1059 .values([1.0, 0.0, f64::NAN, 5.0])
1060 .y_err([0.5, f64::NAN, 1.0])
1061 .smooth(true),
1062 Series::new("b")
1063 .values([10.0, 20.0, 5.0])
1064 .band([(1.0, 30.0), (2.0, 40.0), (0.0, 9.0)])
1065 .secondary_axis(true),
1066 ])
1067 .y_log(true)
1068 .annotation(Annotation::hline(2.0).text("lim"))
1069 .annotation(Annotation::x_region(0.5, 1.5))
1070 .crosshair(Some(Crosshair::new(1.0, 2.0)));
1071 for (w, h) in [(0, 0), (1, 1), (5, 3), (12, 6), (60, 20)] {
1072 let area = Rect::new(0, 0, w, h);
1073 let mut buf = Buffer::empty(area);
1074 (&c).render(area, &mut buf);
1075 }
1076 }
1077
1078 #[test]
1079 fn crosshair_draws_tooltip() {
1080 let area = Rect::new(0, 0, 50, 16);
1081 let mut buf = Buffer::empty(area);
1082 chart()
1083 .crosshair(Some(Crosshair::new(1.0, 2.0)))
1084 .render(area, &mut buf);
1085 let t = text_of(&buf, 50, 16);
1086 assert!(t.contains('┼'));
1087 assert!(t.contains("x 1"));
1088 }
1089
1090 #[cfg(feature = "theme")]
1091 #[test]
1092 fn crosshair_uses_theme_colors() {
1093 let th = Theme::dracula();
1094 let area = Rect::new(0, 0, 50, 16);
1095 let mut buf = Buffer::empty(area);
1096 chart()
1097 .theme(&th)
1098 .crosshair(Some(Crosshair::new(1.0, 2.0)))
1099 .render(area, &mut buf);
1100 assert!(buf
1101 .content()
1102 .iter()
1103 .any(|c| c.symbol() == "┼" && c.fg == th.crosshair));
1104 let mut buf = Buffer::empty(area);
1105 let own = Style::default().fg(Color::Red);
1106 chart()
1107 .theme(&th)
1108 .crosshair(Some(Crosshair::new(1.0, 2.0).style(own)))
1109 .render(area, &mut buf);
1110 assert!(buf
1111 .content()
1112 .iter()
1113 .any(|c| c.symbol() == "┼" && c.fg == Color::Red));
1114 }
1115}