workmux 0.1.182

An opinionated workflow tool that orchestrates git worktrees and tmux
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
//! Diff view rendering (normal diff, patch mode, file list).

use ratatui::{
    Frame,
    layout::{Constraint, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, List, ListItem, Paragraph},
};

use super::super::diff::DiffView;
use super::theme::ThemePalette;

/// Render the diff view (replaces the entire dashboard).
pub fn render_diff_view(f: &mut Frame, diff: &mut DiffView, palette: &ThemePalette) {
    let area = f.area();

    // Layout: content area + footer
    let chunks = Layout::vertical([
        Constraint::Min(1),    // Content area
        Constraint::Length(1), // Footer
    ])
    .split(area);

    // Split content: File List (Right) + Diff (Left)
    // Only show file list if there are files to display
    let has_files = !diff.file_list.is_empty();
    let content_chunks = if has_files {
        Layout::horizontal([
            Constraint::Min(40),        // Diff content (takes remaining space)
            Constraint::Percentage(25), // File list sidebar
        ])
        .split(chunks[0])
    } else {
        // No files - use full width for diff
        Layout::horizontal([Constraint::Percentage(100)]).split(chunks[0])
    };

    let diff_area = content_chunks[0];
    let file_list_area = if has_files {
        Some(content_chunks[1])
    } else {
        None
    };

    // Update viewport height for scroll calculations (subtract 2 for borders)
    diff.viewport_height = diff_area.height.saturating_sub(2);

    if diff.patch_mode {
        // Patch mode with optional file list sidebar
        render_patch_mode(f, diff, diff_area, chunks[1], palette);
        if let Some(file_area) = file_list_area {
            render_file_list(f, diff, file_area, palette);
        }
    } else {
        // Normal diff mode with optional file list
        render_normal_diff(f, diff, diff_area, chunks[1], palette);
        if let Some(file_area) = file_list_area {
            render_file_list(f, diff, file_area, palette);
        }
    }
}

/// Determine which file is currently visible based on scroll position or current hunk.
fn get_current_file_index(diff: &DiffView) -> Option<usize> {
    if diff.file_list.is_empty() {
        return None;
    }

    // In patch mode, use the current hunk's filename
    if diff.patch_mode && !diff.hunks.is_empty() {
        let current_filename = &diff.hunks[diff.current_hunk].filename;
        return diff
            .file_list
            .iter()
            .position(|f| &f.filename == current_filename);
    }

    // Find the last file whose start_line is <= current scroll position
    let mut current_idx = 0;
    for (idx, file) in diff.file_list.iter().enumerate() {
        if file.start_line <= diff.scroll {
            current_idx = idx;
        } else {
            break;
        }
    }
    Some(current_idx)
}

/// Render the file list sidebar (full paths, directory dimmed, left-truncate if needed).
fn render_file_list(f: &mut Frame, diff: &DiffView, area: Rect, palette: &ThemePalette) {
    let current_file_idx = get_current_file_index(diff);

    let block = Block::bordered()
        .title(format!(" Files ({}) ", diff.file_list.len()))
        .title_style(Style::default().fg(palette.header))
        .border_style(Style::default().fg(palette.dimmed));

    // Calculate available width (subtract borders)
    let inner_width = area.width.saturating_sub(2) as usize;

    let mut items: Vec<ListItem> = Vec::new();

    for (idx, file) in diff.file_list.iter().enumerate() {
        let is_current = current_file_idx == Some(idx);

        // Determine status indicator
        let (status_char, status_color) = if file.is_new {
            ("A", palette.success)
        } else if file.lines_added == 0 && file.lines_removed > 0 {
            ("D", palette.danger)
        } else {
            ("M", palette.warning)
        };

        // Format stats
        let stats = match (file.lines_added, file.lines_removed) {
            (0, 0) => String::new(),
            (a, 0) => format!("+{}", a),
            (0, r) => format!("-{}", r),
            (a, r) => format!("+{} -{}", a, r),
        };

        // Calculate space for path: inner_width - status(2) - stats - min_padding(1)
        let stats_width = if stats.is_empty() { 0 } else { stats.len() + 1 };
        let path_max_width = inner_width.saturating_sub(2 + stats_width);

        // Split into directory and basename
        let (dir, basename) = match file.filename.rsplit_once('/') {
            Some((d, b)) => (Some(d), b),
            None => (None, file.filename.as_str()),
        };

        // Truncate path from left if needed
        let full_path_len = file.filename.len();
        let (display_dir, display_basename) = if full_path_len > path_max_width {
            // Need to truncate - prioritize showing basename
            if basename.len() >= path_max_width {
                // Even basename doesn't fit, truncate it
                let trunc_len = path_max_width.saturating_sub(1); // -1 for "..."
                (
                    None,
                    format!(
                        "...{}",
                        &basename[basename.len().saturating_sub(trunc_len)..]
                    ),
                )
            } else {
                // Truncate directory, keep full basename
                // path_max_width = "..." + dir_chars + "/" + basename
                // dir_chars = path_max_width - 1 (...) - 1 (/) - basename.len()
                let dir_chars = path_max_width.saturating_sub(2 + basename.len());
                match dir {
                    Some(d) if dir_chars > 0 => {
                        let start = d.len().saturating_sub(dir_chars);
                        let truncated = format!("...{}", &d[start..]);
                        (Some(truncated), basename.to_string())
                    }
                    Some(_) => (Some("...".to_string()), basename.to_string()),
                    None => (None, basename.to_string()),
                }
            }
        } else {
            (dir.map(|d| d.to_string()), basename.to_string())
        };

        // Calculate displayed path length
        let path_len = match &display_dir {
            Some(d) => d.len() + 1 + display_basename.len(), // dir/ + basename
            None => display_basename.len(),
        };

        // Calculate padding to right-align stats (minimum 1 space)
        // Total used: status(2) + path_len + padding + stats
        let padding = inner_width
            .saturating_sub(2) // status char + space
            .saturating_sub(path_len)
            .saturating_sub(stats.len())
            .max(1);

        // Build spans
        let mut spans = vec![Span::styled(
            format!("{} ", status_char),
            Style::default().fg(status_color),
        )];

        // Path with directory dimmed
        let basename_style = if is_current {
            Style::default()
                .fg(palette.text)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };

        if let Some(d) = display_dir {
            spans.push(Span::styled(
                format!("{}/", d),
                Style::default().fg(palette.dimmed),
            ));
        }
        spans.push(Span::styled(display_basename, basename_style));

        // Padding + stats (right-aligned)
        if !stats.is_empty() {
            spans.push(Span::raw(" ".repeat(padding)));
            // Color the stats
            if file.lines_added > 0 && file.lines_removed > 0 {
                spans.push(Span::styled(
                    format!("+{}", file.lines_added),
                    Style::default().fg(palette.success),
                ));
                spans.push(Span::styled(
                    format!(" -{}", file.lines_removed),
                    Style::default().fg(palette.danger),
                ));
            } else if file.lines_added > 0 {
                spans.push(Span::styled(stats, Style::default().fg(palette.success)));
            } else {
                spans.push(Span::styled(stats, Style::default().fg(palette.danger)));
            }
        }

        items.push(ListItem::new(Line::from(spans)));
    }

    let list = List::new(items).block(block);

    f.render_widget(list, area);
}

