DocumentationReveal
Reveal
Animates its children in when they are scrolled into view.
Shared live previews stay running while you switch code examples and API documentation.
Quick start
Copy the component and everything it needs into your React project.
npx shadcn@latest add https://kida-ui.onrender.com/r/reveal.jsonRun this from a project with components.json. The CLI creates all required files and installs the declared runtime dependencies. New to shadcn? Follow theinstallation guide first.
Copy manually6 files
1. Install runtime dependencies
npm install motion@^13.1.02. Create the source files
Keep this directory structure so the component's relative imports continue to work.
src/components/ui/kida/reveal.tsx
'use client'
import './reveal.css'
import { type RevealOptions, reveal, revealInitialStyle } from './motion/reveal.js'
import type { ElementType, HTMLAttributes, ReactNode } from 'react'
import { forwardRef, useRef } from 'react'
import { composeRefs } from './compose-refs.js'
import { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect.js'
export interface RevealProps extends RevealOptions, Omit<HTMLAttributes<HTMLElement>, 'children'> {
children?: ReactNode
/** Element to render. @default 'div' */
as?: ElementType
}
/**
* Animates its children in when scrolled into view.
*
* The pre-animation state is rendered inline on the very first paint — including during
* SSR — so the content never flashes at full opacity before the effect runs.
*
* Changing a motion option re-arms the controller with the new behavior. Cubic-bezier arrays
* are compared by value, so an equivalent inline tuple does not restart the reveal.
*/
export const Reveal = forwardRef<HTMLElement, RevealProps>(function Reveal(
{
as: Tag = 'div',
children,
y,
x,
scale,
duration,
delay,
ease,
once,
amount,
margin,
style,
...props
},
forwardedRef,
) {
const ref = useRef<HTMLElement>(null)
const options = { y, x, scale, duration, delay, ease, once, amount, margin }
const easeDependency = Array.isArray(ease) ? ease.join(',') : ease
useIsomorphicLayoutEffect(() => {
const element = ref.current
if (!element) return
return reveal(element, options)
}, [Tag, amount, delay, duration, easeDependency, margin, once, scale, x, y])
return (
<Tag
{...props}
ref={composeRefs(ref, forwardedRef)}
data-kida-reveal=""
style={{ ...revealInitialStyle(options), ...style }}
>
{children}
</Tag>
)
})src/components/ui/kida/compose-refs.ts
import type { Ref } from 'react'
/** Feed one node to several refs — ours for measuring, Zag's for animation detection. */
export function composeRefs<T>(...refs: (Ref<T> | undefined)[]) {
return (node: T | null) => {
for (const ref of refs) {
if (typeof ref === 'function') ref(node)
else if (ref) (ref as { current: T | null }).current = node
}
}
}src/components/ui/kida/use-isomorphic-layout-effect.ts
'use client'
import { useEffect, useLayoutEffect } from 'react'
/**
* `useLayoutEffect` in the browser, `useEffect` on the server.
*
* Motion has to be applied before paint or the user sees an unstyled frame, but React
* warns when `useLayoutEffect` runs during SSR — where it does nothing anyway.
*/
export const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffectsrc/components/ui/kida/reveal.css
/* Server markup has the initial inline state before any adapter has hydrated. */
@media (prefers-reduced-motion: reduce) {
[data-kida-reveal] {
/* biome-ignore lint/complexity/noImportantStyles: overrides the SSR inline initial state */
opacity: 1 !important;
/* biome-ignore lint/complexity/noImportantStyles: overrides the SSR inline initial state */
transform: none !important;
/* biome-ignore lint/complexity/noImportantStyles: clears the SSR animation hint before hydration */
will-change: auto !important;
}
}src/components/ui/kida/motion/reveal.ts
import { animate, inView } from 'motion'
import { prefersReducedMotion } from './reduced-motion.js'
/** Derived from `motion` itself, so it can't drift from the engine's own accepted values. */
type InViewMargin = NonNullable<Parameters<typeof inView>[2]>['margin']
/** The easings we expose. Deliberately narrower than what `motion` accepts. */
export type RevealEase =
| 'linear'
| 'easeIn'
| 'easeOut'
| 'easeInOut'
| [number, number, number, number]
| ((t: number) => number)
export interface RevealOptions {
/** Vertical travel in px. Positive = starts below and rises. @default 8 */
y?: number
/** Horizontal travel in px. @default 0 */
x?: number
/** Starting scale. @default 1 */
scale?: number
/** Seconds. @default 0.5 */
duration?: number
/** Seconds. @default 0 */
delay?: number
/** @default [0.16, 1, 0.3, 1] — the same curve as `--kida-ease-out` */
ease?: RevealEase
/** Animate only the first time it enters the viewport. @default true */
once?: boolean
/** How much must be visible before firing. @default 0.3 */
amount?: 'some' | 'all' | number
/** Margin around the viewport, CSS-style. e.g. '0px 0px -10% 0px' */
margin?: InViewMargin
}
const DEFAULTS = {
y: 8,
x: 0,
scale: 1,
duration: 0.5,
delay: 0,
ease: [0.16, 1, 0.3, 1],
once: true,
amount: 0.3,
} as const
/**
* The identity of {@link revealInitialStyle}'s transform, written in the same shape.
*
* Animating to the keyword `none` looks right but is not: the engine has no numbers to
* interpolate towards and commits `matrix(0, 0, 0, 0, 0, 0)`, which collapses the element
* to 0x0. Ending on the same function list we started from keeps the interpolation
* componentwise and the final matrix an actual identity.
*/
const IDENTITY_TRANSFORM = 'translate3d(0px, 0px, 0) scale(1)'
/** The pre-animation state. Exported so adapters can render it on the very first paint. */
export function revealInitialStyle(options: RevealOptions = {}) {
const { y = DEFAULTS.y, x = DEFAULTS.x, scale = DEFAULTS.scale } = options
return {
opacity: 0,
transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`,
willChange: 'transform, opacity',
} as const
}
/**
* Animate an element into view when it is scrolled to.
*
* Framework-agnostic: takes an element, returns a cleanup function. Every adapter
* (React today, Svelte later) is a ~20-line wrapper around this.
*
* Under `prefers-reduced-motion: reduce` the element is put into its final state
* immediately — visible, unanimated. It is never left hidden.
*/
export function reveal(element: HTMLElement, options: RevealOptions = {}): () => void {
const {
duration = DEFAULTS.duration,
delay = DEFAULTS.delay,
ease = DEFAULTS.ease,
once = DEFAULTS.once,
amount = DEFAULTS.amount,
margin,
} = options
// `transform: none` rather than an identity matrix: any transform value other than
// `none` makes the element a containing block for fixed-position descendants, which
// would silently reposition a popover rendered inside a revealed card.
const settle = () => {
element.style.opacity = '1'
element.style.transform = 'none'
element.style.willChange = 'auto'
}
// Own the pre-animation state, so the engine works even when the adapter didn't set it.
const hide = () => {
Object.assign(element.style, revealInitialStyle(options))
}
if (prefersReducedMotion()) {
settle()
return () => {}
}
hide()
// Bumped on every entry and every exit, so a settle scheduled by a pass that has since
// been superseded — or re-hidden — is dropped instead of flashing the element visible.
let pass = 0
let animation: ReturnType<typeof animate> | undefined
let settleFrame = 0
const cancelSettle = () => {
if (!settleFrame) return
cancelAnimationFrame(settleFrame)
settleFrame = 0
}
const stop = inView(
element,
() => {
cancelSettle()
animation?.cancel()
const generation = ++pass
const from = revealInitialStyle(options)
const currentAnimation = animate(
element,
// Both ends spelled out. The engine caches what it last animated an element to, so
// after a completed reveal it believes opacity is already 1 — and `hide()` writing
// the style directly is invisible to that cache. Left to infer its own start, a
// re-entry would resolve instantly and never animate.
{ opacity: [from.opacity, 1], transform: [from.transform, IDENTITY_TRANSFORM] },
// The engine commits its own final keyframe as an inline style, one `onComplete`
// per animated property, and settling from inside that callback loses the race
// against whichever property finishes last. A frame later nothing is left to
// overwrite us. `onComplete` also never fires on cancel, which is what we want:
// an interrupted reveal must not jump to visible.
{
duration,
delay,
ease,
onComplete: () => {
cancelSettle()
settleFrame = requestAnimationFrame(() => {
settleFrame = 0
if (generation === pass) settle()
})
},
},
)
animation = currentAnimation
if (once) {
stop()
return
}
// `inView` runs this when the element leaves again. Without re-arming, `once: false`
// would replay an animation from visible to visible, which is no animation at all.
return () => {
pass++
cancelSettle()
currentAnimation.cancel()
if (animation === currentAnimation) animation = undefined
hide()
}
},
{ amount, ...(margin ? { margin } : {}) },
)
return () => {
pass++
stop()
cancelSettle()
animation?.cancel()
animation = undefined
}
}src/components/ui/kida/motion/reduced-motion.ts
const QUERY = '(prefers-reduced-motion: reduce)'
/**
* Whether the user has asked for reduced motion.
*
* SSR-safe: returns `false` when there is no `window`, matching the CSS default
* (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;
* this is for the JS-driven paths that CSS cannot express).
*/
export function prefersReducedMotion(): boolean {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
return window.matchMedia(QUERY).matches
}
/**
* Subscribe to changes of the reduced-motion preference.
* Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.
*/
export function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}
const list = window.matchMedia(QUERY)
const handler = (event: MediaQueryListEvent) => onChange(event.matches)
list.addEventListener('change', handler)
return () => list.removeEventListener('change', handler)
}import { Reveal } from '@/components/ui/kida/reveal'
export default function RevealExample() {
return (
<Reveal>
<h2>Rises into place</h2>
</Reveal>
)
}The copy-source command includes the stylesheet that keeps server-rendered content visible under
reduced motion before hydration. Package consumers must import @kida-ui/styles/kida.css once.
Customization
{"x":-32,"y":0}{"scale":0.9,"y":0}{"duration":1.2}{"once":false}import { Reveal } from '@kida-ui/react'
const CARDS = [
{ title: 'From the left', options: { x: -32, y: 0 } },
{ title: 'Scale up', options: { scale: 0.9, y: 0 } },
{ title: 'Slow', options: { duration: 1.2 } },
{ title: 'Every time', options: { once: false } },
]
export default function RevealOptions() {
return (
<div className="demo-grid">
{CARDS.map(({ title, options }) => (
<Reveal key={title} {...options} className="demo-card">
<strong>{title}</strong>
<code>{JSON.stringify(options)}</code>
</Reveal>
))}
</div>
)
}API
Props
| Prop | Type | Default | Description |
|---|---|---|---|
y |
number |
8 |
Vertical travel in px. Positive starts below and rises. |
x |
number |
0 |
Horizontal travel in px. |
scale |
number |
1 |
Starting scale. |
duration |
number |
0.5 |
Seconds. |
delay |
number |
0 |
Seconds. |
ease |
RevealEase |
[0.16, 1, 0.3, 1] |
The same curve as --kida-ease-out. |
once |
boolean |
true |
Animate only the first entry into the viewport. |
amount |
'some' | 'all' | number |
0.3 |
How much must be visible before it fires. |
margin |
string |
— | Margin around the viewport, CSS-style. |
as |
ElementType |
'div' |
Element to render. |
className |
string |
— | Passed straight through. |
style |
CSSProperties |
— | Merged over the pre-animation state. |
Safe native attributes, event handlers, and a forwarded ref are passed to the root.
Easing values
ease accepts 'linear', 'easeIn', 'easeOut', 'easeInOut', a four-number cubic
bézier, or your own (t: number) => number. The set is deliberately narrower than what the
underlying engine accepts.
Accessibility and input behavior
Reveal does not change the semantics or focus order of its content. Server-rendered output includes
the starting visual state, so hydration does not flash visible content before the animation begins.
Under prefers-reduced-motion: reduce, the required stylesheet makes content visible before
hydration, and the controller skips animation when it mounts.
Troubleshooting
Changing a motion option cleans up the current controller and re-arms Reveal with the new behavior. Equivalent inline cubic-bézier tuples are compared by value and do not restart the animation.