1use std::cell::RefCell;
4use std::collections::HashSet;
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7use std::sync::Arc;
8
9use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle};
10use ailloli_ui_fs::{
11 DirectoryLoadState, FileEntry, FileError, FileKind, FileMetadata,
12 FileTreeNodeId as RetainedFileTreeNodeId, FileTreeStore as RetainedFileTreeStore, FileUri,
13};
14use ailloli_ui_fs_local::{LocalFileProvider, LocalFileTreeSourceFactory};
15use ailloli_ui_fs_runtime::{FileTreeEnqueueOutcome, FileTreeRuntime, FileTreeWorkerResponse};
16use ailloli_ui_runtime::app::UiServiceRegistration;
17use ailloli_ui_runtime::component::{Binding, ComponentNode, Context, IntoView, View};
18use ailloli_ui_runtime::input::EventCtx;
19
20use crate::layout::layout_ext::finish_view_sized;
21
22use super::explorer::{FileExplorer, FileExplorerAction, FileExplorerSize, FileExplorerStyle};
23use super::model::FileExplorerNode;
24use super::tree::{
25 dedupe_file_uris, error_placeholder, file_uri_ancestors_between, large_directory_placeholder,
26 load_file_tree, loading_placeholder, should_include_file_entry, FileTreeLoadMode,
27 FileTreeOptions,
28};
29
30type ActionHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileExplorerAction)>;
32type UriHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileUri)>;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum LocalFileExplorerLoadingMode {
46 LazyReload,
48 LazyCached,
50 ControlledDepth(usize),
52 FullLoad,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum LocalFileExplorerCacheMode {
66 ReloadOnToggle,
68 CacheLoadedDirectories,
70 LoadOnceSnapshot,
72}
73
74pub struct LocalFileExplorer<A = ()> {
88 pub(crate) layout: LayoutStyle,
90 pub(crate) flex_item: FlexItemStyle,
92 root_path: PathBuf,
94 selected_path: Option<PathBuf>,
96 default_expanded_paths: Vec<PathBuf>,
98 options: FileTreeOptions,
100 loading_mode: LocalFileExplorerLoadingMode,
102 cache_mode: LocalFileExplorerCacheMode,
104 virtualized: bool,
106 scrollable: bool,
108 async_loading: bool,
110 disabled: Binding<bool>,
112 style: FileExplorerStyle,
114 on_action: Option<ActionHandler<A>>,
116 on_select: Option<UriHandler<A>>,
118 on_open: Option<UriHandler<A>>,
120}
121
122crate::impl_layout_builders!(LocalFileExplorer);
123
124impl<A: 'static> LocalFileExplorer<A> {
125 pub fn new(root_path: impl Into<PathBuf>) -> Self {
139 Self {
140 layout: LayoutStyle::default(),
141 flex_item: FlexItemStyle::default(),
142 root_path: make_absolute(root_path.into()),
143 selected_path: None,
144 default_expanded_paths: Vec::new(),
145 options: FileTreeOptions::default(),
146 loading_mode: LocalFileExplorerLoadingMode::LazyCached,
147 cache_mode: LocalFileExplorerCacheMode::CacheLoadedDirectories,
148 virtualized: true,
149 scrollable: true,
150 async_loading: false,
151 disabled: Binding::Static(false),
152 style: FileExplorerStyle::default(),
153 on_action: None,
154 on_select: None,
155 on_open: None,
156 }
157 }
158
159 pub fn selected_path(mut self, path: impl Into<PathBuf>) -> Self {
172 self.selected_path = Some(make_path_absolute_to_root(&self.root_path, path.into()));
173 self
174 }
175
176 pub fn default_expanded_path(mut self, path: impl Into<PathBuf>) -> Self {
189 let path = make_path_absolute_to_root(&self.root_path, path.into());
190 if !self.default_expanded_paths.iter().any(|item| item == &path) {
191 self.default_expanded_paths.push(path);
192 }
193 self
194 }
195
196 pub fn default_expanded_paths(mut self, paths: impl IntoIterator<Item = PathBuf>) -> Self {
208 self.default_expanded_paths.clear();
209 for path in paths {
210 self = self.default_expanded_path(path);
211 }
212 self
213 }
214
215 pub fn file_tree_options(mut self, options: FileTreeOptions) -> Self {
230 self.options = options;
231 self
232 }
233
234 pub fn load_mode(mut self, load_mode: FileTreeLoadMode) -> Self {
249 self.options.load_mode = load_mode;
250 self.loading_mode = match load_mode {
251 FileTreeLoadMode::Lazy => LocalFileExplorerLoadingMode::LazyReload,
252 FileTreeLoadMode::Controlled { preload_depth } => {
253 LocalFileExplorerLoadingMode::ControlledDepth(preload_depth)
254 }
255 FileTreeLoadMode::Full => LocalFileExplorerLoadingMode::FullLoad,
256 };
257 self
258 }
259
260 pub fn lazy_loading(self) -> Self {
270 self.load_mode(FileTreeLoadMode::Lazy)
271 }
272
273 pub fn lazy_cached(mut self) -> Self {
285 self.loading_mode = LocalFileExplorerLoadingMode::LazyCached;
286 self.cache_mode = LocalFileExplorerCacheMode::CacheLoadedDirectories;
287 self.options.load_mode = FileTreeLoadMode::Lazy;
288 self
289 }
290
291 pub fn controlled_loading(self, preload_depth: usize) -> Self {
303 self.load_mode(FileTreeLoadMode::Controlled { preload_depth })
304 }
305
306 pub fn full_load(self) -> Self {
316 self.load_mode(FileTreeLoadMode::Full)
317 }
318
319 pub fn local_loading_mode(mut self, mode: LocalFileExplorerLoadingMode) -> Self {
334 self.loading_mode = mode;
335 self.options.load_mode = match mode {
336 LocalFileExplorerLoadingMode::LazyReload | LocalFileExplorerLoadingMode::LazyCached => {
337 FileTreeLoadMode::Lazy
338 }
339 LocalFileExplorerLoadingMode::ControlledDepth(preload_depth) => {
340 FileTreeLoadMode::Controlled { preload_depth }
341 }
342 LocalFileExplorerLoadingMode::FullLoad => FileTreeLoadMode::Full,
343 };
344 self
345 }
346
347 pub fn cache_mode(mut self, mode: LocalFileExplorerCacheMode) -> Self {
358 self.cache_mode = mode;
359 self
360 }
361
362 pub fn virtualized(mut self, virtualized: bool) -> Self {
375 self.virtualized = virtualized;
376 self
377 }
378
379 pub fn scrollable(mut self, scrollable: bool) -> Self {
391 self.scrollable = scrollable;
392 self
393 }
394
395 pub fn async_loading(mut self, async_loading: bool) -> Self {
408 self.async_loading = async_loading;
409 self
410 }
411
412 pub fn include_hidden(mut self, include_hidden: bool) -> Self {
425 self.options.include_hidden = include_hidden;
426 self
427 }
428
429 pub fn max_depth(mut self, max_depth: usize) -> Self {
442 self.options.max_depth = max_depth;
443 self
444 }
445
446 pub fn reveal_selected(mut self, reveal_selected: bool) -> Self {
456 self.options.reveal_selected = reveal_selected;
457 self
458 }
459
460 pub fn exclude_defaults(mut self, exclude_defaults: bool) -> Self {
472 self.options.exclude_defaults = exclude_defaults;
473 self
474 }
475
476 pub fn max_entries_per_directory(mut self, max_entries: usize) -> Self {
491 self.options.max_entries_per_directory = Some(max_entries);
492 self
493 }
494
495 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
509 self.disabled = disabled.into();
510 self
511 }
512
513 pub fn file_style(mut self, style: FileExplorerStyle) -> Self {
523 self.style = style;
524 self
525 }
526
527 pub fn file_size(mut self, size: FileExplorerSize) -> Self {
540 self.style = FileExplorerStyle::from_theme(ailloli_ui_core::Theme::default(), size);
541 self
542 }
543
544 pub fn on_action(mut self, f: impl Fn(FileExplorerAction) -> A + 'static) -> Self {
557 self.on_action = Some(Rc::new(move |ctx, action| ctx.dispatch(f(action))));
558 self
559 }
560
561 pub fn on_action_ctx(
571 mut self,
572 f: impl Fn(&mut EventCtx<A>, FileExplorerAction) + 'static,
573 ) -> Self {
574 self.on_action = Some(Rc::new(f));
575 self
576 }
577
578 pub fn on_select(mut self, f: impl Fn(FileUri) -> A + 'static) -> Self {
590 self.on_select = Some(Rc::new(move |ctx, uri| ctx.dispatch(f(uri))));
591 self
592 }
593
594 pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>, FileUri) + 'static) -> Self {
604 self.on_select = Some(Rc::new(f));
605 self
606 }
607
608 pub fn on_open(mut self, f: impl Fn(FileUri) -> A + 'static) -> Self {
622 self.on_open = Some(Rc::new(move |ctx, uri| ctx.dispatch(f(uri))));
623 self
624 }
625
626 pub fn on_open_ctx(mut self, f: impl Fn(&mut EventCtx<A>, FileUri) + 'static) -> Self {
636 self.on_open = Some(Rc::new(f));
637 self
638 }
639}
640
641impl<A: 'static> IntoView<A> for LocalFileExplorer<A> {
643 fn into_view(self) -> View<A> {
644 finish_view_sized(
645 View::component(LocalFileExplorerComponent {
646 layout: self.layout,
647 root_path: self.root_path,
648 selected_path: self.selected_path,
649 default_expanded_paths: self.default_expanded_paths,
650 options: self.options,
651 loading_mode: self.loading_mode,
652 cache_mode: self.cache_mode,
653 virtualized: self.virtualized,
654 scrollable: self.scrollable,
655 async_loading: self.async_loading,
656 disabled: self.disabled,
657 style: self.style,
658 on_action: self.on_action,
659 on_select: self.on_select,
660 on_open: self.on_open,
661 }),
662 self.flex_item,
663 LayoutSizeHint::from_layout(self.layout),
664 )
665 }
666}
667
668struct LocalFileExplorerComponent<A> {
670 layout: LayoutStyle,
672 root_path: PathBuf,
674 selected_path: Option<PathBuf>,
676 default_expanded_paths: Vec<PathBuf>,
678 options: FileTreeOptions,
680 loading_mode: LocalFileExplorerLoadingMode,
682 cache_mode: LocalFileExplorerCacheMode,
684 virtualized: bool,
686 scrollable: bool,
688 async_loading: bool,
690 disabled: Binding<bool>,
692 style: FileExplorerStyle,
694 on_action: Option<ActionHandler<A>>,
696 on_select: Option<UriHandler<A>>,
698 on_open: Option<UriHandler<A>>,
700}
701
702impl<A: 'static> ComponentNode<A> for LocalFileExplorerComponent<A> {
704 fn build(&self, context: &mut Context<A>) -> View<A> {
705 let selected = self
706 .selected_path
707 .as_ref()
708 .and_then(|path| FileUri::local(path).ok());
709 let Ok(root_uri) = local_uri_or_error(&self.root_path) else {
710 return FileExplorer::new(error_nodes("Invalid local root"))
711 .disabled(self.disabled.clone())
712 .file_style(self.style.clone())
713 .scrollable(self.scrollable)
714 .into_view();
715 };
716 let default_expanded =
717 default_expanded_uris(&root_uri, &self.default_expanded_paths, selected.as_ref());
718 let root_for_state = root_uri.clone();
719 let selected_for_state = selected.clone();
720 let runtime_signal = context.signal_with(|| {
721 Rc::new(RefCell::new(LocalFileExplorerRuntime::<A>::new(
722 root_for_state,
723 selected_for_state,
724 self.options,
725 self.loading_mode,
726 self.cache_mode,
727 )))
728 });
729 let runtime = runtime_signal.read();
730 {
731 let mut runtime_state = runtime.borrow_mut();
732 if runtime_state.root_uri() != &root_uri {
733 *runtime_state = LocalFileExplorerRuntime::new(
734 root_uri.clone(),
735 selected.clone(),
736 self.options,
737 self.loading_mode,
738 self.cache_mode,
739 );
740 }
741 runtime_state.configure(
742 selected.clone(),
743 self.options,
744 self.loading_mode,
745 self.cache_mode,
746 &default_expanded,
747 );
748 runtime_state.ensure_service(&runtime, context);
749 runtime_state.service_pending();
750 }
751 let _async_loading_compat = self.async_loading;
752 let nodes = runtime.borrow().nodes();
753 let expanded = runtime.borrow().expanded_uris();
754
755 let runtime_for_toggle = runtime.clone();
756 let mut explorer = FileExplorer::new(nodes)
757 .default_expanded_many(expanded)
758 .disabled(self.disabled.clone())
759 .file_style(self.style.clone())
760 .virtualized(self.virtualized)
761 .scrollable(self.scrollable)
762 .on_toggle_ctx(move |ctx, uri, open| {
763 runtime_for_toggle.borrow_mut().toggle(&uri, open);
764 ctx.request_build();
765 });
766 explorer.layout = self.layout;
767
768 if let Some(selected) = selected {
769 explorer = explorer.selected(selected);
770 }
771
772 if let Some(on_action) = &self.on_action {
773 let on_action = on_action.clone();
774 explorer = explorer.on_action_ctx(move |ctx, action| on_action(ctx, action));
775 }
776 if let Some(on_select) = &self.on_select {
777 let on_select = on_select.clone();
778 explorer = explorer.on_select_ctx(move |ctx, uri| on_select(ctx, uri));
779 }
780 if let Some(on_open) = &self.on_open {
781 let on_open = on_open.clone();
782 explorer = explorer.on_open_ctx(move |ctx, uri| on_open(ctx, uri));
783 }
784
785 explorer.into_view()
786 }
787}
788
789struct LocalFileExplorerRuntime<A> {
791 store: RetainedFileTreeStore,
793 worker: Option<FileTreeRuntime>,
795 options: FileTreeOptions,
797 loading_mode: LocalFileExplorerLoadingMode,
799 cache_mode: LocalFileExplorerCacheMode,
801 selected: Option<FileUri>,
803 desired_expanded: Vec<FileUri>,
805 truncated: std::collections::HashSet<RetainedFileTreeNodeId>,
807 watched: HashSet<RetainedFileTreeNodeId>,
809 error: Option<String>,
811 bootstrapped: bool,
813 service_callback: Option<Rc<dyn Fn() -> bool>>,
815 service_registration: Option<UiServiceRegistration<A>>,
817}
818
819impl<A: 'static> LocalFileExplorerRuntime<A> {
820 fn new(
822 root: FileUri,
823 selected: Option<FileUri>,
824 options: FileTreeOptions,
825 loading_mode: LocalFileExplorerLoadingMode,
826 cache_mode: LocalFileExplorerCacheMode,
827 ) -> Self {
828 let store = RetainedFileTreeStore::new(root, FileMetadata::new(FileKind::Directory))
829 .expect("valid local tree root");
830 let worker = FileTreeRuntime::spawn(Arc::new(LocalFileTreeSourceFactory::default())).ok();
831 Self {
832 store,
833 worker,
834 options,
835 loading_mode,
836 cache_mode,
837 selected,
838 desired_expanded: Vec::new(),
839 truncated: std::collections::HashSet::new(),
840 watched: HashSet::new(),
841 error: None,
842 bootstrapped: false,
843 service_callback: None,
844 service_registration: None,
845 }
846 }
847
848 fn root_uri(&self) -> &FileUri {
850 self.store
851 .node(self.store.root())
852 .expect("root exists")
853 .uri()
854 }
855
856 fn configure(
858 &mut self,
859 selected: Option<FileUri>,
860 options: FileTreeOptions,
861 loading_mode: LocalFileExplorerLoadingMode,
862 cache_mode: LocalFileExplorerCacheMode,
863 desired_expanded: &[FileUri],
864 ) {
865 self.selected = selected;
866 self.options = options;
867 self.loading_mode = loading_mode;
868 self.cache_mode = cache_mode;
869 self.desired_expanded.clear();
870 self.desired_expanded.extend_from_slice(desired_expanded);
871 if !self.bootstrapped {
872 self.bootstrapped = true;
873 let root = self.store.root();
874 let _ = self.store.set_expanded(root, true);
875 self.watch(root, true);
876 self.request_load(root, false);
877 }
878 self.drive_load_policy();
879 }
880
881 fn ensure_service(&mut self, owner: &Rc<RefCell<Self>>, context: &Context<A>) {
883 if let (Some(worker), Some(wake)) = (self.worker.as_ref(), context.runtime().ui_wake()) {
884 if let Err(error) = worker.install_wake(wake) {
885 self.error.get_or_insert_with(|| error.to_string());
886 }
887 }
888 if self.service_registration.is_some() {
889 return;
890 }
891 let owner = Rc::downgrade(owner);
892 let callback: Rc<dyn Fn() -> bool> = Rc::new(move || {
893 let Some(owner) = owner.upgrade() else {
894 return false;
895 };
896 let changed = owner.borrow_mut().service_pending();
897 changed
898 });
899 let registration = context.register_ui_service(&callback);
900 self.service_callback = Some(callback);
901 self.service_registration = Some(registration);
902 }
903
904 fn service_pending(&mut self) -> bool {
909 let Some(worker) = self.worker.as_mut() else {
910 return false;
911 };
912 let drain = match worker.drain() {
913 Ok(drain) => drain,
914 Err(error) => {
915 self.error = Some(error.to_string());
916 return true;
917 }
918 };
919 let mut changed = false;
920 for response in drain.responses {
921 match response {
922 FileTreeWorkerResponse::Directory { request, result } => {
923 let result =
924 result.map(|entries| self.filter_entries(request.node_id(), entries));
925 match self.store.apply_directory_result(&request, result) {
926 Ok(delta) => changed |= !delta.changes().is_empty(),
927 Err(error) => self.error = Some(error.to_string()),
928 }
929 }
930 FileTreeWorkerResponse::Watch { events } => match events {
931 Ok(events) => {
932 for event in events {
933 match self.store.apply_watch_event(&event) {
934 Ok(delta) => changed |= !delta.changes().is_empty(),
935 Err(error) => self.error = Some(error.to_string()),
936 }
937 }
938 }
939 Err(error) => self.error = Some(error.to_string()),
940 },
941 FileTreeWorkerResponse::WatchConfigured {
942 result: Err(error), ..
943 } => self.error = Some(error.to_string()),
944 FileTreeWorkerResponse::WatchConfigured { result: Ok(()), .. } => {}
945 _ => {}
946 }
947 }
948 changed | self.drive_load_policy()
949 }
950
951 fn filter_entries(
953 &mut self,
954 parent: RetainedFileTreeNodeId,
955 entries: Vec<(FileEntry, Option<ailloli_ui_fs::FileIdentity>)>,
956 ) -> Vec<(FileEntry, Option<ailloli_ui_fs::FileIdentity>)> {
957 let mut entries = entries
958 .into_iter()
959 .filter(|(entry, _)| {
960 should_include_file_entry(entry, self.selected.as_ref(), self.options)
961 })
962 .collect::<Vec<_>>();
963 entries.sort_by(|(a, _), (b, _)| {
964 (!a.metadata.is_directory_like())
965 .cmp(&(!b.metadata.is_directory_like()))
966 .then_with(|| {
967 a.name
968 .to_ascii_lowercase()
969 .cmp(&b.name.to_ascii_lowercase())
970 })
971 .then_with(|| a.name.cmp(&b.name))
972 });
973 let truncated = self
974 .options
975 .max_entries_per_directory
976 .is_some_and(|limit| entries.len() > limit);
977 if let Some(limit) = self.options.max_entries_per_directory {
978 entries.truncate(limit);
979 }
980 if truncated {
981 self.truncated.insert(parent);
982 } else {
983 self.truncated.remove(&parent);
984 }
985 entries
986 }
987
988 fn drive_load_policy(&mut self) -> bool {
990 let mut changed = false;
991 for uri in self.desired_expanded.clone() {
992 if let Some(id) = self.store.node_id(&uri) {
993 if let Ok(delta) = self.store.set_expanded(id, true) {
994 changed |= !delta.changes().is_empty();
995 }
996 self.watch(id, true);
997 changed |= self.request_load(id, false);
998 }
999 }
1000 let depth_limit = match self.loading_mode {
1001 LocalFileExplorerLoadingMode::LazyReload | LocalFileExplorerLoadingMode::LazyCached => {
1002 None
1003 }
1004 LocalFileExplorerLoadingMode::ControlledDepth(depth) => Some(depth),
1005 LocalFileExplorerLoadingMode::FullLoad => Some(self.options.max_depth),
1006 };
1007 if let Some(depth_limit) = depth_limit {
1008 let mut pending = vec![(self.store.root(), 0_usize)];
1009 let mut candidates = Vec::new();
1010 while let Some((id, depth)) = pending.pop() {
1011 let Some(node) = self.store.node(id) else {
1012 continue;
1013 };
1014 pending.extend(
1015 node.children()
1016 .iter()
1017 .copied()
1018 .map(|child| (child, depth + 1)),
1019 );
1020 if depth <= depth_limit && node.metadata().is_directory_like() {
1021 candidates.push(id);
1022 }
1023 }
1024 for id in candidates {
1025 changed |= self.request_load(id, false);
1026 }
1027 }
1028 changed
1029 }
1030
1031 fn request_load(&mut self, id: RetainedFileTreeNodeId, force: bool) -> bool {
1033 let should_load = self
1034 .store
1035 .node(id)
1036 .is_some_and(|node| match node.directory_state() {
1037 DirectoryLoadState::Loading { .. } => false,
1038 DirectoryLoadState::Loaded { .. } => force,
1039 DirectoryLoadState::Unloaded
1040 | DirectoryLoadState::Stale
1041 | DirectoryLoadState::Error(_) => true,
1042 _ => false,
1043 });
1044 if !should_load {
1045 return false;
1046 }
1047 let Ok((request, delta)) = self.store.begin_directory_load(id) else {
1048 return false;
1049 };
1050 let Some(worker) = self.worker.as_ref() else {
1051 let _ = self.store.apply_directory_result(
1052 &request,
1053 Err(FileError::Other("filesystem worker unavailable".into())),
1054 );
1055 return true;
1056 };
1057 match worker.request_directory(request.clone()) {
1058 Ok(FileTreeEnqueueOutcome::Enqueued | FileTreeEnqueueOutcome::Coalesced) => {
1059 !delta.changes().is_empty()
1060 }
1061 Err(error) => {
1062 let _ = self
1063 .store
1064 .apply_directory_result(&request, Err(FileError::Other(error.to_string())));
1065 true
1066 }
1067 }
1068 }
1069
1070 fn watch(&mut self, id: RetainedFileTreeNodeId, enabled: bool) {
1072 if enabled && !self.watched.insert(id) {
1073 return;
1074 }
1075 if !enabled && !self.watched.remove(&id) {
1076 return;
1077 }
1078 let Some(uri) = self.store.node(id).map(|node| node.uri().clone()) else {
1079 return;
1080 };
1081 let Some(worker) = self.worker.as_ref() else {
1082 return;
1083 };
1084 let result = if enabled {
1085 worker.watch_directory(uri)
1086 } else {
1087 worker.unwatch_directory(uri)
1088 };
1089 if let Err(error) = result {
1090 self.error = Some(error.to_string());
1091 }
1092 }
1093
1094 fn toggle(&mut self, uri: &FileUri, open: bool) {
1096 let Some(id) = self.store.node_id(uri) else {
1097 return;
1098 };
1099 let _ = self.store.set_expanded(id, open);
1100 self.watch(id, open);
1101 if open && self.cache_mode != LocalFileExplorerCacheMode::LoadOnceSnapshot {
1102 let force = self.cache_mode == LocalFileExplorerCacheMode::ReloadOnToggle
1103 || self.loading_mode == LocalFileExplorerLoadingMode::LazyReload;
1104 self.request_load(id, force);
1105 }
1106 }
1107
1108 fn nodes(&self) -> Vec<FileExplorerNode> {
1110 let mut nodes = vec![self.node_snapshot(self.store.root())];
1111 if let Some(error) = &self.error {
1112 nodes[0]
1113 .children
1114 .push(error_placeholder(self.root_uri(), error));
1115 }
1116 nodes
1117 }
1118
1119 fn node_snapshot(&self, id: RetainedFileTreeNodeId) -> FileExplorerNode {
1121 let node = self.store.node(id).expect("snapshot node exists");
1122 let mut entry = FileEntry::new(node.uri().clone(), node.metadata().clone());
1123 if entry.name.is_empty() {
1124 entry.name = node.uri().path().to_string();
1125 }
1126 let mut snapshot = FileExplorerNode::new(entry);
1127 snapshot.disabled = matches!(node.directory_state(), DirectoryLoadState::Loading { .. });
1128 snapshot.children = node
1129 .children()
1130 .iter()
1131 .map(|child| self.node_snapshot(*child))
1132 .collect();
1133 if node.is_expanded() {
1134 match node.directory_state() {
1135 DirectoryLoadState::Loading { .. } => {
1136 snapshot.children.push(loading_placeholder(node.uri()))
1137 }
1138 DirectoryLoadState::Error(error) => snapshot
1139 .children
1140 .push(error_placeholder(node.uri(), error.to_string())),
1141 _ => {}
1142 }
1143 if self.truncated.contains(&id) {
1144 snapshot
1145 .children
1146 .push(large_directory_placeholder(node.uri()));
1147 }
1148 }
1149 snapshot
1150 }
1151
1152 fn expanded_uris(&self) -> Vec<FileUri> {
1154 let mut expanded = Vec::new();
1155 let mut pending = vec![self.store.root()];
1156 while let Some(id) = pending.pop() {
1157 let Some(node) = self.store.node(id) else {
1158 continue;
1159 };
1160 if node.is_expanded() {
1161 expanded.push(node.uri().clone());
1162 }
1163 pending.extend(node.children().iter().copied());
1164 }
1165 expanded
1166 }
1167}
1168
1169pub fn local_file_tree_nodes(
1192 root_path: impl Into<PathBuf>,
1193 expanded_paths: impl IntoIterator<Item = PathBuf>,
1194 selected_path: Option<PathBuf>,
1195 options: FileTreeOptions,
1196) -> Result<Vec<FileExplorerNode>, FileError> {
1197 let root_path = make_absolute(root_path.into());
1198 let root = FileUri::local(&root_path)?;
1199 let selected = selected_path
1200 .map(|path| FileUri::local(make_path_absolute_to_root(&root_path, path)))
1201 .transpose()?;
1202 let expanded_paths = expanded_paths
1203 .into_iter()
1204 .map(|path| make_path_absolute_to_root(&root_path, path))
1205 .collect::<Vec<_>>();
1206 let expanded = default_expanded_uris(&root, &expanded_paths, selected.as_ref());
1207 load_file_tree(
1208 &LocalFileProvider::new(),
1209 &root,
1210 &expanded,
1211 selected.as_ref(),
1212 options,
1213 )
1214}
1215
1216fn error_nodes(message: impl Into<String>) -> Vec<FileExplorerNode> {
1218 vec![FileExplorerNode::named(
1219 FileUri::new("file", None::<String>, "/ailloli_ui-file-error").expect("error uri"),
1220 message,
1221 FileKind::Other,
1222 )
1223 .disabled(true)]
1224}
1225
1226fn local_uri_or_error(path: &Path) -> Result<FileUri, FileError> {
1233 FileUri::local(path)
1234}
1235
1236fn default_expanded_uris(
1238 root: &FileUri,
1239 expanded_paths: &[PathBuf],
1240 selected: Option<&FileUri>,
1241) -> Vec<FileUri> {
1242 let mut uris = vec![root.clone()];
1243 for path in expanded_paths {
1244 if let Ok(uri) = FileUri::local(make_absolute(path.clone())) {
1245 uris.extend(file_uri_ancestors_between(root, &uri));
1246 }
1247 }
1248 if let Some(selected) = selected {
1249 uris.extend(file_uri_ancestors_between(root, selected));
1250 if let Some(parent) = super::tree::file_uri_parent(selected) {
1251 uris.extend(file_uri_ancestors_between(root, &parent));
1252 }
1253 }
1254 dedupe_file_uris(uris)
1255}
1256
1257fn make_path_absolute_to_root(root: &Path, path: PathBuf) -> PathBuf {
1259 if path.is_absolute() {
1260 path
1261 } else {
1262 root.join(path)
1263 }
1264}
1265
1266fn make_absolute(path: PathBuf) -> PathBuf {
1268 if path.is_absolute() {
1269 path
1270 } else {
1271 std::env::current_dir()
1272 .unwrap_or_else(|_| Path::new("/").to_path_buf())
1273 .join(path)
1274 }
1275}
1276
1277#[cfg(test)]
1278mod tests {
1280 use std::fs;
1281 use std::time::{SystemTime, UNIX_EPOCH};
1282
1283 use super::*;
1284
1285 struct TempDir {
1287 path: PathBuf,
1288 }
1289
1290 impl TempDir {
1291 fn new(name: &str) -> Self {
1293 let nanos = SystemTime::now()
1294 .duration_since(UNIX_EPOCH)
1295 .expect("time")
1296 .as_nanos();
1297 let path = std::env::temp_dir().join(format!(
1298 "ailloli_ui_widgets_local_file_explorer_{name}_{}_{}",
1299 std::process::id(),
1300 nanos
1301 ));
1302 fs::create_dir_all(&path).expect("temp dir");
1303 Self { path }
1304 }
1305 }
1306
1307 impl Drop for TempDir {
1308 fn drop(&mut self) {
1309 let _ = fs::remove_dir_all(&self.path);
1310 }
1311 }
1312
1313 #[test]
1314 fn local_file_tree_nodes_builds_from_directory_without_manual_nodes() {
1315 let temp = TempDir::new("tree");
1316 fs::create_dir_all(temp.path.join("src/view")).expect("dirs");
1317 fs::write(temp.path.join("src/view/left.rs"), b"left").expect("left");
1318 fs::write(temp.path.join("Cargo.toml"), b"cargo").expect("cargo");
1319
1320 let nodes = local_file_tree_nodes(
1321 &temp.path,
1322 [PathBuf::from("src/view")],
1323 Some(PathBuf::from("src/view/left.rs")),
1324 FileTreeOptions::default(),
1325 )
1326 .expect("nodes");
1327
1328 assert_eq!(
1329 nodes[0].name(),
1330 temp.path.file_name().unwrap().to_string_lossy()
1331 );
1332 let src = nodes[0]
1333 .children
1334 .iter()
1335 .find(|node| node.name() == "src")
1336 .expect("src");
1337 let view = src
1338 .children
1339 .iter()
1340 .find(|node| node.name() == "view")
1341 .expect("view");
1342 assert!(view.children.iter().any(|node| node.name() == "left.rs"));
1343 }
1344
1345 #[test]
1346 fn local_file_tree_nodes_support_lazy_controlled_and_full_modes() {
1347 let temp = TempDir::new("load_modes");
1348 fs::create_dir_all(temp.path.join("src/nested")).expect("src dirs");
1349 fs::create_dir_all(temp.path.join("sample_app")).expect("sample directory");
1350 fs::write(temp.path.join("src/lib.rs"), b"lib").expect("lib");
1351 fs::write(temp.path.join("src/nested/mod.rs"), b"mod").expect("mod");
1352 fs::write(temp.path.join("sample_app/main.rs"), b"main").expect("main");
1353
1354 let lazy = local_file_tree_nodes(
1355 &temp.path,
1356 std::iter::empty::<PathBuf>(),
1357 None,
1358 FileTreeOptions {
1359 load_mode: FileTreeLoadMode::Lazy,
1360 ..FileTreeOptions::default()
1361 },
1362 )
1363 .expect("lazy nodes");
1364 assert!(
1365 child(&lazy[0], "src").children.is_empty(),
1366 "lazy only loads the root without expansion"
1367 );
1368
1369 let controlled = local_file_tree_nodes(
1370 &temp.path,
1371 std::iter::empty::<PathBuf>(),
1372 None,
1373 FileTreeOptions {
1374 load_mode: FileTreeLoadMode::Controlled { preload_depth: 1 },
1375 ..FileTreeOptions::default()
1376 },
1377 )
1378 .expect("controlled nodes");
1379 let src = child(&controlled[0], "src");
1380 assert!(src.children.iter().any(|node| node.name() == "lib.rs"));
1381 assert!(
1382 child(src, "nested").children.is_empty(),
1383 "controlled depth 1 keeps deeper folders lazy"
1384 );
1385 assert!(child(&controlled[0], "sample_app")
1386 .children
1387 .iter()
1388 .any(|node| node.name() == "main.rs"));
1389
1390 let full = local_file_tree_nodes(
1391 &temp.path,
1392 std::iter::empty::<PathBuf>(),
1393 None,
1394 FileTreeOptions {
1395 load_mode: FileTreeLoadMode::Full,
1396 ..FileTreeOptions::default()
1397 },
1398 )
1399 .expect("full nodes");
1400 assert!(child(child(&full[0], "src"), "nested")
1401 .children
1402 .iter()
1403 .any(|node| node.name() == "mod.rs"));
1404 }
1405
1406 fn child<'a>(node: &'a FileExplorerNode, name: &str) -> &'a FileExplorerNode {
1408 node.children
1409 .iter()
1410 .find(|child| child.name() == name)
1411 .unwrap_or_else(|| panic!("missing child {name} in {}", node.name()))
1412 }
1413}