Skip to content
Myr

main.go

This file

Path

examples/pager/main.go

134 lines · 3.7 KiB · Go

Last changed by

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

History of this file

Take it

1package main23// An example program demonstrating the pager component from the Bubbles4// component library.56import (7	"fmt"8	"os"9	"regexp"10	"strings"1112	"charm.land/bubbles/v2/viewport"13	tea "charm.land/bubbletea/v2"14	"charm.land/lipgloss/v2"15)1617var (18	titleStyle = func() lipgloss.Style {19		b := lipgloss.RoundedBorder()20		b.Right = "├"21		return lipgloss.NewStyle().BorderStyle(b).Padding(0, 1)22	}()2324	infoStyle = func() lipgloss.Style {25		b := lipgloss.RoundedBorder()26		b.Left = "┤"27		return titleStyle.BorderStyle(b)28	}()29)3031type model struct {32	content  string33	ready    bool34	viewport viewport.Model35}3637func (m model) Init() tea.Cmd {38	return nil39}4041func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {42	var (43		cmd  tea.Cmd44		cmds []tea.Cmd45	)4647	switch msg := msg.(type) {48	case tea.KeyPressMsg:49		if k := msg.String(); k == "ctrl+c" || k == "q" || k == "esc" {50			return m, tea.Quit51		}5253	case tea.WindowSizeMsg:54		headerHeight := lipgloss.Height(m.headerView())55		footerHeight := lipgloss.Height(m.footerView())56		verticalMarginHeight := headerHeight + footerHeight5758		if !m.ready {59			// Since this program is using the full size of the viewport we60			// need to wait until we've received the window dimensions before61			// we can initialize the viewport. The initial dimensions come in62			// quickly, though asynchronously, which is why we wait for them63			// here.64			m.viewport = viewport.New(viewport.WithWidth(msg.Width), viewport.WithHeight(msg.Height-verticalMarginHeight))65			m.viewport.YPosition = headerHeight66			m.viewport.LeftGutterFunc = func(info viewport.GutterContext) string {67				if info.Soft {68					return "     │ "69				}70				if info.Index >= info.TotalLines {71					return "   ~ │ "72				}73				return fmt.Sprintf("%4d │ ", info.Index+1)74			}75			m.viewport.HighlightStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("238")).Background(lipgloss.Color("34"))76			m.viewport.SelectedHighlightStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("238")).Background(lipgloss.Color("47"))77			m.viewport.SetContent(m.content)78			m.viewport.SetHighlights(regexp.MustCompile("artichoke").FindAllStringIndex(m.content, -1))79			m.viewport.HighlightNext()80			m.ready = true81		} else {82			m.viewport.SetWidth(msg.Width)83			m.viewport.SetHeight(msg.Height - verticalMarginHeight)84		}85	}8687	// Handle keyboard and mouse events in the viewport88	m.viewport, cmd = m.viewport.Update(msg)89	cmds = append(cmds, cmd)9091	return m, tea.Batch(cmds...)92}9394func (m model) View() tea.View {95	var v tea.View96	v.AltScreen = true                    // use the full size of the terminal in its "alternate screen buffer"97	v.MouseMode = tea.MouseModeCellMotion // turn on mouse support so we can track the mouse wheel98	if !m.ready {99		v.SetContent("\n  Initializing...")100	} else {101		v.SetContent(fmt.Sprintf("%s\n%s\n%s", m.headerView(), m.viewport.View(), m.footerView()))102	}103	return v104}105106func (m model) headerView() string {107	title := titleStyle.Render("Mr. Pager")108	line := strings.Repeat("─", max(0, m.viewport.Width()-lipgloss.Width(title)))109	return lipgloss.JoinHorizontal(lipgloss.Center, title, line)110}111112func (m model) footerView() string {113	info := infoStyle.Render(fmt.Sprintf("%3.f%%:%3.f%%", m.viewport.ScrollPercent()*100, m.viewport.HorizontalScrollPercent()*100))114	line := strings.Repeat("─", max(0, m.viewport.Width()-lipgloss.Width(info)))115	return lipgloss.JoinHorizontal(lipgloss.Center, line, info)116}117118func main() {119	// Load some text for our viewport120	content, err := os.ReadFile("artichoke.md")121	if err != nil {122		fmt.Println("could not load file:", err)123		os.Exit(1)124	}125126	p := tea.NewProgram(127		model{content: string(content)},128	)129130	if _, err := p.Run(); err != nil {131		fmt.Println("could not run program:", err)132		os.Exit(1)133	}134}