Communitygithub.com

ComeOnOliver/skillshub

指導如何根據伺服器/用戶端元件模式以及現有元件結構,來建立 Next.js 16+ 元件的技能。

skillshub 是什麼?

此 AI 技能提供了一套全面的指南,用於使用 Next.js 16+ 的 App Router 和 React 伺服器元件(Server Components)來建立前端元件。它詳細說明了伺服器元件(靜態內容、資料擷取、SEO)與用戶端元件(互動性、Hook、瀏覽器 API)之間的區別,並提供了每種元件的明確模式與範例。該技能還涵蓋了特定的元件模式,如受保護路由、載入指示器、表單處理和 Toast 通知,並整合了 Tailwind CSS 的實用程式類別、深色模式支援和響應式設計原則。此外,它強調了 WCAG 2.1 AA 標準的無障礙功能、TypeScript 嚴格模式和 ESLint/Prettier 程式碼品質工具。參考了既有的元件和頁面範例,以及規範文件。適用於 Claude Code、Cursor 等 AI 代理工具,協助開發者遵循最佳實務來建立一致、可維護且無障礙的 Next.js 前端。

相容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/asmayaseen/frontend-component

在你喜歡的 AI 中提問

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

說明文件

前端元件技能

目的:指導如何根據伺服器/用戶端元件模式以及現有元件結構,建立 Next.js 元件。

概覽

Next.js 16+ 預設使用 App Router 與伺服器元件(Server Components)。僅在需要互動性時(如 Hook、事件處理器、瀏覽器 API)才使用用戶端元件(Client Components)。

伺服器 vs 用戶端元件

伺服器元件(預設)

使用時機:

  • 頁面與佈局
  • 靜態內容
  • 從 API 取得資料(盡可能)
  • SEO 最佳化內容

模式:

// 不需要 "use client" 指示詞
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "頁面標題",
};

export default function PageComponent() {
  return <div>靜態內容</div>;
}

範例:frontend/app/layout.tsx、frontend/app/page.tsx

用戶端元件(需要時使用)

使用時機:

  • 互動元素(按鈕、表單、輸入框)
  • 事件處理器(onClick、onChange 等)
  • React Hook(useState、useEffect、useRouter 等)
  • 瀏覽器 API(localStorage、window、document 等)
  • 即時更新
  • 拖放功能

模式:

"use client"; // 必須是第一行

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";

interface ComponentProps {
  prop1: string;
  prop2?: number;
}

export default function ComponentName({ prop1, prop2 }: ComponentProps) {
  const router = useRouter();
  const [state, setState] = useState("");

  useEffect(() => {
    // 副作用
  }, []);

  return <div>{/* 元件 JSX */}</div>;
}

範例:frontend/components/ProtectedRoute.tsx、frontend/app/signup/page.tsx

元件結構模板

"use client"; // 僅限用戶端元件

/**
 * 元件名稱
 *
 * 簡短說明此元件的功能
 */

import { useState, useEffect } from "react";
import { ComponentType } from "@/types";
import { cn } from "@/lib/utils";

interface ComponentProps {
  prop1: string;
  prop2?: number;
  className?: string;
}

export default function ComponentName({ prop1, prop2, className }: ComponentProps) {
  // 狀態
  const [state, setState] = useState("");

  // 副作用
  useEffect(() => {
    // 副作用邏輯
  }, []);

  // 處理器
  const handleClick = () => {
    // 處理器邏輯
  };

  // 渲染
  return (
    <div className={cn("base-classes", className)}>
      {/* 元件內容 */}
    </div>
  );
}

特定元件模式

1. ProtectedRoute 模式

來源:frontend/components/ProtectedRoute.tsx

"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { isAuthenticated } from "@/lib/auth";
import LoadingSpinner from "./LoadingSpinner";

interface ProtectedRouteProps {
  children: React.ReactNode;
}

export default function ProtectedRoute({ children }: ProtectedRouteProps) {
  const router = useRouter();
  const [isAuthorized, setIsAuthorized] = useState(false);
  const [isChecking, setIsChecking] = useState(true);

  useEffect(() => {
    async function checkAuth() {
      try {
        const authenticated = await isAuthenticated();

        if (!authenticated) {
          const currentPath = window.location.pathname;
          if (currentPath !== "/signin") {
            sessionStorage.setItem("redirectAfterLogin", currentPath);
          }
          router.push("/signin");
        } else {
          setIsAuthorized(true);
        }
      } catch (error) {
        console.error("身份驗證檢查失敗:", error);
        router.push("/signin");
      } finally {
        setIsChecking(false);
      }
    }

    checkAuth();
  }, [router]);

  if (isChecking) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <LoadingSpinner size="large" />
      </div>
    );
  }

  if (!isAuthorized) {
    return null;
  }

  return <>{children}</>;
}

