-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathpager.go
70 lines (61 loc) · 1.42 KB
/
pager.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
package table
import (
"io"
)
// Pager lets you interact with the table rendering in a paged manner.
type Pager interface {
// GoTo moves to the given 1-indexed page number.
GoTo(pageNum int) string
// Location returns the current page number in 1-indexed form.
Location() int
// Next moves to the next available page and returns the same.
Next() string
// Prev moves to the previous available page and returns the same.
Prev() string
// Render returns the current page.
Render() string
// SetOutputMirror sets up the writer to which Render() will write the
// output other than returning.
SetOutputMirror(mirror io.Writer)
}
type pager struct {
index int // 0-indexed
pages []string
outputMirror io.Writer
size int
}
func (p *pager) GoTo(pageNum int) string {
if pageNum < 1 {
pageNum = 1
}
if pageNum > len(p.pages) {
pageNum = len(p.pages)
}
p.index = pageNum - 1
return p.pages[p.index]
}
func (p *pager) Location() int {
return p.index + 1
}
func (p *pager) Next() string {
if p.index < len(p.pages)-1 {
p.index++
}
return p.pages[p.index]
}
func (p *pager) Prev() string {
if p.index > 0 {
p.index--
}
return p.pages[p.index]
}
func (p *pager) Render() string {
pageToWrite := p.pages[p.index]
if p.outputMirror != nil {
_, _ = p.outputMirror.Write([]byte(pageToWrite))
}
return pageToWrite
}
func (p *pager) SetOutputMirror(mirror io.Writer) {
p.outputMirror = mirror
}