arct-tui 0.2.2

Terminal UI for Arc Academy Terminal - interactive shell learning interface
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
//! UI rendering and layout

use crate::app::App;
use crate::icons;
use crate::panels::{
    context::ContextPanel,
    explanation::ExplanationPanel,
    help::HelpPanel,
    PanelId,
};
use crate::theme::Theme;
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::Modifier,
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
    Frame,
};

/// Minimum terminal dimensions for usable display
const MIN_WIDTH: u16 = 40;
const MIN_HEIGHT: u16 = 12;

/// Main UI drawing function
pub fn draw(frame: &mut Frame, app: &mut App) {
    let size = frame.size();

    // Check minimum terminal size
    if size.width < MIN_WIDTH || size.height < MIN_HEIGHT {
        let msg = format!(
            "Terminal too small ({} x {})\nMinimum: {} x {}",
            size.width, size.height, MIN_WIDTH, MIN_HEIGHT
        );
        let paragraph = Paragraph::new(msg)
            .style(app.theme.style_warning())
            .wrap(Wrap { trim: false });
        frame.render_widget(paragraph, size);
        return;
    }

    // Main layout: header + content
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Content
        ])
        .split(size);

    // Draw header
    draw_header(frame, chunks[0], app);

    // Draw main content
    draw_content(frame, chunks[1], app);

    // Draw onboarding wizard if active (highest priority)
    if let Some(ref wizard) = app.onboarding {
        wizard.render(frame, &app.theme);
        return;  // Don't render anything else
    }

    // Draw help overlay if active
    if app.show_help {
        let help_panel = HelpPanel::new();
        help_panel.render(frame, &app.theme);
        return;  // Don't render other overlays
    }

    // Draw settings panel if active
    if let Some(ref panel) = app.settings_panel {
        panel.render(frame, &app.theme, &app.config);
    }

    // Draw lesson menu if active
    if let Some(ref mut menu) = app.lesson_menu {
        menu.render(
            frame,
            &app.theme,
            &app.completed_lessons,
            &app.user_stats,
            &app.recommendation_engine,
        );
    }

    // Draw gamification panels if active
    if let Some(ref panel) = app.achievements_panel {
        panel.render(frame, &app.theme, &app.user_stats.achievements);
    }

    if let Some(ref panel) = app.progress_panel {
        panel.render(frame, &app.theme, &app.user_stats);
    }

    if let Some(ref panel) = app.challenges_panel {
        panel.render(frame, &app.theme, &app.challenge_manager);
    }

    // Achievement notification has highest priority (render last)
    if let Some(ref notification) = app.showing_notification {
        notification.render(frame, &app.theme);
    }
}

/// Draw the header
fn draw_header(frame: &mut Frame, area: Rect, app: &App) {
    let width = area.width as usize;

    // Responsive title - shorter on narrow terminals
    let title = if width >= 60 {
        format!("  {}ARC ACADEMY TERMINAL ", icons::lightning().content)
    } else if width >= 40 {
        format!(" {}ARCT ", icons::lightning().content)
    } else {
        format!("{}A", icons::lightning().content)
    };

    let mode_indicator = if app.lesson_mode {
        if width >= 50 { format!(" {}LESSON ", icons::lesson().content) } else { String::new() }
    } else if app.ai_mode {
        if width >= 50 { format!(" {}AI ", icons::ai().content) } else { String::new() }
    } else {
        String::new()
    };

    // Responsive version info
    let version = if width >= 80 {
        format!("v{} | {} ", env!("CARGO_PKG_VERSION"), app.theme.name)
    } else if width >= 50 {
        format!("v{} ", env!("CARGO_PKG_VERSION"))
    } else {
        String::new()
    };

    // Responsive help text - progressively shorter
    let help_text = if width >= 120 {
        " [? help] [^L lessons] [^A AI] [^T theme] [q quit] "
    } else if width >= 80 {
        " [?] [^L] [^A] [^T] [q] "
    } else if width >= 50 {
        " [? help] "
    } else {
        ""
    };

    let title_len = title.chars().count();
    let version_len = version.chars().count();
    let mode_len = mode_indicator.chars().count();
    let help_len = help_text.chars().count();

    let used_width = title_len + mode_len + version_len + help_len;
    let padding = width.saturating_sub(used_width + 2); // +2 for borders

    let mut spans = vec![
        Span::styled(&title, app.theme.style_accent().add_modifier(Modifier::BOLD)),
    ];

    if !mode_indicator.is_empty() {
        spans.push(Span::styled(&mode_indicator, app.theme.style_success().add_modifier(Modifier::BOLD)));
    }

    if !version.is_empty() {
        spans.push(Span::styled(&version, app.theme.style_info()));
    }

    if padding > 0 {
        spans.push(Span::raw(" ".repeat(padding)));
    }

    if !help_text.is_empty() {
        spans.push(Span::styled(help_text, app.theme.style_dim()));
    }

    let header_text = Line::from(spans);

    let header = Paragraph::new(header_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(app.theme.style_border_focused())
                .style(app.theme.style_block()),  // Set background for light themes
        );

    frame.render_widget(header, area);
}

