Communitygithub.com

padrões-de-animação

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 — construídos sobre tokens e molas motion-foundations. Use ao animar um elemento específico de UI em React ou Next.js.

O que é padrões-de-animação?

Este skill oferece padrões de animação replicáveis e prontos para produção para os componentes de UI mais comuns em React e Next.js, como botões, modais, toasts, listas com escalonamento, transições de página e animações ativadas por scroll. Todos os padrões são construídos sobre os tokens e molas definidos em `motion-foundations`, garantindo consistência visual e desempenho. O skill enfatiza a acessibilidade, sendo SSR-safe, e impõe regras rigorosas, como sempre usar `AnimatePresence` com `key` em renders condicionais, definir animações de saída (`exit`) sempre que houver entrada (`initial`/`animate`), e usar `mode="wait"` em transições de página. Ele também fornece orientação clara sobre quando usar `layout` vs `layoutId`, `whileInView` para revelações no scroll, e inclui exemplos completos de código que seguem as melhores práticas de performance e acessibilidade, como foco em modais e `viewport={{ once: true }}` em animações de scroll. O skill não cobre animações avançadas como arrastar, gestos ou animações de texto, que são delegadas ao skill `motion-advanced`.

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

Perguntar na sua IA favorita

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

Documentação

Padrões de Animação (Motion Patterns)

Padrões de copiar e colar para as necessidades mais comuns de animação em UI. Cada padrão aqui é construído sobre os 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 em conteúdo condicional
  • Implementando animações de revelação no scroll, progresso vinculado ao scroll ou seções de história fixas
  • Construindo cartões expansíveis, acordeões ou transições de elemento compartilhado

Resultados

Este skill produz:

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

Princípios

  • Cada padrão importa de motion-foundations. Sem números brutos.
  • Cada render condicional é encapsulado em AnimatePresence com uma key.
  • Animações de saída são sempre definidas junto com as de entrada — nunca como reflexão tardia.
  • layout é usado apenas para pequenas mudanças isoladas. Subárvores grandes recebem transformações explícitas.

Regras

  1. Sempre encapsule renders condicionais em AnimatePresence com uma key no filho direto. Sem uma key, as animações de saída nunca sã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 com x/y.
  5. O intervalo de escalonamento (stagger) deve ficar entre 0.05s e 0.10s. Abaixo disso parece mecânico; acima parece lento.
  6. Modais devem sempre incluir: armadilha de foco (focus trap), fechamento com tecla Escape, bloqueio de scroll, role="dialog", aria-modal="true".
  7. Revelações no scroll usam viewport={{ once: true }}. Repetir ao sair do scroll é distrativo, não informativo.
  8. Todos os valores de token são importados de motion-foundations. Sem números inline.

Orientação de Decisão

Escolhendo o padrão certo

SituaçãoPadrão
Elemento aparece / desapareceAnimatePresence
Lista de itens carregando em sequênciaVariantes com 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 vinculado à posição do scrolluseScroll + useTransform

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

ModoUse quando
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 devem ser sempre verdade:

  1. AnimatePresence encapsula o condicional
  2. O filho direto tem uma key
  3. O filho tem uma propriedade exit

Se algum destes faltar, 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 — conecta dois elementos separados, fazendo crossfade entre eles em diferentes renders

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"

// Encapsule 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: focus trap, 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 no 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 do 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 com escalonamento 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

Este skill não cobre:

  • Definições de tokens e molas → veja motion-foundations
  • Interações de arrastar, gestos de deslizar, listas reordenáveis → veja motion-advanced
  • Animações de texto (revelação de palavras/caracteres, contadores) → veja motion-advanced
  • Desenho de caminhos SVG ou morphing → veja motion-advanced
  • Hooks de animação personalizados → veja motion-advanced
  • Transições apenas em CSS que não usam 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 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 armadilha de focoRegra 6Adicione focus-trap-react ou Radix Dialog
whileInView sem viewport={{ once: true }}Regra 7Entradas repetitivas distraem, não informam
transition={{ duration: 0.3 }} inlineRegra 8Use motionTokens.duration.normal

Skills Relacionados

  • motion-foundations — define todos os tokens, molas, o hook useSafeMotion e proteções SSR que todo padrão aqui importa. Deve ser configurado primeiro.
  • motion-advanced — estende estes padrões com arrastar, gestos, SVG, texto, hooks personalizados e sequenciamento imperativo. Não redefine nenhum padrão deste skill.

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.

Habilidades Relacionadas