gait 0.1.3

AI-powered toolkit that enhances `Git` workflow
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
#![allow(clippy::as_conversions)]

//! TUI Design System
//!
//! This module implements a design token-based UI system with:
//! - Color palette for consistent theming
//! - Spacing tokens for standardized layout
//! - Typography tokens for text styling

use super::state::{Mode, TuiState};
use super::theme::get_theme;
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap},
};
use unicode_width::UnicodeWidthStr;

// Spacing Tokens (in character units)
const SPACING_XS: u16 = 1; // Smallest spacing
const SPACING_SM: u16 = 2; // Small spacing
const SPACING_MD: u16 = 4; // Medium, default spacing
const SPACING_LG: u16 = 8; // Large spacing

// Helper functions to get theme colors
fn accent_color() -> Color {
    get_theme().accent
}
fn accent_color_active() -> Color {
    get_theme().accent_active
}
fn text_color() -> Color {
    get_theme().text_default
}
fn subtle_color() -> Color {
    get_theme().text_dimmed
}
fn border_color() -> Color {
    get_theme().border
}
fn border_color_active() -> Color {
    get_theme().border_active
}
fn success_color() -> Color {
    get_theme().state_success
}
fn warning_color() -> Color {
    get_theme().state_warning
}
fn error_color() -> Color {
    get_theme().state_error
}
fn brand_primary_color() -> Color {
    get_theme().brand_primary
}
fn font_weight_bold() -> Modifier {
    get_theme().font_weight_bold
}

/// Main UI rendering entry point
pub fn draw_ui(f: &mut Frame, state: &mut TuiState) {
    let chunks = create_layout(f, state);
    render_sections(f, state, &chunks);
}

/// Creates dynamic layout based on visible sections
fn create_layout(f: &Frame, state: &TuiState) -> Vec<Rect> {
    let mut constraints = vec![];

    // Top padding
    constraints.push(Constraint::Length(SPACING_XS));

    if state.nav_bar_visible {
        constraints.push(Constraint::Length(SPACING_MD + SPACING_XS)); // Nav bar with some breathing room
    }

    constraints.push(Constraint::Min(10)); // Main content area

    if state.instructions_visible {
        constraints.push(Constraint::Length(SPACING_LG + SPACING_SM)); // Instructions area
    }

    constraints.push(Constraint::Length(SPACING_XS)); // Status bar

    // Bottom padding
    constraints.push(Constraint::Length(SPACING_XS));

    let vertical_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(f.area());

    // Add horizontal padding using spacing tokens
    let mut final_chunks = vec![];
    for chunk in vertical_layout.iter() {
        let horizontal_layout = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Length(SPACING_MD),
                Constraint::Min(1), // Take remaining space
                Constraint::Length(SPACING_MD),
            ])
            .split(*chunk);
        final_chunks.push(horizontal_layout[1]);
    }

    final_chunks
}

/// Renders all visible UI sections
fn render_sections(f: &mut Frame, state: &mut TuiState, chunks: &[Rect]) {
    // Note: chunks indices need to match create_layout logic
    // 0: Top padding (skip)
    let mut chunk_index = 1;

    if state.nav_bar_visible {
        draw_nav_bar(f, state, chunks[chunk_index]);
        chunk_index += 1;
    }

    draw_commit_message(f, state, chunks[chunk_index]);
    chunk_index += 1;

    if state.instructions_visible {
        draw_instructions(f, state, chunks[chunk_index]);
        chunk_index += 1;
    }

    draw_status(f, state, chunks[chunk_index]);
}

