# Dia Text

Text written in by a band of colour sweeping across it, then left in its base colour. A web port of the Dia-style text reveal, with no dependencies.

Live demo: https://bearerop.in/craft/dia-text

## Install

### 1. Copy and paste the following code into your project.

One file, React only. The sweep runs on the Web Animations API, so there is nothing to install.

#### Usage

```tsx
import { DiaText } from "@/components/craft/dia-text";

export default function MyPage() {
  return (
    <div className="flex min-h-screen flex-col items-center justify-center gap-10 p-8">
      {/* One line, revealed once. Change `text` and it sweeps again. */}
      <DiaText text="Hello, world" className="text-5xl font-semibold" />

      {/* Several lines, cycling */}
      <DiaText
        text={["Design engineering", "Details, on purpose", "Built end to end"]}
        loop
        className="text-5xl font-semibold"
      />

      {/* Your own colours and pace */}
      <DiaText
        text="Monochrome works too"
        sweepColors={["#ffffff", "#8a8a8a"]}
        baseColor="#111111"
        duration={900}
        bandRatio={0.5}
        className="text-3xl"
      />
    </div>
  );
}
```

#### Source

```tsx
"use client";

import { isValidElement, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";

export interface DiaTextProps {
  /**
   * One line, or several to cycle through when `loop` is on. A line is a
   * string, or inline markup such as `<>Built <em>end to end</em></>`.
   */
  text: ReactNode | readonly ReactNode[];
  /** The colours inside the moving band, leading edge last. */
  sweepColors?: readonly string[];
  /** What the text settles into behind the band. Defaults to the surrounding text colour. */
  baseColor?: string;
  /** Length of one sweep, in ms. */
  duration?: number;
  /** Wait before the sweep starts, in ms. */
  delay?: number;
  /** Replay the sweep; with several texts, swap to the next one each time. */
  loop?: boolean;
  /** Pause between a sweep ending and the next beginning, in ms. */
  loopDelay?: number;
  /** Width of the colour band as a fraction of the text's width. */
  bandRatio?: number;
  /** Set to false to render the text hidden until you flip it on. */
  autoPlay?: boolean;
  className?: string;
  style?: CSSProperties;
  onSweepEnd?: (index: number) => void;
}

const SWEEP_COLORS = ["#c679c4", "#fa3d1d", "#ffb005", "#e1e1fe", "#0358f7"] as const;
const SWEEP_EASING = "cubic-bezier(0.65, 0, 0.35, 1)";
const SWAP_EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
const EXIT_MS = 260;
const ENTER_MS = 380;
const SWAP_SHIFT = 12;

// Runs before paint in the browser, so the text is never seen in its final colour first
const useBeforePaint = typeof window === "undefined" ? useEffect : useLayoutEffect;

/**
 * The text is the mask; behind it lies one wide gradient: base colour, then
 * the colour band, then nothing. Sliding that gradient across reveals the text
 * through the band and leaves it in the base colour.
 */
function sweepGradient(colors: readonly string[], base: string, bandRatio: number) {
  const total = 2 + bandRatio;
  const bandStart = (1 / total) * 100;
  const bandEnd = ((1 + bandRatio) / total) * 100;
  const stops = colors.map((color, index) => {
    const at =
      colors.length === 1
        ? (bandStart + bandEnd) / 2
        : bandStart + (index / (colors.length - 1)) * (bandEnd - bandStart);
    return `${color} ${at.toFixed(3)}%`;
  });
  return `linear-gradient(90deg, ${base} 0%, ${base} ${bandStart.toFixed(3)}%, ${stops.join(", ")}, transparent ${bandEnd.toFixed(3)}%, transparent 100%)`;
}

/** The words of a line, whatever markup it carries: what decides whether the line has changed. */
function plainText(node: ReactNode): string {
  if (typeof node === "string" || typeof node === "number") return String(node);
  if (Array.isArray(node)) return node.map(plainText).join("");
  if (isValidElement<{ children?: ReactNode }>(node)) return plainText(node.props.children);
  return "";
}

/**
 * Text that is written in by a band of colour sweeping across it, the way Dia
 * reveals a line. Works on any text, wrapped or not; the type comes from
 * `className` or the surrounding element.
 */
export function DiaText({
  text,
  sweepColors = SWEEP_COLORS,
  baseColor = "currentColor",
  duration = 1500,
  delay = 0,
  loop = false,
  loopDelay = 500,
  bandRatio = 0.34,
  autoPlay = true,
  className,
  style,
  onSweepEnd,
}: DiaTextProps) {
  const texts: readonly ReactNode[] = Array.isArray(text) ? text : [text];
  const count = texts.length;
  // Compared by their words, so inline JSX that is rebuilt every render does not restart the sweep
  const textKey = texts.map(plainText).join("\u0000");
  const isMulti = count > 1;

  const [index, setIndex] = useState(0);
  /** Bumped to replay the sweep when the text itself has not changed. */
  const [cycle, setCycle] = useState(0);
  const element = useRef<HTMLSpanElement>(null);
  const onEnd = useRef(onSweepEnd);
  onEnd.current = onSweepEnd;

  useEffect(() => setIndex(0), [textKey]);

  const label = texts[index] ?? texts[0] ?? "";

  useBeforePaint(() => {
    const node = element.current;
    if (!node || !autoPlay) return;

    let timer: ReturnType<typeof setTimeout> | undefined;
    const running: Animation[] = [];
    const next = () => {
      if (isMulti) setIndex((current) => (current + 1) % count);
      setCycle((current) => current + 1);
    };

    // No motion wanted, or no Web Animations: show the text, and still rotate it if asked to
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches || typeof node.animate !== "function") {
      onEnd.current?.(index);
      if (loop && isMulti) timer = setTimeout(next, duration + loopDelay);
      return () => clearTimeout(timer);
    }

    if (isMulti) {
      running.push(
        node.animate(
          [
            { opacity: 0, transform: `translateY(${SWAP_SHIFT}px)` },
            { opacity: 1, transform: "translateY(0)" },
          ],
          { duration: ENTER_MS, easing: SWAP_EASING }
        )
      );
    }

    const sweep = node.animate([{ backgroundPositionX: "100%" }, { backgroundPositionX: "0%" }], {
      duration,
      delay,
      easing: SWEEP_EASING,
      fill: "both",
    });
    running.push(sweep);

    sweep.onfinish = () => {
      onEnd.current?.(index);
      if (!loop) return;
      timer = setTimeout(() => {
        if (!isMulti) return next();
        const exit = node.animate(
          [
            { opacity: 1, transform: "translateY(0)" },
            { opacity: 0, transform: `translateY(${-SWAP_SHIFT}px)` },
          ],
          { duration: EXIT_MS, easing: SWAP_EASING, fill: "forwards" }
        );
        running.push(exit);
        exit.onfinish = next;
      }, loopDelay);
    };

    return () => {
      clearTimeout(timer);
      for (const animation of running) animation.cancel();
    };
  }, [textKey, index, cycle, autoPlay, duration, delay, loop, loopDelay, isMulti, count]);

  return (
    <span
      ref={element}
      data-index={index}
      className={className}
      style={{
        display: "inline-block",
        // The text is only painted inside this box, so it needs room for what hangs outside the
        // line: italic and swash overhang at the sides, descenders and accents above and below
        paddingInline: "0.12em",
        paddingBlock: "0.2em",
        backgroundImage: sweepGradient(sweepColors, baseColor, bandRatio),
        backgroundSize: `${(2 + bandRatio) * 100}% 100%`,
        backgroundRepeat: "no-repeat",
        // At rest the base colour shows; the sweep starts from 100%, where the gradient is empty
        backgroundPositionX: autoPlay ? "0%" : "100%",
        WebkitBackgroundClip: "text",
        backgroundClip: "text",
        // The fill is cleared, not `color`: currentColor in the gradient must still mean the text colour
        WebkitTextFillColor: "transparent",
        ...style,
      }}
    >
      {label}
    </span>
  );
}

export default DiaText;
```

## Features

- **Works on real text**: The text is the mask, so it stays selectable, readable by screen readers and free to wrap
- **Sweeps again when the text changes**
- **Cycles through several lines**: Pass an array with loop; each line slides out and the next is swept in
- **Custom colours, band width and pace**
- **Respects reduced motion**: The text simply appears
- **No dependencies**

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| text | string \| string[] | - | The line to reveal, or several to cycle through |
| sweepColors | string[] | 5 colours | Colours inside the moving band |
| baseColor | string | currentColor | What the text settles into |
| duration | number | 1500 | Length of one sweep, in ms |
| delay | number | 0 | Wait before the sweep starts, in ms |
| loop | boolean | false | Replay, moving to the next text if there are several |
| loopDelay | number | 500 | Pause between sweeps, in ms |
| bandRatio | number | 0.34 | Band width as a fraction of the text width |
| autoPlay | boolean | true | Set false to hold the text hidden |
| onSweepEnd | (index) => void | - | Called when a sweep finishes |
