@leosdc/exploreio 0.0.0-stage → 0.3.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -2
  3. package/dist/cli.js +192 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/editor/vimBuffer.js +351 -0
  6. package/dist/editor/vimBuffer.js.map +1 -0
  7. package/dist/editor/vimEngine.js +574 -0
  8. package/dist/editor/vimEngine.js.map +1 -0
  9. package/dist/editor/vimView.js +175 -0
  10. package/dist/editor/vimView.js.map +1 -0
  11. package/dist/fs/explorer.js +207 -0
  12. package/dist/fs/explorer.js.map +1 -0
  13. package/dist/renderers/code.js +311 -0
  14. package/dist/renderers/code.js.map +1 -0
  15. package/dist/renderers/html.js +182 -0
  16. package/dist/renderers/html.js.map +1 -0
  17. package/dist/renderers/index.js +180 -0
  18. package/dist/renderers/index.js.map +1 -0
  19. package/dist/renderers/json.js +127 -0
  20. package/dist/renderers/json.js.map +1 -0
  21. package/dist/renderers/markdown.js +252 -0
  22. package/dist/renderers/markdown.js.map +1 -0
  23. package/dist/renderers/mermaid.js +611 -0
  24. package/dist/renderers/mermaid.js.map +1 -0
  25. package/dist/renderers/mermaidParser.js +526 -0
  26. package/dist/renderers/mermaidParser.js.map +1 -0
  27. package/dist/test/exploreio.test.js +202 -0
  28. package/dist/test/exploreio.test.js.map +1 -0
  29. package/dist/test/mermaid.test.js +156 -0
  30. package/dist/test/mermaid.test.js.map +1 -0
  31. package/dist/test/vim-editor.test.js +154 -0
  32. package/dist/test/vim-editor.test.js.map +1 -0
  33. package/dist/themes/palette.js +134 -0
  34. package/dist/themes/palette.js.map +1 -0
  35. package/dist/tui/ansi.js +274 -0
  36. package/dist/tui/ansi.js.map +1 -0
  37. package/dist/tui/app.js +944 -0
  38. package/dist/tui/app.js.map +1 -0
  39. package/dist/tui/clipboard.js +110 -0
  40. package/dist/tui/clipboard.js.map +1 -0
  41. package/dist/tui/input.js +123 -0
  42. package/dist/tui/input.js.map +1 -0
  43. package/dist/tui/screen.js +80 -0
  44. package/dist/tui/screen.js.map +1 -0
  45. package/package.json +51 -4
  46. package/scripts/postinstall.mjs +28 -0
  47. package/scripts/setup.mjs +89 -0
