gravityfile-tui 0.2.4

Terminal user interface for gravityfile
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
//! Directory tree widget.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, StatefulWidget, Widget};

use gravityfile_core::{FileNode, GitStatus, NodeKind};

use crate::app::state::{ClipboardMode, ClipboardState};
use crate::theme::Theme;
use crate::ui::{CompactSizeBar, format_size, truncate_to_width};

/// State for the tree view.
#[derive(Debug, Default, Clone)]
pub struct TreeState {
    /// Currently selected index in the flattened view.
    pub selected: usize,
    /// Scroll offset.
    pub offset: usize,
    /// Set of expanded directory paths.
    pub expanded: HashSet<PathBuf>,
    /// Current root path.
    #[allow(dead_code)]
    root_path: PathBuf,
}

impl TreeState {
    /// Create new tree state.
    pub fn new(root_path: PathBuf) -> Self {
        let mut expanded = HashSet::new();
        // Expand root by default
        expanded.insert(root_path.clone());
        Self {
            selected: 0,
            offset: 0,
            expanded,
            root_path,
        }
    }

    /// Toggle expansion of a path.
    pub fn toggle_expand(&mut self, path: &Path) {
        if self.expanded.contains(path) {
            self.expanded.remove(path);
        } else {
            self.expanded.insert(path.to_path_buf());
        }
    }

    /// Expand a path.
    pub fn expand(&mut self, path: &Path) {
        self.expanded.insert(path.to_path_buf());
    }

    /// Collapse a path.
    pub fn collapse(&mut self, path: &Path) {
        self.expanded.remove(path);
    }

    /// Check if a path is expanded.
    pub fn is_expanded(&self, path: &PathBuf) -> bool {
        self.expanded.contains(path)
    }

    /// Move selection up.
    pub fn move_up(&mut self, count: usize) {
        self.selected = self.selected.saturating_sub(count);
    }

    /// Move selection down.
    pub fn move_down(&mut self, count: usize, max: usize) {
        self.selected = (self.selected + count).min(max.saturating_sub(1));
    }

    /// Jump to top.
    pub fn jump_to_top(&mut self) {
        self.selected = 0;
    }

    /// Jump to bottom.
    pub fn jump_to_bottom(&mut self, max: usize) {
        self.selected = max.saturating_sub(1);
    }

    /// Ensure selected item is visible, adjusting offset if needed.
    pub fn ensure_visible(&mut self, viewport_height: usize) {
        if self.selected < self.offset {
            self.offset = self.selected;
        } else if self.selected >= self.offset + viewport_height {
            self.offset = self.selected - viewport_height + 1;
        }
    }
}

/// A flattened visible item in the tree.
#[derive(Debug, Clone)]
pub struct VisibleItem {
    pub path: PathBuf,
    pub node: VisibleNode,
    pub depth: usize,
    pub is_last_sibling: bool,
    pub parent_last_siblings: Vec<bool>,
}

/// Lightweight node info for display.
#[derive(Debug, Clone)]
pub struct VisibleNode {
    pub name: String,
    pub size: u64,
    pub kind: VisibleNodeKind,
    pub git_status: Option<GitStatus>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VisibleNodeKind {
    Directory { expanded: bool },
    File { executable: bool },
    Symlink { broken: bool },
    Other,
}

/// Tree view widget.
pub struct TreeView<'a> {
    root: &'a FileNode,
    root_path: &'a PathBuf,
    total_size: u64,
    theme: &'a Theme,
    marked: &'a HashSet<PathBuf>,
    clipboard: &'a ClipboardState,
    block: Option<Block<'a>>,
}

impl<'a> TreeView<'a> {
    /// Create a new tree view.
    pub fn new(
        root: &'a FileNode,
        root_path: &'a PathBuf,
        theme: &'a Theme,
        marked: &'a HashSet<PathBuf>,
        clipboard: &'a ClipboardState,
    ) -> Self {
        Self {
            root,
            root_path,
            total_size: root.size,
            theme,
            marked,
            clipboard,
            block: None,
        }
    }

    /// Set the block (border) for the widget.
    pub fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    /// Flatten tree to visible items based on expansion state.
    pub fn flatten(&self, state: &TreeState) -> Vec<VisibleItem> {
        let mut items = Vec::new();
        self.flatten_node(
            self.root,
            self.root_path.clone(),
            0,
            true,
            Vec::new(),
            state,
            &mut items,
        );
        items
    }

    /// Count visible items without allocating a Vec.
    /// Use this when only the count is needed (e.g. updating `cached_tree_len`).
    pub fn flatten_count(&self, state: &TreeState) -> usize {
        self.count_node(self.root, &self.root_path.clone(), state)
    }

