-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtui.go
More file actions
1559 lines (1414 loc) · 40.3 KB
/
tui.go
File metadata and controls
1559 lines (1414 loc) · 40.3 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 (
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"io"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/table"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
const (
viewStateInput = iota
viewStateBrowse
)
const (
modeNormal = iota
modeSearch
modeEdit
modeConfirmDelete
modeParametricSearch
modeDetail
modeRelease
)
const allFilesOption = "All Parts (Combined)"
var (
titleStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("86")).
Bold(true).
Align(lipgloss.Center)
subtitleStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("241")).
Align(lipgloss.Center)
helpStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("241")).
Align(lipgloss.Center)
inputStyle = lipgloss.NewStyle().
BorderStyle(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("62")).
Padding(1, 2).
Width(60)
errorStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("196")).
Align(lipgloss.Center).
MarginTop(1)
listStyle = lipgloss.NewStyle().
Border(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240")).
Padding(1, 2)
tableStyle = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240"))
focusedBorderColor = lipgloss.Color("62")
unfocusedBorderColor = lipgloss.Color("240")
selectedItemStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("170"))
normalItemStyle = lipgloss.NewStyle()
updateStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("220")).
Align(lipgloss.Center)
)
type fileItem struct {
name string
isAllOption bool
}
func (i fileItem) FilterValue() string { return i.name }
type itemDelegate struct{}
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 }
func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
i, ok := listItem.(fileItem)
if !ok {
return
}
str := fmt.Sprintf("%s", i.name)
fn := normalItemStyle.Render
if index == m.Index() {
fn = func(s ...string) string {
return selectedItemStyle.Render("> " + strings.Join(s, " "))
}
}
fmt.Fprint(w, fn(str))
}
type modelNew struct {
width int
height int
viewState int
textInput textinput.Model
fileList list.Model
table table.Model
pmDir string
updateMsg string
error string
csvCollection *CSVFileCollection
selectedFile string
listFocused bool
// Interactive mode fields
mode int
allRows []table.Row
filteredRows []table.Row
rowToDataIdx []int // filtered index -> allRows index
isEditable bool
// Search
searchInput textinput.Model
// Edit
editInputs []textinput.Model
editHeaders []string
editFocusIdx int
editRowIdx int
editIsNew bool
editPrevCursor int
// Delete
deleteRowIdx int
// Parametric search
paramInputs []textinput.Model
paramFocusIdx int
// Detail popup
detailHeaders []string
detailValues []string
detailScroll int
// Release overlay
releaseLog string
releaseScroll int
releaseError bool
}
func initialModelNew(needsPMDir bool, pmDir string, updateMsg string) modelNew {
ti := textinput.New()
ti.Placeholder = "/path/to/partmaster/directory"
ti.Focus()
ti.CharLimit = 256
ti.Width = 50
// Create file list
items := []list.Item{}
l := list.New(items, itemDelegate{}, 0, 0)
l.Title = "CSV Files"
l.SetShowStatusBar(false)
l.SetFilteringEnabled(false)
l.SetShowHelp(false)
// Create table with default columns
columns := []table.Column{
{Title: "No data", Width: 20},
}
t := table.New(
table.WithColumns(columns),
table.WithRows([]table.Row{}),
table.WithHeight(10),
table.WithFocused(false),
)
s := table.DefaultStyles()
s.Header = s.Header.
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240")).
BorderBottom(true).
Bold(false)
s.Selected = s.Selected.
Foreground(lipgloss.Color("229")).
Background(lipgloss.Color("57")).
Bold(false)
t.SetStyles(s)
si := textinput.New()
si.Placeholder = "Search..."
si.CharLimit = 128
si.Width = 40
m := modelNew{
textInput: ti,
fileList: l,
table: t,
viewState: viewStateInput,
pmDir: pmDir,
updateMsg: updateMsg,
listFocused: true,
searchInput: si,
}
if pmDir != "" && !needsPMDir {
m.viewState = viewStateBrowse
// Don't load CSV files here, wait for WindowSizeMsg
} else if needsPMDir {
m.viewState = viewStateInput
}
return m
}
func (m *modelNew) loadCSVFiles() {
if m.pmDir == "" {
return
}
collection, err := loadAllCSVFiles(m.pmDir)
if err != nil {
m.error = "Error loading CSV files: " + err.Error()
return
}
m.csvCollection = collection
// Update file list
items := []list.Item{
fileItem{name: allFilesOption, isAllOption: true},
}
for _, file := range collection.Files {
items = append(items, fileItem{name: file.Name, isAllOption: false})
}
m.fileList.SetItems(items)
// Select first item (All Parts) but don't update table yet
// Let the first WindowSizeMsg handle table initialization
if len(items) > 0 {
m.selectedFile = allFilesOption
}
}
// fitColumns distributes availableWidth among columns proportionally based on
// their weight values. Each column gets at least minCol characters.
func fitColumns(titles []string, weights []int, availableWidth int) []table.Column {
const minCol = 6
if len(titles) == 0 {
return nil
}
// Account for column separators (1 char between each column)
usable := availableWidth - (len(titles) - 1)
if usable < len(titles)*minCol {
usable = len(titles) * minCol
}
totalWeight := 0
for _, w := range weights {
totalWeight += w
}
columns := make([]table.Column, len(titles))
assigned := 0
for i, title := range titles {
w := weights[i] * usable / totalWeight
if w < minCol {
w = minCol
}
columns[i] = table.Column{Title: title, Width: w}
assigned += w
}
// Give any remaining pixels to the last column
if remainder := usable - assigned; remainder > 0 {
columns[len(columns)-1].Width += remainder
}
return columns
}
// tableAvailableWidth returns the width available for table columns,
// accounting for the list pane, borders, and padding.
func (m *modelNew) tableAvailableWidth() int {
listWidth := m.width / 4
// 4 for gap between panes, 2 for table border
w := m.width - listWidth - 4 - 2
if w < 30 {
w = 30
}
return w
}
func (m *modelNew) updateTableForSelectedFile() {
if m.csvCollection == nil || len(m.csvCollection.Files) == 0 {
return
}
// Don't update if we haven't received window size yet
if m.width == 0 || m.height == 0 {
return
}
avail := m.tableAvailableWidth()
if m.selectedFile == allFilesOption {
// Show combined partmaster view
pm, err := m.csvCollection.GetCombinedPartmaster()
if err != nil {
m.error = "Error loading combined partmaster: " + err.Error()
return
}
// Clear rows before changing columns to avoid index-out-of-range panic
m.table.SetRows([]table.Row{})
if len(pm) == 0 {
m.table.SetColumns([]table.Column{{Title: "No partmaster data found", Width: 50}})
m.table.SetRows([]table.Row{})
} else {
titles := []string{"IPN", "Description", "Manufacturer", "MPN", "Value"}
weights := []int{2, 4, 3, 3, 1}
columns := fitColumns(titles, weights, avail)
m.table.SetColumns(columns)
rows := []table.Row{}
for _, part := range pm {
rows = append(rows, table.Row{
string(part.IPN),
part.Description,
part.Manufacturer,
part.MPN,
part.Value,
})
}
m.table.SetRows(rows)
m.allRows = rows
}
m.isEditable = false
} else {
// Show individual CSV file
var csvFile *CSVFile
for _, file := range m.csvCollection.Files {
if file.Name == m.selectedFile {
csvFile = file
break
}
}
if csvFile == nil {
m.error = "File not found: " + m.selectedFile
return
}
// Update table columns based on CSV headers
if len(csvFile.Headers) == 0 {
// Handle empty CSV file
columns := []table.Column{{Title: "Empty file", Width: 30}}
m.table.SetColumns(columns)
m.table.SetRows([]table.Row{})
} else {
titles := make([]string, len(csvFile.Headers))
weights := make([]int, len(csvFile.Headers))
for i, header := range csvFile.Headers {
if header == "" {
titles[i] = fmt.Sprintf("Column %d", i+1)
} else {
titles[i] = header
}
// Give more weight to Description-like columns
switch header {
case "Description":
weights[i] = 4
case "IPN", "MPN", "Manufacturer":
weights[i] = 2
default:
weights[i] = 1
}
}
columns := fitColumns(titles, weights, avail)
// Build rows ensuring they match column count
rows := []table.Row{}
for _, row := range csvFile.Rows {
if len(row) == 0 {
continue
}
tableRow := make([]string, len(columns))
for i := 0; i < len(columns); i++ {
if i < len(row) {
tableRow[i] = strings.TrimSpace(row[i])
} else {
tableRow[i] = ""
}
}
rows = append(rows, tableRow)
}
if len(rows) == 0 {
rows = append(rows, make([]string, len(columns)))
}
// Reset table state before updating
m.table.SetRows([]table.Row{})
m.table.SetColumns(columns)
m.table.SetRows(rows)
m.table.SetCursor(0)
m.allRows = rows
}
m.isEditable = true
}
m.filteredRows = m.allRows
m.rowToDataIdx = nil
m.mode = modeNormal
m.error = ""
}
// getSelectedCSVFile returns the CSVFile for the currently selected file, or nil.
func (m *modelNew) getSelectedCSVFile() *CSVFile {
if m.csvCollection == nil || m.selectedFile == allFilesOption {
return nil
}
for _, file := range m.csvCollection.Files {
if file.Name == m.selectedFile {
return file
}
}
return nil
}
// applySearchFilter filters allRows by case-insensitive substring match across
// all columns. It rebuilds filteredRows, rowToDataIdx, and updates the table.
func (m *modelNew) applySearchFilter(query string) {
if query == "" {
m.filteredRows = m.allRows
m.rowToDataIdx = nil
m.table.SetRows(m.allRows)
return
}
q := strings.ToLower(query)
var filtered []table.Row
var idxMap []int
for i, row := range m.allRows {
for _, cell := range row {
if strings.Contains(strings.ToLower(cell), q) {
filtered = append(filtered, row)
idxMap = append(idxMap, i)
break
}
}
}
m.filteredRows = filtered
m.rowToDataIdx = idxMap
m.table.SetRows(filtered)
if len(filtered) > 0 {
m.table.SetCursor(0)
}
}
// enterEditMode sets up the edit overlay for the given data row index.
func (m *modelNew) enterEditMode(dataRowIdx int, isNew bool) {
csvFile := m.getSelectedCSVFile()
if csvFile == nil || dataRowIdx < 0 || dataRowIdx >= len(csvFile.Rows) {
return
}
row := csvFile.Rows[dataRowIdx]
m.editHeaders = csvFile.Headers
m.editInputs = make([]textinput.Model, len(csvFile.Headers))
for i, header := range csvFile.Headers {
ti := textinput.New()
ti.Placeholder = header
ti.CharLimit = 256
ti.Width = 40
if i < len(row) {
ti.SetValue(row[i])
}
m.editInputs[i] = ti
}
m.editFocusIdx = 0
m.editInputs[0].Focus()
m.editRowIdx = dataRowIdx
m.editIsNew = isNew
m.mode = modeEdit
}
// saveEdit writes the edit form values back to the CSV file, sorts, saves,
// and refreshes the table.
func (m *modelNew) saveEdit() {
csvFile := m.getSelectedCSVFile()
if csvFile == nil || m.editRowIdx < 0 || m.editRowIdx >= len(csvFile.Rows) {
return
}
// Write values back
for i, input := range m.editInputs {
if i < len(csvFile.Rows[m.editRowIdx]) {
csvFile.Rows[m.editRowIdx][i] = input.Value()
}
}
// Remember the IPN so we can restore cursor after sort/refresh
ipnIdx := findHeaderIndex(csvFile.Headers, "IPN")
savedIPN := ""
if ipnIdx >= 0 && ipnIdx < len(csvFile.Rows[m.editRowIdx]) {
savedIPN = csvFile.Rows[m.editRowIdx][ipnIdx]
}
// Sort by IPN
sortRowsByIPN(csvFile.Rows, ipnIdx)
// Save to disk
if err := saveCSVRaw(csvFile); err != nil {
m.error = "Error saving: " + err.Error()
}
m.updateTableForSelectedFile()
m.restoreCursorToIPN(savedIPN, ipnIdx)
}
// restoreCursorToIPN sets the table cursor to the row matching the given IPN.
func (m *modelNew) restoreCursorToIPN(targetIPN string, ipnIdx int) {
if targetIPN == "" || ipnIdx < 0 {
return
}
rows := m.table.Rows()
for i, row := range rows {
if ipnIdx < len(row) && row[ipnIdx] == targetIPN {
m.setCursorVisible(i)
return
}
}
}
// setCursorVisible moves the table cursor to position n and ensures the
// viewport scrolls so the row is visible.
func (m *modelNew) setCursorVisible(n int) {
m.table.GotoTop()
m.table.MoveDown(n)
}
// applyParametricFilter filters allRows by AND-combining per-column substring
// matches from paramInputs.
func (m *modelNew) applyParametricFilter() {
// Check if any filter is active
anyActive := false
for _, pi := range m.paramInputs {
if pi.Value() != "" {
anyActive = true
break
}
}
if !anyActive {
m.filteredRows = m.allRows
m.rowToDataIdx = nil
m.table.SetRows(m.allRows)
return
}
var filtered []table.Row
var idxMap []int
for i, row := range m.allRows {
match := true
for col, pi := range m.paramInputs {
q := strings.ToLower(pi.Value())
if q == "" {
continue
}
cell := ""
if col < len(row) {
cell = strings.ToLower(row[col])
}
if !strings.Contains(cell, q) {
match = false
break
}
}
if match {
filtered = append(filtered, row)
idxMap = append(idxMap, i)
}
}
m.filteredRows = filtered
m.rowToDataIdx = idxMap
m.table.SetRows(filtered)
if len(filtered) > 0 {
m.table.SetCursor(0)
}
}
func (m modelNew) Init() tea.Cmd {
return nil
}
func (m modelNew) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
// Update component sizes with minimum sizes
listWidth := m.width / 4
if listWidth < 20 {
listWidth = 20
}
tableWidth := m.width - listWidth - 4
if tableWidth < 30 {
tableWidth = 30
}
// Calculate available height for panes (similar to View method)
listHeight := m.height - 10 // Conservative estimate for header/footer
if listHeight < 5 {
listHeight = 5
}
m.fileList.SetWidth(listWidth)
m.fileList.SetHeight(listHeight)
// Update table width
if m.viewState == viewStateBrowse {
m.table.SetWidth(tableWidth)
m.table.SetHeight(listHeight)
// Load CSV files if not loaded yet
if m.csvCollection == nil && m.pmDir != "" {
m.loadCSVFiles()
}
// Update table content if we have a selected file but haven't displayed it yet
if m.selectedFile != "" && m.csvCollection != nil {
m.updateTableForSelectedFile()
}
}
return m, nil
case tea.KeyMsg:
if m.viewState == viewStateInput {
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
case "enter":
dir := strings.TrimSpace(m.textInput.Value())
if dir == "" {
m.error = "Directory path cannot be empty"
return m, nil
}
// Check if directory exists
if _, err := os.Stat(dir); os.IsNotExist(err) {
m.error = "Directory does not exist: " + dir
return m, nil
}
// Save config to gitplm.yml
if err := saveConfig(dir); err != nil {
m.error = "Error saving config: " + err.Error()
return m, nil
}
m.pmDir = dir
m.viewState = viewStateBrowse
m.error = ""
m.loadCSVFiles()
return m, nil
}
} else {
switch m.mode {
case modeSearch:
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
case "esc":
m.searchInput.SetValue("")
m.applySearchFilter("")
m.mode = modeNormal
return m, nil
case "enter":
m.mode = modeNormal
return m, nil
case "tab":
m.listFocused = !m.listFocused
if m.listFocused {
m.table.Blur()
} else {
m.table.Focus()
}
return m, nil
case "up", "down":
if !m.listFocused {
m.table, cmd = m.table.Update(msg)
return m, cmd
}
m.fileList, cmd = m.fileList.Update(msg)
return m, cmd
default:
m.searchInput, cmd = m.searchInput.Update(msg)
m.applySearchFilter(m.searchInput.Value())
return m, cmd
}
case modeParametricSearch:
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
case "esc":
for i := range m.paramInputs {
m.paramInputs[i].SetValue("")
}
m.applyParametricFilter()
m.mode = modeNormal
return m, nil
case "enter":
m.mode = modeNormal
return m, nil
case "tab":
m.paramInputs[m.paramFocusIdx].Blur()
m.paramFocusIdx = (m.paramFocusIdx + 1) % len(m.paramInputs)
m.paramInputs[m.paramFocusIdx].Focus()
return m, nil
case "shift+tab":
m.paramInputs[m.paramFocusIdx].Blur()
m.paramFocusIdx = (m.paramFocusIdx - 1 + len(m.paramInputs)) % len(m.paramInputs)
m.paramInputs[m.paramFocusIdx].Focus()
return m, nil
default:
m.paramInputs[m.paramFocusIdx], cmd = m.paramInputs[m.paramFocusIdx].Update(msg)
m.applyParametricFilter()
return m, cmd
}
case modeNormal:
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
case "tab":
m.listFocused = !m.listFocused
if m.listFocused {
m.table.Blur()
} else {
m.table.Focus()
}
return m, nil
case "enter":
if m.listFocused {
selected := m.fileList.SelectedItem()
if item, ok := selected.(fileItem); ok {
m.selectedFile = item.name
m.updateTableForSelectedFile()
m.listFocused = false
m.table.Focus()
}
} else {
cursor := m.table.Cursor()
csvFile := m.getSelectedCSVFile()
if csvFile != nil {
dataIdx := cursor
if m.rowToDataIdx != nil && cursor < len(m.rowToDataIdx) {
dataIdx = m.rowToDataIdx[cursor]
}
if dataIdx >= 0 && dataIdx < len(csvFile.Rows) {
m.detailHeaders = csvFile.Headers
m.detailValues = csvFile.Rows[dataIdx]
m.detailScroll = 0
m.mode = modeDetail
}
} else if m.selectedFile == allFilesOption {
dataIdx := cursor
if m.rowToDataIdx != nil && cursor < len(m.rowToDataIdx) {
dataIdx = m.rowToDataIdx[cursor]
}
if dataIdx >= 0 && dataIdx < len(m.allRows) {
ipnVal := m.allRows[dataIdx][0]
// Navigate into the CSV file containing this IPN
for _, file := range m.csvCollection.Files {
ipnIdx := findHeaderIndex(file.Headers, "IPN")
if ipnIdx < 0 {
continue
}
found := false
for rowIdx, row := range file.Rows {
if ipnIdx < len(row) && row[ipnIdx] == ipnVal {
m.selectedFile = file.Name
m.updateTableForSelectedFile()
m.table.SetCursor(rowIdx)
for i, item := range m.fileList.Items() {
if fi, ok := item.(fileItem); ok && fi.name == file.Name {
m.fileList.Select(i)
break
}
}
m.listFocused = false
m.table.Focus()
found = true
break
}
}
if found {
break
}
}
}
}
}
return m, nil
case "esc":
// Clear active search/parametric filter
if m.searchInput.Value() != "" {
m.searchInput.SetValue("")
m.applySearchFilter("")
return m, nil
}
anyParam := false
for _, pi := range m.paramInputs {
if pi.Value() != "" {
anyParam = true
break
}
}
if anyParam {
for i := range m.paramInputs {
m.paramInputs[i].SetValue("")
}
m.applyParametricFilter()
return m, nil
}
return m, nil
case "/":
m.mode = modeSearch
m.searchInput.Focus()
m.applySearchFilter(m.searchInput.Value())
return m, nil
case "p":
// If we already have paramInputs with matching column count, reuse them
csvFile := m.getSelectedCSVFile()
headers := []string{}
if csvFile != nil {
headers = csvFile.Headers
} else if m.selectedFile == allFilesOption {
headers = []string{"IPN", "Description", "Manufacturer", "MPN", "Value"}
}
if len(headers) > 0 {
if len(m.paramInputs) != len(headers) {
m.paramInputs = make([]textinput.Model, len(headers))
for i, h := range headers {
ti := textinput.New()
ti.Placeholder = h
ti.CharLimit = 128
ti.Width = 15
m.paramInputs[i] = ti
}
}
m.paramFocusIdx = 0
m.paramInputs[0].Focus()
m.mode = modeParametricSearch
}
return m, nil
case "a":
if !m.listFocused && m.isEditable {
m.editPrevCursor = m.table.Cursor()
csvFile := m.getSelectedCSVFile()
if csvFile != nil {
ipnIdx := findHeaderIndex(csvFile.Headers, "IPN")
newIPNStr, err := nextAvailableIPN(csvFile.Rows, ipnIdx)
if err != nil {
m.error = "Cannot add part: " + err.Error()
return m, nil
}
newRow := make([]string, len(csvFile.Headers))
if ipnIdx >= 0 {
newRow[ipnIdx] = newIPNStr
}
csvFile.Rows = append(csvFile.Rows, newRow)
sortRowsByIPN(csvFile.Rows, ipnIdx)
if err := saveCSVRaw(csvFile); err != nil {
m.error = "Error saving: " + err.Error()
}
m.updateTableForSelectedFile()
// Find the new row index after sort
newIdx := -1
for i, row := range csvFile.Rows {
if ipnIdx >= 0 && i < len(csvFile.Rows) && row[ipnIdx] == newIPNStr {
newIdx = i
break
}
}
if newIdx >= 0 {
m.enterEditMode(newIdx, true)
}
}
}
return m, nil
case "e":
if !m.listFocused && m.isEditable {
cursor := m.table.Cursor()
dataIdx := cursor
if m.rowToDataIdx != nil && cursor < len(m.rowToDataIdx) {
dataIdx = m.rowToDataIdx[cursor]
}
m.enterEditMode(dataIdx, false)
}
return m, nil
case "d":
if !m.listFocused && m.isEditable {
cursor := m.table.Cursor()
dataIdx := cursor
if m.rowToDataIdx != nil && cursor < len(m.rowToDataIdx) {
dataIdx = m.rowToDataIdx[cursor]
}
m.deleteRowIdx = dataIdx
m.mode = modeConfirmDelete
}
return m, nil
case "c":
if !m.listFocused && m.isEditable {
csvFile := m.getSelectedCSVFile()
if csvFile != nil {
cursor := m.table.Cursor()
m.editPrevCursor = cursor
dataIdx := cursor
if m.rowToDataIdx != nil && cursor < len(m.rowToDataIdx) {
dataIdx = m.rowToDataIdx[cursor]
}
if dataIdx >= 0 && dataIdx < len(csvFile.Rows) {
// Deep copy the row
srcRow := csvFile.Rows[dataIdx]
newRow := make([]string, len(srcRow))
copy(newRow, srcRow)
csvFile.Rows = append(csvFile.Rows, newRow)
ipnIdx := findHeaderIndex(csvFile.Headers, "IPN")
sortRowsByIPN(csvFile.Rows, ipnIdx)
if err := saveCSVRaw(csvFile); err != nil {
m.error = "Error saving: " + err.Error()
}
m.updateTableForSelectedFile()
// Find the new row (last occurrence of matching IPN)
newIdx := len(csvFile.Rows) - 1
for i := len(csvFile.Rows) - 1; i >= 0; i-- {
if csvFile.Rows[i][0] == newRow[0] && i != dataIdx {
newIdx = i
break
}
}
m.enterEditMode(newIdx, true)
}
}
}
return m, nil
case "o":
if !m.listFocused && m.selectedFile != allFilesOption {
var headers []string
var row []string
csvFile := m.getSelectedCSVFile()
cursor := m.table.Cursor()
dataIdx := cursor
if m.rowToDataIdx != nil && cursor < len(m.rowToDataIdx) {
dataIdx = m.rowToDataIdx[cursor]
}
if csvFile != nil {
if dataIdx >= 0 && dataIdx < len(csvFile.Rows) {
headers = csvFile.Headers
row = csvFile.Rows[dataIdx]
}
}
if row != nil {
for i, h := range headers {
if strings.EqualFold(h, "Datasheet") && i < len(row) {
url := strings.TrimSpace(row[i])
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
if err := openURL(url); err != nil {
m.error = fmt.Sprintf("Failed to open URL: %v", err)
}
return m, nil
}
}
}
m.error = "No valid datasheet URL found"
}
}
return m, nil