hopdeck 1.3.1 → 1.4.0
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 +17 -0
- package/bin/hopdeck.js +119 -39
- package/lib/history.js +42 -9
- package/lib/i18n.js +4 -0
- package/lib/images.js +40 -9
- package/lib/text.js +20 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Cambios
|
|
2
2
|
|
|
3
|
+
## 1.4.0
|
|
4
|
+
|
|
5
|
+
### Nuevo
|
|
6
|
+
- **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).
|
|
7
|
+
|
|
8
|
+
### Mejorado
|
|
9
|
+
- **La búsqueda es más fácil de encontrar y falla menos.**
|
|
10
|
+
- **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.
|
|
11
|
+
- **`⏎` 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í).
|
|
12
|
+
- **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.
|
|
13
|
+
- **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.
|
|
14
|
+
- **Sin resultados lo dice:** «Sin resultados para …» y qué hacer, en lugar de una lista vacía.
|
|
15
|
+
|
|
16
|
+
### Arreglado
|
|
17
|
+
- **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.
|
|
18
|
+
- **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é.
|
|
19
|
+
|
|
3
20
|
## 1.3.1
|
|
4
21
|
|
|
5
22
|
### Nuevo
|
package/bin/hopdeck.js
CHANGED
|
@@ -13,7 +13,7 @@ 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 { baseName, tidy, home, shortPath, fuzzy, wrapText } = require('../lib/text');
|
|
16
|
+
const { baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, wrapText } = require('../lib/text');
|
|
17
17
|
const hist = require('../lib/history');
|
|
18
18
|
const { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, readSession, decodeDir, projectDirs, buildProject, beginScan, endScan } = hist;
|
|
19
19
|
const images = require('../lib/images');
|
|
@@ -126,7 +126,7 @@ function ago(ms) {
|
|
|
126
126
|
}
|
|
127
127
|
|
|
128
128
|
// ───────────────────────── 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: '' };
|
|
129
|
+
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
130
|
const SIDEBAR = process.argv.includes('--sidebar');
|
|
131
131
|
let EMBED = false; // vista dividida con terminal embebido (Windows / sin tmux)
|
|
132
132
|
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 +154,21 @@ async function reloadAsync(after, silent) {
|
|
|
154
154
|
|
|
155
155
|
const clamp = (n, a, b) => Math.max(a, Math.min(b, n));
|
|
156
156
|
|
|
157
|
+
/** 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. */
|
|
158
|
+
const sessTag = (s) => (s.parts ? '↻' + s.parts : s.dup ? '#' + s.id.slice(0, 4) : '');
|
|
159
|
+
|
|
157
160
|
function view() {
|
|
158
|
-
|
|
161
|
+
// La búsqueda son palabras sueltas, sin importar el orden, mayúsculas ni acentos: «vistas roles» encuentra «Roles y vistas».
|
|
162
|
+
// 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.
|
|
163
|
+
const ws = queryWords(S.query);
|
|
159
164
|
const base = S.projects.filter((p) => S.showHidden || !p.hidden);
|
|
160
165
|
const vis = (x) => S.showHidden || !CFG.archived.includes(x.id);
|
|
161
|
-
if (!
|
|
162
|
-
const hitS = (x) => (x.title + ' ' + x.first)
|
|
166
|
+
if (!ws.length) return base.map((p) => ({ p, ss: p.sessions.filter(vis) }));
|
|
167
|
+
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
168
|
const out = [];
|
|
164
169
|
for (const p of base) {
|
|
165
|
-
const hit = (p.name + ' ' + p.cwd)
|
|
166
|
-
const ss = (hit ? p.sessions : p.sessions.filter(hitS)).filter(vis);
|
|
170
|
+
const hit = matchWords(ws, p._f || (p._f = fold(p.name + ' ' + p.cwd)));
|
|
171
|
+
const ss = (hit ? p.sessions : p.sessions.filter((x) => hitS(p, x))).filter(vis);
|
|
167
172
|
if (hit || ss.length) out.push({ p, ss });
|
|
168
173
|
}
|
|
169
174
|
return out;
|
|
@@ -174,8 +179,11 @@ let deepT = null, deepTok = 0, deepPrev = null, deepJob = null;
|
|
|
174
179
|
function queryChanged() {
|
|
175
180
|
clearTimeout(deepT); deepTok++; S.deepHits = null;
|
|
176
181
|
if (deepJob) { deepJob.cancel(); deepJob = null; }
|
|
177
|
-
|
|
178
|
-
|
|
182
|
+
// Si ningún título ni proyecto coincide, se busca solo dentro del contenido sin que haya que pedirlo con Tab
|
|
183
|
+
S.auto = !S.deep && S.query.trim().length >= 3 && !view().length;
|
|
184
|
+
const deepOn = S.deep || S.auto;
|
|
185
|
+
if (!deepOn || !S.query.trim()) deepPrev = null;
|
|
186
|
+
if (!deepOn || S.query.trim().length < 3) { if (!reloading) S.loading = false; return; }
|
|
179
187
|
const tok = deepTok; S.loading = true; ensureSpin();
|
|
180
188
|
deepT = setTimeout(() => {
|
|
181
189
|
const q = S.query.trim().toLowerCase(), hits = new Set();
|
|
@@ -260,7 +268,7 @@ function frame(cols, rows) {
|
|
|
260
268
|
const tw = rw - 2 - when.length - 2;
|
|
261
269
|
right = fit([[mark, C.accent], [e.title, sel ? C.text + C.bold : C.text],
|
|
262
270
|
[e.first && e.first !== e.title ? ' ' + e.first : '', C.dim],
|
|
263
|
-
[e
|
|
271
|
+
[sessTag(e) ? ' ' + sessTag(e) : '', C.accent]], tw + 2, base) +
|
|
264
272
|
fit([[' ' + when, C.dim]], rw - tw - 2, base);
|
|
265
273
|
}
|
|
266
274
|
} else right = ' '.repeat(rw);
|
|
@@ -333,18 +341,20 @@ function chatMark(id) {
|
|
|
333
341
|
|
|
334
342
|
/** Trocea `text` en segmentos [[texto, estilo]] resaltando las coincidencias (sin distinguir mayúsculas) con la búsqueda `q` (en minúsculas). */
|
|
335
343
|
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
|
-
|
|
344
|
+
const t = String(text), ws = queryWords(q);
|
|
345
|
+
if (!ws.length) return [[t, style]];
|
|
346
|
+
const f = fold(t);
|
|
347
|
+
if (f.length !== t.length) return [[t, style]]; // algunas letras cambian de largo al plegarlas: no se resalta
|
|
348
|
+
const on = new Array(t.length).fill(false); // cada palabra de la búsqueda, en cualquier parte y sin importar acentos ni mayúsculas
|
|
349
|
+
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;
|
|
350
|
+
if (!on.includes(true)) return [[t, style]];
|
|
351
|
+
const out = [];
|
|
352
|
+
for (let i = 0; i < t.length;) {
|
|
353
|
+
let j = i; while (j < t.length && on[j] === on[i]) j++;
|
|
354
|
+
out.push([t.slice(i, j), on[i] ? C.brand + C.bold : style]);
|
|
355
|
+
i = j;
|
|
345
356
|
}
|
|
346
|
-
|
|
347
|
-
return out.length ? out : [[t, style]];
|
|
357
|
+
return out;
|
|
348
358
|
}
|
|
349
359
|
|
|
350
360
|
/** Resumen de los chats abiertos para la cabecera de la lista: trabajando ⠋, terminados sin ver ✔, abiertos ●. */
|
|
@@ -368,9 +378,19 @@ function frameTree(W, H) {
|
|
|
368
378
|
const bodyH = H - 5;
|
|
369
379
|
S.coff = scroll(S.coff, S.c, bodyH);
|
|
370
380
|
const lines = [];
|
|
371
|
-
|
|
381
|
+
const searchOn = !S.fb && !S.qs && S.prompt === null && !S.help && (S.searching || !!S.query.trim()); // hay una búsqueda en marcha
|
|
382
|
+
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()];
|
|
383
|
+
// «⌕ / buscar» siempre a la vista, arriba a la derecha (sin la palabra si el título y los chats abiertos ya ocupan el sitio)
|
|
384
|
+
const headW = head.reduce((a, [t]) => a + strW(t), 0), longHint = ' ⌕ / ' + T.k.find + ' ', hint = headW + strW(longHint) <= W ? longHint : headW + 5 <= W ? ' ⌕ / ' : '';
|
|
385
|
+
lines.push(searchOn
|
|
386
|
+
// el cuadro de búsqueda ocupa el lugar del título, arriba, donde se mira primero
|
|
387
|
+
? fit([[' ⌕ ', C.accent], ...withCursor(S.query, S.searching ? S.qpos : [...S.query].length, S.searching), [S.query ? '' : ' ' + T.searchPh, C.dim]], W)
|
|
388
|
+
: 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))
|
|
389
|
+
: fit(head, W));
|
|
372
390
|
lines.push(C.faint + '─'.repeat(W) + R);
|
|
373
391
|
const sq0 = S.query.trim().toLowerCase(); // búsqueda activa: se resaltan las coincidencias
|
|
392
|
+
const qWords = searchOn ? queryWords(S.query) : [];
|
|
393
|
+
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
394
|
const qsList = S.qs ? qsItems() : null;
|
|
375
395
|
const fbList = S.fb && !S.qs ? fbRows() : null;
|
|
376
396
|
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 +423,11 @@ function frameTree(W, H) {
|
|
|
403
423
|
}
|
|
404
424
|
if (S.help) { const t = T.help[r]; lines.push(fit([[t ? ' ' + t : '', r === 0 ? C.accent + C.bold : C.dim]], W)); continue; }
|
|
405
425
|
const e = L[S.coff + r];
|
|
426
|
+
if (!e && searchOn && !L.length && r <= 2) { // búsqueda sin resultados: se dice, y se explica qué hacer
|
|
427
|
+
const msg = r === 0 ? [[' ' + T.noRes(S.query.trim()), C.warn]]
|
|
428
|
+
: r === 2 ? [[' ' + ((S.deep || S.auto) ? (S.loading ? spin() + ' ' + T.searchingContent : '') : T.tryContent), C.dim]] : [];
|
|
429
|
+
lines.push(fit(msg, W)); continue;
|
|
430
|
+
}
|
|
406
431
|
if (!e) { lines.push(' '.repeat(W)); continue; }
|
|
407
432
|
const sel = S.coff + r === S.c;
|
|
408
433
|
const base = sel ? (EMBED && E.focus === 'right' ? C.selOff : C.selOn) : '';
|
|
@@ -426,8 +451,8 @@ function frameTree(W, H) {
|
|
|
426
451
|
lines.push(fit([mark, [' + ', C.accent], [T.newChat, sel ? C.accent + C.bold : C.accent]], W, base));
|
|
427
452
|
} else {
|
|
428
453
|
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 =
|
|
454
|
+
const arch = CFG.archived.includes(e.s.id), tag = sessTag(e.s);
|
|
455
|
+
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
456
|
lines.push(fit([mark, [' ', ''], [mk, mc], ...hl(e.s.title, sq0, ts), ...(inTxt ? [[' ⌕', C.dim]] : [])], W - 13, base) +
|
|
432
457
|
fit([[tag.padEnd(6), C.accent], [ago(e.s.mtime).padStart(6), C.dim], [' ', '']], 13, base));
|
|
433
458
|
}
|
|
@@ -436,7 +461,10 @@ function frameTree(W, H) {
|
|
|
436
461
|
lines.push(C.faint + '─'.repeat(W) + R);
|
|
437
462
|
const br = cur && !S.flash ? gitBranch(cur.p.cwd) : '';
|
|
438
463
|
const note = EMBED && E.note;
|
|
439
|
-
|
|
464
|
+
const deepOn = S.deep || S.auto;
|
|
465
|
+
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
|
|
466
|
+
? [[' ', ''], nHits ? [T.found(nHits), C.accent + C.bold] : [T.noMatch, C.warn], deepOn ? [S.loading ? ' ' + spin() + ' ' + T.searchingContent : ' · ' + T.inContent, C.dim] : ['', '']]
|
|
467
|
+
: 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
468
|
: [[br ? ' ⎇ ' + br + ' ' : '', C.accent], [cur ? (br ? '' : ' ⌂ ') + shortPath(cur.p.cwd) : '', C.dim]], W));
|
|
441
469
|
if (S.qs) {
|
|
442
470
|
lines.push(fit([[' ⌕ ', C.accent], ...withCursor(S.qs.q, S.qs.pc), [S.qs.q ? '' : ' ' + T.qsHint, C.dim]], W));
|
|
@@ -445,9 +473,10 @@ function frameTree(W, H) {
|
|
|
445
473
|
lines.push(fit([[rn ? ' ✎ ' : ' ⌂ ', C.accent], ...withCursor(S.prompt, S.pc), [S.prompt ? '' : ' ' + (rn ? T.renameLbl : T.pathPrompt) + '…', C.dim]], W));
|
|
446
474
|
} else if (S.fb) {
|
|
447
475
|
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
|
-
|
|
476
|
+
} else if (searchOn) {
|
|
477
|
+
// teclas de la búsqueda: mientras se escribe, ⏎ abre la conversación marcada; con la búsqueda ya aceptada, / permite editarla
|
|
478
|
+
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],
|
|
479
|
+
['esc', C.accent], [' ' + (S.searching ? T.kEsc : T.kClear), C.dim]], W));
|
|
451
480
|
} else {
|
|
452
481
|
const k = T.k, segs = [[' ', '']];
|
|
453
482
|
const keys = !cur ? [['⏎', k.open], ['n', k.neu], ['/', k.find], ['?', T.kHelp]]
|
|
@@ -541,7 +570,8 @@ function doRename(x, name) {
|
|
|
541
570
|
|
|
542
571
|
function adjustSidebar(d) {
|
|
543
572
|
const cur = EMBED ? embedLayout().SW || 36 : process.stdout.columns || 40;
|
|
544
|
-
|
|
573
|
+
const lim = EMBED ? panelLimits(process.stdout.columns || 100) : { min: 24, max: 80 };
|
|
574
|
+
CFG.sidebar = clamp(cur + d, lim.min, lim.max); saveCfg();
|
|
545
575
|
if (EMBED) return embedResize();
|
|
546
576
|
if (SIDEBAR) { try { tmux('resize-pane', '-t', process.env.TMUX_PANE, '-x', String(CFG.sidebar)); } catch { /* */ } render(); }
|
|
547
577
|
}
|
|
@@ -724,11 +754,21 @@ function onKeyTree(raw) {
|
|
|
724
754
|
if (S.fb) return fbKey(k, raw);
|
|
725
755
|
if (S.searching) {
|
|
726
756
|
if (k === 'esc') { S.query = ''; S.searching = false; S.c = 0; queryChanged(); }
|
|
727
|
-
else if (k === 'enter')
|
|
757
|
+
else if (k === 'enter') {
|
|
758
|
+
S.searching = false;
|
|
759
|
+
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
|
|
760
|
+
if (en && en.t === 's') { render(); return launch(en.p, en.s); }
|
|
761
|
+
}
|
|
728
762
|
else if (k === '\t') { S.deep = !S.deep; queryChanged(); }
|
|
729
763
|
else if (k === 'up') S.c = Math.max(0, S.c - 1);
|
|
730
764
|
else if (k === 'down') S.c = Math.min(L.length - 1, S.c + 1);
|
|
731
|
-
else {
|
|
765
|
+
else {
|
|
766
|
+
const r = editBuf(S.query, S.qpos, k, raw);
|
|
767
|
+
if (r) {
|
|
768
|
+
const ch = r.s !== S.query; S.query = r.s; S.qpos = r.pos;
|
|
769
|
+
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
|
|
770
|
+
}
|
|
771
|
+
}
|
|
732
772
|
return render();
|
|
733
773
|
}
|
|
734
774
|
S.flash = '';
|
|
@@ -852,14 +892,42 @@ function loadDeps() {
|
|
|
852
892
|
try { return { pty: require('@lydell/node-pty'), Terminal: require('@xterm/headless').Terminal }; } catch { return null; }
|
|
853
893
|
}
|
|
854
894
|
|
|
895
|
+
/** 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). */
|
|
896
|
+
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)) });
|
|
897
|
+
/** Ancho de la lista (panel izquierdo): el guardado por el usuario, o 30 % del terminal por defecto. */
|
|
898
|
+
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));
|
|
899
|
+
/** Ancho del panel de git (derecho): el guardado por el usuario, o GIT_W por defecto. */
|
|
900
|
+
const gitWidth = (W) => (CFG.gitw ? clamp(CFG.gitw, panelLimits(W).min, panelLimits(W).max) : GIT_W);
|
|
901
|
+
|
|
855
902
|
function embedLayout() {
|
|
856
903
|
const W = process.stdout.columns || 100, H = process.stdout.rows || 30;
|
|
857
|
-
const SW =
|
|
904
|
+
const SW = sideWidth(W);
|
|
858
905
|
const room = Math.max(10, W - SW - (SW ? 1 : 0));
|
|
859
|
-
const
|
|
906
|
+
const gw = gitWidth(W);
|
|
907
|
+
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
908
|
return { W, H, SW, GW, rw: GW ? room - GW - 1 : room, rh: Math.max(3, H - 1), th: Math.max(3, H - 3) };
|
|
861
909
|
}
|
|
862
910
|
|
|
911
|
+
/**
|
|
912
|
+
* Arrastre de una línea divisoria: `x` es la columna (desde 1) donde está el ratón. La lista ocupa las columnas anteriores
|
|
913
|
+
* 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.
|
|
914
|
+
*/
|
|
915
|
+
function dragPanel(which, x) {
|
|
916
|
+
const { W, SW, GW } = embedLayout(), l = panelLimits(W);
|
|
917
|
+
if (which === 'side') {
|
|
918
|
+
const hi = Math.max(l.min, Math.min(l.max, W - 1 - (GW ? GW + 1 + GIT_MIN_CHAT : 40)));
|
|
919
|
+
const n = clamp(x - 1, l.min, hi);
|
|
920
|
+
if (n === SW) return;
|
|
921
|
+
CFG.sidebar = n;
|
|
922
|
+
} else {
|
|
923
|
+
const hi = Math.max(l.min, Math.min(l.max, W - (SW ? SW + 1 : 0) - 1 - GIT_MIN_CHAT));
|
|
924
|
+
const n = clamp(W - x, l.min, hi);
|
|
925
|
+
if (n === GW) return;
|
|
926
|
+
CFG.gitw = n;
|
|
927
|
+
}
|
|
928
|
+
embedResize();
|
|
929
|
+
}
|
|
930
|
+
|
|
863
931
|
// ───────────────────────── panel de git (tercer panel, F8) ─────────────────────────
|
|
864
932
|
const GIT_W = 38, GIT_MIN_CHAT = 60;
|
|
865
933
|
const GITC = new Map(); // carpeta → { t, loading, data }
|
|
@@ -880,8 +948,8 @@ const gitCwd = () => {
|
|
|
880
948
|
function toggleGit() {
|
|
881
949
|
if (!EMBED) return flash(T.gitOnlyEmbed);
|
|
882
950
|
if (!E.git) {
|
|
883
|
-
const
|
|
884
|
-
const need = SW + (SW ? 1 : 0) + GIT_MIN_CHAT +
|
|
951
|
+
const W = process.stdout.columns || 100, SW = sideWidth(W);
|
|
952
|
+
const need = SW + (SW ? 1 : 0) + GIT_MIN_CHAT + gitWidth(W) + 1;
|
|
885
953
|
if ((process.stdout.columns || 100) < need) return flash(T.gitNarrow(need));
|
|
886
954
|
}
|
|
887
955
|
E.git = !E.git; CFG.git = E.git; saveCfg();
|
|
@@ -1137,7 +1205,7 @@ function hoverPopup(hv, rw, th) {
|
|
|
1137
1205
|
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
1206
|
rows = hb; tw = sz.tw;
|
|
1139
1207
|
} else {
|
|
1140
|
-
const txt = d === undefined ? spin() + ' …' : T.imgNoPrev
|
|
1208
|
+
const txt = d === undefined ? spin() + ' …' : `${T.imgNoPrev} (${img.media || '?'})`; // el formato ayuda a saber por qué no se pudo leer
|
|
1141
1209
|
tw = Math.max(strW(lab) + 1, Math.min(strW(txt) + 2, Math.max(8, rw - 4)));
|
|
1142
1210
|
rows = [fit([[' ' + txt, d === false ? C.warn : C.accent]], tw)];
|
|
1143
1211
|
}
|
|
@@ -1312,7 +1380,8 @@ function renderEmbed() {
|
|
|
1312
1380
|
const popRow = (ty) => (pop && ty >= pop.top && ty < pop.top + pop.rows.length
|
|
1313
1381
|
? 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
1382
|
: null);
|
|
1315
|
-
const div = (E.focus === 'right' ? C.accent : C.faint) + '│' + R;
|
|
1383
|
+
const div = (E.drag === 'side' || E.focus === 'right' ? C.accent : C.faint) + '│' + R;
|
|
1384
|
+
const gdiv = (E.drag === 'git' ? C.accent : C.faint) + '│' + R; // la línea que se está arrastrando se resalta
|
|
1316
1385
|
const gitR = GW ? gitRows(GW, rh) : null;
|
|
1317
1386
|
for (let y = 0; y < rh; y++) {
|
|
1318
1387
|
const ty = y - 2; // las 2 primeras filas del panel derecho son el título y su línea
|
|
@@ -1322,7 +1391,7 @@ function renderEmbed() {
|
|
|
1322
1391
|
: y === 1 ? C.faint + '─'.repeat(rw) + R : gRows[ty])
|
|
1323
1392
|
: y === 0 ? headerRow(hdr, rw) : y === 1 ? C.faint + '─'.repeat(rw) + R
|
|
1324
1393
|
: 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 ?
|
|
1394
|
+
rowsOut.push((left ? (left[y] || ' '.repeat(SW)) + div : '') + right + (gitR ? gdiv + gitR[y] : ''));
|
|
1326
1395
|
}
|
|
1327
1396
|
const live = E.sessions.size;
|
|
1328
1397
|
const k = (key, d) => [[key, C.accent], [' ' + d + ' ', C.dim]];
|
|
@@ -1470,6 +1539,7 @@ function sidebarMouse(b, x, y, type, rows = process.stdout.rows || 30) {
|
|
|
1470
1539
|
return render();
|
|
1471
1540
|
}
|
|
1472
1541
|
if (type !== 'M' || (b & 3) !== 0 || (b & 32)) return; // solo clic izquierdo (no soltar, ni arrastrar, ni otros botones)
|
|
1542
|
+
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
1543
|
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
1544
|
if (S.qs) { const i = S.qs.off + (y - 3); if (qsItems()[i]) { S.qs.i = i; return onKeyTree('\r'); } return; }
|
|
1475
1545
|
if (S.fb) { const i = S.fb.off + (y - 3); if (fbRows()[i]) { S.fb.i = i; fbActivate(); } return; }
|
|
@@ -1481,6 +1551,15 @@ function onMouse(b, x, y, type) {
|
|
|
1481
1551
|
if (E.gallery) return;
|
|
1482
1552
|
const { SW, GW, rw, rh } = embedLayout();
|
|
1483
1553
|
const sh = E.sessions.get(E.shown);
|
|
1554
|
+
// líneas divisorias arrastrables (columna de cada '│'): lista|chat y chat|git
|
|
1555
|
+
const sx = SW ? SW + 1 : 0, gx = GW ? sx + rw + 1 : 0;
|
|
1556
|
+
if (E.drag) {
|
|
1557
|
+
if (type === 'm') { E.drag = null; saveCfg(); return render(); }
|
|
1558
|
+
if ((b & 32) && (b & 3) === 0) return dragPanel(E.drag, x);
|
|
1559
|
+
} else if (type === 'M' && !(b & 96) && (b & 3) === 0 && y <= rh && ((SW && x === sx) || (GW && x === gx))) {
|
|
1560
|
+
E.drag = x === sx ? 'side' : 'git'; E.sel = null; E.hover = null;
|
|
1561
|
+
return render();
|
|
1562
|
+
}
|
|
1484
1563
|
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
1564
|
if (b & 64) { // rueda
|
|
1486
1565
|
E.hover = null;
|
|
@@ -1515,6 +1594,7 @@ function onMouse(b, x, y, type) {
|
|
|
1515
1594
|
return render();
|
|
1516
1595
|
}
|
|
1517
1596
|
if (type !== 'M' || (b & 3) !== 0) return; // solo clic izquierdo
|
|
1597
|
+
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
|
|
1518
1598
|
if (inPane) { E.focus = 'right'; const c = cell(); E.sel = { a: c, b: c, down: true }; return render(); }
|
|
1519
1599
|
E.sel = null;
|
|
1520
1600
|
if (S.fb && x <= SW) {
|
|
@@ -2184,6 +2264,6 @@ else {
|
|
|
2184
2264
|
readSession, buildProject, scan, scanAsync, finishScan, sortProjects, projectDirs,
|
|
2185
2265
|
view, flatList, stripBlock, offerShortcut, uninstallAll, commandName, suggestCommand, parseTermReplies, sixelOn, SNIP, MARK_A, MARK_B, toggleProject, cacheLoad, selNorm,
|
|
2186
2266
|
decodePNG, decodeImage, scaleBox, fitSize, halfBlocks, collectImages, extractImages,
|
|
2187
|
-
editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
|
|
2267
|
+
onMouse, dragPanel, panelLimits, embedLayout, sessTag, editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
|
|
2188
2268
|
};
|
|
2189
2269
|
}
|
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
|
@@ -44,6 +44,8 @@ const T = {
|
|
|
44
44
|
'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
45
|
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
46
|
idle3: 'F1 proyectos · F2 chat', bar1: 'proyectos', bar2: 'chat', bar3: 'minimizar',
|
|
47
|
+
searchPh: 'buscar conversación o proyecto…', found: (n) => `${n} ${n === 1 ? 'resultado' : 'resultados'}`, noRes: (q) => `Sin resultados para «${q}»`,
|
|
48
|
+
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
49
|
inside: 'Ya estás dentro de Hopdeck (F1 para ir a la lista de proyectos).',
|
|
48
50
|
},
|
|
49
51
|
en: {
|
|
@@ -87,6 +89,8 @@ const T = {
|
|
|
87
89
|
'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
90
|
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
91
|
idle3: 'F1 projects · F2 chat', bar1: 'projects', bar2: 'chat', bar3: 'minimize',
|
|
92
|
+
searchPh: 'search conversation or project…', found: (n) => `${n} ${n === 1 ? 'result' : 'results'}`, noRes: (q) => `No results for “${q}”`,
|
|
93
|
+
searchingContent: 'Searching inside the conversations…', tryContent: 'Press Tab to also search inside the content', inContent: 'in content', kClear: 'clear', kEdit: 'edit', kEsc: 'exit',
|
|
90
94
|
inside: 'You are already inside Hopdeck (F1 jumps to the project list).',
|
|
91
95
|
},
|
|
92
96
|
}[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/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