Skip to content

Commit

Permalink
Fix formatted srcset
Browse files Browse the repository at this point in the history
  • Loading branch information
seantiz committed Dec 20, 2024
1 parent c017e14 commit 18d46d6
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions enhancedimg/findAndReplace.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,27 +115,44 @@ func createPictureElement(ei enhancedImg, originalImg *html.Node) *html.Node {
Data: "picture",
}

// Readable formatting in target picture templates
picture.AppendChild(&html.Node{Type: html.TextNode, Data: "\n"})

for format, srcsets := range ei.sources {
source := &html.Node{
Type: html.ElementNode,
Data: "source",
}
setAttr(source, "srcset", strings.Join(srcsets, ", "))

formattedSrcset := strings.Join(srcsets, ",\n ")

setAttr(source, "srcset", formattedSrcset)
setAttr(source, "type", "image/"+format)
setAttr(source, "sizes", "(max-width: 640px) 640px, (max-width: 1024px) 1024px, 1920px")
setAttr(source, "sizes", "(max-width: 640px) 640px,\n (max-width: 768px) 768px,\n (max-width: 1024px) 1024px,\n 1280px")

picture.AppendChild(&html.Node{Type: html.TextNode, Data: " "})
picture.AppendChild(source)
picture.AppendChild(&html.Node{Type: html.TextNode, Data: "\n"})
}

img := &html.Node{
Type: html.ElementNode,
Data: "img",
}
setAttr(img, "src", "/"+strings.TrimPrefix(ei.img.src, "/"))
setAttr(img, "width", fmt.Sprintf("%d", ei.img.width))
setAttr(img, "height", fmt.Sprintf("%d", ei.img.height))

// Default src is medium variant
mediumSrc := "/static/processed/" + strings.TrimPrefix(ei.img.src, "/")
mediumSrc = strings.Replace(mediumSrc, filepath.Ext(mediumSrc), "-md-768"+filepath.Ext(mediumSrc), 1)

setAttr(img, "src", mediumSrc)
setAttr(img, "width", "768")
setAttr(img, "height", fmt.Sprintf("%d", int(float64(768)*float64(ei.img.height)/float64(ei.img.width))))
setAttr(img, "loading", "lazy")
setAttr(img, "class", getAttr(originalImg, "class"))

picture.AppendChild(&html.Node{Type: html.TextNode, Data: " "})
picture.AppendChild(img)
picture.AppendChild(&html.Node{Type: html.TextNode, Data: "\n "})

return picture
}

0 comments on commit 18d46d6

Please sign in to comment.