К основному содержанию
скилл CX Codex

framer-motion · athevon — скилл для Claude Code: что делает и как установить

Подсказывает агенту правила работы с Framer Motion и Motion в React: анимации раскладки, жесты и хуки без лишних ререндеров.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add AThevon/genjutsu --skill framer-motion -a claude-code
Открыть на GitHub

Что делает framer-motion

Скилл фиксирует соглашения по анимациям в проектах на React 18 и 19. Он объясняет модели импорта: не переписывать зависимости самостоятельно, если в package.json уже указан framer-motion вместо нового пакета motion (или наоборот), и применять motion/react только при наличии пакета motion.

Внутри собраны правила для AnimatePresence с режимами wait и popLayout, синхронизации элементов через layoutId, жестов перетаскивания и оркестрации через variants. Скилл явно предостерегает от устаревших staggerChildren в пользу функции stagger(), а также показывает, как скролл и движение через useMotionValue и useTransform меняют DOM напрямую в обход ререндеров.

Если вы используете styled-components или Emotion вместе с Motion 13+, библиотеке потребуется явная передача isValidProp через MotionConfig, иначе служебные свойства попадут в DOM.

Какие задачи решает

  • настроить появление и удаление компонентов через AnimatePresence
  • анимировать изменение размеров и позиций элементов по layoutId
  • создать перетаскиваемые блоки с ограничением координат через dragConstraints
  • привязать трансформацию элементов к скроллу через useScroll и useTransform
  • предотвратить циклические ререндеры при вызове стейта внутри анимационных событий

Примеры запросов агенту

  • Сделай анимированное модальное окно на Framer Motion с выходом через AnimatePresence mode='wait'
  • Добавь перетаскивание карточки с ограничением по краям и возвратом на место при отпускании
  • Настрой плавное переключение активной вкладки через layoutId

Как установить framer-motion

1Через Skills CLI (Vercel)

npx skills add AThevon/genjutsu --skill framer-motion -a claude-code

2Вручную: положить файлы

~/.claude/skills/framer-motion/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/framer-motion/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора17

threejs-r3f Скилл по Three.js и React Three Fiber: правила сцен, хуков, постобработки и производительности. Пригодится, когда агент пишет 3D на React. CX Codex +1 1 000установок css-native Скилл для ИИ-агента, который подсказывает, как делать анимации и визуальные эффекты на нативном CSS без библиотек. CX Codex +1 1 100установок gsap Скилл помогает агенту писать анимации GSAP: таймлайны, каскадные эффекты и ScrollTrigger. Нужен для сложных движений и прокрутки. CX Codex +1 997установок canvas-generative Скилл для алгоритмической графики на Canvas 2D: частицы, flow fields, шум, фракталы и L-системы. Пригодится, когда нужна анимация или генеративная картинка в браузере. CX Codex +1 995установок desktop-principles Скилл с правилами десктопного UX: ховеры, точность указателя, горячие клавиши, несколько окон. Пригодится, когда интерфейс делают под macOS, Windows или Linux. CX Codex +1 982установок mobile-principles Набор правил для мобильного интерфейса: размеры тап-зон, отказ от hover, зоны большого пальца, safe area и жесты. Подключается, когда агент видит мобильную платформу. CX Codex +1 974установок compose-multiplatform Скилл помогает писать кроссплатформенный интерфейс на Compose Multiplatform для Android, iOS, Desktop и Web. Пригодится при переносе общих компонентов в commonMain. CX Codex +1 951установок swiftui-motion Задаёт правила и готовые паттерны анимаций SwiftUI для ИИ-агента. Помогает настроить пружины, переходы и многофазные эффекты без лишнего визуального мусора. CX Codex +1 943установок

Другие версии framer-motion

Похожие

motion-framer freshtechbro Помогает агенту добавлять анимации Motion и Framer Motion в React-интерфейсы: от эффектов наведения до переходов между состояниями. CX Codex +1 5 900установок framer-motion-animator patricio0312rev Скилл помогает создавать анимации и микроинтерфейсы на Framer Motion: от переходов между страницами до жестов свайпа и скролла. Пригодится при вёрстке интерактивных React-компонентов. CX Codex +1 11 100установок framer-motion-scroll C-Jeril Скилл для Framer Motion: подсказывает агенту, как делать анимации, привязанные к прокрутке, параллакс и индикаторы прогресса. CX Codex +1 803установок framer-motion-gestures C-Jeril Скилл для анимаций жестов в Framer Motion: перетаскивание, панорамирование, нажатие, наведение, фокус. Пригодится, когда собираешь интерактивные элементы и нужны подсказки по пропсам и ограничениям. CX Codex +1 766установок motion secondsky Скилл по библиотеке Motion для React: подсказывает, как собрать drag-and-drop, scroll-анимации и переходы макета. Пригодится, когда агент путает пропсы или ломает exit-анимации. CX Codex +1 1 100установок review-animations emilkowalski Проверяет код интерфейсных анимаций по принципам Эмиля Ковальски. Помогает убрать дерганые переходы, медленный ease-in и лишнюю нагрузку на процессор. CX Codex +1 256 500установок

