Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Hover Glow Effect For Astro

A pointer glow that follows the cursor over any pattern.

Move the pointer

Installation

bunx --bun shadcn@latest add @gnostic/hover-glow
npx shadcn@latest add @gnostic/hover-glow
pnpm dlx shadcn@latest add @gnostic/hover-glow

Complete the Installation guide first. Then copy the component files below.

No extra packages are required.

Copy the files

src/components/patterns/hover-glow/hover-glow.astro
---
import type { HTMLAttributes } from "astro/types"
import type { HoverGlowProps } from "./types.ts"

import { cn } from "cn"
import { mergeStyles } from "../../../lib/merge-styles.ts"

/**
 * Pointer glow over any pattern.
 *
 * The slot holds the pattern and the content. The glow layer paints a
 * radial gradient and follows the pointer. A mask clips that gradient
 * to a pattern shape. With no mask, the glow is a plain spotlight.
 */
type Props = HTMLAttributes<"div"> & HoverGlowProps

const {
  glowSize = 96,
  maskImage = "none",
  maskSize = "auto",
  maskPosition = "center",
  glowColor = `color-mix(in oklch, var(--primary) ${maskImage === "none" ? 42 : 72}%, transparent)`,
  class: className,
  style: styleProp,
  ...props
} = Astro.props

/** The script moves the glow by updating these variables on the glow layer. */
const style = mergeStyles(
  {
    "--glow-color": glowColor,
    "--glow-x": "-1000px",
    "--glow-y": "-1000px",
    "--glow-opacity": "0",
  },
  styleProp,
)

/** Shared paint. Pattern components supply a mask. The script supplies the position. */
const glowStyle = {
  opacity: "var(--glow-opacity)",
  background: `radial-gradient(circle ${glowSize}px at var(--glow-x) var(--glow-y), var(--glow-color) 0%, var(--glow-color) 25%, transparent 72%)`,
  "mask-image": maskImage,
  "mask-size": maskSize,
  "mask-position": maskPosition,
  "-webkit-mask-image": maskImage,
  "-webkit-mask-size": maskSize,
  "-webkit-mask-position": maskPosition,
} satisfies astroHTML.JSX.CSSProperties
---

<div data-slot="hover-glow-viewport" class="contents">
  <div
    data-slot="hover-glow-container"
    class={cn("relative", className)}
    style={style}
    {...props}
  >
    <slot />
    <div
      aria-hidden="true"
      data-slot="hover-glow"
      class="pointer-events-none absolute inset-0 transition-opacity duration-200"
      style={glowStyle}
    />
  </div>
</div>

<script>
  import { createHoverGlow, type HoverGlowController } from "./hover-glow.ts"

  const controllers: HoverGlowController[] = []

  /** Drop listeners before a new page view or a repeat init. */
  function cleanup() {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  }

  /** Bind every glow viewport currently in the document. */
  function init() {
    cleanup()
    document
      .querySelectorAll<HTMLElement>('[data-slot="hover-glow-viewport"]')
      .forEach((viewport) => {
        controllers.push(createHoverGlow(viewport))
      })
  }

  init()
  document.addEventListener("astro:page-load", init)
  document.addEventListener("astro:before-swap", cleanup)
</script>
src/components/patterns/hover-glow/hover-glow.ts
export type GlowPoint = { x: number; y: number }

export type HoverGlowController = {
    destroy: () => void
    readonly isActive: boolean
}

/** Box whose pointer position drives the glow. */
const CONTAINER_SELECTOR = "[data-slot='hover-glow-container']"

/** Layer that receives the glow CSS variables. */
const GLOW_SELECTOR = "[data-slot='hover-glow']"

const active = new WeakMap<HTMLElement, () => void>()

/**
 * Bind pointer tracking for hover-glow layers inside one viewport.
 *
 * The function writes `--glow-x`, `--glow-y`, and
 * `--glow-opacity`. It does not read the pattern under the glow.
 *
 * Listeners attach to the viewport, not `document`. Call again after
 * `astro:page-load`. Call `destroy` on `astro:before-swap`.
 *
 * @param viewport - Element that contains the hover-glow containers.
 * @returns Teardown for this viewport binding.
 */
