Debian Codegraph @

hugolib/page__paginator.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 hugolib
15
16 import (
17 "sync"
18
19 "github.com/gohugoio/hugo/resources/kinds"
20 "github.com/gohugoio/hugo/resources/page"
21 )
22
23 func newPagePaginator(source *pageState) *pagePaginator {
24 return &pagePaginator{
25 source: source,
26 pagePaginatorInit: &pagePaginatorInit{},
27 }
28 }
29
30 type pagePaginator struct {
31 *pagePaginatorInit
32 source *pageState
33 }
34
35 type pagePaginatorInit struct {
36 init sync.Once
37 current *page.Pager
38 }
39
40 // reset resets the paginator to allow for a rebuild.
41 func (p *pagePaginator) reset() {
42 p.pagePaginatorInit = &pagePaginatorInit{}
43 }
44
45 func (p *pagePaginator) Paginate(seq any, options ...any) (*page.Pager, error) {
46 var initErr error
47 p.init.Do(func() {
48 pagerSize, err := page.ResolvePagerSize(p.source.s.Conf, options...)
49 if err != nil {
50 initErr = err
51 return
52 }
53
54 pd := p.source.targetPathDescriptor
55 pd.Type = p.source.outputFormat()
56 paginator, err := page.Paginate(pd, seq, pagerSize)
57 if err != nil {
58 initErr = err
59 return
60 }
61
62 p.current = paginator.Pagers()[0]
63 })
64
65 if initErr != nil {
66 return nil, initErr
67 }
68
69 return p.current, nil
70 }
71
72 func (p *pagePaginator) Paginator(options ...any) (*page.Pager, error) {
73 var initErr error
74 p.init.Do(func() {
75 pagerSize, err := page.ResolvePagerSize(p.source.s.Conf, options...)
76 if err != nil {
77 initErr = err
78 return
79 }
80
81 pd := p.source.targetPathDescriptor
82 pd.Type = p.source.outputFormat()
83
84 var pages page.Pages
85
86 switch p.source.Kind() {
87 case kinds.KindHome:
88 // From Hugo 0.57 we made home.Pages() work like any other
89 // section. To avoid the default paginators for the home page
90 // changing in the wild, we make this a special case.
91 pages = p.source.s.RegularPages()
92 case kinds.KindTerm, kinds.KindTaxonomy:
93 pages = p.source.Pages()
94 default:
95 pages = p.source.RegularPages()
96 }
97
98 paginator, err := page.Paginate(pd, pages, pagerSize)
99 if err != nil {
100 initErr = err
101 return
102 }
103
104 p.current = paginator.Pagers()[0]
105 })
106
107 if initErr != nil {
108 return nil, initErr
109 }
110
111 return p.current, nil
112 }