<TextMorph />

Text continuity for interfaces on the web.

A plugin changes how torph cuts text up, how it moves, or both. Numbers and grouped replacements are plugins too, on by default. Each one below is its whole source.

blur

Letter by letter, text rises into focus and blurs away upwards.

import { blur } from "torph/plugins/blur";

<TextMorph plugins={[blur()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

// Fitted to the reference numeric-text effect: 1.5% overshoot, settled in about half a second.
const SPRING = { stiffness: 265, damping: 26 };

export type BlurOptions = {
  /** How out of focus a letter is as it arrives and leaves, as a CSS length. */
  amount?: string;
  /** How far a letter rises as it arrives and leaves, as a CSS length. */
  rise?: string;
  /** Each letter's delay after the one before, as a share of the duration. */
  stagger?: number;
};

/** Letter by letter, text rises into focus and blurs away upwards. */
export function blur({
  amount = "0.1em",
  rise = "0.35em",
  stagger = 0.15,
}: BlurOptions = {}): TorphPlugin {
  const filter = `blur(${amount})`;
  // Spread over at most 30% of the duration, however many letters move on that side.
  const delay = (index: number, count: number, duration: number) =>
    index * Math.min(stagger, 0.3 / Math.max(1, count - 1)) * duration;
  const away = (x: number, y: number, side: "+" | "-") =>
    `translate(${x}px, calc(${y}px ${side} ${rise})) scale(0.6) rotate(2deg)`;

  return {
    name: "blur",
    key: `${amount}\u0000${rise}\u0000${stagger}`,
    ease: SPRING,
    letters: true,
    // A word that would slide across the line blurs out and back in where it lands instead.
    maxShift: 3,
    // Taken from group replacement, so a long replaced run still goes letter by letter.
    runs: { claim: () => true },
    animate: {
      text: {
        enter: (box, { delta, from, duration, ease, index, arriving }) => [
          box.animate(
            [
              {
                transform: away(
                  delta.x + (from?.tx ?? 0),
                  delta.y + (from?.ty ?? 0),
                  "+",
                ),
                filter,
                opacity: 0,
              },
              { transform: "none", filter: "none", opacity: 1 },
            ],
            {
              duration,
              delay: delay(index, arriving, duration),
              easing: ease,
              fill: "backwards",
            },
          ),
        ],
        exit: (box, { delta, duration, ease, index, leaving }) => [
          box.animate(
            {
              transform: away(delta.x, delta.y, "-"),
              filter,
              opacity: 0,
              offset: 1,
            },
            {
              duration,
              delay: delay(index, leaving, duration),
              easing: ease,
              fill: "both",
            },
          ),
        ],
      },
    },
  };
}

words

A changed word swaps whole, instead of morphing the letters it shares.

import { words } from "torph/plugins/words";

<TextMorph plugins={[words()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

/** A changed word swaps whole, instead of morphing the letters it shares. */
export function words(): TorphPlugin {
  return {
    name: "words",
    claim: () => true,
    segment: (word, { id }) => [{ id: id(word), string: word }],
  };
}

scramble

Letter by letter, arriving text scrambles into place and leaving text scrambles away.

import { scramble } from "torph/plugins/scramble";

<TextMorph plugins={[scramble()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type ScrambleOptions = {
  /** Drawn from while a letter scrambles. */
  glyphs?: string;
  /** How often the glyphs change, in ms. */
  rate?: number;
  /** Each letter's start after the one before, as a share of the duration. */
  stagger?: number;
};

/** Letter by letter, arriving text scrambles into place and leaving text scrambles away. */
export function scramble({
  glyphs = "abcdefghijklmnopqrstuvwxyz0123456789",
  rate = 40,
  stagger = 0.08,
}: ScrambleOptions = {}): TorphPlugin {
  const random = (text: string) =>
    text.replace(
      /\S/g,
      () => glyphs[Math.floor(Math.random() * glyphs.length)]!,
    );
  // Spread over at most half the duration, however many letters move on that side.
  const start = (index: number, count: number, duration: number) =>
    index * Math.min(stagger, 0.5 / Math.max(1, count - 1)) * duration;

  /** Shows random glyphs in `box` from `from` ms until `until` ms, then hands back. */
  const scrambling = (
    box: HTMLElement,
    text: string,
    from: number,
    until: number,
    signal: AbortSignal,
  ) =>
    new Promise<void>((resolve) => {
      const began = performance.now();
      let last = -Infinity;
      const tick = (now: number) => {
        // The next morph owns the box now, and its text with it.
        if (signal.aborted) return resolve();
        const at = now - began;
        if (at >= until) return resolve();
        if (at >= from && now - last >= rate) {
          last = now;
          box.textContent = random(text);
        }
        requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    });

  return {
    name: "scramble",
    key: `${glyphs}\u0000${rate}\u0000${stagger}`,
    letters: true,
    // Taken from group replacement, so a long replaced run still goes letter by letter.
    runs: { claim: () => true },
    animate: {
      text: {
        // Hidden until its turn, then scrambling until it locks on, in reading order.
        enter: (box, { mover, index, arriving, duration, signal }) => {
          const text = mover.textContent ?? "";
          const appear = start(index, arriving, duration);
          box.animate([{ opacity: 0 }, { opacity: 0 }], { duration: appear });
          return scrambling(
            mover,
            text,
            appear,
            appear + duration / 2,
            signal,
          ).then(() => {
            if (!signal.aborted) mover.textContent = text;
          });
        },
        // Scrambling from the start, each dropping out in turn; the engine removes it after.
        exit: (box, { index, leaving, duration, signal }) =>
          scrambling(
            box,
            box.textContent ?? "",
            0,
            start(index, leaving, duration) + duration / 4,
            signal,
          ),
      },
    },
  };
}

flap

Like a departure board, each changing letter flips round to the new one.

import { flap } from "torph/plugins/flap";

<TextMorph plugins={[flap()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type FlapOptions = {
  /** The drum each flap turns through, in order. */
  glyphs?: string;
  /** The most flips a letter makes, however far round the drum it has to go. */
  flips?: number;
};

/** Like a departure board, each place flips round its drum to the new letter, and nothing slides. */
export function flap({
  glyphs = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:",
  flips = 6,
}: FlapOptions = {}): TorphPlugin {
  /** The letters a flap shows on its way from one to the other, ending on the new one. */
  const drum = (from: string, to: string) => {
    const end = glyphs.indexOf(to.toUpperCase());
    if (end < 0) return [to];
    let at = Math.max(0, glyphs.indexOf(from.toUpperCase()));
    const turns: string[] = [];
    while (at !== end) {
      at = (at + 1) % glyphs.length;
      turns.push(at === end ? to : glyphs[at]!);
    }
    return turns.slice(-flips);
  };

  /** Shows each face in turn, folding down from the top; `add`, so it rides on any slide. */
  const turn = (
    face: HTMLElement,
    from: string,
    duration: number,
    signal: AbortSignal,
  ) => {
    const faces = drum(from, face.textContent ?? "");
    const each = duration / faces.length;
    return faces.reduce<Promise<unknown>>(
      (turned, letter) =>
        turned.then(() => {
          // The next morph owns the box now, and its text with it.
          if (signal.aborted) return;
          face.textContent = letter;
          return face.animate(
            [
              { transform: "perspective(20em) rotateX(-90deg)" },
              { transform: "perspective(20em) rotateX(0deg)" },
            ],
            { duration: each, easing: "ease-out", composite: "add" },
          ).finished;
        }),
      Promise.resolve(),
    );
  };

  return {
    name: "flap",
    key: `${glyphs}\u0000${flips}`,
    // Every word, so each keeps its places: letter i of the old word is letter i of the new.
    claim: () => true,
    segment: (word, { previous, id }) =>
      Array.from(word, (letter, i) => ({
        id: previous?.[i]?.id ?? id(),
        string: letter,
      })),
    // Any word flips to the one in its place.
    affinity: () => 1,
    runs: { claim: () => true },
    animate: {
      text: {
        persist: (box, { mover, was, delta, from, duration, ease, signal }) => {
          const x = delta.x + (from?.tx ?? 0);
          const y = delta.y + (from?.ty ?? 0);
          const slide =
            x || y
              ? [
                  box.animate(
                    [
                      { transform: `translate(${x}px, ${y}px)` },
                      { transform: "none" },
                    ],
                    { duration, easing: ease, fill: "backwards" },
                  ),
                ]
              : [];
          if (was === undefined || was === mover.textContent) return slide;
          return Promise.all([
            ...slide.map((a) => a.finished),
            turn(mover, was, duration, signal),
          ]);
        },
        enter: (_box, { mover, duration, signal }) =>
          turn(mover, " ", duration, signal),
        exit: (box, { duration }) => [
          box.animate(
            {
              transform: "perspective(20em) rotateX(90deg)",
              opacity: 0,
              offset: 1,
            },
            { duration: duration / 2, easing: "ease-in", fill: "both" },
          ),
        ],
      },
    },
  };
}

typewriter

Old text backspaces from the end, then the new text types in, caret and all.

import { typewriter } from "torph/plugins/typewriter";

<TextMorph plugins={[typewriter()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type TypewriterOptions = {
  /** Time per keystroke, in ms. */
  keystroke?: number;
};

/** Old text backspaces from the end, then the new text types in, caret and all. */
export function typewriter({
  keystroke = 45,
}: TypewriterOptions = {}): TorphPlugin {
  // A sliver of shadow past the box's right edge is the caret.
  const caret = "0.06em 0 0 0 currentColor";

  return {
    name: "typewriter",
    key: String(keystroke),
    letters: true,
    runs: { claim: () => true },
    animate: {
      text: {
        // Last letter first, each holding the caret until it goes.
        exit: (box, { index, leaving }) => [
          box.animate(
            [
              { boxShadow: caret, opacity: 1 },
              { boxShadow: caret, opacity: 1, offset: 0.999 },
              { boxShadow: "none", opacity: 0 },
            ],
            {
              duration: keystroke,
              delay: (leaving - 1 - index) * keystroke,
              fill: "forwards",
            },
          ),
        ],
        // Once the old text is gone, in reading order, the caret passing along.
        enter: (box, { index, leaving }) => [
          box.animate(
            [
              { opacity: 0 },
              { boxShadow: caret, opacity: 1, offset: 0.001 },
              { boxShadow: caret, opacity: 1, offset: 0.999 },
              { boxShadow: "none", opacity: 1 },
            ],
            {
              duration: keystroke,
              delay: (leaving + index) * keystroke,
              fill: "backwards",
            },
          ),
        ],
      },
    },
  };
}

tokens

Identifiers and paths change at their joins, so the parts that stay put stay put.

import { tokens } from "torph/plugins/tokens";

<TextMorph plugins={[tokens()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

// camelCase humps, acronyms, digit runs, and every separator on its own.
const TOKEN = /[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+|[^A-Za-z\d]/g;
// Only words with an identifier's or a path's joins; a plain word with a comma stays text.
const JOINED = /[a-z\d][A-Z]|[_/]|\w[.:-]\w/;

const split = (word: string) => word.match(TOKEN) ?? [word];

/** In order, the old token that each new one keeps, by index into `old`. */
function kept(old: string[], next: string[]) {
  let from = 0;
  return next.map((token) => {
    const at = old.indexOf(token, from);
    if (at >= 0) from = at + 1;
    return at;
  });
}

/** Identifiers and paths change at their joins: getUserName → getUserEmail keeps getUser. */
export function tokens(): TorphPlugin {
  return {
    name: "tokens",
    claim: (word) => JOINED.test(word),
    segment: (word, { previous = [], id }) => {
      const next = split(word);
      return kept(
        previous.map((s) => s.string),
        next,
      ).map((at, i) =>
        at >= 0
          ? { id: previous[at]!.id, string: next[i]! }
          : { id: id(next[i]), string: next[i]! },
      );
    },
    // Long identifiers share too few letters for the default, but plenty of tokens.
    affinity: (a, b) => {
      if (!JOINED.test(a) || !JOINED.test(b)) return null;
      const [x, y] = [split(a), split(b)];
      return (
        kept(x, y).filter((at) => at >= 0).length / Math.max(x.length, y.length)
      );
    },
  };
}

odometer

Figures count like a car's odometer, every wheel turning the way the value went.

import { odometer } from "torph/plugins/odometer";

<TextMorph plugins={[odometer()]}>{value}</TextMorph>
import type {
  KindSpec,
  MotionContext,
  TorphPlugin,
} from "torph";

// A figure, with a few affix characters either side: "$1,299", "42%", "-3.5".
const FIGURE = /^[^\d\s]{0,3}\d[\d.,'\u00A0\u202F]*[^\d\s]{0,3}$/;
// Prefix, the run from the first digit to the last, suffix.
const PARTS = /^(\D*)(\d(?:.*\d)?)(\D*)$/u;

const parts = (text: string) => {
  const [, before = "", core = "", after = ""] = PARTS.exec(text) ?? [];
  return [before, core, after].map((part) => Array.from(part));
};

/** Pairs `next` with `old` place for place, from the left or, for figures, from the right. */
function align<T>(next: string[], old: T[], fromRight: boolean) {
  const shift = fromRight ? old.length - next.length : 0;
  return next.map((_, i) => old[i + shift]);
}

/** Slides the box from where it was, as any staying box does. */
function slide(
  box: HTMLElement,
  { delta, from, duration, ease }: MotionContext<unknown>,
) {
  const x = delta.x + (from?.tx ?? 0);
  const y = delta.y + (from?.ty ?? 0);
  if (!x && !y) return [];
  return [
    box.animate(
      [{ transform: `translate(${x}px, ${y}px)` }, { transform: "none" }],
      { duration, easing: ease, fill: "backwards" },
    ),
  ];
}

// A wheel's kind carries the way its figure went, so every hook can see it.
const UP = "wheel-up";
const DOWN = "wheel-down";

/** Which way every wheel of a figure turns: with its value, or always one way. */
export type Trend = "auto" | "up" | "down";

/** Turns a wheel from one digit to another, through every digit between, the way the figure went. */
function roll(
  wheel: HTMLElement,
  from: number,
  to: number,
  { kind, line, duration, ease, signal }: MotionContext<unknown>,
) {
  // A turn the last morph left running would hold its end over this one.
  for (const turn of wheel.getAnimations()) turn.cancel();
  const forward = kind === UP;
  const steps = forward ? (to - from + 10) % 10 : (from - to + 10) % 10;
  const digits = Array.from({ length: steps + 1 }, (_, i) =>
    String((from + (forward ? i : -i) + 10) % 10),
  );
  // Counting up, the new digit rises from below; counting down, it drops from above.
  wheel.textContent = (forward ? digits : digits.reverse()).join("\n");
  const far = `translateY(${-steps * line.height}px)`;
  const turn = wheel.animate(
    [
      { transform: forward ? "none" : far },
      { transform: forward ? far : "none" },
    ],
    { duration, easing: ease, fill: "forwards" },
  );
  const settle = () => {
    // Interrupted, the next morph has already put the wheel's digit back.
    if (!signal.aborted) wheel.textContent = String(to);
    turn.cancel();
  };
  signal.addEventListener("abort", () => turn.cancel(), { once: true });
  return turn.finished.then(settle, () => {});
}

/** A figure's value, near enough to tell which way it went: separators dropped, "." kept. */
function value(text: string) {
  const [before = "", core = ""] = PARTS.exec(text)?.slice(1) ?? [];
  const n = Number(core.replace(/[^\d.]/g, "")) || 0;
  return /[-\u2212(]/.test(before) ? -n : n;
}

export type OdometerOptions = {
  /** `"auto"` turns with the value, up as it rises and down as it falls; or always `"up"` or `"down"`. */
  trend?: Trend;
};

/** Figures count like a car's odometer: each place turns through every digit between. */
export function odometer({
  trend = "auto",
}: OdometerOptions = {}): TorphPlugin {
  // A leaving wheel still carries the last morph's kind; the hooks run straight after segment.
  let latest = UP;

  /** The way this figure's wheels turn, carried on their kind so every hook can see it. */
  const direction = (from: string, to: string) =>
    trend === "up" || (trend === "auto" && (!from || value(to) >= value(from)))
      ? UP
      : DOWN;

  const wheel: KindSpec<unknown> = {
    slot: true,
    persist: (box, ctx) => {
      for (const turn of ctx.mover.getAnimations()) turn.cancel();
      const motion = slide(box, ctx);
      const to = ctx.mover.textContent ?? "";
      if (!ctx.was || ctx.was === to || !/\d/.test(ctx.was)) return motion;
      return Promise.all([
        ...motion.map((a) => a.finished),
        roll(ctx.mover, Number(ctx.was), Number(to), ctx),
      ]);
    },
    // A new place, as the figure grows, turns from zero.
    enter: (_box, ctx) =>
      roll(ctx.mover, 0, Number(ctx.mover.textContent), ctx),
    // A place the figure loses leaves the way the wheels turn.
    exit: (_box, { mover, line, duration }) => [
      mover.animate(
        {
          transform: `translateY(${latest === UP ? -line.height : line.height}px)`,
          opacity: 0,
          offset: 1,
        },
        { duration: duration / 2, fill: "both" },
      ),
    ],
  };

  return {
    name: "odometer",
    key: trend,
    claim: (word) => FIGURE.test(word),
    // The figure lines up from the right, so the ones stay the ones however long it gets;
    // the prefix from the left and the suffix from the right, so "$" stays "$".
    segment: (word, { previous = [], id }) => {
      const kind = (latest = direction(
        previous.map((s) => s.string).join(""),
        word,
      ));
      const next = parts(word);
      const perChar = previous.every((s) => Array.from(s.string).length === 1);
      const old = perChar
        ? parts(previous.map((s) => s.string).join(""))
        : [[], [], []];
      let at = 0;
      const was = old.map((part) => previous.slice(at, (at += part.length)));
      return next.flatMap((chars, p) =>
        align(chars, was[p]!, p > 0).map((kept, i) => ({
          id: kept?.id ?? id(),
          string: chars[i]!,
          kind: /\d/.test(chars[i]!) ? kind : undefined,
        })),
      );
    },
    affinity: (a, b) => (FIGURE.test(a) && FIGURE.test(b) ? 1 : null),
    // A wheel is one line tall, with the rest of its digits clipped above and below.
    css: `
[torph-kind^="wheel-"] { clip-path: inset(0 -100vw); }
[torph-kind^="wheel-"] > span { display: inline-block; vertical-align: top; height: 1lh; white-space: pre; }
`,
    kinds: { [UP]: wheel, [DOWN]: wheel },
  };
}

wave

Letter by letter, text drops in with a bounce and falls away under its own weight.

import { wave } from "torph/plugins/wave";

<TextMorph plugins={[wave()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type WaveOptions = {
  /** How far a letter drops in from, and falls away, as a CSS length. */
  height?: string;
  /** Each letter's start after the one before, as a share of the duration. */
  stagger?: number;
};

/** Letter by letter, text drops in with a bounce and falls away under its own weight. */
export function wave({
  height = "0.6em",
  stagger = 0.12,
}: WaveOptions = {}): TorphPlugin {
  const delay = (index: number, count: number, duration: number) =>
    index * Math.min(stagger, 0.3 / Math.max(1, count - 1)) * duration;

  return {
    name: "wave",
    key: `${height}\u0000${stagger}`,
    // Underdamped, so each letter lands with a little bounce.
    ease: { stiffness: 320, damping: 14 },
    letters: true,
    runs: { claim: () => true },
    animate: {
      text: {
        enter: (box, { delta, from, duration, ease, index, arriving }) => [
          box.animate(
            [
              {
                transform: `translate(${delta.x + (from?.tx ?? 0)}px, calc(${delta.y + (from?.ty ?? 0)}px - ${height})) rotate(-6deg)`,
                opacity: 0,
              },
              { transform: "none", opacity: 1 },
            ],
            {
              duration,
              delay: delay(index, arriving, duration),
              easing: ease,
              fill: "backwards",
            },
          ),
        ],
        // Falling, so it speeds up rather than settles.
        exit: (box, { delta, duration, index, leaving }) => [
          box.animate(
            {
              transform: `translate(${delta.x}px, calc(${delta.y}px + ${height} * 1.5)) rotate(10deg)`,
              opacity: 0,
              offset: 1,
            },
            {
              duration: duration * 0.6,
              delay: delay(index, leaving, duration * 0.6),
              easing: "cubic-bezier(0.55, 0, 1, 0.45)",
              fill: "both",
            },
          ),
        ],
      },
    },
  };
}

wipe

An edge crosses the value, wiping the old text away and revealing the new.

import { wipe } from "torph/plugins/wipe";

<TextMorph plugins={[wipe()]}>{value}</TextMorph>
import type { HookSet, TorphPlugin } from "torph";

export type WipeOptions = {
  /** How much of the duration the edge takes to cross the value. */
  sweep?: number;
};

/** An edge crosses the value left to right, wiping the old text away and revealing the new. */
export function wipe({ sweep = 0.8 }: WipeOptions = {}): TorphPlugin {
  /** When the edge reaches the box's left side, and how long it takes to cross it. */
  const crossing = (
    at: { x: number; width: number } | undefined,
    width: number,
    duration: number,
  ) => {
    const span = duration * sweep;
    if (!at || !width) return { delay: 0, duration: span };
    return {
      delay: (at.x / width) * span,
      duration: Math.max(1, (at.width / width) * span),
    };
  };

  const hooks: HookSet<unknown> = {
    enter: (box, { at, extent, duration }) => [
      box.animate(
        [{ clipPath: "inset(0 100% 0 0)" }, { clipPath: "inset(0 0 0 0)" }],
        { ...crossing(at, extent.width, duration), fill: "backwards" },
      ),
    ],
    exit: (box, { at, extent, duration }) => [
      box.animate(
        [{ clipPath: "inset(0 0 0 0)" }, { clipPath: "inset(0 0 0 100%)" }],
        { ...crossing(at, extent.width, duration), fill: "both" },
      ),
    ],
  };

  return {
    name: "wipe",
    key: String(sweep),
    runs: { claim: () => true },
    // Numbers too: an earlier plugin's hooks come before the built-in's own.
    animate: { text: hooks, digit: hooks, symbol: hooks },
  };
}

caseless

A letter that only changes case keeps its box, and pops to the new one in place.

import { caseless } from "torph/plugins/caseless";

<TextMorph plugins={[caseless()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

/** A letter that only changes case keeps its box, and pops to the new one in place. */
export function caseless(): TorphPlugin {
  return {
    name: "caseless",
    fold: (char) => char.toLowerCase(),
    affinity: (a, b) => (a.toLowerCase() === b.toLowerCase() ? 1 : null),
    animate: {
      text: {
        persist: (box, { was, delta, from, duration, ease }) => {
          const x = delta.x + (from?.tx ?? 0);
          const y = delta.y + (from?.ty ?? 0);
          const changed = was !== undefined && was !== box.textContent;
          if (!x && !y && !changed) return;
          return [
            box.animate(
              [
                changed
                  ? {
                      transform: `translate(${x}px, ${y}px) scale(0.7)`,
                      opacity: 0.4,
                    }
                  : { transform: `translate(${x}px, ${y}px)` },
                { transform: "none", opacity: 1 },
              ],
              { duration, easing: ease, fill: "backwards" },
            ),
          ];
        },
      },
    },
  };
}

anagram

Every letter is reused wherever the new value needs it, across words and in any order.

import { anagram } from "torph/plugins/anagram";

<TextMorph plugins={[anagram()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

/** One display string per character: a space as the engine draws it, a newline as a break. */
const characters = (value: string) =>
  Array.from(value, (char) => (char === " " ? " " : char));

/** Every letter is reused wherever the new value needs it, across words and in any order. */
export function anagram(): TorphPlugin {
  return {
    name: "anagram",
    whole: (value, { previous, id }) => {
      // Letters still on screen, by letter, case aside: each can be taken once.
      const pool = new Map<string, string[]>();
      for (const segment of previous) {
        if (Array.from(segment.string).length !== 1) continue;
        const key = segment.string.toLowerCase();
        pool.set(key, [...(pool.get(key) ?? []), segment.id]);
      }
      return characters(value).map((string) => ({
        id: pool.get(string.toLowerCase())?.shift() ?? id(),
        string,
      }));
    },
    // Kept letter by letter, however much of the value changes.
    runs: { claim: () => true },
  };
}

stack

The whole value is one card: the old one slides up and away as the new one rises in.

import { stack } from "torph/plugins/stack";

<TextMorph plugins={[stack()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type StackOptions = {
  /** How far the cards travel, as a CSS length. */
  rise?: string;
};

/** The whole value is one card: the old one slides up and away as the new one rises in. */
export function stack({ rise = "0.8em" }: StackOptions = {}): TorphPlugin {
  return {
    name: "stack",
    key: rise,
    whole: (value, { id }) =>
      value ? [{ id: id(), string: value, kind: "card" }] : [],
    // A card keeps the value's own line breaks.
    css: `[torph-kind="card"] { white-space: pre; }`,
    kinds: {
      card: {
        enter: (box, { duration, ease }) => [
          box.animate(
            [
              { transform: `translateY(${rise})`, opacity: 0 },
              { transform: "none", opacity: 1 },
            ],
            { duration, easing: ease, fill: "backwards" },
          ),
        ],
        exit: (box, { duration, ease }) => [
          box.animate(
            { transform: `translateY(-${rise})`, opacity: 0, offset: 1 },
            { duration, easing: ease, fill: "both" },
          ),
        ],
      },
    },
  };
}

squash

Moving text stretches along its path, then squashes as it lands, like rubber.

import { squash } from "torph/plugins/squash";

<TextMorph plugins={[squash()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type SquashOptions = {
  /** The most a moving box stretches, as a share of its size. */
  stretch?: number;
};

/** Moving text stretches along its path, then squashes as it lands, like rubber. */
export function squash({ stretch = 0.35 }: SquashOptions = {}): TorphPlugin {
  return {
    name: "squash",
    key: String(stretch),
    animate: {
      text: {
        persist: (box, { delta, from, line, duration }) => {
          const x = delta.x + (from?.tx ?? 0);
          const y = delta.y + (from?.ty ?? 0);
          const distance = Math.hypot(x, y);
          if (!distance) return;
          // Further travel stretches more, up to `stretch`, eight lines out.
          const s = Math.min(stretch, distance / (line.height * 8));
          const across = Math.abs(x) >= Math.abs(y);
          const [sx, sy] = across ? [1 + s, 1 - s / 2] : [1 - s / 2, 1 + s];
          const [qx, qy] = across
            ? [1 - s / 2, 1 + s / 3]
            : [1 + s / 3, 1 - s / 2];
          return [
            box.animate(
              [
                { transform: `translate(${x}px, ${y}px)` },
                {
                  transform: `translate(${x * 0.4}px, ${y * 0.4}px) scale(${sx}, ${sy})`,
                  offset: 0.45,
                },
                { transform: `scale(${qx}, ${qy})`, offset: 0.8 },
                { transform: "none" },
              ],
              { duration, easing: "ease-in-out", fill: "backwards" },
            ),
          ];
        },
      },
    },
  };
}

redline

Like track changes: removed words stay struck through before they go, added words come underlined.

import { redline } from "torph/plugins/redline";

<TextMorph plugins={[redline()]}>{value}</TextMorph>
import type { Segment, TorphPlugin } from "torph";

/** Longest common subsequence of two lists, as index pairs in order. */
function common<T>(a: T[], b: T[]): [number, number][] {
  const dp = a.map(() => new Array<number>(b.length + 1).fill(0));
  dp.push(new Array<number>(b.length + 1).fill(0));
  for (let i = a.length - 1; i >= 0; i--) {
    for (let j = b.length - 1; j >= 0; j--) {
      dp[i]![j] =
        a[i] === b[j]
          ? dp[i + 1]![j + 1]! + 1
          : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!);
    }
  }
  const pairs: [number, number][] = [];
  for (let i = 0, j = 0; i < a.length && j < b.length; ) {
    if (a[i] === b[j]) pairs.push([i++, j++]);
    else if (dp[i + 1]![j]! >= dp[i]![j + 1]!) i++;
    else j++;
  }
  return pairs;
}

/** A line's words and spaces, as the engine draws them. */
const pieces = (line: string) =>
  line
    .split(/( )/)
    .filter(Boolean)
    .map((piece) => (piece === " " ? "\u00A0" : piece));

/**
 * A value cut line by line, the way a code diff reads: an unchanged line keeps its boxes,
 * a changed one keeps the words it shares with the line it replaced, and a line with
 * nothing in its place is all new, or all removed.
 */
function byLine(value: string, previous: Segment[], id: () => string) {
  // The old lines' pieces, each line with the break that ends it.
  const old: { pieces: Segment[]; end?: Segment }[] = [{ pieces: [] }];
  for (const segment of previous) {
    if (segment.string === "\n") {
      old.at(-1)!.end = segment;
      old.push({ pieces: [] });
    } else old.at(-1)!.pieces.push(segment);
  }
  const text = (line: { pieces: Segment[] }) =>
    line.pieces.map((p) => p.string).join("");
  const lines = value.split("\n").map(pieces);
  const kept = common(
    old.map(text),
    lines.map((l) => l.join("")),
  );

  // Each new line's old counterpart: the same line, or the one in the same gap between kept lines.
  const partner = new Map<number, number>(kept.map(([o, n]) => [n, o]));
  const anchors: [number, number][] = [
    [-1, -1],
    ...kept,
    [old.length, lines.length],
  ];
  for (let k = 1; k < anchors.length; k++) {
    const [o0, n0] = anchors[k - 1]!;
    const [o1, n1] = anchors[k]!;
    for (let i = 1; n0 + i < n1 && o0 + i < o1; i++)
      partner.set(n0 + i, o0 + i);
  }

  return lines.flatMap((line, n) => {
    const was = partner.get(n);
    const pool = was === undefined ? [] : [...old[was]!.pieces];
    const cut: Segment[] = line.map((string) => {
      // The next old piece with the same text keeps its box, in order.
      const at = pool.findIndex((p) => p.string === string);
      const keep = at >= 0 ? pool.splice(0, at + 1).at(-1) : undefined;
      return { id: keep?.id ?? id(), string };
    });
    if (n < lines.length - 1) {
      cut.push({
        id: (was !== undefined && old[was]!.end?.id) || id(),
        string: "\n",
      });
    }
    return cut;
  });
}

export type RedlineOptions = {
  /** How long removed text stays struck through in the line, as a multiple of the duration. */
  linger?: number;
  /** The colour of removed text and its strike. */
  removed?: string;
  /** The colour of added text and its underline. */
  added?: string;
};

/** Like track changes: removed words stay struck through before they go, added words come underlined. */
export function redline({
  linger = 2,
  removed = "#ff6b6b",
  added = "#6bdc8b",
}: RedlineOptions = {}): TorphPlugin {
  // A line drawn as a background, so it sweeps in along the word.
  const rule = (color: string, at: string) => ({
    backgroundImage: `linear-gradient(${color}, ${color})`,
    backgroundRepeat: "no-repeat",
    backgroundPosition: `0 ${at}`,
  });
  const strike = rule(removed, "55%");
  const underline = rule(added, "100%");

  return {
    name: "redline",
    key: `${linger}\u0000${removed}\u0000${added}`,
    linger,
    // A whole removed line is a replaced run; kept from group replacement, it strikes through like any other.
    runs: { claim: () => true },
    // Several lines are diffed a line at a time, like code; a single line word by word.
    whole: (value, { previous, id }) =>
      value.includes("\n") || previous.some((s) => s.string === "\n")
        ? byLine(value, previous, () => id())
        : null,
    // Whole words, as an editor's changes read.
    claim: () => true,
    segment: (word, { id }) => [{ id: id(word), string: word }],
    animate: {
      text: {
        // Struck through as it lingers, then gone as the line closes up.
        exit: (box, { duration }) => {
          const total = duration * (linger + 0.4);
          // Spaces and breaks still hold the line's shape while they linger, unmarked.
          if (!box.textContent?.trim()) return [];
          return [
            box.animate(
              [
                { ...strike, backgroundSize: "0% 0.08em" },
                {
                  ...strike,
                  backgroundSize: "100% 0.08em",
                  color: removed,
                  offset: (duration * 0.4) / total,
                },
                {
                  ...strike,
                  backgroundSize: "100% 0.08em",
                  color: removed,
                  opacity: 1,
                  offset: (duration * linger) / total,
                },
                {
                  ...strike,
                  backgroundSize: "100% 0.08em",
                  color: removed,
                  opacity: 0,
                },
              ],
              { duration: total, fill: "both" },
            ),
          ];
        },
        // Underlined as it arrives, the mark fading back to plain text.
        enter: (box, { duration }) =>
          !box.textContent?.trim()
            ? []
            : [
                box.animate(
                  [
                    {
                      ...underline,
                      backgroundSize: "0% 0.08em",
                      color: added,
                      opacity: 0,
                    },
                    {
                      ...underline,
                      backgroundSize: "100% 0.08em",
                      color: added,
                      opacity: 1,
                      offset: 0.2,
                    },
                    {
                      ...underline,
                      backgroundSize: "100% 0.08em",
                      color: added,
                      offset: 0.7,
                    },
                    { ...underline, backgroundSize: "100% 0em" },
                  ],
                  { duration: duration * (linger + 1), fill: "backwards" },
                ),
              ],
      },
    },
  };
}

countup

A figure counts through the values between, quick at first and slowing as it arrives.

import { countup } from "torph/plugins/countup";

<TextMorph plugins={[countup()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

// Prefix, the run from the first digit to the last, suffix.
const PARTS = /^(\D*)(\d(?:.*\d)?)(\D*)$/u;

/** A figure's parts and value, read the English way: "," groups, "." is the decimal point. */
function figure(text: string) {
  const [, before = "", core = "", after = ""] = PARTS.exec(text) ?? [];
  if (!core || /[^\d.,]/.test(core)) return null;
  const n = Number(core.replace(/,/g, ""));
  if (!Number.isFinite(n)) return null;
  return {
    before,
    after,
    n: /[-−(]/.test(before) ? -n : n,
    decimals: core.split(".")[1]?.length ?? 0,
    grouped: core.includes(","),
  };
}

export type CountupOptions = {
  /** How long the count takes, in ms. */
  time?: number;
  /** How many values it passes through on the way. */
  steps?: number;
};

/** A figure counts through the values between, quick at first and slowing as it arrives. */
export function countup({
  time = 1000,
  steps = 24,
}: CountupOptions = {}): TorphPlugin {
  return {
    name: "countup",
    key: `${time}\u0000${steps}`,
    tween: (from, to) => {
      const a = figure(from);
      const b = figure(to);
      if (!a || !b || a.n === b.n) return null;
      const format = new Intl.NumberFormat("en", {
        minimumFractionDigits: b.decimals,
        maximumFractionDigits: b.decimals,
        useGrouping: b.grouped,
      });
      const frames: { value: string; at: number }[] = [];
      for (let i = 0; i < steps; i++) {
        const t = (i + 1) / steps;
        // Evenly spaced in time, eased in value: big jumps first, small ones at the end.
        const n = a.n + (b.n - a.n) * (1 - (1 - t) ** 3);
        const value =
          i === steps - 1
            ? to
            : `${n < 0 ? "-" : ""}${b.before.replace(/[-−]/, "")}${format.format(Math.abs(n))}${b.after}`;
        if (value !== frames.at(-1)?.value)
          frames.push({ value, at: (time * i) / steps });
      }
      return frames;
    },
  };
}

skeleton

While the value is empty a shimmering bar holds its place, and the text fades in over it.

import { skeleton } from "torph/plugins/skeleton";

<TextMorph plugins={[skeleton()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type SkeletonOptions = {
  /** How wide the placeholder is, in digit widths. */
  length?: number;
  /** The placeholder's colour. */
  color?: string;
};

/** While the value is empty a shimmering bar holds its place, and the text fades in over it. */
export function skeleton({
  length = 12,
  color = "rgb(128 128 128 / 0.25)",
}: SkeletonOptions = {}): TorphPlugin {
  return {
    name: "skeleton",
    key: `${length}\u0000${color}`,
    // Figure spaces: each as wide as a digit, and none of them a word break.
    whole: (value, { id }) =>
      value ? null : [{ id: id(), string: " ".repeat(length), kind: "bone" }],
    // The shimmer is drawn on the bone's box.
    boxes: (value) => value === "",
    // An endless shimmer, which the morph treats as ambient and never waits on.
    css: `
[torph-kind="bone"] {
  --torph-bone: ${color};
  border-radius: 0.3em;
  background: linear-gradient(90deg, var(--torph-bone) 30%, color-mix(in srgb, var(--torph-bone), white 20%) 50%, var(--torph-bone) 70%) 100% 50% / 300% 70% no-repeat;
  animation: torph-shimmer 1.6s linear infinite;
}
@keyframes torph-shimmer { to { background-position: 0% 50%; } }
`,
    kinds: {
      bone: {
        enter: (box, { duration }) => [
          box.animate([{ opacity: 0 }, { opacity: 1 }], {
            duration,
            fill: "backwards",
          }),
        ],
        // Slower than the text arrives, so the text fades in over the bar.
        exit: (box, { duration }) => [
          box.animate(
            { opacity: 0, offset: 1 },
            {
              duration: duration * 1.5,
              fill: "both",
            },
          ),
        ],
      },
    },
  };
}

magnet

Letters near the pointer lean away from it, and settle back when it leaves.

import { magnet } from "torph/plugins/magnet";

<TextMorph plugins={[magnet()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type MagnetOptions = {
  /** How near the pointer has to come to move a letter, in px. */
  radius?: number;
  /** How far a letter right under the pointer moves, as a share of the radius. */
  strength?: number;
};

/** Letters near the pointer lean away from it, and settle back when it leaves. */
export function magnet({
  radius = 60,
  strength = 0.12,
}: MagnetOptions = {}): TorphPlugin {
  return {
    name: "magnet",
    key: `${radius}\u0000${strength}`,
    letters: true,
    // Pushed letters need a box each, at rest too.
    boxes: () => true,
    // `translate`, not `transform`: it composes with the morph's own motion instead of fighting it.
    css: `[torph-magnet] > [torph-id] { transition: translate 300ms cubic-bezier(0.2, 0.8, 0.2, 1); }`,
    mount: (root) => {
      root.setAttribute("torph-magnet", "");
      const pushed = new WeakMap<Element, [number, number]>();
      let pointer: { x: number; y: number } | null = null;
      let frame = 0;

      const apply = () => {
        frame = 0;
        const boxes = Array.from(
          root.querySelectorAll<HTMLElement>(
            ":scope > [torph-id]:not([torph-exiting])",
          ),
        );
        // Every read before any write.
        const rects = boxes.map((box) => box.getBoundingClientRect());
        boxes.forEach((box, i) => {
          const rect = rects[i]!;
          // Where the letter would be unpushed, so moving it doesn't move the target.
          const [px, py] = pushed.get(box) ?? [0, 0];
          const dx = rect.left + rect.width / 2 - px - (pointer?.x ?? 0);
          const dy = rect.top + rect.height / 2 - py - (pointer?.y ?? 0);
          const distance = Math.hypot(dx, dy);
          if (!pointer || !distance || distance > radius) {
            pushed.delete(box);
            box.style.translate = "";
            return;
          }
          const push = (1 - distance / radius) * radius * strength;
          const offset: [number, number] = [
            (dx / distance) * push,
            (dy / distance) * push,
          ];
          pushed.set(box, offset);
          box.style.translate = `${offset[0]}px ${offset[1]}px`;
        });
      };
      const schedule = () => {
        frame ||= requestAnimationFrame(apply);
      };
      const move = (event: PointerEvent) => {
        pointer = { x: event.clientX, y: event.clientY };
        schedule();
      };
      const leave = () => {
        pointer = null;
        schedule();
      };

      root.addEventListener("pointermove", move);
      root.addEventListener("pointerleave", leave);
      return () => {
        cancelAnimationFrame(frame);
        root.removeEventListener("pointermove", move);
        root.removeEventListener("pointerleave", leave);
        root.removeAttribute("torph-magnet");
        for (const box of Array.from(
          root.querySelectorAll<HTMLElement>("[torph-id]"),
        )) {
          box.style.translate = "";
        }
      };
    },
  };
}

weight

Letter by letter, new text arrives heavy and relaxes to its weight; leaving text thins away.

import { weight } from "torph/plugins/weight";

<TextMorph plugins={[weight()]}>{value}</TextMorph>
import type { TorphPlugin } from "torph";

export type WeightOptions = {
  /** The weight a letter arrives at, before it relaxes to the text's own. Needs a variable font. */
  heavy?: number;
  /** The weight a leaving letter thins to. */
  light?: number;
};

/** Letter by letter, new text arrives heavy and relaxes to its weight; leaving text thins away. */
export function weight({
  heavy = 900,
  light = 100,
}: WeightOptions = {}): TorphPlugin {
  return {
    name: "weight",
    key: `${heavy}\u0000${light}`,
    letters: true,
    runs: { claim: () => true },
    animate: {
      text: {
        enter: (box, { duration, ease }) => [
          box.animate(
            [
              { fontWeight: String(heavy), opacity: 0 },
              { opacity: 1, offset: 0.25 },
            ],
            { duration: duration * 1.5, easing: ease, fill: "backwards" },
          ),
        ],
        exit: (box, { duration }) => [
          box.animate(
            { fontWeight: String(light), opacity: 0, offset: 1 },
            { duration, fill: "both" },
          ),
        ],
      },
    },
  };
}