Skip to content

Commit 38c5ca3

Browse files
committed
working
1 parent eb895f0 commit 38c5ca3

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

d2js/js.go

+71
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,92 @@ import (
88
"strings"
99
"syscall/js"
1010

11+
"oss.terrastruct.com/d2/d2ast"
1112
"oss.terrastruct.com/d2/d2compiler"
1213
"oss.terrastruct.com/d2/d2format"
14+
"oss.terrastruct.com/d2/d2oracle"
1315
"oss.terrastruct.com/d2/d2parser"
1416
"oss.terrastruct.com/d2/d2target"
1517
"oss.terrastruct.com/d2/lib/urlenc"
1618
)
1719

1820
func main() {
21+
js.Global().Set("d2GetRefRanges", js.FuncOf(jsGetRefRanges))
1922
js.Global().Set("d2Compile", js.FuncOf(jsCompile))
2023
js.Global().Set("d2Parse", js.FuncOf(jsParse))
2124
js.Global().Set("d2Encode", js.FuncOf(jsEncode))
2225
js.Global().Set("d2Decode", js.FuncOf(jsDecode))
2326
select {}
2427
}
2528

29+
type jsRefRanges struct {
30+
Ranges []d2ast.Range `json:"ranges"`
31+
ParseError string `json:"parseError"`
32+
UserError string `json:"userError"`
33+
D2Error string `json:"d2Error"`
34+
}
35+
36+
func jsGetRefRanges(this js.Value, args []js.Value) interface{} {
37+
dsl := args[0].String()
38+
key := args[1].String()
39+
40+
mk, err := d2parser.ParseMapKey(key)
41+
if err != nil {
42+
ret := jsRefRanges{D2Error: err.Error()}
43+
str, _ := json.Marshal(ret)
44+
return string(str)
45+
}
46+
47+
g, err := d2compiler.Compile("", strings.NewReader(dsl), &d2compiler.CompileOptions{
48+
UTF16: true,
49+
})
50+
var pe d2parser.ParseError
51+
if err != nil {
52+
if errors.As(err, &pe) {
53+
serialized, _ := json.Marshal(err)
54+
// TODO
55+
ret := jsRefRanges{ParseError: string(serialized)}
56+
str, _ := json.Marshal(ret)
57+
return string(str)
58+
}
59+
ret := jsRefRanges{D2Error: err.Error()}
60+
str, _ := json.Marshal(ret)
61+
return string(str)
62+
}
63+
64+
var ranges []d2ast.Range
65+
if len(mk.Edges) == 1 {
66+
edge := d2oracle.GetEdge(g, key)
67+
if edge == nil {
68+
ret := jsRefRanges{D2Error: "edge not found"}
69+
str, _ := json.Marshal(ret)
70+
return string(str)
71+
}
72+
73+
for _, ref := range edge.References {
74+
ranges = append(ranges, ref.MapKey.Range)
75+
}
76+
} else {
77+
obj := d2oracle.GetObj(g, key)
78+
if obj == nil {
79+
ret := jsRefRanges{D2Error: "obj not found"}
80+
str, _ := json.Marshal(ret)
81+
return string(str)
82+
}
83+
84+
for _, ref := range obj.References {
85+
ranges = append(ranges, ref.Key.Range)
86+
}
87+
}
88+
89+
resp := jsRefRanges{
90+
Ranges: ranges,
91+
}
92+
93+
str, _ := json.Marshal(resp)
94+
return string(str)
95+
}
96+
2697
type jsObject struct {
2798
Result string `json:"result"`
2899
UserError string `json:"userError"`

0 commit comments

Comments
 (0)