Pixel Transition

A pixelated dissolve that swaps one panel for another on hover, focus or tap.

pnpm dlx shadcn@latest add @leo/pixel-transition

Props

NameTypeDefaultDescription
animationStepDurationnumber | undefined0.3
aspectRatiostring | undefined100%
classNamestring | undefined-
firstContentReactNode( <div className="flex h-full w-full flex-col items-center justify-center gap-2" style={{ background: "linear-gradient(135deg, #1e1b4b 0%, #6d28d9 55%, #f472b6 100%)" }} > <span className="text-xs font-semibold uppercase tracking-[0.3em] opacity-70"> Hover to reveal </span> <span className="text-4xl font-black">Pixel</span> </div> )
gridSizenumber | undefined7
onceboolean | undefinedfalse
pixelColorstring | undefinedcurrentColor
secondContentReactNode( <div className="flex h-full w-full flex-col items-center justify-center gap-2" style={{ background: "linear-gradient(135deg, #064e3b 0%, #0d9488 55%, #fde68a 100%)" }} > <span className="text-xs font-semibold uppercase tracking-[0.3em] opacity-70">Revealed</span> <span className="text-4xl font-black">Dissolve</span> </div> )
styleCSSProperties | undefined-

Dependencies

  • gsap@^3.13.0

Source

"use client";

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

// Generated panels so the defaults load nothing from the network.
const DEFAULT_FIRST = (
  <div
    className="flex h-full w-full flex-col items-center justify-center gap-2"
    style={{ background: "linear-gradient(135deg, #1e1b4b 0%, #6d28d9 55%, #f472b6 100%)" }}
  >
    <span className="text-xs font-semibold uppercase tracking-[0.3em] opacity-70">
      Hover to reveal
    </span>
    <span className="text-4xl font-black">Pixel</span>
  </div>
);

const DEFAULT_SECOND = (
  <div
    className="flex h-full w-full flex-col items-center justify-center gap-2"
    style={{ background: "linear-gradient(135deg, #064e3b 0%, #0d9488 55%, #fde68a 100%)" }}
  >
    <span className="text-xs font-semibold uppercase tracking-[0.3em] opacity-70">Revealed</span>
    <span className="text-4xl font-black">Dissolve</span>
  </div>
);

export interface PixelTransitionProps {
  firstContent?: React.ReactNode | string;
  secondContent?: React.ReactNode | string;
  gridSize?: number;
  pixelColor?: string;
  animationStepDuration?: number;
  once?: boolean;
  className?: string;
  style?: CSSProperties;
  aspectRatio?: string;
}

