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 half the duration, however many letters move on that side.
const delay = (index: number, count: number, duration: number) =>
index * Math.min(stagger, 0.5 / 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,
// 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 }],
};
}
Arriving text cycles through random glyphs before it lands.
import { scramble } from "torph/plugins/scramble";
<TextMorph plugins={[scramble()]}>{value}</TextMorph>import type { TorphPlugin } from "torph";
export type ScrambleOptions = {
/** Drawn from while a character settles. */
glyphs?: string;
/** How often the glyphs change, in ms. */
rate?: number;
};
/** Arriving text cycles through random glyphs before it lands. */
export function scramble({
glyphs = "abcdefghijklmnopqrstuvwxyz0123456789",
rate = 40,
}: ScrambleOptions = {}): TorphPlugin {
const random = (text: string) =>
text.replace(
/\S/g,
() => glyphs[Math.floor(Math.random() * glyphs.length)]!,
);
return {
name: "scramble",
key: `${glyphs}\u0000${rate}`,
animate: {
text: {
// Each glyph has its own width, and the line would reflow on every one.
pinWidth: true,
enter: (_box, { mover, duration, signal }) => {
const text = mover.textContent ?? "";
return new Promise<void>((resolve) => {
const start = 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();
if (now - start >= duration) {
mover.textContent = text;
return resolve();
}
if (now - last >= rate) {
last = now;
mover.textContent = random(text);
}
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
});
},
},
},
};
}
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",
},
),
],
},
},
};
}
What changed gets a marker swept behind it, on top of however it moves.
import { highlight } from "torph/plugins/highlight";
<TextMorph plugins={[highlight()]}>{value}</TextMorph>import type { TorphPlugin } from "torph";
export type HighlightOptions = {
/** The marker's colour. */
color?: string;
/** How long the mark lasts, as a multiple of the duration. */
linger?: number;
};
/** What changed flashes a marker behind it, on top of however it moves. */
export function highlight({
color = "rgb(255 206 68 / 0.35)",
linger = 3,
}: HighlightOptions = {}): TorphPlugin {
return {
name: "highlight",
key: `${color}\u0000${linger}`,
decorate: {
"*": {
// Every changed box in step, so neighbouring ones read as one mark.
enter: (box, { duration }) => [
box.animate(
[
{ backgroundColor: "transparent" },
{ backgroundColor: color, offset: 0.1 },
{ backgroundColor: color, offset: 0.6 },
{ backgroundColor: "transparent" },
],
{ duration: duration * linger, easing: "ease-out" },
),
],
},
},
};
}
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)
);
},
};
}