Communitygithub.com

Motion Foundations

Base de movimento para React/Next.js com motion/react. Define tokens, molas, regras de performance, adaptação de dispositivo, acessibilidade e segurança SSR. Camada fundamental — todas as outras habilidades de movimento dependem dela.

O que é Motion Foundations?

Motion Foundations é a camada base do sistema de animação. Ela define cada valor, restrição e regra que as habilidades downstream (como motion-patterns e motion-advanced) herdam. Sua principal função é fornecer um conjunto compartilhado de tokens de movimento (duração, easing, distância, escala) e um mapa de presets de molas (springs), além de uma função `shouldAnimate()` que controla quando as animações devem ser executadas, considerando preferências de acessibilidade (`prefers-reduced-motion`), capacidade do dispositivo e se a animação é essencial. A habilidade também garante segurança SSR, fornecendo um hook `useSafeMotion` que evita warnings de hidratação ao garantir que os `initial` states coincidam com a renderização do servidor. É compatível com React e Next.js usando exclusivamente `motion/react` (nunca `framer-motion`).

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

Perguntar na sua IA favorita

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

Documentação

O que Motion Foundations faz?

A camada base do sistema de movimento. Define cada valor, restrição e regra que as habilidades downstream (motion-patterns, motion-advanced) herdam. Carregue esta habilidade antes de iniciar qualquer trabalho de animação.

Quando Ativar

  • Iniciar qualquer componente animado do zero
  • Configurar tokens, presets de molas ou valores de easing
  • Implementar suporte a prefers-reduced-motion
  • Depurar incompatibilidades de hidratação provenientes de estados iniciais de animação
  • Avaliar se uma animação deve existir

Saídas

Esta habilidade produz:

  • Um objeto motionTokens compartilhado (duração, easing, distância, escala)
  • Um mapa de presets springs (5 configurações nomeadas)
  • Uma função shouldAnimate() usada por todos os componentes
  • Padrões de animação compatíveis com acessibilidade via useReducedMotion
  • Estados iniciais seguros para SSR sem warnings de hidratação

Princípios

O movimento deve atender a pelo menos um dos seguintes critérios ou deve ser removido:

  • Guiar a atenção
  • Comunicar estado
  • Preservar continuidade espacial

Responsividade sempre supera suavidade. Uma animação a 60 fps que causa atraso na entrada é pior do que nenhuma animação.

Regras

Estas são inegociáveis. Aplicam-se a todo componente no sistema.

  1. Use apenas motion/react. Nunca importe de framer-motion. Nunca misture os dois na mesma árvore.
  2. initial deve corresponder à saída do servidor. Se o servidor renderizar opacity: 1, a prop initial também deve ser opacity: 1. Sem exceções.
  3. Movimento reduzido substitui tudo. Quando useReducedMotion() retorna true ou prefersReduced é true, todas as transformações são desabilitadas. Apenas fades com opacidade em ≤ 0,2s são permitidos como fallback.
  4. Nunca anime propriedades de layout. width, height, top, left, margin, padding são proibidos em animate. Use apenas transform e opacity.
  5. Todos os valores de token vêm de motionTokens. Durações e easings hardcoded em arquivos de componente são proibidos.
  6. Todas as configurações de mola vêm do mapa springs. Valores inline de stiffness/damping são proibidos.
  7. "use client" é obrigatório em todo arquivo que importa de motion/react.
  8. Nunca leia window ou navigator no nível do módulo. Sempre proteja com typeof window !== "undefined".

Guia de Decisão

Escolhendo uma duração

TokenUse quando
instantExibir/ocultar tooltip, anel de foco, atualização de badge
fastFeedback de botão, troca de ícone, alternância de chip
normalAbertura de modal, expansão de card, entrada de elemento de página
slowEntrada de herói, transição de página inteira
crawlNarrativa deliberada; use com moderação

Escolhendo uma mola

PresetUse quando
snappyUI padrão — botões, chips, itens de navegação
gentleCards, modais, painéis pousando suavemente
bouncyMomentos lúdicos — estados vazios, onboarding
instantTooltips, popovers, dropdowns
releaseSoltar ao arrastar — sensação física natural

Quando desabilitar a animação completamente

Desabilite (faça shouldAnimate() retornar false) quando:

  • prefersReduced é true
  • isLowEnd é true e a animação não é essencial
  • O elemento está fora da tela e nunca entrará no viewport
  • A animação é puramente decorativa sem propósito UX

Conceitos Principais

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

Flags de tempo de execução

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

Acessibilidade

Ordem de prioridade (maior para menor):

  1. prefers-reduced-motion: reduce — desabilita todas as transformações, limita transições de opacidade a ≤ 0,2s
  2. Detecção de dispositivo de baixo desempenho — reduz duração, remove animações não essenciais
  3. Preferência de design — todo o resto

O movimento deve degradar graciosamente. Nunca deve desaparecer abruptamente de forma que cause deslocamento de layout ou confunda a orientação.

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

Segurança SSR / hidratação

Regra: initial deve sempre corresponder ao que o servidor renderiza.

// ERRADO — servidor renderiza opacity:1 mas initial diz 0 → incompatibilidade de hidratação
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} />

// CORRETO — use AnimatePresence ou adie para montagem do cliente
"use client"
const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])

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

Exemplos de Código

Fim a fim: tokens + molas + acessibilidade + proteção 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) {
  // Proteção SSR — initial deve corresponder à saída do servidor (opacity: 1)
  const [mounted, setMounted] = useState(false)
  useEffect(() => setMounted(true), [])

  // Acessibilidade — desabilita transformação quando movimento reduzido é preferido
  const safeMotion = useSafeMotion(motionTokens.distance.md)

  // Verificação de dispositivo — pula animação em hardware de baixo desempenho
  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>
  )
}

Restrições / Não-Objetivos

Esta habilidade não cobre:

  • Padrões de componentes de UI (botão, modal, escalonamento) → veja motion-patterns
  • Arrastar, gestos, SVG, animações de texto, hooks personalizados → veja motion-advanced
  • Animações apenas com CSS ou classes animate-* do Tailwind sem motion/react
  • Bibliotecas de animação de terceiros (GSAP, anime.js, etc.)
  • Decisões de design de movimento (quando animar, o que enfatizar) — isso é uma preocupação de design, não uma restrição de código

Anti-Padrões

Anti-padrãoRegra violadaCorreção
import { motion } from "framer-motion"Regra 1Use motion/react
initial={{ opacity: 0 }} em componente SSRRegra 2Adicione proteção de montagem
Pular verificação useReducedMotionRegra 3Use hook useSafeMotion
animate={{ width: "100%" }}Regra 4Use transformação scaleX
transition={{ duration: 0.4 }} inlineRegra 5Use motionTokens.duration.normal
{ stiffness: 300, damping: 30 } inlineRegra 6Use springs.snappy
Diretiva "use client" ausenteRegra 7Adicione ao topo do arquivo
navigator.hardwareConcurrency no nível do móduloRegra 8Envolva em typeof navigator !== "undefined"

Habilidades Relacionadas

  • motion-patterns — consome tokens e molas definidos aqui para construir padrões de botão, modal, escalonamento, transição de página e scroll. Não redefine nenhum valor.
  • motion-advanced — consome tokens e molas definidos aqui para padrões de arrastar, SVG, texto e gestos. Adiciona sequências useAnimate e 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.

Habilidades Relacionadas