-
Notifications
You must be signed in to change notification settings - Fork 528
/
Copy pathlayout.go
1817 lines (1689 loc) · 49.9 KB
/
layout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package d2dagrelayout
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"math"
"sort"
"strings"
"log/slog"
"github.com/dop251/goja"
"oss.terrastruct.com/util-go/xdefer"
"oss.terrastruct.com/util-go/go2"
"oss.terrastruct.com/d2/d2graph"
"oss.terrastruct.com/d2/d2target"
"oss.terrastruct.com/d2/lib/geo"
"oss.terrastruct.com/d2/lib/label"
"oss.terrastruct.com/d2/lib/log"
"oss.terrastruct.com/d2/lib/shape"
)
//go:embed setup.js
var setupJS string
//go:embed dagre.js
var dagreJS string
const (
// Edge and spacing constants
EDGE_LABEL_GAP = 20
DEFAULT_PADDING = 20.
MIN_SPACING = 10.
// Rank separation thresholds
MIN_RANK_SEP = 70
RANK_GAP_BUFFER = 20
SPACING_THRESHOLD = 100.
)
type ConfigurableOpts struct {
NodeSep int `json:"nodesep"`
EdgeSep int `json:"edgesep"`
}
var DefaultOpts = ConfigurableOpts{
NodeSep: 60,
EdgeSep: 20,
}
type DagreNode struct {
ID string `json:"id"`
X float64 `json:"x"`
Y float64 `json:"y"`
Width float64 `json:"width"`
Height float64 `json:"height"`
}
type DagreEdge struct {
Points []*geo.Point `json:"points"`
}
type dagreOpts struct {
// for a top to bottom graph: ranksep is y spacing, nodesep is x spacing, edgesep is x spacing
ranksep int
// graph direction: tb (top to bottom)| bt | lr | rl
rankdir string
ConfigurableOpts
}
func DefaultLayout(ctx context.Context, g *d2graph.Graph) (err error) {
return Layout(ctx, g, nil)
}
func Layout(ctx context.Context, g *d2graph.Graph, opts *ConfigurableOpts) (err error) {
if opts == nil {
opts = &DefaultOpts
}
defer xdefer.Errorf(&err, "failed to dagre layout")
debugJS := false
vm := goja.New()
if _, err := vm.RunString(dagreJS); err != nil {
return err
}
if _, err := vm.RunString(setupJS); err != nil {
return err
}
rootAttrs := dagreOpts{
ConfigurableOpts: ConfigurableOpts{
EdgeSep: opts.EdgeSep,
NodeSep: opts.NodeSep,
},
}
isHorizontal := false
switch g.Root.Direction.Value {
case "down":
rootAttrs.rankdir = "TB"
case "right":
rootAttrs.rankdir = "LR"
isHorizontal = true
case "left":
rootAttrs.rankdir = "RL"
isHorizontal = true
case "up":
rootAttrs.rankdir = "BT"
default:
rootAttrs.rankdir = "TB"
}
// set label and icon positions for dagre
for _, obj := range g.Objects {
positionLabelsIcons(obj)
}
maxLabelWidth := 0
maxLabelHeight := 0
for _, edge := range g.Edges {
width := edge.LabelDimensions.Width
height := edge.LabelDimensions.Height
maxLabelWidth = go2.Max(maxLabelWidth, width)
maxLabelHeight = go2.Max(maxLabelHeight, height)
}
if !isHorizontal {
rootAttrs.ranksep = go2.Max(MIN_RANK_SEP, maxLabelHeight+RANK_GAP_BUFFER)
} else {
rootAttrs.ranksep = go2.Max(MIN_RANK_SEP, maxLabelWidth+RANK_GAP_BUFFER)
}
configJS := setGraphAttrs(rootAttrs)
if _, err := vm.RunString(configJS); err != nil {
return err
}
mapper := NewObjectMapper()
for _, obj := range g.Objects {
mapper.Register(obj)
}
loadScript := ""
for _, obj := range g.Objects {
loadScript += mapper.generateAddNodeLine(obj, int(obj.Width), int(obj.Height))
if obj.Parent != g.Root {
loadScript += mapper.generateAddParentLine(obj, obj.Parent)
}
}
for _, edge := range g.Edges {
src, dst := getEdgeEndpoints(g, edge)
width := edge.LabelDimensions.Width
height := edge.LabelDimensions.Height
numEdges := 0
for _, e := range g.Edges {
otherSrc, otherDst := getEdgeEndpoints(g, e)
if (otherSrc == src && otherDst == dst) || (otherSrc == dst && otherDst == src) {
numEdges++
}
}
// We want to leave some gap between multiple edges
if numEdges > 1 {
switch g.Root.Direction.Value {
case "down", "up", "":
width += EDGE_LABEL_GAP
case "left", "right":
height += EDGE_LABEL_GAP
}
}
loadScript += mapper.generateAddEdgeLine(src, dst, edge.AbsID(), width, height)
}
if debugJS {
log.Debug(ctx, "script", slog.Any("all", setupJS+configJS+loadScript))
}
if _, err := vm.RunString(loadScript); err != nil {
return err
}
if _, err := vm.RunString(`dagre.layout(g)`); err != nil {
if debugJS {
log.Warn(ctx, "layout error", slog.Any("err", err))
}
return err
}
for i := range g.Objects {
val, err := vm.RunString(fmt.Sprintf("JSON.stringify(g.node(g.nodes()[%d]))", i))
if err != nil {
return err
}
var dn DagreNode
if err := json.Unmarshal([]byte(val.String()), &dn); err != nil {
return err
}
if debugJS {
log.Debug(ctx, "graph", slog.Any("json", dn))
}
obj := mapper.ToObj(dn.ID)
// dagre gives center of node
obj.TopLeft = geo.NewPoint(math.Round(dn.X-dn.Width/2), math.Round(dn.Y-dn.Height/2))
obj.Width = math.Ceil(dn.Width)
obj.Height = math.Ceil(dn.Height)
}
for i, edge := range g.Edges {
val, err := vm.RunString(fmt.Sprintf("JSON.stringify(g.edge(g.edges()[%d]))", i))
if err != nil {
return err
}
var de DagreEdge
if err := json.Unmarshal([]byte(val.String()), &de); err != nil {
return err
}
if debugJS {
log.Debug(ctx, "graph", slog.Any("json", de))
}
points := make([]*geo.Point, len(de.Points))
for i := range de.Points {
if edge.SrcArrow && !edge.DstArrow {
points[len(de.Points)-i-1] = de.Points[i].Copy()
} else {
points[i] = de.Points[i].Copy()
}
}
startIndex, endIndex := 0, len(points)-1
start, end := points[startIndex], points[endIndex]
// chop where edge crosses the source/target boxes since container edges were routed to a descendant
if edge.Src != edge.Dst {
for i := 1; i < len(points); i++ {
segment := *geo.NewSegment(points[i-1], points[i])
if intersections := edge.Src.Box.Intersections(segment); len(intersections) > 0 {
start = intersections[0]
startIndex = i - 1
}
if intersections := edge.Dst.Box.Intersections(segment); len(intersections) > 0 {
end = intersections[0]
endIndex = i
break
}
}
}
points = points[startIndex : endIndex+1]
points[0] = start
points[len(points)-1] = end
edge.Route = points
}
adjustRankSpacing(g, float64(rootAttrs.ranksep), isHorizontal)
adjustCrossRankSpacing(g, float64(rootAttrs.ranksep), !isHorizontal)
fitContainerPadding(g, float64(rootAttrs.ranksep), isHorizontal)
for _, edge := range g.Edges {
points := edge.Route
startIndex, endIndex := 0, len(points)-1
start, end := points[startIndex], points[endIndex]
// arrowheads can appear broken if segments are very short from dagre routing a point just outside the shape
// to fix this, we try extending the previous segment into the shape instead of having a very short segment
if startIndex+2 < len(points) {
newStartingSegment := *geo.NewSegment(start, points[startIndex+1])
if newStartingSegment.Length() < d2graph.MIN_SEGMENT_LEN {
// we don't want a very short segment right next to the source because it will mess up the arrowhead
// instead we want to extend the next segment into the shape border if possible
nextStart := points[startIndex+1]
nextEnd := points[startIndex+2]
// Note: in other direction to extend towards source
nextSegment := *geo.NewSegment(nextStart, nextEnd)
v := nextSegment.ToVector()
extendedStart := nextEnd.ToVector().Add(v.AddLength(d2graph.MIN_SEGMENT_LEN)).ToPoint()
extended := *geo.NewSegment(nextEnd, extendedStart)
if intersections := edge.Src.Box.Intersections(extended); len(intersections) > 0 {
startIndex++
points[startIndex] = intersections[0]
start = points[startIndex]
}
}
}
if endIndex-2 >= 0 {
newEndingSegment := *geo.NewSegment(end, points[endIndex-1])
if newEndingSegment.Length() < d2graph.MIN_SEGMENT_LEN {
// extend the prev segment into the shape border if possible
prevStart := points[endIndex-2]
prevEnd := points[endIndex-1]
prevSegment := *geo.NewSegment(prevStart, prevEnd)
v := prevSegment.ToVector()
extendedEnd := prevStart.ToVector().Add(v.AddLength(d2graph.MIN_SEGMENT_LEN)).ToPoint()
extended := *geo.NewSegment(prevStart, extendedEnd)
if intersections := edge.Dst.Box.Intersections(extended); len(intersections) > 0 {
endIndex--
points[endIndex] = intersections[0]
end = points[endIndex]
}
}
}
var originalSrcTL, originalDstTL *geo.Point
// if the edge passes through 3d/multiple, use the offset box for tracing to border
if srcDx, srcDy := edge.Src.GetModifierElementAdjustments(); srcDx != 0 || srcDy != 0 {
if start.X > edge.Src.TopLeft.X+srcDx &&
start.Y < edge.Src.TopLeft.Y+edge.Src.Height-srcDy {
originalSrcTL = edge.Src.TopLeft.Copy()
edge.Src.TopLeft.X += srcDx
edge.Src.TopLeft.Y -= srcDy
}
}
if dstDx, dstDy := edge.Dst.GetModifierElementAdjustments(); dstDx != 0 || dstDy != 0 {
if end.X > edge.Dst.TopLeft.X+dstDx &&
end.Y < edge.Dst.TopLeft.Y+edge.Dst.Height-dstDy {
originalDstTL = edge.Dst.TopLeft.Copy()
edge.Dst.TopLeft.X += dstDx
edge.Dst.TopLeft.Y -= dstDy
}
}
startIndex, endIndex = edge.TraceToShape(points, startIndex, endIndex)
points = points[startIndex : endIndex+1]
// build a curved path from the dagre route
vectors := make([]geo.Vector, 0, len(points)-1)
for i := 1; i < len(points); i++ {
vectors = append(vectors, points[i-1].VectorTo(points[i]))
}
path := make([]*geo.Point, 0)
path = append(path, points[0])
if len(vectors) > 1 {
path = append(path, points[0].AddVector(vectors[0].Multiply(.8)))
for i := 1; i < len(vectors)-2; i++ {
p := points[i]
v := vectors[i]
path = append(path, p.AddVector(v.Multiply(.2)))
path = append(path, p.AddVector(v.Multiply(.5)))
path = append(path, p.AddVector(v.Multiply(.8)))
}
path = append(path, points[len(points)-2].AddVector(vectors[len(vectors)-1].Multiply(.2)))
edge.IsCurve = true
}
path = append(path, points[len(points)-1])
edge.Route = path
// compile needs to assign edge label positions
if edge.Label.Value != "" {
edge.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
}
// undo 3d/multiple offset
if originalSrcTL != nil {
edge.Src.TopLeft.X = originalSrcTL.X
edge.Src.TopLeft.Y = originalSrcTL.Y
}
if originalDstTL != nil {
edge.Dst.TopLeft.X = originalDstTL.X
edge.Dst.TopLeft.Y = originalDstTL.Y
}
}
return nil
}
func getEdgeEndpoints(g *d2graph.Graph, edge *d2graph.Edge) (*d2graph.Object, *d2graph.Object) {
// dagre doesn't work with edges to containers so we connect container edges to their first child instead (going all the way down)
// we will chop the edge where it intersects the container border so it only shows the edge from the container
src := edge.Src
for len(src.Children) > 0 && src.Class == nil && src.SQLTable == nil {
// We want to get the bottom node of sources, setting its rank higher than all children
src = getLongestEdgeChainTail(g, src)
}
dst := edge.Dst
for len(dst.Children) > 0 && dst.Class == nil && dst.SQLTable == nil {
dst = getLongestEdgeChainHead(g, dst)
}
if edge.SrcArrow && !edge.DstArrow {
// for `b <- a`, edge.Edge is `a -> b` and we expect this routing result
src, dst = dst, src
}
return src, dst
}
func setGraphAttrs(attrs dagreOpts) string {
return fmt.Sprintf(`g.setGraph({
ranksep: %d,
edgesep: %d,
nodesep: %d,
rankdir: "%s",
});
`,
attrs.ranksep,
attrs.ConfigurableOpts.EdgeSep,
attrs.ConfigurableOpts.NodeSep,
attrs.rankdir,
)
}
// getLongestEdgeChainHead finds the longest chain in a container and gets its head
// If there are multiple chains of the same length, get the head closest to the center
func getLongestEdgeChainHead(g *d2graph.Graph, container *d2graph.Object) *d2graph.Object {
rank := make(map[*d2graph.Object]int)
chainLength := make(map[*d2graph.Object]int)
for _, obj := range container.ChildrenArray {
isHead := true
for _, e := range g.Edges {
if inContainer(e.Src, container) != nil && inContainer(e.Dst, obj) != nil {
isHead = false
break
}
}
if !isHead {
continue
}
rank[obj] = 1
chainLength[obj] = 1
// BFS
queue := []*d2graph.Object{obj}
visited := make(map[*d2graph.Object]struct{})
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
if _, ok := visited[curr]; ok {
continue
}
visited[curr] = struct{}{}
for _, e := range g.Edges {
child := inContainer(e.Dst, container)
if child == curr {
continue
}
if child != nil && inContainer(e.Src, curr) != nil {
if rank[curr]+1 > rank[child] {
rank[child] = rank[curr] + 1
chainLength[obj] = go2.Max(chainLength[obj], rank[child])
}
queue = append(queue, child)
}
}
}
}
max := int(math.MinInt32)
for _, obj := range container.ChildrenArray {
if chainLength[obj] > max {
max = chainLength[obj]
}
}
var heads []*d2graph.Object
for i, obj := range container.ChildrenArray {
if rank[obj] == 1 && chainLength[obj] == max {
heads = append(heads, container.ChildrenArray[i])
}
}
if len(heads) > 0 {
return heads[int(math.Floor(float64(len(heads))/2.0))]
}
return container.ChildrenArray[0]
}
// getLongestEdgeChainTail gets the node at the end of the longest edge chain, because that will be the end of the container
// and is what external connections should connect with.
// If there are multiple of same length, get the one closest to the middle
func getLongestEdgeChainTail(g *d2graph.Graph, container *d2graph.Object) *d2graph.Object {
rank := make(map[*d2graph.Object]int)
for _, obj := range container.ChildrenArray {
isHead := true
for _, e := range g.Edges {
if inContainer(e.Src, container) != nil && inContainer(e.Dst, obj) != nil {
isHead = false
break
}
}
if !isHead {
continue
}
rank[obj] = 1
// BFS
queue := []*d2graph.Object{obj}
visited := make(map[*d2graph.Object]struct{})
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
if _, ok := visited[curr]; ok {
continue
}
visited[curr] = struct{}{}
for _, e := range g.Edges {
child := inContainer(e.Dst, container)
if child == curr {
continue
}
if child != nil && inContainer(e.Src, curr) != nil {
rank[child] = go2.Max(rank[child], rank[curr]+1)
queue = append(queue, child)
}
}
}
}
max := int(math.MinInt32)
for _, obj := range container.ChildrenArray {
if rank[obj] > max {
max = rank[obj]
}
}
var tails []*d2graph.Object
for i, obj := range container.ChildrenArray {
if rank[obj] == max {
tails = append(tails, container.ChildrenArray[i])
}
}
return tails[int(math.Floor(float64(len(tails))/2.0))]
}
func inContainer(obj, container *d2graph.Object) *d2graph.Object {
if obj == nil {
return nil
}
if obj == container {
return obj
}
if obj.Parent == container {
return obj
}
return inContainer(obj.Parent, container)
}
func positionLabelsIcons(obj *d2graph.Object) {
if obj.Icon != nil && obj.IconPosition == nil {
if len(obj.ChildrenArray) > 0 {
obj.IconPosition = go2.Pointer(label.OutsideTopLeft.String())
if obj.LabelPosition == nil {
obj.LabelPosition = go2.Pointer(label.OutsideTopRight.String())
return
}
} else if obj.SQLTable != nil || obj.Class != nil || obj.Language != "" {
obj.IconPosition = go2.Pointer(label.OutsideTopLeft.String())
} else {
obj.IconPosition = go2.Pointer(label.InsideMiddleCenter.String())
}
}
if obj.HasLabel() && obj.LabelPosition == nil {
if len(obj.ChildrenArray) > 0 {
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
} else if obj.HasOutsideBottomLabel() {
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
} else if obj.Icon != nil {
obj.LabelPosition = go2.Pointer(label.InsideTopCenter.String())
} else {
obj.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
}
if float64(obj.LabelDimensions.Width) > obj.Width || float64(obj.LabelDimensions.Height) > obj.Height {
if len(obj.ChildrenArray) > 0 {
obj.LabelPosition = go2.Pointer(label.OutsideTopCenter.String())
} else {
obj.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
}
}
}
}
func getRanks(g *d2graph.Graph, isHorizontal bool) (ranks [][]*d2graph.Object, objectRanks, startingParentRanks, endingParentRanks map[*d2graph.Object]int) {
alignedObjects := make(map[float64][]*d2graph.Object)
for _, obj := range g.Objects {
if !obj.IsContainer() {
if !isHorizontal {
y := math.Ceil(obj.TopLeft.Y + obj.Height/2)
alignedObjects[y] = append(alignedObjects[y], obj)
} else {
x := math.Ceil(obj.TopLeft.X + obj.Width/2)
alignedObjects[x] = append(alignedObjects[x], obj)
}
}
}
levels := make([]float64, 0, len(alignedObjects))
for l := range alignedObjects {
levels = append(levels, l)
}
sort.Slice(levels, func(i, j int) bool {
return levels[i] < levels[j]
})
ranks = make([][]*d2graph.Object, 0, len(levels))
objectRanks = make(map[*d2graph.Object]int)
for i, l := range levels {
for _, obj := range alignedObjects[l] {
objectRanks[obj] = i
}
ranks = append(ranks, alignedObjects[l])
}
startingParentRanks = make(map[*d2graph.Object]int)
endingParentRanks = make(map[*d2graph.Object]int)
for _, obj := range g.Objects {
if obj.IsContainer() {
continue
}
r := objectRanks[obj]
// update all ancestor's min/max ranks
for parent := obj.Parent; parent != nil && parent != g.Root; parent = parent.Parent {
if start, has := startingParentRanks[parent]; !has || r < start {
startingParentRanks[parent] = r
}
if end, has := endingParentRanks[parent]; !has || r > end {
endingParentRanks[parent] = r
}
}
}
return ranks, objectRanks, startingParentRanks, endingParentRanks
}
// shift everything down by distance if it is at or below start position
func shiftDown(g *d2graph.Graph, start, distance float64, isHorizontal bool) {
if isHorizontal {
for _, edge := range g.Edges {
first, last := edge.Route[0], edge.Route[len(edge.Route)-1]
if start <= first.X {
onStaticSrc := first.X == edge.Src.TopLeft.X+edge.Src.Width && edge.Src.TopLeft.X < start
if !onStaticSrc {
// src is not shifting and we are on src so don't shift
first.X += distance
}
}
if start <= last.X {
onStaticDst := last.X == edge.Dst.TopLeft.X+edge.Dst.Width && edge.Dst.TopLeft.X < start
if !onStaticDst {
last.X += distance
}
}
for i := 1; i < len(edge.Route)-1; i++ {
p := edge.Route[i]
if p.X < start {
continue
}
p.X += distance
}
}
for _, obj := range g.Objects {
if obj.TopLeft.X < start {
continue
}
obj.TopLeft.X += distance
}
} else {
for _, edge := range g.Edges {
first, last := edge.Route[0], edge.Route[len(edge.Route)-1]
if start <= first.Y {
onStaticSrc := first.Y == edge.Src.TopLeft.Y+edge.Src.Height && edge.Src.TopLeft.Y < start
if !onStaticSrc {
// src is not shifting and we are on src so don't shift
first.Y += distance
}
}
if start <= last.Y {
onStaticDst := last.Y == edge.Dst.TopLeft.Y+edge.Dst.Height && edge.Dst.TopLeft.Y < start
if !onStaticDst {
last.Y += distance
}
}
for i := 1; i < len(edge.Route)-1; i++ {
p := edge.Route[i]
if p.Y < start {
continue
}
p.Y += distance
}
}
for _, obj := range g.Objects {
if obj.TopLeft.Y < start {
continue
}
obj.TopLeft.Y += distance
}
}
}
func shiftUp(g *d2graph.Graph, start, distance float64, isHorizontal bool) {
if isHorizontal {
for _, edge := range g.Edges {
first, last := edge.Route[0], edge.Route[len(edge.Route)-1]
if first.X <= start {
onStaticSrc := first.X == edge.Src.TopLeft.X && start < edge.Src.TopLeft.X+edge.Src.Width
if !onStaticSrc {
// src is not shifting and we are on src so don't shift
first.X -= distance
}
}
if last.X <= start {
onStaticDst := last.X == edge.Dst.TopLeft.X && start < edge.Dst.TopLeft.X+edge.Dst.Width
if !onStaticDst {
last.X -= distance
}
}
for i := 1; i < len(edge.Route)-1; i++ {
p := edge.Route[i]
if start < p.X {
continue
}
p.X -= distance
}
}
for _, obj := range g.Objects {
if start < obj.TopLeft.X {
continue
}
obj.TopLeft.X -= distance
}
} else {
for _, edge := range g.Edges {
first, last := edge.Route[0], edge.Route[len(edge.Route)-1]
if first.Y <= start {
// don't shift first edge point if src is not shifting and we are on src
onStaticSrc := first.Y == edge.Src.TopLeft.Y && start < edge.Src.TopLeft.Y+edge.Src.Height
if !onStaticSrc {
first.Y -= distance
}
}
if last.Y <= start {
onStaticDst := last.Y == edge.Dst.TopLeft.Y && start < edge.Dst.TopLeft.Y
if !onStaticDst {
last.Y -= distance
}
}
for i := 1; i < len(edge.Route)-1; i++ {
p := edge.Route[i]
// for _, p := range edge.Route {
if start < p.Y {
continue
}
p.Y -= distance
}
}
for _, obj := range g.Objects {
if start < obj.TopLeft.Y {
continue
}
obj.TopLeft.Y -= distance
}
}
}
// shift down everything that is below start
// shift all nodes that are reachable via an edge or being directly below a shifting node or expanding container
// expand containers to wrap shifted nodes
func shiftReachableDown(g *d2graph.Graph, obj *d2graph.Object, start, distance float64, isHorizontal, isMargin bool) map[*d2graph.Object]struct{} {
q := []*d2graph.Object{obj}
needsMove := make(map[*d2graph.Object]struct{})
seen := make(map[*d2graph.Object]struct{})
shifted := make(map[*d2graph.Object]struct{})
shiftedEdges := make(map[*d2graph.Edge]struct{})
queue := func(o *d2graph.Object) {
if _, in := seen[o]; in {
return
}
q = append(q, o)
}
// if object below is within this distance after shifting, also shift it
checkBelow := func(curr *d2graph.Object) {
currBottom := curr.TopLeft.Y + curr.Height
currRight := curr.TopLeft.X + curr.Width
if isHorizontal {
originalRight := currRight
if _, in := shifted[curr]; in {
originalRight -= distance
}
for _, other := range g.Objects {
if other == curr || curr.IsDescendantOf(other) {
continue
}
if originalRight < other.TopLeft.X &&
other.TopLeft.X < originalRight+distance+SPACING_THRESHOLD &&
curr.TopLeft.Y < other.TopLeft.Y+other.Height &&
other.TopLeft.Y < currBottom {
queue(other)
}
}
} else {
originalBottom := currBottom
if _, in := shifted[curr]; in {
originalBottom -= distance
}
for _, other := range g.Objects {
if other == curr || curr.IsDescendantOf(other) {
continue
}
if originalBottom < other.TopLeft.Y &&
other.TopLeft.Y < originalBottom+distance+SPACING_THRESHOLD &&
curr.TopLeft.X < other.TopLeft.X+other.Width &&
other.TopLeft.X < currRight {
queue(other)
}
}
}
}
processQueue := func() {
for len(q) > 0 {
curr := q[0]
q = q[1:]
if _, was := seen[curr]; was {
continue
}
// skip other objects behind start
if curr != obj {
if _, in := needsMove[curr]; !in {
if isHorizontal {
if curr.TopLeft.X < start {
continue
}
} else {
if curr.TopLeft.Y < start {
continue
}
}
}
}
if isHorizontal {
_, shift := needsMove[curr]
if !shift {
if !isMargin {
shift = start < curr.TopLeft.X
} else {
shift = start <= curr.TopLeft.X
}
}
if shift {
curr.TopLeft.X += distance
shifted[curr] = struct{}{}
}
} else {
_, shift := needsMove[curr]
if !shift {
if !isMargin {
shift = start < curr.TopLeft.Y
} else {
shift = start <= curr.TopLeft.Y
}
}
if shift {
curr.TopLeft.Y += distance
shifted[curr] = struct{}{}
}
}
seen[curr] = struct{}{}
if curr.Parent != g.Root && !curr.IsDescendantOf(obj) {
queue(curr.Parent)
}
for _, child := range curr.ChildrenArray {
queue(child)
}
for _, e := range g.Edges {
if _, in := shiftedEdges[e]; in {
continue
}
if e.Src == curr && e.Dst == curr {
if isHorizontal {
for _, p := range e.Route {
p.X += distance
}
} else {
for _, p := range e.Route {
p.Y += distance
}
}
shiftedEdges[e] = struct{}{}
continue
} else if e.Src == curr {
last := e.Route[len(e.Route)-1]
if isHorizontal {
if start <= last.X &&
e.Dst.TopLeft.X+e.Dst.Width < last.X+distance {
needsMove[e.Dst] = struct{}{}
}
} else {
if start <= last.Y &&
e.Dst.TopLeft.Y+e.Dst.Height < last.Y+distance {
needsMove[e.Dst] = struct{}{}
}
}
queue(e.Dst)
first := e.Route[0]
startIndex := 0
_, wasShifted := shifted[curr]
if isHorizontal {
if wasShifted && first.X < curr.TopLeft.X && first.X < start {
first.X += distance
startIndex++
}
for i := startIndex; i < len(e.Route); i++ {
p := e.Route[i]
if start <= p.X {
p.X += distance
}
}
} else {
if wasShifted && first.Y < curr.TopLeft.Y && first.Y < start {
first.Y += distance
startIndex++
}
for i := startIndex; i < len(e.Route); i++ {
p := e.Route[i]
if start <= p.Y {
p.Y += distance
}
}
}
shiftedEdges[e] = struct{}{}
} else if e.Dst == curr {
first := e.Route[0]
if isHorizontal {
if start <= first.X &&
e.Src.TopLeft.X+e.Src.Width < first.X+distance {
needsMove[e.Src] = struct{}{}
}
} else {
if start <= first.Y &&
e.Src.TopLeft.Y+e.Src.Height < first.Y+distance {
needsMove[e.Src] = struct{}{}
}
}
queue(e.Src)
last := e.Route[len(e.Route)-1]
endIndex := len(e.Route)
_, wasShifted := shifted[curr]
if isHorizontal {
if wasShifted && last.X < curr.TopLeft.X && last.X < start {
last.X += distance
endIndex--
}
for i := 0; i < endIndex; i++ {
p := e.Route[i]
if start <= p.X {
p.X += distance
}
}
} else {
if wasShifted && last.Y < curr.TopLeft.Y && last.Y < start {
last.Y += distance
endIndex--
}
for i := 0; i < endIndex; i++ {
p := e.Route[i]
if start <= p.Y {
p.Y += distance
}
}
}
shiftedEdges[e] = struct{}{}
}
}
// check for nodes below that need to move from the shift
checkBelow(curr)
}
}
processQueue()
grown := make(map[*d2graph.Object]struct{})
for o := range seen {
if o.Parent == g.Root {
continue
}
if _, in := shifted[o.Parent]; in {
continue
}
if _, in := grown[o.Parent]; in {
continue
}