Add data-srcset support to "add_dynamic_image rewrite" rewrite rule

This commit is contained in:
Artémis 2021-10-23 03:12:23 +02:00 committed by GitHub
parent d45e1b3bed
commit b585dab6b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View File

@ -100,9 +100,14 @@ func addDynamicImage(entryURL, entryContent string) string {
"data-380src",
}
candidateSrcsetAttrs := []string{
"data-srcset",
}
changed := false
doc.Find("img,div").Each(func(i int, img *goquery.Selection) {
// Src-linked candidates
for _, candidateAttr := range candidateAttrs {
if srcAttr, found := img.Attr(candidateAttr); found {
changed = true
@ -117,6 +122,22 @@ func addDynamicImage(entryURL, entryContent string) string {
break
}
}
// Srcset-linked candidates
for _, candidateAttr := range candidateSrcsetAttrs {
if srcAttr, found := img.Attr(candidateAttr); found {
changed = true
if img.Is("img") {
img.SetAttr("srcset", srcAttr)
} else {
altAttr := img.AttrOr("alt", "")
img.ReplaceWithHtml(`<img srcset="` + srcAttr + `" alt="` + altAttr + `"/>`)
}
break
}
}
})
if !changed {

View File

@ -176,6 +176,26 @@ func TestRewriteWithUnknownLazyNoScriptImage(t *testing.T) {
}
}
func TestRewriteWithLazySrcset(t *testing.T) {
description := `<img srcset="" data-srcset="https://example.org/image.jpg" alt="Image">`
output := Rewriter("https://example.org/article", description, "add_dynamic_image")
expected := `<img srcset="https://example.org/image.jpg" data-srcset="https://example.org/image.jpg" alt="Image"/>`
if expected != output {
t.Errorf(`Not expected output: got "%s" instead of "%s"`, output, expected)
}
}
func TestRewriteWithImageAndLazySrcset(t *testing.T) {
description := `<img src="meow" srcset="" data-srcset="https://example.org/image.jpg" alt="Image">`
output := Rewriter("https://example.org/article", description, "add_dynamic_image")
expected := `<img src="meow" srcset="https://example.org/image.jpg" data-srcset="https://example.org/image.jpg" alt="Image"/>`
if expected != output {
t.Errorf(`Not expected output: got "%s" instead of "%s"`, output, expected)
}
}
func TestNewLineRewriteRule(t *testing.T) {
description := "A\nB\nC"
output := Rewriter("https://example.org/article", description, "nl2br")