Communitygithub.com

Padrões de Animação para React/Next.js

Padrões de animação prontos para produção para React/Next.js: botão, modal, toast, escalonamento, transições de página, animações de saída, scroll e layout, construídos com tokens e molas do motion-foundations.

O que é Next.js?

Este skill fornece um conjunto de padrões de animação prontos para copiar e colar, focados em componentes UI comuns em React e Next.js, como botões, cards, modais, notificações toast, listas com efeito escalonado e transições de página no App Router do Next.js. Todos os padrões são construídos sobre os tokens de design e molas (springs) da biblioteca `motion-foundations`, garantindo consistência, acessibilidade e desempenho SSR. O skill também inclui diretrizes claras de uso, como sempre envolver renderizações condicionais com `AnimatePresence` e uma `key`, definir animações de entrada e saída juntas, e usar `viewport={{ once: true }}` para revelações com scroll. Além disso, oferece uma tabela de decisão para ajudar a escolher o padrão correto e identifica anti-padrões comuns, tornando-se um guia abrangente para animações de interface do usuário de alta qualidade.

Funciona com~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/Cody-W-Tucker/skills/tree/HEAD/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 copiáveis para as necessidades mais comuns de animação de 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, card, modal ou notificação toast
  • Criando entradas de lista com efeito escalonado
  • Configurando transições de página no App Router do Next.js
  • Adicionando animações de entrada ou saída a conteúdo condicional
  • Implementando revelação com scroll, progresso vinculado ao scroll ou seções com sticky story
  • Construindo cards expansíveis, accordions ou transições de elementos compartilhados

Saídas

Este skill produz:

  • Animações acessíveis e seguras para SSR em todos os componentes de UI padrão
  • Renderizações condicionais envolvidas com AnimatePresence com comportamento de saída correto
  • Componente wrapper de transição de página para o App Router do Next.js
  • Padrões de revelação com 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.
  • Cada renderização condicional é envolvida em AnimatePresence com uma key.
  • As animações de saída são sempre definidas junto com as animações de entrada — nunca como um pensamento posterior.
  • layout é usado apenas para pequenas mudanças isoladas. 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 chave, 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 seja concluída.
  4. Nunca use layout em subárvores com mais de ~5 filhos ou DOM profundamente aninhado. Use transformações x/y explícitas.
  5. O intervalo de escalonamento deve ficar entre 0.05s e 0.10s. Abaixo disso parece mecânico; acima parece lento.
  6. Modais sempre devem incluir: foco preso, fechamento com tecla Escape, bloqueio de scroll, role="dialog", aria-modal="true".
  7. Revelações com scroll usam viewport={{ once: true }}. Repetir ao sair é distrativo, não informativo.
  8. Todos os valores de token são importados do motion-foundations. Sem números inline.

Orientação para Decisão

Escolhendo o padrão certo

SituaçãoPadrão
Elemento aparece / desapareceAnimatePresence
Lista de itens carregando em sequênciaVariantes escalonadas (Stagger variants)
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 rolado para a vistawhileInView
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 verdadeiras:

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

Se qualquer uma delas estiver faltando, 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 durante as 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 escalonada

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

// Envolva 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 (App Router do Next.js)

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

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

Accordion

<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

Este skill não cobre:

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

Anti-Padrões

Anti-padrãoRegra violadaCorreção
Filho de AnimatePresence sem keyRegra 1Adicione uma 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

Skills Relacionados

  • motion-foundations — define todos os tokens, molas, o hook useSafeMotion e as proteções SSR que cada padrão aqui importa. Deve ser configurado primeiro.
  • motion-advanced — estende estes padrões com arrasto, 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.

Cody-W-Tucker/skills

Landing page quality assessment for paid advertising campaigns. Evaluates message match, page speed, mobile experience, trust signals, form optimization, and conversion rate potential. Use when user says landing page, post-click experience, landing page audit, conversion rate, or landing page optimization.

Cody-W-Tucker/skills

TikTok Ads deep analysis covering creative quality, tracking, bidding, campaign structure, and TikTok Shop. Evaluates 28 checks with emphasis on creative-first strategy, safe zone compliance, and Smart+ campaigns. Use when user says TikTok Ads, TikTok marketing, TikTok Shop, Spark Ads, Smart+, or TikTok campaign.

Cody-W-Tucker/skills

YouTube Ads specific analysis covering campaign types, creative quality, audience targeting, and measurement. Evaluates video ad performance across skippable, non-skippable, bumper, Shorts, Demand Gen, and Connected TV formats. Covers VAC→Demand Gen migration, Shorts creative requirements, and CTV shoppable ads. Use when user says YouTube Ads, video ads, pre-roll, bumper ads, YouTube campaign, Shorts ads, or CTV ads.

