diff --git a/plugins/picture.ts b/plugins/picture.ts index b101ffad2..9dc3b106e 100644 --- a/plugins/picture.ts +++ b/plugins/picture.ts @@ -90,23 +90,35 @@ export default function (): Plugin { basePath: string, ) { const src = img.getAttribute("src") as string; + const sizes = img.getAttribute("sizes"); const sourceFormats = saveTransform(basePath, src, imagick); for (const sourceFormat of sourceFormats) { - const source = createSource(img.ownerDocument!, src, sourceFormat); + const source = createSource( + img.ownerDocument!, + src, + sourceFormat, + sizes, + ); picture.insertBefore(source, img); } } function handleImg(imagick: string, img: Element, basePath: string) { const src = img.getAttribute("src") as string; + const sizes = img.getAttribute("sizes"); const sourceFormats = saveTransform(basePath, src, imagick); const picture = img.ownerDocument!.createElement("picture"); img.replaceWith(picture); for (const sourceFormat of sourceFormats) { - const source = createSource(img.ownerDocument!, src, sourceFormat); + const source = createSource( + img.ownerDocument!, + src, + sourceFormat, + sizes, + ); picture.append(source); } @@ -194,19 +206,29 @@ function createSource( document: Document, src: string, srcFormat: SourceFormat, + sizes?: string | null | undefined, ) { const source = document.createElement("source"); - const { scales, format } = srcFormat; + const { scales, format, width } = srcFormat; const path = encodeURI(getPathAndExtension(src)[0]); const srcset: string[] = []; for (const [suffix, scale] of Object.entries(scales)) { - const scaleSuffix = scale === 1 ? "" : ` ${scale}x`; + const scaleSuffix = sizes + ? ` ${scale * width}w` + : scale === 1 + ? "" + : ` ${scale}x`; srcset.push(`${path}${suffix}.${format}${scaleSuffix}`); } source.setAttribute("srcset", srcset.join(", ")); source.setAttribute("type", typeByExtension(format)); + + if (sizes) { + source.setAttribute("sizes", sizes); + } + return source; } diff --git a/tests/__snapshots__/picture.test.ts.snap b/tests/__snapshots__/picture.test.ts.snap index 171d71891..ed185d8c8 100644 --- a/tests/__snapshots__/picture.test.ts.snap +++ b/tests/__snapshots__/picture.test.ts.snap @@ -112,6 +112,8 @@ snapshot[`imagick plugin 3`] = ` + +
@@ -125,6 +127,20 @@ snapshot[`imagick plugin 3`] = ` + +
+ +
+ + + + + + + + + + ', data: { children: ' @@ -134,6 +150,8 @@ snapshot[`imagick plugin 3`] = ` + +
@@ -145,6 +163,20 @@ snapshot[`imagick plugin 3`] = ` + + + +
+ +
+ + + + + + + + ', @@ -155,6 +187,8 @@ snapshot[`imagick plugin 3`] = ` + +
@@ -166,6 +200,20 @@ snapshot[`imagick plugin 3`] = ` + + + +
+ +
+ + + + + + + + ', diff --git a/tests/assets/picture/index.njk b/tests/assets/picture/index.njk index 71e85ee13..f2e498bb8 100644 --- a/tests/assets/picture/index.njk +++ b/tests/assets/picture/index.njk @@ -5,6 +5,8 @@ + +
@@ -16,5 +18,19 @@ + + + +
+ +
+ + + + + + + +