hopdeck 1.3.1 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/README.en.md +5 -1
- package/README.md +6 -1
- package/bin/hopdeck.js +240 -69
- package/lib/history.js +42 -9
- package/lib/i18n.js +10 -2
- package/lib/images.js +40 -9
- package/lib/mascot.js +149 -0
- package/lib/text.js +20 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Cambios
|
|
2
2
|
|
|
3
|
+
## Sin publicar
|
|
4
|
+
|
|
5
|
+
### Nuevo
|
|
6
|
+
- **La mascota de Hopdeck, un sapo naranja con auriculares.** Sale en la pantalla de inicio (el panel derecho cuando no hay ningún chat abierto), encima del texto y del mayor tamaño que quepa; si el terminal es pequeño o usas `NO_COLOR`, se queda el texto de siempre. También en la pantalla de carga y en el panel de tmux. Y con el comando `hopdeck mascot` (`--size small|normal|large`, `--plain` para dibujarla sin colores). Va dentro del programa, sin archivos de imagen ni Python; en el README hay una imagen (`docs/mascot.png`).
|
|
7
|
+
|
|
8
|
+
## 1.4.1
|
|
9
|
+
|
|
10
|
+
### Cambiado
|
|
11
|
+
- **Seleccionar texto del chat ya no lo copia solo.** Al soltar, la selección se queda marcada y se copia con `Ctrl+C` o con el clic derecho; `Esc` o un clic en otro sitio la quitan (`Esc` no llega a Claude mientras hay algo seleccionado, porque lo interrumpiría). Quien prefiera el comportamiento anterior puede poner `"copyOnSelect": true` en `~/.hopdeck.json`.
|
|
12
|
+
|
|
13
|
+
### Arreglado
|
|
14
|
+
- **No se podía seleccionar más de lo que cabía en pantalla.** Al arrastrar contra el borde de arriba o de abajo del chat, este se desplaza solo (aunque el ratón se quede quieto) y la selección sigue. La selección ahora se ancla a las líneas del historial, no a las filas de la pantalla, así que también sigue en su sitio si usas la rueda mientras seleccionas.
|
|
15
|
+
- **El spinner de «trabajando» salía sin que Claude estuviera haciendo nada**, a veces en chats donde ni estabas. Hopdeck marcaba un chat como trabajando si escribía cualquier cosa en el último segundo, y eso también ocurre al mover o redimensionar los paneles (todos los chats se repintan), al cambiar de ventana o al actualizarse la barra de estado. Ahora solo cuenta como trabajando cuando la pantalla de Claude muestra «esc to interrupt», y el repintado justo después de redimensionar se ignora. Si una versión de Claude cambiara ese texto, `HOPDECK_BUSY=output` devuelve el criterio anterior.
|
|
16
|
+
|
|
17
|
+
## 1.4.0
|
|
18
|
+
|
|
19
|
+
### Nuevo
|
|
20
|
+
- **Ancho de los paneles con el ratón.** Agarra con el cursor la línea `│` que separa la lista del chat, o el chat del panel de git, y arrástrala a izquierda o derecha. Cada panel puede medir entre el 15 % y el 50 % del ancho del terminal (nunca menos de 20 columnas), el chat siempre conserva su ancho mínimo y el ancho se recuerda para la próxima vez. Solo en el terminal integrado (en tmux, arrastra el borde del panel como siempre).
|
|
21
|
+
|
|
22
|
+
### Mejorado
|
|
23
|
+
- **La búsqueda es más fácil de encontrar y falla menos.**
|
|
24
|
+
- **Se ve de dónde parte:** arriba a la derecha de la lista hay siempre un `⌕ / buscar`; pulsando `/` (o haciendo clic en esa fila) el cuadro de búsqueda ocupa el lugar del título, arriba, y no en la última fila. El pie dice cuántos resultados hay, dónde se busca y qué teclas valen.
|
|
25
|
+
- **`⏎` abre la conversación marcada en el momento:** al escribir se marca el primer resultado y `⏎` lo abre, sin tener que pulsar `⏎` dos veces como antes (el salto rápido `Ctrl+P` ya funcionaba así).
|
|
26
|
+
- **Encuentra más:** las palabras valen en cualquier orden y sin importar mayúsculas ni acentos («vision roles» encuentra «Roles y visión»), y se comparan con el proyecto, el título y el primer mensaje. El salto rápido tampoco distingue acentos.
|
|
27
|
+
- **Si no coincide ningún título, se busca sola dentro del contenido** de las conversaciones (ya no hace falta saber que `Tab` lo activa). Con `Tab` se fuerza también cuando sí hay coincidencias.
|
|
28
|
+
- **Sin resultados lo dice:** «Sin resultados para …» y qué hacer, en lugar de una lista vacía.
|
|
29
|
+
|
|
30
|
+
### Arreglado
|
|
31
|
+
- **Una misma conversación aparecía varias veces** (con el mismo título y un `#xxxx` distinto). Cada vez que reanudas una conversación, o Claude Code la continúa tras agotar el contexto, crea un archivo nuevo que copia todo el historial anterior. Hopdeck ahora reconoce que comparten el primer mensaje, los junta en una sola fila y abre la que tiene el último mensaje, que ya contiene todo lo anterior. La fila lleva `↻N` (continuada N veces). El `#xxxx` queda solo para conversaciones realmente distintas con el mismo título. La fecha del archivo no sirve para elegir: también cambia al abrir una conversación vieja.
|
|
32
|
+
- **macOS: el cuadro del hover salía sin la imagen** cuando el formato no lo entendía el decodificador propio (WebP, GIF, HEIC, TIFF, PNG entrelazado o imágenes enormes). Ahora esas imágenes se convierten con `sips`, que viene con macOS. Y si aun así no se puede leer, el cuadro indica el formato («No se puede previsualizar este formato (image/webp)») para saber por qué.
|
|
33
|
+
|
|
3
34
|
## 1.3.1
|
|
4
35
|
|
|
5
36
|
### Nuevo
|
package/README.en.md
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
</picture>
|
|
6
6
|
</p>
|
|
7
7
|
|
|
8
|
+
<p align="center"><img alt="The Hopdeck mascot: an orange toad with headphones" src="docs/mascot.png" width="130"></p>
|
|
9
|
+
|
|
8
10
|
<p align="center"><b>Hop between your Claude Code projects and conversations without leaving the terminal.</b></p>
|
|
9
11
|
|
|
10
12
|
[Español](README.md) · **English**
|
|
@@ -178,7 +180,7 @@ It refreshes itself every few seconds and never modifies the repository. It need
|
|
|
178
180
|
### Scroll and copy
|
|
179
181
|
|
|
180
182
|
- **Scroll** the chat with the mouse wheel or `PgUp` / `PgDn`; `End` or typing returns you to the bottom.
|
|
181
|
-
- **
|
|
183
|
+
- **Select and copy:** drag with the mouse over the chat to mark text; it is not copied by itself. Copy it with `Ctrl+C` or right click, and clear the selection with `Esc` or by clicking elsewhere. If you drag to the top or bottom edge the chat scrolls on its own and the selection follows, so you can mark far more than fits on screen. For the old behaviour (copy on release) set `"copyOnSelect": true` in `~/.hopdeck.json`. `F3` turns the mouse off if you prefer terminal selection (or use `Shift`+drag).
|
|
182
184
|
|
|
183
185
|
### More
|
|
184
186
|
|
|
@@ -192,6 +194,7 @@ It refreshes itself every few seconds and never modifies the repository. It need
|
|
|
192
194
|
| `hopdeck` | Opens Hopdeck |
|
|
193
195
|
| `hopdeck shortcut on` / `hopdeck shortcut off` | Installs or removes the shortcut so that `claude` opens Hopdeck |
|
|
194
196
|
| `hopdeck theme light` / `dark` / `auto` | Changes the color theme and remembers it (`hopdeck theme` shows the current one) |
|
|
197
|
+
| `hopdeck mascot` | Draws the mascot in the terminal (`--size small\|normal\|large`; `--plain` draws it without colors). It also shows on Hopdeck's start screen |
|
|
195
198
|
| `hopdeck uninstall` | **Uninstalls Hopdeck completely**: the shortcut, your preferences and cache, and the program. Asks first (without a terminal, use `--yes`). Does not touch your Claude Code history |
|
|
196
199
|
| `hopdeck doctor` | Checks your setup and tells you how to fix whatever is missing |
|
|
197
200
|
| `hopdeck --list` | Lists the projects as plain text |
|
|
@@ -232,6 +235,7 @@ Keys in `~/.hopdeck.json` you can edit by hand:
|
|
|
232
235
|
|---|---|---|
|
|
233
236
|
| `notify` | Desktop notification when a chat finishes | `true` |
|
|
234
237
|
| `mouse` | Mouse enabled (`F3` toggles) | `true` |
|
|
238
|
+
| `copyOnSelect` | Copy to the clipboard as soon as you release a chat selection | `false` |
|
|
235
239
|
| `sidebar` | List width (`[` and `]` adjust it) | automatic |
|
|
236
240
|
| `maxImages` | Max images per conversation in the gallery | `200` |
|
|
237
241
|
| `previewMsgs` | Messages shown in the preview | `12` |
|
package/README.md
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
</picture>
|
|
6
6
|
</p>
|
|
7
7
|
|
|
8
|
+
<p align="center"><img alt="La mascota de Hopdeck: un sapo naranja con auriculares" src="docs/mascot.png" width="130"></p>
|
|
9
|
+
|
|
8
10
|
<p align="center"><b>Salta entre tus proyectos y conversaciones de Claude Code, sin salir de la terminal.</b></p>
|
|
9
11
|
|
|
10
12
|
**Español** · [English](README.en.md)
|
|
@@ -178,7 +180,7 @@ Se refresca solo cada pocos segundos y no modifica nada en el repositorio. Neces
|
|
|
178
180
|
### Scroll y copiar
|
|
179
181
|
|
|
180
182
|
- **Scroll** en el chat: rueda del ratón o `PgUp` / `PgDn`; `End` o escribir algo te devuelve al final.
|
|
181
|
-
- **
|
|
183
|
+
- **Seleccionar y copiar:** arrastra con el ratón sobre el chat para marcar texto; no se copia solo. Cópialo con `Ctrl+C` o con el clic derecho, y quita la selección con `Esc` o haciendo clic en otro sitio. Si arrastras hasta el borde de arriba o de abajo, el chat se desplaza solo y la selección sigue, así que puedes marcar mucho más de lo que cabe en pantalla. Si prefieres el comportamiento anterior (copiar al soltar), pon `"copyOnSelect": true` en `~/.hopdeck.json`. `F3` apaga el ratón si prefieres seleccionar con el terminal (o usa `Shift`+arrastrar).
|
|
182
184
|
|
|
183
185
|
### Otros detalles
|
|
184
186
|
|
|
@@ -192,6 +194,7 @@ Se refresca solo cada pocos segundos y no modifica nada en el repositorio. Neces
|
|
|
192
194
|
| `hopdeck` | Abre Hopdeck |
|
|
193
195
|
| `hopdeck shortcut on` / `hopdeck shortcut off` | Instala o quita el atajo para que `claude` abra Hopdeck |
|
|
194
196
|
| `hopdeck theme light` / `dark` / `auto` | Cambia el tema de colores y lo guarda (`hopdeck theme` muestra el actual) |
|
|
197
|
+
| `hopdeck mascot` | Dibuja la mascota en el terminal (`--size small\|normal\|large`; `--plain` la dibuja sin colores). También sale en la pantalla de inicio de Hopdeck |
|
|
195
198
|
| `hopdeck uninstall` | **Desinstala Hopdeck por completo**: el atajo, tus preferencias y la caché, y el programa. Pregunta antes (sin terminal, usa `--yes`). No toca tu historial de Claude Code |
|
|
196
199
|
| `hopdeck doctor` | Revisa tu instalación y dice cómo arreglar lo que falte |
|
|
197
200
|
| `hopdeck --list` | Lista los proyectos en texto plano |
|
|
@@ -217,6 +220,7 @@ Casi nunca hace falta tocar nada. Lo más útil:
|
|
|
217
220
|
| `HOPDECK_LANG` | `es` o `en` (por defecto, el idioma del sistema) |
|
|
218
221
|
| `HOPDECK_THEME` | `light` o `dark`: manda sobre lo guardado con `hopdeck theme` |
|
|
219
222
|
| `HOPDECK_SIXEL` | `1` fuerza la imagen real al pasar el cursor por `[Image #N]`, `0` usa siempre bloques (por defecto se detecta) |
|
|
223
|
+
| `HOPDECK_BUSY` | `output` marca un chat como «trabajando» con cualquier salida reciente. Por defecto solo cuando Claude muestra «esc to interrupt» |
|
|
220
224
|
| `NO_COLOR` | Quita los colores |
|
|
221
225
|
| `CLAUDE_CONFIG_DIR` | Carpeta de Claude Code, si no es `~/.claude` |
|
|
222
226
|
| `HOPDECK_SKIP=1` | Salta Hopdeck una vez: `HOPDECK_SKIP=1 claude` |
|
|
@@ -232,6 +236,7 @@ Claves de `~/.hopdeck.json` que puedes editar a mano:
|
|
|
232
236
|
|---|---|---|
|
|
233
237
|
| `notify` | Aviso de escritorio al terminar un chat | `true` |
|
|
234
238
|
| `mouse` | Ratón activado (`F3` lo alterna) | `true` |
|
|
239
|
+
| `copyOnSelect` | Copiar al portapapeles en cuanto sueltas la selección del chat | `false` |
|
|
235
240
|
| `sidebar` | Ancho de la lista (`[` y `]` lo ajustan) | automático |
|
|
236
241
|
| `maxImages` | Imágenes máximas por conversación en la galería | `200` |
|
|
237
242
|
| `previewMsgs` | Mensajes mostrados en la vista previa | `12` |
|
package/bin/hopdeck.js
CHANGED
|
@@ -13,7 +13,8 @@ const readline = require('readline');
|
|
|
13
13
|
|
|
14
14
|
const { LANG, T } = require('../lib/i18n');
|
|
15
15
|
const { TRUE, NOCOL, LIGHT, setTheme, isLight, fg, bg, R, C, cw, strW, fit, clean } = require('../lib/style');
|
|
16
|
-
const
|
|
16
|
+
const mascot = require('../lib/mascot');
|
|
17
|
+
const { baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, wrapText } = require('../lib/text');
|
|
17
18
|
const hist = require('../lib/history');
|
|
18
19
|
const { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, readSession, decodeDir, projectDirs, buildProject, beginScan, endScan } = hist;
|
|
19
20
|
const images = require('../lib/images');
|
|
@@ -126,7 +127,7 @@ function ago(ms) {
|
|
|
126
127
|
}
|
|
127
128
|
|
|
128
129
|
// ───────────────────────── estado ─────────────────────────
|
|
129
|
-
const S = { qpos: 0, pc: 0, fb: null, confirmMk: null, confirmClose: null, more: new Set(), qs: null, promptKind: 'folder', renameTarget: null, deep: false, deepHits: null, showHidden: false, prompt: null, help: false, loading: false, projects: [], pi: 0, si: 0, focus: 0, query: '', searching: false, poff: 0, soff: 0, flash: '', c: 0, coff: 0, open: null, live: new Set(), liveKey: '' };
|
|
130
|
+
const S = { auto: false, qpos: 0, pc: 0, fb: null, confirmMk: null, confirmClose: null, more: new Set(), qs: null, promptKind: 'folder', renameTarget: null, deep: false, deepHits: null, showHidden: false, prompt: null, help: false, loading: false, projects: [], pi: 0, si: 0, focus: 0, query: '', searching: false, poff: 0, soff: 0, flash: '', c: 0, coff: 0, open: null, live: new Set(), liveKey: '' };
|
|
130
131
|
const SIDEBAR = process.argv.includes('--sidebar');
|
|
131
132
|
let EMBED = false; // vista dividida con terminal embebido (Windows / sin tmux)
|
|
132
133
|
const E = { sessions: new Map(), shown: null, focus: 'left', pend: null, deps: null, mouse: CFG.mouse !== false, hideSide: false, git: !!CFG.git, note: null, sel: null, gallery: null, hover: null, sixelDetected: false, cell: { w: 10, h: 20 }, sixelKey: null, sixelAt: 0, sixelStale: false, sixelRetry: null };
|
|
@@ -154,16 +155,21 @@ async function reloadAsync(after, silent) {
|
|
|
154
155
|
|
|
155
156
|
const clamp = (n, a, b) => Math.max(a, Math.min(b, n));
|
|
156
157
|
|
|
158
|
+
/** Marca junto a una conversación: ↻N = es la misma conversación continuada N veces (se muestra solo la última); #xxxx = otra distinta con el mismo título. */
|
|
159
|
+
const sessTag = (s) => (s.parts ? '↻' + s.parts : s.dup ? '#' + s.id.slice(0, 4) : '');
|
|
160
|
+
|
|
157
161
|
function view() {
|
|
158
|
-
|
|
162
|
+
// La búsqueda son palabras sueltas, sin importar el orden, mayúsculas ni acentos: «vistas roles» encuentra «Roles y vistas».
|
|
163
|
+
// Cada conversación se compara con proyecto + título + primer mensaje; el proyecto entero sale si lo que se busca está en su nombre o ruta.
|
|
164
|
+
const ws = queryWords(S.query);
|
|
159
165
|
const base = S.projects.filter((p) => S.showHidden || !p.hidden);
|
|
160
166
|
const vis = (x) => S.showHidden || !CFG.archived.includes(x.id);
|
|
161
|
-
if (!
|
|
162
|
-
const hitS = (x) => (x.title + ' ' + x.first)
|
|
167
|
+
if (!ws.length) return base.map((p) => ({ p, ss: p.sessions.filter(vis) }));
|
|
168
|
+
const hitS = (p, x) => matchWords(ws, x._f || (x._f = fold(p.name + ' ' + x.title + ' ' + x.first))) || !!(S.deepHits && S.deepHits.has(x.id));
|
|
163
169
|
const out = [];
|
|
164
170
|
for (const p of base) {
|
|
165
|
-
const hit = (p.name + ' ' + p.cwd)
|
|
166
|
-
const ss = (hit ? p.sessions : p.sessions.filter(hitS)).filter(vis);
|
|
171
|
+
const hit = matchWords(ws, p._f || (p._f = fold(p.name + ' ' + p.cwd)));
|
|
172
|
+
const ss = (hit ? p.sessions : p.sessions.filter((x) => hitS(p, x))).filter(vis);
|
|
167
173
|
if (hit || ss.length) out.push({ p, ss });
|
|
168
174
|
}
|
|
169
175
|
return out;
|
|
@@ -174,8 +180,11 @@ let deepT = null, deepTok = 0, deepPrev = null, deepJob = null;
|
|
|
174
180
|
function queryChanged() {
|
|
175
181
|
clearTimeout(deepT); deepTok++; S.deepHits = null;
|
|
176
182
|
if (deepJob) { deepJob.cancel(); deepJob = null; }
|
|
177
|
-
|
|
178
|
-
|
|
183
|
+
// Si ningún título ni proyecto coincide, se busca solo dentro del contenido sin que haya que pedirlo con Tab
|
|
184
|
+
S.auto = !S.deep && S.query.trim().length >= 3 && !view().length;
|
|
185
|
+
const deepOn = S.deep || S.auto;
|
|
186
|
+
if (!deepOn || !S.query.trim()) deepPrev = null;
|
|
187
|
+
if (!deepOn || S.query.trim().length < 3) { if (!reloading) S.loading = false; return; }
|
|
179
188
|
const tok = deepTok; S.loading = true; ensureSpin();
|
|
180
189
|
deepT = setTimeout(() => {
|
|
181
190
|
const q = S.query.trim().toLowerCase(), hits = new Set();
|
|
@@ -260,7 +269,7 @@ function frame(cols, rows) {
|
|
|
260
269
|
const tw = rw - 2 - when.length - 2;
|
|
261
270
|
right = fit([[mark, C.accent], [e.title, sel ? C.text + C.bold : C.text],
|
|
262
271
|
[e.first && e.first !== e.title ? ' ' + e.first : '', C.dim],
|
|
263
|
-
[e
|
|
272
|
+
[sessTag(e) ? ' ' + sessTag(e) : '', C.accent]], tw + 2, base) +
|
|
264
273
|
fit([[' ' + when, C.dim]], rw - tw - 2, base);
|
|
265
274
|
}
|
|
266
275
|
} else right = ' '.repeat(rw);
|
|
@@ -333,18 +342,20 @@ function chatMark(id) {
|
|
|
333
342
|
|
|
334
343
|
/** Trocea `text` en segmentos [[texto, estilo]] resaltando las coincidencias (sin distinguir mayúsculas) con la búsqueda `q` (en minúsculas). */
|
|
335
344
|
function hl(text, q, style) {
|
|
336
|
-
const t = String(text);
|
|
337
|
-
if (!
|
|
338
|
-
const
|
|
339
|
-
if (
|
|
340
|
-
const
|
|
341
|
-
for (let at =
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
+
const t = String(text), ws = queryWords(q);
|
|
346
|
+
if (!ws.length) return [[t, style]];
|
|
347
|
+
const f = fold(t);
|
|
348
|
+
if (f.length !== t.length) return [[t, style]]; // algunas letras cambian de largo al plegarlas: no se resalta
|
|
349
|
+
const on = new Array(t.length).fill(false); // cada palabra de la búsqueda, en cualquier parte y sin importar acentos ni mayúsculas
|
|
350
|
+
for (const w of ws) for (let at = f.indexOf(w); at >= 0; at = f.indexOf(w, at + w.length)) for (let i = at; i < at + w.length; i++) on[i] = true;
|
|
351
|
+
if (!on.includes(true)) return [[t, style]];
|
|
352
|
+
const out = [];
|
|
353
|
+
for (let i = 0; i < t.length;) {
|
|
354
|
+
let j = i; while (j < t.length && on[j] === on[i]) j++;
|
|
355
|
+
out.push([t.slice(i, j), on[i] ? C.brand + C.bold : style]);
|
|
356
|
+
i = j;
|
|
345
357
|
}
|
|
346
|
-
|
|
347
|
-
return out.length ? out : [[t, style]];
|
|
358
|
+
return out;
|
|
348
359
|
}
|
|
349
360
|
|
|
350
361
|
/** Resumen de los chats abiertos para la cabecera de la lista: trabajando ⠋, terminados sin ver ✔, abiertos ●. */
|
|
@@ -368,9 +379,19 @@ function frameTree(W, H) {
|
|
|
368
379
|
const bodyH = H - 5;
|
|
369
380
|
S.coff = scroll(S.coff, S.c, bodyH);
|
|
370
381
|
const lines = [];
|
|
371
|
-
|
|
382
|
+
const searchOn = !S.fb && !S.qs && S.prompt === null && !S.help && (S.searching || !!S.query.trim()); // hay una búsqueda en marcha
|
|
383
|
+
const head = [[' » ', C.brand], ['Hop', C.brand + C.bold], ['deck', C.text + C.bold], [' ' + S.projects.length, C.dim], [S.loading && !searchOn ? ' ' + spin() : '', C.accent], ...liveSummary()];
|
|
384
|
+
// «⌕ / buscar» siempre a la vista, arriba a la derecha (sin la palabra si el título y los chats abiertos ya ocupan el sitio)
|
|
385
|
+
const headW = head.reduce((a, [t]) => a + strW(t), 0), longHint = ' ⌕ / ' + T.k.find + ' ', hint = headW + strW(longHint) <= W ? longHint : headW + 5 <= W ? ' ⌕ / ' : '';
|
|
386
|
+
lines.push(searchOn
|
|
387
|
+
// el cuadro de búsqueda ocupa el lugar del título, arriba, donde se mira primero
|
|
388
|
+
? fit([[' ⌕ ', C.accent], ...withCursor(S.query, S.searching ? S.qpos : [...S.query].length, S.searching), [S.query ? '' : ' ' + T.searchPh, C.dim]], W)
|
|
389
|
+
: hint && !S.fb && !S.qs && S.prompt === null && !S.help ? fit(head, W - strW(hint)) + fit([[' ⌕ ', C.accent], ['/ ', C.accent + C.bold], [hint.slice(5), C.dim]], strW(hint))
|
|
390
|
+
: fit(head, W));
|
|
372
391
|
lines.push(C.faint + '─'.repeat(W) + R);
|
|
373
392
|
const sq0 = S.query.trim().toLowerCase(); // búsqueda activa: se resaltan las coincidencias
|
|
393
|
+
const qWords = searchOn ? queryWords(S.query) : [];
|
|
394
|
+
const nHits = searchOn ? L.filter((x) => x.t === 's' || (x.t === 'p' && !x.open)).length : 0; // conversaciones que coinciden (o el proyecto, si coincidió su nombre)
|
|
374
395
|
const qsList = S.qs ? qsItems() : null;
|
|
375
396
|
const fbList = S.fb && !S.qs ? fbRows() : null;
|
|
376
397
|
if (fbList) { S.fb.i = clamp(S.fb.i, 0, Math.max(0, fbList.length - 1)); S.fb.off = scroll(S.fb.off, S.fb.i, bodyH); lines[0] = fit([[' » ' + T.fbTitle, C.accent + C.bold]], W); }
|
|
@@ -403,6 +424,11 @@ function frameTree(W, H) {
|
|
|
403
424
|
}
|
|
404
425
|
if (S.help) { const t = T.help[r]; lines.push(fit([[t ? ' ' + t : '', r === 0 ? C.accent + C.bold : C.dim]], W)); continue; }
|
|
405
426
|
const e = L[S.coff + r];
|
|
427
|
+
if (!e && searchOn && !L.length && r <= 2) { // búsqueda sin resultados: se dice, y se explica qué hacer
|
|
428
|
+
const msg = r === 0 ? [[' ' + T.noRes(S.query.trim()), C.warn]]
|
|
429
|
+
: r === 2 ? [[' ' + ((S.deep || S.auto) ? (S.loading ? spin() + ' ' + T.searchingContent : '') : T.tryContent), C.dim]] : [];
|
|
430
|
+
lines.push(fit(msg, W)); continue;
|
|
431
|
+
}
|
|
406
432
|
if (!e) { lines.push(' '.repeat(W)); continue; }
|
|
407
433
|
const sel = S.coff + r === S.c;
|
|
408
434
|
const base = sel ? (EMBED && E.focus === 'right' ? C.selOff : C.selOn) : '';
|
|
@@ -426,8 +452,8 @@ function frameTree(W, H) {
|
|
|
426
452
|
lines.push(fit([mark, [' + ', C.accent], [T.newChat, sel ? C.accent + C.bold : C.accent]], W, base));
|
|
427
453
|
} else {
|
|
428
454
|
const [mk, mc] = chatMark(e.s.id);
|
|
429
|
-
const arch = CFG.archived.includes(e.s.id), tag = e.s
|
|
430
|
-
const ts = sel ? C.text + C.bold : arch ? C.dim : C.text, inTxt =
|
|
455
|
+
const arch = CFG.archived.includes(e.s.id), tag = sessTag(e.s);
|
|
456
|
+
const ts = sel ? C.text + C.bold : arch ? C.dim : C.text, inTxt = qWords.length && !matchWords(qWords, fold(e.s.title)); // ⌕: coincide por el proyecto, el primer mensaje o el contenido
|
|
431
457
|
lines.push(fit([mark, [' ', ''], [mk, mc], ...hl(e.s.title, sq0, ts), ...(inTxt ? [[' ⌕', C.dim]] : [])], W - 13, base) +
|
|
432
458
|
fit([[tag.padEnd(6), C.accent], [ago(e.s.mtime).padStart(6), C.dim], [' ', '']], 13, base));
|
|
433
459
|
}
|
|
@@ -436,7 +462,10 @@ function frameTree(W, H) {
|
|
|
436
462
|
lines.push(C.faint + '─'.repeat(W) + R);
|
|
437
463
|
const br = cur && !S.flash ? gitBranch(cur.p.cwd) : '';
|
|
438
464
|
const note = EMBED && E.note;
|
|
439
|
-
|
|
465
|
+
const deepOn = S.deep || S.auto;
|
|
466
|
+
lines.push(fit(S.flash ? [[' ' + S.flash, C.warn]] : searchOn // durante una búsqueda, esta fila dice cuántos resultados hay y dónde se busca
|
|
467
|
+
? [[' ', ''], nHits ? [T.found(nHits), C.accent + C.bold] : [T.noMatch, C.warn], deepOn ? [S.loading ? ' ' + spin() + ' ' + T.searchingContent : ' · ' + T.inContent, C.dim] : ['', '']]
|
|
468
|
+
: S.fb ? [[S.prompt !== null ? ' ' + T.mkIn + ' ' : ' ⌂ ', C.dim], [tailFit(S.fb.dir === '' ? T.fbDrives : shortPath(S.fb.dir) + (S.prompt !== null ? path.sep : ''), W - 14), C.accent]] : note ? [[' ' + note.t, C.ok]]
|
|
440
469
|
: [[br ? ' ⎇ ' + br + ' ' : '', C.accent], [cur ? (br ? '' : ' ⌂ ') + shortPath(cur.p.cwd) : '', C.dim]], W));
|
|
441
470
|
if (S.qs) {
|
|
442
471
|
lines.push(fit([[' ⌕ ', C.accent], ...withCursor(S.qs.q, S.qs.pc), [S.qs.q ? '' : ' ' + T.qsHint, C.dim]], W));
|
|
@@ -445,9 +474,10 @@ function frameTree(W, H) {
|
|
|
445
474
|
lines.push(fit([[rn ? ' ✎ ' : ' ⌂ ', C.accent], ...withCursor(S.prompt, S.pc), [S.prompt ? '' : ' ' + (rn ? T.renameLbl : T.pathPrompt) + '…', C.dim]], W));
|
|
446
475
|
} else if (S.fb) {
|
|
447
476
|
lines.push(fit(S.fb.filt || S.fb.q ? [[' / ', C.accent], ...withCursor(S.fb.q, S.fb.qp, S.fb.filt)] : [[' ' + T.fbHint, C.dim]], W));
|
|
448
|
-
} else if (
|
|
449
|
-
|
|
450
|
-
|
|
477
|
+
} else if (searchOn) {
|
|
478
|
+
// teclas de la búsqueda: mientras se escribe, ⏎ abre la conversación marcada; con la búsqueda ya aceptada, / permite editarla
|
|
479
|
+
lines.push(fit([[' ⏎', C.accent], [' ' + T.k.open + ' ', C.dim], S.searching ? ['Tab', C.accent] : ['/', C.accent], S.searching ? [' ' + (deepOn ? '◉ ' : '○ ') + T.deep + ' ', deepOn ? C.ok : C.dim] : [' ' + T.kEdit + ' ', C.dim],
|
|
480
|
+
['esc', C.accent], [' ' + (S.searching ? T.kEsc : T.kClear), C.dim]], W));
|
|
451
481
|
} else {
|
|
452
482
|
const k = T.k, segs = [[' ', '']];
|
|
453
483
|
const keys = !cur ? [['⏎', k.open], ['n', k.neu], ['/', k.find], ['?', T.kHelp]]
|
|
@@ -541,7 +571,8 @@ function doRename(x, name) {
|
|
|
541
571
|
|
|
542
572
|
function adjustSidebar(d) {
|
|
543
573
|
const cur = EMBED ? embedLayout().SW || 36 : process.stdout.columns || 40;
|
|
544
|
-
|
|
574
|
+
const lim = EMBED ? panelLimits(process.stdout.columns || 100) : { min: 24, max: 80 };
|
|
575
|
+
CFG.sidebar = clamp(cur + d, lim.min, lim.max); saveCfg();
|
|
545
576
|
if (EMBED) return embedResize();
|
|
546
577
|
if (SIDEBAR) { try { tmux('resize-pane', '-t', process.env.TMUX_PANE, '-x', String(CFG.sidebar)); } catch { /* */ } render(); }
|
|
547
578
|
}
|
|
@@ -724,11 +755,21 @@ function onKeyTree(raw) {
|
|
|
724
755
|
if (S.fb) return fbKey(k, raw);
|
|
725
756
|
if (S.searching) {
|
|
726
757
|
if (k === 'esc') { S.query = ''; S.searching = false; S.c = 0; queryChanged(); }
|
|
727
|
-
else if (k === 'enter')
|
|
758
|
+
else if (k === 'enter') {
|
|
759
|
+
S.searching = false;
|
|
760
|
+
const en = L[S.c]; // con una conversación marcada, ⏎ la abre ya (como el salto rápido); sobre un proyecto solo termina de escribir
|
|
761
|
+
if (en && en.t === 's') { render(); return launch(en.p, en.s); }
|
|
762
|
+
}
|
|
728
763
|
else if (k === '\t') { S.deep = !S.deep; queryChanged(); }
|
|
729
764
|
else if (k === 'up') S.c = Math.max(0, S.c - 1);
|
|
730
765
|
else if (k === 'down') S.c = Math.min(L.length - 1, S.c + 1);
|
|
731
|
-
else {
|
|
766
|
+
else {
|
|
767
|
+
const r = editBuf(S.query, S.qpos, k, raw);
|
|
768
|
+
if (r) {
|
|
769
|
+
const ch = r.s !== S.query; S.query = r.s; S.qpos = r.pos;
|
|
770
|
+
if (ch) { queryChanged(); const i = flatList().findIndex((x) => x.t === 's'); S.c = S.query.trim() && i >= 0 ? i : 0; } // se marca el primer resultado
|
|
771
|
+
}
|
|
772
|
+
}
|
|
732
773
|
return render();
|
|
733
774
|
}
|
|
734
775
|
S.flash = '';
|
|
@@ -802,7 +843,10 @@ function idle() {
|
|
|
802
843
|
const c = process.stdout.columns || 80, r = process.stdout.rows || 24;
|
|
803
844
|
const rows = [[C.brand + C.bold, '» Hop\u0001deck'], [C.text, T.idle1], [C.dim, T.idle2], ['', ''], [C.dim, T.idle3]];
|
|
804
845
|
let out = '\x1b[2J\x1b[?25l';
|
|
805
|
-
|
|
846
|
+
const art = mascotArt(c, r - rows.length - 2), gap = art.length ? 1 : 0; // el panel de tmux también lleva la mascota, si cabe
|
|
847
|
+
const top = art.length ? Math.max(1, Math.floor((r - art.length - gap - rows.length) / 2) + 1) : Math.max(1, Math.floor(r / 2) - 2);
|
|
848
|
+
art.forEach((_, j) => { out += `\x1b[${top + j};1H${mascotRow(art, j, c)}`; });
|
|
849
|
+
rows.forEach(([st, t], i) => { out += `\x1b[${top + art.length + gap + i};${Math.max(1, Math.floor((c - strW(t.replace('\u0001', ''))) / 2) + 1)}H${st}${paintMark(t)}${R}`; });
|
|
806
850
|
process.stdout.write(out);
|
|
807
851
|
};
|
|
808
852
|
draw(); process.stdout.on('resize', draw);
|
|
@@ -852,14 +896,42 @@ function loadDeps() {
|
|
|
852
896
|
try { return { pty: require('@lydell/node-pty'), Terminal: require('@xterm/headless').Terminal }; } catch { return null; }
|
|
853
897
|
}
|
|
854
898
|
|
|
899
|
+
/** Límites de un panel lateral al arrastrar su borde con el ratón: del 15 % al 50 % del ancho (y nunca menos de 20 columnas). */
|
|
900
|
+
const panelLimits = (W) => ({ min: Math.min(Math.max(20, Math.round(W * 0.15)), Math.floor(W * 0.5)), max: Math.max(20, Math.floor(W * 0.5)) });
|
|
901
|
+
/** Ancho de la lista (panel izquierdo): el guardado por el usuario, o 30 % del terminal por defecto. */
|
|
902
|
+
const sideWidth = (W) => (E.hideSide ? 0 : CFG.sidebar ? clamp(CFG.sidebar, panelLimits(W).min, panelLimits(W).max) : clamp(Math.floor(W * 0.3), 36, 46));
|
|
903
|
+
/** Ancho del panel de git (derecho): el guardado por el usuario, o GIT_W por defecto. */
|
|
904
|
+
const gitWidth = (W) => (CFG.gitw ? clamp(CFG.gitw, panelLimits(W).min, panelLimits(W).max) : GIT_W);
|
|
905
|
+
|
|
855
906
|
function embedLayout() {
|
|
856
907
|
const W = process.stdout.columns || 100, H = process.stdout.rows || 30;
|
|
857
|
-
const SW =
|
|
908
|
+
const SW = sideWidth(W);
|
|
858
909
|
const room = Math.max(10, W - SW - (SW ? 1 : 0));
|
|
859
|
-
const
|
|
910
|
+
const gw = gitWidth(W);
|
|
911
|
+
const GW = E.git && room - gw - 1 >= GIT_MIN_CHAT ? gw : 0; // tercer panel (git): solo si el chat conserva un ancho cómodo
|
|
860
912
|
return { W, H, SW, GW, rw: GW ? room - GW - 1 : room, rh: Math.max(3, H - 1), th: Math.max(3, H - 3) };
|
|
861
913
|
}
|
|
862
914
|
|
|
915
|
+
/**
|
|
916
|
+
* Arrastre de una línea divisoria: `x` es la columna (desde 1) donde está el ratón. La lista ocupa las columnas anteriores
|
|
917
|
+
* a la línea y el panel de git las posteriores. El chat conserva siempre su ancho mínimo, así el panel de git no desaparece.
|
|
918
|
+
*/
|
|
919
|
+
function dragPanel(which, x) {
|
|
920
|
+
const { W, SW, GW } = embedLayout(), l = panelLimits(W);
|
|
921
|
+
if (which === 'side') {
|
|
922
|
+
const hi = Math.max(l.min, Math.min(l.max, W - 1 - (GW ? GW + 1 + GIT_MIN_CHAT : 40)));
|
|
923
|
+
const n = clamp(x - 1, l.min, hi);
|
|
924
|
+
if (n === SW) return;
|
|
925
|
+
CFG.sidebar = n;
|
|
926
|
+
} else {
|
|
927
|
+
const hi = Math.max(l.min, Math.min(l.max, W - (SW ? SW + 1 : 0) - 1 - GIT_MIN_CHAT));
|
|
928
|
+
const n = clamp(W - x, l.min, hi);
|
|
929
|
+
if (n === GW) return;
|
|
930
|
+
CFG.gitw = n;
|
|
931
|
+
}
|
|
932
|
+
embedResize();
|
|
933
|
+
}
|
|
934
|
+
|
|
863
935
|
// ───────────────────────── panel de git (tercer panel, F8) ─────────────────────────
|
|
864
936
|
const GIT_W = 38, GIT_MIN_CHAT = 60;
|
|
865
937
|
const GITC = new Map(); // carpeta → { t, loading, data }
|
|
@@ -880,8 +952,8 @@ const gitCwd = () => {
|
|
|
880
952
|
function toggleGit() {
|
|
881
953
|
if (!EMBED) return flash(T.gitOnlyEmbed);
|
|
882
954
|
if (!E.git) {
|
|
883
|
-
const
|
|
884
|
-
const need = SW + (SW ? 1 : 0) + GIT_MIN_CHAT +
|
|
955
|
+
const W = process.stdout.columns || 100, SW = sideWidth(W);
|
|
956
|
+
const need = SW + (SW ? 1 : 0) + GIT_MIN_CHAT + gitWidth(W) + 1;
|
|
885
957
|
if ((process.stdout.columns || 100) < need) return flash(T.gitNarrow(need));
|
|
886
958
|
}
|
|
887
959
|
E.git = !E.git; CFG.git = E.git; saveCfg();
|
|
@@ -967,10 +1039,28 @@ function termRow(term, y, width, sel, from = 0) {
|
|
|
967
1039
|
/** Texto con la marca en dos colores: \u0001 separa "Hop" (color de marca) de "deck" (color del texto). */
|
|
968
1040
|
const paintMark = (t) => t.replace('\u0001', R + C.text + C.bold);
|
|
969
1041
|
|
|
1042
|
+
/** La mascota, del mayor tamaño que quepa (en `width` columnas y `rows` filas); nada si no cabe ni la más pequeña o si no hay colores. */
|
|
1043
|
+
function mascotArt(width, rows) {
|
|
1044
|
+
if (NOCOL) return [];
|
|
1045
|
+
const n = mascot.sizeFor(width - 2, rows);
|
|
1046
|
+
return n ? mascot.render(n) : [];
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** Una fila de la mascota centrada en `width` columnas. */
|
|
1050
|
+
function mascotRow(art, j, width) {
|
|
1051
|
+
const n = art.length * 2, pad = Math.max(0, Math.floor((width - n) / 2));
|
|
1052
|
+
return ' '.repeat(pad) + art[j] + ' '.repeat(Math.max(0, width - pad - n));
|
|
1053
|
+
}
|
|
1054
|
+
|
|
970
1055
|
function idleRow(y, width, height) {
|
|
971
1056
|
const k = T.k;
|
|
972
1057
|
const rows = [[C.brand + C.bold, '» Hop\u0001deck'], [C.text, T.idle1], [C.dim, T.idle2], ['', ''], [C.accent, `⏎ ${k.resume} n ${k.neu} / ${k.find} ? ${T.kHelp}`], [C.dim, T.idle3]];
|
|
973
|
-
const
|
|
1058
|
+
const art = mascotArt(width, height - rows.length - 2); // la mascota va encima del texto, si cabe
|
|
1059
|
+
const gap = art.length ? 1 : 0;
|
|
1060
|
+
const start = art.length ? Math.floor((height - art.length - gap - rows.length) / 2) : Math.floor(height / 2) - 2;
|
|
1061
|
+
const j = y - start;
|
|
1062
|
+
if (j >= 0 && j < art.length) return mascotRow(art, j, width);
|
|
1063
|
+
const i = j - art.length - gap;
|
|
974
1064
|
if (i < 0 || i >= rows.length) return ' '.repeat(width);
|
|
975
1065
|
const [st, t] = rows[i];
|
|
976
1066
|
const vis = t.replace('\u0001', ''), pad = Math.max(0, Math.floor((width - strW(vis)) / 2));
|
|
@@ -1137,7 +1227,7 @@ function hoverPopup(hv, rw, th) {
|
|
|
1137
1227
|
if (!hb) { hb = halfBlocks(scaleBox(d.rgba, d.w, d.h, sz.tw, sz.th), sz.tw, sz.th); g.cache.clear(); g.cache.set(key, hb); }
|
|
1138
1228
|
rows = hb; tw = sz.tw;
|
|
1139
1229
|
} else {
|
|
1140
|
-
const txt = d === undefined ? spin() + ' …' : T.imgNoPrev
|
|
1230
|
+
const txt = d === undefined ? spin() + ' …' : `${T.imgNoPrev} (${img.media || '?'})`; // el formato ayuda a saber por qué no se pudo leer
|
|
1141
1231
|
tw = Math.max(strW(lab) + 1, Math.min(strW(txt) + 2, Math.max(8, rw - 4)));
|
|
1142
1232
|
rows = [fit([[' ' + txt, d === false ? C.warn : C.accent]], tw)];
|
|
1143
1233
|
}
|
|
@@ -1312,7 +1402,8 @@ function renderEmbed() {
|
|
|
1312
1402
|
const popRow = (ty) => (pop && ty >= pop.top && ty < pop.top + pop.rows.length
|
|
1313
1403
|
? termRow(sh.term, ty, pop.left, selRange(ty, rw)) + pop.rows[ty - pop.top] + termRow(sh.term, ty, rw - pop.left - pop.bw, selRange(ty, rw), pop.left + pop.bw)
|
|
1314
1404
|
: null);
|
|
1315
|
-
const div = (E.focus === 'right' ? C.accent : C.faint) + '│' + R;
|
|
1405
|
+
const div = (E.drag === 'side' || E.focus === 'right' ? C.accent : C.faint) + '│' + R;
|
|
1406
|
+
const gdiv = (E.drag === 'git' ? C.accent : C.faint) + '│' + R; // la línea que se está arrastrando se resalta
|
|
1316
1407
|
const gitR = GW ? gitRows(GW, rh) : null;
|
|
1317
1408
|
for (let y = 0; y < rh; y++) {
|
|
1318
1409
|
const ty = y - 2; // las 2 primeras filas del panel derecho son el título y su línea
|
|
@@ -1322,7 +1413,7 @@ function renderEmbed() {
|
|
|
1322
1413
|
: y === 1 ? C.faint + '─'.repeat(rw) + R : gRows[ty])
|
|
1323
1414
|
: y === 0 ? headerRow(hdr, rw) : y === 1 ? C.faint + '─'.repeat(rw) + R
|
|
1324
1415
|
: sh && sh.ready ? (popRow(ty) || termRow(sh.term, ty, rw, selRange(ty, rw))) : sh ? loaderRow(ty, rw, th, sh.title) : pvRows ? pvRows[ty] : idleRow(ty, rw, th);
|
|
1325
|
-
rowsOut.push((left ? (left[y] || ' '.repeat(SW)) + div : '') + right + (gitR ?
|
|
1416
|
+
rowsOut.push((left ? (left[y] || ' '.repeat(SW)) + div : '') + right + (gitR ? gdiv + gitR[y] : ''));
|
|
1326
1417
|
}
|
|
1327
1418
|
const live = E.sessions.size;
|
|
1328
1419
|
const k = (key, d) => [[key, C.accent], [' ' + d + ' ', C.dim]];
|
|
@@ -1374,13 +1465,13 @@ function embedLaunch(project, session) {
|
|
|
1374
1465
|
{ name: 'xterm-256color', cols: rw, rows: th, cwd: project.cwd, env });
|
|
1375
1466
|
} catch (e) { flash(String(e.message).split('\n')[0]); return; }
|
|
1376
1467
|
const term = new Terminal({ cols: rw, rows: th, allowProposedApi: true, scrollback: 2000 });
|
|
1377
|
-
const sess = { p, term, cursorHidden: false, ready: false, lastData: Date.now(), working: false, busy: false, unseen: false, title: session ? session.title : T.newChat, t0: Date.now(), project: project.name, cwd: project.cwd, sid: session ? session.id : null, closing: false, branch: gitBranch(project.cwd) };
|
|
1468
|
+
const sess = { p, term, cursorHidden: false, ready: false, lastData: Date.now(), quietUntil: 0, working: false, busy: false, unseen: false, title: session ? session.title : T.newChat, t0: Date.now(), project: project.name, cwd: project.cwd, sid: session ? session.id : null, closing: false, branch: gitBranch(project.cwd) };
|
|
1378
1469
|
const vis = (hidden) => (params) => { if (params.some((x) => x === 25 || (Array.isArray(x) && x.includes(25)))) sess.cursorHidden = hidden; return false; };
|
|
1379
1470
|
term.parser.registerCsiHandler({ prefix: '?', final: 'h' }, vis(false));
|
|
1380
1471
|
term.parser.registerCsiHandler({ prefix: '?', final: 'l' }, vis(true));
|
|
1381
1472
|
term.onData((d) => { try { p.write(d); } catch { /* cerrado */ } }); // respuestas a consultas del terminal
|
|
1382
1473
|
p.onData((d) => {
|
|
1383
|
-
sess.lastData = Date.now();
|
|
1474
|
+
if (Date.now() >= sess.quietUntil) sess.lastData = Date.now(); // lo que Claude repinta justo tras redimensionar no es trabajo
|
|
1384
1475
|
// "listo" = ya hay texto visible. En Windows ConPTY manda secuencias de control al arrancar, antes de que Claude dibuje nada.
|
|
1385
1476
|
term.write(d, () => { if (!sess.ready && hasContent(term)) sess.ready = true; if (E.shown === key) scheduleRender(); });
|
|
1386
1477
|
});
|
|
@@ -1405,22 +1496,51 @@ function selNorm(sl) {
|
|
|
1405
1496
|
if (b.y < a.y || (b.y === a.y && b.x < a.x)) [a, b] = [b, a];
|
|
1406
1497
|
return [a, b];
|
|
1407
1498
|
}
|
|
1499
|
+
// La selección del chat guarda en `y` la línea del historial del terminal (absoluta), no la fila de la pantalla: así sigue sobre
|
|
1500
|
+
// el mismo texto aunque el chat se desplace mientras se arrastra, y puede abarcar más de lo que cabe en pantalla.
|
|
1408
1501
|
function selRange(ty, rw) {
|
|
1409
|
-
if (!E.sel
|
|
1410
|
-
const
|
|
1411
|
-
|
|
1412
|
-
|
|
1502
|
+
if (!E.sel) return null;
|
|
1503
|
+
const sh = E.sessions.get(E.shown); if (!sh) return null;
|
|
1504
|
+
const y = sh.term.buffer.active.viewportY + ty, [a, b] = selNorm(E.sel);
|
|
1505
|
+
if (y < a.y || y > b.y) return null;
|
|
1506
|
+
return [y === a.y ? a.x : 0, y === b.y ? b.x : rw - 1];
|
|
1413
1507
|
}
|
|
1414
1508
|
function selText(sh, sl) {
|
|
1415
1509
|
const [a, b] = selNorm(sl); const buf = sh.term.buffer.active; const out = [];
|
|
1416
1510
|
for (let y = a.y; y <= b.y; y++) {
|
|
1417
|
-
const l = buf.getLine(
|
|
1511
|
+
const l = buf.getLine(y);
|
|
1418
1512
|
out.push(l ? l.translateToString(true, y === a.y ? a.x : 0, y === b.y ? b.x + 1 : sh.term.cols) : '');
|
|
1419
1513
|
}
|
|
1420
1514
|
return out.join('\n').replace(/\s+$/, '');
|
|
1421
1515
|
}
|
|
1516
|
+
/** Copia la selección marcada y la quita. Solo se llama cuando el usuario lo pide (Ctrl+C, clic derecho), o con "copyOnSelect". */
|
|
1517
|
+
function copySelection(sh) {
|
|
1518
|
+
const sl = E.sel; E.sel = null; stopSelScroll();
|
|
1519
|
+
const t = sl && sh ? selText(sh, sl) : '';
|
|
1520
|
+
if (t) { copyText(t); E.note = { t: T.copied(t.length), until: Date.now() + 3000 }; }
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
// Al arrastrar contra el borde de arriba o de abajo, el chat se desplaza solo (aunque el ratón se quede quieto) y la selección sigue.
|
|
1524
|
+
let selTimer = null;
|
|
1525
|
+
function stopSelScroll() { if (selTimer) { clearInterval(selTimer); selTimer = null; } if (E.sel) E.sel.dir = 0; }
|
|
1526
|
+
function selScrollTick() {
|
|
1527
|
+
const sel = E.sel, sh = E.sessions.get(E.shown);
|
|
1528
|
+
if (!sel || !sel.down || !sel.dir || !sh || sh.term.buffer.active.type === 'alternate') return stopSelScroll();
|
|
1529
|
+
sh.term.scrollLines(-sel.dir * 2); // dir > 0: hacia arriba
|
|
1530
|
+
const row = sel.dir > 0 ? 0 : embedLayout().th - 1;
|
|
1531
|
+
sel.b = { x: sel.b.x, y: sh.term.buffer.active.viewportY + row };
|
|
1532
|
+
render();
|
|
1533
|
+
}
|
|
1534
|
+
/** `row`: fila del ratón respecto a la zona del chat (negativa = encima, ≥ th = debajo). Pone en marcha o para el desplazamiento. */
|
|
1535
|
+
function selEdge(sh, row) {
|
|
1536
|
+
const th = embedLayout().th, dir = row < 0 ? 1 : row >= th ? -1 : 0;
|
|
1537
|
+
E.sel.dir = dir;
|
|
1538
|
+
if (dir && sh.term.buffer.active.type !== 'alternate') { if (!selTimer) { selTimer = setInterval(selScrollTick, 60); selScrollTick(); } }
|
|
1539
|
+
else if (selTimer) { clearInterval(selTimer); selTimer = null; }
|
|
1540
|
+
}
|
|
1422
1541
|
/** Copia al portapapeles: OSC 52 (la mayoría de terminales) + comando del sistema como respaldo. */
|
|
1423
1542
|
function copyText(t) {
|
|
1543
|
+
if (process.env.HOPDECK_COPY_LOG) { try { fs.appendFileSync(process.env.HOPDECK_COPY_LOG, JSON.stringify(t) + '\n'); } catch { /* */ } return; } // pruebas: se anota en un archivo y no se toca el portapapeles
|
|
1424
1544
|
try { process.stdout.write(`\x1b]52;c;${Buffer.from(t).toString('base64')}\x07`); } catch { /* */ }
|
|
1425
1545
|
const run = (cmd, args) => { try { const c = cp.spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] }); c.on('error', () => {}); c.stdin.on('error', () => {}); c.stdin.end(t); } catch { /* */ } };
|
|
1426
1546
|
if (process.platform === 'darwin') run('pbcopy', []);
|
|
@@ -1470,6 +1590,7 @@ function sidebarMouse(b, x, y, type, rows = process.stdout.rows || 30) {
|
|
|
1470
1590
|
return render();
|
|
1471
1591
|
}
|
|
1472
1592
|
if (type !== 'M' || (b & 3) !== 0 || (b & 32)) return; // solo clic izquierdo (no soltar, ni arrastrar, ni otros botones)
|
|
1593
|
+
if (y === 1 && !S.help && !S.fb && !S.qs && S.prompt === null) { S.searching = true; S.qpos = [...S.query].length; return render(); } // clic en la fila de arriba: buscar
|
|
1473
1594
|
if (S.help || S.prompt !== null || y < 3 || y > rows - 3) return; // las filas de la lista van de la 3 a rows-3
|
|
1474
1595
|
if (S.qs) { const i = S.qs.off + (y - 3); if (qsItems()[i]) { S.qs.i = i; return onKeyTree('\r'); } return; }
|
|
1475
1596
|
if (S.fb) { const i = S.fb.off + (y - 3); if (fbRows()[i]) { S.fb.i = i; fbActivate(); } return; }
|
|
@@ -1481,6 +1602,15 @@ function onMouse(b, x, y, type) {
|
|
|
1481
1602
|
if (E.gallery) return;
|
|
1482
1603
|
const { SW, GW, rw, rh } = embedLayout();
|
|
1483
1604
|
const sh = E.sessions.get(E.shown);
|
|
1605
|
+
// líneas divisorias arrastrables (columna de cada '│'): lista|chat y chat|git
|
|
1606
|
+
const sx = SW ? SW + 1 : 0, gx = GW ? sx + rw + 1 : 0;
|
|
1607
|
+
if (E.drag) {
|
|
1608
|
+
if (type === 'm') { E.drag = null; saveCfg(); return render(); }
|
|
1609
|
+
if ((b & 32) && (b & 3) === 0) return dragPanel(E.drag, x);
|
|
1610
|
+
} else if (type === 'M' && !(b & 96) && (b & 3) === 0 && y <= rh && ((SW && x === sx) || (GW && x === gx))) {
|
|
1611
|
+
E.drag = x === sx ? 'side' : 'git'; E.sel = null; E.hover = null;
|
|
1612
|
+
return render();
|
|
1613
|
+
}
|
|
1484
1614
|
if (GW && x > (SW ? SW + 1 : 0) + rw) { if (E.hover) { E.hover = null; scheduleRender(); } return; } // el panel de git es de solo lectura
|
|
1485
1615
|
if (b & 64) { // rueda
|
|
1486
1616
|
E.hover = null;
|
|
@@ -1491,7 +1621,7 @@ function onMouse(b, x, y, type) {
|
|
|
1491
1621
|
return render();
|
|
1492
1622
|
}
|
|
1493
1623
|
if ((b & 32) && (b & 3) === 3) { // movimiento sin botón (hover): previsualiza la conversación bajo el cursor
|
|
1494
|
-
if (S.help || S.qs || E.sel) return;
|
|
1624
|
+
if (S.help || S.qs || (E.sel && E.sel.down)) return;
|
|
1495
1625
|
if (S.fb) { const i = S.fb.off + (y - 3); if (x <= SW && y >= 3 && y <= rh - 2 && fbRows()[i] && i !== S.fb.i) { S.fb.i = i; scheduleRender(); } return; }
|
|
1496
1626
|
if (sh) { if (x > SW) hoverChat(sh, x, y); else if (E.hover) { E.hover = null; scheduleRender(); } return; }
|
|
1497
1627
|
if (x > SW || y < 3 || y > rh - 2) return;
|
|
@@ -1500,23 +1630,30 @@ function onMouse(b, x, y, type) {
|
|
|
1500
1630
|
return;
|
|
1501
1631
|
}
|
|
1502
1632
|
const x0 = SW ? SW + 2 : 1, inPane = (SW ? x > SW + 1 : true) && y >= 3 && sh && sh.ready;
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
if (
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1633
|
+
// celda del chat bajo el ratón; `y` es la línea del historial (ver selRange), así que sirve aunque el chat esté desplazado
|
|
1634
|
+
const cell = () => { const L = embedLayout(); return { x: clamp(x - x0, 0, L.rw - 1), y: sh.term.buffer.active.viewportY + clamp(y - 3, 0, L.th - 1) }; };
|
|
1635
|
+
if ((b & 32) && (b & 3) === 0) { // arrastre
|
|
1636
|
+
if (E.sel && E.sel.down && sh) { E.sel.b = cell(); selEdge(sh, y - 3); render(); }
|
|
1637
|
+
return;
|
|
1638
|
+
}
|
|
1639
|
+
if (type === 'm') { // soltar
|
|
1640
|
+
stopSelScroll();
|
|
1641
|
+
const sl = E.sel;
|
|
1642
|
+
if (!sl || !sl.down) return render();
|
|
1643
|
+
if (sl.a.x === sl.b.x && sl.a.y === sl.b.y) { // un clic sin arrastrar: si es sobre un [Image #N], se abre la imagen
|
|
1644
|
+
E.sel = null;
|
|
1645
|
+
if (sh && sh.ready) { const hit = imageMarkerAt(sh.term, sl.a.y - sh.term.buffer.active.viewportY, sl.a.x); if (hit) openMarkerImage(sh, hit.n); }
|
|
1646
|
+
return render();
|
|
1514
1647
|
}
|
|
1648
|
+
sl.down = false; // la selección se queda marcada: no se copia sola (se copia con Ctrl+C o clic derecho), salvo con "copyOnSelect": true
|
|
1649
|
+
if (CFG.copyOnSelect) copySelection(sh); else E.note = { t: T.selHint, until: Date.now() + 8000 };
|
|
1515
1650
|
return render();
|
|
1516
1651
|
}
|
|
1652
|
+
if (type === 'M' && (b & 3) === 2 && E.sel && !E.sel.down && sh) { copySelection(sh); return render(); } // clic derecho: copiar lo marcado
|
|
1517
1653
|
if (type !== 'M' || (b & 3) !== 0) return; // solo clic izquierdo
|
|
1518
|
-
if (
|
|
1519
|
-
E.sel =
|
|
1654
|
+
if (x <= SW && y === 1 && !S.fb && !S.qs && S.prompt === null && !S.help) { E.focus = 'left'; E.sel = null; S.searching = true; S.qpos = [...S.query].length; return render(); } // clic en la fila de arriba de la lista: buscar
|
|
1655
|
+
if (inPane) { E.focus = 'right'; const c = cell(); stopSelScroll(); E.sel = { a: c, b: c, down: true, dir: 0 }; return render(); }
|
|
1656
|
+
stopSelScroll(); E.sel = null;
|
|
1520
1657
|
if (S.fb && x <= SW) {
|
|
1521
1658
|
E.focus = 'left'; const i = S.fb.off + (y - 3);
|
|
1522
1659
|
if (S.prompt === null && y >= 3 && y <= rh - 2 && fbRows()[i]) { S.fb.i = i; return fbActivate(); }
|
|
@@ -1540,7 +1677,11 @@ function hasContent(term) {
|
|
|
1540
1677
|
}
|
|
1541
1678
|
|
|
1542
1679
|
function embedInput(s) {
|
|
1543
|
-
E.sel
|
|
1680
|
+
if (E.sel && !E.sel.down) { // hay texto seleccionado: Ctrl+C lo copia y Esc lo quita, sin llegar a Claude (Esc le interrumpiría)
|
|
1681
|
+
if (s === '\x03') { copySelection(E.sessions.get(E.shown)); return render(); }
|
|
1682
|
+
if (s === '\x1b') { E.sel = null; E.note = null; return render(); }
|
|
1683
|
+
}
|
|
1684
|
+
stopSelScroll(); E.sel = null; E.hover = null;
|
|
1544
1685
|
if (s === '\x1bOP' || s === '\x1b[11~' || s === '\x1b[1;1P') { E.focus = 'left'; if (E.hideSide) { E.hideSide = false; embedResize(); } else render(); return; }
|
|
1545
1686
|
const sh = E.sessions.get(E.shown);
|
|
1546
1687
|
const b = sh.term.buffer.active, scrolled = b.baseY > b.viewportY;
|
|
@@ -1597,10 +1738,26 @@ function closeChat(key) {
|
|
|
1597
1738
|
flash(T.closed(x.title));
|
|
1598
1739
|
}
|
|
1599
1740
|
|
|
1741
|
+
/**
|
|
1742
|
+
* ¿Claude Code está trabajando de verdad? Mientras genera, su pantalla muestra «esc to interrupt» (o «ctrl+c to interrupt»).
|
|
1743
|
+
* Antes bastaba con que el chat escribiera algo en el último segundo, y eso también pasa sin trabajo: al redimensionar los
|
|
1744
|
+
* paneles, al cambiar de ventana, o al actualizar su barra de estado. Se mira solo la pantalla viva (no lo que se ve al subir).
|
|
1745
|
+
*/
|
|
1746
|
+
const BUSY_HINT = /(esc|ctrl\+c) to interrupt/i;
|
|
1747
|
+
function showsBusy(term) {
|
|
1748
|
+
const b = term.buffer.active;
|
|
1749
|
+
for (let y = Math.max(0, term.rows - 14); y < term.rows; y++) {
|
|
1750
|
+
const l = b.getLine(b.baseY + y);
|
|
1751
|
+
if (l && BUSY_HINT.test(l.translateToString(true))) return true;
|
|
1752
|
+
}
|
|
1753
|
+
return false;
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1600
1756
|
function pollChats() {
|
|
1601
1757
|
const now = Date.now(); let changed = false;
|
|
1602
1758
|
for (const [key, x] of E.sessions) {
|
|
1603
|
-
|
|
1759
|
+
// HOPDECK_BUSY=output devuelve el criterio antiguo (cualquier salida reciente) por si una versión de Claude cambia ese texto
|
|
1760
|
+
const working = x.ready && now - x.lastData < 1200 && (process.env.HOPDECK_BUSY === 'output' || showsBusy(x.term));
|
|
1604
1761
|
if (x.working && !working && x.busy) {
|
|
1605
1762
|
x.busy = false;
|
|
1606
1763
|
if (E.shown !== key || E.focus !== 'right') { x.unseen = true; E.note = { t: '✔ ' + x.project + ' › ' + x.title, until: now + 6000 }; process.stdout.write('\x07'); notifyDesktop(x.project + ' › ' + x.title); }
|
|
@@ -1614,9 +1771,9 @@ function pollChats() {
|
|
|
1614
1771
|
const x_any = (e) => [...e.sessions.values()].some((x) => x.working);
|
|
1615
1772
|
|
|
1616
1773
|
function embedResize() {
|
|
1617
|
-
invalidate(); E.sel = null;
|
|
1774
|
+
invalidate(); stopSelScroll(); E.sel = null; // al cambiar el ancho las líneas se reajustan: la selección ya no marcaría lo mismo
|
|
1618
1775
|
const { rw, th } = embedLayout();
|
|
1619
|
-
for (const sess of E.sessions.values()) { try { sess.p.resize(rw, th); sess.term.resize(rw, th); } catch { /* */ } }
|
|
1776
|
+
for (const sess of E.sessions.values()) { sess.quietUntil = Date.now() + 1500; try { sess.p.resize(rw, th); sess.term.resize(rw, th); } catch { /* */ } } // todos los chats se repintan al cambiar el tamaño
|
|
1620
1777
|
render();
|
|
1621
1778
|
}
|
|
1622
1779
|
|
|
@@ -1793,7 +1950,10 @@ function splash(done, total) {
|
|
|
1793
1950
|
const lines = [[C.brand + C.bold, '» Hopdeck'], ['', ''],
|
|
1794
1951
|
[C.dim, `${spin()} ${T.loading}${total ? ` ${done}/${total}` : '…'}`]];
|
|
1795
1952
|
let out = '\x1b[2J';
|
|
1796
|
-
|
|
1953
|
+
const art = mascotArt(c, r - lines.length - 2), gap = art.length ? 1 : 0; // la mascota va encima, si cabe
|
|
1954
|
+
const top = art.length ? Math.max(1, Math.floor((r - art.length - gap - lines.length) / 2) + 1) : Math.max(1, Math.floor(r / 2) - 1);
|
|
1955
|
+
art.forEach((_, j) => { out += `\x1b[${top + j};1H${mascotRow(art, j, c)}`; });
|
|
1956
|
+
lines.forEach(([st, t], i) => { out += `\x1b[${top + art.length + gap + i};${Math.max(1, Math.floor((c - strW(t)) / 2) + 1)}H${st}${t}${R}`; });
|
|
1797
1957
|
process.stdout.write(out);
|
|
1798
1958
|
}
|
|
1799
1959
|
|
|
@@ -2118,9 +2278,9 @@ function tutorial(afterInstall) {
|
|
|
2118
2278
|
|
|
2119
2279
|
// ───────────────────────── entrada ─────────────────────────
|
|
2120
2280
|
// ── Comandos: UNA sola forma para cada uno (shortcut on|off, uninstall, doctor, help). Lo demás no hace nada: da un error con una sugerencia ──
|
|
2121
|
-
const COMMANDS = ['shortcut', 'theme', 'uninstall', 'doctor', 'help'];
|
|
2281
|
+
const COMMANDS = ['shortcut', 'theme', 'mascot', 'uninstall', 'doctor', 'help'];
|
|
2122
2282
|
// Palabras que alguien escribiría para lo mismo: no son comandos y no se ejecutan, solo sirven para sugerir el correcto
|
|
2123
|
-
const SYNONYMS = { install: 'shortcut on', instalar: 'shortcut on', atajo: 'shortcut on', desinstalar: 'uninstall', remove: 'uninstall', delete: 'uninstall', ayuda: 'help', diagnostico: 'doctor', version: '--version', list: '--list', tema: 'theme', modo: 'theme', mode: 'theme', dark: 'theme dark', light: 'theme light', oscuro: 'theme dark', claro: 'theme light' };
|
|
2283
|
+
const SYNONYMS = { install: 'shortcut on', instalar: 'shortcut on', atajo: 'shortcut on', desinstalar: 'uninstall', remove: 'uninstall', delete: 'uninstall', ayuda: 'help', diagnostico: 'doctor', version: '--version', list: '--list', tema: 'theme', mascota: 'mascot', sapo: 'mascot', frog: 'mascot', modo: 'theme', mode: 'theme', dark: 'theme dark', light: 'theme light', oscuro: 'theme dark', claro: 'theme light' };
|
|
2124
2284
|
/** Nombre de comando si `arg` es exactamente uno (sin guiones ni variantes); null si no. */
|
|
2125
2285
|
const commandName = (arg) => (COMMANDS.includes(String(arg || '').toLowerCase()) ? String(arg).toLowerCase() : null);
|
|
2126
2286
|
const editDistance = (a, b) => { const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]); for (let j = 1; j <= b.length; j++) d[0][j] = j; for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); return d[a.length][b.length]; };
|
|
@@ -2155,6 +2315,17 @@ function main() {
|
|
|
2155
2315
|
const eff = env ? (LIGHT ? 'light' : 'dark') : CFG.theme || (/;(7|15)$/.test(process.env.COLORFGBG || '') ? 'light' : 'dark');
|
|
2156
2316
|
console.log(T.themeShow(CFG.theme || 'auto', eff, CFG.theme ? 'config' : 'auto', env));
|
|
2157
2317
|
}
|
|
2318
|
+
else if (commandName(cmd) === 'mascot') { // hopdeck mascot [--size small|normal|large] [--plain]: dibuja la mascota (sin colores con --plain o NO_COLOR)
|
|
2319
|
+
const sizes = { small: 32, normal: 48, large: 64 }; let size = 'normal', plain = false, bad = false;
|
|
2320
|
+
for (let i = 0; i < rest.length; i++) {
|
|
2321
|
+
if (rest[i] === '--plain') plain = true;
|
|
2322
|
+
else if (rest[i] === '--size' && sizes[rest[i + 1]]) size = rest[++i];
|
|
2323
|
+
else bad = true;
|
|
2324
|
+
}
|
|
2325
|
+
if (bad) { console.error(`${C.warn}${T.mascotUsage}${R}`); process.exit(2); }
|
|
2326
|
+
if (plain || NOCOL) console.log(mascot.ASCII);
|
|
2327
|
+
else { const cols = process.stdout.isTTY ? process.stdout.columns || 80 : 999; console.log(mascot.render(Math.max(16, Math.min(sizes[size], cols))).join('\n')); }
|
|
2328
|
+
}
|
|
2158
2329
|
else if (commandName(cmd) === 'uninstall') { // desinstalación completa: atajo, preferencias, caché y programa
|
|
2159
2330
|
if (rest.some((a) => a !== '--yes' && a !== '-y')) { console.error(`${C.warn}${T.unknownCmd(rest.find((a) => a !== '--yes' && a !== '-y'))}${R}\n${C.dim}${T.cmdList}${R}`); process.exit(2); }
|
|
2160
2331
|
uninstallAll({ yes: rest.length > 0 }).then((code) => process.exit(code), (e) => { console.error(e); process.exit(1); });
|
|
@@ -2184,6 +2355,6 @@ else {
|
|
|
2184
2355
|
readSession, buildProject, scan, scanAsync, finishScan, sortProjects, projectDirs,
|
|
2185
2356
|
view, flatList, stripBlock, offerShortcut, uninstallAll, commandName, suggestCommand, parseTermReplies, sixelOn, SNIP, MARK_A, MARK_B, toggleProject, cacheLoad, selNorm,
|
|
2186
2357
|
decodePNG, decodeImage, scaleBox, fitSize, halfBlocks, collectImages, extractImages,
|
|
2187
|
-
editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
|
|
2358
|
+
onMouse, dragPanel, panelLimits, embedLayout, sessTag, editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
|
|
2188
2359
|
};
|
|
2189
2360
|
}
|
package/lib/history.js
CHANGED
|
@@ -19,7 +19,7 @@ function textOf(content) {
|
|
|
19
19
|
// Caché del índice: solo se vuelven a leer las sesiones cuya fecha/tamaño cambió.
|
|
20
20
|
const CACHE_FILE = process.env.HOPDECK_CACHE || path.join(os.homedir(), '.hopdeck-cache.json');
|
|
21
21
|
// Sube la versión cuando cambie cómo se lee una sesión: así las cachés ya guardadas se reconstruyen en vez de repetir resultados antiguos.
|
|
22
|
-
const CACHE_VERSION =
|
|
22
|
+
const CACHE_VERSION = 3;
|
|
23
23
|
let CACHE = null, cacheDirty = false, cacheSeen = null;
|
|
24
24
|
/** Empieza un escaneo: las entradas de la caché que no se vean se descartan al terminar. */
|
|
25
25
|
const beginScan = () => { cacheSeen = new Set(); };
|
|
@@ -48,7 +48,7 @@ function readSession(file) {
|
|
|
48
48
|
const hit = cache.files[file];
|
|
49
49
|
if (hit && hit.m === st.mtimeMs && hit.z === st.size) return hit.d ? { ...hit.d, file, mtime: st.mtimeMs } : null;
|
|
50
50
|
const d = parseSession(file, st);
|
|
51
|
-
cache.files[file] = { m: st.mtimeMs, z: st.size, d: d ? { id: d.id, title: d.title, first: d.first, cwd: d.cwd } : null };
|
|
51
|
+
cache.files[file] = { m: st.mtimeMs, z: st.size, d: d ? { id: d.id, title: d.title, first: d.first, cwd: d.cwd, root: d.root, last: d.last } : null };
|
|
52
52
|
cacheDirty = true;
|
|
53
53
|
return d;
|
|
54
54
|
}
|
|
@@ -82,15 +82,19 @@ function parseSession(file, st) {
|
|
|
82
82
|
try { fd = fs.openSync(file, 'r'); } catch { return null; }
|
|
83
83
|
try {
|
|
84
84
|
const TAIL = 160 * 1024;
|
|
85
|
-
let cwd = '', first = '', custom = '', ai = '';
|
|
85
|
+
let cwd = '', first = '', custom = '', ai = '', root = '';
|
|
86
86
|
scanHead(fd, st.size, (line) => {
|
|
87
87
|
if (!line) return false;
|
|
88
88
|
const wantCwd = !cwd && line.includes('"cwd"');
|
|
89
89
|
const wantUser = !first && isType(line, 'user');
|
|
90
90
|
const wantTitle = line.includes('-title"');
|
|
91
|
-
|
|
91
|
+
const wantRoot = !root && !first && line.includes('"uuid"'); // el primer mensaje del archivo; el primer "user" ya lo trae si antes no hubo otro
|
|
92
|
+
if (wantCwd || wantUser || wantTitle || wantRoot) {
|
|
92
93
|
let j; try { j = JSON.parse(line); } catch { j = null; }
|
|
93
94
|
if (j) {
|
|
95
|
+
// Al reanudar o continuar una conversación, Claude Code crea un archivo nuevo que copia el historial desde el principio:
|
|
96
|
+
// todos comparten el uuid del primer mensaje, y eso permite saber que son la misma conversación.
|
|
97
|
+
if (!root && typeof j.uuid === 'string') root = j.uuid;
|
|
94
98
|
if (wantCwd && j.cwd) cwd = j.cwd;
|
|
95
99
|
if (j.type === 'custom-title' && j.customTitle) custom = j.customTitle;
|
|
96
100
|
if (j.type === 'ai-title' && j.aiTitle) ai = j.aiTitle;
|
|
@@ -118,7 +122,13 @@ function parseSession(file, st) {
|
|
|
118
122
|
}
|
|
119
123
|
const title = tidy(tCustom || custom || tAi || ai || first || '');
|
|
120
124
|
if (!title) return null; // sesión vacía
|
|
121
|
-
|
|
125
|
+
// fecha del último mensaje real: la fecha del archivo cambia también al abrir la conversación o al renombrarla
|
|
126
|
+
let last = 0;
|
|
127
|
+
for (let i = tail.length - 1; i >= 0 && !last; i--) {
|
|
128
|
+
if (!isType(tail[i], 'user') && !isType(tail[i], 'assistant')) continue;
|
|
129
|
+
try { const j = JSON.parse(tail[i]); if (j.type === 'user' || j.type === 'assistant') last = Date.parse(j.timestamp) || 0; } catch { /* línea cortada */ }
|
|
130
|
+
}
|
|
131
|
+
return { id: path.basename(file, '.jsonl'), file, title, first, cwd, root, last, mtime: st.mtimeMs };
|
|
122
132
|
} catch { return null; } finally { try { fs.closeSync(fd); } catch { /* */ } }
|
|
123
133
|
}
|
|
124
134
|
|
|
@@ -132,12 +142,35 @@ function projectDirs() {
|
|
|
132
142
|
try { return fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(root, d.name)); } catch { return []; }
|
|
133
143
|
}
|
|
134
144
|
|
|
145
|
+
/**
|
|
146
|
+
* Las sesiones que comparten el primer mensaje (`root`) son la misma conversación: cada vez que se reanuda o se continúa tras
|
|
147
|
+
* agotar el contexto, Claude Code crea un archivo nuevo que contiene todo el anterior. Se deja solo la del mensaje más reciente
|
|
148
|
+
* (la que tiene el historial completo; no vale la fecha del archivo, que también cambia al abrir una conversación vieja) y se anota
|
|
149
|
+
* en `parts` cuántas continuaciones anteriores se plegaron. Las sesiones sin `root` nunca se juntan. Devuelve la lista por fecha.
|
|
150
|
+
*/
|
|
151
|
+
function foldContinuations(sessions) {
|
|
152
|
+
const groups = new Map(), out = [];
|
|
153
|
+
for (const x of sessions) {
|
|
154
|
+
if (!x.root) { out.push(x); continue; }
|
|
155
|
+
const g = groups.get(x.root);
|
|
156
|
+
if (g) g.push(x); else groups.set(x.root, [x]);
|
|
157
|
+
}
|
|
158
|
+
const at = (x) => x.last || x.mtime;
|
|
159
|
+
for (const g of groups.values()) {
|
|
160
|
+
const rep = g.reduce((a, b) => (at(b) > at(a) || (at(b) === at(a) && b.mtime > a.mtime) ? b : a));
|
|
161
|
+
if (g.length > 1) { rep.parts = g.length - 1; rep.prior = g.filter((x) => x !== rep).map((x) => x.id); }
|
|
162
|
+
out.push(rep);
|
|
163
|
+
}
|
|
164
|
+
return out.sort((a, b) => b.mtime - a.mtime);
|
|
165
|
+
}
|
|
166
|
+
|
|
135
167
|
function buildProject(dir) {
|
|
136
168
|
let files = [];
|
|
137
169
|
try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { return null; }
|
|
138
|
-
const
|
|
139
|
-
if (!
|
|
140
|
-
|
|
170
|
+
const all = files.map((f) => readSession(path.join(dir, f))).filter(Boolean);
|
|
171
|
+
if (!all.length) return null;
|
|
172
|
+
all.sort((a, b) => b.mtime - a.mtime);
|
|
173
|
+
const sessions = foldContinuations(all);
|
|
141
174
|
const seen = {};
|
|
142
175
|
for (const x of sessions) { const k = x.title + '|' + x.first; seen[k] = (seen[k] || 0) + 1; }
|
|
143
176
|
for (const x of sessions) x.dup = seen[x.title + '|' + x.first] > 1;
|
|
@@ -146,4 +179,4 @@ function buildProject(dir) {
|
|
|
146
179
|
return { key, cwd, name: baseName(cwd), sessions, mtime: sessions[0].mtime };
|
|
147
180
|
}
|
|
148
181
|
|
|
149
|
-
module.exports = { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, beginScan, endScan, readSession, parseSession, decodeDir, projectDirs, buildProject };
|
|
182
|
+
module.exports = { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, beginScan, endScan, readSession, parseSession, foldContinuations, decodeDir, projectDirs, buildProject };
|
package/lib/i18n.js
CHANGED
|
@@ -21,8 +21,9 @@ const T = {
|
|
|
21
21
|
prevHint: '⏎ reanudar esta conversación', bar8: 'git', gitNone: 'Elige un proyecto', gitNoRepo: 'Esta carpeta no es un repositorio git', gitMissing: 'git no está instalado', gitErr: 'No se pudo leer el repositorio', gitClean: 'sin cambios', gitDirty: (n) => (n === 1 ? '1 cambio sin guardar' : `${n} cambios sin guardar`), gitMore: (n) => `… y ${n} más`, gitBranches: 'Ramas recientes', gitActivity: 'Actividad de ramas', gitNoActivity: 'Sin cambios de rama', gitFrom: 'desde', gitNarrow: (n) => `Terminal estrecha: el panel de git necesita ${n} columnas`, gitOnlyEmbed: 'El panel de git solo está en el terminal integrado', prevInfo: (a, n) => `${a === 'ahora' ? 'ahora mismo' : 'hace ' + a} · últimos ${n} mensajes`, kUnfold: 'desplegar', kRename: 'renombrar', kPin: 'fijar', kHelp: 'ayuda', noPrev: 'Sin mensajes para mostrar',
|
|
22
22
|
bar6: 'ocultar lista', bar7: 'mostrar lista', deep: 'contenido', pathPrompt: 'nombre de la nueva carpeta', mkIn: 'se crea en', fbTitle: 'Elegir carpeta', fbHere: 'Abrir chat aquí', fbNew: 'Nueva carpeta aquí…', fbUp: 'Subir un nivel', fbProj: 'proyecto', fbHint: '⏎ entrar · ␣ abrir · / buscar · . ocultas', fbDrives: 'Este equipo', fbRecent: 'reciente', hoverMiss: (n) => `[Image #${n}]: aún no está en el historial`, fbEmpty: 'Sin subcarpetas', badId: 'Identificador de sesión no válido',
|
|
23
23
|
imgClickHint: 'clic: abrir en grande', imgOpened: (n) => `[Image #${n}] abierta en el visor de imágenes`,
|
|
24
|
-
unknownCmd: (c) => `Comando desconocido: "${c}"`, didYouMean: (s) => `¿Quisiste decir "${s}"?`, cmdList: 'Comandos: hopdeck shortcut on|off · theme light|dark|auto · uninstall · doctor · help (y --list, --version).\nLas opciones de claude (por ejemplo --model opus) se pasan tal cual: hopdeck --model opus',
|
|
24
|
+
unknownCmd: (c) => `Comando desconocido: "${c}"`, didYouMean: (s) => `¿Quisiste decir "${s}"?`, cmdList: 'Comandos: hopdeck shortcut on|off · theme light|dark|auto · mascot · uninstall · doctor · help (y --list, --version).\nLas opciones de claude (por ejemplo --model opus) se pasan tal cual: hopdeck --model opus',
|
|
25
25
|
themeNow: (n) => `Tema ${n === 'light' ? 'claro' : 'oscuro'} (guardado)`,
|
|
26
|
+
mascotUsage: 'Uso: hopdeck mascot · hopdeck mascot --size small|normal|large · hopdeck mascot --plain (sin colores)',
|
|
26
27
|
themeUsage: 'Uso: hopdeck theme light (claro) · hopdeck theme dark (oscuro) · hopdeck theme auto (según el terminal) · hopdeck theme (ver el actual)',
|
|
27
28
|
themeShow: (saved, eff, from, env) => `Tema guardado: ${saved === 'auto' ? 'automático' : saved === 'light' ? 'claro' : 'oscuro'}.\nSe está usando: ${eff === 'light' ? 'claro' : 'oscuro'}` + (env ? ' (la variable HOPDECK_THEME tiene prioridad sobre lo guardado).' : from === 'auto' ? ' (automático: oscuro salvo que el terminal diga que tiene fondo claro).' : '.'),
|
|
28
29
|
shortcutUsage: 'Uso: hopdeck shortcut on (instalar el atajo de claude) · hopdeck shortcut off (quitarlo)',
|
|
@@ -44,6 +45,9 @@ const T = {
|
|
|
44
45
|
'F1 F2 foco lista / chat', 'F3 copiar texto (ratón)', 'F4 ocultar la lista', 'b F8 panel de git', 't F9 tema claro / oscuro', '⠋ ✔ ● trabajando · terminó · abierta', 'q salir'],
|
|
45
46
|
bar4: 'copiar texto', bar5: 'ratón', up: (n, pct) => `↑ ${n} líneas${pct >= 0 ? ` (${pct}%)` : ''} · PgDn/End`, loading: 'Cargando proyectos', opening: 'Abriendo conversación', close: 'cerrar', idle1: 'Elige una conversación', idle2: 'Usa ↑↓ y ⏎ en el panel izquierdo',
|
|
46
47
|
idle3: 'F1 proyectos · F2 chat', bar1: 'proyectos', bar2: 'chat', bar3: 'minimizar',
|
|
48
|
+
selHint: 'Ctrl+C o clic derecho: copiar · Esc: quitar la selección',
|
|
49
|
+
searchPh: 'buscar conversación o proyecto…', found: (n) => `${n} ${n === 1 ? 'resultado' : 'resultados'}`, noRes: (q) => `Sin resultados para «${q}»`,
|
|
50
|
+
searchingContent: 'Buscando dentro de las conversaciones…', tryContent: 'Pulsa Tab para buscar también dentro del contenido', inContent: 'en el contenido', kClear: 'limpiar', kEdit: 'editar', kEsc: 'salir',
|
|
47
51
|
inside: 'Ya estás dentro de Hopdeck (F1 para ir a la lista de proyectos).',
|
|
48
52
|
},
|
|
49
53
|
en: {
|
|
@@ -64,8 +68,9 @@ const T = {
|
|
|
64
68
|
prevHint: '⏎ resume this conversation', bar8: 'git', gitNone: 'Pick a project', gitNoRepo: 'This folder is not a git repository', gitMissing: 'git is not installed', gitErr: 'Could not read the repository', gitClean: 'clean', gitDirty: (n) => (n === 1 ? '1 uncommitted change' : `${n} uncommitted changes`), gitMore: (n) => `… and ${n} more`, gitBranches: 'Recent branches', gitActivity: 'Branch activity', gitNoActivity: 'No branch changes', gitFrom: 'from', gitNarrow: (n) => `Terminal too narrow: the git panel needs ${n} columns`, gitOnlyEmbed: 'The git panel is only in the built-in terminal', prevInfo: (a, n) => `${a === 'now' ? 'just now' : a + ' ago'} · last ${n} messages`, kUnfold: 'unfold', kRename: 'rename', kPin: 'pin', kHelp: 'help', noPrev: 'No messages to show',
|
|
65
69
|
bar6: 'hide list', bar7: 'show list', deep: 'content', pathPrompt: 'new folder name', mkIn: 'created in', fbTitle: 'Pick a folder', fbHere: 'Open chat here', fbNew: 'New folder here…', fbUp: 'Go up', fbProj: 'project', fbHint: '⏎ enter · ␣ open · / find · . hidden', fbDrives: 'This PC', fbRecent: 'recent', hoverMiss: (n) => `[Image #${n}]: not in the history yet`, fbEmpty: 'No subfolders', badId: 'Invalid session id',
|
|
66
70
|
imgClickHint: 'click: open full size', imgOpened: (n) => `[Image #${n}] opened in the image viewer`,
|
|
67
|
-
unknownCmd: (c) => `Unknown command: "${c}"`, didYouMean: (s) => `Did you mean "${s}"?`, cmdList: 'Commands: hopdeck shortcut on|off · theme light|dark|auto · uninstall · doctor · help (and --list, --version).\nclaude options (for example --model opus) are passed through as they are: hopdeck --model opus',
|
|
71
|
+
unknownCmd: (c) => `Unknown command: "${c}"`, didYouMean: (s) => `Did you mean "${s}"?`, cmdList: 'Commands: hopdeck shortcut on|off · theme light|dark|auto · mascot · uninstall · doctor · help (and --list, --version).\nclaude options (for example --model opus) are passed through as they are: hopdeck --model opus',
|
|
68
72
|
themeNow: (n) => `${n === 'light' ? 'Light' : 'Dark'} theme (saved)`,
|
|
73
|
+
mascotUsage: 'Usage: hopdeck mascot · hopdeck mascot --size small|normal|large · hopdeck mascot --plain (no colors)',
|
|
69
74
|
themeUsage: 'Usage: hopdeck theme light · hopdeck theme dark · hopdeck theme auto (follow the terminal) · hopdeck theme (show the current one)',
|
|
70
75
|
themeShow: (saved, eff, from, env) => `Saved theme: ${saved}.\nIn use: ${eff}` + (env ? ' (the HOPDECK_THEME variable takes priority over the saved one).' : from === 'auto' ? ' (auto: dark unless the terminal says it has a light background).' : '.'),
|
|
71
76
|
shortcutUsage: 'Usage: hopdeck shortcut on (install the claude shortcut) · hopdeck shortcut off (remove it)',
|
|
@@ -87,6 +92,9 @@ const T = {
|
|
|
87
92
|
'F1 F2 focus list / chat', 'F3 copy text (mouse)', 'F4 hide the list', 'b F8 git panel', 't F9 light / dark theme', '⠋ ✔ ● working · done · open', 'q quit'],
|
|
88
93
|
bar4: 'copy text', bar5: 'mouse', up: (n, pct) => `↑ ${n} lines${pct >= 0 ? ` (${pct}%)` : ''} · PgDn/End`, loading: 'Loading projects', opening: 'Opening conversation', close: 'close', idle1: 'Pick a conversation', idle2: 'Use ↑↓ and ⏎ in the left pane',
|
|
89
94
|
idle3: 'F1 projects · F2 chat', bar1: 'projects', bar2: 'chat', bar3: 'minimize',
|
|
95
|
+
selHint: 'Ctrl+C or right click: copy · Esc: clear the selection',
|
|
96
|
+
searchPh: 'search conversation or project…', found: (n) => `${n} ${n === 1 ? 'result' : 'results'}`, noRes: (q) => `No results for “${q}”`,
|
|
97
|
+
searchingContent: 'Searching inside the conversations…', tryContent: 'Press Tab to also search inside the content', inContent: 'in content', kClear: 'clear', kEdit: 'edit', kEsc: 'exit',
|
|
90
98
|
inside: 'You are already inside Hopdeck (F1 jumps to the project list).',
|
|
91
99
|
},
|
|
92
100
|
}[LANG];
|
package/lib/images.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
// Imágenes del historial: extracción de bloques base64, decodificación PNG/JPEG y dibujo con medios bloques (▀).
|
|
3
3
|
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const cp = require('child_process');
|
|
4
7
|
const readline = require('readline');
|
|
5
8
|
const { TRUE, R } = require('./style');
|
|
6
9
|
|
|
@@ -111,18 +114,46 @@ function decodePNG(buf) {
|
|
|
111
114
|
return { w, h, rgba };
|
|
112
115
|
}
|
|
113
116
|
|
|
114
|
-
/**
|
|
117
|
+
/** Extensión según los primeros bytes (sips la usa para saber qué formato lee). */
|
|
118
|
+
function sniffExt(b) {
|
|
119
|
+
if (b.length > 12) {
|
|
120
|
+
if (b.readUInt32BE(0) === 0x89504e47) return 'png';
|
|
121
|
+
if (b[0] === 0xff && b[1] === 0xd8) return 'jpg';
|
|
122
|
+
if (b.toString('latin1', 0, 4) === 'GIF8') return 'gif';
|
|
123
|
+
if (b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP') return 'webp';
|
|
124
|
+
if (b.toString('latin1', 4, 8) === 'ftyp') return 'heic';
|
|
125
|
+
if (b.readUInt32BE(0) === 0x49492a00 || b.readUInt32BE(0) === 0x4d4d002a) return 'tiff';
|
|
126
|
+
}
|
|
127
|
+
return 'img';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* macOS: `sips` (viene con el sistema) convierte a PNG, y reduce, lo que el decodificador propio no entiende: WebP, GIF, HEIC, TIFF,
|
|
132
|
+
* PNG entrelazado o imágenes enormes. `run` se puede sustituir (pruebas). Devuelve { w, h, rgba } o null.
|
|
133
|
+
*/
|
|
134
|
+
function decodeViaSips(buf, run = cp.spawnSync) {
|
|
135
|
+
let dir;
|
|
136
|
+
try {
|
|
137
|
+
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hopdeck-sips-'));
|
|
138
|
+
const src = path.join(dir, 'in.' + sniffExt(buf)), dst = path.join(dir, 'out.png');
|
|
139
|
+
fs.writeFileSync(src, buf);
|
|
140
|
+
const r = run('sips', ['-s', 'format', 'png', '-Z', '1600', src, '--out', dst], { stdio: 'ignore', timeout: 8000 });
|
|
141
|
+
return r && r.status === 0 ? decodePNG(fs.readFileSync(dst)) : null;
|
|
142
|
+
} catch { return null; } finally { if (dir) { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* */ } } }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** PNG (propio) o JPEG (si está jpeg-js); en macOS, lo demás con sips. Devuelve { w, h, rgba } o null. */
|
|
115
146
|
function decodeImage(img) {
|
|
116
147
|
const buf = Buffer.from(img.data, 'base64');
|
|
148
|
+
let d = null;
|
|
117
149
|
try {
|
|
118
|
-
if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47)
|
|
119
|
-
if (buf[0] === 0xff && buf[1] === 0xd8) {
|
|
120
|
-
let jpeg; try { jpeg = require('jpeg-js'); } catch {
|
|
121
|
-
const
|
|
122
|
-
return { w: d.width, h: d.height, rgba: d.data };
|
|
150
|
+
if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47) d = decodePNG(buf);
|
|
151
|
+
else if (buf[0] === 0xff && buf[1] === 0xd8) {
|
|
152
|
+
let jpeg; try { jpeg = require('jpeg-js'); } catch { jpeg = null; }
|
|
153
|
+
if (jpeg) { const j = jpeg.decode(buf, { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 512 }); d = { w: j.width, h: j.height, rgba: j.data }; }
|
|
123
154
|
}
|
|
124
|
-
} catch { /* formato corrupto */ }
|
|
125
|
-
return null;
|
|
155
|
+
} catch { /* formato corrupto o demasiado grande */ }
|
|
156
|
+
return d || (process.platform === 'darwin' ? decodeViaSips(buf) : null);
|
|
126
157
|
}
|
|
127
158
|
|
|
128
159
|
/** Reduce con filtro de caja y compone sobre un fondo oscuro. Devuelve RGB (3 bytes por píxel). */
|
|
@@ -165,4 +196,4 @@ function halfBlocks(rgb, tw, th2) {
|
|
|
165
196
|
return rows;
|
|
166
197
|
}
|
|
167
198
|
|
|
168
|
-
module.exports = { collectImages, extractImages, findImageByNumber, decodePNG, decodeImage, scaleBox, fitSize, halfBlocks };
|
|
199
|
+
module.exports = { collectImages, extractImages, findImageByNumber, decodePNG, decodeImage, decodeViaSips, sniffExt, scaleBox, fitSize, halfBlocks };
|
package/lib/mascot.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// La mascota de Hopdeck: un sapo naranja con auriculares. Son 64×64 píxeles con transparencia que se dibujan con medios bloques
|
|
3
|
+
// (▀ ▄) al tamaño que quepa. Los píxeles van comprimidos (zlib + base64) para no depender de ningún archivo de imagen.
|
|
4
|
+
const zlib = require('zlib');
|
|
5
|
+
const { TRUE, R } = require('./style');
|
|
6
|
+
|
|
7
|
+
const SIZE = 64;
|
|
8
|
+
const PIXELS = zlib.inflateSync(Buffer.from(
|
|
9
|
+
'eNrtewd8VNW2N+WWh42SOpmZc2ZOL3OmlxSSANI7QighCT10AtJ7syCKFEFEAQXlXgXUawMUBNQrCOpFrCBypVdBIQnJlP/Z3++c' +
|
|
10
|
+
'gPJ83vt9n4r63nP/fiszk7P32uu/9tprr732PrVq/V5+L7+XX7nUvo7+p+Osm5+f/weDatWqVeeH6xTUvfq87v8QndS5iucHC8dx' +
|
|
11
|
+
'f7bZbPUKavD+QCmoW+tfPvtt475ebgOnwithWZRHyYK8WuClHRwvf8Ry4hGGk45xnHxQ4OVdEi89LYvyVJ6XmzMMU/97/Or894Be' +
|
|
12
|
+
'8C1ukRE1SZDmC4JykGZlksEoJJ1RzU+KlYmTkwjDyaTmmUzSnAqxMIr5m+flkyIvrWRZMfuHeP9G57g5Rg6HKEq8tJbh5KjFqRAr' +
|
|
13
|
+
'LZCwqiT6NnZH57XzRv/a3RfbWhKI7+4fiL8zIBDf2TcQ39jDF3ugvTs2MNcVy3LJcSsjkXSnQlheJpIgv8iykv97PvO3Zu9mEThh' +
|
|
14
|
+
'DMfLl9OcMuEdDIbma9HNw26Pnx2TCTI5E2RqVjwxMTNW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HkvKoqvkhG9cQujEV7y' +
|
|
99
|
+
'EUXxE/l7pCg+IkjeeJpTq6IFzyVZ9p2RZN8/Zdn3oaT435AV/7Oy7F8hyr7ZouwbIoq+DqLoC/K8x3r1XukvUer+v8fZBXXdbvfN' +
|
|
100
|
+
'HOdNYVnV7vV6+bxAQHPLQR/Pe8I1uqv5lCR/QBBcbk3UxLZZWXR+KJTOMIH6/5+46vybd6tuSCxw7X2t6+kGrb91ahX8574MG7xu' +
|
|
101
|
+
'v/9bfFfs+nf76nyPrtrRNfovz/+3vBf4e/m9/F5+hfJ/AKLTK1o=', 'base64')); // RGBA, 4 bytes por píxel
|
|
102
|
+
|
|
103
|
+
/** La misma mascota sin colores, para NO_COLOR o --plain. */
|
|
104
|
+
const ASCII = " .-============-.\n .-' _ _ '-.\n / (o) (o) \\\\\n .---|---. .. .---|---.\n | >_ | \\____/ | |\n '---|---' '---|---'\n \\ .------. /\n '._ \\____/ _.-'\n '----------'\n /_||_\\\\";
|
|
105
|
+
|
|
106
|
+
/** Color del píxel (r, g, b) de la celda (x, y) de una versión de n×n: promedio de los píxeles que cubre, o null si es transparente. */
|
|
107
|
+
function sample(x, y, n) {
|
|
108
|
+
const x0 = Math.floor((x * SIZE) / n), x1 = Math.max(x0 + 1, Math.floor(((x + 1) * SIZE) / n));
|
|
109
|
+
const y0 = Math.floor((y * SIZE) / n), y1 = Math.max(y0 + 1, Math.floor(((y + 1) * SIZE) / n));
|
|
110
|
+
let a = 0, r = 0, g = 0, b = 0, cnt = 0;
|
|
111
|
+
for (let yy = y0; yy < y1 && yy < SIZE; yy++) {
|
|
112
|
+
for (let xx = x0; xx < x1 && xx < SIZE; xx++) {
|
|
113
|
+
const i = (yy * SIZE + xx) * 4, al = PIXELS[i + 3];
|
|
114
|
+
cnt++; a += al; r += PIXELS[i] * al; g += PIXELS[i + 1] * al; b += PIXELS[i + 2] * al;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (!cnt || !a || a / cnt < 100) return null; // casi transparente
|
|
118
|
+
return [Math.round(r / a), Math.round(g / a), Math.round(b / a)];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const c256 = ([r, g, b]) => { const q = (v) => Math.round((v / 255) * 5); return 16 + 36 * q(r) + 6 * q(g) + q(b); };
|
|
122
|
+
const col = (c, bg) => (TRUE ? `\x1b[${bg ? 48 : 38};2;${c[0]};${c[1]};${c[2]}m` : `\x1b[${bg ? 48 : 38};5;${c256(c)}m`);
|
|
123
|
+
/** Cada celda son dos píxeles: ▀ con el de arriba de color de letra y el de abajo de fondo. Lo transparente deja ver el fondo del terminal. */
|
|
124
|
+
function cell(top, bottom) {
|
|
125
|
+
if (!top && !bottom) return ' ';
|
|
126
|
+
if (top && !bottom) return col(top) + '▀' + R;
|
|
127
|
+
if (!top && bottom) return col(bottom) + '▄' + R;
|
|
128
|
+
return col(top) + col(bottom, true) + '▀' + R;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const CACHE = new Map();
|
|
132
|
+
/** Filas de texto (n celdas de ancho, n/2 de alto) con la mascota a n×n píxeles. */
|
|
133
|
+
function render(n) {
|
|
134
|
+
n = Math.max(2, Math.min(SIZE, n & ~1));
|
|
135
|
+
if (CACHE.has(n)) return CACHE.get(n);
|
|
136
|
+
const rows = [];
|
|
137
|
+
for (let y = 0; y < n; y += 2) {
|
|
138
|
+
let line = '';
|
|
139
|
+
for (let x = 0; x < n; x++) line += cell(sample(x, y, n), sample(x, y + 1, n));
|
|
140
|
+
rows.push(line);
|
|
141
|
+
}
|
|
142
|
+
CACHE.set(n, rows);
|
|
143
|
+
return rows;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** El mayor tamaño que cabe en `maxCols` columnas y `maxRows` filas, o 0 si ni el más pequeño. */
|
|
147
|
+
const sizeFor = (maxCols, maxRows) => [48, 40, 32, 24, 16].find((n) => n <= maxCols && n / 2 <= maxRows) || 0;
|
|
148
|
+
|
|
149
|
+
module.exports = { SIZE, ASCII, render, sizeFor };
|
package/lib/text.js
CHANGED
|
@@ -8,10 +8,27 @@ const tidy = (s) => s.replace(/\s+/g, ' ').trim();
|
|
|
8
8
|
const home = os.homedir();
|
|
9
9
|
const shortPath = (p) => (p.startsWith(home) ? '~' + p.slice(home.length) : p);
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* Minúsculas y sin acentos («Visión» → «vision», «ñ» → «n»). Cada letra se pliega por separado, así el resultado mide lo mismo
|
|
13
|
+
* que el original y una posición encontrada en uno vale para el otro (hace falta para resaltar las coincidencias).
|
|
14
|
+
*/
|
|
15
|
+
function fold(s) {
|
|
16
|
+
let o = '';
|
|
17
|
+
for (const ch of String(s)) {
|
|
18
|
+
const b = Array.from(ch.normalize('NFD'))[0] || ch, l = b.toLowerCase();
|
|
19
|
+
o += l.length === b.length ? l : b;
|
|
20
|
+
}
|
|
21
|
+
return o;
|
|
22
|
+
}
|
|
23
|
+
/** Palabras de una búsqueda, ya plegadas. */
|
|
24
|
+
const queryWords = (q) => fold(q).split(/\s+/).filter(Boolean);
|
|
25
|
+
/** ¿Aparecen todas las palabras (en cualquier orden) en el texto ya plegado? */
|
|
26
|
+
const matchWords = (ws, folded) => ws.every((w) => folded.includes(w));
|
|
27
|
+
|
|
11
28
|
/** Coincidencia difusa: cada palabra de la consulta debe aparecer como subsecuencia. -1 si no coincide. */
|
|
12
29
|
function fuzzy(q, text) {
|
|
13
|
-
const t = text
|
|
14
|
-
for (const term of q
|
|
30
|
+
const t = fold(text); let total = 0;
|
|
31
|
+
for (const term of queryWords(q)) {
|
|
15
32
|
let pos = -1, run = 0, score = 0;
|
|
16
33
|
const sub = t.indexOf(term);
|
|
17
34
|
if (sub >= 0) { total += 10 + term.length * 3 - Math.min(sub, 30) / 3; continue; }
|
|
@@ -40,4 +57,4 @@ function wrapText(text, width) {
|
|
|
40
57
|
return out;
|
|
41
58
|
}
|
|
42
59
|
|
|
43
|
-
module.exports = { baseName, tidy, home, shortPath, fuzzy, wrapText };
|
|
60
|
+
module.exports = { baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, wrapText };
|
package/package.json
CHANGED