Communitygithub.com

motion-patterns

React/Next.js 向けの実戦投入可能なアニメーションパターン集 — ボタン、モーダル、トースト、スタガー、ページトランジション、終了アニメーション、スクロール、レイアウト。motion-foundations のトークンとスプリングをベースに構築。React または Next.js で特定の UI 要素をアニメーションさせる際に使用。

motion-patterns とは?

このスキルは、React および Next.js アプリケーションで頻繁に使用される UI アニメーションのためのコピペ可能なパターンを提供します。すべてのパターンは `motion-foundations` ライブラリで定義されたトークンとスプリングに依存しており、開発者は生の数値や独自のイージングを定義する必要がありません。対応範囲は、ボタンのフィードバックやスタガーリスト、モーダル・トーストの表示/非表示、Next.js App Router のページトランジション、スクロールに連動した表示やプログレスバー、アコーディオンやカードの展開、レイアウト ID を利用した共有要素トランジションなど多岐にわたります。 Claude Code, Cursor, Codex などの AI エージェント上で動作し、`AnimatePresence` による条件付きレンダリングや `layout` / `layoutId` プロパティを適切に扱うための厳格なルールと判断ガイドラインも含まれています。アクセシビリティ(モーダルのフォーカストラップ、ロール属性など)や SSR 対応、`useSafeMotion` フックによるユーザーの動きの軽減設定への対応も組み込まれており、プロダクション品質のアニメーションを一貫して生成できます。

対応~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/motion-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Motion Patterns

最も一般的な UI アニメーションニーズに対するコピペ可能なパターン。 ここにあるすべてのパターンは motion-foundations のトークンとスプリングをベースに構築されています。 新しい duration や easing の値を定義せず、インポートしてください。

いつ有効にするか

  • ボタン、カード、モーダル、トースト通知をアニメーションさせる場合
  • スタガー効果でリストの要素を順に表示する場合
  • Next.js App Router でページトランジションを構築する場合
  • 条件付きコンテンツに出現・終了アニメーションを追加する場合
  • スクロールに応じた表示、スクロール連動プログレス、スティッキーなストーリーセクションを実装する場合
  • 展開カード、アコーディオン、共有要素トランジションを構築する場合

出力内容

このスキルは以下を生成します:

  • アクセシブルで SSR セーフな、すべての標準 UI コンポーネント向けアニメーション
  • 正しい終了動作を持つ AnimatePresence でラップされた条件付きレンダリング
  • Next.js App Router 用のページトランジションラッパーコンポーネント
  • useScroll + useTransform を使用したスクロール表示・スクロール連動パターン
  • 展開およびクロスフェード要素のためのレイアウトアニメーションパターン(layout、layoutId)

原則

  • すべてのパターンは motion-foundations からインポートします。生の数値は使用しません。
  • すべての条件付きレンダリングは AnimatePresence でラップし、key を指定します。
  • 終了アニメーションは常に出現アニメーションと一緒に定義し、後付けにしてはいけません。
  • layout は小さく隔離された動きにのみ使用します。大きなサブツリーには明示的なトランスフォームを使用します。

ルール

  1. 常に条件付きレンダリングを AnimatePresence でラップし、直接の子要素に key を付与します。 key がないと終了アニメーションは決して実行されません。
  2. initial + animate を定義するときは常に exit も定義します。 終了のないアニメーションは不完全です。
  3. ページトランジションには mode="wait" を使用します。 終了が完了するまで出現を開始しないようにします。
  4. 子要素が約5個以上、または DOM が深くネストされているサブツリーでは layout を使用しないでください。 代わりに明示的な x/y トランスフォームを使用します。
  5. スタガー間隔は必ず 0.05s ~ 0.10s の範囲に収めます。 これより短いと機械的に、長いと緩慢に見えます。
  6. モーダルには常に以下を含める必要があります: フォーカストラップ、Escape キーでの閉じる操作、スクロールロック、role="dialog"、aria-modal="true"。
  7. スクロールリビールは viewport={{ once: true }} を使用します。 スクロールアウト時に繰り返すと、情報的ではなく邪魔になります。
  8. すべてのトークン値は motion-foundations からインポートされます。 インラインの数値は使用しません。

判断ガイドライン

適切なパターンの選択

状況パターン
要素が表示 / 非表示になるAnimatePresence
アイテムのリストが順に読み込まれるスタガーバリアント
ルート間を移動するページトランジションラッパー
要素がその場でサイズを変えるlayout プロパティ
同じ要素がページコンテキスト間を移動するlayoutId
要素がビューポートにスクロールされたときに入るwhileInView
値がスクロール位置に連動するuseScroll + useTransform

mode="wait" と mode="sync" の使い分け

モード使用時
waitページトランジション、コンテンツの入れ替え(一度に一つ)
sync積み上げ通知、リストアイテム(重なりが許容される場合)
popLayoutリフローするリストからアイテムが削除される場合

コアコンセプト

