All files / Rindu/components/Carousel Carousel.tsx

82.69% Statements 43/52
71.42% Branches 20/28
55.55% Functions 5/9
89.36% Lines 42/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      19x   19x 19x 19x             6x         10x 10x 10x 10x 10x 10x 10x   10x   6x 4x 4x 4x 4x 4x   4x   4x 4x 4x   4x     4x 4x 4x       6x 6x 6x 6x       10x 2x                                                                                       22x 10x 10x 10x 10x 10x 10x 10x             12x                                                                                                                        
import {
  Children,
  cloneElement,
  HTMLAttributes,
  isValidElement,
  PropsWithChildren,
  ReactElement,
  useEffect,
  useId,
  useRef,
  useState,
} from "react";
 
import { Heading } from "components";
import { Chevron } from "components/icons";
import { useOnSmallScreen } from "hooks";
 
interface CarouselProps {
  title?: string;
  gap: number;
}
 
export default function Carousel({
  title,
  gap = 24,
  children,
}: PropsWithChildren<CarouselProps>): ReactElement | null {
  const [timesMoveCarousel, setTimesMoveCarousel] = useState(0);
  const totalItems = Children.count(children);
  const containerRef = useRef<HTMLDivElement>(null);
  const carouselRef = useRef<HTMLElement>(null);
  const [maxMoves, setMaxMoves] = useState(0);
  const isSmallScreen = useOnSmallScreen();
  const id = useId();
 
  useEffect(() => {
    function updateSize() {
      if (!carouselRef.current || !containerRef.current) return;
      const carousel = carouselRef.current;
      const itemWidth = carousel.children[0].clientWidth + gap;
      const container = containerRef.current;
      const containerWidth = container.offsetWidth;
      const itemsInMainContainer = Math.floor(containerWidth / itemWidth);
      const maximumMoves =
        Math.ceil(totalItems / (itemsInMainContainer || 1)) - 1;
      const shouldMove =
        timesMoveCarousel >= 0 && timesMoveCarousel <= maximumMoves;
      const spaceToMove = timesMoveCarousel * itemsInMainContainer * itemWidth;
      setMaxMoves(maximumMoves);
 
      Iif (timesMoveCarousel > maximumMoves) {
        setTimesMoveCarousel(maximumMoves);
      }
      carousel.style.transform = `translateX(-${spaceToMove}px)`;
      if (shouldMove) {
        carouselRef.current.style.transform = `translateX(-${spaceToMove}px)`;
      }
    }
 
    window.addEventListener("resize", updateSize);
    updateSize();
    return () => {
      window.removeEventListener("resize", updateSize);
    };
  }, [gap, timesMoveCarousel, totalItems]);
 
  if (totalItems === 0) {
    return null;
  }
 
  return (
    <div className="carousel-container" ref={containerRef}>
      <div className="header">
        <Heading id={`title-${id}`} number={2}>
          {title}
        </Heading>
        <div className="button-container">
          {maxMoves > 0 && !isSmallScreen ? (
            <>
              <button
                type="button"
                aria-label="Previous"
                disabled={timesMoveCarousel <= 0}
                onClick={() => {
                  Iif (timesMoveCarousel <= 0) return;
                  setTimesMoveCarousel((prev) => prev - 1);
                }}
              >
                <Chevron rotation={"0deg"} />
              </button>
              <button
                type="button"
                aria-label="Next"
                disabled={timesMoveCarousel >= maxMoves}
                onClick={() => {
                  Iif (timesMoveCarousel >= maxMoves) return;
                  setTimesMoveCarousel((prev) => prev + 1);
                }}
              >
                <Chevron rotation={"180deg"} />
              </button>
            </>
          ) : null}
        </div>
      </div>
      <section
        ref={carouselRef}
        className="carousel-content"
        aria-describedby={`title-${id}`}
      >
        {Children.map(children, (child, number) => {
          if (isValidElement(child) && carouselRef.current) {
            const itemWidth = carouselRef.current.children[0].clientWidth + gap;
            const containerWidth = containerRef.current?.offsetWidth ?? 0;
            const itemsInMainContainer = Math.floor(containerWidth / itemWidth);
            const minRange = itemsInMainContainer * timesMoveCarousel;
            const maxRange = itemsInMainContainer * (timesMoveCarousel + 1);
            const shouldFocus = number < maxRange && number >= minRange;
            return cloneElement(child, {
              ...child.props,
              tabIndex: shouldFocus ? undefined : -1,
              "aria-hidden": shouldFocus ? "false" : "true",
              style: { scrollSnapAlign: "start" },
            } as Partial<unknown> & HTMLAttributes<HTMLElement>);
          }
          return child;
        })}
      </section>
      <style jsx>{`
        .carousel-container {
          margin: 10px 0 30px;
        }
        section.carousel-content > :global(*) {
          width: min-content;
        }
        .header {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        section {
          display: flex;
          grid-gap: ${gap}px;
          margin: 20px 0 50px 0;
          transition: 400ms ease-in;
        }
        .button-container {
          display: flex;
          gap: 16px;
        }
        button {
          display: flex;
          align-items: center;
          background-color: rgba(0, 0, 0, 0.7);
          border: none;
          border-radius: 50%;
          color: #fff;
          height: 32px;
          justify-content: center;
          position: relative;
          width: 32px;
          cursor: pointer;
        }
        button:disabled {
          cursor: not-allowed;
          opacity: 0.6;
        }
 
        @media (max-width: 768px) {
          section {
            overflow-x: scroll;
            scroll-snap-type: x mandatory;
            -webkit-overflow-scrolling: touch;
            width: 100%;
            grid-gap: 0;
            margin: 20px 0;
          }
          section::-webkit-scrollbar {
            display: none;
          }
        }
      `}</style>
    </div>
  );
}