# Integrate `SplitFlap` from Motion Garden

You are helping me add the **SplitFlap** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** SplitFlap
- **Category:** Text Animations
- **Summary:** A Solari departure board. Every column walks the charset one flap at a time until it reaches its letter, so the word is never revealed. It is arrived at, with a real hinged half falling away as the next one seats behind it.
- **Reference:** https://motion-garden.netlify.app/components/split-flap
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add clsx tailwind-merge
```

## Files to create

3 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/split-flap/split-flap.tsx`

```tsx
"use client";

import { useEffect, useRef } from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";
import { cn } from "@/lib/utils";

export interface SplitFlapProps {
  text?: string;
  charset?: "alphanumeric" | "letters" | "digits" | "departures";
  flapDuration?: number;
  stagger?: number;
  settleBounce?: number;
  cardGap?: number;
  seamWeight?: number;
  specular?: number;
  perspective?: number;
  cardColor?: string;
  glyphColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const CHARSETS: Record<string, string> = {
  alphanumeric: " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
  letters: " ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  digits: " 0123456789",
  departures: " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:.-/",
};

interface Cell {
  root: HTMLDivElement | null;
  topGlyph: HTMLSpanElement | null;
  bottomGlyph: HTMLSpanElement | null;
  leafA: HTMLDivElement | null;
  leafAGlyph: HTMLSpanElement | null;
  leafB: HTMLDivElement | null;
  leafBGlyph: HTMLSpanElement | null;
  sheenA: HTMLDivElement | null;
  sheenB: HTMLDivElement | null;
}

const fall = (t: number) => t * t;

const seat = (t: number, bounce: number) => {
  const s = bounce * 1.7;
  const u = t - 1;
  return 1 + (s + 1) * u * u * u + s * u * u;
};

export default function SplitFlap({
  text = "SHADOW",
  charset = "alphanumeric",
  flapDuration = 90,
  stagger = 45,
  settleBounce = 0.5,
  cardGap = 4,
  seamWeight = 1,
  specular = 0.55,
  perspective = 420,
  cardColor = "#17141d",
  glyphColor = "#e8e4ee",
  paused = false,
  reducedMotion = false,
  className,
}: SplitFlapProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const cells = useRef<Cell[]>([]);
  const drawRef = useRef<((dt: number) => void | false) | null>(null);

  const alphabet = CHARSETS[charset] ?? CHARSETS.alphanumeric;
  const columns = Math.max(1, text.length);

  const state = useRef<{ index: number[]; target: number[]; t: number[]; landed: boolean[]; elapsed: number }>({
    index: [],
    target: [],
    t: [],
    landed: [],
    elapsed: 0,
  });

  const live = useRef({ flapDuration, stagger, settleBounce, specular, alphabet, glyphColor });
  live.current = { flapDuration, stagger, settleBounce, specular, alphabet, glyphColor };

  const loop = useAnimationLoop({
    target: containerRef,
    halted: paused,
    onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
  });

  const setWillChange = (on: boolean) => {
    for (const cell of cells.current) {
      if (cell?.leafA) cell.leafA.style.willChange = on ? "transform" : "";
      if (cell?.leafB) cell.leafB.style.willChange = on ? "transform" : "";
    }
  };

  const writeGlyphs = (i: number) => {
    const cell = cells.current[i];
    if (!cell) return;
    const { alphabet: set } = live.current;
    const cur = set[state.current.index[i] % set.length] ?? " ";
    const next = set[(state.current.index[i] + 1) % set.length] ?? " ";
    if (cell.topGlyph) cell.topGlyph.textContent = next;
    if (cell.bottomGlyph) cell.bottomGlyph.textContent = cur;
    if (cell.leafAGlyph) cell.leafAGlyph.textContent = cur;
    if (cell.leafBGlyph) cell.leafBGlyph.textContent = next;
  };

  const settleCell = (i: number) => {
    const cell = cells.current[i];
    if (!cell) return;
    const { alphabet: set } = live.current;
    const glyph = set[state.current.index[i] % set.length] ?? " ";
    if (cell.topGlyph) cell.topGlyph.textContent = glyph;
    if (cell.bottomGlyph) cell.bottomGlyph.textContent = glyph;
    if (cell.leafAGlyph) cell.leafAGlyph.textContent = glyph;
    if (cell.leafBGlyph) cell.leafBGlyph.textContent = glyph;
    if (cell.leafA) cell.leafA.style.transform = "rotateX(0deg)";
    if (cell.leafB) cell.leafB.style.transform = "rotateX(0deg)";
    if (cell.sheenA) cell.sheenA.style.opacity = "0";
    if (cell.sheenB) cell.sheenB.style.opacity = "0";
  };

  useEffect(() => {
    const set = alphabet;
    const s = state.current;
    const upper = text.toUpperCase();

    for (let i = 0; i < columns; i++) {
      const ch = upper[i] ?? " ";
      const found = set.indexOf(ch);
      s.target[i] = found >= 0 ? found : 0;
      if (s.index[i] === undefined) s.index[i] = 0;
      s.t[i] = 0;
      s.landed[i] = reducedMotion || s.index[i] === s.target[i];
    }
    s.index.length = columns;
    s.target.length = columns;
    s.elapsed = 0;

    if (reducedMotion) {
      for (let i = 0; i < columns; i++) {
        s.index[i] = s.target[i];
        s.landed[i] = true;
        settleCell(i);
      }
      setWillChange(false);
      return;
    }

    for (let i = 0; i < columns; i++) {
      if (s.landed[i]) settleCell(i);
      else writeGlyphs(i);
    }
    setWillChange(true);
    loop.start();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [text, alphabet, columns, reducedMotion]);

  useEffect(() => {
    drawRef.current = (dt) => {
      const s = state.current;
      const { flapDuration: ms, stagger: gap, settleBounce: bounce, specular: spec } = live.current;
      s.elapsed += dt * 1000;

      let moving = false;

      for (let i = 0; i < s.index.length; i++) {
        const cell = cells.current[i];
        if (!cell) continue;
        if (s.landed[i]) continue;

        if (s.elapsed < i * gap) {
          moving = true;
          continue;
        }

        moving = true;
        s.t[i] += (dt * 1000) / Math.max(16, ms);

        while (s.t[i] >= 1) {
          s.t[i] -= 1;
          s.index[i] = (s.index[i] + 1) % live.current.alphabet.length;
          if (s.index[i] === s.target[i]) {
            s.landed[i] = true;
            s.t[i] = 0;
            settleCell(i);
            break;
          }
          writeGlyphs(i);
        }
        if (s.landed[i]) continue;

        const t = s.t[i];
        let a = 0;
        let b = 0;
        if (t < 0.5) {
          a = -90 * fall(t / 0.5);
          b = 90;
        } else {
          a = -90;
          b = 90 * (1 - seat((t - 0.5) / 0.5, bounce));
        }

        if (cell.leafA) cell.leafA.style.transform = `rotateX(${a}deg)`;
        if (cell.leafB) cell.leafB.style.transform = `rotateX(${b}deg)`;
        if (cell.sheenA) cell.sheenA.style.opacity = `${Math.abs(Math.sin((a * Math.PI) / 180)) * spec}`;
        if (cell.sheenB) cell.sheenB.style.opacity = `${Math.abs(Math.sin((b * Math.PI) / 180)) * spec}`;
      }

      if (!moving) {
        setWillChange(false);
        return false;
      }
    };
    return () => {
      drawRef.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const topFace = `linear-gradient(180deg, rgba(255,255,255,0.10), rgba(255,255,255,0)), ${cardColor}`;
  const bottomFace = `linear-gradient(180deg, rgba(0,0,0,0.35), rgba(0,0,0,0)), ${cardColor}`;
  const seam = `${seamWeight}px solid rgba(0,0,0,0.9)`;
  const catchLight = "1px solid rgba(255,255,255,0.09)";
  const sheen = "linear-gradient(180deg, rgba(255,255,255,0.55), rgba(255,255,255,0))";

  return (
    <div
      ref={containerRef}
      className={cn("inline-flex", className)}
      style={{ gap: cardGap, color: glyphColor }}
      role="img"
      aria-label={text}
    >
      {Array.from({ length: columns }, (_, i) => (
        <div
          key={i}
          ref={(el) => {
            cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), root: el };
          }}
          className="relative h-[1.4em] w-[0.95em] shrink-0 rounded-[0.08em]"
          style={{ perspective: `${perspective}px` }}
        >
          <div
            className="absolute inset-x-0 top-0 h-1/2 overflow-hidden rounded-t-[0.08em]"
            style={{ background: topFace, borderBottom: seam }}
          >
            <span
              ref={(el) => {
                cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), topGlyph: el };
              }}
              className="absolute inset-x-0 top-0 flex h-[200%] items-center justify-center"
            />
          </div>

          <div
            className="absolute inset-x-0 bottom-0 h-1/2 overflow-hidden rounded-b-[0.08em]"
            style={{ background: bottomFace, borderTop: catchLight }}
          >
            <span
              ref={(el) => {
                cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), bottomGlyph: el };
              }}
              className="absolute inset-x-0 -top-full flex h-[200%] items-center justify-center"
            />
          </div>

          <div
            ref={(el) => {
              cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), leafA: el };
            }}
            className="absolute inset-x-0 top-0 h-1/2 origin-bottom overflow-hidden rounded-t-[0.08em]"
            style={{ background: topFace, borderBottom: seam }}
          >
            <span
              ref={(el) => {
                cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), leafAGlyph: el };
              }}
              className="absolute inset-x-0 top-0 flex h-[200%] items-center justify-center"
            />
            <div
              ref={(el) => {
                cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), sheenA: el };
              }}
              className="pointer-events-none absolute inset-0"
              style={{ background: sheen, opacity: 0 }}
            />
          </div>

          <div
            ref={(el) => {
              cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), leafB: el };
            }}
            className="absolute inset-x-0 bottom-0 h-1/2 origin-top overflow-hidden rounded-b-[0.08em]"
            style={{ background: bottomFace, borderTop: catchLight }}
          >
            <span
              ref={(el) => {
                cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), leafBGlyph: el };
              }}
              className="absolute inset-x-0 -top-full flex h-[200%] items-center justify-center"
            />
            <div
              ref={(el) => {
                cells.current[i] = { ...(cells.current[i] ?? ({} as Cell)), sheenB: el };
              }}
              className="pointer-events-none absolute inset-0"
              style={{ background: sheen, opacity: 0 }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```

