This repository has been archived by the owner on Aug 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathrenderer.go
94 lines (71 loc) · 1.83 KB
/
renderer.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
package golive
import (
"bytes"
"fmt"
"html/template"
"golang.org/x/net/html"
)
type LiveState struct {
html *html.Node
text string
}
func (ls *LiveState) setText(text string) error {
var err error
ls.html, err = nodeFromString(text)
ls.text = text
return err
}
func (ls *LiveState) setHTML(node *html.Node) error {
var err error
ls.text, err = renderInnerHTML(node)
ls.html = node
return err
}
type LiveRenderer struct {
state *LiveState
template *template.Template
templateString string
formatters []func(t string) string
}
func (lr *LiveRenderer) setTemplate(t *template.Template, ts string) {
lr.template = t
lr.templateString = ts
}
func (lr *LiveRenderer) renderToText(data interface{}) (string, error) {
if lr.template == nil {
return "", fmt.Errorf("template is not defined in LiveRenderer")
}
s := bytes.NewBufferString("")
err := lr.template.Execute(s, data)
if err != nil {
err = fmt.Errorf("template execute: %w", err)
}
text := s.String()
for _, f := range lr.formatters {
text = f(text)
}
return text, err
}
func (lr *LiveRenderer) Render(data interface{}) (string, *html.Node, error) {
textRender, err := lr.renderToText(data)
if err != nil {
return "", nil, err
}
err = lr.state.setText(textRender)
return lr.state.text, lr.state.html, err
}
func (lr *LiveRenderer) LiveRender(data interface{}) (*diff, error) {
actualRender := lr.state.html
proposedRenderText, err := lr.renderToText(data)
err = lr.state.setText(proposedRenderText)
if err != nil {
return nil, fmt.Errorf("state set text: %w", err)
}
// TODO: maybe the right way to call a diff is calling based on state
diff := newDiff(actualRender)
diff.propose(lr.state.html)
return diff, nil
}
func (lr *LiveRenderer) useFormatter(f func(t string) string) {
lr.formatters = append(lr.formatters, f)
}