-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
scrollbar.go
91 lines (80 loc) · 2.04 KB
/
scrollbar.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
package tk
import (
"src.elv.sh/pkg/cli/term"
"src.elv.sh/pkg/ui"
)
// VScrollbarContainer is a Renderer consisting of content and a vertical
// scrollbar on the right.
type VScrollbarContainer struct {
Content Renderer
Scrollbar VScrollbar
}
func (v VScrollbarContainer) Render(width, height int) *term.Buffer {
buf := v.Content.Render(width-1, height)
buf.ExtendRight(v.Scrollbar.Render(1, height))
return buf
}
// VScrollbar is a Renderer for a vertical scrollbar.
type VScrollbar struct {
Total int
Low int
High int
}
var (
vscrollbarThumb = ui.T(" ", ui.FgMagenta, ui.Inverse)
vscrollbarTrough = ui.T("│", ui.FgMagenta)
)
func (v VScrollbar) Render(width, height int) *term.Buffer {
posLow, posHigh := findScrollInterval(v.Total, v.Low, v.High, height)
bb := term.NewBufferBuilder(1)
for i := 0; i < height; i++ {
if i > 0 {
bb.Newline()
}
if posLow <= i && i < posHigh {
bb.WriteStyled(vscrollbarThumb)
} else {
bb.WriteStyled(vscrollbarTrough)
}
}
return bb.Buffer()
}
// HScrollbar is a Renderer for a horizontal scrollbar.
type HScrollbar struct {
Total int
Low int
High int
}
var (
hscrollbarThumb = ui.T(" ", ui.FgMagenta, ui.Inverse)
hscrollbarTrough = ui.T("━", ui.FgMagenta)
)
func (h HScrollbar) Render(width, height int) *term.Buffer {
posLow, posHigh := findScrollInterval(h.Total, h.Low, h.High, width)
bb := term.NewBufferBuilder(width)
for i := 0; i < width; i++ {
if posLow <= i && i < posHigh {
bb.WriteStyled(hscrollbarThumb)
} else {
bb.WriteStyled(hscrollbarTrough)
}
}
return bb.Buffer()
}
func findScrollInterval(n, low, high, height int) (int, int) {
f := func(i int) int {
return int(float64(i)/float64(n)*float64(height) + 0.5)
}
scrollLow := f(low)
// We use the following instead of f(high), so that the size of the
// scrollbar remains the same as long as the window size remains the same.
scrollHigh := scrollLow + f(high-low)
if scrollLow == scrollHigh {
if scrollHigh == height {
scrollLow--
} else {
scrollHigh++
}
}
return scrollLow, scrollHigh
}