presentar-terminal 0.3.5

Terminal backend for Presentar UI framework with zero-allocation rendering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! `MicroHeatBar` - Tufte-inspired proportional breakdown visualization
//!
//! A showcase widget demonstrating presentar's data science capabilities:
//! - Heatmap color intensity encoding
//! - Proportional area encoding (Tufte data-ink ratio)
//! - Multi-category display in minimal space
//! - Optional trend indicators
//!
//! # Design Principles (Tufte, 1983)
//! 1. **Data-Ink Ratio**: Every pixel conveys information
//! 2. **Layering**: Color intensity + width = two dimensions in one row
//! 3. **Small Multiples**: Consistent encoding across all instances
//!
//! # Example
//! ```
//! use presentar_terminal::{MicroHeatBar, HeatScheme};
//!
//! // CPU breakdown: usr=54%, sys=19%, io=4%, idle=23%
//! let bar = MicroHeatBar::new(&[54.0, 19.0, 4.0, 23.0])
//!     .with_labels(&["U", "S", "I", "Id"])
//!     .with_scheme(HeatScheme::Thermal);
//! ```

use presentar_core::{Canvas, Color, Point, TextStyle};

/// Color scheme for heat intensity encoding
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HeatScheme {
    /// Thermal: green → yellow → orange → red (for CPU/load)
    #[default]
    Thermal,
    /// Cool: light blue → dark blue (for memory)
    Cool,
    /// Warm: yellow → orange → red (for temperature)
    Warm,
    /// Mono: grayscale (for accessibility)
    Mono,
}

impl HeatScheme {
    /// Map a percentage (0-100) to a color
    pub fn color_for_percent(&self, pct: f64) -> Color {
        let p = pct.clamp(0.0, 100.0) / 100.0;

        match self {
            Self::Thermal => {
                // Green → Yellow → Orange → Red
                if p < 0.5 {
                    // Green to Yellow
                    let t = p * 2.0;
                    Color::new(t as f32, 0.8, 0.2, 1.0)
                } else {
                    // Yellow to Red
                    let t = (p - 0.5) * 2.0;
                    Color::new(1.0, (0.8 - t * 0.6) as f32, 0.2, 1.0)
                }
            }
            Self::Cool => {
                // Light blue to dark blue
                Color::new(0.2, 0.4 + (p * 0.4) as f32, 0.9, 1.0)
            }
            Self::Warm => {
                // Yellow to red
                Color::new(1.0, (0.9 - p * 0.7) as f32, 0.1, 1.0)
            }
            Self::Mono => {
                // White to dark gray
                let v = (0.9 - p * 0.7) as f32;
                Color::new(v, v, v, 1.0)
            }
        }
    }
}

/// Style for the micro heat bar rendering
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BarStyle {
    /// Solid blocks: ████▓▓░░
    #[default]
    Blocks,
    /// Gradient shading: uses 8-level Unicode blocks
    Gradient,
    /// Dots/circles: ●●●○○○
    Dots,
    /// Segments with gaps: █ █ █ ░ ░
    Segments,
}

/// A micro heatmap-style proportional bar for category breakdowns
///
/// Renders categories as colored segments where:
/// - Width ∝ percentage (proportional encoding)
/// - Color intensity ∝ "heat" of that category (heatmap encoding)
#[derive(Debug, Clone)]
pub struct MicroHeatBar {
    /// Percentages for each category (should sum to ~100)
    values: Vec<f64>,
    /// Optional short labels for each category
    labels: Vec<String>,
    /// Color scheme
    scheme: HeatScheme,
    /// Rendering style
    style: BarStyle,
    /// Total width in characters
    width: usize,
    /// Show numeric values
    show_values: bool,
}

impl MicroHeatBar {
    /// Create a new MicroHeatBar with the given percentages
    pub fn new(values: &[f64]) -> Self {
        Self {
            values: values.to_vec(),
            labels: Vec::new(),
            scheme: HeatScheme::Thermal,
            style: BarStyle::Blocks,
            width: 20,
            show_values: false,
        }
    }

