Communitygithub.com

运动系统 v4.2

面向 React/Next.js 的生产级 UI 动画系统,专注于性能、可访问性和用户体验。

运动系统 v4.2 是什么?

该技能提供了一个生产级 UI 动画系统,专门为 React 和 Next.js 设计。它遵循严格的性能原则:仅使用 `transform` 和 `opacity` 属性,并提供了详细的设备自适应策略,通过检测 CPU 核心数和内存来区分低端设备,从而平滑降低动画复杂度。技能还内置了完善的无障碍支持,包括通过 `useReducedMotion` Hook 和 CSS `prefers-reduced-motion` 媒体查询来尊重用户的减少动画偏好。它涵盖了从基础的按钮交互、列表交错动画到复杂的模态框、滚动视差和骨架屏加载等模式,并明确阐述了 `AnimatePresence` 的 `mode` 属性在不同场景下的正确用法,以及应避免的反模式(如动画化布局属性、无限无目的动画等)。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Cody-W-Tucker/skills/tree/HEAD/skills/motion-ui

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

运动系统 v4.2 是做什么的?

面向 React / Next.js 的生产级 UI 动画系统。

专注于性能、可访问性和可用性——而非装饰。

何时使用

在以下情况使用本动画系统:

  • 引导注意力(例如,新手引导、关键操作)
  • 传达状态(加载、成功、错误、过渡)
  • 保持空间连续性(布局变化、导航)

适用场景

  • 交互组件(按钮、模态框、菜单)
  • 状态切换(加载中 → 加载完成,打开 → 关闭)
  • 导航与布局连续性(共享元素、淡入淡出)

注意事项

  • 无障碍:始终支持减少动画偏好
  • 设备适配:为低端设备调整动画效果
  • 性能权衡:优先保证响应性而非视觉流畅度

应避免使用动画的情况

  • 纯粹用于装饰
  • 降低可用性或清晰度
  • 对性能产生负面影响

工作原理

核心原则

动画必须:

  • 引导注意力
  • 传达状态
  • 保持空间连续性

如果不符合上述任何一点,则删除它。


安装

npm install motion

版本

  • motion/react - 当前 Motion for React 项目的默认路径(包名:motion)
  • framer-motion - 旧版导入路径,适用于仍依赖 Framer Motion 的项目

不要混用。 混用会导致内部调度器冲突和 AnimatePresence 上下文损坏——一个包中的组件无法与另一个包中的组件协调退出动画。

检查项目使用的版本:

cat package.json | grep -E '"motion"|"framer-motion"'

始终从单一来源一致导入:

// 正确(现代)
import { motion, AnimatePresence } from "motion/react"

// 正确(旧版)
import { motion, AnimatePresence } from "framer-motion"

// 切勿在同一个项目中混用

动画令牌

// motionTokens.ts
export const motionTokens = {
  duration: {
    fast: 0.18,
    normal: 0.35,
    slow: 0.6
  },
  // 将这些用作 `transition` 对象内的 `ease` 值:
  // transition={{ duration: motionTokens.duration.normal, ease: motionTokens.easing.smooth }}
  easing: {
    smooth: [0.22, 1, 0.36, 1] as [number, number, number, number],
    sharp:  [0.4,  0, 0.2, 1] as [number, number, number, number]
  },
  distance: {
    sm: 8,
    md: 16,
    lg: 24
  }
}

使用示例:

import { motionTokens } from "@/lib/motionTokens"

<motion.div
  initial={{ opacity: 0, y: motionTokens.distance.md }}
  animate={{ opacity: 1, y: 0 }}
  transition={{
    duration: motionTokens.duration.normal,
    ease: motionTokens.easing.smooth
  }}
/>

性能规则

安全

  • transform
  • opacity

避免

  • width / height
  • top / left

规则:响应性 > 流畅度


设备适配

启发式方法结合了 CPU 核心数和可用内存,以提供更可靠的信号。deviceMemory 在 Chrome/Android 上可用;回退方案涵盖了 Safari 和 Firefox。

const isLowEnd =
  typeof navigator !== "undefined" && (
    // 内存不足(仅限 Chrome/Android;其他浏览器为 undefined → 视为性能良好)
    (navigator.deviceMemory !== undefined && navigator.deviceMemory <= 2) ||
    // 核心数少且无内存 API(涵盖在弱硬件上的 Safari/Firefox)
    (navigator.deviceMemory === undefined && navigator.hardwareConcurrency <= 4)
  )

const duration = isLowEnd ? 0.2 : 0.4

无障碍

JS (useReducedMotion)

import { motion, useReducedMotion } from "motion/react"

