facett-graph 0.1.12

facett — graph (node/edge) viewer component, on facett-core
Documentation
//! **facett-graph** — the graph (node/edge) viewer component, on
//! [`facett_core`]. Build a [`Scene`] from a labelled edge list (the common
//! shape: a graph query, a dataflow DAG) and draw it. Source-agnostic — the
//! caller turns its Arrow/Cypher/whatever into edges first.
//!
//! ## FC contract (the canonical Elm split, FC-2 / FC-9)
//! Both facets in this crate — [`GraphView`] (the 2D node/edge skin) and
//! [`DepGraphView`] (the layered dep-DAG) — adopt the [`facett_core::Elm`] split:
//! - **[`GraphState`]** / **[`depgraph::DepGraphState`]** — the complete observable,
//!   serializable, round-trippable *interaction* state. The bulk graph data (the
//!   [`Scene`] / the `nodes`+`edges`) is the *input* held on the struct — `Color32`
//!   is not serde-round-trippable and it is not the state a headless driver mutates,
//!   so it lives OUTSIDE the Model (mirrors how facett-grid keeps its Arrow data on
//!   the struct, not in its `GridState`).
//! - **[`Msg`] + `update`** — the single mutation path (FC-2): a host/robot toggles
//!   the layout ([`GraphView`]) or selects/clears a node ([`DepGraphView`]); a
//!   headless driver ([`facett_core::harness`]) reaches the identical transitions.
//! - **`view`** — a **pure** paint (FC-9): reads `&self`, paints, and *returns* the
//!   [`Msg`]s the interactions produced; the
//!   [`impl_facet_via_elm!`](facett_core::impl_facet_via_elm) bridge applies them.
//! - **Rich `state_json`** — the node/edge/label counts (and the dep-graph's column
//!   depth) a driver reads are *derived* from the input `Scene`/`nodes`, not the
//!   interaction Model, so the macro is invoked in **form 3** (`custom_state_json`)
//!   to publish those exact pre-migration keys instead of a plain `serde(state())`.

use std::collections::{BTreeMap, HashMap};

pub use facett_core::{Edge, Facet, FacetCaps, Layout, Node, Scene, Theme, draw, hash_color, set_theme, theme};

use serde::{Deserialize, Serialize};

mod depgraph;
pub use depgraph::{
    DepEdge, DepGraphState, DepGraphView, DepNode, draw_arrow, Effect as DepGraphEffect, Msg as DepGraphMsg,
};

/// Build a [`Scene`] from a labelled edge list — each row is
/// `(src_id, dst_id, src_label, dst_label)`. Distinct ids become nodes, coloured
/// per label (FNV-hashed). The reusable "graph from edges" adapter korp's Graph
/// and Pipelines views both want.
pub fn scene_from_labeled_edges<I>(rows: I) -> Scene
where
    I: IntoIterator<Item = (i64, i64, String, String)>,
{
    let mut scene = Scene::new();
    let mut idx: HashMap<i64, usize> = HashMap::new();
    for (s, d, sl, dl) in rows {
        let si = *idx.entry(s).or_insert_with(|| scene.node(sl.clone(), hash_color(&sl)));
        let di = *idx.entry(d).or_insert_with(|| scene.node(dl.clone(), hash_color(&dl)));
        scene.edge(si, di);
    }
    scene
}

/// A serde-round-trippable mirror of [`Layout`] (which is `Copy` but neither
/// `Serialize` nor `Debug`, so it cannot live in the [`GraphState`] Model directly).
/// The [`Msg`] and the Model carry this; conversions to/from the core [`Layout`]
/// keep the painter and public API speaking the core type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GraphLayout {
    /// Nodes evenly spaced on a circle.
    #[default]
    Circular,
    /// Deterministic Fruchterman–Reingold force layout.
    Force,
}

impl From<Layout> for GraphLayout {
    fn from(l: Layout) -> Self {
        match l {
            Layout::Circular => GraphLayout::Circular,
            Layout::Force => GraphLayout::Force,
        }
    }
}

impl From<GraphLayout> for Layout {
    fn from(l: GraphLayout) -> Self {
        match l {
            GraphLayout::Circular => Layout::Circular,
            GraphLayout::Force => Layout::Force,
        }
    }
}

/// **The complete observable interaction state (FC-1 / FC-3)** of a [`GraphView`]:
/// the layout knob a host can toggle. The bulk [`Scene`] is *input* held on
/// [`GraphView`] (not serde-round-trippable, not driver-mutated), so it is
/// deliberately kept OUT of this Model — the derived node/edge/label counts a driver
/// reads are published via the form-3 `state_json` instead.
#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct GraphState {
    /// The node-placement strategy (the one knob a host/robot toggles).
    pub layout: GraphLayout,
}

/// A robot-/CLI-addressable control message (FC-2) — the named boundary a headless
/// driver (or a host) drives the [`GraphView`] through. Applied by
/// [`GraphView::update`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Msg {
    /// Switch the node-placement strategy.
    SetLayout(GraphLayout),
}

