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