A encrypted-text component from Aceternity UI.
From Aceternity UI
1"use client";
2import React, { useEffect, useRef, useState } from "react";
3import { motion, useInView } from "motion/react";
4import { cn } from "@/lib/utils";
5
6type EncryptedTextProps = {
7 text: string;
8 className?: string;
9 /**
10 * Time in milliseconds between revealing each subsequent real character.
11 * Lower is faster. Defaults to 50ms per character.
12 */
13 revealDelayMs?: number;
14 /** Optional custom character set to use for the gibberish effect. */
15 charset?: string;
16 /**
17 * Time in milliseconds between gibberish flips for unrevealed characters.
18 * Lower is more jittery. Defaults to 50ms.
19 */
20 flipDelayMs?: number;
21 /** CSS class for styling the encrypted/scrambled characters */
22 encryptedClassName?: string;
23 /** CSS class for styling the revealed characters */
24 revealedClassName?: string;
25};
26
27const DEFAULT_CHARSET =
28 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-={}[];:,.<>/?";
29
30function generateRandomCharacter(charset: string): string {
31 const index = Math.floor(Math.random() * charset.length);
32 return charset.charAt(index);
33}
34
35function generateGibberishPreservingSpaces(
36 original: string,
37 charset: string,
38): string {
39 if (!original) return "";
40 let result = "";
41 for (let i = 0; i < original.length; i += 1) {
42 const ch = original[i];
43 result += ch === " " ? " " : generateRandomCharacter(charset);
44 }
45 return result;
46}
47
48export const EncryptedText: React.FC<EncryptedTextProps> = ({
49 text,
50 className,
51 revealDelayMs = 50,
52 charset = DEFAULT_CHARSET,
53 flipDelayMs = 50,
54 encryptedClassName,
55 revealedClassName,
56}) => {
57 const ref = useRef<HTMLSpanElement>(null);
58 const isInView = useInView(ref, { once: true });
59
60 const [revealCount, setRevealCount] = useState<number>(0);
61 const animationFrameRef = useRef<number | null>(null);
62 const startTimeRef = useRef<number>(0);
63 const lastFlipTimeRef = useRef<number>(0);
64 const scrambleCharsRef = useRef<string[]>(
65 text ? generateGibberishPreservingSpaces(text, charset).split("") : [],
66 );
67
68 useEffect(() => {
69 if (!isInView) return;
70
71 // Reset state for a fresh animation whenever dependencies change
72 const initial = text
73 ? generateGibberishPreservingSpaces(text, charset)
74 : "";
75 scrambleCharsRef.current = initial.split("");
76 startTimeRef.current = performance.now();
77 lastFlipTimeRef.current = startTimeRef.current;
78 setRevealCount(0);
79
80 let isCancelled = false;
81
82 const update = (now: number) => {
83 if (isCancelled) return;
84
85 const elapsedMs = now - startTimeRef.current;
86 const totalLength = text.length;
87 const currentRevealCount = Math.min(
88 totalLength,
89 Math.floor(elapsedMs / Math.max(1, revealDelayMs)),
90 );
91
92 setRevealCount(currentRevealCount);
93
94 if (currentRevealCount >= totalLength) {
95 return;
96 }
97
98 // Re-randomize unrevealed scramble characters on an interval
99 const timeSinceLastFlip = now - lastFlipTimeRef.current;
100 if (timeSinceLastFlip >= Math.max(0, flipDelayMs)) {
101 for (let index = 0; index < totalLength; index += 1) {
102 if (index >= currentRevealCount) {
103 if (text[index] !== " ") {
104 scrambleCharsRef.current[index] =
105 generateRandomCharacter(charset);
106 } else {
107 scrambleCharsRef.current[index] = " ";
108 }
109 }
110 }
111 lastFlipTimeRef.current = now;
112 }
113
114 animationFrameRef.current = requestAnimationFrame(update);
115 };
116
117 animationFrameRef.current = requestAnimationFrame(update);
118
119 return () => {
120 isCancelled = true;
121 if (animationFrameRef.current !== null) {
122 cancelAnimationFrame(animationFrameRef.current);
123 }
124 };
125 }, [isInView, text, revealDelayMs, charset, flipDelayMs]);
126
127 if (!text) return null;
128
129 return (
130 <motion.span
131 ref={ref}
132 className={cn(className)}
133 aria-label={text}
134 role="text"
135 >
136 {text.split("").map((char, index) => {
137 const isRevealed = index < revealCount;
138 const displayChar = isRevealed
139 ? char
140 : char === " "
141 ? " "
142 : (scrambleCharsRef.current[index] ??
143 generateRandomCharacter(charset));
144
145 return (
146 <span
147 key={index}
148 className={cn(isRevealed ? revealedClassName : encryptedClassName)}
149 >
150 {displayChar}
151 </span>
152 );
153 })}
154 </motion.span>
155 );
156};
157