facett-syschart 0.1.17

facett — system-map chart: free-positioned clickable nodes + edges with a per-node badge and an inline expandable detail panel
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! **facett-syschart** — a **system-map chart**: a handful of *free-positioned*
//! peer nodes (not a layered DAG) joined by edges, each carrying a **badge**
//! (a count / status number) and, when selected, an **inline expandable detail
//! panel**. Click a node to select it; its detail renders in a panel under the
//! canvas. The host owns *what* a node's detail is (a string here; richer hosts
//! draw their own widgets after `ui()` keyed off [`SystemChart::selected`]).
//!
//! This is the piece [`facett_core::draw`]/[`facett_graph::GraphView`] don't
//! cover — those paint a *non-interactive* `Scene`; `DepGraphView` is a
//! *layered* DAG with a fixed deps/dependents drill-down. A "monitoring map" of
//! a few peer systems (a PKI/OIDC/Nexus triangle, a service mesh) wants
//! deterministic positions, a per-node badge, click-select, and a free-form
//! detail panel — that's [`SystemChart`].
//!
//! ## FC-2 / FC-9 contract
//! Built on [`facett_core::Elm`]: the complete observable state lives in one
//! serializable [`SysChartModel`] ([`state`](facett_core::Elm::state)); every
//! input is a [`Msg`] applied through the single mutation path
//! [`update`](SystemChart::update) (FC-2); and [`view`](SystemChart::view) is a
//! **pure** function of `&self` that paints and *returns* the [`Msg`]s the frame
//! produced (FC-9). [`impl_facet_via_elm!`](facett_core::impl_facet_via_elm)
//! writes the `impl Facet` bridge (`for m in view(ui) { update(m) }`). A headless
//! driver ([`facett_core::harness`]) feeds a `Vec<Msg>` and snapshots
//! [`state`](facett_core::Elm::state) with no egui / no GPU.

use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, vec2};
use facett_core::clip::{ClipKind, ClipPayload, CopySource};
use facett_core::{FacetCaps, Semantics, a11y_node, theme};
use serde::{Deserialize, Serialize};

/// One system in the map. Positions are **normalized** (`0.0..=1.0` of the
/// canvas), so the layout is resolution-independent and deterministic — ideal
/// for headless rendering and screenshots.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SysNode {
    /// Stable id (used for selection + edges). Unique within a chart.
    pub id: String,
    /// Human label drawn next to the node.
    pub label: String,
    /// Node colour (the host picks the policy — by status, by hash, …).
    pub color: Color32,
    /// A small count/status badge drawn on the node (e.g. an event count).
    pub badge: u64,
    /// Normalized position in the canvas (`0,0` = top-left, `1,1` = bottom-right).
    pub pos: (f32, f32),
    /// Free-form detail shown in the inline panel when this node is selected.
    /// Hosts that draw richer detail can leave this empty and render their own
    /// widgets after `ui()` keyed off [`SystemChart::selected`].
    pub detail: String,
}

impl SysNode {
    pub fn new(id: impl Into<String>, label: impl Into<String>, color: Color32, pos: (f32, f32)) -> Self {
        Self { id: id.into(), label: label.into(), color, badge: 0, pos, detail: String::new() }
    }
    pub fn badge(mut self, n: u64) -> Self {
        self.badge = n;
        self
    }
    pub fn detail(mut self, d: impl Into<String>) -> Self {
        self.detail = d.into();
        self
    }
}

/// An undirected link between two node ids.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SysEdge {
    pub a: String,
    pub b: String,
}

impl SysEdge {
    pub fn new(a: impl Into<String>, b: impl Into<String>) -> Self {
        Self { a: a.into(), b: b.into() }
    }
}

