Communitygithub.com

Motion Foundations

Tokens de movimiento, presets de resorte, reglas de rendimiento, adaptación a dispositivos, cumplimiento de accesibilidad y seguridad SSR para React / Next.js usando motion/react. Capa base — todas las demás habilidades de movimiento dependen de esta.

¿Qué es Motion Foundations?

Esta habilidad establece los cimientos del sistema de movimiento para React y Next.js con motion/react. Define un conjunto compartido de tokens (duración, easing, distancia, escala), una colección de presets de resorte (springs) y funciones de tiempo de ejecución como `shouldAnimate()` y `prefersReduced()`. El objetivo principal es aplicar reglas no negociables: usar exclusivamente `motion/react`, sincronizar el estado inicial con el renderizado del servidor para evitar discrepancias de hidratación, deshabilitar animaciones cuando `prefersReducedMotion` está activado, y prohibir propiedades de layout en animaciones. Además, incluye directrices para elegir duraciones y resortes según el contexto, una puerta de acceso para dispositivos de bajos recursos, y ejemplos de implementación completos con TypeScript, React hooks y CSS. Es la capa base sobre la que se apoyan las habilidades `motion-patterns` y `motion-advanced`.

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

Preguntar en tu IA favorita

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

Documentación

¿Qué hace Motion Foundations?

La capa base del sistema de movimiento. Define cada valor, restricción y regla que las habilidades descendentes (motion-patterns, motion-advanced) heredan. Carga esta habilidad antes de comenzar cualquier trabajo de animación.

Cuándo activarla

  • Al comenzar cualquier componente animado desde cero
  • Al configurar tokens, presets de resorte o valores de easing
  • Al implementar soporte para prefers-reduced-motion
  • Al depurar discrepancias de hidratación causadas por estados iniciales de animación
  • Al evaluar si una animación debería existir en absoluto

Resultados

Esta habilidad produce:

  • Un objeto compartido motionTokens (duración, easing, distancia, escala)
  • Un mapa de presets springs (5 configuraciones nombradas)
  • Una puerta shouldAnimate() utilizada por todos los componentes
  • Valores predeterminados de animación accesibles mediante useReducedMotion
  • Estados iniciales seguros para SSR con cero advertencias de hidratación

Principios

El movimiento debe cumplir al menos una de las siguientes condiciones, o debe eliminarse:

  • Guiar la atención
  • Comunicar estado
  • Preservar la continuidad espacial

La capacidad de respuesta siempre supera a la fluidez. Una animación a 60 fps que causa retraso en la entrada es peor que ninguna animación.

Reglas

Estas son innegociables. Se aplican a todos los componentes del sistema.

  1. Usar solo motion/react. Nunca importar desde framer-motion. No mezclar ambos en el mismo árbol.
  2. initial debe coincidir con la salida del servidor. Si el servidor renderiza opacity: 1, la prop initial también debe ser opacity: 1. Sin excepciones.
  3. Movimiento reducido lo anula todo. Cuando useReducedMotion() devuelve true o prefersReduced es true, todas las transformaciones se deshabilitan. Solo se permiten fundidos de opacidad con una duración ≤ 0,2 s como alternativa.
  4. Nunca animar propiedades de layout. width, height, top, left, margin, padding están prohibidos en animate. Usar solo transform y opacity.
  5. Todos los valores de token provienen de motionTokens. Las duraciones y easings escritos directamente en archivos de componente están prohibidos.
  6. Todas las configuraciones de resorte provienen del mapa springs. Los valores stiffness/damping en línea están prohibidos.
  7. Se requiere "use client" en todo archivo que importe desde motion/react.
  8. Nunca leer window o navigator a nivel de módulo. Siempre proteger con typeof window !== "undefined".

Guía de decisión

Elegir una duración

TokenUsar cuando
instantMostrar/ocultar tooltip, anillo de foco, actualización de badge
fastRetroalimentación de botón, cambio de icono, toggle de chip
normalApertura de modal, expansión de tarjeta, entrada de elemento de página
slowEntrada de héroe, transición de página completa
crawlNarración deliberada; usar con moderación

Elegir un resorte

PresetUsar cuando
snappyUI por defecto — botones, chips, elementos de navegación
gentleTarjetas, modales, paneles que aterrizan suavemente
bouncyMomentos lúdicos — estados vacíos, onboarding
instantTooltips, popovers, desplegables
releaseLiberación al arrastrar — sensación física natural

Cuándo deshabilitar la animación por completo

Deshabilitar (hacer que shouldAnimate() devuelva false) cuando:

  • prefersReduced es true
  • isLowEnd es true y la animación no es esencial
  • El elemento está fuera de la pantalla y nunca entrará en el viewport
  • La animación es puramente decorativa sin propósito de UX

Conceptos centrales

Sistema de tokens

// lib/motion-tokens.ts
export const motionTokens = {
  duration: {
    instant: 0.08,
    fast:    0.18,
    normal:  0.35,
    slow:    0.6,
    crawl:   1.0,
  },
  easing: {
    smooth: [0.22, 1, 0.36, 1],
    sharp:  [0.4, 0, 0.2, 1],
    bounce: [0.34, 1.56, 0.64, 1],
    linear: [0, 0, 1, 1],
  },
  distance: {
    xs: 4,
    sm: 8,
    md: 16,
    lg: 24,
    xl: 48,
  },
  scale: {
    subtle: 0.98,
    press:  0.95,
    pop:    1.04,
  },
}