export function FadeIn() {
  const reduce = useReducedMotion()

  return (
    <motion.div
      initial={{ opacity: 0, y: reduce ? 0 : 24 }}
      animate={{ opacity: 1, y: 0 }}
    />
  )
}

CSS

@media (prefers-reduced-motion: reduce) {
  .motion-safe-transition {
    transition: opacity 0.2s;
  }

  .motion-reduce-transform {
    transform: none !important;
  }
}

Tailwind

<div class="motion-safe:animate-fade motion-reduce:opacity-100"></div>

架构与模式

核心模式

场景模式
悬停反馈whileHover
点击/按压反馈whileTap
滚动时显示whileInView
滚动绑定值useScroll + useTransform
条件挂载/卸载AnimatePresence
小型布局变化(单个元素,变化 < ~300px)layout 属性
大型布局变化或整页重排避免使用 layout;改用 CSS 过渡或页面级路由
复杂、命令式动画序列useAnimate

为什么要在大型容器上避免使用 layout? Framer 的布局动画使用 transform 来协调位置,但在跨越整个视口或触发深度重排的元素上,测量成本会导致明显的卡顿和累积布局偏移 (CLS)。建议改用 CSS Grid/Flexbox 过渡,或仅在特定的子元素上使用 layoutId 进行协调。

布局与过渡

  • 共享元素过渡 → layoutId(每个挂载的实例必须是唯一的)
  • 进入/退出过渡 → AnimatePresence(参见下方的 mode 指导)

AnimatePresence mode

务必显式指定 mode —— 默认值 ("sync") 同时运行进入和退出动画,这会在大多数 UI 模式中导致视觉重叠。

mode何时使用
"wait"退出完成后才进入。用于模态框、快速提示、页面过渡。
"sync" (默认)进入和退出重叠。仅在有意重叠时使用(例如,淡入淡出转盘)。
"popLayout"退出元素立即从布局流中弹出;剩余项目动画填充其位置。用于列表、标签页、可关闭卡片。
// 模态框——始终使用 "wait"
<AnimatePresence mode="wait">
  {open && <Modal key="modal" />}
</AnimatePresence>

// 可关闭的列表项——使用 "popLayout"
<AnimatePresence mode="popLayout">
  {items.map(item => <Card key={item.id} />)}
</AnimatePresence>

高级模式(概念)

  • 视差(滚动绑定变换)
  • 滚动叙述(粘性区域)
  • 3D 倾斜(基于指针的变换)
  • 淡入淡出(共享的 layoutId)
  • 渐进式揭示(clip-path)
  • 骨架屏加载(循环透明度)
  • 微交互(悬停/点击反馈)
  • 弹簧系统(基于物理的动画)

模态框要点

  • 焦点陷阱
  • Escape 键关闭
  • 滚动锁定
  • ARIA 角色
  • 使用 AnimatePresence mode="wait" 以确保退出动画在下一个模态框进入之前完成

完整示例

import React, { useEffect, useRef, useState } from "react"
import { motion, AnimatePresence } from "motion/react"

function useFocusTrap(ref: React.RefObject<HTMLDivElement | null>, active: boolean) {
  useEffect(() => {
    if (!active || !ref.current) return
    const el = ref.current
    const focusable = el.querySelectorAll<HTMLElement>(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    )
    const first = focusable[0]
    const last  = focusable[focusable.length - 1]

    function handleKey(e: KeyboardEvent) {
      if (e.key !== "Tab") return
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault()
        last?.focus()
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault()
        first?.focus()
      }
    }

    el.addEventListener("keydown", handleKey)
    first?.focus()
    return () => el.removeEventListener("keydown", handleKey)
  }, [active, ref])
}

function useScrollLock(active: boolean) {
  useEffect(() => {
    if (!active) return
    const prev = document.body.style.overflow
    document.body.style.overflow = "hidden"
    return () => { document.body.style.overflow = prev }
  }, [active])
}

