From 89a4677391a76bef302fcb701313c425df0afdd3 Mon Sep 17 00:00:00 2001 From: Umputun Date: Sun, 17 Jan 2021 16:26:48 -0600 Subject: [PATCH] enforce loading=lazy att to rendered images html --- backend/app/store/formatter.go | 17 +++++++++++++++++ backend/app/store/formatter_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/backend/app/store/formatter.go b/backend/app/store/formatter.go index 0cff0007..0522eef9 100644 --- a/backend/app/store/formatter.go +++ b/backend/app/store/formatter.go @@ -59,6 +59,7 @@ func (f *CommentFormatter) FormatText(txt string) (res string) { res = conv.Convert(res) } res = f.shortenAutoLinks(res, shortURLLen) + res = f.lazyImage(res) return res } @@ -108,3 +109,19 @@ func (f *CommentFormatter) unEscape(txt string) (res string) { } return res } + +// lazyImage adds loading=“lazy” attribute to all images +func (f *CommentFormatter) lazyImage(commentHTML string) (resHTML string) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(commentHTML)) + if err != nil { + return commentHTML + } + doc.Find("img").Each(func(i int, s *goquery.Selection) { + s.SetAttr("loading", "lazy") + }) + resHTML, err = doc.Find("body").Html() + if err != nil { + return commentHTML + } + return resHTML +} diff --git a/backend/app/store/formatter_test.go b/backend/app/store/formatter_test.go index 7bc5182e..29af0224 100644 --- a/backend/app/store/formatter_test.go +++ b/backend/app/store/formatter_test.go @@ -1,6 +1,7 @@ package store import ( + "strconv" "testing" "time" @@ -24,6 +25,11 @@ func TestFormatter_FormatText(t *testing.T) { "

http://127.0.0." + "1/some-long-link/12345/6789012...

\n!converted", "links", }, + { + "something _aaa_", + "

something aaa

\n!converted", + "lazy image", + }, {"— not translated #354", "

— not translated #354

\n!converted", "mdash"}, {"smth\n```go\nfunc main(aa string) int {return 0}\n```", `

smth

func main(aa string) int {return 0}
@@ -114,3 +120,24 @@ func TestFormatter_ShortenAutoLinks(t *testing.T) {
 		assert.Equalf(t, tt.out, got, "check #%d", n)
 	}
 }
+
+func TestCommentFormatter_lazyImage(t *testing.T) {
+
+	tbl := []struct {
+		inp, out string
+	}{
+		{"", ""},
+		{`blah `, `blah `},
+		{`blah `, `blah `},
+		{`blah  ххх `, `blah  ххх `},
+	}
+
+	f := NewCommentFormatter(nil)
+	for i, tt := range tbl {
+		tt := tt
+		t.Run(strconv.Itoa(i), func(t *testing.T) {
+			assert.Equal(t, tt.out, f.lazyImage(tt.inp))
+		})
+	}
+
+}