viewport.go

 1// Package viewport provides viewport UI components.
 2package viewport
 3
 4import (
 5	"github.com/charmbracelet/bubbles/v2/key"
 6	"github.com/charmbracelet/bubbles/v2/viewport"
 7	tea "github.com/charmbracelet/bubbletea/v2"
 8	"github.com/charmbracelet/soft-serve/pkg/ui/common"
 9)
10
11// Viewport represents a viewport component.
12type Viewport struct {
13	common common.Common
14	*viewport.Model
15}
16
17// New returns a new Viewport.
18func New(c common.Common) *Viewport {
19	vp := viewport.New()
20	vp.SetWidth(c.Width)
21	vp.SetHeight(c.Height)
22	vp.MouseWheelEnabled = true
23	return &Viewport{
24		common: c,
25		Model:  &vp,
26	}
27}
28
29// SetSize implements common.Component.
30func (v *Viewport) SetSize(width, height int) {
31	v.common.SetSize(width, height)
32	v.SetWidth(width)
33	v.SetHeight(height)
34}
35
36// Init implements tea.Model.
37func (v *Viewport) Init() tea.Cmd {
38	return nil
39}
40
41// Update implements tea.Model.
42func (v *Viewport) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
43	switch msg := msg.(type) {
44	case tea.KeyPressMsg:
45		switch {
46		case key.Matches(msg, v.common.KeyMap.GotoTop):
47			v.GotoTop()
48		case key.Matches(msg, v.common.KeyMap.GotoBottom):
49			v.GotoBottom()
50		}
51	}
52	vp, cmd := v.Model.Update(msg)
53	v.Model = &vp
54	return v, cmd
55}
56
57// View implements tea.Model.
58func (v *Viewport) View() string {
59	return v.Model.View()
60}
61
62// SetContent sets the viewport's content.
63func (v *Viewport) SetContent(content string) {
64	v.Model.SetContent(content)
65}
66
67// GotoTop moves the viewport to the top of the log.
68func (v *Viewport) GotoTop() {
69	v.Model.GotoTop()
70}
71
72// GotoBottom moves the viewport to the bottom of the log.
73func (v *Viewport) GotoBottom() {
74	v.Model.GotoBottom()
75}
76
77// HalfViewDown moves the viewport down by half the viewport height.
78func (v *Viewport) HalfViewDown() {
79	v.HalfPageDown()
80}
81
82// HalfViewUp moves the viewport up by half the viewport height.
83func (v *Viewport) HalfViewUp() {
84	v.HalfPageUp()
85}
86
87// ScrollPercent returns the viewport's scroll percentage.
88func (v *Viewport) ScrollPercent() float64 {
89	return v.Model.ScrollPercent()
90}