ailloli_ui_widgets/files/
bridge.rs

1//! Incremental projection from the filesystem store into the retained tree model.
2
3use ailloli_ui_fs::{
4    DirectoryLoadState, FileEntry, FileTreeDelta, FileTreeNode, FileTreeNodeId, FileTreeStore,
5    FileTreeStoreDelta,
6};
7
8use crate::controls::{TreeItem, TreeModel, TreeModelError, TreeModelHandle, TreeMutation};
9
10use super::file_icon_for_entry;
11
12/// Failure while constructing or updating a [`FileTreeModelBridge`].
13///
14/// # Examples
15///
16/// ```
17/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
18/// use ailloli_ui_widgets::files::FileTreeModelBridgeError;
19/// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
20/// let error = FileTreeModelBridgeError::MissingNode(store.root());
21/// assert!(error.to_string().contains("missing node"));
22/// # Ok::<(), Box<dyn std::error::Error>>(())
23/// ```
24#[derive(Debug, thiserror::Error)]
25pub enum FileTreeModelBridgeError {
26    /// A store delta or traversal referenced an absent filesystem node.
27    #[error("filesystem delta references missing node {0:?}")]
28    MissingNode(FileTreeNodeId),
29    /// The retained tree model rejected a structural mutation batch.
30    #[error(transparent)]
31    Model(#[from] TreeModelError<FileTreeNodeId>),
32}
33
34/// Applies precise filesystem deltas to a retained UI model without exporting
35/// or cloning a recursive tree snapshot.
36///
37/// Node identifiers are preserved exactly. Construction performs an iterative
38/// depth-first projection of the complete retained store; later updates mutate
39/// one shared [`TreeModelHandle`] in place.
40///
41/// # Examples
42///
43/// ```
44/// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
45/// use ailloli_ui_widgets::files::FileTreeModelBridge;
46/// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
47/// let bridge = FileTreeModelBridge::from_store(&store)?;
48/// assert!(bridge.model().read(|model| model.item(&store.root()).is_some()));
49/// # Ok::<(), Box<dyn std::error::Error>>(())
50/// ```
51#[derive(Debug, Clone)]
52pub struct FileTreeModelBridge {
53    /// Retained generic tree model updated from file-store deltas.
54    model: TreeModelHandle<FileTreeNodeId>,
55}
56
57impl FileTreeModelBridge {
58    /// Projects every current store node into a new retained model.
59    ///
60    /// Store child order becomes model child order, and expanded
61    /// directory-like nodes remain expanded.
62    ///
63    /// # Errors
64    ///
65    /// Returns [`FileTreeModelBridgeError::MissingNode`] for an inconsistent
66    /// child index, or [`FileTreeModelBridgeError::Model`] when the resulting
67    /// mutation batch violates retained-tree invariants.
68    ///
69    /// # Examples
70    ///
71    /// ```
72    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
73    /// use ailloli_ui_widgets::files::FileTreeModelBridge;
74    /// let store = FileTreeStore::new(FileUri::parse("file:///workspace")?, FileMetadata::new(FileKind::Directory))?;
75    /// let bridge = FileTreeModelBridge::from_store(&store)?;
76    /// assert!(bridge.model().read(|model| model.item(&store.root()).is_some()));
77    /// # Ok::<(), Box<dyn std::error::Error>>(())
78    /// ```
79    pub fn from_store(store: &FileTreeStore) -> Result<Self, FileTreeModelBridgeError> {
80        let mut model = TreeModel::new();
81        let mut mutations = Vec::with_capacity(store.len().saturating_mul(2));
82        collect_subtree(store, store.root(), None, 0, &mut mutations)?;
83        model.apply_batch(mutations)?;
84        Ok(Self {
85            model: TreeModelHandle::new(model),
86        })
87    }
88
89    /// Clones the handle to the bridge's shared retained tree model.
90    ///
91    /// Cloning the handle does not clone the tree: updates applied through this
92    /// bridge are immediately visible through every returned handle.
93    ///
94    /// # Examples
95    ///
96    /// ```
97    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
98    /// use ailloli_ui_widgets::files::FileTreeModelBridge;
99    /// let store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
100    /// let bridge = FileTreeModelBridge::from_store(&store)?;
101    /// let model = bridge.model();
102    /// assert!(model.read(|tree| tree.item(&store.root()).is_some()));
103    /// # Ok::<(), Box<dyn std::error::Error>>(())
104    /// ```
105    pub fn model(&self) -> TreeModelHandle<FileTreeNodeId> {
106        self.model.clone()
107    }
108
109    /// Applies an ordered filesystem-store delta to the shared UI model.
110    ///
111    /// Inserts, removals, moves, metadata updates, and directory-state updates
112    /// are batched atomically. Updates for a node already absent from the final
113    /// store remove any stale model row; unsupported delta variants are ignored.
114    ///
115    /// # Errors
116    ///
117    /// Returns [`FileTreeModelBridgeError::Model`] if the translated batch would
118    /// violate retained-tree identity, parent, or ordering invariants.
119    ///
120    /// # Examples
121    ///
122    /// ```
123    /// use ailloli_ui_fs::{FileKind, FileMetadata, FileTreeStore, FileUri};
124    /// use ailloli_ui_widgets::files::FileTreeModelBridge;
125    /// let mut store = FileTreeStore::new(FileUri::parse("file:///")?, FileMetadata::new(FileKind::Directory))?;
126    /// let bridge = FileTreeModelBridge::from_store(&store)?;
127    /// let delta = store.set_expanded(store.root(), true)?;
128    /// bridge.apply_delta(&store, &delta)?;
129    /// assert!(bridge.model().read(|model| model.is_expanded(&store.root())));
130    /// # Ok::<(), Box<dyn std::error::Error>>(())
131    /// ```
132    pub fn apply_delta(
133        &self,
134        store: &FileTreeStore,
135        delta: &FileTreeStoreDelta,
136    ) -> Result<(), FileTreeModelBridgeError> {
137        let mut mutations = Vec::new();
138        for change in delta.changes() {
139            match change {
140                FileTreeDelta::Inserted {
141                    parent,
142                    index,
143                    node,
144                } => {
145                    mutations.push(TreeMutation::Insert {
146                        parent: Some(*parent),
147                        index: *index,
148                        item: tree_item(node),
149                    });
150                    if node.is_expanded() && node.metadata().is_directory_like() {
151                        mutations.push(TreeMutation::SetExpanded {
152                            id: node.id(),
153                            expanded: true,
154                        });
155                    }
156                }
157                FileTreeDelta::Removed { id } => {
158                    if self.model.read(|model| model.item(id).is_some()) {
159                        mutations.push(TreeMutation::Remove { id: *id });
160                    }
161                }
162                FileTreeDelta::Moved {
163                    id,
164                    new_parent,
165                    index,
166                } => mutations.push(TreeMutation::Move {
167                    id: *id,
168                    new_parent: Some(*new_parent),
169                    index: *index,
170                }),
171                FileTreeDelta::Updated { id } | FileTreeDelta::DirectoryState { id, .. } => {
172                    let Some(node) = store.node(*id) else {
173                        // One bounded worker drain can contain an intermediate
174                        // `pending=false` update immediately followed by a
175                        // successful removal. The store is already at its
176                        // final state when deltas reach this projection.
177                        if self.model.read(|model| model.item(id).is_some()) {
178                            mutations.push(TreeMutation::Remove { id: *id });
179                        }
180                        continue;
181                    };
182                    if self.model.read(|model| model.item(id).is_some()) {
183                        mutations.push(TreeMutation::Update {
184                            item: tree_item(node),
185                        });
186                        let expanded = self.model.read(|model| model.is_expanded(id));
187                        if node.metadata().is_directory_like() && expanded != node.is_expanded() {
188                            mutations.push(TreeMutation::SetExpanded {
189                                id: *id,
190                                expanded: node.is_expanded(),
191                            });
192                        }
193                    }
194                }
195                _ => {}
196            }
197        }
198        self.model.apply_batch(mutations)?;
199        Ok(())
200    }
201}
202
203/// Iteratively emits parent-before-child insertions without recursion depth risk.
204///
205/// # Errors
206///
207/// Returns [`FileTreeModelBridgeError::MissingNode`] when `id` or any referenced
208/// descendant is absent from `store`. Mutations already appended before the
209/// missing node remain in the caller-owned vector.
210fn collect_subtree(
211    store: &FileTreeStore,
212    id: FileTreeNodeId,
213    parent: Option<FileTreeNodeId>,
214    index: usize,
215    mutations: &mut Vec<TreeMutation<FileTreeNodeId>>,
216) -> Result<(), FileTreeModelBridgeError> {
217    let mut pending = vec![(id, parent, index)];
218    while let Some((current, parent, index)) = pending.pop() {
219        let node = store
220            .node(current)
221            .ok_or(FileTreeModelBridgeError::MissingNode(current))?;
222        mutations.push(TreeMutation::Insert {
223            parent,
224            index,
225            item: tree_item(node),
226        });
227        if node.is_expanded() && node.metadata().is_directory_like() {
228            mutations.push(TreeMutation::SetExpanded {
229                id: current,
230                expanded: true,
231            });
232        }
233        pending.extend(
234            node.children()
235                .iter()
236                .copied()
237                .enumerate()
238                .rev()
239                .map(|(index, child)| (child, Some(current), index)),
240        );
241    }
242    Ok(())
243}
244
245/// Converts one filesystem node into its retained UI label and decorations.
246fn tree_item(node: &FileTreeNode) -> TreeItem<FileTreeNodeId> {
247    let label = node
248        .uri()
249        .file_name_decoded()
250        .filter(|label| !label.is_empty())
251        .unwrap_or_else(|| node.uri().path().to_string());
252    let entry = FileEntry::new(node.uri().clone(), node.metadata().clone());
253    let item = if node.metadata().is_directory_like() {
254        TreeItem::branch(node.id(), label)
255    } else {
256        TreeItem::leaf(node.id(), label)
257    };
258    item.disabled(matches!(
259        node.directory_state(),
260        DirectoryLoadState::Loading { .. } | DirectoryLoadState::Error(_)
261    ))
262    .leading_icon(file_icon_for_entry(&entry))
263}