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 for i := byte(0); i < p.numSections; i++ { 22 if i != 0 { 23 str += sep 24 } 25 for page := p.sections[i].First; page <= p.sections[i].Last; page++ { 26 str += pageFn(page) 27 } 28 } 29 return str 30 } 31 32 // HTML calls Print with a HTML based pageFn and a simple elipses. 33 // 34 // The urlBase will have the page number appended to it, so it needs to be 35 // formatted with this in mind. 36 func (p Pagination) HTML(urlBase string) string { 37 return p.Print(func(page uint) string { 38 numStr := itoa(page + 1) 39 if page == p.page { 40 return numStr + " " 41 } 42 return "<a href=\"" + urlBase + numStr + "\">" + numStr + "</a> " 43 }, elipses) 44 } 45 46 // String stringifies the Sections with a simple pageFn 47 func (p Pagination) String() string { 48 return p.Print(func(page uint) string { 49 return itoa(page+1) + " " 50 }, elipses) 51 } 52 53 // Section contains the information for a single section of a pagination. 54 type section struct { 55 First, Last uint 56 } 57 58 func itoa(n uint) string { 59 if n == 0 { 60 return "0" 61 } 62 var digits [20]byte 63 pos := 20 64 for ; n > 0; n /= 10 { 65 pos-- 66 digits[pos] = '0' + byte(n%10) 67 } 68 return string(digits[pos:]) 69 }