diff --git a/d2renderers/textmeasure/markdown.go b/d2renderers/textmeasure/markdown.go index 056af2f77..e625e9597 100644 --- a/d2renderers/textmeasure/markdown.go +++ b/d2renderers/textmeasure/markdown.go @@ -4,7 +4,6 @@ import ( "bytes" "math" "strings" - "unicode/utf8" "github.com/PuerkitoBio/goquery" "github.com/yuin/goldmark" @@ -212,20 +211,17 @@ func (ruler *Ruler) measureNode(depth int, n *html.Node, font d2fonts.Font) bloc if strings.TrimSpace(n.Data) == "" { return blockAttrs{} } - spaceWidths := 0. - - // consecutive leading/trailing spaces end up rendered as a single space - spaceRune, _ := utf8.DecodeRuneInString(" ") - // measure will not include leading or trailing whitespace, so we have to add in the space width - spaceWidth := ruler.atlases[font].glyph(spaceRune).advance - str := n.Data isCode := parentElementType == "pre" || parentElementType == "code" + spaceWidths := 0. if !isCode { + spaceWidth := ruler.spaceWidth(font) + // MeasurePrecise will not include leading or trailing whitespace, so we account for it here str = strings.ReplaceAll(str, "\n", " ") str = strings.ReplaceAll(str, "\t", " ") if strings.HasPrefix(str, " ") { + // consecutive leading/trailing spaces end up rendered as a single space str = strings.TrimPrefix(str, " ") if hasPrev(n) { spaceWidths += spaceWidth diff --git a/d2renderers/textmeasure/textmeasure.go b/d2renderers/textmeasure/textmeasure.go index b9192e58d..5eb309ae4 100644 --- a/d2renderers/textmeasure/textmeasure.go +++ b/d2renderers/textmeasure/textmeasure.go @@ -127,10 +127,6 @@ func NewRuler() (*Ruler, error) { } r.ttfs[font] = ttf } - - for _, fontSize := range d2fonts.FontSizes { - r.addFontSize(font, fontSize) - } } } @@ -139,13 +135,12 @@ func NewRuler() (*Ruler, error) { return r, nil } -func (r *Ruler) addFontSize(font d2fonts.Font, fontSize int) { +func (r *Ruler) addFontSize(font d2fonts.Font) { sizeless := font sizeless.Size = 0 face := truetype.NewFace(r.ttfs[sizeless], &truetype.Options{ - Size: float64(fontSize), + Size: float64(font.Size), }) - font.Size = fontSize atlas := NewAtlas(face, ASCII) r.atlases[font] = atlas r.lineHeights[font] = atlas.lineHeight @@ -159,7 +154,7 @@ func (t *Ruler) Measure(font d2fonts.Font, s string) (width, height int) { func (t *Ruler) MeasurePrecise(font d2fonts.Font, s string) (width, height float64) { if _, ok := t.atlases[font]; !ok { - t.addFontSize(font, font.Size) + t.addFontSize(font) } t.clear() t.buf = append(t.buf, s...) @@ -229,3 +224,11 @@ func (txt *Ruler) drawBuf(font d2fonts.Font) { } } } + +func (ruler *Ruler) spaceWidth(font d2fonts.Font) float64 { + if _, has := ruler.atlases[font]; !has { + ruler.addFontSize(font) + } + spaceRune, _ := utf8.DecodeRuneInString(" ") + return ruler.atlases[font].glyph(spaceRune).advance +}