गिस्ट्स

नेटिव Popover और CSS Modules के साथ React इमेज ज़ूम

tsx · 5 नवंबर 2026

नेटिव Popover API, Web Animations API और CSS Modules का उपयोग करके React में इमेज ज़ूम।

GitHub पर देखें

.trigger {
  display: block;
  padding: 0;
  border: 0;
  background: transparent;
  color: inherit;
  font: inherit;
  cursor: zoom-in;
  overflow: hidden;
  border-radius: inherit;
}
.trigger:disabled { cursor: default; }
.trigger:focus-visible {
  outline: 2px solid var(--ring, Highlight);
  outline-offset: 4px;
}
.thumbnail {
  display: block;
  max-width: 100%;
  height: auto;
  object-fit: contain;
  object-position: center;
}
.error { display: block; padding: 1rem; }

.surface {
  position: fixed;
  inset: 0;
  width: 100%;
  height: 100dvh;
  max-width: none;
  max-height: none;
  margin: 0;
  padding: 0;
  border: 0;
  overflow: hidden;
  background: transparent;
  color: var(--foreground, CanvasText);
  cursor: zoom-out;
}
.surface::backdrop { background: transparent; }
.surface::before {
  content: "";
  position: absolute;
  inset: 0;
  background: color-mix(in srgb, var(--image-zoom-background, var(--background, Canvas)) 90%, transparent);
  animation: backdropIn 320ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.surface[data-closing="true"]::before {
  animation: backdropOut 200ms ease-out both;
}
.floating {
  position: absolute;
  padding: 0;
  border: 0;
  background: transparent;
  transform-origin: top left;
  cursor: zoom-out;
  outline: none;
}
.floating:focus-visible {
  outline: 2px solid var(--ring, Highlight);
  outline-offset: 4px;
}
.floating img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: min(1vw, 8px);
}
@keyframes backdropIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes backdropOut { from { opacity: 1; } to { opacity: 0; } }
@media (prefers-reduced-motion: reduce) {
  .surface::before { animation-duration: 0ms; }
}
"use client";

