Hiệu năng
Cần chú ýTốc độ khung hình: trung bình 60 fps, p5 59.5 · Tác vụ dài: 0 tác vụ, tổng 0 ms, dài nhất 0 ms · Mã nguồn gzip 14 KB · Khi chạy 196 KB
Spring Scale InMITHiệu ứng chữAnimata
Component React Hiệu ứng chữ của Animata. Được thu thập nguyên vẹn từ Animata theo giấy phép MIT và hiển thị trực tiếp tại đây.
Báo cáo chất lượng
Xếp loại và điểm số đến từ các kiểm tra tự động lúc dựng hoặc kiểm thử. Nếu một mục chưa chạy, nó được đánh dấu Chưa kiểm tra — không bao giờ bịa số liệu.
Tốc độ khung hình: trung bình 60 fps, p5 59.5 · Tác vụ dài: 0 tác vụ, tổng 0 ms, dài nhất 0 ms · Mã nguồn gzip 14 KB · Khi chạy 196 KB
Vấn đề 0 · Trình đọc màn hình: Đạt
Tôn trọng giảm chuyển động
Không tràn
Số liệu tốc độ khung hình và tác vụ dài được đo trong Chromium không giao diện với WebGL phần mềm. Chúng chỉ nên được so sánh giữa các thành phần trên trang này, và không đại diện cho thiết bị thật.
Không có vi phạm axe-core.

