/
pagination.go
106 lines (93 loc) · 2.39 KB
/
pagination.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
package templates
// ResultsPerPage is the number of results to display per pagination page.
const (
ResultsPerPage = 15
ResultsPerPageStr = "15"
)
// NewPagination initializes a pagination struct of n pages.
func NewPagination(page, numPages, numResults uint64, resultsPerPage uint64, url, queries string, htmx PaginationHtmx) Pagination {
if len(queries) > 0 {
queries = "&" + queries
}
p := Pagination{
Functions: NewFunctionsData[uint64](),
IsHidden: numResults == 0,
Htmx: htmx,
NumPages: numPages,
NumResults: numResults,
ResultsPerPage: resultsPerPage,
Search: PaginationSearch{CurrentPage: 1},
URL: url,
URLQueries: queries,
}
totalPages := numResults / resultsPerPage
if numResults%resultsPerPage > 0 {
totalPages++
} else {
totalPages = numPages
}
numPages = totalPages
p.NumPages = totalPages
if page == 1 {
p.Prev = 1
} else {
p.Prev = page - 1
}
if (page * resultsPerPage) == numResults {
p.Next = page
} else {
p.Next = page + 1
}
p.Selected = page
if numPages <= 10 {
for i := uint64(1); i <= numPages; i++ {
p.Left = append(p.Left, i)
}
} else {
if page <= numPages/2 {
if page > 4 {
p.Middle = append(p.Middle, page-2, page-1, page, page+1, page+2)
p.Left = append(p.Left, 1)
} else {
for i := uint64(1); i <= page; i++ {
p.Left = append(p.Left, i)
}
p.Left = append(p.Left, page+1, page+2, page+3)
}
p.Right = append(p.Right, numPages)
} else {
if page < numPages-3 {
p.Middle = append(p.Middle, page-2, page-1, page, page+1, page+2)
p.Right = append(p.Right, numPages)
} else {
for i := page - 3; i <= numPages; i++ {
p.Right = append(p.Right, i)
}
}
p.Left = append(p.Left, 1)
}
}
return p
}
// Pagination holds data related to pagination.
type Pagination struct {
Left, Middle, Right []uint64
Prev, Selected, Next uint64
NumPages, NumResults uint64
ResultsPerPage uint64
Functions FunctionsData[uint64]
IsHidden bool
Htmx PaginationHtmx
Search PaginationSearch
URL string
URLQueries string
}
// PaginationHtmx holds data related to htmx for pagination.
type PaginationHtmx struct {
IsSwap bool
Target string
}
// PaginationSearch holds search data for the pagination.
type PaginationSearch struct {
CurrentPage uint64
}