facett-graphview 0.1.11

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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! **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::clip::{ClipKind, ClipPayload, CopySource};
use facett_core::{FacetCaps, Semantics};
use serde::{Deserialize, Serialize};

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
}

/// A robot-/CLI-addressable control message (FC-2) — the named boundary a headless
/// driver (or a host) drives the pane through, the same effect a canvas
/// click/drag/scroll produces. Applied by [`DecoratedGraphView::update`].
#[derive(Clone, Debug, PartialEq)]
pub enum Msg {
    /// Select a node by stable id (lights its downstream subtree), or `None` to clear.
    Select(Option<String>),
    /// Pan the camera by a screen-space delta (the drag gesture).
    PanBy(f32, f32),
    /// Zoom by a scroll amount (multiplicative, clamped) — the scroll-wheel gesture.
    ZoomBy(f32),
    /// Reset pan + zoom (the ⊙ fit affordance).
    Fit,
}

/// Side work as data (FC-8). The pane does no I/O — every [`Msg`] mutates only the
/// in-memory [`GraphViewState`] — so this is uninhabited on purpose: the type-checked
/// statement that [`DecoratedGraphView::update`] never asks the host to do anything.
#[derive(Clone, Debug, PartialEq)]
pub enum Effect {}

/// **The complete observable state (FC-1 / FC-3)** of a [`DecoratedGraphView`], in one
/// serializable, round-trippable struct: the laid-out [`GraphModel`], the
/// caller-supplied [`Decorations`] overlay, the selected node (keyed on its stable
/// id, FC-5), and the camera (pan + zoom). [`DecoratedGraphView::state`] hands back a
/// `&GraphViewState`; a headless driver ([`facett_core::harness`]) snapshots it after
/// feeding a `Vec<Msg>`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphViewState {
    /// The graph to paint (nodes laid out in world space + edges).
    pub model: GraphModel,
    /// The caller-supplied ring/badge + emphasis-edge overlay.
    pub decorations: Decorations,
    /// The selected node id, if any (lights its downstream subtree).
    pub selected: Option<String>,
    /// Camera pan (screen-space) — the x component.
    pub pan_x: f32,
    /// Camera pan (screen-space) — the y component.
    pub pan_y: f32,
    /// Camera zoom (world→screen scale), clamped to `[0.25, 4.0]` by interaction.
    pub zoom: f32,
}

impl Default for GraphViewState {
    fn default() -> Self {
        Self {
            model: GraphModel::default(),
            decorations: Decorations::default(),
            selected: None,
            pan_x: 0.0,
            pan_y: 0.0,
            zoom: 1.0,
        }
    }
}

/// An interactive, decorated pan/zoom graph pane Facet.
pub struct DecoratedGraphView {
    title: String,
    /// All observable state (FC-3).
    state: GraphViewState,
}

impl DecoratedGraphView {
    /// An empty pane titled `title`.
    pub fn new(title: impl Into<String>) -> Self {
        Self { title: title.into(), state: GraphViewState::default() }
    }

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

    /// Set the decorations overlay (rings/badges + emphasis edges).
    pub fn with_decorations(mut self, decorations: Decorations) -> Self {
        self.state.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();
    }

    /// **FC-3** — read the complete observable state at any frame boundary.
    pub fn state(&self) -> &GraphViewState {
        &self.state
    }

    /// **FC-2 / FC-8** — the single mutation path. Apply one [`Msg`]; returns the
    /// (always empty) [`Effect`]s the host should run. The canvas click/drag/scroll
    /// and the fit button all route their [`Msg`] here too, so live == headless.
    pub fn update(&mut self, msg: Msg) -> Vec<Effect> {
        match msg {
            Msg::Select(id) => self.state.selected = id,
            Msg::PanBy(dx, dy) => {
                self.state.pan_x += dx;
                self.state.pan_y += dy;
            }
            Msg::ZoomBy(scroll) => {
                self.state.zoom = (self.state.zoom * (1.0 + scroll * 0.001)).clamp(0.25, 4.0);
            }
            Msg::Fit => {
                self.state.pan_x = 0.0;
                self.state.pan_y = 0.0;
                self.state.zoom = 1.0;
            }
        }
        Vec::new()
    }

