---
name: pencil-design
description: Pencil UI/UX design tool với Atomic Design Hierarchy cho enterprise UI Kits. Design system modularization, component extraction, code conversion (HTML/CSS/React/Blazor), và enterprise-scale design workflows.
compatibility: "Pencil 2.6+, JSON parsing"
metadata:
  author: Velik Ho
  version: "3.0"
  references: "pencil.evolus.vn, Atomic Design by Brad Frost, Material Design, Figma Design Systems"
---

# Pencil Design Tool / Công cụ thiết kế Pencil

## When to Use This Skill / Khi Nào Sử Dụng

Use this skill when:
- Reading and analyzing `.pen` design files / Đọc và phân tích file `.pen`
- Extracting design content and tokens / Trích xuất nội dung và design tokens
- Converting Pencil designs to code / Chuyển đổi thiết kế sang code
- Building component libraries / Xây dựng thư viện components
- Organizing enterprise UI Kits with Atomic Design / Tổ chức UI Kits doanh nghiệp
- Working with modular design systems / Làm việc với hệ thống thiết kế module

## MCP Pencil Integration / Tích Hợp MCP Pencil

> [!TIP]
> MCP Pencil cho phép tương tác realtime với Pencil editor. Xem chi tiết tại [MCP Tools Reference](./references/MCP_TOOLS.md).

### Khi Nào Dùng MCP vs Build Scripts

| Tác vụ | MCP Pencil | Build Scripts |
|--------|------------|---------------|
| Thiết kế UI realtime | ✅ `batch_design` | ❌ |
| Screenshot/verify | ✅ `get_screenshot` | ❌ |
| Style guides | ✅ `get_style_guide` | ❌ |
| Build library | ❌ | ✅ `scripts/build.py` |
| Merge files | ❌ | ✅ `scripts/build.py -m` |

### MCP Tools Quick Reference

```
Document:    open_document, get_editor_state, get_variables, set_variables
Design:      batch_design, batch_get, snapshot_layout, find_empty_space_on_canvas  
Guidelines:  get_guidelines, get_style_guide_tags, get_style_guide
Verify:      get_screenshot
Batch:       search_all_unique_properties, replace_all_matching_properties
```

### MCP Workflow

1. `get_editor_state` → Xác định file, selection, components
2. `get_guidelines("design-system")` → Hướng dẫn thiết kế
3. `get_variables` → Design tokens
4. `batch_design` → Tạo/sửa design (max 25 ops/call)
5. `get_screenshot` → Verify visual

### batch_design Operations

```javascript
binding=I(parent, {type: "frame", ...})      // Insert
U(nodeId, {content: "..."})                   // Update
U(instance+"/child", {content: "..."})        // Update descendant
newNode=R(instance+"/slot", {...})            // Replace
copied=C(sourceId, parent, {...})             // Copy
M(nodeId, newParent, index)                   // Move
D(nodeId)                                     // Delete
G(nodeId, "ai", "prompt...")                  // Generate image
```

---

## Core Concepts / Khái Niệm Cốt Lõi

### What is Pencil / Pencil là gì