    fn count_node(&self, node: &FileNode, path: &PathBuf, state: &TreeState) -> usize {
        let is_expanded = state.is_expanded(path);
        let mut count = 1; // this node itself
        if is_expanded && node.is_dir() {
            for child in &node.children {
                let child_path = path.join(&*child.name);
                count += self.count_node(child, &child_path, state);
            }
        }
        count
    }

    #[allow(clippy::too_many_arguments)]
    fn flatten_node(
        &self,
        node: &FileNode,
        path: PathBuf,
        depth: usize,
        is_last: bool,
        parent_last_siblings: Vec<bool>,
        state: &TreeState,
        items: &mut Vec<VisibleItem>,
    ) {
        let is_expanded = state.is_expanded(&path);

        let kind = match &node.kind {
            NodeKind::Directory { .. } => VisibleNodeKind::Directory {
                expanded: is_expanded,
            },
            NodeKind::File { executable } => VisibleNodeKind::File {
                executable: *executable,
            },
            NodeKind::Symlink { broken, .. } => VisibleNodeKind::Symlink { broken: *broken },
            NodeKind::Other => VisibleNodeKind::Other,
        };

        items.push(VisibleItem {
            path: path.clone(),
            node: VisibleNode {
                name: node.name.to_string(),
                size: node.size,
                kind,
                git_status: node.git_status,
            },
            depth,
            is_last_sibling: is_last,
            parent_last_siblings: parent_last_siblings.clone(),
        });

        // If directory is expanded, add children
        if is_expanded && node.is_dir() {
            let child_count = node.children.len();
            for (i, child) in node.children.iter().enumerate() {
                let child_path = path.join(&*child.name);
                let child_is_last = i == child_count - 1;
                let mut child_parent_lasts = parent_last_siblings.clone();
                child_parent_lasts.push(is_last);

                self.flatten_node(
                    child,
                    child_path,
                    depth + 1,
                    child_is_last,
                    child_parent_lasts,
                    state,
                    items,
                );
            }
        }
    }
}

