...

Source file src/oss.terrastruct.com/d2/d2layouts/d2dagrelayout/object_mapper.go

Documentation: oss.terrastruct.com/d2/d2layouts/d2dagrelayout

     1  package d2dagrelayout
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strconv"
     7  	"strings"
     8  
     9  	"oss.terrastruct.com/d2/d2graph"
    10  )
    11  
    12  type objectMapper struct {
    13  	objToID map[*d2graph.Object]string
    14  	idToObj map[string]*d2graph.Object
    15  }
    16  
    17  func NewObjectMapper() *objectMapper {
    18  	return &objectMapper{
    19  		objToID: make(map[*d2graph.Object]string),
    20  		idToObj: make(map[string]*d2graph.Object),
    21  	}
    22  }
    23  
    24  func (c *objectMapper) Register(obj *d2graph.Object) {
    25  	id := strconv.Itoa(len(c.idToObj))
    26  	c.idToObj[id] = obj
    27  	c.objToID[obj] = id
    28  }
    29  
    30  func (c *objectMapper) ToID(obj *d2graph.Object) string {
    31  	return c.objToID[obj]
    32  }
    33  
    34  func (c *objectMapper) ToObj(id string) *d2graph.Object {
    35  	return c.idToObj[id]
    36  }
    37  
    38  func (c objectMapper) generateAddNodeLine(obj *d2graph.Object, width, height int) string {
    39  	id := c.ToID(obj)
    40  	return fmt.Sprintf("g.setNode(`%s`, { id: `%s`, width: %d, height: %d });\n", id, id, width, height)
    41  }
    42  
    43  func (c objectMapper) generateAddParentLine(child, parent *d2graph.Object) string {
    44  	return fmt.Sprintf("g.setParent(`%s`, `%s`);\n", c.ToID(child), c.ToID(parent))
    45  }
    46  
    47  func (c objectMapper) generateAddEdgeLine(from, to *d2graph.Object, edgeID string, width, height int) string {
    48  	return fmt.Sprintf(
    49  		"g.setEdge({v:`%s`, w:`%s`, name:`%s`}, { width:%d, height:%d, labelpos: `c` });\n",
    50  		c.ToID(from), c.ToID(to), escapeID(edgeID), width, height,
    51  	)
    52  }
    53  
    54  func escapeID(id string) string {
    55  	// fixes \\
    56  	id = strings.ReplaceAll(id, "\\", `\\`)
    57  	// replaces \n with \\n whenever \n is not preceded by \ (does not replace \\n)
    58  	re := regexp.MustCompile(`[^\\]\n`)
    59  	id = re.ReplaceAllString(id, `\\n`)
    60  	// avoid an unescaped \r becoming a \n in the layout result
    61  	id = strings.ReplaceAll(id, "\r", `\r`)
    62  	return id
    63  }
    64  

View as plain text