ailloli_ui_widgets/files/
local.rs

1//! Local-filesystem convenience wrapper around the provider-neutral explorer.
2
3use 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
30/// Shared retained callback for high-level explorer actions.
31type ActionHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileExplorerAction)>;
32/// Shared retained callback for a selected/opened URI.
33type UriHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileUri)>;
34
35/// Local runtime directory-request strategy.
36///
37/// # Examples
38///
39/// ```
40/// use ailloli_ui_widgets::files::LocalFileExplorerLoadingMode;
41/// assert_ne!(LocalFileExplorerLoadingMode::LazyReload, LocalFileExplorerLoadingMode::LazyCached);
42/// assert_eq!(LocalFileExplorerLoadingMode::ControlledDepth(2), LocalFileExplorerLoadingMode::ControlledDepth(2));
43/// ```
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum LocalFileExplorerLoadingMode {
46    /// Loads on demand and forces a fresh read each time a directory opens.
47    LazyReload,
48    /// Loads on demand and reuses already loaded directory state.
49    LazyCached,
50    /// Proactively loads directory nodes through the inclusive zero-based depth.
51    ControlledDepth(usize),
52    /// Proactively loads through [`FileTreeOptions::max_depth`].
53    FullLoad,
54}
55
56/// Cache behavior applied when a user toggles a local directory.
57///
58/// # Examples
59///
60/// ```
61/// use ailloli_ui_widgets::files::LocalFileExplorerCacheMode;
62/// assert_ne!(LocalFileExplorerCacheMode::ReloadOnToggle, LocalFileExplorerCacheMode::LoadOnceSnapshot);
63/// ```
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum LocalFileExplorerCacheMode {
66    /// Forces a provider request on every open transition.
67    ReloadOnToggle,
68    /// Reuses clean loaded directories and watches opened directories.
69    CacheLoadedDirectories,
70    /// Never starts a toggle-driven request after initial policy loading.
71    LoadOnceSnapshot,
72}
73
74/// File explorer that resolves a native root and owns a background local worker.
75///
76/// Paths may be absolute or relative to the process working directory/root. The
77/// default uses lazy cached loading, virtualization, scrolling, retained watcher
78/// updates, and enabled interaction. `A` is the application action type.
79///
80/// # Examples
81///
82/// ```
83/// use ailloli_ui_widgets::files::LocalFileExplorer;
84/// let explorer = LocalFileExplorer::<()>::new(".");
85/// let _ = explorer;
86/// ```
87pub struct LocalFileExplorer<A = ()> {
88    /// Standard logical-pixel size and position constraints.
89    pub(crate) layout: LayoutStyle,
90    /// Standard flex-parent participation settings.
91    pub(crate) flex_item: FlexItemStyle,
92    /// Native filesystem root exposed by this explorer.
93    root_path: PathBuf,
94    /// Optional initially selected native path.
95    selected_path: Option<PathBuf>,
96    /// Native directory paths requested open at bootstrap.
97    default_expanded_paths: Vec<PathBuf>,
98    /// Depth, node-limit, and hidden-entry projection policy.
99    options: FileTreeOptions,
100    /// Lazy or controlled/full directory loading policy.
101    loading_mode: LocalFileExplorerLoadingMode,
102    /// Retention/eviction policy for collapsed directory contents.
103    cache_mode: LocalFileExplorerCacheMode,
104    /// Whether visible rows are bounded to the propagated viewport.
105    virtualized: bool,
106    /// Whether the tree is wrapped in a vertical scroll viewport.
107    scrollable: bool,
108    /// Whether filesystem requests run through the background worker.
109    async_loading: bool,
110    /// Reactive interaction-disable flag.
111    disabled: Binding<bool>,
112    /// Tree row colors and logical-pixel geometry.
113    style: FileExplorerStyle,
114    /// Optional callback receiving semantic explorer actions.
115    on_action: Option<ActionHandler<A>>,
116    /// Optional callback receiving selected canonical URIs.
117    on_select: Option<UriHandler<A>>,
118    /// Optional callback receiving activated/opened canonical URIs.
119    on_open: Option<UriHandler<A>>,
120}
121
122crate::impl_layout_builders!(LocalFileExplorer);
123
124impl<A: 'static> LocalFileExplorer<A> {
125    /// Creates a local explorer rooted at an absolute working-directory path.
126    ///
127    /// Relative paths are joined to the current directory, falling back to `/`
128    /// only if the current directory cannot be queried. The path is not
129    /// canonicalized and need not exist until the component begins loading.
130    ///
131    /// # Examples
132    ///
133    /// ```
134    /// use ailloli_ui_widgets::files::LocalFileExplorer;
135    /// let explorer = LocalFileExplorer::<()>::new("src");
136    /// let _ = explorer;
137    /// ```
138    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    /// Sets the selected path used for row selection and ancestor reveal.
160    ///
161    /// A relative path is joined to the explorer root; an absolute path is kept
162    /// verbatim. The path is not canonicalized or required to exist.
163    ///
164    /// # Examples
165    ///
166    /// ```
167    /// use ailloli_ui_widgets::files::LocalFileExplorer;
168    /// let explorer = LocalFileExplorer::<()>::new(".").selected_path("src/lib.rs");
169    /// let _ = explorer;
170    /// ```
171    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    /// Appends one initially expanded path if not already present.
177    ///
178    /// Relative resolution matches [`Self::selected_path`]. On build, every
179    /// root-to-path ancestor is also expanded; paths outside the root add none.
180    ///
181    /// # Examples
182    ///
183    /// ```
184    /// use ailloli_ui_widgets::files::LocalFileExplorer;
185    /// let explorer = LocalFileExplorer::<()>::new(".").default_expanded_path("src");
186    /// let _ = explorer;
187    /// ```
188    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    /// Replaces initial expansion paths, deduplicating while preserving order.
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// use std::path::PathBuf;
202    /// use ailloli_ui_widgets::files::LocalFileExplorer;
203    /// let explorer = LocalFileExplorer::<()>::new(".")
204    ///     .default_expanded_paths([PathBuf::from("src"), PathBuf::from("tests")]);
205    /// let _ = explorer;
206    /// ```
207    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    /// Replaces the complete provider-neutral filtering/loading policy snapshot.
216    ///
217    /// This does not resynchronize [`LocalFileExplorerLoadingMode`] from
218    /// `options.load_mode`; call [`Self::load_mode`] or [`Self::local_loading_mode`]
219    /// afterward when both must agree.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use ailloli_ui_widgets::files::{FileTreeOptions, LocalFileExplorer};
225    /// let options = FileTreeOptions { include_hidden: true, ..FileTreeOptions::default() };
226    /// let explorer = LocalFileExplorer::<()>::new(".").file_tree_options(options);
227    /// let _ = explorer;
228    /// ```
229    pub fn file_tree_options(mut self, options: FileTreeOptions) -> Self {
230        self.options = options;
231        self
232    }
233
234    /// Sets provider-neutral load mode and maps it to a local runtime mode.
235    ///
236    /// `Lazy` maps to [`LocalFileExplorerLoadingMode::LazyReload`], not the
237    /// builder's default lazy-cached behavior. This method does not change
238    /// [`LocalFileExplorerCacheMode`].
239    ///
240    /// # Examples
241    ///
242    /// ```
243    /// use ailloli_ui_widgets::files::{FileTreeLoadMode, LocalFileExplorer};
244    /// let explorer = LocalFileExplorer::<()>::new(".")
245    ///     .load_mode(FileTreeLoadMode::Controlled { preload_depth: 2 });
246    /// let _ = explorer;
247    /// ```
248    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    /// Selects lazy reload-on-open loading via [`Self::load_mode`].
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// use ailloli_ui_widgets::files::LocalFileExplorer;
266    /// let explorer = LocalFileExplorer::<()>::new(".").lazy_loading();
267    /// let _ = explorer;
268    /// ```
269    pub fn lazy_loading(self) -> Self {
270        self.load_mode(FileTreeLoadMode::Lazy)
271    }
272
273    /// Selects lazy loading that reuses loaded directory state.
274    ///
275    /// This synchronizes local mode, cache mode, and provider-neutral mode.
276    ///
277    /// # Examples
278    ///
279    /// ```
280    /// use ailloli_ui_widgets::files::LocalFileExplorer;
281    /// let explorer = LocalFileExplorer::<()>::new(".").lazy_cached();
282    /// let _ = explorer;
283    /// ```
284    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    /// Proactively loads through the inclusive directory `preload_depth`.
292    ///
293    /// Depth zero includes the root request but not its child directories.
294    ///
295    /// # Examples
296    ///
297    /// ```
298    /// use ailloli_ui_widgets::files::LocalFileExplorer;
299    /// let explorer = LocalFileExplorer::<()>::new(".").controlled_loading(1);
300    /// let _ = explorer;
301    /// ```
302    pub fn controlled_loading(self, preload_depth: usize) -> Self {
303        self.load_mode(FileTreeLoadMode::Controlled { preload_depth })
304    }
305
306    /// Proactively loads directories through the configured maximum depth.
307    ///
308    /// # Examples
309    ///
310    /// ```
311    /// use ailloli_ui_widgets::files::LocalFileExplorer;
312    /// let explorer = LocalFileExplorer::<()>::new(".").max_depth(4).full_load();
313    /// let _ = explorer;
314    /// ```
315    pub fn full_load(self) -> Self {
316        self.load_mode(FileTreeLoadMode::Full)
317    }
318
319    /// Sets the local strategy and synchronizes provider-neutral load mode.
320    ///
321    /// Both lazy variants map to [`FileTreeLoadMode::Lazy`]. Cache mode remains
322    /// independent, so use [`Self::cache_mode`] when a specific toggle policy is
323    /// required.
324    ///
325    /// # Examples
326    ///
327    /// ```
328    /// use ailloli_ui_widgets::files::{LocalFileExplorer, LocalFileExplorerLoadingMode};
329    /// let explorer = LocalFileExplorer::<()>::new(".")
330    ///     .local_loading_mode(LocalFileExplorerLoadingMode::FullLoad);
331    /// let _ = explorer;
332    /// ```
333    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    /// Sets toggle-driven reload/cache behavior independently of load depth.
348    ///
349    /// # Examples
350    ///
351    /// ```
352    /// use ailloli_ui_widgets::files::{LocalFileExplorer, LocalFileExplorerCacheMode};
353    /// let explorer = LocalFileExplorer::<()>::new(".")
354    ///     .cache_mode(LocalFileExplorerCacheMode::LoadOnceSnapshot);
355    /// let _ = explorer;
356    /// ```
357    pub fn cache_mode(mut self, mode: LocalFileExplorerCacheMode) -> Self {
358        self.cache_mode = mode;
359        self
360    }
361
362    /// Enables or disables visible-row virtualization in the inner explorer.
363    ///
364    /// Virtualization is enabled by default and changes rendering cost, not the
365    /// retained filesystem tree or callback semantics.
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// use ailloli_ui_widgets::files::LocalFileExplorer;
371    /// let explorer = LocalFileExplorer::<()>::new(".").virtualized(false);
372    /// let _ = explorer;
373    /// ```
374    pub fn virtualized(mut self, virtualized: bool) -> Self {
375        self.virtualized = virtualized;
376        self
377    }
378
379    /// Enables or disables the inner explorer's scroll viewport.
380    ///
381    /// Disabling scrolling does not disable virtualization automatically.
382    ///
383    /// # Examples
384    ///
385    /// ```
386    /// use ailloli_ui_widgets::files::LocalFileExplorer;
387    /// let explorer = LocalFileExplorer::<()>::new(".").scrollable(false);
388    /// let _ = explorer;
389    /// ```
390    pub fn scrollable(mut self, scrollable: bool) -> Self {
391        self.scrollable = scrollable;
392        self
393    }
394
395    /// Retains the legacy asynchronous-loading preference.
396    ///
397    /// The current retained local implementation always uses its background
398    /// [`FileTreeRuntime`]; this compatibility flag has no behavioral effect.
399    ///
400    /// # Examples
401    ///
402    /// ```
403    /// use ailloli_ui_widgets::files::LocalFileExplorer;
404    /// let explorer = LocalFileExplorer::<()>::new(".").async_loading(true);
405    /// let _ = explorer;
406    /// ```
407    pub fn async_loading(mut self, async_loading: bool) -> Self {
408        self.async_loading = async_loading;
409        self
410    }
411
412    /// Includes dot-prefixed entries when true.
413    ///
414    /// A selected hidden entry and its ancestors remain visible when
415    /// [`Self::reveal_selected`] is enabled, even when this is false.
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// use ailloli_ui_widgets::files::LocalFileExplorer;
421    /// let explorer = LocalFileExplorer::<()>::new(".").include_hidden(true);
422    /// let _ = explorer;
423    /// ```
424    pub fn include_hidden(mut self, include_hidden: bool) -> Self {
425        self.options.include_hidden = include_hidden;
426        self
427    }
428
429    /// Sets the hard recursion/preload depth; root is depth zero.
430    ///
431    /// Zero permits loading the root listing but not descending into child
432    /// directories in the synchronous snapshot helper.
433    ///
434    /// # Examples
435    ///
436    /// ```
437    /// use ailloli_ui_widgets::files::LocalFileExplorer;
438    /// let explorer = LocalFileExplorer::<()>::new(".").max_depth(3);
439    /// let _ = explorer;
440    /// ```
441    pub fn max_depth(mut self, max_depth: usize) -> Self {
442        self.options.max_depth = max_depth;
443        self
444    }
445
446    /// Controls whether selected ancestors bypass filters and load lazily.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// use ailloli_ui_widgets::files::LocalFileExplorer;
452    /// let explorer = LocalFileExplorer::<()>::new(".").reveal_selected(false);
453    /// let _ = explorer;
454    /// ```
455    pub fn reveal_selected(mut self, reveal_selected: bool) -> Self {
456        self.options.reveal_selected = reveal_selected;
457        self
458    }
459
460    /// Excludes the fixed common heavy/generated directory set when true.
461    ///
462    /// Selected ancestors still survive when reveal-selected is enabled.
463    ///
464    /// # Examples
465    ///
466    /// ```
467    /// use ailloli_ui_widgets::files::LocalFileExplorer;
468    /// let explorer = LocalFileExplorer::<()>::new(".").exclude_defaults(true);
469    /// let _ = explorer;
470    /// ```
471    pub fn exclude_defaults(mut self, exclude_defaults: bool) -> Self {
472        self.options.exclude_defaults = exclude_defaults;
473        self
474    }
475
476    /// Sets a per-directory retained entry cap, including zero.
477    ///
478    /// The retained local runtime truncates whenever this is `Some` and adds a
479    /// placeholder. The synchronous [`local_file_tree_nodes`] helper additionally
480    /// follows [`FileTreeOptions::large_directory_policy`]. Replace the complete
481    /// options with `None` to clear an earlier cap.
482    ///
483    /// # Examples
484    ///
485    /// ```
486    /// use ailloli_ui_widgets::files::LocalFileExplorer;
487    /// let explorer = LocalFileExplorer::<()>::new(".").max_entries_per_directory(500);
488    /// let _ = explorer;
489    /// ```
490    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    /// Binds whether inner explorer interaction is disabled.
496    ///
497    /// Disabled state affects row actions but does not stop background loads,
498    /// watches, or model refreshes.
499    ///
500    /// # Examples
501    ///
502    /// ```
503    /// use ailloli_ui_runtime::component::State;
504    /// use ailloli_ui_widgets::files::LocalFileExplorer;
505    /// let explorer = LocalFileExplorer::<()>::new(".").disabled(State::new(true));
506    /// let _ = explorer;
507    /// ```
508    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
509        self.disabled = disabled.into();
510        self
511    }
512
513    /// Replaces the complete inner explorer style.
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// use ailloli_ui_widgets::files::{FileExplorerStyle, LocalFileExplorer};
519    /// let explorer = LocalFileExplorer::<()>::new(".").file_style(FileExplorerStyle::default());
520    /// let _ = explorer;
521    /// ```
522    pub fn file_style(mut self, style: FileExplorerStyle) -> Self {
523        self.style = style;
524        self
525    }
526
527    /// Applies a size preset using the default theme.
528    ///
529    /// This replaces the entire prior style; call it before [`Self::file_style`]
530    /// when combining a preset with custom colors.
531    ///
532    /// # Examples
533    ///
534    /// ```
535    /// use ailloli_ui_widgets::files::{FileExplorerSize, LocalFileExplorer};
536    /// let explorer = LocalFileExplorer::<()>::new(".").file_size(FileExplorerSize::Compact);
537    /// let _ = explorer;
538    /// ```
539    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    /// Maps every inner explorer action into an application action.
545    ///
546    /// Specialized select/open callbacks may also run for the same interaction.
547    ///
548    /// # Examples
549    ///
550    /// ```
551    /// use ailloli_ui_widgets::files::{FileExplorerAction, LocalFileExplorer};
552    /// enum Action { Explorer(FileExplorerAction) }
553    /// let explorer = LocalFileExplorer::<Action>::new(".").on_action(Action::Explorer);
554    /// let _ = explorer;
555    /// ```
556    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    /// Handles every inner explorer action with event-context access.
562    ///
563    /// # Examples
564    ///
565    /// ```
566    /// use ailloli_ui_widgets::files::LocalFileExplorer;
567    /// let explorer = LocalFileExplorer::<()>::new(".").on_action_ctx(|_ctx, _action| {});
568    /// let _ = explorer;
569    /// ```
570    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    /// Maps a row-selection URI into an application action.
579    ///
580    /// # Examples
581    ///
582    /// ```
583    /// use ailloli_ui_fs::FileUri;
584    /// use ailloli_ui_widgets::files::LocalFileExplorer;
585    /// enum Action { Select(FileUri) }
586    /// let explorer = LocalFileExplorer::<Action>::new(".").on_select(Action::Select);
587    /// let _ = explorer;
588    /// ```
589    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    /// Handles selection with direct event-context access.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use ailloli_ui_widgets::files::LocalFileExplorer;
600    /// let explorer = LocalFileExplorer::<()>::new(".").on_select_ctx(|_ctx, _uri| {});
601    /// let _ = explorer;
602    /// ```
603    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    /// Maps a leaf open/activation URI into an application action.
609    ///
610    /// Directory toggle events are not open callbacks.
611    ///
612    /// # Examples
613    ///
614    /// ```
615    /// use ailloli_ui_fs::FileUri;
616    /// use ailloli_ui_widgets::files::LocalFileExplorer;
617    /// enum Action { Open(FileUri) }
618    /// let explorer = LocalFileExplorer::<Action>::new(".").on_open(Action::Open);
619    /// let _ = explorer;
620    /// ```
621    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    /// Handles leaf opening with direct event-context access.
627    ///
628    /// # Examples
629    ///
630    /// ```
631    /// use ailloli_ui_widgets::files::LocalFileExplorer;
632    /// let explorer = LocalFileExplorer::<()>::new(".").on_open_ctx(|_ctx, _uri| {});
633    /// let _ = explorer;
634    /// ```
635    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
641/// Converts builder inputs into a retained runtime-backed explorer component.
642impl<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
668/// Component boundary that persists one local runtime across rebuilds.
669struct LocalFileExplorerComponent<A> {
670    /// Outer logical sizing policy.
671    layout: LayoutStyle,
672    /// Native filesystem root exposed by this explorer.
673    root_path: PathBuf,
674    /// Optional initially selected native path.
675    selected_path: Option<PathBuf>,
676    /// Native directory paths requested open at bootstrap.
677    default_expanded_paths: Vec<PathBuf>,
678    /// Depth, node-limit, and hidden-entry projection policy.
679    options: FileTreeOptions,
680    /// Lazy or controlled/full directory loading policy.
681    loading_mode: LocalFileExplorerLoadingMode,
682    /// Retention/eviction policy for collapsed directory contents.
683    cache_mode: LocalFileExplorerCacheMode,
684    /// Whether visible rows are bounded to the propagated viewport.
685    virtualized: bool,
686    /// Whether the tree is wrapped in a vertical scroll viewport.
687    scrollable: bool,
688    /// Whether filesystem requests run through the background worker.
689    async_loading: bool,
690    /// Reactive interaction-disable flag.
691    disabled: Binding<bool>,
692    /// Tree row colors and logical-pixel geometry.
693    style: FileExplorerStyle,
694    /// Optional retained semantic-action callback.
695    on_action: Option<ActionHandler<A>>,
696    /// Optional retained selection callback.
697    on_select: Option<UriHandler<A>>,
698    /// Optional retained activation callback.
699    on_open: Option<UriHandler<A>>,
700}
701
702/// Resolves native paths, services worker results, and builds the generic explorer.
703impl<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
789/// Retained filesystem store, worker, watchers, and UI-service registration.
790struct LocalFileExplorerRuntime<A> {
791    /// Retained provider-neutral file-tree model.
792    store: RetainedFileTreeStore,
793    /// Optional background request/response runtime.
794    worker: Option<FileTreeRuntime>,
795    /// Depth, node-limit, and hidden-entry projection policy.
796    options: FileTreeOptions,
797    /// Lazy or controlled/full directory loading policy.
798    loading_mode: LocalFileExplorerLoadingMode,
799    /// Retention/eviction policy for collapsed directory contents.
800    cache_mode: LocalFileExplorerCacheMode,
801    /// Canonical URI requested as the current selection.
802    selected: Option<FileUri>,
803    /// Canonical directory URIs requested open by external state.
804    desired_expanded: Vec<FileUri>,
805    /// Directory nodes whose last response was truncated by configured limits.
806    truncated: std::collections::HashSet<RetainedFileTreeNodeId>,
807    /// Directory nodes with active provider-watch subscriptions.
808    watched: HashSet<RetainedFileTreeNodeId>,
809    /// Latest user-visible worker/provider failure, cleared by later success.
810    error: Option<String>,
811    /// Whether initial root loading and desired expansion were requested.
812    bootstrapped: bool,
813    /// UI-local service callback retained for registration lifetime.
814    service_callback: Option<Rc<dyn Fn() -> bool>>,
815    /// Runtime service registration removed when this state is dropped.
816    service_registration: Option<UiServiceRegistration<A>>,
817}
818
819impl<A: 'static> LocalFileExplorerRuntime<A> {
820    /// Creates the root store and attempts to spawn its provider worker.
821    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    /// Borrows the invariant root node URI.
849    fn root_uri(&self) -> &FileUri {
850        self.store
851            .node(self.store.root())
852            .expect("root exists")
853            .uri()
854    }
855
856    /// Updates policy inputs, bootstraps root watch/load once, and drives preload.
857    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    /// Installs worker wake integration and one retained UI drain callback.
882    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    /// Drains all ready worker/watch responses and advances requested load policy.
905    ///
906    /// Returns whether model-visible state changed. Worker/store failures are
907    /// retained as a synthetic root error instead of escaping the UI service.
908    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    /// Filters/sorts one worker listing and records post-sort truncation state.
952    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    /// Expands desired URIs and schedules controlled/full breadth candidates.
989    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    /// Begins/coalesces one eligible request and stores enqueue failures as errors.
1032    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    /// Deduplicates watch state and forwards enable/disable to the worker.
1071    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    /// Updates expansion/watch state and optionally requests a toggle-driven load.
1095    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    /// Snapshots the root and appends any runtime-wide error placeholder.
1109    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    /// Recursively converts retained store nodes and transient state placeholders.
1120    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    /// Iteratively collects expanded URIs from the currently attached store tree.
1153    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
1169/// Synchronously snapshots a native directory with provider-neutral policies.
1170///
1171/// Relative root paths use the process working directory; relative expanded and
1172/// selected paths use the resolved root. Root, expansion ancestors, and selected
1173/// ancestors are deduplicated before depth-first provider traversal.
1174///
1175/// # Errors
1176///
1177/// Returns [`FileError`] for native-path URI conversion, root metadata, directory
1178/// listing, or canonicalization failures. I/O runs synchronously on the caller.
1179///
1180/// # Examples
1181///
1182/// ```
1183/// use std::path::PathBuf;
1184/// use ailloli_ui_fs::FileError;
1185/// use ailloli_ui_widgets::files::{local_file_tree_nodes, FileExplorerNode, FileTreeOptions};
1186/// fn snapshot(path: PathBuf) -> Result<Vec<FileExplorerNode>, FileError> {
1187///     local_file_tree_nodes(path, std::iter::empty(), None, FileTreeOptions::default())
1188/// }
1189/// # let _ = snapshot;
1190/// ```
1191pub 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
1216/// Builds one disabled synthetic root for invalid local path configuration.
1217fn 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
1226/// Converts a native path to the local URI namespace without swallowing errors.
1227///
1228/// # Errors
1229///
1230/// Propagates [`FileError::InvalidUri`] when `path` cannot be represented as an
1231/// absolute local file URI on the current platform.
1232fn local_uri_or_error(path: &Path) -> Result<FileUri, FileError> {
1233    FileUri::local(path)
1234}
1235
1236/// Expands root, configured paths, and selected ancestors in stable unique order.
1237fn 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
1257/// Keeps absolute paths and joins relative paths beneath the explorer root.
1258fn 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
1266/// Keeps absolute paths or joins them to cwd, falling back to `/` on cwd failure.
1267fn 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)]
1278/// Real-filesystem scenarios for path expansion and all synchronous load modes.
1279mod tests {
1280    use std::fs;
1281    use std::time::{SystemTime, UNIX_EPOCH};
1282
1283    use super::*;
1284
1285    /// Process/time-namespaced directory removed after each scenario.
1286    struct TempDir {
1287        path: PathBuf,
1288    }
1289
1290    impl TempDir {
1291        /// Creates one unique OS-temporary fixture directory.
1292        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    /// Finds a named child or panics with parent context.
1407    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}