blaeck 0.4.0

A component-based terminal UI framework for Rust
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Diff component - Git-style diff display.
//!
//! The Diff component displays file changes in unified diff format,
//! with support for line numbers, colors, and chunk headers.
//!
//! ## When to use Diff
//!
//! - Showing code changes before committing
//! - Comparing file versions
//! - Displaying patch content
//!
//! ## See also
//!
//! - [`SyntaxHighlight`](super::SyntaxHighlight) — Code without diff markers
//! - [`Markdown`](super::Markdown) — Formatted text display

use crate::element::{Component, Element};
use crate::style::{Color, Modifier, Style};

/// Type of a diff line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLineType {
    /// Added line (+)
    Added,
    /// Removed line (-)
    Removed,
    /// Context/unchanged line
    Context,
    /// Chunk header (@@ ... @@)
    Header,
}

/// A single line in a diff.
#[derive(Debug, Clone)]
pub struct DiffLine {
    /// The line content.
    pub content: String,
    /// Type of change.
    pub line_type: DiffLineType,
    /// Old line number (for removed/context lines).
    pub old_line: Option<usize>,
    /// New line number (for added/context lines).
    pub new_line: Option<usize>,
}

impl DiffLine {
    /// Create a new diff line.
    pub fn new(content: impl Into<String>, line_type: DiffLineType) -> Self {
        Self {
            content: content.into(),
            line_type,
            old_line: None,
            new_line: None,
        }
    }

    /// Create an added line.
    pub fn added(content: impl Into<String>) -> Self {
        Self::new(content, DiffLineType::Added)
    }

    /// Create a removed line.
    pub fn removed(content: impl Into<String>) -> Self {
        Self::new(content, DiffLineType::Removed)
    }

    /// Create a context line.
    pub fn context(content: impl Into<String>) -> Self {
        Self::new(content, DiffLineType::Context)
    }

    /// Create a chunk header.
    pub fn header(content: impl Into<String>) -> Self {
        Self::new(content, DiffLineType::Header)
    }

    /// Set the old line number.
    #[must_use]
    pub fn old_num(mut self, num: usize) -> Self {
        self.old_line = Some(num);
        self
    }

    /// Set the new line number.
    #[must_use]
    pub fn new_num(mut self, num: usize) -> Self {
        self.new_line = Some(num);
        self
    }

    /// Set both line numbers.
    #[must_use]
    pub fn line_nums(mut self, old: usize, new: usize) -> Self {
        self.old_line = Some(old);
        self.new_line = Some(new);
        self
    }

    /// Get the prefix character for this line type.
    pub fn prefix(&self) -> &str {
        match self.line_type {
            DiffLineType::Added => "+",
            DiffLineType::Removed => "-",
            DiffLineType::Context => " ",
            DiffLineType::Header => "",
        }
    }
}

/// Display style for diffs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DiffStyle {
    /// Unified diff format (default)
    #[default]
    Unified,
    /// Minimal - just +/- with colors, no line numbers
    Minimal,
    /// With line numbers
    LineNumbers,
}

/// Properties for the Diff component.
#[derive(Debug, Clone)]
pub struct DiffProps {
    /// The diff lines to display.
    pub lines: Vec<DiffLine>,
    /// Display style.
    pub style: DiffStyle,
    /// Color for added lines.
    pub added_color: Color,
    /// Color for removed lines.
    pub removed_color: Color,
    /// Color for context lines.
    pub context_color: Color,
    /// Color for chunk headers.
    pub header_color: Color,
    /// Color for line numbers.
    pub line_num_color: Color,
    /// Background color for all lines.
    pub bg_color: Option<Color>,
    /// Whether to show +/- prefixes.
    pub show_prefix: bool,
    /// Whether to dim context lines.
    pub dim_context: bool,
    /// Width for line number column (0 to auto-calculate).
    pub line_num_width: usize,
}

impl Default for DiffProps {
    fn default() -> Self {
        Self {
            lines: Vec::new(),
            style: DiffStyle::Unified,
            added_color: Color::Green,
            removed_color: Color::Red,
            context_color: Color::Reset,
            header_color: Color::Cyan,
            line_num_color: Color::DarkGray,
            bg_color: None,
            show_prefix: true,
            dim_context: true,
            line_num_width: 0,
        }
    }
}

impl DiffProps {
    /// Create new DiffProps.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create from a list of diff lines.
    pub fn with_lines(lines: Vec<DiffLine>) -> Self {
        Self {
            lines,
            ..Default::default()
        }
    }

