Communitygithub.com

Padrões de Animação Motion

Padrões de animação prontos para produção em React/Next.js — botão, modal, toast, escalonamento, transições de página, animações de saída, scroll e layout — baseados em tokens e molas do motion-foundations. Use este padrão ao animar um elemento de UI específico em React ou Next.js — botão, modal, toast, escalonamento, transição de página ou scroll.

O que é Padrões de Animação Motion?

Motion Patterns é um conjunto de padrões de animação copiáveis e prontos para produção, desenvolvidos para React e Next.js. Ele abrange desde animações simples de botões até transições complexas de página, escalonamento de listas, modais acessíveis, toasts empilhados e revelação sob scroll. Todos os padrões se baseiam em tokens e molas (springs) da biblioteca `motion-foundations`, garantindo consistência e desempenho. A habilidade enfatiza boas práticas como usar `AnimatePresence` com `key` e `exit` para animações de saída corretas, evitar `layout` em subárvores grandes e manter intervalos de escalonamento entre 0,05s e 0,10s. Ela é ativada sempre que você precisar animar elementos condicionais, transições entre rotas no App Router do Next.js, listas com entrada escalonada, modais ou elementos que reagem ao scroll. O código gerado é SSR-safe e acessível, seguindo regras como foco em modais e `viewport: {{ once: true }}` para animações de scroll.

Funciona com~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/motion-patterns

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que Padrões de Animação Motion faz?

Padrões copiáveis para as necessidades mais comuns de animação em UI. Cada padrão aqui é construído com base em tokens e molas do motion-foundations. Não defina novos valores de duração ou easing aqui — importe-os.

Quando Ativar

  • Animando um botão, cartão, modal ou notificação toast
  • Construindo entradas de lista com escalonamento (stagger)
  • Configurando transições de página no Next.js App Router
  • Adicionando animações de entrada ou saída a conteúdo condicional
  • Implementando revelação sob scroll, progresso vinculado ao scroll ou seções de história fixas (sticky)
  • Construindo cartões expansíveis, acordeões ou transições de elemento compartilhado

Saídas

Esta habilidade produz:

  • Animações acessíveis e seguras para SSR para todos os componentes padrão de UI
  • Renderizações condicionais envolvidas com AnimatePresence com comportamento de saída correto
  • Componente wrapper de transição de página para Next.js App Router
  • Padrões de revelação sob scroll e vinculados ao scroll usando useScroll + useTransform
  • Padrões de animação de layout (layout, layoutId) para elementos expansíveis e crossfade

Princípios

  • Cada padrão importa do motion-foundations. Sem números brutos.
  • Toda renderização condicional é envolvida em AnimatePresence com uma key.
  • Animações de saída são sempre definidas junto com as de entrada — nunca como um pensamento posterior.
  • layout é usado apenas para pequenos deslocamentos isolados. Subárvores grandes recebem transformações explícitas.

Regras

  1. Sempre envolva renderizações condicionais em AnimatePresence com uma key no filho direto. Sem uma key, as animações de saída nunca serão executadas.
  2. Sempre defina exit ao definir initial + animate. Uma animação sem saída está incompleta.
  3. Use mode="wait" em transições de página. A entrada não deve começar até que a saída termine.
  4. Nunca use layout em subárvores com mais de ~5 filhos ou DOM profundamente aninhado. Use transformações explícitas em x/y.
  5. O intervalo de escalonamento (stagger) deve permanecer entre 0.05s e 0.10s. Abaixo disso parece mecânico; acima parece lerdo.
  6. Modais devem sempre incluir: foco preso (focus trap), fechamento com tecla Escape, bloqueio de scroll, role="dialog", aria-modal="true".
  7. Revelações sob scroll usam viewport={{ once: true }}. Repetir ao sair do scroll é distrativo, não informativo.
  8. Todos os valores de token são importados do motion-foundations. Sem números inline.

Guia de Decisão

Escolhendo o padrão certo

SituaçãoPadrão
Elemento aparece / desapareceAnimatePresence
Lista de itens carregando em sequênciaVariantes com escalonamento (stagger)
Navegando entre rotasWrapper de transição de página
Elemento muda de tamanho no lugarPropriedade layout
Mesmo elemento se move entre contextos de páginalayoutId
Elemento entra quando visível no scrollwhileInView
Valor atrelado à posição do scrolluseScroll + useTransform

