code.gitea.io/gitea@v1.19.3/modules/svg/svg.go (about)

     1  // Copyright 2020 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package svg
     5  
     6  import (
     7  	"fmt"
     8  	"html/template"
     9  	"regexp"
    10  	"strings"
    11  
    12  	"code.gitea.io/gitea/modules/html"
    13  )
    14  
    15  var (
    16  	// SVGs contains discovered SVGs
    17  	SVGs map[string]string
    18  
    19  	widthRe  = regexp.MustCompile(`width="[0-9]+?"`)
    20  	heightRe = regexp.MustCompile(`height="[0-9]+?"`)
    21  )
    22  
    23  const defaultSize = 16
    24  
    25  // Init discovers SVGs and populates the `SVGs` variable
    26  func Init() {
    27  	SVGs = Discover()
    28  }
    29  
    30  // Render render icons - arguments icon name (string), size (int), class (string)
    31  func RenderHTML(icon string, others ...interface{}) template.HTML {
    32  	size, class := html.ParseSizeAndClass(defaultSize, "", others...)
    33  
    34  	if svgStr, ok := SVGs[icon]; ok {
    35  		if size != defaultSize {
    36  			svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size))
    37  			svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size))
    38  		}
    39  		if class != "" {
    40  			svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1)
    41  		}
    42  		return template.HTML(svgStr)
    43  	}
    44  	return template.HTML("")
    45  }