-
Notifications
You must be signed in to change notification settings - Fork 17
/
cli.go
151 lines (130 loc) · 2.35 KB
/
cli.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
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
package main
import (
"fmt"
"os/exec"
"strconv"
)
var input string = ""
var cli hncli
var pageNum = 0
func storyTime() {
cli.SetContent(getStories(pageNum))
cli.SetKeyHandler(storyHandler)
cli.SetHelp("(n: next, p: previous, <num>c: view comments, <num>o: open in browser, q: quit) ")
}
var p *PageCache
func storyHandler(ch string) {
switch ch {
case "c":
if num, err := strconv.Atoi(input); err == nil {
if num < 1 {
break
}
for num-1 > len(p.Articles) {
p.GetNext()
}
text := p.Articles[num-1].PrintComments()
commentTime(text)
input = ""
} else {
cli.Alert("Please enter a number to select a comment")
}
input = ""
break
case "o":
if num, err := strconv.Atoi(input); err == nil {
for num-1 > len(p.Articles) {
p.GetNext()
}
viewInBrowser := exec.Command("xdg-open", p.Articles[num-1].Url)
viewInBrowser.Start()
} else {
cli.Alert("Please enter a number to view an article")
}
input = ""
break
case "q":
cli.Quit()
break
case "n":
//Go forward 1 page
pageNum += 1
cli.SetContent(getStories(pageNum))
input = ""
break
case "p":
//Go back 1 page, unless page < 0
if pageNum > 0 {
pageNum -= 1
}
cli.SetContent(getStories(pageNum))
break
case "enter":
cli.Refresh()
break
case "backspace":
if len(input) > 0 {
input = input[:len(input)-1]
cli.DelChar()
} else {
cli.DelChar()
}
break
default:
input += ch
break
}
}
func commentTime(text string) {
cli.SetContent(text)
cli.ResetScroll()
cli.SetHelp("(d/u scroll 30 lines; j/k: scroll 1 line; n/p scroll 1 page; q: quit to story view)")
cli.SetKeyHandler(commentHandler)
}
func commentHandler(input string) {
switch input {
case "d":
cli.Scroll(30)
break
case "u":
cli.Scroll(-30)
break
case "j":
cli.Scroll(1)
break
case "k":
cli.Scroll(-1)
break
case "g":
cli.ResetScroll()
break
case "n":
cli.Scroll(cli.Height)
break
case "p":
cli.Scroll(-cli.Height)
break
case "q":
storyTime()
break
}
}
func getStories(pageNum int) string {
h := cli.Height
start := h * pageNum
end := start + h
for end > len(p.Articles) {
p.GetNext()
}
str := ""
for i, ar := range p.Articles[start:end] {
str += fmt.Sprintf("%4d.\t(%d)\t%s\n", start+i+1, ar.Karma, ar.Title)
}
return str
}
func runCli() {
cli = GetCli()
p = NewPageCache()
storyTime()
cli.Run()
}