tawasuyu

tawasuyu/brahman

Rust 570TOML 215Markdown 68JSON 198261 Definitions

⎇ 24218447e3876e291f8067aa93cdcb22c3c7f3d5 crates/apps/gioser-web/cytoscape-graph.js JavaScript · 226 lines · 8.4 KB History Who touched what raw

gioser-graph: poll container width before Cytoscape init 24218447e · 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.
6 *
7 * Espera a que el contenedor tenga tamaño real (>0) antes de montar
8 * Cytoscape, porque el deck arranca oculto (transform:scale(0)).
9 *
10 * Efecto "wineandcheesemap": clic en nodo → centra + desvanece resto.
11 * Doble clic → callback de navegación (window.__gioserGraphNavigate).
12 */
13
14(function () {
15  'use strict';
16
17  var COLORS = {
18    logos:  '#d0dbff', aire:   '#d0dbff',
19    nomos:  '#f59056', fuego:  '#f59056',
20    kay:    '#d49873', tierra: '#d49873',
21    uku:    '#6cd0f3', agua:   '#6cd0f3',
22  };
23  function caminoColor(c) { return COLORS[c] || '#888'; }
24
25  function initGraph(container) {
26    var apiUrl = container.getAttribute('data-api-url') || 'https://api.gioser.net';
27    var onNavigate = window.__gioserGraphNavigate || null;
28
29    if (typeof cytoscape === 'undefined') {
30      var chk = setInterval(function () {
31        if (typeof cytoscape !== 'undefined') { clearInterval(chk); initGraph(container); }
32      }, 100);
33      return;
34    }
35
36    // Esperar a que el contenedor tenga ancho real (deck oculto → 0)
37    var wait = setInterval(function () {
38      if (container.offsetWidth > 0 || container.offsetHeight > 0) {
39        clearInterval(wait);
40        doInit(container, apiUrl, onNavigate);
41      }
42    }, 50);
43
44    // Timeout: si después de 10s sigue en 0, forzar con tamaño mínimo
45    setTimeout(function () {
46      if (container.offsetWidth === 0 || container.offsetHeight === 0) {
47        clearInterval(wait);
48        container.style.minWidth = '200px';
49        container.style.minHeight = '180px';
50        doInit(container, apiUrl, onNavigate);
51      }
52    }, 10000);
53  }
54
55  function doInit(container, apiUrl, onNavigate) {
56    fetch(apiUrl + '/graph?limit=500')
57      .then(function (r) { return r.json(); })
58      .then(function (data) {
59        if (!data.nodes || data.nodes.length === 0) {
60          container.innerHTML = '';
61          return;
62        }
63
64        var elements = [];
65        for (var i = 0; i < data.nodes.length; i++) {
66          var d = data.nodes[i].data;
67          if (!d.doc_id) continue;
68          var color = caminoColor(d.camino);
69          elements.push({ group: 'nodes', data: {
70            id: d.id, doc_id: d.doc_id,
71            label: d.name.length > 24 ? d.name.slice(0, 22) + '\u2026' : d.name,
72            camino: d.camino.toUpperCase(), color: color,
73          }});
74        }
75
76        var nodeIds = {};
77        for (var i = 0; i < elements.length; i++) nodeIds[elements[i].data.id] = true;
78
79        for (var i = 0; i < data.edges.length; i++) {
80          var ed = data.edges[i].data;
81          if (!nodeIds[ed.source] || !nodeIds[ed.target]) continue;
82          elements.push({ group: 'edges', data: {
83            id: ed.id, source: ed.source, target: ed.target,
84            weight: ed.weight || 0.7,
85          }});
86        }
87
88        var tipMap = {};
89        for (var i = 0; i < data.nodes.length; i++) {
90          var d = data.nodes[i].data;
91          if (d.doc_id) tipMap[d.id] = d;
92        }
93
94        var cy = cytoscape({
95          container: container,
96          elements: elements,
97          style: [
98            { selector: 'edge', style: {
99              'width': 'mapData(weight, 0.5, 1.0, 0.5, 4.5)',
100              'line-color': 'rgba(255,255,255,0.16)',
101              'curve-style': 'haystack', 'haystack-radius': 0,
102              'opacity': 0.6,
103            }},
104            { selector: 'node', style: {
105              'shape': 'round-rectangle',
106              'width': 130, 'height': 34,
107              'background-color': 'data(color)', 'background-opacity': 0.18,
108              'border-color': 'data(color)', 'border-width': 1.8, 'border-opacity': 0.55,
109              'color': 'rgba(232,234,245,0.88)',
110              'font-size': 11, 'font-family': 'Inter, system-ui, sans-serif',
111              'font-weight': 500,
112              'text-valign': 'center', 'text-halign': 'center',
113              'label': 'data(label)', 'min-zoomed-font-size': 8,
114              'transition-property': 'background-opacity, border-opacity, border-width',
115              'transition-duration': 180,
116            }},
117          ],
118          layout: { name: 'preset', fit: false },
119        });
120
121        cy.layout({
122          name: 'cose',
123          animate: 'end',
124          animationEasing: 'ease-out',
125          animationDuration: 600,
126          idealEdgeLength: 150,
127          nodeRepulsion: 7000,
128          gravity: 0.2,
129          numIter: 800,
130          fit: true,
131          padding: 25,
132        }).run();
133
134        // Tooltip
135        var tooltipEl = document.createElement('div');
136        tooltipEl.className = 'cy-tooltip';
137        tooltipEl.style.cssText =
138          'position:absolute;z-index:10;pointer-events:none;' +
139          'background:rgba(6,5,13,0.90);color:#e8eaf5;' +
140          'padding:6px 10px;border-radius:8px;font-size:11px;' +
141          'font-family:Inter,sans-serif;line-height:1.4;' +
142          'border:1px solid rgba(255,255,255,0.10);' +
143          'backdrop-filter:blur(8px);max-width:220px;' +
144          'opacity:0;transition:opacity 180ms ease;';
145        container.style.position = 'relative';
146        container.appendChild(tooltipEl);
147
148        cy.on('mouseover', 'node', function (ev) {
149          var n = ev.target;
150          n.style({ 'background-opacity': 0.45, 'border-opacity': 0.9, 'border-width': 2.2 });
151          var t = tipMap[n.id()];
152          if (t && t.preview) {
153            tooltipEl.textContent = t.preview.slice(0, 130);
154            tooltipEl.style.opacity = '1';
155          }
156        });
157
158        cy.on('mouseout', 'node', function (ev) {
159          ev.target.style({ 'background-opacity': 0.18, 'border-opacity': 0.55, 'border-width': 1.8 });
160          tooltipEl.style.opacity = '0';
161        });
162
163        cy.on('mousemove', function (ev) {
164          if (tooltipEl.style.opacity === '1') {
165            var p = ev.renderedPosition || { x: 0, y: 0 };
166            tooltipEl.style.left = (p.x + 14) + 'px';
167            tooltipEl.style.top = (p.y - 10) + 'px';
168          }
169        });
170
171        cy.on('click', 'node', function (ev) {
172          var node = ev.target;
173          cy.nodes().not(node).not(node.neighborhood()).forEach(function (n) {
174            n.style({ 'opacity': 0.12 });
175          });
176          cy.edges().forEach(function (e) { e.style({ 'opacity': 0.06 }); });
177          node.neighborhood().nodes().forEach(function (n) { n.style({ 'opacity': 1 }); });
178          node.style({ 'opacity': 1, 'background-opacity': 0.40, 'border-opacity': 1 });
179          node.connectedEdges().forEach(function (e) { e.style({ 'opacity': 0.7 }); });
180          cy.animate({ center: { eles: node }, zoom: 2.5, duration: 350 });
181        });
182
183        cy.on('dblclick', 'node', function (ev) {
184          var docId = ev.target.data('doc_id');
185          if (onNavigate && docId) onNavigate(docId);
186        });
187
188        cy.on('click', function (ev) {
189          if (ev.target === cy) {
190            cy.nodes().forEach(function (n) {
191              n.style({ 'opacity': 1, 'background-opacity': 0.18, 'border-opacity': 0.55, 'border-width': 1.8 });
192            });
193            cy.edges().forEach(function (e) { e.style({ 'opacity': 0.6 }); });
194            cy.animate({ zoom: 1, pan: { x: 0, y: 0 }, duration: 300 });
195          }
196        });
197
198        var ro = new ResizeObserver(function () { cy.resize().fit(25); });
199        ro.observe(container);
200      })
201      .catch(function (err) {
202        console.warn('gioser-graph: error:', err);
203        container.innerHTML =
204          '<div style="padding:1rem;text-align:center;color:rgba(232,234,245,0.30);' +
205          'font-size:0.8rem;font-family:Inter,sans-serif;">' +
206          '· grafo no disponible ·</div>';
207      });
208  }
209
210  // MutationObserver
211  var observer = new MutationObserver(function (mutations) {
212    for (var m = 0; m < mutations.length; m++) {
213      var added = mutations[m].addedNodes;
214      for (var i = 0; i < added.length; i++) {
215        var el = added[i];
216        if (el.tagName && el.tagName.toLowerCase() === 'gioser-graph') { initGraph(el); }
217        var gs = el.querySelectorAll ? el.querySelectorAll('gioser-graph') : [];
218        for (var j = 0; j < gs.length; j++) { initGraph(gs[j]); }
219      }
220    }
221  });
222  observer.observe(document.documentElement, { childList: true, subtree: true });
223
224  var existing = document.querySelectorAll('gioser-graph');
225  for (var i = 0; i < existing.length; i++) { initGraph(existing[i]); }
226})();