From 1c524b73d7abc8d06756a37a39649ad0cde51bfb Mon Sep 17 00:00:00 2001 From: jlopezdev Date: Tue, 24 Nov 2026 15:55:26 +0100 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20gr=C3=A1fico=20de=20colaboradores?= =?UTF-8?q?=20con=20una=20burbuja=20por=20persona?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Botón en la vista Contributors: burbujas del tamaño de los commits de cada persona en la rama actual y una tabla con commits, porcentaje y líneas añadidas y borradas. Paleta común a los webviews de autores, con rojo y cian intercambiados para que las filas vecinas se distingan también en tema claro. --- CHANGELOG.md | 7 ++ README.md | 4 +- extension.js | 3 +- l10n/bundle.l10n.es.json | 10 +- media/burbujas.js | 41 +++++++ media/historia.css | 12 -- media/paleta.css | 15 +++ media/reparto.css | 128 ++++++++++++++++++++ media/reparto.js | 252 +++++++++++++++++++++++++++++++++++++++ package-lock.json | 4 +- package.json | 19 ++- package.nls.es.json | 3 +- package.nls.json | 3 +- src/contribuidores.js | 1 + src/git.js | 11 +- src/historia-vista.js | 1 + src/nucleo/historia.js | 17 +-- src/nucleo/parseo.js | 28 ++++- src/reparto-vista.js | 121 +++++++++++++++++++ test/nucleo.test.js | 25 ++++ 20 files changed, 672 insertions(+), 33 deletions(-) create mode 100644 media/burbujas.js create mode 100644 media/paleta.css create mode 100644 media/reparto.css create mode 100644 media/reparto.js create mode 100644 src/reparto-vista.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e69b33..7acf92a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.8.0 + +- Contributors chart: the chart icon in the Contributors view (or `Show Contributors Chart`) opens a bubble per + person, sized by their commits to the current branch, and a table with everyone's commits, share and lines added + and deleted. Hover a bubble or a row for the details; it updates when you switch branch or commit. +- Visual File History: red and cyan swap places, so neighboring rows are easier to tell apart in light themes too. + ## 0.7.0 - Contributors view in the Source Control panel: everyone who committed to the current branch, by number of commits diff --git a/README.md b/README.md index 3b3cc53..6ed6aa7 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,9 @@ No account, no sign-in, no trial, no paywall, no telemetry. MIT licensed. lists every commit that touched the file, renames included. Select some lines and run `Show Line History` (editor context menu) to see only the commits that changed them. Click a commit to open its diff. - **Contributors.** A *Contributors* view in the Source Control panel lists everyone who committed to the current - branch, by number of commits. Expand a person to see their commits; click one for its files and diffs. + branch, by number of commits. Expand a person to see their commits; click one for its files and diffs. The chart + icon in its title (`Show Contributors Chart`) opens a bubble per person, sized by their commits, with a table of + everyone's commits, share and lines added and deleted. Hover a bubble or a row for the details. - **Visual file history.** `Show Visual File History` (editor context menu, Explorer, or the icon in the File History view) puts every commit to a file on a timeline: one row per author, dots sized by the lines changed, and added and deleted lines underneath. Hover a dot for the commit, click it for its diff, or move between commits with the arrow diff --git a/extension.js b/extension.js index 2aa879a..06e7613 100644 --- a/extension.js +++ b/extension.js @@ -9,6 +9,7 @@ const grafo = require('./src/grafo-vista'); const historia = require('./src/historia-vista'); const revisiones = require('./src/revisiones'); const contribuidores = require('./src/contribuidores'); +const reparto = require('./src/reparto-vista'); const t = vscode.l10n.t; let salida; @@ -62,7 +63,7 @@ function activate(context) { grafo.registrar(context, protegido); historia.registrar(context, protegido, ficheroDelHistorial); revisiones.registrar(context, protegido); - contribuidores.registrar(context, log); + reparto.registrar(context, protegido, contribuidores.registrar(context, log)); } function deactivate() { } diff --git a/l10n/bundle.l10n.es.json b/l10n/bundle.l10n.es.json index 327ed97..e029c3b 100644 --- a/l10n/bundle.l10n.es.json +++ b/l10n/bundle.l10n.es.json @@ -6,14 +6,17 @@ "1 author": "1 autor", "1 commit": "1 commit", "All branches": "Todas las ramas", + "Author": "Autor", "binary": "binario", "Branch {0} is not fully merged. Delete it anyway?": "La rama {0} no está fusionada del todo. ¿Borrarla igualmente?", "Branch, tag or commit SHA": "Rama, tag o SHA de un commit", "Branches to show": "Ramas que se muestran", "Checked out in worktree {0}": "Con checkout en el worktree {0}", "Commit Graph": "Grafo de commits", + "Commits": "Commits", "Compare {0} with…": "Comparar {0} con…", "Compare: base": "Comparar: base", + "Contributors": "Colaboradores", "Copied": "Copiado", "Copied {0}": "Copiado {0}", "Copy SHA": "Copiar SHA", @@ -52,9 +55,11 @@ "No git repository is open": "No hay ningún repositorio git abierto", "Not a valid name for a git ref": "Git no acepta ese nombre", "Not a valid ref: {0}": "No es una ref válida: {0}", + "on {0}": "en {0}", "Only the local tag is deleted.": "Solo se borra el tag local.", "Open a file in a git repository first": "Abre antes un fichero de un repositorio git", "Open a file tracked by git to see its history.": "Abre un fichero que siga git para ver su historial.", + "Open a folder with a git repository first": "Abre antes una carpeta con un repositorio git", "Open changes": "Abrir cambios", "Open on {0}": "Abrir en {0}", "Others ({0})": "Otros ({0})", @@ -68,6 +73,7 @@ "Reset {0} to {1} and discard all changes?": "¿Reset de {0} a {1} descartando todos los cambios?", "Restore": "Restaurar", "Restore {0} to its version in {1}?": "¿Restaurar {0} a su versión de {1}?", + "Share of commits per author": "Reparto de commits por autor", "Show commit": "Ver commit", "Show Commit Files": "Ver ficheros del commit", "Show Commit Graph": "Ver grafo de commits", @@ -88,6 +94,6 @@ "Uncommitted changes and the commits after {0} on this branch are lost.": "Se pierden los cambios sin commit y los commits de esta rama posteriores a {0}.", "Uncommitted changes to this file are lost.": "Se pierden los cambios sin commit de este fichero.", "Visual History": "Historial visual", - "Working Tree": "Árbol de trabajo", - "working tree": "árbol de trabajo" + "working tree": "árbol de trabajo", + "Working Tree": "Árbol de trabajo" } diff --git a/media/burbujas.js b/media/burbujas.js new file mode 100644 index 0000000..f486d84 --- /dev/null +++ b/media/burbujas.js @@ -0,0 +1,41 @@ +// @ts-check +// Empaquetado de burbujas: cada círculo, del más grande al más pequeño, en el primer hueco libre de una espiral. +// Lo carga el webview como script y los tests con require. +(function (exportar) { + 'use strict'; + + // radios en cualquier unidad → centros {x, y, r} sin solaparse, alrededor de (0, 0). aspecto > 1 estira la + // espiral a lo ancho para llenar un panel apaisado + function empaquetar(radios, { hueco = 2, aspecto = 1 } = {}) { + const sitios = []; + const paso = Math.max(0.5, Math.min(...radios.filter(r => r > 0)) / 4); + for (const r of radios) { + let x = 0; + let y = 0; + if (sitios.length) { + for (let a = 0; a < 2000; a += 0.05) { + const d = paso * a; + x = d * Math.cos(a) * aspecto; + y = d * Math.sin(a); + if (sitios.every(s => Math.hypot(s.x - x, s.y - y) >= s.r + r + hueco)) { break; } + } + } + sitios.push({ x, y, r }); + } + return sitios; + } + + // escala y centra los sitios en una caja de ancho × alto (píxeles), con un margen + function encajar(sitios, ancho, alto, margen = 4) { + const izq = Math.min(...sitios.map(s => s.x - s.r)); + const der = Math.max(...sitios.map(s => s.x + s.r)); + const arr = Math.min(...sitios.map(s => s.y - s.r)); + const aba = Math.max(...sitios.map(s => s.y + s.r)); + const k = Math.min((ancho - 2 * margen) / (der - izq), (alto - 2 * margen) / (aba - arr)); + const dx = ancho / 2 - ((izq + der) / 2) * k; + const dy = alto / 2 - ((arr + aba) / 2) * k; + return sitios.map(s => ({ x: s.x * k + dx, y: s.y * k + dy, r: s.r * k })); + } + + exportar({ empaquetar, encajar }); +}(typeof module !== 'undefined' ? f => { module.exports = f; } : f => { /** @type {any} */ (window).BURBUJAS = f; })); diff --git a/media/historia.css b/media/historia.css index f66b314..681c48c 100644 --- a/media/historia.css +++ b/media/historia.css @@ -1,18 +1,6 @@ :root { - /* orden comprobado con el validador de paleta (daltonismo, filas vecinas); amarillo y magenta se confundían */ - --c0: var(--vscode-charts-blue, #3794ff); - --c1: var(--vscode-charts-orange, #d18616); - --c2: var(--vscode-charts-purple, #b180d7); - --c3: var(--vscode-charts-green, #89d185); - --c4: var(--vscode-charts-red, #f14c4c); - --c5: var(--vscode-terminal-ansiCyan, #29b8db); --mas: var(--vscode-gitDecoration-addedResourceForeground, #81b88b); --menos: var(--vscode-gitDecoration-deletedResourceForeground, #c74e39); - --borde: var(--vscode-widget-border, rgba(128, 128, 128, .25)); - --suave: var(--vscode-descriptionForeground); - --fondo: var(--vscode-editor-background); - --salida: cubic-bezier(.22, 1, .36, 1); - --muelle: cubic-bezier(.34, 1.56, .64, 1); --etiquetas: 168px; } diff --git a/media/paleta.css b/media/paleta.css new file mode 100644 index 0000000..d7d68bf --- /dev/null +++ b/media/paleta.css @@ -0,0 +1,15 @@ +/* Común a los webviews de autores (historial visual, gráfico de colaboradores). + Orden comprobado con el validador de paleta en tema claro y oscuro: ningún par vecino se confunde con daltonismo */ +:root { + --c0: var(--vscode-charts-blue, #3794ff); + --c1: var(--vscode-charts-orange, #d18616); + --c2: var(--vscode-charts-purple, #b180d7); + --c3: var(--vscode-charts-green, #89d185); + --c4: var(--vscode-terminal-ansiCyan, #29b8db); + --c5: var(--vscode-charts-red, #f14c4c); + --borde: var(--vscode-widget-border, rgba(128, 128, 128, .25)); + --suave: var(--vscode-descriptionForeground); + --fondo: var(--vscode-editor-background); + --salida: cubic-bezier(.22, 1, .36, 1); + --muelle: cubic-bezier(.34, 1.56, .64, 1); +} diff --git a/media/reparto.css b/media/reparto.css new file mode 100644 index 0000000..5435fac --- /dev/null +++ b/media/reparto.css @@ -0,0 +1,128 @@ +:root { + --mas: var(--vscode-gitDecoration-addedResourceForeground, #81b88b); + --menos: var(--vscode-gitDecoration-deletedResourceForeground, #c74e39); + --alto: 300px; +} + +* { box-sizing: border-box; } +[hidden] { display: none !important; } + +body { + margin: 0; + padding: 16px 16px 24px; + color: var(--vscode-foreground); + background: var(--fondo); + font-family: var(--vscode-font-family); + font-size: var(--vscode-font-size); +} + +.cabecera { margin-bottom: 16px; } +.cabecera h1 { margin: 0; overflow: hidden; font-size: 1.15em; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } +.resumen { margin: 4px 0 0; color: var(--suave); font-variant-numeric: tabular-nums; } +.aviso { color: var(--suave); } +.oculto { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + +.reparto { display: grid; gap: 20px; } +.reparto[aria-busy="true"] { + height: var(--alto); + border-radius: 6px; + background: linear-gradient(90deg, transparent 0, color-mix(in srgb, var(--vscode-foreground) 6%, transparent) 50%, transparent 100%) 0 0 / 200% 100%; + animation: brillo 1.4s linear infinite; +} +@keyframes brillo { to { background-position: -200% 0; } } + +.lienzo { height: var(--alto); min-width: 0; } +.nube { display: block; overflow: visible; } +/* relleno tenue con borde del color: el texto va con la tinta del tema y se lee en claro y en oscuro */ +.burbuja { cursor: default; transform-box: fill-box; transform-origin: center; } +.burbuja circle { + --tinta: var(--suave); + fill: color-mix(in srgb, var(--tinta) 32%, var(--fondo)); + stroke: var(--tinta); + stroke-width: 1.5; + transition: fill .15s ease-out, opacity .15s ease-out; +} +.burbuja.c0 circle { --tinta: var(--c0); } .burbuja.c1 circle { --tinta: var(--c1); } .burbuja.c2 circle { --tinta: var(--c2); } +.burbuja.c3 circle { --tinta: var(--c3); } .burbuja.c4 circle { --tinta: var(--c4); } .burbuja.c5 circle { --tinta: var(--c5); } +.burbuja.activo circle { fill: color-mix(in srgb, var(--tinta) 60%, var(--fondo)); stroke-width: 2.5; } +.enfocando .burbuja:not(.activo) { opacity: .35; } +.burbuja text { fill: var(--vscode-foreground); font-size: 12px; text-anchor: middle; pointer-events: none; font-variant-numeric: tabular-nums; } +.burbuja .nombre { font-weight: 600; } +.burbuja .cuenta { fill: var(--suave); font-size: 11px; } +.burbuja.activo .cuenta { fill: var(--vscode-foreground); } + +.globo { + position: absolute; + top: 0; + left: 0; + z-index: 3; + display: grid; + gap: 2px; + max-width: min(320px, calc(100vw - 16px)); + padding: 8px 10px; + color: var(--vscode-editorHoverWidget-foreground, var(--vscode-foreground)); + background: var(--vscode-editorHoverWidget-background, var(--fondo)); + border: 1px solid var(--vscode-editorHoverWidget-border, var(--borde)); + border-radius: 6px; + box-shadow: 0 4px 16px rgba(0, 0, 0, .25); + pointer-events: none; + font-variant-numeric: tabular-nums; + animation: aparecer .12s var(--salida); +} +.globo strong { overflow-wrap: anywhere; } +.globo .suave { color: var(--suave); overflow-wrap: anywhere; } +@keyframes aparecer { from { opacity: 0; } } + +.lista { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; } +.lista th { padding: 0 8px 6px; color: var(--suave); font-weight: 500; text-align: left; border-bottom: 1px solid var(--borde); } +.lista td { padding: 6px 8px; vertical-align: middle; } +.lista .num { width: 1%; text-align: right; white-space: nowrap; } +.lista td.lineas { min-width: 8.5em; } +.lista tbody tr { cursor: default; outline: none; transition: background .15s ease-out; } +.lista tbody tr:hover, .lista tbody tr.activo { background: var(--vscode-list-hoverBackground); } +.lista tbody tr:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; } +.lista td:first-child { border-radius: 4px 0 0 4px; } +.lista td:last-child { border-radius: 0 4px 4px 0; } + +.autor { max-width: 0; } +.nombre { display: flex; align-items: center; gap: 8px; min-width: 0; } +/* con el nombre repetido, el correo es lo primero que se recorta */ +.nombre .texto { flex: 0 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.correo { flex: 0 100 auto; min-width: 0; overflow: hidden; color: var(--suave); text-overflow: ellipsis; white-space: nowrap; } +.muestra { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--suave); } +.c0 .muestra, .c0 .barra i { background: var(--c0); } .c1 .muestra, .c1 .barra i { background: var(--c1); } +.c2 .muestra, .c2 .barra i { background: var(--c2); } .c3 .muestra, .c3 .barra i { background: var(--c3); } +.c4 .muestra, .c4 .barra i { background: var(--c4); } .c5 .muestra, .c5 .barra i { background: var(--c5); } + +/* barra fina: compara con precisión lo que las burbujas solo enseñan a ojo */ +.barra { display: block; height: 3px; margin: 5px 0 0 18px; } +.barra i { + display: block; + width: calc(var(--parte) * 100%); + min-width: 2px; + height: 100%; + border-radius: 2px; + background: var(--suave); + transform-origin: left; +} +.mas { color: var(--mas); } +.menos { color: var(--menos); } + +/* primera vez: las burbujas brotan de mayor a menor y las barras crecen desde la izquierda */ +.animar .burbuja { animation: brotar .45s var(--muelle) var(--retardo) both; } +.animar .barra i { animation: crecer .5s var(--salida) var(--retardo) both; } +@keyframes brotar { from { transform: scale(0); opacity: 0; } } +@keyframes crecer { from { transform: scaleX(0); } } + +@media (max-width: 560px) { + :root { --alto: 240px; } + body { padding: 12px 8px 16px; } +} +@media (max-width: 400px) { + .lista .lineas { display: none; } +} + +@media (prefers-reduced-motion: reduce) { + .reparto[aria-busy="true"], .animar .burbuja, .animar .barra i, .globo { animation: none !important; } + .burbuja circle, .lista tbody tr { transition: none; } +} diff --git a/media/reparto.js b/media/reparto.js new file mode 100644 index 0000000..3d109cc --- /dev/null +++ b/media/reparto.js @@ -0,0 +1,252 @@ +// @ts-check +(function () { + 'use strict'; + const vscode = acquireVsCodeApi(); + const T = window.TEXTOS; + const { empaquetar, encajar } = /** @type {any} */ (window).BURBUJAS; + const NS = 'http://www.w3.org/2000/svg'; + // a partir de aquí las burbujas serían puntos: el resto va junto en «otros» + const MAX_BURBUJAS = 40; + + const reparto = document.getElementById('reparto'); + const titulo = document.getElementById('titulo'); + const resumen = document.getElementById('resumen'); + const globo = document.getElementById('globo'); + const lengua = document.documentElement.lang || undefined; + const numero = new Intl.NumberFormat(lengua); + const compacto = new Intl.NumberFormat(lengua, { notation: 'compact', maximumFractionDigits: 1 }); + const quieto = matchMedia('(prefers-reduced-motion: reduce)'); + /** @type {any} */ + let datos = null; + /** @type {Record | null} */ + let lineas = null; + let animar = true; + let total = 0; + /** @type {any[]} */ + let grupos = []; + /** @type {HTMLElement | null} */ + let lienzo = null; + let anchoPintado = 0; + + const fmt = (s, ...v) => v.reduce((r, x, i) => r.replace(`{${i}}`, String(x)), s); + const cuantos = (n, uno, varios) => (n === 1 ? uno : fmt(varios, numero.format(n))); + const porcentaje = n => { + const p = (n / total) * 100; + return p > 0 && p < 1 ? '<1%' : `${Math.round(p)}%`; + }; + const tono = color => (color === null ? 'otros' : `c${color}`); + + function el(tag, clase, texto) { + const e = document.createElement(tag); + if (clase) { e.className = clase; } + if (texto !== undefined) { e.textContent = texto; } + return e; + } + + function svg(tag, attrs) { + const e = document.createElementNS(NS, tag); + for (const [k, v] of Object.entries(attrs || {})) { e.setAttribute(k, String(v)); } + return e; + } + + function agrupar(personas) { + if (personas.length <= MAX_BURBUJAS) { return personas.map(p => ({ ...p, miembros: [p] })); } + const propios = personas.slice(0, MAX_BURBUJAS - 1).map(p => ({ ...p, miembros: [p] })); + const resto = personas.slice(MAX_BURBUJAS - 1); + return [...propios, { nombre: fmt(T.otros, resto.length), commits: resto.reduce((n, p) => n + p.commits, 0), color: null, miembros: resto }]; + } + + // recorta a lo que cabe dentro del círculo (≈ 7 px por letra a 12 px) + const cabe = (texto, r) => { + const n = Math.floor((r * 1.6) / 7); + return texto.length <= n ? texto : `${texto.slice(0, Math.max(1, n - 1))}…`; + }; + + // radio por raíz de los commits: lo que se compara a ojo es el área + function dibujarBurbujas() { + if (!lienzo) { return; } + const ancho = Math.round(lienzo.clientWidth); + if (!ancho) { return; } + anchoPintado = ancho; + const alto = Math.round(lienzo.clientHeight); + const sitios = encajar(empaquetar(grupos.map(g => Math.sqrt(g.commits)), { hueco: 0.06 * Math.sqrt(grupos[0].commits), aspecto: Math.min(3, Math.max(1, ancho / alto)) }), ancho, alto); + const dibujo = svg('svg', { class: 'nube', width: ancho, height: alto, 'aria-hidden': 'true' }); + sitios.forEach((s, i) => { + const g = grupos[i]; + const b = svg('g', { class: `burbuja ${tono(g.color)}` }); + b.dataset.b = String(i); + b.style.setProperty('--retardo', `${Math.min(i, 30) * 25}ms`); + b.appendChild(svg('circle', { cx: s.x, cy: s.y, r: Math.max(2, s.r - 1) })); + if (s.r >= 28) { + b.appendChild(svg('text', { x: s.x, y: s.y - 2, class: 'nombre' })).textContent = cabe(g.nombre, s.r); + b.appendChild(svg('text', { x: s.x, y: s.y + 14, class: 'cuenta' })).textContent = numero.format(g.commits); + } else if (s.r >= 14) { + b.appendChild(svg('text', { x: s.x, y: s.y + 4, class: 'cuenta' })).textContent = compacto.format(g.commits); + } + dibujo.appendChild(b); + }); + lienzo.replaceChildren(dibujo); + } + + function celdaLineas(td, p) { + const l = lineas && lineas[p.clave]; + td.replaceChildren(); + td.removeAttribute('title'); + if (!lineas) { td.textContent = '…'; return; } + if (!l) { td.textContent = '—'; return; } + td.title = `+${numero.format(l.mas)} −${numero.format(l.menos)}`; + td.append(el('span', 'mas', `+${compacto.format(l.mas)}`), el('span', 'menos', ` −${compacto.format(l.menos)}`)); + } + + function pintar() { + ocultarGlobo(); + reparto.removeAttribute('aria-busy'); + reparto.replaceChildren(); + const personas = datos.personas; + if (!personas.length) { lienzo = null; reparto.appendChild(el('p', 'aviso', T.sinCommits)); return; } + total = personas.reduce((n, p) => n + p.commits, 0); + grupos = agrupar(personas); + lienzo = el('div', 'lienzo'); + + const tabla = el('table', 'lista'); + tabla.appendChild(el('caption', 'oculto', T.titulo)); + const cabeza = el('tr'); + [[T.autor, 'autor'], [T.columnaCommits, 'num'], ['%', 'num'], [T.lineas, 'num lineas']].forEach(([texto, clase]) => { + const th = el('th', clase, texto); + th.scope = 'col'; + cabeza.appendChild(th); + }); + tabla.appendChild(el('thead')).appendChild(cabeza); + const cuerpo = tabla.appendChild(el('tbody')); + const veces = new Map(); + personas.forEach(p => veces.set(p.nombre, (veces.get(p.nombre) || 0) + 1)); + const max = personas[0].commits; + personas.forEach((p, i) => { + const fila = el('tr', `persona ${tono(p.color)}`); + fila.tabIndex = 0; + fila.dataset.p = String(i); + fila.dataset.b = String(Math.min(i, grupos.length - 1)); + const autor = el('td', 'autor'); + const nombre = el('span', 'nombre'); + nombre.append(el('span', 'muestra'), el('span', 'texto', p.nombre)); + // dos personas con el mismo nombre solo se distinguen por el correo + if (veces.get(p.nombre) > 1) { nombre.appendChild(el('span', 'correo', p.correo)); } + nombre.title = `${p.nombre} <${p.correo}>`; + const barra = el('span', 'barra'); + const relleno = barra.appendChild(el('i')); + relleno.style.setProperty('--parte', String(p.commits / max)); + relleno.style.setProperty('--retardo', `${Math.min(i, 20) * 25}ms`); + autor.append(nombre, barra); + const lin = el('td', 'num lineas'); + celdaLineas(lin, p); + fila.append(autor, el('td', 'num', numero.format(p.commits)), el('td', 'num', porcentaje(p.commits)), lin); + cuerpo.appendChild(fila); + }); + + reparto.append(lienzo, tabla); + reparto.classList.toggle('animar', animar && !quieto.matches); + animar = false; + dibujarBurbujas(); + } + + function mostrarGlobo(g, persona) { + const quien = persona || g; + const partes = [el('strong', '', quien.nombre)]; + if (quien.correo) { partes.push(el('span', 'suave', quien.correo)); } + partes.push(el('span', '', `${cuantos(quien.commits, T.unCommit, T.commits)} · ${porcentaje(quien.commits)}`)); + const l = lineas && quien.clave && lineas[quien.clave]; + if (l) { + const s = el('span'); + s.append(el('span', 'mas', `+${numero.format(l.mas)}`), el('span', 'menos', ` −${numero.format(l.menos)}`)); + partes.push(s); + } + globo.replaceChildren(...partes); + globo.hidden = false; + const ancla = reparto.querySelector(`.burbuja[data-b="${grupos.indexOf(g)}"] circle`); + if (!ancla) { return; } + const caja = ancla.getBoundingClientRect(); + const m = globo.getBoundingClientRect(); + const izq = Math.min(innerWidth - m.width - 8, Math.max(8, caja.left + caja.width / 2 - m.width / 2)); + const arriba = caja.top - m.height - 8 < 8 ? caja.bottom + 8 : caja.top - m.height - 8; + globo.style.transform = `translate(${Math.round(izq)}px, ${Math.round(arriba + scrollY)}px)`; + } + + function ocultarGlobo() { globo.hidden = true; } + + function senalar(fila, burbuja) { + reparto.querySelectorAll('.activo').forEach(e => e.classList.remove('activo')); + reparto.classList.toggle('enfocando', burbuja !== null); + if (burbuja === null) { ocultarGlobo(); return; } + const g = grupos[burbuja]; + reparto.querySelector(`.burbuja[data-b="${burbuja}"]`)?.classList.add('activo'); + const filas = fila !== null ? [fila] : g.miembros.map(p => datos.personas.indexOf(p)); + filas.forEach(i => reparto.querySelector(`tr[data-p="${i}"]`)?.classList.add('activo')); + mostrarGlobo(g, fila !== null ? datos.personas[fila] : g.miembros.length === 1 ? g.miembros[0] : null); + } + + function objetivo(e) { + const t = /** @type {Element} */ (e.target); + const fila = t.closest && t.closest('tr[data-p]'); + if (fila) { return [Number(/** @type {HTMLElement} */ (fila).dataset.p), Number(/** @type {HTMLElement} */ (fila).dataset.b)]; } + const b = t.closest && t.closest('.burbuja'); + if (b) { return [null, Number(/** @type {HTMLElement} */ (b).dataset.b)]; } + return null; + } + + reparto.addEventListener('pointerover', e => { + const o = objetivo(e); + if (o) { senalar(o[0], o[1]); } + }); + reparto.addEventListener('pointerout', e => { + const a = /** @type {Element} */ (e.relatedTarget); + if (!(a && a.closest && (a.closest('tr[data-p]') || a.closest('.burbuja')))) { senalar(null, null); } + }); + reparto.addEventListener('focusin', e => { + const o = objetivo(e); + if (o) { senalar(o[0], o[1]); } + }); + reparto.addEventListener('focusout', e => { + if (!reparto.contains(/** @type {Node} */ (e.relatedTarget))) { senalar(null, null); } + }); + // flechas: de una persona a la siguiente sin tabular por toda la lista + reparto.addEventListener('keydown', e => { + const fila = /** @type {Element} */ (e.target).closest('tr[data-p]'); + const destino = fila && { ArrowDown: fila.nextElementSibling, ArrowUp: fila.previousElementSibling }[e.key]; + if (destino) { e.preventDefault(); /** @type {HTMLElement} */ (destino).focus(); } + }); + + // solo el ancho cambia el empaquetado; un panel abierto oculto mide 0 y se dibuja cuando tiene ancho + let espera; + new ResizeObserver(() => { + const w = lienzo ? Math.round(lienzo.clientWidth) : 0; + if (!w || w === anchoPintado) { return; } + clearTimeout(espera); + espera = setTimeout(() => { ocultarGlobo(); dibujarBurbujas(); }, 80); + }).observe(reparto); + + window.addEventListener('message', ({ data: m }) => { + if (m.tipo === 'error') { + reparto.removeAttribute('aria-busy'); + reparto.replaceChildren(el('p', 'aviso', m.mensaje)); + return; + } + if (m.tipo === 'lineas') { + lineas = m.lineas; + reparto.querySelectorAll('tr[data-p]').forEach(f => { + celdaLineas(/** @type {HTMLElement} */ (f.querySelector('td.lineas')), datos.personas[Number(/** @type {HTMLElement} */ (f).dataset.p)]); + }); + return; + } + if (m.tipo !== 'personas') { return; } + datos = m; + lineas = null; + titulo.textContent = m.repo; + const suma = m.personas.reduce((n, p) => n + p.commits, 0); + const partes = [cuantos(suma, T.unCommit, T.commits), cuantos(m.personas.length, T.unAutor, T.autores)]; + if (m.rama) { partes.push(fmt(T.enRama, m.rama)); } + resumen.textContent = partes.join(' · '); + pintar(); + }); + + vscode.postMessage({ tipo: 'listo' }); +}()); diff --git a/package-lock.json b/package-lock.json index bd23c3a..fb99347 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "git-lore", - "version": "0.7.0", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "git-lore", - "version": "0.7.0", + "version": "0.8.0", "license": "MIT", "devDependencies": { "@vscode/vsce": "^4.1.1", diff --git a/package.json b/package.json index 8ee6768..6a26e12 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "git-lore", "displayName": "%displayName%", "description": "%description%", - "version": "0.7.0", + "version": "0.8.0", "publisher": "jlopez", "license": "MIT", "repository": { @@ -265,6 +265,12 @@ "title": "%command.refresh%", "category": "Git Lore", "icon": "$(refresh)" + }, + { + "command": "gitLore.contributorsChart", + "title": "%command.contributorsChart%", + "category": "Git Lore", + "icon": "$(pie-chart)" } ], "menus": { @@ -400,6 +406,10 @@ { "command": "gitLore.refreshContributors", "when": "false" + }, + { + "command": "gitLore.contributorsChart", + "when": "gitOpenRepositoryCount != 0" } ], "editor/title": [ @@ -493,10 +503,15 @@ "when": "view == gitLore.compare", "group": "navigation@2" }, + { + "command": "gitLore.contributorsChart", + "when": "view == gitLore.contributors", + "group": "navigation@1" + }, { "command": "gitLore.refreshContributors", "when": "view == gitLore.contributors", - "group": "navigation" + "group": "navigation@2" } ], "view/item/context": [ diff --git a/package.nls.es.json b/package.nls.es.json index 391f891..9454211 100644 --- a/package.nls.es.json +++ b/package.nls.es.json @@ -43,5 +43,6 @@ "command.graph.openWorktree": "Abrir worktree en una ventana nueva", "command.previousRevision": "Abrir la revisión anterior", "command.nextRevision": "Abrir la revisión siguiente", - "view.contributors": "Colaboradores" + "view.contributors": "Colaboradores", + "command.contributorsChart": "Ver gráfico de colaboradores" } diff --git a/package.nls.json b/package.nls.json index 9df1c7f..b597200 100644 --- a/package.nls.json +++ b/package.nls.json @@ -43,5 +43,6 @@ "command.graph.openWorktree": "Open Worktree in New Window", "command.previousRevision": "Open Previous Revision", "command.nextRevision": "Open Next Revision", - "view.contributors": "Contributors" + "view.contributors": "Contributors", + "command.contributorsChart": "Show Contributors Chart" } diff --git a/src/contribuidores.js b/src/contribuidores.js index 60b6a53..fe13470 100644 --- a/src/contribuidores.js +++ b/src/contribuidores.js @@ -101,6 +101,7 @@ function registrar(context, log) { vscode.window.onDidChangeActiveTextEditor(elegir), vscode.commands.registerCommand('gitLore.refreshContributors', () => proveedor.cambio.fire()), ); + return () => proveedor.repo; // el gráfico de colaboradores abre el mismo repo que enseña la vista } module.exports = { registrar }; diff --git a/src/git.js b/src/git.js index 17b5c01..3992bbb 100644 --- a/src/git.js +++ b/src/git.js @@ -5,7 +5,7 @@ const fs = require('fs'); const path = require('path'); const vscode = require('vscode'); const { - parsearBlame, parsearLog, parsearShortlog, parsearDiff, parsearNumstat, parsearStash, parsearWorktrees, FORMATO_LOG, FORMATO_SHA, FORMATO_STASH, + parsearBlame, parsearLog, parsearShortlog, parsearLineasPorAutor, FORMATO_AUTOR, parsearDiff, parsearNumstat, parsearStash, parsearWorktrees, FORMATO_LOG, FORMATO_SHA, FORMATO_STASH, } = require('./nucleo/parseo'); const { webDeRemoto, elegirRemoto } = require('./nucleo/remotos'); @@ -161,6 +161,13 @@ async function autores(repo) { return parsearShortlog(await ejecutar(repo.rootUri.fsPath, ['shortlog', '-sne', 'HEAD'])); } +// toda la historia de HEAD: en un repo grande tarda, por eso se puede cancelar. Los merges no suman líneas +async function lineasPorAutor(repo, token) { + if (!repo.state.HEAD || !repo.state.HEAD.commit) { return new Map(); } + return parsearLineasPorAutor(await ejecutar(repo.rootUri.fsPath, + ['log', 'HEAD', '--no-merges', '--numstat', `--format=${FORMATO_AUTOR}`], { token })); +} + // con correo: «» literal (--fixed-strings: un «+» no es regex), sin distinguir mayúsculas como al agrupar. // sin correo git guarda «Nombre <>»: se ancla entera con regex escapada, o «Anabel» casaría con «Ana Anabel <>» async function commitsDeAutor(repo, autor, limite = 200) { @@ -255,5 +262,5 @@ function uriEnRevision(repo, ruta, ref) { module.exports = { ALCANCES, obtenerApi, repoDe, rutaRelativa, resolverRef, blame, mensaje, historial, lineasDeFichero, ficherosDeCommit, grafo, refs, diferencias, webDe, - uriEnRevision, cherryPick, revertir, resetear, crearTag, restaurarFichero, stashes, worktrees, usarStash, firmaDeRefs, dirComun, autores, commitsDeAutor, ErrorGit, + uriEnRevision, cherryPick, revertir, resetear, crearTag, restaurarFichero, stashes, worktrees, usarStash, firmaDeRefs, dirComun, autores, lineasPorAutor, commitsDeAutor, ErrorGit, }; diff --git a/src/historia-vista.js b/src/historia-vista.js index 4862b6b..d9a67eb 100644 --- a/src/historia-vista.js +++ b/src/historia-vista.js @@ -23,6 +23,7 @@ function html(webview, raizExt, nonce) { + diff --git a/src/nucleo/historia.js b/src/nucleo/historia.js index 4afe384..88afb41 100644 --- a/src/nucleo/historia.js +++ b/src/nucleo/historia.js @@ -1,12 +1,15 @@ 'use strict'; -// Historial visual de un fichero: a qué fila (autor) va cada commit. Una persona es su correo, aunque cambie de nombre. +// Historial visual de un fichero: a qué fila (autor) va cada commit. +const { claveDePersona } = require('./parseo'); -// Colores en orden fijo por número de commits; a partir del máximo, todo cae en «otros» (sin color propio). -// 7 filas: los 6 colores del tema que se distinguen entre sí con daltonismo, más «otros» -function agruparAutores(commits, max = 7) { +// los colores del tema que se distinguen entre sí con daltonismo (media/paleta.css); el resto va a «otros» +const COLORES = 6; + +// Colores en orden fijo por número de commits; a partir del máximo, todo cae en «otros» (sin color propio) +function agruparAutores(commits, max = COLORES + 1) { const porClave = new Map(); for (const c of commits) { - const clave = (c.correo || c.autor || '').toLowerCase(); + const clave = claveDePersona(c.correo, c.autor); const a = porClave.get(clave) || { clave, nombre: c.autor, commits: 0 }; a.commits++; porClave.set(clave, a); @@ -18,7 +21,7 @@ function agruparAutores(commits, max = 7) { if (resto.length) { autores.push({ nombre: null, commits: resto.reduce((n, a) => n + a.commits, 0), otros: resto.length, color: null }); } const fila = new Map(propios.map((a, i) => [a.clave, i])); const filaDe = c => { - const i = fila.get((c.correo || c.autor || '').toLowerCase()); + const i = fila.get(claveDePersona(c.correo, c.autor)); return i === undefined ? propios.length : i; }; return { autores, filaDe }; @@ -38,4 +41,4 @@ function cambiosDe(commits, rutaActual) { return cambios; } -module.exports = { agruparAutores, cambiosDe }; +module.exports = { agruparAutores, cambiosDe, COLORES }; diff --git a/src/nucleo/parseo.js b/src/nucleo/parseo.js index 29d7fd2..cbe9a56 100644 --- a/src/nucleo/parseo.js +++ b/src/nucleo/parseo.js @@ -147,13 +147,16 @@ function parsearWorktrees(texto) { } // git shortlog -sne → autores por correo (la misma persona con dos nombres cuenta una vez, con el que más usa) +// una persona es su correo, aunque firme con varios nombres; sin correo, su nombre +const claveDePersona = (correo, nombre) => (correo || nombre || '').toLowerCase(); + function parsearShortlog(texto) { const porCorreo = new Map(); for (const l of texto.split('\n')) { const m = /^\s*(\d+)\t(.*?)\s*<([^>]*)>\s*$/.exec(l); if (!m) { continue; } const [, n, nombre, correo] = m; - const clave = correo.toLowerCase() || nombre; + const clave = claveDePersona(correo, nombre); const a = porCorreo.get(clave) || { nombre, correo, commits: 0, maxNombre: 0 }; a.commits += Number(n); if (Number(n) > a.maxNombre) { a.nombre = nombre; a.maxNombre = Number(n); } @@ -163,8 +166,29 @@ function parsearShortlog(texto) { .sort((a, b) => b.commits - a.commits || a.nombre.localeCompare(b.nombre)); } +// %aE/%aN aplican .mailmap como shortlog: si no, las cifras no cuadrarían con las de commits +const FORMATO_AUTOR = `${SEP_REG}%aE${SEP_CAMPO}%aN`; + +// git log --numstat --format=FORMATO_AUTOR → Map(clave de persona → { mas, menos }) +function parsearLineasPorAutor(texto) { + const porClave = new Map(); + for (const bloque of texto.split(SEP_REG)) { + const [cabecera, ...resto] = bloque.split('\n'); + if (!cabecera.trim()) { continue; } + const [correo, nombre] = cabecera.split(SEP_CAMPO); + const clave = claveDePersona(correo, nombre); + const a = porClave.get(clave) || { mas: 0, menos: 0 }; + for (const l of resto) { + const m = NUMSTAT.exec(l); + if (m && m[1] !== '-') { a.mas += Number(m[1]); a.menos += Number(m[2]); } + } + porClave.set(clave, a); + } + return porClave; +} + module.exports = { - parsearShortlog, + parsearShortlog, parsearLineasPorAutor, claveDePersona, FORMATO_AUTOR, desentrecomillar, parsearBlame, parsearLog, parsearDiff, parsearNumstat, parsearStash, parsearWorktrees, FORMATO_LOG, FORMATO_SHA, FORMATO_STASH, }; diff --git a/src/reparto-vista.js b/src/reparto-vista.js new file mode 100644 index 0000000..f0adf6f --- /dev/null +++ b/src/reparto-vista.js @@ -0,0 +1,121 @@ +'use strict'; +// Gráfico de colaboradores en un webview: una burbuja por persona, del tamaño de sus commits en la rama actual, y la lista. +const crypto = require('crypto'); +const path = require('path'); +const vscode = require('vscode'); +const git = require('./git'); +const { claveDePersona } = require('./nucleo/parseo'); +const { COLORES } = require('./nucleo/historia'); +const { corto } = require('./acciones'); + +const t = vscode.l10n.t; +const paneles = new Map(); // raíz del repo → { panel, cargar } + +function html(webview, raizExt, nonce) { + const recurso = f => webview.asWebviewUri(vscode.Uri.joinPath(raizExt, 'media', f)); + const textos = { + commits: t('{0} commits'), unCommit: t('1 commit'), autores: t('{0} authors'), unAutor: t('1 author'), otros: t('Others ({0})'), + sinCommits: t('No commits'), enRama: t('on {0}'), autor: t('Author'), columnaCommits: t('Commits'), lineas: t('Lines changed'), + titulo: t('Share of commits per author'), + }; + return ` + + + + + + + + + +
+

