-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
49 lines (47 loc) · 2.27 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*!
* @gsap/react 2.1.1
* https://gsap.com
*
* Copyright 2008-2024, GreenSock. All rights reserved.
* Subject to the terms at https://gsap.com/standard-license or for
* Club GSAP members, the agreement issued with that membership.
* @author: Jack Doyle, jack@greensock.com
*/
/* eslint-disable */
import { useEffect, useLayoutEffect, useRef } from "react";
import gsap from "gsap";
let useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect,
isConfig = value => value && !Array.isArray(value) && typeof(value) === "object",
emptyArray = [],
defaultConfig = {},
_gsap = gsap; // accommodates situations where different versions of GSAP may be loaded, so a user can gsap.registerPlugin(useGSAP);
export const useGSAP = (callback, dependencies = emptyArray) => {
let config = defaultConfig;
if (isConfig(callback)) {
config = callback;
callback = null;
dependencies = "dependencies" in config ? config.dependencies : emptyArray;
} else if (isConfig(dependencies)) {
config = dependencies;
dependencies = "dependencies" in config ? config.dependencies : emptyArray;
}
(callback && typeof callback !== "function") && console.warn("First parameter must be a function or config object");
const { scope, revertOnUpdate } = config,
mounted = useRef(false),
context = useRef(_gsap.context(() => { }, scope)),
contextSafe = useRef((func) => context.current.add(null, func)),
deferCleanup = dependencies && dependencies.length && !revertOnUpdate;
useIsomorphicLayoutEffect(() => {
callback && context.current.add(callback, scope);
if (!deferCleanup || !mounted.current) { // React renders bottom-up, thus there could be hooks with dependencies that run BEFORE the component mounts, thus cleanup wouldn't occur since a hook with an empty dependency Array would only run once the component mounts.
return () => context.current.revert();
}
}, dependencies);
deferCleanup && useIsomorphicLayoutEffect(() => {
mounted.current = true;
return () => context.current.revert();
}, emptyArray);
return { context: context.current, contextSafe: contextSafe.current };
};
useGSAP.register = core => { _gsap = core; };
useGSAP.headless = true; // doesn't require the window to be registered.