Kiểm tra ngày 15 thg 11, 2026 · Số liệu đến từ tập lệnh tự động, không phải mẫu viết tay.
Hiển thị đúng kích thước thật.
Bản sao bắt đầu bằng thông báo giấy phép. Hãy giữ lại khi dùng mã.
<div id="root"></div>:root{--bg:#f6f4f0;--ink:#17181a;--background:40 20% 96%;--foreground:24 10% 8%;--card:0 0% 100%}html,body{min-height:100%;margin:0;background:var(--bg);color:var(--ink)}html,body{height:100%;overflow:hidden}body{display:grid;place-items:center}#root{display:grid;place-items:center;max-width:100%;max-height:100%;box-sizing:border-box;padding:16px;color:hsl(var(--foreground))}#root.full{width:100%;height:100%;padding:0}@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-play-state:paused!important;transition-duration:0s!important}}
/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:"Paper Mono", ui-monospace, monospace;--color-yellow-300:oklch(90.5% .182 98.111);--color-yellow-500:oklch(79.5% .184 86.047);--color-blue-300:oklch(80.9% .105 251.813);--color-blue-500:oklch(62.3% .214 259.815);--color-zinc-100:oklch(96.7% .001 286.375);--color-zinc-200:oklch(92% .004 286.32);--color-zinc-700:oklch(37% .013 285.805);--color-zinc-800:oklch(27.4% .006 286.033);--color-zinc-900:oklch(21% .006 285.885);--color-zinc-950:oklch(14.1% .005 285.823);--color-white:#fff;--spacing:.25rem;--radius-lg:var(--radius);--ease-out:cubic-bezier(.22, 1, .36, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-border:hsl(var(--border));--color-background:hsl(var(--background));--color-foreground:hsl(var(--foreground));--ease-apple:cubic-bezier(.4, 0, .6, 1)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{border-color:var(--color-border)}body{background-color:var(--color-background);color:var(--color-foreground)}:root{--background:0 0% 100%;--foreground:0 0% 11%;--card:0 0% 100%;--card-foreground:0 0% 11%;--popover:0 0% 100%;--popover-foreground:0 0% 11%;--primary:0 0% 11%;--primary-foreground:0 0% 100%;--secondary:0 0% 96%;--secondary-foreground:0 0% 11%;--muted:0 0% 96%;--muted-foreground:0 0% 43%;--accent:262 83% 58%;--accent-foreground:0 0% 100%;--destructive:0 84% 60%;--destructive-foreground:0 0% 98%;--border:0 0% 90%;--input:0 0% 90%;--ring:262 83% 58%;--radius:.75rem;--surface-alt:0 0% 96%;--surface-card:0 0% 100%;--surface-dark:0 0% 7%;--text-secondary:0 0% 43%;--ink:#76756f;--ink-faint:#e3e3e3;--link:210 100% 40%;--link-hover:210 100% 32%;--shadow-sm:0 1px 2px #0000000d;--shadow-md:0 2px 8px #0000000f, 0 4px 16px #0000000a;--shadow-lg:0 4px 12px #0000000f, 0 12px 32px #00000014;--footer-surface:#f5f5f7;--footer-ink:#0f1d42;--footer-ink-muted:#1a2d5c;--footer-accent:#1a4fff;--footer-gold:#fc0;--footer-category-title:#1d1d1f;--footer-category-link:#515154;--footer-stamp:#9f9f9f}.dark{--background:0 0% 0%;--foreground:0 0% 96%;--card:0 0% 4%;--card-foreground:0 0% 96%;--popover:0 0% 4%;--popover-foreground:0 0% 96%;--primary:0 0% 96%;--primary-foreground:0 0% 0%;--secondary:0 0% 10%;--secondary-foreground:0 0% 96%;--muted:0 0% 10%;--muted-foreground:0 0% 45%;--accent:262 83% 65%;--accent-foreground:0 0% 100%;--destructive:0 62% 30%;--destructive-foreground:0 0% 98%;--border:0 0% 12%;--input:0 0% 12%;--ring:262 83% 65%;--surface-alt:0 0% 4%;--surface-card:0 0% 6%;--surface-dark:0 0% 2%;--text-secondary:0 0% 55%;--ink:#e3e3e3;--ink-faint:#76756f;--link:262 80% 70%;--link-hover:262 80% 80%;--shadow-sm:none;--shadow-md:none;--shadow-lg:none;--footer-surface:#1d1d1f;--footer-ink:#f5f5f7;--footer-ink-muted:#86868b;--footer-accent:#fc0;--footer-gold:#fc0;--footer-category-title:#f5f5f7;--footer-category-link:#86868b;--footer-stamp:#48484a}}@layer components{.text-animator-demo .text-animation-stage,[data-text-animator-demo] .text-animation-stage{perspective:900px;padding:clamp(1rem,5cqi,1.5rem);font-size:clamp(1rem,10cqi,2rem);font-weight:500;line-height:1.1}.text-animator-demo .text-animation-title,.text-animator-demo .text-animation-kinetic-word,[data-text-animator-demo] .text-animation-title,[data-text-animator-demo] .text-animation-kinetic-word{text-align:center;letter-spacing:-.025em}.text-animator-demo .text-animation-title,[data-text-animator-demo] .text-animation-title{text-wrap:balance;font-variant-numeric:tabular-nums}.text-animation-stage{grid-template-areas:"title";place-items:center;width:100%;height:100%;min-height:0;display:grid;container-type:inline-size}.text-animation-title{pointer-events:none;transform-style:preserve-3d;grid-area:title;margin:0}.text-animation-unit{transform-origin:50% 55%;white-space:pre;will-change:transform,opacity,filter;backface-visibility:hidden;display:inline-block}.text-animation-unit.line{display:block}.text-animation-kinetic-line{width:min(92%,270px);height:72px;position:relative}.text-animation-kinetic-stack{width:min(92%,270px);height:132px;position:relative}.text-animation-kinetic-word{white-space:nowrap;will-change:transform,opacity,filter;backface-visibility:hidden;position:absolute;top:50%;left:50%}.text-animation-fallback{opacity:.74}}@layer utilities{.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.block{display:block}.flex{display:flex}.grid{display:grid}.h-56{height:calc(var(--spacing) * 56)}.h-80{height:calc(var(--spacing) * 80)}.min-h-56{min-height:calc(var(--spacing) * 56)}.w-\[32rem\]{width:32rem}.w-full{width:100%}.transform{transform:var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, )}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-hidden{overflow:hidden}.rounded-lg{border-radius:var(--radius-lg)}.border{border-style:var(--tw-border-style);border-width:1px}.border-zinc-200{border-color:var(--color-zinc-200)}.bg-white{background-color:var(--color-white)}.text-foreground{color:var(--color-foreground)}.text-zinc-900{color:var(--color-zinc-900)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )}.filter{filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )}.dark\:border-zinc-800:where(.dark,.dark *){border-color:var(--color-zinc-800)}.dark\:bg-zinc-950:where(.dark,.dark *){background-color:var(--color-zinc-950)}.dark\:text-zinc-100:where(.dark,.dark *){color:var(--color-zinc-100)}@keyframes orbit-move{0%{transform:translate(-50%,-50%)rotateY(-40deg)rotateX(70deg)rotate(0)translate(100px)}to{transform:translate(-50%,-50%)rotateY(-40deg)rotateX(70deg)rotate(360deg)translate(100px)}}@keyframes counter-rotate{0%{opacity:1;transform:rotate(0)rotateX(-70deg)rotateY(40deg)scale(1)}25%{opacity:1;transform:rotate(-90deg)rotateX(-70deg)rotateY(40deg)scale(1.2)}50%{opacity:.3;transform:rotate(-180deg)rotateX(-70deg)rotateY(40deg)scale(.8)}75%{opacity:.3;transform:rotate(-270deg)rotateX(-70deg)rotateY(40deg)scale(.8)}to{opacity:1;transform:rotate(-360deg)rotateX(-70deg)rotateY(40deg)scale(1)}}@keyframes orbit-indexes{0%,25%,to{z-index:11}50%,99%{z-index:9}}}@property --tw-animation-delay{syntax:"*";inherits:false;initial-value:0s}@property --tw-animation-direction{syntax:"*";inherits:false;initial-value:normal}@property --tw-animation-duration{syntax:"*";inherits:false}@property --tw-animation-fill-mode{syntax:"*";inherits:false;initial-value:none}@property --tw-animation-iteration-count{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-enter-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-enter-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-blur{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-opacity{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-rotate{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-scale{syntax:"*";inherits:false;initial-value:1}@property --tw-exit-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-exit-translate-y{syntax:"*";inherits:false;initial-value:0}.preview{margin-bottom:calc(var(--spacing) * 4)}.preview-light{background-color:#fefefe;background-image:radial-gradient(#efefef 1px,#0000 1px),radial-gradient(#efefef 1px,#0000 1px);background-position:0 0,10px 10px;background-size:20px 20px}.preview-dark{background-image:radial-gradient(#6a6a6a 1px,#0000 1px),radial-gradient(#6a6a6a 1px,#0000 1px);background-position:0 0,10px 10px;background-size:20px 20px}.component-list-item{border-color:var(--color-zinc-200);background-color:#fefefe;background-image:radial-gradient(#efefef 1px,#0000 1px),radial-gradient(#efefef 1px,#0000 1px);background-position:0 0,10px 10px;background-size:20px 20px}.dark .component-list-item{border-color:var(--color-zinc-700);background-color:var(--color-zinc-950);background-image:radial-gradient(#6a6a6a 1px,#0000 1px),radial-gradient(#6a6a6a 1px,#0000 1px);background-position:0 0,10px 10px;background-size:20px 20px}[style*="opacity: 1"]>.scroll-baby{color:var(--color-yellow-300)}[style*="opacity: 1"]>.scroll-baby:where(.dark,.dark *){color:var(--color-yellow-500)}[style*="opacity: 1"]>.scroll-file{color:var(--color-blue-300)}[style*="opacity: 1"]>.scroll-file:where(.dark,.dark *){color:var(--color-blue-500)}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}// animata source (MIT). npm i clsx react tailwind-merge · Tailwind CSS v4
// ── animata/text/spring-scale-in.tsx (https://github.com/codse/animata/blob/25c27e5a874c60a56dcc1609df3b2c4f5f8456f8/animata/text/spring-scale-in.tsx)
"use client";
import { useMemo } from "react";
import TextAnimator, {
type TextAnimationPhaseSpec,
type TextAnimationSpec,
} from "@/animata/text/text-animator";
const BASE_SPEC: TextAnimationSpec = {
id: "spring-scale-in",
target: "per-word",
enter: {
durationMs: 360,
staggerMs: 95,
easing: "cubic-bezier(0.34, 1.56, 0.64, 1)",
from: {
opacity: 0,
scale: 0.7,
},
to: {
opacity: 1,
scale: 1,
},
},
exit: {
durationMs: 200,
staggerMs: 80,
easing: "cubic-bezier(0.7, 0, 0.84, 0)",
from: {
opacity: 1,
scale: 1,
},
to: {
opacity: 0,
scale: 0.8,
},
},
swap: {
mode: "crossfade",
overlapMs: 0,
microDelayMs: 35,
},
};
const DEFAULT_SAMPLES: readonly string[] = [
"Lands with a small bounce.",
"Settles after the spring.",
"A gentle overshoot.",
];
export interface SpringScaleInProps {
/** Text(s) to animate. String = single, array = cycle through. */
text?: string | string[];
/** Override enter phase (merged with default). */
enter?: Partial<TextAnimationPhaseSpec>;
/** Override exit phase (merged with default). */
exit?: Partial<TextAnimationPhaseSpec>;
/** Global speed multiplier. Defaults to the runtime default (0.72) when omitted. */
speed?: number;
/** Hold time between enter and exit in ms. Defaults to the runtime default (550) when omitted. */
holdMs?: number;
/** Gap between cycles in ms. Defaults to the runtime default (320) when omitted. */
gapMs?: number;
/** Y-travel multiplier for all transforms. Defaults to the runtime default (0.58) when omitted. */
yTravel?: number;
className?: string;
}
export default function SpringScaleIn({
text,
enter,
exit,
speed,
holdMs,
gapMs,
yTravel,
className,
}: SpringScaleInProps = {}) {
const spec = useMemo<TextAnimationSpec>(
() => ({
...BASE_SPEC,
enter: {
...BASE_SPEC.enter,
...enter,
from: { ...BASE_SPEC.enter.from, ...enter?.from },
to: { ...BASE_SPEC.enter.to, ...enter?.to },
},
exit: {
...BASE_SPEC.exit,
...exit,
from: { ...BASE_SPEC.exit.from, ...exit?.from },
to: { ...BASE_SPEC.exit.to, ...exit?.to },
},
}),
[enter, exit],
);
const samples = useMemo(() => {
if (text == null) return [...DEFAULT_SAMPLES];
return Array.isArray(text) ? text : [text];
}, [text]);
return (
<TextAnimator
spec={spec}
samples={samples}
speed={speed}
holdMs={holdMs}
gapMs={gapMs}
yTravel={yTravel}
className={className}
/>
);
}
// ── animata/text/text-animator-demo.ts (https://github.com/codse/animata/blob/25c27e5a874c60a56dcc1609df3b2c4f5f8456f8/animata/text/text-animator-demo.ts)
/** Demo frame classes — typography lives in co-located text-animator-demo.css (imported via styles/globals.css). */
export const TEXT_ANIMATOR_DEMO_CLASS = "text-animator-demo";
/** Storybook frame — bordered tile matching doc previews. */
export const TEXT_ANIMATOR_STORY_FRAME_CLASS = `${TEXT_ANIMATOR_DEMO_CLASS} h-80 w-[32rem] rounded-lg border border-zinc-200 bg-white text-zinc-900 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-100`;
/** Text category index grid tiles. */
export const TEXT_ANIMATOR_INDEX_FRAME_CLASS = `${TEXT_ANIMATOR_DEMO_CLASS} h-56 w-full min-h-56 text-foreground`;
// ── animata/text/text-animator-preset.stories-shared.ts (https://github.com/codse/animata/blob/25c27e5a874c60a56dcc1609df3b2c4f5f8456f8/animata/text/text-animator-preset.stories-shared.ts)
import { TEXT_ANIMATOR_STORY_FRAME_CLASS } from "@/animata/text/text-animator-demo";
export const TEXT_ANIMATOR_PRESET_STORY_ARGS = {
speed: 0.72,
holdMs: 550,
gapMs: 320,
className: TEXT_ANIMATOR_STORY_FRAME_CLASS,
} as const;
// ── animata/text/text-animator.css (https://github.com/codse/animata/blob/25c27e5a874c60a56dcc1609df3b2c4f5f8456f8/animata/text/text-animator.css)
@reference "tailwindcss";
@layer components {
.text-animation-stage {
@apply @container grid h-full min-h-0 w-full place-items-center [grid-template-areas:'title'];
}
.text-animation-title {
@apply m-0 pointer-events-none transform-3d [grid-area:title];
}
.text-animation-unit {
@apply inline-block whitespace-pre backface-hidden origin-[50%_55%] [will-change:transform,opacity,filter];
}
.text-animation-unit.line {
@apply block;
}
.text-animation-kinetic-line {
@apply relative h-[72px] w-[min(92%,270px)];
}
.text-animation-kinetic-stack {
@apply relative h-[132px] w-[min(92%,270px)];
}
.text-animation-kinetic-word {
@apply absolute top-1/2 left-1/2 whitespace-nowrap backface-hidden [will-change:transform,opacity,filter];
}
.text-animation-fallback {
@apply opacity-[0.74];
}
}
// ── animata/text/text-animator.tsx (https://github.com/codse/animata/blob/25c27e5a874c60a56dcc1609df3b2c4f5f8456f8/animata/text/text-animator.tsx)
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { TEXT_ANIMATOR_DEMO_CLASS } from "@/animata/text/text-animator-demo";
import { cn } from "@/lib/utils";
import "./text-animator.css";
export type TextAnimationTarget = "whole" | "per-character" | "per-word" | "per-line";
export type TextAnimationStaggerMode = "normal" | "center-out" | "edges-in" | "reverse";
export type TextAnimationCustomRenderer =
| "kinetic-center-build"
| "kinetic-top-build"
| "shared-slide-opacity-stage";
export interface TextAnimationFrameSpec {
opacity?: number;
xPx?: number;
yPx?: number;
zPx?: number;
scale?: number;
rotateDeg?: number;
rotateXDeg?: number;
rotateYDeg?: number;
blurPx?: number;
letterSpacingEm?: number;
color?: string;
}
export interface TextAnimationPhaseSpec {
durationMs: number;
staggerMs: number;
easing: string;
from: TextAnimationFrameSpec;
to: TextAnimationFrameSpec;
}
export interface TextAnimationSwapSpec {
mode?: string;
overlapMs?: number;
microDelayMs?: number;
}
export interface TextAnimationBuildSpec {
firstWordDurationMs?: number;
pushDurationMs?: number;
exitDurationMs?: number;
holdMs?: number;
betweenPhrasesMs?: number;
entryOffsetPx?: number;
entryOffsetYPx?: number;
wordGapPx?: number;
lineGapPx?: number;
firstWordYPx?: number;
entryScale?: number;
entryBlurPx?: number;
reflowBlurPx?: number;
exitYPx?: number;
exitBlurPx?: number;
easing?: string;
exitEasing?: string;
wordOpacityFrom?: number;
wordOpacityTo?: number;
wordOpacityDurationMs?: number;
}
export interface TextAnimationSpec {
id?: string;
target?: TextAnimationTarget;
enter: TextAnimationPhaseSpec;
exit: TextAnimationPhaseSpec;
swap?: TextAnimationSwapSpec;
customRenderer?: TextAnimationCustomRenderer;
staggerMode?: TextAnimationStaggerMode;
build?: TextAnimationBuildSpec;
}
export interface TextAnimatorProps {
spec: TextAnimationSpec;
samples?: string[];
phrases?: string[][];
className?: string;
stageClassName?: string;
/** Merged onto each animated `h3.text-animation-title` node the runtime creates. */
titleClassName?: string;
speed?: number;
holdMs?: number;
gapMs?: number;
yTravel?: number;
}
const DEFAULT_RUNTIME = {
tileSpeed: 0.72,
tileHoldMs: 550,
tileGapMs: 320,
tileYTravel: 0.58,
};
type TileFrame = {
color?: string;
filter: string;
letterSpacingEm: number | null;
opacity: number;
transform: string;
};
type LoopController = {
animations: Set<Animation>;
cancelled: boolean;
stage: HTMLElement;
timers: Set<number>;
pendingResolvers: Set<() => void>;
runtime: typeof DEFAULT_RUNTIME;
titleClassName?: string;
};
type KineticStageFrame = { filter: string; opacity: number; transform: string };
type TextPart = { text: string; animate: boolean; block?: boolean };
function splitTextByTarget(text: string, target: TextAnimationTarget): TextPart[] {
if (target === "whole") return [{ text, animate: true }];
if (target === "per-word") {
const parts: TextPart[] = [];
for (const m of text.matchAll(/(\S+|\s+)/g)) {
parts.push({ text: m[0], animate: /\S/.test(m[0]) });
}
return parts;
}
if (target === "per-line") {
return text.split("\n").map((line) => ({ text: line, animate: true, block: true }));
}
return [...text].map((c) => ({ text: c, animate: true }));
}
function getStaggerRanks(count: number, mode: TextAnimationStaggerMode = "normal"): number[] {
const order: number[] = [];
if (mode === "center-out") {
const center = (count - 1) / 2;
for (let i = 0; i < count; i += 1) order.push(i);
order.sort((a, b) => Math.abs(a - center) - Math.abs(b - center) || a - b);
} else if (mode === "edges-in") {
let l = 0;
let r = count - 1;
while (l <= r) {
order.push(l);
if (r !== l) order.push(r);
l += 1;
r -= 1;
}
} else if (mode === "reverse") {
for (let i = count - 1; i >= 0; i -= 1) order.push(i);
} else {
for (let i = 0; i < count; i += 1) order.push(i);
}
const ranks = Array.from({ length: count }, () => 0);
order.forEach((index, rank) => {
ranks[index] = rank;
});
return ranks;
}
function toAnimationFrame(values: TextAnimationFrameSpec | undefined, yTravel: number): TileFrame {
const f = values ?? {};
const frame: TileFrame = {
filter: `blur(${f.blurPx ?? 0}px)`,
letterSpacingEm: f.letterSpacingEm ?? null,
opacity: f.opacity ?? 1,
transform: `translate3d(${f.xPx ?? 0}px, ${(f.yPx ?? 0) * yTravel}px, ${
f.zPx ?? 0
}px) rotateX(${f.rotateXDeg ?? 0}deg) rotateY(${f.rotateYDeg ?? 0}deg) rotate(${
f.rotateDeg ?? 0
}deg) scale(${f.scale ?? 1})`,
};
if (f.color) frame.color = f.color;
return frame;
}
function materializeTileFrame(
frame: TileFrame,
unit: HTMLElement,
index: number,
count: number,
target: TextAnimationTarget,
): Keyframe {
const k: Keyframe = {
filter: frame.filter,
letterSpacing: "0em",
marginLeft: "0em",
marginRight: "0em",
opacity: frame.opacity,
transform: frame.transform,
};
if (frame.color) k.color = frame.color;
if (frame.letterSpacingEm == null) return k;
if (target === "per-character") {
const text = unit.textContent ?? "";
const isGlyph = /\S/.test(text);
const halfGap = `${frame.letterSpacingEm / 2}em`;
k.marginLeft = isGlyph && index > 0 ? halfGap : "0em";
k.marginRight = isGlyph && index < count - 1 ? halfGap : "0em";
return k;
}
k.letterSpacing = `${frame.letterSpacingEm}em`;
return k;
}
function makeTitle(
doc: Document,
text: string,
target: TextAnimationTarget,
titleClassName?: string,
) {
const title = doc.createElement("h3");
title.className = cn("text-animation-title", titleClassName);
const units: HTMLSpanElement[] = [];
splitTextByTarget(text, target).forEach((part) => {
const unit = doc.createElement("span");
unit.className = `text-animation-unit${part.block ? " line" : ""}`;
unit.textContent = part.text;
title.appendChild(unit);
if (part.animate) units.push(unit);
});
return { title, units };
}
function applyPhaseStart(
units: HTMLElement[],
phase: "enter" | "exit",
spec: TextAnimationSpec,
stage: HTMLElement,
yTravel: number,
) {
const baseFrame = toAnimationFrame(spec[phase].from, yTravel);
units.forEach((unit, index) => {
const kf = materializeTileFrame(
baseFrame,
unit,
index,
units.length,
spec.target ?? "per-character",
);
Object.assign(unit.style, kf);
});
stage.dataset.animationPhase = phase;
}
function animatePhase(
controller: LoopController,
units: HTMLElement[],
phase: "enter" | "exit",
spec: TextAnimationSpec,
): number {
const { tileSpeed, tileYTravel } = controller.runtime;
const currentPhase = spec[phase];
const fromFrame = toAnimationFrame(currentPhase.from, tileYTravel);
const toFrame = toAnimationFrame(currentPhase.to, tileYTravel);
const duration = Math.max(140, Math.round(currentPhase.durationMs * tileSpeed));
const delayStep = Math.max(0, Math.round(currentPhase.staggerMs * tileSpeed));
const ranks = getStaggerRanks(units.length, spec.staggerMode ?? "normal");
units.forEach((unit, index) => {
const fromK = materializeTileFrame(
fromFrame,
unit,
index,
units.length,
spec.target ?? "per-character",
);
const toK = materializeTileFrame(
toFrame,
unit,
index,
units.length,
spec.target ?? "per-character",
);
registerAnimation(
controller,
unit.animate([fromK, toK], {
delay: ranks[index] * delayStep,
duration,
easing: currentPhase.easing,
fill: "forwards",
}),
);
});
return duration + Math.max(0, units.length - 1) * delayStep;
}
function createLoop(
stage: HTMLElement,
runtime: typeof DEFAULT_RUNTIME,
titleClassName?: string,
): LoopController {
return {
animations: new Set(),
cancelled: false,
stage,
timers: new Set(),
pendingResolvers: new Set(),
runtime,
titleClassName,
};
}
function cleanupLoop(c: LoopController) {
c.cancelled = true;
c.timers.forEach((t) => {
window.clearTimeout(t);
});
c.timers.clear();
c.animations.forEach((a) => {
a.cancel();
});
c.animations.clear();
// Resolve any in-flight sleep() promises so awaiting loop functions can
// observe the cancellation flag and unwind, releasing closures + DOM refs.
c.pendingResolvers.forEach((resolve) => {
resolve();
});
c.pendingResolvers.clear();
clearStage(c.stage);
}
function registerAnimation(c: LoopController, a: Animation): Animation {
c.animations.add(a);
void a.finished.finally(() => c.animations.delete(a));
return a;
}
function schedule(c: LoopController, cb: () => void, delay: number) {
if (c.cancelled) return;
const t = window.setTimeout(() => {
c.timers.delete(t);
if (!c.cancelled) cb();
}, delay);
c.timers.add(t);
}
function sleep(c: LoopController, delay: number): Promise<void> {
if (c.cancelled || delay <= 0) return Promise.resolve();
return new Promise((resolve) => {
const wrapped = () => {
c.pendingResolvers.delete(wrapped);
resolve();
};
c.pendingResolvers.add(wrapped);
schedule(c, wrapped, delay);
});
}
function waitForAnimations(animations: Animation[]) {
return Promise.all(animations.map((a) => a.finished.catch(() => undefined)));
}
function clearStage(stage: HTMLElement) {
while (stage.firstChild) stage.removeChild(stage.firstChild);
}
function mix(a: number, b: number, t: number): number {
return a + (b - a) * t;
}
function setKineticPose(el: HTMLElement, frame: KineticStageFrame) {
el.style.filter = frame.filter;
el.style.opacity = `${frame.opacity}`;
el.style.transform = frame.transform;
}
function buildKineticFrame(
x: number,
y: number,
scale: number,
blur: number,
opacity: number,
): KineticStageFrame {
return {
filter: `blur(${blur}px)`,
opacity,
transform: `translate(-50%, -50%) translate3d(${x}px, ${y}px, 0) scale(${scale})`,
};
}
function titleFrame(values: TextAnimationFrameSpec | undefined, yTravel: number): Keyframe {
const f = values ?? {};
return {
filter: `blur(${f.blurPx ?? 0}px)`,
opacity: f.opacity ?? 1,
transform: `translate3d(${f.xPx ?? 0}px, ${(f.yPx ?? 0) * yTravel}px, 0) scale(${f.scale ?? 1})`,
};
}
async function runGenericLoop(c: LoopController, spec: TextAnimationSpec, samples: string[]) {
const { stage, runtime } = c;
const target = spec.target ?? "per-character";
const microDelay = spec.swap?.microDelayMs ?? 0;
// For crossfade swaps the new sample's enter starts `overlapMs` before the
// old sample's exit completes; the two titles share the stage's "title"
// grid area during that window. Other modes wait for exit + microDelay
// before the swap.
const overlap = spec.swap?.mode === "crossfade" ? (spec.swap?.overlapMs ?? 0) : 0;
let currentIndex = 0;
let currentTitle: HTMLElement | null = null;
let currentUnits: HTMLSpanElement[] = [];
const enterSample = (text: string): number => {
const { title, units } = makeTitle(stage.ownerDocument, text, target, c.titleClassName);
applyPhaseStart(units, "enter", spec, stage, runtime.tileYTravel);
clearStage(stage);
stage.appendChild(title);
currentTitle = title;
currentUnits = units;
return animatePhase(c, units, "enter", spec);
};
const firstEnter = enterSample(samples[currentIndex]);
await sleep(c, firstEnter + runtime.tileHoldMs);
while (!c.cancelled) {
const oldTitle = currentTitle;
const exitTotal = currentUnits.length ? animatePhase(c, currentUnits, "exit", spec) : 0;
if (overlap > 0 && oldTitle) {
// Crossfade: start the new enter while the old exit is still finishing.
await sleep(c, Math.max(0, exitTotal - overlap));
if (c.cancelled) break;
currentIndex = (currentIndex + 1) % samples.length;
const next = makeTitle(stage.ownerDocument, samples[currentIndex], target, c.titleClassName);
applyPhaseStart(next.units, "enter", spec, stage, runtime.tileYTravel);
// Mount alongside the still-exiting old title; both share grid-area "title".
stage.appendChild(next.title);
const nextEnter = animatePhase(c, next.units, "enter", spec);
// Drop the old title once its exit finishes (which is `overlap` ms from now).
schedule(c, () => oldTitle.remove(), overlap);
currentTitle = next.title;
currentUnits = next.units;
await sleep(c, nextEnter + runtime.tileHoldMs);
} else {
// Non-overlapping: wait for exit + microDelay, swap, gap, then enter.
await sleep(c, exitTotal + microDelay);
if (c.cancelled) break;
currentIndex = (currentIndex + 1) % samples.length;
const next = makeTitle(stage.ownerDocument, samples[currentIndex], target, c.titleClassName);
applyPhaseStart(next.units, "enter", spec, stage, runtime.tileYTravel);
clearStage(stage);
stage.appendChild(next.title);
currentTitle = next.title;
currentUnits = next.units;
await sleep(c, runtime.tileGapMs);
if (c.cancelled) break;
const nextEnter = animatePhase(c, next.units, "enter", spec);
await sleep(c, nextEnter + runtime.tileHoldMs);
}
}
}
async function runSharedSlideOpacityLoop(
c: LoopController,
spec: TextAnimationSpec,
samples: string[],
) {
const { stage, runtime } = c;
const enter = spec.enter;
const exit = spec.exit;
const build = spec.build ?? {};
const titleDuration = Math.max(180, Math.round((enter.durationMs || 460) * runtime.tileSpeed));
const wordOpacityDuration = Math.max(
90,
Math.round((build.wordOpacityDurationMs ?? 170) * runtime.tileSpeed),
);
const wordStaggerMs = Math.max(0, Math.round((enter.staggerMs || 72) * runtime.tileSpeed));
const exitDuration = Math.max(140, Math.round((exit.durationMs || 300) * runtime.tileSpeed));
const holdMs = Math.max(380, runtime.tileHoldMs);
const gapMs = Math.max(180, runtime.tileGapMs);
const wordOpacityFrom = build.wordOpacityFrom ?? 0;
const wordOpacityTo = build.wordOpacityTo ?? 1;
let currentIndex = 0;
const enterPhrase = async (text: string): Promise<HTMLHeadingElement> => {
const { title, units } = makeTitle(
stage.ownerDocument,
text,
spec.target ?? "per-word",
c.titleClassName,
);
const fromFrame = titleFrame(enter.from, runtime.tileYTravel);
const toFrame = titleFrame(enter.to, runtime.tileYTravel);
Object.assign(title.style, fromFrame);
title.style.willChange = "transform, opacity, filter";
units.forEach((u) => {
u.style.opacity = `${wordOpacityFrom}`;
u.style.willChange = "opacity";
});
clearStage(stage);
stage.appendChild(title);
const animations = [
registerAnimation(
c,
title.animate([fromFrame, toFrame], {
duration: titleDuration,
easing: enter.easing,
fill: "forwards",
}),
),
...units.map((u, i) =>
registerAnimation(
c,
u.animate([{ opacity: wordOpacityFrom }, { opacity: wordOpacityTo }], {
delay: i * wordStaggerMs,
duration: wordOpacityDuration,
easing: enter.easing,
fill: "forwards",
}),
),
),
];
await waitForAnimations(animations);
Object.assign(title.style, toFrame);
units.forEach((u) => {
u.style.opacity = `${wordOpacityTo}`;
});
return title;
};
const exitPhrase = async (title: HTMLHeadingElement | null) => {
if (!title || c.cancelled) return;
const fromFrame = titleFrame(exit.from, runtime.tileYTravel);
const toFrame = titleFrame(exit.to, runtime.tileYTravel);
Object.assign(title.style, fromFrame);
await waitForAnimations([
registerAnimation(
c,
title.animate([fromFrame, toFrame], {
duration: exitDuration,
easing: exit.easing,
fill: "forwards",
}),
),
]);
clearStage(stage);
};
while (!c.cancelled) {
const title = await enterPhrase(samples[currentIndex]);
await sleep(c, holdMs);
if (c.cancelled) break;
await exitPhrase(title);
await sleep(c, gapMs);
currentIndex = (currentIndex + 1) % samples.length;
}
}
async function runKineticCenterBuildLoop(
c: LoopController,
spec: TextAnimationSpec,
phrases: string[][],
) {
const { stage, runtime } = c;
const build = spec.build ?? {};
const line = stage.ownerDocument.createElement("div");
const firstWordDuration = Math.max(
180,
Math.round((build.firstWordDurationMs ?? 360) * runtime.tileSpeed),
);
const pushDuration = Math.max(180, Math.round((build.pushDurationMs ?? 480) * runtime.tileSpeed));
const exitDuration = Math.max(140, Math.round((build.exitDurationMs ?? 260) * runtime.tileSpeed));
const holdMs = Math.max(380, Math.round((build.holdMs ?? 980) * runtime.tileSpeed));
const betweenPhrasesMs = Math.max(
120,
Math.round((build.betweenPhrasesMs ?? 220) * runtime.tileSpeed),
);
const entryOffsetPx = build.entryOffsetPx ?? 96;
const wordGapPx = build.wordGapPx ?? 16;
const firstWordLiftPx = build.firstWordYPx ?? 6;
const entryScale = build.entryScale ?? 0.992;
const entryBlurPx = build.entryBlurPx ?? 3.5;
const reflowBlurPx = build.reflowBlurPx ?? 0.8;
const exitLiftPx = build.exitYPx ?? -6;
const exitBlurPx = build.exitBlurPx ?? 2.5;
const easing = build.easing ?? "cubic-bezier(0.2, 0.8, 0.2, 1)";
const exitEasing = build.exitEasing ?? "cubic-bezier(0.4, 0, 0.2, 1)";
let phraseIndex = 0;
let words: HTMLSpanElement[] = [];
let positions: number[] = [];
clearStage(stage);
line.className = "text-animation-kinetic-line";
stage.appendChild(line);
const computePositions = (widths: number[]) => {
const total = widths.reduce((s, w) => s + w, 0) + wordGapPx * Math.max(0, widths.length - 1);
let cursor = -total / 2;
return widths.map((w) => {
const pos = cursor + w / 2;
cursor += w + wordGapPx;
return pos;
});
};
const buildPhrase = async (phraseWords: string[]) => {
line.innerHTML = "";
words = [];
positions = [];
for (const [index, text] of phraseWords.entries()) {
if (c.cancelled) return;
const word = stage.ownerDocument.createElement("span");
word.className = "text-animation-kinetic-word";
word.textContent = text;
line.appendChild(word);
const widths = Array.from(line.children, (n) => (n as HTMLElement).offsetWidth);
const nextPositions = computePositions(widths);
const animations: Animation[] = [];
if (index === 0) {
const start = buildKineticFrame(0, firstWordLiftPx, entryScale, entryBlurPx, 0);
setKineticPose(word, start);
animations.push(
registerAnimation(
c,
word.animate(
[
start,
{
...buildKineticFrame(0, firstWordLiftPx * 0.35, 0.998, entryBlurPx * 0.45, 0.78),
offset: 0.58,
},
buildKineticFrame(0, 0, 1, 0, 1),
],
{ duration: firstWordDuration, easing, fill: "forwards" },
),
),
);
} else {
words.forEach((currentWord, i) => {
const cX = positions[i];
const nX = nextPositions[i];
animations.push(
registerAnimation(
c,
currentWord.animate(
[
buildKineticFrame(cX, 0, 1, 0, 1),
{
...buildKineticFrame(mix(cX, nX, 0.58), 0, 1, reflowBlurPx, 1),
offset: 0.52,
},
buildKineticFrame(nX, 0, 1, 0, 1),
],
{ duration: pushDuration, easing, fill: "forwards" },
),
),
);
});
const targetX = nextPositions[index];
const startX = targetX + entryOffsetPx;
setKineticPose(word, buildKineticFrame(startX, 0, entryScale, entryBlurPx, 0));
animations.push(
registerAnimation(
c,
word.animate(
[
buildKineticFrame(startX, 0, entryScale, entryBlurPx, 0),
{
...buildKineticFrame(
mix(startX, targetX, 0.72),
0,
0.998,
entryBlurPx * 0.38,
0.84,
),
offset: 0.6,
},
buildKineticFrame(targetX, 0, 1, 0, 1),
],
{ duration: pushDuration, easing, fill: "forwards" },
),
),
);
}
await waitForAnimations(animations);
nextPositions.forEach((position, i) => {
const current = i === words.length ? word : words[i];
setKineticPose(current, buildKineticFrame(position, 0, 1, 0, 1));
});
if (!words.includes(word)) words.push(word);
positions = nextPositions;
}
};
const exitPhrase = async () => {
if (!words.length || c.cancelled) return;
const animations = words.map((word, i) => {
const p = positions[i];
return registerAnimation(
c,
word.animate(
[
buildKineticFrame(p, 0, 1, 0, 1),
{
...buildKineticFrame(p, exitLiftPx * 0.45, 1, exitBlurPx * 0.55, 0.62),
offset: 0.52,
},
buildKineticFrame(p, exitLiftPx, 1, exitBlurPx, 0),
],
{ duration: exitDuration, easing: exitEasing, fill: "forwards" },
),
);
});
await waitForAnimations(animations);
line.innerHTML = "";
words = [];
positions = [];
};
while (!c.cancelled) {
await buildPhrase(phrases[phraseIndex] ?? phrases[0]);
await sleep(c, holdMs);
if (c.cancelled) break;
await exitPhrase();
await sleep(c, betweenPhrasesMs);
phraseIndex = (phraseIndex + 1) % phrases.length;
}
}
async function runKineticTopBuildLoop(
c: LoopController,
spec: TextAnimationSpec,
phrases: string[][],
) {
const { stage, runtime } = c;
const build = spec.build ?? {};
const line = stage.ownerDocument.createElement("div");
const firstWordDuration = Math.max(
180,
Math.round((build.firstWordDurationMs ?? 360) * runtime.tileSpeed),
);
const pushDuration = Math.max(180, Math.round((build.pushDurationMs ?? 500) * runtime.tileSpeed));
const exitDuration = Math.max(140, Math.round((build.exitDurationMs ?? 320) * runtime.tileSpeed));
const holdMs = Math.max(380, Math.round((build.holdMs ?? 1100) * runtime.tileSpeed));
const betweenPhrasesMs = Math.max(
120,
Math.round((build.betweenPhrasesMs ?? 220) * runtime.tileSpeed),
);
const entryOffsetYPx = build.entryOffsetYPx ?? -28;
const lineGapPx = build.lineGapPx ?? build.wordGapPx ?? 12;
const firstWordLiftPx = build.firstWordYPx ?? -14;
const entryScale = build.entryScale ?? 0.992;
const entryBlurPx = build.entryBlurPx ?? 2.4;
const reflowBlurPx = build.reflowBlurPx ?? 0.7;
const exitLiftPx = build.exitYPx ?? 10;
const exitBlurPx = build.exitBlurPx ?? 1.2;
const easing = build.easing ?? "cubic-bezier(0.2, 0.8, 0.2, 1)";
const exitEasing = build.exitEasing ?? "cubic-bezier(0.4, 0, 0.2, 1)";
let phraseIndex = 0;
let words: HTMLSpanElement[] = [];
let positions: number[] = [];
clearStage(stage);
line.className = "text-animation-kinetic-stack";
stage.appendChild(line);
const computePositions = (heights: number[]) => {
const total = heights.reduce((s, h) => s + h, 0) + lineGapPx * Math.max(0, heights.length - 1);
let cursor = -total / 2;
return heights.map((h) => {
const pos = cursor + h / 2;
cursor += h + lineGapPx;
return pos;
});
};
const buildPhrase = async (phraseWords: string[]) => {
line.innerHTML = "";
words = [];
positions = [];
for (const [index, text] of phraseWords.entries()) {
if (c.cancelled) return;
const word = stage.ownerDocument.createElement("span");
word.className = "text-animation-kinetic-word";
word.textContent = text;
line.appendChild(word);
const heights = Array.from(line.children, (n) => (n as HTMLElement).offsetHeight);
const nextPositions = computePositions(heights);
const animations: Animation[] = [];
if (index === 0) {
const start = buildKineticFrame(0, firstWordLiftPx, entryScale, entryBlurPx, 0);
setKineticPose(word, start);
animations.push(
registerAnimation(
c,
word.animate(
[
start,
{
...buildKineticFrame(0, firstWordLiftPx * 0.35, 0.998, entryBlurPx * 0.45, 0.78),
offset: 0.58,
},
buildKineticFrame(0, 0, 1, 0, 1),
],
{ duration: firstWordDuration, easing, fill: "forwards" },
),
),
);
} else {
words.forEach((currentWord, i) => {
const cY = positions[i];
const nY = nextPositions[i];
animations.push(
registerAnimation(
c,
currentWord.animate(
[
buildKineticFrame(0, cY, 1, 0, 1),
{
...buildKineticFrame(0, mix(cY, nY, 0.58), 1, reflowBlurPx, 1),
offset: 0.52,
},
buildKineticFrame(0, nY, 1, 0, 1),
],
{ duration: pushDuration, easing, fill: "forwards" },
),
),
);
});
const targetY = nextPositions[index];
setKineticPose(
word,
buildKineticFrame(0, targetY + entryOffsetYPx, entryScale, entryBlurPx, 0),
);
animations.push(
registerAnimation(
c,
word.animate(
[
buildKineticFrame(0, targetY + entryOffsetYPx, entryScale, entryBlurPx, 0),
{
...buildKineticFrame(
0,
mix(targetY + entryOffsetYPx, targetY, 0.72),
0.998,
entryBlurPx * 0.38,
0.84,
),
offset: 0.6,
},
buildKineticFrame(0, targetY, 1, 0, 1),
],
{ duration: pushDuration, easing, fill: "forwards" },
),
),
);
}
await waitForAnimations(animations);
nextPositions.forEach((position, i) => {
const current = i === words.length ? word : words[i];
setKineticPose(current, buildKineticFrame(0, position, 1, 0, 1));
});
if (!words.includes(word)) words.push(word);
positions = nextPositions;
}
};
const exitPhrase = async () => {
if (!words.length || c.cancelled) return;
const animations = words.map((word, i) => {
const p = positions[i];
return registerAnimation(
c,
word.animate(
[
buildKineticFrame(0, p, 1, 0, 1),
{
...buildKineticFrame(0, p + exitLiftPx * 0.45, 1, exitBlurPx * 0.55, 0.62),
offset: 0.52,
},
buildKineticFrame(0, p + exitLiftPx, 1, exitBlurPx, 0),
],
{ duration: exitDuration, easing: exitEasing, fill: "forwards" },
),
);
});
await waitForAnimations(animations);
line.innerHTML = "";
words = [];
positions = [];
};
while (!c.cancelled) {
await buildPhrase(phrases[phraseIndex] ?? phrases[0]);
await sleep(c, holdMs);
if (c.cancelled) break;
await exitPhrase();
await sleep(c, betweenPhrasesMs);
phraseIndex = (phraseIndex + 1) % phrases.length;
}
}
export default function TextAnimator({
spec,
samples,
phrases,
className,
stageClassName,
titleClassName,
speed,
holdMs,
gapMs,
yTravel,
}: TextAnimatorProps) {
const stageRef = useRef<HTMLDivElement | null>(null);
const [failed, setFailed] = useState(false);
// Track samples/phrases by their *content* rather than array reference so
// a parent that hands us a fresh-but-identical array on every render
// doesn't tear down and restart the animation. / are sentinels
// unlikely to appear in user-supplied copy.
const samplesKey = useMemo(() => samples?.join("") ?? "", [samples]);
const phrasesKey = useMemo(() => phrases?.map((p) => p.join("")).join("") ?? "", [phrases]);
const contentKey = `${samplesKey}|${phrasesKey}`;
const prevContentKeyRef = useRef(contentKey);
if (contentKey !== prevContentKeyRef.current) {
prevContentKeyRef.current = contentKey;
if (failed) {
setFailed(false);
}
}
// Refs let the effect read the latest samples/phrases without listing them
// as deps (we drive re-runs via the content keys above).
const samplesRef = useRef(samples);
const phrasesRef = useRef(phrases);
samplesRef.current = samples;
phrasesRef.current = phrases;
const effectiveSamples = samples?.length ? samples : ["Animation"];
// biome-ignore lint/correctness/useExhaustiveDependencies: samplesKey/phrasesKey track content; samples/phrases are read live from refs.
useEffect(() => {
const stage = stageRef.current;
if (!stage) return;
if (spec.id) stage.dataset.animationId = spec.id;
const runtime = {
tileSpeed: speed ?? DEFAULT_RUNTIME.tileSpeed,
tileHoldMs: holdMs ?? DEFAULT_RUNTIME.tileHoldMs,
tileGapMs: gapMs ?? DEFAULT_RUNTIME.tileGapMs,
tileYTravel: yTravel ?? DEFAULT_RUNTIME.tileYTravel,
};
const controller = createLoop(stage, runtime, titleClassName);
const renderer = spec.customRenderer;
const liveSamples = samplesRef.current;
const livePhrases = phrasesRef.current;
const effectiveSamples = liveSamples?.length ? liveSamples : ["Animation"];
const effectivePhrases = livePhrases?.length ? livePhrases : [["Build", "the", "line"]];
const launch = () => {
let loop: Promise<void>;
if (renderer === "kinetic-center-build") {
loop = runKineticCenterBuildLoop(controller, spec, effectivePhrases);
} else if (renderer === "kinetic-top-build") {
loop = runKineticTopBuildLoop(controller, spec, effectivePhrases);
} else if (renderer === "shared-slide-opacity-stage") {
loop = runSharedSlideOpacityLoop(controller, spec, effectiveSamples);
} else {
loop = runGenericLoop(controller, spec, effectiveSamples);
}
void loop.catch((error) => {
if (!controller.cancelled) {
console.error(`Failed to run text animation "${spec.id ?? "unknown"}"`, error);
setFailed(true);
cleanupLoop(controller);
}
});
};
schedule(controller, launch, Math.random() * 400);
return () => {
cleanupLoop(controller);
};
}, [spec, samplesKey, phrasesKey, speed, holdMs, gapMs, yTravel, titleClassName]);
const demoMode = className != null && String(className).includes(TEXT_ANIMATOR_DEMO_CLASS);
return (
<div
data-text-animator-demo={demoMode ? "" : undefined}
className={cn("relative flex w-full items-center justify-center overflow-hidden", className)}
>
<div ref={stageRef} className={cn("text-animation-stage absolute inset-0", stageClassName)}>
{failed && effectiveSamples[0] ? (
<h3 className={cn("text-animation-title text-animation-fallback", titleClassName)}>
{effectiveSamples[0]}
</h3>
) : null}
</div>
</div>
);
}
// ── lib/utils.ts (https://github.com/codse/animata/blob/25c27e5a874c60a56dcc1609df3b2c4f5f8456f8/lib/utils.ts)
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function absoluteUrl(path: string) {
return `${process.env.NEXT_PUBLIC_APP_URL}${path}`;
}
// Linear interpolation
export function lerp(a: number, b: number, n: number) {
return (1 - n) * a + n * b;
}
// Get distance between two points
export function getDistance(x1: number, y1: number, x2: number, y2: number) {
return Math.hypot(x2 - x1, y2 - y1);
}Điều khiển · HTML · CSS · JS
Sửa mã và tinh chỉnh bằng các nút điều khiển. Bản xem trước cập nhật khi bạn gõ.

Thành phần này chạy từ bản đóng gói nên mã script chỉ xem được ở đây. Hãy sửa HTML và CSS; mã nguồn đầy đủ nằm trong thẻ Mã.
Sửa trực tiếp mọi thành phần, tinh chỉnh bằng nút điều khiển, tải mã nguồn đầy đủ và sao chép prompt nâng cao.
$49 một lầnGiá tạm thời
Chế độ thử: không thu tiền thật.
Miễn phí: xem trước, nút sao chép và ghi chú bài học.
Mỗi từ phát triển từ 70% đến kích thước đầy đủ với một khoảng cách 95ms và một khoảng vượt quá nhỏ, do đó dòng tiếp đất có độ nảy thân thiện.
Tiêu đề thân thiện, các bước giới thiệu và dòng giới thiệu sản phẩm vui nhộn.
Điều chỉnh tỷ lệ from 0,7, độ vọt lố cubic-bezier(0.34,1.56,0.64,1), staggerMs, cộng với speed và holdMs.
Thêm component "Thang đo mùa xuân trong văn bản" từ Animata (github.com/codse/animata) (MIT) vào ứng dụng React + Tailwind CSS của tôi. Tệp nguồn: https://github.com/codse/animata/blob/25c27e5a874c60a56dcc1609df3b2c4f5f8456f8/animata/text/spring-scale-in.tsx. Mỗi từ phát triển từ 70% đến kích thước đầy đủ với một khoảng cách 95ms và một khoảng vượt quá nhỏ, do đó dòng tiếp đất có độ nảy thân thiện. Dùng cho: Tiêu đề thân thiện, các bước giới thiệu và dòng giới thiệu sản phẩm vui nhộn. Các thiết lập cần chỉnh: Điều chỉnh tỷ lệ from 0,7, độ vọt lố cubic-bezier(0.34,1.56,0.64,1), staggerMs, cộng với speed và holdMs. Hỗ trợ giao diện sáng và tối, tôn trọng prefers-reduced-motion. Giữ thông báo giấy phép MIT.
Prompt dài hơn, có các bước tinh chỉnh, trợ năng và tích hợp.