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

Reveal for Astro

Reveal content as it enters view with fade-in and fade-up animations.

Scroll down to reveal each card. Scroll back to repeat.

Plan the project

Content fades in and moves up as it enters view.

Build the first version

Content fades in and moves up as it enters view.

Share the result

Content fades in and moves up as it enters view.

Installation

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

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

No extra packages are required.

Copy the files

src/components/ui/reveal/index.ts
export { default as Reveal } from './reveal.astro'
export type { RevealProps } from './types.ts'
src/components/ui/reveal/reveal.astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cva } from "class-variance-authority"
import { cn } from "cn"
import type { RevealProps } from "./types.ts"

type Props<Tag extends HTMLTag = "div"> = Polymorphic<{ as: Tag }> & RevealProps

const revealVariants = cva(
  "transition-[opacity,translate] delay-(--reveal-delay) duration-(--reveal-duration) focus-within:delay-0 focus-within:duration-0 data-[reveal-state=pending]:opacity-0 motion-reduce:transition-none motion-reduce:delay-0",
  {
    variants: {
      variant: {
        "fade-in": "",
        "fade-up": "data-[reveal-state=pending]:translate-y-6",
      },
    },
    defaultVariants: { variant: "fade-up" },
  },
)

const {
  as: Tag = "div",
  variant = "fade-up",
  duration = 600,
  delay = 0,
  once = true,
  enabled = true,
  class: className,
  style,
  ...props
} = Astro.props

const timing = {
  "--reveal-duration": `${Number.isFinite(duration) ? Math.max(0, duration) : 600}ms`,
  "--reveal-delay": `${Number.isFinite(delay) ? Math.max(0, delay) : 0}ms`,
}
const rootStyle =
  typeof style === "string"
    ? `--reveal-duration:${timing["--reveal-duration"]};--reveal-delay:${timing["--reveal-delay"]};${style}`
    : { ...timing, ...style }
---

<Tag
  {...props}
  data-slot="reveal"
  data-variant={variant}
  data-reveal-once={String(once)}
  data-reveal-disabled={!enabled || undefined}
  class={cn(revealVariants({ variant }), className)}
  style={rootStyle}
>
  <slot />
</Tag>

<script>
  import { observeReveals } from "./reveal-controller.ts"

  observeReveals()
</script>
src/components/ui/reveal/reveal-controller.ts
/** Attach viewport behavior to one rendered Reveal element. */
export function createReveal(root: HTMLElement): () => void {
    if (
        root.hasAttribute('data-reveal-disabled') ||
        typeof IntersectionObserver === 'undefined'
    )
        return () => {}

    const reduced = matchMedia('(prefers-reduced-motion: reduce)')
    const controller = new AbortController()
    const once = root.dataset.revealOnce !== 'false'
    let complete = false
    const show = () => {
        root.dataset.revealState = 'visible'
        if (once) {
            complete = true
            observer.disconnect()
        }
    }
    const observer = new IntersectionObserver(
        (entries) => {
            if (controller.signal.aborted || complete || reduced.matches) return
            for (const entry of entries) {
                if (
                    entry.isIntersecting ||
                    root.contains(root.ownerDocument.activeElement)
                ) {
                    show()
                } else if (!once) {
                    root.dataset.revealState = 'pending'
                }
            }
        },
        { threshold: 0.08 },
    )

    if (reduced.matches || root.contains(root.ownerDocument.activeElement)) {
        show()
    } else {
        root.dataset.revealState = 'pending'
    }
    if (!reduced.matches && !complete) observer.observe(root)

    root.addEventListener('focusin', show, { signal: controller.signal })
    reduced.addEventListener(
        'change',
        () => {
            if (reduced.matches) {
                observer.disconnect()
                show()
            } else if (!complete) {
                observer.observe(root)
            }
        },
        { signal: controller.signal },
    )

    return () => {
        controller.abort()
        observer.disconnect()
        delete root.dataset.revealState
    }
}

