UNPKG

react-scroll-trigger

Version:

React component tied to scroll events with callbacks for enter, exit and progress while scrolling through the viewport.

3 lines (2 loc) 8.97 kB
/*! react-scroll-trigger v0.6.14 | (c) 2022 Ryan Hefner | MIT License | https://github.com/ryanhefner/react-scroll-trigger !*/ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):(e="undefined"!=typeof globalThis?globalThis:e||self)["react-scroll-trigger"]=t(e.React,e.ReactDOM)}(this,(function(e,t){"use strict";function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(e),r=o(t),i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},a="Expected a function",l=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,u=/^0o[0-7]+$/i,d=parseInt,p="object"==typeof i&&i&&i.Object===Object&&i,f="object"==typeof self&&self&&self.Object===Object&&self,h=p||f||Function("return this")(),m=Object.prototype.toString,g=Math.max,y=Math.min,v=function(){return h.Date.now()};function b(e,t,o){var n,r,i,l,s,c,u=0,d=!1,p=!1,f=!0;if("function"!=typeof e)throw new TypeError(a);function h(t){var o=n,i=r;return n=r=void 0,u=t,l=e.apply(i,o)}function m(e){return u=e,s=setTimeout(w,t),d?h(e):l}function b(e){var o=e-c;return void 0===c||o>=t||o<0||p&&e-u>=i}function w(){var e=v();if(b(e))return E(e);s=setTimeout(w,function(e){var o=t-(e-c);return p?y(o,i-(e-u)):o}(e))}function E(e){return s=void 0,f&&n?h(e):(n=r=void 0,l)}function T(){var e=v(),o=b(e);if(n=arguments,r=this,c=e,o){if(void 0===s)return m(c);if(p)return s=setTimeout(w,t),h(c)}return void 0===s&&(s=setTimeout(w,t)),l}return t=O(t)||0,S(o)&&(d=!!o.leading,i=(p="maxWait"in o)?g(O(o.maxWait)||0,t):i,f="trailing"in o?!!o.trailing:f),T.cancel=function(){void 0!==s&&clearTimeout(s),u=0,n=c=r=s=void 0},T.flush=function(){return void 0===s?l:E(v())},T}function S(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function O(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==m.call(e)}(e))return NaN;if(S(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=S(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(l,"");var o=c.test(e);return o||u.test(e)?d(e.slice(2),o?2:8):s.test(e)?NaN:+e}var w=function(e,t,o){var n=!0,r=!0;if("function"!=typeof e)throw new TypeError(a);return S(o)&&(n="leading"in o?!!o.leading:n,r="trailing"in o?!!o.trailing:r),b(e,t,{leading:n,maxWait:t,trailing:r})},E=["accept","acceptCharset","accessKey","action","allowFullScreen","allowTransparency","alt","async","autoComplete","autoFocus","autoPlay","capture","cellPadding","cellSpacing","challenge","charSet","checked","cite","classID","className","colSpan","cols","content","contentEditable","contextMenu","controls","controlsList","coords","crossOrigin","data","dateTime","default","defer","dir","disabled","download","draggable","encType","form","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","headers","height","hidden","high","href","hrefLang","htmlFor","httpEquiv","icon","id","inputMode","integrity","is","keyParams","keyType","kind","label","lang","list","loop","low","manifest","marginHeight","marginWidth","max","maxLength","media","mediaGroup","method","min","minLength","multiple","muted","name","noValidate","nonce","open","optimum","pattern","placeholder","poster","preload","profile","radioGroup","readOnly","rel","required","reversed","role","rowSpan","rows","sandbox","scope","scoped","scrolling","seamless","selected","shape","size","sizes","span","spellCheck","src","srcDoc","srcLang","srcSet","start","step","style","summary","tabIndex","target","title","type","useMap","value","width","wmode","wrap"],T=["about","datatype","inlist","prefix","property","resource","typeof","vocab"],P=["onCopy","onCut","onPaste","onCompositionEnd","onCompositionStart","onCompositionUpdate","onKeyDown","onKeyPress","onKeyUp","onFocus","onBlur","onChange","onInput","onInvalid","onReset","onSubmit","onClick","onContextMenu","onDoubleClick","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onPointerDown","onPointerMove","onPointerUp","onPointerCancel","onGotPointerCapture","onLostPointerCapture","onPointerEnter","onPointerLeave","onPointerOver","onPointerOut","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart","onScroll","onWheel","onAbort","onCanPlay","onCanPlayThrough","onDurationChange","onEmptied","onEncrypted","onEnded","onError","onLoadedData","onLoadedMetadata","onLoadStart","onPause","onPlay","onPlaying","onProgress","onRateChange","onSeeked","onSeeking","onStalled","onSuspend","onTimeUpdate","onVolumeChange","onWaiting","onLoad","onError","onAnimationStart","onAnimationEnd","onAnimationIteration","onTransitionEnd","onToggle"],j=/data-([a-zA-Z0-9\-]*)/,D=/aria-([a-zA-Z0-9\-]*)/;function x(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}function M(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?x(Object(o),!0).forEach((function(t){C(e,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):x(Object(o)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))}))}return e}function C(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function L(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function z(e,t){return z=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},z(e,t)}var R=function(e){var t,o;function i(t){var o;return(o=e.call(this,t)||this).onScrollThrottled=w(o.onScroll.bind(L(o)),t.throttleScroll,{trailing:!1}),o.onResizeThrottled=w(o.onResize.bind(L(o)),t.throttleResize,{trailing:!1}),o.state={inViewport:!1,progress:0,lastScrollPosition:null,lastScrollTime:null},o}o=e,(t=i).prototype=Object.create(o.prototype),t.prototype.constructor=t,z(t,o);var a=i.prototype;return a.componentDidMount=function(){addEventListener("resize",this.onResizeThrottled),addEventListener("scroll",this.onScrollThrottled),this.props.triggerOnLoad&&this.checkStatus()},a.componentDidUpdate=function(e,t){e.throttleScroll!==this.props.throttleScroll&&(removeEventListener("scroll",this.onScrollThrottled),this.onScrollThrottled=w(this.onScroll.bind(this),this.props.throttleScroll,{trailing:!1}),addEventListener("scroll",this.onScrollThrottled)),e.throttleResize!==this.props.throttleResize&&(removeEventListener("resize",this.onResizeThrottled),this.onResizeThrottled=w(this.onResize.bind(this),this.props.throttleResize,{trailing:!1}),addEventListener("resize",this.onResizeThrottled))},a.componentWillUnmount=function(){removeEventListener("resize",this.onResizeThrottled),removeEventListener("scroll",this.onScrollThrottled)},a.onResize=function(){this.checkStatus()},a.onScroll=function(){this.checkStatus()},a.checkStatus=function(){var e=this.props,t=e.containerRef,o=e.onEnter,n=e.onExit,i=e.onProgress,a=this.state,l=a.lastScrollPosition,s=a.lastScrollTime,c=r.default.findDOMNode(this.element).getBoundingClientRect(),u="string"==typeof t?document.querySelector(t):t,d=t===document.documentElement?Math.max(t.clientHeight,window.innerHeight||0):u.clientHeight,p=c.top<=d&&c.bottom>=0,f=window.scrollY,h=l&&s?Math.abs((l-f)/(s-Date.now())):null;if(p){var m=Math.max(0,Math.min(1,1-c.bottom/(d+c.height)));return this.state.inViewport||(this.setState({inViewport:p}),o({progress:m,velocity:h},this)),i({progress:m,velocity:h},this),void this.setState({lastScrollPosition:f,lastScrollTime:Date.now()})}if(this.state.inViewport){var g=c.top<=d?1:0;this.setState({lastScrollPosition:f,lastScrollTime:Date.now(),inViewport:p,progress:g}),i({progress:g,velocity:h},this),n({progress:g,velocity:h},this)}},a.render=function(){var e=this,t=this.props,o=t.children,r=t.component,i=n.default.isValidElement(r)?"cloneElement":"createElement";return n.default[i](r,M(M({},function(e,t,o){void 0===e&&(e={}),void 0===t&&(t=[]),void 0===o&&(o=[]);var n=Object.assign({},e),r=Object.keys(n).filter((function(e){return-1===t.indexOf(e)&&(o.indexOf(e)>-1||-1!==E.indexOf(e)||-1!==T.indexOf(e)||!!j.test(e)||!!D.test(e)||-1!==P.indexOf(e))}));return Object.keys(n).forEach((function(e){-1===r.indexOf(e)&&delete n[e]})),n}(this.props,["onProgress"])),{},{ref:function(t){e.element=t}}),o)},i}(e.Component);return R.defaultProps={component:"div",containerRef:"undefined"!=typeof document?document.documentElement:"html",throttleResize:100,throttleScroll:100,triggerOnLoad:!0,onEnter:function(){},onExit:function(){},onProgress:function(){}},R}));