Communitygithub.com

ComeOnOliver/skillshub

用於建構 UI 元件時使用。強制遵循 ShadCN UI 模式、無障礙標準(Radix UI)以及 2025 年 11 月的 TailwindCSS 最佳實踐。

skillshub 是什麼?

這個技能(ShadCN UI Patterns - November 2025 Standards)是專為使用 ShadCN UI 庫開發 React 前端元件的開發者與 AI 代理所設計的官方指南。它強制執行基於「複製貼上而非 npm 套件」的元件安裝哲學、Radix UI 的無障礙標準(WCAG 2.1 AA 等級)、以及 TailwindCSS 優先的樣式系統。技能詳細說明了 Button、Dialog、Form 等核心元件的正確使用模式,強調 TypeScript 型別安全、React Hook Form 搭配 Zod 的表單驗證,以及 Server Component 與 Client Component 的明確分界。此外,技能還指導開發者避免常見錯誤,例如忘記 DialogTitle 導致無障礙違規、不使用 Form 元件進行表單驗證、硬編碼顏色而非使用語義化變體,以及未正確使用 asChild 屬性來避免巢狀按鈕。它也涵蓋了暗模式支援、焦點管理與鍵盤導航的測試方法。適用於支援 ShadCN UI 的 React 框架(如 Next.js 15),確保元件庫的一致、可維護與無障礙。

相容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/barnhardt-enterprises-inc/shadcn-ui-patterns

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

ShadCN UI 模式 - 2025 年 11 月標準

何時使用

  • 建構新的 UI 元件
  • 重構現有元件以使用 ShadCN
  • 實作含驗證的表單
  • 建立模態框、對話框與疊層
  • 確保無障礙合規性

為什麼選擇 ShadCN UI?

  • 複製貼上,而非 npm - 完全擁有元件程式碼
  • Radix UI 基礎元件 - 內建無障礙支援(WCAG 2.1 AA 等級)
  • TailwindCSS 優先 - 完全自訂,無 CSS-in-JS
  • TypeScript 原生 - 型別安全的 props 與變體
  • Server Component 相容 - 可與 Next.js 15 App Router 搭配使用

核心原則

1. 元件安裝模式

# 依需求安裝個別元件
npx shadcn@latest add button
npx shadcn@latest add dialog
npx shadcn@latest add form
npx shadcn@latest add input
npx shadcn@latest add label

元件會被複製到 src/components/ui/ 目錄 — 你擁有程式碼的所有權。

2. 元件使用模式

Button 元件

import { Button } from "@/components/ui/button"

// ✅ 正確:使用語義化變體
<Button variant="default">儲存</Button>
<Button variant="destructive">刪除</Button>
<Button variant="outline">取消</Button>
<Button variant="ghost">跳過</Button>
<Button variant="link">了解更多</Button>

// ✅ 正確:使用尺寸變體
<Button size="default">中</Button>
<Button size="sm">小</Button>
<Button size="lg">大</Button>
<Button size="icon"><Icon /></Button>

// ❌ 錯誤:不使用 Button 元件而建立自訂按鈕
<button className="px-4 py-2 bg-blue-500">錯誤</button>

Dialog/Modal 元件

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

// ✅ 正確:使用正確的對話框結構(無障礙)
<Dialog>
  <DialogTrigger asChild>
    <Button>開啟設定</Button>
  </DialogTrigger>
  <DialogContent>
    <DialogHeader>
      <DialogTitle>設定</DialogTitle>
      <DialogDescription>
        在此設定你的應用程式選項。
      </DialogDescription>
    </DialogHeader>
    {/* 對話框內容 */}
  </DialogContent>
</Dialog>

// ❌ 錯誤:省略 DialogHeader 或 DialogTitle(破壞螢幕閱讀器)
<DialogContent>
  <h2>設定</h2> {/* 錯誤 - 應使用 DialogTitle */}
</DialogContent>

Form 元件(搭配 React Hook Form + Zod)

import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"

// ✅ 正確:先定義 Zod schema(驗證)
const formSchema = z.object({
  email: z.string().email("無效的電子郵件地址"),
  password: z.string().min(8, "密碼長度至少需要 8 個字元"),
})

function LoginForm() {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: "",
      password: "",
    },
  })

  async function onSubmit(values: z.infer<typeof formSchema>) {
    // 型別安全的驗證資料
    console.log(values)
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>電子郵件</FormLabel>
              <FormControl>
                <Input placeholder="[email protected]" {...field} />
              </FormControl>
              <FormDescription>
                我們絕不會分享你的電子郵件。
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <FormItem>
              <FormLabel>密碼</FormLabel>
              <FormControl>
                <Input type="password" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button type="submit">登入</Button>
      </form>
    </Form>
  )
}

// ❌ 錯誤:使用無驗證的非受控表單
<form>
  <input name="email" /> {/* 無驗證 */}
</form>

3. Server vs Client Components

// ✅ 正確:對靜態對話框使用 Server Component
import { Dialog, DialogContent } from "@/components/ui/dialog"

export default function ServerDialog() {
  // 不需要 'use client'
  return <Dialog>...</Dialog>
}

// ✅ 正確:需要狀態時使用 Client Component
'use client'

import { useState } from 'react'
import { Dialog, DialogContent } from "@/components/ui/dialog"

export function ClientDialog() {
  const [open, setOpen] = useState(false)

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent>...</DialogContent>
    </Dialog>
  )
}

4. 無障礙需求

焦點管理

