ailloli_ui_widgets/files/model.rs
1//! Snapshot tree input and flattened row output for [`super::FileExplorer`].
2
3use ailloli_ui_core::IconId;
4use ailloli_ui_fs::{FileEntry, FileKind, FileMetadata, FileUri};
5
6use super::icons::file_icon_for_entry;
7
8/// Caller-owned recursive file-explorer node.
9///
10/// A directory-like entry is a branch even with no loaded children. Conversely,
11/// any entry with children is treated as a branch so callers can use synthetic
12/// grouping rows. The model performs no URI uniqueness validation.
13///
14/// # Examples
15///
16/// ```
17/// use ailloli_ui_fs::FileUri;
18/// use ailloli_ui_widgets::files::FileExplorerNode;
19/// let node = FileExplorerNode::directory(FileUri::parse("file:///repo")?, "repo")
20/// .child(FileExplorerNode::file(FileUri::parse("file:///repo/main.rs")?, "main.rs"));
21/// assert!(node.is_branch());
22/// # Ok::<(), ailloli_ui_fs::FileError>(())
23/// ```
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct FileExplorerNode {
26 /// URI, display name, and filesystem metadata snapshot.
27 pub entry: FileEntry,
28 /// Children in caller or sorted presentation order.
29 pub children: Vec<FileExplorerNode>,
30 /// Whether interaction with this row is suppressed.
31 pub disabled: bool,
32}
33
34impl FileExplorerNode {
35 /// Creates an enabled leaf candidate with no children.
36 ///
37 /// Branch status still follows `entry.metadata.is_directory_like()`.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// use ailloli_ui_fs::{FileEntry, FileKind, FileMetadata, FileUri};
43 /// use ailloli_ui_widgets::files::FileExplorerNode;
44 /// let entry = FileEntry::new(FileUri::parse("file:///a.txt")?, FileMetadata::new(FileKind::File));
45 /// let node = FileExplorerNode::new(entry);
46 /// assert!(node.children.is_empty() && !node.disabled);
47 /// # Ok::<(), ailloli_ui_fs::FileError>(())
48 /// ```
49 pub fn new(entry: FileEntry) -> Self {
50 Self {
51 entry,
52 children: Vec::new(),
53 disabled: false,
54 }
55 }
56
57 /// Creates an enabled node with an explicit display name and basic metadata.
58 ///
59 /// The name is stored verbatim and need not match the URI filename.
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// use ailloli_ui_fs::{FileKind, FileUri};
65 /// use ailloli_ui_widgets::files::FileExplorerNode;
66 /// let node = FileExplorerNode::named(FileUri::parse("file:///raw")?, "Alias", FileKind::Other);
67 /// assert_eq!(node.name(), "Alias");
68 /// # Ok::<(), ailloli_ui_fs::FileError>(())
69 /// ```
70 pub fn named(uri: FileUri, name: impl Into<String>, kind: FileKind) -> Self {
71 Self::new(FileEntry {
72 uri,
73 name: name.into(),
74 metadata: FileMetadata::new(kind),
75 })
76 }
77
78 /// Creates an enabled [`FileKind::File`] node.
79 ///
80 /// # Examples
81 ///
82 /// ```
83 /// use ailloli_ui_fs::{FileKind, FileUri};
84 /// use ailloli_ui_widgets::files::FileExplorerNode;
85 /// let node = FileExplorerNode::file(FileUri::parse("file:///main.rs")?, "main.rs");
86 /// assert_eq!(node.entry.metadata.kind, FileKind::File);
87 /// # Ok::<(), ailloli_ui_fs::FileError>(())
88 /// ```
89 pub fn file(uri: FileUri, name: impl Into<String>) -> Self {
90 Self::named(uri, name, FileKind::File)
91 }
92
93 /// Creates an enabled [`FileKind::Directory`] node.
94 ///
95 /// # Examples
96 ///
97 /// ```
98 /// use ailloli_ui_fs::FileUri;
99 /// use ailloli_ui_widgets::files::FileExplorerNode;
100 /// let node = FileExplorerNode::directory(FileUri::parse("file:///src")?, "src");
101 /// assert!(node.is_branch());
102 /// # Ok::<(), ailloli_ui_fs::FileError>(())
103 /// ```
104 pub fn directory(uri: FileUri, name: impl Into<String>) -> Self {
105 Self::named(uri, name, FileKind::Directory)
106 }
107
108 /// Appends one child after existing children.
109 ///
110 /// # Examples
111 ///
112 /// ```
113 /// use ailloli_ui_fs::FileUri;
114 /// use ailloli_ui_widgets::files::FileExplorerNode;
115 /// let root = FileExplorerNode::directory(FileUri::parse("file:///")?, "/")
116 /// .child(FileExplorerNode::file(FileUri::parse("file:///a")?, "a"));
117 /// assert_eq!(root.children.len(), 1);
118 /// # Ok::<(), ailloli_ui_fs::FileError>(())
119 /// ```
120 pub fn child(mut self, child: FileExplorerNode) -> Self {
121 self.children.push(child);
122 self
123 }
124
125 /// Extends children in iterator order without replacing existing entries.
126 ///
127 /// # Examples
128 ///
129 /// ```
130 /// use ailloli_ui_fs::FileUri;
131 /// use ailloli_ui_widgets::files::FileExplorerNode;
132 /// let node = FileExplorerNode::directory(FileUri::parse("file:///src")?, "src").children([
133 /// FileExplorerNode::file(FileUri::parse("file:///src/a.rs")?, "a.rs"),
134 /// FileExplorerNode::file(FileUri::parse("file:///src/b.rs")?, "b.rs"),
135 /// ]);
136 /// assert_eq!(node.children.len(), 2);
137 /// # Ok::<(), ailloli_ui_fs::FileError>(())
138 /// ```
139 pub fn children(mut self, children: impl IntoIterator<Item = FileExplorerNode>) -> Self {
140 self.children.extend(children);
141 self
142 }
143
144 /// Sets whether pointer/keyboard actions are suppressed for this row.
145 ///
146 /// # Examples
147 ///
148 /// ```
149 /// use ailloli_ui_fs::FileUri;
150 /// use ailloli_ui_widgets::files::FileExplorerNode;
151 /// let node = FileExplorerNode::file(FileUri::parse("file:///locked")?, "locked").disabled(true);
152 /// assert!(node.disabled);
153 /// # Ok::<(), ailloli_ui_fs::FileError>(())
154 /// ```
155 pub fn disabled(mut self, disabled: bool) -> Self {
156 self.disabled = disabled;
157 self
158 }
159
160 /// Borrows the entry's canonical interaction key.
161 ///
162 /// # Examples
163 ///
164 /// ```
165 /// use ailloli_ui_fs::FileUri;
166 /// use ailloli_ui_widgets::files::FileExplorerNode;
167 /// let uri = FileUri::parse("file:///a")?;
168 /// assert_eq!(FileExplorerNode::file(uri.clone(), "a").uri(), &uri);
169 /// # Ok::<(), ailloli_ui_fs::FileError>(())
170 /// ```
171 pub fn uri(&self) -> &FileUri {
172 &self.entry.uri
173 }
174
175 /// Borrows the caller-provided display name.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use ailloli_ui_fs::FileUri;
181 /// use ailloli_ui_widgets::files::FileExplorerNode;
182 /// let node = FileExplorerNode::file(FileUri::parse("file:///a")?, "Alias");
183 /// assert_eq!(node.name(), "Alias");
184 /// # Ok::<(), ailloli_ui_fs::FileError>(())
185 /// ```
186 pub fn name(&self) -> &str {
187 &self.entry.name
188 }
189
190 /// Reports whether the row can represent expandable children.
191 ///
192 /// Directory-like metadata or any non-empty child list makes a branch;
193 /// broken/file symlinks with no children remain leaves.
194 ///
195 /// # Examples
196 ///
197 /// ```
198 /// use ailloli_ui_fs::FileUri;
199 /// use ailloli_ui_widgets::files::FileExplorerNode;
200 /// assert!(!FileExplorerNode::file(FileUri::parse("file:///a")?, "a").is_branch());
201 /// assert!(FileExplorerNode::directory(FileUri::parse("file:///d")?, "d").is_branch());
202 /// # Ok::<(), ailloli_ui_fs::FileError>(())
203 /// ```
204 pub fn is_branch(&self) -> bool {
205 self.entry.metadata.is_directory_like() || !self.children.is_empty()
206 }
207}
208
209/// Flat visible row produced from a recursive [`FileExplorerNode`] tree.
210///
211/// # Examples
212///
213/// ```
214/// use ailloli_ui_fs::FileUri;
215/// use ailloli_ui_widgets::files::{flatten_file_nodes, FileExplorerNode};
216/// let nodes = [FileExplorerNode::file(FileUri::parse("file:///a")?, "a")];
217/// let row = flatten_file_nodes(&nodes, &[]).remove(0);
218/// assert_eq!((row.name.as_str(), row.depth, row.branch), ("a", 0, false));
219/// # Ok::<(), ailloli_ui_fs::FileError>(())
220/// ```
221#[derive(Clone, Debug, PartialEq, Eq)]
222pub struct FileExplorerRow {
223 /// Stable URI used for selection and expansion matching.
224 pub uri: FileUri,
225 /// Visible label copied from the node entry.
226 pub name: String,
227 /// Raw filesystem kind copied from metadata.
228 pub kind: FileKind,
229 /// Zero-based nesting depth in the flattened output.
230 pub depth: usize,
231 /// Whether the row can expose descendants.
232 pub branch: bool,
233 /// Whether interaction is disabled.
234 pub disabled: bool,
235 /// Icon derived from entry metadata and name.
236 pub icon: IconId,
237}
238
239/// Sorts every sibling slice recursively, directories first then by name.
240///
241/// Directory-like symlinks sort with directories. Names compare first by ASCII
242/// lowercase and then by original bytes for deterministic case ties.
243///
244/// # Examples
245///
246/// ```
247/// use ailloli_ui_fs::FileUri;
248/// use ailloli_ui_widgets::files::{sort_file_nodes, FileExplorerNode};
249/// let mut nodes = vec![
250/// FileExplorerNode::file(FileUri::parse("file:///z")?, "z"),
251/// FileExplorerNode::directory(FileUri::parse("file:///src")?, "src"),
252/// ];
253/// sort_file_nodes(&mut nodes);
254/// assert_eq!(nodes[0].name(), "src");
255/// # Ok::<(), ailloli_ui_fs::FileError>(())
256/// ```
257pub fn sort_file_nodes(nodes: &mut [FileExplorerNode]) {
258 nodes.sort_by(compare_nodes);
259 for node in nodes {
260 sort_file_nodes(&mut node.children);
261 }
262}
263
264/// Flattens roots and descendants whose exact branch URI is expanded.
265///
266/// Root rows have depth zero. Expansion does not require an ancestor URI to be
267/// present in `expanded`, but hidden descendants are visited only after their
268/// immediate parent is expanded. Input order is preserved.
269///
270/// # Examples
271///
272/// ```
273/// use ailloli_ui_fs::FileUri;
274/// use ailloli_ui_widgets::files::{flatten_file_nodes, FileExplorerNode};
275/// let src = FileUri::parse("file:///src")?;
276/// let nodes = [FileExplorerNode::directory(src.clone(), "src")
277/// .child(FileExplorerNode::file(FileUri::parse("file:///src/lib.rs")?, "lib.rs"))];
278/// assert_eq!(flatten_file_nodes(&nodes, &[]).len(), 1);
279/// assert_eq!(flatten_file_nodes(&nodes, &[src])[1].depth, 1);
280/// # Ok::<(), ailloli_ui_fs::FileError>(())
281/// ```
282pub fn flatten_file_nodes(
283 nodes: &[FileExplorerNode],
284 expanded: &[FileUri],
285) -> Vec<FileExplorerRow> {
286 let mut out = Vec::new();
287 for node in nodes {
288 flatten_node(node, 0, expanded, &mut out);
289 }
290 out
291}
292
293/// Orders directory-like nodes before leaves, then case-folded and raw names.
294fn compare_nodes(a: &FileExplorerNode, b: &FileExplorerNode) -> std::cmp::Ordering {
295 directory_rank(&a.entry.metadata)
296 .cmp(&directory_rank(&b.entry.metadata))
297 .then_with(|| {
298 a.entry
299 .name
300 .to_ascii_lowercase()
301 .cmp(&b.entry.name.to_ascii_lowercase())
302 })
303 .then_with(|| a.entry.name.cmp(&b.entry.name))
304}
305
306/// Maps directory-like metadata to rank zero and every other kind to one.
307fn directory_rank(metadata: &FileMetadata) -> u8 {
308 if metadata.is_directory_like() {
309 0
310 } else {
311 match metadata.kind {
312 FileKind::File | FileKind::Symlink | FileKind::Other | FileKind::Directory => 1,
313 }
314 }
315}
316
317/// Appends one row and recursively visits children only when exactly expanded.
318fn flatten_node(
319 node: &FileExplorerNode,
320 depth: usize,
321 expanded: &[FileUri],
322 out: &mut Vec<FileExplorerRow>,
323) {
324 let branch = node.is_branch();
325 out.push(FileExplorerRow {
326 uri: node.entry.uri.clone(),
327 name: node.entry.name.clone(),
328 kind: node.entry.metadata.kind,
329 depth,
330 branch,
331 disabled: node.disabled,
332 icon: file_icon_for_entry(&node.entry),
333 });
334 if !node.children.is_empty() && expanded.iter().any(|uri| uri == &node.entry.uri) {
335 for child in &node.children {
336 flatten_node(child, depth + 1, expanded, out);
337 }
338 }
339}
340
341#[cfg(test)]
342/// Covers recursive sorting, symlink branch classification, and expansion.
343mod tests {
344 use super::*;
345
346 /// Builds a local URI fixture from an absolute path.
347 fn uri(path: &str) -> FileUri {
348 FileUri::parse(format!("file://{path}")).expect("uri")
349 }
350
351 /// Builds a symlink node with an optional resolved target kind.
352 fn symlink_node(
353 path: &str,
354 name: impl Into<String>,
355 target: Option<FileKind>,
356 ) -> FileExplorerNode {
357 let mut metadata = FileMetadata::new(FileKind::Symlink);
358 metadata.symlink_target_kind = target;
359 FileExplorerNode::new(FileEntry {
360 uri: uri(path),
361 name: name.into(),
362 metadata,
363 })
364 }
365
366 #[test]
367 fn sorts_directories_before_files_by_name() {
368 let mut nodes = vec![
369 FileExplorerNode::file(uri("/repo/z.rs"), "z.rs"),
370 FileExplorerNode::directory(uri("/repo/src"), "src"),
371 FileExplorerNode::file(uri("/repo/A.md"), "A.md"),
372 ];
373
374 sort_file_nodes(&mut nodes);
375
376 let labels = nodes.iter().map(FileExplorerNode::name).collect::<Vec<_>>();
377 assert_eq!(labels, ["src", "A.md", "z.rs"]);
378 }
379
380 #[test]
381 fn symlink_directories_sort_with_directories() {
382 let mut nodes = vec![
383 FileExplorerNode::file(uri("/repo/main.rs"), "main.rs"),
384 symlink_node("/repo/bin", "bin", Some(FileKind::Directory)),
385 FileExplorerNode::directory(uri("/repo/var"), "var"),
386 ];
387
388 sort_file_nodes(&mut nodes);
389
390 let labels = nodes.iter().map(FileExplorerNode::name).collect::<Vec<_>>();
391 assert_eq!(labels, ["bin", "var", "main.rs"]);
392 }
393
394 #[test]
395 fn real_directory_is_branch() {
396 assert!(FileExplorerNode::directory(uri("/repo/src"), "src").is_branch());
397 }
398
399 #[test]
400 fn real_file_is_leaf() {
401 assert!(!FileExplorerNode::file(uri("/repo/main.rs"), "main.rs").is_branch());
402 }
403
404 #[test]
405 fn symlink_to_directory_is_branch() {
406 assert!(symlink_node("/repo/bin", "bin", Some(FileKind::Directory)).is_branch());
407 }
408
409 #[test]
410 fn symlink_to_file_is_leaf() {
411 assert!(!symlink_node("/repo/bin", "bin", Some(FileKind::File)).is_branch());
412 }
413
414 #[test]
415 fn broken_symlink_is_leaf() {
416 assert!(!symlink_node("/repo/bin", "bin", None).is_branch());
417 }
418
419 #[test]
420 fn flattens_only_expanded_branches() {
421 let src = uri("/repo/src");
422 let nodes = vec![FileExplorerNode::directory(src.clone(), "src")
423 .child(FileExplorerNode::file(uri("/repo/src/main.rs"), "main.rs"))];
424
425 assert_eq!(flatten_file_nodes(&nodes, &[]).len(), 1);
426
427 let rows = flatten_file_nodes(&nodes, &[src]);
428 assert_eq!(rows.len(), 2);
429 assert_eq!(rows[1].depth, 1);
430 assert_eq!(rows[1].name, "main.rs");
431 }
432}