Skip to content
Myr

main.go

This file

Path

examples/paginator/main.go

99 lines · 2.1 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

1package main23// A simple program demonstrating the paginator component from the Bubbles4// component library.56import (7	"fmt"8	"log"9	"strings"1011	"charm.land/bubbles/v2/paginator"12	"charm.land/lipgloss/v2"1314	tea "charm.land/bubbletea/v2"15)1617type styles struct {18	activeDot   lipgloss.Style19	inactiveDot lipgloss.Style20}2122func newStyles(bgIsDark bool) (s styles) {23	lightDark := lipgloss.LightDark(bgIsDark)2425	s.activeDot = lipgloss.NewStyle().Foreground(lightDark(lipgloss.Color("235"), lipgloss.Color("252"))).SetString("•")26	s.inactiveDot = s.activeDot.Foreground(lightDark(lipgloss.Color("250"), lipgloss.Color("238"))).SetString("•")27	return s28}2930type model struct {31	items     []string32	paginator paginator.Model33}3435func newModel() model {36	var items []string37	for i := 1; i < 101; i++ {38		text := fmt.Sprintf("Item %d", i)39		items = append(items, text)40	}4142	p := paginator.New()43	p.Type = paginator.Dots44	p.PerPage = 1045	p.SetTotalPages(len(items))4647	m := model{48		paginator: p,49		items:     items,50	}5152	m.updateStyles(true) // default to dark styles53	return m54}5556func (m *model) updateStyles(isDark bool) {57	styles := newStyles(isDark)58	m.paginator.ActiveDot = styles.activeDot.String()59	m.paginator.InactiveDot = styles.inactiveDot.String()60}6162func (m model) Init() tea.Cmd {63	return tea.RequestBackgroundColor64}6566func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {67	var cmd tea.Cmd68	switch msg := msg.(type) {69	case tea.BackgroundColorMsg:70		m.updateStyles(msg.IsDark())71		return m, nil72	case tea.KeyPressMsg:73		switch msg.String() {74		case "q", "esc", "ctrl+c":75			return m, tea.Quit76		}77	}78	m.paginator, cmd = m.paginator.Update(msg)79	return m, cmd80}8182func (m model) View() tea.View {83	var b strings.Builder84	b.WriteString("\n  Paginator Example\n\n")85	start, end := m.paginator.GetSliceBounds(len(m.items))86	for _, item := range m.items[start:end] {87		b.WriteString("  • " + item + "\n\n")88	}89	b.WriteString("  " + m.paginator.View())90	b.WriteString("\n\n  h/l ←/→ page • q: quit\n")91	return tea.NewView(b.String())92}9394func main() {95	p := tea.NewProgram(newModel())96	if _, err := p.Run(); err != nil {97		log.Fatal(err)98	}99}