Cody-W-Tucker/skills

Craft the story that makes investors say \"I want in.\" Master the narrative structure that Reid Hoffman, Sequoia, and top founders use to raise capital. Use when: **Preparing to fundraise** to develop your story before the deck; **Investor meetings** to structure conversations that convert; **Pitch practice** to refine your narrative arc; **Cold outreach** to write compelling investor emails; **Pivoting** to reframe your story after a change

Cody-W-Tucker/skills

Identify the best GTM motions and tools across 7 motion types: Inbound, Outbound, Paid Digital, Community, Partners, ABM, and PLG. Use when selecting marketing channels, choosing between inbound and outbound strategy, or planning cross-channel campaigns.

Cody-W-Tucker/skills

Produce a print-grade single-page kami (紙 / 纸) document — warm parchment canvas, ink-blue accent, serif at one weight, no italic, no cool grays. The output reads like a professional white paper or studio one-pager, not an app UI. Multilingual by design (EN · zh-CN · ja). One self-contained HTML file, zero dependencies.

Cody-W-Tucker/skills

Optimize landing pages for maximum conversions using proven frameworks from Unbounce and Oli Gardner—apply the \"one goal, one message, one action\" principle with data-driven design, copy, and CTA best practices. Use when: **Create a new landing page** for a campaign; **Optimize an existing landing page** that isn't converting; **Review landing page design** before launch; **Improve form conversion rates** on lead gen pages; **A/B test landing page elements** systematically

Cody-W-Tucker/skills

Advanced motion patterns for React / Next.js — drag & drop, gestures, text animations, SVG path drawing, custom hooks, imperative sequences (useAnimate), loaders, and the full API decision tree. Requires motion-foundations.

Cody-W-Tucker/skills

Motion tokens, spring presets, performance rules, device adaptation, accessibility enforcement, and SSR safety for React / Next.js using motion/react. Foundation layer — all other motion skills depend on this.

Cody-W-Tucker/skills

A single-frame motion-design composition with looping CSS animations — rotating type ring, animated globe, ticking timer, parallax labels. Renders as a hero video poster you can hand straight to HyperFrames or any keyframe-based exporter. Use when the brief asks for "motion design", "animated hero", "loop", "video poster", "title card", or pairs Open Claude Design with HyperFrames for a kinetic export.

Cody-W-Tucker/skills

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

Cody-W-Tucker/skills

Produce a single-file slide deck in the Atelier Zero visual language (warm-paper background, italic-serif emphasis spans, coral terminating dots, surreal collage plates) — Open Design's brand deck recipe. The deck uses **horizontal magazine-style swipe pagination** (←/→, wheel, swipe), a per-slide chrome strip with brand mark and slide counter, an ESC overview grid, a coral progress bar, and inherits the canonical stylesheet + 16-slot image library from the sister `open-design-landing` skill.

Cody-W-Tucker/skills

Produce a world-class single-page editorial landing site in the Atelier Zero visual language (Monocle / Apartamento / Études editorial collage) — the same aesthetic Open Design uses for its own marketing surface. The agent fills a typed `inputs.json` from a brand brief, optionally generates 16 collage assets via gpt-image-2, then runs a pure-function composer that emits a self-contained HTML file; a separate path can mirror the Astro marketing site in `apps/landing-page/`. Drop-in scroll-reveal motion and a Headroom-style sticky nav are wired automatically.

Cody-W-Tucker/skills

Best practices for Remotion - Video creation in React. 29 domain-specific rules covering 3D, animations, audio, captions, charts, transitions, and more.

Cody-W-Tucker/skills

Single-page SaaS landing with hero, features, social proof, pricing, and CTA. Respects the active DESIGN.md color/typography/layout tokens. Trigger keywords: "saas landing", "marketing page", "product landing".

Cody-W-Tucker/skills

Single-page SaaS landing with hero, features, social proof, pricing, and CTA. Respects the active DESIGN.md color/typography/layout tokens. Trigger keywords: "saas landing", "marketing page", "product landing".

Cody-W-Tucker/skills

Master April Dunford's 8-step sales narrative from \"Sales Pitch\" (2023). Transform your positioning into a compelling story that wins enterprise deals. Use when: Structuring B2B sales presentations and demos; Creating pitch decks for complex products; Training sales teams on narrative-driven selling; Converting positioning strategy into sales conversations; Winning against entrenched competitors

Cody-W-Tucker/skills

Swiss-style user-research narrative template in warm-paper editorial aesthetics. Use when users ask for a premium research deck or story-first live artifact with minimalist typography, high-clarity layout, subtle motion, donut breakdowns, and keyboard/click navigation across slides in a single HTML file.

Cody-W-Tucker/skills

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

Cody-W-Tucker/skills

Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.

Habilidades Relacionadas