---
title: Reveal for Astro
description: "Reveal content as it enters view with fade-in and fade-up animations."
seo:
    title: Reveal for Astro | Shadcn & Tailwind CSS
related:
    - /components/card
    - /components/section
sidebar:
    label: "Reveal"
---

```astro
---
import { Reveal } from "@/components/ui/reveal"
---

<div
  class="h-72 w-full max-w-lg overflow-y-auto rounded-xl border p-6"
  tabindex="0"
  role="region"
  aria-label="Scroll to preview fade-up reveals"
>
  <p class="text-sm text-muted-foreground">
    Scroll down to reveal each card. Scroll back to repeat.
  </p>
  <div class="flex flex-col gap-32 pt-32 pb-8">
    {["Plan the project", "Build the first version", "Share the result"].map(
      (title) => (
        <Reveal
          as="article"
          once={false}
          class="rounded-lg border bg-card p-6 text-card-foreground"
        >
          <h3 class="font-medium">{title}</h3>
          <p class="mt-2 text-sm text-muted-foreground">
            Content fades in and moves up as it enters view.
          </p>
        </Reveal>
      ),
    )}
  </div>
</div>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/reveal
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

No extra packages are required.

#### src/components/ui/reveal/index.ts

```ts
export { default as Reveal } from './reveal.astro'
export type { RevealProps } from './types.ts'
```

#### src/components/ui/reveal/reveal.astro

```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

```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

```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
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```ts
import { Reveal } from "@/components/ui/reveal"
```

```astro
<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.

```astro
---
import { Reveal } from "@/components/ui/reveal"
---

<div
  class="h-72 w-full max-w-lg overflow-y-auto rounded-xl border p-6"
  tabindex="0"
  role="region"
  aria-label="Scroll to preview fade-in reveals"
>
  <p class="text-sm text-muted-foreground">
    Scroll down for a fade without movement.
  </p>
  <div class="flex flex-col gap-32 pt-32 pb-8">
    {["Find your focus", "Make space for the details", "Bring it together"].map(
      (title) => (
        <Reveal
          as="article"
          variant="fade-in"
          once={false}
          class="rounded-lg border bg-card p-6 text-card-foreground"
        >
          <h3 class="font-medium">{title}</h3>
          <p class="mt-2 text-sm text-muted-foreground">
            The layout stays in place while opacity changes.
          </p>
        </Reveal>
      ),
    )}
  </div>
</div>
```

### Timing

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

```astro
---
import { Reveal } from "@/components/ui/reveal"
---

<div
  class="h-72 w-full max-w-lg overflow-y-auto rounded-xl border p-6"
  tabindex="0"
  role="region"
  aria-label="Scroll to preview reveal timing"
>
  <p class="text-sm text-muted-foreground">
    Scroll down to compare the delays.
  </p>
  <div class="grid grid-cols-2 gap-4 pt-48 pb-8">
    <Reveal
      once={false}
      duration={800}
      class="rounded-lg border bg-card p-5 text-card-foreground"
    >
      <p class="font-medium">No delay</p>
      <p class="mt-2 text-sm text-muted-foreground">800 ms duration</p>
    </Reveal>
    <Reveal
      once={false}
      duration={800}
      delay={200}
      class="rounded-lg border bg-card p-5 text-card-foreground"
    >
      <p class="font-medium">200 ms delay</p>
      <p class="mt-2 text-sm text-muted-foreground">800 ms duration</p>
    </Reveal>
  </div>
</div>
```

## 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:

```astro
<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

<AutoTypeTable path="../../packages/ui/src/components/ui/reveal/types.ts" name="RevealProps" />

The `as` prop selects the HTML tag. Native attributes such as `class`, `id`, and
`aria-label` are also supported. Read the [installed source](/r/reveal.json).
