{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"image-viewer","type":"registry:component","title":"Image viewer","description":"Wrap the grid you already have: a thumbnail grows into the full view, zooms where you aim, and shrinks back into its hole when you close.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/image-viewer.tsx","type":"registry:component","content":"// Hairline UI · image-viewer · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\n/* ─────────────────────────────────────────────────────────\n * IMAGE VIEWER: open any image in place, look closer, go back\n *\n * Wrap the grid you already have: <ImageViewer>{grid}</ImageViewer>.\n * Click an image and the thumbnail itself grows into the full\n * view (its crop opening out to the whole picture); close and it\n * shrinks back into the hole it left, the hole of whichever image\n * you ended on. Every image in the wrapper is a slide.\n *\n * Wheel, pinch or double-tap to zoom at the point you aim at, drag\n * to pan with momentum, swipe or arrow keys for the next image,\n * swipe down or Escape to close. All movement runs on springs, so\n * a gesture can take over from any motion mid-flight.\n * ───────────────────────────────────────────────────────── */\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { ChevronLeft, ChevronRight, Minus, Plus, X } from \"lucide-react\";\nimport { createSpring, projectInertia, rubberBand, type Spring } from \"./ui-interaction-motion\";\n\nexport interface ImageViewerProps {\n  /** Your own grid, list or single image. Every matching image inside becomes a slide. */\n  children: React.ReactNode;\n  /** Which images open, a CSS selector for <img> elements. Put data-full=\"…\" on an image for a larger file to load in the viewer. */\n  selector?: string;\n  /** Called with the open slide's index, and null when the viewer closes. */\n  onIndexChange?: (index: number | null) => void;\n  /** Most it zooms, as a multiple of the fitted size. */\n  maxZoom?: number;\n  labels?: { close?: string; next?: string; previous?: string; zoomIn?: string; zoomOut?: string; viewer?: string };\n  className?: string;\n}\n\ntype Item = { el: HTMLImageElement; src: string; full: string; alt: string; w: number; h: number };\ntype Box = { x: number; y: number; w: number; h: number };\n\nconst GAP = 24;\nconst SNAP = { stiffness: 420, damping: 40 };\nconst OPEN = 360;\nconst EASE = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst reducedMotion = () => typeof window !== \"undefined\" && window.matchMedia(reducedQuery).matches;\n\n/** The image's place on screen, contained in the viewport with room for the toolbar, the caption and the arrows. */\nfunction fit(item: Item, vw: number, vh: number): Box {\n  const side = vw < 640 ? 12 : 72;\n  const top = 60;\n  const bottom = 56;\n  const bw = vw - side * 2;\n  const bh = vh - top - bottom;\n  const s = Math.min(bw / item.w, bh / item.h);\n  const w = item.w * s;\n  const h = item.h * s;\n  return { x: side + (bw - w) / 2, y: top + (bh - h) / 2, w, h };\n}\n\n/** The transform and clip that make a fitted image look exactly like its thumbnail (cover-cropped, rounded). */\nfunction thumbPose(thumb: HTMLElement, box: Box) {\n  const r = thumb.getBoundingClientRect();\n  const s = Math.max(r.width / box.w, r.height / box.h);\n  const dx = r.left + r.width / 2 - (box.x + box.w / 2);\n  const dy = r.top + r.height / 2 - (box.y + box.h / 2);\n  const ix = Math.max(0, (box.w - r.width / s) / 2);\n  const iy = Math.max(0, (box.h - r.height / s) / 2);\n  // Thumbnails usually take their rounded corners from a wrapper that clips them.\n  const own = parseFloat(getComputedStyle(thumb).borderTopLeftRadius) || 0;\n  const parent = thumb.parentElement ? parseFloat(getComputedStyle(thumb.parentElement).borderTopLeftRadius) || 0 : 0;\n  const radius = Math.max(own, parent) / s;\n  const visible = r.bottom > 0 && r.top < window.innerHeight && r.width > 0;\n  return { transform: `translate(${dx}px, ${dy}px) scale(${s})`, clip: `inset(${iy}px ${ix}px round ${radius}px)`, visible };\n}\n\nexport function ImageViewer({ children, selector = \"img\", onIndexChange, maxZoom = 4, labels, className = \"\" }: ImageViewerProps) {\n  const root = React.useRef<HTMLDivElement>(null);\n  const [view, setView] = React.useState<{ items: Item[]; index: number; vw: number; vh: number } | null>(null);\n  const [closing, setClosing] = React.useState(false);\n\n  const dialog = React.useRef<HTMLDivElement>(null);\n  const backdrop = React.useRef<HTMLDivElement>(null);\n  const shade = React.useRef<HTMLDivElement>(null);\n  const strip = React.useRef<HTMLDivElement>(null);\n  const zoomText = React.useRef<HTMLSpanElement>(null);\n  const plates = React.useRef(new Map<number, HTMLDivElement>());\n  const springs = React.useRef<{ strip: Spring; zoom: Spring; x: Spring; y: Spring; drop: Spring } | null>(null);\n  const live = React.useRef({ index: 0, vw: 0, vh: 0, items: [] as Item[], hidden: null as HTMLImageElement | null, opener: null as HTMLElement | null });\n\n  const report = React.useRef(onIndexChange);\n  React.useLayoutEffect(() => {\n    report.current = onIndexChange;\n  });\n\n  // Images in the wrapper show they open, and can be reached by keyboard when nothing around them can.\n  React.useEffect(() => {\n    const box = root.current;\n    if (!box) return;\n    const mark = () =>\n      box.querySelectorAll<HTMLImageElement>(selector).forEach((img) => {\n        img.style.cursor = \"zoom-in\";\n        if (!img.closest(\"a, button\") && img.tabIndex < 0) {\n          img.tabIndex = 0;\n          img.setAttribute(\"role\", \"button\");\n        }\n      });\n    mark();\n    const watch = new MutationObserver(mark);\n    watch.observe(box, { childList: true, subtree: true });\n    return () => watch.disconnect();\n  }, [selector]);\n\n  const open = (img: HTMLImageElement, opener: HTMLElement) => {\n    const box = root.current;\n    if (!box || view) return;\n    const items = [...box.querySelectorAll<HTMLImageElement>(selector)].map((el) => {\n      const src = el.currentSrc || el.src;\n      return { el, src, full: el.dataset.full || src, alt: el.alt, w: el.naturalWidth || el.width || 1, h: el.naturalHeight || el.height || 1 };\n    });\n    const index = items.findIndex((i) => i.el === img);\n    if (index < 0) return;\n    live.current = { ...live.current, items, index, vw: window.innerWidth, vh: window.innerHeight, opener };\n    setClosing(false);\n    setView({ items, index, vw: window.innerWidth, vh: window.innerHeight });\n    report.current?.(index);\n  };\n\n  const onClickCapture = (event: React.MouseEvent) => {\n    const target = event.target as HTMLElement;\n    let img = target.closest<HTMLImageElement>(selector);\n    if (!img || !root.current?.contains(img)) {\n      const inside = target.querySelectorAll<HTMLImageElement>(selector);\n      img = inside.length === 1 ? inside[0] : null;\n    }\n    if (!img || !(img instanceof HTMLImageElement)) return;\n    event.preventDefault();\n    event.stopPropagation();\n    // Focus returns to what opened it: the link or button around the image, else the image itself.\n    open(img, (img.closest(\"a, button\") as HTMLElement | null) ?? (img.tabIndex >= 0 ? img : ((img.closest(\"[tabindex]\") as HTMLElement | null) ?? img)));\n  };\n  const onKeyDown = (event: React.KeyboardEvent) => {\n    const target = event.target as HTMLElement;\n    if ((event.key === \"Enter\" || event.key === \" \") && target instanceof HTMLImageElement && target.matches(selector)) {\n      event.preventDefault();\n      open(target, target);\n    }\n  };\n\n  /** Writes every spring's value to the page: the strip, the current image's zoom and pan, the drag to close. */\n  const paint = React.useCallback(() => {\n    const sp = springs.current;\n    const { index, vh } = live.current;\n    if (!sp) return;\n    if (strip.current) strip.current.style.transform = `translate3d(${sp.strip.get()}px, 0, 0)`;\n    const drop = sp.drop.get();\n    const lift = Math.min(1, Math.abs(drop) / (vh * 0.45));\n    plates.current.forEach((plate, i) => {\n      const inner = plate.firstElementChild as HTMLElement | null;\n      if (!inner) return;\n      inner.style.transform =\n        i === index ? `translate3d(${sp.x.get()}px, ${sp.y.get() + drop}px, 0) scale(${sp.zoom.get() * (1 - lift * 0.18)})` : \"\";\n    });\n    if (shade.current) shade.current.style.opacity = String(1 - lift);\n    if (zoomText.current) zoomText.current.textContent = `${Math.round(sp.zoom.get() * 100)}%`;\n  }, []);\n\n  const hideThumb = (el: HTMLImageElement | null) => {\n    const l = live.current;\n    if (l.hidden && l.hidden !== el) l.hidden.style.visibility = \"\";\n    l.hidden = el;\n    if (el) el.style.visibility = \"hidden\";\n  };\n\n  // Opening: springs at rest, the thumbnail's hole, and the flight out of it.\n  React.useLayoutEffect(() => {\n    if (!view) return;\n    const l = live.current;\n    springs.current ??= {\n      strip: createSpring(0, SNAP, paint, 0.1),\n      zoom: createSpring(1, SNAP, paint, 0.001),\n      x: createSpring(0, SNAP, paint, 0.1),\n      y: createSpring(0, SNAP, paint, 0.1),\n      drop: createSpring(0, SNAP, paint, 0.1),\n    };\n    const sp = springs.current;\n    sp.strip.jump(-l.index * (l.vw + GAP));\n    sp.zoom.jump(1);\n    sp.x.jump(0);\n    sp.y.jump(0);\n    sp.drop.jump(0);\n    const item = l.items[l.index];\n    const inner = plates.current.get(l.index)?.firstElementChild as HTMLElement | null;\n    hideThumb(item.el);\n    dialog.current?.focus({ preventScroll: true });\n    if (reducedMotion() || !inner) {\n      backdrop.current?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 160 });\n      return;\n    }\n    const pose = thumbPose(item.el, fit(item, l.vw, l.vh));\n    inner.animate([{ transform: pose.transform, clipPath: pose.clip }, { transform: \"none\", clipPath: \"inset(0px round 0px)\" }], { duration: OPEN, easing: EASE });\n    backdrop.current?.animate([{ opacity: 0 }, { opacity: 1 }], { duration: OPEN * 0.8, easing: \"ease-out\" });\n    // Only the open itself depends on this; later index changes are handled below.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [view !== null]);\n\n  // A new slide: the strip glides to it, zoom resets, and the hole under it moves to that image's thumbnail.\n  React.useEffect(() => {\n    if (!view) return;\n    const l = live.current;\n    const sp = springs.current;\n    if (!sp || l.index === view.index) return;\n    l.index = view.index;\n    sp.strip.set(-view.index * (view.vw + GAP));\n    sp.zoom.jump(1);\n    sp.x.jump(0);\n    sp.y.jump(0);\n    hideThumb(view.items[view.index].el);\n    report.current?.(view.index);\n  }, [view]);\n\n  const go = React.useCallback((dir: 1 | -1) => {\n    setView((v) => {\n      if (!v) return v;\n      const next = Math.max(0, Math.min(v.items.length - 1, v.index + dir));\n      if (next === v.index) {\n        springs.current?.strip.push(dir * -900);\n        return v;\n      }\n      return { ...v, index: next };\n    });\n  }, []);\n\n  const close = React.useCallback(() => {\n    if (closing || !view) return;\n    setClosing(true);\n    const l = live.current;\n    const sp = springs.current;\n    const item = l.items[l.index];\n    const inner = plates.current.get(l.index)?.firstElementChild as HTMLElement | null;\n    const done = () => {\n      hideThumb(null);\n      sp?.zoom.jump(1);\n      sp?.drop.jump(0);\n      setView(null);\n      setClosing(false);\n      report.current?.(null);\n      (l.opener?.isConnected ? l.opener : item.el)?.focus?.({ preventScroll: true });\n    };\n    if (reducedMotion() || !inner || !sp) {\n      backdrop.current?.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 160, fill: \"forwards\" }).finished.then(done);\n      return;\n    }\n    const pose = thumbPose(item.el, fit(item, l.vw, l.vh));\n    const from = inner.style.transform || \"none\";\n    sp.zoom.stop();\n    sp.x.stop();\n    sp.y.stop();\n    sp.drop.stop();\n    const to = pose.visible ? { transform: pose.transform, clipPath: pose.clip } : { transform: \"scale(0.92)\", clipPath: \"inset(0px round 0px)\", opacity: 0 };\n    inner.animate([{ transform: from, clipPath: \"inset(0px round 0px)\" }, to], { duration: OPEN, easing: EASE, fill: \"forwards\" }).finished.then(done);\n    backdrop.current?.animate([{ opacity: 1 }, { opacity: 0 }], { duration: OPEN * 0.8, easing: \"ease-in\", fill: \"forwards\" });\n  }, [closing, view]);\n\n  // Keep the layout right when the window changes size.\n  React.useEffect(() => {\n    if (!view) return;\n    const resize = () => {\n      live.current.vw = window.innerWidth;\n      live.current.vh = window.innerHeight;\n      springs.current?.strip.jump(-live.current.index * (window.innerWidth + GAP));\n      setView((v) => (v ? { ...v, vw: window.innerWidth, vh: window.innerHeight } : v));\n    };\n    window.addEventListener(\"resize\", resize);\n    return () => window.removeEventListener(\"resize\", resize);\n  }, [view]);\n\n  /* ── zoom and pan ─────────────────────────────────────── */\n\n  /** How far the image may be pushed at zoom z before its edge comes inside the screen. */\n  const bounds = (z: number) => {\n    const l = live.current;\n    const box = fit(l.items[l.index], l.vw, l.vh);\n    return { x: Math.max(0, (box.w * z - l.vw) / 2), y: Math.max(0, (box.h * z - l.vh) / 2), box };\n  };\n  /** Zoom to z keeping the screen point px, py where it is. */\n  const zoomAt = (z: number, px: number, py: number, animate = true) => {\n    const sp = springs.current;\n    if (!sp) return;\n    const z0 = sp.zoom.getTarget();\n    const z1 = Math.max(1, Math.min(maxZoom, z));\n    const { box } = bounds(z1);\n    const cx = box.x + box.w / 2 + sp.x.getTarget();\n    const cy = box.y + box.h / 2 + sp.y.getTarget();\n    const b = bounds(z1);\n    const nx = Math.max(-b.x, Math.min(b.x, sp.x.getTarget() + (px - cx) * (1 - z1 / z0)));\n    const ny = Math.max(-b.y, Math.min(b.y, sp.y.getTarget() + (py - cy) * (1 - z1 / z0)));\n    if (animate) {\n      sp.zoom.set(z1);\n      sp.x.set(nx);\n      sp.y.set(ny);\n    } else {\n      sp.zoom.jump(z1);\n      sp.x.jump(nx);\n      sp.y.jump(ny);\n    }\n  };\n  const zoomBy = (factor: number) => {\n    const l = live.current;\n    zoomAt((springs.current?.zoom.getTarget() ?? 1) * factor, l.vw / 2, l.vh / 2);\n  };\n\n  // Wheel zooms at the pointer; the page behind never scrolls.\n  React.useEffect(() => {\n    const el = dialog.current;\n    if (!view || !el) return;\n    const wheel = (event: WheelEvent) => {\n      event.preventDefault();\n      const z = springs.current?.zoom.getTarget() ?? 1;\n      zoomAt(z * Math.exp(-event.deltaY * (event.ctrlKey ? 0.01 : 0.0022)), event.clientX, event.clientY);\n    };\n    const stop = (event: TouchEvent) => event.preventDefault();\n    el.addEventListener(\"wheel\", wheel, { passive: false });\n    el.addEventListener(\"touchmove\", stop, { passive: false });\n    return () => {\n      el.removeEventListener(\"wheel\", wheel);\n      el.removeEventListener(\"touchmove\", stop);\n    };\n    // zoomAt reads live refs only.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [view !== null]);\n\n  /* ── pointers: pan, swipe, pinch, drag to close, double-tap ── */\n\n  const gesture = React.useRef({\n    points: new Map<number, { x: number; y: number }>(),\n    mode: \"\" as \"\" | \"pending\" | \"pan\" | \"swipe\" | \"drop\" | \"pinch\",\n    x0: 0,\n    y0: 0,\n    t0: 0,\n    panX: 0,\n    panY: 0,\n    zoom: 1,\n    dist: 0,\n    midX: 0,\n    midY: 0,\n    strip: 0,\n    samples: [] as { x: number; y: number; t: number }[],\n    lastTap: 0,\n  });\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if ((event.target as HTMLElement).closest(\"button\") || closing) return;\n    const g = gesture.current;\n    const sp = springs.current;\n    if (!sp) return;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    g.points.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    if (g.points.size === 2) {\n      const [a, b] = [...g.points.values()];\n      g.mode = \"pinch\";\n      g.dist = Math.hypot(a.x - b.x, a.y - b.y);\n      g.zoom = sp.zoom.get();\n      g.midX = (a.x + b.x) / 2;\n      g.midY = (a.y + b.y) / 2;\n      g.panX = sp.x.get();\n      g.panY = sp.y.get();\n      return;\n    }\n    g.mode = \"pending\";\n    g.x0 = event.clientX;\n    g.y0 = event.clientY;\n    g.t0 = event.timeStamp;\n    g.panX = sp.x.get();\n    g.panY = sp.y.get();\n    g.strip = sp.strip.get();\n    g.samples = [{ x: event.clientX, y: event.clientY, t: event.timeStamp }];\n    // Taking hold stops whatever was moving, right where it is.\n    sp.x.jump(g.panX);\n    sp.y.jump(g.panY);\n  };\n\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const g = gesture.current;\n    const sp = springs.current;\n    if (!sp || !g.points.has(event.pointerId)) return;\n    g.points.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    const l = live.current;\n    if (g.mode === \"pinch\" && g.points.size >= 2) {\n      const [a, b] = [...g.points.values()];\n      const z = Math.max(0.85, Math.min(maxZoom * 1.15, (g.zoom * Math.hypot(a.x - b.x, a.y - b.y)) / Math.max(1, g.dist)));\n      const midX = (a.x + b.x) / 2;\n      const midY = (a.y + b.y) / 2;\n      const box = fit(l.items[l.index], l.vw, l.vh);\n      const cx = box.x + box.w / 2 + g.panX;\n      const cy = box.y + box.h / 2 + g.panY;\n      sp.zoom.jump(z);\n      sp.x.jump(g.panX + (g.midX - cx) * (1 - z / g.zoom) + (midX - g.midX));\n      sp.y.jump(g.panY + (g.midY - cy) * (1 - z / g.zoom) + (midY - g.midY));\n      return;\n    }\n    const dx = event.clientX - g.x0;\n    const dy = event.clientY - g.y0;\n    g.samples.push({ x: event.clientX, y: event.clientY, t: event.timeStamp });\n    while (g.samples.length > 2 && event.timeStamp - g.samples[0].t > 100) g.samples.shift();\n    if (g.mode === \"pending\") {\n      if (Math.hypot(dx, dy) < 7) return;\n      const zoomed = sp.zoom.get() > 1.01;\n      g.mode = zoomed ? \"pan\" : Math.abs(dx) > Math.abs(dy) ? \"swipe\" : \"drop\";\n      // Movement starts from here, so nothing jumps by the slop.\n      g.x0 = event.clientX;\n      g.y0 = event.clientY;\n      return;\n    }\n    if (g.mode === \"pan\") {\n      const b = bounds(sp.zoom.get());\n      const over = (v: number, m: number, d: number) => (v > m ? m + rubberBand(v - m, d) : v < -m ? -m + rubberBand(v + m, d) : v);\n      sp.x.jump(over(g.panX + dx, b.x, l.vw));\n      sp.y.jump(over(g.panY + dy, b.y, l.vh));\n    } else if (g.mode === \"swipe\") {\n      const first = l.index === 0 && dx > 0;\n      const last = l.index === l.items.length - 1 && dx < 0;\n      sp.strip.jump(g.strip + (first || last ? rubberBand(dx, l.vw) : dx));\n    } else if (g.mode === \"drop\") {\n      sp.drop.jump(dy);\n    }\n  };\n\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const g = gesture.current;\n    const sp = springs.current;\n    if (!sp || !g.points.has(event.pointerId)) return;\n    g.points.delete(event.pointerId);\n    const l = live.current;\n    if (g.mode === \"pinch\") {\n      if (g.points.size) {\n        // One finger stays down: carry on as a pan from here.\n        const [p] = [...g.points.values()];\n        g.mode = \"pan\";\n        g.x0 = p.x;\n        g.y0 = p.y;\n        g.panX = sp.x.get();\n        g.panY = sp.y.get();\n        return;\n      }\n      g.mode = \"\";\n      const z = Math.max(1, Math.min(maxZoom, sp.zoom.get()));\n      const b = bounds(z);\n      sp.zoom.set(z);\n      sp.x.set(Math.max(-b.x, Math.min(b.x, sp.x.get())));\n      sp.y.set(Math.max(-b.y, Math.min(b.y, sp.y.get())));\n      return;\n    }\n    const first = g.samples[0];\n    const end = g.samples[g.samples.length - 1];\n    const span = Math.max(1, end.t - first.t);\n    const vx = event.timeStamp - end.t > 100 ? 0 : (end.x - first.x) / span;\n    const vy = event.timeStamp - end.t > 100 ? 0 : (end.y - first.y) / span;\n    const mode = g.mode;\n    g.mode = \"\";\n    if (mode === \"pending\") {\n      // A tap: twice on the image zooms there; once on the backdrop closes.\n      const onImage = !!(event.target as HTMLElement).closest(\"[data-viewer-image]\");\n      if (onImage && event.timeStamp - g.lastTap < 300) {\n        g.lastTap = 0;\n        const z = sp.zoom.getTarget();\n        zoomAt(z > 1.01 ? 1 : Math.min(maxZoom, 2.5), event.clientX, event.clientY);\n      } else if (onImage) g.lastTap = event.timeStamp;\n      else close();\n      return;\n    }\n    if (mode === \"pan\") {\n      const b = bounds(sp.zoom.get());\n      sp.x.set(Math.max(-b.x, Math.min(b.x, projectInertia(sp.x.get(), vx, 0.25))));\n      sp.y.set(Math.max(-b.y, Math.min(b.y, projectInertia(sp.y.get(), vy, 0.25))));\n    } else if (mode === \"swipe\") {\n      const moved = projectInertia(sp.strip.get() - g.strip, vx);\n      const dir = moved < -l.vw * 0.25 ? 1 : moved > l.vw * 0.25 ? -1 : 0;\n      const next = Math.max(0, Math.min(l.items.length - 1, l.index + dir));\n      if (next !== l.index) setView((v) => (v ? { ...v, index: next } : v));\n      else sp.strip.set(-l.index * (l.vw + GAP));\n      sp.strip.push(vx * 1000 * 0.4);\n    } else if (mode === \"drop\") {\n      if (Math.abs(projectInertia(sp.drop.get(), vy)) > l.vh * 0.22) close();\n      else sp.drop.set(0);\n    }\n  };\n\n  const onDialogKey = (event: React.KeyboardEvent) => {\n    if (event.key === \"Escape\") {\n      event.preventDefault();\n      close();\n    } else if (event.key === \"ArrowRight\") go(1);\n    else if (event.key === \"ArrowLeft\") go(-1);\n    else if (event.key === \"+\" || event.key === \"=\") zoomBy(1.5);\n    else if (event.key === \"-\") zoomBy(1 / 1.5);\n    else if (event.key === \"0\") zoomAt(1, live.current.vw / 2, live.current.vh / 2);\n    else if (event.key === \"Tab\") {\n      // Focus stays inside the viewer.\n      const nodes = [...(dialog.current?.querySelectorAll<HTMLElement>(\"button:not([disabled])\") ?? [])];\n      if (!nodes.length) return;\n      const at = nodes.indexOf(document.activeElement as HTMLElement);\n      if (event.shiftKey && at <= 0) {\n        event.preventDefault();\n        nodes[nodes.length - 1].focus();\n      } else if (!event.shiftKey && at === nodes.length - 1) {\n        event.preventDefault();\n        nodes[0].focus();\n      }\n    }\n  };\n\n  const round = \"grid size-10 cursor-pointer place-items-center rounded-full bg-background text-foreground ring-1 ring-border transition-[background-color,scale,opacity] duration-150 hover:bg-accent active:scale-95 disabled:pointer-events-none disabled:opacity-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60\";\n  const current = view?.items[view.index];\n\n  return (\n    <div ref={root} onClickCapture={onClickCapture} onKeyDown={onKeyDown} className={className}>\n      {children}\n      {view &&\n        current &&\n        createPortal(\n          <div\n            ref={dialog}\n            role=\"dialog\"\n            aria-modal=\"true\"\n            aria-label={labels?.viewer ?? \"Image viewer\"}\n            tabIndex={-1}\n            onKeyDown={onDialogKey}\n            onPointerDown={onPointerDown}\n            onPointerMove={onPointerMove}\n            onPointerUp={onPointerUp}\n            onPointerCancel={onPointerUp}\n            className=\"fixed inset-0 z-[2147482000] touch-none overflow-clip text-foreground outline-none select-none\"\n          >\n            <div ref={backdrop} className=\"absolute inset-0\">\n              <div ref={shade} className=\"absolute inset-0 bg-background\" />\n            </div>\n            <div ref={strip} className=\"absolute inset-0 will-change-transform\">\n              {view.items.map((item, i) => {\n                if (Math.abs(i - view.index) > 1) return null;\n                const box = fit(item, view.vw, view.vh);\n                return (\n                  <div\n                    key={i}\n                    ref={(el) => {\n                      if (el) plates.current.set(i, el);\n                      else plates.current.delete(i);\n                    }}\n                    className=\"absolute\"\n                    style={{ left: i * (view.vw + GAP) + box.x, top: box.y, width: box.w, height: box.h }}\n                    aria-hidden={i !== view.index}\n                  >\n                    <div data-viewer-image=\"\" className=\"relative size-full will-change-transform\" style={{ cursor: \"zoom-in\" }}>\n                      {/* eslint-disable-next-line @next/next/no-img-element */}\n                      <img src={item.src} alt={i === view.index ? item.alt : \"\"} draggable={false} className=\"absolute inset-0 size-full\" />\n                      {item.full !== item.src && (\n                        // eslint-disable-next-line @next/next/no-img-element\n                        <img\n                          src={item.full}\n                          alt=\"\"\n                          draggable={false}\n                          className=\"absolute inset-0 size-full opacity-0 transition-opacity duration-300\"\n                          onLoad={(e) => (e.currentTarget.style.opacity = \"1\")}\n                        />\n                      )}\n                    </div>\n                  </div>\n                );\n              })}\n            </div>\n            <div className=\"absolute inset-x-0 top-0 flex h-[60px] items-center justify-between gap-3 px-3 sm:px-4\">\n              <span className=\"rounded-full bg-background px-2.5 py-1 text-[13px] font-medium tabular-nums text-muted-foreground ring-1 ring-border\" aria-live=\"polite\">\n                {view.index + 1} / {view.items.length}\n              </span>\n              <div className=\"flex items-center gap-1.5\">\n                <button type=\"button\" className={round} aria-label={labels?.zoomOut ?? \"Zoom out\"} onClick={() => zoomBy(1 / 1.5)}>\n                  <Minus className=\"size-4\" aria-hidden=\"true\" />\n                </button>\n                <span ref={zoomText} aria-hidden=\"true\" className=\"w-12 rounded-full bg-background py-1 text-center text-[12.5px] tabular-nums text-muted-foreground ring-1 ring-border\">\n                  100%\n                </span>\n                <button type=\"button\" className={round} aria-label={labels?.zoomIn ?? \"Zoom in\"} onClick={() => zoomBy(1.5)}>\n                  <Plus className=\"size-4\" aria-hidden=\"true\" />\n                </button>\n                <button type=\"button\" className={`${round} ml-2`} aria-label={labels?.close ?? \"Close\"} onClick={close}>\n                  <X className=\"size-4\" aria-hidden=\"true\" />\n                </button>\n              </div>\n            </div>\n            <button\n              type=\"button\"\n              className={`${round} absolute top-1/2 left-4 -translate-y-1/2 max-sm:hidden`}\n              aria-label={labels?.previous ?? \"Previous image\"}\n              disabled={view.index === 0}\n              onClick={() => go(-1)}\n            >\n              <ChevronLeft className=\"size-4\" aria-hidden=\"true\" />\n            </button>\n            <button\n              type=\"button\"\n              className={`${round} absolute top-1/2 right-4 -translate-y-1/2 max-sm:hidden`}\n              aria-label={labels?.next ?? \"Next image\"}\n              disabled={view.index === view.items.length - 1}\n              onClick={() => go(1)}\n            >\n              <ChevronRight className=\"size-4\" aria-hidden=\"true\" />\n            </button>\n            {current.alt && (\n              <div className=\"pointer-events-none absolute inset-x-0 bottom-0 flex h-14 items-center justify-center px-6\">\n                <p className=\"max-w-full truncate rounded-full bg-background px-3 py-1 text-center text-[13px] text-muted-foreground ring-1 ring-border\">{current.alt}</p>\n              </div>\n            )}\n          </div>,\n          document.body,\n        )}\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · image-viewer · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/image-viewer. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}