facett-graphview 0.1.8

facett — a vello-backed, domain-agnostic scalable 2D graph render engine. Runtime-selects vello (GPU/wgpu) when a usable GPU exists, vello_cpu (multithreaded SIMD) as the no-GPU fallback. The eventual home for every graph surface (dep/arch/release dashboards, korp, graph-DB browsing).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! **DecoratedGraphView** — the egui Facet that paints a [`GraphModel`] under a
//! caller-supplied [`Decorations`] overlay (per-node status **rings** + corner
//! **badges**, plus emphasis **edges** drawn on top), with pan/drag + scroll-zoom
//! and click-to-select (lighting the clicked node's downstream subtree). It is
//! the egui twin of nornir's `src/viz/graph_render.rs::draw_graph` — the same
//! decorations layer the existing `facett-graphview` render model lacked a *view*
//! for (the CPU/GPU rasterizer renders to RGBA; this is the interactive egui
//! pane). Domain-agnostic: facett never learns what a "release gate" is — rings,
//! badges, and cut edges are opaque [`Decorations`].
//!
//! Canonical [`Facet`]: `local()`/`remote()`, `state_json()` (the painted nodes +
//! their decorations + the lit downstream set), `selection_json()`, `caps()`.

use std::collections::{BTreeSet, HashMap, VecDeque};

use facett_core::{Facet, FacetCaps, Semantics};

use crate::model::{Color, Decorations, GraphEdge, GraphModel, GraphNode, NodeDecoration, Pos, BOX_H, BOX_W};

/// The downstream-reachable set (BFS over forward edges) from `seed`, in node-id
/// space — the visual twin of an `arch trace`, used to dim everything off the lit
/// path when a node is selected.
pub fn downstream_of(model: &GraphModel, seed: &str) -> BTreeSet<String> {
    let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
    for e in &model.edges {
        adj.entry(e.from.as_str()).or_default().push(e.to.as_str());
    }
    let mut lit: BTreeSet<String> = BTreeSet::new();
    let mut q: VecDeque<&str> = VecDeque::new();
    lit.insert(seed.to_string());
    q.push_back(seed);
    while let Some(cur) = q.pop_front() {
        if let Some(outs) = adj.get(cur) {
            for &nxt in outs {
                if lit.insert(nxt.to_string()) {
                    q.push_back(nxt);
                }
            }
        }
    }
    lit
}

/// An interactive, decorated pan/zoom graph pane Facet.
pub struct DecoratedGraphView {
    title: String,
    model: GraphModel,
    decorations: Decorations,
    pan: egui::Vec2,
    zoom: f32,
    selected: Option<String>,
}

impl DecoratedGraphView {
    /// An empty pane titled `title`.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            model: GraphModel::default(),
            decorations: Decorations::default(),
            pan: egui::Vec2::ZERO,
            zoom: 1.0,
            selected: None,
        }
    }

    /// Set the graph model (nodes already laid out in world space + edges).
    pub fn with_model(mut self, model: GraphModel) -> Self {
        self.model = model;
        self
    }

    /// Set the decorations overlay (rings/badges + emphasis edges).
    pub fn with_decorations(mut self, decorations: Decorations) -> Self {
        self.decorations = decorations;
        self
    }

    /// Re-title (the deck keys facets off [`Facet::title`]).
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = title.into();
    }

    /// Reset pan + zoom (the ⊙ fit affordance).
    pub fn fit(&mut self) {
        self.pan = egui::Vec2::ZERO;
        self.zoom = 1.0;
    }

    /// Select a node by id (lights its downstream subtree), or `None` to clear.
    pub fn select(&mut self, id: Option<String>) {
        self.selected = id;
    }

    /// The downstream-lit set for the current selection (empty when none).
    pub fn lit_set(&self) -> BTreeSet<String> {
        self.selected.as_deref().map(|s| downstream_of(&self.model, s)).unwrap_or_default()
    }

    /// **Discovery-contract `local()`** — a realistic 4-node DAG (a → b, a → c,
    /// b → d, c → d) decorated with a green coverage ring on `a`, an amber badge
    /// on `b`, and an emphasis "cut" edge `d → a` (dashed, labelled), so the pane
    /// paints real chips, rings, a badge, and an overlay edge with no host.
    pub fn local() -> Self {
        let n = |id: &str, label: &str, x: f32, y: f32, fill: Color| GraphNode {
            id: id.into(),
            label: label.into(),
            fill,
            stroke: Color::WHITE,
            pos: Pos::new(x, y),
        };
        let e = |from: &str, to: &str, dashed: bool| GraphEdge {
            from: from.into(),
            to: to.into(),
            color: Color::rgb(200, 200, 220),
            dashed,
            label: None,
        };
        let model = GraphModel {
            nodes: vec![
                n("a", "alpha", 0.0, 0.0, Color::rgb(60, 90, 160)),
                n("b", "beta", 260.0, -90.0, Color::rgb(60, 140, 90)),
                n("c", "gamma", 260.0, 90.0, Color::rgb(160, 90, 60)),
                n("d", "delta", 520.0, 0.0, Color::rgb(120, 90, 160)),
            ],
            edges: vec![e("a", "b", false), e("a", "c", false), e("b", "d", false), e("c", "d", false)],
        };
        let mut nodes = HashMap::new();
        nodes.insert(
            "a".to_string(),
            NodeDecoration { ring: Some(Color::rgb(90, 200, 140)), ..Default::default() },
        );
        nodes.insert(
            "b".to_string(),
            NodeDecoration {
                badge: Some("".into()),
                badge_color: Some(Color::rgb(230, 180, 60)),
                ..Default::default()
            },
        );
        let decorations = Decorations {
            nodes,
            edges: vec![GraphEdge {
                from: "d".into(),
                to: "a".into(),
                color: Color::rgb(230, 90, 90),
                dashed: true,
                label: Some("cut".into()),
            }],
        };
        Self::new("DecoratedGraph").with_model(model).with_decorations(decorations)
    }

    /// **Discovery-contract `remote()`** — same surface, re-titled; the variant a
    /// host builds from a server-streamed model. Kept so the matrix sees both ctors.
    pub fn remote() -> Self {
        let mut v = Self::local();
        v.title = "DecoratedGraph (remote)".into();
        v
    }

    fn col(c: Color) -> egui::Color32 {
        c.into()
    }
}

