lazy-react 3.1.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/demo/index.html CHANGED
@@ -2,38 +2,42 @@
2
2
  <html>
3
3
  <head>
4
4
  <title>Demo</title>
5
- <style type="text/css">
6
- body{
7
- margin: 0;
8
- padding: 0;
9
- max-width: 100vw;
10
- min-height: 110vh;
11
- }
12
- img{
13
- max-height: 100vh;
14
- max-width: 100vw;
15
- margin: 0 auto;
16
- display: block;
17
- }
18
- h2{
19
- font-family: sans-serif;
20
- text-align: center;
21
- }
22
- .fill{
23
- width: 100vw;
24
- height: 100vh;
25
- background-size: cover;
26
- background-position: center center;
27
- }
28
- .styledImage{
29
- height: 500px;
30
- border: 10px solid tomato;
31
- box-sizing: border-box;
32
- }
33
- </style>
5
+ <style>body {
6
+ max-width: 100vw;
7
+ min-height: 110vh;
8
+ margin: 0;
9
+ padding: 0;
10
+ }
11
+
12
+ img {
13
+ max-height: 100vh;
14
+ max-width: 100vw;
15
+ margin: 0 auto;
16
+ display: block;
17
+ }
18
+
19
+ h2 {
20
+ text-align: center;
21
+ font-family: sans-serif;
22
+ }
23
+
24
+ .fill {
25
+ width: 100vw;
26
+ height: 100vh;
27
+ background-position: center;
28
+ background-size: cover;
29
+ }
30
+
31
+ .styledImage {
32
+ height: 500px;
33
+ box-sizing: border-box;
34
+ border: 10px solid tomato;
35
+ }
36
+
37
+ </style>
34
38
  </head>
35
39
  <body>
36
40
  <div id="app"></div>
37
- <script type="text/javascript" src="index.js"></script>
41
+ <script src="/index.0aef4497.js" defer=""></script>
38
42
  </body>
