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
use crate::app::App;
use crate::fs::discovery::FileEntry;
use crate::fs::git_status::GitFileStatus;
use ratatui::{
Frame,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, List, ListItem, ListState},
};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
/// Persistent UI state for the file-tree panel.
#[derive(Debug, Default)]
pub struct FileTreeState {
/// Hierarchical tree of discovered markdown files and directories.
pub entries: Vec<FileEntry>,
/// Flattened, visible list derived from `entries` and `expanded`.
pub flat_items: Vec<FlatItem>,
/// Ratatui list selection state (tracks scroll and highlighted index).
pub list_state: ListState,
/// Set of directory paths that are currently expanded.
pub expanded: HashSet<PathBuf>,
/// Git working-tree status, keyed by absolute path.
///
/// Populated on startup and refreshed on `FilesChanged`. Absent entries are
/// treated as clean. Directories are pre-populated with `Modified` when any
/// descendant has changes (see `fs::git_status::collect`).
pub git_status: HashMap<PathBuf, GitFileStatus>,
}
/// A single visible row in the flattened file-tree list.
#[derive(Debug, Clone)]
pub struct FlatItem {
/// Absolute path to the file or directory.
pub path: PathBuf,
/// Display name (file-name component only).
pub name: String,
/// `true` if this entry represents a directory.
pub is_dir: bool,
/// Visual indent level (0 = root children).
pub depth: usize,
}
impl FileTreeState {
/// Replace the entry tree and rebuild the flat list, preserving selection.
pub fn rebuild(&mut self, entries: Vec<FileEntry>) {
self.entries = entries;
self.flatten_visible();
if !self.flat_items.is_empty() && self.list_state.selected().is_none() {
self.list_state.select(Some(0));
}
}
/// Rebuild `flat_items` from the current `entries` and `expanded` set.
///
/// Uses `std::mem::take` to avoid cloning the entire entry tree: the
/// entries are temporarily moved out, flattened via a standalone function,
/// then moved back — no allocation beyond the flat list itself.
pub fn flatten_visible(&mut self) {
self.flat_items.clear();
// Take entries out to satisfy the borrow checker (we need &self.expanded
// and &mut self.flat_items simultaneously).
let entries = std::mem::take(&mut self.entries);
flatten_entries(&entries, &self.expanded, 0, &mut self.flat_items);
self.entries = entries;
}
/// Return the path of the currently selected item, if any.
pub fn selected_path(&self) -> Option<&std::path::Path> {
let idx = self.list_state.selected()?;
self.flat_items.get(idx).map(|item| item.path.as_path())
}
/// Return a reference to the currently selected flat item, if any.
pub fn selected_item(&self) -> Option<&FlatItem> {
let idx = self.list_state.selected()?;
self.flat_items.get(idx)
}
/// Move the cursor up one row, clamping at the top.
pub fn move_up(&mut self) {
if self.flat_items.is_empty() {
return;
}
let i = match self.list_state.selected() {
Some(i) if i > 0 => i - 1,
_ => 0,
};
self.list_state.select(Some(i));
}
/// Move the cursor down one row, clamping at the bottom.
pub fn move_down(&mut self) {
if self.flat_items.is_empty() {
return;
}
let i = match self.list_state.selected() {
Some(i) if i < self.flat_items.len() - 1 => i + 1,
Some(i) => i,
None => 0,
};
self.list_state.select(Some(i));
}
/// Toggle the expansion state of the selected directory, then re-flatten.
pub fn toggle_expand(&mut self) {
if let Some(item) = self.selected_item().cloned()
&& item.is_dir
{
if self.expanded.contains(&item.path) {
self.expanded.remove(&item.path);
} else {
self.expanded.insert(item.path);
}
self.flatten_visible();
}
}
/// Move the cursor to the first item.
pub fn go_first(&mut self) {
if !self.flat_items.is_empty() {
self.list_state.select(Some(0));
}
}
/// Move the cursor to the last item.
pub fn go_last(&mut self) {
if !self.flat_items.is_empty() {
self.list_state.select(Some(self.flat_items.len() - 1));
}
}
/// Expand every ancestor directory of `path`, rebuild the flat item list,
/// and select the row for `path` if present.
///
/// Safe to call on paths that are outside the tree root — the walk simply
/// finds no matching ancestors and no matching row, making this a no-op.
/// Intended to be invoked whenever a file is opened programmatically (search
/// result, link pick, session restore, etc.) so the tree is always aligned
/// with the viewer.
pub fn reveal_path(&mut self, path: &Path) {
// Walk up the directory hierarchy, inserting each ancestor into the
// expanded set. We stop when `parent()` returns `None` (hit filesystem
// root) or when the parent equals the path itself (POSIX root "/" is its
// own parent — guards against infinite loops).
let mut cursor = path.parent();
while let Some(parent) = cursor {
self.expanded.insert(parent.to_path_buf());
let next = parent.parent();
// POSIX root "/" has itself as its own parent; stop to avoid a loop.
if next == Some(parent) {
break;
}
cursor = next;
}
self.flatten_visible();
if let Some(idx) = self.flat_items.iter().position(|item| item.path == path) {
self.list_state.select(Some(idx));
}
}
}
/// Recursively walk `entries` and append visible rows to `out`.
///
/// A directory's children are only appended when the directory's path is
/// present in `expanded`. This is a free function (not a method) so that
/// `entries` can be borrowed immutably while `out` is built mutably without
/// conflicting with the surrounding `FileTreeState` borrow.
fn flatten_entries(
entries: &[FileEntry],
expanded: &HashSet<PathBuf>,
depth: usize,
out: &mut Vec<FlatItem>,
) {
for entry in entries {
out.push(FlatItem {
path: entry.path.clone(),
name: entry.name.clone(),
is_dir: entry.is_dir,
depth,
});
if entry.is_dir && expanded.contains(&entry.path) {
flatten_entries(&entry.children, expanded, depth + 1, out);
}
}
}
/// Render the file-tree panel into `area`.
pub fn draw(f: &mut Frame, app: &mut App, area: Rect, focused: bool) {
let p = &app.palette;
let border_style = if focused {
p.border_focused_style()
} else {
p.border_style()
};
let block = Block::default()
.title(" Files ")
.title_style(p.title_style())
.borders(Borders::ALL)
.border_style(border_style)
.style(Style::default().bg(p.background));
let items: Vec<ListItem> = app
.tree
.flat_items
.iter()
.map(|item| {
let indent = " ".repeat(item.depth);
let (prefix, prefix_color) = if item.is_dir {
let marker = if app.tree.expanded.contains(&item.path) {
"▼ "
} else {
"▶ "
};
(marker, p.accent)
} else {
(" ", p.foreground)
};
let name_color: Color = match app.tree.git_status.get(&item.path) {
Some(GitFileStatus::New) => p.git_new,
Some(GitFileStatus::Modified) => p.git_modified,
None => {
if item.is_dir {
p.accent
} else {
p.foreground
}
}
};
let prefix_style = Style::default()
.fg(prefix_color)
.add_modifier(if item.is_dir {
Modifier::BOLD
} else {
Modifier::empty()
});
let name_style = Style::default()
.fg(name_color)
.add_modifier(if item.is_dir {
Modifier::BOLD
} else {
Modifier::empty()
});
let line = Line::from(vec![
Span::styled(format!("{indent}{prefix}"), prefix_style),
Span::styled(item.name.clone(), name_style),
]);
ListItem::new(line)
})
.collect();
let list = List::new(items)
.block(block)
.highlight_style(p.selected_style())
.highlight_symbol("│ ");
f.render_stateful_widget(list, area, &mut app.tree.list_state);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fs::discovery::FileEntry;
/// Build a small synthetic tree:
///
/// ```
/// deep/ (dir)
/// nested/ (dir)
/// file.md (file)
/// other.md (file)
/// ```
fn make_test_tree() -> (FileTreeState, PathBuf) {
let deep_nested_file = PathBuf::from("/root/deep/nested/file.md");
let deep = PathBuf::from("/root/deep");
let nested = PathBuf::from("/root/deep/nested");
let entries = vec![
FileEntry {
path: deep.clone(),
name: "deep".to_string(),
is_dir: true,
children: vec![FileEntry {
path: nested,
name: "nested".to_string(),
is_dir: true,
children: vec![FileEntry {
path: deep_nested_file.clone(),
name: "file.md".to_string(),
is_dir: false,
children: vec![],
}],
}],
},
FileEntry {
path: PathBuf::from("/root/other.md"),
name: "other.md".to_string(),
is_dir: false,
children: vec![],
},
];
let mut state = FileTreeState::default();
state.rebuild(entries);
(state, deep_nested_file)
}
/// `reveal_path` must expand all ancestor directories and select the target.
#[test]
fn reveal_path_expands_ancestors() {
let (mut state, target) = make_test_tree();
// Initially only the top-level items are visible (no dirs expanded).
let initial_len = state.flat_items.len();
assert_eq!(initial_len, 2, "only deep/ and other.md at root");
state.reveal_path(&target);
// Both ancestor directories must now be in the expanded set.
assert!(
state.expanded.contains(Path::new("/root/deep")),
"deep/ should be expanded"
);
assert!(
state.expanded.contains(Path::new("/root/deep/nested")),
"deep/nested/ should be expanded"
);
// The flat list must now contain all 4 entries.
assert_eq!(state.flat_items.len(), 4);
// The selection must point at the target file.
let selected = state.list_state.selected().expect("a row must be selected");
assert_eq!(state.flat_items[selected].path, target);
}
/// Calling `reveal_path` on a path not present in the tree must be a no-op.
#[test]
fn reveal_path_on_unknown_file_is_noop() {
let (mut state, _) = make_test_tree();
let before_len = state.flat_items.len();
let before_sel = state.list_state.selected();
state.reveal_path(Path::new("/nonexistent/path/file.md"));
// The flat list shape is unchanged (ancestors inserted into `expanded` but
// they don't match real tree nodes, so flatten produces the same output).
assert_eq!(state.flat_items.len(), before_len);
// Selection is unchanged because the file isn't in the list.
assert_eq!(state.list_state.selected(), before_sel);
}
/// Calling `reveal_path` twice with the same path is idempotent.
#[test]
fn reveal_path_idempotent() {
let (mut state, target) = make_test_tree();
state.reveal_path(&target);
let len_after_first = state.flat_items.len();
let sel_after_first = state.list_state.selected();
state.reveal_path(&target);
assert_eq!(state.flat_items.len(), len_after_first);
assert_eq!(state.list_state.selected(), sel_after_first);
}
}