DocumentationPhotoPile

PhotoPile

Layers draggable photos that spring back into a playful composition.

Svelte

Shared live previews stay running while you switch code examples and API documentation.

Draggable snapshots

Supply your own image URLs in the photos array.. Native attributes use Vue spelling, and component refs expose element.

Quick start

Add to your project

Copy the component and everything it needs into your Vue 3.5+ project.

RecommendedUse the shadcn-vue CLI
npx shadcn-vue@2.8.2 add https://kida-ui.onrender.com/r/vue/photo-pile.json

Run 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.

View registry JSON
Copy manually5 files

1. Install runtime dependencies

npm install motion@^13.1.0

2. Create the source files

Keep this directory structure so the component's relative imports continue to work.

src/components/ui/kida/photo-pile.vue
<script setup lang="ts">
import './photo-pile.css'
import { photoPile } from './photo-pile.motion.js'
import { shallowRef, watch } from 'vue'
import type { PhotoPilePhoto, PhotoPileProps } from './photo-pile.types.js'

defineOptions({ name: 'KidaPhotoPile', inheritAttrs: false })
const props = defineProps<PhotoPileProps>()
const element = shallowRef<HTMLFieldSetElement | null>(null)
const items = new Map<string, HTMLButtonElement>()
defineExpose({ element })
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

watch(
  [
    () => element.value,
    () => JSON.stringify(props.photos.map((photo) => photo.id)),
    () => props.dragScale,
    () => props.tilt,
  ],
  (_, __, onCleanup) => {
    const node = element.value
    if (!node) return
    // Collection changes end the previous gesture and reset layering in the new DOM order.
    node.querySelectorAll<HTMLElement>('[data-kida-photo-item]').forEach((item, index) => {
      item.style.zIndex = String(index + 1)
    })
    onCleanup(photoPile(node, { ...props }))
  },
  { flush: 'post' },
)

function setItem(id: string, node: unknown) {
  if (node) items.set(id, node as HTMLButtonElement)
  else items.delete(id)
}

function itemStyle(photo: PhotoPilePhoto, index: number) {
  const fallback = positions[index % positions.length] ?? positions[0]
  return {
    '--kida-photo-x': `${(photo.x ?? fallback.x) * (props.spread ?? 1)}px`,
    '--kida-photo-y': `${(photo.y ?? fallback.y) * (props.spread ?? 1)}px`,
    '--kida-photo-rotation': `${photo.rotation ?? fallback.rotation}deg`,
    zIndex: items.get(photo.id)?.style.zIndex ?? index + 1,
  }
}
</script>

<template>
  <fieldset v-bind="$attrs" ref="element" :aria-label="($attrs['aria-label'] as string | undefined) ?? 'Draggable photo pile'" data-kida-photo-pile="">
    <span data-kida-photo-stage="">
      <button v-for="(photo, index) in props.photos" :key="photo.id" :ref="(node) => setItem(photo.id, node)" type="button" :aria-label="`Bring ${photo.alt || `Photo ${index + 1}`} to front and drag`" data-kida-photo-item="" :style="itemStyle(photo, index)">
        <span data-kida-photo-card="">
          <img v-bind="photo.imageProps" :src="photo.src" :alt="photo.alt" :draggable="false" />
        </span>
      </button>
    </span>
  </fieldset>
</template>
src/components/ui/kida/photo-pile.types.ts
import type { PhotoPileOptions } from './photo-pile.motion.js';

import type { ImgHTMLAttributes } from 'vue';

export interface PhotoPilePhoto {
    /** Unique, stable key for this photo. */
    id: string;
    src: string;
    alt: string;
    x?: number;
    y?: number;
    rotation?: number;
    imageProps?: Omit<ImgHTMLAttributes, 'src' | 'alt' | 'draggable'>;
}

export interface PhotoPileProps extends PhotoPileOptions {
    photos: readonly PhotoPilePhoto[];
    /** Multiplies default and authored x/y offsets. @default 1 */
    spread?: number;
}

/** Vue component refs expose the root DOM element, null when presence removes it. */
export interface KidaElement {
    element: HTMLElement | null;
}
src/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/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/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 setup lang="ts">
import type { PhotoPilePhoto } from '@/components/ui/kida/photo-pile.types'
import PhotoPile from '@/components/ui/kida/photo-pile.vue'

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>

<template>
  <PhotoPile :photos="photos" />
</template>

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, class, style, event handlers, and a component ref exposing element.

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-fit on [data-kida-photo-card] img.