---
name: extract
description: Extract and consolidate reusable components, design tokens, and patterns into your design system. Identifies opportunities for systematic reuse and enriches your component library.
user-invokable: true
args:
  - name: target
    description: The feature, component, or area to extract from (optional)
    required: false
author: "@firdausmntp"
---

## Intent Primacy

Read the user's request before applying this command's defaults.

1. **Exact target**: Identify the specific feature, file, or area named. If none is named, ask before acting broadly.
2. **Stated scope wins**: "/extract just the header" means only the header. Do not expand scope.
3. **User's choices bind you**: If the user specifies a framework, style, or approach, follow it even if this skill would suggest otherwise. Warn once, then comply.
4. **Proportional output**: A narrow request gets a targeted answer with only the relevant sections from this skill. A broad request gets the full protocol.
5. **No unrequested work**: Do not refactor, rename, add tests, or generate documentation the user did not ask for.
6. **Hard gates only for safety**: Accessibility AA floor and security checks override user intent. Aesthetic or stylistic preferences do not.
7. **Ask only when it matters**: Ambiguity on scope or destructive action (data loss, breaking change, deleting files) — ask once with specific options. Ambiguity on cosmetic defaults — state assumption and proceed. Never stack questions. Never ask what you can read yourself. STOP and call the `question` tool to clarify.

---

Identify reusable patterns, components, and design tokens, then extract and consolidate them into the design system for systematic reuse.

## Discover

Analyze the target area to identify extraction opportunities:

1. **Find the design system**: Locate your design system, component library, or shared UI directory (grep for "design system", "ui", "components", etc.). Understand its structure:
   - Component organization and naming conventions
   - Design token structure (if any)
   - Documentation patterns
   - Import/export conventions
   
   **CRITICAL**: If no design system exists, ask before creating one. Understand the preferred location and structure first.

2. **Identify patterns**: Look for:
   - **Repeated components**: Similar UI patterns used multiple times (buttons, cards, inputs, etc.)
   - **Hard-coded values**: Colors, spacing, typography, shadows that should be tokens
   - **Inconsistent variations**: Multiple implementations of the same concept (3 different button styles)
   - **Reusable patterns**: Layout patterns, composition patterns, interaction patterns worth systematizing

3. **Assess value**: Not everything should be extracted. Consider:
   - Is this used 3+ times, or likely to be reused?
   - Would systematizing this improve consistency?
   - Is this a general pattern or context-specific?
   - What's the maintenance cost vs benefit?

## Plan Extraction

Create a systematic extraction plan:

- **Components to extract**: Which UI elements become reusable components?
- **Tokens to create**: Which hard-coded values become design tokens?
- **Variants to support**: What variations does each component need?
- **Naming conventions**: Component names, token names, prop names that match existing patterns
- **Migration path**: How to refactor existing uses to consume the new shared versions

**IMPORTANT**: Design systems grow incrementally. Extract what's clearly reusable now, not everything that might someday be reusable.

## Extract & Enrich

Build improved, reusable versions:

- **Components**: Create well-designed components with:
  - Clear props API with sensible defaults
  - Proper variants for different use cases
  - Accessibility built in (ARIA, keyboard navigation, focus management)
  - Documentation and usage examples
  
- **Design tokens**: Create tokens with:
  - Clear naming (primitive vs semantic)
  - Proper hierarchy and organization
  - Documentation of when to use each token
  
- **Patterns**: Document patterns with:
  - When to use this pattern
  - Code examples
  - Variations and combinations

**NEVER**:
- Extract one-off, context-specific implementations without generalization
- Create components so generic they're useless
- Extract without considering existing design system conventions
- Skip proper TypeScript types or prop documentation
- Create tokens for every single value (tokens should have semantic meaning)

## Migrate

Replace existing uses with the new shared versions:

- **Find all instances**: Search for the patterns you've extracted
- **Replace systematically**: Update each use to consume the shared version
- **Test thoroughly**: Ensure visual and functional parity
- **Delete dead code**: Remove the old implementations

## Document

Update design system documentation:

- Add new components to the component library
- Document token usage and values
- Add examples and guidelines
- Update any Storybook or component catalog

## Before / After

Extraction is a progression, not a single leap. These examples trace the path from inlined magic values to proper design-system primitives.

### 1. Magic values → primitive tokens → semantic tokens

Three stages of the same card background. Each stage earns its place by what it enables downstream.

```css
/* stage 1 — inlined magic values (slop) */
.card       { background: #f5f3ff; border: 1px solid #ddd6fe; }
.card-dark  { background: #1e1b4b; border: 1px solid #312e81; }
.card-alert { background: #fef2f2; border: 1px solid #fecaca; }
```

