-
Notifications
You must be signed in to change notification settings - Fork 0
/
animatedCounter.tsx
242 lines (224 loc) · 6.62 KB
/
animatedCounter.tsx
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import React, {
memo,
useEffect,
useCallback,
useRef,
useState,
CSSProperties,
} from "react";
export interface AnimatedCounterProps {
value?: number;
incrementColor?: string;
decrementColor?: string;
includeDecimals?: boolean;
decimalPrecision?: number;
padNumber?: number;
showColorsWhenValueChanges?: boolean;
includeCommas?: boolean;
containerStyles?: CSSProperties;
digitStyles?: CSSProperties;
className?: string;
}
export interface NumberColumnProps {
digit: string;
delta: string | null;
incrementColor: string;
decrementColor: string;
digitStyles: CSSProperties;
showColorsWhenValueChanges?: boolean;
}
export interface DecimalColumnProps {
isComma: boolean;
digitStyles: CSSProperties;
}
// Decimal element component
const DecimalColumn = ({ isComma, digitStyles }: DecimalColumnProps) => (
<span className={`${isComma ? "ml-[-0.1rem]" : ""}`} style={digitStyles}>
{isComma ? "," : "."}
</span>
);
// Individual number element component
const NumberColumn = memo(
({
digit,
delta,
incrementColor,
decrementColor,
digitStyles,
showColorsWhenValueChanges,
}: NumberColumnProps) => {
const [position, setPosition] = useState<number>(0);
const [animationClass, setAnimationClass] = useState<string | null>(null);
const [movementType, setMovementType] = useState<
"increment" | "decrement" | null
>(null);
const currentDigit = +digit;
const previousDigit = usePrevious(+currentDigit);
const columnContainer = useRef<HTMLDivElement>(null);
const setColumnToNumber = useCallback(
(number: string) => {
if (columnContainer.current) {
setPosition(
columnContainer.current.clientHeight * parseInt(number, 10),
);
}
},
[columnContainer.current?.clientHeight],
);
useEffect(() => {
setAnimationClass(previousDigit !== currentDigit ? delta : "");
if (!showColorsWhenValueChanges) return;
if (delta === "animate-moveUp") {
setMovementType("increment");
} else if (delta === "animate-moveDown") {
setMovementType("decrement");
}
}, [digit, delta, previousDigit, currentDigit]);
// reset movementType after 300ms
useEffect(() => {
setTimeout(() => {
setMovementType(null);
}, 300);
}, [movementType]);
useEffect(() => {
setColumnToNumber(digit);
}, [digit, setColumnToNumber]);
if (digit === "-") {
return <span>{digit}</span>;
}
return (
<div
className="relative tabular-nums overflow-hidden"
ref={columnContainer}
style={
{
maskImage: `linear-gradient(to top, transparent 0%, black min(0.5rem, 20%)),
linear-gradient(to bottom, transparent 0%, black min(0.5rem, 20%))`,
maskComposite: "intersect",
} as CSSProperties
}
>
<div
className={`absolute w-full flex flex-col ${animationClass} ${
animationClass ? "animate-move" : ""
} transition-all duration-150 ease-in-out`}
style={
{
transform: `translateY(-${position}px)`,
"--increment-color": incrementColor,
"--decrement-color": decrementColor,
color: `var(--${movementType}-color)`,
} as CSSProperties
}
>
{[9, 8, 7, 6, 5, 4, 3, 2, 1, 0].reverse().map((num) => (
<div className="flex justify-center items-center" key={num}>
<span style={digitStyles}>{num}</span>
</div>
))}
</div>
<span className="invisible">0</span>
</div>
);
},
(prevProps, nextProps) =>
prevProps.digit === nextProps.digit && prevProps.delta === nextProps.delta,
);
// Main component
const AnimatedCounter = ({
value = 0,
incrementColor = "#32cd32",
decrementColor = "#fe6862",
includeDecimals = true,
decimalPrecision = 2,
includeCommas = false,
containerStyles = {},
digitStyles = {},
padNumber = 0,
className = "",
showColorsWhenValueChanges = true,
}: AnimatedCounterProps) => {
const numArray = formatForDisplay(
Math.abs(value),
includeDecimals,
decimalPrecision,
includeCommas,
padNumber,
);
const previousNumber = usePrevious(value);
const isNegative = value < 0;
let delta: string | null = null;
if (previousNumber !== null) {
if (value > previousNumber) {
delta = "animate-moveUp"; // Tailwind class for increase
} else if (value < previousNumber) {
delta = "animate-moveDown"; // Tailwind class for decrease
}
}
return (
<div
className={`relative flex flex-wrap transition-all tabular-nums ${className}`}
style={{ ...containerStyles }}
>
{/* If number is negative, render '-' feedback */}
{isNegative && (
<NumberColumn
key={"negative-feedback"}
digit={"-"}
delta={delta}
incrementColor={incrementColor}
decrementColor={decrementColor}
digitStyles={digitStyles}
showColorsWhenValueChanges={showColorsWhenValueChanges}
/>
)}
{/* Format integer to NumberColumn components */}
{numArray.map((number: string, index: number) =>
number === "." || number === "," ? (
<DecimalColumn
key={index}
isComma={number === ","}
digitStyles={digitStyles}
/>
) : (
<NumberColumn
key={index}
digit={number}
delta={delta}
incrementColor={incrementColor}
decrementColor={decrementColor}
digitStyles={digitStyles}
showColorsWhenValueChanges={showColorsWhenValueChanges}
/>
),
)}
</div>
);
};
const formatForDisplay = (
number: number,
includeDecimals: boolean,
decimalPrecision: number,
includeCommas: boolean,
padTo: number = 0,
): string[] => {
const decimalCount = includeDecimals ? decimalPrecision : 0;
const parsedNumber = parseFloat(`${Math.max(number, 0)}`).toFixed(
decimalCount,
);
const numberToFormat = includeCommas
? parseFloat(parsedNumber).toLocaleString("en-US", {
minimumFractionDigits: includeDecimals ? decimalPrecision : 0,
})
: parsedNumber;
return numberToFormat.padStart(padTo, "0").split("");
};
// Hook used to track previous value of primary number state in AnimatedCounter & individual digits in NumberColumn
const usePrevious = (value: number | null) => {
const ref = useRef<number | null>(null);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
export default AnimatedCounter;