impl Facet for DecoratedGraphView {
    fn title(&self) -> &str {
        &self.title
    }

    fn ui(&mut self, ui: &mut egui::Ui) {
        let th = facett_core::theme(ui);
        if self.zoom <= 0.0 {
            self.zoom = 1.0;
        }

        // ── header: counts + a fit button ─────────────────────────────────
        ui.horizontal_wrapped(|ui| {
            ui.label(
                egui::RichText::new(format!("{} nodes · {} edges", self.model.nodes.len(), self.model.edges.len()))
                    .color(th.text)
                    .strong(),
            );
            ui.separator();
            ui.label(
                egui::RichText::new(format!("{} ring(s) · {} badge(s)",
                    self.decorations.nodes.values().filter(|d| d.ring.is_some()).count(),
                    self.decorations.nodes.values().filter(|d| d.badge.is_some()).count(),
                ))
                .color(th.text_dim),
            );
            if ui.button("⊙ fit").clicked() {
                self.fit();
            }
        });
        ui.separator();

        let (resp, painter) = ui.allocate_painter(ui.available_size(), egui::Sense::click_and_drag());
        painter.rect_filled(resp.rect, 4.0, th.bg);
        if resp.dragged() {
            self.pan += resp.drag_delta();
        }
        if resp.hovered() {
            let scroll = ui.input(|i| i.smooth_scroll_delta.y);
            if scroll != 0.0 {
                self.zoom = (self.zoom * (1.0 + scroll * 0.001)).clamp(0.25, 4.0);
            }
        }
        let origin = resp.rect.center() + self.pan;
        let zoom = self.zoom;
        let project = |p: Pos| origin + egui::vec2(p.x, p.y) * zoom;

        // click-to-select.
        if let Some(click) = resp.clicked().then(|| resp.interact_pointer_pos()).flatten() {
            let hit = self.model.nodes.iter().find_map(|nd| {
                let c = project(nd.pos);
                let rect = egui::Rect::from_center_size(c, egui::vec2(BOX_W, BOX_H) * zoom);
                rect.contains(click).then(|| nd.id.clone())
            });
            self.selected = hit;
        }

        let lit = self.lit_set();
        let highlighting = self.selected.is_some();
        let dim = |c: egui::Color32| c.linear_multiply(0.22);

        let idx: HashMap<&str, &GraphNode> =
            self.model.nodes.iter().map(|n| (n.id.as_str(), n)).collect();

        // edges first.
        let draw_edge = |e: &GraphEdge, emphasise: bool| {
            let (Some(fa), Some(fb)) = (idx.get(e.from.as_str()), idx.get(e.to.as_str())) else {
                return;
            };
            let on_trace = highlighting && lit.contains(&e.from) && lit.contains(&e.to);
            let a = project(fa.pos) + egui::vec2(BOX_W * 0.5 * zoom, 0.0);
            let b = project(fb.pos) - egui::vec2(BOX_W * 0.5 * zoom, 0.0);
            let mut color = Self::col(e.color);
            if !emphasise && highlighting && !on_trace {
                color = dim(color);
            }
            let w = if emphasise { 2.6 } else if on_trace { 2.4 } else { 1.4 };
            if e.dashed {
                // sampled dashed line.
                let n = 16;
                for i in 0..n {
                    if i % 2 == 0 {
                        let t0 = i as f32 / n as f32;
                        let t1 = (i + 1) as f32 / n as f32;
                        painter.line_segment([a.lerp(b, t0), a.lerp(b, t1)], egui::Stroke::new(w, color));
                    }
                }
            } else {
                painter.line_segment([a, b], egui::Stroke::new(w, color));
            }
            // arrowhead.
            let dir = (b - a).normalized();
            let perp = egui::vec2(-dir.y, dir.x);
            let head = 6.0 * zoom.clamp(0.6, 1.6);
            painter.line_segment([b, b - dir * head + perp * head * 0.5], egui::Stroke::new(w, color));
            painter.line_segment([b, b - dir * head - perp * head * 0.5], egui::Stroke::new(w, color));
            if let Some(lbl) = &e.label {
                if zoom > 0.45 && !lbl.is_empty() {
                    painter.text(
                        a.lerp(b, 0.5) - egui::vec2(0.0, 6.0 * zoom),
                        egui::Align2::CENTER_BOTTOM,
                        lbl,
                        egui::FontId::proportional(10.0 * zoom.clamp(0.7, 1.3)),
                        if emphasise { color } else { th.text_dim },
                    );
                }
            }
        };
        for e in &self.model.edges {
            draw_edge(e, false);
        }
        for e in &self.decorations.edges {
            draw_edge(e, true);
        }

        // chips.
        for nd in &self.model.nodes {
            let c = project(nd.pos);
            let on_trace = highlighting && lit.contains(&nd.id);
            let mut fill = Self::col(nd.fill);
            let mut stroke = Self::col(nd.stroke);
            if highlighting && !on_trace {
                fill = dim(fill);
                stroke = dim(stroke);
            }
            let rect = egui::Rect::from_center_size(c, egui::vec2(BOX_W, BOX_H) * zoom);
            painter.rect_filled(rect, 5.0 * zoom, fill);

            let deco = self.decorations.nodes.get(&nd.id);
            let ring = if self.selected.as_deref() == Some(nd.id.as_str()) {
                egui::Stroke::new(3.0, th.accent)
            } else if let Some(rc) = deco.and_then(|d| d.ring) {
                let rc = Self::col(rc);
                egui::Stroke::new(2.4, if highlighting && !on_trace { dim(rc) } else { rc })
            } else {
                egui::Stroke::new(1.4, stroke)
            };
            painter.rect_stroke(rect, 5.0 * zoom, ring, egui::epaint::StrokeKind::Outside);

            if zoom > 0.45 {
                painter.text(
                    c,
                    egui::Align2::CENTER_CENTER,
                    &nd.label,
                    egui::FontId::proportional(11.0 * zoom.clamp(0.7, 1.4)),
                    th.text,
                );
                if let Some(badge) = deco.and_then(|d| d.badge.as_deref()) {
                    let bc = deco.and_then(|d| d.badge_color).map(Self::col).unwrap_or(th.text);
                    painter.text(
                        rect.right_top() + egui::vec2(-2.0, 1.0),
                        egui::Align2::RIGHT_TOP,
                        badge,
                        egui::FontId::proportional(12.0 * zoom.clamp(0.7, 1.4)),
                        if highlighting && !on_trace { dim(bc) } else { bc },
                    );
                }
            }
        }

        // pane-level a11y summary.
        resp.widget_info(|| {
            Semantics::image(format!(
                "decorated graph — {} nodes, {} edges, selected {}",
                self.model.nodes.len(),
                self.model.edges.len(),
                self.selected.as_deref().unwrap_or("none"),
            ))
            .widget_info()
        });

        #[cfg(feature = "testmatrix")]
        facett_core::testmatrix::emit(
            "facett-graphview::DecoratedGraphView::ui",
            "ui_render",
            !self.model.nodes.is_empty(),
            &format!("nodes={} edges={} lit={}", self.model.nodes.len(), self.model.edges.len(), lit.len()),
        );
    }