AnimatePresence 契約

以下の3つが常に真である必要があります:

  1. AnimatePresence が条件をラップしている
  2. 直接の子要素が key を持っている
  3. 子要素が exit プロパティを持っている

このうちどれか一つでも欠けると、終了アニメーションは静かに失敗します。

layout と layoutId の違い

  • layout — 要素自身のサイズ/位置の変化をその場でアニメーションする
  • layoutId — 2つの別々の要素をリンクし、レンダリング間でクロスフェードする

拡大するコンテナ内のテキストには layout="position" を使用して、テキストのリフローがアニメーションしないようにします。

コード例

ボタンフィードバック

"use client"
import { motion } from "motion/react"
import { springs, motionTokens } from "@/lib/motion-tokens"

<motion.button
  whileHover={{ scale: motionTokens.scale.pop }}
  whileTap={{ scale: motionTokens.scale.press }}
  transition={springs.snappy}
/>

スタガーリスト

"use client"
import { motion } from "motion/react"
import { motionTokens, springs } from "@/lib/motion-tokens"

const container = {
  hidden: {},
  visible: {
    transition: {
      staggerChildren: 0.08,   // 0.05–0.10 のルール内
      delayChildren: 0.1,
    },
  },
}

const item = {
  hidden:  { opacity: 0, y: motionTokens.distance.md },
  visible: { opacity: 1, y: 0, transition: springs.gentle },
}

<motion.ul variants={container} initial="hidden" animate="visible">
  {items.map((i) => (
    <motion.li key={i.id} variants={item} />
  ))}
</motion.ul>

モーダル

"use client"
import { motion, AnimatePresence } from "motion/react"
import { motionTokens, springs } from "@/lib/motion-tokens"

// 呼び出し側でラップ:
// <AnimatePresence>{isOpen && <Modal key="modal" />}</AnimatePresence>

export function Modal({ onClose }: { onClose: () => void }) {
  return (
    <>
      {/* オーバーレイ */}
      <motion.div
        className="fixed inset-0 bg-black/50"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        onClick={onClose}
      />

      {/* パネル — アクセシビリティ要件: フォーカストラップ、Escape キーで閉じる、
          スクロールロック、role="dialog"、aria-modal="true" */}
      <motion.div
        role="dialog"
        aria-modal="true"
        className="fixed inset-x-4 top-1/2 -translate-y-1/2 rounded-xl bg-white p-6"
        initial={{
          opacity: 0,
          scale: motionTokens.scale.press,
          y: motionTokens.distance.sm,
        }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{
          opacity: 0,
          scale: motionTokens.scale.press,
          y: motionTokens.distance.sm,
        }}
        transition={springs.gentle}
      />
    </>
  )
}

トーストスタック

"use client"
import { motion, AnimatePresence } from "motion/react"
import { motionTokens, springs } from "@/lib/motion-tokens"

<AnimatePresence mode="sync">
  {toasts.map((t) => (
    <motion.div
      key={t.id}
      layout
      initial={{
        opacity: 0,
        x: motionTokens.distance.xl,
        scale: motionTokens.scale.subtle,
      }}
      animate={{ opacity: 1, x: 0, scale: 1 }}
      exit={{
        opacity: 0,
        x: motionTokens.distance.xl,
        scale: motionTokens.scale.subtle,
      }}
      transition={springs.snappy}
    />
  ))}
</AnimatePresence>

ページトランジション(Next.js App Router)

// components/page-transition.tsx
"use client"
import { motion, AnimatePresence } from "motion/react"
import { usePathname } from "next/navigation"
import { motionTokens } from "@/lib/motion-tokens"

const variants = {
  initial: { opacity: 0, y: motionTokens.distance.sm },
  enter:   { opacity: 1, y: 0 },
  exit:    { opacity: 0, y: -motionTokens.distance.sm },
}

export function PageTransition({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  return (
    <AnimatePresence mode="wait">
      <motion.div
        key={pathname}
        variants={variants}
        initial="initial"
        animate="enter"
        exit="exit"
        transition={{
          duration: motionTokens.duration.normal,
          ease: motionTokens.easing.smooth,
        }}
      >
        {children}
      </motion.div>
    </AnimatePresence>
  )
}

スクロールリビール

"use client"
import { motion } from "motion/react"
import { motionTokens, springs } from "@/lib/motion-tokens"

<motion.div
  initial={{ opacity: 0, y: motionTokens.distance.lg }}
  whileInView={{ opacity: 1, y: 0 }}
  viewport={{ once: true, margin: "-80px" }}   // once: true — ルール 7
  transition={{ duration: motionTokens.duration.slow, ease: motionTokens.easing.smooth }}
/>

スクロールプログレスバー

"use client"
import { motion, useScroll } from "motion/react"

export function ScrollProgress() {
  const { scrollYProgress } = useScroll()
  return (
    <motion.div
      className="fixed top-0 left-0 h-1 bg-indigo-500 origin-left w-full"
      style={{ scaleX: scrollYProgress }}
    />
  )
}

展開カード

"use client"
import { useState } from "react"
import { motion, AnimatePresence } from "motion/react"
import { springs, motionTokens } from "@/lib/motion-tokens"

export function ExpandingCard({ title, body }: { title: string; body: string }) {
  const [expanded, setExpanded] = useState(false)

  return (
    <motion.div layout onClick={() => setExpanded(!expanded)} className="cursor-pointer">
      {/* layout="position" によりテキストのリフローがアニメーションしない */}
      <motion.h2 layout="position" className="font-semibold">
        {title}
      </motion.h2>

      <AnimatePresence>
        {expanded && (
          <motion.p
            key="body"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: motionTokens.duration.fast }}
          >
            {body}
          </motion.p>
        )}
      </AnimatePresence>
    </motion.div>
  )
}

