forked from matthewmueller/jsx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsx_test.go
103 lines (88 loc) · 2.03 KB
/
jsx_test.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
99
100
101
102
103
package jsx_test
import (
"fmt"
"strconv"
"strings"
"testing"
"github.com/matthewmueller/diff"
"github.com/matthewmueller/jsx"
"github.com/matthewmueller/jsx/ast"
)
func ExampleParse() {
input := `export default () => <h1>hello world</h1>`
ast, err := jsx.Parse("input.jsx", input)
if err != nil {
fmt.Println(err)
}
fmt.Println(ast.String())
// Output:
// export default () => <h1>hello world</h1>
}
type Printer struct {
s strings.Builder
}
var _ ast.Visitor = (*Printer)(nil)
func (p *Printer) VisitScript(s *ast.Script) {
for _, fragment := range s.Body {
fragment.Visit(p)
}
}
func (p *Printer) VisitText(t *ast.Text) {
p.s.WriteString(t.Value)
}
func (p *Printer) VisitComment(c *ast.Comment) {
p.s.WriteString(c.String())
}
func (p *Printer) VisitField(f *ast.Field) {
p.s.WriteString(f.Name)
p.s.WriteString("=")
f.Value.Visit(p)
}
func (p *Printer) VisitStringValue(s *ast.StringValue) {
p.s.WriteString(s.Value)
}
func (p *Printer) VisitExpr(e *ast.Expr) {
p.s.WriteString("{")
for _, frag := range e.Fragments {
frag.Visit(p)
}
p.s.WriteString("}")
}
func (p *Printer) VisitBoolValue(b *ast.BoolValue) {
p.s.WriteString(strconv.Quote(strconv.FormatBool(b.Value)))
}
func (p *Printer) VisitElement(e *ast.Element) {
p.s.WriteString("<")
p.s.WriteString(e.Name)
if len(e.Attrs) > 0 {
p.s.WriteString(" ")
for i, attr := range e.Attrs {
if i > 0 {
p.s.WriteString(" ")
}
attr.Visit(p)
}
}
p.s.WriteString(">")
for _, child := range e.Children {
child.Visit(p)
}
p.s.WriteString("</")
p.s.WriteString(e.Name)
p.s.WriteString(">")
}
func (p *Printer) String() string {
return p.s.String()
}
func TestVisit(t *testing.T) {
input := `export default () => <style scoped>{"body { background: blue }"}</style>`
script, err := jsx.Parse("input.jsx", input)
if err != nil {
t.Fatal(err)
}
printer := &Printer{}
script.Visit(printer)
actual := printer.String()
expect := `export default () => <style scoped="true">{"body { background: blue }"}</style>`
diff.TestString(t, actual, expect)
}