fc_ui/capabilities/navigation/
file_tree.rs1use crate::capabilities::foundation::theme::use_theme;
2use crate::capabilities::primitives::icon::Icon;
3use crate::capabilities::primitives::icon_source::IconSource;
4use gpui::{prelude::FluentBuilder as _, *};
5use std::collections::HashSet;
6use std::path::PathBuf;
7use std::sync::Arc;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum FileNodeKind {
11 File,
12 Directory,
13 Symlink,
14}
15
16#[derive(Clone, Debug)]
17pub struct FileNode {
18 pub path: PathBuf,
19 pub name: String,
20 pub kind: FileNodeKind,
21 pub children: Vec<FileNode>,
22 pub size: Option<u64>,
23 pub modified: Option<String>,
24 pub is_hidden: bool,
25 pub has_unloaded_children: bool,
26}
27
28impl FileNode {
29 pub fn file(path: impl Into<PathBuf>) -> Self {
30 let path = path.into();
31 let name = path
32 .file_name()
33 .map(|n| n.to_string_lossy().to_string())
34 .unwrap_or_default();
35 Self {
36 path,
37 name,
38 kind: FileNodeKind::File,
39 children: Vec::new(),
40 size: None,
41 modified: None,
42 is_hidden: false,
43 has_unloaded_children: false,
44 }
45 }
46
47 pub fn directory(path: impl Into<PathBuf>) -> Self {
48 let path = path.into();
49 let name = path
50 .file_name()
51 .map(|n| n.to_string_lossy().to_string())
52 .unwrap_or_default();
53 Self {
54 path,
55 name,
56 kind: FileNodeKind::Directory,
57 children: Vec::new(),
58 size: None,
59 modified: None,
60 is_hidden: false,
61 has_unloaded_children: false,
62 }
63 }
64
65 pub fn with_name(mut self, name: impl Into<String>) -> Self {
66 self.name = name.into();
67 self
68 }
69
70 pub fn with_children(mut self, children: Vec<FileNode>) -> Self {
71 self.children = children;
72 self
73 }
74
75 pub fn with_size(mut self, size: u64) -> Self {
76 self.size = Some(size);
77 self
78 }
79
80 pub fn with_modified(mut self, modified: impl Into<String>) -> Self {
81 self.modified = Some(modified.into());
82 self
83 }
84
85 pub fn hidden(mut self, is_hidden: bool) -> Self {
86 self.is_hidden = is_hidden;
87 self
88 }
89
90 pub fn with_unloaded_children(mut self, has_unloaded: bool) -> Self {
91 self.has_unloaded_children = has_unloaded;
92 self
93 }
94
95 pub fn is_directory(&self) -> bool {
96 self.kind == FileNodeKind::Directory
97 }
98
99 pub fn extension(&self) -> Option<&str> {
100 self.path.extension().and_then(|e| e.to_str())
101 }
102
103 pub fn file_icon(&self, is_expanded: bool) -> IconSource {
104 match self.kind {
105 FileNodeKind::Directory => {
106 if is_expanded {
107 IconSource::Named("folder-open".into())
108 } else {
109 IconSource::Named("folder".into())
110 }
111 }
112 FileNodeKind::Symlink => IconSource::Named("link".into()),
113 FileNodeKind::File => match self.extension() {
114 Some("json") | Some("yaml") | Some("yml") | Some("toml") | Some("xml") => {
115 IconSource::Named("file-json".into())
116 }
117 Some("md") | Some("txt") | Some("doc") | Some("docx") | Some("pdf") => {
118 IconSource::Named("file-text".into())
119 }
120 Some("sh") | Some("bash") | Some("zsh") => IconSource::Named("hash".into()),
121 Some("png") | Some("jpg") | Some("jpeg") | Some("gif") | Some("svg")
122 | Some("ico") | Some("webp") => IconSource::Named("image".into()),
123 Some("mp3") | Some("wav") | Some("ogg") | Some("flac") => {
124 IconSource::Named("music".into())
125 }
126 Some("mp4") | Some("mov") | Some("avi") | Some("webm") => {
127 IconSource::Named("video".into())
128 }
129 Some("zip") | Some("tar") | Some("gz") | Some("rar") | Some("7z") => {
130 IconSource::Named("archive".into())
131 }
132 _ => IconSource::Named("file-code".into()),
133 },
134 }
135 }
136
137 pub fn file_icon_color(&self, theme: &crate::capabilities::foundation::theme::Theme) -> Hsla {
138 match self.kind {
139 FileNodeKind::Directory => rgb(0x60a5fa).into(),
140 FileNodeKind::Symlink => theme.tokens.muted_foreground,
141 FileNodeKind::File => match self.extension() {
142 Some("json") | Some("yaml") | Some("yml") | Some("toml") | Some("xml") => {
143 rgb(0xfbbf24).into()
144 }
145 Some("md") | Some("txt") | Some("doc") | Some("docx") | Some("pdf") => {
146 rgb(0xa78bfa).into()
147 }
148 Some("sh") | Some("bash") | Some("zsh") => rgb(0x4ade80).into(),
149 Some("png") | Some("jpg") | Some("jpeg") | Some("gif") | Some("svg")
150 | Some("ico") | Some("webp") => rgb(0x22c55e).into(),
151 Some("mp3") | Some("wav") | Some("ogg") | Some("flac") => rgb(0xf472b6).into(),
152 Some("mp4") | Some("mov") | Some("avi") | Some("webm") => rgb(0xf472b6).into(),
153 Some("zip") | Some("tar") | Some("gz") | Some("rar") | Some("7z") => {
154 rgb(0xfbbf24).into()
155 }
156 _ => rgb(0x9ca3af).into(),
157 },
158 }
159 }
160}
161
162#[derive(Clone)]
163struct FlatFileNode {
164 node: FileNode,
165 level: usize,
166}
167
168fn sort_file_nodes(nodes: &mut [FileNode]) {
169 nodes.sort_by(|a, b| match (a.is_directory(), b.is_directory()) {
170 (true, false) => std::cmp::Ordering::Less,
171 (false, true) => std::cmp::Ordering::Greater,
172 _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
173 });
174 for node in nodes.iter_mut() {
175 if !node.children.is_empty() {
176 sort_file_nodes(&mut node.children);
177 }
178 }
179}
180
181fn flatten_file_tree(
182 nodes: &[FileNode],
183 expanded_paths: &HashSet<PathBuf>,
184 level: usize,
185 show_hidden: bool,
186) -> Vec<FlatFileNode> {
187 let mut flat = Vec::new();
188
189 for node in nodes {
190 if node.is_hidden && !show_hidden {
191 continue;
192 }
193
194 flat.push(FlatFileNode {
195 node: node.clone(),
196 level,
197 });
198
199 let has_children = !node.children.is_empty() || node.has_unloaded_children;
200 if has_children && expanded_paths.contains(&node.path) {
201 let children =
202 flatten_file_tree(&node.children, expanded_paths, level + 1, show_hidden);
203 flat.extend(children);
204 }
205 }
206
207 flat
208}
209
210fn format_size(size: u64) -> String {
211 const KB: u64 = 1024;
212 const MB: u64 = KB * 1024;
213 const GB: u64 = MB * 1024;
214
215 if size >= GB {
216 format!("{:.1} GB", size as f64 / GB as f64)
217 } else if size >= MB {
218 format!("{:.1} MB", size as f64 / MB as f64)
219 } else if size >= KB {
220 format!("{:.1} KB", size as f64 / KB as f64)
221 } else {
222 format!("{} B", size)
223 }
224}
225
226const ROW_HEIGHT: f32 = 28.0;
227
228#[derive(IntoElement)]
229pub struct FileTree {
230 nodes: Vec<FileNode>,
231 selected_path: Option<PathBuf>,
232 expanded_paths: Vec<PathBuf>,
233 show_hidden: bool,
234 show_file_size: bool,
235 on_select: Option<Arc<dyn Fn(&PathBuf, &mut Window, &mut App) + Send + Sync>>,
236 on_open: Option<Arc<dyn Fn(&PathBuf, &mut Window, &mut App) + Send + Sync>>,
237 on_toggle: Option<Arc<dyn Fn(&PathBuf, bool, &mut Window, &mut App) + Send + Sync>>,
238 on_context_menu:
239 Option<Arc<dyn Fn(&PathBuf, Point<Pixels>, &mut Window, &mut App) + Send + Sync>>,
240 style: StyleRefinement,
241}
242
243impl FileTree {
244 pub fn new() -> Self {
245 Self {
246 nodes: Vec::new(),
247 selected_path: None,
248 expanded_paths: Vec::new(),
249 show_hidden: false,
250 show_file_size: false,
251 on_select: None,
252 on_open: None,
253 on_toggle: None,
254 on_context_menu: None,
255 style: StyleRefinement::default(),
256 }
257 }
258
259 pub fn nodes(mut self, mut nodes: Vec<FileNode>) -> Self {
260 sort_file_nodes(&mut nodes);
261 self.nodes = nodes;
262 self
263 }
264
265 pub fn selected_path(mut self, path: impl Into<PathBuf>) -> Self {
266 self.selected_path = Some(path.into());
267 self
268 }
269
270 pub fn expanded_paths(mut self, paths: Vec<PathBuf>) -> Self {
271 self.expanded_paths = paths;
272 self
273 }
274
275 pub fn show_hidden(mut self, show: bool) -> Self {
276 self.show_hidden = show;
277 self
278 }
279
280 pub fn show_file_size(mut self, show: bool) -> Self {
281 self.show_file_size = show;
282 self
283 }
284
285 pub fn on_select<F>(mut self, handler: F) -> Self
286 where
287 F: Fn(&PathBuf, &mut Window, &mut App) + Send + Sync + 'static,
288 {
289 self.on_select = Some(Arc::new(handler));
290 self
291 }
292
293 pub fn on_open<F>(mut self, handler: F) -> Self
294 where
295 F: Fn(&PathBuf, &mut Window, &mut App) + Send + Sync + 'static,
296 {
297 self.on_open = Some(Arc::new(handler));
298 self
299 }
300
301 pub fn on_toggle<F>(mut self, handler: F) -> Self
302 where
303 F: Fn(&PathBuf, bool, &mut Window, &mut App) + Send + Sync + 'static,
304 {
305 self.on_toggle = Some(Arc::new(handler));
306 self
307 }
308
309 pub fn on_context_menu<F>(mut self, handler: F) -> Self
310 where
311 F: Fn(&PathBuf, Point<Pixels>, &mut Window, &mut App) + Send + Sync + 'static,
312 {
313 self.on_context_menu = Some(Arc::new(handler));
314 self
315 }
316}
317
318impl Default for FileTree {
319 fn default() -> Self {
320 Self::new()
321 }
322}
323
324impl Styled for FileTree {
325 fn style(&mut self) -> &mut StyleRefinement {
326 &mut self.style
327 }
328}
329
330impl RenderOnce for FileTree {
331 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
332 let theme = use_theme(cx);
333 let user_style = self.style;
334
335 let expanded_set: HashSet<PathBuf> = self.expanded_paths.into_iter().collect();
336 let flat_nodes = flatten_file_tree(&self.nodes, &expanded_set, 0, self.show_hidden);
337
338 let selected_path = self.selected_path;
339 let on_select = self.on_select;
340 let on_open = self.on_open;
341 let on_toggle = self.on_toggle;
342 let on_context_menu = self.on_context_menu;
343 let show_file_size = self.show_file_size;
344
345 div()
346 .flex()
347 .flex_col()
348 .w_full()
349 .bg(gpui::transparent_black())
350 .map(|mut this| {
351 this.style().refine(&user_style);
352 this
353 })
354 .children(flat_nodes.into_iter().map(|flat_node| {
355 let is_selected = selected_path.as_ref() == Some(&flat_node.node.path);
356 let is_expanded = expanded_set.contains(&flat_node.node.path);
357 let has_children =
358 !flat_node.node.children.is_empty() || flat_node.node.has_unloaded_children;
359 let indent = px((flat_node.level as f32) * 16.0);
360 let node = flat_node.node;
361 let path = node.path.clone();
362
363 let icon_color = node.file_icon_color(&theme);
364 let node_icon = node.file_icon(is_expanded);
365
366 div()
367 .id(SharedString::from(path.to_string_lossy().to_string()))
368 .w_full()
369 .h(px(ROW_HEIGHT))
370 .flex()
371 .items_center()
372 .mx(px(8.0))
373 .px(px(8.0))
374 .pl(indent + px(8.0))
375 .rounded(px(8.0))
376 .cursor_pointer()
377 .bg(if is_selected {
378 theme.tokens.accent
379 } else {
380 gpui::transparent_black()
381 })
382 .text_color(if is_selected {
383 theme.tokens.accent_foreground
384 } else if node.is_hidden {
385 theme.tokens.muted_foreground
386 } else {
387 theme.tokens.foreground
388 })
389 .when(!is_selected, |d| {
390 d.hover(|s| s.bg(theme.tokens.accent.opacity(0.5)))
391 })
392 .on_click({
393 let path = path.clone();
394 let on_select = on_select.clone();
395 let on_toggle = on_toggle.clone();
396 let on_open = on_open.clone();
397 let is_dir = node.is_directory();
398
399 move |event, window, cx| {
400 if let Some(ref handler) = on_select {
401 handler(&path, window, cx);
402 }
403
404 if is_dir {
405 if let Some(ref handler) = on_toggle {
406 handler(&path, !is_expanded, window, cx);
407 }
408 } else if event.click_count() == 2 {
409 if let Some(ref handler) = on_open {
410 handler(&path, window, cx);
411 }
412 }
413 }
414 })
415 .on_mouse_down(MouseButton::Right, {
416 let path = path.clone();
417 let on_context_menu = on_context_menu.clone();
418
419 move |event, window, cx| {
420 if let Some(ref handler) = on_context_menu {
421 handler(&path, event.position, window, cx);
422 }
423 }
424 })
425 .child(
426 div()
427 .flex()
428 .items_center()
429 .gap(px(6.0))
430 .flex_1()
431 .child(
432 div()
433 .w(px(16.0))
434 .h(px(16.0))
435 .flex()
436 .items_center()
437 .justify_center()
438 .when(has_children, |d| {
439 d.child(
440 Icon::new(if is_expanded {
441 "chevron-down"
442 } else {
443 "chevron-right"
444 })
445 .size(px(12.0))
446 .color(theme.tokens.muted_foreground),
447 )
448 }),
449 )
450 .child(Icon::new(node_icon).size(px(16.0)).color(if is_selected {
451 theme.tokens.accent_foreground
452 } else {
453 icon_color
454 }))
455 .child(
456 div()
457 .flex_1()
458 .text_size(px(13.0))
459 .font_family(theme.tokens.font_family.clone())
460 .when(node.is_hidden, |d| d.opacity(0.6))
461 .child(node.name.clone()),
462 )
463 .when(
464 show_file_size && node.size.is_some() && !node.is_directory(),
465 |d| {
466 d.child(
467 div()
468 .text_size(px(11.0))
469 .text_color(theme.tokens.muted_foreground)
470 .child(format_size(node.size.unwrap())),
471 )
472 },
473 ),
474 )
475 }))
476 }
477}