-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtui.go
90 lines (76 loc) · 2.27 KB
/
tui.go
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
package main
import (
"github.com/gdamore/tcell"
"github.com/rivo/tview"
"os/exec"
"strings"
)
type tui struct {
app *tview.Application
form *tview.Form
pages *tview.Pages
fileLocation *string
}
func Init(bookmarks *[]bookmark, fileLocation *string) {
app := tview.NewApplication()
pages := tview.NewPages()
t := tui{app: app, pages: pages, fileLocation: fileLocation}
app.SetInputCapture(t.inputActions)
listView := t.list(bookmarks)
addView := t.addView()
pages.AddPage("Bookmarks", listView, true, true)
pages.AddPage("New Bookmark", addView, true, false)
if err := app.SetRoot(pages, true).SetFocus(pages).Run(); err != nil {
panic(err)
}
}
func (t *tui) list(bookmarks *[]bookmark) *tview.List {
list := tview.NewList()
for _, bookmark := range *bookmarks {
list.AddItem(bookmark.title, bookmark.url, 0, func() {
command := exec.Command("xdg-open", bookmark.url)
err := command.Run()
check(err)
})
}
return list
}
func (t *tui) inputActions(e *tcell.EventKey) *tcell.EventKey {
switch pressed_key := e.Rune(); pressed_key {
case 'q':
t.app.Stop()
case 'a':
t.pages.SwitchToPage("New Bookmark")
}
return e
}
func (t *tui) addView() *tview.Form {
form := tview.NewForm()
t.form = form
form.AddInputField("URL", "", 20, nil, nil)
form.AddInputField("Title", "", 20, nil, nil)
form.AddInputField("Comment", "", 20, nil, nil)
form.AddInputField("Tags (comma-separated)", "", 20, nil, nil)
form.AddButton("Save", t.handleAddAction)
form.AddButton("Quit", func() {
t.app.Stop()
})
return form
}
func (t *tui) handleAddAction() {
urlField := t.form.GetFormItemByLabel("URL")
titleField := t.form.GetFormItemByLabel("Title")
tagsField := t.form.GetFormItemByLabel("Tags (comma-separated)")
commentField := t.form.GetFormItemByLabel("Comment")
url := urlField.(*tview.InputField).GetText()
title := titleField.(*tview.InputField).GetText()
tagsText := tagsField.(*tview.InputField).GetText()
comment := commentField.(*tview.InputField).GetText()
tags := parseTagsString(tagsText)
newBookmark := bookmark{id: 0, url: url, title: title, comment: comment, tags: tags}
writeBookmark(newBookmark, t.fileLocation)
}
func parseTagsString(tagsString string) []string {
splitTags := strings.Split(tagsString, ",")
return splitTags
}