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.
Supply your own image URLs in the photos array. 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/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.
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/photo-pile.svelte
<script lang="ts">
import './photo-pile.css'
import { photoPile } from './photo-pile.motion.js'
import { untrack } from 'svelte'
import type { PhotoPileProps } from './photo-pile.types.js'
let {
photos,
spread = 1,
dragScale,
tilt,
element = $bindable(null),
'aria-label': ariaLabel = 'Draggable photo pile',
...rest
}: PhotoPileProps = $props()
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
const root = $derived(element)
const restartKey = $derived(JSON.stringify([photos.map((photo) => photo.id), dragScale, tilt]))
const layout = $derived(
photos.map((photo, index) => {
const fallback = positions[index % positions.length] ?? positions[0]
return {
photo,
label: `Bring ${photo.alt || `Photo ${index + 1}`} to front and drag`,
x: `${(photo.x ?? fallback.x) * spread}px`,
y: `${(photo.y ?? fallback.y) * spread}px`,
rotation: `${photo.rotation ?? fallback.rotation}deg`,
layer: index + 1,
}
}),
)
$effect(() => {
const node = root
void restartKey
if (!node) return
return untrack(() => {
node.querySelectorAll<HTMLElement>('[data-kida-photo-item]').forEach((item, index) => {
item.style.zIndex = String(index + 1)
})
return photoPile(node, { dragScale, tilt })
})
})
</script>
<fieldset {...rest} bind:this={element} aria-label={ariaLabel} data-kida-photo-pile="">
<span data-kida-photo-stage="">
{#each layout as item (item.photo.id)}
<button
type="button"
aria-label={item.label}
data-kida-photo-item=""
style:--kida-photo-x={item.x}
style:--kida-photo-y={item.y}
style:--kida-photo-rotation={item.rotation}
style:z-index={item.layer}
>
<span data-kida-photo-card="">
<img {...item.photo.imageProps} src={item.photo.src} alt={item.photo.alt} draggable="false" />
</span>
</button>
{/each}
</span>
</fieldset>src/lib/components/ui/kida/photo-pile.types.ts
import type { PhotoPileOptions } from './photo-pile.motion.js';
import type { HTMLAttributes, HTMLImgAttributes } from 'svelte/elements';
type TextAttributes<T extends EventTarget> = Omit<HTMLAttributes<T>, 'children'>;
export interface PhotoPilePhoto {
id: string;
src: string;
alt: string;
x?: number;
y?: number;
rotation?: number;
imageProps?: Omit<HTMLImgAttributes, 'src' | 'alt' | 'draggable'>;
}
export interface PhotoPileProps extends PhotoPileOptions, TextAttributes<HTMLFieldSetElement> {
photos: readonly PhotoPilePhoto[];
spread?: number;
element?: HTMLFieldSetElement | null;
}src/lib/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/lib/components/ui/kida/photo-pile.motion.ts
import { animate } from 'motion'
import { prefersReducedMotion } from './reduced-motion.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/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 PhotoPile from '$lib/components/ui/kida/photo-pile.svelte'
import type { PhotoPilePhoto } from '$lib/components/ui/kida/photo-pile.types.js'
const photos: readonly PhotoPilePhoto[] = [
{ 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' },
]
</script>
<PhotoPile {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. |
element |
HTMLFieldSetElement | null |
null |
Use bind:element to read the root DOM element. |
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, class, style, and event handlers.
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.