    /// Set category labels (short, 1-2 chars recommended)
    pub fn with_labels(mut self, labels: &[&str]) -> Self {
        self.labels = labels.iter().map(|s| (*s).to_string()).collect();
        self
    }

    /// Set the color scheme
    pub fn with_scheme(mut self, scheme: HeatScheme) -> Self {
        self.scheme = scheme;
        self
    }

    /// Set the rendering style
    pub fn with_style(mut self, style: BarStyle) -> Self {
        self.style = style;
        self
    }

    /// Set the total width in characters
    pub fn with_width(mut self, width: usize) -> Self {
        self.width = width;
        self
    }

    /// Show numeric values inline
    pub fn with_values(mut self, show: bool) -> Self {
        self.show_values = show;
        self
    }

    /// Render the bar to a string (for simple display)
    pub fn render_string(&self) -> String {
        let total: f64 = self.values.iter().sum();
        if total <= 0.0 || self.width == 0 {
            return "".repeat(self.width);
        }

        let mut result = String::new();
        let mut remaining_width = self.width;

        for &val in self.values.iter() {
            let proportion = val / total;
            let char_count =
                ((proportion * self.width as f64).round() as usize).min(remaining_width);

            if char_count == 0 {
                continue;
            }

            let ch = match self.style {
                BarStyle::Blocks => {
                    if val > 70.0 {
                        ''
                    } else if val > 40.0 {
                        ''
                    } else if val > 20.0 {
                        ''
                    } else if val > 5.0 {
                        ''
                    } else {
                        ' '
                    }
                }
                BarStyle::Gradient => {
                    // 8-level gradient based on value intensity
                    let level = ((val / 100.0) * 7.0).round() as usize;
                    ['', '', '', '', '', '', '', ''][level.min(7)]
                }
                BarStyle::Dots => {
                    if val > 50.0 {
                        ''
                    } else {
                        ''
                    }
                }
                BarStyle::Segments => '',
            };

            for _ in 0..char_count {
                result.push(ch);
            }
            remaining_width = remaining_width.saturating_sub(char_count);
        }

        // Fill remaining with empty
        while result.chars().count() < self.width {
            result.push('');
        }

        result
    }

    /// Paint the bar to a canvas at the given position
    pub fn paint(&self, canvas: &mut dyn Canvas, pos: Point) {
        let total: f64 = self.values.iter().sum();
        if total <= 0.0 || self.width == 0 {
            return;
        }

        let mut x = pos.x;

        for &val in self.values.iter() {
            let proportion = val / total;
            let char_count = (proportion * self.width as f64).round() as usize;

            if char_count == 0 {
                continue;
            }

            // Color intensity based on the value itself (heatmap principle)
            let color = self.scheme.color_for_percent(val);

            let ch = match self.style {
                BarStyle::Blocks => '',
                BarStyle::Gradient => {
                    let level = ((val / 100.0) * 7.0).round() as usize;
                    ['', '', '', '', '', '', '', ''][level.min(7)]
                }
                BarStyle::Dots => '',
                BarStyle::Segments => '',
            };

            let segment: String = std::iter::repeat(ch).take(char_count).collect();
            canvas.draw_text(
                &segment,
                Point::new(x, pos.y),
                &TextStyle {
                    color,
                    ..Default::default()
                },
            );

            x += char_count as f32;
        }

        // Fill remaining width with dim background
        let remaining = self.width.saturating_sub((x - pos.x) as usize);
        if remaining > 0 {
            let bg: String = std::iter::repeat('').take(remaining).collect();
            canvas.draw_text(
                &bg,
                Point::new(x, pos.y),
                &TextStyle {
                    color: Color::new(0.2, 0.2, 0.2, 1.0),
                    ..Default::default()
                },
            );
        }
    }
}

