Communitygithub.com

Motion 系統 v4.2

適用於 React/Next.js 的生產級 UI 動畫系統。用於實作動畫、轉場或動態模式。

Motion 系統 v4.2 是什麼?

這是一個專為 React 和 Next.js 設計的生產級 UI 動畫系統,核心重點在於「效能、無障礙性與實用性」,而非純粹的裝飾。該技能提供了一套完整的 Motion Token 系統,包含統一的持續時間、緩動函數與距離常數,讓開發者能夠輕鬆維持動畫風格的一致性。支援的動畫模式包括懸浮反饋 (`whileHover`)、點擊反饋 (`whileTap`)、滾動觸發 (`whileInView`)、條件渲染進出場動畫 (`AnimatePresence`)、佈局動畫 (`layout` 與 `layoutId`),以及複雜的連續動畫 (`useAnimate`)。為了確保良好的使用者體驗,內建了裝置適應機制,能根據 CPU 核心數與記憶體自動調整動畫持續時間,並整合 `useReducedMotion` 鉤子與 CSS Media Query 支援使用者對減少動畫的偏好。最後,該技能強烈要求開發者在每次使用 `AnimatePresence` 時明確指定 `mode` 屬性,以避免預設的 `"sync"` 模式造成視覺重疊問題。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Motion 系統 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"

// 請勿在同一個專案中混用兩者

Motion Token

// 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 prop
大幅佈局變動或全頁面重排避免使用 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 prop
  • 水合不匹配(SSR 和用戶端之間的初始狀態不同)
  • 在大容器上誤用 layout prop 導致重排卡頓
  • 由狀態驅動的動畫未觸發(檢查依賴陣列)

品質保證

  • 無 CLS
  • 鍵盤操作正常
  • 模態框內焦點被鎖定
  • ARIA 角色正確(role="dialog", aria-modal="true")
  • 尊重減少動畫偏好(useReducedMotion + CSS Media Query)
  • Next.js 中無水合警告
  • 動畫在卸載時能乾淨停止(無記憶體洩漏)
  • 所有使用處皆明確設定了 AnimatePresence mode

反模式

  • 對佈局屬性進行動畫(width, height, top, left)
  • 無目的的無限動畫(隨時自問:這個動畫溝通了什麼狀態?)
  • 過度交錯列表(保持 staggerChildren ≤ 0.1秒;超過會感覺很慢)
  • 忽略減少動畫的偏好設定
  • 在大容器或全視口容器上使用 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.1秒以避免遲緩感
  }
}

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.

相關技能