impl StatefulWidget for TreeView<'_> {
    type State = TreeState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        // Handle block/border
        let inner_area = if let Some(block) = &self.block {
            let inner = block.inner(area);
            block.clone().render(area, buf);
            inner
        } else {
            area
        };

        if inner_area.height == 0 || inner_area.width == 0 {
            return;
        }

        let items = self.flatten(state);
        let viewport_height = inner_area.height as usize;

        // Ensure selected item is visible
        state.ensure_visible(viewport_height);

        // Calculate visible range
        let start = state.offset;
        let end = (start + viewport_height).min(items.len());

        // Size bar width
        let size_bar_width: u16 = 10;
        let size_text_width: u16 = 10;

        for (row_idx, item_idx) in (start..end).enumerate() {
            let item = &items[item_idx];
            let y = inner_area.y + row_idx as u16;
            let is_selected = item_idx == state.selected;
            let is_marked = self.marked.contains(&item.path);

            // Check if item is in clipboard
            let in_clipboard = self.clipboard.paths.contains(&item.path);
            let clipboard_mode = if in_clipboard {
                self.clipboard.mode
            } else {
                ClipboardMode::Empty
            };

            // Build tree prefix
            let mut prefix = String::new();
            for &parent_is_last in &item.parent_last_siblings {
                prefix.push_str(if parent_is_last { "  " } else { "│ " });
            }
            if item.depth > 0 {
                prefix.push_str(if item.is_last_sibling {
                    "└─"
                } else {
                    "├─"
                });
            }

            // Selection/clipboard indicator
            // Priority: marked > cut > copied > none
            let (checkbox, checkbox_style) = if is_marked {
                ("● ", Style::default().fg(self.theme.info))
            } else if clipboard_mode == ClipboardMode::Cut {
                ("✂ ", Style::default().fg(self.theme.warning))
            } else if clipboard_mode == ClipboardMode::Copy {
                ("⎘ ", Style::default().fg(self.theme.success))
            } else {
                ("  ", Style::default().fg(self.theme.muted))
            };
            let checkbox_width: u16 = 2;

            // Expand indicator
            let expand_indicator = match item.node.kind {
                VisibleNodeKind::Directory { expanded } => {
                    if expanded {
                        "▼ "
                    } else {
                        "▶ "
                    }
                }
                _ => "  ",
            };

            // Node style - clipboard items get special styling
            let base_style = match item.node.kind {
                VisibleNodeKind::Directory { .. } => self.theme.directory,
                VisibleNodeKind::File { executable: true } => self.theme.executable,
                VisibleNodeKind::File { executable: false } => self.theme.file,
                VisibleNodeKind::Symlink { broken: true } => {
                    self.theme.symlink.add_modifier(Modifier::DIM)
                }
                VisibleNodeKind::Symlink { broken: false } => self.theme.symlink,
                VisibleNodeKind::Other => self.theme.muted.into(),
            };

            // Apply clipboard styling (cut items are dimmed, copied items are italic)
            let base_style = if clipboard_mode == ClipboardMode::Cut {
                base_style.add_modifier(Modifier::DIM)
            } else if clipboard_mode == ClipboardMode::Copy {
                base_style.add_modifier(Modifier::ITALIC)
            } else {
                base_style
            };

            // Calculate available width for name
            let prefix_width = prefix.len() + checkbox_width as usize + expand_indicator.len();
            let available_for_name = inner_area
                .width
                .saturating_sub(prefix_width as u16)
                .saturating_sub(size_bar_width + 1)
                .saturating_sub(size_text_width + 1);

            // Truncate name if needed (Unicode-safe)
            let name = {
                use unicode_width::UnicodeWidthStr;
                let max = available_for_name as usize;
                if item.node.name.width() > max {
                    let truncated = truncate_to_width(&item.node.name, max.saturating_sub(1));
                    format!("{}…", truncated)
                } else {
                    item.node.name.clone()
                }
            };

            // Build line with checkbox
            let prefix_span = Span::styled(&prefix, self.theme.tree_lines);
            let checkbox_span = Span::styled(checkbox, checkbox_style);
            let expand_span = Span::styled(expand_indicator, Style::default().fg(self.theme.muted));
            let name_span = Span::styled(&name, base_style);

            // Git status indicator
            let (git_indicator, git_style) = match item.node.git_status {
                Some(status) if status.is_displayable() => {
                    let color = self.theme.git_status_color(status);
                    (
                        format!(" {}", status.indicator()),
                        Style::default().fg(color),
                    )
                }
                _ => (String::new(), Style::default()),
            };
            let git_span = Span::styled(&git_indicator, git_style);

            // Pad name to fill space (accounting for git indicator)
            // Use display width, not byte length, for correct Unicode padding
            let git_display_width = {
                use unicode_width::UnicodeWidthStr;
                git_indicator.width() as u16
            };
            let name_display_width = {
                use unicode_width::UnicodeWidthStr;
                name.width() as u16
            };
            let name_padding = " ".repeat(
                available_for_name
                    .saturating_sub(name_display_width)
                    .saturating_sub(git_display_width) as usize,
            );
            let padding_span = Span::raw(&name_padding);

            // Size text - show "..." for directories with unknown size (0 bytes)
            let size_text = if matches!(item.node.kind, VisibleNodeKind::Directory { .. })
                && item.node.size == 0
            {
                format!("{:>10}", "...")
            } else {
                format!("{:>10}", format_size(item.node.size))
            };
            let size_span = Span::styled(&size_text, Style::default().fg(self.theme.muted));

            let line = Line::from(vec![
                prefix_span,
                checkbox_span,
                expand_span,
                name_span,
                git_span,
                padding_span,
                Span::raw(" "),
                size_span,
            ]);

            // Apply selection style (cursor highlight)
            let line = if is_selected {
                line.style(self.theme.selected)
            } else if is_marked {
                // Marked but not selected - subtle highlight
                line.style(Style::default().add_modifier(Modifier::BOLD))
            } else {
                line
            };

            // Render line
            let line_area = Rect::new(
                inner_area.x,
                y,
                inner_area.width.saturating_sub(size_bar_width + 1),
                1,
            );
            Widget::render(line, line_area, buf);

            // Render size bar
            let ratio = if self.total_size > 0 {
                item.node.size as f64 / self.total_size as f64
            } else {
                0.0
            };

            let bar_area = Rect::new(
                inner_area.x + inner_area.width - size_bar_width,
                y,
                size_bar_width,
                1,
            );

            let bar = CompactSizeBar::new(ratio).style(self.theme.size_bar_style(ratio));

            if is_selected {
                // Dim the bar slightly for selected row
                Widget::render(bar, bar_area, buf);
            } else {
                Widget::render(bar, bar_area, buf);
            }
        }
    }
}

/// Get the selected item from a tree state and flattened items.
#[allow(dead_code)]
pub fn get_selected_item<'a>(
    state: &TreeState,
    items: &'a [VisibleItem],
) -> Option<&'a VisibleItem> {
    items.get(state.selected)
}