/// Draw the main content area
fn draw_content(frame: &mut Frame, area: Rect, app: &App) {
    let width = area.width;

    // Responsive layout: hide context panel on very narrow terminals
    let main_chunks = if width < 60 {
        // Single column - no context panel
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Length(0), // Hide context panel
                Constraint::Min(0),    // Shell + Explanation takes all
            ])
            .split(area)
    } else if width < 100 {
        // Narrower split for medium terminals
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Min(20),   // Context panel min 20
                Constraint::Min(40),   // Shell + Explanation min 40
            ])
            .split(area)
    } else {
        // Standard split for wide terminals
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(30), // Context panel
                Constraint::Percentage(70), // Shell + Explanation
            ])
            .split(area)
    };

    // Left: Context panel (only render if visible)
    if main_chunks[0].width > 0 {
        let context_panel = ContextPanel::new();

        // Get analytics summary if available
        let analytics_summary = app.analytics.as_ref()
            .and_then(|a| a.get_summary().ok());

        context_panel.render(
            frame,
            main_chunks[0],
            app.active_panel == PanelId::Context,
            &app.context,
            &app.theme,
            app.config.ai.enabled,
            analytics_summary.as_ref(),
            app.lesson_mode,
            app.virtual_fs.as_ref(),
            &app.user_stats,
            &app.challenge_manager,
        );
    }

    // Right side: Classic terminal layout (Explanation → Output → Shell at bottom)
    // This follows traditional terminal UX where input is at the bottom
    let height = main_chunks[1].height;
    let right_chunks = if height < 15 {
        // Very short terminal - minimal layout (hide explanation)
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(0),  // Hide explanation
                Constraint::Min(0),     // Everything else to output
                Constraint::Length(3),  // Shell input at bottom
            ])
            .split(main_chunks[1])
    } else if height < 25 {
        // Short terminal - compact layout
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Min(5),     // Explanation (smaller but visible)
                Constraint::Percentage(50), // Command output
                Constraint::Length(3),  // Shell input at bottom
            ])
            .split(main_chunks[1])
    } else {
        // Standard layout - explanation prominent for learning
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Percentage(35), // Explanation (learning focus)
                Constraint::Percentage(40), // Command output
                Constraint::Length(3),  // Shell input at bottom
            ])
            .split(main_chunks[1])
    };

    // Explanation panel OR Lesson panel (top - high visibility for learning)
    if right_chunks[0].height > 0 {
        if app.lesson_mode {
            // Lesson mode - show interactive lessons
            if let Some(ref lesson_panel) = app.lesson_panel {
                lesson_panel.render(
                    frame,
                    right_chunks[0],
                    app.active_panel == PanelId::Explanation,
                    &app.theme,
                );
            }
        } else {
            // Normal mode - show explanations
            let explanation_panel = ExplanationPanel::new();
            explanation_panel.render(
                frame,
                right_chunks[0],
                app.active_panel == PanelId::Explanation,
                app.last_explanation.as_ref(),
                &app.theme,
                app.ai_mode,
                app.ai_response.as_deref(),
            );
        }
    }

    // Output panel (middle - shows command results)
    draw_output_panel(
        frame,
        right_chunks[1],
        app.active_panel == PanelId::Output,
        &app.last_output,
        app.output_scroll,
        &app.theme,
    );

    // Shell panel (bottom - classic terminal position)
    draw_shell_panel(
        frame,
        right_chunks[2],
        app.active_panel == PanelId::Shell,
        &app.command_buffer,
        &app.completion_suggestions,
        &app.theme,
        app.ai_mode,
        &app.ai_input_buffer,
        app.ai_loading,
    );
}

