{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "masonry-photo-gallery",
  "title": "Masonry Photo Gallery",
  "description": "A masonry photo gallery with category tabs under a sliding hairline, photos that glide to their new columns when filtered, hover focus that dims the rest, scroll-in reveals and a captioned keyboard lightbox.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/masonry-photo-gallery/masonry-photo-gallery.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport interface MasonryPhoto {\n  src: string;\n  alt?: string;\n  title?: string;\n  category?: string;\n  /** Width / height. Measured from the image when left out. */\n  ratio?: number;\n}\n\nexport type MasonryPhotoGalleryTheme = \"dark\" | \"light\";\n\nexport interface MasonryPhotoGalleryProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  photos?: MasonryPhoto[];\n  theme?: MasonryPhotoGalleryTheme;\n  /** Columns are as many of this width as fit, capped by maxColumns. */\n  minColumnWidth?: number;\n  maxColumns?: number;\n  gap?: number;\n  borderRadius?: number;\n  /** Category tabs built from the photos' categories. */\n  showFilters?: boolean;\n  allLabel?: string;\n  /** Opacity of the other photos while one is hovered. */\n  dimOpacity?: number;\n  /** Fade photos up as they scroll into view. */\n  reveal?: boolean;\n  enableLightbox?: boolean;\n}\n\nconst PALETTES = {\n  dark: {\n    background: \"#080808\",\n    text: \"rgba(255,255,255,0.9)\",\n    muted: \"rgba(255,255,255,0.42)\",\n    faint: \"rgba(255,255,255,0.12)\",\n    line: \"#FFFFFF\",\n    tile: \"#121212\",\n    caption: \"linear-gradient(to top, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0) 100%)\",\n    focus: \"rgba(255,255,255,0.9)\",\n    lightboxBackground: \"rgba(8,8,8,0.95)\",\n    controlColor: \"rgba(255,255,255,0.8)\",\n    emptyText: \"rgba(255,255,255,0.4)\",\n    emptyBorder: \"1.5px dashed rgba(255,255,255,0.15)\",\n  },\n  light: {\n    background: \"#F5F5F3\",\n    text: \"rgba(0,0,0,0.85)\",\n    muted: \"rgba(0,0,0,0.42)\",\n    faint: \"rgba(0,0,0,0.1)\",\n    line: \"#000000\",\n    tile: \"#E9E9E6\",\n    caption: \"linear-gradient(to top, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%)\",\n    focus: \"rgba(0,0,0,0.85)\",\n    lightboxBackground: \"rgba(255,255,255,0.96)\",\n    controlColor: \"rgba(0,0,0,0.75)\",\n    emptyText: \"rgba(0,0,0,0.4)\",\n    emptyBorder: \"1.5px dashed rgba(0,0,0,0.15)\",\n  },\n} as const;\n\nconst DEFAULT_PHOTOS: MasonryPhoto[] = [\n  { src: \"/demo/3.webp\", title: \"Curtains, late spring\", category: \"Interiors\", ratio: 0.8 },\n  { src: \"/demo/35.webp\", title: \"Wind study\", category: \"Portraits\", ratio: 1 },\n  { src: \"/demo/26.webp\", title: \"Breakaway\", category: \"Motion\", ratio: 1.25 },\n  { src: \"/demo/9.webp\", title: \"Bath, before guests\", category: \"Interiors\", ratio: 1 },\n  { src: \"/demo/42.webp\", title: \"Kenji, studio\", category: \"Portraits\", ratio: 0.75 },\n  { src: \"/demo/29.webp\", title: \"First stride\", category: \"Motion\", ratio: 0.8 },\n  { src: \"/demo/2.webp\", title: \"Dining room, noon\", category: \"Interiors\", ratio: 1.35 },\n  { src: \"/demo/36.webp\", title: \"Grey hour\", category: \"Portraits\", ratio: 0.8 },\n  { src: \"/demo/31.webp\", title: \"Into the bend\", category: \"Motion\", ratio: 1 },\n  { src: \"/demo/7.webp\", title: \"Pale stairwell\", category: \"Interiors\", ratio: 0.75 },\n  { src: \"/demo/44.webp\", title: \"Copper light\", category: \"Portraits\", ratio: 1.25 },\n  { src: \"/demo/23.webp\", title: \"Climb\", category: \"Motion\", ratio: 0.8 },\n  { src: \"/demo/20.webp\", title: \"Last evening\", category: \"Interiors\", ratio: 1.25 },\n  { src: \"/demo/1a.webp\", title: \"Office hours\", category: \"Portraits\", ratio: 1 },\n  { src: \"/demo/33.webp\", title: \"Open water\", category: \"Motion\", ratio: 1.5 },\n  { src: \"/demo/5.webp\", title: \"Reading corner\", category: \"Interiors\", ratio: 0.8 },\n];\n\nconst ASSUMED_WIDTH = 1040;\n\ninterface Placed {\n  x: number;\n  y: number;\n  w: number;\n  h: number;\n}\n\n/** Shortest-column placement, in order. */\nfunction layout(indices: number[], ratios: number[], width: number, minColumnWidth: number, maxColumns: number, gap: number) {\n  const columns = Math.max(1, Math.min(maxColumns, Math.floor((width + gap) / (minColumnWidth + gap))));\n  const colW = (width - gap * (columns - 1)) / columns;\n  const heights = new Array<number>(columns).fill(0);\n  const placed = new Map<number, Placed>();\n  for (const i of indices) {\n    let col = 0;\n    for (let c = 1; c < columns; c++) if (heights[c] < heights[col] - 0.5) col = c;\n    const h = Math.round(colW / (ratios[i] || 1));\n    placed.set(i, { x: Math.round(col * (colW + gap)), y: heights[col], w: Math.round(colW), h });\n    heights[col] += h + gap;\n  }\n  return { placed, height: Math.max(0, Math.max(...heights) - gap), columns };\n}\n\nexport function MasonryPhotoGallery({\n  photos = DEFAULT_PHOTOS,\n  theme = \"dark\",\n  minColumnWidth = 160,\n  maxColumns = 4,\n  gap = 10,\n  borderRadius = 3,\n  showFilters = true,\n  allLabel = \"All\",\n  dimOpacity = 0.4,\n  reveal = true,\n  enableLightbox = true,\n  className,\n  ...props\n}: MasonryPhotoGalleryProps) {\n  const palette = PALETTES[theme];\n  const gridRef = React.useRef<HTMLDivElement>(null);\n  const itemRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const tabRefs = React.useRef<(HTMLButtonElement | null)[]>([]);\n\n  const [width, setWidth] = React.useState<number | null>(null);\n  const [measured, setMeasured] = React.useState<Record<number, number>>({});\n  const [filter, setFilter] = React.useState<string | null>(null);\n  const [hovered, setHovered] = React.useState<number | null>(null);\n  const [shown, setShown] = React.useState<Set<number>>(() => new Set());\n  const [animate, setAnimate] = React.useState(false);\n  const [underline, setUnderline] = React.useState<{ left: number; width: number } | null>(null);\n  const [lightbox, setLightbox] = React.useState<number | null>(null);\n  const dialogRef = React.useRef<HTMLDivElement>(null);\n  const closeButtonRef = React.useRef<HTMLButtonElement>(null);\n  const lastFocusedRef = React.useRef<HTMLElement | null>(null);\n\n  const categories = React.useMemo(() => {\n    const seen: string[] = [];\n    for (const p of photos) if (p.category && !seen.includes(p.category)) seen.push(p.category);\n    return seen;\n  }, [photos]);\n\n  const ratios = React.useMemo(() => photos.map((p, i) => p.ratio ?? measured[i] ?? 1), [photos, measured]);\n  const visible = React.useMemo(() => photos.map((_, i) => i).filter((i) => !filter || photos[i].category === filter), [photos, filter]);\n  const { placed, height } = React.useMemo(() => layout(visible, ratios, width ?? ASSUMED_WIDTH, minColumnWidth, maxColumns, gap), [visible, ratios, width, minColumnWidth, maxColumns, gap]);\n  // Filtered-out photos fade where they'd sit in the unfiltered grid.\n  const home = React.useMemo(() => layout(photos.map((_, i) => i), ratios, width ?? ASSUMED_WIDTH, minColumnWidth, maxColumns, gap).placed, [photos, ratios, width, minColumnWidth, maxColumns, gap]);\n  const ready = width !== null;\n\n  // Track the grid's width; positions only animate once the first real layout has landed.\n  React.useEffect(() => {\n    const el = gridRef.current;\n    if (!el) return;\n    const update = () => setWidth(el.clientWidth);\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(el);\n    const id = requestAnimationFrame(() => requestAnimationFrame(() => setAnimate(true)));\n    return () => {\n      observer.disconnect();\n      cancelAnimationFrame(id);\n    };\n  }, []);\n\n  // Reveal each photo the first time it scrolls into view, in a short stagger.\n  React.useEffect(() => {\n    if (!reveal || !ready) return;\n    let timer: ReturnType<typeof setTimeout> | null = null;\n    const queue: number[] = [];\n    const flush = () => {\n      timer = null;\n      const batch = queue.splice(0, 1);\n      if (batch.length) setShown((prev) => new Set([...prev, ...batch]));\n      if (queue.length) timer = setTimeout(flush, 55);\n    };\n    const observer = new IntersectionObserver(\n      (entries) => {\n        const hits = entries.filter((e) => e.isIntersecting).map((e) => Number((e.target as HTMLElement).dataset.index));\n        hits.sort((a, b) => a - b);\n        for (const i of hits) {\n          observer.unobserve(itemRefs.current[i]!);\n          queue.push(i);\n        }\n        if (queue.length && timer === null) flush();\n      },\n      { rootMargin: \"0px 0px -8% 0px\" },\n    );\n    itemRefs.current.forEach((el) => el && observer.observe(el));\n    return () => {\n      observer.disconnect();\n      if (timer) clearTimeout(timer);\n    };\n  }, [reveal, ready, photos.length]);\n\n  // Sliding 1px underline under the active filter.\n  React.useLayoutEffect(() => {\n    const at = filter === null ? 0 : categories.indexOf(filter) + 1;\n    const el = tabRefs.current[at];\n    if (el) setUnderline({ left: el.offsetLeft, width: el.offsetWidth });\n  }, [filter, categories, width]);\n\n  React.useEffect(() => {\n    if (lightbox === null) {\n      lastFocusedRef.current?.focus();\n      lastFocusedRef.current = null;\n      return;\n    }\n    lastFocusedRef.current = document.activeElement as HTMLElement | null;\n    closeButtonRef.current?.focus();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [lightbox !== null]);\n\n  const step = React.useCallback(\n    (dir: 1 | -1) =>\n      setLightbox((cur) => {\n        if (cur === null) return null;\n        const at = visible.indexOf(cur);\n        return visible[(at + dir + visible.length) % visible.length];\n      }),\n    [visible],\n  );\n\n  React.useEffect(() => {\n    if (lightbox === null) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") setLightbox(null);\n      else if (e.key === \"ArrowRight\") step(1);\n      else if (e.key === \"ArrowLeft\") step(-1);\n      else if (e.key === \"Tab\") {\n        const focusables = Array.from(dialogRef.current?.querySelectorAll<HTMLElement>(\"button\") ?? []);\n        if (focusables.length === 0) return;\n        const first = focusables[0];\n        const last = focusables[focusables.length - 1];\n        if (e.shiftKey && document.activeElement === first) {\n          e.preventDefault();\n          last.focus();\n        } else if (!e.shiftKey && document.activeElement === last) {\n          e.preventDefault();\n          first.focus();\n        }\n      }\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [lightbox, step]);\n\n  if (photos.length === 0) {\n    return (\n      <div className={cn(\"flex h-full w-full items-center justify-center rounded-xl\", className)} style={{ minHeight: 300, background: palette.background, border: palette.emptyBorder }} {...props}>\n        <span className=\"text-center text-sm leading-[1.6]\" style={{ color: palette.emptyText }}>\n          Add photos\n        </span>\n      </div>\n    );\n  }\n\n  const tabs = [{ key: null as string | null, label: allLabel, count: photos.length }, ...categories.map((c) => ({ key: c as string | null, label: c, count: photos.filter((p) => p.category === c).length }))];\n  const ease = \"cubic-bezier(0.22, 1, 0.36, 1)\";\n  const lightboxAt = lightbox === null ? -1 : visible.indexOf(lightbox);\n\n  return (\n    <div className={cn(\"relative w-full px-4 py-8 sm:px-8 sm:py-10\", className)} style={{ background: palette.background }} {...props}>\n      {showFilters && categories.length > 0 && (\n        <div className=\"mb-8 flex items-end justify-between gap-6\">\n          <div role=\"tablist\" aria-label=\"Filter photos\" className=\"relative -mx-1 flex min-w-0 gap-1 overflow-x-auto pb-2 [scrollbar-width:none]\">\n            {tabs.map((t, i) => {\n              const active = t.key === filter;\n              return (\n                <button\n                  key={t.label}\n                  ref={(el) => {\n                    tabRefs.current[i] = el;\n                  }}\n                  type=\"button\"\n                  role=\"tab\"\n                  aria-selected={active}\n                  onClick={() => setFilter(t.key)}\n                  className=\"flex shrink-0 cursor-pointer items-baseline gap-1.5 border-0 bg-transparent px-1 py-1 text-[13px] transition-colors duration-200 outline-none focus-visible:underline\"\n                  style={{ color: active ? palette.text : palette.muted }}\n                >\n                  {t.label}\n                  <span className=\"text-[10px] tabular-nums\" style={{ color: palette.muted }}>\n                    {String(t.count).padStart(2, \"0\")}\n                  </span>\n                </button>\n              );\n            })}\n            <span className=\"absolute bottom-0 left-0 h-px w-full\" style={{ background: palette.faint }} />\n            {underline && <span className=\"absolute bottom-0 h-px transition-[left,width] duration-500\" style={{ left: underline.left, width: underline.width, background: palette.line, transitionTimingFunction: ease }} />}\n          </div>\n          <span className=\"hidden shrink-0 pb-3 text-[10px] tracking-[0.2em] uppercase tabular-nums sm:block\" style={{ color: palette.muted }}>\n            {String(visible.length).padStart(2, \"0\")} photos\n          </span>\n        </div>\n      )}\n\n      <div ref={gridRef} className=\"relative w-full\" style={{ height, transition: animate ? `height 0.6s ${ease}` : undefined }} onMouseLeave={() => setHovered(null)}>\n        {photos.map((photo, i) => {\n          const pos = placed.get(i);\n          const isVisible = pos !== undefined;\n          const isShown = !reveal || shown.has(i);\n          const dim = hovered !== null && hovered !== i;\n          const last = pos ?? home.get(i)!;\n          return (\n            <div\n              key={i}\n              ref={(el) => {\n                itemRefs.current[i] = el;\n              }}\n              data-index={i}\n              className=\"absolute top-0 left-0\"\n              style={{\n                width: last.w,\n                height: last.h,\n                transform: `translate(${last.x}px, ${last.y}px)`,\n                transition: animate ? `transform 0.7s ${ease}, width 0.7s ${ease}, height 0.7s ${ease}` : undefined,\n                visibility: width === null ? \"hidden\" : undefined,\n                pointerEvents: isVisible ? undefined : \"none\",\n                zIndex: isVisible ? 1 : 0,\n              }}\n            >\n              <div\n                role={enableLightbox ? \"button\" : undefined}\n                tabIndex={isVisible && enableLightbox ? 0 : -1}\n                aria-hidden={isVisible ? undefined : true}\n                aria-label={enableLightbox ? `Open ${photo.title ?? `photo ${i + 1}`}` : undefined}\n                onMouseEnter={() => setHovered(i)}\n                onFocus={() => setHovered(i)}\n                onBlur={() => setHovered(null)}\n                onClick={() => enableLightbox && setLightbox(i)}\n                onKeyDown={(e) => {\n                  if (enableLightbox && (e.key === \"Enter\" || e.key === \" \")) {\n                    e.preventDefault();\n                    setLightbox(i);\n                  }\n                }}\n                className=\"group relative h-full w-full overflow-hidden outline-none\"\n                style={{\n                  borderRadius,\n                  background: palette.tile,\n                  cursor: enableLightbox ? \"zoom-in\" : undefined,\n                  opacity: !isVisible || !isShown ? 0 : dim ? dimOpacity : 1,\n                  transform: !isVisible ? \"scale(0.94)\" : isShown ? \"translateY(0)\" : \"translateY(28px)\",\n                  transition: `opacity 0.5s ${ease}, transform 0.8s ${ease}`,\n                  boxShadow: hovered === i ? `0 0 0 1px ${palette.faint}` : undefined,\n                }}\n              >\n                <img\n                  src={photo.src}\n                  alt={photo.alt || photo.title || \"\"}\n                  draggable={false}\n                  loading={i < 8 ? \"eager\" : \"lazy\"}\n                  onLoad={(e) => {\n                    if (photo.ratio) return;\n                    const img = e.currentTarget;\n                    if (img.naturalWidth && img.naturalHeight) setMeasured((m) => (m[i] ? m : { ...m, [i]: img.naturalWidth / img.naturalHeight }));\n                  }}\n                  className=\"pointer-events-none block h-full w-full object-cover transition-transform duration-700 select-none group-hover:scale-[1.04]\"\n                  style={{ transitionTimingFunction: ease }}\n                />\n                {(photo.title || photo.category) && (\n                  <div className=\"pointer-events-none absolute inset-x-0 bottom-0 flex flex-col gap-1 p-3.5 pt-10 opacity-0 transition-opacity duration-300 group-hover:opacity-100 group-focus-visible:opacity-100\" style={{ background: palette.caption }}>\n                    <span className=\"flex items-center gap-2 text-[9.5px] tracking-[0.2em] text-white/60 uppercase\">\n                      <span className=\"h-px w-0 bg-white/70 transition-[width] duration-500 group-hover:w-4 group-focus-visible:w-4\" style={{ transitionTimingFunction: ease }} />\n                      {photo.category}\n                    </span>\n                    <span className=\"truncate text-[13px] text-white\">{photo.title}</span>\n                  </div>\n                )}\n                <span className=\"pointer-events-none absolute inset-0 opacity-0 group-focus-visible:opacity-100\" style={{ borderRadius, boxShadow: `inset 0 0 0 1.5px ${palette.focus}` }} />\n              </div>\n            </div>\n          );\n        })}\n      </div>\n\n      {enableLightbox &&\n        lightbox !== null &&\n        createPortal(\n          <div ref={dialogRef} onClick={() => setLightbox(null)} role=\"dialog\" aria-modal=\"true\" aria-label=\"Photo preview\" className=\"fixed inset-0 z-[999999] flex flex-col items-center justify-center\" style={{ background: palette.lightboxBackground }}>\n            <button\n              ref={closeButtonRef}\n              onClick={(e) => {\n                e.stopPropagation();\n                setLightbox(null);\n              }}\n              aria-label=\"Close\"\n              className=\"absolute top-6 right-8 h-10 w-10 cursor-pointer border-0 bg-transparent text-[28px] leading-none\"\n              style={{ color: palette.controlColor }}\n            >\n              ×\n            </button>\n            {visible.length > 1 && (\n              <>\n                <button\n                  onClick={(e) => {\n                    e.stopPropagation();\n                    step(-1);\n                  }}\n                  aria-label=\"Previous\"\n                  className=\"absolute top-1/2 left-6 h-11 w-11 -translate-y-1/2 cursor-pointer border-0 bg-transparent text-[32px]\"\n                  style={{ color: palette.controlColor }}\n                >\n                  ‹\n                </button>\n                <button\n                  onClick={(e) => {\n                    e.stopPropagation();\n                    step(1);\n                  }}\n                  aria-label=\"Next\"\n                  className=\"absolute top-1/2 right-6 h-11 w-11 -translate-y-1/2 cursor-pointer border-0 bg-transparent text-[32px]\"\n                  style={{ color: palette.controlColor }}\n                >\n                  ›\n                </button>\n              </>\n            )}\n            <img\n              src={photos[lightbox].src}\n              alt={photos[lightbox].alt || photos[lightbox].title || \"\"}\n              onClick={(e) => e.stopPropagation()}\n              className=\"max-w-[82%] object-contain\"\n              style={{ maxHeight: \"78%\", borderRadius: 4, boxShadow: \"0 20px 60px rgba(0,0,0,0.6)\" }}\n              draggable={false}\n            />\n            <div className=\"mt-5 flex items-baseline gap-3 text-[13px]\" style={{ color: palette.controlColor }} onClick={(e) => e.stopPropagation()}>\n              {photos[lightbox].title && <span>{photos[lightbox].title}</span>}\n              <span className=\"text-[11px] tracking-[0.16em] uppercase tabular-nums opacity-60\">\n                {String(lightboxAt + 1).padStart(2, \"0\")} / {String(visible.length).padStart(2, \"0\")}\n              </span>\n            </div>\n          </div>,\n          document.body,\n        )}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}