dxbh-uiGitHub

Scroll Choreo

The heavy alternative to Reveal. One GSAP ScrollTrigger controller for a whole section: batched rises, clip-path media reveals, scrubbed parallax and hairline draws, opted into with data-choreo attributes. Needs gsap.

Preview

Install

npx shadcn@latest add @dxbh-ui/scroll-choreo

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { useState } from "react";
import { ScrollChoreo } from "@/components/ui/scroll-choreo/scroll-choreo";
import { placeholder } from "../photo-rail/placeholder";

export default function ScrollChoreoDemo() {
  // Pass the scroll box as an Element. A string selector is fine in page
  // layouts; the preview needs the element so ScrollTrigger does not have to
  // resolve `#id` against a scoped root.
  const [scroller, setScroller] = useState<HTMLDivElement | null>(null);

  return (
    <div
      ref={setScroller}
      className="h-[28rem] w-full max-w-xl overflow-y-auto rounded-xl border bg-background"
    >
      {scroller ? (
        <ScrollChoreo scroller={scroller} className="space-y-12 px-5 pt-72 pb-32">
          <header className="space-y-3">
            <p data-choreo="rise" className="text-xs font-medium tracking-[0.08em] text-muted-foreground uppercase">
              Chapter one
            </p>
            <h3 data-choreo="rise" className="text-2xl font-semibold tracking-[-0.02em] text-balance">
              A section that unfolds as you read
            </h3>
            <div data-choreo="draw" className="h-px bg-border" />
          </header>
          <figure data-choreo="clip" className="overflow-hidden rounded-xl">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={placeholder(3, 640, 400)} alt="Placeholder landscape" className="aspect-[8/5] w-full object-cover" />
          </figure>
          <div className="grid grid-cols-2 gap-3">
            {["Rises batch and stagger", "Media opens on clip-path", "Parallax scrubs", "Rules draw in"].map((t) => (
              <p key={t} data-choreo="rise" className="rounded-lg border bg-card p-3 text-sm">
                {t}
              </p>
            ))}
          </div>
          <div data-choreo="parallax" data-choreo-amount="10" className="h-48 overflow-hidden rounded-xl">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              data-choreo-target
              src={placeholder(5, 640, 520)}
              alt="Placeholder landscape"
              className="h-[130%] w-full -translate-y-[12%] object-cover"
            />
          </div>
        </ScrollChoreo>
      ) : null}
    </div>
  );
}

Props

PropTypeDefault
data-choreo

Set on descendants to opt in. Space-separate to combine.

"rise" | "clip" | "parallax" | "draw"—
data-choreo-amount

Parallax travel in yPercent each way.

number8
data-choreo-target

The child that moves for parallax, or scales for clip.

attribute—
as

Element to render.

ElementType"div"
scroller

Scroll container to watch when it isn't the window.

Element | string—
refreshKey

Change it to rebuild every trigger, e.g. the pathname.

unknown—

Polish

  • Use Reveal first. Reach for this only when a page needs clip-path reveals, scrub and batching together and ~45kB of gsap is worth it.
  • gsap is a dependency of this item alone; no other dxbh-ui item pulls it in.
  • Scoped to its own subtree instead of the whole document, and opted into with data-choreo so it never collides with Reveal's data-reveal.
  • Content is visible until the controller mounts; initial states are set only inside the no-preference media query.
  • Reduced motion skips everything through gsap.matchMedia, and the data-reduce-motion switch rebuilds it on change. Nothing hides, nothing moves.
  • Media opens with clip-path inset (bottom edge up) while the image settles from 1.08, not 1.12; clip-path and scale props are cleared afterwards.
  • Eases are the nearest gsap built-ins to dxbh-ui's curves: expo.out for enters, power4.inOut for on-screen movement.
  • next/navigation and SplitText removed: refreshKey rebuilds triggers on route change, and a scroller prop supports scroll containers.
  • Client copy, brand and route coupling stripped.

Source

scroll-choreo.tsx
"use client";

import { useEffect, useRef, type ElementType, type HTMLAttributes } from "react";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { cn } from "@/lib/utils";
import { useReducedMotion } from "@/hooks/use-reduced-motion";

/**
 * What a descendant can opt into with `data-choreo`:
 *
 * - `rise`      fades up 24px; elements entering together stagger 60ms
 * - `clip`      media opens from the bottom edge (clip-path inset) while the
 *               image inside settles from 1.08 to 1
 * - `parallax`  drifts a few percent while in view; set the amount with
 *               `data-choreo-amount` (default 8) and the moving child with
 *               `data-choreo-target`
 * - `draw`      a hairline draws from the left (scaleX)
 */
export type ChoreoKind = "rise" | "clip" | "parallax" | "draw";

export type ScrollChoreoProps = HTMLAttributes<HTMLElement> & {
  /** Element to render. Defaults to `div`. */
  as?: ElementType;
  /** Change this to rebuild every trigger, e.g. after a route change. */
  refreshKey?: unknown;
  /** Scroll container to watch when it isn't the window: an element or a selector. */
  scroller?: Element | string;
};

