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.
Place content inside the component. Native attributes and events use Svelte spelling, such as
onclick, and bind:element gives you the root DOM element.
Quick start
Copy the component and everything it needs into your Svelte 5 project.
npx shadcn-svelte@1.8.0 add https://kida-ui.onrender.com/r/svelte/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.
Files land in src/lib/components/ui/kida by default. SvelteKit 3 projects import them through #lib; SvelteKit 2 and Vite projects use $lib, as in the examples here.
Copy manually5 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/lib/components/ui/kida/reveal.svelte
<script lang="ts">
import './reveal.css'
import { reveal, revealInitialStyle } from './reveal.motion.js'
import { untrack } from 'svelte'
import type { RevealProps } from './reveal.types.js'
let {
as = 'div',
x,
y,
scale,
duration,
delay,
ease,
once,
amount,
margin,
element = $bindable(null),
style,
children,
...rest
}: RevealProps = $props()
// A parent's {...spread} invalidates every prop when any one changes. These deriveds only
// notify on a real value change, so unrelated updates cannot restart the controller.
const root = $derived(element)
const easeKey = $derived(Array.isArray(ease) ? ease.join(',') : ease)
const optionsKey = $derived(JSON.stringify([x, y, scale, duration, delay, once, amount, margin]))
// The controller owns these inline values after mount. A changed authored style must carry
// them forward, or it would re-hide a settled reveal. A new root starts from the initial state.
const rootStyle = $derived.by(() => {
const tag = as
const authored = style
const node = untrack(() => element)
const motion =
node?.localName === tag
? {
opacity: node.style.opacity,
transform: node.style.transform,
willChange: node.style.willChange,
}
: untrack(() => revealInitialStyle({ x, y, scale }))
return [
`opacity: ${motion.opacity}`,
`transform: ${motion.transform}`,
`will-change: ${motion.willChange}`,
authored,
]
.filter(Boolean)
.join('; ')
})
$effect(() => {
const node = root
void [optionsKey, easeKey]
if (!node) return
return untrack(() => reveal(node, { x, y, scale, duration, delay, ease, once, amount, margin }))
})
</script>
<svelte:element this={as} {...rest} bind:this={element} data-kida-reveal="" style={rootStyle}>{@render children?.()}</svelte:element>src/lib/components/ui/kida/reveal.types.ts
import type { RevealOptions } from './reveal.motion.js';
import type { HTMLAttributes } from 'svelte/elements';
export type RevealEase = NonNullable<RevealOptions['ease']>;
export interface RevealProps extends RevealOptions, HTMLAttributes<HTMLElement> {
/** Semantic HTML root. @default 'div' */
as?: keyof HTMLElementTagNameMap;
/** Bind to read the root DOM element; null after unmount. */
element?: HTMLElement | null;
}src/lib/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/lib/components/ui/kida/reveal.motion.ts
import { animate, inView } from 'motion'
import { prefersReducedMotion } from './reduced-motion.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/lib/components/ui/kida/reduced-motion.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)
}<script lang="ts">
import Reveal from '$lib/components/ui/kida/reveal.svelte'
</script>
<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.
Customization
{"x":-32,"y":0}{"scale":0.9,"y":0}{"duration":1.2}{"once":false}<script lang="ts">
import { Reveal } from '@kida-ui/svelte'
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 } },
]
</script>
<div class="demo-grid">
{#each cards as card (card.title)}
<Reveal {...card.options} class="demo-card">
<strong>{card.title}</strong>
<code>{JSON.stringify(card.options)}</code>
</Reveal>
{/each}
</div>Use x, y, scale, duration, and ease to tune the entrance. Set once={false} to replay it
each time the content enters the viewport.
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 |
keyof HTMLElementTagNameMap |
'div' |
Element to render. |
element |
HTMLElement | null |
null |
Use bind:element to read the root DOM element. |
class |
string |
— | Passed straight through. |
style |
string |
— | Merged over the pre-animation state. |
Other native attributes and event handlers are passed to the root.
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 shared 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.
Updating unrelated props, such as class, does not restart it, even through a {...rest} spread.