Рядом в теме «Фронтенд и UI»

Всё по теме «Фронтенд и UI» →

Вопросы о framer-motion

Как установить framer-motion в Claude Code?

Выполните команду npx skills add AThevon/genjutsu --skill framer-motion -a claude-code. Также файл скилла можно сохранить вручную по пути ~/.claude/skills/framer-motion/SKILL.md.

Что делает скилл framer-motion?

Он задаёт агенту точные инструкции по синтаксису Framer Motion и Motion 13: правила работы с AnimatePresence, жестами, связками useScroll и типичными ошибками вроде утечки пропсов в DOM.

В чём разница между пакетами motion и framer-motion по правилам скилла?

Библиотека Framer Motion была переименована в Motion, но обе версии публикуются синхронно. Скилл запрещает агенту самовольно мигрировать проект с одного пакета на другой и требует импортировать компоненты строго из того пакета, который прописан в package.json.

Исходный текст

SKILL.md · MIT
---
name: framer-motion
description: "Framer Motion / Motion sub-skill - AnimatePresence, layout animations, gestures, motion values."
metadata:
  internal: true
---

> **Version-sensitive.** Every API name, SDK gate and browser-support claim below was
> verified on **2026-09-08** against primary sources. What against, and when, is in
> `_jutsu/VERSIONS.md`. If that date is old, re-verify before acting on a version number.

# Framer Motion - Sub-skill

> **Two package names, one library.** Framer Motion was renamed to Motion. `motion` and
> `framer-motion` both publish the same version (13.2.0 as of 2026-09-08): `motion` declares
> `"framer-motion": "^13.2.0"` as a dependency and `motion/react` re-exports it. Neither is
> broken, and `framer-motion` is still the one most installed projects have.
>
> **Read `package.json` and follow what is there.** Do not migrate a project from one to the
> other unless the user asks - that is Iron Rule 8 in `cast` / 10 in `paint`.
>
> | In `package.json` | Import from | Install line |
> |---|---|---|
> | `motion` | `"motion/react"` | `npm install motion` |
> | `framer-motion` | `"framer-motion"` | `npm install framer-motion` |
> | both | whichever the file you are editing already imports; say the project is mid-migration | - |
>
> Every API in this skill is identical across the two names at v13. Where a symbol is newer
> than v11, it is flagged inline. Peers: `react` / `react-dom` `^18 || ^19`.

## When to use Framer Motion vs alternatives

| Criteria | Framer Motion | GSAP | Native CSS |
|---------|--------------|------|-----------|
| Layout animations | Excellent (layoutId) | Manual | Impossible |
| Exit animations | AnimatePresence | Timeline reverse | Limited (display) |
| Gestures (drag, hover) | Native, declarative | Draggable plugin | Basic |
| Scroll-driven | useScroll + useTransform | ScrollTrigger (more powerful) | scroll-timeline |
| Complex orchestration | Variants + propagation | Timeline (more flexible) | @keyframes |
| Bundle size | ~50kb tree-shaken | ~30kb core | 0kb |
| React integration | Native, component-first | Refs + useGSAP | className toggle |

**Rule**: Framer Motion for React UI interactions (modals, toasts, reorder, shared layout). GSAP for complex timelines, cinematic scroll-driven, SVG morphing.

## AnimatePresence - Exit animations

```tsx
<AnimatePresence mode="wait">
  {isVisible && (
    <motion.div
      key="unique-key"        // REQUIRED - identifies the component
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
    />
  )}
</AnimatePresence>
```

- `mode="wait"` - waits for exit to finish before enter (page transitions)
- `mode="sync"` - exit and enter simultaneously
- `mode="popLayout"` - removes from flow immediately (good for lists)
- `onExitComplete` - callback when all exit animations are finished

## Layout animations

```tsx
// Shared layout - the element "slides" between two positions
<motion.div layoutId="highlight" className={activeTab === id ? "active" : ""} />

// Auto layout - animates position/size when layout changes
<motion.div layout>
  {isExpanded && <motion.p layout>Additional content</motion.p>}
</motion.div>

// layout="position" - animates position only (not size)
// layout="size" - animates size only
// layout="preserve-aspect" - preserves the ratio during the transition
```