/// Render normal diff view (full diff with scroll).
fn render_normal_diff(
    f: &mut Frame,
    diff: &DiffView,
    content_area: Rect,
    footer_area: Rect,
    palette: &ThemePalette,
) {
    // Create block with title including diff stats
    let title = Line::from(vec![
        Span::styled(
            format!(" {} ", diff.title),
            Style::default()
                .fg(palette.header)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("+{}", diff.lines_added),
            Style::default().fg(palette.success),
        ),
        Span::raw(" "),
        Span::styled(
            format!("-{}", diff.lines_removed),
            Style::default().fg(palette.danger),
        ),
        Span::raw(" "),
    ]);
    let block = Block::bordered()
        .title(title)
        .border_style(Style::default().fg(palette.border));

    // Calculate inner area (content area minus borders)
    let inner_height = content_area.height.saturating_sub(2) as usize;

    // Virtualize: slice only the visible lines from cached parsed_lines
    let max_start = diff.parsed_lines.len().saturating_sub(1);
    let start = diff.scroll.min(max_start);
    let end = (start + inner_height).min(diff.parsed_lines.len());
    let visible_lines: Vec<Line> = diff.parsed_lines[start..end].to_vec();
    let text = Text::from(visible_lines);

    // Render without scroll offset (already sliced to visible portion)
    let paragraph = Paragraph::new(text).block(block);

    f.render_widget(paragraph, content_area);

    // Footer with keybindings - show which diff type is active (toggle with d)
    let (wip_style, review_style) = if diff.is_branch_diff {
        (
            Style::default().fg(palette.dimmed),
            Style::default().fg(palette.success),
        )
    } else {
        (
            Style::default().fg(palette.success),
            Style::default().fg(palette.dimmed),
        )
    };

    let dimmed = Style::default().fg(palette.dimmed);
    let bold_text = Style::default()
        .fg(palette.text)
        .add_modifier(Modifier::BOLD);
    let pipe = || -> Span<'_> { Span::styled(" \u{2502} ", Style::default().fg(palette.border)) };

    let mut footer_spans = vec![
        Span::raw("  "),
        Span::styled("Tab", dimmed),
        Span::raw(" "),
        Span::styled("WIP", wip_style),
        Span::styled(" | ", dimmed),
        Span::styled("review", review_style),
    ];

    // Show patch option only for WIP mode with changes
    if !diff.is_branch_diff && (diff.lines_added > 0 || diff.lines_removed > 0) {
        footer_spans.push(pipe());
        footer_spans.push(Span::styled("a", dimmed));
        footer_spans.push(Span::styled(" Patch", bold_text));
    }

    footer_spans.push(pipe());
    footer_spans.push(Span::styled("j/k", dimmed));
    footer_spans.push(Span::styled(" Scroll", bold_text));
    footer_spans.push(pipe());
    footer_spans.push(Span::styled("c", dimmed));
    footer_spans.push(Span::styled(" Commit", bold_text));
    footer_spans.push(pipe());
    footer_spans.push(Span::styled("m", dimmed));
    footer_spans.push(Span::styled(" Merge", bold_text));
    footer_spans.push(pipe());
    footer_spans.push(Span::styled("q", dimmed));
    footer_spans.push(Span::styled(" Close", bold_text));

    let footer = Paragraph::new(Line::from(footer_spans));
    f.render_widget(footer, footer_area);
}

