Skip to main content

ggplot_rs/
graph.rs

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