Elffuss BraidHub

kikocis/VibeCodeViewer public

main · 21.3 KiBRawPermalink
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.
4import { THEMES } from './themes.js';
5import { applyDocumentTranslations, language, onLanguageChange, setLanguage, t } from './i18n.js';
6
7function fmtSize(b) {
8 if (b < 1024) return `${b}`;
9 if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)}k`;
10 return `${(b / 1024 / 1024).toFixed(1)}M`;
11}
12
13function textSpan(className, text) {
14 const el = document.createElement('span');
15 el.className = className;
16 el.textContent = text ?? '';
17 return el;
18}
19
20function safeGitStatus(status) {
21 return ['M', 'A', 'U', 'R', 'D'].includes(status) ? status : 'U';
22}
23
24export function createUI(cb) {
25 const $ = id => document.getElementById(id);
26 const treeEl = $('tree');
27 const pathEl = $('pathbar');
28 const statsEl = $('stats');
29 const resultsEl = $('search-results');
30 const searchEl = $('search-input');
31
32 let model = null;
33 const fileRows = new Map(); // fileId → fila DOM
34 const nodeRows = new Map(); // nodeId → fila DOM
35 let selectedRow = null;
36 let selectedNodeRow = null;
37
38 // ── árbol lateral (perezoso: los hijos se montan al expandir) ───────
39 // imprescindible en monorepos: cientos de miles de filas no caben en DOM
40 const dirEntries = new Map(); // nodeId → { row, kids, depth, rendered }
41
42 const rowFile = new WeakMap(); // fila DOM → fichero (navegación por teclado)
43 const rowNode = new WeakMap(); // fila DOM → nodo dir
44
45 function addFileRow(container, f, depth, basement) {
46 const row = document.createElement('div');
47 rowFile.set(row, f);
48 row.className = 'row file' + (basement ? ' basement' : '');
49 row.style.paddingLeft = `${depth * 14 + 8}px`;
50 row.appendChild(textSpan('name', f.name));
51 // stats e icono de estado git (visibles solo en modo git)
52 if (f.git) {
53 const gwrap = textSpan('gwrap', '');
54 if (f.git.a || f.git.d) {
55 gwrap.append(
56 textSpan('gadd', `+${Number(f.git.a) || 0}`),
57 textSpan('gdel', `−${Number(f.git.d) || 0}`),
58 );
59 }
60 const status = safeGitStatus(f.git.st);
61 gwrap.appendChild(textSpan(`gicon g${status}`, status));
62 row.appendChild(gwrap);
63 }
64 row.appendChild(textSpan('meta', fmtSize(f.size)));
65 row.addEventListener('click', () => cb.onSelectFile?.(f));
66 fileRows.set(f.id, row);
67 container.appendChild(row);
68 }
69
70 function addDirRow(container, node, depth) {
71 const row = document.createElement('div');
72 rowNode.set(row, node);
73 const label = node.isBasement ? `${node.name} · ${t('tree.basementSuffix')}` : node.name;
74 row.className = 'row dir' + (node.isBasement ? ' basement' : '');
75 row.dataset.name = node.name;
76 row.style.paddingLeft = `${depth * 14 + 8}px`;
77 row.append(
78 textSpan('caret', ''),
79 textSpan('name', label),
80 textSpan('meta', node.fileIds.length + node.children.length || ''),
81 );
82 const kids = document.createElement('div');
83 kids.style.display = 'none';
84 dirEntries.set(node.id, { row, kids, depth, rendered: false });
85 nodeRows.set(node.id, row);
86 row.addEventListener('click', () => {
87 const open = row.classList.toggle('open');
88 if (open) renderChildren(node);
89 kids.style.display = open ? '' : 'none';
90 cb.onSelectNode?.(node);
91 });
92 container.append(row, kids);
93 }
94
95 function renderChildren(node) {
96 const ent = dirEntries.get(node.id);
97 if (!ent || ent.rendered) return;
98 ent.rendered = true;
99 for (const c of node.children) addDirRow(ent.kids, c, ent.depth + 1);
100 const basement = node.isBasement || node.building?.isBasement;
101 for (const fid of node.fileIds) {
102 addFileRow(ent.kids, model.files[fid], ent.depth + 1, basement);
103 }
104 }
105
106 // pliega/despliega una carpeta sin disparar la selección (teclado)
107 function toggleDir(node, open) {
108 const ent = dirEntries.get(node.id);
109 if (!ent) return;
110 if (open) renderChildren(node);
111 ent.row.classList.toggle('open', open);
112 ent.kids.style.display = open ? '' : 'none';
113 }
114
115 // ── navegación por teclado en el árbol ──────────────────────────────
116 treeEl.tabIndex = 0;
117 treeEl.addEventListener('pointerdown', () => treeEl.focus());
118 let cursorRow = null;
119
120 function setCursor(row, scroll = true) {
121 cursorRow?.classList.remove('cursor');
122 cursorRow = row ?? null;
123 if (cursorRow) {
124 cursorRow.classList.add('cursor');
125 if (scroll) cursorRow.scrollIntoView({ block: 'nearest' });
126 }
127 }
128
129 function visibleRows() {
130 return [...treeEl.querySelectorAll('.row')].filter(r => r.offsetParent !== null);
131 }
132
133 treeEl.addEventListener('keydown', (e) => {
134 const rows = visibleRows();
135 if (!rows.length) return;
136 const current = cursorRow && rows.includes(cursorRow)
137 ? cursorRow
138 : (selectedRow && rows.includes(selectedRow) ? selectedRow : rows[0]);
139 const idx = rows.indexOf(current);
140 const page = Math.max(3, Math.floor(treeEl.clientHeight / 24) - 2);
141 const node = rowNode.get(current);
142 const file = rowFile.get(current);
143
144 switch (e.key) {
145 case 'ArrowDown':
146 setCursor(rows[Math.min(idx + 1, rows.length - 1)]);
147 break;
148 case 'ArrowUp':
149 setCursor(rows[Math.max(idx - 1, 0)]);
150 break;
151 case 'ArrowRight':
152 if (node) {
153 if (!current.classList.contains('open')) { toggleDir(node, true); setCursor(current); }
154 else setCursor(visibleRows()[idx + 1] ?? current); // entra al primer hijo
155 }
156 break;
157 case 'ArrowLeft': {
158 if (node && current.classList.contains('open')) { toggleDir(node, false); break; }
159 const parent = node ? node.parent : file?.node;
160 const pRow = parent && parent.role !== 'ciudad' ? nodeRows.get(parent.id) : null;
161 if (pRow) setCursor(pRow);
162 break;
163 }
164 case 'PageDown':
165 setCursor(rows[Math.min(idx + page, rows.length - 1)]);
166 break;
167 case 'PageUp':
168 setCursor(rows[Math.max(idx - page, 0)]);
169 break;
170 case 'Enter':
171 case ' ':
172 if (file) cb.onSelectFile?.(file, { fly: true });
173 else if (node) { toggleDir(node, !current.classList.contains('open')); cb.onSelectNode?.(node); }
174 break;
175 default:
176 return; // no consumir otras teclas (F vuelo, etc.)
177 }
178 e.preventDefault();
179 e.stopPropagation();
180 });
181
182 // monta y abre la cadena de contenedores hasta `node` (incluido)
183 function ensureVisible(node) {
184 const chain = [];
185 for (let n = node; n && n.role !== 'ciudad'; n = n.parent) chain.push(n);
186 for (let i = chain.length - 1; i >= 0; i--) {
187 const ent = dirEntries.get(chain[i].id);
188 if (!ent) return;
189 renderChildren(chain[i]);
190 ent.row.classList.add('open');
191 ent.kids.style.display = '';
192 }
193 }
194
195 function setModel(m) {
196 model = m;
197 fileRows.clear();
198 nodeRows.clear();
199 dirEntries.clear();
200 selectedRow = null;
201 selectedNodeRow = null;
202 treeEl.replaceChildren();
203 for (const c of model.city.children) addDirRow(treeEl, c, 1);
204 for (const fid of model.city.fileIds) addFileRow(treeEl, model.files[fid], 1, false);
205 baseFileCount = model.files.filter(f => !f.node.building?.isBasement).length;
206 setPath(null);
207 setStats(0);
208 searchEl.value = '';
209 hideResults();
210 }
211
212 function markFile(file) {
213 selectedRow?.classList.remove('selected');
214 selectedRow = null;
215 if (file) {
216 ensureVisible(file.node);
217 selectedRow = fileRows.get(file.id) ?? null;
218 }
219 if (selectedRow) {
220 selectedRow.classList.add('selected');
221 selectedRow.scrollIntoView({ block: 'center', behavior: 'smooth' });
222 }
223 }
224
225 // marca una carpeta/nivel (selección sincronizada ciudad ↔ árbol)
226 function markNode(node) {
227 selectedNodeRow?.classList.remove('selected');
228 selectedNodeRow = null;
229 if (node) {
230 ensureVisible(node);
231 selectedNodeRow = nodeRows.get(node.id) ?? null;
232 }
233 if (selectedNodeRow) {
234 selectedNodeRow.classList.add('selected');
235 selectedNodeRow.scrollIntoView({ block: 'center', behavior: 'smooth' });
236 }
237 }
238
239 // ── buscador (con wildcards: * dentro de segmento, ** cruza carpetas) ──
240 function termMatcher(t) {
241 if (!t.includes('*') && !t.includes('?')) {
242 return (f) => f.path.toLowerCase().includes(t);
243 }
244 const globstar = '__DOUBLE_STAR__';
245 const body = t
246 .replace(/[.+^${}()|[\]\\]/g, '\\$&')
247 .replace(/\*\*/g, globstar)
248 .replace(/\*/g, '[^/]*')
249 .replace(new RegExp(globstar, 'g'), '.*')
250 .replace(/\?/g, '[^/]');
251 // ancla a final de nombre/ruta y a límite de segmento: «*.js» casa con
252 // cualquier fichero .js, «src/*.css» con los css directos de un src/
253 const re = new RegExp(`(^|/)${body}$`, 'i');
254 return (f) => re.test(f.name) || re.test(f.path);
255 }
256
257 let results = [];
258 function runSearch(q) {
259 resultsEl.replaceChildren();
260 results = [];
261 const terms = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
262 if (!terms.length) {
263 resultsEl.classList.remove('show');
264 cb.onSuggest?.([]);
265 return;
266 }
267 const matchers = terms.map(termMatcher);
268 results = model.files
269 .filter(f => matchers.every(m => m(f)))
270 .slice(0, 30);
271 for (const f of results) {
272 const div = document.createElement('div');
273 div.className = 'result';
274 const dir = f.path.slice(0, f.path.length - f.name.length);
275 div.append(textSpan('rname', f.name), textSpan('rpath', dir));
276 div.addEventListener('click', () => { cb.onSelectFile?.(f, { fly: true }); hideResults(); });
277 resultsEl.appendChild(div);
278 }
279 resultsEl.classList.toggle('show', results.length > 0);
280 cb.onSuggest?.(results);
281 }
282 function hideResults() {
283 resultsEl.classList.remove('show');
284 cb.onSuggest?.([]);
285 }
286 searchEl.addEventListener('input', () => runSearch(searchEl.value));
287 searchEl.addEventListener('keydown', (e) => {
288 if (e.key === 'Enter' && results.length) {
289 cb.onSelectFile?.(results[0], { fly: true });
290 hideResults();
291 searchEl.blur();
292 }
293 if (e.key === 'Escape') { searchEl.value = ''; hideResults(); searchEl.blur(); }
294 e.stopPropagation();
295 });
296 document.addEventListener('click', (e) => {
297 if (!e.target.closest('#search-panel')) resultsEl.classList.remove('show');
298 });
299
300 // ── ruta inferior ───────────────────────────────────────────────────
301 function setPathParts(names) {
302 pathEl.replaceChildren();
303 if (!names?.length) {
304 pathEl.appendChild(textSpan('dim', t('path.none')));
305 return;
306 }
307 names.forEach((name, index) => {
308 if (index > 0) pathEl.appendChild(textSpan('sep', '/'));
309 pathEl.appendChild(textSpan(index === names.length - 1 ? 'seg last' : 'seg', name));
310 });
311 }
312 function setPath(file, chainNames) {
313 setPathParts(file ? [...chainNames, file.name] : null);
314 }
315
316 // ── botones ─────────────────────────────────────────────────────────
317 $('btn-aerial').addEventListener('click', () => cb.onView?.('aerial'));
318 $('btn-skyline').addEventListener('click', () => cb.onView?.('skyline'));
319 $('btn-reset').addEventListener('click', () => cb.onView?.('reset'));
320 $('btn-settings').addEventListener('click', () => openSettings());
321 const legendBtn = $('btn-legend');
322 let legendOn = true;
323 legendBtn.addEventListener('click', () => {
324 legendOn = !legendOn;
325 legendBtn.classList.toggle('off', !legendOn);
326 cb.onToggleLegend?.(legendOn);
327 });
328 const groundBtn = $('btn-ground');
329 let groundSolid = false;
330 groundBtn.classList.add('off');
331 groundBtn.addEventListener('click', () => {
332 groundSolid = !groundSolid;
333 groundBtn.classList.toggle('off', !groundSolid);
334 cb.onToggleGround?.(groundSolid);
335 });
336 const folderBtn = $('btn-folder');
337 folderBtn.addEventListener('click', () => cb.onPickFolder?.());
338 const reopenBtn = $('btn-reopen');
339 reopenBtn.addEventListener('click', () => cb.onReopenFolder?.());
340 let reopenName = '';
341 function setReopen(name) {
342 reopenName = name || '';
343 reopenBtn.style.display = name ? '' : 'none';
344 if (name) reopenBtn.textContent = t('button.reopen', { name });
345 }
346
347 // ── selector de idioma ──────────────────────────────────────────────
348 const langSel = $('lang-select');
349 langSel.value = language();
350 langSel.addEventListener('change', () => { setLanguage(langSel.value); langSel.blur(); });
351
352 // ── selector de tema ────────────────────────────────────────────────
353 const themeSel = $('theme-select');
354 for (const [key, theme] of Object.entries(THEMES)) {
355 const opt = document.createElement('option');
356 opt.value = key;
357 opt.textContent = t('theme.prefix', { label: theme.label });
358 themeSel.appendChild(opt);
359 }
360 themeSel.addEventListener('change', () => { cb.onTheme?.(themeSel.value); themeSel.blur(); });
361
362 // ── panel de ajustes visuales ──────────────────────────────────────
363 const settingsModal = $('settings-modal');
364 const settingsControls = $('settings-controls');
365 const settingsPresets = $('settings-presets');
366 const bloomBox = $('setting-bloom');
367 const settingsClose = $('settings-close');
368 const settingsReset = $('settings-reset');
369 const sliderDefs = [
370 ['exposure', 'settings.exposure', 0.65, 1.8, 0.01],
371 ['brightness', 'settings.brightness', 0.75, 1.45, 0.01],
372 ['contrast', 'settings.contrast', 0.8, 1.8, 0.01],
373 ['saturate', 'settings.saturate', 0.6, 2.4, 0.01],
374 ['lines', 'settings.lines', 0.45, 2.2, 0.01],
375 ['files', 'settings.files', 0.45, 2.4, 0.01],
376 ['glass', 'settings.glass', 0.35, 2.2, 0.01],
377 ['facades', 'settings.facades', 0.2, 1.8, 0.01],
378 ['labels', 'settings.labels', 0.2, 2.4, 0.01],
379 ['ground', 'settings.ground', 0.25, 1.5, 0.01],
380 ['fog', 'settings.fog', 0.35, 1.8, 0.01],
381 ];
382 const presets = [
383 ['preset.safe', null],
384 ['preset.neon', { exposure: 1.24, brightness: 1.08, contrast: 1.28, saturate: 1.65, lines: 1.22, files: 1.35, glass: 1.16, facades: 1.12, labels: 1.45, ground: 1.08, fog: 0.92 }],
385 ['preset.cinema', { exposure: 1.12, brightness: 0.98, contrast: 1.45, saturate: 1.28, lines: 1.05, files: 1.18, glass: 0.95, facades: 1.05, labels: 1.25, ground: 0.82, fog: 1.22 }],
386 ['preset.intense', { exposure: 1.34, brightness: 1.12, contrast: 1.55, saturate: 2.0, lines: 1.55, files: 1.75, glass: 1.35, facades: 1.35, labels: 1.85, ground: 1.18, fog: 0.78 }],
387 ];
388 const settingInputs = new Map();
389
390 function syncSettings(v) {
391 for (const [key] of sliderDefs) {
392 const input = settingInputs.get(key);
393 const value = v?.[key];
394 if (input && value !== undefined) {
395 input.value = value;
396 input.nextElementSibling.textContent = Number(value).toFixed(2);
397 }
398 }
399 bloomBox.checked = cb.isBloomEnabled?.() ?? false;
400 }
401
402 for (const [labelKey, values] of presets) {
403 const btn = document.createElement('button');
404 btn.type = 'button';
405 btn.dataset.i18n = labelKey;
406 btn.textContent = t(labelKey);
407 btn.addEventListener('click', () => {
408 const next = cb.onVisualPreset?.(values);
409 syncSettings(next);
410 });
411 settingsPresets.appendChild(btn);
412 }
413
414 for (const [key, label, min, max, step] of sliderDefs) {
415 const row = document.createElement('label');
416 row.className = 'setting-row';
417 const labelEl = textSpan('', t(label));
418 labelEl.dataset.i18n = label;
419 const input = document.createElement('input');
420 input.type = 'range';
421 input.min = min;
422 input.max = max;
423 input.step = step;
424 const output = document.createElement('output');
425 row.append(labelEl, input, output);
426 input.addEventListener('input', () => {
427 output.textContent = Number(input.value).toFixed(2);
428 cb.onVisualSettings?.({ [key]: Number(input.value) });
429 });
430 settingInputs.set(key, input);
431 settingsControls.appendChild(row);
432 }
433 bloomBox.addEventListener('change', () => cb.onBloomMode?.(bloomBox.checked));
434 settingsReset.addEventListener('click', () => syncSettings(cb.onVisualPreset?.(null)));
435 settingsClose.addEventListener('click', closeSettings);
436 settingsModal.addEventListener('click', (e) => { if (e.target === settingsModal) closeSettings(); });
437 document.addEventListener('keydown', (e) => {
438 if (e.key === 'Escape' && settingsModal.classList.contains('show')) closeSettings();
439 });
440 function openSettings() {
441 syncSettings(cb.getVisualSettings?.());
442 settingsModal.classList.add('show');
443 settingsModal.setAttribute('aria-hidden', 'false');
444 }
445 function closeSettings() {
446 settingsModal.classList.remove('show');
447 settingsModal.setAttribute('aria-hidden', 'true');
448 }
449 window.VCCOpenSettings = openSettings;
450 window.VCCCloseSettings = closeSettings;
451
452 // ── selector de modo de coloreado ───────────────────────────────────
453 const modeBtns = [...document.querySelectorAll('#mode-switch button')];
454 for (const btn of modeBtns) {
455 btn.addEventListener('click', () => {
456 btn.blur(); // el foco residual se confundía con el estado activo
457 if (!btn.disabled) cb.onMode?.(btn.dataset.mode);
458 });
459 }
460 function setActiveMode(mode) {
461 for (const btn of modeBtns) btn.classList.toggle('active', btn.dataset.mode === mode);
462 }
463 function setModeAvailable(mode, ok) {
464 const btn = modeBtns.find(b => b.dataset.mode === mode);
465 if (btn) {
466 btn.disabled = !ok;
467 const why = {
468 git: 'modeUnavailable.git',
469 ownership: 'modeUnavailable.ownership',
470 blast: 'modeUnavailable.blast',
471 };
472 btn.dataset.available = ok ? '1' : '0';
473 btn.title = ok ? '' : t(why[mode] ?? '');
474 }
475 }
476
477 // leyenda de colores (sobre el panel de navegación)
478 const legendEl = $('color-legend');
479 function setColorLegend(entries) {
480 legendEl.replaceChildren();
481 legendEl.classList.toggle('show', !!entries?.length);
482 for (const e of entries ?? []) {
483 const div = document.createElement('div');
484 div.className = 'entry';
485 const [r, g, b] = e.color.map(c => Math.round(Math.min(1, c) * 255));
486 const swatch = textSpan('swatch', '');
487 swatch.style.background = `rgb(${r},${g},${b})`;
488 swatch.style.color = `rgb(${r},${g},${b})`;
489 div.append(swatch, textSpan('', e.label));
490 legendEl.appendChild(div);
491 }
492 }
493
494 function setFolderSupported(ok) { folderBtn.style.display = ok ? '' : 'none'; }
495 let loadingMsg = '';
496 function setLoading(msg) {
497 loadingMsg = msg || '';
498 folderBtn.disabled = !!msg;
499 reopenBtn.disabled = !!msg;
500 folderBtn.textContent = msg || t('button.openFolder');
501 }
502
503 // ── stats / modo vuelo ──────────────────────────────────────────────
504 let baseFileCount = 0;
505 let gpuLabel = '';
506 let lastGpu = null;
507 function setGpu(gpu) {
508 lastGpu = gpu;
509 if (!gpu) { gpuLabel = ''; return; }
510 const mode = gpu.bloom ? `bloom ×${gpu.msaaSamples}` : t('gpu.direct');
511 if (gpu.tier === 'software') gpuLabel = t('gpu.software', { mode });
512 else if (gpu.tier === 'alta') gpuLabel = t('gpu.high', { brand: gpu.brand || t('gpu.discrete'), mode });
513 else gpuLabel = t('gpu.other', { mode });
514 }
515 // progreso del análisis perezoso del modo Blast (lotes en segundo plano)
516 let analysisLabel = '';
517 let lastFps = 0;
518 function setAnalysis(msg) { analysisLabel = msg ? ` · ${msg}` : ''; }
519 function setStats(fps) {
520 lastFps = fps;
521 if (!model) return;
522 const urbs = model.urbs?.length ? t('stats.urbs', { count: model.urbs.length }) : '';
523 statsEl.textContent = t('stats.main', {
524 base: baseFileCount,
525 ignored: model.files.length - baseFileCount,
526 buildings: model.buildings.length,
527 urbs,
528 districts: model.districts.length,
529 fps,
530 gpu: gpuLabel,
531 analysis: analysisLabel,
532 });
533 }
534
535 function setFlyMode(on) {
536 document.body.classList.toggle('flying', on);
537 }
538
539 function refreshBasementLabels() {
540 treeEl.querySelectorAll('.row.dir.basement').forEach((row) => {
541 const nameEl = row.querySelector('.name');
542 if (nameEl) nameEl.textContent = `${row.dataset.name} · ${t('tree.basementSuffix')}`;
543 });
544 }
545
546 function refreshLanguage() {
547 applyDocumentTranslations();
548 langSel.value = language();
549 for (const opt of themeSel.options) opt.textContent = t('theme.prefix', { label: THEMES[opt.value].label });
550 setReopen(reopenName);
551 if (!loadingMsg) folderBtn.textContent = t('button.openFolder');
552 for (const btn of modeBtns) {
553 if (btn.dataset.available === '0') setModeAvailable(btn.dataset.mode, false);
554 }
555 refreshBasementLabels();
556 if (pathEl.querySelector('.dim')) setPath(null);
557 setGpu(lastGpu);
558 setStats(lastFps);
559 cb.onLanguageChanged?.();
560 }
561
562 refreshLanguage();
563 onLanguageChange(refreshLanguage);
564
565 return {
566 setModel, markFile, markNode, setPath, setPathParts, setStats, setGpu, setAnalysis, setFlyMode, hideResults,
567 setFolderSupported, setLoading, setActiveMode, setModeAvailable, setColorLegend, setReopen,
568 };
569}