fn draw_nav_bar(f: &mut Frame, state: &TuiState, area: Rect) {
    let nav_items: Vec<(&str, &str)> = match state.mode {
        Mode::Completing => vec![
            ("Tab/Shift+Tab", "Navigate"),
            ("Enter", "Accept"),
            ("Esc", "Cancel"),
        ],
        Mode::ContextSelection => vec![
            ("↑/↓", "Navigate"),
            ("Space", "Toggle"),
            ("Tab", "Category"),
            ("Enter", "Confirm"),
            ("Esc", "Cancel"),
        ],
        Mode::EditingMessage => vec![("Tab", "Complete"), ("Esc", "Finish")],
        Mode::EditingInstructions => vec![("Esc", "Finish")],
        Mode::Help => vec![("Any Key", "Close")],
        _ => vec![
            ("←/→", "Navigate"),
            ("E", "Edit Msg"),
            ("I", "Edit Instr"),
            ("C", "Context"),
            ("R", "Regen"),
            ("Enter", "Commit"),
            ("Esc", "Cancel"),
        ],
    };

    let nav_spans = nav_items
        .iter()
        .enumerate()
        .flat_map(|(i, (key, desc))| {
            let mut spans = vec![
                Span::styled(
                    format!(" {key} "),
                    Style::default()
                        .fg(Color::Black)
                        .bg(accent_color_active())
                        .add_modifier(font_weight_bold()),
                ),
                Span::styled(format!(" {desc} "), Style::default().fg(text_color())),
            ];

            if i < nav_items.len() - 1 {
                spans.push(Span::styled("   ", Style::default()));
            }

            spans
        })
        .collect::<Vec<_>>();

    let nav_bar = Paragraph::new(Line::from(nav_spans))
        .alignment(ratatui::layout::Alignment::Center)
        .block(Block::default().borders(Borders::NONE));

    f.render_widget(nav_bar, area);
}

fn draw_commit_message(f: &mut Frame, state: &mut TuiState, area: Rect) {
    match state.mode {
        Mode::Help => draw_help(f, state, area),
        Mode::Completing => draw_completion(f, state, area),
        Mode::ContextSelection => draw_context_selection(f, state, area),
        _ => {
            let is_editing = state.mode == Mode::EditingMessage;
            let border_color = if is_editing {
                border_color_active()
            } else {
                border_color()
            };

            let title = if is_editing {
                " Edit Message "
            } else {
                " Commit Message "
            };

            let message_block = Block::default()
                .title(Span::styled(
                    title,
                    Style::default()
                        .fg(if is_editing {
                            accent_color_active()
                        } else {
                            accent_color()
                        })
                        .add_modifier(font_weight_bold()),
                ))
                .title_alignment(ratatui::layout::Alignment::Center)
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(border_color));

            if is_editing {
                state.message_textarea.set_block(message_block);
                state
                    .message_textarea
                    .set_style(Style::default().fg(text_color()));
                state
                    .message_textarea
                    .set_cursor_style(Style::default().bg(accent_color_active()).fg(Color::Black));
                f.render_widget(&state.message_textarea, area);
            } else {
                render_commit_message_content(f, state, message_block, area);
            }
        }
    }
}

fn render_commit_message_content(f: &mut Frame, state: &TuiState, block: Block, area: Rect) {
    let current_message = &state.messages[state.current_index];

    // Title
    let title_text = Line::from(vec![Span::styled(
        &current_message.title,
        Style::default()
            .fg(accent_color_active())
            .add_modifier(font_weight_bold()),
    )]);

    let mut content = vec![
        Line::from(""), // Padding
        title_text,
        Line::from(""), // Spacing
        Line::from(vec![Span::styled(
            "─".repeat(area.width.saturating_sub(4) as usize),
            Style::default().fg(subtle_color()),
        )]),
        Line::from(""), // Spacing
    ];

    // Split body by newlines to handle them correctly
    for line in current_message.message.lines() {
        content.push(Line::from(vec![Span::styled(
            line,
            Style::default().fg(text_color()),
        )]));
    }

    let message = Paragraph::new(content)
        .block(block)
        .style(Style::default())
        .wrap(Wrap { trim: false }); // Don't trim to preserve formatting

    f.render_widget(message, area);
}

fn draw_instructions(f: &mut Frame, state: &mut TuiState, area: Rect) {
    let is_editing = state.mode == Mode::EditingInstructions;
    let border_color = if is_editing {
        border_color_active()
    } else {
        border_color()
    };

    let title = if is_editing {
        " Edit Instructions "
    } else {
        " Custom Instructions "
    };

    let instructions_block = Block::default()
        .title(Span::styled(
            title,
            Style::default()
                .fg(if is_editing {
                    accent_color_active()
                } else {
                    accent_color()
                })
                .add_modifier(font_weight_bold()),
        ))
        .title_alignment(ratatui::layout::Alignment::Center)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(border_color));

    if is_editing {
        state.instructions_textarea.set_block(instructions_block);
        state
            .instructions_textarea
            .set_style(Style::default().fg(text_color()));
        state
            .instructions_textarea
            .set_cursor_style(Style::default().bg(accent_color_active()).fg(Color::Black));
        f.render_widget(&state.instructions_textarea, area);
    } else {
        let instructions = Paragraph::new(state.custom_instructions.clone())
            .block(instructions_block)
            .style(Style::default().fg(subtle_color()))
            .wrap(Wrap { trim: true });
        f.render_widget(instructions, area);
    }
}