    /// Parse a unified diff string.
    ///
    /// Recognizes lines starting with:
    /// - `+` as added
    /// - `-` as removed
    /// - `@@` as chunk headers
    /// - Everything else as context
    pub fn from_unified(diff_text: &str) -> Self {
        let mut lines = Vec::new();
        let mut old_line = 1usize;
        let mut new_line = 1usize;

        for line in diff_text.lines() {
            if line.starts_with("@@") {
                // Parse chunk header: @@ -start,count +start,count @@
                lines.push(DiffLine::header(line));
                // Try to parse line numbers from header
                if let Some((old_start, new_start)) = parse_chunk_header(line) {
                    old_line = old_start;
                    new_line = new_start;
                }
            } else if line.starts_with('+') && !line.starts_with("+++") {
                let content = if line.len() > 1 { &line[1..] } else { "" };
                lines.push(DiffLine::added(content).new_num(new_line));
                new_line += 1;
            } else if line.starts_with('-') && !line.starts_with("---") {
                let content = if line.len() > 1 { &line[1..] } else { "" };
                lines.push(DiffLine::removed(content).old_num(old_line));
                old_line += 1;
            } else if line.starts_with("---") || line.starts_with("+++") {
                // File headers - treat as headers
                lines.push(DiffLine::header(line));
            } else {
                // Context line (may start with space)
                let content = if line.starts_with(' ') && line.len() > 1 {
                    &line[1..]
                } else {
                    line
                };
                lines.push(DiffLine::context(content).line_nums(old_line, new_line));
                old_line += 1;
                new_line += 1;
            }
        }

        Self::with_lines(lines)
    }

    /// Add an added line.
    #[must_use]
    pub fn added(mut self, content: impl Into<String>) -> Self {
        self.lines.push(DiffLine::added(content));
        self
    }

    /// Add a removed line.
    #[must_use]
    pub fn removed(mut self, content: impl Into<String>) -> Self {
        self.lines.push(DiffLine::removed(content));
        self
    }

    /// Add a context line.
    #[must_use]
    pub fn context(mut self, content: impl Into<String>) -> Self {
        self.lines.push(DiffLine::context(content));
        self
    }

    /// Add a chunk header.
    #[must_use]
    pub fn header(mut self, content: impl Into<String>) -> Self {
        self.lines.push(DiffLine::header(content));
        self
    }

    /// Add a diff line.
    #[must_use]
    pub fn line(mut self, line: DiffLine) -> Self {
        self.lines.push(line);
        self
    }

    /// Set the display style.
    #[must_use]
    pub fn style(mut self, style: DiffStyle) -> Self {
        self.style = style;
        self
    }

    /// Set the color for added lines.
    #[must_use]
    pub fn added_color(mut self, color: Color) -> Self {
        self.added_color = color;
        self
    }

    /// Set the color for removed lines.
    #[must_use]
    pub fn removed_color(mut self, color: Color) -> Self {
        self.removed_color = color;
        self
    }

    /// Set the color for context lines.
    #[must_use]
    pub fn context_color(mut self, color: Color) -> Self {
        self.context_color = color;
        self
    }

    /// Set the color for headers.
    #[must_use]
    pub fn header_color(mut self, color: Color) -> Self {
        self.header_color = color;
        self
    }

    /// Set the background color for all lines.
    #[must_use]
    pub fn bg_color(mut self, color: Color) -> Self {
        self.bg_color = Some(color);
        self
    }

    /// Enable/disable +/- prefixes.
    #[must_use]
    pub fn show_prefix(mut self, show: bool) -> Self {
        self.show_prefix = show;
        self
    }

    /// Enable/disable dimming context lines.
    #[must_use]
    pub fn dim_context(mut self, dim: bool) -> Self {
        self.dim_context = dim;
        self
    }

    /// Calculate the width needed for line numbers.
    fn calc_line_num_width(&self) -> usize {
        if self.line_num_width > 0 {
            return self.line_num_width;
        }

        let max_line = self
            .lines
            .iter()
            .filter_map(|l| l.old_line.max(l.new_line))
            .max()
            .unwrap_or(0);

        if max_line == 0 {
            0
        } else {
            max_line.to_string().len()
        }
    }

