Browse Source

feat: src and srcSet, better sizes

fix/headings-faq
Thomas Osmonson 4 years ago
committed by Thomas Osmonson
parent
commit
1c7c618812
  1. 19
      src/components/mdx/image.tsx

19
src/components/mdx/image.tsx

@ -18,23 +18,36 @@ const getUrl = pathname => {
}; };
const useImgix = (src: string) => { const useImgix = (src: string) => {
if (process.env.NODE_ENV !== 'production' || !src) return src; if (process.env.NODE_ENV !== 'production' || !src)
return {
src,
srcset: undefined,
};
let _src = src; let _src = src;
const router = useRouter(); const router = useRouter();
if (!src?.startsWith('http')) { if (!src?.startsWith('http')) {
const path = src.startsWith('/') ? '' : getUrl(router.pathname); const path = src.startsWith('/') ? '' : getUrl(router.pathname);
_src = `${imgix + path + src + params}`; _src = `${imgix + path + src + params}`;
} }
return _src; const srcset = `${_src}&w=860&dpr=1&fit=max 1x,
${_src}&w=480&fit=max&q=40&dpr=2 2x,
${_src}&w=480&fit=max&q=20&dpr=3 3x`;
const base = `${_src}&w=720&dpr=1&fit=max`;
return {
srcset,
src: base,
};
}; };
export const Img: React.FC<BoxProps & { loading?: string; src?: string; alt?: string }> = ({ export const Img: React.FC<BoxProps & { loading?: string; src?: string; alt?: string }> = ({
src: _src, src: _src,
...rest ...rest
}) => { }) => {
const src = useImgix(_src); const { src, srcset } = useImgix(_src);
const props = { const props = {
src, src,
srcSet: srcset,
...rest, ...rest,
}; };
return <Box loading="lazy" maxWidth="100%" display="block" as="img" {...props} />; return <Box loading="lazy" maxWidth="100%" display="block" as="img" {...props} />;

Loading…
Cancel
Save