/// Side work as data (FC-8). The graph view does no I/O — every [`Msg`] mutates
/// only the in-memory [`GraphState`] — so this is uninhabited on purpose.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Effect {}

/// A simple graph-view widget: a [`Scene`] + a [`Layout`]. Implements [`Facet`],
/// so it drops into a `FacetDeck` and exposes `state_json` for free.
pub struct GraphView {
    /// The graph data being drawn — *input* (like facett-grid's Arrow data): held
    /// on the struct, outside the observable [`GraphState`] Model.
    pub scene: Scene,
    /// Shown centred when the scene has no nodes.
    pub empty_hint: String,
    /// The deck keys facets off this.
    pub title: String,
    /// All observable interaction state (FC-3).
    state: GraphState,
}

impl GraphView {
    pub fn new(scene: Scene) -> Self {
        Self { scene, empty_hint: "empty".into(), title: "graph".into(), state: GraphState::default() }
    }
    pub fn empty_hint(mut self, hint: impl Into<String>) -> Self {
        self.empty_hint = hint.into();
        self
    }
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }
    /// Set the layout strategy at build time.
    pub fn with_layout(mut self, layout: Layout) -> Self {
        self.state.layout = layout.into();
        self
    }

    /// **FC-3** — read the complete observable interaction state.
    pub fn state(&self) -> &GraphState {
        &self.state
    }

    /// The active node-placement strategy (as the core [`Layout`]).
    pub fn layout(&self) -> Layout {
        self.state.layout.into()
    }

    /// Switch the layout — a thin wrapper over the FC-2 [`update`](Self::update)
    /// mutation path (the sole way the Model changes).
    pub fn set_layout(&mut self, layout: Layout) {
        let _ = self.update(Msg::SetLayout(layout.into()));
    }

    /// **FC-2 / FC-8** — the single mutation path. Apply one [`Msg`]; returns the
    /// (always empty) [`Effect`]s the host should run.
    pub fn update(&mut self, msg: Msg) -> Vec<Effect> {
        match msg {
            Msg::SetLayout(layout) => self.state.layout = layout,
        }
        Vec::new()
    }

    /// Paint the scene (pure draw helper; no mutation).
    pub fn show(&self, ui: &mut egui::Ui) {
        draw(ui, &self.scene, self.state.layout.into(), &self.empty_hint);
    }

    /// **FC-9 render** — a **pure** function of `&self`: it paints the scene and
    /// *returns* the [`Msg`]s the interactions produced (none — the 2D skin is a
    /// static viewer; its layout is driven through the [`Msg`] surface by the host).
    /// It MUST NOT mutate the Model or do I/O.
    pub fn view(&self, ui: &mut egui::Ui) -> Vec<Msg> {
        self.show(ui);
        // ── render-lane emit: this pure-view paint path RAN ───────────────────
        #[cfg(feature = "testmatrix")]
        facett_core::testmatrix::emit(
            "facett-graph::GraphView::view",
            "ui_render",
            !self.scene.nodes.is_empty() || !self.empty_hint.is_empty(),
            &format!("nodes={} edges={}", self.scene.nodes.len(), self.scene.edges.len()),
        );
        Vec::new()
    }

    /// Per-label node counts (for the introspection).
    pub fn label_counts(&self) -> BTreeMap<String, usize> {
        let mut m = BTreeMap::new();
        for n in &self.scene.nodes {
            *m.entry(n.label.clone()).or_insert(0) += 1;
        }
        m
    }
}

impl GraphView {
    /// The copyable text: every node label, one per line (the graph carries no
    /// per-node selection, so this is the whole scene's label list).
    pub fn copy_text(&self) -> Option<String> {
        if self.scene.nodes.is_empty() {
            return None;
        }
        Some(self.scene.nodes.iter().map(|n| n.label.clone()).collect::<Vec<_>>().join("\n"))
    }
}

// ── typed copy (§16) — read-only: the scene's node labels as Text ─────────────
impl facett_core::clip::CopySource for GraphView {
    fn copy_kinds(&self) -> &[facett_core::clip::ClipKind] {
        use facett_core::clip::ClipKind;
        &[ClipKind::Text]
    }
    fn copy_payload(&self) -> Option<facett_core::clip::ClipPayload> {
        self.copy_text().map(facett_core::clip::ClipPayload::Text)
    }
}

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

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

