Skip to content

Commit

Permalink
save
Browse files Browse the repository at this point in the history
  • Loading branch information
alixander committed Jun 5, 2023
1 parent 326f738 commit 3b10404
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions d2js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import (
"oss.terrastruct.com/d2/d2ast"
"oss.terrastruct.com/d2/d2compiler"
"oss.terrastruct.com/d2/d2format"
"oss.terrastruct.com/d2/d2graph"
"oss.terrastruct.com/d2/d2oracle"
"oss.terrastruct.com/d2/d2parser"
"oss.terrastruct.com/d2/d2target"
"oss.terrastruct.com/d2/lib/urlenc"
)

func main() {
js.Global().Set("d2GetObjOrder", js.FuncOf(jsGetObjOrder))
js.Global().Set("d2GetRefRanges", js.FuncOf(jsGetRefRanges))
js.Global().Set("d2Compile", js.FuncOf(jsCompile))
js.Global().Set("d2Parse", js.FuncOf(jsParse))
Expand All @@ -26,6 +28,61 @@ func main() {
select {}
}

type jsObjOrder struct {
Order []string `json:"order"`
Error string `json:"error"`
}

func jsGetObjOrder(this js.Value, args []js.Value) interface{} {
dsl := args[0].String()

g, err := d2compiler.Compile("", strings.NewReader(dsl), &d2compiler.CompileOptions{
UTF16: true,
})
if err != nil {
ret := jsObjOrder{Error: err.Error()}
str, _ := json.Marshal(ret)
return string(str)
}

var order []string

queue := []string{""}
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
var obj *d2graph.Object
if curr == "" {
obj = g.Root
} else {
mk, err := d2parser.ParseMapKey(curr)
if err != nil {
ret := jsObjOrder{Error: err.Error()}
str, _ := json.Marshal(ret)
return string(str)
}
var ok bool
obj, ok = g.Root.HasChild(d2graph.Key(mk.Key))
if !ok {
ret := jsObjOrder{Error: "not found"}
str, _ := json.Marshal(ret)
return string(str)
}
}
order = append(order, obj.AbsID())
for _, ch := range obj.ChildrenArray {
queue = append(queue, ch.AbsID())
}
}

resp := jsObjOrder{
Order: order,
}

str, _ := json.Marshal(resp)
return string(str)
}

type jsRefRanges struct {
Ranges []d2ast.Range `json:"ranges"`
ParseError string `json:"parseError"`
Expand Down

0 comments on commit 3b10404

Please sign in to comment.