{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "gallery-scatter",
  "type": "registry:component",
  "title": "Gallery Scatter",
  "description": "Polaroid-style prints lie scattered at loose angles. Drag any of them to the top of the pile, or tidy the whole table into a neat grid.",
  "author": "Hyperblur <hello@hyperblur.dev>",
  "dependencies": [],
  "registryDependencies": [],
  "categories": [
    "components",
    "gallery",
    "polaroid",
    "drag",
    "photos",
    "grid",
    "playful"
  ],
  "docs": "https://hyperblur.dev/effects/gallery-scatter",
  "files": [
    {
      "path": "registry/hyperblur/gallery-scatter.tsx",
      "type": "registry:component",
      "target": "components/hyperblur/gallery-scatter.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface ScatterImage {\n  src?: string;\n  title: string;\n  caption?: string;\n}\n\nexport interface GalleryScatterProps\n  extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  images?: ScatterImage[];\n  onChange?: (index: number) => void;\n  tidy?: boolean;\n  defaultTidy?: boolean;\n  onTidyChange?: (tidy: boolean) => void;\n  autoPlay?: boolean;\n  interval?: number;\n  accent?: string;\n  height?: number | string;\n}\n\ntype Scene = {\n  title: string;\n  caption: string;\n  sky: [string, string, string];\n  sun: string;\n  hills: [string, string, string];\n};\n\nconst scenes: Scene[] = [\n  { title: \"Dune Sunrise\", caption: \"Erg Chebbi, 6:12 am\", sky: [\"#ffd08a\", \"#ff7a59\", \"#5b2a6e\"], sun: \"#fff1c9\", hills: [\"#c4573f\", \"#7d2e45\", \"#3a1631\"] },\n  { title: \"Harbor Lights\", caption: \"Lisbon waterfront\", sky: [\"#0d1640\", \"#2c3f9c\", \"#7aa7ff\"], sun: \"#e8f0ff\", hills: [\"#2a3a8a\", \"#18205a\", \"#0a0e2c\"] },\n  { title: \"Glacier Lake\", caption: \"Moraine Lake, Alberta\", sky: [\"#d6fbf6\", \"#5fcfcf\", \"#0e5a74\"], sun: \"#ffffff\", hills: [\"#3e8fa0\", \"#1f5f73\", \"#0b2f40\"] },\n  { title: \"Neon Alley\", caption: \"Shinjuku, 1:40 am\", sky: [\"#2a0b3f\", \"#8a1f7a\", \"#ff4fa3\"], sun: \"#ffd1ec\", hills: [\"#5a1460\", \"#33093f\", \"#16041f\"] },\n  { title: \"Pine Ridge\", caption: \"Olympic Peninsula\", sky: [\"#eef4d8\", \"#97c27a\", \"#28563a\"], sun: \"#fffbe6\", hills: [\"#4f8a52\", \"#2c5c3a\", \"#123222\"] },\n  { title: \"Coral Hour\", caption: \"Big Sur coastline\", sky: [\"#ffe6d6\", \"#ff9f8a\", \"#c2457a\"], sun: \"#fff4e8\", hills: [\"#d0627a\", \"#8e2f5c\", \"#46163a\"] },\n];\n\nfunction mod(n: number, m: number) {\n  return ((n % m) + m) % m;\n}\n\nfunction hash(n: number) {\n  let x = Math.imul(n + 1, 2654435761) >>> 0;\n  x = Math.imul(x ^ (x >>> 15), 2246822519) >>> 0;\n  x = Math.imul(x ^ (x >>> 13), 3266489917) >>> 0;\n  return (x ^ (x >>> 16)) >>> 0;\n}\n\nconst sceneCache = new Map<number, string>();\n\nfunction sceneUri(i: number) {\n  const k = mod(i, scenes.length);\n  const hit = sceneCache.get(k);\n  if (hit) return hit;\n  const sc = scenes[k];\n  let s = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 320 200\" preserveAspectRatio=\"xMidYMid slice\"><defs><linearGradient id=\"s\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"${sc.sky[0]}\"/><stop offset=\"0.55\" stop-color=\"${sc.sky[1]}\"/><stop offset=\"1\" stop-color=\"${sc.sky[2]}\"/></linearGradient></defs><rect width=\"320\" height=\"200\" fill=\"url(#s)\"/>`;\n  const sx = 60 + (hash(k * 13) % 200);\n  const sy = 40 + (hash(k * 17) % 40);\n  s += `<circle cx=\"${sx}\" cy=\"${sy}\" r=\"34\" fill=\"${sc.sun}\" opacity=\"0.18\"/><circle cx=\"${sx}\" cy=\"${sy}\" r=\"18\" fill=\"${sc.sun}\" opacity=\"0.9\"/>`;\n  for (let l = 0; l < 3; l += 1) {\n    const base = 112 + l * 30;\n    const amp = 34 - l * 8;\n    let d = `M0 200 L0 ${base - (hash(k * 41 + l * 7) % amp)}`;\n    for (let j = 1; j <= 8; j += 1) {\n      d += ` L${j * 40} ${base - (hash(k * 41 + l * 7 + j * 3) % amp)}`;\n    }\n    s += `<path d=\"${d} L320 200Z\" fill=\"${sc.hills[l]}\"/>`;\n  }\n  s += \"</svg>\";\n  const uri = `data:image/svg+xml,${encodeURIComponent(s)}`;\n  sceneCache.set(k, uri);\n  return uri;\n}\n\nconst defaults: ScatterImage[] = scenes.map((s) => ({ title: s.title, caption: s.caption }));\n\nfunction imageUrl(list: ScatterImage[], i: number) {\n  const item = list[i];\n  return item?.src ? `url(${JSON.stringify(item.src)})` : `url(\"${sceneUri(i)}\")`;\n}\n\nconst motionQuery = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeMotion(callback: () => void) {\n  const query = window.matchMedia(motionQuery);\n  query.addEventListener(\"change\", callback);\n  return () => query.removeEventListener(\"change\", callback);\n}\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    subscribeMotion,\n    () => window.matchMedia(motionQuery).matches,\n    () => false,\n  );\n}\n\nfunction useInView(ref: React.RefObject<HTMLElement | null>) {\n  const [visible, setVisible] = React.useState(true);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || typeof IntersectionObserver === \"undefined\") return;\n    const observer = new IntersectionObserver((entries) => {\n      const last = entries[entries.length - 1];\n      if (last) setVisible(last.isIntersecting);\n    });\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [ref]);\n  return visible;\n}\n\ntype Spot = { x: number; y: number; r: number };\n\ntype Layout = { order: number[]; mode: boolean; pos: (Spot | null)[]; cycle: number };\n\nfunction clamp(v: number, a: number, b: number) {\n  return Math.max(a, Math.min(b, v));\n}\n\nfunction scatterSpot(i: number, n: number, seed = 0): Spot {\n  const h1 = hash(i * 31 + seed * 977 + 5);\n  const h2 = hash(i * 17 + seed * 613 + 11);\n  const h3 = hash(i * 53 + seed * 389 + 23);\n  const jx = ((h1 % 1000) / 1000 - 0.5) * 0.1;\n  const jy = ((h2 % 1000) / 1000 - 0.5) * 0.16;\n  return {\n    x: clamp(0.14 + ((i + 0.5) / n) * 0.72 + jx, 0.12, 0.88),\n    y: clamp((i % 2 === 0 ? 0.37 : 0.58) + jy, 0.26, 0.66),\n    r: Number((((h3 % 1000) / 1000 - 0.5) * 26).toFixed(2)),\n  };\n}\n\nfunction tidySpot(i: number, n: number, aspect: number): Spot {\n  const cols = clamp(Math.round(Math.sqrt(n * aspect * 0.75)), 1, n);\n  const rows = Math.ceil(n / cols);\n  const c = i % cols;\n  const r = Math.floor(i / cols);\n  const inRow = r === rows - 1 ? n - cols * (rows - 1) : cols;\n  const shift = (cols - inRow) / 2;\n  return {\n    x: 0.07 + ((c + shift + 0.5) / cols) * 0.86,\n    y: 0.05 + ((r + 0.5) / rows) * 0.72,\n    r: 0,\n  };\n}\n\nconst css = `\n.hb-zx4 {\n  --hb-zx4-a: #2f7bff;\n  position: relative;\n  box-sizing: border-box;\n  width: 100%;\n  overflow: hidden;\n  container-type: size;\n  border: 1px solid #232323;\n  border-radius: 14px;\n  background:\n    radial-gradient(circle at 1px 1px, rgba(255,255,255,0.07) 1px, transparent 1.4px) 0 0 / 16px 16px,\n    radial-gradient(120% 90% at 30% 10%, #191a1d 0%, #0c0c0d 70%);\n  color: #ededed;\n  font-family: inherit;\n  user-select: none;\n  -webkit-user-select: none;\n  -webkit-tap-highlight-color: transparent;\n  isolation: isolate;\n}\n.hb-zx4 *, .hb-zx4 *::before, .hb-zx4 *::after { box-sizing: border-box; }\n.hb-zx4-print {\n  --hb-zx4-w: min(26cqw, 38cqh);\n  position: absolute;\n  width: var(--hb-zx4-w);\n  margin: 0;\n  padding: calc(var(--hb-zx4-w) * 0.06) calc(var(--hb-zx4-w) * 0.06) 0;\n  border: 0;\n  border-radius: 2px;\n  background: #f4f1ea;\n  color: #2b2b2b;\n  font: inherit;\n  text-align: left;\n  cursor: grab;\n  touch-action: none;\n  box-shadow: 0 6px 14px rgba(0,0,0,0.45), 0 1px 2px rgba(0,0,0,0.35);\n  transition: left 0.75s cubic-bezier(0.22, 0.8, 0.24, 1), top 0.75s cubic-bezier(0.22, 0.8, 0.24, 1), transform 0.75s cubic-bezier(0.22, 0.8, 0.24, 1), box-shadow 0.3s ease;\n  transition-delay: var(--hb-zx4-d, 0s);\n  -webkit-tap-highlight-color: transparent;\n}\n.hb-zx4-print:hover { box-shadow: 0 10px 22px rgba(0,0,0,0.5), 0 1px 2px rgba(0,0,0,0.35); }\n.hb-zx4-print:focus-visible { outline: 2px solid var(--hb-zx4-a); outline-offset: 3px; }\n.hb-zx4-print[data-lift=\"true\"] {\n  cursor: grabbing;\n  transition: transform 0.25s ease, box-shadow 0.25s ease;\n  box-shadow: 0 22px 40px rgba(0,0,0,0.6), 0 4px 10px rgba(0,0,0,0.4);\n}\n.hb-zx4-img {\n  display: block;\n  width: 100%;\n  aspect-ratio: 1 / 1;\n  background-size: cover;\n  background-position: center;\n  box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08);\n  pointer-events: none;\n}\n.hb-zx4-label {\n  display: block;\n  padding: calc(var(--hb-zx4-w) * 0.05) 1px calc(var(--hb-zx4-w) * 0.07);\n  font-size: calc(var(--hb-zx4-w) * 0.105);\n  font-weight: 600;\n  line-height: 1.15;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  pointer-events: none;\n}\n.hb-zx4-tape {\n  position: absolute;\n  left: 50%;\n  top: calc(var(--hb-zx4-w) * -0.05);\n  width: calc(var(--hb-zx4-w) * 0.34);\n  height: calc(var(--hb-zx4-w) * 0.1);\n  transform: translateX(-50%) rotate(-3deg);\n  background: rgba(240, 232, 200, 0.55);\n  box-shadow: 0 1px 2px rgba(0,0,0,0.15);\n  pointer-events: none;\n}\n.hb-zx4-tidy {\n  position: absolute;\n  right: 8px;\n  bottom: 8px;\n  z-index: 1000;\n  display: inline-flex;\n  align-items: center;\n  gap: 6px;\n  height: 26px;\n  margin: 0;\n  padding: 0 10px 0 8px;\n  border: 1px solid rgba(255,255,255,0.12);\n  border-radius: 999px;\n  background: rgba(16,16,16,0.82);\n  -webkit-backdrop-filter: blur(6px);\n  backdrop-filter: blur(6px);\n  color: #ededed;\n  font: inherit;\n  font-size: 11px;\n  font-weight: 500;\n  cursor: pointer;\n  transition: background 0.2s ease, border-color 0.2s ease, transform 0.15s ease;\n}\n.hb-zx4-tidy:hover { background: rgba(28,28,28,0.9); border-color: rgba(255,255,255,0.2); }\n.hb-zx4-tidy:active { transform: scale(0.96); }\n.hb-zx4-tidy:focus-visible { outline: 2px solid var(--hb-zx4-a); outline-offset: 2px; }\n.hb-zx4-tidy svg { color: var(--hb-zx4-a); }\n@media (prefers-reduced-motion: reduce) {\n  .hb-zx4-print, .hb-zx4-print[data-lift=\"true\"], .hb-zx4-tidy { transition: none; }\n}\n`;\n\nexport function GalleryScatter({\n  images,\n  onChange,\n  tidy,\n  defaultTidy = false,\n  onTidyChange,\n  autoPlay = true,\n  interval = 3200,\n  accent = \"#2f7bff\",\n  height,\n  className,\n  style,\n  onPointerEnter,\n  onPointerLeave,\n  onFocus,\n  onBlur,\n  ...rest\n}: GalleryScatterProps) {\n  const list = images && images.length > 0 ? images : defaults;\n  const n = list.length;\n  const controlled = tidy !== undefined;\n  const [innerTidy, setInnerTidy] = React.useState(defaultTidy);\n  const isTidy = controlled ? tidy : innerTidy;\n  const [layout, setLayout] = React.useState<Layout>(() => ({\n    order: list.map((_, i) => i),\n    mode: defaultTidy,\n    pos: [],\n    cycle: 0,\n  }));\n  const [aspect, setAspect] = React.useState(16 / 9);\n  const [lift, setLift] = React.useState<number | null>(null);\n  const [paused, setPaused] = React.useState(false);\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const dragRef = React.useRef<null | { id: number; i: number; sx: number; sy: number; start: Spot; w: number; h: number; moved: boolean }>(null);\n  const reduced = useReducedMotion();\n  const visible = useInView(rootRef);\n\n  const spot = (i: number): Spot => {\n    const custom = layout.mode === isTidy ? layout.pos[i] : null;\n    if (custom) return custom;\n    return isTidy ? tidySpot(i, n, aspect) : scatterSpot(i, n);\n  };\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el || typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver(() => {\n      if (el.clientHeight > 0) setAspect(el.clientWidth / el.clientHeight);\n    });\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  React.useEffect(() => {\n    if (!autoPlay || reduced || !visible || paused || isTidy || lift !== null || n < 2) return;\n    const id = window.setInterval(() => {\n      setLayout((prev) => {\n        const order = prev.order.filter((i) => i < n);\n        for (let i = 0; i < n; i += 1) if (!order.includes(i)) order.unshift(i);\n        const pick = order[0];\n        const cycle = prev.cycle + 1;\n        const pos = prev.mode === false ? prev.pos.slice() : [];\n        pos[pick] = scatterSpot(pick, n, cycle);\n        return { order: [...order.slice(1), pick], mode: false, pos, cycle };\n      });\n    }, interval);\n    return () => window.clearInterval(id);\n  }, [autoPlay, reduced, visible, paused, isTidy, lift, n, interval]);\n\n  const toFront = (i: number) => {\n    setLayout((prev) => {\n      const order = prev.order.filter((k) => k !== i && k < n);\n      for (let k = 0; k < n; k += 1) if (k !== i && !order.includes(k)) order.unshift(k);\n      return { ...prev, order: [...order, i] };\n    });\n  };\n\n  const place = (i: number, s: Spot) => {\n    setLayout((prev) => {\n      const pos = prev.mode === isTidy ? prev.pos.slice() : [];\n      pos[i] = s;\n      return { ...prev, mode: isTidy, pos };\n    });\n  };\n\n  const toggleTidy = () => {\n    const next = !isTidy;\n    if (!controlled) setInnerTidy(next);\n    setLayout((prev) => ({ ...prev, mode: next, pos: [] }));\n    onTidyChange?.(next);\n  };\n\n  const down = (e: React.PointerEvent<HTMLButtonElement>, i: number) => {\n    if (e.button !== 0) return;\n    const root = rootRef.current;\n    if (!root) return;\n    e.currentTarget.setPointerCapture(e.pointerId);\n    dragRef.current = {\n      id: e.pointerId,\n      i,\n      sx: e.clientX,\n      sy: e.clientY,\n      start: spot(i),\n      w: root.clientWidth,\n      h: root.clientHeight,\n      moved: false,\n    };\n    setLift(i);\n    toFront(i);\n  };\n\n  const move = (e: React.PointerEvent<HTMLButtonElement>) => {\n    const d = dragRef.current;\n    if (!d || d.id !== e.pointerId) return;\n    const dx = e.clientX - d.sx;\n    const dy = e.clientY - d.sy;\n    if (!d.moved && Math.hypot(dx, dy) > 3) d.moved = true;\n    if (!d.moved) return;\n    place(d.i, {\n      x: clamp(d.start.x + dx / d.w, 0.05, 0.95),\n      y: clamp(d.start.y + dy / d.h, 0.08, 0.92),\n      r: d.start.r,\n    });\n  };\n\n  const up = (e: React.PointerEvent<HTMLButtonElement>) => {\n    const d = dragRef.current;\n    if (!d || d.id !== e.pointerId) return;\n    dragRef.current = null;\n    setLift(null);\n    onChange?.(d.i);\n  };\n\n  const key = (e: React.KeyboardEvent<HTMLButtonElement>, i: number) => {\n    const stepSize = e.shiftKey ? 0.08 : 0.03;\n    let dx = 0;\n    let dy = 0;\n    if (e.key === \"ArrowLeft\") dx = -stepSize;\n    else if (e.key === \"ArrowRight\") dx = stepSize;\n    else if (e.key === \"ArrowUp\") dy = -stepSize;\n    else if (e.key === \"ArrowDown\") dy = stepSize;\n    else if (e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault();\n      toFront(i);\n      onChange?.(i);\n      return;\n    } else return;\n    e.preventDefault();\n    const s = spot(i);\n    toFront(i);\n    place(i, { x: clamp(s.x + dx, 0.05, 0.95), y: clamp(s.y + dy, 0.08, 0.92), r: s.r });\n  };\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"region\"\n      aria-label=\"Scattered prints\"\n      className={className ? `hb-zx4 ${className}` : \"hb-zx4\"}\n      style={{\n        ...(height !== undefined ? { height } : { aspectRatio: \"16 / 10\" }),\n        [\"--hb-zx4-a\" as string]: accent,\n        ...style,\n      }}\n      onPointerEnter={(e) => {\n        setPaused(true);\n        onPointerEnter?.(e);\n      }}\n      onPointerLeave={(e) => {\n        setPaused(false);\n        onPointerLeave?.(e);\n      }}\n      onFocus={(e) => {\n        if (e.target.matches(\":focus-visible\")) setPaused(true);\n        onFocus?.(e);\n      }}\n      onBlur={(e) => {\n        if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setPaused(false);\n        onBlur?.(e);\n      }}\n      {...rest}\n    >\n      <style href=\"hb-gallery-scatter\" precedence=\"default\">\n        {css}\n      </style>\n      {list.map((item, i) => {\n        const s = spot(i);\n        const z = layout.order.indexOf(i) + 1;\n        const lifted = lift === i;\n        return (\n          <button\n            key={i}\n            type=\"button\"\n            className=\"hb-zx4-print\"\n            data-lift={lifted}\n            aria-label={`${item.title}${item.caption ? `, ${item.caption}` : \"\"}. Arrow keys move it.`}\n            style={{\n              left: `${(s.x * 100).toFixed(2)}%`,\n              top: `${(s.y * 100).toFixed(2)}%`,\n              zIndex: lifted ? 999 : z,\n              transform: `translate(-50%, -50%) rotate(${(lifted ? s.r * 0.4 : s.r).toFixed(2)}deg) scale(${lifted ? 1.07 : 1})`,\n              [\"--hb-zx4-d\" as string]: `${(i * 0.04).toFixed(2)}s`,\n            }}\n            onPointerDown={(e) => down(e, i)}\n            onPointerMove={move}\n            onPointerUp={up}\n            onPointerCancel={up}\n            onKeyDown={(e) => key(e, i)}\n          >\n            <span className=\"hb-zx4-tape\" />\n            <span className=\"hb-zx4-img\" style={{ backgroundImage: imageUrl(list, i) }} />\n            <span className=\"hb-zx4-label\">{item.title}</span>\n          </button>\n        );\n      })}\n      <button type=\"button\" className=\"hb-zx4-tidy\" aria-pressed={isTidy} onClick={toggleTidy}>\n        {isTidy ? (\n          <svg width=\"13\" height=\"13\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n            <rect x=\"4\" y=\"6\" width=\"9\" height=\"11\" rx=\"1\" transform=\"rotate(-10 8.5 11.5)\" />\n            <rect x=\"11\" y=\"7\" width=\"9\" height=\"11\" rx=\"1\" transform=\"rotate(8 15.5 12.5)\" />\n          </svg>\n        ) : (\n          <svg width=\"13\" height=\"13\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n            <rect x=\"4\" y=\"4\" width=\"7\" height=\"7\" rx=\"1.5\" />\n            <rect x=\"13\" y=\"4\" width=\"7\" height=\"7\" rx=\"1.5\" />\n            <rect x=\"4\" y=\"13\" width=\"7\" height=\"7\" rx=\"1.5\" />\n            <rect x=\"13\" y=\"13\" width=\"7\" height=\"7\" rx=\"1.5\" />\n          </svg>\n        )}\n        {isTidy ? \"Scatter\" : \"Tidy up\"}\n      </button>\n    </div>\n  );\n}\n\nexport default GalleryScatter;\n"
    }
  ]
}