ratkit 0.2.14

A comprehensive collection of reusable TUI components for ratatui including resizable splits, tree views, markdown rendering, toast notifications, dialogs, and terminal embedding
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
//! AI Chat Widget for interactive chat interfaces.
//!
//! Provides a chat interface with:
//! - Multi-line text input (Ctrl+J for newline)
//! - File attachments via @ prefix with fuzzy search
//! - Commands via / prefix (e.g., /clear)
//! - Message history display
//! - Loading spinner for AI responses

use crate::widgets::ai_chat::{InputState, Message, MessageRole, MessageStore};
use ratatui::style::Style;

/// Result of handling a key event.
#[derive(Debug, Clone, PartialEq)]
pub enum AIChatEvent {
    /// No event
    None,
    /// Message submitted
    MessageSubmitted(String),
    /// File attached
    FileAttached(String),
    /// Command executed
    Command(String),
}

/// AI Chat widget for interactive chat interfaces.
pub struct AIChat {
    /// Store for chat messages
    messages: MessageStore,
    /// Input state for text entry
    input: InputState,
    /// Whether AI is generating a response
    is_loading: bool,
    /// Style for user messages
    user_message_style: Style,
    /// Style for AI messages
    ai_message_style: Style,
    /// Style for input area
    input_style: Style,
    /// Prompt text for input
    input_prompt: String,
    /// Available commands
    commands: Vec<String>,
    /// Selected command index in command mode
    selected_command_index: usize,
}

impl AIChat {
    /// Create a new AI chat widget.
    pub fn new() -> Self {
        Self {
            messages: MessageStore::new(),
            input: InputState::new(),
            is_loading: false,
            user_message_style: Style::default()
                .fg(Color::LightCyan)
                .add_modifier(Modifier::BOLD),
            ai_message_style: Style::default().fg(Color::White),
            input_style: Style::default().fg(Color::White),
            input_prompt: "You: ".to_string(),
            commands: vec!["/clear".to_string()],
            selected_command_index: 0,
        }
    }

    /// Set selected command index (for builder pattern).
    pub fn with_selected_command_index(mut self, index: usize) -> Self {
        self.selected_command_index = index;
        self
    }

    /// Register a command.
    pub fn register_command(&mut self, command: String) {
        if !self.commands.contains(&command) {
            self.commands.push(command);
        }
    }

    /// Get available commands.
    pub fn commands(&self) -> &[String] {
        &self.commands
    }

    /// Get filtered commands matching the current command input.
    pub fn filtered_commands(&self) -> Vec<String> {
        let command_lower = self.input.command().to_lowercase();
        self.commands
            .iter()
            .filter(|c| c.to_lowercase().starts_with(&format!("/{}", command_lower)))
            .cloned()
            .collect()
    }

    /// Get selected command index.
    pub fn selected_command_index(&self) -> usize {
        self.selected_command_index
    }

    /// Set selected command index.
    pub fn set_selected_command_index(&mut self, index: usize) {
        self.selected_command_index = index;
    }

    /// Handle a command string (e.g., "/clear").
    ///
    /// Returns true if command was handled, false if unknown.
    pub fn handle_command(&mut self, command: &str) -> bool {
        match command {
            "/clear" => {
                self.messages.clear();
                true
            }
            _ => false,
        }
    }

    /// Set the loading state.
    pub fn set_loading(&mut self, loading: bool) {
        self.is_loading = loading;
    }

    /// Get the loading state.
    pub fn is_loading(&self) -> bool {
        self.is_loading
    }

    /// Set user message style.
    pub fn with_user_message_style(mut self, style: Style) -> Self {
        self.user_message_style = style;
        self
    }

    /// Set AI message style.
    pub fn with_ai_message_style(mut self, style: Style) -> Self {
        self.ai_message_style = style;
        self
    }

    /// Set input style.
    pub fn with_input_style(mut self, style: Style) -> Self {
        self.input_style = style;
        self
    }

    /// Set input prompt text.
    pub fn with_prompt(mut self, prompt: String) -> Self {
        self.input_prompt = prompt;
        self
    }

    /// Handle a key event.
    ///
    /// Returns an event indicating what happened.
    pub fn handle_key(&mut self, key: crossterm::event::KeyCode) -> AIChatEvent {
        use crossterm::event::{KeyEvent, KeyModifiers};

        let key = KeyEvent::new(key, KeyModifiers::NONE);

        if let Some(result) = self.input.handle_key(key) {
            if result.starts_with('@') {
                return AIChatEvent::FileAttached(result);
            }
            if result.starts_with('/') {
                if self.handle_command(&result) {
                    return AIChatEvent::Command(result);
                }
                return AIChatEvent::Command(result);
            }
            if !result.is_empty() {
                self.messages.add(Message::user(result.clone()));
                self.is_loading = true;
                return AIChatEvent::MessageSubmitted(result);
            }
        }
        AIChatEvent::None
    }

    /// Get messages reference.
    pub fn messages(&self) -> &MessageStore {
        &self.messages
    }

    /// Get messages mutable reference.
    pub fn messages_mut(&mut self) -> &mut MessageStore {
        &mut self.messages
    }

    /// Get input reference.
    pub fn input(&self) -> &InputState {
        &self.input
    }

    /// Get input mutable reference.
    pub fn input_mut(&mut self) -> &mut InputState {
        &mut self.input
    }
}

use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style as TuiStyle},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, List, ListItem, Paragraph},
    Frame,
};