/// A robot-/CLI-addressable control message — the named boundary a headless
/// driver (or a host toolbar) drives the chart through, the same effect the
/// canvas gestures produce. Applied by [`SystemChart::update`]; the pure
/// [`view`](SystemChart::view) *returns* these (it never mutates `self`).
#[derive(Clone, Debug, PartialEq)]
pub enum Msg {
    /// **Toggle**-select the node with this stable id: selecting the already-
    /// selected node clears it, an unknown id is a no-op (parity with the click).
    Select(String),
    /// Clear any selection.
    ClearSelection,
    /// Set a node's badge count by id (e.g. a live event count). No-op if unknown.
    SetBadge(String, u64),
    /// Set a node's detail text by id. No-op if unknown.
    SetDetail(String, String),
}

/// Side work as data (FC-8). The syschart does no I/O — every [`Msg`] mutates
/// only the in-memory [`SysChartModel`] — so this is uninhabited on purpose: the
/// type-checked statement that [`SystemChart::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 [`SystemChart`], in one
/// serializable, round-trippable struct: every node + edge, the selection (keyed
/// on the stable [`SysNode::id`], FC-5, so reorder/insert/delete preserves it),
/// and the canvas height. [`SystemChart::state`](facett_core::Elm::state) hands
/// back a `&SysChartModel`; a headless driver ([`facett_core::harness`]) snapshots
/// it after feeding a `Vec<Msg>`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SysChartModel {
    /// Free-positioned peer nodes.
    pub nodes: Vec<SysNode>,
    /// Undirected links between node ids.
    pub edges: Vec<SysEdge>,
    /// Stable id of the selected node (drives the detail panel), keyed on the
    /// domain id ([`SysNode::id`]) not an enumeration index (FC-5).
    pub selected: Option<String>,
    /// Height (px) the node canvas takes before the detail panel.
    pub canvas_h: f32,
}

/// The system-map chart [`Facet`](facett_core::Facet): a tab title plus the
/// complete observable [`SysChartModel`]. The FC-9 pure [`view`](Self::view) reads
/// it and the FC-2 [`update`](Self::update) is the sole path that mutates it.
pub struct SystemChart {
    /// Tab/panel title.
    pub title: String,
    /// All observable state (FC-3).
    pub state: SysChartModel,
}

const NODE_R: f32 = 16.0;

impl SystemChart {
    pub fn new(title: impl Into<String>, nodes: Vec<SysNode>, edges: Vec<SysEdge>) -> Self {
        Self {
            title: title.into(),
            state: SysChartModel { nodes, edges, selected: None, canvas_h: 280.0 },
        }
    }
    pub fn with_canvas_height(mut self, h: f32) -> Self {
        self.state.canvas_h = h;
        self
    }

    /// Build a **layered** system map — the architecture/topology "grouped by
    /// layer" shape. `layers` are top-to-bottom bands (e.g. ingress → services →
    /// storage); each band's nodes are spread evenly across the width and pinned to
    /// that band's vertical position, so the map reads as a constellation diagram
    /// organised by layer. Node `pos` fields are overwritten by the layout; `edges`
    /// (the dependencies) are added as given. This is [`SystemChart::new`] with the
    /// free positions computed from the layering instead of supplied.
    pub fn from_layers(title: impl Into<String>, layers: Vec<Vec<SysNode>>, edges: Vec<SysEdge>) -> Self {
        let n_layers = layers.len().max(1) as f32;
        let mut nodes = Vec::new();
        for (li, layer) in layers.into_iter().enumerate() {
            // Band y: single layer sits mid-canvas; otherwise 0.12..=0.88 evenly.
            let y = if n_layers <= 1.0 { 0.5 } else { 0.12 + (li as f32) * (0.76 / (n_layers - 1.0)) };
            let count = layer.len().max(1) as f32;
            for (ni, mut node) in layer.into_iter().enumerate() {
                let x = if count <= 1.0 { 0.5 } else { 0.1 + (ni as f32) * (0.8 / (count - 1.0)) };
                node.pos = (x, y);
                nodes.push(node);
            }
        }
        Self::new(title, nodes, edges)
    }

