forked from terrastruct/d2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd2svg.go
2320 lines (2135 loc) · 70.3 KB
/
d2svg.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
// d2svg implements an SVG renderer for d2 diagrams.
// The input is d2exporter's output
package d2svg
import (
"bytes"
_ "embed"
"errors"
"fmt"
"hash/fnv"
"html"
"io"
"sort"
"strings"
"math"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
"oss.terrastruct.com/d2/d2graph"
"oss.terrastruct.com/d2/d2renderers/d2fonts"
"oss.terrastruct.com/d2/d2renderers/d2latex"
"oss.terrastruct.com/d2/d2renderers/d2sketch"
"oss.terrastruct.com/d2/d2target"
"oss.terrastruct.com/d2/d2themes"
"oss.terrastruct.com/d2/d2themes/d2themescatalog"
"oss.terrastruct.com/d2/lib/color"
"oss.terrastruct.com/d2/lib/geo"
"oss.terrastruct.com/d2/lib/label"
"oss.terrastruct.com/d2/lib/shape"
"oss.terrastruct.com/d2/lib/svg"
"oss.terrastruct.com/d2/lib/textmeasure"
"oss.terrastruct.com/d2/lib/version"
)
const (
DEFAULT_PADDING = 100
appendixIconRadius = 16
)
var multipleOffset = geo.NewVector(d2target.MULTIPLE_OFFSET, -d2target.MULTIPLE_OFFSET)
//go:embed tooltip.svg
var TooltipIcon string
//go:embed link.svg
var LinkIcon string
//go:embed style.css
var BaseStylesheet string
//go:embed github-markdown.css
var MarkdownCSS string
//go:embed dots.txt
var dots string
//go:embed lines.txt
var lines string
//go:embed grain.txt
var grain string
//go:embed paper.txt
var paper string
type RenderOpts struct {
Pad *int64
Sketch *bool
Center *bool
ThemeID *int64
DarkThemeID *int64
ThemeOverrides *d2target.ThemeOverrides
DarkThemeOverrides *d2target.ThemeOverrides
Font string
// the svg will be scaled by this factor, if unset the svg will fit to screen
Scale *float64
// MasterID is passed when the diagram should use something other than its own hash for unique targeting
// Currently, that's when multi-boards are collapsed
MasterID string
}
func dimensions(diagram *d2target.Diagram, pad int) (left, top, width, height int) {
tl, br := diagram.BoundingBox()
left = tl.X - pad
top = tl.Y - pad
width = br.X - tl.X + pad*2
height = br.Y - tl.Y + pad*2
return left, top, width, height
}
func arrowheadMarkerID(isTarget bool, connection d2target.Connection) string {
var arrowhead d2target.Arrowhead
if isTarget {
arrowhead = connection.DstArrow
} else {
arrowhead = connection.SrcArrow
}
return fmt.Sprintf("mk-%s", hash(fmt.Sprintf("%s,%t,%d,%s",
arrowhead, isTarget, connection.StrokeWidth, connection.Stroke,
)))
}
func arrowheadMarker(isTarget bool, id string, connection d2target.Connection) string {
arrowhead := connection.DstArrow
if !isTarget {
arrowhead = connection.SrcArrow
}
strokeWidth := float64(connection.StrokeWidth)
width, height := arrowhead.Dimensions(strokeWidth)
var path string
switch arrowhead {
case d2target.ArrowArrowhead:
polygonEl := d2themes.NewThemableElement("polygon")
polygonEl.Fill = connection.Stroke
polygonEl.ClassName = "connection"
polygonEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
if isTarget {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f %f,%f",
0., 0.,
width, height/2,
0., height,
width/4, height/2,
)
} else {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f %f,%f",
0., height/2,
width, 0.,
width*3/4, height/2,
width, height,
)
}
path = polygonEl.Render()
case d2target.UnfilledTriangleArrowhead:
polygonEl := d2themes.NewThemableElement("polygon")
polygonEl.Fill = d2target.BG_COLOR
polygonEl.Stroke = connection.Stroke
polygonEl.ClassName = "connection"
polygonEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
inset := strokeWidth / 2
if isTarget {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f",
inset, inset,
width-inset, height/2.0,
inset, height-inset,
)
} else {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f",
width-inset, inset,
inset, height/2.0,
width-inset, height-inset,
)
}
path = polygonEl.Render()
case d2target.TriangleArrowhead:
polygonEl := d2themes.NewThemableElement("polygon")
polygonEl.Fill = connection.Stroke
polygonEl.ClassName = "connection"
polygonEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
if isTarget {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f",
0., 0.,
width, height/2.0,
0., height,
)
} else {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f",
width, 0.,
0., height/2.0,
width, height,
)
}
path = polygonEl.Render()
case d2target.LineArrowhead:
polylineEl := d2themes.NewThemableElement("polyline")
polylineEl.Fill = color.None
polylineEl.ClassName = "connection"
polylineEl.Stroke = connection.Stroke
polylineEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
if isTarget {
polylineEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f",
strokeWidth/2, strokeWidth/2,
width-strokeWidth/2, height/2,
strokeWidth/2, height-strokeWidth/2,
)
} else {
polylineEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f",
width-strokeWidth/2, strokeWidth/2,
strokeWidth/2, height/2,
width-strokeWidth/2, height-strokeWidth/2,
)
}
path = polylineEl.Render()
case d2target.FilledDiamondArrowhead:
polygonEl := d2themes.NewThemableElement("polygon")
polygonEl.ClassName = "connection"
polygonEl.Fill = connection.Stroke
polygonEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
if isTarget {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f %f,%f",
0., height/2.0,
width/2.0, 0.,
width, height/2.0,
width/2.0, height,
)
} else {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f %f,%f",
0., height/2.0,
width/2.0, 0.,
width, height/2.0,
width/2.0, height,
)
}
path = polygonEl.Render()
case d2target.DiamondArrowhead:
polygonEl := d2themes.NewThemableElement("polygon")
polygonEl.ClassName = "connection"
polygonEl.Fill = d2target.BG_COLOR
polygonEl.Stroke = connection.Stroke
polygonEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
if isTarget {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f %f,%f",
0., height/2.0,
width/2, height/8,
width, height/2.0,
width/2.0, height*0.9,
)
} else {
polygonEl.Points = fmt.Sprintf("%f,%f %f,%f %f,%f %f,%f",
width/8, height/2.0,
width*0.6, height/8,
width*1.1, height/2.0,
width*0.6, height*7/8,
)
}
path = polygonEl.Render()
case d2target.FilledCircleArrowhead:
radius := width / 2
circleEl := d2themes.NewThemableElement("circle")
circleEl.Cy = radius
circleEl.R = radius - strokeWidth/2
circleEl.Fill = connection.Stroke
circleEl.ClassName = "connection"
circleEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
if isTarget {
circleEl.Cx = radius + strokeWidth/2
} else {
circleEl.Cx = radius - strokeWidth/2
}
path = circleEl.Render()
case d2target.CircleArrowhead:
radius := width / 2
circleEl := d2themes.NewThemableElement("circle")
circleEl.Cy = radius
circleEl.R = radius - strokeWidth
circleEl.Fill = d2target.BG_COLOR
circleEl.Stroke = connection.Stroke
circleEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
if isTarget {
circleEl.Cx = radius + strokeWidth/2
} else {
circleEl.Cx = radius - strokeWidth/2
}
path = circleEl.Render()
case d2target.CfOne, d2target.CfMany, d2target.CfOneRequired, d2target.CfManyRequired:
offset := 3.0 + float64(connection.StrokeWidth)*1.8
var modifierEl *d2themes.ThemableElement
if arrowhead == d2target.CfOneRequired || arrowhead == d2target.CfManyRequired {
modifierEl = d2themes.NewThemableElement("path")
modifierEl.D = fmt.Sprintf("M%f,%f %f,%f",
offset, 0.,
offset, height,
)
modifierEl.Fill = d2target.BG_COLOR
modifierEl.Stroke = connection.Stroke
modifierEl.ClassName = "connection"
modifierEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
} else {
modifierEl = d2themes.NewThemableElement("circle")
modifierEl.Cx = offset/2.0 + 2.0
modifierEl.Cy = height / 2.0
modifierEl.R = offset / 2.0
modifierEl.Fill = d2target.BG_COLOR
modifierEl.Stroke = connection.Stroke
modifierEl.ClassName = "connection"
modifierEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
}
childPathEl := d2themes.NewThemableElement("path")
if arrowhead == d2target.CfMany || arrowhead == d2target.CfManyRequired {
childPathEl.D = fmt.Sprintf("M%f,%f %f,%f M%f,%f %f,%f M%f,%f %f,%f",
width-3.0, height/2.0,
width+offset, height/2.0,
offset+3.0, height/2.0,
width+offset, 0.,
offset+3.0, height/2.0,
width+offset, height,
)
} else {
childPathEl.D = fmt.Sprintf("M%f,%f %f,%f M%f,%f %f,%f",
width-3.0, height/2.0,
width+offset, height/2.0,
offset*2.0, 0.,
offset*2.0, height,
)
}
gEl := d2themes.NewThemableElement("g")
if !isTarget {
gEl.Transform = fmt.Sprintf("scale(-1) translate(-%f, -%f)", width, height)
}
gEl.Fill = d2target.BG_COLOR
gEl.Stroke = connection.Stroke
gEl.ClassName = "connection"
gEl.Attributes = fmt.Sprintf(`stroke-width="%d"`, connection.StrokeWidth)
gEl.Content = fmt.Sprintf("%s%s",
modifierEl.Render(), childPathEl.Render(),
)
path = gEl.Render()
default:
return ""
}
var refX float64
refY := height / 2
switch arrowhead {
case d2target.DiamondArrowhead:
if isTarget {
refX = width - 0.6*strokeWidth
} else {
refX = width/8 + 0.6*strokeWidth
}
width *= 1.1
default:
if isTarget {
refX = width - 1.5*strokeWidth
} else {
refX = 1.5 * strokeWidth
}
}
return strings.Join([]string{
fmt.Sprintf(`<marker id="%s" markerWidth="%f" markerHeight="%f" refX="%f" refY="%f"`,
id, width, height, refX, refY,
),
fmt.Sprintf(`viewBox="%f %f %f %f"`, 0., 0., width, height),
`orient="auto" markerUnits="userSpaceOnUse">`,
path,
"</marker>",
}, " ")
}
// compute the (dx, dy) adjustment to apply to get the arrowhead-adjusted end point
func arrowheadAdjustment(start, end *geo.Point, arrowhead d2target.Arrowhead, edgeStrokeWidth, shapeStrokeWidth int) *geo.Point {
distance := (float64(edgeStrokeWidth) + float64(shapeStrokeWidth)) / 2.0
if arrowhead != d2target.NoArrowhead {
distance += float64(edgeStrokeWidth)
}
v := geo.NewVector(end.X-start.X, end.Y-start.Y)
return v.Unit().Multiply(-distance).ToPoint()
}
func getArrowheadAdjustments(connection d2target.Connection, idToShape map[string]d2target.Shape) (srcAdj, dstAdj *geo.Point) {
route := connection.Route
srcShape := idToShape[connection.Src]
dstShape := idToShape[connection.Dst]
sourceAdjustment := arrowheadAdjustment(route[1], route[0], connection.SrcArrow, connection.StrokeWidth, srcShape.StrokeWidth)
targetAdjustment := arrowheadAdjustment(route[len(route)-2], route[len(route)-1], connection.DstArrow, connection.StrokeWidth, dstShape.StrokeWidth)
return sourceAdjustment, targetAdjustment
}
// returns the path's d attribute for the given connection
func pathData(connection d2target.Connection, srcAdj, dstAdj *geo.Point) string {
var path []string
route := connection.Route
path = append(path, fmt.Sprintf("M %f %f",
route[0].X+srcAdj.X,
route[0].Y+srcAdj.Y,
))
if connection.IsCurve {
i := 1
for ; i < len(route)-3; i += 3 {
path = append(path, fmt.Sprintf("C %f %f %f %f %f %f",
route[i].X, route[i].Y,
route[i+1].X, route[i+1].Y,
route[i+2].X, route[i+2].Y,
))
}
// final curve target adjustment
path = append(path, fmt.Sprintf("C %f %f %f %f %f %f",
route[i].X, route[i].Y,
route[i+1].X, route[i+1].Y,
route[i+2].X+dstAdj.X,
route[i+2].Y+dstAdj.Y,
))
} else {
for i := 1; i < len(route)-1; i++ {
prevSource := route[i-1]
prevTarget := route[i]
currTarget := route[i+1]
prevVector := prevSource.VectorTo(prevTarget)
currVector := prevTarget.VectorTo(currTarget)
dist := geo.EuclideanDistance(prevTarget.X, prevTarget.Y, currTarget.X, currTarget.Y)
connectionBorderRadius := connection.BorderRadius
units := math.Min(connectionBorderRadius, dist/2)
prevTranslations := prevVector.Unit().Multiply(units).ToPoint()
currTranslations := currVector.Unit().Multiply(units).ToPoint()
path = append(path, fmt.Sprintf("L %f %f",
prevTarget.X-prevTranslations.X,
prevTarget.Y-prevTranslations.Y,
))
// If the segment length is too small, instead of drawing 2 arcs, just skip this segment and bezier curve to the next one
if units < connectionBorderRadius && i < len(route)-2 {
nextTarget := route[i+2]
nextVector := geo.NewVector(nextTarget.X-currTarget.X, nextTarget.Y-currTarget.Y)
i++
nextTranslations := nextVector.Unit().Multiply(units).ToPoint()
// These 2 bezier control points aren't just at the corner -- they are reflected at the corner, which causes the curve to be ~tangent to the corner,
// which matches how the two arcs look
path = append(path, fmt.Sprintf("C %f %f %f %f %f %f",
// Control point
prevTarget.X+prevTranslations.X,
prevTarget.Y+prevTranslations.Y,
// Control point
currTarget.X-nextTranslations.X,
currTarget.Y-nextTranslations.Y,
// Where curve ends
currTarget.X+nextTranslations.X,
currTarget.Y+nextTranslations.Y,
))
} else {
path = append(path, fmt.Sprintf("S %f %f %f %f",
prevTarget.X,
prevTarget.Y,
prevTarget.X+currTranslations.X,
prevTarget.Y+currTranslations.Y,
))
}
}
lastPoint := route[len(route)-1]
path = append(path, fmt.Sprintf("L %f %f",
lastPoint.X+dstAdj.X,
lastPoint.Y+dstAdj.Y,
))
}
return strings.Join(path, " ")
}
func makeLabelMask(labelTL *geo.Point, width, height int, opacity float64) string {
fill := "black"
if opacity != 1 {
fill = fmt.Sprintf("rgba(0,0,0,%.2f)", opacity)
}
return fmt.Sprintf(`<rect x="%f" y="%f" width="%d" height="%d" fill="%s"></rect>`,
labelTL.X, labelTL.Y,
width,
height,
fill,
)
}
func drawConnection(writer io.Writer, labelMaskID string, connection d2target.Connection, markers map[string]struct{}, idToShape map[string]d2target.Shape, sketchRunner *d2sketch.Runner) (labelMask string, _ error) {
opacityStyle := ""
if connection.Opacity != 1.0 {
opacityStyle = fmt.Sprintf(" style='opacity:%f'", connection.Opacity)
}
classStr := ""
if len(connection.Classes) > 0 {
classStr = fmt.Sprintf(` class="%s"`, strings.Join(connection.Classes, " "))
}
fmt.Fprintf(writer, `<g id="%s"%s%s>`, svg.EscapeText(connection.ID), opacityStyle, classStr)
var markerStart string
if connection.SrcArrow != d2target.NoArrowhead {
id := arrowheadMarkerID(false, connection)
if _, in := markers[id]; !in {
marker := arrowheadMarker(false, id, connection)
if marker == "" {
panic(fmt.Sprintf("received empty arrow head marker for: %#v", connection))
}
fmt.Fprint(writer, marker)
markers[id] = struct{}{}
}
markerStart = fmt.Sprintf(`marker-start="url(#%s)" `, id)
}
var markerEnd string
if connection.DstArrow != d2target.NoArrowhead {
id := arrowheadMarkerID(true, connection)
if _, in := markers[id]; !in {
marker := arrowheadMarker(true, id, connection)
if marker == "" {
panic(fmt.Sprintf("received empty arrow head marker for: %#v", connection))
}
fmt.Fprint(writer, marker)
markers[id] = struct{}{}
}
markerEnd = fmt.Sprintf(`marker-end="url(#%s)" `, id)
}
var labelTL *geo.Point
if connection.Label != "" {
labelTL = connection.GetLabelTopLeft()
labelTL.X = math.Round(labelTL.X)
labelTL.Y = math.Round(labelTL.Y)
if label.FromString(connection.LabelPosition).IsOnEdge() {
labelMask = makeLabelMask(labelTL, connection.LabelWidth, connection.LabelHeight, 1)
} else {
labelMask = makeLabelMask(labelTL, connection.LabelWidth, connection.LabelHeight, 0.75)
}
}
srcAdj, dstAdj := getArrowheadAdjustments(connection, idToShape)
path := pathData(connection, srcAdj, dstAdj)
mask := fmt.Sprintf(`mask="url(#%s)"`, labelMaskID)
if sketchRunner != nil {
out, err := d2sketch.Connection(sketchRunner, connection, path, mask)
if err != nil {
return "", err
}
fmt.Fprint(writer, out)
// render sketch arrowheads separately
arrowPaths, err := d2sketch.Arrowheads(sketchRunner, connection, srcAdj, dstAdj)
if err != nil {
return "", err
}
fmt.Fprint(writer, arrowPaths)
} else {
animatedClass := ""
if connection.Animated {
animatedClass = " animated-connection"
}
pathEl := d2themes.NewThemableElement("path")
pathEl.D = path
pathEl.Fill = color.None
pathEl.Stroke = connection.Stroke
pathEl.ClassName = fmt.Sprintf("connection%s", animatedClass)
pathEl.Style = connection.CSSStyle()
pathEl.Attributes = fmt.Sprintf("%s%s%s", markerStart, markerEnd, mask)
fmt.Fprint(writer, pathEl.Render())
}
if connection.Label != "" {
fontClass := "text"
if connection.FontFamily == "mono" {
fontClass = "text-mono"
}
if connection.Bold {
fontClass += "-bold"
} else if connection.Italic {
fontClass += "-italic"
}
if connection.Underline {
fontClass += " text-underline"
}
if connection.Fill != color.Empty {
rectEl := d2themes.NewThemableElement("rect")
rectEl.X, rectEl.Y = labelTL.X, labelTL.Y
rectEl.Width, rectEl.Height = float64(connection.LabelWidth), float64(connection.LabelHeight)
rectEl.Fill = connection.Fill
fmt.Fprint(writer, rectEl.Render())
}
textEl := d2themes.NewThemableElement("text")
textEl.X = labelTL.X + float64(connection.LabelWidth)/2
textEl.Y = labelTL.Y + float64(connection.FontSize)
textEl.Fill = connection.GetFontColor()
textEl.ClassName = fontClass
textEl.Style = fmt.Sprintf("text-anchor:%s;font-size:%vpx", "middle", connection.FontSize)
textEl.Content = RenderText(connection.Label, textEl.X, float64(connection.LabelHeight))
fmt.Fprint(writer, textEl.Render())
}
if connection.SrcLabel != nil && connection.SrcLabel.Label != "" {
fmt.Fprint(writer, renderArrowheadLabel(connection, connection.SrcLabel.Label, false))
}
if connection.DstLabel != nil && connection.DstLabel.Label != "" {
fmt.Fprint(writer, renderArrowheadLabel(connection, connection.DstLabel.Label, true))
}
fmt.Fprintf(writer, `</g>`)
return
}
func renderArrowheadLabel(connection d2target.Connection, text string, isDst bool) string {
var width, height float64
if isDst {
width = float64(connection.DstLabel.LabelWidth)
height = float64(connection.DstLabel.LabelHeight)
} else {
width = float64(connection.SrcLabel.LabelWidth)
height = float64(connection.SrcLabel.LabelHeight)
}
labelTL := connection.GetArrowheadLabelPosition(isDst)
// svg text is positioned with the center of its baseline
baselineCenter := geo.Point{
X: labelTL.X + width/2.,
Y: labelTL.Y + float64(connection.FontSize),
}
textEl := d2themes.NewThemableElement("text")
textEl.X = baselineCenter.X
textEl.Y = baselineCenter.Y
textEl.Fill = d2target.FG_COLOR
if isDst {
if connection.DstLabel.Color != "" {
textEl.Fill = connection.DstLabel.Color
}
} else {
if connection.SrcLabel.Color != "" {
textEl.Fill = connection.SrcLabel.Color
}
}
textEl.ClassName = "text-italic"
textEl.Style = fmt.Sprintf("text-anchor:middle;font-size:%vpx", connection.FontSize)
textEl.Content = RenderText(text, textEl.X, height)
return textEl.Render()
}
func renderOval(tl *geo.Point, width, height float64, fill, fillPattern, stroke, style string) string {
el := d2themes.NewThemableElement("ellipse")
el.Rx = width / 2
el.Ry = height / 2
el.Cx = tl.X + el.Rx
el.Cy = tl.Y + el.Ry
el.Fill, el.Stroke = fill, stroke
el.FillPattern = fillPattern
el.ClassName = "shape"
el.Style = style
return el.Render()
}
func renderDoubleOval(tl *geo.Point, width, height float64, fill, fillStroke, stroke, style string) string {
var innerTL *geo.Point = tl.AddVector(geo.NewVector(d2target.INNER_BORDER_OFFSET, d2target.INNER_BORDER_OFFSET))
return renderOval(tl, width, height, fill, fillStroke, stroke, style) + renderOval(innerTL, width-10, height-10, fill, "", stroke, style)
}
func defineShadowFilter(writer io.Writer) {
fmt.Fprint(writer, `<defs>
<filter id="shadow-filter" width="200%" height="200%" x="-50%" y="-50%">
<feGaussianBlur stdDeviation="1.7 " in="SourceGraphic"></feGaussianBlur>
<feFlood flood-color="#3d4574" flood-opacity="0.4" result="ShadowFeFlood" in="SourceGraphic"></feFlood>
<feComposite in="ShadowFeFlood" in2="SourceAlpha" operator="in" result="ShadowFeComposite"></feComposite>
<feOffset dx="3" dy="5" result="ShadowFeOffset" in="ShadowFeComposite"></feOffset>
<feBlend in="SourceGraphic" in2="ShadowFeOffset" mode="normal" result="ShadowFeBlend"></feBlend>
</filter>
</defs>`)
}
func render3DRect(targetShape d2target.Shape) string {
moveTo := func(p d2target.Point) string {
return fmt.Sprintf("M%d,%d", p.X+targetShape.Pos.X, p.Y+targetShape.Pos.Y)
}
lineTo := func(p d2target.Point) string {
return fmt.Sprintf("L%d,%d", p.X+targetShape.Pos.X, p.Y+targetShape.Pos.Y)
}
// draw border all in one path to prevent overlapping sections
var borderSegments []string
borderSegments = append(borderSegments,
moveTo(d2target.Point{X: 0, Y: 0}),
)
for _, v := range []d2target.Point{
{X: d2target.THREE_DEE_OFFSET, Y: -d2target.THREE_DEE_OFFSET},
{X: targetShape.Width + d2target.THREE_DEE_OFFSET, Y: -d2target.THREE_DEE_OFFSET},
{X: targetShape.Width + d2target.THREE_DEE_OFFSET, Y: targetShape.Height - d2target.THREE_DEE_OFFSET},
{X: targetShape.Width, Y: targetShape.Height},
{X: 0, Y: targetShape.Height},
{X: 0, Y: 0},
{X: targetShape.Width, Y: 0},
{X: targetShape.Width, Y: targetShape.Height},
} {
borderSegments = append(borderSegments, lineTo(v))
}
// move to top right to draw last segment without overlapping
borderSegments = append(borderSegments,
moveTo(d2target.Point{X: targetShape.Width, Y: 0}),
)
borderSegments = append(borderSegments,
lineTo(d2target.Point{X: targetShape.Width + d2target.THREE_DEE_OFFSET, Y: -d2target.THREE_DEE_OFFSET}),
)
border := d2themes.NewThemableElement("path")
border.D = strings.Join(borderSegments, " ")
border.Fill = color.None
_, borderStroke := d2themes.ShapeTheme(targetShape)
border.Stroke = borderStroke
borderStyle := targetShape.CSSStyle()
border.Style = borderStyle
renderedBorder := border.Render()
// create mask from border stroke, to cut away from the shape fills
maskID := fmt.Sprintf("border-mask-%v", svg.EscapeText(targetShape.ID))
borderMask := strings.Join([]string{
fmt.Sprintf(`<defs><mask id="%s" maskUnits="userSpaceOnUse" x="%d" y="%d" width="%d" height="%d">`,
maskID, targetShape.Pos.X, targetShape.Pos.Y-d2target.THREE_DEE_OFFSET, targetShape.Width+d2target.THREE_DEE_OFFSET, targetShape.Height+d2target.THREE_DEE_OFFSET,
),
fmt.Sprintf(`<rect x="%d" y="%d" width="%d" height="%d" fill="white"></rect>`,
targetShape.Pos.X, targetShape.Pos.Y-d2target.THREE_DEE_OFFSET, targetShape.Width+d2target.THREE_DEE_OFFSET, targetShape.Height+d2target.THREE_DEE_OFFSET,
),
fmt.Sprintf(`<path d="%s" style="%s;stroke:#000;fill:none;opacity:1;"/></mask></defs>`,
strings.Join(borderSegments, ""), borderStyle),
}, "\n")
// render the main rectangle without stroke and the border mask
mainShape := d2themes.NewThemableElement("rect")
mainShape.X = float64(targetShape.Pos.X)
mainShape.Y = float64(targetShape.Pos.Y)
mainShape.Width = float64(targetShape.Width)
mainShape.Height = float64(targetShape.Height)
mainShape.SetMaskUrl(maskID)
mainShapeFill, _ := d2themes.ShapeTheme(targetShape)
mainShape.Fill = mainShapeFill
mainShape.FillPattern = targetShape.FillPattern
mainShape.Stroke = color.None
mainShape.Style = targetShape.CSSStyle()
mainShapeRendered := mainShape.Render()
// render the side shapes in the darkened color without stroke and the border mask
var sidePoints []string
for _, v := range []d2target.Point{
{X: 0, Y: 0},
{X: d2target.THREE_DEE_OFFSET, Y: -d2target.THREE_DEE_OFFSET},
{X: targetShape.Width + d2target.THREE_DEE_OFFSET, Y: -d2target.THREE_DEE_OFFSET},
{X: targetShape.Width + d2target.THREE_DEE_OFFSET, Y: targetShape.Height - d2target.THREE_DEE_OFFSET},
{X: targetShape.Width, Y: targetShape.Height},
{X: targetShape.Width, Y: 0},
} {
sidePoints = append(sidePoints,
fmt.Sprintf("%d,%d", v.X+targetShape.Pos.X, v.Y+targetShape.Pos.Y),
)
}
darkerColor, err := color.Darken(targetShape.Fill)
if err != nil {
darkerColor = targetShape.Fill
}
sideShape := d2themes.NewThemableElement("polygon")
sideShape.Fill = darkerColor
sideShape.Points = strings.Join(sidePoints, " ")
sideShape.SetMaskUrl(maskID)
sideShape.Style = targetShape.CSSStyle()
renderedSides := sideShape.Render()
return borderMask + mainShapeRendered + renderedSides + renderedBorder
}
func render3DHexagon(targetShape d2target.Shape) string {
moveTo := func(p d2target.Point) string {
return fmt.Sprintf("M%d,%d", p.X+targetShape.Pos.X, p.Y+targetShape.Pos.Y)
}
lineTo := func(p d2target.Point) string {
return fmt.Sprintf("L%d,%d", p.X+targetShape.Pos.X, p.Y+targetShape.Pos.Y)
}
scale := func(n int, f float64) int {
return int(float64(n) * f)
}
halfYFactor := 43.6 / 87.3
// draw border all in one path to prevent overlapping sections
var borderSegments []string
// start from the top-left
borderSegments = append(borderSegments,
moveTo(d2target.Point{X: scale(targetShape.Width, 0.25), Y: 0}),
)
Y_OFFSET := d2target.THREE_DEE_OFFSET / 2
// The following iterates through the sidepoints in clockwise order from top-left, then the main points in clockwise order from bottom-right
for _, v := range []d2target.Point{
{X: scale(targetShape.Width, 0.25) + d2target.THREE_DEE_OFFSET, Y: -Y_OFFSET},
{X: scale(targetShape.Width, 0.75) + d2target.THREE_DEE_OFFSET, Y: -Y_OFFSET},
{X: targetShape.Width + d2target.THREE_DEE_OFFSET, Y: scale(targetShape.Height, halfYFactor) - Y_OFFSET},
{X: scale(targetShape.Width, 0.75) + d2target.THREE_DEE_OFFSET, Y: targetShape.Height - Y_OFFSET},
{X: scale(targetShape.Width, 0.75), Y: targetShape.Height},
{X: scale(targetShape.Width, 0.25), Y: targetShape.Height},
{X: 0, Y: scale(targetShape.Height, halfYFactor)},
{X: scale(targetShape.Width, 0.25), Y: 0},
{X: scale(targetShape.Width, 0.75), Y: 0},
{X: targetShape.Width, Y: scale(targetShape.Height, halfYFactor)},
{X: scale(targetShape.Width, 0.75), Y: targetShape.Height},
} {
borderSegments = append(borderSegments, lineTo(v))
}
for _, v := range []d2target.Point{
{X: scale(targetShape.Width, 0.75), Y: 0},
{X: targetShape.Width, Y: scale(targetShape.Height, halfYFactor)},
{X: scale(targetShape.Width, 0.75), Y: targetShape.Height},
} {
borderSegments = append(borderSegments, moveTo(v))
borderSegments = append(borderSegments, lineTo(
d2target.Point{X: v.X + d2target.THREE_DEE_OFFSET, Y: v.Y - Y_OFFSET},
))
}
border := d2themes.NewThemableElement("path")
border.D = strings.Join(borderSegments, " ")
border.Fill = color.None
_, borderStroke := d2themes.ShapeTheme(targetShape)
border.Stroke = borderStroke
borderStyle := targetShape.CSSStyle()
border.Style = borderStyle
renderedBorder := border.Render()
var mainPoints []string
for _, v := range []d2target.Point{
{X: scale(targetShape.Width, 0.25), Y: 0},
{X: scale(targetShape.Width, 0.75), Y: 0},
{X: targetShape.Width, Y: scale(targetShape.Height, halfYFactor)},
{X: scale(targetShape.Width, 0.75), Y: targetShape.Height},
{X: scale(targetShape.Width, 0.25), Y: targetShape.Height},
{X: 0, Y: scale(targetShape.Height, halfYFactor)},
} {
mainPoints = append(mainPoints,
fmt.Sprintf("%d,%d", v.X+targetShape.Pos.X, v.Y+targetShape.Pos.Y),
)
}
mainPointsPoly := strings.Join(mainPoints, " ")
// create mask from border stroke, to cut away from the shape fills
maskID := fmt.Sprintf("border-mask-%v", svg.EscapeText(targetShape.ID))
borderMask := strings.Join([]string{
fmt.Sprintf(`<defs><mask id="%s" maskUnits="userSpaceOnUse" x="%d" y="%d" width="%d" height="%d">`,
maskID, targetShape.Pos.X, targetShape.Pos.Y-d2target.THREE_DEE_OFFSET, targetShape.Width+d2target.THREE_DEE_OFFSET, targetShape.Height+d2target.THREE_DEE_OFFSET,
),
fmt.Sprintf(`<rect x="%d" y="%d" width="%d" height="%d" fill="white"></rect>`,
targetShape.Pos.X, targetShape.Pos.Y-d2target.THREE_DEE_OFFSET, targetShape.Width+d2target.THREE_DEE_OFFSET, targetShape.Height+d2target.THREE_DEE_OFFSET,
),
fmt.Sprintf(`<path d="%s" style="%s;stroke:#000;fill:none;opacity:1;"/></mask></defs>`,
strings.Join(borderSegments, ""), borderStyle),
}, "\n")
// render the main hexagon without stroke and the border mask
mainShape := d2themes.NewThemableElement("polygon")
mainShape.X = float64(targetShape.Pos.X)
mainShape.Y = float64(targetShape.Pos.Y)
mainShape.Points = mainPointsPoly
mainShape.SetMaskUrl(maskID)
mainShapeFill, _ := d2themes.ShapeTheme(targetShape)
mainShape.FillPattern = targetShape.FillPattern
mainShape.Fill = mainShapeFill
mainShape.Stroke = color.None
mainShape.Style = targetShape.CSSStyle()
mainShapeRendered := mainShape.Render()
// render the side shapes in the darkened color without stroke and the border mask
var sidePoints []string
for _, v := range []d2target.Point{
{X: scale(targetShape.Width, 0.25) + d2target.THREE_DEE_OFFSET, Y: -Y_OFFSET},
{X: scale(targetShape.Width, 0.75) + d2target.THREE_DEE_OFFSET, Y: -Y_OFFSET},
{X: targetShape.Width + d2target.THREE_DEE_OFFSET, Y: scale(targetShape.Height, halfYFactor) - Y_OFFSET},
{X: scale(targetShape.Width, 0.75) + d2target.THREE_DEE_OFFSET, Y: targetShape.Height - Y_OFFSET},
{X: scale(targetShape.Width, 0.75), Y: targetShape.Height},
{X: targetShape.Width, Y: scale(targetShape.Height, halfYFactor)},
{X: scale(targetShape.Width, 0.75), Y: 0},
{X: scale(targetShape.Width, 0.25), Y: 0},
} {
sidePoints = append(sidePoints,
fmt.Sprintf("%d,%d", v.X+targetShape.Pos.X, v.Y+targetShape.Pos.Y),
)
}
// TODO make darker color part of the theme? or just keep this bypass
darkerColor, err := color.Darken(targetShape.Fill)
if err != nil {
darkerColor = targetShape.Fill
}
sideShape := d2themes.NewThemableElement("polygon")
sideShape.Fill = darkerColor
sideShape.Points = strings.Join(sidePoints, " ")
sideShape.SetMaskUrl(maskID)
sideShape.Style = targetShape.CSSStyle()
renderedSides := sideShape.Render()
return borderMask + mainShapeRendered + renderedSides + renderedBorder
}
func drawShape(writer, appendixWriter io.Writer, diagramHash string, targetShape d2target.Shape, sketchRunner *d2sketch.Runner) (labelMask string, err error) {
closingTag := "</g>"
if targetShape.Link != "" {
fmt.Fprintf(writer, `<a href="%s" xlink:href="%[1]s">`, svg.EscapeText(targetShape.Link))
closingTag += "</a>"
}
// Opacity is a unique style, it applies to everything for a shape
opacityStyle := ""
if targetShape.Opacity != 1.0 {
opacityStyle = fmt.Sprintf(" style='opacity:%f'", targetShape.Opacity)
}
// this clipPath must be defined outside `g` element
if targetShape.BorderRadius != 0 && (targetShape.Type == d2target.ShapeClass || targetShape.Type == d2target.ShapeSQLTable) {
fmt.Fprint(writer, clipPathForBorderRadius(diagramHash, targetShape))
}
classStr := ""
if len(targetShape.Classes) > 0 {
classStr = fmt.Sprintf(` class="%s"`, strings.Join(targetShape.Classes, " "))
}
fmt.Fprintf(writer, `<g id="%s"%s%s>`, svg.EscapeText(targetShape.ID), opacityStyle, classStr)
tl := geo.NewPoint(float64(targetShape.Pos.X), float64(targetShape.Pos.Y))
width := float64(targetShape.Width)
height := float64(targetShape.Height)
fill, stroke := d2themes.ShapeTheme(targetShape)
style := targetShape.CSSStyle()
shapeType := d2target.DSL_SHAPE_TO_SHAPE_TYPE[targetShape.Type]
s := shape.NewShape(shapeType, geo.NewBox(tl, width, height))
if shapeType == shape.CLOUD_TYPE && targetShape.ContentAspectRatio != nil {
s.SetInnerBoxAspectRatio(*targetShape.ContentAspectRatio)
}
var shadowAttr string
if targetShape.Shadow {
switch targetShape.Type {
case d2target.ShapeText,
d2target.ShapeCode,
d2target.ShapeClass,
d2target.ShapeSQLTable:
default:
shadowAttr = `filter="url(#shadow-filter)" `
}
}
var blendModeClass string
if targetShape.Blend {
blendModeClass = " blend"
}
fmt.Fprintf(writer, `<g class="shape%s" %s>`, blendModeClass, shadowAttr)
var multipleTL *geo.Point
if targetShape.Multiple {
multipleTL = tl.AddVector(multipleOffset)
}
switch targetShape.Type {
case d2target.ShapeClass:
if sketchRunner != nil {
out, err := d2sketch.Class(sketchRunner, targetShape)
if err != nil {
return "", err
}
fmt.Fprint(writer, out)
} else {
drawClass(writer, diagramHash, targetShape)
}
addAppendixItems(appendixWriter, targetShape, s)
fmt.Fprint(writer, `</g>`)
fmt.Fprint(writer, closingTag)
return labelMask, nil
case d2target.ShapeSQLTable:
if sketchRunner != nil {
out, err := d2sketch.Table(sketchRunner, targetShape)
if err != nil {
return "", err
}
fmt.Fprint(writer, out)
} else {
drawTable(writer, diagramHash, targetShape)
}
addAppendixItems(appendixWriter, targetShape, s)
fmt.Fprint(writer, `</g>`)
fmt.Fprint(writer, closingTag)
return labelMask, nil
case d2target.ShapeOval:
if targetShape.DoubleBorder {
if targetShape.Multiple {
fmt.Fprint(writer, renderDoubleOval(multipleTL, width, height, fill, "", stroke, style))