export function createHoverGlow(viewport: HTMLElement): HoverGlowController {
    // Replace an earlier binding for this viewport.
    active.get(viewport)?.()

    // Latest pointer position for each container, in container pixels.
    const points = new WeakMap<HTMLElement, GlowPoint>()
    // Pending animation frame id for each container.
    const frames = new WeakMap<HTMLElement, number>()

    // The event target can be content inside the container.
    const getContainer = (event: PointerEvent) => {
        const target = event.target
        if (!(target instanceof Element)) return null
        const container = target.closest<HTMLElement>(CONTAINER_SELECTOR)
        return container && viewport.contains(container) ? container : null
    }

    const getGlow = (container: HTMLElement) =>
        container.querySelector<HTMLElement>(GLOW_SELECTOR)

    const paint = (container: HTMLElement) => {
        frames.delete(container)
        const point = points.get(container)
        const glow = getGlow(container)
        if (!point || !glow) return
        glow.style.setProperty('--glow-x', `${point.x}px`)
        glow.style.setProperty('--glow-y', `${point.y}px`)
    }

    const hide = (container: HTMLElement) => {
        points.delete(container)
        const glow = getGlow(container)
        if (!glow) return
        glow.style.setProperty('--glow-opacity', '0')
    }

    const hideAllInViewport = () => {
        viewport
            .querySelectorAll<HTMLElement>(CONTAINER_SELECTOR)
            .forEach((container) => hide(container))
    }

    const onPointerEnter = (event: PointerEvent) => {
        const container = getContainer(event)
        const glow = container && getGlow(container)
        if (!container || !glow) return
        glow.style.setProperty('--glow-opacity', '1')
    }

    const onPointerMove = (event: PointerEvent) => {
        const container = getContainer(event)
        if (!container) return
        const rect = container.getBoundingClientRect()
        points.set(container, {
            x: event.clientX - rect.left,
            y: event.clientY - rect.top,
        })
        if (frames.has(container)) return
        frames.set(
            container,
            requestAnimationFrame(() => paint(container)),
        )
    }

    const onPointerLeave = (event: PointerEvent) => {
        const container = getContainer(event)
        if (!container) return
        const next = event.relatedTarget
        // Ignore moves between elements inside the same container.
        if (next instanceof Node && container.contains(next)) return
        hide(container)
    }

    const onWindowBlur = () => {
        hideAllInViewport()
    }

    // pointerenter and pointerleave do not bubble, so listen during capture.
    viewport.addEventListener('pointerenter', onPointerEnter, true)
    viewport.addEventListener('pointermove', onPointerMove, { passive: true })
    viewport.addEventListener('pointerleave', onPointerLeave, true)
    window.addEventListener('blur', onWindowBlur)

    const destroy = () => {
        viewport.removeEventListener('pointerenter', onPointerEnter, true)
        viewport.removeEventListener('pointermove', onPointerMove)
        viewport.removeEventListener('pointerleave', onPointerLeave, true)
        window.removeEventListener('blur', onWindowBlur)
        hideAllInViewport()
        active.delete(viewport)
    }

    active.set(viewport, destroy)
    return {
        destroy,
        get isActive() {
            return active.has(viewport)
        },
    }
}
src/components/patterns/hover-glow/index.ts
export { default as HoverGlow } from './hover-glow.astro'
export type { HoverGlowProps } from './types.ts'
src/components/patterns/hover-glow/types.ts
/**
 * Pointer glow that sits over any pattern or content.
 *
 * The default slot is the pattern and the content. A color layer fades in
 * under the pointer. `maskImage` clips that layer to a pattern shape.
 * Leave the mask unset for a plain spotlight.
 */
export type HoverGlowProps = {
    /**
     * CSS color of the glow.
     * Use the color's alpha value to set the glow opacity.
     * The default keeps the glow soft.
     *
     * @default "color-mix(in oklch, var(--primary) 72%, transparent)"
     */
    glowColor?: string
    /**
     * Radius of the glow, in pixels.
     *
     * @default 96
     */
    glowSize?: number
    /**
     * CSS `mask-image` for the glow layer.
     * Use a repeating mask so the glow shows only inside a pattern shape.
     *
     * @default "none"
     */
    maskImage?: string
    /**
     * CSS `mask-size` for the glow layer.
     *
     * @default "auto"
     */
    maskSize?: string
    /**
     * CSS `mask-position` for the glow layer.
     *
     * @default "center"
     */
    maskPosition?: string
}

Usage

HoverGlow is the positioned container. Move the pointer over it to show the glow. The preview above has no pattern. Give text relative z-10 when the text must stay above the glow.

import { HoverGlow } from "@/components/patterns/hover-glow"
<HoverGlow class="h-72">
  <p class="relative z-10">Move the pointer</p>
</HoverGlow>

The glow color defaults to a 40 percent mix of var(--color-primary), so a plain spotlight stays soft. A masked pattern is small, so give it more alpha or the shapes disappear. glowSize sets the radius in pixels.

The glow fades out when the pointer leaves the container or the window loses focus.

Set maskImage to one tile of a pattern and maskSize to the tile size when the glow should follow that pattern. The color shows only inside the tile. Leave the pattern out of the slot to hide it until the pointer arrives. Put the same pattern in the slot when it should stay visible and the glow should only color its shape. Leave the mask unset to paint the glow across the whole area.

Dots use a small circle for each tile:

<HoverGlow
  class="h-72"
  maskImage="radial-gradient(circle, black 1.5px, transparent 1.5px)"
  maskSize="18px 18px"
/>

A grid uses one horizontal line and one vertical line. 60px matches the default grid cell:

<HoverGlow
  class="h-72"
  maskImage="linear-gradient(black 1px, transparent 1px), linear-gradient(90deg, black 1px, transparent 1px)"
  maskSize="60px 60px"
/>

Dot Pattern with Glow keeps the base dots and uses the dot mask, so the dots stay visible and the glow colors them.

Examples

Reveal on hover

This example has no base pattern. The dot mask is the only pattern.

Hidden until hover

API Reference

HoverGlowProps

PropType
glowColor?string

CSS color of the glow. Use the color's alpha value to set the glow opacity. The default keeps the glow soft.

Typestring
Default"color-mix(in oklch, var(--primary) 72%, transparent)"
glowSize?number

Radius of the glow, in pixels.

Typenumber
Default96
maskImage?string

CSS `mask-image` for the glow layer. Use a repeating mask so the glow shows only inside a pattern shape.

Typestring
Default"none"
maskSize?string

CSS `mask-size` for the glow layer.

Typestring
Default"auto"
maskPosition?string

CSS `mask-position` for the glow layer.

Typestring
Default"center"

See the registry source for the component source.