dugong 0.6.0

Dagre-compatible graph layout algorithms (port of dagrejs/dagre).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Dagre-style layout pipeline.
//!
//! This pipeline follows upstream Dagre's structure more closely (ranking, normalization,
//! ordering, BK positioning, translation).

use crate::graphlib;
use crate::{
    EdgeLabel, GraphLabel, LabelPos, NodeLabel, Point, RankDir, acyclic, add_border_segments,
    coordinate_system, nesting_graph, normalize, order, parent_dummy_chains, position, rank,
    self_edges, util,
};

pub fn layout_dagreish(g: &mut graphlib::Graph<NodeLabel, EdgeLabel, GraphLabel>) {
    let timing_enabled = std::env::var("DUGONG_DAGREISH_TIMING")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);

    #[derive(Debug, Default, Clone)]
    struct DagreishTimings {
        total: std::time::Duration,
        preprocess: std::time::Duration,
        self_edges_remove: std::time::Duration,
        acyclic: std::time::Duration,
        nesting_run: std::time::Duration,
        rank: std::time::Duration,
        edge_label_proxies: std::time::Duration,
        assign_rank_min_max: std::time::Duration,
        normalize_run: std::time::Duration,
        compound_border: std::time::Duration,
        order: std::time::Duration,
        coord_adjust: std::time::Duration,
        self_edges_insert: std::time::Duration,
        layering_y: std::time::Duration,
        position_x: std::time::Duration,
        self_edges_position: std::time::Duration,
        remove_border_nodes: std::time::Duration,
        normalize_undo: std::time::Duration,
        translate: std::time::Duration,
        edge_points: std::time::Duration,
        acyclic_undo: std::time::Duration,
    }

    let total_start = timing_enabled.then(std::time::Instant::now);
    let mut timings = DagreishTimings::default();

    // Mirror Dagre's `makeSpaceForEdgeLabels` so edge-label proxy ranks become integers
    // (we later materialize label nodes in `normalize::run`).
    let preprocess_start = timing_enabled.then(std::time::Instant::now);
    g.graph_mut().ranksep /= 2.0;
    let rankdir = g.graph().rankdir;
    g.for_each_edge_mut(|_ek, e| {
        e.minlen = e.minlen.max(1).saturating_mul(2);
        if !matches!(e.labelpos, LabelPos::C) {
            match rankdir {
                RankDir::TB | RankDir::BT => e.width += e.labeloffset,
                RankDir::LR | RankDir::RL => e.height += e.labeloffset,
            }
        }
    });
    if let Some(s) = preprocess_start {
        timings.preprocess = s.elapsed();
    }

    // Dagre removes self-loops before ranking/normalization and re-inserts them during positioning
    // via dummy "selfedge" nodes. This avoids invalid rank constraints and gives self-loops a
    // deterministic, spacing-aware offset in BK positioning.
    let self_edges_remove_start = timing_enabled.then(std::time::Instant::now);
    self_edges::remove_self_edges(g);
    if let Some(s) = self_edges_remove_start {
        timings.self_edges_remove = s.elapsed();
    }

    let mut has_compound_structure = false;
    g.for_each_node(|id, _n| {
        if g.parent(id).is_some() || g.children_iter(id).next().is_some() {
            has_compound_structure = true;
        }
    });
    let tiny_simple_chain = g.node_count() == 2 && g.edge_count() == 1 && !has_compound_structure;
    let first_edge_pre = if tiny_simple_chain {
        g.edges().next().cloned()
    } else {
        None
    };

    let acyclic_start = timing_enabled.then(std::time::Instant::now);
    let ran_acyclic = if tiny_simple_chain || g.edge_count() <= 1 {
        false
    } else {
        acyclic::run(g);
        true
    };
    if let Some(s) = acyclic_start {
        timings.acyclic = s.elapsed();
    }

    // Mermaid's dagre adapter always enables `compound: true`, and Dagre's ranker expects a
    // connected graph. Nesting graph connects components (even if there are no explicit
    // subgraphs), preventing network-simplex from panicking on disconnected inputs.
    if g.options().compound {
        let nesting_start = timing_enabled.then(std::time::Instant::now);
        let ran_nesting = if tiny_simple_chain {
            false
        } else {
            nesting_graph::run(g);
            true
        };
        if let Some(s) = nesting_start {
            if ran_nesting {
                timings.nesting_run = s.elapsed();
            }
        }
    }

    // Match upstream Dagre: ranking runs on a non-compound view of the graph so cluster nodes
    // (nodes with children) do not participate in ranking / network-simplex connectivity.
    //
    // `nesting_graph::run` materializes border nodes and nesting edges; those border nodes are
    // leaf nodes and remain in the non-compound graph, providing the constraints Dagre expects.
    let rank_start = timing_enabled.then(std::time::Instant::now);
    if tiny_simple_chain {
        // For the smallest flowcharts (e.g. `A --> B`) network-simplex + ordering overhead
        // dominates total runtime. A deterministic direct rank assignment keeps behavior
        // identical for these cases while cutting fixed-cost work.
        g.for_each_node_mut(|_id, n| n.rank = Some(0));
        if let Some(ek) = first_edge_pre.clone() {
            let minlen = g
                .edge_by_key(&ek)
                .map(|e| e.minlen.max(1) as i32)
                .unwrap_or(1);
            if let Some(n) = g.node_mut(&ek.v) {
                n.rank = Some(0);
            }
            if let Some(n) = g.node_mut(&ek.w) {
                n.rank = Some(minlen);
            }
        }
    } else {
        let mut rank_graph = util::as_non_compound_graph(g);
        rank::rank(&mut rank_graph);
        // Mirror Dagre's JS behavior: `rank(asNonCompoundGraph(g))` mutates the same label objects
        // for leaf nodes, but does not propagate ranks to compound nodes (nodes with children).
        //
        // In Rust we don't share label objects between graphs, so we copy ranks explicitly for leaf
        // nodes only.
        for v in g.node_ids() {
            if g.children_iter(&v).next().is_some() {
                continue;
            }
            let Some(rank) = rank_graph.node(&v).and_then(|n| n.rank) else {
                continue;
            };
            if let Some(n) = g.node_mut(&v) {
                n.rank = Some(rank);
            }
        }
    }
    if let Some(s) = rank_start {
        timings.rank = s.elapsed();
    }

    // Mirror Dagre's `injectEdgeLabelProxies` / `removeEdgeLabelProxies` to compute label ranks.
    // These label ranks are used by `normalize::run` to materialize `edge-label` dummy nodes with
    // the correct width/height, letting BK positioning account for edge labels.
    let edge_proxy_start = timing_enabled.then(std::time::Instant::now);
    let mut edge_proxy_nodes: Vec<String> = Vec::new();
    // Only clone edge keys when a proxy is actually needed.
    let mut to_proxy: Vec<(graphlib::EdgeKey, i32)> = Vec::new();
    g.for_each_edge(|ek, edge| {
        if edge.width <= 0.0 || edge.height <= 0.0 {
            return;
        }
        let Some(v_rank) = g.node(&ek.v).and_then(|n| n.rank) else {
            return;
        };
        let Some(w_rank) = g.node(&ek.w).and_then(|n| n.rank) else {
            return;
        };
        let rank = (w_rank - v_rank) / 2 + v_rank;
        to_proxy.push((ek.clone(), rank));
    });

    for (ek, rank) in to_proxy {
        let id = util::unique_id("_ep");
        edge_proxy_nodes.push(id.clone());
        g.set_node(
            id,
            NodeLabel {
                rank: Some(rank),
                dummy: Some("edge-proxy".to_string()),
                edge_obj: Some(ek),
                ..Default::default()
            },
        );
    }

    util::remove_empty_ranks(g);

    // Match upstream Dagre: `nestingGraph.cleanup` must happen before ordering/positioning.
    if g.options().compound && !tiny_simple_chain {
        nesting_graph::cleanup(g);
    }

    util::normalize_ranks(g);

    // Remove edge label proxy nodes, storing their rank on the corresponding edge label.
    for v in std::mem::take(&mut edge_proxy_nodes) {
        let Some(node) = g.node(&v).cloned() else {
            let _ = g.remove_node(&v);
            continue;
        };
        if node.dummy.as_deref() != Some("edge-proxy") {
            let _ = g.remove_node(&v);
            continue;
        }
        let Some(edge_obj) = node.edge_obj else {
            let _ = g.remove_node(&v);
            continue;
        };
        if let Some(lbl) = g.edge_mut_by_key(&edge_obj) {
            lbl.label_rank = node.rank;
        }
        let _ = g.remove_node(&v);
    }

    // Defensive parity: if the caller-provided graph already contained edge-proxy nodes,
    // remove them as well to match the previous best-effort behavior.
    let mut leftovers: Vec<String> = Vec::new();
    g.for_each_node(|id, n| {
        if n.dummy.as_deref() == Some("edge-proxy") {
            leftovers.push(id.to_string());
        }
    });
    for v in leftovers {
        let Some(node) = g.node(&v).cloned() else {
            let _ = g.remove_node(&v);
            continue;
        };
        let Some(edge_obj) = node.edge_obj else {
            let _ = g.remove_node(&v);
            continue;
        };
        if let Some(lbl) = g.edge_mut_by_key(&edge_obj) {
            lbl.label_rank = node.rank;
        }
        let _ = g.remove_node(&v);
    }
    if let Some(s) = edge_proxy_start {
        timings.edge_label_proxies = s.elapsed();
    }

    // Dagre uses `assignRankMinMax` to annotate compound nodes with their rank span, derived from
    // the `nestingGraph` border top/bottom nodes. This rank span is later used by subgraph
    // ordering and border segment generation.
    if g.options().compound && !tiny_simple_chain {
        let span_start = timing_enabled.then(std::time::Instant::now);
        let node_ids = g.node_ids();
        for v in node_ids {
            let Some(node) = g.node(&v).cloned() else {
                continue;
            };
            let (Some(bt), Some(bb)) = (node.border_top.clone(), node.border_bottom.clone()) else {
                continue;
            };
            let (Some(min_rank), Some(max_rank)) = (
                g.node(&bt).and_then(|n| n.rank),
                g.node(&bb).and_then(|n| n.rank),
            ) else {
                continue;
            };
            if let Some(n) = g.node_mut(&v) {
                n.min_rank = Some(min_rank);
                n.max_rank = Some(max_rank);
            }
        }
        if let Some(s) = span_start {
            timings.assign_rank_min_max = s.elapsed();
        }
    }

    let normalize_run_start = timing_enabled.then(std::time::Instant::now);
    normalize::run(g);
    if let Some(s) = normalize_run_start {
        timings.normalize_run = s.elapsed();
    }
    if g.options().compound && !tiny_simple_chain {
        let border_start = timing_enabled.then(std::time::Instant::now);
        parent_dummy_chains::parent_dummy_chains(g);
        add_border_segments::add_border_segments(g);
        if let Some(s) = border_start {
            timings.compound_border = s.elapsed();
        }
    }
    let order_start = timing_enabled.then(std::time::Instant::now);
    if tiny_simple_chain {
        let mut nodes: Vec<(i32, String)> = Vec::with_capacity(g.node_count());
        g.for_each_node(|id, n| nodes.push((n.rank.unwrap_or(0), id.to_string())));
        nodes.sort_by(|a, b| (a.0, a.1.as_str()).cmp(&(b.0, b.1.as_str())));

        let mut cur_rank: Option<i32> = None;
        let mut next_order: usize = 0;
        for (rank, id) in nodes {
            if cur_rank != Some(rank) {
                cur_rank = Some(rank);
                next_order = 0;
            }
            if let Some(n) = g.node_mut(&id) {
                n.order = Some(next_order);
            }
            next_order += 1;
        }
    } else {
        order::order(
            g,
            order::OrderOptions {
                disable_optimal_order_heuristic: false,
            },
        );
    }
    if let Some(s) = order_start {
        timings.order = s.elapsed();
    }

    // Positioning runs in TB coordinates; `coordinate_system::adjust` maps LR/RL/BT into TB.
    let coord_adjust_start = timing_enabled.then(std::time::Instant::now);
    coordinate_system::adjust(g);
    if let Some(s) = coord_adjust_start {
        timings.coord_adjust = s.elapsed();
    }

    // Insert dummy self-edge nodes after ordering and rankdir transforms, so their sizes match the
    // active coordinate system (TB) and they can influence BK x-positioning.
    let self_edges_insert_start = timing_enabled.then(std::time::Instant::now);
    self_edges::insert_self_edges(g);
    if let Some(s) = self_edges_insert_start {
        timings.self_edges_insert = s.elapsed();
    }

    let rank_sep = g.graph().ranksep;
    let layering_start = timing_enabled.then(std::time::Instant::now);
    let layering = util::build_layer_matrix(g);

    let mut prev_y: f64 = 0.0;
    for (idx, layer) in layering.iter().enumerate() {
        let max_h = layer
            .iter()
            .filter_map(|id| g.node(id).map(|n| n.height))
            .fold(0.0_f64, f64::max);
        let y = prev_y + max_h / 2.0;
        for id in layer {
            if let Some(n) = g.node_mut(id) {
                n.y = Some(y);
            }
        }
        prev_y += max_h;
        if idx + 1 < layering.len() {
            prev_y += rank_sep;
        }
    }
    if let Some(s) = layering_start {
        timings.layering_y = s.elapsed();
    }

    let position_x_start = timing_enabled.then(std::time::Instant::now);
    let xs = position::bk::position_x_with_layering(g, &layering);
    g.for_each_node_mut(|id, n| {
        n.x = Some(xs.get(id).copied().unwrap_or(0.0));
    });
    if let Some(s) = position_x_start {
        timings.position_x = s.elapsed();
    }

    // Convert dummy self-edge nodes into self-loop edge point sequences and remove the dummy nodes.
    let self_edges_position_start = timing_enabled.then(std::time::Instant::now);
    self_edges::position_self_edges(g);
    if let Some(s) = self_edges_position_start {
        timings.self_edges_position = s.elapsed();
    }

    // Match upstream Dagre: `removeBorderNodes` runs after positioning and before `normalize.undo`.
    // It sets compound-node geometry (x/y/width/height) from border nodes, then removes all
    // border dummy nodes.
    if g.options().compound && !tiny_simple_chain {
        let remove_border_start = timing_enabled.then(std::time::Instant::now);
        super::compound::remove_border_nodes(g);
        if let Some(s) = remove_border_start {
            timings.remove_border_nodes = s.elapsed();
        }
    }

    let normalize_undo_start = timing_enabled.then(std::time::Instant::now);
    normalize::undo(g);
    coordinate_system::undo(g);
    if let Some(s) = normalize_undo_start {
        timings.normalize_undo = s.elapsed();
    }

    // Translate so the minimum top-left is at (marginx, marginy), matching Dagre's
    // `translateGraph(...)` behavior.
    let translate_start = timing_enabled.then(std::time::Instant::now);
    let mut min_x: f64 = f64::INFINITY;
    let mut min_y: f64 = f64::INFINITY;
    g.for_each_node(|_id, n| {
        let (Some(x), Some(y)) = (n.x, n.y) else {
            return;
        };
        min_x = min_x.min(x - n.width / 2.0);
        min_y = min_y.min(y - n.height / 2.0);
    });
    g.for_each_edge(|_ek, lbl| {
        // Match Dagre's `translateGraph(...)`: it computes min/max based on nodes and edge-label
        // boxes, but does not include intermediate edge points. This can leave some internal spline
        // control points with negative coordinates (which Mermaid preserves in `data-points`), while
        // the rendered path remains within the viewBox because `curveBasis` does not pass through
        // those interior points.
        if let (Some(x), Some(y)) = (lbl.x, lbl.y) {
            min_x = min_x.min(x - lbl.width / 2.0);
            min_y = min_y.min(y - lbl.height / 2.0);
        }
    });

    if min_x.is_finite() && min_y.is_finite() {
        // Dagre shifts the graph by `-(min - margin)` so the smallest x/y becomes `margin`.
        // This is observable in Mermaid flowchart-v2 SVG output where `diagramPadding: 0`
        // still yields a `viewBox` starting at x=8 (the Dagre margin).
        min_x -= g.graph().marginx;
        min_y -= g.graph().marginy;
        let dx = -min_x;
        let dy = -min_y;
        g.for_each_node_mut(|_id, n| {
            if let Some(x) = n.x {
                n.x = Some(x + dx);
            }
            if let Some(y) = n.y {
                n.y = Some(y + dy);
            }
        });
        g.for_each_edge_mut(|_ek, lbl| {
            for p in &mut lbl.points {
                p.x += dx;
                p.y += dy;
            }
            if let Some(x) = lbl.x {
                lbl.x = Some(x + dx);
            }
            if let Some(y) = lbl.y {
                lbl.y = Some(y + dy);
            }
        });
    }
    if let Some(s) = translate_start {
        timings.translate = s.elapsed();
    }

    // Ensure every edge has at least one internal point (so D3 `curveBasis` emits cubic beziers),
    // and add node intersection endpoints to better match Dagre/Mermaid edge point semantics.
    let edge_points_start = timing_enabled.then(std::time::Instant::now);
    let edge_keys: Vec<graphlib::EdgeKey> = g.edges().cloned().collect();
    for e in edge_keys {
        let Some((sx, sy, sw, sh)) = g
            .node(&e.v)
            .map(|n| (n.x.unwrap_or(0.0), n.y.unwrap_or(0.0), n.width, n.height))
        else {
            continue;
        };
        let Some((tx, ty, tw, th)) = g
            .node(&e.w)
            .map(|n| (n.x.unwrap_or(0.0), n.y.unwrap_or(0.0), n.width, n.height))
        else {
            continue;
        };

        let Some(lbl) = g.edge_mut(&e.v, &e.w, e.name.as_deref()) else {
            continue;
        };

        let mut internal: Vec<Point> = if lbl.points.is_empty() {
            vec![Point {
                x: (sx + tx) / 2.0,
                y: (sy + ty) / 2.0,
            }]
        } else {
            lbl.points.clone()
        };
        if internal.is_empty() {
            internal.push(Point {
                x: (sx + tx) / 2.0,
                y: (sy + ty) / 2.0,
            });
        }

        let Some(first) = internal.first().copied() else {
            continue;
        };
        let Some(last) = internal.last().copied() else {
            continue;
        };

        let mut pts: Vec<Point> = Vec::with_capacity(internal.len() + 2);

        pts.push(util::intersect_rect(
            util::Rect {
                x: sx,
                y: sy,
                width: sw,
                height: sh,
            },
            first,
        ));
        pts.extend(internal);
        pts.push(util::intersect_rect(
            util::Rect {
                x: tx,
                y: ty,
                width: tw,
                height: th,
            },
            last,
        ));

        lbl.points = pts;

        if (lbl.width > 0.0 || lbl.height > 0.0) && lbl.x.is_none() && lbl.y.is_none() {
            if let Some(mid) = lbl.points.get(lbl.points.len() / 2).copied() {
                let mut ex = mid.x;
                let ey = mid.y;
                match lbl.labelpos {
                    LabelPos::C => {}
                    LabelPos::L => ex -= lbl.labeloffset + lbl.width / 2.0,
                    LabelPos::R => ex += lbl.labeloffset + lbl.width / 2.0,
                }
                lbl.x = Some(ex);
                lbl.y = Some(ey);
            }
        }
    }
    if let Some(s) = edge_points_start {
        timings.edge_points = s.elapsed();
    }

    let acyclic_undo_start = timing_enabled.then(std::time::Instant::now);
    if ran_acyclic {
        acyclic::undo(g);
    }
    if let Some(s) = acyclic_undo_start {
        timings.acyclic_undo = s.elapsed();
    }

    if let Some(s) = total_start {
        timings.total = s.elapsed();
        eprintln!(
            "[dugong-timing] pipeline=dagreish nodes={} edges={} total={:?} preprocess={:?} self_edges_remove={:?} acyclic={:?} nesting_run={:?} rank={:?} edge_label_proxies={:?} assign_rank_min_max={:?} normalize_run={:?} compound_border={:?} order={:?} coord_adjust={:?} self_edges_insert={:?} layering_y={:?} position_x={:?} self_edges_position={:?} remove_border_nodes={:?} normalize_undo={:?} translate={:?} edge_points={:?} acyclic_undo={:?}",
            g.node_count(),
            g.edge_count(),
            timings.total,
            timings.preprocess,
            timings.self_edges_remove,
            timings.acyclic,
            timings.nesting_run,
            timings.rank,
            timings.edge_label_proxies,
            timings.assign_rank_min_max,
            timings.normalize_run,
            timings.compound_border,
            timings.order,
            timings.coord_adjust,
            timings.self_edges_insert,
            timings.layering_y,
            timings.position_x,
            timings.self_edges_position,
            timings.remove_border_nodes,
            timings.normalize_undo,
            timings.translate,
            timings.edge_points,
            timings.acyclic_undo,
        );
    }
}