forked from webpack/webpack.js.org
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextRotater.jsx
More file actions
89 lines (77 loc) · 2.53 KB
/
TextRotater.jsx
File metadata and controls
89 lines (77 loc) · 2.53 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { clsx } from "clsx";
import PropTypes from "prop-types";
import {
Children,
cloneElement,
memo,
useCallback,
useEffect,
useRef,
useState,
} from "react";
function TextRotater({ children, delay = 0, repeatDelay = 3000, maxWidth }) {
const [currentIndex, setCurrentIndex] = useState(0);
const [contentHeight, setContentHeight] = useState(0);
const [isAnimating, setIsAnimating] = useState(false);
const contentNodeRef = useRef(null);
const heightTimeoutRef = useRef(null);
const animationTimeoutRef = useRef(null);
const repeatTimeoutRef = useRef(null);
const contentCallbackRef = useCallback((node) => {
contentNodeRef.current = node;
}, []);
useEffect(() => {
const calculateHeight = () => {
if (contentNodeRef.current) {
setContentHeight(contentNodeRef.current.clientHeight);
}
};
heightTimeoutRef.current = setTimeout(calculateHeight, 50);
animationTimeoutRef.current = setTimeout(() => setIsAnimating(true), delay);
window.addEventListener("resize", calculateHeight);
return () => {
clearTimeout(heightTimeoutRef.current);
clearTimeout(animationTimeoutRef.current);
clearTimeout(repeatTimeoutRef.current);
window.removeEventListener("resize", calculateHeight);
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const handleTransitionEnd = useCallback(() => {
const childrenCount = Children.count(children);
setCurrentIndex((prev) => (prev + 1) % childrenCount);
setIsAnimating(false);
repeatTimeoutRef.current = setTimeout(() => {
setIsAnimating(true);
}, repeatDelay);
}, [children, repeatDelay]);
const childrenCount = Children.count(children);
const nextChild = cloneElement(children[(currentIndex + 1) % childrenCount]);
return (
<div
className="
relative inline-block overflow-hidden align-bottom px-[0.3em]
"
>
<div
className={clsx(
"inline-flex flex-col text-left",
isAnimating && "text-rotater--slide-up",
)}
onTransitionEnd={handleTransitionEnd}
style={{ height: contentHeight, width: maxWidth }}
>
<span ref={contentCallbackRef}>{children[currentIndex]}</span>
{nextChild}
</div>
</div>
);
}
TextRotater.propTypes = {
children: PropTypes.arrayOf(PropTypes.node),
delay: PropTypes.number,
repeatDelay: PropTypes.number,
// Needed to prevent jump when
// rotating between texts of different widths
maxWidth: PropTypes.number,
};
export default memo(TextRotater);