マイクロインタラクション(Micro-interactions)

いいね・ブックマーク・コピーしました・送信ボタン・カートに追加・削除の取り消し。押したことが伝わる小さな動き6つを、Framer Motion・React Spring・GSAP・CSS で同じように作って比べます。どのタブも「動きを減らす設定」に対応していて、デモの上の切り替えで違いを見られます。

ネイティブ実装: CSS の @keyframes と transition だけでも作れます(このページの「CSS Animation」タブ)。 キーフレームアニメーション →トランジション →

Framer Motion

プレビュー
読み込み中...
tsx
"use client";

import { AnimatePresence, motion } from "motion/react";
import { Bookmark, Check, Copy, Heart, Loader2, Send, ShoppingCart, Trash2 } from "lucide-react";
import {
  MicroDemoShell,
  Scene,
  btn,
  useReduced,
  useLike,
  useBookmark,
  useCopy,
  useSend,
  useCart,
  useUndoList,
  PARTICLES,
} from "./shared";

const ACCENT = "var(--color-accent)";

function LikeScene() {
  const reduced = useReduced();
  const { liked, count, pop, toggle } = useLike();
  return (
    <Scene title="いいね" hint="ハートが弾み、粒が飛ぶ">
      <button type="button" className={btn} aria-pressed={liked} onClick={toggle}>
        <span className="relative inline-flex">
          <motion.span
            key={reduced ? "static" : pop}
            initial={reduced || pop === 0 ? false : { scale: 0.6 }}
            animate={{ scale: 1 }}
            transition={{ type: "spring", stiffness: 500, damping: 12 }}
            className="inline-flex"
          >
            <Heart size={18} aria-hidden fill={liked ? ACCENT : "none"} stroke={liked ? ACCENT : "currentColor"} />
          </motion.span>
          {!reduced && pop > 0 && (
            <span key={pop} aria-hidden className="pointer-events-none absolute inset-0">
              {PARTICLES.map((p, i) => (
                <motion.span
                  key={i}
                  className="absolute left-1/2 top-1/2 size-1.5 -ml-[3px] -mt-[3px] rounded-full"
                  style={{ background: ACCENT }}
                  initial={{ x: 0, y: 0, opacity: 1, scale: 1 }}
                  animate={{ x: p.x, y: p.y, opacity: 0, scale: 0.4 }}
                  transition={{ duration: 0.5, ease: "easeOut" }}
                />
              ))}
            </span>
          )}
        </span>
        <span className="tabular-nums">{count}</span>
      </button>
    </Scene>
  );
}

