-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtui_model.go
More file actions
968 lines (846 loc) · 26.7 KB
/
Copy pathtui_model.go
File metadata and controls
968 lines (846 loc) · 26.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
package main
import (
"fmt"
"os"
"runtime"
"sort"
"strings"
"sync"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// ── Export constants ──────────────────────────────────────────────────────────
type exportFmt struct {
label string
value string
}
var (
exportFmts = []exportFmt{
{"graphml", "graphml"},
{"dot", "dot"},
{"json2xml", "graphml_json2xml"},
}
exportDepthPresets = []string{"", "1", "2", "3", "5", "10"} // "" means -1 (all)
)
// ── Messages ──────────────────────────────────────────────────────────────────
type vertexInfoMsg struct {
id string
gen int
fvi *fullVertexInfo
err error
}
type linksLoadedMsg struct {
id string
gen int
links []displayLink
partialErr error
}
type queryResultMsg struct {
gen int
results []string
err error
}
type depth2TypesMsg struct {
gen int
outTypes []string
inTypes []string
}
type exportResultMsg struct {
gen int
file string
err error
}
// ── displayLink ───────────────────────────────────────────────────────────────
type displayLink struct {
info fullLinkInfo
isOut bool
}
func (dl displayLink) target() string {
if dl.isOut {
return dl.info.to
}
return dl.info.id.from
}
func (dl displayLink) label() string {
return dl.info.id.name
}
// ── Grouped view ──────────────────────────────────────────────────────────────
type flatItemKind int
const (
flatTypeGroup flatItemKind = iota // type-group header — Tab collapses
flatLink // individual link row — Enter navigates
)
type flatItem struct {
kind flatItemKind
groupIdx int // index in the corresponding groups slice
linkIdx int // flatLink only: index within group.links
}
type linkGroup struct {
tp string
links []displayLink
collapsed bool
}
type groupedView struct {
outGroups []linkGroup
inGroups []linkGroup
outFlat []flatItem // navigable rows for the right (outgoing) panel
inFlat []flatItem // navigable rows for the left (incoming) panel
}
func buildGroupedView(links []displayLink, searchQuery string) groupedView {
outByType := map[string][]displayLink{}
inByType := map[string][]displayLink{}
for _, dl := range links {
tp := dl.info.tp
if tp == "" {
tp = "(no type)"
}
if dl.isOut {
outByType[tp] = append(outByType[tp], dl)
} else {
inByType[tp] = append(inByType[tp], dl)
}
}
buildGroups := func(byType map[string][]displayLink) []linkGroup {
types := make([]string, 0, len(byType))
for k := range byType {
types = append(types, k)
}
sort.Strings(types)
groups := make([]linkGroup, 0, len(types))
for _, tp := range types {
ls := byType[tp]
sort.Slice(ls, func(i, j int) bool {
return ls[i].info.id.name < ls[j].info.id.name
})
if searchQuery != "" {
q := strings.ToLower(searchQuery)
filtered := ls[:0:0]
for _, dl := range ls {
if strings.Contains(strings.ToLower(dl.label()), q) ||
strings.Contains(strings.ToLower(dl.target()), q) {
filtered = append(filtered, dl)
}
}
ls = filtered
}
if len(ls) == 0 {
continue
}
groups = append(groups, linkGroup{tp: tp, links: ls})
}
return groups
}
gv := groupedView{
outGroups: buildGroups(outByType),
inGroups: buildGroups(inByType),
}
gv.outFlat = buildPanelFlat(gv.outGroups)
gv.inFlat = buildPanelFlat(gv.inGroups)
return gv
}
// buildPanelFlat builds the navigable flat list for a single panel's group list.
func buildPanelFlat(groups []linkGroup) []flatItem {
flat := make([]flatItem, 0, len(groups)*4)
for gi, g := range groups {
flat = append(flat, flatItem{kind: flatTypeGroup, groupIdx: gi})
if !g.collapsed {
for li := range g.links {
flat = append(flat, flatItem{kind: flatLink, groupIdx: gi, linkIdx: li})
}
}
}
return flat
}
func (gv *groupedView) rebuildFlat() {
gv.outFlat = buildPanelFlat(gv.outGroups)
gv.inFlat = buildPanelFlat(gv.inGroups)
}
// linkForItemIn returns the displayLink for a flatLink item within groups.
func linkForItemIn(groups []linkGroup, item flatItem) (displayLink, bool) {
if item.kind != flatLink || item.groupIdx >= len(groups) {
return displayLink{}, false
}
g := groups[item.groupIdx]
if item.linkIdx >= len(g.links) {
return displayLink{}, false
}
return g.links[item.linkIdx], true
}
// nextSelectable advances the cursor by dir (+1/-1), wrapping around the list.
//
// There is no "nothing selected" position: leaving the links is a move to the
// centre column, not a cursor value. A highlight in an unfocused panel is
// never drawn, so the cursor sitting on row 0 there claims nothing.
func nextSelectable(flat []flatItem, from, dir int) int {
n := len(flat)
if n == 0 {
return 0
}
if from < 0 {
from = 0
}
return (from + dir + n) % n
}
// ── Panel focus ────────────────────────────────────────────────────────────────
// panelFocus says which of the three columns the user is in, and therefore
// what they are working with.
//
// The centre column is part of the cycle, and that is what makes the highlight
// honest. Focus on the centre means the subject is the vertex, and neither
// side panel draws a highlight — a non-focused panel never has — so arriving
// at a vertex no longer asserts that some link is selected. Step into a side
// panel and its first row highlights, because there the claim is true.
//
// The order is the physical one: incoming, centre, outgoing. h and l move
// between them and clamp at the ends rather than wrapping, because the mental
// model is a position on screen, not a ring.
type panelFocus int
const (
panelIn panelFocus = iota // left column — incoming links
panelCenter // middle column — the vertex itself (default)
panelOut // right column — outgoing links
)
// left and right move the focus one column, clamped.
func (f panelFocus) left() panelFocus {
if f > panelIn {
return f - 1
}
return f
}
func (f panelFocus) right() panelFocus {
if f < panelOut {
return f + 1
}
return f
}
func (f panelFocus) onLinks() bool { return f == panelIn || f == panelOut }
// ── Model ─────────────────────────────────────────────────────────────────────
type tuiModel struct {
currentID string
fvi *fullVertexInfo
links []displayLink
grouped groupedView
focus panelFocus
rCursor int // cursor in grouped.outFlat (right/outgoing panel)
lCursor int // cursor in grouped.inFlat (left/incoming panel)
rOffset int // scroll offset in right panel
lOffset int // scroll offset in left panel
bodyVP viewport.Model
ready bool
loading bool
linksTotal int
loadGen int
errMsg string
history []string
queryMode bool
queryInput textinput.Model
queryResult string
queryResults []string
qCursor int
qOffset int
searchMode bool
searchInput textinput.Model
searchQuery string
// searchPrev is the filter in force when `f` was pressed, so Esc can put
// it back instead of destroying it.
searchPrev string
// gotoMode is the id prompt. Walking is the normal way to move, but a
// browser with no address bar means the only way back to a known vertex is
// to remember the path to it — and R, the one shortcut, also resets
// everything else.
gotoMode bool
gotoInput textinput.Model
exportMode bool
exportDepStep bool // false = format selection, true = depth entry
exportFmtIdx int
exportDepthIdx int // index in exportDepthPresets
exportInput textinput.Model
outTypes2 []string
inTypes2 []string
rawBody bool
// form holds the active CRUD form, or nil. It is checked FIRST in the
// dispatch chain, so "a form is modal" is the semantics rather than a
// convention. Keeping it a single nullable field leaves every existing
// mode and every existing test untouched.
form *formState
// llMode forces the low-level API even on typed vertices — the escape
// hatch for inspecting or repairing graph state that the high-level API
// would refuse to express.
llMode bool
// restore carries view state across a reload; see tui_restore.go.
restore *viewRestore
// pendingNavAfterDelete is where to go once the in-flight delete of the
// current vertex succeeds. Decided before the delete, while the history is
// still intact.
pendingNavAfterDelete string
// linking is a link-in-progress: source chosen, target being walked to.
linking *pendingLink
// linkDetails caches the tags and body of edges the user has looked at.
// Keyed by (owner, name) — the address the API uses — so an edge is the
// same entry whichever of its two endpoints you are standing on.
linkDetails map[linkKey]linkDetail
// linkPeek is the edge the cursor is resting on, awaiting its debounce.
linkPeek linkKey
// bodyRegister holds a yanked body, offered as a template when creating
// or editing another entity. Navigating to a sibling, pressing y, and
// coming back is how "copy the body of an existing object" works without
// any extra API surface.
bodyRegister string
// helpOffset scrolls the keymap; it does not fit an 80x24 terminal and
// entries that run off the bottom may as well not exist.
helpOffset int
// helpOpen shows the full keymap. Checked before everything else, since
// the status bar can only advertise a handful of the bindings.
helpOpen bool
width int
height int
}
// ── Active-panel helpers ───────────────────────────────────────────────────────
// The active* helpers describe the focused LINK panel. On the centre column
// there is none, and they answer with nothing — which is what makes
// cursorLink false there, and the subject the vertex.
func (m tuiModel) activeFlat() []flatItem {
switch m.focus {
case panelIn:
return m.grouped.inFlat
case panelOut:
return m.grouped.outFlat
}
return nil
}
func (m tuiModel) activeCursorVal() int {
if m.focus == panelIn {
return m.lCursor
}
return m.rCursor
}
// linkPanelFocused reports whether a link panel owns the subject.
func (m tuiModel) linkPanelFocused() bool { return m.focus.onLinks() }
func (m tuiModel) activeOffsetVal() int {
if m.focus == panelIn {
return m.lOffset
}
return m.rOffset
}
func (m tuiModel) activeGroups() []linkGroup {
switch m.focus {
case panelIn:
return m.grouped.inGroups
case panelOut:
return m.grouped.outGroups
}
return nil
}
func (m tuiModel) setActiveCursor(v int) tuiModel {
switch m.focus {
case panelIn:
m.lCursor = v
case panelOut:
m.rCursor = v
}
return m
}
func (m tuiModel) setActiveOffset(v int) tuiModel {
switch m.focus {
case panelIn:
m.lOffset = v
case panelOut:
m.rOffset = v
}
return m
}
// refreshBody re-syncs the body viewport size and content. No-op if not ready.
func (m tuiModel) refreshBody() tuiModel {
if !m.ready {
return m
}
m.bodyVP.Width = m.vpWidth()
m.bodyVP.Height = m.vpHeight()
m.bodyVP.SetContent(m.bodyContent())
return m
}
// cursorLink returns the displayLink at the active cursor (only for flatLink items).
func (m tuiModel) cursorLink() (displayLink, bool) {
flat := m.activeFlat()
cursor := m.activeCursorVal()
if cursor < 0 || cursor >= len(flat) {
return displayLink{}, false
}
return linkForItemIn(m.activeGroups(), flat[cursor])
}
// cursorGroup returns the group the cursor is on, when it is on a header.
func (m tuiModel) cursorGroup() (linkGroup, bool) {
flat := m.activeFlat()
cursor := m.activeCursorVal()
if cursor < 0 || cursor >= len(flat) {
return linkGroup{}, false
}
item := flat[cursor]
groups := m.activeGroups()
if item.kind != flatTypeGroup || item.groupIdx >= len(groups) {
return linkGroup{}, false
}
return groups[item.groupIdx], true
}
// ── Constructor ───────────────────────────────────────────────────────────────
func newTuiModel(startID string) tuiModel {
ti := textinput.New()
ti.Placeholder = "JPGQL expression…"
ti.CharLimit = 512
ti.PromptStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("99"))
ti.TextStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("255"))
si := textinput.New()
si.Placeholder = "search…"
si.CharLimit = 128
si.PromptStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("226"))
si.TextStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("255"))
gi := textinput.New()
gi.Placeholder = "vertex id…"
gi.CharLimit = 256
gi.PromptStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("99"))
gi.TextStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("255"))
ei := textinput.New()
ei.Placeholder = "all"
ei.CharLimit = 6
ei.PromptStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("208"))
ei.TextStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("255"))
return tuiModel{
currentID: startID,
loading: true,
queryInput: ti,
searchInput: si,
exportInput: ei,
gotoInput: gi,
linkDetails: make(map[linkKey]linkDetail),
focus: panelCenter,
}
}
func gWalkTUI() error {
if err := gWalkLoad(); err != nil {
return err
}
startID := canonID(gWalkData.GetByPath("id").AsStringDefault(""))
if startID == "" {
startID = hubID("root")
_ = gWalkTo(startID)
}
p := tea.NewProgram(newTuiModel(startID), tea.WithAltScreen())
_, err := p.Run()
return err
}
// ── Commands ──────────────────────────────────────────────────────────────────
// fetchVertexCmd loads a vertex. It canonicalises the id first, and every id
// the model stores flows from the msg it returns — so this is the choke point
// that keeps m.currentID, m.history and the gwalk cursor file all speaking the
// same form.
func fetchVertexCmd(id string, gen int) tea.Cmd {
id = canonID(id)
return func() tea.Msg {
if err := initDBClient(); err != nil {
return vertexInfoMsg{id: id, gen: gen, err: err}
}
fvi, err := getVertexFullInfo(id)
if err != nil {
return vertexInfoMsg{id: id, gen: gen, err: err}
}
return vertexInfoMsg{id: id, gen: gen, fvi: &fvi}
}
}
func fetchLinksCmd(id string, gen int, fvi *fullVertexInfo) tea.Cmd {
return func() tea.Msg {
// Fast path: the vertex read already carried every link's target and
// type, so there is nothing left to fetch. This is the difference
// between one request and one-per-link — and every mutation triggers a
// refresh, so on a type vertex with thousands of instances the fan-out
// would dominate. Link bodies and tags are not needed here (the list
// view never shows them) and are read lazily when an editor opens.
if len(fvi.outFull)+len(fvi.inFull) == len(fvi.outLinks)+len(fvi.inLinks) {
links := make([]displayLink, 0, len(fvi.outFull)+len(fvi.inFull))
for _, fli := range fvi.outFull {
links = append(links, displayLink{info: fli, isOut: true})
}
for _, fli := range fvi.inFull {
links = append(links, displayLink{info: fli, isOut: false})
}
return linksLoadedMsg{id: id, gen: gen, links: links}
}
type result struct {
dl displayLink
err error
}
type linkTask struct {
lid linkId
isOut bool
}
all := make([]linkTask, 0, len(fvi.outLinks)+len(fvi.inLinks))
for _, lid := range fvi.outLinks {
all = append(all, linkTask{lid, true})
}
for _, lid := range fvi.inLinks {
all = append(all, linkTask{lid, false})
}
results := make([]result, len(all))
workers := runtime.NumCPU() * 3
if workers < 4 {
workers = 4
}
sem := make(chan struct{}, workers)
var wg sync.WaitGroup
for i, task := range all {
wg.Add(1)
sem <- struct{}{}
go func(i int, lid linkId, isOut bool) {
defer wg.Done()
defer func() { <-sem }()
fli, err := getLinkFullInfo(lid)
if err != nil {
results[i] = result{err: err}
} else {
results[i] = result{dl: displayLink{info: fli, isOut: isOut}}
}
}(i, task.lid, task.isOut)
}
wg.Wait()
links := make([]displayLink, 0, len(all))
var failed int
for _, r := range results {
if r.err != nil {
failed++
} else {
links = append(links, r.dl)
}
}
var partialErr error
if failed > 0 {
partialErr = fmt.Errorf("%d link(s) failed to load", failed)
}
return linksLoadedMsg{id: id, gen: gen, links: links, partialErr: partialErr}
}
}
// fetchDepth2TypesCmd fetches link types one hop beyond the current vertex's direct neighbours.
// For each level-1 link type, it picks one representative neighbour, fetches that vertex's
// link list, then fetches types for those links — all in parallel.
func fetchDepth2TypesCmd(gen int, links []displayLink) tea.Cmd {
return func() tea.Msg {
if len(links) == 0 {
return depth2TypesMsg{gen: gen}
}
if err := initDBClient(); err != nil {
return depth2TypesMsg{gen: gen}
}
// One representative neighbour per (direction × level-1 type).
outReps := map[string]string{}
inReps := map[string]string{}
for _, dl := range links {
target := dl.target()
if target == "" {
continue
}
tp := dl.info.tp
if tp == "" {
tp = "(no type)"
}
if dl.isOut {
if _, ok := outReps[tp]; !ok {
outReps[tp] = target
}
} else {
if _, ok := inReps[tp]; !ok {
inReps[tp] = target
}
}
}
type neighbor struct {
id string
isOut bool
}
neighbors := make([]neighbor, 0, len(outReps)+len(inReps))
for _, id := range outReps {
neighbors = append(neighbors, neighbor{id, true})
}
for _, id := range inReps {
neighbors = append(neighbors, neighbor{id, false})
}
// Fetch vertex info for each representative in parallel.
type vtxResult struct {
isOut bool
fvi fullVertexInfo
ok bool
}
vtxResults := make([]vtxResult, len(neighbors))
workers := runtime.NumCPU() * 3
if workers < 4 {
workers = 4
}
sem := make(chan struct{}, workers)
var wg sync.WaitGroup
for i, nb := range neighbors {
wg.Add(1)
sem <- struct{}{}
go func(i int, id string, isOut bool) {
defer wg.Done()
defer func() { <-sem }()
fvi, err := getVertexFullInfo(id)
vtxResults[i] = vtxResult{isOut: isOut, fvi: fvi, ok: err == nil}
}(i, nb.id, nb.isOut)
}
wg.Wait()
// Collect link IDs from all representative vertices (hard cap).
type linkTask struct {
lid linkId
isOut bool
}
const maxTasks = 200
var tasks []linkTask
for _, vr := range vtxResults {
if !vr.ok {
continue
}
if vr.isOut {
// outgoing rep: only its outLinks reach depth-2 outgoing territory
for _, lid := range vr.fvi.outLinks {
tasks = append(tasks, linkTask{lid, true})
if len(tasks) >= maxTasks {
break
}
}
} else {
// incoming rep: only its inLinks reach depth-2 incoming territory
for _, lid := range vr.fvi.inLinks {
tasks = append(tasks, linkTask{lid, false})
if len(tasks) >= maxTasks {
break
}
}
}
if len(tasks) >= maxTasks {
break
}
}
if len(tasks) == 0 {
return depth2TypesMsg{gen: gen}
}
// Fetch link types in parallel.
type typeResult struct {
tp string
isOut bool
}
typeResults := make([]typeResult, len(tasks))
for i, task := range tasks {
wg.Add(1)
sem <- struct{}{}
go func(i int, lid linkId, isOut bool) {
defer wg.Done()
defer func() { <-sem }()
fli, err := getLinkFullInfo(lid)
if err != nil {
return
}
tp := fli.tp
if tp == "" {
tp = "(no type)"
}
typeResults[i] = typeResult{tp: tp, isOut: isOut}
}(i, task.lid, task.isOut)
}
wg.Wait()
outSet := map[string]bool{}
inSet := map[string]bool{}
for _, tr := range typeResults {
if tr.tp == "" {
continue
}
if tr.isOut {
outSet[tr.tp] = true
} else {
inSet[tr.tp] = true
}
}
out2 := make([]string, 0, len(outSet))
for tp := range outSet {
out2 = append(out2, tp)
}
sort.Strings(out2)
in2 := make([]string, 0, len(inSet))
for tp := range inSet {
in2 = append(in2, tp)
}
sort.Strings(in2)
return depth2TypesMsg{gen: gen, outTypes: out2, inTypes: in2}
}
}
func runExportCmd(gen int, fromID, format string, depth int) tea.Cmd {
return func() tea.Msg {
if err := initDBClient(); err != nil {
return exportResultMsg{gen: gen, err: err}
}
data, err := gWalkGetGraph(format, fromID, depth, nil, nil)
if err != nil {
return exportResultMsg{gen: gen, err: err}
}
ext := "graphml"
if format == "dot" {
ext = "dot"
}
safe := strings.NewReplacer("/", "_", ":", "_", " ", "_").Replace(fromID)
filename := safe + "." + ext
if err := os.WriteFile(filename, []byte(data), 0o644); err != nil {
return exportResultMsg{gen: gen, err: err}
}
return exportResultMsg{gen: gen, file: filename}
}
}
func runQueryCmd(gen int, fromID, query string) tea.Cmd {
return func() tea.Msg {
if err := initDBClient(); err != nil {
return queryResultMsg{gen: gen, err: err}
}
result, err := dbClient.Query.JPGQLCtraQuery(fromID, query)
if err != nil {
return queryResultMsg{gen: gen, err: err}
}
return queryResultMsg{gen: gen, results: result}
}
}
// ── Init ──────────────────────────────────────────────────────────────────────
func (m tuiModel) Init() tea.Cmd {
return fetchVertexCmd(m.currentID, m.loadGen)
}
// ── Styles ────────────────────────────────────────────────────────────────────
var (
colorAccent = lipgloss.Color("99")
colorOut = lipgloss.Color("42")
colorIn = lipgloss.Color("214")
colorDim = lipgloss.Color("240")
colorSelected = lipgloss.Color("57")
colorErr = lipgloss.Color("196")
colorLoading = lipgloss.Color("220")
colorHeader = lipgloss.Color("205")
colorType = lipgloss.Color("75")
styleHeader = lipgloss.NewStyle().
Bold(true).
Foreground(colorHeader)
stylePanel = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("238"))
stylePanelActive = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(colorAccent)
styleTitle = lipgloss.NewStyle().
Foreground(colorAccent).
Bold(true)
styleSelected = lipgloss.NewStyle().
Background(colorSelected).
Foreground(lipgloss.Color("255"))
styleOut = lipgloss.NewStyle().Foreground(colorOut)
styleIn = lipgloss.NewStyle().Foreground(colorIn)
styleDim = lipgloss.NewStyle().Foreground(colorDim)
styleMetaKey = lipgloss.NewStyle().Foreground(colorAccent)
styleMetaVal = lipgloss.NewStyle().Foreground(lipgloss.Color("253"))
styleTypeHdr = lipgloss.NewStyle().Foreground(colorType)
styleStatus = lipgloss.NewStyle().
Background(lipgloss.Color("235")).
Foreground(lipgloss.Color("253")).
Padding(0, 1)
styleHintKey = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("255"))
styleHintSep = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))
styleErr = lipgloss.NewStyle().Foreground(colorErr)
styleLoading = lipgloss.NewStyle().Foreground(colorLoading)
// CRUD feedback: applied vs. a mode that destroys data if misread.
styleOk = lipgloss.NewStyle().Foreground(colorOut)
styleWarn = lipgloss.NewStyle().Bold(true).Foreground(colorIn)
styleSearch = lipgloss.NewStyle().Background(lipgloss.Color("226")).Foreground(lipgloss.Color("16"))
)
// ── Dimensions ────────────────────────────────────────────────────────────────
const narrowThreshold = 90
func (m tuiModel) isNarrow() bool { return m.width < narrowThreshold }
// sideW is the total outer width (including border) of each side panel.
func (m tuiModel) sideW() int {
w := m.width / 3 // ~33% each side
if w < 28 {
w = 28
}
if w > 52 {
w = 52
}
return w
}
// centerW is the total outer width of the center panel.
func (m tuiModel) centerW() int {
w := m.width - 2*m.sideW()
if w < 10 {
w = 10
}
return w
}
// sideContentW is the inner content width for a side panel (border adds 2).
func (m tuiModel) sideContentW() int {
w := m.sideW() - 2
if w < 1 {
w = 1
}
return w
}
// centerContentW is the inner content width for the center panel.
func (m tuiModel) centerContentW() int {
w := m.centerW() - 2
if w < 1 {
w = 1
}
return w
}
// breadcrumbH also reserves the row for the pending-link banner, which lives
// there even with no history.
func (m tuiModel) breadcrumbH() int {
if len(m.history) > 0 || m.linking != nil {
return 1
}
return 0
}
// panelContentH is the inner content height available inside all panels.
func (m tuiModel) panelContentH() int {
h := m.height - 1 - m.breadcrumbH() - 1 - 2
if h < 1 {
h = 1
}
return h
}
// vpWidth is the body viewport content width (full center content area).
func (m tuiModel) vpWidth() int {
return m.centerContentW()
}
// typeMapH is the height of the type-flow map in the lower half of the center panel.
func (m tuiModel) typeMapH() int {
available := m.panelContentH() - 2 // subtract title + divider
if available < 2 {
return 1
}
return available / 2
}
// vpHeight is the body viewport height — top half of center panel (minus title + divider + type map).
func (m tuiModel) vpHeight() int {
h := m.panelContentH() - 2 - m.typeMapH()
if h < 1 {
h = 1
}
return h
}
// displayLinksOf builds the link list from a vertex read, the same way
// fetchLinksCmd's fast path does. ok is false when the runtime did not return
// the structured form, in which case the links are not classifiable without a
// per-link fan-out.
func displayLinksOf(fvi fullVertexInfo) ([]displayLink, bool) {
if len(fvi.outFull)+len(fvi.inFull) != len(fvi.outLinks)+len(fvi.inLinks) {
return nil, false
}
links := make([]displayLink, 0, len(fvi.outFull)+len(fvi.inFull))
for _, fli := range fvi.outFull {
links = append(links, displayLink{info: fli, isOut: true})
}
for _, fli := range fvi.inFull {
links = append(links, displayLink{info: fli, isOut: false})
}
return links, true
}