diff --git a/d2compiler/compile.go b/d2compiler/compile.go index be71308b8..584dd20af 100644 --- a/d2compiler/compile.go +++ b/d2compiler/compile.go @@ -42,6 +42,7 @@ func Compile(path string, r io.RuneReader, opts *CompileOptions) (*d2graph.Graph if err != nil { return nil, err } + g.SortObjectsByAST() g.SortEdgesByAST() return g, nil } diff --git a/d2graph/d2graph.go b/d2graph/d2graph.go index f8b66c110..9a89ed7e3 100644 --- a/d2graph/d2graph.go +++ b/d2graph/d2graph.go @@ -1460,6 +1460,21 @@ func (g *Graph) GetBoard(name string) *Graph { return nil } +func (g *Graph) SortObjectsByAST() { + objects := append([]*Object(nil), g.Objects...) + sort.Slice(objects, func(i, j int) bool { + o1 := objects[i] + o2 := objects[j] + if len(o1.References) == 0 || len(o2.References) == 0 { + return i < j + } + r1 := o1.References[0] + r2 := o2.References[0] + return r1.Key.Path[r1.KeyPathIndex].Unbox().GetRange().Before(r2.Key.Path[r2.KeyPathIndex].Unbox().GetRange()) + }) + g.Objects = objects +} + func (g *Graph) SortEdgesByAST() { edges := append([]*Edge(nil), g.Edges...) sort.Slice(edges, func(i, j int) bool { diff --git a/d2renderers/d2sketch/testdata/arrowheads/sketch.exp.svg b/d2renderers/d2sketch/testdata/arrowheads/sketch.exp.svg index 9181a6394..b817b2038 100644 --- a/d2renderers/d2sketch/testdata/arrowheads/sketch.exp.svg +++ b/d2renderers/d2sketch/testdata/arrowheads/sketch.exp.svg @@ -51,7 +51,7 @@ width="1810" height="779" viewBox="-102 -102 1810 779">