pub fn draw_status(f: &mut Frame, state: &mut TuiState, area: Rect) {
    let (spinner, content, color, _) = get_status_components(state);

    let status_line = Line::from(vec![
        Span::styled(spinner, Style::default().fg(accent_color_active())),
        Span::raw(" "),
        Span::styled(content, Style::default().fg(color)),
    ]);

    let status_widget = Paragraph::new(status_line).alignment(ratatui::layout::Alignment::Center);

    f.render_widget(Clear, area);
    f.render_widget(status_widget, area);
}

fn get_status_components(state: &mut TuiState) -> (String, String, Color, usize) {
    if let Some(spinner) = &mut state.spinner {
        spinner.tick()
    } else {
        let color = if state.status.contains("Error") || state.status.contains("Failed") {
            error_color()
        } else if state.status.contains("Success") || state.status.contains("Complete") {
            success_color()
        } else if state.status.contains("Warning") {
            warning_color()
        } else {
            subtle_color()
        };

        (
            String::new(),
            state.status.clone(),
            color,
            state.status.width(),
        )
    }
}

#[allow(clippy::too_many_lines)]
fn draw_help(f: &mut Frame, _state: &mut TuiState, area: Rect) {
    // Simplified Help
    let help_text = vec![
        Line::from(""),
        Line::from(vec![Span::styled(
            "Navigation",
            Style::default()
                .fg(brand_primary_color())
                .add_modifier(font_weight_bold()),
        )]),
        Line::from(vec![Span::raw("  ←/→        Next/Prev Message")]),
        Line::from(vec![Span::raw("  ↑/↓        Scroll Content")]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "Actions",
            Style::default()
                .fg(brand_primary_color())
                .add_modifier(font_weight_bold()),
        )]),
        Line::from(vec![Span::raw("  Enter      Commit")]),
        Line::from(vec![Span::raw("  E          Edit Message")]),
        Line::from(vec![Span::raw("  I          Edit Instructions")]),
        Line::from(vec![Span::raw("  R          Regenerate")]),
        Line::from(vec![Span::raw("  Esc        Cancel/Back")]),
    ];

    let help_block = Block::default()
        .title(" Help ")
        .title_alignment(ratatui::layout::Alignment::Center)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(brand_primary_color()));

    let area = centered_rect(area, 60, 50);

    f.render_widget(Clear, area); // Clear background

    let help_paragraph = Paragraph::new(help_text)
        .block(help_block)
        .alignment(ratatui::layout::Alignment::Center)
        .wrap(Wrap { trim: true });

    f.render_widget(help_paragraph, area);
}

fn draw_completion(f: &mut Frame, state: &mut TuiState, area: Rect) {
    let title = format!(
        " Completion Suggestions ({}/{}) ",
        state.completion_index + 1,
        state.completion_suggestions.len()
    );

    let completion_block = Block::default()
        .title(Span::styled(
            title,
            Style::default()
                .fg(accent_color_active())
                .add_modifier(font_weight_bold()),
        ))
        .title_alignment(ratatui::layout::Alignment::Center)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(accent_color_active()));

    let mut completion_lines = Vec::new();

    // Add instructions at the top
    completion_lines.push(Line::from(vec![Span::styled(
        "Use Tab/Shift+Tab to navigate, Enter to accept, Esc to cancel",
        Style::default().fg(subtle_color()),
    )]));
    completion_lines.push(Line::from(""));

    for (i, suggestion) in state.completion_suggestions.iter().enumerate() {
        let (marker, style) = if i == state.completion_index {
            (
                ">",
                Style::default()
                    .fg(Color::Black)
                    .bg(accent_color_active())
                    .add_modifier(font_weight_bold()),
            )
        } else {
            (" ", Style::default().fg(text_color()))
        };

        completion_lines.push(Line::from(vec![
            Span::styled(marker, style),
            Span::raw(" "),
            Span::styled(suggestion, style),
        ]));
    }

    // Position completion box - make it wider for better readability
    let area = centered_rect(area, 70, 50);

    f.render_widget(Clear, area);

    let completion_paragraph = Paragraph::new(completion_lines)
        .block(completion_block)
        .style(Style::default())
        .wrap(Wrap { trim: true });

    f.render_widget(completion_paragraph, area);
}