    fn state_json(&self) -> serde_json::Value {
        let lit = self.lit_set();
        serde_json::json!({
            "title": self.title,
            "node_count": self.model.nodes.len(),
            "edge_count": self.model.edges.len(),
            "decoration_edges": self.decorations.edges.len(),
            "rings": self.decorations.nodes.values().filter(|d| d.ring.is_some()).count(),
            "badges": self.decorations.nodes.values().filter(|d| d.badge.is_some()).count(),
            "selected": self.selected,
            "lit": lit.iter().cloned().collect::<Vec<_>>(),
            "zoom": self.zoom,
            "nodes": self.model.nodes.iter().map(|n| {
                let d = self.decorations.nodes.get(&n.id);
                serde_json::json!({
                    "id": n.id,
                    "label": n.label,
                    "x": n.pos.x,
                    "y": n.pos.y,
                    "ring": d.and_then(|d| d.ring).is_some(),
                    "badge": d.and_then(|d| d.badge.clone()),
                })
            }).collect::<Vec<_>>(),
            "edges": self.model.edges.iter().map(|e| serde_json::json!({
                "from": e.from, "to": e.to, "dashed": e.dashed,
            })).collect::<Vec<_>>(),
        })
    }

    fn selection_json(&self) -> serde_json::Value {
        match &self.selected {
            Some(id) => serde_json::json!({ "node": id, "downstream": self.lit_set().iter().cloned().collect::<Vec<_>>() }),
            None => serde_json::Value::Null,
        }
    }

