2020-07-12 05:10:56 -04:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
2022-11-27 13:20:29 -05:00
|
|
|
// SPDX-License-Identifier: MIT
|
2020-07-12 05:10:56 -04:00
|
|
|
|
|
|
|
package svg
|
|
|
|
|
2022-11-08 10:13:58 -05:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"html/template"
|
2023-04-12 06:16:45 -04:00
|
|
|
"path"
|
2022-11-08 10:13:58 -05:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"code.gitea.io/gitea/modules/html"
|
2023-04-12 06:16:45 -04:00
|
|
|
"code.gitea.io/gitea/modules/log"
|
|
|
|
"code.gitea.io/gitea/modules/public"
|
2022-11-08 10:13:58 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// SVGs contains discovered SVGs
|
2023-04-12 06:16:45 -04:00
|
|
|
SVGs = map[string]string{}
|
2022-11-08 10:13:58 -05:00
|
|
|
|
|
|
|
widthRe = regexp.MustCompile(`width="[0-9]+?"`)
|
|
|
|
heightRe = regexp.MustCompile(`height="[0-9]+?"`)
|
|
|
|
)
|
|
|
|
|
|
|
|
const defaultSize = 16
|
2020-07-12 05:10:56 -04:00
|
|
|
|
|
|
|
// Init discovers SVGs and populates the `SVGs` variable
|
2023-04-12 06:16:45 -04:00
|
|
|
func Init() error {
|
|
|
|
files, err := public.AssetFS().ListFiles("img/svg")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-03-21 01:39:27 -04:00
|
|
|
|
|
|
|
// Remove `xmlns` because inline SVG does not need it
|
2023-04-12 06:16:45 -04:00
|
|
|
reXmlns := regexp.MustCompile(`(<svg\b[^>]*?)\s+xmlns="[^"]*"`)
|
|
|
|
for _, file := range files {
|
|
|
|
if path.Ext(file) != ".svg" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
bs, err := public.AssetFS().ReadFile("img/svg", file)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("Failed to read SVG file %s: %v", file, err)
|
|
|
|
} else {
|
|
|
|
SVGs[file[:len(file)-4]] = reXmlns.ReplaceAllString(string(bs), "$1")
|
|
|
|
}
|
2023-03-21 01:39:27 -04:00
|
|
|
}
|
2023-04-12 06:16:45 -04:00
|
|
|
return nil
|
2020-07-12 05:10:56 -04:00
|
|
|
}
|
2022-11-08 10:13:58 -05:00
|
|
|
|
2023-04-12 06:16:45 -04:00
|
|
|
// RenderHTML renders icons - arguments icon name (string), size (int), class (string)
|
2023-07-04 23:41:32 -04:00
|
|
|
func RenderHTML(icon string, others ...any) template.HTML {
|
2022-11-08 10:13:58 -05:00
|
|
|
size, class := html.ParseSizeAndClass(defaultSize, "", others...)
|
|
|
|
|
|
|
|
if svgStr, ok := SVGs[icon]; ok {
|
|
|
|
if size != defaultSize {
|
|
|
|
svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size))
|
|
|
|
svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size))
|
|
|
|
}
|
|
|
|
if class != "" {
|
|
|
|
svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1)
|
|
|
|
}
|
|
|
|
return template.HTML(svgStr)
|
|
|
|
}
|
2023-06-13 08:04:40 -04:00
|
|
|
return ""
|
2022-11-08 10:13:58 -05:00
|
|
|
}
|