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