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