/// Compact breakdown showing label + micro bar + percentage
/// Example: "U:54 S:19 I:4 ████▓▓░░"
pub struct CompactBreakdown {
    /// Category values
    values: Vec<f64>,
    /// Category labels
    labels: Vec<String>,
    /// Color scheme
    scheme: HeatScheme,
}

impl CompactBreakdown {
    pub fn new(labels: &[&str], values: &[f64]) -> Self {
        Self {
            values: values.to_vec(),
            labels: labels.iter().map(|s| (*s).to_string()).collect(),
            scheme: HeatScheme::Thermal,
        }
    }

    pub fn with_scheme(mut self, scheme: HeatScheme) -> Self {
        self.scheme = scheme;
        self
    }

    /// Render as a compact string: "U:54 S:19 I:4 Id:23"
    pub fn render_text(&self, _width: usize) -> String {
        let parts: Vec<String> = self
            .labels
            .iter()
            .zip(self.values.iter())
            .map(|(l, v)| format!("{}:{:.0}", l, v))
            .collect();

        parts.join(" ")
    }

    /// Paint with colors to canvas
    pub fn paint(&self, canvas: &mut dyn Canvas, pos: Point) {
        let mut x = pos.x;

        for (label, &val) in self.labels.iter().zip(self.values.iter()) {
            let color = self.scheme.color_for_percent(val);
            let text = format!("{}:{:.0} ", label, val);

            canvas.draw_text(
                &text,
                Point::new(x, pos.y),
                &TextStyle {
                    color,
                    ..Default::default()
                },
            );

            x += text.chars().count() as f32;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::direct::{CellBuffer, DirectTerminalCanvas};

    // =========================================================================
    // HEAT SCHEME TESTS
    // =========================================================================

    #[test]
    fn test_heat_scheme_default() {
        assert_eq!(HeatScheme::default(), HeatScheme::Thermal);
    }

    #[test]
    fn test_heat_scheme_thermal() {
        let scheme = HeatScheme::Thermal;

        let low = scheme.color_for_percent(10.0);
        let high = scheme.color_for_percent(90.0);

        // Low should be more green, high should be more red
        assert!(low.g > low.r);
        assert!(high.r > high.g);
    }

    #[test]
    fn test_heat_scheme_thermal_midpoint() {
        let scheme = HeatScheme::Thermal;
        let mid = scheme.color_for_percent(50.0);
        // At 50%, should be transitioning (yellow-ish)
        assert!(mid.r > 0.5);
        assert!(mid.g > 0.5);
    }

    #[test]
    fn test_heat_scheme_cool() {
        let scheme = HeatScheme::Cool;
        let low = scheme.color_for_percent(10.0);
        let high = scheme.color_for_percent(90.0);

        // Cool scheme should be blue-ish
        assert!(low.b > low.r);
        assert!(high.b > high.r);
        // Higher values should have more green component
        assert!(high.g > low.g);
    }

    #[test]
    fn test_heat_scheme_warm() {
        let scheme = HeatScheme::Warm;
        let low = scheme.color_for_percent(10.0);
        let high = scheme.color_for_percent(90.0);

        // Low should be yellow-ish (high green), high should be red
        assert!(low.g > high.g);
        assert_eq!(low.r, 1.0);
        assert_eq!(high.r, 1.0);
    }

    #[test]
    fn test_heat_scheme_mono() {
        let scheme = HeatScheme::Mono;
        let low = scheme.color_for_percent(10.0);
        let high = scheme.color_for_percent(90.0);

        // Mono should have equal RGB components (grayscale)
        assert_eq!(low.r, low.g);
        assert_eq!(low.g, low.b);
        assert_eq!(high.r, high.g);
        assert_eq!(high.g, high.b);

        // Lower values should be brighter (closer to white)
        assert!(low.r > high.r);
    }

    #[test]
    fn test_heat_scheme_clamps_values() {
        let scheme = HeatScheme::Thermal;

        // Values outside 0-100 should be clamped
        let neg = scheme.color_for_percent(-50.0);
        let over = scheme.color_for_percent(150.0);

        // Same as 0% and 100%
        let zero = scheme.color_for_percent(0.0);
        let hundred = scheme.color_for_percent(100.0);

        assert_eq!(neg.r, zero.r);
        assert_eq!(over.r, hundred.r);
    }

    // =========================================================================
    // BAR STYLE TESTS
    // =========================================================================

    #[test]
    fn test_bar_style_default() {
        assert_eq!(BarStyle::default(), BarStyle::Blocks);
    }

    // =========================================================================
    // MICRO HEAT BAR TESTS
    // =========================================================================

    #[test]
    fn test_micro_heat_bar_new() {
        let bar = MicroHeatBar::new(&[50.0, 30.0, 20.0]);
        assert_eq!(bar.values.len(), 3);
        assert_eq!(bar.width, 20);
        assert!(!bar.show_values);
    }

    #[test]
    fn test_micro_heat_bar_with_labels() {
        let bar = MicroHeatBar::new(&[50.0, 50.0]).with_labels(&["A", "B"]);
        assert_eq!(bar.labels.len(), 2);
        assert_eq!(bar.labels[0], "A");
    }

    #[test]
    fn test_micro_heat_bar_with_scheme() {
        let bar = MicroHeatBar::new(&[50.0]).with_scheme(HeatScheme::Cool);
        assert_eq!(bar.scheme, HeatScheme::Cool);
    }

    #[test]
    fn test_micro_heat_bar_with_style() {
        let bar = MicroHeatBar::new(&[50.0]).with_style(BarStyle::Gradient);
        assert_eq!(bar.style, BarStyle::Gradient);
    }

    #[test]
    fn test_micro_heat_bar_with_width() {
        let bar = MicroHeatBar::new(&[50.0]).with_width(40);
        assert_eq!(bar.width, 40);
    }

    #[test]
    fn test_micro_heat_bar_with_values() {
        let bar = MicroHeatBar::new(&[50.0]).with_values(true);
        assert!(bar.show_values);
    }

    #[test]
    fn test_micro_heat_bar_render() {
        let bar = MicroHeatBar::new(&[54.0, 19.0, 4.0, 23.0]).with_width(20);

        let rendered = bar.render_string();
        assert_eq!(rendered.chars().count(), 20);
    }

    #[test]
    fn test_micro_heat_bar_render_empty() {
        let bar = MicroHeatBar::new(&[]).with_width(10);
        let rendered = bar.render_string();
        assert_eq!(rendered, "░░░░░░░░░░");
    }

    #[test]
    fn test_micro_heat_bar_render_zero_width() {
        let bar = MicroHeatBar::new(&[50.0]).with_width(0);
        let rendered = bar.render_string();
        assert_eq!(rendered, "");
    }

    #[test]
    fn test_micro_heat_bar_render_all_zeros() {
        let bar = MicroHeatBar::new(&[0.0, 0.0, 0.0]).with_width(10);
        let rendered = bar.render_string();
        assert_eq!(rendered, "░░░░░░░░░░");
    }

    #[test]
    fn test_micro_heat_bar_render_blocks_style() {
        let bar = MicroHeatBar::new(&[80.0, 50.0, 30.0, 10.0, 2.0])
            .with_style(BarStyle::Blocks)
            .with_width(10);
        let rendered = bar.render_string();
        // High values should use denser blocks
        assert!(rendered.contains('') || rendered.contains('') || rendered.contains(''));
    }

    #[test]
    fn test_micro_heat_bar_render_gradient_style() {
        let bar = MicroHeatBar::new(&[50.0, 50.0])
            .with_style(BarStyle::Gradient)
            .with_width(10);
        let rendered = bar.render_string();
        // Gradient uses different block heights
        assert!(rendered
            .chars()
            .any(|c| matches!(c, '' | '' | '' | '' | '' | '' | '' | '')));
    }

    #[test]
    fn test_micro_heat_bar_render_dots_style() {
        let bar = MicroHeatBar::new(&[60.0, 40.0])
            .with_style(BarStyle::Dots)
            .with_width(10);
        let rendered = bar.render_string();
        // Dots style uses filled or empty circles
        assert!(rendered.contains('') || rendered.contains(''));
    }

    #[test]
    fn test_micro_heat_bar_render_segments_style() {
        let bar = MicroHeatBar::new(&[50.0, 50.0])
            .with_style(BarStyle::Segments)
            .with_width(10);
        let rendered = bar.render_string();
        assert!(rendered.contains(''));
    }

    #[test]
    fn test_micro_heat_bar_paint() {
        let mut buffer = CellBuffer::new(30, 5);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);

        let bar = MicroHeatBar::new(&[54.0, 19.0, 4.0, 23.0]).with_width(20);
        bar.paint(&mut canvas, Point::new(0.0, 0.0));
    }

    #[test]
    fn test_micro_heat_bar_paint_empty() {
        let mut buffer = CellBuffer::new(30, 5);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);

        let bar = MicroHeatBar::new(&[]).with_width(10);
        bar.paint(&mut canvas, Point::new(0.0, 0.0));
        // Should return early without error
    }

