Change when new random shapes background is generated

This commit is contained in:
Amy 2021-08-26 01:04:38 -04:00
parent 4cf69f2070
commit afece801bf
1 changed files with 24 additions and 6 deletions

View File

@ -1,29 +1,47 @@
import { useWindowDimension } from "hooks/useWindowDimension";
import { useRouter } from "next/router";
import React, { CSSProperties, useEffect, useRef, useState } from "react";
import { Image } from "./Image";
import styles from "./ShapesBackground.module.css";
const MOBILE_WIDTH = 768;
interface Props {
getConfig?: GetShapesConfig;
}
export function ShapesBackground({ getConfig }: Props) {
const [config, setConfig] = useState<ShapesConfig>({});
const [prevWidth, setPrevWidth] = useState<number>(-1);
const [prevRoute, setPrevRoute] = useState<string>("");
const { width, height } = useWindowDimension();
const shapesContainerRef = useRef<HTMLDivElement>(null);
const router = useRouter();
useEffect(() => {
const width = shapesContainerRef.current?.clientWidth;
const height = shapesContainerRef.current?.clientHeight;
const containerWidth = shapesContainerRef.current?.offsetWidth;
const containerHeight = shapesContainerRef.current?.offsetHeight;
if (width == null || height == null) {
if (
containerWidth == null ||
containerHeight == null ||
!(
router.pathname === "/" ||
router.pathname !== prevRoute ||
prevWidth < 0 ||
(prevWidth <= MOBILE_WIDTH && MOBILE_WIDTH < width) ||
(prevWidth > MOBILE_WIDTH && MOBILE_WIDTH >= width)
)
) {
return;
}
setConfig(getConfig?.(width, height) ?? {});
}, [getConfig, width, height]);
setPrevWidth(width);
setPrevRoute(router.pathname);
setConfig(getConfig?.(containerWidth, containerHeight) ?? {});
}, [getConfig, width, height, prevWidth, prevRoute, router.pathname]);
return (
<div className={styles.shapesContainer} ref={shapesContainerRef}>
@ -171,7 +189,7 @@ const shapesBySize = {
// Used to generate random shapes in the margins
export const defaultGetShapesConfig = ((pageWidth, pageHeight) => {
if (window.innerWidth <= 768) {
if (window.innerWidth <= MOBILE_WIDTH) {
return mobileShapesConfig;
}