Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP feat(examples): add p/moul/pageable #3414

Draft
wants to merge 21 commits into
base: master
Choose a base branch
from
254 changes: 55 additions & 199 deletions examples/gno.land/p/demo/avl/pager/pager.gno
Original file line number Diff line number Diff line change
@@ -1,223 +1,79 @@
// Package pager provides pagination functionality for AVL trees by implementing
// the pageable.Pageable interface. It allows for:
//
// - Forward and reverse pagination through AVL tree entries
// - Configurable page sizes
// - URL query parameter parsing for page navigation
// - Markdown-based pagination UI
//
// The package works by wrapping an avl.ITree instance to make it compatible with
// the pageable interface. To use it:
//
// tree := avl.NewTree()
// // ... add items to tree ...
//
// // Create a new pager with default page size of 10, forward ordering
// pager := pager.NewPager(tree, 10, false)
//
// // Get specific page
// page := pager.GetPage(1)
//
// // Or get page from URL query parameters
// page = pager.MustGetPageByPath("/path?page=1&size=20")
//
// // Generate pagination UI
// ui := page.Picker()
//
// This package is used in conjunction with gno.land/p/moul/pageable which provides
// the core pagination functionality.
package pager

import (
"math"
"net/url"
"strconv"

"gno.land/p/demo/avl"
"gno.land/p/demo/ufmt"
"gno.land/p/moul/pageable"
)

// Pager is a struct that holds the AVL tree and pagination parameters.
type Pager struct {
Tree avl.ITree
PageQueryParam string
SizeQueryParam string
DefaultPageSize int
Reversed bool
}

// Page represents a single page of results.
type Page struct {
Items []Item
PageNumber int
PageSize int
TotalItems int
TotalPages int
HasPrev bool
HasNext bool
Pager *Pager // Reference to the parent Pager
}

// Item represents a key-value pair in the AVL tree.
type Item struct {
Key string
Value interface{}
}

// NewPager creates a new Pager with default values.
func NewPager(tree avl.ITree, defaultPageSize int, reversed bool) *Pager {
return &Pager{
Tree: tree,
PageQueryParam: "page",
SizeQueryParam: "size",
DefaultPageSize: defaultPageSize,
Reversed: reversed,
}
}

// GetPage retrieves a page of results from the AVL tree.
func (p *Pager) GetPage(pageNumber int) *Page {
return p.GetPageWithSize(pageNumber, p.DefaultPageSize)
func NewPager(tree avl.ITree, defaultPageSize int, reversed bool) *pageable.Pager {
wrappedTree := NewWrapper(tree)
return pageable.NewPager(wrappedTree, defaultPageSize, reversed)
}

func (p *Pager) GetPageWithSize(pageNumber, pageSize int) *Page {
totalItems := p.Tree.Size()
totalPages := int(math.Ceil(float64(totalItems) / float64(pageSize)))

page := &Page{
TotalItems: totalItems,
TotalPages: totalPages,
PageSize: pageSize,
Pager: p,
}

// pages without content
if pageSize < 1 {
return page
}

// page number provided is not available
if pageNumber < 1 {
page.HasNext = totalPages > 0
return page
}

// page number provided is outside the range of total pages
if pageNumber > totalPages {
page.PageNumber = pageNumber
page.HasPrev = pageNumber > 0
return page
}

startIndex := (pageNumber - 1) * pageSize
endIndex := startIndex + pageSize
if endIndex > totalItems {
endIndex = totalItems
}

items := []Item{}

if p.Reversed {
p.Tree.ReverseIterateByOffset(startIndex, endIndex-startIndex, func(key string, value interface{}) bool {
items = append(items, Item{Key: key, Value: value})
return false
})
} else {
p.Tree.IterateByOffset(startIndex, endIndex-startIndex, func(key string, value interface{}) bool {
items = append(items, Item{Key: key, Value: value})
return false
})
}

page.Items = items
page.PageNumber = pageNumber
page.HasPrev = pageNumber > 1
page.HasNext = pageNumber < totalPages
return page
// Wrapper adapts an avl.ITree to implement Pageable
type Wrapper struct {
tree avl.ITree
}

func (p *Pager) MustGetPageByPath(rawURL string) *Page {
page, err := p.GetPageByPath(rawURL)
if err != nil {
panic("invalid path")
}
return page
func NewWrapper(tree avl.ITree) *Wrapper {
return &Wrapper{tree: tree}
}

// GetPageByPath retrieves a page of results based on the query parameters in the URL path.
func (p *Pager) GetPageByPath(rawURL string) (*Page, error) {
pageNumber, pageSize, err := p.ParseQuery(rawURL)
if err != nil {
return nil, err
}
return p.GetPageWithSize(pageNumber, pageSize), nil
func (w *Wrapper) Size() int {
return w.tree.Size()
}

// Picker generates the Markdown UI for the page Picker
func (p *Page) Picker() string {
pageNumber := p.PageNumber
pageNumber = max(pageNumber, 1)

if p.TotalPages <= 1 {
return ""
func (w *Wrapper) IterateByOffset(offset int, count int, cb func(index interface{}, value interface{}) bool) bool {
if count == 0 {
return false
}

md := ""

if p.HasPrev {
// Always show the first page link
md += ufmt.Sprintf("[%d](?%s=%d) | ", 1, p.Pager.PageQueryParam, 1)

// Before
if p.PageNumber > 4 {
md += "… | "
}

if p.PageNumber > 3 {
md += ufmt.Sprintf("[%d](?%s=%d) | ", p.PageNumber-2, p.Pager.PageQueryParam, p.PageNumber-2)
}

if p.PageNumber > 2 {
md += ufmt.Sprintf("[%d](?%s=%d) | ", p.PageNumber-1, p.Pager.PageQueryParam, p.PageNumber-1)
}
size := w.tree.Size()
if size == 0 {
return false
}

if p.PageNumber > 0 && p.PageNumber <= p.TotalPages {
// Current page
md += ufmt.Sprintf("**%d**", p.PageNumber)
} else {
md += ufmt.Sprintf("_%d_", p.PageNumber)
if offset >= size {
return false
}

if p.HasNext {
md += " | "

if p.PageNumber < p.TotalPages-1 {
md += ufmt.Sprintf("[%d](?%s=%d) | ", p.PageNumber+1, p.Pager.PageQueryParam, p.PageNumber+1)
}

if p.PageNumber < p.TotalPages-2 {
md += ufmt.Sprintf("[%d](?%s=%d) | ", p.PageNumber+2, p.Pager.PageQueryParam, p.PageNumber+2)
}

if p.PageNumber < p.TotalPages-3 {
md += "… | "
}

// Always show the last page link
md += ufmt.Sprintf("[%d](?%s=%d)", p.TotalPages, p.Pager.PageQueryParam, p.TotalPages)
}

return md
}

// ParseQuery parses the URL to extract the page number and page size.
func (p *Pager) ParseQuery(rawURL string) (int, int, error) {
u, err := url.Parse(rawURL)
if err != nil {
return 1, p.DefaultPageSize, err
}

query := u.Query()
pageNumber := 1
pageSize := p.DefaultPageSize

if p.PageQueryParam != "" {
if pageStr := query.Get(p.PageQueryParam); pageStr != "" {
pageNumber, err = strconv.Atoi(pageStr)
if err != nil || pageNumber < 1 {
pageNumber = 1
}
}
}

if p.SizeQueryParam != "" {
if sizeStr := query.Get(p.SizeQueryParam); sizeStr != "" {
pageSize, err = strconv.Atoi(sizeStr)
if err != nil || pageSize < 1 {
pageSize = p.DefaultPageSize
}
}
// Use ReverseIterateByOffset for negative count
if count < 0 {
return w.tree.ReverseIterateByOffset(offset, -count, func(key string, value interface{}) bool {
return cb(key, value)
})
}

return pageNumber, pageSize, nil
}

func max(a, b int) int {
if a > b {
return a
}
return b
return w.tree.IterateByOffset(offset, count, func(key string, value interface{}) bool {
return cb(key, value)
})
}
Loading
Loading