-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathupdate.go
More file actions
1092 lines (993 loc) · 30.7 KB
/
update.go
File metadata and controls
1092 lines (993 loc) · 30.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tui
import (
"fmt"
"log"
"strings"
"github.com/charmbracelet/bubbles/key"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/gitxtui/gitx/internal/git"
zone "github.com/lrstanley/bubblezone"
)
var keys = DefaultKeyMap()
// commandExecutedMsg is sent after a git command has been run successfully.
type commandExecutedMsg struct {
cmdStr string
}
// panelContentUpdatedMsg is sent when new content for a panel has been fetched.
type panelContentUpdatedMsg struct {
panel Panel
content string
}
// mainContentUpdatedMsg is sent when the content for the main panel has been fetched.
type mainContentUpdatedMsg struct {
content string
}
// lineClickedMsg is sent when a user clicks on a line in a selectable panel.
type lineClickedMsg struct {
panel Panel
lineIndex int
}
// fileWatcherMsg is sent by the file watcher when the repository state changes.
type fileWatcherMsg struct{}
// errMsg is used to propagate errors back to the update loop.
type errMsg struct{ err error }
func (e errMsg) Error() string { return e.err.Error() }
// Update is the main message handler for the TUI. It processes user input,
// window events, and application-specific messages.
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch m.mode {
case modeInput:
return m.updateInput(msg)
case modeConfirm:
return m.updateConfirm(msg)
case modeCommit:
return m.updateCommit(msg)
}
var cmd tea.Cmd
var cmds []tea.Cmd
oldFocus := m.focusedPanel
switch msg := msg.(type) {
case commandExecutedMsg:
// A command was successful, add it to our history.
m.CommandHistory = append([]string{msg.cmdStr}, m.CommandHistory...)
// Update the history viewport content.
historyContent := strings.Join(m.CommandHistory, "\n\n")
m.panels[SecondaryPanel].content = historyContent
m.panels[SecondaryPanel].viewport.SetContent(historyContent)
m.panels[SecondaryPanel].viewport.GotoTop()
// Trigger a refresh of all
// relevant panels from this central location.
return m, tea.Batch(
m.fetchPanelContent(FilesPanel),
m.fetchPanelContent(CommitsPanel),
m.fetchPanelContent(BranchesPanel),
m.fetchPanelContent(StatusPanel),
)
case errMsg:
// You can improve this to show errors in the UI
log.Printf("error: %v", msg)
errorLine := m.theme.ErrorText.Render(msg.Error())
m.CommandHistory = append([]string{errorLine}, m.CommandHistory...)
// Update the history panel's content and scroll to the new error.
rawHistoryContent := strings.Join(m.CommandHistory, "\n\n")
contentWidth := m.panels[SecondaryPanel].viewport.Width
wrappedContent := lipgloss.NewStyle().Width(contentWidth).Render(rawHistoryContent)
m.panels[SecondaryPanel].content = wrappedContent
m.panels[SecondaryPanel].viewport.SetContent(wrappedContent)
m.panels[SecondaryPanel].viewport.GotoTop()
return m, tea.Batch(
m.fetchPanelContent(FilesPanel),
m.fetchPanelContent(CommitsPanel),
m.fetchPanelContent(BranchesPanel),
m.fetchPanelContent(StatusPanel),
)
case mainContentUpdatedMsg:
m.panels[MainPanel].content = msg.content
m.panels[MainPanel].viewport.SetContent(msg.content)
return m, nil
case panelContentUpdatedMsg:
var selectedPath string
// If the FilesPanel is being updated, try to find the path of the
// currently selected item to preserve the cursor position after the refresh.
if msg.panel == FilesPanel && m.panels[FilesPanel].cursor < len(m.panels[FilesPanel].lines) {
line := m.panels[FilesPanel].lines[m.panels[FilesPanel].cursor]
parts := strings.Split(line, "\t")
if len(parts) == 4 {
selectedPath = parts[3]
}
}
oldCursor := m.panels[msg.panel].cursor
if msg.panel == FilesPanel {
root := BuildTree(msg.content)
renderedTree := root.Render(m.theme)
m.panels[FilesPanel].lines = renderedTree
m.panels[FilesPanel].viewport.SetContent(strings.Join(renderedTree, "\n"))
// Restore the cursor to the previously selected file path.
newCursorPos := 0 // Default to top.
if selectedPath != "" {
for i, line := range renderedTree {
parts := strings.Split(line, "\t")
if len(parts) == 4 && parts[3] == selectedPath {
newCursorPos = i
break
}
}
}
m.panels[FilesPanel].cursor = newCursorPos
} else {
lines := strings.Split(msg.content, "\n")
m.panels[msg.panel].lines = lines
m.panels[msg.panel].viewport.SetContent(msg.content)
m.panels[msg.panel].content = msg.content
// Restore cursor by index for other, more stable panels.
if oldCursor < len(lines) {
m.panels[msg.panel].cursor = oldCursor
} else if len(lines) > 0 {
m.panels[msg.panel].cursor = len(lines) - 1
} else {
m.panels[msg.panel].cursor = 0
}
}
return m, m.updateMainPanel()
case fileWatcherMsg:
// When the repository changes, trigger a content refresh for all panels.
return m, tea.Batch(
m.fetchPanelContent(StatusPanel),
m.fetchPanelContent(FilesPanel),
m.fetchPanelContent(BranchesPanel),
m.fetchPanelContent(CommitsPanel),
m.fetchPanelContent(StashPanel),
)
case lineClickedMsg:
// Handle direct selection of a line via mouse click.
if msg.lineIndex < len(m.panels[msg.panel].lines) {
p := &m.panels[msg.panel]
p.cursor = msg.lineIndex
// Ensure the selected line is visible in the viewport.
if p.cursor < p.viewport.YOffset {
p.viewport.SetYOffset(p.cursor)
}
if p.cursor >= p.viewport.YOffset+p.viewport.Height {
p.viewport.SetYOffset(p.cursor - p.viewport.Height + 1)
}
}
m.activeSourcePanel = msg.panel
m.panels[MainPanel].viewport.GotoTop()
return m, m.updateMainPanel()
case tea.WindowSizeMsg:
m, cmd = m.handleWindowSizeMsg(msg)
cmds = append(cmds, cmd)
case tea.MouseMsg:
m, cmd = m.handleMouseMsg(msg)
cmds = append(cmds, cmd)
case tea.KeyMsg:
if m.showHelp {
switch {
case key.Matches(msg, keys.ToggleHelp):
m.toggleHelp()
return m, nil
case key.Matches(msg, keys.Escape):
m.toggleHelp()
return m, nil
default:
// Pass other keys to help viewport for scrolling
m.helpViewport, cmd = m.helpViewport.Update(msg)
return m, cmd
}
}
switch {
case key.Matches(msg, keys.Quit):
return m, tea.Quit
case key.Matches(msg, keys.Escape):
return m, nil
case key.Matches(msg, keys.ToggleHelp):
m.toggleHelp()
case key.Matches(msg, keys.SwitchTheme):
m.nextTheme()
case key.Matches(msg, keys.ToggleDiffView):
m.toggleDiffView()
cmd = m.updateMainPanel()
cmds = append(cmds, cmd)
case key.Matches(msg, keys.FocusNext), key.Matches(msg, keys.FocusPrev),
key.Matches(msg, keys.FocusZero), key.Matches(msg, keys.FocusOne),
key.Matches(msg, keys.FocusTwo), key.Matches(msg, keys.FocusThree),
key.Matches(msg, keys.FocusFour), key.Matches(msg, keys.FocusFive),
key.Matches(msg, keys.FocusSix):
m.handleFocusKeys(msg)
}
cmd = m.handlePanelKeys(msg)
if cmd != nil {
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}
}
if m.focusedPanel != oldFocus {
// When focus changes, reset scroll for the Stash and Secondary panels
if m.focusedPanel == StashPanel || m.focusedPanel == SecondaryPanel {
m.panels[m.focusedPanel].viewport.GotoTop()
}
// Update the active source panel and main panel content if the new focus is a source panel
if m.focusedPanel != MainPanel && m.focusedPanel != SecondaryPanel {
m.activeSourcePanel = m.focusedPanel
m.panels[MainPanel].viewport.GotoTop() // Reset main panel scroll on source change
cmd = m.updateMainPanel()
cmds = append(cmds, cmd)
}
m = m.recalculateLayout()
}
// The original viewport update logic for scrolling
m.panels[m.focusedPanel].viewport, cmd = m.panels[m.focusedPanel].viewport.Update(msg)
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
}
// updateInput handles updates when in text input mode.
func (m Model) updateInput(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyEnter:
val := m.textInput.Value()
cmd = m.inputCallback(val)
m.mode = modeNormal
m.textInput.Reset()
return m, cmd
case tea.KeyEsc:
m.mode = modeNormal
m.textInput.Reset()
return m, nil
}
}
m.textInput, cmd = m.textInput.Update(msg)
return m, cmd
}
// updateCommit handles updates when in commit message input mode.
func (m Model) updateCommit(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyEnter:
// Only submit if focused on title input
if m.textInput.Focused() {
title := m.textInput.Value()
description := m.descriptionInput.Value()
cmd = m.commitCallback(title, description)
m.mode = modeNormal
m.textInput.Reset()
m.descriptionInput.Reset()
return m, cmd
} else {
// If in description, allow newlines
m.descriptionInput, cmd = m.descriptionInput.Update(msg)
return m, cmd
}
case tea.KeyEsc:
m.mode = modeNormal
m.textInput.Reset()
m.descriptionInput.Reset()
return m, nil
case tea.KeyTab:
if m.textInput.Focused() {
m.textInput.Blur()
m.descriptionInput.Focus()
} else {
m.descriptionInput.Blur()
m.textInput.Focus()
}
return m, nil
}
}
if m.textInput.Focused() {
m.textInput, cmd = m.textInput.Update(msg)
} else {
m.descriptionInput, cmd = m.descriptionInput.Update(msg)
}
return m, cmd
}
// updateConfirm handles updates when in confirmation mode.
func (m Model) updateConfirm(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
switch strings.ToLower(msg.String()) {
case "y":
cmd = m.confirmCallback(true)
m.mode = modeNormal
return m, cmd
case "n", "esc":
cmd = m.confirmCallback(false)
m.mode = modeNormal
return m, cmd
}
}
return m, nil
}
// fetchPanelContent returns a command that fetches the content for a specific panel.
func (m Model) fetchPanelContent(panel Panel) tea.Cmd {
return func() tea.Msg {
var content, repoName, branchName string
var err error
switch panel {
case StatusPanel:
repoName, branchName, err = m.git.GetRepoInfo()
if err == nil {
repo := m.theme.BranchCurrent.Render(repoName)
branch := m.theme.BranchCurrent.Render(branchName)
content = fmt.Sprintf("%s → %s", repo, branch)
}
case FilesPanel:
content, err = m.git.GetStatus(git.StatusOptions{Porcelain: true})
case BranchesPanel:
var branchList []*git.Branch
branchList, err = m.git.GetBranches()
if err == nil {
var builder strings.Builder
for _, b := range branchList {
name := b.Name
if b.IsCurrent {
name = fmt.Sprintf("(*) → %s", b.Name)
}
line := fmt.Sprintf("%s\t%s", b.LastCommit, name)
builder.WriteString(line + "\n")
}
content = strings.TrimSpace(builder.String())
}
case CommitsPanel:
var logs []git.CommitLog
logs, err = m.git.GetCommitLogsGraph()
if err == nil {
var builder strings.Builder
for _, log := range logs {
var line string
if log.SHA != "" {
line = fmt.Sprintf("%s\t%s\t%s\t%s", log.Graph, log.SHA, log.AuthorInitials, log.Subject)
} else {
line = log.Graph
}
builder.WriteString(line + "\n")
}
content = strings.TrimSpace(builder.String())
}
case StashPanel:
var stashList []*git.Stash
stashList, err = m.git.GetStashes()
if err == nil {
if len(stashList) == 0 {
content = "No stashed changes."
} else {
var builder strings.Builder
for _, s := range stashList {
line := fmt.Sprintf("%s\t%s: %s", s.Name, s.Branch, s.Message)
builder.WriteString(line + "\n")
}
content = strings.TrimSpace(builder.String())
}
}
case SecondaryPanel:
if len(m.CommandHistory) == 0 {
content = "Command history will appear here..."
} else {
content = strings.Join(m.CommandHistory, "\n")
}
err = nil // Set err to nil as there's no operation that can fail here.
}
if err != nil {
content = "Error: " + err.Error()
}
return panelContentUpdatedMsg{panel: panel, content: content}
}
}
// updateMainPanel returns a command that fetches the content for the main panel
// based on the currently active source panel.
func (m *Model) updateMainPanel() tea.Cmd {
return func() tea.Msg {
var content string
var err error
switch m.activeSourcePanel {
case StatusPanel:
userName, _ := m.git.GetUserName()
url := m.theme.Hyperlink.Render(docsPage)
msgHeading := m.theme.WelcomeHeading.Render(asciiArt)
msgBody := fmt.Sprintf(welcomeMsg, m.theme.UserName.Render(userName), url)
content = fmt.Sprintf(msgHeading, m.theme.WelcomeMsg.Render(msgBody))
case FilesPanel:
if m.panels[FilesPanel].cursor < len(m.panels[FilesPanel].lines) {
line := m.panels[FilesPanel].lines[m.panels[FilesPanel].cursor]
parts := strings.Split(line, "\t")
if len(parts) == 4 {
status := parts[1]
path := parts[3] // Always use the full path from the 4th column
if path != "" {
if status == "" { // It's a directory
content, err = m.git.ShowDiff(git.DiffOptions{Color: true, Commit1: "HEAD", Commit2: path})
} else { // It's a file
stagedChanges := status[0] != ' ' && status[0] != '?'
unstagedChanges := status[1] != ' '
if stagedChanges {
content, err = m.git.ShowDiff(git.DiffOptions{Color: true, Cached: true, Commit1: path})
} else if unstagedChanges {
content, err = m.git.ShowDiff(git.DiffOptions{Color: true, Commit1: path})
} else if status == "??" {
content = "Untracked file: Stage to see content as a diff."
}
}
}
}
}
case BranchesPanel:
if m.panels[BranchesPanel].cursor < len(m.panels[BranchesPanel].lines) {
line := m.panels[BranchesPanel].lines[m.panels[BranchesPanel].cursor]
parts := strings.Split(line, "\t")
if len(parts) > 1 {
branchName := strings.TrimSpace(strings.TrimPrefix(parts[1], "(*) → "))
content, err = m.git.ShowLog(git.LogOptions{Graph: true, Color: "always", Branch: branchName})
}
}
case CommitsPanel:
if m.panels[CommitsPanel].cursor < len(m.panels[CommitsPanel].lines) {
line := m.panels[CommitsPanel].lines[m.panels[CommitsPanel].cursor]
parts := strings.Split(line, "\t")
if len(parts) >= 2 {
sha := parts[1]
content, err = m.git.ShowCommit(sha)
}
}
case StashPanel:
if len(m.panels[StashPanel].lines) == 1 && m.panels[StashPanel].lines[0] == "No stashed changes." {
content = "No stashed changes."
} else if m.panels[StashPanel].cursor < len(m.panels[StashPanel].lines) {
line := m.panels[StashPanel].lines[m.panels[StashPanel].cursor]
parts := strings.SplitN(line, "\t", 2)
if len(parts) > 0 {
stashID := parts[0]
content, _, err = m.git.Stash(git.StashOptions{Show: true, StashID: stashID})
}
}
}
if err != nil {
content = "Error: " + err.Error()
}
if content == "" {
content = "Select an item to see details."
}
// Apply adaptive visual styling: split-view for wide terminals, unified for narrow ones
// Calculate right panel width (approximately 65% of total width minus borders)
rightPanelWidth := int(float64(m.width)*(1-leftPanelWidthRatio)) - borderWidth - 2
content = renderAdaptiveDiffView(content, rightPanelWidth, m.theme, m.forcedDiffViewMode)
return mainContentUpdatedMsg{content: content}
}
}
// handleWindowSizeMsg recalculates the layout and resizes all viewports on window resize.
func (m Model) handleWindowSizeMsg(msg tea.WindowSizeMsg) (Model, tea.Cmd) {
m.width = msg.Width
m.height = msg.Height
m.help.Width = msg.Width
m.helpViewport.Width = int(float64(m.width) * helpViewWidthRatio)
m.helpViewport.Height = int(float64(m.height) * helpViewHeightRatio)
m = m.recalculateLayout()
return m, nil
}
// handleMouseMsg handles all mouse events, including clicks and scrolling.
func (m Model) handleMouseMsg(msg tea.MouseMsg) (Model, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
if m.showHelp {
if zone.Get("help-button").InBounds(msg) && msg.Action == tea.MouseActionRelease {
m.toggleHelp()
} else {
m.helpViewport, cmd = m.helpViewport.Update(msg)
cmds = append(cmds, cmd)
}
return m, tea.Batch(cmds...)
}
if msg.Action == tea.MouseActionRelease && msg.Button == tea.MouseButtonLeft {
if zone.Get("help-button").InBounds(msg) {
m.toggleHelp()
return m, nil
}
// Check for clicks on selectable lines first.
for p := range m.panels {
panel := Panel(p)
if panel != FilesPanel && panel != BranchesPanel && panel != CommitsPanel && panel != StashPanel {
continue
}
for i := 0; i < len(m.panels[panel].lines); i++ {
lineID := fmt.Sprintf("%s-line-%d", panel.ID(), i)
if zone.Get(lineID).InBounds(msg) {
m.focusedPanel = panel
return m, func() tea.Msg {
return lineClickedMsg{panel: panel, lineIndex: i}
}
}
}
}
// If no line was clicked, check for clicks on the panel itself to change focus.
for i := range m.panels {
if zone.Get(Panel(i).ID()).InBounds(msg) {
m.focusedPanel = Panel(i)
break
}
}
}
// Pass mouse events to the corresponding panel's viewport for scrolling.
for i := range m.panels {
panel := Panel(i)
if zone.Get(panel.ID()).InBounds(msg) {
m.panels[panel].viewport, cmd = m.panels[panel].viewport.Update(msg)
cmds = append(cmds, cmd)
break
}
}
return m, tea.Batch(cmds...)
}
// handlePanelKeys handles keybindings that are specific to the focused panel.
func (m *Model) handlePanelKeys(msg tea.KeyMsg) tea.Cmd {
switch m.focusedPanel {
case FilesPanel:
return m.handleFilesPanelKeys(msg)
case BranchesPanel:
return m.handleBranchesPanelKeys(msg)
case CommitsPanel:
return m.handleCommitsPanelKeys(msg)
case StashPanel:
return m.handleStashPanelKeys(msg)
}
return nil
}
// handleCursorMovement is a helper to handle up/down cursor movement in selectable panels.
// It returns true if the key was handled.
func (m *Model) handleCursorMovement(msg tea.KeyMsg) (bool, tea.Cmd) {
p := &m.panels[m.focusedPanel]
itemSelected := false
switch {
case key.Matches(msg, keys.Up):
if p.cursor > 0 {
p.cursor--
if p.cursor < p.viewport.YOffset {
p.viewport.SetYOffset(p.cursor)
}
itemSelected = true
}
case key.Matches(msg, keys.Down):
if p.cursor < len(p.lines)-1 {
p.cursor++
if p.cursor >= p.viewport.YOffset+p.viewport.Height {
p.viewport.SetYOffset(p.cursor - p.viewport.Height + 1)
}
itemSelected = true
}
}
if itemSelected {
m.panels[MainPanel].viewport.GotoTop()
return true, m.updateMainPanel()
}
return false, nil
}
func (m *Model) handleFilesPanelKeys(msg tea.KeyMsg) tea.Cmd {
if handled, cmd := m.handleCursorMovement(msg); handled {
return cmd
}
if m.panels[FilesPanel].cursor >= len(m.panels[FilesPanel].lines) {
return nil
}
line := m.panels[FilesPanel].lines[m.panels[FilesPanel].cursor]
parts := strings.Split(line, "\t")
if len(parts) < 4 {
return nil
}
status := parts[1]
filePath := parts[3]
switch {
case key.Matches(msg, keys.Commit):
m.mode = modeCommit
m.textInput.SetValue("")
m.descriptionInput.SetValue("")
m.textInput.Focus()
m.commitCallback = func(title, description string) tea.Cmd {
return func() tea.Msg {
commitMsg := title
if description != "" {
commitMsg = title + "\n\n" + description
}
_, cmdStr, err := m.git.Commit(git.CommitOptions{Message: commitMsg})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
}
}
case key.Matches(msg, keys.StageItem):
return tea.Batch(
func() tea.Msg {
var cmdStr string
var err error
if status[0] == ' ' || status[0] == '?' {
_, cmdStr, err = m.git.AddFiles([]string{filePath})
} else {
_, cmdStr, err = m.git.ResetFiles([]string{filePath})
}
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
m.fetchPanelContent(FilesPanel),
m.fetchPanelContent(StatusPanel),
)
case key.Matches(msg, keys.StageAll):
return tea.Batch(
func() tea.Msg {
_, cmdStr, err := m.git.AddFiles([]string{"."})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
m.fetchPanelContent(FilesPanel),
)
case key.Matches(msg, keys.Discard):
m.mode = modeConfirm
m.confirmMessage = fmt.Sprintf("Discard changes to %s?", filePath)
m.confirmCallback = func(confirmed bool) tea.Cmd {
m.mode = modeNormal
if !confirmed {
return nil
}
return func() tea.Msg {
_, cmdStr, err := m.git.Restore(git.RestoreOptions{
Paths: []string{filePath},
WorkingDir: true,
})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
}
}
case key.Matches(msg, keys.StashAll):
return tea.Batch(
func() tea.Msg {
_, cmdStr, err := m.git.StashAll()
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
m.fetchPanelContent(FilesPanel),
m.fetchPanelContent(StashPanel),
)
}
return nil
}
func (m *Model) handleBranchesPanelKeys(msg tea.KeyMsg) tea.Cmd {
if handled, cmd := m.handleCursorMovement(msg); handled {
return cmd
}
if m.panels[BranchesPanel].cursor >= len(m.panels[BranchesPanel].lines) {
return nil
}
line := m.panels[BranchesPanel].lines[m.panels[BranchesPanel].cursor]
parts := strings.Split(line, "\t")
if len(parts) < 2 {
return nil
}
branchName := strings.TrimSpace(strings.TrimPrefix(parts[1], "(*) → "))
switch {
case key.Matches(msg, keys.Checkout):
return tea.Batch(
func() tea.Msg {
_, cmdStr, err := m.git.Checkout(branchName)
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
m.fetchPanelContent(StatusPanel),
m.fetchPanelContent(BranchesPanel),
m.fetchPanelContent(CommitsPanel),
)
case key.Matches(msg, keys.NewBranch):
m.mode = modeInput
m.promptTitle = "New Branch Name"
m.textInput.SetValue("")
m.textInput.Focus()
m.inputCallback = func(input string) tea.Cmd {
m.mode = modeNormal
if input == "" {
return nil
}
return tea.Sequence(
func() tea.Msg {
_, cmdStr, err := m.git.ManageBranch(git.BranchOptions{Create: true, Name: input})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
func() tea.Msg {
_, cmdStr, err := m.git.Checkout(input)
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
)
}
case key.Matches(msg, keys.DeleteBranch):
m.mode = modeConfirm
m.confirmMessage = fmt.Sprintf("Delete branch %s?", branchName)
m.confirmCallback = func(confirmed bool) tea.Cmd {
m.mode = modeNormal
if !confirmed {
return nil
}
return func() tea.Msg {
_, cmdStr, err := m.git.ManageBranch(git.BranchOptions{Delete: true, Name: branchName})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
}
}
case key.Matches(msg, keys.RenameBranch):
m.mode = modeInput
m.promptTitle = "New Branch Name"
m.textInput.SetValue(branchName)
m.textInput.Focus()
m.inputCallback = func(input string) tea.Cmd {
m.mode = modeNormal
if input == "" || input == branchName {
return nil
}
return func() tea.Msg {
_, cmdStr, err := m.git.RenameBranch(branchName, input)
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
}
}
}
return nil
}
func (m *Model) handleCommitsPanelKeys(msg tea.KeyMsg) tea.Cmd {
if handled, cmd := m.handleCursorMovement(msg); handled {
return cmd
}
if m.panels[CommitsPanel].cursor >= len(m.panels[CommitsPanel].lines) {
return nil
}
line := m.panels[CommitsPanel].lines[m.panels[CommitsPanel].cursor]
parts := strings.Split(line, "\t")
if len(parts) < 2 {
return nil
}
sha := parts[1]
switch {
case key.Matches(msg, keys.AmendCommit):
m.mode = modeCommit
m.textInput.SetValue("")
m.descriptionInput.SetValue("")
m.textInput.Focus()
m.commitCallback = func(title, description string) tea.Cmd {
return func() tea.Msg {
commitMsg := title
if description != "" {
commitMsg = title + "\n\n" + description
}
_, cmdStr, err := m.git.Commit(git.CommitOptions{Message: commitMsg, Amend: true})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
}
}
case key.Matches(msg, keys.Revert):
m.mode = modeConfirm
m.confirmMessage = fmt.Sprintf("Revert commit %s?", sha)
m.confirmCallback = func(confirmed bool) tea.Cmd {
m.mode = modeNormal
if !confirmed {
return nil
}
return func() tea.Msg {
_, cmdStr, err := m.git.Revert(sha)
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
}
}
case key.Matches(msg, keys.ResetToCommit):
m.mode = modeConfirm
m.confirmMessage = fmt.Sprintf("Hard reset to commit %s? This will discard all changes!", sha)
m.confirmCallback = func(confirmed bool) tea.Cmd {
m.mode = modeNormal
if !confirmed {
return nil
}
return func() tea.Msg {
_, cmdStr, err := m.git.ResetToCommit(sha)
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
}
}
}
return nil
}
func (m *Model) handleStashPanelKeys(msg tea.KeyMsg) tea.Cmd {
if handled, cmd := m.handleCursorMovement(msg); handled {
return cmd
}
if m.panels[StashPanel].cursor >= len(m.panels[StashPanel].lines) {
return nil
}
line := m.panels[StashPanel].lines[m.panels[StashPanel].cursor]
parts := strings.SplitN(line, "\t", 2)
if len(parts) < 1 {
return nil
}
stashID := parts[0]
switch {
case key.Matches(msg, keys.StashApply):
return tea.Batch(
func() tea.Msg {
_, cmdStr, err := m.git.Stash(git.StashOptions{Apply: true, StashID: stashID})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
m.fetchPanelContent(FilesPanel),
m.fetchPanelContent(StashPanel),
)
case key.Matches(msg, keys.StashPop):
return tea.Batch(
func() tea.Msg {
_, cmdStr, err := m.git.Stash(git.StashOptions{Pop: true, StashID: stashID})
if err != nil {
return errMsg{err}
}
return commandExecutedMsg{cmdStr}
},
m.fetchPanelContent(FilesPanel),
m.fetchPanelContent(StashPanel),
)
case key.Matches(msg, keys.StashDrop):
m.mode = modeConfirm
m.confirmMessage = fmt.Sprintf("Drop stash %s?", stashID)
m.confirmCallback = func(confirmed bool) tea.Cmd {
m.mode = modeNormal
if !confirmed {
return nil
}
return func() tea.Msg {
_, cmdStr, err := m.git.Stash(git.StashOptions{Drop: true, StashID: stashID})
if err != nil {
return errMsg{err}
}
// Reset cursor if we deleted the last item
if m.panels[StashPanel].cursor >= len(m.panels[StashPanel].lines)-1 && m.panels[StashPanel].cursor > 0 {
m.panels[StashPanel].cursor--
}
return commandExecutedMsg{cmdStr}
}
}
}
return nil
}
// handleFocusKeys changes the focused panel based on keyboard shortcuts.
func (m *Model) handleFocusKeys(msg tea.KeyMsg) {
switch {
case key.Matches(msg, keys.FocusNext):
m.nextPanel()
case key.Matches(msg, keys.FocusPrev):
m.prevPanel()
case key.Matches(msg, keys.FocusZero):
m.focusedPanel = MainPanel
case key.Matches(msg, keys.FocusOne):
m.focusedPanel = StatusPanel
case key.Matches(msg, keys.FocusTwo):
m.focusedPanel = FilesPanel
case key.Matches(msg, keys.FocusThree):
m.focusedPanel = BranchesPanel
case key.Matches(msg, keys.FocusFour):
m.focusedPanel = CommitsPanel
case key.Matches(msg, keys.FocusFive):
m.focusedPanel = StashPanel
case key.Matches(msg, keys.FocusSix):
m.focusedPanel = SecondaryPanel
}
}
// recalculateLayout is the single source of truth for panel sizes and layout.
func (m Model) recalculateLayout() Model {
if m.width == 0 || m.height == 0 {
return m
}
contentHeight := m.height - 1 // Account for help bar