Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 36 additions & 17 deletions components/core/text-morph.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';
import { cn } from '@/lib/utils';
import { AnimatePresence, motion, Transition, Variants } from 'motion/react';
import { useMemo, useId } from 'react';
"use client";
import { cn } from "@/lib/utils";
import { AnimatePresence, motion, Transition, Variants } from "motion/react";
import { useMemo, useId } from "react";

export type TextMorphProps = {
children: string;
Expand All @@ -14,7 +14,7 @@ export type TextMorphProps = {

export function TextMorph({
children,
as: Component = 'p',
as: Component = "p",
className,
style,
variants,
Expand All @@ -23,15 +23,34 @@ export function TextMorph({
const uniqueId = useId();

const characters = useMemo(() => {
const charCounts: Record<string, number> = {};
const chars = children.split("");

return children.split('').map((char) => {
const totalCharCounts = chars.reduce(
(acc, char) => {
const lower = char.toLowerCase();
acc[lower] = (acc[lower] || 0) + 1;
return acc;
},
{} as Record<string, number>
);

const leftCharCounts: Record<string, number> = {};
const rightCharCounts = { ...totalCharCounts };

return chars.map((char) => {
const lowerChar = char.toLowerCase();
charCounts[lowerChar] = (charCounts[lowerChar] || 0) + 1;

const leftCount = (leftCharCounts[lowerChar] =
(leftCharCounts[lowerChar] || 0) + 1);

const rightCount = rightCharCounts[lowerChar];
if (rightCharCounts[lowerChar] !== undefined) {
rightCharCounts[lowerChar]--;
}

return {
id: `${uniqueId}-${lowerChar}${charCounts[lowerChar]}`,
label: char === ' ' ? '\u00A0' : char,
id: `${uniqueId}-${lowerChar}-${leftCount}-${rightCount}`,
label: char === " " ? "\u00A0" : char,
};
});
}, [children, uniqueId]);
Expand All @@ -43,24 +62,24 @@ export function TextMorph({
};

const defaultTransition: Transition = {
type: 'spring',
type: "spring",
stiffness: 280,
damping: 18,
mass: 0.3,
};

return (
<Component className={cn(className)} aria-label={children} style={style}>
<AnimatePresence mode='popLayout' initial={false}>
<AnimatePresence mode="popLayout" initial={false}>
{characters.map((character) => (
<motion.span
key={character.id}
layoutId={character.id}
className='inline-block'
aria-hidden='true'
initial='initial'
animate='animate'
exit='exit'
className="inline-block"
aria-hidden="true"
initial="initial"
animate="animate"
exit="exit"
variants={variants || defaultVariants}
transition={transition || defaultTransition}
>
Expand Down