1use 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
25const LABEL_PX: f64 = 13.0;
27const VALUE_PX: f64 = 12.0;
28const BADGE_PX: f64 = 11.0;
29const 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;
36const SPARK_H: f64 = 22.0;
38const ARROW: f64 = 7.0;
41const MAX_LINES: usize = 3;
43
44fn 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
50pub 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
59fn wrap(s: &str, max: f64) -> Vec<String> {
65 let cap = ((max / (LABEL_PX * 0.6)).floor() as usize).max(4);
66 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#[derive(Clone, Debug, PartialEq)]
116pub struct NodeBox {
117 pub w: f64,
118 pub h: f64,
119 pub lines: Vec<String>,
120}
121
122pub 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#[derive(Clone, Debug)]
153pub struct GraphStyle {
154 pub card: Rgb,
156 pub band: Rgb,
158 pub muted: Rgb,
160 pub heading: Rgb,
162 pub ink: Rgb,
164 pub variable_fill: Rgb,
166 pub observed_fill: Rgb,
169 pub plate: Rgb,
171 pub class_prefix: String,
177 pub math_font: Option<String>,
182 pub glyph_fill: Option<Rgb>,
184 pub glyph_ink: Option<Rgb>,
186}
187
188impl Default for GraphStyle {
189 fn default() -> Self {
190 GraphStyle {
191 card: (255, 255, 255),
192 band: (226, 228, 233),
193 muted: (107, 114, 128),
194 heading: (17, 24, 39),
195 ink: (31, 41, 55),
196 variable_fill: (229, 231, 235),
197 observed_fill: (75, 85, 99),
198 plate: (107, 114, 128),
199 class_prefix: "gg-graph-".to_string(),
200 math_font: None,
201 glyph_fill: None,
202 glyph_ink: None,
203 }
204 }
205}
206
207#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
212pub enum NodeShape {
213 #[default]
215 Box,
216 Circle,
217 FilledCircle,
218 Square,
220 FilledSquare,
222 Text,
224 Glyph,
227 Terminal,
230}
231
232impl NodeShape {
233 fn name(self) -> &'static str {
234 match self {
235 NodeShape::Box => "box",
236 NodeShape::Circle => "circle",
237 NodeShape::FilledCircle => "filled-circle",
238 NodeShape::Square => "square",
239 NodeShape::FilledSquare => "filled-square",
240 NodeShape::Text => "text",
241 NodeShape::Glyph => "glyph",
242 NodeShape::Terminal => "terminal",
243 }
244 }
245}
246
247pub const BELIEF_W: f64 = 46.0;
249pub const BELIEF_H: f64 = 16.0;
250const SQUARE: f64 = 14.0;
252const TERMINAL: f64 = 11.0;
254const GLYPH_SIDE: f64 = 34.0;
256const GLYPH_PX: f64 = 15.0;
257
258pub fn node_size(shape: NodeShape, label: &str) -> NodeBox {
262 let one = || vec![label.to_string()];
263 match shape {
264 NodeShape::Box => node_box(label, None, None, false),
265 NodeShape::Circle | NodeShape::FilledCircle => {
266 let d = (text_w(label, LABEL_PX, true) + 14.0).max(30.0);
267 NodeBox {
268 w: d,
269 h: d,
270 lines: one(),
271 }
272 }
273 NodeShape::Square | NodeShape::FilledSquare => NodeBox {
274 w: SQUARE,
275 h: SQUARE,
276 lines: if label.is_empty() { Vec::new() } else { one() },
277 },
278 NodeShape::Terminal => NodeBox {
279 w: TERMINAL,
280 h: TERMINAL,
281 lines: if label.is_empty() { Vec::new() } else { one() },
282 },
283 NodeShape::Text => NodeBox {
284 w: text_w(label, LABEL_PX, false) + 8.0,
285 h: 20.0,
286 lines: one(),
287 },
288 NodeShape::Glyph => {
289 let side = (text_w(label, GLYPH_PX, true) + 14.0).max(GLYPH_SIDE);
290 NodeBox {
291 w: side,
292 h: GLYPH_SIDE,
293 lines: one(),
294 }
295 }
296 }
297}
298
299#[derive(Clone, Debug, Default)]
302pub struct Plate {
303 pub label: String,
304 pub nodes: Vec<usize>,
305}
306
307pub type DataAttr = (String, Option<String>);
310
311#[derive(Clone, Debug, Default)]
314pub struct DrawNode {
315 pub id: String,
317 pub shape: NodeShape,
319 pub lines: Vec<String>,
321 pub value: Option<String>,
323 pub badge: Option<(String, Rgb)>,
325 pub stroke: Rgb,
327 pub accent: Option<Rgb>,
330 pub spark: Option<(Vec<f64>, Rgb)>,
332 pub belief: Option<(Vec<f64>, Rgb)>,
335 pub prior: Option<(Vec<f64>, Rgb)>,
339 pub tooltip: String,
340 pub attrs: Vec<DataAttr>,
343}
344
345#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
347pub enum EdgeLine {
348 #[default]
349 Solid,
350 Dashed,
351 Dots,
353}
354
355#[derive(Clone, Debug, Default)]
359pub struct DrawEdge {
360 pub colour: Rgb,
361 pub width: f64,
363 pub line: EdgeLine,
364 pub class: Option<String>,
366 pub tooltip: String,
367 pub label: Option<String>,
369 pub label_at: Option<f64>,
373 pub undirected: bool,
375 pub label_math: bool,
379 pub attrs: Vec<DataAttr>,
382 pub label_attrs: Vec<DataAttr>,
384}
385
386pub fn flow_width(value: Option<f64>, max: f64, line: EdgeLine) -> f64 {
390 let width = match value {
391 Some(v) if max > 0.0 => 1.4 + 5.6 * (v.max(0.0) / max).sqrt(),
392 _ => 1.6,
393 };
394 let width = match line {
395 EdgeLine::Dots => width.clamp(3.0, 6.0),
396 _ => width,
397 };
398 (width * 10.0).round() / 10.0
399}
400
401#[derive(Default)]
403struct Frame(Vec<(String, Vec<Value>)>);
404
405impl Frame {
406 fn col(&mut self, name: &str) -> &mut Vec<Value> {
407 let i = match self.0.iter().position(|(n, _)| n == name) {
408 Some(i) => i,
409 None => {
410 self.0.push((name.to_string(), Vec::new()));
411 self.0.len() - 1
412 }
413 };
414 &mut self.0[i].1
415 }
416 fn num(&mut self, name: &str, v: f64) -> &mut Self {
417 self.col(name).push(Value::Float(v));
418 self
419 }
420 fn txt(&mut self, name: &str, v: impl Into<String>) -> &mut Self {
421 self.col(name).push(Value::Str(v.into()));
422 self
423 }
424 fn opt(&mut self, name: &str, v: Option<String>) -> &mut Self {
425 self.col(name).push(v.map_or(Value::Na, Value::Str));
426 self
427 }
428 fn attrs(&mut self, attrs: &[DataAttr]) -> &mut Self {
430 for (n, v) in attrs {
431 self.opt(&format!("a:{n}"), v.clone());
432 }
433 self
434 }
435 fn is_empty(&self) -> bool {
436 self.0.first().is_none_or(|(_, v)| v.is_empty())
437 }
438 fn attr_aes(&self, mut aes: Aes) -> Aes {
440 for (n, _) in &self.0 {
441 if let Some(name) = n.strip_prefix("a:") {
442 aes = aes.data_attr(name, n);
443 }
444 }
445 aes
446 }
447 fn take(&mut self, h: f64) -> Vec<(String, Vec<Value>)> {
451 let flip = |v: Vec<Value>| -> Vec<Value> {
452 v.into_iter()
453 .map(|x| match x {
454 Value::Float(y) => Value::Float(h - y),
455 other => other,
456 })
457 .collect()
458 };
459 std::mem::take(&mut self.0)
460 .into_iter()
461 .map(|(n, v)| match n.as_str() {
462 "y" => (n, flip(v)),
463 "y0" => ("y1".to_string(), flip(v)),
464 "y1" => ("y0".to_string(), flip(v)),
465 _ => (n, v),
466 })
467 .collect()
468 }
469}
470
471fn by_colour(v: &mut Vec<(Rgb, Frame)>, c: Rgb) -> &mut Frame {
474 let i = match v.iter().position(|(k, _)| *k == c) {
475 Some(i) => i,
476 None => {
477 v.push((c, Frame::default()));
478 v.len() - 1
479 }
480 };
481 &mut v[i].1
482}
483
484fn hex(c: Rgb) -> String {
485 format!("#{:02x}{:02x}{:02x}", c.0, c.1, c.2)
486}
487
488fn point_at(pts: &[(f64, f64)], t: f64) -> (f64, f64) {
490 let seg = |i: usize| {
491 let (a, b) = (pts[i], pts[i + 1]);
492 ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
493 };
494 let total: f64 = (0..pts.len().saturating_sub(1)).map(seg).sum();
495 let mut left = total * t;
496 for i in 0..pts.len().saturating_sub(1) {
497 let l = seg(i);
498 if l >= left && l > 0.0 {
499 let t = left / l;
500 let (a, b) = (pts[i], pts[i + 1]);
501 return (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
502 }
503 left -= l;
504 }
505 pts.first().copied().unwrap_or((0.0, 0.0))
506}
507
508fn edge_label_at(pts: &[(f64, f64)], label: &str, nodes: &[PlacedNode]) -> (f64, f64) {
512 let lines = label.split('\n').count();
513 let hw = edge_label_width(label) / 2.0 + 3.0;
514 let hh = lines as f64 * 6.6 + 3.0;
515 let clear = |(x, y): (f64, f64)| {
516 let cy = y - 4.0 - 0.36 * SMALL_PX;
517 nodes
518 .iter()
519 .all(|n| (x - n.cx).abs() >= hw + n.w / 2.0 || (cy - n.cy).abs() >= hh + n.h / 2.0)
520 };
521 let mid = point_at(pts, 0.5);
522 [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74, 0.18, 0.82]
523 .into_iter()
524 .map(|t| point_at(pts, t))
525 .find(|&p| clear(p))
526 .unwrap_or(mid)
527}
528
529fn end_label_at(pts: &[(f64, f64)], label: &str, t: f64) -> (f64, f64) {
535 use crate::graph_layout::LABEL_CLEAR;
536 let n = pts.len();
537 if n < 2 {
538 return pts.first().copied().unwrap_or((0.0, 0.0));
539 }
540 let (end, prev) = if t >= 0.5 {
541 (pts[n - 1], pts[n - 2])
542 } else {
543 (pts[0], pts[1])
544 };
545 let (dx, dy) = (prev.0 - end.0, prev.1 - end.1);
546 let len = (dx * dx + dy * dy).sqrt();
547 if len == 0.0 {
548 return end;
549 }
550 let (ux, uy) = (dx / len, dy / len);
551 let lines = label.split('\n').count() as f64;
552 let hw = edge_label_width(label) / 2.0;
553 let hh = lines * 6.6;
554 let below_mid = 4.0 + 0.36 * SMALL_PX;
556 if ux.abs() >= uy.abs() {
557 let s = (hw + LABEL_CLEAR).min(len * 0.5);
559 (end.0 + ux * s, end.1 + uy * s)
560 } else {
561 let s = (hh + LABEL_CLEAR).min(len * 0.5);
563 (end.0 + LABEL_CLEAR + hw, end.1 + uy * s + below_mid)
564 }
565}
566
567fn mid_of_baseline(baseline: f64, px: f64) -> f64 {
570 baseline - 0.36 * px
571}
572
573pub fn draw(
580 layout: &GraphLayout,
581 lanes: &[String],
582 plates: &[Plate],
583 nodes: &[DrawNode],
584 edges: &[DrawEdge],
585 style: &GraphStyle,
586 mut theme: Theme,
587) -> GGPlot {
588 let s = style;
589 let class = |name: &str| format!("{}{name}", s.class_prefix);
590 let (w, h) = (layout.w.ceil().max(1.0), layout.h.ceil().max(1.0));
591 theme.legend_position = crate::theme::LegendPosition::None;
592 let mut plot = GGPlot::new(vec![
593 ("x".to_string(), vec![Value::Float(0.0), Value::Float(w)]),
594 ("y".to_string(), vec![Value::Float(0.0), Value::Float(h)]),
595 ])
596 .theme(theme)
597 .scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
600 .scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0))
601 .coord_cartesian_zoom(Some((0.0, w)), Some((0.0, h)))
602 .scale_color_identity()
603 .scale_fill_identity()
604 .scale_linewidth(
605 ScaleLinewidthContinuous::new()
606 .with_limits(0.0, 16.0)
607 .with_range(0.0, 16.0),
608 )
609 .scale_linetype_manual(vec![
610 ("solid", Linetype::Solid),
611 ("dashed", Linetype::Custom(vec![(6.0, 4.0)])),
612 ("dots", Linetype::Custom(vec![(0.0, 10.0)])),
614 ]);
615 let rect_aes = || Aes::new().xmin("x0").xmax("x1").ymin("y0").ymax("y1");
616 let inert = [("pointer-events", "none")];
617
618 let (mut even, mut odd, mut names) = (Frame::default(), Frame::default(), Frame::default());
620 for &(l, x0, y0, x1, y1) in &layout.bands {
621 let name = lanes.get(l).cloned().unwrap_or_default();
622 let f = if l % 2 == 0 { &mut even } else { &mut odd };
623 f.num("x0", x0).num("x1", x1).num("y0", y0).num("y1", y1);
624 f.txt("lane", name.clone());
625 names
626 .num("x", x0 + 8.0)
627 .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
628 names.txt("label", name);
629 }
630 for (mut f, alpha) in [(even, 0.35), (odd, 0.18)] {
631 if f.is_empty() {
632 continue;
633 }
634 plot = plot
635 .geom_rect_with(
636 GeomRect {
637 fill: s.band,
638 alpha,
639 line_width: 0.0,
640 ..Default::default()
641 }
642 .with_radius(6.0),
643 )
644 .layer_data(f.take(h))
645 .layer_aes(rect_aes().data_attr("lane", "lane"))
646 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane"))]);
647 }
648 if !names.is_empty() {
649 plot = plot
650 .geom_text_with(GeomText {
651 size: SMALL_PX,
652 color: s.muted,
653 hjust: 0.0,
654 fontface: FontFace::Bold,
655 ..Default::default()
656 })
657 .layer_data(names.take(h))
658 .layer_aes(Aes::new().x("x").y("y").label("label"))
659 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("lane-label"))]);
660 }
661
662 let (mut pf, mut pl) = (Frame::default(), Frame::default());
664 for p in plates {
665 let members: Vec<&PlacedNode> = p
666 .nodes
667 .iter()
668 .filter_map(|&i| layout.nodes.get(i))
669 .collect();
670 if members.is_empty() {
671 continue;
672 }
673 let pad = 8.0;
674 let x0 = members
675 .iter()
676 .map(|n| n.cx - n.w / 2.0)
677 .fold(f64::INFINITY, f64::min)
678 - pad;
679 let x1 = members
680 .iter()
681 .map(|n| n.cx + n.w / 2.0)
682 .fold(f64::NEG_INFINITY, f64::max)
683 + pad;
684 let y0 = members
685 .iter()
686 .map(|n| n.cy - n.h / 2.0)
687 .fold(f64::INFINITY, f64::min)
688 - pad
689 - 14.0;
690 let y1 = members
691 .iter()
692 .map(|n| n.cy + n.h / 2.0)
693 .fold(f64::NEG_INFINITY, f64::max)
694 + pad;
695 for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)] {
696 pf.num("x", x).num("y", y).txt("lt", "dashed");
697 pf.txt("g", p.label.clone()).txt("plate", p.label.clone());
698 }
699 pl.num("x", x0 + 6.0)
700 .num("y", mid_of_baseline(y0 + 13.0, SMALL_PX));
701 pl.txt("label", p.label.clone());
702 }
703 if !pf.is_empty() {
704 plot = plot
705 .geom_path_with(GeomPath::default().color(s.plate).linewidth(1.0))
706 .layer_data(pf.take(h))
707 .layer_aes(
708 Aes::new()
709 .x("x")
710 .y("y")
711 .group("g")
712 .linetype("lt")
713 .data_attr("plate", "plate"),
714 )
715 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate"))]);
716 plot = plot
717 .geom_text_with(GeomText {
718 size: SMALL_PX,
719 color: s.plate,
720 hjust: 0.0,
721 ..Default::default()
722 })
723 .layer_data(pl.take(h))
724 .layer_aes(Aes::new().x("x").y("y").label("label"))
725 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("plate-label"))]);
726 }
727
728 let (mut ef, mut uf, mut lf) = (Frame::default(), Frame::default(), Frame::default());
730 let mut lmf = Frame::default();
732 for (k, e) in edges.iter().enumerate() {
733 let Some(route) = layout.edges.get(k) else {
734 continue;
735 };
736 let mut pts = route.clone();
737 if pts.len() < 2 {
738 continue;
739 }
740 if !e.undirected {
745 let n = pts.len();
746 let ((fx, fy), (tx, ty)) = (pts[n - 2], pts[n - 1]);
747 let len = ((tx - fx).powi(2) + (ty - fy).powi(2)).sqrt().max(1e-6);
748 let pull = e.width.min(len / 2.0);
749 pts[n - 1] = (tx - (tx - fx) / len * pull, ty - (ty - fy) / len * pull);
750 }
751 let ef = if e.undirected { &mut uf } else { &mut ef };
752 let lt = match e.line {
753 EdgeLine::Solid => "solid",
754 EdgeLine::Dashed => "dashed",
755 EdgeLine::Dots => "dots",
756 };
757 for &(x, y) in &pts {
758 ef.num("x", x).num("y", y).txt("g", format!("e{k:04}"));
759 ef.txt("col", hex(e.colour))
760 .num("lw", e.width)
761 .txt("lt", lt);
762 ef.opt("cls", e.class.clone()).txt("tip", e.tooltip.clone());
763 ef.attrs(&e.attrs);
764 }
765 let routed = layout.routed.get(k).copied().unwrap_or(false);
768 if let Some(l) = e.label.as_ref().filter(|_| !routed) {
769 let (mx, my) = match e.label_at {
770 Some(t) => end_label_at(route, l, t),
773 None => edge_label_at(route, l, &layout.nodes),
774 };
775 let f = if e.label_math && s.math_font.is_some() {
776 &mut lmf
777 } else {
778 &mut lf
779 };
780 f.num("x", mx).num("y", mid_of_baseline(my - 4.0, SMALL_PX));
781 f.txt("label", l.clone());
782 f.attrs(&e.label_attrs);
783 }
784 }
785 for (mut f, arrowed) in [(ef, true), (uf, false)] {
786 if f.is_empty() {
787 continue;
788 }
789 let aes = f.attr_aes(
790 Aes::new()
791 .x("x")
792 .y("y")
793 .group("g")
794 .color("col")
795 .linewidth("lw")
796 .linetype("lt")
797 .class("cls")
798 .tooltip("tip"),
799 );
800 let mut geom = GeomPath::default().lineend(LineEnd::Round);
801 if arrowed {
802 geom = geom.arrow(
804 arrow()
805 .closed()
806 .angle(29.0)
807 .length(ARROW + 1.0)
808 .length_per_linewidth(1.2),
809 );
810 }
811 plot = plot
812 .geom_path_with(geom)
813 .layer_data(f.take(h))
814 .layer_aes(aes)
815 .layer_svg_attr("class", class("edge"));
816 }
817 if !lmf.is_empty() {
818 let aes = lmf.attr_aes(Aes::new().x("x").y("y").label("label"));
819 plot = plot
820 .geom_text_with(
821 GeomText {
822 size: LABEL_PX + 1.0,
823 color: s.heading,
824 fontface: FontFace::Italic,
825 fontfamily: s.math_font.clone().unwrap_or_default(),
826 ..Default::default()
827 }
828 .bg_colour(s.card)
829 .bg_r(2.0),
830 )
831 .layer_data(lmf.take(h))
832 .layer_aes(aes)
833 .layer_svg_attrs(inert)
834 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
835 }
836 if !lf.is_empty() {
837 let aes = lf.attr_aes(Aes::new().x("x").y("y").label("label"));
839 plot = plot
840 .geom_text_with(
841 GeomText {
842 size: SMALL_PX,
843 color: s.muted,
844 ..Default::default()
845 }
846 .bg_colour(s.card)
847 .bg_r(2.0),
848 )
849 .layer_data(lf.take(h))
850 .layer_aes(aes)
851 .layer_svg_attrs(inert)
852 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("edge-label"))]);
853 }
854
855 let mut order: Vec<usize> = (0..nodes.len().min(layout.nodes.len())).collect();
858 order.sort_by_key(|&i| (layout.nodes[i].order, i));
859 let mut boxes: Vec<(Rgb, Frame)> = Vec::new();
860 let mut beliefs = Frame::default();
861 let mut priors = Frame::default();
862 let mut shaped: Vec<((NodeShape, u64, Rgb), Frame)> = Vec::new();
864 let (mut inside, mut inverse, mut above, mut glyphs, mut texts, mut beside) = (
865 Frame::default(),
866 Frame::default(),
867 Frame::default(),
868 Frame::default(),
869 Frame::default(),
870 Frame::default(),
871 );
872 let mut badges: Vec<(Rgb, Frame)> = Vec::new();
873 let (mut accent, mut lines, mut values) =
874 (Frame::default(), Frame::default(), Frame::default());
875 let (mut dots, mut btext, mut spark, mut ends) = (
876 Frame::default(),
877 Frame::default(),
878 Frame::default(),
879 Frame::default(),
880 );
881 for v in order {
882 let nd = &nodes[v];
883 let pn = &layout.nodes[v];
884 let id = nd.id.clone();
885 let (x, y) = (pn.cx - pn.w / 2.0, pn.cy - pn.h / 2.0);
886 let squared = matches!(nd.shape, NodeShape::Square | NodeShape::FilledSquare);
888 let base = y - if squared { 17.0 } else { 3.0 };
889 let x0 = pn.cx - BELIEF_W / 2.0;
890 let curve = |hs: &[f64]| -> Vec<(f64, f64)> {
891 let last = (hs.len() - 1) as f64;
892 hs.iter()
893 .enumerate()
894 .map(|(i, &h)| {
895 (
896 x0 + BELIEF_W * i as f64 / last,
897 base - h.clamp(0.0, 1.0) * BELIEF_H,
898 )
899 })
900 .collect()
901 };
902 if let Some((hs, col)) = nd.prior.as_ref().filter(|(h, _)| h.len() >= 3) {
904 for (px, py) in curve(hs) {
905 priors.num("x", px).num("y", py).txt("g", id.clone());
906 priors.txt("col", hex(*col)).txt("lt", "dashed");
907 priors.txt("of", id.clone());
908 }
909 }
910 if let Some((hs, col)) = nd.belief.as_ref().filter(|(h, _)| h.len() >= 3) {
911 let mut pts = curve(hs);
912 pts.push((x0 + BELIEF_W, base));
913 pts.push((x0, base));
914 for (px, py) in pts {
915 beliefs.num("x", px).num("y", py).txt("g", id.clone());
916 beliefs.txt("fill", hex(*col)).txt("of", id.clone());
917 }
918 }
919 if nd.shape != NodeShape::Box {
920 let r = match nd.shape {
921 NodeShape::Circle | NodeShape::FilledCircle => pn.w.min(pn.h) / 2.0,
922 NodeShape::Square | NodeShape::FilledSquare | NodeShape::Terminal => 1.5,
923 NodeShape::Glyph => 4.0,
924 _ => 0.0,
925 };
926 let (fill, stroke) = match nd.shape {
927 NodeShape::Circle => (s.variable_fill, nd.stroke),
928 NodeShape::FilledCircle | NodeShape::FilledSquare | NodeShape::Terminal => {
931 let c = nd.accent.unwrap_or(s.observed_fill);
932 (c, c)
933 }
934 NodeShape::Square => (s.card, nd.stroke),
935 NodeShape::Glyph => (s.glyph_fill.unwrap_or(s.card), nd.stroke),
936 _ => (s.card, s.card),
937 };
938 let key = (nd.shape, r.to_bits(), stroke);
939 let i = match shaped.iter().position(|(k, _)| *k == key) {
940 Some(i) => i,
941 None => {
942 shaped.push((key, Frame::default()));
943 shaped.len() - 1
944 }
945 };
946 let f = &mut shaped[i].1;
947 f.num("x0", x)
948 .num("x1", x + pn.w)
949 .num("y0", y)
950 .num("y1", y + pn.h);
951 f.txt("fill", hex(fill));
952 f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
953 let label = nd.lines.join(" ");
954 if label.is_empty() {
955 continue;
956 }
957 let target = match nd.shape {
958 NodeShape::Glyph => &mut glyphs,
959 NodeShape::FilledCircle => &mut inverse,
960 NodeShape::Square | NodeShape::FilledSquare => &mut above,
961 NodeShape::Text => &mut texts,
963 NodeShape::Terminal => &mut beside,
964 _ => &mut inside,
965 };
966 let ly = match nd.shape {
967 NodeShape::Square | NodeShape::FilledSquare => y - 4.0 - 0.36 * SMALL_PX,
968 _ => pn.cy,
969 };
970 let lx = match nd.shape {
972 NodeShape::Terminal => x + pn.w + 5.0,
973 _ => pn.cx,
974 };
975 target.num("x", lx).num("y", ly);
976 target.txt("label", label).txt("of", id.clone());
977 continue;
978 }
979 let f = by_colour(&mut boxes, nd.stroke);
980 f.num("x0", x)
981 .num("x1", x + pn.w)
982 .num("y0", y)
983 .num("y1", y + pn.h);
984 f.txt("tip", nd.tooltip.clone()).attrs(&nd.attrs);
985
986 if let Some(a) = nd.accent {
987 accent.num("x0", x + 1.5).num("x1", x + 4.5);
988 accent
989 .num("y0", y + 6.0)
990 .num("y1", y + 6.0 + (pn.h - 12.0).max(4.0));
991 accent.txt("fill", hex(a)).txt("of", id.clone());
992 }
993 let mut base = y + BOX_PAD_Y + 12.0;
994 for line in &nd.lines {
995 lines
996 .num("x", pn.cx)
997 .num("y", mid_of_baseline(base, LABEL_PX));
998 lines.txt("label", line.clone()).txt("of", id.clone());
999 base += LINE_H;
1000 }
1001 if let Some(fv) = &nd.value {
1002 values
1003 .num("x", pn.cx)
1004 .num("y", mid_of_baseline(base, VALUE_PX));
1005 values.txt("label", fv.clone()).txt("of", id.clone());
1006 base += LINE_H;
1007 }
1008 if let Some((b, dot)) = &nd.badge {
1009 let bw = text_w(b, BADGE_PX, false) + 20.0;
1010 let (bx, by) = (pn.cx - bw / 2.0, base - 9.0);
1011 let f = by_colour(&mut badges, *dot);
1012 f.num("x0", bx)
1013 .num("x1", bx + bw)
1014 .num("y0", by)
1015 .num("y1", by + 16.0);
1016 f.txt("of", id.clone());
1017 dots.num("x", bx + 9.0).num("y", by + 8.0);
1018 dots.txt("col", hex(*dot)).txt("of", id.clone());
1019 btext.num("x", bx + 15.0).num("y", by + 8.0);
1020 btext.txt("label", b.clone()).txt("of", id.clone());
1021 base += 20.0;
1022 }
1023 if let Some((values, colour)) = nd.spark.as_ref().filter(|(v, _)| v.len() >= 2) {
1025 let (lo, hi) = values
1026 .iter()
1027 .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
1028 (a.min(v), b.max(v))
1029 });
1030 let rng = if hi > lo { hi - lo } else { 1.0 };
1031 let (sx0, sw) = (x + BOX_PAD_X, pn.w - 2.0 * BOX_PAD_X);
1032 let (top, sh) = (base - 8.0, SPARK_H - 8.0);
1033 let last = values.len() - 1;
1034 let col = hex(*colour);
1035 for (i, &sv) in values.iter().enumerate() {
1036 let (px, py) = (
1037 sx0 + sw * i as f64 / last as f64,
1038 top + sh - (sv - lo) / rng * sh,
1039 );
1040 spark.num("x", px).num("y", py).txt("g", id.clone());
1041 spark.txt("col", col.clone()).txt("of", id.clone());
1042 if i == last {
1043 ends.num("x", px).num("y", py);
1044 ends.txt("col", col.clone()).txt("of", id.clone());
1045 }
1046 }
1047 }
1048 }
1049 for (stroke, mut f) in boxes {
1050 let aes = f.attr_aes(rect_aes().tooltip("tip"));
1051 plot = plot
1052 .geom_rect_with(
1053 GeomRect {
1054 fill: s.card,
1055 color: stroke,
1056 alpha: 1.0,
1057 line_width: 1.2,
1058 ..Default::default()
1059 }
1060 .with_radius(8.0),
1061 )
1062 .layer_data(f.take(h))
1063 .layer_aes(aes)
1064 .layer_svg_attr("class", class("node"));
1065 }
1066 for ((shape, r, stroke), mut f) in shaped {
1067 let aes = f.attr_aes(rect_aes().fill("fill").tooltip("tip"));
1068 let cls = format!(
1069 "{} {}",
1070 class("node"),
1071 class(&format!("node-{}", shape.name()))
1072 );
1073 plot = plot
1074 .geom_rect_with(
1075 GeomRect {
1076 color: stroke,
1077 alpha: 1.0,
1078 line_width: if shape == NodeShape::Text { 0.0 } else { 1.2 },
1079 ..Default::default()
1080 }
1081 .with_radius(f64::from_bits(r)),
1082 )
1083 .layer_data(f.take(h))
1084 .layer_aes(aes)
1085 .layer_svg_attr("class", cls);
1086 }
1087 if !priors.is_empty() {
1088 plot = plot
1089 .geom_path_with(GeomPath {
1090 alpha: 0.7,
1091 ..GeomPath::default().linewidth(1.0)
1092 })
1093 .layer_data(priors.take(h))
1094 .layer_aes(
1095 Aes::new()
1096 .x("x")
1097 .y("y")
1098 .group("g")
1099 .color("col")
1100 .linetype("lt")
1101 .group_wrap("of", "of"),
1102 )
1103 .decorative()
1104 .layer_svg_attrs(inert)
1105 .layer_svg_attr("class", class("node-prior"));
1106 }
1107 if !beliefs.is_empty() {
1108 plot = plot
1109 .geom_polygon_with(GeomPolygon {
1110 alpha: 0.45,
1111 line_width: 0.0,
1112 ..Default::default()
1113 })
1114 .layer_data(beliefs.take(h))
1115 .layer_aes(
1116 Aes::new()
1117 .x("x")
1118 .y("y")
1119 .group("g")
1120 .fill("fill")
1121 .group_wrap("of", "of"),
1122 )
1123 .decorative()
1124 .layer_svg_attrs(inert)
1125 .layer_svg_attr("class", class("node-belief"));
1126 }
1127 let of = |a: Aes| a.group_wrap("of", "of");
1129 if !accent.is_empty() {
1130 plot = plot
1131 .geom_rect_with(
1132 GeomRect {
1133 alpha: 1.0,
1134 line_width: 0.0,
1135 ..Default::default()
1136 }
1137 .with_radius(1.5),
1138 )
1139 .layer_data(accent.take(h))
1140 .layer_aes(of(rect_aes().fill("fill")))
1141 .decorative()
1142 .layer_svg_attrs(inert);
1143 }
1144 for (mut f, size, colour, cls, math, hjust) in [
1145 (lines, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1146 (values, VALUE_PX, s.ink, class("node-value"), false, 0.5),
1147 (inside, LABEL_PX, s.heading, class("node-label"), true, 0.5),
1148 (texts, LABEL_PX, s.heading, class("node-label"), false, 0.5),
1149 (inverse, LABEL_PX, s.card, class("node-label"), true, 0.5),
1150 (above, SMALL_PX, s.muted, class("node-label"), true, 0.5),
1151 (beside, LABEL_PX, s.heading, class("node-label"), true, 0.0),
1152 (
1153 glyphs,
1154 GLYPH_PX,
1155 s.glyph_ink.unwrap_or(s.heading),
1156 class("node-label"),
1157 true,
1158 0.5,
1159 ),
1160 ] {
1161 if f.is_empty() {
1162 continue;
1163 }
1164 let (fontfamily, fontface, size) = match s.math_font.as_ref().filter(|_| math) {
1166 Some(family) => (family.clone(), FontFace::Italic, size + 2.0),
1167 None => (String::new(), FontFace::Bold, size),
1168 };
1169 plot = plot
1170 .geom_text_with(GeomText {
1171 size,
1172 color: colour,
1173 fontface,
1174 fontfamily,
1175 hjust,
1176 ..Default::default()
1177 })
1178 .layer_data(f.take(h))
1179 .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1180 .layer_svg_attrs(inert)
1181 .layer_svg_attrs([("aria-hidden", "true"), ("class", cls.as_str())]);
1182 }
1183 for (dot, mut f) in badges {
1184 plot = plot
1185 .geom_rect_with(
1186 GeomRect {
1187 fill: s.card,
1188 color: dot,
1189 alpha: 0.0,
1190 line_width: 1.0,
1191 ..Default::default()
1192 }
1193 .with_radius(8.0),
1194 )
1195 .layer_data(f.take(h))
1196 .layer_aes(of(rect_aes()))
1197 .decorative()
1198 .layer_svg_attrs(inert);
1199 }
1200 for (mut f, size) in [(dots, 3.0), (ends, 2.2)] {
1201 if f.is_empty() {
1202 continue;
1203 }
1204 plot = plot
1205 .geom_point_with(GeomPoint {
1206 size,
1207 ..Default::default()
1208 })
1209 .layer_data(f.take(h))
1210 .layer_aes(of(Aes::new().x("x").y("y").color("col")))
1211 .decorative()
1212 .layer_svg_attrs(inert);
1213 }
1214 if !btext.is_empty() {
1215 plot = plot
1216 .geom_text_with(GeomText {
1217 size: BADGE_PX,
1218 color: s.ink,
1219 hjust: 0.0,
1220 ..Default::default()
1221 })
1222 .layer_data(btext.take(h))
1223 .layer_aes(of(Aes::new().x("x").y("y").label("label")))
1224 .layer_svg_attrs(inert)
1225 .layer_svg_attrs([("aria-hidden", "true"), ("class", &*class("node-badge"))]);
1226 }
1227 if !spark.is_empty() {
1228 plot = plot
1229 .geom_path_with(GeomPath::default().linewidth(1.4))
1230 .layer_data(spark.take(h))
1231 .layer_aes(of(Aes::new().x("x").y("y").group("g").color("col")))
1232 .decorative()
1233 .layer_svg_attrs(inert)
1234 .layer_svg_attr("class", class("node-spark"));
1235 }
1236 plot
1237}
1238
1239#[cfg(test)]
1240mod tests {
1241 use super::*;
1242 use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
1243
1244 #[test]
1245 fn an_end_label_sits_beside_its_box() {
1246 let hw = edge_label_width("variance") / 2.0;
1249 let (x, y) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "variance", 0.8);
1250 assert!(
1251 (x - (100.0 - hw - crate::graph_layout::LABEL_CLEAR)).abs() < 1e-9 && y == 0.0,
1252 "{x} {y}"
1253 );
1254 let (x, _) = end_label_at(&[(0.0, 0.0), (100.0, 0.0)], "mean", 0.2);
1255 assert!(
1256 x - edge_label_width("mean") / 2.0 >= crate::graph_layout::LABEL_CLEAR - 1e-9,
1257 "{x}"
1258 );
1259 let (x, y) = end_label_at(&[(50.0, 0.0), (50.0, 40.0)], "out", 0.2);
1261 assert!(
1262 x - edge_label_width("out") / 2.0 > 50.0 && y > 0.0,
1263 "{x} {y}"
1264 );
1265 let (x, _) = end_label_at(&[(0.0, 0.0), (20.0, 0.0)], "variance", 0.8);
1267 assert!((x - 10.0).abs() < 1e-9, "{x}");
1268 }
1269
1270 #[test]
1271 fn wraps_long_labels_in_three_lines() {
1272 let l = wrap(
1273 "Recommend replenishment orders for every store and every week of the coming year",
1274 152.0,
1275 );
1276 assert_eq!(l.len(), 3);
1277 assert!(l[2].ends_with('…'));
1278 assert_eq!(wrap("Ingest", 152.0), ["Ingest"]);
1279 }
1280
1281 #[test]
1284 fn wraps_at_word_boundaries() {
1285 let max = BOX_MAX_W - 2.0 * BOX_PAD_X;
1286 for label in [
1287 "duckdb/community-extensions (descriptions)",
1288 "Locked DuckDB server (anofox-visualization)",
1289 "Parquet snapshot (downloads, extensions)",
1290 "fetch.sh: download, file by ISO week, merge",
1291 ] {
1292 let l = wrap(label, max);
1293 assert!(l.len() <= MAX_LINES, "{l:?}");
1294 assert!(!l.iter().any(|x| x.contains('…')), "{label}: {l:?}");
1295 let joined: String = l.concat();
1297 assert_eq!(joined.replace(' ', ""), label.replace(' ', ""), "{l:?}");
1298 for w in l.windows(2) {
1299 let end = w[0].chars().last().unwrap();
1300 let next = w[1].chars().next().unwrap();
1301 let at_space = label.contains(&format!(
1302 "{} {}",
1303 w[0].split(' ').next_back().unwrap(),
1304 w[1].split(' ').next().unwrap()
1305 ));
1306 assert!(
1307 at_space || matches!(end, '/' | '-' | '_' | '.' | ','),
1308 "{l:?} breaks at {end}{next}"
1309 );
1310 }
1311 }
1312 assert_eq!(
1313 wrap("duckdb/community-extensions (descriptions)", max),
1314 ["duckdb/community-", "extensions", "(descriptions)"]
1315 );
1316 }
1317
1318 #[test]
1319 fn node_box_grows_with_its_contents() {
1320 let plain = node_box("Ingest", None, None, false);
1321 assert_eq!((plain.w, plain.h), (BOX_MIN_W, 2.0 * BOX_PAD_Y + LINE_H));
1322 let full = node_box("Ingest", Some("1,240"), Some("late"), true);
1323 assert_eq!(full.h, plain.h + LINE_H + 20.0 + SPARK_H);
1324 assert!(full.w >= 110.0 + 2.0 * BOX_PAD_X);
1325 let long = node_box(&"word ".repeat(40), None, None, false);
1326 assert!(long.w <= BOX_MAX_W && long.lines.len() == MAX_LINES);
1327 }
1328
1329 #[test]
1331 fn edge_label_keeps_clear_of_nodes() {
1332 let node = |cx: f64, w: f64| PlacedNode {
1333 cx,
1334 cy: 0.0,
1335 w,
1336 h: 40.0,
1337 layer: 0,
1338 order: 0,
1339 };
1340 let pts = [(0.0, 0.0), (300.0, 0.0)];
1341 assert_eq!(edge_label_at(&pts, "spikes flagged", &[]), (150.0, 0.0));
1343 let nodes = [node(150.0, 60.0)];
1345 let (x, _) = edge_label_at(&pts, "spikes flagged", &nodes);
1346 let hw = edge_label_width("spikes flagged") / 2.0 + 3.0;
1347 assert!((x - 150.0).abs() >= hw + 30.0, "{x}");
1348 assert_eq!(point_at(&pts, 0.25), (75.0, 0.0));
1349 }
1350
1351 #[test]
1352 fn flow_width_is_area_true_and_rounded() {
1353 assert_eq!(flow_width(None, 10.0, EdgeLine::Solid), 1.6);
1354 assert_eq!(flow_width(Some(10.0), 10.0, EdgeLine::Solid), 7.0);
1355 assert_eq!(flow_width(Some(2.5), 10.0, EdgeLine::Solid), 4.2);
1356 assert_eq!(flow_width(None, 10.0, EdgeLine::Dots), 3.0);
1357 }
1358
1359 #[test]
1363 fn draws_marks_with_attributes_and_groups() {
1364 let labels = ["Ingest", "Model", "Publish"];
1365 let boxes: Vec<NodeBox> = labels
1366 .iter()
1367 .enumerate()
1368 .map(|(i, l)| node_box(l, (i == 1).then_some("42"), None, i == 2))
1369 .collect();
1370 let gnodes: Vec<GraphNode> = boxes
1371 .iter()
1372 .enumerate()
1373 .map(|(i, b)| GraphNode {
1374 w: b.w,
1375 h: b.h,
1376 lane: Some(i % 2),
1377 ..Default::default()
1378 })
1379 .collect();
1380 let gedges = [
1381 GraphEdge {
1382 from: 0,
1383 to: 1,
1384 label_w: Some(edge_label_width("rows")),
1385 },
1386 GraphEdge {
1387 from: 1,
1388 to: 2,
1389 label_w: None,
1390 },
1391 ];
1392 let params = LayeredParams {
1393 lanes: 2,
1394 ..Default::default()
1395 };
1396 let l = layered(&gnodes, &gedges, ¶ms);
1397 let nodes: Vec<DrawNode> = labels
1398 .iter()
1399 .zip(&boxes)
1400 .enumerate()
1401 .map(|(i, (id, b))| DrawNode {
1402 id: id.to_string(),
1403 lines: b.lines.clone(),
1404 value: (i == 1).then(|| "42".to_string()),
1405 stroke: (90, 90, 90),
1406 accent: (i == 0).then_some((200, 0, 0)),
1407 spark: (i == 2).then(|| (vec![1.0, 3.0, 2.0], (0, 0, 200))),
1408 tooltip: format!("{id}!"),
1409 attrs: vec![
1410 ("node".to_string(), Some(id.to_string())),
1411 ("value".to_string(), (i == 1).then(|| "42".to_string())),
1412 ],
1413 ..Default::default()
1414 })
1415 .collect();
1416 let edges: Vec<DrawEdge> = [(0, 1), (1, 2)]
1417 .iter()
1418 .map(|&(a, b)| DrawEdge {
1419 colour: (100, 100, 100),
1420 width: flow_width(None, 0.0, EdgeLine::Solid),
1421 line: if a == 0 {
1422 EdgeLine::Solid
1423 } else {
1424 EdgeLine::Dashed
1425 },
1426 class: (a == 1).then(|| "flowing".to_string()),
1427 tooltip: format!("{} → {}", labels[a], labels[b]),
1428 label: (a == 0).then(|| "rows".to_string()),
1429 attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
1430 label_attrs: vec![("from".to_string(), Some(labels[a].to_string()))],
1431 ..Default::default()
1432 })
1433 .collect();
1434 let lanes = ["Left".to_string(), "Right".to_string()];
1435 let svg = draw(
1436 &l,
1437 &lanes,
1438 &[],
1439 &nodes,
1440 &edges,
1441 &GraphStyle::default(),
1442 crate::theme::presets::theme_void(),
1443 )
1444 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1445 .unwrap();
1446 let mut tags: Vec<(&str, bool)> = Vec::new();
1448 let mut stack: Vec<bool> = Vec::new();
1449 for part in svg.split('<').skip(1) {
1450 let tag = &part[..part.find('>').unwrap()];
1451 if tag.starts_with('/') {
1452 stack.pop();
1453 continue;
1454 }
1455 let inside = stack.iter().any(|&g| g);
1456 tags.push((tag, inside));
1457 if !tag.ends_with('/') {
1458 stack.push(tag.contains("data-of="));
1459 }
1460 }
1461 let attr = |tag: &str, name: &str| {
1462 let key = format!(" {name}=\"");
1463 tag.find(&key).map(|i| {
1464 let rest = &tag[i + key.len()..];
1465 rest[..rest.find('"').unwrap()].to_string()
1466 })
1467 };
1468 let boxes: Vec<_> = tags
1470 .iter()
1471 .filter(|(t, _)| t.contains("data-node="))
1472 .collect();
1473 assert_eq!(boxes.len(), 3);
1474 for (b, inside) in &boxes {
1475 assert!(!inside, "{b}");
1476 let id = attr(b, "data-node").unwrap();
1477 assert_eq!(attr(b, "data-value").is_some(), id == "Model", "{id}");
1478 }
1479 assert!(tags.iter().any(|(t, _)| t.contains("data-edge=\"1>2\"")
1481 && attr(t, "class").is_some_and(|c| c.contains("flowing"))));
1482 assert!(tags
1483 .iter()
1484 .any(|(t, _)| attr(t, "data-from").as_deref() == Some("Ingest")));
1485 assert!(svg.contains(" gg-graph-node\"") && svg.contains("gg-graph-edge-label"));
1486 for id in labels {
1488 assert!(svg.contains(&format!("data-of=\"{id}\"")), "{id}");
1489 }
1490 assert!(svg.contains("data-lane=\"Right\""));
1491 assert!(svg.contains(">Left<") && svg.contains(">42<"));
1492 }
1493
1494 #[test]
1497 fn forney_terminals_and_variable_edges() {
1498 use crate::graph_layout::{layered, GraphEdge, GraphNode, LayeredParams};
1499 let spec = [
1500 ("Cat", NodeShape::Glyph),
1501 ("T", NodeShape::Glyph),
1502 ("x₁", NodeShape::Terminal),
1503 ];
1504 let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
1505 assert_eq!((sizes[2].w, sizes[2].h), (TERMINAL, TERMINAL));
1506 let gnodes: Vec<GraphNode> = sizes
1507 .iter()
1508 .map(|b| GraphNode {
1509 w: b.w,
1510 h: b.h,
1511 ..Default::default()
1512 })
1513 .collect();
1514 let gedges = vec![
1515 GraphEdge {
1516 from: 0,
1517 to: 1,
1518 label_w: None,
1519 },
1520 GraphEdge {
1521 from: 1,
1522 to: 2,
1523 label_w: None,
1524 },
1525 ];
1526 let l = layered(&gnodes, &gedges, &LayeredParams::default());
1527 let nodes: Vec<DrawNode> = spec
1528 .iter()
1529 .zip(&sizes)
1530 .enumerate()
1531 .map(|(i, ((_, shape), b))| DrawNode {
1532 id: format!("n{i}"),
1533 shape: *shape,
1534 lines: b.lines.clone(),
1535 stroke: (13, 148, 136),
1536 tooltip: b.lines.join(" "),
1537 attrs: vec![("node".to_string(), Some(format!("n{i}")))],
1538 accent: (*shape == NodeShape::Terminal).then_some((217, 119, 6)),
1540 ..Default::default()
1541 })
1542 .collect();
1543 let edges = vec![
1544 DrawEdge {
1546 colour: (13, 148, 136),
1547 width: 1.2,
1548 undirected: true,
1549 label: Some("s₀".to_string()),
1550 label_math: true,
1551 ..Default::default()
1552 },
1553 DrawEdge {
1554 colour: (13, 148, 136),
1555 width: 1.2,
1556 undirected: true,
1557 ..Default::default()
1558 },
1559 ];
1560 let render = |style: &GraphStyle| {
1561 draw(
1562 &l,
1563 &[],
1564 &[],
1565 &nodes,
1566 &edges,
1567 style,
1568 crate::theme::presets::theme_void(),
1569 )
1570 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32 + 40, l.h.ceil() as u32)
1571 .unwrap()
1572 };
1573 let math = GraphStyle {
1574 math_font: Some("STIX Two Math, serif".to_string()),
1575 ..GraphStyle::default()
1576 };
1577 let svg = render(&math);
1578 let el = |text: &str| {
1579 let at = svg
1580 .find(&format!(">{text}</text>"))
1581 .unwrap_or_else(|| panic!("{text}"));
1582 svg[svg[..at].rfind('<').unwrap()..at].to_string()
1583 };
1584 assert!(svg.contains("gg-graph-node-terminal"), "terminal mark");
1586 assert!(
1587 svg.contains("fill=\"#D97706\""),
1588 "the terminal in its accent"
1589 );
1590 let x1 = el("x₁");
1591 assert!(
1592 x1.contains("text-anchor=\"start\"") && x1.contains("italic"),
1593 "{x1}"
1594 );
1595 let t = &l.nodes[2];
1596 let lx: f64 = x1
1597 .split("x=\"")
1598 .nth(1)
1599 .unwrap()
1600 .split('"')
1601 .next()
1602 .unwrap()
1603 .parse()
1604 .unwrap();
1605 assert!(
1606 lx > t.cx + t.w / 2.0,
1607 "the label right of the square: {lx} vs {}",
1608 t.cx
1609 );
1610 let s0 = el("s₀");
1612 assert!(
1613 s0.contains("STIX Two Math") && s0.contains("italic"),
1614 "{s0}"
1615 );
1616 let plain = render(&GraphStyle::default());
1618 let at = plain.find(">s₀</text>").unwrap();
1619 assert!(!plain[plain[..at].rfind('<').unwrap()..at].contains("italic"));
1620 }
1621
1622 #[test]
1627 fn draws_a_factor_graph_with_shapes_and_a_plate() {
1628 let n = 3;
1629 let mut spec = vec![
1631 ("Beta", NodeShape::Box),
1632 ("θ", NodeShape::Circle),
1633 ("=", NodeShape::Square),
1634 ];
1635 for _ in 0..n {
1636 spec.push(("Ber", NodeShape::Box));
1637 }
1638 for _ in 0..n {
1639 spec.push(("y", NodeShape::FilledCircle));
1640 }
1641 spec.push(("2.0", NodeShape::Text));
1642 let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh)| node_size(*sh, l)).collect();
1643 let mut links = vec![(0, 1, "out"), (1, 2, ""), (9, 0, "a")];
1645 for i in 0..n {
1646 links.push((2, 3 + i, "p"));
1647 links.push((3 + i, 3 + n + i, "out"));
1648 }
1649 let gnodes: Vec<GraphNode> = sizes
1650 .iter()
1651 .map(|b| GraphNode {
1652 w: b.w,
1653 h: b.h,
1654 ..Default::default()
1655 })
1656 .collect();
1657 let gedges: Vec<GraphEdge> = links
1658 .iter()
1659 .map(|&(a, b, _)| GraphEdge {
1660 from: a,
1661 to: b,
1662 label_w: None,
1663 })
1664 .collect();
1665 let params = LayeredParams {
1667 margin: 32.0,
1668 ..Default::default()
1669 };
1670 let l = layered(&gnodes, &gedges, ¶ms);
1671 let nodes: Vec<DrawNode> = spec
1672 .iter()
1673 .zip(&sizes)
1674 .enumerate()
1675 .map(|(i, ((_, shape), b))| DrawNode {
1676 id: format!("n{i}"),
1677 shape: *shape,
1678 lines: b.lines.clone(),
1679 stroke: (60, 60, 60),
1680 tooltip: b.lines.join(" "),
1681 attrs: vec![("node".to_string(), Some(format!("n{i}")))],
1682 belief: (i == 1).then(|| (vec![0.0, 0.3, 1.0, 0.3, 0.0], (120, 80, 200))),
1684 prior: (i == 1).then(|| (vec![0.2, 0.4, 0.5, 0.4, 0.2], (150, 150, 150))),
1686 ..Default::default()
1687 })
1688 .collect();
1689 let edges: Vec<DrawEdge> = links
1690 .iter()
1691 .map(|&(a, b, iface)| DrawEdge {
1692 colour: (90, 90, 90),
1693 width: 1.2,
1694 undirected: true,
1695 label: (!iface.is_empty()).then(|| iface.to_string()),
1696 label_at: Some(if spec[b].1 == NodeShape::Box {
1698 0.8
1699 } else {
1700 0.2
1701 }),
1702 attrs: vec![("edge".to_string(), Some(format!("{a}>{b}")))],
1703 ..Default::default()
1704 })
1705 .collect();
1706 let plates = [Plate {
1707 label: "i = 1..3".to_string(),
1708 nodes: (3..3 + 2 * n).collect(),
1709 }];
1710 let style = GraphStyle::default();
1711 let svg = draw(
1712 &l,
1713 &[],
1714 &plates,
1715 &nodes,
1716 &edges,
1717 &style,
1718 crate::theme::presets::theme_void(),
1719 )
1720 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1721 .unwrap();
1722 assert_eq!(svg.matches("data-node=").count(), spec.len());
1724 for shape in ["circle", "filled-circle", "square", "text"] {
1725 assert!(svg.contains(&format!("gg-graph-node-{shape}")), "{shape}");
1726 }
1727 assert!(
1728 !svg.contains("data-part=\"arrow\""),
1729 "an undirected edge has no arrowhead"
1730 );
1731 assert_eq!(svg.matches("data-edge=").count(), links.len());
1732 assert!(svg.contains("gg-graph-node-belief"), "belief layer");
1734 assert!(svg.contains("fill=\"#7850C8\""), "belief colour");
1735 let (pr, be) = (
1737 svg.find("gg-graph-node-prior").expect("prior layer"),
1738 svg.find("gg-graph-node-belief").unwrap(),
1739 );
1740 assert!(pr < be, "the prior under the belief");
1741 let mark = &svg[svg[..pr].rfind('<').unwrap()..pr];
1742 assert!(mark.contains("stroke-dasharray"), "dashed prior: {mark}");
1743 assert!(!svg.contains("font-style=\"italic\""), "plain labels");
1745 let math = GraphStyle {
1747 math_font: Some("STIX Two Math, serif".to_string()),
1748 glyph_fill: Some((240, 247, 246)),
1749 glyph_ink: Some((13, 148, 136)),
1750 ..style.clone()
1751 };
1752 let msvg = draw(
1753 &l,
1754 &[],
1755 &plates,
1756 &nodes,
1757 &edges,
1758 &math,
1759 crate::theme::presets::theme_void(),
1760 )
1761 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1762 .unwrap();
1763 assert!(msvg.contains("STIX Two Math"), "math font");
1764 assert!(msvg.contains("font-style=\"italic\""), "italic labels");
1765 let two = msvg.find(">2.0<").expect("the constant 2.0");
1767 let el = &msvg[msvg[..two].rfind('<').unwrap()..two];
1768 assert!(!el.contains("italic"), "upright constant: {el}");
1769 assert!(svg.contains("data-plate=\"i = 1..3\"") && svg.contains(">i = 1..3<"));
1771 assert!(svg.contains(&format!(
1773 "fill=\"{}\"",
1774 hex(style.observed_fill).to_uppercase()
1775 )));
1776 for (i, a) in l.nodes.iter().enumerate() {
1778 for b in &l.nodes[i + 1..] {
1779 let apart = (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
1780 || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0;
1781 assert!(apart, "overlap");
1782 }
1783 }
1784 let c = &l.nodes[1];
1786 assert!(svg.contains(&format!("rx=\"{:.2}\"", c.w / 2.0)), "{}", c.w);
1787 }
1788
1789 #[test]
1793 fn banded_hmm_keeps_the_state_chain_straight() {
1794 use crate::graph_layout::{banded, BandedParams};
1795 let t_n = 5;
1796 let mut spec: Vec<(String, NodeShape, usize)> = vec![
1798 ("Dir".into(), NodeShape::Glyph, 0), ("A".into(), NodeShape::Square, 0), ("Dir".into(), NodeShape::Glyph, 0), ("B".into(), NodeShape::Square, 0), ("Cat".into(), NodeShape::Glyph, 1), ("s₀".into(), NodeShape::Circle, 1), ];
1805 let mut links: Vec<(usize, usize, &str)> =
1806 vec![(0, 1, "out"), (2, 3, "out"), (4, 5, "out")];
1807 let mut prev = 5;
1808 for t in 1..=t_n {
1809 let tr = spec.len();
1810 spec.push(("T".into(), NodeShape::Glyph, 1));
1811 let eq = spec.len();
1812 spec.push((format!("s{t}"), NodeShape::Square, 1));
1813 let ob = spec.len();
1814 spec.push(("T".into(), NodeShape::Glyph, 2));
1815 let x = spec.len();
1816 spec.push((format!("x{t}"), NodeShape::FilledCircle, 2));
1817 links.extend([
1818 (prev, tr, "in"),
1819 (1, tr, "a"),
1820 (tr, eq, "out"),
1821 (eq, ob, "in"),
1822 (3, ob, "a"),
1823 (ob, x, "out"),
1824 ]);
1825 prev = eq;
1826 }
1827 let sizes: Vec<NodeBox> = spec.iter().map(|(l, sh, _)| node_size(*sh, l)).collect();
1828 let gnodes: Vec<GraphNode> = spec
1829 .iter()
1830 .zip(&sizes)
1831 .map(|((_, _, b), s)| GraphNode {
1832 w: s.w,
1833 h: s.h,
1834 lane: Some(*b),
1835 ..Default::default()
1836 })
1837 .collect();
1838 let gedges: Vec<GraphEdge> = links
1839 .iter()
1840 .map(|&(a, b, _)| GraphEdge {
1841 from: a,
1842 to: b,
1843 label_w: None,
1844 })
1845 .collect();
1846 let l = banded(
1847 &gnodes,
1848 &gedges,
1849 &BandedParams {
1850 bands: 3,
1851 margin: 32.0,
1852 ..Default::default()
1853 },
1854 );
1855 let chain: Vec<usize> = (0..spec.len())
1857 .filter(|&i| spec[i].2 == 1 && i != 4)
1858 .collect();
1859 let y = l.nodes[chain[0]].cy;
1860 for &i in &chain {
1861 assert_eq!(l.nodes[i].cy, y, "{} off the row", spec[i].0);
1862 }
1863 for t in 0..t_n {
1865 let (eq, ob) = (6 + 4 * t + 1, 6 + 4 * t + 2);
1866 assert_eq!(l.nodes[eq].cx, l.nodes[ob].cx, "slice {t}");
1867 assert!(l.nodes[ob].cy > y);
1868 }
1869 let crosses = |(x0, y0): (f64, f64), (x1, y1): (f64, f64), n: &PlacedNode| {
1871 (0..=40).any(|k| {
1873 let t = k as f64 / 40.0;
1874 let (x, y) = (x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
1875 (x - n.cx).abs() < n.w / 2.0 - 1.0 && (y - n.cy).abs() < n.h / 2.0 - 1.0
1876 })
1877 };
1878 for (k, &(a, b, _)) in links.iter().enumerate() {
1879 for w in l.edges[k].windows(2) {
1880 for (i, n) in l.nodes.iter().enumerate() {
1881 if i != a && i != b {
1882 assert!(
1883 !crosses(w[0], w[1], n),
1884 "edge {a}->{b} crosses {}",
1885 spec[i].0
1886 );
1887 }
1888 }
1889 }
1890 }
1891 for (i, a) in l.nodes.iter().enumerate() {
1893 for b in &l.nodes[i + 1..] {
1894 assert!(
1895 (a.cx - b.cx).abs() >= (a.w + b.w) / 2.0
1896 || (a.cy - b.cy).abs() >= (a.h + b.h) / 2.0
1897 );
1898 }
1899 }
1900 let nodes: Vec<DrawNode> = spec
1901 .iter()
1902 .zip(&sizes)
1903 .enumerate()
1904 .map(|(i, ((_, shape, _), b))| DrawNode {
1905 id: format!("n{i}"),
1906 shape: *shape,
1907 lines: b.lines.clone(),
1908 stroke: (60, 60, 60),
1909 ..Default::default()
1910 })
1911 .collect();
1912 let edges: Vec<DrawEdge> = links
1913 .iter()
1914 .map(|&(_, b, iface)| DrawEdge {
1915 colour: (90, 90, 90),
1916 width: 1.2,
1917 undirected: true,
1918 label: Some(iface.to_string()),
1919 label_at: Some(if spec[b].1 == NodeShape::Glyph {
1920 0.8
1921 } else {
1922 0.2
1923 }),
1924 ..Default::default()
1925 })
1926 .collect();
1927 let lanes = ["param".to_string(), "state".to_string(), "obs".to_string()];
1928 let svg = draw(
1929 &l,
1930 &lanes,
1931 &[],
1932 &nodes,
1933 &edges,
1934 &GraphStyle::default(),
1935 crate::theme::presets::theme_void(),
1936 )
1937 .render_svg_native_at(0.0, 0.0, l.w.ceil() as u32, l.h.ceil() as u32)
1938 .unwrap();
1939 if let Ok(path) = std::env::var("GGPLOT_GRAPH_SVG") {
1940 std::fs::write(path, &svg).unwrap();
1941 }
1942 assert_eq!(svg.matches("data-lane=").count(), 3);
1943 }
1944}