Files
SAE-BUT2-frontend/src/components/Background/Background.tsx
T

78 lines
2.5 KiB
TypeScript

import styles from "./Background.module.css";
import { useEffect, useRef, useState, ReactNode } from "react";
interface BackgroundProps {
children?: ReactNode;
className?: string;
}
const Background = ({ children, className }: BackgroundProps) => {
const circlesRef = useRef<(HTMLDivElement | null)[]>([]);
const [theme, setTheme] = useState("light");
const getRandomTranslation = (): { x: number; y: number } => {
const randomX = Math.floor(Math.random() * 100) - 30;
const randomY = Math.floor(Math.random() * 100) - 30;
return { x: randomX, y: randomY };
};
useEffect(() => {
circlesRef.current.forEach((circle) => {
if (circle) {
const { x, y } = getRandomTranslation();
circle.style.setProperty('--random-x', `${x}px`);
circle.style.setProperty('--random-y', `${y}px`);
}
});
}, []);
useEffect(() => {
const updateTheme = () => {
setTheme(localStorage.getItem("theme") || "light");
};
updateTheme();
window.addEventListener("theme-changed", updateTheme);
return () => {
window.removeEventListener("theme-changed", updateTheme);
};
}, []);
return (
<div className={`${styles.backgroundContainer} ${className || ''} ${theme === "light" ? styles.backgroundLight : styles.backgroundDark}`}>
<div
ref={(el) => { circlesRef.current[0] = el; }}
className={`${styles["circle"]} ${styles["circle-1"]}`}
style={{ "--random-x": "0px", "--random-y": "0px" } as React.CSSProperties}
></div>
<div
ref={(el) => { circlesRef.current[1] = el; }}
className={`${styles["circle"]} ${styles["circle-2"]}`}
style={{ "--random-x": "0px", "--random-y": "0px" } as React.CSSProperties}
></div>
<div
ref={(el) => { circlesRef.current[2] = el; }}
className={`${styles["circle"]} ${styles["circle-3"]}`}
style={{ "--random-x": "0px", "--random-y": "0px" } as React.CSSProperties}
></div>
<div
ref={(el) => { circlesRef.current[3] = el; }}
className={`${styles["circle"]} ${styles["circle-4"]}`}
style={{ "--random-x": "0px", "--random-y": "0px" } as React.CSSProperties}
></div>
<div
ref={(el) => { circlesRef.current[4] = el; }}
className={`${styles["circle"]} ${styles["circle-5"]}`}
style={{ "--random-x": "0px", "--random-y": "0px" } as React.CSSProperties}
></div>
{children}
</div>
);
};
export default Background;