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