facett-syschart 0.1.10

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
//! **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`].
//!
//! Like every facett component it implements [`Facet`]: `title` / `ui` /
//! `state_json` (every node, badge, edge + the selection), so it drops into a
//! `FacetDeck` and is robot-testable through `facett_core::harness` — drive
//! [`SystemChart::select`] headlessly and assert `state_json`.

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

/// 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)]
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)]
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() }
    }
}

/// The system-map chart: nodes + edges + the current selection.
pub struct SystemChart {
    pub title: String,
    pub nodes: Vec<SysNode>,
    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, so reorder/insert/
    /// delete preserves the selection (FC-5).
    selected: Option<String>,
    /// Height (px) the node canvas takes before the detail panel.
    canvas_h: f32,
}

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(), nodes, edges, selected: None, canvas_h: 280.0 }
    }
    pub fn with_canvas_height(mut self, h: f32) -> Self {
        self.canvas_h = h;
        self
    }

    fn index_of(&self, id: &str) -> Option<usize> {
        self.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.selected.as_deref().and_then(|id| self.index_of(id))
    }

    /// Select a node by id (headless-test + host entry point). Selecting the
    /// already-selected node deselects it. Unknown id is a no-op.
    pub fn select(&mut self, id: &str) {
        if self.index_of(id).is_some() {
            self.selected = if self.selected.as_deref() == Some(id) {
                None
            } else {
                Some(id.to_string())
            };
        }
    }
    /// Clear the selection.
    pub fn clear_selection(&mut self) {
        self.selected = None;
    }
    /// The selected node's id, if any.
    pub fn selected(&self) -> Option<&str> {
        self.selected.as_deref()
    }

    /// Update a node's badge by id (e.g. a live event count). No-op if unknown.
    pub fn set_badge(&mut self, id: &str, badge: u64) {
        if let Some(i) = self.index_of(id) {
            self.nodes[i].badge = badge;
        }
    }
    /// Update a node's detail text by id. No-op if unknown.
    pub fn set_detail(&mut self, id: &str, detail: impl Into<String>) {
        if let Some(i) = self.index_of(id) {
            self.nodes[i].detail = 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 `ui` 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.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.nodes.is_empty() {
            return None;
        }
        if let Some(n) = self.selected().and_then(|id| self.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.nodes {
            out.push('\n');
            out.push_str(&format!("{}\t{}\t{}", n.id, n.label, n.badge));
        }
        Some(out)
    }
}

// ── 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)
    }
}

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

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

    fn ui(&mut self, ui: &mut Ui) {
        let th = theme(ui);
        // ── node canvas ──────────────────────────────────────────────────────
        let canvas = vec2(ui.available_width(), self.canvas_h.min(ui.available_height().max(self.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);

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

        // edges first (under the nodes)
        for e in &self.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, th.edge));
            }
        }

        // nodes — paint as before, plus an AccessKit node per element (FC-4) keyed
        // on the stable domain id (FC-5). Collect the click into a local and apply
        // selection AFTER the loop to avoid borrowing `self` mutably mid-iteration.
        let sel_id = self.selected.clone();
        let mut toggle: Option<String> = None;
        for (i, node) in self.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 } else { 1.0 }, 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() {
                toggle = Some(node.id.clone());
            }
        }

        // click-select: toggle the clicked node by its stable id.
        if let Some(id) = toggle {
            self.select(&id);
        }

        // ── inline detail panel ──────────────────────────────────────────────
        ui.separator();
        match self.selected_idx() {
            None => {
                ui.weak("Click a node to expand its detail.");
            }
            Some(i) => {
                let node = &self.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 Facet::ui path RAN ─────────────────────────
        #[cfg(feature = "testmatrix")]
        facett_core::testmatrix::emit(
            "facett-syschart::SystemChart::ui",
            "ui_render",
            !self.nodes.is_empty(),
            &format!("nodes={} edges={}", self.nodes.len(), self.edges.len()),
        );
    }

    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "nodes": self.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": self.edges.iter().map(|e| serde_json::json!([e.a, e.b])).collect::<Vec<_>>(),
            "selected": self.selected(),
        })
    }

    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 {

    #[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());
    }

    use super::*;
    use facett_core::harness;

    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");
    }
}