@bentoo/react-lazy 0.2.1 → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Manuel Bento
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,66 +1,154 @@
1
-
2
1
  # @bentoo/react-lazy
3
2
 
4
- Uma biblioteca para facilitar o a implementação de Lazy Loading com React.
3
+ A lightweight and flexible **React lazy loading library**.
4
+ Load components or images **only when they enter the viewport**, improving performance, reducing initial bundle size, and providing optional callbacks when elements become visible.
5
5
 
6
- ## Instalação
6
+ [![Version](https://img.shields.io/npm/v/@bentoo/react-lazy?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/@bentoo/react-lazy)
7
+ [![Downloads](https://img.shields.io/npm/dt/@bentoo/react-lazy.svg?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/@bentoo/react-lazy)
8
+ [![License](https://img.shields.io/npm/l/@bentoo/react-lazy.svg?style=flat&colorA=000000&colorB=000000)](LICENSE)
7
9
 
8
- Você pode instalar o pacote via NPM:
10
+ ---
9
11
 
10
- ```bash
11
- npm install @bentoo/react-lazy
12
- ```
13
- ou via Yarn:
12
+ ## Features
13
+
14
+ - Lazy load **any component or element** in React.
15
+ - Optional **fallback content** while loading.
16
+ - Callback support when an element becomes visible.
17
+ - Works with **Next.js**, **React 18**, and **TypeScript**.
18
+ - Lightweight, fully typed, and tree-shakable.
19
+
20
+ ---
21
+
22
+ ## Installation
14
23
 
15
24
  ```bash
25
+ npm install @bentoo/react-lazy
26
+ # or
16
27
  yarn add @bentoo/react-lazy
17
- ```
18
- ou via pnpm
19
- ```bash
28
+ # or
20
29
  pnpm add @bentoo/react-lazy
21
- ```
30
+ ````
31
+
32
+ ---
33
+
34
+ ## Usage
22
35
 
23
- ## Uso
36
+ ### 1. LazyComponent
24
37
 
25
- Aqui está um exemplo básico de como usar o `@bentoo/react-lazy` em seu projeto:
38
+ Lazy load any React component with a fallback:
26
39
 
27
40
  ```tsx
28
41
  import React from 'react';
29
42
  import { LazyComponent } from '@bentoo/react-lazy';
30
43
 
31
- const App = () => {
44
+ export default function App() {
32
45
  return (
33
46
  <div>
34
- <h1>My image</h1>
35
- <LazyComponent fallback={<h1>Loading...</h1>}>
36
- <img src='/myPicture.png' alt='MyPicture'/>
37
- </LazyComponent>
47
+ <h1>My content</h1>
48
+ <LazyComponent fallback={<h2>Loading...</h2>}>
49
+ <img src="/myPicture.png" alt="MyPicture" />
50
+ </LazyComponent>
38
51
  </div>
39
52
  );
40
- };
53
+ }
54
+ ```
55
+
56
+ **Props**:
57
+
58
+ | Prop | Type | Description |
59
+ | ---------- | ----------- | ----------------------------------- |
60
+ | `children` | `ReactNode` | Content to display after lazy load. |
61
+ | `fallback` | `ReactNode` | Content displayed while loading. |
62
+
63
+ ---
64
+
65
+ ### 2. LazyImage
66
+
67
+ Lazy load images with optional **placeholder, blur, fade-in, and Next.js support**:
41
68
 
42
- export default App;
69
+ ```tsx
70
+ import { LazyImage } from '@bentoo/react-lazy';
71
+ // For Next.js, pass ImageComponent={NextImage}
72
+
73
+ <LazyImage
74
+ src="/photo.jpg"
75
+ alt="My Photo"
76
+ width={600}
77
+ height={400}
78
+ placeholder="/photo-low.jpg"
79
+ blur
80
+ />
81
+ ```
82
+
83
+ **Props**:
84
+
85
+ | Prop | Type | Description |
86
+ | ---------------- | ----------------- | --------------------------------------- |
87
+ | `src` | `string` | Image source |
88
+ | `alt` | `string` | Image alt text |
89
+ | `width`/`height` | `number` | Optional width/height |
90
+ | `placeholder` | `string` | Low-res placeholder for blur effect |
91
+ | `blur` | `boolean` | Apply blur to placeholder |
92
+ | `ImageComponent` | `React Component` | Optional (pass `next/image` in Next.js) |
93
+
94
+ ---
95
+
96
+ ### 3. Lazy with Callback
97
+
98
+ Trigger a function when an element enters the viewport:
99
+
100
+ ```tsx
101
+ import { useLazyCallback } from '@bentoo/react-lazy';
102
+
103
+ export default function Section() {
104
+ const { ref } = useLazyCallback({
105
+ onVisible: () => console.log('Element is now visible!'),
106
+ triggerOnce: true
107
+ });
108
+
109
+ return <div ref={ref}>Watch me appear!</div>;
110
+ }
111
+ ```
112
+
113
+ ---
114
+
115
+ ## Next.js Example
116
+
117
+ ```tsx
118
+ import Image from 'next/image';
119
+ import { LazyImage } from '@bentoo/react-lazy';
120
+
121
+ export default function NextApp() {
122
+ return (
123
+ <LazyImage
124
+ ImageComponent={Image}
125
+ src="/photo.jpg"
126
+ alt="Next.js Image"
127
+ width={600}
128
+ height={400}
129
+ placeholder="/photo-low.jpg"
130
+ blur
131
+ />
132
+ );
133
+ }
43
134
  ```
44
135
 
45
- ### Propriedades
136
+ > Note: `next/image` already supports lazy loading, but `LazyImage` adds viewport-triggered effects and callbacks.
46
137
 
47
- `LazyComponent` aceita as seguintes propriedades:
138
+ ---
48
139
 
49
- | Propriedade | Tipo | Descrição |
50
- |-------------|-----------|-------------------------------|
51
- | `fallback` | `ReactNode` | O conteúdo a ser exibido enquanto o componente está sendo carregado.|
52
- |children | `ReactNode` | O conteúdo que será exibido após o carregamento.|
140
+ ## Contribution
53
141
 
54
- ## Contribuição
142
+ We welcome contributions!
55
143
 
56
- Se você deseja contribuir, fique à vontade para abrir um pull request ou reportar um problema.
144
+ 1. Fork the repository
145
+ 2. Create a feature branch (`git checkout -b my-feature`)
146
+ 3. Commit your changes (`git commit -m 'Add feature'`)
147
+ 4. Push to the branch (`git push origin my-feature`)
148
+ 5. Open a Pull Request
57
149
 
58
- 1. Faça um fork do projeto.
59
- 2. Crie sua feature branch (`git checkout -b minha-nova-funcionalidade`).
60
- 3. Commit suas mudanças (`git commit -m 'Adicionando nova funcionalidade'`).
61
- 4. Faça um push para a branch (`git push origin minha-nova-funcionalidade`).
62
- 5. Abra um Pull Request.
150
+ ---
63
151
 
64
- ## Licença
152
+ ## License
65
153
 
66
- Este projeto está licenciado sob a MIT License. Veja o arquivo [LICENSE](LICENSE) para mais detalhes.
154
+ MIT License see the [LICENSE](LICENSE) file for details.
@@ -1,7 +1,10 @@
1
1
  import { default as React } from 'react';
2
- interface LazyComponentProps {
2
+ import { LazyProps } from '../hooks';
3
+ type LazyComponentProps = LazyProps & {
3
4
  children: React.ReactNode;
4
- fallback: React.ReactNode;
5
- }
6
- export default function LazyComponent({ fallback, children }: LazyComponentProps): import("react/jsx-runtime").JSX.Element;
5
+ fallback?: React.ReactNode;
6
+ className?: string;
7
+ style?: React.CSSProperties;
8
+ };
9
+ export declare function LazyComponent({ children, fallback, className, style, root, rootMargin, threshold, triggerOnce }: LazyComponentProps): import("react/jsx-runtime").JSX.Element;
7
10
  export {};
@@ -0,0 +1,13 @@
1
+ import { default as React, ElementType } from 'react';
2
+ type LazyImageProps = {
3
+ src: string;
4
+ alt: string;
5
+ placeholder?: string;
6
+ blur?: boolean;
7
+ width?: number;
8
+ height?: number;
9
+ ImageComponent?: ElementType;
10
+ fadeInDuration?: number;
11
+ } & Omit<React.ImgHTMLAttributes<HTMLImageElement>, "src" | "alt">;
12
+ export declare function LazyImage({ src, alt, placeholder, blur, fadeInDuration, width, height, style, ImageComponent, ...rest }: LazyImageProps): import("react/jsx-runtime").JSX.Element;
13
+ export {};
@@ -1 +1,3 @@
1
- export { default as LazyComponent } from './container';
1
+ export { LazyComponent } from './container';
2
+ export { LazySuspense } from './suspense';
3
+ export { LazyImage } from './image';
@@ -0,0 +1,7 @@
1
+ import { default as React } from 'react';
2
+ type LazySuspenseProps = {
3
+ children: React.ReactNode;
4
+ fallback?: React.ReactNode;
5
+ };
6
+ export declare function LazySuspense({ children, fallback }: LazySuspenseProps): import("react/jsx-runtime").JSX.Element;
7
+ export {};
@@ -0,0 +1,2 @@
1
+ export * from './useLazy';
2
+ export * from './useLazyCallback';
@@ -0,0 +1,10 @@
1
+ type Props = {
2
+ src: string;
3
+ visible: boolean;
4
+ };
5
+ export declare const useImage: ({ src, visible }: Props) => {
6
+ handleLoad: () => void;
7
+ loaded: boolean;
8
+ shouldLoad: boolean;
9
+ };
10
+ export {};
@@ -0,0 +1,10 @@
1
+ export type LazyProps = {
2
+ root?: Element | null;
3
+ rootMargin?: string;
4
+ threshold?: number | number[];
5
+ triggerOnce?: boolean;
6
+ };
7
+ export declare const useLazy: <T extends HTMLElement>({ root, rootMargin, threshold, triggerOnce }: LazyProps) => {
8
+ ref: import('react').RefObject<T | null>;
9
+ visible: boolean;
10
+ };
@@ -0,0 +1,7 @@
1
+ import { LazyProps } from './useLazy';
2
+ export type LazyCallbackProps = LazyProps & {
3
+ onVisible: () => void;
4
+ };
5
+ export declare const useLazyCallback: <T extends HTMLElement>({ onVisible, root, rootMargin, threshold, triggerOnce }: LazyCallbackProps) => {
6
+ ref: import('react').RefObject<T | null>;
7
+ };
@@ -0,0 +1,6 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("react");var g={exports:{}},y={};var W;function te(){if(W)return y;W=1;var t=Symbol.for("react.transitional.element"),s=Symbol.for("react.fragment");function c(u,n,a){var i=null;if(a!==void 0&&(i=""+a),n.key!==void 0&&(i=""+n.key),"key"in n){a={};for(var l in n)l!=="key"&&(a[l]=n[l])}else a=n;return n=a.ref,{$$typeof:t,type:u,key:i,ref:n!==void 0?n:null,props:a}}return y.Fragment=s,y.jsx=c,y.jsxs=c,y}var k={};var M;function ne(){return M||(M=1,process.env.NODE_ENV!=="production"&&(function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===K?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case A:return"Fragment";case J:return"Profiler";case q:return"StrictMode";case B:return"Suspense";case H:return"SuspenseList";case Q:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case w:return"Portal";case G:return e.displayName||"Context";case V:return(e._context.displayName||"Context")+".Consumer";case X:var r=e.render;return e=e.displayName,e||(e=r.displayName||r.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Z:return r=e.displayName||null,r!==null?r:t(e.type)||"Memo";case P:r=e._payload,e=e._init;try{return t(e(r))}catch{}}return null}function s(e){return""+e}function c(e){try{s(e);var r=!1}catch{r=!0}if(r){r=console;var o=r.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return o.call(r,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),s(e)}}function u(e){if(e===A)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===P)return"<...>";try{var r=t(e);return r?"<"+r+">":"<...>"}catch{return"<...>"}}function n(){var e=h.A;return e===null?null:e.getOwner()}function a(){return Error("react-stack-top-frame")}function i(e){if(I.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function l(e,r){function o(){Y||(Y=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",r))}o.isReactWarning=!0,Object.defineProperty(e,"key",{get:o,configurable:!0})}function m(){var e=t(this.type);return $[e]||($[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function v(e,r,o,f,j,L){var d=o.ref;return e={$$typeof:T,type:e,key:r,props:o,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:m}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:j}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:L}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function S(e,r,o,f,j,L){var d=r.children;if(d!==void 0)if(f)if(ee(d)){for(f=0;f<d.length;f++)x(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else x(d);if(I.call(r,"key")){d=t(e);var R=Object.keys(r).filter(function(re){return re!=="key"});f=0<R.length?"{key: someKey, "+R.join(": ..., ")+": ...}":"{key: someKey}",D[d+f]||(R=0<R.length?"{"+R.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
+ let props = %s;
3
+ <%s {...props} />
4
+ React keys must be passed directly to JSX without using spread:
5
+ let props = %s;
6
+ <%s key={someKey} {...props} />`,f,d,R,d),D[d+f]=!0)}if(d=null,o!==void 0&&(c(o),d=""+o),i(r)&&(c(r.key),d=""+r.key),"key"in r){o={};for(var C in r)C!=="key"&&(o[C]=r[C])}else o=r;return d&&l(o,typeof e=="function"?e.displayName||e.name||"Unknown":e),v(e,d,o,n(),j,L)}function x(e){p(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===P&&(e._payload.status==="fulfilled"?p(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function p(e){return typeof e=="object"&&e!==null&&e.$$typeof===T}var E=b,T=Symbol.for("react.transitional.element"),w=Symbol.for("react.portal"),A=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),J=Symbol.for("react.profiler"),V=Symbol.for("react.consumer"),G=Symbol.for("react.context"),X=Symbol.for("react.forward_ref"),B=Symbol.for("react.suspense"),H=Symbol.for("react.suspense_list"),Z=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),Q=Symbol.for("react.activity"),K=Symbol.for("react.client.reference"),h=E.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,I=Object.prototype.hasOwnProperty,ee=Array.isArray,N=console.createTask?console.createTask:function(){return null};E={react_stack_bottom_frame:function(e){return e()}};var Y,$={},z=E.react_stack_bottom_frame.bind(E,a)(),F=N(u(a)),D={};k.Fragment=A,k.jsx=function(e,r,o){var f=1e4>h.recentlyCreatedOwnerStacks++;return S(e,r,o,!1,f?Error("react-stack-top-frame"):z,f?N(u(e)):F)},k.jsxs=function(e,r,o){var f=1e4>h.recentlyCreatedOwnerStacks++;return S(e,r,o,!0,f?Error("react-stack-top-frame"):z,f?N(u(e)):F)}})()),k}var U;function ae(){return U||(U=1,process.env.NODE_ENV==="production"?g.exports=te():g.exports=ne()),g.exports}var _=ae();const O=({root:t=null,rootMargin:s="0px",threshold:c=.1,triggerOnce:u=!0})=>{const n=b.useRef(null),[a,i]=b.useState(!1);return b.useEffect(()=>{const l=n.current;if(!l)return;const m=new IntersectionObserver(([v])=>{v.isIntersecting?(i(!0),u&&m.unobserve(v.target)):u||i(!1)},{root:t,rootMargin:s,threshold:c});return m.observe(l),()=>{m.unobserve(l),m.disconnect()}},[t,s,c,u]),{ref:n,visible:a}},oe=({onVisible:t,root:s=null,rootMargin:c="0px",threshold:u=.1,triggerOnce:n=!0})=>{const a=b.useRef(null),i=b.useRef(!1);return b.useEffect(()=>{const l=a.current;if(!l)return;const m=new IntersectionObserver(([v])=>{v.isIntersecting&&((!i.current||!n)&&(t(),i.current=!0),n&&m.unobserve(v.target))},{root:s,rootMargin:c,threshold:u});return m.observe(l),()=>{m.unobserve(l),m.disconnect()}},[t,s,c,u,n]),{ref:a}};function se({children:t,fallback:s=null,className:c,style:u,root:n,rootMargin:a,threshold:i,triggerOnce:l}){const{ref:m,visible:v}=O({root:n,rootMargin:a,threshold:i,triggerOnce:l});return _.jsx("div",{ref:m,className:c,style:u,children:v?t:s})}function ue({children:t,fallback:s=null}){const{ref:c,visible:u}=O({});return _.jsx("div",{ref:c,children:u&&_.jsx(b.Suspense,{fallback:s,children:t})})}const le=({src:t,visible:s})=>{const[c,u]=b.useState(!1),[n,a]=b.useState(!1);function i(){a(!0)}return b.useEffect(()=>{if(!s||!t)return;const l=new Image;l.src=t,l.onload=()=>{u(!0)}},[s,t]),{handleLoad:i,loaded:n,shouldLoad:c}};function ce({src:t,alt:s,placeholder:c,blur:u=!1,fadeInDuration:n=300,width:a,height:i,style:l,ImageComponent:m="img",...v}){const{ref:S,visible:x}=O({}),{loaded:p,handleLoad:E,shouldLoad:T}=le({src:t,visible:x}),w=m!=="img";return _.jsxs("div",{style:{position:"relative",overflow:"hidden",width:a,height:i},children:[c&&!p&&_.jsx("img",{src:c,alt:s,"aria-hidden":!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",filter:u?"blur(20px)":"none",transform:u?"scale(1.1)":void 0}}),w?_.jsx(m,{src:T?t:"",alt:s,width:a,height:i,onLoad:E,style:{opacity:p?1:0,transition:`opacity ${n}ms ease`,...l},...v}):_.jsx("img",{ref:S,src:T?t:void 0,alt:s,loading:"lazy",width:a,height:i,onLoad:E,style:{opacity:p?1:0,transition:`opacity ${n}ms ease`,width:"100%",height:"100%",objectFit:"cover",display:"block",...l},...v})]})}exports.LazyComponent=se;exports.LazyImage=ce;exports.LazySuspense=ue;exports.useLazy=O;exports.useLazyCallback=oe;
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
1
  export * from './components';
2
+ export * from './hooks';