    /// A self-contained **demo constellation map** — a small nordisk architecture in
    /// three layers (ingress `gateway` → the `korp`/`nornir`/`holger` services →
    /// the `skade`/`iceberg` storage), with dependency edges and per-service badges.
    /// The fixture the `syschart_panel` demo (and the Pages site) mounts.
    #[must_use]
    pub fn demo() -> Self {
        let c = Color32::from_rgb;
        let layers = vec![
            vec![SysNode::new("gateway", "Gateway", c(120, 200, 255), (0.0, 0.0)).badge(2).detail("ingress · TLS terminate")],
            vec![
                SysNode::new("korp", "korp", c(200, 160, 255), (0.0, 0.0)).badge(5).detail("case + analysis warehouse"),
                SysNode::new("nornir", "nornir", c(160, 255, 180), (0.0, 0.0)).badge(3).detail("orchestrator + test matrix"),
                SysNode::new("holger", "holger", c(255, 200, 140), (0.0, 0.0)).badge(1).detail("registry browser"),
            ],
            vec![
                SysNode::new("skade", "skade", c(140, 190, 255), (0.0, 0.0)).badge(8).detail("lakehouse warehouse"),
                SysNode::new("iceberg", "Iceberg", c(180, 220, 160), (0.0, 0.0)).badge(0).detail("table format"),
            ],
        ];
        let edges = vec![
            SysEdge::new("gateway", "korp"),
            SysEdge::new("gateway", "nornir"),
            SysEdge::new("korp", "holger"),
            SysEdge::new("korp", "skade"),
            SysEdge::new("nornir", "skade"),
            SysEdge::new("skade", "iceberg"),
        ];
        Self::from_layers("System Map", layers, edges)
    }

    /// The nodes (read-only view of the model).
    pub fn nodes(&self) -> &[SysNode] {
        &self.state.nodes
    }
    /// The edges (read-only view of the model).
    pub fn edges(&self) -> &[SysEdge] {
        &self.state.edges
    }

    fn index_of(&self, id: &str) -> Option<usize> {
        self.state.nodes.iter().position(|n| n.id == id)
    }

    /// Index of the currently-selected node, resolved from its stable id.
    fn selected_idx(&self) -> Option<usize> {
        self.state.selected.as_deref().and_then(|id| self.index_of(id))
    }

    /// **FC-2 / FC-8** — the single mutation path. Apply one [`Msg`]; returns the
    /// (always empty) [`Effect`]s the host should run. The canvas click routes its
    /// [`Msg`] here too, so live == headless.
    pub fn update(&mut self, msg: Msg) -> Vec<Effect> {
        match msg {
            Msg::Select(id) => {
                if self.index_of(&id).is_some() {
                    self.state.selected = if self.state.selected.as_deref() == Some(id.as_str()) {
                        None
                    } else {
                        Some(id)
                    };
                }
            }
            Msg::ClearSelection => self.state.selected = None,
            Msg::SetBadge(id, badge) => {
                if let Some(i) = self.index_of(&id) {
                    self.state.nodes[i].badge = badge;
                }
            }
            Msg::SetDetail(id, detail) => {
                if let Some(i) = self.index_of(&id) {
                    self.state.nodes[i].detail = detail;
                }
            }
        }
        Vec::new()
    }

    /// Select a node by id (headless-test + host entry point). Selecting the
    /// already-selected node deselects it. Unknown id is a no-op. Thin wrapper
    /// over [`update`](Self::update)`(`[`Msg::Select`]`)` — the single mutation path.
    pub fn select(&mut self, id: &str) {
        let _ = self.update(Msg::Select(id.to_string()));
    }
    /// Clear the selection ([`Msg::ClearSelection`]).
    pub fn clear_selection(&mut self) {
        let _ = self.update(Msg::ClearSelection);
    }
    /// The selected node's id, if any.
    pub fn selected(&self) -> Option<&str> {
        self.state.selected.as_deref()
    }

    /// Update a node's badge by id (e.g. a live event count). No-op if unknown.
    /// Thin wrapper over [`update`](Self::update)`(`[`Msg::SetBadge`]`)`.
    pub fn set_badge(&mut self, id: &str, badge: u64) {
        let _ = self.update(Msg::SetBadge(id.to_string(), badge));
    }
    /// Update a node's detail text by id. No-op if unknown. Thin wrapper over
    /// [`update`](Self::update)`(`[`Msg::SetDetail`]`)`.
    pub fn set_detail(&mut self, id: &str, detail: impl Into<String>) {
        let _ = self.update(Msg::SetDetail(id.to_string(), detail.into()));
    }

