{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "lightbox",
  "type": "registry:ui",
  "title": "Lightbox",
  "description": "A full-screen viewer for a set of pictures (or any media the project renders): swipe or arrow between slides, zoom and pan, a counter, captions, thumbnails, and the picture growing out of the thumbnail that opened it.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react",
    "radix-ui"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/direction",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/lightbox.tsx",
      "type": "registry:ui",
      "target": "components/ui/lightbox.tsx",
      "content": "\"use client\";\n/**\n * @name lightbox\n * @category ui\n * @description A full-screen viewer for a set of pictures (or any media the project renders): swipe or arrow between slides, zoom and pan, a counter, captions, thumbnails, and the picture growing out of the thumbnail that opened it.\n * @when Looking closely at pictures that are shown small on the page: a listing's photos, a portfolio, attachments. It is a modal dialog, so focus is held inside and returns to the thumbnail of the picture shown when it closes. For a grid of thumbnails that opens it use gallery (GalleryLightbox does both). For one picture with text beside it use dialog; for a row of cards that scroll in the page use a scroll-snap row, not a lightbox. Always give it a LightboxTitle (className=\"sr-only\" hides it) and say how many slides there are with `count`.\n * @example\n * <Lightbox count={photos.length}>\n *   {photos.map((photo, index) => (\n *     <LightboxTrigger key={photo.src} index={index} aria-label={`Open picture: ${photo.alt}`}>\n *       <img src={photo.thumb} alt=\"\" className=\"size-24 rounded-control object-cover\" />\n *     </LightboxTrigger>\n *   ))}\n *   <LightboxContent>\n *     <LightboxHeader>\n *       <LightboxTitle className=\"sr-only\">Photos</LightboxTitle>\n *       <LightboxCounter />\n *       <LightboxZoom className=\"ms-auto\" />\n *       <LightboxClose />\n *     </LightboxHeader>\n *     <LightboxStage>\n *       <LightboxViewport>\n *         {photos.map((photo, index) => (\n *           <LightboxSlide key={photo.src} index={index}>\n *             <img src={photo.src} alt={photo.alt} className=\"max-h-full max-w-full object-contain\" />\n *           </LightboxSlide>\n *         ))}\n *       </LightboxViewport>\n *       <LightboxPrevious />\n *       <LightboxNext />\n *     </LightboxStage>\n *   </LightboxContent>\n * </Lightbox>\n */\nimport { Dialog as DialogPrimitive, Slot } from \"radix-ui\";\nimport { ChevronLeft, ChevronRight, X, ZoomIn, ZoomOut } from \"lucide-react\";\nimport {\n  createContext,\n  use,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { inlineStep } from \"@/lib/direction\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\ntype Zoom = { scale: number; x: number; y: number };\nconst NO_ZOOM: Zoom = { scale: 1, x: 0, y: 0 };\n/** What one press of a zoom button, or one + or - key, multiplies the scale by. */\nconst ZOOM_STEP = 1.5;\n/** The scale a double click or double tap goes to. */\nconst ZOOM_DOUBLE = 2.5;\n\ntype LightboxContextValue = {\n  open: boolean;\n  count: number;\n  index: number;\n  loop: boolean;\n  maxZoom: number;\n  zoom: Zoom;\n  /** True when open and close run as a view transition: the dialog's own fade is then switched off. */\n  viaTransition: boolean;\n  /** The view-transition-name shared by a thumbnail and its slide. */\n  transitionName: string;\n  formatPosition: (current: number, total: number) => string;\n  viewportRef: RefObject<HTMLDivElement | null>;\n  surfaceRef: RefObject<HTMLDivElement | null>;\n  registerTrigger: (index: number, element: HTMLElement | null) => void;\n  focusTrigger: () => void;\n  openAt: (index: number) => void;\n  /** Shows a slide. Out of range wraps round with `loop` and is ignored without. */\n  go: (index: number) => void;\n  /** Follows the track after a swipe: sets the index without scrolling again. */\n  settle: (index: number) => void;\n  /** Sets the scale, keeping the point `origin` (in viewport coordinates) under the pointer. `say` announces the new level. */\n  zoomTo: (scale: number, options?: { origin?: { x: number; y: number }; say?: boolean }) => void;\n  panTo: (x: number, y: number) => void;\n};\n\nconst LightboxContext = createContext<LightboxContextValue | null>(null);\n\n/** The lightbox's state, for a part the project writes itself: a caption for the current slide, a download button. */\nexport function useLightbox(part = \"useLightbox\"): LightboxContextValue {\n  const context = use(LightboxContext);\n  if (!context) throw new Error(`<${part}> must be used inside <Lightbox>.`);\n  return context;\n}\n\nconst canTransition = (): boolean =>\n  typeof document !== \"undefined\" && typeof document.startViewTransition === \"function\" && !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\nconst reducedMotion = (): boolean => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n/** The slide whose centre is nearest the centre of the track: the one in view. Works in both directions. */\nfunction nearestSlide(viewport: HTMLElement): number {\n  const box = viewport.getBoundingClientRect();\n  const centre = box.left + box.width / 2;\n  let best = -1;\n  let distance = Number.POSITIVE_INFINITY;\n  for (const slide of viewport.querySelectorAll<HTMLElement>(\":scope > [data-slot=lightbox-slide]\")) {\n    const rect = slide.getBoundingClientRect();\n    const away = Math.abs(rect.left + rect.width / 2 - centre);\n    if (away < distance) {\n      distance = away;\n      best = Number(slide.dataset[\"index\"]);\n    }\n  }\n  return best;\n}\n\nexport type LightboxProps = {\n  /** How many slides there are. */\n  count: number;\n  open?: boolean;\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** The slide shown, from 0. */\n  index?: number;\n  defaultIndex?: number;\n  onIndexChange?: (index: number) => void;\n  /** Going past the last slide comes back to the first. Default false: the buttons are disabled at the ends. */\n  loop?: boolean;\n  /** The largest scale zoom reaches. Default 4. */\n  maxZoom?: number;\n  /**\n   * Open and close as a shared-element transition: the picture grows out of its thumbnail and shrinks back\n   * into it (the browser's View Transitions API; a plain fade where that is missing or motion is reduced).\n   * Default true.\n   */\n  sharedTransition?: boolean;\n  /** The words for a position: the counter's text and each slide's name. Default \"3 of 12\". */\n  formatPosition?: (current: number, total: number) => string;\n  /** What is announced when the zoom buttons or keys change the scale. Default \"Zoom 150%\". */\n  formatZoom?: (percent: number) => string;\n  children?: ReactNode;\n};\n\n/**\n * Holds the state: whether it is open, which slide is shown, and the zoom of that slide. Open and index are\n * each controlled (`open` / `index`) or uncontrolled (`defaultOpen` / `defaultIndex`).\n *\n * The shared-element transition uses `document.startViewTransition` directly, because the thumbnail stays\n * mounted while the dialog opens (React's <ViewTransition> shares between an element that unmounts and one\n * that mounts). Do not run it inside a React transition that also animates <ViewTransition> components.\n */\nexport function Lightbox({\n  count,\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  index,\n  defaultIndex = 0,\n  onIndexChange,\n  loop = false,\n  maxZoom = 4,\n  sharedTransition = true,\n  formatPosition = (current, total) => `${current} of ${total}`,\n  formatZoom = (percent) => `Zoom ${percent}%`,\n  children,\n}: LightboxProps) {\n  const [isOpen, setOpen] = useControllableState({ value: open, defaultValue: defaultOpen, onChange: onOpenChange });\n  const [current, setCurrent] = useControllableState({ value: index, defaultValue: defaultIndex, onChange: onIndexChange });\n  // The zoom belongs to one slide: it is dropped as soon as another slide is shown.\n  const [zoomState, setZoomState] = useState<Zoom & { index: number }>({ ...NO_ZOOM, index: -1 });\n  const [viaTransition, setViaTransition] = useState(false);\n  /** Every trigger of each slide: one picture may have two (a tile in a grid and another in a row that scrolls). */\n  const triggers = useRef(new Map<number, Set<HTMLElement>>());\n  const opener = useRef(0);\n  /** A wait for a trigger to become reachable, so that a newer one can replace it. */\n  const focusWait = useRef(0);\n  /** The triggers of a slide that are drawn, the ones a person can reach first. */\n  const triggersOf = (at: number): HTMLElement[] => {\n    const all = triggers.current.get(at);\n    if (!all) return [];\n    // A trigger that has left the page is forgotten here: a ref is not told which element went.\n    for (const element of all) if (!element.isConnected) all.delete(element);\n    const drawn = [...all].filter((element) => element.getClientRects().length > 0);\n    // In view and reachable first, then reachable, then the rest.\n    const rank = (element: HTMLElement): number => (reachable(element) ? (inView(element) ? 0 : 1) : 2);\n    return drawn.sort((a, b) => rank(a) - rank(b));\n  };\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const surfaceRef = useRef<HTMLDivElement>(null);\n  const transitionName = `rui-lightbox-${useId().replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n\n  const shown = Math.min(Math.max(0, current), Math.max(0, count - 1));\n  const zoom = zoomState.index === shown ? zoomState : NO_ZOOM;\n\n  const changeOpen = (next: boolean, at: number): void => {\n    const apply = (via: boolean): void => {\n      setViaTransition(via);\n      if (next) setCurrent(at);\n      else setZoomState({ ...NO_ZOOM, index: -1 });\n      setOpen(next);\n    };\n    if (!sharedTransition || !canTransition()) {\n      apply(false);\n      return;\n    }\n    // The thumbnail carries the shared name in the view without the dialog; the slide carries it in the view with it.\n    const trigger = triggersOf(at)[0];\n    const thumbnail = trigger?.isConnected ? (trigger.querySelector<HTMLElement>(\"img, [data-lightbox-shared]\") ?? trigger) : null;\n    if (next && thumbnail) thumbnail.style.viewTransitionName = transitionName;\n    const transition = document.startViewTransition(() => {\n      flushSync(() => apply(true));\n      if (thumbnail) thumbnail.style.viewTransitionName = next ? \"\" : transitionName;\n    });\n    const clear = (): void => {\n      if (thumbnail) thumbnail.style.viewTransitionName = \"\";\n    };\n    transition.finished.then(clear, clear);\n  };\n\n  const go = (target: number): void => {\n    if (count === 0) return;\n    const next = loop ? ((target % count) + count) % count : target;\n    if (next < 0 || next > count - 1) return;\n    setCurrent(next);\n  };\n\n  const clampOffset = (scale: number, x: number, y: number): Zoom => {\n    const surface = surfaceRef.current;\n    const slide = surface?.parentElement;\n    if (!surface || !slide || scale <= 1) return NO_ZOOM;\n    const maxX = Math.max(0, (surface.offsetWidth * scale - slide.clientWidth) / 2);\n    const maxY = Math.max(0, (surface.offsetHeight * scale - slide.clientHeight) / 2);\n    return { scale, x: Math.min(maxX, Math.max(-maxX, x)), y: Math.min(maxY, Math.max(-maxY, y)) };\n  };\n\n  const zoomTo: LightboxContextValue[\"zoomTo\"] = (target, options) => {\n    const slide = surfaceRef.current?.parentElement;\n    if (!slide) return;\n    const scale = Math.min(maxZoom, Math.max(1, target));\n    const box = slide.getBoundingClientRect();\n    // The point to keep still, measured from the centre of the slide (the transform's origin).\n    const px = options?.origin ? options.origin.x - (box.left + box.width / 2) : 0;\n    const py = options?.origin ? options.origin.y - (box.top + box.height / 2) : 0;\n    const ratio = scale / zoom.scale;\n    setZoomState({ ...clampOffset(scale, px - (px - zoom.x) * ratio, py - (py - zoom.y) * ratio), index: shown });\n    if (options?.say && scale !== zoom.scale) announce(formatZoom(Math.round(scale * 100)));\n  };\n\n  const context: LightboxContextValue = {\n    open: isOpen,\n    count,\n    index: shown,\n    loop,\n    maxZoom,\n    zoom,\n    viaTransition,\n    transitionName,\n    formatPosition,\n    viewportRef,\n    surfaceRef,\n    registerTrigger: (at, element) => {\n      if (!element) return;\n      // An element is the trigger of one slide: a tile whose index changed leaves its old one.\n      for (const [index, all] of triggers.current) if (index !== at) all.delete(element);\n      const all = triggers.current.get(at) ?? new Set<HTMLElement>();\n      all.add(element);\n      triggers.current.set(at, all);\n    },\n    focusTrigger: () => {\n      window.cancelAnimationFrame(focusWait.current);\n      // The trigger of the slide shown, else the one that opened; of two for one slide, the one in view.\n      const target = [...triggersOf(shown), ...triggersOf(opener.current)][0];\n      if (!target) return;\n      if (reachable(target)) {\n        target.focus();\n        return;\n      }\n      // It is inside something inert because it is out of view (a slide of a carousel): bring it into\n      // view, and focus it once whatever made it inert has let go.\n      target.scrollIntoView({ block: \"nearest\", inline: \"nearest\", behavior: \"instant\" });\n      let frames = 0;\n      const attempt = (): void => {\n        frames += 1;\n        if (!target.isConnected) return;\n        if (reachable(target) || frames >= FOCUS_WAIT_FRAMES) target.focus();\n        else focusWait.current = window.requestAnimationFrame(attempt);\n      };\n      focusWait.current = window.requestAnimationFrame(attempt);\n    },\n    openAt: (at) => {\n      opener.current = at;\n      changeOpen(true, Math.min(Math.max(0, at), Math.max(0, count - 1)));\n    },\n    go,\n    settle: (at) => {\n      if (at >= 0 && at !== shown) setCurrent(at);\n    },\n    zoomTo,\n    panTo: (x, y) => setZoomState({ ...clampOffset(zoom.scale, x, y), index: shown }),\n  };\n\n  return (\n    <LightboxContext value={context}>\n      <DialogPrimitive.Root open={isOpen} onOpenChange={(next) => changeOpen(next, shown)}>\n        {children}\n      </DialogPrimitive.Root>\n    </LightboxContext>\n  );\n}\n\n/**\n * A picture directly inside a slide is never larger than the slide. `max-h-full` on the picture cannot do\n * that by itself: the wrapper around it is as tall as its content, and a percentage of that is no limit, so\n * a picture taller than the slide was cut off. The slide's own size, in container units, is a limit.\n */\nconst SLIDE_PICTURE = \"[&>img]:max-h-[100cqh] [&>img]:max-w-[100cqw]\";\n\n/** Whether focus can go to an element now: nothing around it is inert. */\nconst reachable = (element: HTMLElement): boolean => element.closest(\"[inert]\") === null;\n/** Whether any of an element is inside the window. */\nconst inView = (element: HTMLElement): boolean => {\n  const box = element.getBoundingClientRect();\n  return box.bottom > 0 && box.right > 0 && box.top < window.innerHeight && box.left < window.innerWidth;\n};\n/** How long a trigger that was scrolled into view is waited for before focus is tried anyway: about a second. */\nconst FOCUS_WAIT_FRAMES = 60;\n\nexport type LightboxTriggerProps = ComponentProps<\"button\"> & {\n  /** The slide this opens at, from 0. */\n  index?: number;\n  /** Make the child element the trigger (a gallery tile, for example). */\n  asChild?: boolean;\n};\n\n/**\n * A thumbnail (or any button) that opens the lightbox at a slide. The lightbox remembers it: focus comes\n * back here on close, or to the trigger of the slide shown at that moment. A trigger that is out of view\n * inside something inert (a slide of a carousel) is scrolled into view first and then focused; where one\n * slide has two triggers, the one in view is used. The picture inside it (the first <img>, or an element\n * marked `data-lightbox-shared`) is what the slide grows out of.\n */\nexport function LightboxTrigger({ index = 0, asChild = false, onClick, ref, ...props }: LightboxTriggerProps) {\n  const { registerTrigger, openAt } = useLightbox(\"LightboxTrigger\");\n  const Comp = asChild ? Slot.Root : \"button\";\n  const setRef = (element: HTMLButtonElement | null): void => {\n    registerTrigger(index, element);\n    assignRef(ref, element);\n  };\n  return (\n    <Comp\n      data-slot=\"lightbox-trigger\"\n      aria-haspopup=\"dialog\"\n      {...(asChild ? {} : { type: \"button\" as const })}\n      ref={setRef}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) openAt(index);\n      }}\n      {...props}\n    />\n  );\n}\n\nfunction assignRef<T>(ref: Ref<T> | undefined, value: T | null): void {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\nexport type LightboxContentProps = ComponentProps<typeof DialogPrimitive.Content>;\n\n/**\n * The full-screen dialog, with its portal. Keys, anywhere inside: Left and Right arrows show the previous\n * and next slide (the other way round in right-to-left pages), Home and End the first and last, + and -\n * zoom, 0 resets the zoom, Escape closes.\n */\nexport function LightboxContent({ className, children, onKeyDown, onCloseAutoFocus, ...props }: LightboxContentProps) {\n  const context = useLightbox(\"LightboxContent\");\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return;\n    if (event.target instanceof HTMLElement && event.target.closest(\"input, textarea, select, [contenteditable=true]\")) return;\n    const step = inlineStep(event.key, event.currentTarget);\n    if (step !== 0) context.go(context.index + step);\n    else if (event.key === \"Home\") context.go(0);\n    else if (event.key === \"End\") context.go(context.count - 1);\n    else if (event.key === \"+\" || event.key === \"=\") context.zoomTo(context.zoom.scale * ZOOM_STEP, { say: true });\n    else if (event.key === \"-\") context.zoomTo(context.zoom.scale / ZOOM_STEP, { say: true });\n    else if (event.key === \"0\") context.zoomTo(1, { say: true });\n    else return;\n    event.preventDefault();\n  };\n  return (\n    <DialogPrimitive.Portal>\n      <DialogPrimitive.Content\n        data-slot=\"lightbox-content\"\n        data-transition={context.viaTransition ? \"shared\" : \"fade\"}\n        aria-describedby={undefined}\n        onKeyDown={handleKeyDown}\n        onCloseAutoFocus={(event) => {\n          onCloseAutoFocus?.(event);\n          if (event.defaultPrevented) return;\n          event.preventDefault();\n          context.focusTrigger();\n        }}\n        className={cn(\n          \"fixed inset-0 z-50 flex flex-col bg-background text-foreground outline-none ease-out animation-duration-(--duration-base) fade-in-0 fade-out-0 data-[state=closed]:animate-out data-[state=open]:animate-in data-[transition=shared]:animate-none! motion-reduce:animate-none!\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      </DialogPrimitive.Content>\n    </DialogPrimitive.Portal>\n  );\n}\n\n/** The bar above the stage: title, counter, zoom, close. */\nexport function LightboxHeader({ className, ...props }: ComponentProps<\"div\">) {\n  return <div data-slot=\"lightbox-header\" className={cn(\"flex min-h-(--control-h-lg) shrink-0 items-center gap-2 border-b px-3 py-1.5 ps-4\", className)} {...props} />;\n}\n\n/** The bar below the stage: caption, thumbnails. */\nexport function LightboxFooter({ className, ...props }: ComponentProps<\"div\">) {\n  return <div data-slot=\"lightbox-footer\" className={cn(\"flex shrink-0 flex-col gap-2 border-t px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\", className)} {...props} />;\n}\n\n/** The dialog's name. Required; add className=\"sr-only\" to hide it. */\nexport function LightboxTitle({ className, ...props }: ComponentProps<typeof DialogPrimitive.Title>) {\n  return <DialogPrimitive.Title data-slot=\"lightbox-title\" className={cn(\"min-w-0 truncate text-sm font-medium\", className)} {...props} />;\n}\n\n/** The area the slides fill, and what the previous and next buttons are placed against. */\nexport function LightboxStage({ className, ...props }: ComponentProps<\"div\">) {\n  return <div data-slot=\"lightbox-stage\" className={cn(\"relative min-h-0 flex-1\", className)} {...props} />;\n}\n\nexport type LightboxViewportProps = ComponentProps<\"div\"> & {\n  /** What the track is called by a screen reader's role description. Default \"carousel\". */\n  roleDescription?: string;\n};\n\n/**\n * The track: a horizontal scroll-snap row, one slide wide. Swiping is the browser's own scrolling, so it has\n * momentum, follows the finger and runs the right way in right-to-left pages; the current index follows\n * where the track comes to rest. Changing the index (keys, buttons, thumbnails, a controlled `index`)\n * scrolls to that slide, without travel under reduced motion. While a slide is zoomed the track does not\n * scroll. Name it with `aria-label` (default \"Pictures\").\n */\nexport function LightboxViewport({ className, children, roleDescription = \"carousel\", \"aria-label\": ariaLabel = \"Pictures\", ...props }: LightboxViewportProps) {\n  const { viewportRef, index, settle, zoom } = useLightbox(\"LightboxViewport\");\n  const first = useRef(true);\n  /** The slide a scroll started here is on its way to. Until it arrives, where the track rests is not a swipe. */\n  const heading = useRef<number | null>(null);\n  const previous = useRef(index);\n\n  // Bring the current slide into view: at once when the dialog opens, travelling to a neighbour after\n  // that, and at once again for a jump further than a neighbour (a long travel past other pictures).\n  useLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    if (!viewport) return;\n    const opening = first.current;\n    first.current = false;\n    // Measured from the slide last asked for, not from where the track is: a second key press during a travel is still one step.\n    const from = previous.current;\n    previous.current = index;\n    if (heading.current === null && nearestSlide(viewport) === index) return;\n    const slide = viewport.querySelector<HTMLElement>(`:scope > [data-slot=lightbox-slide][data-index=\"${index}\"]`);\n    if (!slide) return;\n    const box = viewport.getBoundingClientRect();\n    const rect = slide.getBoundingClientRect();\n    const instant = opening || reducedMotion() || Math.abs(from - index) > 1;\n    // An instant scroll has arrived by the time this returns; only a travelling one is waited for, and not for ever.\n    heading.current = instant ? null : index;\n    if (!instant) window.setTimeout(() => {\n      if (heading.current === index) heading.current = null;\n    }, 1200);\n    // scrollTo, not scrollBy: a relative scroll is a direction to the browser, and it would stop at the first slide it meets.\n    viewport.scrollTo({ left: viewport.scrollLeft + rect.left + rect.width / 2 - (box.left + box.width / 2), behavior: instant ? \"instant\" : \"smooth\" });\n  }, [index, viewportRef]);\n\n  // Follow the track when it comes to rest after a swipe.\n  const latest = useRef(settle);\n  useEffect(() => {\n    latest.current = settle;\n  });\n  useEffect(() => {\n    const viewport = viewportRef.current;\n    if (!viewport) return;\n    const rest = (): void => {\n      const at = nearestSlide(viewport);\n      if (heading.current === null) latest.current(at);\n      else if (at === heading.current) heading.current = null;\n    };\n    // A finger, a wheel or a pen on the track takes over from a scroll started here.\n    const takeOver = (): void => {\n      heading.current = null;\n    };\n    viewport.addEventListener(\"pointerdown\", takeOver);\n    viewport.addEventListener(\"wheel\", takeOver, { passive: true });\n    if (\"onscrollend\" in window) {\n      viewport.addEventListener(\"scrollend\", rest);\n      return () => {\n        viewport.removeEventListener(\"scrollend\", rest);\n        viewport.removeEventListener(\"pointerdown\", takeOver);\n        viewport.removeEventListener(\"wheel\", takeOver);\n      };\n    }\n    let timer = 0;\n    const onScroll = (): void => {\n      window.clearTimeout(timer);\n      timer = window.setTimeout(rest, 140);\n    };\n    viewport.addEventListener(\"scroll\", onScroll, { passive: true });\n    return () => {\n      window.clearTimeout(timer);\n      viewport.removeEventListener(\"scroll\", onScroll);\n      viewport.removeEventListener(\"pointerdown\", takeOver);\n      viewport.removeEventListener(\"wheel\", takeOver);\n    };\n  }, [viewportRef]);\n\n  return (\n    <div\n      ref={viewportRef}\n      data-slot=\"lightbox-viewport\"\n      data-zoomed={zoom.scale > 1 ? \"\" : undefined}\n      role=\"group\"\n      aria-roledescription={roleDescription}\n      aria-label={ariaLabel}\n      tabIndex={0}\n      className={cn(\n        \"flex size-full snap-x snap-mandatory overflow-x-auto overflow-y-hidden overscroll-x-contain [scrollbar-width:none] data-[zoomed]:overflow-x-hidden\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport type LightboxSlideProps = ComponentProps<\"div\"> & {\n  /** Its position, from 0. */\n  index: number;\n  /** What the slide is called by a screen reader's role description. Default \"slide\". */\n  roleDescription?: string;\n};\n\n/**\n * One slide. Put the picture inside with `max-h-full max-w-full object-contain`; anything else the project\n * renders (a video, a document page) works too. The slide in view can be zoomed: double click or double\n * tap, pinch with two fingers, Ctrl and the wheel, and dragged about while zoomed, never further than its\n * own edge. Slides out of view are inert. Its name is its position (\"3 of 12\") unless `aria-label` is given.\n */\nexport function LightboxSlide({ index, className, children, roleDescription = \"slide\", \"aria-label\": ariaLabel, ...props }: LightboxSlideProps) {\n  const context = useLightbox(\"LightboxSlide\");\n  const active = context.index === index;\n  return (\n    <div\n      data-slot=\"lightbox-slide\"\n      data-index={index}\n      data-active={active ? \"\" : undefined}\n      role=\"group\"\n      aria-roledescription={roleDescription}\n      aria-label={ariaLabel ?? context.formatPosition(index + 1, context.count)}\n      inert={!active}\n      // A size container: the picture inside is held to the slide's own height and width (see SLIDE_PICTURE).\n      className={cn(\"relative flex size-full shrink-0 snap-center snap-always items-center justify-center overflow-hidden p-2 [container-type:size]\", className)}\n      {...props}\n    >\n      {active ? <ZoomSurface>{children}</ZoomSurface> : <div className={cn(\"flex max-h-full max-w-full items-center justify-center\", SLIDE_PICTURE)}>{children}</div>}\n    </div>\n  );\n}\n\n/** The current slide's content: the element that is scaled and moved, and that carries the shared transition name. */\nfunction ZoomSurface({ children }: { children: ReactNode }) {\n  const { surfaceRef, zoom, zoomTo, panTo, open, viaTransition, transitionName } = useLightbox(\"LightboxSlide\");\n  const [gesturing, setGesturing] = useState(false);\n  const pointers = useRef(new Map<number, { x: number; y: number }>());\n  const gesture = useRef<{ kind: \"pan\"; x: number; y: number; fromX: number; fromY: number } | { kind: \"pinch\"; distance: number; scale: number } | null>(null);\n  const lastTap = useRef({ time: 0, x: 0, y: 0 });\n  const lastTouch = useRef(0);\n\n  // Ctrl and the wheel (and a trackpad pinch, which browsers report the same way) zoom about the pointer.\n  // Registered by hand because the page must not zoom with it, and React's wheel listener cannot prevent that.\n  const latest = useRef({ zoom, zoomTo });\n  useEffect(() => {\n    latest.current = { zoom, zoomTo };\n  });\n  useEffect(() => {\n    const slide = surfaceRef.current?.parentElement;\n    if (!slide) return;\n    const onWheel = (event: WheelEvent): void => {\n      if (!event.ctrlKey) return;\n      event.preventDefault();\n      latest.current.zoomTo(latest.current.zoom.scale * Math.exp(-event.deltaY * 0.01), { origin: { x: event.clientX, y: event.clientY } });\n    };\n    slide.addEventListener(\"wheel\", onWheel, { passive: false });\n    return () => slide.removeEventListener(\"wheel\", onWheel);\n  }, [surfaceRef]);\n\n  const spread = (): number => {\n    const [a, b] = [...pointers.current.values()];\n    return a && b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;\n  };\n  const middle = (): { x: number; y: number } => {\n    const [a, b] = [...pointers.current.values()];\n    return a && b ? { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } : { x: 0, y: 0 };\n  };\n\n  const onPointerDown = (event: PointerEvent<HTMLDivElement>): void => {\n    if (event.pointerType === \"mouse\" && event.button !== 0) return;\n    pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    if (pointers.current.size === 2) {\n      gesture.current = { kind: \"pinch\", distance: spread(), scale: zoom.scale };\n      setGesturing(true);\n    } else if (pointers.current.size === 1 && zoom.scale > 1) {\n      gesture.current = { kind: \"pan\", x: event.clientX, y: event.clientY, fromX: zoom.x, fromY: zoom.y };\n      event.currentTarget.setPointerCapture(event.pointerId);\n      setGesturing(true);\n    }\n  };\n\n  const onPointerMove = (event: PointerEvent<HTMLDivElement>): void => {\n    if (!pointers.current.has(event.pointerId)) return;\n    pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    const current = gesture.current;\n    if (current?.kind === \"pinch\" && pointers.current.size === 2 && current.distance > 0) {\n      zoomTo(current.scale * (spread() / current.distance), { origin: middle() });\n    } else if (current?.kind === \"pan\") {\n      panTo(current.fromX + event.clientX - current.x, current.fromY + event.clientY - current.y);\n    }\n  };\n\n  const onPointerEnd = (event: PointerEvent<HTMLDivElement>): void => {\n    if (!pointers.current.delete(event.pointerId)) return;\n    const moved = gesture.current !== null;\n    gesture.current = null;\n    setGesturing(false);\n    // A double tap: touch screens do not send dblclick to an element that handles its own touches.\n    if (event.type === \"pointerup\" && event.pointerType !== \"mouse\" && !moved && pointers.current.size === 0) {\n      const now = event.timeStamp;\n      lastTouch.current = now;\n      const near = Math.hypot(event.clientX - lastTap.current.x, event.clientY - lastTap.current.y) < 30;\n      if (now - lastTap.current.time < 300 && near) {\n        lastTap.current.time = 0;\n        zoomTo(zoom.scale > 1 ? 1 : ZOOM_DOUBLE, { origin: { x: event.clientX, y: event.clientY } });\n      } else {\n        lastTap.current = { time: now, x: event.clientX, y: event.clientY };\n      }\n    }\n  };\n\n  const style: CSSProperties = {\n    transform: zoom.scale === 1 ? undefined : `translate3d(${zoom.x}px, ${zoom.y}px, 0) scale(${zoom.scale})`,\n    ...(open && viaTransition ? { viewTransitionName: transitionName } : {}),\n  };\n\n  return (\n    <div\n      ref={surfaceRef}\n      data-slot=\"lightbox-zoom-surface\"\n      data-zoomed={zoom.scale > 1 ? \"\" : undefined}\n      data-gesture={gesturing ? \"\" : undefined}\n      style={style}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerEnd}\n      onPointerCancel={onPointerEnd}\n      onDoubleClick={(event) => {\n        // A double tap has already been handled from the pointer events.\n        if (event.timeStamp - lastTouch.current < 700) return;\n        zoomTo(zoom.scale > 1 ? 1 : ZOOM_DOUBLE, { origin: { x: event.clientX, y: event.clientY } });\n      }}\n      className={cn(SLIDE_PICTURE, \"flex max-h-full max-w-full touch-pan-x items-center justify-center transition-transform duration-base ease-out select-none data-[gesture]:transition-none data-[zoomed]:cursor-grab data-[zoomed]:touch-none data-[zoomed]:data-[gesture]:cursor-grabbing motion-reduce:transition-none [&_img]:pointer-events-none\")}\n    >\n      {children}\n    </div>\n  );\n}\n\nconst iconButton =\n  \"inline-flex size-(--control-h) shrink-0 items-center justify-center rounded-control text-foreground transition-[background-color,color,opacity] duration-instant ease-out hover:bg-accent aria-disabled:pointer-events-none aria-disabled:opacity-40 motion-reduce:transition-none [&_svg]:size-4\";\n\n/**\n * A button that cannot act just now says so with aria-disabled and stays focusable. The disabled attribute\n * would drop keyboard focus the moment the button that was just pressed reaches its limit (the next button\n * on the last slide, zoom out at 100%), and a disabled button swallows the keys pressed after that.\n */\nconst unavailable = (off: boolean): { \"aria-disabled\"?: \"true\" } => (off ? { \"aria-disabled\": \"true\" } : {});\n\ntype StepButtonProps = Omit<ComponentProps<\"button\">, \"type\">;\n\nfunction StepButton({ step, className, children, onClick, ...props }: StepButtonProps & { step: -1 | 1 }) {\n  const { index, count, loop, go } = useLightbox(step === 1 ? \"LightboxNext\" : \"LightboxPrevious\");\n  const atEnd = !loop && (step === 1 ? index >= count - 1 : index <= 0);\n  return (\n    <button\n      type=\"button\"\n      {...unavailable(atEnd || count < 2)}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented && !(atEnd || count < 2)) go(index + step);\n      }}\n      className={cn(iconButton, \"absolute top-1/2 -translate-y-1/2 border bg-background\", step === 1 ? \"end-2\" : \"start-2\", className)}\n      {...props}\n    >\n      {children}\n    </button>\n  );\n}\n\n/** Shows the previous slide. Sits at the start edge of the stage. Its name (\"Previous picture\") is an `aria-label`: translate it. */\nexport function LightboxPrevious({ children, \"aria-label\": ariaLabel = \"Previous picture\", ...props }: StepButtonProps) {\n  return (\n    <StepButton data-slot=\"lightbox-previous\" step={-1} aria-label={ariaLabel} {...props}>\n      {children ?? <ChevronLeft aria-hidden=\"true\" strokeWidth={1.5} className=\"rtl:-scale-x-100\" />}\n    </StepButton>\n  );\n}\n\n/** Shows the next slide. Sits at the end edge of the stage. Its name (\"Next picture\") is an `aria-label`: translate it. */\nexport function LightboxNext({ children, \"aria-label\": ariaLabel = \"Next picture\", ...props }: StepButtonProps) {\n  return (\n    <StepButton data-slot=\"lightbox-next\" step={1} aria-label={ariaLabel} {...props}>\n      {children ?? <ChevronRight aria-hidden=\"true\" strokeWidth={1.5} className=\"rtl:-scale-x-100\" />}\n    </StepButton>\n  );\n}\n\n/** \"3 of 12\". A polite live region: the new position is read out when the slide changes, whatever changed it. */\nexport function LightboxCounter({ className, ...props }: Omit<ComponentProps<\"p\">, \"children\">) {\n  const { index, count, formatPosition } = useLightbox(\"LightboxCounter\");\n  return (\n    <p data-slot=\"lightbox-counter\" aria-live=\"polite\" aria-atomic=\"true\" className={cn(\"shrink-0 text-sm text-muted-foreground tabular-nums\", className)} {...props}>\n      {formatPosition(index + 1, count)}\n    </p>\n  );\n}\n\n/** The words under the picture. Render the caption of the current slide: `useLightbox().index` says which. */\nexport function LightboxCaption({ className, ...props }: ComponentProps<\"p\">) {\n  return <p data-slot=\"lightbox-caption\" dir=\"auto\" className={cn(\"text-sm text-foreground\", className)} {...props} />;\n}\n\n/** A strip of small pictures to jump between slides. It scrolls sideways when it is longer than the screen. Name it with `aria-label` (default \"All pictures\"). */\nexport function LightboxThumbnails({ className, \"aria-label\": ariaLabel = \"All pictures\", ...props }: ComponentProps<\"div\">) {\n  return (\n    <div\n      data-slot=\"lightbox-thumbnails\"\n      role=\"group\"\n      aria-label={ariaLabel}\n      className={cn(\"-mx-1 flex gap-2 overflow-x-auto px-1 py-1 [scrollbar-width:thin]\", className)}\n      {...props}\n    />\n  );\n}\n\nexport type LightboxThumbnailProps = Omit<ComponentProps<\"button\">, \"type\"> & { index: number };\n\n/**\n * One small picture in the strip. The one for the slide in view has `aria-current`, a strong edge and full\n * opacity. Give it a name: an `aria-label`, or the `alt` of the picture inside.\n */\nexport function LightboxThumbnail({ index, className, onClick, ...props }: LightboxThumbnailProps) {\n  const context = useLightbox(\"LightboxThumbnail\");\n  const active = context.index === index;\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"lightbox-thumbnail\"\n      aria-current={active ? \"true\" : undefined}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) context.go(index);\n      }}\n      className={cn(\n        \"relative size-12 shrink-0 overflow-hidden rounded-control border border-border opacity-60 transition-opacity duration-instant ease-out hover:opacity-100 aria-[current]:border-2 aria-[current]:border-primary aria-[current]:opacity-100 motion-reduce:transition-none [&_img]:size-full [&_img]:object-cover\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport type LightboxZoomProps = Omit<ComponentProps<\"div\">, \"children\"> & {\n  zoomInLabel?: string;\n  zoomOutLabel?: string;\n  /** Read before the level on the middle button, which goes back to 100% (\"Reset zoom: 150%\"). */\n  resetLabel?: string;\n};\n\n/**\n * Zoom out, the level (press it to reset), zoom in. The buttons are the alternative to pinching and to the\n * wheel; the keys + - and 0 do the same anywhere in the lightbox. The new level is announced.\n */\nexport function LightboxZoom({ className, zoomInLabel = \"Zoom in\", zoomOutLabel = \"Zoom out\", resetLabel = \"Reset zoom\", \"aria-label\": ariaLabel = \"Zoom\", ...props }: LightboxZoomProps) {\n  const { zoom, zoomTo, maxZoom } = useLightbox(\"LightboxZoom\");\n  return (\n    <div data-slot=\"lightbox-zoom\" role=\"group\" aria-label={ariaLabel} className={cn(\"flex shrink-0 items-center\", className)} {...props}>\n      <button type=\"button\" data-slot=\"lightbox-zoom-out\" aria-label={zoomOutLabel} {...unavailable(zoom.scale <= 1)} onClick={() => zoomTo(zoom.scale / ZOOM_STEP, { say: true })} className={iconButton}>\n        <ZoomOut aria-hidden=\"true\" strokeWidth={1.5} />\n      </button>\n      <button\n        type=\"button\"\n        data-slot=\"lightbox-zoom-reset\"\n        {...unavailable(zoom.scale === 1)}\n        onClick={() => zoomTo(1, { say: true })}\n        className={cn(iconButton, \"w-auto min-w-12 px-1 text-sm tabular-nums aria-disabled:opacity-100\")}\n      >\n        <span className=\"sr-only\">{resetLabel}: </span>\n        <span data-slot=\"lightbox-zoom-level\">{Math.round(zoom.scale * 100)}%</span>\n      </button>\n      <button type=\"button\" data-slot=\"lightbox-zoom-in\" aria-label={zoomInLabel} {...unavailable(zoom.scale >= maxZoom)} onClick={() => zoomTo(zoom.scale * ZOOM_STEP, { say: true })} className={iconButton}>\n        <ZoomIn aria-hidden=\"true\" strokeWidth={1.5} />\n      </button>\n    </div>\n  );\n}\n\n/** Closes the lightbox. Its name (\"Close\") is an `aria-label`: translate it. */\nexport function LightboxClose({ className, children, \"aria-label\": ariaLabel = \"Close\", ...props }: ComponentProps<typeof DialogPrimitive.Close>) {\n  return (\n    <DialogPrimitive.Close data-slot=\"lightbox-close\" aria-label={ariaLabel} className={cn(iconButton, className)} {...props}>\n      {children ?? <X aria-hidden=\"true\" strokeWidth={1.5} />}\n    </DialogPrimitive.Close>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Looking closely at pictures that are shown small on the page: a listing's photos, a portfolio, attachments. It is a modal dialog, so focus is held inside and returns to the thumbnail of the picture shown when it closes. For a grid of thumbnails that opens it use gallery (GalleryLightbox does both). For one picture with text beside it use dialog; for a row of cards that scroll in the page use a scroll-snap row, not a lightbox. Always give it a LightboxTitle (className=\"sr-only\" hides it) and say how many slides there are with `count`.",
    "example": "<Lightbox count={photos.length}>\n  {photos.map((photo, index) => (\n    <LightboxTrigger key={photo.src} index={index} aria-label={`Open picture: ${photo.alt}`}>\n      <img src={photo.thumb} alt=\"\" className=\"size-24 rounded-control object-cover\" />\n    </LightboxTrigger>\n  ))}\n  <LightboxContent>\n    <LightboxHeader>\n      <LightboxTitle className=\"sr-only\">Photos</LightboxTitle>\n      <LightboxCounter />\n      <LightboxZoom className=\"ms-auto\" />\n      <LightboxClose />\n    </LightboxHeader>\n    <LightboxStage>\n      <LightboxViewport>\n        {photos.map((photo, index) => (\n          <LightboxSlide key={photo.src} index={index}>\n            <img src={photo.src} alt={photo.alt} className=\"max-h-full max-w-full object-contain\" />\n          </LightboxSlide>\n        ))}\n      </LightboxViewport>\n      <LightboxPrevious />\n      <LightboxNext />\n    </LightboxStage>\n  </LightboxContent>\n</Lightbox>",
    "client": true
  }
}