Quando usar mode="wait" vs mode="sync"

ModoQuando usar
waitTransições de página, trocas de conteúdo (um de cada vez)
syncNotificações empilhadas, itens de lista (sobreposição é aceitável)
popLayoutItens removidos de uma lista com reflow

Conceitos Principais

Contrato do AnimatePresence

Três coisas sempre devem ser verdade:

  1. AnimatePresence envolve a condicional
  2. O filho direto tem uma key
  3. O filho tem uma propriedade exit

Se qualquer uma dessas falhar, a animação de saída falha silenciosamente.

layout vs layoutId

  • layout — anima a própria mudança de tamanho/posição do elemento no lugar
  • layoutId — liga dois elementos separados, aplicando crossfade entre eles através de renderizações

Use layout="position" em texto dentro de um contêiner expansível para evitar que o reflow do texto seja animado.

Exemplos de Código

Feedback de botão

"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}
/>

Lista com escalonamento (stagger)

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

const container = {
  hidden: {},
  visible: {
    transition: {
      staggerChildren: 0.08,   // dentro da regra 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>

Modal

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

// Envolver no local de chamada:
// <AnimatePresence>{isOpen && <Modal key="modal" />}</AnimatePresence>

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

      {/* Painel — requisitos de acessibilidade: foco preso, fechamento com Escape,
          bloqueio de scroll, 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}
      />
    </>
  )
}

Pilha de toasts

"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>

Transição de página (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>
  )
}

Revelação sob scroll

"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 — regra 7
  transition={{ duration: motionTokens.duration.slow, ease: motionTokens.easing.smooth }}
/>

Barra de progresso de scroll

"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 }}
    />
  )
}

Cartão expansível

"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" impede que o reflow do texto seja animado */}
      <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>
  )
}

Crossfade de elemento compartilhado

// Contexto de origem
<motion.img layoutId="hero-image" src={src} className="w-16 h-16 rounded" />

// Contexto de destino (mesmo layoutId — motion lida com a transição)
<motion.img layoutId="hero-image" src={src} className="w-full rounded-xl" />

Acordeão

<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>

Exemplo Completo

Uma lista escalonada que entra na montagem, lida com presença condicional e respeita movimento reduzido — combinando tokens, molas, AnimatePresence e o hook de acessibilidade do 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}>Remover</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>
  )
}

Restrições / Não-Objetivos

Esta habilidade não cobre:

  • Definições de tokens e molas → veja motion-foundations
  • Interações de arrasto, gestos de swipe, listas reordenáveis → veja motion-advanced
  • Animações de texto (revelação de palavra/caractere, contadores) → veja motion-advanced
  • Desenho ou morphing de caminho SVG → veja motion-advanced
  • Hooks de animação personalizados → veja motion-advanced
  • Transições apenas com CSS sem usar motion/react

Anti-Padrões

Anti-padrãoRegra violadaCorreção
Filho de AnimatePresence sem keyRegra 1Adicione key estável ao filho direto
initial + animate sem exitRegra 2Sempre defina todos os três juntos
Transição de página sem mode="wait"Regra 3Adicione mode="wait" ao AnimatePresence
layout em uma lista de 50 itensRegra 4Use mode="popLayout" ou transformações explícitas
staggerChildren: 0.2 em uma lista de 10 itensRegra 5Limite a 0.08–0.10
Modal sem foco presoRegra 6Adicione focus-trap-react ou Radix Dialog
whileInView sem viewport={{ once: true }}Regra 7Entradas repetidas distraem, não informam
transition={{ duration: 0.3 }} inlineRegra 8Use motionTokens.duration.normal

Habilidades Relacionadas

  • motion-foundations — define todos os tokens, molas, o hook useSafeMotion e guards SSR que cada padrão aqui importa. Deve ser configurado primeiro.
  • motion-advanced — estende esses padrões com arrasto, gestos, SVG, texto, hooks personalizados e sequenciamento imperativo. Não redefine nenhum padrão desta habilidade.

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

Habilidades Relacionadas