Skip to main content

matrix_sdk_ui/spaces/
graph.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for that specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
16
17use ruma::{OwnedRoomId, RoomId};
18
19#[derive(Debug)]
20struct SpaceGraphNode {
21    id: OwnedRoomId,
22    parents: BTreeSet<OwnedRoomId>,
23    children: BTreeSet<OwnedRoomId>,
24}
25
26impl SpaceGraphNode {
27    fn new(id: OwnedRoomId) -> Self {
28        Self { id, parents: BTreeSet::new(), children: BTreeSet::new() }
29    }
30}
31
32/// A graph structure representing a space hierarchy. Contains functionality for
33/// mapping parent-child relationships between rooms, removing cycles and
34/// retrieving top-level parents/roots.
35#[derive(Debug)]
36pub(super) struct SpaceGraph {
37    nodes: BTreeMap<OwnedRoomId, SpaceGraphNode>,
38}
39
40impl Default for SpaceGraph {
41    fn default() -> Self {
42        Self::new()
43    }
44}
45
46impl SpaceGraph {
47    /// Creates a new empty space graph containing no nodes or edges.
48    pub(super) fn new() -> Self {
49        Self { nodes: BTreeMap::new() }
50    }
51
52    /// Returns the root nodes of the graph, which are nodes without any
53    /// parents.
54    pub(super) fn root_nodes(&self) -> Vec<&RoomId> {
55        self.nodes
56            .values()
57            .filter(|node| node.parents.is_empty())
58            .map(|node| node.id.as_ref())
59            .collect()
60    }
61
62    /// Returns the children of a given node. If the node does not exist, it
63    /// returns an empty vector.
64    pub(super) fn children_of(&self, node_id: &RoomId) -> Vec<&RoomId> {
65        self.nodes
66            .get(node_id)
67            .map_or(vec![], |node| node.children.iter().map(|id| id.as_ref()).collect())
68    }
69
70    /// Returns the parents of a given node. If the node does not exist, it
71    /// returns an empty vector.
72    pub(super) fn parents_of(&self, node_id: &RoomId) -> Vec<&RoomId> {
73        self.nodes
74            .get(node_id)
75            .map_or(vec![], |node| node.parents.iter().map(|id| id.as_ref()).collect())
76    }
77
78    /// Adds a node to the graph. If the node already exists, it does nothing.
79    pub(super) fn add_node(&mut self, node_id: OwnedRoomId) {
80        self.nodes.entry(node_id.clone()).or_insert(SpaceGraphNode::new(node_id));
81    }
82
83    /// Returns whether a node exists in the graph.
84    pub(super) fn has_node(&self, node_id: &RoomId) -> bool {
85        self.nodes.contains_key(node_id)
86    }
87
88    /// Returns all the ancestors of the given node, closest first: its
89    /// parents, then their parents, and so on.
90    pub(super) fn ancestors_of(&self, node_id: &RoomId) -> Vec<OwnedRoomId> {
91        let mut queue = VecDeque::from([node_id.to_owned()]);
92        let mut visited = HashSet::from([node_id.to_owned()]);
93        let mut ancestors = Vec::new();
94        while let Some(current) = queue.pop_front() {
95            for parent in self.parents_of(&current) {
96                if visited.insert(parent.to_owned()) {
97                    ancestors.push(parent.to_owned());
98                    queue.push_back(parent.to_owned());
99                }
100            }
101        }
102        ancestors
103    }
104
105    /// Adds a directed edge from `parent_id` to `child_id`, creating nodes if
106    /// they do not already exist in the graph.
107    pub(super) fn add_edge(&mut self, parent_id: OwnedRoomId, child_id: OwnedRoomId) {
108        let parent_entry =
109            self.nodes.entry(parent_id.clone()).or_insert(SpaceGraphNode::new(parent_id.clone()));
110        parent_entry.children.insert(child_id.clone());
111
112        let child_entry =
113            self.nodes.entry(child_id.clone()).or_insert(SpaceGraphNode::new(child_id));
114        child_entry.parents.insert(parent_id);
115    }
116
117    /// Returns the subtree of the given node in a bottom-up order.
118    ///
119    /// Does a BFS starting from the given node tracking the visited nodes and
120    /// returning them in the reverse order.
121    pub(super) fn flattened_bottom_up_subtree(&self, node_id: &RoomId) -> Vec<OwnedRoomId> {
122        if !self.has_node(node_id) {
123            return Vec::new();
124        }
125
126        let mut stack = vec![node_id.to_owned()];
127        let mut result = Vec::new();
128
129        while let Some(node) = stack.pop() {
130            result.insert(0, node.clone());
131
132            if let Some(node) = self.nodes.get(&node) {
133                for child in &node.children {
134                    stack.push(child.to_owned());
135                }
136            }
137        }
138
139        result
140    }
141
142    /// Removes cycles in the graph by performing a depth-first search (DFS) and
143    /// remembering the visited nodes. If a node is revisited while still in the
144    /// current path (i.e. it's on the stack), it indicates a cycle.
145    pub(super) fn remove_cycles(&mut self) {
146        let mut visited = BTreeSet::new();
147        let mut stack = BTreeSet::new();
148
149        let mut edges_to_remove = Vec::new();
150
151        for node_id in self.nodes.keys() {
152            self.dfs_remove_cycles(node_id, &mut visited, &mut stack, &mut edges_to_remove);
153        }
154
155        for (parent, child) in edges_to_remove {
156            if let Some(node) = self.nodes.get_mut(&parent) {
157                node.children.remove(&child);
158            }
159            if let Some(node) = self.nodes.get_mut(&child) {
160                node.parents.remove(&parent);
161            }
162        }
163    }
164
165    fn dfs_remove_cycles(
166        &self,
167        node_id: &OwnedRoomId,
168        visited: &mut BTreeSet<OwnedRoomId>,
169        stack: &mut BTreeSet<OwnedRoomId>,
170        edges_to_remove: &mut Vec<(OwnedRoomId, OwnedRoomId)>,
171    ) {
172        if !visited.insert(node_id.clone()) {
173            return;
174        }
175
176        stack.insert(node_id.clone());
177
178        if let Some(node) = self.nodes.get(node_id) {
179            for child in &node.children {
180                if stack.contains(child) {
181                    // Found a cycle → mark this edge for removal
182                    edges_to_remove.push((node_id.clone(), child.clone()));
183                } else {
184                    self.dfs_remove_cycles(child, visited, stack, edges_to_remove);
185                }
186            }
187        }
188
189        stack.remove(node_id);
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use ruma::{owned_room_id, room_id};
196
197    use super::*;
198
199    #[test]
200    fn test_add_edge_and_root_nodes() {
201        let mut graph = SpaceGraph::new();
202
203        let a = owned_room_id!("!a:example.org");
204        let b = owned_room_id!("!b:example.org");
205        let c = owned_room_id!("!c:example.org");
206
207        graph.add_edge(a.clone(), b.clone());
208        graph.add_edge(a.clone(), c.clone());
209
210        assert_eq!(graph.root_nodes(), vec![&a]);
211
212        assert_eq!(graph.parents_of(&b), vec![&a]);
213        assert_eq!(graph.parents_of(&c), vec![&a]);
214
215        assert_eq!(graph.children_of(&a), vec![&b, &c]);
216    }
217
218    #[test]
219    fn test_remove_cycles() {
220        let mut graph = SpaceGraph::new();
221
222        let a = owned_room_id!("!a:example.org");
223        let b = owned_room_id!("!b:example.org");
224        let c = owned_room_id!("!c:example.org");
225
226        graph.add_edge(a.clone(), b.clone());
227        graph.add_edge(b, c.clone());
228        graph.add_edge(c.clone(), a.clone()); // creates a cycle
229
230        assert!(graph.nodes[&c].children.contains(&a));
231
232        graph.remove_cycles();
233
234        assert!(!graph.nodes[&c].children.contains(&a));
235        assert!(!graph.nodes[&a].parents.contains(&c));
236    }
237
238    #[test]
239    fn test_disconnected_graph_roots() {
240        let mut graph = SpaceGraph::new();
241
242        let a = owned_room_id!("!a:example.org");
243        let b = owned_room_id!("!b:example.org");
244        graph.add_edge(a.clone(), b);
245
246        let x = owned_room_id!("!x:example.org");
247        let y = owned_room_id!("!y:example.org");
248        graph.add_edge(x.clone(), y);
249
250        let mut roots = graph.root_nodes();
251        roots.sort_by_key(|key| key.to_string());
252
253        let expected: Vec<&OwnedRoomId> = vec![&a, &x];
254        assert_eq!(roots, expected);
255    }
256
257    #[test]
258    fn test_multiple_parents() {
259        let mut graph = SpaceGraph::new();
260
261        let a = owned_room_id!("!a:example.org");
262        let b = owned_room_id!("!b:example.org");
263        let c = owned_room_id!("!c:example.org");
264        let d = owned_room_id!("!d:example.org");
265
266        graph.add_edge(a.clone(), c.clone());
267        graph.add_edge(b.clone(), c.clone());
268        graph.add_edge(c.clone(), d);
269
270        let mut roots = graph.root_nodes();
271        roots.sort_by_key(|key| key.to_string());
272
273        let expected = vec![&a, &b];
274        assert_eq!(roots, expected);
275
276        let c_parents = &graph.nodes[&c].parents;
277        assert!(c_parents.contains(&a));
278        assert!(c_parents.contains(&b));
279    }
280
281    #[test]
282    fn test_flattened_bottom_up_subtree() {
283        let graph = vehicle_graph();
284
285        let children = graph.flattened_bottom_up_subtree(room_id!("!personal:x.y"));
286        let expected = vec![
287            owned_room_id!("!gravel:x.y"),
288            owned_room_id!("!mountain:x.y"),
289            owned_room_id!("!road:x.y"),
290            owned_room_id!("!bicycle:x.y"),
291            owned_room_id!("!car:x.y"),
292            owned_room_id!("!helicopter:x.y"),
293            owned_room_id!("!personal:x.y"),
294        ];
295
296        assert_eq!(children, expected);
297
298        let children = graph.flattened_bottom_up_subtree(room_id!("!shared:x.y"));
299        let expected = vec![
300            owned_room_id!("!bus:x.y"),
301            owned_room_id!("!train:x.y"),
302            owned_room_id!("!shared:x.y"),
303        ];
304
305        assert_eq!(children, expected);
306
307        let children = graph.flattened_bottom_up_subtree(room_id!("!plane:x.y"));
308        let expected = vec![owned_room_id!("!plane:x.y")];
309
310        assert_eq!(children, expected);
311
312        let children = graph.flattened_bottom_up_subtree(room_id!("!floo_powder:x.y"));
313        assert!(children.is_empty());
314    }
315
316    fn vehicle_graph() -> SpaceGraph {
317        // Vehicles
318        // ├── Shared
319        // │   ├── Bus
320        // │   └── Train
321        // ├── Personal
322        // │   ├── Car
323        // │   ├── Bicycle
324        // │   │   ├── Road
325        // │   │   ├── Gravel
326        // │   │   └── Mountain
327        // │   └── Helicopter
328        // └── Cargo
329        //     └── Plane
330
331        let mut graph = SpaceGraph::new();
332
333        graph.add_edge(owned_room_id!("!vehicles:x.y"), owned_room_id!("!shared:x.y"));
334        graph.add_edge(owned_room_id!("!shared:x.y"), owned_room_id!("!bus:x.y"));
335        graph.add_edge(owned_room_id!("!shared:x.y"), owned_room_id!("!train:x.y"));
336
337        graph.add_edge(owned_room_id!("!vehicles:x.y"), owned_room_id!("!personal:x.y"));
338        graph.add_edge(owned_room_id!("!personal:x.y"), owned_room_id!("!car:x.y"));
339
340        graph.add_edge(owned_room_id!("!personal:x.y"), owned_room_id!("!bicycle:x.y"));
341        graph.add_edge(owned_room_id!("!bicycle:x.y"), owned_room_id!("!road:x.y"));
342        graph.add_edge(owned_room_id!("!bicycle:x.y"), owned_room_id!("!gravel:x.y"));
343        graph.add_edge(owned_room_id!("!bicycle:x.y"), owned_room_id!("!mountain:x.y"));
344
345        graph.add_edge(owned_room_id!("!personal:x.y"), owned_room_id!("!helicopter:x.y"));
346
347        graph.add_edge(owned_room_id!("!vehicles:x.y"), owned_room_id!("!cargo:x.y"));
348        graph.add_edge(owned_room_id!("!cargo:x.y"), owned_room_id!("!plane:x.y"));
349
350        graph
351    }
352}