React BitsText effectsMIT+
React BitsRotating Text
Text effectsRotatingText/RotatingText.tsx
'use client';
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState
} from 'react';
import {
motion,
AnimatePresence,
MotionConfig,
animate as animateValue,
useMotionValue,
useReducedMotion,
type AnimationPlaybackControls,
type Transition,
type VariantLabels,
type Target,
type TargetAndTransition
} from 'motion/react';
function cn(...classes: (string | undefined | null | boolean)[]): string {
return classes.filter(Boolean).join(' ');
}
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
const segmenter =
typeof Intl !== 'undefined' && Intl.Segmenter ? new Intl.Segmenter('en', { granularity: 'grapheme' }) : null;
const splitIntoCharacters = (text: string): string[] =>
segmenter ? Array.from(segmenter.segment(text), segment => segment.segment) : Array.from(text);
const withFilter = <T,>(state: T, filter: string): T =>
state && typeof state === 'object' && !Array.isArray(state) ? ({ ...state, filter } as T) : state;
export type RotatingTextEffect = 'slide' | 'flip' | 'blur' | 'scale' | 'drop';
export interface RotatingTextRef {
next: () => void;
previous: () => void;
jumpTo: (index: number) => void;
reset: () => void;
}
export interface RotatingTextProps
extends Omit<
React.ComponentPropsWithoutRef<typeof motion.span>,
'children' | 'transition' | 'initial' | 'animate' | 'exit'
> {
texts: string[];
transition?: Transition;
initial?: boolean | Target | VariantLabels;
animate?: boolean | VariantLabels | TargetAndTransition;
exit?: Target | VariantLabels;
effect?: RotatingTextEffect;
direction?: 'up' | 'down';
highlight?: boolean;
highlightColor?: string;
animatePresenceMode?: 'sync' | 'wait';
animatePresenceInitial?: boolean;
rotationInterval?: number;
staggerDuration?: number;
staggerFrom?: 'first' | 'last' | 'center' | 'random' | number;
loop?: boolean;
auto?: boolean;
pauseOnHover?: boolean;
blur?: number;
splitBy?: string;
onNext?: (index: number) => void;
mainClassName?: string;
splitLevelClassName?: string;
elementLevelClassName?: string;
}
interface EffectPreset {
initial: Target;
animate: Target;
exit: Target;
transition: Transition;
exitTransition?: Transition;
}
const LAYOUT_SPRING: Transition = { type: 'spring', damping: 25, stiffness: 300 };
const WIDTH_SPRING: Transition = { type: 'spring', damping: 34, stiffness: 320 };
const FLIP_STYLE: React.CSSProperties = { transformOrigin: '50% 50% -0.45em', backfaceVisibility: 'hidden' };
const EFFECTS: Record<RotatingTextEffect, (up: boolean) => EffectPreset> = {
slide: up => ({
initial: { y: up ? '100%' : '-100%', opacity: 0 },
animate: { y: 0, opacity: 1 },
exit: { y: up ? '-120%' : '120%', opacity: 0 },
transition: { type: 'spring', damping: 25, stiffness: 300 }
}),
flip: up => ({
initial: { rotateX: up ? -90 : 90, opacity: 0, transformPerspective: 480 },
animate: { rotateX: 0, opacity: 1, transformPerspective: 480 },
exit: { rotateX: up ? 90 : -90, opacity: 0, transformPerspective: 480 },
transition: { type: 'tween', duration: 0.6, ease: [0.34, 1.4, 0.64, 1] },
exitTransition: { type: 'tween', duration: 0.32, ease: [0.5, 0, 0.75, 0] }
}),
blur: up => ({
initial: { y: up ? '45%' : '-45%', opacity: 0 },
animate: { y: 0, opacity: 1 },
exit: { y: up ? '-45%' : '45%', opacity: 0 },
transition: { type: 'tween', duration: 0.55, ease: [0.22, 1, 0.36, 1] }
}),
scale: up => ({
initial: { scale: up ? 0.35 : 1.7, opacity: 0 },
animate: { scale: 1, opacity: 1 },
exit: { scale: up ? 1.7 : 0.35, opacity: 0 },
transition: { type: 'spring', damping: 17, stiffness: 240 }
}),
drop: () => ({
initial: { y: '-110%', opacity: 0 },
animate: { y: 0, opacity: 1 },
exit: { y: '110%', opacity: 0 },
transition: { type: 'spring', damping: 18, stiffness: 320, mass: 0.9 },
exitTransition: { type: 'tween', duration: 0.3, ease: [0.55, 0, 1, 0.45] }
})
};
const readableText = (color: string): string | undefined => {
const value = String(color ?? '').trim();
let rgb: number[] | null = null;
const hex = value.match(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (hex) {
const digits = hex[1].length < 6 ? [...hex[1].slice(0, 3)].map(c => c + c).join('') : hex[1].slice(0, 6);
rgb = [0, 2, 4].map(i => parseInt(digits.slice(i, i + 2), 16));
} else {
const fn = value.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i);
if (fn) rgb = fn.slice(1, 4).map(Number);
}
if (!rgb) return undefined;
const [r, g, b] = rgb.map(channel => {
const c = Math.min(Math.max(channel / 255, 0), 1);
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.3 ? '#0b0b0c' : '#ffffff';
};
const RotatingText = forwardRef<RotatingTextRef, RotatingTextProps>((props, ref) => {
const {
texts,
transition,
initial,
animate,
exit,
effect = 'slide',
direction = 'up',
highlight = false,
highlightColor = '#a855f7',
animatePresenceMode = 'wait',
animatePresenceInitial = false,
rotationInterval = 2000,
staggerDuration = 0,
staggerFrom = 'first',
loop = true,
auto = true,
pauseOnHover = false,
blur = 0,
splitBy = 'characters',
onNext,
onMouseEnter,
onMouseLeave,
mainClassName,
splitLevelClassName,
elementLevelClassName,
style,
...rest
} = props;
const [currentTextIndex, setCurrentTextIndex] = useState<number>(0);
const [hovered, setHovered] = useState(false);
const indexRef = useRef(0);
const onNextRef = useRef(onNext);
onNextRef.current = onNext;
const contentRef = useRef<HTMLSpanElement | null>(null);
const width = useMotionValue<number | string>('auto');
const reduceMotion = useReducedMotion();
const lastIndex = Math.max(texts.length - 1, 0);
const activeIndex = Math.min(currentTextIndex, lastIndex);
const elements = useMemo(() => {
const currentText: string = texts[activeIndex] ?? '';
if (splitBy === 'characters') {
const words = currentText.split(' ');
return words.map((word, i) => ({
characters: splitIntoCharacters(word),
needsSpace: i !== words.length - 1
}));
}
if (splitBy === 'words') {
return currentText.split(' ').map((word, i, arr) => ({
characters: [word],
needsSpace: i !== arr.length - 1
}));
}
if (splitBy === 'lines') {
return currentText.split('\n').map((line, i, arr) => ({
characters: [line],
needsSpace: i !== arr.length - 1
}));
}
return currentText.split(splitBy).map((part, i, arr) => ({
characters: [part],
needsSpace: i !== arr.length - 1
}));
}, [texts, activeIndex, splitBy]);
const order = useMemo(() => {
const total = elements.reduce((sum, word) => sum + word.characters.length, 0);
const shuffled = Array.from({ length: total }, (_, i) => i).sort(() => Math.random() - 0.5);
return { total, shuffled };
}, [elements]);
const getStaggerDelay = (index: number): number => {
const { total, shuffled } = order;
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 shuffled[index] * staggerDuration;
return Math.abs((staggerFrom as number) - index) * staggerDuration;
};
const goTo = useCallback((index: number) => {
if (index === indexRef.current) return;
indexRef.current = index;
setCurrentTextIndex(index);
onNextRef.current?.(index);
}, []);
const next = useCallback(() => {
const current = Math.min(indexRef.current, lastIndex);
goTo(current < lastIndex ? current + 1 : loop ? 0 : current);
}, [lastIndex, loop, goTo]);
const previous = useCallback(() => {
const current = Math.min(indexRef.current, lastIndex);
goTo(current > 0 ? current - 1 : loop ? lastIndex : current);
}, [lastIndex, loop, goTo]);
const jumpTo = useCallback((index: number) => goTo(Math.max(0, Math.min(index, lastIndex))), [lastIndex, goTo]);
const reset = useCallback(() => goTo(0), [goTo]);
useImperativeHandle(
ref,
() => ({
next,
previous,
jumpTo,
reset
}),
[next, previous, jumpTo, reset]
);
const paused = pauseOnHover && hovered;
useEffect(() => {
if (!auto || paused) return;
const timeoutId = setTimeout(next, rotationInterval);
return () => clearTimeout(timeoutId);
}, [next, rotationInterval, auto, paused, activeIndex]);
useIsomorphicLayoutEffect(() => {
const content = contentRef.current;
if (!highlight || !content) {
width.set('auto');
return undefined;
}
let controls: AnimationPlaybackControls | null = null;
let settled = false;
const fit = () => {
const target = content.offsetWidth + 1;
controls?.stop();
if (!settled || reduceMotion) {
settled = true;
width.set(target);
return;
}
controls = animateValue(width, target, WIDTH_SPRING);
};
fit();
const observer = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(fit) : null;
observer?.observe(content);
return () => {
observer?.disconnect();
controls?.stop();
};
}, [highlight, reduceMotion, width]);
const handleMouseEnter = (event: React.MouseEvent<HTMLSpanElement>) => {
if (pauseOnHover) setHovered(true);
onMouseEnter?.(event);
};
const handleMouseLeave = (event: React.MouseEvent<HTMLSpanElement>) => {
setHovered(false);
onMouseLeave?.(event);
};
const motionPreset: EffectPreset = (EFFECTS[effect] ?? EFFECTS.slide)(direction !== 'down');
const blurAmount = blur > 0 ? blur : effect === 'blur' ? 10 : 0;
const enterState: boolean | Target | VariantLabels = initial ?? motionPreset.initial;
const restState: boolean | VariantLabels | TargetAndTransition = animate ?? motionPreset.animate;
const leaveState: Target | VariantLabels = exit ?? motionPreset.exit;
const charTransition = transition ?? motionPreset.transition;
const exitTransition = transition || exit ? null : motionPreset.exitTransition;
const enterFrom = blurAmount > 0 ? withFilter(enterState, `blur(${blurAmount}px)`) : enterState;
const enterTo = blurAmount > 0 ? withFilter(restState, 'blur(0px)') : restState;
const leaveTo = blurAmount > 0 ? withFilter(leaveState, `blur(${blurAmount}px)`) : leaveState;
const charStyle = effect === 'flip' ? FLIP_STYLE : undefined;
const blockStyle = highlight
? { ...style, width, backgroundColor: highlightColor, color: readableText(highlightColor) ?? style?.color }
: style;
const presence = (
<AnimatePresence mode={animatePresenceMode} initial={animatePresenceInitial}>
<motion.span
key={activeIndex}
className={cn(splitBy === 'lines' ? 'flex flex-col w-full' : 'flex flex-wrap whitespace-pre-wrap relative')}
layout={!highlight}
aria-hidden="true"
>
{elements.map((wordObj, wordIndex, array) => {
const previousCharsCount = array.slice(0, wordIndex).reduce((sum, word) => sum + word.characters.length, 0);
return (
<span key={wordIndex} className={cn('inline-flex', splitLevelClassName)}>
{wordObj.characters.map((char, charIndex) => {
const delay = getStaggerDelay(previousCharsCount + charIndex);
return (
<motion.span
key={charIndex}
initial={enterFrom}
animate={enterTo}
exit={
exitTransition ? { ...(leaveTo as Target), transition: { ...exitTransition, delay } } : leaveTo
}
transition={{ ...charTransition, delay }}
className={cn('inline-block', elementLevelClassName)}
style={charStyle}
>
{char}
</motion.span>
);
})}
{wordObj.needsSpace && <span className="whitespace-pre"> </span>}
</span>
);
})}
</motion.span>
</AnimatePresence>
);
return (
<MotionConfig reducedMotion="user">
<motion.span
className={cn(
'flex whitespace-pre-wrap relative',
highlight
? 'box-content flex-nowrap justify-center overflow-hidden px-[0.28em] py-[0.1em] rounded-[0.16em]'
: 'flex-wrap',
mainClassName
)}
{...rest}
style={blockStyle}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
layout={!highlight}
transition={transition ?? LAYOUT_SPRING}
>
<span className="sr-only">{texts[activeIndex]}</span>
{highlight ? (
<span ref={contentRef} className="flex shrink-0 whitespace-pre">
{presence}
</span>
) : (
presence
)}
</motion.span>
</MotionConfig>
);
});
RotatingText.displayName = 'RotatingText';
export default RotatingText;
React BitsText effectsMIT+
React BitsText effectsMIT+
React BitsCursor & effectsMIT+
Eldora UIMedia & 3D
React BitsText effectsMIT+
Motion PrimitivesCards
8bitcnButtons
React BitsBackgroundsMIT+
React BitsText effectsMIT+
React BitsText effectsMIT+
React BitsCursor & effectsMIT+
Motion PrimitivesMedia & 3D
Motion PrimitivesCursor & effects
Motion PrimitivesMedia & 3D
Motion PrimitivesCursor & effects