{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "motion-text-3d-flip",
  "title": "Text 3d flip",
  "description": "Letters that turn over like small blocks, one after another, when the link or button they sit in is hovered or focused.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "components/core/text-3d-flip.tsx",
      "content": "'use client';\nimport { cn } from '@/lib/utils';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  Fragment,\n  useEffect,\n  useRef,\n  useState,\n  type CSSProperties,\n  type ElementType,\n  type RefObject,\n} from 'react';\n\nexport type Text3DFlipDirection = 'up' | 'down' | 'left' | 'right';\n\nexport type Text3DFlipStaggerFrom =\n  'first' | 'last' | 'center' | 'random' | number;\n\ntype Turn = {\n  front: string;\n  back: string;\n  origin: string;\n};\n\ntype Letter = {\n  character: string;\n  index: number;\n};\n\ntype Word = {\n  letters: Letter[];\n};\n\ntype FaceStyles = {\n  front: CSSProperties;\n  back: CSSProperties;\n};\n\ntype Timing = {\n  duration: number;\n  delay: number;\n};\n\n/**\n * Each letter is the front of a small cube: the axis sits half a line (or half a letter) behind\n * the text, so the face that leaves and the face that arrives turn together like one block.\n */\nconst VERTICAL_ORIGIN = '50% 50% -0.5lh';\n\nconst HORIZONTAL_ORIGIN = '50% 50% -0.3em';\n\nconst TURNS: Record<Text3DFlipDirection, Turn> = {\n  up: {\n    front: 'rotateX(90deg)',\n    back: 'rotateX(-90deg)',\n    origin: VERTICAL_ORIGIN,\n  },\n  down: {\n    front: 'rotateX(-90deg)',\n    back: 'rotateX(90deg)',\n    origin: VERTICAL_ORIGIN,\n  },\n  left: {\n    front: 'rotateY(-90deg)',\n    back: 'rotateY(90deg)',\n    origin: HORIZONTAL_ORIGIN,\n  },\n  right: {\n    front: 'rotateY(90deg)',\n    back: 'rotateY(-90deg)',\n    origin: HORIZONTAL_ORIGIN,\n  },\n};\n\nconst RESTING = 'none';\n\nconst EASE_OUT_STRONG = 'cubic-bezier(0.23, 1, 0.32, 1)';\n\nconst RETURN_SPEED = 0.7;\n\nconst RETURN_STAGGER = 0.6;\n\nconst FADE_MS = 150;\n\nconst INTERACTIVE_ANCESTOR = [\n  'a[href]',\n  'button',\n  'summary',\n  'label',\n  '[role=\"button\"]',\n  '[role=\"link\"]',\n  '[role=\"tab\"]',\n  '[role=\"menuitem\"]',\n  '[role=\"option\"]',\n].join(', ');\n\nfunction wordsOf(text: string): Word[] {\n  const words: Word[] = [];\n  let index = 0;\n  for (const part of text.split(' ')) {\n    const letters: Letter[] = [];\n    for (const character of Array.from(part)) {\n      letters.push({ character, index });\n      index += 1;\n    }\n    words.push({ letters });\n  }\n  return words;\n}\n\nfunction letterCountOf(words: readonly Word[]) {\n  let count = 0;\n  for (const word of words) {\n    count += word.letters.length;\n  }\n  return count;\n}\n\n/** A fixed shuffle, so the server and the browser agree on the order. */\nfunction shuffledRankOf(index: number, count: number) {\n  const position = index + 1;\n  const angle = position * 12.9898;\n  const sine = Math.sin(angle);\n  const wave = sine * 43758.5453;\n  const whole = Math.floor(wave);\n  const fraction = wave - whole;\n  const lastIndex = count - 1;\n  const spread = Math.max(lastIndex, 0);\n  return fraction * spread;\n}\n\nfunction rankOf(index: number, count: number, from: Text3DFlipStaggerFrom) {\n  const lastIndex = count - 1;\n  if (typeof from === 'number') {\n    return Math.abs(index - from);\n  }\n  if (from === 'last') {\n    return lastIndex - index;\n  }\n  if (from === 'center') {\n    const middle = lastIndex / 2;\n    return Math.abs(index - middle);\n  }\n  if (from === 'random') {\n    return shuffledRankOf(index, count);\n  }\n  return index;\n}\n\nfunction timingOf(\n  rank: number,\n  isFlipped: boolean,\n  duration: number,\n  stagger: number\n): Timing {\n  if (isFlipped) {\n    const delay = rank * stagger;\n    return { duration, delay };\n  }\n  const returnDuration = duration * RETURN_SPEED;\n  const returnStagger = stagger * RETURN_STAGGER;\n  const returnDelay = rank * returnStagger;\n  return { duration: returnDuration, delay: returnDelay };\n}\n\nfunction millisecondsOf(seconds: number) {\n  const milliseconds = seconds * 1000;\n  return Math.round(milliseconds);\n}\n\nfunction transitionOf(property: string, timing: Timing) {\n  const durationMs = millisecondsOf(timing.duration);\n  const delayMs = millisecondsOf(timing.delay);\n  return `${property} ${durationMs}ms ${EASE_OUT_STRONG} ${delayMs}ms`;\n}\n\nfunction frontTransformOf(turn: Turn, isFlipped: boolean) {\n  if (isFlipped) {\n    return turn.front;\n  }\n  return RESTING;\n}\n\nfunction backTransformOf(turn: Turn, isFlipped: boolean) {\n  if (isFlipped) {\n    return RESTING;\n  }\n  return turn.back;\n}\n\nfunction turningStylesOf(\n  turn: Turn,\n  isFlipped: boolean,\n  timing: Timing\n): FaceStyles {\n  const transition = transitionOf('transform', timing);\n  return {\n    front: {\n      transform: frontTransformOf(turn, isFlipped),\n      transformOrigin: turn.origin,\n      transition,\n    },\n    back: {\n      transform: backTransformOf(turn, isFlipped),\n      transformOrigin: turn.origin,\n      transition,\n    },\n  };\n}\n\nfunction frontOpacityOf(isFlipped: boolean) {\n  if (isFlipped) {\n    return 0;\n  }\n  return 1;\n}\n\nfunction backOpacityOf(isFlipped: boolean) {\n  if (isFlipped) {\n    return 1;\n  }\n  return 0;\n}\n\nfunction fadingStylesOf(isFlipped: boolean): FaceStyles {\n  const transition = `opacity ${FADE_MS}ms ${EASE_OUT_STRONG}`;\n  return {\n    front: { opacity: frontOpacityOf(isFlipped), transition },\n    back: { opacity: backOpacityOf(isFlipped), transition },\n  };\n}\n\nfunction isTouchPointer(event: PointerEvent) {\n  return event.pointerType === 'touch';\n}\n\nfunction isKeyboardFocus(event: FocusEvent) {\n  const target = event.target;\n  if (!(target instanceof Element)) {\n    return false;\n  }\n  return target.matches(':focus-visible');\n}\n\n/**\n * Hover and keyboard focus of the link or button the text sits in. Text outside a link or a\n * button never reacts to the pointer: plain text that moves on hover reads as something to click.\n */\nfunction useAncestorActivity(\n  rootRef: RefObject<HTMLElement | null>,\n  isListening: boolean\n) {\n  const [isHovered, setIsHovered] = useState(false);\n  const [isFocused, setIsFocused] = useState(false);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!isListening) {\n      return;\n    }\n    if (!root) {\n      return;\n    }\n    const trigger = root.closest<HTMLElement>(INTERACTIVE_ANCESTOR);\n    if (!trigger) {\n      return;\n    }\n    const handlePointerEnter = (event: PointerEvent) => {\n      if (isTouchPointer(event)) {\n        return;\n      }\n      setIsHovered(true);\n    };\n    const handlePointerLeave = () => {\n      setIsHovered(false);\n    };\n    const handleFocusIn = (event: FocusEvent) => {\n      const isFromKeyboard = isKeyboardFocus(event);\n      setIsFocused(isFromKeyboard);\n    };\n    const handleFocusOut = () => {\n      setIsFocused(false);\n    };\n    trigger.addEventListener('pointerenter', handlePointerEnter);\n    trigger.addEventListener('pointerleave', handlePointerLeave);\n    trigger.addEventListener('focusin', handleFocusIn);\n    trigger.addEventListener('focusout', handleFocusOut);\n    return () => {\n      trigger.removeEventListener('pointerenter', handlePointerEnter);\n      trigger.removeEventListener('pointerleave', handlePointerLeave);\n      trigger.removeEventListener('focusin', handleFocusIn);\n      trigger.removeEventListener('focusout', handleFocusOut);\n    };\n  }, [rootRef, isListening]);\n\n  return isHovered || isFocused;\n}\n\ntype FlipLetterProps = {\n  character: string;\n  styles: FaceStyles;\n  textClassName?: string;\n  backClassName?: string;\n};\n\nfunction FlipLetter({\n  character,\n  styles,\n  textClassName,\n  backClassName,\n}: FlipLetterProps) {\n  return (\n    <span className='inline-grid [perspective:4em]'>\n      <span\n        className={cn('col-start-1 row-start-1 backface-hidden', textClassName)}\n        style={styles.front}\n      >\n        {character}\n      </span>\n      <span\n        className={cn('col-start-1 row-start-1 backface-hidden', backClassName)}\n        style={styles.back}\n      >\n        {character}\n      </span>\n    </span>\n  );\n}\n\nexport type Text3DFlipProps = {\n  children: string;\n  as?: ElementType;\n  className?: string;\n  textClassName?: string;\n  backClassName?: string;\n  direction?: Text3DFlipDirection;\n  staggerFrom?: Text3DFlipStaggerFrom;\n  stagger?: number;\n  duration?: number;\n  flipped?: boolean;\n};\n\nexport function Text3DFlip({\n  children,\n  as: Component = 'span',\n  className,\n  textClassName,\n  backClassName,\n  direction = 'up',\n  staggerFrom = 'first',\n  stagger = 0.03,\n  duration = 0.5,\n  flipped,\n}: Text3DFlipProps) {\n  const rootRef = useRef<HTMLElement>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const isControlled = flipped !== undefined;\n  const isActive = useAncestorActivity(rootRef, !isControlled);\n  const isFlipped = flipped ?? isActive;\n  const words = wordsOf(children);\n  const count = letterCountOf(words);\n  const turn = TURNS[direction];\n\n  const stylesOf = (letter: Letter) => {\n    if (shouldReduceMotion) {\n      return fadingStylesOf(isFlipped);\n    }\n    const rank = rankOf(letter.index, count, staggerFrom);\n    const timing = timingOf(rank, isFlipped, duration, stagger);\n    return turningStylesOf(turn, isFlipped, timing);\n  };\n\n  return (\n    <Component ref={rootRef} className={className}>\n      <span className='sr-only'>{children}</span>\n      <span aria-hidden='true'>\n        {words.map((word, wordIndex) => (\n          <Fragment key={wordIndex}>\n            {wordIndex > 0 && ' '}\n            <span className='whitespace-nowrap'>\n              {word.letters.map((letter) => (\n                <FlipLetter\n                  key={letter.index}\n                  character={letter.character}\n                  styles={stylesOf(letter)}\n                  textClassName={textClassName}\n                  backClassName={backClassName}\n                />\n              ))}\n            </span>\n          </Fragment>\n        ))}\n      </span>\n    </Component>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/core/text-3d-flip.tsx"
    }
  ],
  "categories": [
    "motion"
  ],
  "type": "registry:component"
}