<TextMorph />

Text continuity for interfaces on the web.

A plugin changes how torph cuts text up, how it moves, or both. torph's own look is a set of plugins too, classic(), and each one below is added in front of it. Each is its whole source.

mix them

torph's default set, classic(), is ticked. Add any of the others in front of it, take parts of it away, or type your own text.

classic()
in front of it
<TextMorph>{value}</TextMorph> // classic()

blur

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

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

<TextMorph plugins={[blur(), ...classic()]}>{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 { classic } from "torph";
import { words } from "torph/plugins/words";

<TextMorph plugins={[words(), ...classic()]}>{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 { classic } from "torph";
import { scramble } from "torph/plugins/scramble";

<TextMorph plugins={[scramble(), ...classic()]}>{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 { classic } from "torph";
import { flap } from "torph/plugins/flap";

<TextMorph plugins={[flap(), ...classic()]}>{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 ?? "");
    // A tile, like the board's: a wide glyph on the drum can't paint over its neighbours, nor show its back.
    face.style.overflow = "clip";
    face.style.backfaceVisibility = "hidden";
    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 { classic } from "torph";
import { typewriter } from "torph/plugins/typewriter";

<TextMorph plugins={[typewriter(), ...classic()]}>{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 { classic } from "torph";
import { tokens } from "torph/plugins/tokens";

<TextMorph plugins={[tokens(), ...classic()]}>{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.

default05:00odometer()05:00
import { classic } from "torph";
import { odometer } from "torph/plugins/odometer";

<TextMorph plugins={[odometer(), ...classic()]}>{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, fading in so it doesn't pop up out of nowhere.
    enter: (_box, ctx) =>
      Promise.all([
        roll(ctx.mover, 0, Number(ctx.mover.textContent), ctx),
        ctx.mover.animate([{ opacity: 0 }, { opacity: 1 }], {
          duration: ctx.duration / 2,
          fill: "backwards",
        }).finished,
      ]),
    // A place the figure loses leaves the way the wheels turn.
    exit: (_box, { mover, line, duration, signal }) => {
      const leave = mover.animate(
        {
          transform: `translateY(${latest === UP ? -line.height : line.height}px)`,
          opacity: 0,
          offset: 1,
        },
        { duration: duration / 2, fill: "both" },
      );
      // Cut short by the next change, it hurries off rather than sit under a place that arrives where it stood.
      signal.addEventListener("abort", () => leave.updatePlaybackRate(4), {
        once: true,
      });
      return [leave];
    },
  };

  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 { classic } from "torph";
import { wave } from "torph/plugins/wave";

<TextMorph plugins={[wave(), ...classic()]}>{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.
        // All at once, with no stagger: leaving text gets out of the way of what arrives.
        exit: (box, { delta, duration }) => [
          box.animate(
            {
              transform: `translate(${delta.x}px, calc(${delta.y}px + ${height} * 1.5)) rotate(10deg)`,
              opacity: 0,
              offset: 1,
            },
            {
              duration: duration * 0.6,
              easing: "cubic-bezier(0.55, 0, 1, 0.45)",
              fill: "both",
            },
          ),
        ],
      },
    },
  };
}

caseless

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

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

<TextMorph plugins={[caseless(), ...classic()]}>{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" },
            ),
          ];
        },
      },
    },
  };
}

stack

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

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

