# @creatly/figma-icons

从 Figma 同步图标到 Iconify JSON 格式，支持 UnoCSS 和 VSCode 预览。

> ⚠️ **首次使用提醒**：如果 `json/` 目录中的图标文件是空的，请参考 [🔄 同步图标（维护者）](#-同步图标维护者) 部分首次同步图标。

## ✨ 特性

- 🎨 **直接从 Figma 同步** - 使用 Iconify 官方 API，无需手动导出
- 🎯 **支持单色和多色** - 自动转换 currentColor 或保留原始颜色
- ⚡ **智能缓存** - 避免重复请求，加快同步速度
- 🔧 **CLI 和 API** - 命令行工具和编程接口两种使用方式
- 📦 **标准格式** - 输出 Iconify JSON，兼容 UnoCSS 和其他工具
- 👁️ **VSCode 预览** - 生成的图标支持 VSCode 插件预览
- 🚀 **零配置使用** - 像 `@iconify-json/carbon` 一样简单，无需手动转换格式

## 📦 安装

```bash
pnpm add -D @creatly/figma-icons
```

## 🚀 快速开始

### 1. 安装依赖

```bash
pnpm add -D @creatly/figma-icons
```

### 2. 在 UnoCSS 中使用

```typescript
// unocss.config.ts
import { defineConfig, presetIcons } from 'unocss'

export default defineConfig({
  presets: [
    presetIcons({
      collections: {
        // 使用 Iconify 官方图标集
        carbon: 'carbon',

        // 使用 @creatly/figma-icons 提供的图标
        // 像使用 @iconify-json/carbon 一样简单！
        creatly: () => import('@creatly/figma-icons/json/icons.json').then(i => i.default),
      },
    }),
  ],
})
```

### 3. 在代码中使用

```vue
<template>
  <!-- 使用官方图标 -->
  <div class="i-carbon-logo-github" />

  <!-- 使用自定义单色图标（支持改色） -->
  <div class="i-creatly-home text-red-500" />

  <!-- 使用自定义多色图标（保留设计颜色） -->
  <div class="i-creatly-power" />
</template>
```

就是这么简单！✨

---

## 🔄 同步图标（维护者）

⚠️ **首次使用或更新图标时需要执行**

### 1. 获取 Figma 配置

#### 获取 Figma Access Token

1. 登录 [Figma](https://www.figma.com/)
2. 点击左上角头像 → **Settings**
3. 滚动到 **Personal access tokens** 部分
4. 点击 **Generate new token**
5. 输入描述（如：`Creatly Icon Sync`）
6. 复制生成的 token（格式：`figd_xxxxx...`）

⚠️ **重要**：Token 只显示一次，请妥善保存！

#### 获取 Figma File ID

从 Figma 文件 URL 中获取：

```
https://www.figma.com/design/AbC123XyZ456/Your-Design-File
                              ↑↑↑↑↑↑↑↑↑↑↑↑
                              这就是 File ID
```

### 2. 配置环境变量

```bash
# .env.local
FIGMA_TOKEN=figd_xxxxx...
FIGMA_FILE_ID=AbC123XyZ456
```

### 3. 配置图标同步

创建 `figma-icons.config.ts` 配置文件：

```typescript
import { defineConfig } from '@creatly/figma-icons'

export default defineConfig({
  // 图标集前缀
  prefix: 'creatly',

  // 输出文件路径
  output: 'json/icons.json',

  // 图标来源配置（可从多个 Page 收集）
  collections: [
    {
      // 单色图标 Page
      pages: ['Icons'],
      // 将所有颜色转换为 currentColor
      convertToCurrentColor: true,
    },
    {
      // 多色图标 Page
      pages: ['Icons-Colored'],
      // 保持原始颜色
      convertToCurrentColor: false,
    },
  ],

  // 图标层级深度
  depth: 4,
})
```

### 4. 同步图标

```bash
cd packages/figma-icons

# 普通同步（使用缓存，速度快）
pnpm sync

# 强制同步（删除缓存，从 Figma 拉取最新数据）
pnpm sync:force
# 或
pnpm sync --force
```

这会生成：

- `json/icons.json` - 合并的图标集（包含单色和多色图标）

**缓存机制**：

- **默认同步**：使用缓存来加速（API 缓存 3 天，SVG 缓存 30 天）
- **强制同步**：删除 `.figma-cache/` 目录，从 Figma 拉取最新数据
- **使用场景**：
  - 🔄 Figma 中更新了图标，需要立即同步
  - 🐛 怀疑缓存数据有问题
  - 🚀 首次同步或需要完全刷新

### 5. 验证生成的图标

```bash
# 查看生成的图标数量
cat json/icons.json | grep -o '".*":' | wc -l
```

### 6. 提交到 Git

```bash
git add json/
git commit -m "feat: update icons from Figma"
git push
```

**重要**：

- ✅ JSON 文件必须提交到 Git
- ✅ 其他开发者会自动获得最新图标
- ✅ 无需每人都配置 Figma Token

### API 使用（编程方式）

```typescript
import { syncAndExport } from '@creatly/figma-icons'

await syncAndExport(
  {
    fileId: 'YOUR_FIGMA_FILE_ID',
    token: 'YOUR_FIGMA_TOKEN',
    prefix: 'creatly',
    pages: ['Icons'], // 可选
    convertToCurrentColor: true, // 单色图标
  },
  './json/icons.json',
)
```

## ⚙️ 配置选项

### 配置文件结构

使用 TypeScript 配置文件 `figma-icons.config.ts`：

```typescript
// 配置文件类型定义
// 使用示例
import { defineConfig } from '@creatly/figma-icons'

interface FigmaIconsConfigFile {
  /** 图标集前缀 (例如: 'creatly') */
  prefix: string

  /** 输出文件路径 */
  output: string

  /** 图标来源配置列表 */
  collections: Array<{
    /** 要导出的 Figma Page 名称列表 */
    pages: string[]

    /** 是否转换为 currentColor (单色图标) */
    convertToCurrentColor?: boolean // 默认: true

    /** 要替换为 currentColor 的颜色列表 */
    colorsToReplace?: string[]
  }>

  /** 图标所在的层级深度 */
  depth?: number // 默认: 2

  /** 缓存目录 */
  cacheDir?: string // 默认: '.figma-cache'
}

export default defineConfig({
  prefix: 'creatly',
  output: 'json/icons.json',
  collections: [
    {
      pages: ['Icons'],
      convertToCurrentColor: true,
    },
    {
      pages: ['Icons-Colored'],
      convertToCurrentColor: false,
    },
  ],
  depth: 4,
})
```

### API 配置（编程方式）

```typescript
interface FigmaIconsConfig {
  /** Figma 文件 ID */
  fileId: string
  /** Figma API Token */
  token: string
  /** 图标集前缀 */
  prefix: string
  /** 要同步的 Pages */
  pages?: string[]
  /** 图标层级深度 */
  depth?: number
  /** 是否转换为 currentColor */
  convertToCurrentColor?: boolean
  /** 要替换的颜色列表 */
  colorsToReplace?: string[]
  /** 缓存目录 */
  cacheDir?: string
  /** API 缓存时间 (毫秒) */
  cacheAPITTL?: number
  /** SVG 缓存时间 (毫秒) */
  cacheSVGTTL?: number
}
```

## 📋 环境变量

必需的环境变量（通过 `.env.local` 文件提供）：

```bash
# .env.local
FIGMA_TOKEN=figd_xxx_your_token
FIGMA_FILE_ID=your_file_id
```

**如何获取这些值？** 请参考 [同步图标（维护者）](#🔄-同步图标维护者) 中的详细说明。

## 🎯 使用场景

### 单色图标（界面图标）

适用于需要随主题变色的图标：

在配置文件中：

```typescript
collections: [
  {
    pages: ['Icons'],
    convertToCurrentColor: true, // 转换为 currentColor
  }
]
```

在 Figma 中：

- 使用纯黑色 (#000000)
- 会自动转换为 `currentColor`
- 支持 CSS 控制颜色

### 多色图标（品牌 Logo）

适用于需要保留设计颜色的图标：

在配置文件中：

```typescript
collections: [
  {
    pages: ['Icons-Colored'],
    convertToCurrentColor: false, // 保留原始颜色
  }
]
```

在 Figma 中：

- 使用实际设计颜色
- 保留所有颜色信息
- 不支持 CSS 改色

## 🔧 在 Figma 中准备图标

### 推荐结构

```
📄 Figma File
  📁 Icons (Page) - 单色图标
    🔷 home (Component)
    🔷 arrow-left (Component)
    🔷 user (Component)

  📁 Icons-Colored (Page) - 多色图标
    🔷 brand-logo (Component)
    🔷 product-icon (Component)
```

### 设计要求

1. **使用 Component** - 每个图标必须是 Component
2. **命名规范** - 使用 kebab-case（会自动转换）
3. **统一尺寸** - 建议 24×24px 或 32×32px
4. **单色图标** - 使用纯黑色 (#000000)
5. **多色图标** - 使用实际设计颜色

## 🎨 VSCode 预览支持

生成的 JSON 文件符合 Iconify 规范，支持 VSCode 预览。

### 1. 安装插件

- UnoCSS (`antfu.unocss`)
- Iconify IntelliSense (`antfu.iconify`)

### 2. 配置 VSCode

`.vscode/settings.json`:

```json
{
  "iconify.customCollectionJsonPaths": [
    "packages/figma-icons/json/icons.json"
  ]
}
```

### 3. 使用

在代码中输入 `i-creatly-` 即可看到：

- ✅ 自动补全
- ✅ 图标预览（悬停显示）
- ✅ 模糊搜索

## 🔍 故障排查

### 问题：图标文件是空的

**症状**：`json/icons.json` 只有基本结构，没有图标数据

**原因**：需要维护者首次从 Figma 同步图标

**解决方案**：

1. 配置环境变量（`.env.local`）：

   ```bash
   FIGMA_TOKEN=your_token
   FIGMA_FILE_ID=your_file_id
   ```

2. 创建配置文件 `figma-icons.config.ts`（参考上文示例）

3. 运行同步命令：

   ```bash
   cd packages/figma-icons
   pnpm sync
   ```

4. 提交到 Git：
   ```bash
   git add json/ figma-icons.config.ts
   git commit -m "feat: sync icons from Figma"
   ```

详见 [json/README.md](json/README.md)

### 问题：VSCode 中看不到图标预览

**解决方案**：

1. 确保已安装 Iconify IntelliSense 插件
2. 检查 `.vscode/settings.json` 配置是否正确
3. 重启 VSCode（Cmd+Shift+P → Reload Window）

### 问题：同步失败

检查：

- Figma Token 是否正确
- Figma File ID 是否正确
- 网络连接是否正常

### 问题：同步失败并提示重名图标

**症状**：日志中出现“检测到重名图标，已终止同步”并附带重名明细

**原因**：Figma 允许重名，但同步时会把图标名称规范化后作为 key：

- 转小写
- 空格转换为 `-`
- 移除特殊字符

规范化后同名会发生覆盖，因此会直接报错并中断同步。

**解决方案**：

1. 按错误日志中的明细定位冲突节点（Page、Node、ID、Path）
2. 在 Figma 中将冲突图标改成唯一名称
3. 重新执行 `pnpm sync`（必要时使用 `pnpm sync:force`）

### 问题：找不到图标

检查：

- 图标是否是 Component
- Pages 参数是否正确
- depth 参数是否匹配 Figma 层级

### 问题：图标显示不正确

检查：

- 单色图标是否使用了多种颜色
- 多色图标是否使用了 `--colored` 参数
- SVG 是否包含复杂的滤镜或效果

## 📚 相关资源

- [Iconify Documentation](https://iconify.design/docs/)
- [Iconify Tools](https://iconify.design/docs/libraries/tools/)
- [Figma API](https://www.figma.com/developers/api)
- [UnoCSS Icons](https://unocss.dev/presets/icons)

## 📄 License

MIT

## 🤝 Contributing

欢迎贡献！请提交 PR 或 Issue。
