ailloli_ui_widgets/controls/tree_model.rs
1//! Stable-ID retained tree model with atomic mutations and a persistent flat index.
2//!
3//! Removed IDs are retired permanently, batches commit all-or-nothing, and each
4//! nonempty successful batch advances a checked `u64` revision exactly once.
5
6use std::cell::RefCell;
7use std::collections::{HashMap, HashSet};
8use std::fmt;
9use std::hash::Hash;
10use std::rc::{Rc, Weak};
11
12use ailloli_ui_core::{Color, IconId};
13
14use super::tree_view::TreeNodeTrailingAction;
15
16/// Stable retained item stored by [`TreeModel`].
17///
18/// Branch/leaf identity belongs to the item rather than being inferred from
19/// children. Builder methods replace optional presentation metadata.
20///
21/// # Examples
22///
23/// ```
24/// use ailloli_ui_widgets::controls::TreeItem;
25/// let item = TreeItem::branch(1_u64, "src").disabled(true);
26/// assert!(item.is_branch());
27/// assert!(item.is_disabled());
28/// ```
29#[derive(Clone, PartialEq)]
30pub struct TreeItem<T> {
31 /// Stable identifier, unique across active and retired IDs.
32 id: T,
33 /// Display label stored unchanged.
34 label: String,
35 /// Whether this item can own children and expansion state.
36 branch: bool,
37 /// Whether selection/navigation should skip the item.
38 disabled: bool,
39 /// Optional leading icon.
40 leading_icon: Option<IconId>,
41 /// Optional leading-icon tint override.
42 leading_icon_tint: Option<Color>,
43 /// Optional trailing action metadata.
44 trailing_action: Option<TreeNodeTrailingAction>,
45 /// Whether the item represents provisional UI state.
46 transient: bool,
47}
48
49impl<T: fmt::Debug> fmt::Debug for TreeItem<T> {
50 /// Formats core identity/state while deliberately omitting tint/action details.
51 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52 formatter
53 .debug_struct("TreeItem")
54 .field("id", &self.id)
55 .field("label", &self.label)
56 .field("branch", &self.branch)
57 .field("disabled", &self.disabled)
58 .field("leading_icon", &self.leading_icon)
59 .field("transient", &self.transient)
60 .finish_non_exhaustive()
61 }
62}
63
64impl<T> TreeItem<T> {
65 /// Creates an enabled branch with no presentation metadata.
66 ///
67 /// # Examples
68 ///
69 /// ```
70 /// use ailloli_ui_widgets::controls::TreeItem;
71 /// let item = TreeItem::branch("root", "Root");
72 /// assert!(item.is_branch());
73 /// ```
74 pub fn branch(id: T, label: impl Into<String>) -> Self {
75 Self::new(id, label, true)
76 }
77
78 /// Creates an enabled leaf with no presentation metadata.
79 ///
80 /// # Examples
81 ///
82 /// ```
83 /// use ailloli_ui_widgets::controls::TreeItem;
84 /// let item = TreeItem::leaf(7, "README.md");
85 /// assert!(!item.is_branch());
86 /// ```
87 pub fn leaf(id: T, label: impl Into<String>) -> Self {
88 Self::new(id, label, false)
89 }
90
91 /// Creates an item with the supplied branch flag and default metadata.
92 fn new(id: T, label: impl Into<String>, branch: bool) -> Self {
93 Self {
94 id,
95 label: label.into(),
96 branch,
97 disabled: false,
98 leading_icon: None,
99 leading_icon_tint: None,
100 trailing_action: None,
101 transient: false,
102 }
103 }
104
105 /// Sets whether the item is unavailable to tree interaction.
106 ///
107 /// # Examples
108 ///
109 /// ```
110 /// use ailloli_ui_widgets::controls::TreeItem;
111 /// assert!(TreeItem::leaf(1, "locked").disabled(true).is_disabled());
112 /// ```
113 pub fn disabled(mut self, disabled: bool) -> Self {
114 self.disabled = disabled;
115 self
116 }
117
118 /// Sets the leading icon, replacing any previous icon.
119 ///
120 /// # Examples
121 ///
122 /// ```
123 /// use ailloli_ui_core::IconId;
124 /// use ailloli_ui_widgets::controls::TreeItem;
125 /// let item = TreeItem::leaf(1, "file").leading_icon(IconId::History);
126 /// assert_eq!(item.leading_icon_ref(), Some(&IconId::History));
127 /// ```
128 pub fn leading_icon(mut self, icon: IconId) -> Self {
129 self.leading_icon = Some(icon);
130 self
131 }
132
133 /// Sets the leading-icon tint override.
134 ///
135 /// # Examples
136 ///
137 /// ```
138 /// use ailloli_ui_core::Color;
139 /// use ailloli_ui_widgets::controls::TreeItem;
140 /// let item = TreeItem::leaf(1, "file").leading_icon_tint(Color::WHITE);
141 /// assert_eq!(item.leading_icon_tint_ref(), Some(Color::WHITE));
142 /// ```
143 pub fn leading_icon_tint(mut self, tint: Color) -> Self {
144 self.leading_icon_tint = Some(tint);
145 self
146 }
147
148 /// Sets trailing action metadata, replacing any previous action.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// use ailloli_ui_core::IconId;
154 /// use ailloli_ui_widgets::controls::{TreeItem, TreeNodeTrailingAction};
155 /// let item = TreeItem::leaf(1, "file").trailing_action(TreeNodeTrailingAction::new(IconId::Close));
156 /// assert!(item.trailing_action_ref().is_some());
157 /// ```
158 pub fn trailing_action(mut self, action: TreeNodeTrailingAction) -> Self {
159 self.trailing_action = Some(action);
160 self
161 }
162
163 /// Marks or unmarks provisional presentation state.
164 ///
165 /// The model does not otherwise treat transient items specially.
166 ///
167 /// # Examples
168 ///
169 /// ```
170 /// use ailloli_ui_widgets::controls::TreeItem;
171 /// assert!(TreeItem::leaf(1, "draft").transient(true).is_transient());
172 /// ```
173 pub fn transient(mut self, transient: bool) -> Self {
174 self.transient = transient;
175 self
176 }
177
178 /// Borrows the stable item identifier.
179 ///
180 /// # Examples
181 ///
182 /// ```
183 /// use ailloli_ui_widgets::controls::TreeItem;
184 /// assert_eq!(TreeItem::leaf(42, "answer").id(), &42);
185 /// ```
186 pub fn id(&self) -> &T {
187 &self.id
188 }
189
190 /// Borrows the stored display label.
191 ///
192 /// # Examples
193 ///
194 /// ```
195 /// use ailloli_ui_widgets::controls::TreeItem;
196 /// assert_eq!(TreeItem::leaf(1, "README").label(), "README");
197 /// ```
198 pub fn label(&self) -> &str {
199 &self.label
200 }
201
202 /// Reports whether the item can own children and expansion state.
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// use ailloli_ui_widgets::controls::TreeItem;
208 /// assert!(TreeItem::branch(1, "dir").is_branch());
209 /// ```
210 pub const fn is_branch(&self) -> bool {
211 self.branch
212 }
213
214 /// Reports whether tree interaction should skip this item.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// use ailloli_ui_widgets::controls::TreeItem;
220 /// assert!(!TreeItem::leaf(1, "file").is_disabled());
221 /// ```
222 pub const fn is_disabled(&self) -> bool {
223 self.disabled
224 }
225
226 /// Borrows the optional leading icon.
227 ///
228 /// # Examples
229 ///
230 /// ```
231 /// use ailloli_ui_widgets::controls::TreeItem;
232 /// assert!(TreeItem::leaf(1, "file").leading_icon_ref().is_none());
233 /// ```
234 pub fn leading_icon_ref(&self) -> Option<&IconId> {
235 self.leading_icon.as_ref()
236 }
237
238 /// Returns the optional leading-icon tint by value.
239 ///
240 /// # Examples
241 ///
242 /// ```
243 /// use ailloli_ui_widgets::controls::TreeItem;
244 /// assert_eq!(TreeItem::leaf(1, "file").leading_icon_tint_ref(), None);
245 /// ```
246 pub const fn leading_icon_tint_ref(&self) -> Option<Color> {
247 self.leading_icon_tint
248 }
249
250 /// Borrows optional trailing action metadata.
251 ///
252 /// # Examples
253 ///
254 /// ```
255 /// use ailloli_ui_widgets::controls::TreeItem;
256 /// assert!(TreeItem::leaf(1, "file").trailing_action_ref().is_none());
257 /// ```
258 pub fn trailing_action_ref(&self) -> Option<&TreeNodeTrailingAction> {
259 self.trailing_action.as_ref()
260 }
261
262 /// Reports whether this is provisional presentation state.
263 ///
264 /// # Examples
265 ///
266 /// ```
267 /// use ailloli_ui_widgets::controls::TreeItem;
268 /// assert!(!TreeItem::leaf(1, "file").is_transient());
269 /// ```
270 pub const fn is_transient(&self) -> bool {
271 self.transient
272 }
273}
274
275/// Atomic retained-tree mutation.
276///
277/// Indices are zero-based insertion positions in the selected root/child list.
278/// A batch validates against a clone and commits all mutations or none.
279///
280/// # Examples
281///
282/// ```
283/// use ailloli_ui_widgets::controls::{TreeItem, TreeMutation};
284/// let mutation = TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") };
285/// assert!(matches!(mutation, TreeMutation::Insert { index: 0, .. }));
286/// ```
287#[non_exhaustive]
288#[derive(Debug, Clone, PartialEq)]
289pub enum TreeMutation<T> {
290 /// Inserts a new, never-used ID at a root or child position.
291 Insert {
292 /// Parent branch ID, or `None` for a root.
293 parent: Option<T>,
294 /// Insertion position in `0..=sibling_count`.
295 index: usize,
296 /// New item; its children start empty and expansion starts false.
297 item: TreeItem<T>,
298 },
299 /// Removes the identified item and its entire descendant subtree.
300 Remove {
301 /// Existing root or descendant ID to retire.
302 id: T,
303 },
304 /// Replaces item metadata while preserving hierarchy and expansion.
305 Update {
306 /// Replacement item carrying an existing ID.
307 item: TreeItem<T>,
308 },
309 /// Moves an existing subtree to a root or branch position.
310 Move {
311 /// Existing subtree root ID.
312 id: T,
313 /// New parent branch, or `None` for roots.
314 new_parent: Option<T>,
315 /// Final position in the target sibling list.
316 index: usize,
317 },
318 /// Changes expansion on an existing branch.
319 SetExpanded {
320 /// Existing branch ID.
321 id: T,
322 /// New expansion state.
323 expanded: bool,
324 },
325}
326
327/// One successfully committed atomic batch.
328///
329/// Empty batches return the current revision and no mutations without advancing
330/// the model. Nonempty batches advance exactly once.
331///
332/// # Examples
333///
334/// ```
335/// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
336/// let mut model = TreeModel::new();
337/// let delta = model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
338/// assert_eq!(delta.revision(), 1);
339/// assert_eq!(delta.mutations().len(), 1);
340/// ```
341#[derive(Debug, Clone, PartialEq)]
342pub struct TreeModelDelta<T> {
343 /// Revision after the batch committed.
344 revision: u64,
345 /// Exact input mutations in application order.
346 mutations: Vec<TreeMutation<T>>,
347}
348
349impl<T> TreeModelDelta<T> {
350 /// Returns the model revision after commit.
351 ///
352 /// # Examples
353 ///
354 /// ```
355 /// use ailloli_ui_widgets::controls::{TreeModel, TreeMutation};
356 /// let mut model = TreeModel::<u8>::new();
357 /// assert_eq!(model.apply_batch(Vec::<TreeMutation<u8>>::new()).unwrap().revision(), 0);
358 /// ```
359 pub const fn revision(&self) -> u64 {
360 self.revision
361 }
362
363 /// Borrows committed mutations in input order.
364 ///
365 /// # Examples
366 ///
367 /// ```
368 /// use ailloli_ui_widgets::controls::{TreeModel, TreeMutation};
369 /// let mut model = TreeModel::<u8>::new();
370 /// let delta = model.apply_batch(Vec::<TreeMutation<u8>>::new()).unwrap();
371 /// assert!(delta.mutations().is_empty());
372 /// ```
373 pub fn mutations(&self) -> &[TreeMutation<T>] {
374 &self.mutations
375 }
376}
377
378/// Validation failure for a retained tree mutation. The whole batch is rolled
379/// back on error.
380///
381/// # Examples
382///
383/// ```
384/// use ailloli_ui_widgets::controls::TreeModelError;
385/// let error = TreeModelError::DuplicateId { id: 7_u64 };
386/// assert!(error.to_string().contains("already exists"));
387/// ```
388#[non_exhaustive]
389#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
390pub enum TreeModelError<T: fmt::Debug> {
391 /// An inserted ID is already active.
392 #[error("tree item already exists: {id:?}")]
393 DuplicateId {
394 /// Active identifier that the insertion attempted to duplicate.
395 id: T,
396 },
397 /// A referenced item or parent does not exist.
398 #[error("tree item does not exist: {id:?}")]
399 MissingId {
400 /// Identifier that could not be resolved in the active model.
401 id: T,
402 },
403 /// An inserted ID was previously removed and permanently retired.
404 #[error("tree item identifier was retired and cannot be reused: {id:?}")]
405 ReusedId {
406 /// Tombstoned identifier that must not be inserted again.
407 id: T,
408 },
409 /// An insertion/move target cannot own children.
410 #[error("parent is not a branch: {id:?}")]
411 ParentIsLeaf {
412 /// Leaf identifier supplied as the requested parent.
413 id: T,
414 },
415 /// An insertion/move position exceeds its allowed inclusive upper bound.
416 #[error("child index {index} is outside 0..={len}")]
417 InvalidIndex {
418 /// Requested zero-based insertion position.
419 index: usize,
420 /// Current child count and inclusive append position.
421 len: usize,
422 },
423 /// A move would make an item its own ancestor.
424 #[error("moving {id:?} below {new_parent:?} would create a cycle")]
425 Cycle {
426 /// Identifier of the item being moved.
427 id: T,
428 /// Descendant identifier proposed as the new parent.
429 new_parent: T,
430 },
431 /// An update attempted to turn a populated branch into a leaf.
432 #[error("a branch with children cannot become a leaf: {id:?}")]
433 NonEmptyBranchToLeaf {
434 /// Populated branch identifier whose kind change was rejected.
435 id: T,
436 },
437 /// Expansion was requested for a leaf.
438 #[error("only branch items can be expanded: {id:?}")]
439 NotBranch {
440 /// Leaf identifier supplied to a branch-only operation.
441 id: T,
442 },
443 /// Incrementing the checked `u64` revision would overflow.
444 #[error("tree model revision space is exhausted")]
445 RevisionExhausted,
446 /// Optimistic mutation expected a different current revision.
447 #[error("stale tree mutation: expected revision {expected}, current revision {actual}")]
448 StaleRevision {
449 /// Revision required by the optimistic mutation.
450 expected: u64,
451 /// Revision held by the model when validation ran.
452 actual: u64,
453 },
454}
455
456#[derive(Debug, Clone, PartialEq, Eq)]
457/// One visible depth-first row in a [`FlatTreeIndex`].
458///
459/// # Examples
460///
461/// ```
462/// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
463/// let mut model = TreeModel::new();
464/// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
465/// let row = &model.flat_index().rows()[0];
466/// assert_eq!((row.node_id(), row.depth()), (&1, 0));
467/// ```
468pub struct FlatTreeRow<T> {
469 /// Stable retained item ID.
470 node_id: T,
471 /// Visible depth, saturating at `u16::MAX`.
472 depth: u16,
473}
474
475impl<T> FlatTreeRow<T> {
476 /// Borrows the row's stable item ID.
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
482 /// let mut model = TreeModel::new();
483 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf("a", "A") }).unwrap();
484 /// assert_eq!(model.flat_index().rows()[0].node_id(), &"a");
485 /// ```
486 pub fn node_id(&self) -> &T {
487 &self.node_id
488 }
489
490 /// Returns the saturated visible hierarchy depth.
491 ///
492 /// # Examples
493 ///
494 /// ```
495 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
496 /// let mut model = TreeModel::new();
497 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "A") }).unwrap();
498 /// assert_eq!(model.flat_index().rows()[0].depth(), 0);
499 /// ```
500 pub const fn depth(&self) -> u16 {
501 self.depth
502 }
503}
504
505/// Persistent visible-row index. It changes only when a model mutation is
506/// committed, never during layout, paint, hit-test, or a pure scroll.
507///
508/// Rows are depth-first in root/child order and include descendants only below
509/// expanded branches.
510///
511/// # Examples
512///
513/// ```
514/// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
515/// let mut model = TreeModel::new();
516/// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
517/// assert_eq!(model.flat_index().rows().len(), 1);
518/// ```
519#[derive(Debug, Clone)]
520pub struct FlatTreeIndex<T> {
521 /// Visible rows in depth-first presentation order.
522 rows: Vec<FlatTreeRow<T>>,
523 /// Constant-time visible ID-to-row lookup.
524 row_by_id: HashMap<T, usize>,
525 /// Model revision represented by this index.
526 revision: u64,
527 /// Saturating count of full index rebuilds.
528 rebuilds: u64,
529 /// First visible non-disabled row, if one exists.
530 first_enabled_row: Option<usize>,
531}
532
533impl<T> Default for FlatTreeIndex<T> {
534 fn default() -> Self {
535 Self {
536 rows: Vec::new(),
537 row_by_id: HashMap::new(),
538 revision: 0,
539 rebuilds: 0,
540 first_enabled_row: None,
541 }
542 }
543}
544
545impl<T: Eq + Hash> FlatTreeIndex<T> {
546 /// Borrows all visible rows in depth-first presentation order.
547 ///
548 /// # Examples
549 ///
550 /// ```
551 /// use ailloli_ui_widgets::controls::TreeModel;
552 /// assert!(TreeModel::<u8>::new().flat_index().rows().is_empty());
553 /// ```
554 pub fn rows(&self) -> &[FlatTreeRow<T>] {
555 &self.rows
556 }
557
558 /// Returns an item's visible zero-based row, or `None` when hidden/missing.
559 ///
560 /// # Examples
561 ///
562 /// ```
563 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
564 /// let mut model = TreeModel::new();
565 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(9, "file") }).unwrap();
566 /// assert_eq!(model.flat_index().row_of(&9), Some(0));
567 /// assert_eq!(model.flat_index().row_of(&8), None);
568 /// ```
569 pub fn row_of(&self, id: &T) -> Option<usize> {
570 self.row_by_id.get(id).copied()
571 }
572
573 /// Returns the model revision represented by the flat index.
574 ///
575 /// # Examples
576 ///
577 /// ```
578 /// use ailloli_ui_widgets::controls::TreeModel;
579 /// assert_eq!(TreeModel::<u8>::new().flat_index().revision(), 0);
580 /// ```
581 pub const fn revision(&self) -> u64 {
582 self.revision
583 }
584
585 /// Returns the saturating count of full index materializations.
586 ///
587 /// Incremental batches normally splice rows and leave this unchanged; batches
588 /// of at least 1,024 mutations rebuild once at commit.
589 ///
590 /// # Examples
591 ///
592 /// ```
593 /// use ailloli_ui_widgets::controls::TreeModel;
594 /// assert_eq!(TreeModel::<u8>::new().flat_index().rebuilds(), 0);
595 /// ```
596 pub const fn rebuilds(&self) -> u64 {
597 self.rebuilds
598 }
599
600 /// Returns the first visible row whose item is not disabled.
601 ///
602 /// # Examples
603 ///
604 /// ```
605 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
606 /// let mut model = TreeModel::new();
607 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "off").disabled(true) }).unwrap();
608 /// assert_eq!(model.flat_index().first_enabled_row(), None);
609 /// ```
610 pub const fn first_enabled_row(&self) -> Option<usize> {
611 self.first_enabled_row
612 }
613}
614
615#[derive(Debug, Clone)]
616/// Internal hierarchy record preserving parent, ordered children, and expansion.
617struct TreeRecord<T> {
618 /// Public item metadata.
619 item: TreeItem<T>,
620 /// Parent ID, or `None` for a root.
621 parent: Option<T>,
622 /// Child IDs in presentation order.
623 children: Vec<T>,
624 /// Whether visible descendants are materialized in the flat index.
625 expanded: bool,
626}
627
628/// Retained hierarchical model with stable identifiers and an incremental
629/// presentation revision.
630///
631/// IDs must remain globally unique for the lifetime of a model: removal retires
632/// an ID and its descendants. Mutations are atomic, and visible rows are cached
633/// persistently for cheap layout/paint access.
634///
635/// # Examples
636///
637/// ```
638/// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
639/// let mut model = TreeModel::new();
640/// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::branch(1, "root") }).unwrap();
641/// assert_eq!((model.len(), model.visible_len(), model.revision()), (1, 1, 1));
642/// ```
643#[derive(Debug, Clone)]
644pub struct TreeModel<T> {
645 /// Active records indexed by stable ID.
646 nodes: HashMap<T, TreeRecord<T>>,
647 /// Root IDs in presentation order.
648 roots: Vec<T>,
649 /// Permanently unavailable IDs removed from this model.
650 retired_ids: HashSet<T>,
651 /// Persistent visible-row index.
652 flat: FlatTreeIndex<T>,
653 /// Checked transaction revision.
654 revision: u64,
655}
656
657impl<T> Default for TreeModel<T> {
658 fn default() -> Self {
659 Self {
660 nodes: HashMap::new(),
661 roots: Vec::new(),
662 retired_ids: HashSet::new(),
663 flat: FlatTreeIndex::default(),
664 revision: 0,
665 }
666 }
667}
668
669impl<T> TreeModel<T>
670where
671 T: Clone + Eq + Hash + fmt::Debug,
672{
673 /// Creates an empty revision-zero model.
674 ///
675 /// # Examples
676 ///
677 /// ```
678 /// use ailloli_ui_widgets::controls::TreeModel;
679 /// let model = TreeModel::<u64>::new();
680 /// assert!(model.is_empty());
681 /// assert_eq!(model.revision(), 0);
682 /// ```
683 pub fn new() -> Self {
684 Self::default()
685 }
686
687 /// Returns the current transaction revision.
688 ///
689 /// Successful nonempty batches increment once; empty batches and failed
690 /// batches leave it unchanged.
691 ///
692 /// # Examples
693 ///
694 /// ```
695 /// use ailloli_ui_widgets::controls::TreeModel;
696 /// assert_eq!(TreeModel::<u8>::new().revision(), 0);
697 /// ```
698 pub const fn revision(&self) -> u64 {
699 self.revision
700 }
701
702 /// Returns active item count, including currently hidden descendants.
703 ///
704 /// # Examples
705 ///
706 /// ```
707 /// use ailloli_ui_widgets::controls::TreeModel;
708 /// assert_eq!(TreeModel::<u8>::new().len(), 0);
709 /// ```
710 pub fn len(&self) -> usize {
711 self.nodes.len()
712 }
713
714 /// Reports whether the model contains no active items.
715 ///
716 /// # Examples
717 ///
718 /// ```
719 /// use ailloli_ui_widgets::controls::TreeModel;
720 /// assert!(TreeModel::<u8>::new().is_empty());
721 /// ```
722 pub fn is_empty(&self) -> bool {
723 self.nodes.is_empty()
724 }
725
726 /// Returns cached visible row count under current expansion state.
727 ///
728 /// # Examples
729 ///
730 /// ```
731 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
732 /// let mut model = TreeModel::new();
733 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
734 /// assert_eq!(model.visible_len(), 1);
735 /// ```
736 pub fn visible_len(&self) -> usize {
737 self.flat.rows.len()
738 }
739
740 /// Borrows the persistent visible-row index.
741 ///
742 /// # Examples
743 ///
744 /// ```
745 /// use ailloli_ui_widgets::controls::TreeModel;
746 /// assert_eq!(TreeModel::<u8>::new().flat_index().revision(), 0);
747 /// ```
748 pub fn flat_index(&self) -> &FlatTreeIndex<T> {
749 &self.flat
750 }
751
752 /// Borrows active item metadata by ID.
753 ///
754 /// Returns `None` for missing and retired IDs.
755 ///
756 /// # Examples
757 ///
758 /// ```
759 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
760 /// let mut model = TreeModel::new();
761 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
762 /// assert_eq!(model.item(&1).unwrap().label(), "file");
763 /// ```
764 pub fn item(&self, id: &T) -> Option<&TreeItem<T>> {
765 self.nodes.get(id).map(|record| &record.item)
766 }
767
768 /// Borrows an active item's parent ID.
769 ///
770 /// Returns `None` both for roots and missing IDs; use [`Self::item`] when the
771 /// distinction matters.
772 ///
773 /// # Examples
774 ///
775 /// ```
776 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
777 /// let mut model = TreeModel::new();
778 /// model.apply_batch([
779 /// TreeMutation::Insert { parent: None, index: 0, item: TreeItem::branch(1, "root") },
780 /// TreeMutation::Insert { parent: Some(1), index: 0, item: TreeItem::leaf(2, "file") },
781 /// ]).unwrap();
782 /// assert_eq!(model.parent(&2), Some(&1));
783 /// ```
784 pub fn parent(&self, id: &T) -> Option<&T> {
785 self.nodes.get(id).and_then(|record| record.parent.as_ref())
786 }
787
788 /// Borrows an active item's child IDs in presentation order.
789 ///
790 /// Leaves return `Some(empty)`; missing IDs return `None`.
791 ///
792 /// # Examples
793 ///
794 /// ```
795 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
796 /// let mut model = TreeModel::new();
797 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
798 /// assert_eq!(model.children(&1), Some([].as_slice()));
799 /// ```
800 pub fn children(&self, id: &T) -> Option<&[T]> {
801 self.nodes.get(id).map(|record| record.children.as_slice())
802 }
803
804 /// Borrows root IDs in presentation order.
805 ///
806 /// # Examples
807 ///
808 /// ```
809 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
810 /// let mut model = TreeModel::new();
811 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(7, "root") }).unwrap();
812 /// assert_eq!(model.roots(), &[7]);
813 /// ```
814 pub fn roots(&self) -> &[T] {
815 &self.roots
816 }
817
818 /// Reports expansion for an active branch.
819 ///
820 /// Missing IDs and leaves return `false`.
821 ///
822 /// # Examples
823 ///
824 /// ```
825 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
826 /// let mut model = TreeModel::new();
827 /// model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::branch(1, "root") }).unwrap();
828 /// assert!(!model.is_expanded(&1));
829 /// ```
830 pub fn is_expanded(&self, id: &T) -> bool {
831 self.nodes.get(id).is_some_and(|record| record.expanded)
832 }
833
834 /// Atomically applies one mutation.
835 ///
836 /// On validation failure the complete hierarchy, flat index, retired IDs,
837 /// and revision remain unchanged.
838 ///
839 /// # Errors
840 ///
841 /// Returns [`TreeModelError`] for invalid IDs, parents, indices, cycles,
842 /// branch transitions, expansion, or revision overflow.
843 ///
844 /// # Examples
845 ///
846 /// ```
847 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
848 /// let mut model = TreeModel::new();
849 /// let delta = model.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
850 /// assert_eq!(delta.revision(), 1);
851 /// ```
852 pub fn apply(
853 &mut self,
854 mutation: TreeMutation<T>,
855 ) -> Result<TreeModelDelta<T>, TreeModelError<T>> {
856 self.apply_batch([mutation])
857 }
858
859 /// Applies a batch only when the caller still observes `expected_revision`.
860 ///
861 /// This lets worker/UI bridges reject stale structural mutations without
862 /// partially changing the retained model. Revision comparison precedes input
863 /// collection and validation.
864 ///
865 /// # Errors
866 ///
867 /// Returns [`TreeModelError::StaleRevision`] on mismatch, otherwise the same
868 /// validation errors as [`Self::apply_batch`].
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelError, TreeMutation};
874 /// let mut model = TreeModel::<u8>::new();
875 /// let error = model.apply_batch_if_revision(1, Vec::<TreeMutation<u8>>::new()).unwrap_err();
876 /// assert_eq!(error, TreeModelError::StaleRevision { expected: 1, actual: 0 });
877 /// ```
878 pub fn apply_batch_if_revision(
879 &mut self,
880 expected_revision: u64,
881 mutations: impl IntoIterator<Item = TreeMutation<T>>,
882 ) -> Result<TreeModelDelta<T>, TreeModelError<T>> {
883 if self.revision != expected_revision {
884 return Err(TreeModelError::StaleRevision {
885 expected: expected_revision,
886 actual: self.revision,
887 });
888 }
889 self.apply_batch(mutations)
890 }
891
892 /// Atomically applies mutations in iterator order as one transaction.
893 ///
894 /// Empty input succeeds without revision change. Nonempty success increments
895 /// once. Batches of at least 1,024 mutations defer flat-index materialization
896 /// to the transaction boundary; smaller batches splice it incrementally.
897 ///
898 /// # Errors
899 ///
900 /// Returns the first validation error and commits no candidate state.
901 ///
902 /// # Examples
903 ///
904 /// ```
905 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeMutation};
906 /// let mut model = TreeModel::new();
907 /// let delta = model.apply_batch([
908 /// TreeMutation::Insert { parent: None, index: 0, item: TreeItem::branch(1, "root") },
909 /// TreeMutation::Insert { parent: Some(1), index: 0, item: TreeItem::leaf(2, "file") },
910 /// ]).unwrap();
911 /// assert_eq!((delta.revision(), model.len()), (1, 2));
912 /// ```
913 pub fn apply_batch(
914 &mut self,
915 mutations: impl IntoIterator<Item = TreeMutation<T>>,
916 ) -> Result<TreeModelDelta<T>, TreeModelError<T>> {
917 let mutations: Vec<_> = mutations.into_iter().collect();
918 if mutations.is_empty() {
919 return Ok(TreeModelDelta {
920 revision: self.revision,
921 mutations,
922 });
923 }
924 let mut candidate = self.clone();
925 // A large provider result is one logical model transaction even when
926 // its parent already exists. Updating the row-to-id map after every
927 // inserted row would turn opening directories such as `/bin` into
928 // O(N²) UI-thread work. Materialize the persistent index once at the
929 // transaction boundary; ordinary interactive batches continue to use
930 // the precise splice path below.
931 let bulk_materialization = mutations.len() >= 1_024;
932 if bulk_materialization {
933 for mutation in &mutations {
934 candidate.apply_one_hierarchy(mutation)?;
935 }
936 } else {
937 for mutation in &mutations {
938 candidate.apply_one_incremental(mutation)?;
939 }
940 }
941 candidate.revision = self
942 .revision
943 .checked_add(1)
944 .ok_or(TreeModelError::RevisionExhausted)?;
945 if bulk_materialization {
946 candidate.rebuild_flat_index();
947 }
948 candidate.flat.revision = candidate.revision;
949 candidate.refresh_flat_metadata();
950 let revision = candidate.revision;
951 *self = candidate;
952 Ok(TreeModelDelta {
953 revision,
954 mutations,
955 })
956 }
957
958 /// Applies one mutation to hierarchy only, used by bulk transactions.
959 ///
960 /// # Errors
961 ///
962 /// Propagates the mutation-specific [`TreeModelError`] documented by
963 /// [`Self::insert`], [`Self::remove`], [`Self::update`],
964 /// [`Self::move_item`], or [`Self::set_expanded`].
965 fn apply_one_hierarchy(&mut self, mutation: &TreeMutation<T>) -> Result<(), TreeModelError<T>> {
966 match mutation {
967 TreeMutation::Insert {
968 parent,
969 index,
970 item,
971 } => self.insert(parent.clone(), *index, item.clone()),
972 TreeMutation::Remove { id } => self.remove(id),
973 TreeMutation::Update { item } => self.update(item.clone()),
974 TreeMutation::Move {
975 id,
976 new_parent,
977 index,
978 } => self.move_item(id, new_parent.clone(), *index),
979 TreeMutation::SetExpanded { id, expanded } => self.set_expanded(id, *expanded),
980 }
981 }
982
983 /// Applies one mutation and splices the persistent visible-row index.
984 ///
985 /// # Errors
986 ///
987 /// Propagates the hierarchy-validation errors documented by the private
988 /// mutation helpers, plus [`TreeModelError::MissingId`] if a newly inserted
989 /// visible subtree cannot resolve its root.
990 ///
991 /// # Panics
992 ///
993 /// Panics only if a successful hierarchy mutation leaves the private flat
994 /// index inconsistent with the active node and parent records.
995 fn apply_one_incremental(
996 &mut self,
997 mutation: &TreeMutation<T>,
998 ) -> Result<(), TreeModelError<T>> {
999 match mutation {
1000 TreeMutation::Insert {
1001 parent,
1002 index,
1003 item,
1004 } => {
1005 self.insert(parent.clone(), *index, item.clone())?;
1006 self.insert_visible_subtree(item.id())
1007 }
1008 TreeMutation::Remove { id } => {
1009 self.remove_visible_subtree(id);
1010 self.remove(id)
1011 }
1012 TreeMutation::Update { item } => self.update(item.clone()),
1013 TreeMutation::Move {
1014 id,
1015 new_parent,
1016 index,
1017 } => {
1018 self.remove_visible_subtree(id);
1019 self.move_item(id, new_parent.clone(), *index)?;
1020 self.insert_visible_subtree(id)
1021 }
1022 TreeMutation::SetExpanded { id, expanded } => {
1023 let was_expanded = self.is_expanded(id);
1024 self.set_expanded(id, *expanded)?;
1025 if was_expanded == *expanded {
1026 return Ok(());
1027 }
1028 let Some(row) = self.flat.row_of(id) else {
1029 return Ok(());
1030 };
1031 if *expanded {
1032 let depth = self.flat.rows[row].depth.saturating_add(1);
1033 let mut rows = Vec::new();
1034 for child in self
1035 .nodes
1036 .get(id)
1037 .expect("expanded node exists")
1038 .children
1039 .clone()
1040 {
1041 self.push_visible(&child, depth, &mut rows);
1042 }
1043 self.flat.rows.splice(row + 1..row + 1, rows);
1044 } else {
1045 let range = self.visible_descendant_range(row);
1046 self.flat.rows.drain(range);
1047 }
1048 self.refresh_flat_metadata();
1049 Ok(())
1050 }
1051 }
1052 }
1053
1054 /// Validates and inserts an initially collapsed childless record.
1055 ///
1056 /// # Errors
1057 ///
1058 /// Returns [`TreeModelError::DuplicateId`] or [`TreeModelError::ReusedId`]
1059 /// for an invalid identity, [`TreeModelError::MissingId`] or
1060 /// [`TreeModelError::ParentIsLeaf`] for an invalid parent, and
1061 /// [`TreeModelError::InvalidIndex`] when `index` exceeds the append position.
1062 ///
1063 /// # Panics
1064 ///
1065 /// Panics only if the validated parent disappears from this exclusively
1066 /// borrowed model before the child link is inserted.
1067 fn insert(
1068 &mut self,
1069 parent: Option<T>,
1070 index: usize,
1071 item: TreeItem<T>,
1072 ) -> Result<(), TreeModelError<T>> {
1073 let id = item.id.clone();
1074 if self.nodes.contains_key(&id) {
1075 return Err(TreeModelError::DuplicateId { id });
1076 }
1077 if self.retired_ids.contains(&id) {
1078 return Err(TreeModelError::ReusedId { id });
1079 }
1080 if let Some(parent_id) = &parent {
1081 let parent_record =
1082 self.nodes
1083 .get(parent_id)
1084 .ok_or_else(|| TreeModelError::MissingId {
1085 id: parent_id.clone(),
1086 })?;
1087 if !parent_record.item.branch {
1088 return Err(TreeModelError::ParentIsLeaf {
1089 id: parent_id.clone(),
1090 });
1091 }
1092 if index > parent_record.children.len() {
1093 return Err(TreeModelError::InvalidIndex {
1094 index,
1095 len: parent_record.children.len(),
1096 });
1097 }
1098 } else if index > self.roots.len() {
1099 return Err(TreeModelError::InvalidIndex {
1100 index,
1101 len: self.roots.len(),
1102 });
1103 }
1104
1105 self.nodes.insert(
1106 id.clone(),
1107 TreeRecord {
1108 item,
1109 parent: parent.clone(),
1110 children: Vec::new(),
1111 expanded: false,
1112 },
1113 );
1114 match parent {
1115 Some(parent) => self
1116 .nodes
1117 .get_mut(&parent)
1118 .expect("validated parent")
1119 .children
1120 .insert(index, id),
1121 None => self.roots.insert(index, id),
1122 }
1123 Ok(())
1124 }
1125
1126 /// Detaches and iteratively retires an item and every descendant.
1127 ///
1128 /// # Errors
1129 ///
1130 /// Returns [`TreeModelError::MissingId`] when `id` is not active.
1131 ///
1132 /// # Panics
1133 ///
1134 /// Panics if the active item's recorded parent is absent, which would
1135 /// violate the model's private hierarchy invariant.
1136 fn remove(&mut self, id: &T) -> Result<(), TreeModelError<T>> {
1137 let parent = self
1138 .nodes
1139 .get(id)
1140 .ok_or_else(|| TreeModelError::MissingId { id: id.clone() })?
1141 .parent
1142 .clone();
1143 self.detach_from_parent(id, parent.as_ref());
1144 let mut pending = vec![id.clone()];
1145 while let Some(current) = pending.pop() {
1146 if let Some(record) = self.nodes.remove(¤t) {
1147 pending.extend(record.children);
1148 self.retired_ids.insert(current);
1149 }
1150 }
1151 Ok(())
1152 }
1153
1154 /// Replaces metadata, rejecting leaf conversion for a populated branch.
1155 ///
1156 /// # Errors
1157 ///
1158 /// Returns [`TreeModelError::MissingId`] for an inactive item, or
1159 /// [`TreeModelError::NonEmptyBranchToLeaf`] when the update would strand
1160 /// existing children beneath a leaf.
1161 fn update(&mut self, item: TreeItem<T>) -> Result<(), TreeModelError<T>> {
1162 let id = item.id.clone();
1163 let record = self
1164 .nodes
1165 .get_mut(&id)
1166 .ok_or_else(|| TreeModelError::MissingId { id: id.clone() })?;
1167 if !item.branch && !record.children.is_empty() {
1168 return Err(TreeModelError::NonEmptyBranchToLeaf { id });
1169 }
1170 record.item = item;
1171 if !record.item.branch {
1172 record.expanded = false;
1173 }
1174 Ok(())
1175 }
1176
1177 /// Validates and moves one subtree to its final sibling position.
1178 ///
1179 /// # Errors
1180 ///
1181 /// Returns [`TreeModelError::MissingId`] for an absent item or parent,
1182 /// [`TreeModelError::ParentIsLeaf`] for a leaf destination,
1183 /// [`TreeModelError::Cycle`] for a self/descendant destination, or
1184 /// [`TreeModelError::InvalidIndex`] for an invalid final sibling position.
1185 ///
1186 /// # Panics
1187 ///
1188 /// Panics only if validated node/parent links disappear while this method
1189 /// holds exclusive access, indicating an already-corrupt hierarchy.
1190 fn move_item(
1191 &mut self,
1192 id: &T,
1193 new_parent: Option<T>,
1194 index: usize,
1195 ) -> Result<(), TreeModelError<T>> {
1196 let old_parent = self
1197 .nodes
1198 .get(id)
1199 .ok_or_else(|| TreeModelError::MissingId { id: id.clone() })?
1200 .parent
1201 .clone();
1202 if let Some(parent) = &new_parent {
1203 let parent_record = self
1204 .nodes
1205 .get(parent)
1206 .ok_or_else(|| TreeModelError::MissingId { id: parent.clone() })?;
1207 if !parent_record.item.branch {
1208 return Err(TreeModelError::ParentIsLeaf { id: parent.clone() });
1209 }
1210 if parent == id || self.is_descendant_of(parent, id) {
1211 return Err(TreeModelError::Cycle {
1212 id: id.clone(),
1213 new_parent: parent.clone(),
1214 });
1215 }
1216 }
1217
1218 let target_len = new_parent
1219 .as_ref()
1220 .and_then(|parent| self.nodes.get(parent).map(|record| record.children.len()))
1221 .unwrap_or(self.roots.len());
1222 let same_container = old_parent == new_parent;
1223 let max_index = if same_container {
1224 target_len.saturating_sub(1)
1225 } else {
1226 target_len
1227 };
1228 if index > max_index {
1229 return Err(TreeModelError::InvalidIndex {
1230 index,
1231 len: max_index,
1232 });
1233 }
1234
1235 self.detach_from_parent(id, old_parent.as_ref());
1236 match &new_parent {
1237 Some(parent) => self
1238 .nodes
1239 .get_mut(parent)
1240 .expect("validated parent")
1241 .children
1242 .insert(index, id.clone()),
1243 None => self.roots.insert(index, id.clone()),
1244 }
1245 self.nodes.get_mut(id).expect("validated item").parent = new_parent;
1246 Ok(())
1247 }
1248
1249 /// Sets expansion only on an existing branch.
1250 ///
1251 /// # Errors
1252 ///
1253 /// Returns [`TreeModelError::MissingId`] for an inactive item or
1254 /// [`TreeModelError::NotBranch`] when `id` identifies a leaf.
1255 fn set_expanded(&mut self, id: &T, expanded: bool) -> Result<(), TreeModelError<T>> {
1256 let record = self
1257 .nodes
1258 .get_mut(id)
1259 .ok_or_else(|| TreeModelError::MissingId { id: id.clone() })?;
1260 if !record.item.branch {
1261 return Err(TreeModelError::NotBranch { id: id.clone() });
1262 }
1263 record.expanded = expanded;
1264 Ok(())
1265 }
1266
1267 /// Removes an ID from its parent child list or root list when present.
1268 fn detach_from_parent(&mut self, id: &T, parent: Option<&T>) {
1269 let siblings = match parent {
1270 Some(parent) => {
1271 &mut self
1272 .nodes
1273 .get_mut(parent)
1274 .expect("validated parent")
1275 .children
1276 }
1277 None => &mut self.roots,
1278 };
1279 if let Some(index) = siblings.iter().position(|candidate| candidate == id) {
1280 siblings.remove(index);
1281 }
1282 }
1283
1284 /// Walks parent links and reports whether candidate is at/below ancestor.
1285 fn is_descendant_of(&self, candidate: &T, ancestor: &T) -> bool {
1286 let mut current = Some(candidate);
1287 while let Some(id) = current {
1288 if id == ancestor {
1289 return true;
1290 }
1291 current = self.nodes.get(id).and_then(|record| record.parent.as_ref());
1292 }
1293 false
1294 }
1295
1296 /// Rebuilds visible ID lookup and first-enabled row from cached rows.
1297 fn refresh_flat_metadata(&mut self) {
1298 self.flat.row_by_id = self
1299 .flat
1300 .rows
1301 .iter()
1302 .enumerate()
1303 .map(|(index, row): (usize, &FlatTreeRow<T>)| (row.node_id.clone(), index))
1304 .collect();
1305 self.flat.first_enabled_row = self.flat.rows.iter().position(|row| {
1306 self.nodes
1307 .get(&row.node_id)
1308 .is_some_and(|record| !record.item.disabled)
1309 });
1310 }
1311
1312 /// Fully materializes visible rows and saturating-increments rebuild count.
1313 fn rebuild_flat_index(&mut self) {
1314 let mut rows = Vec::with_capacity(self.nodes.len());
1315 for root in &self.roots {
1316 self.push_visible(root, 0, &mut rows);
1317 }
1318 self.flat.rows = rows;
1319 self.flat.rebuilds = self.flat.rebuilds.saturating_add(1);
1320 }
1321
1322 /// Removes a visible row and its visible descendants when materialized.
1323 fn remove_visible_subtree(&mut self, id: &T) {
1324 let Some(row) = self.flat.row_of(id) else {
1325 return;
1326 };
1327 let range = row..self.visible_descendant_range(row).end;
1328 self.flat.rows.drain(range);
1329 self.refresh_flat_metadata();
1330 }
1331
1332 /// Inserts a subtree's visible rows when its parent path is visible/expanded.
1333 ///
1334 /// # Errors
1335 ///
1336 /// Returns [`TreeModelError::MissingId`] when `id` is not active.
1337 ///
1338 /// # Panics
1339 ///
1340 /// Panics if an active record is not linked from its recorded parent or root,
1341 /// or if a visible parent row is missing from the flat-row backing vector.
1342 fn insert_visible_subtree(&mut self, id: &T) -> Result<(), TreeModelError<T>> {
1343 let record = self
1344 .nodes
1345 .get(id)
1346 .ok_or_else(|| TreeModelError::MissingId { id: id.clone() })?;
1347 let (insert_at, depth) = match record.parent.as_ref() {
1348 Some(parent) => {
1349 let Some(parent_row) = self.flat.row_of(parent) else {
1350 return Ok(());
1351 };
1352 if !self.is_expanded(parent) {
1353 return Ok(());
1354 }
1355 let siblings = &self.nodes.get(parent).expect("parent exists").children;
1356 let index = siblings
1357 .iter()
1358 .position(|sibling| sibling == id)
1359 .expect("inserted child is linked");
1360 let insert_at = siblings
1361 .get(index + 1)
1362 .and_then(|next| self.flat.row_of(next))
1363 .unwrap_or_else(|| self.visible_descendant_range(parent_row).end);
1364 (
1365 insert_at,
1366 self.flat.rows[parent_row].depth.saturating_add(1),
1367 )
1368 }
1369 None => {
1370 let index = self
1371 .roots
1372 .iter()
1373 .position(|root| root == id)
1374 .expect("inserted root is linked");
1375 let insert_at = self
1376 .roots
1377 .get(index + 1)
1378 .and_then(|next| self.flat.row_of(next))
1379 .unwrap_or(self.flat.rows.len());
1380 (insert_at, 0)
1381 }
1382 };
1383 let mut rows = Vec::new();
1384 self.push_visible(id, depth, &mut rows);
1385 self.flat.rows.splice(insert_at..insert_at, rows);
1386 self.refresh_flat_metadata();
1387 Ok(())
1388 }
1389
1390 /// Returns visible descendants after `row`, excluding the row itself.
1391 fn visible_descendant_range(&self, row: usize) -> std::ops::Range<usize> {
1392 let depth = self.flat.rows[row].depth;
1393 let end = self
1394 .flat
1395 .rows
1396 .iter()
1397 .enumerate()
1398 .skip(row + 1)
1399 .find(|(_, candidate)| candidate.depth <= depth)
1400 .map_or(self.flat.rows.len(), |(index, _)| index);
1401 row + 1..end
1402 }
1403
1404 /// Iteratively appends a depth-first expanded subtree with saturating depth.
1405 fn push_visible(&self, id: &T, depth: u16, rows: &mut Vec<FlatTreeRow<T>>) {
1406 // Model depth is user-controlled; never recurse on the process stack.
1407 let mut pending = vec![(id.clone(), depth)];
1408 while let Some((current, current_depth)) = pending.pop() {
1409 let Some(record) = self.nodes.get(¤t) else {
1410 continue;
1411 };
1412 rows.push(FlatTreeRow {
1413 node_id: current,
1414 depth: current_depth,
1415 });
1416 if record.expanded {
1417 pending.extend(
1418 record
1419 .children
1420 .iter()
1421 .rev()
1422 .cloned()
1423 .map(|child| (child, current_depth.saturating_add(1))),
1424 );
1425 }
1426 }
1427 }
1428}
1429
1430/// Revision listener stored weakly by the shared handle.
1431type RevisionCallback = dyn Fn(u64);
1432
1433#[derive(Default)]
1434/// Weak subscriber slots and wrapping allocation cursor.
1435struct SubscriberRegistry {
1436 /// Next subscription slot ID; wraps after `u64::MAX`.
1437 next_id: u64,
1438 /// Weak callbacks keyed by their guard-owned slot ID.
1439 callbacks: HashMap<u64, Weak<RevisionCallback>>,
1440}
1441
1442/// UI-local shared handle for a retained tree model.
1443///
1444/// Clones share one `Rc<RefCell<_>>` model and subscriber registry, so the handle
1445/// is single-threaded. Successful nonempty writes notify live weak subscribers
1446/// after releasing internal mutable borrows.
1447///
1448/// # Examples
1449///
1450/// ```
1451/// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeModelHandle, TreeMutation};
1452/// let handle = TreeModelHandle::new(TreeModel::new());
1453/// handle.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
1454/// assert_eq!(handle.revision(), 1);
1455/// ```
1456#[derive(Clone)]
1457pub struct TreeModelHandle<T> {
1458 /// Shared single-threaded retained model.
1459 model: Rc<RefCell<TreeModel<T>>>,
1460 /// Shared weak revision subscribers.
1461 subscribers: Rc<RefCell<SubscriberRegistry>>,
1462}
1463
1464impl<T> fmt::Debug for TreeModelHandle<T>
1465where
1466 T: Clone + Eq + Hash + fmt::Debug,
1467{
1468 /// Formats revision and active/visible counts without dumping hierarchy.
1469 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1470 let model = self.model.borrow();
1471 formatter
1472 .debug_struct("TreeModelHandle")
1473 .field("revision", &model.revision())
1474 .field("nodes", &model.len())
1475 .field("visible", &model.visible_len())
1476 .finish_non_exhaustive()
1477 }
1478}
1479
1480impl<T> Default for TreeModelHandle<T> {
1481 fn default() -> Self {
1482 Self {
1483 model: Rc::new(RefCell::new(TreeModel::default())),
1484 subscribers: Rc::new(RefCell::new(SubscriberRegistry::default())),
1485 }
1486 }
1487}
1488
1489impl<T> TreeModelHandle<T>
1490where
1491 T: Clone + Eq + Hash + fmt::Debug,
1492{
1493 /// Wraps an existing model in a new unshared subscriber registry.
1494 ///
1495 /// # Examples
1496 ///
1497 /// ```
1498 /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1499 /// let handle = TreeModelHandle::new(TreeModel::<u64>::new());
1500 /// assert_eq!(handle.revision(), 0);
1501 /// ```
1502 pub fn new(model: TreeModel<T>) -> Self {
1503 Self {
1504 model: Rc::new(RefCell::new(model)),
1505 subscribers: Rc::new(RefCell::new(SubscriberRegistry::default())),
1506 }
1507 }
1508
1509 /// Returns the shared model's current revision.
1510 ///
1511 /// # Panics
1512 ///
1513 /// Panics on reentrant access while the model is mutably borrowed.
1514 ///
1515 /// # Examples
1516 ///
1517 /// ```
1518 /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1519 /// assert_eq!(TreeModelHandle::new(TreeModel::<u8>::new()).revision(), 0);
1520 /// ```
1521 pub fn revision(&self) -> u64 {
1522 self.model.borrow().revision()
1523 }
1524
1525 /// Runs `read` under a shared borrow and returns its result.
1526 ///
1527 /// # Panics
1528 ///
1529 /// Panics on conflicting reentrant model access. Do not call handle mutation
1530 /// methods from inside the closure.
1531 ///
1532 /// # Examples
1533 ///
1534 /// ```
1535 /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1536 /// let handle = TreeModelHandle::new(TreeModel::<u8>::new());
1537 /// assert_eq!(handle.read(|model| model.len()), 0);
1538 /// ```
1539 pub fn read<R>(&self, read: impl FnOnce(&TreeModel<T>) -> R) -> R {
1540 read(&self.model.borrow())
1541 }
1542
1543 /// Atomically applies one mutation and notifies on nonempty success.
1544 ///
1545 /// # Errors
1546 ///
1547 /// Returns model validation or revision-overflow errors.
1548 ///
1549 /// # Panics
1550 ///
1551 /// Panics on conflicting reentrant model/subscriber borrows.
1552 ///
1553 /// # Examples
1554 ///
1555 /// ```
1556 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeModelHandle, TreeMutation};
1557 /// let handle = TreeModelHandle::new(TreeModel::new());
1558 /// handle.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
1559 /// assert_eq!(handle.read(|model| model.len()), 1);
1560 /// ```
1561 pub fn apply(&self, mutation: TreeMutation<T>) -> Result<TreeModelDelta<T>, TreeModelError<T>> {
1562 self.apply_batch([mutation])
1563 }
1564
1565 /// Atomically applies a batch and notifies once on nonempty success.
1566 ///
1567 /// Empty batches do not notify or advance revision.
1568 ///
1569 /// # Errors
1570 ///
1571 /// Returns the first model validation error without committing candidate state.
1572 ///
1573 /// # Panics
1574 ///
1575 /// Panics on conflicting reentrant model/subscriber borrows.
1576 ///
1577 /// # Examples
1578 ///
1579 /// ```
1580 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeModelHandle, TreeMutation};
1581 /// let handle = TreeModelHandle::new(TreeModel::new());
1582 /// let delta = handle.apply_batch([TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }]).unwrap();
1583 /// assert_eq!(delta.revision(), 1);
1584 /// ```
1585 pub fn apply_batch(
1586 &self,
1587 mutations: impl IntoIterator<Item = TreeMutation<T>>,
1588 ) -> Result<TreeModelDelta<T>, TreeModelError<T>> {
1589 let delta = self.model.borrow_mut().apply_batch(mutations)?;
1590 if !delta.mutations.is_empty() {
1591 self.notify(delta.revision);
1592 }
1593 Ok(delta)
1594 }
1595
1596 /// Applies and notifies only when `expected_revision` is still current.
1597 ///
1598 /// # Errors
1599 ///
1600 /// Returns [`TreeModelError::StaleRevision`] on mismatch or another model
1601 /// validation error without committing candidate state.
1602 ///
1603 /// # Panics
1604 ///
1605 /// Panics on conflicting reentrant model/subscriber borrows.
1606 ///
1607 /// # Examples
1608 ///
1609 /// ```
1610 /// use ailloli_ui_widgets::controls::{TreeModel, TreeModelError, TreeModelHandle, TreeMutation};
1611 /// let handle = TreeModelHandle::new(TreeModel::<u8>::new());
1612 /// let error = handle.apply_batch_if_revision(2, Vec::<TreeMutation<u8>>::new()).unwrap_err();
1613 /// assert_eq!(error, TreeModelError::StaleRevision { expected: 2, actual: 0 });
1614 /// ```
1615 pub fn apply_batch_if_revision(
1616 &self,
1617 expected_revision: u64,
1618 mutations: impl IntoIterator<Item = TreeMutation<T>>,
1619 ) -> Result<TreeModelDelta<T>, TreeModelError<T>> {
1620 let delta = self
1621 .model
1622 .borrow_mut()
1623 .apply_batch_if_revision(expected_revision, mutations)?;
1624 if !delta.mutations.is_empty() {
1625 self.notify(delta.revision);
1626 }
1627 Ok(delta)
1628 }
1629
1630 /// Registers a weak revision listener.
1631 ///
1632 /// The model never owns the target; dropping either the callback or returned
1633 /// guard removes the edge. The callback runs after model/subscriber mutable
1634 /// borrows are released and receives the committed revision.
1635 ///
1636 /// # Panics
1637 ///
1638 /// Panics on conflicting reentrant subscriber-registry access.
1639 ///
1640 /// # Examples
1641 ///
1642 /// ```
1643 /// use std::cell::Cell;
1644 /// use std::rc::Rc;
1645 /// use ailloli_ui_widgets::controls::{TreeItem, TreeModel, TreeModelHandle, TreeMutation};
1646 /// let handle = TreeModelHandle::new(TreeModel::new());
1647 /// let seen = Rc::new(Cell::new(0));
1648 /// let sink = seen.clone();
1649 /// let callback: Rc<dyn Fn(u64)> = Rc::new(move |revision| sink.set(revision));
1650 /// let _guard = handle.subscribe(&callback);
1651 /// handle.apply(TreeMutation::Insert { parent: None, index: 0, item: TreeItem::leaf(1, "file") }).unwrap();
1652 /// assert_eq!(seen.get(), 1);
1653 /// ```
1654 pub fn subscribe(&self, callback: &Rc<RevisionCallback>) -> TreeModelSubscription {
1655 let mut subscribers = self.subscribers.borrow_mut();
1656 let id = subscribers.next_id;
1657 subscribers.next_id = subscribers.next_id.wrapping_add(1);
1658 subscribers.callbacks.insert(id, Rc::downgrade(callback));
1659 TreeModelSubscription {
1660 id,
1661 subscribers: Rc::downgrade(&self.subscribers),
1662 }
1663 }
1664
1665 /// Prunes dead callbacks and invokes upgraded listeners outside registry borrow.
1666 fn notify(&self, revision: u64) {
1667 let callbacks: Vec<_> = {
1668 let mut subscribers = self.subscribers.borrow_mut();
1669 let callbacks = subscribers
1670 .callbacks
1671 .iter()
1672 .filter_map(|(id, callback)| callback.upgrade().map(|callback| (*id, callback)))
1673 .collect::<Vec<_>>();
1674 subscribers
1675 .callbacks
1676 .retain(|_, callback| callback.strong_count() != 0);
1677 callbacks
1678 };
1679 for (_, callback) in callbacks {
1680 callback(revision);
1681 }
1682 }
1683}
1684
1685/// RAII subscription guard returned by [`TreeModelHandle::subscribe`].
1686///
1687/// Dropping the guard removes its callback slot when the registry still exists.
1688///
1689/// # Examples
1690///
1691/// ```
1692/// use std::rc::Rc;
1693/// use ailloli_ui_widgets::controls::{TreeModel, TreeModelHandle};
1694/// let handle = TreeModelHandle::new(TreeModel::<u8>::new());
1695/// let callback: Rc<dyn Fn(u64)> = Rc::new(|_| {});
1696/// let guard = handle.subscribe(&callback);
1697/// drop(guard);
1698/// ```
1699pub struct TreeModelSubscription {
1700 /// Callback slot ID owned by this guard.
1701 id: u64,
1702 /// Weak registry reference so guards do not keep handles alive.
1703 subscribers: Weak<RefCell<SubscriberRegistry>>,
1704}
1705
1706impl fmt::Debug for TreeModelSubscription {
1707 /// Formats the subscription ID without retaining registry state.
1708 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1709 formatter
1710 .debug_struct("TreeModelSubscription")
1711 .field("id", &self.id)
1712 .finish_non_exhaustive()
1713 }
1714}
1715
1716impl Drop for TreeModelSubscription {
1717 /// Removes the callback slot when its registry remains alive.
1718 fn drop(&mut self) {
1719 if let Some(subscribers) = self.subscribers.upgrade() {
1720 subscribers.borrow_mut().callbacks.remove(&self.id);
1721 }
1722 }
1723}