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};
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
}
#[derive(Clone, Debug, PartialEq)]
pub enum Msg {
Select(Option<String>),
PanBy(f32, f32),
ZoomBy(f32),
Fit,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Effect {}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphViewState {
pub model: GraphModel,
pub decorations: Decorations,
pub selected: Option<String>,
pub pan_x: f32,
pub pan_y: f32,
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,
}
}
}
pub struct DecoratedGraphView {
title: String,
state: GraphViewState,
}
impl DecoratedGraphView {
pub fn new(title: impl Into<String>) -> Self {
Self { title: title.into(), state: GraphViewState::default() }
}
pub fn with_model(mut self, model: GraphModel) -> Self {
self.state.model = model;
self
}
pub fn with_decorations(mut self, decorations: Decorations) -> Self {
self.state.decorations = decorations;
self
}
pub fn set_title(&mut self, title: impl Into<String>) {
self.title = title.into();
}
pub fn state(&self) -> &GraphViewState {
&self.state
}
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()
}
pub fn fit(&mut self) {
let _ = self.update(Msg::Fit);
}
pub fn select(&mut self, id: Option<String>) {
let _ = self.update(Msg::Select(id));
}
pub fn lit_set(&self) -> BTreeSet<String> {
self.state.selected.as_deref().map(|s| downstream_of(&self.state.model, s)).unwrap_or_default()
}
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)
}
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 {
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"))
}
}
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 {
pub fn view(&self, ui: &mut egui::Ui) -> Vec<Msg> {
let mut msgs: Vec<Msg> = Vec::new();
let th = facett_core::theme(ui);
let zoom = if self.state.zoom > 0.0 { self.state.zoom } else { 1.0 };
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;
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();
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 {
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));
}
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);
}
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 },
);
}
}
}
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
}
}
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)
}
}
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,
}
}
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::*;
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();
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());
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();
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");
}
#[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`");
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"], "⚠");
assert_eq!(j["selected"], serde_json::Value::Null);
assert!(j["lit"].as_array().unwrap().is_empty());
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)");
}
#[test]
fn harness_snapshot_drives_camera_and_selection() {
use facett_core::harness;
let mut v = DecoratedGraphView::local();
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");
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();
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");
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)");
}
#[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();
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");
assert!(v.state().model.nodes.iter().any(|n| n.id == "b"));
}
}