## Variants - Propagation and orchestration

```tsx
import { stagger } from "motion/react";

const container = {
  hidden: { opacity: 0 },
  show: {
    opacity: 1,
    transition: {
      // staggerChildren + staggerDirection are DEPRECATED (Motion 12.22, Jul 2025).
      // Pass a stagger() function to delayChildren instead.
      delayChildren: stagger(0.08, { startDelay: 0.2 }),
      // reverse order: stagger(0.08, { from: "last" })
      // also available: from: "first" | "center" | "last" | index, and ease
    },
  },
};

const item = {
  hidden: { opacity: 0, y: 20 },
  show: { opacity: 1, y: 0 },
};

<motion.ul variants={container} initial="hidden" animate="show">
  {items.map((i) => (
    <motion.li key={i.id} variants={item} />
  ))}
</motion.ul>
```

Variants **automatically propagate** to motion children - no need for `initial`/`animate` on children.

## Gestures

```tsx
<motion.div
  whileHover={{ scale: 1.05 }}
  whileTap={{ scale: 0.95 }}
  whileFocus={{ borderColor: "#3b82f6" }}
  // Drag
  drag               // true = x+y, "x" = horizontal only, "y" = vertical only
  dragConstraints={{ left: -100, right: 100, top: -50, bottom: 50 }}
  dragElastic={0.2}  // 0 = rigid, 1 = free (default 0.35)
  dragSnapToOrigin   // returns to initial position
  onDragEnd={(e, info) => {
    if (info.offset.x > 100) handleSwipe("right");
  }}
/>
```

## Motion values - Reactive without re-render

```tsx
const x = useMotionValue(0);
const opacity = useTransform(x, [-200, 0, 200], [0, 1, 0]);
const background = useTransform(x, [-200, 200], ["#ff0000", "#00ff00"]);

// Spring-based smoothing
const smoothX = useSpring(x, { stiffness: 300, damping: 30 });

// Scroll tracking
const { scrollY, scrollYProgress } = useScroll();
const parallaxY = useTransform(scrollYProgress, [0, 1], [0, -300]);

// Element-scoped scroll
const ref = useRef(null);
const { scrollYProgress } = useScroll({
  target: ref,
  offset: ["start end", "end start"],
});
```

**Motion values do NOT trigger React re-renders** - they update the DOM directly via `style`.

## Do Not

### Do not use motion with styled-components / Emotion without `isValidProp` (v13+)

Motion 13.0 removed `@emotion/is-prop-valid` as an optional dependency. Without explicit injection, motion-only props leak onto the DOM.

```tsx
import isPropValid from "@emotion/is-prop-valid";
import { MotionConfig } from "motion/react";

<MotionConfig isValidProp={isPropValid}>
  <App />
</MotionConfig>
```

Or reverse the composition so the styling library owns prop forwarding: `const MotionDiv = motion.create(StyledDiv)`.

### Do not setState in callbacks without a guard

```tsx
// BAD - infinite re-render if animate depends on state
onUpdate={(latest) => setPosition(latest.x)}

// GOOD - guard or useMotionValueEvent
const x = useMotionValue(0);
useMotionValueEvent(x, "change", (latest) => {
  if (latest > threshold) onThresholdReached();
});
```

### Do not use layout animation without a stable key

```tsx
// BAD - key changes every render, breaks layout tracking
<motion.div layout key={Math.random()} />

// GOOD - stable key derived from data
<motion.div layout key={item.id} />
```

### Do not forget the unique key on AnimatePresence

```tsx
// BAD - no key, exit animation does not trigger
<AnimatePresence>
  {isOpen && <motion.div exit={{ opacity: 0 }} />}
</AnimatePresence>

// GOOD - unique key for each conditional child
<AnimatePresence>
  {isOpen && <motion.div key="modal" exit={{ opacity: 0 }} />}
</AnimatePresence>
```

### Do not wrap an already animated component with motion.div

```tsx
// BAD - double animation, transform conflicts
<motion.div animate={{ x: 100 }}>
  <motion.div animate={{ x: -50 }}>Content</motion.div>
</motion.div>

// GOOD - single animation level per transform axis
<motion.div animate={{ x: 100 }}>
  <motion.div animate={{ opacity: 0.5 }}>Content</motion.div>
</motion.div>

// GOOD - use variants to coordinate parent/child
<motion.div variants={parent} animate="active">
  <motion.div variants={child} />
</motion.div>
```

© AThevon · MIT · AThevon/genjutsu

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой