Skip to content

Commit

Permalink
feat: Introduce paginator options
Browse files Browse the repository at this point in the history
  • Loading branch information
nervo authored and meowgorithm committed Aug 27, 2024
1 parent f25096d commit 5110925
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
27 changes: 25 additions & 2 deletions paginator/paginator.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,12 @@ func (m Model) OnFirstPage() bool {
return m.Page == 0
}

// Option is used to set options in New.
type Option func(*Model)

// New creates a new model with defaults.
func New() Model {
return Model{
func New(opts ...Option) Model {
m := Model{
Type: Arabic,
Page: 0,
PerPage: 1,
Expand All @@ -142,13 +145,33 @@ func New() Model {
InactiveDot: "○",
ArabicFormat: "%d/%d",
}

for _, opt := range opts {
opt(&m)
}

return m
}

// NewModel creates a new model with defaults.
//
// Deprecated: use [New] instead.
var NewModel = New

// WithTotalPages sets the total pages.
func WithTotalPages(totalPages int) Option {
return func(m *Model) {
m.TotalPages = totalPages
}
}

// WithPerPage sets the total pages.
func WithPerPage(perPage int) Option {
return func(m *Model) {
m.PerPage = perPage
}
}

// Update is the Tea update function which binds keystrokes to pagination.
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
switch msg := msg.(type) {
Expand Down
26 changes: 26 additions & 0 deletions paginator/paginator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,32 @@ import (
tea "github.com/charmbracelet/bubbletea"
)

func TestNew(t *testing.T) {
model := New()

if model.PerPage != 1 {
t.Errorf("PerPage = %d, expected %d", model.PerPage, 1)
}
if model.TotalPages != 1 {
t.Errorf("TotalPages = %d, expected %d", model.TotalPages, 1)
}

perPage := 42
totalPages := 42

model = New(
WithPerPage(perPage),
WithTotalPages(totalPages),
)

if model.PerPage != perPage {
t.Errorf("PerPage = %d, expected %d", model.PerPage, perPage)
}
if model.TotalPages != totalPages {
t.Errorf("TotalPages = %d, expected %d", model.TotalPages, totalPages)
}
}

func TestSetTotalPages(t *testing.T) {
tests := []struct {
name string
Expand Down

0 comments on commit 5110925

Please sign in to comment.