apps/sipp/tui/content_model.go 1.7 K raw
1
package tui
2
3
import (
4
	"charm.land/bubbles/v2/viewport"
5
	tea "charm.land/bubbletea/v2"
6
	"charm.land/lipgloss/v2"
7
)
8
9
type contentModel struct {
10
	vp          viewport.Model
11
	highlighter *highlighter
12
	wrap        bool
13
14
	shortID string
15
	name    string
16
	body    string
17
}
18
19
func newContentModel() contentModel {
20
	return contentModel{vp: viewport.New(), highlighter: newHighlighter(), wrap: true}
21
}
22
23
func (c contentModel) Update(msg tea.Msg) (contentModel, tea.Cmd) {
24
	var cmd tea.Cmd
25
	c.vp, cmd = c.vp.Update(msg)
26
	return c, cmd
27
}
28
29
func (c *contentModel) SetSize(w, h int) {
30
	c.vp.SetWidth(w)
31
	c.vp.SetHeight(h)
32
	c.refresh()
33
}
34
35
func (c *contentModel) SetSnippet(s *Snippet) {
36
	if s == nil {
37
		c.shortID, c.name, c.body = "", "", ""
38
		c.vp.SetContent("")
39
		c.vp.GotoTop()
40
		return
41
	}
42
	c.shortID = s.ShortID
43
	c.name = s.Name
44
	c.body = s.Content
45
	c.vp.GotoTop()
46
	c.refresh()
47
}
48
49
func (c *contentModel) ToggleWrap() {
50
	c.wrap = !c.wrap
51
	c.vp.GotoTop()
52
	c.refresh()
53
}
54
55
func (c *contentModel) Wrap() bool { return c.wrap }
56
57
func (c *contentModel) Invalidate(shortID string) {
58
	if c.highlighter != nil {
59
		c.highlighter.invalidate(shortID)
60
	}
61
}
62
63
func (c *contentModel) refresh() {
64
	if c.body == "" {
65
		c.vp.SetContent("")
66
		return
67
	}
68
	body := c.body
69
	if c.highlighter != nil {
70
		body = c.highlighter.render(c.shortID, c.name, c.body)
71
	}
72
	if c.wrap && c.vp.Width() > 0 {
73
		body = lipgloss.NewStyle().Width(c.vp.Width()).Render(body)
74
	}
75
	c.vp.SetContent(body)
76
}
77
78
func (c contentModel) Header() string {
79
	if c.name != "" {
80
		return c.name
81
	}
82
	return c.shortID
83
}
84
85
func (c contentModel) View() string { return c.vp.View() }
86
87
func (c contentModel) ScrollUp(n int) contentModel {
88
	c.vp.ScrollUp(n)
89
	return c
90
}
91
92
func (c contentModel) ScrollDown(n int) contentModel {
93
	c.vp.ScrollDown(n)
94
	return c
95
}