Bounce Cards

A fan of tilted photo cards that bounce in with an elastic stagger and push their neighbours aside on hover.

pnpm dlx shadcn@latest add @leo/bounce-cards

Props

NameTypeDefaultDescription
animationDelaynumber | undefined0.5
animationStaggernumber | undefined0.06
classNamestring | undefined-
containerHeightnumber | undefined400
containerWidthnumber | undefined400
easeTypestring | undefinedelastic.out(1, 0.8)
enableHoverboolean | undefinedfalse
imagesstring[] | undefined[215, 275, 330, 20, 150].map((hue, i) => createDefaultCard(hue, i))
transformStylesstring[] | undefined[ "rotate(10deg) translate(-170px)", "rotate(5deg) translate(-85px)", "rotate(-3deg)", "rotate(-10deg) translate(85px)", "rotate(2deg) translate(170px)", ]

Dependencies

  • gsap@^3.13.0

Source

"use client";

import { gsap } from "gsap";
import { useEffect, useRef } from "react";
import { cn } from "@/lib/utils";

// Generated artwork so the default cards load nothing from the network.
function createDefaultCard(hue: number, variant: number): string {
  const h2 = (hue + 55) % 360;
  const sunX = 120 + ((variant * 94) % 180);
  const svg =
    '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400">' +
    `<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="hsl(${hue} 60% 24%)"/><stop offset="1" stop-color="hsl(${h2} 75% 60%)"/></linearGradient></defs>` +
    '<rect width="400" height="400" fill="url(#g)"/>' +
    `<circle cx="${sunX}" cy="130" r="${48 + (variant % 3) * 10}" fill="hsl(${h2} 90% 85%)" fill-opacity="0.85"/>` +
    `<path d="M0 290 Q110 ${200 + variant * 8} 220 280 T400 260 V400 H0Z" fill="hsl(${hue} 45% 14%)" fill-opacity="0.8"/>` +
    "</svg>";
  return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}

const DEFAULT_IMAGES = [215, 275, 330, 20, 150].map((hue, i) => createDefaultCard(hue, i));

export interface BounceCardsProps {
  className?: string;
  images?: string[];
  containerWidth?: number;
  containerHeight?: number;
  animationDelay?: number;
  animationStagger?: number;
  easeType?: string;
  transformStyles?: string[];
  enableHover?: boolean;
}

export function BounceCards({
  className,
  images = DEFAULT_IMAGES,
  containerWidth = 400,
  containerHeight = 400,
  animationDelay = 0.5,
  animationStagger = 0.06,
  easeType = "elastic.out(1, 0.8)",
  transformStyles = [
    "rotate(10deg) translate(-170px)",
    "rotate(5deg) translate(-85px)",
    "rotate(-3deg)",
    "rotate(-10deg) translate(85px)",
    "rotate(2deg) translate(170px)",
  ],
  enableHover = false,
}: BounceCardsProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const container = containerRef.current;
    const ctx = gsap.context(() => {
      gsap.fromTo(
        ".card",
        { scale: 0 },
        {
          scale: 1,
          stagger: animationStagger,
          ease: easeType,
          delay: animationDelay,
        },
      );
    }, containerRef);
    return () => {
      ctx.revert();
      // Hover tweens are created outside the context.
      if (container) gsap.killTweensOf(container.querySelectorAll(".card"));
    };
  }, [animationDelay, animationStagger, easeType]);

  const getNoRotationTransform = (transformStr: string): string => {
    const hasRotate = /rotate\([\s\S]*?\)/.test(transformStr);
    if (hasRotate) {
      return transformStr.replace(/rotate\([\s\S]*?\)/, "rotate(0deg)");
    } else if (transformStr === "none") {
      return "rotate(0deg)";
    } else {
      return `${transformStr} rotate(0deg)`;
    }
  };

  const getPushedTransform = (baseTransform: string, offsetX: number): string => {
    const translateRegex = /translate\(([-0-9.]+)px\)/;
    const match = baseTransform.match(translateRegex);
    if (match) {
      const currentX = parseFloat(match[1]);
      const newX = currentX + offsetX;
      return baseTransform.replace(translateRegex, `translate(${newX}px)`);
    } else {
      return baseTransform === "none"
        ? `translate(${offsetX}px)`
        : `${baseTransform} translate(${offsetX}px)`;
    }
  };

  const pushSiblings = (hoveredIdx: number) => {
    const q = gsap.utils.selector(containerRef);
    if (!enableHover || !containerRef.current) return;

    images.forEach((_, i) => {
      const selector = q(`.card-${i}`);
      gsap.killTweensOf(selector);

      const baseTransform = transformStyles[i] || "none";

      if (i === hoveredIdx) {
        const noRotation = getNoRotationTransform(baseTransform);
        gsap.to(selector, {
          transform: noRotation,
          duration: 0.4,
          ease: "back.out(1.4)",
          overwrite: "auto",
        });
      } else {
        const offsetX = i < hoveredIdx ? -160 : 160;
        const pushedTransform = getPushedTransform(baseTransform, offsetX);

        const distance = Math.abs(hoveredIdx - i);
        const delay = distance * 0.05;

        gsap.to(selector, {
          transform: pushedTransform,
          duration: 0.4,
          ease: "back.out(1.4)",
          delay,
          overwrite: "auto",
        });
      }
    });
  };

  const resetSiblings = () => {
    if (!enableHover || !containerRef.current) return;
    const q = gsap.utils.selector(containerRef);

    images.forEach((_, i) => {
      const selector = q(`.card-${i}`);
      gsap.killTweensOf(selector);

      const baseTransform = transformStyles[i] || "none";
      gsap.to(selector, {
        transform: baseTransform,
        duration: 0.4,
        ease: "back.out(1.4)",
        overwrite: "auto",
      });
    });
  };

  return (
    <div
      className={cn("relative flex items-center justify-center", className)}
      ref={containerRef}
      style={{
        width: containerWidth,
        height: containerHeight,
      }}
    >
      {images.map((src, idx) => (
        // biome-ignore lint/a11y/noStaticElementInteractions: hover only drives a decorative push-aside effect
        <div
          // biome-ignore lint/suspicious/noArrayIndexKey: cards are positional and the transforms are index-addressed
          key={idx}
          className={`card card-${idx} absolute w-[200px] aspect-square border-8 border-white rounded-[30px] overflow-hidden`}
          style={{
            boxShadow: "0 4px 10px rgba(0, 0, 0, 0.2)",
            transform: transformStyles[idx] || "none",
          }}
          onMouseEnter={() => pushSiblings(idx)}
          onMouseLeave={resetSiblings}
        >
          <img className="w-full h-full object-cover" src={src} alt={`card-${idx}`} />
        </div>
      ))}
    </div>
  );
}

export default BounceCards;