From 3b104046c5333b73ea12af42eaaef06ec85c313c Mon Sep 17 00:00:00 2001 From: Alexander Wang Date: Wed, 10 May 2023 16:11:10 -0700 Subject: [PATCH] save --- d2js/js.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/d2js/js.go b/d2js/js.go index 2c17196a8f..7aa664abcd 100644 --- a/d2js/js.go +++ b/d2js/js.go @@ -11,6 +11,7 @@ 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" @@ -18,6 +19,7 @@ import ( ) 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)) @@ -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"`