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