Debian Codegraph @

resources/page/pagination.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package page
15
16 import (
17 "errors"
18 "fmt"
19 "math"
20 "reflect"
21
22 "github.com/gohugoio/hugo/config"
23
24 "github.com/spf13/cast"
25 )
26
27 // PaginatorProvider provides two ways to create a page paginator.
28 type PaginatorProvider interface {
29 // Paginator creates a paginator with the default page set.
30 Paginator(options ...any) (*Pager, error)
31 // Paginate creates a paginator with the given page set in pages.
32 Paginate(pages any, options ...any) (*Pager, error)
33 }
34
35 var _ PaginatorProvider = (*PaginatorNotSupportedFunc)(nil)
36
37 type PaginatorNotSupportedFunc func() error
38
39 func (f PaginatorNotSupportedFunc) Paginate(pages any, options ...any) (*Pager, error) {
40 return nil, f()
41 }
42
43 func (f PaginatorNotSupportedFunc) Paginator(options ...any) (*Pager, error) {
44 return nil, f()
45 }
46
47 // Pager represents one of the elements in a paginator.
48 // The number, starting on 1, represents its place.
49 type Pager struct {
50 number int
51 *Paginator
52 }
53
54 func (p Pager) String() string {
55 return fmt.Sprintf("Pager %d", p.number)
56 }
57
58 type paginatedElement interface {
59 Len() int
60 }
61
62 type pagers []*Pager
63
64 var (
65 paginatorEmptyPages Pages
66 paginatorEmptyPageGroups PagesGroup
67 )
68
69 type Paginator struct {
70 paginatedElements []paginatedElement
71 pagers
72 paginationURLFactory
73 total int
74 size int
75 }
76
77 type paginationURLFactory func(int) string
78
79 // PageNumber returns the current page's number in the pager sequence.
80 func (p *Pager) PageNumber() int {
81 return p.number
82 }
83
84 // URL returns the URL to the current page.
85 func (p *Pager) URL() string {
86 return p.paginationURLFactory(p.PageNumber())
87 }
88
89 // Pages returns the Pages on this page.
90 // Note: If this return a non-empty result, then PageGroups() will return empty.
91 func (p *Pager) Pages() Pages {
92 if len(p.paginatedElements) == 0 {
93 return paginatorEmptyPages
94 }
95
96 if pages, ok := p.element().(Pages); ok {
97 return pages
98 }
99
100 return paginatorEmptyPages
101 }
102
103 // PageGroups return Page groups for this page.
104 // Note: If this return non-empty result, then Pages() will return empty.
105 func (p *Pager) PageGroups() PagesGroup {
106 if len(p.paginatedElements) == 0 {
107 return paginatorEmptyPageGroups
108 }
109
110 if groups, ok := p.element().(PagesGroup); ok {
111 return groups
112 }
113
114 return paginatorEmptyPageGroups
115 }
116
117 func (p *Pager) element() paginatedElement {
118 if len(p.paginatedElements) == 0 {
119 return paginatorEmptyPages
120 }
121 return p.paginatedElements[p.PageNumber()-1]
122 }
123
124 // page returns the Page with the given index
125 func (p *Pager) page(index int) (Page, error) {
126 if pages, ok := p.element().(Pages); ok {
127 if pages != nil && len(pages) > index {
128 return pages[index], nil
129 }
130 return nil, nil
131 }
132
133 // must be PagesGroup
134 // this construction looks clumsy, but ...
135 // ... it is the difference between 99.5% and 100% test coverage :-)
136 groups := p.element().(PagesGroup)
137
138 i := 0
139 for _, v := range groups {
140 for _, page := range v.Pages {
141 if i == index {
142 return page, nil
143 }
144 i++
145 }
146 }
147 return nil, nil
148 }
149
150 // NumberOfElements gets the number of elements on this page.
151 func (p *Pager) NumberOfElements() int {
152 return p.element().Len()
153 }
154
155 // HasPrev tests whether there are page(s) before the current.
156 func (p *Pager) HasPrev() bool {
157 return p.PageNumber() > 1
158 }
159
160 // Prev returns the pager for the previous page.
161 func (p *Pager) Prev() *Pager {
162 if !p.HasPrev() {
163 return nil
164 }
165 return p.pagers[p.PageNumber()-2]
166 }
167
168 // HasNext tests whether there are page(s) after the current.
169 func (p *Pager) HasNext() bool {
170 return p.PageNumber() < len(p.paginatedElements)
171 }
172
173 // Next returns the pager for the next page.
174 func (p *Pager) Next() *Pager {
175 if !p.HasNext() {
176 return nil
177 }
178 return p.pagers[p.PageNumber()]
179 }
180
181 // First returns the pager for the first page.
182 func (p *Pager) First() *Pager {
183 return p.pagers[0]
184 }
185
186 // Last returns the pager for the last page.
187 func (p *Pager) Last() *Pager {
188 return p.pagers[len(p.pagers)-1]
189 }
190
191 // Pagers returns a list of pagers that can be used to build a pagination menu.
192 func (p *Paginator) Pagers() pagers {
193 return p.pagers
194 }
195
196 // PagerSize returns the size of each paginator page.
197 func (p *Paginator) PagerSize() int {
198 return p.size
199 }
200
201 // TotalPages returns the number of pages in the paginator.
202 func (p *Paginator) TotalPages() int {
203 return len(p.paginatedElements)
204 }
205
206 // TotalNumberOfElements returns the number of elements on all pages in this paginator.
207 func (p *Paginator) TotalNumberOfElements() int {
208 return p.total
209 }
210
211 func splitPages(pages Pages, size int) []paginatedElement {
212 var split []paginatedElement
213 for low, j := 0, len(pages); low < j; low += size {
214 high := int(math.Min(float64(low+size), float64(len(pages))))
215 split = append(split, pages[low:high])
216 }
217
218 return split
219 }
220
221 func splitPageGroups(pageGroups PagesGroup, size int) []paginatedElement {
222 type keyPage struct {
223 key any
224 page Page
225 }
226
227 var (
228 split []paginatedElement
229 flattened []keyPage
230 )
231
232 for _, g := range pageGroups {
233 for _, p := range g.Pages {
234 flattened = append(flattened, keyPage{g.Key, p})
235 }
236 }
237
238 numPages := len(flattened)
239
240 for low, j := 0, numPages; low < j; low += size {
241 high := int(math.Min(float64(low+size), float64(numPages)))
242
243 var (
244 pg PagesGroup
245 key any
246 groupIndex = -1
247 )
248
249 for k := low; k < high; k++ {
250 kp := flattened[k]
251 if key == nil || key != kp.key {
252 key = kp.key
253 pg = append(pg, PageGroup{Key: key})
254 groupIndex++
255 }
256 pg[groupIndex].Pages = append(pg[groupIndex].Pages, kp.page)
257 }
258 split = append(split, pg)
259 }
260
261 return split
262 }
263
264 func ResolvePagerSize(conf config.AllProvider, options ...any) (int, error) {
265 if len(options) == 0 {
266 return conf.Pagination().PagerSize, nil
267 }
268
269 if len(options) > 1 {
270 return -1, errors.New("too many arguments, 'pager size' is currently the only option")
271 }
272
273 pas, err := cast.ToIntE(options[0])
274
275 if err != nil || pas <= 0 {
276 return -1, errors.New(("'pager size' must be a positive integer"))
277 }
278
279 return pas, nil
280 }
281
282 func Paginate(td TargetPathDescriptor, seq any, pagerSize int) (*Paginator, error) {
283 if pagerSize <= 0 {
284 return nil, errors.New("'paginate' configuration setting must be positive to paginate")
285 }
286
287 urlFactory := newPaginationURLFactory(td)
288
289 var paginator *Paginator
290
291 groups, ok, err := ToPagesGroup(seq)
292 if err != nil {
293 return nil, err
294 }
295 if ok {
296 paginator, _ = newPaginatorFromPageGroups(groups, pagerSize, urlFactory)
297 } else {
298 pages, err := ToPages(seq)
299 if err != nil {
300 return nil, err
301 }
302 paginator, _ = newPaginatorFromPages(pages, pagerSize, urlFactory)
303 }
304
305 return paginator, nil
306 }
307
308 // probablyEqual checks page lists for probable equality.
309 // It may return false positives.
310 // The motivation behind this is to avoid potential costly reflect.DeepEqual
311 // when "probably" is good enough.
312 func probablyEqualPageLists(a1 any, a2 any) bool {
313 if a1 == nil || a2 == nil {
314 return a1 == a2
315 }
316
317 t1 := reflect.TypeOf(a1)
318 t2 := reflect.TypeOf(a2)
319
320 if t1 != t2 {
321 return false
322 }
323
324 if g1, ok := a1.(PagesGroup); ok {
325 g2 := a2.(PagesGroup)
326 if len(g1) != len(g2) {
327 return false
328 }
329 if len(g1) == 0 {
330 return true
331 }
332 if g1.Len() != g2.Len() {
333 return false
334 }
335
336 return g1[0].Pages[0] == g2[0].Pages[0]
337 }
338
339 p1, err1 := ToPages(a1)
340 p2, err2 := ToPages(a2)
341
342 // probably the same wrong type
343 if err1 != nil && err2 != nil {
344 return true
345 }
346
347 if len(p1) != len(p2) {
348 return false
349 }
350
351 if len(p1) == 0 {
352 return true
353 }
354
355 return p1[0] == p2[0]
356 }
357
358 func newPaginatorFromPages(pages Pages, size int, urlFactory paginationURLFactory) (*Paginator, error) {
359 if size <= 0 {
360 return nil, errors.New("Paginator size must be positive")
361 }
362
363 split := splitPages(pages, size)
364
365 return newPaginator(split, len(pages), size, urlFactory)
366 }
367
368 func newPaginatorFromPageGroups(pageGroups PagesGroup, size int, urlFactory paginationURLFactory) (*Paginator, error) {
369 if size <= 0 {
370 return nil, errors.New("Paginator size must be positive")
371 }
372
373 split := splitPageGroups(pageGroups, size)
374
375 return newPaginator(split, pageGroups.Len(), size, urlFactory)
376 }
377
378 func newPaginator(elements []paginatedElement, total, size int, urlFactory paginationURLFactory) (*Paginator, error) {
379 p := &Paginator{total: total, paginatedElements: elements, size: size, paginationURLFactory: urlFactory}
380
381 var ps pagers
382
383 if len(elements) > 0 {
384 ps = make(pagers, len(elements))
385 for i := range p.paginatedElements {
386 ps[i] = &Pager{number: (i + 1), Paginator: p}
387 }
388 } else {
389 ps = make(pagers, 1)
390 ps[0] = &Pager{number: 1, Paginator: p}
391 }
392
393 p.pagers = ps
394
395 return p, nil
396 }
397
398 func newPaginationURLFactory(d TargetPathDescriptor) paginationURLFactory {
399 return func(pageNumber int) string {
400 pathDescriptor := d
401 var rel string
402 if pageNumber > 1 {
403 rel = fmt.Sprintf("/%s/%d/", d.PathSpec.Cfg.Pagination().Path, pageNumber)
404 pathDescriptor.Addends = rel
405 }
406
407 return CreateTargetPaths(pathDescriptor).RelPermalink(d.PathSpec)
408 }
409 }