# TextLoader

> A loading placeholder for numbers, KPIs and short labels that scrambles while it loads, then takes the real value's shape and hands over to it.

TextLoader is Dotquilt's loading placeholder for a number or a short label, such as a KPI. While it loads, its characters cross-fade through look-alikes in the shape of the answer. When the value arrives, the marks slide into the shapes of its real characters, then the value wipes in from left to right as they leave.

## Usage

TextLoader is its own loading region: set its state, and put the value in as its text. The mask is the shape of the answer, such as `$00,000`; without one, the placeholder takes the shape of the current text.

**React**

```tsx title="RevenueTotal.tsx"
'use client';
import { TextLoader } from '@dotquilt/react';
import { useEffect, useState } from 'react';

async function fetchTotal(month: string, signal: AbortSignal): Promise<number> {
  const response = await fetch(`/api/revenue/${month}/total`, { signal });
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  const { total } = await response.json();
  return total;
}

const money = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 0,
});

type Result =
  | { status: 'loading' }
  | { status: 'done'; total: number }
  | { status: 'failed' };

export function RevenueTotal({ month }: { month: string }) {
  const [result, setResult] = useState<Result>({ status: 'loading' });

  useEffect(() => {
    const request = new AbortController();
    setResult({ status: 'loading' });
    fetchTotal(month, request.signal)
      .then((total) => setResult({ status: 'done', total }))
      .catch(() => {
        if (!request.signal.aborted) setResult({ status: 'failed' });
      });
    return () => request.abort();
  }, [month]);

  return (
    <p className="kpi">
      <TextLoader
        aria-label="Revenue this month"
        // The mask is the shape of the answer: the placeholder shows it in marks.
        mask="$00,000"
        state={result.status === 'loading' ? 'pending' : 'ready'}
        cycle={month}
        timing={result.status === 'failed' ? { duration: 0 } : undefined}
      >
        {result.status === 'done'
          ? money.format(result.total)
          : result.status === 'failed'
            ? 'Unavailable'
            : ''}
      </TextLoader>
    </p>
  );
}

// Loads again whenever `month` changes.
export function Dashboard() {
  return <RevenueTotal month="2026-11" />;
}
```

**Native**

```html title="index.html"
<p class="kpi">
  <dotquilt-text-loader
    id="total"
    state="pending"
    mask="$00,000"
    aria-label="Revenue this month"
  ></dotquilt-text-loader>
</p>
```
```ts title="total.ts"
import { registerTextLoader, type TextLoader } from 'dotquilt/text';

registerTextLoader();

const total = document.getElementById('total') as TextLoader | null;
const money = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 0,
});

export async function showTotal(month: string): Promise<void> {
  if (!total) return;
  total.update({ state: 'pending', cycle: month });
  try {
    const response = await fetch(`/api/revenue/${month}/total`);
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    const body: { total: number } = await response.json();
    // A newer request took over while this one was in flight.
    if (total.cycle !== month) return;
    // The loader's own text is the value; the characters lock into it.
    total.textContent = money.format(body.total);
    total.update({ state: 'ready' });
  } catch {
    if (total.cycle !== month) return;
    total.textContent = 'Unavailable';
    total.update({ state: 'ready', timing: { duration: 0 } });
  }
}

void showTotal('2026-11');
```

## Options

| Attribute | React | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `state` | `state` | `pending` \| `refreshing` \| `ready` | `ready` | Whether the value is loading. |
| `cycle` | `cycle` | string | | Names one load, so a stale answer can't settle a newer one. |
| `delay` | `delay` | number (ms) | `0` | Wait this long before showing the placeholder. A response inside it shows no placeholder and no handoff, so fast loads don't flicker. A placeholder already on the page, such as server markup, is never hidden. Up to 10000. |
| `min-display` | `minDisplay` | number (ms) | `0` | Once a placeholder shows, keep it at least this long before handing over, so it never flashes. Up to 10000. |
| `mask` | `mask` | string | the text | The shape the placeholder shows. |
| `mark` | `mark` | `dot` \| `square` \| `dash` | `dot` | Squares make a clean pixel font. Dashes read as hatching here. |
| `speed` | `speed` | number | `1` | How fast the characters change. |
| `pointer-response` | `pointerResponse` | `none` \| `lift` | `none` | `lift` lights the marks around the pointer while the placeholder shows, on devices with a fine pointer. |
| `motion` | `motion` | `system` \| `paused` | `system` | `system` follows the visitor's reduced-motion setting; `paused` stills the characters. |
| | `timing` | `{ duration?, easing? }` | | The handoff's length and curve. `{ duration: 0 }` swaps at once. |

## Animations

Import alternatives from `dotquilt/animations/text` and pass them as `animations`.

| Phase | Default | Also available |
| --- | --- | --- |
| Idle | `scramble`: characters cross-fade about every 280 ms | `scrambleCharacters`: each character changes on its own clock; `scrambleWords`: one word changes at a time, in reading order; `labelPulse`: a calm highlight moves across the placeholder |
| Handoff | `morphWipe`: the marks take the real characters' shapes, then the value wipes in | `lock`: characters lock left to right, each easing in over 300 ms; `printText`: the value prints in from the left as the characters lock; `fade`: the value fades in |

| Animation | Options (default) |
| --- | --- |
| `scramble`, `scrambleCharacters`, `scrambleWords` | `changesPerSecond` 0.5–4 |
| `labelPulse` | `travelPxPerSecond` 20–140 (70) |
| `morphWipe` | `travel` 0.2–0.5 (0.34), `wipeStart` 0.3–0.6 (0.46), `edge` 4–80 px (36) |
| `lock`, `printText` | `staggerMs` 0–60 (40), `reelMs` 0–100 (55), `settleMs` 40–400 (300), `pop` 0–0.3 (0) |
| `fade` | `duration` ms (150) |

## Languages and long text

The character effect draws Latin letters, digits and punctuation (printable ASCII) on a single line, up to 256 characters. Anything else still gets a placeholder: accented or non-Latin letters, right-to-left text, text that wraps, or longer text all show a plain field of marks in the text's place, and the value fades in when it arrives. Wider character support may come in a later release.

## Accessibility

While pending, the scrambled characters are hidden from assistive technology, so give the loader a label that says what is loading. When the value is ready, it is ordinary text.