    /// Render a single line to a string.
    fn render_line(&self, line: &DiffLine, line_width: usize) -> String {
        let prefix = if self.show_prefix { line.prefix() } else { "" };

        match self.style {
            DiffStyle::Minimal => {
                format!("{}{}", prefix, line.content)
            }
            DiffStyle::Unified => {
                format!("{}{}", prefix, line.content)
            }
            DiffStyle::LineNumbers => {
                let old_num = line
                    .old_line
                    .map(|n| format!("{:>width$}", n, width = line_width))
                    .unwrap_or_else(|| " ".repeat(line_width));
                let new_num = line
                    .new_line
                    .map(|n| format!("{:>width$}", n, width = line_width))
                    .unwrap_or_else(|| " ".repeat(line_width));

                if line.line_type == DiffLineType::Header {
                    line.content.clone()
                } else {
                    format!("{} {} {}{}", old_num, new_num, prefix, line.content)
                }
            }
        }
    }

    /// Render the diff as lines (for plain text output).
    pub fn render_lines(&self) -> Vec<String> {
        let line_width = self.calc_line_num_width();
        self.lines
            .iter()
            .map(|line| self.render_line(line, line_width))
            .collect()
    }

    /// Render the diff as a single string.
    pub fn render_string(&self) -> String {
        self.render_lines().join("\n")
    }
}

/// Parse chunk header to extract line numbers.
/// Format: @@ -old_start,old_count +new_start,new_count @@
fn parse_chunk_header(header: &str) -> Option<(usize, usize)> {
    // Simple parsing - look for -N and +N patterns
    let mut old_start = None;
    let mut new_start = None;

    for part in header.split_whitespace() {
        if part.starts_with('-') && part.len() > 1 {
            if let Some(num_str) = part[1..].split(',').next() {
                old_start = num_str.parse().ok();
            }
        } else if part.starts_with('+') && part.len() > 1 {
            if let Some(num_str) = part[1..].split(',').next() {
                new_start = num_str.parse().ok();
            }
        }
    }

    match (old_start, new_start) {
        (Some(o), Some(n)) => Some((o, n)),
        _ => None,
    }
}

/// A component that displays a diff.
///
/// # Examples
///
/// ```ignore
/// // Simple diff
/// Element::node::<Diff>(
///     DiffProps::new()
///         .removed("old line")
///         .added("new line")
///         .context("unchanged"),
///     vec![]
/// )
///
/// // From unified diff string
/// Element::node::<Diff>(
///     DiffProps::from_unified("+added\n-removed\n context"),
///     vec![]
/// )
/// ```
pub struct Diff;

impl Component for Diff {
    type Props = DiffProps;

    fn render(props: &Self::Props) -> Element {
        if props.lines.is_empty() {
            return Element::text("");
        }

        // Build a Fragment with each line as a styled Text element
        let line_width = props.calc_line_num_width();
        let mut elements = Vec::new();

        for line in props.lines.iter() {
            let rendered = props.render_line(line, line_width);

            let mut style = Style::new();
            match line.line_type {
                DiffLineType::Added => {
                    style = style.fg(props.added_color);
                }
                DiffLineType::Removed => {
                    style = style.fg(props.removed_color);
                }
                DiffLineType::Context => {
                    style = style.fg(props.context_color);
                    if props.dim_context {
                        style = style.add_modifier(Modifier::DIM);
                    }
                }
                DiffLineType::Header => {
                    style = style.fg(props.header_color).add_modifier(Modifier::BOLD);
                }
            }

            if let Some(bg) = props.bg_color {
                style = style.bg(bg);
            }

            elements.push(Element::Text {
                content: rendered,
                style,
            });
        }

        Element::Fragment(elements)
    }
}

