ailloli_ui_widgets/files/
explorer.rs

1//! Snapshot-backed and retained-model filesystem tree widgets.
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::fmt;
6use std::hash::Hash;
7use std::rc::Rc;
8
9use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle};
10use ailloli_ui_core::Point;
11use ailloli_ui_core::{IconId, Theme};
12use ailloli_ui_fs::{FileKind, FileUri};
13use ailloli_ui_runtime::component::reactive::with_untracked_reads;
14use ailloli_ui_runtime::component::{
15    Binding, ComponentNode, Context, IntoView, Signal, State, View,
16};
17use ailloli_ui_runtime::input::{ClickAction, EventCtx};
18use ailloli_ui_runtime::Invalidation;
19
20use crate::controls::{
21    ContextMenu, ContextMenuEntry, ContextMenuItem, TreeContextMenu, TreeCreateKind,
22    TreeCreateRequest, TreeDropPosition, TreeModelHandle, TreeMove, TreeMutationMode, TreeNode,
23    TreeShortcut, TreeView, TreeViewCommand, TreeViewDiagnostics, TreeViewSize, TreeViewStyle,
24};
25use crate::layout::layout_ext::finish_view_sized;
26use crate::layout::{Container, LayoutExt, ScrollView};
27
28use super::icons::file_icon_visual_for_entry;
29use super::model::{sort_file_nodes, FileExplorerNode};
30
31/// Shared callback for the complete high-level action stream.
32type ActionHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileExplorerAction)>;
33/// Shared callback for one selected/opened URI.
34type UriHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileUri)>;
35/// Shared callback for an expansion transition.
36type ToggleHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileUri, bool)>;
37/// Shared callback for a committed inline rename.
38type RenameHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileExplorerRename)>;
39/// Shared callback for a committed directory draft.
40type CreateDirHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileExplorerCreateDir)>;
41/// Shared callback for a committed removal URI and optional parent.
42type RemoveHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileUri, Option<FileUri>)>;
43/// Resolves opaque retained identity to current file metadata on demand.
44type RetainedNodeResolver<T> = Rc<dyn Fn(T) -> Option<FileExplorerNode>>;
45/// Resolves a URI back to opaque retained identity for commands.
46type RetainedIdResolver<T> = Rc<dyn Fn(&FileUri) -> Option<T>>;
47/// Reserves an identity for a transient create draft.
48type RetainedNodeReserve<T> = Rc<dyn Fn(Option<&T>, FileKind) -> Option<T>>;
49/// Releases a reserved identity after create cancellation/failure.
50type RetainedNodeRelease<T> = Rc<dyn Fn(T)>;
51/// Shared callback for identity-aware retained model events.
52type RetainedEventHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, FileExplorerModelEvent<T>)>;
53/// Begins inline rename through the inner tree command channel.
54type TreeRenameCommandHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileUri)>;
55/// Begins inline create through the inner tree command channel.
56type TreeCreateCommandHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileUri, &'static str)>;
57
58/// Cloneable pair of context-menu-to-tree edit command adapters.
59struct FileExplorerTreeCommands<A> {
60    /// Callback translating an inline rename into an explorer action.
61    rename: TreeRenameCommandHandler<A>,
62    /// Callback translating an inline create into an explorer action.
63    create: TreeCreateCommandHandler<A>,
64}
65
66/// Clones only reference-counted command closures, never application state.
67impl<A> Clone for FileExplorerTreeCommands<A> {
68    fn clone(&self) -> Self {
69        Self {
70            rename: self.rename.clone(),
71            create: self.create.clone(),
72        }
73    }
74}
75
76impl<A> FileExplorerTreeCommands<A> {
77    /// Requests inline editing for the URI row.
78    fn begin_rename(&self, ctx: &mut EventCtx<A>, uri: FileUri) {
79        (self.rename)(ctx, uri);
80    }
81
82    /// Requests a transient child draft with the supplied default label.
83    fn begin_create(&self, ctx: &mut EventCtx<A>, parent: FileUri, label: &'static str) {
84        (self.create)(ctx, parent, label);
85    }
86}
87
88/// Sentinel default label that also classifies a transient draft as a file.
89const NEW_FILE_NAME: &str = "New_File";
90/// Sentinel default label for a transient directory draft.
91const NEW_FOLDER_NAME: &str = "New_Folder";
92
93/// High-level intent emitted by snapshot and retained file explorers.
94///
95/// Requested variants start UI/application workflows; committed variants carry
96/// completed inline edit data. The widget never performs filesystem mutations.
97/// Context-menu items that require an absent handler are rendered disabled.
98///
99/// # Examples
100///
101/// ```
102/// use ailloli_ui_fs::FileUri;
103/// use ailloli_ui_widgets::files::FileExplorerAction;
104/// let uri = FileUri::parse("file:///repo/main.rs")?;
105/// assert_eq!(FileExplorerAction::Select(uri.clone()), FileExplorerAction::Select(uri));
106/// # Ok::<(), ailloli_ui_fs::FileError>(())
107/// ```
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub enum FileExplorerAction {
110    /// Row selection changed to the URI.
111    Select(FileUri),
112    /// A leaf or context-menu target was activated.
113    Open(FileUri),
114    /// A branch changed expansion state.
115    Toggle {
116        /// Branch URI.
117        uri: FileUri,
118        /// `true` for expanded, `false` for collapsed.
119        expanded: bool,
120    },
121    /// UI should begin or authorize renaming this URI.
122    RenameRequested {
123        /// Target URI before rename.
124        uri: FileUri,
125    },
126    /// Inline rename was committed.
127    Rename(FileExplorerRename),
128    /// UI/application should confirm or begin removal.
129    RemoveRequested {
130        /// Target URI.
131        uri: FileUri,
132        /// Lexical parent when available.
133        parent: Option<FileUri>,
134    },
135    /// Tree delete interaction was committed.
136    Remove {
137        /// Target URI.
138        uri: FileUri,
139        /// Lexical parent when available.
140        parent: Option<FileUri>,
141    },
142    /// UI should begin a file draft below the parent.
143    CreateFileRequested {
144        /// Intended parent directory.
145        parent: FileUri,
146    },
147    /// UI should begin a directory draft below the parent.
148    CreateDirRequested {
149        /// Intended parent directory.
150        parent: FileUri,
151    },
152    /// Inline file creation was committed.
153    CreateFile(FileExplorerCreateFile),
154    /// Inline directory creation was committed.
155    CreateDir(FileExplorerCreateDir),
156    /// Copies an absolute/display path string through application integration.
157    CopyPath {
158        /// URI whose path is requested.
159        uri: FileUri,
160    },
161    /// Copies a path relative to its matching explorer root.
162    CopyRelativePath {
163        /// URI whose relative path is requested.
164        uri: FileUri,
165    },
166    /// Copies the file/directory entry to application clipboard state.
167    CopyFile {
168        /// Source URI.
169        uri: FileUri,
170    },
171    /// Cuts the entry into application clipboard state.
172    CutFile {
173        /// Source URI.
174        uri: FileUri,
175    },
176    /// Pastes clipboard content into a directory.
177    PasteInto {
178        /// Destination directory URI.
179        target_dir: FileUri,
180    },
181    /// Drag/drop move intent with resolved source/destination metadata.
182    MoveEntry(FileExplorerMove),
183    /// Requests refreshing one directory/workspace root.
184    Refresh {
185        /// Directory URI to refresh.
186        uri: FileUri,
187    },
188    /// Requests a terminal rooted at a directory.
189    OpenTerminalHere {
190        /// Directory URI.
191        uri: FileUri,
192    },
193    /// Requests scoped search in a directory.
194    SearchInFolder {
195        /// Directory URI.
196        uri: FileUri,
197    },
198    /// Requests revealing the entry in a workspace integration.
199    RevealInWorkspace {
200        /// Entry URI.
201        uri: FileUri,
202    },
203    /// Adds a directory as a workspace root.
204    AddFolderToWorkspace {
205        /// Directory URI.
206        uri: FileUri,
207    },
208    /// Removes an existing explorer root from the workspace.
209    RemoveFolderFromWorkspace {
210        /// Root URI.
211        uri: FileUri,
212    },
213    /// Replaces the workspace root with a directory.
214    SetWorkspaceRoot {
215        /// New root URI.
216        uri: FileUri,
217    },
218    /// Opens a workspace rooted at the URI.
219    OpenWorkspaceHere {
220        /// Workspace root URI.
221        uri: FileUri,
222    },
223    /// Opens workspace settings.
224    OpenWorkspaceSettings,
225    /// Collapses all branches.
226    CollapseAll,
227    /// Expands all branches.
228    ExpandAll,
229    /// Reveals the application's active file.
230    RevealActiveFile,
231    /// Opens workspace-wide search.
232    SearchInWorkspace,
233}
234
235/// Committed inline rename payload.
236///
237/// Names are stored verbatim; validation and filesystem mutation belong to the
238/// application/provider layer.
239///
240/// # Examples
241///
242/// ```
243/// use ailloli_ui_fs::FileUri;
244/// use ailloli_ui_widgets::files::FileExplorerRename;
245/// let rename = FileExplorerRename { uri: FileUri::parse("file:///old")?, old_name: "old".into(), new_name: "new".into() };
246/// assert_eq!(rename.new_name, "new");
247/// # Ok::<(), ailloli_ui_fs::FileError>(())
248/// ```
249#[derive(Clone, Debug, PartialEq, Eq)]
250pub struct FileExplorerRename {
251    /// URI before the rename is applied.
252    pub uri: FileUri,
253    /// Previous visible label.
254    pub old_name: String,
255    /// User-committed new label, possibly empty/invalid.
256    pub new_name: String,
257}
258
259/// Committed inline directory-creation payload.
260///
261/// # Examples
262///
263/// ```
264/// use ailloli_ui_fs::FileUri;
265/// use ailloli_ui_widgets::files::FileExplorerCreateDir;
266/// let parent = FileUri::parse("file:///repo")?;
267/// let event = FileExplorerCreateDir { uri: parent.join_child("src")?, parent: Some(parent), after: None, name: "src".into() };
268/// assert_eq!(event.name, "src");
269/// # Ok::<(), ailloli_ui_fs::FileError>(())
270/// ```
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub struct FileExplorerCreateDir {
273    /// Proposed URI for the new directory.
274    pub uri: FileUri,
275    /// Parent directory, or `None` for a root-level draft.
276    pub parent: Option<FileUri>,
277    /// Optional sibling after which the draft was positioned.
278    pub after: Option<FileUri>,
279    /// User-committed name stored verbatim.
280    pub name: String,
281}
282
283/// Committed inline file-creation payload.
284///
285/// # Examples
286///
287/// ```
288/// use ailloli_ui_fs::FileUri;
289/// use ailloli_ui_widgets::files::FileExplorerCreateFile;
290/// let parent = FileUri::parse("file:///repo")?;
291/// let event = FileExplorerCreateFile { uri: parent.join_child("main.rs")?, parent: Some(parent), after: None, name: "main.rs".into() };
292/// assert_eq!(event.name, "main.rs");
293/// # Ok::<(), ailloli_ui_fs::FileError>(())
294/// ```
295#[derive(Clone, Debug, PartialEq, Eq)]
296pub struct FileExplorerCreateFile {
297    /// Proposed URI for the new file.
298    pub uri: FileUri,
299    /// Parent directory, or `None` for a root-level draft.
300    pub parent: Option<FileUri>,
301    /// Optional sibling after which the draft was positioned.
302    pub after: Option<FileUri>,
303    /// User-committed name stored verbatim.
304    pub name: String,
305}
306
307/// Resolved drag/drop move intent.
308///
309/// # Examples
310///
311/// ```
312/// use ailloli_ui_fs::FileUri;
313/// use ailloli_ui_widgets::files::FileExplorerMove;
314/// let from = FileUri::parse("file:///repo/a")?;
315/// let parent = FileUri::parse("file:///repo/sub")?;
316/// let movement = FileExplorerMove { from: from.clone(), to: parent.join_child("a")?, source_parent: from.parent(), target_parent: parent };
317/// assert_ne!(movement.from, movement.to);
318/// # Ok::<(), ailloli_ui_fs::FileError>(())
319/// ```
320#[derive(Clone, Debug, PartialEq, Eq)]
321pub struct FileExplorerMove {
322    /// Original entry URI.
323    pub from: FileUri,
324    /// Proposed destination URI including the original filename.
325    pub to: FileUri,
326    /// Original lexical parent, if one exists.
327    pub source_parent: Option<FileUri>,
328    /// Resolved destination directory.
329    pub target_parent: FileUri,
330}
331
332/// Identity-aware event emitted by [`RetainedFileExplorer`]. The opaque node
333/// IDs let a filesystem coordinator mutate its store without rediscovering a
334/// node from a path that may already have changed.
335///
336/// # Examples
337///
338/// ```
339/// use ailloli_ui_fs::FileUri;
340/// use ailloli_ui_widgets::files::FileExplorerModelEvent;
341/// let event = FileExplorerModelEvent::Select { node_id: 7_u64, uri: FileUri::parse("file:///a")? };
342/// assert!(matches!(event, FileExplorerModelEvent::Select { node_id: 7, .. }));
343/// # Ok::<(), ailloli_ui_fs::FileError>(())
344/// ```
345#[non_exhaustive]
346#[derive(Clone, Debug, PartialEq, Eq)]
347pub enum FileExplorerModelEvent<T> {
348    /// Selection changed to an existing retained node.
349    Select {
350        /// Opaque stable node identity.
351        node_id: T,
352        /// URI resolved at interaction time.
353        uri: FileUri,
354    },
355    /// An existing retained leaf was activated.
356    Open {
357        /// Opaque stable node identity.
358        node_id: T,
359        /// URI resolved at interaction time.
360        uri: FileUri,
361    },
362    /// Expansion changed for an existing retained branch.
363    Toggle {
364        /// Opaque stable node identity.
365        node_id: T,
366        /// URI resolved at interaction time.
367        uri: FileUri,
368        /// New expansion state.
369        expanded: bool,
370    },
371    /// Inline rename committed for an existing retained node.
372    Rename {
373        /// Opaque stable node identity.
374        node_id: T,
375        /// Path/name payload.
376        rename: FileExplorerRename,
377    },
378    /// Inline create committed using a previously reserved identity.
379    Create {
380        /// Reserved identity for the new node.
381        node_id: T,
382        /// Existing destination parent identity.
383        parent_id: T,
384        /// Requested file or directory kind.
385        kind: FileKind,
386        /// Proposed destination URI.
387        uri: FileUri,
388        /// User-committed name.
389        name: String,
390    },
391    /// Inline create was cancelled and the reserved identity was released.
392    CancelCreate {
393        /// Released draft identity.
394        node_id: T,
395    },
396    /// Valid drag/drop move resolved to retained identities.
397    Move {
398        /// Moved node identity.
399        node_id: T,
400        /// Destination parent identity.
401        target_parent_id: T,
402        /// URI-level move payload.
403        movement: FileExplorerMove,
404    },
405}
406
407/// Row-density preset for file explorer tree styling.
408///
409/// # Examples
410///
411/// ```
412/// use ailloli_ui_widgets::files::FileExplorerSize;
413/// assert_eq!(FileExplorerSize::default(), FileExplorerSize::Default);
414/// ```
415#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
416pub enum FileExplorerSize {
417    /// Compact tree row metrics.
418    Compact,
419    /// Standard tree row metrics and default.
420    #[default]
421    Default,
422}
423
424/// File explorer styling delegated to the underlying tree view.
425///
426/// # Examples
427///
428/// ```
429/// use ailloli_ui_widgets::files::FileExplorerStyle;
430/// let style = FileExplorerStyle::default();
431/// let _ = style.tree;
432/// ```
433#[derive(Clone, Debug, PartialEq)]
434pub struct FileExplorerStyle {
435    /// Complete tree row, indent, icon, and interaction styling.
436    pub tree: TreeViewStyle,
437}
438
439/// Derives standard-density styling from the default theme.
440impl Default for FileExplorerStyle {
441    fn default() -> Self {
442        Self::from_theme(Theme::default(), FileExplorerSize::Default)
443    }
444}
445
446impl FileExplorerStyle {
447    /// Maps file density to the equivalent tree-view size under `theme`.
448    ///
449    /// # Examples
450    ///
451    /// ```
452    /// use ailloli_ui_core::Theme;
453    /// use ailloli_ui_widgets::files::{FileExplorerSize, FileExplorerStyle};
454    /// let style = FileExplorerStyle::from_theme(Theme::default(), FileExplorerSize::Compact);
455    /// let _ = style.tree;
456    /// ```
457    pub fn from_theme(theme: Theme, size: FileExplorerSize) -> Self {
458        let tree_size = match size {
459            FileExplorerSize::Compact => TreeViewSize::Compact,
460            FileExplorerSize::Default => TreeViewSize::Default,
461        };
462        Self {
463            tree: TreeViewStyle::from_theme(theme, tree_size),
464        }
465    }
466}
467
468/// Snapshot-backed, URI-identified filesystem tree with editing and context menus.
469///
470/// Input snapshots are recursively sorted directory-first on each build and
471/// projected into an intent-only [`TreeView`]. The widget emits actions but does
472/// not mutate a filesystem. Default rendering is non-virtualized and vertically
473/// scrollable. `A` is the surrounding application's action type.
474///
475/// # Examples
476///
477/// ```
478/// use ailloli_ui_fs::FileUri;
479/// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerNode};
480/// let nodes = [FileExplorerNode::directory(FileUri::parse("file:///repo")?, "repo")];
481/// let explorer = FileExplorer::<()>::new(nodes);
482/// let _ = explorer;
483/// # Ok::<(), ailloli_ui_fs::FileError>(())
484/// ```
485pub struct FileExplorer<A = ()> {
486    /// Standard logical-pixel size and position constraints.
487    pub(crate) layout: LayoutStyle,
488    /// Standard flex-parent participation settings.
489    pub(crate) flex_item: FlexItemStyle,
490    /// Read-only fallback flat file-node snapshot.
491    nodes: Vec<FileExplorerNode>,
492    /// Optional reactive authoritative node snapshot.
493    bound_nodes: Option<Signal<Vec<FileExplorerNode>>>,
494    /// Optional readable selected URI.
495    selected: Option<Binding<FileUri>>,
496    /// Optional writable selected URI.
497    bound_selected: Option<Signal<FileUri>>,
498    /// Optional readable expanded-directory URI list.
499    expanded: Option<Binding<Vec<FileUri>>>,
500    /// Optional writable expanded-directory URI list.
501    bound_expanded: Option<Signal<Vec<FileUri>>>,
502    /// Initial expansion list used when the explorer owns its state.
503    default_expanded: Vec<FileUri>,
504    /// Reactive interaction-disable flag.
505    disabled: Binding<bool>,
506    /// Reactive capability indicating whether paste actions are available.
507    clipboard_can_paste: Binding<bool>,
508    /// Tree row colors and logical-pixel geometry.
509    style: FileExplorerStyle,
510    /// Whether visible rows are bounded to the propagated viewport.
511    virtualized: bool,
512    /// Whether the tree is wrapped in a vertical scroll viewport.
513    scrollable: bool,
514    /// Optional callback receiving semantic explorer actions.
515    on_action: Option<ActionHandler<A>>,
516    /// Optional callback receiving selected URIs.
517    on_select: Option<UriHandler<A>>,
518    /// Optional callback receiving activated/opened URIs.
519    on_open: Option<UriHandler<A>>,
520    /// Optional callback receiving directory expansion changes.
521    on_toggle: Option<ToggleHandler<A>>,
522    /// Optional callback receiving inline rename requests.
523    on_rename: Option<RenameHandler<A>>,
524    /// Optional callback receiving removal requests.
525    on_remove: Option<RemoveHandler<A>>,
526    /// Optional callback receiving directory-creation requests.
527    on_create_dir: Option<CreateDirHandler<A>>,
528}
529
530crate::impl_layout_builders!(FileExplorer);
531
532/// Creates an empty enabled explorer through [`Self::new`].
533impl<A: 'static> Default for FileExplorer<A> {
534    fn default() -> Self {
535        Self::new(Vec::new())
536    }
537}
538
539impl<A: 'static> FileExplorer<A> {
540    /// Collects a static recursive snapshot with default interaction/style state.
541    ///
542    /// Input order is not retained during rendering: sibling nodes are sorted
543    /// recursively. Duplicate URIs are accepted but make identity ambiguous.
544    ///
545    /// # Examples
546    ///
547    /// ```
548    /// use ailloli_ui_fs::FileUri;
549    /// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerNode};
550    /// let explorer = FileExplorer::<()>::new([
551    ///     FileExplorerNode::file(FileUri::parse("file:///a")?, "a"),
552    /// ]);
553    /// let _ = explorer;
554    /// # Ok::<(), ailloli_ui_fs::FileError>(())
555    /// ```
556    pub fn new(nodes: impl IntoIterator<Item = FileExplorerNode>) -> Self {
557        Self {
558            layout: LayoutStyle::default(),
559            flex_item: FlexItemStyle::default(),
560            nodes: nodes.into_iter().collect(),
561            bound_nodes: None,
562            selected: None,
563            bound_selected: None,
564            expanded: None,
565            bound_expanded: None,
566            default_expanded: Vec::new(),
567            disabled: Binding::Static(false),
568            clipboard_can_paste: Binding::Static(false),
569            style: FileExplorerStyle::default(),
570            virtualized: false,
571            scrollable: true,
572            on_action: None,
573            on_select: None,
574            on_open: None,
575            on_toggle: None,
576            on_rename: None,
577            on_remove: None,
578            on_create_dir: None,
579        }
580    }
581
582    /// Binds the recursive snapshot to live shared state.
583    ///
584    /// Bound nodes take precedence over constructor nodes. Each build reads,
585    /// clones, and recursively sorts the current vector.
586    ///
587    /// # Examples
588    ///
589    /// ```
590    /// use ailloli_ui_runtime::component::State;
591    /// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerNode};
592    /// let explorer = FileExplorer::<()>::default().bind_nodes(State::new(Vec::<FileExplorerNode>::new()));
593    /// let _ = explorer;
594    /// ```
595    pub fn bind_nodes(mut self, nodes: impl Into<Signal<Vec<FileExplorerNode>>>) -> Self {
596        self.bound_nodes = Some(nodes.into());
597        self
598    }
599
600    /// Sets static/generic selected-URI input and clears writable selection state.
601    ///
602    /// User selection still emits callbacks, but only [`Self::bind_selected`]
603    /// installs the writable signal that the inner tree updates automatically.
604    ///
605    /// # Examples
606    ///
607    /// ```
608    /// use ailloli_ui_fs::FileUri;
609    /// use ailloli_ui_widgets::files::FileExplorer;
610    /// let explorer = FileExplorer::<()>::default().selected(FileUri::parse("file:///a")?);
611    /// let _ = explorer;
612    /// # Ok::<(), ailloli_ui_fs::FileError>(())
613    /// ```
614    pub fn selected(mut self, selected: impl Into<Binding<FileUri>>) -> Self {
615        self.selected = Some(selected.into());
616        self.bound_selected = None;
617        self
618    }
619
620    /// Binds selection to writable shared state.
621    ///
622    /// The inner tree writes the URI on user selection before callbacks.
623    ///
624    /// # Examples
625    ///
626    /// ```
627    /// use ailloli_ui_fs::FileUri;
628    /// use ailloli_ui_runtime::component::State;
629    /// use ailloli_ui_widgets::files::FileExplorer;
630    /// let selected = State::new(FileUri::parse("file:///a")?);
631    /// let explorer = FileExplorer::<()>::default().bind_selected(selected);
632    /// let _ = explorer;
633    /// # Ok::<(), ailloli_ui_fs::FileError>(())
634    /// ```
635    pub fn bind_selected(mut self, selected: impl Into<Signal<FileUri>>) -> Self {
636        let signal = selected.into();
637        self.selected = Some(Binding::Signal(signal.clone()));
638        self.bound_selected = Some(signal);
639        self
640    }
641
642    /// Sets static/generic expanded URIs and clears writable expansion state.
643    ///
644    /// This input takes precedence over default expansion. Only a signal installed
645    /// by [`Self::bind_expanded`] is automatically written on toggles.
646    ///
647    /// # Examples
648    ///
649    /// ```
650    /// use ailloli_ui_fs::FileUri;
651    /// use ailloli_ui_widgets::files::FileExplorer;
652    /// let explorer = FileExplorer::<()>::default().expanded(vec![FileUri::parse("file:///repo")?]);
653    /// let _ = explorer;
654    /// # Ok::<(), ailloli_ui_fs::FileError>(())
655    /// ```
656    pub fn expanded(mut self, expanded: impl Into<Binding<Vec<FileUri>>>) -> Self {
657        self.expanded = Some(expanded.into());
658        self.bound_expanded = None;
659        self
660    }
661
662    /// Binds expansion to writable shared state.
663    ///
664    /// # Examples
665    ///
666    /// ```
667    /// use ailloli_ui_fs::FileUri;
668    /// use ailloli_ui_runtime::component::State;
669    /// use ailloli_ui_widgets::files::FileExplorer;
670    /// let expanded = State::new(vec![FileUri::parse("file:///repo")?]);
671    /// let explorer = FileExplorer::<()>::default().bind_expanded(expanded);
672    /// let _ = explorer;
673    /// # Ok::<(), ailloli_ui_fs::FileError>(())
674    /// ```
675    pub fn bind_expanded(mut self, expanded: impl Into<Signal<Vec<FileUri>>>) -> Self {
676        let signal = expanded.into();
677        self.expanded = Some(Binding::Signal(signal.clone()));
678        self.bound_expanded = Some(signal);
679        self
680    }
681
682    /// Appends one unique initial expansion URI.
683    ///
684    /// Defaults apply only when neither [`Self::expanded`] nor
685    /// [`Self::bind_expanded`] supplies controlled state.
686    ///
687    /// # Examples
688    ///
689    /// ```
690    /// use ailloli_ui_fs::FileUri;
691    /// use ailloli_ui_widgets::files::FileExplorer;
692    /// let explorer = FileExplorer::<()>::default().default_expanded(FileUri::parse("file:///repo")?);
693    /// let _ = explorer;
694    /// # Ok::<(), ailloli_ui_fs::FileError>(())
695    /// ```
696    pub fn default_expanded(mut self, uri: FileUri) -> Self {
697        if !self.default_expanded.iter().any(|item| item == &uri) {
698            self.default_expanded.push(uri);
699        }
700        self
701    }
702
703    /// Replaces initial expansion URIs, preserving first-occurrence order.
704    ///
705    /// # Examples
706    ///
707    /// ```
708    /// use ailloli_ui_fs::FileUri;
709    /// use ailloli_ui_widgets::files::FileExplorer;
710    /// let root = FileUri::parse("file:///repo")?;
711    /// let explorer = FileExplorer::<()>::default().default_expanded_many([root.clone(), root]);
712    /// let _ = explorer;
713    /// # Ok::<(), ailloli_ui_fs::FileError>(())
714    /// ```
715    pub fn default_expanded_many(mut self, uris: impl IntoIterator<Item = FileUri>) -> Self {
716        self.default_expanded.clear();
717        for uri in uris {
718            if !self.default_expanded.iter().any(|item| item == &uri) {
719                self.default_expanded.push(uri);
720            }
721        }
722        self
723    }
724
725    /// Binds whether tree interaction is disabled.
726    ///
727    /// # Examples
728    ///
729    /// ```
730    /// use ailloli_ui_runtime::component::State;
731    /// use ailloli_ui_widgets::files::FileExplorer;
732    /// let explorer = FileExplorer::<()>::default().disabled(State::new(true));
733    /// let _ = explorer;
734    /// ```
735    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
736        self.disabled = disabled.into();
737        self
738    }
739
740    /// Binds whether keyboard/blank-area paste actions are eligible.
741    ///
742    /// A row context menu can still emit `PasteInto` when an aggregate action
743    /// handler exists; this flag primarily gates shortcuts and blank menus.
744    ///
745    /// # Examples
746    ///
747    /// ```
748    /// use ailloli_ui_widgets::files::FileExplorer;
749    /// let explorer = FileExplorer::<()>::default().clipboard_can_paste(true);
750    /// let _ = explorer;
751    /// ```
752    pub fn clipboard_can_paste(mut self, can_paste: impl Into<Binding<bool>>) -> Self {
753        self.clipboard_can_paste = can_paste.into();
754        self
755    }
756
757    /// Replaces the complete tree style.
758    ///
759    /// # Examples
760    ///
761    /// ```
762    /// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerStyle};
763    /// let explorer = FileExplorer::<()>::default().file_style(FileExplorerStyle::default());
764    /// let _ = explorer;
765    /// ```
766    pub fn file_style(mut self, style: FileExplorerStyle) -> Self {
767        self.style = style;
768        self
769    }
770
771    /// Applies a density preset using the default theme.
772    ///
773    /// This replaces the entire existing style.
774    ///
775    /// # Examples
776    ///
777    /// ```
778    /// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerSize};
779    /// let explorer = FileExplorer::<()>::default().file_size(FileExplorerSize::Compact);
780    /// let _ = explorer;
781    /// ```
782    pub fn file_size(mut self, size: FileExplorerSize) -> Self {
783        self.style = FileExplorerStyle::from_theme(Theme::default(), size);
784        self
785    }
786
787    /// Enables viewport-driven row virtualization in the inner tree.
788    ///
789    /// The default is `false`; this changes rendering work, not snapshot contents.
790    ///
791    /// # Examples
792    ///
793    /// ```
794    /// use ailloli_ui_widgets::files::FileExplorer;
795    /// let explorer = FileExplorer::<()>::default().virtualized(true);
796    /// let _ = explorer;
797    /// ```
798    pub fn virtualized(mut self, virtualized: bool) -> Self {
799        self.virtualized = virtualized;
800        self
801    }
802
803    /// Wraps the tree in a vertical [`ScrollView`] when true.
804    ///
805    /// Scrolling is enabled by default. When disabled, explorer layout builders
806    /// apply directly to the tree.
807    ///
808    /// # Examples
809    ///
810    /// ```
811    /// use ailloli_ui_widgets::files::FileExplorer;
812    /// let explorer = FileExplorer::<()>::default().scrollable(false);
813    /// let _ = explorer;
814    /// ```
815    pub fn scrollable(mut self, scrollable: bool) -> Self {
816        self.scrollable = scrollable;
817        self
818    }
819
820    /// Maps the complete explorer action stream into application actions.
821    ///
822    /// Specialized callbacks run first for their committed interaction, so both
823    /// may dispatch for one event.
824    ///
825    /// # Examples
826    ///
827    /// ```
828    /// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerAction};
829    /// enum Action { Explorer(FileExplorerAction) }
830    /// let explorer = FileExplorer::<Action>::default().on_action(Action::Explorer);
831    /// let _ = explorer;
832    /// ```
833    pub fn on_action(mut self, f: impl Fn(FileExplorerAction) -> A + 'static) -> Self {
834        self.on_action = Some(Rc::new(move |ctx, action| ctx.dispatch(f(action))));
835        self
836    }
837
838    /// Handles the complete action stream with direct event-context access.
839    ///
840    /// # Examples
841    ///
842    /// ```
843    /// use ailloli_ui_widgets::files::FileExplorer;
844    /// let explorer = FileExplorer::<()>::default().on_action_ctx(|_ctx, _action| {});
845    /// let _ = explorer;
846    /// ```
847    pub fn on_action_ctx(
848        mut self,
849        f: impl Fn(&mut EventCtx<A>, FileExplorerAction) + 'static,
850    ) -> Self {
851        self.on_action = Some(Rc::new(f));
852        self
853    }
854
855    /// Maps row selection into an application action before aggregate emission.
856    ///
857    /// # Examples
858    ///
859    /// ```
860    /// use ailloli_ui_fs::FileUri;
861    /// use ailloli_ui_widgets::files::FileExplorer;
862    /// enum Action { Select(FileUri) }
863    /// let explorer = FileExplorer::<Action>::default().on_select(Action::Select);
864    /// let _ = explorer;
865    /// ```
866    pub fn on_select(mut self, f: impl Fn(FileUri) -> A + 'static) -> Self {
867        self.on_select = Some(Rc::new(move |ctx, uri| ctx.dispatch(f(uri))));
868        self
869    }
870
871    /// Handles row selection with direct event-context access.
872    ///
873    /// # Examples
874    ///
875    /// ```
876    /// use ailloli_ui_widgets::files::FileExplorer;
877    /// let explorer = FileExplorer::<()>::default().on_select_ctx(|_ctx, _uri| {});
878    /// let _ = explorer;
879    /// ```
880    pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>, FileUri) + 'static) -> Self {
881        self.on_select = Some(Rc::new(f));
882        self
883    }
884
885    /// Maps leaf/context-menu activation before aggregate `Open` emission.
886    ///
887    /// # Examples
888    ///
889    /// ```
890    /// use ailloli_ui_fs::FileUri;
891    /// use ailloli_ui_widgets::files::FileExplorer;
892    /// enum Action { Open(FileUri) }
893    /// let explorer = FileExplorer::<Action>::default().on_open(Action::Open);
894    /// let _ = explorer;
895    /// ```
896    pub fn on_open(mut self, f: impl Fn(FileUri) -> A + 'static) -> Self {
897        self.on_open = Some(Rc::new(move |ctx, uri| ctx.dispatch(f(uri))));
898        self
899    }
900
901    /// Handles leaf/context-menu activation with event-context access.
902    ///
903    /// # Examples
904    ///
905    /// ```
906    /// use ailloli_ui_widgets::files::FileExplorer;
907    /// let explorer = FileExplorer::<()>::default().on_open_ctx(|_ctx, _uri| {});
908    /// let _ = explorer;
909    /// ```
910    pub fn on_open_ctx(mut self, f: impl Fn(&mut EventCtx<A>, FileUri) + 'static) -> Self {
911        self.on_open = Some(Rc::new(f));
912        self
913    }
914
915    /// Maps branch URI/new-state transitions before aggregate emission.
916    ///
917    /// # Examples
918    ///
919    /// ```
920    /// use ailloli_ui_fs::FileUri;
921    /// use ailloli_ui_widgets::files::FileExplorer;
922    /// enum Action { Toggle(FileUri, bool) }
923    /// let explorer = FileExplorer::<Action>::default().on_toggle(Action::Toggle);
924    /// let _ = explorer;
925    /// ```
926    pub fn on_toggle(mut self, f: impl Fn(FileUri, bool) -> A + 'static) -> Self {
927        self.on_toggle = Some(Rc::new(move |ctx, uri, open| ctx.dispatch(f(uri, open))));
928        self
929    }
930
931    /// Handles branch expansion transitions with event-context access.
932    ///
933    /// # Examples
934    ///
935    /// ```
936    /// use ailloli_ui_widgets::files::FileExplorer;
937    /// let explorer = FileExplorer::<()>::default().on_toggle_ctx(|_ctx, _uri, _open| {});
938    /// let _ = explorer;
939    /// ```
940    pub fn on_toggle_ctx(mut self, f: impl Fn(&mut EventCtx<A>, FileUri, bool) + 'static) -> Self {
941        self.on_toggle = Some(Rc::new(f));
942        self
943    }
944
945    /// Maps committed inline renames before aggregate `Rename` emission.
946    ///
947    /// Context-menu rename requests begin editing and emit `RenameRequested` but
948    /// do not call this handler until editing commits.
949    ///
950    /// # Examples
951    ///
952    /// ```
953    /// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerRename};
954    /// enum Action { Rename(FileExplorerRename) }
955    /// let explorer = FileExplorer::<Action>::default().on_rename(Action::Rename);
956    /// let _ = explorer;
957    /// ```
958    pub fn on_rename(mut self, f: impl Fn(FileExplorerRename) -> A + 'static) -> Self {
959        self.on_rename = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
960        self
961    }
962
963    /// Handles committed inline renames with event-context access.
964    ///
965    /// # Examples
966    ///
967    /// ```
968    /// use ailloli_ui_widgets::files::FileExplorer;
969    /// let explorer = FileExplorer::<()>::default().on_rename_ctx(|_ctx, _rename| {});
970    /// let _ = explorer;
971    /// ```
972    pub fn on_rename_ctx(
973        mut self,
974        f: impl Fn(&mut EventCtx<A>, FileExplorerRename) + 'static,
975    ) -> Self {
976        self.on_rename = Some(Rc::new(f));
977        self
978    }
979
980    /// Maps committed tree delete events before aggregate `Remove` emission.
981    ///
982    /// Context-menu delete emits `RemoveRequested` through the aggregate handler;
983    /// it uses this handler only to enable the item and does not call it directly.
984    ///
985    /// # Examples
986    ///
987    /// ```
988    /// use ailloli_ui_fs::FileUri;
989    /// use ailloli_ui_widgets::files::FileExplorer;
990    /// enum Action { Remove(FileUri, Option<FileUri>) }
991    /// let explorer = FileExplorer::<Action>::default().on_remove(Action::Remove);
992    /// let _ = explorer;
993    /// ```
994    pub fn on_remove(mut self, f: impl Fn(FileUri, Option<FileUri>) -> A + 'static) -> Self {
995        self.on_remove = Some(Rc::new(move |ctx, uri, parent| {
996            ctx.dispatch(f(uri, parent))
997        }));
998        self
999    }
1000
1001    /// Handles committed tree delete events with event-context access.
1002    ///
1003    /// # Examples
1004    ///
1005    /// ```
1006    /// use ailloli_ui_widgets::files::FileExplorer;
1007    /// let explorer = FileExplorer::<()>::default().on_remove_ctx(|_ctx, _uri, _parent| {});
1008    /// let _ = explorer;
1009    /// ```
1010    pub fn on_remove_ctx(
1011        mut self,
1012        f: impl Fn(&mut EventCtx<A>, FileUri, Option<FileUri>) + 'static,
1013    ) -> Self {
1014        self.on_remove = Some(Rc::new(f));
1015        self
1016    }
1017
1018    /// Maps committed directory drafts before aggregate `CreateDir` emission.
1019    ///
1020    /// File drafts have no specialized callback and emit only aggregate
1021    /// [`FileExplorerAction::CreateFile`].
1022    ///
1023    /// # Examples
1024    ///
1025    /// ```
1026    /// use ailloli_ui_widgets::files::{FileExplorer, FileExplorerCreateDir};
1027    /// enum Action { Create(FileExplorerCreateDir) }
1028    /// let explorer = FileExplorer::<Action>::default().on_create_dir(Action::Create);
1029    /// let _ = explorer;
1030    /// ```
1031    pub fn on_create_dir(mut self, f: impl Fn(FileExplorerCreateDir) -> A + 'static) -> Self {
1032        self.on_create_dir = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1033        self
1034    }
1035
1036    /// Handles committed directory drafts with event-context access.
1037    ///
1038    /// # Examples
1039    ///
1040    /// ```
1041    /// use ailloli_ui_widgets::files::FileExplorer;
1042    /// let explorer = FileExplorer::<()>::default().on_create_dir_ctx(|_ctx, _event| {});
1043    /// let _ = explorer;
1044    /// ```
1045    pub fn on_create_dir_ctx(
1046        mut self,
1047        f: impl Fn(&mut EventCtx<A>, FileExplorerCreateDir) + 'static,
1048    ) -> Self {
1049        self.on_create_dir = Some(Rc::new(f));
1050        self
1051    }
1052}
1053
1054/// Converts the builder into an intent-only tree, optional scroll view, and menu.
1055impl<A: 'static> IntoView<A> for FileExplorer<A> {
1056    fn into_view(self) -> View<A> {
1057        finish_view_sized(
1058            View::component(FileExplorerComponent {
1059                input_identity: Rc::new(()),
1060                layout: self.layout,
1061                nodes: self.nodes,
1062                bound_nodes: self.bound_nodes,
1063                selected: self.selected,
1064                bound_selected: self.bound_selected,
1065                expanded: self.expanded,
1066                bound_expanded: self.bound_expanded,
1067                default_expanded: self.default_expanded,
1068                disabled: self.disabled,
1069                clipboard_can_paste: self.clipboard_can_paste,
1070                style: self.style,
1071                virtualized: self.virtualized,
1072                scrollable: self.scrollable,
1073                on_action: self.on_action,
1074                on_select: self.on_select,
1075                on_open: self.on_open,
1076                on_toggle: self.on_toggle,
1077                on_rename: self.on_rename,
1078                on_remove: self.on_remove,
1079                on_create_dir: self.on_create_dir,
1080            }),
1081            self.flex_item,
1082            LayoutSizeHint::from_layout(self.layout),
1083        )
1084    }
1085}
1086
1087/// Snapshot explorer component inputs retained across runtime builds.
1088struct FileExplorerComponent<A> {
1089    /// Identity of one declarative explorer payload across its own rebuilds.
1090    input_identity: Rc<()>,
1091    /// Outer logical sizing policy.
1092    layout: LayoutStyle,
1093    /// Read-only fallback flat file-node snapshot.
1094    nodes: Vec<FileExplorerNode>,
1095    /// Optional reactive authoritative node snapshot.
1096    bound_nodes: Option<Signal<Vec<FileExplorerNode>>>,
1097    /// Optional readable selected URI.
1098    selected: Option<Binding<FileUri>>,
1099    /// Optional writable selected URI.
1100    bound_selected: Option<Signal<FileUri>>,
1101    /// Optional readable expanded-directory URI list.
1102    expanded: Option<Binding<Vec<FileUri>>>,
1103    /// Optional writable expanded-directory URI list.
1104    bound_expanded: Option<Signal<Vec<FileUri>>>,
1105    /// Initial expansion list used for uncontrolled state.
1106    default_expanded: Vec<FileUri>,
1107    /// Reactive interaction-disable flag.
1108    disabled: Binding<bool>,
1109    /// Reactive capability indicating whether paste actions are available.
1110    clipboard_can_paste: Binding<bool>,
1111    /// Tree row colors and logical-pixel geometry.
1112    style: FileExplorerStyle,
1113    /// Whether visible rows are bounded to the propagated viewport.
1114    virtualized: bool,
1115    /// Whether the tree is wrapped in a vertical scroll viewport.
1116    scrollable: bool,
1117    /// Optional retained semantic-action callback.
1118    on_action: Option<ActionHandler<A>>,
1119    /// Optional retained selection callback.
1120    on_select: Option<UriHandler<A>>,
1121    /// Optional retained activation callback.
1122    on_open: Option<UriHandler<A>>,
1123    /// Optional retained expansion callback.
1124    on_toggle: Option<ToggleHandler<A>>,
1125    /// Optional retained rename callback.
1126    on_rename: Option<RenameHandler<A>>,
1127    /// Optional retained removal callback.
1128    on_remove: Option<RemoveHandler<A>>,
1129    /// Optional retained directory-creation callback.
1130    on_create_dir: Option<CreateDirHandler<A>>,
1131}
1132
1133/// Passive owner for the snapshot signal handed to the inner [`TreeView`].
1134///
1135/// Rebuilding the explorer for an unrelated menu/edit signal must not rewrite
1136/// the complete tree and enqueue another owner build. A genuinely replaced
1137/// declarative payload, or a new bound-node revision, swaps in a fresh
1138/// standalone source. The enclosing build already owns reconciliation of the
1139/// new source, so no redundant invalidation is emitted while it is running.
1140struct FileExplorerTreeSnapshot {
1141    /// Identity of the declarative component payload that supplied the nodes.
1142    input_identity: Rc<()>,
1143    /// Last bound-node revision projected into `signal`.
1144    bound_revision: Option<u64>,
1145    /// Snapshot source observed by the inner tree only.
1146    signal: Signal<Vec<TreeNode<FileUri>>>,
1147}
1148
1149impl FileExplorerTreeSnapshot {
1150    /// Creates the first retained projection without scheduling owner work.
1151    fn new(
1152        input_identity: Rc<()>,
1153        bound_revision: Option<u64>,
1154        nodes: Vec<TreeNode<FileUri>>,
1155    ) -> Self {
1156        Self {
1157            input_identity,
1158            bound_revision,
1159            signal: State::new(nodes).into_signal(),
1160        }
1161    }
1162
1163    /// Replaces the source only when the authoritative input actually changed.
1164    fn sync_input(
1165        &mut self,
1166        input_identity: &Rc<()>,
1167        bound_revision: Option<u64>,
1168        nodes: Vec<TreeNode<FileUri>>,
1169    ) {
1170        if Rc::ptr_eq(&self.input_identity, input_identity) && self.bound_revision == bound_revision
1171        {
1172            return;
1173        }
1174        let current = with_untracked_reads(|| self.signal.read());
1175        let nodes = preserve_transient_tree_nodes(current, nodes);
1176        self.input_identity = input_identity.clone();
1177        self.bound_revision = bound_revision;
1178        self.signal = State::new(nodes).into_signal();
1179    }
1180
1181    /// Refreshes one bound snapshot after an action callback mutated its source.
1182    fn sync_bound_nodes(&mut self, nodes: &Signal<Vec<FileExplorerNode>>) {
1183        let revision = nodes.revision();
1184        if self.bound_revision == Some(revision) {
1185            return;
1186        }
1187        let mut nodes = nodes.read();
1188        sort_file_nodes(&mut nodes);
1189        let next = nodes.iter().map(to_tree_node).collect::<Vec<_>>();
1190        let next = preserve_transient_tree_nodes(self.signal.read(), next);
1191        self.bound_revision = Some(revision);
1192        self.signal = State::new(next).into_signal();
1193    }
1194}
1195
1196/// Retains one standalone source in a component hook slot.
1197///
1198/// The outer hook signal never changes; the inner source is observed and
1199/// invalidated only by the nested retained consumer that reads it.
1200fn retained_standalone_signal<A: 'static, T: 'static>(
1201    context: &mut Context<A>,
1202    initial: T,
1203) -> Signal<T> {
1204    context
1205        .signal_with(|| State::new(initial))
1206        .read()
1207        .into_signal()
1208}
1209
1210/// Builds a sorted intent-only tree plus transient edit and context-menu wiring.
1211impl<A: 'static> ComponentNode<A> for FileExplorerComponent<A> {
1212    fn build(&self, context: &mut Context<A>) -> View<A> {
1213        let mut nodes = self
1214            .bound_nodes
1215            .as_ref()
1216            .map(Signal::read)
1217            .unwrap_or_else(|| self.nodes.clone());
1218        sort_file_nodes(&mut nodes);
1219
1220        let tree_nodes = nodes.iter().map(to_tree_node).collect::<Vec<_>>();
1221        let bound_revision = self.bound_nodes.as_ref().map(Signal::revision);
1222        let mut initial_tree_nodes = Some(tree_nodes);
1223        let tree_snapshot = context
1224            .signal_with(|| {
1225                Rc::new(RefCell::new(FileExplorerTreeSnapshot::new(
1226                    self.input_identity.clone(),
1227                    bound_revision,
1228                    initial_tree_nodes
1229                        .take()
1230                        .expect("initial file explorer tree snapshot"),
1231                )))
1232            })
1233            .read();
1234        if let Some(tree_nodes) = initial_tree_nodes {
1235            tree_snapshot
1236                .borrow_mut()
1237                .sync_input(&self.input_identity, bound_revision, tree_nodes);
1238        }
1239        let tree_nodes_signal = tree_snapshot.borrow().signal.clone();
1240        // These values belong to the nested menu/tree consumers. Standalone
1241        // sources let exact dependency tracking rebuild or relayout only that
1242        // consumer instead of invoking FileExplorer's historical Build edge.
1243        let menu_open = retained_standalone_signal(context, false);
1244        let menu_anchor = retained_standalone_signal(context, Point::default());
1245        let menu_entries = retained_standalone_signal(context, Vec::<ContextMenuEntry<A>>::new());
1246        let tree_command = retained_standalone_signal(context, None::<TreeViewCommand<FileUri>>);
1247        let tree_focus_key = format!("ailloli_ui-file-explorer-tree-{}", context.element_id().0);
1248        let menu_focus_key = format!(
1249            "ailloli_ui-file-explorer-context-menu-{}",
1250            context.element_id().0
1251        );
1252        let request_tree_layout = context.invalidation_target(Invalidation::Layout);
1253        let tree_commands = FileExplorerTreeCommands {
1254            rename: {
1255                let tree_command = tree_command.clone();
1256                let tree_focus_key = tree_focus_key.clone();
1257                let request_tree_layout = request_tree_layout.clone();
1258                Rc::new(move |ctx, uri| {
1259                    tree_command.set(Some(TreeViewCommand::BeginRename(uri)));
1260                    ctx.request_focus_key(tree_focus_key.clone());
1261                    request_tree_layout();
1262                })
1263            },
1264            create: {
1265                let tree_command = tree_command.clone();
1266                let tree_focus_key = tree_focus_key.clone();
1267                let request_tree_layout = request_tree_layout.clone();
1268                Rc::new(move |ctx, parent, default_label| {
1269                    tree_command.set(Some(TreeViewCommand::BeginCreate(TreeCreateRequest {
1270                        parent: Some(parent),
1271                        after: None,
1272                        kind: TreeCreateKind::Child,
1273                        default_label: default_label.to_string(),
1274                    })));
1275                    ctx.request_focus_key(tree_focus_key.clone());
1276                    request_tree_layout();
1277                })
1278            },
1279        };
1280
1281        let mut tree = TreeView::new()
1282            .bind_nodes(tree_nodes_signal.clone())
1283            .bind_command(tree_command.clone())
1284            .disabled(self.disabled.clone())
1285            .mutation_mode(TreeMutationMode::IntentOnly)
1286            .tree_style(self.style.tree.clone())
1287            .virtualized(self.virtualized);
1288        if !self.scrollable {
1289            tree.layout = self.layout;
1290        }
1291
1292        if let Some(bound_selected) = &self.bound_selected {
1293            tree = tree.bind_selected(bound_selected.clone());
1294        } else if let Some(selected) = &self.selected {
1295            tree = tree.selected(selected.clone());
1296        }
1297
1298        if let Some(bound_expanded) = &self.bound_expanded {
1299            tree = tree.bind_expanded(bound_expanded.clone());
1300        } else if let Some(expanded) = &self.expanded {
1301            tree = tree.expanded(expanded.clone());
1302        } else {
1303            tree = tree.default_expanded_many(self.default_expanded.clone());
1304        }
1305        let expanded_for_menu = if let Some(bound_expanded) = &self.bound_expanded {
1306            Binding::Signal(bound_expanded.clone())
1307        } else if let Some(expanded) = &self.expanded {
1308            expanded.clone()
1309        } else {
1310            Binding::Static(self.default_expanded.clone())
1311        };
1312
1313        let on_action = self.on_action.clone();
1314        let on_select = self.on_select.clone();
1315        tree = tree.on_select_ctx(move |ctx, uri| {
1316            if let Some(handler) = &on_select {
1317                handler(ctx, uri.clone());
1318            }
1319            emit_action(ctx, &on_action, FileExplorerAction::Select(uri));
1320        });
1321
1322        let on_action = self.on_action.clone();
1323        let on_open = self.on_open.clone();
1324        tree = tree.on_activate_ctx(move |ctx, uri| {
1325            if let Some(handler) = &on_open {
1326                handler(ctx, uri.clone());
1327            }
1328            emit_action(ctx, &on_action, FileExplorerAction::Open(uri));
1329        });
1330
1331        let on_action = self.on_action.clone();
1332        let on_toggle = self.on_toggle.clone();
1333        let bound_nodes_for_toggle = self.bound_nodes.clone();
1334        let tree_snapshot_for_toggle = tree_snapshot.clone();
1335        tree = tree.on_toggle_ctx(move |ctx, uri, expanded| {
1336            if let Some(handler) = &on_toggle {
1337                handler(ctx, uri.clone(), expanded);
1338            }
1339            emit_action(
1340                ctx,
1341                &on_action,
1342                FileExplorerAction::Toggle { uri, expanded },
1343            );
1344            sync_bound_tree_nodes(&bound_nodes_for_toggle, &tree_snapshot_for_toggle);
1345        });
1346
1347        if self.on_action.is_some() || self.on_remove.is_some() {
1348            let nodes_for_shortcuts = nodes.clone();
1349            let on_action = self.on_action.clone();
1350            let on_remove = self.on_remove.clone();
1351            let clipboard_can_paste = self.clipboard_can_paste.clone();
1352            tree = tree.on_shortcut_ctx(move |ctx, shortcut| {
1353                dispatch_file_shortcut(
1354                    ctx,
1355                    &nodes_for_shortcuts,
1356                    clipboard_can_paste.read(),
1357                    &on_action,
1358                    &on_remove,
1359                    shortcut,
1360                );
1361            });
1362        }
1363
1364        if self.on_action.is_some() {
1365            let nodes_for_move = nodes.clone();
1366            let on_action = self.on_action.clone();
1367            tree = tree.draggable(true).on_move_ctx(move |ctx, event| {
1368                if let Some(action) = file_move_action_from_tree_move(&nodes_for_move, event) {
1369                    emit_action(ctx, &on_action, action);
1370                }
1371            });
1372        }
1373
1374        if self.on_rename.is_some() || self.on_action.is_some() {
1375            let on_action = self.on_action.clone();
1376            let on_rename = self.on_rename.clone();
1377            tree = tree.editable(true).on_rename_ctx(move |ctx, event| {
1378                let event = FileExplorerRename {
1379                    uri: event.id,
1380                    old_name: event.old_label,
1381                    new_name: event.new_label,
1382                };
1383                if let Some(handler) = &on_rename {
1384                    handler(ctx, event.clone());
1385                }
1386                emit_action(ctx, &on_action, FileExplorerAction::Rename(event));
1387            });
1388        }
1389
1390        if self.on_remove.is_some() || self.on_action.is_some() {
1391            let on_action = self.on_action.clone();
1392            let on_remove = self.on_remove.clone();
1393            tree = tree.deletable(true).on_delete_ctx(move |ctx, event| {
1394                if let Some(handler) = &on_remove {
1395                    handler(ctx, event.id.clone(), event.parent.clone());
1396                }
1397                emit_action(
1398                    ctx,
1399                    &on_action,
1400                    FileExplorerAction::Remove {
1401                        uri: event.id,
1402                        parent: event.parent,
1403                    },
1404                );
1405            });
1406        }
1407
1408        if self.on_create_dir.is_some() || self.on_action.is_some() {
1409            let on_action = self.on_action.clone();
1410            let on_create_dir = self.on_create_dir.clone();
1411            tree = tree
1412                .creatable(true)
1413                .create_node_with(create_explorer_node)
1414                .on_create_ctx(move |ctx, event| {
1415                    let is_file = is_create_file_id(&event.id);
1416                    let parent = event.parent.clone().or_else(|| event.id.parent());
1417                    let uri = create_uri_from_event(&event.id, parent.as_ref(), &event.label);
1418                    if is_file {
1419                        emit_action(
1420                            ctx,
1421                            &on_action,
1422                            FileExplorerAction::CreateFile(FileExplorerCreateFile {
1423                                uri,
1424                                parent,
1425                                after: event.after,
1426                                name: event.label,
1427                            }),
1428                        );
1429                    } else {
1430                        let event = FileExplorerCreateDir {
1431                            uri,
1432                            parent,
1433                            after: event.after,
1434                            name: event.label,
1435                        };
1436                        if let Some(handler) = &on_create_dir {
1437                            handler(ctx, event.clone());
1438                        }
1439                        emit_action(ctx, &on_action, FileExplorerAction::CreateDir(event));
1440                    }
1441                });
1442        }
1443
1444        {
1445            let nodes_for_menu = nodes.clone();
1446            let on_action = self.on_action.clone();
1447            let on_open = self.on_open.clone();
1448            let on_rename = self.on_rename.clone();
1449            let on_remove = self.on_remove.clone();
1450            let on_create_dir = self.on_create_dir.clone();
1451            let clipboard_can_paste = self.clipboard_can_paste.clone();
1452            let expanded_for_menu = expanded_for_menu.clone();
1453            let selected_for_menu = self.selected.clone();
1454            let menu_open_for_tree = menu_open.clone();
1455            let menu_anchor_for_tree = menu_anchor.clone();
1456            let menu_entries_for_tree = menu_entries.clone();
1457            let tree_commands_for_menu = tree_commands.clone();
1458            let menu_focus_key_for_tree = menu_focus_key.clone();
1459            tree = tree.on_context_menu_ctx(move |ctx, event| {
1460                let entries = build_context_menu_entries(
1461                    &nodes_for_menu,
1462                    &expanded_for_menu.read(),
1463                    clipboard_can_paste.read(),
1464                    &on_action,
1465                    &on_open,
1466                    &on_rename,
1467                    &on_remove,
1468                    &on_create_dir,
1469                    selected_for_menu.as_ref().map(Binding::read),
1470                    tree_commands_for_menu.clone(),
1471                    event.clone(),
1472                );
1473                let anchor = match event {
1474                    TreeContextMenu::Row {
1475                        pointer_position, ..
1476                    }
1477                    | TreeContextMenu::Blank { pointer_position } => pointer_position,
1478                };
1479                menu_anchor_for_tree.set(anchor);
1480                menu_entries_for_tree.set(entries);
1481                menu_open_for_tree.set(true);
1482                ctx.request_focus_key(menu_focus_key_for_tree.clone());
1483            });
1484        }
1485
1486        let tree_view = tree.into_view().key(tree_focus_key);
1487        let content = if self.scrollable {
1488            let mut viewport = Container::new().child(ScrollView::vertical().child(tree_view));
1489            *viewport.layout_mut() = self.layout;
1490            viewport.into_view()
1491        } else {
1492            tree_view
1493        };
1494        ContextMenu::new(content)
1495            .bind_open(menu_open)
1496            .bind_anchor(menu_anchor)
1497            .bind_entries(menu_entries)
1498            .into_view()
1499            .key(menu_focus_key)
1500    }
1501}
1502
1503/// Filesystem explorer backed by a retained [`TreeModelHandle`]. Node
1504/// metadata is resolved only for the row being interacted with; ordinary
1505/// build, layout, paint, and scroll never reconstruct a recursive snapshot.
1506///
1507/// The inner tree is always virtualized and uses intent-only mutation mode.
1508/// Callers own the authoritative model/store and apply emitted identity-aware
1509/// events. Reserved create IDs must be unique and must remain valid until commit
1510/// or the matching release callback.
1511///
1512/// # Examples
1513///
1514/// ```
1515/// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1516/// use ailloli_ui_widgets::files::RetainedFileExplorer;
1517/// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1518/// let explorer = RetainedFileExplorer::<u64, ()>::new(
1519///     model, |_| None, |_| None, |_parent, _kind| Some(1), |_id| {},
1520/// );
1521/// let _ = explorer;
1522/// ```
1523pub struct RetainedFileExplorer<T, A = ()> {
1524    /// Standard logical-pixel size and position constraints.
1525    pub(crate) layout: LayoutStyle,
1526    /// Standard flex-parent participation settings.
1527    pub(crate) flex_item: FlexItemStyle,
1528    /// Retained generic tree model and its revisioned state.
1529    model: TreeModelHandle<T>,
1530    /// Resolver mapping stable model IDs to file explorer rows.
1531    resolve_node: RetainedNodeResolver<T>,
1532    /// Resolver mapping canonical URIs back to stable model IDs.
1533    resolve_id: RetainedIdResolver<T>,
1534    /// Reservation callback used before inline create commits.
1535    reserve_node: RetainedNodeReserve<T>,
1536    /// Release callback used when a reserved create is cancelled.
1537    release_node: RetainedNodeRelease<T>,
1538    /// Optional readable selected model ID.
1539    selected: Option<Binding<T>>,
1540    /// Optional writable selected model ID.
1541    bound_selected: Option<Signal<T>>,
1542    /// Reactive interaction-disable flag.
1543    disabled: Binding<bool>,
1544    /// Reactive capability indicating whether paste actions are available.
1545    clipboard_can_paste: Binding<bool>,
1546    /// Tree row colors and logical-pixel geometry.
1547    style: FileExplorerStyle,
1548    /// Whether the tree is wrapped in a vertical scroll viewport.
1549    scrollable: bool,
1550    /// Optional worker/cache diagnostic snapshot displayed by the tree.
1551    diagnostics: Option<TreeViewDiagnostics>,
1552    /// Optional callback receiving semantic explorer actions.
1553    on_action: Option<ActionHandler<A>>,
1554    /// Optional callback receiving retained-model events.
1555    on_model_event: Option<RetainedEventHandler<T, A>>,
1556}
1557
1558/// Exposes standard layout mutation to generated extension/builders.
1559impl<T, A> LayoutExt for RetainedFileExplorer<T, A> {
1560    fn layout_mut(&mut self) -> &mut LayoutStyle {
1561        &mut self.layout
1562    }
1563}
1564
1565impl<T, A> RetainedFileExplorer<T, A>
1566where
1567    T: Clone + Eq + Hash + fmt::Debug + 'static,
1568    A: 'static,
1569{
1570    /// Creates a virtualized explorer over an authoritative retained model.
1571    ///
1572    /// `resolve_node` supplies current URI/metadata for one ID, `resolve_id`
1573    /// maps context-menu URI commands back to identity, `reserve_node` allocates
1574    /// a transient file/directory draft ID, and `release_node` rolls it back on
1575    /// cancellation or invalid commit. Returning `None` rejects that operation.
1576    ///
1577    /// # Examples
1578    ///
1579    /// ```
1580    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1581    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1582    /// let model = TreeModelHandle::new(TreeModel::<u32>::new());
1583    /// let explorer = RetainedFileExplorer::<u32, ()>::new(
1584    ///     model, |_| None, |_| None, |_parent, _kind| Some(10), |_id| {},
1585    /// );
1586    /// let _ = explorer;
1587    /// ```
1588    pub fn new(
1589        model: TreeModelHandle<T>,
1590        resolve_node: impl Fn(T) -> Option<FileExplorerNode> + 'static,
1591        resolve_id: impl Fn(&FileUri) -> Option<T> + 'static,
1592        reserve_node: impl Fn(Option<&T>, FileKind) -> Option<T> + 'static,
1593        release_node: impl Fn(T) + 'static,
1594    ) -> Self {
1595        Self {
1596            layout: LayoutStyle::default(),
1597            flex_item: FlexItemStyle::default(),
1598            model,
1599            resolve_node: Rc::new(resolve_node),
1600            resolve_id: Rc::new(resolve_id),
1601            reserve_node: Rc::new(reserve_node),
1602            release_node: Rc::new(release_node),
1603            selected: None,
1604            bound_selected: None,
1605            disabled: Binding::Static(false),
1606            clipboard_can_paste: Binding::Static(false),
1607            style: FileExplorerStyle::default(),
1608            scrollable: true,
1609            diagnostics: None,
1610            on_action: None,
1611            on_model_event: None,
1612        }
1613    }
1614
1615    /// Sets static/generic retained selection and clears writable selection state.
1616    ///
1617    /// # Examples
1618    ///
1619    /// ```
1620    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1621    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1622    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1623    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).selected(1);
1624    /// let _ = explorer;
1625    /// ```
1626    pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
1627        self.selected = Some(selected.into());
1628        self.bound_selected = None;
1629        self
1630    }
1631
1632    /// Binds selection to writable shared retained identity state.
1633    ///
1634    /// # Examples
1635    ///
1636    /// ```
1637    /// use ailloli_ui_runtime::component::State;
1638    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1639    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1640    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1641    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).bind_selected(State::new(1));
1642    /// let _ = explorer;
1643    /// ```
1644    pub fn bind_selected(mut self, selected: impl Into<Signal<T>>) -> Self {
1645        let selected = selected.into();
1646        self.selected = Some(Binding::Signal(selected.clone()));
1647        self.bound_selected = Some(selected);
1648        self
1649    }
1650
1651    /// Binds whether retained-tree interaction is disabled.
1652    ///
1653    /// # Examples
1654    ///
1655    /// ```
1656    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1657    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1658    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1659    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).disabled(true);
1660    /// let _ = explorer;
1661    /// ```
1662    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
1663        self.disabled = disabled.into();
1664        self
1665    }
1666
1667    /// Binds keyboard and blank-menu paste eligibility.
1668    ///
1669    /// # Examples
1670    ///
1671    /// ```
1672    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1673    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1674    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1675    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).clipboard_can_paste(true);
1676    /// let _ = explorer;
1677    /// ```
1678    pub fn clipboard_can_paste(mut self, can_paste: impl Into<Binding<bool>>) -> Self {
1679        self.clipboard_can_paste = can_paste.into();
1680        self
1681    }
1682
1683    /// Replaces the complete retained tree style.
1684    ///
1685    /// # Examples
1686    ///
1687    /// ```
1688    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1689    /// use ailloli_ui_widgets::files::{FileExplorerStyle, RetainedFileExplorer};
1690    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1691    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).file_style(FileExplorerStyle::default());
1692    /// let _ = explorer;
1693    /// ```
1694    pub fn file_style(mut self, style: FileExplorerStyle) -> Self {
1695        self.style = style;
1696        self
1697    }
1698
1699    /// Applies a density preset under the default theme, replacing prior style.
1700    ///
1701    /// # Examples
1702    ///
1703    /// ```
1704    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1705    /// use ailloli_ui_widgets::files::{FileExplorerSize, RetainedFileExplorer};
1706    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1707    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).file_size(FileExplorerSize::Compact);
1708    /// let _ = explorer;
1709    /// ```
1710    pub fn file_size(mut self, size: FileExplorerSize) -> Self {
1711        self.style = FileExplorerStyle::from_theme(Theme::default(), size);
1712        self
1713    }
1714
1715    /// Wraps the retained tree in a vertical scroll view when true.
1716    ///
1717    /// Scrolling defaults to true; row virtualization remains enabled either way.
1718    ///
1719    /// # Examples
1720    ///
1721    /// ```
1722    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1723    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1724    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1725    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).scrollable(false);
1726    /// let _ = explorer;
1727    /// ```
1728    pub fn scrollable(mut self, scrollable: bool) -> Self {
1729        self.scrollable = scrollable;
1730        self
1731    }
1732
1733    /// Attaches permanent structural counters to the retained tree.
1734    ///
1735    /// The handle is UI-local and does not affect model ownership or worker
1736    /// scheduling. It is intended for performance gates and diagnostics.
1737    ///
1738    /// # Examples
1739    ///
1740    /// ```
1741    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle, TreeViewDiagnostics};
1742    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1743    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1744    /// let diagnostics = TreeViewDiagnostics::new();
1745    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).tree_diagnostics(diagnostics.clone());
1746    /// assert_eq!(diagnostics.snapshot().layout_calls, 0);
1747    /// let _ = explorer;
1748    /// ```
1749    pub fn tree_diagnostics(mut self, diagnostics: TreeViewDiagnostics) -> Self {
1750        self.diagnostics = Some(diagnostics);
1751        self
1752    }
1753
1754    /// Maps high-level URI actions into application actions.
1755    ///
1756    /// Identity-aware model events are emitted separately and first where both
1757    /// representations exist.
1758    ///
1759    /// # Examples
1760    ///
1761    /// ```
1762    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1763    /// use ailloli_ui_widgets::files::{FileExplorerAction, RetainedFileExplorer};
1764    /// enum Action { Explorer(FileExplorerAction) }
1765    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1766    /// let explorer = RetainedFileExplorer::<u64, Action>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).on_action(Action::Explorer);
1767    /// let _ = explorer;
1768    /// ```
1769    pub fn on_action(mut self, f: impl Fn(FileExplorerAction) -> A + 'static) -> Self {
1770        self.on_action = Some(Rc::new(move |ctx, action| ctx.dispatch(f(action))));
1771        self
1772    }
1773
1774    /// Handles high-level URI actions with event-context access.
1775    ///
1776    /// # Examples
1777    ///
1778    /// ```
1779    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1780    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1781    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1782    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).on_action_ctx(|_ctx, _action| {});
1783    /// let _ = explorer;
1784    /// ```
1785    pub fn on_action_ctx(
1786        mut self,
1787        f: impl Fn(&mut EventCtx<A>, FileExplorerAction) + 'static,
1788    ) -> Self {
1789        self.on_action = Some(Rc::new(f));
1790        self
1791    }
1792
1793    /// Maps identity-aware select/open/toggle/edit events into application actions.
1794    ///
1795    /// # Examples
1796    ///
1797    /// ```
1798    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1799    /// use ailloli_ui_widgets::files::{FileExplorerModelEvent, RetainedFileExplorer};
1800    /// enum Action { Model(FileExplorerModelEvent<u64>) }
1801    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1802    /// let explorer = RetainedFileExplorer::<u64, Action>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).on_model_event(Action::Model);
1803    /// let _ = explorer;
1804    /// ```
1805    pub fn on_model_event(mut self, f: impl Fn(FileExplorerModelEvent<T>) -> A + 'static) -> Self {
1806        self.on_model_event = Some(Rc::new(move |ctx, event| ctx.dispatch(f(event))));
1807        self
1808    }
1809
1810    /// Handles identity-aware events with direct event-context access.
1811    ///
1812    /// # Examples
1813    ///
1814    /// ```
1815    /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1816    /// use ailloli_ui_widgets::files::RetainedFileExplorer;
1817    /// let model = TreeModelHandle::new(TreeModel::<u64>::new());
1818    /// let explorer = RetainedFileExplorer::<u64, ()>::new(model, |_| None, |_| None, |_, _| Some(1), |_| {}).on_model_event_ctx(|_ctx, _event| {});
1819    /// let _ = explorer;
1820    /// ```
1821    pub fn on_model_event_ctx(
1822        mut self,
1823        f: impl Fn(&mut EventCtx<A>, FileExplorerModelEvent<T>) + 'static,
1824    ) -> Self {
1825        self.on_model_event = Some(Rc::new(f));
1826        self
1827    }
1828}
1829
1830/// Converts the retained adapter into a virtualized tree and context-menu view.
1831impl<T, A> IntoView<A> for RetainedFileExplorer<T, A>
1832where
1833    T: Clone + Eq + Hash + fmt::Debug + 'static,
1834    A: 'static,
1835{
1836    fn into_view(self) -> View<A> {
1837        finish_view_sized(
1838            View::component(RetainedFileExplorerComponent {
1839                layout: self.layout,
1840                model: self.model,
1841                resolve_node: self.resolve_node,
1842                resolve_id: self.resolve_id,
1843                reserve_node: self.reserve_node,
1844                release_node: self.release_node,
1845                selected: self.selected,
1846                bound_selected: self.bound_selected,
1847                disabled: self.disabled,
1848                clipboard_can_paste: self.clipboard_can_paste,
1849                style: self.style,
1850                scrollable: self.scrollable,
1851                diagnostics: self.diagnostics,
1852                on_action: self.on_action,
1853                on_model_event: self.on_model_event,
1854            }),
1855            self.flex_item,
1856            LayoutSizeHint::from_layout(self.layout),
1857        )
1858    }
1859}
1860
1861/// Retained-model explorer inputs and identity resolver lifecycle callbacks.
1862struct RetainedFileExplorerComponent<T, A> {
1863    /// Outer logical sizing policy.
1864    layout: LayoutStyle,
1865    /// Retained generic tree model and its revisioned state.
1866    model: TreeModelHandle<T>,
1867    /// Resolver mapping stable model IDs to file explorer rows.
1868    resolve_node: RetainedNodeResolver<T>,
1869    /// Resolver mapping canonical URIs back to stable model IDs.
1870    resolve_id: RetainedIdResolver<T>,
1871    /// Reservation callback used before inline create commits.
1872    reserve_node: RetainedNodeReserve<T>,
1873    /// Release callback used when a reserved create is cancelled.
1874    release_node: RetainedNodeRelease<T>,
1875    /// Optional readable selected model ID.
1876    selected: Option<Binding<T>>,
1877    /// Optional writable selected model ID.
1878    bound_selected: Option<Signal<T>>,
1879    /// Reactive interaction-disable flag.
1880    disabled: Binding<bool>,
1881    /// Reactive capability indicating whether paste actions are available.
1882    clipboard_can_paste: Binding<bool>,
1883    /// Tree row colors and logical-pixel geometry.
1884    style: FileExplorerStyle,
1885    /// Whether the tree is wrapped in a vertical scroll viewport.
1886    scrollable: bool,
1887    /// Optional worker/cache diagnostic snapshot displayed by the tree.
1888    diagnostics: Option<TreeViewDiagnostics>,
1889    /// Optional retained semantic-action callback.
1890    on_action: Option<ActionHandler<A>>,
1891    /// Optional retained model-event callback.
1892    on_model_event: Option<RetainedEventHandler<T, A>>,
1893}
1894
1895/// Wires direct model virtualization to identity-aware interactions and drafts.
1896impl<T, A> ComponentNode<A> for RetainedFileExplorerComponent<T, A>
1897where
1898    T: Clone + Eq + Hash + fmt::Debug + 'static,
1899    A: 'static,
1900{
1901    fn build(&self, context: &mut Context<A>) -> View<A> {
1902        let menu_open = context.signal(false);
1903        let menu_anchor = context.signal(Point::default());
1904        let menu_entries = context.signal(Vec::<ContextMenuEntry<A>>::new());
1905        let tree_command = context.signal(None::<TreeViewCommand<T>>);
1906        let draft_kinds = context
1907            .signal_with(|| Rc::new(RefCell::new(HashMap::<T, FileKind>::new())))
1908            .read();
1909        let tree_focus_key = format!(
1910            "ailloli_ui-retained-file-explorer-tree-{}",
1911            context.element_id().0
1912        );
1913        let menu_focus_key = format!(
1914            "ailloli_ui-retained-file-explorer-context-menu-{}",
1915            context.element_id().0
1916        );
1917        let request_tree_layout = context.invalidation_target(Invalidation::Layout);
1918
1919        let tree_commands = FileExplorerTreeCommands {
1920            rename: {
1921                let resolve_id = self.resolve_id.clone();
1922                let tree_command = tree_command.clone();
1923                let tree_focus_key = tree_focus_key.clone();
1924                let request_tree_layout = request_tree_layout.clone();
1925                Rc::new(move |ctx, uri| {
1926                    let Some(node_id) = resolve_id(&uri) else {
1927                        return;
1928                    };
1929                    tree_command.set(Some(TreeViewCommand::BeginRename(node_id)));
1930                    ctx.request_focus_key(tree_focus_key.clone());
1931                    request_tree_layout();
1932                })
1933            },
1934            create: {
1935                let resolve_id = self.resolve_id.clone();
1936                let tree_command = tree_command.clone();
1937                let tree_focus_key = tree_focus_key.clone();
1938                let request_tree_layout = request_tree_layout.clone();
1939                Rc::new(move |ctx, parent, default_label| {
1940                    let Some(parent) = resolve_id(&parent) else {
1941                        return;
1942                    };
1943                    tree_command.set(Some(TreeViewCommand::BeginCreate(TreeCreateRequest {
1944                        parent: Some(parent),
1945                        after: None,
1946                        kind: TreeCreateKind::Child,
1947                        default_label: default_label.to_string(),
1948                    })));
1949                    ctx.request_focus_key(tree_focus_key.clone());
1950                    request_tree_layout();
1951                })
1952            },
1953        };
1954
1955        let mut tree = TreeView::new()
1956            .model(self.model.clone())
1957            .bind_command(tree_command)
1958            .disabled(self.disabled.clone())
1959            .mutation_mode(TreeMutationMode::IntentOnly)
1960            .tree_style(self.style.tree.clone())
1961            .virtualized(true);
1962        if let Some(diagnostics) = &self.diagnostics {
1963            tree = tree.diagnostics(diagnostics.clone());
1964        }
1965        if !self.scrollable {
1966            tree.layout = self.layout;
1967        }
1968        if let Some(selected) = &self.bound_selected {
1969            tree = tree.bind_selected(selected.clone());
1970        } else if let Some(selected) = &self.selected {
1971            tree = tree.selected(selected.clone());
1972        }
1973
1974        let resolve_node = self.resolve_node.clone();
1975        let on_action = self.on_action.clone();
1976        let on_model_event = self.on_model_event.clone();
1977        tree = tree.on_select_ctx(move |ctx, node_id| {
1978            let Some(node) = resolve_node(node_id.clone()) else {
1979                return;
1980            };
1981            emit_model_event(
1982                ctx,
1983                &on_model_event,
1984                FileExplorerModelEvent::Select {
1985                    node_id,
1986                    uri: node.entry.uri.clone(),
1987                },
1988            );
1989            emit_action(ctx, &on_action, FileExplorerAction::Select(node.entry.uri));
1990        });
1991
1992        let resolve_node = self.resolve_node.clone();
1993        let on_action = self.on_action.clone();
1994        let on_model_event = self.on_model_event.clone();
1995        tree = tree.on_activate_ctx(move |ctx, node_id| {
1996            let Some(node) = resolve_node(node_id.clone()) else {
1997                return;
1998            };
1999            emit_model_event(
2000                ctx,
2001                &on_model_event,
2002                FileExplorerModelEvent::Open {
2003                    node_id,
2004                    uri: node.entry.uri.clone(),
2005                },
2006            );
2007            emit_action(ctx, &on_action, FileExplorerAction::Open(node.entry.uri));
2008        });
2009
2010        let resolve_node = self.resolve_node.clone();
2011        let on_action = self.on_action.clone();
2012        let on_model_event = self.on_model_event.clone();
2013        tree = tree.on_toggle_ctx(move |ctx, node_id, expanded| {
2014            let Some(node) = resolve_node(node_id.clone()) else {
2015                return;
2016            };
2017            emit_model_event(
2018                ctx,
2019                &on_model_event,
2020                FileExplorerModelEvent::Toggle {
2021                    node_id,
2022                    uri: node.entry.uri.clone(),
2023                    expanded,
2024                },
2025            );
2026            emit_action(
2027                ctx,
2028                &on_action,
2029                FileExplorerAction::Toggle {
2030                    uri: node.entry.uri,
2031                    expanded,
2032                },
2033            );
2034        });
2035
2036        let resolve_node = self.resolve_node.clone();
2037        let model = self.model.clone();
2038        let on_action = self.on_action.clone();
2039        let on_model_event = self.on_model_event.clone();
2040        tree = tree.draggable(true).on_move_ctx(move |ctx, event| {
2041            let Some((node_id, target_parent_id, movement)) =
2042                retained_file_move(&model, &resolve_node, event)
2043            else {
2044                return;
2045            };
2046            emit_model_event(
2047                ctx,
2048                &on_model_event,
2049                FileExplorerModelEvent::Move {
2050                    node_id,
2051                    target_parent_id,
2052                    movement: movement.clone(),
2053                },
2054            );
2055            emit_action(ctx, &on_action, FileExplorerAction::MoveEntry(movement));
2056        });
2057
2058        let resolve_node = self.resolve_node.clone();
2059        let on_action = self.on_action.clone();
2060        let on_model_event = self.on_model_event.clone();
2061        tree = tree.editable(true).on_rename_ctx(move |ctx, event| {
2062            let Some(node) = resolve_node(event.id.clone()) else {
2063                return;
2064            };
2065            let rename = FileExplorerRename {
2066                uri: node.entry.uri,
2067                old_name: event.old_label,
2068                new_name: event.new_label,
2069            };
2070            emit_model_event(
2071                ctx,
2072                &on_model_event,
2073                FileExplorerModelEvent::Rename {
2074                    node_id: event.id,
2075                    rename: rename.clone(),
2076                },
2077            );
2078            emit_action(ctx, &on_action, FileExplorerAction::Rename(rename));
2079        });
2080
2081        let reserve_node = self.reserve_node.clone();
2082        let draft_kinds_for_create = draft_kinds.clone();
2083        tree = tree.creatable(true).create_node_with(move |request| {
2084            let kind = if request.default_label == NEW_FILE_NAME {
2085                FileKind::File
2086            } else {
2087                FileKind::Directory
2088            };
2089            let node_id = reserve_node(request.parent.as_ref(), kind)?;
2090            draft_kinds_for_create
2091                .borrow_mut()
2092                .insert(node_id.clone(), kind);
2093            Some(if kind == FileKind::File {
2094                TreeNode::leaf(node_id, request.default_label)
2095                    .leading_icon(IconId::Devicon('\u{f15b}'))
2096                    .leading_icon_tint(ailloli_ui_core::Color::hex_rgb(0x94a3b8))
2097                    .transient(true)
2098            } else {
2099                TreeNode::branch(node_id, request.default_label)
2100                    .leading_icon(IconId::Devicon('\u{f07b}'))
2101                    .leading_icon_tint(ailloli_ui_core::Color::hex_rgb(0xf59e0b))
2102                    .transient(true)
2103            })
2104        });
2105
2106        let resolve_node = self.resolve_node.clone();
2107        let on_action = self.on_action.clone();
2108        let on_model_event = self.on_model_event.clone();
2109        let release_failed_create = self.release_node.clone();
2110        let draft_kinds_for_commit = draft_kinds.clone();
2111        tree = tree.on_create_ctx(move |ctx, event| {
2112            let Some(kind) = draft_kinds_for_commit.borrow_mut().remove(&event.id) else {
2113                return;
2114            };
2115            let Some(parent_id) = event.parent else {
2116                release_failed_create(event.id);
2117                return;
2118            };
2119            let Some(parent) = resolve_node(parent_id.clone()) else {
2120                release_failed_create(event.id);
2121                return;
2122            };
2123            let Ok(uri) = parent.entry.uri.join_child(&event.label) else {
2124                release_failed_create(event.id);
2125                return;
2126            };
2127            emit_model_event(
2128                ctx,
2129                &on_model_event,
2130                FileExplorerModelEvent::Create {
2131                    node_id: event.id.clone(),
2132                    parent_id,
2133                    kind,
2134                    uri: uri.clone(),
2135                    name: event.label.clone(),
2136                },
2137            );
2138            if kind == FileKind::File {
2139                emit_action(
2140                    ctx,
2141                    &on_action,
2142                    FileExplorerAction::CreateFile(FileExplorerCreateFile {
2143                        uri,
2144                        parent: Some(parent.entry.uri),
2145                        after: None,
2146                        name: event.label,
2147                    }),
2148                );
2149            } else {
2150                emit_action(
2151                    ctx,
2152                    &on_action,
2153                    FileExplorerAction::CreateDir(FileExplorerCreateDir {
2154                        uri,
2155                        parent: Some(parent.entry.uri),
2156                        after: None,
2157                        name: event.label,
2158                    }),
2159                );
2160            }
2161        });
2162
2163        let release_node = self.release_node.clone();
2164        let on_model_event = self.on_model_event.clone();
2165        let draft_kinds_for_cancel = draft_kinds;
2166        tree = tree.on_create_cancel_ctx(move |ctx, event| {
2167            if draft_kinds_for_cancel
2168                .borrow_mut()
2169                .remove(&event.id)
2170                .is_some()
2171            {
2172                release_node(event.id.clone());
2173                emit_model_event(
2174                    ctx,
2175                    &on_model_event,
2176                    FileExplorerModelEvent::CancelCreate { node_id: event.id },
2177                );
2178            }
2179        });
2180
2181        let resolve_node = self.resolve_node.clone();
2182        let model = self.model.clone();
2183        let on_action = self.on_action.clone();
2184        let clipboard_can_paste = self.clipboard_can_paste.clone();
2185        tree = tree.on_shortcut_ctx(move |ctx, shortcut| {
2186            dispatch_retained_file_shortcut(
2187                ctx,
2188                &model,
2189                &resolve_node,
2190                clipboard_can_paste.read(),
2191                &on_action,
2192                shortcut,
2193            );
2194        });
2195
2196        let model = self.model.clone();
2197        let resolve_node = self.resolve_node.clone();
2198        let on_action = self.on_action.clone();
2199        let clipboard_can_paste = self.clipboard_can_paste.clone();
2200        let selected = self.selected.clone();
2201        let menu_open_for_tree = menu_open.clone();
2202        let menu_anchor_for_tree = menu_anchor.clone();
2203        let menu_entries_for_tree = menu_entries.clone();
2204        let menu_focus_key_for_tree = menu_focus_key.clone();
2205        tree = tree.on_context_menu_ctx(move |ctx, event| {
2206            let roots = retained_root_nodes(&model, &resolve_node);
2207            let entries = match &event {
2208                TreeContextMenu::Row { row_id, .. } => resolve_node(row_id.clone())
2209                    .map(|node| {
2210                        let expanded = if model.read(|model| model.is_expanded(row_id)) {
2211                            vec![node.entry.uri.clone()]
2212                        } else {
2213                            Vec::new()
2214                        };
2215                        build_row_context_menu(
2216                            &roots,
2217                            &expanded,
2218                            &node,
2219                            &on_action,
2220                            &None,
2221                            &None,
2222                            &None,
2223                            &None,
2224                            tree_commands.clone(),
2225                        )
2226                    })
2227                    .unwrap_or_default(),
2228                TreeContextMenu::Blank { .. } => {
2229                    let selected_uri = selected
2230                        .as_ref()
2231                        .map(Binding::read)
2232                        .and_then(|id| resolve_node(id))
2233                        .map(|node| node.entry.uri);
2234                    build_blank_context_menu(
2235                        &roots,
2236                        selected_uri,
2237                        clipboard_can_paste.read(),
2238                        &on_action,
2239                        &None,
2240                        tree_commands.clone(),
2241                    )
2242                }
2243            };
2244            let anchor = match event {
2245                TreeContextMenu::Row {
2246                    pointer_position, ..
2247                }
2248                | TreeContextMenu::Blank { pointer_position } => pointer_position,
2249            };
2250            menu_anchor_for_tree.set(anchor);
2251            menu_entries_for_tree.set(entries);
2252            menu_open_for_tree.set(true);
2253            ctx.request_focus_key(menu_focus_key_for_tree.clone());
2254        });
2255
2256        let tree_view = tree.into_view().key(tree_focus_key);
2257        let content = if self.scrollable {
2258            let mut viewport = Container::new().child(ScrollView::vertical().child(tree_view));
2259            *viewport.layout_mut() = self.layout;
2260            viewport.into_view()
2261        } else {
2262            tree_view
2263        };
2264        ContextMenu::new(content)
2265            .bind_open(menu_open)
2266            .bind_anchor(menu_anchor)
2267            .bind_entries(menu_entries)
2268            .into_view()
2269            .key(menu_focus_key)
2270    }
2271}
2272
2273/// Invokes the optional aggregate URI action handler.
2274fn emit_action<A>(
2275    ctx: &mut EventCtx<A>,
2276    on_action: &Option<ActionHandler<A>>,
2277    action: FileExplorerAction,
2278) {
2279    if let Some(handler) = on_action {
2280        handler(ctx, action);
2281    }
2282}
2283
2284/// Invokes the optional identity-aware retained event handler.
2285fn emit_model_event<T, A>(
2286    ctx: &mut EventCtx<A>,
2287    handler: &Option<RetainedEventHandler<T, A>>,
2288    event: FileExplorerModelEvent<T>,
2289) {
2290    if let Some(handler) = handler {
2291        handler(ctx, event);
2292    }
2293}
2294
2295/// Resolves only retained root IDs for context-menu workspace operations.
2296fn retained_root_nodes<T>(
2297    model: &TreeModelHandle<T>,
2298    resolve_node: &RetainedNodeResolver<T>,
2299) -> Vec<FileExplorerNode>
2300where
2301    T: Clone + Eq + Hash + fmt::Debug,
2302{
2303    model.read(|model| {
2304        model
2305            .roots()
2306            .iter()
2307            .filter_map(|id| resolve_node(id.clone()))
2308            .collect()
2309    })
2310}
2311
2312/// Validates a retained drag/drop and resolves its destination parent/URI.
2313///
2314/// Self-drops, before/after root drops, leaf-inside drops, descendant cycles,
2315/// missing names/resolvers, invalid joins, and no-op destinations return `None`.
2316fn retained_file_move<T>(
2317    model: &TreeModelHandle<T>,
2318    resolve_node: &RetainedNodeResolver<T>,
2319    event: TreeMove<T>,
2320) -> Option<(T, T, FileExplorerMove)>
2321where
2322    T: Clone + Eq + Hash + fmt::Debug,
2323{
2324    if event.source == event.target {
2325        return None;
2326    }
2327    let source_id = event.source.clone();
2328    let target_id = event.target.clone();
2329    let source = resolve_node(source_id.clone())?;
2330    let target = resolve_node(target_id.clone())?;
2331    let source_name = source.entry.uri.file_name_decoded()?;
2332    let source_parent = source.entry.uri.parent();
2333    let target_parent_id = match event.position {
2334        TreeDropPosition::Inside => {
2335            if !(target.entry.metadata.is_directory_like() || target.is_branch()) {
2336                return None;
2337            }
2338            target_id.clone()
2339        }
2340        TreeDropPosition::Before | TreeDropPosition::After => {
2341            model.read(|model| model.parent(&target_id).cloned())?
2342        }
2343    };
2344    let target_parent = resolve_node(target_parent_id.clone())?.entry.uri;
2345    if (source.entry.metadata.is_directory_like() || source.is_branch())
2346        && uri_is_same_or_descendant(&target_parent, &source.entry.uri)
2347    {
2348        return None;
2349    }
2350    let to = target_parent.join_child(&source_name).ok()?;
2351    if to == source.entry.uri {
2352        return None;
2353    }
2354    Some((
2355        source_id,
2356        target_parent_id,
2357        FileExplorerMove {
2358            from: source.entry.uri,
2359            to,
2360            source_parent,
2361            target_parent,
2362        },
2363    ))
2364}
2365
2366/// Converts supported retained tree shortcuts into high-level URI actions.
2367///
2368/// Missing resolvers suppress the action. Paste is additionally gated by the
2369/// clipboard flag and resolves a leaf selection to its parent directory.
2370fn dispatch_retained_file_shortcut<T, A>(
2371    ctx: &mut EventCtx<A>,
2372    model: &TreeModelHandle<T>,
2373    resolve_node: &RetainedNodeResolver<T>,
2374    clipboard_can_paste: bool,
2375    on_action: &Option<ActionHandler<A>>,
2376    shortcut: TreeShortcut<T>,
2377) where
2378    T: Clone + Eq + Hash + fmt::Debug,
2379{
2380    match shortcut {
2381        TreeShortcut::Delete { id } => {
2382            let Some(node) = resolve_node(id) else {
2383                return;
2384            };
2385            let uri = node.entry.uri;
2386            emit_action(
2387                ctx,
2388                on_action,
2389                FileExplorerAction::RemoveRequested {
2390                    parent: uri.parent(),
2391                    uri,
2392                },
2393            );
2394        }
2395        TreeShortcut::Copy { id } => {
2396            let Some(node) = resolve_node(id) else {
2397                return;
2398            };
2399            emit_action(
2400                ctx,
2401                on_action,
2402                FileExplorerAction::CopyFile {
2403                    uri: node.entry.uri,
2404                },
2405            );
2406        }
2407        TreeShortcut::Cut { id } => {
2408            let Some(node) = resolve_node(id) else {
2409                return;
2410            };
2411            emit_action(
2412                ctx,
2413                on_action,
2414                FileExplorerAction::CutFile {
2415                    uri: node.entry.uri,
2416                },
2417            );
2418        }
2419        TreeShortcut::Paste { id } => {
2420            if !clipboard_can_paste {
2421                return;
2422            }
2423            let target = id
2424                .and_then(|id| resolve_node(id))
2425                .and_then(|node| {
2426                    if node.entry.metadata.is_directory_like() || node.is_branch() {
2427                        Some(node.entry.uri)
2428                    } else {
2429                        node.entry.uri.parent()
2430                    }
2431                })
2432                .or_else(|| {
2433                    model.read(|model| {
2434                        model
2435                            .roots()
2436                            .first()
2437                            .and_then(|id| resolve_node(id.clone()))
2438                            .map(|node| node.entry.uri)
2439                    })
2440                });
2441            if let Some(target_dir) = target {
2442                emit_action(ctx, on_action, FileExplorerAction::PasteInto { target_dir });
2443            }
2444        }
2445    }
2446}
2447
2448/// Mirrors transient/expanded tree state back only when snapshot nodes are bound.
2449fn sync_bound_tree_nodes(
2450    bound_nodes: &Option<Signal<Vec<FileExplorerNode>>>,
2451    tree_snapshot: &Rc<RefCell<FileExplorerTreeSnapshot>>,
2452) {
2453    if let Some(nodes) = bound_nodes {
2454        tree_snapshot.borrow_mut().sync_bound_nodes(nodes);
2455    }
2456}
2457
2458/// Routes snapshot-tree delete/copy/cut/paste shortcuts to specialized/actions.
2459fn dispatch_file_shortcut<A>(
2460    ctx: &mut EventCtx<A>,
2461    nodes: &[FileExplorerNode],
2462    clipboard_can_paste: bool,
2463    on_action: &Option<ActionHandler<A>>,
2464    on_remove: &Option<RemoveHandler<A>>,
2465    shortcut: TreeShortcut<FileUri>,
2466) {
2467    match shortcut {
2468        TreeShortcut::Delete { id } => {
2469            let parent = id.parent();
2470            if let Some(handler) = on_remove {
2471                handler(ctx, id.clone(), parent.clone());
2472            }
2473            emit_action(
2474                ctx,
2475                on_action,
2476                FileExplorerAction::RemoveRequested { uri: id, parent },
2477            );
2478        }
2479        TreeShortcut::Copy { id } => {
2480            emit_action(ctx, on_action, FileExplorerAction::CopyFile { uri: id })
2481        }
2482        TreeShortcut::Cut { id } => {
2483            emit_action(ctx, on_action, FileExplorerAction::CutFile { uri: id })
2484        }
2485        TreeShortcut::Paste { id } => {
2486            if !clipboard_can_paste {
2487                return;
2488            }
2489            if let Some(target_dir) = shortcut_paste_target(nodes, id.as_ref()) {
2490                emit_action(ctx, on_action, FileExplorerAction::PasteInto { target_dir });
2491            }
2492        }
2493    }
2494}
2495
2496/// Resolves paste to selected directory/branch, selected leaf parent, or first root.
2497fn shortcut_paste_target(nodes: &[FileExplorerNode], id: Option<&FileUri>) -> Option<FileUri> {
2498    if let Some(uri) = id {
2499        if let Some(node) = find_node(nodes, uri) {
2500            if node.entry.metadata.is_directory_like() || node.is_branch() {
2501                return Some(uri.clone());
2502            }
2503        }
2504        if let Some(parent) = uri.parent() {
2505            return Some(parent);
2506        }
2507    }
2508    nodes.first().map(|node| node.entry.uri.clone())
2509}
2510
2511/// Converts URI-identified drag/drop into a validated high-level move action.
2512fn file_move_action_from_tree_move(
2513    nodes: &[FileExplorerNode],
2514    event: TreeMove<FileUri>,
2515) -> Option<FileExplorerAction> {
2516    if event.source == event.target {
2517        return None;
2518    }
2519    let source = find_node(nodes, &event.source)?;
2520    let target = find_node(nodes, &event.target)?;
2521    let source_name = event.source.file_name_decoded()?;
2522    let source_parent = event.source.parent();
2523    let target_parent = match event.position {
2524        TreeDropPosition::Inside => {
2525            if !(target.entry.metadata.is_directory_like() || target.is_branch()) {
2526                return None;
2527            }
2528            event.target.clone()
2529        }
2530        TreeDropPosition::Before | TreeDropPosition::After => event.target.parent()?,
2531    };
2532    if (source.entry.metadata.is_directory_like() || source.is_branch())
2533        && uri_is_same_or_descendant(&target_parent, &event.source)
2534    {
2535        return None;
2536    }
2537    let to = target_parent.join_child(&source_name).ok()?;
2538    if to == event.source {
2539        return None;
2540    }
2541    Some(FileExplorerAction::MoveEntry(FileExplorerMove {
2542        from: event.source,
2543        to,
2544        source_parent,
2545        target_parent,
2546    }))
2547}
2548
2549/// Tests location-aware ancestry through `relative_path_from`, including self.
2550fn uri_is_same_or_descendant(candidate: &FileUri, root: &FileUri) -> bool {
2551    if candidate.scheme() != root.scheme() || candidate.authority() != root.authority() {
2552        return false;
2553    }
2554    let root_path = root.path().trim_end_matches('/');
2555    candidate.path() == root_path
2556        || candidate
2557            .path()
2558            .strip_prefix(root_path)
2559            .is_some_and(|suffix| suffix.starts_with('/'))
2560}
2561
2562#[allow(clippy::too_many_arguments)]
2563/// Dispatches row/blank context menu construction from a tree event.
2564fn build_context_menu_entries<A: 'static>(
2565    nodes: &[FileExplorerNode],
2566    expanded: &[FileUri],
2567    clipboard_can_paste: bool,
2568    on_action: &Option<ActionHandler<A>>,
2569    on_open: &Option<UriHandler<A>>,
2570    on_rename: &Option<RenameHandler<A>>,
2571    on_remove: &Option<RemoveHandler<A>>,
2572    on_create_dir: &Option<CreateDirHandler<A>>,
2573    selected: Option<FileUri>,
2574    tree_commands: FileExplorerTreeCommands<A>,
2575    event: TreeContextMenu<FileUri>,
2576) -> Vec<ContextMenuEntry<A>> {
2577    match event {
2578        TreeContextMenu::Row { row_id, .. } => find_node(nodes, &row_id)
2579            .map(|node| {
2580                build_row_context_menu(
2581                    nodes,
2582                    expanded,
2583                    node,
2584                    on_action,
2585                    on_open,
2586                    on_rename,
2587                    on_remove,
2588                    on_create_dir,
2589                    tree_commands,
2590                )
2591            })
2592            .unwrap_or_default(),
2593        TreeContextMenu::Blank { .. } => build_blank_context_menu(
2594            nodes,
2595            selected,
2596            clipboard_can_paste,
2597            on_action,
2598            on_create_dir,
2599            tree_commands,
2600        ),
2601    }
2602}
2603
2604#[allow(clippy::too_many_arguments)]
2605/// Selects directory or file menus using metadata plus synthetic branch status.
2606fn build_row_context_menu<A: 'static>(
2607    nodes: &[FileExplorerNode],
2608    expanded: &[FileUri],
2609    node: &FileExplorerNode,
2610    on_action: &Option<ActionHandler<A>>,
2611    on_open: &Option<UriHandler<A>>,
2612    on_rename: &Option<RenameHandler<A>>,
2613    on_remove: &Option<RemoveHandler<A>>,
2614    on_create_dir: &Option<CreateDirHandler<A>>,
2615    tree_commands: FileExplorerTreeCommands<A>,
2616) -> Vec<ContextMenuEntry<A>> {
2617    if node.entry.metadata.is_directory_like() || node.is_branch() {
2618        build_directory_context_menu(
2619            nodes,
2620            expanded,
2621            node,
2622            on_action,
2623            on_open,
2624            on_rename,
2625            on_remove,
2626            on_create_dir,
2627            tree_commands,
2628        )
2629    } else {
2630        build_file_context_menu(
2631            nodes,
2632            node,
2633            on_action,
2634            on_open,
2635            on_rename,
2636            on_remove,
2637            tree_commands,
2638        )
2639    }
2640}
2641
2642#[allow(clippy::vec_init_then_push)]
2643#[allow(clippy::too_many_arguments)]
2644/// Builds file actions and disables integrations lacking required handlers.
2645fn build_file_context_menu<A: 'static>(
2646    nodes: &[FileExplorerNode],
2647    node: &FileExplorerNode,
2648    on_action: &Option<ActionHandler<A>>,
2649    on_open: &Option<UriHandler<A>>,
2650    on_rename: &Option<RenameHandler<A>>,
2651    on_remove: &Option<RemoveHandler<A>>,
2652    tree_commands: FileExplorerTreeCommands<A>,
2653) -> Vec<ContextMenuEntry<A>> {
2654    let uri = node.entry.uri.clone();
2655    let parent = uri.parent();
2656    let terminal_target = parent.clone().unwrap_or_else(|| uri.clone());
2657    let mut entries = Vec::new();
2658    entries.push(open_item("Open", "Enter", &uri, on_action, on_open));
2659    entries.push(ContextMenuEntry::Separator);
2660    entries.push(action_item(
2661        "Cut",
2662        Some("Ctrl+X"),
2663        on_action,
2664        FileExplorerAction::CutFile { uri: uri.clone() },
2665        on_action.is_none(),
2666    ));
2667    entries.push(action_item(
2668        "Copy File",
2669        Some("Ctrl+C"),
2670        on_action,
2671        FileExplorerAction::CopyFile { uri: uri.clone() },
2672        on_action.is_none(),
2673    ));
2674    entries.push(ContextMenuEntry::Separator);
2675    push_path_items(&mut entries, nodes, &uri, on_action);
2676    entries.push(ContextMenuEntry::Separator);
2677    entries.push(rename_item(&uri, on_action, on_rename, tree_commands));
2678    entries.push(remove_item(&uri, parent.clone(), on_action, on_remove));
2679    entries.push(ContextMenuEntry::Separator);
2680    entries.push(action_item(
2681        "Reveal in Workspace",
2682        None,
2683        on_action,
2684        FileExplorerAction::RevealInWorkspace { uri: uri.clone() },
2685        on_action.is_none(),
2686    ));
2687    entries.push(action_item(
2688        "Open Terminal Here",
2689        None,
2690        on_action,
2691        FileExplorerAction::OpenTerminalHere {
2692            uri: terminal_target.clone(),
2693        },
2694        on_action.is_none(),
2695    ));
2696    entries.push(action_item(
2697        "Search from Parent",
2698        None,
2699        on_action,
2700        FileExplorerAction::SearchInFolder {
2701            uri: terminal_target,
2702        },
2703        true,
2704    ));
2705    entries
2706}
2707
2708#[allow(clippy::too_many_arguments)]
2709#[allow(clippy::vec_init_then_push)]
2710/// Builds branch creation/clipboard/path/workspace actions and compacts separators.
2711fn build_directory_context_menu<A: 'static>(
2712    nodes: &[FileExplorerNode],
2713    expanded: &[FileUri],
2714    node: &FileExplorerNode,
2715    on_action: &Option<ActionHandler<A>>,
2716    on_open: &Option<UriHandler<A>>,
2717    on_rename: &Option<RenameHandler<A>>,
2718    on_remove: &Option<RemoveHandler<A>>,
2719    on_create_dir: &Option<CreateDirHandler<A>>,
2720    tree_commands: FileExplorerTreeCommands<A>,
2721) -> Vec<ContextMenuEntry<A>> {
2722    let uri = node.entry.uri.clone();
2723    let parent = uri.parent();
2724    let is_expanded = expanded.iter().any(|expanded| expanded == &uri);
2725    let is_root = nodes.iter().any(|root| root.entry.uri == uri);
2726    let mut entries = Vec::new();
2727    entries.push(open_item(
2728        if is_expanded {
2729            "Collapse"
2730        } else {
2731            "Open / Expand"
2732        },
2733        "Enter",
2734        &uri,
2735        on_action,
2736        on_open,
2737    ));
2738    entries.push(ContextMenuEntry::Separator);
2739    entries.push(create_item(
2740        "New File",
2741        &uri,
2742        NEW_FILE_NAME,
2743        on_action,
2744        FileExplorerAction::CreateFileRequested {
2745            parent: uri.clone(),
2746        },
2747        on_action.is_none(),
2748        tree_commands.clone(),
2749    ));
2750    entries.push(create_item(
2751        "New Folder",
2752        &uri,
2753        NEW_FOLDER_NAME,
2754        on_action,
2755        FileExplorerAction::CreateDirRequested {
2756            parent: uri.clone(),
2757        },
2758        on_action.is_none() && on_create_dir.is_none(),
2759        tree_commands.clone(),
2760    ));
2761    entries.push(ContextMenuEntry::Separator);
2762    entries.push(action_item(
2763        "Cut",
2764        Some("Ctrl+X"),
2765        on_action,
2766        FileExplorerAction::CutFile { uri: uri.clone() },
2767        on_action.is_none(),
2768    ));
2769    entries.push(action_item(
2770        "Copy Folder",
2771        Some("Ctrl+C"),
2772        on_action,
2773        FileExplorerAction::CopyFile { uri: uri.clone() },
2774        on_action.is_none() || node.entry.metadata.kind == FileKind::Symlink,
2775    ));
2776    entries.push(action_item(
2777        "Paste Into",
2778        Some("Ctrl+V"),
2779        on_action,
2780        FileExplorerAction::PasteInto {
2781            target_dir: uri.clone(),
2782        },
2783        on_action.is_none(),
2784    ));
2785    entries.push(ContextMenuEntry::Separator);
2786    push_path_items(&mut entries, nodes, &uri, on_action);
2787    entries.push(ContextMenuEntry::Separator);
2788    entries.push(rename_item(&uri, on_action, on_rename, tree_commands));
2789    entries.push(remove_item(&uri, parent, on_action, on_remove));
2790    entries.push(ContextMenuEntry::Separator);
2791    entries.push(action_item(
2792        "Refresh",
2793        None,
2794        on_action,
2795        FileExplorerAction::Refresh { uri: uri.clone() },
2796        on_action.is_none(),
2797    ));
2798    entries.push(action_item(
2799        "Open Terminal Here",
2800        None,
2801        on_action,
2802        FileExplorerAction::OpenTerminalHere { uri: uri.clone() },
2803        on_action.is_none(),
2804    ));
2805    entries.push(action_item(
2806        "Search in Folder",
2807        None,
2808        on_action,
2809        FileExplorerAction::SearchInFolder { uri: uri.clone() },
2810        true,
2811    ));
2812    entries.push(ContextMenuEntry::Separator);
2813    entries.push(action_item(
2814        "Add Folder to Workspace",
2815        None,
2816        on_action,
2817        FileExplorerAction::AddFolderToWorkspace { uri: uri.clone() },
2818        on_action.is_none(),
2819    ));
2820    entries.push(action_item(
2821        "Set as Workspace Root",
2822        None,
2823        on_action,
2824        FileExplorerAction::SetWorkspaceRoot { uri: uri.clone() },
2825        on_action.is_none(),
2826    ));
2827    entries.push(action_item(
2828        "Remove from Workspace",
2829        None,
2830        on_action,
2831        FileExplorerAction::RemoveFolderFromWorkspace { uri },
2832        on_action.is_none() || !is_root,
2833    ));
2834    compact_separators(entries)
2835}
2836
2837#[allow(clippy::vec_init_then_push)]
2838/// Builds workspace/selected-target actions for context clicks outside rows.
2839fn build_blank_context_menu<A: 'static>(
2840    nodes: &[FileExplorerNode],
2841    selected: Option<FileUri>,
2842    clipboard_can_paste: bool,
2843    on_action: &Option<ActionHandler<A>>,
2844    on_create_dir: &Option<CreateDirHandler<A>>,
2845    tree_commands: FileExplorerTreeCommands<A>,
2846) -> Vec<ContextMenuEntry<A>> {
2847    let target = blank_target_dir(nodes, selected);
2848    let mut entries = Vec::new();
2849    if let Some(target) = target.clone() {
2850        entries.push(create_item(
2851            "New File",
2852            &target,
2853            NEW_FILE_NAME,
2854            on_action,
2855            FileExplorerAction::CreateFileRequested {
2856                parent: target.clone(),
2857            },
2858            on_action.is_none(),
2859            tree_commands.clone(),
2860        ));
2861        entries.push(create_item(
2862            "New Folder",
2863            &target,
2864            NEW_FOLDER_NAME,
2865            on_action,
2866            FileExplorerAction::CreateDirRequested {
2867                parent: target.clone(),
2868            },
2869            on_action.is_none() && on_create_dir.is_none(),
2870            tree_commands,
2871        ));
2872        entries.push(action_item(
2873            "Paste",
2874            Some("Ctrl+V"),
2875            on_action,
2876            FileExplorerAction::PasteInto {
2877                target_dir: target.clone(),
2878            },
2879            on_action.is_none() || !clipboard_can_paste,
2880        ));
2881        entries.push(ContextMenuEntry::Separator);
2882        entries.push(action_item(
2883            "Refresh Workspace",
2884            None,
2885            on_action,
2886            FileExplorerAction::Refresh {
2887                uri: target.clone(),
2888            },
2889            on_action.is_none(),
2890        ));
2891        entries.push(action_item(
2892            "Open Terminal at Workspace Root",
2893            None,
2894            on_action,
2895            FileExplorerAction::OpenTerminalHere { uri: target },
2896            on_action.is_none(),
2897        ));
2898    }
2899    entries.push(action_item(
2900        "Collapse All",
2901        None,
2902        on_action,
2903        FileExplorerAction::CollapseAll,
2904        on_action.is_none(),
2905    ));
2906    entries.push(action_item(
2907        "Expand All",
2908        None,
2909        on_action,
2910        FileExplorerAction::ExpandAll,
2911        on_action.is_none(),
2912    ));
2913    entries.push(action_item(
2914        "Reveal Active File",
2915        None,
2916        on_action,
2917        FileExplorerAction::RevealActiveFile,
2918        on_action.is_none(),
2919    ));
2920    entries.push(ContextMenuEntry::Separator);
2921    entries.push(action_item(
2922        "Search in Workspace",
2923        None,
2924        on_action,
2925        FileExplorerAction::SearchInWorkspace,
2926        true,
2927    ));
2928    entries.push(action_item(
2929        "Add Folder to Workspace",
2930        None,
2931        on_action,
2932        FileExplorerAction::OpenWorkspaceHere {
2933            uri: nodes
2934                .first()
2935                .map(|node| node.entry.uri.clone())
2936                .unwrap_or_else(|| FileUri::new("file", None::<String>, "/").unwrap()),
2937        },
2938        on_action.is_none(),
2939    ));
2940    entries.push(action_item(
2941        "Open Workspace Settings",
2942        None,
2943        on_action,
2944        FileExplorerAction::OpenWorkspaceSettings,
2945        true,
2946    ));
2947    compact_separators(entries)
2948}
2949
2950/// Appends absolute and root-relative path-copy actions with availability gates.
2951fn push_path_items<A: 'static>(
2952    entries: &mut Vec<ContextMenuEntry<A>>,
2953    nodes: &[FileExplorerNode],
2954    uri: &FileUri,
2955    on_action: &Option<ActionHandler<A>>,
2956) {
2957    entries.push(action_item(
2958        "Copy Path",
2959        Some("Ctrl+Alt+C"),
2960        on_action,
2961        FileExplorerAction::CopyPath { uri: uri.clone() },
2962        on_action.is_none(),
2963    ));
2964    entries.push(action_item(
2965        "Copy Relative Path",
2966        Some("Ctrl+Shift+Alt+C"),
2967        on_action,
2968        FileExplorerAction::CopyRelativePath { uri: uri.clone() },
2969        on_action.is_none() || root_for_uri(nodes, uri).is_none(),
2970    ));
2971}
2972
2973/// Builds an open item that invokes specialized then aggregate callbacks.
2974fn open_item<A: 'static>(
2975    label: &'static str,
2976    shortcut: &'static str,
2977    uri: &FileUri,
2978    on_action: &Option<ActionHandler<A>>,
2979    on_open: &Option<UriHandler<A>>,
2980) -> ContextMenuEntry<A> {
2981    let uri = uri.clone();
2982    let on_action = on_action.clone();
2983    let on_open = on_open.clone();
2984    let disabled = on_action.is_none() && on_open.is_none();
2985    let mut item = ContextMenuItem::new(label)
2986        .shortcut(shortcut)
2987        .disabled(disabled);
2988    item = item.on_select(ClickAction::handler(move |ctx| {
2989        if let Some(handler) = &on_open {
2990            handler(ctx, uri.clone());
2991        }
2992        emit_action(ctx, &on_action, FileExplorerAction::Open(uri.clone()));
2993    }));
2994    ContextMenuEntry::Item(item)
2995}
2996
2997/// Builds the F2 item that begins inline editing and emits a request intent.
2998fn rename_item<A: 'static>(
2999    uri: &FileUri,
3000    on_action: &Option<ActionHandler<A>>,
3001    on_rename: &Option<RenameHandler<A>>,
3002    tree_commands: FileExplorerTreeCommands<A>,
3003) -> ContextMenuEntry<A> {
3004    let uri = uri.clone();
3005    let on_action = on_action.clone();
3006    let disabled = on_action.is_none() && on_rename.is_none();
3007    ContextMenuEntry::Item(
3008        ContextMenuItem::new("Rename...")
3009            .shortcut("F2")
3010            .disabled(disabled)
3011            .on_select(ClickAction::handler(move |ctx| {
3012                tree_commands.begin_rename(ctx, uri.clone());
3013                emit_action(
3014                    ctx,
3015                    &on_action,
3016                    FileExplorerAction::RenameRequested { uri: uri.clone() },
3017                );
3018                ctx.request_repaint();
3019            })),
3020    )
3021}
3022
3023#[allow(clippy::too_many_arguments)]
3024/// Builds an inline-create launcher plus its high-level requested intent.
3025fn create_item<A: 'static>(
3026    label: &'static str,
3027    parent: &FileUri,
3028    default_label: &'static str,
3029    on_action: &Option<ActionHandler<A>>,
3030    action: FileExplorerAction,
3031    disabled: bool,
3032    tree_commands: FileExplorerTreeCommands<A>,
3033) -> ContextMenuEntry<A> {
3034    let parent = parent.clone();
3035    let on_action = on_action.clone();
3036    ContextMenuEntry::Item(ContextMenuItem::new(label).disabled(disabled).on_select(
3037        ClickAction::handler(move |ctx| {
3038            tree_commands.begin_create(ctx, parent.clone(), default_label);
3039            emit_action(ctx, &on_action, action.clone());
3040            ctx.request_repaint();
3041        }),
3042    ))
3043}
3044
3045/// Builds a delete-request item; committed removal occurs in the tree handler.
3046fn remove_item<A: 'static>(
3047    uri: &FileUri,
3048    parent: Option<FileUri>,
3049    on_action: &Option<ActionHandler<A>>,
3050    on_remove: &Option<RemoveHandler<A>>,
3051) -> ContextMenuEntry<A> {
3052    let uri = uri.clone();
3053    let on_action = on_action.clone();
3054    let disabled = on_action.is_none() && on_remove.is_none();
3055    ContextMenuEntry::Item(
3056        ContextMenuItem::new("Delete")
3057            .shortcut("Delete")
3058            .disabled(disabled)
3059            .on_select(ClickAction::handler(move |ctx| {
3060                emit_action(
3061                    ctx,
3062                    &on_action,
3063                    FileExplorerAction::RemoveRequested {
3064                        uri: uri.clone(),
3065                        parent: parent.clone(),
3066                    },
3067                );
3068            })),
3069    )
3070}
3071
3072/// Builds a generic optional-shortcut item that clones one emitted action.
3073fn action_item<A: 'static>(
3074    label: &'static str,
3075    shortcut: Option<&'static str>,
3076    on_action: &Option<ActionHandler<A>>,
3077    action: FileExplorerAction,
3078    disabled: bool,
3079) -> ContextMenuEntry<A> {
3080    let on_action = on_action.clone();
3081    let mut item = ContextMenuItem::new(label).disabled(disabled);
3082    if let Some(shortcut) = shortcut {
3083        item = item.shortcut(shortcut);
3084    }
3085    ContextMenuEntry::Item(item.on_select(ClickAction::handler(move |ctx| {
3086        emit_action(ctx, &on_action, action.clone());
3087    })))
3088}
3089
3090/// Recursively returns the first depth-first node with an exact URI.
3091fn find_node<'a>(nodes: &'a [FileExplorerNode], uri: &FileUri) -> Option<&'a FileExplorerNode> {
3092    for node in nodes {
3093        if &node.entry.uri == uri {
3094            return Some(node);
3095        }
3096        if let Some(found) = find_node(&node.children, uri) {
3097            return Some(found);
3098        }
3099    }
3100    None
3101}
3102
3103/// Resolves blank-menu target from selected branch/leaf or first branch root.
3104fn blank_target_dir(nodes: &[FileExplorerNode], selected: Option<FileUri>) -> Option<FileUri> {
3105    if let Some(selected) = selected {
3106        if let Some(node) = find_node(nodes, &selected) {
3107            if node.entry.metadata.is_directory_like() || node.is_branch() {
3108                return Some(node.entry.uri.clone());
3109            }
3110            if let Some(parent) = selected.parent() {
3111                return Some(parent);
3112            }
3113        }
3114    }
3115    nodes
3116        .iter()
3117        .find(|node| node.entry.metadata.is_directory_like() || node.is_branch())
3118        .map(|node| node.entry.uri.clone())
3119}
3120
3121/// Returns the first root from which `uri` has a relative path.
3122fn root_for_uri<'a>(nodes: &'a [FileExplorerNode], uri: &FileUri) -> Option<&'a FileUri> {
3123    nodes
3124        .iter()
3125        .find(|node| uri.relative_path_from(&node.entry.uri).is_some())
3126        .map(|node| &node.entry.uri)
3127}
3128
3129/// Removes leading, trailing, and adjacent context-menu separators.
3130fn compact_separators<A>(entries: Vec<ContextMenuEntry<A>>) -> Vec<ContextMenuEntry<A>> {
3131    let mut out = Vec::new();
3132    let mut last_separator = true;
3133    for entry in entries {
3134        match entry {
3135            ContextMenuEntry::Separator if last_separator => {}
3136            ContextMenuEntry::Separator => {
3137                last_separator = true;
3138                out.push(ContextMenuEntry::Separator);
3139            }
3140            item => {
3141                last_separator = false;
3142                out.push(item);
3143            }
3144        }
3145    }
3146    while matches!(out.last(), Some(ContextMenuEntry::Separator)) {
3147        out.pop();
3148    }
3149    out
3150}
3151
3152/// Recursively projects snapshot metadata to URI-identified decorated tree nodes.
3153///
3154/// Empty-name nodes are forced disabled, and icon tint follows file icon mapping.
3155fn to_tree_node(node: &FileExplorerNode) -> TreeNode<FileUri> {
3156    let icon = file_icon_visual_for_entry(&node.entry);
3157    let mut tree = if node.is_branch() {
3158        TreeNode::branch(node.entry.uri.clone(), node.entry.name.clone())
3159            .children(node.children.iter().map(to_tree_node))
3160    } else {
3161        TreeNode::leaf(node.entry.uri.clone(), node.entry.name.clone())
3162    }
3163    .leading_icon(icon.icon)
3164    .disabled(node.disabled);
3165    if let Some(color) = icon.color {
3166        tree = tree.leading_icon_tint(color);
3167    }
3168
3169    if node.entry.name.is_empty() {
3170        tree = tree.disabled(true);
3171    }
3172    tree
3173}
3174
3175/// Keeps the current tree wholesale while any inline create draft exists.
3176fn preserve_transient_tree_nodes(
3177    current: Vec<TreeNode<FileUri>>,
3178    next: Vec<TreeNode<FileUri>>,
3179) -> Vec<TreeNode<FileUri>> {
3180    if has_transient_tree_node(&current) {
3181        current
3182    } else {
3183        next
3184    }
3185}
3186
3187/// Recursively detects an inline transient node.
3188fn has_transient_tree_node(nodes: &[TreeNode<FileUri>]) -> bool {
3189    nodes
3190        .iter()
3191        .any(|node| node.is_transient() || has_transient_tree_node(node.child_nodes()))
3192}
3193
3194/// Creates a styled transient file/folder node from sentinel default labels.
3195fn create_explorer_node(request: TreeCreateRequest<FileUri>) -> Option<TreeNode<FileUri>> {
3196    let uri = create_entry_uri(&request)?;
3197    if request.default_label == NEW_FILE_NAME {
3198        return Some(
3199            TreeNode::leaf(uri, NEW_FILE_NAME)
3200                .leading_icon(IconId::Devicon('\u{f15b}'))
3201                .leading_icon_tint(ailloli_ui_core::Color::hex_rgb(0x94a3b8))
3202                .transient(true),
3203        );
3204    }
3205    Some(
3206        TreeNode::branch(uri, NEW_FOLDER_NAME)
3207            .leading_icon(IconId::Devicon('\u{f07b}'))
3208            .leading_icon_tint(ailloli_ui_core::Color::hex_rgb(0xf59e0b))
3209            .children(Vec::<TreeNode<FileUri>>::new())
3210            .transient(true),
3211    )
3212}
3213
3214/// Resolves child or sibling draft placement; missing/invalid parents return none.
3215fn create_entry_uri(request: &TreeCreateRequest<FileUri>) -> Option<FileUri> {
3216    let name = if request.default_label.is_empty() {
3217        NEW_FOLDER_NAME
3218    } else {
3219        request.default_label.as_str()
3220    };
3221    match request.kind {
3222        TreeCreateKind::Child => request.parent.as_ref()?.join_child(name).ok(),
3223        TreeCreateKind::SiblingAfter => request.after.as_ref()?.parent()?.join_child(name).ok(),
3224    }
3225}
3226
3227/// Classifies a snapshot draft as a file by the decoded sentinel filename.
3228fn is_create_file_id(uri: &FileUri) -> bool {
3229    uri.file_name_decoded().as_deref() == Some(NEW_FILE_NAME)
3230}
3231
3232/// Prefers parent join, then filename replacement, then the unchanged draft URI.
3233fn create_uri_from_event(fallback: &FileUri, parent: Option<&FileUri>, label: &str) -> FileUri {
3234    parent
3235        .and_then(|parent| parent.join_child(label).ok())
3236        .or_else(|| fallback.with_file_name(label).ok())
3237        .unwrap_or_else(|| fallback.clone())
3238}