function BookmarkScene() {
  const reduced = useReduced();
  const { saved, toggle } = useBookmark();
  return (
    <Scene title="ブックマーク" hint="枠のアイコンが下から塗られる">
      <div className="flex flex-col items-center gap-2">
        <button type="button" className={btn} aria-pressed={saved} onClick={toggle}>
          <span className="relative inline-flex size-[18px]">
            <Bookmark size={18} aria-hidden className="absolute inset-0" />
            <motion.span
              className="absolute inset-0 inline-flex"
              initial={false}
              animate={{ clipPath: saved ? "inset(0% 0 0 0)" : "inset(100% 0 0 0)" }}
              transition={{ duration: reduced ? 0 : 0.35, ease: "easeOut" }}
            >
              <Bookmark size={18} aria-hidden fill={ACCENT} stroke={ACCENT} />
            </motion.span>
          </span>
          {saved ? "保存済み" : "保存"}
        </button>
        <AnimatePresence>
          {saved && (
            <motion.p
              className="text-xs text-gray-600"
              initial={{ opacity: 0, y: reduced ? 0 : -4 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              transition={{ duration: reduced ? 0.12 : 0.25 }}
            >
              あとで読むリストに保存しました
            </motion.p>
          )}
        </AnimatePresence>
      </div>
    </Scene>
  );
}

function CopyScene() {
  const reduced = useReduced();
  const { copied, copy } = useCopy();
  return (
    <Scene title="コピーしました" hint="アイコンがチェックに変わり、吹き出しが出て消える">
      <div className="relative flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 py-1.5 pl-3 pr-1.5">
        <code className="font-mono text-sm text-gray-800">npm install motion</code>
        <button type="button" className={`${btn} px-2 py-1.5`} onClick={copy} aria-label="コピー">
          <AnimatePresence mode="popLayout" initial={false}>
            <motion.span
              key={copied ? "check" : "copy"}
              className="inline-flex"
              initial={reduced ? { opacity: 0 } : { opacity: 0, scale: 0.5, rotate: -45 }}
              animate={{ opacity: 1, scale: 1, rotate: 0 }}
              exit={reduced ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}
              transition={{ duration: reduced ? 0.1 : 0.2 }}
            >
              {copied ? <Check size={16} aria-hidden /> : <Copy size={16} aria-hidden />}
            </motion.span>
          </AnimatePresence>
        </button>
        <AnimatePresence>
          {copied && (
            <motion.span
              role="status"
              className="absolute -top-9 right-0 rounded-md bg-gray-900 px-2 py-1 text-xs text-white"
              initial={{ opacity: 0, y: reduced ? 0 : 6 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              transition={{ duration: reduced ? 0.1 : 0.2 }}
            >
              コピーしました
            </motion.span>
          )}
        </AnimatePresence>
      </div>
    </Scene>
  );
}

function SendScene() {
  const reduced = useReduced();
  const { phase, send } = useSend();
  return (
    <Scene title="送信ボタン" hint="押す → 読み込み中 → 完了のチェック → 元に戻る">
      <motion.button
        type="button"
        onClick={send}
        aria-live="polite"
        className="inline-flex h-10 items-center justify-center overflow-hidden rounded-full bg-[var(--color-accent-fill)] text-sm font-bold text-white"
        animate={{ width: phase === "idle" ? 112 : 40 }}
        transition={{ duration: reduced ? 0 : 0.3, ease: "easeInOut" }}
      >
        <AnimatePresence mode="wait" initial={false}>
          <motion.span
            key={phase}
            className="inline-flex items-center gap-1.5 whitespace-nowrap"
            initial={{ opacity: 0, scale: reduced ? 1 : 0.6 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: reduced ? 0.1 : 0.18 }}
          >
            {phase === "idle" && (
              <>
                <Send size={16} aria-hidden />
                送信
              </>
            )}
            {phase === "sending" && (
              <motion.span
                className="inline-flex"
                animate={reduced ? undefined : { rotate: 360 }}
                transition={{ repeat: Infinity, duration: 0.8, ease: "linear" }}
              >
                <Loader2 size={18} aria-label="送信中" />
              </motion.span>
            )}
            {phase === "done" && <Check size={18} aria-label="送信しました" />}
          </motion.span>
        </AnimatePresence>
      </motion.button>
    </Scene>
  );
}

function CartScene() {
  const reduced = useReduced();
  const { count, bump, add } = useCart();
  return (
    <Scene title="カートに追加" hint="数字のバッジが跳ねる">
      <div className="flex items-center gap-6">
        <button type="button" className={btn} onClick={add}>
          カートに追加
        </button>
        <span className="relative inline-flex text-gray-800" aria-label={`カートの中身 ${count} 点`} role="status">
          <motion.span
            key={reduced ? "static" : `cart-${bump}`}
            className="inline-flex"
            initial={reduced || bump === 0 ? false : { rotate: -12 }}
            animate={{ rotate: 0 }}
            transition={{ type: "spring", stiffness: 400, damping: 8 }}
          >
            <ShoppingCart size={26} aria-hidden />
          </motion.span>
          <motion.span
            key={reduced ? "badge" : `badge-${bump}`}
            aria-hidden
            className="absolute -right-2.5 -top-2 grid min-w-5 h-5 place-items-center rounded-full bg-[var(--color-accent-fill)] px-1 text-xs font-bold text-white tabular-nums"
            initial={reduced || bump === 0 ? false : { scale: 1.5, y: -6 }}
            animate={{ scale: 1, y: 0 }}
            transition={{ type: "spring", stiffness: 500, damping: 10 }}
          >
            {count}
          </motion.span>
        </span>
      </div>
    </Scene>
  );
}

function UndoScene() {
  const reduced = useReduced();
  const { rows, removed, remove, undo, reset } = useUndoList();
  return (
    <Scene title="削除の取り消し" hint="行が縮んで消え、「元に戻す」で戻る">
      <div className="relative w-full">
        <ul className="rounded-md border border-gray-200">
          <AnimatePresence initial={false}>
            {rows.map((r) => (
              <motion.li
                key={r.id}
                className="overflow-hidden border-b border-gray-200 last:border-b-0"
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: "auto", opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: reduced ? 0 : 0.25, ease: "easeInOut" }}
              >
                <div className="flex items-center justify-between px-3 py-2 text-sm text-gray-800">
                  {r.name}
                  <button type="button" onClick={() => remove(r.id)} aria-label={`${r.name} を削除`} className="rounded-md p-1 text-gray-600 hover:bg-gray-100">
                    <Trash2 size={16} aria-hidden />
                  </button>
                </div>
              </motion.li>
            ))}
          </AnimatePresence>
          {rows.length === 0 && (
            <li className="px-3 py-2 text-sm text-gray-600">
              空になりました。<button type="button" onClick={reset} className="underline">最初に戻す</button>
            </li>
          )}
        </ul>
        <AnimatePresence>
          {removed && (
            <motion.div
              role="status"
              className="mt-3 flex items-center justify-between rounded-md bg-gray-900 px-3 py-2 text-sm text-white"
              initial={{ opacity: 0, y: reduced ? 0 : 12 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: reduced ? 0 : 12 }}
              transition={{ duration: reduced ? 0.1 : 0.2 }}
            >
              「{removed.row.name}」を削除しました
              <button type="button" onClick={undo} className="ml-3 font-bold underline">
                元に戻す
              </button>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </Scene>
  );
}

export default function MotionMicroDemo() {
  return (
    <MicroDemoShell>
      <LikeScene />
      <BookmarkScene />
      <CopyScene />
      <SendScene />
      <CartScene />
      <UndoScene />
    </MicroDemoShell>
  );
}

// ───────── shared.tsx(6つの場面の状態と、動きを減らす切り替え。4つのタブで共通)─────────

"use client";

/**
 * マイクロインタラクション(#297)の共通部分。
 *
 * - 6つの場面の「状態」(押した・送信中・削除したなど)はここで持ち、各ライブラリのデモは「動き」だけを書く。
 *   こうすると、タブを替えても同じ操作で同じ結果になり、ライブラリごとの差が動きだけに出る
 * - 「動きを減らす」:OS の prefers-reduced-motion か、ページ上の切り替えのどちらかが入っていれば true。
 *   各デモは true のとき、弾み・粒・回転をやめ、短いフェードだけにする
 */
import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";

/* ── 動きを減らす ───────────────────────────────── */

const ReducedContext = createContext(false);

/** デモの中で「動きを減らすか」を読む */
export function useReduced(): boolean {
  return useContext(ReducedContext);
}

function useOsReduced(): boolean {
  const [reduced, setReduced] = useState(false);
  useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);
  return reduced;
}

/** デモ全体を包む。上に「動きを減らす設定で見る」の切り替えを置く */
export function MicroDemoShell({ children }: { children: ReactNode }) {
  const os = useOsReduced();
  const [preview, setPreview] = useState(false);
  const reduced = os || preview;
  return (
    <ReducedContext.Provider value={reduced}>
      <div className="p-5 sm:p-6">
        <label className="mb-5 flex w-fit items-center gap-2 text-sm text-gray-700 cursor-pointer select-none">
          <input
            type="checkbox"
            checked={reduced}
            disabled={os}
            onChange={(e) => setPreview(e.target.checked)}
            className="size-4 accent-[var(--color-accent)]"
          />
          動きを減らす設定で見る
          {os && <span className="text-xs text-gray-600">(この端末で設定されています)</span>}
        </label>
        <div className="grid gap-4 sm:grid-cols-2">{children}</div>
      </div>
    </ReducedContext.Provider>
  );
}

/** 1つの場面の枠 */
export function Scene({ title, hint, children }: { title: string; hint: string; children: ReactNode }) {
  return (
    <section className="flex flex-col rounded-[var(--radius)] border border-gray-200 bg-white p-4">
      <h3 className="text-sm font-bold text-gray-900">{title}</h3>
      <p className="mt-0.5 mb-4 text-xs text-gray-600">{hint}</p>
      <div className="flex flex-1 items-center justify-center min-h-32">{children}</div>
    </section>
  );
}

/** 場面で使うボタンの見た目(どのライブラリでも同じ) */
export const btn =
  "inline-flex items-center justify-center gap-1.5 rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-800 hover:bg-gray-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900";

/* ── 6つの場面の状態 ─────────────────────────────── */

/** いいね:押すと数が1増え、もう一度押すと戻る。pop は「いいねした瞬間」だけ増える(取り消しでは動かさない) */
export function useLike() {
  const [liked, setLiked] = useState(false);
  const [pop, setPop] = useState(0);
  const toggle = useCallback(() => {
    if (!liked) setPop((p) => p + 1);
    setLiked(!liked);
  }, [liked]);
  return { liked, count: liked ? 129 : 128, pop, toggle };
}

/** ブックマーク:保存・解除を切り替える */
export function useBookmark() {
  const [saved, setSaved] = useState(false);
  return { saved, toggle: () => setSaved((v) => !v) };
}

/** コピー:押すと 1.6 秒だけ「コピーしました」になる */
export const COPY_TEXT = "npm install motion";
export function useCopy() {
  const [copied, setCopied] = useState(false);
  const timer = useRef<number | undefined>(undefined);
  const copy = useCallback(() => {
    // 実際にクリップボードへ書く(拒否されてもデモは続ける)
    navigator.clipboard?.writeText(COPY_TEXT).catch(() => {});
    setCopied(true);
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setCopied(false), 1600);
  }, []);
  useEffect(() => () => window.clearTimeout(timer.current), []);
  return { copied, copy };
}

/** 送信:idle → sending(1.2 秒)→ done(1.4 秒)→ idle */
export type SendPhase = "idle" | "sending" | "done";
export function useSend() {
  const [phase, setPhase] = useState<SendPhase>("idle");
  const timers = useRef<number[]>([]);
  const send = useCallback(() => {
    if (phase !== "idle") return;
    setPhase("sending");
    timers.current.push(
      window.setTimeout(() => setPhase("done"), 1200),
      window.setTimeout(() => setPhase("idle"), 2600),
    );
  }, [phase]);
  useEffect(() => () => timers.current.forEach((t) => window.clearTimeout(t)), []);
  return { phase, send };
}

/** カート:追加するたびに数が増え、bump が増える(バッジを弾ませる合図) */
export function useCart() {
  const [count, setCount] = useState(2);
  const [bump, setBump] = useState(0);
  return {
    count,
    bump,
    add: () => {
      setCount((c) => c + 1);
      setBump((b) => b + 1);
    },
  };
}

/** 削除の取り消し:消した行を 4 秒だけ取り消せる。取り消さなければ確定する */
export type Row = { id: number; name: string };
const INITIAL_ROWS: Row[] = [
  { id: 1, name: "請求書_10月.pdf" },
  { id: 2, name: "見積書_A社.pdf" },
  { id: 3, name: "議事録_11-02.docx" },
];
export function useUndoList() {
  const [rows, setRows] = useState<Row[]>(INITIAL_ROWS);
  const [removed, setRemoved] = useState<{ row: Row; index: number } | null>(null);
  const timer = useRef<number | undefined>(undefined);
  const remove = useCallback(
    (id: number) => {
      const index = rows.findIndex((r) => r.id === id);
      if (index < 0) return;
      setRemoved({ row: rows[index], index });
      setRows((rs) => rs.filter((r) => r.id !== id));
      window.clearTimeout(timer.current);
      timer.current = window.setTimeout(() => setRemoved(null), 4000);
    },
    [rows],
  );
  const undo = useCallback(() => {
    if (!removed) return;
    window.clearTimeout(timer.current);
    setRows((rs) => {
      const next = [...rs];
      next.splice(removed.index, 0, removed.row);
      return next;
    });
    setRemoved(null);
  }, [removed]);
  const reset = () => {
    window.clearTimeout(timer.current);
    setRows(INITIAL_ROWS);
    setRemoved(null);
  };
  useEffect(() => () => window.clearTimeout(timer.current), []);
  return { rows, removed, remove, undo, reset };
}

/** いいねの粒の飛ぶ向き(6方向) */
export const PARTICLES = [0, 60, 120, 180, 240, 300].map((deg) => {
  const rad = (deg * Math.PI) / 180;
  return { x: Math.cos(rad) * 22, y: Math.sin(rad) * 22 };
});

AIプロンプトテンプレート

React + Framer Motion(motion/react)で、マイクロインタラクションを6つ実装してください。
- いいね:押すとハートが弾み(0.6→1倍、バネ)、6方向に小さな粒が飛んで消える。数が1増える。取り消しでは動かさない
- ブックマーク:枠のアイコンを、塗りつぶしたアイコンで下から上へ塗る(clip-path)。下に「保存しました」をフェードで出す
- コピーしました:コピーのアイコンがチェックに入れ替わり(縮小+回転から戻す)、上に「コピーしました」の吹き出しが出て1.6秒で消える
- 送信ボタン:押すと横幅が丸まで縮み、回る読み込みアイコン → 完了のチェック → 元の「送信」に戻る
- カートに追加:カートのアイコンが小さく揺れ、数字のバッジが上から落ちて弾む
- 削除の取り消し:行が高さ0まで縮んで消え、下に「削除しました/元に戻す」のスナックバーが出る。元に戻すと行が広がって戻る。4秒で確定
- prefers-reduced-motion のとき(とページ上の切り替え)は、弾み・粒・回転をやめ、0.1秒ほどのフェードだけにする
- 動きは motion 要素・AnimatePresence(mode="wait"/"popLayout")・key の付け替えで書く
- TypeScript / Tailwind CSS v4 を使用

このプロンプトはあくまでたたき台です。AIの回答はモデルやバージョン、会話の文脈によって毎回異なります。意図通りに動かない場合は、条件を追記・修正してお使いください。

上記のデモは、React / Next.jsです。Next.jsの基本セットアップは 公式ドキュメントを参照してください。

マイクロインタラクションの決まりごと

マイクロインタラクションは、ひとつの操作に対して「受け取った」「終わった」を返す小さな動きです。主役は操作の結果で、動きはそれを伝える脇役です。

  • 短くする:0.2〜0.5 秒。待たされていると感じさせない
  • 操作した場所で動かす:押したボタンそのもの、またはそのすぐそば
  • 結果を文字でも伝える:「コピーしました」「送信しました」。色や動きだけに頼らない(読み上げにも届くよう role="status" を付ける)
  • 取り消しでは弾ませない:いいねを外すときは、静かに戻す
  • 動きを減らす設定を尊重する:弾み・粒・回転をやめ、短いフェードだけにする

手法ごとのページ

このページは「場面」ごとにまとめています。動きの「手法」ごとに詳しく見るときは、重さと弾み・形の変形・要素の切り替え・順番に動かす・目を引く・表示・非表示のページへ。

このUIについて

マイクロインタラクションは、ボタンを押す・保存する・コピーするといったひとつの操作に、短い動きで「受け取った」「終わった」を返すUI。

SNS のいいね、記事の保存、コードのコピー、フォームの送信、EC のカート追加、メールやファイルの削除と取り消しなど、操作の結果がその場で見えにくい場面で使われる。

主なバリエーション

  • 弾む(スケール・バネ)
  • 塗る(clip-path)
  • 入れ替える(アイコンの切り替え)
  • 縮めて消す(高さ0)
  • 数字のバッジ
  • スナックバー

このページに関するニュース