// gsap has no cubic-bezier ease without CustomEase. These are the closest
// built-ins to dxbh-ui's --ease-out and --ease-in-out curves.
const EASE_OUT = "expo.out";
const EASE_IN_OUT = "power4.inOut";

/**
 * One ScrollTrigger controller for everything inside it. Children stay server
 * components and opt in with `data-choreo`. Content is visible until this
 * mounts, and stays visible under reduced motion: nothing is hidden, nothing
 * moves.
 *
 * Reach for `@dxbh-ui/reveal` first. It does fade-ups with CSS alone. Use this
 * when a page needs clip-path media reveals, scrubbed parallax and batching
 * in one timeline, and the ~45kB of gsap is worth it.
 */
export function ScrollChoreo({ as: Tag = "div", refreshKey, scroller, className, children, ...props }: ScrollChoreoProps) {
  const ref = useRef<HTMLElement>(null);
  const reduced = useReducedMotion();

  useEffect(() => {
    const root = ref.current;
    if (!root || reduced) return;
    gsap.registerPlugin(ScrollTrigger);

    // Resolve the scroller against the document. Do not pass a string into
    // ScrollTrigger while matchMedia/context is scoped — GSAP would look for
    // `#id` only under `root`, miss a parent scroll box, and warn/fail.
    const scrollerEl =
      typeof scroller === "string" ? document.querySelector(scroller) : (scroller ?? null);
    if (typeof scroller === "string" && !scrollerEl) return;
    const scrollerOpt = scrollerEl ? { scroller: scrollerEl } : {};

    const q = (kind: ChoreoKind) => Array.from(root.querySelectorAll<HTMLElement>(`[data-choreo~="${kind}"]`));

    // matchMedia re-runs when the OS setting flips and records every tween /
    // trigger so revert() undoes all of them. Scope is not passed: targets are
    // already Element arrays from `root.querySelectorAll`.
    const mm = gsap.matchMedia();
    mm.add("(prefers-reduced-motion: no-preference)", () => {
      const rises = q("rise");
      if (rises.length) {
        gsap.set(rises, { autoAlpha: 0, y: 24 });
        ScrollTrigger.batch(rises, {
          ...scrollerOpt,
          start: "top 90%",
          once: true,
          onEnter: (batch) =>
            gsap.to(batch, { autoAlpha: 1, y: 0, duration: 0.8, stagger: 0.06, ease: EASE_OUT, overwrite: true }),
        });
      }

      for (const el of q("clip")) {
        const media = el.querySelector("img, video, picture, [data-choreo-target]");
        const tl = gsap.timeline({ scrollTrigger: { ...scrollerOpt, trigger: el, start: "top 85%", once: true } });
        tl.fromTo(
          el,
          { clipPath: "inset(100% 0% 0% 0%)" },
          { clipPath: "inset(0% 0% 0% 0%)", duration: 1.1, ease: EASE_IN_OUT, clearProps: "clipPath" },
        );
        if (media) tl.fromTo(media, { scale: 1.08 }, { scale: 1, duration: 1.4, ease: EASE_OUT, clearProps: "scale" }, 0.1);
      }

      for (const el of q("parallax")) {
        const target = el.querySelector<HTMLElement>("[data-choreo-target]") ?? el;
        const amount = Number(el.dataset.choreoAmount) || 8;
        gsap.fromTo(
          target,
          { yPercent: -amount },
          {
            yPercent: amount,
            ease: "none",
            scrollTrigger: { ...scrollerOpt, trigger: el, start: "top bottom", end: "bottom top", scrub: true },
          },
        );
      }

      const draws = q("draw");
      if (draws.length) {
        gsap.set(draws, { scaleX: 0, transformOrigin: "0% 50%" });
        ScrollTrigger.batch(draws, {
          ...scrollerOpt,
          start: "top 92%",
          once: true,
          onEnter: (batch) =>
            gsap.to(batch, {
              scaleX: 1,
              duration: 1,
              stagger: 0.06,
              ease: EASE_IN_OUT,
              // A leftover identity transform paints 1px rules at fractional
              // offsets where faint ones vanish; drop it so they pixel-snap.
              clearProps: "transform,transformOrigin",
            }),
        });
      }
    });

    // Images and fonts shift layout after mount; measure again once settled.
    const refresh = () => ScrollTrigger.refresh();
    let frame = 0;
    if (document.readyState === "complete") frame = requestAnimationFrame(refresh);
    else window.addEventListener("load", refresh, { once: true });

    return () => {
      cancelAnimationFrame(frame);
      window.removeEventListener("load", refresh);
      // Reverts every tween, trigger and inline style set above.
      mm.revert();
    };
  }, [reduced, refreshKey, scroller]);

  return (
    <Tag ref={ref} className={cn(className)} {...props}>
      {children}
    </Tag>
  );
}

Extracted from anchor/src/components/motion/PageMotion.tsx at aec8105.