    /// **Test/host hook (additive).** The public, return-asserted view of the
    /// private [`center`](Self::center) layout node — the absolute pixel centre
    /// node `i`'s circle is painted at inside `rect`. Exposed so the syschart
    /// call-chain matrix can assert the *layout/place* stage (finite, confined to
    /// the padded inner rect, monotone in the normalized pos) without a painter.
    /// Calls the **same** private fn `view` paints with — additive, no behaviour
    /// change. The node radius the layout pads for is [`SystemChart::NODE_R`].
    pub fn node_center(&self, i: usize, rect: Rect) -> Pos2 {
        self.center(i, rect)
    }
    /// The node radius (px) the free-position layout pads the canvas by, exposed so
    /// the matrix can assert nodes land inside `rect` by exactly this inset.
    pub const NODE_R: f32 = NODE_R;

    /// Absolute pixel centre of node `i` inside `rect`.
    fn center(&self, i: usize, rect: Rect) -> Pos2 {
        let (nx, ny) = self.state.nodes[i].pos;
        let pad = NODE_R + 6.0;
        let inner = Rect::from_min_max(
            rect.min + vec2(pad, pad),
            rect.max - vec2(pad, pad),
        );
        Pos2::new(
            inner.min.x + nx.clamp(0.0, 1.0) * inner.width().max(1.0),
            inner.min.y + ny.clamp(0.0, 1.0) * inner.height().max(1.0),
        )
    }
}

impl SystemChart {
    /// The copyable text: the selected node's `label · detail` (badge in a suffix)
    /// when a node is selected, else the whole node list as a TSV rectangle
    /// (`id \t label \t badge`).
    pub fn copy_text(&self) -> Option<String> {
        if self.state.nodes.is_empty() {
            return None;
        }
        if let Some(n) = self.selected().and_then(|id| self.state.nodes.iter().find(|n| n.id == id)) {
            let mut s = format!("{} (badge {})", n.label, n.badge);
            if !n.detail.is_empty() {
                s.push('\n');
                s.push_str(&n.detail);
            }
            return Some(s);
        }
        let mut out = String::from("id\tlabel\tbadge");
        for n in &self.state.nodes {
            out.push('\n');
            out.push_str(&format!("{}\t{}\t{}", n.id, n.label, n.badge));
        }
        Some(out)
    }