+

+
+
+ + + + + +`; +} + +function abrir(context, repo) { + const raiz = repo.rootUri.fsPath; + const existente = paneles.get(raiz); + if (existente) { + existente.panel.reveal(); + return existente.cargar(); + } + const panel = vscode.window.createWebviewPanel('gitLore.contributorsChart', `${t('Contributors')}: ${path.basename(raiz)}`, + vscode.ViewColumn.Active, { + enableScripts: true, + retainContextWhenHidden: true, + localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'media')], + }); + panel.iconPath = new vscode.ThemeIcon('pie-chart'); + let cerrado = false; + let generacion = 0; + let cancelar = null; + const enviar = m => { if (!cerrado) { panel.webview.postMessage(m).then(undefined, () => { }); } }; + + // primero los commits (shortlog es rápido) y luego las líneas, que recorren toda la historia + async function cargar() { + const mia = ++generacion; + if (cancelar) { cancelar.cancel(); cancelar.dispose(); } + cancelar = new vscode.CancellationTokenSource(); + const token = cancelar.token; + try { + const personas = await git.autores(repo); + if (mia !== generacion) { return; } + const head = repo.state.HEAD; + enviar({ + tipo: 'personas', + repo: path.basename(raiz), + rama: head ? head.name || (head.commit && corto(head.commit)) : '', + personas: personas.map((p, i) => ({ ...p, clave: claveDePersona(p.correo, p.nombre), color: i < COLORES ? i : null })), + }); + const lineas = await git.lineasPorAutor(repo, token); + if (mia === generacion) { enviar({ tipo: 'lineas', lineas: Object.fromEntries(lineas) }); } + } catch (e) { + if (e instanceof vscode.CancellationError || mia !== generacion) { return; } + enviar({ tipo: 'error', mensaje: e.message }); + } + } + + // como la vista Contributors: otra rama u otro commit cambian las cifras + const firma = () => repo.state.HEAD && `${repo.state.HEAD.name}@${repo.state.HEAD.commit}`; + let vista = firma(); + const vigia = repo.state.onDidChange(() => { + if (firma() === vista) { return; } + vista = firma(); + cargar(); + }); + + paneles.set(raiz, { panel, cargar }); + const suscripcion = panel.webview.onDidReceiveMessage(m => { + if (m && m.tipo === 'listo') { cargar(); } + }); + panel.onDidDispose(() => { + cerrado = true; + paneles.delete(raiz); + if (cancelar) { cancelar.cancel(); cancelar.dispose(); } + vigia.dispose(); + suscripcion.dispose(); + }); + panel.webview.html = html(panel.webview, context.extensionUri, crypto.randomBytes(16).toString('base64')); +} + +// sin argumento va el repo que enseña la vista Contributors; desde la paleta sin esa vista, el del editor o el primero +function registrar(context, protegido, repoDeContribuidores) { + context.subscriptions.push(vscode.commands.registerCommand('gitLore.contributorsChart', () => protegido(async () => { + const api = await git.obtenerApi(); + const editor = vscode.window.activeTextEditor; + const repo = repoDeContribuidores() || (editor && api.getRepository(editor.document.uri)) || api.repositories[0]; + if (!repo) { return vscode.window.showWarningMessage(t('Open a folder with a git repository first')); } + abrir(context, repo); + }))); +} + +module.exports = { registrar }; diff --git a/test/nucleo.test.js b/test/nucleo.test.js index 6834c20..2fa6ee3 100644 --- a/test/nucleo.test.js +++ b/test/nucleo.test.js @@ -254,3 +254,28 @@ test('contribuidores: shortlog agrupado por correo, con el nombre más usado', ( const real = parsearShortlog(git('shortlog', '-sne', 'HEAD')); assert.deepStrictEqual(real.map(x => [x.nombre, x.commits]), [['Ana', 3]]); }); + +test('contribuidores: líneas por persona con la misma clave que shortlog', () => { + const { parsearLineasPorAutor, parsearShortlog, claveDePersona, FORMATO_AUTOR } = require('../src/nucleo/parseo'); + const l = parsearLineasPorAutor('\x1eANA@x.com\x1fAna\n\n3\t1\ta.txt\n-\t-\tlogo.png\n\x1eana@x.com\x1fAna López\n\n2\t0\tb.txt\n\x1e\x1fSin Correo\n\n1\t1\tc.txt\n'); + assert.deepStrictEqual(Object.fromEntries(l), { 'ana@x.com': { mas: 5, menos: 1 }, 'sin correo': { mas: 1, menos: 1 } }); + assert.strictEqual(claveDePersona('', 'Sin Correo'), 'sin correo'); + // real: cada persona de shortlog encuentra sus líneas + const real = parsearLineasPorAutor(git('log', 'HEAD', '--no-merges', '--numstat', `--format=${FORMATO_AUTOR}`)); + for (const p of parsearShortlog(git('shortlog', '-sne', 'HEAD'))) { assert.ok(real.get(claveDePersona(p.correo, p.nombre)).mas > 0); } +}); + +test('burbujas: ninguna se solapa y todas caben en la caja', () => { + const { empaquetar, encajar } = require('../media/burbujas'); + const radios = [45, 16, 16, 12, 10, 8.5, 7, 7, 6.6, 3, 1, 1, 1]; + const sitios = encajar(empaquetar(radios, { hueco: 1, aspecto: 2.5 }), 900, 300); + assert.strictEqual(sitios.length, radios.length); + for (let i = 0; i < sitios.length; i++) { + const a = sitios[i]; + assert.ok(a.x - a.r >= 3.9 && a.x + a.r <= 900.1 - 3.9 && a.y - a.r >= 3.9 && a.y + a.r <= 300.1 - 3.9); + for (let j = i + 1; j < sitios.length; j++) { assert.ok(Math.hypot(a.x - sitios[j].x, a.y - sitios[j].y) >= a.r + sitios[j].r); } + } + // proporcional: el doble de radio sigue siendo el doble tras encajar + assert.ok(Math.abs(sitios[0].r / sitios[1].r - 45 / 16) < 1e-9); + assert.deepStrictEqual(encajar(empaquetar([5]), 100, 100).map(s => [s.x, s.y, s.r]), [[50, 50, 46]]); +}); From 3823d58b69605d8a367a4d9aa7c32d523356a098 Mon Sep 17 00:00:00 2001 From: jlopezdev Date: Tue, 24 Nov 2026 15:57:21 +0100 Subject: [PATCH 2/4] =?UTF-8?q?fix:=20el=20gr=C3=A1fico=20de=20colaborador?= =?UTF-8?q?es=20se=20redibuja=20tras=20recargar=20oculto=20y=20no=20se=20b?= =?UTF-8?q?orra=20si=20fallan=20las=20l=C3=ADneas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- media/burbujas.js | 6 ++++-- media/reparto.js | 8 ++++++-- src/reparto-vista.js | 6 +++++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/media/burbujas.js b/media/burbujas.js index f486d84..898ced9 100644 --- a/media/burbujas.js +++ b/media/burbujas.js @@ -8,12 +8,14 @@ // espiral a lo ancho para llenar un panel apaisado function empaquetar(radios, { hueco = 2, aspecto = 1 } = {}) { const sitios = []; - const paso = Math.max(0.5, Math.min(...radios.filter(r => r > 0)) / 4); + const menor = Math.min(...radios.filter(r => r > 0)); + const paso = Number.isFinite(menor) ? Math.max(0.5, menor / 4) : 1; // sin radios positivos, un paso cualquiera for (const r of radios) { let x = 0; let y = 0; if (sitios.length) { - for (let a = 0; a < 2000; a += 0.05) { + // sin tope: la espiral acaba saliendo de todo lo ya colocado + for (let a = 0; ; a += 0.05) { const d = paso * a; x = d * Math.cos(a) * aspecto; y = d * Math.sin(a); diff --git a/media/reparto.js b/media/reparto.js index 3d109cc..668428e 100644 --- a/media/reparto.js +++ b/media/reparto.js @@ -88,8 +88,11 @@ lienzo.replaceChildren(dibujo); } + // hasOwn: alguien sin correo llamado «constructor» no debe leer lo heredado de Object + const lineasDe = clave => (lineas && clave && Object.hasOwn(lineas, clave) ? lineas[clave] : null); + function celdaLineas(td, p) { - const l = lineas && lineas[p.clave]; + const l = lineasDe(p.clave); td.replaceChildren(); td.removeAttribute('title'); if (!lineas) { td.textContent = '…'; return; } @@ -146,6 +149,7 @@ reparto.append(lienzo, tabla); reparto.classList.toggle('animar', animar && !quieto.matches); animar = false; + anchoPintado = 0; // lienzo nuevo: si ahora mide 0 (panel oculto), el ResizeObserver lo dibuja al volver dibujarBurbujas(); } @@ -154,7 +158,7 @@ const partes = [el('strong', '', quien.nombre)]; if (quien.correo) { partes.push(el('span', 'suave', quien.correo)); } partes.push(el('span', '', `${cuantos(quien.commits, T.unCommit, T.commits)} · ${porcentaje(quien.commits)}`)); - const l = lineas && quien.clave && lineas[quien.clave]; + const l = lineasDe(quien.clave); if (l) { const s = el('span'); s.append(el('span', 'mas', `+${numero.format(l.mas)}`), el('span', 'menos', ` −${numero.format(l.menos)}`)); diff --git a/src/reparto-vista.js b/src/reparto-vista.js index f0adf6f..a98d330 100644 --- a/src/reparto-vista.js +++ b/src/reparto-vista.js @@ -76,7 +76,11 @@ function abrir(context, repo) { rama: head ? head.name || (head.commit && corto(head.commit)) : '', personas: personas.map((p, i) => ({ ...p, clave: claveDePersona(p.correo, p.nombre), color: i < COLORES ? i : null })), }); - const lineas = await git.lineasPorAutor(repo, token); + // si fallan las líneas, el gráfico de commits ya pintado se queda: sus celdas salen vacías + const lineas = await git.lineasPorAutor(repo, token).catch(e => { + if (e instanceof vscode.CancellationError) { throw e; } + return new Map(); + }); if (mia === generacion) { enviar({ tipo: 'lineas', lineas: Object.fromEntries(lineas) }); } } catch (e) { if (e instanceof vscode.CancellationError || mia !== generacion) { return; } From 5867c255278fef6cb33219eff8063c7eff5c2066 Mon Sep 17 00:00:00 2001 From: jlopezdev Date: Tue, 24 Nov 2026 15:59:52 +0100 Subject: [PATCH 3/4] =?UTF-8?q?fix:=20el=20gr=C3=A1fico=20de=20colaborador?= =?UTF-8?q?es=20no=20recalcula=20las=20l=C3=ADneas=20en=20el=20mismo=20com?= =?UTF-8?q?mit=20y=20registra=20si=20fallan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extension.js | 2 +- media/burbujas.js | 5 +++-- src/reparto-vista.js | 27 ++++++++++++++++++--------- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/extension.js b/extension.js index 06e7613..4ae8f0c 100644 --- a/extension.js +++ b/extension.js @@ -63,7 +63,7 @@ function activate(context) { grafo.registrar(context, protegido); historia.registrar(context, protegido, ficheroDelHistorial); revisiones.registrar(context, protegido); - reparto.registrar(context, protegido, contribuidores.registrar(context, log)); + reparto.registrar(context, protegido, log, contribuidores.registrar(context, log)); } function deactivate() { } diff --git a/media/burbujas.js b/media/burbujas.js index 898ced9..606f8dd 100644 --- a/media/burbujas.js +++ b/media/burbujas.js @@ -8,8 +8,9 @@ // espiral a lo ancho para llenar un panel apaisado function empaquetar(radios, { hueco = 2, aspecto = 1 } = {}) { const sitios = []; - const menor = Math.min(...radios.filter(r => r > 0)); - const paso = Number.isFinite(menor) ? Math.max(0.5, menor / 4) : 1; // sin radios positivos, un paso cualquiera + const positivos = radios.filter(r => r > 0); + // relativo también al mayor: con 10.000 commits frente a 1, un paso del menor daría millones de vueltas + const paso = positivos.length ? Math.max(0.5, Math.min(...positivos), Math.max(...positivos) / 50) / 4 : 1; for (const r of radios) { let x = 0; let y = 0; diff --git a/src/reparto-vista.js b/src/reparto-vista.js index a98d330..261da08 100644 --- a/src/reparto-vista.js +++ b/src/reparto-vista.js @@ -41,7 +41,7 @@ function html(webview, raizExt, nonce) { `; } -function abrir(context, repo) { +function abrir(context, repo, log) { const raiz = repo.rootUri.fsPath; const existente = paneles.get(raiz); if (existente) { @@ -58,6 +58,7 @@ function abrir(context, repo) { let cerrado = false; let generacion = 0; let cancelar = null; + let hechas = null; // { commit, lineas }: volver a abrir el panel en el mismo commit no recorre otra vez la historia const enviar = m => { if (!cerrado) { panel.webview.postMessage(m).then(undefined, () => { }); } }; // primero los commits (shortlog es rápido) y luego las líneas, que recorren toda la historia @@ -76,12 +77,20 @@ function abrir(context, repo) { rama: head ? head.name || (head.commit && corto(head.commit)) : '', personas: personas.map((p, i) => ({ ...p, clave: claveDePersona(p.correo, p.nombre), color: i < COLORES ? i : null })), }); - // si fallan las líneas, el gráfico de commits ya pintado se queda: sus celdas salen vacías - const lineas = await git.lineasPorAutor(repo, token).catch(e => { - if (e instanceof vscode.CancellationError) { throw e; } - return new Map(); - }); - if (mia === generacion) { enviar({ tipo: 'lineas', lineas: Object.fromEntries(lineas) }); } + const commit = head && head.commit; + if (!hechas || hechas.commit !== commit) { + // si fallan las líneas, el gráfico de commits ya pintado se queda: sus celdas salen vacías + // shortcut: la salida de --numstat entera va a memoria; en repos enormes (Linux) puede fallar, y entonces + // haría falta leerla por streaming + const lineas = await git.lineasPorAutor(repo, token).catch(e => { + if (e instanceof vscode.CancellationError) { throw e; } + log(`contributors chart: ${e.message}`); + return null; + }); + if (mia !== generacion) { return; } + hechas = lineas ? { commit, lineas: Object.fromEntries(lineas) } : null; + } + if (mia === generacion) { enviar({ tipo: 'lineas', lineas: hechas ? hechas.lineas : {} }); } } catch (e) { if (e instanceof vscode.CancellationError || mia !== generacion) { return; } enviar({ tipo: 'error', mensaje: e.message }); @@ -112,13 +121,13 @@ function abrir(context, repo) { } // sin argumento va el repo que enseña la vista Contributors; desde la paleta sin esa vista, el del editor o el primero -function registrar(context, protegido, repoDeContribuidores) { +function registrar(context, protegido, log, repoDeContribuidores) { context.subscriptions.push(vscode.commands.registerCommand('gitLore.contributorsChart', () => protegido(async () => { const api = await git.obtenerApi(); const editor = vscode.window.activeTextEditor; const repo = repoDeContribuidores() || (editor && api.getRepository(editor.document.uri)) || api.repositories[0]; if (!repo) { return vscode.window.showWarningMessage(t('Open a folder with a git repository first')); } - abrir(context, repo); + abrir(context, repo, log); }))); } From 5196a87a51f19941d57952050327a27bf4095b9d Mon Sep 17 00:00:00 2001 From: jlopezdev Date: Tue, 24 Nov 2026 16:02:19 +0100 Subject: [PATCH 4/4] =?UTF-8?q?fix:=20paso=20m=C3=ADnimo=20de=20la=20espir?= =?UTF-8?q?al=20y=20comentario=20de=20la=20cach=C3=A9=20de=20l=C3=ADneas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- media/burbujas.js | 2 +- src/reparto-vista.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/media/burbujas.js b/media/burbujas.js index 606f8dd..7c5cb67 100644 --- a/media/burbujas.js +++ b/media/burbujas.js @@ -10,7 +10,7 @@ const sitios = []; const positivos = radios.filter(r => r > 0); // relativo también al mayor: con 10.000 commits frente a 1, un paso del menor daría millones de vueltas - const paso = positivos.length ? Math.max(0.5, Math.min(...positivos), Math.max(...positivos) / 50) / 4 : 1; + const paso = positivos.length ? Math.max(0.5, Math.max(Math.min(...positivos), Math.max(...positivos) / 50) / 4) : 1; for (const r of radios) { let x = 0; let y = 0; diff --git a/src/reparto-vista.js b/src/reparto-vista.js index 261da08..10d4b23 100644 --- a/src/reparto-vista.js +++ b/src/reparto-vista.js @@ -58,7 +58,7 @@ function abrir(context, repo, log) { let cerrado = false; let generacion = 0; let cancelar = null; - let hechas = null; // { commit, lineas }: volver a abrir el panel en el mismo commit no recorre otra vez la historia + let hechas = null; // { commit, lineas }: recargar este panel sin cambiar de commit no recorre otra vez la historia const enviar = m => { if (!cerrado) { panel.webview.postMessage(m).then(undefined, () => { }); } }; // primero los commits (shortlog es rápido) y luego las líneas, que recorren toda la historia