Make Image component's srcSet reactive

This commit is contained in:
2021-10-23 15:30:58 +02:00
parent a2c0842aa7
commit ff4222c05e

View File

@@ -17,15 +17,7 @@
large?: { width?: number, height?: number }
}
/**
* Get asset url from size
* @description Adds the size and the format to the result
* @returns string `id?key={key}-{size}-{format}`
*/
const getSizeUrl = (key: string, size: string, format: string) => {
return getAssetUrlKey(id, `${key}-${size}-${format}`)
}
let srcSet = { webp: [], jpg: [] }
/**
@@ -52,20 +44,32 @@
/**
* Image attributes
*/
const imgWidth: number = sizes && sizes.small ? sizes.small.width : width
const imgHeight: number = sizes && sizes.small ? sizes.small.height : height
const imgSrc = id ? getSizeUrl(sizeKey, 'small', 'jpg') : src ? src : null
$: imgWidth = sizes && sizes.small ? sizes.small.width : width
$: imgHeight = sizes && sizes.small ? sizes.small.height : height
$: imgSrc = id ? getAssetUrlKey(id, `${sizeKey}-small-jpg`) : src ? src : null
$: srcSet = {
webp: [
`${getAssetUrlKey(id, `${sizeKey}-small-webp`)} 345w`,
sizes && sizes.medium ? `${getAssetUrlKey(id, `${sizeKey}-medium-webp`)} 768w` : null,
sizes && sizes.large ? `${getAssetUrlKey(id, `${sizeKey}-large-webp`)} 1280w` : null,
],
jpg: [
`${getAssetUrlKey(id, `${sizeKey}-small-jpg`)} 345w`,
sizes && sizes.medium ? `${getAssetUrlKey(id, `${sizeKey}-medium-jpg`)} 768w` : null,
sizes && sizes.large ? `${getAssetUrlKey(id, `${sizeKey}-large-jpg`)} 1280w` : null,
]
}
</script>
<picture class={$$props.class ? $$props.class : ''}>
<source
type="image/webp"
srcset="{getSizeUrl(sizeKey, 'small', 'webp')} 345w {sizes && sizes.medium ? `, ${getSizeUrl(sizeKey, 'medium', 'webp')} 768w,` : ''} {sizes && sizes.large ? `, ${getSizeUrl(sizeKey, 'large', 'webp')} 1280w` : ''}"
srcset={srcSet.webp.join(', ').trim()}
>
<img
src={imgSrc}
sizes="(min-width: 1200px) 864px, (min-width: 992px) 708px, (min-width: 768px) 540px, 100%"
srcset="{getSizeUrl(sizeKey, 'small', 'jpg')} 300w {sizes && sizes.medium ? `, ${getSizeUrl(sizeKey, 'medium', 'jpg')} 768w` : ''} {sizes && sizes.large ? `, ${getSizeUrl(sizeKey, 'large', 'jpg')} 1280w` : ''}"
srcset={srcSet.jpg.join(', ').trim()}
width={imgWidth}
height={imgHeight}
alt={alt}