import { useCallback, useEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
import { createPortal } from "react-dom";
import styles from "./image-zoom.module.css";

/**
 * Native image attributes plus zoom presentation options.
 *
 * @property alt - Required alternative text; also labels the zoom controls.
 * @property className - Outer button classes, including layout and spacing.
 * @property imageClassName - Thumbnail image classes.
 * @property zoomSrc - Optional full-resolution source with the same composition.
 * @property disabled - Disables zoom. Defaults to `false`.
 */
export type ImageZoomProps = Omit<ComponentPropsWithoutRef<"img">, "alt" | "className"> & {
  alt: string;
  className?: string;
  imageClassName?: string;
  zoomSrc?: string;
  disabled?: boolean;
};

const EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
const VIEWPORT_PADDING = 16;

function classNames(...values: (string | undefined)[]) {
  return values.filter(Boolean).join(" ");
}

function imageBounds(image: HTMLImageElement) {
  const rect = image.getBoundingClientRect();
  const scale = Math.min(rect.width / image.naturalWidth, rect.height / image.naturalHeight);
  const width = image.naturalWidth * scale;
  const height = image.naturalHeight * scale;
  return {
    width,
    height,
    left: rect.left + (rect.width - width) / 2,
    top: rect.top + (rect.height - height) / 2,
  };
}

function thumbnailTransform(image: HTMLImageElement, target: HTMLElement) {
  const bounds = imageBounds(image);
  const { left, top, width, height } = target.style;
  return `translate(${bounds.left - parseFloat(left)}px, ${bounds.top - parseFloat(top)}px) scale(${bounds.width / parseFloat(width)}, ${bounds.height / parseFloat(height)})`;
}

function motionDuration(duration: number) {
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : duration;
}

/**
 * Expands an image from its thumbnail into the browser's native popover top layer.
 *
 * @param props - Native image attributes and zoom options.
 * @returns A zoomable thumbnail and its temporary foreground layer.
 *
 * @remarks
 * Requires the colocated CSS Module. Keep thumbnails centered with
 * `object-fit: contain` so the expansion matches their painted bounds.
 * Loading defaults to `lazy`; decoding defaults to `async`.
 * Click, Escape, scroll, or resize dismisses the image and restores focus.
 * Respects reduced motion. Browsers without Popover support open a new tab.
 *
 * @example
 * ```tsx
 * <ImageZoom
 *   src="/photo-small.jpg"
 *   zoomSrc="/photo-original.jpg"
 *   alt="A mountain reflected in a lake"
 *   className="photo"
 *   imageClassName="photo-image"
 * />
 * ```
 */
export function ImageZoom({
  src,
  alt,
  className,
  imageClassName,
  zoomSrc,
  disabled = false,
  loading = "lazy",
  decoding = "async",
  onError,
  onLoad,
  ...imageProps
}: ImageZoomProps) {
  const trigger = useRef<HTMLButtonElement>(null);
  const original = useRef<HTMLImageElement>(null);
  const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
  const [failed, setFailed] = useState(false);
  const dismiss = useCallback(() => setExpandedSrc(null), []);

  return (
    <>
      <button
        ref={trigger}
        type="button"
        disabled={disabled}
        aria-label={failed ? `Retry ${alt || "image"}` : `Enlarge ${alt || "image"}`}
        aria-expanded={expandedSrc !== null}
        className={classNames(styles.trigger, className)}
        onClick={() => {
          if (failed) {
            setFailed(false);
            return;
          }
          const image = original.current;
          if (!image?.naturalWidth) return;
          const source = zoomSrc || image.currentSrc || (typeof src === "string" ? src : "");
          if (!source) return;
          if (typeof HTMLElement.prototype.showPopover !== "function") {
            window.open(source, "_blank", "noopener,noreferrer");
            return;
          }
          setExpandedSrc(source);
        }}
      >
        {failed ? <span className={styles.error}>Retry image</span> : (
          <img
            {...imageProps}
            ref={original}
            src={src}
            alt={alt}
            loading={loading}
            decoding={decoding}
            className={classNames(styles.thumbnail, imageClassName)}
            onLoad={(event) => { setFailed(false); onLoad?.(event); }}
            onError={(event) => { setFailed(true); onError?.(event); }}
          />
        )}
      </button>
      {expandedSrc && createPortal(
        <ZoomSurface
          key={expandedSrc}
          src={expandedSrc}
          alt={alt}
          original={original}
          trigger={trigger}
          crossOrigin={imageProps.crossOrigin}
          referrerPolicy={imageProps.referrerPolicy}
          onClose={dismiss}
        />,
        document.body,
      )}
    </>
  );
}

type ZoomSurfaceProps = Pick<ImageZoomProps, "alt" | "crossOrigin" | "referrerPolicy"> & {
  src: string;
  original: { readonly current: HTMLImageElement | null };
  trigger: { readonly current: HTMLButtonElement | null };
  onClose: () => void;
};

function ZoomSurface({ src, alt, original, trigger, crossOrigin, referrerPolicy, onClose }: ZoomSurfaceProps) {
  const surface = useRef<HTMLDivElement>(null);
  const floating = useRef<HTMLButtonElement>(null);
  const expanded = useRef<HTMLImageElement>(null);
  const animation = useRef<Animation | null>(null);
  const closing = useRef(false);

  const close = useCallback(() => {
    if (closing.current) return;
    closing.current = true;
    const node = floating.current;
    const image = original.current;
    const layer = surface.current;
    if (!node || !image?.naturalWidth || !layer?.matches(":popover-open")) {
      onClose();
      return;
    }
    const current = getComputedStyle(node).transform;
    animation.current?.cancel();
    layer.dataset.closing = "true";
    animation.current = node.animate([
      { transform: current },
      { transform: thumbnailTransform(image, node) },
    ], { duration: motionDuration(200), easing: EASING, fill: "forwards" });
    void animation.current.finished.then(onClose).catch(() => {});
  }, [original, onClose]);

  useEffect(() => {
    const layer = surface.current!;
    const node = floating.current!;
    const image = original.current;
    const opener = trigger.current;
    if (!image) { onClose(); return; }
    const previousVisibility = image.style.visibility;
    let disposed = false;
    closing.current = false;

    async function show() {
      const fullImage = expanded.current!;
      try { await fullImage.decode(); }
      catch { if (!disposed) onClose(); return; }
      if (disposed || closing.current || !image) return;
      const fit = Math.min(
        Math.max(1, window.innerWidth - VIEWPORT_PADDING * 2) / fullImage.naturalWidth,
        Math.max(1, window.innerHeight - VIEWPORT_PADDING * 2) / fullImage.naturalHeight,
        1,
      );
      const width = fullImage.naturalWidth * fit;
      const height = fullImage.naturalHeight * fit;
      Object.assign(node.style, {
        width: `${width}px`,
        height: `${height}px`,
        left: `${(window.innerWidth - width) / 2}px`,
        top: `${(window.innerHeight - height) / 2}px`,
      });
      layer.showPopover();
      image.style.visibility = "hidden";
      node.focus({ preventScroll: true });
      animation.current = node.animate([
        { transform: thumbnailTransform(image, node) },
        { transform: "translate(0, 0) scale(1)" },
      ], { duration: motionDuration(320), easing: EASING, fill: "forwards" });
    }

    function onKey(event: KeyboardEvent) {
      if (!layer.matches(":popover-open")) return;
      if (event.key === "Escape") {
        event.preventDefault();
        event.stopPropagation();
        close();
      }
      if (event.key === "Tab") {
        event.preventDefault();
        node.focus({ preventScroll: true });
      }
    }

    void show();
    document.addEventListener("keydown", onKey, true);
    window.addEventListener("resize", close);
    window.addEventListener("scroll", close, { capture: true, passive: true });
    return () => {
      disposed = true;
      animation.current?.cancel();
      if (layer.matches(":popover-open")) layer.hidePopover();
      image.style.visibility = previousVisibility;
      if (opener?.isConnected) opener.focus({ preventScroll: true });
      document.removeEventListener("keydown", onKey, true);
      window.removeEventListener("resize", close);
      window.removeEventListener("scroll", close, true);
    };
  }, [close, onClose, original, trigger]);

  return (
    <div ref={surface} popover="manual" role="region" aria-label="Enlarged image" className={styles.surface} onClick={close} onWheel={close}>
      <button ref={floating} type="button" className={styles.floating} aria-label={`Close enlarged ${alt || "image"}`}>
        <img ref={expanded} src={src} alt={alt} crossOrigin={crossOrigin} referrerPolicy={referrerPolicy} draggable={false} />
      </button>
    </div>
  );
}