This document details the StarsBackground component that creates an animated starfield background effect.
Location: src/components/Stars/StarsBackground.tsx
The StarsBackground component creates a visually appealing animated background with twinkling stars and occasional shooting stars.
flowchart TD
accTitle: StarsBackground Component Architecture
accDescr: StarsBackground creates a sky container with star elements that have random positions, sizes, twinkle animations, and occasional shooting star effects
StarsBackground[StarsBackground] -->|Creates| Container[Sky Container]
Container -->|Generates| Stars[Star Elements]
Stars -->|Random| Position[Random Positions]
Stars -->|Random| Size[Random Sizes]
Stars -->|Random| Animation[Twinkle Animation]
Stars -->|Occasional| Shooting[Shooting Stars]
Stars are generated on component mount based on window width:
const screenWidth = typeof window !== 'undefined' && window?.innerWidth ? window?.innerWidth : 400;
const maxStars = Math.min(screenWidth, MAX_STARS);
const numberOfStars = Math.floor(Math.random() * (maxStars / 2)) + 10;Each star is a Box with random size, position, and a twinkle animation; the full generation loop lives in createStars() in StarsBackground.tsx.
Star Count: Based on window width (10 to maxStars/2, where maxStars is the screen width capped at 600)
Each star has:
- Position: Random coordinates using viewport units (
vh,vw) for consistent sizing - Size: Random size between 1-6px
- Animation: Infinite twinkling with random duration (0-5 seconds)
- Opacity: Semi-transparent at 0.5 for a softer appearance
- Background: White with 50% opacity (
#ffffff50)
Stars twinkle using CSS animations applied through the sx prop. Each star receives:
- animation:
twinklewith a random duration (Math.random() * 5seconds) andease-in-outtiming, set toinfinite
The twinkle keyframes live in globals.scss, which also defines the shootAway keyframes the shooting-star handler applies. twinkle steps opacity from 0.5 at both ends up to 1 at the midpoint, so a star fades in and out rather than blinking. Because the component names both animations as strings, renaming either keyframe in the stylesheet silently stops the effect.
Stars can become shooting stars on hover or through automatic triggering:
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})`;
setTimeout(() => {
if (target) {
target.setAttribute('data-star-used', 'true');
}
}, shootingStarSpeed * 1000);
};Automatic Shooting Stars:
handleForceStarAnimation() in StarsBackground.tsx drives the unattended loop. It collects every star that has not already been shot, by filtering the data-star-used attribute the hover handler stamps, then branches on how many are left:
- Above
THRESHOLDS.MIN_STARS_FOR_ANIMATION(15): it shoots one star chosen at random, then schedules itself again after a random 1.5 to 6.5 seconds. It clears the previous timeout handle before storing the new one, so the recursion does not leak a timer per iteration. - At or below the threshold: it calls
createStars()instead, discarding the spent field and generating a fresh one, which schedules the next forced shot afterDELAYS.STAR_ANIMATION_INITIALas on first mount.
The pool has to stay larger than the threshold for the random pick to keep finding unused stars without repeating, so the field is replaced and the loop carries on with it. Each generation keys its stars afresh (star-<generation>-<index>), so React mounts new elements rather than reusing the spent ones, whose data-star-used attribute and inline shootAway style are set outside React. Because the generated count starts at 10, a regenerated field can still contain 15 or fewer stars; each such field is replaced again after DELAYS.STAR_ANIMATION_INITIAL.
flowchart TD
accTitle: Automatic Shooting Star Regeneration Cycle
accDescr: Each forced-animation timeout checks the unused stars. More than 15 unused stars leads to shooting one random star and scheduling another check after 1.5 to 6.5 seconds. Fifteen or fewer unused stars leads to creating a fresh field and scheduling another check after the initial delay. Both paths return to the check, which continues until unmount.
Timeout[Forced animation timeout fires] --> Check{More than 15 unused stars?}
Check -->|Yes| Shoot[Shoot one random star]
Shoot --> RandomWait[Schedule another check after 1.5 to 6.5 seconds]
RandomWait --> Timeout
Check -->|No| Regenerate[Create a fresh star field]
Regenerate --> InitialWait[Schedule another check after the initial delay]
InitialWait --> Timeout
sequenceDiagram
accTitle: StarsBackground Mount and Rendering Sequence
accDescr {
Component mounts and asks State to calculate a count from the capped viewport width and generate star properties.
State returns the star array to Component. Component renders the star elements in DOM, DOM applies CSS animations,
and CSS animates the stars in DOM.
}
participant Component
participant State
participant DOM
participant CSS
Component->>Component: Mount
Component->>State: Calculate 10 plus a random value below half the capped width
Component->>State: Generate star properties
State-->>Component: Update stars array
Component->>DOM: Render star elements
DOM->>CSS: Apply animations
CSS->>DOM: Animate stars
The component uses proper ARIA attributes for screen readers:
id='sky'- Unique identifier for the containeraria-label='Starry background'- Descriptive label for assistive technologiescomponent='div'- Renders as a div elementrole='img'- Identifies as an image for screen readerssxprop contains styling with spread operator for dynamic styles
Note: Unlike decorative backgrounds that use aria-hidden='true', this component uses role='img' with an aria-label because it's a significant visual element of the user experience.
- Fixed Position: Uses
position: fixedto avoid reflow - Controlled Overflow:
overflow: hiddenprevents scrollbars - GPU Acceleration: CSS animations use GPU when possible
- Single Generation: Stars generated once on mount, not on every render
- Dynamic Count: Star count based on viewport width for responsive performance
- Memory Cleanup: Every forced-animation timeout, including the first one
createStars()schedules, is held inforceAnimationTimeoutRef, which the effect clears on unmount - Fade Effect: Uses MUI Fade component for smooth appearance
- Analytics Throttling: First hover tracked, subsequent hovers don't spam analytics
Cleanup Logic:
useEffect(() => {
createStars();
// Cleanup timeout on unmount to prevent memory leaks
return () => {
if (forceAnimationTimeoutRef.current) {
clearTimeout(forceAnimationTimeoutRef.current);
}
};
}, []);GeneralLayout renders StarsBackground inside its <main> element, as a sibling of the page children and the PolicyDialogGate; the ConsentBanner sits outside <main>, before the navbar. Placement there rather than at the layout root keeps the starfield inside the flex item that grows to fill the viewport; its own position: fixed then takes it out of flow, so it paints behind the content regardless of where the page is scrolled. See Layouts for the surrounding structure.
Test file: src/components/Stars/StarsBackground.test.tsx
Test Coverage:
- Stars render inside the
role='img'container named "Starry background", whoseskyID the aaaahhhh helper looks up - The generated count uses the viewport width capped at
MAX_STARS, withMath.randomheld fixed - Hovering stars logs the
stars-triggeredanalytics event once, however many are hovered - Once every star is spent, the field regenerates with fresh stars and the forced shooting resumes
- Unmounting before the first forced shooting star leaves no pending timer
To customize the background:
- Star Count: Adjust
Math.floor(Math.random() * (maxStars / 2)) + 10increateStars() - Star Size: Modify
Math.random() * 5 + 1(currently 1-6px) - Animation Speed: Change
Math.random() * 5for twinkle duration - Shooting Star Speed: Adjust
Math.random() * 4 + 1inhandleStarAnimation - Background Color: Inherited from global
bodybackground (#131518) - Star Color: Modify
background: '#ffffff50'instarStyles - Auto-trigger Threshold: Change
THRESHOLDS.MIN_STARS_FOR_ANIMATIONin src/constants/index.ts to control how small the unused pool may get before the field regenerates - Initial Trigger Delay: Change
DELAYS.STAR_ANIMATION_INITIALin src/constants/index.ts to control the pause between the first render and the first forced shooting star - Star Cap: Change
MAX_STARSin src/constants/index.ts to raise or lower the 600-pixel width cap used to generate the random star count
stateDiagram-v2
accTitle: Star Twinkle Animation Life Cycle
accDescr {
The cycle starts at Visible with opacity 1, moves to Fading for a random duration, then Dim with opacity 0.5,
then Brightening for a random duration, and returns to Visible. The cycle has no terminal state.
}
[*] --> Visible: opacity 1
Visible --> Fading: random duration
Fading --> Dim: opacity 0.5
Dim --> Brightening: random duration
Brightening --> Visible: opacity 1
💡 Tip: The starfield creates depth and visual interest without distracting from content. Keep star count reasonable for performance.