-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
100 lines (88 loc) · 2.33 KB
/
parse.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
package uidoc
import (
"encoding/json"
"fmt"
"github.com/andlabs/ui"
)
type parseEle struct {
Type string
Margins float64
MarginTop, MarginRight, MarginBottom, MarginLeft *float64
Paddings float64
PaddingTop, PaddingRight, PaddingBottom, PaddingLeft *float64
Mode string
// Group Properties
Children []parseEle
// Text Properties
Text string
FontFamily string
FontSize float64
FontWeight string
}
func Parse(data []byte) (ele Element, err error) {
defer func() {
if v := recover(); v != nil {
err = v.(error)
}
}()
var root parseEle
if err := json.Unmarshal(data, &root); err != nil {
return nil, err
}
ele = root.Element()
return
}
func (p parseEle) Element() Element {
switch p.Type {
case "Text":
f := &ui.FontDescriptor{
Family: p.FontFamily,
Size: p.FontSize,
}
switch p.FontWeight {
case "Bold":
f.Weight = ui.TextWeightBold
case "Normal", "":
f.Weight = ui.TextWeightNormal
}
base := NewText(p.Text, ui.LoadClosestFont(f))
base.ElementBase = parseElementBase(p)
return base
case "Group":
children := make([]Element, len(p.Children))
for i, child := range p.Children {
children[i] = child.Element()
}
base := NewGroup(children)
base.ElementBase = parseElementBase(p)
return base
default:
panic(fmt.Errorf("Unknown Type %v", p.Type))
}
}
func parseElementBase(p parseEle) ElementBase {
base := ElementBase{}
base.MarginTop = marginVal(p.Margins, p.MarginTop)
base.MarginRight = marginVal(p.Margins, p.MarginRight)
base.MarginBottom = marginVal(p.Margins, p.MarginBottom)
base.MarginLeft = marginVal(p.Margins, p.MarginLeft)
base.PaddingTop = marginVal(p.Paddings, p.PaddingTop)
base.PaddingRight = marginVal(p.Paddings, p.PaddingRight)
base.PaddingBottom = marginVal(p.Paddings, p.PaddingBottom)
base.PaddingLeft = marginVal(p.Paddings, p.PaddingLeft)
switch p.Mode {
case "Block", "":
base.LayoutMode = LayoutBlock
case "Inline":
base.LayoutMode = LayoutInline
default:
panic(fmt.Errorf("Unknown Layout Mode %v", p.Mode))
}
return base
}
func marginVal(overall float64, specific *float64) float64 {
if specific != nil {
return *specific
}
return overall
}