模式:

  • 在元件掛載時檢查身份驗證
  • 檢查期間顯示載入指示器
  • 將預期目的地儲存在 sessionStorage 中
  • 若未通過驗證,重新導向至 /signin
  • 僅在授權通過時渲染 children

2. LoadingSpinner 模式

來源:frontend/components/LoadingSpinner.tsx

interface LoadingSpinnerProps {
  size?: "small" | "medium" | "large";
  color?: string;
  label?: string;
}

export default function LoadingSpinner({
  size = "medium",
  color = "blue",
  label = "載入中...",
}: LoadingSpinnerProps) {
  const sizeClasses = {
    small: "w-4 h-4 border-2",
    medium: "w-8 h-8 border-3",
    large: "w-12 h-12 border-4",
  };

  const colorClasses = {
    blue: "border-blue-600 border-t-transparent",
    gray: "border-gray-600 border-t-transparent",
    white: "border-white border-t-transparent",
  };

  const spinnerClass = `${sizeClasses[size]} ${
    colorClasses[color as keyof typeof colorClasses] || colorClasses.blue
  } rounded-full animate-spin`;

  return (
    <div
      className="flex items-center justify-center"
      role="status"
      aria-label={label}
      aria-live="polite"
    >
      <div className={spinnerClass}></div>
      <span className="sr-only">{label}</span>
    </div>
  );
}

模式:

  • 多種尺寸(small、medium、large)
  • 多種顏色(blue、gray、white)
  • 無障礙標籤(role="status"、aria-label、aria-live)
  • 使用 sr-only 類別的螢幕閱讀器文字

3. 表單處理模式

來源:frontend/app/signup/page.tsx

"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api";
import { isValidEmail, getPasswordStrength } from "@/lib/utils";

export default function SignupPage() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(false);
  const [apiError, setApiError] = useState("");

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = "名稱為必填";
    }

    if (!formData.email.trim()) {
      newErrors.email = "電子郵件為必填";
    } else if (!isValidEmail(formData.email)) {
      newErrors.email = "請輸入有效的電子郵件地址";
    }

    // 更多驗證...

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setApiError("");

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      const response = await api.signup(formData);
      if (response.success) {
        router.push("/dashboard");
      } else {
        setApiError(response.message || "註冊失敗");
      }
    } catch (error: any) {
      setApiError(error.message || "發生錯誤");
    } finally {
      setIsLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    // 使用者開始輸入時清除該欄位的錯誤
    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: "" }));
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* 表單欄位 */}
    </form>
  );
}

模式:

  • 分別為表單資料、錯誤、載入狀態和 API 錯誤建立獨立狀態
  • 回傳布林值的驗證函數
  • 輸入變更時清除錯誤
  • 提交期間的載入狀態
  • 用 try-catch 進行錯誤處理
  • 成功時重新導向

4. ToastNotification 模式

來源:frontend/components/ToastNotification.tsx

"use client";

import { useEffect, useState } from "react";
import { ToastMessage, ToastType } from "@/types";

export function useToast() {
  const [toasts, setToasts] = useState<ToastMessage[]>([]);

  const showToast = (type: ToastType, message: string, duration?: number) => {
    const id = `toast-${Date.now()}-${Math.random()}`;
    const newToast: ToastMessage = {
      id,
      type,
      message,
      duration,
    };
    setToasts((prev) => [...prev, newToast]);
  };

  const dismissToast = (id: string) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  };

  return {
    toasts,
    showToast,
    dismissToast,
    success: (message: string, duration?: number) => showToast("success", message, duration),
    error: (message: string, duration?: number) => showToast("error", message, duration),
    // ...
  };
}

模式:

  • 用於 Toast 管理的自訂 Hook
  • 可設定持續時間的自動關閉功能
  • 支援疊加多條 Toast
  • 輔助方法(success、error、warning、info)

Tailwind CSS 模式

1. 僅使用實用程式類別

<div className="flex items-center justify-center gap-4 p-6 bg-white rounded-lg shadow-md">

模式:使用 Tailwind 實用程式類別,不要使用內聯樣式

2. 使用 cn() 實用程式的條件式類別

import { cn } from "@/lib/utils";

<div className={cn(
  "base-classes",
  condition && "conditional-classes",
  className // 允許透過 prop 覆寫
)}>

