Taster

진단부품톤 고르기
부품 갤러리 / Gooey text

Gooey text

Motion effect and particles

Use text motion once and with purpose: words firm up as the reader scrolls, one headline word cycles, a tagline types out. Never a different effect on every heading.

내 사이트에서 가져오기

색을 고르면 아래 부품이 그 색으로 바뀝니다.

실제로 돌아가는 부품입니다. 눌러 보고 입력해 보세요.

내 앱에 넣기

  1. 아직 npm 패키지가 없어서 Taster 리포를 받아 그 안의 명령을 씁니다. 내 앱 폴더가 들어 있는 폴더에서 한 번만 받습니다.

    git clone https://github.com/makim-414/taster.git && npm ci --prefix taster/packages/engine
  2. 내 앱 폴더에서 이 부품을 넣습니다. 부품 파일과 토큰 파일이 src/components/taster 에 들어갑니다.

    node ../taster/packages/engine/cli.mjs add motion/gooey-text --from https://taster-six.vercel.app --dir src/components/taster
  3. 부품은 Tailwind 클래스로 그리고, Taster 프리셋이 그 클래스를 토큰에 연결합니다. Tailwind CSS 를 설치하고, tokens.css 를 앱 루트에서 한 번 불러온 뒤, 앱 루트에 이 설정을 둡니다. 프리셋이 없으면 빌드는 되어도 부품이 스타일 없이 나옵니다.

    // tailwind.config.cjs
    module.exports = {
      presets: [require('./src/components/taster/tailwind-preset.cjs')],
      content: ['./index.html', './src/**/*.{ts,tsx}'],
    };

    Tailwind v3 는 이 파일을 그대로 읽습니다. v4 는 Tailwind 를 불러오는 src/ 의 스타일시트 맨 위에 이 두 줄을 넣습니다.

    @import "tailwindcss";
    @config "../tailwind.config.cjs";

    tokens.css 는 :root 에 --bg, --text, --border, --accent 를 정의합니다. 내 앱의 스타일시트가 같은 이름을 뒤에서 다시 정의하면 그쪽 색이 이깁니다. 새 Vite 앱의 스타터 CSS 처럼 그런 변수가 있으면 지우거나 이름을 바꾸세요.

언제 쓰나요

  • Animated textUse text motion once and with purpose: words firm up as the reader scrolls, one headline word cycles, a tagline types out. Never a different effect on every heading.

대신 없애 주는 AI 티

  • Gradient-filled text (COL-04)
  • The same entrance animation on every block (MOT-01)
  • One italic serif word in the headline (TYP-03)

정보

설치할 패키지
tailwindcss
라이선스
MIT
출처
Gooey Text Morphing by Victor Welander, MIT as listed (no LICENSE file published), https://21st.dev/@victorwelander/components/gooey-text-morphing
코드 보기
import * as React from 'react'
import { cn } from '../blocks/_cn'
import { useReducedMotion } from './_motion'

// Gooey text: cycles through words, melting one into the next with an SVG threshold filter.
// Source: "Gooey Text Morphing" by Victor Welander on 21st.dev
// (https://21st.dev/@victorwelander/components/gooey-text-morphing).
// Changes: each instance gets its own filter id (two on one page no longer share a filter), the size
// comes from className instead of a fixed display size, the box reserves the longest word, text color
// is the --text token, reduced motion shows the first word still, and screen readers get the word list
// once instead of every frame.
// Upstream license: MIT as stated on the 21st.dev listing (no LICENSE file published),
// Copyright (c) Victor Welander. Full text in THIRD_PARTY_NOTICES.md.

export interface GooeyTextProps {
  texts: string[]
  /** Seconds one word takes to melt into the next. */
  morphTime?: number
  /** Seconds a word stays before the next melt. */
  cooldownTime?: number
  /** Wrapper classes. The wrapper takes the size of the longest word, so no height is needed. */
  className?: string
  /** Classes for the two word layers, for example a text size. */
  textClassName?: string
}

export function GooeyText({ texts, morphTime = 1, cooldownTime = 0.25, className, textClassName }: GooeyTextProps) {
  const filterId = `dsg-gooey-${React.useId().replace(/:/g, '')}`
  const reduced = useReducedMotion()
  const a = React.useRef<HTMLSpanElement>(null)
  const b = React.useRef<HTMLSpanElement>(null)

  React.useEffect(() => {
    const t1 = a.current
    const t2 = b.current
    if (!t1 || !t2 || !texts.length) return
    if (reduced) {
      t1.textContent = ''
      t2.textContent = texts[0]
      t1.style.filter = t2.style.filter = ''
      t1.style.opacity = '0%'
      t2.style.opacity = '100%'
      return
    }
    let index = texts.length - 1
    let last = performance.now()
    let morph = 0
    let cooldown = cooldownTime
    let raf = 0

    const setMorph = (fraction: number) => {
      t2.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`
      t2.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`
      const rest = 1 - fraction
      t1.style.filter = `blur(${Math.min(8 / rest - 8, 100)}px)`
      t1.style.opacity = `${Math.pow(rest, 0.4) * 100}%`
    }
    const settle = () => {
      morph = 0
      t2.style.filter = ''
      t2.style.opacity = '100%'
      t1.style.filter = ''
      t1.style.opacity = '0%'
    }
    const frame = (now: number) => {
      raf = requestAnimationFrame(frame)
      const next = cooldown > 0
      const dt = (now - last) / 1000
      last = now
      cooldown -= dt
      if (cooldown <= 0) {
        if (next) {
          index = (index + 1) % texts.length
          t1.textContent = texts[index % texts.length]
          t2.textContent = texts[(index + 1) % texts.length]
        }
        morph -= cooldown
        cooldown = 0
        let fraction = morph / morphTime
        if (fraction > 1) {
          cooldown = cooldownTime
          fraction = 1
        }
        setMorph(fraction)
      } else {
        settle()
      }
    }
    raf = requestAnimationFrame(frame)
    return () => cancelAnimationFrame(raf)
  }, [texts, morphTime, cooldownTime, reduced])

  const layer = cn('absolute inline-block select-none text-center text-text', textClassName)
  const longest = texts.reduce((a, t) => (t.length > a.length ? t : a), '')
  return (
    <div className={cn('relative inline-block', className)} aria-label={texts.join(', ')} role="img">
      {/* Invisible sizer: reserves the width and height of the longest word. */}
      <span aria-hidden className={cn('invisible inline-block select-none', textClassName)}>
        {longest}
      </span>
      <svg className="absolute h-0 w-0" aria-hidden focusable="false">
        <defs>
          <filter id={filterId}>
            <feColorMatrix in="SourceGraphic" type="matrix" values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 255 -140" />
          </filter>
        </defs>
      </svg>
      <div className="absolute inset-0 flex items-center justify-center" style={{ filter: `url(#${filterId})` }} aria-hidden>
        <span ref={a} className={layer} />
        <span ref={b} className={layer}>
          {texts[0]}
        </span>
      </div>
    </div>
  )
}