#[allow(clippy::too_many_lines)]
fn draw_context_selection(f: &mut Frame, state: &mut TuiState, area: Rect) {
    let title = " Context Selection ";

    let context_block = Block::default()
        .title(Span::styled(
            title,
            Style::default()
                .fg(accent_color_active())
                .add_modifier(font_weight_bold()),
        ))
        .title_alignment(ratatui::layout::Alignment::Center)
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(accent_color_active()));

    let mut context_lines = Vec::new();

    // Instructions
    context_lines.push(Line::from(vec![Span::styled(
        "Select context to include in commit message generation:",
        Style::default().fg(subtle_color()),
    )]));
    context_lines.push(Line::from(vec![Span::styled(
        "Arrow keys: navigate | Space: toggle | Tab: switch category | Enter: confirm | Esc: cancel",
        Style::default().fg(subtle_color()),
    )]));
    context_lines.push(Line::from(""));

    if let Some(context) = &state.context {
        // Files section
        context_lines.push(Line::from(vec![Span::styled(
            "Files:",
            Style::default()
                .fg(
                    if state.context_selection_category
                        == super::state::ContextSelectionCategory::Files
                    {
                        accent_color_active()
                    } else {
                        text_color()
                    },
                )
                .add_modifier(font_weight_bold()),
        )]));

        for (i, file) in context.staged_files.iter().enumerate() {
            let is_selected = state.selected_files.get(i).copied().unwrap_or(true);
            let is_current = state.context_selection_category
                == super::state::ContextSelectionCategory::Files
                && state.context_selection_index == i;

            let marker = if is_current { ">" } else { " " };
            let checkbox = if is_selected { "[x]" } else { "[ ]" };

            let style = if is_current {
                Style::default()
                    .fg(Color::Black)
                    .bg(accent_color_active())
                    .add_modifier(font_weight_bold())
            } else {
                Style::default().fg(text_color())
            };

            context_lines.push(Line::from(vec![
                Span::styled(format!("{marker} {checkbox}"), style),
                Span::raw(" "),
                Span::styled(&file.path, style),
                Span::raw(" "),
                Span::styled(
                    format!("({})", file.change_type),
                    Style::default().fg(subtle_color()),
                ),
            ]));
        }

        context_lines.push(Line::from(""));

        // Commits section
        context_lines.push(Line::from(vec![Span::styled(
            "Recent Commits:",
            Style::default()
                .fg(
                    if state.context_selection_category
                        == super::state::ContextSelectionCategory::Commits
                    {
                        accent_color_active()
                    } else {
                        text_color()
                    },
                )
                .add_modifier(font_weight_bold()),
        )]));

        for (i, commit) in context.recent_commits.iter().enumerate() {
            let file_index = context.staged_files.len() + i;
            let is_selected = state.selected_commits.get(i).copied().unwrap_or(true);
            let is_current = state.context_selection_category
                == super::state::ContextSelectionCategory::Commits
                && state.context_selection_index == file_index;

            let marker = if is_current { ">" } else { " " };
            let checkbox = if is_selected { "[x]" } else { "[ ]" };

            let style = if is_current {
                Style::default()
                    .fg(Color::Black)
                    .bg(accent_color_active())
                    .add_modifier(font_weight_bold())
            } else {
                Style::default().fg(text_color())
            };

            // Truncate commit message for display
            let short_message = if commit.message.len() > 60 {
                format!("{}...", &commit.message[..57])
            } else {
                commit.message.clone()
            };

            context_lines.push(Line::from(vec![
                Span::styled(format!("{marker} {checkbox}"), style),
                Span::raw(" "),
                Span::styled(&commit.hash[..7], Style::default().fg(subtle_color())),
                Span::raw(" "),
                Span::styled(short_message, style),
            ]));
        }
    } else {
        context_lines.push(Line::from(vec![Span::styled(
            "No context available",
            Style::default().fg(warning_color()),
        )]));
    }

    let context_paragraph = Paragraph::new(context_lines)
        .block(context_block)
        .style(Style::default())
        .wrap(Wrap { trim: true });

    f.render_widget(context_paragraph, area);
}

/// Helper to center a rect
fn centered_rect(r: Rect, percent_x: u16, percent_y: u16) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}