├── .babelrc
├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── demo
├── .gitignore
├── README.md
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── manifest.json
│ └── robots.txt
├── src
│ ├── App.tsx
│ ├── github.png
│ ├── index.css
│ ├── index.tsx
│ └── react-app-env.d.ts
├── tsconfig.json
└── yarn.lock
├── dist
├── esm
│ ├── components
│ │ ├── AnimationOnScroll.js
│ │ ├── AnimationOnScroll.js.map
│ │ ├── index.js
│ │ └── index.js.map
│ ├── index.js
│ └── index.js.map
├── js
│ ├── components
│ │ ├── AnimationOnScroll.d.ts
│ │ ├── AnimationOnScroll.js
│ │ ├── AnimationOnScroll.js.map
│ │ ├── index.d.ts
│ │ ├── index.js
│ │ └── index.js.map
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
└── umd
│ ├── components
│ ├── AnimationOnScroll.js
│ ├── AnimationOnScroll.js.map
│ ├── index.js
│ └── index.js.map
│ ├── index.js
│ └── index.js.map
├── package-lock.json
├── package.json
├── scripts
└── copyTS.js
├── src
├── components
│ ├── AnimationOnScroll.tsx
│ └── index.ts
└── index.tsx
├── tsconfig.gen-dts.json
├── tsconfig.json
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["@babel/react", ["@babel/preset-typescript", {"allowNamespaces": true}]],
3 | "ignore": ["**/__snapshots__", "**/*.d.ts", "**/*.test.*"],
4 | "plugins": [
5 | "@babel/plugin-transform-typescript",
6 | "@babel/plugin-proposal-export-default-from",
7 | "@babel/proposal-class-properties",
8 | "@babel/proposal-object-rest-spread"
9 | ]
10 | }
11 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | build
2 | node_modules
3 | dist/**/demos
4 | dist/**/examples
5 | dist/**/__snapshots__
6 | dist/**/*.test.js
7 | dist/**/*.map
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 MetinArslanturk
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.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React Animation On Scroll
2 |
3 | React component to animate elements on scroll with [animate.css](https://daneden.github.io/animate.css/).
4 | This library is re-implementation of [dbramwell/react-animate-on-scroll](https://github.com/dbramwell/react-animate-on-scroll).
5 | Re-implemented the old one with react functional components in TypeScript. Also added animate.css@4.0+ support.
6 | Supports server-side rendering and TypeScript.
7 |
8 | ## [Click to see Demo](https://www.metinarslanturk.com/react-animation-on-scroll)
9 |
10 | ## Install:
11 |
12 | ```
13 | npm install react-animation-on-scroll --save
14 | ```
15 |
16 | or
17 |
18 | ```
19 | yarn add react-animation-on-scroll
20 | ```
21 |
22 | **Please be sure to include animate.css (version 4 and higher) in someway in your project**
23 | This can be done in a number of ways, eg:
24 |
25 | ```
26 | npm install --save animate.css
27 | ```
28 |
29 | or
30 |
31 | ```
32 | yarn add animate.css
33 | ```
34 |
35 | and then importing in your project:
36 |
37 | ```
38 | import "animate.css/animate.min.css";
39 | ```
40 |
41 | Or by simply including a link to the file hosted by CDNJS:
42 |
43 | ```
44 |
45 |
46 |
47 | ```
48 |
49 | ## Most Simple Use:
50 |
51 | ```
52 | import { AnimationOnScroll } from 'react-animation-on-scroll';
53 |
54 | Some Text
55 |
56 | ```
57 |
58 | ## Properties:
59 |
60 | **offset** - default 150
61 |
62 | The "viewport" is by default 150 pixels from the top and bottom of the screen. When part of an element is within the "viewport", animateIn is triggered. When no part of the element is in the "viewport", animateOut is triggered. This size of the "viewport" can be overridden by setting the offset property.
63 |
64 | **animateIn**
65 |
66 | Any css animation defined against a class, be it from [animate.css](https://daneden.github.io/animate.css/) or an animation that you have created yourself. The Animation triggers when the element enters the "viewport" (see offset property for more details on this).
67 |
68 | **animateOut**
69 |
70 | Any css animation defined against a class, be it from [animate.css](https://daneden.github.io/animate.css/) or an animation that you have created yourself. The Animation triggers when the element is leaving the "viewport" (see offset property for more details on this).
71 |
72 | **duration** - default 1
73 |
74 | Animation duration in seconds.
75 |
76 | **initiallyVisible** - default false
77 |
78 | Whether the element should be visible to begin with or not. Recomending to set true if you have got server-side rendering.
79 |
80 | **delay** - default 0
81 |
82 | How long to delay the animation for (in milliseconds) once it enters or leaves the view.
83 |
84 | **animateOnce** - default false
85 |
86 | Whether the element should only animate once or not.
87 |
88 | **style** - default {}
89 |
90 | A style object can be assigned to any ScrollAnimation component and will be passed to the rendered dom element. Its probably best to avoid manually setting animationDuration or opacity as the component will modify those attributes.
91 |
92 | **scrollableParentSelector**
93 |
94 | By default the code checks to see if the element is visible within the window. This can be changed to any other parent element of the ScrollAnimation by adding a css selector pointing to the parent that you wish to use.
95 |
96 | **afterAnimatedIn**
97 |
98 | Callback function to run once the animateIn animation has completed. Receives the visibility of the element at time of execution.
99 | Example:
100 |
101 | ```
102 | function(visible) {
103 | if (visible.inViewport) {
104 | // Part of the element is in the viewport (the area defined by the offset property)
105 | } else if (visible.onScreen) {
106 | // Part of the element is visible on the screen
107 | } else {
108 | // Element is no longer visible
109 | }
110 | }
111 | ```
112 |
113 | **afterAnimatedOut**
114 |
115 | Callback function to run once the animateOut animation has completed. Receives the visibility of the element at time of execution.
116 | Example:
117 |
118 | ```
119 | function(visible) {
120 | if (visible.inViewport) {
121 | // Part of the element is in the viewport (the area defined by the offset property)
122 | } else if (visible.onScreen) {
123 | // Part of the element is visible on the screen
124 | } else {
125 | // Element is no longer visible
126 | }
127 | }
128 | ```
129 |
130 | **animatePreScroll** - default true
131 |
132 | By default if a ScrollAnimation is in view as soon as a page loads, then the animation will begin. If you don't want the animation to being until the user scrolls, then set this to false.
133 |
134 | Please feel free to contribute or contact from contact@metinarslanturk.com
135 |
--------------------------------------------------------------------------------
/demo/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/demo/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `yarn start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13 |
14 | The page will reload if you make edits.\
15 | You will also see any lint errors in the console.
16 |
17 | ### `yarn test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `yarn build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `yarn eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35 |
36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39 |
40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
--------------------------------------------------------------------------------
/demo/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "demo",
3 | "version": "4.0.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^5.11.4",
7 | "@testing-library/react": "^11.1.0",
8 | "@testing-library/user-event": "^12.1.10",
9 | "@types/jest": "^26.0.15",
10 | "@types/node": "^12.0.0",
11 | "@types/react": "^16.9.53",
12 | "@types/react-dom": "^16.9.8",
13 | "animate.css": "^4.1.1",
14 | "bootstrap": "^4.5.3",
15 | "react": "^17.0.1",
16 | "react-animation-on-scroll": "^5.1.0",
17 | "react-bootstrap": "^1.4.3",
18 | "react-dom": "^17.0.1",
19 | "react-scripts": "4.0.1",
20 | "typescript": "^4.0.3",
21 | "web-vitals": "^0.2.4"
22 | },
23 | "homepage": "/react-animation-on-scroll",
24 | "scripts": {
25 | "start": "react-scripts start",
26 | "build": "react-scripts build",
27 | "test": "react-scripts test",
28 | "eject": "react-scripts eject"
29 | },
30 | "eslintConfig": {
31 | "extends": [
32 | "react-app",
33 | "react-app/jest"
34 | ]
35 | },
36 | "browserslist": {
37 | "production": [
38 | ">0.2%",
39 | "not dead",
40 | "not op_mini all"
41 | ],
42 | "development": [
43 | "last 1 chrome version",
44 | "last 1 firefox version",
45 | "last 1 safari version"
46 | ]
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/demo/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MetinArslanturk/react-animation-on-scroll/cde4e010d2caf10f5d07fd9828307837a0f852ec/demo/public/favicon.ico
--------------------------------------------------------------------------------
/demo/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
16 |
17 |
21 |
22 |
31 | React Animation On Scroll
32 |
33 |
34 | You need to enable JavaScript to run this app.
35 |
36 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/demo/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React Animation On Scroll",
3 | "name": "React Animation On Scroll",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/demo/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/demo/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { AnimationOnScroll } from 'react-animation-on-scroll';
3 | import { Card, Col, Container, Navbar, Row } from 'react-bootstrap';
4 | import github from './github.png';
5 |
6 | const App = () => {
7 | const [afterInState, setAfterInState] = useState(0);
8 | const [afterOutState, setAfterOutState] = useState(0);
9 |
10 | return (
11 | <>
12 |
13 | React Animation On Scroll
14 |
15 |
16 |
17 |
22 |
23 |
24 |
25 |
26 |
27 | Keep scroll to see demos
28 |
29 |
30 |
31 |
32 |
33 |
34 | Animate In
35 |
36 | Look what i am doing
37 |
38 |
39 |
40 | Look me too.
41 |
42 |
43 | {
44 |
45 | {``}
46 |
47 |
48 | {`
49 | Look what i am doing `}
50 |
51 | {`
52 | `}
53 |
54 | {``}
55 |
56 |
57 | {`
58 | Look me too. `}
59 |
60 | {`
61 | `}
62 |
63 | }
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 | Animate Out{' '}
80 |
81 | (Slowly scroll you will see the animate out)
82 |
83 |
84 |
88 | Look what i am doing
89 |
90 |
91 | {
92 |
93 | {``}
94 |
95 |
96 | {`
97 | Look what i am doing `}
98 |
99 | {`
100 | `}
101 |
102 | }
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 | Initially Visible
118 |
122 | Look what i am doing
123 |
124 |
125 | {
126 |
127 | {``}
128 |
129 |
130 | {`
131 | Look what i am doing `}
132 |
133 | {`
134 | `}
135 |
136 | }
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 | Duration
152 |
157 | Look what i am doing
158 |
159 |
160 | {
161 |
162 | {``}
163 |
164 |
165 | {`
166 | Look what i am doing `}
167 |
168 | {`
169 | `}
170 |
171 | }
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 | Delay Wait 2 seconds delay
188 |
189 |
194 | Look what i am doing
195 |
196 |
197 | {
198 |
199 | {``}
200 |
201 |
202 | {`
203 | Look what i am doing `}
204 |
205 | {`
206 | `}
207 |
208 | }
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 | Animate Once
224 |
228 | Look what i am doing
229 |
230 |
231 | {
232 |
233 | {``}
234 |
235 |
236 | {`
237 | Look what i am doing `}
238 |
239 | {`
240 | `}
241 |
242 | }
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 | scrollableParentSelector
258 |
259 |
260 |
Scroll me
261 |
266 | Look what i am doing
267 |
268 |
269 |
270 |
271 | {
272 |
273 | {``}
274 |
275 |
276 | {`
277 | Look what i am doing `}
278 |
279 | {`
280 | `}
281 |
282 | }
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 | afterAnimatedIn Counter: {afterInState}
298 |
299 | Counter increments with afterAnimatedIn function callback
300 |
301 |
302 | setAfterInState((c) => c + 1)}
306 | >
307 | Look what i am doing
308 |
309 |
310 | {
311 |
312 | {` setAfterInState((c) => c + 1)}>`}
313 |
314 |
315 | {`
316 | Look what i am doing `}
317 |
318 | {`
319 | `}
320 |
321 | }
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 | afterAnimatedOut Counter: {afterOutState}
337 |
338 | Counter increments with afterAnimatedOut function callback
339 |
340 |
341 | setAfterOutState((c) => c + 1)}
345 | >
346 | Look what i am doing
347 |
348 |
349 | {
350 |
351 | {` setAfterOutState((c) => c + 1)}>`}
352 |
353 |
354 | {`
355 | Look what i am doing `}
356 |
357 | {`
358 | `}
359 |
360 | }
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 | More
376 |
377 | animatePreScroll: If your target element in
378 | view on load but you don't want to trigger animate
379 | immediately. Then with animatePreScroll prop you can set
380 | animate trigger only on scrolling like{' '}
381 | {'animatePreScroll={false}'}
382 |
383 |
384 |
385 | This library is a react component to animate elements on
386 | scroll with{' '}
387 |
392 | animate.css
393 |
394 | . This library is re-implementation of{' '}
395 |
400 | dbramwell/react-animate-on-scroll
401 |
402 | . Re-implemented the old one with react functional
403 | components in TypeScript. Also added animate.css@4.0+
404 | support. Supports server-side rendering and TypeScript.
405 |
406 | Install:
407 |
408 | npm install react-animation-on-scroll --save
409 |
410 | or
411 | yarn add react-animation-on-scroll
412 |
413 |
414 |
415 | Please check{' '}
416 |
421 | GitHub
422 | {' '}
423 | for full documentation and info.
424 |
425 |
426 | If you have any question, please feel free to contact from{' '}
427 | contact@metinarslanturk.com
428 |
429 | Made with Love, Metin Arslantürk @ 2021
430 |
431 |
432 |
433 |
434 |
435 |
436 | >
437 | );
438 | };
439 |
440 | export default App;
441 |
--------------------------------------------------------------------------------
/demo/src/github.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MetinArslanturk/react-animation-on-scroll/cde4e010d2caf10f5d07fd9828307837a0f852ec/demo/src/github.png
--------------------------------------------------------------------------------
/demo/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
15 | .padding-top-5r {
16 | padding-top: 5rem;
17 | }
18 |
19 | .margin-top-0-5r {
20 | padding-top: 0.5rem;
21 | }
22 |
23 | .margin-top-2r {
24 | padding-top: 2rem;
25 | }
26 |
27 | .margin-top-4r {
28 | margin-top: 4rem;
29 | }
30 |
31 | .min-95vh {
32 | min-height: 95vh;
33 | }
34 |
35 | .gray-bg {
36 | background-color: #f0f0f0;
37 | }
38 |
39 | .padding-bottom-1r {
40 | padding-bottom: 1rem;
41 | }
42 |
43 | .center {
44 | display: flex;
45 | justify-content: center;
46 | align-items: center;
47 | }
48 |
49 | .direction-column {
50 | flex-direction: column;
51 | }
52 |
53 | .code {
54 | border: 1px solid #ccc;
55 | border-radius: 1.5rem;
56 | padding: 2rem;
57 | }
58 |
59 | #parent {
60 | height: 30rem;
61 | width: 80%;
62 | overflow-y: auto;
63 | padding-bottom: 10rem;
64 | }
65 |
66 | #child {
67 | height: 70rem;
68 | display: flex;
69 | flex-direction: column;
70 | justify-content: space-between;
71 | align-items: center;
72 | }
73 |
74 | .small-f {
75 | font-size: 1rem;
76 | }
77 |
--------------------------------------------------------------------------------
/demo/src/index.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import 'bootstrap/dist/css/bootstrap.min.css';
4 | import 'animate.css/animate.min.css';
5 | import './index.css';
6 | import App from './App';
7 |
8 | ReactDOM.render(
9 |
10 |
11 | ,
12 | document.getElementById('root')
13 | );
14 |
--------------------------------------------------------------------------------
/demo/src/react-app-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/demo/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "dom",
6 | "dom.iterable",
7 | "esnext"
8 | ],
9 | "allowJs": true,
10 | "skipLibCheck": true,
11 | "esModuleInterop": true,
12 | "allowSyntheticDefaultImports": true,
13 | "strict": true,
14 | "forceConsistentCasingInFileNames": true,
15 | "noFallthroughCasesInSwitch": true,
16 | "module": "esnext",
17 | "moduleResolution": "node",
18 | "resolveJsonModule": true,
19 | "isolatedModules": true,
20 | "noEmit": true,
21 | "jsx": "react-jsx"
22 | },
23 | "include": [
24 | "src"
25 | ]
26 | }
27 |
--------------------------------------------------------------------------------
/dist/esm/components/AnimationOnScroll.js:
--------------------------------------------------------------------------------
1 | import React, { useMemo, useCallback, useState, useEffect, useRef } from 'react';
2 | import throttle from 'lodash.throttle';
3 | const animatedClass = 'animate__animated';
4 | const serverSide = typeof window === 'undefined';
5 | let scrollableParentRefInitialValue = undefined;
6 |
7 | if (!serverSide) {
8 | scrollableParentRefInitialValue = window;
9 | }
10 |
11 | export const AnimationOnScroll = ({
12 | offset = 150,
13 | duration = 1,
14 | style: styleProps,
15 | className: classNameProps,
16 | initiallyVisible = false,
17 | animateIn,
18 | afterAnimatedIn,
19 | animateOut,
20 | delay = 0,
21 | animatePreScroll = true,
22 | afterAnimatedOut,
23 | scrollableParentSelector,
24 | animateOnce = false,
25 | children
26 | }) => {
27 | const [classes, setClasses] = useState(animatedClass);
28 | const [style, setStyle] = useState({
29 | animationDuration: `${duration}s`,
30 | opacity: initiallyVisible ? 1 : 0
31 | });
32 | const node = useRef(null);
33 | const animating = useRef(false);
34 | const visibilityRef = useRef({
35 | onScreen: false,
36 | inViewport: false
37 | });
38 | const delayedAnimationTORef = useRef(undefined);
39 | const callbackTORef = useRef(undefined);
40 | const scrollableParentRef = useRef(scrollableParentRefInitialValue);
41 | const getElementTop = useCallback(elm => {
42 | let yPos = 0;
43 |
44 | while (elm && elm.offsetTop !== undefined && elm.clientTop !== undefined) {
45 | yPos += elm.offsetTop + elm.clientTop;
46 | elm = elm.offsetParent;
47 | }
48 |
49 | return yPos;
50 | }, []);
51 | const getScrollPos = useCallback(() => {
52 | if (scrollableParentRef.current.pageYOffset !== undefined) {
53 | return scrollableParentRef.current.pageYOffset;
54 | }
55 |
56 | return scrollableParentRef.current.scrollTop;
57 | }, [scrollableParentRef]);
58 | const getScrollableParentHeight = useCallback(() => {
59 | if (scrollableParentRef.current.innerHeight !== undefined) {
60 | return scrollableParentRef.current.innerHeight;
61 | }
62 |
63 | return scrollableParentRef.current.clientHeight;
64 | }, [scrollableParentRef]);
65 | const getViewportTop = useCallback(() => {
66 | return getScrollPos() + offset;
67 | }, [offset, getScrollPos]);
68 | const getViewportBottom = useCallback(() => {
69 | return getScrollPos() + getScrollableParentHeight() - offset;
70 | }, [offset, getScrollPos, getScrollableParentHeight]);
71 | const isInViewport = useCallback(y => {
72 | return y >= getViewportTop() && y <= getViewportBottom();
73 | }, [getViewportTop, getViewportBottom]);
74 | const isAboveViewport = useCallback(y => {
75 | return y < getViewportTop();
76 | }, [getViewportTop]);
77 | const isBelowViewport = useCallback(y => {
78 | return y > getViewportBottom();
79 | }, [getViewportBottom]);
80 | const inViewport = useCallback((elementTop, elementBottom) => {
81 | return isInViewport(elementTop) || isInViewport(elementBottom) || isAboveViewport(elementTop) && isBelowViewport(elementBottom);
82 | }, [isInViewport, isAboveViewport, isBelowViewport]);
83 | const isAboveScreen = useCallback(y => {
84 | return y < getScrollPos();
85 | }, [getScrollPos]);
86 | const isBelowScreen = useCallback(y => {
87 | return y > getScrollPos() + getScrollableParentHeight();
88 | }, [getScrollPos, getScrollableParentHeight]);
89 | const onScreen = useCallback((elementTop, elementBottom) => {
90 | return !isAboveScreen(elementBottom) && !isBelowScreen(elementTop);
91 | }, [isAboveScreen, isBelowScreen]);
92 | const getVisibility = useCallback(() => {
93 | const elementTop = getElementTop(node.current) - getElementTop(scrollableParentRef.current);
94 | const elementBottom = elementTop + node.current.clientHeight;
95 | return {
96 | inViewport: inViewport(elementTop, elementBottom),
97 | onScreen: onScreen(elementTop, elementBottom)
98 | };
99 | }, [getElementTop, node, inViewport, onScreen, scrollableParentRef]);
100 | const visibilityHasChanged = useCallback((previousVis, currentVis) => {
101 | return previousVis.inViewport !== currentVis.inViewport || previousVis.onScreen !== currentVis.onScreen;
102 | }, []);
103 | const animate = useCallback((animation, callback) => {
104 | delayedAnimationTORef.current = setTimeout(() => {
105 | animating.current = true;
106 | setClasses(`${animatedClass} ${animation}`);
107 | setStyle({
108 | animationDuration: `${duration}s`
109 | });
110 | callbackTORef.current = setTimeout(callback, duration * 1000);
111 | }, delay);
112 | }, [animating, delay, duration]);
113 | const animateInTrigger = useCallback(callback => {
114 | animate(animateIn, () => {
115 | if (!animateOnce) {
116 | setStyle({
117 | animationDuration: `${duration}s`,
118 | opacity: 1
119 | });
120 | animating.current = false;
121 | }
122 |
123 | const vis = getVisibility();
124 |
125 | if (callback) {
126 | callback(vis);
127 | }
128 | });
129 | }, [animating, animateIn, animateOnce, duration, animate, getVisibility]);
130 | const animateOutTrigger = useCallback(callback => {
131 | animate(animateOut, () => {
132 | setClasses(animatedClass);
133 | setStyle({
134 | animationDuration: `${duration}s`,
135 | opacity: 0
136 | });
137 | const vis = getVisibility();
138 |
139 | if (vis.inViewport && animateIn) {
140 | animateInTrigger(afterAnimatedIn);
141 | } else {
142 | animating.current = false;
143 | }
144 |
145 | if (callback) {
146 | callback(vis);
147 | }
148 | });
149 | }, [animating, animate, animateIn, duration, afterAnimatedIn, animateInTrigger, animateOut, getVisibility]);
150 | const handleScroll = useCallback(() => {
151 | if (!animating.current) {
152 | const {
153 | current: visibility
154 | } = visibilityRef;
155 | const currentVis = getVisibility();
156 |
157 | if (visibilityHasChanged(visibility, currentVis)) {
158 | clearTimeout(delayedAnimationTORef.current);
159 |
160 | if (!currentVis.onScreen) {
161 | setClasses(animatedClass);
162 | setStyle({
163 | animationDuration: `${duration}s`,
164 | opacity: initiallyVisible ? 1 : 0
165 | });
166 | } else if (currentVis.inViewport && animateIn) {
167 | animateInTrigger(afterAnimatedIn);
168 | } else if (currentVis.onScreen && visibility.inViewport && animateOut && node.current.style.opacity === '1') {
169 | animateOutTrigger(afterAnimatedOut);
170 | }
171 |
172 | visibilityRef.current = currentVis;
173 | }
174 | }
175 | }, [afterAnimatedIn, afterAnimatedOut, animateIn, animateInTrigger, animateOut, duration, initiallyVisible, visibilityHasChanged, animateOutTrigger, getVisibility]);
176 | const listener = useMemo(() => throttle(() => {
177 | handleScroll();
178 | }, 50), [handleScroll]);
179 | useEffect(() => {
180 | if (!serverSide) {
181 | const parentSelector = scrollableParentSelector;
182 | scrollableParentRef.current = parentSelector ? document.querySelector(parentSelector) : window;
183 |
184 | if (scrollableParentRef.current && scrollableParentRef.current.addEventListener) {
185 | scrollableParentRef.current.addEventListener('scroll', listener);
186 | } else {
187 | console.warn(`Cannot find element by locator: ${scrollableParentSelector}`);
188 | }
189 |
190 | if (animatePreScroll) {
191 | handleScroll();
192 | }
193 |
194 | return () => {
195 | clearTimeout(delayedAnimationTORef.current);
196 | clearTimeout(callbackTORef.current);
197 |
198 | if (window && window.removeEventListener) {
199 | window.removeEventListener('scroll', listener);
200 | }
201 | };
202 | }
203 | }, [handleScroll, scrollableParentSelector, scrollableParentRef, listener, animatePreScroll]);
204 | return /*#__PURE__*/React.createElement("div", {
205 | ref: node,
206 | className: classNameProps ? `${classNameProps} ${classes}` : classes,
207 | style: Object.assign({}, style, styleProps)
208 | }, children);
209 | };
210 | //# sourceMappingURL=AnimationOnScroll.js.map
--------------------------------------------------------------------------------
/dist/esm/components/AnimationOnScroll.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["../../../src/components/AnimationOnScroll.tsx"],"names":["React","useMemo","useCallback","useState","useEffect","useRef","throttle","animatedClass","serverSide","window","scrollableParentRefInitialValue","undefined","AnimationOnScroll","offset","duration","style","styleProps","className","classNameProps","initiallyVisible","animateIn","afterAnimatedIn","animateOut","delay","animatePreScroll","afterAnimatedOut","scrollableParentSelector","animateOnce","children","classes","setClasses","setStyle","animationDuration","opacity","node","animating","visibilityRef","onScreen","inViewport","delayedAnimationTORef","callbackTORef","scrollableParentRef","getElementTop","elm","yPos","offsetTop","clientTop","offsetParent","getScrollPos","current","pageYOffset","scrollTop","getScrollableParentHeight","innerHeight","clientHeight","getViewportTop","getViewportBottom","isInViewport","y","isAboveViewport","isBelowViewport","elementTop","elementBottom","isAboveScreen","isBelowScreen","getVisibility","visibilityHasChanged","previousVis","currentVis","animate","animation","callback","setTimeout","animateInTrigger","vis","animateOutTrigger","handleScroll","visibility","clearTimeout","listener","parentSelector","document","querySelector","addEventListener","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D;AACF,GA5BQ,EA4BN,CACDH,YADC,EAEDlD,wBAFC,EAGDe,mBAHC,EAIDsC,QAJC,EAKDvD,gBALC,CA5BM,CAAT;AAoCA,sBACE;AACE,IAAA,GAAG,EAAEU,IADP;AAEE,IAAA,SAAS,EAAEhB,cAAc,GAAI,GAAEA,cAAe,IAAGW,OAAQ,EAAhC,GAAoCA,OAF/D;AAGE,IAAA,KAAK,EAAE0D,MAAM,CAACC,MAAP,CAAc,EAAd,EAAkBzE,KAAlB,EAAyBC,UAAzB;AAHT,KAKGY,QALH,CADF;AASD,CA9RM","sourcesContent":["import React, {\n useMemo,\n useCallback,\n useState,\n useEffect,\n useRef,\n} from 'react';\nimport throttle from 'lodash.throttle';\n\nconst animatedClass = 'animate__animated';\nconst serverSide = typeof window === 'undefined';\n\nlet scrollableParentRefInitialValue: any = undefined;\nif (!serverSide) {\n scrollableParentRefInitialValue = window;\n}\n\ntype Props = {\n offset?: number;\n duration?: number;\n style?: any;\n className?: string;\n initiallyVisible?: boolean;\n animateIn?: string;\n afterAnimatedIn?: any;\n animateOut?: string;\n delay?: number;\n animatePreScroll?: boolean;\n afterAnimatedOut?: any;\n scrollableParentSelector?: string;\n animateOnce?: boolean;\n children?: any;\n};\n\ntype styleProp = {\n animationDuration: string;\n opacity?: number;\n};\n\nexport const AnimationOnScroll = ({\n offset = 150,\n duration = 1,\n style: styleProps,\n className: classNameProps,\n initiallyVisible = false,\n animateIn,\n afterAnimatedIn,\n animateOut,\n delay = 0,\n animatePreScroll = true,\n afterAnimatedOut,\n scrollableParentSelector,\n animateOnce = false,\n children,\n}: Props) => {\n const [classes, setClasses] = useState(animatedClass);\n const [style, setStyle] = useState({\n animationDuration: `${duration}s`,\n opacity: initiallyVisible ? 1 : 0,\n });\n\n const node: { current: any } = useRef(null);\n const animating: { current: boolean } = useRef(false);\n const visibilityRef: {\n current: { onScreen: boolean; inViewport: boolean };\n } = useRef({ onScreen: false, inViewport: false });\n\n const delayedAnimationTORef: { current: any } = useRef(undefined);\n const callbackTORef: { current: any } = useRef(undefined);\n const scrollableParentRef: { current: any } = useRef(scrollableParentRefInitialValue);\n\n const getElementTop = useCallback((elm: any) => {\n let yPos = 0;\n while (elm && elm.offsetTop !== undefined && elm.clientTop !== undefined) {\n yPos += elm.offsetTop + elm.clientTop;\n elm = elm.offsetParent;\n }\n return yPos;\n }, []);\n\n const getScrollPos = useCallback(() => {\n if (scrollableParentRef.current.pageYOffset !== undefined) {\n return scrollableParentRef.current.pageYOffset;\n }\n return scrollableParentRef.current.scrollTop;\n }, [scrollableParentRef]);\n\n const getScrollableParentHeight = useCallback(() => {\n if (scrollableParentRef.current.innerHeight !== undefined) {\n return scrollableParentRef.current.innerHeight;\n }\n return scrollableParentRef.current.clientHeight;\n }, [scrollableParentRef]);\n\n const getViewportTop = useCallback(() => {\n return getScrollPos() + offset;\n }, [offset, getScrollPos]);\n\n const getViewportBottom = useCallback(() => {\n return getScrollPos() + getScrollableParentHeight() - offset;\n }, [offset, getScrollPos, getScrollableParentHeight]);\n\n const isInViewport = useCallback(\n (y) => {\n return y >= getViewportTop() && y <= getViewportBottom();\n },\n [getViewportTop, getViewportBottom]\n );\n\n const isAboveViewport = useCallback(\n (y) => {\n return y < getViewportTop();\n },\n [getViewportTop]\n );\n\n const isBelowViewport = useCallback(\n (y) => {\n return y > getViewportBottom();\n },\n [getViewportBottom]\n );\n\n const inViewport = useCallback(\n (elementTop, elementBottom) => {\n return (\n isInViewport(elementTop) ||\n isInViewport(elementBottom) ||\n (isAboveViewport(elementTop) && isBelowViewport(elementBottom))\n );\n },\n [isInViewport, isAboveViewport, isBelowViewport]\n );\n\n const isAboveScreen = useCallback(\n (y) => {\n return y < getScrollPos();\n },\n [getScrollPos]\n );\n\n const isBelowScreen = useCallback(\n (y) => {\n return y > getScrollPos() + getScrollableParentHeight();\n },\n [getScrollPos, getScrollableParentHeight]\n );\n\n const onScreen = useCallback(\n (elementTop, elementBottom) => {\n return !isAboveScreen(elementBottom) && !isBelowScreen(elementTop);\n },\n [isAboveScreen, isBelowScreen]\n );\n\n const getVisibility = useCallback(() => {\n const elementTop =\n getElementTop(node.current) - getElementTop(scrollableParentRef.current);\n const elementBottom = elementTop + node.current.clientHeight;\n\n return {\n inViewport: inViewport(elementTop, elementBottom),\n onScreen: onScreen(elementTop, elementBottom),\n };\n }, [getElementTop, node, inViewport, onScreen, scrollableParentRef]);\n\n const visibilityHasChanged = useCallback((previousVis, currentVis) => {\n return (\n previousVis.inViewport !== currentVis.inViewport ||\n previousVis.onScreen !== currentVis.onScreen\n );\n }, []);\n\n const animate = useCallback(\n (animation, callback) => {\n delayedAnimationTORef.current = setTimeout(() => {\n animating.current = true;\n setClasses(`${animatedClass} ${animation}`);\n setStyle({ animationDuration: `${duration}s` });\n callbackTORef.current = setTimeout(callback, duration * 1000);\n }, delay);\n },\n [animating, delay, duration]\n );\n\n const animateInTrigger = useCallback(\n (callback) => {\n animate(animateIn, () => {\n if (!animateOnce) {\n setStyle({\n animationDuration: `${duration}s`,\n opacity: 1,\n });\n animating.current = false;\n }\n const vis = getVisibility();\n if (callback) {\n callback(vis);\n }\n });\n },\n [animating, animateIn, animateOnce, duration, animate, getVisibility]\n );\n\n const animateOutTrigger = useCallback(\n (callback) => {\n animate(animateOut, () => {\n setClasses(animatedClass);\n setStyle({ animationDuration: `${duration}s`, opacity: 0 });\n const vis = getVisibility();\n\n if (vis.inViewport && animateIn) {\n animateInTrigger(afterAnimatedIn);\n } else {\n animating.current = false;\n }\n\n if (callback) {\n callback(vis);\n }\n });\n },\n [\n animating,\n animate,\n animateIn,\n duration,\n afterAnimatedIn,\n animateInTrigger,\n animateOut,\n getVisibility,\n ]\n );\n\n const handleScroll = useCallback(() => {\n if (!animating.current) {\n const { current: visibility } = visibilityRef;\n const currentVis = getVisibility();\n if (visibilityHasChanged(visibility, currentVis)) {\n clearTimeout(delayedAnimationTORef.current);\n if (!currentVis.onScreen) {\n setClasses(animatedClass);\n setStyle({\n animationDuration: `${duration}s`,\n opacity: initiallyVisible ? 1 : 0,\n });\n } else if (currentVis.inViewport && animateIn) {\n animateInTrigger(afterAnimatedIn);\n } else if (\n currentVis.onScreen &&\n visibility.inViewport &&\n animateOut &&\n node.current.style.opacity === '1'\n ) {\n animateOutTrigger(afterAnimatedOut);\n }\n visibilityRef.current = currentVis;\n }\n }\n }, [\n afterAnimatedIn,\n afterAnimatedOut,\n animateIn,\n animateInTrigger,\n animateOut,\n duration,\n initiallyVisible,\n visibilityHasChanged,\n animateOutTrigger,\n getVisibility,\n ]);\n\n const listener = useMemo(\n () =>\n throttle(() => {\n handleScroll();\n }, 50),\n [handleScroll]\n );\n\n useEffect(() => {\n if (!serverSide) {\n const parentSelector = scrollableParentSelector;\n scrollableParentRef.current = parentSelector\n ? document.querySelector(parentSelector)\n : window;\n if (\n scrollableParentRef.current &&\n scrollableParentRef.current.addEventListener\n ) {\n scrollableParentRef.current.addEventListener('scroll', listener);\n } else {\n console.warn(\n `Cannot find element by locator: ${scrollableParentSelector}`\n );\n }\n if (animatePreScroll) {\n handleScroll();\n }\n\n return () => {\n clearTimeout(delayedAnimationTORef.current);\n clearTimeout(callbackTORef.current);\n if (window && window.removeEventListener) {\n window.removeEventListener('scroll', listener);\n }\n };\n }\n }, [\n handleScroll,\n scrollableParentSelector,\n scrollableParentRef,\n listener,\n animatePreScroll,\n ]);\n\n return (\n \n {children}\n
\n );\n};\n"],"file":"AnimationOnScroll.js"}
--------------------------------------------------------------------------------
/dist/esm/components/index.js:
--------------------------------------------------------------------------------
1 | export * from './AnimationOnScroll';
2 | //# sourceMappingURL=index.js.map
--------------------------------------------------------------------------------
/dist/esm/components/index.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["../../../src/components/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAd","sourcesContent":["export * from './AnimationOnScroll';\n"],"file":"index.js"}
--------------------------------------------------------------------------------
/dist/esm/index.js:
--------------------------------------------------------------------------------
1 | export * from './components';
2 | //# sourceMappingURL=index.js.map
--------------------------------------------------------------------------------
/dist/esm/index.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["../../src/index.tsx"],"names":[],"mappings":"AAAA,cAAc,cAAd","sourcesContent":["export * from './components';\n"],"file":"index.js"}
--------------------------------------------------------------------------------
/dist/js/components/AnimationOnScroll.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 | declare type Props = {
3 | offset?: number;
4 | duration?: number;
5 | style?: any;
6 | className?: string;
7 | initiallyVisible?: boolean;
8 | animateIn?: string;
9 | afterAnimatedIn?: any;
10 | animateOut?: string;
11 | delay?: number;
12 | animatePreScroll?: boolean;
13 | afterAnimatedOut?: any;
14 | scrollableParentSelector?: string;
15 | animateOnce?: boolean;
16 | children?: any;
17 | };
18 | export declare const AnimationOnScroll: ({ offset, duration, style: styleProps, className: classNameProps, initiallyVisible, animateIn, afterAnimatedIn, animateOut, delay, animatePreScroll, afterAnimatedOut, scrollableParentSelector, animateOnce, children, }: Props) => JSX.Element;
19 | export {};
20 |
--------------------------------------------------------------------------------
/dist/js/components/AnimationOnScroll.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
4 |
5 | Object.defineProperty(exports, "__esModule", {
6 | value: true
7 | });
8 | exports.AnimationOnScroll = void 0;
9 |
10 | var _react = _interopRequireWildcard(require("react"));
11 |
12 | var _lodash = _interopRequireDefault(require("lodash.throttle"));
13 |
14 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15 |
16 | function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17 |
18 | function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
19 |
20 | function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
21 |
22 | function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
23 |
24 | function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
25 |
26 | function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
27 |
28 | function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
29 |
30 | function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
31 |
32 | var animatedClass = 'animate__animated';
33 | var serverSide = typeof window === 'undefined';
34 | var scrollableParentRefInitialValue = undefined;
35 |
36 | if (!serverSide) {
37 | scrollableParentRefInitialValue = window;
38 | }
39 |
40 | var AnimationOnScroll = function AnimationOnScroll(_ref) {
41 | var _ref$offset = _ref.offset,
42 | offset = _ref$offset === void 0 ? 150 : _ref$offset,
43 | _ref$duration = _ref.duration,
44 | duration = _ref$duration === void 0 ? 1 : _ref$duration,
45 | styleProps = _ref.style,
46 | classNameProps = _ref.className,
47 | _ref$initiallyVisible = _ref.initiallyVisible,
48 | initiallyVisible = _ref$initiallyVisible === void 0 ? false : _ref$initiallyVisible,
49 | animateIn = _ref.animateIn,
50 | afterAnimatedIn = _ref.afterAnimatedIn,
51 | animateOut = _ref.animateOut,
52 | _ref$delay = _ref.delay,
53 | delay = _ref$delay === void 0 ? 0 : _ref$delay,
54 | _ref$animatePreScroll = _ref.animatePreScroll,
55 | animatePreScroll = _ref$animatePreScroll === void 0 ? true : _ref$animatePreScroll,
56 | afterAnimatedOut = _ref.afterAnimatedOut,
57 | scrollableParentSelector = _ref.scrollableParentSelector,
58 | _ref$animateOnce = _ref.animateOnce,
59 | animateOnce = _ref$animateOnce === void 0 ? false : _ref$animateOnce,
60 | children = _ref.children;
61 |
62 | var _useState = (0, _react.useState)(animatedClass),
63 | _useState2 = _slicedToArray(_useState, 2),
64 | classes = _useState2[0],
65 | setClasses = _useState2[1];
66 |
67 | var _useState3 = (0, _react.useState)({
68 | animationDuration: "".concat(duration, "s"),
69 | opacity: initiallyVisible ? 1 : 0
70 | }),
71 | _useState4 = _slicedToArray(_useState3, 2),
72 | style = _useState4[0],
73 | setStyle = _useState4[1];
74 |
75 | var node = (0, _react.useRef)(null);
76 | var animating = (0, _react.useRef)(false);
77 | var visibilityRef = (0, _react.useRef)({
78 | onScreen: false,
79 | inViewport: false
80 | });
81 | var delayedAnimationTORef = (0, _react.useRef)(undefined);
82 | var callbackTORef = (0, _react.useRef)(undefined);
83 | var scrollableParentRef = (0, _react.useRef)(scrollableParentRefInitialValue);
84 | var getElementTop = (0, _react.useCallback)(function (elm) {
85 | var yPos = 0;
86 |
87 | while (elm && elm.offsetTop !== undefined && elm.clientTop !== undefined) {
88 | yPos += elm.offsetTop + elm.clientTop;
89 | elm = elm.offsetParent;
90 | }
91 |
92 | return yPos;
93 | }, []);
94 | var getScrollPos = (0, _react.useCallback)(function () {
95 | if (scrollableParentRef.current.pageYOffset !== undefined) {
96 | return scrollableParentRef.current.pageYOffset;
97 | }
98 |
99 | return scrollableParentRef.current.scrollTop;
100 | }, [scrollableParentRef]);
101 | var getScrollableParentHeight = (0, _react.useCallback)(function () {
102 | if (scrollableParentRef.current.innerHeight !== undefined) {
103 | return scrollableParentRef.current.innerHeight;
104 | }
105 |
106 | return scrollableParentRef.current.clientHeight;
107 | }, [scrollableParentRef]);
108 | var getViewportTop = (0, _react.useCallback)(function () {
109 | return getScrollPos() + offset;
110 | }, [offset, getScrollPos]);
111 | var getViewportBottom = (0, _react.useCallback)(function () {
112 | return getScrollPos() + getScrollableParentHeight() - offset;
113 | }, [offset, getScrollPos, getScrollableParentHeight]);
114 | var isInViewport = (0, _react.useCallback)(function (y) {
115 | return y >= getViewportTop() && y <= getViewportBottom();
116 | }, [getViewportTop, getViewportBottom]);
117 | var isAboveViewport = (0, _react.useCallback)(function (y) {
118 | return y < getViewportTop();
119 | }, [getViewportTop]);
120 | var isBelowViewport = (0, _react.useCallback)(function (y) {
121 | return y > getViewportBottom();
122 | }, [getViewportBottom]);
123 | var inViewport = (0, _react.useCallback)(function (elementTop, elementBottom) {
124 | return isInViewport(elementTop) || isInViewport(elementBottom) || isAboveViewport(elementTop) && isBelowViewport(elementBottom);
125 | }, [isInViewport, isAboveViewport, isBelowViewport]);
126 | var isAboveScreen = (0, _react.useCallback)(function (y) {
127 | return y < getScrollPos();
128 | }, [getScrollPos]);
129 | var isBelowScreen = (0, _react.useCallback)(function (y) {
130 | return y > getScrollPos() + getScrollableParentHeight();
131 | }, [getScrollPos, getScrollableParentHeight]);
132 | var onScreen = (0, _react.useCallback)(function (elementTop, elementBottom) {
133 | return !isAboveScreen(elementBottom) && !isBelowScreen(elementTop);
134 | }, [isAboveScreen, isBelowScreen]);
135 | var getVisibility = (0, _react.useCallback)(function () {
136 | var elementTop = getElementTop(node.current) - getElementTop(scrollableParentRef.current);
137 | var elementBottom = elementTop + node.current.clientHeight;
138 | return {
139 | inViewport: inViewport(elementTop, elementBottom),
140 | onScreen: onScreen(elementTop, elementBottom)
141 | };
142 | }, [getElementTop, node, inViewport, onScreen, scrollableParentRef]);
143 | var visibilityHasChanged = (0, _react.useCallback)(function (previousVis, currentVis) {
144 | return previousVis.inViewport !== currentVis.inViewport || previousVis.onScreen !== currentVis.onScreen;
145 | }, []);
146 | var animate = (0, _react.useCallback)(function (animation, callback) {
147 | delayedAnimationTORef.current = setTimeout(function () {
148 | animating.current = true;
149 | setClasses("".concat(animatedClass, " ").concat(animation));
150 | setStyle({
151 | animationDuration: "".concat(duration, "s")
152 | });
153 | callbackTORef.current = setTimeout(callback, duration * 1000);
154 | }, delay);
155 | }, [animating, delay, duration]);
156 | var animateInTrigger = (0, _react.useCallback)(function (callback) {
157 | animate(animateIn, function () {
158 | if (!animateOnce) {
159 | setStyle({
160 | animationDuration: "".concat(duration, "s"),
161 | opacity: 1
162 | });
163 | animating.current = false;
164 | }
165 |
166 | var vis = getVisibility();
167 |
168 | if (callback) {
169 | callback(vis);
170 | }
171 | });
172 | }, [animating, animateIn, animateOnce, duration, animate, getVisibility]);
173 | var animateOutTrigger = (0, _react.useCallback)(function (callback) {
174 | animate(animateOut, function () {
175 | setClasses(animatedClass);
176 | setStyle({
177 | animationDuration: "".concat(duration, "s"),
178 | opacity: 0
179 | });
180 | var vis = getVisibility();
181 |
182 | if (vis.inViewport && animateIn) {
183 | animateInTrigger(afterAnimatedIn);
184 | } else {
185 | animating.current = false;
186 | }
187 |
188 | if (callback) {
189 | callback(vis);
190 | }
191 | });
192 | }, [animating, animate, animateIn, duration, afterAnimatedIn, animateInTrigger, animateOut, getVisibility]);
193 | var handleScroll = (0, _react.useCallback)(function () {
194 | if (!animating.current) {
195 | var visibility = visibilityRef.current;
196 | var currentVis = getVisibility();
197 |
198 | if (visibilityHasChanged(visibility, currentVis)) {
199 | clearTimeout(delayedAnimationTORef.current);
200 |
201 | if (!currentVis.onScreen) {
202 | setClasses(animatedClass);
203 | setStyle({
204 | animationDuration: "".concat(duration, "s"),
205 | opacity: initiallyVisible ? 1 : 0
206 | });
207 | } else if (currentVis.inViewport && animateIn) {
208 | animateInTrigger(afterAnimatedIn);
209 | } else if (currentVis.onScreen && visibility.inViewport && animateOut && node.current.style.opacity === '1') {
210 | animateOutTrigger(afterAnimatedOut);
211 | }
212 |
213 | visibilityRef.current = currentVis;
214 | }
215 | }
216 | }, [afterAnimatedIn, afterAnimatedOut, animateIn, animateInTrigger, animateOut, duration, initiallyVisible, visibilityHasChanged, animateOutTrigger, getVisibility]);
217 | var listener = (0, _react.useMemo)(function () {
218 | return (0, _lodash.default)(function () {
219 | handleScroll();
220 | }, 50);
221 | }, [handleScroll]);
222 | (0, _react.useEffect)(function () {
223 | if (!serverSide) {
224 | var parentSelector = scrollableParentSelector;
225 | scrollableParentRef.current = parentSelector ? document.querySelector(parentSelector) : window;
226 |
227 | if (scrollableParentRef.current && scrollableParentRef.current.addEventListener) {
228 | scrollableParentRef.current.addEventListener('scroll', listener);
229 | } else {
230 | console.warn("Cannot find element by locator: ".concat(scrollableParentSelector));
231 | }
232 |
233 | if (animatePreScroll) {
234 | handleScroll();
235 | }
236 |
237 | return function () {
238 | clearTimeout(delayedAnimationTORef.current);
239 | clearTimeout(callbackTORef.current);
240 |
241 | if (window && window.removeEventListener) {
242 | window.removeEventListener('scroll', listener);
243 | }
244 | };
245 | }
246 | }, [handleScroll, scrollableParentSelector, scrollableParentRef, listener, animatePreScroll]);
247 | return /*#__PURE__*/_react.default.createElement("div", {
248 | ref: node,
249 | className: classNameProps ? "".concat(classNameProps, " ").concat(classes) : classes,
250 | style: Object.assign({}, style, styleProps)
251 | }, children);
252 | };
253 |
254 | exports.AnimationOnScroll = AnimationOnScroll;
255 | //# sourceMappingURL=AnimationOnScroll.js.map
--------------------------------------------------------------------------------
/dist/js/components/AnimationOnScroll.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["../../../src/components/AnimationOnScroll.tsx"],"names":["animatedClass","serverSide","window","scrollableParentRefInitialValue","undefined","AnimationOnScroll","offset","duration","styleProps","style","classNameProps","className","initiallyVisible","animateIn","afterAnimatedIn","animateOut","delay","animatePreScroll","afterAnimatedOut","scrollableParentSelector","animateOnce","children","classes","setClasses","animationDuration","opacity","setStyle","node","animating","visibilityRef","onScreen","inViewport","delayedAnimationTORef","callbackTORef","scrollableParentRef","getElementTop","elm","yPos","offsetTop","clientTop","offsetParent","getScrollPos","current","pageYOffset","scrollTop","getScrollableParentHeight","innerHeight","clientHeight","getViewportTop","getViewportBottom","isInViewport","y","isAboveViewport","isBelowViewport","elementTop","elementBottom","isAboveScreen","isBelowScreen","getVisibility","visibilityHasChanged","previousVis","currentVis","animate","animation","callback","setTimeout","animateInTrigger","vis","animateOutTrigger","handleScroll","visibility","clearTimeout","listener","parentSelector","document","querySelector","addEventListener","console","warn","removeEventListener","Object","assign"],"mappings":";;;;;;;;;AAAA;;AAOA;;;;;;;;;;;;;;;;;;;;AAEA,IAAMA,aAAa,GAAG,mBAAtB;AACA,IAAMC,UAAU,GAAG,OAAOC,MAAP,KAAkB,WAArC;AAEA,IAAIC,+BAAoC,GAAGC,SAA3C;;AACA,IAAI,CAACH,UAAL,EAAiB;AACfE,EAAAA,+BAA+B,GAAGD,MAAlC;AACD;;AAwBM,IAA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AACA,YAAD,CALe,CAAjB;AAQA,wBAAU,YAAM;AACd,QAAI,CAACpE,UAAL,EAAiB;AACf,UAAMwE,cAAc,GAAGtD,wBAAvB;AACAe,MAAAA,mBAAmB,CAACQ,OAApB,GAA8B+B,cAAc,GACxCC,QAAQ,CAACC,aAAT,CAAuBF,cAAvB,CADwC,GAExCvE,MAFJ;;AAGA,UACEgC,mBAAmB,CAACQ,OAApB,IACAR,mBAAmB,CAACQ,OAApB,CAA4BkC,gBAF9B,EAGE;AACA1C,QAAAA,mBAAmB,CAACQ,OAApB,CAA4BkC,gBAA5B,CAA6C,QAA7C,EAAuDJ,QAAvD;AACD,OALD,MAKO;AACLK,QAAAA,OAAO,CAACC,IAAR,2CACqC3D,wBADrC;AAGD;;AACD,UAAIF,gBAAJ,EAAsB;AACpBoD,QAAAA,YAAY;AACb;;AAED,aAAO,YAAM;AACXE,QAAAA,YAAY,CAACvC,qBAAqB,CAACU,OAAvB,CAAZ;AACA6B,QAAAA,YAAY,CAACtC,aAAa,CAACS,OAAf,CAAZ;;AACA,YAAIxC,MAAM,IAAIA,MAAM,CAAC6E,mBAArB,EAA0C;AACxC7E,UAAAA,MAAM,CAAC6E,mBAAP,CAA2B,QAA3B,EAAqCP,QAArC;AACD;AACF,OAND;AAOD;AACF,GA5BD,EA4BG,CACDH,YADC,EAEDlD,wBAFC,EAGDe,mBAHC,EAIDsC,QAJC,EAKDvD,gBALC,CA5BH;AAoCA,sBACE;AACE,IAAA,GAAG,EAAEU,IADP;AAEE,IAAA,SAAS,EAAEjB,cAAc,aAAMA,cAAN,cAAwBY,OAAxB,IAAoCA,OAF/D;AAGE,IAAA,KAAK,EAAE0D,MAAM,CAACC,MAAP,CAAc,EAAd,EAAkBxE,KAAlB,EAAyBD,UAAzB;AAHT,KAKGa,QALH,CADF;AASD,CA9RM","sourcesContent":["import React, {\n useMemo,\n useCallback,\n useState,\n useEffect,\n useRef,\n} from 'react';\nimport throttle from 'lodash.throttle';\n\nconst animatedClass = 'animate__animated';\nconst serverSide = typeof window === 'undefined';\n\nlet scrollableParentRefInitialValue: any = undefined;\nif (!serverSide) {\n scrollableParentRefInitialValue = window;\n}\n\ntype Props = {\n offset?: number;\n duration?: number;\n style?: any;\n className?: string;\n initiallyVisible?: boolean;\n animateIn?: string;\n afterAnimatedIn?: any;\n animateOut?: string;\n delay?: number;\n animatePreScroll?: boolean;\n afterAnimatedOut?: any;\n scrollableParentSelector?: string;\n animateOnce?: boolean;\n children?: any;\n};\n\ntype styleProp = {\n animationDuration: string;\n opacity?: number;\n};\n\nexport const AnimationOnScroll = ({\n offset = 150,\n duration = 1,\n style: styleProps,\n className: classNameProps,\n initiallyVisible = false,\n animateIn,\n afterAnimatedIn,\n animateOut,\n delay = 0,\n animatePreScroll = true,\n afterAnimatedOut,\n scrollableParentSelector,\n animateOnce = false,\n children,\n}: Props) => {\n const [classes, setClasses] = useState(animatedClass);\n const [style, setStyle] = useState({\n animationDuration: `${duration}s`,\n opacity: initiallyVisible ? 1 : 0,\n });\n\n const node: { current: any } = useRef(null);\n const animating: { current: boolean } = useRef(false);\n const visibilityRef: {\n current: { onScreen: boolean; inViewport: boolean };\n } = useRef({ onScreen: false, inViewport: false });\n\n const delayedAnimationTORef: { current: any } = useRef(undefined);\n const callbackTORef: { current: any } = useRef(undefined);\n const scrollableParentRef: { current: any } = useRef(scrollableParentRefInitialValue);\n\n const getElementTop = useCallback((elm: any) => {\n let yPos = 0;\n while (elm && elm.offsetTop !== undefined && elm.clientTop !== undefined) {\n yPos += elm.offsetTop + elm.clientTop;\n elm = elm.offsetParent;\n }\n return yPos;\n }, []);\n\n const getScrollPos = useCallback(() => {\n if (scrollableParentRef.current.pageYOffset !== undefined) {\n return scrollableParentRef.current.pageYOffset;\n }\n return scrollableParentRef.current.scrollTop;\n }, [scrollableParentRef]);\n\n const getScrollableParentHeight = useCallback(() => {\n if (scrollableParentRef.current.innerHeight !== undefined) {\n return scrollableParentRef.current.innerHeight;\n }\n return scrollableParentRef.current.clientHeight;\n }, [scrollableParentRef]);\n\n const getViewportTop = useCallback(() => {\n return getScrollPos() + offset;\n }, [offset, getScrollPos]);\n\n const getViewportBottom = useCallback(() => {\n return getScrollPos() + getScrollableParentHeight() - offset;\n }, [offset, getScrollPos, getScrollableParentHeight]);\n\n const isInViewport = useCallback(\n (y) => {\n return y >= getViewportTop() && y <= getViewportBottom();\n },\n [getViewportTop, getViewportBottom]\n );\n\n const isAboveViewport = useCallback(\n (y) => {\n return y < getViewportTop();\n },\n [getViewportTop]\n );\n\n const isBelowViewport = useCallback(\n (y) => {\n return y > getViewportBottom();\n },\n [getViewportBottom]\n );\n\n const inViewport = useCallback(\n (elementTop, elementBottom) => {\n return (\n isInViewport(elementTop) ||\n isInViewport(elementBottom) ||\n (isAboveViewport(elementTop) && isBelowViewport(elementBottom))\n );\n },\n [isInViewport, isAboveViewport, isBelowViewport]\n );\n\n const isAboveScreen = useCallback(\n (y) => {\n return y < getScrollPos();\n },\n [getScrollPos]\n );\n\n const isBelowScreen = useCallback(\n (y) => {\n return y > getScrollPos() + getScrollableParentHeight();\n },\n [getScrollPos, getScrollableParentHeight]\n );\n\n const onScreen = useCallback(\n (elementTop, elementBottom) => {\n return !isAboveScreen(elementBottom) && !isBelowScreen(elementTop);\n },\n [isAboveScreen, isBelowScreen]\n );\n\n const getVisibility = useCallback(() => {\n const elementTop =\n getElementTop(node.current) - getElementTop(scrollableParentRef.current);\n const elementBottom = elementTop + node.current.clientHeight;\n\n return {\n inViewport: inViewport(elementTop, elementBottom),\n onScreen: onScreen(elementTop, elementBottom),\n };\n }, [getElementTop, node, inViewport, onScreen, scrollableParentRef]);\n\n const visibilityHasChanged = useCallback((previousVis, currentVis) => {\n return (\n previousVis.inViewport !== currentVis.inViewport ||\n previousVis.onScreen !== currentVis.onScreen\n );\n }, []);\n\n const animate = useCallback(\n (animation, callback) => {\n delayedAnimationTORef.current = setTimeout(() => {\n animating.current = true;\n setClasses(`${animatedClass} ${animation}`);\n setStyle({ animationDuration: `${duration}s` });\n callbackTORef.current = setTimeout(callback, duration * 1000);\n }, delay);\n },\n [animating, delay, duration]\n );\n\n const animateInTrigger = useCallback(\n (callback) => {\n animate(animateIn, () => {\n if (!animateOnce) {\n setStyle({\n animationDuration: `${duration}s`,\n opacity: 1,\n });\n animating.current = false;\n }\n const vis = getVisibility();\n if (callback) {\n callback(vis);\n }\n });\n },\n [animating, animateIn, animateOnce, duration, animate, getVisibility]\n );\n\n const animateOutTrigger = useCallback(\n (callback) => {\n animate(animateOut, () => {\n setClasses(animatedClass);\n setStyle({ animationDuration: `${duration}s`, opacity: 0 });\n const vis = getVisibility();\n\n if (vis.inViewport && animateIn) {\n animateInTrigger(afterAnimatedIn);\n } else {\n animating.current = false;\n }\n\n if (callback) {\n callback(vis);\n }\n });\n },\n [\n animating,\n animate,\n animateIn,\n duration,\n afterAnimatedIn,\n animateInTrigger,\n animateOut,\n getVisibility,\n ]\n );\n\n const handleScroll = useCallback(() => {\n if (!animating.current) {\n const { current: visibility } = visibilityRef;\n const currentVis = getVisibility();\n if (visibilityHasChanged(visibility, currentVis)) {\n clearTimeout(delayedAnimationTORef.current);\n if (!currentVis.onScreen) {\n setClasses(animatedClass);\n setStyle({\n animationDuration: `${duration}s`,\n opacity: initiallyVisible ? 1 : 0,\n });\n } else if (currentVis.inViewport && animateIn) {\n animateInTrigger(afterAnimatedIn);\n } else if (\n currentVis.onScreen &&\n visibility.inViewport &&\n animateOut &&\n node.current.style.opacity === '1'\n ) {\n animateOutTrigger(afterAnimatedOut);\n }\n visibilityRef.current = currentVis;\n }\n }\n }, [\n afterAnimatedIn,\n afterAnimatedOut,\n animateIn,\n animateInTrigger,\n animateOut,\n duration,\n initiallyVisible,\n visibilityHasChanged,\n animateOutTrigger,\n getVisibility,\n ]);\n\n const listener = useMemo(\n () =>\n throttle(() => {\n handleScroll();\n }, 50),\n [handleScroll]\n );\n\n useEffect(() => {\n if (!serverSide) {\n const parentSelector = scrollableParentSelector;\n scrollableParentRef.current = parentSelector\n ? document.querySelector(parentSelector)\n : window;\n if (\n scrollableParentRef.current &&\n scrollableParentRef.current.addEventListener\n ) {\n scrollableParentRef.current.addEventListener('scroll', listener);\n } else {\n console.warn(\n `Cannot find element by locator: ${scrollableParentSelector}`\n );\n }\n if (animatePreScroll) {\n handleScroll();\n }\n\n return () => {\n clearTimeout(delayedAnimationTORef.current);\n clearTimeout(callbackTORef.current);\n if (window && window.removeEventListener) {\n window.removeEventListener('scroll', listener);\n }\n };\n }\n }, [\n handleScroll,\n scrollableParentSelector,\n scrollableParentRef,\n listener,\n animatePreScroll,\n ]);\n\n return (\n \n {children}\n
\n );\n};\n"],"file":"AnimationOnScroll.js"}
--------------------------------------------------------------------------------
/dist/js/components/index.d.ts:
--------------------------------------------------------------------------------
1 | export * from './AnimationOnScroll';
2 |
--------------------------------------------------------------------------------
/dist/js/components/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | var _AnimationOnScroll = require("./AnimationOnScroll");
8 |
9 | Object.keys(_AnimationOnScroll).forEach(function (key) {
10 | if (key === "default" || key === "__esModule") return;
11 | if (key in exports && exports[key] === _AnimationOnScroll[key]) return;
12 | Object.defineProperty(exports, key, {
13 | enumerable: true,
14 | get: function get() {
15 | return _AnimationOnScroll[key];
16 | }
17 | });
18 | });
19 | //# sourceMappingURL=index.js.map
--------------------------------------------------------------------------------
/dist/js/components/index.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["../../../src/components/index.ts"],"names":[],"mappings":";;;;;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","sourcesContent":["export * from './AnimationOnScroll';\n"],"file":"index.js"}
--------------------------------------------------------------------------------
/dist/js/index.d.ts:
--------------------------------------------------------------------------------
1 | export * from './components';
2 |
--------------------------------------------------------------------------------
/dist/js/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | var _components = require("./components");
8 |
9 | Object.keys(_components).forEach(function (key) {
10 | if (key === "default" || key === "__esModule") return;
11 | if (key in exports && exports[key] === _components[key]) return;
12 | Object.defineProperty(exports, key, {
13 | enumerable: true,
14 | get: function get() {
15 | return _components[key];
16 | }
17 | });
18 | });
19 | //# sourceMappingURL=index.js.map
--------------------------------------------------------------------------------
/dist/js/index.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["../../src/index.tsx"],"names":[],"mappings":";;;;;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","sourcesContent":["export * from './components';\n"],"file":"index.js"}
--------------------------------------------------------------------------------
/dist/umd/components/AnimationOnScroll.js:
--------------------------------------------------------------------------------
1 | (function (global, factory) {
2 | if (typeof define === "function" && define.amd) {
3 | define(["exports", "react", "lodash.throttle"], factory);
4 | } else if (typeof exports !== "undefined") {
5 | factory(exports, require("react"), require("lodash.throttle"));
6 | } else {
7 | var mod = {
8 | exports: {}
9 | };
10 | factory(mod.exports, global.react, global.lodash);
11 | global.undefined = mod.exports;
12 | }
13 | })(this, function (exports, _react, _lodash) {
14 | "use strict";
15 |
16 | Object.defineProperty(exports, "__esModule", {
17 | value: true
18 | });
19 | exports.AnimationOnScroll = undefined;
20 |
21 | var _react2 = _interopRequireDefault(_react);
22 |
23 | var _lodash2 = _interopRequireDefault(_lodash);
24 |
25 | function _interopRequireDefault(obj) {
26 | return obj && obj.__esModule ? obj : {
27 | default: obj
28 | };
29 | }
30 |
31 | const animatedClass = 'animate__animated';
32 | const serverSide = typeof window === 'undefined';
33 | let scrollableParentRefInitialValue = undefined;
34 |
35 | if (!serverSide) {
36 | scrollableParentRefInitialValue = window;
37 | }
38 |
39 | const AnimationOnScroll = exports.AnimationOnScroll = ({
40 | offset = 150,
41 | duration = 1,
42 | style: styleProps,
43 | className: classNameProps,
44 | initiallyVisible = false,
45 | animateIn,
46 | afterAnimatedIn,
47 | animateOut,
48 | delay = 0,
49 | animatePreScroll = true,
50 | afterAnimatedOut,
51 | scrollableParentSelector,
52 | animateOnce = false,
53 | children
54 | }) => {
55 | const [classes, setClasses] = (0, _react.useState)(animatedClass);
56 | const [style, setStyle] = (0, _react.useState)({
57 | animationDuration: `${duration}s`,
58 | opacity: initiallyVisible ? 1 : 0
59 | });
60 | const node = (0, _react.useRef)(null);
61 | const animating = (0, _react.useRef)(false);
62 | const visibilityRef = (0, _react.useRef)({
63 | onScreen: false,
64 | inViewport: false
65 | });
66 | const delayedAnimationTORef = (0, _react.useRef)(undefined);
67 | const callbackTORef = (0, _react.useRef)(undefined);
68 | const scrollableParentRef = (0, _react.useRef)(scrollableParentRefInitialValue);
69 | const getElementTop = (0, _react.useCallback)(elm => {
70 | let yPos = 0;
71 |
72 | while (elm && elm.offsetTop !== undefined && elm.clientTop !== undefined) {
73 | yPos += elm.offsetTop + elm.clientTop;
74 | elm = elm.offsetParent;
75 | }
76 |
77 | return yPos;
78 | }, []);
79 | const getScrollPos = (0, _react.useCallback)(() => {
80 | if (scrollableParentRef.current.pageYOffset !== undefined) {
81 | return scrollableParentRef.current.pageYOffset;
82 | }
83 |
84 | return scrollableParentRef.current.scrollTop;
85 | }, [scrollableParentRef]);
86 | const getScrollableParentHeight = (0, _react.useCallback)(() => {
87 | if (scrollableParentRef.current.innerHeight !== undefined) {
88 | return scrollableParentRef.current.innerHeight;
89 | }
90 |
91 | return scrollableParentRef.current.clientHeight;
92 | }, [scrollableParentRef]);
93 | const getViewportTop = (0, _react.useCallback)(() => {
94 | return getScrollPos() + offset;
95 | }, [offset, getScrollPos]);
96 | const getViewportBottom = (0, _react.useCallback)(() => {
97 | return getScrollPos() + getScrollableParentHeight() - offset;
98 | }, [offset, getScrollPos, getScrollableParentHeight]);
99 | const isInViewport = (0, _react.useCallback)(y => {
100 | return y >= getViewportTop() && y <= getViewportBottom();
101 | }, [getViewportTop, getViewportBottom]);
102 | const isAboveViewport = (0, _react.useCallback)(y => {
103 | return y < getViewportTop();
104 | }, [getViewportTop]);
105 | const isBelowViewport = (0, _react.useCallback)(y => {
106 | return y > getViewportBottom();
107 | }, [getViewportBottom]);
108 | const inViewport = (0, _react.useCallback)((elementTop, elementBottom) => {
109 | return isInViewport(elementTop) || isInViewport(elementBottom) || isAboveViewport(elementTop) && isBelowViewport(elementBottom);
110 | }, [isInViewport, isAboveViewport, isBelowViewport]);
111 | const isAboveScreen = (0, _react.useCallback)(y => {
112 | return y < getScrollPos();
113 | }, [getScrollPos]);
114 | const isBelowScreen = (0, _react.useCallback)(y => {
115 | return y > getScrollPos() + getScrollableParentHeight();
116 | }, [getScrollPos, getScrollableParentHeight]);
117 | const onScreen = (0, _react.useCallback)((elementTop, elementBottom) => {
118 | return !isAboveScreen(elementBottom) && !isBelowScreen(elementTop);
119 | }, [isAboveScreen, isBelowScreen]);
120 | const getVisibility = (0, _react.useCallback)(() => {
121 | const elementTop = getElementTop(node.current) - getElementTop(scrollableParentRef.current);
122 | const elementBottom = elementTop + node.current.clientHeight;
123 | return {
124 | inViewport: inViewport(elementTop, elementBottom),
125 | onScreen: onScreen(elementTop, elementBottom)
126 | };
127 | }, [getElementTop, node, inViewport, onScreen, scrollableParentRef]);
128 | const visibilityHasChanged = (0, _react.useCallback)((previousVis, currentVis) => {
129 | return previousVis.inViewport !== currentVis.inViewport || previousVis.onScreen !== currentVis.onScreen;
130 | }, []);
131 | const animate = (0, _react.useCallback)((animation, callback) => {
132 | delayedAnimationTORef.current = setTimeout(() => {
133 | animating.current = true;
134 | setClasses(`${animatedClass} ${animation}`);
135 | setStyle({
136 | animationDuration: `${duration}s`
137 | });
138 | callbackTORef.current = setTimeout(callback, duration * 1000);
139 | }, delay);
140 | }, [animating, delay, duration]);
141 | const animateInTrigger = (0, _react.useCallback)(callback => {
142 | animate(animateIn, () => {
143 | if (!animateOnce) {
144 | setStyle({
145 | animationDuration: `${duration}s`,
146 | opacity: 1
147 | });
148 | animating.current = false;
149 | }
150 |
151 | const vis = getVisibility();
152 |
153 | if (callback) {
154 | callback(vis);
155 | }
156 | });
157 | }, [animating, animateIn, animateOnce, duration, animate, getVisibility]);
158 | const animateOutTrigger = (0, _react.useCallback)(callback => {
159 | animate(animateOut, () => {
160 | setClasses(animatedClass);
161 | setStyle({
162 | animationDuration: `${duration}s`,
163 | opacity: 0
164 | });
165 | const vis = getVisibility();
166 |
167 | if (vis.inViewport && animateIn) {
168 | animateInTrigger(afterAnimatedIn);
169 | } else {
170 | animating.current = false;
171 | }
172 |
173 | if (callback) {
174 | callback(vis);
175 | }
176 | });
177 | }, [animating, animate, animateIn, duration, afterAnimatedIn, animateInTrigger, animateOut, getVisibility]);
178 | const handleScroll = (0, _react.useCallback)(() => {
179 | if (!animating.current) {
180 | const {
181 | current: visibility
182 | } = visibilityRef;
183 | const currentVis = getVisibility();
184 |
185 | if (visibilityHasChanged(visibility, currentVis)) {
186 | clearTimeout(delayedAnimationTORef.current);
187 |
188 | if (!currentVis.onScreen) {
189 | setClasses(animatedClass);
190 | setStyle({
191 | animationDuration: `${duration}s`,
192 | opacity: initiallyVisible ? 1 : 0
193 | });
194 | } else if (currentVis.inViewport && animateIn) {
195 | animateInTrigger(afterAnimatedIn);
196 | } else if (currentVis.onScreen && visibility.inViewport && animateOut && node.current.style.opacity === '1') {
197 | animateOutTrigger(afterAnimatedOut);
198 | }
199 |
200 | visibilityRef.current = currentVis;
201 | }
202 | }
203 | }, [afterAnimatedIn, afterAnimatedOut, animateIn, animateInTrigger, animateOut, duration, initiallyVisible, visibilityHasChanged, animateOutTrigger, getVisibility]);
204 | const listener = (0, _react.useMemo)(() => (0, _lodash2.default)(() => {
205 | handleScroll();
206 | }, 50), [handleScroll]);
207 | (0, _react.useEffect)(() => {
208 | if (!serverSide) {
209 | const parentSelector = scrollableParentSelector;
210 | scrollableParentRef.current = parentSelector ? document.querySelector(parentSelector) : window;
211 |
212 | if (scrollableParentRef.current && scrollableParentRef.current.addEventListener) {
213 | scrollableParentRef.current.addEventListener('scroll', listener);
214 | } else {
215 | console.warn(`Cannot find element by locator: ${scrollableParentSelector}`);
216 | }
217 |
218 | if (animatePreScroll) {
219 | handleScroll();
220 | }
221 |
222 | return () => {
223 | clearTimeout(delayedAnimationTORef.current);
224 | clearTimeout(callbackTORef.current);
225 |
226 | if (window && window.removeEventListener) {
227 | window.removeEventListener('scroll', listener);
228 | }
229 | };
230 | }
231 | }, [handleScroll, scrollableParentSelector, scrollableParentRef, listener, animatePreScroll]);
232 | return /*#__PURE__*/_react2.default.createElement("div", {
233 | ref: node,
234 | className: classNameProps ? `${classNameProps} ${classes}` : classes,
235 | style: Object.assign({}, style, styleProps)
236 | }, children);
237 | };
238 | });
239 | //# sourceMappingURL=AnimationOnScroll.js.map
--------------------------------------------------------------------------------
/dist/umd/components/AnimationOnScroll.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"AnimationOnScroll.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,QAAMA,aAAa,GAAG,mBAAtB;AACA,QAAMC,UAAU,GAAG,OAAOC,MAAP,KAAkB,WAArC;AAEA,MAAIC,+BAAoC,GAAGC,SAA3C;;AACA,MAAI,CAACH,UAAL,EAAiB;AACfE,mCAA+B,GAAGD,MAAlCC;AACD;;AAwBM,QAAME,iBAAiB,WAAjBA,iBAAiB,GAAG,CAAC;AAChCC,UAAM,GAAG,GADuB;AAEhCC,YAAQ,GAAG,CAFqB;AAGhCC,SAAK,EAAEC,UAHyB;AAIhCC,aAAS,EAAEC,cAJqB;AAKhCC,oBAAgB,GAAG,KALa;AAMhCC,aANgC;AAOhCC,mBAPgC;AAQhCC,cARgC;AAShCC,SAAK,GAAG,CATwB;AAUhCC,oBAAgB,GAAG,IAVa;AAWhCC,oBAXgC;AAYhCC,4BAZgC;AAahCC,eAAW,GAAG,KAbkB;AAchCC;AAdgC,GAAD,KAepB;AACX,UAAM,CAACC,OAAD,EAAUC,UAAV,IAAwBC,qBAASxB,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,QAArCzE;AACD;AALH;AAOD;AA3BM,KAAT4E,EA4BG,CACDN,YADC,EAEDrD,wBAFC,EAGDiB,mBAHC,EAIDuC,QAJC,EAKD1D,gBALC,CA5BH6D;AAoCA,wBACEQ;AACEC,SAAG,EAAE3D,IADP;AAEElB,eAAS,EAAEC,cAAc,GAAI,GAAEA,cAAe,IAAGW,OAAQ,EAAhC,GAAoCA,OAF/D;AAGEd,WAAK,EAAEgF,MAAM,CAACC,MAAPD,CAAc,EAAdA,EAAkBhF,KAAlBgF,EAAyB/E,UAAzB+E;AAHT,OAKGnE,QALH,CADF;AArRK","names":["animatedClass","serverSide","window","scrollableParentRefInitialValue","undefined","AnimationOnScroll","offset","duration","style","styleProps","className","classNameProps","initiallyVisible","animateIn","afterAnimatedIn","animateOut","delay","animatePreScroll","afterAnimatedOut","scrollableParentSelector","animateOnce","children","classes","setClasses","useState","setStyle","animationDuration","opacity","node","useRef","animating","visibilityRef","onScreen","inViewport","delayedAnimationTORef","callbackTORef","scrollableParentRef","getElementTop","useCallback","elm","yPos","offsetTop","clientTop","offsetParent","getScrollPos","current","pageYOffset","scrollTop","getScrollableParentHeight","innerHeight","clientHeight","getViewportTop","getViewportBottom","isInViewport","y","isAboveViewport","isBelowViewport","elementTop","elementBottom","isAboveScreen","isBelowScreen","getVisibility","visibilityHasChanged","previousVis","currentVis","animate","animation","callback","setTimeout","animateInTrigger","vis","animateOutTrigger","handleScroll","visibility","clearTimeout","listener","useMemo","throttle","useEffect","parentSelector","document","querySelector","addEventListener","console","warn","removeEventListener","React","ref","Object","assign"],"sources":["../../../src/components/AnimationOnScroll.tsx"],"sourcesContent":["import React, {\n useMemo,\n useCallback,\n useState,\n useEffect,\n useRef,\n} from 'react';\nimport throttle from 'lodash.throttle';\n\nconst animatedClass = 'animate__animated';\nconst serverSide = typeof window === 'undefined';\n\nlet scrollableParentRefInitialValue: any = undefined;\nif (!serverSide) {\n scrollableParentRefInitialValue = window;\n}\n\ntype Props = {\n offset?: number;\n duration?: number;\n style?: any;\n className?: string;\n initiallyVisible?: boolean;\n animateIn?: string;\n afterAnimatedIn?: any;\n animateOut?: string;\n delay?: number;\n animatePreScroll?: boolean;\n afterAnimatedOut?: any;\n scrollableParentSelector?: string;\n animateOnce?: boolean;\n children?: any;\n};\n\ntype styleProp = {\n animationDuration: string;\n opacity?: number;\n};\n\nexport const AnimationOnScroll = ({\n offset = 150,\n duration = 1,\n style: styleProps,\n className: classNameProps,\n initiallyVisible = false,\n animateIn,\n afterAnimatedIn,\n animateOut,\n delay = 0,\n animatePreScroll = true,\n afterAnimatedOut,\n scrollableParentSelector,\n animateOnce = false,\n children,\n}: Props) => {\n const [classes, setClasses] = useState(animatedClass);\n const [style, setStyle] = useState({\n animationDuration: `${duration}s`,\n opacity: initiallyVisible ? 1 : 0,\n });\n\n const node: { current: any } = useRef(null);\n const animating: { current: boolean } = useRef(false);\n const visibilityRef: {\n current: { onScreen: boolean; inViewport: boolean };\n } = useRef({ onScreen: false, inViewport: false });\n\n const delayedAnimationTORef: { current: any } = useRef(undefined);\n const callbackTORef: { current: any } = useRef(undefined);\n const scrollableParentRef: { current: any } = useRef(scrollableParentRefInitialValue);\n\n const getElementTop = useCallback((elm: any) => {\n let yPos = 0;\n while (elm && elm.offsetTop !== undefined && elm.clientTop !== undefined) {\n yPos += elm.offsetTop + elm.clientTop;\n elm = elm.offsetParent;\n }\n return yPos;\n }, []);\n\n const getScrollPos = useCallback(() => {\n if (scrollableParentRef.current.pageYOffset !== undefined) {\n return scrollableParentRef.current.pageYOffset;\n }\n return scrollableParentRef.current.scrollTop;\n }, [scrollableParentRef]);\n\n const getScrollableParentHeight = useCallback(() => {\n if (scrollableParentRef.current.innerHeight !== undefined) {\n return scrollableParentRef.current.innerHeight;\n }\n return scrollableParentRef.current.clientHeight;\n }, [scrollableParentRef]);\n\n const getViewportTop = useCallback(() => {\n return getScrollPos() + offset;\n }, [offset, getScrollPos]);\n\n const getViewportBottom = useCallback(() => {\n return getScrollPos() + getScrollableParentHeight() - offset;\n }, [offset, getScrollPos, getScrollableParentHeight]);\n\n const isInViewport = useCallback(\n (y) => {\n return y >= getViewportTop() && y <= getViewportBottom();\n },\n [getViewportTop, getViewportBottom]\n );\n\n const isAboveViewport = useCallback(\n (y) => {\n return y < getViewportTop();\n },\n [getViewportTop]\n );\n\n const isBelowViewport = useCallback(\n (y) => {\n return y > getViewportBottom();\n },\n [getViewportBottom]\n );\n\n const inViewport = useCallback(\n (elementTop, elementBottom) => {\n return (\n isInViewport(elementTop) ||\n isInViewport(elementBottom) ||\n (isAboveViewport(elementTop) && isBelowViewport(elementBottom))\n );\n },\n [isInViewport, isAboveViewport, isBelowViewport]\n );\n\n const isAboveScreen = useCallback(\n (y) => {\n return y < getScrollPos();\n },\n [getScrollPos]\n );\n\n const isBelowScreen = useCallback(\n (y) => {\n return y > getScrollPos() + getScrollableParentHeight();\n },\n [getScrollPos, getScrollableParentHeight]\n );\n\n const onScreen = useCallback(\n (elementTop, elementBottom) => {\n return !isAboveScreen(elementBottom) && !isBelowScreen(elementTop);\n },\n [isAboveScreen, isBelowScreen]\n );\n\n const getVisibility = useCallback(() => {\n const elementTop =\n getElementTop(node.current) - getElementTop(scrollableParentRef.current);\n const elementBottom = elementTop + node.current.clientHeight;\n\n return {\n inViewport: inViewport(elementTop, elementBottom),\n onScreen: onScreen(elementTop, elementBottom),\n };\n }, [getElementTop, node, inViewport, onScreen, scrollableParentRef]);\n\n const visibilityHasChanged = useCallback((previousVis, currentVis) => {\n return (\n previousVis.inViewport !== currentVis.inViewport ||\n previousVis.onScreen !== currentVis.onScreen\n );\n }, []);\n\n const animate = useCallback(\n (animation, callback) => {\n delayedAnimationTORef.current = setTimeout(() => {\n animating.current = true;\n setClasses(`${animatedClass} ${animation}`);\n setStyle({ animationDuration: `${duration}s` });\n callbackTORef.current = setTimeout(callback, duration * 1000);\n }, delay);\n },\n [animating, delay, duration]\n );\n\n const animateInTrigger = useCallback(\n (callback) => {\n animate(animateIn, () => {\n if (!animateOnce) {\n setStyle({\n animationDuration: `${duration}s`,\n opacity: 1,\n });\n animating.current = false;\n }\n const vis = getVisibility();\n if (callback) {\n callback(vis);\n }\n });\n },\n [animating, animateIn, animateOnce, duration, animate, getVisibility]\n );\n\n const animateOutTrigger = useCallback(\n (callback) => {\n animate(animateOut, () => {\n setClasses(animatedClass);\n setStyle({ animationDuration: `${duration}s`, opacity: 0 });\n const vis = getVisibility();\n\n if (vis.inViewport && animateIn) {\n animateInTrigger(afterAnimatedIn);\n } else {\n animating.current = false;\n }\n\n if (callback) {\n callback(vis);\n }\n });\n },\n [\n animating,\n animate,\n animateIn,\n duration,\n afterAnimatedIn,\n animateInTrigger,\n animateOut,\n getVisibility,\n ]\n );\n\n const handleScroll = useCallback(() => {\n if (!animating.current) {\n const { current: visibility } = visibilityRef;\n const currentVis = getVisibility();\n if (visibilityHasChanged(visibility, currentVis)) {\n clearTimeout(delayedAnimationTORef.current);\n if (!currentVis.onScreen) {\n setClasses(animatedClass);\n setStyle({\n animationDuration: `${duration}s`,\n opacity: initiallyVisible ? 1 : 0,\n });\n } else if (currentVis.inViewport && animateIn) {\n animateInTrigger(afterAnimatedIn);\n } else if (\n currentVis.onScreen &&\n visibility.inViewport &&\n animateOut &&\n node.current.style.opacity === '1'\n ) {\n animateOutTrigger(afterAnimatedOut);\n }\n visibilityRef.current = currentVis;\n }\n }\n }, [\n afterAnimatedIn,\n afterAnimatedOut,\n animateIn,\n animateInTrigger,\n animateOut,\n duration,\n initiallyVisible,\n visibilityHasChanged,\n animateOutTrigger,\n getVisibility,\n ]);\n\n const listener = useMemo(\n () =>\n throttle(() => {\n handleScroll();\n }, 50),\n [handleScroll]\n );\n\n useEffect(() => {\n if (!serverSide) {\n const parentSelector = scrollableParentSelector;\n scrollableParentRef.current = parentSelector\n ? document.querySelector(parentSelector)\n : window;\n if (\n scrollableParentRef.current &&\n scrollableParentRef.current.addEventListener\n ) {\n scrollableParentRef.current.addEventListener('scroll', listener);\n } else {\n console.warn(\n `Cannot find element by locator: ${scrollableParentSelector}`\n );\n }\n if (animatePreScroll) {\n handleScroll();\n }\n\n return () => {\n clearTimeout(delayedAnimationTORef.current);\n clearTimeout(callbackTORef.current);\n if (window && window.removeEventListener) {\n window.removeEventListener('scroll', listener);\n }\n };\n }\n }, [\n handleScroll,\n scrollableParentSelector,\n scrollableParentRef,\n listener,\n animatePreScroll,\n ]);\n\n return (\n \n {children}\n
\n );\n};\n"]}
--------------------------------------------------------------------------------
/dist/umd/components/index.js:
--------------------------------------------------------------------------------
1 | (function (global, factory) {
2 | if (typeof define === "function" && define.amd) {
3 | define(["exports", "./AnimationOnScroll"], factory);
4 | } else if (typeof exports !== "undefined") {
5 | factory(exports, require("./AnimationOnScroll"));
6 | } else {
7 | var mod = {
8 | exports: {}
9 | };
10 | factory(mod.exports, global.AnimationOnScroll);
11 | global.undefined = mod.exports;
12 | }
13 | })(this, function (exports, _AnimationOnScroll) {
14 | "use strict";
15 |
16 | Object.defineProperty(exports, "__esModule", {
17 | value: true
18 | });
19 | Object.keys(_AnimationOnScroll).forEach(function (key) {
20 | if (key === "default" || key === "__esModule") return;
21 | Object.defineProperty(exports, key, {
22 | enumerable: true,
23 | get: function () {
24 | return _AnimationOnScroll[key];
25 | }
26 | });
27 | });
28 | });
29 | //# sourceMappingURL=index.js.map
--------------------------------------------------------------------------------
/dist/umd/components/index.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"index.js","mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","names":[],"sources":["../../../src/components/index.ts"],"sourcesContent":["export * from './AnimationOnScroll';\n"]}
--------------------------------------------------------------------------------
/dist/umd/index.js:
--------------------------------------------------------------------------------
1 | (function (global, factory) {
2 | if (typeof define === "function" && define.amd) {
3 | define(["exports", "./components"], factory);
4 | } else if (typeof exports !== "undefined") {
5 | factory(exports, require("./components"));
6 | } else {
7 | var mod = {
8 | exports: {}
9 | };
10 | factory(mod.exports, global.components);
11 | global.undefined = mod.exports;
12 | }
13 | })(this, function (exports, _components) {
14 | "use strict";
15 |
16 | Object.defineProperty(exports, "__esModule", {
17 | value: true
18 | });
19 | Object.keys(_components).forEach(function (key) {
20 | if (key === "default" || key === "__esModule") return;
21 | Object.defineProperty(exports, key, {
22 | enumerable: true,
23 | get: function () {
24 | return _components[key];
25 | }
26 | });
27 | });
28 | });
29 | //# sourceMappingURL=index.js.map
--------------------------------------------------------------------------------
/dist/umd/index.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"index.js","mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","names":[],"sources":["../../src/index.tsx"],"sourcesContent":["export * from './components';\n"]}
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-animation-on-scroll",
3 | "version": "5.1.0",
4 | "private": false,
5 | "keywords": [
6 | "reactScrollEffects",
7 | "react scroll",
8 | "reactJS",
9 | "react-component",
10 | "animate",
11 | "animation",
12 | "on",
13 | "scroll",
14 | "reactAnimationOnScroll"
15 | ],
16 | "author": "MetinArslanturk",
17 | "main": "dist/js/index.js",
18 | "module": "dist/esm/index.js",
19 | "types": "dist/js/index.d.ts",
20 | "publishConfig": {
21 | "access": "public",
22 | "tag": "prerelease"
23 | },
24 | "repository": {
25 | "type": "git",
26 | "url": "https://github.com/MetinArslanturk/react-animation-on-scroll"
27 | },
28 | "homepage": "https://www.metinarslanturk.com/react-animation-on-scroll",
29 | "files": [
30 | "dist"
31 | ],
32 | "license": "MIT",
33 | "dependencies": {
34 | "lodash.throttle": "^4.1.1"
35 | },
36 | "scripts": {
37 | "build:lib": "yarn build:babel && yarn build:types && node ./scripts/copyTS.js",
38 | "build:babel": "concurrently \"yarn build:babel:esm && yarn build:babel:umd\" \"yarn build:babel:cjs\"",
39 | "build:babel:cjs": "BABEL_ENV=cjs babel --source-maps --extensions \".js,.ts,.tsx\" src --out-dir dist/js --presets=@babel/env",
40 | "build:babel:esm": "BABEL_ENV=esm babel --source-maps --extensions \".js,.ts,.tsx\" src --out-dir dist/esm",
41 | "build:babel:umd": "BABEL_ENV=umd babel --source-maps --extensions \".js\" dist/esm --out-dir dist/umd --plugins=transform-es2015-modules-umd",
42 | "build:types": "tsc -p tsconfig.gen-dts.json",
43 | "clean": "rimraf dist",
44 | "develop": "yarn build:types && yarn build:babel:esm --skip-initial-build --watch --verbose"
45 | },
46 | "eslintConfig": {
47 | "extends": [
48 | "react-app",
49 | "react-app/jest"
50 | ]
51 | },
52 | "browserslist": {
53 | "production": [
54 | ">0.2%",
55 | "not dead",
56 | "not op_mini all"
57 | ],
58 | "development": [
59 | "last 1 chrome version",
60 | "last 1 firefox version",
61 | "last 1 safari version"
62 | ]
63 | },
64 | "peerDependencies": {
65 | "react": ">= 15.4.1"
66 | },
67 | "devDependencies": {
68 | "@babel/cli": "^7.12.10",
69 | "@babel/core": "^7.12.10",
70 | "@babel/plugin-proposal-export-default-from": "^7.12.1",
71 | "@babel/plugin-transform-typescript": "^7.12.1",
72 | "@babel/preset-env": "^7.12.11",
73 | "@babel/preset-react": "^7.12.10",
74 | "@babel/preset-typescript": "^7.16.7",
75 | "@types/jest": "^26.0.15",
76 | "@types/lodash.throttle": "^4.1.6",
77 | "@types/node": "^12.0.0",
78 | "@types/react": "^16.9.53",
79 | "@types/react-dom": "^16.9.8",
80 | "babel-plugin-transform-es2015-modules-umd": "^6.24.1",
81 | "concurrently": "^5.3.0",
82 | "fs-extra": "^9.0.1",
83 | "typescript": "^4.0.3"
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/scripts/copyTS.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable @typescript-eslint/no-var-requires */
2 | const path = require('path');
3 | const glob = require('glob');
4 | const fse = require('fs-extra');
5 | /* eslint-enable @typescript-eslint/no-var-requires */
6 | const srcDir = path.join('./src');
7 | const distDir = path.join('./dist/js');
8 | const files = glob.sync('**/*.d.ts', {
9 | cwd: srcDir
10 | });
11 | files.forEach(file => {
12 | const from = path.join(srcDir, file);
13 | const to = path.join(distDir, file);
14 | fse.copySync(from, to);
15 | });
16 |
--------------------------------------------------------------------------------
/src/components/AnimationOnScroll.tsx:
--------------------------------------------------------------------------------
1 | import React, {
2 | useMemo,
3 | useCallback,
4 | useState,
5 | useEffect,
6 | useRef,
7 | } from 'react';
8 | import throttle from 'lodash.throttle';
9 |
10 | const animatedClass = 'animate__animated';
11 | const serverSide = typeof window === 'undefined';
12 |
13 | let scrollableParentRefInitialValue: any = undefined;
14 | if (!serverSide) {
15 | scrollableParentRefInitialValue = window;
16 | }
17 |
18 | type Props = {
19 | offset?: number;
20 | duration?: number;
21 | style?: any;
22 | className?: string;
23 | initiallyVisible?: boolean;
24 | animateIn?: string;
25 | afterAnimatedIn?: any;
26 | animateOut?: string;
27 | delay?: number;
28 | animatePreScroll?: boolean;
29 | afterAnimatedOut?: any;
30 | scrollableParentSelector?: string;
31 | animateOnce?: boolean;
32 | children?: any;
33 | };
34 |
35 | type styleProp = {
36 | animationDuration: string;
37 | opacity?: number;
38 | };
39 |
40 | export const AnimationOnScroll = ({
41 | offset = 150,
42 | duration = 1,
43 | style: styleProps,
44 | className: classNameProps,
45 | initiallyVisible = false,
46 | animateIn,
47 | afterAnimatedIn,
48 | animateOut,
49 | delay = 0,
50 | animatePreScroll = true,
51 | afterAnimatedOut,
52 | scrollableParentSelector,
53 | animateOnce = false,
54 | children,
55 | }: Props) => {
56 | const [classes, setClasses] = useState(animatedClass);
57 | const [style, setStyle] = useState({
58 | animationDuration: `${duration}s`,
59 | opacity: initiallyVisible ? 1 : 0,
60 | });
61 |
62 | const node: { current: any } = useRef(null);
63 | const animating: { current: boolean } = useRef(false);
64 | const visibilityRef: {
65 | current: { onScreen: boolean; inViewport: boolean };
66 | } = useRef({ onScreen: false, inViewport: false });
67 |
68 | const delayedAnimationTORef: { current: any } = useRef(undefined);
69 | const callbackTORef: { current: any } = useRef(undefined);
70 | const scrollableParentRef: { current: any } = useRef(scrollableParentRefInitialValue);
71 |
72 | const getElementTop = useCallback((elm: any) => {
73 | let yPos = 0;
74 | while (elm && elm.offsetTop !== undefined && elm.clientTop !== undefined) {
75 | yPos += elm.offsetTop + elm.clientTop;
76 | elm = elm.offsetParent;
77 | }
78 | return yPos;
79 | }, []);
80 |
81 | const getScrollPos = useCallback(() => {
82 | if (scrollableParentRef.current.pageYOffset !== undefined) {
83 | return scrollableParentRef.current.pageYOffset;
84 | }
85 | return scrollableParentRef.current.scrollTop;
86 | }, [scrollableParentRef]);
87 |
88 | const getScrollableParentHeight = useCallback(() => {
89 | if (scrollableParentRef.current.innerHeight !== undefined) {
90 | return scrollableParentRef.current.innerHeight;
91 | }
92 | return scrollableParentRef.current.clientHeight;
93 | }, [scrollableParentRef]);
94 |
95 | const getViewportTop = useCallback(() => {
96 | return getScrollPos() + offset;
97 | }, [offset, getScrollPos]);
98 |
99 | const getViewportBottom = useCallback(() => {
100 | return getScrollPos() + getScrollableParentHeight() - offset;
101 | }, [offset, getScrollPos, getScrollableParentHeight]);
102 |
103 | const isInViewport = useCallback(
104 | (y) => {
105 | return y >= getViewportTop() && y <= getViewportBottom();
106 | },
107 | [getViewportTop, getViewportBottom]
108 | );
109 |
110 | const isAboveViewport = useCallback(
111 | (y) => {
112 | return y < getViewportTop();
113 | },
114 | [getViewportTop]
115 | );
116 |
117 | const isBelowViewport = useCallback(
118 | (y) => {
119 | return y > getViewportBottom();
120 | },
121 | [getViewportBottom]
122 | );
123 |
124 | const inViewport = useCallback(
125 | (elementTop, elementBottom) => {
126 | return (
127 | isInViewport(elementTop) ||
128 | isInViewport(elementBottom) ||
129 | (isAboveViewport(elementTop) && isBelowViewport(elementBottom))
130 | );
131 | },
132 | [isInViewport, isAboveViewport, isBelowViewport]
133 | );
134 |
135 | const isAboveScreen = useCallback(
136 | (y) => {
137 | return y < getScrollPos();
138 | },
139 | [getScrollPos]
140 | );
141 |
142 | const isBelowScreen = useCallback(
143 | (y) => {
144 | return y > getScrollPos() + getScrollableParentHeight();
145 | },
146 | [getScrollPos, getScrollableParentHeight]
147 | );
148 |
149 | const onScreen = useCallback(
150 | (elementTop, elementBottom) => {
151 | return !isAboveScreen(elementBottom) && !isBelowScreen(elementTop);
152 | },
153 | [isAboveScreen, isBelowScreen]
154 | );
155 |
156 | const getVisibility = useCallback(() => {
157 | const elementTop =
158 | getElementTop(node.current) - getElementTop(scrollableParentRef.current);
159 | const elementBottom = elementTop + node.current.clientHeight;
160 |
161 | return {
162 | inViewport: inViewport(elementTop, elementBottom),
163 | onScreen: onScreen(elementTop, elementBottom),
164 | };
165 | }, [getElementTop, node, inViewport, onScreen, scrollableParentRef]);
166 |
167 | const visibilityHasChanged = useCallback((previousVis, currentVis) => {
168 | return (
169 | previousVis.inViewport !== currentVis.inViewport ||
170 | previousVis.onScreen !== currentVis.onScreen
171 | );
172 | }, []);
173 |
174 | const animate = useCallback(
175 | (animation, callback) => {
176 | delayedAnimationTORef.current = setTimeout(() => {
177 | animating.current = true;
178 | setClasses(`${animatedClass} ${animation}`);
179 | setStyle({ animationDuration: `${duration}s` });
180 | callbackTORef.current = setTimeout(callback, duration * 1000);
181 | }, delay);
182 | },
183 | [animating, delay, duration]
184 | );
185 |
186 | const animateInTrigger = useCallback(
187 | (callback) => {
188 | animate(animateIn, () => {
189 | if (!animateOnce) {
190 | setStyle({
191 | animationDuration: `${duration}s`,
192 | opacity: 1,
193 | });
194 | animating.current = false;
195 | }
196 | const vis = getVisibility();
197 | if (callback) {
198 | callback(vis);
199 | }
200 | });
201 | },
202 | [animating, animateIn, animateOnce, duration, animate, getVisibility]
203 | );
204 |
205 | const animateOutTrigger = useCallback(
206 | (callback) => {
207 | animate(animateOut, () => {
208 | setClasses(animatedClass);
209 | setStyle({ animationDuration: `${duration}s`, opacity: 0 });
210 | const vis = getVisibility();
211 |
212 | if (vis.inViewport && animateIn) {
213 | animateInTrigger(afterAnimatedIn);
214 | } else {
215 | animating.current = false;
216 | }
217 |
218 | if (callback) {
219 | callback(vis);
220 | }
221 | });
222 | },
223 | [
224 | animating,
225 | animate,
226 | animateIn,
227 | duration,
228 | afterAnimatedIn,
229 | animateInTrigger,
230 | animateOut,
231 | getVisibility,
232 | ]
233 | );
234 |
235 | const handleScroll = useCallback(() => {
236 | if (!animating.current) {
237 | const { current: visibility } = visibilityRef;
238 | const currentVis = getVisibility();
239 | if (visibilityHasChanged(visibility, currentVis)) {
240 | clearTimeout(delayedAnimationTORef.current);
241 | if (!currentVis.onScreen) {
242 | setClasses(animatedClass);
243 | setStyle({
244 | animationDuration: `${duration}s`,
245 | opacity: initiallyVisible ? 1 : 0,
246 | });
247 | } else if (currentVis.inViewport && animateIn) {
248 | animateInTrigger(afterAnimatedIn);
249 | } else if (
250 | currentVis.onScreen &&
251 | visibility.inViewport &&
252 | animateOut &&
253 | node.current.style.opacity === '1'
254 | ) {
255 | animateOutTrigger(afterAnimatedOut);
256 | }
257 | visibilityRef.current = currentVis;
258 | }
259 | }
260 | }, [
261 | afterAnimatedIn,
262 | afterAnimatedOut,
263 | animateIn,
264 | animateInTrigger,
265 | animateOut,
266 | duration,
267 | initiallyVisible,
268 | visibilityHasChanged,
269 | animateOutTrigger,
270 | getVisibility,
271 | ]);
272 |
273 | const listener = useMemo(
274 | () =>
275 | throttle(() => {
276 | if(node.current) handleScroll();
277 | }, 50),
278 | [handleScroll]
279 | );
280 |
281 | useEffect(() => {
282 | if (!serverSide) {
283 | const parentSelector = scrollableParentSelector;
284 | scrollableParentRef.current = parentSelector
285 | ? document.querySelector(parentSelector)
286 | : window;
287 | if (
288 | scrollableParentRef.current &&
289 | scrollableParentRef.current.addEventListener
290 | ) {
291 | scrollableParentRef.current.addEventListener('scroll', listener);
292 | } else {
293 | console.warn(
294 | `Cannot find element by locator: ${scrollableParentSelector}`
295 | );
296 | }
297 | if (animatePreScroll) {
298 | handleScroll();
299 | }
300 |
301 | return () => {
302 | clearTimeout(delayedAnimationTORef.current);
303 | clearTimeout(callbackTORef.current);
304 | if (window && window.removeEventListener) {
305 | window.removeEventListener('scroll', listener);
306 | }
307 | };
308 | }
309 | }, [
310 | handleScroll,
311 | scrollableParentSelector,
312 | scrollableParentRef,
313 | listener,
314 | animatePreScroll,
315 | ]);
316 |
317 | return (
318 |
323 | {children}
324 |
325 | );
326 | };
327 |
--------------------------------------------------------------------------------
/src/components/index.ts:
--------------------------------------------------------------------------------
1 | export * from './AnimationOnScroll';
2 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | export * from './components';
2 |
--------------------------------------------------------------------------------
/tsconfig.gen-dts.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "declaration": true,
4 | "emitDeclarationOnly": true,
5 | "esModuleInterop": true,
6 | "outDir": "dist/js",
7 | "jsx": "react",
8 | "lib": ["es2017", "dom"],
9 | "module": "commonjs",
10 | "moduleResolution": "node",
11 | "skipLibCheck": true,
12 | "strict": true,
13 | "strictNullChecks": false,
14 | "target": "es5"
15 | },
16 | "include": ["./src/*", "./src/**/*"],
17 | "exclude": [
18 | "./src/**/**.test.tsx",
19 | "./src/**/**.test.ts",
20 | "./src/**/**.stories.ts",
21 | "./src/**/**.stories.tsx",
22 | "./src/**/examples/**"
23 | ]
24 | }
25 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": ["dom", "dom.iterable", "esnext"],
5 | "allowJs": true,
6 | "skipLibCheck": true,
7 | "esModuleInterop": true,
8 | "allowSyntheticDefaultImports": true,
9 | "strict": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "noFallthroughCasesInSwitch": true,
12 | "module": "esnext",
13 | "moduleResolution": "node",
14 | "resolveJsonModule": true,
15 | "isolatedModules": true,
16 | "noEmit": true,
17 | "jsx": "react-jsx"
18 | },
19 | "include": ["src"]
20 | }
21 |
--------------------------------------------------------------------------------