    /// **FC-9 pure view** — a function of `&self`: it paints the chart and *returns*
    /// the [`Msg`]s the frame produced (a node click → [`Msg::Select`]). It does
    /// **not** mutate the model; the [`impl_facet_via_elm!`](facett_core::impl_facet_via_elm)
    /// bridge applies the returned messages through [`update`](Self::update), so a
    /// headless driver feeding the same [`Msg`]s reproduces the live behaviour.
    pub fn view(&self, ui: &mut Ui) -> Vec<Msg> {
        let mut msgs: Vec<Msg> = Vec::new();
        let th = theme(ui);
        // ── node canvas ──────────────────────────────────────────────────────
        let canvas = vec2(
            ui.available_width(),
            self.state.canvas_h.min(ui.available_height().max(self.state.canvas_h)),
        );
        let (rect, resp) = ui.allocate_exact_size(canvas, Sense::hover());
        let base = ui.id().with("syschart-node");
        let painter = ui.painter_at(rect);

        // The empty-data state carries the stable UI error code facet-syschart-1 (see
        // facett_core::errcode) so tests + consumers react to the CODE, not a string;
        // when empty the canvas atom also carries the Error severity + the code, and
        // the pink code is painted beneath the human hint.
        if self.state.nodes.is_empty() {
            resp.widget_info(|| {
                Semantics::image(format!("{} — no peers", self.title))
                    .severity(facett_core::Severity::Error)
                    .error_code("facet-syschart-1")
                    .widget_info()
            });
            painter.text(rect.center(), Align2::CENTER_CENTER, "no peers to show", FontId::proportional(13.0), th.text_dim);
            facett_core::errcode::paint_code(&painter, rect.center() + vec2(0.0, 16.0), "facet-syschart-1");
            #[cfg(feature = "testmatrix")]
            facett_core::testmatrix::emit(
                "facett-syschart::SystemChart::view",
                "ui_render",
                false,
                "nodes=0 drew=empty_hint code=facet-syschart-1",
            );
            return msgs;
        }

        let centers: Vec<Pos2> = (0..self.state.nodes.len()).map(|i| self.center(i, rect)).collect();

        // edges first (under the nodes)
        for e in &self.state.edges {
            if let (Some(ai), Some(bi)) = (self.index_of(&e.a), self.index_of(&e.b)) {
                painter.line_segment([centers[ai], centers[bi]], Stroke::new(1.5_f32, th.edge));
            }
        }

        // nodes — paint, plus an AccessKit node per element (FC-4) keyed on the
        // stable domain id (FC-5). A click is collected as a `Msg::Select` and
        // RETURNED; the `update` bridge applies the (toggle) selection — the view
        // itself stays pure (no `self` mutation).
        let sel_id = self.state.selected.clone();
        for (i, node) in self.state.nodes.iter().enumerate() {
            let c = centers[i];
            let selected = sel_id.as_deref() == Some(node.id.as_str());
            let r = if selected { NODE_R + 3.0 } else { NODE_R };
            // Elevation shadow under the raised node chip (Windows-pronounced /
            // macOS-restrained, per the active NativeFeel) — painted BEFORE the fill
            // so it sits behind the node. No-op under Device (effects-off).
            facett_core::look::elevation_shadow(ui, Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r)), r);
            painter.circle_filled(c, r, node.color);
            let ring = if selected { th.accent } else { th.node_stroke };
            painter.circle_stroke(c, r, Stroke::new(if selected { 2.5_f32 } else { 1.0_f32 }, ring));
            // badge inside the node
            painter.text(c, Align2::CENTER_CENTER, node.badge.to_string(), FontId::proportional(11.0), th.text);
            // label under the node
            painter.text(
                c + vec2(0.0, r + 2.0),
                Align2::CENTER_TOP,
                &node.label,
                FontId::proportional(11.0),
                th.text,
            );

            // AccessKit hit-test node over the node's circle (FC-4): role=Button,
            // label = "{label} · {badge} events", numeric_value = badge, selected.
            let node_rect = Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r));
            // ── native-feel cues (mac/windows parity): the Windows reveal glow on
            // hover + the platform focus ring/rect on the selected node. Both read
            // the active Theme's NativeFeel through the shared `look::feel` helpers,
            // so this node follows the platform preset (no-op on Neutral/Device).
            facett_core::look::reveal_on_hover(ui, node_rect, r);
            facett_core::look::apply_focus_ring(ui, node_rect, selected, r);
            let label = format!("{} · {} events", node.label, node.badge);
            let hit = a11y_node(
                ui,
                base,
                &node.id,
                Sense::click(),
                node_rect,
                Semantics::button(label).value(node.badge as f64).selected(selected),
            );
            if hit.clicked() {
                msgs.push(Msg::Select(node.id.clone()));
            }
        }

        // ── inline detail panel ──────────────────────────────────────────────
        ui.separator();
        match self.selected_idx() {
            None => {
                ui.weak("Click a node to expand its detail.");
            }
            Some(i) => {
                let node = &self.state.nodes[i];
                ui.horizontal(|ui| {
                    ui.strong(&node.label);
                    ui.weak(format!("· {} events", node.badge));
                });
                if node.detail.is_empty() {
                    ui.weak("(no detail)");
                } else {
                    for line in node.detail.lines() {
                        ui.monospace(line);
                    }
                }
            }
        }

        // ── render-lane emit: this view path RAN ──────────────────────────────
        #[cfg(feature = "testmatrix")]
        facett_core::testmatrix::emit(
            "facett-syschart::SystemChart::view",
            "ui_render",
            !self.state.nodes.is_empty(),
            &format!("nodes={} edges={}", self.state.nodes.len(), self.state.edges.len()),
        );

        msgs
    }
}

