Skip to main content

egui_pop_views/tree/
model.rs

1//! The tree's model: what the view knows of the application's tree.
2//!
3//! The application owns its tree; the view keeps a cache of the
4//! branches it loaded, keyed by node, so that edits (insert, remove,
5//! move, rename) arriving at any time keep the selection and the
6//! expansion, which are keyed too. The rows on screen are the cache
7//! flattened through the expanded branches, rebuilt only when something
8//! changed.
9
10use std::collections::{HashMap, HashSet};
11
12use serde::{Deserialize, Serialize};
13
14use crate::select::Key;
15
16/// A node as the application gives it.
17#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
18pub struct Node<K> {
19    pub key: K,
20    /// What the row shows, decorations included.
21    pub label: String,
22    /// Whether it may have children (they are loaded when it is first
23    /// expanded).
24    pub branch: bool,
25    /// The plain name a rename starts from and type-ahead searches,
26    /// when the label carries more (a count, a state); `None`: the
27    /// label.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub name: Option<String>,
30}
31
32impl<K> Node<K> {
33    pub fn leaf(key: K, label: impl Into<String>) -> Self {
34        Self {
35            key,
36            label: label.into(),
37            branch: false,
38            name: None,
39        }
40    }
41
42    pub fn branch(key: K, label: impl Into<String>) -> Self {
43        Self {
44            key,
45            label: label.into(),
46            branch: true,
47            name: None,
48        }
49    }
50
51    /// With a plain name apart from its label.
52    pub fn with_name(mut self, name: impl Into<String>) -> Self {
53        self.name = Some(name.into());
54        self
55    }
56
57    /// The plain name: the one given, else the label.
58    pub fn name(&self) -> &str {
59        self.name.as_deref().unwrap_or(&self.label)
60    }
61}
62
63/// Where dropped nodes go, relative to the target.
64#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "lowercase")]
66pub enum Position {
67    Before,
68    After,
69    /// As the target's last children.
70    Inside,
71}
72
73/// What the view knows of a branch's children.
74#[derive(Clone, Debug, PartialEq)]
75pub enum Children<K> {
76    /// Asked for; `stale` are the children shown meanwhile (a reload).
77    Loading {
78        ticket: u64,
79        stale: Vec<K>,
80    },
81    Loaded(Vec<K>),
82    Failed(String),
83    /// To be loaded again; shown as they were until then.
84    Stale(Vec<K>),
85}
86
87/// A row on screen.
88#[derive(Clone, Debug, PartialEq)]
89pub enum Row<K> {
90    Node {
91        key: K,
92        depth: usize,
93    },
94    /// A branch whose children are on their way.
95    Loading {
96        parent: Option<K>,
97        depth: usize,
98    },
99    /// A branch whose children could not be loaded.
100    Failed {
101        parent: Option<K>,
102        depth: usize,
103        reason: String,
104    },
105    /// An expanded branch without children.
106    Empty {
107        parent: Option<K>,
108        depth: usize,
109    },
110}
111
112impl<K> Row<K> {
113    pub fn key(&self) -> Option<&K> {
114        match self {
115            Row::Node { key, .. } => Some(key),
116            _ => None,
117        }
118    }
119
120    pub fn depth(&self) -> usize {
121        match self {
122            Row::Node { depth, .. }
123            | Row::Loading { depth, .. }
124            | Row::Failed { depth, .. }
125            | Row::Empty { depth, .. } => *depth,
126        }
127    }
128}
129
130/// A change to the cache, from the application or a source.
131#[derive(Clone, Debug, PartialEq)]
132pub enum Edit<K> {
133    /// A branch's children, from a load (`ticket`) or set directly
134    /// (`None`).
135    Children {
136        parent: Option<K>,
137        ticket: Option<u64>,
138        result: Result<Vec<Node<K>>, String>,
139    },
140    /// A node under `parent`, at `index` (`None`: last).
141    Insert {
142        parent: Option<K>,
143        index: Option<usize>,
144        node: Node<K>,
145    },
146    /// A node and what is under it.
147    Remove(K),
148    /// A node to another place.
149    Move {
150        key: K,
151        parent: Option<K>,
152        index: Option<usize>,
153    },
154    Rename {
155        key: K,
156        label: String,
157    },
158    /// A node's label, name and kind.
159    Update(Node<K>),
160    /// A branch to load again (`None`: the roots).
161    Reload(Option<K>),
162}
163
164/// The cache, the expansion and the rows.
165#[derive(Debug)]
166pub struct Model<K: Key> {
167    nodes: HashMap<K, (Node<K>, Option<K>)>,
168    children: HashMap<Option<K>, Children<K>>,
169    expanded: HashSet<K>,
170    rows: Vec<Row<K>>,
171    /// The rows that are nodes, by index.
172    node_rows: Vec<usize>,
173    /// Branches the last flattening found expanded and not loaded.
174    wanted: Vec<Option<K>>,
175    dirty: bool,
176    tickets: u64,
177    /// Counts the changes to the nodes (not to the expansion).
178    version: u64,
179    /// The filter's matches, while there is a query.
180    filter: Option<Filtered<K>>,
181    /// How many times the rows were flattened.
182    flattens: u64,
183}
184
185/// What a filter shows: the nodes that match, their ancestors, and the
186/// branches opened or closed while it filters.
187#[derive(Debug)]
188struct Filtered<K> {
189    matched: HashSet<K>,
190    ancestors: HashSet<K>,
191    folds: HashMap<K, bool>,
192}
193
194impl<K: Key> Default for Model<K> {
195    fn default() -> Self {
196        Self {
197            nodes: HashMap::new(),
198            children: HashMap::new(),
199            expanded: HashSet::new(),
200            rows: Vec::new(),
201            node_rows: Vec::new(),
202            wanted: Vec::new(),
203            dirty: true,
204            tickets: 0,
205            version: 0,
206            filter: None,
207            flattens: 0,
208        }
209    }
210}
211
212impl<K: Key> Model<K> {
213    pub fn node(&self, key: &K) -> Option<&Node<K>> {
214        self.nodes.get(key).map(|(n, _)| n)
215    }
216
217    pub fn contains(&self, key: &K) -> bool {
218        self.nodes.contains_key(key)
219    }
220
221    /// The parent of a known node (`Some(None)`: a root).
222    pub fn parent(&self, key: &K) -> Option<Option<&K>> {
223        self.nodes.get(key).map(|(_, p)| p.as_ref())
224    }
225
226    pub fn children(&self, parent: Option<&K>) -> Option<&Children<K>> {
227        self.children.get(&parent.cloned())
228    }
229
230    /// A branch's loaded children.
231    pub fn loaded(&self, parent: Option<&K>) -> Option<&[K]> {
232        match self.children(parent)? {
233            Children::Loaded(v) => Some(v),
234            _ => None,
235        }
236    }
237
238    /// Whether a branch is open in the fold the tree keeps (a filter
239    /// may show it otherwise, see [`Model::is_open`]).
240    pub fn is_expanded(&self, key: &K) -> bool {
241        self.expanded.contains(key)
242    }
243
244    /// Whether a branch shows open: as the filter opened it while there
245    /// is one, else as it is expanded.
246    pub fn is_open(&self, key: &K) -> bool {
247        match &self.filter {
248            Some(f) => f
249                .folds
250                .get(key)
251                .copied()
252                .unwrap_or_else(|| f.ancestors.contains(key)),
253            None => self.expanded.contains(key),
254        }
255    }
256
257    /// Opens or closes a branch as it shows: while a filter is set, until
258    /// the query changes, the fold kept untouched; else its expansion.
259    pub(crate) fn set_open(&mut self, key: &K, open: bool) {
260        match &mut self.filter {
261            Some(f) => {
262                f.folds.insert(key.clone(), open);
263                self.dirty = true;
264            }
265            None => self.set_expanded(key, open),
266        }
267    }
268
269    /// Every node the view knows, in no order.
270    pub fn nodes(&self) -> impl Iterator<Item = &Node<K>> {
271        self.nodes.values().map(|(n, _)| n)
272    }
273
274    /// Changes to the nodes so far: it moves when a node comes, goes,
275    /// moves or changes.
276    pub fn version(&self) -> u64 {
277        self.version
278    }
279
280    /// Whether a filter is set.
281    pub fn is_filtered(&self) -> bool {
282        self.filter.is_some()
283    }
284
285    /// Whether a node matches the filter set.
286    pub fn is_match(&self, key: &K) -> bool {
287        self.filter
288            .as_ref()
289            .is_some_and(|f| f.matched.contains(key))
290    }
291
292    /// How many nodes match the filter set (`None`: no filter).
293    pub fn matches(&self) -> Option<usize> {
294        self.filter.as_ref().map(|f| f.matched.len())
295    }
296
297    /// Sets the nodes the filter matched (`None`: no filter). `fresh`: a
298    /// new query, which forgets the branches opened or closed under the
299    /// last one.
300    pub(crate) fn set_matches(&mut self, matched: Option<HashSet<K>>, fresh: bool) {
301        let Some(matched) = matched else {
302            self.dirty |= self.filter.take().is_some();
303            return;
304        };
305        let mut ancestors = HashSet::new();
306        for k in &matched {
307            let mut at = self.nodes.get(k).and_then(|(_, p)| p.clone());
308            while let Some(p) = at {
309                if !ancestors.insert(p.clone()) {
310                    break;
311                }
312                at = self.nodes.get(&p).and_then(|(_, p)| p.clone());
313            }
314        }
315        let folds = match self.filter.take() {
316            Some(f) if !fresh => f.folds,
317            _ => HashMap::new(),
318        };
319        self.filter = Some(Filtered {
320            matched,
321            ancestors,
322            folds,
323        });
324        self.dirty = true;
325    }
326
327    pub fn set_expanded(&mut self, key: &K, expanded: bool) {
328        let changed = if expanded {
329            self.expanded.insert(key.clone())
330        } else {
331            self.expanded.remove(key)
332        };
333        self.dirty |= changed;
334    }
335
336    /// How many nodes the cache holds.
337    pub fn len(&self) -> usize {
338        self.nodes.len()
339    }
340
341    pub fn is_empty(&self) -> bool {
342        self.nodes.is_empty()
343    }
344
345    /// Whether `key` is `ancestor` or under it.
346    pub fn is_within(&self, key: &K, ancestor: &K) -> bool {
347        let mut at = Some(key.clone());
348        while let Some(k) = at {
349            if k == *ancestor {
350                return true;
351            }
352            at = self.nodes.get(&k).and_then(|(_, p)| p.clone());
353        }
354        false
355    }
356
357    /// Marks a branch as loading and returns its ticket: only the
358    /// answer carrying it is taken.
359    pub fn begin_load(&mut self, parent: Option<&K>) -> u64 {
360        self.tickets += 1;
361        let ticket = self.tickets;
362        let stale = match self.children.remove(&parent.cloned()) {
363            Some(Children::Loaded(v) | Children::Stale(v)) => v,
364            Some(Children::Loading { stale, .. }) => stale,
365            _ => Vec::new(),
366        };
367        self.children
368            .insert(parent.cloned(), Children::Loading { ticket, stale });
369        self.dirty = true;
370        ticket
371    }
372
373    /// Loads every branch again, as a [`Edit::Reload`] of each: what
374    /// was loaded stays on screen until its new children come, a branch
375    /// that was loading or had failed is asked for again (the answer it
376    /// waited for is no longer taken). Used when edits were dropped.
377    pub fn reload_all(&mut self) {
378        let parents: Vec<Option<K>> = self.children.keys().cloned().collect();
379        for parent in parents {
380            let stale = match self.children.remove(&parent) {
381                Some(Children::Loaded(v) | Children::Stale(v)) => v,
382                Some(Children::Loading { stale, .. }) => stale,
383                Some(Children::Failed(_)) | None => continue,
384            };
385            self.children.insert(parent, Children::Stale(stale));
386        }
387        self.dirty = true;
388        self.version += 1;
389    }
390
391    /// Marks a branch as failed (a load vetoed or refused).
392    pub fn fail(&mut self, parent: Option<&K>, reason: &str) {
393        let stale = match self.children.remove(&parent.cloned()) {
394            Some(Children::Loaded(v) | Children::Stale(v)) => v,
395            Some(Children::Loading { stale, .. }) => stale,
396            _ => Vec::new(),
397        };
398        for k in stale {
399            self.forget(&k);
400        }
401        self.children
402            .insert(parent.cloned(), Children::Failed(reason.into()));
403        self.dirty = true;
404        self.version += 1;
405    }
406
407    /// Applies an edit; returns whether it changed anything.
408    pub fn apply(&mut self, edit: Edit<K>) -> bool {
409        let changed = match edit {
410            Edit::Children {
411                parent,
412                ticket,
413                result,
414            } => self.set_children(parent, ticket, result),
415            Edit::Insert {
416                parent,
417                index,
418                node,
419            } => self.insert(parent, index, node),
420            Edit::Remove(key) => {
421                let known = self.contains(&key);
422                self.detach(&key);
423                self.forget(&key);
424                known
425            }
426            Edit::Move { key, parent, index } => self.move_to(&key, parent, index),
427            Edit::Rename { key, label } => match self.nodes.get_mut(&key) {
428                Some((n, _)) if n.label != label => {
429                    n.label = label;
430                    true
431                }
432                _ => false,
433            },
434            Edit::Update(node) => match self.nodes.get_mut(&node.key) {
435                Some((n, _)) if *n != node => {
436                    *n = node;
437                    true
438                }
439                _ => false,
440            },
441            Edit::Reload(parent) => match self.children.remove(&parent) {
442                Some(Children::Loaded(v) | Children::Stale(v)) => {
443                    self.children.insert(parent, Children::Stale(v));
444                    true
445                }
446                Some(Children::Failed(_)) | None => true,
447                Some(c @ Children::Loading { .. }) => {
448                    self.children.insert(parent, c);
449                    false
450                }
451            },
452        };
453        self.dirty |= changed;
454        if changed {
455            self.version += 1;
456        }
457        changed
458    }
459
460    fn set_children(
461        &mut self,
462        parent: Option<K>,
463        ticket: Option<u64>,
464        result: Result<Vec<Node<K>>, String>,
465    ) -> bool {
466        if let Some(t) = ticket
467            && !matches!(self.children.get(&parent), Some(Children::Loading { ticket, .. }) if *ticket == t)
468        {
469            return false;
470        }
471        if let Some(p) = &parent
472            && !self.contains(p)
473        {
474            return false;
475        }
476        let old = match self.children.remove(&parent) {
477            Some(Children::Loaded(v) | Children::Stale(v)) => v,
478            Some(Children::Loading { stale, .. }) => stale,
479            _ => Vec::new(),
480        };
481        match result {
482            Ok(nodes) => {
483                let keep: HashSet<&K> = nodes.iter().map(|n| &n.key).collect();
484                for k in old.iter().filter(|k| !keep.contains(k)) {
485                    self.forget(k);
486                }
487                let mut keys = Vec::with_capacity(nodes.len());
488                for node in nodes {
489                    // A node shown elsewhere moves here.
490                    if self.nodes.get(&node.key).is_some_and(|(_, p)| *p != parent) {
491                        self.detach(&node.key);
492                    }
493                    keys.push(node.key.clone());
494                    self.nodes.insert(node.key.clone(), (node, parent.clone()));
495                }
496                self.children.insert(parent, Children::Loaded(keys));
497            }
498            Err(reason) => {
499                for k in &old {
500                    self.forget(k);
501                }
502                self.children.insert(parent, Children::Failed(reason));
503            }
504        }
505        true
506    }
507
508    fn insert(&mut self, parent: Option<K>, index: Option<usize>, node: Node<K>) -> bool {
509        if self.contains(&node.key) {
510            let key = node.key.clone();
511            self.apply(Edit::Update(node));
512            return self.move_to(&key, parent, index);
513        }
514        let Some(Children::Loaded(list)) = self.children.get_mut(&parent) else {
515            // Not loaded: the node comes with the branch.
516            return false;
517        };
518        let at = index.unwrap_or(list.len()).min(list.len());
519        list.insert(at, node.key.clone());
520        self.nodes.insert(node.key.clone(), (node, parent));
521        true
522    }
523
524    fn move_to(&mut self, key: &K, parent: Option<K>, index: Option<usize>) -> bool {
525        if !self.contains(key) || parent.as_ref().is_some_and(|p| self.is_within(p, key)) {
526            return false;
527        }
528        self.detach(key);
529        match self.children.get_mut(&parent) {
530            Some(Children::Loaded(list)) => {
531                let at = index.unwrap_or(list.len()).min(list.len());
532                list.insert(at, key.clone());
533                if let Some(e) = self.nodes.get_mut(key) {
534                    e.1 = parent;
535                }
536            }
537            // The branch shows it once loaded.
538            _ => self.forget(key),
539        }
540        true
541    }
542
543    /// Moves nodes, in order, before, after or inside `target` (a
544    /// branch not loaded takes them when it loads). Nodes that would go
545    /// into themselves are left where they are.
546    pub fn move_many(&mut self, keys: &[K], target: &K, position: Position) {
547        let parent = match position {
548            Position::Inside => Some(target.clone()),
549            _ => match self.nodes.get(target) {
550                Some((_, p)) => p.clone(),
551                None => return,
552            },
553        };
554        let keys: Vec<K> = keys
555            .iter()
556            .filter(|k| self.contains(k) && *k != target)
557            .filter(|k| !parent.as_ref().is_some_and(|p| self.is_within(p, k)))
558            .cloned()
559            .collect();
560        for k in &keys {
561            self.detach(k);
562        }
563        self.dirty = true;
564        self.version += 1;
565        let Some(Children::Loaded(list)) = self.children.get_mut(&parent) else {
566            for k in &keys {
567                self.forget(k);
568            }
569            return;
570        };
571        let at = match position {
572            Position::Inside => list.len(),
573            Position::Before => list.iter().position(|k| k == target).unwrap_or(list.len()),
574            Position::After => list
575                .iter()
576                .position(|k| k == target)
577                .map_or(list.len(), |i| i + 1),
578        };
579        list.splice(at..at, keys.iter().cloned());
580        for k in &keys {
581            if let Some(e) = self.nodes.get_mut(k) {
582                e.1 = parent.clone();
583            }
584        }
585    }
586
587    /// Takes a node out of its parent's list.
588    fn detach(&mut self, key: &K) {
589        let Some((_, parent)) = self.nodes.get(key) else {
590            return;
591        };
592        if let Some(
593            Children::Loaded(list) | Children::Stale(list) | Children::Loading { stale: list, .. },
594        ) = self.children.get_mut(parent)
595        {
596            list.retain(|k| k != key);
597        }
598    }
599
600    /// Drops a node and what is under it from the cache (not from its
601    /// parent's list). The expansion is kept: a node coming back opens
602    /// as it was.
603    fn forget(&mut self, key: &K) {
604        let mut todo = vec![key.clone()];
605        while let Some(k) = todo.pop() {
606            self.nodes.remove(&k);
607            if let Some(
608                Children::Loaded(v) | Children::Stale(v) | Children::Loading { stale: v, .. },
609            ) = self.children.remove(&Some(k))
610            {
611                todo.extend(v);
612            }
613        }
614        self.dirty = true;
615        self.version += 1;
616    }
617
618    /// The rows, flattened again when something changed.
619    pub fn rows(&mut self) -> &[Row<K>] {
620        if self.dirty {
621            self.flatten();
622        }
623        &self.rows
624    }
625
626    /// The indices of the rows that are nodes, as last flattened.
627    pub fn node_rows(&self) -> &[usize] {
628        &self.node_rows
629    }
630
631    /// The rows as last flattened.
632    pub fn rows_now(&self) -> &[Row<K>] {
633        &self.rows
634    }
635
636    pub fn is_dirty(&self) -> bool {
637        self.dirty
638    }
639
640    /// Branches shown expanded whose children were never asked for, or
641    /// must be asked again, since the last call.
642    pub fn take_wanted(&mut self) -> Vec<Option<K>> {
643        if self.dirty {
644            self.flatten();
645        }
646        std::mem::take(&mut self.wanted)
647    }
648
649    fn flatten(&mut self) {
650        /// A node to show, its depth, and whether it is under a node that
651        /// matches the filter (then all of its children show).
652        enum Item<K> {
653            Node(K, usize, bool),
654            Row(Row<K>),
655        }
656        let filter = self.filter.as_ref();
657        let mut rows = Vec::with_capacity(self.rows.len());
658        let mut wanted = Vec::new();
659        let mut stack: Vec<Item<K>> = Vec::new();
660        let push = |parent: Option<K>,
661                    depth: usize,
662                    under: bool,
663                    stack: &mut Vec<Item<K>>,
664                    wanted: &mut Vec<Option<K>>| {
665            // A filter hides what is neither a match, an ancestor of one,
666            // nor under a match: the rows saying how a branch loads too.
667            let all = filter.is_none() || under;
668            let list = match self.children.get(&parent) {
669                None => {
670                    if all {
671                        wanted.push(parent.clone());
672                        stack.push(Item::Row(Row::Loading { parent, depth }));
673                    }
674                    return;
675                }
676                Some(Children::Loading { stale, .. }) if stale.is_empty() => {
677                    if all {
678                        stack.push(Item::Row(Row::Loading { parent, depth }));
679                    }
680                    return;
681                }
682                Some(Children::Failed(reason)) => {
683                    if all {
684                        stack.push(Item::Row(Row::Failed {
685                            parent,
686                            depth,
687                            reason: reason.clone(),
688                        }));
689                    }
690                    return;
691                }
692                Some(Children::Loaded(v)) if v.is_empty() => {
693                    if all {
694                        stack.push(Item::Row(Row::Empty { parent, depth }));
695                    }
696                    return;
697                }
698                Some(Children::Stale(v)) => {
699                    wanted.push(parent.clone());
700                    v
701                }
702                Some(Children::Loaded(v) | Children::Loading { stale: v, .. }) => v,
703            };
704            let shown = |k: &&K| {
705                all || filter.is_some_and(|f| f.matched.contains(*k) || f.ancestors.contains(*k))
706            };
707            stack.extend(
708                list.iter()
709                    .rev()
710                    .filter(shown)
711                    .map(|k| Item::Node(k.clone(), depth, under)),
712            );
713        };
714        push(None, 0, false, &mut stack, &mut wanted);
715        while let Some(item) = stack.pop() {
716            match item {
717                Item::Row(r) => rows.push(r),
718                Item::Node(key, depth, under) => {
719                    let open = self
720                        .nodes
721                        .get(&key)
722                        .is_some_and(|(n, _)| n.branch && self.is_open(&key));
723                    let under = under || filter.is_some_and(|f| f.matched.contains(&key));
724                    rows.push(Row::Node {
725                        key: key.clone(),
726                        depth,
727                    });
728                    if open {
729                        push(Some(key), depth + 1, under, &mut stack, &mut wanted);
730                    }
731                }
732            }
733        }
734        self.node_rows = rows
735            .iter()
736            .enumerate()
737            .filter(|(_, r)| matches!(r, Row::Node { .. }))
738            .map(|(i, _)| i)
739            .collect();
740        self.rows = rows;
741        self.wanted = wanted;
742        self.dirty = false;
743        self.flattens += 1;
744    }
745
746    /// How many times the rows were flattened: it moves when they may
747    /// have changed.
748    pub(crate) fn flattens(&self) -> u64 {
749        self.flattens
750    }
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756
757    fn keys(m: &mut Model<String>) -> Vec<String> {
758        m.rows()
759            .iter()
760            .map(|r| match r {
761                Row::Node { key, depth } => format!("{}{key}", " ".repeat(*depth)),
762                Row::Loading { depth, .. } => format!("{}…", " ".repeat(*depth)),
763                Row::Failed { depth, .. } => format!("{}!", " ".repeat(*depth)),
764                Row::Empty { depth, .. } => format!("{}-", " ".repeat(*depth)),
765            })
766            .collect()
767    }
768
769    fn load(m: &mut Model<String>, parent: Option<&str>, nodes: Vec<Node<String>>) {
770        let p = parent.map(String::from);
771        let t = m.begin_load(p.as_ref());
772        assert!(m.apply(Edit::Children {
773            parent: p,
774            ticket: Some(t),
775            result: Ok(nodes),
776        }));
777    }
778
779    fn b(k: &str) -> Node<String> {
780        Node::branch(k.to_string(), k)
781    }
782
783    fn l(k: &str) -> Node<String> {
784        Node::leaf(k.to_string(), k)
785    }
786
787    #[test]
788    fn expanded_branches_ask_for_their_children_once() {
789        let mut m = Model::<String>::default();
790        assert_eq!(keys(&mut m), ["…"]);
791        assert_eq!(m.take_wanted(), vec![None]);
792        load(&mut m, None, vec![b("a"), l("b")]);
793        assert_eq!(keys(&mut m), ["a", "b"]);
794        m.set_expanded(&"a".into(), true);
795        assert_eq!(keys(&mut m), ["a", " …", "b"]);
796        assert_eq!(m.take_wanted(), vec![Some("a".into())]);
797        let t = m.begin_load(Some(&"a".into()));
798        assert!(m.take_wanted().is_empty(), "asked once");
799        // A late answer of an older ticket is dropped.
800        assert!(!m.apply(Edit::Children {
801            parent: Some("a".into()),
802            ticket: Some(t - 1),
803            result: Ok(vec![]),
804        }));
805        m.apply(Edit::Children {
806            parent: Some("a".into()),
807            ticket: Some(t),
808            result: Ok(vec![l("a1"), b("a2")]),
809        });
810        assert_eq!(keys(&mut m), ["a", " a1", " a2", "b"]);
811    }
812
813    #[test]
814    fn edits_keep_the_expansion_and_refuse_cycles() {
815        let mut m = Model::<String>::default();
816        load(&mut m, None, vec![b("a"), b("b")]);
817        m.set_expanded(&"a".into(), true);
818        load(&mut m, Some("a"), vec![b("a1")]);
819        m.set_expanded(&"a1".into(), true);
820        load(&mut m, Some("a1"), vec![l("x")]);
821        assert_eq!(keys(&mut m), ["a", " a1", "  x", "b"]);
822        // Into its own child: refused.
823        assert!(!m.apply(Edit::Move {
824            key: "a".into(),
825            parent: Some("a1".into()),
826            index: None,
827        }));
828        m.apply(Edit::Insert {
829            parent: None,
830            index: Some(0),
831            node: l("new"),
832        });
833        m.apply(Edit::Move {
834            key: "x".into(),
835            parent: None,
836            index: None,
837        });
838        assert_eq!(keys(&mut m), ["new", "a", " a1", "  -", "b", "x"]);
839        m.apply(Edit::Remove("a".into()));
840        assert!(!m.contains(&"a1".into()));
841        assert!(m.is_expanded(&"a".into()), "kept for when it comes back");
842        assert_eq!(keys(&mut m), ["new", "b", "x"]);
843    }
844
845    #[test]
846    fn a_reload_shows_the_old_children_until_the_new_ones_come() {
847        let mut m = Model::<String>::default();
848        load(&mut m, None, vec![l("a"), l("b")]);
849        m.apply(Edit::Reload(None));
850        assert_eq!(keys(&mut m), ["a", "b"]);
851        assert_eq!(m.take_wanted(), vec![None]);
852        let t = m.begin_load(None);
853        assert_eq!(keys(&mut m), ["a", "b"]);
854        m.apply(Edit::Children {
855            parent: None,
856            ticket: Some(t),
857            result: Ok(vec![l("b"), l("c")]),
858        });
859        assert_eq!(keys(&mut m), ["b", "c"]);
860        assert!(!m.contains(&"a".into()));
861        let t = m.begin_load(None);
862        m.apply(Edit::Children {
863            parent: None,
864            ticket: Some(t),
865            result: Err("offline".into()),
866        });
867        assert_eq!(keys(&mut m), ["!"]);
868    }
869
870    #[test]
871    fn several_nodes_drop_in_order() {
872        let mut m = Model::<String>::default();
873        load(&mut m, None, vec![l("a"), l("b"), l("c"), b("d")]);
874        m.move_many(&["c".into(), "a".into()], &"b".into(), Position::Before);
875        assert_eq!(keys(&mut m), ["c", "a", "b", "d"]);
876        m.move_many(&["c".into()], &"d".into(), Position::After);
877        assert_eq!(keys(&mut m), ["a", "b", "d", "c"]);
878        m.set_expanded(&"d".into(), true);
879        load(&mut m, Some("d"), vec![]);
880        m.move_many(&["a".into(), "b".into()], &"d".into(), Position::Inside);
881        assert_eq!(keys(&mut m), ["d", " a", " b", "c"]);
882        // Into itself: left where it is.
883        m.move_many(&["d".into()], &"a".into(), Position::After);
884        assert_eq!(keys(&mut m), ["d", " a", " b", "c"]);
885    }
886
887    #[test]
888    fn a_filter_shows_matches_with_their_ancestors_and_keeps_the_fold() {
889        let mut m = Model::<String>::default();
890        load(&mut m, None, vec![b("a"), b("b"), l("c")]);
891        m.set_expanded(&"a".into(), true);
892        load(&mut m, Some("a"), vec![b("a1"), l("a2")]);
893        m.set_expanded(&"a1".into(), true);
894        load(&mut m, Some("a1"), vec![l("x"), l("y")]);
895        m.set_expanded(&"a1".into(), false);
896        assert_eq!(keys(&mut m), ["a", " a1", " a2", "b", "c"]);
897        // `y` matches: its folded ancestors open for it, `b` (not
898        // loaded) and the rest hide.
899        m.set_matches(Some(["y".to_string()].into()), true);
900        assert_eq!(keys(&mut m), ["a", " a1", "  y"]);
901        assert!(m.take_wanted().is_empty(), "nothing loads for a filter");
902        assert!(!m.is_expanded(&"a1".into()) && m.is_open(&"a1".into()));
903        // Closed while filtering: only the filter's fold changes.
904        m.set_open(&"a1".into(), false);
905        assert_eq!(keys(&mut m), ["a", " a1"]);
906        assert!(!m.is_expanded(&"a1".into()));
907        // The same query again keeps it; a new one forgets it.
908        m.set_matches(Some(["y".to_string()].into()), false);
909        assert_eq!(keys(&mut m), ["a", " a1"]);
910        // A branch that matches opens onto all of its children.
911        m.set_matches(Some(["a1".to_string()].into()), true);
912        assert_eq!(keys(&mut m), ["a", " a1"]);
913        m.set_open(&"a1".into(), true);
914        assert_eq!(keys(&mut m), ["a", " a1", "  x", "  y"]);
915        // Nothing matches: no row.
916        m.set_matches(Some(Default::default()), true);
917        assert!(keys(&mut m).is_empty());
918        // No filter: the fold as it was kept.
919        m.set_matches(None, true);
920        assert_eq!(keys(&mut m), ["a", " a1", " a2", "b", "c"]);
921    }
922
923    #[test]
924    fn a_hundred_thousand_nodes_flatten() {
925        let mut m = Model::<u32>::default();
926        let t = m.begin_load(None);
927        m.apply(Edit::Children {
928            parent: None,
929            ticket: Some(t),
930            result: Ok((0..1000).map(|i| Node::branch(i, format!("{i}"))).collect()),
931        });
932        for i in 0..1000u32 {
933            m.set_expanded(&i, true);
934            let t = m.begin_load(Some(&i));
935            m.apply(Edit::Children {
936                parent: Some(i),
937                ticket: Some(t),
938                result: Ok((0..99)
939                    .map(|j| Node::leaf(10_000 + i * 100 + j, format!("{i}.{j}")))
940                    .collect()),
941            });
942        }
943        assert_eq!(m.rows().len(), 100_000);
944        assert_eq!(m.len(), 100_000);
945    }
946}