| 1 | // Vista «Arquitectura» — grafo 3D de dependencias del proyecto, FIEL a CodeFlow |
| 2 | // (braedonsaunders/codeflow, MIT): usa la MISMA librería `3d-force-graph`, con |
| 3 | // nodos coloreados por capa (carpeta de primer nivel), tamaño por número de |
| 4 | // conexiones y partículas de flujo viajando por los enlaces (la firma de |
| 5 | // CodeFlow). Lee los ficheros reales, extrae los imports y resuelve las aristas. |
| 6 | // Clic en un nodo → abre el fichero en Monaco. |
| 7 | import * as code from './tools/code.js'; |
| 8 | |
| 9 | const CODE_EXT = /\.(js|mjs|cjs|jsx|ts|tsx|py|go|rs|java|c|h|cpp|hpp|vue|svelte)$/i; |
| 10 | const FG_URL = 'https://cdn.jsdelivr.net/npm/3d-force-graph@1/dist/3d-force-graph.min.js'; |
| 11 | // paleta por capa (carpeta de primer nivel), estilo CodeFlow |
| 12 | const LAYER_COLORS = ['#7c5cff', '#49e8ff', '#ff4d8d', '#3fb970', '#ffd479', '#ff9f45', '#a86cff', '#42b883', '#e34c26', '#00add8']; |
| 13 | |
| 14 | // Extrae destinos de import de un fichero (JS/TS/Py, tolerante). |
| 15 | function importsOf(path, src) { |
| 16 | const t = []; |
| 17 | const re = /(?:import\s+[^'"]*from\s+|import\s+|require\(\s*|export\s+[^'"]*from\s+)['"]([^'"]+)['"]/g; |
| 18 | let m; while ((m = re.exec(src))) t.push(m[1]); |
| 19 | const py = /^\s*(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))/gm; |
| 20 | while ((m = py.exec(src))) t.push((m[1] || m[2]).replace(/\./g, '/')); |
| 21 | return t; |
| 22 | } |
| 23 | |
| 24 | // Resuelve un import relativo a un fichero real del proyecto. |
| 25 | function resolve(from, spec, files) { |
| 26 | if (!/^[./]/.test(spec)) { |
| 27 | const hit = files.find(f => f.endsWith('/' + spec) || f.includes('/' + spec + '.') || f.includes('/' + spec + '/')); |
| 28 | return hit || null; |
| 29 | } |
| 30 | const base = from.split('/').slice(0, -1); |
| 31 | for (const part of spec.split('/')) { if (part === '..') base.pop(); else if (part !== '.') base.push(part); } |
| 32 | const cand = base.join('/'); |
| 33 | return files.find(f => f === cand) || |
| 34 | files.find(f => f.replace(CODE_EXT, '') === cand) || |
| 35 | files.find(f => f === cand + '/index.js' || f === cand + '/__init__.py') || null; |
| 36 | } |
| 37 | |
| 38 | // Monaco carga un loader AMD (define.amd); el UMD de 3d-force-graph se |
| 39 | // registraría por AMD y NO crearía window.ForceGraph3D. Anulamos `define` |
| 40 | // mientras carga el bundle para forzar la rama global (igual que con xterm). |
| 41 | const loadFG = () => window.ForceGraph3D ? Promise.resolve() : new Promise((res, rej) => { |
| 42 | const savedDefine = window.define; |
| 43 | window.define = undefined; |
| 44 | const restore = () => { window.define = savedDefine; }; |
| 45 | const s = document.createElement('script'); |
| 46 | s.src = FG_URL; |
| 47 | s.onload = () => { restore(); window.ForceGraph3D ? res() : rej(new Error('3d-force-graph cargó pero no expuso ForceGraph3D')); }; |
| 48 | s.onerror = () => { restore(); rej(new Error('no cargó 3d-force-graph')); }; |
| 49 | document.head.appendChild(s); |
| 50 | }); |
| 51 | |
| 52 | let graph = null; |
| 53 | |
| 54 | export async function renderArchitecture(container, onOpenFile) { |
| 55 | disposeArch(); |
| 56 | container.innerHTML = '<div class="view-loading">Analizando la arquitectura del proyecto…</div>'; |
| 57 | const files = (await code.fileList()).filter(f => CODE_EXT.test(f)).slice(0, 400); |
| 58 | if (!files.length) { container.innerHTML = '<div class="view-loading">Sin ficheros de código para analizar.</div>'; return; } |
| 59 | |
| 60 | const topOf = p => p.includes('/') ? p.split('/')[0] : '(raíz)'; |
| 61 | const layers = [...new Set(files.map(topOf))]; |
| 62 | const layerColor = new Map(layers.map((l, i) => [l, LAYER_COLORS[i % LAYER_COLORS.length]])); |
| 63 | const deg = new Map(files.map(f => [f, 0])); |
| 64 | const links = []; |
| 65 | const seen = new Set(); |
| 66 | for (const p of files) { |
| 67 | let src = ''; try { src = await code.read({ path: p }); } catch { continue; } |
| 68 | for (const spec of importsOf(p, src)) { |
| 69 | const target = resolve(p, spec, files); |
| 70 | if (target && target !== p) { |
| 71 | const key = p + '\u0000' + target; |
| 72 | if (seen.has(key)) continue; seen.add(key); |
| 73 | links.push({ source: p, target }); |
| 74 | deg.set(p, deg.get(p) + 1); deg.set(target, deg.get(target) + 1); |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | const nodes = files.map(p => ({ id: p, name: p.split('/').pop(), layer: topOf(p), val: 1 + deg.get(p) * 2, color: layerColor.get(topOf(p)) })); |
| 79 | |
| 80 | container.innerHTML = |
| 81 | '<div id="arch-graph"></div>' + |
| 82 | '<div class="view-head">Arquitectura · ' + nodes.length + ' ficheros, ' + links.length + ' dependencias' + |
| 83 | '<span class="view-hint">arrastra para orbitar · las partículas fluyen del importado al importador · clic en un nodo → abrir</span></div>'; |
| 84 | const el = container.querySelector('#arch-graph'); |
| 85 | |
| 86 | await loadFG(); |
| 87 | graph = window.ForceGraph3D({ controlType: 'orbit' })(el) |
| 88 | .backgroundColor('#0b0d12') |
| 89 | .width(el.clientWidth || 800).height(el.clientHeight || 600) |
| 90 | .graphData({ nodes, links }) |
| 91 | .nodeVal('val') |
| 92 | .nodeColor('color') |
| 93 | .nodeOpacity(0.92) |
| 94 | .nodeLabel(n => `${n.id} · ${deg.get(n.id)} conexiones`) |
| 95 | .nodeResolution(12) |
| 96 | .linkColor(() => 'rgba(140,150,180,0.28)') |
| 97 | .linkWidth(0.6) |
| 98 | .linkDirectionalParticles(2) |
| 99 | .linkDirectionalParticleSpeed(0.006) |
| 100 | .linkDirectionalParticleWidth(1.8) |
| 101 | .linkDirectionalParticleColor(() => '#49e8ff') |
| 102 | .onNodeClick(n => onOpenFile(n.id)) |
| 103 | .onBackgroundClick(() => {}) |
| 104 | .cooldownTicks(120) |
| 105 | .onEngineStop(() => graph && graph.zoomToFit(500, 40)); |
| 106 | // separación por capas: espaciar un poco las cargas de nodos |
| 107 | graph.d3Force('charge').strength(-120); |
| 108 | graph.nodeThreeObjectExtend?.(false); |
| 109 | const onResize = () => graph && graph.width(el.clientWidth).height(el.clientHeight); |
| 110 | window.addEventListener('resize', onResize); |
| 111 | graph.__onResize = onResize; |
| 112 | // para pruebas: nº de nodos accesible en el DOM |
| 113 | el.dataset.nodes = String(nodes.length); |
| 114 | el.dataset.links = String(links.length); |
| 115 | // Lo mismo que el lienzo, como lista (la monta main.js al lado): con teclado |
| 116 | // o lector de pantalla un grafo 3D no se puede recorrer. `locate` lleva la |
| 117 | // cámara hasta un fichero, como cuando se busca en el grafo de CodeFlow. |
| 118 | return { |
| 119 | items: nodes.map(n => ({ path: n.id, conexiones: deg.get(n.id) })), |
| 120 | locate(path) { |
| 121 | const n = nodes.find(x => x.id === path); |
| 122 | if (!graph || !n || n.x == null) return false; |
| 123 | const lejos = 70, r = 1 + lejos / (Math.hypot(n.x, n.y, n.z) || 1); |
| 124 | graph.cameraPosition({ x: n.x * r, y: n.y * r, z: n.z * r }, n, 800); |
| 125 | return true; |
| 126 | }, |
| 127 | }; |
| 128 | } |
| 129 | |
| 130 | export function disposeArch() { |
| 131 | if (!graph) return; |
| 132 | try { if (graph.__onResize) window.removeEventListener('resize', graph.__onResize); graph._destructor?.(); } catch { /* mejor esfuerzo */ } |
| 133 | graph = null; |
| 134 | } |