arta-tui 0.2.1

Terminal workspace manager for concurrent AI coding agent sessions (tmux/zellij)
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
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use std::fs;

#[derive(Clone, Copy, PartialEq)]
pub enum InputMode {
    Text,
    Path,
}

pub enum InputAction {
    None,
    Submit(String),
    Cancel,
}

struct DirEntry {
    name: String,
    is_dir: bool,
}

pub struct InputPanel {
    mode: InputMode,
    title: String,
    value: String,
    cursor_pos: usize,
    active: bool,
    width: u16,
    height: u16,
    dir_entries: Vec<DirEntry>,
    dir_cursor: usize,
    dir_scroll: usize,
}

impl InputPanel {
    pub fn new() -> Self {
        InputPanel {
            mode: InputMode::Text,
            title: String::new(),
            value: String::new(),
            cursor_pos: 0,
            active: false,
            width: 80,
            height: 15,
            dir_entries: Vec::new(),
            dir_cursor: 0,
            dir_scroll: 0,
        }
    }

    pub fn activate(
        &mut self,
        mode: InputMode,
        title: &str,
        initial_value: &str,
        width: u16,
        height: u16,
    ) {
        self.mode = mode;
        self.title = title.to_string();
        self.value = initial_value.to_string();
        self.cursor_pos = self.value.len();
        self.active = true;
        self.width = width;
        self.height = height;
        self.dir_cursor = 0;
        self.dir_scroll = 0;
        if mode == InputMode::Path {
            self.update_dir_listing();
        }
    }

    pub fn deactivate(&mut self) {
        self.active = false;
    }

    pub fn is_active(&self) -> bool {
        self.active
    }

    pub fn cursor_position(&self, area: Rect) -> (u16, u16) {
        // Title is on line 1 (after border), input on line 2
        let x = area.x + self.cursor_pos as u16;
        let y = area.y + 2;
        (x, y)
    }

    pub fn handle_key(&mut self, key: &KeyEvent) -> InputAction {
        if !self.active {
            return InputAction::None;
        }

        match key.code {
            KeyCode::Esc => {
                self.deactivate();
                InputAction::Cancel
            }

            KeyCode::Enter => {
                if self.mode == InputMode::Path && !self.dir_entries.is_empty() {
                    let entry = &self.dir_entries[self.dir_cursor];
                    if entry.is_dir {
                        let current = self.expand_path(&self.value);
                        let dir = if current.ends_with('/') {
                            current
                        } else {
                            match current.rfind('/') {
                                Some(i) => current[..=i].to_string(),
                                None => current,
                            }
                        };
                        let new_path = format!("{}{}/", dir, entry.name);
                        self.value = new_path;
                        self.cursor_pos = self.value.len();
                        self.dir_cursor = 0;
                        self.dir_scroll = 0;
                        self.update_dir_listing();
                        return InputAction::None;
                    }
                }
                let val = self.value.clone();
                self.deactivate();
                InputAction::Submit(val)
            }

            KeyCode::Tab => {
                if self.mode == InputMode::Path {
                    self.tab_complete();
                }
                InputAction::None
            }

            KeyCode::Up => {
                if self.mode == InputMode::Path && self.dir_cursor > 0 {
                    self.dir_cursor -= 1;
                    if self.dir_cursor < self.dir_scroll {
                        self.dir_scroll = self.dir_cursor;
                    }
                }
                InputAction::None
            }

            KeyCode::Down => {
                if self.mode == InputMode::Path
                    && self.dir_cursor < self.dir_entries.len().saturating_sub(1)
                {
                    self.dir_cursor += 1;
                    let max_visible = self.max_visible_entries();
                    if self.dir_cursor >= self.dir_scroll + max_visible {
                        self.dir_scroll = self.dir_cursor - max_visible + 1;
                    }
                }
                InputAction::None
            }

            KeyCode::Char(c) => {
                self.value.insert(self.cursor_pos, c);
                self.cursor_pos += c.len_utf8();
                if self.mode == InputMode::Path {
                    self.update_dir_listing();
                }
                InputAction::None
            }

            KeyCode::Backspace => {
                if self.cursor_pos > 0 {
                    // Find the previous char boundary
                    let prev = self.value[..self.cursor_pos]
                        .char_indices()
                        .last()
                        .map(|(i, _)| i)
                        .unwrap_or(0);
                    self.value.remove(prev);
                    self.cursor_pos = prev;
                    if self.mode == InputMode::Path {
                        self.update_dir_listing();
                    }
                }
                InputAction::None
            }

            KeyCode::Left => {
                if self.cursor_pos > 0 {
                    self.cursor_pos = self.value[..self.cursor_pos]
                        .char_indices()
                        .last()
                        .map(|(i, _)| i)
                        .unwrap_or(0);
                }
                InputAction::None
            }

            KeyCode::Right => {
                if self.cursor_pos < self.value.len() {
                    self.cursor_pos += self.value[self.cursor_pos..]
                        .chars()
                        .next()
                        .map(|c| c.len_utf8())
                        .unwrap_or(0);
                }
                InputAction::None
            }

            _ => InputAction::None,
        }
    }

