forked from Greenstand/treetracker-admin-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add optimized images (Greenstand#20)
* feat: add optimized images * feat: add fallback src
- Loading branch information
1 parent
3de6580
commit f9e57ec
Showing
5 changed files
with
696 additions
and
486 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import React from 'react'; | ||
|
||
export default function OptimizedImage(props) { | ||
const { | ||
src, | ||
width = 320, | ||
height, | ||
quality, | ||
screenWidths = [1600, 1280, 960, 0], | ||
imageSizes = [400, 300, 250, 200], | ||
fixed, | ||
...rest | ||
} = props; | ||
|
||
if (!src) return <></>; | ||
|
||
const cdnPath = 'https://cdn.statically.io/img'; | ||
const matches = src.match(/\/\/(.*)\/(.*)/); | ||
|
||
let cdnUrl, sizes, srcSet; | ||
|
||
if (matches?.length > 1) { | ||
const domain = matches[1]; | ||
const imagePath = matches[2]; | ||
const params = | ||
`f=auto,w=${width}` + | ||
(height ? `,h=${height}` : '') + | ||
(quality ? `,q=${quality}` : ''); | ||
|
||
cdnUrl = `${cdnPath}/${domain}/${params}/${imagePath}`; | ||
|
||
if (!fixed && screenWidths.length === imageSizes.length) { | ||
sizes = screenWidths | ||
.map((size, i) => `(min-width: ${size}px) ${imageSizes[i]}px`) | ||
.join(', '); | ||
srcSet = imageSizes | ||
.map((size) => `${cdnPath}/${domain}/${params}/${imagePath} ${size}w`) | ||
.join(', '); | ||
} | ||
} | ||
|
||
return ( | ||
<> | ||
<img | ||
src={cdnUrl || src} | ||
alt=".." | ||
srcSet={srcSet} | ||
sizes={sizes} | ||
loading="lazy" | ||
style={{ | ||
position: 'absolute', | ||
inset: 0, | ||
objectFit: 'cover', | ||
width: '100%', | ||
height: '100%', | ||
}} | ||
{...rest} | ||
/> | ||
</> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.