@@ -0,0 +1,944 @@
1
+ /**
2
+ * Exploreio TUI Application Controller (SPEC-001)
3
+ * Navegador estilo Yazi (3 painéis: Pai | Atual | Preview Rico) + Modo Leitor
4
+ * Fullscreen nativo no prompt com busca, JSON Tree interativo, Markdown rico,
5
+ * HTML Reader/Source, Syntax Highlighting e 3 temas oficiais.
6
+ */
7
+ import path from 'node:path';
8
+ import { VimEngine } from '../editor/vimEngine.js';
9
+ import { buildEditorFrame } from '../editor/vimView.js';
10
+ import { createFileOrDir, deleteEntry, formatBytes, readDirectoryEntries, renameEntry, safeReadFilePreview, safeWriteTextFile, } from '../fs/explorer.js';
11
+ import { collectAllCollapsiblePaths } from '../renderers/json.js';
12
+ import { renderDirectoryPreview, renderDocument, } from '../renderers/index.js';
13
+ import { bg, fg, getTheme, nextTheme } from '../themes/palette.js';
14
+ import { BOLD, DIM, ITALIC, RESET, fitAnsi, highlightSearch, stripUnsafeAnsi, truncateAnsi, visibleLength } from './ansi.js';
15
+ import { copyTextToClipboard } from './clipboard.js';
16
+ import { parseInputChunk } from './input.js';
17
+ import { ScreenBuffer } from './screen.js';
18
+ function getFileBadge(entry, theme) {
19
+ if (entry.isDirectory)
20
+ return `${fg(theme.dir)}${BOLD}▸${RESET}`;
21
+ switch (entry.ext) {
22
+ case '.md':
23
+ case '.mdx':
24
+ return `${fg(theme.accent)}${BOLD}M${RESET}`;
25
+ case '.json':
26
+ case '.jsonc':
27
+ return `${fg(theme.warning)}${BOLD}{}${RESET}`;
28
+ case '.html':
29
+ case '.htm':
30
+ return `${fg(theme.syntaxTag)}${BOLD}<>${RESET}`;
31
+ case '.ts':
32
+ case '.tsx':
33
+ case '.js':
34
+ case '.jsx':
35
+ case '.py':
36
+ case '.rs':
37
+ case '.go':
38
+ return `${fg(theme.syntaxFunction)}${BOLD}λ${RESET}`;
39
+ default:
40
+ return `${fg(theme.muted)}·${RESET}`;
41
+ }
42
+ }
43
+ export class ExploreioApp {
44
+ screen = new ScreenBuffer();
45
+ themeName;
46
+ view = 'browser';
47
+ showHidden;
48
+ showHelp = false;
49
+ // Estado do navegador 3 painéis
50
+ currentDir;
51
+ parentEntries = [];
52
+ currentEntries = [];
53
+ selectedIndex = 0;
54
+ listScroll = 0;
55
+ filterQuery = '';
56
+ // Preview & Leitor Fullscreen
57
+ previewLines = [];
58
+ previewBadge = '';
59
+ activeFilePreview = null;
60
+ activeDoc = null;
61
+ preferredMode;
62
+ collapsedJsonPaths = new Set();
63
+ readerScroll = 0;
64
+ readerCursor = 0;
65
+ readerSearchQuery = '';
66
+ readerSearchMatches = [];
67
+ readerSearchCursor = 0;
68
+ // Editor modal estilo Vim (SPEC-002)
69
+ editorEngine = null;
70
+ editorFilePath = '';
71
+ editorReturnView = 'browser';
72
+ editorViewport = { scrollY: 0, scrollX: 0 };
73
+ editorStatusMessage = '';
74
+ editorStatusIsError = false;
75
+ editorSavedAny = false;
76
+ // Prompt modal inline (barra inferior)
77
+ promptKind = null;
78
+ promptInput = '';
79
+ toastMessage = '';
80
+ running = false;
81
+ constructor(options) {
82
+ this.currentDir = path.resolve(options.startDir);
83
+ this.themeName = options.themeName ?? 'midnight';
84
+ this.showHidden = Boolean(options.showHidden);
85
+ if (options.initialFile) {
86
+ this.currentDir = path.dirname(path.resolve(options.initialFile));
87
+ }
88
+ }
89
+ async start(initialFile) {
90
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
91
+ throw new Error('O modo interativo requer um terminal TTY. Use `--print <arquivo>` para saída direta.');
92
+ }
93
+ this.running = true;
94
+ this.screen.enter();
95
+ const cleanup = () => {
96
+ this.running = false;
97
+ this.screen.leave();
98
+ };
99
+ process.once('SIGINT', () => {
100
+ cleanup();
101
+ process.exit(0);
102
+ });
103
+ process.once('SIGTERM', () => {
104
+ cleanup();
105
+ process.exit(0);
106
+ });
107
+ process.stdout.on('resize', this.onResize);
108
+ process.stdin.on('data', this.onStdinData);
109
+ try {
110
+ await this.reloadDirectory();
111
+ if (initialFile) {
112
+ const resolved = path.resolve(initialFile);
113
+ const idx = this.currentEntries.findIndex((e) => e.fullPath === resolved);
114
+ if (idx >= 0)
115
+ this.selectedIndex = idx;
116
+ await this.openFileInReader(resolved);
117
+ }
118
+ this.draw();
119
+ }
120
+ catch (err) {
121
+ cleanup();
122
+ throw err;
123
+ }
124
+ }
125
+ shutdown() {
126
+ this.running = false;
127
+ process.stdout.off('resize', this.onResize);
128
+ process.stdin.off('data', this.onStdinData);
129
+ this.screen.leave();
130
+ }
131
+ onResize = () => {
132
+ this.screen.forceClear();
133
+ if (this.view === 'reader' && this.activeFilePreview) {
134
+ this.rerenderReaderDoc();
135
+ }
136
+ else {
137
+ void this.refreshSelectedPreview().then(() => this.draw());
138
+ }
139
+ this.draw();
140
+ };
141
+ onStdinData = (chunk) => {
142
+ if (!this.running)
143
+ return;
144
+ const events = parseInputChunk(chunk.toString('utf8'));
145
+ void this.handleEvents(events);
146
+ };
147
+ async handleEvents(events) {
148
+ for (const ev of events) {
149
+ if (!this.running)
150
+ return;
151
+ if (ev.ctrl && ev.name === 'c') {
152
+ this.shutdown();
153
+ process.exit(0);
154
+ }
155
+ if (this.showHelp) {
156
+ if (ev.name === 'escape' || ev.char === '?' || ev.char === 'q') {
157
+ this.showHelp = false;
158
+ this.draw();
159
+ }
160
+ continue;
161
+ }
162
+ if (this.promptKind) {
163
+ await this.handlePromptKey(ev);
164
+ continue;
165
+ }
166
+ if (this.view === 'editor') {
167
+ await this.handleEditorKey(ev);
168
+ }
169
+ else if (this.view === 'reader') {
170
+ await this.handleReaderKey(ev);
171
+ }
172
+ else {
173
+ await this.handleBrowserKey(ev);
174
+ }
175
+ }
176
+ }
177
+ async handlePromptKey(ev) {
178
+ if (ev.name === 'escape') {
179
+ if (this.promptKind === 'filter') {
180
+ this.filterQuery = '';
181
+ await this.reloadDirectory();
182
+ }
183
+ this.promptKind = null;
184
+ this.promptInput = '';
185
+ this.draw();
186
+ return;
187
+ }
188
+ if (ev.name === 'enter') {
189
+ const kind = this.promptKind;
190
+ const value = this.promptInput;
191
+ this.promptKind = null;
192
+ this.promptInput = '';
193
+ if (kind === 'filter') {
194
+ this.filterQuery = value;
195
+ await this.reloadDirectory();
196
+ }
197
+ else if (kind === 'search') {
198
+ this.readerSearchQuery = value.trim();
199
+ this.recomputeSearchMatches();
200
+ if (this.readerSearchMatches.length > 0) {
201
+ this.readerSearchCursor = 0;
202
+ this.jumpToMatch(0);
203
+ this.toastMessage = `${this.readerSearchMatches.length} ocorrência(s) encontrada(s)`;
204
+ }
205
+ else if (this.readerSearchQuery) {
206
+ this.toastMessage = `Nenhuma ocorrência para "${this.readerSearchQuery}"`;
207
+ }
208
+ }
209
+ else if (kind === 'create' && value.trim()) {
210
+ try {
211
+ await createFileOrDir(this.currentDir, value);
212
+ this.toastMessage = `Criado: ${value.trim()}`;
213
+ await this.reloadDirectory();
214
+ }
215
+ catch (err) {
216
+ this.toastMessage = err instanceof Error ? err.message : String(err);
217
+ }
218
+ }
219
+ else if (kind === 'rename' && value.trim()) {
220
+ const current = this.currentEntries[this.selectedIndex];
221
+ if (current) {
222
+ try {
223
+ await renameEntry(current.fullPath, value);
224
+ this.toastMessage = `Renomeado para: ${value.trim()}`;
225
+ await this.reloadDirectory();
226
+ }
227
+ catch (err) {
228
+ this.toastMessage = err instanceof Error ? err.message : String(err);
229
+ }
230
+ }
231
+ }
232
+ else if (kind === 'delete') {
233
+ const current = this.currentEntries[this.selectedIndex];
234
+ if (current && (value.trim().toLowerCase() === 'y' || value.trim().toLowerCase() === 's')) {
235
+ try {
236
+ await deleteEntry(current.fullPath);
237
+ this.toastMessage = `Removido: ${current.name}`;
238
+ await this.reloadDirectory();
239
+ }
240
+ catch (err) {
241
+ this.toastMessage = err instanceof Error ? err.message : String(err);
242
+ }
243
+ }
244
+ else {
245
+ this.toastMessage = 'Exclusão cancelada.';
246
+ }
247
+ }
248
+ this.draw();
249
+ return;
250
+ }
251
+ if (ev.name === 'backspace') {
252
+ this.promptInput = this.promptInput.slice(0, -1);
253
+ if (this.promptKind === 'filter') {
254
+ this.filterQuery = this.promptInput;
255
+ await this.reloadDirectory();
256
+ }
257
+ this.draw();
258
+ return;
259
+ }
260
+ if (ev.char) {
261
+ this.promptInput += ev.char;
262
+ if (this.promptKind === 'filter') {
263
+ this.filterQuery = this.promptInput;
264
+ await this.reloadDirectory();
265
+ }
266
+ this.draw();
267
+ }
268
+ }
269
+ async handleBrowserKey(ev) {
270
+ this.toastMessage = '';
271
+ const maxIdx = Math.max(0, this.currentEntries.length - 1);
272
+ if (ev.char === 'q') {
273
+ this.shutdown();
274
+ process.exit(0);
275
+ }
276
+ if (ev.char === '?') {
277
+ this.showHelp = true;
278
+ this.draw();
279
+ return;
280
+ }
281
+ if (ev.char === 't') {
282
+ this.themeName = nextTheme(this.themeName);
283
+ this.toastMessage = `Tema ativo: ${getTheme(this.themeName).label}`;
284
+ await this.refreshSelectedPreview();
285
+ this.draw();
286
+ return;
287
+ }
288
+ if (ev.char === '.') {
289
+ this.showHidden = !this.showHidden;
290
+ this.toastMessage = this.showHidden ? 'Exibindo arquivos ocultos' : 'Ocultando arquivos iniciados por "."';
291
+ await this.reloadDirectory();
292
+ this.draw();
293
+ return;
294
+ }
295
+ if (ev.char === '/' || ev.char === 'f') {
296
+ this.promptKind = 'filter';
297
+ this.promptInput = this.filterQuery;
298
+ this.draw();
299
+ return;
300
+ }
301
+ if (ev.char === 'a') {
302
+ this.promptKind = 'create';
303
+ this.promptInput = '';
304
+ this.draw();
305
+ return;
306
+ }
307
+ if (ev.char === 'r' && this.currentEntries[this.selectedIndex]) {
308
+ this.promptKind = 'rename';
309
+ this.promptInput = this.currentEntries[this.selectedIndex]?.name ?? '';
310
+ this.draw();
311
+ return;
312
+ }
313
+ if (ev.char === 'd' && this.currentEntries[this.selectedIndex]) {
314
+ this.promptKind = 'delete';
315
+ this.promptInput = '';
316
+ this.draw();
317
+ return;
318
+ }
319
+ if (ev.char === 'y') {
320
+ await this.copySelectedPath();
321
+ return;
322
+ }
323
+ if (ev.char === 'e') {
324
+ const entry = this.currentEntries[this.selectedIndex];
325
+ if (entry && !entry.isDirectory) {
326
+ await this.openFileInEditor(entry.fullPath, 'browser');
327
+ }
328
+ else {
329
+ this.toastMessage = 'Selecione um arquivo de texto para abrir no editor Vim (e).';
330
+ this.draw();
331
+ }
332
+ return;
333
+ }
334
+ if (ev.name === 'up' || ev.char === 'k' || ev.name === 'wheel_up') {
335
+ if (this.selectedIndex > 0) {
336
+ this.selectedIndex--;
337
+ await this.refreshSelectedPreview();
338
+ }
339
+ }
340
+ else if (ev.name === 'down' || ev.char === 'j' || ev.name === 'wheel_down') {
341
+ if (this.selectedIndex < maxIdx) {
342
+ this.selectedIndex++;
343
+ await this.refreshSelectedPreview();
344
+ }
345
+ }
346
+ else if (ev.name === 'pageup') {
347
+ this.selectedIndex = Math.max(0, this.selectedIndex - 10);
348
+ await this.refreshSelectedPreview();
349
+ }
350
+ else if (ev.name === 'pagedown') {
351
+ this.selectedIndex = Math.min(maxIdx, this.selectedIndex + 10);
352
+ await this.refreshSelectedPreview();
353
+ }
354
+ else if (ev.name === 'home' || ev.char === 'g') {
355
+ this.selectedIndex = 0;
356
+ await this.refreshSelectedPreview();
357
+ }
358
+ else if (ev.name === 'end' || ev.char === 'G') {
359
+ this.selectedIndex = maxIdx;
360
+ await this.refreshSelectedPreview();
361
+ }
362
+ else if (ev.name === 'left' || ev.char === 'h' || ev.name === 'backspace') {
363
+ const parent = path.dirname(this.currentDir);
364
+ if (parent !== this.currentDir) {
365
+ const previousName = path.basename(this.currentDir);
366
+ this.currentDir = parent;
367
+ this.filterQuery = '';
368
+ await this.reloadDirectory(previousName);
369
+ }
370
+ }
371
+ else if (ev.name === 'enter' || ev.name === 'right' || ev.char === 'l') {
372
+ const entry = this.currentEntries[this.selectedIndex];
373
+ if (!entry)
374
+ return;
375
+ if (entry.isDirectory) {
376
+ this.currentDir = entry.fullPath;
377
+ this.filterQuery = '';
378
+ this.selectedIndex = 0;
379
+ this.listScroll = 0;
380
+ await this.reloadDirectory();
381
+ }
382
+ else {
383
+ await this.openFileInReader(entry.fullPath);
384
+ }
385
+ }
386
+ this.draw();
387
+ }
388
+ async handleReaderKey(ev) {
389
+ this.toastMessage = '';
390
+ const { height } = this.screen.getSize();
391
+ const bodyHeight = Math.max(4, height - 3);
392
+ const totalLines = this.activeDoc?.lines.length ?? 0;
393
+ const isJsonTree = this.activeDoc?.kind === 'json' && this.activeDoc.activeMode === 'tree';
394
+ if (ev.name === 'escape' || ev.char === 'q' || ev.name === 'backspace') {
395
+ this.view = 'browser';
396
+ this.readerSearchQuery = '';
397
+ this.readerSearchMatches = [];
398
+ await this.refreshSelectedPreview();
399
+ this.draw();
400
+ return;
401
+ }
402
+ if (ev.char === '?') {
403
+ this.showHelp = true;
404
+ this.draw();
405
+ return;
406
+ }
407
+ if (ev.char === 't') {
408
+ this.themeName = nextTheme(this.themeName);
409
+ this.toastMessage = `Tema ativo: ${getTheme(this.themeName).label}`;
410
+ this.rerenderReaderDoc();
411
+ this.draw();
412
+ return;
413
+ }
414
+ if (ev.char === 'y') {
415
+ await this.copySelectedPath();
416
+ return;
417
+ }
418
+ if ((ev.char === 'E' || (ev.char === 'e' && !isJsonTree)) && this.activeFilePreview) {
419
+ await this.openFileInEditor(this.activeFilePreview.filePath, 'reader');
420
+ return;
421
+ }
422
+ if (ev.name === 'tab' && this.activeDoc && this.activeDoc.modes.length > 1) {
423
+ const idx = this.activeDoc.modes.indexOf(this.activeDoc.activeMode);
424
+ this.preferredMode = this.activeDoc.modes[(idx + 1) % this.activeDoc.modes.length];
425
+ this.readerScroll = 0;
426
+ this.readerCursor = 0;
427
+ this.rerenderReaderDoc();
428
+ this.toastMessage = `Modo: ${this.activeDoc?.badge ?? ''}`;
429
+ this.draw();
430
+ return;
431
+ }
432
+ if (ev.char === '/') {
433
+ this.promptKind = 'search';
434
+ this.promptInput = this.readerSearchQuery;
435
+ this.draw();
436
+ return;
437
+ }
438
+ if (ev.char === 'n' && this.readerSearchMatches.length > 0) {
439
+ this.readerSearchCursor = (this.readerSearchCursor + 1) % this.readerSearchMatches.length;
440
+ this.jumpToMatch(this.readerSearchCursor);
441
+ this.draw();
442
+ return;
443
+ }
444
+ if (ev.char === 'N' && this.readerSearchMatches.length > 0) {
445
+ this.readerSearchCursor =
446
+ (this.readerSearchCursor - 1 + this.readerSearchMatches.length) % this.readerSearchMatches.length;
447
+ this.jumpToMatch(this.readerSearchCursor);
448
+ this.draw();
449
+ return;
450
+ }
451
+ // Interações exclusivas da Árvore JSON (expandir/recolher)
452
+ if (isJsonTree && this.activeDoc) {
453
+ const row = this.activeDoc.jsonTreeRows[this.readerCursor];
454
+ if (ev.name === 'enter' || ev.name === 'space') {
455
+ if (row?.collapsible) {
456
+ if (this.collapsedJsonPaths.has(row.path))
457
+ this.collapsedJsonPaths.delete(row.path);
458
+ else
459
+ this.collapsedJsonPaths.add(row.path);
460
+ this.rerenderReaderDoc();
461
+ }
462
+ this.draw();
463
+ return;
464
+ }
465
+ if (ev.name === 'left' || ev.char === 'h') {
466
+ if (row?.collapsible && !row.collapsed) {
467
+ this.collapsedJsonPaths.add(row.path);
468
+ this.rerenderReaderDoc();
469
+ }
470
+ this.draw();
471
+ return;
472
+ }
473
+ if (ev.name === 'right' || ev.char === 'l') {
474
+ if (row?.collapsible && row.collapsed) {
475
+ this.collapsedJsonPaths.delete(row.path);
476
+ this.rerenderReaderDoc();
477
+ }
478
+ this.draw();
479
+ return;
480
+ }
481
+ if (ev.char === 'e') {
482
+ this.collapsedJsonPaths.clear();
483
+ this.rerenderReaderDoc();
484
+ this.toastMessage = 'Todos os nós JSON expandidos';
485
+ this.draw();
486
+ return;
487
+ }
488
+ if (ev.char === 'c' && this.activeFilePreview) {
489
+ try {
490
+ const parsed = JSON.parse(this.activeFilePreview.text);
491
+ const all = collectAllCollapsiblePaths(parsed).filter((p) => p !== '$');
492
+ this.collapsedJsonPaths = new Set(all);
493
+ this.readerCursor = 0;
494
+ this.readerScroll = 0;
495
+ this.rerenderReaderDoc();
496
+ this.toastMessage = 'Nós JSON recolhidos';
497
+ }
498
+ catch {
499
+ // Ignora se JSON inválido
500
+ }
501
+ this.draw();
502
+ return;
503
+ }
504
+ }
505
+ // Scroll & navegação vertical no leitor
506
+ const maxScroll = Math.max(0, totalLines - bodyHeight);
507
+ if (ev.name === 'up' || ev.char === 'k' || ev.name === 'wheel_up') {
508
+ if (isJsonTree) {
509
+ this.readerCursor = Math.max(0, this.readerCursor - 1);
510
+ if (this.readerCursor < this.readerScroll)
511
+ this.readerScroll = this.readerCursor;
512
+ }
513
+ else {
514
+ this.readerScroll = Math.max(0, this.readerScroll - (ev.name === 'wheel_up' ? 3 : 1));
515
+ }
516
+ }
517
+ else if (ev.name === 'down' || ev.char === 'j' || ev.name === 'wheel_down') {
518
+ if (isJsonTree) {
519
+ this.readerCursor = Math.min(Math.max(0, totalLines - 1), this.readerCursor + 1);
520
+ if (this.readerCursor >= this.readerScroll + bodyHeight) {
521
+ this.readerScroll = this.readerCursor - bodyHeight + 1;
522
+ }
523
+ }
524
+ else {
525
+ this.readerScroll = Math.min(maxScroll, this.readerScroll + (ev.name === 'wheel_down' ? 3 : 1));
526
+ }
527
+ }
528
+ else if (ev.name === 'pageup' || ev.char === 'b') {
529
+ const step = Math.max(4, bodyHeight - 2);
530
+ this.readerScroll = Math.max(0, this.readerScroll - step);
531
+ this.readerCursor = Math.max(0, this.readerCursor - step);
532
+ }
533
+ else if (ev.name === 'pagedown' || ev.name === 'space') {
534
+ const step = Math.max(4, bodyHeight - 2);
535
+ this.readerScroll = Math.min(maxScroll, this.readerScroll + step);
536
+ this.readerCursor = Math.min(Math.max(0, totalLines - 1), this.readerCursor + step);
537
+ }
538
+ else if (ev.name === 'home' || ev.char === 'g') {
539
+ this.readerScroll = 0;
540
+ this.readerCursor = 0;
541
+ }
542
+ else if (ev.name === 'end' || ev.char === 'G') {
543
+ this.readerScroll = maxScroll;
544
+ this.readerCursor = Math.max(0, totalLines - 1);
545
+ }
546
+ this.draw();
547
+ }
548
+ async copySelectedPath() {
549
+ const targetPath = this.view === 'reader'
550
+ ? (this.activeFilePreview?.filePath ?? this.currentDir)
551
+ : (this.currentEntries[this.selectedIndex]?.fullPath ?? this.currentDir);
552
+ const result = await copyTextToClipboard(targetPath);
553
+ if (result.ok) {
554
+ this.toastMessage = `Caminho copiado: ${stripUnsafeAnsi(targetPath)}`;
555
+ }
556
+ else {
557
+ this.toastMessage = `Falha ao copiar caminho: ${stripUnsafeAnsi(result.error ?? 'clipboard indisponível')}`;
558
+ }
559
+ this.draw();
560
+ }
561
+ async reloadDirectory(focusEntryName) {
562
+ const parentDir = path.dirname(this.currentDir);
563
+ const [parentRes, currentRes] = await Promise.all([
564
+ parentDir !== this.currentDir
565
+ ? readDirectoryEntries(parentDir, { showHidden: this.showHidden })
566
+ : Promise.resolve({ dirPath: parentDir, entries: [] }),
567
+ readDirectoryEntries(this.currentDir, { showHidden: this.showHidden, filter: this.filterQuery }),
568
+ ]);
569
+ this.parentEntries = parentRes.entries;
570
+ this.currentEntries = currentRes.entries;
571
+ if (focusEntryName) {
572
+ const idx = this.currentEntries.findIndex((e) => e.name === focusEntryName);
573
+ this.selectedIndex = idx >= 0 ? idx : 0;
574
+ }
575
+ else {
576
+ this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.currentEntries.length - 1));
577
+ }
578
+ await this.refreshSelectedPreview();
579
+ }
580
+ async refreshSelectedPreview() {
581
+ const entry = this.currentEntries[this.selectedIndex];
582
+ const theme = getTheme(this.themeName);
583
+ const { width, height } = this.screen.getSize();
584
+ const previewWidth = Math.max(24, Math.floor(width * 0.45) - 4);
585
+ if (!entry) {
586
+ this.previewBadge = 'VAZIO';
587
+ this.previewLines = [`${fg(theme.muted)}${ITALIC}(nenhum item selecionado)${RESET}`];
588
+ return;
589
+ }
590
+ if (entry.isDirectory) {
591
+ const sub = await readDirectoryEntries(entry.fullPath, { showHidden: this.showHidden });
592
+ this.previewBadge = 'DIR';
593
+ this.previewLines = renderDirectoryPreview(entry.fullPath, sub.entries, theme, sub.error);
594
+ return;
595
+ }
596
+ const preview = await safeReadFilePreview(entry.fullPath);
597
+ const doc = renderDocument(preview, {
598
+ width: previewWidth,
599
+ theme,
600
+ maxPreviewLines: Math.max(height + 20, 80),
601
+ });
602
+ this.previewBadge = doc.badge;
603
+ this.previewLines = doc.lines;
604
+ }
605
+ async openFileInReader(filePath) {
606
+ this.activeFilePreview = await safeReadFilePreview(filePath);
607
+ this.preferredMode = undefined;
608
+ this.collapsedJsonPaths.clear();
609
+ this.readerScroll = 0;
610
+ this.readerCursor = 0;
611
+ this.readerSearchQuery = '';
612
+ this.readerSearchMatches = [];
613
+ this.view = 'reader';
614
+ this.rerenderReaderDoc();
615
+ }
616
+ rerenderReaderDoc() {
617
+ if (!this.activeFilePreview)
618
+ return;
619
+ const { width } = this.screen.getSize();
620
+ const theme = getTheme(this.themeName);
621
+ this.activeDoc = renderDocument(this.activeFilePreview, {
622
+ width: Math.max(30, width - 4),
623
+ theme,
624
+ preferredMode: this.preferredMode,
625
+ collapsedJsonPaths: this.collapsedJsonPaths,
626
+ });
627
+ this.recomputeSearchMatches();
628
+ }
629
+ recomputeSearchMatches() {
630
+ this.readerSearchMatches = [];
631
+ if (!this.readerSearchQuery || !this.activeDoc)
632
+ return;
633
+ const theme = getTheme(this.themeName);
634
+ this.activeDoc.lines.forEach((line, idx) => {
635
+ if (highlightSearch(line, this.readerSearchQuery, theme.searchBg, theme.searchFg).matches > 0) {
636
+ this.readerSearchMatches.push(idx);
637
+ }
638
+ });
639
+ }
640
+ jumpToMatch(matchIdx) {
641
+ const lineNum = this.readerSearchMatches[matchIdx];
642
+ if (lineNum === undefined)
643
+ return;
644
+ const { height } = this.screen.getSize();
645
+ const bodyHeight = Math.max(4, height - 3);
646
+ this.readerCursor = lineNum;
647
+ this.readerScroll = Math.max(0, lineNum - Math.floor(bodyHeight / 3));
648
+ }
649
+ async openFileInEditor(filePath, returnTo) {
650
+ const preview = await safeReadFilePreview(filePath);
651
+ if (preview.error) {
652
+ this.toastMessage = preview.error;
653
+ this.draw();
654
+ return;
655
+ }
656
+ if (preview.isBinary) {
657
+ this.toastMessage = `Edição bloqueada: arquivo binário (${preview.magicLabel}).`;
658
+ this.draw();
659
+ return;
660
+ }
661
+ if (preview.truncated) {
662
+ this.toastMessage = 'Edição bloqueada: arquivo excede o limite seguro de 2 MB.';
663
+ this.draw();
664
+ return;
665
+ }
666
+ this.editorEngine = new VimEngine(preview.text);
667
+ this.editorFilePath = preview.filePath;
668
+ this.editorReturnView = returnTo;
669
+ this.editorViewport = { scrollY: 0, scrollX: 0 };
670
+ this.editorStatusMessage = `"${path.basename(preview.filePath)}" ${this.editorEngine.buffer.lines.length}L`;
671
+ this.editorStatusIsError = false;
672
+ this.editorSavedAny = false;
673
+ this.view = 'editor';
674
+ this.draw();
675
+ }
676
+ async handleEditorKey(ev) {
677
+ if (!this.editorEngine) {
678
+ this.view = this.editorReturnView;
679
+ this.draw();
680
+ return;
681
+ }
682
+ const { height } = this.screen.getSize();
683
+ const pageSize = Math.max(4, height - 2);
684
+ this.editorStatusMessage = '';
685
+ this.editorStatusIsError = false;
686
+ const action = this.editorEngine.handleKey(ev, pageSize);
687
+ if (action.message) {
688
+ this.editorStatusMessage = action.message;
689
+ this.editorStatusIsError = Boolean(action.isError);
690
+ }
691
+ if (action.type === 'save' || action.type === 'save-and-quit') {
692
+ try {
693
+ const text = this.editorEngine.buffer.toText();
694
+ const { bytes } = await safeWriteTextFile(this.editorFilePath, text);
695
+ this.editorEngine.buffer.dirty = false;
696
+ this.editorSavedAny = true;
697
+ this.editorStatusMessage = `"${path.basename(this.editorFilePath)}" ${this.editorEngine.buffer.lines.length}L, ${bytes}B salvos`;
698
+ this.editorStatusIsError = false;
699
+ if (action.type === 'save-and-quit') {
700
+ await this.closeEditor();
701
+ return;
702
+ }
703
+ }
704
+ catch (err) {
705
+ this.editorStatusMessage = `Erro ao salvar: ${err instanceof Error ? err.message : String(err)}`;
706
+ this.editorStatusIsError = true;
707
+ }
708
+ }
709
+ else if (action.type === 'quit' || action.type === 'force-quit') {
710
+ await this.closeEditor();
711
+ return;
712
+ }
713
+ this.draw();
714
+ }
715
+ async closeEditor() {
716
+ const returnTo = this.editorReturnView;
717
+ const savedPath = this.editorFilePath;
718
+ const didSave = this.editorSavedAny;
719
+ this.editorEngine = null;
720
+ this.editorFilePath = '';
721
+ this.editorStatusMessage = '';
722
+ this.editorStatusIsError = false;
723
+ this.view = returnTo;
724
+ if (returnTo === 'reader' && didSave && savedPath) {
725
+ await this.openFileInReader(savedPath);
726
+ this.toastMessage = `Salvo: ${path.basename(savedPath)}`;
727
+ }
728
+ else if (returnTo === 'browser') {
729
+ if (didSave) {
730
+ await this.reloadDirectory(path.basename(savedPath));
731
+ this.toastMessage = `Salvo: ${path.basename(savedPath)}`;
732
+ }
733
+ else {
734
+ await this.refreshSelectedPreview();
735
+ }
736
+ }
737
+ this.draw();
738
+ }
739
+ draw() {
740
+ const theme = getTheme(this.themeName);
741
+ const { width, height } = this.screen.getSize();
742
+ const lines = this.view === 'editor' && this.editorEngine
743
+ ? buildEditorFrame({
744
+ engine: this.editorEngine,
745
+ filePath: this.editorFilePath,
746
+ width,
747
+ height,
748
+ theme,
749
+ viewport: this.editorViewport,
750
+ statusMessage: this.editorStatusMessage,
751
+ statusIsError: this.editorStatusIsError,
752
+ })
753
+ : this.view === 'reader'
754
+ ? this.buildReaderFrame(width, height, theme)
755
+ : this.buildBrowserFrame(width, height, theme);
756
+ if (this.showHelp) {
757
+ this.overlayHelpModal(lines, width, height, theme);
758
+ }
759
+ this.screen.render(lines);
760
+ }
761
+ buildBrowserFrame(width, height, theme) {
762
+ const bodyHeight = Math.max(4, height - 2);
763
+ const useThreePanes = width >= 96;
764
+ const useTwoPanes = width >= 60 && !useThreePanes;
765
+ const parentW = useThreePanes ? Math.max(16, Math.floor(width * 0.2)) : 0;
766
+ const currentW = useThreePanes
767
+ ? Math.max(24, Math.floor(width * 0.34))
768
+ : useTwoPanes
769
+ ? Math.max(24, Math.floor(width * 0.44))
770
+ : width;
771
+ const previewW = Math.max(0, width - parentW - currentW - (useThreePanes ? 2 : useTwoPanes ? 1 : 0));
772
+ // Cabeçalho superior
773
+ const brand = `${bg(theme.headerBg)}${fg(theme.accent)}${BOLD} ◈ EXPLOREIO ${RESET}`;
774
+ const themePill = `${bg(theme.headerBg)}${fg(theme.muted)} [${theme.label}]${this.showHidden ? ' [.*]' : ''} ${RESET}`;
775
+ const pathMax = Math.max(10, width - visibleLength(brand) - visibleLength(themePill) - 2);
776
+ const headerPath = `${bg(theme.headerBg)}${fg(theme.headerFg)}${BOLD} ${truncateAnsi(stripUnsafeAnsi(this.currentDir), pathMax)} ${RESET}`;
777
+ const headerFill = `${bg(theme.headerBg)}${' '.repeat(Math.max(0, width - visibleLength(brand) - visibleLength(headerPath) - visibleLength(themePill)))}${RESET}`;
778
+ const headerLine = `${brand}${headerPath}${headerFill}${themePill}`;
779
+ // Mantém seleção centralizada/visível no painel atual
780
+ if (this.selectedIndex < this.listScroll)
781
+ this.listScroll = this.selectedIndex;
782
+ if (this.selectedIndex >= this.listScroll + bodyHeight) {
783
+ this.listScroll = this.selectedIndex - bodyHeight + 1;
784
+ }
785
+ const currentName = path.basename(this.currentDir);
786
+ const parentActiveIdx = this.parentEntries.findIndex((e) => e.name === currentName);
787
+ const parentScroll = Math.max(0, parentActiveIdx - Math.floor(bodyHeight / 2));
788
+ const sep = `${fg(theme.border)}│${RESET}`;
789
+ const rows = [headerLine];
790
+ for (let r = 0; r < bodyHeight; r++) {
791
+ let rowStr = '';
792
+ if (useThreePanes) {
793
+ const pEntry = this.parentEntries[parentScroll + r];
794
+ let pText = '';
795
+ if (pEntry) {
796
+ const isCur = pEntry.name === currentName;
797
+ const safePName = stripUnsafeAnsi(pEntry.name);
798
+ const prefix = pEntry.isDirectory ? '▸ ' : '· ';
799
+ pText = isCur
800
+ ? `${bg(theme.selectionBg)}${fg(theme.selectionFg)}${BOLD}${fitAnsi(`${prefix}${safePName}`, parentW)}${RESET}`
801
+ : `${fg(pEntry.isDirectory ? theme.dir : theme.muted)}${fitAnsi(`${prefix}${safePName}`, parentW)}${RESET}`;
802
+ }
803
+ else {
804
+ pText = ' '.repeat(parentW);
805
+ }
806
+ rowStr += `${pText}${sep}`;
807
+ }
808
+ // Painel central (diretório atual)
809
+ const cIdx = this.listScroll + r;
810
+ const cEntry = this.currentEntries[cIdx];
811
+ if (cEntry) {
812
+ const selected = cIdx === this.selectedIndex;
813
+ const sizeLabel = cEntry.isDirectory ? '/' : formatBytes(cEntry.size);
814
+ const badge = getFileBadge(cEntry, theme);
815
+ const nameBudget = Math.max(8, currentW - sizeLabel.length - 5);
816
+ const clippedName = truncateAnsi(stripUnsafeAnsi(cEntry.name), nameBudget);
817
+ if (selected) {
818
+ const inner = ` ▸ ${clippedName}${' '.repeat(Math.max(1, currentW - visibleLength(clippedName) - sizeLabel.length - 4))}${sizeLabel} `;
819
+ rowStr += `${bg(theme.selectionBg)}${fg(theme.selectionFg)}${BOLD}${fitAnsi(inner, currentW)}${RESET}`;
820
+ }
821
+ else {
822
+ const color = cEntry.isDirectory ? theme.dir : theme.text;
823
+ const left = ` ${badge} ${fg(color)}${clippedName}${RESET}`;
824
+ const pad = ' '.repeat(Math.max(1, currentW - visibleLength(left) - sizeLabel.length - 1));
825
+ rowStr += fitAnsi(`${left}${pad}${fg(theme.muted)}${DIM}${sizeLabel}${RESET} `, currentW);
826
+ }
827
+ }
828
+ else if (r === 0 && this.currentEntries.length === 0) {
829
+ rowStr += fitAnsi(` ${fg(theme.muted)}${ITALIC}(vazio)${RESET}`, currentW);
830
+ }
831
+ else {
832
+ rowStr += ' '.repeat(currentW);
833
+ }
834
+ // Painel direito (Preview rico ao vivo)
835
+ if (previewW > 0) {
836
+ const pLine = r === 0
837
+ ? `${fg(theme.accentAlt)}${BOLD} Preview${this.previewBadge ? ` · ${this.previewBadge}` : ''}${RESET}`
838
+ : ` ${this.previewLines[r - 1] ?? ''}`;
839
+ rowStr += `${sep}${fitAnsi(pLine, previewW)}`;
840
+ }
841
+ rows.push(rowStr);
842
+ }
843
+ rows.push(this.buildFooterBar(width, theme));
844
+ return rows;
845
+ }
846
+ buildReaderFrame(width, height, theme) {
847
+ const bodyHeight = Math.max(4, height - 2);
848
+ const doc = this.activeDoc;
849
+ const totalLines = doc?.lines.length ?? 0;
850
+ const isJsonTree = doc?.kind === 'json' && doc.activeMode === 'tree';
851
+ const pct = totalLines <= bodyHeight ? '100%' : `${Math.min(100, Math.round(((this.readerScroll + bodyHeight) / totalLines) * 100))}%`;
852
+ const fileName = this.activeFilePreview ? stripUnsafeAnsi(path.basename(this.activeFilePreview.filePath)) : '';
853
+ const left = `${bg(theme.headerBg)}${fg(theme.accent)}${BOLD} ◈ LEITOR ${RESET}${bg(theme.headerBg)}${fg(theme.headerFg)}${BOLD} ${fileName} ${RESET}`;
854
+ const right = `${bg(theme.headerBg)}${fg(theme.accentAlt)}${BOLD}[${doc?.badge ?? 'TEXT'}]${RESET}${bg(theme.headerBg)}${fg(theme.muted)} ${pct} · ${totalLines}L ${RESET}`;
855
+ const fill = `${bg(theme.headerBg)}${' '.repeat(Math.max(0, width - visibleLength(left) - visibleLength(right)))}${RESET}`;
856
+ const rows = [`${left}${fill}${right}`];
857
+ for (let r = 0; r < bodyHeight; r++) {
858
+ const idx = this.readerScroll + r;
859
+ let line = doc?.lines[idx] ?? '';
860
+ if (this.readerSearchQuery && line) {
861
+ line = highlightSearch(line, this.readerSearchQuery, theme.searchBg, theme.searchFg).text;
862
+ }
863
+ if (isJsonTree && idx === this.readerCursor && idx < totalLines) {
864
+ rows.push(`${bg(theme.selectionBg)}${fg(theme.selectionFg)}${fitAnsi(` ▸ ${line}`, width)}${RESET}`);
865
+ }
866
+ else {
867
+ rows.push(fitAnsi(` ${line}`, width));
868
+ }
869
+ }
870
+ rows.push(this.buildFooterBar(width, theme));
871
+ return rows;
872
+ }
873
+ buildFooterBar(width, theme) {
874
+ if (this.promptKind) {
875
+ const labels = {
876
+ filter: 'Filtrar arquivos: ',
877
+ search: 'Buscar no arquivo: ',
878
+ create: 'Criar arquivo ou pasta/ : ',
879
+ rename: 'Renomear para: ',
880
+ delete: `Excluir "${this.currentEntries[this.selectedIndex]?.name ?? ''}"? (y/N): `,
881
+ };
882
+ const text = ` ${labels[this.promptKind]}${this.promptInput}█`;
883
+ return `${bg(theme.selectionBg)}${fg(theme.selectionFg)}${BOLD}${fitAnsi(text, width)}${RESET}`;
884
+ }
885
+ if (this.toastMessage) {
886
+ return `${bg(theme.statusBg)}${fg(theme.warning)}${BOLD}${fitAnsi(` ◆ ${this.toastMessage}`, width)}${RESET}`;
887
+ }
888
+ if (this.view === 'reader') {
889
+ const isJsonTree = this.activeDoc?.kind === 'json' && this.activeDoc.activeMode === 'tree';
890
+ const hint = isJsonTree
891
+ ? ' Esc Voltar · ↑↓ Navegar · Enter/←→ Nó · e/c Tudo · E Vim · Tab Pretty · y Path · / Buscar · t Tema'
892
+ : ' Esc Voltar · e Editar (Vim) · ↑↓/PgUp/PgDn Rolar · Tab Modo · y Path · / Buscar · t Tema · ? Ajuda';
893
+ return `${bg(theme.statusBg)}${fg(theme.statusFg)}${fitAnsi(hint, width)}${RESET}`;
894
+ }
895
+ const pos = this.currentEntries.length > 0 ? `${this.selectedIndex + 1}/${this.currentEntries.length}` : '0/0';
896
+ const filterTag = this.filterQuery ? ` [filtro: ${this.filterQuery}]` : '';
897
+ const hint = ` ${pos}${filterTag} · Enter Ler · e Vim · ←→ Navegar · y Path · / Filtrar · . Ocultos · t Tema · a/r/d · ? Ajuda · q Sair`;
898
+ return `${bg(theme.statusBg)}${fg(theme.statusFg)}${fitAnsi(hint, width)}${RESET}`;
899
+ }
900
+ overlayHelpModal(lines, width, height, theme) {
901
+ const boxW = Math.min(78, width - 4);
902
+ const helpItems = [
903
+ ' NAVEGADOR (3 Painéis estilo Yazi)',
904
+ ' ↑/↓ ou j/k Mover seleção (roda do mouse suportada)',
905
+ ' Enter ou → / l Entrar na pasta ou ABRIR ARQUIVO NO LEITOR',
906
+ ' ← / h / Bksp Subir para diretório pai',
907
+ ' / ou f Filtrar arquivos (fuzzy)',
908
+ ' . Mostrar/ocultar arquivos ocultos',
909
+ ' y Copiar caminho selecionado (arquivo ou pasta)',
910
+ ' a / r / d Criar / Renomear / Excluir (com confirmação)',
911
+ '',
912
+ ' MODO LEITOR FULLSCREEN (Markdown · JSON · HTML · Código)',
913
+ ' Tab Alternar modo (Rendered↔Raw | Tree↔Pretty | Reader↔Source)',
914
+ ' Enter / ← / → Expandir/recolher nó no JSON Tree (e=tudo, c=recolher)',
915
+ ' / e n / N Buscar texto no arquivo e saltar ocorrências',
916
+ ' y Copiar caminho completo do arquivo aberto',
917
+ ' e (ou E no JSON) Abrir arquivo no EDITOR VIM NATIVO',
918
+ ' t Alternar tema (Midnight · Parchment Light · Nord)',
919
+ ' Esc ou q Voltar ao navegador (ou sair)',
920
+ '',
921
+ ' MODO EDITOR VIM (NORMAL · INSERT · VISUAL · COMMAND)',
922
+ ' i/I/a/A/o/O Entrar em INSERT (Esc volta para NORMAL)',
923
+ ' hjkl · w/b/e Navegar · 0/^/$ · gg/G · Ctrl+d/u · / Buscar (n/N)',
924
+ ' x · dd · yy · p Editar · v/V Visual (y/d/c) · u Undo · Ctrl+r Redo',
925
+ ' :w · :wq · :q! Salvar · Salvar e sair · Sair sem salvar · :<linha>',
926
+ ];
927
+ const startRow = Math.max(1, Math.floor((height - (helpItems.length + 4)) / 2));
928
+ const padLeft = ' '.repeat(Math.max(0, Math.floor((width - boxW) / 2)));
929
+ const innerW = boxW - 2;
930
+ const modalLines = [
931
+ `${padLeft}${fg(theme.borderActive)}${BOLD}╭${'─'.repeat(innerW)}╮${RESET}`,
932
+ `${padLeft}${fg(theme.borderActive)}${BOLD}│${bg(theme.headerBg)}${fg(theme.accent)}${fitAnsi(' ◈ EXPLOREIO — ATALHOS DE TECLADO (Esc/? para fechar)', innerW)}${RESET}${fg(theme.borderActive)}${BOLD}│${RESET}`,
933
+ ...helpItems.map((item) => `${padLeft}${fg(theme.borderActive)}│${bg(theme.statusBg)}${fg(item.startsWith(' NAVEGADOR') || item.startsWith(' MODO') ? theme.accentAlt : theme.text)}${fitAnsi(item, innerW)}${RESET}${fg(theme.borderActive)}│${RESET}`),
934
+ `${padLeft}${fg(theme.borderActive)}${BOLD}╰${'─'.repeat(innerW)}╯${RESET}`,
935
+ ];
936
+ modalLines.forEach((mLine, offset) => {
937
+ const targetRow = startRow + offset;
938
+ if (targetRow >= 0 && targetRow < lines.length) {
939
+ lines[targetRow] = mLine;
940
+ }
941
+ });
942
+ }
943
+ }
944
+ //# sourceMappingURL=app.js.map