Skip to main content

xpict_core/
elk.rs

1//! Multi-molecule diagram placement via **elkrs** (native ELK).
2//!
3//! Used by [`crate::doc::compose_scheme`] for reaction_scheme documents.
4
5use std::collections::BTreeMap;
6
7use crate::doc::{EdgeRouting, LayoutAlgorithm, LayoutDirection, LayoutOpts};
8
9/// Whether the diagram uses reaction packing defaults (vs generic network).
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum DiagramKind {
12    Network,
13    Reaction,
14}
15
16fn direction_elk(d: LayoutDirection) -> &'static str {
17    match d {
18        LayoutDirection::Right => "RIGHT",
19        LayoutDirection::Left => "LEFT",
20        LayoutDirection::Up => "UP",
21        LayoutDirection::Down => "DOWN",
22    }
23}
24
25fn routing_elk(r: EdgeRouting) -> &'static str {
26    match r {
27        EdgeRouting::Orthogonal => "ORTHOGONAL",
28        EdgeRouting::Polyline => "POLYLINE",
29        EdgeRouting::Splines => "SPLINES",
30    }
31}
32
33fn algorithm_elk(a: LayoutAlgorithm) -> &'static str {
34    match a {
35        LayoutAlgorithm::Layered => "layered",
36        LayoutAlgorithm::Radial => "radial",
37        LayoutAlgorithm::Force => "force",
38        LayoutAlgorithm::Stress => "stress",
39    }
40}
41
42/// Backend-agnostic [`LayoutOpts`] → ELK `layoutOptions` map.
43///
44/// Reaction diagrams pack tightly (node spacing ~20, layer spacing ~0) and pin
45/// `unnecessaryBendpoints=false` so shafts only bend where they turn.
46pub fn scheme_layout_options(kind: DiagramKind, opts: &LayoutOpts) -> BTreeMap<String, String> {
47    let mut base: BTreeMap<String, String> = BTreeMap::from([
48        ("elk.algorithm".into(), "layered".into()),
49        ("elk.direction".into(), "RIGHT".into()),
50        ("elk.edgeRouting".into(), "POLYLINE".into()),
51        // Keep shafts simple: only bend where the edge actually turns.
52        ("elk.layered.unnecessaryBendpoints".into(), "false".into()),
53        ("elk.spacing.nodeNode".into(), "40".into()),
54        ("elk.spacing.edgeEdge".into(), "16".into()),
55        ("elk.spacing.edgeNode".into(), "20".into()),
56        (
57            "elk.layered.spacing.nodeNodeBetweenLayers".into(),
58            "48".into(),
59        ),
60        (
61            "elk.layered.spacing.edgeNodeBetweenLayers".into(),
62            "24".into(),
63        ),
64        (
65            "elk.layered.crossingMinimization.strategy".into(),
66            "LAYER_SWEEP".into(),
67        ),
68        (
69            "elk.layered.nodePlacement.strategy".into(),
70            "NETWORK_SIMPLEX".into(),
71        ),
72        // Slide dummy ports along the flow side toward the other endpoint.
73        ("elk.portConstraints".into(), "FIXED_SIDE".into()),
74        (
75            "elk.layered.nodePlacement.networkSimplex.nodeFlexibility.default".into(),
76            "PORT_POSITION".into(),
77        ),
78    ]);
79
80    if kind == DiagramKind::Reaction {
81        // Depth-first cycle breaking keeps the real sources on top; greedy can lift a cycle member there.
82        base.insert(
83            "elk.layered.cycleBreaking.strategy".into(),
84            "DEPTH_FIRST".into(),
85        );
86        base.insert(
87            "elk.spacing.nodeNode".into(),
88            LayoutOpts::DEFAULT_NODE_SPACING.to_string(),
89        );
90        base.insert(
91            "elk.layered.spacing.nodeNodeBetweenLayers".into(),
92            LayoutOpts::DEFAULT_LAYER_SPACING.to_string(),
93        );
94        base.insert(
95            "elk.layered.spacing.edgeNodeBetweenLayers".into(),
96            LayoutOpts::DEFAULT_LAYER_SPACING.to_string(),
97        );
98        base.insert("elk.spacing.edgeEdge".into(), "16".into());
99        base.insert(
100            "elk.layered.crossingMinimization.forceNodeModelOrder".into(),
101            "false".into(),
102        );
103    }
104
105    if opts.algorithm.is_some() {
106        base.insert(
107            "elk.algorithm".into(),
108            algorithm_elk(opts.algorithm_or_default()).into(),
109        );
110    }
111    if opts.direction.is_some() {
112        base.insert(
113            "elk.direction".into(),
114            direction_elk(opts.direction_or_default()).into(),
115        );
116    }
117    if opts.edge_routing.is_some() {
118        base.insert(
119            "elk.edgeRouting".into(),
120            routing_elk(opts.edge_routing_or_default()).into(),
121        );
122    }
123    if let Some(ns) = opts.node_spacing {
124        base.insert("elk.spacing.nodeNode".into(), ns.to_string());
125    }
126    if let Some(ls) = opts.layer_spacing {
127        base.insert(
128            "elk.layered.spacing.nodeNodeBetweenLayers".into(),
129            ls.to_string(),
130        );
131        base.insert(
132            "elk.layered.spacing.edgeNodeBetweenLayers".into(),
133            (ls * 0.5).max(0.0).to_string(),
134        );
135    }
136    base
137}
138
139/// Per-child options so dummy ports slide along the flow side toward the other mol.
140pub fn scheme_node_layout_options() -> BTreeMap<String, String> {
141    BTreeMap::from([
142        ("elk.portConstraints".into(), "FIXED_SIDE".into()),
143        (
144            "elk.layered.nodePlacement.networkSimplex.nodeFlexibility".into(),
145            "PORT_POSITION".into(),
146        ),
147    ])
148}
149
150/// Lay out an ELK JSON graph string; returns laid-out JSON.
151///
152/// Errors are returned as strings (invalid JSON, unknown algorithm, …).
153pub fn layout_json(input: &str) -> Result<String, String> {
154    let value = elkrs::create_elk().layout_json(input)?;
155    Ok(value.to_string())
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn reaction_defaults_tight_pack_no_extra_bends() {
164        let opts = LayoutOpts::default();
165        let m = scheme_layout_options(DiagramKind::Reaction, &opts);
166        assert_eq!(m.get("elk.algorithm").unwrap(), "layered");
167        assert_eq!(m.get("elk.layered.unnecessaryBendpoints").unwrap(), "false");
168        assert_eq!(m.get("elk.portConstraints").unwrap(), "FIXED_SIDE");
169        assert_eq!(
170            m.get("elk.layered.nodePlacement.networkSimplex.nodeFlexibility.default")
171                .unwrap(),
172            "PORT_POSITION"
173        );
174        assert_eq!(
175            m.get("elk.spacing.nodeNode").unwrap(),
176            &LayoutOpts::DEFAULT_NODE_SPACING.to_string()
177        );
178        assert_eq!(
179            m.get("elk.layered.spacing.nodeNodeBetweenLayers").unwrap(),
180            &LayoutOpts::DEFAULT_LAYER_SPACING.to_string()
181        );
182    }
183
184    #[test]
185    fn algorithm_override_selects_force() {
186        let opts = LayoutOpts {
187            algorithm: Some(LayoutAlgorithm::Force),
188            ..Default::default()
189        };
190        let m = scheme_layout_options(DiagramKind::Network, &opts);
191        assert_eq!(m.get("elk.algorithm").unwrap(), "force");
192    }
193
194    #[test]
195    fn layout_opts_map_direction_routing_spacing() {
196        for (dir, want) in [
197            (LayoutDirection::Right, "RIGHT"),
198            (LayoutDirection::Left, "LEFT"),
199            (LayoutDirection::Up, "UP"),
200            (LayoutDirection::Down, "DOWN"),
201        ] {
202            let opts = LayoutOpts {
203                direction: Some(dir),
204                ..Default::default()
205            };
206            let m = scheme_layout_options(DiagramKind::Network, &opts);
207            assert_eq!(m.get("elk.direction").unwrap(), want);
208        }
209        for (r, want) in [
210            (EdgeRouting::Orthogonal, "ORTHOGONAL"),
211            (EdgeRouting::Polyline, "POLYLINE"),
212            (EdgeRouting::Splines, "SPLINES"),
213        ] {
214            let opts = LayoutOpts {
215                edge_routing: Some(r),
216                ..Default::default()
217            };
218            let m = scheme_layout_options(DiagramKind::Network, &opts);
219            assert_eq!(m.get("elk.edgeRouting").unwrap(), want);
220        }
221        for (a, want) in [
222            (LayoutAlgorithm::Layered, "layered"),
223            (LayoutAlgorithm::Radial, "radial"),
224            (LayoutAlgorithm::Force, "force"),
225            (LayoutAlgorithm::Stress, "stress"),
226        ] {
227            let opts = LayoutOpts {
228                algorithm: Some(a),
229                ..Default::default()
230            };
231            assert_eq!(
232                scheme_layout_options(DiagramKind::Reaction, &opts)
233                    .get("elk.algorithm")
234                    .unwrap(),
235                want
236            );
237        }
238        let opts = LayoutOpts {
239            node_spacing: Some(24.0),
240            layer_spacing: Some(40.0),
241            ..Default::default()
242        };
243        let m = scheme_layout_options(DiagramKind::Reaction, &opts);
244        assert_eq!(m.get("elk.spacing.nodeNode").unwrap(), "24");
245        assert_eq!(
246            m.get("elk.layered.spacing.nodeNodeBetweenLayers").unwrap(),
247            "40"
248        );
249        assert_eq!(
250            m.get("elk.layered.spacing.edgeNodeBetweenLayers").unwrap(),
251            "20"
252        );
253    }
254
255    #[test]
256    fn layered_orthogonal_emits_edge_sections() {
257        let input = r#"{
258          "id": "root",
259          "layoutOptions": {
260            "elk.algorithm": "layered",
261            "elk.direction": "RIGHT",
262            "elk.edgeRouting": "ORTHOGONAL"
263          },
264          "children": [
265            {"id": "a", "width": 40.0, "height": 30.0},
266            {"id": "extra", "width": 10.0, "height": 10.0},
267            {"id": "b", "width": 40.0, "height": 30.0}
268          ],
269          "edges": [{"id": "e0", "sources": ["a"], "targets": ["b"]}]
270        }"#;
271        let out = layout_json(input).expect("layout");
272        assert!(out.contains("\"x\""), "{out}");
273        assert!(
274            out.contains("sections") && out.contains("startPoint"),
275            "{out}"
276        );
277        // Parity with Python ``test_elk_layout_json_layered``: b is right of a.
278        let parsed: serde_json::Value = serde_json::from_str(&out).expect("json");
279        let children = parsed["children"].as_array().expect("children");
280        let mut ax = None;
281        let mut bx = None;
282        for c in children {
283            match c["id"].as_str() {
284                Some("a") => ax = c["x"].as_f64(),
285                Some("b") => bx = c["x"].as_f64(),
286                _ => {}
287            }
288        }
289        assert!(bx.unwrap() > ax.unwrap(), "b.x should be > a.x: {out}");
290        let edge = &parsed["edges"][0];
291        assert!(edge["sections"]
292            .as_array()
293            .map(|s| !s.is_empty())
294            .unwrap_or(false));
295        assert!(edge["sections"][0].get("startPoint").is_some());
296    }
297
298    #[test]
299    fn layered_ignores_extra_children_in_assert_loop() {
300        // Extra node exercises the `_` arm when scanning children by id.
301        let input = r#"{
302          "id": "root",
303          "layoutOptions": {
304            "elk.algorithm": "layered",
305            "elk.direction": "RIGHT",
306            "elk.edgeRouting": "ORTHOGONAL"
307          },
308          "children": [
309            {"id": "a", "width": 40.0, "height": 30.0},
310            {"id": "extra", "width": 20.0, "height": 20.0},
311            {"id": "b", "width": 40.0, "height": 30.0}
312          ],
313          "edges": [{"id": "e0", "sources": ["a"], "targets": ["b"]}]
314        }"#;
315        let out = layout_json(input).expect("layout");
316        let parsed: serde_json::Value = serde_json::from_str(&out).expect("json");
317        assert!(parsed["children"].as_array().unwrap().len() >= 3);
318    }
319
320    #[test]
321    fn port_flexibility_slides_toward_shorter_neighbor() {
322        let graph_opts = {
323            let mut m = scheme_layout_options(
324                DiagramKind::Network,
325                &LayoutOpts {
326                    edge_routing: Some(crate::doc::EdgeRouting::Orthogonal),
327                    ..Default::default()
328                },
329            );
330            m.insert("elk.algorithm".into(), "layered".into());
331            m
332        };
333        let node_opts = scheme_node_layout_options();
334        let input = serde_json::json!({
335            "id": "root",
336            "layoutOptions": graph_opts,
337            "children": [
338                {"id": "a", "width": 40.0, "height": 20.0, "layoutOptions": node_opts.clone()},
339                {"id": "b", "width": 40.0, "height": 80.0, "layoutOptions": node_opts},
340            ],
341            "edges": [{"id": "e0", "sources": ["a"], "targets": ["b"]}],
342        })
343        .to_string();
344        let parsed: serde_json::Value =
345            serde_json::from_str(&layout_json(&input).expect("layout")).expect("json");
346        let start = &parsed["edges"][0]["sections"][0]["startPoint"];
347        let end = &parsed["edges"][0]["sections"][0]["endPoint"];
348        let sy = start["y"].as_f64().unwrap();
349        let ey = end["y"].as_f64().unwrap();
350        // Centers of 20 vs 80 boxes differ by 30px if tops align; sliding ports
351        // should keep the shaft closer than that.
352        assert!(
353            (sy - ey).abs() < 20.0,
354            "port Y should slide toward the source, start={sy} end={ey} json={parsed}"
355        );
356    }
357}