/// Draw the shell panel
fn draw_shell_panel(
    frame: &mut Frame,
    area: Rect,
    focused: bool,
    command: &str,
    completions: &[String],
    theme: &Theme,
    ai_mode: bool,
    ai_input: &str,
    ai_loading: bool,
) {
    let border_style = if focused {
        theme.style_border_focused()
    } else {
        theme.style_border()
    };

    let title = if ai_mode {
        if focused {
            format!(" {}AI Assistant (Active - Ctrl+A to exit, Enter to ask) ", icons::ai().content)
        } else {
            format!(" {}AI Assistant ", icons::ai().content)
        }
    } else if focused {
        format!(" {}Shell (Active - Ctrl+A for AI, Tab to complete, ↑↓ for history) ", icons::shell().content)
    } else {
        format!(" {}Shell ", icons::shell().content)
    };

    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(border_style)
        .style(theme.style_block());  // Set background for light themes

    // Build lines for the panel
    let mut lines = Vec::new();

    // First line: prompt and command (or AI input)
    if ai_mode {
        let prompt = icons::ai();
        let input_text = if ai_loading {
            Span::styled(format!("{}Thinking...", icons::loading().content), theme.style_dim())
        } else {
            Span::styled(ai_input, theme.style_normal())
        };

        let mut input_line = vec![prompt, input_text];

        // Add cursor if focused and not loading
        if focused && !ai_loading {
            input_line.push(Span::styled("", theme.style_accent()));
        }

        lines.push(Line::from(input_line));
    } else {
        let prompt = Span::styled("$ ", theme.style_accent());
        let command_text = Span::styled(command, theme.style_normal());

        let mut command_line = vec![prompt, command_text];

        // Add cursor if focused
        if focused {
            command_line.push(Span::styled("", theme.style_accent()));
        }

        lines.push(Line::from(command_line));
    }

    // Add completion suggestions if any (only in shell mode)
    if !ai_mode && !completions.is_empty() {
        lines.push(Line::from(""));  // Empty line
        lines.push(Line::from(vec![
            icons::hint(),
            Span::styled("Suggestions:", theme.style_dim()),
        ]));

        for completion in completions.iter().take(5) {
            lines.push(Line::from(vec![
                Span::styled("", theme.style_dim()),
                Span::styled(completion, theme.style_success()),
            ]));
        }

        if completions.len() > 5 {
            lines.push(Line::from(vec![
                Span::styled(format!("  ...and {} more", completions.len() - 5), theme.style_dim()),
            ]));
        }
    }

    let paragraph = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });

    frame.render_widget(paragraph, area);
}

/// Draw the output panel
fn draw_output_panel(
    frame: &mut Frame,
    area: Rect,
    focused: bool,
    output: &str,
    scroll_offset: usize,
    theme: &Theme,
) {
    let border_style = if focused {
        theme.style_border_focused()
    } else {
        theme.style_border()
    };

    let title = if focused {
        format!(" {}Output (↑↓ scroll) ", icons::output().content)
    } else {
        format!(" {}Output (^↑↓ scroll) ", icons::output().content)
    };

    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(border_style)
        .style(theme.style_block());  // Set background for light themes

    let inner_height = area.height.saturating_sub(2) as usize; // Subtract borders

    let text = if output.is_empty() {
        vec![
            Line::from(""),
            Line::from(vec![
                Span::styled("  Ready to execute commands!", theme.style_dim()),
            ]),
            Line::from(""),
            Line::from(vec![
                Span::styled("  Type a command above and press ", theme.style_dim()),
                Span::styled("Enter", theme.style_accent()),
            ]),
        ]
    } else {
        // Parse ANSI codes for colored output!
        let all_lines: Vec<Line> = crate::ansi::parse_ansi(output);
        let total_lines = all_lines.len();

        // Show scroll indicator if there are more lines than can fit
        let mut visible_lines: Vec<Line> = all_lines
            .into_iter()
            .skip(scroll_offset)
            .take(inner_height)
            .collect();

        // Add scroll indicator at bottom if not at end
        if scroll_offset + inner_height < total_lines {
            let remaining = total_lines - (scroll_offset + inner_height);
            visible_lines.push(Line::from(vec![
                Span::styled(
                    format!("{} more lines (press ↓ or j to scroll)", remaining),
                    theme.style_dim(),
                ),
            ]));
        }

        // Add scroll indicator at top if not at beginning
        if scroll_offset > 0 {
            visible_lines.insert(0, Line::from(vec![
                Span::styled(
                    format!("{} lines above (press ↑ or k to scroll)", scroll_offset),
                    theme.style_dim(),
                ),
            ]));
        }

        visible_lines
    };

    let paragraph = Paragraph::new(text)
        .block(block)
        .wrap(Wrap { trim: false });

    frame.render_widget(paragraph, area);
}