DocumentationPhotoPile
PhotoPile
Layers draggable photos that spring back into a playful composition.
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/photo-pile.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/photo-pile.tsx
'use client'
import './photo-pile.css'
import { type PhotoPileOptions, photoPile } from './motion/photo-pile.js'
import type { CSSProperties, HTMLAttributes, ImgHTMLAttributes } from 'react'
import { forwardRef, useRef } from 'react'
import { composeRefs } from './compose-refs.js'
import { useIsomorphicLayoutEffect } from './use-isomorphic-layout-effect.js'
export interface PhotoPilePhoto {
/** Stable key for this photo. */
id: string
src: string
alt: string
/** Horizontal offset from the center, in CSS pixels. */
x?: number
/** Vertical offset from the center, in CSS pixels. */
y?: number
/** Resting rotation in degrees. */
rotation?: number
imageProps?: Omit<ImgHTMLAttributes<HTMLImageElement>, 'src' | 'alt' | 'draggable'>
}
export interface PhotoPileProps
extends PhotoPileOptions,
Omit<HTMLAttributes<HTMLFieldSetElement>, 'children'> {
photos: readonly PhotoPilePhoto[]
/** Multiplies the default and authored x/y offsets. @default 1 */
spread?: number
}
const POSITIONS = [
{ x: -54, y: -10, rotation: -7 },
{ x: 52, y: -18, rotation: 6 },
{ x: 2, y: 30, rotation: -1.5 },
{ x: -24, y: -38, rotation: 4 },
{ x: 38, y: 24, rotation: -5 },
] as const
type ItemStyle = CSSProperties & {
'--kida-photo-x': string
'--kida-photo-y': string
'--kida-photo-rotation': string
}
export const PhotoPile = forwardRef<HTMLFieldSetElement, PhotoPileProps>(function PhotoPile(
{ photos, spread = 1, dragScale, tilt, 'aria-label': ariaLabel, ...props },
forwardedRef,
) {
const ref = useRef<HTMLFieldSetElement>(null)
const photoKey = photos.map((photo) => photo.id).join('\u0000')
useIsomorphicLayoutEffect(() => {
const root = ref.current
if (!root) return
return photoPile(root, { dragScale, tilt })
}, [photoKey, dragScale, tilt])
return (
<fieldset
{...props}
ref={composeRefs(ref, forwardedRef)}
aria-label={ariaLabel ?? 'Draggable photo pile'}
data-kida-photo-pile=""
>
<span data-kida-photo-stage="">
{photos.map((photo, index) => {
const fallback = POSITIONS[index % POSITIONS.length] ?? POSITIONS[0]
const label = photo.alt || `Photo ${index + 1}`
const style: ItemStyle = {
'--kida-photo-x': `${(photo.x ?? fallback.x) * spread}px`,
'--kida-photo-y': `${(photo.y ?? fallback.y) * spread}px`,
'--kida-photo-rotation': `${photo.rotation ?? fallback.rotation}deg`,
zIndex: index + 1,
}
return (
<button
key={photo.id}
type="button"
aria-label={`Bring ${label} to front and drag`}
data-kida-photo-item=""
style={style}
>
<span data-kida-photo-card="">
<img {...photo.imageProps} src={photo.src} alt={photo.alt} draggable={false} />
</span>
</button>
)
})}
</span>
</fieldset>
)
})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/photo-pile.css
[data-kida-photo-pile] {
--kida-photo-width: clamp(9rem, 42%, 13.5rem);
--kida-photo-radius: 0.55rem;
--kida-photo-frame: #fffafb;
--kida-photo-shadow: 0 0.8rem 2rem rgb(50 30 42 / 16%);
position: relative;
display: block;
min-inline-size: 0;
width: min(100%, 36rem);
min-height: 22rem;
margin: 0;
padding: 0;
border: 0;
isolation: isolate;
}
/* Chromium does not reliably use a fieldset itself as the containing block for absolutely
positioned children. A normal-flow stage keeps every card anchored to the pile wherever the
fieldset appears on the page. */
[data-kida-photo-stage] {
position: relative;
/* Grid centers fractional card sizes without percentage transforms, which WebKit rounds. */
display: grid;
place-items: center;
/* Fill explicitly sized previews as well as the pile's default minimum height. */
height: 100%;
min-height: inherit;
}
[data-kida-photo-item] {
position: absolute;
width: var(--kida-photo-width);
margin: 0;
padding: 0;
border: 0;
border-radius: var(--kida-photo-radius);
background: transparent;
cursor: grab;
touch-action: none;
transform: translate(var(--kida-photo-x), var(--kida-photo-y)) rotate(var(--kida-photo-rotation));
}
[data-kida-photo-item][data-dragging] {
cursor: grabbing;
}
[data-kida-photo-item]:focus-visible {
outline: 3px solid var(--kida-photo-focus, #6d52a8);
outline-offset: 5px;
}
[data-kida-photo-card] {
display: block;
padding: 0.45rem 0.45rem 1.8rem;
border: 1px solid rgb(55 35 48 / 12%);
border-radius: var(--kida-photo-radius);
background: var(--kida-photo-frame);
box-shadow: var(--kida-photo-shadow);
user-select: none;
}
[data-kida-photo-card] img {
display: block;
width: 100%;
aspect-ratio: 4 / 5;
border-radius: calc(var(--kida-photo-radius) - 0.2rem);
object-fit: cover;
pointer-events: none;
}
@media (max-width: 32rem) {
[data-kida-photo-pile] {
--kida-photo-width: min(48%, 10.5rem);
min-height: 18rem;
}
}
@media (prefers-reduced-motion: reduce) {
[data-kida-photo-card] {
/* biome-ignore lint/complexity/noImportantStyles: stops an in-flight inline transform */
transform: none !important;
}
}src/components/ui/kida/motion/photo-pile.ts
import { animate } from 'motion'
import { prefersReducedMotion } from './reduced-motion.js'
export interface PhotoPileOptions {
/** Scale applied while a photo is being dragged. @default 1.035 */
dragScale?: number
/** Degrees of responsive tilt per horizontal CSS pixel. @default 0.025 */
tilt?: number
}
const DEFAULTS = { dragScale: 1.035, tilt: 0.025 } as const
const IDENTITY = 'translate3d(0px, 0px, 0) rotate(0deg) scale(1)'
/**
* Adds direct pointer dragging and a spring return to every photo card in a pile.
* The positioned item stays still; only its inner card moves, so authored layout transforms
* never compete with the drag transform.
*/
export function photoPile(root: HTMLElement, options: PhotoPileOptions = {}): () => void {
const { dragScale = DEFAULTS.dragScale, tilt = DEFAULTS.tilt } = options
const reduced = prefersReducedMotion()
const items = [...root.querySelectorAll<HTMLElement>('[data-kida-photo-item]')]
const cleanups: Array<() => void> = []
const originalZ = new Map(items.map((item) => [item, item.style.zIndex]))
let topLayer = items.length
const activate = (item: HTMLElement) => {
topLayer += 1
item.style.zIndex = String(topLayer)
}
for (const item of items) {
const card = item.querySelector<HTMLElement>('[data-kida-photo-card]')
if (!card) continue
let pointerId: number | undefined
let originX = 0
let originY = 0
let x = 0
let y = 0
let frame = 0
let settleFrame = 0
let controls: ReturnType<typeof animate> | undefined
const transform = () =>
`translate3d(${x}px, ${y}px, 0) rotate(${x * tilt}deg) scale(${dragScale})`
const paint = () => {
frame = 0
card.style.transform = transform()
}
const settle = () => {
controls?.cancel()
controls = undefined
card.style.transform = 'none'
card.style.willChange = 'auto'
delete item.dataset.dragging
}
const onPointerDown = (event: PointerEvent) => {
if (pointerId !== undefined || (event.pointerType === 'mouse' && event.button !== 0)) return
if (settleFrame) {
cancelAnimationFrame(settleFrame)
settleFrame = 0
}
controls?.cancel()
pointerId = event.pointerId
originX = event.clientX
originY = event.clientY
x = 0
y = 0
activate(item)
item.dataset.dragging = ''
card.style.willChange = 'transform'
card.style.transform = IDENTITY
try {
item.setPointerCapture(pointerId)
} catch {
// Synthetic pointer events and older browsers may not expose capture; window listeners
// below still keep the gesture alive.
}
}
const onPointerMove = (event: PointerEvent) => {
if (event.pointerId !== pointerId) return
x = event.clientX - originX
y = event.clientY - originY
if (!frame) frame = requestAnimationFrame(paint)
}
const onPointerEnd = (event: PointerEvent) => {
if (event.pointerId !== pointerId) return
pointerId = undefined
if (frame) {
cancelAnimationFrame(frame)
frame = 0
card.style.transform = transform()
}
try {
if (item.hasPointerCapture(event.pointerId)) item.releasePointerCapture(event.pointerId)
} catch {
// See the capture fallback above.
}
if (reduced) {
settle()
return
}
const from = transform()
controls = animate(
card,
{ transform: [from, IDENTITY] },
{
type: 'spring',
stiffness: 420,
damping: 30,
mass: 0.7,
// Motion commits the final keyframe after calling onComplete. Clear that committed
// identity transform on the following frame so the card truly returns to authored CSS.
onComplete: () => {
settleFrame = requestAnimationFrame(() => {
settleFrame = 0
settle()
})
},
},
)
}
const onFocus = () => activate(item)
item.addEventListener('pointerdown', onPointerDown)
window.addEventListener('pointermove', onPointerMove)
window.addEventListener('pointerup', onPointerEnd)
window.addEventListener('pointercancel', onPointerEnd)
item.addEventListener('focusin', onFocus)
cleanups.push(() => {
item.removeEventListener('pointerdown', onPointerDown)
window.removeEventListener('pointermove', onPointerMove)
window.removeEventListener('pointerup', onPointerEnd)
window.removeEventListener('pointercancel', onPointerEnd)
item.removeEventListener('focusin', onFocus)
if (frame) cancelAnimationFrame(frame)
if (settleFrame) cancelAnimationFrame(settleFrame)
settle()
})
}
return () => {
for (const cleanup of cleanups) cleanup()
for (const item of items) item.style.zIndex = originalZ.get(item) ?? ''
}
}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 { PhotoPile } from '@/components/ui/kida/photo-pile'
const photos = [
{ id: 'garden', src: '/garden.jpg', alt: 'Flowers in the garden' },
{ id: 'coast', src: '/coast.jpg', alt: 'Sunset over the coast' },
{ id: 'pool', src: '/pool.jpg', alt: 'Striped float in a pool' },
]
export default function PhotoPileExample() {
return <PhotoPile photos={photos} />
}API
Props
| Prop | Type | Default | Description |
|---|---|---|---|
photos |
readonly PhotoPilePhoto[] |
required | Photos rendered in their initial stack order. |
spread |
number |
1 |
Multiplier for every photo’s resting x/y offset. |
dragScale |
number |
1.035 |
Scale applied while a photo is dragged. |
tilt |
number |
0.025 |
Responsive rotation in degrees per horizontal pixel. |
Each photo requires id, src, and alt. Add optional x, y, and rotation values to author
its resting position, or pass imageProps for ordinary image attributes. The root also accepts
fieldset attributes, className, style, event handlers, and a forwarded ref.
CSS custom properties
| Property | Default | Description |
|---|---|---|
--kida-photo-width |
clamp(9rem, 42%, 13.5rem) |
Width of every photo. |
--kida-photo-radius |
0.55rem |
Corner radius of the photo frame. |
--kida-photo-frame |
#fffafb |
Frame background. |
--kida-photo-shadow |
soft shadow | Resting shadow. |
--kida-photo-focus |
#6d52a8 |
Keyboard focus outline. |
Customization
Set x, y, and rotation on individual photos to author the resting composition, then use
spread to tighten or expand all offsets together. The --kida-photo-* properties control frame
size, color, radius, shadow, and focus treatment without changing drag behavior.
Accessibility and input behavior
The pile is a labeled fieldset and every photo is a button with useful alternative text. Pointer users can drag a photo and release it to spring home. Focusing or clicking a photo brings it to the front, so keyboard users can inspect the complete stack without needing a drag equivalent. The resting layout does not encode information.
Reduced motion keeps the pile static and removes both drag travel and spring movement. Images are also marked non-draggable so native browser image dragging cannot compete with the component.
Troubleshooting
Give the pile enough surrounding room for its absolutely positioned photos. If images look cropped, adjust their source composition or override
object-fiton[data-kida-photo-card] img.