@leosdc/exploreio 0.4.0 → 0.6.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/dist/tui/app.js CHANGED
@@ -7,12 +7,15 @@
7
7
  import path from 'node:path';
8
8
  import { VimEngine } from '../editor/vimEngine.js';
9
9
  import { buildEditorFrame } from '../editor/vimView.js';
10
+ import { getGitSummaryBadge, gitCheckoutBranch, gitCommit, gitCreateBranch, gitDiscardFile, gitFetch, gitPull, gitPush, gitStageAll, gitStageFile, gitStashPop, gitStashPush, gitUnstageAll, gitUnstageFile, loadCommitDetails, loadFileDiff, loadGitHubData, loadGitPanelSnapshot, } from '../git/gitService.js';
11
+ import { buildGitHubListItems, buildGitPanelFrame, buildQuickActions, buildStatusListItems, formatGitHeaderBadge, } from '../git/gitView.js';
10
12
  import { createFileOrDir, deleteEntry, formatBytes, readDirectoryEntries, renameEntry, safeReadFilePreview, safeWriteTextFile, } from '../fs/explorer.js';
11
13
  import { collectAllCollapsiblePaths } from '../renderers/json.js';
12
14
  import { renderDirectoryPreview, renderDocument, } from '../renderers/index.js';
13
15
  import { bg, fg, getTheme, nextTheme } from '../themes/palette.js';
14
16
  import { BOLD, DIM, ITALIC, RESET, fitAnsi, highlightSearch, stripUnsafeAnsi, truncateAnsi, visibleLength } from './ansi.js';
15
17
  import { copyTextToClipboard } from './clipboard.js';
18
+ import { openInFullscreenShell } from './fullscreenLauncher.js';
16
19
  import { parseInputChunk } from './input.js';
17
20
  import { ScreenBuffer } from './screen.js';
