@bentoo/react-lazy 0.2.2 → 1.0.1

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/README.md CHANGED
@@ -1,71 +1,154 @@
1
-
2
1
  # @bentoo/react-lazy
3
2
 
4
- A library designed to make it easier to implement `Lazy Loading` in `React` applications. It allows components to load only when they become visible on the screen, providing a way to monitor the entry of elements into the viewport.
5
-
6
- With this tool, you can improve the performance of your application by reducing the initial loading time and ensuring that `only the necessary elements are loaded`. This approach contributes to a more agile and responsive user experience.
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.
7
5
 
8
- ## Installation
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)
9
9
 
10
- You can install the package via NPM:
10
+ ---
11
11
 
12
- ```bash
13
- npm install @bentoo/react-lazy
14
- ```
12
+ ## Features
15
13
 
16
- or via Yarn:
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.
17
19
 
18
- ```bash
19
- yarn add @bentoo/react-lazy
20
- ```
20
+ ---
21
21
 
22
- or via pnpm:
22
+ ## Installation
23
23
 
24
24
  ```bash
25
+ npm install @bentoo/react-lazy
26
+ # or
27
+ yarn add @bentoo/react-lazy
28
+ # or
25
29
  pnpm add @bentoo/react-lazy
26
- ```
30
+ ````
31
+
32
+ ---
27
33
 
28
34
  ## Usage
29
35
 
30
- Here’s a basic example of how to use `@bentoo/react-lazy` in your project:
36
+ ### 1. LazyComponent
37
+
38
+ Lazy load any React component with a fallback:
31
39
 
32
40
  ```tsx
33
41
  import React from 'react';
34
42
  import { LazyComponent } from '@bentoo/react-lazy';
35
43
 
36
- const App = () => {
44
+ export default function App() {
37
45
  return (
38
46
  <div>
39
- <h1>My image</h1>
40
- <LazyComponent fallback={<h1>Loading...</h1>}>
41
- <img src='/myPicture.png' alt='MyPicture'/>
42
- </LazyComponent>
47
+ <h1>My content</h1>
48
+ <LazyComponent fallback={<h2>Loading...</h2>}>
49
+ <img src="/myPicture.png" alt="MyPicture" />
50
+ </LazyComponent>
43
51
  </div>
44
52
  );
45
- };
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
46
66
 
47
- export default App;
67
+ Lazy load images with optional **placeholder, blur, fade-in, and Next.js support**:
68
+
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
+ }
48
111
  ```
49
112
 
50
- ### Props
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
+ }
134
+ ```
51
135
 
52
- `LazyComponent` accepts the following props:
136
+ > Note: `next/image` already supports lazy loading, but `LazyImage` adds viewport-triggered effects and callbacks.
53
137
 
54
- | Prop | Type | Description |
55
- |-------------|-------------|-------------------------------------------------------------------|
56
- | `fallback` | `ReactNode` | The content to display while the component is being loaded. |
57
- | `children` | `ReactNode` | The content that will be displayed after loading. |
138
+ ---
58
139
 
59
140
  ## Contribution
60
141
 
61
- If you would like to contribute, feel free to open a pull request or report an issue.
142
+ We welcome contributions!
143
+
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
62
149
 
63
- 1. Fork the project.
64
- 2. Create your feature branch (`git checkout -b my-new-feature`).
65
- 3. Commit your changes (`git commit -m 'Adding new feature'`).
66
- 4. Push to the branch (`git push origin my-new-feature`).
67
- 5. Open a Pull Request.
150
+ ---
68
151
 
69
152
  ## License
70
153
 
71
- This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.
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';