tawasuyu

tawasuyu/brahman

Rust 320TOML 122JSON 14Markdown 114164 Sutichaykuna

⎇ 9db79617eb50a5faf5c54e7f68a86c9b4cd7ca69 crates/apps/gioser-web/cytoscape-graph.js JavaScript · 273 siq'ikuna · 8.8 KB Ñawpa willay Pi imata llamkarqan ch'uya

gioser-graph: wrap init in requestAnimationFrame for hidden deck 9db79617e · Sergio ·

1/**
2 * gioser-graph.js — Grafo semántico con Cytoscape.js
3 *
4 * Detecta automáticamente elementos <gioser-graph> agregados al DOM
5 * (incluso los creados dinámicamente por el WASM) y monta el grafo.
6 *
7 * Efecto "wineandcheesemap": clic en nodo → centra + desvanece resto.
8 * Doble clic → callback de navegación (window.__gioserGraphNavigate).
9 */
10
11(function () {
12  'use strict';
13
14  var COLORS = {
15    logos:  '#d0dbff',
16    aire:   '#d0dbff',
17    nomos:  '#f59056',
18    fuego:  '#f59056',
19    kay:    '#d49873',
20    tierra: '#d49873',
21    uku:    '#6cd0f3',
22    agua:   '#6cd0f3',
23  };
24
25  function caminoColor(c) { return COLORS[c] || '#888'; }
26
27  function initGraph(container) {
28    var apiUrl = container.getAttribute('data-api-url') || 'https://api.gioser.net';
29    var onNavigate = window.__gioserGraphNavigate || null;
30
31    if (typeof cytoscape === 'undefined') {
32      var check = setInterval(function () {
33        if (typeof cytoscape !== 'undefined') {
34          clearInterval(check);
35          initGraph(container);
36        }
37      }, 100);
38      return;
39    }
40
41    // Esperar un frame antes de fetch — el deck puede estar oculto
42    // y Cytoscape necesita tamaño real para el layout cose.
43    requestAnimationFrame(function () {
44
45    fetch(apiUrl + '/graph?limit=500')
46      .then(function (r) { return r.json(); })
47      .then(function (data) {
48        if (!data.nodes || data.nodes.length === 0) return;
49
50        var elements = [];
51
52        for (var i = 0; i < data.nodes.length; i++) {
53          var d = data.nodes[i].data;
54          if (!d.doc_id) continue;
55          var color = caminoColor(d.camino);
56          elements.push({
57            group: 'nodes',
58            data: {
59              id: d.id,
60              doc_id: d.doc_id,
61              label: d.name.length > 24 ? d.name.slice(0, 22) + '\u2026' : d.name,
62              camino: d.camino.toUpperCase(),
63              color: color,
64            },
65          });
66        }
67
68        var nodeIds = {};
69        for (var i = 0; i < elements.length; i++) {
70          nodeIds[elements[i].data.id] = true;
71        }
72
73        for (var i = 0; i < data.edges.length; i++) {
74          var ed = data.edges[i].data;
75          if (!nodeIds[ed.source] || !nodeIds[ed.target]) continue;
76          elements.push({
77            group: 'edges',
78            data: {
79              id: ed.id,
80              source: ed.source,
81              target: ed.target,
82              weight: ed.weight || 0.7,
83            },
84          });
85        }
86
87        var tipMap = {};
88        for (var i = 0; i < data.nodes.length; i++) {
89          var d = data.nodes[i].data;
90          if (d.doc_id) tipMap[d.id] = d;
91        }
92
93        // Layout: 'preset' primero con posiciones aleatorias para
94        // que el contenedor tome tamaño, luego cose cuando visible.
95        var cy = cytoscape({
96          container: container,
97          elements: elements,
98          style: [
99            {
100              selector: 'edge',
101              style: {
102                'width': 'mapData(weight, 0.5, 1.0, 0.5, 4.5)',
103                'line-color': 'rgba(255,255,255,0.16)',
104                'curve-style': 'haystack',
105                'haystack-radius': 0,
106                'opacity': 0.6,
107              },
108            },
109            {
110              selector: 'node',
111              style: {
112                'shape': 'round-rectangle',
113                'width': 130,
114                'height': 34,
115                'background-color': 'data(color)',
116                'background-opacity': 0.18,
117                'border-color': 'data(color)',
118                'border-width': 1.8,
119                'border-opacity': 0.55,
120                'color': 'rgba(232,234,245,0.88)',
121                'font-size': 11,
122                'font-family': 'Inter, system-ui, sans-serif',
123                'font-weight': 500,
124                'text-valign': 'center',
125                'text-halign': 'center',
126                'label': 'data(label)',
127                'min-zoomed-font-size': 8,
128                'transition-property': 'background-opacity, border-opacity, border-width',
129                'transition-duration': 180,
130              },
131            },
132          ],
133          layout: {
134            name: 'preset',
135            fit: false,
136          },
137        });
138
139        // Ahora aplicar layout cose con animación (se adaptará al tamaño real)
140        cy.layout({
141          name: 'cose',
142          animate: 'end',
143          animationEasing: 'ease-out',
144          animationDuration: 600,
145          idealEdgeLength: 150,
146          nodeRepulsion: 7000,
147          gravity: 0.2,
148          numIter: 800,
149          fit: true,
150          padding: 25,
151        }).run();
152
153        // Tooltip
154        var tooltipEl = document.createElement('div');
155        tooltipEl.className = 'cy-tooltip';
156        tooltipEl.style.cssText =
157          'position:absolute;z-index:10;pointer-events:none;' +
158          'background:rgba(6,5,13,0.90);color:#e8eaf5;' +
159          'padding:6px 10px;border-radius:8px;font-size:11px;' +
160          'font-family:Inter,sans-serif;line-height:1.4;' +
161          'border:1px solid rgba(255,255,255,0.10);' +
162          'backdrop-filter:blur(8px);max-width:220px;' +
163          'opacity:0;transition:opacity 180ms ease;';
164        container.style.position = 'relative';
165        container.appendChild(tooltipEl);
166
167        cy.on('mouseover', 'node', function (ev) {
168          var n = ev.target;
169          n.style({ 'background-opacity': 0.45, 'border-opacity': 0.9, 'border-width': 2.2 });
170          var tipData = tipMap[n.id()];
171          if (tipData && tipData.preview) {
172            tooltipEl.textContent = tipData.preview.slice(0, 130);
173            tooltipEl.style.opacity = '1';
174          }
175        });
176
177        cy.on('mouseout', 'node', function (ev) {
178          var n = ev.target;
179          n.style({ 'background-opacity': 0.18, 'border-opacity': 0.55, 'border-width': 1.8 });
180          tooltipEl.style.opacity = '0';
181        });
182
183        cy.on('mousemove', function (ev) {
184          if (tooltipEl.style.opacity === '1') {
185            var pos = ev.renderedPosition || { x: 0, y: 0 };
186            tooltipEl.style.left = (pos.x + 14) + 'px';
187            tooltipEl.style.top = (pos.y - 10) + 'px';
188          }
189        });
190
191        cy.on('click', 'node', function (ev) {
192          var node = ev.target;
193          cy.nodes().not(node).not(node.neighborhood()).forEach(function (n) {
194            n.style({ 'opacity': 0.12 });
195          });
196          cy.edges().forEach(function (e) {
197            e.style({ 'opacity': 0.06 });
198          });
199          node.neighborhood().nodes().forEach(function (n) {
200            n.style({ 'opacity': 1 });
201          });
202          node.style({ 'opacity': 1, 'background-opacity': 0.40, 'border-opacity': 1 });
203          node.connectedEdges().forEach(function (e) {
204            e.style({ 'opacity': 0.7 });
205          });
206          cy.animate({
207            center: { eles: node },
208            zoom: 2.5,
209            duration: 350,
210          });
211        });
212
213        cy.on('dblclick', 'node', function (ev) {
214          var docId = ev.target.data('doc_id');
215          if (onNavigate && docId) onNavigate(docId);
216        });
217
218        cy.on('click', function (ev) {
219          if (ev.target === cy) {
220            cy.nodes().forEach(function (n) {
221              n.style({ 'opacity': 1, 'background-opacity': 0.18, 'border-opacity': 0.55, 'border-width': 1.8 });
222            });
223            cy.edges().forEach(function (e) {
224              e.style({ 'opacity': 0.6 });
225            });
226            cy.animate({ zoom: 1, pan: { x: 0, y: 0 }, duration: 300 });
227          }
228        });
229
230        var ro = new ResizeObserver(function () {
231          cy.resize().fit(25);
232        });
233        ro.observe(container);
234      })
235      .catch(function (err) {
236        console.warn('gioser-graph: error:', err);
237        container.innerHTML =
238          '<div style="padding:1rem;text-align:center;color:rgba(232,234,245,0.30);' +
239          'font-size:0.8rem;font-family:Inter,sans-serif;">' +
240          '· grafo no disponible ·</div>';
241      });
242
243    }); // requestAnimationFrame
244  }
245
246  // MutationObserver: detecta <gioser-graph> agregados dinámicamente
247  var observer = new MutationObserver(function (mutations) {
248    for (var m = 0; m < mutations.length; m++) {
249      var added = mutations[m].addedNodes;
250      for (var i = 0; i < added.length; i++) {
251        var el = added[i];
252        if (el.tagName && el.tagName.toLowerCase() === 'gioser-graph') {
253          initGraph(el);
254        }
255        var graphs = el.querySelectorAll ? el.querySelectorAll('gioser-graph') : [];
256        for (var j = 0; j < graphs.length; j++) {
257          initGraph(graphs[j]);
258        }
259      }
260    }
261  });
262
263  observer.observe(document.documentElement, {
264    childList: true,
265    subtree: true,
266  });
267
268  // Inicializar los que ya existen
269  var existing = document.querySelectorAll('gioser-graph');
270  for (var i = 0; i < existing.length; i++) {
271    initGraph(existing[i]);
272  }
273})();