    /// Reset pan + zoom (the ⊙ fit affordance). A thin wrapper over the FC-2
    /// [`update`](Self::update) mutation path.
    pub fn fit(&mut self) {
        let _ = self.update(Msg::Fit);
    }

    /// Select a node by id (lights its downstream subtree), or `None` to clear. A thin
    /// wrapper over the FC-2 [`update`](Self::update) mutation path.
    pub fn select(&mut self, id: Option<String>) {
        let _ = self.update(Msg::Select(id));
    }

    /// The downstream-lit set for the current selection (empty when none).
    pub fn lit_set(&self) -> BTreeSet<String> {
        self.state.selected.as_deref().map(|s| downstream_of(&self.state.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 DecoratedGraphView {
    /// The copyable text: the selected node's `label` when one is selected, else
    /// every node label, one per line.
    pub fn copy_text(&self) -> Option<String> {
        if self.state.model.nodes.is_empty() {
            return None;
        }
        if let Some(id) = self.state.selected.as_deref() {
            if let Some(n) = self.state.model.nodes.iter().find(|n| n.id == id) {
                return Some(n.label.clone());
            }
        }
        Some(self.state.model.nodes.iter().map(|n| n.label.clone()).collect::<Vec<_>>().join("\n"))
    }
}

// ── typed copy (§16) — read-only: selected node label or the label list ───────
impl CopySource for DecoratedGraphView {
    fn copy_kinds(&self) -> &[ClipKind] {
        &[ClipKind::Text]
    }
    fn copy_payload(&self) -> Option<ClipPayload> {
        self.copy_text().map(ClipPayload::Text)
    }
}

impl DecoratedGraphView {
    /// **FC-9 render** — a **pure** function of `&self`: it paints the header, the
    /// edges + decorated chips, and *returns* the [`Msg`]s the interactions produced
    /// (fit / pan / zoom / node-select). It MUST NOT mutate the [`GraphViewState`];
    /// the [`impl_facet_via_elm!`](facett_core::impl_facet_via_elm) bridge applies the
    /// returned messages through [`update`](Self::update). One-frame latency on the
    /// camera + selection is the standard immediate-mode Elm trade (a repaint follows).
    pub fn view(&self, ui: &mut egui::Ui) -> Vec<Msg> {
        let mut msgs: Vec<Msg> = Vec::new();
        let th = facett_core::theme(ui);
        // Effective zoom for this frame's projection: never paint at a non-positive
        // scale. Read-only — the stored zoom is kept valid by `update`'s clamp.
        let zoom = if self.state.zoom > 0.0 { self.state.zoom } else { 1.0 };

        // ── header: counts + a fit button ─────────────────────────────────
        ui.horizontal_wrapped(|ui| {
            ui.label(
                egui::RichText::new(format!("{} nodes · {} edges", self.state.model.nodes.len(), self.state.model.edges.len()))
                    .color(th.text)
                    .strong(),
            );
            ui.separator();
            ui.label(
                egui::RichText::new(format!("{} ring(s) · {} badge(s)",
                    self.state.decorations.nodes.values().filter(|d| d.ring.is_some()).count(),
                    self.state.decorations.nodes.values().filter(|d| d.badge.is_some()).count(),
                ))
                .color(th.text_dim),
            );
            if ui.button("⊙ fit").clicked() {
                msgs.push(Msg::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() {
            let d = resp.drag_delta();
            msgs.push(Msg::PanBy(d.x, d.y));
        }
        if resp.hovered() {
            let scroll = ui.input(|i| i.smooth_scroll_delta.y);
            if scroll != 0.0 {
                msgs.push(Msg::ZoomBy(scroll));
            }
        }
        let origin = resp.rect.center() + egui::vec2(self.state.pan_x, self.state.pan_y);
        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.state.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())
            });
            msgs.push(Msg::Select(hit));
        }

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

        let idx: HashMap<&str, &GraphNode> =
            self.state.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.state.model.edges {
            draw_edge(e, false);
        }
        for e in &self.state.decorations.edges {
            draw_edge(e, true);
        }

        // chips.
        for nd in &self.state.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.state.decorations.nodes.get(&nd.id);
            let ring = if self.state.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.state.model.nodes.len(),
                self.state.model.edges.len(),
                self.state.selected.as_deref().unwrap_or("none"),
            ))
            .widget_info()
        });

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

        msgs
    }
}

