enforce loading=lazy att to rendered images html
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -24,6 +25,11 @@ func TestFormatter_FormatText(t *testing.T) {
|
||||
"<p><a href=\"http://127.0.0.1/some-long-link/12345/678901234567890\">http://127.0.0." +
|
||||
"1/some-long-link/12345/6789012...</a></p>\n!converted", "links",
|
||||
},
|
||||
{
|
||||
"something <img src=\"some.png\"/> _aaa_",
|
||||
"<p>something <img src=\"some.png\" loading=\"lazy\"/> <em>aaa</em></p>\n!converted",
|
||||
"lazy image",
|
||||
},
|
||||
{"— not translated #354", "<p>— not translated #354</p>\n!converted", "mdash"},
|
||||
{"smth\n```go\nfunc main(aa string) int {return 0}\n```", `<p>smth</p>
|
||||
<pre class="chroma"><span class="kd">func</span> <span class="nf">main</span><span class="p">(</span><span class="nx">aa</span> <span class="kt">string</span><span class="p">)</span> <span class="kt">int</span> <span class="p">{</span><span class="k">return</span> <span class="mi">0</span><span class="p">}</span>
|
||||
@@ -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 <img src="some.png" />`, `blah <img src="some.png" loading="lazy"/>`},
|
||||
{`blah <img src="some.png" loading="lazy"/>`, `blah <img src="some.png" loading="lazy"/>`},
|
||||
{`blah <img src="some.png"/> ххх <img src=http://example.com/pp2.jpg>`, `blah <img src="some.png" loading="lazy"/> ххх <img src="http://example.com/pp2.jpg" loading="lazy"/>`},
|
||||
}
|
||||
|
||||
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))
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user