<TextMorph plugins={[stack(), ...classic()]}>{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

Like a cartoon: moving text winds up, stretches and lands with a squash and a wobble; new text drops in and splats.

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

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

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

// Squashes pivot on the baseline, so text lands on the line rather than shrinking into the air.
const ORIGIN = "50% 100%";

/** Like a cartoon: moving text winds up, stretches along its path and lands with a squash and a wobble; arriving text drops in and splats, leaving text squishes flat and zips away. */
export function squash({ stretch = 0.6 }: SquashOptions = {}): TorphPlugin {
  /** Scale that stretches `by` along the path and thins across it. */
  const along = (across: boolean, by: number) => {
    const thin = 1 / (1 + by);
    return across ? `scale(${1 + by}, ${thin})` : `scale(${thin}, ${1 + by})`;
  };

  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`, three lines out.
          const s = Math.min(stretch, distance / (line.height * 3));
          const across = Math.abs(x) >= Math.abs(y);
          const at = (k: number, scale: string) =>
            `translate(${x * k}px, ${y * k}px) ${scale}`;
          return [
            box.animate(
              [
                { transform: at(1, "scale(1)") },
                // Wind-up: a little back, bunched up against the push.
                { transform: at(1.06, along(across, -s / 3)), offset: 0.14 },
                { transform: at(0.4, along(across, s)), offset: 0.45 },
                // Past the mark, squashed flat against it.
                { transform: at(-0.08, along(across, -s / 2)), offset: 0.66 },
                { transform: at(0.03, along(across, s / 4)), offset: 0.82 },
                { transform: at(0, along(across, -s / 10)), offset: 0.92 },
                { transform: "none" },
              ].map((frame) => ({
                ...frame,
                transformOrigin: ORIGIN,
                easing: "ease-in-out",
              })),
              { duration: duration * 1.2, fill: "backwards" },
            ),
          ];
        },
        // Dropped in tall and thin, it splats wide, then bounces back to shape.
        enter: (box, { delta, from, duration }) => {
          const x = delta.x + (from?.tx ?? 0);
          const y = delta.y + (from?.ty ?? 0);
          return [
            box.animate(
              [
                {
                  transform: `translate(${x}px, calc(${y}px - 0.8em)) scale(${1 - stretch / 2}, ${1 + stretch})`,
                  opacity: 0,
                },
                {
                  transform: `translate(${x * 0.3}px, ${y * 0.3}px) scale(${1 + stretch}, ${1 - stretch / 2})`,
                  opacity: 1,
                  offset: 0.45,
                },
                {
                  transform: `scale(${1 - stretch / 5}, ${1 + stretch / 4})`,
                  offset: 0.7,
                },
                { transform: `scale(1.05, 0.96)`, offset: 0.86 },
                { transform: "none" },
              ].map((frame) => ({ ...frame, transformOrigin: ORIGIN })),
              {
                duration: duration * 1.2,
                easing: "ease-out",
                fill: "backwards",
              },
            ),
          ];
        },
        // Squished flat, then gone upward, thin as a pin.
        exit: (box, { delta, duration }) => [
          box.animate(
            [
              { transform: "none", opacity: 1 },
              {
                transform: `translate(${delta.x * 0.3}px, ${delta.y * 0.3}px) scale(${1 + stretch}, ${1 - stretch * 0.6})`,
                opacity: 1,
                offset: 0.35,
              },
              {
                transform: `translate(${delta.x}px, calc(${delta.y}px - 0.8em)) scale(${1 - stretch * 0.7}, ${1 + stretch})`,
                opacity: 0,
              },
            ].map((frame) => ({ ...frame, transformOrigin: ORIGIN })),
            { duration: duration * 0.8, easing: "ease-in", fill: "both" },
          ),
        ],
      },
    },
  };
}

redline

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

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

<TextMorph plugins={[redline(), ...classic()]}>{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 = 1.5,
  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 { classic } from "torph";
import { countup } from "torph/plugins/countup";

<TextMorph plugins={[countup(), ...classic()]}>{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;
    },
  };
}

rows

Each line is one box, known by its key, so a reordered list slides every row to its new place.

import { classic } from "torph";
import { rows } from "torph/plugins/rows";

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

export type RowsOptions = {
  /** What a line is known by from one value to the next: the whole line, by default. */
  key?: (line: string) => string;
};

/** Each line is one box, known by its key, so a reordered list slides every row to its new place. */
export function rows({ key = (line) => line }: RowsOptions = {}): TorphPlugin {
  return {
    name: "rows",
    whole: (value, { previous, id }) => {
      // Last value's rows by key, so a row keeps its box wherever it lands.
      const was = new Map(
        previous
          .filter((segment) => segment.kind === "row")
          .map((segment) => [key(segment.string), segment.id]),
      );
      const breaks = previous.filter((segment) => segment.string === "\n");
      return value.split("\n").flatMap((line, i): Segment[] => {
        const kept = was.get(key(line));
        // Taken once: a second line with the same key is a new row.
        was.delete(key(line));
        return [
          ...(i > 0 ? [{ id: breaks[i - 1]?.id ?? id(), string: "\n" }] : []),
          { id: kept ?? id(), string: line, kind: "row" },
        ];
      });
    },
    css: `[torph-kind="row"] { white-space: pre; }`,
    kinds: {
      row: {
        // A row that changed while it moved settles on its new text with a blink.
        persist: (box, { delta, from, was, mover, duration, ease }) => {
          const x = delta.x + (from?.tx ?? 0);
          const y = delta.y + (from?.ty ?? 0);
          return [
            box.animate(
              [
                { transform: `translate(${x}px, ${y}px)` },
                { transform: "none" },
              ],
              { duration, easing: ease, fill: "backwards" },
            ),
            ...(was !== undefined && was !== mover.textContent
              ? [
                  mover.animate([{ opacity: 0.35 }, { opacity: 1 }], {
                    duration: duration / 2,
                    delay: duration / 2,
                    fill: "backwards",
                  }),
                ]
              : []),
          ];
        },
      },
    },
  };
}

trend

What changes in a figure flashes green as it rises and red as it falls, then fades back.

default$1,284.20trend()$1,284.20
import { classic } from "torph";
import { trend } from "torph/plugins/trend";

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

export type TrendOptions = {
  /** The flash as the figure rises. */
  up?: string;
  /** The flash as it falls. */
  down?: string;
};

const figure = (text: string) => {
  const digits = text.replace(/[^\d.-]/g, "");
  return digits ? Number(digits) : NaN;
};

/** What changes in a figure flashes green as it rises and red as it falls, then fades back. */
export function trend({
  up = "#4ade80",
  down = "#ff6b6b",
}: TrendOptions = {}): TorphPlugin<string | null> {
  return {
    name: "trend",
    key: `${up}\u0000${down}`,
    read: (_root, _style, { from, to }) => {
      const [a, b] = [figure(from), figure(to)];
      return a === b || Number.isNaN(a) || Number.isNaN(b)
        ? null
        : b > a
          ? up
          : down;
    },
    idle: null,
    // Alongside whatever moves the box, so the numbers' own slide still runs.
    decorate: {
      "*": {
        enter: (box, { state, duration }) =>
          state
            ? [
                box.animate(
                  { color: state, offset: 0 },
                  { duration: duration * 2.5, easing: "ease-in" },
                ),
              ]
            : [],
      },
    },
  };
}

reveal

Each place keeps its box and turns over to its new character, like a masked value revealed.

import { classic } from "torph";
import { reveal } from "torph/plugins/reveal";

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

export type RevealOptions = {
  /** Each character's turn after the one before, as a share of the duration. */
  stagger?: number;
};

/** Each place keeps its box, and turns over in place to its new character: a masked value revealed. */
export function reveal({ stagger = 0.08 }: RevealOptions = {}): TorphPlugin {
  return {
    name: "reveal",
    key: `${stagger}`,
    // Every word, so character i of the old is character i of the new.
    claim: () => true,
    segment: (word, { previous, id }) =>
      Array.from(word, (char, i) => ({
        id: previous?.[i]?.id ?? id(),
        string: char,
      })),
    affinity: () => 1,
    runs: { claim: () => true },
    animate: {
      text: {
        persist: (box, { mover, was, index, duration, signal }) => {
          const text = mover.textContent ?? "";
          if (was === undefined || was === text) return;
          const half = duration / 3;
          // Shows the old character until its turn, then turns it edge-on and back as the new one.
          mover.textContent = was;
          return mover
            .animate(
              [
                { transform: "perspective(20em) rotateY(0deg)" },
                { transform: "perspective(20em) rotateY(90deg)" },
              ],
              {
                duration: half,
                delay: index * stagger * duration,
                easing: "ease-in",
              },
            )
            .finished.then(() => {
              // The next morph owns the box now, and its text with it.
              if (signal.aborted) return;
              mover.textContent = text;
              return mover.animate(
                [
                  { transform: "perspective(20em) rotateY(-90deg)" },
                  { transform: "perspective(20em) rotateY(0deg)" },
                ],
                { duration: half, easing: "ease-out" },
              ).finished;
            });
        },
      },
    },
  };
}