Skip to main content

ggplot_rs/
graph.rs

1//! Drawing a laid-out graph of boxes: swimlane bands, edges (polylines with
2//! an arrowhead, a linetype, a width and an optional label placed clear of
3//! the boxes) and node boxes (a wrapped label, an optional value line,
4//! status badge and sparkline, and an accent bar), as one [`GGPlot`] of
5//! ordinary layers.
6//!
7//! Works with [`graph_layout`](crate::graph_layout): size the boxes with
8//! [`node_box`], lay them out with [`layered`](crate::graph_layout::layered),
9//! then [`draw`] the result. What each mark says and what colour it takes
10//! is the caller's (the [`DrawNode`] / [`DrawEdge`] fields); where things go
11//! inside a box and along an edge is decided here. Every mark carries the
12//! caller's `data-*` attributes, and what belongs to one node is wrapped in
13//! `<g data-of="<id>">`, so a browser can address a node as one element.
14//! Moved here from anofox-visualization's `::DIAGRAM`
15//! (sipemu/ggplot-rs#497, DataZooDE/anofox-visualization#1153).
16
17use crate::geom::arrow::arrow;
18use crate::graph_layout::{GraphLayout, PlacedNode};
19use crate::prelude::*;
20use crate::render::backend::{LineEnd, Linetype};
21use crate::scale::linewidth::ScaleLinewidthContinuous;
22
23type Rgb = (u8, u8, u8);
24
25/// Box geometry (px).
26const LABEL_PX: f64 = 13.0;
27const VALUE_PX: f64 = 12.0;
28const BADGE_PX: f64 = 11.0;
29/// An edge label's and a lane name's text size.
30const SMALL_PX: f64 = 11.0;
31const LINE_H: f64 = 16.0;
32const BOX_PAD_X: f64 = 12.0;
33const BOX_PAD_Y: f64 = 9.0;
34const BOX_MIN_W: f64 = 92.0;
35const BOX_MAX_W: f64 = 208.0;
36/// A sparkline's strip in a box.
37const SPARK_H: f64 = 22.0;
38/// The arrowhead's length (px) at zero line width; the layout's
39/// [`LayeredParams::arrow`](crate::graph_layout::LayeredParams::arrow).
40const ARROW: f64 = 7.0;
41/// A node label's line limit; only beyond it is the last line cut with "…".
42const MAX_LINES: usize = 3;
43
44/// Approximate rendered width of `s` at `px` (proportional sans-serif).
45fn text_w(s: &str, px: f64, bold: bool) -> f64 {
46    let per = if bold { 0.6 } else { 0.56 };
47    s.chars().count() as f64 * px * per
48}
49
50/// The width (px) of an edge label as [`draw`] sets it (its widest line):
51/// the layout's [`GraphEdge::label_w`](crate::graph_layout::GraphEdge::label_w).
52pub fn edge_label_width(label: &str) -> f64 {
53    label
54        .split('\n')
55        .map(|l| text_w(l, SMALL_PX, false))
56        .fold(0.0, f64::max)
57}
58
59/// `s` wrapped into at most [`MAX_LINES`] lines of `max` px (the last cut
60/// with "…" when the label doesn't fit). Breaks at spaces; a word longer
61/// than a line breaks after a `/`, `-`, `_`, `.` or `,` in it
62/// (`duckdb/community-` + `extensions`, not `community-ex` + `tensions`),
63/// and only mid-word when it has none.
64fn wrap(s: &str, max: f64) -> Vec<String> {
65    let cap = ((max / (LABEL_PX * 0.6)).floor() as usize).max(4);
66    // (piece, glued to the previous one) — a long word's pieces are glued
67    let mut pieces: Vec<(String, bool)> = Vec::new();
68    for word in s.split_whitespace() {
69        let chars: Vec<char> = word.chars().collect();
70        let mut start = 0;
71        let mut first = true;
72        while chars.len() - start > cap {
73            let window = &chars[start..start + cap];
74            let cut = window
75                .iter()
76                .rposition(|c| matches!(c, '/' | '-' | '_' | '.' | ','))
77                .filter(|&i| i + 1 >= cap / 3)
78                .map(|i| i + 1)
79                .unwrap_or(cap);
80            pieces.push((chars[start..start + cut].iter().collect(), !first));
81            first = false;
82            start += cut;
83        }
84        pieces.push((chars[start..].iter().collect(), !first));
85    }
86    let mut lines: Vec<String> = Vec::new();
87    let mut cur = String::new();
88    for (piece, glued) in pieces {
89        let sep = if glued || cur.is_empty() { 0 } else { 1 };
90        if !cur.is_empty() && cur.chars().count() + sep + piece.chars().count() > cap {
91            lines.push(std::mem::take(&mut cur));
92        } else if sep == 1 {
93            cur.push(' ');
94        }
95        cur.push_str(&piece);
96    }
97    if !cur.is_empty() {
98        lines.push(cur);
99    }
100    if lines.is_empty() {
101        lines.push(String::new());
102    }
103    if lines.len() > MAX_LINES {
104        let rest = lines[MAX_LINES - 1..].join(" ");
105        let mut last: String = rest.chars().take(cap.saturating_sub(1)).collect();
106        last = last.trim_end().to_string();
107        last.push('…');
108        lines.truncate(MAX_LINES - 1);
109        lines.push(last);
110    }
111    lines
112}
113
114/// A node box's size and its label wrapped to fit.
115#[derive(Clone, Debug, PartialEq)]
116pub struct NodeBox {
117    pub w: f64,
118    pub h: f64,
119    pub lines: Vec<String>,
120}
121
122/// The box a node needs: its label wrapped onto at most three lines, plus a
123/// line for `value`, a badge row for `badge` and a sparkline strip when
124/// `spark` (as [`draw`] fills it).
125pub fn node_box(label: &str, value: Option<&str>, badge: Option<&str>, spark: bool) -> NodeBox {
126    let lines = wrap(label, BOX_MAX_W - 2.0 * BOX_PAD_X);
127    let mut w = lines
128        .iter()
129        .map(|l| text_w(l, LABEL_PX, true))
130        .fold(0.0, f64::max);
131    let mut h = 2.0 * BOX_PAD_Y + LINE_H * lines.len() as f64;
132    if let Some(v) = value {
133        w = w.max(text_w(v, VALUE_PX, true));
134        h += LINE_H;
135    }
136    if let Some(b) = badge {
137        w = w.max(text_w(b, BADGE_PX, false) + 22.0);
138        h += 20.0;
139    }
140    if spark {
141        w = w.max(110.0);
142        h += SPARK_H;
143    }
144    NodeBox {
145        w: (w + 2.0 * BOX_PAD_X).clamp(BOX_MIN_W, BOX_MAX_W),
146        h,
147        lines,
148    }
149}
150
151/// The colours and class names of a drawing.
152#[derive(Clone, Debug)]
153pub struct GraphStyle {
154    /// Box and badge fill, and the halo behind edge labels.
155    pub card: Rgb,
156    /// Swimlane band tint.
157    pub band: Rgb,
158    /// Lane names and edge labels.
159    pub muted: Rgb,
160    /// Node labels.
161    pub heading: Rgb,
162    /// Node values and badge text.
163    pub ink: Rgb,
164    /// A variable's circle ([`NodeShape::Circle`]).
165    pub variable_fill: Rgb,
166    /// An observed variable's circle ([`NodeShape::FilledCircle`]) and a
167    /// delta node's square; their labels are drawn in `card`.
168    pub observed_fill: Rgb,
169    /// A plate's dashed outline and its label.
170    pub plate: Rgb,
171    /// Prefix of the layer classes (`<prefix>node`, `<prefix>edge`,
172    /// `<prefix>edge-label`, `<prefix>lane`, `<prefix>lane-label`,
173    /// `<prefix>node-label`, `<prefix>node-value`, `<prefix>node-badge`,
174    /// `<prefix>node-spark`, `<prefix>plate`, `<prefix>plate-label`,
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 mark on a node, at its top right corner in a small round badge.
643#[derive(Clone, Copy, Debug, PartialEq, Eq)]
644pub enum NodeIcon {
645    /// A hand: the node is set by an intervention (`do`).
646    Hand,
647}
648
649/// What a node's box shows, and its attributes. Its geometry comes from the
650/// layout ([`PlacedNode`]); its label lines from [`node_box`].
651#[derive(Clone, Debug, Default)]
652pub struct DrawNode {
653    /// The `data-of` group of everything drawn for the node.
654    pub id: String,
655    /// Its mark; anything but a box shows only the label.
656    pub shape: NodeShape,
657    /// The label, wrapped ([`NodeBox::lines`]).
658    pub lines: Vec<String>,
659    /// A value line under the label.
660    pub value: Option<String>,
661    /// A badge row: its text and its dot's (and outline's) colour.
662    pub badge: Option<(String, Rgb)>,
663    /// The box (or circle, square) outline.
664    pub stroke: Rgb,
665    /// A thin bar along the box's left edge; a filled mark (an observation,
666    /// a terminal) is filled with it instead.
667    pub accent: Option<Rgb>,
668    /// A sparkline (two values or more) along the bottom, and its colour.
669    pub spark: Option<(Vec<f64>, Rgb)>,
670    /// A belief curve over the node (a factor graph variable's density):
671    /// heights 0..=1 at evenly spaced points (three or more), and its colour.
672    pub belief: Option<(Vec<f64>, Rgb)>,
673    /// The prior behind the belief curve: heights on the same scale and
674    /// span as [`DrawNode::belief`], drawn as a faint dashed outline, and
675    /// its colour.
676    pub prior: Option<(Vec<f64>, Rgb)>,
677    /// A discrete node's states, one row each under the label (a boxed
678    /// shape; size it with [`states_box`]), and the bars' colour.
679    pub states: Option<(Vec<StateBar>, Rgb)>,
680    /// The box's (or diamond's) fill; `None` is the card colour. E.g. a
681    /// node with evidence, shaded.
682    pub fill: Option<Rgb>,
683    /// A mark at the box's top right corner, e.g. a hand for a node set by
684    /// an intervention.
685    pub icon: Option<NodeIcon>,
686    /// A table under the label (a boxed shape; size it with
687    /// [`table_box`]), e.g. an influence diagram's policy, and the colour
688    /// its marked cells are tinted with.
689    pub table: Option<(NodeTable, Rgb)>,
690    pub tooltip: String,
691    /// `data-*` on the box (the hit target); every node lists the same
692    /// names, in the same order.
693    pub attrs: Vec<DataAttr>,
694}
695
696/// An edge's line pattern.
697#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
698pub enum EdgeLine {
699    #[default]
700    Solid,
701    Dashed,
702    /// Round dots (zero-length dashes with round caps).
703    Dots,
704}
705
706/// What an edge looks like, and its attributes. Its points come from the
707/// layout ([`GraphLayout::edges`]); the arrowhead is on its last point,
708/// unless `undirected`.
709#[derive(Clone, Debug, Default)]
710pub struct DrawEdge {
711    pub colour: Rgb,
712    /// Line width (px), see [`flow_width`].
713    pub width: f64,
714    pub line: EdgeLine,
715    /// Extra CSS classes on the path.
716    pub class: Option<String>,
717    pub tooltip: String,
718    /// A label (`\n` breaks lines) on the edge, clear of the boxes.
719    pub label: Option<String>,
720    /// Where along the edge the label goes (0 at its start, 1 at its end),
721    /// e.g. near a factor for an interface name; `None`: the middle, moved
722    /// along the edge until no box covers it.
723    pub label_at: Option<f64>,
724    /// No arrowhead (a factor graph's edges).
725    pub undirected: bool,
726    /// The label names a variable (Forney style: the edge is the variable):
727    /// set in [`GraphStyle::math_font`] when there is one, in the heading
728    /// colour.
729    pub label_math: bool,
730    /// `data-*` on the path; every edge lists the same names, in the same
731    /// order.
732    pub attrs: Vec<DataAttr>,
733    /// `data-*` on the label (and on a cut edge's break mark).
734    pub label_attrs: Vec<DataAttr>,
735    /// The edge is cut (its child is set by an intervention, so the parent
736    /// no longer acts on it): a break mark across its middle — a gap and
737    /// two slashes in the edge's colour. Give it a muted colour.
738    pub cut: bool,
739}
740
741/// An edge's width (px) for what it carries, `value` of the graph's `max`:
742/// area-true (`sqrt`), 1.4 px to 7 px; 1.6 px without a value; dotted edges
743/// 3–6 px so their dots show. Rounded to 0.1 px.
744pub fn flow_width(value: Option<f64>, max: f64, line: EdgeLine) -> f64 {
745    let width = match value {
746        Some(v) if max > 0.0 => 1.4 + 5.6 * (v.max(0.0) / max).sqrt(),
747        _ => 1.6,
748    };
749    let width = match line {
750        EdgeLine::Dots => width.clamp(3.0, 6.0),
751        _ => width,
752    };
753    (width * 10.0).round() / 10.0
754}
755
756/// Columns built row by row, in px with y down.
757#[derive(Default)]
758struct Frame(Vec<(String, Vec<Value>)>);
759
760impl Frame {
761    fn col(&mut self, name: &str) -> &mut Vec<Value> {
762        let i = match self.0.iter().position(|(n, _)| n == name) {
763            Some(i) => i,
764            None => {
765                self.0.push((name.to_string(), Vec::new()));
766                self.0.len() - 1
767            }
768        };
769        &mut self.0[i].1
770    }
771    fn num(&mut self, name: &str, v: f64) -> &mut Self {
772        self.col(name).push(Value::Float(v));
773        self
774    }
775    fn txt(&mut self, name: &str, v: impl Into<String>) -> &mut Self {
776        self.col(name).push(Value::Str(v.into()));
777        self
778    }
779    fn opt(&mut self, name: &str, v: Option<String>) -> &mut Self {
780        self.col(name).push(v.map_or(Value::Na, Value::Str));
781        self
782    }
783    /// `attrs` as columns `a:<name>`.
784    fn attrs(&mut self, attrs: &[DataAttr]) -> &mut Self {
785        for (n, v) in attrs {
786            self.opt(&format!("a:{n}"), v.clone());
787        }
788        self
789    }
790    fn is_empty(&self) -> bool {
791        self.0.first().is_none_or(|(_, v)| v.is_empty())
792    }
793    /// `aes` plus a `data_attr` per `a:<name>` column, in column order.
794    fn attr_aes(&self, mut aes: Aes) -> Aes {
795        for (n, _) in &self.0 {
796            if let Some(name) = n.strip_prefix("a:") {
797                aes = aes.data_attr(name, n);
798            }
799        }
800        aes
801    }
802    /// The frame's columns, its pixel y (down) flipped to data y (up) on a
803    /// canvas `h` tall: `y` → `h - y`, and a rect's `y0`/`y1` swapped as
804    /// they flip so `y0` stays the low edge.
805    fn take(&mut self, h: f64) -> Vec<(String, Vec<Value>)> {
806        let flip = |v: Vec<Value>| -> Vec<Value> {
807            v.into_iter()
808                .map(|x| match x {
809                    Value::Float(y) => Value::Float(h - y),
810                    other => other,
811                })
812                .collect()
813        };
814        std::mem::take(&mut self.0)
815            .into_iter()
816            .map(|(n, v)| match n.as_str() {
817                "y" => (n, flip(v)),
818                "y0" => ("y1".to_string(), flip(v)),
819                "y1" => ("y0".to_string(), flip(v)),
820                _ => (n, v),
821            })
822            .collect()
823    }
824}
825
826/// Frames keyed by a colour a geom only takes as a fixed parameter (a
827/// rect's stroke), in first-seen order: one layer per colour.
828fn by_colour(v: &mut Vec<(Rgb, Frame)>, c: Rgb) -> &mut Frame {
829    let i = match v.iter().position(|(k, _)| *k == c) {
830        Some(i) => i,
831        None => {
832            v.push((c, Frame::default()));
833            v.len() - 1
834        }
835    };
836    &mut v[i].1
837}
838
839/// `aes` plus `data-state` when the frame has a `state` column (a state
840/// row's name and probability: what a click on the row names; the bars are
841/// decorative and carry none).
842fn state_attr(f: &Frame, aes: Aes) -> Aes {
843    if f.0.iter().any(|(n, _)| n == "state") {
844        aes.data_attr("state", "state")
845    } else {
846        aes
847    }
848}
849
850fn hex(c: Rgb) -> String {
851    format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
852}
853
854/// The point a fraction `t` (0..1) of the way along a polyline.
855fn point_at(pts: &[(f64, f64)], t: f64) -> (f64, f64) {
856    let seg = |i: usize| {
857        let (a, b) = (pts[i], pts[i + 1]);
858        ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
859    };
860    let total: f64 = (0..pts.len().saturating_sub(1)).map(seg).sum();
861    let mut left = total * t;
862    for i in 0..pts.len().saturating_sub(1) {
863        let l = seg(i);
864        if l >= left && l > 0.0 {
865            let t = left / l;
866            let (a, b) = (pts[i], pts[i + 1]);
867            return (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
868        }
869        left -= l;
870    }
871    pts.first().copied().unwrap_or((0.0, 0.0))
872}
873
874/// Where an edge's label goes: the midpoint of the edge, else the nearest
875/// point along it where the label's box (11 px lines drawn around `y - 4`)
876/// touches no node box — so a node doesn't cover it.
877fn edge_label_at(pts: &[(f64, f64)], label: &str, nodes: &[PlacedNode]) -> (f64, f64) {
878    let lines = label.split('\n').count();
879    let hw = edge_label_width(label) / 2.0 + 3.0;
880    let hh = lines as f64 * 6.6 + 3.0;
881    let clear = |(x, y): (f64, f64)| {
882        let cy = y - 4.0 - 0.36 * SMALL_PX;
883        nodes
884            .iter()
885            .all(|n| (x - n.cx).abs() >= hw + n.w / 2.0 || (cy - n.cy).abs() >= hh + n.h / 2.0)
886    };
887    let mid = point_at(pts, 0.5);
888    [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74, 0.18, 0.82]
889        .into_iter()
890        .map(|t| point_at(pts, t))
891        .find(|&p| clear(p))
892        .unwrap_or(mid)
893}
894
895/// An end label's anchor (as for a mid label: the text goes 4 px above
896/// it): on the edge's last (first) segment, its near side `LABEL_CLEAR`
897/// from the box the edge ends at; on a vertical segment beside the line
898/// instead, its top `LABEL_CLEAR` below (above) that box. At most half
899/// the segment in.
900fn end_label_at(pts: &[(f64, f64)], label: &str, t: f64) -> (f64, f64) {
901    use crate::graph_layout::LABEL_CLEAR;
902    let n = pts.len();
903    if n < 2 {
904        return pts.first().copied().unwrap_or((0.0, 0.0));
905    }
906    let (end, prev) = if t >= 0.5 {
907        (pts[n - 1], pts[n - 2])
908    } else {
909        (pts[0], pts[1])
910    };
911    let (dx, dy) = (prev.0 - end.0, prev.1 - end.1);
912    let len = (dx * dx + dy * dy).sqrt();
913    if len == 0.0 {
914        return end;
915    }
916    let (ux, uy) = (dx / len, dy / len);
917    let lines = label.split('\n').count() as f64;
918    let hw = edge_label_width(label) / 2.0;
919    let hh = lines * 6.6;
920    // the anchor sits 4 px + 0.36 em below the text's middle
921    let below_mid = 4.0 + 0.36 * SMALL_PX;
922    if ux.abs() >= uy.abs() {
923        // along the line, above it: its near side LABEL_CLEAR from the box
924        let s = (hw + LABEL_CLEAR).min(len * 0.5);
925        (end.0 + ux * s, end.1 + uy * s)
926    } else {
927        // beside a vertical line, its top (bottom) clear of the box
928        let s = (hh + LABEL_CLEAR).min(len * 0.5);
929        (end.0 + LABEL_CLEAR + hw, end.1 + uy * s + below_mid)
930    }
931}
932
933/// Text is centred on its y (`dominant-baseline="middle"`); the layout
934/// places lines by their baseline. A cap-height-ish shift between the two.
935fn mid_of_baseline(baseline: f64, px: f64) -> f64 {
936    baseline - 0.36 * px
937}
938
939/// Draw a laid-out graph on a `layout.w` × `layout.h` px canvas: `lanes`
940/// names the layout's bands, `plates` group nodes, `nodes` and `edges` are
941/// in the layout's order.
942/// `theme` is the base (a void theme; the legend is turned off). Render the
943/// result with e.g. `render_svg_native_at(0.0, 0.0, w, h)` at the canvas
944/// size rounded up.
945pub fn draw(
946    layout: &GraphLayout,
947    lanes: &[String],
948    plates: &[Plate],
949    nodes: &[DrawNode],
950    edges: &[DrawEdge],
951    style: &GraphStyle,
952    mut theme: Theme,
953) -> GGPlot {
954    let s = style;
955    let class = |name: &str| format!("{}{name}", s.class_prefix);
956    let (w, h) = (layout.w.ceil().max(1.0), layout.h.ceil().max(1.0));
957    theme.legend_position = crate::theme::LegendPosition::None;
958    let mut plot = GGPlot::new(vec![
959        ("x".to_string(), vec![Value::Float(0.0), Value::Float(w)]),
960        ("y".to_string(), vec![Value::Float(0.0), Value::Float(h)]),
961    ])
962    .theme(theme)
963    // the canvas is the view (a zoom, so a mark reaching past it is clipped
964    // rather than dropped); `Frame::take` flips the layout's y-down pixels
965    .scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
966    .scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
967    .coord_cartesian_zoom(Some((0.0, w)), Some((0.0, h)))
968    .scale_color_identity()
969    .scale_fill_identity()
970    .scale_linewidth(
971        ScaleLinewidthContinuous::new()
972            .with_limits(0.0, 16.0)
973            .with_range(0.0, 16.0),
974    )
975    .scale_linetype_manual(vec![
976        ("solid", Linetype::Solid),
977        ("dashed", Linetype::Custom(vec![(6.0, 4.0)])),
978        // round caps on a zero-length dash: moving dots
979        ("dots", Linetype::Custom(vec![(0.0, 10.0)])),
980    ]);
981    let rect_aes = || Aes::new().xmin("x0").xmax("x1").ymin("y0").ymax("y1");
982    let inert = [("pointer-events", "none")];
983
984    // swimlanes (under everything): a tinted band per lane, its name on top
985    let (mut even, mut odd, mut names) = (Frame::default(), Frame::default(), Frame::default());
986    for &(l, x0, y0, x1, y1) in &layout.bands {
987        let name = lanes.get(l).cloned().unwrap_or_default();
988        let f = if l % 2 == 0 { &mut even } else { &mut odd };
989        f.num("x0", x0).num("x1", x1).num("y0", y0).num("y1", y1);
990        f.txt("lane", name.clone());
991        names
992            .num("x", x0 + 8.0)
993            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
994        names.txt("label", name);
995    }
996    for (mut f, alpha) in [(even, 0.35), (odd, 0.18)] {
997        if f.is_empty() {
998            continue;
999        }
1000        plot = plot
1001            .geom_rect_with(
1002                GeomRect {
1003                    fill: s.band,
1004                    alpha,
1005                    line_width: 0.0,
1006                    ..Default::default()
1007                }
1008                .with_radius(6.0),
1009            )
1010            .layer_data(f.take(h))
1011            .layer_aes(rect_aes().data_attr("lane", "lane"))
1012            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane"))]);
1013    }
1014    if !names.is_empty() {
1015        plot = plot
1016            .geom_text_with(GeomText {
1017                size: SMALL_PX,
1018                color: s.muted,
1019                hjust: 0.0,
1020                fontface: FontFace::Bold,
1021                ..Default::default()
1022            })
1023            .layer_data(names.take(h))
1024            .layer_aes(Aes::new().x("x").y("y").label("label"))
1025            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane-label"))]);
1026    }
1027
1028    // plates (under the edges): a dashed box around each collection
1029    let (mut pf, mut pl) = (Frame::default(), Frame::default());
1030    for p in plates {
1031        let members: Vec<&PlacedNode> = p
1032            .nodes
1033            .iter()
1034            .filter_map(|&i| layout.nodes.get(i))
1035            .collect();
1036        if members.is_empty() {
1037            continue;
1038        }
1039        let pad = 8.0;
1040        let x0 = members
1041            .iter()
1042            .map(|n| n.cx - n.w / 2.0)
1043            .fold(f64::INFINITY, f64::min)
1044            - pad;
1045        let x1 = members
1046            .iter()
1047            .map(|n| n.cx + n.w / 2.0)
1048            .fold(f64::NEG_INFINITY, f64::max)
1049            + pad;
1050        let y0 = members
1051            .iter()
1052            .map(|n| n.cy - n.h / 2.0)
1053            .fold(f64::INFINITY, f64::min)
1054            - pad
1055            - 14.0;
1056        let y1 = members
1057            .iter()
1058            .map(|n| n.cy + n.h / 2.0)
1059            .fold(f64::NEG_INFINITY, f64::max)
1060            + pad;
1061        for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] {
1062            pf.num("x", x).num("y", y).txt("lt", "dashed");
1063            pf.txt("g", p.label.clone()).txt("plate", p.label.clone());
1064        }
1065        pl.num("x", x0 + 6.0)
1066            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
1067        pl.txt("label", p.label.clone());
1068    }
1069    if !pf.is_empty() {
1070        plot = plot
1071            .geom_path_with(GeomPath::default().color(s.plate).linewidth(1.0))
1072            .layer_data(pf.take(h))
1073            .layer_aes(
1074                Aes::new()
1075                    .x("x")
1076                    .y("y")
1077                    .group("g")
1078                    .linetype("lt")
1079                    .data_attr("plate", "plate"),
1080            )
1081            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate"))]);
1082        plot = plot
1083            .geom_text_with(GeomText {
1084                size: SMALL_PX,
1085                color: s.plate,
1086                hjust: 0.0,
1087                ..Default::default()
1088            })
1089            .layer_data(pl.take(h))
1090            .layer_aes(Aes::new().x("x").y("y").label("label"))
1091            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate-label"))]);
1092    }
1093
1094    // edges (under the nodes): one path per edge, arrowed ones first
1095    let (mut ef, mut uf, mut lf) = (Frame::default(), Frame::default(), Frame::default());
1096    // a variable's name on its edge (Forney style), in the math font
1097    let mut lmf = Frame::default();
1098    // a cut edge's break mark: the gap (card-coloured) and two slashes
1099    let (mut cgap, mut cmark) = (Frame::default(), Frame::default());
1100    for (k, e) in edges.iter().enumerate() {
1101        let Some(route) = layout.edges.get(k) else {
1102            continue;
1103        };
1104        let mut pts = route.clone();
1105        if pts.len() < 2 {
1106            continue;
1107        }
1108        // the arrow's tip is on the path's last point and its head is
1109        // stroked as wide as the line (its mitred tip reaching about one
1110        // line width further): end the path one width short of the box so
1111        // the tip lands on its edge.
1112        if !e.undirected {
1113            let n = pts.len();
1114            let ((fx, fy), (tx, ty)) = (pts[n - 2], pts[n - 1]);
1115            let len = ((tx - fx).powi(2) + (ty - fy).powi(2)).sqrt().max(1e-6);
1116            let pull = e.width.min(len / 2.0);
1117            pts[n - 1] = (tx - (tx - fx) / len * pull, ty - (ty - fy) / len * pull);
1118        }
1119        if e.cut {
1120            let total: f64 = pts
1121                .windows(2)
1122                .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt())
1123                .sum();
1124            if total > 16.0 {
1125                let (mx, my) = point_at(&pts, 0.5);
1126                let (ax, ay) = point_at(&pts, 0.5 - 2.0 / total);
1127                let (bx, by) = point_at(&pts, 0.5 + 2.0 / total);
1128                let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt().max(1e-6);
1129                let (ux, uy) = ((bx - ax) / len, (by - ay) / len);
1130                let g = format!("c{k:04}");
1131                for d in [-4.0, 4.0] {
1132                    cgap.num("x", mx + ux * d).num("y", my + uy * d);
1133                    cgap.txt("g", g.clone()).num("lw", e.width + 2.5);
1134                    cgap.attrs(&e.label_attrs);
1135                }
1136                // each slash across the line, leaning 30° along it
1137                let (c30, s30) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
1138                let (vx, vy) = (-uy * c30 + ux * s30, ux * c30 + uy * s30);
1139                for (i, off) in [-3.5, 3.5].into_iter().enumerate() {
1140                    let (cx, cy) = (mx + ux * off, my + uy * off);
1141                    for t in [-5.0, 5.0] {
1142                        cmark.num("x", cx + vx * t).num("y", cy + vy * t);
1143                        cmark.txt("g", format!("{g}-{i}")).txt("col", hex(e.colour));
1144                        cmark.attrs(&e.label_attrs);
1145                    }
1146                }
1147            }
1148        }
1149        let ef = if e.undirected { &mut uf } else { &mut ef };
1150        let lt = match e.line {
1151            EdgeLine::Solid => "solid",
1152            EdgeLine::Dashed => "dashed",
1153            EdgeLine::Dots => "dots",
1154        };
1155        for &(x, y) in &pts {
1156            ef.num("x", x).num("y", y).txt("g", format!("e{k:04}"));
1157            ef.txt("col", hex(e.colour))
1158                .num("lw", e.width)
1159                .txt("lt", lt);
1160            ef.opt("cls", e.class.clone()).txt("tip", e.tooltip.clone());
1161            ef.attrs(&e.attrs);
1162        }
1163        // a bus-routed edge's label is left to its tooltip: on the shared
1164        // lane or at a shared entry it would only clutter
1165        let routed = layout.routed.get(k).copied().unwrap_or(false);
1166        if let Some(l) = e.label.as_ref().filter(|_| !routed) {
1167            let (mx, my) = match e.label_at {
1168                // near an end (a factor's interface): beside the box at
1169                // that end, clear of it (anofox-visualization#1238)
1170                Some(t) => end_label_at(route, l, t),
1171                None => edge_label_at(route, l, &layout.nodes),
1172            };
1173            let f = if e.label_math && s.math_font.is_some() {
1174                &mut lmf
1175            } else {
1176                &mut lf
1177            };
1178            f.num("x", mx).num("y", mid_of_baseline(my - 4.0, SMALL_PX));
1179            f.txt("label", l.clone());
1180            f.attrs(&e.label_attrs);
1181        }
1182    }
1183    for (mut f, arrowed) in [(ef, true), (uf, false)] {
1184        if f.is_empty() {
1185            continue;
1186        }
1187        let aes = f.attr_aes(
1188            Aes::new()
1189                .x("x")
1190                .y("y")
1191                .group("g")
1192                .color("col")
1193                .linewidth("lw")
1194                .linetype("lt")
1195                .class("cls")
1196                .tooltip("tip"),
1197        );
1198        let mut geom = GeomPath::default().lineend(LineEnd::Round);
1199        if arrowed {
1200            // a 7 px + width head, ~29° half-angle
1201            geom = geom.arrow(
1202                arrow()
1203                    .closed()
1204                    .angle(29.0)
1205                    .length(ARROW + 1.0)
1206                    .length_per_linewidth(1.2),
1207            );
1208        }
1209        plot = plot
1210            .geom_path_with(geom)
1211            .layer_data(f.take(h))
1212            .layer_aes(aes)
1213            .layer_svg_attr("class", class("edge"));
1214    }
1215    if !cgap.is_empty() {
1216        let aes = cgap.attr_aes(Aes::new().x("x").y("y").group("g").linewidth("lw"));
1217        plot = plot
1218            .geom_path_with(GeomPath::default().color(s.card).lineend(LineEnd::Butt))
1219            .layer_data(cgap.take(h))
1220            .layer_aes(aes)
1221            .decorative()
1222            .layer_svg_attrs(inert)
1223            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-cut"))]);
1224        let aes = cmark.attr_aes(Aes::new().x("x").y("y").group("g").color("col"));
1225        plot = plot
1226            .geom_path_with(GeomPath::default().linewidth(1.4).lineend(LineEnd::Round))
1227            .layer_data(cmark.take(h))
1228            .layer_aes(aes)
1229            .decorative()
1230            .layer_svg_attrs(inert)
1231            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-cut"))]);
1232    }
1233    if !lmf.is_empty() {
1234        let aes = lmf.attr_aes(Aes::new().x("x").y("y").label("label"));
1235        plot = plot
1236            .geom_text_with(
1237                GeomText {
1238                    size: LABEL_PX + 1.0,
1239                    color: s.heading,
1240                    fontface: FontFace::Italic,
1241                    fontfamily: s.math_font.clone().unwrap_or_default(),
1242                    ..Default::default()
1243                }
1244                .bg_colour(s.card)
1245                .bg_r(2.0),
1246            )
1247            .layer_data(lmf.take(h))
1248            .layer_aes(aes)
1249            .layer_svg_attrs(inert)
1250            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
1251    }
1252    if !lf.is_empty() {
1253        // text directly on the line, a card-coloured halo keeping it legible
1254        let aes = lf.attr_aes(Aes::new().x("x").y("y").label("label"));
1255        plot = plot
1256            .geom_text_with(
1257                GeomText {
1258                    size: SMALL_PX,
1259                    color: s.muted,
1260                    ..Default::default()
1261                }
1262                .bg_colour(s.card)
1263                .bg_r(2.0),
1264            )
1265            .layer_data(lf.take(h))
1266            .layer_aes(aes)
1267            .layer_svg_attrs(inert)
1268            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
1269    }
1270
1271    // nodes in reading order: the box (the hit target, outside any `data-of`
1272    // group), then what it shows, grouped per node
1273    let mut order: Vec<usize> = (0..nodes.len().min(layout.nodes.len())).collect();
1274    order.sort_by_key(|&i| (layout.nodes[i].order, i));
1275    // boxes, a layer per (outline, shape, fill)
1276    let mut boxes: Vec<((Rgb, NodeShape, Rgb), Frame)> = Vec::new();
1277    // a double box's inner outline, by colour
1278    let mut outlines: Vec<(Rgb, Frame)> = Vec::new();
1279    // a diamond's hit target (an invisible box) and its mark, by outline
1280    let (mut hits, mut diamonds) = (Frame::default(), Vec::<(Rgb, Frame)>::new());
1281    // state rows: the prior's faint bar, its tick, the bar, the names (the
1282    // observed one bold) and the probabilities
1283    let (mut sprior, mut stick, mut sbar) = (Frame::default(), Frame::default(), Frame::default());
1284    let (mut sname, mut sseen, mut stext) = (Frame::default(), Frame::default(), Frame::default());
1285    // a state's change (▲ up in the heading colour, bold; ▼ down muted)
1286    let (mut sup, mut sdown) = (Frame::default(), Frame::default());
1287    // a node's table: the current row's band, the marked cells' tint, the
1288    // header (left, right), the row names, the cells and the marked cells
1289    let (mut tband, mut tmarkbg) = (Frame::default(), Frame::default());
1290    let (mut thead_l, mut thead_r) = (Frame::default(), Frame::default());
1291    let (mut tname, mut tcell, mut tmark) = (Frame::default(), Frame::default(), Frame::default());
1292    // an icon's badge, its rounded rects and polygons
1293    let (mut ibadge, mut irect, mut ipoly) = (Frame::default(), Frame::default(), Frame::default());
1294    let mut beliefs = Frame::default();
1295    let mut priors = Frame::default();
1296    // shaped nodes, a layer per (shape, corner radius, outline)
1297    let mut shaped: Vec<((NodeShape, u64, Rgb), Frame)> = Vec::new();
1298    let (mut inside, mut inverse, mut above, mut glyphs, mut texts, mut beside) = (
1299        Frame::default(),
1300        Frame::default(),
1301        Frame::default(),
1302        Frame::default(),
1303        Frame::default(),
1304        Frame::default(),
1305    );
1306    let mut badges: Vec<(Rgb, Frame)> = Vec::new();
1307    let (mut accent, mut lines, mut values) =
1308        (Frame::default(), Frame::default(), Frame::default());
1309    let (mut dots, mut btext, mut spark, mut ends) = (
1310        Frame::default(),
1311        Frame::default(),
1312        Frame::default(),
1313        Frame::default(),
1314    );
1315    for v in order {
1316        let nd = &nodes[v];
1317        let pn = &layout.nodes[v];
1318        let id = nd.id.clone();
1319        let (x, y) = (pn.cx - pn.w / 2.0, pn.cy - pn.h / 2.0);
1320        // the belief curve sits over the node (over a square's label)
1321        let squared = matches!(nd.shape, NodeShape::Square | NodeShape::FilledSquare);
1322        let base = y - if squared { 17.0 } else { 3.0 };
1323        let x0 = pn.cx - BELIEF_W / 2.0;
1324        let curve = |hs: &[f64]| -> Vec<(f64, f64)> {
1325            let last = (hs.len() - 1) as f64;
1326            hs.iter()
1327                .enumerate()
1328                .map(|(i, &h)| {
1329                    (
1330                        x0 + BELIEF_W * i as f64 / last,
1331                        base - h.clamp(0.0, 1.0) * BELIEF_H,
1332                    )
1333                })
1334                .collect()
1335        };
1336        // the prior: a faint outline behind the belief
1337        if let Some((hs, col)) = nd.prior.as_ref().filter(|(h, _)| h.len() >= 3) {
1338            for (px, py) in curve(hs) {
1339                priors.num("x", px).num("y", py).txt("g", id.clone());
1340                priors.txt("col", hex(*col)).txt("lt", "dashed");
1341                priors.txt("of", id.clone());
1342            }
1343        }
1344        if let Some((hs, col)) = nd.belief.as_ref().filter(|(h, _)| h.len() >= 3) {
1345            let mut pts = curve(hs);
1346            pts.push((x0 + BELIEF_W, base));
1347            pts.push((x0, base));
1348            for (px, py) in pts {
1349                beliefs.num("x", px).num("y", py).txt("g", id.clone());
1350                beliefs.txt("fill", hex(*col)).txt("of", id.clone());
1351            }
1352        }
1353        if nd.shape == NodeShape::Diamond {
1354            hits.num("x0", x)
1355                .num("x1", x + pn.w)
1356                .num("y0", y)
1357                .num("y1", y + pn.h);
1358            hits.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1359            let f = by_colour(&mut diamonds, nd.stroke);
1360            for (px, py) in [(pn.cx, y), (x + pn.w, pn.cy), (pn.cx, y + pn.h), (x, pn.cy)] {
1361                f.num("x", px).num("y", py).txt("g", id.clone());
1362                f.txt("fill", hex(nd.fill.unwrap_or(s.card)))
1363                    .txt("of", id.clone());
1364            }
1365            // the label (and value) centred in it
1366            let n = nd.lines.len() + usize::from(nd.value.is_some());
1367            let mut base = pn.cy - LINE_H * n as f64 / 2.0 + 12.0;
1368            for line in &nd.lines {
1369                lines
1370                    .num("x", pn.cx)
1371                    .num("y", mid_of_baseline(base, LABEL_PX));
1372                lines.txt("label", line.clone()).txt("of", id.clone());
1373                base += LINE_H;
1374            }
1375            if let Some(fv) = &nd.value {
1376                values
1377                    .num("x", pn.cx)
1378                    .num("y", mid_of_baseline(base, VALUE_PX));
1379                values.txt("label", fv.clone()).txt("of", id.clone());
1380            }
1381            continue;
1382        }
1383        if !nd.shape.boxed() {
1384            let r = match nd.shape {
1385                NodeShape::Circle | NodeShape::FilledCircle => pn.w.min(pn.h) / 2.0,
1386                NodeShape::Square | NodeShape::FilledSquare | NodeShape::Terminal => 1.5,
1387                NodeShape::Glyph => 4.0,
1388                _ => 0.0,
1389            };
1390            let (fill, stroke) = match nd.shape {
1391                NodeShape::Circle => (s.variable_fill, nd.stroke),
1392                // a filled mark takes the node's accent (a status: an
1393                // observation the model did not expect) over the observed fill
1394                NodeShape::FilledCircle | NodeShape::FilledSquare | NodeShape::Terminal => {
1395                    let c = nd.accent.unwrap_or(s.observed_fill);
1396                    (c, c)
1397                }
1398                NodeShape::Square => (s.card, nd.stroke),
1399                NodeShape::Glyph => (s.glyph_fill.unwrap_or(s.card), nd.stroke),
1400                _ => (s.card, s.card),
1401            };
1402            let key = (nd.shape, r.to_bits(), stroke);
1403            let i = match shaped.iter().position(|(k, _)| *k == key) {
1404                Some(i) => i,
1405                None => {
1406                    shaped.push((key, Frame::default()));
1407                    shaped.len() - 1
1408                }
1409            };
1410            let f = &mut shaped[i].1;
1411            f.num("x0", x)
1412                .num("x1", x + pn.w)
1413                .num("y0", y)
1414                .num("y1", y + pn.h);
1415            f.txt("fill", hex(fill));
1416            f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1417            let label = nd.lines.join(" ");
1418            if label.is_empty() {
1419                continue;
1420            }
1421            let target = match nd.shape {
1422                NodeShape::Glyph => &mut glyphs,
1423                NodeShape::FilledCircle => &mut inverse,
1424                NodeShape::Square | NodeShape::FilledSquare => &mut above,
1425                // a constant is a number: upright, never the math italic
1426                NodeShape::Text => &mut texts,
1427                NodeShape::Terminal => &mut beside,
1428                _ => &mut inside,
1429            };
1430            let ly = match nd.shape {
1431                NodeShape::Square | NodeShape::FilledSquare => y - 4.0 - 0.36 * SMALL_PX,
1432                _ => pn.cy,
1433            };
1434            // a terminal's label starts just right of it
1435            let lx = match nd.shape {
1436                NodeShape::Terminal => x + pn.w + 5.0,
1437                _ => pn.cx,
1438            };
1439            target.num("x", lx).num("y", ly);
1440            target.txt("label", label).txt("of", id.clone());
1441            continue;
1442        }
1443        // a node without a fill of its own: tinted by how far it moved
1444        let fill = nd.fill.unwrap_or_else(|| {
1445            match (
1446                s.moved,
1447                nd.states.as_ref().and_then(|(r, _)| moved_share(r)),
1448            ) {
1449                (Some(c), Some(t)) => mix(s.card, c, t),
1450                _ => s.card,
1451            }
1452        });
1453        let key = (nd.stroke, nd.shape, fill);
1454        let i = match boxes.iter().position(|(k, _)| *k == key) {
1455            Some(i) => i,
1456            None => {
1457                boxes.push((key, Frame::default()));
1458                boxes.len() - 1
1459            }
1460        };
1461        let f = &mut boxes[i].1;
1462        if nd.shape == NodeShape::DoubleBox {
1463            let o = by_colour(&mut outlines, nd.stroke);
1464            o.num("x0", x + 3.5)
1465                .num("x1", x + pn.w - 3.5)
1466                .num("y0", y + 3.5)
1467                .num("y1", y + pn.h - 3.5);
1468            o.txt("of", id.clone());
1469        }
1470        f.num("x0", x)
1471            .num("x1", x + pn.w)
1472            .num("y0", y)
1473            .num("y1", y + pn.h);
1474        f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1475        // the icon in a round badge on the top right corner
1476        if let Some(NodeIcon::Hand) = nd.icon {
1477            let (bx, by) = (x + pn.w - 11.0, y - 7.0);
1478            ibadge
1479                .num("x0", bx)
1480                .num("x1", bx + 18.0)
1481                .num("y0", by)
1482                .num("y1", by + 18.0);
1483            ibadge.txt("of", id.clone());
1484            let (ox, oy) = (bx + 3.0, by + 3.0);
1485            for (x0, y0, x1, y1) in HAND_RECTS {
1486                irect
1487                    .num("x0", ox + x0)
1488                    .num("x1", ox + x1)
1489                    .num("y0", oy + y0)
1490                    .num("y1", oy + y1);
1491                irect.txt("of", id.clone());
1492            }
1493            for (px, py) in HAND_THUMB {
1494                ipoly.num("x", ox + px).num("y", oy + py);
1495                ipoly.txt("g", id.clone()).txt("of", id.clone());
1496            }
1497        }
1498
1499        if let Some(a) = nd.accent {
1500            accent.num("x0", x + 1.5).num("x1", x + 4.5);
1501            accent
1502                .num("y0", y + 6.0)
1503                .num("y1", y + 6.0 + (pn.h - 12.0).max(4.0));
1504            accent.txt("fill", hex(a)).txt("of", id.clone());
1505        }
1506        let mut base = y + BOX_PAD_Y + 12.0;
1507        for line in &nd.lines {
1508            lines
1509                .num("x", pn.cx)
1510                .num("y", mid_of_baseline(base, LABEL_PX));
1511            lines.txt("label", line.clone()).txt("of", id.clone());
1512            base += LINE_H;
1513        }
1514        if let Some(fv) = &nd.value {
1515            values
1516                .num("x", pn.cx)
1517                .num("y", mid_of_baseline(base, VALUE_PX));
1518            values.txt("label", fv.clone()).txt("of", id.clone());
1519            base += LINE_H;
1520        }
1521        if let Some((b, dot)) = &nd.badge {
1522            let bw = text_w(b, BADGE_PX, false) + 20.0;
1523            let (bx, by) = (pn.cx - bw / 2.0, base - 9.0);
1524            let f = by_colour(&mut badges, *dot);
1525            f.num("x0", bx)
1526                .num("x1", bx + bw)
1527                .num("y0", by)
1528                .num("y1", by + 16.0);
1529            f.txt("of", id.clone());
1530            dots.num("x", bx + 9.0).num("y", by + 8.0);
1531            dots.txt("col", hex(*dot)).txt("of", id.clone());
1532            btext.num("x", bx + 15.0).num("y", by + 8.0);
1533            btext.txt("label", b.clone()).txt("of", id.clone());
1534            base += 20.0;
1535        }
1536        // the states, a row each: name, the prior's faint bar with a tick
1537        // where it ends, the bar, the probability
1538        if let Some((rows, colour)) = nd.states.as_ref().filter(|(r, _)| !r.is_empty()) {
1539            let names = rows
1540                .iter()
1541                .map(|r| text_w(&state_name(&r.name), SMALL_PX, true))
1542                .fold(0.0, f64::max);
1543            let bx = x + BOX_PAD_X + names + STATE_GAP;
1544            let delta = if rows.iter().any(|r| r.was.is_some()) {
1545                STATE_DELTA_W
1546            } else {
1547                0.0
1548            };
1549            // the bar takes what the box leaves it, at most its full length
1550            let bw = (pn.w - 2.0 * BOX_PAD_X - names - 2.0 * STATE_GAP - STATE_TEXT_W - delta)
1551                .clamp(16.0, STATE_BAR_W);
1552            base += 4.0;
1553            for r in rows {
1554                let cy = mid_of_baseline(base, SMALL_PX);
1555                let f = if r.observed { &mut sseen } else { &mut sname };
1556                f.num("x", x + BOX_PAD_X).num("y", cy);
1557                f.txt("label", state_name(&r.name)).txt("of", id.clone());
1558                f.txt("state", r.name.clone());
1559                if let Some(q) = r.prior {
1560                    let q = if q.is_finite() {
1561                        q.clamp(0.0, 1.0)
1562                    } else {
1563                        0.0
1564                    };
1565                    sprior
1566                        .num("x0", bx)
1567                        .num("x1", bx + bw * q)
1568                        .num("y0", cy - 5.0)
1569                        .num("y1", cy + 5.0);
1570                    sprior.txt("fill", hex(s.muted)).txt("of", id.clone());
1571                    stick
1572                        .num("x0", bx + bw * q - 0.75)
1573                        .num("x1", bx + bw * q + 0.75)
1574                        .num("y0", cy - 6.0)
1575                        .num("y1", cy + 6.0);
1576                    stick.txt("fill", hex(s.muted)).txt("of", id.clone());
1577                }
1578                let p = if r.p.is_finite() {
1579                    r.p.clamp(0.0, 1.0)
1580                } else {
1581                    0.0
1582                };
1583                sbar.num("x0", bx)
1584                    .num("x1", bx + bw * p)
1585                    .num("y0", cy - 3.5)
1586                    .num("y1", cy + 3.5);
1587                sbar.txt("fill", hex(*colour)).txt("of", id.clone());
1588                stext.num("x", bx + bw + STATE_GAP).num("y", cy);
1589                stext.txt("label", r.text.clone()).txt("of", id.clone());
1590                stext.txt("state", r.name.clone());
1591                if let Some((t, up)) = r.was.and_then(|w| delta_text(p, w)) {
1592                    let f = if up { &mut sup } else { &mut sdown };
1593                    f.num("x", bx + bw + STATE_GAP + STATE_TEXT_W).num("y", cy);
1594                    f.txt("label", t).txt("of", id.clone());
1595                }
1596                base += STATE_H;
1597            }
1598        }
1599        // a table (an influence diagram's policy): the header, then a row
1600        // each; the first column left, the others right-aligned
1601        if let Some((t, colour)) = nd.table.as_ref().filter(|(t, _)| !t.rows.is_empty()) {
1602            let widths = t.widths();
1603            let x0 = pn.cx - t.width() / 2.0;
1604            // each column's left and right edge
1605            let mut edges = Vec::with_capacity(widths.len());
1606            let mut cx = x0;
1607            for w in &widths {
1608                edges.push((cx, cx + w));
1609                cx += w + TABLE_GAP;
1610            }
1611            base += 4.0;
1612            if t.has_header() {
1613                let cy = mid_of_baseline(base, SMALL_PX);
1614                for (c, h) in t.header.iter().enumerate().filter(|(_, h)| !h.is_empty()) {
1615                    let (f, hx) = if c == 0 {
1616                        (&mut thead_l, edges[c].0)
1617                    } else {
1618                        (&mut thead_r, edges[c].1)
1619                    };
1620                    f.num("x", hx).num("y", cy);
1621                    f.txt("label", t.cell(c, h)).txt("of", id.clone());
1622                    if c > 0 {
1623                        f.opt("state", t.key(c));
1624                    }
1625                }
1626                base += STATE_H;
1627            }
1628            for (k, row) in t.rows.iter().enumerate() {
1629                let cy = mid_of_baseline(base, SMALL_PX);
1630                if t.current == Some(k) {
1631                    tband
1632                        .num("x0", x + 4.0)
1633                        .num("x1", x + pn.w - 4.0)
1634                        .num("y0", cy - 7.0)
1635                        .num("y1", cy + 7.0);
1636                    tband.txt("fill", hex(s.muted)).txt("of", id.clone());
1637                }
1638                let mark = t.marked.get(k).copied().flatten();
1639                for (c, cell) in row.iter().enumerate().take(edges.len()) {
1640                    let marked = c > 0 && mark == Some(c);
1641                    if marked {
1642                        tmarkbg
1643                            .num("x0", edges[c].0 - 3.0)
1644                            .num("x1", edges[c].1 + 3.0)
1645                            .num("y0", cy - 6.5)
1646                            .num("y1", cy + 6.5);
1647                        tmarkbg.txt("fill", hex(*colour)).txt("of", id.clone());
1648                    }
1649                    let (f, cx) = match (c, marked) {
1650                        (0, _) => (&mut tname, edges[c].0),
1651                        (_, true) => (&mut tmark, edges[c].1),
1652                        _ => (&mut tcell, edges[c].1),
1653                    };
1654                    f.num("x", cx).num("y", cy);
1655                    f.txt("label", t.cell(c, cell)).txt("of", id.clone());
1656                    if c > 0 {
1657                        f.opt("state", t.key(c));
1658                    }
1659                }
1660                base += STATE_H;
1661            }
1662        }
1663        // a mini trend along the bottom of the box
1664        if let Some((values, colour)) = nd.spark.as_ref().filter(|(v, _)| v.len() >= 2) {
1665            let (lo, hi) = values
1666                .iter()
1667                .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
1668                    (a.min(v), b.max(v))
1669                });
1670            let rng = if hi > lo { hi - lo } else { 1.0 };
1671            let (sx0, sw) = (x + BOX_PAD_X, pn.w - 2.0 * BOX_PAD_X);
1672            let (top, sh) = (base - 8.0, SPARK_H - 8.0);
1673            let last = values.len() - 1;
1674            let col = hex(*colour);
1675            for (i, &sv) in values.iter().enumerate() {
1676                let (px, py) = (
1677                    sx0 + sw * i as f64 / last as f64,
1678                    top + sh - (sv - lo) / rng * sh,
1679                );
1680                spark.num("x", px).num("y", py).txt("g", id.clone());
1681                spark.txt("col", col.clone()).txt("of", id.clone());
1682                if i == last {
1683                    ends.num("x", px).num("y", py);
1684                    ends.txt("col", col.clone()).txt("of", id.clone());
1685                }
1686            }
1687        }
1688    }
1689    for ((stroke, shape, fill), mut f) in boxes {
1690        let aes = f.attr_aes(rect_aes().tooltip("tip"));
1691        let cls = match shape {
1692            NodeShape::Box => class("node"),
1693            _ => format!(
1694                "{} {}",
1695                class("node"),
1696                class(&format!("node-{}", shape.name()))
1697            ),
1698        };
1699        plot = plot
1700            .geom_rect_with(
1701                GeomRect {
1702                    fill,
1703                    color: stroke,
1704                    alpha: 1.0,
1705                    line_width: 1.2,
1706                    ..Default::default()
1707                }
1708                .with_radius(if shape == NodeShape::Rect { 0.0 } else { 8.0 }),
1709            )
1710            .layer_data(f.take(h))
1711            .layer_aes(aes)
1712            .layer_svg_attr("class", cls);
1713    }
1714    if !hits.is_empty() {
1715        // a diamond's hit target: its bounding box, invisible
1716        let aes = hits.attr_aes(rect_aes().tooltip("tip"));
1717        let cls = format!("{} {}", class("node"), class("node-diamond"));
1718        plot = plot
1719            .geom_rect_with(GeomRect {
1720                fill: s.card,
1721                alpha: 0.0,
1722                line_width: 0.0,
1723                ..Default::default()
1724            })
1725            .layer_data(hits.take(h))
1726            .layer_aes(aes)
1727            .layer_svg_attr("class", cls);
1728    }
1729    for ((shape, r, stroke), mut f) in shaped {
1730        let aes = f.attr_aes(rect_aes().fill("fill").tooltip("tip"));
1731        let cls = format!(
1732            "{} {}",
1733            class("node"),
1734            class(&format!("node-{}", shape.name()))
1735        );
1736        plot = plot
1737            .geom_rect_with(
1738                GeomRect {
1739                    color: stroke,
1740                    alpha: 1.0,
1741                    line_width: if shape == NodeShape::Text { 0.0 } else { 1.2 },
1742                    ..Default::default()
1743                }
1744                .with_radius(f64::from_bits(r)),
1745            )
1746            .layer_data(f.take(h))
1747            .layer_aes(aes)
1748            .layer_svg_attr("class", cls);
1749    }
1750    if !priors.is_empty() {
1751        plot = plot
1752            .geom_path_with(GeomPath {
1753                alpha: 0.7,
1754                ..GeomPath::default().linewidth(1.0)
1755            })
1756            .layer_data(priors.take(h))
1757            .layer_aes(
1758                Aes::new()
1759                    .x("x")
1760                    .y("y")
1761                    .group("g")
1762                    .color("col")
1763                    .linetype("lt")
1764                    .group_wrap("of", "of"),
1765            )
1766            .decorative()
1767            .layer_svg_attrs(inert)
1768            .layer_svg_attr("class", class("node-prior"));
1769    }
1770    if !beliefs.is_empty() {
1771        plot = plot
1772            .geom_polygon_with(GeomPolygon {
1773                alpha: 0.45,
1774                line_width: 0.0,
1775                ..Default::default()
1776            })
1777            .layer_data(beliefs.take(h))
1778            .layer_aes(
1779                Aes::new()
1780                    .x("x")
1781                    .y("y")
1782                    .group("g")
1783                    .fill("fill")
1784                    .group_wrap("of", "of"),
1785            )
1786            .decorative()
1787            .layer_svg_attrs(inert)
1788            .layer_svg_attr("class", class("node-belief"));
1789    }
1790    // everything below: dims / lights with its node (`data-of`), inert
1791    let of = |a: Aes| a.group_wrap("of", "of");
1792    if !accent.is_empty() {
1793        plot = plot
1794            .geom_rect_with(
1795                GeomRect {
1796                    alpha: 1.0,
1797                    line_width: 0.0,
1798                    ..Default::default()
1799                }
1800                .with_radius(1.5),
1801            )
1802            .layer_data(accent.take(h))
1803            .layer_aes(of(rect_aes().fill("fill")))
1804            .decorative()
1805            .layer_svg_attrs(inert);
1806    }
1807    for (stroke, mut f) in outlines {
1808        plot = plot
1809            .geom_rect_with(
1810                GeomRect {
1811                    fill: s.card,
1812                    color: stroke,
1813                    alpha: 0.0,
1814                    line_width: 1.0,
1815                    ..Default::default()
1816                }
1817                .with_radius(5.5),
1818            )
1819            .layer_data(f.take(h))
1820            .layer_aes(of(rect_aes()))
1821            .decorative()
1822            .layer_svg_attrs(inert)
1823            .layer_svg_attr("class", class("node-outline"));
1824    }
1825    for (stroke, mut f) in diamonds {
1826        plot = plot
1827            .geom_polygon_with(GeomPolygon {
1828                color: stroke,
1829                alpha: 1.0,
1830                line_width: 1.2,
1831                ..Default::default()
1832            })
1833            .layer_data(f.take(h))
1834            .layer_aes(of(Aes::new().x("x").y("y").group("g").fill("fill")))
1835            .decorative()
1836            .layer_svg_attrs(inert)
1837            .layer_svg_attr("class", class("node-diamond-mark"));
1838    }
1839    for (mut f, alpha, cls) in [
1840        (sprior, 0.28, "node-state-prior"),
1841        (sbar, 0.9, "node-state-bar"),
1842        (stick, 0.9, "node-state-prior"),
1843        (tband, 0.14, "node-table-current"),
1844        (tmarkbg, 0.2, "node-table-mark"),
1845    ] {
1846        if f.is_empty() {
1847            continue;
1848        }
1849        plot = plot
1850            .geom_rect_with(GeomRect {
1851                alpha,
1852                line_width: 0.0,
1853                ..Default::default()
1854            })
1855            .layer_data(f.take(h))
1856            .layer_aes(of(rect_aes().fill("fill")))
1857            .decorative()
1858            .layer_svg_attrs(inert)
1859            .layer_svg_attr("class", class(cls));
1860    }
1861    for (mut f, colour, face, cls) in [
1862        (sname, s.ink, FontFace::Plain, "node-state"),
1863        (sseen, s.heading, FontFace::Bold, "node-state"),
1864        (stext, s.muted, FontFace::Plain, "node-state-value"),
1865    ] {
1866        if f.is_empty() {
1867            continue;
1868        }
1869        plot = plot
1870            .geom_text_with(GeomText {
1871                size: SMALL_PX,
1872                color: colour,
1873                fontface: face,
1874                hjust: 0.0,
1875                ..Default::default()
1876            })
1877            .layer_aes(of(state_attr(&f, Aes::new().x("x").y("y").label("label"))))
1878            .layer_data(f.take(h))
1879            .layer_svg_attrs(inert)
1880            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class(cls))]);
1881    }
1882    for (mut f, colour, face, hjust, cls) in [
1883        (thead_l, s.muted, FontFace::Plain, 0.0, "node-table-head"),
1884        (thead_r, s.muted, FontFace::Plain, 1.0, "node-table-head"),
1885        (tname, s.ink, FontFace::Plain, 0.0, "node-table-name"),
1886        (tcell, s.muted, FontFace::Plain, 1.0, "node-table-cell"),
1887        (
1888            tmark,
1889            s.heading,
1890            FontFace::Bold,
1891            1.0,
1892            "node-table-cell node-table-chosen",
1893        ),
1894    ] {
1895        if f.is_empty() {
1896            continue;
1897        }
1898        let cls = cls.split(' ').map(&class).collect::<Vec<_>>().join(" ");
1899        plot = plot
1900            .geom_text_with(GeomText {
1901                size: SMALL_PX,
1902                color: colour,
1903                fontface: face,
1904                hjust,
1905                ..Default::default()
1906            })
1907            .layer_aes(of(state_attr(&f, Aes::new().x("x").y("y").label("label"))))
1908            .layer_data(f.take(h))
1909            .layer_svg_attrs(inert)
1910            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*cls)]);
1911    }
1912    for (mut f, face, colour) in [
1913        (sup, FontFace::Bold, s.heading),
1914        (sdown, FontFace::Plain, s.muted),
1915    ] {
1916        if f.is_empty() {
1917            continue;
1918        }
1919        plot = plot
1920            .geom_text_with(GeomText {
1921                size: SMALL_PX - 1.0,
1922                color: colour,
1923                fontface: face,
1924                hjust: 0.0,
1925                ..Default::default()
1926            })
1927            .layer_data(f.take(h))
1928            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1929            .layer_svg_attrs(inert)
1930            .layer_svg_attrs([
1931                ("aria-hidden", "true"),
1932                ("class", &*class("node-state-delta")),
1933            ]);
1934    }
1935    if !ibadge.is_empty() {
1936        plot = plot
1937            .geom_rect_with(
1938                GeomRect {
1939                    fill: s.card,
1940                    color: s.heading,
1941                    alpha: 1.0,
1942                    line_width: 1.1,
1943                    ..Default::default()
1944                }
1945                .with_radius(9.0),
1946            )
1947            .layer_data(ibadge.take(h))
1948            .layer_aes(of(rect_aes()))
1949            .decorative()
1950            .layer_svg_attrs(inert)
1951            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
1952        plot = plot
1953            .geom_rect_with(
1954                GeomRect {
1955                    fill: s.heading,
1956                    alpha: 1.0,
1957                    line_width: 0.0,
1958                    ..Default::default()
1959                }
1960                .with_radius(0.9),
1961            )
1962            .layer_data(irect.take(h))
1963            .layer_aes(of(rect_aes()))
1964            .decorative()
1965            .layer_svg_attrs(inert)
1966            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
1967        plot = plot
1968            .geom_polygon_with(GeomPolygon {
1969                fill: s.heading,
1970                alpha: 1.0,
1971                line_width: 0.0,
1972                ..Default::default()
1973            })
1974            .layer_data(ipoly.take(h))
1975            .layer_aes(of(Aes::new().x("x").y("y").group("g")))
1976            .decorative()
1977            .layer_svg_attrs(inert)
1978            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-icon"))]);
1979    }
1980    for (mut f, size, colour, cls, math, hjust) in [
1981        (lines, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1982        (values, VALUE_PX, s.ink, class("node-value"), false, 0.5),
1983        (inside, LABEL_PX, s.heading, class("node-label"), true, 0.5),
1984        (texts, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1985        (inverse, LABEL_PX, s.card, class("node-label"), true, 0.5),
1986        (above, SMALL_PX, s.muted, class("node-label"), true, 0.5),
1987        (beside, LABEL_PX, s.heading, class("node-label"), true, 0.0),
1988        (
1989            glyphs,
1990            GLYPH_PX,
1991            s.glyph_ink.unwrap_or(s.heading),
1992            class("node-label"),
1993            true,
1994            0.5,
1995        ),
1996    ] {
1997        if f.is_empty() {
1998            continue;
1999        }
2000        // a factor graph's labels as mathematics: the math font, italic
2001        let (fontfamily, fontface, size) = match s.math_font.as_ref().filter(|_| math) {
2002            Some(family) => (family.clone(), FontFace::Italic, size + 2.0),
2003            None => (String::new(), FontFace::Bold, size),
2004        };
2005        plot = plot
2006            .geom_text_with(GeomText {
2007                size,
2008                color: colour,
2009                fontface,
2010                fontfamily,
2011                hjust,
2012                ..Default::default()
2013            })
2014            .layer_data(f.take(h))
2015            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2016            .layer_svg_attrs(inert)
2017            .layer_svg_attrs([("aria-hidden", "true"), ("class", cls.as_str())]);
2018    }
2019    for (dot, mut f) in badges {
2020        plot = plot
2021            .geom_rect_with(
2022                GeomRect {
2023                    fill: s.card,
2024                    color: dot,
2025                    alpha: 0.0,
2026                    line_width: 1.0,
2027                    ..Default::default()
2028                }
2029                .with_radius(8.0),
2030            )
2031            .layer_data(f.take(h))
2032            .layer_aes(of(rect_aes()))
2033            .decorative()
2034            .layer_svg_attrs(inert);
2035    }
2036    for (mut f, size) in [(dots, 3.0), (ends, 2.2)] {
2037        if f.is_empty() {
2038            continue;
2039        }
2040        plot = plot
2041            .geom_point_with(GeomPoint {
2042                size,
2043                ..Default::default()
2044            })
2045            .layer_data(f.take(h))
2046            .layer_aes(of(Aes::new().x("x").y("y").color("col")))
2047            .decorative()
2048            .layer_svg_attrs(inert);
2049    }
2050    if !btext.is_empty() {
2051        plot = plot
2052            .geom_text_with(GeomText {
2053                size: BADGE_PX,
2054                color: s.ink,
2055                hjust: 0.0,
2056                ..Default::default()
2057            })
2058            .layer_data(btext.take(h))
2059            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
2060            .layer_svg_attrs(inert)
2061            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-badge"))]);
2062    }
2063    if !spark.is_empty() {
2064        plot = plot
2065            .geom_path_with(GeomPath::default().linewidth(1.4))
2066            .layer_data(spark.take(h))
2067            .layer_aes(of(Aes::new().x("x").y("y").group("g").color("col")))
2068            .decorative()
2069            .layer_svg_attrs(inert)
2070            .layer_svg_attr("class", class("node-spark"));
2071    }
2072    plot
2073}
2074
2075#[cfg(test)]
2076mod tests {
2077    use super::*;
2078    use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
2079
2080    #[test]
2081    fn an_end_label_sits_beside_its_box() {
2082        // anofox-visualization#1238: an interface name near a factor is
2083        // clear of the factor's box, not centred on its border
2084        let hw = edge_label_width("variance") / 2.0;
2085        let (x, y) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "variance", 0.8);
2086        assert!(
2087            (x - (100.0 - hw - crate::graph_layout::LABEL_CLEAR)).abs() < 1e-9 && y == 0.0,
2088            "{x} {y}"
2089        );
2090        let (x, _) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "mean", 0.2);
2091        assert!(
2092            x - edge_label_width("mean") / 2.0 >= crate::graph_layout::LABEL_CLEAR - 1e-9,
2093            "{x}"
2094        );
2095        // a vertical edge: beside the line, below the box it leaves
2096        let (x, y) = end_label_at(&[(50.0, 0.0), (50.0, 40.0)], "out", 0.2);
2097        assert!(
2098            x - edge_label_width("out") / 2.0 > 50.0 && y > 0.0,
2099            "{x} {y}"
2100        );
2101        // a short edge: the label stays on it
2102        let (x, _) = end_label_at(&[(0.0, 0.0), (20.0, 0.0)], "variance", 0.8);
2103        assert!((x - 10.0).abs() < 1e-9, "{x}");
2104    }
2105
2106    /// A Bayesian network's nodes (Netica / GeNIe style): a chance node's
2107    /// states as rows of bars with the prior behind them, an observed node
2108    /// shaded with its state in bold, a decision as a square-cornered box,
2109    /// a utility as a diamond (an invisible box as its hit target), a
2110    /// deterministic node with a double outline.
2111    #[test]
2112    fn draws_bayes_net_nodes_with_state_bars() {
2113        let states = vec!["yes".to_string(), "no".to_string()];
2114        let spec = [
2115            ("Rain", NodeShape::Box),
2116            ("Wet grass", NodeShape::Box),
2117            ("Water?", NodeShape::Rect),
2118            ("Cost", NodeShape::Diamond),
2119            ("Either", NodeShape::DoubleBox),
2120        ];
2121        let sizes: Vec<NodeBox> = spec
2122            .iter()
2123            .map(|(l, sh)| match sh {
2124                NodeShape::Diamond => diamond_box(l, Some("-12.5")),
2125                _ => states_box(l, None, None, &states),
2126            })
2127            .collect();
2128        // two state rows below the label; room for the bars
2129        let plain = node_box("Rain", None, None, false);
2130        assert_eq!(sizes[0].h, plain.h + 4.0 + 2.0 * STATE_H);
2131        assert!(sizes[0].w >= 2.0 * BOX_PAD_X + STATE_BAR_W + STATE_TEXT_W);
2132        assert!(sizes[3].w > sizes[3].h, "a diamond wider than tall");
2133        let gnodes: Vec<GraphNode> = sizes
2134            .iter()
2135            .map(|b| GraphNode {
2136                w: b.w,
2137                h: b.h,
2138                ..Default::default()
2139            })
2140            .collect();
2141        let links = [(0, 1), (2, 1), (1, 3), (0, 4)];
2142        let gedges: Vec<GraphEdge> = links
2143            .iter()
2144            .map(|&(a, b)| GraphEdge {
2145                from: a,
2146                to: b,
2147                label_w: None,
2148            })
2149            .collect();
2150        let params = LayeredParams {
2151            direction: crate::graph_layout::Direction::TopBottom,
2152            ..Default::default()
2153        };
2154        let l = layered(&gnodes, &gedges, &params);
2155        let bar = |name: &str, p: f64, prior: Option<f64>, observed: bool| StateBar {
2156            name: name.to_string(),
2157            p,
2158            prior,
2159            text: format!("{:.0}%", p * 100.0),
2160            observed,
2161            was: None,
2162        };
2163        let nodes: Vec<DrawNode> = spec
2164            .iter()
2165            .zip(&sizes)
2166            .enumerate()
2167            .map(|(i, ((_, shape), b))| DrawNode {
2168                id: format!("n{i}"),
2169                shape: *shape,
2170                lines: b.lines.clone(),
2171                value: (*shape == NodeShape::Diamond).then(|| "-12.5".to_string()),
2172                stroke: (60, 60, 60),
2173                tooltip: b.lines.join(" "),
2174                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2175                states: (*shape != NodeShape::Diamond).then(|| {
2176                    if i == 1 {
2177                        (
2178                            vec![
2179                                bar("yes", 1.0, Some(0.65), true),
2180                                bar("no", 0.0, Some(0.35), false),
2181                            ],
2182                            (37, 99, 235),
2183                        )
2184                    } else {
2185                        (
2186                            vec![
2187                                bar("yes", 0.3, Some(0.5), false),
2188                                bar("no", 0.7, Some(0.5), false),
2189                            ],
2190                            (37, 99, 235),
2191                        )
2192                    }
2193                }),
2194                fill: (i == 1).then_some((230, 236, 250)),
2195                ..Default::default()
2196            })
2197            .collect();
2198        let edges: Vec<DrawEdge> = links
2199            .iter()
2200            .map(|&(a, b)| DrawEdge {
2201                colour: (90, 90, 90),
2202                width: 1.6,
2203                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2204                ..Default::default()
2205            })
2206            .collect();
2207        let svg = draw(
2208            &l,
2209            &[],
2210            &[],
2211            &nodes,
2212            &edges,
2213            &GraphStyle::default(),
2214            crate::theme::presets::theme_void(),
2215        )
2216        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2217        .unwrap();
2218        // one hit target per node, classed by shape; directed edges
2219        assert_eq!(svg.matches("data-node=").count(), spec.len());
2220        for c in [
2221            "gg-graph-node-rect",
2222            "gg-graph-node-diamond",
2223            "gg-graph-node-double-box",
2224        ] {
2225            assert!(svg.contains(c), "{c}");
2226        }
2227        assert!(
2228            svg.contains("gg-graph-node-diamond-mark") && svg.contains("gg-graph-node-outline")
2229        );
2230        assert!(
2231            svg.contains("data-part=\"arrow\""),
2232            "arrowheads at the child"
2233        );
2234        // state rows: four bars, their priors, the names and probabilities
2235        assert!(
2236            svg.contains("gg-graph-node-state-bar") && svg.contains("gg-graph-node-state-prior")
2237        );
2238        assert!(svg.contains(">30%<") && svg.contains(">100%<"));
2239        // the observed node shaded, its observed state in bold
2240        assert!(svg.contains("fill=\"#E6ECFA\""), "shaded");
2241        assert!(
2242            svg.match_indices(">yes</text>")
2243                .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2244            "the observed state in bold"
2245        );
2246        // the diamond's value inside it
2247        assert!(svg.contains(">-12.5<"));
2248        // a plain box keeps its round corners and the plain class
2249        let plain = svg
2250            .split("<rect")
2251            .find(|r| r.contains("data-node=\"n0\""))
2252            .unwrap();
2253        assert!(plain.contains("gg-graph-node\""), "{plain}");
2254    }
2255
2256    /// An influence diagram's policy as a table in the decision's box
2257    /// (DataZooDE/anofox-visualization#1279): a header, a row per
2258    /// configuration of the informational parents, the chosen option bold
2259    /// on a tint, the configuration the evidence picks on a band.
2260    #[test]
2261    fn draws_a_policy_table_in_a_decision() {
2262        let table = NodeTable {
2263            header: vec!["Seismic".into(), "drill".into(), "don't drill".into()],
2264            rows: vec![
2265                vec!["closed".into(), "87.5".into(), "0".into()],
2266                vec!["open".into(), "22.9".into(), "0".into()],
2267                vec!["diffuse".into(), "-25.6".into(), "0".into()],
2268                vec![
2269                    "a very long configuration name".into(),
2270                    "1".into(),
2271                    "2".into(),
2272                ],
2273            ],
2274            marked: vec![Some(1), Some(1), Some(2)],
2275            current: Some(1),
2276            keys: vec![String::new(), "drill".into(), "dont".into()],
2277        };
2278        let b = table_box("Drill?", None, None, &table);
2279        let plain = node_box("Drill?", None, None, false);
2280        // a header row and four rows under the label, room for the columns
2281        assert_eq!(b.h, plain.h + 4.0 + 5.0 * STATE_H);
2282        assert!(
2283            b.w >= table.width() + 2.0 * BOX_PAD_X,
2284            "{} {}",
2285            b.w,
2286            table.width()
2287        );
2288        // no header row when every head is empty; no rows: a plain box
2289        let bare = NodeTable {
2290            header: vec![String::new(), "EU".into()],
2291            ..table.clone()
2292        };
2293        assert_eq!(table_box("Drill?", None, None, &bare).h, b.h);
2294        let headless = NodeTable {
2295            header: Vec::new(),
2296            ..table.clone()
2297        };
2298        assert_eq!(table_box("Drill?", None, None, &headless).h, b.h - STATE_H);
2299        assert_eq!(
2300            table_box("Drill?", None, None, &NodeTable::default()),
2301            plain
2302        );
2303        let gnodes = [GraphNode {
2304            w: b.w,
2305            h: b.h,
2306            ..Default::default()
2307        }];
2308        let l = layered(&gnodes, &[], &LayeredParams::default());
2309        let nodes = [DrawNode {
2310            id: "drill".into(),
2311            shape: NodeShape::Rect,
2312            lines: b.lines.clone(),
2313            stroke: (60, 60, 60),
2314            tooltip: "Drill?".into(),
2315            attrs: vec![("node".to_string(), Some("drill".to_string()))],
2316            table: Some((table, (37, 99, 235))),
2317            ..Default::default()
2318        }];
2319        let svg = draw(
2320            &l,
2321            &[],
2322            &[],
2323            &nodes,
2324            &[],
2325            &GraphStyle::default(),
2326            crate::theme::presets::theme_void(),
2327        )
2328        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2329        .unwrap();
2330        assert!(
2331            svg.contains(">Seismic<") && svg.contains(">don&#39;t drill<"),
2332            "{svg}"
2333        );
2334        assert!(svg.contains(">closed<") && svg.contains(">-25.6<"));
2335        // the long name cut with …
2336        assert!(svg.contains(">a very long c…<"), "{svg}");
2337        // three chosen cells, bold on a tint; one band for the current row
2338        assert_eq!(svg.matches("gg-graph-node-table-chosen").count(), 3);
2339        assert_eq!(svg.matches("gg-graph-node-table-mark").count(), 3);
2340        assert!(svg.contains("gg-graph-node-table-mark"));
2341        assert!(svg.contains("gg-graph-node-table-current"));
2342        assert!(
2343            svg.match_indices(">87.5</text>")
2344                .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2345            "the chosen option in bold"
2346        );
2347        assert!(
2348            svg.match_indices(">0</text>")
2349                .any(|(i, _)| !svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
2350            "the others plain"
2351        );
2352        // a column's head and cells name its key; the row names none
2353        assert_eq!(svg.matches("data-state=\"dont\"").count(), 5);
2354        assert_eq!(svg.matches("data-state=\"drill\"").count(), 5);
2355        assert!(!svg
2356            .split("<text")
2357            .any(|t| t.contains(">closed<") && t.contains("data-state")));
2358        // the cells are right-aligned
2359        assert!(
2360            svg.match_indices(">22.9</text>")
2361                .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i]
2362                    .contains("text-anchor=\"end\"")),
2363            "right-aligned"
2364        );
2365    }
2366
2367    /// Interactive evidence on a Bayesian network
2368    /// (DataZooDE/anofox-visualization#1276): a state's change after its
2369    /// probability, a node tinted by how far it moved, a hand on a node set
2370    /// by an intervention, its incoming edge cut, `data-state` on each row.
2371    #[test]
2372    fn draws_belief_deltas_cut_edges_and_a_hand() {
2373        let states = vec!["yes".to_string(), "no".to_string()];
2374        let plain = states_box("Rain", None, None, &states);
2375        let wide = states_box_with_deltas("Rain", None, None, &states, true);
2376        assert_eq!(wide.w, plain.w + STATE_DELTA_W, "room for the change");
2377        let gnodes = vec![
2378            GraphNode {
2379                w: wide.w,
2380                h: wide.h,
2381                ..Default::default()
2382            };
2383            2
2384        ];
2385        let l = layered(
2386            &gnodes,
2387            &[GraphEdge {
2388                from: 0,
2389                to: 1,
2390                label_w: None,
2391            }],
2392            &LayeredParams {
2393                direction: crate::graph_layout::Direction::TopBottom,
2394                ..Default::default()
2395            },
2396        );
2397        let bar = |name: &str, p: f64, was: f64| StateBar {
2398            name: name.to_string(),
2399            p,
2400            text: format!("{:.0}%", p * 100.0),
2401            was: Some(was),
2402            ..Default::default()
2403        };
2404        let nodes: Vec<DrawNode> = (0..2)
2405            .map(|i| DrawNode {
2406                id: format!("n{i}"),
2407                lines: vec![if i == 0 { "Cloudy" } else { "Rain" }.to_string()],
2408                stroke: (60, 60, 60),
2409                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2410                states: Some((
2411                    if i == 0 {
2412                        vec![bar("yes", 0.5, 0.5), bar("no", 0.5, 0.5)]
2413                    } else {
2414                        vec![bar("yes", 0.71, 0.5), bar("no", 0.29, 0.5)]
2415                    },
2416                    (37, 99, 235),
2417                )),
2418                icon: (i == 0).then_some(NodeIcon::Hand),
2419                ..Default::default()
2420            })
2421            .collect();
2422        let edges = vec![DrawEdge {
2423            colour: (160, 160, 160),
2424            width: 1.6,
2425            cut: true,
2426            attrs: vec![("edge".to_string(), Some("n0>n1".to_string()))],
2427            label_attrs: vec![("to".to_string(), Some("n1".to_string()))],
2428            ..Default::default()
2429        }];
2430        let style = GraphStyle {
2431            moved: Some((245, 158, 11)),
2432            ..Default::default()
2433        };
2434        let svg = draw(
2435            &l,
2436            &[],
2437            &[],
2438            &nodes,
2439            &edges,
2440            &style,
2441            crate::theme::presets::theme_void(),
2442        )
2443        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2444        .unwrap();
2445        // Rain moved: ▲21 / ▼21, tinted; Cloudy did not move: no change, no tint
2446        assert!(svg.contains(">▲21<") && svg.contains(">▼21<"), "deltas");
2447        assert_eq!(svg.matches("gg-graph-node-state-delta").count(), 2);
2448        let tint = mix(
2449            (255, 255, 255),
2450            (245, 158, 11),
2451            moved_share(&nodes[1].states.as_ref().unwrap().0).unwrap(),
2452        );
2453        assert!(
2454            svg.to_ascii_lowercase()
2455                .contains(&format!("fill=\"{}\"", hex(tint))),
2456            "tinted"
2457        );
2458        assert!(
2459            svg.contains("fill=\"#FFFFFF\"") || svg.contains("fill=\"#ffffff\""),
2460            "Cloudy untinted"
2461        );
2462        // the hand and the cut mark
2463        assert!(svg.contains("gg-graph-node-icon"), "hand");
2464        assert!(svg.contains("gg-graph-edge-cut"), "cut mark");
2465        // a click on a row names its state
2466        assert!(svg.contains("data-state=\"yes\"") && svg.contains("data-state=\"no\""));
2467    }
2468
2469    #[test]
2470    fn js_distance_is_zero_for_the_same_and_one_for_disjoint() {
2471        assert!(js_distance(&[0.5, 0.5], &[0.5, 0.5]).abs() < 1e-12);
2472        assert!((js_distance(&[1.0, 0.0], &[0.0, 1.0]) - 1.0).abs() < 1e-12);
2473        let d = js_distance(&[0.71, 0.29], &[0.5, 0.5]);
2474        assert!(d > 0.1 && d < 0.2, "{d}");
2475        // unnormalised input, or a length mismatch
2476        assert!((js_distance(&[2.0, 2.0], &[0.5, 0.5])).abs() < 1e-12);
2477        assert_eq!(js_distance(&[1.0], &[0.5, 0.5]), 0.0);
2478        assert_eq!(delta_text(0.71, 0.5), Some(("▲21".to_string(), true)));
2479        assert_eq!(delta_text(0.5, 0.503), None);
2480    }
2481
2482    #[test]
2483    fn wraps_long_labels_in_three_lines() {
2484        let l = wrap(
2485            "Recommend replenishment orders for every store and every week of the coming year",
2486            152.0,
2487        );
2488        assert_eq!(l.len(), 3);
2489        assert!(l[2].ends_with('…'));
2490        assert_eq!(wrap("Ingest", 152.0), ["Ingest"]);
2491    }
2492
2493    /// No ellipsis while the label fits; breaks at word boundaries and
2494    /// after `/` / `-`, never mid-word when there is a separator.
2495    #[test]
2496    fn wraps_at_word_boundaries() {
2497        let max = BOX_MAX_W - 2.0 * BOX_PAD_X;
2498        for label in [
2499            "duckdb/community-extensions (descriptions)",
2500            "Locked DuckDB server (anofox-visualization)",
2501            "Parquet snapshot (downloads, extensions)",
2502            "fetch.sh: download, file by ISO week, merge",
2503        ] {
2504            let l = wrap(label, max);
2505            assert!(l.len() <= MAX_LINES, "{l:?}");
2506            assert!(!l.iter().any(|x| x.contains('…')), "{label}: {l:?}");
2507            // every line ends at a space or after a separator
2508            let joined: String = l.concat();
2509            assert_eq!(joined.replace(' ', ""), label.replace(' ', ""), "{l:?}");
2510            for w in l.windows(2) {
2511                let end = w[0].chars().last().unwrap();
2512                let next = w[1].chars().next().unwrap();
2513                let at_space = label.contains(&format!(
2514                    "{} {}",
2515                    w[0].split(' ').next_back().unwrap(),
2516                    w[1].split(' ').next().unwrap()
2517                ));
2518                assert!(
2519                    at_space || matches!(end, '/' | '-' | '_' | '.' | ','),
2520                    "{l:?} breaks at {end}{next}"
2521                );
2522            }
2523        }
2524        assert_eq!(
2525            wrap("duckdb/community-extensions (descriptions)", max),
2526            ["duckdb/community-", "extensions", "(descriptions)"]
2527        );
2528    }
2529
2530    #[test]
2531    fn node_box_grows_with_its_contents() {
2532        let plain = node_box("Ingest", None, None, false);
2533        assert_eq!((plain.w, plain.h), (BOX_MIN_W, 2.0 * BOX_PAD_Y + LINE_H));
2534        let full = node_box("Ingest", Some("1,240"), Some("late"), true);
2535        assert_eq!(full.h, plain.h + LINE_H + 20.0 + SPARK_H);
2536        assert!(full.w >= 110.0 + 2.0 * BOX_PAD_X);
2537        let long = node_box(&"word ".repeat(40), None, None, false);
2538        assert!(long.w <= BOX_MAX_W && long.lines.len() == MAX_LINES);
2539    }
2540
2541    /// An edge label a node box would cover moves along the edge.
2542    #[test]
2543    fn edge_label_keeps_clear_of_nodes() {
2544        let node = |cx: f64, w: f64| PlacedNode {
2545            cx,
2546            cy: 0.0,
2547            w,
2548            h: 40.0,
2549            layer: 0,
2550            order: 0,
2551        };
2552        let pts = [(0.0, 0.0), (300.0, 0.0)];
2553        // nothing in the way: the midpoint
2554        assert_eq!(edge_label_at(&pts, "spikes flagged", &[]), (150.0, 0.0));
2555        // a box over the middle: somewhere else along the edge, clear of it
2556        let nodes = [node(150.0, 60.0)];
2557        let (x, _) = edge_label_at(&pts, "spikes flagged", &nodes);
2558        let hw = edge_label_width("spikes flagged") / 2.0 + 3.0;
2559        assert!((x - 150.0).abs() >= hw + 30.0, "{x}");
2560        assert_eq!(point_at(&pts, 0.25), (75.0, 0.0));
2561    }
2562
2563    #[test]
2564    fn flow_width_is_area_true_and_rounded() {
2565        assert_eq!(flow_width(None, 10.0, EdgeLine::Solid), 1.6);
2566        assert_eq!(flow_width(Some(10.0), 10.0, EdgeLine::Solid), 7.0);
2567        assert_eq!(flow_width(Some(2.5), 10.0, EdgeLine::Solid), 4.2);
2568        assert_eq!(flow_width(None, 10.0, EdgeLine::Dots), 3.0);
2569    }
2570
2571    /// Two lanes, three boxes, a labelled edge: the marks carry the
2572    /// caller's attributes and classes, a node's contents sit in its
2573    /// `data-of` group, and the box itself (the hit target) stays outside.
2574    #[test]
2575    fn draws_marks_with_attributes_and_groups() {
2576        let labels = ["Ingest", "Model", "Publish"];
2577        let boxes: Vec<NodeBox> = labels
2578            .iter()
2579            .enumerate()
2580            .map(|(i, l)| node_box(l, (i == 1).then_some("42"), None, i == 2))
2581            .collect();
2582        let gnodes: Vec<GraphNode> = boxes
2583            .iter()
2584            .enumerate()
2585            .map(|(i, b)| GraphNode {
2586                w: b.w,
2587                h: b.h,
2588                lane: Some(i % 2),
2589                ..Default::default()
2590            })
2591            .collect();
2592        let gedges = [
2593            GraphEdge {
2594                from: 0,
2595                to: 1,
2596                label_w: Some(edge_label_width("rows")),
2597            },
2598            GraphEdge {
2599                from: 1,
2600                to: 2,
2601                label_w: None,
2602            },
2603        ];
2604        let params = LayeredParams {
2605            lanes: 2,
2606            ..Default::default()
2607        };
2608        let l = layered(&gnodes, &gedges, &params);
2609        let nodes: Vec<DrawNode> = labels
2610            .iter()
2611            .zip(&boxes)
2612            .enumerate()
2613            .map(|(i, (id, b))| DrawNode {
2614                id: id.to_string(),
2615                lines: b.lines.clone(),
2616                value: (i == 1).then(|| "42".to_string()),
2617                stroke: (90, 90, 90),
2618                accent: (i == 0).then_some((200, 0, 0)),
2619                spark: (i == 2).then(|| (vec![1.0, 3.0, 2.0], (0, 0, 200))),
2620                tooltip: format!("{id}!"),
2621                attrs: vec![
2622                    ("node".to_string(), Some(id.to_string())),
2623                    ("value".to_string(), (i == 1).then(|| "42".to_string())),
2624                ],
2625                ..Default::default()
2626            })
2627            .collect();
2628        let edges: Vec<DrawEdge> = [(0, 1), (1, 2)]
2629            .iter()
2630            .map(|&(a, b)| DrawEdge {
2631                colour: (100, 100, 100),
2632                width: flow_width(None, 0.0, EdgeLine::Solid),
2633                line: if a == 0 {
2634                    EdgeLine::Solid
2635                } else {
2636                    EdgeLine::Dashed
2637                },
2638                class: (a == 1).then(|| "flowing".to_string()),
2639                tooltip: format!("{} → {}", labels[a], labels[b]),
2640                label: (a == 0).then(|| "rows".to_string()),
2641                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2642                label_attrs: vec![("from".to_string(), Some(labels[a].to_string()))],
2643                ..Default::default()
2644            })
2645            .collect();
2646        let lanes = ["Left".to_string(), "Right".to_string()];
2647        let svg = draw(
2648            &l,
2649            &lanes,
2650            &[],
2651            &nodes,
2652            &edges,
2653            &GraphStyle::default(),
2654            crate::theme::presets::theme_void(),
2655        )
2656        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2657        .unwrap();
2658        // start tags, each with whether it sits inside a `data-of` group
2659        let mut tags: Vec<(&str, bool)> = Vec::new();
2660        let mut stack: Vec<bool> = Vec::new();
2661        for part in svg.split('<').skip(1) {
2662            let tag = &part[..part.find('>').unwrap()];
2663            if tag.starts_with('/') {
2664                stack.pop();
2665                continue;
2666            }
2667            let inside = stack.iter().any(|&g| g);
2668            tags.push((tag, inside));
2669            if !tag.ends_with('/') {
2670                stack.push(tag.contains("data-of="));
2671            }
2672        }
2673        let attr = |tag: &str, name: &str| {
2674            let key = format!(" {name}=\"");
2675            tag.find(&key).map(|i| {
2676                let rest = &tag[i + key.len()..];
2677                rest[..rest.find('"').unwrap()].to_string()
2678            })
2679        };
2680        // boxes: one per node, outside the groups, an NA attribute left off
2681        let boxes: Vec<_> = tags
2682            .iter()
2683            .filter(|(t, _)| t.contains("data-node="))
2684            .collect();
2685        assert_eq!(boxes.len(), 3);
2686        for (b, inside) in &boxes {
2687            assert!(!inside, "{b}");
2688            let id = attr(b, "data-node").unwrap();
2689            assert_eq!(attr(b, "data-value").is_some(), id == "Model", "{id}");
2690        }
2691        // edges: the caller's class on a path; the label's attributes
2692        assert!(tags.iter().any(|(t, _)| t.contains("data-edge=\"1&gt;2\"")
2693            && attr(t, "class").is_some_and(|c| c.contains("flowing"))));
2694        assert!(tags
2695            .iter()
2696            .any(|(t, _)| attr(t, "data-from").as_deref() == Some("Ingest")));
2697        assert!(svg.contains(" gg-graph-node\"") && svg.contains("gg-graph-edge-label"));
2698        // node contents grouped by node; lanes drawn with their names
2699        for id in labels {
2700            assert!(svg.contains(&format!("data-of=\"{id}\"")), "{id}");
2701        }
2702        assert!(svg.contains("data-lane=\"Right\""));
2703        assert!(svg.contains(">Left<") && svg.contains(">42<"));
2704    }
2705
2706    /// Forney style (#1172): an observation as a terminal square, its label
2707    /// beside it; a variable as a labelled edge, its name in the math font.
2708    #[test]
2709    fn forney_terminals_and_variable_edges() {
2710        use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
2711        let spec = [
2712            ("Cat", NodeShape::Glyph),
2713            ("T", NodeShape::Glyph),
2714            ("x₁", NodeShape::Terminal),
2715        ];
2716        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
2717        assert_eq!((sizes[2].w, sizes[2].h), (TERMINAL, TERMINAL));
2718        let gnodes: Vec<GraphNode> = sizes
2719            .iter()
2720            .map(|b| GraphNode {
2721                w: b.w,
2722                h: b.h,
2723                ..Default::default()
2724            })
2725            .collect();
2726        let gedges = vec![
2727            GraphEdge {
2728                from: 0,
2729                to: 1,
2730                label_w: None,
2731            },
2732            GraphEdge {
2733                from: 1,
2734                to: 2,
2735                label_w: None,
2736            },
2737        ];
2738        let l = layered(&gnodes, &gedges, &LayeredParams::default());
2739        let nodes: Vec<DrawNode> = spec
2740            .iter()
2741            .zip(&sizes)
2742            .enumerate()
2743            .map(|(i, ((_, shape), b))| DrawNode {
2744                id: format!("n{i}"),
2745                shape: *shape,
2746                lines: b.lines.clone(),
2747                stroke: (13, 148, 136),
2748                tooltip: b.lines.join(" "),
2749                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2750                // the observation flagged: filled in its accent
2751                accent: (*shape == NodeShape::Terminal).then_some((217, 119, 6)),
2752                ..Default::default()
2753            })
2754            .collect();
2755        let edges = vec![
2756            // the variable s₀ between the two factors
2757            DrawEdge {
2758                colour: (13, 148, 136),
2759                width: 1.2,
2760                undirected: true,
2761                label: Some("s₀".to_string()),
2762                label_math: true,
2763                ..Default::default()
2764            },
2765            DrawEdge {
2766                colour: (13, 148, 136),
2767                width: 1.2,
2768                undirected: true,
2769                ..Default::default()
2770            },
2771        ];
2772        let render = |style: &GraphStyle| {
2773            draw(
2774                &l,
2775                &[],
2776                &[],
2777                &nodes,
2778                &edges,
2779                style,
2780                crate::theme::presets::theme_void(),
2781            )
2782            .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32 + 40, l.h.ceil() as u32)
2783            .unwrap()
2784        };
2785        let math = GraphStyle {
2786            math_font: Some("STIX Two Math, serif".to_string()),
2787            ..GraphStyle::default()
2788        };
2789        let svg = render(&math);
2790        let el = |text: &str| {
2791            let at = svg
2792                .find(&format!(">{text}</text>"))
2793                .unwrap_or_else(|| panic!("{text}"));
2794            svg[svg[..at].rfind('<').unwrap()..at].to_string()
2795        };
2796        // the terminal: a filled square, its label starting beside it
2797        assert!(svg.contains("gg-graph-node-terminal"), "terminal mark");
2798        assert!(
2799            svg.contains("fill=\"#D97706\""),
2800            "the terminal in its accent"
2801        );
2802        let x1 = el("x₁");
2803        assert!(
2804            x1.contains("text-anchor=\"start\"") && x1.contains("italic"),
2805            "{x1}"
2806        );
2807        let t = &l.nodes[2];
2808        let lx: f64 = x1
2809            .split("x=\"")
2810            .nth(1)
2811            .unwrap()
2812            .split('"')
2813            .next()
2814            .unwrap()
2815            .parse()
2816            .unwrap();
2817        assert!(
2818            lx > t.cx + t.w / 2.0,
2819            "the label right of the square: {lx} vs {}",
2820            t.cx
2821        );
2822        // the variable's edge label in the math font
2823        let s0 = el("s₀");
2824        assert!(
2825            s0.contains("STIX Two Math") && s0.contains("italic"),
2826            "{s0}"
2827        );
2828        // without a math font: a plain edge label
2829        let plain = render(&GraphStyle::default());
2830        let at = plain.find(">s₀</text>").unwrap();
2831        assert!(!plain[plain[..at].rfind('<').unwrap()..at].contains("italic"));
2832    }
2833
2834    /// A coin toss as a Forney-style factor graph: a Beta prior box, the
2835    /// parameter's circle, an equality node, Bernoulli boxes and observed
2836    /// circles in a plate; undirected edges with interface names near the
2837    /// factor.
2838    #[test]
2839    fn draws_a_factor_graph_with_shapes_and_a_plate() {
2840        let n = 3;
2841        // (label, shape)
2842        let mut spec = vec![
2843            ("Beta", NodeShape::Box),
2844            ("θ", NodeShape::Circle),
2845            ("=", NodeShape::Square),
2846        ];
2847        for _ in 0..n {
2848            spec.push(("Ber", NodeShape::Box));
2849        }
2850        for _ in 0..n {
2851            spec.push(("y", NodeShape::FilledCircle));
2852        }
2853        spec.push(("2.0", NodeShape::Text));
2854        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
2855        // (from, to, interface)
2856        let mut links = vec![(0, 1, "out"), (1, 2, ""), (9, 0, "a")];
2857        for i in 0..n {
2858            links.push((2, 3 + i, "p"));
2859            links.push((3 + i, 3 + n + i, "out"));
2860        }
2861        let gnodes: Vec<GraphNode> = sizes
2862            .iter()
2863            .map(|b| GraphNode {
2864                w: b.w,
2865                h: b.h,
2866                ..Default::default()
2867            })
2868            .collect();
2869        let gedges: Vec<GraphEdge> = links
2870            .iter()
2871            .map(|&(a, b, _)| GraphEdge {
2872                from: a,
2873                to: b,
2874                label_w: None,
2875            })
2876            .collect();
2877        // a plate reaches past its nodes: room for it in the margin
2878        let params = LayeredParams {
2879            margin: 32.0,
2880            ..Default::default()
2881        };
2882        let l = layered(&gnodes, &gedges, &params);
2883        let nodes: Vec<DrawNode> = spec
2884            .iter()
2885            .zip(&sizes)
2886            .enumerate()
2887            .map(|(i, ((_, shape), b))| DrawNode {
2888                id: format!("n{i}"),
2889                shape: *shape,
2890                lines: b.lines.clone(),
2891                stroke: (60, 60, 60),
2892                tooltip: b.lines.join(" "),
2893                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2894                // θ's belief curve
2895                belief: (i == 1).then(|| (vec![0.0, 0.3, 1.0, 0.3, 0.0], (120, 80, 200))),
2896                // and its prior, wider
2897                prior: (i == 1).then(|| (vec![0.2, 0.4, 0.5, 0.4, 0.2], (150, 150, 150))),
2898                ..Default::default()
2899            })
2900            .collect();
2901        let edges: Vec<DrawEdge> = links
2902            .iter()
2903            .map(|&(a, b, iface)| DrawEdge {
2904                colour: (90, 90, 90),
2905                width: 1.2,
2906                undirected: true,
2907                label: (!iface.is_empty()).then(|| iface.to_string()),
2908                // the interface name near the factor
2909                label_at: Some(if spec[b].1 == NodeShape::Box {
2910                    0.8
2911                } else {
2912                    0.2
2913                }),
2914                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2915                ..Default::default()
2916            })
2917            .collect();
2918        let plates = [Plate {
2919            label: "i = 1..3".to_string(),
2920            nodes: (3..3 + 2 * n).collect(),
2921        }];
2922        let style = GraphStyle::default();
2923        let svg = draw(
2924            &l,
2925            &[],
2926            &plates,
2927            &nodes,
2928            &edges,
2929            &style,
2930            crate::theme::presets::theme_void(),
2931        )
2932        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2933        .unwrap();
2934        // every node is a mark, shapes classed, undirected: no arrowheads
2935        assert_eq!(svg.matches("data-node=").count(), spec.len());
2936        for shape in ["circle", "filled-circle", "square", "text"] {
2937            assert!(svg.contains(&format!("gg-graph-node-{shape}")), "{shape}");
2938        }
2939        assert!(
2940            !svg.contains("data-part=\"arrow\""),
2941            "an undirected edge has no arrowhead"
2942        );
2943        assert_eq!(svg.matches("data-edge=").count(), links.len());
2944        // θ's belief curve: a filled shape over its circle, in its group
2945        assert!(svg.contains("gg-graph-node-belief"), "belief layer");
2946        assert!(svg.contains("fill=\"#7850C8\""), "belief colour");
2947        // its prior: a dashed outline, drawn before (under) the belief
2948        let (pr, be) = (
2949            svg.find("gg-graph-node-prior").expect("prior layer"),
2950            svg.find("gg-graph-node-belief").unwrap(),
2951        );
2952        assert!(pr < be, "the prior under the belief");
2953        let mark = &svg[svg[..pr].rfind('<').unwrap()..pr];
2954        assert!(mark.contains("stroke-dasharray"), "dashed prior: {mark}");
2955        // no math font: bold sans labels
2956        assert!(!svg.contains("font-style=\"italic\""), "plain labels");
2957        // a math font: the shaped nodes' labels in it, italic; glyph colours
2958        let math = GraphStyle {
2959            math_font: Some("STIX Two Math, serif".to_string()),
2960            glyph_fill: Some((240, 247, 246)),
2961            glyph_ink: Some((13, 148, 136)),
2962            ..style.clone()
2963        };
2964        let msvg = draw(
2965            &l,
2966            &[],
2967            &plates,
2968            &nodes,
2969            &edges,
2970            &math,
2971            crate::theme::presets::theme_void(),
2972        )
2973        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2974        .unwrap();
2975        assert!(msvg.contains("STIX Two Math"), "math font");
2976        assert!(msvg.contains("font-style=\"italic\""), "italic labels");
2977        // …but a constant stays upright
2978        let two = msvg.find(">2.0<").expect("the constant 2.0");
2979        let el = &msvg[msvg[..two].rfind('<').unwrap()..two];
2980        assert!(!el.contains("italic"), "upright constant: {el}");
2981        // the plate, and its label
2982        assert!(svg.contains("data-plate=\"i = 1..3\"") && svg.contains(">i = 1..3<"));
2983        // the observed circles' dark fill
2984        assert!(svg.contains(&format!(
2985            "fill=\"{}\"",
2986            hex(style.observed_fill).to_uppercase()
2987        )));
2988        // no two nodes overlap
2989        for (i, a) in l.nodes.iter().enumerate() {
2990            for b in &l.nodes[i + 1..] {
2991                let apart = (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
2992                    || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0;
2993                assert!(apart, "overlap");
2994            }
2995        }
2996        // the circle is round: rx is half its width
2997        let c = &l.nodes[1];
2998        assert!(svg.contains(&format!("rx=\"{:.2}\"", c.w / 2.0)), "{}", c.w);
2999    }
3000
3001    /// An HMM over five slices with learned transition (A) and observation
3002    /// (B) matrices, in bands param / state / obs: the state chain is one
3003    /// straight row, each observation below its state.
3004    #[test]
3005    fn banded_hmm_keeps_the_state_chain_straight() {
3006        use crate::graph_layout::{banded, BandedParams};
3007        let t_n = 5;
3008        // (label, shape, band)
3009        let mut spec: Vec<(String, NodeShape, usize)> = vec![
3010            ("Dir".into(), NodeShape::Glyph, 0), // 0: prior on A
3011            ("A".into(), NodeShape::Square, 0),  // 1: = of A
3012            ("Dir".into(), NodeShape::Glyph, 0), // 2: prior on B
3013            ("B".into(), NodeShape::Square, 0),  // 3: = of B
3014            ("Cat".into(), NodeShape::Glyph, 1), // 4: initial state prior
3015            ("s₀".into(), NodeShape::Circle, 1), // 5
3016        ];
3017        let mut links: Vec<(usize, usize, &str)> =
3018            vec![(0, 1, "out"), (2, 3, "out"), (4, 5, "out")];
3019        let mut prev = 5;
3020        for t in 1..=t_n {
3021            let tr = spec.len();
3022            spec.push(("T".into(), NodeShape::Glyph, 1));
3023            let eq = spec.len();
3024            spec.push((format!("s{t}"), NodeShape::Square, 1));
3025            let ob = spec.len();
3026            spec.push(("T".into(), NodeShape::Glyph, 2));
3027            let x = spec.len();
3028            spec.push((format!("x{t}"), NodeShape::FilledCircle, 2));
3029            links.extend([
3030                (prev, tr, "in"),
3031                (1, tr, "a"),
3032                (tr, eq, "out"),
3033                (eq, ob, "in"),
3034                (3, ob, "a"),
3035                (ob, x, "out"),
3036            ]);
3037            prev = eq;
3038        }
3039        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh, _)| node_size(*sh, l)).collect();
3040        let gnodes: Vec<GraphNode> = spec
3041            .iter()
3042            .zip(&sizes)
3043            .map(|((_, _, b), s)| GraphNode {
3044                w: s.w,
3045                h: s.h,
3046                lane: Some(*b),
3047                ..Default::default()
3048            })
3049            .collect();
3050        let gedges: Vec<GraphEdge> = links
3051            .iter()
3052            .map(|&(a, b, _)| GraphEdge {
3053                from: a,
3054                to: b,
3055                label_w: None,
3056            })
3057            .collect();
3058        let l = banded(
3059            &gnodes,
3060            &gedges,
3061            &BandedParams {
3062                bands: 3,
3063                margin: 32.0,
3064                ..Default::default()
3065            },
3066        );
3067        // the chain: every transition and state node on one row
3068        let chain: Vec<usize> = (0..spec.len())
3069            .filter(|&i| spec[i].2 == 1 && i != 4)
3070            .collect();
3071        let y = l.nodes[chain[0]].cy;
3072        for &i in &chain {
3073            assert_eq!(l.nodes[i].cy, y, "{} off the row", spec[i].0);
3074        }
3075        // each observation factor straight below its state's = node
3076        for t in 0..t_n {
3077            let (eq, ob) = (6 + 4 * t + 1, 6 + 4 * t + 2);
3078            assert_eq!(l.nodes[eq].cx, l.nodes[ob].cx, "slice {t}");
3079            assert!(l.nodes[ob].cy > y);
3080        }
3081        // no edge passes through a box other than its own two ends
3082        let crosses = |(x0, y0): (f64, f64), (x1, y1): (f64, f64), n: &PlacedNode| {
3083            // sampled along the segment, the box shrunk by a pixel
3084            (0..=40).any(|k| {
3085                let t = k as f64 / 40.0;
3086                let (x, y) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
3087                (x - n.cx).abs() < n.w / 2.0 - 1.0 && (y - n.cy).abs() < n.h / 2.0 - 1.0
3088            })
3089        };
3090        for (k, &(a, b, _)) in links.iter().enumerate() {
3091            for w in l.edges[k].windows(2) {
3092                for (i, n) in l.nodes.iter().enumerate() {
3093                    if i != a && i != b {
3094                        assert!(
3095                            !crosses(w[0], w[1], n),
3096                            "edge {a}->{b} crosses {}",
3097                            spec[i].0
3098                        );
3099                    }
3100                }
3101            }
3102        }
3103        // nothing overlaps
3104        for (i, a) in l.nodes.iter().enumerate() {
3105            for b in &l.nodes[i + 1..] {
3106                assert!(
3107                    (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
3108                        || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0
3109                );
3110            }
3111        }
3112        let nodes: Vec<DrawNode> = spec
3113            .iter()
3114            .zip(&sizes)
3115            .enumerate()
3116            .map(|(i, ((_, shape, _), b))| DrawNode {
3117                id: format!("n{i}"),
3118                shape: *shape,
3119                lines: b.lines.clone(),
3120                stroke: (60, 60, 60),
3121                ..Default::default()
3122            })
3123            .collect();
3124        let edges: Vec<DrawEdge> = links
3125            .iter()
3126            .map(|&(_, b, iface)| DrawEdge {
3127                colour: (90, 90, 90),
3128                width: 1.2,
3129                undirected: true,
3130                label: Some(iface.to_string()),
3131                label_at: Some(if spec[b].1 == NodeShape::Glyph {
3132                    0.8
3133                } else {
3134                    0.2
3135                }),
3136                ..Default::default()
3137            })
3138            .collect();
3139        let lanes = ["param".to_string(), "state".to_string(), "obs".to_string()];
3140        let svg = draw(
3141            &l,
3142            &lanes,
3143            &[],
3144            &nodes,
3145            &edges,
3146            &GraphStyle::default(),
3147            crate::theme::presets::theme_void(),
3148        )
3149        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
3150        .unwrap();
3151        if let Ok(path) = std::env::var("GGPLOT_GRAPH_SVG") {
3152            std::fs::write(path, &svg).unwrap();
3153        }
3154        assert_eq!(svg.matches("data-lane=").count(), 3);
3155    }
3156}