模式:使用來自 @/lib/utils 的 cn() 來處理條件式類別

3. 深色模式支援

<div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">

模式:使用 dark: 前綴來設定深色模式樣式

4. 響應式設計

<div className="w-full sm:w-1/2 md:w-1/3 lg:w-1/4">

模式:使用斷點前綴(sm:、md:、lg:、xl:)

無障礙模式(符合 WCAG 2.1 AA)

1. ARIA 標籤

<button aria-label="關閉對話框">×</button>
<div role="status" aria-live="polite" aria-label="載入中...">

模式:始終為純圖示按鈕提供 aria-label

2. 語意化 HTML

<nav>
  <ul>
    <li><a href="/">首頁</a></li>
  </ul>
</nav>

模式:使用語意化 HTML 元素(nav、main、section、article 等)

3. 鍵盤導航

<button
  onClick={handleClick}
  onKeyDown={(e) => {
    if (e.key === "Enter" || e.key === " ") {
      handleClick();
    }
  }}
>

模式:確保所有互動元素都支援鍵盤操作

4. 螢幕閱讀器文字

<span className="sr-only">正在載入內容</span>

模式:使用 sr-only 類別來提供僅供螢幕閱讀器讀取的文字

5. 焦點管理

<input
  autoFocus
  className="focus:outline-none focus:ring-2 focus:ring-blue-500"
/>

模式:始終提供可見的焦點指示器

檔案命名慣例

  • 頁面:kebab-case(例如 signup.tsx、signin.tsx)
  • 元件:PascalCase(例如 TaskList.tsx、TaskItem.tsx)
  • 佈局:layout.tsx
  • 錯誤頁面:error.tsx、not-found.tsx

憲法要求

  • FR-033:Next.js 16+ App Router 結構 ✅
  • FR-034:預設伺服器元件,需要時使用用戶端元件 ✅
  • FR-035:錯誤邊界 ✅
  • FR-036:符合 WCAG 2.1 AA ✅
  • FR-037:TypeScript 嚴格模式 ✅
  • FR-038:Prettier 格式化 ✅
  • FR-039:ESLint 規則 ✅

參考資料

  • 規範文件:specs/002-frontend-todo-app/spec.md - 元件規格
  • 現有元件:frontend/components/*.tsx - 元件範例
  • 現有頁面:frontend/app/*.tsx - 頁面範例

進階元件模式

1. 拖放模式(第 7 階段 - T065)

函式庫:@dnd-kit/core

"use client";

import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";

export default function SortableTaskList({ tasks, onReorder }: Props) {
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over && active.id !== over.id) {
      onReorder(active.id, over.id);
    }
  };

  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
      <SortableContext items={tasks.map(t => t.id)} strategy={verticalListSortingStrategy}>
        {tasks.map(task => (
          <SortableTaskItem key={task.id} task={task} />
        ))}
      </SortableContext>
    </DndContext>
  );
}

模式:使用 @dnd-kit/core 進行拖放,在拖曳結束時處理重新排序

2. 復原/重做模式(第 7 階段 - T066)

"use client";

import { useReducer } from "react";

interface HistoryState<T> {
  past: T[];
  present: T;
  future: T[];
}

function historyReducer<T>(state: HistoryState<T>, action: { type: string; newPresent?: T }): HistoryState<T> {
  const { past, present, future } = state;

  switch (action.type) {
    case "UNDO":
      if (past.length === 0) return state;
      return {
        past: past.slice(0, past.length - 1),
        present: past[past.length - 1],
        future: [present, ...future],
      };
    case "REDO":
      if (future.length === 0) return state;
      return {
        past: [...past, present],
        present: future[0],
        future: future.slice(1),
      };
    case "SET":
      if (action.newPresent === present) return state;
      return {
        past: [...past, present],
        present: action.newPresent!,
        future: [],
      };
    default:
      return state;
  }
}

export function useHistory<T>(initialPresent: T) {
  const [state, dispatch] = useReducer(historyReducer, {
    past: [],
    present: initialPresent,
    future: [],
  });

  const undo = () => dispatch({ type: "UNDO" });
  const redo = () => dispatch({ type: "REDO" });
  const set = (newPresent: T) => dispatch({ type: "SET", newPresent });

  return { state: state.present, undo, redo, set, canUndo: state.past.length > 0, canRedo: state.future.length > 0 };
}

模式:使用 useReducer 管理歷史狀態(past、present、future),透過「UNDO」、「REDO」和「SET」動作來支援復原和重做

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

相關技能