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)]
229pub struct LineChart {
230 series: Vec<Series>,
231 x_axis: Axis,
232 y_axis: Axis,
233 y2_axis: Axis,
234 y_log: bool,
235 smooth: bool,
236 annotations: Vec<Annotation>,
237 crosshair: Option<Crosshair>,
238 block: Option<Block<'static>>,
239 marker: Marker,
240 mode: LineMode,
241 legend: LegendPosition,
242 legend_style: Option<Style>,
243 theme: Option<Theme>,
244 style: Option<Style>,
245}
246
247impl LineChart {
248 pub fn new(series: Vec<Series>) -> Self {
250 Self {
251 series,
252 ..Default::default()
253 }
254 }
255
256 setter!(
257 series: Vec<Series>
259 );
260
261 pub fn x_axis(mut self, axis: Axis) -> Self {
263 self.x_axis = axis;
264 if let Some(t) = &self.theme {
265 self.x_axis.theme_in_place(t);
266 }
267 self
268 }
269
270 pub fn y_axis(mut self, axis: Axis) -> Self {
272 self.y_axis = axis;
273 if let Some(t) = &self.theme {
274 self.y_axis.theme_in_place(t);
275 }
276 self
277 }
278
279 pub fn y2_axis(mut self, axis: Axis) -> Self {
281 self.y2_axis = axis;
282 if let Some(t) = &self.theme {
283 self.y2_axis.theme_in_place(t);
284 }
285 self
286 }
287
288 setter!(
289 y_log: bool
292 );
293
294 setter!(
295 smooth: bool
297 );
298
299 pub fn annotation(mut self, annotation: Annotation) -> Self {
301 self.annotations.push(annotation);
302 self
303 }
304
305 setter!(
306 crosshair: Option<Crosshair>
308 );
309
310 block_setter!(block, 'static);
311
312 setter!(
313 marker: Marker
315 );
316
317 setter!(
318 mode: LineMode
320 );
321
322 #[cfg(feature = "theme")]
325 pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
326 let t = theme.into();
327 self.x_axis.theme_in_place(&t);
328 self.y_axis.theme_in_place(&t);
329 self.y2_axis.theme_in_place(&t);
330 self.theme = Some(t);
331 self
332 }
333
334 base_style_setter!(style);
335
336 opt_setter!(
337 legend_style: Style
339 );
340
341 fn series_color(&self, i: usize, s: &Series) -> Color {
342 s.color.unwrap_or_else(|| match &self.theme {
343 Some(t) => t.color(i),
344 None => PALETTE[i % PALETTE.len()],
345 })
346 }
347
348 setter!(
349 legend: LegendPosition
351 );
352
353 fn has_secondary(&self) -> bool {
354 self.series.iter().any(|s| s.secondary && !s.is_empty())
355 }
356
357 fn y_range(&self, secondary: bool, positive_only: bool) -> Option<(f64, f64)> {
359 let mut r: Option<(f64, f64)> = None;
360 for v in self
361 .series
362 .iter()
363 .filter(|s| s.secondary == secondary)
364 .flat_map(|s| s.y_values())
365 .filter(|v| !positive_only || *v > 0.0)
366 {
367 r = Some(r.map_or((v, v), |(a, b)| (a.min(v), b.max(v))));
368 }
369 r
370 }
371
372 pub fn bounds(&self) -> ((f64, f64), (f64, f64)) {
374 let mut xs = (f64::INFINITY, f64::NEG_INFINITY);
375 for &(x, _) in self
376 .series
377 .iter()
378 .flat_map(|s| s.data.iter())
379 .filter(|(x, y)| x.is_finite() && y.is_finite())
380 {
381 xs = (xs.0.min(x), xs.1.max(x));
382 }
383 let x = self.x_axis.bounds.unwrap_or_else(|| {
384 if xs.0.is_finite() {
385 if xs.1 <= xs.0 {
386 (xs.0 - 1.0, xs.1 + 1.0)
387 } else {
388 xs
389 }
390 } else {
391 (0.0, 1.0)
392 }
393 });
394 let y = if self.y_log {
395 match self.y_axis.bounds {
396 Some((a, b)) if a > 0.0 && b > a => (a, b),
397 _ => log_bounds(self.y_range(false, true)),
398 }
399 } else {
400 self.y_axis.bounds.unwrap_or_else(|| {
401 self.y_range(false, false)
402 .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y_axis.ticks))
403 })
404 };
405 (x, y)
406 }
407
408 pub fn y2_bounds(&self) -> Option<(f64, f64)> {
410 if !self.has_secondary() {
411 return None;
412 }
413 Some(self.y2_axis.bounds.unwrap_or_else(|| {
414 self.y_range(true, false)
415 .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y2_axis.ticks))
416 }))
417 }
418
419 fn scales(&self) -> (Scale, Scale, Option<Scale>) {
420 let (xb, yb) = self.bounds();
421 (
422 Scale {
423 lo: xb.0,
424 hi: xb.1,
425 log: false,
426 },
427 Scale {
428 lo: yb.0,
429 hi: yb.1,
430 log: self.y_log,
431 },
432 self.y2_bounds().map(|b| Scale {
433 lo: b.0,
434 hi: b.1,
435 log: false,
436 }),
437 )
438 }
439
440 pub fn nearest(&self, x: f64, y: f64) -> Option<NearestPoint> {
444 let (sx, sy, sy2) = self.scales();
445 let target = (sx.frac(x)?, sy.frac(y)?);
446 let mut best: Option<(f64, NearestPoint)> = None;
447 for (si, s) in self.series.iter().enumerate() {
448 let ys = if s.secondary { sy2.unwrap_or(sy) } else { sy };
449 let pts = s
450 .data
451 .iter()
452 .map(|&(px, py)| match (sx.frac(px), ys.frac(py)) {
453 (Some(a), Some(b)) => (a, b),
454 _ => (f64::NAN, f64::NAN),
455 });
456 if let Some((i, d)) = nearest_point(pts, target, (1.0, 1.0)) {
457 if best.is_none_or(|(bd, _)| d < bd) {
458 let (px, py) = s.data[i];
459 best = Some((
460 d,
461 NearestPoint {
462 series: si,
463 index: i,
464 x: px,
465 y: py,
466 },
467 ));
468 }
469 }
470 }
471 best.map(|b| b.1)
472 }
473
474 fn y_marks(&self, b: (f64, f64)) -> Vec<(f64, String)> {
475 if !self.y_log || self.y_axis.labels.is_some() {
476 return self.y_axis.tick_marks(b);
477 }
478 let (l0, l1) = (b.0.log10(), b.1.log10());
479 if l1.is_nan() || l1 <= l0 {
480 return vec![];
481 }
482 let (k0, k1) = ((l0 - 1e-9).ceil() as i32, (l1 + 1e-9).floor() as i32);
483 let n = (i64::from(k1) - i64::from(k0) + 1).max(0) as usize;
484 let stride = n.div_ceil(self.y_axis.ticks.max(2)).max(1);
485 (k0..=k1)
486 .step_by(stride)
487 .map(|k| {
488 let label = match self.y_axis.format(10f64.powi(k)) {
489 Some(l) => l,
490 None => decade_label(k),
491 };
492 (f64::from(k) - l0, label)
493 })
494 .map(|(d, l)| (d / (l1 - l0), l))
495 .collect()
496 }
497
498 fn render_inner(&self, area: Rect, buf: &mut Buffer) {
499 let inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
500 let (xb, yb) = self.bounds();
501 if xb.1 <= xb.0 || yb.1 <= yb.0 {
502 return;
503 }
504 let (sx, sy, sy2) = self.scales();
505 let y_marks = self.y_marks(yb);
506 let x_marks = self.x_axis.tick_marks(xb);
507 let y2_marks = match (&sy2, self.y2_bounds()) {
508 (Some(_), Some(b)) if b.1 > b.0 => self.y2_axis.tick_marks(b),
509 _ => vec![],
510 };
511 let y2_reserve = if sy2.is_some() {
512 y2_marks
513 .iter()
514 .map(|(_, l)| text_width(l))
515 .max()
516 .unwrap_or(0)
517 + 1
518 } else {
519 0
520 };
521 let inner = Rect {
522 width: inner.width.saturating_sub(y2_reserve),
523 ..inner
524 };
525 let yw = y_marks
526 .iter()
527 .map(|(_, l)| text_width(l))
528 .max()
529 .unwrap_or(0);
530 let Some(a) = layout::compute(
531 inner,
532 yw,
533 !x_marks.is_empty(),
534 self.x_axis.title.is_some(),
535 self.y_axis.title.is_some(),
536 ) else {
537 return;
538 };
539 let (rx, ry) = self.marker.resolution();
540 let plot = a.plot;
541 let y_ticks: Vec<(u16, String)> = y_marks
542 .iter()
543 .map(|(f, l)| (layout::frac_row(*f, plot.height, ry), l.clone()))
544 .collect();
545 let x_ticks: Vec<(u16, String)> = x_marks
546 .iter()
547 .map(|(f, l)| (layout::frac_col(*f, plot.width, rx), l.clone()))
548 .collect();
549
550 let grid_rows: Vec<u16> = if self.y_axis.grid {
551 y_ticks.iter().map(|t| t.0).collect()
552 } else {
553 vec![]
554 };
555 let grid_cols: Vec<u16> = if self.x_axis.grid {
556 x_ticks.iter().map(|t| t.0).collect()
557 } else {
558 vec![]
559 };
560 layout::draw_grid(
561 buf,
562 plot,
563 &grid_cols,
564 &grid_rows,
565 self.x_axis.grid_style,
566 self.x_axis.grid_kind,
567 );
568
569 let clampi = |v: f64| v.round().clamp(-20_000.0, 20_000.0) as i32;
571 let (nw, nh) = (
572 (plot.width as f64 * rx as f64 - 1.0).max(0.0),
573 (plot.height as f64 * ry as f64 - 1.0).max(0.0),
574 );
575 let x_cell = |x: f64| sx.frac(x).map(|f| clampi(f * nw).div_euclid(rx as i32));
576 let y_cell = |y: f64| {
577 sy.frac(y)
578 .map(|f| clampi((1.0 - f) * nh).div_euclid(ry as i32))
579 };
580 draw_annotations(buf, plot, &self.annotations, &x_cell, &y_cell);
581
582 let mut canvas = Canvas::new(plot.width, plot.height, self.marker);
583 let (pw, ph) = (canvas.px_w(), canvas.px_h());
584 let proj = |x: f64, y: f64, sec: bool| -> Option<(i32, i32)> {
585 let ys = if sec { sy2.as_ref()? } else { &sy };
586 let (fx, fy) = (sx.frac(x)?, ys.frac(y)?);
587 Some((
588 clampi(fx * (pw - 1) as f64),
589 clampi((1.0 - fy) * (ph - 1) as f64),
590 ))
591 };
592 for (i, s) in self.series.iter().enumerate() {
593 let color = self.series_color(i, s);
594 let mode = s.mode.unwrap_or(self.mode);
595 let sec = s.secondary && sy2.is_some();
596 let mut pts: Vec<(i32, i32)> = Vec::with_capacity(s.data.len());
597 let mut band: Vec<(i32, i32, i32)> = Vec::new();
598 for (k, &(x, y)) in s.data.iter().enumerate() {
599 if !x.is_finite() || !y.is_finite() {
600 continue;
601 }
602 let Some(p) = proj(x, y, sec) else { continue };
603 pts.push(p);
604 if let Some(&(lo, hi)) = s.band.get(k) {
605 let lo_p = proj(x, lo, sec).map_or(ph - 1, |q| q.1);
606 let hi_p = proj(x, hi, sec).map_or(ph - 1, |q| q.1);
607 band.push((p.0, lo_p, hi_p));
608 }
609 if let Some(e) = s.y_err.get(k).filter(|e| e.is_finite()) {
610 let e = e.abs();
611 let lo_p = proj(x, y - e, sec).map_or(ph - 1, |q| q.1);
612 let hi_p = proj(x, y + e, sec).map_or(ph - 1, |q| q.1);
613 canvas.line(p.0, lo_p, p.0, hi_p, color);
614 canvas.line(p.0 - 2, lo_p, p.0 + 2, lo_p, color);
615 canvas.line(p.0 - 2, hi_p, p.0 + 2, hi_p, color);
616 }
617 }
618 fill_band(&mut canvas, &band, color);
619 if (s.smooth || self.smooth) && matches!(mode, LineMode::Line | LineMode::Area) {
620 pts = catmull_rom(&pts);
621 }
622 if mode != LineMode::Scatter && pts.len() > canvas.px_w() as usize * 4 {
623 pts = decimate(&pts);
624 }
625 draw_series(&mut canvas, &pts, mode, color, s.fill_gradient.as_ref());
626 }
627 canvas.render(buf, plot);
628
629 if let Some(ch) = &self.crosshair {
630 if let (Some(c), Some(r)) = (x_cell(ch.x), y_cell(ch.y)) {
631 let themed = self.theme.as_ref().map(|t| ch.with_theme(t));
632 let ch = themed.as_ref().unwrap_or(ch);
633 crosshair::draw(buf, plot, ch, c, r, &self.tooltip_lines(ch));
634 }
635 }
636
637 layout::draw_axes(buf, &a, self.x_axis.style, self.y_axis.style);
638 layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.y_axis.label_style);
639 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.x_axis.label_style);
640 if y2_reserve > 0 {
641 for y in plot.y..a.axis_row {
642 buf.set_string(plot.right(), y, "│", self.y2_axis.style);
643 }
644 buf.set_string(plot.right(), a.axis_row, "┘", self.x_axis.style);
645 let mut last: Option<u16> = None;
646 for (f, label) in &y2_marks {
647 let row = layout::frac_row(*f, plot.height, ry);
648 if last == Some(row) {
649 continue;
650 }
651 last = Some(row);
652 buf.set_stringn(
653 plot.right() + 1,
654 plot.y + row,
655 label,
656 (y2_reserve - 1) as usize,
657 self.y2_axis.label_style,
658 );
659 }
660 }
661 layout::draw_titles(
662 buf,
663 inner,
664 &a,
665 self.x_axis
666 .title
667 .as_deref()
668 .map(|t| (t, self.x_axis.label_style)),
669 self.y_axis
670 .title
671 .as_deref()
672 .map(|t| (t, self.y_axis.label_style)),
673 );
674 self.draw_legend(buf, plot);
675 }
676
677 fn tooltip_lines(&self, ch: &Crosshair) -> Vec<String> {
678 let mut lines = vec![
679 format!("x {}", format_compact(ch.x)),
680 format!("y {}", format_compact(ch.y)),
681 ];
682 for s in self.series.iter().filter(|s| !s.name.is_empty()) {
683 if let Some((i, _)) =
684 nearest_point(s.data.iter().copied(), (ch.x, 0.0), (1.0, f64::INFINITY))
685 {
686 lines.push(format!("{} {}", s.name, format_compact(s.data[i].1)));
687 }
688 }
689 lines
690 }
691
692 fn draw_legend(&self, buf: &mut Buffer, plot: Rect) {
693 if self.legend == LegendPosition::None {
694 return;
695 }
696 let entries: Vec<(&str, Color)> = self
697 .series
698 .iter()
699 .enumerate()
700 .filter(|(_, s)| !s.name.is_empty())
701 .map(|(i, s)| (s.name.as_str(), self.series_color(i, s)))
702 .collect();
703 let w = entries
704 .iter()
705 .map(|(n, _)| text_width(n) + 2)
706 .max()
707 .unwrap_or(0);
708 if w == 0 || w > plot.width {
709 return;
710 }
711 let x = match self.legend {
712 LegendPosition::TopLeft | LegendPosition::BottomLeft => plot.x,
713 _ => plot.right() - w,
714 };
715 let label = self.legend_style.unwrap_or_else(|| {
716 Style::default().fg(self.theme.as_ref().map_or(Color::Gray, |t| t.muted))
717 });
718 for (i, (name, color)) in entries.iter().enumerate() {
719 let row = i as u16;
720 if row >= plot.height {
721 break;
722 }
723 let y = match self.legend {
724 LegendPosition::BottomLeft | LegendPosition::BottomRight => {
725 plot.bottom() - 1 - (entries.len() as u16 - 1 - row).min(plot.height - 1)
726 }
727 _ => plot.y + row,
728 };
729 buf.set_string(x, y, "●", Style::default().fg(*color));
730 buf.set_string(x + 2, y, name, label);
731 }
732 }
733}
734
735fn catmull_rom(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
737 if pts.len() < 3 {
738 return pts.to_vec();
739 }
740 let n = pts.len();
741 let mut out = Vec::with_capacity(n * 4);
742 for i in 0..n - 1 {
743 let p0 = pts[i.saturating_sub(1)];
744 let (p1, p2) = (pts[i], pts[i + 1]);
745 let p3 = pts[(i + 2).min(n - 1)];
746 out.push(p1);
747 let span = (p2.0 - p1.0).abs().max((p2.1 - p1.1).abs());
748 let steps = (span / 2).clamp(1, 64);
749 for k in 1..steps {
750 let t = k as f64 / steps as f64;
751 let (t2, t3) = (t * t, t * t * t);
752 let f = |a: i32, b: i32, c: i32, d: i32| {
753 let (a, b, c, d) = (a as f64, b as f64, c as f64, d as f64);
754 (0.5 * (2.0 * b
755 + (c - a) * t
756 + (2.0 * a - 5.0 * b + 4.0 * c - d) * t2
757 + (3.0 * b - a - 3.0 * c + d) * t3))
758 .round()
759 .clamp(-20_000.0, 20_000.0) as i32
760 };
761 out.push((f(p0.0, p1.0, p2.0, p3.0), f(p0.1, p1.1, p2.1, p3.1)));
762 }
763 }
764 out.push(pts[n - 1]);
765 out
766}
767
768fn fill_band(canvas: &mut Canvas, band: &[(i32, i32, i32)], color: Color) {
770 let (pw, ph) = (canvas.px_w(), canvas.px_h());
771 let column = |px: i32, a: i32, b: i32, canvas: &mut Canvas| {
772 if !(0..pw).contains(&px) {
773 return;
774 }
775 for py in a.min(b).max(0)..=a.max(b).min(ph - 1) {
776 if (px + py) % 2 == 0 {
777 canvas.set(px, py, color);
778 }
779 }
780 };
781 if band.len() == 1 {
782 column(band[0].0, band[0].1, band[0].2, canvas);
783 }
784 for w in band.windows(2) {
785 let (l, r) = if w[0].0 <= w[1].0 {
786 (w[0], w[1])
787 } else {
788 (w[1], w[0])
789 };
790 for px in l.0.max(0)..=r.0.min(pw - 1) {
791 let t = if r.0 == l.0 {
792 0.0
793 } else {
794 (px - l.0) as f64 / (r.0 - l.0) as f64
795 };
796 let lerp = |a: i32, b: i32| (a as f64 + t * (b - a) as f64).round() as i32;
797 column(px, lerp(l.1, r.1), lerp(l.2, r.2), canvas);
798 }
799 }
800}
801
802fn decimate(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
806 if pts.windows(2).any(|w| w[1].0 < w[0].0) {
807 return pts.to_vec();
808 }
809 let mut out = Vec::with_capacity(pts.len() / 8 + 8);
810 let mut i = 0;
811 while i < pts.len() {
812 let x = pts[i].0;
813 let mut j = i;
814 let (mut lo, mut hi) = (i, i);
815 while j < pts.len() && pts[j].0 == x {
816 if pts[j].1 < pts[lo].1 {
817 lo = j;
818 }
819 if pts[j].1 > pts[hi].1 {
820 hi = j;
821 }
822 j += 1;
823 }
824 let mut keep = [i, lo, hi, j - 1];
825 keep.sort_unstable();
826 let mut last = usize::MAX;
827 for k in keep {
828 if k != last {
829 out.push(pts[k]);
830 last = k;
831 }
832 }
833 i = j;
834 }
835 out
836}
837
838fn draw_series(
839 canvas: &mut Canvas,
840 pts: &[(i32, i32)],
841 mode: LineMode,
842 color: Color,
843 grad: Option<&Gradient>,
844) {
845 let bottom = canvas.px_h() - 1;
846 match mode {
847 LineMode::Scatter => {
848 for &(x, y) in pts {
849 canvas.blob(x, y, color);
850 }
851 }
852 LineMode::Line | LineMode::Area | LineMode::Step => {
853 if mode == LineMode::Area {
854 for w in pts.windows(2) {
855 fill_segment(canvas, w[0], w[1], bottom, color, grad);
856 }
857 }
858 if pts.len() == 1 {
859 canvas.set(pts[0].0, pts[0].1, color);
860 }
861 for w in pts.windows(2) {
862 let ((x0, y0), (x1, y1)) = (w[0], w[1]);
863 if mode == LineMode::Step {
864 canvas.line(x0, y0, x1, y0, color);
865 canvas.line(x1, y0, x1, y1, color);
866 } else {
867 canvas.line(x0, y0, x1, y1, color);
868 }
869 }
870 }
871 }
872}
873
874fn fill_segment(
875 canvas: &mut Canvas,
876 a: (i32, i32),
877 b: (i32, i32),
878 bottom: i32,
879 color: Color,
880 grad: Option<&Gradient>,
881) {
882 let (lo, hi) = if a.0 <= b.0 { (a, b) } else { (b, a) };
883 let start = lo.0.max(0);
884 let end = hi.0.min(canvas.px_w() - 1);
885 let (rx, ry) = canvas.marker().resolution();
887 let (sx, sy) = (if rx > 1 { 2 } else { 1 }, if ry > 1 { 2 } else { 1 });
888 for px in start..=end {
889 let t = if hi.0 == lo.0 {
890 0.0
891 } else {
892 (px - lo.0) as f64 / (hi.0 - lo.0) as f64
893 };
894 let py = (lo.1 as f64 + t * (hi.1 - lo.1) as f64).round() as i32;
895 for yy in py.max(0)..=bottom {
896 if px % sx == 0 && yy % sy == 0 {
897 let c = match grad {
898 Some(g) if bottom > 0 => g.color_at((bottom - yy) as f64 / bottom as f64),
899 _ => color,
900 };
901 canvas.set(px, yy, c);
902 }
903 }
904 }
905}
906
907impl LineChart {
908 fn render_into(&self, area: Rect, buf: &mut Buffer) {
909 self.render_inner(area, buf);
910 }
911}
912
913widget_impls!(LineChart);
914
915#[cfg(feature = "theme")]
916impl tui_nuances::Themed for LineChart {
917 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
918 self.theme(theme)
919 }
920}
921
922#[cfg(test)]
923mod tests {
924 use super::*;
925 use ratatui::widgets::Widget;
926
927 fn chart() -> LineChart {
928 LineChart::new(vec![
929 Series::new("a").values([1.0, 3.0, 2.0, 5.0]),
930 Series::new("b").data([(0.0, 0.0), (3.0, 4.0)]),
931 ])
932 }
933
934 #[test]
935 fn bounds_auto() {
936 let ((x0, x1), (y0, y1)) = chart().bounds();
937 assert_eq!((x0, x1), (0.0, 3.0));
938 assert!(y0 <= 0.0 && y1 >= 5.0);
939 }
940
941 #[test]
942 fn bounds_fixed_and_empty() {
943 let c = LineChart::default().x_axis(Axis::new().bounds(2.0, 4.0));
944 assert_eq!(c.bounds().0, (2.0, 4.0));
945 assert_eq!(c.bounds().1, (0.0, 1.0));
946 }
947
948 #[test]
949 fn bounds_single_point_padded() {
950 let c = LineChart::new(vec![Series::new("p").data([(1.0, 1.0)])]);
951 let ((x0, x1), (y0, y1)) = c.bounds();
952 assert!(x1 > x0 && y1 > y0);
953 }
954
955 #[test]
956 fn nan_points_ignored() {
957 let c = LineChart::new(vec![Series::new("p").data([
958 (f64::NAN, 1.0),
959 (1.0, 2.0),
960 (2.0, 4.0),
961 ])]);
962 assert_eq!(c.bounds().0, (1.0, 2.0));
963 }
964
965 #[test]
966 fn series_helpers() {
967 let s = Series::new("x")
968 .values([1.0, 2.0])
969 .color(Color::Red)
970 .mode(LineMode::Step);
971 assert_eq!(s.name(), "x");
972 assert_eq!(s.len(), 2);
973 assert!(!s.is_empty());
974 assert!(Series::new("e").is_empty());
975 }
976
977 #[test]
978 fn renders_without_panic_all_modes() {
979 for mode in [
980 LineMode::Line,
981 LineMode::Step,
982 LineMode::Area,
983 LineMode::Scatter,
984 ] {
985 for marker in [
986 Marker::Braille,
987 Marker::HalfBlock,
988 Marker::Block,
989 Marker::Dot,
990 ] {
991 let area = Rect::new(0, 0, 50, 14);
992 let mut buf = Buffer::empty(area);
993 chart()
994 .mode(mode)
995 .marker(marker)
996 .x_axis(Axis::new().title("x").grid(true))
997 .y_axis(Axis::new().title("y").grid(true))
998 .block(Block::bordered().title("t"))
999 .render(area, &mut buf);
1000 }
1001 }
1002 }
1003
1004 #[test]
1005 fn tiny_area_is_safe() {
1006 for (w, h) in [(0, 0), (1, 1), (5, 3), (9, 4)] {
1007 let area = Rect::new(0, 0, w, h);
1008 let mut buf = Buffer::empty(area);
1009 chart().render(area, &mut buf);
1010 }
1011 }
1012
1013 #[test]
1014 fn draws_data_and_legend() {
1015 let area = Rect::new(0, 0, 40, 12);
1016 let mut buf = Buffer::empty(area);
1017 chart().render(area, &mut buf);
1018 let text: String = (0..12)
1019 .flat_map(|y| (0..40).map(move |x| (x, y)))
1020 .map(|p| buf[p].symbol().to_string())
1021 .collect();
1022 assert!(text.chars().any(|c| ('\u{2801}'..='\u{28ff}').contains(&c)));
1023 assert!(text.contains('●'));
1024 assert!(text.contains('└'));
1025 }
1026
1027 #[test]
1028 fn legend_none_hides() {
1029 let area = Rect::new(0, 0, 40, 12);
1030 let mut buf = Buffer::empty(area);
1031 chart().legend(LegendPosition::None).render(area, &mut buf);
1032 let text: String = (0..12)
1033 .flat_map(|y| (0..40).map(move |x| (x, y)))
1034 .map(|p| buf[p].symbol().to_string())
1035 .collect();
1036 assert!(!text.contains('●'));
1037 }
1038
1039 fn text_of(buf: &Buffer, w: u16, h: u16) -> String {
1040 (0..h)
1041 .flat_map(|y| (0..w).map(move |x| (x, y)))
1042 .map(|p| buf[p].symbol().to_string())
1043 .collect()
1044 }
1045
1046 #[test]
1047 fn log_bounds_decades_and_labels() {
1048 let c = LineChart::new(vec![Series::new("a").data([
1049 (0.0, 3.0),
1050 (1.0, 4500.0),
1051 (2.0, -1.0),
1052 ])])
1053 .y_log(true);
1054 assert_eq!(c.bounds().1, (1.0, 10_000.0));
1055 let m = c.y_marks((1.0, 10_000.0));
1056 assert_eq!(m.first().unwrap().1, "1");
1057 assert_eq!(m.last().unwrap().1, "10000");
1058 assert!((m[2].0 - 0.5).abs() < 1e-9);
1059 assert_eq!(LineChart::default().y_log(true).bounds().1, (1.0, 10.0));
1060 }
1061
1062 #[test]
1063 fn secondary_axis_bounds_and_render() {
1064 let c = LineChart::new(vec![
1065 Series::new("a").values([1.0, 2.0]),
1066 Series::new("b").values([100.0, 900.0]).secondary_axis(true),
1067 ]);
1068 assert!(c.bounds().1 .1 < 10.0);
1069 let b2 = c.y2_bounds().unwrap();
1070 assert!(b2.1 >= 900.0);
1071 let area = Rect::new(0, 0, 40, 10);
1072 let mut buf = Buffer::empty(area);
1073 c.render(area, &mut buf);
1074 assert!(text_of(&buf, 40, 10).contains('┘'));
1075 assert!(LineChart::default().y2_bounds().is_none());
1076 }
1077
1078 #[test]
1079 fn err_band_extend_bounds() {
1080 let c = LineChart::new(vec![Series::new("a")
1081 .values([1.0, 2.0])
1082 .y_err([10.0, 10.0])]);
1083 assert!(c.bounds().1 .1 >= 12.0);
1084 let c = LineChart::new(vec![Series::new("a")
1085 .values([1.0, 2.0])
1086 .band([(-5.0, 1.0), (0.0, 3.0)])]);
1087 assert!(c.bounds().1 .0 <= -5.0);
1088 }
1089
1090 #[test]
1091 fn catmull_densifies() {
1092 let p = catmull_rom(&[(0, 0), (20, 10), (40, 0), (60, 10)]);
1093 assert!(p.len() > 4);
1094 assert_eq!(p[0], (0, 0));
1095 assert_eq!(*p.last().unwrap(), (60, 10));
1096 assert_eq!(catmull_rom(&[(1, 1)]), vec![(1, 1)]);
1097 }
1098
1099 #[test]
1100 fn nearest_finds_point() {
1101 let n = chart().nearest(3.0, 4.0).unwrap();
1102 assert_eq!((n.series, n.index), (1, 1));
1103 assert!(LineChart::default().nearest(0.0, 0.0).is_none());
1104 }
1105
1106 #[test]
1107 fn features_render_safely_everywhere() {
1108 let c = LineChart::new(vec![
1109 Series::new("a")
1110 .values([1.0, 0.0, f64::NAN, 5.0])
1111 .y_err([0.5, f64::NAN, 1.0])
1112 .smooth(true),
1113 Series::new("b")
1114 .values([10.0, 20.0, 5.0])
1115 .band([(1.0, 30.0), (2.0, 40.0), (0.0, 9.0)])
1116 .secondary_axis(true),
1117 ])
1118 .y_log(true)
1119 .annotation(Annotation::hline(2.0).text("lim"))
1120 .annotation(Annotation::x_region(0.5, 1.5))
1121 .crosshair(Some(Crosshair::new(1.0, 2.0)));
1122 for (w, h) in [(0, 0), (1, 1), (5, 3), (12, 6), (60, 20)] {
1123 let area = Rect::new(0, 0, w, h);
1124 let mut buf = Buffer::empty(area);
1125 (&c).render(area, &mut buf);
1126 }
1127 }
1128
1129 #[test]
1130 fn crosshair_draws_tooltip() {
1131 let area = Rect::new(0, 0, 50, 16);
1132 let mut buf = Buffer::empty(area);
1133 chart()
1134 .crosshair(Some(Crosshair::new(1.0, 2.0)))
1135 .render(area, &mut buf);
1136 let t = text_of(&buf, 50, 16);
1137 assert!(t.contains('┼'));
1138 assert!(t.contains("x 1"));
1139 }
1140
1141 #[cfg(feature = "theme")]
1142 #[test]
1143 fn crosshair_uses_theme_colors() {
1144 let th = Theme::dracula();
1145 let area = Rect::new(0, 0, 50, 16);
1146 let mut buf = Buffer::empty(area);
1147 chart()
1148 .theme(&th)
1149 .crosshair(Some(Crosshair::new(1.0, 2.0)))
1150 .render(area, &mut buf);
1151 assert!(buf
1152 .content()
1153 .iter()
1154 .any(|c| c.symbol() == "┼" && c.fg == th.crosshair));
1155 let mut buf = Buffer::empty(area);
1156 let own = Style::default().fg(Color::Red);
1157 chart()
1158 .theme(&th)
1159 .crosshair(Some(Crosshair::new(1.0, 2.0).style(own)))
1160 .render(area, &mut buf);
1161 assert!(buf
1162 .content()
1163 .iter()
1164 .any(|c| c.symbol() == "┼" && c.fg == Color::Red));
1165 }
1166
1167 #[test]
1168 fn decimate_keeps_extremes_and_order() {
1169 let pts = vec![(0, 5), (0, 1), (0, 9), (0, 4), (1, 2), (2, 3)];
1170 let d = decimate(&pts);
1171 assert_eq!(d, vec![(0, 5), (0, 1), (0, 9), (0, 4), (1, 2), (2, 3)]);
1172 let unsorted = vec![(3, 1), (1, 1)];
1173 assert_eq!(decimate(&unsorted), unsorted);
1174 }
1175}