// ── typed copy (§16) — read-only: selected node text or node-list rows ─────────
impl CopySource for SystemChart {
    fn copy_kinds(&self) -> &[ClipKind] {
        &[ClipKind::Text]
    }

    fn copy_payload(&self) -> Option<ClipPayload> {
        self.copy_text().map(ClipPayload::Text)
    }
}

// ── the Elm contract (FC-2 / FC-9) ─────────────────────────────────────────────
impl facett_core::Elm for SystemChart {
    type Model = SysChartModel;
    type Msg = Msg;
    type Effect = Effect;

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

// The bridge macro writes `impl Facet for SystemChart` 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 chart publishes a
// RICHER `state_json` than plain `serde(state())` — it flattens each node to
// `id/label/badge/pos/has_detail` (colour omitted, detail as a bool) and each edge
// to an `[a,b]` pair, exactly the observable shape the demo's mega-matrix asserts.
facett_core::impl_facet_via_elm!(SystemChart, custom_state_json, {
    fn copy(&mut self) -> Option<String> {
        self.copy_payload().map(|p| p.as_text())
    }

    fn state_json(&self) -> serde_json::Value {
        let s = &self.state;
        serde_json::json!({
            "nodes": s.nodes.iter().map(|n| serde_json::json!({
                "id": n.id,
                "label": n.label,
                "badge": n.badge,
                "pos": [n.pos.0, n.pos.1],
                "has_detail": !n.detail.is_empty(),
            })).collect::<Vec<_>>(),
            "edges": s.edges.iter().map(|e| serde_json::json!([e.a, e.b])).collect::<Vec<_>>(),
            "selected": self.selected(),
            // The stable UI ERROR CODE for the empty-data state (facett_core::errcode):
            // present so tests + consumers react to the CODE, not a matched string.
            "error_code": if s.nodes.is_empty() {
                serde_json::json!("facet-syschart-1")
            } else {
                serde_json::Value::Null
            },
        })
    }

    /// STRUCTURAL severity (the Robot-UI gate signal): RED when the chart has no
    /// peers to show (the facet-syschart-1 empty state), the Info floor otherwise.
    fn severity(&self) -> facett_core::Severity {
        if self.state.nodes.is_empty() {
            facett_core::Severity::Error
        } else {
            facett_core::Severity::Info
        }
    }

    fn selection_json(&self) -> serde_json::Value {
        match self.selected() {
            Some(id) => serde_json::json!(id),
            None => serde_json::Value::Null,
        }
    }

    /// Painted with the active `Theme` (nodes/edges/text/accent ring), and its
    /// canvas takes the host's available width — themeable + resizable.
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE.themeable().resizable().selectable().copyable()
    }

    /// Opt into typed downcast so a host (e.g. the demo's robot-UI node-select
    /// toolbar) can forward a selection to [`SystemChart::select`] when this chart
    /// lives boxed inside a `FacetDeck`.
    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        Some(self)
    }
});

#[cfg(test)]
mod tests {
    use super::*;
    // `Elm` for `state()`; `Facet` for `state_json`/`selection_json`.
    use facett_core::{Elm, Facet, harness};

    #[test]
    fn typed_copy_is_selected_node_or_node_list_rows() {
        use facett_core::clip::{ClipKind, CopySource};
        let mut c = SystemChart::new(
            "sys",
            vec![
                SysNode::new("pki", "PKI", Color32::WHITE, (0.1, 0.1)).badge(3),
                SysNode::new("oidc", "OIDC", Color32::WHITE, (0.9, 0.1)).badge(7),
            ],
            vec![SysEdge::new("pki", "oidc")],
        );
        // No selection -> the node list as a TSV rectangle.
        let p = c.copy_payload().unwrap();
        assert_eq!(p.kind(), ClipKind::Text);
        assert!(p.as_text().starts_with("id\tlabel\tbadge"), "{}", p.as_text());
        assert!(p.as_text().contains("\npki\tPKI\t3"));
        // Selecting narrows to that node's label + badge.
        c.select("oidc");
        assert_eq!(c.copy_payload().unwrap().as_text(), "OIDC (badge 7)");
        assert!(SystemChart::new("empty", vec![], vec![]).copy_payload().is_none());
    }