const PixelTransition: React.FC<PixelTransitionProps> = ({
  firstContent = DEFAULT_FIRST,
  secondContent = DEFAULT_SECOND,
  gridSize = 7,
  pixelColor = "currentColor",
  animationStepDuration = 0.3,
  once = false,
  aspectRatio = "100%",
  className,
  style,
}) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const pixelGridRef = useRef<HTMLDivElement | null>(null);
  const activeRef = useRef<HTMLDivElement | null>(null);
  const delayedCallRef = useRef<gsap.core.Tween | null>(null);

  const [isActive, setIsActive] = useState<boolean>(false);

  const [isTouchDevice, setIsTouchDevice] = useState<boolean>(false);

  // Read in an effect: `window` does not exist while the static export renders.
  useEffect(() => {
    setIsTouchDevice(
      "ontouchstart" in window ||
        navigator.maxTouchPoints > 0 ||
        window.matchMedia("(pointer: coarse)").matches,
    );
  }, []);

  useEffect(() => {
    const pixelGridEl = pixelGridRef.current;
    if (!pixelGridEl) return;

    pixelGridEl.innerHTML = "";

    for (let row = 0; row < gridSize; row++) {
      for (let col = 0; col < gridSize; col++) {
        const pixel = document.createElement("div");
        pixel.classList.add("pixelated-image-card__pixel");
        pixel.classList.add("absolute", "hidden");
        pixel.style.backgroundColor = pixelColor;

        const size = 100 / gridSize;
        pixel.style.width = `${size}%`;
        pixel.style.height = `${size}%`;
        pixel.style.left = `${col * size}%`;
        pixel.style.top = `${row * size}%`;

        pixelGridEl.appendChild(pixel);
      }
    }
  }, [gridSize, pixelColor]);

  // Kill in-flight tweens on unmount: their callbacks would otherwise touch detached nodes.
  useEffect(() => {
    const pixelGridEl = pixelGridRef.current;
    return () => {
      delayedCallRef.current?.kill();
      if (pixelGridEl) gsap.killTweensOf(pixelGridEl.querySelectorAll("div"));
    };
  }, []);

  const animatePixels = (activate: boolean): void => {
    setIsActive(activate);

    const pixelGridEl = pixelGridRef.current;
    const activeEl = activeRef.current;
    if (!pixelGridEl || !activeEl) return;

    const pixels = pixelGridEl.querySelectorAll<HTMLDivElement>(".pixelated-image-card__pixel");
    if (!pixels.length) return;

    gsap.killTweensOf(pixels);
    if (delayedCallRef.current) {
      delayedCallRef.current.kill();
    }

    gsap.set(pixels, { display: "none" });

    const totalPixels = pixels.length;
    const staggerDuration = animationStepDuration / totalPixels;

    gsap.to(pixels, {
      display: "block",
      duration: 0,
      stagger: {
        each: staggerDuration,
        from: "random",
      },
    });

    delayedCallRef.current = gsap.delayedCall(animationStepDuration, () => {
      activeEl.style.display = activate ? "block" : "none";
      activeEl.style.pointerEvents = activate ? "none" : "";
    });

    gsap.to(pixels, {
      display: "none",
      duration: 0,
      delay: animationStepDuration,
      stagger: {
        each: staggerDuration,
        from: "random",
      },
    });
  };

  const handleEnter = (): void => {
    if (!isActive) animatePixels(true);
  };
  const handleLeave = (): void => {
    if (isActive && !once) animatePixels(false);
  };
  const handleClick = (): void => {
    if (!isActive) animatePixels(true);
    else if (isActive && !once) animatePixels(false);
  };
  return (
    // biome-ignore lint/a11y/noStaticElementInteractions: hover, focus and tap only drive a decorative dissolve
    // biome-ignore lint/a11y/useKeyWithClickEvents: tap is the touch fallback; keyboard users trigger it through focus
    <div
      ref={containerRef}
      className={cn(
        "bg-[#222] text-white rounded-[15px] border-2 border-white w-[300px] max-w-full relative overflow-hidden",
        className,
      )}
      style={style}
      onMouseEnter={!isTouchDevice ? handleEnter : undefined}
      onMouseLeave={!isTouchDevice ? handleLeave : undefined}
      onClick={isTouchDevice ? handleClick : undefined}
      onFocus={!isTouchDevice ? handleEnter : undefined}
      onBlur={!isTouchDevice ? handleLeave : undefined}
      // biome-ignore lint/a11y/noNoninteractiveTabindex: the wrapper must be focusable so keyboard users can trigger the dissolve
      tabIndex={0}
    >
      <div style={{ paddingTop: aspectRatio }} />

      <div className="absolute inset-0 w-full h-full" aria-hidden={isActive}>
        {firstContent}
      </div>

      <div
        ref={activeRef}
        className="absolute inset-0 w-full h-full z-[2]"
        style={{ display: "none" }}
        aria-hidden={!isActive}
      >
        {secondContent}
      </div>

      <div
        ref={pixelGridRef}
        className="absolute inset-0 w-full h-full pointer-events-none z-[3]"
      />
    </div>
  );
};

export { PixelTransition };
export default PixelTransition;