UNPKG

gatsby-plugin-image

Version:

Adding responsive images to your site while maintaining high performance scores can be difficult to do manually. The Gatsby Image plugin handles the hard parts of producing images in multiple sizes and formats for you!

3 lines (2 loc) 19.4 kB
import*as e from"react";import t,{Fragment as r,forwardRef as i,createRef as a,Component as n}from"react";import{stripIndent as o}from"common-tags";import s from"camelcase";import*as l from"prop-types";import d from"prop-types";function u(){return u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},u.apply(this,arguments)}function c(e,t){return c=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},c(e,t)}function h(e,t){if(null==e)return{};var r,i,a={},n=Object.keys(e);for(i=0;i<n.length;i++)t.indexOf(r=n[i])>=0||(a[r]=e[r]);return a}var p,g=[.25,.5,1,2],f=[750,1080,1366,1920],m=[320,654,768,1024,1366,1600,1920,2048,2560,3440,3840,4096],v=function(e){return console.warn(e)},y=function(e,t){return e-t},w=function(e){return e.map(function(e){return e.src+" "+e.width+"w"}).join(",\n")};function b(e){var t=e.lastIndexOf(".");if(-1!==t){var r=e.slice(t+1);if("jpeg"===r)return"jpg";if(3===r.length||4===r.length)return r}}function E(e){var t=e.layout,r=void 0===t?"constrained":t,i=e.width,a=e.height,n=e.sourceMetadata,o=e.breakpoints,l=e.aspectRatio,d=e.formats,c=void 0===d?["auto","webp"]:d;return c=c.map(function(e){return e.toLowerCase()}),r=s(r),i&&a?u({},e,{formats:c,layout:r,aspectRatio:i/a}):(n.width&&n.height&&!l&&(l=n.width/n.height),"fullWidth"===r?(i=i||n.width||o[o.length-1],a=a||Math.round(i/(l||1.3333333333333333))):(i||(i=a&&l?a*l:n.width?n.width:a?Math.round(a/1.3333333333333333):800),l&&!a?a=Math.round(i/l):l||(l=i/a)),u({},e,{width:i,height:a,aspectRatio:l,layout:r,formats:c}))}function R(e,t){var r;return void 0===t&&(t=20),null==(r=(0,(e=E(e)).generateImageSource)(e.filename,t,Math.round(t/e.aspectRatio),e.sourceMetadata.format||"jpg",e.fit,e.options))?void 0:r.src}function S(e){var t,r=(e=E(e)).pluginName,i=e.sourceMetadata,a=e.generateImageSource,n=e.layout,s=e.fit,l=e.options,d=e.width,c=e.height,h=e.filename,m=e.reporter,y=void 0===m?{warn:v}:m,R=e.backgroundColor,S=e.placeholderURL;if(r||y.warn('[gatsby-plugin-image] "generateImageData" was not passed a plugin name'),"function"!=typeof a)throw new Error("generateImageSource must be a function");i&&(i.width||i.height)?i.format||(i.format=b(h)):i={width:d,height:c,format:(null==(t=i)?void 0:t.format)||b(h)||"auto"};var _=new Set(e.formats);(0===_.size||_.has("auto")||_.has(""))&&(_.delete("auto"),_.delete(""),_.add(i.format)),_.has("jpg")&&_.has("png")&&(y.warn("["+r+"] Specifying both 'jpg' and 'png' formats is not supported. Using 'auto' instead"),_.delete("jpg"===i.format?"png":"jpg"));var j=function(e){var t=e.filename,r=e.layout,i=void 0===r?"constrained":r,a=e.sourceMetadata,n=e.reporter,s=void 0===n?{warn:v}:n,l=e.breakpoints,d=void 0===l?f:l,c=Object.entries({width:e.width,height:e.height}).filter(function(e){var t=e[1];return"number"==typeof t&&t<1});if(c.length)throw new Error("Specified dimensions for images must be positive numbers (> 0). Problem dimensions you have are "+c.map(function(e){return e.join(": ")}).join(", "));return"fixed"===i?function(e){var t=e.filename,r=e.sourceMetadata,i=e.width,a=e.height,n=e.fit,s=void 0===n?"cover":n,l=e.outputPixelDensities,d=e.reporter,u=void 0===d?{warn:v}:d,c=r.width/r.height,h=M(void 0===l?g:l);if(i&&a){var f=k(r,{width:i,height:a,fit:s});i=f.width,a=f.height,c=f.aspectRatio}i?a||(a=Math.round(i/c)):i=a?Math.round(a*c):800;var m,y,w=i;if(r.width<i||r.height<a){var b=r.width<i?"width":"height";u.warn(o(p||(m=["\n The requested ",' "','px" for the image '," was larger than the actual image "," of ","px. If possible, replace the current image with a larger one."],y||(y=m.slice(0)),m.raw=y,p=m),b,"width"===b?i:a,t,b,r[b])),"width"===b?(i=r.width,a=Math.round(i/c)):i=(a=r.height)*c}return{sizes:h.filter(function(e){return e>=1}).map(function(e){return Math.round(e*i)}).filter(function(e){return e<=r.width}),aspectRatio:c,presentationWidth:w,presentationHeight:Math.round(w/c),unscaledWidth:i}}(e):"constrained"===i?L(e):"fullWidth"===i?L(u({breakpoints:d},e)):(s.warn("No valid layout was provided for the image at "+t+". Valid image layouts are fixed, fullWidth, and constrained. Found "+i),{sizes:[a.width],presentationWidth:a.width,presentationHeight:a.height,aspectRatio:a.width/a.height,unscaledWidth:a.width})}(u({},e,{sourceMetadata:i})),N={sources:[]},x=e.sizes;x||(x=function(e,t){switch(t){case"constrained":return"(min-width: "+e+"px) "+e+"px, 100vw";case"fixed":return e+"px";case"fullWidth":return"100vw";default:return}}(j.presentationWidth,n)),_.forEach(function(e){var t=j.sizes.map(function(t){var i=a(h,t,Math.round(t/j.aspectRatio),e,s,l);if(null!=i&&i.width&&i.height&&i.src&&i.format)return i;y.warn("["+r+"] The resolver for image "+h+" returned an invalid value.")}).filter(Boolean);if("jpg"===e||"png"===e||"auto"===e){var i=t.find(function(e){return e.width===j.unscaledWidth})||t[0];i&&(N.fallback={src:i.src,srcSet:w(t),sizes:x})}else{var n;null==(n=N.sources)||n.push({srcSet:w(t),sizes:x,type:"image/"+e})}});var I={images:N,layout:n,backgroundColor:R};switch(S&&(I.placeholder={fallback:S}),n){case"fixed":I.width=j.presentationWidth,I.height=j.presentationHeight;break;case"fullWidth":I.width=1,I.height=1/j.aspectRatio;break;case"constrained":I.width=e.width||j.presentationWidth||1,I.height=(I.width||1)/j.aspectRatio}return I}var M=function(e){return Array.from(new Set([1].concat(e))).sort(y)};function L(e){var t,r=e.sourceMetadata,i=e.width,a=e.height,n=e.fit,o=void 0===n?"cover":n,s=e.outputPixelDensities,l=e.breakpoints,d=e.layout,u=r.width/r.height,c=M(void 0===s?g:s);if(i&&a){var h=k(r,{width:i,height:a,fit:o});i=h.width,a=h.height,u=h.aspectRatio}i=i&&Math.min(i,r.width),a=a&&Math.min(a,r.height),i||a||(a=(i=Math.min(800,r.width))/u),i||(i=a*u);var p=i;return(r.width<i||r.height<a)&&(i=r.width,a=r.height),i=Math.round(i),(null==l?void 0:l.length)>0?(t=l.filter(function(e){return e<=r.width})).length<l.length&&!t.includes(r.width)&&t.push(r.width):t=(t=c.map(function(e){return Math.round(e*i)})).filter(function(e){return e<=r.width}),"constrained"!==d||t.includes(i)||t.push(i),{sizes:t=t.sort(y),aspectRatio:u,presentationWidth:p,presentationHeight:Math.round(p/u),unscaledWidth:i}}function k(e,t){var r=e.width/e.height,i=t.width,a=t.height;switch(t.fit){case"fill":i=t.width?t.width:e.width,a=t.height?t.height:e.height;break;case"inside":var n=t.width?t.width:Number.MAX_SAFE_INTEGER,o=t.height?t.height:Number.MAX_SAFE_INTEGER;i=Math.min(n,Math.round(o*r)),a=Math.min(o,Math.round(n/r));break;case"outside":var s=t.width?t.width:0,l=t.height?t.height:0;i=Math.max(s,Math.round(l*r)),a=Math.max(l,Math.round(s/r));break;default:t.width&&!t.height&&(i=t.width,a=Math.round(t.width/r)),t.height&&!t.width&&(i=Math.round(t.height*r),a=t.height)}return{width:i,height:a,aspectRatio:i/a}}var _=["baseUrl","urlBuilder","sourceWidth","sourceHeight","pluginName","formats","breakpoints","options"],j=["images","placeholder"],N=new Set,x=function(){return"undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype};function I(){return"undefined"!=typeof GATSBY___IMAGE&&GATSBY___IMAGE}function O(e){e&&N.add(e)}function W(e){return N.has(e)}var z=function(e){var t;return function(e){var t,r;return Boolean(null==e||null==(t=e.images)||null==(r=t.fallback)?void 0:r.src)}(e)?e:function(e){return Boolean(null==e?void 0:e.gatsbyImageData)}(e)?e.gatsbyImageData:null==e||null==(t=e.childImageSharp)?void 0:t.gatsbyImageData},T=function(e){var t,r,i;return null==(t=z(e))||null==(r=t.images)||null==(i=r.fallback)?void 0:i.src},H=function(e){var t,r,i;return null==(t=z(e))||null==(r=t.images)||null==(i=r.fallback)?void 0:i.srcSet};function P(e){var t,r=e.baseUrl,i=e.urlBuilder,a=e.sourceWidth,n=e.sourceHeight,o=e.pluginName,s=void 0===o?"getImageData":o,l=e.formats,d=void 0===l?["auto"]:l,c=e.breakpoints,p=e.options,g=h(e,_);return null!=(t=c)&&t.length||"fullWidth"!==g.layout&&"FULL_WIDTH"!==g.layout||(c=m),S(u({},g,{pluginName:s,generateImageSource:function(e,t,r,a){return{width:t,height:r,format:a,src:i({baseUrl:e,width:t,height:r,options:p,format:a})}},filename:r,formats:d,breakpoints:c,sourceMetadata:{width:a,height:n,format:"auto"}}))}function D(e,t,r,i,a,n,o,s){var l,d;return void 0===s&&(s={}),null!=o&&o.current&&!("objectFit"in document.documentElement.style)&&(o.current.dataset.objectFit=null!=(l=s.objectFit)?l:"cover",o.current.dataset.objectPosition=""+(null!=(d=s.objectPosition)?d:"50% 50%"),function(e){try{var t=function(){window.objectFitPolyfill(e.current)},r=function(){if(!("objectFitPolyfill"in window))return Promise.resolve(import("objectFitPolyfill")).then(function(){})}();Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}}(o)),I()||(s=u({height:"100%",left:0,position:"absolute",top:0,transform:"translateZ(0)",transition:"opacity 250ms linear",width:"100%",willChange:"opacity"},s)),u({},r,{loading:i,shouldLoad:e,"data-main-image":"",style:u({},s,{opacity:t?1:0}),onLoad:function(e){if(!t){O(n);var r=e.currentTarget,i=new Image;i.src=r.currentSrc,i.decode?i.decode().catch(function(){}).then(function(){a(!0)}):a(!0)}},ref:o})}function q(e,t,r,i,a,n,o,s){var l={};n&&(l.backgroundColor=n,"fixed"===r?(l.width=i,l.height=a,l.backgroundColor=n,l.position="relative"):("constrained"===r||"fullWidth"===r)&&(l.position="absolute",l.top=0,l.left=0,l.bottom=0,l.right=0)),o&&(l.objectFit=o),s&&(l.objectPosition=s);var d=u({},e,{"aria-hidden":!0,"data-placeholder-image":"",style:u({opacity:t?0:1,transition:"opacity 500ms linear"},l)});return I()||(d.style={height:"100%",left:0,position:"absolute",top:0,width:"100%"}),d}function C(e,t){var r,i,a,n=e.images,o=e.placeholder,s=u({},h(e,j),{images:u({},n,{sources:[]}),placeholder:o&&u({},o,{sources:[]})});return t.forEach(function(t){var r,i=t.media,a=t.image;i?(a.layout!==e.layout&&"development"===process.env.NODE_ENV&&console.warn('[gatsby-plugin-image] Mismatched image layout: expected "'+e.layout+'" but received "'+a.layout+'". All art-directed images use the same layout as the default image'),(r=s.images.sources).push.apply(r,a.images.sources.map(function(e){return u({},e,{media:i})}).concat([{media:i,srcSet:a.images.fallback.srcSet}])),s.placeholder&&s.placeholder.sources.push({media:i,srcSet:a.placeholder.fallback})):"development"===process.env.NODE_ENV&&console.warn("[gatsby-plugin-image] All art-directed images passed to must have a value set for `media`. Skipping.")}),(r=s.images.sources).push.apply(r,n.sources),null!=o&&o.sources&&(null==(i=s.placeholder)||(a=i.sources).push.apply(a,o.sources)),s}var A,F=["children"],V=function(e){var r=e.layout,i=e.width,a=e.height;return"fullWidth"===r?t.createElement("div",{"aria-hidden":!0,style:{paddingTop:a/i*100+"%"}}):"constrained"===r?t.createElement("div",{style:{maxWidth:i,display:"block"}},t.createElement("img",{alt:"",role:"presentation","aria-hidden":"true",src:"data:image/svg+xml;charset=utf-8,%3Csvg height='"+a+"' width='"+i+"' xmlns='http://www.w3.org/2000/svg' version='1.1'%3E%3C/svg%3E",style:{maxWidth:"100%",display:"block",position:"static"}})):null},G=function(e){var i=e.children,a=h(e,F);return t.createElement(r,null,t.createElement(V,u({},a)),i,!1)},U=["src","srcSet","loading","alt","shouldLoad","innerRef"],B=["fallback","sources","shouldLoad"],J=function(e){var r=e.src,i=e.srcSet,a=e.loading,n=e.alt,o=void 0===n?"":n,s=e.shouldLoad,l=e.innerRef,d=h(e,U);return t.createElement("img",u({},d,{decoding:"async",loading:a,src:s?r:void 0,"data-src":s?void 0:r,srcSet:s?i:void 0,"data-srcset":s?void 0:i,alt:o,ref:l}))},Y=i(function(e,r){var i=e.fallback,a=e.sources,n=void 0===a?[]:a,o=e.shouldLoad,s=void 0===o||o,l=h(e,B),d=l.sizes||(null==i?void 0:i.sizes),c=t.createElement(J,u({},l,i,{sizes:d,shouldLoad:s,innerRef:r}));return n.length?t.createElement("picture",null,n.map(function(e){var r=e.media,i=e.srcSet,a=e.type;return t.createElement("source",{key:r+"-"+a+"-"+i,type:a,media:r,srcSet:s?i:void 0,"data-srcset":s?void 0:i,sizes:d})}),c):c});J.propTypes={src:l.string.isRequired,alt:l.string.isRequired,sizes:l.string,srcSet:l.string,shouldLoad:l.bool},Y.displayName="Picture",Y.propTypes={alt:l.string.isRequired,shouldLoad:l.bool,fallback:l.exact({src:l.string.isRequired,srcSet:l.string,sizes:l.string}),sources:l.arrayOf(l.oneOfType([l.exact({media:l.string.isRequired,type:l.string,sizes:l.string,srcSet:l.string.isRequired}),l.exact({media:l.string,type:l.string.isRequired,sizes:l.string,srcSet:l.string.isRequired})]))};var X=["fallback"],Z=function(e){var r=e.fallback,i=h(e,X);return r?t.createElement(Y,u({},i,{fallback:{src:r},"aria-hidden":!0,alt:""})):t.createElement("div",u({},i))};Z.displayName="Placeholder",Z.propTypes={fallback:l.string,sources:null==(A=Y.propTypes)?void 0:A.sources,alt:function(e,t,r){return e[t]?new Error("Invalid prop `"+t+"` supplied to `"+r+"`. Validation failed."):null}};var K=i(function(e,r){return t.createElement(t.Fragment,null,t.createElement(Y,u({ref:r},e)),t.createElement("noscript",null,t.createElement(Y,u({},e,{shouldLoad:!0}))))});K.displayName="MainImage",K.propTypes=Y.propTypes;var Q,$=function(e,t,r){return e.alt||""===e.alt?d.string.apply(d,[e,t,r].concat([].slice.call(arguments,3))):new Error('The "alt" prop is required in '+r+'. If the image is purely presentational then pass an empty string: e.g. alt="". Learn more: https://a11y-style-guide.com/style-guide/section-media.html')},ee={image:d.object.isRequired,alt:$},te=["style","className"];if(HAS_REACT_18){var re=require("react-dom/client");Q=function(e,t,r){return r||(r=re.createRoot(t)),r.render(e),r}}else{var ie=require("react-dom");Q=function(e,t){ie.render(e,t)}}var ae=function(e){var r,i;function n(t){var r;return(r=e.call(this,t)||this).root=a(),r.hydrated={current:!1},r.forceRender={current:"development"===process.env.NODE_ENV},r.lazyHydrator=null,r.ref=a(),r.unobserveRef=void 0,r.reactRootRef=a(),r.state={isLoading:x(),isLoaded:!1},r}i=e,(r=n).prototype=Object.create(i.prototype),r.prototype.constructor=r,c(r,i);var o=n.prototype;return o._lazyHydrate=function(e,t){var r=this,i=this.root.current.querySelector("[data-gatsby-image-ssr]");return x()&&i&&!this.hydrated.current?(this.hydrated.current=!0,Promise.resolve()):import("./lazy-hydrate-2d1e8cb4.js").then(function(i){var a=i.lazyHydrate,n=JSON.stringify(r.props.image.images);r.lazyHydrator=a(u({image:e.image.images,isLoading:t.isLoading||W(n),isLoaded:t.isLoaded||W(n),toggleIsLoaded:function(){null==e.onLoad||e.onLoad(),r.setState({isLoaded:!0})},ref:r.ref},e),r.root,r.hydrated,r.forceRender,r.reactRootRef)})},o._setupIntersectionObserver=function(e){var t=this;void 0===e&&(e=!0),import("./intersection-observer-6b794dd8.js").then(function(r){var i=(0,r.createIntersectionObserver)(function(){if(t.root.current){var r=JSON.stringify(t.props.image.images);null==t.props.onStartLoad||t.props.onStartLoad({wasCached:e&&W(r)}),t.setState({isLoading:!0,isLoaded:e&&W(r)})}});t.root.current&&(t.unobserveRef=i(t.root))})},o.shouldComponentUpdate=function(e,t){var r=this,i=!1;return this.state.isLoading||!t.isLoading||t.isLoaded||(this.forceRender.current=!0),this.props.image.images!==e.image.images&&(this.unobserveRef&&(this.unobserveRef(),this.hydrated.current&&this.lazyHydrator&&(this.reactRootRef.current=Q(null,this.root.current,this.reactRootRef.current))),this.setState({isLoading:!1,isLoaded:!1},function(){r._setupIntersectionObserver(!1)}),i=!0),this.root.current&&!i&&this._lazyHydrate(e,t),!1},o.componentDidMount=function(){if(this.root.current){var e=this.root.current.querySelector("[data-gatsby-image-ssr]"),t=JSON.stringify(this.props.image.images);if(x()&&e&&I()){var r,i;if(null==(r=(i=this.props).onStartLoad)||r.call(i,{wasCached:!1}),e.complete){var a,n;null==(a=(n=this.props).onLoad)||a.call(n),O(t)}else{var o=this;e.addEventListener("load",function r(){e.removeEventListener("load",r),null==o.props.onLoad||o.props.onLoad(),O(t)})}return}this._setupIntersectionObserver(!0)}},o.componentWillUnmount=function(){this.unobserveRef&&(this.unobserveRef(),this.hydrated.current&&this.lazyHydrator&&this.lazyHydrator())},o.render=function(){var e=this.props.as||"div",r=this.props.image,i=r.width,a=r.height,n=r.layout,o=function(e,t,r){var i={},a="gatsby-image-wrapper";return I()||(i.position="relative",i.overflow="hidden"),"fixed"===r?(i.width=e,i.height=t):"constrained"===r&&(I()||(i.display="inline-block",i.verticalAlign="top"),a="gatsby-image-wrapper gatsby-image-wrapper-constrained"),{className:a,"data-gatsby-image-wrapper":"",style:i}}(i,a,n),s=o.style,l=o.className,d=h(o,te),c=this.props.className;this.props.class&&(c=this.props.class);var p=function(e,t,r){var i=null;return"fullWidth"===e&&(i='<div aria-hidden="true" style="padding-top: '+r/t*100+'%;"></div>'),"constrained"===e&&(i='<div style="max-width: '+t+'px; display: block;"><img alt="" role="presentation" aria-hidden="true" src="data:image/svg+xml;charset=utf-8,%3Csvg height=\''+r+"' width='"+t+"' xmlns='http://www.w3.org/2000/svg' version='1.1'%3E%3C/svg%3E\" style=\"max-width: 100%; display: block; position: static;\"></div>"),i}(n,i,a);return t.createElement(e,u({},d,{style:u({},s,this.props.style,{backgroundColor:this.props.backgroundColor}),className:l+(c?" "+c:""),ref:this.root,dangerouslySetInnerHTML:{__html:p},suppressHydrationWarning:!0}))},n}(n),ne=function(e){if(!e.image)return"development"===process.env.NODE_ENV&&console.warn("[gatsby-plugin-image] Missing image prop"),null;I()||"development"!==process.env.NODE_ENV||console.warn('[gatsby-plugin-image] You\'re missing out on some cool performance features. Please add "gatsby-plugin-image" to your gatsby-config.js');var r=e.image,i=JSON.stringify([r.width,r.height,r.layout,e.className,e.class,e.backgroundColor]);return t.createElement(ae,u({key:i},e))};ne.propTypes=ee,ne.displayName="GatsbyImage";var oe=["src","__imageData","__error","width","height","aspectRatio","tracedSVGOptions","placeholder","formats","quality","transformOptions","jpgOptions","pngOptions","webpOptions","avifOptions","blurredOptions"],se=function(e,t){return"fullWidth"!==e.layout||"width"!==t&&"height"!==t||!e[t]?d.number.apply(d,[e,t].concat([].slice.call(arguments,2))):new Error('"'+t+'" '+e[t]+" may not be passed when layout is fullWidth.")},le=new Set(["fixed","fullWidth","constrained"]),de={src:d.string.isRequired,alt:$,width:se,height:se,sizes:d.string,layout:function(e){if(void 0!==e.layout&&!le.has(e.layout))return new Error("Invalid value "+e.layout+'" provided for prop "layout". Defaulting to "constrained". Valid values are "fixed", "fullWidth" or "constrained".')}},ue=function(e){return function(r){var i=r.src,a=r.__imageData,n=r.__error,o=h(r,oe);return n&&console.warn(n),a?t.createElement(e,u({image:a},o)):(console.warn("Image not loaded",i),n||"development"!==process.env.NODE_ENV||console.warn('Please ensure that "gatsby-plugin-image" is included in the plugins array in gatsby-config.js, and that your version of gatsby is at least 2.24.78'),null)}}(ne);function ce(t){var r=t.children;return e.useEffect(function(){import("./lazy-hydrate-2d1e8cb4.js")},[]),r}ue.displayName="StaticImage",ue.propTypes=de;export{ne as G,G as L,K as M,Z as P,ue as S,h as _,u as a,D as b,ce as c,z as d,T as e,H as f,q as g,P as h,S as i,R as j,C as w}; //# sourceMappingURL=index.browser-4e524ce6.js.map