/// Render patch mode (hunk-by-hunk staging like git add -p).
fn render_patch_mode(
    f: &mut Frame,
    diff: &DiffView,
    content_area: Rect,
    footer_area: Rect,
    palette: &ThemePalette,
) {
    let hunk = &diff.hunks[diff.current_hunk];

    // Title shows filename and hunk progress
    let title = Line::from(vec![
        Span::styled(
            " PATCH ",
            Style::default()
                .fg(palette.current_row_bg)
                .bg(palette.accent)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(" "),
        Span::styled(
            &hunk.filename,
            Style::default()
                .fg(palette.header)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(" "),
        Span::styled(
            format!(
                "[{}/{}]",
                diff.hunks_processed + diff.current_hunk + 1,
                diff.hunks_total
            ),
            Style::default().fg(palette.keycap),
        ),
        Span::raw(" "),
        Span::styled(
            format!("+{}", hunk.lines_added),
            Style::default().fg(palette.success),
        ),
        Span::raw(" "),
        Span::styled(
            format!("-{}", hunk.lines_removed),
            Style::default().fg(palette.danger),
        ),
        Span::raw(" "),
    ]);

    let block = Block::bordered()
        .title(title)
        .border_style(Style::default().fg(palette.accent));

    // Calculate inner area (content area minus borders)
    let inner_height = content_area.height.saturating_sub(2) as usize;

    // Virtualize: slice only the visible lines from cached parsed_lines
    let max_start = hunk.parsed_lines.len().saturating_sub(1);
    let start = diff.scroll.min(max_start);
    let end = (start + inner_height).min(hunk.parsed_lines.len());
    let visible_lines: Vec<Line> = hunk.parsed_lines[start..end].to_vec();
    let text = Text::from(visible_lines);

    // Render without scroll offset (already sliced to visible portion)
    let paragraph = Paragraph::new(text).block(block);

    f.render_widget(paragraph, content_area);

    let dimmed = Style::default().fg(palette.dimmed);
    let bold_text = Style::default()
        .fg(palette.text)
        .add_modifier(Modifier::BOLD);
    let pipe = || -> Span<'_> { Span::styled(" \u{2502} ", Style::default().fg(palette.border)) };

    // Footer: show comment input if in comment mode, otherwise show keybindings
    if let Some(ref input) = diff.comment_input {
        // Comment input mode - hints on left stay fixed, input on right
        let mut spans = vec![
            Span::raw("  "),
            Span::styled("Enter", dimmed),
            Span::styled(" Send", bold_text),
            pipe(),
            Span::styled("Esc", dimmed),
            Span::styled(" Cancel", bold_text),
            Span::raw("  "),
            Span::styled("\u{2502} ", Style::default().fg(palette.border)),
        ];

        if input.is_empty() {
            // Show cursor then placeholder when empty
            spans.push(Span::styled("|", Style::default().fg(palette.text)));
            spans.push(Span::styled("Type your comment...", dimmed));
        } else {
            spans.push(Span::raw(input));
            spans.push(Span::styled("|", Style::default().fg(palette.text)));
        }

        let footer = Paragraph::new(Line::from(spans));
        f.render_widget(footer, footer_area);
    } else {
        // Normal patch mode keybindings
        let mut footer_spans = vec![
            Span::raw("  "),
            Span::styled("y", dimmed),
            Span::styled(" Stage", bold_text),
            pipe(),
            Span::styled("n", dimmed),
            Span::styled(" Skip", bold_text),
        ];

        // Show undo option if there are staged hunks
        if !diff.staged_hunks.is_empty() {
            footer_spans.push(pipe());
            footer_spans.push(Span::styled("u", dimmed));
            footer_spans.push(Span::styled(" Undo", bold_text));
        }

        footer_spans.push(pipe());
        footer_spans.push(Span::styled("s", dimmed));
        footer_spans.push(Span::styled(" Split", bold_text));
        footer_spans.push(pipe());
        footer_spans.push(Span::styled("o", dimmed));
        footer_spans.push(Span::styled(" Comment", bold_text));
        footer_spans.push(pipe());
        footer_spans.push(Span::styled("j/k", dimmed));
        footer_spans.push(Span::styled(" Nav", bold_text));
        footer_spans.push(pipe());
        footer_spans.push(Span::styled("q", dimmed));
        footer_spans.push(Span::styled(" Quit", bold_text));

        let footer = Paragraph::new(Line::from(footer_spans));
        f.render_widget(footer, footer_area);
    }
}