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.1 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)},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 a=e.slice(t+1);if("jpeg"===a)return"jpg";if(3===a.length||4===a.length)return a}}function E(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 k(e){var t,a=(e=E(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,y=e.backgroundColor,k=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 N=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=M(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?x(e):"fullWidth"===i?x(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})),L={sources:[]},j=e.sizes;j||(j=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}}(N.presentationWidth,n)),I.forEach(function(e){var t=N.sizes.map(function(t){var i=r(g,t,Math.round(t/N.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===N.unscaledWidth})||t[0];i&&(L.fallback={src:i.src,srcSet:w(t),sizes:j})}else{var n;null==(n=L.sources)||n.push({srcSet:w(t),sizes:j,type:"image/"+e})}});var W={images:L,layout:n,backgroundColor:y};switch(k&&(W.placeholder={fallback:k}),n){case"fixed":W.width=N.presentationWidth,W.height=N.presentationHeight;break;case"fullWidth":W.width=1,W.height=1/N.aspectRatio;break;case"constrained":W.width=e.width||N.presentationWidth||1,W.height=(W.width||1)/N.aspectRatio}return W}var S=function(e){return Array.from(new Set([1].concat(e))).sort(y)};function x(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=M(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(y),aspectRatio:d,presentationWidth:f,presentationHeight:Math.round(f/d),unscaledWidth:i}}function M(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"],N=["images","placeholder"],L=function(){return"undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype};function j(){return"undefined"!=typeof GATSBY___IMAGE&&GATSBY___IMAGE}var 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};function R(e,t,a){var i={},r="gatsby-image-wrapper";return j()||(i.position="relative",i.overflow="hidden"),"fixed"===a?(i.width=e,i.height=t):"constrained"===a&&(j()||(i.display="inline-block",i.verticalAlign="top"),r="gatsby-image-wrapper gatsby-image-wrapper-constrained"),{className:r,"data-gatsby-image-wrapper":"",style:i}}function _(e,t,a,i,r){return void 0===r&&(r={}),j()||(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:t?1:0})})}function T(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:t?0:1,transition:"opacity 500ms linear"},l)});return j()||(d.style={height:"100%",left:0,position:"absolute",top:0,width:"100%"}),d}var O,C=["children"],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},D=function(t){var a=t.children,i=d(t,C);return n.default.createElement(e.Fragment,null,n.default.createElement(P,u({},i)),a,null)},z=["src","srcSet","loading","alt","shouldLoad"],q=["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,z);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}))},H=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,q),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},H.displayName="Picture",H.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 F=["fallback"],G=function(e){var t=e.fallback,a=d(e,F);return t?n.default.createElement(H,u({},a,{fallback:{src:t},"aria-hidden":!0,alt:""})):n.default.createElement("div",u({},a))};G.displayName="Placeholder",G.propTypes={fallback:s.string,sources:null==(O=H.propTypes)?void 0:O.sources,alt:function(e,t,a){return e[t]?new Error("Invalid prop `"+t+"` supplied to `"+a+"`. Validation failed."):null}};var V=function(e){return n.default.createElement(n.default.Fragment,null,n.default.createElement(H,u({},e)),n.default.createElement("noscript",null,n.default.createElement(H,u({},e,{shouldLoad:!0}))))};V.displayName="MainImage",V.propTypes=H.propTypes;var B,U,Y=["as","className","class","style","image","loading","imgClassName","imgStyle","backgroundColor","objectFit","objectPosition"],X=["style","className"],J=function(e){return e.replace(/\n/g,"")},Z=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')},K={image:l.default.object.isRequired,alt:Z},Q=["as","image","style","backgroundColor","className","class","onStartLoad","onLoad","onError"],$=["style","className"],ee=new Set,te=function(t){var a=t.as,i=void 0===a?"div":a,r=t.image,n=t.style,o=t.backgroundColor,s=t.className,l=t.class,c=t.onStartLoad,h=t.onLoad,g=t.onError,p=d(t,Q),f=r.width,m=r.height,v=r.layout,y=R(f,m,v),w=y.style,b=y.className,E=d(y,$),k=e.useRef(),S=e.useMemo(function(){return JSON.stringify(r.images)},[r.images]);l&&(s=l);var x=function(e,t,a){var i="";return"fullWidth"===e&&(i='<div aria-hidden="true" style="padding-top: '+a/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%20height=\''+a+"'%20width='"+t+"'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%3E%3C/svg%3E\" style=\"max-width: 100%; display: block; position: static;\"></div>"),i}(v,f,m);return e.useEffect(function(){B||(B=Promise.resolve().then(function(){return require("./lazy-hydrate-6ff2d17c.js")}).then(function(e){var t=e.renderImageToString;return U=t,{renderImageToString:t,swapPlaceholderImage:e.swapPlaceholderImage}}));var e,t,a=k.current.querySelector("[data-gatsby-image-ssr]");return a&&L()?(a.complete?(null==c||c({wasCached:!0}),null==h||h({wasCached:!0}),setTimeout(function(){a.removeAttribute("data-gatsby-image-ssr")},0)):(null==c||c({wasCached:!0}),a.addEventListener("load",function e(){a.removeEventListener("load",e),null==h||h({wasCached:!0}),setTimeout(function(){a.removeAttribute("data-gatsby-image-ssr")},0)})),void ee.add(S)):U&&ee.has(S)?void 0:(B.then(function(a){var i=a.swapPlaceholderImage;k.current&&(k.current.innerHTML=(0,a.renderImageToString)(u({isLoading:!0,isLoaded:ee.has(S),image:r},p)),ee.has(S)||(e=requestAnimationFrame(function(){k.current&&(t=i(k.current,S,ee,n,c,h,g))})))}),function(){e&&cancelAnimationFrame(e),t&&t()})},[r]),e.useLayoutEffect(function(){ee.has(S)&&U&&(k.current.innerHTML=U(u({isLoading:ee.has(S),isLoaded:ee.has(S),image:r},p)),null==c||c({wasCached:!0}),null==h||h({wasCached:!0}))},[r]),e.createElement(i,u({},E,{style:u({},w,n,{backgroundColor:o}),className:b+(s?" "+s:""),ref:k,dangerouslySetInnerHTML:{__html:x},suppressHydrationWarning:!0}))},ae=e.memo(function(t){return t.image?(j()||"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'),e.createElement(te,t)):("development"===process.env.NODE_ENV&&console.warn("[gatsby-plugin-image] Missing image prop"),null)});ae.propTypes=K,ae.displayName="GatsbyImage";var ie=["src","__imageData","__error","width","height","aspectRatio","tracedSVGOptions","placeholder","formats","quality","transformOptions","jpgOptions","pngOptions","webpOptions","avifOptions","blurredOptions","breakpoints","outputPixelDensities"];function re(e){return function(t){var a=t.src,i=t.__imageData,r=t.__error,o=d(t,ie);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)}}var ne=re(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,Y);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 y=s.width,w=s.height,b=s.layout,E=s.images,k=s.placeholder,S=s.backgroundColor,x=R(y,w,b),M=x.style,I=x.className,N=d(x,X),L={fallback:void 0,sources:[]};return E.fallback&&(L.fallback=u({},E.fallback,{srcSet:E.fallback.srcSet?J(E.fallback.srcSet):void 0})),E.sources&&(L.sources=E.sources.map(function(e){return u({},e,{srcSet:J(e.srcSet)})})),n.default.createElement(a,u({},N,{style:u({},M,o,{backgroundColor:p}),className:I+(i?" "+i:"")}),n.default.createElement(D,{layout:b,width:y,height:w},n.default.createElement(G,u({},T(k,!1,b,y,w,S,f,m))),n.default.createElement(V,u({"data-gatsby-image-ssr":"",className:h},v,_("eager"===c,!1,L,c,g)))))}),oe=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.")},se=new Set(["fixed","fullWidth","constrained"]),le={src:l.default.string.isRequired,alt:Z,width:oe,height:oe,sizes:l.default.string,layout:function(e){if(void 0!==e.layout&&!se.has(e.layout))return new Error("Invalid value "+e.layout+'" provided for prop "layout". Defaulting to "constrained". Valid values are "fixed", "fullWidth" or "constrained".')}};ne.displayName="StaticImage",ne.propTypes=le;var ue=re(ae);ue.displayName="StaticImage",ue.propTypes=le,exports.GatsbyImage=ae,exports.LayoutWrapper=D,exports.MainImage=V,exports.Placeholder=G,exports.StaticImage=ue,exports._extends=u,exports._objectWithoutPropertiesLoose=d,exports.generateImageData=k,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),k(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=E(e)).generateImageSource)(e.filename,t,Math.round(t/e.aspectRatio),e.sourceMetadata.format||"jpg",e.fit,e.options))?void 0:a.src},exports.getMainProps=_,exports.getPlaceholderProps=T,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.hasNativeLazyLoadSupport=L,exports.withArtDirection=function(e,t){var a,i,r,n=e.images,o=e.placeholder,s=u({},d(e,N),{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=index.browser-395cc902.js.map