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`; a shaped node's
178    /// mark also has `<prefix>node-<shape>`).
179    pub class_prefix: String,
180    /// A factor graph's math font: when set, the labels of shaped nodes
181    /// (variables, observations, equality nodes, glyph factors) are set in
182    /// this family, italic and regular weight — `θ`, `x₁`, `𝒩` read as
183    /// mathematics. `None` keeps the bold sans labels.
184    pub math_font: Option<String>,
185    /// A glyph factor's fill ([`NodeShape::Glyph`]); `None` is `card`.
186    pub glyph_fill: Option<Rgb>,
187    /// A glyph factor's glyph colour; `None` is `heading`.
188    pub glyph_ink: Option<Rgb>,
189}
190
191impl Default for GraphStyle {
192    fn default() -> Self {
193        GraphStyle {
194            card: (255, 255, 255),
195            band: (226, 228, 233),
196            muted: (107, 114, 128),
197            heading: (17, 24, 39),
198            ink: (31, 41, 55),
199            variable_fill: (229, 231, 235),
200            observed_fill: (75, 85, 99),
201            plate: (107, 114, 128),
202            class_prefix: "gg-graph-".to_string(),
203            math_font: None,
204            glyph_fill: None,
205            glyph_ink: None,
206        }
207    }
208}
209
210/// A node's mark. A factor graph (Forney style) draws factors as boxes,
211/// variables as circles (filled when observed), equality nodes as small
212/// squares, deterministic (delta) nodes as small filled squares, and
213/// constants as plain text.
214#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
215pub enum NodeShape {
216    /// A box with a label, value, badge and sparkline ([`node_box`]).
217    #[default]
218    Box,
219    Circle,
220    FilledCircle,
221    /// A small square, its label above it.
222    Square,
223    /// A small filled square, its label above it.
224    FilledSquare,
225    /// The label alone.
226    Text,
227    /// A small square box with a short glyph centred in it (a factor drawn
228    /// as `𝒩`, `Γ`, `Ber`, …): uniform, so a factor graph stays compact.
229    Glyph,
230    /// A small filled square at the end of an edge, its label beside it (to
231    /// the right): an observation in Forney style, where data enters.
232    Terminal,
233    /// A box with square corners and a box's contents: an influence
234    /// diagram's decision.
235    Rect,
236    /// A diamond with the label (and a value line) inside: an influence
237    /// diagram's utility.
238    Diamond,
239    /// A box with a second outline inside it and a box's contents: a
240    /// deterministic node of a Bayesian network.
241    DoubleBox,
242}
243
244impl NodeShape {
245    fn name(self) -> &'static str {
246        match self {
247            NodeShape::Box => "box",
248            NodeShape::Circle => "circle",
249            NodeShape::FilledCircle => "filled-circle",
250            NodeShape::Square => "square",
251            NodeShape::FilledSquare => "filled-square",
252            NodeShape::Text => "text",
253            NodeShape::Glyph => "glyph",
254            NodeShape::Terminal => "terminal",
255            NodeShape::Rect => "rect",
256            NodeShape::Diamond => "diamond",
257            NodeShape::DoubleBox => "double-box",
258        }
259    }
260
261    /// A box's contents (label, value, badge, sparkline, states) go inside:
262    /// [`NodeShape::Box`], [`NodeShape::Rect`], [`NodeShape::DoubleBox`].
263    pub fn boxed(self) -> bool {
264        matches!(
265            self,
266            NodeShape::Box | NodeShape::Rect | NodeShape::DoubleBox
267        )
268    }
269}
270
271/// A belief curve's size over its node (px).
272pub const BELIEF_W: f64 = 46.0;
273pub const BELIEF_H: f64 = 16.0;
274/// A small square's side (px).
275const SQUARE: f64 = 14.0;
276/// A terminal's side (px).
277const TERMINAL: f64 = 11.0;
278/// A glyph factor's side (px) and its glyph's size.
279const GLYPH_SIDE: f64 = 34.0;
280const GLYPH_PX: f64 = 15.0;
281
282/// A state row's height, its bar's length and the widest state name (px).
283const STATE_H: f64 = 15.0;
284const STATE_BAR_W: f64 = 64.0;
285const STATE_NAME_MAX: f64 = 84.0;
286/// The gaps around a state's bar, and the room for its text ("100%").
287const STATE_GAP: f64 = 6.0;
288const STATE_TEXT_W: f64 = 30.0;
289/// A box with state rows may be this much wider than a plain one.
290const STATES_MAX_W: f64 = 224.0;
291
292/// A state's name as its row shows it: cut with "…" past
293/// `STATE_NAME_MAX`.
294fn state_name(name: &str) -> String {
295    let cap = (STATE_NAME_MAX / (SMALL_PX * 0.56)).floor() as usize;
296    if name.chars().count() <= cap {
297        return name.to_string();
298    }
299    let mut s: String = name.chars().take(cap.saturating_sub(1)).collect();
300    s = s.trim_end().to_string();
301    s.push('…');
302    s
303}
304
305/// The box a discrete node needs (a Bayesian network's node, Netica /
306/// GeNIe style): [`node_box`]'s label, value and badge, then one row per
307/// state (its name, a bar and the probability as text), as [`draw`] fills
308/// it from [`DrawNode::states`]. No states: [`node_box`].
309pub fn states_box(
310    label: &str,
311    value: Option<&str>,
312    badge: Option<&str>,
313    states: &[String],
314) -> NodeBox {
315    let b = node_box(label, value, badge, false);
316    if states.is_empty() {
317        return b;
318    }
319    let names = states
320        .iter()
321        .map(|n| text_w(&state_name(n), SMALL_PX, true))
322        .fold(0.0, f64::max);
323    let rows = names + STATE_GAP + STATE_BAR_W + STATE_GAP + STATE_TEXT_W;
324    NodeBox {
325        w: b.w.max(rows + 2.0 * BOX_PAD_X).min(STATES_MAX_W),
326        h: b.h + 4.0 + STATE_H * states.len() as f64,
327        lines: b.lines,
328    }
329}
330
331/// The diamond a [`NodeShape::Diamond`] needs for its label and an
332/// optional value line: the text's box, its corners on the diamond's edges.
333pub fn diamond_box(label: &str, value: Option<&str>) -> NodeBox {
334    let lines = wrap(label, 132.0);
335    let mut w = lines
336        .iter()
337        .map(|l| text_w(l, LABEL_PX, true))
338        .fold(0.0, f64::max);
339    let mut h = LINE_H * lines.len() as f64;
340    if let Some(v) = value {
341        w = w.max(text_w(v, VALUE_PX, true));
342        h += LINE_H;
343    }
344    // a w × h box inscribed in the diamond takes twice each, plus a margin
345    NodeBox {
346        w: (2.0 * w + 16.0).max(72.0),
347        h: (2.0 * h + 8.0).max(44.0),
348        lines,
349    }
350}
351
352/// The size a node of `shape` needs for `label` (a [`NodeShape::Box`] is
353/// [`node_box`] without a value, badge or sparkline). A circle fits its
354/// label on one line, at least 30 px across.
355pub fn node_size(shape: NodeShape, label: &str) -> NodeBox {
356    let one = || vec![label.to_string()];
357    match shape {
358        NodeShape::Box | NodeShape::Rect | NodeShape::DoubleBox => {
359            node_box(label, None, None, false)
360        }
361        NodeShape::Diamond => diamond_box(label, None),
362        NodeShape::Circle | NodeShape::FilledCircle => {
363            let d = (text_w(label, LABEL_PX, true) + 14.0).max(30.0);
364            NodeBox {
365                w: d,
366                h: d,
367                lines: one(),
368            }
369        }
370        NodeShape::Square | NodeShape::FilledSquare => NodeBox {
371            w: SQUARE,
372            h: SQUARE,
373            lines: if label.is_empty() { Vec::new() } else { one() },
374        },
375        NodeShape::Terminal => NodeBox {
376            w: TERMINAL,
377            h: TERMINAL,
378            lines: if label.is_empty() { Vec::new() } else { one() },
379        },
380        NodeShape::Text => NodeBox {
381            w: text_w(label, LABEL_PX, false) + 8.0,
382            h: 20.0,
383            lines: one(),
384        },
385        NodeShape::Glyph => {
386            let side = (text_w(label, GLYPH_PX, true) + 14.0).max(GLYPH_SIDE);
387            NodeBox {
388                w: side,
389                h: GLYPH_SIDE,
390                lines: one(),
391            }
392        }
393    }
394}
395
396/// A plate: a dashed box around a collection of nodes (indices in the
397/// layout's order), labelled at its top left (`x_t`, `t = 1..T`).
398#[derive(Clone, Debug, Default)]
399pub struct Plate {
400    pub label: String,
401    pub nodes: Vec<usize>,
402}
403
404/// A `data-*` attribute: its name (without `data-`) and value; `None` leaves
405/// it off that mark.
406pub type DataAttr = (String, Option<String>);
407
408/// One state of a discrete node: a row in its box with the state's name, a
409/// bar for its probability and that probability as text, the prior as a
410/// faint bar behind it with a tick where it ends (Netica / GeNIe style).
411#[derive(Clone, Debug, Default, PartialEq)]
412pub struct StateBar {
413    pub name: String,
414    /// The probability, 0..=1 (clamped).
415    pub p: f64,
416    /// The probability before any evidence, 0..=1.
417    pub prior: Option<f64>,
418    /// What the row says after the bar (e.g. `36%`).
419    pub text: String,
420    /// The observed state: its name in bold.
421    pub observed: bool,
422}
423
424/// What a node's box shows, and its attributes. Its geometry comes from the
425/// layout ([`PlacedNode`]); its label lines from [`node_box`].
426#[derive(Clone, Debug, Default)]
427pub struct DrawNode {
428    /// The `data-of` group of everything drawn for the node.
429    pub id: String,
430    /// Its mark; anything but a box shows only the label.
431    pub shape: NodeShape,
432    /// The label, wrapped ([`NodeBox::lines`]).
433    pub lines: Vec<String>,
434    /// A value line under the label.
435    pub value: Option<String>,
436    /// A badge row: its text and its dot's (and outline's) colour.
437    pub badge: Option<(String, Rgb)>,
438    /// The box (or circle, square) outline.
439    pub stroke: Rgb,
440    /// A thin bar along the box's left edge; a filled mark (an observation,
441    /// a terminal) is filled with it instead.
442    pub accent: Option<Rgb>,
443    /// A sparkline (two values or more) along the bottom, and its colour.
444    pub spark: Option<(Vec<f64>, Rgb)>,
445    /// A belief curve over the node (a factor graph variable's density):
446    /// heights 0..=1 at evenly spaced points (three or more), and its colour.
447    pub belief: Option<(Vec<f64>, Rgb)>,
448    /// The prior behind the belief curve: heights on the same scale and
449    /// span as [`DrawNode::belief`], drawn as a faint dashed outline, and
450    /// its colour.
451    pub prior: Option<(Vec<f64>, Rgb)>,
452    /// A discrete node's states, one row each under the label (a boxed
453    /// shape; size it with [`states_box`]), and the bars' colour.
454    pub states: Option<(Vec<StateBar>, Rgb)>,
455    /// The box's (or diamond's) fill; `None` is the card colour. E.g. a
456    /// node with evidence, shaded.
457    pub fill: Option<Rgb>,
458    pub tooltip: String,
459    /// `data-*` on the box (the hit target); every node lists the same
460    /// names, in the same order.
461    pub attrs: Vec<DataAttr>,
462}
463
464/// An edge's line pattern.
465#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
466pub enum EdgeLine {
467    #[default]
468    Solid,
469    Dashed,
470    /// Round dots (zero-length dashes with round caps).
471    Dots,
472}
473
474/// What an edge looks like, and its attributes. Its points come from the
475/// layout ([`GraphLayout::edges`]); the arrowhead is on its last point,
476/// unless `undirected`.
477#[derive(Clone, Debug, Default)]
478pub struct DrawEdge {
479    pub colour: Rgb,
480    /// Line width (px), see [`flow_width`].
481    pub width: f64,
482    pub line: EdgeLine,
483    /// Extra CSS classes on the path.
484    pub class: Option<String>,
485    pub tooltip: String,
486    /// A label (`\n` breaks lines) on the edge, clear of the boxes.
487    pub label: Option<String>,
488    /// Where along the edge the label goes (0 at its start, 1 at its end),
489    /// e.g. near a factor for an interface name; `None`: the middle, moved
490    /// along the edge until no box covers it.
491    pub label_at: Option<f64>,
492    /// No arrowhead (a factor graph's edges).
493    pub undirected: bool,
494    /// The label names a variable (Forney style: the edge is the variable):
495    /// set in [`GraphStyle::math_font`] when there is one, in the heading
496    /// colour.
497    pub label_math: bool,
498    /// `data-*` on the path; every edge lists the same names, in the same
499    /// order.
500    pub attrs: Vec<DataAttr>,
501    /// `data-*` on the label.
502    pub label_attrs: Vec<DataAttr>,
503}
504
505/// An edge's width (px) for what it carries, `value` of the graph's `max`:
506/// area-true (`sqrt`), 1.4 px to 7 px; 1.6 px without a value; dotted edges
507/// 3–6 px so their dots show. Rounded to 0.1 px.
508pub fn flow_width(value: Option<f64>, max: f64, line: EdgeLine) -> f64 {
509    let width = match value {
510        Some(v) if max > 0.0 => 1.4 + 5.6 * (v.max(0.0) / max).sqrt(),
511        _ => 1.6,
512    };
513    let width = match line {
514        EdgeLine::Dots => width.clamp(3.0, 6.0),
515        _ => width,
516    };
517    (width * 10.0).round() / 10.0
518}
519
520/// Columns built row by row, in px with y down.
521#[derive(Default)]
522struct Frame(Vec<(String, Vec<Value>)>);
523
524impl Frame {
525    fn col(&mut self, name: &str) -> &mut Vec<Value> {
526        let i = match self.0.iter().position(|(n, _)| n == name) {
527            Some(i) => i,
528            None => {
529                self.0.push((name.to_string(), Vec::new()));
530                self.0.len() - 1
531            }
532        };
533        &mut self.0[i].1
534    }
535    fn num(&mut self, name: &str, v: f64) -> &mut Self {
536        self.col(name).push(Value::Float(v));
537        self
538    }
539    fn txt(&mut self, name: &str, v: impl Into<String>) -> &mut Self {
540        self.col(name).push(Value::Str(v.into()));
541        self
542    }
543    fn opt(&mut self, name: &str, v: Option<String>) -> &mut Self {
544        self.col(name).push(v.map_or(Value::Na, Value::Str));
545        self
546    }
547    /// `attrs` as columns `a:<name>`.
548    fn attrs(&mut self, attrs: &[DataAttr]) -> &mut Self {
549        for (n, v) in attrs {
550            self.opt(&format!("a:{n}"), v.clone());
551        }
552        self
553    }
554    fn is_empty(&self) -> bool {
555        self.0.first().is_none_or(|(_, v)| v.is_empty())
556    }
557    /// `aes` plus a `data_attr` per `a:<name>` column, in column order.
558    fn attr_aes(&self, mut aes: Aes) -> Aes {
559        for (n, _) in &self.0 {
560            if let Some(name) = n.strip_prefix("a:") {
561                aes = aes.data_attr(name, n);
562            }
563        }
564        aes
565    }
566    /// The frame's columns, its pixel y (down) flipped to data y (up) on a
567    /// canvas `h` tall: `y` → `h - y`, and a rect's `y0`/`y1` swapped as
568    /// they flip so `y0` stays the low edge.
569    fn take(&mut self, h: f64) -> Vec<(String, Vec<Value>)> {
570        let flip = |v: Vec<Value>| -> Vec<Value> {
571            v.into_iter()
572                .map(|x| match x {
573                    Value::Float(y) => Value::Float(h - y),
574                    other => other,
575                })
576                .collect()
577        };
578        std::mem::take(&mut self.0)
579            .into_iter()
580            .map(|(n, v)| match n.as_str() {
581                "y" => (n, flip(v)),
582                "y0" => ("y1".to_string(), flip(v)),
583                "y1" => ("y0".to_string(), flip(v)),
584                _ => (n, v),
585            })
586            .collect()
587    }
588}
589
590/// Frames keyed by a colour a geom only takes as a fixed parameter (a
591/// rect's stroke), in first-seen order: one layer per colour.
592fn by_colour(v: &mut Vec<(Rgb, Frame)>, c: Rgb) -> &mut Frame {
593    let i = match v.iter().position(|(k, _)| *k == c) {
594        Some(i) => i,
595        None => {
596            v.push((c, Frame::default()));
597            v.len() - 1
598        }
599    };
600    &mut v[i].1
601}
602
603fn hex(c: Rgb) -> String {
604    format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
605}
606
607/// The point a fraction `t` (0..1) of the way along a polyline.
608fn point_at(pts: &[(f64, f64)], t: f64) -> (f64, f64) {
609    let seg = |i: usize| {
610        let (a, b) = (pts[i], pts[i + 1]);
611        ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
612    };
613    let total: f64 = (0..pts.len().saturating_sub(1)).map(seg).sum();
614    let mut left = total * t;
615    for i in 0..pts.len().saturating_sub(1) {
616        let l = seg(i);
617        if l >= left && l > 0.0 {
618            let t = left / l;
619            let (a, b) = (pts[i], pts[i + 1]);
620            return (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
621        }
622        left -= l;
623    }
624    pts.first().copied().unwrap_or((0.0, 0.0))
625}
626
627/// Where an edge's label goes: the midpoint of the edge, else the nearest
628/// point along it where the label's box (11 px lines drawn around `y - 4`)
629/// touches no node box — so a node doesn't cover it.
630fn edge_label_at(pts: &[(f64, f64)], label: &str, nodes: &[PlacedNode]) -> (f64, f64) {
631    let lines = label.split('\n').count();
632    let hw = edge_label_width(label) / 2.0 + 3.0;
633    let hh = lines as f64 * 6.6 + 3.0;
634    let clear = |(x, y): (f64, f64)| {
635        let cy = y - 4.0 - 0.36 * SMALL_PX;
636        nodes
637            .iter()
638            .all(|n| (x - n.cx).abs() >= hw + n.w / 2.0 || (cy - n.cy).abs() >= hh + n.h / 2.0)
639    };
640    let mid = point_at(pts, 0.5);
641    [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74, 0.18, 0.82]
642        .into_iter()
643        .map(|t| point_at(pts, t))
644        .find(|&p| clear(p))
645        .unwrap_or(mid)
646}
647
648/// An end label's anchor (as for a mid label: the text goes 4 px above
649/// it): on the edge's last (first) segment, its near side `LABEL_CLEAR`
650/// from the box the edge ends at; on a vertical segment beside the line
651/// instead, its top `LABEL_CLEAR` below (above) that box. At most half
652/// the segment in.
653fn end_label_at(pts: &[(f64, f64)], label: &str, t: f64) -> (f64, f64) {
654    use crate::graph_layout::LABEL_CLEAR;
655    let n = pts.len();
656    if n < 2 {
657        return pts.first().copied().unwrap_or((0.0, 0.0));
658    }
659    let (end, prev) = if t >= 0.5 {
660        (pts[n - 1], pts[n - 2])
661    } else {
662        (pts[0], pts[1])
663    };
664    let (dx, dy) = (prev.0 - end.0, prev.1 - end.1);
665    let len = (dx * dx + dy * dy).sqrt();
666    if len == 0.0 {
667        return end;
668    }
669    let (ux, uy) = (dx / len, dy / len);
670    let lines = label.split('\n').count() as f64;
671    let hw = edge_label_width(label) / 2.0;
672    let hh = lines * 6.6;
673    // the anchor sits 4 px + 0.36 em below the text's middle
674    let below_mid = 4.0 + 0.36 * SMALL_PX;
675    if ux.abs() >= uy.abs() {
676        // along the line, above it: its near side LABEL_CLEAR from the box
677        let s = (hw + LABEL_CLEAR).min(len * 0.5);
678        (end.0 + ux * s, end.1 + uy * s)
679    } else {
680        // beside a vertical line, its top (bottom) clear of the box
681        let s = (hh + LABEL_CLEAR).min(len * 0.5);
682        (end.0 + LABEL_CLEAR + hw, end.1 + uy * s + below_mid)
683    }
684}
685
686/// Text is centred on its y (`dominant-baseline="middle"`); the layout
687/// places lines by their baseline. A cap-height-ish shift between the two.
688fn mid_of_baseline(baseline: f64, px: f64) -> f64 {
689    baseline - 0.36 * px
690}
691
692/// Draw a laid-out graph on a `layout.w` × `layout.h` px canvas: `lanes`
693/// names the layout's bands, `plates` group nodes, `nodes` and `edges` are
694/// in the layout's order.
695/// `theme` is the base (a void theme; the legend is turned off). Render the
696/// result with e.g. `render_svg_native_at(0.0, 0.0, w, h)` at the canvas
697/// size rounded up.
698pub fn draw(
699    layout: &GraphLayout,
700    lanes: &[String],
701    plates: &[Plate],
702    nodes: &[DrawNode],
703    edges: &[DrawEdge],
704    style: &GraphStyle,
705    mut theme: Theme,
706) -> GGPlot {
707    let s = style;
708    let class = |name: &str| format!("{}{name}", s.class_prefix);
709    let (w, h) = (layout.w.ceil().max(1.0), layout.h.ceil().max(1.0));
710    theme.legend_position = crate::theme::LegendPosition::None;
711    let mut plot = GGPlot::new(vec![
712        ("x".to_string(), vec![Value::Float(0.0), Value::Float(w)]),
713        ("y".to_string(), vec![Value::Float(0.0), Value::Float(h)]),
714    ])
715    .theme(theme)
716    // the canvas is the view (a zoom, so a mark reaching past it is clipped
717    // rather than dropped); `Frame::take` flips the layout's y-down pixels
718    .scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
719    .scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
720    .coord_cartesian_zoom(Some((0.0, w)), Some((0.0, h)))
721    .scale_color_identity()
722    .scale_fill_identity()
723    .scale_linewidth(
724        ScaleLinewidthContinuous::new()
725            .with_limits(0.0, 16.0)
726            .with_range(0.0, 16.0),
727    )
728    .scale_linetype_manual(vec![
729        ("solid", Linetype::Solid),
730        ("dashed", Linetype::Custom(vec![(6.0, 4.0)])),
731        // round caps on a zero-length dash: moving dots
732        ("dots", Linetype::Custom(vec![(0.0, 10.0)])),
733    ]);
734    let rect_aes = || Aes::new().xmin("x0").xmax("x1").ymin("y0").ymax("y1");
735    let inert = [("pointer-events", "none")];
736
737    // swimlanes (under everything): a tinted band per lane, its name on top
738    let (mut even, mut odd, mut names) = (Frame::default(), Frame::default(), Frame::default());
739    for &(l, x0, y0, x1, y1) in &layout.bands {
740        let name = lanes.get(l).cloned().unwrap_or_default();
741        let f = if l % 2 == 0 { &mut even } else { &mut odd };
742        f.num("x0", x0).num("x1", x1).num("y0", y0).num("y1", y1);
743        f.txt("lane", name.clone());
744        names
745            .num("x", x0 + 8.0)
746            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
747        names.txt("label", name);
748    }
749    for (mut f, alpha) in [(even, 0.35), (odd, 0.18)] {
750        if f.is_empty() {
751            continue;
752        }
753        plot = plot
754            .geom_rect_with(
755                GeomRect {
756                    fill: s.band,
757                    alpha,
758                    line_width: 0.0,
759                    ..Default::default()
760                }
761                .with_radius(6.0),
762            )
763            .layer_data(f.take(h))
764            .layer_aes(rect_aes().data_attr("lane", "lane"))
765            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane"))]);
766    }
767    if !names.is_empty() {
768        plot = plot
769            .geom_text_with(GeomText {
770                size: SMALL_PX,
771                color: s.muted,
772                hjust: 0.0,
773                fontface: FontFace::Bold,
774                ..Default::default()
775            })
776            .layer_data(names.take(h))
777            .layer_aes(Aes::new().x("x").y("y").label("label"))
778            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane-label"))]);
779    }
780
781    // plates (under the edges): a dashed box around each collection
782    let (mut pf, mut pl) = (Frame::default(), Frame::default());
783    for p in plates {
784        let members: Vec<&PlacedNode> = p
785            .nodes
786            .iter()
787            .filter_map(|&i| layout.nodes.get(i))
788            .collect();
789        if members.is_empty() {
790            continue;
791        }
792        let pad = 8.0;
793        let x0 = members
794            .iter()
795            .map(|n| n.cx - n.w / 2.0)
796            .fold(f64::INFINITY, f64::min)
797            - pad;
798        let x1 = members
799            .iter()
800            .map(|n| n.cx + n.w / 2.0)
801            .fold(f64::NEG_INFINITY, f64::max)
802            + pad;
803        let y0 = members
804            .iter()
805            .map(|n| n.cy - n.h / 2.0)
806            .fold(f64::INFINITY, f64::min)
807            - pad
808            - 14.0;
809        let y1 = members
810            .iter()
811            .map(|n| n.cy + n.h / 2.0)
812            .fold(f64::NEG_INFINITY, f64::max)
813            + pad;
814        for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] {
815            pf.num("x", x).num("y", y).txt("lt", "dashed");
816            pf.txt("g", p.label.clone()).txt("plate", p.label.clone());
817        }
818        pl.num("x", x0 + 6.0)
819            .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
820        pl.txt("label", p.label.clone());
821    }
822    if !pf.is_empty() {
823        plot = plot
824            .geom_path_with(GeomPath::default().color(s.plate).linewidth(1.0))
825            .layer_data(pf.take(h))
826            .layer_aes(
827                Aes::new()
828                    .x("x")
829                    .y("y")
830                    .group("g")
831                    .linetype("lt")
832                    .data_attr("plate", "plate"),
833            )
834            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate"))]);
835        plot = plot
836            .geom_text_with(GeomText {
837                size: SMALL_PX,
838                color: s.plate,
839                hjust: 0.0,
840                ..Default::default()
841            })
842            .layer_data(pl.take(h))
843            .layer_aes(Aes::new().x("x").y("y").label("label"))
844            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate-label"))]);
845    }
846
847    // edges (under the nodes): one path per edge, arrowed ones first
848    let (mut ef, mut uf, mut lf) = (Frame::default(), Frame::default(), Frame::default());
849    // a variable's name on its edge (Forney style), in the math font
850    let mut lmf = Frame::default();
851    for (k, e) in edges.iter().enumerate() {
852        let Some(route) = layout.edges.get(k) else {
853            continue;
854        };
855        let mut pts = route.clone();
856        if pts.len() < 2 {
857            continue;
858        }
859        // the arrow's tip is on the path's last point and its head is
860        // stroked as wide as the line (its mitred tip reaching about one
861        // line width further): end the path one width short of the box so
862        // the tip lands on its edge.
863        if !e.undirected {
864            let n = pts.len();
865            let ((fx, fy), (tx, ty)) = (pts[n - 2], pts[n - 1]);
866            let len = ((tx - fx).powi(2) + (ty - fy).powi(2)).sqrt().max(1e-6);
867            let pull = e.width.min(len / 2.0);
868            pts[n - 1] = (tx - (tx - fx) / len * pull, ty - (ty - fy) / len * pull);
869        }
870        let ef = if e.undirected { &mut uf } else { &mut ef };
871        let lt = match e.line {
872            EdgeLine::Solid => "solid",
873            EdgeLine::Dashed => "dashed",
874            EdgeLine::Dots => "dots",
875        };
876        for &(x, y) in &pts {
877            ef.num("x", x).num("y", y).txt("g", format!("e{k:04}"));
878            ef.txt("col", hex(e.colour))
879                .num("lw", e.width)
880                .txt("lt", lt);
881            ef.opt("cls", e.class.clone()).txt("tip", e.tooltip.clone());
882            ef.attrs(&e.attrs);
883        }
884        // a bus-routed edge's label is left to its tooltip: on the shared
885        // lane or at a shared entry it would only clutter
886        let routed = layout.routed.get(k).copied().unwrap_or(false);
887        if let Some(l) = e.label.as_ref().filter(|_| !routed) {
888            let (mx, my) = match e.label_at {
889                // near an end (a factor's interface): beside the box at
890                // that end, clear of it (anofox-visualization#1238)
891                Some(t) => end_label_at(route, l, t),
892                None => edge_label_at(route, l, &layout.nodes),
893            };
894            let f = if e.label_math && s.math_font.is_some() {
895                &mut lmf
896            } else {
897                &mut lf
898            };
899            f.num("x", mx).num("y", mid_of_baseline(my - 4.0, SMALL_PX));
900            f.txt("label", l.clone());
901            f.attrs(&e.label_attrs);
902        }
903    }
904    for (mut f, arrowed) in [(ef, true), (uf, false)] {
905        if f.is_empty() {
906            continue;
907        }
908        let aes = f.attr_aes(
909            Aes::new()
910                .x("x")
911                .y("y")
912                .group("g")
913                .color("col")
914                .linewidth("lw")
915                .linetype("lt")
916                .class("cls")
917                .tooltip("tip"),
918        );
919        let mut geom = GeomPath::default().lineend(LineEnd::Round);
920        if arrowed {
921            // a 7 px + width head, ~29° half-angle
922            geom = geom.arrow(
923                arrow()
924                    .closed()
925                    .angle(29.0)
926                    .length(ARROW + 1.0)
927                    .length_per_linewidth(1.2),
928            );
929        }
930        plot = plot
931            .geom_path_with(geom)
932            .layer_data(f.take(h))
933            .layer_aes(aes)
934            .layer_svg_attr("class", class("edge"));
935    }
936    if !lmf.is_empty() {
937        let aes = lmf.attr_aes(Aes::new().x("x").y("y").label("label"));
938        plot = plot
939            .geom_text_with(
940                GeomText {
941                    size: LABEL_PX + 1.0,
942                    color: s.heading,
943                    fontface: FontFace::Italic,
944                    fontfamily: s.math_font.clone().unwrap_or_default(),
945                    ..Default::default()
946                }
947                .bg_colour(s.card)
948                .bg_r(2.0),
949            )
950            .layer_data(lmf.take(h))
951            .layer_aes(aes)
952            .layer_svg_attrs(inert)
953            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
954    }
955    if !lf.is_empty() {
956        // text directly on the line, a card-coloured halo keeping it legible
957        let aes = lf.attr_aes(Aes::new().x("x").y("y").label("label"));
958        plot = plot
959            .geom_text_with(
960                GeomText {
961                    size: SMALL_PX,
962                    color: s.muted,
963                    ..Default::default()
964                }
965                .bg_colour(s.card)
966                .bg_r(2.0),
967            )
968            .layer_data(lf.take(h))
969            .layer_aes(aes)
970            .layer_svg_attrs(inert)
971            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
972    }
973
974    // nodes in reading order: the box (the hit target, outside any `data-of`
975    // group), then what it shows, grouped per node
976    let mut order: Vec<usize> = (0..nodes.len().min(layout.nodes.len())).collect();
977    order.sort_by_key(|&i| (layout.nodes[i].order, i));
978    // boxes, a layer per (outline, shape, fill)
979    let mut boxes: Vec<((Rgb, NodeShape, Rgb), Frame)> = Vec::new();
980    // a double box's inner outline, by colour
981    let mut outlines: Vec<(Rgb, Frame)> = Vec::new();
982    // a diamond's hit target (an invisible box) and its mark, by outline
983    let (mut hits, mut diamonds) = (Frame::default(), Vec::<(Rgb, Frame)>::new());
984    // state rows: the prior's faint bar, its tick, the bar, the names (the
985    // observed one bold) and the probabilities
986    let (mut sprior, mut stick, mut sbar) = (Frame::default(), Frame::default(), Frame::default());
987    let (mut sname, mut sseen, mut stext) = (Frame::default(), Frame::default(), Frame::default());
988    let mut beliefs = Frame::default();
989    let mut priors = Frame::default();
990    // shaped nodes, a layer per (shape, corner radius, outline)
991    let mut shaped: Vec<((NodeShape, u64, Rgb), Frame)> = Vec::new();
992    let (mut inside, mut inverse, mut above, mut glyphs, mut texts, mut beside) = (
993        Frame::default(),
994        Frame::default(),
995        Frame::default(),
996        Frame::default(),
997        Frame::default(),
998        Frame::default(),
999    );
1000    let mut badges: Vec<(Rgb, Frame)> = Vec::new();
1001    let (mut accent, mut lines, mut values) =
1002        (Frame::default(), Frame::default(), Frame::default());
1003    let (mut dots, mut btext, mut spark, mut ends) = (
1004        Frame::default(),
1005        Frame::default(),
1006        Frame::default(),
1007        Frame::default(),
1008    );
1009    for v in order {
1010        let nd = &nodes[v];
1011        let pn = &layout.nodes[v];
1012        let id = nd.id.clone();
1013        let (x, y) = (pn.cx - pn.w / 2.0, pn.cy - pn.h / 2.0);
1014        // the belief curve sits over the node (over a square's label)
1015        let squared = matches!(nd.shape, NodeShape::Square | NodeShape::FilledSquare);
1016        let base = y - if squared { 17.0 } else { 3.0 };
1017        let x0 = pn.cx - BELIEF_W / 2.0;
1018        let curve = |hs: &[f64]| -> Vec<(f64, f64)> {
1019            let last = (hs.len() - 1) as f64;
1020            hs.iter()
1021                .enumerate()
1022                .map(|(i, &h)| {
1023                    (
1024                        x0 + BELIEF_W * i as f64 / last,
1025                        base - h.clamp(0.0, 1.0) * BELIEF_H,
1026                    )
1027                })
1028                .collect()
1029        };
1030        // the prior: a faint outline behind the belief
1031        if let Some((hs, col)) = nd.prior.as_ref().filter(|(h, _)| h.len() >= 3) {
1032            for (px, py) in curve(hs) {
1033                priors.num("x", px).num("y", py).txt("g", id.clone());
1034                priors.txt("col", hex(*col)).txt("lt", "dashed");
1035                priors.txt("of", id.clone());
1036            }
1037        }
1038        if let Some((hs, col)) = nd.belief.as_ref().filter(|(h, _)| h.len() >= 3) {
1039            let mut pts = curve(hs);
1040            pts.push((x0 + BELIEF_W, base));
1041            pts.push((x0, base));
1042            for (px, py) in pts {
1043                beliefs.num("x", px).num("y", py).txt("g", id.clone());
1044                beliefs.txt("fill", hex(*col)).txt("of", id.clone());
1045            }
1046        }
1047        if nd.shape == NodeShape::Diamond {
1048            hits.num("x0", x)
1049                .num("x1", x + pn.w)
1050                .num("y0", y)
1051                .num("y1", y + pn.h);
1052            hits.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1053            let f = by_colour(&mut diamonds, nd.stroke);
1054            for (px, py) in [(pn.cx, y), (x + pn.w, pn.cy), (pn.cx, y + pn.h), (x, pn.cy)] {
1055                f.num("x", px).num("y", py).txt("g", id.clone());
1056                f.txt("fill", hex(nd.fill.unwrap_or(s.card)))
1057                    .txt("of", id.clone());
1058            }
1059            // the label (and value) centred in it
1060            let n = nd.lines.len() + usize::from(nd.value.is_some());
1061            let mut base = pn.cy - LINE_H * n as f64 / 2.0 + 12.0;
1062            for line in &nd.lines {
1063                lines
1064                    .num("x", pn.cx)
1065                    .num("y", mid_of_baseline(base, LABEL_PX));
1066                lines.txt("label", line.clone()).txt("of", id.clone());
1067                base += LINE_H;
1068            }
1069            if let Some(fv) = &nd.value {
1070                values
1071                    .num("x", pn.cx)
1072                    .num("y", mid_of_baseline(base, VALUE_PX));
1073                values.txt("label", fv.clone()).txt("of", id.clone());
1074            }
1075            continue;
1076        }
1077        if !nd.shape.boxed() {
1078            let r = match nd.shape {
1079                NodeShape::Circle | NodeShape::FilledCircle => pn.w.min(pn.h) / 2.0,
1080                NodeShape::Square | NodeShape::FilledSquare | NodeShape::Terminal => 1.5,
1081                NodeShape::Glyph => 4.0,
1082                _ => 0.0,
1083            };
1084            let (fill, stroke) = match nd.shape {
1085                NodeShape::Circle => (s.variable_fill, nd.stroke),
1086                // a filled mark takes the node's accent (a status: an
1087                // observation the model did not expect) over the observed fill
1088                NodeShape::FilledCircle | NodeShape::FilledSquare | NodeShape::Terminal => {
1089                    let c = nd.accent.unwrap_or(s.observed_fill);
1090                    (c, c)
1091                }
1092                NodeShape::Square => (s.card, nd.stroke),
1093                NodeShape::Glyph => (s.glyph_fill.unwrap_or(s.card), nd.stroke),
1094                _ => (s.card, s.card),
1095            };
1096            let key = (nd.shape, r.to_bits(), stroke);
1097            let i = match shaped.iter().position(|(k, _)| *k == key) {
1098                Some(i) => i,
1099                None => {
1100                    shaped.push((key, Frame::default()));
1101                    shaped.len() - 1
1102                }
1103            };
1104            let f = &mut shaped[i].1;
1105            f.num("x0", x)
1106                .num("x1", x + pn.w)
1107                .num("y0", y)
1108                .num("y1", y + pn.h);
1109            f.txt("fill", hex(fill));
1110            f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1111            let label = nd.lines.join(" ");
1112            if label.is_empty() {
1113                continue;
1114            }
1115            let target = match nd.shape {
1116                NodeShape::Glyph => &mut glyphs,
1117                NodeShape::FilledCircle => &mut inverse,
1118                NodeShape::Square | NodeShape::FilledSquare => &mut above,
1119                // a constant is a number: upright, never the math italic
1120                NodeShape::Text => &mut texts,
1121                NodeShape::Terminal => &mut beside,
1122                _ => &mut inside,
1123            };
1124            let ly = match nd.shape {
1125                NodeShape::Square | NodeShape::FilledSquare => y - 4.0 - 0.36 * SMALL_PX,
1126                _ => pn.cy,
1127            };
1128            // a terminal's label starts just right of it
1129            let lx = match nd.shape {
1130                NodeShape::Terminal => x + pn.w + 5.0,
1131                _ => pn.cx,
1132            };
1133            target.num("x", lx).num("y", ly);
1134            target.txt("label", label).txt("of", id.clone());
1135            continue;
1136        }
1137        let key = (nd.stroke, nd.shape, nd.fill.unwrap_or(s.card));
1138        let i = match boxes.iter().position(|(k, _)| *k == key) {
1139            Some(i) => i,
1140            None => {
1141                boxes.push((key, Frame::default()));
1142                boxes.len() - 1
1143            }
1144        };
1145        let f = &mut boxes[i].1;
1146        if nd.shape == NodeShape::DoubleBox {
1147            let o = by_colour(&mut outlines, nd.stroke);
1148            o.num("x0", x + 3.5)
1149                .num("x1", x + pn.w - 3.5)
1150                .num("y0", y + 3.5)
1151                .num("y1", y + pn.h - 3.5);
1152            o.txt("of", id.clone());
1153        }
1154        f.num("x0", x)
1155            .num("x1", x + pn.w)
1156            .num("y0", y)
1157            .num("y1", y + pn.h);
1158        f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
1159
1160        if let Some(a) = nd.accent {
1161            accent.num("x0", x + 1.5).num("x1", x + 4.5);
1162            accent
1163                .num("y0", y + 6.0)
1164                .num("y1", y + 6.0 + (pn.h - 12.0).max(4.0));
1165            accent.txt("fill", hex(a)).txt("of", id.clone());
1166        }
1167        let mut base = y + BOX_PAD_Y + 12.0;
1168        for line in &nd.lines {
1169            lines
1170                .num("x", pn.cx)
1171                .num("y", mid_of_baseline(base, LABEL_PX));
1172            lines.txt("label", line.clone()).txt("of", id.clone());
1173            base += LINE_H;
1174        }
1175        if let Some(fv) = &nd.value {
1176            values
1177                .num("x", pn.cx)
1178                .num("y", mid_of_baseline(base, VALUE_PX));
1179            values.txt("label", fv.clone()).txt("of", id.clone());
1180            base += LINE_H;
1181        }
1182        if let Some((b, dot)) = &nd.badge {
1183            let bw = text_w(b, BADGE_PX, false) + 20.0;
1184            let (bx, by) = (pn.cx - bw / 2.0, base - 9.0);
1185            let f = by_colour(&mut badges, *dot);
1186            f.num("x0", bx)
1187                .num("x1", bx + bw)
1188                .num("y0", by)
1189                .num("y1", by + 16.0);
1190            f.txt("of", id.clone());
1191            dots.num("x", bx + 9.0).num("y", by + 8.0);
1192            dots.txt("col", hex(*dot)).txt("of", id.clone());
1193            btext.num("x", bx + 15.0).num("y", by + 8.0);
1194            btext.txt("label", b.clone()).txt("of", id.clone());
1195            base += 20.0;
1196        }
1197        // the states, a row each: name, the prior's faint bar with a tick
1198        // where it ends, the bar, the probability
1199        if let Some((rows, colour)) = nd.states.as_ref().filter(|(r, _)| !r.is_empty()) {
1200            let names = rows
1201                .iter()
1202                .map(|r| text_w(&state_name(&r.name), SMALL_PX, true))
1203                .fold(0.0, f64::max);
1204            let bx = x + BOX_PAD_X + names + STATE_GAP;
1205            // the bar takes what the box leaves it, at most its full length
1206            let bw = (pn.w - 2.0 * BOX_PAD_X - names - 2.0 * STATE_GAP - STATE_TEXT_W)
1207                .clamp(16.0, STATE_BAR_W);
1208            base += 4.0;
1209            for r in rows {
1210                let cy = mid_of_baseline(base, SMALL_PX);
1211                let f = if r.observed { &mut sseen } else { &mut sname };
1212                f.num("x", x + BOX_PAD_X).num("y", cy);
1213                f.txt("label", state_name(&r.name)).txt("of", id.clone());
1214                if let Some(q) = r.prior {
1215                    let q = if q.is_finite() {
1216                        q.clamp(0.0, 1.0)
1217                    } else {
1218                        0.0
1219                    };
1220                    sprior
1221                        .num("x0", bx)
1222                        .num("x1", bx + bw * q)
1223                        .num("y0", cy - 5.0)
1224                        .num("y1", cy + 5.0);
1225                    sprior.txt("fill", hex(s.muted)).txt("of", id.clone());
1226                    stick
1227                        .num("x0", bx + bw * q - 0.75)
1228                        .num("x1", bx + bw * q + 0.75)
1229                        .num("y0", cy - 6.0)
1230                        .num("y1", cy + 6.0);
1231                    stick.txt("fill", hex(s.muted)).txt("of", id.clone());
1232                }
1233                let p = if r.p.is_finite() {
1234                    r.p.clamp(0.0, 1.0)
1235                } else {
1236                    0.0
1237                };
1238                sbar.num("x0", bx)
1239                    .num("x1", bx + bw * p)
1240                    .num("y0", cy - 3.5)
1241                    .num("y1", cy + 3.5);
1242                sbar.txt("fill", hex(*colour)).txt("of", id.clone());
1243                stext.num("x", bx + bw + STATE_GAP).num("y", cy);
1244                stext.txt("label", r.text.clone()).txt("of", id.clone());
1245                base += STATE_H;
1246            }
1247        }
1248        // a mini trend along the bottom of the box
1249        if let Some((values, colour)) = nd.spark.as_ref().filter(|(v, _)| v.len() >= 2) {
1250            let (lo, hi) = values
1251                .iter()
1252                .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
1253                    (a.min(v), b.max(v))
1254                });
1255            let rng = if hi > lo { hi - lo } else { 1.0 };
1256            let (sx0, sw) = (x + BOX_PAD_X, pn.w - 2.0 * BOX_PAD_X);
1257            let (top, sh) = (base - 8.0, SPARK_H - 8.0);
1258            let last = values.len() - 1;
1259            let col = hex(*colour);
1260            for (i, &sv) in values.iter().enumerate() {
1261                let (px, py) = (
1262                    sx0 + sw * i as f64 / last as f64,
1263                    top + sh - (sv - lo) / rng * sh,
1264                );
1265                spark.num("x", px).num("y", py).txt("g", id.clone());
1266                spark.txt("col", col.clone()).txt("of", id.clone());
1267                if i == last {
1268                    ends.num("x", px).num("y", py);
1269                    ends.txt("col", col.clone()).txt("of", id.clone());
1270                }
1271            }
1272        }
1273    }
1274    for ((stroke, shape, fill), mut f) in boxes {
1275        let aes = f.attr_aes(rect_aes().tooltip("tip"));
1276        let cls = match shape {
1277            NodeShape::Box => class("node"),
1278            _ => format!(
1279                "{} {}",
1280                class("node"),
1281                class(&format!("node-{}", shape.name()))
1282            ),
1283        };
1284        plot = plot
1285            .geom_rect_with(
1286                GeomRect {
1287                    fill,
1288                    color: stroke,
1289                    alpha: 1.0,
1290                    line_width: 1.2,
1291                    ..Default::default()
1292                }
1293                .with_radius(if shape == NodeShape::Rect { 0.0 } else { 8.0 }),
1294            )
1295            .layer_data(f.take(h))
1296            .layer_aes(aes)
1297            .layer_svg_attr("class", cls);
1298    }
1299    if !hits.is_empty() {
1300        // a diamond's hit target: its bounding box, invisible
1301        let aes = hits.attr_aes(rect_aes().tooltip("tip"));
1302        let cls = format!("{} {}", class("node"), class("node-diamond"));
1303        plot = plot
1304            .geom_rect_with(GeomRect {
1305                fill: s.card,
1306                alpha: 0.0,
1307                line_width: 0.0,
1308                ..Default::default()
1309            })
1310            .layer_data(hits.take(h))
1311            .layer_aes(aes)
1312            .layer_svg_attr("class", cls);
1313    }
1314    for ((shape, r, stroke), mut f) in shaped {
1315        let aes = f.attr_aes(rect_aes().fill("fill").tooltip("tip"));
1316        let cls = format!(
1317            "{} {}",
1318            class("node"),
1319            class(&format!("node-{}", shape.name()))
1320        );
1321        plot = plot
1322            .geom_rect_with(
1323                GeomRect {
1324                    color: stroke,
1325                    alpha: 1.0,
1326                    line_width: if shape == NodeShape::Text { 0.0 } else { 1.2 },
1327                    ..Default::default()
1328                }
1329                .with_radius(f64::from_bits(r)),
1330            )
1331            .layer_data(f.take(h))
1332            .layer_aes(aes)
1333            .layer_svg_attr("class", cls);
1334    }
1335    if !priors.is_empty() {
1336        plot = plot
1337            .geom_path_with(GeomPath {
1338                alpha: 0.7,
1339                ..GeomPath::default().linewidth(1.0)
1340            })
1341            .layer_data(priors.take(h))
1342            .layer_aes(
1343                Aes::new()
1344                    .x("x")
1345                    .y("y")
1346                    .group("g")
1347                    .color("col")
1348                    .linetype("lt")
1349                    .group_wrap("of", "of"),
1350            )
1351            .decorative()
1352            .layer_svg_attrs(inert)
1353            .layer_svg_attr("class", class("node-prior"));
1354    }
1355    if !beliefs.is_empty() {
1356        plot = plot
1357            .geom_polygon_with(GeomPolygon {
1358                alpha: 0.45,
1359                line_width: 0.0,
1360                ..Default::default()
1361            })
1362            .layer_data(beliefs.take(h))
1363            .layer_aes(
1364                Aes::new()
1365                    .x("x")
1366                    .y("y")
1367                    .group("g")
1368                    .fill("fill")
1369                    .group_wrap("of", "of"),
1370            )
1371            .decorative()
1372            .layer_svg_attrs(inert)
1373            .layer_svg_attr("class", class("node-belief"));
1374    }
1375    // everything below: dims / lights with its node (`data-of`), inert
1376    let of = |a: Aes| a.group_wrap("of", "of");
1377    if !accent.is_empty() {
1378        plot = plot
1379            .geom_rect_with(
1380                GeomRect {
1381                    alpha: 1.0,
1382                    line_width: 0.0,
1383                    ..Default::default()
1384                }
1385                .with_radius(1.5),
1386            )
1387            .layer_data(accent.take(h))
1388            .layer_aes(of(rect_aes().fill("fill")))
1389            .decorative()
1390            .layer_svg_attrs(inert);
1391    }
1392    for (stroke, mut f) in outlines {
1393        plot = plot
1394            .geom_rect_with(
1395                GeomRect {
1396                    fill: s.card,
1397                    color: stroke,
1398                    alpha: 0.0,
1399                    line_width: 1.0,
1400                    ..Default::default()
1401                }
1402                .with_radius(5.5),
1403            )
1404            .layer_data(f.take(h))
1405            .layer_aes(of(rect_aes()))
1406            .decorative()
1407            .layer_svg_attrs(inert)
1408            .layer_svg_attr("class", class("node-outline"));
1409    }
1410    for (stroke, mut f) in diamonds {
1411        plot = plot
1412            .geom_polygon_with(GeomPolygon {
1413                color: stroke,
1414                alpha: 1.0,
1415                line_width: 1.2,
1416                ..Default::default()
1417            })
1418            .layer_data(f.take(h))
1419            .layer_aes(of(Aes::new().x("x").y("y").group("g").fill("fill")))
1420            .decorative()
1421            .layer_svg_attrs(inert)
1422            .layer_svg_attr("class", class("node-diamond-mark"));
1423    }
1424    for (mut f, alpha, cls) in [
1425        (sprior, 0.28, "node-state-prior"),
1426        (sbar, 0.9, "node-state-bar"),
1427        (stick, 0.9, "node-state-prior"),
1428    ] {
1429        if f.is_empty() {
1430            continue;
1431        }
1432        plot = plot
1433            .geom_rect_with(GeomRect {
1434                alpha,
1435                line_width: 0.0,
1436                ..Default::default()
1437            })
1438            .layer_data(f.take(h))
1439            .layer_aes(of(rect_aes().fill("fill")))
1440            .decorative()
1441            .layer_svg_attrs(inert)
1442            .layer_svg_attr("class", class(cls));
1443    }
1444    for (mut f, colour, face, cls) in [
1445        (sname, s.ink, FontFace::Plain, "node-state"),
1446        (sseen, s.heading, FontFace::Bold, "node-state"),
1447        (stext, s.muted, FontFace::Plain, "node-state-value"),
1448    ] {
1449        if f.is_empty() {
1450            continue;
1451        }
1452        plot = plot
1453            .geom_text_with(GeomText {
1454                size: SMALL_PX,
1455                color: colour,
1456                fontface: face,
1457                hjust: 0.0,
1458                ..Default::default()
1459            })
1460            .layer_data(f.take(h))
1461            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1462            .layer_svg_attrs(inert)
1463            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class(cls))]);
1464    }
1465    for (mut f, size, colour, cls, math, hjust) in [
1466        (lines, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1467        (values, VALUE_PX, s.ink, class("node-value"), false, 0.5),
1468        (inside, LABEL_PX, s.heading, class("node-label"), true, 0.5),
1469        (texts, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1470        (inverse, LABEL_PX, s.card, class("node-label"), true, 0.5),
1471        (above, SMALL_PX, s.muted, class("node-label"), true, 0.5),
1472        (beside, LABEL_PX, s.heading, class("node-label"), true, 0.0),
1473        (
1474            glyphs,
1475            GLYPH_PX,
1476            s.glyph_ink.unwrap_or(s.heading),
1477            class("node-label"),
1478            true,
1479            0.5,
1480        ),
1481    ] {
1482        if f.is_empty() {
1483            continue;
1484        }
1485        // a factor graph's labels as mathematics: the math font, italic
1486        let (fontfamily, fontface, size) = match s.math_font.as_ref().filter(|_| math) {
1487            Some(family) => (family.clone(), FontFace::Italic, size + 2.0),
1488            None => (String::new(), FontFace::Bold, size),
1489        };
1490        plot = plot
1491            .geom_text_with(GeomText {
1492                size,
1493                color: colour,
1494                fontface,
1495                fontfamily,
1496                hjust,
1497                ..Default::default()
1498            })
1499            .layer_data(f.take(h))
1500            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1501            .layer_svg_attrs(inert)
1502            .layer_svg_attrs([("aria-hidden", "true"), ("class", cls.as_str())]);
1503    }
1504    for (dot, mut f) in badges {
1505        plot = plot
1506            .geom_rect_with(
1507                GeomRect {
1508                    fill: s.card,
1509                    color: dot,
1510                    alpha: 0.0,
1511                    line_width: 1.0,
1512                    ..Default::default()
1513                }
1514                .with_radius(8.0),
1515            )
1516            .layer_data(f.take(h))
1517            .layer_aes(of(rect_aes()))
1518            .decorative()
1519            .layer_svg_attrs(inert);
1520    }
1521    for (mut f, size) in [(dots, 3.0), (ends, 2.2)] {
1522        if f.is_empty() {
1523            continue;
1524        }
1525        plot = plot
1526            .geom_point_with(GeomPoint {
1527                size,
1528                ..Default::default()
1529            })
1530            .layer_data(f.take(h))
1531            .layer_aes(of(Aes::new().x("x").y("y").color("col")))
1532            .decorative()
1533            .layer_svg_attrs(inert);
1534    }
1535    if !btext.is_empty() {
1536        plot = plot
1537            .geom_text_with(GeomText {
1538                size: BADGE_PX,
1539                color: s.ink,
1540                hjust: 0.0,
1541                ..Default::default()
1542            })
1543            .layer_data(btext.take(h))
1544            .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1545            .layer_svg_attrs(inert)
1546            .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-badge"))]);
1547    }
1548    if !spark.is_empty() {
1549        plot = plot
1550            .geom_path_with(GeomPath::default().linewidth(1.4))
1551            .layer_data(spark.take(h))
1552            .layer_aes(of(Aes::new().x("x").y("y").group("g").color("col")))
1553            .decorative()
1554            .layer_svg_attrs(inert)
1555            .layer_svg_attr("class", class("node-spark"));
1556    }
1557    plot
1558}
1559
1560#[cfg(test)]
1561mod tests {
1562    use super::*;
1563    use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
1564
1565    #[test]
1566    fn an_end_label_sits_beside_its_box() {
1567        // anofox-visualization#1238: an interface name near a factor is
1568        // clear of the factor's box, not centred on its border
1569        let hw = edge_label_width("variance") / 2.0;
1570        let (x, y) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "variance", 0.8);
1571        assert!(
1572            (x - (100.0 - hw - crate::graph_layout::LABEL_CLEAR)).abs() < 1e-9 && y == 0.0,
1573            "{x} {y}"
1574        );
1575        let (x, _) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "mean", 0.2);
1576        assert!(
1577            x - edge_label_width("mean") / 2.0 >= crate::graph_layout::LABEL_CLEAR - 1e-9,
1578            "{x}"
1579        );
1580        // a vertical edge: beside the line, below the box it leaves
1581        let (x, y) = end_label_at(&[(50.0, 0.0), (50.0, 40.0)], "out", 0.2);
1582        assert!(
1583            x - edge_label_width("out") / 2.0 > 50.0 && y > 0.0,
1584            "{x} {y}"
1585        );
1586        // a short edge: the label stays on it
1587        let (x, _) = end_label_at(&[(0.0, 0.0), (20.0, 0.0)], "variance", 0.8);
1588        assert!((x - 10.0).abs() < 1e-9, "{x}");
1589    }
1590
1591    /// A Bayesian network's nodes (Netica / GeNIe style): a chance node's
1592    /// states as rows of bars with the prior behind them, an observed node
1593    /// shaded with its state in bold, a decision as a square-cornered box,
1594    /// a utility as a diamond (an invisible box as its hit target), a
1595    /// deterministic node with a double outline.
1596    #[test]
1597    fn draws_bayes_net_nodes_with_state_bars() {
1598        let states = vec!["yes".to_string(), "no".to_string()];
1599        let spec = [
1600            ("Rain", NodeShape::Box),
1601            ("Wet grass", NodeShape::Box),
1602            ("Water?", NodeShape::Rect),
1603            ("Cost", NodeShape::Diamond),
1604            ("Either", NodeShape::DoubleBox),
1605        ];
1606        let sizes: Vec<NodeBox> = spec
1607            .iter()
1608            .map(|(l, sh)| match sh {
1609                NodeShape::Diamond => diamond_box(l, Some("-12.5")),
1610                _ => states_box(l, None, None, &states),
1611            })
1612            .collect();
1613        // two state rows below the label; room for the bars
1614        let plain = node_box("Rain", None, None, false);
1615        assert_eq!(sizes[0].h, plain.h + 4.0 + 2.0 * STATE_H);
1616        assert!(sizes[0].w >= 2.0 * BOX_PAD_X + STATE_BAR_W + STATE_TEXT_W);
1617        assert!(sizes[3].w > sizes[3].h, "a diamond wider than tall");
1618        let gnodes: Vec<GraphNode> = sizes
1619            .iter()
1620            .map(|b| GraphNode {
1621                w: b.w,
1622                h: b.h,
1623                ..Default::default()
1624            })
1625            .collect();
1626        let links = [(0, 1), (2, 1), (1, 3), (0, 4)];
1627        let gedges: Vec<GraphEdge> = links
1628            .iter()
1629            .map(|&(a, b)| GraphEdge {
1630                from: a,
1631                to: b,
1632                label_w: None,
1633            })
1634            .collect();
1635        let params = LayeredParams {
1636            direction: crate::graph_layout::Direction::TopBottom,
1637            ..Default::default()
1638        };
1639        let l = layered(&gnodes, &gedges, &params);
1640        let bar = |name: &str, p: f64, prior: Option<f64>, observed: bool| StateBar {
1641            name: name.to_string(),
1642            p,
1643            prior,
1644            text: format!("{:.0}%", p * 100.0),
1645            observed,
1646        };
1647        let nodes: Vec<DrawNode> = spec
1648            .iter()
1649            .zip(&sizes)
1650            .enumerate()
1651            .map(|(i, ((_, shape), b))| DrawNode {
1652                id: format!("n{i}"),
1653                shape: *shape,
1654                lines: b.lines.clone(),
1655                value: (*shape == NodeShape::Diamond).then(|| "-12.5".to_string()),
1656                stroke: (60, 60, 60),
1657                tooltip: b.lines.join(" "),
1658                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
1659                states: (*shape != NodeShape::Diamond).then(|| {
1660                    if i == 1 {
1661                        (
1662                            vec![
1663                                bar("yes", 1.0, Some(0.65), true),
1664                                bar("no", 0.0, Some(0.35), false),
1665                            ],
1666                            (37, 99, 235),
1667                        )
1668                    } else {
1669                        (
1670                            vec![
1671                                bar("yes", 0.3, Some(0.5), false),
1672                                bar("no", 0.7, Some(0.5), false),
1673                            ],
1674                            (37, 99, 235),
1675                        )
1676                    }
1677                }),
1678                fill: (i == 1).then_some((230, 236, 250)),
1679                ..Default::default()
1680            })
1681            .collect();
1682        let edges: Vec<DrawEdge> = links
1683            .iter()
1684            .map(|&(a, b)| DrawEdge {
1685                colour: (90, 90, 90),
1686                width: 1.6,
1687                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
1688                ..Default::default()
1689            })
1690            .collect();
1691        let svg = draw(
1692            &l,
1693            &[],
1694            &[],
1695            &nodes,
1696            &edges,
1697            &GraphStyle::default(),
1698            crate::theme::presets::theme_void(),
1699        )
1700        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1701        .unwrap();
1702        // one hit target per node, classed by shape; directed edges
1703        assert_eq!(svg.matches("data-node=").count(), spec.len());
1704        for c in [
1705            "gg-graph-node-rect",
1706            "gg-graph-node-diamond",
1707            "gg-graph-node-double-box",
1708        ] {
1709            assert!(svg.contains(c), "{c}");
1710        }
1711        assert!(
1712            svg.contains("gg-graph-node-diamond-mark") && svg.contains("gg-graph-node-outline")
1713        );
1714        assert!(
1715            svg.contains("data-part=\"arrow\""),
1716            "arrowheads at the child"
1717        );
1718        // state rows: four bars, their priors, the names and probabilities
1719        assert!(
1720            svg.contains("gg-graph-node-state-bar") && svg.contains("gg-graph-node-state-prior")
1721        );
1722        assert!(svg.contains(">30%<") && svg.contains(">100%<"));
1723        // the observed node shaded, its observed state in bold
1724        assert!(svg.contains("fill=\"#E6ECFA\""), "shaded");
1725        assert!(
1726            svg.match_indices(">yes</text>")
1727                .any(|(i, _)| svg[svg[..i].rfind("<text").unwrap()..i].contains("bold")),
1728            "the observed state in bold"
1729        );
1730        // the diamond's value inside it
1731        assert!(svg.contains(">-12.5<"));
1732        // a plain box keeps its round corners and the plain class
1733        let plain = svg
1734            .split("<rect")
1735            .find(|r| r.contains("data-node=\"n0\""))
1736            .unwrap();
1737        assert!(plain.contains("gg-graph-node\""), "{plain}");
1738    }
1739
1740    #[test]
1741    fn wraps_long_labels_in_three_lines() {
1742        let l = wrap(
1743            "Recommend replenishment orders for every store and every week of the coming year",
1744            152.0,
1745        );
1746        assert_eq!(l.len(), 3);
1747        assert!(l[2].ends_with('…'));
1748        assert_eq!(wrap("Ingest", 152.0), ["Ingest"]);
1749    }
1750
1751    /// No ellipsis while the label fits; breaks at word boundaries and
1752    /// after `/` / `-`, never mid-word when there is a separator.
1753    #[test]
1754    fn wraps_at_word_boundaries() {
1755        let max = BOX_MAX_W - 2.0 * BOX_PAD_X;
1756        for label in [
1757            "duckdb/community-extensions (descriptions)",
1758            "Locked DuckDB server (anofox-visualization)",
1759            "Parquet snapshot (downloads, extensions)",
1760            "fetch.sh: download, file by ISO week, merge",
1761        ] {
1762            let l = wrap(label, max);
1763            assert!(l.len() <= MAX_LINES, "{l:?}");
1764            assert!(!l.iter().any(|x| x.contains('…')), "{label}: {l:?}");
1765            // every line ends at a space or after a separator
1766            let joined: String = l.concat();
1767            assert_eq!(joined.replace(' ', ""), label.replace(' ', ""), "{l:?}");
1768            for w in l.windows(2) {
1769                let end = w[0].chars().last().unwrap();
1770                let next = w[1].chars().next().unwrap();
1771                let at_space = label.contains(&format!(
1772                    "{} {}",
1773                    w[0].split(' ').next_back().unwrap(),
1774                    w[1].split(' ').next().unwrap()
1775                ));
1776                assert!(
1777                    at_space || matches!(end, '/' | '-' | '_' | '.' | ','),
1778                    "{l:?} breaks at {end}{next}"
1779                );
1780            }
1781        }
1782        assert_eq!(
1783            wrap("duckdb/community-extensions (descriptions)", max),
1784            ["duckdb/community-", "extensions", "(descriptions)"]
1785        );
1786    }
1787
1788    #[test]
1789    fn node_box_grows_with_its_contents() {
1790        let plain = node_box("Ingest", None, None, false);
1791        assert_eq!((plain.w, plain.h), (BOX_MIN_W, 2.0 * BOX_PAD_Y + LINE_H));
1792        let full = node_box("Ingest", Some("1,240"), Some("late"), true);
1793        assert_eq!(full.h, plain.h + LINE_H + 20.0 + SPARK_H);
1794        assert!(full.w >= 110.0 + 2.0 * BOX_PAD_X);
1795        let long = node_box(&"word ".repeat(40), None, None, false);
1796        assert!(long.w <= BOX_MAX_W && long.lines.len() == MAX_LINES);
1797    }
1798
1799    /// An edge label a node box would cover moves along the edge.
1800    #[test]
1801    fn edge_label_keeps_clear_of_nodes() {
1802        let node = |cx: f64, w: f64| PlacedNode {
1803            cx,
1804            cy: 0.0,
1805            w,
1806            h: 40.0,
1807            layer: 0,
1808            order: 0,
1809        };
1810        let pts = [(0.0, 0.0), (300.0, 0.0)];
1811        // nothing in the way: the midpoint
1812        assert_eq!(edge_label_at(&pts, "spikes flagged", &[]), (150.0, 0.0));
1813        // a box over the middle: somewhere else along the edge, clear of it
1814        let nodes = [node(150.0, 60.0)];
1815        let (x, _) = edge_label_at(&pts, "spikes flagged", &nodes);
1816        let hw = edge_label_width("spikes flagged") / 2.0 + 3.0;
1817        assert!((x - 150.0).abs() >= hw + 30.0, "{x}");
1818        assert_eq!(point_at(&pts, 0.25), (75.0, 0.0));
1819    }
1820
1821    #[test]
1822    fn flow_width_is_area_true_and_rounded() {
1823        assert_eq!(flow_width(None, 10.0, EdgeLine::Solid), 1.6);
1824        assert_eq!(flow_width(Some(10.0), 10.0, EdgeLine::Solid), 7.0);
1825        assert_eq!(flow_width(Some(2.5), 10.0, EdgeLine::Solid), 4.2);
1826        assert_eq!(flow_width(None, 10.0, EdgeLine::Dots), 3.0);
1827    }
1828
1829    /// Two lanes, three boxes, a labelled edge: the marks carry the
1830    /// caller's attributes and classes, a node's contents sit in its
1831    /// `data-of` group, and the box itself (the hit target) stays outside.
1832    #[test]
1833    fn draws_marks_with_attributes_and_groups() {
1834        let labels = ["Ingest", "Model", "Publish"];
1835        let boxes: Vec<NodeBox> = labels
1836            .iter()
1837            .enumerate()
1838            .map(|(i, l)| node_box(l, (i == 1).then_some("42"), None, i == 2))
1839            .collect();
1840        let gnodes: Vec<GraphNode> = boxes
1841            .iter()
1842            .enumerate()
1843            .map(|(i, b)| GraphNode {
1844                w: b.w,
1845                h: b.h,
1846                lane: Some(i % 2),
1847                ..Default::default()
1848            })
1849            .collect();
1850        let gedges = [
1851            GraphEdge {
1852                from: 0,
1853                to: 1,
1854                label_w: Some(edge_label_width("rows")),
1855            },
1856            GraphEdge {
1857                from: 1,
1858                to: 2,
1859                label_w: None,
1860            },
1861        ];
1862        let params = LayeredParams {
1863            lanes: 2,
1864            ..Default::default()
1865        };
1866        let l = layered(&gnodes, &gedges, &params);
1867        let nodes: Vec<DrawNode> = labels
1868            .iter()
1869            .zip(&boxes)
1870            .enumerate()
1871            .map(|(i, (id, b))| DrawNode {
1872                id: id.to_string(),
1873                lines: b.lines.clone(),
1874                value: (i == 1).then(|| "42".to_string()),
1875                stroke: (90, 90, 90),
1876                accent: (i == 0).then_some((200, 0, 0)),
1877                spark: (i == 2).then(|| (vec![1.0, 3.0, 2.0], (0, 0, 200))),
1878                tooltip: format!("{id}!"),
1879                attrs: vec![
1880                    ("node".to_string(), Some(id.to_string())),
1881                    ("value".to_string(), (i == 1).then(|| "42".to_string())),
1882                ],
1883                ..Default::default()
1884            })
1885            .collect();
1886        let edges: Vec<DrawEdge> = [(0, 1), (1, 2)]
1887            .iter()
1888            .map(|&(a, b)| DrawEdge {
1889                colour: (100, 100, 100),
1890                width: flow_width(None, 0.0, EdgeLine::Solid),
1891                line: if a == 0 {
1892                    EdgeLine::Solid
1893                } else {
1894                    EdgeLine::Dashed
1895                },
1896                class: (a == 1).then(|| "flowing".to_string()),
1897                tooltip: format!("{} → {}", labels[a], labels[b]),
1898                label: (a == 0).then(|| "rows".to_string()),
1899                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
1900                label_attrs: vec![("from".to_string(), Some(labels[a].to_string()))],
1901                ..Default::default()
1902            })
1903            .collect();
1904        let lanes = ["Left".to_string(), "Right".to_string()];
1905        let svg = draw(
1906            &l,
1907            &lanes,
1908            &[],
1909            &nodes,
1910            &edges,
1911            &GraphStyle::default(),
1912            crate::theme::presets::theme_void(),
1913        )
1914        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1915        .unwrap();
1916        // start tags, each with whether it sits inside a `data-of` group
1917        let mut tags: Vec<(&str, bool)> = Vec::new();
1918        let mut stack: Vec<bool> = Vec::new();
1919        for part in svg.split('<').skip(1) {
1920            let tag = &part[..part.find('>').unwrap()];
1921            if tag.starts_with('/') {
1922                stack.pop();
1923                continue;
1924            }
1925            let inside = stack.iter().any(|&g| g);
1926            tags.push((tag, inside));
1927            if !tag.ends_with('/') {
1928                stack.push(tag.contains("data-of="));
1929            }
1930        }
1931        let attr = |tag: &str, name: &str| {
1932            let key = format!(" {name}=\"");
1933            tag.find(&key).map(|i| {
1934                let rest = &tag[i + key.len()..];
1935                rest[..rest.find('"').unwrap()].to_string()
1936            })
1937        };
1938        // boxes: one per node, outside the groups, an NA attribute left off
1939        let boxes: Vec<_> = tags
1940            .iter()
1941            .filter(|(t, _)| t.contains("data-node="))
1942            .collect();
1943        assert_eq!(boxes.len(), 3);
1944        for (b, inside) in &boxes {
1945            assert!(!inside, "{b}");
1946            let id = attr(b, "data-node").unwrap();
1947            assert_eq!(attr(b, "data-value").is_some(), id == "Model", "{id}");
1948        }
1949        // edges: the caller's class on a path; the label's attributes
1950        assert!(tags.iter().any(|(t, _)| t.contains("data-edge=\"1&gt;2\"")
1951            && attr(t, "class").is_some_and(|c| c.contains("flowing"))));
1952        assert!(tags
1953            .iter()
1954            .any(|(t, _)| attr(t, "data-from").as_deref() == Some("Ingest")));
1955        assert!(svg.contains(" gg-graph-node\"") && svg.contains("gg-graph-edge-label"));
1956        // node contents grouped by node; lanes drawn with their names
1957        for id in labels {
1958            assert!(svg.contains(&format!("data-of=\"{id}\"")), "{id}");
1959        }
1960        assert!(svg.contains("data-lane=\"Right\""));
1961        assert!(svg.contains(">Left<") && svg.contains(">42<"));
1962    }
1963
1964    /// Forney style (#1172): an observation as a terminal square, its label
1965    /// beside it; a variable as a labelled edge, its name in the math font.
1966    #[test]
1967    fn forney_terminals_and_variable_edges() {
1968        use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
1969        let spec = [
1970            ("Cat", NodeShape::Glyph),
1971            ("T", NodeShape::Glyph),
1972            ("x₁", NodeShape::Terminal),
1973        ];
1974        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
1975        assert_eq!((sizes[2].w, sizes[2].h), (TERMINAL, TERMINAL));
1976        let gnodes: Vec<GraphNode> = sizes
1977            .iter()
1978            .map(|b| GraphNode {
1979                w: b.w,
1980                h: b.h,
1981                ..Default::default()
1982            })
1983            .collect();
1984        let gedges = vec![
1985            GraphEdge {
1986                from: 0,
1987                to: 1,
1988                label_w: None,
1989            },
1990            GraphEdge {
1991                from: 1,
1992                to: 2,
1993                label_w: None,
1994            },
1995        ];
1996        let l = layered(&gnodes, &gedges, &LayeredParams::default());
1997        let nodes: Vec<DrawNode> = spec
1998            .iter()
1999            .zip(&sizes)
2000            .enumerate()
2001            .map(|(i, ((_, shape), b))| DrawNode {
2002                id: format!("n{i}"),
2003                shape: *shape,
2004                lines: b.lines.clone(),
2005                stroke: (13, 148, 136),
2006                tooltip: b.lines.join(" "),
2007                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2008                // the observation flagged: filled in its accent
2009                accent: (*shape == NodeShape::Terminal).then_some((217, 119, 6)),
2010                ..Default::default()
2011            })
2012            .collect();
2013        let edges = vec![
2014            // the variable s₀ between the two factors
2015            DrawEdge {
2016                colour: (13, 148, 136),
2017                width: 1.2,
2018                undirected: true,
2019                label: Some("s₀".to_string()),
2020                label_math: true,
2021                ..Default::default()
2022            },
2023            DrawEdge {
2024                colour: (13, 148, 136),
2025                width: 1.2,
2026                undirected: true,
2027                ..Default::default()
2028            },
2029        ];
2030        let render = |style: &GraphStyle| {
2031            draw(
2032                &l,
2033                &[],
2034                &[],
2035                &nodes,
2036                &edges,
2037                style,
2038                crate::theme::presets::theme_void(),
2039            )
2040            .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32 + 40, l.h.ceil() as u32)
2041            .unwrap()
2042        };
2043        let math = GraphStyle {
2044            math_font: Some("STIX Two Math, serif".to_string()),
2045            ..GraphStyle::default()
2046        };
2047        let svg = render(&math);
2048        let el = |text: &str| {
2049            let at = svg
2050                .find(&format!(">{text}</text>"))
2051                .unwrap_or_else(|| panic!("{text}"));
2052            svg[svg[..at].rfind('<').unwrap()..at].to_string()
2053        };
2054        // the terminal: a filled square, its label starting beside it
2055        assert!(svg.contains("gg-graph-node-terminal"), "terminal mark");
2056        assert!(
2057            svg.contains("fill=\"#D97706\""),
2058            "the terminal in its accent"
2059        );
2060        let x1 = el("x₁");
2061        assert!(
2062            x1.contains("text-anchor=\"start\"") && x1.contains("italic"),
2063            "{x1}"
2064        );
2065        let t = &l.nodes[2];
2066        let lx: f64 = x1
2067            .split("x=\"")
2068            .nth(1)
2069            .unwrap()
2070            .split('"')
2071            .next()
2072            .unwrap()
2073            .parse()
2074            .unwrap();
2075        assert!(
2076            lx > t.cx + t.w / 2.0,
2077            "the label right of the square: {lx} vs {}",
2078            t.cx
2079        );
2080        // the variable's edge label in the math font
2081        let s0 = el("s₀");
2082        assert!(
2083            s0.contains("STIX Two Math") && s0.contains("italic"),
2084            "{s0}"
2085        );
2086        // without a math font: a plain edge label
2087        let plain = render(&GraphStyle::default());
2088        let at = plain.find(">s₀</text>").unwrap();
2089        assert!(!plain[plain[..at].rfind('<').unwrap()..at].contains("italic"));
2090    }
2091
2092    /// A coin toss as a Forney-style factor graph: a Beta prior box, the
2093    /// parameter's circle, an equality node, Bernoulli boxes and observed
2094    /// circles in a plate; undirected edges with interface names near the
2095    /// factor.
2096    #[test]
2097    fn draws_a_factor_graph_with_shapes_and_a_plate() {
2098        let n = 3;
2099        // (label, shape)
2100        let mut spec = vec![
2101            ("Beta", NodeShape::Box),
2102            ("θ", NodeShape::Circle),
2103            ("=", NodeShape::Square),
2104        ];
2105        for _ in 0..n {
2106            spec.push(("Ber", NodeShape::Box));
2107        }
2108        for _ in 0..n {
2109            spec.push(("y", NodeShape::FilledCircle));
2110        }
2111        spec.push(("2.0", NodeShape::Text));
2112        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
2113        // (from, to, interface)
2114        let mut links = vec![(0, 1, "out"), (1, 2, ""), (9, 0, "a")];
2115        for i in 0..n {
2116            links.push((2, 3 + i, "p"));
2117            links.push((3 + i, 3 + n + i, "out"));
2118        }
2119        let gnodes: Vec<GraphNode> = sizes
2120            .iter()
2121            .map(|b| GraphNode {
2122                w: b.w,
2123                h: b.h,
2124                ..Default::default()
2125            })
2126            .collect();
2127        let gedges: Vec<GraphEdge> = links
2128            .iter()
2129            .map(|&(a, b, _)| GraphEdge {
2130                from: a,
2131                to: b,
2132                label_w: None,
2133            })
2134            .collect();
2135        // a plate reaches past its nodes: room for it in the margin
2136        let params = LayeredParams {
2137            margin: 32.0,
2138            ..Default::default()
2139        };
2140        let l = layered(&gnodes, &gedges, &params);
2141        let nodes: Vec<DrawNode> = spec
2142            .iter()
2143            .zip(&sizes)
2144            .enumerate()
2145            .map(|(i, ((_, shape), b))| DrawNode {
2146                id: format!("n{i}"),
2147                shape: *shape,
2148                lines: b.lines.clone(),
2149                stroke: (60, 60, 60),
2150                tooltip: b.lines.join(" "),
2151                attrs: vec![("node".to_string(), Some(format!("n{i}")))],
2152                // θ's belief curve
2153                belief: (i == 1).then(|| (vec![0.0, 0.3, 1.0, 0.3, 0.0], (120, 80, 200))),
2154                // and its prior, wider
2155                prior: (i == 1).then(|| (vec![0.2, 0.4, 0.5, 0.4, 0.2], (150, 150, 150))),
2156                ..Default::default()
2157            })
2158            .collect();
2159        let edges: Vec<DrawEdge> = links
2160            .iter()
2161            .map(|&(a, b, iface)| DrawEdge {
2162                colour: (90, 90, 90),
2163                width: 1.2,
2164                undirected: true,
2165                label: (!iface.is_empty()).then(|| iface.to_string()),
2166                // the interface name near the factor
2167                label_at: Some(if spec[b].1 == NodeShape::Box {
2168                    0.8
2169                } else {
2170                    0.2
2171                }),
2172                attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
2173                ..Default::default()
2174            })
2175            .collect();
2176        let plates = [Plate {
2177            label: "i = 1..3".to_string(),
2178            nodes: (3..3 + 2 * n).collect(),
2179        }];
2180        let style = GraphStyle::default();
2181        let svg = draw(
2182            &l,
2183            &[],
2184            &plates,
2185            &nodes,
2186            &edges,
2187            &style,
2188            crate::theme::presets::theme_void(),
2189        )
2190        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2191        .unwrap();
2192        // every node is a mark, shapes classed, undirected: no arrowheads
2193        assert_eq!(svg.matches("data-node=").count(), spec.len());
2194        for shape in ["circle", "filled-circle", "square", "text"] {
2195            assert!(svg.contains(&format!("gg-graph-node-{shape}")), "{shape}");
2196        }
2197        assert!(
2198            !svg.contains("data-part=\"arrow\""),
2199            "an undirected edge has no arrowhead"
2200        );
2201        assert_eq!(svg.matches("data-edge=").count(), links.len());
2202        // θ's belief curve: a filled shape over its circle, in its group
2203        assert!(svg.contains("gg-graph-node-belief"), "belief layer");
2204        assert!(svg.contains("fill=\"#7850C8\""), "belief colour");
2205        // its prior: a dashed outline, drawn before (under) the belief
2206        let (pr, be) = (
2207            svg.find("gg-graph-node-prior").expect("prior layer"),
2208            svg.find("gg-graph-node-belief").unwrap(),
2209        );
2210        assert!(pr < be, "the prior under the belief");
2211        let mark = &svg[svg[..pr].rfind('<').unwrap()..pr];
2212        assert!(mark.contains("stroke-dasharray"), "dashed prior: {mark}");
2213        // no math font: bold sans labels
2214        assert!(!svg.contains("font-style=\"italic\""), "plain labels");
2215        // a math font: the shaped nodes' labels in it, italic; glyph colours
2216        let math = GraphStyle {
2217            math_font: Some("STIX Two Math, serif".to_string()),
2218            glyph_fill: Some((240, 247, 246)),
2219            glyph_ink: Some((13, 148, 136)),
2220            ..style.clone()
2221        };
2222        let msvg = draw(
2223            &l,
2224            &[],
2225            &plates,
2226            &nodes,
2227            &edges,
2228            &math,
2229            crate::theme::presets::theme_void(),
2230        )
2231        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2232        .unwrap();
2233        assert!(msvg.contains("STIX Two Math"), "math font");
2234        assert!(msvg.contains("font-style=\"italic\""), "italic labels");
2235        // …but a constant stays upright
2236        let two = msvg.find(">2.0<").expect("the constant 2.0");
2237        let el = &msvg[msvg[..two].rfind('<').unwrap()..two];
2238        assert!(!el.contains("italic"), "upright constant: {el}");
2239        // the plate, and its label
2240        assert!(svg.contains("data-plate=\"i = 1..3\"") && svg.contains(">i = 1..3<"));
2241        // the observed circles' dark fill
2242        assert!(svg.contains(&format!(
2243            "fill=\"{}\"",
2244            hex(style.observed_fill).to_uppercase()
2245        )));
2246        // no two nodes overlap
2247        for (i, a) in l.nodes.iter().enumerate() {
2248            for b in &l.nodes[i + 1..] {
2249                let apart = (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
2250                    || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0;
2251                assert!(apart, "overlap");
2252            }
2253        }
2254        // the circle is round: rx is half its width
2255        let c = &l.nodes[1];
2256        assert!(svg.contains(&format!("rx=\"{:.2}\"", c.w / 2.0)), "{}", c.w);
2257    }
2258
2259    /// An HMM over five slices with learned transition (A) and observation
2260    /// (B) matrices, in bands param / state / obs: the state chain is one
2261    /// straight row, each observation below its state.
2262    #[test]
2263    fn banded_hmm_keeps_the_state_chain_straight() {
2264        use crate::graph_layout::{banded, BandedParams};
2265        let t_n = 5;
2266        // (label, shape, band)
2267        let mut spec: Vec<(String, NodeShape, usize)> = vec![
2268            ("Dir".into(), NodeShape::Glyph, 0), // 0: prior on A
2269            ("A".into(), NodeShape::Square, 0),  // 1: = of A
2270            ("Dir".into(), NodeShape::Glyph, 0), // 2: prior on B
2271            ("B".into(), NodeShape::Square, 0),  // 3: = of B
2272            ("Cat".into(), NodeShape::Glyph, 1), // 4: initial state prior
2273            ("s₀".into(), NodeShape::Circle, 1), // 5
2274        ];
2275        let mut links: Vec<(usize, usize, &str)> =
2276            vec![(0, 1, "out"), (2, 3, "out"), (4, 5, "out")];
2277        let mut prev = 5;
2278        for t in 1..=t_n {
2279            let tr = spec.len();
2280            spec.push(("T".into(), NodeShape::Glyph, 1));
2281            let eq = spec.len();
2282            spec.push((format!("s{t}"), NodeShape::Square, 1));
2283            let ob = spec.len();
2284            spec.push(("T".into(), NodeShape::Glyph, 2));
2285            let x = spec.len();
2286            spec.push((format!("x{t}"), NodeShape::FilledCircle, 2));
2287            links.extend([
2288                (prev, tr, "in"),
2289                (1, tr, "a"),
2290                (tr, eq, "out"),
2291                (eq, ob, "in"),
2292                (3, ob, "a"),
2293                (ob, x, "out"),
2294            ]);
2295            prev = eq;
2296        }
2297        let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh, _)| node_size(*sh, l)).collect();
2298        let gnodes: Vec<GraphNode> = spec
2299            .iter()
2300            .zip(&sizes)
2301            .map(|((_, _, b), s)| GraphNode {
2302                w: s.w,
2303                h: s.h,
2304                lane: Some(*b),
2305                ..Default::default()
2306            })
2307            .collect();
2308        let gedges: Vec<GraphEdge> = links
2309            .iter()
2310            .map(|&(a, b, _)| GraphEdge {
2311                from: a,
2312                to: b,
2313                label_w: None,
2314            })
2315            .collect();
2316        let l = banded(
2317            &gnodes,
2318            &gedges,
2319            &BandedParams {
2320                bands: 3,
2321                margin: 32.0,
2322                ..Default::default()
2323            },
2324        );
2325        // the chain: every transition and state node on one row
2326        let chain: Vec<usize> = (0..spec.len())
2327            .filter(|&i| spec[i].2 == 1 && i != 4)
2328            .collect();
2329        let y = l.nodes[chain[0]].cy;
2330        for &i in &chain {
2331            assert_eq!(l.nodes[i].cy, y, "{} off the row", spec[i].0);
2332        }
2333        // each observation factor straight below its state's = node
2334        for t in 0..t_n {
2335            let (eq, ob) = (6 + 4 * t + 1, 6 + 4 * t + 2);
2336            assert_eq!(l.nodes[eq].cx, l.nodes[ob].cx, "slice {t}");
2337            assert!(l.nodes[ob].cy > y);
2338        }
2339        // no edge passes through a box other than its own two ends
2340        let crosses = |(x0, y0): (f64, f64), (x1, y1): (f64, f64), n: &PlacedNode| {
2341            // sampled along the segment, the box shrunk by a pixel
2342            (0..=40).any(|k| {
2343                let t = k as f64 / 40.0;
2344                let (x, y) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
2345                (x - n.cx).abs() < n.w / 2.0 - 1.0 && (y - n.cy).abs() < n.h / 2.0 - 1.0
2346            })
2347        };
2348        for (k, &(a, b, _)) in links.iter().enumerate() {
2349            for w in l.edges[k].windows(2) {
2350                for (i, n) in l.nodes.iter().enumerate() {
2351                    if i != a && i != b {
2352                        assert!(
2353                            !crosses(w[0], w[1], n),
2354                            "edge {a}->{b} crosses {}",
2355                            spec[i].0
2356                        );
2357                    }
2358                }
2359            }
2360        }
2361        // nothing overlaps
2362        for (i, a) in l.nodes.iter().enumerate() {
2363            for b in &l.nodes[i + 1..] {
2364                assert!(
2365                    (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
2366                        || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0
2367                );
2368            }
2369        }
2370        let nodes: Vec<DrawNode> = spec
2371            .iter()
2372            .zip(&sizes)
2373            .enumerate()
2374            .map(|(i, ((_, shape, _), b))| DrawNode {
2375                id: format!("n{i}"),
2376                shape: *shape,
2377                lines: b.lines.clone(),
2378                stroke: (60, 60, 60),
2379                ..Default::default()
2380            })
2381            .collect();
2382        let edges: Vec<DrawEdge> = links
2383            .iter()
2384            .map(|&(_, b, iface)| DrawEdge {
2385                colour: (90, 90, 90),
2386                width: 1.2,
2387                undirected: true,
2388                label: Some(iface.to_string()),
2389                label_at: Some(if spec[b].1 == NodeShape::Glyph {
2390                    0.8
2391                } else {
2392                    0.2
2393                }),
2394                ..Default::default()
2395            })
2396            .collect();
2397        let lanes = ["param".to_string(), "state".to_string(), "obs".to_string()];
2398        let svg = draw(
2399            &l,
2400            &lanes,
2401            &[],
2402            &nodes,
2403            &edges,
2404            &GraphStyle::default(),
2405            crate::theme::presets::theme_void(),
2406        )
2407        .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
2408        .unwrap();
2409        if let Ok(path) = std::env::var("GGPLOT_GRAPH_SVG") {
2410            std::fs::write(path, &svg).unwrap();
2411        }
2412        assert_eq!(svg.matches("data-lane=").count(), 3);
2413    }
2414}