gioser

tawasuyu/brahman

Rust 582TOML 222Markdown 73JSON 198635 Definitions

⎇ 05f2e54ed1ebace301975819b16b515a23f23e48 crates/modules/gioser/gioser-graph-web/src/lib.rs Rust · 511 lines · 19.7 KB History Who touched what raw

gioser-web: draggable graph nodes, fixed controls, history.pushState routing 05f2e54ed · 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, PointerEvent, 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 {\
206              filter: drop-shadow(0 0 14px rgba(255,255,255,0.2));\
207            }\
208            .gb-edge-group { pointer-events: none; }\
209            .gb-line { transition: opacity 400ms ease; }",
210        ));
211        svg.append_child(&style_el).ok();
212
213        // Grupo para aristas (sin animación de respiración, están detrás)
214        let edges_group: web_sys::SvgElement = self
215            .document
216            .create_element_ns(Some(ns), "g")
217            .unwrap()
218            .dyn_into()
219            .unwrap();
220        edges_group.set_attribute("class", "gb-edge-group").ok();
221
222        // Grupo para nodos (con respiración, encima)
223        let nodes_group: web_sys::SvgElement = self
224            .document
225            .create_element_ns(Some(ns), "g")
226            .unwrap()
227            .dyn_into()
228            .unwrap();
229        nodes_group.set_attribute("class", "gb-svg").ok();
230
231        // Mapas: UUID → posición y color
232        let pos_map: std::collections::HashMap<&str, (f64, f64)> = positions
233            .iter()
234            .map(|(id, p)| (id.as_str(), *p))
235            .collect();
236        let color_map: std::collections::HashMap<&str, &str> = self.nodes
237            .iter()
238            .map(|n| (n.id.as_str(), camino_color(&n.camino)))
239            .collect();
240
241        // ── Aristas: mezcla de colores de los nodos que conecta ──
242        let mut drawn = std::collections::HashSet::new();
243        for edge in &self.edges {
244            let key = if edge.source < edge.target {
245                (edge.source.as_str(), edge.target.as_str())
246            } else {
247                (edge.target.as_str(), edge.source.as_str())
248            };
249            if !drawn.insert(key) { continue; }
250
251            let Some((x1, y1)) = pos_map.get(edge.source.as_str()) else { continue; };
252            let Some((x2, y2)) = pos_map.get(edge.target.as_str()) else { continue; };
253
254            let c1 = color_map.get(edge.source.as_str()).copied().unwrap_or("#888");
255            let c2 = color_map.get(edge.target.as_str()).copied().unwrap_or("#888");
256
257            let w = edge.weight.unwrap_or(0.7);
258
259            // Min-max scaling: expandir el rango real (0.83-0.93) a 0.0-1.0
260            // Con un mínimo global de 0.80 para capturar todo
261            let norm = ((w - 0.80) / 0.15).clamp(0.0, 1.0);
262            // Curva cuadrática para exagerar diferencias: norm²
263            let expanded = norm * norm;
264
265            // Grosor sutil: 0.5px a 3.5px (no grueso, diferenciado)
266            let thick = 0.8 + expanded * 3.0;
267
268            // Color mezclado
269            let blended = blend_colors(c1, c2, 0.5);
270            let (br, bg, bb) = parse_hex(&blended);
271            // Brillo: sin expander, normal 0-1, sútil
272            let bright_factor = norm * 0.5;
273            let r = (br as f64 + (255.0 - br as f64) * bright_factor).min(255.0) as u32;
274            let g = (bg as f64 + (255.0 - bg as f64) * bright_factor).min(255.0) as u32;
275            let b = (bb as f64 + (255.0 - bb as f64) * bright_factor).min(255.0) as u32;
276
277            // Opacidad baja y sutil: 15% a 40%
278            let alpha = 0.12 + expanded * 0.30;
279
280            let line: SvgLineElement = self
281                .document
282                .create_element_ns(Some(ns), "line")
283                .unwrap()
284                .dyn_into()
285                .unwrap();
286            line.set_attribute("x1", &format!("{:.1}", x1)).ok();
287            line.set_attribute("y1", &format!("{:.1}", y1)).ok();
288            line.set_attribute("x2", &format!("{:.1}", x2)).ok();
289            line.set_attribute("y2", &format!("{:.1}", y2)).ok();
290            line.set_attribute("stroke", &format!("#{:02x}{:02x}{:02x}", r, g, b)).ok();
291            line.set_attribute("stroke-width", &format!("{:.1}", thick)).ok();
292            line.set_attribute("stroke-opacity", &format!("{:.2}", alpha)).ok();
293            line.set_attribute("class", "gb-line").ok();
294            edges_group.append_child(&line).ok();
295        }
296
297        // ── Nodos ──
298        let on_nav = self.on_navigate.clone();
299        for (i, node) in self.nodes.iter().enumerate() {
300            let Some((cx, cy)) = positions.get(i).map(|(_, p)| *p) else { continue; };
301            let color = camino_color(&node.camino).to_string();
302            let label = if node.name.chars().count() > 20 {
303                let cutoff: String = node.name.chars().take(18).collect();
304                format!("{}…", cutoff)
305            } else {
306                node.name.clone()
307            };
308            let camino_up = node.camino.to_uppercase();
309
310            let g: web_sys::SvgElement = self
311                .document
312                .create_element_ns(Some(ns), "g")
313                .unwrap()
314                .dyn_into()
315                .unwrap();
316            g.style().set_property("cursor", "pointer").ok();
317            g.set_attribute("class", "gb-node").ok();
318            g.set_attribute("title", &format!("{} — {}", node.name, camino_up)).ok();
319
320            let rx = cx - NODE_W / 2.0;
321            let ry = cy - NODE_H / 2.0;
322
323            let glow: SvgCircleElement = self
324                .document
325                .create_element_ns(Some(ns), "circle")
326                .unwrap()
327                .dyn_into()
328                .unwrap();
329            glow.set_attribute("cx", &format!("{:.1}", cx)).ok();
330            glow.set_attribute("cy", &format!("{:.1}", cy)).ok();
331            glow.set_attribute("r", "32").ok();
332            glow.set_attribute("fill", &color).ok();
333            glow.set_attribute("fill-opacity", "0.05").ok();
334            g.append_child(&glow).ok();
335
336            let rect: SvgRectElement = self
337                .document
338                .create_element_ns(Some(ns), "rect")
339                .unwrap()
340                .dyn_into()
341                .unwrap();
342            rect.set_attribute("x", &format!("{:.1}", rx)).ok();
343            rect.set_attribute("y", &format!("{:.1}", ry)).ok();
344            rect.set_attribute("width", &format!("{:.1}", NODE_W)).ok();
345            rect.set_attribute("height", &format!("{:.1}", NODE_H)).ok();
346            rect.set_attribute("rx", "8").ok();
347            rect.set_attribute("ry", "8").ok();
348            rect.set_attribute("fill", &color).ok();
349            rect.set_attribute("fill-opacity", "0.28").ok();
350            rect.set_attribute("stroke", &color).ok();
351            rect.set_attribute("stroke-width", "1.8").ok();
352            rect.set_attribute("stroke-opacity", "0.7").ok();
353            rect.style().set_property("transition", "all 200ms ease").ok();
354
355            let text: SvgTextElement = self
356                .document
357                .create_element_ns(Some(ns), "text")
358                .unwrap()
359                .dyn_into()
360                .unwrap();
361            text.set_attribute("x", &format!("{:.1}", cx)).ok();
362            text.set_attribute("y", &format!("{:.1}", cy - 2.0)).ok();
363            text.set_attribute("text-anchor", "middle").ok();
364            text.set_attribute("dominant-baseline", "middle").ok();
365            text.set_attribute("fill", "rgba(232,234,245,0.88)").ok();
366            text.set_attribute("font-size", "13").ok();
367            text.set_attribute("font-family", "Inter, system-ui, sans-serif").ok();
368            text.set_attribute("font-weight", "500").ok();
369            text.set_text_content(Some(&label));
370
371            let sub: SvgTextElement = self
372                .document
373                .create_element_ns(Some(ns), "text")
374                .unwrap()
375                .dyn_into()
376                .unwrap();
377            sub.set_attribute("x", &format!("{:.1}", cx)).ok();
378            sub.set_attribute("y", &format!("{:.1}", cy + 15.0)).ok();
379            sub.set_attribute("text-anchor", "middle").ok();
380            sub.set_attribute("dominant-baseline", "middle").ok();
381            sub.set_attribute("fill", "rgba(232,234,245,0.45)").ok();
382            sub.set_attribute("font-size", "9").ok();
383            sub.set_attribute("font-family", "Inter, system-ui, sans-serif").ok();
384            sub.set_attribute("letter-spacing", "0.25em").ok();
385            sub.set_text_content(Some(&camino_up));
386
387            g.append_child(&rect).ok();
388            g.append_child(&text).ok();
389            g.append_child(&sub).ok();
390
391            // Hover + drag
392            let rect_h = rect.clone();
393            let col_h = color.clone();
394            let glow_h = glow.clone();
395            let g_hover = g.clone();
396            let g_clone_for_drag = g.clone();
397
398            let enter = Closure::<dyn FnMut(MouseEvent)>::new(move |_| {
399                rect_h.set_attribute("fill-opacity", "0.55").ok();
400                rect_h.set_attribute("stroke-opacity", "1").ok();
401                rect_h.style()
402                    .set_property("filter", &format!("drop-shadow(0 0 12px {})", col_h))
403                    .ok();
404                glow_h.set_attribute("fill-opacity", "0.20").ok();
405            });
406            g_hover.add_event_listener_with_callback("mouseenter", enter.as_ref().unchecked_ref()).ok();
407            enter.forget();
408
409            let rect_l = rect.clone();
410            let glow_l = glow.clone();
411            let leave = Closure::<dyn FnMut(MouseEvent)>::new(move |_| {
412                rect_l.set_attribute("fill-opacity", "0.28").ok();
413                rect_l.set_attribute("stroke-opacity", "0.7").ok();
414                rect_l.style().set_property("filter", "none").ok();
415                glow_l.set_attribute("fill-opacity", "0.05").ok();
416            });
417            g.add_event_listener_with_callback("mouseleave", leave.as_ref().unchecked_ref()).ok();
418            leave.forget();
419
420            // Click → navegar
421            let nav_target = node.camino.clone();
422            let on_nav2 = on_nav.clone();
423            let click = Closure::<dyn FnMut(MouseEvent)>::new(move |_| {
424                let mut cb = on_nav2.borrow_mut();
425                if let Some(ref mut f) = *cb { f(nav_target.clone()); }
426            });
427            g.add_event_listener_with_callback("click", click.as_ref().unchecked_ref()).ok();
428            click.forget();
429
430            // Drag: pointerdown → move → up (reacomodar al soltar)
431            let g_drag = g.clone();
432            let g_move = g.clone();
433            let g_up = g.clone();
434            let drag_start = Rc::new(RefCell::new(None::<(f64, f64, f64, f64)>));
435            let drag_start2 = drag_start.clone();
436            let drag_start3 = drag_start.clone();
437
438            let pdown = Closure::<dyn FnMut(PointerEvent)>::new(move |e: PointerEvent| {
439                e.prevent_default();
440                let g_rect = g_drag.get_bounding_client_rect();
441                *drag_start.borrow_mut() = Some((
442                    e.client_x() as f64,
443                    e.client_y() as f64,
444                    g_rect.left() + g_rect.width() / 2.0,
445                    g_rect.top() + g_rect.height() / 2.0,
446                ));
447                g_drag.set_pointer_capture(e.pointer_id()).ok();
448            });
449            g.add_event_listener_with_callback("pointerdown", pdown.as_ref().unchecked_ref()).ok();
450            pdown.forget();
451
452            let pmove = Closure::<dyn FnMut(PointerEvent)>::new(move |e: PointerEvent| {
453                if let Some((start_cx, start_cy, _, _)) = *drag_start2.borrow() {
454                    let dx = e.client_x() as f64 - start_cx;
455                    let dy = e.client_y() as f64 - start_cy;
456                    g_move.set_attribute(
457                        "transform",
458                        &format!("translate({:.1},{:.1})", dx, dy),
459                    ).ok();
460                }
461            });
462            g.add_event_listener_with_callback("pointermove", pmove.as_ref().unchecked_ref()).ok();
463            pmove.forget();
464
465            let pup = Closure::<dyn FnMut(PointerEvent)>::new(move |_e: PointerEvent| {
466                *drag_start3.borrow_mut() = None;
467                g_up.set_attribute("transform", "translate(0,0)").ok();
468            });
469            g.add_event_listener_with_callback("pointerup", pup.as_ref().unchecked_ref()).ok();
470            pup.forget();
471
472            g.style().set_property("transition", "transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1)").ok();
473
474            nodes_group.append_child(&g).ok();
475        }
476
477        svg.append_child(&edges_group).ok();
478        svg.append_child(&nodes_group).ok();
479        self.container.append_child(&svg).ok();
480    }
481}
482
483// ─── Layout grid: 3 columnas ─────────────────────────────────────
484
485fn grid_layout(nodes: &[NodeData], w: f64, h: f64) -> Vec<(String, (f64, f64))> {
486    let n = nodes.len();
487    if n == 0 { return vec![]; }
488
489    let rows = (n + COLS - 1) / COLS;
490    let actual_rows = rows.max(3);
491    let margin_x = NODE_W / 2.0 + 20.0;
492    let margin_y = NODE_H / 2.0 + 20.0;
493    let usable_w = w - margin_x * 2.0;
494    let usable_h = h - margin_y * 2.0;
495    let col_gap = usable_w / (COLS as f64);
496    let row_gap = usable_h / (actual_rows as f64);
497
498    let mut out = Vec::with_capacity(n);
499    for (i, node) in nodes.iter().enumerate() {
500        let col = i % COLS;
501        let row = i / COLS;
502        let offset_x = if row == rows - 1 && n % COLS != 0 {
503            let remaining = n - row * COLS;
504            (usable_w - remaining as f64 * col_gap) / 2.0
505        } else { 0.0 };
506        let x = margin_x + offset_x + col as f64 * col_gap + col_gap / 2.0;
507        let y = margin_y + row as f64 * row_gap + row_gap / 2.0;
508        out.push((node.id.clone(), (x, y)));
509    }
510    out
511}