    fn sample() -> SystemChart {
        let nodes = vec![
            SysNode::new("pki", "PKI", Color32::from_rgb(120, 200, 255), (0.1, 0.1)).badge(3).detail("issued: a\nissued: b"),
            SysNode::new("oidc", "OIDC", Color32::from_rgb(200, 160, 255), (0.9, 0.1)).badge(7),
            SysNode::new("nexus", "Nexus", Color32::from_rgb(160, 255, 180), (0.5, 0.9)).badge(0),
        ];
        let edges = vec![
            SysEdge::new("pki", "oidc"),
            SysEdge::new("pki", "nexus"),
            SysEdge::new("oidc", "nexus"),
        ];
        SystemChart::new("System Map", nodes, edges)
    }

    #[test]
    fn select_toggles_and_reports() {
        let mut c = sample();
        assert_eq!(c.selected(), None);
        c.select("oidc");
        assert_eq!(c.selected(), Some("oidc"));
        c.select("oidc"); // toggle off
        assert_eq!(c.selected(), None);
        c.select("nope"); // unknown → no-op
        assert_eq!(c.selected(), None);
    }

    #[test]
    fn set_badge_and_detail_mutate_named_node() {
        let mut c = sample();
        c.set_badge("nexus", 42);
        c.set_detail("nexus", "repo: maven-releases");
        let nexus = c.nodes().iter().find(|n| n.id == "nexus").unwrap();
        assert_eq!(nexus.badge, 42);
        assert!(nexus.detail.contains("maven-releases"));
    }

    #[test]
    fn state_json_carries_every_node_edge_and_selection() {
        let mut c = sample();
        c.select("pki");
        let j = c.state_json();
        assert_eq!(j["nodes"].as_array().unwrap().len(), 3);
        assert_eq!(j["edges"].as_array().unwrap().len(), 3);
        assert_eq!(j["selected"], "pki");
        // badge + detail flags surfaced for robot assertions
        let pki = j["nodes"].as_array().unwrap().iter().find(|n| n["id"] == "pki").unwrap();
        assert_eq!(pki["badge"], 3);
        assert_eq!(pki["has_detail"], true);
    }

    #[test]
    fn headless_render_draws_and_selection_shows_detail() {
        // Inject a real chart + a real selection, render offscreen, assert it
        // both DREW pixels and reported the selected node in its state — the
        // inject-input/assert-output law, no display.
        let mut c = sample();
        c.select("pki");
        let r = harness::headless_render(&mut c);
        assert_eq!(r.title, "System Map");
        assert!(r.drew(), "a 3-node chart should tessellate to vertices");
        assert_eq!(r.state["selected"], "pki");
        assert_eq!(r.state["nodes"].as_array().unwrap().len(), 3);
    }

    #[test]
    fn caps_advertise_selectable_themeable_resizable() {
        let caps = sample().caps();
        assert!(caps.selectable);
        assert!(caps.themeable);
        assert!(caps.resizable);
        assert!(!caps.scalable, "syschart has no zoom yet");
    }

    // ── FC-2 / FC-9 harness properties: drive `Msg`s, snapshot `state()`, no GPU ──

    #[test]
    fn drive_select_toggles_via_msg_no_effects() {
        let mut c = sample();
        // Select → the id lands; select again → toggles off; unknown id → no-op.
        let fx = harness::drive(&mut c, [Msg::Select("oidc".into())]);
        assert!(fx.is_empty(), "syschart issues no Effects (uninhabited)");
        assert_eq!(c.state().selected.as_deref(), Some("oidc"));
        harness::drive(&mut c, [Msg::Select("oidc".into())]);
        assert_eq!(c.state().selected, None, "re-select toggles off");
        harness::drive(&mut c, [Msg::Select("ghost".into())]);
        assert_eq!(c.state().selected, None, "unknown id is a no-op");
    }