[Pencil](https://pencil.evolus.vn/) is an open-source UI/UX design tool. Project files have `.pen` extension and are stored as JSON.

**Agent capabilities with .pen files:**
- ✅ Read and analyze design structure
- ✅ Extract content (text, colors, images)
- ✅ Convert to HTML/CSS/React/Blazor
- ✅ Understand component system and design tokens
- ❌ Render preview (requires Pencil app)
- ❌ Edit directly in app

### File Structure / Cấu trúc File

```json
{
  "version": "2.6",
  "children": [ /* Pages and components */ ],
  "variables": { /* Design tokens */ }
}
```

**Key elements:**
- `children`: Page frames and components
- `variables`: Design tokens (colors, spacing, typography)
- `reusable: true`: Marks reusable components

### Design Tokens / Design Tokens

Variables stored in `variables` object:

```json
"variables": {
  "bg-page": { "type": "color", "value": "#0A0A0B" },
  "text-primary": { "type": "color", "value": "#FFFFFF" },
  "orange-primary": { "type": "color", "value": "#FF5C00" },
  "space-4": { "type": "number", "value": 16 }
}
```

**Usage in elements:**
```json
"fill": "$bg-page",
"fontSize": "$text-lg"
```

### Component System / Hệ thống Component

**Reusable components:**
```json
{
  "type": "frame",
  "id": "btn_001",
  "name": "Button/Primary",
  "reusable": true,
  "children": [...]
}
```

**Component instances (refs):**
```json
{
  "type": "ref",
  "ref": "btn_001",
  "descendants": {
    "label_id": {
      "content": "Submit"
    }
  }
}
```

**External component references (build system):**
```json
{
  "type": "component_ref",
  "component": "ui-kit#Button/Primary",
  "overrides": { ... }
}
```

> [!NOTE]
> `component_ref` is processed by the build system and converted to `ref` during build.

### Atomic Design Architecture / Kiến trúc Atomic Design

For enterprise-scale UI Kits (50+ components), organize with Atomic Design:

```
src/
├── foundations/
│   └── design-tokens.pen     # Colors, typography, spacing
├── atoms/                    # Buttons, inputs, badges
├── molecules/                # Form fields, search bars
├── organisms/                # Cards, navigation, headers
└── pages/                    # Complete pages
```

**Benefits:**
- ✅ Industry standard (Figma, Material Design)
- ✅ Maximum scalability
- ✅ Team collaboration
- ✅ Small, focused files (<500 lines each)

**Naming convention:**
```
{Level}/{Component}/{Variant}/{State}

Examples:
- Atom/Button/Primary/Default
- Atom/Button/Primary/Hover
- Molecule/FormField/Text/Default
- Organism/Card/Feature/Default
```

## Key Patterns / Mẫu Chính

### Reading .pen Files

```javascript
import fs from 'fs';

// Read file
const data = JSON.parse(fs.readFileSync('design.pen', 'utf-8'));

// Get design tokens
const tokens = data.variables;

// Get main page
const mainPage = data.children[0];

// Find sections
const sections = mainPage.children;
```

### Extracting Content

```javascript
// Find all text elements
function extractAllText(element, texts = []) {
  if (element.type === 'text') {
    texts.push(element.content);
  }
  if (element.children) {
    element.children.forEach(child => extractAllText(child, texts));
  }
  return texts;
}

const allText = extractAllText(mainPage);
```

### Converting to CSS Variables

```javascript
// Generate CSS from design tokens
function generateCSSTokens(variables) {
  const cssVars = Object.entries(variables)
    .map(([key, value]) => {
      if (value.type === 'color') return `  --${key}: ${value.value};`;
      if (value.type === 'number') return `  --${key}: ${value.value}px;`;
      return `  --${key}: ${value.value};`;
    })
    .join('\n');
  
  return `:root {\n${cssVars}\n}`;
}
```

### Build System Usage

**Monolithic build (recommended):**
```bash
python3 scripts/build.py --monolithic
# or
python3 scripts/build.py -m

# Output: tPOS.pen (all pages + components in one file)
```

**Standard build:**
```bash
python3 scripts/build.py

# Output: build/ directory with individual files
```

### Atomic Design Extraction

For large UI Kits, extract to Atomic Design structure:

```bash
# Create structure
mkdir -p src/foundations src/atoms src/molecules src/organisms

# Run extraction script (see references/ATOMIC_DESIGN.md)
python3 scripts/extract-atomic.py
```

### Creating New Components

When adding components to Atomic Design structure:

**1. Create `.pen` file in appropriate directory:**
```bash
# Atoms: Buttons, inputs, badges
touch src/atoms/pos-controls.pen

# Molecules: 2-3 atoms combined
touch src/molecules/order-items.pen

# Organisms: Complex sections
touch src/organisms/pos-layout.pen
```

**2. Use proper component structure:**
```json
{
  "version": "2.6",
  "children": [
    {
      "type": "frame",
      "id": "numpad_key_001",
      "name": "Atom/NumpadKey/Standard",
      "reusable": true,
      "width": 64,
      "height": 64,
      "fill": "$bg-elevated",
      "cornerRadius": "$radius-md",
      "children": [...]
    }
  ]
}
```

**3. Follow naming convention:**
```
{Level}/{Component}/{Variant}/{State}

Examples:
- Atom/NumpadKey/Standard
- Atom/NumpadKey/Action/Clear
- Molecule/OrderItem/Standard
- Organism/Dialog/Confirm
```

**4. Rebuild library:**
```bash
python3 scripts/build.py --library
```

## Common Mistakes / Lỗi Thường Gặp

> [!TIP]
> See [Pitfalls Reference](./references/PITFALLS.md) for detailed examples and solutions.

| # | Pitfall | Quick Fix |
|---|---------|-----------|
| 1 | Hardcoding colors | Use `$token` variables |
| 2 | Ignoring `ref` system | Resolve refs by component ID |
| 3 | Opening source files directly | Build first: `python3 scripts/build.py -m` |
| 4 | Direct hex values | Use `$orange-primary` not `#FF5C00` |
| 5 | Centering without width | Add `width: "fill_container"` |
| 6 | Font weight as number | Use `type: "string"`, `value: "500"` |
| 7 | Empty `variables: {}` | Define all used tokens |
| 8 | Token refs in fontSize | Use numbers directly: `fontSize: 14` |
| 9 | Emoji text for icons | Use `icon_font` with Lucide |
| 10 | `glob()` missing subdirs | Use `rglob()` for recursive scan |
| 11 | Components at root level | Wrap in Showcase frame with layout |
| 12 | `wrap: true` unreliable | Use manual rows instead |
| 13 | Footer overlapping content | Ensure footer inside dialog + calculate height |


## Quick Reference / Tham Chiếu Nhanh

### Common Element Types

| Type | Purpose | Key Properties |
|------|---------|----------------|
| `frame` | Container/layout | `layout`, `gap`, `padding`, `children` |
| `text` | Text element | `content`, `fontSize`, `fontFamily`, `fill` |
| `rectangle` | Shape | `width`, `height`, `fill`, `cornerRadius` |
| `icon_font` | Icon (Lucide) | `iconFontName`, `fill` |
| `ref` | Component instance | `ref`, `descendants` |
| `component_ref` | External ref | `component`, `overrides` |

### Layout Properties

| Property | Values | Description |
|----------|--------|-------------|
| `layout` | `vertical`, `horizontal`, `none` | Flexbox direction |
| `gap` | number | Spacing between children (px) |
| `padding` | number/array | `16` or `[vertical, horizontal]` |
| `justifyContent` | `start`, `center`, `end`, `space_between` | Main axis |
| `alignItems` | `start`, `center`, `end` | Cross axis |

### Build Commands

| Command | Purpose |
|---------|---------|
| `python3 scripts/build.py --library` | Build component library from Atomic sources |
| `python3 scripts/build.py -m` | Monolithic build (all pages + library) |
| `python3 scripts/build.py` | Standard build (inject refs) |
| `python3 scripts/build.py -m --output name.pen` | Custom output filename |
| `jq empty file.pen && echo "✅ Valid"` | Validate JSON syntax |
| `jq '.variables' file.pen` | Extract design tokens |

### Token Categories

| Prefix | Purpose | Examples |
|--------|---------|----------|
| `bg-` | Background | `$bg-page`, `$bg-surface` |
| `text-` | Text color/size | `$text-primary`, `$text-lg` |
| `border-` | Border | `$border-default` |
| `space-` | Spacing | `$space-4`, `$space-6` |
| `radius-` | Border radius | `$radius-md` |

### Atomic Design Levels

| Level | Description | Examples |
|-------|-------------|----------|
| **Foundations** | Design tokens | Colors, typography, spacing |
| **Atoms** | Smallest units | Buttons, inputs, badges |
| **Molecules** | 2-3 atoms | Form fields, search bars |
| **Organisms** | Complex sections | Cards, navigation, headers |
| **Pages** | Complete layouts | Home, dashboard, login |

## Security Considerations

1. **Script Execution**: Build scripts (`scripts/build.py`, `scripts/extract-atomic.py`) run on your local machine. Ensure you understand what they do before running usage commands.
2. **File Overwrite**: Automated extraction scripts may overwrite existing files in `src/`. Always use version control (Git) to protect your work.
3. **External Resources**: Be cautious when importing Pencil collections from untrusted sources.

## Resources / Tài Nguyên

### Detailed References

- [MCP Tools Reference](./references/MCP_TOOLS.md) - MCP Pencil integration, realtime design tools
- [File Format Reference](./references/FILE_FORMAT.md) - Complete .pen structure, element types, properties
- [Build System Reference](./references/BUILD_SYSTEM.md) - Build configuration, workflows, troubleshooting
- [Atomic Design Reference](./references/ATOMIC_DESIGN.md) - Enterprise UI Kit organization, extraction scripts
- [Code Conversion Reference](./references/CODE_CONVERSION.md) - Design to HTML/CSS/React/Blazor conversion
- [Pitfalls Reference](./references/PITFALLS.md) - Common mistakes and solutions

### Related Skills

- [Tailwind Design System](../tailwind-design-system/SKILL.md) - CSS framework integration
- [React UI Components](../react-ui-components/SKILL.md) - React component patterns
- [Blazor Theme Patterns](../blazor-theme-patterns/SKILL.md) - Blazor theming
- [MAUI Branding Expert](../maui-branding-expert/SKILL.md) - Mobile UI/UX standards
- [Swift UI Components](../swift-ui-components/SKILL.md) - iOS component patterns

### Workflows

- [/pencil-build](../../workflows/pencil-build.md) - Build operations workflow

### External Resources

- [Pencil Official Site](https://pencil.evolus.vn/)
- [Pencil GitHub](https://github.com/pencilinc/pencil)
- [Atomic Design Book](https://atomicdesign.bradfrost.com/)
- [Material Design System](https://m3.material.io/)
