-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewbuilder.go
98 lines (85 loc) · 2.25 KB
/
viewbuilder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package input
import (
"strings"
"github.com/charmbracelet/lipgloss"
)
type ViewBuilder struct {
view string
viewLen int
extraOffset int
rawView string
cursor int
cursorStyle lipgloss.Style
delimiter string
showCursor bool
}
func NewViewBuilder(
cursor int,
cursorStyle lipgloss.Style,
delimiter string,
showCursor bool,
) *ViewBuilder {
return &ViewBuilder{
cursor: cursor,
cursorStyle: cursorStyle,
delimiter: delimiter,
showCursor: showCursor,
}
}
func (v ViewBuilder) View() string {
if v.cursor == v.viewLen {
return v.view + v.cursorView(" ", lipgloss.NewStyle())
}
return v.view
}
func (v *ViewBuilder) Render(newRunes []rune, column int, style lipgloss.Style) {
offset := column - 1
if offset < 0 {
offset = 0
}
cursorPos := v.cursor
if offset+v.extraOffset > v.viewLen {
newRunes = append(
[]rune(strings.Repeat(string(v.delimiter), offset+v.extraOffset-v.viewLen)),
newRunes...)
}
if cursorPos >= v.viewLen && cursorPos < v.viewLen+len(newRunes) {
v.view += v.renderAllWithCursor(newRunes, cursorPos-v.viewLen, style)
} else {
v.view += style.Render(string(newRunes))
}
v.rawView += string(newRunes)
v.viewLen += len(newRunes)
}
func (v *ViewBuilder) ViewLen() int {
return v.viewLen
}
func (v *ViewBuilder) RenderPlaceholder(newRunes []rune, offset int, style lipgloss.Style) {
v.Render(newRunes, offset, style)
// Add offset to account for the extra characters we added to the view that aren't part of what the user typed
v.extraOffset += len(newRunes)
}
func (v ViewBuilder) Last() *byte {
if v.viewLen == 0 {
return nil
}
last := v.rawView[len(v.rawView)-1]
return &last
}
func (v ViewBuilder) renderWithCursor(runes []rune, cursorPos int, s lipgloss.Style) string {
view := v.cursorView(string(runes[cursorPos]), s)
view += s.Render(string(runes[cursorPos+1:]))
return view
}
func (v ViewBuilder) renderAllWithCursor(runes []rune, cursorPos int, s lipgloss.Style) string {
view := ""
view += s.Render(string(runes[:cursorPos]))
view += v.renderWithCursor(runes, cursorPos, s)
return view
}
func (v ViewBuilder) cursorView(view string, s lipgloss.Style) string {
if !v.showCursor {
return s.Render(view)
}
return v.cursorStyle.Inline(true).Reverse(true).Render(view)
}