function Modal({ open, closeModal }: { open: boolean; closeModal: () => void }) {
  const ref = useRef<HTMLDivElement>(null)

  useFocusTrap(ref, open)
  useScrollLock(open)

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") closeModal()
    }
    if (open) window.addEventListener("keydown", onKey)
    return () => window.removeEventListener("keydown", onKey)
  }, [open, closeModal])

  return (
    // mode="wait" 确保退出动画完成后再进入任何新模态框
    <AnimatePresence mode="wait">
      {open && (
        <motion.div
          role="dialog"
          aria-modal="true"
          aria-labelledby="modal-title"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          className="fixed inset-0 flex items-center justify-center bg-black/40"
        >
          <motion.div
            ref={ref}
            initial={{ scale: 0.95, opacity: 0 }}
            animate={{ scale: 1,    opacity: 1 }}
            exit={{    scale: 0.95, opacity: 0 }}
            transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
            className="bg-white p-6 rounded"
          >
            <h2 id="modal-title">对话框标题</h2>
            <button onClick={closeModal}>关闭</button>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}

export function Example() {
  const [open, setOpen] = useState(false)

  return (
    <>
      <button onClick={() => setOpen(true)}>打开</button>
      <Modal open={open} closeModal={() => setOpen(false)} />
    </>
  )
}

SSR 安全性

  • 匹配服务端和客户端渲染的初始状态
  • 避免隐式动画起点(始终显式设置 initial)
  • 在 Next.js App Router 中,将 motion 组件包裹在 "use client" 中

调试

检查:

  • 错误的导入(混用 motion/react 和 framer-motion)
  • Next.js App Router 中缺少 "use client" 指令
  • AnimatePresence 子元素缺少 key 属性
  • 水合不匹配(SSR 和客户端的初始状态不同)
  • 在大型容器上误用 layout 属性导致重排卡顿
  • 状态驱动的动画未触发(检查依赖数组)

质量保证

  • 无 CLS
  • 键盘操作正常
  • 模态框中焦点已锁定
  • ARIA 角色正确(role="dialog",aria-modal="true")
  • 尊重减少动画偏好(useReducedMotion + CSS 媒体查询)
  • Next.js 中无水合警告
  • 卸载时动画干净停止(无内存泄漏)
  • 所有使用 AnimatePresence 的地方显式设置了 mode

反模式

  • 对布局属性进行动画(width、height、top、left)
  • 无目的的无限动画(始终问:这个动画传达了何种状态?)
  • 过度交错列表(保持 staggerChildren ≤ 0.1s;超过此值会显得缓慢)
  • 忽略减少动画的偏好设置
  • 在大型或全视口容器上使用 layout
  • 在 AnimatePresence 上省略 mode(默认 "sync" 会导致视觉重叠)
  • 纯粹为了装饰而使用动画

理念

动画即是交互设计。


最终规则

如果动画不能改善用户体验,就删除它。


示例

按钮交互

import { motion } from "motion/react"

export function Button() {
  return (
    <motion.button
      whileHover={{ scale: 1.02 }}
      whileTap={{ scale: 0.97 }}
      transition={{ duration: 0.15, ease: [0.4, 0, 0.2, 1] }}
    >
      点击我
    </motion.button>
  )
}

减少动画示例

import { motion, useReducedMotion } from "motion/react"

export function FadeIn() {
  const reduce = useReducedMotion()

  return (
    <motion.div
      initial={{ opacity: 0, y: reduce ? 0 : 24 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: reduce ? 0.1 : 0.35, ease: [0.22, 1, 0.36, 1] }}
    />
  )
}

交错列表

import { motion } from "motion/react"

const container = {
  hidden: {},
  visible: {
    transition: { staggerChildren: 0.08 } // 保持 ≤ 0.1s 以避免迟缓
  }
}

const item = {
  hidden:  { opacity: 0, y: 10 },
  visible: { opacity: 1, y: 0,  transition: { duration: 0.3, ease: [0.22, 1, 0.36, 1] } }
}

export function List() {
  return (
    <motion.ul variants={container} initial="hidden" animate="visible">
      {[1, 2, 3].map(i => (
        <motion.li key={i} variants={item}>项目 {i}</motion.li>
      ))}
    </motion.ul>
  )
}

使用 AnimatePresence 的模态框

import { motion, AnimatePresence } from "motion/react"

export function Modal({ open }: { open: boolean }) {
  return (
    <AnimatePresence mode="wait">
      {open && (
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1    }}
          exit={{    opacity: 0, scale: 0.95 }}
          transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
        />
      )}
    </AnimatePresence>
  )
}

滚动视差

import { useScroll, useTransform, motion } from "motion/react"

export function Parallax() {
  const { scrollYProgress } = useScroll()
  const y = useTransform(scrollYProgress, [0, 1], [0, -80])

  return <motion.div style={{ y }} />
}

骨架屏加载

import { motion } from "motion/react"

export function Skeleton() {
  return (
    <motion.div
      className="bg-gray-200 h-6 w-full rounded"
      animate={{ opacity: [0.5, 1, 0.5] }}
      transition={{
        duration: 1.5,       // 舒适的脉冲——之前缺失,导致快速闪烁
        repeat: Infinity,
        ease: "easeInOut"
      }}
    />
  )
}

共享布局(淡入淡出)

import { motion } from "motion/react"

// layoutId 每个挂载的实例必须是唯一的。
// 如果多个实例可以同时存在,请附加一个唯一 ID:
// layoutId={`shared-${item.id}`}
export function Shared() {
  return <motion.div layoutId="shared" />
}

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

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.

相关技能