cctakt 0.1.1

TUI orchestrator for multiple Claude Code agents using Git Worktree
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
//! Diff viewer module for cctakt
//!
//! Provides a scrollable diff viewer widget for reviewing changes
//! before merging branches.

use crate::theme::theme;
use ratatui::{
    layout::{Alignment, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
    Frame,
};

/// A scrollable diff viewer widget
///
/// # Example
/// ```ignore
/// let diff_content = merger.diff("feat/auth")?;
/// let mut diffview = DiffView::new(diff_content);
///
/// // Handle scroll
/// diffview.scroll_down(5);
///
/// // Render
/// diffview.render(f, area);
/// ```
pub struct DiffView {
    /// The raw diff content
    diff_content: String,
    /// Parsed and styled lines
    lines: Vec<DiffLine>,
    /// Current scroll position
    scroll: u16,
    /// Whether syntax highlighting is enabled
    syntax_highlight: bool,
    /// Title for the diff view (e.g., "feat/auth -> main")
    title: Option<String>,
}

/// A parsed diff line with its type
#[derive(Debug, Clone)]
struct DiffLine {
    content: String,
    line_type: DiffLineType,
}

/// Type of diff line for styling
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DiffLineType {
    /// Regular context line
    Context,
    /// Added line (+)
    Addition,
    /// Removed line (-)
    Deletion,
    /// Hunk header (@@)
    HunkHeader,
    /// File header (diff --git, ---, +++)
    FileHeader,
    /// Empty line
    Empty,
}

impl DiffLineType {
    /// Get the foreground color for this line type
    fn color(&self) -> Color {
        let t = theme();
        match self {
            DiffLineType::Context => t.diff_context(),
            DiffLineType::Addition => t.diff_addition(),
            DiffLineType::Deletion => t.diff_deletion(),
            DiffLineType::HunkHeader => t.diff_hunk_header(),
            DiffLineType::FileHeader => t.diff_file_header(),
            DiffLineType::Empty => t.text_primary(),
        }
    }

    /// Get the background color for this line type (if any)
    fn bg_color(&self) -> Option<Color> {
        let t = theme();
        match self {
            DiffLineType::Addition => Some(t.diff_add_bg()),
            DiffLineType::Deletion => Some(t.diff_del_bg()),
            _ => None,
        }
    }
}

impl DiffView {
    /// Create a new diff view with the given content
    pub fn new(diff: String) -> Self {
        let lines = parse_diff(&diff);
        Self {
            diff_content: diff,
            lines,
            scroll: 0,
            syntax_highlight: true,
            title: None,
        }
    }

    /// Set the title for the diff view
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Enable or disable syntax highlighting
    pub fn set_syntax_highlight(&mut self, enabled: bool) {
        self.syntax_highlight = enabled;
    }

    /// Get the current scroll position
    pub fn scroll_position(&self) -> u16 {
        self.scroll
    }

    /// Get the total number of lines
    pub fn line_count(&self) -> usize {
        self.lines.len()
    }

    /// Scroll up by the specified number of lines
    pub fn scroll_up(&mut self, lines: u16) {
        self.scroll = self.scroll.saturating_sub(lines);
    }

    /// Scroll down by the specified number of lines
    pub fn scroll_down(&mut self, lines: u16) {
        let max_scroll = self.lines.len().saturating_sub(1) as u16;
        self.scroll = (self.scroll + lines).min(max_scroll);
    }

    /// Scroll to the top
    pub fn scroll_to_top(&mut self) {
        self.scroll = 0;
    }

    /// Scroll to the bottom
    pub fn scroll_to_bottom(&mut self) {
        self.scroll = self.lines.len().saturating_sub(1) as u16;
    }

    /// Page up (scroll by viewport height)
    pub fn page_up(&mut self, viewport_height: u16) {
        self.scroll_up(viewport_height.saturating_sub(2));
    }

    /// Page down (scroll by viewport height)
    pub fn page_down(&mut self, viewport_height: u16) {
        self.scroll_down(viewport_height.saturating_sub(2));
    }

    /// Get the raw diff content
    pub fn content(&self) -> &str {
        &self.diff_content
    }

    /// Check if the diff is empty
    pub fn is_empty(&self) -> bool {
        self.diff_content.is_empty()
    }

    /// Render the diff view
    pub fn render(&self, f: &mut Frame, area: Rect) {
        let t = theme();

        // Calculate content area (excluding borders)
        let content_height = area.height.saturating_sub(4) as usize; // borders + help line

        // Build the block
        let title = self.title.clone().unwrap_or_else(|| "Diff".to_string());
        let block = Block::default()
            .title(format!(" {title} "))
            .borders(Borders::ALL)
            .border_style(Style::default().fg(t.border_primary()));

        // Build styled lines
        let visible_lines: Vec<Line> = self
            .lines
            .iter()
            .skip(self.scroll as usize)
            .take(content_height)
            .map(|line| {
                if self.syntax_highlight {
                    style_diff_line(line)
                } else {
                    Line::from(line.content.clone())
                }
            })
            .collect();

        // Add empty lines if needed
        let all_lines = visible_lines;

        // Add help line at the bottom
        let help_line = Line::from(vec![
            Span::styled(
                "[",
                Style::default().fg(t.text_muted()),
            ),
            Span::styled(
                "\u{2191}/\u{2193}",
                Style::default().fg(t.key_binding()),
            ),
            Span::styled(
                "] Scroll  ",
                Style::default().fg(t.text_muted()),
            ),
            Span::styled(
                "[Enter]",
                t.style_success(),
            ),
            Span::styled(
                " Merge  ",
                Style::default().fg(t.text_muted()),
            ),
            Span::styled(
                "[Esc]",
                t.style_error(),
            ),
            Span::styled(
                " Cancel",
                Style::default().fg(t.text_muted()),
            ),
        ]);

        // Render main content
        let diff_widget = Paragraph::new(all_lines)
            .block(block)
            .alignment(Alignment::Left);

        f.render_widget(diff_widget, area);

        // Render help line at the bottom inside the border
        let help_area = Rect::new(
            area.x + 2,
            area.y + area.height.saturating_sub(2),
            area.width.saturating_sub(4),
            1,
        );
        let help_widget = Paragraph::new(help_line).alignment(Alignment::Center);
        f.render_widget(help_widget, help_area);

        // Render scrollbar if needed
        if self.lines.len() > content_height {
            let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(Some("\u{25b2}")) // â–²
                .end_symbol(Some("\u{25bc}"));   // â–¼

            let mut scrollbar_state = ScrollbarState::new(self.lines.len())
                .position(self.scroll as usize);

            let scrollbar_area = Rect::new(
                area.x + area.width.saturating_sub(1),
                area.y + 1,
                1,
                area.height.saturating_sub(3),
            );

            f.render_stateful_widget(scrollbar, scrollbar_area, &mut scrollbar_state);
        }
    }

    /// Render with a custom block (for embedding in other widgets)
    pub fn render_with_block(&self, f: &mut Frame, area: Rect, block: Block) {
        let inner = block.inner(area);
        f.render_widget(block, area);

        let content_height = inner.height as usize;

        let visible_lines: Vec<Line> = self
            .lines
            .iter()
            .skip(self.scroll as usize)
            .take(content_height)
            .map(|line| {
                if self.syntax_highlight {
                    style_diff_line(line)
                } else {
                    Line::from(line.content.clone())
                }
            })
            .collect();

        let diff_widget = Paragraph::new(visible_lines);
        f.render_widget(diff_widget, inner);
    }
}

/// Parse diff content into typed lines
fn parse_diff(diff: &str) -> Vec<DiffLine> {
    diff.lines()
        .map(|line| {
            let line_type = classify_diff_line(line);
            DiffLine {
                content: line.to_string(),
                line_type,
            }
        })
        .collect()
}

/// Classify a diff line by its prefix
fn classify_diff_line(line: &str) -> DiffLineType {
    if line.is_empty() {
        DiffLineType::Empty
    } else if line.starts_with("diff --git")
        || line.starts_with("index ")
        || line.starts_with("---")
        || line.starts_with("+++")
    {
        DiffLineType::FileHeader
    } else if line.starts_with("@@") {
        DiffLineType::HunkHeader
    } else if line.starts_with('+') {
        DiffLineType::Addition
    } else if line.starts_with('-') {
        DiffLineType::Deletion
    } else {
        DiffLineType::Context
    }
}

/// Style a diff line based on its type
fn style_diff_line(line: &DiffLine) -> Line<'static> {
    let mut style = Style::default().fg(line.line_type.color());

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

    // Add bold for headers
    if matches!(
        line.line_type,
        DiffLineType::FileHeader | DiffLineType::HunkHeader
    ) {
        style = style.add_modifier(Modifier::BOLD);
    }

    Line::from(Span::styled(line.content.clone(), style))
}

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

    #[test]
    fn test_diffview_new() {
        let diff = "+ added line\n- removed line\n context".to_string();
        let view = DiffView::new(diff.clone());
        assert_eq!(view.content(), diff);
        assert_eq!(view.line_count(), 3);
        assert_eq!(view.scroll_position(), 0);
    }

    #[test]
    fn test_diffview_with_title() {
        let view = DiffView::new("".to_string()).with_title("feat/auth -> main");
        assert_eq!(view.title, Some("feat/auth -> main".to_string()));
    }

    #[test]
    fn test_diffview_scroll_down() {
        let diff = (0..100).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
        let mut view = DiffView::new(diff);

        assert_eq!(view.scroll_position(), 0);

        view.scroll_down(10);
        assert_eq!(view.scroll_position(), 10);

        view.scroll_down(1000);
        assert_eq!(view.scroll_position(), 99); // max is line_count - 1
    }

    #[test]
    fn test_diffview_scroll_up() {
        let diff = (0..100).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
        let mut view = DiffView::new(diff);

        view.scroll_down(50);
        assert_eq!(view.scroll_position(), 50);

        view.scroll_up(20);
        assert_eq!(view.scroll_position(), 30);

        view.scroll_up(100);
        assert_eq!(view.scroll_position(), 0); // min is 0
    }

    #[test]
    fn test_diffview_scroll_to_top_bottom() {
        let diff = (0..100).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
        let mut view = DiffView::new(diff);

        view.scroll_down(50);
        view.scroll_to_top();
        assert_eq!(view.scroll_position(), 0);

        view.scroll_to_bottom();
        assert_eq!(view.scroll_position(), 99);
    }

    #[test]
    fn test_diffview_is_empty() {
        let empty = DiffView::new("".to_string());
        assert!(empty.is_empty());

        let non_empty = DiffView::new("some content".to_string());
        assert!(!non_empty.is_empty());
    }

    #[test]
    fn test_classify_diff_line() {
        assert_eq!(classify_diff_line(""), DiffLineType::Empty);
        assert_eq!(classify_diff_line("diff --git a/file b/file"), DiffLineType::FileHeader);
        assert_eq!(classify_diff_line("--- a/file"), DiffLineType::FileHeader);
        assert_eq!(classify_diff_line("+++ b/file"), DiffLineType::FileHeader);
        assert_eq!(classify_diff_line("index abc123..def456"), DiffLineType::FileHeader);
        assert_eq!(classify_diff_line("@@ -1,5 +1,6 @@"), DiffLineType::HunkHeader);
        assert_eq!(classify_diff_line("+ added line"), DiffLineType::Addition);
        assert_eq!(classify_diff_line("- removed line"), DiffLineType::Deletion);
        assert_eq!(classify_diff_line(" context line"), DiffLineType::Context);
        assert_eq!(classify_diff_line("plain text"), DiffLineType::Context);
    }

    #[test]
    fn test_diff_line_type_color() {
        let t = theme();
        assert_eq!(DiffLineType::Context.color(), t.diff_context());
        assert_eq!(DiffLineType::Addition.color(), t.diff_addition());
        assert_eq!(DiffLineType::Deletion.color(), t.diff_deletion());
        assert_eq!(DiffLineType::HunkHeader.color(), t.diff_hunk_header());
        assert_eq!(DiffLineType::FileHeader.color(), t.diff_file_header());
    }

    #[test]
    fn test_syntax_highlight_toggle() {
        let mut view = DiffView::new("+ line".to_string());
        assert!(view.syntax_highlight);

        view.set_syntax_highlight(false);
        assert!(!view.syntax_highlight);
    }

    #[test]
    fn test_page_up_down() {
        let diff = (0..100).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
        let mut view = DiffView::new(diff);

        view.page_down(20);
        assert_eq!(view.scroll_position(), 18); // 20 - 2

        view.page_up(20);
        assert_eq!(view.scroll_position(), 0);
    }
}