    /// Themed (chips/rings follow the palette) + resizable + selectable (a node
    /// drill-in) + navigable (pan/drag + scroll-zoom + fit).
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE.themeable().resizable().selectable().navigable()
    }

    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        Some(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn downstream_is_bfs_closure_from_seed() {
        let v = DecoratedGraphView::local();
        // a → b, a → c, b → d, c → d. Downstream of a = all; of b = {b, d}.
        let from_a = downstream_of(&v.model, "a");
        assert!(from_a.contains("a") && from_a.contains("b") && from_a.contains("c") && from_a.contains("d"));
        let from_b = downstream_of(&v.model, "b");
        assert!(from_b.contains("b") && from_b.contains("d"));
        assert!(!from_b.contains("a"), "BFS is forward-only");
        assert!(!from_b.contains("c"), "c is not downstream of b");
    }

    /// inject-assert (LAW 6): the local view seeds a real decorated graph; assert
    /// its `state_json` reports the nodes, the ring + badge decorations, the
    /// emphasis edge, and — after a selection — the lit downstream set.
    #[test]
    fn local_view_reports_decorations_and_selection() {
        let mut v = DecoratedGraphView::local();
        let j = v.state_json();
        assert_eq!(<DecoratedGraphView as Facet>::title(&v), "DecoratedGraph");
        assert_eq!(j["node_count"], 4);
        assert_eq!(j["edge_count"], 4);
        assert_eq!(j["decoration_edges"], 1, "the dashed cut edge");
        assert_eq!(j["rings"], 1, "a green coverage ring on `a`");
        assert_eq!(j["badges"], 1, "a ⚠ badge on `b`");
        // node `a` carries a ring, `b` carries the badge text.
        let nodes = j["nodes"].as_array().unwrap();
        let a = nodes.iter().find(|n| n["id"] == "a").unwrap();
        assert_eq!(a["ring"], true);
        let b = nodes.iter().find(|n| n["id"] == "b").unwrap();
        assert_eq!(b["badge"], "");
        // no selection → null + empty lit set.
        assert_eq!(j["selected"], serde_json::Value::Null);
        assert!(j["lit"].as_array().unwrap().is_empty());

        // select `b` → the lit set is its downstream {b, d}.
        v.select(Some("b".into()));
        let j2 = v.state_json();
        assert_eq!(j2["selected"], "b");
        let lit: BTreeSet<String> =
            j2["lit"].as_array().unwrap().iter().map(|x| x.as_str().unwrap().to_string()).collect();
        assert_eq!(lit, ["b", "d"].iter().map(|s| s.to_string()).collect::<BTreeSet<_>>());
        let sel = v.selection_json();
        assert_eq!(sel["node"], "b");
    }

    #[test]
    fn fit_resets_pan_and_zoom() {
        let mut v = DecoratedGraphView::local();
        v.pan = egui::vec2(20.0, 10.0);
        v.zoom = 2.5;
        v.fit();
        assert_eq!(v.pan, egui::Vec2::ZERO);
        assert_eq!(v.zoom, 1.0);
        assert_eq!(<DecoratedGraphView as Facet>::title(&DecoratedGraphView::remote()), "DecoratedGraph (remote)");
    }
}