-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewport.go
118 lines (106 loc) · 2.08 KB
/
viewport.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
/*
* Copyright (c) 2023 Brandon Jordan
*/
package ttuy
import (
"strings"
"github.com/eiannone/keyboard"
)
var lineIdx int
var lastLineIdx = -1
var stopViewport = make(chan bool)
var contents string
var contentsLines []string
var contentsLinesCount int
var lastViewport string
// Viewport displays content in a scrollable widget
func Viewport(content string) {
terminalRows()
terminalCols()
lineIdx = 0
lastLineIdx = -1
contents = wrapString(&content)
contentsLines = strings.Split(contents, eol)
contentsLinesCount = len(contentsLines)
go ReadKeys(handleViewportKeys)
Painter(func() (template string) {
if lineIdx != lastLineIdx {
var matchingRows = rows + lineIdx - 1
for i := lineIdx; i < matchingRows; i++ {
if i < contentsLinesCount {
template += contentsLines[i]
for c := 0; c < (cols - len(contentsLines[i]) - 1); c++ {
template += " "
}
template += eol
}
}
if matchingRows < rows {
for i := 0; i < ((rows - 1) - contentsLinesCount); i++ {
for c := 0; c < cols; c++ {
template += " "
}
template += eol
}
}
template += eol + Style("^C Exit \t "+upArrow+" "+downArrow+" Scroll", Dim)
lastViewport = template
} else {
template = lastViewport
}
return
})
}
func wrapString(str *string) (wrapped string) {
chars := strings.Split(*str, "")
i := 0
for _, char := range chars {
if char == eol || i == cols {
if i == cols {
wrapped += eol + char
i = 1
} else {
wrapped += eol
i = 0
}
continue
}
wrapped += char
i++
}
return
}
func moveUp(n int) {
if (lineIdx - 1) >= 0 {
lineIdx -= n
} else {
Bell()
}
}
func moveDown(n int) {
if (rows + lineIdx - 1) < contentsLinesCount {
lineIdx += n
} else {
Bell()
}
}
func handleViewportKeys(key keyboard.Key) {
select {
case <-stopViewport:
return
default:
switch key {
case keyboard.KeyCtrlC:
StopPainting()
stopViewport <- true
case keyboard.KeyPgup:
moveUp(5)
case keyboard.KeyPgdn:
moveDown(5)
case keyboard.KeyArrowUp:
moveUp(1)
case keyboard.KeyArrowDown:
moveDown(1)
}
}
}