kikocis/VibeCodeViewer public
Changesets · Branches · Tags · Compare
| Changeset | 26f65a4fb4c58fabb6e727312261fcfbd8b4620017b332e61053540975c414fc |
|---|---|
| Author | Sendery <sendery@gmail.com> · 2026-06-17 01:38 +02:00 |
| Committer | Sendery <sendery@gmail.com> · 2026-06-17 01:38 +02:00 |
| Parents | None: the first changeset |
38 files changed
added .gitignore +4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +.cache/ | |
| 2 | +__pycache__/ | |
| 3 | +node_modules/ | |
| 4 | +*.log |
added README.md +280 −0
| @@ -0,0 +1,280 @@ | ||
| 1 | +# VibeCodeViewer — Metrópolis de Cristal | |
| 2 | + | |
| 3 | +Ciudad procedural de **edificios de cristal** (Three.js) que visualiza un | |
| 4 | +repositorio de código como una metrópolis estilo *hacker noventero*: wireframes | |
| 5 | +cian nítidos, suelo de placa de circuito impreso y bloom selectivo solo en lo | |
| 6 | +que se resalta — nada de neblina permanente. | |
| 7 | + | |
| 8 | +## Mapeo repo → ciudad | |
| 9 | + | |
| 10 | +| Repositorio | Ciudad | | |
| 11 | +| ----------------------------- | ------------------------------------------ | | |
| 12 | +| raíz | ciudad | | |
| 13 | +| carpetas de nivel 1 | distritos (plotas moradas en el suelo) | | |
| 14 | +| carpetas de nivel 2 | edificios | | |
| 15 | +| subárboles muy profundos/poblados | **urbanizaciones**: plotas dentro del distrito que agrupan sus subcarpetas como edificios (recursivo) | | |
| 16 | +| anidamiento interior | plantas → apartamentos → habitaciones → archivadores → cajones | | |
| 17 | +| archivos | celdas luminosas (en cualquier nivel) | | |
| 18 | + | |
| 19 | +- **Ancho/profundidad** del edificio ∝ tamaño en bytes de la carpeta (escala log). | |
| 20 | +- **Altura** ∝ número de ficheros contenidos (recursivo). | |
| 21 | +- Sobre la fachada de cristal se imprime el **árbol de ficheros** del edificio; | |
| 22 | + al seleccionar un fichero se resalta su ruta en la propia fachada. | |
| 23 | +- Dentro de un **cajón**, los ficheros se dibujan como carpetas colgantes | |
| 24 | + (láminas verticales); en el resto de niveles, como una rejilla de cubos. | |
| 25 | + | |
| 26 | +## Iluminación jerárquica de densidad | |
| 27 | + | |
| 28 | +Seleccionar un fichero (clic o buscador) enciende su celda al máximo y la luz | |
| 29 | +decae nivel a nivel hacia fuera (×0.56 por salto): | |
| 30 | + | |
| 31 | +``` | |
| 32 | +fichero ▓▓▓▓▓▓ → cajón ▓▓▓▓ → archivador ▓▓▓ → habitación ▓▓ → planta ▓ → edificio ░ → distrito · | |
| 33 | +``` | |
| 34 | + | |
| 35 | +Los niveles interiores encendidos reciben además un relleno volumétrico tenue; | |
| 36 | +el edificio y el distrito solo iluminan aristas y fresnel para no velar el | |
| 37 | +interior (la clave para que no se vea «difuminado»). | |
| 38 | + | |
| 39 | +## Receta anti-difuminado | |
| 40 | + | |
| 41 | +1. Aristas finas con **colores HDR** en un único `LineSegments` (rangos de | |
| 42 | + color por nodo): el bloom (umbral 0.85) solo se dispara en lo resaltado. | |
| 43 | +2. Cristal **fresnel** de opacidad mínima (α ≈ 0.02 en el centro de la cara). | |
| 44 | +3. Cero volúmenes aditivos permanentes: los rellenos solo existen mientras un | |
| 45 | + nivel está encendido (pool de 10 cajas reutilizables). | |
| 46 | + | |
| 47 | +## Extras | |
| 48 | + | |
| 49 | +- **Abrir Carpeta…** (Chrome/Edge): escanea cualquier carpeta local con la | |
| 50 | + File System Access API y reconstruye la ciudad al vuelo, sin regenerar | |
| 51 | + `src/data.js`. | |
| 52 | +- **Sótanos**: los ficheros que caen bajo `.gitignore` / `.dockerignore` / | |
| 53 | + `.npmignore` se mapean bajo el plano de circuitos, con el mismo patrón de | |
| 54 | + segmentación pero creciendo hacia abajo (el suelo es semitransparente y en | |
| 55 | + modo vuelo puedes bajar a recorrerlos). En el árbol lateral aparecen en | |
| 56 | + ámbar como `carpeta · sótano`. Si una carpeta no tiene **nada** en | |
| 57 | + superficie (todo su contenido está ignorado), en vez de torre se dibuja un | |
| 58 | + **búnker**: una losa baja y más opaca que señala que la información está | |
| 59 | + bajo el suelo. | |
| 60 | +- **Leyenda** (botón o tecla `L`): nombres de los barrios serigrafiados en el | |
| 61 | + suelo como pistas de circuito y nombre de la carpeta en el tejado de cada | |
| 62 | + edificio. | |
| 63 | +- **Pulse de barrio**: el distrito de la selección queda algo más iluminado y | |
| 64 | + late suavemente. | |
| 65 | +- **Sugerencias de búsqueda**: mientras escribes, todos los ficheros que | |
| 66 | + casan parpadean en la ciudad y se resaltan en las fachadas de sus edificios. | |
| 67 | + | |
| 68 | +## Modos de coloreado | |
| 69 | + | |
| 70 | +Selector arriba al centro (Básico · Git · Owners). El color del fichero se | |
| 71 | +propaga atenuado a toda su jerarquía: cajón, habitación, planta, edificio y | |
| 72 | +barrio se tiñen según lo que contienen. | |
| 73 | + | |
| 74 | +- **Básico**: la paleta cian original. | |
| 75 | +- **Git**: cada fichero según su estado (`scan.mjs` recoge `git status` y | |
| 76 | + `git diff --numstat`): ámbar = modificado, verde = nuevo/sin seguimiento, | |
| 77 | + azul = renombrado. El árbol lateral muestra además un icono de estado y las | |
| 78 | + líneas añadidas/borradas (`+a −d`). Deshabilitado si el snapshot no | |
| 79 | + proviene de un repo git (p. ej. al usar **Abrir Carpeta…**). | |
| 80 | +- **Owners**: parsea `CODEOWNERS` (en cualquier nivel) y los `package.yml` | |
| 81 | + con `metadata.owner` (convención descrita en `code_ownership_files.md`). | |
| 82 | + Cada owner recibe un color (hues en ángulo áureo) y aparece en una leyenda | |
| 83 | + sobre el panel de navegación con su recuento de ficheros. La semántica es | |
| 84 | + la de CODEOWNERS: la última regla que casa gana. Deshabilitado si no se | |
| 85 | + encuentra ninguna regla. | |
| 86 | +- **Blast**: análisis estático en dos capas para estimar el **impacto de un | |
| 87 | + cambio**. (1) Imports por ruta (`src/codeLinks.js`): `import`/`export | |
| 88 | + from`/`require`/`import()` en JS/TS, `#include` en C/C++, `import`/`from` | |
| 89 | + en Python, `@import`/`url()` en CSS, `src`/`href` en HTML, `source` en | |
| 90 | + shell. (2) **Índice de símbolos** (`src/codeIndex.js`) para JS/TS(X), | |
| 91 | + Python, Ruby, C/C++ y Bash: extrae definiciones (funciones, clases, | |
| 92 | + interfaces, types, enums, módulos, constantes, `attr_accessor`/`scope`, | |
| 93 | + `#define`/`typedef`/`using`, funciones bash…) y las cruza con los | |
| 94 | + identificadores usados en los demás ficheros — con filtros anti-ruido: | |
| 95 | + en JS/TS solo cuenta lo exportado, en Python solo el nivel de módulo, | |
| 96 | + stopwords, y los símbolos definidos en >3 ficheros se descartan por | |
| 97 | + ambiguos (máx. 40 aristas/fichero, las menos ambiguas primero). | |
| 98 | + | |
| 99 | + Al seleccionar un fichero: **los que dependen de él** (su impacto: | |
| 100 | + lo importan o usan sus símbolos) se encienden en el color `beamIn` del | |
| 101 | + tema, y **sus dependencias** en `beam`, con haces cuyo pulso viaja en el | |
| 102 | + sentido de la propagación (hacia fuera en impactos, hacia dentro en | |
| 103 | + dependencias). La leyenda muestra ambos recuentos. | |
| 104 | + | |
| 105 | + El análisis por fichero se **cachea** (clave `versión|ruta|tamaño|mtime`): | |
| 106 | + en node en `.cache/analysis.json` y en el navegador en IndexedDB, de modo | |
| 107 | + que re-escanear solo reanaliza lo que cambió. Las definiciones quedan | |
| 108 | + guardadas en `REPO_META.codeIndex.defs` para futuros análisis. Las specs | |
| 109 | + se resuelven contra el árbol real (rutas relativas, `/index.*`, sufijos de | |
| 110 | + paquete tipo `three/addons/...` y nombres sueltos si son únicos). | |
| 111 | + | |
| 112 | +Con **Abrir Carpeta…** el estado git se estima parseando `.git/index` | |
| 113 | +(v2/v3) directamente en el navegador: mismo tamaño y mtime → limpio; difiere | |
| 114 | +→ modificado; ausente del índice → sin seguimiento (sin stats `+/−`, que | |
| 115 | +requieren `git diff`). El análisis Blast y el ownership también se calculan | |
| 116 | +en el navegador, así que los cuatro modos funcionan sobre carpetas locales. | |
| 117 | + | |
| 118 | +## Temas de color | |
| 119 | + | |
| 120 | +Selector «Tema · …» en la columna de botones. Toda la paleta (escena, suelo | |
| 121 | +de circuitos, fachadas, leyendas y variables CSS de la interfaz) vive en | |
| 122 | +`src/themes.js`; cambiar de tema reconstruye solo la ciudad, conservando | |
| 123 | +modelo, cámara y selección. | |
| 124 | + | |
| 125 | +- **Hacker** — el cian/morado original sobre negro. | |
| 126 | +- **Factorial** — corporativo en oscuro con rojo dominante `#E51943` | |
| 127 | + (edificios, celdas, selección) y verde `#007C85` estructural (distritos, | |
| 128 | + serigrafías). Los paneles de la interfaz van en claro (`uiLight`). | |
| 129 | +- **Synthwave** — magenta y naranja atardecer sobre púrpura profundo. | |
| 130 | +- **Matrix** — fósforo verde monocromo sobre negro. | |
| 131 | +- **Glaciar** — azules de hielo y blancos fríos sobre azul marino. | |
| 132 | + | |
| 133 | +Más botones de vista: **Suelo Opaco** (tecla `G`) — translúcido deja intuir | |
| 134 | +los sótanos; opaco escribe profundidad y los **oculta de verdad** (desde | |
| 135 | +debajo, en modo vuelo, se siguen viendo). | |
| 136 | + | |
| 137 | +## Teclado en el árbol | |
| 138 | + | |
| 139 | +Con el árbol enfocado (clic sobre él): `↑`/`↓` mueven el cursor, `→` | |
| 140 | +despliega una carpeta (o entra en ella), `←` la pliega (o salta al padre), | |
| 141 | +`AvPág`/`RePág` saltan una página y `Enter`/`Espacio` seleccionan el | |
| 142 | +elemento (con vuelo de cámara). | |
| 143 | + | |
| 144 | +## Monorepos grandes | |
| 145 | + | |
| 146 | +Probado con un monorepo real de ~120k ficheros y 42 distritos de primer | |
| 147 | +nivel (vía `tools/tree2data.mjs`, que convierte una salida de `tree` en | |
| 148 | +snapshot para pruebas): | |
| 149 | + | |
| 150 | +- **Urbanizaciones**: un edificio absorbe 5 niveles de anidamiento | |
| 151 | + (planta→…→cajón); cuando una carpeta es más profunda (y tiene >200 | |
| 152 | + ficheros) o simplemente enorme (>2000 ficheros), se convierte en una | |
| 153 | + plota dentro del distrito y sus subcarpetas pasan a ser edificios — de | |
| 154 | + forma recursiva, así la profundidad sobrante se despliega por la ciudad | |
| 155 | + en vez de comprimirse dentro de una torre. Tienen su propio serigrafiado | |
| 156 | + de suelo en la leyenda y se seleccionan desde el árbol como cualquier | |
| 157 | + nivel. | |
| 158 | +- En ciudades con miles de edificios se aplica además una atenuación | |
| 159 | + global suave y **uniforme** a aristas, cristal y celdas (todos los | |
| 160 | + edificios conservan el mismo aspecto entre sí); los perímetros de | |
| 161 | + distritos y urbanizaciones quedan siempre a brillo pleno. | |
| 162 | +- El escaneo del árbol es **completo y sin límite de ficheros**. El análisis | |
| 163 | + Blast lee contenidos solo hasta un presupuesto (20k ficheros / 48 MB), | |
| 164 | + gastado por prioridad (ficheros clave primero, ver `src/filePriority.js`), | |
| 165 | + en lotes con checkpoints reanudables y con la ciudad ya cargada. | |
| 166 | +- **LOD por presupuesto**: solo dibujan aristas las ~12k cajas más | |
| 167 | + relevantes (distritos y edificios siempre); el brillo de aristas y celdas | |
| 168 | + se normaliza **por edificio** (presupuesto de luz constante), de modo que | |
| 169 | + un rascacielos con 50k ficheros no se quema en blanco y un chalet con 20 | |
| 170 | + se ve igual que antes. | |
| 171 | +- Las fachadas con texto se limitan a los 250 edificios mayores, las | |
| 172 | + etiquetas de tejado a 400, y los forjados a 4000 plantas. | |
| 173 | +- El **árbol lateral es perezoso**: las ramas se montan en el DOM al | |
| 174 | + expandirlas (con 150k filas el navegador no sobrevive). La selección | |
| 175 | + sincronizada las expande automáticamente. | |
| 176 | +- `node_modules` y `.git/objects` se omiten siempre. | |
| 177 | + | |
| 178 | +Con **Abrir Carpeta…** sobre un monorepo así, el escaneo tarda un rato | |
| 179 | +(lee el tamaño de cada fichero); el botón muestra el progreso. | |
| 180 | + | |
| 181 | +## Ejecutar | |
| 182 | + | |
| 183 | +Necesita un servidor estático (módulos ES + importmap no funcionan en `file://`): | |
| 184 | + | |
| 185 | +```bash | |
| 186 | +./serve.sh # sirve en todas las interfaces de red y lista las URLs | |
| 187 | +./serve.sh 9000 # puerto alternativo | |
| 188 | +# o a mano: python3 -m http.server 8137 --bind 0.0.0.0 | |
| 189 | +``` | |
| 190 | + | |
| 191 | +Nota: la File System Access API (**Abrir Carpeta…**) requiere contexto | |
| 192 | +seguro; desde otra máquina de la red usa HTTPS o un túnel — en | |
| 193 | +`http://localhost` siempre funciona. | |
| 194 | + | |
| 195 | +Sin build: Three.js r160 vendorizado en `vendor/` (funciona offline). | |
| 196 | + | |
| 197 | +Para regenerar el snapshot del repo (`src/data.js`): | |
| 198 | + | |
| 199 | +```bash | |
| 200 | +node scan.mjs # escanea la carpeta padre | |
| 201 | +node scan.mjs /otra/ruta # o cualquier otro árbol | |
| 202 | +``` | |
| 203 | + | |
| 204 | +## Modo test: `./serve.sh --test N M [K]` | |
| 205 | + | |
| 206 | +Genera un `src/data.js` sintético y determinista (`tools/gentest.mjs`) para | |
| 207 | +depurar el renderizado con geometría controlada — glitches en interiores | |
| 208 | +profundos, urbanizaciones y serigrafiado de nombres en fachadas/techos. | |
| 209 | + | |
| 210 | +**Sin K**: N cadenas independientes; cada fichero queda al fondo de M | |
| 211 | +carpetas anidadas (`folder_i/folder_i_1/…/file_i`). Cada cadena es un | |
| 212 | +distrito con un único edificio cuyo interior se subdivide M niveles. | |
| 213 | + | |
| 214 | +**Con K (modo urbanización)**: los N ficheros se agrupan; cada distrito | |
| 215 | +`folder_g` contiene un bloque `urb_g` que crea **K carpetas en el nivel de | |
| 216 | +urbanización** (`folder_g_1…folder_g_K`), y cada una continúa su cadena | |
| 217 | +hasta profundidad M total. (El bloque intermedio es necesario: las carpetas | |
| 218 | +de primer nivel son siempre distritos, y la urbanización solo se interpone | |
| 219 | +en los bloques *dentro* de un distrito.) | |
| 220 | + | |
| 221 | +### Cómo decide el modelo cuándo hay urbanización | |
| 222 | + | |
| 223 | +Un edificio absorbe como máximo **5 niveles** de anidamiento interior | |
| 224 | +(planta → apartamento → habitación → archivador → cajón; `URB_DEPTH` en | |
| 225 | +`src/model.js`). Cuando una carpeta excede lo que cabe en una torre, se | |
| 226 | +interpone una **urbanización**: una plota dentro del distrito cuyas | |
| 227 | +subcarpetas pasan a ser edificios (recursivo). Los umbrales (`needsUrb`): | |
| 228 | + | |
| 229 | +- más de **2000 ficheros** en el subárbol (`URB_MAX_FILES`), a cualquier | |
| 230 | + profundidad, o | |
| 231 | +- más de **200 ficheros** (`URB_MIN_FILES`) **y** subárbol de profundidad | |
| 232 | + mayor que 5 — con el generador, M ≥ 8 (el subárbol bajo `urb_g` tiene | |
| 233 | + profundidad M−2). | |
| 234 | + | |
| 235 | +### Ejemplos por profundidad y distribución (verificados contra `buildModel`) | |
| 236 | + | |
| 237 | +```bash | |
| 238 | +./serve.sh --test 2 3 # mínimo: 2 cadenas de 3 carpetas (el ejemplo del header) | |
| 239 | +./serve.sh --test 500 8 # 500 torres de interior profundo (sin urbanizaciones) | |
| 240 | +./serve.sh --test 1000 8 250 # 4 grupos × 250 carpetas, M−2=6 > 5 → 4 urbanizaciones | |
| 241 | +./serve.sh --test 1000 4 250 # mismos grupos pero poco profundos (4−2 ≤ 5) → 4 torres densas | |
| 242 | +./serve.sh --test 2500 3 2500 # 1 grupo de 2500 (> 2000) → urbanización aunque sea plano | |
| 243 | +./serve.sh --test 9000 9 300 # 30 urbanizaciones profundas: estrés de LOD + serigrafiado | |
| 244 | +./serve.sh 8200 --test 100 10 # puerto alternativo + test | |
| 245 | +``` | |
| 246 | + | |
| 247 | +El generador avisa al ejecutarse de si la combinación N/M/K elegida supera | |
| 248 | +o no los umbrales de urbanización. | |
| 249 | + | |
| 250 | +Restaurar el snapshot real: `git checkout -- src/data.js` o relanzar | |
| 251 | +`scan.mjs`. `./serve.sh --help` muestra este resumen. | |
| 252 | + | |
| 253 | +## Controles | |
| 254 | + | |
| 255 | +| Entrada | Acción | | |
| 256 | +| ------------------ | --------------------------------------------- | | |
| 257 | +| arrastrar / rueda | orbitar · zoom | | |
| 258 | +| clic | seleccionar fichero o edificio · vacío = limpiar | | |
| 259 | +| hover | resalta el edificio bajo el cursor | | |
| 260 | +| `F` | **modo vuelo** (pointer-lock, atraviesa paredes) | | |
| 261 | +| `W A S D` / ratón | mover · mirar (en vuelo) | | |
| 262 | +| `Space`/`E` · `C`/`Q` | subir · bajar · `Shift` turbo | | |
| 263 | +| `1` `2` `3` | Reset Vista · Vista Aérea · Vista Altura Edificios | | |
| 264 | +| `X` · `/` | limpiar selección · enfocar el buscador | | |
| 265 | +| `Esc` | salir del vuelo / cerrar buscador | | |
| 266 | + | |
| 267 | +## Estructura | |
| 268 | + | |
| 269 | +``` | |
| 270 | +index.html marco HTML + importmap | |
| 271 | +scan.mjs escáner del repo → src/data.js | |
| 272 | +src/ | |
| 273 | + data.js snapshot del árbol (generado) | |
| 274 | + model.js jerarquía + layout (cajas anidadas, empaquetado urbano) | |
| 275 | + builder.js escena: aristas HDR, cristal fresnel, fachadas, suelo PCB | |
| 276 | + controls.js órbita + vuelo libre + vuelos de cámara | |
| 277 | + ui.js árbol lateral, buscador, ruta, stats | |
| 278 | + main.js selección jerárquica, raycast, bucle de render | |
| 279 | +vendor/ Three.js r160 + addons (offline) | |
| 280 | +``` |
added code_ownership_files.md +50 −0
| @@ -0,0 +1,50 @@ | ||
| 1 | +# Code Ownership — Referencia | |
| 2 | + | |
| 3 | +VibeCodeViewer puede visualizar el ownership de un repositorio (modo **Owners**) | |
| 4 | +parseando dos fuentes: | |
| 5 | + | |
| 6 | +## 1. CODEOWNERS | |
| 7 | + | |
| 8 | +Fichero estándar de GitHub/GitLab. Cada línea asocia un patrón de ruta a uno | |
| 9 | +o más propietarios: | |
| 10 | + | |
| 11 | +``` | |
| 12 | +/src/ @org/frontend-team | |
| 13 | +/backend/ @org/backend-team | |
| 14 | +*.md @org/docs | |
| 15 | +``` | |
| 16 | + | |
| 17 | +La última regla que casa gana (semántica GitHub). VibeCodeViewer lo parsea en | |
| 18 | +`src/ownership.js`. | |
| 19 | + | |
| 20 | +## 2. package.yml con metadata.owner | |
| 21 | + | |
| 22 | +Convención habitual en monorepos: cada componente declara su propietario en un | |
| 23 | +`package.yml`: | |
| 24 | + | |
| 25 | +```yaml | |
| 26 | +metadata: | |
| 27 | + domain: YourDomain | |
| 28 | + owner: '@org/your_team' | |
| 29 | + reviewers: [] | |
| 30 | +``` | |
| 31 | + | |
| 32 | +VibeCodeViewer escanea todos los `package.yml` del árbol y extrae | |
| 33 | +`metadata.owner` como owner de la carpeta que lo contiene. | |
| 34 | + | |
| 35 | +## Consultar ownership | |
| 36 | + | |
| 37 | +```bash | |
| 38 | +# Propietario de un fichero según CODEOWNERS | |
| 39 | +git check-attr CODEOWNERS ruta/a/tu/archivo.rb | |
| 40 | + | |
| 41 | +# Listar ficheros de un equipo | |
| 42 | +grep "@org/team-name" CODEOWNERS | awk '{print $1}' | |
| 43 | +``` | |
| 44 | + | |
| 45 | +## Visualización | |
| 46 | + | |
| 47 | +En el modo **Owners**, cada owner recibe un color (hues en ángulo áureo) y | |
| 48 | +aparece en una leyenda sobre el panel de navegación con su recuento de ficheros. | |
| 49 | +El color se propaga atenuado a toda la jerarquía: cajón, habitación, planta, | |
| 50 | +edificio y barrio se tiñen según lo que contienen. |
added index.html +76 −0
| @@ -0,0 +1,76 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html lang="es"> | |
| 3 | +<head> | |
| 4 | + <meta charset="UTF-8"> | |
| 5 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| 6 | + <title>VibeCodeViewer — Metrópolis de Cristal</title> | |
| 7 | + <link rel="stylesheet" href="src/styles.css"> | |
| 8 | + <script type="importmap"> | |
| 9 | + { | |
| 10 | + "imports": { | |
| 11 | + "three": "./vendor/three.module.js", | |
| 12 | + "three/addons/": "./vendor/addons/" | |
| 13 | + } | |
| 14 | + } | |
| 15 | + </script> | |
| 16 | +</head> | |
| 17 | +<body> | |
| 18 | + <canvas id="view"></canvas> | |
| 19 | + | |
| 20 | + <div id="stats"></div> | |
| 21 | + | |
| 22 | + <div id="mode-switch"> | |
| 23 | + <button data-mode="basic" class="active">Básico</button> | |
| 24 | + <button data-mode="git">Git</button> | |
| 25 | + <button data-mode="ownership">Owners</button> | |
| 26 | + <button data-mode="blast">Blast</button> | |
| 27 | + </div> | |
| 28 | + | |
| 29 | + | |
| 30 | + <div id="view-buttons"> | |
| 31 | + <button id="btn-aerial">Vista Aérea</button> | |
| 32 | + <button id="btn-skyline">Vista Altura Edificios</button> | |
| 33 | + <button id="btn-reset">Reset Vista</button> | |
| 34 | + <button id="btn-legend">Leyenda</button> | |
| 35 | + <button id="btn-ground">Suelo Opaco</button> | |
| 36 | + <select id="theme-select" title="Tema de color"></select> | |
| 37 | + <button id="btn-reopen" style="display:none"></button> | |
| 38 | + <button id="btn-folder">Abrir Carpeta…</button> | |
| 39 | + </div> | |
| 40 | + | |
| 41 | + <div id="search-panel"> | |
| 42 | + <div class="title">Búsqueda</div> | |
| 43 | + <input id="search-input" type="text" placeholder="Buscar fichero… (p. ej. *.js, src/*.css)" autocomplete="off" spellcheck="false"> | |
| 44 | + <div id="search-results"></div> | |
| 45 | + </div> | |
| 46 | + | |
| 47 | + <div id="tree-panel"> | |
| 48 | + <div class="title">Árbol de ficheros</div> | |
| 49 | + <div id="tree"></div> | |
| 50 | + </div> | |
| 51 | + | |
| 52 | + <div id="pathbar"></div> | |
| 53 | + | |
| 54 | + <div id="right-stack"> | |
| 55 | + <div id="color-legend"></div> | |
| 56 | + <div id="help"> | |
| 57 | + <div class="title">Navegación</div> | |
| 58 | + <table> | |
| 59 | + <tr><td>Arrastrar</td><td>orbitar · rueda zoom</td></tr> | |
| 60 | + <tr><td>Clic</td><td>seleccionar fichero / edificio</td></tr> | |
| 61 | + <tr><td><b>F</b></td><td>modo vuelo (atraviesa paredes)</td></tr> | |
| 62 | + <tr><td>W A S D</td><td>mover · ratón mirar</td></tr> | |
| 63 | + <tr><td>Space / C</td><td>subir / bajar · <b>Shift</b> turbo</td></tr> | |
| 64 | + <tr><td>1 · 2 · 3</td><td>reset · aérea · altura</td></tr> | |
| 65 | + <tr><td><b>X</b></td><td>limpiar selección · <b>/</b> buscar</td></tr> | |
| 66 | + <tr><td><b>L</b> · <b>G</b></td><td>leyenda · suelo opaco</td></tr> | |
| 67 | + <tr><td>↑↓ ←→</td><td>navegar árbol · plegar/desplegar</td></tr> | |
| 68 | + </table> | |
| 69 | + </div> | |
| 70 | + </div> | |
| 71 | + | |
| 72 | + <div id="crosshair">+</div> | |
| 73 | + | |
| 74 | + <script type="module" src="src/main.js"></script> | |
| 75 | +</body> | |
| 76 | +</html> |
added scan.mjs +190 −0
| @@ -0,0 +1,190 @@ | ||
| 1 | +#!/usr/bin/env node | |
| 2 | +// Escanea un directorio y genera src/data.js con: | |
| 3 | +// - REPO_TREE: árbol de ficheros (ignorados marcados → sótano) | |
| 4 | +// - REPO_META: estado git por fichero y reglas de code ownership | |
| 5 | +// Uso: node scan.mjs [rutaRaiz] (por defecto: el directorio padre) | |
| 6 | +import { readdirSync, statSync, readFileSync, writeFileSync } from 'node:fs'; | |
| 7 | +import { execSync } from 'node:child_process'; | |
| 8 | +import { join, basename, dirname, resolve, relative, sep } from 'node:path'; | |
| 9 | +import { fileURLToPath } from 'node:url'; | |
| 10 | +import { IgnoreStack, IGNORE_FILES } from './src/ignore.js'; | |
| 11 | +import { isCodeownersFile, isPackageMeta, parseCodeowners, parsePackageMeta } from './src/ownership.js'; | |
| 12 | +import { isAnalyzable, extractRefs, resolveAll } from './src/codeLinks.js'; | |
| 13 | +import { stripCommentsAndStrings, extractDefs, extractTokens, buildSymbolLinks, isIndexable, INDEX_VERSION } from './src/codeIndex.js'; | |
| 14 | +import { mkdirSync, existsSync } from 'node:fs'; | |
| 15 | + | |
| 16 | +const HERE = dirname(fileURLToPath(import.meta.url)); | |
| 17 | +const ROOT = resolve(process.argv[2] ?? join(HERE, '..')); | |
| 18 | +const SKIP = new Set(['node_modules', '.DS_Store']); | |
| 19 | + | |
| 20 | +let total = 0, ignoredCount = 0; | |
| 21 | +const ownerRules = []; | |
| 22 | +const refsMap = {}, fileRels = [], dirRels = []; | |
| 23 | +const defsMap = {}, tokensMap = {}; | |
| 24 | + | |
| 25 | +// caché del análisis por fichero: clave rel|size|mtime | |
| 26 | +const CACHE_PATH = join(HERE, '.cache', 'analysis.json'); | |
| 27 | +let analysisCache = {}; | |
| 28 | +try { analysisCache = JSON.parse(readFileSync(CACHE_PATH, 'utf8')); } catch { /* primera vez */ } | |
| 29 | +const newCache = {}; | |
| 30 | +let cacheHits = 0, analyzedNew = 0; | |
| 31 | +const FLUSH_EVERY = 2000; | |
| 32 | + | |
| 33 | +function flushCache(obj) { | |
| 34 | + try { | |
| 35 | + if (!existsSync(join(HERE, '.cache'))) mkdirSync(join(HERE, '.cache')); | |
| 36 | + writeFileSync(CACHE_PATH, JSON.stringify(obj)); | |
| 37 | + } catch { /* la caché es opcional */ } | |
| 38 | +} | |
| 39 | + | |
| 40 | +function analyzeFile(full, rel, name, size, mtimeMs) { | |
| 41 | + const wantRefs = isAnalyzable(name, size); | |
| 42 | + const wantIndex = isIndexable(name, size); | |
| 43 | + if (!wantRefs && !wantIndex) return; | |
| 44 | + const key = `v${INDEX_VERSION}|${rel}|${size}|${Math.round(mtimeMs)}`; | |
| 45 | + const hit = analysisCache[key]; | |
| 46 | + if (hit) { | |
| 47 | + cacheHits++; | |
| 48 | + newCache[key] = hit; | |
| 49 | + if (hit.specs?.length) refsMap[rel] = hit.specs; | |
| 50 | + if (hit.defs?.length) defsMap[rel] = hit.defs; | |
| 51 | + if (hit.tokens?.length) tokensMap[rel] = hit.tokens; | |
| 52 | + return; | |
| 53 | + } | |
| 54 | + let text; | |
| 55 | + try { text = readFileSync(full, 'utf8'); } catch { return; } | |
| 56 | + const entry = {}; | |
| 57 | + if (wantRefs) { | |
| 58 | + const specs = extractRefs(name, text); | |
| 59 | + if (specs.length) { refsMap[rel] = specs; entry.specs = specs; } | |
| 60 | + } | |
| 61 | + if (wantIndex) { | |
| 62 | + const clean = stripCommentsAndStrings(text, name); | |
| 63 | + const defs = extractDefs(name, clean); | |
| 64 | + const tokens = [...extractTokens(clean)]; | |
| 65 | + if (defs.length) { defsMap[rel] = defs; entry.defs = defs; } | |
| 66 | + if (tokens.length) { tokensMap[rel] = tokens; entry.tokens = tokens; } | |
| 67 | + } | |
| 68 | + newCache[key] = entry; | |
| 69 | + // persistencia incremental: si el proceso muere a medias (memoria, corte), | |
| 70 | + // lo ya analizado queda guardado y la próxima ejecución continúa desde ahí. | |
| 71 | + // Se vuelca el merge para no perder entradas aún no visitadas en esta pasada. | |
| 72 | + if (++analyzedNew % FLUSH_EVERY === 0) flushCache({ ...analysisCache, ...newCache }); | |
| 73 | +} | |
| 74 | + | |
| 75 | +function scanDir(path, rel, forced, stack) { | |
| 76 | + const name = basename(path); | |
| 77 | + let entries = []; | |
| 78 | + try { entries = readdirSync(path, { withFileTypes: true }); } catch { return [name, [], []]; } | |
| 79 | + entries.sort((a, b) => a.name.localeCompare(b.name)); | |
| 80 | + | |
| 81 | + let pushed = 0; | |
| 82 | + for (const e of entries) { | |
| 83 | + if (!e.isFile()) continue; | |
| 84 | + if (IGNORE_FILES.includes(e.name)) { | |
| 85 | + try { | |
| 86 | + stack.push(rel, readFileSync(join(path, e.name), 'utf8').split('\n')); | |
| 87 | + pushed++; | |
| 88 | + } catch { /* ignorar */ } | |
| 89 | + } | |
| 90 | + if (!rel.includes('.git') && (isCodeownersFile(e.name) || isPackageMeta(e.name))) { | |
| 91 | + try { | |
| 92 | + const txt = readFileSync(join(path, e.name), 'utf8'); | |
| 93 | + if (isCodeownersFile(e.name)) ownerRules.push(...parseCodeowners(txt)); | |
| 94 | + else { | |
| 95 | + const rule = parsePackageMeta(txt, rel); | |
| 96 | + if (rule) ownerRules.push(rule); | |
| 97 | + } | |
| 98 | + } catch { /* ignorar */ } | |
| 99 | + } | |
| 100 | + } | |
| 101 | + | |
| 102 | + const dirs = [], files = []; | |
| 103 | + for (const e of entries) { | |
| 104 | + if (SKIP.has(e.name)) continue; | |
| 105 | + const full = join(path, e.name); | |
| 106 | + const childRel = rel ? `${rel}/${e.name}` : e.name; | |
| 107 | + if (e.isDirectory()) { | |
| 108 | + if (childRel === '.git/objects') continue; // ruido binario sin interés | |
| 109 | + const ign = forced || stack.ignored(childRel, true); | |
| 110 | + dirRels.push(childRel); | |
| 111 | + dirs.push(scanDir(full, childRel, ign, stack)); | |
| 112 | + } else if (e.isFile()) { | |
| 113 | + let size = 0, mtimeMs = 0; | |
| 114 | + try { const st = statSync(full); size = st.size; mtimeMs = st.mtimeMs; } catch { /* ignorar */ } | |
| 115 | + const ign = forced || stack.ignored(childRel, false); | |
| 116 | + files.push(ign ? [e.name, size, 1] : [e.name, size]); | |
| 117 | + fileRels.push(childRel); | |
| 118 | + total++; | |
| 119 | + if (ign) ignoredCount++; | |
| 120 | + // relaciones de código + índice de símbolos para el modo Blast | |
| 121 | + if (!childRel.startsWith('.git/')) analyzeFile(full, childRel, e.name, size, mtimeMs); | |
| 122 | + } | |
| 123 | + } | |
| 124 | + while (pushed--) stack.pop(); | |
| 125 | + return [name, dirs, files]; | |
| 126 | +} | |
| 127 | + | |
| 128 | +// ── estado git: status por fichero + líneas añadidas/borradas ───────────── | |
| 129 | +function gitMeta() { | |
| 130 | + const run = (cmd) => execSync(cmd, { cwd: ROOT, maxBuffer: 64 * 1024 * 1024 }).toString(); | |
| 131 | + let top; | |
| 132 | + try { top = run('git rev-parse --show-toplevel').trim(); } catch { return null; } | |
| 133 | + // prefijo de ROOT dentro del repo (por si se escanea un subdirectorio) | |
| 134 | + const prefix = relative(top, ROOT).split(sep).filter(Boolean).join('/'); | |
| 135 | + const toRel = (p) => { | |
| 136 | + p = p.replace(/^"|"$/g, ''); | |
| 137 | + if (!prefix) return p; | |
| 138 | + return p.startsWith(prefix + '/') ? p.slice(prefix.length + 1) : null; | |
| 139 | + }; | |
| 140 | + const git = {}; | |
| 141 | + try { | |
| 142 | + for (const line of run('git status --porcelain -uall').split('\n')) { | |
| 143 | + if (!line.trim()) continue; | |
| 144 | + const xy = line.slice(0, 2); | |
| 145 | + let p = line.slice(3); | |
| 146 | + if (p.includes(' -> ')) p = p.split(' -> ')[1]; | |
| 147 | + const rel = toRel(p); | |
| 148 | + if (!rel) continue; | |
| 149 | + let st = 'M'; | |
| 150 | + if (xy === '??') st = 'U'; | |
| 151 | + else if (xy.includes('A')) st = 'A'; | |
| 152 | + else if (xy.includes('R')) st = 'R'; | |
| 153 | + else if (xy.includes('D')) st = 'D'; | |
| 154 | + git[rel] = [st, 0, 0]; | |
| 155 | + } | |
| 156 | + for (const line of run('git diff --numstat HEAD').split('\n')) { | |
| 157 | + const m = line.match(/^(\d+|-)\t(\d+|-)\t(.+)$/); | |
| 158 | + if (!m) continue; | |
| 159 | + const rel = toRel(m[3]); | |
| 160 | + if (!rel) continue; | |
| 161 | + const a = m[1] === '-' ? 0 : +m[1], d = m[2] === '-' ? 0 : +m[2]; | |
| 162 | + if (git[rel]) { git[rel][1] = a; git[rel][2] = d; } | |
| 163 | + else git[rel] = ['M', a, d]; | |
| 164 | + } | |
| 165 | + } catch { /* repo sin HEAD o git no disponible */ } | |
| 166 | + return git; | |
| 167 | +} | |
| 168 | + | |
| 169 | +const tree = scanDir(ROOT, '', false, new IgnoreStack()); | |
| 170 | +const symLinks = buildSymbolLinks(defsMap, tokensMap); | |
| 171 | +const meta = { | |
| 172 | + git: gitMeta(), | |
| 173 | + owners: ownerRules, | |
| 174 | + links: resolveAll(refsMap, fileRels, dirRels), | |
| 175 | + codeIndex: { version: INDEX_VERSION, defs: defsMap, symLinks }, | |
| 176 | +}; | |
| 177 | +// persiste la caché del análisis (solo las claves vigentes) | |
| 178 | +flushCache(newCache); | |
| 179 | +const out = `// Generado por scan.mjs — ${new Date().toISOString()} — raíz: ${ROOT} | |
| 180 | +// dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes, ignorado?] | |
| 181 | +export const REPO_TREE = ${JSON.stringify(tree)}; | |
| 182 | +// git: { ruta: [estado, +líneas, −líneas] } · owners: [[patrón, @owner], …] | |
| 183 | +export const REPO_META = ${JSON.stringify(meta)}; | |
| 184 | +`; | |
| 185 | +writeFileSync(join(HERE, 'src', 'data.js'), out); | |
| 186 | +const nGit = meta.git ? Object.keys(meta.git).length : 0; | |
| 187 | +const nLinks = Object.values(meta.links).reduce((a, l) => a + l.length, 0); | |
| 188 | +const nSym = Object.values(symLinks).reduce((a, l) => a + l.length, 0); | |
| 189 | +const nDefs = Object.values(defsMap).reduce((a, l) => a + l.length, 0); | |
| 190 | +console.log(`OK: ${total} ficheros (${ignoredCount} ignorados) · git: ${meta.git ? nGit + ' cambios' : 'no'} · ownership: ${ownerRules.length} reglas · blast: ${nLinks} imports + ${nSym} aristas de símbolo (${nDefs} defs, caché: ${cacheHits} hits) → src/data.js`); |
added serve.sh +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# Sirve VibeCodeViewer en todas las interfaces de red. | |
| 3 | +set -euo pipefail | |
| 4 | +cd "$(dirname "$0")" | |
| 5 | + | |
| 6 | +usage() { | |
| 7 | + cat <<'EOF' | |
| 8 | +Uso: ./serve.sh [puerto] | |
| 9 | + ./serve.sh [puerto] --test N M [K] | |
| 10 | + ./serve.sh --help | |
| 11 | + | |
| 12 | + puerto puerto HTTP (por defecto 8137) | |
| 13 | + --test N M genera un src/data.js sintético (tools/gentest.mjs) con N | |
| 14 | + ficheros, cada uno al fondo de su propia cadena de M carpetas | |
| 15 | + anidadas, y luego sirve. Para depurar el renderizado. | |
| 16 | + --test N M K modo urbanización: cada distrito folder_g contiene un bloque | |
| 17 | + urb_g que crea K carpetas en el nivel de urbanización; cada | |
| 18 | + carpeta continúa la cadena hasta profundidad M. urb_g se | |
| 19 | + convierte en urbanización si K > 2000, o si K > 200 y M ≥ 8 | |
| 20 | + (umbrales de src/model.js). | |
| 21 | + | |
| 22 | +Ejemplos: | |
| 23 | + ./serve.sh --test 2 3 # 2 cadenas de 3 carpetas con 1 fichero | |
| 24 | + ./serve.sh --test 500 8 # 500 edificios de interior profundo | |
| 25 | + ./serve.sh --test 1000 8 250 # 4 urbanizaciones de 250 edificios | |
| 26 | + ./serve.sh --test 1000 4 250 # mismos grupos, poco profundos → sin urbanización | |
| 27 | + ./serve.sh --test 2500 3 2500 # urbanización por población (>2000) | |
| 28 | + ./serve.sh 8200 --test 100 10 # puerto alternativo + test | |
| 29 | + | |
| 30 | +Restaurar el data.js real: git checkout -- src/data.js, o relanzar scan.mjs. | |
| 31 | +EOF | |
| 32 | +} | |
| 33 | + | |
| 34 | +PORT=8137 | |
| 35 | +if [[ $# -gt 0 && "$1" =~ ^(--help|-h)$ ]]; then usage; exit 0; fi | |
| 36 | +if [[ $# -gt 0 && "$1" != --test ]]; then PORT="$1"; shift; fi | |
| 37 | + | |
| 38 | +if [[ $# -gt 0 ]]; then | |
| 39 | + case "$1" in | |
| 40 | + --test) | |
| 41 | + shift | |
| 42 | + [[ $# -ge 2 ]] || { usage >&2; exit 1; } | |
| 43 | + node tools/gentest.mjs "$@" | |
| 44 | + ;; | |
| 45 | + --help|-h) usage; exit 0 ;; | |
| 46 | + *) usage >&2; exit 1 ;; | |
| 47 | + esac | |
| 48 | +fi | |
| 49 | + | |
| 50 | +echo "VibeCodeViewer — sirviendo en:" | |
| 51 | +echo " http://localhost:${PORT}/" | |
| 52 | +for ip in $(hostname -I 2>/dev/null); do | |
| 53 | + echo " http://${ip}:${PORT}/" | |
| 54 | +done | |
| 55 | +exec python3 -m http.server "$PORT" --bind 0.0.0.0 |
added src/analysisCache.js +179 −0
| @@ -0,0 +1,179 @@ | ||
| 1 | +// Caché persistente (IndexedDB) del análisis para el navegador, en tres capas: | |
| 2 | +// - 'files': entrada por fichero con clave `v|rel|size|mtime` → si el fichero | |
| 3 | +// no cambió, el re-escaneo reutiliza specs/defs/tokens sin releerlo. | |
| 4 | +// - 'snapshots': consolidado por commit de HEAD → sobrevive a checkouts y | |
| 5 | +// re-clones (donde cambian todos los mtime y la capa anterior falla). | |
| 6 | +// - 'handles': el FileSystemDirectoryHandle de la última carpeta, para poder | |
| 7 | +// reabrirla pidiendo el permiso de lectura nada más pulsar el botón. | |
| 8 | +const DB_NAME = 'vcc-analysis'; | |
| 9 | +const FILES = 'files'; | |
| 10 | +const SNAPSHOTS = 'snapshots'; | |
| 11 | +const HANDLES = 'handles'; | |
| 12 | +const MAX_ENTRIES = 400000; | |
| 13 | +const MAX_SNAPSHOTS = 4; | |
| 14 | + | |
| 15 | +function openDB() { | |
| 16 | + return new Promise((resolve, reject) => { | |
| 17 | + const req = indexedDB.open(DB_NAME, 2); | |
| 18 | + req.onupgradeneeded = () => { | |
| 19 | + const db = req.result; | |
| 20 | + if (!db.objectStoreNames.contains(FILES)) db.createObjectStore(FILES); | |
| 21 | + if (!db.objectStoreNames.contains(SNAPSHOTS)) db.createObjectStore(SNAPSHOTS); | |
| 22 | + if (!db.objectStoreNames.contains(HANDLES)) db.createObjectStore(HANDLES); | |
| 23 | + }; | |
| 24 | + req.onsuccess = () => resolve(req.result); | |
| 25 | + req.onerror = () => reject(req.error); | |
| 26 | + }); | |
| 27 | +} | |
| 28 | + | |
| 29 | +function get(store, key) { | |
| 30 | + return openDB().then(db => new Promise((resolve) => { | |
| 31 | + const req = db.transaction(store, 'readonly').objectStore(store).get(key); | |
| 32 | + req.onsuccess = () => resolve(req.result ?? null); | |
| 33 | + req.onerror = () => resolve(null); | |
| 34 | + })).catch(() => null); | |
| 35 | +} | |
| 36 | + | |
| 37 | +// carga toda la caché en memoria (una transacción es mucho más rápida que | |
| 38 | +// miles de lecturas individuales durante el escaneo) | |
| 39 | +export async function loadAnalysisCache() { | |
| 40 | + try { | |
| 41 | + const db = await openDB(); | |
| 42 | + return await new Promise((resolve) => { | |
| 43 | + const tx = db.transaction(FILES, 'readonly').objectStore(FILES); | |
| 44 | + const keysReq = tx.getAllKeys(); | |
| 45 | + const valsReq = tx.getAll(); | |
| 46 | + keysReq.onsuccess = () => { | |
| 47 | + valsReq.onsuccess = () => { | |
| 48 | + const map = new Map(); | |
| 49 | + keysReq.result.forEach((k, i) => map.set(k, valsReq.result[i])); | |
| 50 | + resolve(map); | |
| 51 | + }; | |
| 52 | + }; | |
| 53 | + keysReq.onerror = () => resolve(new Map()); | |
| 54 | + }); | |
| 55 | + } catch { | |
| 56 | + return new Map(); | |
| 57 | + } | |
| 58 | +} | |
| 59 | + | |
| 60 | +// guarda entradas en bloque; se llama por lotes durante el análisis para que | |
| 61 | +// una ejecución interrumpida (memoria, cierre de pestaña) deje lo ya hecho | |
| 62 | +// persistido y la siguiente continúe desde ahí vía aciertos de caché | |
| 63 | +export async function saveAnalysisCache(newEntries) { | |
| 64 | + if (!newEntries.size) return; | |
| 65 | + try { | |
| 66 | + const db = await openDB(); | |
| 67 | + await new Promise((resolve, reject) => { | |
| 68 | + const tx = db.transaction(FILES, 'readwrite'); | |
| 69 | + const store = tx.objectStore(FILES); | |
| 70 | + let n = 0; | |
| 71 | + for (const [k, v] of newEntries) { | |
| 72 | + store.put(v, k); | |
| 73 | + if (++n >= MAX_ENTRIES) break; | |
| 74 | + } | |
| 75 | + tx.oncomplete = resolve; | |
| 76 | + tx.onerror = () => reject(tx.error); | |
| 77 | + }); | |
| 78 | + } catch { /* caché es solo una optimización */ } | |
| 79 | +} | |
| 80 | + | |
| 81 | +// ── snapshots por commit, en chunks (checkpoints) ────────────────────────── | |
| 82 | +// Cada checkpoint del análisis escribe un chunk pequeño bajo la clave | |
| 83 | +// `commit#seq` con valor { commit, when, files: { rel → { size, entry } } }. | |
| 84 | +// Escribir solo el delta evita el read-modify-write del snapshot completo en | |
| 85 | +// cada punto de control; al cargar se fusionan todos los chunks del commit. | |
| 86 | + | |
| 87 | +let chunkSeq = 0; | |
| 88 | + | |
| 89 | +function getAllSnapshotChunks() { | |
| 90 | + return openDB().then(db => new Promise((resolve) => { | |
| 91 | + const req = db.transaction(SNAPSHOTS, 'readonly').objectStore(SNAPSHOTS).getAll(); | |
| 92 | + req.onsuccess = () => resolve(req.result ?? []); | |
| 93 | + req.onerror = () => resolve([]); | |
| 94 | + })).catch(() => []); | |
| 95 | +} | |
| 96 | + | |
| 97 | +export async function loadSnapshot(commit) { | |
| 98 | + if (!commit) return null; | |
| 99 | + const chunks = (await getAllSnapshotChunks()).filter(s => s.commit === commit); | |
| 100 | + if (!chunks.length) return null; | |
| 101 | + chunks.sort((a, b) => a.when - b.when); | |
| 102 | + const files = {}; | |
| 103 | + for (const c of chunks) Object.assign(files, c.files); | |
| 104 | + return { commit, when: chunks[chunks.length - 1].when, files }; | |
| 105 | +} | |
| 106 | + | |
| 107 | +export async function latestSnapshot(excludeCommit) { | |
| 108 | + const all = (await getAllSnapshotChunks()).filter(s => s.commit !== excludeCommit); | |
| 109 | + if (!all.length) return null; | |
| 110 | + const best = all.reduce((a, b) => (b.when > a.when ? b : a)); | |
| 111 | + return loadSnapshot(best.commit); | |
| 112 | +} | |
| 113 | + | |
| 114 | +// checkpoint: persiste el delta analizado desde el último punto de control | |
| 115 | +export async function saveSnapshotChunk(commit, filesMap) { | |
| 116 | + if (!commit || !Object.keys(filesMap).length) return; | |
| 117 | + try { | |
| 118 | + const db = await openDB(); | |
| 119 | + await new Promise((resolve, reject) => { | |
| 120 | + const tx = db.transaction(SNAPSHOTS, 'readwrite'); | |
| 121 | + tx.objectStore(SNAPSHOTS).put( | |
| 122 | + { commit, when: Date.now(), files: filesMap }, | |
| 123 | + `${commit}#${Date.now()}-${chunkSeq++}`, | |
| 124 | + ); | |
| 125 | + tx.oncomplete = resolve; | |
| 126 | + tx.onerror = () => reject(tx.error); | |
| 127 | + }); | |
| 128 | + } catch { /* caché es solo una optimización */ } | |
| 129 | +} | |
| 130 | + | |
| 131 | +// compacta los chunks de un commit en uno y poda los commits más antiguos; | |
| 132 | +// se llama una vez al terminar el análisis, no en cada checkpoint | |
| 133 | +export async function pruneSnapshots(keepCommit) { | |
| 134 | + try { | |
| 135 | + const db = await openDB(); | |
| 136 | + const merged = keepCommit ? await loadSnapshot(keepCommit) : null; | |
| 137 | + await new Promise((resolve, reject) => { | |
| 138 | + const tx = db.transaction(SNAPSHOTS, 'readwrite'); | |
| 139 | + const store = tx.objectStore(SNAPSHOTS); | |
| 140 | + const keysReq = store.getAllKeys(); | |
| 141 | + const valsReq = store.getAll(); | |
| 142 | + keysReq.onsuccess = () => valsReq.onsuccess = () => { | |
| 143 | + const keys = keysReq.result ?? [], vals = valsReq.result ?? []; | |
| 144 | + // último `when` por commit → conservar los MAX_SNAPSHOTS más recientes | |
| 145 | + const newest = new Map(); | |
| 146 | + vals.forEach(v => newest.set(v.commit, Math.max(newest.get(v.commit) ?? 0, v.when))); | |
| 147 | + const keep = new Set([...newest.entries()] | |
| 148 | + .sort((a, b) => b[1] - a[1]).slice(0, MAX_SNAPSHOTS).map(([c]) => c)); | |
| 149 | + keys.forEach((k, i) => { | |
| 150 | + const c = vals[i].commit; | |
| 151 | + if (!keep.has(c) || (c === keepCommit && merged)) store.delete(k); | |
| 152 | + }); | |
| 153 | + if (merged && keep.has(keepCommit)) { | |
| 154 | + store.put(merged, `${keepCommit}#${Date.now()}-${chunkSeq++}`); | |
| 155 | + } | |
| 156 | + }; | |
| 157 | + tx.oncomplete = resolve; | |
| 158 | + tx.onerror = () => reject(tx.error); | |
| 159 | + }); | |
| 160 | + } catch { /* caché es solo una optimización */ } | |
| 161 | +} | |
| 162 | + | |
| 163 | +// ── handle persistente de la última carpeta ──────────────────────────────── | |
| 164 | + | |
| 165 | +export function loadSavedHandle() { | |
| 166 | + return get(HANDLES, 'last'); | |
| 167 | +} | |
| 168 | + | |
| 169 | +export async function saveHandle(handle) { | |
| 170 | + try { | |
| 171 | + const db = await openDB(); | |
| 172 | + await new Promise((resolve, reject) => { | |
| 173 | + const tx = db.transaction(HANDLES, 'readwrite'); | |
| 174 | + tx.objectStore(HANDLES).put(handle, 'last'); | |
| 175 | + tx.oncomplete = resolve; | |
| 176 | + tx.onerror = () => reject(tx.error); | |
| 177 | + }); | |
| 178 | + } catch { /* opcional */ } | |
| 179 | +} |
added src/builder.js +617 −0
| @@ -0,0 +1,617 @@ | ||
| 1 | +// Construcción de la escena: ciudad de cristal nítida. | |
| 2 | +// Receta anti-difuminado: aristas finas con colores HDR (el bloom solo se | |
| 3 | +// dispara en lo resaltado), cristal con fresnel de opacidad mínima y nada | |
| 4 | +// de volúmenes aditivos permanentes. | |
| 5 | +// Toda la paleta viene del tema activo (src/themes.js); los temas claros | |
| 6 | +// usan blending normal en lugar de aditivo. | |
| 7 | +import * as THREE from 'three'; | |
| 8 | + | |
| 9 | +function lerp3(a, b, t) { return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; } | |
| 10 | + | |
| 11 | +// 12 aristas de una caja → 24 vértices | |
| 12 | +const EDGE_PAIRS = [ | |
| 13 | + [0, 1], [1, 3], [3, 2], [2, 0], | |
| 14 | + [4, 5], [5, 7], [7, 6], [6, 4], | |
| 15 | + [0, 4], [1, 5], [2, 6], [3, 7], | |
| 16 | +]; | |
| 17 | +function corners(b) { | |
| 18 | + const x0 = b.cx - b.sx / 2, x1 = b.cx + b.sx / 2; | |
| 19 | + const y0 = b.cy - b.sy / 2, y1 = b.cy + b.sy / 2; | |
| 20 | + const z0 = b.cz - b.sz / 2, z1 = b.cz + b.sz / 2; | |
| 21 | + return [ | |
| 22 | + [x0, y0, z0], [x1, y0, z0], [x0, y0, z1], [x1, y0, z1], | |
| 23 | + [x0, y1, z0], [x1, y1, z0], [x0, y1, z1], [x1, y1, z1], | |
| 24 | + ]; | |
| 25 | +} | |
| 26 | + | |
| 27 | +// ── suelo: placa de circuito impreso ────────────────────────────────────── | |
| 28 | +function circuitTexture(theme) { | |
| 29 | + const T = theme.ground; | |
| 30 | + const S = 1024; | |
| 31 | + const cv = document.createElement('canvas'); | |
| 32 | + cv.width = cv.height = S; | |
| 33 | + const g = cv.getContext('2d'); | |
| 34 | + g.fillStyle = T.bg; | |
| 35 | + g.fillRect(0, 0, S, S); | |
| 36 | + g.strokeStyle = T.grid; | |
| 37 | + g.lineWidth = 1; | |
| 38 | + for (let i = 0; i <= S; i += 64) { | |
| 39 | + g.beginPath(); g.moveTo(i, 0); g.lineTo(i, S); g.stroke(); | |
| 40 | + g.beginPath(); g.moveTo(0, i); g.lineTo(S, i); g.stroke(); | |
| 41 | + } | |
| 42 | + const rnd = (() => { let s = 1234567; return () => (s = (s * 16807) % 2147483647) / 2147483647; })(); | |
| 43 | + for (let i = 0; i < 260; i++) { | |
| 44 | + const isA = rnd() < 0.58; | |
| 45 | + const a = 0.18 + rnd() * 0.5; | |
| 46 | + const [tr, tg, tb] = isA ? T.traceA : T.traceB; | |
| 47 | + g.strokeStyle = `rgba(${tr}, ${tg}, ${tb}, ${isA ? a : a * 0.9})`; | |
| 48 | + g.lineWidth = rnd() < 0.12 ? 3 : 1.4; | |
| 49 | + let x = rnd() * S, y = rnd() * S; | |
| 50 | + g.beginPath(); g.moveTo(x, y); | |
| 51 | + const segs = 2 + Math.floor(rnd() * 4); | |
| 52 | + for (let sg = 0; sg < segs; sg++) { | |
| 53 | + const len = 24 + rnd() * 150; | |
| 54 | + if (rnd() < 0.5) x += rnd() < 0.5 ? len : -len; else y += rnd() < 0.5 ? len : -len; | |
| 55 | + g.lineTo(x, y); | |
| 56 | + } | |
| 57 | + g.stroke(); | |
| 58 | + const [pr, pg, pb] = isA ? T.padA : T.padB; | |
| 59 | + g.fillStyle = `rgba(${pr}, ${pg}, ${pb}, ${a + 0.2})`; | |
| 60 | + const ps = 2 + rnd() * 3; | |
| 61 | + g.fillRect(x - ps / 2, y - ps / 2, ps, ps); | |
| 62 | + } | |
| 63 | + const tx = new THREE.CanvasTexture(cv); | |
| 64 | + tx.wrapS = tx.wrapT = THREE.RepeatWrapping; | |
| 65 | + tx.colorSpace = THREE.SRGBColorSpace; | |
| 66 | + tx.anisotropy = 8; | |
| 67 | + return tx; | |
| 68 | +} | |
| 69 | + | |
| 70 | +// ── cristal con fresnel (bordes algo más vivos, centro casi invisible) ──── | |
| 71 | +function glassMaterial(theme, dim = 1, solid = 0) { | |
| 72 | + return new THREE.ShaderMaterial({ | |
| 73 | + uniforms: { | |
| 74 | + uColor: { value: new THREE.Color(...theme.glass) }, | |
| 75 | + uHi: { value: new THREE.Color(...theme.glassHi) }, | |
| 76 | + uGlow: { value: 0 }, | |
| 77 | + uDim: { value: dim }, | |
| 78 | + uSolid: { value: solid }, | |
| 79 | + }, | |
| 80 | + vertexShader: /* glsl */` | |
| 81 | + varying vec3 vN, vV; | |
| 82 | + void main() { | |
| 83 | + vec4 mv = modelViewMatrix * vec4(position, 1.0); | |
| 84 | + vN = normalMatrix * normal; | |
| 85 | + vV = -mv.xyz; | |
| 86 | + gl_Position = projectionMatrix * mv; | |
| 87 | + }`, | |
| 88 | + fragmentShader: /* glsl */` | |
| 89 | + uniform vec3 uColor; | |
| 90 | + uniform vec3 uHi; | |
| 91 | + uniform float uGlow; | |
| 92 | + uniform float uDim; | |
| 93 | + uniform float uSolid; | |
| 94 | + varying vec3 vN, vV; | |
| 95 | + void main() { | |
| 96 | + float fr = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.6); | |
| 97 | + vec3 col = mix(uColor, uHi, uGlow); | |
| 98 | + float alpha = (0.022 + fr * 0.12 + uSolid * 0.12) * uDim + uGlow * 0.05; | |
| 99 | + gl_FragColor = vec4(col * ((0.5 + fr * 1.9) * uDim + uGlow), alpha); | |
| 100 | + }`, | |
| 101 | + transparent: true, | |
| 102 | + depthWrite: false, | |
| 103 | + side: THREE.DoubleSide, | |
| 104 | + }); | |
| 105 | +} | |
| 106 | + | |
| 107 | +// ── fachada: árbol de ficheros impreso sobre el cristal ─────────────────── | |
| 108 | +const FACADE_MAX_LINES = 150; | |
| 109 | + | |
| 110 | +function facadeLines(building) { | |
| 111 | + const lines = []; | |
| 112 | + let overflow = false; | |
| 113 | + (function walk(node, depth) { | |
| 114 | + if (lines.length > FACADE_MAX_LINES) { overflow = true; return; } | |
| 115 | + lines.push({ text: node.name + '/', depth, key: 'n' + node.id }); | |
| 116 | + for (const c of node.children) walk(c, depth + 1); | |
| 117 | + for (const fid of node.fileIds) { | |
| 118 | + if (lines.length > FACADE_MAX_LINES) { overflow = true; return; } | |
| 119 | + const f = building.modelFiles[fid]; | |
| 120 | + lines.push({ text: f.name, depth: depth + 1, key: 'f' + f.id }); | |
| 121 | + } | |
| 122 | + })(building, 0); | |
| 123 | + if (overflow) lines.push({ text: '· · ·', depth: 1, key: '' }); | |
| 124 | + return lines; | |
| 125 | +} | |
| 126 | + | |
| 127 | +function drawFacade(building, highlight, theme) { | |
| 128 | + const cv = building.facadeCanvas; | |
| 129 | + if (!cv) return; // edificio sin fachada (recorte en ciudades enormes) | |
| 130 | + const g = cv.getContext('2d'); | |
| 131 | + const W = cv.width, H = cv.height; | |
| 132 | + g.clearRect(0, 0, W, H); | |
| 133 | + const lines = building.facadeLineCache; | |
| 134 | + const fs = Math.max(9, Math.min(30, (H - 60) / (lines.length + 1))); | |
| 135 | + g.font = `${fs}px "JetBrains Mono", "Cascadia Code", monospace`; | |
| 136 | + g.textBaseline = 'top'; | |
| 137 | + let y = 26; | |
| 138 | + for (const ln of lines) { | |
| 139 | + const x = 22 + ln.depth * fs * 1.1; | |
| 140 | + const hot = highlight && highlight.has(ln.key); | |
| 141 | + if (hot) { | |
| 142 | + g.shadowColor = theme.facade.hotGlow; | |
| 143 | + g.shadowBlur = 14; | |
| 144 | + g.fillStyle = theme.facade.hotBg; | |
| 145 | + g.fillRect(x - 6, y - 3, g.measureText(ln.text).width + 12, fs + 6); | |
| 146 | + g.fillStyle = theme.facade.hot; | |
| 147 | + } else { | |
| 148 | + g.shadowBlur = 0; | |
| 149 | + g.fillStyle = theme.facade.text; | |
| 150 | + } | |
| 151 | + g.fillText(ln.text, x, y); | |
| 152 | + y += fs * 1.18; | |
| 153 | + if (y > H - fs) break; | |
| 154 | + } | |
| 155 | + g.shadowBlur = 0; | |
| 156 | + building.facadeTexture.needsUpdate = true; | |
| 157 | +} | |
| 158 | + | |
| 159 | +function buildFacade(building, model, group, theme) { | |
| 160 | + building.modelFiles = model.files; | |
| 161 | + building.facadeLineCache = facadeLines(building); | |
| 162 | + const b = building.box; | |
| 163 | + const H = 1024; | |
| 164 | + const W = Math.round(Math.min(2048, Math.max(256, H * (b.sx / b.sy)))); | |
| 165 | + const cv = document.createElement('canvas'); | |
| 166 | + cv.width = W; cv.height = H; | |
| 167 | + building.facadeCanvas = cv; | |
| 168 | + const tx = new THREE.CanvasTexture(cv); | |
| 169 | + tx.colorSpace = THREE.SRGBColorSpace; | |
| 170 | + tx.anisotropy = 8; | |
| 171 | + building.facadeTexture = tx; | |
| 172 | + drawFacade(building, null, theme); | |
| 173 | + const mat = new THREE.MeshBasicMaterial({ | |
| 174 | + map: tx, transparent: true, depthWrite: false, side: THREE.FrontSide, | |
| 175 | + }); | |
| 176 | + const E = 0.14; | |
| 177 | + const faces = [ | |
| 178 | + { w: b.sx, pos: [b.cx, b.cy, b.cz + b.sz / 2 + E], rot: 0 }, | |
| 179 | + { w: b.sx, pos: [b.cx, b.cy, b.cz - b.sz / 2 - E], rot: Math.PI }, | |
| 180 | + { w: b.sz, pos: [b.cx + b.sx / 2 + E, b.cy, b.cz], rot: Math.PI / 2 }, | |
| 181 | + { w: b.sz, pos: [b.cx - b.sx / 2 - E, b.cy, b.cz], rot: -Math.PI / 2 }, | |
| 182 | + ]; | |
| 183 | + for (const f of faces) { | |
| 184 | + const plane = new THREE.Mesh(new THREE.PlaneGeometry(f.w, b.sy), mat); | |
| 185 | + plane.position.set(...f.pos); | |
| 186 | + plane.rotation.y = f.rot; | |
| 187 | + plane.renderOrder = 3; | |
| 188 | + group.add(plane); | |
| 189 | + } | |
| 190 | +} | |
| 191 | + | |
| 192 | +// ── leyenda: nombres serigrafiados (suelo de distrito y tejado) ─────────── | |
| 193 | +function labelTexture(text, color) { | |
| 194 | + const fs = 96, pad = 40; | |
| 195 | + const probe = document.createElement('canvas').getContext('2d'); | |
| 196 | + probe.font = `bold ${fs}px "JetBrains Mono", monospace`; | |
| 197 | + const tw = probe.measureText(text).width; | |
| 198 | + const cv = document.createElement('canvas'); | |
| 199 | + cv.width = Math.ceil(tw + pad * 2 + 220); | |
| 200 | + cv.height = 190; | |
| 201 | + const g = cv.getContext('2d'); | |
| 202 | + g.font = `bold ${fs}px "JetBrains Mono", monospace`; | |
| 203 | + g.textBaseline = 'middle'; | |
| 204 | + // pista de circuito: línea con pads a ambos lados del texto | |
| 205 | + g.strokeStyle = color; g.globalAlpha = 0.65; g.lineWidth = 5; | |
| 206 | + const y = cv.height / 2; | |
| 207 | + g.beginPath(); g.moveTo(14, y); g.lineTo(pad + 60, y); g.stroke(); | |
| 208 | + g.beginPath(); g.moveTo(pad + 100 + tw, y); g.lineTo(cv.width - 14, y); g.stroke(); | |
| 209 | + g.fillStyle = color; | |
| 210 | + for (const px of [14, pad + 60, pad + 100 + tw, cv.width - 26]) g.fillRect(px - 7, y - 7, 14, 14); | |
| 211 | + g.globalAlpha = 0.92; | |
| 212 | + g.shadowColor = color; g.shadowBlur = 16; | |
| 213 | + g.fillText(text, pad + 80, y); | |
| 214 | + const tx = new THREE.CanvasTexture(cv); | |
| 215 | + tx.colorSpace = THREE.SRGBColorSpace; | |
| 216 | + tx.anisotropy = 8; | |
| 217 | + return { tx, aspect: cv.width / cv.height }; | |
| 218 | +} | |
| 219 | + | |
| 220 | +const LEGEND_MAX_BUILDINGS = 400; | |
| 221 | + | |
| 222 | +function buildLegend(model, labeled, theme) { | |
| 223 | + const legend = new THREE.Group(); | |
| 224 | + const add = (text, color, width, pos, flat) => { | |
| 225 | + const { tx, aspect } = labelTexture(text, color); | |
| 226 | + const w = Math.min(width, aspect * 8); | |
| 227 | + const mesh = new THREE.Mesh( | |
| 228 | + new THREE.PlaneGeometry(w, w / aspect), | |
| 229 | + new THREE.MeshBasicMaterial({ | |
| 230 | + map: tx, transparent: true, depthWrite: false, | |
| 231 | + blending: theme.light ? THREE.NormalBlending : THREE.AdditiveBlending, | |
| 232 | + }), | |
| 233 | + ); | |
| 234 | + if (flat) mesh.rotation.x = -Math.PI / 2; | |
| 235 | + mesh.position.set(...pos); | |
| 236 | + mesh.renderOrder = 4; | |
| 237 | + legend.add(mesh); | |
| 238 | + }; | |
| 239 | + for (const di of model.districts) { | |
| 240 | + add(di.name, theme.labels.district, di.box.sx * 0.85, | |
| 241 | + [di.box.cx, 0.3, di.box.cz + di.box.sz / 2 - 2], true); | |
| 242 | + } | |
| 243 | + // urbanizaciones: mismo serigrafiado de suelo que los distritos, en tono | |
| 244 | + // intermedio; en monorepos se etiquetan las de mayor superficie | |
| 245 | + const urbs = [...model.urbs].sort((a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz); | |
| 246 | + for (const u of urbs.slice(0, LEGEND_MAX_BUILDINGS)) { | |
| 247 | + add(u.name, theme.labels.urb, u.box.sx * 0.8, | |
| 248 | + [u.box.cx, 0.32, u.box.cz + u.box.sz / 2 - 1.4], true); | |
| 249 | + } | |
| 250 | + for (const b of labeled.slice(0, LEGEND_MAX_BUILDINGS)) { | |
| 251 | + if (b.isBasement) continue; // su tejado es la calle: sin etiqueta | |
| 252 | + add(b.name, theme.labels.building, b.box.sx * 0.95, | |
| 253 | + [b.box.cx, b.box.cy + b.box.sy / 2 + 0.12, b.box.cz], true); | |
| 254 | + } | |
| 255 | + return legend; | |
| 256 | +} | |
| 257 | + | |
| 258 | +// ── ciudad completa ─────────────────────────────────────────────────────── | |
| 259 | +export function buildCity(scene, model, theme) { | |
| 260 | + const group = new THREE.Group(); | |
| 261 | + scene.add(group); | |
| 262 | + // paleta del tema; en temas claros el blending aditivo no funciona | |
| 263 | + const ROLE_COLOR = theme.roleColor; | |
| 264 | + const HI = theme.hi; | |
| 265 | + const FILE_BASE = theme.fileBase; | |
| 266 | + const FILE_HI = theme.fileHi; | |
| 267 | + const BLEND = theme.light ? THREE.NormalBlending : THREE.AdditiveBlending; | |
| 268 | + | |
| 269 | + // suelo | |
| 270 | + const extent = Math.max(model.city.box.sx, model.city.box.sz); | |
| 271 | + const ground = new THREE.Mesh( | |
| 272 | + new THREE.PlaneGeometry(extent * 7, extent * 7), | |
| 273 | + // semitransparente y a doble cara: los sótanos (ficheros ignorados) | |
| 274 | + // se intuyen a través del plano de circuitos. depthWrite: false — era el | |
| 275 | + // único material que escribía profundidad y, con el rango near/far de la | |
| 276 | + // ciudad, las plotas y serigrafías a ras de suelo hacían z-fighting | |
| 277 | + // (parpadeo en franjas) al mover la cámara | |
| 278 | + new THREE.MeshBasicMaterial({ | |
| 279 | + map: circuitTexture(theme), transparent: true, opacity: 0.8, side: THREE.DoubleSide, | |
| 280 | + depthWrite: false, | |
| 281 | + // separa el suelo en el z-buffer de plotas y serigrafías a ras de | |
| 282 | + // suelo (evita el z-fighting cuando el modo opaco activa depthWrite) | |
| 283 | + polygonOffset: true, polygonOffsetFactor: 2, polygonOffsetUnits: 2, | |
| 284 | + }), | |
| 285 | + ); | |
| 286 | + ground.material.map.repeat.set(7, 7); | |
| 287 | + ground.rotation.x = -Math.PI / 2; | |
| 288 | + ground.position.y = -0.05; | |
| 289 | + group.add(ground); | |
| 290 | + | |
| 291 | + // aristas de las cajas en un único buffer con rangos por nodo. | |
| 292 | + // LOD por presupuesto para monorepos: decenas de miles de wireframes | |
| 293 | + // aditivos se acumulan en blanco. Distritos y edificios siempre dibujan; | |
| 294 | + // del interior se conservan las cajas más grandes y menos profundas. | |
| 295 | + const LINE_BUDGET = 12000; | |
| 296 | + const ROLE_DEPTH = { distrito: 0, urbanizacion: 0, edificio: 0, planta: 1, apartamento: 2, habitacion: 3, archivador: 4, cajon: 5 }; | |
| 297 | + const candidates = model.nodes.filter(n => n.role !== 'ciudad' && n.box); | |
| 298 | + let boxNodes = candidates; | |
| 299 | + if (candidates.length > LINE_BUDGET) { | |
| 300 | + const score = (n) => (n.role === 'distrito' || n.role === 'urbanizacion' || n.role === 'edificio') | |
| 301 | + ? Infinity | |
| 302 | + : Math.max(n.box.sx, n.box.sy, n.box.sz) - ROLE_DEPTH[n.role] * 3; | |
| 303 | + boxNodes = candidates.sort((a, b) => score(b) - score(a)).slice(0, LINE_BUDGET); | |
| 304 | + } | |
| 305 | + const positions = new Float32Array(boxNodes.length * 24 * 3); | |
| 306 | + const colors = new Float32Array(boxNodes.length * 24 * 3); | |
| 307 | + // brillo de arista normalizado por edificio: el interior de un edificio | |
| 308 | + // reparte un presupuesto de luz constante (mismo principio que las celdas) | |
| 309 | + const boxesPerBuilding = new Map(); | |
| 310 | + for (const n of boxNodes) { | |
| 311 | + if (n.building && n.building !== n) { | |
| 312 | + boxesPerBuilding.set(n.building.id, (boxesPerBuilding.get(n.building.id) ?? 0) + 1); | |
| 313 | + } | |
| 314 | + } | |
| 315 | + // …y una atenuación global suave en ciudades con miles de edificios: | |
| 316 | + // uniforme (todos los edificios conservan el mismo aspecto entre sí), | |
| 317 | + // solo evita que la acumulación aditiva a vista de pájaro se queme | |
| 318 | + const cityDim = Math.min(1, Math.max(0.45, Math.sqrt(900 / Math.max(model.buildings.length, 1)))); | |
| 319 | + for (const n of boxNodes) { | |
| 320 | + const local = (!n.building || n.building === n) | |
| 321 | + ? 1 | |
| 322 | + : Math.min(1, Math.max(0.12, 30 / (boxesPerBuilding.get(n.building.id) ?? 1))); | |
| 323 | + // las plotas (distrito y urbanización) son solo perímetro: siempre nítidas | |
| 324 | + n.lineDim = (n.role === 'distrito' || n.role === 'urbanizacion') ? 1 : local * cityDim; | |
| 325 | + } | |
| 326 | + | |
| 327 | + let v = 0; | |
| 328 | + for (const node of boxNodes) { | |
| 329 | + node.lineStart = v; | |
| 330 | + const cs = corners(node.box); | |
| 331 | + const base = (ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon).map(c => c * node.lineDim); | |
| 332 | + node.baseColor = base; | |
| 333 | + for (const [a, b] of EDGE_PAIRS) { | |
| 334 | + for (const p of [cs[a], cs[b]]) { | |
| 335 | + positions[v * 3] = p[0]; positions[v * 3 + 1] = p[1]; positions[v * 3 + 2] = p[2]; | |
| 336 | + colors[v * 3] = base[0]; colors[v * 3 + 1] = base[1]; colors[v * 3 + 2] = base[2]; | |
| 337 | + v++; | |
| 338 | + } | |
| 339 | + } | |
| 340 | + } | |
| 341 | + const lineGeo = new THREE.BufferGeometry(); | |
| 342 | + lineGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3)); | |
| 343 | + lineGeo.setAttribute('color', new THREE.BufferAttribute(colors, 3)); | |
| 344 | + // opacidad adaptativa: cuantas más cajas, más tenue cada arista | |
| 345 | + const lineOpacity = Math.min(0.95, Math.max(0.4, Math.sqrt(4000 / Math.max(boxNodes.length, 1)))); | |
| 346 | + const lines = new THREE.LineSegments(lineGeo, new THREE.LineBasicMaterial({ | |
| 347 | + vertexColors: true, transparent: true, opacity: lineOpacity, | |
| 348 | + blending: BLEND, depthWrite: false, | |
| 349 | + })); | |
| 350 | + lines.renderOrder = 2; | |
| 351 | + group.add(lines); | |
| 352 | + | |
| 353 | + // carcasas de cristal por edificio (también sirven para el raycast). | |
| 354 | + // En ciudades enormes las fachadas con texto se reservan a los edificios | |
| 355 | + // más grandes (una textura canvas por edificio no escala a miles). | |
| 356 | + const byArea = [...model.buildings].sort( | |
| 357 | + (a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz); | |
| 358 | + const facadeSet = new Set(byArea.slice(0, 250)); | |
| 359 | + const shells = []; | |
| 360 | + for (const b of model.buildings) { | |
| 361 | + const mat = glassMaterial(theme, cityDim, b.onlyBasement ? 1 : 0); | |
| 362 | + const mesh = new THREE.Mesh(new THREE.BoxGeometry(b.box.sx, b.box.sy, b.box.sz), mat); | |
| 363 | + mesh.position.set(b.box.cx, b.box.cy, b.box.cz); | |
| 364 | + mesh.renderOrder = 1; | |
| 365 | + mesh.userData.building = b; | |
| 366 | + b.shell = mesh; | |
| 367 | + shells.push(mesh); | |
| 368 | + group.add(mesh); | |
| 369 | + if (facadeSet.has(b)) buildFacade(b, model, group, theme); | |
| 370 | + } | |
| 371 | + | |
| 372 | + // forjados de las plantas (losa fina, casi invisible); con tope en | |
| 373 | + // monorepos, priorizando las plantas de mayor superficie | |
| 374 | + let slabNodes = model.nodes.filter(n => n.role === 'planta'); | |
| 375 | + if (slabNodes.length > 4000) { | |
| 376 | + slabNodes = slabNodes | |
| 377 | + .sort((a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz) | |
| 378 | + .slice(0, 4000); | |
| 379 | + } | |
| 380 | + if (slabNodes.length) { | |
| 381 | + const slabGeo = new THREE.BoxGeometry(1, 1, 1); | |
| 382 | + const slabMat = new THREE.MeshBasicMaterial({ | |
| 383 | + color: new THREE.Color(...theme.slab), transparent: true, | |
| 384 | + opacity: Math.min(0.045, 0.045 * Math.sqrt(1500 / slabNodes.length)), | |
| 385 | + depthWrite: false, blending: BLEND, | |
| 386 | + }); | |
| 387 | + const slabs = new THREE.InstancedMesh(slabGeo, slabMat, slabNodes.length); | |
| 388 | + const m = new THREE.Matrix4(); | |
| 389 | + slabNodes.forEach((n, i) => { | |
| 390 | + m.makeScale(n.box.sx, 0.12, n.box.sz); | |
| 391 | + m.setPosition(n.box.cx, n.box.cy - n.box.sy / 2, n.box.cz); | |
| 392 | + slabs.setMatrixAt(i, m); | |
| 393 | + }); | |
| 394 | + slabs.renderOrder = 1; | |
| 395 | + group.add(slabs); | |
| 396 | + } | |
| 397 | + | |
| 398 | + // celdas de fichero (instanciadas) | |
| 399 | + const fileGeo = new THREE.BoxGeometry(1, 1, 1); | |
| 400 | + const fileMat = new THREE.MeshBasicMaterial({ | |
| 401 | + transparent: true, opacity: 0.9, depthWrite: false, blending: BLEND, | |
| 402 | + }); | |
| 403 | + const filesMesh = new THREE.InstancedMesh(fileGeo, fileMat, model.files.length); | |
| 404 | + { | |
| 405 | + const m = new THREE.Matrix4(); | |
| 406 | + const c = new THREE.Color(); | |
| 407 | + for (const f of model.files) { | |
| 408 | + m.makeScale(f.box.sx, f.box.sy, f.box.sz); | |
| 409 | + m.setPosition(f.box.cx, f.box.cy, f.box.cz); | |
| 410 | + filesMesh.setMatrixAt(f.id, m); | |
| 411 | + filesMesh.setColorAt(f.id, c.setRGB(...FILE_BASE)); | |
| 412 | + } | |
| 413 | + filesMesh.instanceColor.needsUpdate = true; | |
| 414 | + } | |
| 415 | + filesMesh.renderOrder = 2; | |
| 416 | + group.add(filesMesh); | |
| 417 | + | |
| 418 | + // cajas de relleno para los niveles encendidos (pool reutilizable) | |
| 419 | + const fillPool = []; | |
| 420 | + for (let i = 0; i < 10; i++) { | |
| 421 | + const mesh = new THREE.Mesh( | |
| 422 | + new THREE.BoxGeometry(1, 1, 1), | |
| 423 | + new THREE.MeshBasicMaterial({ | |
| 424 | + color: new THREE.Color(...theme.fill), transparent: true, opacity: 0, | |
| 425 | + depthWrite: false, blending: BLEND, | |
| 426 | + }), | |
| 427 | + ); | |
| 428 | + mesh.visible = false; | |
| 429 | + mesh.renderOrder = 2; | |
| 430 | + group.add(mesh); | |
| 431 | + fillPool.push(mesh); | |
| 432 | + } | |
| 433 | + | |
| 434 | + // ── API de iluminación ────────────────────────────────────────────── | |
| 435 | + const touchedNodes = new Set(); | |
| 436 | + const touchedFiles = new Set(); | |
| 437 | + const colorAttr = lineGeo.getAttribute('color'); | |
| 438 | + const tmpColor = new THREE.Color(); | |
| 439 | + // atenuación normalizada por edificio: cada edificio reparte un presupuesto | |
| 440 | + // de luz constante entre sus celdas — así un rascacielos con 50k ficheros | |
| 441 | + // no se quema y uno con 20 sigue viéndose igual que antes | |
| 442 | + const filesPerBuilding = new Map(); | |
| 443 | + for (const f of model.files) { | |
| 444 | + const b = f.node.building; | |
| 445 | + if (b) filesPerBuilding.set(b.id, (filesPerBuilding.get(b.id) ?? 0) + 1); | |
| 446 | + } | |
| 447 | + const dimOf = (f) => { | |
| 448 | + const n = filesPerBuilding.get(f.node.building?.id) ?? 1; | |
| 449 | + return Math.min(1, Math.max(0.05, 350 / n)) * cityDim; | |
| 450 | + }; | |
| 451 | + // color base por fichero, reescribible por los modos de coloreado | |
| 452 | + const fileBase = model.files.map(f => FILE_BASE.map(c => c * dimOf(f))); | |
| 453 | + | |
| 454 | + function paintNode(node, glow, hi = HI) { | |
| 455 | + // los nodos diminutos no tienen aristas (LOD): solo carcasa/relleno | |
| 456 | + if (node.lineStart !== undefined) { | |
| 457 | + const col = lerp3(node.baseColor, hi, Math.pow(glow, 1.35)); | |
| 458 | + for (let i = node.lineStart; i < node.lineStart + 24; i++) { | |
| 459 | + colorAttr.array[i * 3] = col[0]; | |
| 460 | + colorAttr.array[i * 3 + 1] = col[1]; | |
| 461 | + colorAttr.array[i * 3 + 2] = col[2]; | |
| 462 | + } | |
| 463 | + // subida parcial: en monorepos el buffer completo pesa decenas de MB | |
| 464 | + colorAttr.addUpdateRange(node.lineStart * 3, 72); | |
| 465 | + colorAttr.needsUpdate = true; | |
| 466 | + } | |
| 467 | + if (node.shell) node.shell.material.uniforms.uGlow.value = glow * 0.3; | |
| 468 | + if (glow > 0.01) touchedNodes.add(node); else touchedNodes.delete(node); | |
| 469 | + } | |
| 470 | + | |
| 471 | + function paintFile(fileId, glow, hi = FILE_HI) { | |
| 472 | + const col = lerp3(fileBase[fileId], hi, glow); | |
| 473 | + filesMesh.setColorAt(fileId, tmpColor.setRGB(...col)); | |
| 474 | + filesMesh.instanceColor.addUpdateRange(fileId * 3, 3); | |
| 475 | + filesMesh.instanceColor.needsUpdate = true; | |
| 476 | + if (glow > 0.01) touchedFiles.add(fileId); else touchedFiles.delete(fileId); | |
| 477 | + } | |
| 478 | + | |
| 479 | + function clearGlows() { | |
| 480 | + for (const n of [...touchedNodes]) paintNode(n, 0); | |
| 481 | + for (const f of [...touchedFiles]) paintFile(f, 0); | |
| 482 | + for (const mesh of fillPool) mesh.visible = false; | |
| 483 | + } | |
| 484 | + | |
| 485 | + // haces del modo Blast: del fichero seleccionado a sus relacionados, | |
| 486 | + // con pulsos viajando por la línea como paquetes de datos | |
| 487 | + let blastBeams = null; | |
| 488 | + function setBlastBeams(pairs) { | |
| 489 | + if (blastBeams) { | |
| 490 | + group.remove(blastBeams); | |
| 491 | + blastBeams.geometry.dispose(); | |
| 492 | + blastBeams.material.dispose(); | |
| 493 | + blastBeams = null; | |
| 494 | + } | |
| 495 | + if (!pairs?.length) return; | |
| 496 | + // pairs: { a, b, impact } — impact=true: b depende del seleccionado | |
| 497 | + // (consecuencias de un cambio); el pulso siempre viaja en el sentido de | |
| 498 | + // la propagación: hacia fuera en impactos, hacia dentro en dependencias | |
| 499 | + const pos = new Float32Array(pairs.length * 6); | |
| 500 | + const dist = new Float32Array(pairs.length * 2); | |
| 501 | + const dir = new Float32Array(pairs.length * 2); | |
| 502 | + pairs.forEach(({ a, b, impact }, i) => { | |
| 503 | + pos.set(a, i * 6); | |
| 504 | + pos.set(b, i * 6 + 3); | |
| 505 | + const len = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]); | |
| 506 | + dist[i * 2] = impact ? 0 : len; | |
| 507 | + dist[i * 2 + 1] = impact ? len : 0; | |
| 508 | + dir[i * 2] = dir[i * 2 + 1] = impact ? 1 : 0; | |
| 509 | + }); | |
| 510 | + const geo = new THREE.BufferGeometry(); | |
| 511 | + geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); | |
| 512 | + geo.setAttribute('aDist', new THREE.BufferAttribute(dist, 1)); | |
| 513 | + geo.setAttribute('aDir', new THREE.BufferAttribute(dir, 1)); | |
| 514 | + blastBeams = new THREE.LineSegments(geo, new THREE.ShaderMaterial({ | |
| 515 | + uniforms: { | |
| 516 | + uTime: { value: 0 }, | |
| 517 | + uColor: { value: new THREE.Color(...theme.beam) }, | |
| 518 | + uColorIn: { value: new THREE.Color(...(theme.beamIn ?? theme.beam)) }, | |
| 519 | + }, | |
| 520 | + vertexShader: /* glsl */` | |
| 521 | + attribute float aDist; | |
| 522 | + attribute float aDir; | |
| 523 | + varying float vD; | |
| 524 | + varying float vDir; | |
| 525 | + void main() { | |
| 526 | + vD = aDist; | |
| 527 | + vDir = aDir; | |
| 528 | + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); | |
| 529 | + }`, | |
| 530 | + fragmentShader: /* glsl */` | |
| 531 | + uniform float uTime; | |
| 532 | + uniform vec3 uColor; | |
| 533 | + uniform vec3 uColorIn; | |
| 534 | + varying float vD; | |
| 535 | + varying float vDir; | |
| 536 | + void main() { | |
| 537 | + // tren de pulsos avanzando por la línea (cada ~8 unidades); la | |
| 538 | + // línea base se mantiene bien visible entre pulsos | |
| 539 | + float w = fract(vD * 0.125 - uTime * 1.4); | |
| 540 | + float pulse = exp(-pow((w - 0.2) * 6.0, 2.0)); | |
| 541 | + vec3 col = mix(uColor, uColorIn, vDir); | |
| 542 | + gl_FragColor = vec4(col * (0.6 + pulse * 2.4), 0.5 + pulse * 0.5); | |
| 543 | + }`, | |
| 544 | + transparent: true, | |
| 545 | + blending: BLEND, | |
| 546 | + depthWrite: false, | |
| 547 | + })); | |
| 548 | + blastBeams.renderOrder = 3; | |
| 549 | + group.add(blastBeams); | |
| 550 | + } | |
| 551 | + | |
| 552 | + function tickBeams(timeMs) { | |
| 553 | + if (blastBeams) blastBeams.material.uniforms.uTime.value = timeMs / 1000; | |
| 554 | + } | |
| 555 | + | |
| 556 | + // modos de coloreado: reescribe los colores base de nodos y ficheros | |
| 557 | + // (fileColorFn/nodeColorFn → [r,g,b] o null para el color por defecto) | |
| 558 | + function setModeColors(fileColorFn, nodeColorFn) { | |
| 559 | + for (const node of boxNodes) { | |
| 560 | + const col = nodeColorFn?.(node) ?? (ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon); | |
| 561 | + node.baseColor = col.map(c => c * (node.lineDim ?? 1)); | |
| 562 | + paintNode(node, 0); | |
| 563 | + } | |
| 564 | + for (const f of model.files) { | |
| 565 | + const dim = dimOf(f); | |
| 566 | + const col = fileColorFn?.(f) ?? FILE_BASE; | |
| 567 | + fileBase[f.id] = col.map(c => c * dim); | |
| 568 | + paintFile(f.id, 0); | |
| 569 | + } | |
| 570 | + // se ha tocado todo: mejor una única subida completa que miles de rangos | |
| 571 | + colorAttr.clearUpdateRanges(); | |
| 572 | + filesMesh.instanceColor.clearUpdateRanges(); | |
| 573 | + } | |
| 574 | + | |
| 575 | + function fillBoxes(boxesWithGlow) { | |
| 576 | + fillPool.forEach((mesh, i) => { | |
| 577 | + const entry = boxesWithGlow[i]; | |
| 578 | + if (!entry) { mesh.visible = false; return; } | |
| 579 | + const { box, glow } = entry; | |
| 580 | + mesh.scale.set(box.sx, box.sy, box.sz); | |
| 581 | + mesh.position.set(box.cx, box.cy, box.cz); | |
| 582 | + mesh.material.opacity = 0.008 + glow * 0.045; | |
| 583 | + mesh.visible = true; | |
| 584 | + }); | |
| 585 | + } | |
| 586 | + | |
| 587 | + // leyenda serigrafiada (conmutable) | |
| 588 | + const legend = buildLegend(model, byArea, theme); | |
| 589 | + group.add(legend); | |
| 590 | + | |
| 591 | + function dispose() { | |
| 592 | + scene.remove(group); | |
| 593 | + group.traverse((o) => { | |
| 594 | + o.geometry?.dispose?.(); | |
| 595 | + for (const m of Array.isArray(o.material) ? o.material : [o.material]) { | |
| 596 | + m?.map?.dispose?.(); | |
| 597 | + m?.dispose?.(); | |
| 598 | + } | |
| 599 | + }); | |
| 600 | + } | |
| 601 | + | |
| 602 | + return { | |
| 603 | + group, lines, shells, filesMesh, ground, legend, | |
| 604 | + paintNode, paintFile, clearGlows, fillBoxes, dispose, setModeColors, setBlastBeams, tickBeams, | |
| 605 | + setLegend: (v) => { legend.visible = v; }, | |
| 606 | + // suelo opaco/translúcido. Opaco = escribe profundidad y se dibuja en la | |
| 607 | + // pasada de opacos: oculta de verdad los sótanos (ficheros ignorados) | |
| 608 | + setGroundOpaque: (v) => { | |
| 609 | + const m = ground.material; | |
| 610 | + m.opacity = v ? 1 : 0.8; | |
| 611 | + m.transparent = !v; | |
| 612 | + m.depthWrite = v; | |
| 613 | + m.needsUpdate = true; | |
| 614 | + }, | |
| 615 | + redrawFacade: (building, highlightKeys) => drawFacade(building, highlightKeys, theme), | |
| 616 | + }; | |
| 617 | +} |
added src/codeIndex.js +0 −0
Binary content is not shown. View the file.
added src/codeLinks.js +113 −0
| @@ -0,0 +1,113 @@ | ||
| 1 | +// Análisis estático ligero de relaciones entre ficheros para el modo Blast: | |
| 2 | +// imports/exports/require/include/source/url(...) → enlaces fichero→fichero | |
| 3 | +// o fichero→carpeta. Compartido por scan.mjs y fsScan.js. | |
| 4 | + | |
| 5 | +const SRC_EXT = /\.(m?js|cjs|jsx|tsx?|css|html?|py|c|cc|cpp|h|hpp|sh|vue|svelte)$/i; | |
| 6 | +export const MAX_SRC_BYTES = 400 * 1024; | |
| 7 | + | |
| 8 | +export function isAnalyzable(name, size) { | |
| 9 | + return size > 0 && size <= MAX_SRC_BYTES && SRC_EXT.test(name); | |
| 10 | +} | |
| 11 | + | |
| 12 | +// extrae las "specs" crudas referenciadas desde un fichero | |
| 13 | +export function extractRefs(name, text) { | |
| 14 | + const specs = new Set(); | |
| 15 | + const add = (s) => { | |
| 16 | + if (!s) return; | |
| 17 | + s = s.split(/[?#]/)[0].trim(); | |
| 18 | + if (s && !/^(https?:|\/\/|data:|mailto:|about:)/.test(s)) specs.add(s); | |
| 19 | + }; | |
| 20 | + const scan = (re) => { for (const m of text.matchAll(re)) add(m[1]); }; | |
| 21 | + const n = name.toLowerCase(); | |
| 22 | + | |
| 23 | + if (/\.(m?js|cjs|jsx|tsx?|vue|svelte|html?)$/.test(n)) { | |
| 24 | + scan(/import\s+(?:[\s\S]*?from\s*)?['"]([^'"]+)['"]/g); | |
| 25 | + scan(/export\s+[^;'"]*?from\s*['"]([^'"]+)['"]/g); | |
| 26 | + scan(/require\s*\(\s*['"]([^'"]+)['"]/g); | |
| 27 | + scan(/import\s*\(\s*['"]([^'"]+)['"]/g); | |
| 28 | + } | |
| 29 | + if (/\.(html?|vue|svelte)$/.test(n)) scan(/(?:src|href)\s*=\s*["']([^"']+)["']/g); | |
| 30 | + if (/\.css$/.test(n)) { | |
| 31 | + scan(/@import\s+(?:url\(\s*)?['"]?([^'")\s]+)/g); | |
| 32 | + scan(/url\(\s*['"]?([^'")\s]+)/g); | |
| 33 | + } | |
| 34 | + if (/\.py$/.test(n)) { | |
| 35 | + for (const m of text.matchAll(/^\s*from\s+([\w.]+)\s+import/gm)) add(m[1].replace(/\./g, '/')); | |
| 36 | + for (const m of text.matchAll(/^\s*import\s+([\w.]+)/gm)) add(m[1].replace(/\./g, '/')); | |
| 37 | + } | |
| 38 | + if (/\.(c|cc|cpp|h|hpp)$/.test(n)) scan(/#include\s*["<]([^">]+)[">]/g); | |
| 39 | + if (/\.sh$/.test(n)) scan(/(?:^|\s)(?:source|\.)\s+(\S+\.\w+)/gm); | |
| 40 | + return [...specs]; | |
| 41 | +} | |
| 42 | + | |
| 43 | +const RESOLVE_EXTS = ['', '.js', '.mjs', '.ts', '.tsx', '.jsx', '.css', '.html', '.py', '.h', '.hpp', '.sh', '.json']; | |
| 44 | + | |
| 45 | +function normalize(parts) { | |
| 46 | + const out = []; | |
| 47 | + for (const p of parts) { | |
| 48 | + if (!p || p === '.') continue; | |
| 49 | + if (p === '..') { if (!out.length) return null; out.pop(); } | |
| 50 | + else out.push(p); | |
| 51 | + } | |
| 52 | + return out.join('/'); | |
| 53 | +} | |
| 54 | + | |
| 55 | +// resuelve las specs contra el conjunto de ficheros/carpetas del árbol. | |
| 56 | +// refs: { relFichero: [spec, …] } → { relFichero: ['F:rel'|'D:rel', …] } | |
| 57 | +export function resolveAll(refs, fileRels, dirRels) { | |
| 58 | + const files = new Set(fileRels); | |
| 59 | + const dirs = new Set(dirRels); | |
| 60 | + // índice por nombre para specs sueltas ('three' → three.module.js) | |
| 61 | + const byName = new Map(); | |
| 62 | + for (const rel of fileRels) { | |
| 63 | + const base = rel.split('/').pop(); | |
| 64 | + const stem = base.replace(/\.[^.]+$/, ''); | |
| 65 | + for (const k of new Set([base, stem, stem.split('.')[0]])) { | |
| 66 | + if (!byName.has(k)) byName.set(k, []); | |
| 67 | + byName.get(k).push(rel); | |
| 68 | + } | |
| 69 | + } | |
| 70 | + const tryResolve = (cand) => { | |
| 71 | + for (const e of RESOLVE_EXTS) if (files.has(cand + e)) return 'F:' + cand + e; | |
| 72 | + for (const e of RESOLVE_EXTS) if (e && files.has(`${cand}/index${e}`)) return `F:${cand}/index${e}`; | |
| 73 | + if (dirs.has(cand)) return 'D:' + cand; | |
| 74 | + return null; | |
| 75 | + }; | |
| 76 | + | |
| 77 | + const links = {}; | |
| 78 | + for (const [src, specs] of Object.entries(refs)) { | |
| 79 | + const dir = src.split('/').slice(0, -1); | |
| 80 | + const out = new Set(); | |
| 81 | + for (const spec of specs) { | |
| 82 | + let hit = null; | |
| 83 | + if (spec.startsWith('.')) { | |
| 84 | + const p = normalize([...dir, ...spec.split('/')]); | |
| 85 | + if (p != null) hit = tryResolve(p); | |
| 86 | + } else if (spec.startsWith('/')) { | |
| 87 | + hit = tryResolve(spec.slice(1)); | |
| 88 | + } else { | |
| 89 | + // ruta implícita relativa, luego anclada a la raíz | |
| 90 | + const p = normalize([...dir, ...spec.split('/')]); | |
| 91 | + hit = (p != null && tryResolve(p)) || tryResolve(spec); | |
| 92 | + if (!hit && spec.includes('/')) { | |
| 93 | + // spec de paquete ('three/addons/x.js'): sufijo único en el árbol. | |
| 94 | + // Se buscan candidatos por nombre de fichero en vez de filtrar el | |
| 95 | + // árbol entero: con cientos de miles de ficheros y miles de specs | |
| 96 | + // sin resolver, el filtro lineal congelaba el análisis. | |
| 97 | + const tail = spec.split('/').slice(1).join('/'); | |
| 98 | + const cand = tail ? byName.get(tail.split('/').pop()) ?? [] : []; | |
| 99 | + const m = cand.filter(f => f.endsWith('/' + tail)); | |
| 100 | + if (m.length === 1) hit = 'F:' + m[0]; | |
| 101 | + } | |
| 102 | + if (!hit && !spec.includes('/')) { | |
| 103 | + // nombre suelto único en todo el árbol | |
| 104 | + const m = byName.get(spec); | |
| 105 | + if (m && m.length === 1) hit = 'F:' + m[0]; | |
| 106 | + } | |
| 107 | + } | |
| 108 | + if (hit && hit !== 'F:' + src) out.add(hit); | |
| 109 | + } | |
| 110 | + if (out.size) links[src] = [...out]; | |
| 111 | + } | |
| 112 | + return links; | |
| 113 | +} |
added src/colorModes.js +103 −0
| @@ -0,0 +1,103 @@ | ||
| 1 | +// Modos de coloreado: basic (estado actual), git (estado del fichero según | |
| 2 | +// git) y ownership (un color por code owner). El color del fichero se | |
| 3 | +// propaga atenuado a sus contenedores: habitación, planta, edificio, barrio… | |
| 4 | +// Los colores base por rol salen del tema activo. | |
| 5 | + | |
| 6 | +export const GIT_STATUS = { | |
| 7 | + M: { label: 'Modificado', color: [0.95, 0.65, 0.10] }, | |
| 8 | + A: { label: 'Añadido (staged)', color: [0.15, 0.85, 0.45] }, | |
| 9 | + U: { label: 'Sin seguimiento', color: [0.20, 0.90, 0.30] }, | |
| 10 | + R: { label: 'Renombrado', color: [0.30, 0.55, 1.00] }, | |
| 11 | + D: { label: 'Borrado', color: [1.00, 0.25, 0.25] }, | |
| 12 | +}; | |
| 13 | + | |
| 14 | +function lerp3(a, b, t) { return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; } | |
| 15 | + | |
| 16 | +function hsl(h, s, l) { | |
| 17 | + const f = (n) => { | |
| 18 | + const k = (n + h / 30) % 12; | |
| 19 | + return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1)); | |
| 20 | + }; | |
| 21 | + return [f(0), f(8), f(4)]; | |
| 22 | +} | |
| 23 | + | |
| 24 | +// paleta de owners: ángulo áureo para hues bien separados; saturación y | |
| 25 | +// luminosidad ajustables por tema para que casen con su esquema | |
| 26 | +export function ownerColor(i, theme) { | |
| 27 | + const p = theme?.ownerHsl ?? {}; | |
| 28 | + return hsl((i * 137.5 + (p.offset ?? 24)) % 360, p.s ?? 0.85, p.l ?? 0.55); | |
| 29 | +} | |
| 30 | + | |
| 31 | +// agrega por nodo: total de ficheros y recuento por clave (estado u owner) | |
| 32 | +function aggregate(model, keyOf) { | |
| 33 | + const data = new Map(); | |
| 34 | + (function walk(node) { | |
| 35 | + const acc = { counts: new Map(), total: 0 }; | |
| 36 | + for (const fid of node.fileIds) { | |
| 37 | + acc.total++; | |
| 38 | + const k = keyOf(model.files[fid]); | |
| 39 | + if (k != null) acc.counts.set(k, (acc.counts.get(k) ?? 0) + 1); | |
| 40 | + } | |
| 41 | + for (const c of node.children) { | |
| 42 | + const sub = walk(c); | |
| 43 | + acc.total += sub.total; | |
| 44 | + for (const [k, v] of sub.counts) acc.counts.set(k, (acc.counts.get(k) ?? 0) + v); | |
| 45 | + } | |
| 46 | + data.set(node.id, acc); | |
| 47 | + return acc; | |
| 48 | + })(model.city); | |
| 49 | + return data; | |
| 50 | +} | |
| 51 | + | |
| 52 | +function dominantTint(acc, colorOf) { | |
| 53 | + if (!acc || !acc.total || !acc.counts.size) return null; | |
| 54 | + let bestK = null, bestN = 0, mix = [0, 0, 0], n = 0; | |
| 55 | + for (const [k, v] of acc.counts) { | |
| 56 | + if (v > bestN) { bestN = v; bestK = k; } | |
| 57 | + const c = colorOf(k); | |
| 58 | + mix[0] += c[0] * v; mix[1] += c[1] * v; mix[2] += c[2] * v; n += v; | |
| 59 | + } | |
| 60 | + void bestK; | |
| 61 | + return { color: [mix[0] / n, mix[1] / n, mix[2] / n], frac: n / acc.total }; | |
| 62 | +} | |
| 63 | + | |
| 64 | +export function computeMode(model, mode, theme) { | |
| 65 | + const ROLE_COLOR = theme.roleColor; | |
| 66 | + // colores de estado git del tema (caen al estándar si no los define) | |
| 67 | + const gitColor = (st) => theme.gitColors?.[st] ?? GIT_STATUS[st].color; | |
| 68 | + if (mode === 'git' && model.hasGit) { | |
| 69 | + const agg = aggregate(model, f => f.git?.st ?? null); | |
| 70 | + const present = new Set(model.files.map(f => f.git?.st).filter(Boolean)); | |
| 71 | + return { | |
| 72 | + fileColor: (f) => { | |
| 73 | + const st = f.git?.st; | |
| 74 | + return st ? gitColor(st).map(c => c * 0.85) : null; | |
| 75 | + }, | |
| 76 | + nodeColor: (node) => { | |
| 77 | + const t = dominantTint(agg.get(node.id), k => gitColor(k)); | |
| 78 | + if (!t) return null; | |
| 79 | + const base = ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon; | |
| 80 | + return lerp3(base, t.color.map(c => c * 0.55), 0.25 + 0.55 * t.frac); | |
| 81 | + }, | |
| 82 | + legend: [...present].map(st => ({ label: GIT_STATUS[st].label, color: gitColor(st) })), | |
| 83 | + }; | |
| 84 | + } | |
| 85 | + if (mode === 'ownership' && model.owners.length) { | |
| 86 | + const agg = aggregate(model, f => f.owner); | |
| 87 | + const counts = model.owners.map((_, i) => | |
| 88 | + model.files.reduce((a, f) => a + (f.owner === i ? 1 : 0), 0)); | |
| 89 | + return { | |
| 90 | + fileColor: (f) => (f.owner != null ? ownerColor(f.owner, theme).map(c => c * 0.8) : null), | |
| 91 | + nodeColor: (node) => { | |
| 92 | + const t = dominantTint(agg.get(node.id), (i) => ownerColor(i, theme)); | |
| 93 | + if (!t) return null; | |
| 94 | + const base = ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon; | |
| 95 | + return lerp3(base, t.color.map(c => c * 0.5), 0.3 + 0.5 * t.frac); | |
| 96 | + }, | |
| 97 | + legend: model.owners.map((o, i) => ({ | |
| 98 | + label: `${o} · ${counts[i]}`, color: ownerColor(i, theme), | |
| 99 | + })), | |
| 100 | + }; | |
| 101 | + } | |
| 102 | + return { fileColor: null, nodeColor: null, legend: null }; | |
| 103 | +} |
added src/controls.js +144 −0
| @@ -0,0 +1,144 @@ | ||
| 1 | +// Navegación: órbita (modo cursor), vuelo libre sin colisiones (modo | |
| 2 | +// videojuego, atraviesa paredes) y vuelos de cámara con easing. | |
| 3 | +import * as THREE from 'three'; | |
| 4 | +import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; | |
| 5 | + | |
| 6 | +const EASE = t => 1 - Math.pow(1 - t, 3); | |
| 7 | + | |
| 8 | +export function createNavigation(camera, dom, cityBox) { | |
| 9 | + const orbit = new OrbitControls(camera, dom); | |
| 10 | + orbit.enableDamping = true; | |
| 11 | + orbit.dampingFactor = 0.08; | |
| 12 | + orbit.maxPolarAngle = Math.PI * 0.495; | |
| 13 | + | |
| 14 | + const extent = Math.max(cityBox.sx, cityBox.sz); | |
| 15 | + const center = new THREE.Vector3(cityBox.cx, 0, cityBox.cz); | |
| 16 | + | |
| 17 | + // ── vuelos de cámara ──────────────────────────────────────────────── | |
| 18 | + let tween = null; | |
| 19 | + function flyTo(pos, target, ms = 1100) { | |
| 20 | + tween = { | |
| 21 | + t0: performance.now(), ms, | |
| 22 | + p0: camera.position.clone(), p1: pos.clone(), | |
| 23 | + l0: orbit.target.clone(), l1: target.clone(), | |
| 24 | + }; | |
| 25 | + } | |
| 26 | + | |
| 27 | + const VIEWS = { | |
| 28 | + reset: () => flyTo( | |
| 29 | + center.clone().add(new THREE.Vector3(extent * 0.55, extent * 0.42, extent * 0.62)), | |
| 30 | + center.clone(), | |
| 31 | + ), | |
| 32 | + aerial: () => flyTo( | |
| 33 | + center.clone().add(new THREE.Vector3(0.001, extent * 1.25, 0.001)), | |
| 34 | + center.clone(), | |
| 35 | + ), | |
| 36 | + skyline: () => flyTo( | |
| 37 | + center.clone().add(new THREE.Vector3(extent * 0.72, 14, extent * 0.1)), | |
| 38 | + center.clone().setY(12), | |
| 39 | + ), | |
| 40 | + focus: (box, dist = 2.5) => { | |
| 41 | + const target = new THREE.Vector3(box.cx, box.cy, box.cz); | |
| 42 | + const d = Math.max(Math.max(box.sx, box.sy, box.sz) * dist, 14); | |
| 43 | + const dir = camera.position.clone().sub(target); | |
| 44 | + dir.y = 0; | |
| 45 | + if (dir.lengthSq() < 1) dir.set(1, 0, 1); | |
| 46 | + dir.normalize(); | |
| 47 | + const pos = target.clone().addScaledVector(dir, d); | |
| 48 | + pos.y = box.cy + d * 0.45; | |
| 49 | + flyTo(pos, target, 900); | |
| 50 | + }, | |
| 51 | + }; | |
| 52 | + | |
| 53 | + // ── modo vuelo ────────────────────────────────────────────────────── | |
| 54 | + const fly = { | |
| 55 | + active: false, | |
| 56 | + keys: new Set(), | |
| 57 | + vel: new THREE.Vector3(), | |
| 58 | + yaw: 0, pitch: 0, | |
| 59 | + }; | |
| 60 | + | |
| 61 | + function enterFly() { | |
| 62 | + if (fly.active) return; | |
| 63 | + fly.active = true; | |
| 64 | + orbit.enabled = false; | |
| 65 | + tween = null; | |
| 66 | + const e = new THREE.Euler().setFromQuaternion(camera.quaternion, 'YXZ'); | |
| 67 | + fly.yaw = e.y; fly.pitch = e.x; | |
| 68 | + dom.requestPointerLock(); | |
| 69 | + dom.dispatchEvent(new CustomEvent('flymode', { detail: true })); | |
| 70 | + } | |
| 71 | + function exitFly() { | |
| 72 | + if (!fly.active) return; | |
| 73 | + fly.active = false; | |
| 74 | + fly.keys.clear(); | |
| 75 | + orbit.enabled = true; | |
| 76 | + // recoloca el target de la órbita delante de la cámara | |
| 77 | + const fwd = new THREE.Vector3(); | |
| 78 | + camera.getWorldDirection(fwd); | |
| 79 | + orbit.target.copy(camera.position).addScaledVector(fwd, 40); | |
| 80 | + if (document.pointerLockElement === dom) document.exitPointerLock(); | |
| 81 | + dom.dispatchEvent(new CustomEvent('flymode', { detail: false })); | |
| 82 | + } | |
| 83 | + | |
| 84 | + const onLockChange = () => { | |
| 85 | + if (document.pointerLockElement !== dom && fly.active) exitFly(); | |
| 86 | + }; | |
| 87 | + const onMouseMove = (e) => { | |
| 88 | + if (!fly.active) return; | |
| 89 | + fly.yaw -= e.movementX * 0.0022; | |
| 90 | + fly.pitch = Math.max(-1.45, Math.min(1.45, fly.pitch - e.movementY * 0.0022)); | |
| 91 | + }; | |
| 92 | + const onKeyDown = (e) => { | |
| 93 | + if (e.code === 'KeyF' && !e.repeat && document.activeElement?.tagName !== 'INPUT') { | |
| 94 | + fly.active ? exitFly() : enterFly(); | |
| 95 | + } | |
| 96 | + if (fly.active) fly.keys.add(e.code); | |
| 97 | + }; | |
| 98 | + const onKeyUp = (e) => fly.keys.delete(e.code); | |
| 99 | + document.addEventListener('pointerlockchange', onLockChange); | |
| 100 | + document.addEventListener('mousemove', onMouseMove); | |
| 101 | + document.addEventListener('keydown', onKeyDown); | |
| 102 | + document.addEventListener('keyup', onKeyUp); | |
| 103 | + | |
| 104 | + function dispose() { | |
| 105 | + exitFly(); | |
| 106 | + document.removeEventListener('pointerlockchange', onLockChange); | |
| 107 | + document.removeEventListener('mousemove', onMouseMove); | |
| 108 | + document.removeEventListener('keydown', onKeyDown); | |
| 109 | + document.removeEventListener('keyup', onKeyUp); | |
| 110 | + orbit.dispose(); | |
| 111 | + } | |
| 112 | + | |
| 113 | + // ── actualización por frame ───────────────────────────────────────── | |
| 114 | + function update(dt) { | |
| 115 | + if (tween) { | |
| 116 | + const t = Math.min(1, (performance.now() - tween.t0) / tween.ms); | |
| 117 | + const k = EASE(t); | |
| 118 | + camera.position.lerpVectors(tween.p0, tween.p1, k); | |
| 119 | + orbit.target.lerpVectors(tween.l0, tween.l1, k); | |
| 120 | + if (t >= 1) tween = null; | |
| 121 | + } | |
| 122 | + if (fly.active) { | |
| 123 | + camera.quaternion.setFromEuler(new THREE.Euler(fly.pitch, fly.yaw, 0, 'YXZ')); | |
| 124 | + const speed = (fly.keys.has('ShiftLeft') || fly.keys.has('ShiftRight') ? 90 : 28); | |
| 125 | + const dir = new THREE.Vector3(); | |
| 126 | + const fwd = new THREE.Vector3(); | |
| 127 | + camera.getWorldDirection(fwd); | |
| 128 | + const right = new THREE.Vector3().crossVectors(fwd, camera.up).normalize(); | |
| 129 | + if (fly.keys.has('KeyW') || fly.keys.has('ArrowUp')) dir.add(fwd); | |
| 130 | + if (fly.keys.has('KeyS') || fly.keys.has('ArrowDown')) dir.sub(fwd); | |
| 131 | + if (fly.keys.has('KeyD') || fly.keys.has('ArrowRight')) dir.add(right); | |
| 132 | + if (fly.keys.has('KeyA') || fly.keys.has('ArrowLeft')) dir.sub(right); | |
| 133 | + if (fly.keys.has('Space') || fly.keys.has('KeyE')) dir.y += 1; | |
| 134 | + if (fly.keys.has('KeyC') || fly.keys.has('KeyQ') || fly.keys.has('ControlLeft')) dir.y -= 1; | |
| 135 | + if (dir.lengthSq()) dir.normalize().multiplyScalar(speed); | |
| 136 | + fly.vel.lerp(dir, 1 - Math.pow(0.0001, dt)); // aceleración suave | |
| 137 | + camera.position.addScaledVector(fly.vel, dt); | |
| 138 | + } else { | |
| 139 | + orbit.update(); | |
| 140 | + } | |
| 141 | + } | |
| 142 | + | |
| 143 | + return { orbit, fly, update, flyTo, VIEWS, enterFly, exitFly, dispose }; | |
| 144 | +} |
added src/data.js +5 −0
| @@ -0,0 +1,5 @@ | ||
| 1 | +// Generado por scan.mjs — 2026-06-10T20:47:00.496Z — raíz: /home/arb/Workspaces/VibeCodeViewer | |
| 2 | +// dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes, ignorado?] | |
| 3 | +export const REPO_TREE = ["VibeCodeViewer",[[".git",[["branches",[],[]],["hooks",[],[["applypatch-msg.sample",478],["commit-msg.sample",896],["fsmonitor-watchman.sample",4655],["post-update.sample",189],["pre-applypatch.sample",424],["pre-commit.sample",1643],["pre-merge-commit.sample",416],["pre-push.sample",1374],["pre-rebase.sample",4898],["pre-receive.sample",544],["prepare-commit-msg.sample",1492],["push-to-checkout.sample",2783],["update.sample",3650]]],["info",[],[["exclude",240]]],["logs",[["refs",[["heads",[],[["develop",1018]]]],[]]],[["HEAD",1018]]],["refs",[["heads",[],[["develop",41]]],["tags",[],[]]],[]]],[["COMMIT_EDITMSG",575],["config",92],["description",73],["HEAD",24],["index",10583]]],["claude_versions",[],[["index.html",32228]]],["codex_versions",[[".agents",[],[]],[".codex",[],[]],[".git",[],[]],["captures",[],[["render-check-20260607-004754.png",295286]]],["src",[["vendor",[],[["three.module.js",1272972]]]],[["main.js",43969],["styles.css",6161]]]],[["capture.sh",381],["index.html",3196]]],["copilot_versions",[["src",[["controls",[],[["flyControls.js",4182]]],["data",[],[["repoData.js",3397],["repoModel.js",6727]]],["scene",[],[["cityBuilder.js",14900],["sceneSetup.js",6831]]],["ui",[],[["fileTree.js",4574],["search.js",2114],["selection.js",5425],["uiController.js",4661]]],["vendor",[["addons",[["controls",[],[["OrbitControls.js",29868]]],["postprocessing",[],[["EffectComposer.js",4651],["MaskPass.js",2231],["OutputPass.js",2398],["Pass.js",1706],["RenderPass.js",1915],["ShaderPass.js",1576],["UnrealBloomPass.js",12406]]],["shaders",[],[["CopyShader.js",571],["LuminosityHighPassShader.js",1192],["OutputShader.js",1393]]]],[]]],[["three.module.js",1272972]]]],[["main.js",7975],["styles.css",8015]]]],[["index.html",2946],["README.md",5797],["render-aerial.png",795542],["render-default.png",776923],["render-file.png",925289],["render-fourfaces.png",1016117],["render-height.png",750643],["render-level-sliders.png",42484],["scan-repo.mjs",1968]]],["fable_version",[[".cache",[],[["analysis.json",80771,1]]],["captures",[],[["base-solid.png",287552,1],["base-trans.png",287417,1],["blast-main.png",956048,1],["blast-symbols.png",1052717,1],["blast.py",1321],["blast2.py",1286],["bunker-city.png",723781,1],["bunker-close.png",811836,1],["check1.png",902691,1],["check2-search.png",802170,1],["check3-aerial.png",636840,1],["check4-skyline.png",479318,1],["check5-facade.png",624224,1],["check6-drawer.png",811733,1],["closeup.py",1683],["diag-nofiles.png",690792,1],["diag-nolegend.png",567892,1],["diag-nolines.png",597836,1],["diag-noshells.png",578651,1],["diag.py",834],["feat1-legend.png",922231,1],["feat2-suggest.png",943385,1],["feat3-selected.png",911308,1],["feat4-basement.png",414164,1],["feat5-legend-off.png",904733,1],["features.py",1778],["fix-blast-a.png",1031418,1],["fix-blast-b.png",1036523,1],["fix-factorial.png",1077428,1],["fix-factorial2.png",1013748,1],["fix-ground-solid.png",786527,1],["fix-ground-trans.png",850057,1],["fix-legend.png",1047318,1],["fix2.py",1523],["fix3.py",896],["fix4.py",1662],["gittree.py",727],["ground-solid.png",1062471,1],["interact.py",1190],["mode-basic.png",1164673,1],["mode-git-tree.png",1120173,1],["mode-git.png",929703,1],["mode-owners-sel.png",1137784,1],["mode-owners.png",942196,1],["modes.py",1203],["mono-city.png",855634,1],["mono-select.png",912818,1],["mono.py",1361],["msaa-city.png",976437,1],["msaa-close.png",629864,1],["small-after-urb.png",904499,1],["theme-factorial.png",748272,1],["theme-glaciar.png",1084404,1],["theme-hacker.png",1006583,1],["theme-matrix.png",914481,1],["theme-synthwave.png",1048034,1],["themes.py",1558],["tree-keys.png",1152171,1],["tree-sync.png",1199078,1],["urb-district.png",1028871,1],["urb-select.png",977748,1],["urb.py",1346]]],["src",[],[["analysisCache.js",1902],["builder.js",24720],["codeIndex.js",7532],["codeLinks.js",4251],["colorModes.js",3733],["controls.js",5695],["data.js",88315],["fsScan.js",6317],["gitIndex.js",1693],["ignore.js",2069],["main.js",15982],["model.js",14519],["ownership.js",1856],["styles.css",11049],["themes.js",7417],["ui.js",14238]]],["tools",[],[["tree2data.mjs",3075]]],["vendor",[["addons",[["controls",[],[["OrbitControls.js",29868]]],["postprocessing",[],[["EffectComposer.js",4651],["MaskPass.js",2231],["OutputPass.js",2398],["Pass.js",1706],["RenderPass.js",1915],["ShaderPass.js",1576],["UnrealBloomPass.js",12406]]],["shaders",[],[["CopyShader.js",571],["LuminosityHighPassShader.js",1192],["OutputShader.js",1393]]]],[]]],[["three.module.js",1272972]]]],[[".gitignore",55],["code_ownership_files.md",4508],["factorial_tree.txt",15087836,1],["index.html",2441],["README.md",11281],["scan.mjs",7671],["serve.sh",401]]]],[[".gitignore",6],["CODEOWNERS",270],["input.mp4",226193921,1],["output_720p_max.mp4",35964958,1],["output_720p.mp4",30529552,1],["output_cuda.mp4",244777105,1],["output.mp4",203836657,1]]]; | |
| 4 | +// git: { ruta: [estado, +líneas, −líneas] } · owners: [[patrón, @owner], …] | |
| 5 | +export const REPO_META = {"git":{"fable_version/scan.mjs":["M",60,11],"fable_version/src/builder.js":["M",19,5],"fable_version/src/data.js":["M",3,3],"fable_version/src/fsScan.js":["M",42,9],"fable_version/src/main.js":["M",55,20],"fable_version/src/model.js":["M",7,0],"fable_version/src/themes.js":["M",5,5],"fable_version/captures/blast2.py":["U",0,0],"fable_version/src/analysisCache.js":["U",0,0],"fable_version/src/codeIndex.js":["U",0,0]},"owners":[["/claude_versions/","@team/claude"],["/codex_versions/","@team/codex"],["/copilot_versions/","@team/copilot"],["/fable_version/","@team/fable"],["*.md","@team/docs"],["*.png","@team/design"]],"links":{"codex_versions/index.html":["F:codex_versions/src/styles.css","F:codex_versions/src/main.js"],"copilot_versions/index.html":["F:copilot_versions/src/styles.css","F:copilot_versions/src/main.js"],"copilot_versions/src/main.js":["F:copilot_versions/src/scene/sceneSetup.js","F:copilot_versions/src/scene/cityBuilder.js","F:copilot_versions/src/data/repoModel.js","F:copilot_versions/src/data/repoData.js","F:copilot_versions/src/controls/flyControls.js","F:copilot_versions/src/ui/selection.js","F:copilot_versions/src/ui/uiController.js","F:copilot_versions/src/ui/search.js"],"copilot_versions/src/scene/cityBuilder.js":["F:copilot_versions/src/scene/sceneSetup.js"],"copilot_versions/src/scene/sceneSetup.js":["F:copilot_versions/src/vendor/addons/postprocessing/EffectComposer.js","F:copilot_versions/src/vendor/addons/postprocessing/RenderPass.js","F:copilot_versions/src/vendor/addons/postprocessing/UnrealBloomPass.js","F:copilot_versions/src/vendor/addons/postprocessing/OutputPass.js"],"copilot_versions/src/ui/selection.js":["F:copilot_versions/src/scene/cityBuilder.js"],"copilot_versions/src/ui/uiController.js":["F:copilot_versions/src/ui/fileTree.js","F:copilot_versions/src/ui/selection.js"],"copilot_versions/src/vendor/addons/postprocessing/EffectComposer.js":["F:copilot_versions/src/vendor/addons/shaders/CopyShader.js","F:copilot_versions/src/vendor/addons/postprocessing/ShaderPass.js","F:copilot_versions/src/vendor/addons/postprocessing/MaskPass.js"],"copilot_versions/src/vendor/addons/postprocessing/MaskPass.js":["F:copilot_versions/src/vendor/addons/postprocessing/Pass.js"],"copilot_versions/src/vendor/addons/postprocessing/OutputPass.js":["F:copilot_versions/src/vendor/addons/postprocessing/Pass.js","F:copilot_versions/src/vendor/addons/shaders/OutputShader.js"],"copilot_versions/src/vendor/addons/postprocessing/RenderPass.js":["F:copilot_versions/src/vendor/addons/postprocessing/Pass.js"],"copilot_versions/src/vendor/addons/postprocessing/ShaderPass.js":["F:copilot_versions/src/vendor/addons/postprocessing/Pass.js"],"copilot_versions/src/vendor/addons/postprocessing/UnrealBloomPass.js":["F:copilot_versions/src/vendor/addons/postprocessing/Pass.js","F:copilot_versions/src/vendor/addons/shaders/CopyShader.js","F:copilot_versions/src/vendor/addons/shaders/LuminosityHighPassShader.js"],"fable_version/index.html":["F:fable_version/src/styles.css","F:fable_version/src/main.js"],"fable_version/scan.mjs":["F:fable_version/src/ignore.js","F:fable_version/src/ownership.js","F:fable_version/src/codeLinks.js","F:fable_version/src/codeIndex.js"],"fable_version/src/fsScan.js":["F:fable_version/src/ignore.js","F:fable_version/src/ownership.js","F:fable_version/src/gitIndex.js","F:fable_version/src/codeLinks.js","F:fable_version/src/codeIndex.js","F:fable_version/src/analysisCache.js"],"fable_version/src/main.js":["F:fable_version/src/data.js","F:fable_version/src/model.js","F:fable_version/src/colorModes.js","F:fable_version/src/builder.js","F:fable_version/src/controls.js","F:fable_version/src/ui.js","F:fable_version/src/fsScan.js","F:fable_version/src/themes.js"],"fable_version/src/model.js":["F:fable_version/src/ownership.js"],"fable_version/src/ownership.js":["F:fable_version/src/ignore.js"],"fable_version/src/ui.js":["F:fable_version/src/themes.js"],"fable_version/vendor/addons/postprocessing/EffectComposer.js":["F:fable_version/vendor/addons/shaders/CopyShader.js","F:fable_version/vendor/addons/postprocessing/ShaderPass.js","F:fable_version/vendor/addons/postprocessing/MaskPass.js"],"fable_version/vendor/addons/postprocessing/MaskPass.js":["F:fable_version/vendor/addons/postprocessing/Pass.js"],"fable_version/vendor/addons/postprocessing/OutputPass.js":["F:fable_version/vendor/addons/postprocessing/Pass.js","F:fable_version/vendor/addons/shaders/OutputShader.js"],"fable_version/vendor/addons/postprocessing/RenderPass.js":["F:fable_version/vendor/addons/postprocessing/Pass.js"],"fable_version/vendor/addons/postprocessing/ShaderPass.js":["F:fable_version/vendor/addons/postprocessing/Pass.js"],"fable_version/vendor/addons/postprocessing/UnrealBloomPass.js":["F:fable_version/vendor/addons/postprocessing/Pass.js","F:fable_version/vendor/addons/shaders/CopyShader.js","F:fable_version/vendor/addons/shaders/LuminosityHighPassShader.js"]},"codeIndex":{"version":3,"defs":{"copilot_versions/src/controls/flyControls.js":["FlyControls"],"copilot_versions/src/data/repoData.js":["REPO_TREE"],"copilot_versions/src/data/repoModel.js":["generateRepo","indexFiles","prepareCityTree"],"copilot_versions/src/scene/cityBuilder.js":["buildCity","LEVEL_LABELS","LEVEL_INTENSITY","LEVEL_GLOW_PEAK"],"copilot_versions/src/scene/sceneSetup.js":["createScene","createGround","createSprawl","PALETTE"],"copilot_versions/src/ui/fileTree.js":["renderTreeTexture","renderTreeHTML","BuildingFacePlate"],"copilot_versions/src/ui/search.js":["setupSearch"],"copilot_versions/src/ui/selection.js":["buildDensityRows","SelectionManager"],"copilot_versions/src/ui/uiController.js":["UIController"],"copilot_versions/src/vendor/addons/controls/OrbitControls.js":["OrbitControls"],"copilot_versions/src/vendor/addons/postprocessing/EffectComposer.js":["EffectComposer"],"copilot_versions/src/vendor/addons/postprocessing/MaskPass.js":["MaskPass","ClearMaskPass"],"copilot_versions/src/vendor/addons/postprocessing/OutputPass.js":["OutputPass"],"copilot_versions/src/vendor/addons/postprocessing/Pass.js":["Pass","FullScreenQuad"],"copilot_versions/src/vendor/addons/postprocessing/RenderPass.js":["RenderPass"],"copilot_versions/src/vendor/addons/postprocessing/ShaderPass.js":["ShaderPass"],"copilot_versions/src/vendor/addons/postprocessing/UnrealBloomPass.js":["UnrealBloomPass"],"copilot_versions/src/vendor/addons/shaders/CopyShader.js":["CopyShader"],"copilot_versions/src/vendor/addons/shaders/LuminosityHighPassShader.js":["LuminosityHighPassShader"],"copilot_versions/src/vendor/addons/shaders/OutputShader.js":["OutputShader"],"fable_version/src/analysisCache.js":["loadAnalysisCache","saveAnalysisCache"],"fable_version/src/builder.js":["buildCity"],"fable_version/src/codeIndex.js":["stripCommentsAndStrings","isIndexable","extractDefs","extractTokens","buildSymbolLinks","INDEX_VERSION"],"fable_version/src/codeLinks.js":["isAnalyzable","extractRefs","resolveAll","MAX_SRC_BYTES"],"fable_version/src/colorModes.js":["ownerColor","computeMode","GIT_STATUS"],"fable_version/src/controls.js":["createNavigation"],"fable_version/src/data.js":["REPO_TREE","REPO_META"],"fable_version/src/fsScan.js":["canPickFolder","pickAndScanFolder"],"fable_version/src/gitIndex.js":["parseGitIndex","gitStatusOf"],"fable_version/src/ignore.js":["globToRegex","IgnoreStack","IGNORE_FILES"],"fable_version/src/model.js":["buildModel","ROLES"],"fable_version/src/ownership.js":["isCodeownersFile","isPackageMeta","parseCodeowners","parsePackageMeta","makeOwnerResolver"],"fable_version/src/themes.js":["THEMES"],"fable_version/src/ui.js":["createUI"],"fable_version/vendor/addons/controls/OrbitControls.js":["OrbitControls"],"fable_version/vendor/addons/postprocessing/EffectComposer.js":["EffectComposer"],"fable_version/vendor/addons/postprocessing/MaskPass.js":["MaskPass","ClearMaskPass"],"fable_version/vendor/addons/postprocessing/OutputPass.js":["OutputPass"],"fable_version/vendor/addons/postprocessing/Pass.js":["Pass","FullScreenQuad"],"fable_version/vendor/addons/postprocessing/RenderPass.js":["RenderPass"],"fable_version/vendor/addons/postprocessing/ShaderPass.js":["ShaderPass"],"fable_version/vendor/addons/postprocessing/UnrealBloomPass.js":["UnrealBloomPass"],"fable_version/vendor/addons/shaders/CopyShader.js":["CopyShader"],"fable_version/vendor/addons/shaders/LuminosityHighPassShader.js":["LuminosityHighPassShader"],"fable_version/vendor/addons/shaders/OutputShader.js":["OutputShader"]},"symLinks":{"codex_versions/src/main.js":[["copilot_versions/src/scene/cityBuilder.js","buildCity"],["fable_version/src/builder.js","buildCity"]],"copilot_versions/src/data/repoData.js":[["fable_version/src/data.js","REPO_TREE"]],"copilot_versions/src/main.js":[["copilot_versions/src/scene/sceneSetup.js","createScene"],["copilot_versions/src/scene/sceneSetup.js","createGround"],["copilot_versions/src/scene/sceneSetup.js","createSprawl"],["copilot_versions/src/data/repoModel.js","prepareCityTree"],["copilot_versions/src/controls/flyControls.js","FlyControls"],["copilot_versions/src/ui/selection.js","SelectionManager"],["copilot_versions/src/ui/uiController.js","UIController"],["copilot_versions/src/ui/search.js","setupSearch"],["copilot_versions/src/scene/cityBuilder.js","buildCity"],["fable_version/src/builder.js","buildCity"],["copilot_versions/src/data/repoData.js","REPO_TREE"],["fable_version/src/data.js","REPO_TREE"]],"copilot_versions/src/scene/cityBuilder.js":[["copilot_versions/src/scene/sceneSetup.js","PALETTE"],["fable_version/src/builder.js","buildCity"]],"copilot_versions/src/scene/sceneSetup.js":[["copilot_versions/src/vendor/addons/postprocessing/EffectComposer.js","EffectComposer"],["fable_version/vendor/addons/postprocessing/EffectComposer.js","EffectComposer"],["copilot_versions/src/vendor/addons/postprocessing/RenderPass.js","RenderPass"],["fable_version/vendor/addons/postprocessing/RenderPass.js","RenderPass"],["copilot_versions/src/vendor/addons/postprocessing/UnrealBloomPass.js","UnrealBloomPass"],["fable_version/vendor/addons/postprocessing/UnrealBloomPass.js","UnrealBloomPass"],["copilot_versions/src/vendor/addons/postprocessing/OutputPass.js","OutputPass"],["fable_version/vendor/addons/postprocessing/OutputPass.js","OutputPass"]],"copilot_versions/src/ui/selection.js":[["copilot_versions/src/scene/cityBuilder.js","LEVEL_INTENSITY"],["copilot_versions/src/scene/cityBuilder.js","LEVEL_LABELS"]],"copilot_versions/src/ui/uiController.js":[["copilot_versions/src/ui/fileTree.js","BuildingFacePlate"],["copilot_versions/src/ui/fileTree.js","renderTreeHTML"],["copilot_versions/src/ui/selection.js","buildDensityRows"]],"copilot_versions/src/vendor/addons/controls/OrbitControls.js":[["fable_version/vendor/addons/controls/OrbitControls.js","OrbitControls"]],"copilot_versions/src/vendor/addons/postprocessing/EffectComposer.js":[["copilot_versions/src/vendor/addons/shaders/CopyShader.js","CopyShader"],["fable_version/vendor/addons/shaders/CopyShader.js","CopyShader"],["copilot_versions/src/vendor/addons/postprocessing/ShaderPass.js","ShaderPass"],["fable_version/vendor/addons/postprocessing/ShaderPass.js","ShaderPass"],["copilot_versions/src/vendor/addons/postprocessing/MaskPass.js","MaskPass"],["fable_version/vendor/addons/postprocessing/MaskPass.js","MaskPass"],["copilot_versions/src/vendor/addons/postprocessing/MaskPass.js","ClearMaskPass"],["fable_version/vendor/addons/postprocessing/MaskPass.js","ClearMaskPass"],["fable_version/vendor/addons/postprocessing/EffectComposer.js","EffectComposer"]],"copilot_versions/src/vendor/addons/postprocessing/MaskPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/MaskPass.js","MaskPass"],["fable_version/vendor/addons/postprocessing/MaskPass.js","ClearMaskPass"]],"copilot_versions/src/vendor/addons/postprocessing/OutputPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["fable_version/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["copilot_versions/src/vendor/addons/shaders/OutputShader.js","OutputShader"],["fable_version/vendor/addons/shaders/OutputShader.js","OutputShader"],["fable_version/vendor/addons/postprocessing/OutputPass.js","OutputPass"]],"copilot_versions/src/vendor/addons/postprocessing/Pass.js":[["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","FullScreenQuad"]],"copilot_versions/src/vendor/addons/postprocessing/RenderPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/RenderPass.js","RenderPass"]],"copilot_versions/src/vendor/addons/postprocessing/ShaderPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["fable_version/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["fable_version/vendor/addons/postprocessing/ShaderPass.js","ShaderPass"]],"copilot_versions/src/vendor/addons/postprocessing/UnrealBloomPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["fable_version/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["copilot_versions/src/vendor/addons/shaders/CopyShader.js","CopyShader"],["fable_version/vendor/addons/shaders/CopyShader.js","CopyShader"],["copilot_versions/src/vendor/addons/shaders/LuminosityHighPassShader.js","LuminosityHighPassShader"],["fable_version/vendor/addons/shaders/LuminosityHighPassShader.js","LuminosityHighPassShader"],["fable_version/vendor/addons/postprocessing/UnrealBloomPass.js","UnrealBloomPass"]],"copilot_versions/src/vendor/addons/shaders/CopyShader.js":[["fable_version/vendor/addons/shaders/CopyShader.js","CopyShader"]],"copilot_versions/src/vendor/addons/shaders/LuminosityHighPassShader.js":[["fable_version/vendor/addons/shaders/LuminosityHighPassShader.js","LuminosityHighPassShader"]],"copilot_versions/src/vendor/addons/shaders/OutputShader.js":[["fable_version/vendor/addons/shaders/OutputShader.js","OutputShader"]],"fable_version/scan.mjs":[["fable_version/src/ignore.js","IgnoreStack"],["fable_version/src/ignore.js","IGNORE_FILES"],["fable_version/src/ownership.js","isCodeownersFile"],["fable_version/src/ownership.js","isPackageMeta"],["fable_version/src/ownership.js","parseCodeowners"],["fable_version/src/ownership.js","parsePackageMeta"],["fable_version/src/codeLinks.js","isAnalyzable"],["fable_version/src/codeLinks.js","extractRefs"],["fable_version/src/codeLinks.js","resolveAll"],["fable_version/src/codeIndex.js","stripCommentsAndStrings"],["fable_version/src/codeIndex.js","extractDefs"],["fable_version/src/codeIndex.js","extractTokens"],["fable_version/src/codeIndex.js","buildSymbolLinks"],["fable_version/src/codeIndex.js","isIndexable"],["fable_version/src/codeIndex.js","INDEX_VERSION"]],"fable_version/src/builder.js":[["copilot_versions/src/scene/cityBuilder.js","buildCity"]],"fable_version/src/controls.js":[["copilot_versions/src/vendor/addons/controls/OrbitControls.js","OrbitControls"],["fable_version/vendor/addons/controls/OrbitControls.js","OrbitControls"]],"fable_version/src/data.js":[["copilot_versions/src/data/repoData.js","REPO_TREE"]],"fable_version/src/fsScan.js":[["fable_version/src/ignore.js","IgnoreStack"],["fable_version/src/ignore.js","IGNORE_FILES"],["fable_version/src/ownership.js","isCodeownersFile"],["fable_version/src/ownership.js","isPackageMeta"],["fable_version/src/ownership.js","parseCodeowners"],["fable_version/src/ownership.js","parsePackageMeta"],["fable_version/src/gitIndex.js","parseGitIndex"],["fable_version/src/gitIndex.js","gitStatusOf"],["fable_version/src/codeLinks.js","isAnalyzable"],["fable_version/src/codeLinks.js","extractRefs"],["fable_version/src/codeLinks.js","resolveAll"],["fable_version/src/codeIndex.js","stripCommentsAndStrings"],["fable_version/src/codeIndex.js","extractDefs"],["fable_version/src/codeIndex.js","extractTokens"],["fable_version/src/codeIndex.js","buildSymbolLinks"],["fable_version/src/codeIndex.js","isIndexable"],["fable_version/src/codeIndex.js","INDEX_VERSION"],["fable_version/src/analysisCache.js","loadAnalysisCache"],["fable_version/src/analysisCache.js","saveAnalysisCache"]],"fable_version/src/main.js":[["fable_version/src/data.js","REPO_META"],["fable_version/src/model.js","buildModel"],["fable_version/src/colorModes.js","computeMode"],["fable_version/src/controls.js","createNavigation"],["fable_version/src/ui.js","createUI"],["fable_version/src/fsScan.js","canPickFolder"],["fable_version/src/fsScan.js","pickAndScanFolder"],["fable_version/src/themes.js","THEMES"],["copilot_versions/src/vendor/addons/postprocessing/EffectComposer.js","EffectComposer"],["fable_version/vendor/addons/postprocessing/EffectComposer.js","EffectComposer"],["copilot_versions/src/vendor/addons/postprocessing/RenderPass.js","RenderPass"],["fable_version/vendor/addons/postprocessing/RenderPass.js","RenderPass"],["copilot_versions/src/vendor/addons/postprocessing/UnrealBloomPass.js","UnrealBloomPass"],["fable_version/vendor/addons/postprocessing/UnrealBloomPass.js","UnrealBloomPass"],["copilot_versions/src/vendor/addons/postprocessing/OutputPass.js","OutputPass"],["fable_version/vendor/addons/postprocessing/OutputPass.js","OutputPass"],["copilot_versions/src/data/repoData.js","REPO_TREE"],["fable_version/src/data.js","REPO_TREE"],["copilot_versions/src/scene/cityBuilder.js","buildCity"],["fable_version/src/builder.js","buildCity"]],"fable_version/src/model.js":[["fable_version/src/ownership.js","makeOwnerResolver"]],"fable_version/src/ownership.js":[["fable_version/src/ignore.js","globToRegex"]],"fable_version/src/ui.js":[["fable_version/src/themes.js","THEMES"]],"fable_version/vendor/addons/controls/OrbitControls.js":[["copilot_versions/src/vendor/addons/controls/OrbitControls.js","OrbitControls"]],"fable_version/vendor/addons/postprocessing/EffectComposer.js":[["copilot_versions/src/vendor/addons/shaders/CopyShader.js","CopyShader"],["fable_version/vendor/addons/shaders/CopyShader.js","CopyShader"],["copilot_versions/src/vendor/addons/postprocessing/ShaderPass.js","ShaderPass"],["fable_version/vendor/addons/postprocessing/ShaderPass.js","ShaderPass"],["copilot_versions/src/vendor/addons/postprocessing/MaskPass.js","MaskPass"],["fable_version/vendor/addons/postprocessing/MaskPass.js","MaskPass"],["copilot_versions/src/vendor/addons/postprocessing/MaskPass.js","ClearMaskPass"],["fable_version/vendor/addons/postprocessing/MaskPass.js","ClearMaskPass"],["copilot_versions/src/vendor/addons/postprocessing/EffectComposer.js","EffectComposer"]],"fable_version/vendor/addons/postprocessing/MaskPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/MaskPass.js","MaskPass"],["copilot_versions/src/vendor/addons/postprocessing/MaskPass.js","ClearMaskPass"]],"fable_version/vendor/addons/postprocessing/OutputPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["fable_version/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["copilot_versions/src/vendor/addons/shaders/OutputShader.js","OutputShader"],["fable_version/vendor/addons/shaders/OutputShader.js","OutputShader"],["copilot_versions/src/vendor/addons/postprocessing/OutputPass.js","OutputPass"]],"fable_version/vendor/addons/postprocessing/Pass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/Pass.js","FullScreenQuad"]],"fable_version/vendor/addons/postprocessing/RenderPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/RenderPass.js","RenderPass"]],"fable_version/vendor/addons/postprocessing/ShaderPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["fable_version/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["copilot_versions/src/vendor/addons/postprocessing/ShaderPass.js","ShaderPass"]],"fable_version/vendor/addons/postprocessing/UnrealBloomPass.js":[["copilot_versions/src/vendor/addons/postprocessing/Pass.js","Pass"],["fable_version/vendor/addons/postprocessing/Pass.js","Pass"],["copilot_versions/src/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["fable_version/vendor/addons/postprocessing/Pass.js","FullScreenQuad"],["copilot_versions/src/vendor/addons/shaders/CopyShader.js","CopyShader"],["fable_version/vendor/addons/shaders/CopyShader.js","CopyShader"],["copilot_versions/src/vendor/addons/shaders/LuminosityHighPassShader.js","LuminosityHighPassShader"],["fable_version/vendor/addons/shaders/LuminosityHighPassShader.js","LuminosityHighPassShader"],["copilot_versions/src/vendor/addons/postprocessing/UnrealBloomPass.js","UnrealBloomPass"]],"fable_version/vendor/addons/shaders/CopyShader.js":[["copilot_versions/src/vendor/addons/shaders/CopyShader.js","CopyShader"]],"fable_version/vendor/addons/shaders/LuminosityHighPassShader.js":[["copilot_versions/src/vendor/addons/shaders/LuminosityHighPassShader.js","LuminosityHighPassShader"]],"fable_version/vendor/addons/shaders/OutputShader.js":[["copilot_versions/src/vendor/addons/shaders/OutputShader.js","OutputShader"]]}}}; |
added src/filePriority.js +48 −0
| @@ -0,0 +1,48 @@ | ||
| 1 | +// Prioridad de análisis para repos enormes: el presupuesto de lectura del | |
| 2 | +// modo Blast se gasta primero en los ficheros más "clave" del repositorio, | |
| 3 | +// en lugar de en el orden alfabético del paseo por el árbol. | |
| 4 | +// | |
| 5 | +// Heurística barata (solo ruta, nombre y tamaño, sin leer contenido): | |
| 6 | +// + poca profundidad (lo cercano a la raíz define el proyecto) | |
| 7 | +// + directorios de fuente: src, lib, app, core, packages… | |
| 8 | +// + puntos de entrada: index.*, main.*, __init__.py, lib.rs… | |
| 9 | +// − tests, fixtures, ejemplos, docs, vendored, build/dist, generados | |
| 10 | +// − minificados, lockfiles, sourcemaps y ficheros gigantes (suelen ser generados) | |
| 11 | + | |
| 12 | +const SOURCE_DIRS = new Set([ | |
| 13 | + 'src', 'lib', 'app', 'apps', 'core', 'source', 'internal', 'pkg', | |
| 14 | + 'packages', 'modules', 'services', 'components', 'server', 'client', | |
| 15 | +]); | |
| 16 | +const PENALTY_DIRS = new Set([ | |
| 17 | + 'test', 'tests', '__tests__', 'spec', 'specs', 'testing', 'testdata', | |
| 18 | + 'fixtures', 'fixture', 'mocks', '__mocks__', 'snapshots', '__snapshots__', | |
| 19 | + 'examples', 'example', 'samples', 'demo', 'demos', 'docs', 'doc', | |
| 20 | + 'vendor', 'vendored', 'third_party', 'thirdparty', 'external', 'deps', | |
| 21 | + 'dist', 'build', 'out', 'output', 'target', 'generated', 'gen', | |
| 22 | + 'migrations', 'benchmarks', 'bench', 'scripts', 'tools', | |
| 23 | +]); | |
| 24 | +const ENTRY_EXACT = new Set([ | |
| 25 | + '__init__.py', 'mod.rs', 'lib.rs', 'main.go', 'manage.py', 'conftest.py', | |
| 26 | +]); | |
| 27 | +const ENTRY_RE = /^(index|main|app|server|cli|api|router|routes|core|setup)\.[^.]+$/i; | |
| 28 | +const TEST_NAME_RE = /(\.(test|spec)\.[^.]+|_test\.[^.]+|Test\.[^.]+)$/; | |
| 29 | +const GENERATED_RE = /(\.min\.|\.bundle\.|\.d\.ts$|\.map$|\.lock$|\.snap$|_pb2?\.|\.generated\.)/; | |
| 30 | + | |
| 31 | +export function priorityScore(rel, name, size) { | |
| 32 | + const parts = rel.split('/'); | |
| 33 | + let s = 100 - Math.min(parts.length - 1, 12) * 6; | |
| 34 | + for (let i = 0; i < parts.length - 1; i++) { | |
| 35 | + const dir = parts[i].toLowerCase(); | |
| 36 | + if (SOURCE_DIRS.has(dir)) s += 14; | |
| 37 | + if (PENALTY_DIRS.has(dir)) s -= 40; | |
| 38 | + if (dir.startsWith('.')) s -= 25; | |
| 39 | + } | |
| 40 | + const low = name.toLowerCase(); | |
| 41 | + if (ENTRY_EXACT.has(low) || ENTRY_RE.test(name)) s += 25; | |
| 42 | + if (TEST_NAME_RE.test(name)) s -= 35; | |
| 43 | + if (GENERATED_RE.test(low)) s -= 60; | |
| 44 | + if (size > 512 * 1024) s -= 20; | |
| 45 | + else if (size > 128 * 1024) s -= 8; | |
| 46 | + else if (size < 64) s -= 10; | |
| 47 | + return s; | |
| 48 | +} |
added src/fsScan.js +284 −0
| @@ -0,0 +1,284 @@ | ||
| 1 | +// Escáner en navegador con la File System Access API (Chrome/Edge). | |
| 2 | +// Produce el mismo formato compacto que scan.mjs: | |
| 3 | +// dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes, ignorado?] | |
| 4 | +// | |
| 5 | +// El escaneo del árbol es completo y sin límite; el análisis de contenidos | |
| 6 | +// (modo Blast) se devuelve como `runAnalysis`, una pasada perezosa por lotes | |
| 7 | +// que se ejecuta con la ciudad ya cargada, prioriza los ficheros clave y | |
| 8 | +// persiste cada lote, de modo que una ejecución interrumpida continúa donde | |
| 9 | +// se quedó. | |
| 10 | +import { IgnoreStack, IGNORE_FILES } from './ignore.js'; | |
| 11 | +import { isCodeownersFile, isPackageMeta, parseCodeowners, parsePackageMeta } from './ownership.js'; | |
| 12 | +import { parseGitIndex, gitStatusOf, readHeadCommit } from './gitIndex.js'; | |
| 13 | +import { isAnalyzable, extractRefs, resolveAll } from './codeLinks.js'; | |
| 14 | +import { stripCommentsAndStrings, extractDefs, extractTokens, buildSymbolLinks, isIndexable, INDEX_VERSION } from './codeIndex.js'; | |
| 15 | +import { | |
| 16 | + loadAnalysisCache, saveAnalysisCache, | |
| 17 | + loadSnapshot, latestSnapshot, saveSnapshotChunk, pruneSnapshots, | |
| 18 | + loadSavedHandle, saveHandle, | |
| 19 | +} from './analysisCache.js'; | |
| 20 | +import { priorityScore } from './filePriority.js'; | |
| 21 | + | |
| 22 | +const SKIP = new Set(['node_modules', '.DS_Store']); | |
| 23 | +// presupuesto del análisis de código (modo Blast): solo la lectura de | |
| 24 | +// contenidos tiene tope, y se gasta por orden de prioridad | |
| 25 | +const ANALYZE_MAX_FILES = 20000; | |
| 26 | +const ANALYZE_MAX_BYTES = 48 * 1024 * 1024; | |
| 27 | +// tamaño de lote: tras cada lote se escribe un checkpoint (caché de ficheros | |
| 28 | +// + chunk de snapshot del commit), de modo que un análisis interrumpido | |
| 29 | +// continúa desde el último punto de control | |
| 30 | +const BATCH_FILES = 1500; | |
| 31 | +const BATCH_BYTES = 8 * 1024 * 1024; | |
| 32 | +// el refresco de enlaces (resolveAll + buildSymbolLinks sobre lo acumulado) | |
| 33 | +// es caro y síncrono: se hace cada REFRESH_FILES analizados, no por lote | |
| 34 | +const REFRESH_FILES = 6000; | |
| 35 | +// cesión periódica del hilo dentro del lote para no congelar el render | |
| 36 | +const YIELD_EVERY = 100; | |
| 37 | + | |
| 38 | +export function canPickFolder() { | |
| 39 | + return typeof window.showDirectoryPicker === 'function'; | |
| 40 | +} | |
| 41 | + | |
| 42 | +// pide el permiso de lectura dentro del gesto de usuario: en carpetas grandes | |
| 43 | +// el primer acceso diferido retrasaba el prompt varios segundos | |
| 44 | +async function ensureReadPermission(handle) { | |
| 45 | + if (await handle.queryPermission?.({ mode: 'read' }) === 'granted') return true; | |
| 46 | + return (await handle.requestPermission?.({ mode: 'read' })) === 'granted'; | |
| 47 | +} | |
| 48 | + | |
| 49 | +export async function pickAndScanFolder(onProgress) { | |
| 50 | + const handle = await window.showDirectoryPicker(); | |
| 51 | + if (!await ensureReadPermission(handle)) throw Object.assign(new Error('permiso denegado'), { name: 'AbortError' }); | |
| 52 | + saveHandle(handle); // para poder reabrir sin picker la próxima vez | |
| 53 | + return scanHandle(handle, onProgress); | |
| 54 | +} | |
| 55 | + | |
| 56 | +// nombre de la última carpeta abierta (o null), para el botón "Reabrir" | |
| 57 | +export async function savedFolderName() { | |
| 58 | + const h = await loadSavedHandle(); | |
| 59 | + return h?.name ?? null; | |
| 60 | +} | |
| 61 | + | |
| 62 | +export async function reopenLastFolder(onProgress) { | |
| 63 | + const handle = await loadSavedHandle(); | |
| 64 | + if (!handle) return null; | |
| 65 | + if (!await ensureReadPermission(handle)) return null; | |
| 66 | + return scanHandle(handle, onProgress); | |
| 67 | +} | |
| 68 | + | |
| 69 | +async function scanHandle(handle, onProgress) { | |
| 70 | + let count = 0; | |
| 71 | + const stack = new IgnoreStack(); | |
| 72 | + const ownerRules = []; | |
| 73 | + const refsMap = {}, fileRels = [], dirRels = []; | |
| 74 | + const defsMap = {}, tokensMap = {}; | |
| 75 | + // candidatos a análisis: se recogen durante el paseo y se leen después, | |
| 76 | + // por lotes y ordenados por prioridad (ver filePriority.js) | |
| 77 | + const candidates = []; | |
| 78 | + // rel → { size, entry } pendiente de consolidar en el snapshot del commit; | |
| 79 | + // se vacía en cada checkpoint (cada chunk escribe solo el delta) | |
| 80 | + let pendingUsed = {}; | |
| 81 | + // la caché se carga en paralelo con el índice git y el commit de HEAD | |
| 82 | + const cachePromise = loadAnalysisCache(); | |
| 83 | + const newCacheEntries = new Map(); | |
| 84 | + let cacheHits = 0, snapHits = 0; | |
| 85 | + | |
| 86 | + // estado git aproximado: parsea .git/index (sin binario git en el navegador) | |
| 87 | + let gitIndex = null, headCommit = null; | |
| 88 | + try { | |
| 89 | + const gh = await handle.getDirectoryHandle('.git'); | |
| 90 | + const fh = await gh.getFileHandle('index'); | |
| 91 | + gitIndex = parseGitIndex(await (await fh.getFile()).arrayBuffer()); | |
| 92 | + headCommit = await readHeadCommit(gh); | |
| 93 | + } catch { /* sin .git */ } | |
| 94 | + const gitMap = gitIndex ? {} : null; | |
| 95 | + | |
| 96 | + // capas de reutilización: caché por mtime + snapshots por commit. El | |
| 97 | + // snapshot del commit actual vale tal cual (aunque el mtime haya cambiado | |
| 98 | + // por un checkout o re-clone); el de otro commit solo para ficheros | |
| 99 | + // trackeados cuyo tamaño coincide con el índice git. | |
| 100 | + const analysisCache = await cachePromise; | |
| 101 | + const snap = headCommit ? await loadSnapshot(headCommit) : null; | |
| 102 | + const donor = gitIndex ? await latestSnapshot(headCommit) : null; | |
| 103 | + | |
| 104 | + function applyEntry(rel, size, entry, consolidate = true) { | |
| 105 | + if (entry.specs?.length) refsMap[rel] = entry.specs; | |
| 106 | + if (entry.defs?.length) defsMap[rel] = entry.defs; | |
| 107 | + if (entry.tokens?.length) tokensMap[rel] = entry.tokens; | |
| 108 | + // lo que ya vive en el snapshot del commit actual no se reescribe | |
| 109 | + if (consolidate) pendingUsed[rel] = { size, entry }; | |
| 110 | + } | |
| 111 | + | |
| 112 | + function snapshotEntry(rel, size) { | |
| 113 | + const s = snap?.files[rel]; | |
| 114 | + if (s && s.size === size) return { entry: s.entry, fromCurrent: true }; | |
| 115 | + const d = donor?.files[rel]; | |
| 116 | + if (d && d.size === size && gitIndex?.get(rel)?.size === size) { | |
| 117 | + return { entry: d.entry, fromCurrent: false }; | |
| 118 | + } | |
| 119 | + return null; | |
| 120 | + } | |
| 121 | + | |
| 122 | + async function walk(h, rel, forced) { | |
| 123 | + const dirs = [], files = []; | |
| 124 | + for await (const e of h.values()) { | |
| 125 | + (e.kind === 'directory' ? dirs : files).push(e); | |
| 126 | + } | |
| 127 | + dirs.sort((a, b) => a.name.localeCompare(b.name)); | |
| 128 | + files.sort((a, b) => a.name.localeCompare(b.name)); | |
| 129 | + | |
| 130 | + let pushed = 0; | |
| 131 | + for (const f of files) { | |
| 132 | + const isIgn = IGNORE_FILES.includes(f.name); | |
| 133 | + const isOwn = !rel.includes('.git') && (isCodeownersFile(f.name) || isPackageMeta(f.name)); | |
| 134 | + if (!isIgn && !isOwn) continue; | |
| 135 | + try { | |
| 136 | + const txt = await (await f.getFile()).text(); | |
| 137 | + if (isIgn) { stack.push(rel, txt.split('\n')); pushed++; } | |
| 138 | + if (isOwn) { | |
| 139 | + if (isCodeownersFile(f.name)) ownerRules.push(...parseCodeowners(txt)); | |
| 140 | + else { | |
| 141 | + const rule = parsePackageMeta(txt, rel); | |
| 142 | + if (rule) ownerRules.push(rule); | |
| 143 | + } | |
| 144 | + } | |
| 145 | + } catch { /* ignorar */ } | |
| 146 | + } | |
| 147 | + | |
| 148 | + const outFiles = [], outDirs = []; | |
| 149 | + for (const f of files) { | |
| 150 | + const childRel = rel ? `${rel}/${f.name}` : f.name; | |
| 151 | + let file = null, size = 0; | |
| 152 | + try { file = await f.getFile(); size = file.size; } catch { /* ignorar */ } | |
| 153 | + const ign = forced || stack.ignored(childRel, false); | |
| 154 | + outFiles.push(ign ? [f.name, size, 1] : [f.name, size]); | |
| 155 | + fileRels.push(childRel); | |
| 156 | + count++; | |
| 157 | + if (count % 200 === 0) onProgress?.(`${count} ficheros`); | |
| 158 | + if (!file || childRel.startsWith('.git/')) continue; | |
| 159 | + // estado git aproximado (limpio → sin entrada) | |
| 160 | + if (gitMap && !ign) { | |
| 161 | + const st = gitStatusOf(gitIndex, childRel, size, file.lastModified); | |
| 162 | + if (st) gitMap[childRel] = [st, 0, 0]; | |
| 163 | + } | |
| 164 | + // relaciones de código + índice de símbolos (con caché y presupuesto) | |
| 165 | + const wantRefs = isAnalyzable(f.name, size); | |
| 166 | + const wantIndex = isIndexable(f.name, size); | |
| 167 | + if (wantRefs || wantIndex) { | |
| 168 | + const key = `v${INDEX_VERSION}|${childRel}|${size}|${file.lastModified}`; | |
| 169 | + const hit = analysisCache.get(key); | |
| 170 | + const se = hit ? { entry: hit, fromCurrent: false } : snapshotEntry(childRel, size); | |
| 171 | + if (se) { | |
| 172 | + hit ? cacheHits++ : snapHits++; | |
| 173 | + // lo recuperado del snapshot se reescribe con la clave mtime actual | |
| 174 | + // para que el próximo escaneo acierte por la vía rápida | |
| 175 | + newCacheEntries.set(key, se.entry); | |
| 176 | + applyEntry(childRel, size, se.entry, !se.fromCurrent); | |
| 177 | + } else { | |
| 178 | + candidates.push({ | |
| 179 | + file, key, rel: childRel, name: f.name, size, wantRefs, wantIndex, | |
| 180 | + score: priorityScore(childRel, f.name, size), | |
| 181 | + }); | |
| 182 | + } | |
| 183 | + } | |
| 184 | + } | |
| 185 | + for (const d of dirs) { | |
| 186 | + if (SKIP.has(d.name)) continue; | |
| 187 | + const childRel = rel ? `${rel}/${d.name}` : d.name; | |
| 188 | + if (childRel === '.git/objects') continue; // ruido binario sin interés | |
| 189 | + const ign = forced || stack.ignored(childRel, true); | |
| 190 | + dirRels.push(childRel); | |
| 191 | + outDirs.push(await walk(d, childRel, ign)); | |
| 192 | + } | |
| 193 | + while (pushed--) stack.pop(); | |
| 194 | + return [h.name, outDirs, outFiles]; | |
| 195 | + } | |
| 196 | + | |
| 197 | + const tree = await walk(handle, '', false); | |
| 198 | + // lo recuperado de caché/snapshot se persiste ya: el primer meta queda | |
| 199 | + // consolidado aunque el análisis perezoso no llegue a ejecutarse | |
| 200 | + await saveAnalysisCache(newCacheEntries); | |
| 201 | + newCacheEntries.clear(); | |
| 202 | + // la caché en memoria ya no se consulta más: liberarla antes del análisis | |
| 203 | + // (en repos grandes puede ocupar cientos de MB) | |
| 204 | + analysisCache.clear(); | |
| 205 | + console.info(`[fsScan] ${count} ficheros · caché: ${cacheHits} hits, snapshot: ${snapHits} · pendientes de análisis: ${candidates.length}`); | |
| 206 | + | |
| 207 | + const buildMeta = () => ({ | |
| 208 | + links: resolveAll(refsMap, fileRels, dirRels), | |
| 209 | + codeIndex: { version: INDEX_VERSION, defs: defsMap, symLinks: buildSymbolLinks(defsMap, tokensMap) }, | |
| 210 | + }); | |
| 211 | + | |
| 212 | + // ── análisis perezoso por lotes (se lanza con la ciudad ya cargada) ────── | |
| 213 | + candidates.sort((a, b) => b.score - a.score); | |
| 214 | + const total = Math.min(candidates.length, ANALYZE_MAX_FILES); | |
| 215 | + | |
| 216 | + async function runAnalysis({ onBatch, onProgress: onTick, isCancelled } = {}) { | |
| 217 | + let analyzed = 0, analyzedBytes = 0, batchBytes = 0; | |
| 218 | + let checkpoints = 0, lastRefresh = 0; | |
| 219 | + | |
| 220 | + // checkpoint: persiste la caché del lote y el chunk de snapshot (delta); | |
| 221 | + // si la pestaña muere aquí en adelante, la próxima ejecución parte de esto | |
| 222 | + async function checkpoint() { | |
| 223 | + await saveAnalysisCache(newCacheEntries); | |
| 224 | + newCacheEntries.clear(); | |
| 225 | + if (headCommit) await saveSnapshotChunk(headCommit, pendingUsed); | |
| 226 | + pendingUsed = {}; | |
| 227 | + batchBytes = 0; | |
| 228 | + checkpoints++; | |
| 229 | + onTick?.(`análisis ${analyzed}/${total} · checkpoint ${checkpoints}`); | |
| 230 | + } | |
| 231 | + | |
| 232 | + for (const c of candidates) { | |
| 233 | + if (analyzed >= ANALYZE_MAX_FILES || analyzedBytes >= ANALYZE_MAX_BYTES) break; | |
| 234 | + if (isCancelled?.()) break; | |
| 235 | + try { | |
| 236 | + analyzed++; | |
| 237 | + analyzedBytes += c.size; | |
| 238 | + batchBytes += c.size; | |
| 239 | + const text = await c.file.text(); | |
| 240 | + const entry = {}; | |
| 241 | + if (c.wantRefs) { | |
| 242 | + const specs = extractRefs(c.name, text); | |
| 243 | + if (specs.length) entry.specs = specs; | |
| 244 | + } | |
| 245 | + if (c.wantIndex) { | |
| 246 | + const clean = stripCommentsAndStrings(text, c.name); | |
| 247 | + const defs = extractDefs(c.name, clean); | |
| 248 | + const tokens = [...extractTokens(clean)]; | |
| 249 | + if (defs.length) entry.defs = defs; | |
| 250 | + if (tokens.length) entry.tokens = tokens; | |
| 251 | + } | |
| 252 | + applyEntry(c.rel, c.size, entry); | |
| 253 | + newCacheEntries.set(c.key, entry); | |
| 254 | + } catch { /* ignorar */ } | |
| 255 | + // ceder el hilo con regularidad: el render no se congela dentro del lote | |
| 256 | + if (analyzed % YIELD_EVERY === 0) await new Promise(r => setTimeout(r, 0)); | |
| 257 | + if (newCacheEntries.size >= BATCH_FILES || batchBytes >= BATCH_BYTES) { | |
| 258 | + await checkpoint(); | |
| 259 | + // el refresco de enlaces es lo caro: solo cada REFRESH_FILES, no por lote | |
| 260 | + if (analyzed - lastRefresh >= REFRESH_FILES) { | |
| 261 | + lastRefresh = analyzed; | |
| 262 | + onBatch?.(buildMeta()); | |
| 263 | + await new Promise(r => setTimeout(r, 0)); | |
| 264 | + } | |
| 265 | + } | |
| 266 | + } | |
| 267 | + await checkpoint(); | |
| 268 | + if (headCommit) await pruneSnapshots(headCommit); | |
| 269 | + if (analyzed) onBatch?.(buildMeta()); | |
| 270 | + console.info(`[fsScan] análisis perezoso: ${analyzed}/${total} ficheros · ${checkpoints} checkpoints`); | |
| 271 | + return { analyzed, total }; | |
| 272 | + } | |
| 273 | + | |
| 274 | + return { | |
| 275 | + tree, | |
| 276 | + meta: { | |
| 277 | + git: gitMap, // aproximado desde .git/index (sin +/− líneas) | |
| 278 | + owners: ownerRules, | |
| 279 | + ...buildMeta(), // enlaces ya consolidados desde caché/snapshot | |
| 280 | + }, | |
| 281 | + pending: total, | |
| 282 | + runAnalysis, | |
| 283 | + }; | |
| 284 | +} |
added src/gitIndex.js +63 −0
| @@ -0,0 +1,63 @@ | ||
| 1 | +// Parser del fichero .git/index (v2/v3) para estimar el estado git desde el | |
| 2 | +// navegador, donde no hay binario git: un fichero presente en el índice con | |
| 3 | +// el mismo tamaño y mtime se considera limpio; si difiere → modificado; si | |
| 4 | +// no está en el índice → sin seguimiento. (v4 usa compresión de rutas y no | |
| 5 | +// se soporta: en ese caso el modo git queda deshabilitado.) | |
| 6 | +export function parseGitIndex(buf) { | |
| 7 | + const dv = new DataView(buf); | |
| 8 | + if (buf.byteLength < 12 || dv.getUint32(0) !== 0x44495243) return null; // 'DIRC' | |
| 9 | + const version = dv.getUint32(4); | |
| 10 | + if (version < 2 || version > 3) return null; | |
| 11 | + const count = dv.getUint32(8); | |
| 12 | + const bytes = new Uint8Array(buf); | |
| 13 | + const td = new TextDecoder(); | |
| 14 | + const map = new Map(); | |
| 15 | + let off = 12; | |
| 16 | + for (let i = 0; i < count; i++) { | |
| 17 | + if (off + 62 > buf.byteLength) return null; | |
| 18 | + const start = off; | |
| 19 | + const mtime = dv.getUint32(off + 8); | |
| 20 | + const size = dv.getUint32(off + 36); | |
| 21 | + const flags = dv.getUint16(off + 60); | |
| 22 | + let nameOff = off + 62; | |
| 23 | + if (version === 3 && (flags & 0x4000)) nameOff += 2; | |
| 24 | + let end = nameOff; | |
| 25 | + while (end < buf.byteLength && bytes[end] !== 0) end++; | |
| 26 | + map.set(td.decode(bytes.subarray(nameOff, end)), { size, mtime }); | |
| 27 | + // la entrada se rellena con NULs hasta múltiplo de 8 (mínimo 1) | |
| 28 | + off = start + Math.ceil((end + 1 - start) / 8) * 8; | |
| 29 | + } | |
| 30 | + return map; | |
| 31 | +} | |
| 32 | + | |
| 33 | +// commit de HEAD desde el navegador: resuelve la ref de .git/HEAD contra | |
| 34 | +// refs/… o packed-refs. Es la clave de los snapshots consolidados de la caché. | |
| 35 | +export async function readHeadCommit(gitDir) { | |
| 36 | + const readText = async (dir, name) => (await (await dir.getFileHandle(name)).getFile()).text(); | |
| 37 | + try { | |
| 38 | + const head = (await readText(gitDir, 'HEAD')).trim(); | |
| 39 | + const m = head.match(/^ref:\s*(\S+)/); | |
| 40 | + if (!m) return /^[0-9a-f]{40,64}$/.test(head) ? head : null; // detached | |
| 41 | + const parts = m[1].split('/'); | |
| 42 | + try { | |
| 43 | + let dir = gitDir; | |
| 44 | + for (const p of parts.slice(0, -1)) dir = await dir.getDirectoryHandle(p); | |
| 45 | + return (await readText(dir, parts[parts.length - 1])).trim(); | |
| 46 | + } catch { | |
| 47 | + const packed = await readText(gitDir, 'packed-refs'); | |
| 48 | + for (const line of packed.split('\n')) { | |
| 49 | + if (line.endsWith(' ' + m[1])) return line.split(' ')[0]; | |
| 50 | + } | |
| 51 | + } | |
| 52 | + } catch { /* sin HEAD legible */ } | |
| 53 | + return null; | |
| 54 | +} | |
| 55 | + | |
| 56 | +// estado aproximado de un fichero del árbol frente al índice | |
| 57 | +export function gitStatusOf(index, relPath, size, lastModifiedMs) { | |
| 58 | + const ent = index.get(relPath); | |
| 59 | + if (!ent) return 'U'; | |
| 60 | + if (ent.size !== size) return 'M'; | |
| 61 | + if (Math.abs(lastModifiedMs / 1000 - ent.mtime) > 2) return 'M'; | |
| 62 | + return null; // limpio | |
| 63 | +} |
added src/gpu.js +55 −0
| @@ -0,0 +1,55 @@ | ||
| 1 | +// Detección de la aceleración gráfica real del navegador. | |
| 2 | +// Lee el renderer sin máscara de WebGL (WEBGL_debug_renderer_info) y | |
| 3 | +// clasifica el hardware en niveles para adaptar la calidad del render: | |
| 4 | +// - alta: GPU discreta NVIDIA/AMD/Intel Arc o Apple Silicon (Metal) | |
| 5 | +// - media: integradas u origen desconocido (valores actuales del proyecto) | |
| 6 | +// - software: SwiftShader/llvmpipe → sin MSAA y resolución nativa 1:1 | |
| 7 | + | |
| 8 | +export function detectGPU(gl) { | |
| 9 | + let renderer = '', vendor = ''; | |
| 10 | + try { | |
| 11 | + const dbg = gl.getExtension('WEBGL_debug_renderer_info'); | |
| 12 | + renderer = String(dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER) ?? ''); | |
| 13 | + vendor = String(dbg ? gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR) ?? ''); | |
| 14 | + } catch { /* contexto perdido o cabeceras bloqueadas */ } | |
| 15 | + const low = `${renderer} ${vendor}`.toLowerCase(); | |
| 16 | + | |
| 17 | + const isSoftware = /swiftshader|llvmpipe|softpipe|software|basic render/.test(low); | |
| 18 | + const isNvidia = /nvidia|geforce|quadro|\brtx\b|\bgtx\b/.test(low); | |
| 19 | + // macOS: ANGLE sobre Metal reporta "Apple M1/M2/…" o el genérico "Apple GPU" | |
| 20 | + const isApple = /apple m\d|apple gpu|angle.*metal/.test(low) | |
| 21 | + || (/apple/.test(low) && /mac/i.test(navigator.platform ?? '')); | |
| 22 | + const isAmd = /\bamd\b|radeon/.test(low); | |
| 23 | + const isIntelArc = /intel.*arc/.test(low); | |
| 24 | + | |
| 25 | + let tier = 'media'; | |
| 26 | + if (isSoftware) tier = 'software'; | |
| 27 | + else if (isNvidia || isApple || isAmd || isIntelArc) tier = 'alta'; | |
| 28 | + | |
| 29 | + let maxSamples = 4; | |
| 30 | + try { maxSamples = gl.getParameter(gl.MAX_SAMPLES) ?? 4; } catch { /* WebGL1 */ } | |
| 31 | + | |
| 32 | + // MSAA ×8 + HalfFloat + pixelRatio 3 corrompía el render en algunas GPUs | |
| 33 | + // discretas (regiones negras y geometría estirada según el ángulo de | |
| 34 | + // cámara: el driver no aguanta render targets multisample tan grandes). | |
| 35 | + // Techo conservador conocido-bueno: ×4 y ratio ≤2; el render software | |
| 36 | + // baja a 1:1 sin multisampling. Overrides para depurar: ?msaa=N&pr=N | |
| 37 | + const params = new URLSearchParams(window.location?.search ?? ''); | |
| 38 | + const ovMsaa = params.get('msaa'), ovPr = params.get('pr'); | |
| 39 | + | |
| 40 | + const profile = { | |
| 41 | + name: renderer || 'GPU desconocida', | |
| 42 | + tier, isNvidia, isApple, | |
| 43 | + webgpu: 'gpu' in navigator, | |
| 44 | + pixelRatioCap: tier === 'software' ? 1 : 2, | |
| 45 | + msaaSamples: tier === 'software' ? 0 : Math.min(4, maxSamples), | |
| 46 | + bloom: tier !== 'software', | |
| 47 | + }; | |
| 48 | + if (ovMsaa !== null && ovMsaa !== '') { | |
| 49 | + profile.msaaSamples = Math.max(0, Math.min(+ovMsaa || 0, maxSamples)); | |
| 50 | + } | |
| 51 | + if (ovPr !== null && ovPr !== '') { | |
| 52 | + profile.pixelRatioCap = Math.max(0.5, Math.min(+ovPr || 1, 4)); | |
| 53 | + } | |
| 54 | + return profile; | |
| 55 | +} |
added src/ignore.js +67 −0
| @@ -0,0 +1,67 @@ | ||
| 1 | +// Matcher de patrones .gitignore / .dockerignore (subconjunto razonable). | |
| 2 | +// Compartido por el escáner de node (scan.mjs) y el del navegador (fsScan.js). | |
| 3 | +export const IGNORE_FILES = ['.gitignore', '.dockerignore', '.npmignore']; | |
| 4 | + | |
| 5 | +export function globToRegex(p) { | |
| 6 | + let rx = ''; | |
| 7 | + for (let i = 0; i < p.length; i++) { | |
| 8 | + const c = p[i]; | |
| 9 | + if (c === '*') { | |
| 10 | + if (p[i + 1] === '*') { | |
| 11 | + if (p[i + 2] === '/') { rx += '(?:[^/]+/)*'; i += 2; } | |
| 12 | + else { rx += '.*'; i += 1; } | |
| 13 | + } else rx += '[^/]*'; | |
| 14 | + } else if (c === '?') { | |
| 15 | + rx += '[^/]'; | |
| 16 | + } else { | |
| 17 | + rx += c.replace(/[.+^${}()|[\]\\]/g, '\\$&'); | |
| 18 | + } | |
| 19 | + } | |
| 20 | + return rx; | |
| 21 | +} | |
| 22 | + | |
| 23 | +function makeRule(line) { | |
| 24 | + line = line.trim(); | |
| 25 | + if (!line || line.startsWith('#')) return null; | |
| 26 | + let neg = false; | |
| 27 | + if (line.startsWith('!')) { neg = true; line = line.slice(1); } | |
| 28 | + let dirOnly = false; | |
| 29 | + if (line.endsWith('/')) { dirOnly = true; line = line.slice(0, -1); } | |
| 30 | + let body; | |
| 31 | + if (line.startsWith('/')) body = globToRegex(line.slice(1)); | |
| 32 | + else if (line.includes('/')) body = globToRegex(line); | |
| 33 | + else body = '(?:[^/]+/)*' + globToRegex(line); // sin barra: basename a cualquier nivel | |
| 34 | + try { | |
| 35 | + return { re: new RegExp(`^${body}$`), neg, dirOnly }; | |
| 36 | + } catch { | |
| 37 | + return null; | |
| 38 | + } | |
| 39 | +} | |
| 40 | + | |
| 41 | +export class IgnoreStack { | |
| 42 | + constructor() { this.layers = []; } | |
| 43 | + | |
| 44 | + // base: ruta relativa (desde la raíz del escaneo) del dir que contiene el fichero de ignore | |
| 45 | + push(base, lines) { | |
| 46 | + this.layers.push({ base, rules: lines.map(makeRule).filter(Boolean) }); | |
| 47 | + } | |
| 48 | + | |
| 49 | + pop() { this.layers.pop(); } | |
| 50 | + | |
| 51 | + // relPath con '/'; el escáner propaga: si un dir se ignora, todo su contenido también | |
| 52 | + ignored(relPath, isDir) { | |
| 53 | + let state = false; | |
| 54 | + for (const layer of this.layers) { | |
| 55 | + let sub = relPath; | |
| 56 | + if (layer.base) { | |
| 57 | + if (!relPath.startsWith(layer.base + '/')) continue; | |
| 58 | + sub = relPath.slice(layer.base.length + 1); | |
| 59 | + } | |
| 60 | + for (const r of layer.rules) { | |
| 61 | + if (r.dirOnly && !isDir) continue; | |
| 62 | + if (r.re.test(sub)) state = !r.neg; | |
| 63 | + } | |
| 64 | + } | |
| 65 | + return state; | |
| 66 | + } | |
| 67 | +} |
added src/main.js +457 −0
| @@ -0,0 +1,457 @@ | ||
| 1 | +// VibeCodeViewer — metrópolis de cristal nítida. | |
| 2 | +import * as THREE from 'three'; | |
| 3 | +import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; | |
| 4 | +import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; | |
| 5 | +import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; | |
| 6 | +import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; | |
| 7 | +import { REPO_TREE, REPO_META } from './data.js'; | |
| 8 | +import { buildModel, applyCodeMeta } from './model.js'; | |
| 9 | +import { computeMode } from './colorModes.js'; | |
| 10 | +import { buildCity } from './builder.js'; | |
| 11 | +import { createNavigation } from './controls.js'; | |
| 12 | +import { createUI } from './ui.js'; | |
| 13 | +import { canPickFolder, pickAndScanFolder, reopenLastFolder, savedFolderName } from './fsScan.js'; | |
| 14 | +import { detectGPU } from './gpu.js'; | |
| 15 | +import { THEMES } from './themes.js'; | |
| 16 | + | |
| 17 | +// ── base persistente (renderer, cámara, composer) ───────────────────────── | |
| 18 | +// powerPreference fuerza la GPU discreta en portátiles con doble gráfica | |
| 19 | +const canvas = document.getElementById('view'); | |
| 20 | +const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' }); | |
| 21 | +const gpu = detectGPU(renderer.getContext()); | |
| 22 | +console.info(`[gpu] ${gpu.name} · nivel ${gpu.tier} · MSAA ×${gpu.msaaSamples} · pixelRatio ≤${gpu.pixelRatioCap}${gpu.webgpu ? ' · WebGPU disponible' : ''}`); | |
| 23 | +renderer.setPixelRatio(Math.min(window.devicePixelRatio, gpu.pixelRatioCap)); | |
| 24 | +renderer.toneMapping = THREE.ACESFilmicToneMapping; | |
| 25 | +renderer.toneMappingExposure = 1.05; | |
| 26 | + | |
| 27 | +const scene = new THREE.Scene(); | |
| 28 | +scene.background = new THREE.Color(0x020309); | |
| 29 | +const camera = new THREE.PerspectiveCamera(55, 1, 0.1, 1000); | |
| 30 | + | |
| 31 | +// el antialias del canvas no aplica al renderizar vía composer: sin MSAA | |
| 32 | +// en el render target, las aristas de 1px parpadean con el bloom al mover | |
| 33 | +// la cámara (aliasing temporal). HalfFloat para conservar los colores HDR. | |
| 34 | +// Las muestras se adaptan a la GPU detectada (×8 en discretas/Apple Silicon, | |
| 35 | +// 0 en render software). | |
| 36 | +const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(1, 1, { | |
| 37 | + type: THREE.HalfFloatType, | |
| 38 | + samples: gpu.msaaSamples, | |
| 39 | +})); | |
| 40 | +composer.addPass(new RenderPass(scene, camera)); | |
| 41 | +const bloom = new UnrealBloomPass(new THREE.Vector2(1, 1), 0.65, 0.25, 0.85); | |
| 42 | +bloom.enabled = gpu.bloom; | |
| 43 | +composer.addPass(bloom); | |
| 44 | +composer.addPass(new OutputPass()); | |
| 45 | + | |
| 46 | +function resize() { | |
| 47 | + const w = window.innerWidth, h = window.innerHeight; | |
| 48 | + renderer.setSize(w, h, false); | |
| 49 | + composer.setSize(w, h); | |
| 50 | + bloom.resolution.set(w, h); | |
| 51 | + camera.aspect = w / h; | |
| 52 | + camera.updateProjectionMatrix(); | |
| 53 | +} | |
| 54 | +window.addEventListener('resize', resize); | |
| 55 | + | |
| 56 | +// ── estado reconstruible (modelo + ciudad + navegación) ─────────────────── | |
| 57 | +let model = null, city = null, nav = null; | |
| 58 | +let legendOn = true; | |
| 59 | +let groundSolid = false; | |
| 60 | +let colorMode = 'basic'; | |
| 61 | +let themeName = 'hacker'; | |
| 62 | + | |
| 63 | +// aplica la parte "barata" del tema: escena, bloom y variables CSS de la UI | |
| 64 | +function setSceneTheme(t) { | |
| 65 | + scene.background = new THREE.Color(t.background); | |
| 66 | + scene.fog?.color.set(t.fog); | |
| 67 | + bloom.strength = t.bloom.strength; | |
| 68 | + bloom.threshold = t.bloom.threshold; | |
| 69 | + for (const [k, v] of Object.entries(t.css)) { | |
| 70 | + document.documentElement.style.setProperty('--' + k, v); | |
| 71 | + } | |
| 72 | + // la clase `light` gobierna la UI; el blending de la escena usa t.light | |
| 73 | + document.body.classList.toggle('light', !!(t.uiLight ?? t.light)); | |
| 74 | +} | |
| 75 | + | |
| 76 | +function buildCityThemed() { | |
| 77 | + const t = THEMES[themeName]; | |
| 78 | + setSceneTheme(t); | |
| 79 | + city = buildCity(scene, model, t); | |
| 80 | + city.setLegend(legendOn); | |
| 81 | + city.setGroundOpaque(groundSolid); | |
| 82 | +} | |
| 83 | + | |
| 84 | +function boot(packedTree, meta) { | |
| 85 | + selectedFile = null; | |
| 86 | + hoveredBuilding = null; | |
| 87 | + litFacade = null; | |
| 88 | + pulsers = []; | |
| 89 | + suggestions = []; | |
| 90 | + sugFacades.clear(); | |
| 91 | + | |
| 92 | + city?.dispose(); | |
| 93 | + nav?.dispose(); | |
| 94 | + | |
| 95 | + model = buildModel(packedTree, meta); | |
| 96 | + const extent = Math.max(model.city.box.sx, model.city.box.sz); | |
| 97 | + scene.fog = new THREE.FogExp2(THEMES[themeName].fog, 0.62 / extent); | |
| 98 | + camera.far = extent * 14; | |
| 99 | + camera.updateProjectionMatrix(); | |
| 100 | + | |
| 101 | + buildCityThemed(); | |
| 102 | + nav = createNavigation(camera, canvas, model.city.box); | |
| 103 | + nav.VIEWS.reset(); | |
| 104 | + ui.setModel(model); | |
| 105 | + ui.setModeAvailable('git', model.hasGit); | |
| 106 | + ui.setModeAvailable('ownership', model.owners.length > 0); | |
| 107 | + ui.setModeAvailable('blast', | |
| 108 | + Object.keys(model.linksOut).length > 0 || Object.keys(model.symOut).length > 0); | |
| 109 | + applyColorMode('basic'); | |
| 110 | + window.VCC = { model, city, nav, camera, selectFile, selectNode, clearSelection, applyColorMode, applyTheme }; | |
| 111 | +} | |
| 112 | + | |
| 113 | +// cambia de tema reconstruyendo solo la ciudad (modelo y cámara intactos) | |
| 114 | +function applyTheme(name) { | |
| 115 | + if (!THEMES[name]) return; | |
| 116 | + themeName = name; | |
| 117 | + const sel = selectedFile; | |
| 118 | + city?.dispose(); | |
| 119 | + hoveredBuilding = null; | |
| 120 | + litFacade = null; | |
| 121 | + pulsers = []; | |
| 122 | + sugFacades.clear(); | |
| 123 | + suggestions = []; | |
| 124 | + buildCityThemed(); | |
| 125 | + applyColorMode(colorMode); | |
| 126 | + if (sel) selectFile(sel); | |
| 127 | + window.VCC.city = city; | |
| 128 | +} | |
| 129 | + | |
| 130 | +// ── modos de coloreado (básico / git / ownership) ───────────────────────── | |
| 131 | +function applyColorMode(mode) { | |
| 132 | + colorMode = mode; | |
| 133 | + document.body.classList.toggle('mode-git', mode === 'git'); | |
| 134 | + const theme = THEMES[themeName]; | |
| 135 | + const m = computeMode(model, mode, theme); | |
| 136 | + city.setModeColors(m.fileColor, m.nodeColor); | |
| 137 | + ui.setColorLegend(mode === 'blast' | |
| 138 | + ? [ | |
| 139 | + { label: 'Impacto: dependen de él', color: theme.beamIn ?? theme.beam }, | |
| 140 | + { label: 'Dependencias: usa de ellos', color: theme.beam }, | |
| 141 | + ] | |
| 142 | + : m.legend); | |
| 143 | + ui.setActiveMode(mode); | |
| 144 | + city.setBlastBeams(null); | |
| 145 | + // reaplica la selección activa sobre los nuevos colores base | |
| 146 | + if (selectedFile) selectFile(selectedFile); | |
| 147 | +} | |
| 148 | + | |
| 149 | +// ── modo Blast: relaciones de código del fichero seleccionado ───────────── | |
| 150 | +// dependencias (lo que este fichero usa) en theme.beam; dependientes —el | |
| 151 | +// impacto de cambiarlo: imports + usos de sus símbolos— en theme.beamIn. | |
| 152 | + | |
| 153 | +function blastEdges(file) { | |
| 154 | + // rel destino → { impact, syms:Set } (impact gana si hay ambas direcciones) | |
| 155 | + const edges = new Map(); | |
| 156 | + const dirs = new Set(); | |
| 157 | + const touch = (rel, impact, sym) => { | |
| 158 | + if (rel === file.rel) return; | |
| 159 | + const e = edges.get(rel) ?? { impact: false, syms: new Set() }; | |
| 160 | + e.impact ||= impact; | |
| 161 | + if (sym) e.syms.add(sym); | |
| 162 | + edges.set(rel, e); | |
| 163 | + }; | |
| 164 | + for (const tok of model.linksOut[file.rel] ?? []) { | |
| 165 | + if (tok.startsWith('F:')) touch(tok.slice(2), false); | |
| 166 | + else dirs.add(tok.slice(2)); | |
| 167 | + } | |
| 168 | + for (const [target, sym] of model.symOut[file.rel] ?? []) touch(target, false, sym); | |
| 169 | + for (const src of model.linksIn[file.rel] ?? []) touch(src, true); | |
| 170 | + for (const [src, sym] of model.symIn[file.rel] ?? []) touch(src, true, sym); | |
| 171 | + return { edges, dirs }; | |
| 172 | +} | |
| 173 | + | |
| 174 | +function applyBlast(file) { | |
| 175 | + const theme = THEMES[themeName]; | |
| 176 | + const BLAST_DEP = theme.beam.map(c => c * 1.2); | |
| 177 | + const BLAST_IMP = (theme.beamIn ?? theme.beam).map(c => c * 1.2); | |
| 178 | + const NODE_DEP = theme.beam.map(c => c * 0.75); | |
| 179 | + const NODE_IMP = (theme.beamIn ?? theme.beam).map(c => c * 0.75); | |
| 180 | + const from = [file.box.cx, file.box.cy, file.box.cz]; | |
| 181 | + const { edges, dirs } = blastEdges(file); | |
| 182 | + const pairs = []; | |
| 183 | + let nImp = 0, nDep = 0; | |
| 184 | + for (const [rel, e] of edges) { | |
| 185 | + const t = model.fileByRel.get(rel); | |
| 186 | + if (!t) continue; | |
| 187 | + e.impact ? nImp++ : nDep++; | |
| 188 | + city.paintFile(t.id, e.impact ? 0.95 : 0.8, e.impact ? BLAST_IMP : BLAST_DEP); | |
| 189 | + city.paintNode(t.node, 0.3, e.impact ? NODE_IMP : NODE_DEP); | |
| 190 | + pairs.push({ a: from, b: [t.box.cx, t.box.cy, t.box.cz], impact: e.impact }); | |
| 191 | + } | |
| 192 | + for (const rel of dirs) { | |
| 193 | + const n = model.dirByRel.get(rel); | |
| 194 | + if (!n?.box) continue; | |
| 195 | + nDep++; | |
| 196 | + city.paintNode(n, 0.55, NODE_DEP); | |
| 197 | + pairs.push({ a: from, b: [n.box.cx, n.box.cy, n.box.cz], impact: false }); | |
| 198 | + } | |
| 199 | + city.setBlastBeams(pairs); | |
| 200 | + ui.setColorLegend([ | |
| 201 | + { label: `Impacto: dependen de él · ${nImp}`, color: theme.beamIn ?? theme.beam }, | |
| 202 | + { label: `Dependencias: usa de ellos · ${nDep}`, color: theme.beam }, | |
| 203 | + ]); | |
| 204 | +} | |
| 205 | + | |
| 206 | +// ── selección jerárquica ────────────────────────────────────────────────── | |
| 207 | +const DECAY = 0.56; // caída de intensidad por nivel: cajón → … → distrito | |
| 208 | +let selectedFile = null; | |
| 209 | +let hoveredBuilding = null; | |
| 210 | +let litFacade = null; | |
| 211 | +let pulsers = []; // distritos encendidos que laten | |
| 212 | +let suggestions = []; // resultados de búsqueda que parpadean | |
| 213 | +const sugFacades = new Set(); | |
| 214 | + | |
| 215 | +function setFacade(building, keys) { | |
| 216 | + if (litFacade && litFacade !== building) city.redrawFacade(litFacade, null); | |
| 217 | + litFacade = building; | |
| 218 | + if (building) city.redrawFacade(building, keys); | |
| 219 | +} | |
| 220 | + | |
| 221 | +function glowChain(startNode, startGlow) { | |
| 222 | + const fills = []; | |
| 223 | + pulsers = []; | |
| 224 | + let glow = startGlow; | |
| 225 | + for (let n = startNode; n && n.role !== 'ciudad'; n = n.parent) { | |
| 226 | + if (n.role === 'distrito') { | |
| 227 | + // el barrio se ilumina algo más y late (pulse en el bucle de render) | |
| 228 | + const g = Math.min(1, glow * 2.4); | |
| 229 | + city.paintNode(n, g); | |
| 230 | + pulsers.push({ node: n, glow: g }); | |
| 231 | + } else { | |
| 232 | + city.paintNode(n, glow); | |
| 233 | + // relleno volumétrico solo en niveles interiores: el edificio se marca | |
| 234 | + // con aristas y fresnel para no velar el interior | |
| 235 | + if (fills.length < 10 && n.role !== 'edificio') fills.push({ box: n.box, glow }); | |
| 236 | + } | |
| 237 | + glow *= DECAY; | |
| 238 | + } | |
| 239 | + city.fillBoxes(fills); | |
| 240 | +} | |
| 241 | + | |
| 242 | +function selectFile(file, { fly = false } = {}) { | |
| 243 | + city.clearGlows(); | |
| 244 | + city.setBlastBeams(null); | |
| 245 | + selectedFile = file; | |
| 246 | + hoveredBuilding = null; | |
| 247 | + ui.markNode(null); | |
| 248 | + // celda a tope, hermanas del mismo contenedor a media luz | |
| 249 | + for (const fid of file.node.fileIds) city.paintFile(fid, fid === file.id ? 1 : 0.18); | |
| 250 | + glowChain(file.node, 1); | |
| 251 | + // fachada: resalta la ruta dentro del edificio | |
| 252 | + const building = file.node.building; | |
| 253 | + if (building) { | |
| 254 | + const keys = new Set(['f' + file.id]); | |
| 255 | + for (let n = file.node; n && n.building === building; n = n.parent) keys.add('n' + n.id); | |
| 256 | + setFacade(building, keys); | |
| 257 | + } | |
| 258 | + if (colorMode === 'blast') applyBlast(file); | |
| 259 | + const chainNames = [...file.chain].reverse().filter(n => !n.virtual).map(n => n.name); | |
| 260 | + ui.setPath(file, chainNames); | |
| 261 | + ui.markFile(file); | |
| 262 | + if (fly) nav.VIEWS.focus(file.node.box, 3.2); | |
| 263 | +} | |
| 264 | + | |
| 265 | +function selectNode(node) { | |
| 266 | + if (!node.box) return; | |
| 267 | + city.clearGlows(); | |
| 268 | + city.setBlastBeams(null); | |
| 269 | + selectedFile = null; | |
| 270 | + setFacade(null, null); | |
| 271 | + glowChain(node, 0.85); | |
| 272 | + // selección sincronizada ciudad ↔ árbol, con la ruta del nivel | |
| 273 | + const names = []; | |
| 274 | + for (let n = node; n && n.role !== 'ciudad'; n = n.parent) if (!n.virtual) names.unshift(n.name); | |
| 275 | + ui.setPathParts(names.length ? names : null); | |
| 276 | + ui.markFile(null); | |
| 277 | + ui.markNode(node); | |
| 278 | + const wide = node.role === 'edificio' || node.role === 'distrito' || node.role === 'urbanizacion'; | |
| 279 | + nav.VIEWS.focus(node.box, wide ? 1.6 : 2.6); | |
| 280 | +} | |
| 281 | + | |
| 282 | +function clearSelection() { | |
| 283 | + city.clearGlows(); | |
| 284 | + city.setBlastBeams(null); | |
| 285 | + setFacade(null, null); | |
| 286 | + pulsers = []; | |
| 287 | + selectedFile = null; | |
| 288 | + ui.setPath(null); | |
| 289 | + ui.markFile(null); | |
| 290 | + ui.markNode(null); | |
| 291 | +} | |
| 292 | + | |
| 293 | +// ── sugerencias de búsqueda: parpadeo en ciudad y fachadas ──────────────── | |
| 294 | +function setSuggestions(files) { | |
| 295 | + for (const f of suggestions) if (f !== selectedFile) city.paintFile(f.id, 0); | |
| 296 | + for (const b of sugFacades) if (b !== litFacade) city.redrawFacade(b, null); | |
| 297 | + sugFacades.clear(); | |
| 298 | + suggestions = files; | |
| 299 | + const byBuilding = new Map(); | |
| 300 | + for (const f of files) { | |
| 301 | + const b = f.node.building; | |
| 302 | + if (!b || b === litFacade) continue; | |
| 303 | + if (!byBuilding.has(b)) byBuilding.set(b, new Set()); | |
| 304 | + byBuilding.get(b).add('f' + f.id); | |
| 305 | + } | |
| 306 | + for (const [b, keys] of byBuilding) { | |
| 307 | + city.redrawFacade(b, keys); | |
| 308 | + sugFacades.add(b); | |
| 309 | + } | |
| 310 | +} | |
| 311 | + | |
| 312 | +// ── interacción de ratón ────────────────────────────────────────────────── | |
| 313 | +const raycaster = new THREE.Raycaster(); | |
| 314 | +const pointer = new THREE.Vector2(); | |
| 315 | + | |
| 316 | +canvas.addEventListener('pointermove', (e) => { | |
| 317 | + pointer.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1); | |
| 318 | +}); | |
| 319 | + | |
| 320 | +function pick() { | |
| 321 | + if (nav.fly.active) raycaster.setFromCamera(new THREE.Vector2(0, 0), camera); | |
| 322 | + else raycaster.setFromCamera(pointer, camera); | |
| 323 | + const fileHit = raycaster.intersectObject(city.filesMesh)[0]; | |
| 324 | + const shellHit = raycaster.intersectObjects(city.shells)[0]; | |
| 325 | + return { fileHit, shellHit }; | |
| 326 | +} | |
| 327 | + | |
| 328 | +function updateHover() { | |
| 329 | + if (selectedFile) return; | |
| 330 | + // solo carcasas: raycast contra cientos de miles de celdas por frame no escala | |
| 331 | + if (nav.fly.active) raycaster.setFromCamera(new THREE.Vector2(0, 0), camera); | |
| 332 | + else raycaster.setFromCamera(pointer, camera); | |
| 333 | + const shellHit = raycaster.intersectObjects(city.shells)[0]; | |
| 334 | + const b = shellHit?.object.userData.building ?? null; | |
| 335 | + if (b !== hoveredBuilding) { | |
| 336 | + if (hoveredBuilding) city.paintNode(hoveredBuilding, 0); | |
| 337 | + hoveredBuilding = b; | |
| 338 | + if (b) city.paintNode(b, 0.16); | |
| 339 | + canvas.style.cursor = b ? 'pointer' : 'default'; | |
| 340 | + } | |
| 341 | +} | |
| 342 | + | |
| 343 | +let downAt = null; | |
| 344 | +canvas.addEventListener('pointerdown', (e) => { downAt = [e.clientX, e.clientY]; }); | |
| 345 | +canvas.addEventListener('pointerup', (e) => { | |
| 346 | + if (!downAt) return; | |
| 347 | + const moved = Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]); | |
| 348 | + downAt = null; | |
| 349 | + if (moved > 5) return; // era un arrastre de cámara | |
| 350 | + const { fileHit, shellHit } = pick(); | |
| 351 | + if (fileHit && (!shellHit || fileHit.distance < shellHit.distance + 2)) { | |
| 352 | + selectFile(model.files[fileHit.instanceId]); | |
| 353 | + } else if (shellHit) { | |
| 354 | + selectNode(shellHit.object.userData.building); | |
| 355 | + } else { | |
| 356 | + clearSelection(); | |
| 357 | + } | |
| 358 | +}); | |
| 359 | + | |
| 360 | +document.addEventListener('keydown', (e) => { | |
| 361 | + if (document.activeElement?.tagName === 'INPUT') return; | |
| 362 | + if (e.code === 'Digit1') nav.VIEWS.reset(); | |
| 363 | + if (e.code === 'Digit2') nav.VIEWS.aerial(); | |
| 364 | + if (e.code === 'Digit3') nav.VIEWS.skyline(); | |
| 365 | + if (e.code === 'KeyX') clearSelection(); | |
| 366 | + if (e.code === 'KeyL') document.getElementById('btn-legend').click(); | |
| 367 | + if (e.code === 'KeyG') document.getElementById('btn-ground').click(); | |
| 368 | + if (e.code === 'Slash' || (e.code === 'KeyB' && e.ctrlKey)) { | |
| 369 | + e.preventDefault(); | |
| 370 | + document.getElementById('search-input').focus(); | |
| 371 | + } | |
| 372 | +}); | |
| 373 | + | |
| 374 | +// ── carga de carpetas: escaneo + análisis perezoso del modo Blast ───────── | |
| 375 | +// `scanGen` invalida un análisis en curso si se carga otra carpeta encima | |
| 376 | +let scanGen = 0; | |
| 377 | +async function loadScan(scanFn) { | |
| 378 | + let scan; | |
| 379 | + try { | |
| 380 | + ui.setLoading('Escaneando…'); | |
| 381 | + scan = await scanFn((msg) => ui.setLoading(`Escaneando… ${msg}`)); | |
| 382 | + } catch (err) { | |
| 383 | + if (err?.name !== 'AbortError') console.error(err); | |
| 384 | + } finally { | |
| 385 | + ui.setLoading(null); | |
| 386 | + } | |
| 387 | + if (!scan) return; | |
| 388 | + const gen = ++scanGen; | |
| 389 | + boot(scan.tree, scan.meta); | |
| 390 | + ui.setReopen(await savedFolderName()); | |
| 391 | + // el análisis de contenidos corre por lotes con la ciudad ya cargada: | |
| 392 | + // cada lote persiste su caché y refresca los enlaces del modo Blast | |
| 393 | + await scan.runAnalysis?.({ | |
| 394 | + isCancelled: () => gen !== scanGen, | |
| 395 | + onProgress: (msg) => { if (gen === scanGen) ui.setAnalysis(msg); }, | |
| 396 | + onBatch: (m) => { | |
| 397 | + if (gen !== scanGen) return; | |
| 398 | + applyCodeMeta(model, m.links, m.codeIndex); | |
| 399 | + ui.setModeAvailable('blast', | |
| 400 | + Object.keys(model.linksOut).length > 0 || Object.keys(model.symOut).length > 0); | |
| 401 | + if (colorMode === 'blast' && selectedFile) applyBlast(selectedFile); | |
| 402 | + }, | |
| 403 | + }); | |
| 404 | + if (gen === scanGen) ui.setAnalysis(null); | |
| 405 | +} | |
| 406 | + | |
| 407 | +// ── UI ──────────────────────────────────────────────────────────────────── | |
| 408 | +const ui = createUI({ | |
| 409 | + onSelectFile: (f, opts) => selectFile(f, opts ?? { fly: true }), | |
| 410 | + onSelectNode: (n) => { if (n.box) selectNode(n); }, | |
| 411 | + onView: (v) => nav.VIEWS[v](), | |
| 412 | + onSuggest: (files) => setSuggestions(files), | |
| 413 | + onToggleLegend: (on) => { legendOn = on; city.setLegend(on); }, | |
| 414 | + onToggleGround: (solid) => { groundSolid = solid; city.setGroundOpaque(solid); }, | |
| 415 | + onTheme: (name) => applyTheme(name), | |
| 416 | + onMode: (mode) => applyColorMode(mode), | |
| 417 | + onPickFolder: () => loadScan(pickAndScanFolder), | |
| 418 | + onReopenFolder: () => loadScan(reopenLastFolder), | |
| 419 | +}); | |
| 420 | +ui.setFolderSupported(canPickFolder()); | |
| 421 | +ui.setGpu(gpu); | |
| 422 | +if (canPickFolder()) savedFolderName().then((name) => ui.setReopen(name)); | |
| 423 | +canvas.addEventListener('flymode', (e) => ui.setFlyMode(e.detail)); | |
| 424 | + | |
| 425 | +// ── arranque + bucle ────────────────────────────────────────────────────── | |
| 426 | +boot(REPO_TREE, REPO_META); | |
| 427 | +resize(); | |
| 428 | + | |
| 429 | +let last = performance.now(); | |
| 430 | +let fpsAcc = 0, fpsN = 0; | |
| 431 | +function frame(now) { | |
| 432 | + const dt = Math.min(0.05, (now - last) / 1000); | |
| 433 | + last = now; | |
| 434 | + nav.update(dt); | |
| 435 | + updateHover(); | |
| 436 | + | |
| 437 | + // pulse de los barrios encendidos | |
| 438 | + for (const p of pulsers) { | |
| 439 | + city.paintNode(p.node, Math.min(1, p.glow * (0.78 + 0.3 * Math.sin(now * 0.004)))); | |
| 440 | + } | |
| 441 | + // parpadeo suave de las sugerencias de búsqueda | |
| 442 | + suggestions.forEach((f, i) => { | |
| 443 | + if (f === selectedFile) return; | |
| 444 | + city.paintFile(f.id, 0.1 + 0.2 * (0.5 + 0.5 * Math.sin(now * 0.006 + i * 0.8))); | |
| 445 | + }); | |
| 446 | + // pulsos de datos por los haces del modo Blast | |
| 447 | + city.tickBeams(now); | |
| 448 | + | |
| 449 | + composer.render(); | |
| 450 | + fpsAcc += dt; fpsN++; | |
| 451 | + if (fpsAcc >= 0.5) { | |
| 452 | + ui.setStats(Math.round(fpsN / fpsAcc)); | |
| 453 | + fpsAcc = 0; fpsN = 0; | |
| 454 | + } | |
| 455 | + requestAnimationFrame(frame); | |
| 456 | +} | |
| 457 | +requestAnimationFrame(frame); |
added src/model.js +360 −0
| @@ -0,0 +1,360 @@ | ||
| 1 | +// Modelo: convierte el árbol del repo en una ciudad con cajas anidadas. | |
| 2 | +// Jerarquía: ciudad → distrito → edificio → planta → apartamento → habitación | |
| 3 | +// → archivador → cajón → fichero (los ficheros pueden vivir en | |
| 4 | +// cualquier nivel: se les reserva un hueco en su contenedor). | |
| 5 | +// Cuando un subárbol es demasiado profundo/poblado para un solo edificio, | |
| 6 | +// se interpone una «urbanización»: una plota dentro del distrito que agrupa | |
| 7 | +// procedualmente a sus subcarpetas como edificios (recursivo), de modo que | |
| 8 | +// la profundidad sobrante se despliega por la ciudad en vez de comprimirse. | |
| 9 | +// Los ficheros ignorados (.gitignore y equivalentes) se separan en un | |
| 10 | +// sótano espejado bajo el plano de circuitos. | |
| 11 | +import { makeOwnerResolver } from './ownership.js'; | |
| 12 | + | |
| 13 | +export const ROLES = ['ciudad', 'distrito', 'edificio', 'planta', 'apartamento', 'habitacion', 'archivador', 'cajon']; | |
| 14 | +const ROLE_AXIS = { planta: 'y', apartamento: 'x', habitacion: 'z', archivador: 'x', cajon: 'y' }; | |
| 15 | + | |
| 16 | +const STREET = 14; // separación entre distritos | |
| 17 | +const ALLEY = 4; // separación entre edificios | |
| 18 | +const URB_PAD = 3; // margen interior de una urbanización | |
| 19 | +// un edificio absorbe 5 niveles (planta→…→cajón); más allá, urbanización | |
| 20 | +const URB_DEPTH = 5; | |
| 21 | +const URB_MIN_FILES = 200; | |
| 22 | +const URB_MAX_FILES = 2000; // aun siendo poco profundo, esto no cabe en uno | |
| 23 | +const GROUND_Y = 0; | |
| 24 | + | |
| 25 | +let nextNode = 0; | |
| 26 | +let nextFile = 0; | |
| 27 | + | |
| 28 | +function hash01(str) { | |
| 29 | + let h = 2166136261; | |
| 30 | + for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } | |
| 31 | + return ((h >>> 0) % 1000) / 1000; | |
| 32 | +} | |
| 33 | + | |
| 34 | +function unpack(packed) { | |
| 35 | + const [name, dirs, leaf] = packed; | |
| 36 | + const node = { name, dirs: dirs.map(unpack), leaf: leaf.map(([n, s, ig]) => ({ name: n, size: s, ignored: !!ig })) }; | |
| 37 | + node.files = node.leaf.length + node.dirs.reduce((a, d) => a + d.files, 0); | |
| 38 | + node.size = node.leaf.reduce((a, f) => a + f.size, 0) + node.dirs.reduce((a, d) => a + d.size, 0); | |
| 39 | + return node; | |
| 40 | +} | |
| 41 | + | |
| 42 | +function recount(node) { | |
| 43 | + node.files = node.leaf.length + node.dirs.reduce((a, d) => a + d.files, 0); | |
| 44 | + node.size = node.leaf.reduce((a, f) => a + f.size, 0) + node.dirs.reduce((a, d) => a + d.size, 0); | |
| 45 | + return node; | |
| 46 | +} | |
| 47 | + | |
| 48 | +// separa un subárbol en parte visible y parte ignorada (sótano) | |
| 49 | +function splitSrc(src) { | |
| 50 | + const kept = { name: src.name, dirs: [], leaf: src.leaf.filter(f => !f.ignored) }; | |
| 51 | + const ign = { name: src.name, dirs: [], leaf: src.leaf.filter(f => f.ignored) }; | |
| 52 | + for (const d of src.dirs) { | |
| 53 | + const s = splitSrc(d); | |
| 54 | + if (s.kept.files) kept.dirs.push(s.kept); | |
| 55 | + if (s.ign.files) ign.dirs.push(s.ign); | |
| 56 | + } | |
| 57 | + return { kept: recount(kept), ign: recount(ign) }; | |
| 58 | +} | |
| 59 | + | |
| 60 | +function makeNode(model, name, role, parent, { virtual = false } = {}) { | |
| 61 | + const node = { | |
| 62 | + id: nextNode++, name, role, parent, children: [], fileIds: [], | |
| 63 | + virtual, box: null, building: null, | |
| 64 | + path: parent ? (virtual ? parent.path : `${parent.path}/${name}`) : name, | |
| 65 | + }; | |
| 66 | + if (parent) parent.children.push(node); | |
| 67 | + model.nodes.push(node); | |
| 68 | + return node; | |
| 69 | +} | |
| 70 | + | |
| 71 | +function addFiles(model, node, leaf) { | |
| 72 | + for (const f of leaf) { | |
| 73 | + const file = { | |
| 74 | + id: nextFile++, name: f.name, size: f.size, node, | |
| 75 | + path: `${node.path}/${f.name}`, box: null, | |
| 76 | + }; | |
| 77 | + node.fileIds.push(file.id); | |
| 78 | + model.files.push(file); | |
| 79 | + } | |
| 80 | +} | |
| 81 | + | |
| 82 | +// ── dimensiones de edificio ─────────────────────────────────────────────── | |
| 83 | +function buildingDims(src) { | |
| 84 | + const kb = src.size / 1024; | |
| 85 | + const side = Math.min(22, Math.max(6, 4 + Math.log2(1 + kb) * 1.5)); | |
| 86 | + const j = hash01(src.name); | |
| 87 | + const w = side * (0.85 + 0.3 * j); | |
| 88 | + const d = side * (0.85 + 0.3 * (1 - j)); | |
| 89 | + const floors = Math.max(1, src.dirs.length + (src.leaf.length ? 1 : 0)); | |
| 90 | + const h = Math.max(6, Math.max(floors * 3.0, 6 + src.files * 1.8)); | |
| 91 | + return { w, d, h: Math.min(h, 80) }; | |
| 92 | +} | |
| 93 | + | |
| 94 | +// ── reparto de un eje en franjas ponderadas ─────────────────────────────── | |
| 95 | +function splitAxis(box, axis, weights, inset) { | |
| 96 | + const total = weights.reduce((a, b) => a + b, 0); | |
| 97 | + const span = box['s' + axis]; | |
| 98 | + const start = box['c' + axis] - span / 2; | |
| 99 | + const gap = Math.min(inset, span * 0.04); | |
| 100 | + const usable = span - gap * (weights.length + 1); | |
| 101 | + const out = []; | |
| 102 | + let cursor = start + gap; | |
| 103 | + for (const w of weights) { | |
| 104 | + const s = usable * (w / total); | |
| 105 | + out.push({ ...box, ['c' + axis]: cursor + s / 2, ['s' + axis]: s }); | |
| 106 | + cursor += s + gap; | |
| 107 | + } | |
| 108 | + return out; | |
| 109 | +} | |
| 110 | + | |
| 111 | +function shrink(box, f) { | |
| 112 | + return { ...box, sx: box.sx * f, sy: box.sy * f, sz: box.sz * f }; | |
| 113 | +} | |
| 114 | + | |
| 115 | +// ── celdas de fichero dentro de su contenedor ───────────────────────────── | |
| 116 | +function placeFiles(model, node, box, files) { | |
| 117 | + const n = files.length; | |
| 118 | + if (!n) return; | |
| 119 | + if (node.role === 'cajon') { | |
| 120 | + // carpetas colgantes: láminas verticales en fila | |
| 121 | + const slabs = splitAxis({ ...box, sy: box.sy * 0.72, cy: box.cy - box.sy * 0.1 }, 'x', | |
| 122 | + files.map(() => 1), 0.05); | |
| 123 | + files.forEach((fid, i) => { | |
| 124 | + const s = slabs[i]; | |
| 125 | + model.files[fid].box = { ...s, sx: Math.min(s.sx * 0.55, 0.5), sz: s.sz * 0.78 }; | |
| 126 | + }); | |
| 127 | + return; | |
| 128 | + } | |
| 129 | + // rejilla de cubos apoyada en el suelo del contenedor | |
| 130 | + const aspect = box.sx / box.sz || 1; | |
| 131 | + const cols = Math.max(1, Math.round(Math.sqrt(n * aspect))); | |
| 132 | + const rows = Math.ceil(n / cols); | |
| 133 | + const cw = box.sx / cols, cd = box.sz / rows; | |
| 134 | + const base = Math.min(cw, cd, box.sy) * 0.5; | |
| 135 | + files.forEach((fid, i) => { | |
| 136 | + const f = model.files[fid]; | |
| 137 | + const col = i % cols, row = Math.floor(i / cols); | |
| 138 | + const k = 0.65 + 0.45 * Math.min(1, Math.log2(2 + f.size / 1024) / 8); | |
| 139 | + const s = Math.max(0.25, base * k); | |
| 140 | + f.box = { | |
| 141 | + cx: box.cx - box.sx / 2 + cw * (col + 0.5), | |
| 142 | + cz: box.cz - box.sz / 2 + cd * (row + 0.5), | |
| 143 | + cy: box.cy - box.sy / 2 + s / 2 + 0.05, | |
| 144 | + sx: s, sy: s, sz: s, | |
| 145 | + }; | |
| 146 | + }); | |
| 147 | +} | |
| 148 | + | |
| 149 | +// ── subdivisión recursiva del interior del edificio ─────────────────────── | |
| 150 | +// flipY: en los sótanos las plantas crecen hacia abajo (dirección inversa) | |
| 151 | +function layoutInterior(model, node, src, box, role, flipY = false) { | |
| 152 | + node.box = box; | |
| 153 | + const dirs = src.dirs; | |
| 154 | + const hasFiles = src.leaf.length > 0; | |
| 155 | + addFiles(model, node, src.leaf); | |
| 156 | + | |
| 157 | + if (!dirs.length) { | |
| 158 | + placeFiles(model, node, shrink(box, 0.9), node.fileIds); | |
| 159 | + return; | |
| 160 | + } | |
| 161 | + const childRole = ROLES[Math.min(ROLES.indexOf(role) + 1, ROLES.length - 1)]; | |
| 162 | + const axis = ROLE_AXIS[childRole] ?? 'y'; | |
| 163 | + const weights = dirs.map(d => 1 + Math.sqrt(d.files)); | |
| 164 | + if (hasFiles) weights.push(0.8 + Math.sqrt(src.leaf.length) * 0.7); | |
| 165 | + const slices = splitAxis(box, axis, weights, 0.5); | |
| 166 | + if (flipY && axis === 'y') slices.reverse(); | |
| 167 | + dirs.forEach((d, i) => { | |
| 168 | + const child = makeNode(model, d.name, childRole, node); | |
| 169 | + child.building = node.building; | |
| 170 | + layoutInterior(model, child, d, shrink(slices[i], 0.94), childRole, flipY); | |
| 171 | + }); | |
| 172 | + if (hasFiles) placeFiles(model, node, shrink(slices[slices.length - 1], 0.9), node.fileIds); | |
| 173 | +} | |
| 174 | + | |
| 175 | +// ── empaquetado en rejilla (edificios en distrito, distritos en ciudad) ─── | |
| 176 | +function packGrid(items, gap) { | |
| 177 | + // items: { w, d } → coloca en filas; devuelve posiciones y tamaño del plot | |
| 178 | + const area = items.reduce((a, it) => a + (it.w + gap) * (it.d + gap), 0); | |
| 179 | + const targetW = Math.max(Math.sqrt(area) * 1.15, ...items.map(it => it.w + gap)); | |
| 180 | + let x = 0, z = 0, rowD = 0, plotW = 0; | |
| 181 | + const pos = []; | |
| 182 | + for (const it of items) { | |
| 183 | + if (x > 0 && x + it.w > targetW) { x = 0; z += rowD + gap; rowD = 0; } | |
| 184 | + pos.push({ x: x + it.w / 2, z: z + it.d / 2 }); | |
| 185 | + x += it.w + gap; | |
| 186 | + rowD = Math.max(rowD, it.d); | |
| 187 | + plotW = Math.max(plotW, x - gap); | |
| 188 | + } | |
| 189 | + return { pos, w: plotW, d: z + rowD }; | |
| 190 | +} | |
| 191 | + | |
| 192 | +function subtreeDepth(src) { | |
| 193 | + let d = 0; | |
| 194 | + for (const s of src.dirs) d = Math.max(d, 1 + subtreeDepth(s)); | |
| 195 | + return d; | |
| 196 | +} | |
| 197 | + | |
| 198 | +// ¿demasiado profundo y poblado para un solo edificio? → urbanización | |
| 199 | +function needsUrb(src) { | |
| 200 | + if (src.virtual || !src.dirs.length) return false; | |
| 201 | + if (src.files > URB_MAX_FILES) return true; | |
| 202 | + return src.files > URB_MIN_FILES && subtreeDepth(src) > URB_DEPTH; | |
| 203 | +} | |
| 204 | + | |
| 205 | +function fileBlockSrc(leaf) { | |
| 206 | + return { name: '(ficheros)', dirs: [], leaf, files: leaf.length, size: leaf.reduce((a, f) => a + f.size, 0), virtual: true }; | |
| 207 | +} | |
| 208 | + | |
| 209 | +// un «bloque» es lo que ocupa una parcela: un edificio o una urbanización. | |
| 210 | +// Devuelve { w, d, place(cx, cz) } para el empaquetado en rejilla. | |
| 211 | +function buildBlock(model, parent, src) { | |
| 212 | + if (needsUrb(src)) return buildUrb(model, parent, src); | |
| 213 | + const split = splitSrc(src); | |
| 214 | + const b = makeNode(model, src.name, 'edificio', parent, { virtual: !!src.virtual }); | |
| 215 | + b.building = b; | |
| 216 | + b.dims = buildingDims(split.kept.files ? split.kept : src); | |
| 217 | + // sin nada en superficie y todo en el sótano: búnker bajo y más opaco | |
| 218 | + // que señala que la información está bajo el suelo | |
| 219 | + if (!split.kept.files && split.ign.files) { | |
| 220 | + b.onlyBasement = true; | |
| 221 | + b.dims.h = 3; | |
| 222 | + } | |
| 223 | + b.srcKept = split.kept; | |
| 224 | + b.srcIgn = split.ign; | |
| 225 | + model.buildings.push(b); | |
| 226 | + return { w: b.dims.w, d: b.dims.d, place: (cx, cz) => placeBuilding(model, b, cx, cz) }; | |
| 227 | +} | |
| 228 | + | |
| 229 | +function buildUrb(model, parent, src) { | |
| 230 | + const urb = makeNode(model, src.name, 'urbanizacion', parent); | |
| 231 | + const childSrcs = [...src.dirs]; | |
| 232 | + if (src.leaf.length) childSrcs.push(fileBlockSrc(src.leaf)); | |
| 233 | + const blocks = childSrcs.map(s => buildBlock(model, urb, s)); | |
| 234 | + const grid = packGrid(blocks, ALLEY); | |
| 235 | + const w = grid.w + URB_PAD * 2, d = grid.d + URB_PAD * 2; | |
| 236 | + model.urbs.push(urb); | |
| 237 | + return { | |
| 238 | + w, d, | |
| 239 | + place: (cx, cz) => { | |
| 240 | + urb.box = { cx, cy: GROUND_Y + 0.26, cz, sx: w, sy: 0.14, sz: d }; | |
| 241 | + const ox = cx - w / 2 + URB_PAD, oz = cz - d / 2 + URB_PAD; | |
| 242 | + blocks.forEach((blk, i) => blk.place(ox + grid.pos[i].x, oz + grid.pos[i].z)); | |
| 243 | + }, | |
| 244 | + }; | |
| 245 | +} | |
| 246 | + | |
| 247 | +function placeBuilding(model, b, cx, cz) { | |
| 248 | + const { w, d, h } = b.dims; | |
| 249 | + layoutInterior(model, b, b.srcKept, { cx, cz, cy: GROUND_Y + h / 2, sx: w, sy: h, sz: d }, 'edificio'); | |
| 250 | + // sótano: los ficheros ignorados crecen hacia abajo, mismo patrón invertido | |
| 251 | + if (b.srcIgn.files) { | |
| 252 | + const hb = Math.min(60, Math.max(5, Math.max( | |
| 253 | + (b.srcIgn.dirs.length + (b.srcIgn.leaf.length ? 1 : 0)) * 3.0, | |
| 254 | + 5 + b.srcIgn.files * 1.6, | |
| 255 | + ))); | |
| 256 | + const bb = makeNode(model, b.name, 'edificio', b.parent, { virtual: b.virtual }); | |
| 257 | + bb.building = bb; | |
| 258 | + bb.isBasement = true; | |
| 259 | + model.buildings.push(bb); | |
| 260 | + layoutInterior(model, bb, b.srcIgn, | |
| 261 | + { cx, cz, cy: GROUND_Y - 0.7 - hb / 2, sx: w, sy: hb, sz: d }, 'edificio', true); | |
| 262 | + } | |
| 263 | + delete b.srcKept; delete b.srcIgn; | |
| 264 | +} | |
| 265 | + | |
| 266 | +function buildDistrict(model, city, srcDir, files) { | |
| 267 | + const district = makeNode(model, srcDir ? srcDir.name : '(raíz)', 'distrito', city, { virtual: !srcDir }); | |
| 268 | + const blockSrcs = []; | |
| 269 | + if (srcDir) { | |
| 270 | + for (const d of srcDir.dirs) blockSrcs.push(d); | |
| 271 | + if (srcDir.leaf.length) blockSrcs.push(fileBlockSrc(srcDir.leaf)); | |
| 272 | + } else { | |
| 273 | + blockSrcs.push(fileBlockSrc(files)); | |
| 274 | + } | |
| 275 | + const blocks = blockSrcs.map(s => buildBlock(model, district, s)); | |
| 276 | + const grid = packGrid(blocks, ALLEY); | |
| 277 | + district.plot = { w: grid.w + ALLEY * 2, d: grid.d + ALLEY * 2 }; | |
| 278 | + district.blocks = blocks; | |
| 279 | + district.grid = grid; | |
| 280 | + model.districts.push(district); | |
| 281 | + return district; | |
| 282 | +} | |
| 283 | + | |
| 284 | +export function buildModel(packedTree, meta = null) { | |
| 285 | + nextNode = 0; nextFile = 0; | |
| 286 | + const model = { nodes: [], files: [], buildings: [], districts: [], urbs: [], city: null }; | |
| 287 | + const root = unpack(packedTree); | |
| 288 | + const city = makeNode(model, root.name, 'ciudad', null); | |
| 289 | + model.city = city; | |
| 290 | + | |
| 291 | + for (const d of root.dirs) buildDistrict(model, city, d, []); | |
| 292 | + if (root.leaf.length) buildDistrict(model, city, null, root.leaf); | |
| 293 | + | |
| 294 | + // colocar distritos en la ciudad | |
| 295 | + const plots = model.districts.map(di => ({ w: di.plot.w, d: di.plot.d })); | |
| 296 | + const cityGrid = packGrid(plots, STREET); | |
| 297 | + const ox = -cityGrid.w / 2, oz = -cityGrid.d / 2; | |
| 298 | + model.districts.forEach((di, i) => { | |
| 299 | + const p = cityGrid.pos[i]; | |
| 300 | + const px = ox + p.x, pz = oz + p.z; | |
| 301 | + di.box = { cx: px, cy: GROUND_Y + 0.12, cz: pz, sx: di.plot.w, sy: 0.24, sz: di.plot.d }; | |
| 302 | + const bx = px - di.plot.w / 2 + ALLEY, bz = pz - di.plot.d / 2 + ALLEY; | |
| 303 | + di.blocks.forEach((blk, j) => blk.place(bx + di.grid.pos[j].x, bz + di.grid.pos[j].z)); | |
| 304 | + delete di.blocks; delete di.grid; | |
| 305 | + }); | |
| 306 | + city.box = { cx: 0, cy: 0, cz: 0, sx: cityGrid.w + STREET * 2, sy: 1, sz: cityGrid.d + STREET * 2 }; | |
| 307 | + | |
| 308 | + // cadena de ancestros por fichero (para la iluminación jerárquica) | |
| 309 | + // + metadatos git y code ownership por fichero | |
| 310 | + const rootPrefix = city.name + '/'; | |
| 311 | + const resolveOwner = makeOwnerResolver(meta?.owners); | |
| 312 | + const ownerIndex = new Map(); | |
| 313 | + for (const f of model.files) { | |
| 314 | + const chain = []; | |
| 315 | + for (let n = f.node; n; n = n.parent) chain.push(n); | |
| 316 | + f.chain = chain; // del contenedor inmediato hacia la ciudad | |
| 317 | + f.rel = f.path.startsWith(rootPrefix) ? f.path.slice(rootPrefix.length) : f.path; | |
| 318 | + const g = meta?.git?.[f.rel]; | |
| 319 | + f.git = g ? { st: g[0], a: g[1], d: g[2] } : null; | |
| 320 | + const owner = resolveOwner(f.rel); | |
| 321 | + if (owner != null) { | |
| 322 | + if (!ownerIndex.has(owner)) ownerIndex.set(owner, ownerIndex.size); | |
| 323 | + f.owner = ownerIndex.get(owner); | |
| 324 | + } else { | |
| 325 | + f.owner = null; | |
| 326 | + } | |
| 327 | + } | |
| 328 | + model.owners = [...ownerIndex.keys()]; | |
| 329 | + model.hasGit = !!meta?.git; | |
| 330 | + | |
| 331 | + applyCodeMeta(model, meta?.links, meta?.codeIndex); | |
| 332 | + model.fileByRel = new Map(model.files.map(f => [f.rel, f])); | |
| 333 | + model.dirByRel = new Map(); | |
| 334 | + for (const n of model.nodes) { | |
| 335 | + if (n.role === 'ciudad' || n.virtual || n.isBasement || n.building?.isBasement) continue; | |
| 336 | + const rel = n.path.startsWith(rootPrefix) ? n.path.slice(rootPrefix.length) : n.path; | |
| 337 | + if (!model.dirByRel.has(rel)) model.dirByRel.set(rel, n); | |
| 338 | + } | |
| 339 | + return model; | |
| 340 | +} | |
| 341 | + | |
| 342 | +// enlaces de código (modo Blast): adyacencia saliente y entrante. Es una | |
| 343 | +// función aparte porque el análisis perezoso los refresca por lotes sobre | |
| 344 | +// el modelo ya construido, sin reconstruir la ciudad. | |
| 345 | +export function applyCodeMeta(model, links, codeIndex) { | |
| 346 | + model.linksOut = links ?? {}; | |
| 347 | + model.linksIn = {}; | |
| 348 | + for (const [src, toks] of Object.entries(model.linksOut)) { | |
| 349 | + for (const tok of toks) { | |
| 350 | + if (tok.startsWith('F:')) (model.linksIn[tok.slice(2)] ??= []).push(src); | |
| 351 | + } | |
| 352 | + } | |
| 353 | + // índice de símbolos (funciones/clases/tipos): aristas "src usa sym de target" | |
| 354 | + model.defs = codeIndex?.defs ?? {}; | |
| 355 | + model.symOut = codeIndex?.symLinks ?? {}; | |
| 356 | + model.symIn = {}; | |
| 357 | + for (const [src, edges] of Object.entries(model.symOut)) { | |
| 358 | + for (const [target, sym] of edges) (model.symIn[target] ??= []).push([src, sym]); | |
| 359 | + } | |
| 360 | +} |
added src/ownership.js +49 −0
| @@ -0,0 +1,49 @@ | ||
| 1 | +// Code ownership: parsing de ficheros CODEOWNERS y de metadatos | |
| 2 | +// `package.yml` (metadata.owner), según las convenciones descritas en | |
| 3 | +// code_ownership_files.md. Compartido por scan.mjs y fsScan.js. | |
| 4 | +import { globToRegex } from './ignore.js'; | |
| 5 | + | |
| 6 | +// nombres de fichero que aportan reglas de ownership | |
| 7 | +export function isCodeownersFile(name) { return name === 'CODEOWNERS'; } | |
| 8 | +export function isPackageMeta(name) { return name === 'package.yml' || name === 'package.yaml'; } | |
| 9 | + | |
| 10 | +// CODEOWNERS: "patrón @owner1 [@owner2 …]" → [patrón, primer owner] | |
| 11 | +export function parseCodeowners(text) { | |
| 12 | + const rules = []; | |
| 13 | + for (let line of text.split('\n')) { | |
| 14 | + line = line.trim(); | |
| 15 | + if (!line || line.startsWith('#')) continue; | |
| 16 | + const parts = line.split(/\s+/); | |
| 17 | + if (parts.length < 2 || !parts[1].startsWith('@')) continue; | |
| 18 | + rules.push([parts[0], parts[1]]); | |
| 19 | + } | |
| 20 | + return rules; | |
| 21 | +} | |
| 22 | + | |
| 23 | +// package.yml: metadata.owner: '@team' → regla "dir/ → owner" | |
| 24 | +export function parsePackageMeta(text, dirRel) { | |
| 25 | + const m = text.match(/owner:\s*['"]?(@[\w/@.-]+)/); | |
| 26 | + if (!m) return null; | |
| 27 | + return [`/${dirRel}/`, m[1]]; | |
| 28 | +} | |
| 29 | + | |
| 30 | +// compila reglas (semántica CODEOWNERS: la última que casa gana) | |
| 31 | +export function makeOwnerResolver(rules) { | |
| 32 | + const compiled = []; | |
| 33 | + for (const [pat0, owner] of rules ?? []) { | |
| 34 | + let pat = pat0; | |
| 35 | + if (pat.endsWith('/')) pat = pat.slice(0, -1); | |
| 36 | + let prefix = ''; | |
| 37 | + if (pat.startsWith('/')) pat = pat.slice(1); | |
| 38 | + else if (!pat.includes('/')) prefix = '(?:[^/]+/)*'; | |
| 39 | + try { | |
| 40 | + // el patrón casa con la ruta exacta o como prefijo de directorio | |
| 41 | + compiled.push({ re: new RegExp(`^${prefix}${globToRegex(pat)}(?:/.*)?$`), owner }); | |
| 42 | + } catch { /* patrón inválido: se omite */ } | |
| 43 | + } | |
| 44 | + return (relPath) => { | |
| 45 | + let owner = null; | |
| 46 | + for (const r of compiled) if (r.re.test(relPath)) owner = r.owner; | |
| 47 | + return owner; | |
| 48 | + }; | |
| 49 | +} |
added src/styles.css +306 −0
| @@ -0,0 +1,306 @@ | ||
| 1 | +/* VibeCodeViewer · fable_version — HUD estilo holograma noventero */ | |
| 2 | +:root { | |
| 3 | + --cyan: #2ee6ff; | |
| 4 | + --cyan-dim: rgba(46, 230, 255, 0.55); | |
| 5 | + --panel-bg: rgba(3, 10, 16, 0.82); | |
| 6 | + --panel-border: rgba(46, 230, 255, 0.22); | |
| 7 | + --text: #bfeef6; | |
| 8 | +} | |
| 9 | + | |
| 10 | +* { margin: 0; padding: 0; box-sizing: border-box; } | |
| 11 | + | |
| 12 | +html, body { width: 100%; height: 100%; overflow: hidden; background: #020309; } | |
| 13 | + | |
| 14 | +body { | |
| 15 | + font-family: "JetBrains Mono", "Cascadia Code", "Fira Code", monospace; | |
| 16 | + color: var(--text); | |
| 17 | + font-size: 13px; | |
| 18 | +} | |
| 19 | + | |
| 20 | +#view { position: fixed; inset: 0; width: 100%; height: 100%; display: block; } | |
| 21 | + | |
| 22 | +.title { | |
| 23 | + color: var(--cyan); | |
| 24 | + font-size: 11px; | |
| 25 | + letter-spacing: 0.18em; | |
| 26 | + text-transform: uppercase; | |
| 27 | + margin-bottom: 8px; | |
| 28 | +} | |
| 29 | + | |
| 30 | +/* ── stats ─────────────────────────────────────────────── */ | |
| 31 | +#stats { | |
| 32 | + position: fixed; top: 12px; left: 16px; | |
| 33 | + color: rgba(170, 220, 235, 0.6); | |
| 34 | + font-size: 12px; | |
| 35 | + pointer-events: none; | |
| 36 | + text-shadow: 0 0 8px rgba(0, 0, 0, 0.8); | |
| 37 | +} | |
| 38 | + | |
| 39 | +/* ── botones de vista ──────────────────────────────────── */ | |
| 40 | +#view-buttons { | |
| 41 | + position: fixed; top: 36px; left: 16px; | |
| 42 | + display: flex; flex-direction: column; gap: 8px; | |
| 43 | +} | |
| 44 | +#view-buttons button { | |
| 45 | + font: inherit; | |
| 46 | + color: var(--text); | |
| 47 | + background: var(--panel-bg); | |
| 48 | + border: 1px solid var(--panel-border); | |
| 49 | + border-radius: 4px; | |
| 50 | + padding: 8px 18px; | |
| 51 | + cursor: pointer; | |
| 52 | + text-align: left; | |
| 53 | + backdrop-filter: blur(4px); | |
| 54 | + transition: border-color 0.15s, color 0.15s, box-shadow 0.15s; | |
| 55 | +} | |
| 56 | +#view-buttons button:hover { | |
| 57 | + color: #ffffff; | |
| 58 | + border-color: var(--cyan); | |
| 59 | + box-shadow: 0 0 14px rgba(46, 230, 255, 0.25), inset 0 0 10px rgba(46, 230, 255, 0.08); | |
| 60 | +} | |
| 61 | +#view-buttons button.off { color: rgba(140, 195, 210, 0.4); border-style: dashed; } | |
| 62 | +#view-buttons button:disabled { color: rgba(140, 195, 210, 0.5); cursor: progress; } | |
| 63 | +#view-buttons select { | |
| 64 | + font: inherit; | |
| 65 | + color: var(--text); | |
| 66 | + background: var(--panel-bg); | |
| 67 | + border: 1px solid var(--panel-border); | |
| 68 | + border-radius: 4px; | |
| 69 | + padding: 8px 12px; | |
| 70 | + cursor: pointer; | |
| 71 | + backdrop-filter: blur(4px); | |
| 72 | +} | |
| 73 | +#view-buttons select:hover { border-color: var(--cyan); } | |
| 74 | +#view-buttons select option { background: #04121a; color: var(--text); } | |
| 75 | +body.light #view-buttons select option { background: #fcfbf9; } | |
| 76 | + | |
| 77 | +/* ── selector de modo de coloreado ─────────────────────── */ | |
| 78 | +#mode-switch { | |
| 79 | + position: fixed; top: 12px; left: 50%; | |
| 80 | + transform: translateX(-50%); | |
| 81 | + display: flex; | |
| 82 | + background: var(--panel-bg); | |
| 83 | + border: 1px solid var(--panel-border); | |
| 84 | + border-radius: 6px; | |
| 85 | + overflow: hidden; | |
| 86 | + backdrop-filter: blur(4px); | |
| 87 | +} | |
| 88 | +#mode-switch button { | |
| 89 | + font: inherit; | |
| 90 | + color: rgba(170, 220, 235, 0.65); | |
| 91 | + background: transparent; | |
| 92 | + border: none; | |
| 93 | + border-right: 1px solid var(--panel-border); | |
| 94 | + padding: 8px 20px; | |
| 95 | + cursor: pointer; | |
| 96 | + letter-spacing: 0.06em; | |
| 97 | +} | |
| 98 | +#mode-switch button:last-child { border-right: none; } | |
| 99 | +#mode-switch button:focus { outline: none; } | |
| 100 | +#mode-switch button:hover { color: #ffffff; } | |
| 101 | +#mode-switch button.active { | |
| 102 | + color: #03191e; | |
| 103 | + background: var(--cyan); | |
| 104 | + text-shadow: none; | |
| 105 | +} | |
| 106 | +#mode-switch button:disabled { | |
| 107 | + color: rgba(120, 150, 165, 0.3); | |
| 108 | + cursor: not-allowed; | |
| 109 | +} | |
| 110 | + | |
| 111 | +/* ── columna derecha: leyenda de colores apilada sobre la ayuda ── */ | |
| 112 | +#right-stack { | |
| 113 | + position: fixed; right: 16px; bottom: 56px; | |
| 114 | + display: flex; flex-direction: column; gap: 8px; | |
| 115 | + align-items: stretch; | |
| 116 | +} | |
| 117 | + | |
| 118 | +#color-legend { | |
| 119 | + display: none; | |
| 120 | + flex-direction: column; gap: 5px; | |
| 121 | + background: var(--panel-bg); | |
| 122 | + border: 1px solid var(--panel-border); | |
| 123 | + border-radius: 6px; | |
| 124 | + padding: 10px 14px; | |
| 125 | + backdrop-filter: blur(4px); | |
| 126 | + font-size: 11.5px; | |
| 127 | + max-height: 38vh; overflow-y: auto; | |
| 128 | +} | |
| 129 | +#color-legend.show { display: flex; } | |
| 130 | +#color-legend .entry { display: flex; align-items: center; gap: 8px; } | |
| 131 | +#color-legend .swatch { | |
| 132 | + width: 12px; height: 12px; border-radius: 2px; | |
| 133 | + box-shadow: 0 0 8px currentColor; | |
| 134 | +} | |
| 135 | + | |
| 136 | +/* ── stats git en el árbol ─────────────────────────────── */ | |
| 137 | +.row .gwrap { display: none; margin-left: auto; align-items: center; gap: 6px; } | |
| 138 | +body.mode-git .row .gwrap { display: inline-flex; } | |
| 139 | +body.mode-git .row .meta { display: none; } | |
| 140 | +.gadd { color: #3fe06b; font-size: 10.5px; } | |
| 141 | +.gdel { color: #ff5f56; font-size: 10.5px; } | |
| 142 | +.gicon { | |
| 143 | + font-size: 10px; font-weight: bold; | |
| 144 | + width: 14px; height: 14px; line-height: 14px; | |
| 145 | + text-align: center; border-radius: 3px; | |
| 146 | +} | |
| 147 | +.gicon.gM { color: #0c0800; background: #f2a825; } | |
| 148 | +.gicon.gU, .gicon.gA { color: #03140a; background: #34d058; } | |
| 149 | +.gicon.gR { color: #020a14; background: #4d8fff; } | |
| 150 | +.gicon.gD { color: #140202; background: #ff4444; } | |
| 151 | + | |
| 152 | +/* ── buscador ──────────────────────────────────────────── */ | |
| 153 | +#search-panel { | |
| 154 | + position: fixed; top: 12px; right: 16px; | |
| 155 | + width: 330px; | |
| 156 | + background: var(--panel-bg); | |
| 157 | + border: 1px solid var(--panel-border); | |
| 158 | + border-radius: 6px; | |
| 159 | + padding: 12px; | |
| 160 | + backdrop-filter: blur(4px); | |
| 161 | +} | |
| 162 | +#search-input { | |
| 163 | + width: 100%; | |
| 164 | + font: inherit; | |
| 165 | + color: #e6feff; | |
| 166 | + background: rgba(8, 22, 32, 0.9); | |
| 167 | + border: 1px solid rgba(46, 230, 255, 0.3); | |
| 168 | + border-radius: 4px; | |
| 169 | + padding: 8px 10px; | |
| 170 | + outline: none; | |
| 171 | +} | |
| 172 | +#search-input:focus { border-color: var(--cyan); box-shadow: 0 0 12px rgba(46, 230, 255, 0.25); } | |
| 173 | +#search-input::placeholder { color: rgba(150, 200, 215, 0.4); } | |
| 174 | + | |
| 175 | +#search-results { display: none; max-height: 46vh; overflow-y: auto; margin-top: 8px; } | |
| 176 | +#search-results.show { display: block; } | |
| 177 | +.result { | |
| 178 | + padding: 6px 8px; | |
| 179 | + border-radius: 3px; | |
| 180 | + cursor: pointer; | |
| 181 | + display: flex; flex-direction: column; gap: 1px; | |
| 182 | +} | |
| 183 | +.result:hover { background: rgba(46, 230, 255, 0.12); } | |
| 184 | +.result .rname { color: #d9feff; } | |
| 185 | +.result .rpath { color: rgba(140, 195, 210, 0.55); font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } | |
| 186 | + | |
| 187 | +/* ── árbol lateral ─────────────────────────────────────── */ | |
| 188 | +#tree-panel { | |
| 189 | + position: fixed; left: 16px; bottom: 56px; | |
| 190 | + width: 320px; max-height: 56vh; | |
| 191 | + display: flex; flex-direction: column; | |
| 192 | + background: var(--panel-bg); | |
| 193 | + border: 1px solid var(--panel-border); | |
| 194 | + border-radius: 6px; | |
| 195 | + padding: 12px 0 6px; | |
| 196 | + backdrop-filter: blur(4px); | |
| 197 | +} | |
| 198 | +#tree-panel .title { padding: 0 12px; } | |
| 199 | +#tree { overflow-y: auto; flex: 1; } | |
| 200 | + | |
| 201 | +.row { | |
| 202 | + display: flex; align-items: center; gap: 6px; | |
| 203 | + padding: 3px 10px 3px 8px; | |
| 204 | + cursor: pointer; | |
| 205 | + white-space: nowrap; | |
| 206 | + border-left: 2px solid transparent; | |
| 207 | +} | |
| 208 | +.row:hover { background: rgba(46, 230, 255, 0.08); } | |
| 209 | +.row .name { overflow: hidden; text-overflow: ellipsis; } | |
| 210 | +.row .meta { margin-left: auto; color: rgba(140, 195, 210, 0.45); font-size: 11px; } | |
| 211 | +.row.dir .name { color: #8fd8e8; } | |
| 212 | +.row.dir .caret { width: 0; height: 0; border: 4px solid transparent; border-left-color: var(--cyan-dim); transition: transform 0.12s; } | |
| 213 | +.row.dir.open .caret { transform: rotate(90deg) translateX(-2px); } | |
| 214 | +.row.file .name { color: rgba(190, 235, 245, 0.8); } | |
| 215 | +.row.selected { | |
| 216 | + background: rgba(46, 230, 255, 0.18); | |
| 217 | + border-left-color: var(--cyan); | |
| 218 | +} | |
| 219 | +.row.selected .name { color: #ffffff !important; text-shadow: 0 0 8px var(--cyan); } | |
| 220 | +.row.basement .name { color: rgba(200, 160, 120, 0.65); font-style: italic; } | |
| 221 | + | |
| 222 | +/* cursor de navegación por teclado */ | |
| 223 | +#tree:focus { outline: none; } | |
| 224 | +#tree-panel:focus-within { border-color: var(--cyan); } | |
| 225 | +.row.cursor { | |
| 226 | + outline: 1px dashed var(--cyan-dim); | |
| 227 | + outline-offset: -1px; | |
| 228 | +} | |
| 229 | + | |
| 230 | +/* ── ruta inferior ─────────────────────────────────────── */ | |
| 231 | +#pathbar { | |
| 232 | + position: fixed; left: 16px; right: 16px; bottom: 12px; | |
| 233 | + background: var(--panel-bg); | |
| 234 | + border: 1px solid var(--panel-border); | |
| 235 | + border-radius: 6px; | |
| 236 | + padding: 9px 14px; | |
| 237 | + backdrop-filter: blur(4px); | |
| 238 | + overflow: hidden; white-space: nowrap; text-overflow: ellipsis; | |
| 239 | +} | |
| 240 | +#pathbar .sep { color: rgba(46, 230, 255, 0.4); margin: 0 4px; } | |
| 241 | +#pathbar .seg { color: #9adfee; } | |
| 242 | +#pathbar .seg.last { | |
| 243 | + color: #03191e; | |
| 244 | + background: var(--cyan); | |
| 245 | + border-radius: 3px; | |
| 246 | + padding: 2px 8px; | |
| 247 | + text-shadow: none; | |
| 248 | + box-shadow: 0 0 14px rgba(46, 230, 255, 0.6); | |
| 249 | +} | |
| 250 | +#pathbar .dim { color: rgba(140, 195, 210, 0.4); } | |
| 251 | + | |
| 252 | +/* ── ayuda ─────────────────────────────────────────────── */ | |
| 253 | +#help { | |
| 254 | + background: var(--panel-bg); | |
| 255 | + border: 1px solid var(--panel-border); | |
| 256 | + border-radius: 6px; | |
| 257 | + padding: 12px 14px; | |
| 258 | + backdrop-filter: blur(4px); | |
| 259 | + font-size: 11.5px; | |
| 260 | +} | |
| 261 | +#help td { padding: 1.5px 0; color: rgba(170, 220, 235, 0.75); } | |
| 262 | +#help td:first-child { color: var(--cyan); padding-right: 14px; } | |
| 263 | + | |
| 264 | +/* ── modo vuelo ────────────────────────────────────────── */ | |
| 265 | +#crosshair { | |
| 266 | + position: fixed; left: 50%; top: 50%; | |
| 267 | + transform: translate(-50%, -50%); | |
| 268 | + color: var(--cyan); | |
| 269 | + font-size: 22px; | |
| 270 | + text-shadow: 0 0 10px var(--cyan); | |
| 271 | + display: none; | |
| 272 | + pointer-events: none; | |
| 273 | +} | |
| 274 | +body.flying #crosshair { display: block; } | |
| 275 | +body.flying #tree-panel, body.flying #right-stack, body.flying #search-panel { opacity: 0.25; } | |
| 276 | + | |
| 277 | +/* scrollbars discretas */ | |
| 278 | +::-webkit-scrollbar { width: 8px; } | |
| 279 | +::-webkit-scrollbar-track { background: transparent; } | |
| 280 | +::-webkit-scrollbar-thumb { background: rgba(46, 230, 255, 0.2); border-radius: 4px; } | |
| 281 | + | |
| 282 | +/* ── tema claro (p. ej. Factorial): textos fijos que no usan variables ── */ | |
| 283 | +body.light { background: #f4f2ee; } | |
| 284 | +body.light #stats { color: rgba(30, 70, 78, 0.75); text-shadow: none; } | |
| 285 | +body.light .row.dir .name { color: #00646d; } | |
| 286 | +body.light .row.file .name { color: rgba(25, 60, 66, 0.85); } | |
| 287 | +body.light .row .meta, | |
| 288 | +body.light #help td { color: rgba(40, 90, 98, 0.7); } | |
| 289 | +body.light #help td:first-child { color: var(--cyan); } | |
| 290 | +body.light .row:hover { background: rgba(0, 124, 133, 0.10); } | |
| 291 | +body.light .row.selected { background: rgba(229, 25, 67, 0.14); } | |
| 292 | +body.light .row.selected .name { color: #7c0c24 !important; text-shadow: none; } | |
| 293 | +body.light .row.basement .name { color: rgba(150, 100, 40, 0.8); } | |
| 294 | +body.light #search-input { background: rgba(255, 255, 255, 0.85); color: #143a40; } | |
| 295 | +body.light #search-input::placeholder { color: rgba(40, 90, 98, 0.45); } | |
| 296 | +body.light .result .rname { color: #143a40; } | |
| 297 | +body.light .result .rpath { color: rgba(40, 90, 98, 0.6); } | |
| 298 | +body.light .result:hover { background: rgba(0, 124, 133, 0.10); } | |
| 299 | +body.light #pathbar .seg { color: #00646d; } | |
| 300 | +body.light #pathbar .seg.last { color: #ffffff; } | |
| 301 | +body.light #pathbar .dim { color: rgba(40, 90, 98, 0.5); } | |
| 302 | +body.light #mode-switch button { color: rgba(30, 70, 78, 0.7); } | |
| 303 | +body.light #mode-switch button.active { color: #ffffff; } | |
| 304 | +body.light #mode-switch button:hover:not(.active):not(:disabled) { color: #00323a; } | |
| 305 | +body.light #view-buttons button:hover { color: #00323a; } | |
| 306 | +body.light ::-webkit-scrollbar-thumb { background: rgba(0, 124, 133, 0.3); } |
added src/themes.js +188 −0
| @@ -0,0 +1,188 @@ | ||
| 1 | +// Temas de color. Cada tema define la paleta completa de la escena y de la | |
| 2 | +// UI (variables CSS). Los temas `light: true` cambian el blending aditivo | |
| 3 | +// por normal (sobre fondo claro lo aditivo desaparece) y contienen el bloom. | |
| 4 | +// | |
| 5 | +// Campos: | |
| 6 | +// roleColor aristas por nivel · hi: color HDR de resaltado de aristas | |
| 7 | +// fileBase/fileHi celdas de fichero (reposo / seleccionada) | |
| 8 | +// glass/glassHi cristal fresnel (reposo / encendido) | |
| 9 | +// ground placa de circuito: fondo, rejilla y pistas A/B con sus pads | |
| 10 | +// facade texto del árbol impreso en fachada | |
| 11 | +// labels serigrafiados de leyenda (distrito / urbanización / tejado) | |
| 12 | +// beam/fill/slab haces blast · rellenos encendidos · forjados | |
| 13 | +// css variables de la interfaz (--cyan, --panel-bg, …) | |
| 14 | + | |
| 15 | +export const THEMES = { | |
| 16 | + hacker: { | |
| 17 | + label: 'Hacker', | |
| 18 | + light: false, | |
| 19 | + background: 0x020309, fog: 0x030510, | |
| 20 | + bloom: { strength: 0.65, threshold: 0.85 }, | |
| 21 | + roleColor: { | |
| 22 | + distrito: [0.16, 0.07, 0.30], urbanizacion: [0.13, 0.09, 0.30], | |
| 23 | + edificio: [0.10, 0.30, 0.36], planta: [0.06, 0.20, 0.26], | |
| 24 | + apartamento: [0.05, 0.16, 0.21], habitacion: [0.045, 0.13, 0.18], | |
| 25 | + archivador: [0.04, 0.11, 0.15], cajon: [0.035, 0.10, 0.13], | |
| 26 | + }, | |
| 27 | + hi: [0.28, 3.0, 3.6], | |
| 28 | + fileBase: [0.05, 0.22, 0.28], fileHi: [1.0, 5.0, 6.0], | |
| 29 | + glass: [0.12, 0.55, 0.65], glassHi: [0.3, 2.4, 2.8], | |
| 30 | + ground: { | |
| 31 | + bg: '#04050b', grid: 'rgba(50, 80, 140, 0.07)', | |
| 32 | + traceA: [112, 60, 235], traceB: [40, 200, 235], | |
| 33 | + padA: [170, 120, 255], padB: [120, 240, 255], | |
| 34 | + }, | |
| 35 | + facade: { | |
| 36 | + text: 'rgba(140, 232, 250, 0.72)', hot: '#c8ffff', | |
| 37 | + hotGlow: 'rgba(0,255,255,0.9)', hotBg: 'rgba(0,255,255,0.16)', | |
| 38 | + }, | |
| 39 | + labels: { district: '#a86cff', urb: '#8a7bff', building: '#49e8ff' }, | |
| 40 | + beam: [2.6, 1.1, 0.25], beamIn: [3.4, 0.5, 0.8], fill: [0.08, 0.75, 0.95], slab: [0.1, 0.5, 0.6], | |
| 41 | + gitColors: { M: [0.95, 0.65, 0.10], A: [0.15, 0.85, 0.45], U: [0.20, 0.90, 0.30], R: [0.30, 0.55, 1.00], D: [1.00, 0.25, 0.25] }, | |
| 42 | + ownerHsl: { s: 0.85, l: 0.55, offset: 24 }, | |
| 43 | + css: { | |
| 44 | + cyan: '#2ee6ff', 'cyan-dim': 'rgba(46, 230, 255, 0.55)', | |
| 45 | + 'panel-bg': 'rgba(3, 10, 16, 0.82)', 'panel-border': 'rgba(46, 230, 255, 0.22)', | |
| 46 | + text: '#bfeef6', | |
| 47 | + }, | |
| 48 | + }, | |
| 49 | + | |
| 50 | + factorial: { | |
| 51 | + label: 'Factorial', | |
| 52 | + // solo los dos colores de marca sobre fondo oscuro: radical red #E51943 | |
| 53 | + // dominante y verde #007C85 como secundario estructural | |
| 54 | + light: false, | |
| 55 | + uiLight: true, // paneles de la interfaz en claro | |
| 56 | + background: 0x0e0309, fog: 0x140510, | |
| 57 | + bloom: { strength: 0.65, threshold: 0.85 }, | |
| 58 | + roleColor: { | |
| 59 | + distrito: [0.00, 0.30, 0.33], urbanizacion: [0.02, 0.26, 0.29], | |
| 60 | + edificio: [0.46, 0.07, 0.15], planta: [0.34, 0.06, 0.12], | |
| 61 | + apartamento: [0.28, 0.06, 0.11], habitacion: [0.22, 0.07, 0.11], | |
| 62 | + archivador: [0.16, 0.09, 0.11], cajon: [0.10, 0.11, 0.12], | |
| 63 | + }, | |
| 64 | + hi: [3.8, 0.42, 1.1], | |
| 65 | + fileBase: [0.34, 0.05, 0.11], fileHi: [4.8, 0.5, 1.4], | |
| 66 | + glass: [0.55, 0.10, 0.20], glassHi: [2.6, 0.30, 0.85], | |
| 67 | + ground: { | |
| 68 | + bg: '#0c0207', grid: 'rgba(229, 25, 67, 0.07)', | |
| 69 | + traceA: [229, 25, 67], traceB: [0, 156, 167], | |
| 70 | + padA: [255, 90, 125], padB: [60, 200, 210], | |
| 71 | + }, | |
| 72 | + facade: { | |
| 73 | + text: 'rgba(255, 150, 175, 0.72)', hot: '#ffd0da', | |
| 74 | + hotGlow: 'rgba(229,25,67,0.9)', hotBg: 'rgba(229,25,67,0.18)', | |
| 75 | + }, | |
| 76 | + labels: { district: '#00b8c4', urb: '#2cc5cf', building: '#ff4a6e' }, | |
| 77 | + beam: [3.2, 0.6, 0.9], beamIn: [0.4, 2.6, 2.8], fill: [0.95, 0.15, 0.35], slab: [0.45, 0.10, 0.18], | |
| 78 | + gitColors: { M: [1.00, 0.25, 0.40], A: [0.20, 0.95, 0.85], U: [0.00, 0.85, 0.90], R: [0.95, 0.85, 0.90], D: [0.60, 0.05, 0.10] }, | |
| 79 | + ownerHsl: { s: 0.70, l: 0.60, offset: 340 }, | |
| 80 | + css: { | |
| 81 | + cyan: '#E51943', 'cyan-dim': 'rgba(229, 25, 67, 0.55)', | |
| 82 | + 'panel-bg': 'rgba(252, 251, 249, 0.88)', 'panel-border': 'rgba(0, 124, 133, 0.35)', | |
| 83 | + text: '#16444a', | |
| 84 | + }, | |
| 85 | + }, | |
| 86 | + | |
| 87 | + synthwave: { | |
| 88 | + label: 'Synthwave', | |
| 89 | + light: false, | |
| 90 | + background: 0x0d0221, fog: 0x190b33, | |
| 91 | + bloom: { strength: 0.8, threshold: 0.8 }, | |
| 92 | + roleColor: { | |
| 93 | + distrito: [0.30, 0.05, 0.25], urbanizacion: [0.26, 0.06, 0.24], | |
| 94 | + edificio: [0.36, 0.08, 0.30], planta: [0.26, 0.06, 0.22], | |
| 95 | + apartamento: [0.22, 0.05, 0.18], habitacion: [0.18, 0.05, 0.15], | |
| 96 | + archivador: [0.15, 0.04, 0.12], cajon: [0.12, 0.04, 0.10], | |
| 97 | + }, | |
| 98 | + hi: [3.6, 0.5, 2.2], | |
| 99 | + fileBase: [0.30, 0.10, 0.05], fileHi: [5.0, 2.2, 0.4], | |
| 100 | + glass: [0.55, 0.15, 0.45], glassHi: [2.8, 0.5, 1.8], | |
| 101 | + ground: { | |
| 102 | + bg: '#0c0220', grid: 'rgba(255, 80, 180, 0.06)', | |
| 103 | + traceA: [255, 60, 170], traceB: [255, 150, 40], | |
| 104 | + padA: [255, 130, 210], padB: [255, 200, 90], | |
| 105 | + }, | |
| 106 | + facade: { | |
| 107 | + text: 'rgba(255, 170, 220, 0.70)', hot: '#ffd9f0', | |
| 108 | + hotGlow: 'rgba(255,80,200,0.9)', hotBg: 'rgba(255,80,200,0.16)', | |
| 109 | + }, | |
| 110 | + labels: { district: '#ff9a3c', urb: '#ff7bd5', building: '#ff4fc3' }, | |
| 111 | + beam: [3.2, 1.4, 0.2], beamIn: [0.5, 2.8, 1.2], fill: [0.95, 0.20, 0.65], slab: [0.5, 0.12, 0.4], | |
| 112 | + gitColors: { M: [1.00, 0.60, 0.10], A: [0.20, 0.90, 0.60], U: [0.30, 1.00, 0.75], R: [0.50, 0.70, 1.00], D: [1.00, 0.20, 0.30] }, | |
| 113 | + ownerHsl: { s: 0.90, l: 0.65, offset: 300 }, | |
| 114 | + css: { | |
| 115 | + cyan: '#ff4fc3', 'cyan-dim': 'rgba(255, 79, 195, 0.55)', | |
| 116 | + 'panel-bg': 'rgba(16, 3, 34, 0.84)', 'panel-border': 'rgba(255, 79, 195, 0.28)', | |
| 117 | + text: '#ffd6ef', | |
| 118 | + }, | |
| 119 | + }, | |
| 120 | + | |
| 121 | + matrix: { | |
| 122 | + label: 'Matrix', | |
| 123 | + light: false, | |
| 124 | + background: 0x010401, fog: 0x021006, | |
| 125 | + bloom: { strength: 0.7, threshold: 0.85 }, | |
| 126 | + roleColor: { | |
| 127 | + distrito: [0.04, 0.22, 0.06], urbanizacion: [0.04, 0.20, 0.06], | |
| 128 | + edificio: [0.06, 0.34, 0.10], planta: [0.04, 0.24, 0.07], | |
| 129 | + apartamento: [0.035, 0.20, 0.06], habitacion: [0.03, 0.16, 0.05], | |
| 130 | + archivador: [0.025, 0.13, 0.04], cajon: [0.02, 0.11, 0.035], | |
| 131 | + }, | |
| 132 | + hi: [0.5, 3.8, 0.9], | |
| 133 | + fileBase: [0.06, 0.26, 0.08], fileHi: [1.2, 6.0, 1.6], | |
| 134 | + glass: [0.10, 0.55, 0.18], glassHi: [0.4, 2.8, 0.7], | |
| 135 | + ground: { | |
| 136 | + bg: '#020703', grid: 'rgba(40, 140, 60, 0.08)', | |
| 137 | + traceA: [30, 160, 60], traceB: [120, 230, 120], | |
| 138 | + padA: [80, 220, 100], padB: [190, 255, 190], | |
| 139 | + }, | |
| 140 | + facade: { | |
| 141 | + text: 'rgba(140, 250, 160, 0.72)', hot: '#d8ffd8', | |
| 142 | + hotGlow: 'rgba(60,255,120,0.9)', hotBg: 'rgba(60,255,120,0.14)', | |
| 143 | + }, | |
| 144 | + labels: { district: '#3fcf6a', urb: '#5fdf85', building: '#8cfa9f' }, | |
| 145 | + beam: [2.4, 3.0, 0.3], beamIn: [3.4, 1.2, 0.3], fill: [0.15, 0.9, 0.3], slab: [0.08, 0.45, 0.14], | |
| 146 | + gitColors: { M: [1.00, 0.85, 0.20], A: [0.25, 0.90, 0.35], U: [0.40, 1.00, 0.45], R: [0.80, 1.00, 0.80], D: [1.00, 0.30, 0.20] }, | |
| 147 | + ownerHsl: { s: 0.60, l: 0.60, offset: 90 }, | |
| 148 | + css: { | |
| 149 | + cyan: '#41ff7a', 'cyan-dim': 'rgba(65, 255, 122, 0.55)', | |
| 150 | + 'panel-bg': 'rgba(2, 12, 5, 0.84)', 'panel-border': 'rgba(65, 255, 122, 0.25)', | |
| 151 | + text: '#c0f5cc', | |
| 152 | + }, | |
| 153 | + }, | |
| 154 | + | |
| 155 | + glaciar: { | |
| 156 | + label: 'Glaciar', | |
| 157 | + light: false, | |
| 158 | + background: 0x050a14, fog: 0x081020, | |
| 159 | + bloom: { strength: 0.6, threshold: 0.87 }, | |
| 160 | + roleColor: { | |
| 161 | + distrito: [0.08, 0.14, 0.34], urbanizacion: [0.08, 0.13, 0.30], | |
| 162 | + edificio: [0.16, 0.30, 0.46], planta: [0.11, 0.22, 0.36], | |
| 163 | + apartamento: [0.09, 0.18, 0.30], habitacion: [0.08, 0.15, 0.25], | |
| 164 | + archivador: [0.07, 0.13, 0.21], cajon: [0.06, 0.11, 0.18], | |
| 165 | + }, | |
| 166 | + hi: [1.8, 2.8, 4.2], | |
| 167 | + fileBase: [0.14, 0.20, 0.30], fileHi: [3.0, 4.5, 6.5], | |
| 168 | + glass: [0.30, 0.45, 0.65], glassHi: [1.2, 2.0, 3.0], | |
| 169 | + ground: { | |
| 170 | + bg: '#060c18', grid: 'rgba(120, 160, 220, 0.07)', | |
| 171 | + traceA: [70, 120, 230], traceB: [200, 225, 255], | |
| 172 | + padA: [130, 180, 255], padB: [240, 248, 255], | |
| 173 | + }, | |
| 174 | + facade: { | |
| 175 | + text: 'rgba(200, 225, 255, 0.72)', hot: '#ffffff', | |
| 176 | + hotGlow: 'rgba(170,210,255,0.95)', hotBg: 'rgba(170,210,255,0.16)', | |
| 177 | + }, | |
| 178 | + labels: { district: '#7aa2ff', urb: '#9ab8ff', building: '#cfe2ff' }, | |
| 179 | + beam: [2.8, 2.2, 0.8], beamIn: [3.4, 0.8, 0.6], fill: [0.45, 0.65, 1.0], slab: [0.25, 0.38, 0.6], | |
| 180 | + gitColors: { M: [1.00, 0.70, 0.30], A: [0.40, 0.85, 0.95], U: [0.50, 0.95, 1.00], R: [0.60, 0.70, 1.00], D: [1.00, 0.35, 0.35] }, | |
| 181 | + ownerHsl: { s: 0.65, l: 0.65, offset: 200 }, | |
| 182 | + css: { | |
| 183 | + cyan: '#9cc8ff', 'cyan-dim': 'rgba(156, 200, 255, 0.55)', | |
| 184 | + 'panel-bg': 'rgba(5, 12, 24, 0.84)', 'panel-border': 'rgba(156, 200, 255, 0.25)', | |
| 185 | + text: '#dbe9ff', | |
| 186 | + }, | |
| 187 | + }, | |
| 188 | +}; |
added src/ui.js +396 −0
| @@ -0,0 +1,396 @@ | ||
| 1 | +// Interfaz HTML: árbol lateral, buscador, botones de vista, ruta y stats. | |
| 2 | +// createUI se llama una sola vez; setModel() reconstruye el árbol cuando se | |
| 3 | +// carga otra carpeta raíz. | |
| 4 | +import { THEMES } from './themes.js'; | |
| 5 | + | |
| 6 | +function fmtSize(b) { | |
| 7 | + if (b < 1024) return `${b}`; | |
| 8 | + if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)}k`; | |
| 9 | + return `${(b / 1024 / 1024).toFixed(1)}M`; | |
| 10 | +} | |
| 11 | + | |
| 12 | +export function createUI(cb) { | |
| 13 | + const $ = id => document.getElementById(id); | |
| 14 | + const treeEl = $('tree'); | |
| 15 | + const pathEl = $('pathbar'); | |
| 16 | + const statsEl = $('stats'); | |
| 17 | + const resultsEl = $('search-results'); | |
| 18 | + const searchEl = $('search-input'); | |
| 19 | + | |
| 20 | + let model = null; | |
| 21 | + const fileRows = new Map(); // fileId → fila DOM | |
| 22 | + const nodeRows = new Map(); // nodeId → fila DOM | |
| 23 | + let selectedRow = null; | |
| 24 | + let selectedNodeRow = null; | |
| 25 | + | |
| 26 | + // ── árbol lateral (perezoso: los hijos se montan al expandir) ─────── | |
| 27 | + // imprescindible en monorepos: cientos de miles de filas no caben en DOM | |
| 28 | + const dirEntries = new Map(); // nodeId → { row, kids, depth, rendered } | |
| 29 | + | |
| 30 | + const rowFile = new WeakMap(); // fila DOM → fichero (navegación por teclado) | |
| 31 | + const rowNode = new WeakMap(); // fila DOM → nodo dir | |
| 32 | + | |
| 33 | + function addFileRow(container, f, depth, basement) { | |
| 34 | + const row = document.createElement('div'); | |
| 35 | + rowFile.set(row, f); | |
| 36 | + row.className = 'row file' + (basement ? ' basement' : ''); | |
| 37 | + row.style.paddingLeft = `${depth * 14 + 8}px`; | |
| 38 | + // stats e icono de estado git (visibles solo en modo git) | |
| 39 | + let gitHtml = ''; | |
| 40 | + if (f.git) { | |
| 41 | + const stats = (f.git.a || f.git.d) | |
| 42 | + ? `<span class="gadd">+${f.git.a}</span><span class="gdel">−${f.git.d}</span>` : ''; | |
| 43 | + gitHtml = `<span class="gwrap">${stats}<span class="gicon g${f.git.st}">${f.git.st}</span></span>`; | |
| 44 | + } | |
| 45 | + row.innerHTML = `<span class="name">${f.name}</span>${gitHtml}<span class="meta">${fmtSize(f.size)}</span>`; | |
| 46 | + row.addEventListener('click', () => cb.onSelectFile?.(f)); | |
| 47 | + fileRows.set(f.id, row); | |
| 48 | + container.appendChild(row); | |
| 49 | + } | |
| 50 | + | |
| 51 | + function addDirRow(container, node, depth) { | |
| 52 | + const row = document.createElement('div'); | |
| 53 | + rowNode.set(row, node); | |
| 54 | + const label = node.isBasement ? `${node.name} · sótano` : node.name; | |
| 55 | + row.className = 'row dir' + (node.isBasement ? ' basement' : ''); | |
| 56 | + row.style.paddingLeft = `${depth * 14 + 8}px`; | |
| 57 | + row.innerHTML = `<span class="caret"></span><span class="name">${label}</span><span class="meta">${node.fileIds.length + node.children.length || ''}</span>`; | |
| 58 | + const kids = document.createElement('div'); | |
| 59 | + kids.style.display = 'none'; | |
| 60 | + dirEntries.set(node.id, { row, kids, depth, rendered: false }); | |
| 61 | + nodeRows.set(node.id, row); | |
| 62 | + row.addEventListener('click', () => { | |
| 63 | + const open = row.classList.toggle('open'); | |
| 64 | + if (open) renderChildren(node); | |
| 65 | + kids.style.display = open ? '' : 'none'; | |
| 66 | + cb.onSelectNode?.(node); | |
| 67 | + }); | |
| 68 | + container.append(row, kids); | |
| 69 | + } | |
| 70 | + | |
| 71 | + function renderChildren(node) { | |
| 72 | + const ent = dirEntries.get(node.id); | |
| 73 | + if (!ent || ent.rendered) return; | |
| 74 | + ent.rendered = true; | |
| 75 | + for (const c of node.children) addDirRow(ent.kids, c, ent.depth + 1); | |
| 76 | + const basement = node.isBasement || node.building?.isBasement; | |
| 77 | + for (const fid of node.fileIds) { | |
| 78 | + addFileRow(ent.kids, model.files[fid], ent.depth + 1, basement); | |
| 79 | + } | |
| 80 | + } | |
| 81 | + | |
| 82 | + // pliega/despliega una carpeta sin disparar la selección (teclado) | |
| 83 | + function toggleDir(node, open) { | |
| 84 | + const ent = dirEntries.get(node.id); | |
| 85 | + if (!ent) return; | |
| 86 | + if (open) renderChildren(node); | |
| 87 | + ent.row.classList.toggle('open', open); | |
| 88 | + ent.kids.style.display = open ? '' : 'none'; | |
| 89 | + } | |
| 90 | + | |
| 91 | + // ── navegación por teclado en el árbol ────────────────────────────── | |
| 92 | + treeEl.tabIndex = 0; | |
| 93 | + treeEl.addEventListener('pointerdown', () => treeEl.focus()); | |
| 94 | + let cursorRow = null; | |
| 95 | + | |
| 96 | + function setCursor(row, scroll = true) { | |
| 97 | + cursorRow?.classList.remove('cursor'); | |
| 98 | + cursorRow = row ?? null; | |
| 99 | + if (cursorRow) { | |
| 100 | + cursorRow.classList.add('cursor'); | |
| 101 | + if (scroll) cursorRow.scrollIntoView({ block: 'nearest' }); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 105 | + function visibleRows() { | |
| 106 | + return [...treeEl.querySelectorAll('.row')].filter(r => r.offsetParent !== null); | |
| 107 | + } | |
| 108 | + | |
| 109 | + treeEl.addEventListener('keydown', (e) => { | |
| 110 | + const rows = visibleRows(); | |
| 111 | + if (!rows.length) return; | |
| 112 | + const current = cursorRow && rows.includes(cursorRow) | |
| 113 | + ? cursorRow | |
| 114 | + : (selectedRow && rows.includes(selectedRow) ? selectedRow : rows[0]); | |
| 115 | + const idx = rows.indexOf(current); | |
| 116 | + const page = Math.max(3, Math.floor(treeEl.clientHeight / 24) - 2); | |
| 117 | + const node = rowNode.get(current); | |
| 118 | + const file = rowFile.get(current); | |
| 119 | + | |
| 120 | + switch (e.key) { | |
| 121 | + case 'ArrowDown': | |
| 122 | + setCursor(rows[Math.min(idx + 1, rows.length - 1)]); | |
| 123 | + break; | |
| 124 | + case 'ArrowUp': | |
| 125 | + setCursor(rows[Math.max(idx - 1, 0)]); | |
| 126 | + break; | |
| 127 | + case 'ArrowRight': | |
| 128 | + if (node) { | |
| 129 | + if (!current.classList.contains('open')) { toggleDir(node, true); setCursor(current); } | |
| 130 | + else setCursor(visibleRows()[idx + 1] ?? current); // entra al primer hijo | |
| 131 | + } | |
| 132 | + break; | |
| 133 | + case 'ArrowLeft': { | |
| 134 | + if (node && current.classList.contains('open')) { toggleDir(node, false); break; } | |
| 135 | + const parent = node ? node.parent : file?.node; | |
| 136 | + const pRow = parent && parent.role !== 'ciudad' ? nodeRows.get(parent.id) : null; | |
| 137 | + if (pRow) setCursor(pRow); | |
| 138 | + break; | |
| 139 | + } | |
| 140 | + case 'PageDown': | |
| 141 | + setCursor(rows[Math.min(idx + page, rows.length - 1)]); | |
| 142 | + break; | |
| 143 | + case 'PageUp': | |
| 144 | + setCursor(rows[Math.max(idx - page, 0)]); | |
| 145 | + break; | |
| 146 | + case 'Enter': | |
| 147 | + case ' ': | |
| 148 | + if (file) cb.onSelectFile?.(file, { fly: true }); | |
| 149 | + else if (node) { toggleDir(node, !current.classList.contains('open')); cb.onSelectNode?.(node); } | |
| 150 | + break; | |
| 151 | + default: | |
| 152 | + return; // no consumir otras teclas (F vuelo, etc.) | |
| 153 | + } | |
| 154 | + e.preventDefault(); | |
| 155 | + e.stopPropagation(); | |
| 156 | + }); | |
| 157 | + | |
| 158 | + // monta y abre la cadena de contenedores hasta `node` (incluido) | |
| 159 | + function ensureVisible(node) { | |
| 160 | + const chain = []; | |
| 161 | + for (let n = node; n && n.role !== 'ciudad'; n = n.parent) chain.push(n); | |
| 162 | + for (let i = chain.length - 1; i >= 0; i--) { | |
| 163 | + const ent = dirEntries.get(chain[i].id); | |
| 164 | + if (!ent) return; | |
| 165 | + renderChildren(chain[i]); | |
| 166 | + ent.row.classList.add('open'); | |
| 167 | + ent.kids.style.display = ''; | |
| 168 | + } | |
| 169 | + } | |
| 170 | + | |
| 171 | + function setModel(m) { | |
| 172 | + model = m; | |
| 173 | + fileRows.clear(); | |
| 174 | + nodeRows.clear(); | |
| 175 | + dirEntries.clear(); | |
| 176 | + selectedRow = null; | |
| 177 | + selectedNodeRow = null; | |
| 178 | + treeEl.innerHTML = ''; | |
| 179 | + for (const c of model.city.children) addDirRow(treeEl, c, 1); | |
| 180 | + for (const fid of model.city.fileIds) addFileRow(treeEl, model.files[fid], 1, false); | |
| 181 | + baseFileCount = model.files.filter(f => !f.node.building?.isBasement).length; | |
| 182 | + setPath(null); | |
| 183 | + setStats(0); | |
| 184 | + searchEl.value = ''; | |
| 185 | + hideResults(); | |
| 186 | + } | |
| 187 | + | |
| 188 | + function markFile(file) { | |
| 189 | + selectedRow?.classList.remove('selected'); | |
| 190 | + selectedRow = null; | |
| 191 | + if (file) { | |
| 192 | + ensureVisible(file.node); | |
| 193 | + selectedRow = fileRows.get(file.id) ?? null; | |
| 194 | + } | |
| 195 | + if (selectedRow) { | |
| 196 | + selectedRow.classList.add('selected'); | |
| 197 | + selectedRow.scrollIntoView({ block: 'center', behavior: 'smooth' }); | |
| 198 | + } | |
| 199 | + } | |
| 200 | + | |
| 201 | + // marca una carpeta/nivel (selección sincronizada ciudad ↔ árbol) | |
| 202 | + function markNode(node) { | |
| 203 | + selectedNodeRow?.classList.remove('selected'); | |
| 204 | + selectedNodeRow = null; | |
| 205 | + if (node) { | |
| 206 | + ensureVisible(node); | |
| 207 | + selectedNodeRow = nodeRows.get(node.id) ?? null; | |
| 208 | + } | |
| 209 | + if (selectedNodeRow) { | |
| 210 | + selectedNodeRow.classList.add('selected'); | |
| 211 | + selectedNodeRow.scrollIntoView({ block: 'center', behavior: 'smooth' }); | |
| 212 | + } | |
| 213 | + } | |
| 214 | + | |
| 215 | + // ── buscador (con wildcards: * dentro de segmento, ** cruza carpetas) ── | |
| 216 | + function termMatcher(t) { | |
| 217 | + if (!t.includes('*') && !t.includes('?')) { | |
| 218 | + return (f) => f.path.toLowerCase().includes(t); | |
| 219 | + } | |
| 220 | + const body = t | |
| 221 | + .replace(/[.+^${}()|[\]\\]/g, '\\$&') | |
| 222 | + .replace(/\*\*/g, ' |