    #[test]
    fn test_micro_heat_bar_paint_gradient() {
        let mut buffer = CellBuffer::new(30, 5);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);

        let bar = MicroHeatBar::new(&[50.0, 50.0])
            .with_style(BarStyle::Gradient)
            .with_width(20);
        bar.paint(&mut canvas, Point::new(0.0, 0.0));
    }

    #[test]
    fn test_micro_heat_bar_paint_dots() {
        let mut buffer = CellBuffer::new(30, 5);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);

        let bar = MicroHeatBar::new(&[60.0, 40.0])
            .with_style(BarStyle::Dots)
            .with_width(20);
        bar.paint(&mut canvas, Point::new(0.0, 0.0));
    }

    #[test]
    fn test_micro_heat_bar_paint_with_remaining() {
        let mut buffer = CellBuffer::new(50, 5);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);

        // Small values that won't fill the whole width
        let bar = MicroHeatBar::new(&[10.0]).with_width(30);
        bar.paint(&mut canvas, Point::new(0.0, 0.0));
        // Should fill remaining with dim background
    }

    // =========================================================================
    // COMPACT BREAKDOWN TESTS
    // =========================================================================

    #[test]
    fn test_compact_breakdown_new() {
        let breakdown = CompactBreakdown::new(&["U", "S", "I"], &[50.0, 30.0, 20.0]);
        assert_eq!(breakdown.labels.len(), 3);
        assert_eq!(breakdown.values.len(), 3);
    }

    #[test]
    fn test_compact_breakdown_with_scheme() {
        let breakdown = CompactBreakdown::new(&["A"], &[50.0]).with_scheme(HeatScheme::Cool);
        assert_eq!(breakdown.scheme, HeatScheme::Cool);
    }

    #[test]
    fn test_compact_breakdown_render_text() {
        let breakdown = CompactBreakdown::new(&["U", "S", "I", "Id"], &[54.0, 19.0, 4.0, 23.0]);

        let text = breakdown.render_text(40);
        assert!(text.contains("U:54"));
        assert!(text.contains("S:19"));
        assert!(text.contains("I:4"));
        assert!(text.contains("Id:23"));
    }

    #[test]
    fn test_compact_breakdown_paint() {
        let mut buffer = CellBuffer::new(50, 5);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);

        let breakdown = CompactBreakdown::new(&["U", "S"], &[60.0, 40.0]);
        breakdown.paint(&mut canvas, Point::new(0.0, 0.0));
    }

    #[test]
    fn test_compact_breakdown_paint_with_scheme() {
        let mut buffer = CellBuffer::new(50, 5);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);

        let breakdown =
            CompactBreakdown::new(&["A", "B"], &[80.0, 20.0]).with_scheme(HeatScheme::Warm);
        breakdown.paint(&mut canvas, Point::new(0.0, 0.0));
    }
}