    pub fn render(&self, area: Rect, buf: &mut Buffer) {
        if !self.active {
            return;
        }

        let dim = Style::default().add_modifier(Modifier::DIM);
        let title_style = Style::default()
            .fg(Color::Rgb(0x51, 0xAF, 0xEF))
            .add_modifier(Modifier::BOLD);
        let selected_style = Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD);
        let dir_style = Style::default().fg(Color::Rgb(0x51, 0xAF, 0xEF));

        let mut y = area.y;

        // Top border
        if y < area.y + area.height {
            let sep = "\u{2500}".repeat(area.width as usize);
            buf.set_line(area.x, y, &Line::from(Span::styled(sep, dim)), area.width);
            y += 1;
        }

        // Title
        if y < area.y + area.height {
            buf.set_line(
                area.x,
                y,
                &Line::from(Span::styled(&self.title, title_style)),
                area.width,
            );
            y += 1;
        }

        // Input value
        if y < area.y + area.height {
            buf.set_line(
                area.x,
                y,
                &Line::from(Span::raw(&self.value)),
                area.width,
            );
            y += 1;
        }

        if self.mode == InputMode::Path {
            // Separator
            if y < area.y + area.height {
                let sep = "\u{2500}".repeat(area.width as usize);
                buf.set_line(area.x, y, &Line::from(Span::styled(sep, dim)), area.width);
                y += 1;
            }

            let max_visible = self.max_visible_entries();
            let end = (self.dir_scroll + max_visible).min(self.dir_entries.len());

            for i in self.dir_scroll..end {
                if y >= area.y + area.height {
                    break;
                }
                let entry = &self.dir_entries[i];
                let suffix = if entry.is_dir { "/" } else { "" };
                let text = format!("  {}{}", entry.name, suffix);

                let style = if i == self.dir_cursor {
                    selected_style
                } else if entry.is_dir {
                    dir_style
                } else {
                    dim
                };

                buf.set_line(area.x, y, &Line::from(Span::styled(text, style)), area.width);
                y += 1;
            }

            if self.dir_entries.is_empty() && y < area.y + area.height {
                buf.set_line(
                    area.x,
                    y,
                    &Line::from(Span::styled("  (empty)", dim)),
                    area.width,
                );
                y += 1;
            }
        }

        // Help line at the bottom
        let help_y = area.y + area.height - 1;
        if help_y > y || y >= area.y + area.height {
            let help = if self.mode == InputMode::Path {
                " esc cancel  tab complete  \u{2191}\u{2193} select  enter open/confirm"
            } else {
                " esc cancel"
            };
            buf.set_line(
                area.x,
                help_y,
                &Line::from(Span::styled(help, dim)),
                area.width,
            );
        }
    }

    fn split_dir_prefix<'a>(path: &'a str) -> (&'a str, &'a str) {
        if path.ends_with('/') {
            (path, "")
        } else {
            match path.rfind('/') {
                Some(i) => (&path[..=i], &path[i + 1..]),
                None => (path, ""),
            }
        }
    }

    fn update_dir_listing(&mut self) {
        let path = self.expand_path(&self.value);
        let (dir, prefix) = Self::split_dir_prefix(&path);
        let prefix_lower = prefix.to_lowercase();

        self.dir_entries = match fs::read_dir(dir) {
            Ok(entries) => entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    let name = e.file_name().to_string_lossy().to_string();
                    !name.starts_with('.')
                        && (prefix_lower.is_empty()
                            || name.to_lowercase().starts_with(&prefix_lower))
                })
                .map(|e| {
                    let name = e.file_name().to_string_lossy().to_string();
                    let is_dir = e.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
                    DirEntry { name, is_dir }
                })
                .collect(),
            Err(_) => Vec::new(),
        };

        // Sort: dirs first, then alphabetically
        self.dir_entries
            .sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then(a.name.cmp(&b.name)));

        if self.dir_cursor >= self.dir_entries.len() {
            self.dir_cursor = self.dir_entries.len().saturating_sub(1);
        }
    }

    fn tab_complete(&mut self) {
        let path = self.expand_path(&self.value);
        let (dir, prefix) = Self::split_dir_prefix(&path);
        let prefix_lower = prefix.to_lowercase();

        let matches: Vec<String> = match fs::read_dir(dir) {
            Ok(entries) => entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    e.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
                        && e.file_name()
                            .to_string_lossy()
                            .to_lowercase()
                            .starts_with(&prefix_lower)
                })
                .map(|e| e.file_name().to_string_lossy().to_string())
                .collect(),
            Err(_) => Vec::new(),
        };

        if matches.len() == 1 {
            self.value = format!("{}{}/", dir, matches[0]);
            self.cursor_pos = self.value.len();
        } else if matches.len() > 1 {
            // Find common prefix
            let mut common = matches[0].clone();
            for m in &matches[1..] {
                let shared: String = common
                    .chars()
                    .zip(m.chars())
                    .take_while(|(a, b)| a == b)
                    .map(|(a, _)| a)
                    .collect();
                common = shared;
            }
            if common.len() > prefix.len() {
                self.value = format!("{}{}", dir, common);
                self.cursor_pos = self.value.len();
            }
        }

        self.dir_cursor = 0;
        self.dir_scroll = 0;
        self.update_dir_listing();
    }

    fn expand_path(&self, path: &str) -> String {
        crate::app::expand_tilde(path)
    }

    fn max_visible_entries(&self) -> usize {
        // Reserve lines for: border, title, input, separator, help
        let available = self.height as usize;
        available.saturating_sub(5).max(3)
    }
}