### 3. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `charset` | `"alphanumeric" | "letters" | "digits" | "departures"` | `"alphanumeric"` | Which glyphs a column walks through on its way to its letter. This is what sets the length of the journey — a digits-only board lands almost immediately, a full alphanumeric one takes its time. |
| `flapDuration` | `number` | `90` | Time for one flap. Under about 50ms the column reads as a blur rather than as discrete cards, which throws away the whole point of the mechanism. Range 30–300 ms. |
| `stagger` | `number` | `45` | Delay between one column starting and the next. At 0 the board moves as one slab; a small offset is what makes it sound like a board even in silence. Range 0–300 ms. |
| `settleBounce` | `number` | `0.5` | Overshoot as a flap hits its stop. This is follow-through: the card has mass, so it arrives slightly past and comes back. Range 0–1.5. |
| `cardGap` | `number` | `4` | Space between one card stack and the next. Range 0–16 px. |
| `seamWeight` | `number` | `1` | The hairline across the middle of a card, where the two halves meet. Kept in the DOM rather than drawn, so the browser snaps it to the pixel grid instead of letting it shimmer on fractional scaling. Range 0–4 px. |
| `specular` | `number` | `0.55` | Light sweeping across a moving flap, brightest edge-on. Without it a flip reads as a rectangle changing shape rather than as a surface turning. Range 0–1. |
| `perspective` | `number` | `420` | Depth of the foreshortening. Lower exaggerates the hinge and puts the viewer close to the board; higher flattens it toward a straight fold. Range 120–1200 px. |
| `cardColor` | `string (hex)` | `"#17141d"` | Body of the cards. Its own material, not a themed surface — a departure board is a dark object in any room. |
| `glyphColor` | `string (hex)` | `"#e8e4ee"` | The printed characters. |

## Usage

```tsx
import SplitFlap from "@/components/registry/split-flap/split-flap";

<SplitFlap
  charset="alphanumeric"
  flapDuration={90}
  stagger={45}
  settleBounce={0.5}
  cardGap={4}
  seamWeight={1}
  specular={0.55}
  perspective={420}
  cardColor="#17141d"
  glyphColor="#e8e4ee"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
