# Proximity Text
*URL: https://www.grettech.com/components/proximity-text*

A headline whose letters swell, lift and light up as the cursor gets close, like a magnifying wave. Stays real, indexable text.

- Letters react smoothly to cursor distance
- Real text: server-rendered, indexable and read normally by screen readers
- Scale, lift, accent colour and weight change are props
- Off on touch screens and with reduced motion

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/proximity-text
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/proximity-text-demo`

**Dependencies:** npm: clsx, tailwind-merge

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses and the shadcn/ui components it builds on. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install clsx tailwind-merge
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/proximity-text.tsx`
```tsx
"use client"

import { cn } from "@/lib/utils"
import * as React from "react"

export interface ProximityTextProps extends React.HTMLAttributes<HTMLElement> {
  /** The text; letters near the cursor swell */
  children: string
  as?: "h1" | "h2" | "h3" | "p" | "span"
  /** Reach of the effect in px */
  radius?: number
  /** Scale of the letter right under the cursor */
  maxScale?: number
  /** How far the nearest letter lifts, in px */
  lift?: number
  /** Colour letters take on near the cursor */
  accentColor?: string
  /** Font weight away from the cursor */
  weight?: number
  /** Extra weight near the cursor; smooth with a variable font such as Inter */
  weightBoost?: number
}

/**
 * Real text, split into letters that react to cursor distance through one
 * CSS variable each (--p, 0–1). It renders as normal text on the server, so
 * it's indexable and paints immediately.
 */
export const ProximityText = React.forwardRef<HTMLElement, ProximityTextProps>(
  (
    {
      children,
      as: Tag = "h2",
      radius = 140,
      maxScale = 1.45,
      lift = 10,
      accentColor = "#8b5cf6",
      weight = 600,
      weightBoost = 300,
      className,
      style,
      ...props
    },
    forwardedRef
  ) => {
    const ref = React.useRef<HTMLElement>(null)
    React.useImperativeHandle(forwardedRef, () => ref.current!)

    React.useEffect(() => {
      const root = ref.current
      if (!root) return
      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
      // Touch screens have no hover position to follow
      if (!window.matchMedia("(hover: hover)").matches) return

      // Each letter's wrapper never transforms, so its on-screen box is the
      // letter's resting place (scaled containers included)
      const slots = [...root.querySelectorAll<HTMLElement>("[data-letter]")]
      const letters = slots.map((el) => el.firstElementChild as HTMLElement)
      let centres: { x: number; y: number }[] = []
      let stale = true
      const measure = () => {
        centres = slots.map((el) => {
          const r = el.getBoundingClientRect()
          return { x: r.left + r.width / 2, y: r.top + r.height / 2 }
        })
        stale = false
      }
      const markStale = () => (stale = true)
      const resizeObserver = new ResizeObserver(markStale)
      resizeObserver.observe(root)

      let raf = 0
      let pointer: { x: number; y: number } | null = null
      const apply = () => {
        raf = 0
        if (stale) measure()
        letters.forEach((el, i) => {
          let p = 0
          if (pointer) {
            const d = Math.hypot(
              centres[i].x - pointer.x,
              centres[i].y - pointer.y
            )
            p = Math.max(0, 1 - d / radius) ** 2
          }
          el.style.setProperty("--p", p.toFixed(3))
        })
      }
      const onMove = (e: PointerEvent) => {
        pointer = { x: e.clientX, y: e.clientY }
        if (!raf) raf = requestAnimationFrame(apply)
      }
      const onLeave = () => {
        pointer = null
        if (!raf) raf = requestAnimationFrame(apply)
      }

      // Listen on the page so letters react as the cursor approaches
      let listening = false
      const io = new IntersectionObserver(([entry]) => {
        if (entry.isIntersecting && !listening) {
          stale = true
          window.addEventListener("pointermove", onMove, { passive: true })
          window.addEventListener("scroll", markStale, { passive: true })
          document.documentElement.addEventListener("pointerleave", onLeave)
          listening = true
        } else if (!entry.isIntersecting && listening) {
          window.removeEventListener("pointermove", onMove)
          window.removeEventListener("scroll", markStale)
          document.documentElement.removeEventListener("pointerleave", onLeave)
          listening = false
          onLeave()
        }
      })
      io.observe(root)

      return () => {
        cancelAnimationFrame(raf)
        io.disconnect()
        resizeObserver.disconnect()
        window.removeEventListener("pointermove", onMove)
        window.removeEventListener("scroll", markStale)
        document.documentElement.removeEventListener("pointerleave", onLeave)
      }
    }, [children, radius])

    // Words stay unbreakable; letters are the moving parts
    const words = children.split(" ")

    return (
      <Tag
        ref={ref as React.Ref<never>}
        aria-label={children}
        className={cn("cursor-default", className)}
        style={
          {
            "--pt-accent": accentColor,
            "--pt-scale": maxScale - 1,
            "--pt-lift": `${lift}px`,
            "--pt-weight": weightBoost,
            fontWeight: weight,
            ...style,
          } as React.CSSProperties
        }
        {...props}
      >
        {words.map((word, w) => (
          <React.Fragment key={w}>
            <span aria-hidden="true" className="inline-block whitespace-nowrap">
              {[...word].map((char, c) => (
                <span key={c} data-letter="" className="inline-block">
                  <span
                    className="inline-block origin-bottom transition-[transform,color,font-weight] duration-150 ease-out will-change-transform"
                    style={{
                      transform:
                        "translateY(calc(var(--p, 0) * var(--pt-lift) * -1)) scale(calc(1 + var(--p, 0) * var(--pt-scale)))",
                      color:
                        "color-mix(in oklab, var(--pt-accent) calc(var(--p, 0) * 100%), currentColor)",
                      fontWeight: `calc(${weight} + var(--p, 0) * var(--pt-weight))`,
                    }}
                  >
                    {char}
                  </span>
                </span>
              ))}
            </span>
            {w < words.length - 1 && " "}
          </React.Fragment>
        ))}
      </Tag>
    )
  }
)
ProximityText.displayName = "ProximityText"

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `children` | `string` | - | Yes | The text. |
| `as` | `"h1" \| "h2" \| "h3" \| "p" \| "span"` | `"h2"` | No | Element to render. |
| `radius` | `number` | `140` | No | Reach of the effect in px. |
| `maxScale` | `number` | `1.45` | No | Scale of the letter under the cursor. |
| `lift` | `number` | `10` | No | How far the nearest letter rises, in px. |
| `accentColor` | `string` | `"#8b5cf6"` | No | Colour letters take on near the cursor. |
| `weight` | `number` | `600` | No | Font weight away from the cursor. Use this rather than a font-* class. |
| `weightBoost` | `number` | `300` | No | Extra weight near the cursor; smooth with a variable font such as Inter. |
| `className` | `string` | - | No | Extra classes for the text element. |
| `...props` | `React.HTMLAttributes<HTMLElement>` | - | No | Any other attributes, passed to the text element. |

## Usage
```tsx
"use client"

import { ProximityText } from "@/components/ui/proximity-text"

export default function ProximityTextDemo() {
  return (
    <div className="flex w-full max-w-3xl flex-col items-center gap-3 px-6 py-16 text-center">
      <ProximityText
        as="h2"
        className="text-4xl tracking-tight text-foreground sm:text-6xl"
      >
        Interfaces that notice you
      </ProximityText>
      <p className="text-sm text-muted-foreground">
        Glide your cursor across the headline
      </p>
    </div>
  )
}

```
