Browse Source

feat(icon): minify svg favicons

jvoisin 7 months ago
parent
commit
cad40cc158
2 changed files with 28 additions and 1 deletions
  1. 15 1
      internal/reader/icon/finder.go
  2. 13 0
      internal/reader/icon/finder_test.go

+ 15 - 1
internal/reader/icon/finder.go

@@ -26,6 +26,8 @@ import (
 	"miniflux.app/v2/internal/urllib"
 
 	"github.com/PuerkitoBio/goquery"
+	"github.com/tdewolff/minify/v2"
+	"github.com/tdewolff/minify/v2/svg"
 	"golang.org/x/image/draw"
 	"golang.org/x/image/webp"
 )
@@ -194,13 +196,25 @@ func (f *iconFinder) downloadIcon(iconURL string) (*model.Icon, error) {
 }
 
 func resizeIcon(icon *model.Icon) *model.Icon {
-	r := bytes.NewReader(icon.Content)
+	if icon.MimeType == "image/svg+xml" {
+		minifier := minify.New()
+		minifier.AddFunc("image/svg+xml", svg.Minify)
+		var err error
+		// minifier.Bytes returns the data unchanged in case of error.
+		icon.Content, err = minifier.Bytes("image/svg+xml", icon.Content)
+		if err != nil {
+			slog.Error("Unable to minimize the svg file", slog.Any("error", err))
+		}
+		return icon
+	}
 
 	if !slices.Contains([]string{"image/jpeg", "image/png", "image/gif", "image/webp"}, icon.MimeType) {
 		slog.Info("icon isn't a png/gif/jpeg/webp, can't resize", slog.String("mimetype", icon.MimeType))
 		return icon
 	}
 
+	r := bytes.NewReader(icon.Content)
+
 	// Don't resize icons that we can't decode, or that already have the right size.
 	config, _, err := image.DecodeConfig(r)
 	if err != nil {

+ 13 - 0
internal/reader/icon/finder_test.go

@@ -194,3 +194,16 @@ func TestResizeInvalidImage(t *testing.T) {
 		t.Fatalf("Tried to convert an invalid image")
 	}
 }
+func TestMinifySvg(t *testing.T) {
+	data := []byte(`<svg path d=" M1 4h-.001 V1h2v.001 M1 2.6 h1v.001"/></svg>`)
+	want := []byte(`<svg path="" d="M1 4H.999V1h2v.001M1 2.6h1v.001"/></svg>`)
+
+	icon := model.Icon{
+		Content:  data,
+		MimeType: "image/svg+xml",
+	}
+	got := resizeIcon(&icon).Content
+	if !bytes.Equal(want, got) {
+		t.Fatalf("Didn't correctly minimize the svg: got %s instead of %s", got, want)
+	}
+}