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.
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",
},
),
],
},
},
};
}
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 }],
};
}
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: {
// Each glyph has its own width, and the line would reflow on every one.
pinWidth: true,
// 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,
),
},
},
};
}
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: {
// Each glyph has its own width, and the line would reflow on every flip.
pinWidth: true,
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" },
),
],
},
},
};
}
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",
},
),
],
},
},
};
}
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)
);
},
};
}
Figures count like a car's odometer: each place turns through every digit between.
import { odometer } from "torph/plugins/odometer";
<TextMorph plugins={[odometer()]}>{value}</TextMorph>import type { 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" },
),
];
}
/** Turns a wheel from one digit to another the short way round, through every digit between. */
function roll(
wheel: HTMLElement,
from: number,
to: number,
{ 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 up = (to - from + 10) % 10;
const forward = up <= 10 - up;
const steps = forward ? up : 10 - up;
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, () => {});
}
/** Figures count like a car's odometer: each place turns through every digit between. */
export function odometer(): TorphPlugin {
return {
name: "odometer",
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 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]!) ? "wheel" : 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: {
wheel: {
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 up from zero.
enter: (_box, ctx) =>
roll(ctx.mover, 0, Number(ctx.mover.textContent), ctx),
exit: (_box, { mover, line, duration }) => [
mover.animate(
{
transform: `translateY(${-line.height}px)`,
opacity: 0,
offset: 1,
},
{ duration: duration / 2, fill: "both" },
),
],
},
},
};
}
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",
},
),
],
},
},
};
}
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 },
};
}
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" },
),
];
},
},
},
};
}