Skip to main content

ggplot_rs/
graph.rs

1//! Drawing a laid-out graph of boxes: swimlane bands, edges (polylines with
2//! an arrowhead, a linetype, a width and an optional label placed clear of
3//! the boxes) and node boxes (a wrapped label, an optional value line,
4//! status badge and sparkline, and an accent bar), as one [`GGPlot`] of
5//! ordinary layers.
6//!
7//! Works with [`graph_layout`](crate::graph_layout): size the boxes with
8//! [`node_box`], lay them out with [`layered`](crate::graph_layout::layered),
9//! then [`draw`] the result. What each mark says and what colour it takes
10//! is the caller's (the [`DrawNode`] / [`DrawEdge`] fields); where things go
11//! inside a box and along an edge is decided here. Every mark carries the
12//! caller's `data-*` attributes, and what belongs to one node is wrapped in
13//! `<g data-of="<id>">`, so a browser can address a node as one element.
14//! Moved here from anofox-visualization's `::DIAGRAM`
15//! (sipemu/ggplot-rs#497, DataZooDE/anofox-visualization#1153).
16
17use crate::geom::arrow::arrow;
18use crate::graph_layout::{GraphLayout, PlacedNode};
19use crate::prelude::*;
20use crate::render::backend::{LineEnd, Linetype};
21use crate::scale::linewidth::ScaleLinewidthContinuous;
22
23type Rgb = (u8, u8, u8);
24
25/// Box geometry (px).
26const LABEL_PX: f64 = 13.0;
27const VALUE_PX: f64 = 12.0;
28const BADGE_PX: f64 = 11.0;
29/// An edge label's and a lane name's text size.
30const SMALL_PX: f64 = 11.0;
31const LINE_H: f64 = 16.0;
32const BOX_PAD_X: f64 = 12.0;
33const BOX_PAD_Y: f64 = 9.0;
34const BOX_MIN_W: f64 = 92.0;
35const BOX_MAX_W: f64 = 208.0;
36/// A sparkline's strip in a box.
37const SPARK_H: f64 = 22.0;
38/// The arrowhead's length (px) at zero line width; the layout's
39/// [`LayeredParams::arrow`](crate::graph_layout::LayeredParams::arrow).
40const ARROW: f64 = 7.0;
41/// A node label's line limit; only beyond it is the last line cut with "…".
42const MAX_LINES: usize = 3;
43
44/// Approximate rendered width of `s` at `px` (proportional sans-serif).
45fn text_w(s: &str, px: f64, bold: bool) -> f64 {
46    let per = if bold { 0.6 } else { 0.56 };
47    s.chars().count() as f64 * px * per
48}
49
50/// The width (px) of an edge label as [`draw`] sets it (its widest line):
51/// the layout's [`GraphEdge::label_w`](crate::graph_layout::GraphEdge::label_w).
52pub fn edge_label_width(label: &str) -> f64 {
53    label
54        .split('\n')
55        .map(|l| text_w(l, SMALL_PX, false))
56        .fold(0.0, f64::max)
57}
58
59/// `s` wrapped into at most [`MAX_LINES`] lines of `max` px (the last cut
60/// with "…" when the label doesn't fit). Breaks at spaces; a word longer
61/// than a line breaks after a `/`, `-`, `_`, `.` or `,` in it
62/// (`duckdb/community-` + `extensions`, not `community-ex` + `tensions`),
63/// and only mid-word when it has none.
64fn wrap(s: &str, max: f64) -> Vec<String> {
65    let cap = ((max / (LABEL_PX * 0.6)).floor() as usize).max(4);
66    // (piece, glued to the previous one) — a long word's pieces are glued
67    let mut pieces: Vec<(String, bool)> = Vec::new();
68    for word in s.split_whitespace() {
69        let chars: Vec<char> = word.chars().collect();
70        let mut start = 0;
71        let mut first = true;
72        while chars.len() - start > cap {
73            let window = &chars[start..start + cap];
74            let cut = window
75                .iter()
76                .rposition(|c| matches!(c, '/' | '-' | '_' | '.' | ','))
77                .filter(|&i| i + 1 >= cap / 3)
78                .map(|i| i + 1)
79                .unwrap_or(cap);
80            pieces.push((chars[start..start + cut].iter().collect(), !first));
81            first = false;
82            start += cut;
83        }
84        pieces.push((chars[start..].iter().collect(), !first));
85    }
86    let mut lines: Vec<String> = Vec::new();
87    let mut cur = String::new();
88    for (piece, glued) in pieces {
89        let sep = if glued || cur.is_empty() { 0 } else { 1 };
90        if !cur.is_empty() && cur.chars().count() + sep + piece.chars().count() > cap {
91            lines.push(std::mem::take(&mut cur));
92        } else if sep == 1 {
93            cur.push(' ');
94        }
95        cur.push_str(&piece);
96    }
97    if !cur.is_empty() {
98        lines.push(cur);
99    }
100    if lines.is_empty() {
101        lines.push(String::new());
102    }
103    if lines.len() > MAX_LINES {
104        let rest = lines[MAX_LINES - 1..].join(" ");
105        let mut last: String = rest.chars().take(cap.saturating_sub(1)).collect();
106        last = last.trim_end().to_string();
107        last.push('…');
108        lines.truncate(MAX_LINES - 1);
109        lines.push(last);
110    }
111    lines
112}
113
114/// A node box's size and its label wrapped to fit.
115#[derive(Clone, Debug, PartialEq)]
116pub struct NodeBox {
117    pub w: f64,
118    pub h: f64,
119    pub lines: Vec<String>,
120}
121
122/// The box a node needs: its label wrapped onto at most three lines, plus a
123/// line for `value`, a badge row for `badge` and a sparkline strip when
124/// `spark` (as [`draw`] fills it).
125pub fn node_box(label: &str, value: Option<&str>, badge: Option<&str>, spark: bool) -> NodeBox {
126    let lines = wrap(label, BOX_MAX_W - 2.0 * BOX_PAD_X);
127    let mut w = lines
128        .iter()
129        .map(|l| text_w(l, LABEL_PX, true))
130        .fold(0.0, f64::max);
131    let mut h = 2.0 * BOX_PAD_Y + LINE_H * lines.len() as f64;
132    if let Some(v) = value {
133        w = w.max(text_w(v, VALUE_PX, true));
134        h += LINE_H;
135    }
136    if let Some(b) = badge {
137        w = w.max(text_w(b, BADGE_PX, false) + 22.0);
138        h += 20.0;
139    }
140    if spark {
141        w = w.max(110.0);
142        h += SPARK_H;
143    }
144    NodeBox {
145        w: (w + 2.0 * BOX_PAD_X).clamp(BOX_MIN_W, BOX_MAX_W),
146        h,
147        lines,
148    }
149}
150
151/// The colours and class names of a drawing.
152#[derive(Clone, Debug)]
153pub struct GraphStyle {
154    /// Box and badge fill, and the halo behind edge labels.
155    pub card: Rgb,
156    /// Swimlane band tint.
157    pub band: Rgb,
158    /// Lane names and edge labels.
159    pub muted: Rgb,
160    /// Node labels.
161    pub heading: Rgb,
162    /// Node values and badge text.
163    pub ink: Rgb,
164    /// A variable's circle ([`NodeShape::Circle`]).
165    pub variable_fill: Rgb,
166    /// An observed variable's circle ([`NodeShape::FilledCircle`]) and a
167    /// delta node's square; their labels are drawn in `card`.
168    pub observed_fill: Rgb,
169    /// A plate's dashed outline and its label.
170    pub plate: Rgb,
171    /// Prefix of the layer classes (`<prefix>node`, `<prefix>edge`,
172    /// `<prefix>edge-label`, `<prefix>lane`, `<prefix>lane-label`,
173    /// `<prefix>node-label`, `<prefix>node-value`, `<prefix>node-badge`,
174    /// `<prefix>node-spark`, `<prefix>plate`, `<prefix>plate-label`; a
175    /// shaped node's mark also has `<prefix>node-<shape>`).
176    pub class_prefix: String,
177    /// A factor graph's math font: when set, the labels of shaped nodes
178    /// (variables, observations, equality nodes, glyph factors) are set in
179    /// this family, italic and regular weight — `θ`, `x₁`, `𝒩` read as
180    /// mathematics. `None` keeps the bold sans labels.
181    pub math_font: Option<String>,
182    /// A glyph factor's fill ([`NodeShape::Glyph`]); `None` is `card`.
183    pub glyph_fill: Option<Rgb>,
184    /// A glyph factor's glyph colour; `None` is `heading`.
185    pub glyph_ink: Option<Rgb>,
186}
187
188impl Default for GraphStyle {
189    fn default() -> Self {
190        GraphStyle {
191            card: (255, 255, 255),
192            band: (226, 228, 233),
193            muted: (107, 114, 128),
194            heading: (17, 24, 39),
195            ink: (31, 41, 55),
196            variable_fill: (229, 231, 235),
197            observed_fill: (75, 85, 99),
198            plate: (107, 114, 128),
199            class_prefix: "gg-graph-".to_string(),
200            math_font: None,
201            glyph_fill: None,
202            glyph_ink: None,
203        }
204    }
205}
206
207/// A node's mark. A factor graph (Forney style) draws factors as boxes,
208/// variables as circles (filled when observed), equality nodes as small
209/// squares, deterministic (delta) nodes as small filled squares, and
210/// constants as plain text.
211#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
212pub enum NodeShape {
213    /// A box with a label, value, badge and sparkline ([`node_box`]).
214    #[default]
215    Box,
216    Circle,
217    FilledCircle,
218    /// A small square, its label above it.
219    Square,
220    /// A small filled square, its label above it.
221    FilledSquare,
222    /// The label alone.
223    Text,
224    /// A small square box with a short glyph centred in it (a factor drawn
225    /// as `𝒩`, `Γ`, `Ber`, …): uniform, so a factor graph stays compact.
226    Glyph,
227    /// A small filled square at the end of an edge, its label beside it (to
228    /// the right): an observation in Forney style, where data enters.
229    Terminal,
230}
231
232impl NodeShape {
233    fn name(self) -> &'static str {
234        match self {
235            NodeShape::Box => "box",
236            NodeShape::Circle => "circle",
237            NodeShape::FilledCircle => "filled-circle",
238            NodeShape::Square => "square",
239            NodeShape::FilledSquare => "filled-square",
240            NodeShape::Text => "text",
241            NodeShape::Glyph => "glyph",
242            NodeShape::Terminal => "terminal",
243        }
244    }
245}
246
247/// How far from its end an edge label set near that end sits, at most (px).
248const LABEL_REACH: f64 = 22.0;
249/// A belief curve's size over its node (px).
250pub const BELIEF_W: f64 = 46.0;
251pub const BELIEF_H: f64 = 16.0;
252/// A small square's side (px).
253const SQUARE: f64 = 14.0;
254/// A terminal's side (px).
255const TERMINAL: f64 = 11.0;
256/// A glyph factor's side (px) and its glyph's size.
257const GLYPH_SIDE: f64 = 34.0;
258const GLYPH_PX: f64 = 15.0;
259
260/// The size a node of `shape` needs for `label` (a [`NodeShape::Box`] is
261/// [`node_box`] without a value, badge or sparkline). A circle fits its
262/// label on one line, at least 30 px across.
263pub fn node_size(shape: NodeShape, label: &str) -> NodeBox {
264    let one = || vec![label.to_string()];
265    match shape {
266        NodeShape::Box => node_box(label, None, None, false),
267        NodeShape::Circle | NodeShape::FilledCircle => {
268            let d = (text_w(label, LABEL_PX, true) + 14.0).max(30.0);
269            NodeBox {
270                w: d,
271                h: d,
272                lines: one(),
273            }
274        }
275        NodeShape::Square | NodeShape::FilledSquare => NodeBox {
276            w: SQUARE,
277            h: SQUARE,
278            lines: if label.is_empty() { Vec::new() } else { one() },
279        },
280        NodeShape::Terminal => NodeBox {
281            w: TERMINAL,
282            h: TERMINAL,
283            lines: if label.is_empty() { Vec::new() } else { one() },
284        },
285        NodeShape::Text => NodeBox {
286            w: text_w(label, LABEL_PX, false) + 8.0,
287            h: 20.0,
288            lines: one(),
289        },
290        NodeShape::Glyph => {
291            let side = (text_w(label, GLYPH_PX, true) + 14.0).max(GLYPH_SIDE);
292            NodeBox {
293                w: side,
294                h: GLYPH_SIDE,
295                lines: one(),
296            }
297        }
298    }
299}
300
301/// A plate: a dashed box around a collection of nodes (indices in the
302/// layout's order), labelled at its top left (`x_t`, `t = 1..T`).
303#[derive(Clone, Debug, Default)]
304pub struct Plate {
305    pub label: String,
306    pub nodes: Vec<usize>,
307}
308
309/// A `data-*` attribute: its name (without `data-`) and value; `None` leaves
310/// it off that mark.
311pub type DataAttr = (String, Option<String>);
312
313/// What a node's box shows, and its attributes. Its geometry comes from the
314/// layout ([`PlacedNode`]); its label lines from [`node_box`].
315#[derive(Clone, Debug, Default)]
316pub struct DrawNode {
317    /// The `data-of` group of everything drawn for the node.
318    pub id: String,
319    /// Its mark; anything but a box shows only the label.
320    pub shape: NodeShape,
321    /// The label, wrapped ([`NodeBox::lines`]).
322    pub lines: Vec<String>,
323    /// A value line under the label.
324    pub value: Option<String>,
325    /// A badge row: its text and its dot's (and outline's) colour.
326    pub badge: Option<(String, Rgb)>,
327    /// The box (or circle, square) outline.
328    pub stroke: Rgb,
329    /// A thin bar along the box's left edge; a filled mark (an observation,
330    /// a terminal) is filled with it instead.
331    pub accent: Option<Rgb>,
332    /// A sparkline (two values or more) along the bottom, and its colour.
333    pub spark: Option<(Vec<f64>, Rgb)>,
334    /// A belief curve over the node (a factor graph variable's density):
335    /// heights 0..=1 at evenly spaced points (three or more), and its colour.
336    pub belief: Option<(Vec<f64>, Rgb)>,
337    /// The prior behind the belief curve: heights on the same scale and
338    /// span as [`DrawNode::belief`], drawn as a faint dashed outline, and
339    /// its colour.
340    pub prior: Option<(Vec<f64>, Rgb)>,
341    pub tooltip: String,
342    /// `data-*` on the box (the hit target); every node lists the same
343    /// names, in the same order.
344    pub attrs: Vec<DataAttr>,
345}
346
347/// An edge's line pattern.
348#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
349pub enum EdgeLine {
350    #[default]
351    Solid,
352    Dashed,
353    /// Round dots (zero-length dashes with round caps).
354    Dots,
355}
356
357/// What an edge looks like, and its attributes. Its points come from the
358/// layout ([`GraphLayout::edges`]); the arrowhead is on its last point,
359/// unless `undirected`.
360#[derive(Clone, Debug, Default)]
361pub struct DrawEdge {
362    pub colour: Rgb,
363    /// Line width (px), see [`flow_width`].
364    pub width: f64,
365    pub line: EdgeLine,
366    /// Extra CSS classes on the path.
367    pub class: Option<String>,
368    pub tooltip: String,
369    /// A label (`\n` breaks lines) on the edge, clear of the boxes.
370    pub label: Option<String>,
371    /// Where along the edge the label goes (0 at its start, 1 at its end),
372    /// e.g. near a factor for an interface name; `None`: the middle, moved
373    /// along the edge until no box covers it.
374    pub label_at: Option<f64>,
375    /// No arrowhead (a factor graph's edges).
376    pub undirected: bool,
377    /// The label names a variable (Forney style: the edge is the variable):
378    /// set in [`GraphStyle::math_font`] when there is one, in the heading
379    /// colour.
380    pub label_math: bool,
381    /// `data-*` on the path; every edge lists the same names, in the same
382    /// order.
383    pub attrs: Vec<DataAttr>,
384    /// `data-*` on the label.
385    pub label_attrs: Vec<DataAttr>,
386}
387
388/// An edge's width (px) for what it carries, `value` of the graph's `max`:
389/// area-true (`sqrt`), 1.4 px to 7 px; 1.6 px without a value; dotted edges
390/// 3–6 px so their dots show. Rounded to 0.1 px.
391pub fn flow_width(value: Option<f64>, max: f64, line: EdgeLine) -> f64 {
392    let width = match value {
393        Some(v) if max > 0.0 => 1.4 + 5.6 * (v.max(0.0) / max).sqrt(),
394        _ => 1.6,
395    };
396    let width = match line {
397        EdgeLine::Dots => width.clamp(3.0, 6.0),
398        _ => width,
399    };
400    (width * 10.0).round() / 10.0
401}
402
403/// Columns built row by row, in px with y down.
404#[derive(Default)]
405struct Frame(Vec<(String, Vec<Value>)>);
406
407impl Frame {
408    fn col(&mut self, name: &str) -> &mut Vec<Value> {
409        let i = match self.0.iter().position(|(n, _)| n == name) {
410            Some(i) => i,
411            None => {
412                self.0.push((name.to_string(), Vec::new()));
413                self.0.len() - 1
414            }
415        };
416        &mut self.0[i].1
417    }
418    fn num(&mut self, name: &str, v: f64) -> &mut Self {
419        self.col(name).push(Value::Float(v));
420        self
421    }
422    fn txt(&mut self, name: &str, v: impl Into<String>) -> &mut Self {
423        self.col(name).push(Value::Str(v.into()));
424        self
425    }
426    fn opt(&mut self, name: &str, v: Option<String>) -> &mut Self {
427        self.col(name).push(v.map_or(Value::Na, Value::Str));
428        self
429    }
430    /// `attrs` as columns `a:<name>`.
431    fn attrs(&mut self, attrs: &[DataAttr]) -> &mut Self {
432        for (n, v) in attrs {
433            self.opt(&format!("a:{n}"), v.clone());
434        }
435        self
436    }
437    fn is_empty(&self) -> bool {
438        self.0.first().is_none_or(|(_, v)| v.is_empty())
439    }
440    /// `aes` plus a `data_attr` per `a:<name>` column, in column order.
441    fn attr_aes(&self, mut aes: Aes) -> Aes {
442        for (n, _) in &self.0 {
443            if let Some(name) = n.strip_prefix("a:") {
444                aes = aes.data_attr(name, n);
445            }
446        }
447        aes
448    }
449    /// The frame's columns, its pixel y (down) flipped to data y (up) on a
450    /// canvas `h` tall: `y` → `h - y`, and a rect's `y0`/`y1` swapped as
451    /// they flip so `y0` stays the low edge.
452    fn take(&mut self, h: f64) -> Vec<(String, Vec<Value>)> {
453        let flip = |v: Vec<Value>| -> Vec<Value> {
454            v.into_iter()
455                .map(|x| match x {
456                    Value::Float(y) => Value::Float(h - y),
457                    other => other,
458                })
459                .collect()
460        };
461        std::mem::take(&mut self.0)
462            .into_iter()
463            .map(|(n, v)| match n.as_str() {
464                "y" => (n, flip(v)),
465                "y0" => ("y1".to_string(), flip(v)),
466                "y1" => ("y0".to_string(), flip(v)),
467                _ => (n, v),
468            })
469            .collect()
470    }
471}
472
473/// Frames keyed by a colour a geom only takes as a fixed parameter (a
474/// rect's stroke), in first-seen order: one layer per colour.
475fn by_colour(v: &mut Vec<(Rgb, Frame)>, c: Rgb) -> &mut Frame {
476    let i = match v.iter().position(|(k, _)| *k == c) {
477        Some(i) => i,
478        None => {
479            v.push((c, Frame::default()));
480            v.len() - 1
481        }
482    };
483    &mut v[i].1
484}
485
486fn hex(c: Rgb) -> String {
487    format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
488}
489
490/// The point a fraction `t` (0..1) of the way along a polyline.
491fn point_at(pts: &[(f64, f64)], t: f64) -> (f64, f64) {
492    let seg = |i: usize| {
493        let (a, b) = (pts[i], pts[i + 1]);
494        ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
495    };
496    let total: f64 = (0..pts.len().saturating_sub(1)).map(seg).sum();
497    let mut left = total * t;
498    for i in 0..pts.len().saturating_sub(1) {
499        let l = seg(i);
500        if l >= left && l > 0.0 {
501            let t = left / l;
502            let (a, b) = (pts[i], pts[i + 1]);
503            return (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
504        }
505        left -= l;
506    }
507    pts.first().copied().unwrap_or((0.0, 0.0))
508}
509
510/// Where an edge's label goes: the midpoint of the edge, else the nearest
511/// point along it where the label's box (11 px lines drawn around `y - 4`)
512/// touches no node box — so a node doesn't cover it.
513fn edge_label_at(pts: &[(f64, f64)], label: &str, nodes: &[PlacedNode]) -> (f64, f64) {
514    let lines = label.split('\n').count();
515    let hw = edge_label_width(label) / 2.0 + 3.0;
516    let hh = lines as f64 * 6.6 + 3.0;
517    let clear = |(x, y): (f64, f64)| {
518        let cy = y - 4.0 - 0.36 * SMALL_PX;
519        nodes
520            .iter()
521            .all(|n| (x - n.cx).abs() >= hw + n.w / 2.0 || (cy - n.cy).abs() >= hh + n.h / 2.0)
522    };
523    let mid = point_at(pts, 0.5);
524    [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74, 0.18, 0.82]
525        .into_iter()
526        .map(|t| point_at(pts, t))
527        .find(|&p| clear(p))
528        .unwrap_or(mid)
529}
530
531/// Text is centred on its y (`dominant-baseline="middle"`); the layout
532/// places lines by their baseline. A cap-height-ish shift between the two.
533fn mid_of_baseline(baseline: f64, px: f64) -> f64 {
534    baseline - 0.36 * px
535}
536
537/// Draw a laid-out graph on a `layout.w` × `layout.h` px canvas: `lanes`
538/// names the layout's bands, `plates` group nodes, `nodes` and `edges` are
539/// in the layout's order.
540/// `theme` is the base (a void theme; the legend is turned off). Render the
541/// result with e.g. `render_svg_native_at(0.0, 0.0, w, h)` at the canvas
542/// size rounded up.
543pub fn draw(
544    layout: &GraphLayout,
545    lanes: &[String],
546    plates: &[Plate],
547    nodes: &[DrawNode],
548    edges: &[DrawEdge],
549    style: &GraphStyle,
550    mut theme: Theme,
551) -> GGPlot {
552    let s = style;
553    let class = |name: &str| format!("{}{name}", s.class_prefix);
554    let (w, h) = (layout.w.ceil().max(1.0), layout.h.ceil().max(1.0));
555    theme.legend_position = crate::theme::LegendPosition::None;
556    let mut plot = GGPlot::new(vec![
557        ("x".to_string(), vec![Value::Float(0.0), Value::Float(w)]),
558        ("y".to_string(), vec![Value::Float(0.0), Value::Float(h)]),
559    ])
560    .theme(theme)
561    // the canvas is the view (a zoom, so a mark reaching past it is clipped
562    // rather than dropped); `Frame::take` flips the layout's y-down pixels
563    .scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
564    .scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
565    .coord_cartesian_zoom(Some((0.0, w)), Some((0.0, h)))
566    .scale_color_identity()
567    .scale_fill_identity()
568    .scale_linewidth(
569        ScaleLinewidthContinuous::new()
570            .with_limits(0.0, 16.0)
571            .with_range(0.0, 16.0),
572    )
573    .scale_linetype_manual(vec![
574        ("solid", Linetype::Solid),
575        ("dashed", Linetype::Custom(vec![(6.0, 4.0)])),
576        // round caps on a zero-length dash: moving dots
577        ("dots", Linetype::Custom(vec![(0.0, 10.0)])),
578    ]);
579    let rect_aes = || Aes::new().xmin("x0").xmax("x1").ymin("y0").ymax("y1");
580    let inert = [("pointer-events", "none")];
581
582    // swimlanes (under everything): a tinted band per lane, its name on top
583    let (mut even, mut odd, mut names) = (Frame::default(), Frame::default(), Frame::default());
584    for &(l, x0, y0, x1, y1) in &layout.bands {
585        let name = lanes.get(l).cloned().unwrap_or_default();
586        let f = if l % 2 == 0 { &mut even } else { &mut odd };
587        f.num("x0", x0).num("x1", x1).num("y0", y0).num("y1", y1);
588        f.txt("lane", name.clone());
589        names
590            .num("x", x0 + 8.0)
591            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
592        names.txt("label", name);
593    }
594    for (mut f, alpha) in [(even, 0.35), (odd, 0.18)] {
595        if f.is_empty() {
596            continue;
597        }
598        plot = plot
599            .geom_rect_with(
600                GeomRect {
601                    fill: s.band,
602                    alpha,
603                    line_width: 0.0,
604                    ..Default::default()
605                }
606                .with_radius(6.0),
607            )
608            .layer_data(f.take(h))
609            .layer_aes(rect_aes().data_attr("lane", "lane"))
610            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane"))]);
611    }
612    if !names.is_empty() {
613        plot = plot
614            .geom_text_with(GeomText {
615                size: SMALL_PX,
616                color: s.muted,
617                hjust: 0.0,
618                fontface: FontFace::Bold,
619                ..Default::default()
620            })
621            .layer_data(names.take(h))
622            .layer_aes(Aes::new().x("x").y("y").label("label"))
623            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane-label"))]);
624    }
625
626    // plates (under the edges): a dashed box around each collection
627    let (mut pf, mut pl) = (Frame::default(), Frame::default());
628    for p in plates {
629        let members: Vec<&PlacedNode> = p
630            .nodes
631            .iter()
632            .filter_map(|&i| layout.nodes.get(i))
633            .collect();
634        if members.is_empty() {
635            continue;
636        }
637        let pad = 8.0;
638        let x0 = members
639            .iter()
640            .map(|n| n.cx - n.w / 2.0)
641            .fold(f64::INFINITY, f64::min)
642            - pad;
643        let x1 = members
644            .iter()
645            .map(|n| n.cx + n.w / 2.0)
646            .fold(f64::NEG_INFINITY, f64::max)
647            + pad;
648        let y0 = members
649            .iter()
650            .map(|n| n.cy - n.h / 2.0)
651            .fold(f64::INFINITY, f64::min)
652            - pad
653            - 14.0;
654        let y1 = members
655            .iter()
656            .map(|n| n.cy + n.h / 2.0)
657            .fold(f64::NEG_INFINITY, f64::max)
658            + pad;
659        for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] {
660            pf.num("x", x).num("y", y).txt("lt", "dashed");
661            pf.txt("g", p.label.clone()).txt("plate", p.label.clone());
662        }
663        pl.num("x", x0 + 6.0)
664            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
665        pl.txt("label", p.label.clone());
666    }
667    if !pf.is_empty() {
668        plot = plot
669            .geom_path_with(GeomPath::default().color(s.plate).linewidth(1.0))
670            .layer_data(pf.take(h))
671            .layer_aes(
672                Aes::new()
673                    .x("x")
674                    .y("y")
675                    .group("g")
676                    .linetype("lt")
677                    .data_attr("plate", "plate"),
678            )
679            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate"))]);
680        plot = plot
681            .geom_text_with(GeomText {
682                size: SMALL_PX,
683                color: s.plate,
684                hjust: 0.0,
685                ..Default::default()
686            })
687            .layer_data(pl.take(h))
688            .layer_aes(Aes::new().x("x").y("y").label("label"))
689            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate-label"))]);
690    }
691
692    // edges (under the nodes): one path per edge, arrowed ones first
693    let (mut ef, mut uf, mut lf) = (Frame::default(), Frame::default(), Frame::default());
694    // a variable's name on its edge (Forney style), in the math font
695    let mut lmf = Frame::default();
696    for (k, e) in edges.iter().enumerate() {
697        let Some(route) = layout.edges.get(k) else {
698            continue;
699        };
700        let mut pts = route.clone();
701        if pts.len() < 2 {
702            continue;
703        }
704        // the arrow's tip is on the path's last point and its head is
705        // stroked as wide as the line (its mitred tip reaching about one
706        // line width further): end the path one width short of the box so
707        // the tip lands on its edge.
708        if !e.undirected {
709            let n = pts.len();
710            let ((fx, fy), (tx, ty)) = (pts[n - 2], pts[n - 1]);
711            let len = ((tx - fx).powi(2) + (ty - fy).powi(2)).sqrt().max(1e-6);
712            let pull = e.width.min(len / 2.0);
713            pts[n - 1] = (tx - (tx - fx) / len * pull, ty - (ty - fy) / len * pull);
714        }
715        let ef = if e.undirected { &mut uf } else { &mut ef };
716        let lt = match e.line {
717            EdgeLine::Solid => "solid",
718            EdgeLine::Dashed => "dashed",
719            EdgeLine::Dots => "dots",
720        };
721        for &(x, y) in &pts {
722            ef.num("x", x).num("y", y).txt("g", format!("e{k:04}"));
723            ef.txt("col", hex(e.colour))
724                .num("lw", e.width)
725                .txt("lt", lt);
726            ef.opt("cls", e.class.clone()).txt("tip", e.tooltip.clone());
727            ef.attrs(&e.attrs);
728        }
729        // a bus-routed edge's label is left to its tooltip: on the shared
730        // lane or at a shared entry it would only clutter
731        let routed = layout.routed.get(k).copied().unwrap_or(false);
732        if let Some(l) = e.label.as_ref().filter(|_| !routed) {
733            let (mx, my) = match e.label_at {
734                // near an end: at most LABEL_REACH px from it
735                Some(t) => {
736                    let t = t.clamp(0.0, 1.0);
737                    let len: f64 = route
738                        .windows(2)
739                        .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt())
740                        .sum();
741                    let reach = |f: f64| {
742                        if len > 0.0 {
743                            (len * f).min(LABEL_REACH) / len
744                        } else {
745                            f
746                        }
747                    };
748                    point_at(
749                        route,
750                        if t >= 0.5 {
751                            1.0 - reach(1.0 - t)
752                        } else {
753                            reach(t)
754                        },
755                    )
756                }
757                None => edge_label_at(route, l, &layout.nodes),
758            };
759            let f = if e.label_math && s.math_font.is_some() {
760                &mut lmf
761            } else {
762                &mut lf
763            };
764            f.num("x", mx).num("y", mid_of_baseline(my - 4.0, SMALL_PX));
765            f.txt("label", l.clone());
766            f.attrs(&e.label_attrs);
767        }
768    }
769    for (mut f, arrowed) in [(ef, true), (uf, false)] {
770        if f.is_empty() {
771            continue;
772        }
773        let aes = f.attr_aes(
774            Aes::new()
775                .x("x")
776                .y("y")
777                .group("g")
778                .color("col")
779                .linewidth("lw")
780                .linetype("lt")
781                .class("cls")
782                .tooltip("tip"),
783        );
784        let mut geom = GeomPath::default().lineend(LineEnd::Round);
785        if arrowed {
786            // a 7 px + width head, ~29° half-angle
787            geom = geom.arrow(
788                arrow()
789                    .closed()
790                    .angle(29.0)
791                    .length(ARROW + 1.0)
792                    .length_per_linewidth(1.2),
793            );
794        }
795        plot = plot
796            .geom_path_with(geom)
797            .layer_data(f.take(h))
798            .layer_aes(aes)
799            .layer_svg_attr("class", class("edge"));
800    }
801    if !lmf.is_empty() {
802        let aes = lmf.attr_aes(Aes::new().x("x").y("y").label("label"));
803        plot = plot
804            .geom_text_with(
805                GeomText {
806                    size: LABEL_PX + 1.0,
807                    color: s.heading,
808                    fontface: FontFace::Italic,
809                    fontfamily: s.math_font.clone().unwrap_or_default(),
810                    ..Default::default()
811                }
812                .bg_colour(s.card)
813                .bg_r(2.0),
814            )
815            .layer_data(lmf.take(h))
816            .layer_aes(aes)
817            .layer_svg_attrs(inert)
818            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
819    }
820    if !lf.is_empty() {
821        // text directly on the line, a card-coloured halo keeping it legible
822        let aes = lf.attr_aes(Aes::new().x("x").y("y").label("label"));
823        plot = plot
824            .geom_text_with(
825                GeomText {
826                    size: SMALL_PX,
827                    color: s.muted,
828                    ..Default::default()
829                }
830                .bg_colour(s.card)
831                .bg_r(2.0),
832            )
833            .layer_data(lf.take(h))
834            .layer_aes(aes)
835            .layer_svg_attrs(inert)
836            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
837    }
838
839    // nodes in reading order: the box (the hit target, outside any `data-of`
840    // group), then what it shows, grouped per node
841    let mut order: Vec<usize> = (0..nodes.len().min(layout.nodes.len())).collect();
842    order.sort_by_key(|&i| (layout.nodes[i].order, i));
843    let mut boxes: Vec<(Rgb, Frame)> = Vec::new();
844    let mut beliefs = Frame::default();
845    let mut priors = Frame::default();
846    // shaped nodes, a layer per (shape, corner radius, outline)
847    let mut shaped: Vec<((NodeShape, u64, Rgb), Frame)> = Vec::new();
848    let (mut inside, mut inverse, mut above, mut glyphs, mut texts, mut beside) = (
849        Frame::default(),
850        Frame::default(),
851        Frame::default(),
852        Frame::default(),
853        Frame::default(),
854        Frame::default(),
855    );
856    let mut badges: Vec<(Rgb, Frame)> = Vec::new();
857    let (mut accent, mut lines, mut values) =
858        (Frame::default(), Frame::default(), Frame::default());
859    let (mut dots, mut btext, mut spark, mut ends) = (
860        Frame::default(),
861        Frame::default(),
862        Frame::default(),
863        Frame::default(),
864    );
865    for v in order {
866        let nd = &nodes[v];
867        let pn = &layout.nodes[v];
868        let id = nd.id.clone();
869        let (x, y) = (pn.cx - pn.w / 2.0, pn.cy - pn.h / 2.0);
870        // the belief curve sits over the node (over a square's label)
871        let squared = matches!(nd.shape, NodeShape::Square | NodeShape::FilledSquare);
872        let base = y - if squared { 17.0 } else { 3.0 };
873        let x0 = pn.cx - BELIEF_W / 2.0;
874        let curve = |hs: &[f64]| -> Vec<(f64, f64)> {
875            let last = (hs.len() - 1) as f64;
876            hs.iter()
877                .enumerate()
878                .map(|(i, &h)| {
879                    (
880                        x0 + BELIEF_W * i as f64 / last,
881                        base - h.clamp(0.0, 1.0) * BELIEF_H,
882                    )
883                })
884                .collect()
885        };
886        // the prior: a faint outline behind the belief
887        if let Some((hs, col)) = nd.prior.as_ref().filter(|(h, _)| h.len() >= 3) {
888            for (px, py) in curve(hs) {
889                priors.num("x", px).num("y", py).txt("g", id.clone());
890                priors.txt("col", hex(*col)).txt("lt", "dashed");
891                priors.txt("of", id.clone());
892            }
893        }
894        if let Some((hs, col)) = nd.belief.as_ref().filter(|(h, _)| h.len() >= 3) {
895            let mut pts = curve(hs);
896            pts.push((x0 + BELIEF_W, base));
897            pts.push((x0, base));
898            for (px, py) in pts {
899                beliefs.num("x", px).num("y", py).txt("g", id.clone());
900                beliefs.txt("fill", hex(*col)).txt("of", id.clone());
901            }
902        }
903        if nd.shape != NodeShape::Box {
904            let r = match nd.shape {
905                NodeShape::Circle | NodeShape::FilledCircle => pn.w.min(pn.h) / 2.0,
906                NodeShape::Square | NodeShape::FilledSquare | NodeShape::Terminal => 1.5,
907                NodeShape::Glyph => 4.0,
908                _ => 0.0,
909            };
910            let (fill, stroke) = match nd.shape {
911                NodeShape::Circle => (s.variable_fill, nd.stroke),
912                // a filled mark takes the node's accent (a status: an
913                // observation the model did not expect) over the observed fill
914                NodeShape::FilledCircle | NodeShape::FilledSquare | NodeShape::Terminal => {
915                    let c = nd.accent.unwrap_or(s.observed_fill);
916                    (c, c)
917                }
918                NodeShape::Square => (s.card, nd.stroke),
919                NodeShape::Glyph => (s.glyph_fill.unwrap_or(s.card), nd.stroke),
920                _ => (s.card, s.card),
921            };
922            let key = (nd.shape, r.to_bits(), stroke);
923            let i = match shaped.iter().position(|(k, _)| *k == key) {
924                Some(i) => i,
925                None => {
926                    shaped.push((key, Frame::default()));
927                    shaped.len() - 1
928                }
929            };
930            let f = &mut shaped[i].1;
931            f.num("x0", x)
932                .num("x1", x + pn.w)
933                .num("y0", y)
934                .num("y1", y + pn.h);
935            f.txt("fill", hex(fill));
936            f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
937            let label = nd.lines.join(" ");
938            if label.is_empty() {
939                continue;
940            }
941            let target = match nd.shape {
942                NodeShape::Glyph => &mut glyphs,
943                NodeShape::FilledCircle => &mut inverse,
944                NodeShape::Square | NodeShape::FilledSquare => &mut above,
945                // a constant is a number: upright, never the math italic
946                NodeShape::Text => &mut texts,
947                NodeShape::Terminal => &mut beside,
948                _ => &mut inside,
949            };
950            let ly = match nd.shape {
951                NodeShape::Square | NodeShape::FilledSquare => y - 4.0 - 0.36 * SMALL_PX,
952                _ => pn.cy,
953            };
954            // a terminal's label starts just right of it
955            let lx = match nd.shape {
956                NodeShape::Terminal => x + pn.w + 5.0,
957                _ => pn.cx,
958            };
959            target.num("x", lx).num("y", ly);
960            target.txt("label", label).txt("of", id.clone());
961            continue;
962        }
963        let f = by_colour(&mut boxes, nd.stroke);
964        f.num("x0", x)
965            .num("x1", x + pn.w)
966            .num("y0", y)
967            .num("y1", y + pn.h);
968        f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
969
970        if let Some(a) = nd.accent {
971            accent.num("x0", x + 1.5).num("x1", x + 4.5);
972            accent
973                .num("y0", y + 6.0)
974                .num("y1", y + 6.0 + (pn.h - 12.0).max(4.0));
975            accent.txt("fill", hex(a)).txt("of", id.clone());
976        }
977        let mut base = y + BOX_PAD_Y + 12.0;
978        for line in &nd.lines {
979            lines
980                .num("x", pn.cx)
981                .num("y", mid_of_baseline(base, LABEL_PX));
982            lines.txt("label", line.clone()).txt("of", id.clone());
983            base += LINE_H;
984        }
985        if let Some(fv) = &nd.value {
986            values
987                .num("x", pn.cx)
988                .num("y", mid_of_baseline(base, VALUE_PX));
989            values.txt("label", fv.clone()).txt("of", id.clone());
990            base += LINE_H;
991        }
992        if let Some((b, dot)) = &nd.badge {
993            let bw = text_w(b, BADGE_PX, false) + 20.0;
994            let (bx, by) = (pn.cx - bw / 2.0, base - 9.0);
995            let f = by_colour(&mut badges, *dot);
996            f.num("x0", bx)
997                .num("x1", bx + bw)
998                .num("y0", by)
999                .num("y1", by + 16.0);
1000            f.txt("of", id.clone());
1001            dots.num("x", bx + 9.0).num("y", by + 8.0);
1002            dots.txt("col", hex(*dot)).txt("of", id.clone());
1003            btext.num("x", bx + 15.0).num("y", by + 8.0);
1004            btext.txt("label", b.clone()).txt("of", id.clone());
1005            base += 20.0;
1006        }
1007        // a mini trend along the bottom of the box
1008        if let Some((values, colour)) = nd.spark.as_ref().filter(|(v, _)| v.len() >= 2) {
1009            let (lo, hi) = values
1010                .iter()
1011                .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
1012                    (a.min(v), b.max(v))
1013                });
1014            let rng = if hi > lo { hi - lo } else { 1.0 };
1015            let (sx0, sw) = (x + BOX_PAD_X, pn.w - 2.0 * BOX_PAD_X);
1016            let (top, sh) = (base - 8.0, SPARK_H - 8.0);
1017            let last = values.len() - 1;
1018            let col = hex(*colour);
1019            for (i, &sv) in values.iter().enumerate() {
1020                let (px, py) = (
1021                    sx0 + sw * i as f64 / last as f64,
1022                    top + sh - (sv - lo) / rng * sh,
1023                );
1024                spark.num("x", px).num("y", py).txt("g", id.clone());
1025                spark.txt("col", col.clone()).txt("of", id.clone());
1026                if i == last {
1027                    ends.num("x", px).num("y", py);
1028                    ends.txt("col", col.clone()).txt("of", id.clone());
1029                }
1030            }
1031        }
1032    }
1033    for (stroke, mut f) in boxes {
1034        let aes = f.attr_aes(rect_aes().tooltip("tip"));
1035        plot = plot
1036            .geom_rect_with(
1037                GeomRect {
1038                    fill: s.card,
1039                    color: stroke,
1040                    alpha: 1.0,
1041                    line_width: 1.2,
1042                    ..Default::default()
1043                }
1044                .with_radius(8.0),
1045            )
1046            .layer_data(f.take(h))
1047            .layer_aes(aes)
1048            .layer_svg_attr("class", class("node"));
1049    }
1050    for ((shape, r, stroke), mut f) in shaped {
1051        let aes = f.attr_aes(rect_aes().fill("fill").tooltip("tip"));
1052        let cls = format!(
1053            "{} {}",
1054            class("node"),
1055            class(&format!("node-{}", shape.name()))
1056        );
1057        plot = plot
1058            .geom_rect_with(
1059                GeomRect {
1060                    color: stroke,
1061                    alpha: 1.0,
1062                    line_width: if shape == NodeShape::Text { 0.0 } else { 1.2 },
1063                    ..Default::default()
1064                }
1065                .with_radius(f64::from_bits(r)),
1066            )
1067            .layer_data(f.take(h))
1068            .layer_aes(aes)
1069            .layer_svg_attr("class", cls);
1070    }
1071    if !priors.is_empty() {
1072        plot = plot
1073            .geom_path_with(GeomPath {
1074                alpha: 0.7,
1075                ..GeomPath::default().linewidth(1.0)
1076            })
1077            .layer_data(priors.take(h))
1078            .layer_aes(
1079                Aes::new()
1080                    .x("x")
1081                    .y("y")
1082                    .group("g")
1083                    .color("col")
1084                    .linetype("lt")
1085                    .group_wrap("of", "of"),
1086            )
1087            .decorative()
1088            .layer_svg_attrs(inert)
1089            .layer_svg_attr("class", class("node-prior"));
1090    }
1091    if !beliefs.is_empty() {
1092        plot = plot
1093            .geom_polygon_with(GeomPolygon {
1094                alpha: 0.45,
1095                line_width: 0.0,
1096                ..Default::default()
1097            })
1098            .layer_data(beliefs.take(h))
1099            .layer_aes(
1100                Aes::new()
1101                    .x("x")
1102                    .y("y")
1103                    .group("g")
1104                    .fill("fill")
1105                    .group_wrap("of", "of"),
1106            )
1107            .decorative()
1108            .layer_svg_attrs(inert)
1109            .layer_svg_attr("class", class("node-belief"));
1110    }
1111    // everything below: dims / lights with its node (`data-of`), inert
1112    let of = |a: Aes| a.group_wrap("of", "of");
1113    if !accent.is_empty() {
1114        plot = plot
1115            .geom_rect_with(
1116                GeomRect {
1117                    alpha: 1.0,
1118                    line_width: 0.0,
1119                    ..Default::default()
1120                }
1121                .with_radius(1.5),
1122            )
1123            .layer_data(accent.take(h))
1124            .layer_aes(of(rect_aes().fill("fill")))
1125            .decorative()
1126            .layer_svg_attrs(inert);
1127    }
1128    for (mut f, size, colour, cls, math, hjust) in [
1129        (lines, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1130        (values, VALUE_PX, s.ink, class("node-value"), false, 0.5),
1131        (inside, LABEL_PX, s.heading, class("node-label"), true, 0.5),
1132        (texts, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1133        (inverse, LABEL_PX, s.card, class("node-label"), true, 0.5),
1134        (above, SMALL_PX, s.muted, class("node-label"), true, 0.5),
1135        (beside, LABEL_PX, s.heading, class("node-label"), true, 0.0),
1136        (
1137            glyphs,
1138            GLYPH_PX,
1139            s.glyph_ink.unwrap_or(s.heading),
1140            class("node-label"),
1141            true,
1142            0.5,
1143        ),
1144    ] {
1145        if f.is_empty() {
1146            continue;
1147        }
1148        // a factor graph's labels as mathematics: the math font, italic
1149        let (fontfamily, fontface, size) = match s.math_font.as_ref().filter(|_| math) {
1150            Some(family) => (family.clone(), FontFace::Italic, size + 2.0),
1151            None => (String::new(), FontFace::Bold, size),
1152        };
1153        plot = plot
1154            .geom_text_with(GeomText {
1155                size,
1156                color: colour,
1157                fontface,
1158                fontfamily,
1159                hjust,
1160                ..Default::default()
1161            })
1162            .layer_data(f.take(h))
1163            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1164            .layer_svg_attrs(inert)
1165            .layer_svg_attrs([("aria-hidden", "true"), ("class", cls.as_str())]);
1166    }
1167    for (dot, mut f) in badges {
1168        plot = plot
1169            .geom_rect_with(
1170                GeomRect {
1171                    fill: s.card,
1172                    color: dot,
1173                    alpha: 0.0,
1174                    line_width: 1.0,
1175                    ..Default::default()
1176                }
1177                .with_radius(8.0),
1178            )
1179            .layer_data(f.take(h))
1180            .layer_aes(of(rect_aes()))
1181            .decorative()
1182            .layer_svg_attrs(inert);
1183    }
1184    for (mut f, size) in [(dots, 3.0), (ends, 2.2)] {
1185        if f.is_empty() {
1186            continue;
1187        }
1188        plot = plot
1189            .geom_point_with(GeomPoint {
1190                size,
1191                ..Default::default()
1192            })
1193            .layer_data(f.take(h))
1194            .layer_aes(of(Aes::new().x("x").y("y").color("col")))
1195            .decorative()
1196            .layer_svg_attrs(inert);
1197    }
1198    if !btext.is_empty() {
1199        plot = plot
1200            .geom_text_with(GeomText {
1201                size: BADGE_PX,
1202                color: s.ink,
1203                hjust: 0.0,
1204                ..Default::default()
1205            })
1206            .layer_data(btext.take(h))
1207            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1208            .layer_svg_attrs(inert)
1209            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-badge"))]);
1210    }
1211    if !spark.is_empty() {
1212        plot = plot
1213            .geom_path_with(GeomPath::default().linewidth(1.4))
1214            .layer_data(spark.take(h))
1215            .layer_aes(of(Aes::new().x("x").y("y").group("g").color("col")))
1216            .decorative()
1217            .layer_svg_attrs(inert)
1218            .layer_svg_attr("class", class("node-spark"));
1219    }
1220    plot
1221}
1222
1223#[cfg(test)]
1224mod tests {
1225    use super::*;
1226    use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
1227
1228    #[test]
1229    fn wraps_long_labels_in_three_lines() {
1230        let l = wrap(
1231            "Recommend replenishment orders for every store and every week of the coming year",
1232            152.0,
1233        );
1234        assert_eq!(l.len(), 3);
1235        assert!(l[2].ends_with('…'));
1236        assert_eq!(wrap("Ingest", 152.0), ["Ingest"]);
1237    }
1238
1239    /// No ellipsis while the label fits; breaks at word boundaries and
1240    /// after `/` / `-`, never mid-word when there is a separator.
1241    #[test]
1242    fn wraps_at_word_boundaries() {
1243        let max = BOX_MAX_W - 2.0 * BOX_PAD_X;
1244        for label in [
1245            "duckdb/community-extensions (descriptions)",
1246            "Locked DuckDB server (anofox-visualization)",
1247            "Parquet snapshot (downloads, extensions)",
1248            "fetch.sh: download, file by ISO week, merge",
1249        ] {
1250            let l = wrap(label, max);
1251            assert!(l.len() <= MAX_LINES, "{l:?}");
1252            assert!(!l.iter().any(|x| x.contains('…')), "{label}: {l:?}");
1253            // every line ends at a space or after a separator
1254            let joined: String = l.concat();
1255            assert_eq!(joined.replace(' ', ""), label.replace(' ', ""), "{l:?}");
1256            for w in l.windows(2) {
1257                let end = w[0].chars().last().unwrap();
1258                let next = w[1].chars().next().unwrap();
1259                let at_space = label.contains(&format!(
1260                    "{} {}",
1261                    w[0].split(' ').next_back().unwrap(),
1262                    w[1].split(' ').next().unwrap()
1263                ));
1264                assert!(
1265                    at_space || matches!(end, '/' | '-' | '_' | '.' | ','),
1266                    "{l:?} breaks at {end}{next}"
1267                );
1268            }
1269        }
1270        assert_eq!(
1271            wrap("duckdb/community-extensions (descriptions)", max),
1272            ["duckdb/community-", "extensions", "(descriptions)"]
1273        );
1274    }
1275
1276    #[test]
1277    fn node_box_grows_with_its_contents() {
1278        let plain = node_box("Ingest", None, None, false);
1279        assert_eq!((plain.w, plain.h), (BOX_MIN_W, 2.0 * BOX_PAD_Y + LINE_H));
1280        let full = node_box("Ingest", Some("1,240"), Some("late"), true);
1281        assert_eq!(full.h, plain.h + LINE_H + 20.0 + SPARK_H);
1282        assert!(full.w >= 110.0 + 2.0 * BOX_PAD_X);
1283        let long = node_box(&"word ".repeat(40), None, None, false);
1284        assert!(long.w <= BOX_MAX_W && long.lines.len() == MAX_LINES);
1285    }
1286
1287    /// An edge label a node box would cover moves along the edge.
1288    #[test]
1289    fn edge_label_keeps_clear_of_nodes() {
1290        let node = |cx: f64, w: f64| PlacedNode {
1291            cx,
1292            cy: 0.0,
1293            w,
1294            h: 40.0,
1295            layer: 0,
1296            order: 0,
1297        };
1298        let pts = [(0.0, 0.0), (300.0, 0.0)];
1299        // nothing in the way: the midpoint
1300        assert_eq!(edge_label_at(&pts, "spikes flagged", &[]), (150.0, 0.0));
1301        // a box over the middle: somewhere else along the edge, clear of it
1302        let nodes = [node(150.0, 60.0)];
1303        let (x, _) = edge_label_at(&pts, "spikes flagged", &nodes);
1304        let hw = edge_label_width("spikes flagged") / 2.0 + 3.0;
1305        assert!((x - 150.0).abs() >= hw + 30.0, "{x}");
1306        assert_eq!(point_at(&pts, 0.25), (75.0, 0.0));
1307    }
1308
1309    #[test]
1310    fn flow_width_is_area_true_and_rounded() {
1311        assert_eq!(flow_width(None, 10.0, EdgeLine::Solid), 1.6);
1312        assert_eq!(flow_width(Some(10.0), 10.0, EdgeLine::Solid), 7.0);
1313        assert_eq!(flow_width(Some(2.5), 10.0, EdgeLine::Solid), 4.2);
1314        assert_eq!(flow_width(None, 10.0, EdgeLine::Dots), 3.0);
1315    }
1316
1317    /// Two lanes, three boxes, a labelled edge: the marks carry the
1318    /// caller's attributes and classes, a node's contents sit in its
1319    /// `data-of` group, and the box itself (the hit target) stays outside.
1320    #[test]
1321    fn draws_marks_with_attributes_and_groups() {
1322        let labels = ["Ingest", "Model", "Publish"];
1323        let boxes: Vec<NodeBox> = labels
1324            .iter()
1325            .enumerate()
1326            .map(|(i, l)| node_box(l, (i == 1).then_some("42"), None, i == 2))
1327            .collect();
1328        let gnodes: Vec<GraphNode> = boxes
1329            .iter()
1330            .enumerate()
1331            .map(|(i, b)| GraphNode {
1332                w: b.w,
1333                h: b.h,
1334                lane: Some(i % 2),
1335                ..Default::default()
1336            })
1337            .collect();
1338        let gedges = [
1339            GraphEdge {
1340                from: 0,
1341                to: 1,
1342                label_w: Some(edge_label_width("rows")),
1343            },
1344            GraphEdge {
1345                from: 1,
1346                to: 2,
1347                label_w: None,
1348            },
1349        ];
1350        let params = LayeredParams {
1351            lanes: 2,
1352            ..Default::default()
1353        };
1354        let l = layered(&gnodes, &gedges, &params);
1355        let nodes: Vec<DrawNode> = labels
1356            .iter()
1357            .zip(&boxes)
1358            .enumerate()
1359            .map(|(i, (id, b))| DrawNode {
1360                id: id.to_string(),
1361                lines: b.lines.clone(),
1362                value: (i == 1).then(|| "42".to_string()),
1363                stroke: (90, 90, 90),
1364                accent: (i == 0).then_some((200, 0, 0)),
1365                spark: (i == 2).then(|| (vec![1.0, 3.0, 2.0], (0, 0, 200))),
1366                tooltip: format!("{id}!"),
1367                attrs: vec![
1368                    ("node".to_string(), Some(id.to_string())),
1369                    ("value".to_string(), (i == 1).then(|| "42".to_string())),
1370                ],
1371                ..Default::default()
1372            })
1373            .collect();
1374        let edges: Vec<DrawEdge> = [(0, 1), (1, 2)]
1375            .iter()
1376            .map(|&(a, b)| DrawEdge {
1377                colour: (100, 100, 100),
1378                width: flow_width(None, 0.0, EdgeLine::Solid),
1379                line: if a == 0 {
1380                    EdgeLine::Solid
1381                } else {
1382                    EdgeLine::Dashed
1383                },
1384                class: (a == 1).then(|| "flowing".to_string()),
1385                tooltip: format!("{} → {}", labels[a], labels[b]),
1386                label: (a == 0).then(|| "rows".to_string()),
1387                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
1388                label_attrs: vec![("from".to_string(), Some(labels[a].to_string()))],
1389                ..Default::default()
1390            })
1391            .collect();
1392        let lanes = ["Left".to_string(), "Right".to_string()];
1393        let svg = draw(
1394            &l,
1395            &lanes,
1396            &[],
1397            &nodes,
1398            &edges,
1399            &GraphStyle::default(),
1400            crate::theme::presets::theme_void(),
1401        )
1402        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1403        .unwrap();
1404        // start tags, each with whether it sits inside a `data-of` group
1405        let mut tags: Vec<(&str, bool)> = Vec::new();
1406        let mut stack: Vec<bool> = Vec::new();
1407        for part in svg.split('<').skip(1) {
1408            let tag = &part[..part.find('>').unwrap()];
1409            if tag.starts_with('/') {
1410                stack.pop();
1411                continue;
1412            }
1413            let inside = stack.iter().any(|&g| g);
1414            tags.push((tag, inside));
1415            if !tag.ends_with('/') {
1416                stack.push(tag.contains("data-of="));
1417            }
1418        }
1419        let attr = |tag: &str, name: &str| {
1420            let key = format!(" {name}=\"");
1421            tag.find(&key).map(|i| {
1422                let rest = &tag[i + key.len()..];
1423                rest[..rest.find('"').unwrap()].to_string()
1424            })
1425        };
1426        // boxes: one per node, outside the groups, an NA attribute left off
1427        let boxes: Vec<_> = tags
1428            .iter()
1429            .filter(|(t, _)| t.contains("data-node="))
1430            .collect();
1431        assert_eq!(boxes.len(), 3);
1432        for (b, inside) in &boxes {
1433            assert!(!inside, "{b}");
1434            let id = attr(b, "data-node").unwrap();
1435            assert_eq!(attr(b, "data-value").is_some(), id == "Model", "{id}");
1436        }
1437        // edges: the caller's class on a path; the label's attributes
1438        assert!(tags.iter().any(|(t, _)| t.contains("data-edge=\"1&gt;2\"")
1439            && attr(t, "class").is_some_and(|c| c.contains("flowing"))));
1440        assert!(tags
1441            .iter()
1442            .any(|(t, _)| attr(t, "data-from").as_deref() == Some("Ingest")));
1443        assert!(svg.contains(" gg-graph-node\"") && svg.contains("gg-graph-edge-label"));
1444        // node contents grouped by node; lanes drawn with their names
1445        for id in labels {
1446            assert!(svg.contains(&format!("data-of=\"{id}\"")), "{id}");
1447        }
1448        assert!(svg.contains("data-lane=\"Right\""));
1449        assert!(svg.contains(">Left<") && svg.contains(">42<"));
1450    }
1451
1452    /// Forney style (#1172): an observation as a terminal square, its label
1453    /// beside it; a variable as a labelled edge, its name in the math font.
1454    #[test]
1455    fn forney_terminals_and_variable_edges() {
1456        use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
1457        let spec = [
1458            ("Cat", NodeShape::Glyph),
1459            ("T", NodeShape::Glyph),
1460            ("x₁", NodeShape::Terminal),
1461        ];
1462        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
1463        assert_eq!((sizes[2].w, sizes[2].h), (TERMINAL, TERMINAL));
1464        let gnodes: Vec<GraphNode> = sizes
1465            .iter()
1466            .map(|b| GraphNode {
1467                w: b.w,
1468                h: b.h,
1469                ..Default::default()
1470            })
1471            .collect();
1472        let gedges = vec![
1473            GraphEdge {
1474                from: 0,
1475                to: 1,
1476                label_w: None,
1477            },
1478            GraphEdge {
1479                from: 1,
1480                to: 2,
1481                label_w: None,
1482            },
1483        ];
1484        let l = layered(&gnodes, &gedges, &LayeredParams::default());
1485        let nodes: Vec<DrawNode> = spec
1486            .iter()
1487            .zip(&sizes)
1488            .enumerate()
1489            .map(|(i, ((_, shape), b))| DrawNode {
1490                id: format!("n{i}"),
1491                shape: *shape,
1492                lines: b.lines.clone(),
1493                stroke: (13, 148, 136),
1494                tooltip: b.lines.join(" "),
1495                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
1496                // the observation flagged: filled in its accent
1497                accent: (*shape == NodeShape::Terminal).then_some((217, 119, 6)),
1498                ..Default::default()
1499            })
1500            .collect();
1501        let edges = vec![
1502            // the variable s₀ between the two factors
1503            DrawEdge {
1504                colour: (13, 148, 136),
1505                width: 1.2,
1506                undirected: true,
1507                label: Some("s₀".to_string()),
1508                label_math: true,
1509                ..Default::default()
1510            },
1511            DrawEdge {
1512                colour: (13, 148, 136),
1513                width: 1.2,
1514                undirected: true,
1515                ..Default::default()
1516            },
1517        ];
1518        let render = |style: &GraphStyle| {
1519            draw(
1520                &l,
1521                &[],
1522                &[],
1523                &nodes,
1524                &edges,
1525                style,
1526                crate::theme::presets::theme_void(),
1527            )
1528            .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32 + 40, l.h.ceil() as u32)
1529            .unwrap()
1530        };
1531        let math = GraphStyle {
1532            math_font: Some("STIX Two Math, serif".to_string()),
1533            ..GraphStyle::default()
1534        };
1535        let svg = render(&math);
1536        let el = |text: &str| {
1537            let at = svg
1538                .find(&format!(">{text}</text>"))
1539                .unwrap_or_else(|| panic!("{text}"));
1540            svg[svg[..at].rfind('<').unwrap()..at].to_string()
1541        };
1542        // the terminal: a filled square, its label starting beside it
1543        assert!(svg.contains("gg-graph-node-terminal"), "terminal mark");
1544        assert!(
1545            svg.contains("fill=\"#D97706\""),
1546            "the terminal in its accent"
1547        );
1548        let x1 = el("x₁");
1549        assert!(
1550            x1.contains("text-anchor=\"start\"") && x1.contains("italic"),
1551            "{x1}"
1552        );
1553        let t = &l.nodes[2];
1554        let lx: f64 = x1
1555            .split("x=\"")
1556            .nth(1)
1557            .unwrap()
1558            .split('"')
1559            .next()
1560            .unwrap()
1561            .parse()
1562            .unwrap();
1563        assert!(
1564            lx > t.cx + t.w / 2.0,
1565            "the label right of the square: {lx} vs {}",
1566            t.cx
1567        );
1568        // the variable's edge label in the math font
1569        let s0 = el("s₀");
1570        assert!(
1571            s0.contains("STIX Two Math") && s0.contains("italic"),
1572            "{s0}"
1573        );
1574        // without a math font: a plain edge label
1575        let plain = render(&GraphStyle::default());
1576        let at = plain.find(">s₀</text>").unwrap();
1577        assert!(!plain[plain[..at].rfind('<').unwrap()..at].contains("italic"));
1578    }
1579
1580    /// A coin toss as a Forney-style factor graph: a Beta prior box, the
1581    /// parameter's circle, an equality node, Bernoulli boxes and observed
1582    /// circles in a plate; undirected edges with interface names near the
1583    /// factor.
1584    #[test]
1585    fn draws_a_factor_graph_with_shapes_and_a_plate() {
1586        let n = 3;
1587        // (label, shape)
1588        let mut spec = vec![
1589            ("Beta", NodeShape::Box),
1590            ("θ", NodeShape::Circle),
1591            ("=", NodeShape::Square),
1592        ];
1593        for _ in 0..n {
1594            spec.push(("Ber", NodeShape::Box));
1595        }
1596        for _ in 0..n {
1597            spec.push(("y", NodeShape::FilledCircle));
1598        }
1599        spec.push(("2.0", NodeShape::Text));
1600        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
1601        // (from, to, interface)
1602        let mut links = vec![(0, 1, "out"), (1, 2, ""), (9, 0, "a")];
1603        for i in 0..n {
1604            links.push((2, 3 + i, "p"));
1605            links.push((3 + i, 3 + n + i, "out"));
1606        }
1607        let gnodes: Vec<GraphNode> = sizes
1608            .iter()
1609            .map(|b| GraphNode {
1610                w: b.w,
1611                h: b.h,
1612                ..Default::default()
1613            })
1614            .collect();
1615        let gedges: Vec<GraphEdge> = links
1616            .iter()
1617            .map(|&(a, b, _)| GraphEdge {
1618                from: a,
1619                to: b,
1620                label_w: None,
1621            })
1622            .collect();
1623        // a plate reaches past its nodes: room for it in the margin
1624        let params = LayeredParams {
1625            margin: 32.0,
1626            ..Default::default()
1627        };
1628        let l = layered(&gnodes, &gedges, &params);
1629        let nodes: Vec<DrawNode> = spec
1630            .iter()
1631            .zip(&sizes)
1632            .enumerate()
1633            .map(|(i, ((_, shape), b))| DrawNode {
1634                id: format!("n{i}"),
1635                shape: *shape,
1636                lines: b.lines.clone(),
1637                stroke: (60, 60, 60),
1638                tooltip: b.lines.join(" "),
1639                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
1640                // θ's belief curve
1641                belief: (i == 1).then(|| (vec![0.0, 0.3, 1.0, 0.3, 0.0], (120, 80, 200))),
1642                // and its prior, wider
1643                prior: (i == 1).then(|| (vec![0.2, 0.4, 0.5, 0.4, 0.2], (150, 150, 150))),
1644                ..Default::default()
1645            })
1646            .collect();
1647        let edges: Vec<DrawEdge> = links
1648            .iter()
1649            .map(|&(a, b, iface)| DrawEdge {
1650                colour: (90, 90, 90),
1651                width: 1.2,
1652                undirected: true,
1653                label: (!iface.is_empty()).then(|| iface.to_string()),
1654                // the interface name near the factor
1655                label_at: Some(if spec[b].1 == NodeShape::Box {
1656                    0.8
1657                } else {
1658                    0.2
1659                }),
1660                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
1661                ..Default::default()
1662            })
1663            .collect();
1664        let plates = [Plate {
1665            label: "i = 1..3".to_string(),
1666            nodes: (3..3 + 2 * n).collect(),
1667        }];
1668        let style = GraphStyle::default();
1669        let svg = draw(
1670            &l,
1671            &[],
1672            &plates,
1673            &nodes,
1674            &edges,
1675            &style,
1676            crate::theme::presets::theme_void(),
1677        )
1678        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1679        .unwrap();
1680        // every node is a mark, shapes classed, undirected: no arrowheads
1681        assert_eq!(svg.matches("data-node=").count(), spec.len());
1682        for shape in ["circle", "filled-circle", "square", "text"] {
1683            assert!(svg.contains(&format!("gg-graph-node-{shape}")), "{shape}");
1684        }
1685        assert!(
1686            !svg.contains("data-part=\"arrow\""),
1687            "an undirected edge has no arrowhead"
1688        );
1689        assert_eq!(svg.matches("data-edge=").count(), links.len());
1690        // θ's belief curve: a filled shape over its circle, in its group
1691        assert!(svg.contains("gg-graph-node-belief"), "belief layer");
1692        assert!(svg.contains("fill=\"#7850C8\""), "belief colour");
1693        // its prior: a dashed outline, drawn before (under) the belief
1694        let (pr, be) = (
1695            svg.find("gg-graph-node-prior").expect("prior layer"),
1696            svg.find("gg-graph-node-belief").unwrap(),
1697        );
1698        assert!(pr < be, "the prior under the belief");
1699        let mark = &svg[svg[..pr].rfind('<').unwrap()..pr];
1700        assert!(mark.contains("stroke-dasharray"), "dashed prior: {mark}");
1701        // no math font: bold sans labels
1702        assert!(!svg.contains("font-style=\"italic\""), "plain labels");
1703        // a math font: the shaped nodes' labels in it, italic; glyph colours
1704        let math = GraphStyle {
1705            math_font: Some("STIX Two Math, serif".to_string()),
1706            glyph_fill: Some((240, 247, 246)),
1707            glyph_ink: Some((13, 148, 136)),
1708            ..style.clone()
1709        };
1710        let msvg = draw(
1711            &l,
1712            &[],
1713            &plates,
1714            &nodes,
1715            &edges,
1716            &math,
1717            crate::theme::presets::theme_void(),
1718        )
1719        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1720        .unwrap();
1721        assert!(msvg.contains("STIX Two Math"), "math font");
1722        assert!(msvg.contains("font-style=\"italic\""), "italic labels");
1723        // …but a constant stays upright
1724        let two = msvg.find(">2.0<").expect("the constant 2.0");
1725        let el = &msvg[msvg[..two].rfind('<').unwrap()..two];
1726        assert!(!el.contains("italic"), "upright constant: {el}");
1727        // the plate, and its label
1728        assert!(svg.contains("data-plate=\"i = 1..3\"") && svg.contains(">i = 1..3<"));
1729        // the observed circles' dark fill
1730        assert!(svg.contains(&format!(
1731            "fill=\"{}\"",
1732            hex(style.observed_fill).to_uppercase()
1733        )));
1734        // no two nodes overlap
1735        for (i, a) in l.nodes.iter().enumerate() {
1736            for b in &l.nodes[i + 1..] {
1737                let apart = (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
1738                    || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0;
1739                assert!(apart, "overlap");
1740            }
1741        }
1742        // the circle is round: rx is half its width
1743        let c = &l.nodes[1];
1744        assert!(svg.contains(&format!("rx=\"{:.2}\"", c.w / 2.0)), "{}", c.w);
1745    }
1746
1747    /// An HMM over five slices with learned transition (A) and observation
1748    /// (B) matrices, in bands param / state / obs: the state chain is one
1749    /// straight row, each observation below its state.
1750    #[test]
1751    fn banded_hmm_keeps_the_state_chain_straight() {
1752        use crate::graph_layout::{banded, BandedParams};
1753        let t_n = 5;
1754        // (label, shape, band)
1755        let mut spec: Vec<(String, NodeShape, usize)> = vec![
1756            ("Dir".into(), NodeShape::Glyph, 0), // 0: prior on A
1757            ("A".into(), NodeShape::Square, 0),  // 1: = of A
1758            ("Dir".into(), NodeShape::Glyph, 0), // 2: prior on B
1759            ("B".into(), NodeShape::Square, 0),  // 3: = of B
1760            ("Cat".into(), NodeShape::Glyph, 1), // 4: initial state prior
1761            ("s₀".into(), NodeShape::Circle, 1), // 5
1762        ];
1763        let mut links: Vec<(usize, usize, &str)> =
1764            vec![(0, 1, "out"), (2, 3, "out"), (4, 5, "out")];
1765        let mut prev = 5;
1766        for t in 1..=t_n {
1767            let tr = spec.len();
1768            spec.push(("T".into(), NodeShape::Glyph, 1));
1769            let eq = spec.len();
1770            spec.push((format!("s{t}"), NodeShape::Square, 1));
1771            let ob = spec.len();
1772            spec.push(("T".into(), NodeShape::Glyph, 2));
1773            let x = spec.len();
1774            spec.push((format!("x{t}"), NodeShape::FilledCircle, 2));
1775            links.extend([
1776                (prev, tr, "in"),
1777                (1, tr, "a"),
1778                (tr, eq, "out"),
1779                (eq, ob, "in"),
1780                (3, ob, "a"),
1781                (ob, x, "out"),
1782            ]);
1783            prev = eq;
1784        }
1785        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh, _)| node_size(*sh, l)).collect();
1786        let gnodes: Vec<GraphNode> = spec
1787            .iter()
1788            .zip(&sizes)
1789            .map(|((_, _, b), s)| GraphNode {
1790                w: s.w,
1791                h: s.h,
1792                lane: Some(*b),
1793                ..Default::default()
1794            })
1795            .collect();
1796        let gedges: Vec<GraphEdge> = links
1797            .iter()
1798            .map(|&(a, b, _)| GraphEdge {
1799                from: a,
1800                to: b,
1801                label_w: None,
1802            })
1803            .collect();
1804        let l = banded(
1805            &gnodes,
1806            &gedges,
1807            &BandedParams {
1808                bands: 3,
1809                margin: 32.0,
1810                ..Default::default()
1811            },
1812        );
1813        // the chain: every transition and state node on one row
1814        let chain: Vec<usize> = (0..spec.len())
1815            .filter(|&i| spec[i].2 == 1 && i != 4)
1816            .collect();
1817        let y = l.nodes[chain[0]].cy;
1818        for &i in &chain {
1819            assert_eq!(l.nodes[i].cy, y, "{} off the row", spec[i].0);
1820        }
1821        // each observation factor straight below its state's = node
1822        for t in 0..t_n {
1823            let (eq, ob) = (6 + 4 * t + 1, 6 + 4 * t + 2);
1824            assert_eq!(l.nodes[eq].cx, l.nodes[ob].cx, "slice {t}");
1825            assert!(l.nodes[ob].cy > y);
1826        }
1827        // no edge passes through a box other than its own two ends
1828        let crosses = |(x0, y0): (f64, f64), (x1, y1): (f64, f64), n: &PlacedNode| {
1829            // sampled along the segment, the box shrunk by a pixel
1830            (0..=40).any(|k| {
1831                let t = k as f64 / 40.0;
1832                let (x, y) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
1833                (x - n.cx).abs() < n.w / 2.0 - 1.0 && (y - n.cy).abs() < n.h / 2.0 - 1.0
1834            })
1835        };
1836        for (k, &(a, b, _)) in links.iter().enumerate() {
1837            for w in l.edges[k].windows(2) {
1838                for (i, n) in l.nodes.iter().enumerate() {
1839                    if i != a && i != b {
1840                        assert!(
1841                            !crosses(w[0], w[1], n),
1842                            "edge {a}->{b} crosses {}",
1843                            spec[i].0
1844                        );
1845                    }
1846                }
1847            }
1848        }
1849        // nothing overlaps
1850        for (i, a) in l.nodes.iter().enumerate() {
1851            for b in &l.nodes[i + 1..] {
1852                assert!(
1853                    (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
1854                        || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0
1855                );
1856            }
1857        }
1858        let nodes: Vec<DrawNode> = spec
1859            .iter()
1860            .zip(&sizes)
1861            .enumerate()
1862            .map(|(i, ((_, shape, _), b))| DrawNode {
1863                id: format!("n{i}"),
1864                shape: *shape,
1865                lines: b.lines.clone(),
1866                stroke: (60, 60, 60),
1867                ..Default::default()
1868            })
1869            .collect();
1870        let edges: Vec<DrawEdge> = links
1871            .iter()
1872            .map(|&(_, b, iface)| DrawEdge {
1873                colour: (90, 90, 90),
1874                width: 1.2,
1875                undirected: true,
1876                label: Some(iface.to_string()),
1877                label_at: Some(if spec[b].1 == NodeShape::Glyph {
1878                    0.8
1879                } else {
1880                    0.2
1881                }),
1882                ..Default::default()
1883            })
1884            .collect();
1885        let lanes = ["param".to_string(), "state".to_string(), "obs".to_string()];
1886        let svg = draw(
1887            &l,
1888            &lanes,
1889            &[],
1890            &nodes,
1891            &edges,
1892            &GraphStyle::default(),
1893            crate::theme::presets::theme_void(),
1894        )
1895        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1896        .unwrap();
1897        if let Ok(path) = std::env::var("GGPLOT_GRAPH_SVG") {
1898            std::fs::write(path, &svg).unwrap();
1899        }
1900        assert_eq!(svg.matches("data-lane=").count(), 3);
1901    }
1902}