{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-viewer",
  "title": "Image viewer",
  "description": "A morphing lightbox with zoom, pan and swipe. Adapted from beUI (MIT).",
  "dependencies": [
    "@keyline-icons/react@^2.2.0",
    "motion@^12.23.12"
  ],
  "registryDependencies": [
    "@khaeli/ease",
    "@khaeli/utils"
  ],
  "files": [
    {
      "path": "registry/khaeli/ui/image-viewer.tsx",
      "content": "\"use client\";\n\n/*\n * beUI, https://github.com/starc007/ui-components\n * MIT License, Copyright (c) 2026 Saurabh Chauhan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n// Adapted from beUI (MIT) https://beui.dev — components/motion/morphing-lightbox.\n// Restyled for this design system: Keyline icon controls, `cn` from the shared\n// package, tiles on our radius scale. beUI's modal-scope/presence-gate helpers\n// are dropped: a small inline scope (scroll lock, Escape, Tab loop) replaces\n// them. The stage's gesture set (pinch, Ctrl/Cmd+wheel and double-tap zoom\n// around the pointer, panning with rubber-band edges, swipe paging, and a\n// drag down to dismiss on phones) is this file's own code; Arc's\n// lightbox-gallery served only as an interaction reference. Gestures paint\n// transforms from refs, so a drag never re-renders. Image dimensions are\n// optional: attachment endpoints don't ship intrinsic sizes, so zoom reads the\n// loaded image's natural size.\n\nimport {\n\ttype ComponentPropsWithRef,\n\ttype PointerEvent as ReactPointerEvent,\n\ttype ReactNode,\n\ttype RefObject,\n\tcreateContext,\n\tuseContext,\n\tuseEffect,\n\tuseId,\n\tuseLayoutEffect,\n\tuseRef,\n\tuseState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { AnimatePresence, LayoutGroup, animate, useReducedMotion } from \"motion/react\";\nimport * as m from \"motion/react-m\";\nimport { ChevronLeftIcon, ChevronRightIcon, XIcon } from \"@keyline-icons/react\";\nimport { cn } from \"@/lib/utils\";\nimport { EASE_OUT, SPRING_LAYOUT } from \"@/lib/ease\";\n\nexport interface LightboxImage {\n\tid: string;\n\tsrc: string;\n\talt: string;\n\t/** Intrinsic dimensions, when known, keep the aspect through the morph. */\n\twidth?: number;\n\theight?: number;\n\tcaption?: string;\n}\n\nexport interface ImageViewerProps {\n\timages: LightboxImage[];\n\tvalue?: string | null;\n\tdefaultValue?: string | null;\n\tonValueChange?: (id: string | null) => void;\n\tlabel?: string;\n\tclassName?: string;\n\tthumbnailClassName?: string;\n\trenderCaption?: (image: LightboxImage) => ReactNode;\n\t/** Compose gallery and viewer parts instead of the default layout. */\n\tchildren?: ReactNode;\n}\n\ninterface ViewerContextValue {\n\timages: LightboxImage[];\n\tvalue: string | null;\n\timage: LightboxImage | undefined;\n\tindex: number;\n\tlabel: string;\n\tgroupId: string;\n\treduce: boolean;\n\trenderCaption?: (image: LightboxImage) => ReactNode;\n\tselect: (id: string | null) => void;\n\tmove: (direction: -1 | 1) => void;\n}\n\nconst ViewerContext = createContext<ViewerContextValue | null>(null);\n\nfunction useViewerContext(part: string): ViewerContextValue {\n\tconst context = useContext(ViewerContext);\n\tif (!context) throw new Error(`${part} must be used within ImageViewer.`);\n\treturn context;\n}\n\n/** A composable image gallery with a focus-managed, thumbnail-connected viewer. */\nexport function ImageViewer({\n\timages,\n\tvalue: controlledValue,\n\tdefaultValue = null,\n\tonValueChange,\n\tlabel = \"Image gallery\",\n\tclassName,\n\tthumbnailClassName,\n\trenderCaption,\n\tchildren,\n}: ImageViewerProps) {\n\tconst [internalValue, setInternalValue] = useState(defaultValue);\n\tconst value = controlledValue === undefined ? internalValue : controlledValue;\n\tconst index = images.findIndex((image) => image.id === value);\n\tconst image = images[index];\n\tconst groupId = useId();\n\tconst reduce = useReducedMotion() ?? false;\n\tconst select = (id: string | null) => {\n\t\tif (controlledValue === undefined) setInternalValue(id);\n\t\tonValueChange?.(id);\n\t};\n\t// Drop removed identities instead of letting a re-added image reopen a session.\n\tif (controlledValue === undefined && internalValue !== null && index < 0) setInternalValue(null);\n\tconst move = (direction: -1 | 1) => {\n\t\tconst next = images[index + direction];\n\t\tif (image && next) select(next.id);\n\t};\n\treturn (\n\t\t<ViewerContext.Provider value={{ images, value, image, index, label, groupId, reduce, renderCaption, select, move }}>\n\t\t\t<LayoutGroup id={groupId}>\n\t\t\t\t{children === undefined ? (\n\t\t\t\t\t<>\n\t\t\t\t\t\t<ImageViewerGallery className={className}>\n\t\t\t\t\t\t\t{images.map((item) => (\n\t\t\t\t\t\t\t\t<ImageViewerThumbnail key={item.id} imageId={item.id} className={thumbnailClassName} />\n\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</ImageViewerGallery>\n\t\t\t\t\t\t<ImageViewerContent />\n\t\t\t\t\t</>\n\t\t\t\t) : (\n\t\t\t\t\tchildren\n\t\t\t\t)}\n\t\t\t</LayoutGroup>\n\t\t</ViewerContext.Provider>\n\t);\n}\n\nexport function ImageViewerGallery({ className, ...props }: ComponentPropsWithRef<\"section\">) {\n\tconst { label } = useViewerContext(\"ImageViewerGallery\");\n\treturn <section aria-label={label} {...props} className={cn(\"flex flex-wrap gap-3\", className)} />;\n}\n\nexport interface ImageViewerThumbnailProps extends Omit<ComponentPropsWithRef<\"button\">, \"children\"> {\n\timageId: string;\n\timageClassName?: string;\n\tchildren?: ReactNode;\n}\n\n/** The image keeps its shared-layout identity when the trigger is customised. */\nexport function ImageViewerThumbnail({ imageId, className, imageClassName, children, onClick, disabled, ...props }: ImageViewerThumbnailProps) {\n\tconst { images, value, groupId, reduce, select } = useViewerContext(\"ImageViewerThumbnail\");\n\tconst image = images.find((item) => item.id === imageId);\n\tif (!image) throw new Error(`ImageViewerThumbnail: unknown image id \"${imageId}\".`);\n\treturn (\n\t\t<button\n\t\t\ttype=\"button\"\n\t\t\taria-label={`Open ${image.alt}`}\n\t\t\t{...props}\n\t\t\tdisabled={disabled}\n\t\t\taria-haspopup=\"dialog\"\n\t\t\taria-expanded={image.id === value}\n\t\t\tonClick={(event) => {\n\t\t\t\tonClick?.(event);\n\t\t\t\tif (!event.defaultPrevented && !disabled) select(image.id);\n\t\t\t}}\n\t\t\tclassName={cn(\n\t\t\t\t\"relative overflow-hidden rounded-md bg-muted focus-ring-inset\",\n\t\t\t\tclassName,\n\t\t\t)}\n\t\t>\n\t\t\t<m.img\n\t\t\t\tlayoutId={reduce ? undefined : `${groupId}-${image.id}`}\n\t\t\t\tsrc={image.src}\n\t\t\t\talt={image.alt}\n\t\t\t\twidth={image.width}\n\t\t\t\theight={image.height}\n\t\t\t\tloading=\"lazy\"\n\t\t\t\tdraggable={false}\n\t\t\t\ttransition={SPRING_LAYOUT}\n\t\t\t\tclassName={cn(\"block size-full object-cover\", imageClassName)}\n\t\t\t/>\n\t\t\t{children}\n\t\t</button>\n\t);\n}\n\nexport function ImageViewerCounter({ className, ...props }: ComponentPropsWithRef<\"span\">) {\n\tconst { index, images } = useViewerContext(\"ImageViewerCounter\");\n\treturn (\n\t\t<span aria-live=\"polite\" {...props} className={cn(\"text-xs tabular-nums\", className)}>\n\t\t\t{index + 1} / {images.length}\n\t\t</span>\n\t);\n}\n\nexport function ImageViewerCaption({ className, children, ...props }: ComponentPropsWithRef<\"div\">) {\n\tconst { image, renderCaption } = useViewerContext(\"ImageViewerCaption\");\n\treturn (\n\t\t<div aria-live=\"polite\" {...props} data-lightbox-content=\"\" className={cn(\"min-w-0 truncate text-center text-sm\", className)}>\n\t\t\t{children ?? (image && (renderCaption ? renderCaption(image) : (image.caption ?? image.alt)))}\n\t\t</div>\n\t);\n}\n\nconst controlClass =\n\t\"inline-flex size-9 shrink-0 items-center justify-center rounded-full bg-white/10 text-white transition-colors hover:bg-white/20 focus-ring [--ring:white] disabled:opacity-30\";\n\ntype ViewerButtonProps = ComponentPropsWithRef<\"button\">;\n\nfunction ViewerButton({ action, className, children, disabled, onClick, ...props }: ViewerButtonProps & { action: \"close\" | \"previous\" | \"next\" }) {\n\tconst { index, images, select, move } = useViewerContext(\"ImageViewer controls\");\n\tconst unavailable = action === \"previous\" ? index <= 0 : action === \"next\" ? index < 0 || index >= images.length - 1 : false;\n\tconst Icon = action === \"close\" ? XIcon : action === \"previous\" ? ChevronLeftIcon : ChevronRightIcon;\n\treturn (\n\t\t<button\n\t\t\ttype=\"button\"\n\t\t\taria-label={action === \"close\" ? \"Close viewer\" : action === \"previous\" ? \"Previous image\" : \"Next image\"}\n\t\t\t{...props}\n\t\t\tdisabled={disabled || unavailable}\n\t\t\tonClick={(event) => {\n\t\t\t\tonClick?.(event);\n\t\t\t\tif (!event.defaultPrevented) {\n\t\t\t\t\tif (action === \"close\") select(null);\n\t\t\t\t\telse move(action === \"previous\" ? -1 : 1);\n\t\t\t\t}\n\t\t\t}}\n\t\t\tclassName={cn(controlClass, className)}\n\t\t>\n\t\t\t{children ?? <Icon className=\"size-[18px]\" aria-hidden=\"true\" />}\n\t\t</button>\n\t);\n}\n\nexport function ImageViewerClose(props: ViewerButtonProps) {\n\treturn <ViewerButton {...props} action=\"close\" />;\n}\nexport function ImageViewerPrevious(props: ViewerButtonProps) {\n\treturn <ViewerButton {...props} action=\"previous\" />;\n}\nexport function ImageViewerNext(props: ViewerButtonProps) {\n\treturn <ViewerButton {...props} action=\"next\" />;\n}\n\nexport interface ImageViewerContentProps {\n\tclassName?: string;\n\t/** Custom header; defaults to the counter and close control. */\n\theader?: ReactNode;\n\t/** Custom footer; defaults to navigation and the image caption. */\n\tchildren?: ReactNode;\n}\n\n/** Owns the portal, the focus scope and the morphing stage. */\nexport function ImageViewerContent({ className, header, children }: ImageViewerContentProps) {\n\tconst context = useViewerContext(\"ImageViewerContent\");\n\tconst { image, label, reduce, select, move } = context;\n\tconst [mounted, setMounted] = useState(false);\n\tconst panel = useRef<HTMLDivElement>(null);\n\tconst scrim = useRef<HTMLSpanElement>(null);\n\tconst stage = useRef<StageControls>(null);\n\tuseEffect(() => setMounted(true), []);\n\tconst open = mounted && Boolean(image);\n\t// Minimal modal scope: scroll lock, Escape, Tab loop, focus restoration.\n\tuseEffect(() => {\n\t\tif (!open) return;\n\t\tconst returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n\t\tconst previousOverflow = document.body.style.overflow;\n\t\tdocument.body.style.overflow = \"hidden\";\n\t\tpanel.current?.focus({ preventScroll: true });\n\t\tconst onKey = (event: KeyboardEvent) => {\n\t\t\tif (event.key === \"Escape\") {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tselect(null);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (event.key !== \"Tab\" || !panel.current) return;\n\t\t\tconst focusables = Array.from(panel.current.querySelectorAll<HTMLElement>(\"button:not(:disabled), a[href]\"));\n\t\t\tconst first = focusables[0];\n\t\t\tconst last = focusables.at(-1);\n\t\t\tif (!first || !last) return;\n\t\t\tif (event.shiftKey && document.activeElement === first) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tlast.focus();\n\t\t\t} else if (!event.shiftKey && document.activeElement === last) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfirst.focus();\n\t\t\t}\n\t\t};\n\t\tdocument.addEventListener(\"keydown\", onKey);\n\t\treturn () => {\n\t\t\tdocument.removeEventListener(\"keydown\", onKey);\n\t\t\tdocument.body.style.overflow = previousOverflow;\n\t\t\treturnFocus?.focus({ preventScroll: true });\n\t\t};\n\t}, [open, select]);\n\tif (!mounted) return null;\n\treturn createPortal(\n\t\t<AnimatePresence>\n\t\t\t{image && (\n\t\t\t\t<ViewerContext.Provider value={context}>\n\t\t\t\t\t<m.button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\t\taria-hidden=\"true\"\n\t\t\t\t\t\tonClick={() => select(null)}\n\t\t\t\t\t\tinitial={{ opacity: 0 }}\n\t\t\t\t\t\tanimate={{ opacity: 1 }}\n\t\t\t\t\t\texit={{ opacity: 0 }}\n\t\t\t\t\t\ttransition={{ duration: reduce ? 0.1 : 0.18, ease: EASE_OUT }}\n\t\t\t\t\t\tclassName=\"fixed inset-0 z-[100] h-full w-full cursor-default\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{/* A separate layer, so a drag down to dismiss can fade it without fighting the enter/exit fade. */}\n\t\t\t\t\t\t<span ref={scrim} className=\"absolute inset-0 bg-black/90\" />\n\t\t\t\t\t</m.button>\n\t\t\t\t\t<div className=\"pointer-events-none fixed inset-3 z-[101] sm:inset-6\">\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tref={panel}\n\t\t\t\t\t\t\trole=\"dialog\"\n\t\t\t\t\t\t\taria-modal=\"true\"\n\t\t\t\t\t\t\taria-label={label}\n\t\t\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\t\t\tclassName={cn(\"pointer-events-auto flex h-full flex-col outline-none\", className)}\n\t\t\t\t\t\t\tonPointerDownCapture={(event) => {\n\t\t\t\t\t\t\t\tconst target = event.target;\n\t\t\t\t\t\t\t\tif (target instanceof Element && !target.closest(\"button, a, img, [data-lightbox-content]\")) select(null);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\tonKeyDown={(event) => {\n\t\t\t\t\t\t\t\tif (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return;\n\t\t\t\t\t\t\t\tconst zoom = event.key === \"+\" || event.key === \"=\" ? 1 : event.key === \"-\" ? -1 : event.key === \"0\" ? 0 : null;\n\t\t\t\t\t\t\t\tif (zoom !== null) {\n\t\t\t\t\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\t\t\t\t\tstage.current?.zoom(zoom);\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (event.shiftKey) return;\n\t\t\t\t\t\t\t\tif (event.key === \"ArrowLeft\" || event.key === \"ArrowRight\") {\n\t\t\t\t\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\t\t\t\t\tmove(event.key === \"ArrowLeft\" ? -1 : 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<m.div\n\t\t\t\t\t\t\t\tinitial={{ opacity: 0 }}\n\t\t\t\t\t\t\t\tanimate={{ opacity: 1 }}\n\t\t\t\t\t\t\t\texit={{ opacity: 0 }}\n\t\t\t\t\t\t\t\ttransition={{ duration: reduce ? 0.1 : 0.15, ease: EASE_OUT }}\n\t\t\t\t\t\t\t\tdata-lightbox-content=\"\"\n\t\t\t\t\t\t\t\tclassName=\"flex items-center justify-between gap-3 pb-3 text-white\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{header === undefined ? (\n\t\t\t\t\t\t\t\t\t<>\n\t\t\t\t\t\t\t\t\t\t<ImageViewerCounter />\n\t\t\t\t\t\t\t\t\t\t<ImageViewerClose />\n\t\t\t\t\t\t\t\t\t</>\n\t\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t\theader\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t</m.div>\n\t\t\t\t\t\t\t<ViewerStage image={image} scrimRef={scrim} controlsRef={stage} />\n\t\t\t\t\t\t\t<m.div\n\t\t\t\t\t\t\t\tinitial={{ opacity: 0 }}\n\t\t\t\t\t\t\t\tanimate={{ opacity: 1 }}\n\t\t\t\t\t\t\t\texit={{ opacity: 0 }}\n\t\t\t\t\t\t\t\ttransition={{ duration: reduce ? 0.1 : 0.15, ease: EASE_OUT }}\n\t\t\t\t\t\t\t\tdata-lightbox-content=\"\"\n\t\t\t\t\t\t\t\tclassName=\"flex items-center justify-between gap-3 pt-3 text-white\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{children === undefined ? (\n\t\t\t\t\t\t\t\t\t<>\n\t\t\t\t\t\t\t\t\t\t<ImageViewerPrevious />\n\t\t\t\t\t\t\t\t\t\t<ImageViewerCaption />\n\t\t\t\t\t\t\t\t\t\t<ImageViewerNext />\n\t\t\t\t\t\t\t\t\t</>\n\t\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t\tchildren\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t</m.div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</ViewerContext.Provider>\n\t\t\t)}\n\t\t</AnimatePresence>,\n\t\tdocument.body,\n\t);\n}\n\n/** Space between neighbouring slides while swiping, in px. */\nconst SWIPE_GAP = 24;\nconst MAX_ZOOM = 4;\n/** A large screenshot may zoom past MAX_ZOOM up to its own pixels, never beyond this. */\nconst MAX_PIXEL_ZOOM = 8;\nconst DOUBLE_TAP_ZOOM = 2.5;\nconst KEY_ZOOM = 1.5;\nconst DOUBLE_TAP_MS = 300;\nconst DOUBLE_TAP_SLOP = 32;\n/** Travel before a press becomes a drag, so a tap never pans, pages or dismisses. */\nconst DRAG_SLOP = 6;\n/** px/s: a release faster than this commits a swipe or dismiss whatever the distance. */\nconst FLING_VELOCITY = 500;\n/** Share of the stage width a slow swipe must cover to page. */\nconst SWIPE_COMMIT = 0.25;\n/** Share of the stage height a slow drag down must cover to dismiss. */\nconst DISMISS_COMMIT = 0.18;\n/** Seconds of release velocity a pan glides on before settling. */\nconst MOMENTUM = 0.2;\nconst NARROW_VIEWPORT = \"(max-width: 639px)\";\n\ninterface Point {\n\tx: number;\n\ty: number;\n}\ninterface Sample extends Point {\n\tt: number;\n}\n/** The zoom layer's transform: `translate(x, y) scale(s)` about its top-left corner, in stage px. */\ninterface View {\n\ts: number;\n\tx: number;\n\ty: number;\n}\n/** The slide strip's swipe offset, plus the current image's dismiss drag. */\ninterface Offset {\n\tswipe: number;\n\tx: number;\n\ty: number;\n}\ninterface Box {\n\tx: number;\n\ty: number;\n\tw: number;\n\th: number;\n}\n/** Stage geometry for one gesture: its viewport origin and size, the painted image rect at rest, the zoom ceiling. */\ninterface Metrics {\n\tleft: number;\n\ttop: number;\n\tw: number;\n\th: number;\n\tcontent: Box;\n\tmax: number;\n}\ninterface StageControls {\n\tzoom: (step: -1 | 0 | 1) => void;\n}\ntype Stoppable = { stop: () => void };\ntype DragGesture = {\n\tkind: \"press\" | \"pan\" | \"swipe\" | \"dismiss\" | \"hold\";\n\tid: number;\n\tstart: Point;\n\tview: View;\n\toffset: Offset;\n\tmetrics: Metrics | null;\n\tsamples: Sample[];\n\tdismissable: boolean;\n\ttap: boolean;\n};\ntype PinchGesture = { kind: \"pinch\"; distance: number; view: View; anchor: Point; mid: Point; metrics: Metrics };\ntype Gesture = { kind: \"idle\" } | DragGesture | PinchGesture;\n\nconst ORIGIN: Point = { x: 0, y: 0 };\nconst FIT: View = { s: 1, x: 0, y: 0 };\nconst REST: Offset = { swipe: 0, x: 0, y: 0 };\nconst IDLE: Gesture = { kind: \"idle\" };\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));\nconst distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);\nconst midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });\n\n/** Past an edge the content follows less the further it is pulled, and never travels more than `extent`. */\nfunction rubber(overshoot: number, extent: number) {\n\treturn Math.sign(overshoot) * extent * (1 - 1 / ((Math.abs(overshoot) * 0.55) / extent + 1));\n}\n\nfunction resist(value: number, [min, max]: readonly [number, number], extent: number) {\n\tif (value < min) return min + rubber(value - min, extent);\n\tif (value > max) return max + rubber(value - max, extent);\n\treturn value;\n}\n\n/** Where an axis of the zoom layer may sit: centred while the scaled image fits the stage, edge to edge once it is larger. */\nfunction panRange(start: number, size: number, scale: number, length: number): [number, number] {\n\tif (size * scale <= length) {\n\t\tconst centred = length / 2 - scale * (start + size / 2);\n\t\treturn [centred, centred];\n\t}\n\treturn [length - scale * (start + size), -scale * start];\n}\n\nfunction clampView(view: View, metrics: Metrics): View {\n\tconst s = clamp(view.s, 1, metrics.max);\n\t// At rest the layout already centres the image.\n\tif (s === 1) return { ...FIT };\n\tconst [minX, maxX] = panRange(metrics.content.x, metrics.content.w, s, metrics.w);\n\tconst [minY, maxY] = panRange(metrics.content.y, metrics.content.h, s, metrics.h);\n\treturn { s, x: clamp(view.x, minX, maxX), y: clamp(view.y, minY, maxY) };\n}\n\n/** Rescales the zoom layer so the stage point `at` stays under the pointer. */\nfunction zoomAt(view: View, scale: number, at: Point): View {\n\tconst ratio = scale / view.s;\n\treturn { s: scale, x: at.x - (at.x - view.x) * ratio, y: at.y - (at.y - view.y) * ratio };\n}\n\n/** The painted rect of an `object-contain` image of `width` × `height` inside `box`. */\nfunction containBox(box: Box, width: number, height: number): Box {\n\tconst ratio = Math.min(box.w / width, box.h / height);\n\tconst w = width * ratio;\n\tconst h = height * ratio;\n\treturn { x: box.x + (box.w - w) / 2, y: box.y + (box.h - h) / 2, w, h };\n}\n\n/** How long the pointer may rest before release and still fling. */\nconst FLING_IDLE_MS = 80;\n/** How much recent movement the fling estimate reads. */\nconst FLING_WINDOW_MS = 100;\n\n/**\n * Release velocity in px/s: the least-squares slope of x and y against time\n * over the recent samples, so one jittery last event can't dominate. A\n * pointer that rested before letting go has none.\n */\nfunction releaseVelocity(samples: readonly Sample[]): Point {\n\tconst now = performance.now();\n\tconst recent = samples.filter((sample) => now - sample.t <= FLING_WINDOW_MS);\n\tconst newest = recent.at(-1);\n\tif (recent.length < 2 || !newest || now - newest.t > FLING_IDLE_MS) return ORIGIN;\n\tlet meanT = 0;\n\tlet meanX = 0;\n\tlet meanY = 0;\n\tfor (const sample of recent) {\n\t\tmeanT += sample.t / recent.length;\n\t\tmeanX += sample.x / recent.length;\n\t\tmeanY += sample.y / recent.length;\n\t}\n\tlet spread = 0;\n\tlet coX = 0;\n\tlet coY = 0;\n\tfor (const sample of recent) {\n\t\tconst dt = sample.t - meanT;\n\t\tspread += dt * dt;\n\t\tcoX += dt * (sample.x - meanX);\n\t\tcoY += dt * (sample.y - meanY);\n\t}\n\tif (spread === 0) return ORIGIN;\n\t// Slopes are px/ms.\n\treturn { x: (coX / spread) * 1000, y: (coY / spread) * 1000 };\n}\n\n/** Wheel deltas in px, whatever unit the device reports. */\nfunction wheelPixels(event: WheelEvent): Point {\n\tconst unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? window.innerHeight : 1;\n\treturn { x: event.deltaX * unit, y: event.deltaY * unit };\n}\n\ninterface ViewerStageProps {\n\timage: LightboxImage;\n\tscrimRef: RefObject<HTMLSpanElement | null>;\n\tcontrolsRef: RefObject<StageControls | null>;\n}\n\n/** The image stage: zoom, pan, swipe paging and drag to dismiss over the morphing image. */\nfunction ViewerStage({ image, scrimRef, controlsRef }: ViewerStageProps) {\n\tconst { images, index, groupId, reduce, select, move } = useViewerContext(\"ImageViewerContent\");\n\tconst stageRef = useRef<HTMLDivElement>(null);\n\tconst trackRef = useRef<HTMLDivElement>(null);\n\tconst liftRef = useRef<HTMLDivElement>(null);\n\tconst zoomRef = useRef<HTMLDivElement>(null);\n\tconst imgRef = useRef<HTMLImageElement>(null);\n\t// Mutable gesture state lives outside React; `paint` writes it to the DOM.\n\tconst [view] = useState<View>(() => ({ ...FIT }));\n\tconst [offset] = useState<Offset>(() => ({ ...REST }));\n\tconst [pointers] = useState(() => new Map<number, Point>());\n\tconst stageHeight = useRef(1);\n\tconst gesture = useRef<Gesture>(IDLE);\n\tconst lastTap = useRef<Sample | null>(null);\n\tconst committing = useRef(false);\n\tconst viewAnimations = useRef<Stoppable[]>([]);\n\tconst offsetAnimations = useRef<Stoppable[]>([]);\n\t// How the current image arrived: the thumbnail morph, a fade after paging, or already in place after a swipe.\n\tconst [swiped, setSwiped] = useState<{ from: string; to: string } | null>(null);\n\tconst [entry, setEntry] = useState<{ id: string; via: \"open\" | \"page\" | \"swipe\" }>({ id: image.id, via: \"open\" });\n\tif (entry.id !== image.id) {\n\t\tsetEntry({ id: image.id, via: swiped?.from === entry.id && swiped.to === image.id ? \"swipe\" : \"page\" });\n\t}\n\n\tconst paint = () => {\n\t\tconst { s, x, y } = view;\n\t\tconst zoomed = s > 1.001;\n\t\tconst pull = offset.y > 0 ? Math.min(1, offset.y / stageHeight.current) : 0;\n\t\tif (zoomRef.current) zoomRef.current.style.transform = s === 1 && x === 0 && y === 0 ? \"\" : `translate3d(${x}px, ${y}px, 0) scale(${s})`;\n\t\tif (trackRef.current) trackRef.current.style.transform = offset.swipe === 0 ? \"\" : `translate3d(${offset.swipe}px, 0, 0)`;\n\t\tif (liftRef.current) {\n\t\t\tliftRef.current.style.transform =\n\t\t\t\toffset.x === 0 && offset.y === 0 ? \"\" : `translate3d(${offset.x}px, ${offset.y}px, 0) scale(${1 - pull * 0.35})`;\n\t\t}\n\t\tif (scrimRef.current) scrimRef.current.style.opacity = pull === 0 ? \"\" : String(1 - Math.min(1, pull * 1.6));\n\t\tconst stage = stageRef.current;\n\t\tif (!stage) return;\n\t\t// A zoomed image stays inside the stage so the header and footer controls stay legible.\n\t\tstage.style.overflow = zoomed ? \"hidden\" : \"\";\n\t\tconst cursor = gesture.current.kind === \"pan\" ? \"grabbing\" : zoomed ? \"grab\" : \"\";\n\t\tif (stage.dataset.cursor !== cursor) stage.dataset.cursor = cursor;\n\t};\n\n\tconst measure = (): Metrics | null => {\n\t\tconst stage = stageRef.current;\n\t\tif (!stage) return null;\n\t\tconst rect = stage.getBoundingClientRect();\n\t\tconst w = stage.clientWidth;\n\t\tconst h = stage.clientHeight;\n\t\tstageHeight.current = Math.max(1, h);\n\t\t// Before the image loads (and without intrinsic dimensions) the whole stage stands in for it.\n\t\tlet content: Box = { x: 0, y: 0, w, h };\n\t\tlet max = MAX_ZOOM;\n\t\tconst img = imgRef.current;\n\t\tif (img && img.offsetWidth > 0 && img.offsetHeight > 0) {\n\t\t\t// offset* ignore transforms, so this is the rest rect even mid-zoom or mid-morph.\n\t\t\tconst box = { x: img.offsetLeft, y: img.offsetTop, w: img.offsetWidth, h: img.offsetHeight };\n\t\t\tconst naturalWidth = img.naturalWidth || image.width || 0;\n\t\t\tconst naturalHeight = img.naturalHeight || image.height || 0;\n\t\t\tcontent = naturalWidth > 0 && naturalHeight > 0 ? containBox(box, naturalWidth, naturalHeight) : box;\n\t\t\tif (img.naturalWidth > 0) max = clamp(img.naturalWidth / content.w, MAX_ZOOM, MAX_PIXEL_ZOOM);\n\t\t}\n\t\treturn { left: rect.left, top: rect.top, w, h, content, max };\n\t};\n\n\tconst stop = (animations: RefObject<Stoppable[]>) => {\n\t\tfor (const animation of animations.current) animation.stop();\n\t\tanimations.current = [];\n\t};\n\n\t/** Springs the zoom layer to `target`; reduced motion jumps there. */\n\tconst settleView = (target: View, velocity: Point = ORIGIN) => {\n\t\tstop(viewAnimations);\n\t\tif (reduce) {\n\t\t\tObject.assign(view, target);\n\t\t\tpaint();\n\t\t\treturn;\n\t\t}\n\t\tviewAnimations.current = ([\"s\", \"x\", \"y\"] as const)\n\t\t\t.filter((key) => view[key] !== target[key])\n\t\t\t.map((key) =>\n\t\t\t\tanimate(view[key], target[key], {\n\t\t\t\t\t...SPRING_LAYOUT,\n\t\t\t\t\tvelocity: key === \"s\" ? 0 : velocity[key],\n\t\t\t\t\tonUpdate: (latest) => {\n\t\t\t\t\t\tview[key] = latest;\n\t\t\t\t\t\tpaint();\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t};\n\n\t/** Springs the swipe and dismiss offsets to `target`, then calls `done`; reduced motion jumps there. */\n\tconst settleOffset = (target: Offset, velocity: Point = ORIGIN, done?: () => void) => {\n\t\tstop(offsetAnimations);\n\t\tconst keys = ([\"swipe\", \"x\", \"y\"] as const).filter((key) => offset[key] !== target[key]);\n\t\tif (reduce || keys.length === 0) {\n\t\t\tObject.assign(offset, target);\n\t\t\tpaint();\n\t\t\tdone?.();\n\t\t\treturn;\n\t\t}\n\t\tlet remaining = keys.length;\n\t\toffsetAnimations.current = keys.map((key) =>\n\t\t\tanimate(offset[key], target[key], {\n\t\t\t\t...SPRING_LAYOUT,\n\t\t\t\tvelocity: key === \"y\" ? velocity.y : velocity.x,\n\t\t\t\tonUpdate: (latest) => {\n\t\t\t\t\toffset[key] = latest;\n\t\t\t\t\tpaint();\n\t\t\t\t},\n\t\t\t\tonComplete: () => {\n\t\t\t\t\tremaining -= 1;\n\t\t\t\t\tif (remaining === 0) done?.();\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t};\n\n\tconst restore = (metrics: Metrics) => {\n\t\tsettleView(clampView(view, metrics));\n\t\tsettleOffset(REST);\n\t};\n\n\tconst press = (id: number, point: Point, dismissable: boolean, tap: boolean) => {\n\t\tgesture.current = {\n\t\t\tkind: \"press\",\n\t\t\tid,\n\t\t\tstart: point,\n\t\t\tview: { ...view },\n\t\t\toffset: { ...offset },\n\t\t\tmetrics: measure(),\n\t\t\tsamples: [{ ...point, t: performance.now() }],\n\t\t\tdismissable,\n\t\t\ttap,\n\t\t};\n\t};\n\n\tconst beginPinch = () => {\n\t\tconst [a, b] = Array.from(pointers.values());\n\t\tconst metrics = measure();\n\t\tif (!a || !b || !metrics) return;\n\t\tstop(viewAnimations);\n\t\tstop(offsetAnimations);\n\t\t// Pinch maths assume the slide sits at rest.\n\t\tObject.assign(offset, REST);\n\t\tlastTap.current = null;\n\t\tconst centre = midpoint(a, b);\n\t\tconst mid = { x: centre.x - metrics.left, y: centre.y - metrics.top };\n\t\tgesture.current = {\n\t\t\tkind: \"pinch\",\n\t\t\tdistance: Math.max(1, distance(a, b)),\n\t\t\tview: { ...view },\n\t\t\tanchor: { x: (mid.x - view.x) / view.s, y: (mid.y - view.y) / view.s },\n\t\t\tmid,\n\t\t\tmetrics,\n\t\t};\n\t\tpaint();\n\t};\n\n\tconst finishPinch = (pinch: PinchGesture) => {\n\t\tconst s = clamp(view.s, 1, pinch.metrics.max);\n\t\tsettleView(s === 1 ? FIT : clampView(zoomAt(view, s, pinch.mid), pinch.metrics));\n\t};\n\n\t/** A tap off the image closes; a second tap on it toggles between fit and DOUBLE_TAP_ZOOM around the pointer. */\n\tconst tap = (point: Point, metrics: Metrics) => {\n\t\tconst at = { x: point.x - metrics.left, y: point.y - metrics.top };\n\t\tconst { content } = metrics;\n\t\tconst left = view.x + view.s * content.x;\n\t\tconst top = view.y + view.s * content.y;\n\t\tconst onImage = at.x >= left && at.x <= left + view.s * content.w && at.y >= top && at.y <= top + view.s * content.h;\n\t\tif (!onImage) {\n\t\t\tlastTap.current = null;\n\t\t\tselect(null);\n\t\t\treturn;\n\t\t}\n\t\tconst now = performance.now();\n\t\tconst last = lastTap.current;\n\t\tif (last && now - last.t < DOUBLE_TAP_MS && distance(last, point) < DOUBLE_TAP_SLOP) {\n\t\t\tlastTap.current = null;\n\t\t\tsettleView(view.s > 1.001 ? FIT : clampView(zoomAt(view, Math.min(DOUBLE_TAP_ZOOM, metrics.max), at), metrics));\n\t\t\treturn;\n\t\t}\n\t\tlastTap.current = { ...point, t: now };\n\t\trestore(metrics);\n\t};\n\n\tconst releaseSwipe = (metrics: Metrics, velocity: Point) => {\n\t\tconst shift = offset.swipe;\n\t\tconst direction: -1 | 1 = shift < 0 ? 1 : -1;\n\t\tconst target = images[index + direction];\n\t\tconst flung = Math.abs(velocity.x) > FLING_VELOCITY;\n\t\tconst commit = shift !== 0 && (flung ? Math.sign(velocity.x) === Math.sign(shift) : Math.abs(shift) > metrics.w * SWIPE_COMMIT);\n\t\tif (!target || !commit) {\n\t\t\tsettleOffset(REST, velocity);\n\t\t\treturn;\n\t\t}\n\t\tcommitting.current = true;\n\t\tsettleOffset({ swipe: -direction * (metrics.w + SWIPE_GAP), x: 0, y: 0 }, velocity, () => {\n\t\t\tsetSwiped({ from: image.id, to: target.id });\n\t\t\tmove(direction);\n\t\t});\n\t};\n\n\tconst releaseDismiss = (metrics: Metrics, velocity: Point) => {\n\t\tconst pulled = offset.y > 0 && velocity.y > -FLING_VELOCITY;\n\t\tif (pulled && (offset.y > metrics.h * DISMISS_COMMIT || velocity.y > FLING_VELOCITY)) {\n\t\t\t// The exit morph starts from wherever the drag left the image.\n\t\t\tcommitting.current = true;\n\t\t\tselect(null);\n\t\t\treturn;\n\t\t}\n\t\tsettleOffset(REST, velocity);\n\t};\n\n\tconst onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n\t\tif (committing.current || (event.pointerType === \"mouse\" && event.button !== 0)) return;\n\t\tconst point = { x: event.clientX, y: event.clientY };\n\t\tpointers.set(event.pointerId, point);\n\t\tevent.currentTarget.setPointerCapture(event.pointerId);\n\t\tif (pointers.size === 2) beginPinch();\n\t\telse if (pointers.size === 1) {\n\t\t\tpress(event.pointerId, point, event.pointerType === \"touch\" || window.matchMedia(NARROW_VIEWPORT).matches, true);\n\t\t}\n\t};\n\n\tconst onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n\t\tif (!pointers.has(event.pointerId)) return;\n\t\tconst point = { x: event.clientX, y: event.clientY };\n\t\tpointers.set(event.pointerId, point);\n\t\tconst g = gesture.current;\n\t\tif (g.kind === \"pinch\") {\n\t\t\tconst [a, b] = Array.from(pointers.values());\n\t\t\tif (!a || !b) return;\n\t\t\tconst { max } = g.metrics;\n\t\t\tconst raw = (g.view.s * distance(a, b)) / g.distance;\n\t\t\tconst s = raw < 1 ? 1 + rubber(raw - 1, 0.5) : raw > max ? max + rubber(raw - max, max / 2) : raw;\n\t\t\tconst mid = midpoint(a, b);\n\t\t\tg.mid = { x: mid.x - g.metrics.left, y: mid.y - g.metrics.top };\n\t\t\tview.s = s;\n\t\t\tview.x = g.mid.x - s * g.anchor.x;\n\t\t\tview.y = g.mid.y - s * g.anchor.y;\n\t\t\tpaint();\n\t\t\treturn;\n\t\t}\n\t\tif (g.kind === \"idle\" || g.id !== event.pointerId) return;\n\t\tg.samples.push({ ...point, t: performance.now() });\n\t\tif (g.samples.length > 24) g.samples.shift();\n\t\tif (g.kind === \"press\") {\n\t\t\tconst dx = point.x - g.start.x;\n\t\t\tconst dy = point.y - g.start.y;\n\t\t\tif (Math.hypot(dx, dy) < DRAG_SLOP) return;\n\t\t\tg.tap = false;\n\t\t\tlastTap.current = null;\n\t\t\tif (view.s > 1.001) g.kind = \"pan\";\n\t\t\telse if (Math.abs(dx) > Math.abs(dy)) g.kind = images.length > 1 ? \"swipe\" : \"hold\";\n\t\t\telse g.kind = g.dismissable && dy > 0 ? \"dismiss\" : \"hold\";\n\t\t\t// Catch whatever is still settling and drag it from where it is.\n\t\t\tif (g.kind === \"pan\") stop(viewAnimations);\n\t\t\telse stop(offsetAnimations);\n\t\t\tg.view = { ...view };\n\t\t\tg.offset = { ...offset };\n\t\t\tg.start = point;\n\t\t\tg.metrics ??= measure();\n\t\t\tpaint();\n\t\t\treturn;\n\t\t}\n\t\tconst metrics = g.metrics;\n\t\tif (!metrics) return;\n\t\tconst dx = point.x - g.start.x;\n\t\tconst dy = point.y - g.start.y;\n\t\tif (g.kind === \"pan\") {\n\t\t\tconst { content } = metrics;\n\t\t\tview.x = resist(g.view.x + dx, panRange(content.x, content.w, g.view.s, metrics.w), metrics.w);\n\t\t\tview.y = resist(g.view.y + dy, panRange(content.y, content.h, g.view.s, metrics.h), metrics.h);\n\t\t} else if (g.kind === \"swipe\") {\n\t\t\tconst next = g.offset.swipe + dx;\n\t\t\tconst blocked = next > 0 ? index <= 0 : index >= images.length - 1;\n\t\t\toffset.swipe = blocked ? rubber(next, metrics.w) : next;\n\t\t} else if (g.kind === \"dismiss\") {\n\t\t\tconst next = g.offset.y + dy;\n\t\t\toffset.x = g.offset.x + dx;\n\t\t\toffset.y = next < 0 ? rubber(next, metrics.h) : next;\n\t\t} else return;\n\t\tpaint();\n\t};\n\n\tconst release = (event: ReactPointerEvent<HTMLDivElement>, cancelled: boolean) => {\n\t\tif (!pointers.delete(event.pointerId)) return;\n\t\tconst g = gesture.current;\n\t\tif (g.kind === \"pinch\") {\n\t\t\tif (pointers.size >= 2) {\n\t\t\t\tbeginPinch();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinishPinch(g);\n\t\t\tconst [rest] = Array.from(pointers.entries());\n\t\t\tif (rest) press(rest[0], rest[1], false, false);\n\t\t\telse gesture.current = IDLE;\n\t\t\treturn;\n\t\t}\n\t\tif (g.kind === \"idle\" || g.id !== event.pointerId) return;\n\t\tgesture.current = IDLE;\n\t\tpaint();\n\t\tconst metrics = g.metrics ?? measure();\n\t\tif (!metrics) return;\n\t\tconst velocity = cancelled || reduce ? ORIGIN : releaseVelocity(g.samples);\n\t\tif (g.kind === \"press\") {\n\t\t\tif (g.tap && !cancelled) tap({ x: event.clientX, y: event.clientY }, metrics);\n\t\t\telse restore(metrics);\n\t\t} else if (g.kind === \"pan\") {\n\t\t\tconst glide = { s: view.s, x: view.x + velocity.x * MOMENTUM, y: view.y + velocity.y * MOMENTUM };\n\t\t\tsettleView(clampView(glide, metrics), velocity);\n\t\t} else if (g.kind === \"swipe\") releaseSwipe(metrics, velocity);\n\t\telse if (g.kind === \"dismiss\") releaseDismiss(metrics, velocity);\n\t\telse restore(metrics);\n\t};\n\n\tconst onWheel = (event: WheelEvent) => {\n\t\t// Nothing behind the viewer scrolls; keep trackpad swipes from navigating the page.\n\t\tevent.preventDefault();\n\t\tif (committing.current || gesture.current.kind !== \"idle\") return;\n\t\tconst zooming = event.ctrlKey || event.metaKey;\n\t\tif (!zooming && view.s <= 1.001) return;\n\t\tconst metrics = measure();\n\t\tif (!metrics) return;\n\t\tstop(viewAnimations);\n\t\tconst delta = wheelPixels(event);\n\t\tconst next = zooming\n\t\t\t? zoomAt(view, clamp(view.s * Math.exp(-clamp(delta.y, -40, 40) * 0.01), 1, metrics.max), {\n\t\t\t\t\tx: event.clientX - metrics.left,\n\t\t\t\t\ty: event.clientY - metrics.top,\n\t\t\t\t})\n\t\t\t: { s: view.s, x: view.x - delta.x, y: view.y - delta.y };\n\t\tObject.assign(view, clampView(next, metrics));\n\t\tpaint();\n\t};\n\n\tconst onResize = () => {\n\t\tif (committing.current) return;\n\t\tstop(viewAnimations);\n\t\tstop(offsetAnimations);\n\t\tObject.assign(view, FIT);\n\t\tObject.assign(offset, REST);\n\t\tpaint();\n\t};\n\n\t/** Keyboard zoom about the stage centre: 1 in, -1 out, 0 back to fit. */\n\tconst zoomStep = (step: -1 | 0 | 1) => {\n\t\tconst metrics = measure();\n\t\tif (!metrics || committing.current) return;\n\t\tconst s = step === 0 ? 1 : clamp(view.s * KEY_ZOOM ** step, 1, metrics.max);\n\t\tsettleView(s === 1 ? FIT : clampView(zoomAt(view, s, { x: metrics.w / 2, y: metrics.h / 2 }), metrics));\n\t};\n\n\t// A new image starts at fit with the strip at rest. Runs before paint, so a committed swipe lands seamlessly:\n\t// the neighbour that slid into the centre is replaced by the same picture at the same spot.\n\tuseLayoutEffect(() => {\n\t\tstop(viewAnimations);\n\t\tstop(offsetAnimations);\n\t\tObject.assign(view, FIT);\n\t\tObject.assign(offset, REST);\n\t\tgesture.current = IDLE;\n\t\tpointers.clear();\n\t\tlastTap.current = null;\n\t\tcommitting.current = false;\n\t\tpaint();\n\t}, [image.id]);\n\n\tconst handlers = useRef({ wheel: onWheel, resize: onResize });\n\tuseLayoutEffect(() => {\n\t\thandlers.current = { wheel: onWheel, resize: onResize };\n\t\tcontrolsRef.current = { zoom: zoomStep };\n\t});\n\tuseEffect(() => {\n\t\tconst stage = stageRef.current;\n\t\t// React's wheel listener is passive, and Ctrl+wheel must not zoom the page.\n\t\tconst wheel = (event: WheelEvent) => handlers.current.wheel(event);\n\t\tconst resize = () => handlers.current.resize();\n\t\tstage?.addEventListener(\"wheel\", wheel, { passive: false });\n\t\twindow.addEventListener(\"resize\", resize);\n\t\treturn () => {\n\t\t\tstage?.removeEventListener(\"wheel\", wheel);\n\t\t\twindow.removeEventListener(\"resize\", resize);\n\t\t\tfor (const animation of [...viewAnimations.current, ...offsetAnimations.current]) animation.stop();\n\t\t\tcontrolsRef.current = null;\n\t\t};\n\t}, [controlsRef]);\n\n\tconst previous = images[index - 1];\n\tconst next = images[index + 1];\n\treturn (\n\t\t<div\n\t\t\tref={stageRef}\n\t\t\tdata-lightbox-content=\"\"\n\t\t\tclassName=\"group/stage relative min-h-0 flex-1 touch-none select-none\"\n\t\t\tonPointerDown={onPointerDown}\n\t\t\tonPointerMove={onPointerMove}\n\t\t\tonPointerUp={(event) => release(event, false)}\n\t\t\tonPointerCancel={(event) => release(event, true)}\n\t\t\tonLostPointerCapture={(event) => release(event, true)}\n\t\t>\n\t\t\t<div ref={trackRef} className=\"absolute inset-0\">\n\t\t\t\t{previous && <ViewerNeighbor image={previous} side=\"previous\" />}\n\t\t\t\t<div ref={liftRef} className=\"absolute inset-0\">\n\t\t\t\t\t<div ref={zoomRef} className=\"absolute inset-0 flex origin-top-left items-center justify-center\">\n\t\t\t\t\t\t<m.img\n\t\t\t\t\t\t\tkey={image.id}\n\t\t\t\t\t\t\tref={imgRef}\n\t\t\t\t\t\t\tlayoutId={reduce ? undefined : `${groupId}-${image.id}`}\n\t\t\t\t\t\t\tinitial={entry.via === \"swipe\" ? false : { opacity: 0 }}\n\t\t\t\t\t\t\tanimate={{ opacity: 1 }}\n\t\t\t\t\t\t\texit={reduce ? { opacity: 0 } : undefined}\n\t\t\t\t\t\t\tsrc={image.src}\n\t\t\t\t\t\t\talt={image.alt}\n\t\t\t\t\t\t\twidth={image.width}\n\t\t\t\t\t\t\theight={image.height}\n\t\t\t\t\t\t\tdraggable={false}\n\t\t\t\t\t\t\t// Only opening morphs from the thumbnail; a paged or swiped image is placed at once.\n\t\t\t\t\t\t\ttransition={\n\t\t\t\t\t\t\t\treduce\n\t\t\t\t\t\t\t\t\t? { duration: 0.1, ease: EASE_OUT }\n\t\t\t\t\t\t\t\t\t: entry.via === \"open\"\n\t\t\t\t\t\t\t\t\t\t? SPRING_LAYOUT\n\t\t\t\t\t\t\t\t\t\t: { ...SPRING_LAYOUT, layout: { duration: 0 } }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdata-lightbox-content=\"\"\n\t\t\t\t\t\t\tclassName=\"max-h-full max-w-full cursor-zoom-in rounded-lg object-contain select-none group-data-[cursor=grab]/stage:cursor-grab group-data-[cursor=grabbing]/stage:cursor-grabbing\"\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t{next && <ViewerNeighbor image={next} side=\"next\" />}\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n\n/** The adjacent image, parked one stage width away so a swipe drags it into view. */\nfunction ViewerNeighbor({ image, side }: { image: LightboxImage; side: \"previous\" | \"next\" }) {\n\tconst gap = `calc(100% + ${SWIPE_GAP}px)`;\n\treturn (\n\t\t<div\n\t\t\taria-hidden=\"true\"\n\t\t\tclassName=\"pointer-events-none absolute inset-y-0 flex w-full items-center justify-center\"\n\t\t\tstyle={side === \"previous\" ? { right: gap } : { left: gap }}\n\t\t>\n\t\t\t<img\n\t\t\t\tsrc={image.src}\n\t\t\t\talt=\"\"\n\t\t\t\twidth={image.width}\n\t\t\t\theight={image.height}\n\t\t\t\tdraggable={false}\n\t\t\t\tclassName=\"max-h-full max-w-full rounded-lg object-contain select-none\"\n\t\t\t/>\n\t\t</div>\n\t);\n}\n",
      "type": "registry:ui"
    }
  ],
  "docs": "Install @khaeli/foundation first: this item's styling lives in its tokens and [data-slot] rules.",
  "type": "registry:ui"
}