Communitygithub.com

Patrones de Animación (Motion Patterns)

Patrones de animación listos para producción para React / Next.js — botón, modal, notificación, escalonado, transiciones de página, animaciones de salida, scroll y layout — construidos sobre tokens y springs de motion-foundations.

¿Qué es Patrones de Animación (Motion Patterns)?

Este skill proporciona un conjunto completo de patrones de animación reutilizables y listos para producción para React y Next.js. Está diseñado para desarrolladores que necesitan implementar animaciones de interfaz de usuario comunes de forma rápida y accesible, adhiriéndose a las mejores prácticas de rendimiento y accesibilidad. El skill está construido sobre el sistema de tokens y springs de 'motion-foundations', lo que garantiza consistencia visual y evita valores codificados. Cubre animaciones para botones, tarjetas, modales, notificaciones, listas escalonadas, transiciones de página en Next.js App Router, revelaciones al hacer scroll, barras de progreso de scroll, tarjetas expandibles, acordeones y transiciones de elementos compartidos. Es compatible con las plataformas React y Next.js, utilizando la librería `motion`. El skill se activa ante cualquier necesidad de animación de componentes de UI y produce código SSR-seguro y accesible. Sigue principios estrictos como envolver siempre los renders condicionales en `AnimatePresence` con una `key`, definir animaciones de salida, usar `mode="wait"` para transiciones de página, y limitar el uso de `layout` a pequeños cambios aislados.

Compatible con~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/Cody-W-Tucker/skills/tree/HEAD/skills/motion-patterns

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

¿Qué hace Patrones de Animación (Motion Patterns)?

Patrones de copiar y pegar para las necesidades de animación de UI más comunes. Cada patrón aquí está construido sobre los tokens y springs de motion-foundations. No definas nuevos valores de duración o easing aquí — impórtalos.

Cuándo Activar

  • Al animar un botón, tarjeta, modal o notificación (toast)
  • Al construir entradas de listas con escalonado (stagger)
  • Al configurar transiciones de página en Next.js App Router
  • Al añadir animaciones de entrada o salida a contenido condicional
  • Al implementar revelaciones por scroll, progreso vinculado al scroll o secciones adhesivas (sticky)
  • Al construir tarjetas expandibles, acordeones o transiciones de elementos compartidos

Salidas

Este skill produce:

  • Animación accesible y segura para SSR para todos los componentes de UI estándar
  • Renderizados condicionales envueltos en AnimatePresence con comportamiento de salida correcto
  • Componente envolvente de transición de página para Next.js App Router
  • Patrones de revelación por scroll y vinculados al scroll usando useScroll + useTransform
  • Patrones de animación de layout (layout, layoutId) para expandir y difuminar elementos

Principios

  • Cada patrón importa desde motion-foundations. Sin números directos.
  • Cada render condicional está envuelto en AnimatePresence con una key.
  • Las animaciones de salida siempre se definen junto con las de entrada — nunca como una ocurrencia tardía.
  • layout se usa solo para cambios pequeños y aislados. Los subárboles grandes reciben transformaciones explícitas.

Reglas

  1. Envuelve siempre los renders condicionales en AnimatePresence con una key en el hijo directo. Sin una key, las animaciones de salida nunca se ejecutan.
  2. Define siempre exit cuando definas initial + animate. Una animación sin salida está incompleta.
  3. Usa mode="wait" en las transiciones de página. La entrada no debe comenzar hasta que la salida se complete.
  4. Nunca uses layout en subárboles con más de ~5 hijos o DOM profundamente anidado. Usa transformaciones explícitas con x/y en su lugar.
  5. El intervalo de escalonado (stagger) debe mantenerse entre 0.05 s y 0.10 s. Por debajo se siente mecánico; por encima se siente lento.
  6. Los modales siempre deben incluir: trampa de foco (focus trap), cierre con tecla Escape, bloqueo de scroll, role="dialog", aria-modal="true".
  7. Las revelaciones por scroll usan viewport={{ once: true }}. Repetir al salir del viewport distrae, no informa.
  8. Todos los valores de token se importan de motion-foundations. Sin números en línea.

Guía de Decisión

Elegir el patrón correcto