impl AIChat {
    pub fn render(&self, frame: &mut Frame, area: Rect) {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(0), Constraint::Length(3)])
            .split(area);

        let messages_area = chunks[0];
        let input_area = chunks[1];

        self.render_messages(frame, messages_area);
        self.render_input(frame, input_area);

        if self.input.is_file_mode() {
            self.render_file_popup(frame, input_area);
        } else if self.input.is_command_mode() {
            self.render_command_popup(frame, input_area);
        }
    }

    fn render_messages(&self, frame: &mut Frame, area: Rect) {
        let block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title(" Chat ");

        let inner = block.inner(area);
        frame.render_widget(block, area);

        let mut items = Vec::new();

        for msg in self.messages.messages() {
            let prefix = match msg.role {
                MessageRole::User => "You: ",
                MessageRole::Assistant => "AI:  ",
            };

            let style = match msg.role {
                MessageRole::User => self.user_message_style,
                MessageRole::Assistant => self.ai_message_style,
            };

            let mut content = vec![Span::styled(prefix, style)];

            if !msg.attachments.is_empty() {
                let files_str = msg
                    .attachments
                    .iter()
                    .map(|f| format!("@{}", f))
                    .collect::<Vec<_>>()
                    .join(", ");
                content.push(Span::styled(
                    format!("[{}] ", files_str),
                    TuiStyle::default().fg(Color::Yellow),
                ));
            }

            content.push(Span::raw(&msg.content));

            let line = Line::from(content);
            items.push(ListItem::new(line));
        }

        if self.is_loading {
            items.push(ListItem::new(Line::from(vec![
                Span::styled("AI:  ", self.ai_message_style),
                Span::styled("â ‹ Thinking...", TuiStyle::default().fg(Color::Gray)),
            ])));
        }

        let list = List::new(items)
            .block(Block::default())
            .style(TuiStyle::default());

        frame.render_widget(list, inner);
    }

    fn render_input(&self, frame: &mut Frame, area: Rect) {
        let mut input_text = self.input.text().to_string();

        if self.input.is_file_mode() {
            let filtered = self.input.filtered_files();
            if let Some(file) = filtered.get(self.input.selected_file_index()) {
                input_text = format!("@{}{}", self.input.file_query(), file);
            } else {
                input_text = format!("@{}", self.input.file_query());
            }
        } else if self.input.is_command_mode() {
            let filtered = self.filtered_commands();
            if let Some(cmd) = filtered.get(self.selected_command_index()) {
                input_text = cmd.clone();
            } else {
                input_text = format!("/{}", self.input.command());
            }
        }

        let prompt = &self.input_prompt;
        let cursor_pos = prompt.len() + self.input.cursor();

        let paragraph = Paragraph::new(format!("{}{}", prompt, input_text))
            .style(self.input_style)
            .block(Block::default());

        frame.render_widget(paragraph, area);

        if cursor_pos < input_text.len() + prompt.len() {
            let cursor_x = area.x + cursor_pos as u16;
            let cursor_y = area.y;
            frame.set_cursor_position((cursor_x, cursor_y));
        }
    }

    fn render_file_popup(&self, frame: &mut Frame, input_area: Rect) {
        let filtered = self.input.filtered_files();

        if filtered.is_empty() {
            return;
        }

        let max_height = 10.min(filtered.len() as u16);
        let popup_height = max_height + 2;

        let popup_y = if input_area.y.saturating_sub(popup_height) > 0 {
            input_area.y.saturating_sub(popup_height)
        } else {
            input_area.y.saturating_add(1)
        };

        let popup_width = 40.min(input_area.width);
        let popup_x = input_area.x;

        let popup_area = Rect {
            x: popup_x,
            y: popup_y,
            width: popup_width,
            height: popup_height,
        };

        let items: Vec<ListItem> = filtered
            .iter()
            .enumerate()
            .map(|(i, file)| {
                let style = if i == self.input.selected_file_index() {
                    TuiStyle::default()
                        .bg(Color::Blue)
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD)
                } else {
                    TuiStyle::default().fg(Color::White).bg(Color::Black)
                };
                ListItem::new(Span::styled(file.clone(), style))
            })
            .collect();

        let list = List::new(items).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .style(TuiStyle::default().bg(Color::Black)),
        );

        frame.render_widget(list, popup_area);
    }

    fn render_command_popup(&self, frame: &mut Frame, input_area: Rect) {
        let filtered = self.filtered_commands();

        if filtered.is_empty() {
            return;
        }

        let max_height = 10.min(filtered.len() as u16);
        let popup_height = max_height + 2;

        let popup_y = if input_area.y.saturating_sub(popup_height) > 0 {
            input_area.y.saturating_sub(popup_height)
        } else {
            input_area.y.saturating_add(1)
        };

        let popup_width = 40.min(input_area.width);
        let popup_x = input_area.x;

        let popup_area = Rect {
            x: popup_x,
            y: popup_y,
            width: popup_width,
            height: popup_height,
        };

        let items: Vec<ListItem> = filtered
            .iter()
            .enumerate()
            .map(|(i, cmd)| {
                let style = if i == self.selected_command_index() {
                    TuiStyle::default()
                        .bg(Color::Blue)
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD)
                } else {
                    TuiStyle::default().fg(Color::White).bg(Color::Black)
                };
                ListItem::new(Span::styled(cmd.clone(), style))
            })
            .collect();

        let list = List::new(items).block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .style(TuiStyle::default().bg(Color::Black)),
        );

        frame.render_widget(list, popup_area);
    }
}