// The bridge macro writes `impl Facet for GraphView` from the `Elm` impl: `title`,
// the FC-9 `ui` loop (`for m in view(ui) { update(m) }`), plus the overrides below.
// **Form 3** (`custom_state_json`) because the view publishes a RICHER `state_json`
// than a plain `serde(state())`: the `nodes`/`edges`/`labels` counts facett-demo's
// mega_matrix reads are *derived* from the input `Scene`, not the layout Model — so
// the default `state_json` is suppressed and these EXACT pre-migration keys supplied.
facett_core::impl_facet_via_elm!(GraphView, custom_state_json, {
    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "nodes": self.scene.nodes.len(),
            "edges": self.scene.edges.len(),
            "labels": self.label_counts(),
        })
    }
    fn copy(&mut self) -> Option<String> {
        use facett_core::clip::CopySource as _;
        self.copy_payload().map(|p| p.as_text())
    }
    /// Painted via [`draw`], which reads the active [`Theme`] (edges/labels/empty
    /// hint) from the context; its canvas takes the host's `available_size`.
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE.themeable().resizable().copyable()
    }
});

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

    #[test]
    fn typed_copy_is_the_node_label_list() {
        use facett_core::clip::{ClipKind, CopySource};
        let scene = scene_from_labeled_edges(vec![(1, 2, "Person".into(), "Company".into())]);
        let mut g = GraphView::new(scene);
        let p = g.copy_payload().expect("a populated scene copies");
        assert_eq!(p.kind(), ClipKind::Text);
        assert!(p.as_text().contains("Person") && p.as_text().contains("Company"));
        assert_eq!(<GraphView as Facet>::copy(&mut g), Some(p.as_text()));
    }

    #[test]
    fn builds_scene_from_labeled_edges() {
        let scene = scene_from_labeled_edges(vec![
            (1, 2, "Person".into(), "Company".into()),
            (1, 3, "Person".into(), "Address".into()),
        ]);
        assert_eq!(scene.nodes.len(), 3, "1, 2, 3 distinct");
        assert_eq!(scene.edges.len(), 2);
        assert_eq!(scene.nodes[0].label, "Person");
    }

    // ── Elm split: state_json keys preserved byte-for-byte ───────────────────
    #[test]
    fn state_json_preserves_the_pre_migration_keys() {
        let scene = scene_from_labeled_edges(vec![
            (1, 2, "Person".into(), "Company".into()),
            (1, 3, "Person".into(), "Address".into()),
        ]);
        let g = GraphView::new(scene);
        let j = Facet::state_json(&g);
        // Exactly `nodes` / `edges` / `labels` — no layout key leaks from the Model.
        assert_eq!(j["nodes"], 3);
        assert_eq!(j["edges"], 2);
        assert_eq!(j["labels"]["Person"], 1);
        let obj = j.as_object().unwrap();
        assert_eq!(obj.len(), 3, "exactly nodes/edges/labels, no extra keys: {:?}", obj.keys().collect::<Vec<_>>());
        assert!(obj.contains_key("nodes") && obj.contains_key("edges") && obj.contains_key("labels"));
    }

    // ── FC-2 → FC-3 as a *headless* property via the core harness ─────────────
    #[test]
    fn harness_drives_setlayout_and_snapshots_state() {
        use facett_core::harness;
        let mut g = GraphView::new(scene_from_labeled_edges(vec![(1, 2, "A".into(), "B".into())]));
        assert_eq!(g.state().layout, GraphLayout::Circular, "default layout");
        // SetLayout is observable in the snapshot.
        let snap = harness::snapshot(&mut g, [Msg::SetLayout(GraphLayout::Force)]);
        assert_eq!(snap.layout, GraphLayout::Force, "layout is observable headlessly");
        assert_eq!(&snap, g.state(), "the snapshot is a clone of the live state");
        assert_eq!(g.state().layout, GraphLayout::Force, "the live view reflects the driven layout");
        assert!(matches!(g.layout(), Layout::Force), "the accessor maps back to the core Layout");
    }

    #[test]
    fn drive_reports_no_effects_and_state_round_trips() {
        use facett_core::harness;
        let mut g = GraphView::new(Scene::new());
        // FC-8: the graph view does no I/O, so the effect stream is always empty.
        let effects = harness::drive(&mut g, [Msg::SetLayout(GraphLayout::Force)]);
        assert!(effects.is_empty(), "FC-8: graph view emits no Effects");
        // FC-3: the observable Model round-trips through serde.
        let json = serde_json::to_value(g.state()).unwrap();
        assert_eq!(json["layout"], "force");
        let back: GraphState = serde_json::from_value(json).unwrap();
        assert_eq!(&back, g.state(), "serde(state) -> state round-trips");
    }

    #[test]
    fn headless_render_draws_and_reports_state() {
        use facett_core::harness;
        let mut g = GraphView::new(scene_from_labeled_edges(vec![
            (1, 2, "Person".into(), "Company".into()),
            (2, 3, "Company".into(), "Address".into()),
        ]))
        .with_title("graph");
        let r = harness::headless_render(&mut g);
        assert_eq!(r.title, "graph");
        assert_eq!(r.state["nodes"], 3);
        assert_eq!(r.state["edges"], 2);
        assert!(r.drew(), "a 3-node graph tessellates to vertices");
    }
}