New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@classuper/react-graceful-image

Package Overview
Dependencies
Maintainers
2
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@classuper/react-graceful-image - npm Package Compare versions

Comparing version

to
1.2.13

146

lib/index.js

@@ -1,1 +0,145 @@

!function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("react"));else if("function"==typeof define&&define.amd)define(["react"],e);else{var n="object"==typeof exports?e(require("react")):e(t.react);for(var r in n)("object"==typeof exports?exports:t)[r]=n[r]}}(window,(function(t){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=2)}([function(e,n){e.exports=t},function(t,e,n){(function(e){var n="Expected a function",r=NaN,o="[object Symbol]",i=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,s=parseInt,l="object"==typeof e&&e&&e.Object===Object&&e,f="object"==typeof self&&self&&self.Object===Object&&self,p=l||f||Function("return this")(),d=Object.prototype.toString,y=Math.max,h=Math.min,m=function(){return p.Date.now()};function v(t,e,r){var o,i,a,u,c,s,l=0,f=!1,p=!1,d=!0;if("function"!=typeof t)throw new TypeError(n);function v(e){var n=o,r=i;return o=i=void 0,l=e,u=t.apply(r,n)}function w(t){var n=t-s;return void 0===s||n>=e||n<0||p&&t-l>=a}function O(){var t=m();if(w(t))return j(t);c=setTimeout(O,function(t){var n=e-(t-s);return p?h(n,a-(t-l)):n}(t))}function j(t){return c=void 0,d&&o?v(t):(o=i=void 0,u)}function x(){var t=m(),n=w(t);if(o=arguments,i=this,s=t,n){if(void 0===c)return function(t){return l=t,c=setTimeout(O,e),f?v(t):u}(s);if(p)return c=setTimeout(O,e),v(s)}return void 0===c&&(c=setTimeout(O,e)),u}return e=b(e)||0,g(r)&&(f=!!r.leading,a=(p="maxWait"in r)?y(b(r.maxWait)||0,e):a,d="trailing"in r?!!r.trailing:d),x.cancel=function(){void 0!==c&&clearTimeout(c),l=0,o=s=i=c=void 0},x.flush=function(){return void 0===c?u:j(m())},x}function g(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function b(t){if("number"==typeof t)return t;if(function(t){return"symbol"==typeof t||function(t){return!!t&&"object"==typeof t}(t)&&d.call(t)==o}(t))return r;if(g(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=g(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(i,"");var n=u.test(t);return n||c.test(t)?s(t.slice(2),n?2:8):a.test(t)?r:+t}t.exports=function(t,e,r){var o=!0,i=!0;if("function"!=typeof t)throw new TypeError(n);return g(r)&&(o="leading"in r?!!r.leading:o,i="trailing"in r?!!r.trailing:i),v(t,e,{leading:o,maxWait:e,trailing:i})}}).call(this,n(3))},function(t,e,n){"use strict";n.r(e);var r=n(0),o=n.n(r),i=n(1),a=n.n(i);function u(t){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function c(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function s(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?c(n,!0).forEach((function(e){y(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):c(n).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function l(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function f(t){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function p(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function d(t,e){return(d=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function y(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function h(t,e){window.addEventListener?window.addEventListener(t,e):window.attachEvent("on"+t,e)}function m(t){if(!t)return!1;var e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.top<=(window.innerHeight||document.documentElement.clientHeight)&&e.left<=(window.innerWidth||document.documentElement.clientWidth)}var v=document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1"),g=function(t){function e(t){var n;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),n=function(t,e){return!e||"object"!==u(e)&&"function"!=typeof e?p(t):e}(this,f(e).call(this,t)),y(p(n),"lazyLoad",(function(){m(n.placeholderImage)&&(n.clearEventListeners(),n.loadImage())})),n._isMounted=!1;var r=null;if(v){var o=n.props.style&&n.props.style.width?n.props.style.width:n.props.width?n.props.width:"200",i=n.props.style&&n.props.style.height?n.props.style.height:n.props.height?n.props.height:"150";r=(r="data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width%3D'{{w}}' height%3D'{{h}}' viewBox%3D'0 0 {{w}} {{h}}'%2F%3E").replace(/{{w}}/g,o).replace(/{{h}}/g,i)}return n.throttledFunction=a()(n.lazyLoad,150),n.state={loaded:!1,retryDelay:n.props.retry.delay,retryCount:1,placeholder:r},n}var n,r,i;return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&d(t,e)}(e,t),n=e,(r=[{key:"addAnimationStyles",value:function(){if(!document.head.querySelectorAll("[data-gracefulimage]").length){var t=document.createElement("style");t.setAttribute("data-gracefulimage","exists"),document.head.appendChild(t),t.sheet.insertRule("\n @keyframes gracefulimage {\n 0% { opacity: 0.25; }\n 50% { opacity: 0.5; }\n 100% { opacity: 1; }\n }\n",t.sheet.cssRules.length)}}},{key:"setLoaded",value:function(){this._isMounted&&this.setState({loaded:!0})}},{key:"loadImage",value:function(){var t=this,e=new Image;e.onload=function(){t.setLoaded()},e.onerror=function(){t.handleImageRetries(e)},e.src=this.props.src}},{key:"componentDidMount",value:function(){this._isMounted=!0,this.addAnimationStyles(),!this.props.noLazyLoad&&v?m(this.placeholderImage)?this.loadImage():(h("load",this.throttledFunction),h("scroll",this.throttledFunction),h("resize",this.throttledFunction),h("gestureend",this.throttledFunction)):this.loadImage()}},{key:"clearEventListeners",value:function(){this.throttledFunction.cancel(),window.removeEventListener("load",this.throttledFunction),window.removeEventListener("scroll",this.throttledFunction),window.removeEventListener("resize",this.throttledFunction),window.removeEventListener("gestureend",this.throttledFunction)}},{key:"componentWillUnmount",value:function(){this._isMounted=!1,this.timeout&&window.clearTimeout(this.timeout),this.clearEventListeners()}},{key:"handleImageRetries",value:function(t){var e=this;this._isMounted&&this.setState({loaded:!1},(function(){e.state.retryCount<=e.props.retry.count&&(e.timeout=setTimeout((function(){e._isMounted&&(t.src=e.props.src,e.setState((function(t){return{retryDelay:"multiply"===e.props.retry.accumulate?t.retryDelay*e.props.retry.delay:"add"===e.props.retry.accumulate?t.retryDelay+e.props.retry.delay:"noop"===e.props.retry.accumulate?e.props.retry.delay:"multiply",retryCount:t.retryCount+1}})))}),1e3*e.state.retryDelay))}))}},{key:"render",value:function(){var t=this;if(!this.state.loaded&&(this.props.noPlaceholder||!v))return null;var e=this.state.loaded?this.props.src:this.state.placeholder,n=this.state.loaded?{animationName:"gracefulimage",animationDuration:"0.3s",animationIterationCount:1,animationTimingFunction:"ease-in"}:{background:this.props.placeholderColor};return o.a.createElement("img",{src:e,srcSet:this.props.srcSet,className:this.props.className,width:this.props.width,height:this.props.height,style:s({},n,{},this.props.style),alt:this.props.alt,ref:function(e){return t.placeholderImage=e}})}}])&&l(n.prototype,r),i&&l(n,i),e}(r.Component);g.defaultProps={placeholderColor:"#eee",retry:{count:8,delay:2,accumulate:"multiply"},noRetry:!1,noPlaceholder:!1,noLazyLoad:!1},e.default=g},function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n}])}));
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else {
var a = typeof exports === 'object' ? factory(require("react")) : factory(root["react"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_react__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/index.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/lodash.throttle/index.js":
/*!***********************************************!*\
!*** ./node_modules/lodash.throttle/index.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("/* WEBPACK VAR INJECTION */(function(global) {/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\nfunction throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = throttle;\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/lodash.throttle/index.js?");
/***/ }),
/***/ "./node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?");
/***/ }),
/***/ "./src/index.js":
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"react\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var lodash_throttle__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash.throttle */ \"./node_modules/lodash.throttle/index.js\");\n/* harmony import */ var lodash_throttle__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash_throttle__WEBPACK_IMPORTED_MODULE_1__);\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n\n\n\nfunction registerListener(event, fn) {\n if (window.addEventListener) {\n window.addEventListener(event, fn);\n } else {\n window.attachEvent(\"on\" + event, fn);\n }\n}\n\nfunction isClient() {\n return typeof window !== 'undefined' && window.document;\n}\n\nfunction isInViewport(el) {\n if (!el) return false;\n var rect = el.getBoundingClientRect();\n return rect.top >= 0 && rect.left >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth);\n}\n\nvar fadeIn = \"\\n @keyframes gracefulimage {\\n 0% { opacity: 0.25; }\\n 50% { opacity: 0.5; }\\n 100% { opacity: 1; }\\n }\\n\";\nvar IS_SSR = !isClient();\nvar IS_SVG_SUPPORTED = IS_SSR ? false : document.implementation.hasFeature(\"http://www.w3.org/TR/SVG11/feature#Image\", \"1.1\");\n\nvar GracefulImage =\n/*#__PURE__*/\nfunction (_Component) {\n _inherits(GracefulImage, _Component);\n\n function GracefulImage(props) {\n var _this;\n\n _classCallCheck(this, GracefulImage);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(GracefulImage).call(this, props));\n\n _defineProperty(_assertThisInitialized(_this), \"lazyLoad\", function () {\n if (isInViewport(_this.placeholderImage)) {\n _this.clearEventListeners();\n\n _this.loadImage();\n }\n });\n\n _this._isMounted = false;\n var placeholder = null;\n\n if (IS_SVG_SUPPORTED) {\n var width = _this.props.style && _this.props.style.width ? _this.props.style.width : _this.props.width ? _this.props.width : \"200\";\n var height = _this.props.style && _this.props.style.height ? _this.props.style.height : _this.props.height ? _this.props.height : \"150\";\n placeholder = \"data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width%3D'{{w}}' height%3D'{{h}}' viewBox%3D'0 0 {{w}} {{h}}'%2F%3E\";\n placeholder = placeholder.replace(/{{w}}/g, width).replace(/{{h}}/g, height);\n } // store a reference to the throttled function\n\n\n _this.throttledFunction = lodash_throttle__WEBPACK_IMPORTED_MODULE_1___default()(_this.lazyLoad, 150);\n _this.state = {\n loaded: false,\n retryDelay: _this.props.retry.delay,\n retryCount: 1,\n placeholder: placeholder\n };\n return _this;\n }\n /*\n Creating a stylesheet to hold the fading animation\n */\n\n\n _createClass(GracefulImage, [{\n key: \"addAnimationStyles\",\n value: function addAnimationStyles() {\n if (IS_SSR) return;\n var exists = document.head.querySelectorAll(\"[data-gracefulimage]\");\n\n if (!exists.length) {\n var styleElement = document.createElement(\"style\");\n styleElement.setAttribute(\"data-gracefulimage\", \"exists\");\n document.head.appendChild(styleElement);\n styleElement.sheet.insertRule(fadeIn, styleElement.sheet.cssRules.length);\n }\n }\n /*\n Marks an image as loaded\n */\n\n }, {\n key: \"setLoaded\",\n value: function setLoaded() {\n if (this._isMounted) {\n this.setState({\n loaded: true\n });\n }\n }\n /*\n Attempts to download an image, and tracks its success / failure\n */\n\n }, {\n key: \"loadImage\",\n value: function loadImage() {\n var _this2 = this;\n\n var image = new Image();\n\n image.onload = function () {\n _this2.setLoaded();\n };\n\n image.onerror = function () {\n _this2.handleImageRetries(image);\n };\n\n image.src = this.props.src;\n }\n /*\n If placeholder is currently within the viewport then load the actual image\n and remove all event listeners associated with it\n */\n\n }, {\n key: \"componentDidMount\",\n\n /*\n Attempts to load an image src passed via props\n and utilises image events to track sccess / failure of the loading\n */\n value: function componentDidMount() {\n this._isMounted = true;\n this.addAnimationStyles(); // if user wants to lazy load\n\n if (!this.props.noLazyLoad && IS_SVG_SUPPORTED) {\n // check if already within viewport to avoid attaching listeners\n if (isInViewport(this.placeholderImage)) {\n this.loadImage();\n } else {\n registerListener(\"load\", this.throttledFunction);\n registerListener(\"scroll\", this.throttledFunction);\n registerListener(\"resize\", this.throttledFunction);\n registerListener(\"gestureend\", this.throttledFunction); // to detect pinch on mobile devices\n }\n } else {\n this.loadImage();\n }\n }\n }, {\n key: \"clearEventListeners\",\n value: function clearEventListeners() {\n this.throttledFunction.cancel();\n window.removeEventListener(\"load\", this.throttledFunction);\n window.removeEventListener(\"scroll\", this.throttledFunction);\n window.removeEventListener(\"resize\", this.throttledFunction);\n window.removeEventListener(\"gestureend\", this.throttledFunction);\n }\n /*\n Clear timeout incase retry is still running\n And clear any existing event listeners\n */\n\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n this._isMounted = false;\n\n if (this.timeout) {\n window.clearTimeout(this.timeout);\n }\n\n this.clearEventListeners();\n }\n /*\n Handles the actual re-attempts of loading the image\n following the default / provided retry algorithm\n */\n\n }, {\n key: \"handleImageRetries\",\n value: function handleImageRetries(image) {\n var _this3 = this;\n\n // if we are not mounted anymore, we do not care, and we can bail\n if (!this._isMounted) {\n return;\n }\n\n this.setState({\n loaded: false\n }, function () {\n if (_this3.state.retryCount <= _this3.props.retry.count) {\n _this3.timeout = setTimeout(function () {\n // if we are not mounted anymore, we do not care, and we can bail\n if (!_this3._isMounted) {\n return;\n } // re-attempt fetching the image\n\n\n image.src = _this3.props.src; // update count and delay\n\n _this3.setState(function (prevState) {\n var updateDelay;\n\n if (_this3.props.retry.accumulate === \"multiply\") {\n updateDelay = prevState.retryDelay * _this3.props.retry.delay;\n } else if (_this3.props.retry.accumulate === \"add\") {\n updateDelay = prevState.retryDelay + _this3.props.retry.delay;\n } else if (_this3.props.retry.accumulate === \"noop\") {\n updateDelay = _this3.props.retry.delay;\n } else {\n updateDelay = \"multiply\";\n }\n\n return {\n retryDelay: updateDelay,\n retryCount: prevState.retryCount + 1\n };\n });\n }, _this3.state.retryDelay * 1000);\n }\n });\n }\n /*\n - If image hasn't yet loaded AND user didn't want a placeholder OR SVG not supported then don't render anything\n - Else if image has loaded then render the image\n - Else render the placeholder\n */\n\n }, {\n key: \"render\",\n value: function render() {\n var _this4 = this;\n\n if (!this.state.loaded && (this.props.noPlaceholder || !IS_SVG_SUPPORTED)) return null;\n var src = this.state.loaded ? this.props.src : this.state.placeholder;\n var animationStyle = this.props.noAnimation ? {} : {\n animationName: \"gracefulimage\",\n animationDuration: \"0.3s\",\n animationIterationCount: 1,\n animationTimingFunction: \"ease-in\"\n };\n var style = this.state.loaded ? animationStyle : {\n background: this.props.placeholderColor\n };\n return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"img\", {\n src: src,\n srcSet: this.props.srcSet,\n className: this.props.className,\n width: this.props.width,\n height: this.props.height,\n style: _objectSpread({}, style, {}, this.props.style),\n alt: this.props.alt,\n ref: function ref(_ref) {\n return _this4.placeholderImage = _ref;\n }\n });\n }\n }]);\n\n return GracefulImage;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\nGracefulImage.defaultProps = {\n placeholderColor: \"#eee\",\n retry: {\n count: 8,\n delay: 2,\n accumulate: \"multiply\"\n },\n noRetry: false,\n noPlaceholder: false,\n noLazyLoad: false,\n noAnimation: false\n};\n/* harmony default export */ __webpack_exports__[\"default\"] = (GracefulImage);\n\n//# sourceURL=webpack:///./src/index.js?");
/***/ }),
/***/ "react":
/*!************************!*\
!*** external "react" ***!
\************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("module.exports = __WEBPACK_EXTERNAL_MODULE_react__;\n\n//# sourceURL=webpack:///external_%22react%22?");
/***/ })
/******/ });
});

2

package.json
{
"name": "@classuper/react-graceful-image",
"version": "1.2.12",
"version": "1.2.13",
"description": "An image component for gracefully dealing with images errors by providing a placeholder and retries on failure",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

Sorry, the diff of this file is not supported yet