SituaciónPatrón
El elemento aparece / desapareceAnimatePresence
Lista de elementos cargando en secuenciaVariantes con escalonado (stagger)
Navegando entre rutasEnvolvente de transición de página
El elemento cambia de tamaño en su lugarPropiedad layout
El mismo elemento se mueve entre contextos de páginalayoutId
El elemento aparece al hacer scroll hasta élwhileInView
Valor vinculado a la posición de scrolluseScroll + useTransform

Cuándo usar mode="wait" vs mode="sync"

ModoÚsalo cuando
waitTransiciones de página, intercambios de contenido (uno a la vez)
syncNotificaciones apiladas, elementos de lista (la superposición está bien)
popLayoutElementos eliminados de una lista con reflujo

Conceptos Clave

Contrato de AnimatePresence

Tres cosas siempre deben ser ciertas:

  1. AnimatePresence envuelve el condicional
  2. El hijo directo tiene una key
  3. El hijo tiene una propiedad exit

Si falta alguna de estas, la animación de salida falla silenciosamente.

layout vs layoutId

  • layout — anima el cambio de tamaño/posición del propio elemento en su lugar
  • layoutId — vincula dos elementos separados, difuminando entre ellos a través de renders

Usa layout="position" en el texto dentro de un contenedor en expansión para evitar que el reflujo del texto se anime.

Ejemplos de Código

Feedback de botón

"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 (stagger)

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

const container = {
  hidden: {},
  visible: {
    transition: {
      staggerChildren: 0.08,   // dentro de la regla 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 en el sitio de llamada:
// <AnimatePresence>{isOpen && <Modal key="modal" />}</AnimatePresence>

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

      {/* Panel — requisitos de accesibilidad: trampa de foco, cierre con Escape,
          bloqueo 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}
      />
    </>
  )
}

Pila de notificaciones (toast)

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

Transición 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>
  )
}

Revelación por 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 — regla 7
  transition={{ duration: motionTokens.duration.slow, ease: motionTokens.easing.smooth }}
/>

Barra de progreso 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 }}
    />
  )
}

Tarjeta expandible

"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" evita que el reflujo del texto se anime */}
      <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>
  )
}

Difuminado de elemento compartido (crossfade)

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

// Contexto de destino (mismo layoutId — motion maneja la transición)
<motion.img layoutId="hero-image" src={src} className="w-full rounded-xl" />

Acordeón

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

Ejemplo Completo

Una lista escalonada que entra al montar, maneja presencia condicional y respeta el movimiento reducido — combinando tokens, springs, AnimatePresence y el hook de accesibilidad de 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}>Eliminar</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>
  )
}

Restricciones / No Objetivos

Este skill no cubre:

  • Definiciones de tokens y springs → ver motion-foundations
  • Interacciones de arrastre, gestos de deslizamiento, listas reordenables → ver motion-advanced
  • Animaciones de texto (revelación de palabras/caracteres, contadores) → ver motion-advanced
  • Dibujo o morphing de trazados SVG → ver motion-advanced
  • Hooks de animación personalizados → ver motion-advanced
  • Transiciones solo CSS que no usen motion/react

Anti-patrones

Anti-patrónRegla violadaCorrección
Hijo de AnimatePresence sin keyRegla 1Añade key estable al hijo directo
initial + animate sin exitRegla 2Siempre define los tres juntos
Transición de página sin mode="wait"Regla 3Añade mode="wait" a AnimatePresence
layout en una lista de 50 elementosRegla 4Usa mode="popLayout" o transformaciones explícitas
staggerChildren: 0.2 en una lista de 10 elementosRegla 5Limita a 0.08–0.10
Modal sin trampa de focoRegla 6Añade focus-trap-react o Radix Dialog
whileInView sin viewport={{ once: true }}Regla 7Las entradas repetidas distraen, no informan
transition={{ duration: 0.3 }} en líneaRegla 8Usa motionTokens.duration.normal

Skills Relacionados

  • motion-foundations — define todos los tokens, springs, el hook useSafeMotion y las protecciones SSR que cada patrón aquí importa. Debe configurarse primero.
  • motion-advanced — extiende estos patrones con arrastre, gestos, SVG, texto, hooks personalizados y secuenciación imperativa. No redefine ningún patrón de este 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.

Skills relacionados