{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "motion-scroll-velocity",
  "title": "Scroll velocity",
  "description": "Stacked rows of text or pictures that loop sideways, speed up with the scroll, turn around when it scrolls up and lean into their speed.",
  "dependencies": [
    "motion"
  ],
  "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/scroll-velocity.tsx",
      "content": "'use client';\nimport { cn } from '@/lib/utils';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  motion,\n  useAnimationFrame,\n  useInView,\n  useMotionValue,\n  useScroll,\n  useSpring,\n  useTransform,\n  useVelocity,\n  wrap,\n  type MotionValue,\n} from 'motion/react';\nimport {\n  createContext,\n  useContext,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ReactNode,\n  type RefObject,\n} from 'react';\n\nexport type ScrollVelocityDirection = 'left' | 'right';\n\ntype DirectionSign = 1 | -1;\n\ntype ScrollVelocityContextValue = {\n  boost: MotionValue<number>;\n  isRunning: boolean;\n  reverseOnScrollUp: boolean;\n  lean: boolean;\n};\n\nconst VELOCITY_SPRING = { damping: 50, stiffness: 400 };\n\n/** At 1000px of scroll per second, the rows run this many times faster than at rest. */\nconst BOOST_PER_1000_PX = 4;\n\nconst LEAN_PER_BOOST = 2;\n\nconst MAX_LEAN = 6;\n\n/** A long first frame (a tab coming back) would throw the rows forward, so a frame never counts for more than this. */\nconst MAX_FRAME_SECONDS = 0.1;\n\nconst MAX_COPIES = 24;\n\n/** The copy that screen readers and keyboards reach; the others are visual repeats. */\nconst READABLE_COPY = 1;\n\nconst ScrollVelocityContext = createContext<ScrollVelocityContextValue | null>(\n  null\n);\n\nfunction useScrollVelocityContext() {\n  const context = useContext(ScrollVelocityContext);\n  if (!context) {\n    throw new Error('ScrollVelocityRow must be used inside ScrollVelocity');\n  }\n  return context;\n}\n\nfunction signOf(direction: ScrollVelocityDirection): DirectionSign {\n  if (direction === 'right') {\n    return 1;\n  }\n  return -1;\n}\n\nfunction oppositeOf(sign: DirectionSign): DirectionSign {\n  if (sign === 1) {\n    return -1;\n  }\n  return 1;\n}\n\nfunction signForBoost(\n  boost: number,\n  baseSign: DirectionSign,\n  current: DirectionSign\n) {\n  if (boost < 0) {\n    return oppositeOf(baseSign);\n  }\n  if (boost > 0) {\n    return baseSign;\n  }\n  return current;\n}\n\n/** Enough copies to cover the row twice over the width of one copy, so neither edge ever shows a gap. */\nfunction copyCountOf(rowWidth: number, copyWidth: number) {\n  if (copyWidth <= 0) {\n    return 3;\n  }\n  const covering = rowWidth / copyWidth;\n  const rounded = Math.ceil(covering);\n  const withSpares = rounded + 2;\n  return Math.min(withSpares, MAX_COPIES);\n}\n\nfunction leanOf(boost: number, sign: DirectionSign) {\n  const size = Math.abs(boost);\n  const raw = size * LEAN_PER_BOOST;\n  const clamped = Math.min(raw, MAX_LEAN);\n  const against = -sign;\n  return clamped * against;\n}\n\n/** The track starts one copy to the left, so the readable copy sits at the left edge at rest. */\nfunction trackTransformOf(offset: number, copyWidth: number, lean: number) {\n  const shifted = offset - copyWidth;\n  return `translateX(${shifted}px) skewX(${lean}deg)`;\n}\n\nfunction isRepeatedCopy(index: number) {\n  return index !== READABLE_COPY;\n}\n\nfunction hiddenFromReadersOf(isRepeated: boolean) {\n  if (isRepeated) {\n    return true;\n  }\n  return undefined;\n}\n\nfunction copyRefOf(index: number, copyRef: RefObject<HTMLDivElement | null>) {\n  if (index === READABLE_COPY) {\n    return copyRef;\n  }\n  return undefined;\n}\n\nfunction frameSecondsOf(delta: number) {\n  const seconds = delta / 1000;\n  return Math.min(seconds, MAX_FRAME_SECONDS);\n}\n\nexport type ScrollVelocityProps = {\n  children: ReactNode;\n  containerRef?: RefObject<HTMLElement | null>;\n  reverseOnScrollUp?: boolean;\n  lean?: boolean;\n  fade?: boolean;\n  className?: string;\n};\n\nexport function ScrollVelocity({\n  children,\n  containerRef,\n  reverseOnScrollUp = true,\n  lean = true,\n  fade = true,\n  className,\n}: ScrollVelocityProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const isInView = useInView(rootRef);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const { scrollY } = useScroll({ container: containerRef });\n  const scrollVelocity = useVelocity(scrollY);\n  const smoothVelocity = useSpring(scrollVelocity, VELOCITY_SPRING);\n  const boost = useTransform(\n    smoothVelocity,\n    [0, 1000],\n    [0, BOOST_PER_1000_PX],\n    { clamp: false }\n  );\n  const isRunning = isInView && !shouldReduceMotion;\n  const value = useMemo(\n    () => ({ boost, isRunning, reverseOnScrollUp, lean }),\n    [boost, isRunning, reverseOnScrollUp, lean]\n  );\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\n        'flex flex-col overflow-hidden',\n        fade && 'mask-x-from-85%',\n        className\n      )}\n    >\n      <ScrollVelocityContext.Provider value={value}>\n        {children}\n      </ScrollVelocityContext.Provider>\n    </div>\n  );\n}\n\ntype RowDriverProps = {\n  offset: MotionValue<number>;\n  copyWidth: MotionValue<number>;\n  tilt: MotionValue<number>;\n  boost: MotionValue<number>;\n  speed: number;\n  baseSign: DirectionSign;\n  signRef: RefObject<DirectionSign>;\n  reverseOnScrollUp: boolean;\n  lean: boolean;\n};\n\n/**\n * The frame loop of the animation library runs for as long as one `useAnimationFrame` is mounted,\n * even when its callback does nothing, and each of those frames costs the whole page. So the loop\n * lives in this leaf, which is mounted only while the row runs.\n */\nfunction RowDriver({\n  offset,\n  copyWidth,\n  tilt,\n  boost,\n  speed,\n  baseSign,\n  signRef,\n  reverseOnScrollUp,\n  lean,\n}: RowDriverProps) {\n  useAnimationFrame((_, delta) => {\n    const currentBoost = boost.get();\n    if (reverseOnScrollUp) {\n      signRef.current = signForBoost(currentBoost, baseSign, signRef.current);\n    }\n    if (!reverseOnScrollUp) {\n      signRef.current = baseSign;\n    }\n    const seconds = frameSecondsOf(delta);\n    const boostSize = Math.abs(currentBoost);\n    const multiplier = 1 + boostSize;\n    const distanceAtRest = speed * seconds;\n    const distance = distanceAtRest * multiplier;\n    const step = signRef.current * distance;\n    const width = copyWidth.get();\n    if (width <= 0) {\n      return;\n    }\n    const currentOffset = offset.get();\n    const travelled = currentOffset + step;\n    const wrapped = wrap(-width, 0, travelled);\n    offset.set(wrapped);\n    if (lean) {\n      const nextTilt = leanOf(currentBoost, signRef.current);\n      tilt.set(nextTilt);\n    }\n  });\n\n  return null;\n}\n\nexport type ScrollVelocityRowProps = {\n  children: ReactNode;\n  speed?: number;\n  direction?: ScrollVelocityDirection;\n  gap?: number;\n  className?: string;\n};\n\nexport function ScrollVelocityRow({\n  children,\n  speed = 40,\n  direction = 'left',\n  gap = 32,\n  className,\n}: ScrollVelocityRowProps) {\n  const { boost, isRunning, reverseOnScrollUp, lean } =\n    useScrollVelocityContext();\n  const rowRef = useRef<HTMLDivElement>(null);\n  const copyRef = useRef<HTMLDivElement>(null);\n  const [copyCount, setCopyCount] = useState(3);\n  const baseSign = signOf(direction);\n  const signRef = useRef<DirectionSign>(baseSign);\n  const offset = useMotionValue(0);\n  const copyWidth = useMotionValue(0);\n  const tilt = useMotionValue(0);\n  const transform = useTransform<number, string>(\n    [offset, copyWidth, tilt],\n    ([latestOffset, latestCopyWidth, latestTilt]) =>\n      trackTransformOf(latestOffset, latestCopyWidth, latestTilt)\n  );\n  const copies = Array.from({ length: copyCount }, (_, index) => index);\n\n  useEffect(() => {\n    const row = rowRef.current;\n    const copy = copyRef.current;\n    if (!row) {\n      return;\n    }\n    if (!copy) {\n      return;\n    }\n    const measure = () => {\n      const rowWidth = row.getBoundingClientRect().width;\n      const measuredCopyWidth = copy.getBoundingClientRect().width;\n      const nextCopyCount = copyCountOf(rowWidth, measuredCopyWidth);\n      copyWidth.set(measuredCopyWidth);\n      setCopyCount(nextCopyCount);\n    };\n    const observer = new ResizeObserver(measure);\n    observer.observe(row);\n    observer.observe(copy);\n    return () => observer.disconnect();\n  }, [copyWidth]);\n\n  return (\n    <div ref={rowRef} className={cn('flex overflow-hidden', className)}>\n      {isRunning && (\n        <RowDriver\n          offset={offset}\n          copyWidth={copyWidth}\n          tilt={tilt}\n          boost={boost}\n          speed={speed}\n          baseSign={baseSign}\n          signRef={signRef}\n          reverseOnScrollUp={reverseOnScrollUp}\n          lean={lean}\n        />\n      )}\n      <motion.div\n        className='flex w-max shrink-0 whitespace-nowrap'\n        style={{ transform }}\n      >\n        {copies.map((index) => {\n          const isRepeated = isRepeatedCopy(index);\n\n          return (\n            <div\n              key={index}\n              ref={copyRefOf(index, copyRef)}\n              aria-hidden={hiddenFromReadersOf(isRepeated)}\n              inert={isRepeated}\n              className='flex shrink-0 items-center'\n              style={{ paddingInlineEnd: gap }}\n            >\n              {children}\n            </div>\n          );\n        })}\n      </motion.div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/core/scroll-velocity.tsx"
    }
  ],
  "categories": [
    "motion"
  ],
  "type": "registry:component"
}