Skip to main content

laravel_nestedset/
arrange.rs

1//! Rearranging a tree from a nested list of keys, such as a drag-and-drop editor sends.
2
3use std::collections::{HashMap, HashSet};
4
5use laravel::db::IntoExpr;
6use laravel::model::__query;
7use serde::{Deserialize, Serialize};
8
9use crate::check::write_rebuilt;
10use crate::error::NestedSetError;
11use crate::event::{TreeChange, changed};
12use crate::locks::Locks;
13use crate::node::NestedSet;
14use crate::ops::{ATTEMPTS, connection, find};
15
16/// A node's place in a new arrangement: its key and its children, in order. It deserializes from
17/// the JSON a drag-and-drop tree editor sends, with the key as `key` or `id`:
18///
19/// ```json
20/// [{ "id": 1, "children": [{ "id": 3 }, { "id": 2, "children": [] }] }]
21/// ```
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Arrangement<K> {
24    /// The node's key.
25    #[serde(alias = "id")]
26    pub key: K,
27    /// The node's children, in order.
28    #[serde(default)]
29    pub children: Vec<Arrangement<K>>,
30}
31
32impl<K> Arrangement<K> {
33    /// The node with `key`, without children yet.
34    pub fn new(key: K) -> Self {
35        Self {
36            key,
37            children: Vec::new(),
38        }
39    }
40
41    /// Adds `children` after the node's other children.
42    #[must_use]
43    pub fn children(mut self, children: impl IntoIterator<Item = Arrangement<K>>) -> Self {
44        self.children.extend(children);
45        self
46    }
47}
48
49/// A listed node still to place, with the parent it goes under.
50type Pending<K> = (Arrangement<K>, Option<K>);
51
52/// Puts the listed nodes where `items` says, under `anchor` or as roots, and rebuilds the tree.
53pub(crate) async fn arrange<M: NestedSet>(anchor: Option<&M>, items: Vec<Arrangement<M::Key>>) -> laravel::Result<u64>
54where
55    Option<M::Key>: IntoExpr,
56{
57    // Each listed node's parent and its place in the list, depth first.
58    let anchor_key = anchor.map(|anchor| anchor.node_key().clone());
59    let mut placed: HashMap<M::Key, (Option<M::Key>, usize)> = HashMap::new();
60    let mut stack: Vec<Pending<M::Key>> = items.into_iter().rev().map(|item| (item, anchor_key.clone())).collect();
61    while let Some((item, parent)) = stack.pop() {
62        let order = placed.len();
63        if placed.insert(item.key.clone(), (parent, order)).is_some() {
64            return Err(NestedSetError::DuplicateKey {
65                model: M::META.name,
66                key: item.key.to_string(),
67            }
68            .into());
69        }
70        let key = item.key;
71        stack.extend(item.children.into_iter().rev().map(|child| (child, Some(key.clone()))));
72    }
73    let Some(first) = placed.keys().next().cloned() else {
74        return Ok(0);
75    };
76
77    // The tree, read before the transaction: inside it, every read comes after the locks.
78    let scope = match anchor {
79        Some(anchor) => anchor.scope(),
80        None => find::<M>(&first).await?.scope(),
81    };
82    connection::<M>()?
83        .transaction_with_attempts(ATTEMPTS, async |tx| {
84            let mut locks = Locks::open::<M>(tx).await?;
85            locks.roots::<M>(tx).await?;
86            locks.tree(tx, &scope).await?;
87            let tree = locks
88                .fresh(scope.apply(__query::<M>()))
89                .order_by(M::lft_column().asc())
90                .get()
91                .await?;
92
93            let present: HashSet<&M::Key> = tree.iter().map(NestedSet::node_key).collect();
94            if let Some(missing) = placed.keys().find(|key| !present.contains(key)) {
95                return Err(NestedSetError::NodeNotFound {
96                    model: M::META.name,
97                    key: missing.to_string(),
98                }
99                .into());
100            }
101            if let Some(anchor_key) = &anchor_key {
102                let anchor = tree.iter().find(|node| node.node_key() == anchor_key).ok_or_else(|| {
103                    NestedSetError::NodeNotFound {
104                        model: M::META.name,
105                        key: anchor_key.to_string(),
106                    }
107                })?;
108                // The anchor can't go below itself: it and its ancestors stay out of the list.
109                if let Some(around) = tree
110                    .iter()
111                    .find(|node| placed.contains_key(node.node_key()) && anchor.is_descendant_of(node))
112                    .or_else(|| placed.contains_key(anchor_key).then_some(anchor))
113                {
114                    return Err(NestedSetError::MoveIntoOwnSubtree {
115                        model: M::META.name,
116                        key: around.node_key().to_string(),
117                        target: anchor_key.to_string(),
118                    }
119                    .into());
120                }
121            }
122
123            // Listed nodes come first among their siblings, in the list's order; the others keep
124            // their order after them.
125            let mut ordered: Vec<&M> = tree.iter().collect();
126            ordered.sort_by_key(|node| placed.get(node.node_key()).map_or(usize::MAX, |(_, order)| *order));
127            let nodes: Vec<M> = ordered.into_iter().cloned().collect();
128            let parents: Vec<Option<M::Key>> = nodes
129                .iter()
130                .map(|node| match placed.get(node.node_key()) {
131                    Some((parent, _)) => parent.clone(),
132                    None => node.parent_key().cloned(),
133                })
134                .collect();
135            let changed_rows = write_rebuilt(&nodes, &parents).await?;
136            changed::<M>(TreeChange::Arranged, None).await?;
137            locks.release_after_commit(tx).await?;
138            Ok(changed_rows)
139        })
140        .await
141}