SunUI
創設メンバー$79・永久更新・1月11日まで枠を確保する
無料押す

ホットスポット

画像の上の番号付きピン(商品写真、スクリーンショット、地図、図解など)。

使いどころ

  • 素材やディテールを説明する商品ページ
  • 一枚の写真に複数の商品が写るコーディネート

注意点

  • ピンは外周 10% より内側に。カードの余白が必要です
  • 重要なディテールは画像を見ない人のためにページ本文にも

エージェントに追加してもらう

インストールコマンド、使いどころ、props、デザインルールを一度にコピーできます。Claude Code、Cursor、Codex に貼り付けてください。

CLI でインストール

shadcn CLI を使います。ソースはプロジェクトにコピーされるので、すべての行があなたのものです。

$ npx shadcn@latest add https://sunui.synvize.com/r/hotspots.json

手動でインストール

  1. 1. 依存パッケージをインストールします。
    $ npm install clsx tailwind-merge framer-motion
  2. 2. cn ヘルパーがなければ lib/utils.ts に追加します。shadcn/ui を使っていない場合は、色のトークン用に sunui-theme.css も追加します(手順)。そのあとコンポーネントをコピーします。
    hotspots.tsx
    "use client";
    
    import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
    import { useEffect, useId, useRef, useState, type ReactNode } from "react";
    
    import { cn } from "@/lib/utils";
    
    /** Brand accent color: follows the theme's --primary by default; buyers set --sunui-spot to use their own brand color. Used only for selection, the offer and current progress */
    const spotBorder = "border-[color:var(--sunui-spot,var(--primary))]";
    const spotFill = "bg-[color:var(--sunui-spot,var(--primary))] text-[color:var(--sunui-spot-foreground,var(--primary-foreground))]";
    
    const springs = {
      snappy: { type: "spring", stiffness: 520, damping: 34 },
      gentle: { type: "spring", stiffness: 240, damping: 30 },
    } as const;
    
    export interface Hotspot {
      id: string;
      /** Horizontal position, 0 to 100 (%) */
      x: number;
      /** Vertical position, 0 to 100 (%) */
      y: number;
      title: ReactNode;
      description?: ReactNode;
      /** Action at the bottom of the detail card, for example the price or "Add to cart" */
      action?: ReactNode;
      /** Button name for screen readers; title is used when not given */
      label?: string;
    }
    
    export interface HotspotsProps {
      /** Base image, usually an img; the container is sized by its dimensions */
      children: ReactNode;
      spots: Hotspot[];
      /** Controlled: which one is currently open */
      active?: string | null;
      defaultActive?: string | null;
      onActiveChange?: (id: string | null) => void;
      /** number: shows the number; dot: just a dot */
      marker?: "number" | "dot";
      /** Detail card width (px) */
      cardWidth?: number;
      className?: string;
    }
    
    export function Hotspots({ children, spots, active: activeProp, defaultActive = null, onActiveChange, marker = "number", cardWidth = 224, className }: HotspotsProps) {
      const reduce = useReducedMotion();
      const uid = useId();
      const rootRef = useRef<HTMLDivElement>(null);
      const [inner, setInner] = useState<string | null>(defaultActive);
      const active = activeProp !== undefined ? activeProp : inner;
      const open = spots.find((s) => s.id === active) ?? null;
    
      const set = (id: string | null) => {
        if (activeProp === undefined) setInner(id);
        onActiveChange?.(id);
      };
    
      useEffect(() => {
        if (!open) return;
        const onKey = (e: KeyboardEvent) => e.key === "Escape" && set(null);
        const onDown = (e: PointerEvent) => {
          if (rootRef.current && !rootRef.current.contains(e.target as Node)) set(null);
        };
        document.addEventListener("keydown", onKey);
        document.addEventListener("pointerdown", onDown);
        return () => {
          document.removeEventListener("keydown", onKey);
          document.removeEventListener("pointerdown", onDown);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [open?.id]);
    
      // Which side of the point the detail card sits on: points on the right open to the left, points near the bottom open upward
      const place = (s: Hotspot) => ({
        side: s.x > 55 ? "left" : "right",
        vertical: s.y > 60 ? "up" : "down",
      });
    
      return (
        <div ref={rootRef} className={cn("relative isolate", className)}>
          {children}
          {spots.map((s, i) => {
            const on = s.id === active;
            return (
              <motion.button
                key={s.id}
                type="button"
                aria-expanded={on}
                aria-controls={on ? `${uid}-card` : undefined}
                aria-label={s.label ?? (typeof s.title === "string" ? s.title : `${i + 1}`)}
                onClick={() => set(on ? null : s.id)}
                whileTap={reduce ? undefined : { scale: 0.9 }}
                transition={springs.snappy}
                className={cn(
                  "absolute z-10 -ml-3.5 -mt-3.5 grid size-7 place-items-center rounded-full border-[1.5px] text-xs font-semibold tabular-nums outline-offset-2 transition-colors focus-visible:outline-2",
                  on
                    ? cn(spotBorder, spotFill)
                    : "border-foreground bg-card text-foreground hover:bg-foreground/10",
                )}
                style={{ left: `${s.x}%`, top: `${s.y}%` }}
              >
                <motion.span initial={false} animate={{ rotate: on ? 45 : 0 }} transition={reduce ? { duration: 0 } : springs.snappy} className="grid place-items-center">
                  {on || marker === "dot" ? (
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" className="size-3.5" aria-hidden="true">
                      <path d="M12 6v12M6 12h12" />
                    </svg>
                  ) : (
                    i + 1
                  )}
                </motion.span>
              </motion.button>
            );
          })}
          <AnimatePresence>
            {open && (
              <div
                key={open.id}
                className="pointer-events-none absolute z-20"
                style={{
                  left: `${open.x}%`,
                  top: `${open.y}%`,
                  width: cardWidth,
                  maxWidth: "calc(100% - 1rem)",
                  transform: `translate(${place(open).side === "left" ? "calc(-100% - 22px)" : "22px"}, ${place(open).vertical === "up" ? "calc(-100% + 14px)" : "-14px"})`,
                }}
              >
                <motion.div
                  id={`${uid}-card`}
                  role="region"
                  aria-label={typeof open.title === "string" ? open.title : undefined}
                  className="pointer-events-auto rounded-xl border border-foreground/10 bg-card p-3.5 text-foreground shadow-[0_1px_2px_rgb(0_0_0/0.05),0_4px_12px_-6px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]"
                  style={{ originX: place(open).side === "left" ? 1 : 0, originY: place(open).vertical === "up" ? 1 : 0 }}
                  initial={{ opacity: 0, scale: reduce ? 1 : 0.96 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, transition: { duration: 0.12 } }}
                  transition={reduce ? { duration: 0 } : springs.gentle}
                >
                  <p className="text-sm font-semibold tracking-tight">{open.title}</p>
                  {open.description && <p className="mt-1 text-xs leading-relaxed text-muted-foreground">{open.description}</p>}
                  {open.action && <div className="mt-3 border-t border-foreground/10 pt-3">{open.action}</div>}
                </motion.div>
              </div>
            )}
          </AnimatePresence>
        </div>
      );
    }