共有要素クロスフェード

// ソースコンテキスト
<motion.img layoutId="hero-image" src={src} className="w-16 h-16 rounded" />

// 宛先コンテキスト(同じ layoutId — motion がトランジションを処理)
<motion.img layoutId="hero-image" src={src} className="w-full rounded-xl" />

アコーディオン

<motion.div
  initial={false}
  animate={{ opacity: open ? 1 : 0, scaleY: open ? 1 : 0 }}
  style={{ transformOrigin: "top", overflow: "hidden" }}
  transition={{
    duration: motionTokens.duration.normal,
    ease: motionTokens.easing.smooth,
  }}
> {children}
</motion.div>

エンドツーエンドの例

マウント時に現れ、条件付きプレゼンスを処理し、動きの軽減設定を尊重するスタガーリスト — トークン、スプリング、AnimatePresence、そして motion-foundations のアクセシビリティフックを組み合わせたもの:

"use client"
import { useState } from "react"
import { motion, AnimatePresence } from "motion/react"
import { motionTokens, springs } from "@/lib/motion-tokens"
import { useSafeMotion } from "@/hooks/use-reduced-motion"

const containerVariants = {
  hidden: {},
  visible: {
    transition: { staggerChildren: 0.08, delayChildren: 0.1 },
  },
}

function ListItem({ label, onRemove }: { label: string; onRemove: () => void }) {
  const safe = useSafeMotion(motionTokens.distance.sm)
  return (
    <motion.li
      variants={{
        hidden:  safe.initial,
        visible: safe.animate,
      }}
      exit={safe.exit}
      transition={springs.gentle}
      className="flex items-center justify-between p-3 rounded-lg bg-white shadow-sm"
    >
      <span>{label}</span>
      <button onClick={onRemove}>削除</button>
    </motion.li>
  )
}

export function AnimatedList({ items, onRemove }: {
  items: { id: string; label: string }[]
  onRemove: (id: string) => void
}) {
  return (
    <motion.ul
      variants={containerVariants}
      initial="hidden"
      animate="visible"
      className="space-y-2"
    >
      <AnimatePresence mode="popLayout">
        {items.map((item) => (
          <ListItem
            key={item.id}
            label={item.label}
            onRemove={() => onRemove(item.id)}
          />
        ))}
      </AnimatePresence>
    </motion.ul>
  )
}

制約 / 対象外

このスキルは以下を カバーしません:

  • トークンとスプリングの定義 → motion-foundations を参照
  • ドラッグ操作、スワイプジェスチャー、並べ替え可能リスト → motion-advanced を参照
  • テキストアニメーション(単語/文字の表示、カウンター) → motion-advanced を参照
  • SVG パス描画またはモーフィング → motion-advanced を参照
  • カスタムアニメーションフック → motion-advanced を参照
  • motion/react を使用しない CSS のみのトランジション

アンチパターン

アンチパターン違反するルール修正方法
AnimatePresence の子要素に key がないルール 1直接の子要素に安定した key を追加
initial + animate に exit がないルール 2常に3つすべてを一緒に定義する
mode="wait" のないページトランジションルール 3AnimatePresence に mode="wait" を追加
50 個のアイテムがあるリストでの layoutルール 4mode="popLayout" または明示的なトランスフォームを使用
10 個のアイテムがあるリストでの staggerChildren: 0.2ルール 50.08–0.10 に抑える
フォーカストラップのないモーダルルール 6focus-trap-react または Radix Dialog を追加
viewport={{ once: true }} のない whileInViewルール 7繰り返し出現は情報的でなく邪魔
transition={{ duration: 0.3 }} のインライン記述ルール 8motionTokens.duration.normal を使用

関連スキル

  • motion-foundations — ここにあるすべてのパターンがインポートする、すべてのトークン、スプリング、useSafeMotion フック、SSR ガードを定義します。最初にセットアップする必要があります。
  • motion-advanced — これらのパターンをドラッグ、ジェスチャー、SVG、テキスト、カスタムフック、命令型シーケンスで拡張します。このスキルのパターンを再定義することはありません。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル