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) • 16.7 kB
JavaScript
var e=require("react"),t=require("camelcase"),a=require("prop-types");function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function r(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(a){if("default"!==a){var i=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,i.get?i:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,t}var n=/*#__PURE__*/i(e),o=/*#__PURE__*/i(t),s=/*#__PURE__*/r(a),l=/*#__PURE__*/i(a);function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(e[i]=a[i])}return e},u.apply(this,arguments)}function d(e,t){if(null==e)return{};var a,i,r={},n=Object.keys(e);for(i=0;i<n.length;i++)t.indexOf(a=n[i])>=0||(r[a]=e[a]);return r}var c=[.25,.5,1,2],h=[750,1080,1366,1920],g=[320,654,768,1024,1366,1600,1920,2048,2560,3440,3840,4096],p=800,f=800,m=4/3,v=function(e){return console.warn(e)},w=function(e,t){return e-t},y=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 a=e.slice(t+1);if("jpeg"===a)return"jpg";if(3===a.length||4===a.length)return a}}function k(e){var t=e.layout,a=void 0===t?"constrained":t,i=e.width,r=e.height,n=e.sourceMetadata,s=e.breakpoints,l=e.aspectRatio,d=e.formats,c=void 0===d?["auto","webp"]:d;return c=c.map(function(e){return e.toLowerCase()}),a=o.default(a),i&&r?u({},e,{formats:c,layout:a,aspectRatio:i/r}):(n.width&&n.height&&!l&&(l=n.width/n.height),"fullWidth"===a?(i=i||n.width||s[s.length-1],r=r||Math.round(i/(l||m))):(i||(i=r&&l?r*l:n.width?n.width:r?Math.round(r/m):f),l&&!r?r=Math.round(i/l):l||(l=i/r)),u({},e,{width:i,height:r,aspectRatio:l,layout:a,formats:c}))}function E(e){var t,a=(e=k(e)).pluginName,i=e.sourceMetadata,r=e.generateImageSource,n=e.layout,o=e.fit,s=e.options,l=e.width,d=e.height,g=e.filename,p=e.reporter,m=void 0===p?{warn:v}:p,w=e.backgroundColor,E=e.placeholderURL;if(a||m.warn('[gatsby-plugin-image] "generateImageData" was not passed a plugin name'),"function"!=typeof r)throw new Error("generateImageSource must be a function");i&&(i.width||i.height)?i.format||(i.format=b(g)):i={width:l,height:d,format:(null==(t=i)?void 0:t.format)||b(g)||"auto"};var I=new Set(e.formats);(0===I.size||I.has("auto")||I.has(""))&&(I.delete("auto"),I.delete(""),I.add(i.format)),I.has("jpg")&&I.has("png")&&(m.warn("["+a+"] Specifying both 'jpg' and 'png' formats is not supported. Using 'auto' instead"),I.delete("jpg"===i.format?"png":"jpg"));var j=function(e){var t=e.filename,a=e.layout,i=void 0===a?"constrained":a,r=e.sourceMetadata,n=e.reporter,o=void 0===n?{warn:v}:n,s=e.breakpoints,l=void 0===s?h:s,d=Object.entries({width:e.width,height:e.height}).filter(function(e){var t=e[1];return"number"==typeof t&&t<1});if(d.length)throw new Error("Specified dimensions for images must be positive numbers (> 0). Problem dimensions you have are "+d.map(function(e){return e.join(": ")}).join(", "));return"fixed"===i?function(e){var t=e.filename,a=e.sourceMetadata,i=e.width,r=e.height,n=e.fit,o=void 0===n?"cover":n,s=e.outputPixelDensities,l=e.reporter,u=void 0===l?{warn:v}:l,d=a.width/a.height,h=S(void 0===s?c:s);if(i&&r){var g=x(a,{width:i,height:r,fit:o});i=g.width,r=g.height,d=g.aspectRatio}i?r||(r=Math.round(i/d)):i=r?Math.round(r*d):f;var p=i;if(a.width<i||a.height<r){var m=a.width<i?"width":"height";u.warn("\nThe requested "+m+' "'+("width"===m?i:r)+'px" for the image '+t+" was larger than the actual image "+m+" of "+a[m]+"px. If possible, replace the current image with a larger one."),"width"===m?(i=a.width,r=Math.round(i/d)):i=(r=a.height)*d}return{sizes:h.filter(function(e){return e>=1}).map(function(e){return Math.round(e*i)}).filter(function(e){return e<=a.width}),aspectRatio:d,presentationWidth:p,presentationHeight:Math.round(p/d),unscaledWidth:i}}(e):"constrained"===i?M(e):"fullWidth"===i?M(u({breakpoints:l},e)):(o.warn("No valid layout was provided for the image at "+t+". Valid image layouts are fixed, fullWidth, and constrained. Found "+i),{sizes:[r.width],presentationWidth:r.width,presentationHeight:r.height,aspectRatio:r.width/r.height,unscaledWidth:r.width})}(u({},e,{sourceMetadata:i})),N={sources:[]},R=e.sizes;R||(R=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)),I.forEach(function(e){var t=j.sizes.map(function(t){var i=r(g,t,Math.round(t/j.aspectRatio),e,o,s);if(null!=i&&i.width&&i.height&&i.src&&i.format)return i;m.warn("["+a+"] The resolver for image "+g+" 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:y(t),sizes:R})}else{var n;null==(n=N.sources)||n.push({srcSet:y(t),sizes:R,type:"image/"+e})}});var W={images:N,layout:n,backgroundColor:w};switch(E&&(W.placeholder={fallback:E}),n){case"fixed":W.width=j.presentationWidth,W.height=j.presentationHeight;break;case"fullWidth":W.width=1,W.height=1/j.aspectRatio;break;case"constrained":W.width=e.width||j.presentationWidth||1,W.height=(W.width||1)/j.aspectRatio}return W}var S=function(e){return Array.from(new Set([1].concat(e))).sort(w)};function M(e){var t,a=e.sourceMetadata,i=e.width,r=e.height,n=e.fit,o=void 0===n?"cover":n,s=e.outputPixelDensities,l=e.breakpoints,u=e.layout,d=a.width/a.height,h=S(void 0===s?c:s);if(i&&r){var g=x(a,{width:i,height:r,fit:o});i=g.width,r=g.height,d=g.aspectRatio}i=i&&Math.min(i,a.width),r=r&&Math.min(r,a.height),i||r||(r=(i=Math.min(p,a.width))/d),i||(i=r*d);var f=i;return(a.width<i||a.height<r)&&(i=a.width,r=a.height),i=Math.round(i),(null==l?void 0:l.length)>0?(t=l.filter(function(e){return e<=a.width})).length<l.length&&!t.includes(a.width)&&t.push(a.width):t=(t=h.map(function(e){return Math.round(e*i)})).filter(function(e){return e<=a.width}),"constrained"!==u||t.includes(i)||t.push(i),{sizes:t=t.sort(w),aspectRatio:d,presentationWidth:f,presentationHeight:Math.round(f/d),unscaledWidth:i}}function x(e,t){var a=e.width/e.height,i=t.width,r=t.height;switch(t.fit){case"fill":i=t.width?t.width:e.width,r=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*a)),r=Math.min(o,Math.round(n/a));break;case"outside":var s=t.width?t.width:0,l=t.height?t.height:0;i=Math.max(s,Math.round(l*a)),r=Math.max(l,Math.round(s/a));break;default:t.width&&!t.height&&(i=t.width,r=Math.round(t.width/a)),t.height&&!t.width&&(i=Math.round(t.height*a),r=t.height)}return{width:i,height:r,aspectRatio:i/r}}var I=["baseUrl","urlBuilder","sourceWidth","sourceHeight","pluginName","formats","breakpoints","options"],j=["images","placeholder"];function N(){return"undefined"!=typeof GATSBY___IMAGE&&GATSBY___IMAGE}var R,W=function(e){var t;return function(e){var t,a;return Boolean(null==e||null==(t=e.images)||null==(a=t.fallback)?void 0:a.src)}(e)?e:function(e){return Boolean(null==e?void 0:e.gatsbyImageData)}(e)?e.gatsbyImageData:function(e){return Boolean(null==e?void 0:e.gatsbyImage)}(e)?e.gatsbyImage:null==e||null==(t=e.childImageSharp)?void 0:t.gatsbyImageData},_=["src","srcSet","loading","alt","shouldLoad"],O=["fallback","sources","shouldLoad"],A=function(e){var t=e.src,a=e.srcSet,i=e.loading,r=e.alt,o=void 0===r?"":r,s=e.shouldLoad,l=d(e,_);return n.default.createElement("img",u({},l,{decoding:"async",loading:i,src:s?t:void 0,"data-src":s?void 0:t,srcSet:s?a:void 0,"data-srcset":s?void 0:a,alt:o}))},T=function(e){var t=e.fallback,a=e.sources,i=void 0===a?[]:a,r=e.shouldLoad,o=void 0===r||r,s=d(e,O),l=s.sizes||(null==t?void 0:t.sizes),c=n.default.createElement(A,u({},s,t,{sizes:l,shouldLoad:o}));return i.length?n.default.createElement("picture",null,i.map(function(e){var t=e.media,a=e.srcSet,i=e.type;return n.default.createElement("source",{key:t+"-"+i+"-"+a,type:i,media:t,srcSet:o?a:void 0,"data-srcset":o?void 0:a,sizes:l})}),c):c};A.propTypes={src:s.string.isRequired,alt:s.string.isRequired,sizes:s.string,srcSet:s.string,shouldLoad:s.bool},T.displayName="Picture",T.propTypes={alt:s.string.isRequired,shouldLoad:s.bool,fallback:s.exact({src:s.string.isRequired,srcSet:s.string,sizes:s.string}),sources:s.arrayOf(s.oneOfType([s.exact({media:s.string.isRequired,type:s.string,sizes:s.string,srcSet:s.string.isRequired}),s.exact({media:s.string,type:s.string.isRequired,sizes:s.string,srcSet:s.string.isRequired})]))};var D=["fallback"],L=function(e){var t=e.fallback,a=d(e,D);return t?n.default.createElement(T,u({},a,{fallback:{src:t},"aria-hidden":!0,alt:""})):n.default.createElement("div",u({},a))};L.displayName="Placeholder",L.propTypes={fallback:s.string,sources:null==(R=T.propTypes)?void 0:R.sources,alt:function(e,t,a){return e[t]?new Error("Invalid prop `"+t+"` supplied to `"+a+"`. Validation failed."):null}};var q=function(e){return n.default.createElement(n.default.Fragment,null,n.default.createElement(T,u({},e)),n.default.createElement("noscript",null,n.default.createElement(T,u({},e,{shouldLoad:!0}))))};q.displayName="MainImage",q.propTypes=T.propTypes;var z=["children"],C=function(){return n.default.createElement("script",{type:"module",dangerouslySetInnerHTML:{__html:'const t="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;if(t){const t=document.querySelectorAll("img[data-main-image]");for(let e of t){e.dataset.src&&(e.setAttribute("src",e.dataset.src),e.removeAttribute("data-src")),e.dataset.srcset&&(e.setAttribute("srcset",e.dataset.srcset),e.removeAttribute("data-srcset"));const t=e.parentNode.querySelectorAll("source[data-srcset]");for(let e of t)e.setAttribute("srcset",e.dataset.srcset),e.removeAttribute("data-srcset");e.complete&&(e.style.opacity=1,e.parentNode.parentNode.querySelector("[data-placeholder-image]").style.opacity=0)}}'}})},P=function(e){var t=e.layout,a=e.width,i=e.height;return"fullWidth"===t?n.default.createElement("div",{"aria-hidden":!0,style:{paddingTop:i/a*100+"%"}}):"constrained"===t?n.default.createElement("div",{style:{maxWidth:a,display:"block"}},n.default.createElement("img",{alt:"",role:"presentation","aria-hidden":"true",src:"data:image/svg+xml;charset=utf-8,%3Csvg%20height='"+i+"'%20width='"+a+"'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%3E%3C/svg%3E",style:{maxWidth:"100%",display:"block",position:"static"}})):null},F=function(t){var a=t.children,i=d(t,z);return n.default.createElement(e.Fragment,null,n.default.createElement(P,u({},i)),a,n.default.createElement(C,null))},H=["as","className","class","style","image","loading","imgClassName","imgStyle","backgroundColor","objectFit","objectPosition"],B=["style","className"],G=function(e){return e.replace(/\n/g,"")},U=function(e){var t=e.as,a=void 0===t?"div":t,i=e.className,r=e.class,o=e.style,s=e.image,l=e.loading,c=void 0===l?"lazy":l,h=e.imgClassName,g=e.imgStyle,p=e.backgroundColor,f=e.objectFit,m=e.objectPosition,v=d(e,H);if(!s)return console.warn("[gatsby-plugin-image] Missing image prop"),null;r&&(i=r),g=u({objectFit:f,objectPosition:m,backgroundColor:p},g);var w=s.width,y=s.height,b=s.layout,k=s.images,E=s.placeholder,S=s.backgroundColor,M=function(e,t,a){var i={},r="gatsby-image-wrapper";return N()||(i.position="relative",i.overflow="hidden"),"fixed"===a?(i.width=e,i.height=t):"constrained"===a&&(N()||(i.display="inline-block",i.verticalAlign="top"),r="gatsby-image-wrapper gatsby-image-wrapper-constrained"),{className:r,"data-gatsby-image-wrapper":"",style:i}}(w,y,b),x=M.style,I=M.className,j=d(M,B),R={fallback:void 0,sources:[]};return k.fallback&&(R.fallback=u({},k.fallback,{srcSet:k.fallback.srcSet?G(k.fallback.srcSet):void 0})),k.sources&&(R.sources=k.sources.map(function(e){return u({},e,{srcSet:G(e.srcSet)})})),n.default.createElement(a,u({},j,{style:u({},x,o,{backgroundColor:p}),className:I+(i?" "+i:"")}),n.default.createElement(F,{layout:b,width:w,height:y},n.default.createElement(L,u({},function(e,t,a,i,r,n,o,s){var l={};n&&(l.backgroundColor=n,"fixed"===a?(l.width=i,l.height=r,l.backgroundColor=n,l.position="relative"):("constrained"===a||"fullWidth"===a)&&(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:1,transition:"opacity 500ms linear"},l)});return N()||(d.style={height:"100%",left:0,position:"absolute",top:0,width:"100%"}),d}(E,0,b,w,y,S,f,m))),n.default.createElement(q,u({"data-gatsby-image-ssr":"",className:h},v,function(e,t,a,i,r){return void 0===r&&(r={}),N()||(r=u({height:"100%",left:0,position:"absolute",top:0,transform:"translateZ(0)",transition:"opacity 250ms linear",width:"100%",willChange:"opacity"},r)),u({},a,{loading:i,shouldLoad:e,"data-main-image":"",style:u({},r,{opacity:0})})}("eager"===c,0,R,c,g)))))},V=["src","__imageData","__error","width","height","aspectRatio","tracedSVGOptions","placeholder","formats","quality","transformOptions","jpgOptions","pngOptions","webpOptions","avifOptions","blurredOptions","breakpoints","outputPixelDensities"],X=function(e){return function(t){var a=t.src,i=t.__imageData,r=t.__error,o=d(t,V);return r&&console.warn(r),i?n.default.createElement(e,u({image:i},o)):(console.warn("Image not loaded",a),r||"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)}}(U),Y=function(e,t){return"fullWidth"!==e.layout||"width"!==t&&"height"!==t||!e[t]?l.default.number.apply(l.default,[e,t].concat([].slice.call(arguments,2))):new Error('"'+t+'" '+e[t]+" may not be passed when layout is fullWidth.")},Z=new Set(["fixed","fullWidth","constrained"]),J={src:l.default.string.isRequired,alt:function(e,t,a){return e.alt||""===e.alt?l.default.string.apply(l.default,[e,t,a].concat([].slice.call(arguments,3))):new Error('The "alt" prop is required in '+a+'. 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')},width:Y,height:Y,sizes:l.default.string,layout:function(e){if(void 0!==e.layout&&!Z.has(e.layout))return new Error("Invalid value "+e.layout+'" provided for prop "layout". Defaulting to "constrained". Valid values are "fixed", "fullWidth" or "constrained".')}};X.displayName="StaticImage",X.propTypes=J,exports.GatsbyImage=U,exports.MainImage=q,exports.Placeholder=L,exports.StaticImage=X,exports.generateImageData=E,exports.getImage=W,exports.getImageData=function(e){var t,a=e.baseUrl,i=e.urlBuilder,r=e.sourceWidth,n=e.sourceHeight,o=e.pluginName,s=void 0===o?"getImageData":o,l=e.formats,c=void 0===l?["auto"]:l,h=e.breakpoints,p=e.options,f=d(e,I);return null!=(t=h)&&t.length||"fullWidth"!==f.layout&&"FULL_WIDTH"!==f.layout||(h=g),E(u({},f,{pluginName:s,generateImageSource:function(e,t,a,r){return{width:t,height:a,format:r,src:i({baseUrl:e,width:t,height:a,options:p,format:r})}},filename:a,formats:c,breakpoints:h,sourceMetadata:{width:r,height:n,format:"auto"}}))},exports.getLowResolutionImageURL=function(e,t){var a;return void 0===t&&(t=20),null==(a=(0,(e=k(e)).generateImageSource)(e.filename,t,Math.round(t/e.aspectRatio),e.sourceMetadata.format||"jpg",e.fit,e.options))?void 0:a.src},exports.getSrc=function(e){var t,a,i;return null==(t=W(e))||null==(a=t.images)||null==(i=a.fallback)?void 0:i.src},exports.getSrcSet=function(e){var t,a,i;return null==(t=W(e))||null==(a=t.images)||null==(i=a.fallback)?void 0:i.srcSet},exports.withArtDirection=function(e,t){var a,i,r,n=e.images,o=e.placeholder,s=u({},d(e,j),{images:u({},n,{sources:[]}),placeholder:o&&u({},o,{sources:[]})});return t.forEach(function(t){var a,i=t.media,r=t.image;i?(r.layout!==e.layout&&"development"===process.env.NODE_ENV&&console.warn('[gatsby-plugin-image] Mismatched image layout: expected "'+e.layout+'" but received "'+r.layout+'". All art-directed images use the same layout as the default image'),(a=s.images.sources).push.apply(a,r.images.sources.map(function(e){return u({},e,{media:i})}).concat([{media:i,srcSet:r.images.fallback.srcSet}])),s.placeholder&&s.placeholder.sources.push({media:i,srcSet:r.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.")}),(a=s.images.sources).push.apply(a,n.sources),null!=o&&o.sources&&(null==(i=s.placeholder)||(r=i.sources).push.apply(r,o.sources)),s};
//# sourceMappingURL=gatsby-image.js.map