Skip to content

Commit 2d0f7ce

Browse files
committedMay 1, 2023
d2parse
1 parent 2aa4800 commit 2d0f7ce

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
 

‎d2js/js.go

+64
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@ import (
1111
"oss.terrastruct.com/d2/d2compiler"
1212
"oss.terrastruct.com/d2/d2format"
1313
"oss.terrastruct.com/d2/d2parser"
14+
"oss.terrastruct.com/d2/d2target"
1415
"oss.terrastruct.com/d2/lib/urlenc"
1516
)
1617

1718
func main() {
1819
js.Global().Set("d2Compile", js.FuncOf(jsCompile))
20+
js.Global().Set("d2Parse", js.FuncOf(jsParse))
1921
js.Global().Set("d2Encode", js.FuncOf(jsEncode))
2022
js.Global().Set("d2Decode", js.FuncOf(jsDecode))
2123
select {}
@@ -27,6 +29,68 @@ type jsObject struct {
2729
D2Error string `json:"d2Error"`
2830
}
2931

32+
type jsParseResponse struct {
33+
DSL string `json:"dsl"`
34+
Texts []*d2target.MText `json:"texts"`
35+
ParseError string `json:"parseError"`
36+
UserError string `json:"userError"`
37+
D2Error string `json:"d2Error"`
38+
}
39+
40+
func jsParse(this js.Value, args []js.Value) interface{} {
41+
dsl := args[0].String()
42+
themeID := args[1].Int()
43+
44+
g, err := d2compiler.Compile("", strings.NewReader(dsl), &d2compiler.CompileOptions{
45+
UTF16: true,
46+
})
47+
var pe d2parser.ParseError
48+
if err != nil {
49+
if errors.As(err, &pe) {
50+
serialized, _ := json.Marshal(err)
51+
ret := jsParseResponse{ParseError: string(serialized)}
52+
str, _ := json.Marshal(ret)
53+
return string(str)
54+
}
55+
ret := jsParseResponse{D2Error: err.Error()}
56+
str, _ := json.Marshal(ret)
57+
return string(str)
58+
}
59+
60+
if len(g.Layers) > 0 || len(g.Scenarios) > 0 || len(g.Steps) > 0 {
61+
ret := jsParseResponse{UserError: "layers, scenarios, and steps are not yet supported. Coming soon."}
62+
str, _ := json.Marshal(ret)
63+
return string(str)
64+
}
65+
66+
for _, o := range g.Objects {
67+
if (o.Attributes.Top == nil) != (o.Attributes.Left == nil) {
68+
ret := jsParseResponse{UserError: `keywords "top" and "left" currently must be used together`}
69+
str, _ := json.Marshal(ret)
70+
return string(str)
71+
}
72+
}
73+
74+
err = g.ApplyTheme(int64(themeID))
75+
if err != nil {
76+
ret := jsParseResponse{D2Error: err.Error()}
77+
str, _ := json.Marshal(ret)
78+
return string(str)
79+
}
80+
81+
resp := jsParseResponse{
82+
Texts: g.Texts(),
83+
}
84+
85+
newDSL := d2format.Format(g.AST)
86+
if dsl != newDSL {
87+
resp.DSL = newDSL
88+
}
89+
90+
str, _ := json.Marshal(resp)
91+
return string(str)
92+
}
93+
3094
// TODO error passing
3195
// TODO recover panics
3296
func jsCompile(this js.Value, args []js.Value) interface{} {

0 commit comments

Comments
 (0)