# Text Scramble

> Characters scramble through random glyphs before resolving to the final text, creating a cipher-decoding effect on mount.

Docs: https://ui.cnippet.dev/motion/text-animations/text-scramble

```tsx
import { TextScramble } from "@/registry/default/motion/text-scramble";

export default function TextScrambleHero() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <TextScramble
        as="h1"
        className="max-w-2xl text-center font-bold text-4xl text-foreground tracking-tight sm:text-5xl"
        duration={1.2}
        speed={0.03}
      >
        The future of UI is in motion
      </TextScramble>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @cnippet/text-scramble
```

**Manual**

1. Install the following dependencies:

```bash
npm install motion
```

2. Copy and paste the following code into your project.

`components/motion/text-scramble.tsx`

```tsx
"use client";

import { type MotionProps, motion, useReducedMotion } from "motion/react";
import { type JSX, useEffect, useRef, useState } from "react";

const DEFAULT_CHARS =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

export type TextScrambleProps = {
  children: string;
  duration?: number;
  speed?: number;
  characterSet?: string;
  as?: React.ElementType;
  className?: string;
  trigger?: boolean;
  onScrambleComplete?: () => void;
} & MotionProps;

export function TextScramble({
  children,
  duration = 0.8,
  speed = 0.04,
  characterSet = DEFAULT_CHARS,
  className,
  as: Component = "p",
  trigger = true,
  onScrambleComplete,
  ...props
}: TextScrambleProps) {
  const MotionComponent = motion.create(
    Component as keyof JSX.IntrinsicElements,
  );
  const reduceMotion = useReducedMotion();
  const [scrambledText, setScrambledText] = useState<string | null>(null);
  const onScrambleCompleteRef = useRef(onScrambleComplete);
  onScrambleCompleteRef.current = onScrambleComplete;

  useEffect(() => {
    if (!trigger) return;
    if (reduceMotion) {
      onScrambleCompleteRef.current?.();
      return;
    }

    const steps = Math.ceil(duration / speed);
    let step = 0;

    const interval = setInterval(() => {
      const progress = step / steps;
      let scrambled = "";

      for (let i = 0; i < children.length; i++) {
        if (children[i] === " ") {
          scrambled += " ";
          continue;
        }
        if (progress * children.length > i) {
          scrambled += children[i];
        } else {
          scrambled +=
            characterSet[Math.floor(Math.random() * characterSet.length)];
        }
      }

      step++;

      if (step > steps) {
        clearInterval(interval);
        setScrambledText(null);
        onScrambleCompleteRef.current?.();
      } else {
        setScrambledText(scrambled);
      }
    }, speed * 1000);

    return () => clearInterval(interval);
  }, [trigger, children, duration, speed, characterSet, reduceMotion]);

  return (
    <MotionComponent className={className} {...props}>
      {scrambledText ?? children}
    </MotionComponent>
  );
}
```

3. Update the import paths to match your project setup.

## Usage

```tsx
import { TextScramble } from "@/components/motion/text-scramble";
```

```tsx
<TextScramble duration={0.8}>Your text here</TextScramble>
```

## Anatomy

```tsx
<TextScramble duration={0.8}>Your text here</TextScramble> {/* <p> that scrambles, then settles */}
```

## Good to know

- `children` must be a plain string.
- It plays as soon as it mounts. Set `trigger={false}` and switch it to `true` to replay or delay it.
- `duration` and `speed` are in seconds. `onScrambleComplete` fires when the text settles.
- Screen readers may read the scrambled characters. Add an `aria-label` with the final text if that matters.
- When the user has turned on reduced motion, the text shows straight away with no scramble; `onScrambleComplete` still fires.

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `string` | — | The target text to resolve to |
| `duration` | `number` | `0.8` | Total scramble duration in seconds |
| `speed` | `number` | `0.04` | Interval between scramble steps in seconds |
| `characterSet` | `string` | A–Z, a–z, 0–9 | Characters to scramble through |
| `trigger` | `boolean` | `true` | Set `false` to pause, `true` to play |
| `as` | `React.ElementType` | `"p"` | HTML tag for the container |
| `onScrambleComplete` | `() => void` | — | Callback fired when scramble finishes |
| `className` | `string` | — | Class applied to the container |

## Examples

### Hero Headline

Auto-triggers on mount and resolves the full headline left-to-right. Increase `duration` for longer text.

```tsx
import { TextScramble } from "@/registry/default/motion/text-scramble";

export default function TextScrambleHero() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <TextScramble
        as="h1"
        className="max-w-2xl text-center font-bold text-4xl text-foreground tracking-tight sm:text-5xl"
        duration={1.2}
        speed={0.03}
      >
        The future of UI is in motion
      </TextScramble>
    </div>
  );
}
```

### Click to Retrigger

Manually controls the `trigger` prop by briefly resetting it, letting users replay the scramble on demand.

```tsx
"use client";

import { useState } from "react";
import { TextScramble } from "@/registry/default/motion/text-scramble";

export default function TextScrambleTrigger() {
  const [trigger, setTrigger] = useState(true);

  function handleClick() {
    setTrigger(false);
    setTimeout(() => setTrigger(true), 50);
  }

  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-6 px-6">
      <TextScramble
        as="p"
        className="font-medium font-mono text-foreground text-xl uppercase tracking-widest"
        duration={0.8}
        speed={0.04}
        trigger={trigger}
      >
        Decrypt on demand
      </TextScramble>
      <button
        className="rounded-md border border-border bg-background px-4 py-1.5 text-muted-foreground text-sm transition-colors hover:bg-accent hover:text-foreground"
        onClick={handleClick}
        type="button"
      >
        Scramble again
      </button>
    </div>
  );
}
```

### Scrambled Stats

Multiple `TextScramble` instances with staggered `duration` values create a sequential reveal across a stats row.

```tsx
import { TextScramble } from "@/registry/default/motion/text-scramble";

const features = [
  { label: "Components", value: "164+" },
  { label: "Bundle size", value: "~4kb" },
  { label: "TypeScript", value: "100%" },
];

export default function TextScrambleStats() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div className="grid grid-cols-3 divide-x divide-border">
        {features.map(({ label, value }, i) => (
          <div
            className="flex flex-col items-center gap-1 px-8 py-4"
            key={label}
          >
            <TextScramble
              as="span"
              className="font-bold text-3xl text-foreground tabular-nums"
              duration={0.6 + i * 0.2}
              speed={0.03}
            >
              {value}
            </TextScramble>
            <span className="text-muted-foreground text-sm">{label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
```
