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>edge-label-box`, `<prefix>lane`, `<prefix>lane-label`,
173    /// `<prefix>node-label`, `<prefix>node-value`, `<prefix>node-badge`,
174    /// `<prefix>node-spark`, `<prefix>plate`, `<prefix>plate-label`,
175    /// `<prefix>node-state`, `<prefix>node-state-bar`,
176    /// `<prefix>node-state-prior`, `<prefix>node-state-value`,
177    /// `<prefix>node-outline`, `<prefix>node-diamond-mark`,
178    /// `<prefix>node-state-delta`, `<prefix>node-icon`, `<prefix>edge-cut`;
179    /// a shaped node's mark also has `<prefix>node-<shape>`).
180    pub class_prefix: String,
181    /// A factor graph's math font: when set, the labels of shaped nodes
182    /// (variables, observations, equality nodes, glyph factors) are set in
183    /// this family, italic and regular weight — `θ`, `x₁`, `𝒩` read as
184    /// mathematics. `None` keeps the bold sans labels.
185    pub math_font: Option<String>,
186    /// A glyph factor's fill ([`NodeShape::Glyph`]); `None` is `card`.
187    pub glyph_fill: Option<Rgb>,
188    /// A glyph factor's glyph colour; `None` is `heading`.
189    pub glyph_ink: Option<Rgb>,
190    /// A discrete node's tint by how far its belief moved (every
191    /// [`StateBar::was`] given): the box fill mixed towards this colour by
192    /// the [`js_distance`] between the two, up to 45 % at a distance of 0.4
193    /// or more. Only a node without a [`DrawNode::fill`] of its own; `None`
194    /// tints nothing.
195    pub moved: Option<Rgb>,
196}
197
198impl Default for GraphStyle {
199    fn default() -> Self {
200        GraphStyle {
201            card: (255, 255, 255),
202            band: (226, 228, 233),
203            muted: (107, 114, 128),
204            heading: (17, 24, 39),
205            ink: (31, 41, 55),
206            variable_fill: (229, 231, 235),
207            observed_fill: (75, 85, 99),
208            plate: (107, 114, 128),
209            class_prefix: "gg-graph-".to_string(),
210            math_font: None,
211            glyph_fill: None,
212            glyph_ink: None,
213            moved: None,
214        }
215    }
216}
217
218/// A node's mark. A factor graph (Forney style) draws factors as boxes,
219/// variables as circles (filled when observed), equality nodes as small
220/// squares, deterministic (delta) nodes as small filled squares, and
221/// constants as plain text.
222#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
223pub enum NodeShape {
224    /// A box with a label, value, badge and sparkline ([`node_box`]).
225    #[default]
226    Box,
227    Circle,
228    FilledCircle,
229    /// A small square, its label above it.
230    Square,
231    /// A small filled square, its label above it.
232    FilledSquare,
233    /// The label alone.
234    Text,
235    /// A small square box with a short glyph centred in it (a factor drawn
236    /// as `𝒩`, `Γ`, `Ber`, …): uniform, so a factor graph stays compact.
237    Glyph,
238    /// A small filled square at the end of an edge, its label beside it (to
239    /// the right): an observation in Forney style, where data enters.
240    Terminal,
241    /// A box with square corners and a box's contents: an influence
242    /// diagram's decision.
243    Rect,
244    /// A diamond with the label (and a value line) inside: an influence
245    /// diagram's utility.
246    Diamond,
247    /// A box with a second outline inside it and a box's contents: a
248    /// deterministic node of a Bayesian network.
249    DoubleBox,
250}
251
252impl NodeShape {
253    fn name(self) -> &'static str {
254        match self {
255            NodeShape::Box => "box",
256            NodeShape::Circle => "circle",
257            NodeShape::FilledCircle => "filled-circle",
258            NodeShape::Square => "square",
259            NodeShape::FilledSquare => "filled-square",
260            NodeShape::Text => "text",
261            NodeShape::Glyph => "glyph",
262            NodeShape::Terminal => "terminal",
263            NodeShape::Rect => "rect",
264            NodeShape::Diamond => "diamond",
265            NodeShape::DoubleBox => "double-box",
266        }
267    }
268
269    /// A box's contents (label, value, badge, sparkline, states) go inside:
270    /// [`NodeShape::Box`], [`NodeShape::Rect`], [`NodeShape::DoubleBox`].
271    pub fn boxed(self) -> bool {
272        matches!(
273            self,
274            NodeShape::Box | NodeShape::Rect | NodeShape::DoubleBox
275        )
276    }
277}
278
279/// A belief curve's size over its node (px).
280pub const BELIEF_W: f64 = 46.0;
281pub const BELIEF_H: f64 = 16.0;
282/// A small square's side (px).
283const SQUARE: f64 = 14.0;
284/// A terminal's side (px).
285const TERMINAL: f64 = 11.0;
286/// A glyph factor's side (px) and its glyph's size.
287const GLYPH_SIDE: f64 = 34.0;
288const GLYPH_PX: f64 = 15.0;
289
290/// A state row's height, its bar's length and the widest state name (px).
291const STATE_H: f64 = 15.0;
292const STATE_BAR_W: f64 = 64.0;
293const STATE_NAME_MAX: f64 = 84.0;
294/// The gaps around a state's bar, and the room for its text ("100%").
295const STATE_GAP: f64 = 6.0;
296const STATE_TEXT_W: f64 = 30.0;
297/// A box with state rows may be this much wider than a plain one.
298const STATES_MAX_W: f64 = 224.0;
299/// The room for a state's change after its probability (`▲21`).
300const STATE_DELTA_W: f64 = 28.0;
301/// A change smaller than this is not shown.
302const MIN_DELTA: f64 = 0.005;
303
304/// The Jensen–Shannon distance between two distributions over the same
305/// states (base 2: 0 the same, 1 disjoint), each normalised to sum to 1;
306/// 0 when either sums to 0 or they differ in length.
307pub fn js_distance(p: &[f64], q: &[f64]) -> f64 {
308    let clean = |v: &[f64]| -> Option<Vec<f64>> {
309        let v: Vec<f64> = v
310            .iter()
311            .map(|x| if x.is_finite() { x.max(0.0) } else { 0.0 })
312            .collect();
313        let s: f64 = v.iter().sum();
314        (s > 0.0).then(|| v.into_iter().map(|x| x / s).collect())
315    };
316    let (Some(p), Some(q)) = (clean(p), clean(q)) else {
317        return 0.0;
318    };
319    if p.len() != q.len() {
320        return 0.0;
321    }
322    let kl = |a: &[f64], m: &[f64]| -> f64 {
323        a.iter()
324            .zip(m)
325            .filter(|(x, _)| **x > 0.0)
326            .map(|(x, y)| x * (x / y).log2())
327            .sum()
328    };
329    let m: Vec<f64> = p.iter().zip(&q).map(|(a, b)| (a + b) / 2.0).collect();
330    let jsd = (kl(&p, &m) + kl(&q, &m)) / 2.0;
331    jsd.clamp(0.0, 1.0).sqrt()
332}
333
334/// `a` mixed towards `b` by `t` (0..=1).
335fn mix(a: Rgb, b: Rgb, t: f64) -> Rgb {
336    let t = t.clamp(0.0, 1.0);
337    let m = |x: u8, y: u8| (x as f64 + (y as f64 - x as f64) * t).round() as u8;
338    (m(a.0, b.0), m(a.1, b.1), m(a.2, b.2))
339}
340
341/// A node's tint ([`GraphStyle::moved`]): how much of the colour, by how
342/// far its belief moved.
343fn moved_share(states: &[StateBar]) -> Option<f64> {
344    let was: Option<Vec<f64>> = states.iter().map(|r| r.was).collect();
345    let was = was?;
346    let now: Vec<f64> = states.iter().map(|r| r.p).collect();
347    let d = js_distance(&now, &was);
348    (d >= 0.01).then(|| (d / 0.4).min(1.0) * 0.45)
349}
350
351/// A state's change as its row shows it: `▲21`, `▼4` (percentage
352/// points), `None` under [`MIN_DELTA`].
353fn delta_text(p: f64, was: f64) -> Option<(String, bool)> {
354    let d = p - was;
355    if !d.is_finite() || d.abs() < MIN_DELTA {
356        return None;
357    }
358    let pts = (d.abs() * 100.0).round().max(1.0);
359    Some((
360        format!("{}{pts:.0}", if d > 0.0 { '▲' } else { '▼' }),
361        d > 0.0,
362    ))
363}
364
365/// A hand (an intervention), in a 12 × 12 px box from its top left: the
366/// palm and four fingers as rounded rects `(x0, y0, x1, y1)`, the thumb as
367/// a polygon.
368const HAND_RECTS: [(f64, f64, f64, f64); 5] = [
369    (0.6, 5.2, 9.2, 11.8),
370    (0.6, 1.8, 2.5, 7.0),
371    (2.8, 0.4, 4.7, 7.0),
372    (5.0, 0.8, 6.9, 7.0),
373    (7.2, 2.2, 9.1, 7.0),
374];
375const HAND_THUMB: [(f64, f64); 4] = [(8.2, 8.4), (11.0, 5.2), (12.2, 6.2), (9.4, 10.6)];
376
377/// A state's name as its row shows it: cut with "…" past
378/// `STATE_NAME_MAX`.
379fn state_name(name: &str) -> String {
380    let cap = (STATE_NAME_MAX / (SMALL_PX * 0.56)).floor() as usize;
381    if name.chars().count() <= cap {
382        return name.to_string();
383    }
384    let mut s: String = name.chars().take(cap.saturating_sub(1)).collect();
385    s = s.trim_end().to_string();
386    s.push('…');
387    s
388}
389
390/// The box a discrete node needs (a Bayesian network's node, Netica /
391/// GeNIe style): [`node_box`]'s label, value and badge, then one row per
392/// state (its name, a bar and the probability as text), as [`draw`] fills
393/// it from [`DrawNode::states`]. No states: [`node_box`].
394pub fn states_box(
395    label: &str,
396    value: Option<&str>,
397    badge: Option<&str>,
398    states: &[String],
399) -> NodeBox {
400    states_box_with_deltas(label, value, badge, states, false)
401}
402
403/// [`states_box`] with room for each row's change after its probability
404/// (`deltas`, see [`StateBar::was`]).
405pub fn states_box_with_deltas(
406    label: &str,
407    value: Option<&str>,
408    badge: Option<&str>,
409    states: &[String],
410    deltas: bool,
411) -> NodeBox {
412    let b = node_box(label, value, badge, false);
413    if states.is_empty() {
414        return b;
415    }
416    let names = states
417        .iter()
418        .map(|n| text_w(&state_name(n), SMALL_PX, true))
419        .fold(0.0, f64::max);
420    let delta = if deltas { STATE_DELTA_W } else { 0.0 };
421    let rows = names + STATE_GAP + STATE_BAR_W + STATE_GAP + STATE_TEXT_W + delta;
422    NodeBox {
423        w: b.w.max(rows + 2.0 * BOX_PAD_X).min(STATES_MAX_W + delta),
424        h: b.h + 4.0 + STATE_H * states.len() as f64,
425        lines: b.lines,
426    }
427}
428
429/// The diamond a [`NodeShape::Diamond`] needs for its label and an
430/// optional value line: the text's box, its corners on the diamond's edges.
431pub fn diamond_box(label: &str, value: Option<&str>) -> NodeBox {
432    let lines = wrap(label, 132.0);
433    let mut w = lines
434        .iter()
435        .map(|l| text_w(l, LABEL_PX, true))
436        .fold(0.0, f64::max);
437    let mut h = LINE_H * lines.len() as f64;
438    if let Some(v) = value {
439        w = w.max(text_w(v, VALUE_PX, true));
440        h += LINE_H;
441    }
442    // a w × h box inscribed in the diamond takes twice each, plus a margin
443    NodeBox {
444        w: (2.0 * w + 16.0).max(72.0),
445        h: (2.0 * h + 8.0).max(44.0),
446        lines,
447    }
448}
449
450/// A table's widest first column (row names) and widest further column (px).
451const TABLE_NAME_MAX: f64 = 96.0;
452const TABLE_CELL_MAX: f64 = 84.0;
453/// The gap between a table's columns (px).
454const TABLE_GAP: f64 = 10.0;
455
456/// A small table in a node's box, under its label (an influence diagram's
457/// policy: a row per configuration of the decision's informational parents,
458/// a column per option with its expected utility, the chosen option
459/// marked). The first column holds the row names, left-aligned; the others
460/// are right-aligned. Size the box with [`table_box`].
461#[derive(Clone, Debug, Default, PartialEq)]
462pub struct NodeTable {
463    /// The column heads (the first one names the rows and may be empty);
464    /// all empty: no header row.
465    pub header: Vec<String>,
466    /// The rows: the name, then a cell per further column.
467    pub rows: Vec<Vec<String>>,
468    /// Per row, the column (1 or more) of its marked cell, e.g. the chosen
469    /// option: bold, on a tint of the table's colour.
470    pub marked: Vec<Option<usize>>,
471    /// A row to highlight with a band, e.g. the configuration the evidence
472    /// picks.
473    pub current: Option<usize>,
474    /// Per column, the `data-state` its head and cells carry (empty: none),
475    /// e.g. the option a click on the column names.
476    pub keys: Vec<String>,
477}
478
479/// `s` cut with "…" to at most `max` px (bold).
480fn fit_text(s: &str, max: f64) -> String {
481    let cap = (max / (SMALL_PX * 0.6)).floor() as usize;
482    if s.chars().count() <= cap {
483        return s.to_string();
484    }
485    let mut out: String = s.chars().take(cap.saturating_sub(1)).collect();
486    out = out.trim_end().to_string();
487    out.push('…');
488    out
489}
490
491impl NodeTable {
492    fn has_header(&self) -> bool {
493        self.header.iter().any(|h| !h.is_empty())
494    }
495
496    fn columns(&self) -> usize {
497        self.rows
498            .iter()
499            .map(Vec::len)
500            .chain([self.header.len()])
501            .max()
502            .unwrap_or(0)
503    }
504
505    /// Column `c`'s `data-state`, if it has one.
506    fn key(&self, c: usize) -> Option<String> {
507        self.keys.get(c).filter(|k| !k.is_empty()).cloned()
508    }
509
510    /// A cell's text as drawn: cut to its column's limit.
511    fn cell(&self, c: usize, s: &str) -> String {
512        fit_text(
513            s,
514            if c == 0 {
515                TABLE_NAME_MAX
516            } else {
517                TABLE_CELL_MAX
518            },
519        )
520    }
521
522    /// Each column's width (px), header and cells as drawn (bold, the
523    /// widest case).
524    fn widths(&self) -> Vec<f64> {
525        (0..self.columns())
526            .map(|c| {
527                self.rows
528                    .iter()
529                    .filter_map(|r| r.get(c))
530                    .chain(self.header.get(c))
531                    .map(|s| text_w(&self.cell(c, s), SMALL_PX, true))
532                    .fold(0.0, f64::max)
533            })
534            .collect()
535    }
536
537    /// The width of the table (px).
538    fn width(&self) -> f64 {
539        let w = self.widths();
540        w.iter().sum::<f64>() + TABLE_GAP * w.len().saturating_sub(1) as f64
541    }
542}
543
544/// The box a node with a [`NodeTable`] needs: [`node_box`]'s label, value
545/// and badge, then the header row (when there is one) and a row per table
546/// row, as [`draw`] fills it from [`DrawNode::table`].
547pub fn table_box(
548    label: &str,
549    value: Option<&str>,
550    badge: Option<&str>,
551    table: &NodeTable,
552) -> NodeBox {
553    let b = node_box(label, value, badge, false);
554    if table.rows.is_empty() {
555        return b;
556    }
557    let rows = table.rows.len() + usize::from(table.has_header());
558    NodeBox {
559        w: b.w.max(table.width() + 2.0 * BOX_PAD_X),
560        h: b.h + 4.0 + STATE_H * rows as f64,
561        lines: b.lines,
562    }
563}
564
565/// The size a node of `shape` needs for `label` (a [`NodeShape::Box`] is
566/// [`node_box`] without a value, badge or sparkline). A circle fits its
567/// label on one line, at least 30 px across.
568pub fn node_size(shape: NodeShape, label: &str) -> NodeBox {
569    let one = || vec![label.to_string()];
570    match shape {
571        NodeShape::Box | NodeShape::Rect | NodeShape::DoubleBox => {
572            node_box(label, None, None, false)
573        }
574        NodeShape::Diamond => diamond_box(label, None),
575        NodeShape::Circle | NodeShape::FilledCircle => {
576            let d = (text_w(label, LABEL_PX, true) + 14.0).max(30.0);
577            NodeBox {
578                w: d,
579                h: d,
580                lines: one(),
581            }
582        }
583        NodeShape::Square | NodeShape::FilledSquare => NodeBox {
584            w: SQUARE,
585            h: SQUARE,
586            lines: if label.is_empty() { Vec::new() } else { one() },
587        },
588        NodeShape::Terminal => NodeBox {
589            w: TERMINAL,
590            h: TERMINAL,
591            lines: if label.is_empty() { Vec::new() } else { one() },
592        },
593        NodeShape::Text => NodeBox {
594            w: text_w(label, LABEL_PX, false) + 8.0,
595            h: 20.0,
596            lines: one(),
597        },
598        NodeShape::Glyph => {
599            let side = (text_w(label, GLYPH_PX, true) + 14.0).max(GLYPH_SIDE);
600            NodeBox {
601                w: side,
602                h: GLYPH_SIDE,
603                lines: one(),
604            }
605        }
606    }
607}
608
609/// A plate: a dashed box around a collection of nodes (indices in the
610/// layout's order), labelled at its top left (`x_t`, `t = 1..T`).
611#[derive(Clone, Debug, Default)]
612pub struct Plate {
613    pub label: String,
614    pub nodes: Vec<usize>,
615}
616
617/// A `data-*` attribute: its name (without `data-`) and value; `None` leaves
618/// it off that mark.
619pub type DataAttr = (String, Option<String>);
620
621/// One state of a discrete node: a row in its box with the state's name, a
622/// bar for its probability and that probability as text, the prior as a
623/// faint bar behind it with a tick where it ends (Netica / GeNIe style).
624#[derive(Clone, Debug, Default, PartialEq)]
625pub struct StateBar {
626    pub name: String,
627    /// The probability, 0..=1 (clamped).
628    pub p: f64,
629    /// The probability before any evidence, 0..=1.
630    pub prior: Option<f64>,
631    /// What the row says after the bar (e.g. `36%`).
632    pub text: String,
633    /// The observed state: its name in bold.
634    pub observed: bool,
635    /// The probability before the last change (e.g. under the evidence as it
636    /// was), 0..=1: a ▲ / ▼ and the change in percentage points after the
637    /// probability (`▲21`), none for a change under half a point. Size the
638    /// box with [`states_box_with_deltas`].
639    pub was: Option<f64>,
640}
641
642/// A continuous node's belief in its box, under the label (a Bayesian
643/// network's Gaussian node): the density as a filled curve, the prior as a
644/// dashed outline behind it, an interval shaded under the curve, a marked
645/// value (e.g. the observed one) and a line of text under it. The heights
646/// share one span (left to right), `band` and `marker` are fractions of it.
647/// Size the box with [`density_box`].
648#[derive(Clone, Debug, Default, PartialEq)]
649pub struct NodeDensity {
650    /// The density, 0..=1 at evenly spaced points (three or more).
651    pub heights: Vec<f64>,
652    /// The prior's density on the same scale and span.
653    pub prior: Option<Vec<f64>>,
654    /// An interval (e.g. 90 %), its ends as fractions of the span: the
655    /// curve's area between them drawn darker.
656    pub band: Option<(f64, f64)>,
657    /// A value as a fraction of the span: a line across the curve.
658    pub marker: Option<f64>,
659    /// The line under the curve, e.g. `12.3 (10.1–14.5)`.
660    pub text: String,
661}
662
663/// A density's size in its box (px).
664const DENSITY_W: f64 = 132.0;
665const DENSITY_H: f64 = 28.0;
666
667/// The box a continuous node needs: [`node_box`]'s label, value and badge,
668/// then its density and a text line ([`DrawNode::density`]).
669pub fn density_box(label: &str, value: Option<&str>, badge: Option<&str>, text: &str) -> NodeBox {
670    let b = node_box(label, value, badge, false);
671    let w = DENSITY_W.max(text_w(text, SMALL_PX, false));
672    NodeBox {
673        w: b.w.max(w + 2.0 * BOX_PAD_X).min(STATES_MAX_W),
674        h: b.h + 6.0 + DENSITY_H + STATE_H,
675        lines: b.lines,
676    }
677}
678
679/// The heights' polygon from fraction `a` to `b` of the span, on `x0..x0+w`
680/// with its base at `base` (the area under the curve between them).
681fn area_between(hs: &[f64], a: f64, b: f64, x0: f64, w: f64, base: f64, h: f64) -> Vec<(f64, f64)> {
682    let last = (hs.len() - 1) as f64;
683    let at = |f: f64| {
684        let t = f.clamp(0.0, 1.0) * last;
685        let i = (t.floor() as usize).min(hs.len() - 2);
686        let k = t - i as f64;
687        hs[i] * (1.0 - k) + hs[i + 1] * k
688    };
689    let (a, b) = (a.clamp(0.0, 1.0), b.clamp(0.0, 1.0));
690    let y = |v: f64| base - v.clamp(0.0, 1.0) * h;
691    let mut pts = vec![(x0 + w * a, base), (x0 + w * a, y(at(a)))];
692    for (i, v) in hs.iter().enumerate() {
693        let f = i as f64 / last;
694        if f > a && f < b {
695            pts.push((x0 + w * f, y(*v)));
696        }
697    }
698    pts.push((x0 + w * b, y(at(b))));
699    pts.push((x0 + w * b, base));
700    pts
701}
702
703/// A mark on a node, at its top right corner in a small round badge.
704#[derive(Clone, Copy, Debug, PartialEq, Eq)]
705pub enum NodeIcon {
706    /// A hand: the node is set by an intervention (`do`).
707    Hand,
708    /// A letter (bold, in the heading colour) in the badge: e.g. `X` a
709    /// treatment, `Y` an outcome, `M` a mediator in a causal diagram.
710    Letter(char),
711}
712
713/// What a node's box shows, and its attributes. Its geometry comes from the
714/// layout ([`PlacedNode`]); its label lines from [`node_box`].
715#[derive(Clone, Debug, Default)]
716pub struct DrawNode {
717    /// The `data-of` group of everything drawn for the node.
718    pub id: String,
719    /// Its mark; anything but a box shows only the label.
720    pub shape: NodeShape,
721    /// The label, wrapped ([`NodeBox::lines`]).
722    pub lines: Vec<String>,
723    /// A value line under the label.
724    pub value: Option<String>,
725    /// A badge row: its text and its dot's (and outline's) colour.
726    pub badge: Option<(String, Rgb)>,
727    /// The box (or circle, square) outline.
728    pub stroke: Rgb,
729    /// A thin bar along the box's left edge; a filled mark (an observation,
730    /// a terminal) is filled with it instead.
731    pub accent: Option<Rgb>,
732    /// A sparkline (two values or more) along the bottom, and its colour.
733    pub spark: Option<(Vec<f64>, Rgb)>,
734    /// A belief curve over the node (a factor graph variable's density):
735    /// heights 0..=1 at evenly spaced points (three or more), and its colour.
736    pub belief: Option<(Vec<f64>, Rgb)>,
737    /// The prior behind the belief curve: heights on the same scale and
738    /// span as [`DrawNode::belief`], drawn as a faint dashed outline, and
739    /// its colour.
740    pub prior: Option<(Vec<f64>, Rgb)>,
741    /// A discrete node's states, one row each under the label (a boxed
742    /// shape; size it with [`states_box`]), and the bars' colour.
743    pub states: Option<(Vec<StateBar>, Rgb)>,
744    /// A continuous node's density under the label (a boxed shape; size it
745    /// with [`density_box`]), and its colour.
746    pub density: Option<(NodeDensity, Rgb)>,
747    /// The box's (or diamond's) fill; `None` is the card colour. E.g. a
748    /// node with evidence, shaded.
749    pub fill: Option<Rgb>,
750    /// A mark at the box's top right corner, e.g. a hand for a node set by
751    /// an intervention.
752    pub icon: Option<NodeIcon>,
753    /// A table under the label (a boxed shape; size it with
754    /// [`table_box`]), e.g. an influence diagram's policy, and the colour
755    /// its marked cells are tinted with.
756    pub table: Option<(NodeTable, Rgb)>,
757    /// A second outline around the box (or diamond), 4 px outside it and
758    /// 2 px wide, in this colour: the node is singled out, e.g. adjusted for
759    /// in a causal diagram (an adjustment set).
760    pub ring: Option<Rgb>,
761    pub tooltip: String,
762    /// `data-*` on the box (the hit target); every node lists the same
763    /// names, in the same order.
764    pub attrs: Vec<DataAttr>,
765}
766
767/// An edge's line pattern.
768#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
769pub enum EdgeLine {
770    #[default]
771    Solid,
772    Dashed,
773    /// Round dots (zero-length dashes with round caps).
774    Dots,
775}
776
777/// What an edge looks like, and its attributes. Its points come from the
778/// layout ([`GraphLayout::edges`]); the arrowhead is on its last point,
779/// unless `undirected`.
780#[derive(Clone, Debug, Default)]
781pub struct DrawEdge {
782    pub colour: Rgb,
783    /// Line width (px), see [`flow_width`].
784    pub width: f64,
785    pub line: EdgeLine,
786    /// Extra CSS classes on the path.
787    pub class: Option<String>,
788    pub tooltip: String,
789    /// A label (`\n` breaks lines) on the edge, clear of the boxes.
790    pub label: Option<String>,
791    /// Where along the edge the label goes (0 at its start, 1 at its end),
792    /// e.g. near a factor for an interface name; `None`: the middle, moved
793    /// along the edge until no box covers it.
794    pub label_at: Option<f64>,
795    /// No arrowhead (a factor graph's edges).
796    pub undirected: bool,
797    /// The label names a variable (Forney style: the edge is the variable):
798    /// set in [`GraphStyle::math_font`] when there is one, in the heading
799    /// colour.
800    pub label_math: bool,
801    /// `data-*` on the path; every edge lists the same names, in the same
802    /// order.
803    pub attrs: Vec<DataAttr>,
804    /// `data-*` on the label (and on a cut edge's break mark).
805    pub label_attrs: Vec<DataAttr>,
806    /// The edge is cut (its child is set by an intervention, so the parent
807    /// no longer acts on it): a break mark across its middle — a gap and
808    /// two slashes in the edge's colour. Give it a muted colour.
809    pub cut: bool,
810    /// The edge is blocked (a path through it is closed, e.g. by adjusting
811    /// for a node on it): a bar across its middle, square to the line, in
812    /// the edge's colour.
813    pub blocked: bool,
814}
815
816/// An edge's width (px) for what it carries, `value` of the graph's `max`:
817/// area-true (`sqrt`), 1.4 px to 7 px; 1.6 px without a value; dotted edges
818/// 3–6 px so their dots show. Rounded to 0.1 px.
819pub fn flow_width(value: Option<f64>, max: f64, line: EdgeLine) -> f64 {
820    let width = match value {
821        Some(v) if max > 0.0 => 1.4 + 5.6 * (v.max(0.0) / max).sqrt(),
822        _ => 1.6,
823    };
824    let width = match line {
825        EdgeLine::Dots => width.clamp(3.0, 6.0),
826        _ => width,
827    };
828    (width * 10.0).round() / 10.0
829}
830
831/// Columns built row by row, in px with y down.
832#[derive(Default)]
833struct Frame(Vec<(String, Vec<Value>)>);
834
835impl Frame {
836    fn col(&mut self, name: &str) -> &mut Vec<Value> {
837        let i = match self.0.iter().position(|(n, _)| n == name) {
838            Some(i) => i,
839            None => {
840                self.0.push((name.to_string(), Vec::new()));
841                self.0.len() - 1
842            }
843        };
844        &mut self.0[i].1
845    }
846    fn num(&mut self, name: &str, v: f64) -> &mut Self {
847        self.col(name).push(Value::Float(v));
848        self
849    }
850    fn txt(&mut self, name: &str, v: impl Into<String>) -> &mut Self {
851        self.col(name).push(Value::Str(v.into()));
852        self
853    }
854    fn opt(&mut self, name: &str, v: Option<String>) -> &mut Self {
855        self.col(name).push(v.map_or(Value::Na, Value::Str));
856        self
857    }
858    /// `attrs` as columns `a:<name>`.
859    fn attrs(&mut self, attrs: &[DataAttr]) -> &mut Self {
860        for (n, v) in attrs {
861            self.opt(&format!("a:{n}"), v.clone());
862        }
863        self
864    }
865    fn is_empty(&self) -> bool {
866        self.0.first().is_none_or(|(_, v)| v.is_empty())
867    }
868    /// `aes` plus a `data_attr` per `a:<name>` column, in column order.
869    fn attr_aes(&self, mut aes: Aes) -> Aes {
870        for (n, _) in &self.0 {
871            if let Some(name) = n.strip_prefix("a:") {
872                aes = aes.data_attr(name, n);
873            }
874        }
875        aes
876    }
877    /// The frame's columns, its pixel y (down) flipped to data y (up) on a
878    /// canvas `h` tall: `y` → `h - y`, and a rect's `y0`/`y1` swapped as
879    /// they flip so `y0` stays the low edge.
880    fn take(&mut self, h: f64) -> Vec<(String, Vec<Value>)> {
881        let flip = |v: Vec<Value>| -> Vec<Value> {
882            v.into_iter()
883                .map(|x| match x {
884                    Value::Float(y) => Value::Float(h - y),
885                    other => other,
886                })
887                .collect()
888        };
889        std::mem::take(&mut self.0)
890            .into_iter()
891            .map(|(n, v)| match n.as_str() {
892                "y" => (n, flip(v)),
893                "y0" => ("y1".to_string(), flip(v)),
894                "y1" => ("y0".to_string(), flip(v)),
895                _ => (n, v),
896            })
897            .collect()
898    }
899}
900
901/// Frames keyed by a colour a geom only takes as a fixed parameter (a
902/// rect's stroke), in first-seen order: one layer per colour.
903fn by_colour(v: &mut Vec<(Rgb, Frame)>, c: Rgb) -> &mut Frame {
904    let i = match v.iter().position(|(k, _)| *k == c) {
905        Some(i) => i,
906        None => {
907            v.push((c, Frame::default()));
908            v.len() - 1
909        }
910    };
911    &mut v[i].1
912}
913
914/// `aes` plus `data-state` when the frame has a `state` column (a state
915/// row's name and probability: what a click on the row names; the bars are
916/// decorative and carry none).
917fn state_attr(f: &Frame, aes: Aes) -> Aes {
918    if f.0.iter().any(|(n, _)| n == "state") {
919        aes.data_attr("state", "state")
920    } else {
921        aes
922    }
923}
924
925fn hex(c: Rgb) -> String {
926    format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
927}
928
929/// The point a fraction `t` (0..1) of the way along a polyline.
930fn point_at(pts: &[(f64, f64)], t: f64) -> (f64, f64) {
931    let seg = |i: usize| {
932        let (a, b) = (pts[i], pts[i + 1]);
933        ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
934    };
935    let total: f64 = (0..pts.len().saturating_sub(1)).map(seg).sum();
936    let mut left = total * t;
937    for i in 0..pts.len().saturating_sub(1) {
938        let l = seg(i);
939        if l >= left && l > 0.0 {
940            let t = left / l;
941            let (a, b) = (pts[i], pts[i + 1]);
942            return (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
943        }
944        left -= l;
945    }
946    pts.first().copied().unwrap_or((0.0, 0.0))
947}
948
949/// Where an edge's label goes: the midpoint of the edge, else the nearest
950/// point along it where the label's box (11 px lines drawn around `y - 4`)
951/// touches no node box — so a node doesn't cover it.
952fn edge_label_at(pts: &[(f64, f64)], label: &str, nodes: &[PlacedNode]) -> (f64, f64) {
953    let lines = label.split('\n').count();
954    let hw = edge_label_width(label) / 2.0 + 3.0;
955    let hh = lines as f64 * 6.6 + 3.0;
956    let clear = |(x, y): (f64, f64)| {
957        let cy = y - 4.0 - 0.36 * SMALL_PX;
958        nodes
959            .iter()
960            .all(|n| (x - n.cx).abs() >= hw + n.w / 2.0 || (cy - n.cy).abs() >= hh + n.h / 2.0)
961    };
962    let mid = point_at(pts, 0.5);
963    [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74, 0.18, 0.82]
964        .into_iter()
965        .map(|t| point_at(pts, t))
966        .find(|&p| clear(p))
967        .unwrap_or(mid)
968}
969
970/// An end label's anchor (as for a mid label: the text goes 4 px above
971/// it): on the edge's last (first) segment, its near side `LABEL_CLEAR`
972/// from the box the edge ends at; on a vertical segment beside the line
973/// instead, its top `LABEL_CLEAR` below (above) that box. At most half
974/// the segment in.
975fn end_label_at(pts: &[(f64, f64)], label: &str, t: f64) -> (f64, f64) {
976    use crate::graph_layout::LABEL_CLEAR;
977    let n = pts.len();
978    if n < 2 {
979        return pts.first().copied().unwrap_or((0.0, 0.0));
980    }
981    let (end, prev) = if t >= 0.5 {
982        (pts[n - 1], pts[n - 2])
983    } else {
984        (pts[0], pts[1])
985    };
986    let (dx, dy) = (prev.0 - end.0, prev.1 - end.1);
987    let len = (dx * dx + dy * dy).sqrt();
988    if len == 0.0 {
989        return end;
990    }
991    let (ux, uy) = (dx / len, dy / len);
992    let lines = label.split('\n').count() as f64;
993    let hw = edge_label_width(label) / 2.0;
994    let hh = lines * 6.6;
995    // the anchor sits 4 px + 0.36 em below the text's middle
996    let below_mid = 4.0 + 0.36 * SMALL_PX;
997    if ux.abs() >= uy.abs() {
998        // along the line, above it: its near side LABEL_CLEAR from the box
999        let s = (hw + LABEL_CLEAR).min(len * 0.5);
1000        (end.0 + ux * s, end.1 + uy * s)
1001    } else {
1002        // beside a vertical line, its top (bottom) clear of the box
1003        let s = (hh + LABEL_CLEAR).min(len * 0.5);
1004        (end.0 + LABEL_CLEAR + hw, end.1 + uy * s + below_mid)
1005    }
1006}
1007
1008/// The box (w, h px) behind an edge label set at `px`: its widest line and
1009/// its lines, plus a little room (anofox-visualization#1317).
1010fn label_box(label: &str, px: f64) -> (f64, f64) {
1011    let w = label
1012        .split('\n')
1013        .map(|l| text_w(l, px, false))
1014        .fold(0.0, f64::max);
1015    let n = label.split('\n').count() as f64;
1016    (w + 6.0, n * px * 1.2 + 3.0)
1017}
1018
1019/// Text is centred on its y (`dominant-baseline="middle"`); the layout
1020/// places lines by their baseline. A cap-height-ish shift between the two.
1021fn mid_of_baseline(baseline: f64, px: f64) -> f64 {
1022    baseline - 0.36 * px
1023}
1024
1025/// Draw a laid-out graph on a `layout.w` × `layout.h` px canvas: `lanes`
1026/// names the layout's bands, `plates` group nodes, `nodes` and `edges` are
1027/// in the layout's order.
1028/// `theme` is the base (a void theme; the legend is turned off). Render the
1029/// result with e.g. `render_svg_native_at(0.0, 0.0, w, h)` at the canvas
1030/// size rounded up.
1031pub fn draw(
1032    layout: &GraphLayout,
1033    lanes: &[String],
1034    plates: &[Plate],
1035    nodes: &[DrawNode],
1036    edges: &[DrawEdge],
1037    style: &GraphStyle,
1038    mut theme: Theme,
1039) -> GGPlot {
1040    let s = style;
1041    let class = |name: &str| format!("{}{name}", s.class_prefix);
1042    let (w, h) = (layout.w.ceil().max(1.0), layout.h.ceil().max(1.0));
1043    theme.legend_position = crate::theme::LegendPosition::None;
1044    let mut plot = GGPlot::new(vec![
1045        ("x".to_string(), vec![Value::Float(0.0), Value::Float(w)]),
1046        ("y".to_string(), vec![Value::Float(0.0), Value::Float(h)]),
1047    ])
1048    .theme(theme)
1049    // the canvas is the view (a zoom, so a mark reaching past it is clipped
1050    // rather than dropped); `Frame::take` flips the layout's y-down pixels
1051    .scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
1052    .scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
1053    .coord_cartesian_zoom(Some((0.0, w)), Some((0.0, h)))
1054    .scale_color_identity()
1055    .scale_fill_identity()
1056    .scale_linewidth(
1057        ScaleLinewidthContinuous::new()
1058            .with_limits(0.0, 16.0)
1059            .with_range(0.0, 16.0),
1060    )
1061    .scale_linetype_manual(vec![
1062        ("solid", Linetype::Solid),
1063        ("dashed", Linetype::Custom(vec![(6.0, 4.0)])),
1064        // round caps on a zero-length dash: moving dots
1065        ("dots", Linetype::Custom(vec![(0.0, 10.0)])),
1066    ]);
1067    let rect_aes = || Aes::new().xmin("x0").xmax("x1").ymin("y0").ymax("y1");
1068    let inert = [("pointer-events", "none")];
1069
1070    // swimlanes (under everything): a tinted band per lane, its name on top
1071    let (mut even, mut odd, mut names) = (Frame::default(), Frame::default(), Frame::default());
1072    for &(l, x0, y0, x1, y1) in &layout.bands {
1073        let name = lanes.get(l).cloned().unwrap_or_default();
1074        let f = if l % 2 == 0 { &mut even } else { &mut odd };
1075        f.num("x0", x0).num("x1", x1).num("y0", y0).num("y1", y1);
1076        f.txt("lane", name.clone());
1077        names
1078            .num("x", x0 + 8.0)
1079            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
1080        names.txt("label", name);
1081    }
1082    for (mut f, alpha) in [(even, 0.35), (odd, 0.18)] {
1083        if f.is_empty() {
1084            continue;
1085        }
1086        plot = plot
1087            .geom_rect_with(
1088                GeomRect {
1089                    fill: s.band,
1090                    alpha,
1091                    line_width: 0.0,
1092                    ..Default::default()
1093                }
1094                .with_radius(6.0),
1095            )
1096            .layer_data(f.take(h))
1097            .layer_aes(rect_aes().data_attr("lane", "lane"))
1098            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane"))]);
1099    }
1100    if !names.is_empty() {
1101        plot = plot
1102            .geom_text_with(GeomText {
1103                size: SMALL_PX,
1104                color: s.muted,
1105                hjust: 0.0,
1106                fontface: FontFace::Bold,
1107                ..Default::default()
1108            })
1109            .layer_data(names.take(h))
1110            .layer_aes(Aes::new().x("x").y("y").label("label"))
1111            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane-label"))]);
1112    }
1113
1114    // plates (under the edges): a dashed box around each collection
1115    let (mut pf, mut pl) = (Frame::default(), Frame::default());
1116    for p in plates {
1117        let members: Vec<&PlacedNode> = p
1118            .nodes
1119            .iter()
1120            .filter_map(|&i| layout.nodes.get(i))
1121            .collect();
1122        if members.is_empty() {
1123            continue;
1124        }
1125        let pad = 8.0;
1126        let x0 = members
1127            .iter()
1128            .map(|n| n.cx - n.w / 2.0)
1129            .fold(f64::INFINITY, f64::min)
1130            - pad;
1131        let x1 = members
1132            .iter()
1133            .map(|n| n.cx + n.w / 2.0)
1134            .fold(f64::NEG_INFINITY, f64::max)
1135            + pad;
1136        let y0 = members
1137            .iter()
1138            .map(|n| n.cy - n.h / 2.0)
1139            .fold(f64::INFINITY, f64::min)
1140            - pad
1141            - 14.0;
1142        let y1 = members
1143            .iter()
1144            .map(|n| n.cy + n.h / 2.0)
1145            .fold(f64::NEG_INFINITY, f64::max)
1146            + pad;
1147        for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] {
1148            pf.num("x", x).num("y", y).txt("lt", "dashed");
1149            pf.txt("g", p.label.clone()).txt("plate", p.label.clone());
1150        }
1151        pl.num("x", x0 + 6.0)
1152            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
1153        pl.txt("label", p.label.clone());
1154    }
1155    if !pf.is_empty() {
1156        plot = plot
1157            .geom_path_with(GeomPath::default().color(s.plate).linewidth(1.0))
1158            .layer_data(pf.take(h))
1159            .layer_aes(
1160                Aes::new()
1161                    .x("x")
1162                    .y("y")
1163                    .group("g")
1164                    .linetype("lt")
1165                    .data_attr("plate", "plate"),
1166            )
1167            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate"))]);
1168        plot = plot
1169            .geom_text_with(GeomText {
1170                size: SMALL_PX,
1171                color: s.plate,
1172                hjust: 0.0,
1173                ..Default::default()
1174            })
1175            .layer_data(pl.take(h))
1176            .layer_aes(Aes::new().x("x").y("y").label("label"))
1177            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate-label"))]);
1178    }
1179
1180    // edges (under the nodes): one path per edge, arrowed ones first
1181    let (mut ef, mut uf, mut lf) = (Frame::default(), Frame::default(), Frame::default());
1182    // a variable's name on its edge (Forney style), in the math font
1183    let mut lmf = Frame::default();
1184    // a cut edge's break mark: the gap (card-coloured) and two slashes
1185    let (mut cgap, mut cmark) = (Frame::default(), Frame::default());
1186    // a blocked edge's bar
1187    let mut bmark = Frame::default();
1188    // a card-coloured box behind each edge label: the line stops clear of
1189    // the text instead of running through it (anofox-visualization#1317)
1190    let mut lbox = Frame::default();
1191    for (k, e) in edges.iter().enumerate() {
1192        let Some(route) = layout.edges.get(k) else {
1193            continue;
1194        };
1195        let mut pts = route.clone();
1196        if pts.len() < 2 {
1197            continue;
1198        }
1199        // the arrow's tip is on the path's last point and its head is
1200        // stroked as wide as the line (its mitred tip reaching about one
1201        // line width further): end the path one width short of the box so
1202        // the tip lands on its edge.
1203        if !e.undirected {
1204            let n = pts.len();
1205            let ((fx, fy), (tx, ty)) = (pts[n - 2], pts[n - 1]);
1206            let len = ((tx - fx).powi(2) + (ty - fy).powi(2)).sqrt().max(1e-6);
1207            let pull = e.width.min(len / 2.0);
1208            pts[n - 1] = (tx - (tx - fx) / len * pull, ty - (ty - fy) / len * pull);
1209        }
1210        if e.cut {
1211            let total: f64 = pts
1212                .windows(2)
1213                .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt())
1214                .sum();
1215            if total > 16.0 {
1216                let (mx, my) = point_at(&pts, 0.5);
1217                let (ax, ay) = point_at(&pts, 0.5 - 2.0 / total);
1218                let (bx, by) = point_at(&pts, 0.5 + 2.0 / total);
1219                let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt().max(1e-6);
1220                let (ux, uy) = ((bx - ax) / len, (by - ay) / len);
1221                let g = format!("c{k:04}");
1222                for d in [-4.0, 4.0] {
1223                    cgap.num("x", mx + ux * d).num("y", my + uy * d);
1224                    cgap.txt("g", g.clone()).num("lw", e.width + 2.5);
1225                    cgap.attrs(&e.label_attrs);
1226                }
1227                // each slash across the line, leaning 30° along it
1228                let (c30, s30) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
1229                let (vx, vy) = (-uy * c30 + ux * s30, ux * c30 + uy * s30);
1230                for (i, off) in [-3.5, 3.5].into_iter().enumerate() {
1231                    let (cx, cy) = (mx + ux * off, my + uy * off);
1232                    for t in [-5.0, 5.0] {
1233                        cmark.num("x", cx + vx * t).num("y", cy + vy * t);
1234                        cmark.txt("g", format!("{g}-{i}")).txt("col", hex(e.colour));
1235                        cmark.attrs(&e.label_attrs);
1236                    }
1237                }
1238            }
1239        }
1240        if e.blocked {
1241            let total: f64 = pts
1242                .windows(2)
1243                .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt())
1244                .sum();
1245            if total > 12.0 {
1246                let (mx, my) = point_at(&pts, 0.5);
1247                let (ax, ay) = point_at(&pts, 0.5 - 2.0 / total);
1248                let (bx, by) = point_at(&pts, 0.5 + 2.0 / total);
1249                let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt().max(1e-6);
1250                let (vx, vy) = (-(by - ay) / len, (bx - ax) / len);
1251                let half = 6.0 + e.width;
1252                for t in [-half, half] {
1253                    bmark.num("x", mx + vx * t).num("y", my + vy * t);
1254                    bmark.txt("g", format!("b{k:04}")).txt("col", hex(e.colour));
1255                    bmark.attrs(&e.label_attrs);
1256                }
1257            }
1258        }
1259        let ef = if e.undirected { &mut uf } else { &mut ef };
1260        let lt = match e.line {
1261            EdgeLine::Solid => "solid",
1262            EdgeLine::Dashed => "dashed",
1263            EdgeLine::Dots => "dots",
1264        };
1265        for &(x, y) in &pts {
1266            ef.num("x", x).num("y", y).txt("g", format!("e{k:04}"));
1267            ef.txt("col", hex(e.colour))
1268                .num("lw", e.width)
1269                .txt("lt", lt);
1270            ef.opt("cls", e.class.clone()).txt("tip", e.tooltip.clone());
1271            ef.attrs(&e.attrs);
1272        }
1273        // a bus-routed edge's label is left to its tooltip: on the shared
1274        // lane or at a shared entry it would only clutter
1275        let routed = layout.routed.get(k).copied().unwrap_or(false);
1276        if let Some(l) = e.label.as_ref().filter(|_| !routed) {
1277            let (mx, my) = match e.label_at {
1278                // near an end (a factor's interface): beside the box at
1279                // that end, clear of it (anofox-visualization#1238)
1280                Some(t) => end_label_at(route, l, t),
1281                None => edge_label_at(route, l, &layout.nodes),
1282            };
1283            let math = e.label_math && s.math_font.is_some();
1284            let (f, px) = if math {
1285                (&mut lmf, LABEL_PX + 1.0)
1286            } else {
1287                (&mut lf, SMALL_PX)
1288            };
1289            let y = mid_of_baseline(my - 4.0, SMALL_PX);
1290            f.num("x", mx).num("y", y);
1291            f.txt("label", l.clone());
1292            f.attrs(&e.label_attrs);
1293            let (bw, bh) = label_box(l, px);
1294            lbox.num("x0", mx - bw / 2.0)
1295                .num("x1", mx + bw / 2.0)
1296                .num("y0", y - bh / 2.0)
1297                .num("y1", y + bh / 2.0);
1298        }
1299    }
1300    for (mut f, arrowed) in [(ef, true), (uf, false)] {
1301        if f.is_empty() {
1302            continue;
1303        }
1304        let aes = f.attr_aes(
1305            Aes::new()
1306                .x("x")
1307                .y("y")
1308                .group("g")
1309                .color("col")
1310                .linewidth("lw")
1311                .linetype("lt")
1312                .class("cls")
1313                .tooltip("tip"),
1314        );
1315        let mut geom = GeomPath::default().lineend(LineEnd::Round);
1316        if arrowed {
1317            // a 7 px + width head, ~29° half-angle
1318            geom = geom.arrow(
1319                arrow()
1320                    .closed()
1321                    .angle(29.0)
1322                    .length(ARROW + 1.0)
1323                    .length_per_linewidth(1.2),
1324            );
1325        }
1326        plot = plot
1327            .geom_path_with(geom)
1328            .layer_data(f.take(h))
1329            .layer_aes(aes)
1330            .layer_svg_attr("class", class("edge"));
1331    }
1332    if !cgap.is_empty() {
1333        let aes = cgap.attr_aes(Aes::new().x("x").y("y").group("g").linewidth("lw"));
1334        plot = plot
1335            .geom_path_with(GeomPath::default().color(s.card).lineend(LineEnd::Butt))
1336            .layer_data(cgap.take(h))
1337            .layer_aes(aes)
1338            .decorative()
1339            .layer_svg_attrs(inert)
1340            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-cut"))]);
1341        let aes = cmark.attr_aes(Aes::new().x("x").y("y").group("g").color("col"));
1342        plot = plot
1343            .geom_path_with(GeomPath::default().linewidth(1.4).lineend(LineEnd::Round))
1344            .layer_data(cmark.take(h))
1345            .layer_aes(aes)
1346            .decorative()
1347            .layer_svg_attrs(inert)
1348            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-cut"))]);
1349    }
1350    if !bmark.is_empty() {
1351        let aes = bmark.attr_aes(Aes::new().x("x").y("y").group("g").color("col"));
1352        plot = plot
1353            .geom_path_with(GeomPath::default().linewidth(2.4).lineend(LineEnd::Butt))
1354            .layer_data(bmark.take(h))
1355            .layer_aes(aes)
1356            .decorative()
1357            .layer_svg_attrs(inert)
1358            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-block"))]);
1359    }
1360    if !lbox.is_empty() {
1361        plot = plot
1362            .geom_rect_with(
1363                GeomRect {
1364                    fill: s.card,
1365                    alpha: 1.0,
1366                    line_width: 0.0,
1367                    ..Default::default()
1368                }
1369                .with_radius(3.0),
1370            )
1371            .layer_data(lbox.take(h))
1372            .layer_aes(rect_aes())
1373            .decorative()
1374            .layer_svg_attrs(inert)
1375            .layer_svg_attrs([
1376                ("aria-hidden", "true"),
1377                ("class", &*class("edge-label-box")),
1378            ]);
1379    }
1380    if !lmf.is_empty() {
1381        let aes = lmf.attr_aes(Aes::new().x("x").y("y").label("label"));
1382        plot = plot
1383            .geom_text_with(
1384                GeomText {
1385                    size: LABEL_PX + 1.0,
1386                    color: s.heading,
1387                    fontface: FontFace::Italic,
1388                    fontfamily: s.math_font.clone().unwrap_or_default(),
1389                    ..Default::default()
1390                }
1391                .bg_colour(s.card)
1392                .bg_r(2.0),
1393            )
1394            .layer_data(lmf.take(h))
1395            .layer_aes(aes)
1396            .layer_svg_attrs(inert)
1397            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
1398    }
1399    if !lf.is_empty() {
1400        // text directly on the line, a card-coloured halo keeping it legible
1401        let aes = lf.attr_aes(Aes::new().x("x").y("y").label("label"));
1402        plot = plot
1403            .geom_text_with(
1404                GeomText {
1405                    size: SMALL_PX,
1406                    color: s.muted,
1407                    ..Default::default()
1408                }
1409                .bg_colour(s.card)
1410                .bg_r(2.0),
1411            )
1412            .layer_data(lf.take(h))
1413            .layer_aes(aes)
1414            .layer_svg_attrs(inert)
1415            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
1416    }
1417
1418    // nodes in reading order: the box (the hit target, outside any `data-of`
1419    // group), then what it shows, grouped per node
1420    let mut order: Vec<usize> = (0..nodes.len().min(layout.nodes.len())).collect();
1421    order.sort_by_key(|&i| (layout.nodes[i].order, i));
1422    // boxes, a layer per (outline, shape, fill)
1423    let mut boxes: Vec<((Rgb, NodeShape, Rgb), Frame)> = Vec::new();
1424    // a double box's inner outline, by colour
1425    let mut outlines: Vec<(Rgb, Frame)> = Vec::new();
1426    // a diamond's hit target (an invisible box) and its mark, by outline
1427    let (mut hits, mut diamonds) = (Frame::default(), Vec::<(Rgb, Frame)>::new());
1428    // state rows: the prior's faint bar, its tick, the bar, the names (the
1429    // observed one bold) and the probabilities
1430    let (mut sprior, mut stick, mut sbar) = (Frame::default(), Frame::default(), Frame::default());
1431    let (mut sname, mut sseen, mut stext) = (Frame::default(), Frame::default(), Frame::default());
1432    // a state's change (▲ up in the heading colour, bold; ▼ down muted)
1433    let (mut sup, mut sdown) = (Frame::default(), Frame::default());
1434    // a node's table: the current row's band, the marked cells' tint, the
1435    // header (left, right), the row names, the cells and the marked cells
1436    let (mut tband, mut tmarkbg) = (Frame::default(), Frame::default());
1437    let (mut thead_l, mut thead_r) = (Frame::default(), Frame::default());
1438    let (mut tname, mut tcell, mut tmark) = (Frame::default(), Frame::default(), Frame::default());
1439    // an icon's badge, its rounded rects and polygons
1440    let (mut ibadge, mut irect, mut ipoly) = (Frame::default(), Frame::default(), Frame::default());
1441    // an icon's letter; a ring around a box, by colour
1442    let mut iletter = Frame::default();
1443    let mut rings: Vec<(Rgb, Frame)> = Vec::new();
1444    let mut beliefs = Frame::default();
1445    let mut priors = Frame::default();
1446    // a continuous node's density: its interval, the marked value, the text
1447    let (mut dband, mut dmark, mut dtext) = (Frame::default(), Frame::default(), Frame::default());
1448    // shaped nodes, a layer per (shape, corner radius, outline)
1449    let mut shaped: Vec<((NodeShape, u64, Rgb), Frame)> = Vec::new();
1450    let (mut inside, mut inverse, mut above, mut glyphs, mut texts, mut beside) = (
1451        Frame::default(),
1452        Frame::default(),
1453        Frame::default(),
1454        Frame::default(),
1455        Frame::default(),
1456        Frame::default(),
1457    );
1458    let mut badges: Vec<(Rgb, Frame)> = Vec::new();
1459    let (mut accent, mut lines, mut values) =
1460        (Frame::default(), Frame::default(), Frame::default());
1461    let (mut dots, mut btext, mut spark, mut ends) = (
1462        Frame::default(),
1463        Frame::default(),
1464        Frame::default(),
1465        Frame::default(),
1466    );
1467    for v in order {
1468        let nd = &nodes[v];
1469        let pn = &layout.nodes[v];
1470        let id = nd.id.clone();
1471        let (x, y) = (pn.cx - pn.w / 2.0, pn.cy - pn.h / 2.0);
1472        // the belief curve sits over the node (over a square's label)
1473        let squared = matches!(nd.shape, NodeShape::Square | NodeShape::FilledSquare);
1474        let base = y - if squared { 17.0 } else { 3.0 };
1475        let x0 = pn.cx - BELIEF_W / 2.0;
1476        let curve = |hs: &[f64]| -> Vec<(f64, f64)> {
1477            let last = (hs.len() - 1) as f64;
1478            hs.iter()
1479                .enumerate()
1480                .map(|(i, &h)| {
1481                    (
1482                        x0 + BELIEF_W * i as f64 / last,
1483                        base - h.clamp(0.0, 1.0) * BELIEF_H,
1484                    )
1485                })
1486                .collect()
1487        };
1488        // the prior: a faint outline behind the belief
1489        if let Some((hs, col)) = nd.prior.as_ref().filter(|(h, _)| h.len() >= 3) {
1490            for (px, py) in curve(hs) {
1491                priors.num("x", px).num("y", py).txt("g", id.clone());
1492                priors.txt("col", hex(*col)).txt("lt", "dashed");
1493                priors.txt("of", id.clone());
1494            }
1495        }
1496        if let Some((hs, col)) = nd.belief.as_ref().filter(|(h, _)| h.len() >= 3) {
1497            let mut pts = curve(hs);
1498            pts.push((x0 + BELIEF_W, base));
1499            pts.push((x0, base));
1500            for (px, py) in pts {
1501                beliefs.num("x", px).num("y", py).txt("g", id.clone());
1502                beliefs.txt("fill", hex(*col)).txt("of", id.clone());
1503            }
1504        }
1505        if let Some(c) = nd
1506            .ring
1507            .filter(|_| nd.shape.boxed() || nd.shape == NodeShape::Diamond)
1508        {
1509            let f = by_colour(&mut rings, c);
1510            f.num("x0", x - 4.0)
1511                .num("x1", x + pn.w + 4.0)
1512                .num("y0", y - 4.0)
1513                .num("y1", y + pn.h + 4.0);
1514            f.txt("of", id.clone());
1515        }
1516        if nd.shape == NodeShape::Diamond {
1517            hits.num("x0", x)
1518                .num("x1", x + pn.w)
1519                .num("y0", y)
1520                .num("y1", y + pn.h);
1521            hits.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1522            let f = by_colour(&mut diamonds, nd.stroke);
1523            for (px, py) in [(pn.cx, y), (x + pn.w, pn.cy), (pn.cx, y + pn.h), (x, pn.cy)] {
1524                f.num("x", px).num("y", py).txt("g", id.clone());
1525                f.txt("fill", hex(nd.fill.unwrap_or(s.card)))
1526                    .txt("of", id.clone());
1527            }
1528            // the label (and value) centred in it
1529            let n = nd.lines.len() + usize::from(nd.value.is_some());
1530            let mut base = pn.cy - LINE_H * n as f64 / 2.0 + 12.0;
1531            for line in &nd.lines {
1532                lines
1533                    .num("x", pn.cx)
1534                    .num("y", mid_of_baseline(base, LABEL_PX));
1535                lines.txt("label", line.clone()).txt("of", id.clone());
1536                base += LINE_H;
1537            }
1538            if let Some(fv) = &nd.value {
1539                values
1540                    .num("x", pn.cx)
1541                    .num("y", mid_of_baseline(base, VALUE_PX));
1542                values.txt("label", fv.clone()).txt("of", id.clone());
1543            }
1544            continue;
1545        }
1546        if !nd.shape.boxed() {
1547            let r = match nd.shape {
1548                NodeShape::Circle | NodeShape::FilledCircle => pn.w.min(pn.h) / 2.0,
1549                NodeShape::Square | NodeShape::FilledSquare | NodeShape::Terminal => 1.5,
1550                NodeShape::Glyph => 4.0,
1551                _ => 0.0,
1552            };
1553            let (fill, stroke) = match nd.shape {
1554                NodeShape::Circle => (s.variable_fill, nd.stroke),
1555                // a filled mark takes the node's accent (a status: an
1556                // observation the model did not expect) over the observed fill
1557                NodeShape::FilledCircle | NodeShape::FilledSquare | NodeShape::Terminal => {
1558                    let c = nd.accent.unwrap_or(s.observed_fill);
1559                    (c, c)
1560                }
1561                NodeShape::Square => (s.card, nd.stroke),
1562                NodeShape::Glyph => (s.glyph_fill.unwrap_or(s.card), nd.stroke),
1563                _ => (s.card, s.card),
1564            };
1565            let key = (nd.shape, r.to_bits(), stroke);
1566            let i = match shaped.iter().position(|(k, _)| *k == key) {
1567                Some(i) => i,
1568                None => {
1569                    shaped.push((key, Frame::default()));
1570                    shaped.len() - 1
1571                }
1572            };
1573            let f = &mut shaped[i].1;
1574            f.num("x0", x)
1575                .num("x1", x + pn.w)
1576                .num("y0", y)
1577                .num("y1", y + pn.h);
1578            f.txt("fill", hex(fill));
1579            f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1580            let label = nd.lines.join(" ");
1581            if label.is_empty() {
1582                continue;
1583            }
1584            let target = match nd.shape {
1585                NodeShape::Glyph => &mut glyphs,
1586                NodeShape::FilledCircle => &mut inverse,
1587                NodeShape::Square | NodeShape::FilledSquare => &mut above,
1588                // a constant is a number: upright, never the math italic
1589                NodeShape::Text => &mut texts,
1590                NodeShape::Terminal => &mut beside,
1591                _ => &mut inside,
1592            };
1593            let ly = match nd.shape {
1594                NodeShape::Square | NodeShape::FilledSquare => y - 4.0 - 0.36 * SMALL_PX,
1595                _ => pn.cy,
1596            };
1597            // a terminal's label starts just right of it
1598            let lx = match nd.shape {
1599                NodeShape::Terminal => x + pn.w + 5.0,
1600                _ => pn.cx,
1601            };
1602            target.num("x", lx).num("y", ly);
1603            target.txt("label", label).txt("of", id.clone());
1604            continue;
1605        }
1606        // a node without a fill of its own: tinted by how far it moved
1607        let fill = nd.fill.unwrap_or_else(|| {
1608            match (
1609                s.moved,
1610                nd.states.as_ref().and_then(|(r, _)| moved_share(r)),
1611            ) {
1612                (Some(c), Some(t)) => mix(s.card, c, t),
1613                _ => s.card,
1614            }
1615        });
1616        let key = (nd.stroke, nd.shape, fill);
1617        let i = match boxes.iter().position(|(k, _)| *k == key) {
1618            Some(i) => i,
1619            None => {
1620                boxes.push((key, Frame::default()));
1621                boxes.len() - 1
1622            }
1623        };
1624        let f = &mut boxes[i].1;
1625        if nd.shape == NodeShape::DoubleBox {
1626            let o = by_colour(&mut outlines, nd.stroke);
1627            o.num("x0", x + 3.5)
1628                .num("x1", x + pn.w - 3.5)
1629                .num("y0", y + 3.5)
1630                .num("y1", y + pn.h - 3.5);
1631            o.txt("of", id.clone());
1632        }
1633        f.num("x0", x)
1634            .num("x1", x + pn.w)
1635            .num("y0", y)
1636            .num("y1", y + pn.h);
1637        f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1638        // the icon in a round badge on the top right corner
1639        let (bx, by) = (x + pn.w - 11.0, y - 7.0);
1640        if nd.icon.is_some() {
1641            ibadge
1642                .num("x0", bx)
1643                .num("x1", bx + 18.0)
1644                .num("y0", by)
1645                .num("y1", by + 18.0);
1646            ibadge.txt("of", id.clone());
1647        }
1648        if let Some(NodeIcon::Letter(c)) = nd.icon {
1649            iletter
1650                .num("x", bx + 9.0)
1651                .num("y", mid_of_baseline(by + 13.0, BADGE_PX));
1652            iletter.txt("label", c.to_string()).txt("of", id.clone());
1653        }
1654        if let Some(NodeIcon::Hand) = nd.icon {
1655            let (ox, oy) = (bx + 3.0, by + 3.0);
1656            for (x0, y0, x1, y1) in HAND_RECTS {
1657                irect
1658                    .num("x0", ox + x0)
1659                    .num("x1", ox + x1)
1660                    .num("y0", oy + y0)
1661                    .num("y1", oy + y1);
1662                irect.txt("of", id.clone());
1663            }
1664            for (px, py) in HAND_THUMB {
1665                ipoly.num("x", ox + px).num("y", oy + py);
1666                ipoly.txt("g", id.clone()).txt("of", id.clone());
1667            }
1668        }
1669
1670        if let Some(a) = nd.accent {
1671            accent.num("x0", x + 1.5).num("x1", x + 4.5);
1672            accent
1673                .num("y0", y + 6.0)
1674                .num("y1", y + 6.0 + (pn.h - 12.0).max(4.0));
1675            accent.txt("fill", hex(a)).txt("of", id.clone());
1676        }
1677        let mut base = y + BOX_PAD_Y + 12.0;
1678        for line in &nd.lines {
1679            lines
1680                .num("x", pn.cx)
1681                .num("y", mid_of_baseline(base, LABEL_PX));
1682            lines.txt("label", line.clone()).txt("of", id.clone());
1683            base += LINE_H;
1684        }
1685        if let Some(fv) = &nd.value {
1686            values
1687                .num("x", pn.cx)
1688                .num("y", mid_of_baseline(base, VALUE_PX));
1689            values.txt("label", fv.clone()).txt("of", id.clone());
1690            base += LINE_H;
1691        }
1692        if let Some((b, dot)) = &nd.badge {
1693            let bw = text_w(b, BADGE_PX, false) + 20.0;
1694            let (bx, by) = (pn.cx - bw / 2.0, base - 9.0);
1695            let f = by_colour(&mut badges, *dot);
1696            f.num("x0", bx)
1697                .num("x1", bx + bw)
1698                .num("y0", by)
1699                .num("y1", by + 16.0);
1700            f.txt("of", id.clone());
1701            dots.num("x", bx + 9.0).num("y", by + 8.0);
1702            dots.txt("col", hex(*dot)).txt("of", id.clone());
1703            btext.num("x", bx + 15.0).num("y", by + 8.0);
1704            btext.txt("label", b.clone()).txt("of", id.clone());
1705            base += 20.0;
1706        }
1707        // the states, a row each: name, the prior's faint bar with a tick
1708        // where it ends, the bar, the probability
1709        if let Some((rows, colour)) = nd.states.as_ref().filter(|(r, _)| !r.is_empty()) {
1710            let names = rows
1711                .iter()
1712                .map(|r| text_w(&state_name(&r.name), SMALL_PX, true))
1713                .fold(0.0, f64::max);
1714            let bx = x + BOX_PAD_X + names + STATE_GAP;
1715            let delta = if rows.iter().any(|r| r.was.is_some()) {
1716                STATE_DELTA_W
1717            } else {
1718                0.0
1719            };
1720            // the bar takes what the box leaves it, at most its full length
1721            let bw = (pn.w - 2.0 * BOX_PAD_X - names - 2.0 * STATE_GAP - STATE_TEXT_W - delta)
1722                .clamp(16.0, STATE_BAR_W);
1723            base += 4.0;
1724            for r in rows {
1725                let cy = mid_of_baseline(base, SMALL_PX);
1726                let f = if r.observed { &mut sseen } else { &mut sname };
1727                f.num("x", x + BOX_PAD_X).num("y", cy);
1728                f.txt("label", state_name(&r.name)).txt("of", id.clone());
1729                f.txt("state", r.name.clone());
1730                if let Some(q) = r.prior {
1731                    let q = if q.is_finite() {
1732                        q.clamp(0.0, 1.0)
1733                    } else {
1734                        0.0
1735                    };
1736                    sprior
1737                        .num("x0", bx)
1738                        .num("x1", bx + bw * q)
1739                        .num("y0", cy - 5.0)
1740                        .num("y1", cy + 5.0);
1741                    sprior.txt("fill", hex(s.muted)).txt("of", id.clone());
1742                    stick
1743                        .num("x0", bx + bw * q - 0.75)
1744                        .num("x1", bx + bw * q + 0.75)
1745                        .num("y0", cy - 6.0)
1746                        .num("y1", cy + 6.0);
1747                    stick.txt("fill", hex(s.muted)).txt("of", id.clone());
1748                }
1749                let p = if r.p.is_finite() {
1750                    r.p.clamp(0.0, 1.0)
1751                } else {
1752                    0.0
1753                };
1754                sbar.num("x0", bx)
1755                    .num("x1", bx + bw * p)
1756                    .num("y0", cy - 3.5)
1757                    .num("y1", cy + 3.5);
1758                sbar.txt("fill", hex(*colour)).txt("of", id.clone());
1759                stext.num("x", bx + bw + STATE_GAP).num("y", cy);
1760                stext.txt("label", r.text.clone()).txt("of", id.clone());
1761                stext.txt("state", r.name.clone());
1762                if let Some((t, up)) = r.was.and_then(|w| delta_text(p, w)) {
1763                    let f = if up { &mut sup } else { &mut sdown };
1764                    f.num("x", bx + bw + STATE_GAP + STATE_TEXT_W).num("y", cy);
1765                    f.txt("label", t).txt("of", id.clone());
1766                }
1767                base += STATE_H;
1768            }
1769        }
1770        // a continuous node's density: the prior behind, the curve, the
1771        // interval darker under it, the marked value across, the text under
1772        if let Some((d, colour)) = nd
1773            .density
1774            .as_ref()
1775            .filter(|(d, _)| d.heights.len() >= 3 && nd.shape.boxed())
1776        {
1777            let w = DENSITY_W.min(pn.w - 2.0 * BOX_PAD_X);
1778            let x0 = pn.cx - w / 2.0;
1779            // `base` is the next text baseline: the curve starts just under
1780            // the label, the text line on the box's last row
1781            let floor = base - 6.0 + DENSITY_H;
1782            let g = format!("{id}\u{1f}d");
1783            if let Some(hs) = d.prior.as_ref().filter(|h| h.len() >= 3) {
1784                let last = (hs.len() - 1) as f64;
1785                for (i, v) in hs.iter().enumerate() {
1786                    priors.num("x", x0 + w * i as f64 / last);
1787                    priors.num("y", floor - v.clamp(0.0, 1.0) * DENSITY_H);
1788                    priors.txt("g", g.clone()).txt("col", hex(s.muted));
1789                    priors.txt("lt", "dashed").txt("of", id.clone());
1790                }
1791            }
1792            for (px, py) in area_between(&d.heights, 0.0, 1.0, x0, w, floor, DENSITY_H) {
1793                beliefs.num("x", px).num("y", py).txt("g", g.clone());
1794                beliefs.txt("fill", hex(*colour)).txt("of", id.clone());
1795            }
1796            if let Some((a, b)) = d.band.filter(|(a, b)| b > a) {
1797                for (px, py) in area_between(&d.heights, a, b, x0, w, floor, DENSITY_H) {
1798                    dband.num("x", px).num("y", py).txt("g", g.clone());
1799                    dband.txt("fill", hex(*colour)).txt("of", id.clone());
1800                }
1801            }
1802            if let Some(m) = d.marker.filter(|m| m.is_finite()) {
1803                let mx = x0 + w * m.clamp(0.0, 1.0);
1804                dmark
1805                    .num("x0", mx - 0.75)
1806                    .num("x1", mx + 0.75)
1807                    .num("y0", floor - DENSITY_H - 2.0)
1808                    .num("y1", floor + 1.0);
1809                dmark.txt("fill", hex(s.heading)).txt("of", id.clone());
1810            }
1811            base = floor + 13.0;
1812            if !d.text.is_empty() {
1813                dtext
1814                    .num("x", pn.cx)
1815                    .num("y", mid_of_baseline(base, SMALL_PX));
1816                dtext.txt("label", d.text.clone()).txt("of", id.clone());
1817            }
1818            base += STATE_H;
1819        }
1820        // a table (an influence diagram's policy): the header, then a row
1821        // each; the first column left, the others right-aligned
1822        if let Some((t, colour)) = nd.table.as_ref().filter(|(t, _)| !t.rows.is_empty()) {
1823            let widths = t.widths();
1824            let x0 = pn.cx - t.width() / 2.0;
1825            // each column's left and right edge
1826            let mut edges = Vec::with_capacity(widths.len());
1827            let mut cx = x0;
1828            for w in &widths {
1829                edges.push((cx, cx + w));
1830                cx += w + TABLE_GAP;
1831            }
1832            base += 4.0;
1833            if t.has_header() {
1834                let cy = mid_of_baseline(base, SMALL_PX);
1835                for (c, h) in t.header.iter().enumerate().filter(|(_, h)| !h.is_empty()) {
1836                    let (f, hx) = if c == 0 {
1837                        (&mut thead_l, edges[c].0)
1838                    } else {
1839                        (&mut thead_r, edges[c].1)
1840                    };
1841                    f.num("x", hx).num("y", cy);
1842                    f.txt("label", t.cell(c, h)).txt("of", id.clone());
1843                    if c > 0 {
1844                        f.opt("state", t.key(c));
1845                    }
1846                }
1847                base += STATE_H;
1848            }
1849            for (k, row) in t.rows.iter().enumerate() {
1850                let cy = mid_of_baseline(base, SMALL_PX);
1851                if t.current == Some(k) {
1852                    tband
1853                        .num("x0", x + 4.0)
1854                        .num("x1", x + pn.w - 4.0)
1855                        .num("y0", cy - 7.0)
1856                        .num("y1", cy + 7.0);
1857                    tband.txt("fill", hex(s.muted)).txt("of", id.clone());
1858                }
1859                let mark = t.marked.get(k).copied().flatten();
1860                for (c, cell) in row.iter().enumerate().take(edges.len()) {
1861                    let marked = c > 0 && mark == Some(c);
1862                    if marked {
1863                        tmarkbg
1864                            .num("x0", edges[c].0 - 3.0)
1865                            .num("x1", edges[c].1 + 3.0)
1866                            .num("y0", cy - 6.5)
1867                            .num("y1", cy + 6.5);
1868                        tmarkbg.txt("fill", hex(*colour)).txt("of", id.clone());
1869                    }
1870                    let (f, cx) = match (c, marked) {
1871                        (0, _) => (&mut tname, edges[c].0),
1872                        (_, true) => (&mut tmark, edges[c].1),
1873                        _ => (&mut tcell, edges[c].1),
1874                    };
1875                    f.num("x", cx).num("y", cy);
1876                    f.txt("label", t.cell(c, cell)).txt("of", id.clone());
1877                    if c > 0 {
1878                        f.opt("state", t.key(c));
1879                    }
1880                }
1881                base += STATE_H;
1882            }
1883        }
1884        // a mini trend along the bottom of the box
1885        if let Some((values, colour)) = nd.spark.as_ref().filter(|(v, _)| v.len() >= 2) {
1886            let (lo, hi) = values
1887                .iter()
1888                .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
1889                    (a.min(v), b.max(v))
1890                });
1891            let rng = if hi > lo { hi - lo } else { 1.0 };
1892            let (sx0, sw) = (x + BOX_PAD_X, pn.w - 2.0 * BOX_PAD_X);
1893            let (top, sh) = (base - 8.0, SPARK_H - 8.0);
1894            let last = values.len() - 1;
1895            let col = hex(*colour);
1896            for (i, &sv) in values.iter().enumerate() {
1897                let (px, py) = (
1898                    sx0 + sw * i as f64 / last as f64,
1899                    top + sh - (sv - lo) / rng * sh,
1900                );
1901                spark.num("x", px).num("y", py).txt("g", id.clone());
1902                spark.txt("col", col.clone()).txt("of", id.clone());
1903                if i == last {
1904                    ends.num("x", px).num("y", py);
1905                    ends.txt("col", col.clone()).txt("of", id.clone());
1906                }
1907            }
1908        }
1909    }
1910    for ((stroke, shape, fill), mut f) in boxes {
1911        let aes = f.attr_aes(rect_aes().tooltip("tip"));
1912        let cls = match shape {
1913            NodeShape::Box => class("node"),
1914            _ => format!(
1915                "{} {}",
1916                class("node"),
1917                class(&format!("node-{}", shape.name()))
1918            ),
1919        };
1920        plot = plot
1921            .geom_rect_with(
1922                GeomRect {
1923                    fill,
1924                    color: stroke,
1925                    alpha: 1.0,
1926                    line_width: 1.2,
1927                    ..Default::default()
1928                }
1929                .with_radius(if shape == NodeShape::Rect { 0.0 } else { 8.0 }),
1930            )
1931            .layer_data(f.take(h))
1932            .layer_aes(aes)
1933            .layer_svg_attr("class", cls);
1934    }
1935    // a ring around a singled-out node, outside its box (after the boxes:
1936    // the first `data-of` group of a node holds what it shows)
1937    for (c, mut f) in rings {
1938        plot = plot
1939            .geom_rect_with(
1940                GeomRect {
1941                    fill: s.card,
1942                    color: c,
1943                    alpha: 0.0,
1944                    line_width: 2.0,
1945                    ..Default::default()
1946                }
1947                .with_radius(11.0),
1948            )
1949            .layer_data(f.take(h))
1950            .layer_aes(rect_aes().group_wrap("of", "of"))
1951            .decorative()
1952            .layer_svg_attrs(inert)
1953            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-ring"))]);
1954    }
1955    if !hits.is_empty() {
1956        // a diamond's hit target: its bounding box, invisible
1957        let aes = hits.attr_aes(rect_aes().tooltip("tip"));
1958        let cls = format!("{} {}", class("node"), class("node-diamond"));
1959        plot = plot
1960            .geom_rect_with(GeomRect {
1961                fill: s.card,
1962                alpha: 0.0,
1963                line_width: 0.0,
1964                ..Default::default()
1965            })
1966            .layer_data(hits.take(h))
1967            .layer_aes(aes)
1968            .layer_svg_attr("class", cls);
1969    }
1970    for ((shape, r, stroke), mut f) in shaped {
1971        let aes = f.attr_aes(rect_aes().fill("fill").tooltip("tip"));
1972        let cls = format!(
1973            "{} {}",
1974            class("node"),
1975            class(&format!("node-{}", shape.name()))
1976        );
1977        plot = plot
1978            .geom_rect_with(
1979                GeomRect {
1980                    color: stroke,
1981                    alpha: 1.0,
1982                    line_width: if shape == NodeShape::Text { 0.0 } else { 1.2 },
1983                    ..Default::default()
1984                }
1985                .with_radius(f64::from_bits(r)),
1986            )
1987            .layer_data(f.take(h))
1988            .layer_aes(aes)
1989            .layer_svg_attr("class", cls);
1990    }
1991    if !priors.is_empty() {
1992        plot = plot
1993            .geom_path_with(GeomPath {
1994                alpha: 0.7,
1995                ..GeomPath::default().linewidth(1.0)
1996            })
1997            .layer_data(priors.take(h))
1998            .layer_aes(
1999                Aes::new()
2000                    .x("x")
2001                    .y("y")
2002                    .group("g")
2003                    .color("col")
2004                    .linetype("lt")
2005                    .group_wrap("of", "of"),
2006            )
2007            .decorative()
2008            .layer_svg_attrs(inert)
2009            .layer_svg_attr("class", class("node-prior"));
2010    }
2011    if !beliefs.is_empty() {
2012        plot = plot
2013            .geom_polygon_with(GeomPolygon {
2014                alpha: 0.45,
2015                line_width: 0.0,
2016                ..Default::default()
2017            })
2018            .layer_data(beliefs.take(h))
2019            .layer_aes(
2020                Aes::new()
2021                    .x("x")
2022                    .y("y")
2023                    .group("g")
2024                    .fill("fill")
2025                    .group_wrap("of", "of"),
2026            )
2027            .decorative()
2028            .layer_svg_attrs(inert)
2029            .layer_svg_attr("class", class("node-belief"));
2030    }
2031    if !dband.is_empty() {
2032        plot = plot
2033            .geom_polygon_with(GeomPolygon {
2034                alpha: 0.5,
2035                line_width: 0.0,
2036                ..Default::default()
2037            })
2038            .layer_data(dband.take(h))
2039            .layer_aes(
2040                Aes::new()
2041                    .x("x")
2042                    .y("y")
2043                    .group("g")
2044                    .fill("fill")
2045                    .group_wrap("of", "of"),
2046            )
2047            .decorative()
2048            .layer_svg_attrs(inert)
2049            .layer_svg_attr("class", class("node-density-band"));
2050    }
2051    // everything below: dims / lights with its node (`data-of`), inert
2052    let of = |a: Aes| a.group_wrap("of", "of");
2053    if !accent.is_empty() {
2054        plot = plot
2055            .geom_rect_with(
2056                GeomRect {
2057                    alpha: 1.0,
2058                    line_width: 0.0,
2059                    ..Default::default()
2060                }
2061                .with_radius(1.5),
2062            )
2063            .layer_data(accent.take(h))
2064            .layer_aes(of(rect_aes().fill("fill")))
2065            .decorative()
2066            .layer_svg_attrs(inert);
2067    }
2068    for (stroke, mut f) in outlines {
2069        plot = plot
2070            .geom_rect_with(
2071                GeomRect {
2072                    fill: s.card,
2073                    color: stroke,
2074                    alpha: 0.0,
2075                    line_width: 1.0,
2076                    ..Default::default()
2077                }
2078                .with_radius(5.5),
2079            )
2080            .layer_data(f.take(h))
2081            .layer_aes(of(rect_aes()))
2082            .decorative()
2083            .layer_svg_attrs(inert)
2084            .layer_svg_attr("class", class("node-outline"));
2085    }
2086    for (stroke, mut f) in diamonds {
2087        plot = plot
2088            .geom_polygon_with(GeomPolygon {
2089                color: stroke,
2090                alpha: 1.0,
2091                line_width: 1.2,
2092                ..Default::default()
2093            })
2094            .layer_data(f.take(h))
2095            .layer_aes(of(Aes::new().x("x").y("y").group("g").fill("fill")))
2096            .decorative()
2097            .layer_svg_attrs(inert)
2098            .layer_svg_attr("class", class("node-diamond-mark"));
2099    }
2100    for (mut f, alpha, cls) in [
2101        (sprior, 0.28, "node-state-prior"),
2102        (sbar, 0.9, "node-state-bar"),
2103        (stick, 0.9, "node-state-prior"),
2104        (tband, 0.14, "node-table-current"),
2105        (tmarkbg, 0.2, "node-table-mark"),
2106        (dmark, 0.9, "node-density-mark"),
2107    ] {
2108        if f.is_empty() {
2109            continue;
2110        }
2111        plot = plot
2112            .geom_rect_with(GeomRect {
2113                alpha,
2114                line_width: 0.0,
2115                ..Default::default()
2116            })
2117            .layer_data(f.take(h))
2118            .layer_aes(of(rect_aes().fill("fill")))
2119            .decorative()
2120            .layer_svg_attrs(inert)
2121            .layer_svg_attr("class", class(cls));
2122    }
2123    for (mut f, colour, face, cls) in [
2124        (sname, s.ink, FontFace::Plain, "node-state"),
2125        (sseen, s.heading, FontFace::Bold, "node-state"),
2126        (stext, s.muted, FontFace::Plain, "node-state-value"),
2127    ] {
2128        if f.is_empty() {
2129            continue;
2130        }
2131        plot = plot
2132            .geom_text_with(GeomText {
2133                size: SMALL_PX,
2134                color: colour,
2135                fontface: face,
2136                hjust: 0.0,
2137                ..Default::default()
2138            })
2139            .layer_aes(of(state_attr(&f, Aes::new().x("x").y("y").label("label"))))
2140            .layer_data(f.take(h))
2141            .layer_svg_attrs(inert)
2142            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class(cls))]);
2143    }
2144    if !dtext.is_empty() {
2145        plot = plot
2146            .geom_text_with(GeomText {
2147                size: SMALL_PX,
2148                color: s.muted,
2149                hjust: 0.5,
2150                ..Default::default()
2151            })
2152            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2153            .layer_data(dtext.take(h))
2154            .layer_svg_attrs(inert)
2155            .layer_svg_attrs([
2156                ("aria-hidden", "true"),
2157                ("class", &*class("node-density-text")),
2158            ]);
2159    }
2160    for (mut f, colour, face, hjust, cls) in [
2161        (thead_l, s.muted, FontFace::Plain, 0.0, "node-table-head"),
2162        (thead_r, s.muted, FontFace::Plain, 1.0, "node-table-head"),
2163        (tname, s.ink, FontFace::Plain, 0.0, "node-table-name"),
2164        (tcell, s.muted, FontFace::Plain, 1.0, "node-table-cell"),
2165        (
2166            tmark,
2167            s.heading,
2168            FontFace::Bold,
2169            1.0,
2170            "node-table-cell node-table-chosen",
2171        ),
2172    ] {
2173        if f.is_empty() {
2174            continue;
2175        }
2176        let cls = cls.split(' ').map(&class).collect::<Vec<_>>().join(" ");
2177        plot = plot
2178            .geom_text_with(GeomText {
2179                size: SMALL_PX,
2180                color: colour,
2181                fontface: face,
2182                hjust,
2183                ..Default::default()
2184            })
2185            .layer_aes(of(state_attr(&f, Aes::new().x("x").y("y").label("label"))))
2186            .layer_data(f.take(h))
2187            .layer_svg_attrs(inert)
2188            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*cls)]);
2189    }
2190    for (mut f, face, colour) in [
2191        (sup, FontFace::Bold, s.heading),
2192        (sdown, FontFace::Plain, s.muted),
2193    ] {
2194        if f.is_empty() {
2195            continue;
2196        }
2197        plot = plot
2198            .geom_text_with(GeomText {
2199                size: SMALL_PX - 1.0,
2200                color: colour,
2201                fontface: face,
2202                hjust: 0.0,
2203                ..Default::default()
2204            })
2205            .layer_data(f.take(h))
2206            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2207            .layer_svg_attrs(inert)
2208            .layer_svg_attrs([
2209                ("aria-hidden", "true"),
2210                ("class", &*class("node-state-delta")),
2211            ]);
2212    }
2213    if !ibadge.is_empty() {
2214        plot = plot
2215            .geom_rect_with(
2216                GeomRect {
2217                    fill: s.card,
2218                    color: s.heading,
2219                    alpha: 1.0,
2220                    line_width: 1.1,
2221                    ..Default::default()
2222                }
2223                .with_radius(9.0),
2224            )
2225            .layer_data(ibadge.take(h))
2226            .layer_aes(of(rect_aes()))
2227            .decorative()
2228            .layer_svg_attrs(inert)
2229            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
2230    }
2231    if !irect.is_empty() {
2232        plot = plot
2233            .geom_rect_with(
2234                GeomRect {
2235                    fill: s.heading,
2236                    alpha: 1.0,
2237                    line_width: 0.0,
2238                    ..Default::default()
2239                }
2240                .with_radius(0.9),
2241            )
2242            .layer_data(irect.take(h))
2243            .layer_aes(of(rect_aes()))
2244            .decorative()
2245            .layer_svg_attrs(inert)
2246            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
2247        plot = plot
2248            .geom_polygon_with(GeomPolygon {
2249                fill: s.heading,
2250                alpha: 1.0,
2251                line_width: 0.0,
2252                ..Default::default()
2253            })
2254            .layer_data(ipoly.take(h))
2255            .layer_aes(of(Aes::new().x("x").y("y").group("g")))
2256            .decorative()
2257            .layer_svg_attrs(inert)
2258            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
2259    }
2260    if !iletter.is_empty() {
2261        plot = plot
2262            .geom_text_with(GeomText {
2263                size: BADGE_PX,
2264                color: s.heading,
2265                fontface: FontFace::Bold,
2266                ..Default::default()
2267            })
2268            .layer_data(iletter.take(h))
2269            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2270            .layer_svg_attrs(inert)
2271            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
2272    }
2273    for (mut f, size, colour, cls, math, hjust) in [
2274        (lines, LABEL_PX, s.heading, class("node-label"), false, 0.5),
2275        (values, VALUE_PX, s.ink, class("node-value"), false, 0.5),
2276        (inside, LABEL_PX, s.heading, class("node-label"), true, 0.5),
2277        (texts, LABEL_PX, s.heading, class("node-label"), false, 0.5),
2278        (inverse, LABEL_PX, s.card, class("node-label"), true, 0.5),
2279        (above, SMALL_PX, s.muted, class("node-label"), true, 0.5),
2280        (beside, LABEL_PX, s.heading, class("node-label"), true, 0.0),
2281        (
2282            glyphs,
2283            GLYPH_PX,
2284            s.glyph_ink.unwrap_or(s.heading),
2285            class("node-label"),
2286            true,
2287            0.5,
2288        ),
2289    ] {
2290        if f.is_empty() {
2291            continue;
2292        }
2293        // a factor graph's labels as mathematics: the math font, italic
2294        let (fontfamily, fontface, size) = match s.math_font.as_ref().filter(|_| math) {
2295            Some(family) => (family.clone(), FontFace::Italic, size + 2.0),
2296            None => (String::new(), FontFace::Bold, size),
2297        };
2298        plot = plot
2299            .geom_text_with(GeomText {
2300                size,
2301                color: colour,
2302                fontface,
2303                fontfamily,
2304                hjust,
2305                ..Default::default()
2306            })
2307            .layer_data(f.take(h))
2308            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2309            .layer_svg_attrs(inert)
2310            .layer_svg_attrs([("aria-hidden", "true"), ("class", cls.as_str())]);
2311    }
2312    for (dot, mut f) in badges {
2313        plot = plot
2314            .geom_rect_with(
2315                GeomRect {
2316                    fill: s.card,
2317                    color: dot,
2318                    alpha: 0.0,
2319                    line_width: 1.0,
2320                    ..Default::default()
2321                }
2322                .with_radius(8.0),
2323            )
2324            .layer_data(f.take(h))
2325            .layer_aes(of(rect_aes()))
2326            .decorative()
2327            .layer_svg_attrs(inert);
2328    }
2329    for (mut f, size) in [(dots, 3.0), (ends, 2.2)] {
2330        if f.is_empty() {
2331            continue;
2332        }
2333        plot = plot
2334            .geom_point_with(GeomPoint {
2335                size,
2336                ..Default::default()
2337            })
2338            .layer_data(f.take(h))
2339            .layer_aes(of(Aes::new().x("x").y("y").color("col")))
2340            .decorative()
2341            .layer_svg_attrs(inert);
2342    }
2343    if !btext.is_empty() {
2344        plot = plot
2345            .geom_text_with(GeomText {
2346                size: BADGE_PX,
2347                color: s.ink,
2348                hjust: 0.0,
2349                ..Default::default()
2350            })
2351            .layer_data(btext.take(h))
2352            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2353            .layer_svg_attrs(inert)
2354            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-badge"))]);
2355    }
2356    if !spark.is_empty() {
2357        plot = plot
2358            .geom_path_with(GeomPath::default().linewidth(1.4))
2359            .layer_data(spark.take(h))
2360            .layer_aes(of(Aes::new().x("x").y("y").group("g").color("col")))
2361            .decorative()
2362            .layer_svg_attrs(inert)
2363            .layer_svg_attr("class", class("node-spark"));
2364    }
2365    plot
2366}
2367
2368#[cfg(test)]
2369mod tests {
2370    use super::*;
2371    use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
2372
2373    #[test]
2374    fn an_end_label_sits_beside_its_box() {
2375        // anofox-visualization#1238: an interface name near a factor is
2376        // clear of the factor's box, not centred on its border
2377        let hw = edge_label_width("variance") / 2.0;
2378        let (x, y) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "variance", 0.8);
2379        assert!(
2380            (x - (100.0 - hw - crate::graph_layout::LABEL_CLEAR)).abs() < 1e-9 && y == 0.0,
2381            "{x} {y}"
2382        );
2383        let (x, _) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "mean", 0.2);
2384        assert!(
2385            x - edge_label_width("mean") / 2.0 >= crate::graph_layout::LABEL_CLEAR - 1e-9,
2386            "{x}"
2387        );
2388        // a vertical edge: beside the line, below the box it leaves
2389        let (x, y) = end_label_at(&[(50.0, 0.0), (50.0, 40.0)], "out", 0.2);
2390        assert!(
2391            x - edge_label_width("out") / 2.0 > 50.0 && y > 0.0,
2392            "{x} {y}"
2393        );
2394        // a short edge: the label stays on it
2395        let (x, _) = end_label_at(&[(0.0, 0.0), (20.0, 0.0)], "variance", 0.8);
2396        assert!((x - 10.0).abs() < 1e-9, "{x}");
2397    }
2398
2399    /// A Bayesian network's nodes (Netica / GeNIe style): a chance node's
2400    /// states as rows of bars with the prior behind them, an observed node
2401    /// shaded with its state in bold, a decision as a square-cornered box,
2402    /// a utility as a diamond (an invisible box as its hit target), a
2403    /// deterministic node with a double outline.
2404    #[test]
2405    fn draws_bayes_net_nodes_with_state_bars() {
2406        let states = vec!["yes".to_string(), "no".to_string()];
2407        let spec = [
2408            ("Rain", NodeShape::Box),
2409            ("Wet grass", NodeShape::Box),
2410            ("Water?", NodeShape::Rect),
2411            ("Cost", NodeShape::Diamond),
2412            ("Either", NodeShape::DoubleBox),
2413        ];
2414        let sizes: Vec<NodeBox> = spec
2415            .iter()
2416            .map(|(l, sh)| match sh {
2417                NodeShape::Diamond => diamond_box(l, Some("-12.5")),
2418                _ => states_box(l, None, None, &states),
2419            })
2420            .collect();
2421        // two state rows below the label; room for the bars
2422        let plain = node_box("Rain", None, None, false);
2423        assert_eq!(sizes[0].h, plain.h + 4.0 + 2.0 * STATE_H);
2424        assert!(sizes[0].w >= 2.0 * BOX_PAD_X + STATE_BAR_W + STATE_TEXT_W);
2425        assert!(sizes[3].w > sizes[3].h, "a diamond wider than tall");
2426        let gnodes: Vec<GraphNode> = sizes
2427            .iter()
2428            .map(|b| GraphNode {
2429                w: b.w,
2430                h: b.h,
2431                ..Default::default()
2432            })
2433            .collect();
2434        let links = [(0, 1), (2, 1), (1, 3), (0, 4)];
2435        let gedges: Vec<GraphEdge> = links
2436            .iter()
2437            .map(|&(a, b)| GraphEdge {
2438                from: a,
2439                to: b,
2440                label_w: None,
2441            })
2442            .collect();
2443        let params = LayeredParams {
2444            direction: crate::graph_layout::Direction::TopBottom,
2445            ..Default::default()
2446        };
2447        let l = layered(&gnodes, &gedges, &params);
2448        let bar = |name: &str, p: f64, prior: Option<f64>, observed: bool| StateBar {
2449            name: name.to_string(),
2450            p,
2451            prior,
2452            text: format!("{:.0}%", p * 100.0),
2453            observed,
2454            was: None,
2455        };
2456        let nodes: Vec<DrawNode> = spec
2457            .iter()
2458            .zip(&sizes)
2459            .enumerate()
2460            .map(|(i, ((_, shape), b))| DrawNode {
2461                id: format!("n{i}"),
2462                shape: *shape,
2463                lines: b.lines.clone(),
2464                value: (*shape == NodeShape::Diamond).then(|| "-12.5".to_string()),
2465                stroke: (60, 60, 60),
2466                tooltip: b.lines.join(" "),
2467                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2468                states: (*shape != NodeShape::Diamond).then(|| {
2469                    if i == 1 {
2470                        (
2471                            vec![
2472                                bar("yes", 1.0, Some(0.65), true),
2473                                bar("no", 0.0, Some(0.35), false),
2474                            ],
2475                            (37, 99, 235),
2476                        )
2477                    } else {
2478                        (
2479                            vec![
2480                                bar("yes", 0.3, Some(0.5), false),
2481                                bar("no", 0.7, Some(0.5), false),
2482                            ],
2483                            (37, 99, 235),
2484                        )
2485                    }
2486                }),
2487                fill: (i == 1).then_some((230, 236, 250)),
2488                ..Default::default()
2489            })
2490            .collect();
2491        let edges: Vec<DrawEdge> = links
2492            .iter()
2493            .map(|&(a, b)| DrawEdge {
2494                colour: (90, 90, 90),
2495                width: 1.6,
2496                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2497                ..Default::default()
2498            })
2499            .collect();
2500        let svg = draw(
2501            &l,
2502            &[],
2503            &[],
2504            &nodes,
2505            &edges,
2506            &GraphStyle::default(),
2507            crate::theme::presets::theme_void(),
2508        )
2509        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2510        .unwrap();
2511        // one hit target per node, classed by shape; directed edges
2512        assert_eq!(svg.matches("data-node=").count(), spec.len());
2513        for c in [
2514            "gg-graph-node-rect",
2515            "gg-graph-node-diamond",
2516            "gg-graph-node-double-box",
2517        ] {
2518            assert!(svg.contains(c), "{c}");
2519        }
2520        assert!(
2521            svg.contains("gg-graph-node-diamond-mark") && svg.contains("gg-graph-node-outline")
2522        );
2523        assert!(
2524            svg.contains("data-part=\"arrow\""),
2525            "arrowheads at the child"
2526        );
2527        // state rows: four bars, their priors, the names and probabilities
2528        assert!(
2529            svg.contains("gg-graph-node-state-bar") && svg.contains("gg-graph-node-state-prior")
2530        );
2531        assert!(svg.contains(">30%<") && svg.contains(">100%<"));
2532        // the observed node shaded, its observed state in bold
2533        assert!(svg.contains("fill=\"#E6ECFA\""), "shaded");
2534        assert!(
2535            svg.match_indices(">yes</text>")
2536                .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2537            "the observed state in bold"
2538        );
2539        // the diamond's value inside it
2540        assert!(svg.contains(">-12.5<"));
2541        // a plain box keeps its round corners and the plain class
2542        let plain = svg
2543            .split("<rect")
2544            .find(|r| r.contains("data-node=\"n0\""))
2545            .unwrap();
2546        assert!(plain.contains("gg-graph-node\""), "{plain}");
2547    }
2548
2549    /// A continuous node's density in its box
2550    /// (DataZooDE/anofox-visualization#1445): the curve over the prior, the
2551    /// interval darker under it, the marked value, the text line.
2552    #[test]
2553    fn draws_a_density_in_a_box() {
2554        let hs: Vec<f64> = (0..25)
2555            .map(|i| (-0.5 * ((i as f64 - 12.0) / 3.0).powi(2)).exp())
2556            .collect();
2557        let prior: Vec<f64> = (0..25)
2558            .map(|i| 0.4 * (-0.5 * ((i as f64 - 10.0) / 7.0).powi(2)).exp())
2559            .collect();
2560        let d = NodeDensity {
2561            heights: hs,
2562            prior: Some(prior),
2563            band: Some((0.3, 0.7)),
2564            marker: Some(0.6),
2565            text: "12.3 (10.1–14.5)".into(),
2566        };
2567        let b = density_box("Wait time", None, None, &d.text);
2568        let plain = node_box("Wait time", None, None, false);
2569        assert_eq!(b.h, plain.h + 6.0 + DENSITY_H + STATE_H);
2570        assert!(b.w >= DENSITY_W + 2.0 * BOX_PAD_X);
2571        let gnodes = [GraphNode {
2572            w: b.w,
2573            h: b.h,
2574            ..Default::default()
2575        }];
2576        let l = layered(&gnodes, &[], &LayeredParams::default());
2577        let nodes = [DrawNode {
2578            id: "wait".into(),
2579            shape: NodeShape::Rect,
2580            lines: b.lines.clone(),
2581            stroke: (60, 60, 60),
2582            tooltip: "Wait time".into(),
2583            attrs: vec![("node".to_string(), Some("wait".to_string()))],
2584            density: Some((d, (37, 99, 235))),
2585            ..Default::default()
2586        }];
2587        let svg = draw(
2588            &l,
2589            &[],
2590            &[],
2591            &nodes,
2592            &[],
2593            &GraphStyle::default(),
2594            crate::theme::presets::theme_void(),
2595        )
2596        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2597        .unwrap();
2598        for c in [
2599            "gg-graph-node-belief",
2600            "gg-graph-node-prior",
2601            "gg-graph-node-density-band",
2602            "gg-graph-node-density-mark",
2603            "gg-graph-node-density-text",
2604        ] {
2605            assert!(svg.contains(c), "{c}");
2606        }
2607        assert!(svg.contains(">12.3 (10.1–14.5)<"), "{svg}");
2608        // the curve stays inside the box
2609        let pn = &l.nodes[0];
2610        let (top, bottom) = (pn.cy - pn.h / 2.0, pn.cy + pn.h / 2.0);
2611        let poly = svg
2612            .split("<polygon")
2613            .find(|p| p.contains("node-belief"))
2614            .unwrap();
2615        let pts = poly
2616            .split("points=\"")
2617            .nth(1)
2618            .unwrap()
2619            .split('"')
2620            .next()
2621            .unwrap();
2622        for xy in pts.split_whitespace() {
2623            let y: f64 = xy.split(',').nth(1).unwrap().parse().unwrap();
2624            assert!(y >= top && y <= bottom, "{y} outside {top}..{bottom}");
2625        }
2626        // no density on a shaped node (a circle): nothing drawn
2627        let round = [DrawNode {
2628            shape: NodeShape::Circle,
2629            ..nodes[0].clone()
2630        }];
2631        let svg = draw(
2632            &l,
2633            &[],
2634            &[],
2635            &round,
2636            &[],
2637            &GraphStyle::default(),
2638            crate::theme::presets::theme_void(),
2639        )
2640        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2641        .unwrap();
2642        assert!(!svg.contains("gg-graph-node-density-band"));
2643    }
2644
2645    /// An influence diagram's policy as a table in the decision's box
2646    /// (DataZooDE/anofox-visualization#1279): a header, a row per
2647    /// configuration of the informational parents, the chosen option bold
2648    /// on a tint, the configuration the evidence picks on a band.
2649    #[test]
2650    fn draws_a_policy_table_in_a_decision() {
2651        let table = NodeTable {
2652            header: vec!["Seismic".into(), "drill".into(), "don't drill".into()],
2653            rows: vec![
2654                vec!["closed".into(), "87.5".into(), "0".into()],
2655                vec!["open".into(), "22.9".into(), "0".into()],
2656                vec!["diffuse".into(), "-25.6".into(), "0".into()],
2657                vec![
2658                    "a very long configuration name".into(),
2659                    "1".into(),
2660                    "2".into(),
2661                ],
2662            ],
2663            marked: vec![Some(1), Some(1), Some(2)],
2664            current: Some(1),
2665            keys: vec![String::new(), "drill".into(), "dont".into()],
2666        };
2667        let b = table_box("Drill?", None, None, &table);
2668        let plain = node_box("Drill?", None, None, false);
2669        // a header row and four rows under the label, room for the columns
2670        assert_eq!(b.h, plain.h + 4.0 + 5.0 * STATE_H);
2671        assert!(
2672            b.w >= table.width() + 2.0 * BOX_PAD_X,
2673            "{} {}",
2674            b.w,
2675            table.width()
2676        );
2677        // no header row when every head is empty; no rows: a plain box
2678        let bare = NodeTable {
2679            header: vec![String::new(), "EU".into()],
2680            ..table.clone()
2681        };
2682        assert_eq!(table_box("Drill?", None, None, &bare).h, b.h);
2683        let headless = NodeTable {
2684            header: Vec::new(),
2685            ..table.clone()
2686        };
2687        assert_eq!(table_box("Drill?", None, None, &headless).h, b.h - STATE_H);
2688        assert_eq!(
2689            table_box("Drill?", None, None, &NodeTable::default()),
2690            plain
2691        );
2692        let gnodes = [GraphNode {
2693            w: b.w,
2694            h: b.h,
2695            ..Default::default()
2696        }];
2697        let l = layered(&gnodes, &[], &LayeredParams::default());
2698        let nodes = [DrawNode {
2699            id: "drill".into(),
2700            shape: NodeShape::Rect,
2701            lines: b.lines.clone(),
2702            stroke: (60, 60, 60),
2703            tooltip: "Drill?".into(),
2704            attrs: vec![("node".to_string(), Some("drill".to_string()))],
2705            table: Some((table, (37, 99, 235))),
2706            ..Default::default()
2707        }];
2708        let svg = draw(
2709            &l,
2710            &[],
2711            &[],
2712            &nodes,
2713            &[],
2714            &GraphStyle::default(),
2715            crate::theme::presets::theme_void(),
2716        )
2717        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2718        .unwrap();
2719        assert!(
2720            svg.contains(">Seismic<") && svg.contains(">don&#39;t drill<"),
2721            "{svg}"
2722        );
2723        assert!(svg.contains(">closed<") && svg.contains(">-25.6<"));
2724        // the long name cut with …
2725        assert!(svg.contains(">a very long c…<"), "{svg}");
2726        // three chosen cells, bold on a tint; one band for the current row
2727        assert_eq!(svg.matches("gg-graph-node-table-chosen").count(), 3);
2728        assert_eq!(svg.matches("gg-graph-node-table-mark").count(), 3);
2729        assert!(svg.contains("gg-graph-node-table-mark"));
2730        assert!(svg.contains("gg-graph-node-table-current"));
2731        assert!(
2732            svg.match_indices(">87.5</text>")
2733                .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2734            "the chosen option in bold"
2735        );
2736        assert!(
2737            svg.match_indices(">0</text>")
2738                .any(|(i, _)| !svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2739            "the others plain"
2740        );
2741        // a column's head and cells name its key; the row names none
2742        assert_eq!(svg.matches("data-state=\"dont\"").count(), 5);
2743        assert_eq!(svg.matches("data-state=\"drill\"").count(), 5);
2744        assert!(!svg
2745            .split("<text")
2746            .any(|t| t.contains(">closed<") && t.contains("data-state")));
2747        // the cells are right-aligned
2748        assert!(
2749            svg.match_indices(">22.9</text>")
2750                .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i]
2751                    .contains("text-anchor=\"end\"")),
2752            "right-aligned"
2753        );
2754    }
2755
2756    /// Interactive evidence on a Bayesian network
2757    /// (DataZooDE/anofox-visualization#1276): a state's change after its
2758    /// probability, a node tinted by how far it moved, a hand on a node set
2759    /// by an intervention, its incoming edge cut, `data-state` on each row.
2760    #[test]
2761    fn draws_belief_deltas_cut_edges_and_a_hand() {
2762        let states = vec!["yes".to_string(), "no".to_string()];
2763        let plain = states_box("Rain", None, None, &states);
2764        let wide = states_box_with_deltas("Rain", None, None, &states, true);
2765        assert_eq!(wide.w, plain.w + STATE_DELTA_W, "room for the change");
2766        let gnodes = vec![
2767            GraphNode {
2768                w: wide.w,
2769                h: wide.h,
2770                ..Default::default()
2771            };
2772            2
2773        ];
2774        let l = layered(
2775            &gnodes,
2776            &[GraphEdge {
2777                from: 0,
2778                to: 1,
2779                label_w: None,
2780            }],
2781            &LayeredParams {
2782                direction: crate::graph_layout::Direction::TopBottom,
2783                ..Default::default()
2784            },
2785        );
2786        let bar = |name: &str, p: f64, was: f64| StateBar {
2787            name: name.to_string(),
2788            p,
2789            text: format!("{:.0}%", p * 100.0),
2790            was: Some(was),
2791            ..Default::default()
2792        };
2793        let nodes: Vec<DrawNode> = (0..2)
2794            .map(|i| DrawNode {
2795                id: format!("n{i}"),
2796                lines: vec![if i == 0 { "Cloudy" } else { "Rain" }.to_string()],
2797                stroke: (60, 60, 60),
2798                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2799                states: Some((
2800                    if i == 0 {
2801                        vec![bar("yes", 0.5, 0.5), bar("no", 0.5, 0.5)]
2802                    } else {
2803                        vec![bar("yes", 0.71, 0.5), bar("no", 0.29, 0.5)]
2804                    },
2805                    (37, 99, 235),
2806                )),
2807                icon: (i == 0).then_some(NodeIcon::Hand),
2808                ..Default::default()
2809            })
2810            .collect();
2811        let edges = vec![DrawEdge {
2812            colour: (160, 160, 160),
2813            width: 1.6,
2814            cut: true,
2815            attrs: vec![("edge".to_string(), Some("n0>n1".to_string()))],
2816            label_attrs: vec![("to".to_string(), Some("n1".to_string()))],
2817            ..Default::default()
2818        }];
2819        let style = GraphStyle {
2820            moved: Some((245, 158, 11)),
2821            ..Default::default()
2822        };
2823        let svg = draw(
2824            &l,
2825            &[],
2826            &[],
2827            &nodes,
2828            &edges,
2829            &style,
2830            crate::theme::presets::theme_void(),
2831        )
2832        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2833        .unwrap();
2834        // Rain moved: ▲21 / ▼21, tinted; Cloudy did not move: no change, no tint
2835        assert!(svg.contains(">▲21<") && svg.contains(">▼21<"), "deltas");
2836        assert_eq!(svg.matches("gg-graph-node-state-delta").count(), 2);
2837        let tint = mix(
2838            (255, 255, 255),
2839            (245, 158, 11),
2840            moved_share(&nodes[1].states.as_ref().unwrap().0).unwrap(),
2841        );
2842        assert!(
2843            svg.to_ascii_lowercase()
2844                .contains(&format!("fill=\"{}\"", hex(tint))),
2845            "tinted"
2846        );
2847        assert!(
2848            svg.contains("fill=\"#FFFFFF\"") || svg.contains("fill=\"#ffffff\""),
2849            "Cloudy untinted"
2850        );
2851        // the hand and the cut mark
2852        assert!(svg.contains("gg-graph-node-icon"), "hand");
2853        assert!(svg.contains("gg-graph-edge-cut"), "cut mark");
2854        // a click on a row names its state
2855        assert!(svg.contains("data-state=\"yes\"") && svg.contains("data-state=\"no\""));
2856    }
2857
2858    /// A causal diagram's marks: a ring around an adjusted node, a letter
2859    /// in the badge (X a treatment, M a mediator), a bar across a blocked
2860    /// edge.
2861    #[test]
2862    fn draws_rings_letters_and_blocked_edges() {
2863        let gnodes = vec![
2864            GraphNode {
2865                w: 90.0,
2866                h: 40.0,
2867                ..Default::default()
2868            };
2869            3
2870        ];
2871        let gedges = [(0, 1), (1, 2)].map(|(from, to)| GraphEdge {
2872            from,
2873            to,
2874            label_w: None,
2875        });
2876        let l = layered(&gnodes, &gedges, &LayeredParams::default());
2877        let nodes: Vec<DrawNode> = ["Engaged", "Discount", "Stays"]
2878            .iter()
2879            .enumerate()
2880            .map(|(i, name)| DrawNode {
2881                id: format!("n{i}"),
2882                lines: vec![name.to_string()],
2883                stroke: (60, 60, 60),
2884                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2885                ring: (i == 0).then_some((37, 99, 235)),
2886                icon: match i {
2887                    1 => Some(NodeIcon::Letter('X')),
2888                    2 => Some(NodeIcon::Letter('Y')),
2889                    _ => None,
2890                },
2891                ..Default::default()
2892            })
2893            .collect();
2894        let edges = vec![
2895            DrawEdge {
2896                colour: (160, 160, 160),
2897                width: 1.6,
2898                blocked: true,
2899                line: EdgeLine::Dashed,
2900                ..Default::default()
2901            },
2902            DrawEdge {
2903                colour: (160, 160, 160),
2904                width: 1.6,
2905                ..Default::default()
2906            },
2907        ];
2908        let svg = draw(
2909            &l,
2910            &[],
2911            &[],
2912            &nodes,
2913            &edges,
2914            &GraphStyle::default(),
2915            crate::theme::presets::theme_void(),
2916        )
2917        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2918        .unwrap();
2919        assert_eq!(svg.matches("gg-graph-node-ring").count(), 1, "one ring");
2920        assert!(
2921            svg.to_ascii_lowercase().contains("stroke=\"#2563eb\""),
2922            "ring colour"
2923        );
2924        assert!(svg.contains(">X<") && svg.contains(">Y<"), "letters");
2925        assert_eq!(svg.matches("gg-graph-edge-block").count(), 1, "one bar");
2926    }
2927
2928    #[test]
2929    fn js_distance_is_zero_for_the_same_and_one_for_disjoint() {
2930        assert!(js_distance(&[0.5, 0.5], &[0.5, 0.5]).abs() < 1e-12);
2931        assert!((js_distance(&[1.0, 0.0], &[0.0, 1.0]) - 1.0).abs() < 1e-12);
2932        let d = js_distance(&[0.71, 0.29], &[0.5, 0.5]);
2933        assert!(d > 0.1 && d < 0.2, "{d}");
2934        // unnormalised input, or a length mismatch
2935        assert!((js_distance(&[2.0, 2.0], &[0.5, 0.5])).abs() < 1e-12);
2936        assert_eq!(js_distance(&[1.0], &[0.5, 0.5]), 0.0);
2937        assert_eq!(delta_text(0.71, 0.5), Some(("▲21".to_string(), true)));
2938        assert_eq!(delta_text(0.5, 0.503), None);
2939    }
2940
2941    #[test]
2942    fn wraps_long_labels_in_three_lines() {
2943        let l = wrap(
2944            "Recommend replenishment orders for every store and every week of the coming year",
2945            152.0,
2946        );
2947        assert_eq!(l.len(), 3);
2948        assert!(l[2].ends_with('…'));
2949        assert_eq!(wrap("Ingest", 152.0), ["Ingest"]);
2950    }
2951
2952    /// No ellipsis while the label fits; breaks at word boundaries and
2953    /// after `/` / `-`, never mid-word when there is a separator.
2954    #[test]
2955    fn wraps_at_word_boundaries() {
2956        let max = BOX_MAX_W - 2.0 * BOX_PAD_X;
2957        for label in [
2958            "duckdb/community-extensions (descriptions)",
2959            "Locked DuckDB server (anofox-visualization)",
2960            "Parquet snapshot (downloads, extensions)",
2961            "fetch.sh: download, file by ISO week, merge",
2962        ] {
2963            let l = wrap(label, max);
2964            assert!(l.len() <= MAX_LINES, "{l:?}");
2965            assert!(!l.iter().any(|x| x.contains('…')), "{label}: {l:?}");
2966            // every line ends at a space or after a separator
2967            let joined: String = l.concat();
2968            assert_eq!(joined.replace(' ', ""), label.replace(' ', ""), "{l:?}");
2969            for w in l.windows(2) {
2970                let end = w[0].chars().last().unwrap();
2971                let next = w[1].chars().next().unwrap();
2972                let at_space = label.contains(&format!(
2973                    "{} {}",
2974                    w[0].split(' ').next_back().unwrap(),
2975                    w[1].split(' ').next().unwrap()
2976                ));
2977                assert!(
2978                    at_space || matches!(end, '/' | '-' | '_' | '.' | ','),
2979                    "{l:?} breaks at {end}{next}"
2980                );
2981            }
2982        }
2983        assert_eq!(
2984            wrap("duckdb/community-extensions (descriptions)", max),
2985            ["duckdb/community-", "extensions", "(descriptions)"]
2986        );
2987    }
2988
2989    #[test]
2990    fn node_box_grows_with_its_contents() {
2991        let plain = node_box("Ingest", None, None, false);
2992        assert_eq!((plain.w, plain.h), (BOX_MIN_W, 2.0 * BOX_PAD_Y + LINE_H));
2993        let full = node_box("Ingest", Some("1,240"), Some("late"), true);
2994        assert_eq!(full.h, plain.h + LINE_H + 20.0 + SPARK_H);
2995        assert!(full.w >= 110.0 + 2.0 * BOX_PAD_X);
2996        let long = node_box(&"word ".repeat(40), None, None, false);
2997        assert!(long.w <= BOX_MAX_W && long.lines.len() == MAX_LINES);
2998    }
2999
3000    /// An edge label a node box would cover moves along the edge.
3001    #[test]
3002    fn edge_label_keeps_clear_of_nodes() {
3003        let node = |cx: f64, w: f64| PlacedNode {
3004            cx,
3005            cy: 0.0,
3006            w,
3007            h: 40.0,
3008            layer: 0,
3009            order: 0,
3010        };
3011        let pts = [(0.0, 0.0), (300.0, 0.0)];
3012        // nothing in the way: the midpoint
3013        assert_eq!(edge_label_at(&pts, "spikes flagged", &[]), (150.0, 0.0));
3014        // a box over the middle: somewhere else along the edge, clear of it
3015        let nodes = [node(150.0, 60.0)];
3016        let (x, _) = edge_label_at(&pts, "spikes flagged", &nodes);
3017        let hw = edge_label_width("spikes flagged") / 2.0 + 3.0;
3018        assert!((x - 150.0).abs() >= hw + 30.0, "{x}");
3019        assert_eq!(point_at(&pts, 0.25), (75.0, 0.0));
3020    }
3021
3022    #[test]
3023    fn flow_width_is_area_true_and_rounded() {
3024        assert_eq!(flow_width(None, 10.0, EdgeLine::Solid), 1.6);
3025        assert_eq!(flow_width(Some(10.0), 10.0, EdgeLine::Solid), 7.0);
3026        assert_eq!(flow_width(Some(2.5), 10.0, EdgeLine::Solid), 4.2);
3027        assert_eq!(flow_width(None, 10.0, EdgeLine::Dots), 3.0);
3028    }
3029
3030    /// Two lanes, three boxes, a labelled edge: the marks carry the
3031    /// caller's attributes and classes, a node's contents sit in its
3032    /// `data-of` group, and the box itself (the hit target) stays outside.
3033    #[test]
3034    fn draws_marks_with_attributes_and_groups() {
3035        let labels = ["Ingest", "Model", "Publish"];
3036        let boxes: Vec<NodeBox> = labels
3037            .iter()
3038            .enumerate()
3039            .map(|(i, l)| node_box(l, (i == 1).then_some("42"), None, i == 2))
3040            .collect();
3041        let gnodes: Vec<GraphNode> = boxes
3042            .iter()
3043            .enumerate()
3044            .map(|(i, b)| GraphNode {
3045                w: b.w,
3046                h: b.h,
3047                lane: Some(i % 2),
3048                ..Default::default()
3049            })
3050            .collect();
3051        let gedges = [
3052            GraphEdge {
3053                from: 0,
3054                to: 1,
3055                label_w: Some(edge_label_width("rows")),
3056            },
3057            GraphEdge {
3058                from: 1,
3059                to: 2,
3060                label_w: None,
3061            },
3062        ];
3063        let params = LayeredParams {
3064            lanes: 2,
3065            ..Default::default()
3066        };
3067        let l = layered(&gnodes, &gedges, &params);
3068        let nodes: Vec<DrawNode> = labels
3069            .iter()
3070            .zip(&boxes)
3071            .enumerate()
3072            .map(|(i, (id, b))| DrawNode {
3073                id: id.to_string(),
3074                lines: b.lines.clone(),
3075                value: (i == 1).then(|| "42".to_string()),
3076                stroke: (90, 90, 90),
3077                accent: (i == 0).then_some((200, 0, 0)),
3078                spark: (i == 2).then(|| (vec![1.0, 3.0, 2.0], (0, 0, 200))),
3079                tooltip: format!("{id}!"),
3080                attrs: vec![
3081                    ("node".to_string(), Some(id.to_string())),
3082                    ("value".to_string(), (i == 1).then(|| "42".to_string())),
3083                ],
3084                ..Default::default()
3085            })
3086            .collect();
3087        let edges: Vec<DrawEdge> = [(0, 1), (1, 2)]
3088            .iter()
3089            .map(|&(a, b)| DrawEdge {
3090                colour: (100, 100, 100),
3091                width: flow_width(None, 0.0, EdgeLine::Solid),
3092                line: if a == 0 {
3093                    EdgeLine::Solid
3094                } else {
3095                    EdgeLine::Dashed
3096                },
3097                class: (a == 1).then(|| "flowing".to_string()),
3098                tooltip: format!("{} → {}", labels[a], labels[b]),
3099                label: (a == 0).then(|| "rows".to_string()),
3100                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
3101                label_attrs: vec![("from".to_string(), Some(labels[a].to_string()))],
3102                ..Default::default()
3103            })
3104            .collect();
3105        let lanes = ["Left".to_string(), "Right".to_string()];
3106        let svg = draw(
3107            &l,
3108            &lanes,
3109            &[],
3110            &nodes,
3111            &edges,
3112            &GraphStyle::default(),
3113            crate::theme::presets::theme_void(),
3114        )
3115        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
3116        .unwrap();
3117        // start tags, each with whether it sits inside a `data-of` group
3118        let mut tags: Vec<(&str, bool)> = Vec::new();
3119        let mut stack: Vec<bool> = Vec::new();
3120        for part in svg.split('<').skip(1) {
3121            let tag = &part[..part.find('>').unwrap()];
3122            if tag.starts_with('/') {
3123                stack.pop();
3124                continue;
3125            }
3126            let inside = stack.iter().any(|&g| g);
3127            tags.push((tag, inside));
3128            if !tag.ends_with('/') {
3129                stack.push(tag.contains("data-of="));
3130            }
3131        }
3132        let attr = |tag: &str, name: &str| {
3133            let key = format!(" {name}=\"");
3134            tag.find(&key).map(|i| {
3135                let rest = &tag[i + key.len()..];
3136                rest[..rest.find('"').unwrap()].to_string()
3137            })
3138        };
3139        // boxes: one per node, outside the groups, an NA attribute left off
3140        let boxes: Vec<_> = tags
3141            .iter()
3142            .filter(|(t, _)| t.contains("data-node="))
3143            .collect();
3144        assert_eq!(boxes.len(), 3);
3145        for (b, inside) in &boxes {
3146            assert!(!inside, "{b}");
3147            let id = attr(b, "data-node").unwrap();
3148            assert_eq!(attr(b, "data-value").is_some(), id == "Model", "{id}");
3149        }
3150        // edges: the caller's class on a path; the label's attributes
3151        assert!(tags.iter().any(|(t, _)| t.contains("data-edge=\"1&gt;2\"")
3152            && attr(t, "class").is_some_and(|c| c.contains("flowing"))));
3153        assert!(tags
3154            .iter()
3155            .any(|(t, _)| attr(t, "data-from").as_deref() == Some("Ingest")));
3156        assert!(svg.contains(" gg-graph-node\"") && svg.contains("gg-graph-edge-label"));
3157        // anofox-visualization#1317: a card-coloured box behind the label,
3158        // drawn before its text, so the edge stops clear of it
3159        let lbox = svg.find("gg-graph-edge-label-box").expect("a label box");
3160        let text = svg.find("gg-graph-edge-label\"").expect("the label");
3161        assert!(lbox < text, "the box is under the text");
3162        let rect = &svg[svg[..lbox].rfind('<').unwrap()..lbox];
3163        assert!(
3164            rect.starts_with("<rect") || rect.contains("<rect"),
3165            "{rect}"
3166        );
3167        // node contents grouped by node; lanes drawn with their names
3168        for id in labels {
3169            assert!(svg.contains(&format!("data-of=\"{id}\"")), "{id}");
3170        }
3171        assert!(svg.contains("data-lane=\"Right\""));
3172        assert!(svg.contains(">Left<") && svg.contains(">42<"));
3173    }
3174
3175    /// Forney style (#1172): an observation as a terminal square, its label
3176    /// beside it; a variable as a labelled edge, its name in the math font.
3177    #[test]
3178    fn forney_terminals_and_variable_edges() {
3179        use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
3180        let spec = [
3181            ("Cat", NodeShape::Glyph),
3182            ("T", NodeShape::Glyph),
3183            ("x₁", NodeShape::Terminal),
3184        ];
3185        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
3186        assert_eq!((sizes[2].w, sizes[2].h), (TERMINAL, TERMINAL));
3187        let gnodes: Vec<GraphNode> = sizes
3188            .iter()
3189            .map(|b| GraphNode {
3190                w: b.w,
3191                h: b.h,
3192                ..Default::default()
3193            })
3194            .collect();
3195        let gedges = vec![
3196            GraphEdge {
3197                from: 0,
3198                to: 1,
3199                label_w: None,
3200            },
3201            GraphEdge {
3202                from: 1,
3203                to: 2,
3204                label_w: None,
3205            },
3206        ];
3207        let l = layered(&gnodes, &gedges, &LayeredParams::default());
3208        let nodes: Vec<DrawNode> = spec
3209            .iter()
3210            .zip(&sizes)
3211            .enumerate()
3212            .map(|(i, ((_, shape), b))| DrawNode {
3213                id: format!("n{i}"),
3214                shape: *shape,
3215                lines: b.lines.clone(),
3216                stroke: (13, 148, 136),
3217                tooltip: b.lines.join(" "),
3218                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
3219                // the observation flagged: filled in its accent
3220                accent: (*shape == NodeShape::Terminal).then_some((217, 119, 6)),
3221                ..Default::default()
3222            })
3223            .collect();
3224        let edges = vec![
3225            // the variable s₀ between the two factors
3226            DrawEdge {
3227                colour: (13, 148, 136),
3228                width: 1.2,
3229                undirected: true,
3230                label: Some("s₀".to_string()),
3231                label_math: true,
3232                ..Default::default()
3233            },
3234            DrawEdge {
3235                colour: (13, 148, 136),
3236                width: 1.2,
3237                undirected: true,
3238                ..Default::default()
3239            },
3240        ];
3241        let render = |style: &GraphStyle| {
3242            draw(
3243                &l,
3244                &[],
3245                &[],
3246                &nodes,
3247                &edges,
3248                style,
3249                crate::theme::presets::theme_void(),
3250            )
3251            .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32 + 40, l.h.ceil() as u32)
3252            .unwrap()
3253        };
3254        let math = GraphStyle {
3255            math_font: Some("STIX Two Math, serif".to_string()),
3256            ..GraphStyle::default()
3257        };
3258        let svg = render(&math);
3259        let el = |text: &str| {
3260            let at = svg
3261                .find(&format!(">{text}</text>"))
3262                .unwrap_or_else(|| panic!("{text}"));
3263            svg[svg[..at].rfind('<').unwrap()..at].to_string()
3264        };
3265        // the terminal: a filled square, its label starting beside it
3266        assert!(svg.contains("gg-graph-node-terminal"), "terminal mark");
3267        assert!(
3268            svg.contains("fill=\"#D97706\""),
3269            "the terminal in its accent"
3270        );
3271        let x1 = el("x₁");
3272        assert!(
3273            x1.contains("text-anchor=\"start\"") && x1.contains("italic"),
3274            "{x1}"
3275        );
3276        let t = &l.nodes[2];
3277        let lx: f64 = x1
3278            .split("x=\"")
3279            .nth(1)
3280            .unwrap()
3281            .split('"')
3282            .next()
3283            .unwrap()
3284            .parse()
3285            .unwrap();
3286        assert!(
3287            lx > t.cx + t.w / 2.0,
3288            "the label right of the square: {lx} vs {}",
3289            t.cx
3290        );
3291        // the variable's edge label in the math font
3292        let s0 = el("s₀");
3293        assert!(
3294            s0.contains("STIX Two Math") && s0.contains("italic"),
3295            "{s0}"
3296        );
3297        // without a math font: a plain edge label
3298        let plain = render(&GraphStyle::default());
3299        let at = plain.find(">s₀</text>").unwrap();
3300        assert!(!plain[plain[..at].rfind('<').unwrap()..at].contains("italic"));
3301    }
3302
3303    /// A coin toss as a Forney-style factor graph: a Beta prior box, the
3304    /// parameter's circle, an equality node, Bernoulli boxes and observed
3305    /// circles in a plate; undirected edges with interface names near the
3306    /// factor.
3307    #[test]
3308    fn draws_a_factor_graph_with_shapes_and_a_plate() {
3309        let n = 3;
3310        // (label, shape)
3311        let mut spec = vec![
3312            ("Beta", NodeShape::Box),
3313            ("θ", NodeShape::Circle),
3314            ("=", NodeShape::Square),
3315        ];
3316        for _ in 0..n {
3317            spec.push(("Ber", NodeShape::Box));
3318        }
3319        for _ in 0..n {
3320            spec.push(("y", NodeShape::FilledCircle));
3321        }
3322        spec.push(("2.0", NodeShape::Text));
3323        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
3324        // (from, to, interface)
3325        let mut links = vec![(0, 1, "out"), (1, 2, ""), (9, 0, "a")];
3326        for i in 0..n {
3327            links.push((2, 3 + i, "p"));
3328            links.push((3 + i, 3 + n + i, "out"));
3329        }
3330        let gnodes: Vec<GraphNode> = sizes
3331            .iter()
3332            .map(|b| GraphNode {
3333                w: b.w,
3334                h: b.h,
3335                ..Default::default()
3336            })
3337            .collect();
3338        let gedges: Vec<GraphEdge> = links
3339            .iter()
3340            .map(|&(a, b, _)| GraphEdge {
3341                from: a,
3342                to: b,
3343                label_w: None,
3344            })
3345            .collect();
3346        // a plate reaches past its nodes: room for it in the margin
3347        let params = LayeredParams {
3348            margin: 32.0,
3349            ..Default::default()
3350        };
3351        let l = layered(&gnodes, &gedges, &params);
3352        let nodes: Vec<DrawNode> = spec
3353            .iter()
3354            .zip(&sizes)
3355            .enumerate()
3356            .map(|(i, ((_, shape), b))| DrawNode {
3357                id: format!("n{i}"),
3358                shape: *shape,
3359                lines: b.lines.clone(),
3360                stroke: (60, 60, 60),
3361                tooltip: b.lines.join(" "),
3362                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
3363                // θ's belief curve
3364                belief: (i == 1).then(|| (vec![0.0, 0.3, 1.0, 0.3, 0.0], (120, 80, 200))),
3365                // and its prior, wider
3366                prior: (i == 1).then(|| (vec![0.2, 0.4, 0.5, 0.4, 0.2], (150, 150, 150))),
3367                ..Default::default()
3368            })
3369            .collect();
3370        let edges: Vec<DrawEdge> = links
3371            .iter()
3372            .map(|&(a, b, iface)| DrawEdge {
3373                colour: (90, 90, 90),
3374                width: 1.2,
3375                undirected: true,
3376                label: (!iface.is_empty()).then(|| iface.to_string()),
3377                // the interface name near the factor
3378                label_at: Some(if spec[b].1 == NodeShape::Box {
3379                    0.8
3380                } else {
3381                    0.2
3382                }),
3383                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
3384                ..Default::default()
3385            })
3386            .collect();
3387        let plates = [Plate {
3388            label: "i = 1..3".to_string(),
3389            nodes: (3..3 + 2 * n).collect(),
3390        }];
3391        let style = GraphStyle::default();
3392        let svg = draw(
3393            &l,
3394            &[],
3395            &plates,
3396            &nodes,
3397            &edges,
3398            &style,
3399            crate::theme::presets::theme_void(),
3400        )
3401        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
3402        .unwrap();
3403        // every node is a mark, shapes classed, undirected: no arrowheads
3404        assert_eq!(svg.matches("data-node=").count(), spec.len());
3405        for shape in ["circle", "filled-circle", "square", "text"] {
3406            assert!(svg.contains(&format!("gg-graph-node-{shape}")), "{shape}");
3407        }
3408        assert!(
3409            !svg.contains("data-part=\"arrow\""),
3410            "an undirected edge has no arrowhead"
3411        );
3412        assert_eq!(svg.matches("data-edge=").count(), links.len());
3413        // θ's belief curve: a filled shape over its circle, in its group
3414        assert!(svg.contains("gg-graph-node-belief"), "belief layer");
3415        assert!(svg.contains("fill=\"#7850C8\""), "belief colour");
3416        // its prior: a dashed outline, drawn before (under) the belief
3417        let (pr, be) = (
3418            svg.find("gg-graph-node-prior").expect("prior layer"),
3419            svg.find("gg-graph-node-belief").unwrap(),
3420        );
3421        assert!(pr < be, "the prior under the belief");
3422        let mark = &svg[svg[..pr].rfind('<').unwrap()..pr];
3423        assert!(mark.contains("stroke-dasharray"), "dashed prior: {mark}");
3424        // no math font: bold sans labels
3425        assert!(!svg.contains("font-style=\"italic\""), "plain labels");
3426        // a math font: the shaped nodes' labels in it, italic; glyph colours
3427        let math = GraphStyle {
3428            math_font: Some("STIX Two Math, serif".to_string()),
3429            glyph_fill: Some((240, 247, 246)),
3430            glyph_ink: Some((13, 148, 136)),
3431            ..style.clone()
3432        };
3433        let msvg = draw(
3434            &l,
3435            &[],
3436            &plates,
3437            &nodes,
3438            &edges,
3439            &math,
3440            crate::theme::presets::theme_void(),
3441        )
3442        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
3443        .unwrap();
3444        assert!(msvg.contains("STIX Two Math"), "math font");
3445        assert!(msvg.contains("font-style=\"italic\""), "italic labels");
3446        // …but a constant stays upright
3447        let two = msvg.find(">2.0<").expect("the constant 2.0");
3448        let el = &msvg[msvg[..two].rfind('<').unwrap()..two];
3449        assert!(!el.contains("italic"), "upright constant: {el}");
3450        // the plate, and its label
3451        assert!(svg.contains("data-plate=\"i = 1..3\"") && svg.contains(">i = 1..3<"));
3452        // the observed circles' dark fill
3453        assert!(svg.contains(&format!(
3454            "fill=\"{}\"",
3455            hex(style.observed_fill).to_uppercase()
3456        )));
3457        // no two nodes overlap
3458        for (i, a) in l.nodes.iter().enumerate() {
3459            for b in &l.nodes[i + 1..] {
3460                let apart = (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
3461                    || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0;
3462                assert!(apart, "overlap");
3463            }
3464        }
3465        // the circle is round: rx is half its width
3466        let c = &l.nodes[1];
3467        assert!(svg.contains(&format!("rx=\"{:.2}\"", c.w / 2.0)), "{}", c.w);
3468    }
3469
3470    /// An HMM over five slices with learned transition (A) and observation
3471    /// (B) matrices, in bands param / state / obs: the state chain is one
3472    /// straight row, each observation below its state.
3473    #[test]
3474    fn banded_hmm_keeps_the_state_chain_straight() {
3475        use crate::graph_layout::{banded, BandedParams};
3476        let t_n = 5;
3477        // (label, shape, band)
3478        let mut spec: Vec<(String, NodeShape, usize)> = vec![
3479            ("Dir".into(), NodeShape::Glyph, 0), // 0: prior on A
3480            ("A".into(), NodeShape::Square, 0),  // 1: = of A
3481            ("Dir".into(), NodeShape::Glyph, 0), // 2: prior on B
3482            ("B".into(), NodeShape::Square, 0),  // 3: = of B
3483            ("Cat".into(), NodeShape::Glyph, 1), // 4: initial state prior
3484            ("s₀".into(), NodeShape::Circle, 1), // 5
3485        ];
3486        let mut links: Vec<(usize, usize, &str)> =
3487            vec![(0, 1, "out"), (2, 3, "out"), (4, 5, "out")];
3488        let mut prev = 5;
3489        for t in 1..=t_n {
3490            let tr = spec.len();
3491            spec.push(("T".into(), NodeShape::Glyph, 1));
3492            let eq = spec.len();
3493            spec.push((format!("s{t}"), NodeShape::Square, 1));
3494            let ob = spec.len();
3495            spec.push(("T".into(), NodeShape::Glyph, 2));
3496            let x = spec.len();
3497            spec.push((format!("x{t}"), NodeShape::FilledCircle, 2));
3498            links.extend([
3499                (prev, tr, "in"),
3500                (1, tr, "a"),
3501                (tr, eq, "out"),
3502                (eq, ob, "in"),
3503                (3, ob, "a"),
3504                (ob, x, "out"),
3505            ]);
3506            prev = eq;
3507        }
3508        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh, _)| node_size(*sh, l)).collect();
3509        let gnodes: Vec<GraphNode> = spec
3510            .iter()
3511            .zip(&sizes)
3512            .map(|((_, _, b), s)| GraphNode {
3513                w: s.w,
3514                h: s.h,
3515                lane: Some(*b),
3516                ..Default::default()
3517            })
3518            .collect();
3519        let gedges: Vec<GraphEdge> = links
3520            .iter()
3521            .map(|&(a, b, _)| GraphEdge {
3522                from: a,
3523                to: b,
3524                label_w: None,
3525            })
3526            .collect();
3527        let l = banded(
3528            &gnodes,
3529            &gedges,
3530            &BandedParams {
3531                bands: 3,
3532                margin: 32.0,
3533                ..Default::default()
3534            },
3535        );
3536        // the chain: every transition and state node on one row
3537        let chain: Vec<usize> = (0..spec.len())
3538            .filter(|&i| spec[i].2 == 1 && i != 4)
3539            .collect();
3540        let y = l.nodes[chain[0]].cy;
3541        for &i in &chain {
3542            assert_eq!(l.nodes[i].cy, y, "{} off the row", spec[i].0);
3543        }
3544        // each observation factor straight below its state's = node
3545        for t in 0..t_n {
3546            let (eq, ob) = (6 + 4 * t + 1, 6 + 4 * t + 2);
3547            assert_eq!(l.nodes[eq].cx, l.nodes[ob].cx, "slice {t}");
3548            assert!(l.nodes[ob].cy > y);
3549        }
3550        // no edge passes through a box other than its own two ends
3551        let crosses = |(x0, y0): (f64, f64), (x1, y1): (f64, f64), n: &PlacedNode| {
3552            // sampled along the segment, the box shrunk by a pixel
3553            (0..=40).any(|k| {
3554                let t = k as f64 / 40.0;
3555                let (x, y) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
3556                (x - n.cx).abs() < n.w / 2.0 - 1.0 && (y - n.cy).abs() < n.h / 2.0 - 1.0
3557            })
3558        };
3559        for (k, &(a, b, _)) in links.iter().enumerate() {
3560            for w in l.edges[k].windows(2) {
3561                for (i, n) in l.nodes.iter().enumerate() {
3562                    if i != a && i != b {
3563                        assert!(
3564                            !crosses(w[0], w[1], n),
3565                            "edge {a}->{b} crosses {}",
3566                            spec[i].0
3567                        );
3568                    }
3569                }
3570            }
3571        }
3572        // nothing overlaps
3573        for (i, a) in l.nodes.iter().enumerate() {
3574            for b in &l.nodes[i + 1..] {
3575                assert!(
3576                    (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
3577                        || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0
3578                );
3579            }
3580        }
3581        let nodes: Vec<DrawNode> = spec
3582            .iter()
3583            .zip(&sizes)
3584            .enumerate()
3585            .map(|(i, ((_, shape, _), b))| DrawNode {
3586                id: format!("n{i}"),
3587                shape: *shape,
3588                lines: b.lines.clone(),
3589                stroke: (60, 60, 60),
3590                ..Default::default()
3591            })
3592            .collect();
3593        let edges: Vec<DrawEdge> = links
3594            .iter()
3595            .map(|&(_, b, iface)| DrawEdge {
3596                colour: (90, 90, 90),
3597                width: 1.2,
3598                undirected: true,
3599                label: Some(iface.to_string()),
3600                label_at: Some(if spec[b].1 == NodeShape::Glyph {
3601                    0.8
3602                } else {
3603                    0.2
3604                }),
3605                ..Default::default()
3606            })
3607            .collect();
3608        let lanes = ["param".to_string(), "state".to_string(), "obs".to_string()];
3609        let svg = draw(
3610            &l,
3611            &lanes,
3612            &[],
3613            &nodes,
3614            &edges,
3615            &GraphStyle::default(),
3616            crate::theme::presets::theme_void(),
3617        )
3618        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
3619        .unwrap();
3620        if let Ok(path) = std::env::var("GGPLOT_GRAPH_SVG") {
3621            std::fs::write(path, &svg).unwrap();
3622        }
3623        assert_eq!(svg.matches("data-lane=").count(), 3);
3624    }
3625}