18
21
  function getFileBadge(entry, theme) {
@@ -42,6 +45,8 @@ function getFileBadge(entry, theme) {
42
45
  }
43
46
  export class ExploreioApp {
44
47
  screen = new ScreenBuffer();
48
+ initialMode;
49
+ singleFile;
45
50
  themeName;
46
51
  view = 'browser';
47
52
  showHidden;
@@ -73,6 +78,28 @@ export class ExploreioApp {
73
78
  editorStatusMessage = '';
74
79
  editorStatusIsError = false;
75
80
  editorSavedAny = false;
81
+ // Painel Git & GitHub + Badge no navegador (SPEC-005)
82
+ gitSummary = null;
83
+ gitSummarySeq = 0;
84
+ gitSnapshot = null;
85
+ gitHubData = {
86
+ available: false,
87
+ loading: false,
88
+ repoSlug: null,
89
+ pullRequests: [],
90
+ issues: [],
91
+ workflowRuns: [],
92
+ };
93
+ gitTab = 'status';
94
+ gitSelectedIndex = 0;
95
+ gitListScroll = 0;
96
+ gitDetailTitle = '';
97
+ gitDetailLines = [];
98
+ gitDetailScroll = 0;
99
+ gitShowQuickPalette = false;
100
+ gitQuickPaletteIndex = 0;
101
+ gitBusyMessage = '';
102
+ gitPendingConfirm = null;
76
103
  // Prompt modal inline (barra inferior)
77
104
  promptKind = null;
78
105
  promptInput = '';
@@ -80,6 +107,8 @@ export class ExploreioApp {
80
107
  running = false;
81
108
  constructor(options) {
82
109
  this.currentDir = path.resolve(options.startDir);
110
+ this.initialMode = options.initialMode;
111
+ this.singleFile = Boolean(options.singleFile);
83
112
  this.themeName = options.themeName ?? 'midnight';
84
113
  this.showHidden = Boolean(options.showHidden);
85
114
  if (options.initialFile) {
@@ -113,7 +142,7 @@ export class ExploreioApp {
113
142
  const idx = this.currentEntries.findIndex((e) => e.fullPath === resolved);
114
143
  if (idx >= 0)
115
144
  this.selectedIndex = idx;
116
- await this.openFileInReader(resolved);
145
+ await this.openFileInReader(resolved, this.initialMode);
117
146
  }
118
147
  this.draw();
119
148
  }
@@ -166,6 +195,9 @@ export class ExploreioApp {
166
195
  if (this.view === 'editor') {
167
196
  await this.handleEditorKey(ev);
168
197
  }
198
+ else if (this.view === 'git') {
199
+ await this.handleGitKey(ev);
200
+ }
169
201
  else if (this.view === 'reader') {
170
202
  await this.handleReaderKey(ev);
171
203
  }
@@ -245,6 +277,22 @@ export class ExploreioApp {
245
277
  this.toastMessage = 'Exclusão cancelada.';
246
278
  }
247
279
  }
280
+ else if (kind === 'git-commit') {
281
+ await this.executeGitCommitPrompt(value);
282
+ }
283
+ else if (kind === 'git-branch-create') {
284
+ await this.executeGitCreateBranchPrompt(value);
285
+ }
286
+ else if (kind === 'git-confirm') {
287
+ const pending = this.gitPendingConfirm;
288
+ this.gitPendingConfirm = null;
289
+ if (pending && (value.trim().toLowerCase() === 'y' || value.trim().toLowerCase() === 's')) {
290
+ await pending.run();
291
+ }
292
+ else {
293
+ this.toastMessage = 'Operação Git cancelada.';
294
+ }
295
+ }
248
296
  this.draw();
249
297
  return;
250
298
  }
@@ -320,6 +368,21 @@ export class ExploreioApp {
320
368
  await this.copySelectedPath();
321
369
  return;
322
370
  }
371
+ if (ev.char === 'o' || ev.char === 'F') {
372
+ const entry = this.currentEntries[this.selectedIndex];
373
+ if (entry && !entry.isDirectory) {
374
+ await this.openInFullscreenTerminal(entry.fullPath);
375
+ }
376
+ else {
377
+ this.toastMessage = 'Selecione um arquivo para abrir em terminal tela cheia (o).';
378
+ this.draw();
379
+ }
380
+ return;
381
+ }
382
+ if (ev.name === 'tab' || (ev.ctrl && ev.name === 'g')) {
383
+ await this.openGitPanel();
384
+ return;
385
+ }
323
386
  if (ev.char === 'e') {
324
387
  const entry = this.currentEntries[this.selectedIndex];
325
388
  if (entry && !entry.isDirectory) {
@@ -392,6 +455,10 @@ export class ExploreioApp {
392
455
  const totalLines = this.activeDoc?.lines.length ?? 0;
393
456
  const isJsonTree = this.activeDoc?.kind === 'json' && this.activeDoc.activeMode === 'tree';
394
457
  if (ev.name === 'escape' || ev.char === 'q' || ev.name === 'backspace') {
458
+ if (this.singleFile) {
459
+ this.shutdown();
460
+ process.exit(0);
461
+ }
395
462
  this.view = 'browser';
396
463
  this.readerSearchQuery = '';
397
464
  this.readerSearchMatches = [];
@@ -415,6 +482,14 @@ export class ExploreioApp {
415
482
  await this.copySelectedPath();
416
483
  return;
417
484
  }
485
+ if ((ev.char === 'o' || ev.char === 'F') && this.activeFilePreview) {
486
+ await this.openInFullscreenTerminal(this.activeFilePreview.filePath, this.activeDoc?.activeMode);
487
+ return;
488
+ }
489
+ if (ev.ctrl && ev.name === 'g') {
490
+ await this.openGitPanel();
491
+ return;
492
+ }
418
493
  if ((ev.char === 'E' || (ev.char === 'e' && !isJsonTree)) && this.activeFilePreview) {
419
494
  await this.openFileInEditor(this.activeFilePreview.filePath, 'reader');
420
495
  return;
@@ -576,6 +651,7 @@ export class ExploreioApp {
576
651
  this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.currentEntries.length - 1));
577
652
  }
578
653
  await this.refreshSelectedPreview();
654
+ this.refreshGitHeaderSummary();
579
655
  }
580
656
  async refreshSelectedPreview() {
581
657
  const entry = this.currentEntries[this.selectedIndex];
@@ -602,9 +678,22 @@ export class ExploreioApp {
602
678
  this.previewBadge = doc.badge;
603
679
  this.previewLines = doc.lines;
604
680
  }
605
- async openFileInReader(filePath) {
681
+ async openInFullscreenTerminal(filePath, viewMode) {
682
+ const result = await openInFullscreenShell(filePath, {
683
+ themeName: this.themeName,
684
+ viewMode,
685
+ });
686
+ if (result.ok) {
687
+ this.toastMessage = `Aberto em terminal tela cheia: ${stripUnsafeAnsi(path.basename(filePath))}`;
688
+ }
689
+ else {
690
+ this.toastMessage = `Falha ao abrir tela cheia: ${stripUnsafeAnsi(result.error ?? 'terminal indisponível')}`;
691
+ }
692
+ this.draw();
693
+ }
694
+ async openFileInReader(filePath, initialMode) {
606
695
  this.activeFilePreview = await safeReadFilePreview(filePath);
607
- this.preferredMode = undefined;
696
+ this.preferredMode = initialMode;
608
697
  this.collapsedJsonPaths.clear();
609
698
  this.readerScroll = 0;
610
699
  this.readerCursor = 0;
@@ -750,9 +839,24 @@ export class ExploreioApp {
750
839
  statusMessage: this.editorStatusMessage,
751
840
  statusIsError: this.editorStatusIsError,
752
841
  })
753
- : this.view === 'reader'
754
- ? this.buildReaderFrame(width, height, theme)
755
- : this.buildBrowserFrame(width, height, theme);
842
+ : this.view === 'git' && this.gitSnapshot
843
+ ? buildGitPanelFrame({
844
+ snapshot: this.gitSnapshot,
845
+ github: this.gitHubData,
846
+ activeTab: this.gitTab,
847
+ selectedIndex: this.gitSelectedIndex,
848
+ listScroll: this.gitListScroll,
849
+ detailTitle: this.gitDetailTitle,
850
+ detailLines: this.gitDetailLines,
851
+ detailScroll: this.gitDetailScroll,
852
+ showQuickPalette: this.gitShowQuickPalette,
853
+ quickPaletteIndex: this.gitQuickPaletteIndex,
854
+ busyMessage: this.gitBusyMessage,
855
+ footerLine: this.buildFooterBar(width, theme),
856
+ }, width, height, theme)
857
+ : this.view === 'reader'
858
+ ? this.buildReaderFrame(width, height, theme)
859
+ : this.buildBrowserFrame(width, height, theme);
756
860
  if (this.showHelp) {
757
861
  this.overlayHelpModal(lines, width, height, theme);
758
862
  }
@@ -771,11 +875,12 @@ export class ExploreioApp {
771
875
  const previewW = Math.max(0, width - parentW - currentW - (useThreePanes ? 2 : useTwoPanes ? 1 : 0));
772
876
  // Cabeçalho superior
773
877
  const brand = `${bg(theme.headerBg)}${fg(theme.accent)}${BOLD} ◈ EXPLOREIO ${RESET}`;
878
+ const gitBadge = formatGitHeaderBadge(this.gitSummary, theme);
774
879
  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);
880
+ const pathMax = Math.max(10, width - visibleLength(brand) - visibleLength(gitBadge) - visibleLength(themePill) - 2);
776
881
  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}`;
882
+ const headerFill = `${bg(theme.headerBg)}${' '.repeat(Math.max(0, width - visibleLength(brand) - visibleLength(headerPath) - visibleLength(gitBadge) - visibleLength(themePill)))}${RESET}`;
883
+ const headerLine = `${brand}${headerPath}${headerFill}${gitBadge}${themePill}`;
779
884
  // Mantém seleção centralizada/visível no painel atual
780
885
  if (this.selectedIndex < this.listScroll)
781
886
  this.listScroll = this.selectedIndex;
@@ -878,6 +983,9 @@ export class ExploreioApp {
878
983
  create: 'Criar arquivo ou pasta/ : ',
879
984
  rename: 'Renomear para: ',
880
985
  delete: `Excluir "${this.currentEntries[this.selectedIndex]?.name ?? ''}"? (y/N): `,
986
+ 'git-commit': 'git commit -m : ',
987
+ 'git-branch-create': 'Nova branch (git checkout -b): ',
988
+ 'git-confirm': `${this.gitPendingConfirm?.label ?? 'Confirmar operação Git'}? (y/N): `,
881
989
  };
882
990
  const text = ` ${labels[this.promptKind]}${this.promptInput}█`;
883
991
  return `${bg(theme.selectionBg)}${fg(theme.selectionFg)}${BOLD}${fitAnsi(text, width)}${RESET}`;
@@ -887,14 +995,25 @@ export class ExploreioApp {
887
995
  }
888
996
  if (this.view === 'reader') {
889
997
  const isJsonTree = this.activeDoc?.kind === 'json' && this.activeDoc.activeMode === 'tree';
998
+ const exitLabel = this.singleFile ? 'Esc/q Fechar' : 'Esc Voltar';
890
999
  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';
1000
+ ? ` ${exitLabel} · ↑↓ Navegar · Enter/←→ Nó · e/c Tudo · o Tela cheia · E Vim · Tab Pretty · y Path · / Buscar · t Tema`
1001
+ : ` ${exitLabel} · o Tela cheia · e Vim · ↑↓/PgUp/PgDn Rolar · Tab Modo · y Path · / Buscar · t Tema · ? Ajuda`;
1002
+ return `${bg(theme.statusBg)}${fg(theme.statusFg)}${fitAnsi(hint, width)}${RESET}`;
1003
+ }
1004
+ if (this.view === 'git') {
1005
+ const hint = this.gitTab === 'status'
1006
+ ? ' Esc Voltar · 1-4/Tab Abas · ↑↓ Selecionar · J/K Rolar diff · s/Space Stage · S All · c Commit · p Pull · P Push · b Branch · ? Ações'
1007
+ : this.gitTab === 'graph'
1008
+ ? ' Esc Voltar · 1-4/Tab Abas · ↑↓ Commits · J/K Rolar show · y Copiar hash · p Pull · P Push · f Fetch · r Atualizar · ? Ações'
1009
+ : this.gitTab === 'branches'
1010
+ ? ' Esc Voltar · 1-4/Tab Abas · ↑↓ Branches · Enter Checkout · b +Branch · p Pull · P Push · f Fetch · ? Ações'
1011
+ : ' Esc Voltar · 1-4/Tab Abas · ↑↓ Itens · y/Enter Copiar URL · r Atualizar · t Tema · ? Ações';
893
1012
  return `${bg(theme.statusBg)}${fg(theme.statusFg)}${fitAnsi(hint, width)}${RESET}`;
894
1013
  }
895
1014
  const pos = this.currentEntries.length > 0 ? `${this.selectedIndex + 1}/${this.currentEntries.length}` : '0/0';
896
1015
  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`;
1016
+ const hint = ` ${pos}${filterTag} · Enter Ler · Tab/Ctrl+G Git · o Tela cheia · e Vim · ←→ Navegar · y Path · / Filtrar · t Tema · ? Ajuda · q Sair`;
898
1017
  return `${bg(theme.statusBg)}${fg(theme.statusFg)}${fitAnsi(hint, width)}${RESET}`;
899
1018
  }
900
1019
  overlayHelpModal(lines, width, height, theme) {
@@ -908,9 +1027,16 @@ export class ExploreioApp {
908
1027
  ' . Mostrar/ocultar arquivos ocultos',
909
1028
  ' y Copiar caminho selecionado (arquivo ou pasta)',
910
1029
  ' a / r / d Criar / Renomear / Excluir (com confirmação)',
1030
+ ' Tab ou Ctrl+G Abrir PAINEL GIT / GITHUB (status, árvore, branches, PRs)',
1031
+ '',
1032
+ ' PAINEL GIT / GITHUB (Tab ou Ctrl+G)',
1033
+ ' 1-4 ou Tab Alternar abas (Status/Parados · Árvore · Branches · GitHub)',
1034
+ ' s / S / c Stage/Unstage · Stage All · Commit com mensagem',
1035
+ ' p / P / f / b Pull · Push · Fetch · Criar nova branch (? abre paleta)',
911
1036
  '',
912
- ' MODO LEITOR FULLSCREEN (Markdown · JSON · HTML · Código)',
1037
+ ' MODO LEITOR FULLSCREEN (Markdown · Mermaid · JSON · HTML · Código)',
913
1038
  ' Tab Alternar modo (Rendered↔Raw | Tree↔Pretty | Reader↔Source)',
1039
+ ' o ou F Abrir arquivo em novo terminal TELA CHEIA (ideal p/ split)',
914
1040
  ' Enter / ← / → Expandir/recolher nó no JSON Tree (e=tudo, c=recolher)',
915
1041
  ' / e n / N Buscar texto no arquivo e saltar ocorrências',
916
1042
  ' y Copiar caminho completo do arquivo aberto',
@@ -940,5 +1066,643 @@ export class ExploreioApp {
940
1066
  }
941
1067
  });
942
1068
  }
1069
+ // ==================== PAINEL GIT & GITHUB (SPEC-005) ====================
1070
+ refreshGitHeaderSummary() {
1071
+ const seq = ++this.gitSummarySeq;
1072
+ const targetDir = this.currentDir;
1073
+ void getGitSummaryBadge(targetDir).then((summary) => {
1074
+ if (seq !== this.gitSummarySeq)
1075
+ return;
1076
+ this.gitSummary = summary;
1077
+ if (this.running && this.view === 'browser') {
1078
+ this.draw();
1079
+ }
1080
+ });
1081
+ }
1082
+ async openGitPanel() {
1083
+ this.view = 'git';
1084
+ this.gitShowQuickPalette = false;
1085
+ this.gitQuickPaletteIndex = 0;
1086
+ this.gitTab = 'status';
1087
+ this.gitSelectedIndex = 0;
1088
+ this.gitListScroll = 0;
1089
+ this.gitDetailScroll = 0;
1090
+ this.gitBusyMessage = 'Carregando repositório Git...';
1091
+ this.toastMessage = '';
1092
+ await this.refreshGitPanelData(true);
1093
+ }
1094
+ async refreshGitPanelData(reloadGitHub = false) {
1095
+ this.gitBusyMessage = 'Atualizando Git...';
1096
+ if (this.gitSnapshot)
1097
+ this.draw();
1098
+ const snap = await loadGitPanelSnapshot(this.currentDir);
1099
+ this.gitSnapshot = snap;
1100
+ this.gitBusyMessage = '';
1101
+ if (snap.isGitRepo) {
1102
+ this.gitSummary = {
1103
+ repoRoot: snap.repoRoot,
1104
+ branch: snap.status.branch,
1105
+ upstream: snap.status.upstream,
1106
+ ahead: snap.status.ahead,
1107
+ behind: snap.status.behind,
1108
+ stagedCount: snap.status.stagedCount,
1109
+ unstagedCount: snap.status.unstagedCount,
1110
+ untrackedCount: snap.status.untrackedCount,
1111
+ dirtyCount: snap.status.stagedCount +
1112
+ snap.status.unstagedCount +
1113
+ snap.status.untrackedCount +
1114
+ snap.status.conflictedCount,
1115
+ };
1116
+ }
1117
+ this.clampGitSelection(1);
1118
+ await this.refreshGitDetail();
1119
+ this.draw();
1120
+ if (reloadGitHub && snap.isGitRepo) {
1121
+ this.gitHubData = {
1122
+ available: false,
1123
+ loading: true,
1124
+ repoSlug: snap.githubRepo,
1125
+ pullRequests: [],
1126
+ issues: [],
1127
+ workflowRuns: [],
1128
+ };
1129
+ if (this.gitTab === 'github')
1130
+ this.draw();
1131
+ void loadGitHubData(snap.repoRoot, snap.githubRepo).then((ghData) => {
1132
+ this.gitHubData = ghData;
1133
+ if (this.running && this.view === 'git') {
1134
+ if (this.gitTab === 'github') {
1135
+ this.clampGitSelection(1);
1136
+ void this.refreshGitDetail().then(() => this.draw());
1137
+ }
1138
+ else {
1139
+ this.draw();
1140
+ }
1141
+ }
1142
+ });
1143
+ }
1144
+ }
1145
+ getGitTabListLength() {
1146
+ if (!this.gitSnapshot || !this.gitSnapshot.isGitRepo)
1147
+ return 0;
1148
+ if (this.gitTab === 'status')
1149
+ return buildStatusListItems(this.gitSnapshot).length;
1150
+ if (this.gitTab === 'graph')
1151
+ return this.gitSnapshot.commitGraph.length;
1152
+ if (this.gitTab === 'branches')
1153
+ return this.gitSnapshot.branches.length;
1154
+ return buildGitHubListItems(this.gitHubData).length;
1155
+ }
1156
+ isGitRowSelectable(index) {
1157
+ if (!this.gitSnapshot || !this.gitSnapshot.isGitRepo)
1158
+ return false;
1159
+ if (this.gitTab === 'status') {
1160
+ const item = buildStatusListItems(this.gitSnapshot)[index];
1161
+ return Boolean(item && item.kind !== 'header');
1162
+ }
1163
+ if (this.gitTab === 'graph') {
1164
+ const row = this.gitSnapshot.commitGraph[index];
1165
+ return Boolean(row && !row.isConnectorOnly);
1166
+ }
1167
+ if (this.gitTab === 'branches') {
1168
+ return Boolean(this.gitSnapshot.branches[index]);
1169
+ }
1170
+ const ghItem = buildGitHubListItems(this.gitHubData)[index];
1171
+ return Boolean(ghItem && ghItem.kind !== 'header');
1172
+ }
1173
+ clampGitSelection(direction = 1) {
1174
+ const len = this.getGitTabListLength();
1175
+ if (len === 0) {
1176
+ this.gitSelectedIndex = 0;
1177
+ this.gitListScroll = 0;
1178
+ return;
1179
+ }
1180
+ let idx = Math.max(0, Math.min(len - 1, this.gitSelectedIndex));
1181
+ if (!this.isGitRowSelectable(idx)) {
1182
+ let found = -1;
1183
+ for (let i = idx; i >= 0 && i < len; i += direction) {
1184
+ if (this.isGitRowSelectable(i)) {
1185
+ found = i;
1186
+ break;
1187
+ }
1188
+ }
1189
+ if (found === -1) {
1190
+ for (let i = idx; i >= 0 && i < len; i -= direction) {
1191
+ if (this.isGitRowSelectable(i)) {
1192
+ found = i;
1193
+ break;
1194
+ }
1195
+ }
1196
+ }
1197
+ idx = found >= 0 ? found : 0;
1198
+ }
1199
+ this.gitSelectedIndex = idx;
1200
+ const { height } = this.screen.getSize();
1201
+ const bodyHeight = Math.max(4, height - 3);
1202
+ if (this.gitSelectedIndex < this.gitListScroll) {
1203
+ this.gitListScroll = this.gitSelectedIndex;
1204
+ }
1205
+ else if (this.gitSelectedIndex >= this.gitListScroll + bodyHeight) {
1206
+ this.gitListScroll = this.gitSelectedIndex - bodyHeight + 1;
1207
+ }
1208
+ }
1209
+ moveGitSelection(delta) {
1210
+ const len = this.getGitTabListLength();
1211
+ if (len === 0)
1212
+ return;
1213
+ const dir = delta >= 0 ? 1 : -1;
1214
+ let next = this.gitSelectedIndex + delta;
1215
+ while (next >= 0 && next < len && !this.isGitRowSelectable(next)) {
1216
+ next += dir;
1217
+ }
1218
+ if (next >= 0 && next < len && this.isGitRowSelectable(next)) {
1219
+ this.gitSelectedIndex = next;
1220
+ }
1221
+ this.clampGitSelection(dir);
1222
+ }
1223
+ async refreshGitDetail() {
1224
+ this.gitDetailScroll = 0;
1225
+ const snap = this.gitSnapshot;
1226
+ if (!snap || !snap.isGitRepo) {
1227
+ this.gitDetailTitle = 'Git';
1228
+ this.gitDetailLines = [];
1229
+ return;
1230
+ }
1231
+ if (this.gitTab === 'status') {
1232
+ const item = buildStatusListItems(snap)[this.gitSelectedIndex];
1233
+ if (!item || item.kind === 'header') {
1234
+ this.gitDetailTitle = `Resumo · ${snap.githubRepo ?? snap.repoName}`;
1235
+ this.gitDetailLines = [
1236
+ `Branch: ${snap.status.branch}`,
1237
+ `Upstream: ${snap.status.upstream ?? '(nenhum — use P para publicar)'}`,
1238
+ `Commits parados (ahead): ${snap.unpushedCommits.length}`,
1239
+ `Commits atrás (behind): ${snap.status.behind}`,
1240
+ `Staged: ${snap.status.stagedCount} | Modificados: ${snap.status.unstagedCount} | Untracked: ${snap.status.untrackedCount}`,
1241
+ `Stashes: ${snap.stashCount}`,
1242
+ snap.remoteUrl ? `Remote: ${snap.remoteUrl}` : 'Remote: (nenhum)',
1243
+ '',
1244
+ 'Dica: pressione `?` para abrir a Paleta de Comandos Rápidos.',
1245
+ ];
1246
+ return;
1247
+ }
1248
+ if (item.kind === 'unpushed') {
1249
+ this.gitDetailTitle = `Commit Parado ↑ ${item.commit.shortHash}`;
1250
+ this.gitDetailLines = await loadCommitDetails(snap.repoRoot, item.commit.fullHash || item.commit.shortHash);
1251
+ return;
1252
+ }
1253
+ const sectionLabel = item.entry.section === 'staged'
1254
+ ? 'STAGED'
1255
+ : item.entry.section === 'untracked'
1256
+ ? 'NOVO'
1257
+ : 'DIFF';
1258
+ this.gitDetailTitle = `${sectionLabel} · ${item.entry.path}`;
1259
+ this.gitDetailLines = await loadFileDiff(snap.repoRoot, item.entry);
1260
+ return;
1261
+ }
1262
+ if (this.gitTab === 'graph') {
1263
+ const row = snap.commitGraph[this.gitSelectedIndex];
1264
+ if (!row || row.isConnectorOnly) {
1265
+ this.gitDetailTitle = 'Árvore de Commits';
1266
+ this.gitDetailLines = ['Selecione um commit para inspecionar o diff completo.'];
1267
+ return;
1268
+ }
1269
+ this.gitDetailTitle = `Commit ${row.shortHash}${row.isUnpushed ? ' (↑ parado)' : ''}`;
1270
+ this.gitDetailLines = await loadCommitDetails(snap.repoRoot, row.fullHash || row.shortHash);
1271
+ return;
1272
+ }
1273
+ if (this.gitTab === 'branches') {
1274
+ const br = snap.branches[this.gitSelectedIndex];
1275
+ if (!br) {
1276
+ this.gitDetailTitle = 'Branches';
1277
+ this.gitDetailLines = [];
1278
+ return;
1279
+ }
1280
+ this.gitDetailTitle = `Branch · ${br.name}`;
1281
+ this.gitDetailLines = [
1282
+ `Branch: ${br.name}${br.isCurrent ? ' (ATIVA)' : ''}`,
1283
+ `Tipo: ${br.isRemote ? 'Remota' : 'Local'}`,
1284
+ `Upstream: ${br.upstream || '(não configurado)'}`,
1285
+ `Status: ${br.track || 'sincronizada'}`,
1286
+ `Última atividade: ${br.relativeDate}`,
1287
+ `Último commit: ${br.subject}`,
1288
+ '',
1289
+ 'Atalhos nesta aba:',
1290
+ ' Enter -> git checkout <branch> (com confirmação)',
1291
+ ' b -> git checkout -b <nova-branch>',
1292
+ ' p / P -> git pull / git push',
1293
+ ' ? -> Paleta de comandos rápidos',
1294
+ ];
1295
+ return;
1296
+ }
1297
+ const ghItem = buildGitHubListItems(this.gitHubData)[this.gitSelectedIndex];
1298
+ if (!ghItem || ghItem.kind === 'header') {
1299
+ this.gitDetailTitle = `GitHub · ${this.gitHubData.repoSlug ?? ''}`;
1300
+ this.gitDetailLines = this.gitHubData.available
1301
+ ? [
1302
+ `Repositório: ${this.gitHubData.repoSlug}`,
1303
+ `Pull Requests abertos: ${this.gitHubData.pullRequests.length}`,
1304
+ `Issues abertas: ${this.gitHubData.issues.length}`,
1305
+ `Workflow Runs recentes: ${this.gitHubData.workflowRuns.length}`,
1306
+ ]
1307
+ : [this.gitHubData.reason ?? 'GitHub indisponível.'];
1308
+ return;
1309
+ }
1310
+ if (ghItem.kind === 'pr') {
1311
+ const pr = ghItem.pr;
1312
+ this.gitDetailTitle = `PR #${pr.number}`;
1313
+ this.gitDetailLines = [
1314
+ `#${pr.number} — ${pr.title}`,
1315
+ `Autor: @${pr.author}`,
1316
+ `Branches: ${pr.headRefName} → ${pr.baseRefName}`,
1317
+ `Status: ${pr.isDraft ? 'Draft' : 'Open'}${pr.reviewDecision ? ` · Review: ${pr.reviewDecision}` : ''}`,
1318
+ `Atualizado: ${pr.updatedAt}`,
1319
+ `URL: ${pr.url}`,
1320
+ '',
1321
+ 'Pressione Enter ou y para copiar a URL do PR.',
1322
+ ];
1323
+ return;
1324
+ }
1325
+ if (ghItem.kind === 'issue') {
1326
+ const issue = ghItem.issue;
1327
+ this.gitDetailTitle = `Issue #${issue.number}`;
1328
+ this.gitDetailLines = [
1329
+ `#${issue.number} — ${issue.title}`,
1330
+ `Autor: @${issue.author}`,
1331
+ `Labels: ${issue.labels.length > 0 ? issue.labels.join(', ') : '(nenhuma)'}`,
1332
+ `Atualizado: ${issue.updatedAt}`,
1333
+ `URL: ${issue.url}`,
1334
+ '',
1335
+ 'Pressione Enter ou y para copiar a URL da Issue.',
1336
+ ];
1337
+ return;
1338
+ }
1339
+ const run = ghItem.run;
1340
+ this.gitDetailTitle = `Action · ${run.workflowName}`;
1341
+ this.gitDetailLines = [
1342
+ `Workflow: ${run.workflowName}`,
1343
+ `Título: ${run.title}`,
1344
+ `Branch: ${run.branch}`,
1345
+ `Status: ${run.status} · Conclusão: ${run.conclusion || 'em andamento'}`,
1346
+ `Atualizado: ${run.updatedAt}`,
1347
+ `URL: ${run.url}`,
1348
+ '',
1349
+ 'Pressione Enter ou y para copiar a URL do Workflow Run.',
1350
+ ];
1351
+ }
1352
+ async handleGitKey(ev) {
1353
+ this.toastMessage = '';
1354
+ // Paleta interativa de comandos rápidos (`?`)
1355
+ if (this.gitShowQuickPalette && this.gitSnapshot) {
1356
+ const actions = buildQuickActions(this.gitSnapshot);
1357
+ if (ev.name === 'escape' || ev.char === '?' || ev.char === 'q') {
1358
+ this.gitShowQuickPalette = false;
1359
+ this.draw();
1360
+ return;
1361
+ }
1362
+ if (ev.name === 'up' || ev.char === 'k') {
1363
+ this.gitQuickPaletteIndex = (this.gitQuickPaletteIndex - 1 + actions.length) % actions.length;
1364
+ this.draw();
1365
+ return;
1366
+ }
1367
+ if (ev.name === 'down' || ev.char === 'j') {
1368
+ this.gitQuickPaletteIndex = (this.gitQuickPaletteIndex + 1) % actions.length;
1369
+ this.draw();
1370
+ return;
1371
+ }
1372
+ if (ev.name === 'enter') {
1373
+ const chosen = actions[this.gitQuickPaletteIndex];
1374
+ this.gitShowQuickPalette = false;
1375
+ if (chosen)
1376
+ await this.triggerGitQuickAction(chosen.id);
1377
+ this.draw();
1378
+ return;
1379
+ }
1380
+ if (ev.char && ev.char >= '1' && ev.char <= '9') {
1381
+ const chosen = actions.find((a) => a.hotkey === ev.char);
1382
+ this.gitShowQuickPalette = false;
1383
+ if (chosen)
1384
+ await this.triggerGitQuickAction(chosen.id);
1385
+ this.draw();
1386
+ return;
1387
+ }
1388
+ return;
1389
+ }
1390
+ if (ev.name === 'escape' || ev.char === 'q') {
1391
+ this.view = 'browser';
1392
+ await this.reloadDirectory();
1393
+ this.draw();
1394
+ return;
1395
+ }
1396
+ if (ev.char === 't') {
1397
+ this.themeName = nextTheme(this.themeName);
1398
+ this.toastMessage = `Tema ativo: ${getTheme(this.themeName).label}`;
1399
+ this.draw();
1400
+ return;
1401
+ }
1402
+ if (ev.char === '?' && this.gitSnapshot?.isGitRepo) {
1403
+ this.gitShowQuickPalette = true;
1404
+ this.gitQuickPaletteIndex = 0;
1405
+ this.draw();
1406
+ return;
1407
+ }
1408
+ if (!this.gitSnapshot?.isGitRepo) {
1409
+ this.draw();
1410
+ return;
1411
+ }
1412
+ // Troca de abas (1..4 ou Tab / Shift+Tab)
1413
+ const tabOrder = ['status', 'graph', 'branches', 'github'];
1414
+ if (ev.char === '1' || ev.char === '2' || ev.char === '3' || ev.char === '4') {
1415
+ const nextTab = tabOrder[Number(ev.char) - 1] ?? 'status';
1416
+ if (nextTab !== this.gitTab) {
1417
+ this.gitTab = nextTab;
1418
+ this.gitSelectedIndex = 0;
1419
+ this.gitListScroll = 0;
1420
+ this.clampGitSelection(1);
1421
+ await this.refreshGitDetail();
1422
+ }
1423
+ this.draw();
1424
+ return;
1425
+ }
1426
+ if (ev.name === 'tab') {
1427
+ const idx = tabOrder.indexOf(this.gitTab);
1428
+ const nextIdx = ev.shift ? (idx - 1 + tabOrder.length) % tabOrder.length : (idx + 1) % tabOrder.length;
1429
+ this.gitTab = tabOrder[nextIdx] ?? 'status';
1430
+ this.gitSelectedIndex = 0;
1431
+ this.gitListScroll = 0;
1432
+ this.clampGitSelection(1);
1433
+ await this.refreshGitDetail();
1434
+ this.draw();
1435
+ return;
1436
+ }
1437
+ // Navegação na lista
1438
+ if (ev.name === 'up' || ev.char === 'k' || ev.name === 'wheel_up') {
1439
+ this.moveGitSelection(-1);
1440
+ await this.refreshGitDetail();
1441
+ this.draw();
1442
+ return;
1443
+ }
1444
+ if (ev.name === 'down' || ev.char === 'j' || ev.name === 'wheel_down') {
1445
+ this.moveGitSelection(1);
1446
+ await this.refreshGitDetail();
1447
+ this.draw();
1448
+ return;
1449
+ }
1450
+ // Rolagem do painel direito (diff / detalhes)
1451
+ if (ev.char === 'J' || ev.name === 'pagedown') {
1452
+ this.gitDetailScroll = Math.min(Math.max(0, this.gitDetailLines.length - 5), this.gitDetailScroll + 8);
1453
+ this.draw();
1454
+ return;
1455
+ }
1456
+ if (ev.char === 'K' || ev.name === 'pageup') {
1457
+ this.gitDetailScroll = Math.max(0, this.gitDetailScroll - 8);
1458
+ this.draw();
1459
+ return;
1460
+ }
1461
+ // Ações rápidas diretas
1462
+ if (ev.char === 'r') {
1463
+ await this.refreshGitPanelData(true);
1464
+ this.toastMessage = 'Painel Git/GitHub atualizado.';
1465
+ this.draw();
1466
+ return;
1467
+ }
1468
+ if (ev.char === 'f') {
1469
+ await this.triggerGitQuickAction('fetch');
1470
+ return;
1471
+ }
1472
+ if (ev.char === 'p') {
1473
+ await this.triggerGitQuickAction('pull');
1474
+ return;
1475
+ }
1476
+ if (ev.char === 'P') {
1477
+ await this.triggerGitQuickAction('push');
1478
+ return;
1479
+ }
1480
+ if (ev.char === 'c') {
1481
+ await this.triggerGitQuickAction('commit');
1482
+ return;
1483
+ }
1484
+ if (ev.char === 'b') {
1485
+ await this.triggerGitQuickAction('create-branch');
1486
+ return;
1487
+ }
1488
+ if (ev.char === 'S') {
1489
+ await this.triggerGitQuickAction('stage-all');
1490
+ return;
1491
+ }
1492
+ if (ev.char === 'U') {
1493
+ const res = await gitUnstageAll(this.gitSnapshot.repoRoot);
1494
+ this.toastMessage = res.ok ? 'Todas as alterações removidas do stage.' : (res.errorMessage ?? 'Erro no unstage.');
1495
+ await this.refreshGitPanelData(false);
1496
+ return;
1497
+ }
1498
+ // Stage / Unstage individual na aba Status
1499
+ if ((ev.char === 's' || ev.name === 'space') && this.gitTab === 'status') {
1500
+ const item = buildStatusListItems(this.gitSnapshot)[this.gitSelectedIndex];
1501
+ if (item?.kind === 'file') {
1502
+ const res = item.entry.section === 'staged'
1503
+ ? await gitUnstageFile(this.gitSnapshot.repoRoot, item.entry.path)
1504
+ : await gitStageFile(this.gitSnapshot.repoRoot, item.entry.path);
1505
+ this.toastMessage = res.ok
1506
+ ? `${item.entry.section === 'staged' ? 'Unstaged' : 'Staged'}: ${item.entry.path}`
1507
+ : (res.errorMessage ?? 'Erro ao alterar stage.');
1508
+ await this.refreshGitPanelData(false);
1509
+ }
1510
+ return;
1511
+ }
1512
+ // Descartar alterações de um arquivo (com confirmação obrigatória)
1513
+ if (ev.char === 'x' && this.gitTab === 'status') {
1514
+ const item = buildStatusListItems(this.gitSnapshot)[this.gitSelectedIndex];
1515
+ if (item?.kind === 'file' && item.entry.section !== 'staged') {
1516
+ const entry = item.entry;
1517
+ const repoRoot = this.gitSnapshot.repoRoot;
1518
+ this.askGitConfirm(`Descartar alterações de "${entry.path}"`, async () => {
1519
+ const res = await gitDiscardFile(repoRoot, entry);
1520
+ this.toastMessage = res.ok ? `Descartado: ${entry.path}` : (res.errorMessage ?? 'Erro ao descartar.');
1521
+ await this.refreshGitPanelData(false);
1522
+ });
1523
+ }
1524
+ return;
1525
+ }
1526
+ // Copiar hash / path / branch / URL
1527
+ if (ev.char === 'y') {
1528
+ await this.copyActiveGitItem();
1529
+ return;
1530
+ }
1531
+ // Enter contextual por aba
1532
+ if (ev.name === 'enter') {
1533
+ if (this.gitTab === 'branches') {
1534
+ const br = this.gitSnapshot.branches[this.gitSelectedIndex];
1535
+ if (br && !br.isCurrent) {
1536
+ const repoRoot = this.gitSnapshot.repoRoot;
1537
+ this.askGitConfirm(`Trocar para branch "${br.name}" (git checkout)`, async () => {
1538
+ const res = await gitCheckoutBranch(repoRoot, br.name);
1539
+ this.toastMessage = res.ok ? `Branch ativa: ${br.name}` : (res.errorMessage ?? 'Erro no checkout.');
1540
+ await this.refreshGitPanelData(false);
1541
+ });
1542
+ }
1543
+ return;
1544
+ }
1545
+ if (this.gitTab === 'status') {
1546
+ const item = buildStatusListItems(this.gitSnapshot)[this.gitSelectedIndex];
1547
+ if (item?.kind === 'file') {
1548
+ const fullPath = path.resolve(this.gitSnapshot.repoRoot, item.entry.path);
1549
+ await this.openFileInReader(fullPath);
1550
+ this.draw();
1551
+ }
1552
+ return;
1553
+ }
1554
+ if (this.gitTab === 'github') {
1555
+ await this.copyActiveGitItem();
1556
+ }
1557
+ }
1558
+ }
1559
+ askGitConfirm(label, run) {
1560
+ this.gitPendingConfirm = { label, run };
1561
+ this.promptKind = 'git-confirm';
1562
+ this.promptInput = '';
1563
+ this.draw();
1564
+ }
1565
+ async triggerGitQuickAction(actionId) {
1566
+ const snap = this.gitSnapshot;
1567
+ if (!snap || !snap.isGitRepo)
1568
+ return;
1569
+ const repoRoot = snap.repoRoot;
1570
+ switch (actionId) {
1571
+ case 'pull':
1572
+ this.askGitConfirm(`Executar git pull --ff-only em "${snap.status.branch}"`, async () => {
1573
+ this.gitBusyMessage = 'Executando git pull...';
1574
+ this.draw();
1575
+ const res = await gitPull(repoRoot);
1576
+ this.gitBusyMessage = '';
1577
+ this.toastMessage = res.ok ? 'git pull concluído com sucesso.' : (res.errorMessage ?? 'Erro no git pull.');
1578
+ await this.refreshGitPanelData(true);
1579
+ });
1580
+ return;
1581
+ case 'push': {
1582
+ const noUpstream = !snap.status.upstream ? snap.status.branch : undefined;
1583
+ const cmdLabel = noUpstream ? `git push -u origin ${noUpstream}` : 'git push';
1584
+ this.askGitConfirm(`Executar ${cmdLabel}`, async () => {
1585
+ this.gitBusyMessage = `Executando ${cmdLabel}...`;
1586
+ this.draw();
1587
+ const res = await gitPush(repoRoot, noUpstream);
1588
+ this.gitBusyMessage = '';
1589
+ this.toastMessage = res.ok ? `${cmdLabel} concluído.` : (res.errorMessage ?? 'Erro no git push.');
1590
+ await this.refreshGitPanelData(true);
1591
+ });
1592
+ return;
1593
+ }
1594
+ case 'fetch':
1595
+ this.gitBusyMessage = 'Executando git fetch --all --prune...';
1596
+ this.draw();
1597
+ {
1598
+ const res = await gitFetch(repoRoot);
1599
+ this.gitBusyMessage = '';
1600
+ this.toastMessage = res.ok ? 'git fetch concluído.' : (res.errorMessage ?? 'Erro no git fetch.');
1601
+ await this.refreshGitPanelData(true);
1602
+ }
1603
+ return;
1604
+ case 'commit':
1605
+ if (snap.status.stagedCount === 0) {
1606
+ this.toastMessage = 'Nenhum arquivo em stage. Use `s` ou `S` (Stage All) antes de commitar.';
1607
+ this.draw();
1608
+ return;
1609
+ }
1610
+ this.promptKind = 'git-commit';
1611
+ this.promptInput = '';
1612
+ this.draw();
1613
+ return;
1614
+ case 'create-branch':
1615
+ this.promptKind = 'git-branch-create';
1616
+ this.promptInput = '';
1617
+ this.draw();
1618
+ return;
1619
+ case 'goto-branches':
1620
+ this.gitTab = 'branches';
1621
+ this.gitSelectedIndex = 0;
1622
+ this.gitListScroll = 0;
1623
+ this.clampGitSelection(1);
1624
+ await this.refreshGitDetail();
1625
+ this.draw();
1626
+ return;
1627
+ case 'stage-all': {
1628
+ const res = await gitStageAll(repoRoot);
1629
+ this.toastMessage = res.ok ? 'Todas as alterações adicionadas ao stage (git add -A).' : (res.errorMessage ?? 'Erro no stage.');
1630
+ await this.refreshGitPanelData(false);
1631
+ return;
1632
+ }
1633
+ case 'stash-push':
1634
+ this.askGitConfirm('Guardar alterações atuais com git stash push -u', async () => {
1635
+ const res = await gitStashPush(repoRoot);
1636
+ this.toastMessage = res.ok ? 'Alterações salvas no stash.' : (res.errorMessage ?? 'Erro no stash.');
1637
+ await this.refreshGitPanelData(false);
1638
+ });
1639
+ return;
1640
+ case 'stash-pop':
1641
+ this.askGitConfirm('Restaurar último stash (git stash pop)', async () => {
1642
+ const res = await gitStashPop(repoRoot);
1643
+ this.toastMessage = res.ok ? 'Último stash restaurado.' : (res.errorMessage ?? 'Erro no stash pop.');
1644
+ await this.refreshGitPanelData(false);
1645
+ });
1646
+ }
1647
+ }
1648
+ async executeGitCommitPrompt(message) {
1649
+ if (!this.gitSnapshot?.isGitRepo)
1650
+ return;
1651
+ const clean = message.trim();
1652
+ if (!clean) {
1653
+ this.toastMessage = 'Commit cancelado (mensagem vazia).';
1654
+ return;
1655
+ }
1656
+ const res = await gitCommit(this.gitSnapshot.repoRoot, clean);
1657
+ this.toastMessage = res.ok ? `Commit criado: ${clean}` : (res.errorMessage ?? 'Erro ao criar commit.');
1658
+ await this.refreshGitPanelData(false);
1659
+ }
1660
+ async executeGitCreateBranchPrompt(branchName) {
1661
+ if (!this.gitSnapshot?.isGitRepo)
1662
+ return;
1663
+ const clean = branchName.trim();
1664
+ if (!clean) {
1665
+ this.toastMessage = 'Criação de branch cancelada.';
1666
+ return;
1667
+ }
1668
+ const res = await gitCreateBranch(this.gitSnapshot.repoRoot, clean);
1669
+ this.toastMessage = res.ok ? `Branch criada e ativada: ${clean}` : (res.errorMessage ?? 'Erro ao criar branch.');
1670
+ await this.refreshGitPanelData(false);
1671
+ }
1672
+ async copyActiveGitItem() {
1673
+ const snap = this.gitSnapshot;
1674
+ if (!snap || !snap.isGitRepo)
1675
+ return;
1676
+ let value = '';
1677
+ if (this.gitTab === 'status') {
1678
+ const item = buildStatusListItems(snap)[this.gitSelectedIndex];
1679
+ if (item?.kind === 'unpushed')
1680
+ value = item.commit.shortHash;
1681
+ else if (item?.kind === 'file')
1682
+ value = path.resolve(snap.repoRoot, item.entry.path);
1683
+ }
1684
+ else if (this.gitTab === 'graph') {
1685
+ value = snap.commitGraph[this.gitSelectedIndex]?.shortHash ?? '';
1686
+ }
1687
+ else if (this.gitTab === 'branches') {
1688
+ value = snap.branches[this.gitSelectedIndex]?.name ?? '';
1689
+ }
1690
+ else {
1691
+ const item = buildGitHubListItems(this.gitHubData)[this.gitSelectedIndex];
1692
+ if (item?.kind === 'pr')
1693
+ value = item.pr.url;
1694
+ else if (item?.kind === 'issue')
1695
+ value = item.issue.url;
1696
+ else if (item?.kind === 'run')
1697
+ value = item.run.url;
1698
+ }
1699
+ if (!value)
1700
+ return;
1701
+ const res = await copyTextToClipboard(value);
1702
+ this.toastMessage = res.ok
1703
+ ? `Copiado: ${stripUnsafeAnsi(value)}`
1704
+ : `Falha ao copiar: ${stripUnsafeAnsi(res.error ?? 'clipboard indisponível')}`;
1705
+ this.draw();
1706
+ }
943
1707
  }
944
1708
  //# sourceMappingURL=app.js.map