gioser

tawasuyu/brahman

Rust 326TOML 123JSON 14Markdown 114554 Definiciones

⎇ ac894390f96b8a36df16bb1fb9e2009ca7f568ee crates/modules/gioser/gioser-graph-web/src/lib.rs Rust · 455 líneas · 17.3 KB Historia Quién tocó qué crudo

gioser-graph: exaggerated thickness & brightness, edges behind with pointer-events:none ac894390f · Sergio ·

1//! `gioser-graph-web` — grafo semántico SVG inline.
2//!
3//! Layout grid: 3 columnas, filas según cantidad de nodos.
4//! Nodos: rectángulos redondeados 170×44px con texto + subtexto (camino).
5//! Aristas: opacidad/brillo según weight (más peso = más blanca y opaca).
6//! Respiración CSS suave en el SVG (opacity oscila perpetua).
7//! Hover: glow + opacidad.
8//! Las aristas conectan por ID (UUID), no por doc_id.
9
10use std::cell::RefCell;
11use std::rc::Rc;
12
13use serde::Deserialize;
14use wasm_bindgen::prelude::*;
15use wasm_bindgen::JsCast;
16use wasm_bindgen_futures::JsFuture;
17use web_sys::{
18    Document, HtmlElement, MouseEvent, Response, SvgLineElement, SvgRectElement,
19    SvgsvgElement, SvgTextElement, SvgCircleElement,
20};
21
22pub(crate) fn document() -> Option<Document> {
23    web_sys::window().and_then(|w| w.document())
24}
25
26// ─── Tipos de respuesta de `/graph` ──────────────────────────────
27
28#[derive(Deserialize, Debug, Clone)]
29struct GraphResponse {
30    nodes: Vec<GraphNode>,
31    edges: Vec<GraphEdge>,
32    stats: GraphStats,
33}
34
35#[derive(Deserialize, Debug, Clone)]
36struct GraphNode {
37    data: NodeData,
38}
39
40#[derive(Deserialize, Debug, Clone)]
41struct NodeData {
42    id: String,
43    name: String,
44    camino: String,
45    doc_id: Option<String>,
46    #[allow(dead_code)]
47    preview: Option<String>,
48}
49
50#[derive(Deserialize, Debug, Clone)]
51struct GraphEdge {
52    data: EdgeData,
53}
54
55#[derive(Deserialize, Debug, Clone)]
56struct EdgeData {
57    id: String,
58    source: String,
59    target: String,
60    weight: Option<f64>,
61}
62
63#[derive(Deserialize, Debug, Clone)]
64struct GraphStats {
65    points: u32,
66    edges: u32,
67    #[allow(dead_code)]
68    by_camino: Option<std::collections::HashMap<String, u32>>,
69}
70
71// ─── Widget ──────────────────────────────────────────────────────
72
73type NavCallback = Rc<RefCell<Option<Box<dyn FnMut(String)>>>>;
74
75const CANVAS_W: f64 = 800.0;
76const CANVAS_H: f64 = 420.0;
77const NODE_W: f64 = 170.0;
78const NODE_H: f64 = 44.0;
79const COLS: usize = 3;
80
81const CAMINO_COLORS: &[(&str, &str)] = &[
82    ("logos", "#d0dbff"), ("aire",   "#d0dbff"),
83    ("nomos", "#f59056"), ("fuego",  "#f59056"),
84    ("kay",   "#d49873"), ("tierra", "#d49873"),
85    ("uku",   "#6cd0f3"), ("agua",   "#6cd0f3"),
86];
87
88fn camino_color(camino: &str) -> &str {
89    for (k, v) in CAMINO_COLORS {
90        if *k == camino { return v; }
91    }
92    "#888888"
93}
94
95fn parse_hex(hex: &str) -> (u8, u8, u8) {
96    let h = hex.trim_start_matches('#');
97    if h.len() == 6 {
98        let r = u8::from_str_radix(&h[0..2], 16).unwrap_or(128);
99        let g = u8::from_str_radix(&h[2..4], 16).unwrap_or(128);
100        let b = u8::from_str_radix(&h[4..6], 16).unwrap_or(128);
101        (r, g, b)
102    } else {
103        (136, 136, 136)
104    }
105}
106
107fn blend_colors(c1: &str, c2: &str, t: f64) -> String {
108    let (r1, g1, b1) = parse_hex(c1);
109    let (r2, g2, b2) = parse_hex(c2);
110    let r = (r1 as f64 * (1.0 - t) + r2 as f64 * t) as u32;
111    let g = (g1 as f64 * (1.0 - t) + g2 as f64 * t) as u32;
112    let b = (b1 as f64 * (1.0 - t) + b2 as f64 * t) as u32;
113    format!("#{:02x}{:02x}{:02x}", r, g, b)
114}
115
116pub struct GraphWidget {
117    container: HtmlElement,
118    api_url: String,
119    nodes: Vec<NodeData>,
120    edges: Vec<EdgeData>,
121    on_navigate: NavCallback,
122    document: Document,
123}
124
125impl GraphWidget {
126    pub fn new(
127        container: HtmlElement,
128        api_url: &str,
129        on_navigate: Option<Box<dyn FnMut(String)>>,
130    ) -> Self {
131        let doc = crate::document().unwrap_or_else(|| {
132            web_sys::window()
133                .and_then(|w| w.document())
134                .expect("no document")
135        });
136        Self {
137            container,
138            api_url: api_url.to_string(),
139            nodes: Vec::new(),
140            edges: Vec::new(),
141            on_navigate: Rc::new(RefCell::new(on_navigate)),
142            document: doc,
143        }
144    }
145
146    pub async fn load(&mut self) -> Result<(), JsValue> {
147        let url = format!("{}/graph?limit=500", self.api_url);
148        let window = web_sys::window().ok_or_else(|| JsValue::from_str("no window"))?;
149        let resp_value = JsFuture::from(window.fetch_with_str(&url)).await?;
150        let resp: Response = resp_value.dyn_into()?;
151        if !resp.ok() {
152            return Err(JsValue::from_str(&format!("HTTP {}", resp.status())));
153        }
154        let text = JsFuture::from(resp.text()?).await?;
155        let body = text.as_string().unwrap_or_default();
156
157        let graph: GraphResponse =
158            serde_json::from_str(&body).map_err(|e| JsValue::from_str(&format!("JSON: {e}")))?;
159
160        let nodes: Vec<NodeData> = graph.nodes.into_iter().map(|n| n.data).collect();
161        let edges: Vec<EdgeData> = graph.edges.into_iter().map(|e| e.data).collect();
162
163        self.nodes = nodes;
164        self.edges = edges;
165        self.render();
166        Ok(())
167    }
168
169    fn render(&self) {
170        self.container.set_inner_html("");
171
172        if self.nodes.is_empty() {
173            return;
174        }
175
176        let positions = grid_layout(&self.nodes, CANVAS_W, CANVAS_H);
177
178        let ns = "http://www.w3.org/2000/svg";
179        let svg: SvgsvgElement = self
180            .document
181            .create_element_ns(Some(ns), "svg")
182            .unwrap()
183            .dyn_into()
184            .unwrap();
185        svg.set_attribute("viewBox", &format!("0 0 {} {}", CANVAS_W as u32, CANVAS_H as u32)).ok();
186        svg.set_attribute("width", "100%").ok();
187        svg.set_attribute("preserveAspectRatio", "xMidYMid meet").ok();
188        svg.style().set_property("display", "block").ok();
189        svg.style().set_property("margin", "1.5rem auto 0").ok();
190        svg.style().set_property("max-width", "100%").ok();
191        svg.style().set_property("height", "auto").ok();
192        svg.style().set_property("background", "rgba(255,255,255,0.02)").ok();
193        svg.style().set_property("border-radius", "12px").ok();
194        svg.style().set_property("border", "1px solid rgba(216,168,93,0.15)").ok();
195
196        // Estilo inline en SVG: respiración y transiciones
197        let style_el = self.document.create_element_ns(Some(ns), "style").unwrap();
198        style_el.set_text_content(Some(
199            "@keyframes graph-breathe {\
200              0%, 100% { opacity: 1; }\
201              50% { opacity: 0.92; }\
202            }\
203            .gb-svg { animation: graph-breathe 5s ease-in-out infinite; }\
204            .gb-node { transition: filter 250ms ease, opacity 200ms ease; }\
205            .gb-node:hover { filter: drop-shadow(0 0 14px rgba(255,255,255,0.2)); }\
206            .gb-edge-group { pointer-events: none; }\
207            .gb-line { transition: opacity 400ms ease; }",
208        ));
209        svg.append_child(&style_el).ok();
210
211        // Grupo para aristas (sin animación de respiración, están detrás)
212        let edges_group: web_sys::SvgElement = self
213            .document
214            .create_element_ns(Some(ns), "g")
215            .unwrap()
216            .dyn_into()
217            .unwrap();
218        edges_group.set_attribute("class", "gb-edge-group").ok();
219
220        // Grupo para nodos (con respiración, encima)
221        let nodes_group: web_sys::SvgElement = self
222            .document
223            .create_element_ns(Some(ns), "g")
224            .unwrap()
225            .dyn_into()
226            .unwrap();
227        nodes_group.set_attribute("class", "gb-svg").ok();
228
229        // Mapas: UUID → posición y color
230        let pos_map: std::collections::HashMap<&str, (f64, f64)> = positions
231            .iter()
232            .map(|(id, p)| (id.as_str(), *p))
233            .collect();
234        let color_map: std::collections::HashMap<&str, &str> = self.nodes
235            .iter()
236            .map(|n| (n.id.as_str(), camino_color(&n.camino)))
237            .collect();
238
239        // ── Aristas: mezcla de colores de los nodos que conecta ──
240        let mut drawn = std::collections::HashSet::new();
241        for edge in &self.edges {
242            let key = if edge.source < edge.target {
243                (edge.source.as_str(), edge.target.as_str())
244            } else {
245                (edge.target.as_str(), edge.source.as_str())
246            };
247            if !drawn.insert(key) { continue; }
248
249            let Some((x1, y1)) = pos_map.get(edge.source.as_str()) else { continue; };
250            let Some((x2, y2)) = pos_map.get(edge.target.as_str()) else { continue; };
251
252            let c1 = color_map.get(edge.source.as_str()).copied().unwrap_or("#888");
253            let c2 = color_map.get(edge.target.as_str()).copied().unwrap_or("#888");
254
255            let w = edge.weight.unwrap_or(0.7);
256            // EXAGERADO: grosor 1 a 10px, máximo contraste
257            // weight 0.50 → 3px, weight 0.95 → 9px
258            let thick = 1.5 + w * 8.0;
259
260            // Color más saturado: mezcla sin gris, cada canal al extremo
261            let blended = blend_colors(c1, c2, 0.5);
262            let (br, bg, bb) = parse_hex(&blended);
263            // Brillo exagerado: peso bajo = color puro; peso alto → blanco
264            let bright_factor = w * 0.7;
265            let r = (br as f64 + (255.0 - br as f64) * bright_factor).min(255.0) as u32;
266            let g = (bg as f64 + (255.0 - bg as f64) * bright_factor).min(255.0) as u32;
267            let b = (bb as f64 + (255.0 - bb as f64) * bright_factor).min(255.0) as u32;
268
269            // Opacidad: peso bajo = 40%, peso alto = 95%
270            let alpha = 0.40 + w * 0.55;
271
272            let line: SvgLineElement = self
273                .document
274                .create_element_ns(Some(ns), "line")
275                .unwrap()
276                .dyn_into()
277                .unwrap();
278            line.set_attribute("x1", &format!("{:.1}", x1)).ok();
279            line.set_attribute("y1", &format!("{:.1}", y1)).ok();
280            line.set_attribute("x2", &format!("{:.1}", x2)).ok();
281            line.set_attribute("y2", &format!("{:.1}", y2)).ok();
282            line.set_attribute("stroke", &format!("#{:02x}{:02x}{:02x}", r, g, b)).ok();
283            line.set_attribute("stroke-width", &format!("{:.1}", thick)).ok();
284            line.set_attribute("stroke-opacity", &format!("{:.2}", alpha)).ok();
285            line.set_attribute("class", "gb-line").ok();
286            edges_group.append_child(&line).ok();
287        }
288
289        // ── Nodos ──
290        let on_nav = self.on_navigate.clone();
291        for (i, node) in self.nodes.iter().enumerate() {
292            let Some((cx, cy)) = positions.get(i).map(|(_, p)| *p) else { continue; };
293            let color = camino_color(&node.camino).to_string();
294            let label = if node.name.chars().count() > 20 {
295                let cutoff: String = node.name.chars().take(18).collect();
296                format!("{}…", cutoff)
297            } else {
298                node.name.clone()
299            };
300            let camino_up = node.camino.to_uppercase();
301
302            let g: web_sys::SvgElement = self
303                .document
304                .create_element_ns(Some(ns), "g")
305                .unwrap()
306                .dyn_into()
307                .unwrap();
308            g.style().set_property("cursor", "pointer").ok();
309            g.set_attribute("class", "gb-node").ok();
310            g.set_attribute("title", &format!("{} — {}", node.name, camino_up)).ok();
311
312            let rx = cx - NODE_W / 2.0;
313            let ry = cy - NODE_H / 2.0;
314
315            let glow: SvgCircleElement = self
316                .document
317                .create_element_ns(Some(ns), "circle")
318                .unwrap()
319                .dyn_into()
320                .unwrap();
321            glow.set_attribute("cx", &format!("{:.1}", cx)).ok();
322            glow.set_attribute("cy", &format!("{:.1}", cy)).ok();
323            glow.set_attribute("r", "32").ok();
324            glow.set_attribute("fill", &color).ok();
325            glow.set_attribute("fill-opacity", "0.05").ok();
326            g.append_child(&glow).ok();
327
328            let rect: SvgRectElement = self
329                .document
330                .create_element_ns(Some(ns), "rect")
331                .unwrap()
332                .dyn_into()
333                .unwrap();
334            rect.set_attribute("x", &format!("{:.1}", rx)).ok();
335            rect.set_attribute("y", &format!("{:.1}", ry)).ok();
336            rect.set_attribute("width", &format!("{:.1}", NODE_W)).ok();
337            rect.set_attribute("height", &format!("{:.1}", NODE_H)).ok();
338            rect.set_attribute("rx", "8").ok();
339            rect.set_attribute("ry", "8").ok();
340            rect.set_attribute("fill", &color).ok();
341            rect.set_attribute("fill-opacity", "0.28").ok();
342            rect.set_attribute("stroke", &color).ok();
343            rect.set_attribute("stroke-width", "1.8").ok();
344            rect.set_attribute("stroke-opacity", "0.7").ok();
345            rect.style().set_property("transition", "all 200ms ease").ok();
346
347            let text: SvgTextElement = self
348                .document
349                .create_element_ns(Some(ns), "text")
350                .unwrap()
351                .dyn_into()
352                .unwrap();
353            text.set_attribute("x", &format!("{:.1}", cx)).ok();
354            text.set_attribute("y", &format!("{:.1}", cy - 2.0)).ok();
355            text.set_attribute("text-anchor", "middle").ok();
356            text.set_attribute("dominant-baseline", "middle").ok();
357            text.set_attribute("fill", "rgba(232,234,245,0.88)").ok();
358            text.set_attribute("font-size", "13").ok();
359            text.set_attribute("font-family", "Inter, system-ui, sans-serif").ok();
360            text.set_attribute("font-weight", "500").ok();
361            text.set_text_content(Some(&label));
362
363            let sub: SvgTextElement = self
364                .document
365                .create_element_ns(Some(ns), "text")
366                .unwrap()
367                .dyn_into()
368                .unwrap();
369            sub.set_attribute("x", &format!("{:.1}", cx)).ok();
370            sub.set_attribute("y", &format!("{:.1}", cy + 15.0)).ok();
371            sub.set_attribute("text-anchor", "middle").ok();
372            sub.set_attribute("dominant-baseline", "middle").ok();
373            sub.set_attribute("fill", "rgba(232,234,245,0.45)").ok();
374            sub.set_attribute("font-size", "9").ok();
375            sub.set_attribute("font-family", "Inter, system-ui, sans-serif").ok();
376            sub.set_attribute("letter-spacing", "0.25em").ok();
377            sub.set_text_content(Some(&camino_up));
378
379            g.append_child(&rect).ok();
380            g.append_child(&text).ok();
381            g.append_child(&sub).ok();
382
383            // Hover
384            let rect_clone = rect.clone();
385            let color_c = color.clone();
386            let glow_clone = glow.clone();
387            let enter = Closure::<dyn FnMut(MouseEvent)>::new(move |_| {
388                rect_clone.set_attribute("fill-opacity", "0.55").ok();
389                rect_clone.set_attribute("stroke-opacity", "1").ok();
390                rect_clone.style()
391                    .set_property("filter", &format!("drop-shadow(0 0 12px {})", color_c))
392                    .ok();
393                glow_clone.set_attribute("fill-opacity", "0.20").ok();
394            });
395            g.add_event_listener_with_callback("mouseenter", enter.as_ref().unchecked_ref()).ok();
396            enter.forget();
397
398            let rect_clone2 = rect.clone();
399            let glow_clone2 = glow.clone();
400            let leave = Closure::<dyn FnMut(MouseEvent)>::new(move |_| {
401                rect_clone2.set_attribute("fill-opacity", "0.28").ok();
402                rect_clone2.set_attribute("stroke-opacity", "0.7").ok();
403                rect_clone2.style().set_property("filter", "none").ok();
404                glow_clone2.set_attribute("fill-opacity", "0.05").ok();
405            });
406            g.add_event_listener_with_callback("mouseleave", leave.as_ref().unchecked_ref()).ok();
407            leave.forget();
408
409            let doc_id = node.doc_id.clone().unwrap_or_default();
410            let on_nav2 = on_nav.clone();
411            let click = Closure::<dyn FnMut(MouseEvent)>::new(move |_| {
412                let mut cb = on_nav2.borrow_mut();
413                if let Some(ref mut f) = *cb { f(doc_id.clone()); }
414            });
415            g.add_event_listener_with_callback("click", click.as_ref().unchecked_ref()).ok();
416            click.forget();
417
418            nodes_group.append_child(&g).ok();
419        }
420
421        svg.append_child(&edges_group).ok();
422        svg.append_child(&nodes_group).ok();
423        self.container.append_child(&svg).ok();
424    }
425}
426
427// ─── Layout grid: 3 columnas ─────────────────────────────────────
428
429fn grid_layout(nodes: &[NodeData], w: f64, h: f64) -> Vec<(String, (f64, f64))> {
430    let n = nodes.len();
431    if n == 0 { return vec![]; }
432
433    let rows = (n + COLS - 1) / COLS;
434    let actual_rows = rows.max(3);
435    let margin_x = NODE_W / 2.0 + 20.0;
436    let margin_y = NODE_H / 2.0 + 20.0;
437    let usable_w = w - margin_x * 2.0;
438    let usable_h = h - margin_y * 2.0;
439    let col_gap = usable_w / (COLS as f64);
440    let row_gap = usable_h / (actual_rows as f64);
441
442    let mut out = Vec::with_capacity(n);
443    for (i, node) in nodes.iter().enumerate() {
444        let col = i % COLS;
445        let row = i / COLS;
446        let offset_x = if row == rows - 1 && n % COLS != 0 {
447            let remaining = n - row * COLS;
448            (usable_w - remaining as f64 * col_gap) / 2.0
449        } else { 0.0 };
450        let x = margin_x + offset_x + col as f64 * col_gap + col_gap / 2.0;
451        let y = margin_y + row as f64 * row_gap + row_gap / 2.0;
452        out.push((node.id.clone(), (x, y)));
453    }
454    out
455}