Skip to main content

ggplot_rs/
graph.rs

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