Repository navigation
Expand file tree
/
Copy pathStarsBackground.tsx
More file actions
170 lines (143 loc) · 4.93 KB
/
Copy pathStarsBackground.tsx
File metadata and controls
170 lines (143 loc) · 4.93 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
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
'use client';
import { logAnalyticsEvent } from '@configs/firebase';
import { DELAYS, MAX_STARS, THRESHOLDS } from '@constants/index';
import { Box, Fade } from '@mui/material';
import { isEmpty } from 'lodash';
import { ReactElement, useEffect, useRef, useState } from 'react';
/**
* Renders a fixed starry background whose stars twinkle and occasionally shoot.
*
* Returns `null` until the first client render, since star placement depends on `window`.
*/
export default function StarsBackground(): ReactElement | null {
// The randomness throughout is cosmetic: it keeps the field from looking tiled.
const [stars, setStars] = useState<ReactElement[] | null>(null);
const [fade, setFade] = useState(false);
// A ref, because each star's hover handler is created once on mount and would otherwise read that render's value forever.
const starsTriggeredRef = useRef(false);
// Held so the pending timeout can be cleared on unmount.
const forceAnimationTimeoutRef = useRef<NodeJS.Timeout | null>(null);
// Part of each star's key, so a regenerated field mounts new nodes rather than reusing spent ones, whose
// `data-star-used` and inline `shootAway` styles are set outside React and would otherwise survive.
const generationRef = useRef(0);
const starStyles = {
background: `#ffffff50`,
borderRadius: '50%',
opacity: 0.5,
position: 'absolute',
transition: 'transform 1s',
};
const handleStarAnimation = (e: React.MouseEvent<HTMLElement> | { target: HTMLElement }): void => {
const target = e.target as HTMLElement;
const shootingStarSpeed = Math.random() * 4 + 1;
target.style.animation = `shootAway ${shootingStarSpeed}s forwards`;
target.style.background = '#fff90050';
target.style.transform = `scale(${Math.random() * 2 + 1})`;
// Marks the star spent once its animation finishes, so it is not picked again.
setTimeout(() => {
if (target) {
target.setAttribute('data-star-used', 'true');
}
}, shootingStarSpeed * 1000);
};
const handleForceStarAnimation = () => {
// Stars that have not been shot yet.
const allStars = Array.from(document.querySelectorAll('[data-testid="star"]')).filter(
(star) => star.getAttribute('data-star-used') !== 'true',
);
// Needs a pool larger than the threshold to keep picking from without repeating.
if (!isEmpty(allStars) && allStars.length > THRESHOLDS.MIN_STARS_FOR_ANIMATION) {
const randomStar = allStars[Math.floor(Math.random() * allStars.length)] as HTMLElement;
if (randomStar) {
handleStarAnimation({ target: randomStar });
}
const randomTime = Math.random() * 5 + 1.5;
// Clearing first prevents an orphaned timeout leaking on every recursion.
if (forceAnimationTimeoutRef.current) {
clearTimeout(forceAnimationTimeoutRef.current);
}
forceAnimationTimeoutRef.current = setTimeout(() => {
handleForceStarAnimation();
}, randomTime * 1000);
} else {
// Regenerates the field once the usable pool is exhausted, which also restarts the forced shooting.
createStars();
}
};
const createStars = () => {
setFade(false);
generationRef.current += 1;
const starsArray: ReactElement[] = [];
const screenWidth = typeof window !== 'undefined' && window?.innerWidth ? window?.innerWidth : 400;
// Capped because star count scales with width, and an unbounded field drops frames.
const maxStars = Math.min(screenWidth, MAX_STARS);
const numberOfStars = Math.floor(Math.random() * (maxStars / 2)) + 10;
for (let i = 0; i < numberOfStars; i += 1) {
const starSize = `${Math.random() * 5 + 1}px`;
const style = {
...starStyles,
animation: `twinkle ${Math.random() * 5}s ease-in-out infinite`,
width: starSize,
height: starSize,
top: `${Math.random() * 100}vh`,
left: `${Math.random() * 100}vw`,
};
starsArray.push(
<Box
key={`star-${generationRef.current}-${i}`}
component='div'
data-testid='star'
onMouseEnter={(e) => {
if (!starsTriggeredRef.current) {
starsTriggeredRef.current = true;
logAnalyticsEvent('stars-triggered', {
name: 'stars-triggered',
type: 'hover',
});
}
handleStarAnimation(e);
}}
sx={style}
/>,
);
}
setStars(starsArray);
setFade(true);
forceAnimationTimeoutRef.current = setTimeout(() => {
handleForceStarAnimation();
}, DELAYS.STAR_ANIMATION_INITIAL);
};
useEffect(() => {
// window is only available after mount.
createStars();
// Cleanup timeout on unmount to prevent memory leaks
return () => {
if (forceAnimationTimeoutRef.current) {
clearTimeout(forceAnimationTimeoutRef.current);
}
};
}, []);
return (
stars && (
<Fade in={fade} timeout={50}>
<Box
key='sky'
aria-label='Starry background'
component='div'
id='sky'
role='img'
sx={{
left: 0,
position: 'fixed',
top: 0,
height: '100vh',
width: '100vw',
overflow: 'hidden',
}}
>
{stars}
</Box>
</Fade>
)
);
}