Cut reveal
Each letter or word slides up from behind an invisible line, one after another. Made for your name, a page title or a big statement, and it can wait until it scrolls into view.
Each letter or word slides up from behind an invisible line, one after another. Made for your name, a page title or a big statement, and it can wait until it scrolls into view.
/**
* MIT License
*
* Copyright (c) 2024 Daniel Petho
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Rewritten for Tastebud in plain React and CSS, without Tailwind or framer-motion.
*/
"use client";
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import styles from "./cut-reveal.module.css";
/** A spring for each piece (stiffness, damping, mass), plus a `delay` in seconds before the first one moves. */
export type CutRevealTransition = { stiffness?: number; damping?: number; mass?: number; delay?: number };
/** A spring's motion written as a CSS easing, plus how long it takes to settle, in ms. */
function springEasing(stiffness: number, damping: number, mass: number) {
const w0 = Math.sqrt(stiffness / mass);
const zeta = damping / (2 * Math.sqrt(stiffness * mass));
const at = (t: number) => {
if (zeta < 1) {
const wd = w0 * Math.sqrt(1 - zeta * zeta);
return 1 - Math.exp(-zeta * w0 * t) * (Math.cos(wd * t) + ((zeta * w0) / wd) * Math.sin(wd * t));
}
if (zeta === 1) return 1 - Math.exp(-w0 * t) * (1 + w0 * t);
const s = Math.sqrt(zeta * zeta - 1);
const r1 = -w0 * (zeta - s);
const r2 = -w0 * (zeta + s);
return 1 - (r2 * Math.exp(r1 * t) - r1 * Math.exp(r2 * t)) / (r2 - r1);
};
let end = 0;
for (let t = 0; t < 8; t += 0.01) if (Math.abs(1 - at(t)) > 0.002) end = t;
end += 0.01;
const points = Array.from({ length: 41 }, (_, i) => (i === 40 ? 1 : Number(at((end * i) / 40).toFixed(4))));
return { easing: `linear(${points.join(", ")})`, duration: Math.round(end * 1000) };
}
const splitIntoCharacters = (text: string): string[] => {
if (typeof Intl !== "undefined" && "Segmenter" in Intl) {
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
return Array.from(segmenter.segment(text), ({ segment }) => segment);
}
return Array.from(text);
};
export interface CutRevealProps {
children: React.ReactNode;
/** Pieces drop in from above instead of rising from below. */
reverse?: boolean;
transition?: CutRevealTransition;
/** Animate by "characters", "words", "lines" or any separator string. */
splitBy?: "words" | "characters" | "lines" | string;
/** Seconds between each piece starting. */
staggerDuration?: number;
staggerFrom?: "first" | "last" | "center" | "random" | number;
containerClassName?: string;
wordLevelClassName?: string;
elementLevelClassName?: string;
onClick?: () => void;
onStart?: () => void;
onComplete?: () => void;
/** Start on mount. */
autoStart?: boolean;
/** Wait until the text scrolls into view, then start once. Overrides autoStart. */
startInView?: boolean;
}
export interface CutRevealRef {
startAnimation: () => void;
reset: () => void;
}
interface WordObject {
characters: string[];
needsSpace: boolean;
}
export const CutReveal = forwardRef<CutRevealRef, CutRevealProps>(
(
{
children,
reverse = false,
transition,
splitBy = "words",
staggerDuration = 0.2,
staggerFrom = "first",
containerClassName,
wordLevelClassName,
elementLevelClassName,
onClick,
onStart,
onComplete,
autoStart = true,
startInView = false,
},
ref,
) => {
const containerRef = useRef<HTMLSpanElement>(null);
const [inView, setInView] = useState(false);
const text = typeof children === "string" ? children : String(children ?? "");
const [isAnimating, setIsAnimating] = useState(false);
// Like a spring with stiffness 190 and damping 22 unless told otherwise.
const stiffness = transition?.stiffness ?? 190;
const damping = transition?.damping ?? 22;
const mass = transition?.mass ?? 1;
const baseDelay = transition?.delay ?? 0;
const timing = useMemo(() => springEasing(stiffness, damping, mass), [stiffness, damping, mass]);
// Starts once the text is 40% on screen.
useEffect(() => {
if (!startInView || !containerRef.current) return;
const io = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) {
setInView(true);
io.disconnect();
}
},
{ threshold: 0.4 },
);
io.observe(containerRef.current);
return () => io.disconnect();
}, [startInView]);
const words: WordObject[] = useMemo(() => {
if (splitBy === "characters") {
const parts = text.split(" ");
return parts.map((word, i) => ({ characters: splitIntoCharacters(word), needsSpace: i !== parts.length - 1 }));
}
const parts = splitBy === "words" ? text.split(" ") : splitBy === "lines" ? text.split("\n") : text.split(splitBy);
return parts.map((el, i) => ({ characters: [el], needsSpace: i !== parts.length - 1 }));
}, [text, splitBy]);
const delays = useMemo(() => {
const total = splitBy === "characters" ? words.reduce((acc, w) => acc + w.characters.length + (w.needsSpace ? 1 : 0), 0) : words.length;
const count = words.reduce((acc, w) => acc + w.characters.length, 0);
return Array.from({ length: count }, (_, index) => {
if (staggerFrom === "first") return index * staggerDuration;
if (staggerFrom === "last") return (total - 1 - index) * staggerDuration;
if (staggerFrom === "center") return Math.abs(Math.floor(total / 2) - index) * staggerDuration;
if (staggerFrom === "random") return Math.abs(Math.floor(Math.random() * total) - index) * staggerDuration;
return Math.abs(staggerFrom - index) * staggerDuration;
});
}, [words, splitBy, staggerFrom, staggerDuration]);
const startAnimation = useCallback(() => {
// Reading the size makes the browser settle the hidden start first, so the move always plays.
void containerRef.current?.offsetHeight;
setIsAnimating(true);
onStart?.();
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) onComplete?.();
}, [onStart, onComplete]);
useImperativeHandle(ref, () => ({ startAnimation, reset: () => setIsAnimating(false) }));
useEffect(() => {
if (startInView ? inView : autoStart) startAnimation();
// Starts once, when it mounts or first comes into view.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [autoStart, startInView, inView]);
const style = { "--cut-duration": `${timing.duration}ms`, "--cut-easing": timing.easing } as React.CSSProperties;
return (
<span
className={`${styles.container} ${splitBy === "lines" ? styles.lines : ""} ${reverse ? styles.reverse : ""} ${isAnimating ? styles.playing : ""} ${containerClassName ?? ""}`}
style={style}
onClick={onClick}
ref={containerRef}
>
<span className={styles.srOnly}>{text}</span>
{words.map((wordObj, wordIndex, array) => {
const previousCharsCount = array.slice(0, wordIndex).reduce((sum, word) => sum + word.characters.length, 0);
return (
<span key={wordIndex} aria-hidden="true" className={`${styles.word} ${wordLevelClassName ?? ""}`}>
{wordObj.characters.map((char, charIndex) => {
const last = wordIndex === array.length - 1 && charIndex === wordObj.characters.length - 1;
return (
<span className={`${styles.element} ${elementLevelClassName ?? ""}`} key={charIndex}>
<span
className={styles.piece}
style={{ "--cut-delay": `${baseDelay + delays[previousCharsCount + charIndex]}s` } as React.CSSProperties}
onTransitionEnd={last && onComplete ? (e) => e.propertyName === "transform" && onComplete() : undefined}
>
{char}
</span>
</span>
);
})}
{wordObj.needsSpace && <span> </span>}
</span>
);
})}
</span>
);
},
);
CutReveal.displayName = "CutReveal";
/* Each word clips its letters; each letter waits below (or above) the edge, then springs up into place. */
.container {
display: flex;
flex-wrap: wrap;
white-space: pre-wrap;
}
.lines {
flex-direction: column;
}
.srOnly {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.word {
display: inline-flex;
overflow: hidden;
}
.element {
position: relative;
white-space: pre-wrap;
}
.piece {
display: inline-block;
transform: translateY(100%);
}
.reverse .piece {
transform: translateY(-100%);
}
.playing .piece {
transform: none;
transition: transform var(--cut-duration, 600ms) var(--cut-easing, ease-out) var(--cut-delay, 0s);
}
@media (prefers-reduced-motion: reduce) {
.playing .piece {
transition: none;
}
}