Commit 2de0a5f0 by liimin

fix(engine): 补齐 React+shadcn/ui 脚手架基础组件,修复生成应用导入失败

- 新增 nodes/initial/shadcn-ui.ts:随 shadcn/ui 画像生成 button/input/card 等 19 个基础组件 + lib/utils,并注入所需依赖(radix/class-variance-authority/clsx/tailwind-merge/lucide-react/react-hook-form)
- scaffold.ts React 策略按 componentLibrary 解析 shadcn,合并 UI 文件与依赖到 package.json
- 修复 generate-react-app 因缺少 @/components/ui/* 导致 Vite 解析失败的问题
1 parent f67ea294
# CodeRio 项目结构与架构说明
> 面向「设计稿 → 代码」的 Figma 转代码(design-to-code)全栈系统。
> 仓库:pnpm workspace monorepo,含 **前端 / 编排服务 / 生成引擎** 三层。
---
## 0. 顶层结构与运行模型
```
coderio-monorepo/
├── packages/coderio/ # 引擎:设计转代码核心(LangGraph 流程 + 工具/Agent)
├── apps/server/ # 编排服务:REST + SSE、Job 持久化、并发队列、预览托管
├── apps/web/ # 前端:React 18 + Vite + TS + shadcn 风格
├── scripts/dev.mjs # 开发 supervisor(端口 4174,常驻控制后端 4173 + Vite 5173)
└── pnpm-workspace.yaml # packages/* + apps/*
```
- **开发模式(supervisor 架构,`npm run dev`)**:`dev.mjs` 常驻,统一拉起并管控后端(4173)与前端 Vite(5173);停后端不会杀 supervisor,故随时可「启动后端」。改 `dev.mjs` 需 Ctrl+C 重起。
- **生产模式(`npm run server`)**:单进程直接跑后端,前端可构建后由后端托管 `apps/web/dist`。
- **关键铁律**:引擎改 `src/*` 后必须 `node packages/coderio/build-esbuild.mjs` 重建 `dist/index.js`,服务端加载的是 dist。**框架扩展走 OCP**:加新框架 = 新增 strategy + scaffold,绝不重构现有 React prompt。
---
## 一、底层引擎 `packages/coderio`(设计转代码引擎)
> 入口 `src/index.ts` 导出:`design2code`(主流程)、类型、`ProjectProfile` 画像 API、`loadConfig/subscribeLogs` 等编排支撑 API。
### 1.1 核心编排 `src/graph.ts` —— LangGraph 四节点流水线
`design2code(url, mode, options)` 编译并执行:
```
START → INITIAL → PROCESS → CODE → VALIDATION → END
```
- `Design2CodeOptions`:`modelConfig`(provider/model/baseUrl/apiKey/figmaToken,后端注入覆盖 `~/.coderio/config.yaml`)、`projectProfile`(项目画像)、`target`(生成落点)、`fillContainer`(撑满容器开关,默认 true)。
- 每任务 SQLite checkpoint(`node:sqlite`)支持断点续跑;`resume` 参数为 false 时整库重置(用 SQL 清 WAL,绕过环境的 safe-delete 钩子)。
- 节点执行顺序由 `GraphStateAnnotation` 共享状态:`urlInfo / workspace / protocol / figmaInfo / config`。
### 1.2 四个节点
| 节点 | 文件 | 职责 |
|---|---|---|
| **INITIAL** | `nodes/initial/index.ts` + `scaffold.ts` | 确定性生成脚手架(不走 LLM,避免死循环)。`reactScaffold`/`vue3Scaffold` 工厂化,`getScaffoldForFramework()` 按 framework 命中;`getScaffoldEssentialFiles()` 做完整性校验。 |
| **PROCESS** | `nodes/process/index.ts` + `structure/` | `executeFigmaAndImagesActions`(fetch+清洗+下载图片)→ `figmaTool.processedStyle` → `generateStructure` → 写出 `protocol.json` / `images.json`。 |
| **CODE** | `nodes/code/index.ts` + `utils.ts` | `processNode`(逐组件生成,增量缓存)→ `injectRootComponentToApp`。策略派发:`utils.ts` 经 `getActiveStrategy()` 调 React/Vue prompt;拓展点 `strategies/component-usage.ts` 的 `LIBRARY_COMPONENT_CATALOG`(降级链:自定义 > 库组件 > 原生)。 |
| **VALIDATION** | `nodes/validation/index.ts` | 按 `validationMode`:`code`(仅 git commit)/`full`/`with-report` → 调 `validationLoop`(Playwright 截图 + Figma 缩略图 MAE 比对)+ `commit`。 |
### 1.3 框架策略(OCP 加法式)
`nodes/code/strategies/`:`types.ts`(接口)、`react.ts`(薄包装现有 prompt)、`vue3.ts`(Vue3 SFC)、`index.ts`(注册表 `STRATEGIES` + `getStrategyForProfile`,按 framework 小写命中)。新增框架 = 加一个策略文件 + 注册一行。
### 1.4 工具层 `src/tools/`
- `figma-tool`:拉取/清洗 Figma 文档、下载图片、简化图片节点、样式转 CSS、url 解析。
- `launch-tool` + `utils/dev-server-manager.ts`:起/停内部校验 dev server(Windows 用 `taskkill /f /t` 杀进程树,杜绝泄漏)。
- `report-tool`:产物可视化(`template/dist/` 被引擎消费,源码已裁剪)。
- `hierarchy-tool` / `history-tool` / `position-tool` / `style-tool` / `visualization-tool`:结构、历史、定位、样式、可视化辅助。
### 1.5 Agents `src/agents/`
`initial-agent` / `judger-agent` / `refiner-agent` / `commit-agent` / `launch-agent` —— 接入 graph 的多工具 LLM Agent(保留,非可折叠样板)。
### 1.6 支撑模块 `src/utils/`
`logger`(subscribeLogs 供服务端 SSE 转发)、`config`(loadConfig/setRuntimeConfig)、`project-profile`(loadProjectProfile/renderProfileConstraint + 运行时 holder)、`checkpoint`(SQLite)、`workspace`(路径解析)、`file`(`writeFileSyncSafe` 抗 EPERM 重试)、`code-cache`、`patch-evoltagent`、`url-parser`。
> **构建**:`build-esbuild.mjs`(tsup 在本环境必失败,故用 esbuild Node API 直接构建)→ `dist/index.js` + `tsc --emitDeclarationOnly` 生成 `.d.ts`。
---
## 二、服务端 `apps/server`(编排服务)
> 端口 **4173**,Node 内置 `http` + `node:sqlite`,零外部框架。**密钥完全服务端化**:前端不接触 API key / Figma token。
### 2.1 装配入口 `src/index.ts`(main)
- `loadDotEnv` → `resolveServerOptions`(端口/host/outputDir/maxConcurrent)→ `loadServerModelConfig`。
- `JobStore`(SQLite 持久化,`reconcileOnStartup` 把遗留 running/queued 标为 cancelled)。
- `hub.broadcast` 总线 → `createApp` 拿到真实 SSE 广播器后接管。
- 端口监听带 **EADDRINUSE 重试(25 次 / 300ms)** + 启动前 `killOtherListenersOnPort` 清陈旧监听者。
- 重启/关停:`restartServer`(spawn `npm run server` 新进程后释放端口)、`shutdownServer`。
### 2.2 HTTP 层 `src/server.ts`(createApp)
- **REST**:`/api/config`、`/api/generate`、`/api/jobs`、`/api/job/:id`、`/api/project-profile`(GET/PUT)、`/api/project-profile/scan`、`/api/fs/list`、`/api/admin/status`、`/api/preview(+stop/restart)`、`/api/project/run(+stop)`、`/api/admin/restart/shutdown`。
- **SSE**:`/api/stream` 单条事件流(`log/jobs/preview/projectRun`),连接时 replay 快照(最新日志环形缓冲 1000 条 + 当前 jobs/preview/projectRun)。
- **就绪探针**:`/api/health`(端口仅在引擎 + sqlite 就绪后才 listen,故 200 即代表可接收 `/api/generate`)。
- **静态托管**:优先 `apps/web/dist`(SPA 回退),否则回退 `public/index.html`;开发模式(`COD_SERVE_WEB=0`)根路径 302 到前端 5173。
### 2.3 队列与执行
- `queue.ts` `JobQueue`:并发上限(默认 1),FIFO;`cancel()` 对排队任务直接丢弃、对运行任务杀子进程;`position()` 返回排队序号。
- `runner.ts` `runJob`:**子进程隔离** spawn `tsx generate-child.ts`,`env.COD_RUNTIME_CONFIG` 注入 `modelConfig/projectProfile/target/fillContainer`;监听 stdout/stderr 转发日志,识别 `__D2C_DONE__` / `__D2C_ERROR__` 哨兵;`cancelRun` 杀进程树(POSIX 负 pid / Windows `child.kill`)。
- `generate-child.ts`:解析 `COD_RUNTIME_CONFIG` → 调用 `design2code`。
### 2.4 预览与运行
- `preview.ts` `PreviewManager`:托管**生成产物 my-app** 的 vite dev server(端口 5180–5195),`killStalePreviewPorts()` 清理 5180–6199 残留(避开前端 5173)。
- `project-runner.ts` `ProjectRunner`:托管**目标项目自身** dev server;用 `wmic` 进程树 + netstat 探测端口,排除 baseline(避免误认编排服务自身端口)。
### 2.5 配置与画像
- `config.ts`:`loadServerModelConfig`(env > `~/.coderio/config.yaml` > 默认);`loadProjectProfile/saveProjectProfile` 读写 `~/.coderio/coderio.project.json`;`configView` 返回前端安全视图(不暴露密钥)。
- `project-scanner.ts` `scanProject`:扫描目标项目(Phase 1 草稿式),识别框架/样式/组件库/状态管理/路由/设计令牌/CSS 变量/导出组件与工具,产出 `ProjectProfile` + `CODERIO.md` 草稿(仅草稿不落盘,由 UI 确认后 PUT)。
### 2.6 持久化 `jobStore.ts`
SQLite(`jobs.db`,建表 `jobs(id,payload,updated_at)`;SQLite 不可用时回退 JSON `jobs.json`)。`create/update/get/delete/clear/list/reconcileOnStartup`。
---
## 三、前端 `apps/web`(React + Vite + TS + shadcn)
> 端口 **5173**(dev)。`vite.config.ts` 代理 `/api`→4173、`/devctl`→4174。
### 3.1 框架与路由 `App.tsx`
`Sidebar` + `Topbar` + `<Routes>`:`/`(Workbench)、`/history`(History)、`/settings`(Settings)。
### 3.2 数据与连接 `lib/`
- `api.ts`:**`api` 对象**封装全部 REST(含后端重启冷却重试 `markBackendRestarting`、后端停机友好标记 `setBackendKnownDown`);`checkBackendHealth` 直接探测 `/api/health`;**全局单例 SSE** `onSSE(event, handler)` 订阅(log/jobs/preview/projectRun/system),避免每组件各自轮询。
- `connection.tsx`:`ConnectionProvider` / `useConnection` 提供「已连接」状态(顶栏脉冲指示)。
- `jobActions.ts`:统一抽取 `cancelJob` / `deleteJob` / `startPreview` / `clearAllJobs`(confirm + toast),供 Workbench 与 History 复用。
- `types.ts`:`Job` / `TechStack` / `ProjectProfile` / `SystemStatus` 等。
### 3.3 组件
- `components/layout`:`Sidebar`、`Topbar`、`PageHeader`(仅 icon+description+actions,标题由 Topbar 渲染)、`ErrorBoundary`、`nav`。
- `components/project`:`Combobox`、`DirectoryField`、`DirectoryPickerDialog`、`profile-presets`(6 项技术栈预设)、`ProjectAccessPanel`(目标项目接入/启动)。
- `components/ui`:shadcn 风格 `badge/button/input/ `label/progress/sonner/status-pill`。
### 3.4 页面
- **Workbench**:生成目标选择 + 技术栈预设卡片(独立预览可选框架,项目模式只读画像)+ 撑满容器开关 + 任务列表(徽章/取消/启动预览/删除)+ 实时日志终端 + 产物预览 iframe。
- **History**:历史任务记录(复用 jobActions)。
- **Settings**:服务启动入口(LaunchOverview:前端 5173 / 后端 4173 / supervisor 4174 / 预览)、项目接入画像(GET/PUT / 扫描)、模型配置(只读视图)、生命周期(重启/停止后端、停止全部)。
---
## 🔁 端到端数据流
```
用户(Workbench 提交 Figma URL + 技术栈/画像)
→ POST /api/generate → JobQueue.enqueue
→ runner.spawn(tsx) → 注入 COD_RUNTIME_CONFIG
→ design2code:
INITIAL 生成脚手架(React/Vue)
PROCESS Figma 抓取 + 样式处理 + structure(protocol.json)
CODE LLM 逐组件生成 + 注入根组件(命中 strategy / 组件库降级链)
VALIDATION Playwright 截图 ↔ Figma 缩略图 MAE 比对 + git commit
→ SSE 推送 jobs/logs/preview 实时回流前端
→ PreviewManager 启动 my-app vite(5180) → 前端嵌入预览
```
## 🧩 核心设计原则(贯穿三层)
1. **密钥服务端化**:API key / Figma token 只在服务端,经 `COD_RUNTIME_CONFIG` 注入子进程,前端零接触。
2. **子进程隔离**:生成(Playwright / 多 Agent)跑在 detached 子进程,崩了不拖垮服务;取消即杀进程树。
3. **框架扩展 OCP**:新增框架 = 新增 strategy + scaffold,不触碰既有 React prompt;组件库 / UI kit 单一扩展点 `LIBRARY_COMPONENT_CATALOG`。
4. **画像透传闭环**:扫描(`scanProject`) → PUT `/api/project-profile` → 服务端持久化 → 生成子进程读取 → 引擎 prompt 注入(`<project_profile>`),生成贴合既有代码。
5. **复盘自愈**:后端端口 EADDRINUSE 重试 + 陈旧端口清理;Windows 进程树清理;EPERM 安全写入重试;孤儿任务启动自愈。
...@@ -2,6 +2,7 @@ import fs from 'node:fs'; ...@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { writeFileSyncSafe } from '../../utils/file'; import { writeFileSyncSafe } from '../../utils/file';
import type { ProjectProfile } from '../../types/project-profile'; import type { ProjectProfile } from '../../types/project-profile';
import { buildShadcnUiFiles, shadcnDeps, isShadcnLibrary } from './shadcn-ui';
/** /**
* Framework-aware scaffold. * Framework-aware scaffold.
...@@ -26,10 +27,10 @@ export interface ScaffoldStrategy { ...@@ -26,10 +27,10 @@ export interface ScaffoldStrategy {
// React scaffold (default — behavior unchanged) // React scaffold (default — behavior unchanged)
// ============================================================ // ============================================================
function renderPackageJson(appName: string): string { function renderPackageJson(appName: string, extraDeps: Record<string, string> = {}): string {
return JSON.stringify( return JSON.stringify(
{ {
name: appName || 'my-app', name: appName || 'my-app',
private: true, private: true,
version: '0.0.0', version: '0.0.0',
type: 'module', type: 'module',
...@@ -41,6 +42,7 @@ function renderPackageJson(appName: string): string { ...@@ -41,6 +42,7 @@ function renderPackageJson(appName: string): string {
dependencies: { dependencies: {
react: '^18.3.1', react: '^18.3.1',
'react-dom': '^18.3.1', 'react-dom': '^18.3.1',
...extraDeps,
}, },
devDependencies: { devDependencies: {
'@tailwindcss/vite': '^4.1.4', '@tailwindcss/vite': '^4.1.4',
...@@ -216,9 +218,10 @@ const reactScaffold: ScaffoldStrategy = { ...@@ -216,9 +218,10 @@ const reactScaffold: ScaffoldStrategy = {
'src/main.tsx', 'src/main.tsx',
'src/App.tsx', 'src/App.tsx',
], ],
build(appName) { build(appName, profile) {
const isShadcn = isShadcnLibrary(profile?.componentLibrary);
return { return {
'package.json': renderPackageJson(appName), 'package.json': renderPackageJson(appName, isShadcn ? shadcnDeps : {}),
'vite.config.ts': renderViteConfig(), 'vite.config.ts': renderViteConfig(),
'tsconfig.json': renderTsConfig(), 'tsconfig.json': renderTsConfig(),
'index.html': renderIndexHtml(appName || 'my-app'), 'index.html': renderIndexHtml(appName || 'my-app'),
...@@ -228,6 +231,7 @@ const reactScaffold: ScaffoldStrategy = { ...@@ -228,6 +231,7 @@ const reactScaffold: ScaffoldStrategy = {
'src/App.less': renderAppLess(), 'src/App.less': renderAppLess(),
'src/vite-env.d.ts': renderViteEnvDts(), 'src/vite-env.d.ts': renderViteEnvDts(),
'.gitignore': renderGitignore(), '.gitignore': renderGitignore(),
...(isShadcn ? buildShadcnUiFiles() : {}),
}; };
}, },
}; };
......
/**
* shadcn/ui primitive components for the React scaffold.
*
* When a generation's `componentLibrary` resolves to `shadcn/ui`, the
* `LIBRARY_COMPONENT_CATALOG` (`component-usage.ts`) instructs the CODE node to
* import primitives from `@/components/ui/*`. The React scaffold must therefore
* emit those files — otherwise the generated app fails to resolve the imports
* (the exact bug this module fixes).
*
* This is the single extension point for the shadcn kit (Open-Closed Principle):
* the React scaffold simply merges `buildShadcnUiFiles()` into its output and
* `shadcnDeps` into package.json. No existing React prompt code is touched.
*/
/** Extra runtime dependencies required by the shadcn primitives. */
export const shadcnDeps: Record<string, string> = {
"@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-label": "^2.1.1",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-radio-group": "^1.2.3",
"@radix-ui/react-switch": "^1.1.2",
"@radix-ui/react-progress": "^1.1.1",
"@radix-ui/react-slider": "^1.2.2",
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-dropdown-menu": "^2.1.6",
"@radix-ui/react-tooltip": "^1.1.8",
"@radix-ui/react-tabs": "^1.1.3",
"class-variance-authority": "^0.7.1",
clsx: "^2.1.1",
"tailwind-merge": "^2.6.0",
"lucide-react": "^0.469.0",
"react-hook-form": "^7.54.2",
};
const utils = `import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
`;
const button = `import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: { variant: "default", size: "default" },
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
`;
const input = `import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
ref={ref}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
`;
const label = `import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
`;
const card = `import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("rounded-xl border bg-card text-card-foreground shadow", className)}
{...props}
/>
)
)
Card.displayName = "Card"
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col gap-1.5 p-6", className)} {...props} />
)
)
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("font-semibold leading-none tracking-tight", className)} {...props} />
)
)
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
)
)
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
)
)
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
)
)
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
`;
const badge = `import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: { variant: "default" },
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />
}
export { Badge, badgeVariants }
`;
const alert = `import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive: "border-destructive/50 text-destructive [&>svg]:text-destructive",
},
},
defaultVariants: { variant: "default" },
}
)
const Alert = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>>(
({ className, variant, ...props }, ref) => (
<div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} />
)
)
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h5 ref={ref} className={cn("mb-1 font-medium leading-none tracking-tight", className)} {...props} />
)
)
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} {...props} />
)
)
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }
`;
const avatar = `import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image ref={ref} className={cn("aspect-square h-full w-full", className)} {...props} />
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }
`;
const checkbox = `import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }
`;
const radioGroup = `import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => (
<RadioGroupPrimitive.Root className={cn("grid gap-2", className)} {...props} ref={ref} />
))
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
))
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName
export { RadioGroup, RadioGroupItem }
`;
const switchCmp = `import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName
export { Switch }
`;
const progress = `import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20", className)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: \`translateX(-\${100 - (value || 0)}%)\` }}
/>
</ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName
export { Progress }
`;
const slider = `import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"
import { cn } from "@/lib/utils"
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn("relative flex w-full touch-none select-none items-center", className)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-primary/20">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
export { Slider }
`;
const table = `import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
)
)
Table.displayName = "Table"
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
)
)
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
)
)
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tfoot ref={ref} className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-0", className)} {...props} />
)
)
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr ref={ref} className={cn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", className)} {...props} />
)
)
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th ref={ref} className={cn("h-10 px-2 text-left align-middle font-medium text-muted-foreground", className)} {...props} />
)
)
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<td ref={ref} className={cn("p-2 align-middle", className)} {...props} />
)
)
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
({ className, ...props }, ref) => (
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
)
)
TableCaption.displayName = "TableCaption"
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption }
`;
const dialog = `import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col gap-1.5 text-center sm:text-left", className)} {...props} />
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end gap-2", className)} {...props} />
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold leading-none tracking-tight", className)} {...props} />
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog, DialogPortal, DialogOverlay, DialogTrigger, DialogClose, DialogContent,
DialogHeader, DialogFooter, DialogTitle, DialogDescription,
}
`;
const sheet = `import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Sheet = SheetPrimitive.Root
const SheetTrigger = SheetPrimitive.Trigger
const SheetClose = SheetPrimitive.Close
const SheetPortal = SheetPrimitive.Portal
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className)}
{...props}
ref={ref}
/>
))
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom: "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right: "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: { side: "right" },
}
)
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
))
SheetContent.displayName = SheetPrimitive.Content.displayName
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col gap-1.5 p-4", className)} {...props} />
)
SheetHeader.displayName = "SheetHeader"
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />
)
SheetFooter.displayName = "SheetFooter"
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title ref={ref} className={cn("text-lg font-semibold text-foreground", className)} {...props} />
))
SheetTitle.displayName = SheetPrimitive.Title.displayName
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref)
=> (
<SheetPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
))
SheetDescription.displayName = SheetPrimitive.Description.displayName
export {
Sheet, SheetPortal, SheetOverlay, SheetTrigger, SheetClose, SheetContent,
SheetHeader, SheetFooter, SheetTitle, SheetDescription,
}
`;
const tabs = `import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground", className)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.TabsTrigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", className)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
`;
const tooltip = `import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95", className)}
{...props}
/>
</TooltipPrimitive.Portal>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
`;
const dropdownMenu = `import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md", className)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & { inset?: boolean }
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & { inset?: boolean }
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label ref={ref} className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)} {...props} />
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
export {
DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem,
DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel,
DropdownMenuSeparator, DropdownMenuGroup, DropdownMenuPortal,
DropdownMenuSub, DropdownMenuRadioGroup,
}
`;
const form = `import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import { Controller, FormProvider, useFormContext, useFormState } from "react-hook-form"
import { cn } from "@/lib/utils"
const Form = FormProvider
const FormFieldContext = React.createContext<{ name?: string }>({})
const FormField = ({ name, ...props }: { name: string } & React.ComponentProps<typeof Controller>) => {
return (
<FormFieldContext.Provider value={{ name }}>
<Controller name={name} {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const { getFieldState } = useFormState({ name: fieldContext.name })
const formContext = useFormContext()
const fieldState = getFieldState(formContext)
return { name: fieldContext.name, formItemId: \`\${fieldContext.name}-form-item\`, formDescriptionId: \`\${fieldContext.name}-form-item-description\`, formMessageId: \`\${fieldContext.name}-form-item-message\`, ...fieldState }
}
const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => <div ref={ref} className={cn("space-y-2", className)} {...props} />
)
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn("text-sm font-medium", className)} {...props} />
))
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot>>(
({ ...props }, ref) => <Slot ref={ref} {...props} />
)
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
)
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
if (!body) return null
return (
<p ref={ref} id={formMessageId} className={cn("text-sm font-medium text-destructive", className)} {...props}>
{body}
</p>
)
}
)
FormMessage.displayName = "FormMessage"
export { Form, FormField, FormItem, FormLabel, FormControl, FormDescription, FormMessage, useFormField }
`;
/**
* Build the full set of shadcn/ui primitive files for the React scaffold.
* Keyed by their `@/components/ui/<name>` path (without the `@/` prefix).
*/
export function buildShadcnUiFiles(): Record<string, string> {
return {
'src/lib/utils.ts': utils,
'src/components/ui/button.tsx': button,
'src/components/ui/input.tsx': input,
'src/components/ui/label.tsx': label,
'src/components/ui/card.tsx': card,
'src/components/ui/badge.tsx': badge,
'src/components/ui/alert.tsx': alert,
'src/components/ui/avatar.tsx': avatar,
'src/components/ui/checkbox.tsx': checkbox,
'src/components/ui/radio-group.tsx': radioGroup,
'src/components/ui/switch.tsx': switchCmp,
'src/components/ui/progress.tsx': progress,
'src/components/ui/slider.tsx': slider,
'src/components/ui/table.tsx': table,
'src/components/ui/dialog.tsx': dialog,
'src/components/ui/sheet.tsx': sheet,
'src/components/ui/tabs.tsx': tabs,
'src/components/ui/tooltip.tsx': tooltip,
'src/components/ui/dropdown-menu.tsx': dropdownMenu,
'src/components/ui/form.tsx': form,
};
}
/** Whether a profile's component library resolves to shadcn/ui. */
export function isShadcnLibrary(componentLibrary: string | undefined): boolean {
const lib = (componentLibrary || '').toLowerCase();
return lib.includes('shadcn') || lib.includes('shadcn/ui');
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!