piekarnikgosipl/html/image.templ
2026-06-15 20:06:43 +02:00

57 lines
1.6 KiB
Text

package html
import (
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"piekarnikgosi/utils"
)
func imageSrcDst(input string) (src, dst string) {
src = "img/" + input
hash := sha256.Sum256([]byte(input))
dst = "www/images/" + hex.EncodeToString(hash[:])[:16] + ".avif"
return src, dst
}
func processImage(fileName string) string {
dst, _ := utils.CopyIfNotExists(imageSrcDst(fileName))
return "/" + dst[4:]
}
func thumbnailPath(fullPath string) string {
ext := filepath.Ext(fullPath)
return fullPath[:len(fullPath)-len(ext)] + "_thumb.avif"
}
templ AvifAlbumImage(srcPath, alt string) {
<img
src={ processImage(albumImageSrc(srcPath)) }
data-fullsrc={ processImage(srcPath) }
alt={ alt }
loading="lazy"
/>
}
func albumImageSrc(srcPath string) string {
thumb := thumbnailPath(srcPath)
if _, err := os.Stat("img/" + thumb); err == nil {
return thumb
}
return srcPath
}
templ AvifImage(srcPath, alt string, lazy bool) {
<img
src={ processImage(srcPath) }
alt={ alt }
if lazy {
loading="lazy"
} else {
fetchpriority="high"
}
onerror="this.onerror=null;this.parentElement.style.position='relative';this.src='data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 24 24%27 fill=%27none%27 stroke=%27currentColor%27 stroke-width=%272%27 stroke-linecap=%27round%27 stroke-linejoin=%27round%27%3E%3Ccircle cx=%2712%27 cy=%2712%27 r=%2710%27/%3E%3Cline x1=%2712%27 x2=%2712%27 y1=%278%27 y2=%2712%27/%3E%3Cline x1=%2712%27 x2=%2712.01%27 y1=%2716%27 y2=%2716%27/%3E%3C/svg%3E';this.style.cssText='width:48px;height:48px;object-fit:contain;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)'"
/>
}