// ✅ 正確:使用 asChild 搭配 DialogTrigger 以獲得正確焦點
<DialogTrigger asChild>
  <Button>開啟</Button>
</DialogTrigger>

// ❌ 錯誤:手動觸發而未妥善處理焦點
<Button onClick={() => setOpen(true)}>開啟</Button>

鍵盤導航

// ✅ ShadCN 會自動處理:
// - ESC 關閉對話框
// - Tab 導航可聚焦元素
// - Enter/Space 啟用按鈕
// - 方向鍵導航選單

// ❌ 錯誤:沒有正當理由不要覆蓋預設鍵盤行為

螢幕閱讀器支援

// ✅ 正確:務必包含 DialogTitle(ARIA 必要)
<DialogHeader>
  <DialogTitle>刪除專案</DialogTitle>
  <DialogDescription>
    此動作無法復原。
  </DialogDescription>
</DialogHeader>

// ❌ 錯誤:不正確地使用視覺隱藏標題
<DialogTitle className="sr-only">刪除</DialogTitle>
// 僅在有清楚的視覺替代方案時才隱藏

5. 常用元件

元件使用情境關鍵 Props
Button所有可點擊動作variant, size, asChild
Dialog模態框、確認對話框open, onOpenChange
Sheet側邊面板、抽屜side, open, onOpenChange
Popover工具提示、選單open, onOpenChange
Form所有表單form(來自 useForm)
Input文字輸入type, placeholder
Select下拉選單value, onValueChange
Checkbox布林輸入checked, onCheckedChange
RadioGroup單一選擇value, onValueChange
Table資料表格table(來自 TanStack Table)
Card內容容器CardHeader, CardContent, CardFooter
Toast通知title, description, variant
Command指令面板onSelect
Tabs分頁導航value, onValueChange

6. TailwindCSS 最佳實踐

// ✅ 正確:使用 Tailwind 工具類別
<Button className="w-full mt-4">提交</Button>

// ✅ 正確:使用 cn() 輔助函數處理條件類別
import { cn } from "@/lib/utils"

<Button className={cn(
  "w-full",
  isLoading && "opacity-50 cursor-not-allowed"
)}>
  提交
</Button>

// ❌ 錯誤:使用內聯樣式
<Button style={{ width: '100%', marginTop: '16px' }}>提交</Button>

// ❌ 錯誤:為元件建立自訂 CSS 檔案
// styles.css
.my-button { width: 100%; }

7. 暗模式支援

// ✅ 正確:使用 Tailwind 暗模式類別
<div className="bg-white dark:bg-gray-900 text-black dark:text-white">
  內容
</div>

// ✅ ShadCN 元件內建暗模式
<Button variant="default">
  {/* 自動根據暗模式調整樣式 */}
</Button>

常見錯誤

❌ 遺漏 DialogTitle(無障礙違規)

// 錯誤
<DialogContent>
  <h2>設定</h2>
  <p>內容</p>
</DialogContent>

// 正確
<DialogContent>
  <DialogHeader>
    <DialogTitle>設定</DialogTitle>
  </DialogHeader>
  <p>內容</p>
</DialogContent>

❌ 未使用 Form 元件處理表單

// 錯誤 - 無驗證、使用者體驗差
<form>
  <input name="email" />
  <button type="submit">提交</button>
</form>

// 正確 - 有驗證、錯誤訊息、無障礙
<Form {...form}>
  <form onSubmit={form.handleSubmit(onSubmit)}>
    <FormField name="email" ... />
  </form>
</Form>

❌ 硬編碼顏色而非使用變體

// 錯誤
<Button className="bg-red-500 hover:bg-red-600">刪除</Button>

// 正確
<Button variant="destructive">刪除</Button>

❌ 未對觸發器使用 asChild

// 錯誤 - 建立不必要的巢狀按鈕
<DialogTrigger>
  <Button>開啟</Button>
</DialogTrigger>
// 渲染:<button><button>開啟</button></button>(無效 HTML)

// 正確 - 將 props 合併到單一按鈕
<DialogTrigger asChild>
  <Button>開啟</Button>
</DialogTrigger>
// 渲染:<button>開啟</button>

測試 ShadCN 元件

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Dialog, DialogTrigger, DialogContent } from '@/components/ui/dialog'

describe('Dialog', () => {
  it('應在點擊觸發器時開啟', async () => {
    const user = userEvent.setup()

    render(
      <Dialog>
        <DialogTrigger asChild>
          <button>開啟</button>
        </DialogTrigger>
        <DialogContent>
          <div>對話框內容</div>
        </DialogContent>
      </Dialog>
    )

    // 對話框內容最初不應可見
    expect(screen.queryByText('對話框內容')).not.toBeInTheDocument()

    // 點擊觸發器
    await user.click(screen.getByText('開啟'))

    // 對話框內容現在應可見
    expect(screen.getByText('對話框內容')).toBeInTheDocument()
  })

  it('應在按下 ESC 鍵時關閉', async () => {
    const user = userEvent.setup()

    render(
      <Dialog defaultOpen>
        <DialogContent>對話框內容</DialogContent>
      </Dialog>
    )

    expect(screen.getByText('對話框內容')).toBeInTheDocument()

    await user.keyboard('{Escape}')

    expect(screen.queryByText('對話框內容')).not.toBeInTheDocument()
  })
})

資源

2025 年 11 月備註

截至 2025 年 11 月,ShadCN UI 是 React 元件庫的行業標準。所有新的 Quetrex 應用程式必須使用 ShadCN UI,以確保一致性、無障礙性與可維護性。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能