| 1 |
import { BaseControl, Button } from '@wordpress/components'; |
| 2 |
import { useDebounce } from '@wordpress/compose'; |
| 3 |
import { useCallback, useEffect, useRef } from '@wordpress/element'; |
| 4 |
|
| 5 |
const { |
| 6 |
Motion: { animate, spring }, |
| 7 |
} = window; |
| 8 |
|
| 9 |
export default function TransitionPreview(props) { |
| 10 |
const { label, options } = props; |
| 11 |
const buttonRef = useRef(); |
| 12 |
const buttonSquareRef = useRef(); |
| 13 |
const animationRef = useRef(); |
| 14 |
|
| 15 |
// Reset animation. |
| 16 |
function resetAnimation() { |
| 17 |
if (animationRef?.current) { |
| 18 |
animationRef.current.stop(); |
| 19 |
} |
| 20 |
|
| 21 |
if (buttonSquareRef.current) { |
| 22 |
animationRef.current = animate( |
| 23 |
buttonSquareRef.current, |
| 24 |
{ x: 0 }, |
| 25 |
{ duration: 0 } |
| 26 |
); |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
// Run animation. |
| 31 |
function runAnimation(opts) { |
| 32 |
resetAnimation(); |
| 33 |
|
| 34 |
setTimeout(() => { |
| 35 |
if (buttonRef.current && buttonSquareRef.current) { |
| 36 |
const animationOptions = {}; |
| 37 |
|
| 38 |
if (opts?.type === 'easing') { |
| 39 |
animationOptions.easing = opts.easing; |
| 40 |
animationOptions.duration = opts.duration; |
| 41 |
} else if (opts?.type === 'spring') { |
| 42 |
animationOptions.easing = spring({ |
| 43 |
stiffness: opts.stiffness, |
| 44 |
damping: opts.damping, |
| 45 |
mass: opts.mass, |
| 46 |
}); |
| 47 |
} |
| 48 |
|
| 49 |
const computedStyle = window.getComputedStyle( |
| 50 |
buttonRef.current |
| 51 |
); |
| 52 |
let translateX = buttonRef.current.clientWidth; |
| 53 |
translateX -= buttonSquareRef.current.clientWidth; |
| 54 |
translateX -= |
| 55 |
parseFloat(computedStyle.paddingLeft) + |
| 56 |
parseFloat(computedStyle.paddingRight); |
| 57 |
|
| 58 |
animationRef.current = animate( |
| 59 |
buttonSquareRef.current, |
| 60 |
{ |
| 61 |
x: `${translateX}px`, |
| 62 |
}, |
| 63 |
animationOptions |
| 64 |
); |
| 65 |
} |
| 66 |
}, 1); |
| 67 |
} |
| 68 |
|
| 69 |
// eslint-disable-next-line react-hooks/exhaustive-deps |
| 70 |
const runAnimationDebounce = useCallback( |
| 71 |
useDebounce(runAnimation, 1000), |
| 72 |
[] |
| 73 |
); |
| 74 |
|
| 75 |
useEffect(() => { |
| 76 |
// Reset animation. |
| 77 |
resetAnimation(); |
| 78 |
|
| 79 |
runAnimationDebounce(options); |
| 80 |
}, [buttonRef, buttonSquareRef, options, runAnimationDebounce]); |
| 81 |
|
| 82 |
return ( |
| 83 |
<BaseControl |
| 84 |
id={label} |
| 85 |
label={label} |
| 86 |
className="ghostkit-component-transition-preview-wrapper" |
| 87 |
> |
| 88 |
<Button |
| 89 |
className="ghostkit-component-transition-preview" |
| 90 |
ref={buttonRef} |
| 91 |
onClick={(e) => { |
| 92 |
e.preventDefault(); |
| 93 |
runAnimation(options); |
| 94 |
}} |
| 95 |
> |
| 96 |
<span ref={buttonSquareRef} /> |
| 97 |
</Button> |
| 98 |
</BaseControl> |
| 99 |
); |
| 100 |
} |
| 101 |
|