laravel_nestedset/tree.rs
1//! Turning a list of nodes into a tree: `into_tree` and `into_flat_tree`.
2
3use std::collections::HashMap;
4
5use laravel::model::{CreateBuilder, Model};
6use serde::Serialize;
7
8use crate::node::NestedSet;
9
10/// A node with its children, built by [`IntoTree::into_tree`]. It serializes as the model's own
11/// fields plus `depth` and `children`, ready for a JSON API or a template:
12///
13/// ```json
14/// { "id": 1, "name": "Shop", "depth": 0, "children": [{ "id": 2, "name": "Phones", ... }] }
15/// ```
16#[derive(Debug, Clone, Serialize)]
17pub struct TreeNode<M> {
18 /// The node.
19 #[serde(flatten)]
20 pub node: M,
21 /// The node's depth in the built tree: `0` for the nodes at its top.
22 pub depth: usize,
23 /// The node's children, in the order the list had them.
24 pub children: Vec<TreeNode<M>>,
25}
26
27/// Builds trees from a list of nodes, such as the result of a query.
28///
29/// ```no_run
30/// # use laravel::model::{Column, model};
31/// # use laravel_nestedset::NestedSet;
32/// # #[model]
33/// # pub struct Category {
34/// # pub id: i64,
35/// # pub name: String,
36/// # #[default]
37/// # pub lft: i64,
38/// # #[default]
39/// # pub rgt: i64,
40/// # pub parent_id: Option<i64>,
41/// # }
42/// # impl NestedSet for Category {
43/// # fn lft_column() -> Column<Self, i64> { Category::lft }
44/// # fn rgt_column() -> Column<Self, i64> { Category::rgt }
45/// # fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
46/// # }
47/// use laravel_nestedset::IntoTree;
48/// # async fn example() -> laravel::Result<()> {
49/// let menu = Category::query()
50/// .scope(Category::default_order)
51/// .get()
52/// .await?
53/// .into_tree();
54/// # Ok(())
55/// # }
56/// ```
57pub trait IntoTree<M> {
58 /// Nests each node under its parent, when the parent is in the list. Nodes whose parent isn't
59 /// in the list are at the top. Siblings keep the list's order, so order the query with
60 /// [`NestedSet::default_order`] for tree order.
61 fn into_tree(self) -> Vec<TreeNode<M>>;
62
63 /// Lists every node right before its children, without nesting them. Handy for a `<select>` of categories indented by depth.
64 fn into_flat_tree(self) -> Vec<M>;
65
66 /// [`into_flat_tree`](Self::into_flat_tree) with each node's depth in the built tree: `0`
67 /// for the nodes at its top. The depth to indent a `<select>` option by.
68 fn into_flat_tree_with_depth(self) -> Vec<(M, usize)>;
69}
70
71impl<M: NestedSet> IntoTree<M> for Vec<M> {
72 fn into_tree(self) -> Vec<TreeNode<M>> {
73 let (mut slots, tops, children) = link(self);
74 tops.into_iter()
75 .map(|index| build(index, 0, &mut slots, &children))
76 .collect()
77 }
78
79 fn into_flat_tree(self) -> Vec<M> {
80 self.into_flat_tree_with_depth()
81 .into_iter()
82 .map(|(node, _)| node)
83 .collect()
84 }
85
86 fn into_flat_tree_with_depth(self) -> Vec<(M, usize)> {
87 let (mut slots, tops, children) = link(self);
88 let mut flat = Vec::with_capacity(slots.len());
89 let mut stack: Vec<(usize, usize)> = tops.into_iter().rev().map(|index| (index, 0)).collect();
90 while let Some((index, depth)) = stack.pop() {
91 if let Some(node) = slots[index].take() {
92 flat.push((node, depth));
93 }
94 if let Some(below) = children.get(&index) {
95 stack.extend(below.iter().rev().map(|&child| (child, depth + 1)));
96 }
97 }
98 flat
99 }
100}
101
102/// The nodes in slots, the indexes of the top nodes, and each node's child indexes.
103type Linked<M> = (Vec<Option<M>>, Vec<usize>, HashMap<usize, Vec<usize>>);
104
105fn link<M: NestedSet>(nodes: Vec<M>) -> Linked<M> {
106 let positions: HashMap<&M::Key, usize> = nodes
107 .iter()
108 .enumerate()
109 .map(|(index, node)| (node.node_key(), index))
110 .collect();
111 let mut tops = Vec::new();
112 let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
113 for (index, node) in nodes.iter().enumerate() {
114 match node.parent_key().and_then(|parent| positions.get(parent)) {
115 Some(&parent) if parent != index => children.entry(parent).or_default().push(index),
116 _ => tops.push(index),
117 }
118 }
119 (nodes.into_iter().map(Some).collect(), tops, children)
120}
121
122fn build<M>(
123 index: usize,
124 depth: usize,
125 slots: &mut Vec<Option<M>>,
126 children: &HashMap<usize, Vec<usize>>,
127) -> TreeNode<M> {
128 let node = slots[index].take().expect("each node is built once");
129 let children = children
130 .get(&index)
131 .map(|below| {
132 below
133 .iter()
134 .map(|&child| build(child, depth + 1, slots, children))
135 .collect()
136 })
137 .unwrap_or_default();
138 TreeNode { node, depth, children }
139}
140
141/// A node to create with its children, for
142/// [`NestedSet::create_tree`] and [`NestedSet::create_child_tree`].
143///
144/// ```no_run
145/// # use laravel::model::{Column, model};
146/// # use laravel_nestedset::NestedSet;
147/// # #[model]
148/// # pub struct Category {
149/// # pub id: i64,
150/// # pub name: String,
151/// # #[default]
152/// # pub lft: i64,
153/// # #[default]
154/// # pub rgt: i64,
155/// # pub parent_id: Option<i64>,
156/// # }
157/// # impl NestedSet for Category {
158/// # fn lft_column() -> Column<Self, i64> { Category::lft }
159/// # fn rgt_column() -> Column<Self, i64> { Category::rgt }
160/// # fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
161/// # }
162/// use laravel_nestedset::NewNode;
163/// # async fn example() -> laravel::Result<()> {
164/// let shop = Category::create_tree(
165/// NewNode::new(Category::create().name("Shop")).children([
166/// NewNode::new(Category::create().name("Phones")),
167/// NewNode::new(Category::create().name("Laptops")),
168/// ]),
169/// )
170/// .await?;
171/// # Ok(())
172/// # }
173/// ```
174pub struct NewNode<M: Model> {
175 pub(crate) create: CreateBuilder<M>,
176 pub(crate) children: Vec<NewNode<M>>,
177}
178
179impl<M: Model> NewNode<M> {
180 /// A node that `create` makes, without children yet.
181 pub fn new(create: impl Into<CreateBuilder<M>>) -> Self {
182 Self {
183 create: create.into(),
184 children: Vec::new(),
185 }
186 }
187
188 /// Adds `children` after the node's other children.
189 #[must_use]
190 pub fn children(mut self, children: impl IntoIterator<Item = NewNode<M>>) -> Self {
191 self.children.extend(children);
192 self
193 }
194}