Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
* @author: Jack Doyle, [email protected]
*/
/* eslint-disable */
import { useEffect, useLayoutEffect, useRef } from "react";
import { useEffect, useLayoutEffect, useRef, useState, useCallback } from "react";
import gsap from "gsap";
import Flip from "gsap/Flip";

let useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect,
isConfig = value => value && !Array.isArray(value) && typeof(value) === "object",
Expand Down Expand Up @@ -47,3 +48,40 @@ export const useGSAP = (callback, dependencies = emptyArray) => {
};
useGSAP.register = core => { _gsap = core; };
useGSAP.headless = true; // doesn't require the window to be registered.

export const useFlip = (
target,
options
) => {
const [isFlipped, setIsFlipped] = useState(false)
const flipStateRef = useRef(null)
const scopeRef = useRef(null)

const { props, simple, revertOnUpdate, ...vars } = options

const captureState = useCallback(() => {
const mergedVars = { props, simple, targets: target }
flipStateRef.current = Flip.getState(target, mergedVars)
}, [target, props, simple])

const flip = useCallback(() => {
captureState()
setIsFlipped((prev) => !prev)
}, [captureState])

useGSAP(
() => {
if (flipStateRef.current) {
Flip.from(flipStateRef.current, vars)
flipStateRef.current = null
}
},
{
scope: scopeRef,
dependencies: [isFlipped],
revertOnUpdate: revertOnUpdate,
}
)

return { isFlipped, flip, scopeRef }
}
10 changes: 9 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,12 @@ interface useGSAPConfig {
* @param {Array | useGSAPConfig} [dependencies]
* @returns {useGSAPReturn} Object with "context" and "contextSafe" properties
*/
export function useGSAP(func?: ContextFunc | useGSAPConfig, dependencies?: unknown[] | useGSAPConfig): useGSAPReturn;
export function useGSAP(func?: ContextFunc | useGSAPConfig, dependencies?: unknown[] | useGSAPConfig): useGSAPReturn;

/**
* Flip animation hook for animating React components that encapsulates the GSAP Flip API.
* @param target - The target element to animate.
* @param options - The options for the flip animation.
* @returns {isFlipped: boolean, flip: () => void, scope: ReactRef} - An object containing the flip state, the flip function, and the scope of the animation.
*/
export function useFlip(target: gsap.DOMTarget, options: Flip.FlipStateVars & Flip.FromToVars & { revertOnUpdate?: boolean }): { isFlipped: boolean, flip: () => void, scope: ReactRef };