```css
/* stage 2 — primitives (values named, but still tied to hue) */
:root {
  --violet-50:  oklch(97% 0.02 290);
  --violet-200: oklch(88% 0.06 290);
  --violet-900: oklch(30% 0.12 290);
  --red-50:     oklch(97% 0.02 25);
  --red-200:    oklch(88% 0.09 25);
}
.card       { background: var(--violet-50); border-color: var(--violet-200); }
.card-alert { background: var(--red-50);    border-color: var(--red-200); }
```

```css
/* stage 3 — semantic tokens (intent, not hue — swappable per theme) */
:root {
  --surface-subtle:  var(--violet-50);
  --surface-danger:  var(--red-50);
  --border-subtle:   var(--violet-200);
  --border-danger:   var(--red-200);
}
.card       { background: var(--surface-subtle); border-color: var(--border-subtle); }
.card-alert { background: var(--surface-danger); border-color: var(--border-danger); }
```

**Decision rule**: stop at primitives if the system ships one brand. Go to semantic if you theme, re-skin, or want meaning (danger, success, subtle) to survive a palette swap.

### 2. Duplicated JSX → shared Card with typed prop API

Three product cards, three subtly different implementations. That is three bugs waiting to drift apart.

```tsx
// before — repeated JSX, shape drift guaranteed
<div className="rounded-xl border p-4 shadow-sm">
  <img src={p.image} className="rounded-lg mb-3" />
  <h3 className="font-semibold text-lg">{p.name}</h3>
  <p className="text-gray-600 text-sm">{p.summary}</p>
</div>

<div className="rounded-2xl border p-5 shadow">
  <img src={a.cover} className="rounded-md mb-2" />
  <h3 className="font-bold text-xl">{a.title}</h3>
  <p className="text-gray-500">{a.excerpt}</p>
</div>
```

```tsx
// after — one Card with an explicit API, no hidden coupling
type CardProps = {
  media?: { src: string; alt: string };
  title: string;
  description?: string;
  density?: "compact" | "comfortable";
  footer?: React.ReactNode;
};

export function Card({ media, title, description, density = "comfortable", footer }: CardProps) {
  return (
    <article className={cn("rounded-xl border bg-surface shadow-sm", densityPadding[density])}>
      {media && <img src={media.src} alt={media.alt} className="rounded-lg mb-3" />}
      <h3 className="text-heading-sm">{title}</h3>
      {description && <p className="text-body-muted mt-1">{description}</p>}
      {footer && <div className="mt-4">{footer}</div>}
    </article>
  );
}
```

### 3. Ad-hoc utility soup → token + CVA variants

A long utility string repeated across twelve buttons is a component hiding in plain sight.

```tsx
// before — utility soup, copy-pasted everywhere
<button className="inline-flex items-center gap-2 px-4 py-2 rounded-md bg-violet-600 hover:bg-violet-700 text-white font-medium shadow-sm focus:outline-none focus:ring-2 focus:ring-violet-500 focus:ring-offset-2 disabled:opacity-50 transition">
  Save
</button>
```

```tsx
// after — CVA variants wired to semantic tokens
import { cva } from "class-variance-authority";

const button = cva(
  "inline-flex items-center gap-2 rounded-md font-medium transition focus-visible:ring-2 focus-visible:ring-offset-2 disabled:opacity-50",
  {
    variants: {
      intent: {
        primary: "bg-[--color-primary] hover:bg-[--color-primary-strong] text-[--color-on-primary] focus-visible:ring-[--color-primary]",
        ghost:   "bg-transparent hover:bg-[--color-surface-subtle] text-[--color-fg]",
      },
      size: {
        sm: "px-3 py-1.5 text-sm",
        md: "px-4 py-2 text-base",
      },
    },
    defaultVariants: { intent: "primary", size: "md" },
  }
);

export const Button = ({ intent, size, ...rest }) => (
  <button className={button({ intent, size })} {...rest} />
);
```

### 4. Decision — component vs utility?

Not every repeated class string earns a component. The gating questions:

```tsx
// STAY a utility — purely presentational, no logic, no variants, no a11y concerns
<div className="flex items-center justify-between" />

// BECOME a token — a value used 3+ times with semantic meaning
--radius-card: 0.75rem;

// BECOME a component — any of: variants, state, a11y wiring, composition, or repeated 3+ times
<Dialog />   // focus trap, aria-modal, escape handling, portal → component
<Button />   // variants, disabled state, focus ring → component
<Stack />    // layout primitive reused everywhere → component (or utility class)
```

**Rule of thumb**: extract a token the moment a value appears with *meaning* (not just the third time it appears). Extract a component when there is behavior, accessibility, or a stable API to protect. Everything else stays a utility.

---

Remember: A good design system is a living system. Extract patterns as they emerge, enrich them thoughtfully, and maintain them consistently.