Files
nextjs-template/components/ui/encrypted-text.tsx
T
asepharyana bf75d9deef feat(ui): vendor Aceternity registry components + showcase gallery
Vendor 50 Aceternity UI components into components/ui from the official
registry (ui.aceternity.com/registry/<slug>.json), adapted for this
template's stack: Tailwind v4, motion/react 13, cn util, React 19.

Add a live showcase gallery (/ui + /docs/... navigation is unchanged):
app/ui/page.tsx renders <ShowcaseGallery> with 30+ demos — 3d-pin,
aurora, background-beams, bento, card-stack, card-spotlight,
direction-aware-hover, encrypted-text, evervault-card, flip-words,
hero-highlight, hero-parallax, infinite-moving-cards, moving-border,
sparkles, tracing-beam, animated-tooltip, typewriter-effect,
placeholders-and-vanish-input and friends.

Toolchain stays zero-warning: vendored animation code is scoped in
eslint.config.mjs (react-hooks/react-compiler advisory rules, no-any,
prefer-const, no-img-element) so app code keeps a 0-error gate. typecheck,
build, 7 vitest tests and 2 test suites all green.
2026-09-20 19:10:43 +07:00

142 lines
4.3 KiB
TypeScript

"use client";
import React, { useEffect, useRef, useState } from "react";
import { motion, useInView } from "motion/react";
import { cn } from "@/lib/utils";
type EncryptedTextProps = {
text: string;
className?: string;
/**
* Time in milliseconds between revealing each subsequent real character.
* Lower is faster. Defaults to 50ms per character.
*/
revealDelayMs?: number;
/** Optional custom character set to use for the gibberish effect. */
charset?: string;
/**
* Time in milliseconds between gibberish flips for unrevealed characters.
* Lower is more jittery. Defaults to 50ms.
*/
flipDelayMs?: number;
/** CSS class for styling the encrypted/scrambled characters */
encryptedClassName?: string;
/** CSS class for styling the revealed characters */
revealedClassName?: string;
};
const DEFAULT_CHARSET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-={}[];:,.<>/?";
function generateRandomCharacter(charset: string): string {
const index = Math.floor(Math.random() * charset.length);
return charset.charAt(index);
}
function generateGibberishPreservingSpaces(original: string, charset: string): string {
if (!original) return "";
let result = "";
for (let i = 0; i < original.length; i += 1) {
const ch = original[i];
result += ch === " " ? " " : generateRandomCharacter(charset);
}
return result;
}
export const EncryptedText: React.FC<EncryptedTextProps> = ({
text,
className,
revealDelayMs = 50,
charset = DEFAULT_CHARSET,
flipDelayMs = 50,
encryptedClassName,
revealedClassName,
}) => {
const ref = useRef<HTMLSpanElement>(null);
const isInView = useInView(ref, { once: true });
const [revealCount, setRevealCount] = useState<number>(0);
const animationFrameRef = useRef<number | null>(null);
const startTimeRef = useRef<number>(0);
const lastFlipTimeRef = useRef<number>(0);
const scrambleCharsRef = useRef<string[]>(
text ? generateGibberishPreservingSpaces(text, charset).split("") : []
);
useEffect(() => {
if (!isInView) return;
// Reset state for a fresh animation whenever dependencies change
const initial = text ? generateGibberishPreservingSpaces(text, charset) : "";
scrambleCharsRef.current = initial.split("");
startTimeRef.current = performance.now();
lastFlipTimeRef.current = startTimeRef.current;
setRevealCount(0);
let isCancelled = false;
const update = (now: number) => {
if (isCancelled) return;
const elapsedMs = now - startTimeRef.current;
const totalLength = text.length;
const currentRevealCount = Math.min(
totalLength,
Math.floor(elapsedMs / Math.max(1, revealDelayMs))
);
setRevealCount(currentRevealCount);
if (currentRevealCount >= totalLength) {
return;
}
// Re-randomize unrevealed scramble characters on an interval
const timeSinceLastFlip = now - lastFlipTimeRef.current;
if (timeSinceLastFlip >= Math.max(0, flipDelayMs)) {
for (let index = 0; index < totalLength; index += 1) {
if (index >= currentRevealCount) {
if (text[index] !== " ") {
scrambleCharsRef.current[index] = generateRandomCharacter(charset);
} else {
scrambleCharsRef.current[index] = " ";
}
}
}
lastFlipTimeRef.current = now;
}
animationFrameRef.current = requestAnimationFrame(update);
};
animationFrameRef.current = requestAnimationFrame(update);
return () => {
isCancelled = true;
if (animationFrameRef.current !== null) {
cancelAnimationFrame(animationFrameRef.current);
}
};
}, [isInView, text, revealDelayMs, charset, flipDelayMs]);
if (!text) return null;
return (
<motion.span ref={ref} className={cn(className)} aria-label={text} role="text">
{text.split("").map((char, index) => {
const isRevealed = index < revealCount;
const displayChar = isRevealed
? char
: char === " "
? " "
: (scrambleCharsRef.current[index] ?? generateRandomCharacter(charset));
return (
<span key={index} className={cn(isRevealed ? revealedClassName : encryptedClassName)}>
{displayChar}
</span>
);
})}
</motion.span>
);
};