Transitions

Fade swap

Cross-fades two renders of the same slot. Both nodes stay mounted for the duration, so the outgoing content leaves instead of vanishing.

  • cross-fade
  • status
  • keyed

Preview

Connecting

Reaching the workspace…

Usage

<FadeSwap activeKey={status}>
  <StatusRow status={status} />
</FadeSwap>
"use client";

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

export type SwapDirection = "up" | "down" | "left" | "right" | "none";

export interface FadeSwapProps {
  /** Change this to trigger a swap. */
  activeKey: string | number;
  children: React.ReactNode;
  duration?: number;
  direction?: SwapDirection;
  /** Distance travelled during the swap, in px. */
  distance?: number;
  blur?: boolean;
  className?: string;
}

const offsets: Record<SwapDirection, (d: number) => string> = {
  up: (d) => `translateY(${d}px)`,
  down: (d) => `translateY(${-d}px)`,
  left: (d) => `translateX(${d}px)`,
  right: (d) => `translateX(${-d}px)`,
  none: () => "none",
};

/**
 * Cross-fades between two renders of the same slot. Both the outgoing and
 * incoming node are mounted for `duration`, so nothing pops.
 */
export function FadeSwap({
  activeKey,
  children,
  duration = 280,
  direction = "up",
  distance = 8,
  blur = true,
  className,
}: FadeSwapProps) {
  const [current, setCurrent] = useState({ key: activeKey, node: children });
  const [previous, setPrevious] = useState<{ key: string | number; node: React.ReactNode } | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  useEffect(() => {
    setCurrent((prev) => {
      if (prev.key === activeKey) return { key: activeKey, node: children };
      setPrevious(prev);
      clearTimeout(timer.current);
      timer.current = setTimeout(() => setPrevious(null), duration);
      return { key: activeKey, node: children };
    });
  }, [activeKey, children, duration]);

  useEffect(() => () => clearTimeout(timer.current), []);

  return (
    <div className={cn("relative grid", className)}>
      {previous && (
        <Face key={`out-${previous.key}`} phase="out" {...{ duration, direction, distance, blur }}>
          {previous.node}
        </Face>
      )}
      <Face key={`in-${current.key}`} phase="in" {...{ duration, direction, distance, blur }}>
        {current.node}
      </Face>
    </div>
  );
}

function Face({
  phase,
  duration,
  direction,
  distance,
  blur,
  children,
}: {
  phase: "in" | "out";
  duration: number;
  direction: SwapDirection;
  distance: number;
  blur: boolean;
  children: React.ReactNode;
}) {
  const [mounted, setMounted] = useState(phase === "out");

  useEffect(() => {
    const raf = requestAnimationFrame(() => setMounted(true));
    return () => cancelAnimationFrame(raf);
  }, []);

  const hidden = phase === "in" ? !mounted : true;
  const travel = phase === "in" ? offsets[direction](distance) : offsets[direction](-distance);

  return (
    <div
      className="col-start-1 row-start-1"
      style={{
        opacity: hidden ? 0 : 1,
        transform: hidden ? travel : "none",
        filter: hidden && blur ? "blur(3px)" : "blur(0px)",
        pointerEvents: phase === "out" ? "none" : undefined,
        transition: `opacity ${duration}ms var(--ease-out-quint), transform ${duration}ms var(--ease-out-quint), filter ${duration}ms var(--ease-out-quint)`,
      }}
    >
      {children}
    </div>
  );
}

export default FadeSwap;