1use std::collections::{BTreeMap, HashMap};
7
8pub use facett_core::{Edge, Facet, FacetCaps, Layout, Node, Scene, Theme, draw, hash_color, set_theme, theme};
9
10mod depgraph;
11pub use depgraph::{DepEdge, DepGraphView, DepNode, draw_arrow};
12
13pub fn scene_from_labeled_edges<I>(rows: I) -> Scene
18where
19 I: IntoIterator<Item = (i64, i64, String, String)>,
20{
21 let mut scene = Scene::new();
22 let mut idx: HashMap<i64, usize> = HashMap::new();
23 for (s, d, sl, dl) in rows {
24 let si = *idx.entry(s).or_insert_with(|| scene.node(sl.clone(), hash_color(&sl)));
25 let di = *idx.entry(d).or_insert_with(|| scene.node(dl.clone(), hash_color(&dl)));
26 scene.edge(si, di);
27 }
28 scene
29}
30
31pub struct GraphView {
34 pub scene: Scene,
35 pub layout: Layout,
36 pub empty_hint: String,
37 pub title: String,
38}
39
40impl GraphView {
41 pub fn new(scene: Scene) -> Self {
42 Self { scene, layout: Layout::default(), empty_hint: "empty".into(), title: "graph".into() }
43 }
44 pub fn empty_hint(mut self, hint: impl Into<String>) -> Self {
45 self.empty_hint = hint.into();
46 self
47 }
48 pub fn with_title(mut self, title: impl Into<String>) -> Self {
49 self.title = title.into();
50 self
51 }
52 pub fn show(&self, ui: &mut egui::Ui) {
53 draw(ui, &self.scene, self.layout, &self.empty_hint);
54 }
55 pub fn label_counts(&self) -> BTreeMap<String, usize> {
57 let mut m = BTreeMap::new();
58 for n in &self.scene.nodes {
59 *m.entry(n.label.clone()).or_insert(0) += 1;
60 }
61 m
62 }
63}
64
65impl Facet for GraphView {
66 fn title(&self) -> &str {
67 &self.title
68 }
69 fn ui(&mut self, ui: &mut egui::Ui) {
70 self.show(ui);
71 }
72 fn state_json(&self) -> serde_json::Value {
73 serde_json::json!({
74 "nodes": self.scene.nodes.len(),
75 "edges": self.scene.edges.len(),
76 "labels": self.label_counts(),
77 })
78 }
79 fn caps(&self) -> FacetCaps {
82 FacetCaps::NONE.themeable().resizable()
83 }
84}
85
86#[cfg(test)]
87mod tests {
88 use super::*;
89
90 #[test]
91 fn builds_scene_from_labeled_edges() {
92 let scene = scene_from_labeled_edges(vec![
93 (1, 2, "Person".into(), "Company".into()),
94 (1, 3, "Person".into(), "Address".into()),
95 ]);
96 assert_eq!(scene.nodes.len(), 3, "1, 2, 3 distinct");
97 assert_eq!(scene.edges.len(), 2);
98 assert_eq!(scene.nodes[0].label, "Person");
99 }
100}