Repository navigation
Expand file tree
/
Copy pathtui.go
More file actions
1071 lines (955 loc) · 26.1 KB
/
Copy pathtui.go
File metadata and controls
1071 lines (955 loc) · 26.1 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 main
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"image/color"
"io"
"net/http"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/eliukblau/pixterm/pkg/ansimage"
// pixterm registers png/jpeg/gif/webp/bmp/tiff decoders via blank imports.
// AVIF is intentionally not supported: the only pure-Go decoder
// (gen2brain/avif) ships a libdav1d WebAssembly blob that adds ~5 MiB to
// the binary.
)
const listLimit = 500
type tuiMode int
const (
modeBrowse tuiMode = iota
modeSearch
)
type focusedPane int
const (
paneList focusedPane = iota
paneDetail
)
type tabKind int
const (
tabRequest tabKind = iota
tabRespHeaders
tabRespBody
)
var tabLabels = []string{"Request", "Resp Headers", "Resp Body"}
type newSessionMsg struct{ id int64 }
type listResultMsg struct {
rows []SessionRow
filter filterSpec
}
type detailMsg struct {
id int64
session *Session
}
type sessionItem struct {
row SessionRow
}
func (s sessionItem) FilterValue() string { return s.row.URL() }
func (r SessionRow) URL() string {
return r.Scheme + "://" + r.Host + r.Path
}
type itemDelegate struct {
width int
}
func (d itemDelegate) Height() int { return 1 }
func (d itemDelegate) Spacing() int { return 0 }
func (d itemDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }
const (
colMethodW = 5
colStatusW = 4
colHostW = 22
colDurW = 7
colSep = 1 // one space between columns
)
func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
it, ok := listItem.(sessionItem)
if !ok {
return
}
r := it.row
statusStr := "—"
if r.Status != 0 {
statusStr = fmt.Sprintf("%d", r.Status)
} else if r.Err != "" {
statusStr = "ERR"
}
method := padRight(r.Method, colMethodW)
status := padRight(statusStr, colStatusW)
host := truncate(sanitizeLine(r.Host), colHostW)
path := sanitizeLine(r.Path)
if path == "" {
path = "/"
}
// 5 fixed cols + 4 separators
overhead := colMethodW + colStatusW + colHostW + colDurW + 4*colSep
available := d.width - overhead
if available < 8 {
available = 8
}
path = truncate(path, available)
dur := fmt.Sprintf("%dms", r.DurationMS)
dur = padRight(truncate(dur, colDurW), colDurW)
line := fmt.Sprintf("%s %s %s %s %s",
methodStyle(r.Method).Render(method),
statusStyle(r.Status, r.Err != "").Render(status),
padRight(host, colHostW),
padRight(path, available),
mutedStyle.Render(dur),
)
if index == m.Index() {
line = selectedRowStyle.Render(strings.TrimRight(line, " "))
}
fmt.Fprint(w, line)
}
var (
titleBarStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("230")).
Background(lipgloss.Color("62")).
Padding(0, 1)
paneBorderFocused = lipgloss.NewStyle().
Border(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("212"))
paneBorderBlurred = lipgloss.NewStyle().
Border(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240"))
statusBarStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("230")).
Background(lipgloss.Color("236")).
Padding(0, 1)
mutedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))
selectedRowStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("230")).
Background(lipgloss.Color("57")).
Bold(true)
detailHeader = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("212"))
detailDivider = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
tabActiveStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("230")).
Background(lipgloss.Color("57")).
Padding(0, 1)
tabInactiveStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("244")).
Background(lipgloss.Color("236")).
Padding(0, 1)
)
func methodStyle(method string) lipgloss.Style {
color := lipgloss.Color("244")
switch method {
case http.MethodGet:
color = lipgloss.Color("78")
case http.MethodPost:
color = lipgloss.Color("214")
case http.MethodPut, http.MethodPatch:
color = lipgloss.Color("221")
case http.MethodDelete:
color = lipgloss.Color("203")
case http.MethodConnect:
color = lipgloss.Color("147")
}
return lipgloss.NewStyle().Foreground(color).Bold(true)
}
func statusStyle(status int, hasErr bool) lipgloss.Style {
color := lipgloss.Color("244")
switch {
case hasErr:
color = lipgloss.Color("203")
case status >= 500:
color = lipgloss.Color("203")
case status >= 400:
color = lipgloss.Color("214")
case status >= 300:
color = lipgloss.Color("147")
case status >= 200:
color = lipgloss.Color("78")
}
return lipgloss.NewStyle().Foreground(color)
}
type rect struct{ x, y, w, h int }
func (r rect) contains(x, y int) bool {
return x >= r.x && x < r.x+r.w && y >= r.y && y < r.y+r.h
}
type tuiModel struct {
store *Store
events <-chan int64
port int
list list.Model
detail viewport.Model
search textinput.Model
mode tuiMode
focused focusedPane
activeTab tabKind
selID int64
selSession *Session
filter filterSpec
width int
height int
ready bool
// Layout regions computed in applyLayout, used for mouse hit testing.
listRegion rect
tabRegion rect
detailRegion rect
tabRanges []rect
}
func newTUIModel(store *Store, events <-chan int64, port int) tuiModel {
delegate := itemDelegate{width: 80}
l := list.New(nil, delegate, 0, 0)
l.SetShowHelp(false)
l.SetShowTitle(false)
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowPagination(false)
l.DisableQuitKeybindings()
ti := textinput.New()
ti.Placeholder = "filter: s:4xx m:POST h:api free text → FTS"
ti.Prompt = "/ "
ti.CharLimit = 256
vp := viewport.New(0, 0)
return tuiModel{
store: store,
events: events,
port: port,
list: l,
detail: vp,
search: ti,
mode: modeBrowse,
focused: paneList,
}
}
func (m tuiModel) Init() tea.Cmd {
return tea.Batch(
m.refreshListCmd(filterSpec{}),
m.waitForEventCmd(),
)
}
func (m tuiModel) waitForEventCmd() tea.Cmd {
return func() tea.Msg {
id, ok := <-m.events
if !ok {
return nil
}
return newSessionMsg{id: id}
}
}
func (m tuiModel) refreshListCmd(f filterSpec) tea.Cmd {
store := m.store
return func() tea.Msg {
rows, err := store.Search(f.ftsText, listLimit)
if err != nil {
return listResultMsg{rows: nil, filter: f}
}
rows = applyFilter(rows, f)
return listResultMsg{rows: rows, filter: f}
}
}
func (m tuiModel) loadDetailCmd(id int64) tea.Cmd {
store := m.store
return func() tea.Msg {
ses, err := store.Get(id)
if err != nil {
return detailMsg{id: id, session: nil}
}
return detailMsg{id: id, session: ses}
}
}
func (m tuiModel) clearCmd() tea.Cmd {
store := m.store
f := m.filter
return func() tea.Msg {
_ = store.Clear()
return listResultMsg{rows: nil, filter: f}
}
}
func (m *tuiModel) onListSelectionChanged() tea.Cmd {
if it, ok := m.list.SelectedItem().(sessionItem); ok {
if it.row.ID != m.selID {
m.selID = it.row.ID
return m.loadDetailCmd(m.selID)
}
}
return nil
}
// refreshDetailContent recomputes viewport content from the cached session +
// active tab. Called whenever the session loads or the user switches tabs.
func (m *tuiModel) refreshDetailContent() {
if m.selSession == nil {
m.detail.SetContent(mutedStyle.Render("(no session selected)"))
return
}
w, h := m.detail.Width, m.detail.Height
var content string
switch m.activeTab {
case tabRequest:
content = renderRequest(m.selSession, w, h)
case tabRespHeaders:
content = renderRespHeaders(m.selSession)
case tabRespBody:
content = renderRespBody(m.selSession, w, h)
}
m.detail.SetContent(content)
m.detail.GotoTop()
}
func (m tuiModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
m.ready = true
m = m.applyLayout()
m.refreshDetailContent()
return m, nil
case newSessionMsg:
cmds = append(cmds, m.waitForEventCmd(), m.refreshListCmd(m.filter))
return m, tea.Batch(cmds...)
case listResultMsg:
items := make([]list.Item, 0, len(msg.rows))
for _, r := range msg.rows {
items = append(items, sessionItem{row: r})
}
m.list.SetItems(items)
m.filter = msg.filter
if m.selID == 0 && len(items) > 0 {
m.selID = msg.rows[0].ID
cmds = append(cmds, m.loadDetailCmd(m.selID))
}
return m, tea.Batch(cmds...)
case detailMsg:
if msg.id == m.selID {
m.selSession = msg.session
m.refreshDetailContent()
}
return m, nil
case tea.MouseMsg:
return m.handleMouse(msg)
case tea.KeyMsg:
return m.handleKey(msg)
}
return m, nil
}
func (m tuiModel) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
// Search/filter mode swallows everything.
if m.mode == modeSearch {
switch msg.String() {
case "esc":
m.mode = modeBrowse
m.search.Blur()
m.search.SetValue("")
return m, m.refreshListCmd(filterSpec{})
case "enter":
m.mode = modeBrowse
m.search.Blur()
return m, nil
}
var cmd tea.Cmd
m.search, cmd = m.search.Update(msg)
return m, tea.Batch(cmd, m.refreshListCmd(parseFilter(m.search.Value())))
}
// Global keys (regardless of focused pane).
switch {
case key.Matches(msg, keyQuit):
return m, tea.Quit
case key.Matches(msg, keySearch):
m.mode = modeSearch
m.search.Focus()
return m, textinput.Blink
case key.Matches(msg, keyClear):
return m, m.clearCmd()
case key.Matches(msg, keyToggleFocus):
if m.focused == paneList {
m.focused = paneDetail
} else {
m.focused = paneList
}
return m, nil
}
// Per-pane keys.
switch m.focused {
case paneList:
switch {
case key.Matches(msg, keyDown):
m.list.CursorDown()
return m, m.onListSelectionChanged()
case key.Matches(msg, keyUp):
m.list.CursorUp()
return m, m.onListSelectionChanged()
case key.Matches(msg, keyPageDown):
for i := 0; i < 10; i++ {
m.list.CursorDown()
}
return m, m.onListSelectionChanged()
case key.Matches(msg, keyPageUp):
for i := 0; i < 10; i++ {
m.list.CursorUp()
}
return m, m.onListSelectionChanged()
}
case paneDetail:
switch {
case key.Matches(msg, keyDown):
m.detail.ScrollDown(1)
return m, nil
case key.Matches(msg, keyUp):
m.detail.ScrollUp(1)
return m, nil
case key.Matches(msg, keyPageDown):
m.detail.ScrollDown(m.detail.Height)
return m, nil
case key.Matches(msg, keyPageUp):
m.detail.ScrollUp(m.detail.Height)
return m, nil
case key.Matches(msg, keyTabPrev):
if m.activeTab > 0 {
m.activeTab--
m.refreshDetailContent()
}
return m, nil
case key.Matches(msg, keyTabNext):
if int(m.activeTab) < len(tabLabels)-1 {
m.activeTab++
m.refreshDetailContent()
}
return m, nil
}
}
return m, nil
}
func (m tuiModel) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
switch msg.Button {
case tea.MouseButtonWheelDown:
if m.detailRegion.contains(msg.X, msg.Y) {
m.detail.ScrollDown(3)
return m, nil
}
if m.listRegion.contains(msg.X, msg.Y) {
for i := 0; i < 3; i++ {
m.list.CursorDown()
}
return m, m.onListSelectionChanged()
}
case tea.MouseButtonWheelUp:
if m.detailRegion.contains(msg.X, msg.Y) {
m.detail.ScrollUp(3)
return m, nil
}
if m.listRegion.contains(msg.X, msg.Y) {
for i := 0; i < 3; i++ {
m.list.CursorUp()
}
return m, m.onListSelectionChanged()
}
case tea.MouseButtonLeft:
if msg.Action != tea.MouseActionPress {
return m, nil
}
// Tab bar click.
for i, r := range m.tabRanges {
if r.contains(msg.X, msg.Y) {
m.focused = paneDetail
m.activeTab = tabKind(i)
m.refreshDetailContent()
return m, nil
}
}
// Detail body click.
if m.detailRegion.contains(msg.X, msg.Y) {
m.focused = paneDetail
return m, nil
}
// List click — pick the row by Y offset.
if m.listRegion.contains(msg.X, msg.Y) {
m.focused = paneList
rel := msg.Y - m.listRegion.y
top := m.list.Paginator.Page * m.list.Paginator.PerPage
idx := top + rel
if idx >= 0 && idx < len(m.list.Items()) {
m.list.Select(idx)
return m, m.onListSelectionChanged()
}
}
}
return m, nil
}
func (m tuiModel) applyLayout() tuiModel {
if !m.ready {
return m
}
const chrome = 2 // title + bottom status
bodyH := m.height - chrome
if bodyH < 5 {
bodyH = 5
}
listW := m.width * 45 / 100
if listW < 30 {
listW = 30
}
detailW := m.width - listW
innerListW := listW - 2
if innerListW < 10 {
innerListW = 10
}
innerDetailW := detailW - 2
if innerDetailW < 10 {
innerDetailW = 10
}
innerH := bodyH - 2
if innerH < 1 {
innerH = 1
}
m.list.SetSize(innerListW, innerH)
m.list.SetDelegate(itemDelegate{width: innerListW})
// Right pane inner layout: 2 lines overview, 1 line tab bar, rest viewport.
const overviewH = 2
const tabBarH = 1
viewportH := innerH - overviewH - tabBarH
if viewportH < 1 {
viewportH = 1
}
m.detail.Width = innerDetailW
m.detail.Height = viewportH
m.search.Width = m.width - 4
// Compute mouse-hit regions in screen coordinates.
// Title bar is row 0; body starts at row 1.
// Pane border: 1 char around the inner content on each side.
leftBorderX := 0
leftInnerX := leftBorderX + 1
leftInnerY := 1 + 1 // title row + top border
m.listRegion = rect{x: leftInnerX, y: leftInnerY, w: innerListW, h: innerH}
rightBorderX := listW
rightInnerX := rightBorderX + 1
rightInnerY := leftInnerY
// Tab bar sits at the bottom of the overview area.
tabRowY := rightInnerY + overviewH
m.tabRegion = rect{x: rightInnerX, y: tabRowY, w: innerDetailW, h: tabBarH}
m.detailRegion = rect{x: rightInnerX, y: tabRowY + tabBarH, w: innerDetailW, h: viewportH}
// Per-tab x-ranges. Tab content rendered as " Label "; we compute the
// width of each label including the lipgloss padding.
m.tabRanges = m.tabRanges[:0]
x := rightInnerX
for _, label := range tabLabels {
w := lipgloss.Width(tabInactiveStyle.Render(label))
m.tabRanges = append(m.tabRanges, rect{x: x, y: tabRowY, w: w, h: tabBarH})
x += w
}
return m
}
func (m tuiModel) View() string {
if !m.ready {
return "Initializing…"
}
title := fmt.Sprintf("NetMiddler · :%d · %d sessions · focus: %s",
m.port, len(m.list.Items()), paneName(m.focused))
if summary := m.filter.summary(); summary != "" {
title += " · filter: " + summary
}
titleBar := titleBarStyle.Width(m.width).Render(truncate(title, m.width))
listW := m.width * 45 / 100
if listW < 30 {
listW = 30
}
detailW := m.width - listW
leftBorder := paneBorderBlurred
rightBorder := paneBorderBlurred
switch m.focused {
case paneList:
leftBorder = paneBorderFocused
case paneDetail:
rightBorder = paneBorderFocused
}
bodyH := m.height - 2
if bodyH < 5 {
bodyH = 5
}
innerH := bodyH - 2
leftPane := leftBorder.Width(listW - 2).Height(innerH).Render(m.list.View())
// Right pane content: overview (2 lines), tab bar (1 line), viewport.
innerDetailW := detailW - 2
overview := renderOverview(m.selSession, innerDetailW)
tabBar := renderTabBar(m.activeTab)
right := lipgloss.JoinVertical(lipgloss.Left, overview, tabBar, m.detail.View())
rightPane := rightBorder.Width(innerDetailW).Height(innerH).Render(right)
row := lipgloss.JoinHorizontal(lipgloss.Top, leftPane, rightPane)
var bottom string
if m.mode == modeSearch {
bottom = m.search.View()
} else {
help := "tab=switch pane · ↑/↓=within pane · ←/→=tab · / filter (s:4xx m:POST h:api free→FTS) · c clear · q quit"
bottom = mutedStyle.Render(help)
}
status := statusBarStyle.Width(m.width).Render(bottom)
return lipgloss.JoinVertical(lipgloss.Left, titleBar, row, status)
}
func paneName(p focusedPane) string {
if p == paneList {
return "list"
}
return "detail"
}
func renderTabBar(active tabKind) string {
parts := make([]string, 0, len(tabLabels))
for i, label := range tabLabels {
if tabKind(i) == active {
parts = append(parts, tabActiveStyle.Render(label))
} else {
parts = append(parts, tabInactiveStyle.Render(label))
}
}
return strings.Join(parts, "")
}
func renderOverview(s *Session, width int) string {
if s == nil {
return mutedStyle.Render(truncate("(no session selected)", width)) + "\n" +
mutedStyle.Render(strings.Repeat(" ", 0))
}
urlText := fmt.Sprintf("%s %s %s", s.Scheme, s.Method, sanitizeLine(s.URL))
urlText = truncate(urlText, width)
urlLine := detailHeader.Render(urlText)
var metaText string
if s.Err != "" {
metaText = fmt.Sprintf("captured %s · %d ms · error: %s",
s.TS.Format(time.RFC3339), s.DurationMS, sanitizeLine(s.Err))
} else {
metaText = fmt.Sprintf("captured %s · %d ms · %d %s",
s.TS.Format(time.RFC3339), s.DurationMS, s.Status, summaryStatus(s))
}
metaText = truncate(metaText, width)
meta := mutedStyle.Render(metaText)
return urlLine + "\n" + meta
}
func summaryStatus(s *Session) string {
if s.Status == 0 {
return "—"
}
return http.StatusText(s.Status)
}
func renderRequest(s *Session, width, height int) string {
var b strings.Builder
fmt.Fprintln(&b, detailHeader.Render("HEADERS"))
b.WriteString(sanitizeHeaders(s.ReqHeaders))
b.WriteString(detailDivider.Render(strings.Repeat("─", 40)))
b.WriteByte('\n')
fmt.Fprintln(&b, detailHeader.Render("BODY"))
if len(s.ReqBody) > 0 || s.ReqBodySize > 0 {
writeBody(&b, s.ReqBody, s.ReqBodySize, contentTypeFromHeaders(s.ReqHeaders), width, height)
} else {
fmt.Fprintln(&b, mutedStyle.Render("(no body)"))
}
return b.String()
}
func renderRespHeaders(s *Session) string {
var b strings.Builder
if s.Err != "" {
fmt.Fprintln(&b, detailHeader.Render("ERROR"))
fmt.Fprintln(&b, sanitizeLine(s.Err))
return b.String()
}
fmt.Fprintln(&b, detailHeader.Render("HEADERS"))
b.WriteString(sanitizeHeaders(s.RespHeaders))
return b.String()
}
func renderRespBody(s *Session, width, height int) string {
var b strings.Builder
if s.Err != "" {
fmt.Fprintln(&b, detailHeader.Render("ERROR"))
fmt.Fprintln(&b, sanitizeLine(s.Err))
return b.String()
}
if len(s.RespBody) == 0 && s.RespBodySize == 0 {
fmt.Fprintln(&b, mutedStyle.Render("(no body)"))
return b.String()
}
writeBody(&b, s.RespBody, s.RespBodySize, contentTypeFromHeaders(s.RespHeaders), width, height)
return b.String()
}
func writeBody(b *strings.Builder, body []byte, totalSize int64, contentType string, width, height int) {
if len(body) == 0 {
fmt.Fprintf(b, "%s\n", mutedStyle.Render(fmt.Sprintf("(empty, %d bytes original)", totalSize)))
return
}
// Try JSON pretty-print — applies to application/json and any */*+json
// variants. Falls through to plain-text rendering on parse failure (which
// also handles the truncated-body case).
if pretty, ok := tryPrettyJSON(body, contentType); ok {
ct := contentType
if ct == "" {
ct = "application/json"
}
fmt.Fprintf(b, "%s\n", mutedStyle.Render(
fmt.Sprintf("[json %s · %s of %s]",
ct, humanBytes(int64(len(body))), humanBytes(totalSize)),
))
b.WriteString(sanitizeText([]byte(pretty)))
if !strings.HasSuffix(pretty, "\n") {
b.WriteByte('\n')
}
if int64(len(body)) < totalSize {
fmt.Fprintf(b, "%s\n", mutedStyle.Render(
fmt.Sprintf("…[truncated: showing %s of %s]",
humanBytes(int64(len(body))), humanBytes(totalSize)),
))
}
return
}
// Try image render — applies to image/* content types we can decode.
if rendered, ok := tryRenderImage(body, contentType, width, height); ok {
ct := contentType
if ct == "" {
ct = http.DetectContentType(body)
}
fmt.Fprintf(b, "%s\n",
mutedStyle.Render(fmt.Sprintf("[image %s · %s]",
ct, humanBytes(totalSize))),
)
b.WriteString(rendered)
if !strings.HasSuffix(rendered, "\n") {
b.WriteByte('\n')
}
if int64(len(body)) < totalSize {
fmt.Fprintf(b, "%s\n", mutedStyle.Render(
fmt.Sprintf("…[body truncated: %s of %s captured]",
humanBytes(int64(len(body))), humanBytes(totalSize)),
))
}
return
}
if isBinaryBody(body, contentType) {
ct := contentType
if ct == "" {
ct = http.DetectContentType(body)
}
fmt.Fprintf(b, "%s\n",
mutedStyle.Render(fmt.Sprintf("[binary %s · %s of %s]",
ct, humanBytes(int64(len(body))), humanBytes(totalSize))),
)
const hexLimit = 512
dump := body
if len(dump) > hexLimit {
dump = dump[:hexLimit]
}
b.WriteString(hex.Dump(dump))
if len(body) > hexLimit {
fmt.Fprintf(b, "%s\n",
mutedStyle.Render(fmt.Sprintf("…[hex dump truncated to first %d bytes]", hexLimit)),
)
}
return
}
b.WriteString(sanitizeText(body))
if !strings.HasSuffix(string(body), "\n") {
b.WriteByte('\n')
}
if int64(len(body)) < totalSize {
fmt.Fprintf(b, "%s\n", mutedStyle.Render(
fmt.Sprintf("…[truncated: showing %s of %s]",
humanBytes(int64(len(body))), humanBytes(totalSize)),
))
}
}
// tryPrettyJSON returns the indented form of body when the Content-Type is
// application/json or any */*+json variant (e.g., application/ld+json) and
// the body parses cleanly. Bodies truncated by our 1 MiB cap will usually
// fail to parse — the caller falls back to plain-text rendering in that
// case, which is the correct behavior.
func tryPrettyJSON(body []byte, contentType string) (string, bool) {
ct := strings.ToLower(strings.TrimSpace(contentType))
if i := strings.Index(ct, ";"); i >= 0 {
ct = strings.TrimSpace(ct[:i])
}
if ct != "application/json" && !strings.HasSuffix(ct, "+json") {
return "", false
}
if len(bytes.TrimSpace(body)) == 0 {
return "", false
}
var pretty bytes.Buffer
if err := json.Indent(&pretty, body, "", " "); err != nil {
return "", false
}
return pretty.String(), true
}
// imageContentTypes lists Content-Type prefixes pixterm can decode.
var imageContentTypes = []string{
"image/png",
"image/jpeg", "image/jpg",
"image/gif",
"image/webp",
"image/bmp",
"image/tiff",
}
func looksLikeImage(body []byte, contentType string) bool {
ct := strings.ToLower(strings.TrimSpace(contentType))
if i := strings.Index(ct, ";"); i >= 0 {
ct = strings.TrimSpace(ct[:i])
}
if ct == "" {
ct = http.DetectContentType(body)
if i := strings.Index(ct, ";"); i >= 0 {
ct = strings.TrimSpace(ct[:i])
}
}
for _, prefix := range imageContentTypes {
if ct == prefix {
return true
}
}
return false
}
// tryRenderImage decodes body as an image (if its Content-Type is one we
// support) and returns a pixterm half-block ANSI rendering scaled to fit
// width × height terminal cells. Returns ("", false) if the body isn't
// a supported image, decoding fails, or the viewport is too small.
func tryRenderImage(body []byte, contentType string, width, height int) (string, bool) {
if !looksLikeImage(body, contentType) {
return "", false
}
if width < 10 || height < 4 {
return "", false
}
// Reserve 2 rows for the "[image ...]" label and trailing truncation note.
imgRows := height - 2
if imgRows < 2 {
imgRows = height
}
img, err := ansimage.NewScaledFromReader(
bytes.NewReader(body),
imgRows*2, // pixel rows; half-block packs 2 px per terminal cell
width,
color.Transparent,
ansimage.ScaleModeFit,
ansimage.NoDithering,
)
if err != nil {
return "", false
}
return img.Render(), true
}
var (
ansiEscapeRE = regexp.MustCompile(`\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)|[@-Z\\-_])`)
contentTypeRE = regexp.MustCompile(`(?im)^content-type:\s*([^\r\n]+)`)
)
var binaryContentTypes = []string{
"image/", "video/", "audio/", "font/",
"application/octet-stream",
"application/pdf",
"application/zip", "application/gzip", "application/x-gzip",
"application/x-tar", "application/x-bzip", "application/x-bzip2",
"application/x-7z-compressed", "application/x-rar-compressed",
"application/wasm",
"application/x-protobuf", "application/protobuf",
"application/grpc",
}
func isBinaryBody(body []byte, contentType string) bool {
ct := strings.ToLower(strings.TrimSpace(contentType))
for _, prefix := range binaryContentTypes {
if strings.HasPrefix(ct, prefix) {
return true
}
}
probe := body
if len(probe) > 8192 {
probe = probe[:8192]
}
for _, c := range probe {
if c == 0x00 {
return true
}
}
if len(probe) > 0 && !utf8.Valid(probe) {
return true
}
return false
}
func contentTypeFromHeaders(raw string) string {
m := contentTypeRE.FindStringSubmatch(raw)
if len(m) < 2 {
return ""
}
v := m[1]
if i := strings.Index(v, ";"); i >= 0 {
v = v[:i]
}
return strings.TrimSpace(v)
}
func sanitizeText(b []byte) string {
s := ansiEscapeRE.ReplaceAllString(string(b), "")
var out strings.Builder
out.Grow(len(s))
for _, r := range s {
switch {