39
43
  </html>
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.LazyReact=t(require("react")):e.LazyReact=t(e.React)}(self,(function(e){return(()=>{"use strict";var t={787:t=>{t.exports=e}},r={};function n(e){var o=r[e];if(void 0!==o)return o.exports;var i=r[e]={exports:{}};return t[e](i,i.exports,n),i.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};return(()=>{n.r(o),n.d(o,{LazyBackgroundImage:()=>u,LazyComponent:()=>f,LazyFrame:()=>s,LazyImage:()=>c,useRenderIfInViewPort:()=>i});var e=n(787),t=n.n(e);function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function i(t,n){var o,i,a=(o=(0,e.useState)({link:"",visible:!1}),i=2,function(e){if(Array.isArray(e))return e}(o)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i=[],l=!0,a=!1;try{for(r=r.call(e);!(l=(n=r.next()).done)&&(i.push(n.value),!t||i.length!==t);l=!0);}catch(e){a=!0,o=e}finally{try{l||null==r.return||r.return()}finally{if(a)throw o}}return i}}(o,i)||function(e,t){if(e){if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}(o,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),u=a[0],c=a[1];function s(){c({visible:!0,link:n.link})}return(0,e.useEffect)((function(){return void 0!==t.current&&l.addElement({element:t.current,props:n,makeItVisible:s}),function(){return l.removeElementFromList({element:t.current,props:n,makeItVisible:s})}}),[]),u}var l={elements:[]};function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function u(r){var n,o,l=(0,e.useRef)(),u=i(l,r),c=(n=(0,e.useState)(Object.assign({backgroundImage:"url(".concat(u.link,")")},r.style)),o=2,function(e){if(Array.isArray(e))return e}(n)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,i=[],l=!0,a=!1;try{for(r=r.call(e);!(l=(n=r.next()).done)&&(i.push(n.value),!t||i.length!==t);l=!0);}catch(e){a=!0,o=e}finally{try{l||null==r.return||r.return()}finally{if(a)throw o}}return i}}(n,o)||function(e,t){if(e){if("string"==typeof e)return a(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(e,t):void 0}}(n,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),s=c[0],f=c[1];return(0,e.useEffect)((function(){f(Object.assign({backgroundImage:"url(".concat(u.link,")")},r.style))}),[u]),t().createElement("div",{className:r.className,style:s,ref:l},r.children)}function c(r){var n=(0,e.useRef)(),o=i(n,r);return t().createElement("img",{src:o.link,alt:r.alt,style:r.style,className:r.className,ref:n})}function s(r){var n=(0,e.useRef)(),o=i(n,r);return t().createElement("iframe",{height:r.height||"500",scrolling:r.scrolling||"no",src:o.link,frameBorder:r.frameBorder||"no",allowtransparency:r.allowTransparency||"true",allowFullScreen:r.allowFullScreen||!0,style:r.style||{},ref:n})}function f(r){var n=(0,e.useRef)(),o=i(n,r),l=t().createElement("div",{style:r.style?r.style:{heigt:"300px",width:"300px"}});return t().createElement("div",{ref:n},o.visible?r.children:l)}l.isInViewPort=function(e){var t=e.offset,r=e.top,n=e.left;return r<window.innerHeight+t&&n<window.innerWidth+t},l.calculateNewPosition=function(e){var t=e.element.getBoundingClientRect(),r=t.top,n=t.left;return Object.assign({},e,{top:r,left:n})},l.addElement=function(e){var t=e.element,r=e.props,n=e.makeItVisible,o=t.getBoundingClientRect(),i=o.top,a=o.left;l.elements.push({element:t,top:i,left:a,offset:r.offset||100,makeItVisible:n}),"boolean"==typeof l.isListenerAttached&&(l.isListenerAttached=window.requestAnimationFrame(l.eventHandler))},l.eventHandler=function(){0===l.elements.length?l.removeScrollHandler():(l.elements.forEach((function(e,t){l.isInViewPort(e)?(e.makeItVisible(),l.removeElementFromList(e)):l.elements[t]=l.calculateNewPosition(e)})),l.isListenerAttached=window.requestAnimationFrame(l.eventHandler))},l.removeScrollHandler=function(){window.cancelAnimationFrame(l.isListenerAttached),l.isListenerAttached=!1},l.removeElementFromList=function(e){l.elements=l.elements.filter((function(t){return t!==e}))},l.isListenerAttached=!1})(),o})()}));
1
+ var e,t=require("react/jsx-runtime"),n=require("react");function r(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}function l(e){let[r,l,i]=a(e);const[o,s]=(0,n.useState)({backgroundImage:`url(${l})`,...e.style});return(0,n.useEffect)((()=>{s({backgroundImage:`url(${l})`,...e.style})}),[l,i]),(0,t.jsx)("div",{className:e.className,style:o,ref:e=>{r(e)},children:e.children})}function i(e){const[n,r]=a(e);return(0,t.jsx)("div",{ref:e=>{n(e)},children:(0,t.jsx)("img",{src:r,alt:e.alt,style:e.style,className:e.className})})}function o(e){let[n,r]=a(e);return(0,t.jsx)("iframe",{height:e.height||"500",scrolling:e.scrolling||"no",src:r,frameBorder:e.frameBorder||"no",allowFullScreen:e.allowFullScreen||!0,style:e.style||{},ref:e=>{n(e)},...e})}function s(e){const[n,r,l]=a(e);return l?(0,t.jsx)("div",{children:e.children}):(0,t.jsx)("div",{ref:e=>{n(e)},style:{height:"300px",width:"300px",...e.style}})}function a(e){const[t,r]=(0,n.useState)(""),[l,i]=(0,n.useState)(!1);let[o,s]=(0,n.useState)(null);const a=(0,n.useMemo)((()=>({element:o,makeItVisible:d,offset:e.offset||100})),[o,e]),c=(0,n.useCallback)((e=>{null!==e&&s(e)}),[]);function d(){e.link&&r((()=>e.link)),i((()=>!0))}return(0,n.useEffect)((()=>(null!==o&&u.addElement(a),()=>u.removeElementFromList(a))),[o]),[c,t,l]}e=module.exports,Object.defineProperty(e,"__esModule",{value:!0,configurable:!0}),r(module.exports,"default",(()=>a)),r(module.exports,"LazyBackgroundImage",(()=>l)),r(module.exports,"LazyImage",(()=>i)),r(module.exports,"LazyFrame",(()=>o)),r(module.exports,"LazyComponent",(()=>s));let c=[];const u={isInViewPort:({offset:e,top:t,left:n})=>t<window.innerHeight+e&&n<window.innerWidth+e,calculateNewPosition:e=>{const{top:t,left:n}=e.element?.getBoundingClientRect()||{top:0,left:0};return{...e,top:t,left:n}},addElement:function(e){c.push(e),0===u.isListenerAttached&&(u.isListenerAttached=window.requestAnimationFrame(u.eventHandler))},eventHandler:function(){0===c.length?u.removeScrollHandler():(c.forEach(((e,t)=>{u.isInViewPort(u.calculateNewPosition(e))&&(e.makeItVisible(),u.removeElementFromList(e))})),u.isListenerAttached=window.requestAnimationFrame(u.eventHandler))},removeScrollHandler:function(){window.cancelAnimationFrame(u.isListenerAttached),u.isListenerAttached=0},removeElementFromList:function(e){c=c.filter((t=>t!==e))},isListenerAttached:0};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"mappings":"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","sources":["src/lazyLoadBackgroundImage.tsx","src/lazyLoadImage.tsx","src/lazyLoadFrame.tsx","src/lazyLoadComponent.tsx","src/useIsInViewport.tsx"],"sourcesContent":["import React, { useState, useEffect } from 'react' // eslint-disable-line no-unused-vars\nimport useIsInViewPort from './index'\n\nexport default function LazyBackgroundImage(props: any) {\n let [setRef, link, isViewable] = useIsInViewPort(props)\n\n const [style, setStyle] = useState({\n backgroundImage: `url(${link})`,\n ...props.style,\n })\n\n useEffect(() => {\n setStyle({\n backgroundImage: `url(${link})`,\n ...props.style,\n })\n }, [link, isViewable])\n\n return (\n <div\n className={props.className}\n style={style}\n ref={(node) => {\n setRef(node)\n }}\n >\n {props.children}\n </div>\n )\n}\n","import React from 'react' // eslint-disable-line no-unused-vars\nimport useIsInViewPort from './index'\n\nexport default function LazyImage(props: any) {\n const [setRef, link] = useIsInViewPort(props)\n\n return (\n <div\n ref={(node) => {\n setRef(node)\n }}\n >\n <img\n src={link}\n alt={props.alt}\n style={props.style}\n className={props.className}\n />\n </div>\n )\n}\n","import React from 'react' // eslint-disable-line no-unused-vars\nimport useIsInViewPort from './index'\n\nexport default function LazyFrame(props: any) {\n let [setRef, link] = useIsInViewPort(props)\n\n return (\n <iframe\n height={props.height || '500'}\n scrolling={props.scrolling || 'no'}\n src={link}\n frameBorder={props.frameBorder || 'no'}\n allowFullScreen={props.allowFullScreen || true}\n style={props.style || {}}\n ref={(node) => {\n setRef(node)\n }}\n {...props}\n />\n )\n}\n","import React from 'react'\nimport useIsInViewport from './index'\n\nexport default function LazyComponent(props: any) {\n const [setRef, link, isVisible] = useIsInViewport(props)\n\n if (!isVisible)\n return (\n <div\n ref={(node) => {\n setRef(node)\n }}\n style={{\n height: '300px',\n width: '300px',\n ...props.style,\n }}\n ></div>\n )\n\n return <div>{props.children}</div>\n}\n","import React, { useState, useEffect, useMemo, useCallback } from 'react' // eslint-disable-line no-unused-vars\n\ninterface InstanceElement {\n makeItVisible: () => void\n element: HTMLElement | null\n offset: number\n}\n\nexport default function useRenderIfInViewPort(props: {\n link: string\n offset: number\n}): [Function, string, boolean] {\n const [link, setLink] = useState('')\n const [visible, setVisible] = useState(false)\n\n let [ref, setRef] = useState(null)\n\n const thisInstance = useMemo(() => {\n return {\n element: ref,\n makeItVisible,\n offset: props.offset || 100,\n }\n }, [ref, props])\n\n const getRef = useCallback((node) => {\n if (node !== null) setRef(node)\n }, [])\n\n function makeItVisible() {\n if(props.link)\n setLink(() => props.link)\n setVisible(() => true)\n }\n\n useEffect(() => {\n if (ref !== null)\n // add the element to the array of elements that are waiting to be lazy loaded\n CheckIfRender.addElement(thisInstance)\n return () =>\n // if the element is unloaded remove the element from the list of elements that needs to be lazy loader\n CheckIfRender.removeElementFromList(thisInstance)\n }, [ref])\n\n return [getRef, link, visible]\n}\n\n// array with all the elements that are waiting to be shown in the viewport\nlet elements: InstanceElement[] = []\n\nconst CheckIfRender = {\n // top: the position of the element in relation with the top of the browser\n // left: the position of the element in relation with the left of the browser\n // offset: the desired offset of the element in relation of the viewport\n isInViewPort: ({\n offset,\n top,\n left,\n }: {\n offset: number\n top: number\n left: number\n }) => top < window.innerHeight + offset && left < window.innerWidth + offset,\n\n calculateNewPosition: (elem: InstanceElement) => {\n const { top, left } = elem.element?.getBoundingClientRect() || {\n top: 0,\n left: 0,\n }\n\n return {\n ...elem,\n top,\n left,\n }\n },\n addElement: function (element: InstanceElement) {\n //the distance from the pixel 0,0 and the top of the element\n elements.push(element)\n //check if has already been started the rAF cycle\n if (CheckIfRender.isListenerAttached === 0) {\n CheckIfRender.isListenerAttached = window.requestAnimationFrame(\n CheckIfRender.eventHandler\n )\n }\n },\n eventHandler: function () {\n //if there is no more element to lazy load remove the listener/rAF\n if (elements.length === 0) {\n CheckIfRender.removeScrollHandler()\n } else {\n elements.forEach((elem, i) => {\n const haveToShow = CheckIfRender.isInViewPort(\n CheckIfRender.calculateNewPosition(elem)\n )\n if (haveToShow) {\n elem.makeItVisible()\n // remove element from the list of elements to lazy load\n CheckIfRender.removeElementFromList(elem)\n }\n })\n CheckIfRender.isListenerAttached = window.requestAnimationFrame(\n CheckIfRender.eventHandler\n )\n }\n },\n\n removeScrollHandler: function () {\n window.cancelAnimationFrame(CheckIfRender.isListenerAttached)\n CheckIfRender.isListenerAttached = 0\n },\n //When an element is unloaded remove it from the list of elements that are waiting to be lazy-loaded\n removeElementFromList: function (toRemove: InstanceElement) {\n elements = elements.filter((elem) => elem !== toRemove)\n },\n isListenerAttached: 0, // intended as not set\n}\n\nexport { CheckIfRender }\n"],"names":["$6e38eea936045ca0$export$2e2bcd8739ae039","props","setRef","link","isViewable","$03b515f3f8c77d8f$export$2e2bcd8739ae039","style","setStyle","$9w1Q4$react","useState","backgroundImage","useEffect","$9w1Q4$reactjsxruntime","jsx","className","ref","node","children","$f6f596272f209e0c$export$2e2bcd8739ae039","src","alt","$8e3d626f2d1eebd8$export$2e2bcd8739ae039","height","scrolling","frameBorder","allowFullScreen","$c17687259f8b5ddf$export$2e2bcd8739ae039","isVisible","width","setLink","visible","setVisible","thisInstance","useMemo","element","makeItVisible","offset","getRef","useCallback","$03b515f3f8c77d8f$export$8ed7e1fb47d2eef9","addElement","removeElementFromList","$03b515f3f8c77d8f$var$elements","isInViewPort","top","left","window","innerHeight","innerWidth","calculateNewPosition","elem","getBoundingClientRect","push","isListenerAttached","requestAnimationFrame","eventHandler","length","removeScrollHandler","forEach","i","cancelAnimationFrame","toRemove","filter"],"version":3,"file":"index.js.map"}
package/package.json CHANGED
@@ -1,17 +1,22 @@
1
1
  {
2
2
  "name": "lazy-react",
3
- "version": "3.1.1",
3
+ "version": "3.4.0",
4
4
  "description": "components to lazy load iframes, images and images as backgrounds",
5
+ "source": "./src/index.tsx",
5
6
  "main": "./dist/index.js",
6
7
  "scripts": {
7
- "build:release": "webpack",
8
- "build:demo": "webpack --config webpack.config.demo.js",
9
- "build": "npm run build:release && npm run build:demo",
10
8
  "lint": "eslint src/*",
11
9
  "lint:fix": "eslint --fix src/*",
12
- "prettify": "prettier --write --single-quote --no-semi ./src/*.js",
10
+ "format": "prettier --write --single-quote --no-semi ./src/*.tsx",
13
11
  "precommit": "lint-staged",
14
- "test": "jest"
12
+ "test": "jest",
13
+ "build": "parcel build",
14
+ "serve": "parcel serve ./src/demo/index.html --dist-dir ./demo"
15
+ },
16
+ "targets": {
17
+ "main": {
18
+ "optimize": true
19
+ }
15
20
  },
16
21
  "lint-staged": {
17
22
  "src/*.js": [
@@ -30,26 +35,19 @@
30
35
  "url": "https://github.com/jonathanobino/react-lazy"
31
36
  },
32
37
  "devDependencies": {
33
- "@babel/core": "^7.11.6",
34
- "@babel/plugin-proposal-object-rest-spread": "^7.11.0",
35
- "@babel/preset-env": "^7.11.5",
36
- "@babel/preset-react": "^7.10.4",
37
- "@types/jest": "^27.4.0",
38
- "babel-cli": "^6.26.0",
39
- "babel-loader": "^8.1.0",
40
- "babel-plugin-transform-object-rest-spread": "^6.26.0",
38
+ "@testing-library/react": "^12.1.4",
39
+ "@types/jest": "^27.4.1",
40
+ "@types/node": "^17.0.21",
41
+ "@types/react": "^17.0.43",
42
+ "@types/react-dom": "^17.0.14",
41
43
  "eslint": "^7.10.0",
42
44
  "eslint-plugin-react": "^7.21.3",
43
45
  "husky": "^4.3.0",
44
46
  "jest": "^27.5.1",
45
47
  "lint-staged": "^10.4.0",
48
+ "parcel": "^2.6.2",
46
49
  "prettier": "^2.1.2",
47
- "webpack": "^5.66.0",
48
- "webpack-cli": "^4.9.1"
49
- },
50
- "dependencies": {
51
- "react": "^17.0.2",
52
- "react-dom": "^17.0.2"
50
+ "process": "^0.11.10"
53
51
  },
54
52
  "peerDependencies": {
55
53
  "react": "^17.0.2",
@@ -0,0 +1,39 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Demo</title>
5
+ <style type="text/css">
6
+ body{
7
+ margin: 0;
8
+ padding: 0;
9
+ max-width: 100vw;
10
+ min-height: 110vh;
11
+ }
12
+ img{
13
+ max-height: 100vh;
14
+ max-width: 100vw;
15
+ margin: 0 auto;
16
+ display: block;
17
+ }
18
+ h2{
19
+ font-family: sans-serif;
20
+ text-align: center;
21
+ }
22
+ .fill{
23
+ width: 100vw;
24
+ height: 100vh;
25
+ background-size: cover;
26
+ background-position: center center;
27
+ }
28
+ .styledImage{
29
+ height: 500px;
30
+ border: 10px solid tomato;
31
+ box-sizing: border-box;
32
+ }
33
+ </style>
34
+ </head>
35
+ <body>
36
+ <div id="app"></div>
37
+ <script type="module" src="index.js"></script>
38
+ </body>
39
+ </html>
@@ -1,6 +1,6 @@
1
1
  import React, {Component} from 'react'
2
2
  import ReactDOM from 'react-dom'
3
- import {LazyImage, LazyBackgroundImage, LazyFrame, LazyComponent} from '../dist'
3
+ import {LazyImage, LazyBackgroundImage, LazyFrame, LazyComponent} from '../../dist'
4
4
 
5
5
 
6
6
  function Experimental (props){
@@ -9,7 +9,7 @@ function Experimental (props){
9
9
 
10
10
  class Demo extends Component {
11
11
  constructor(props) {
12
- super(props)
12
+ super(props);
13
13
  }
14
14
 
15
15
  render() {
@@ -2,12 +2,6 @@ import LazyBackgroundImage from './lazyLoadBackgroundImage'
2
2
  import LazyImage from './lazyLoadImage'
3
3
  import LazyFrame from './lazyLoadFrame'
4
4
  import LazyComponent from './lazyLoadComponent'
5
- import useRenderIfInViewPort from './baseClass'
6
5
 
7
- export {
8
- LazyBackgroundImage,
9
- LazyImage,
10
- LazyFrame,
11
- LazyComponent,
12
- useRenderIfInViewPort,
13
- }
6
+ export { default } from './useIsInViewport'
7
+ export { LazyBackgroundImage, LazyImage, LazyFrame, LazyComponent }
@@ -0,0 +1,30 @@
1
+ import React, { useState, useEffect } from 'react' // eslint-disable-line no-unused-vars
2
+ import useIsInViewPort from './index'
3
+
4
+ export default function LazyBackgroundImage(props: any) {
5
+ let [setRef, link, isViewable] = useIsInViewPort(props)
6
+
7
+ const [style, setStyle] = useState({
8
+ backgroundImage: `url(${link})`,
9
+ ...props.style,
10
+ })
11
+
12
+ useEffect(() => {
13
+ setStyle({
14
+ backgroundImage: `url(${link})`,
15
+ ...props.style,
16
+ })
17
+ }, [link, isViewable])
18
+
19
+ return (
20
+ <div
21
+ className={props.className}
22
+ style={style}
23
+ ref={(node) => {
24
+ setRef(node)
25
+ }}
26
+ >
27
+ {props.children}
28
+ </div>
29
+ )
30
+ }
@@ -0,0 +1,22 @@
1
+ import React from 'react'
2
+ import useIsInViewport from './index'
3
+
4
+ export default function LazyComponent(props: any) {
5
+ const [setRef, link, isVisible] = useIsInViewport(props)
6
+
7
+ if (!isVisible)
8
+ return (
9
+ <div
10
+ ref={(node) => {
11
+ setRef(node)
12
+ }}
13
+ style={{
14
+ height: '300px',
15
+ width: '300px',
16
+ ...props.style,
17
+ }}
18
+ ></div>
19
+ )
20
+
21
+ return <div>{props.children}</div>
22
+ }
@@ -0,0 +1,21 @@
1
+ import React from 'react' // eslint-disable-line no-unused-vars
2
+ import useIsInViewPort from './index'
3
+
4
+ export default function LazyFrame(props: any) {
5
+ let [setRef, link] = useIsInViewPort(props)
6
+
7
+ return (
8
+ <iframe
9
+ height={props.height || '500'}
10
+ scrolling={props.scrolling || 'no'}
11
+ src={link}
12
+ frameBorder={props.frameBorder || 'no'}
13
+ allowFullScreen={props.allowFullScreen || true}
14
+ style={props.style || {}}
15
+ ref={(node) => {
16
+ setRef(node)
17
+ }}
18
+ {...props}
19
+ />
20
+ )
21
+ }
@@ -0,0 +1,21 @@
1
+ import React from 'react' // eslint-disable-line no-unused-vars
2
+ import useIsInViewPort from './index'
3
+
4
+ export default function LazyImage(props: any) {
5
+ const [setRef, link] = useIsInViewPort(props)
6
+
7
+ return (
8
+ <div
9
+ ref={(node) => {
10
+ setRef(node)
11
+ }}
12
+ >
13
+ <img
14
+ src={link}
15
+ alt={props.alt}
16
+ style={props.style}
17
+ className={props.className}
18
+ />
19
+ </div>
20
+ )
21
+ }
@@ -0,0 +1,119 @@
1
+ import React, { useState, useEffect, useMemo, useCallback } from 'react' // eslint-disable-line no-unused-vars
2
+
3
+ interface InstanceElement {
4
+ makeItVisible: () => void
5
+ element: HTMLElement | null
6
+ offset: number
7
+ }
8
+
9
+ export default function useRenderIfInViewPort(props: {
10
+ link: string
11
+ offset: number
12
+ }): [Function, string, boolean] {
13
+ const [link, setLink] = useState('')
14
+ const [visible, setVisible] = useState(false)
15
+
16
+ let [ref, setRef] = useState(null)
17
+
18
+ const thisInstance = useMemo(() => {
19
+ return {
20
+ element: ref,
21
+ makeItVisible,
22
+ offset: props.offset || 100,
23
+ }
24
+ }, [ref, props])
25
+
26
+ const getRef = useCallback((node) => {
27
+ if (node !== null) setRef(node)
28
+ }, [])
29
+
30
+ function makeItVisible() {
31
+ if(props.link)
32
+ setLink(() => props.link)
33
+ setVisible(() => true)
34
+ }
35
+
36
+ useEffect(() => {
37
+ if (ref !== null)
38
+ // add the element to the array of elements that are waiting to be lazy loaded
39
+ CheckIfRender.addElement(thisInstance)
40
+ return () =>
41
+ // if the element is unloaded remove the element from the list of elements that needs to be lazy loader
42
+ CheckIfRender.removeElementFromList(thisInstance)
43
+ }, [ref])
44
+
45
+ return [getRef, link, visible]
46
+ }
47
+
48
+ // array with all the elements that are waiting to be shown in the viewport
49
+ let elements: InstanceElement[] = []
50
+
51
+ const CheckIfRender = {
52
+ // top: the position of the element in relation with the top of the browser
53
+ // left: the position of the element in relation with the left of the browser
54
+ // offset: the desired offset of the element in relation of the viewport
55
+ isInViewPort: ({
56
+ offset,
57
+ top,
58
+ left,
59
+ }: {
60
+ offset: number
61
+ top: number
62
+ left: number
63
+ }) => top < window.innerHeight + offset && left < window.innerWidth + offset,
64
+
65
+ calculateNewPosition: (elem: InstanceElement) => {
66
+ const { top, left } = elem.element?.getBoundingClientRect() || {
67
+ top: 0,
68
+ left: 0,
69
+ }
70
+
71
+ return {
72
+ ...elem,
73
+ top,
74
+ left,
75
+ }
76
+ },
77
+ addElement: function (element: InstanceElement) {
78
+ //the distance from the pixel 0,0 and the top of the element
79
+ elements.push(element)
80
+ //check if has already been started the rAF cycle
81
+ if (CheckIfRender.isListenerAttached === 0) {
82
+ CheckIfRender.isListenerAttached = window.requestAnimationFrame(
83
+ CheckIfRender.eventHandler
84
+ )
85
+ }
86
+ },
87
+ eventHandler: function () {
88
+ //if there is no more element to lazy load remove the listener/rAF
89
+ if (elements.length === 0) {
90
+ CheckIfRender.removeScrollHandler()
91
+ } else {
92
+ elements.forEach((elem, i) => {
93
+ const haveToShow = CheckIfRender.isInViewPort(
94
+ CheckIfRender.calculateNewPosition(elem)
95
+ )
96
+ if (haveToShow) {
97
+ elem.makeItVisible()
98
+ // remove element from the list of elements to lazy load
99
+ CheckIfRender.removeElementFromList(elem)
100
+ }
101
+ })
102
+ CheckIfRender.isListenerAttached = window.requestAnimationFrame(
103
+ CheckIfRender.eventHandler
104
+ )
105
+ }
106
+ },
107
+
108
+ removeScrollHandler: function () {
109
+ window.cancelAnimationFrame(CheckIfRender.isListenerAttached)
110
+ CheckIfRender.isListenerAttached = 0
111
+ },
112
+ //When an element is unloaded remove it from the list of elements that are waiting to be lazy-loaded
113
+ removeElementFromList: function (toRemove: InstanceElement) {
114
+ elements = elements.filter((elem) => elem !== toRemove)
115
+ },
116
+ isListenerAttached: 0, // intended as not set
117
+ }
118
+
119
+ export { CheckIfRender }
package/.babelrc DELETED
@@ -1,6 +0,0 @@
1
- {
2
- "presets": ["@babel/preset-env", "@babel/preset-react"],
3
- "plugins": [
4
- ["@babel/plugin-proposal-object-rest-spread", { "loose": true, "useBuiltIns": true }]
5
- ]
6
- }