/// Helper to create a simple diff from old/new content.
pub fn diff_lines(old: &[&str], new: &[&str]) -> DiffProps {
    let mut props = DiffProps::new();

    // Simple diff: show all old as removed, all new as added
    // (A real diff algorithm would be more sophisticated)
    for line in old {
        props = props.removed(*line);
    }
    for line in new {
        props = props.added(*line);
    }

    props
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_diff_line_new() {
        let line = DiffLine::new("test", DiffLineType::Added);
        assert_eq!(line.content, "test");
        assert_eq!(line.line_type, DiffLineType::Added);
    }

    #[test]
    fn test_diff_line_helpers() {
        let added = DiffLine::added("new");
        assert_eq!(added.line_type, DiffLineType::Added);
        assert_eq!(added.prefix(), "+");

        let removed = DiffLine::removed("old");
        assert_eq!(removed.line_type, DiffLineType::Removed);
        assert_eq!(removed.prefix(), "-");

        let context = DiffLine::context("same");
        assert_eq!(context.line_type, DiffLineType::Context);
        assert_eq!(context.prefix(), " ");
    }

    #[test]
    fn test_diff_line_with_nums() {
        let line = DiffLine::added("new").new_num(42);
        assert_eq!(line.new_line, Some(42));
        assert!(line.old_line.is_none());

        let line2 = DiffLine::context("same").line_nums(10, 12);
        assert_eq!(line2.old_line, Some(10));
        assert_eq!(line2.new_line, Some(12));
    }

    #[test]
    fn test_diff_props_new() {
        let props = DiffProps::new();
        assert!(props.lines.is_empty());
        assert_eq!(props.added_color, Color::Green);
        assert_eq!(props.removed_color, Color::Red);
    }

    #[test]
    fn test_diff_props_builder() {
        let props = DiffProps::new().removed("old").added("new").context("same");

        assert_eq!(props.lines.len(), 3);
        assert_eq!(props.lines[0].line_type, DiffLineType::Removed);
        assert_eq!(props.lines[1].line_type, DiffLineType::Added);
        assert_eq!(props.lines[2].line_type, DiffLineType::Context);
    }

    #[test]
    fn test_diff_props_from_unified() {
        let diff_text = "+added line\n-removed line\n context line";
        let props = DiffProps::from_unified(diff_text);

        assert_eq!(props.lines.len(), 3);
        assert_eq!(props.lines[0].line_type, DiffLineType::Added);
        assert_eq!(props.lines[0].content, "added line");
        assert_eq!(props.lines[1].line_type, DiffLineType::Removed);
        assert_eq!(props.lines[1].content, "removed line");
        assert_eq!(props.lines[2].line_type, DiffLineType::Context);
    }

    #[test]
    fn test_diff_props_from_unified_with_header() {
        let diff_text = "@@ -1,3 +1,4 @@\n context\n-removed\n+added";
        let props = DiffProps::from_unified(diff_text);

        assert_eq!(props.lines.len(), 4);
        assert_eq!(props.lines[0].line_type, DiffLineType::Header);
    }

    #[test]
    fn test_parse_chunk_header() {
        let result = parse_chunk_header("@@ -10,5 +12,7 @@");
        assert_eq!(result, Some((10, 12)));

        let result2 = parse_chunk_header("@@ -1 +1 @@");
        assert_eq!(result2, Some((1, 1)));
    }

    #[test]
    fn test_diff_render_string() {
        let props = DiffProps::new()
            .removed("old")
            .added("new")
            .style(DiffStyle::Minimal);

        let result = props.render_string();
        assert!(result.contains("-old"));
        assert!(result.contains("+new"));
    }

    #[test]
    fn test_diff_render_no_prefix() {
        let props = DiffProps::new()
            .removed("old")
            .added("new")
            .show_prefix(false);

        let result = props.render_string();
        assert!(!result.contains("-old"));
        assert!(!result.contains("+new"));
        assert!(result.contains("old"));
        assert!(result.contains("new"));
    }

    #[test]
    fn test_diff_component_render() {
        let props = DiffProps::new().added("test");
        let elem = Diff::render(&props);
        assert!(elem.is_fragment());
    }

    #[test]
    fn test_diff_component_render_empty() {
        let props = DiffProps::new();
        let elem = Diff::render(&props);
        assert!(elem.is_text());
    }

    #[test]
    fn test_diff_lines_helper() {
        let props = diff_lines(&["old1", "old2"], &["new1"]);
        assert_eq!(props.lines.len(), 3);
        assert_eq!(props.lines[0].line_type, DiffLineType::Removed);
        assert_eq!(props.lines[1].line_type, DiffLineType::Removed);
        assert_eq!(props.lines[2].line_type, DiffLineType::Added);
    }

    #[test]
    fn test_diff_line_numbers_style() {
        let props = DiffProps::new()
            .line(DiffLine::removed("old").old_num(10))
            .line(DiffLine::added("new").new_num(10))
            .style(DiffStyle::LineNumbers);

        let result = props.render_string();
        assert!(result.contains("10"));
    }

    #[test]
    fn test_diff_component_render_has_styles() {
        let props = DiffProps::new().removed("old line").added("new line");
        let elem = Diff::render(&props);

        if let crate::Element::Fragment(children) = elem {
            assert_eq!(children.len(), 2);
            // First child (removed) should have red color
            if let crate::Element::Text { style, .. } = &children[0] {
                assert_eq!(style.fg, Color::Red);
            } else {
                panic!("Expected Text element");
            }
            // Second child (added) should have green color
            if let crate::Element::Text { style, .. } = &children[1] {
                assert_eq!(style.fg, Color::Green);
            } else {
                panic!("Expected Text element");
            }
        } else {
            panic!("Expected Fragment element");
        }
    }
}