From 14300dc9f801851e0530d689e5604d5ba80bc2fd Mon Sep 17 00:00:00 2001 From: Gavin Nishizawa Date: Mon, 19 Jun 2023 15:25:14 -0700 Subject: [PATCH] update leading/trailing accounting --- d2graph/d2graph.go | 21 ++++++++++----------- d2renderers/d2svg/d2svg.go | 4 ++-- lib/textmeasure/textmeasure.go | 1 + 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/d2graph/d2graph.go b/d2graph/d2graph.go index e39ec27ca..a91c95e12 100644 --- a/d2graph/d2graph.go +++ b/d2graph/d2graph.go @@ -1314,29 +1314,28 @@ func GetTextDimensions(mtexts []*d2target.MText, ruler *textmeasure.Ruler, t *d2 var h int if t.Language != "" { originalLineHeight := ruler.LineHeightFactor - ruler.LineHeightFactor = 1.3 + ruler.LineHeightFactor = textmeasure.CODE_LINE_HEIGHT w, h = ruler.MeasureMono(d2fonts.SourceCodePro.Font(t.FontSize, d2fonts.FONT_STYLE_REGULAR), t.Text) ruler.LineHeightFactor = originalLineHeight // count empty leading and trailing lines since ruler will not be able to measure it lines := strings.Split(t.Text, "\n") - leadingLines := 0 - for _, line := range lines { - if strings.TrimSpace(line) == "" { - leadingLines++ - } else { - break - } + hasLeading := false + if len(lines) > 0 && strings.TrimSpace(lines[0]) == "" { + hasLeading = true } - trailingLines := 0 + numTrailing := 0 for i := len(lines) - 1; i >= 0; i-- { if strings.TrimSpace(lines[i]) == "" { - trailingLines++ + numTrailing++ } else { break } } - h += t.FontSize * (leadingLines + trailingLines) + if hasLeading && numTrailing < len(lines) { + h += t.FontSize + } + h += int(math.Ceil(textmeasure.CODE_LINE_HEIGHT * float64(t.FontSize*numTrailing))) } else { style := d2fonts.FONT_STYLE_REGULAR if t.IsBold { diff --git a/d2renderers/d2svg/d2svg.go b/d2renderers/d2svg/d2svg.go index 3b4f0650e..a432c6dc3 100644 --- a/d2renderers/d2svg/d2svg.go +++ b/d2renderers/d2svg/d2svg.go @@ -1272,9 +1272,9 @@ func drawShape(writer io.Writer, diagramHash string, targetShape d2target.Shape, padding := float64(targetShape.FontSize) / 2. fmt.Fprintf(writer, ``, padding, padding) - lineHeight := 1.3 + lineHeight := textmeasure.CODE_LINE_HEIGHT for index, tokens := range chroma.SplitTokensIntoLines(iterator.Tokens()) { - fmt.Fprintf(writer, "", 1+lineHeight*float64(index)) + fmt.Fprintf(writer, "", 1+float64(index)*lineHeight) for _, token := range tokens { text := svgEscaper.Replace(token.String()) attr := styleAttr(svgStyles, token.Type) diff --git a/lib/textmeasure/textmeasure.go b/lib/textmeasure/textmeasure.go index 8602a0bed..8df3a346e 100644 --- a/lib/textmeasure/textmeasure.go +++ b/lib/textmeasure/textmeasure.go @@ -18,6 +18,7 @@ import ( const TAB_SIZE = 4 const SIZELESS_FONT_SIZE = 0 +const CODE_LINE_HEIGHT = 1.3 // ASCII is a set of all ASCII runes. These runes are codepoints from 32 to 127 inclusive. var ASCII []rune