/** Bind new instances and clean up removed instances, including Astro navigation. */
export function observeReveals(): () => void {
    const selector = '[data-slot="reveal"]'
    const instances = new Map<HTMLElement, () => void>()
    const controller = new AbortController()
    const bind = (root: HTMLElement) => {
        if (!instances.has(root)) instances.set(root, createReveal(root))
    }
    const scan = (parent: ParentNode) => {
        parent.querySelectorAll<HTMLElement>(selector).forEach(bind)
    }
    const clear = () => {
        instances.forEach((cleanup) => cleanup())
        instances.clear()
    }
    const mutations = new MutationObserver((records) => {
        for (const [root, cleanup] of instances) {
            if (!root.isConnected) {
                cleanup()
                instances.delete(root)
            }
        }
        for (const record of records) {
            for (const node of record.addedNodes) {
                if (!(node instanceof HTMLElement) || !node.isConnected)
                    continue
                if (node.matches(selector)) bind(node)
                scan(node)
            }
        }
    })

    scan(document)
    mutations.observe(document.documentElement, {
        childList: true,
        subtree: true,
    })
    document.addEventListener('astro:page-load', () => scan(document), {
        signal: controller.signal,
    })
    document.addEventListener('astro:before-swap', clear, {
        signal: controller.signal,
    })

    return () => {
        controller.abort()
        mutations.disconnect()
        clear()
    }
}
src/components/ui/reveal/types.ts
/** Options for an element that appears when it enters the visible area. */
export interface RevealProps {
    /**
     * Entrance effect. Fade-up also moves the element up from its starting offset.
     * @default 'fade-up'
     */
    variant?: 'fade-in' | 'fade-up'
    /**
     * Transition duration in milliseconds.
     * @default 600
     */
    duration?: number
    /**
     * Delay before the transition, in milliseconds.
     * @default 0
     */
    delay?: number
    /**
     * Reveal once. Set false to repeat when the element leaves and enters view.
     * @default true
     */
    once?: boolean
    /**
     * Enable the reveal behavior. Disabled elements remain visible.
     * @default true
     */
    enabled?: boolean
}

Usage

import { Reveal } from "@/components/ui/reveal"
<Reveal as="h2" variant="fade-up" class="text-section-title">
  A clear view of your next project
</Reveal>

Reveal renders one HTML element. Use as to select its tag; the default is div. Native attributes, caller classes, and styles apply to that element. There is no extra wrapper, and the component includes its browser script.

Examples

Fade up

The default variant fades in and moves up from a small vertical offset. Scroll inside the preview to reveal the content. These examples use once={false} so you can scroll away and repeat the animation.

Fade in

Use fade-in to change opacity without movement.

Scroll down for a fade without movement.

Find your focus

The layout stays in place while opacity changes.

Make space for the details

The layout stays in place while opacity changes.

Bring it together

The layout stays in place while opacity changes.

Timing

Set duration and delay in milliseconds. Each element has its own timing.

Scroll down to compare the delays.

No delay

800 ms duration

200 ms delay

800 ms duration

Behavior

The default once={true} keeps content visible after its first entrance. With once={false}, content returns to its starting state after it leaves view. Set enabled={false} to keep an instance visible without reveal behavior.

Content is visible in the server-rendered HTML. It stays visible when JavaScript or Intersection Observer is unavailable. Reduced motion skips the entrance effect. Keyboard focus reveals content immediately, including nested reveals. The script cleans up removed instances and handles Astro page navigation.

Reveal handles viewport entrance effects. It does not manage exit animations or delay the removal of an element. It uses CSS transitions and a browser observer; it does not require Motion or a hydrated UI framework.

Theme and layout

Colors, fonts, and layout come from your content and classes. Reveal does not select a preset. Its animation utilities work with the selected project preset. Use cn-merged classes to change timing or the pending offset when needed:

<Reveal class="duration-300 data-[reveal-state=pending]:translate-y-2">
  <p>A shorter, faster entrance.</p>
</Reveal>

Apply transforms for other effects to a child when they must move independently of the reveal. Use an element with a layout box for fade-up; a plain inline element can use class="inline-block".

API Reference

PropType
variant?'fade-in' | 'fade-up'

Entrance effect. Fade-up also moves the element up from its starting offset.

Type'fade-in' | 'fade-up'
Default'fade-up'
duration?number

Transition duration in milliseconds.

Typenumber
Default600
delay?number

Delay before the transition, in milliseconds.

Typenumber
Default0
once?boolean

Reveal once. Set false to repeat when the element leaves and enters view.

Typeboolean
Defaulttrue
enabled?boolean

Enable the reveal behavior. Disabled elements remain visible.

Typeboolean
Defaulttrue

The as prop selects the HTML tag. Native attributes such as class, id, and aria-label are also supported. Read the installed source.