Skip to main content

webizen_studio/
canvas_graph.rs

1//! Pane relationship graph — shared by node view and the selection sidebar.
2
3use std::collections::{HashMap, HashSet};
4
5use crate::canvas_model::PanePlacement;
6
7#[derive(Clone, Debug, PartialEq, Eq, Hash)]
8pub struct GraphEdge {
9    pub from_idx: usize,
10    pub to_idx: usize,
11    pub label: String,
12    /// Shared binding count or anchor weight (1 = anchor-only).
13    pub strength: u8,
14}
15
16/// Directed edges from anchors and shared `data_bindings`, with binding-strength scores.
17pub fn derive_graph_edges(panes: &[PanePlacement]) -> Vec<GraphEdge> {
18    let mut edges = Vec::new();
19    let mut seen: HashSet<(usize, usize, String)> = HashSet::new();
20    let mut strength_map: HashMap<(usize, usize, String), u8> = HashMap::new();
21
22    let index_by_id: HashMap<&str, usize> = panes
23        .iter()
24        .enumerate()
25        .map(|(i, p)| (p.component_id.as_str(), i))
26        .collect();
27
28    for (to_idx, pane) in panes.iter().enumerate() {
29        if let Some(anchor) = pane.anchor.as_deref() {
30            if let Some(&from_idx) = index_by_id.get(anchor) {
31                let key = (from_idx, to_idx, "anchor".to_string());
32                strength_map.insert(key.clone(), 1);
33                if seen.insert(key) {
34                    edges.push(GraphEdge {
35                        from_idx,
36                        to_idx,
37                        label: "anchor".to_string(),
38                        strength: 1,
39                    });
40                }
41            }
42        }
43
44        for binding in &pane.data_bindings {
45            for (from_idx, other) in panes.iter().enumerate() {
46                if from_idx == to_idx {
47                    continue;
48                }
49                let shared = other.data_bindings.iter().filter(|b| *b == binding).count() as u8;
50                if shared == 0 {
51                    continue;
52                }
53                let a = from_idx.min(to_idx);
54                let b = from_idx.max(to_idx);
55                let key = (a, b, binding.clone());
56                let entry = strength_map.entry(key.clone()).or_insert(0);
57                *entry = entry.saturating_add(shared.max(1));
58                if seen.insert(key.clone()) {
59                    edges.push(GraphEdge {
60                        from_idx: a,
61                        to_idx: b,
62                        label: binding.clone(),
63                        strength: *strength_map.get(&key).unwrap_or(&1),
64                    });
65                } else if let Some(edge) = edges
66                    .iter_mut()
67                    .find(|e| e.from_idx == a && e.to_idx == b && e.label == *binding)
68                {
69                    edge.strength = edge.strength.saturating_add(shared.max(1));
70                }
71            }
72        }
73    }
74
75    edges
76}
77
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct GraphNeighbor {
80    pub idx: usize,
81    pub component_id: String,
82    pub relation: String,
83    pub strength: u8,
84}
85
86/// Panes linked to `selected_idx` (incoming or outgoing).
87pub fn graph_neighbors(
88    edges: &[GraphEdge],
89    panes: &[PanePlacement],
90    selected_idx: usize,
91) -> Vec<GraphNeighbor> {
92    let mut out = Vec::new();
93    let mut seen = HashSet::new();
94
95    for edge in edges {
96        let (other_idx, relation) = if edge.from_idx == selected_idx {
97            (edge.to_idx, edge.label.clone())
98        } else if edge.to_idx == selected_idx {
99            (edge.from_idx, edge.label.clone())
100        } else {
101            continue;
102        };
103        if !seen.insert(other_idx) {
104            continue;
105        }
106        let component_id = panes
107            .get(other_idx)
108            .map(|p| p.component_id.clone())
109            .unwrap_or_else(|| format!("pane-{other_idx}"));
110        out.push(GraphNeighbor {
111            idx: other_idx,
112            component_id,
113            relation,
114            strength: edge.strength,
115        });
116    }
117
118    out.sort_by(|a, b| {
119        b.strength
120            .cmp(&a.strength)
121            .then_with(|| a.component_id.cmp(&b.component_id))
122    });
123    out
124}
125
126/// Edge visual descriptor.
127pub fn edge_visual(strength: u8) -> (f64, f64, &'static str) {
128    let s = strength.max(1) as f64;
129    let width = (1.0 + s * 0.45).min(4.5);
130    let opacity = (0.35 + s * 0.12).min(0.95);
131    let glow = if strength >= 3 {
132        "filter: drop-shadow(0 0 6px rgba(245,158,11,0.55));"
133    } else {
134        ""
135    };
136    (width, opacity, glow)
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::canvas_model::LayerBehavior;
143
144    fn pane(cid: &str, anchor: Option<&str>, bindings: &[&str]) -> PanePlacement {
145        PanePlacement {
146            component_id: cid.to_string(),
147            x: 0,
148            y: 0,
149            w: 10,
150            h: 8,
151            data_bindings: bindings.iter().map(|s| s.to_string()).collect(),
152            binds_rpc: None,
153            requires_capability: vec![],
154            ui_mode: None,
155            layer: LayerBehavior::Docked,
156            anchor: anchor.map(str::to_string),
157            min_w_points: 0,
158            min_h_points: 0,
159            supported_presentations: vec![],
160            theme: Default::default(),
161        }
162    }
163
164    #[test]
165    fn shared_bindings_increase_strength() {
166        let panes = vec![
167            pane("a", None, &["ctx:chat", "ctx:user"]),
168            pane("b", None, &["ctx:chat", "ctx:user"]),
169        ];
170        let edges = derive_graph_edges(&panes);
171        assert!(!edges.is_empty());
172        assert!(edges.iter().any(|e| e.strength >= 2));
173    }
174
175    #[test]
176    fn neighbors_sorted_by_strength() {
177        let panes = vec![
178            pane("hub", None, &["ctx:main"]),
179            pane("weak", Some("hub"), &[]),
180            pane("strong", None, &["ctx:main"]),
181        ];
182        let edges = derive_graph_edges(&panes);
183        let neighbors = graph_neighbors(&edges, &panes, 0);
184        assert!(!neighbors.is_empty());
185    }
186}