1use crate::types::{DiagramWarning, Direction, Graph, NodeId, NodeShape, RenderOptions};
2use std::collections::{HashMap, VecDeque};
3
4const MIN_NODE_WIDTH: usize = 5;
5const NODE_HEIGHT: usize = 3;
6const DEFAULT_HORIZONTAL_GAP: usize = 8;
7const DEFAULT_VERTICAL_GAP: usize = 4;
8const MIN_GAP: usize = 2;
9
10const SUBGRAPH_PADDING: usize = 2;
11
12pub fn compute_layout(graph: &mut Graph) -> Vec<DiagramWarning> {
16 compute_layout_with_options(graph, &RenderOptions::default())
17}
18
19pub fn compute_layout_with_options(
23 graph: &mut Graph,
24 options: &RenderOptions,
25) -> Vec<DiagramWarning> {
26 let mut warnings = Vec::new();
27
28 for node in graph.nodes.values_mut() {
30 node.width = (node.label.chars().count() + 2).max(MIN_NODE_WIDTH);
31 node.height = NODE_HEIGHT;
32 if node.shape == NodeShape::Cylinder {
33 node.height = 5;
34 }
35 }
36
37 let layers = assign_layers(graph, &mut warnings);
39
40 let (h_gap, v_gap) = calculate_gaps(graph, &layers, options.max_width);
42
43 assign_coordinates_with_gaps(graph, &layers, h_gap, v_gap);
45
46 compute_subgraph_bounds(graph);
48
49 warnings
50}
51
52fn calculate_gaps(
54 graph: &Graph,
55 layers: &HashMap<NodeId, usize>,
56 max_width: Option<usize>,
57) -> (usize, usize) {
58 let max_width = match max_width {
59 Some(w) => w,
60 None => return (DEFAULT_HORIZONTAL_GAP, DEFAULT_VERTICAL_GAP),
61 };
62
63 let mut layers_map: HashMap<usize, Vec<&NodeId>> = HashMap::new();
65 let mut max_layer = 0;
66
67 for (id, &layer) in layers {
68 layers_map.entry(layer).or_default().push(id);
69 max_layer = max_layer.max(layer);
70 }
71 for nodes in layers_map.values_mut() {
72 nodes.sort();
73 }
74
75 if graph.direction.is_horizontal() {
77 let mut total_width = 0;
78 for l in 0..=max_layer {
79 let nodes_in_layer = layers_map.get(&l).map(|v| v.as_slice()).unwrap_or(&[]);
80 let layer_max_width = nodes_in_layer
81 .iter()
82 .filter_map(|id| graph.nodes.get(*id))
83 .map(|n| n.width)
84 .max()
85 .unwrap_or(0);
86 total_width += layer_max_width;
87 }
88 total_width += max_layer * DEFAULT_HORIZONTAL_GAP;
89
90 if total_width > max_width && max_layer > 0 {
92 let node_width = total_width - max_layer * DEFAULT_HORIZONTAL_GAP;
93 let available_for_gaps = max_width.saturating_sub(node_width);
94 let new_gap = (available_for_gaps / max_layer).max(MIN_GAP);
95 return (new_gap, DEFAULT_VERTICAL_GAP);
96 }
97 }
98
99 (DEFAULT_HORIZONTAL_GAP, DEFAULT_VERTICAL_GAP)
100}
101
102fn compute_subgraph_bounds(graph: &mut Graph) {
104 for sg in &mut graph.subgraphs {
105 if sg.nodes.is_empty() {
106 continue;
107 }
108
109 let mut min_x = usize::MAX;
110 let mut min_y = usize::MAX;
111 let mut max_x = 0;
112 let mut max_y = 0;
113
114 for node_id in &sg.nodes {
115 if let Some(node) = graph.nodes.get(node_id) {
116 min_x = min_x.min(node.x);
117 min_y = min_y.min(node.y);
118 max_x = max_x.max(node.x + node.width);
119 max_y = max_y.max(node.y + node.height);
120 }
121 }
122
123 if min_x != usize::MAX {
124 sg.x = min_x.saturating_sub(SUBGRAPH_PADDING);
126 sg.y = min_y.saturating_sub(SUBGRAPH_PADDING + 1); sg.width = (max_x - min_x) + SUBGRAPH_PADDING * 2;
128 sg.height = (max_y - min_y) + SUBGRAPH_PADDING * 2 + 1;
129 }
130 }
131}
132
133fn assign_layers(graph: &Graph, warnings: &mut Vec<DiagramWarning>) -> HashMap<NodeId, usize> {
135 let mut node_layers: HashMap<NodeId, usize> = HashMap::new();
136 let mut in_degree: HashMap<NodeId, usize> = HashMap::new();
137
138 for id in graph.nodes.keys() {
140 in_degree.insert(id.clone(), 0);
141 node_layers.insert(id.clone(), 0);
142 }
143
144 for edge in &graph.edges {
146 *in_degree.entry(edge.to.clone()).or_insert(0) += 1;
147 }
148
149 let mut queue: VecDeque<NodeId> = VecDeque::new();
151 let mut zero_in: Vec<&NodeId> = in_degree
152 .iter()
153 .filter(|(_, °)| deg == 0)
154 .map(|(id, _)| id)
155 .collect();
156 zero_in.sort();
157 for id in zero_in {
158 queue.push_back(id.clone());
159 }
160
161 let mut processed = 0;
162 while let Some(u) = queue.pop_front() {
163 processed += 1;
164
165 let mut neighbors: Vec<NodeId> = graph
167 .edges
168 .iter()
169 .filter(|e| e.from == u)
170 .map(|e| e.to.clone())
171 .collect();
172 neighbors.sort();
173
174 for v in neighbors {
175 let u_layer = *node_layers.get(&u).unwrap_or(&0);
177 let v_layer = node_layers.entry(v.clone()).or_insert(0);
178 *v_layer = (*v_layer).max(u_layer + 1);
179
180 if let Some(deg) = in_degree.get_mut(&v) {
182 *deg -= 1;
183 if *deg == 0 {
184 queue.push_back(v);
185 }
186 }
187 }
188 }
189
190 if processed < graph.nodes.len() {
195 let mut cycle_nodes: Vec<String> = in_degree
196 .iter()
197 .filter(|(_, °)| deg > 0)
198 .map(|(id, _)| id.clone())
199 .collect();
200 cycle_nodes.sort();
201 warnings.push(DiagramWarning::CycleDetected { nodes: cycle_nodes });
202 }
203
204 node_layers
205}
206
207fn assign_coordinates_with_gaps(
209 graph: &mut Graph,
210 node_layers: &HashMap<NodeId, usize>,
211 h_gap: usize,
212 v_gap: usize,
213) {
214 let direction = graph.direction;
215
216 let mut layers_map: HashMap<usize, Vec<NodeId>> = HashMap::new();
218 let mut max_layer = 0;
219
220 for (id, &layer) in node_layers {
221 layers_map.entry(layer).or_default().push(id.clone());
222 max_layer = max_layer.max(layer);
223 }
224 for nodes in layers_map.values_mut() {
225 nodes.sort();
226 }
227
228 let mut layer_widths: HashMap<usize, usize> = HashMap::new();
230 let mut layer_heights: HashMap<usize, usize> = HashMap::new();
231
232 for l in 0..=max_layer {
233 let nodes_in_layer = layers_map.get(&l).map(|v| v.as_slice()).unwrap_or(&[]);
234 let mut max_w = 0;
235 let mut max_h = 0;
236 let mut total_w = 0;
237 let mut total_h = 0;
238
239 for id in nodes_in_layer {
240 if let Some(node) = graph.nodes.get(id) {
241 max_w = max_w.max(node.width);
242 max_h = max_h.max(node.height);
243 total_w += node.width + h_gap;
244 total_h += node.height + v_gap;
245 }
246 }
247
248 if direction.is_horizontal() {
249 layer_widths.insert(l, max_w);
250 layer_heights.insert(l, total_h.saturating_sub(v_gap));
251 } else {
252 layer_widths.insert(l, total_w.saturating_sub(h_gap));
253 layer_heights.insert(l, max_h);
254 }
255 }
256
257 let max_total_width = layer_widths.values().copied().max().unwrap_or(0);
258 let max_total_height = layer_heights.values().copied().max().unwrap_or(0);
259
260 if direction.is_horizontal() {
261 let mut current_x = 0;
262 for l in 0..=max_layer {
263 let layer_idx = match direction {
264 Direction::LR => l,
265 Direction::RL => max_layer - l,
266 _ => l,
267 };
268
269 let nodes_in_layer = layers_map.get(&layer_idx).cloned().unwrap_or_default();
270 let layer_h = *layer_heights.get(&layer_idx).unwrap_or(&0);
271 let mut start_y = (max_total_height.saturating_sub(layer_h)) / 2;
272
273 for id in nodes_in_layer {
274 if let Some(node) = graph.nodes.get_mut(&id) {
275 node.x = current_x;
276 node.y = start_y;
277 start_y += node.height + v_gap;
278 }
279 }
280
281 current_x += layer_widths.get(&layer_idx).unwrap_or(&0) + h_gap;
282 }
283 } else {
284 let mut current_y = 0;
285 for l in 0..=max_layer {
286 let layer_idx = match direction {
287 Direction::TB => l,
288 Direction::BT => max_layer - l,
289 _ => l,
290 };
291
292 let nodes_in_layer = layers_map.get(&layer_idx).cloned().unwrap_or_default();
293 let layer_w = *layer_widths.get(&layer_idx).unwrap_or(&0);
294 let mut start_x = (max_total_width.saturating_sub(layer_w)) / 2;
295
296 for id in nodes_in_layer {
297 if let Some(node) = graph.nodes.get_mut(&id) {
298 node.x = start_x;
299 node.y = current_y;
300 start_x += node.width + h_gap;
301 }
302 }
303
304 current_y += layer_heights.get(&layer_idx).unwrap_or(&0) + v_gap;
305 }
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312 use crate::parser::parse_mermaid;
313
314 #[test]
315 fn test_layout_lr() {
316 let mut graph = parse_mermaid("flowchart LR\nA --> B").unwrap();
317 let warnings = compute_layout(&mut graph);
318
319 let a = graph.nodes.get("A").unwrap();
320 let b = graph.nodes.get("B").unwrap();
321
322 assert!(a.x < b.x);
323 assert!(warnings.is_empty());
324 }
325
326 #[test]
327 fn test_layout_tb() {
328 let mut graph = parse_mermaid("flowchart TB\nA --> B").unwrap();
329 let warnings = compute_layout(&mut graph);
330
331 let a = graph.nodes.get("A").unwrap();
332 let b = graph.nodes.get("B").unwrap();
333
334 assert!(a.y < b.y);
335 assert!(warnings.is_empty());
336 }
337
338 #[test]
339 fn test_node_sizes() {
340 let mut graph = parse_mermaid("flowchart LR\nA[Hello World]").unwrap();
341 compute_layout(&mut graph);
342
343 let a = graph.nodes.get("A").unwrap();
344 assert_eq!(a.width, "Hello World".len() + 2);
345 assert_eq!(a.height, NODE_HEIGHT);
346 }
347
348 #[test]
349 fn test_cycle_produces_warning() {
350 let mut graph = parse_mermaid("flowchart LR\nA --> B\nB --> C\nC --> A").unwrap();
351 let warnings = compute_layout(&mut graph);
352 assert_eq!(warnings.len(), 1);
353 assert!(warnings[0].to_string().contains("Cycle"));
354 }
355
356 #[test]
357 fn test_acyclic_no_warning() {
358 let mut graph = parse_mermaid("flowchart LR\nA --> B\nB --> C\nA --> C").unwrap();
359 let warnings = compute_layout(&mut graph);
360 assert!(warnings.is_empty());
361 }
362}