Skip to content

Commit

Permalink
chore: optimize images (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
flaff authored Apr 5, 2021
1 parent 3524397 commit ea3ebaa
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/components/Project.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const DetailsButton = styled(Button)`
}
`

const Project = ({ project, images }) => {
const Project = ({ project }) => {
const { title, description, artPieces } = project
const [detailsVisible, setDetailsVisible] = useState(false)
const { t } = useSimpleTranslation()
Expand Down
4 changes: 2 additions & 2 deletions src/components/SimpleLazyGallery.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ const SimpleLazyGallery = ({ artPieces }) => {
return (
<MasonGridImageWrapper>
<GatsbyImage
image={getSanityGatsbyImageData(image)}
image={getSanityGatsbyImageData(image, { width: 400 })}
key={slug.current}
alt={t(image.alt) || t(title)}
/>
</MasonGridImageWrapper>
)
}),
[artPieces]
[artPieces, t]
)

return <MasonGrid>{imageElements}</MasonGrid>
Expand Down
42 changes: 32 additions & 10 deletions src/utils/getSanityGatsbyImageData.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,41 @@ const DEFAULT_OPTIONS = {
placeholder: "blurred",
}

function stringifyParams(params) {
return Object.entries(params)
.map(([key, value]) => `${key}=${value}`)
.join("&")
}

function addQueryParams(url, params) {
const queryParams = stringifyParams(params)
return url.includes("?")
? url.replace("?", `?${queryParams}&`)
: `${url}?${stringifyParams(params)}`
}

function modifyImages(imageProps, params) {
imageProps.images.fallback.src = addQueryParams(
imageProps.images.fallback.src,
params
)
imageProps.images.fallback.srcSet = imageProps.images.fallback.srcSet
.split(",")
.map(srcSet => addQueryParams(srcSet, params))
.join(",")
}

const getSanityGatsbyImageData = (image, options) => {
const mergedOptions = { ...DEFAULT_OPTIONS, ...options };
const imageProps = getGatsbyImageData(
image,
mergedOptions,
SANITY_CONFIG
);

if (mergedOptions.placeholder === 'blurred') {
const mergedOptions = { ...DEFAULT_OPTIONS, ...options }
const imageProps = getGatsbyImageData(image, mergedOptions, SANITY_CONFIG)

if (mergedOptions.placeholder === "blurred") {
imageProps.placeholder = { fallback: image.asset.metadata.lqip }
}

return imageProps;

modifyImages(imageProps, { q: 50 })

return imageProps
}

export default getSanityGatsbyImageData

0 comments on commit ea3ebaa

Please sign in to comment.