export const springs = {
  snappy:  { type: "spring", stiffness: 300, damping: 30 },
  gentle:  { type: "spring", stiffness: 120, damping: 14 },
  bouncy:  { type: "spring", stiffness: 400, damping: 10 },
  instant: { type: "spring", stiffness: 600, damping: 35 },
  release: { type: "spring", stiffness: 200, damping: 20, restDelta: 0.001 },
}

Banderas de tiempo de ejecución

// lib/motion-config.ts
export const motionConfig = {
  isLowEnd() {
    return (
      typeof navigator !== "undefined" &&
      navigator.hardwareConcurrency <= 4
    )
  },

  prefersReduced() {
    return (
      typeof window !== "undefined" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches
    )
  },

  shouldAnimate({ essential = false } = {}) {
    if (this.prefersReduced()) return false
    if (!essential && this.isLowEnd()) return false
    return true
  },

  duration() {
    return this.isLowEnd() || this.prefersReduced()
      ? motionTokens.duration.instant
      : motionTokens.duration.normal
  },
}

Accesibilidad

Orden de prioridad (de mayor a menor):

  1. prefers-reduced-motion: reduce — deshabilita todas las transformaciones, limita las transiciones de opacidad a ≤ 0,2 s
  2. Detección de dispositivo de bajos recursos — reduce la duración, elimina animaciones no esenciales
  3. Preferencia de diseño — todo lo demás

El movimiento debe degradarse con gracia. Nunca debe desaparecer de forma abrupta causando un cambio de layout o desorientación.

// hooks/use-reduced-motion.tsx
"use client"
import { useReducedMotion } from "motion/react"

export function useSafeMotion(fullY: number = 16) {
  const reduce = useReducedMotion()
  return {
    initial: { opacity: 0, y: reduce ? 0 : fullY },
    animate: { opacity: 1, y: 0 },
    exit:    { opacity: 0, y: reduce ? 0 : -fullY },
  }
}
/* globals.css */
@media (prefers-reduced-motion: reduce) {
  .motion-safe-transition  { transition: opacity 0.15s; }
  .motion-reduce-transform { transform: none !important; }
}
<!-- Tailwind -->
<div class="motion-safe:animate-fade motion-reduce:opacity-100"></div>

Seguridad SSR / hidratación

Regla: initial siempre debe coincidir con lo que el servidor renderiza.

// INCORRECTO — el servidor renderiza opacity:1 pero initial dice 0 → discrepancia de hidratación
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} />

// CORRECTO — usar AnimatePresence o diferir al montaje del cliente
"use client"
const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])

<motion.div
  initial={{ opacity: mounted ? 0 : 1 }}
  animate={{ opacity: 1 }}
/>

Ejemplos de código

Completo: tokens + resortes + accesibilidad + protección SSR

// components/fade-in-card.tsx
"use client"

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

interface FadeInCardProps {
  children: React.ReactNode
  delay?: number
}

export function FadeInCard({ children, delay = 0 }: FadeInCardProps) {
  // Protección SSR — initial debe coincidir con la salida del servidor (opacity: 1)
  const [mounted, setMounted] = useState(false)
  useEffect(() => setMounted(true), [])

  // Accesibilidad — deshabilita transformaciones cuando se prefiere movimiento reducido
  const safeMotion = useSafeMotion(motionTokens.distance.md)

  // Puerta de dispositivo — saltar animación en hardware de bajos recursos
  if (!motionConfig.shouldAnimate() || !mounted) {
    return <div>{children}</div>
  }

  return (
    <motion.div
      initial={safeMotion.initial}
      animate={safeMotion.animate}
      exit={safeMotion.exit}
      transition={{
        ...springs.gentle,
        delay,
      }}
      whileHover={{ scale: motionTokens.scale.pop }}
      whileTap={{ scale: motionTokens.scale.press }}
    >
      {children}
    </motion.div>
  )
}

Restricciones / No objetivos

Esta habilidad no cubre:

  • Patrones de componentes de UI (botón, modal, escalonado) → ver motion-patterns
  • Arrastre, gestos, SVG, animaciones de texto, hooks personalizados → ver motion-advanced
  • Animaciones solo CSS o clases animate-* de Tailwind sin motion/react
  • Bibliotecas de animación de terceros (GSAP, anime.js, etc.)
  • Decisiones de diseño de movimiento (cuándo animar, qué enfatizar) — eso es una preocupación de diseño, no una restricción de código

Anti-patrones

Anti-patrónRegla violadaCorrección
import { motion } from "framer-motion"Regla 1Usar motion/react
initial={{ opacity: 0 }} en componente SSRRegla 2Agregar protección de montaje
Omitir verificación useReducedMotionRegla 3Usar hook useSafeMotion
animate={{ width: "100%" }}Regla 4Usar transformación scaleX en su lugar
transition={{ duration: 0.4 }} en líneaRegla 5Usar motionTokens.duration.normal
{ stiffness: 300, damping: 30 } en líneaRegla 6Usar springs.snappy
Falta directiva "use client"Regla 7Agregar al inicio del archivo
navigator.hardwareConcurrency a nivel de móduloRegla 8Envolver en typeof navigator !== "undefined"

Habilidades relacionadas

  • motion-patterns — consume los tokens y resortes definidos aquí para construir patrones de botón, modal, escalonado, transición de página y desplazamiento. No redefine ningún valor.
  • motion-advanced — consume los tokens y resortes definidos aquí para patrones de arrastre, SVG, texto y gestos. Añade secuencias useAnimate y hooks personalizados sobre esta base.

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

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 animation patterns for React / Next.js — button, modal, toast, stagger, page transitions, exit animations, scroll, and layout — built on motion-foundations tokens and springs.

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