    #[test]
    fn drive_clear_selection_via_msg() {
        let mut c = sample();
        let snap = harness::snapshot(&mut c, [Msg::Select("pki".into()), Msg::ClearSelection]);
        assert_eq!(snap.selected, None);
    }

    #[test]
    fn drive_set_badge_and_detail_via_msg() {
        let mut c = sample();
        let snap = harness::snapshot(
            &mut c,
            [
                Msg::SetBadge("nexus".into(), 42),
                Msg::SetDetail("nexus".into(), "repo: maven-releases".into()),
                // unknown ids are inert
                Msg::SetBadge("ghost".into(), 99),
            ],
        );
        let nexus = snap.nodes.iter().find(|n| n.id == "nexus").unwrap();
        assert_eq!(nexus.badge, 42);
        assert!(nexus.detail.contains("maven-releases"));
        assert!(snap.nodes.iter().all(|n| n.id != "ghost"));
    }

    #[test]
    fn drive_produces_no_effects_for_any_msg() {
        let mut c = sample();
        let fx = harness::drive(
            &mut c,
            [
                Msg::Select("pki".into()),
                Msg::ClearSelection,
                Msg::SetBadge("oidc".into(), 5),
                Msg::SetDetail("oidc".into(), "x".into()),
            ],
        );
        assert!(fx.is_empty(), "the syschart never asks the host to do side work");
    }

    #[test]
    fn from_layers_groups_nodes_into_vertical_bands() {
        let c = SystemChart::from_layers(
            "layered",
            vec![
                vec![SysNode::new("a", "A", Color32::WHITE, (0.0, 0.0))],
                vec![
                    SysNode::new("b", "B", Color32::WHITE, (0.0, 0.0)),
                    SysNode::new("c", "C", Color32::WHITE, (0.0, 0.0)),
                ],
            ],
            vec![SysEdge::new("a", "b")],
        );
        // Every node survived the flatten, layout overwrote positions.
        assert_eq!(c.nodes().len(), 3);
        let y = |id: &str| c.nodes().iter().find(|n| n.id == id).unwrap().pos.1;
        // Band 0 (A) sits above band 1 (B, C), which share a y.
        assert!(y("a") < y("b"), "the first layer is above the second");
        assert!((y("b") - y("c")).abs() < f32::EPSILON, "same-layer nodes share a band");
        // A single node in a band is centred; two are spread apart horizontally.
        let x = |id: &str| c.nodes().iter().find(|n| n.id == id).unwrap().pos.0;
        assert!((x("a") - 0.5).abs() < f32::EPSILON, "a lone node centres");
        assert!(x("b") < x("c"), "peers spread across the band");
    }

    #[test]
    fn demo_is_a_layered_constellation_that_renders() {
        let mut c = SystemChart::demo();
        assert_eq!(c.nodes().len(), 6, "gateway + 3 services + 2 storage");
        assert_eq!(c.edges().len(), 6);
        // Three distinct vertical bands (gateway / services / storage).
        use std::collections::BTreeSet;
        let bands: BTreeSet<i32> = c.nodes().iter().map(|n| (n.pos.1 * 1000.0) as i32).collect();
        assert_eq!(bands.len(), 3, "three layers ⇒ three vertical bands");
        // The demo fixture paints headlessly (the same panel the host mounts).
        let r = harness::headless_render(&mut c);
        assert_eq!(r.title, "System Map");
        assert!(r.drew(), "a 6-node constellation tessellates to vertices");
        assert_eq!(r.state["nodes"].as_array().unwrap().len(), 6);
    }

    #[test]
    fn model_serde_round_trips() {
        let mut c = sample();
        c.select("oidc");
        let json = serde_json::to_value(c.state()).unwrap();
        let back: SysChartModel = serde_json::from_value(json).unwrap();
        assert_eq!(&back, c.state(), "the Model round-trips through serde (FC-3)");
    }
}