image.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. "client";
  2. "use strict";
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.default = Image;
  7. var _extends = require("@swc/helpers/lib/_extends.js").default;
  8. var _interop_require_default = require("@swc/helpers/lib/_interop_require_default.js").default;
  9. var _interop_require_wildcard = require("@swc/helpers/lib/_interop_require_wildcard.js").default;
  10. var _object_without_properties_loose = require("@swc/helpers/lib/_object_without_properties_loose.js").default;
  11. var _react = _interop_require_wildcard(require("react"));
  12. var _head = _interop_require_default(require("../../shared/lib/head"));
  13. var _imageBlurSvg = require("../../shared/lib/image-blur-svg");
  14. var _imageConfig = require("../../shared/lib/image-config");
  15. var _imageConfigContext = require("../../shared/lib/image-config-context");
  16. var _utils = require("../../shared/lib/utils");
  17. function Image(_param) {
  18. var { src , sizes , unoptimized =false , priority =false , loading , className , quality , width , height , fill , style , onLoadingComplete , placeholder ='empty' , blurDataURL } = _param, all = _object_without_properties_loose(_param, [
  19. "src",
  20. "sizes",
  21. "unoptimized",
  22. "priority",
  23. "loading",
  24. "className",
  25. "quality",
  26. "width",
  27. "height",
  28. "fill",
  29. "style",
  30. "onLoadingComplete",
  31. "placeholder",
  32. "blurDataURL"
  33. ]);
  34. const configContext = (0, _react).useContext(_imageConfigContext.ImageConfigContext);
  35. const config = (0, _react).useMemo(()=>{
  36. const c = configEnv || configContext || _imageConfig.imageConfigDefault;
  37. const allSizes = [
  38. ...c.deviceSizes,
  39. ...c.imageSizes
  40. ].sort((a, b)=>a - b);
  41. const deviceSizes = c.deviceSizes.sort((a, b)=>a - b);
  42. return _extends({}, c, {
  43. allSizes,
  44. deviceSizes
  45. });
  46. }, [
  47. configContext
  48. ]);
  49. let rest = all;
  50. let loader = defaultLoader;
  51. if ('loader' in rest) {
  52. if (rest.loader) {
  53. const customImageLoader = rest.loader;
  54. var _tmp;
  55. _tmp = (obj)=>{
  56. const { config: _ } = obj, opts = _object_without_properties_loose(obj, [
  57. "config"
  58. ]);
  59. // The config object is internal only so we must
  60. // not pass it to the user-defined loader()
  61. return customImageLoader(opts);
  62. }, loader = _tmp, _tmp;
  63. }
  64. // Remove property so it's not spread on <img>
  65. delete rest.loader;
  66. }
  67. let staticSrc = '';
  68. let widthInt = getInt(width);
  69. let heightInt = getInt(height);
  70. let blurWidth;
  71. let blurHeight;
  72. if (isStaticImport(src)) {
  73. const staticImageData = isStaticRequire(src) ? src.default : src;
  74. if (!staticImageData.src) {
  75. throw new Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ${JSON.stringify(staticImageData)}`);
  76. }
  77. if (!staticImageData.height || !staticImageData.width) {
  78. throw new Error(`An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(staticImageData)}`);
  79. }
  80. blurWidth = staticImageData.blurWidth;
  81. blurHeight = staticImageData.blurHeight;
  82. blurDataURL = blurDataURL || staticImageData.blurDataURL;
  83. staticSrc = staticImageData.src;
  84. if (!fill) {
  85. if (!widthInt && !heightInt) {
  86. widthInt = staticImageData.width;
  87. heightInt = staticImageData.height;
  88. } else if (widthInt && !heightInt) {
  89. const ratio = widthInt / staticImageData.width;
  90. heightInt = Math.round(staticImageData.height * ratio);
  91. } else if (!widthInt && heightInt) {
  92. const ratio = heightInt / staticImageData.height;
  93. widthInt = Math.round(staticImageData.width * ratio);
  94. }
  95. }
  96. }
  97. src = typeof src === 'string' ? src : staticSrc;
  98. let isLazy = !priority && (loading === 'lazy' || typeof loading === 'undefined');
  99. if (src.startsWith('data:') || src.startsWith('blob:')) {
  100. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  101. unoptimized = true;
  102. isLazy = false;
  103. }
  104. if (config.unoptimized) {
  105. unoptimized = true;
  106. }
  107. const [blurComplete, setBlurComplete] = (0, _react).useState(false);
  108. const [showAltText, setShowAltText] = (0, _react).useState(false);
  109. const qualityInt = getInt(quality);
  110. if (process.env.NODE_ENV !== 'production') {
  111. if (!src) {
  112. // React doesn't show the stack trace and there's
  113. // no `src` to help identify which image, so we
  114. // instead console.error(ref) during mount.
  115. unoptimized = true;
  116. } else {
  117. if (fill) {
  118. if (width) {
  119. throw new Error(`Image with src "${src}" has both "width" and "fill" properties. Only one should be used.`);
  120. }
  121. if (height) {
  122. throw new Error(`Image with src "${src}" has both "height" and "fill" properties. Only one should be used.`);
  123. }
  124. if ((style == null ? void 0 : style.position) && style.position !== 'absolute') {
  125. throw new Error(`Image with src "${src}" has both "fill" and "style.position" properties. Images with "fill" always use position absolute - it cannot be modified.`);
  126. }
  127. if ((style == null ? void 0 : style.width) && style.width !== '100%') {
  128. throw new Error(`Image with src "${src}" has both "fill" and "style.width" properties. Images with "fill" always use width 100% - it cannot be modified.`);
  129. }
  130. if ((style == null ? void 0 : style.height) && style.height !== '100%') {
  131. throw new Error(`Image with src "${src}" has both "fill" and "style.height" properties. Images with "fill" always use height 100% - it cannot be modified.`);
  132. }
  133. } else {
  134. if (typeof widthInt === 'undefined') {
  135. throw new Error(`Image with src "${src}" is missing required "width" property.`);
  136. } else if (isNaN(widthInt)) {
  137. throw new Error(`Image with src "${src}" has invalid "width" property. Expected a numeric value in pixels but received "${width}".`);
  138. }
  139. if (typeof heightInt === 'undefined') {
  140. throw new Error(`Image with src "${src}" is missing required "height" property.`);
  141. } else if (isNaN(heightInt)) {
  142. throw new Error(`Image with src "${src}" has invalid "height" property. Expected a numeric value in pixels but received "${height}".`);
  143. }
  144. }
  145. }
  146. if (!VALID_LOADING_VALUES.includes(loading)) {
  147. throw new Error(`Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map(String).join(',')}.`);
  148. }
  149. if (priority && loading === 'lazy') {
  150. throw new Error(`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`);
  151. }
  152. if (placeholder === 'blur') {
  153. if (widthInt && heightInt && widthInt * heightInt < 1600) {
  154. (0, _utils).warnOnce(`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`);
  155. }
  156. if (!blurDataURL) {
  157. const VALID_BLUR_EXT = [
  158. 'jpeg',
  159. 'png',
  160. 'webp',
  161. 'avif'
  162. ] // should match next-image-loader
  163. ;
  164. throw new Error(`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
  165. Possible solutions:
  166. - Add a "blurDataURL" property, the contents should be a small Data URL to represent the image
  167. - Change the "src" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join(',')}
  168. - Remove the "placeholder" property, effectively no blur effect
  169. Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url`);
  170. }
  171. }
  172. if ('ref' in rest) {
  173. (0, _utils).warnOnce(`Image with src "${src}" is using unsupported "ref" property. Consider using the "onLoadingComplete" property instead.`);
  174. }
  175. if (!unoptimized && loader !== defaultLoader) {
  176. const urlStr = loader({
  177. config,
  178. src,
  179. width: widthInt || 400,
  180. quality: qualityInt || 75
  181. });
  182. let url;
  183. try {
  184. url = new URL(urlStr);
  185. } catch (err) {}
  186. if (urlStr === src || url && url.pathname === src && !url.search) {
  187. (0, _utils).warnOnce(`Image with src "${src}" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead.` + `\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader-width`);
  188. }
  189. }
  190. if (typeof window !== 'undefined' && !perfObserver && window.PerformanceObserver) {
  191. perfObserver = new PerformanceObserver((entryList)=>{
  192. for (const entry of entryList.getEntries()){
  193. var ref;
  194. // @ts-ignore - missing "LargestContentfulPaint" class with "element" prop
  195. const imgSrc = (entry == null ? void 0 : (ref = entry.element) == null ? void 0 : ref.src) || '';
  196. const lcpImage = allImgs.get(imgSrc);
  197. if (lcpImage && !lcpImage.priority && lcpImage.placeholder !== 'blur' && !lcpImage.src.startsWith('data:') && !lcpImage.src.startsWith('blob:')) {
  198. // https://web.dev/lcp/#measure-lcp-in-javascript
  199. (0, _utils).warnOnce(`Image with src "${lcpImage.src}" was detected as the Largest Contentful Paint (LCP). Please add the "priority" property if this image is above the fold.` + `\nRead more: https://nextjs.org/docs/api-reference/next/image#priority`);
  200. }
  201. }
  202. });
  203. try {
  204. perfObserver.observe({
  205. type: 'largest-contentful-paint',
  206. buffered: true
  207. });
  208. } catch (err) {
  209. // Log error but don't crash the app
  210. console.error(err);
  211. }
  212. }
  213. }
  214. const imgStyle = Object.assign(fill ? {
  215. position: 'absolute',
  216. height: '100%',
  217. width: '100%',
  218. left: 0,
  219. top: 0,
  220. right: 0,
  221. bottom: 0
  222. } : {}, showAltText ? {} : {
  223. color: 'transparent'
  224. }, style);
  225. const blurStyle = placeholder === 'blur' && blurDataURL && !blurComplete ? {
  226. backgroundSize: imgStyle.objectFit || 'cover',
  227. backgroundPosition: imgStyle.objectPosition || '50% 50%',
  228. backgroundRepeat: 'no-repeat',
  229. backgroundImage: `url("data:image/svg+xml;charset=utf-8,${(0, _imageBlurSvg).getImageBlurSvg({
  230. widthInt,
  231. heightInt,
  232. blurWidth,
  233. blurHeight,
  234. blurDataURL
  235. })}")`
  236. } : {};
  237. if (process.env.NODE_ENV === 'development') {
  238. if (blurStyle.backgroundImage && (blurDataURL == null ? void 0 : blurDataURL.startsWith('/'))) {
  239. // During `next dev`, we don't want to generate blur placeholders with webpack
  240. // because it can delay starting the dev server. Instead, `next-image-loader.js`
  241. // will inline a special url to lazily generate the blur placeholder at request time.
  242. blurStyle.backgroundImage = `url("${blurDataURL}")`;
  243. }
  244. }
  245. const imgAttributes = generateImgAttrs({
  246. config,
  247. src,
  248. unoptimized,
  249. width: widthInt,
  250. quality: qualityInt,
  251. sizes,
  252. loader
  253. });
  254. let srcString = src;
  255. if (process.env.NODE_ENV !== 'production') {
  256. if (typeof window !== 'undefined') {
  257. let fullUrl;
  258. try {
  259. fullUrl = new URL(imgAttributes.src);
  260. } catch (e) {
  261. fullUrl = new URL(imgAttributes.src, window.location.href);
  262. }
  263. allImgs.set(fullUrl.href, {
  264. src,
  265. priority,
  266. placeholder
  267. });
  268. }
  269. }
  270. let imageSrcSetPropName = 'imagesrcset';
  271. let imageSizesPropName = 'imagesizes';
  272. if (process.env.__NEXT_REACT_ROOT) {
  273. imageSrcSetPropName = 'imageSrcSet';
  274. imageSizesPropName = 'imageSizes';
  275. }
  276. const linkProps = {
  277. // Note: imagesrcset and imagesizes are not in the link element type with react 17.
  278. [imageSrcSetPropName]: imgAttributes.srcSet,
  279. [imageSizesPropName]: imgAttributes.sizes,
  280. crossOrigin: rest.crossOrigin
  281. };
  282. const onLoadingCompleteRef = (0, _react).useRef(onLoadingComplete);
  283. (0, _react).useEffect(()=>{
  284. onLoadingCompleteRef.current = onLoadingComplete;
  285. }, [
  286. onLoadingComplete
  287. ]);
  288. const imgElementArgs = _extends({
  289. isLazy,
  290. imgAttributes,
  291. heightInt,
  292. widthInt,
  293. qualityInt,
  294. className,
  295. imgStyle,
  296. blurStyle,
  297. loading,
  298. config,
  299. fill,
  300. unoptimized,
  301. placeholder,
  302. loader,
  303. srcString,
  304. onLoadingCompleteRef,
  305. setBlurComplete,
  306. setShowAltText
  307. }, rest);
  308. return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(ImageElement, Object.assign({}, imgElementArgs)), priority ? // Note how we omit the `href` attribute, as it would only be relevant
  309. // for browsers that do not support `imagesrcset`, and in those cases
  310. // it would likely cause the incorrect image to be preloaded.
  311. //
  312. // https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
  313. /*#__PURE__*/ _react.default.createElement(_head.default, null, /*#__PURE__*/ _react.default.createElement("link", Object.assign({
  314. key: '__nimg-' + imgAttributes.src + imgAttributes.srcSet + imgAttributes.sizes,
  315. rel: "preload",
  316. as: "image",
  317. href: imgAttributes.srcSet ? undefined : imgAttributes.src
  318. }, linkProps))) : null);
  319. }
  320. 'client';
  321. const configEnv = process.env.__NEXT_IMAGE_OPTS;
  322. const allImgs = new Map();
  323. let perfObserver;
  324. if (typeof window === 'undefined') {
  325. global.__NEXT_IMAGE_IMPORTED = true;
  326. }
  327. const VALID_LOADING_VALUES = [
  328. 'lazy',
  329. 'eager',
  330. undefined
  331. ];
  332. function isStaticRequire(src) {
  333. return src.default !== undefined;
  334. }
  335. function isStaticImageData(src) {
  336. return src.src !== undefined;
  337. }
  338. function isStaticImport(src) {
  339. return typeof src === 'object' && (isStaticRequire(src) || isStaticImageData(src));
  340. }
  341. function getWidths({ deviceSizes , allSizes }, width, sizes) {
  342. if (sizes) {
  343. // Find all the "vw" percent sizes used in the sizes prop
  344. const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g;
  345. const percentSizes = [];
  346. for(let match; match = viewportWidthRe.exec(sizes); match){
  347. percentSizes.push(parseInt(match[2]));
  348. }
  349. if (percentSizes.length) {
  350. const smallestRatio = Math.min(...percentSizes) * 0.01;
  351. return {
  352. widths: allSizes.filter((s)=>s >= deviceSizes[0] * smallestRatio),
  353. kind: 'w'
  354. };
  355. }
  356. return {
  357. widths: allSizes,
  358. kind: 'w'
  359. };
  360. }
  361. if (typeof width !== 'number') {
  362. return {
  363. widths: deviceSizes,
  364. kind: 'w'
  365. };
  366. }
  367. const widths = [
  368. ...new Set(// > This means that most OLED screens that say they are 3x resolution,
  369. // > are actually 3x in the green color, but only 1.5x in the red and
  370. // > blue colors. Showing a 3x resolution image in the app vs a 2x
  371. // > resolution image will be visually the same, though the 3x image
  372. // > takes significantly more data. Even true 3x resolution screens are
  373. // > wasteful as the human eye cannot see that level of detail without
  374. // > something like a magnifying glass.
  375. // https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html
  376. [
  377. width,
  378. width * 2 /*, width * 3*/
  379. ].map((w)=>allSizes.find((p)=>p >= w) || allSizes[allSizes.length - 1])),
  380. ];
  381. return {
  382. widths,
  383. kind: 'x'
  384. };
  385. }
  386. function generateImgAttrs({ config , src , unoptimized , width , quality , sizes , loader }) {
  387. if (unoptimized) {
  388. return {
  389. src,
  390. srcSet: undefined,
  391. sizes: undefined
  392. };
  393. }
  394. const { widths , kind } = getWidths(config, width, sizes);
  395. const last = widths.length - 1;
  396. return {
  397. sizes: !sizes && kind === 'w' ? '100vw' : sizes,
  398. srcSet: widths.map((w, i)=>`${loader({
  399. config,
  400. src,
  401. quality,
  402. width: w
  403. })} ${kind === 'w' ? w : i + 1}${kind}`).join(', '),
  404. // It's intended to keep `src` the last attribute because React updates
  405. // attributes in order. If we keep `src` the first one, Safari will
  406. // immediately start to fetch `src`, before `sizes` and `srcSet` are even
  407. // updated by React. That causes multiple unnecessary requests if `srcSet`
  408. // and `sizes` are defined.
  409. // This bug cannot be reproduced in Chrome or Firefox.
  410. src: loader({
  411. config,
  412. src,
  413. quality,
  414. width: widths[last]
  415. })
  416. };
  417. }
  418. function getInt(x) {
  419. if (typeof x === 'number' || typeof x === 'undefined') {
  420. return x;
  421. }
  422. if (typeof x === 'string' && /^[0-9]+$/.test(x)) {
  423. return parseInt(x, 10);
  424. }
  425. return NaN;
  426. }
  427. // See https://stackoverflow.com/q/39777833/266535 for why we use this ref
  428. // handler instead of the img's onLoad attribute.
  429. function handleLoading(img, src, placeholder, onLoadingCompleteRef, setBlurComplete) {
  430. if (!img || img['data-loaded-src'] === src) {
  431. return;
  432. }
  433. img['data-loaded-src'] = src;
  434. const p = 'decode' in img ? img.decode() : Promise.resolve();
  435. p.catch(()=>{}).then(()=>{
  436. if (!img.parentNode) {
  437. // Exit early in case of race condition:
  438. // - onload() is called
  439. // - decode() is called but incomplete
  440. // - unmount is called
  441. // - decode() completes
  442. return;
  443. }
  444. if (placeholder === 'blur') {
  445. setBlurComplete(true);
  446. }
  447. if (onLoadingCompleteRef == null ? void 0 : onLoadingCompleteRef.current) {
  448. onLoadingCompleteRef.current(img);
  449. }
  450. if (process.env.NODE_ENV !== 'production') {
  451. if (img.getAttribute('data-nimg') === 'future-fill') {
  452. if (!img.getAttribute('sizes') || img.getAttribute('sizes') === '100vw') {
  453. let widthViewportRatio = img.getBoundingClientRect().width / window.innerWidth;
  454. if (widthViewportRatio < 0.6) {
  455. (0, _utils).warnOnce(`Image with src "${src}" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more: https://nextjs.org/docs/api-reference/next/future/image#sizes`);
  456. }
  457. }
  458. if (img.parentElement) {
  459. const { position } = window.getComputedStyle(img.parentElement);
  460. const valid = [
  461. 'absolute',
  462. 'fixed',
  463. 'relative'
  464. ];
  465. if (!valid.includes(position)) {
  466. (0, _utils).warnOnce(`Image with src "${src}" has "fill" and parent element with invalid "position". Provided "${position}" should be one of ${valid.map(String).join(',')}.`);
  467. }
  468. }
  469. if (img.height === 0) {
  470. (0, _utils).warnOnce(`Image with src "${src}" has "fill" and a height value of 0. This is likely because the parent element of the image has not been styled to have a set height.`);
  471. }
  472. }
  473. const heightModified = img.height.toString() !== img.getAttribute('height');
  474. const widthModified = img.width.toString() !== img.getAttribute('width');
  475. if (heightModified && !widthModified || !heightModified && widthModified) {
  476. (0, _utils).warnOnce(`Image with src "${src}" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.`);
  477. }
  478. }
  479. });
  480. }
  481. const ImageElement = (_param)=>{
  482. var { imgAttributes , heightInt , widthInt , qualityInt , className , imgStyle , blurStyle , isLazy , fill , placeholder , loading , srcString , config , unoptimized , loader , onLoadingCompleteRef , setBlurComplete , setShowAltText , onLoad , onError } = _param, rest = _object_without_properties_loose(_param, [
  483. "imgAttributes",
  484. "heightInt",
  485. "widthInt",
  486. "qualityInt",
  487. "className",
  488. "imgStyle",
  489. "blurStyle",
  490. "isLazy",
  491. "fill",
  492. "placeholder",
  493. "loading",
  494. "srcString",
  495. "config",
  496. "unoptimized",
  497. "loader",
  498. "onLoadingCompleteRef",
  499. "setBlurComplete",
  500. "setShowAltText",
  501. "onLoad",
  502. "onError"
  503. ]);
  504. loading = isLazy ? 'lazy' : loading;
  505. return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement("img", Object.assign({}, rest, imgAttributes, {
  506. width: widthInt,
  507. height: heightInt,
  508. decoding: "async",
  509. "data-nimg": `future${fill ? '-fill' : ''}`,
  510. className: className,
  511. // @ts-ignore - TODO: upgrade to `@types/react@17`
  512. loading: loading,
  513. style: _extends({}, imgStyle, blurStyle),
  514. ref: (0, _react).useCallback((img)=>{
  515. if (!img) {
  516. return;
  517. }
  518. if (onError) {
  519. // If the image has an error before react hydrates, then the error is lost.
  520. // The workaround is to wait until the image is mounted which is after hydration,
  521. // then we set the src again to trigger the error handler (if there was an error).
  522. // eslint-disable-next-line no-self-assign
  523. img.src = img.src;
  524. }
  525. if (process.env.NODE_ENV !== 'production') {
  526. if (!srcString) {
  527. console.error(`Image is missing required "src" property:`, img);
  528. }
  529. if (img.getAttribute('objectFit') || img.getAttribute('objectfit')) {
  530. console.error(`Image has unknown prop "objectFit". Did you mean to use the "style" prop instead?`, img);
  531. }
  532. if (img.getAttribute('objectPosition') || img.getAttribute('objectposition')) {
  533. console.error(`Image has unknown prop "objectPosition". Did you mean to use the "style" prop instead?`, img);
  534. }
  535. if (img.getAttribute('alt') === null) {
  536. console.error(`Image is missing required "alt" property. Please add Alternative Text to describe the image for screen readers and search engines.`);
  537. }
  538. }
  539. if (img.complete) {
  540. handleLoading(img, srcString, placeholder, onLoadingCompleteRef, setBlurComplete);
  541. }
  542. }, [
  543. srcString,
  544. placeholder,
  545. onLoadingCompleteRef,
  546. setBlurComplete,
  547. onError,
  548. ]),
  549. onLoad: (event)=>{
  550. const img = event.currentTarget;
  551. handleLoading(img, srcString, placeholder, onLoadingCompleteRef, setBlurComplete);
  552. if (onLoad) {
  553. onLoad(event);
  554. }
  555. },
  556. onError: (event)=>{
  557. // if the real image fails to load, this will ensure "alt" is visible
  558. setShowAltText(true);
  559. if (placeholder === 'blur') {
  560. // If the real image fails to load, this will still remove the placeholder.
  561. setBlurComplete(true);
  562. }
  563. if (onError) {
  564. onError(event);
  565. }
  566. }
  567. })));
  568. };
  569. function defaultLoader({ config , src , width , quality }) {
  570. if (process.env.NODE_ENV !== 'production') {
  571. const missingValues = [];
  572. // these should always be provided but make sure they are
  573. if (!src) missingValues.push('src');
  574. if (!width) missingValues.push('width');
  575. if (missingValues.length > 0) {
  576. throw new Error(`Next Image Optimization requires ${missingValues.join(', ')} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify({
  577. src,
  578. width,
  579. quality
  580. })}`);
  581. }
  582. if (src.startsWith('//')) {
  583. throw new Error(`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`);
  584. }
  585. if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
  586. let parsedSrc;
  587. try {
  588. parsedSrc = new URL(src);
  589. } catch (err) {
  590. console.error(err);
  591. throw new Error(`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`);
  592. }
  593. if (process.env.NODE_ENV !== 'test') {
  594. // We use dynamic require because this should only error in development
  595. const { hasMatch } = require('../../shared/lib/match-remote-pattern');
  596. if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
  597. throw new Error(`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` + `See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`);
  598. }
  599. }
  600. }
  601. }
  602. if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
  603. // Special case to make svg serve as-is to avoid proxying
  604. // through the built-in Image Optimization API.
  605. return src;
  606. }
  607. return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${quality || 75}`;
  608. }
  609. if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
  610. Object.defineProperty(exports.default, '__esModule', { value: true });
  611. Object.assign(exports.default, exports);
  612. module.exports = exports.default;
  613. }
  614. //# sourceMappingURL=image.js.map