D3vugu-components/components/navigation/pagination.go

91 lines
2.1 KiB
Go
Raw Normal View History

package navigation
import "github.com/vugu/vugu"
type Pagination struct {
AttrMap vugu.AttrMap
buttons []paginationButtonInfo
Page int `vugu:"data"`
Pages int `vugu:"data"`
Pagination PaginationHandler // External handler that is called upon an event.
}
type paginationButtonInfo struct {
Page int
Class string
}
func (c *Pagination) handleClickPrev(event vugu.DOMEvent) {
c.handleClickPage(event, c.Page-1)
}
func (c *Pagination) handleClickNext(event vugu.DOMEvent) {
c.handleClickPage(event, c.Page+1)
}
func (c *Pagination) handleClickPage(event vugu.DOMEvent, page int) {
if page <= 0 || page > c.Pages {
return
}
if c.Pagination != nil {
c.Pagination.PaginationHandle(PaginationEvent{
DOMEvent: event,
Page: page,
})
}
}
func (c *Pagination) Init(ctx vugu.InitCtx) {
c.Pages = 10
}
func (c *Pagination) Compute(ctx vugu.ComputeCtx) {
// Number of buttons around the current page.
// Excluding first and last page.
const AroundButtons = 2
// Number of buttons that can change, so excluding first and last page.
const DynamicButtons = AroundButtons + 1 + AroundButtons
// Number of buttons with page numbers, so excluding "previous" and "next".
const TotalButtons = 1 + DynamicButtons + 1
// Prepare buttons.
buttons := [TotalButtons]paginationButtonInfo{
0: {Page: 1},
TotalButtons - 1: {Page: c.Pages},
}
startPage := 2
if startPage < c.Page-AroundButtons {
startPage = c.Page - AroundButtons
}
if startPage > c.Pages-DynamicButtons {
startPage = c.Pages - DynamicButtons
}
for i := 0; i < DynamicButtons; i++ {
buttons[i+1] = paginationButtonInfo{Page: i + startPage}
}
// Remove duplicates and set class accordingly.
// pageCounter is used to check if pages are strictly monotonically increasing.
buttonsFiltered := make([]paginationButtonInfo, 0, len(buttons))
pageCounter := 0
for _, page := range buttons {
if pageCounter < page.Page && page.Page <= c.Pages {
pageCounter = page.Page
if page.Page == c.Page {
page.Class = "d3c-color-accent"
}
buttonsFiltered = append(buttonsFiltered, page)
}
}
c.buttons = buttonsFiltered
}