// ── FC-2 / FC-3 / FC-8 / FC-9: the canonical Elm split ────────────────────────
impl facett_core::Elm for DecoratedGraphView {
    type Model = GraphViewState;
    type Msg = Msg;
    type Effect = Effect;

    fn title(&self) -> &str {
        &self.title
    }
    fn state(&self) -> &GraphViewState {
        &self.state
    }
    fn update(&mut self, msg: Msg) -> Vec<Effect> {
        DecoratedGraphView::update(self, msg)
    }
    fn view(&self, ui: &mut egui::Ui) -> Vec<Msg> {
        DecoratedGraphView::view(self, ui)
    }
}

// The bridge macro writes `impl Facet for DecoratedGraphView` from the `Elm` impl:
// `title`, the FC-9 `ui` loop (`for m in view(ui) { update(m) }`), plus the extra
// overrides below. **Form 3** (`custom_state_json`) because the pane publishes a
// RICHER `state_json` than a plain `serde(state())`: the derived counts (rings/badges),
// the lit downstream set, and the flattened per-node/per-edge introspection keys that
// facett-demo's mega_matrix reads are computed from the model + decorations, not the
// raw serde dump — so the default `state_json` is suppressed and this byte-for-byte
// one supplied.
facett_core::impl_facet_via_elm!(DecoratedGraphView, custom_state_json, {
    fn state_json(&self) -> serde_json::Value {
        let lit = self.lit_set();
        serde_json::json!({
            "title": self.title,
            "node_count": self.state.model.nodes.len(),
            "edge_count": self.state.model.edges.len(),
            "decoration_edges": self.state.decorations.edges.len(),
            "rings": self.state.decorations.nodes.values().filter(|d| d.ring.is_some()).count(),
            "badges": self.state.decorations.nodes.values().filter(|d| d.badge.is_some()).count(),
            "selected": self.state.selected,
            "lit": lit.iter().cloned().collect::<Vec<_>>(),
            "zoom": self.state.zoom,
            "nodes": self.state.model.nodes.iter().map(|n| {
                let d = self.state.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.state.model.edges.iter().map(|e| serde_json::json!({
                "from": e.from, "to": e.to, "dashed": e.dashed,
            })).collect::<Vec<_>>(),
        })
    }

    fn copy(&mut self) -> Option<String> {
        self.copy_payload().map(|p| p.as_text())
    }

    fn selection_json(&self) -> serde_json::Value {
        match &self.state.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().copyable()
    }

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

#[cfg(test)]
mod tests {
    use super::*;
    // `Facet` for `state_json`/`selection_json`/`title`/`caps`; `state()`/`select()`/
    // `update()`/`fit()` are inherent.
    use facett_core::Facet;

    #[test]
    fn typed_copy_is_selected_label_or_the_label_list() {
        use facett_core::clip::{ClipKind, CopySource};
        let mut v = DecoratedGraphView::local();
        // No selection -> a multi-line label list.
        let p = v.copy_payload().expect("populated graph copies");
        assert_eq!(p.kind(), ClipKind::Text);
        assert!(p.as_text().contains('\n'), "label list is multi-line: {}", p.as_text());
        // Select node "a" -> the copy narrows to that node's single label.
        v.select(Some("a".into()));
        let sel = v.copy_payload().unwrap().as_text();
        assert!(!sel.contains('\n'), "selected copy is one label: {sel}");
        assert_eq!(sel, v.state().model.nodes.iter().find(|n| n.id == "a").unwrap().label);
    }

    #[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.state().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.state().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.state.pan_x = 20.0;
        v.state.pan_y = 10.0;
        v.state.zoom = 2.5;
        v.fit();
        assert_eq!((v.state().pan_x, v.state().pan_y), (0.0, 0.0));
        assert_eq!(v.state().zoom, 1.0);
        assert_eq!(<DecoratedGraphView as Facet>::title(&DecoratedGraphView::remote()), "DecoratedGraph (remote)");
    }

    // ── FC-2 → FC-3 as a *headless* property: feed a `Vec<Msg>` through the core
    //    harness and assert the resulting `GraphViewState` — no egui, no GPU. ──────
    #[test]
    fn harness_snapshot_drives_camera_and_selection() {
        use facett_core::harness;
        let mut v = DecoratedGraphView::local();
        // Pan + zoom + select are all observable in the headless snapshot.
        let snap = harness::snapshot(
            &mut v,
            [Msg::PanBy(12.0, -4.0), Msg::ZoomBy(500.0), Msg::Select(Some("b".into()))],
        );
        assert_eq!((snap.pan_x, snap.pan_y), (12.0, -4.0), "pan accumulates");
        assert!(snap.zoom > 1.0 && snap.zoom <= 4.0, "zoom grows but stays clamped: {}", snap.zoom);
        assert_eq!(snap.selected.as_deref(), Some("b"), "selection is observable headlessly");
        assert_eq!(&snap, v.state(), "the snapshot is a clone of the live state");
        // Fit resets the camera; ZoomBy is clamped at the low end too.
        let snap = harness::snapshot(&mut v, [Msg::ZoomBy(-100000.0), Msg::Fit]);
        assert_eq!((snap.pan_x, snap.pan_y, snap.zoom), (0.0, 0.0, 1.0), "Fit re-centers + unit-zooms");
    }

    #[test]
    fn drive_reports_no_effects_and_state_round_trips() {
        use facett_core::harness;
        let mut v = DecoratedGraphView::local();
        // FC-8: the pane does no I/O, so the effect stream is always empty.
        let effects = harness::drive(&mut v, [Msg::Select(Some("a".into())), Msg::PanBy(3.0, 3.0)]);
        assert!(effects.is_empty(), "FC-8: the pane emits no Effects");
        // FC-3: the observable Model (graph + decorations + camera + selection)
        // round-trips through serde.
        let json = serde_json::to_value(v.state()).unwrap();
        assert_eq!(json["selected"], "a");
        let back: GraphViewState = serde_json::from_value(json).unwrap();
        assert_eq!(&back, v.state(), "serde(state) -> state round-trips (the whole graph survives)");
    }

    /// FC-5: node selection is keyed on the **stable node id**, so it survives a full
    /// re-layout — moving every node to new world coordinates leaves the selection and
    /// its lit downstream set intact (they resolve by id, never by position).
    #[test]
    fn selection_survives_relayout_on_stable_id() {
        use facett_core::harness;
        let mut v = DecoratedGraphView::local();
        let _ = harness::drive(&mut v, [Msg::Select(Some("b".into()))]);
        let lit_before = v.lit_set();
        // Re-layout: shove every node to a fresh position (same ids + edges).
        let mut relaid = v.state().model.clone();
        for (i, n) in relaid.nodes.iter_mut().enumerate() {
            n.pos = Pos::new(1000.0 + i as f32 * 37.0, -500.0 - i as f32 * 19.0);
        }
        v = v.with_model(relaid);
        assert_eq!(v.state().selected.as_deref(), Some("b"), "selection keyed on id survives the move");
        assert_eq!(v.lit_set(), lit_before, "the lit downstream set is identical after re-layout");
        assert_eq!(v.selection_json()["node"], "b");
        // And the id still resolves to a (now-relocated) real node.
        assert!(v.state().model.nodes.iter().any(|n| n.id == "b"));
    }
}