d2/d2layouts/d2sequence/sequence_diagram.go

677 lines
20 KiB
Go
Raw Normal View History

2022-12-01 21:40:19 +00:00
package d2sequence
import (
"errors"
2022-12-01 21:40:19 +00:00
"fmt"
"math"
"sort"
2023-09-29 00:54:01 +00:00
"strconv"
2022-12-03 17:38:08 +00:00
"strings"
2022-12-01 21:40:19 +00:00
2022-12-02 02:33:01 +00:00
"oss.terrastruct.com/util-go/go2"
2022-12-01 21:40:19 +00:00
"oss.terrastruct.com/d2/d2graph"
"oss.terrastruct.com/d2/d2target"
2022-12-01 21:40:19 +00:00
"oss.terrastruct.com/d2/lib/geo"
"oss.terrastruct.com/d2/lib/label"
"oss.terrastruct.com/d2/lib/shape"
)
type sequenceDiagram struct {
2022-12-02 18:26:07 +00:00
root *d2graph.Object
2022-12-01 21:40:19 +00:00
messages []*d2graph.Edge
lifelines []*d2graph.Edge
actors []*d2graph.Object
2022-12-04 22:53:12 +00:00
groups []*d2graph.Object
2022-12-01 21:40:19 +00:00
spans []*d2graph.Object
2022-12-04 08:11:03 +00:00
notes []*d2graph.Object
2022-12-01 21:40:19 +00:00
// can be either actors or spans
// rank: left to right position of actors/spans (spans have the same rank as their parents)
objectRank map[*d2graph.Object]int
// keep track of the first and last message of a given actor/span
2022-12-03 17:38:08 +00:00
firstMessage map[*d2graph.Object]*d2graph.Edge
lastMessage map[*d2graph.Object]*d2graph.Edge
2022-12-01 21:40:19 +00:00
2022-12-05 18:27:55 +00:00
// the distance from actor[i] center to actor[i+1] center
// every neighbor actors need different distances depending on the message labels between them
actorXStep []float64
2022-12-04 08:11:38 +00:00
yStep float64
2022-12-01 21:40:19 +00:00
maxActorHeight float64
2022-12-04 08:11:03 +00:00
verticalIndices map[string]int
}
func getObjEarliestLineNum(o *d2graph.Object) int {
min := int(math.MaxInt32)
2022-12-04 08:11:03 +00:00
for _, ref := range o.References {
if ref.MapKey == nil {
continue
}
min = go2.IntMin(min, ref.MapKey.Range.Start.Line)
}
return min
}
func getEdgeEarliestLineNum(e *d2graph.Edge) int {
min := int(math.MaxInt32)
2022-12-04 08:11:03 +00:00
for _, ref := range e.References {
if ref.MapKey == nil {
continue
}
min = go2.IntMin(min, ref.MapKey.Range.Start.Line)
}
return min
}
func newSequenceDiagram(objects []*d2graph.Object, messages []*d2graph.Edge) (*sequenceDiagram, error) {
2022-12-04 22:53:12 +00:00
var actors []*d2graph.Object
var groups []*d2graph.Object
for _, obj := range objects {
2022-12-05 05:57:59 +00:00
if obj.IsSequenceDiagramGroup() {
2022-12-04 22:53:12 +00:00
queue := []*d2graph.Object{obj}
// Groups may have more nested groups
for len(queue) > 0 {
curr := queue[0]
2023-07-17 21:21:36 +00:00
curr.LabelPosition = go2.Pointer(label.InsideTopLeft.String())
2022-12-04 22:53:12 +00:00
groups = append(groups, curr)
queue = queue[1:]
queue = append(queue, curr.ChildrenArray...)
2022-12-04 22:53:12 +00:00
}
2022-12-05 05:12:59 +00:00
} else {
actors = append(actors, obj)
2022-12-04 22:53:12 +00:00
}
}
if len(actors) == 0 {
return nil, errors.New("no actors declared in sequence diagram")
}
2022-12-01 21:40:19 +00:00
sd := &sequenceDiagram{
2022-12-04 08:11:03 +00:00
messages: messages,
actors: actors,
2022-12-04 22:53:12 +00:00
groups: groups,
2022-12-04 08:11:03 +00:00
spans: nil,
notes: nil,
lifelines: nil,
objectRank: make(map[*d2graph.Object]int),
firstMessage: make(map[*d2graph.Object]*d2graph.Edge),
lastMessage: make(map[*d2graph.Object]*d2graph.Edge),
2022-12-05 18:27:55 +00:00
actorXStep: make([]float64, len(actors)-1),
2022-12-04 08:11:38 +00:00
yStep: MIN_MESSAGE_DISTANCE,
2022-12-04 08:11:03 +00:00
maxActorHeight: 0.,
verticalIndices: make(map[string]int),
2022-12-01 21:40:19 +00:00
}
for rank, actor := range actors {
2022-12-02 18:26:07 +00:00
sd.root = actor.Parent
2022-12-01 21:40:19 +00:00
sd.objectRank[actor] = rank
2022-12-03 01:08:04 +00:00
if actor.Width < MIN_ACTOR_WIDTH {
2023-04-14 03:04:55 +00:00
dslShape := strings.ToLower(actor.Shape.Value)
switch dslShape {
2023-02-13 19:16:26 +00:00
case d2target.ShapePerson, d2target.ShapeOval, d2target.ShapeSquare, d2target.ShapeCircle:
// scale shape up to min width uniformly
actor.Height *= MIN_ACTOR_WIDTH / actor.Width
}
2022-12-03 01:08:04 +00:00
actor.Width = MIN_ACTOR_WIDTH
}
2022-12-01 21:40:19 +00:00
sd.maxActorHeight = math.Max(sd.maxActorHeight, actor.Height)
queue := make([]*d2graph.Object, len(actor.ChildrenArray))
copy(queue, actor.ChildrenArray)
2022-12-05 19:36:20 +00:00
maxNoteWidth := 0.
2022-12-01 21:40:19 +00:00
for len(queue) > 0 {
2022-12-04 08:11:03 +00:00
child := queue[0]
2022-12-01 21:40:19 +00:00
queue = queue[1:]
2022-12-04 08:11:03 +00:00
// spans are children of actors that have edges
2022-12-04 22:53:12 +00:00
// edge groups are children of actors with no edges and children edges
2022-12-05 04:26:37 +00:00
if child.IsSequenceDiagramNote() {
2022-12-04 08:11:03 +00:00
sd.verticalIndices[child.AbsID()] = getObjEarliestLineNum(child)
2023-04-14 03:04:55 +00:00
child.Shape = d2graph.Scalar{Value: shape.PAGE_TYPE}
2022-12-04 08:11:03 +00:00
sd.notes = append(sd.notes, child)
sd.objectRank[child] = rank
2023-07-17 21:21:36 +00:00
child.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
2022-12-05 19:36:20 +00:00
maxNoteWidth = math.Max(maxNoteWidth, child.Width)
2022-12-05 04:26:37 +00:00
} else {
// spans have no labels
// TODO why not? Spans should be able to
2023-04-14 03:04:55 +00:00
child.Label = d2graph.Scalar{Value: ""}
child.Shape = d2graph.Scalar{Value: shape.SQUARE_TYPE}
2022-12-05 04:26:37 +00:00
sd.spans = append(sd.spans, child)
sd.objectRank[child] = rank
2022-12-04 08:11:03 +00:00
}
2022-12-01 21:40:19 +00:00
2022-12-04 08:11:03 +00:00
queue = append(queue, child.ChildrenArray...)
2022-12-01 21:40:19 +00:00
}
2022-12-05 18:27:55 +00:00
if rank != len(actors)-1 {
actorHW := actor.Width / 2.
nextActorHW := actors[rank+1].Width / 2.
sd.actorXStep[rank] = math.Max(actorHW+nextActorHW+HORIZONTAL_PAD, MIN_ACTOR_DISTANCE)
2022-12-05 19:36:20 +00:00
sd.actorXStep[rank] = math.Max(maxNoteWidth/2.+HORIZONTAL_PAD, sd.actorXStep[rank])
2022-12-05 21:43:05 +00:00
if rank > 0 {
sd.actorXStep[rank-1] = math.Max(maxNoteWidth/2.+HORIZONTAL_PAD, sd.actorXStep[rank-1])
}
2022-12-05 18:27:55 +00:00
}
2022-12-01 21:40:19 +00:00
}
2022-12-03 17:38:08 +00:00
for _, message := range sd.messages {
2022-12-04 08:11:03 +00:00
sd.verticalIndices[message.AbsID()] = getEdgeEarliestLineNum(message)
2022-12-01 21:40:19 +00:00
// ensures that long labels, spanning over multiple actors, don't make for large gaps between actors
// by distributing the label length across the actors rank difference
rankDiff := math.Abs(float64(sd.objectRank[message.Src]) - float64(sd.objectRank[message.Dst]))
2022-12-03 17:38:08 +00:00
if rankDiff != 0 {
// rankDiff = 0 for self edges
distributedLabelWidth := float64(message.LabelDimensions.Width) / rankDiff
2022-12-06 06:45:11 +00:00
for rank := go2.IntMin(sd.objectRank[message.Src], sd.objectRank[message.Dst]); rank <= go2.IntMax(sd.objectRank[message.Src], sd.objectRank[message.Dst])-1; rank++ {
2022-12-05 18:27:55 +00:00
sd.actorXStep[rank] = math.Max(sd.actorXStep[rank], distributedLabelWidth+HORIZONTAL_PAD)
}
2022-12-03 17:38:08 +00:00
}
sd.lastMessage[message.Src] = message
if _, exists := sd.firstMessage[message.Src]; !exists {
sd.firstMessage[message.Src] = message
}
sd.lastMessage[message.Dst] = message
if _, exists := sd.firstMessage[message.Dst]; !exists {
sd.firstMessage[message.Dst] = message
}
2022-12-01 21:40:19 +00:00
}
2022-12-04 08:11:38 +00:00
sd.yStep += VERTICAL_PAD
2022-12-03 02:39:29 +00:00
sd.maxActorHeight += VERTICAL_PAD
if sd.root.HasLabel() {
sd.maxActorHeight += float64(sd.root.LabelDimensions.Height)
2022-12-03 02:39:29 +00:00
}
2022-12-01 21:40:19 +00:00
return sd, nil
2022-12-01 21:40:19 +00:00
}
2022-12-03 17:38:08 +00:00
func (sd *sequenceDiagram) layout() error {
2022-12-01 21:40:19 +00:00
sd.placeActors()
2022-12-05 03:38:01 +00:00
sd.placeNotes()
2022-12-03 17:38:08 +00:00
if err := sd.routeMessages(); err != nil {
return err
}
2022-12-01 21:40:19 +00:00
sd.placeSpans()
2022-12-03 17:38:08 +00:00
sd.adjustRouteEndpoints()
2022-12-04 22:53:12 +00:00
sd.placeGroups()
2022-12-01 21:40:19 +00:00
sd.addLifelineEdges()
2022-12-03 17:38:08 +00:00
return nil
2022-12-01 21:40:19 +00:00
}
2022-12-04 22:53:12 +00:00
func (sd *sequenceDiagram) placeGroups() {
2022-12-05 07:38:47 +00:00
sort.SliceStable(sd.groups, func(i, j int) bool {
return sd.groups[i].Level() > sd.groups[j].Level()
})
2022-12-04 22:53:12 +00:00
for _, group := range sd.groups {
2022-12-05 04:53:31 +00:00
group.ZIndex = GROUP_Z_INDEX
2022-12-04 22:53:12 +00:00
sd.placeGroup(group)
}
2023-02-12 17:59:44 +00:00
for _, group := range sd.groups {
sd.adjustGroupLabel(group)
}
2022-12-04 22:53:12 +00:00
}
func (sd *sequenceDiagram) placeGroup(group *d2graph.Object) {
minX := math.Inf(1)
minY := math.Inf(1)
maxX := math.Inf(-1)
maxY := math.Inf(-1)
for _, m := range sd.messages {
2022-12-05 04:26:37 +00:00
if m.ContainedBy(group) {
2022-12-04 22:53:12 +00:00
for _, p := range m.Route {
labelHeight := float64(m.LabelDimensions.Height) / 2.
edgePad := math.Max(labelHeight+GROUP_CONTAINER_PADDING, MIN_MESSAGE_DISTANCE/2.)
2022-12-05 17:54:45 +00:00
minX = math.Min(minX, p.X-HORIZONTAL_PAD)
minY = math.Min(minY, p.Y-edgePad)
2022-12-05 17:54:45 +00:00
maxX = math.Max(maxX, p.X+HORIZONTAL_PAD)
maxY = math.Max(maxY, p.Y+edgePad)
2022-12-04 22:53:12 +00:00
}
}
}
// Groups should horizontally encompass all notes of the actor
for _, n := range sd.notes {
inGroup := false
for _, ref := range n.References {
2023-01-24 05:48:43 +00:00
curr := ref.ScopeObj
2022-12-04 22:53:12 +00:00
for curr != nil {
if curr == group {
inGroup = true
break
}
curr = curr.Parent
}
if inGroup {
break
}
}
if inGroup {
2022-12-05 17:54:45 +00:00
minX = math.Min(minX, n.TopLeft.X-HORIZONTAL_PAD)
2023-02-10 03:19:40 +00:00
minY = math.Min(minY, n.TopLeft.Y-MIN_MESSAGE_DISTANCE/2.)
2023-02-09 06:11:52 +00:00
maxX = math.Max(maxX, n.TopLeft.X+n.Width+HORIZONTAL_PAD)
2023-02-10 03:19:40 +00:00
maxY = math.Max(maxY, n.TopLeft.Y+n.Height+MIN_MESSAGE_DISTANCE/2.)
2022-12-04 22:53:12 +00:00
}
}
2022-12-05 07:38:47 +00:00
for _, ch := range group.ChildrenArray {
for _, g := range sd.groups {
if ch == g {
minX = math.Min(minX, ch.TopLeft.X-GROUP_CONTAINER_PADDING)
2023-02-09 20:19:33 +00:00
minY = math.Min(minY, ch.TopLeft.Y-GROUP_CONTAINER_PADDING)
2022-12-05 07:38:47 +00:00
maxX = math.Max(maxX, ch.TopLeft.X+ch.Width+GROUP_CONTAINER_PADDING)
maxY = math.Max(maxY, ch.TopLeft.Y+ch.Height+GROUP_CONTAINER_PADDING)
break
}
}
}
2022-12-04 22:53:12 +00:00
group.Box = geo.NewBox(
geo.NewPoint(
2022-12-05 07:38:47 +00:00
minX,
minY,
2022-12-04 22:53:12 +00:00
),
2022-12-05 07:38:47 +00:00
maxX-minX,
maxY-minY,
2022-12-04 22:53:12 +00:00
)
}
2023-02-12 17:59:44 +00:00
func (sd *sequenceDiagram) adjustGroupLabel(group *d2graph.Object) {
if !group.HasLabel() {
2023-02-12 17:59:44 +00:00
return
}
heightAdd := (group.LabelDimensions.Height + EDGE_GROUP_LABEL_PADDING/2.)
if heightAdd < GROUP_CONTAINER_PADDING {
2023-02-12 17:59:44 +00:00
return
}
group.Height += float64(heightAdd)
// Extend stuff within this group
for _, g := range sd.groups {
if g.TopLeft.Y < group.TopLeft.Y && g.TopLeft.Y+g.Height > group.TopLeft.Y {
g.Height += float64(heightAdd)
}
}
for _, s := range sd.spans {
if s.TopLeft.Y < group.TopLeft.Y && s.TopLeft.Y+s.Height > group.TopLeft.Y {
s.Height += float64(heightAdd)
}
}
// Move stuff down
for _, m := range sd.messages {
if go2.Min(m.Route[0].Y, m.Route[len(m.Route)-1].Y) > group.TopLeft.Y {
for _, p := range m.Route {
p.Y += float64(heightAdd)
}
}
}
for _, s := range sd.spans {
if s.TopLeft.Y > group.TopLeft.Y {
s.TopLeft.Y += float64(heightAdd)
}
}
for _, g := range sd.groups {
if g.TopLeft.Y > group.TopLeft.Y {
g.TopLeft.Y += float64(heightAdd)
}
}
for _, n := range sd.notes {
if n.TopLeft.Y > group.TopLeft.Y {
n.TopLeft.Y += float64(heightAdd)
}
}
}
2022-12-05 18:19:26 +00:00
// placeActors places actors bottom aligned, side by side with centers spaced by sd.actorXStep
2022-12-01 21:40:19 +00:00
func (sd *sequenceDiagram) placeActors() {
2022-12-05 18:19:26 +00:00
centerX := sd.actors[0].Width / 2.
2022-12-05 18:27:55 +00:00
for rank, actor := range sd.actors {
var yOffset float64
2023-03-02 22:52:30 +00:00
if actor.HasOutsideBottomLabel() {
2023-07-17 21:21:36 +00:00
actor.LabelPosition = go2.Pointer(label.OutsideBottomCenter.String())
2022-12-04 21:58:38 +00:00
yOffset = sd.maxActorHeight - actor.Height
if actor.HasLabel() {
yOffset -= float64(actor.LabelDimensions.Height)
2022-12-04 21:58:38 +00:00
}
} else {
2023-07-17 21:21:36 +00:00
actor.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
yOffset = sd.maxActorHeight - actor.Height
}
2022-12-05 18:19:26 +00:00
halfWidth := actor.Width / 2.
actor.TopLeft = geo.NewPoint(math.Round(centerX-halfWidth), yOffset)
2022-12-05 18:27:55 +00:00
if rank != len(sd.actors)-1 {
centerX += sd.actorXStep[rank]
}
2022-12-01 21:40:19 +00:00
}
}
// addLifelineEdges adds a new edge for each actor in the graph that represents the its lifeline
2023-03-14 18:18:46 +00:00
// . ┌──────────────┐
// . │ actor │
// . └──────┬───────┘
// . │
// . │ lifeline
// . │
// . │
2022-12-01 21:40:19 +00:00
func (sd *sequenceDiagram) addLifelineEdges() {
2022-12-04 08:11:38 +00:00
endY := 0.
2022-12-12 00:28:30 +00:00
if len(sd.messages) > 0 {
lastRoute := sd.messages[len(sd.messages)-1].Route
for _, p := range lastRoute {
endY = math.Max(endY, p.Y)
}
2022-12-04 08:11:38 +00:00
}
2022-12-04 08:11:03 +00:00
for _, note := range sd.notes {
2022-12-04 08:11:38 +00:00
endY = math.Max(endY, note.TopLeft.Y+note.Height)
2022-12-04 08:11:03 +00:00
}
2022-12-12 00:28:30 +00:00
for _, actor := range sd.actors {
endY = math.Max(endY, actor.TopLeft.Y+actor.Height)
}
2022-12-04 08:11:38 +00:00
endY += sd.yStep
2022-12-04 08:11:03 +00:00
2022-12-01 21:40:19 +00:00
for _, actor := range sd.actors {
actorBottom := actor.Center()
actorBottom.Y = actor.TopLeft.Y + actor.Height
2023-07-17 21:21:36 +00:00
if *actor.LabelPosition == label.OutsideBottomCenter.String() && actor.HasLabel() {
actorBottom.Y += float64(actor.LabelDimensions.Height) + LIFELINE_LABEL_PAD
}
2022-12-01 21:40:19 +00:00
actorLifelineEnd := actor.Center()
actorLifelineEnd.Y = endY
style := d2graph.Style{
StrokeDash: &d2graph.Scalar{Value: fmt.Sprintf("%d", LIFELINE_STROKE_DASH)},
StrokeWidth: &d2graph.Scalar{Value: fmt.Sprintf("%d", LIFELINE_STROKE_WIDTH)},
}
2023-04-14 03:04:55 +00:00
if actor.Style.StrokeDash != nil {
style.StrokeDash = &d2graph.Scalar{Value: actor.Style.StrokeDash.Value}
}
2023-04-14 03:04:55 +00:00
if actor.Style.Stroke != nil {
style.Stroke = &d2graph.Scalar{Value: actor.Style.Stroke.Value}
}
2022-12-01 21:40:19 +00:00
sd.lifelines = append(sd.lifelines, &d2graph.Edge{
2023-04-14 03:04:55 +00:00
Attributes: d2graph.Attributes{Style: style},
Src: actor,
SrcArrow: false,
2022-12-01 21:40:19 +00:00
Dst: &d2graph.Object{
ID: actor.ID + fmt.Sprintf("-lifeline-end-%d", go2.StringToIntHash(actor.ID+"-lifeline-end")),
},
DstArrow: false,
Route: []*geo.Point{actorBottom, actorLifelineEnd},
2022-12-05 05:19:40 +00:00
ZIndex: LIFELINE_Z_INDEX,
2022-12-01 21:40:19 +00:00
})
}
}
2023-09-29 00:54:01 +00:00
func IsLifelineEnd(obj *d2graph.Object) bool {
// lifeline ends only have ID and no graph parent or box set
if obj.Graph != nil || obj.Parent != nil || obj.Box != nil {
return false
}
if !strings.Contains(obj.ID, "-lifeline-end-") {
return false
}
parts := strings.Split(obj.ID, "-lifeline-end-")
if len(parts) > 1 {
hash := parts[len(parts)-1]
actorID := strings.Join(parts[:len(parts)-1], "-lifeline-end-")
if strconv.Itoa(go2.StringToIntHash(actorID+"-lifeline-end")) == hash {
return true
}
}
return false
}
2022-12-04 08:11:03 +00:00
func (sd *sequenceDiagram) placeNotes() {
rankToX := make(map[int]float64)
for _, actor := range sd.actors {
rankToX[sd.objectRank[actor]] = actor.Center().X
}
2023-02-12 17:59:44 +00:00
for _, note := range sd.notes {
2022-12-04 08:11:03 +00:00
verticalIndex := sd.verticalIndices[note.AbsID()]
2022-12-04 08:11:38 +00:00
y := sd.maxActorHeight + sd.yStep
2022-12-04 08:11:03 +00:00
for _, msg := range sd.messages {
if sd.verticalIndices[msg.AbsID()] < verticalIndex {
2024-08-05 05:01:14 +00:00
y += sd.yStep + float64(msg.LabelDimensions.Height)
2022-12-04 08:11:03 +00:00
}
}
2023-02-12 17:59:44 +00:00
for _, otherNote := range sd.notes {
if sd.verticalIndices[otherNote.AbsID()] < verticalIndex {
y += otherNote.Height + sd.yStep
}
2022-12-04 08:11:03 +00:00
}
x := rankToX[sd.objectRank[note]] - (note.Width / 2.)
note.Box.TopLeft = geo.NewPoint(x, y)
2022-12-05 04:53:31 +00:00
note.ZIndex = NOTE_Z_INDEX
2022-12-04 08:11:03 +00:00
}
}
2022-12-01 21:40:19 +00:00
// placeSpans places spans over the object lifeline
2023-03-14 18:18:46 +00:00
// . ┌──────────┐
// . │ actor │
// . └────┬─────┘
// . ┌─┴──┐
// . │ │
// . |span|
// . │ │
// . └─┬──┘
// . │
// . lifeline
// . │
2022-12-01 21:40:19 +00:00
func (sd *sequenceDiagram) placeSpans() {
// quickly find the span center X
rankToX := make(map[int]float64)
for _, actor := range sd.actors {
rankToX[sd.objectRank[actor]] = actor.Center().X
}
// places spans from most to least nested
2022-12-03 01:08:04 +00:00
// the order is important because the only way a child span exists is if there's a message to it
2022-12-01 21:40:19 +00:00
// however, the parent span might not have a message to it and then its position is based on the child position
// or, there can be a message to it, but it comes after the child one meaning the top left position is still based on the child
// and not on its own message
spanFromMostNested := make([]*d2graph.Object, len(sd.spans))
copy(spanFromMostNested, sd.spans)
sort.SliceStable(spanFromMostNested, func(i, j int) bool {
return spanFromMostNested[i].Level() > spanFromMostNested[j].Level()
})
for _, span := range spanFromMostNested {
// finds the position based on children
minChildY := math.Inf(1)
maxChildY := math.Inf(-1)
for _, child := range span.ChildrenArray {
minChildY = math.Min(minChildY, child.TopLeft.Y)
maxChildY = math.Max(maxChildY, child.TopLeft.Y+child.Height)
}
// finds the position if there are messages to this span
minMessageY := math.Inf(1)
2022-12-03 17:38:08 +00:00
if firstMessage, exists := sd.firstMessage[span]; exists {
2022-12-06 22:19:17 +00:00
if firstMessage.Src == firstMessage.Dst || span == firstMessage.Src {
2022-12-03 17:38:08 +00:00
minMessageY = firstMessage.Route[0].Y
} else {
minMessageY = firstMessage.Route[len(firstMessage.Route)-1].Y
}
2022-12-01 21:40:19 +00:00
}
maxMessageY := math.Inf(-1)
2022-12-03 17:38:08 +00:00
if lastMessage, exists := sd.lastMessage[span]; exists {
2022-12-06 22:19:17 +00:00
if lastMessage.Src == lastMessage.Dst || span == lastMessage.Dst {
2022-12-03 17:38:08 +00:00
maxMessageY = lastMessage.Route[len(lastMessage.Route)-1].Y
2022-12-06 22:19:17 +00:00
} else {
maxMessageY = lastMessage.Route[0].Y
2022-12-03 17:38:08 +00:00
}
2022-12-01 21:40:19 +00:00
}
// if it is the same as the child top left, add some padding
minY := math.Min(minMessageY, minChildY)
2022-12-03 00:02:34 +00:00
if minY == minChildY || minY == minMessageY {
minY -= SPAN_MESSAGE_PAD
2022-12-01 21:40:19 +00:00
}
maxY := math.Max(maxMessageY, maxChildY)
2022-12-03 00:02:34 +00:00
if maxY == maxChildY || maxY == maxMessageY {
maxY += SPAN_MESSAGE_PAD
2022-12-01 21:40:19 +00:00
}
height := math.Max(maxY-minY, MIN_SPAN_HEIGHT)
2022-12-05 06:31:37 +00:00
// -1 because the actors count as 1 level
width := SPAN_BASE_WIDTH + (float64(span.Level()-sd.root.Level()-2) * SPAN_DEPTH_GROWTH_FACTOR)
2022-12-01 21:40:19 +00:00
x := rankToX[sd.objectRank[span]] - (width / 2.)
span.Box = geo.NewBox(geo.NewPoint(x, minY), width, height)
2022-12-05 04:53:31 +00:00
span.ZIndex = SPAN_Z_INDEX
2022-12-01 21:40:19 +00:00
}
}
2022-12-03 17:38:08 +00:00
// routeMessages routes horizontal edges (messages) from Src to Dst lifeline (actor/span center)
// in another step, routes are adjusted to spans borders when necessary
func (sd *sequenceDiagram) routeMessages() error {
2022-12-05 03:38:01 +00:00
messageOffset := sd.maxActorHeight + sd.yStep
2022-12-03 17:38:08 +00:00
for _, message := range sd.messages {
2022-12-05 04:53:31 +00:00
message.ZIndex = MESSAGE_Z_INDEX
2022-12-05 03:38:01 +00:00
noteOffset := 0.
2022-12-05 03:12:49 +00:00
for _, note := range sd.notes {
if sd.verticalIndices[note.AbsID()] < sd.verticalIndices[message.AbsID()] {
2022-12-05 03:38:01 +00:00
noteOffset += note.Height + sd.yStep
2022-12-05 03:12:49 +00:00
}
}
2022-12-01 21:40:19 +00:00
var startX, endX float64
2022-12-03 17:38:08 +00:00
if startCenter := getCenter(message.Src); startCenter != nil {
startX = startCenter.X
2022-12-01 21:40:19 +00:00
} else {
2023-02-08 04:47:12 +00:00
return fmt.Errorf("could not find center of %s. Is it declared as an actor?", message.Src.ID)
2022-12-01 21:40:19 +00:00
}
2022-12-03 17:38:08 +00:00
if endCenter := getCenter(message.Dst); endCenter != nil {
endX = endCenter.X
2022-12-01 21:40:19 +00:00
} else {
2023-02-08 04:47:12 +00:00
return fmt.Errorf("could not find center of %s. Is it declared as an actor?", message.Dst.ID)
2022-12-01 21:40:19 +00:00
}
2022-12-19 04:03:07 +00:00
isToDescendant := strings.HasPrefix(message.Dst.AbsID(), message.Src.AbsID()+".")
isFromDescendant := strings.HasPrefix(message.Src.AbsID(), message.Dst.AbsID()+".")
2022-12-03 17:38:08 +00:00
isSelfMessage := message.Src == message.Dst
2022-12-01 21:40:19 +00:00
2023-01-20 02:09:32 +00:00
currSrc := message.Src
for !currSrc.Parent.IsSequenceDiagram() {
currSrc = currSrc.Parent
}
currDst := message.Dst
for !currDst.Parent.IsSequenceDiagram() {
currDst = currDst.Parent
}
isToSibling := currSrc == currDst
if isSelfMessage || isToDescendant || isFromDescendant || isToSibling {
2022-12-05 06:34:38 +00:00
midX := startX + SELF_MESSAGE_HORIZONTAL_TRAVEL
2024-08-05 05:01:14 +00:00
startY := messageOffset + noteOffset
endY := startY + math.Max(float64(message.LabelDimensions.Height), MIN_MESSAGE_DISTANCE)*1.5
2022-12-03 05:49:51 +00:00
message.Route = []*geo.Point{
geo.NewPoint(startX, startY),
2022-12-03 17:38:08 +00:00
geo.NewPoint(midX, startY),
geo.NewPoint(midX, endY),
geo.NewPoint(endX, endY),
2022-12-03 05:49:51 +00:00
}
2024-08-05 05:01:14 +00:00
messageOffset = endY + sd.yStep - noteOffset
2022-12-03 05:49:51 +00:00
} else {
2024-08-05 05:01:14 +00:00
startY := messageOffset + noteOffset + float64(message.LabelDimensions.Height/2.)
2022-12-03 05:49:51 +00:00
message.Route = []*geo.Point{
geo.NewPoint(startX, startY),
geo.NewPoint(endX, startY),
}
2024-08-05 05:01:14 +00:00
messageOffset = startY + float64(message.LabelDimensions.Height/2.) + sd.yStep - noteOffset
2022-12-01 21:40:19 +00:00
}
2023-04-14 03:04:55 +00:00
if message.Label.Value != "" {
2023-07-17 21:21:36 +00:00
message.LabelPosition = go2.Pointer(label.InsideMiddleCenter.String())
2022-12-01 21:40:19 +00:00
}
}
2022-12-03 17:38:08 +00:00
return nil
}
func getCenter(obj *d2graph.Object) *geo.Point {
if obj == nil {
return nil
2023-02-08 04:47:12 +00:00
} else if obj.Box != nil && obj.Box.TopLeft != nil {
2022-12-03 17:38:08 +00:00
return obj.Center()
}
return getCenter(obj.Parent)
2022-12-01 21:40:19 +00:00
}
2022-12-03 17:38:08 +00:00
// adjustRouteEndpoints adjust the first and last points of message routes when they are spans
// routeMessages() will route to the actor lifelife as a reference point and this function
// adjust to span width when necessary
func (sd *sequenceDiagram) adjustRouteEndpoints() {
for _, message := range sd.messages {
route := message.Route
if !sd.isActor(message.Src) {
if sd.objectRank[message.Src] <= sd.objectRank[message.Dst] {
route[0].X += message.Src.Width / 2.
} else {
route[0].X -= message.Src.Width / 2.
}
}
if !sd.isActor(message.Dst) {
if sd.objectRank[message.Src] < sd.objectRank[message.Dst] {
route[len(route)-1].X -= message.Dst.Width / 2.
} else {
route[len(route)-1].X += message.Dst.Width / 2.
}
}
}
2022-12-01 21:40:19 +00:00
}
func (sd *sequenceDiagram) isActor(obj *d2graph.Object) bool {
2022-12-02 18:26:07 +00:00
return obj.Parent == sd.root
2022-12-01 21:40:19 +00:00
}
func (sd *sequenceDiagram) getWidth() float64 {
// the layout is always placed starting at 0, so the width is just the last actor
lastActor := sd.actors[len(sd.actors)-1]
rightmost := lastActor.TopLeft.X + lastActor.Width
for _, m := range sd.messages {
for _, p := range m.Route {
rightmost = math.Max(rightmost, p.X)
}
// Self referential messages may have labels that extend further
if m.Src == m.Dst {
rightmost = math.Max(rightmost, m.Route[1].X+float64(m.LabelDimensions.Width)/2.)
}
}
return rightmost
2022-12-01 21:40:19 +00:00
}
func (sd *sequenceDiagram) getHeight() float64 {
2022-12-03 17:38:08 +00:00
return sd.lifelines[0].Route[1].Y
2022-12-01 21:40:19 +00:00
}
func (sd *sequenceDiagram) shift(tl *geo.Point) {
allObjects := append([]*d2graph.Object{}, sd.actors...)
allObjects = append(allObjects, sd.spans...)
2022-12-05 21:55:00 +00:00
allObjects = append(allObjects, sd.groups...)
allObjects = append(allObjects, sd.notes...)
2022-12-01 21:40:19 +00:00
for _, obj := range allObjects {
obj.TopLeft.X += tl.X
obj.TopLeft.Y += tl.Y
}
allEdges := append([]*d2graph.Edge{}, sd.messages...)
allEdges = append(allEdges, sd.lifelines...)
for _, edge := range allEdges {
for _, p := range edge.Route {
p.X += tl.X
p.Y += tl.Y
}
}
}