1 // Package pagination implements a pagination solution for multiple front-ends. 2 package pagination // import "vimagination.zapto.org/pagination" 3 4 const elipses = "..." 5 6 // Pagination contains the information necessary to print a proper pagination. 7 type Pagination struct { 8 numSections byte 9 page uint 10 sections [3]section 11 } 12 13 // Print converts the Pagination sections into a string. 14 // 15 // The pageFn func takes a page number and returns whatever text is needed for 16 // that page. 17 // 18 // The sep string is what is to appear between the sections. 19 func (p Pagination) Print(pageFn func(uint) string, sep string) string { 20 str := "" 21 22 for i := byte(0); i < p.numSections; i++ { 23 if i != 0 { 24 str += sep 25 } 26 27 for page := p.sections[i].First; page <= p.sections[i].Last; page++ { 28 str += pageFn(page) 29 } 30 } 31 32 return str 33 } 34 35 // HTML calls Print with a HTML based pageFn and a simple ellipses. 36 // 37 // The urlBase will have the page number appended to it, so it needs to be 38 // formatted with this in mind. 39 func (p Pagination) HTML(urlBase string) string { 40 return p.Print(func(page uint) string { 41 numStr := itoa(page + 1) 42 43 if page == p.page { 44 return numStr + " " 45 } 46 47 return "<a href=\"" + urlBase + numStr + "\">" + numStr + "</a> " 48 }, elipses) 49 } 50 51 // String stringifies the Sections with a simple pageFn. 52 func (p Pagination) String() string { 53 return p.Print(func(page uint) string { 54 return itoa(page+1) + " " 55 }, elipses) 56 } 57 58 // Section contains the information for a single section of a pagination. 59 type section struct { 60 First, Last uint 61 } 62 63 func itoa(n uint) string { 64 if n == 0 { 65 return "0" 66 } 67 68 var digits [20]byte 69 70 pos := 20 71 72 for ; n > 0; n /= 10 { 73 pos-- 74 digits[pos] = '0' + byte(n%10) 75 } 76 77 return string(digits[pos:]) 78 } 79