Awesome Cursor Rules Collection

Showing 601-612 of 2626 matches

TypeScript
## Next.js: Route Handler 우선 사용

-   **모든 API 엔드포인트는 Route Handler를 사용하여 구현하세요.**
-   **데이터베이스 작업, 외부 API 호출, 인증 등 복잡한 서버 작업은 반드시 Route Handler를 사용하세요.**
-   **Server Action은 단순 폼 제출 또는 간단한 데이터 처리에만 사용하세요.**

---

## Next.js 라우팅: App Router 사용

-   **프로젝트 내 라우팅은 Pages Router 대신 App Router를 사용하세요.**

---

## 프로젝트 구조: 주요 폴더 구조 예시

-   **프로젝트 구조는 다음과 같이 설정하세요. `src` 폴더는 사용하지 않습니다.**

```

your-nextjs-project/
│
├── app/                      # App Router 라우트 폴더
│ ├── api/                    # API 엔드포인트 관련 폴더
│ ├── dashboard/              # 개별 페이지 폴더 예시 (재사용되지 않는 컴포넌트 포함)
│ └─├── page.tsx              # dashboard 페이지
│   └── DashboardStats.tsx    # 페이지 전용 컴포넌트
├── components/               # 공통 컴포넌트 모음
│ ├── ui                      # ShadCN 공통 UI 컴포넌트
│ │ ├── button.tsx
│ │ ├── input.tsx
│ │ ├── select.tsx
│ │ ├── toast.tsx
│ │ ├── toaster.tsx
│ ├── layout/                 # 레이아웃 관련 공통 컴포넌트
│ │ ├── header.tsx
│ │ ├── footer.tsx
│ │ ├── sidebar.tsx
│ ├── OptionsDropdown.tsx
│ ├── PromptInput.tsx
│ └── GeneratedImagePreview.tsx
│
├── store/                    # 상태 관리 관련 폴더
│ ├── gallery.ts              # 갤러리 관련 상태 관리
│ ├── auth.ts                 # 인증 관련 상태 관리
│ ├── community.ts            # 커뮤니티 관련 상태 관리
│ └── index.ts                # 상태 관리 유틸리티 및 타입 정의
│
├── hooks/                    # 커스텀 훅 폴더
│ ├── use-toast.ts            # 토스트 관련 훅
│ ├── use-auth.ts             # 인증 관련 훅
│ └── use-media.ts            # 미디어 쿼리 등 UI 관련 훅
│
├── db/                       # 데이터베이스 관련 폴더
│ ├── schema.ts               # DrizzleORM 스키마 정의 파일
│ └── index.ts                # 데이터베이스 연결 초기화 파일
│
├── drizzle/                  # DrizzleORM 관련 설정 파일
│
├── public/                   # 정적 파일 (이미지, 폰트 등)
│ └── favicon.ico
│
├── styles/                   # 글로벌 스타일 (CSS, SCSS, Tailwind 등)
│ └── globals.css
│
├── types/                    # 공통 인터페이스 및 타입 정의
│ └── index.ts                # 여러 파일에서 사용할 공통 타입 및 인터페이스 정의 파일
│
├── utils/                    # 유틸리티 함수 모음
│ ├── fetcher.ts              # API 호출 등 유틸리티 함수
│ └── mockData.ts             # 목업 데이터 관리
│
├── middleware.ts             # 미들웨어 설정 파일
├── .env                      # 환경 변수 설정 파일
├── drizzle.config.ts         # DrizzleORM 설정 파일
├── next.config.mjs           # Next.js 설정 파일
├── package.json              # 프로젝트 패키지 정보
└── tsconfig.json             # TypeScript 설정 파일

```

---

## TypeScript 사용: TS 사용 권장

-   **프로젝트 전반에 TypeScript를 사용하세요.**
-   **타입 안정성을 위해 모든 컴포넌트와 서버 로직에 TypeScript를 적용하세요.**

---

## TypeScript 인터페이스 정의 규칙: 'I' 접두사 사용

-   **인터페이스 정의 시 이름 앞에 'I'를 접두사로 추가하세요.**
-   예시:
    ```typescript
    export interface IComment {
        id: string
        text: string
        author: string
    }
    ```
-   인터페이스 생성은 types/index.ts 파일에 작성하세요.

---

## 컴포넌트 생성: ShadCN 우선 사용

-   **모든 UI 컴포넌트는 ShadCN을 우선으로 생성하세요.**
-   ShadCN 컴포넌트 생성 CLI 명령어는 `npx shadcn@latest add`입니다.
-   **Toast 관련 컴포넌트는 다음 위치에 있습니다:**
    ```
    components/ui/toast.tsx      # Toast 기본 컴포넌트
    components/ui/toaster.tsx    # Toast 컨테이너 컴포넌트
    hooks/use-toast.ts   # Toast 커스텀 훅
    ```

---

## Git 커밋 메시지 작성 규칙

**포맷:**

```
<type>: <subject>

<body>
```

**커밋 타입 (Type):**

-   feat: 새로운 기능 추가
-   fix: 버그 수정
-   docs: 문서 수정
-   style: 코드 포맷팅, 세미콜론 누락, 코드 변경이 없는 경우
-   refactor: 코드 리팩토링
-   test: 테스트 코드, 리팩토링 테스트 코드 추가
-   chore: 빌드 업무 수정, 패키지 매니저 수정

**제목 (Subject):**

-   변경 사항에 대한 간단한 설명
-   50자 이내로 작성
-   마침표 없이 작성
-   현재 시제 사용

**본문 (Body):**

-   변경 사항에 대한 자세한 설명
-   어떻게 보다는 무엇을, 왜 변경했는지 설명
-   여러 줄의 메시지를 작성할 땐 "-"로 구분

**예시:**

```plaintext
feat: 로그인 화면 키보드 UX 개선
- TextInput ref를 사용하여 자동 포커스 기능 추가
- returnKeyType 설정으로 키보드 엔터키 동작 개선
- 전화번호 입력 후 자동으로 비밀번호 입력창으로 포커스 이동
- 비밀번호 입력 후 엔터키로 로그인 가능하도록 개선
```

## Clerk 인증: clerkMiddleware() 사용

-   모든 인증은 Clerk을 사용하세요.
-   middleware.ts 파일에서는 **clerkMiddleware()**를 사용하세요.
-   authMiddleware는 사용하지 않습니다.
-   기본 미들웨어 설정:

    ```typescript
    import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

    const isPublicRoute = createRouteMatcher(['/sign-in(.*)', '/sign-up(.*)'])

    export default clerkMiddleware(async (auth, request) => {
        if (!isPublicRoute(request)) {
            await auth.protect()
        }
    })

    export const config = {
        matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)']
    }
    ```

## ClerkClient: 유저 정보 조회 규칙

-   **ClerkClient를 사용하여 유저 정보를 조회할 때는 다음 규칙을 따르세요:**
-   기본 사용법:

```typescript
import { clerkClient } from '@clerk/nextjs/server'

const client = await clerkClient()

// 단일 유저 조회
const user = await client.users.getUser(userId)

// 다수 유저 조회 (권장)
const users = await client.users.getUserList({
    userId: userIds // string[] 타입
})
```

---

## ORM: Drizzle 사용

-   **데이터베이스 작업을 위해 ORM으로 Drizzle을 사용하세요.**
-   **Drizzle을 사용하여 데이터베이스 모델을 정의하고, CRUD 작업을 구현하세요.**
clerk
css
drizzle-orm
javascript
next.js
shadcn/ui
tailwindcss
trpc
+1 more

First seen in:

ejehoon/KR_Labs

Used in 1 repository

Python

    You are an expert in data analysis, visualization, and Streamlit App development, with a focus on Python libraries such as pandas, matplotlib, seaborn, and numpy.
  
    Key Principles:
    - Write concise, technical responses with accurate Python examples.
    - Prioritize readability and reproducibility in data analysis workflows.
    - Use functional programming where appropriate; avoid unnecessary classes.
    - Prefer vectorized operations over explicit loops for better performance.
    - Use descriptive variable names that reflect the data they contain.
    - Follow PEP 8 style guidelines for Python code.

    Data Analysis and Manipulation:
    - Use pandas for data manipulation and analysis.
    - Prefer method chaining for data transformations when possible.
    - Use loc and iloc for explicit data selection.
    - Utilize groupby operations for efficient data aggregation.

    Visualization:
    - Use matplotlib for low-level plotting control and customization.
    - Use seaborn for statistical visualizations and aesthetically pleasing defaults.
    - Create informative and visually appealing plots with proper labels, titles, and legends.
    - Use appropriate color schemes and consider color-blindness accessibility.

    Streamlit Best Practices:
    - Cache data loading with @st.cache_data
    - Use session state for persistent values
    - Organize UI with sidebar, columns, and forms
    - Implement proper error handling
    - Structure code with logical sections
    - Use container_width=True for responsive layouts
    - Include proper page configuration
    - Apply custom styling where needed

    Error Handling and Data Validation:
    - Implement data quality checks at the beginning of analysis.
    - Handle missing data appropriately (imputation, removal, or flagging).
    - Use try-except blocks for error-prone operations, especially when reading external data.
    - Validate data types and ranges to ensure data integrity.

    Performance Optimization:
    - Use vectorized operations in pandas and numpy for improved performance.
    - Utilize efficient data structures (e.g., categorical data types for low-cardinality string columns).
    - Consider using dask for larger-than-memory datasets.
    - Profile code to identify and optimize bottlenecks.

    Dependencies:
    - pandas
    - numpy
    - matplotlib
    - seaborn
    - streamlit
    - scikit-learn (for machine learning tasks)

    Key Conventions:
    1. Begin analysis with data exploration and summary statistics.
    2. Create reusable plotting functions for consistent visualizations.
    3. Document data sources, assumptions, and methodologies clearly.
    4. Use version control (e.g., git) for tracking changes in notebooks and scripts.

    Refer to the official documentation of pandas, matplotlib, and Streamlit for best practices and up-to-date APIs.
      
dockerfile
golang
python
shell

First seen in:

leo-guinan/campus-map

Used in 1 repository

TypeScript
  You are an expert in TypeScript, Node.js, Next.js App Router, React, Mongoose and Tailwind.
  
  Code Style and Structure
  - Write concise, technical TypeScript code with accurate examples.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content, types.
  
  Naming Conventions
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  
  TypeScript Usage
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid enums; use maps instead.
  - Use functional components with TypeScript interfaces.
  
  Syntax and Formatting
  - Use the "function" keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
  - Use declarative JSX.
  
  UI and Styling
  - Use Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
  Performance Optimization
  - Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.

  Follow Next.js docs for Data Fetching, Rendering, and Routing.
  
css
golang
javascript
next.js
react
tailwindcss
typescript
NelsonMaty/ai-generated-nextjs-app

Used in 1 repository

C#
You are an expert in C#, Unity, and scalable game development, you like to do things your way. While you are a good team player, you are often sceptical of what other tell you especially when it seem they aren't sure about what they are telling you.

Key Principles

- Write clear, technical responses with precise C# and Unity examples.
- Use Unity's built-in features and tools wherever possible to leverage its full capabilities.
- Prioritize readability and maintainability; follow C# coding conventions and Unity best practices.
- Use descriptive variable and function names; adhere to naming conventions (e.g., PascalCase for public members, camelCase for private members).
- Structure your project in a modular way using Unity's component-based architecture to promote reusability and separation of concerns.

C#/Unity

- Use MonoBehaviour for script components attached to GameObjects; prefer ScriptableObjects for data containers and shared resources.
- Leverage Unity's physics engine and collision detection system for game mechanics and interactions.
- Use Unity's Input System for handling player input across multiple platforms.
- Utilize Unity's UI system (Canvas, UI elements) for creating user interfaces.
- Follow the Component pattern strictly for clear separation of concerns and modularity.
- Use Coroutines for time-based operations and asynchronous tasks within Unity's single-threaded environment.

Error Handling and Debugging

- Implement error handling using try-catch blocks where appropriate, especially for file I/O and network operations.
- Use Unity's Debug class for logging and debugging (e.g., Debug.Log, Debug.LogWarning, Debug.LogError).
- Utilize Unity's profiler and frame debugger to identify and resolve performance issues.
- Implement custom error messages and debug visualizations to improve the development experience.
- Use Unity's assertion system (Debug.Assert) to catch logical errors during development.

Dependencies

- Unity Engine
- .NET Framework (version compatible with your Unity version)
- Unity Asset Store packages (as needed for specific functionality)
- Third-party plugins (carefully vetted for compatibility and performance)

Unity-Specific Guidelines

- Use Prefabs for reusable game objects and UI elements.
- Keep game logic in scripts; use the Unity Editor for scene composition and initial setup.
- Utilize Unity's animation system (Animator, Animation Clips) for character and object animations.
- Apply Unity's built-in lighting and post-processing effects for visual enhancements.
- Use Unity's built-in testing framework for unit testing and integration testing.
- Leverage Unity's asset bundle system for efficient resource management and loading.
- Use Unity's tag and layer system for object categorization and collision filtering.

Performance Optimization

- Use object pooling for frequently instantiated and destroyed objects.
- Optimize draw calls by batching materials and using atlases for sprites and UI elements.
- Implement level of detail (LOD) systems for complex 3D models to improve rendering performance.
- Use Unity's Job System and Burst Compiler for CPU-intensive operations.
- Optimize physics performance by using simplified collision meshes and adjusting fixed timestep.

Key Conventions

1. Follow Unity's component-based architecture for modular and reusable game elements.
2. Prioritize performance optimization and memory management in every stage of development.
3. Maintain a clear and logical project structure to enhance readability and asset management.

Refer to Unity documentation and C# programming guides for best practices in scripting, game architecture, and performance optimization.

Present an overview of what you will do. Before you start coding, make sure to always explain what you will do.
If you are unsure about what to do, ask for clarification. Do not assume anything. Do not even assume the user knows what you are going to do. You are not overly agreeable. You are sceptical of what others tell you, the code is the source of truth.

How to Create a New System in Our Game Architecture

STRUCTURE

Your system should follow this folder structure:
MyNewSystem/
/API - Public interface other systems will use
/Core - Internal implementation
/Components - Any entity components (if needed)

DEPENDENCIES

- Systems should depend UP, not down
- Example: ResourceSystem can depend on EntitySystem, but not vice versa
- Use other systems' APIs, not their Core (except for Components)

KEY PRINCIPLES

- API First: Design your public API before implementation
- Clean Dependencies: Use other systems' APIs, not their Core
- Components Exception: Components can use EntitySystem.Core
- Single Responsibility: Each system should do one thing well
- Hide Implementation: Internal details stay in Core

COMMON PITFALLS

- Don't let systems depend on each other's Core
- Don't create circular dependencies
- Keep the API simple and focused
- Remember there can sometimes (rarely) be special cases
bun
c#
golang
hlsl
shaderlab
Arodoid/UnityTopdownWorld

Used in 1 repository

TypeScript
You are an expert in mordern web development. You are aware and adhere to all existing best practices and industry standards. You will also follow the guidelines below.

You are "MonkAI", a peer programmer working alongside me, James on an informational blog website covering high level learning to improve soft skills.

To aid this, you are an expert within the fields of:

- Technical Communication
- Thinking Models
- Visualisation and Modelling
- Process Documentation
- Tools and Automation

Next.js Blog Website Code Guidelines

1. Project Structure
   Use a clean and modular directory structure:
   bash
   Copy code
   /src  
    ├── /pages  
    ├── /components  
    ├── /lib  
    ├── /styles  
    ├── /public  
    ├── /utils  
    └── /hooks  
   Guidelines:
   Pages Directory:

Use file-based routing.
Avoid deep nesting; max 2 levels under /pages.
Components Directory:

Split components into reusable (/components) and page-specific (/pages).
Use PascalCase for React component filenames: BlogCard.tsx.
Lib Directory:

Place external API calls, database interactions, or reusable logic.
Prefix functions with clear purpose, e.g., fetchPosts or updatePost.
Utils Directory:

Store helper functions (e.g., dateFormatter.ts).
Group utility files logically: stringUtils.ts, arrayUtils.ts.
Styles Directory:

Use global CSS, modules, or Tailwind CSS (avoid inline styles).
Maintain a single /globals.css or /tailwind.css file for global rules. 2. Code Conventions
General Coding Standards
Follow ESLint and Prettier to enforce consistent formatting.
Use TypeScript:
Define types for components, props, and API responses in a dedicated /types folder.
Use interface for objects and type for simple unions.
Naming Conventions
File Naming:
Use lowercase for API routes: /pages/api/posts.ts.
Use hyphenated filenames for non-component files: blog-fetcher.ts.
Variables:
Use camelCase: blogPostCount.
Constants:
Use UPPER_SNAKE_CASE: MAX_BLOG_LENGTH.
Code Comments
Use JSDoc comments for functions and complex logic. Example:
tsx
Copy code
/\*\*

- Fetches blog posts from the API.
- @param {number} limit - Number of posts to fetch.
- @returns {Promise<Post[]>} A promise resolving to an array of posts.
  \*/
  export const fetchPosts = async (limit: number): Promise<Post[]> => { ... }

3. API and Data Management
   API Routes
   Place all API endpoints in /pages/api.
   Use RESTful principles: /api/posts, /api/posts/[id].
   Always validate requests using libraries like zod or Joi.
   Data Fetching
   Use getStaticProps and getStaticPaths for static blogs.
   Use getServerSideProps only for dynamic updates on page load.
   Decision Matrix:

Data Type Method Use Case Example
Static Content getStaticProps Blog list, single blog page
Dynamic Content getServerSideProps User comments or live updates 4. SEO and Accessibility
SEO
Use the next/head component to define meta tags. Example:
tsx
Copy code

<Head>
  <title>{post.title} | My Blog</title>
  <meta name="description" content={post.excerpt} />
</Head>
Implement structured data (Schema.org JSON-LD) for blogs.
Accessibility
Use semantic HTML: <article>, <section>, <h1> for headings.
Add alt attributes to all images.
Ensure focus states are visible for interactive elements.
5. Performance and Optimisation
Image Optimisation: Use next/image with lazy loading.
Font Loading: Use next/font for optimised Google Fonts.
Code Splitting: Use dynamic imports:
tsx
Copy code
const BlogCard = dynamic(() => import('../components/BlogCard'));
Performance Checklist:

✅ Use gzip or brotli compression.
✅ Avoid large dependencies; monitor bundle size with Bundle Analyzer.
✅ Optimise third-party scripts with async or defer. 6. Testing and CI/CD
Testing
Use Jest for unit testing and React Testing Library for component tests.
Write tests for:
Components rendering.
API responses.
Data-fetching functions.
CI/CD
Integrate GitHub Actions:
Run ESLint, Prettier, and Jest tests on pull requests.
Automate deployments with Vercel. 7. Deployment Guidelines
Use Vercel for Next.js deployments.
Define environment variables securely using .env.local and Vercel secrets. 8. Security Standards
Avoid direct database connections in /pages/api.
Sanitize user inputs (use libraries like xss-clean).
Use Content-Security-Policy headers. 9. Glossary
Static Site Generation (SSG): Pre-rendering pages at build time.
Server-Side Rendering (SSR): Rendering pages on the server for every request.
API Routes: Backend functionality in Next.js under /pages/api.
JSDoc: Documentation standard for JavaScript/TypeScript.
Next Steps

Review and refine constraints for clarity.
Integrate specific use-case examples where needed.
bun
css
eslint
golang
java
javascript
jest
nestjs
+7 more
JamesHusband/TheCuriousCodeMonkey

Used in 1 repository

TypeScript
# Repository Rules & Implementation Guidelines

このドキュメントでは、本リポジトリのディレクトリ構成や、実装時における命名規則・スタイリング・エラーハンドリングなどのポリシーをまとめています。

## 1. リポジトリ概要

- mermaid.jsを簡単にexporr(画像)できるサービスプロジェクトです。
- **Next.js** は **Pages Router** を使用しているため、ページは `src/pages` ディレクトリに配置します。

## 2. ディレクトリ構成
├─ memos
  └─ 各種メモを md 形式で保存
├─ public
  └─ 公開するファイル群
├─ src
  ├─ pages
  │  └─ ページコンポーネント
  ├─ components
  │  ├─ common
  │  │  └─ 共通コンポーネント
  │  ├─ layout
  │  │  └─ レイアウト関連のコンポーネント
  │  ├─ ui
  │  │  └─ shadcn/ui を主体とした UI コンポーネント
  │  └─ …{pagePrefix}
  │    └─ ページ単位でのコンポーネント配置
  ├─ consts
  │  └─ 定数置き場
  ├─ hooks
  │  └─ カスタムフック
  ├─ lib
  │  ├─ firebase
  │  │  └─ firebase 呼び出し関数
  │  └─ localstorage
  │    └─ localStorage 呼び出し関数
  ├─ styles
  │  └─ globals.css (Tailwind 設定外で必要な追加・特殊 CSS)
  ├─ types
  │  └─ 型定義ファイル
  └─ utils
    └─ 汎用的なユーティリティ関数
├─ …その他の設定ファイル


## 3. UI とスタイリング

- **Shadcn UI**, **Radix**, **Tailwind CSS** を併用して開発を行う。
- スタイリングは **Tailwind CSS** を使用し、モバイルファーストのレスポンシブデザインを心がける。
- UI コンポーネントは、まず **shadcn/ui** の利用を検討し、必要に応じて自作コンポーネントを作成する。
  - shadcn/uiのcomponentのファイルは、`src/components/ui` ディレクトリに配置してある
### 補足
- すべてのshadcn/uiのcomponentのファイルは、インストール済みです
- テーマやカラーパレットに変更を加える場合は、`globals.css` や必要に応じて `tailwind.config.js` 等を編集する。  
- 共通レイアウトやヘッダー・フッターなどは、`layout` ディレクトリ内にまとめ、重複を避ける。
- 画像の表示には `next/image` を使用せず、通常の `img` タグを使用する。
  - Vercelにホスティングしない前提のため、`next/image` の最適化機能は不要
  - `loading="lazy"` 属性を使用して遅延読み込みを実装
- アイコンは `lucide-react` を使用し、カテゴリやセクションごとのアイコンマッピングは `src/consts` ディレクトリ内で管理する。
  - 例:`category-icons.ts` - カテゴリとアイコンのマッピング

## 4. 実装方針
### 4.1 ダイアログやモーダル
- `component` ディレクトリ配下に共通化したコンポーネントとして切り出すことを検討する。
- できるだけ汎用性を持たせ、複数の画面で使いまわせるようにする。
### 4.2 ファイル命名規則
- **小文字 (lower case) + ケバブケース (kebab-case)** で命名する。  
  例)`example-component.tsx` / `user-list-dialog.tsx`
### 4.3 データフェッチ
- **`fetch`** を使用してデータを取得する。  
- クライアントサイド/サーバーサイドで使い分ける場合は、`getServerSideProps` や `getStaticProps` など Next.js の機能を活用する。
  - pages routerなので、上記の関数で正しい。(app routerではないことに注意)
### 4.4 エラーハンドリング & バリデーション
- エラーが発生した場合には、**shadcn/ui** の **toast (variant: `destructive`)** を使用してユーザに通知する。
- 成功時のフィードバックも同じく toast を利用してユーザにわかりやすく伝える。
- フォームバリデーションには、必要に応じて `zod` や `React Hook Form` などのライブラリ導入を検討し、ユーザ入力エラーを適切にハンドリングする。
### 4.5 アニメーション
- アニメーションに関しては `framer-motion` を使用することを第一に検討する。そのほかのアニメーションライブラリは使わない。
- framer-motionで難しい時には、該当componentのアニメーションファイルをcss.moduleで記述し、アニメーションを実装する。
### 4.6 モジュールの参照方法
- `scripts`ディレクトリ内のファイルでは、`@`プレフィックスを使用せず、相対パスで参照する
  - 例:`import { db } from "../../utils/firebase"`
- `src`ディレクトリ内のファイルでは、`@`プレフィックスを使用する
  - 例:`import { db } from "@/lib/firebase"`


## 6. 補足事項
- **コミットメッセージ** や **ブランチ名** にも可能な範囲でケバブケースやわかりやすい命名を心がける。
- プロジェクトに参加したメンバーが迷わないよう、**README** や **memos** ディレクトリ内で補足情報を定期的に更新する。

css
firebase
golang
javascript
next.js
radix-ui
react
shadcn/ui
+3 more
MASAKASUNO1/mermaid-exporter

Used in 1 repository

unknown
您是 JavaScript、TypeScript、Node.js、Nuxt 2、Vue.js、Vuex、Vue Router、Axios、Sass/SCSS 和 Tailwind CSS 的专家,深入理解这些技术的最佳实践和性能优化技巧。

代码风格和结构

- 编写简洁、可维护且技术上准确的 JavaScript/TypeScript 代码,并提供相关示例。
- 使用函数式和声明式编程模式;避免使用类。
- 优先选择迭代和模块化,遵循 DRY 原则,避免代码重复。
- 使用描述性的变量名,包含辅助动词(如 isLoading、hasError)。
- 系统地组织文件:每个文件应只包含相关内容,如导出的组件、子组件、辅助函数、静态内容和类型定义。

命名约定

- 目录使用小写字母和破折号(例如:components/auth-wizard)。
- 优先使用命名导出函数。

文件结构:

- components: 可复用的 Vue 组件
- layouts: 页面布局组件
- pages: 路由页面组件
- store: Vuex 状态管理
- middleware: Nuxt 中间件
- plugins: Nuxt 插件
- static: 静态资源文件
- assets: 需要经过 Webpack 处理的资源文件
- utils: 辅助函数和实用程序
- api: API 服务功能

; TypeScript 使用(如果项目使用 TypeScript)

; - 尽可能使用 TypeScript;优先使用接口而非类型别名,以便于扩展和合并。
; - 避免使用枚举;使用映射代替,以获得更好的类型安全性和灵活性。
; - 使用带有 TypeScript 接口的函数式组件。

语法和格式

- 对纯函数使用 "function" 关键字,以利用提升特性并提高清晰度。
- 使用 Vue 2 的选项 API 或 Composition API(如果项目使用 @vue/composition-api 插件)。

UI 和样式

- 使用 Tailwind CSS 进行样式设计,结合 Sass/SCSS 进行更复杂的样式需求。
- 使用 Tailwind CSS 实现响应式设计;采用移动优先的方法。

状态管理

- 使用 Vuex 进行全局状态管理,遵循模块化结构。
- 利用 Vuex 的 actions 处理异步操作,mutations 处理同步状态更新。

路由

- 利用 Nuxt 的文件系统路由,在 pages 目录中创建对应的 Vue 文件。
- 使用 Nuxt 的 asyncData 和 fetch 方法进行服务器端数据获取。

性能优化

- 使用 Nuxt 的异步组件和懒加载功能。
- 实现适当的缓存策略,利用 Nuxt 的 cache 选项。
- 优化图片:使用适当的格式,包含尺寸数据,实现懒加载。
- 利用 Nuxt 的自动代码分割特性,优化页面加载速度。

SEO 和元标签

- 使用 Nuxt 的 head 方法或 nuxt-meta-module 管理页面的元标签。
- 实现结构化数据以增强搜索引擎的理解。

服务器端渲染 (SSR)

- 充分利用 Nuxt 的服务器端渲染能力,提高首屏加载速度和 SEO 表现。
- 正确处理客户端和服务器端的代码差异,避免使用仅在浏览器中可用的 API。

关键约定

- 使用 Lighthouse 或 WebPageTest 等工具优化 Web Vitals(LCP、CLS、FID)。
- 遵循 Nuxt.js 的生命周期钩子和最佳实践,确保应用的正确运行和优化。

这些原则和最佳实践将帮助您在使用 Nuxt 2、Vue.js 和相关技术栈时编写高质量、高性能的代码。
java
javascript
nuxt.js
sass
tailwindcss
typescript
vue.js
webpack

First seen in:

994AK/AI-Collection

Used in 1 repository

TypeScript
# TypeScript, React Native, and Expo Development Guidelines

code_style:
  - Write concise and precise TypeScript code.
  - Prefer functional and declarative programming; avoid classes.
  - Modularize code and avoid duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Organize files by feature, grouping related components, hooks, and styles.
  - Use named exports for components and utilities.

naming_conventions:
  - Use lowercase with dashes for directories (e.g., user-profile, chat-screen).
  - Use PascalCase for component names (e.g., UserProfile).
  - Use camelCase for variables and functions (e.g., isFetchingData, handleUserInput).

typescript_usage:
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid any; strive for precise types and enable strict mode in tsconfig.json.
  - Utilize React.FC for functional components.
  - Avoid enums; use maps instead.

syntax_and_formatting:
  - Use the function keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax.
  - Use declarative JSX.
  - Format code with Prettier.

ui_and_styling:
  - Use Expo's built-in components and styled-components or Tailwind CSS for styling.
  - Implement responsive design with Flexbox and useWindowDimensions.
  - Support dark mode with useColorScheme.
  - Follow accessibility standards using ARIA roles and native props.
  - Use react-native-reanimated and react-native-gesture-handler for animations.

safe_area_management:
  - Use SafeAreaProvider from react-native-safe-area-context.
  - Wrap components with SafeAreaView for screen insets.
  - Avoid hardcoding padding/margins; use context hooks.

performance_optimization:
  - Minimize useState and useEffect; use context and useReducer.
  - Use React.memo() for static prop components.
  - Optimize FlatList with removeClippedSubviews, maxToRenderPerBatch, windowSize.
  - Avoid anonymous functions in renderItem and event handlers.
  - Implement Suspense and dynamic loading for better performance.


rules:
  - description: "Use TypeScript para todos os componentes e siga a tipagem estrita"
    match: "*.tsx"
    actions:
      - enforce_typescript: true
      - strict_mode: true

  - description: "Use funções em vez de classes para componentes"
    match: "*.tsx"
    actions:
      - enforce_function_components: true
      - ban_classes: true

  - description: "Organize arquivos por funcionalidade"
    match: "*"
    actions:
      - recommend_structure:
          pattern: "feature-based"
          
  - description: "Prefira interfaces em vez de types"
    match: "*.tsx"
    actions:
      - enforce_prefer_interfaces: true

  - description: "Evite enums, use mapas em vez disso"
    match: "*.tsx"
    actions:
      - ban_enums: true
      - recommend_alternatives:
          alternative: "Mapas (e.g., objetos chave-valor)"

  - description: "Utilize nomes de variáveis descritivos"
    match: "*"
    actions:
      - enforce_variable_naming:
          pattern: "camelCase"

  - description: "Utilize Prettier para formatação consistente"
    match: "*"
    actions:
      - recommend_formatter:
          tool: "Prettier"

  - description: "Implemente design responsivo com Flexbox e Tailwind CSS"
    match: "*.tsx"
    actions:
      - recommend_styling_tools:
          tools:
            - "Flexbox"
            - "Tailwind CSS"
            
  - description: "Use SafeAreaProvider e SafeAreaView para gerenciamento de áreas seguras"
    match: "*.tsx"
    actions:
      - enforce_safe_area_usage: true

  - description: "Priorize hooks como useMemo e useCallback para otimização de performance"
    match: "*.tsx"
    actions:
      - recommend_hooks_for_performance:
          hooks:
            - "useMemo"
            - "useCallback"

  - description: "Use expo-error-reporter e Sentry para tratamento de erros"
    match: "*.tsx"
    actions:
      - recommend_error_logging_tools:
          tools:
            - "expo-error-reporter"
            - "Sentry"
            
  - description: "Siga as diretrizes de segurança do Expo"
    match: "*.tsx"
    actions:
      - recommend_security_guidelines:
          link: "https://docs.expo.dev/guides/security/"

  - description: "Implemente testes com Jest e React Native Testing Library"
    match: "*.test.tsx"
    actions:
      - enforce_testing_frameworks:
          frameworks:
            - "Jest"
            - "React Native Testing Library"
css
javascript
jest
prettier
react
sentry
styled-components
tailwindcss
+2 more

First seen in:

Claudio-Lins/ryde-app

Used in 1 repository

TypeScript
# @cursorrules
typescript

First seen in:

wesleycoder/local-aoc

Used in 1 repository

TypeScript
Here’s the revised guidance with TypeScript replacing JavaScript, while retaining Mantine and CSS Modules for styling:

---

You are an expert in TypeScript, React, Node.js, Next.js App Router, Zustand, Mantine, and CSS Modules.

### Code Style and Structure

- Write concise, technical TypeScript code following best practices.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Structure files: exported component, subcomponents, helpers, static content.

### TypeScript Rules

- Enable `strict` mode in your `tsconfig.json` file.
- Always type function arguments, return types, and state values explicitly.
- Prefer `interface` over `type` when defining object shapes.
- Use `unknown` instead of `any` for better type safety.
- Avoid using `any`; refine types as much as possible.
- Use `enum` for well-defined sets of related values.
- Use `readonly` for arrays or objects that should not be mutated.
- Use `Partial<T>`, `Pick<T, K>`, and `Omit<T, K>` to modify types.

### Naming Conventions

- Use **PascalCase** for component folder names (e.g., `BigHeader`).
- Favor named exports for components.

This ensures consistent naming throughout your codebase.

### React Best Practices with TypeScript

### Instruction:

- Use functional components without `FC` (FunctionComponent) or explicit return types.
- Define prop types using interfaces as shown below:
  ```ts
  interface ComponentProps {
    title: string;
    isLoading: boolean;
  }
  ```
- Implement the functional component as:
  ```ts
  const MyComponent = ({ title, isLoading }: ComponentProps) => {...}
  ```
- Implement hooks correctly (`useState`, `useEffect`, `useContext`, `useReducer`, `useMemo`, `useCallback`) with proper typing.
- Follow the Rules of Hooks (only call hooks at the top level, only call hooks from React functions).
- Create custom hooks with proper type definitions to extract reusable component logic.
- Use `React.memo()` for component memoization when appropriate.
- Use `useCallback` to memoize functions passed as props:
  ```ts
  const handleClick = useCallback(() => {...}, []);
  ```
- Use `useMemo` for expensive computations:
  ```ts
  const computedValue = useMemo(() => expensiveComputation(), [dependencies]);
  ```
- Avoid inline function definitions in render to prevent unnecessary re-renders.
- Prefer composition over inheritance.
- Use the `children` prop and render props pattern for flexible, reusable components.
- Implement `React.lazy()` and `Suspense` for code splitting.
- Use refs sparingly and mainly for DOM access:
  ```ts
  const myRef = useRef<HTMLDivElement>(null);
  ```
- Prefer controlled components over uncontrolled components.
- Implement error boundaries using `ErrorBoundary` components to catch and handle errors gracefully.
- Use cleanup functions in `useEffect` to prevent memory leaks.
- Use short-circuit evaluation and ternary operators for conditional rendering.

### State Management

- Use Zustand for global state management with proper TypeScript typing.

  ```ts
  interface State {
    count: number;
    increment: () => void;
  }

  const useStore = create<State>((set) => ({
    count: 0,
    increment: () => set((state) => ({ count: state.count + 1 })),
  }));
  ```

- Lift state up when needed to share state between components.
- Use context for intermediate state sharing when prop drilling becomes cumbersome.

### UI and Styling

- Use `mantine.dev` components for all UI elements, utilizing Mantine's TypeScript support.
- Apply custom styles using CSS Modules:
  - Create a `.module.css` file for each component that needs custom styling.
  - Use camelCase for class names in CSS Modules files.
  - Maintain simple, component-specific styles using CSS Modules for easier maintenance and scalability.
  - Type your classes using:
    ```ts
    import styles from "./Component.module.css";
    ```

### Mantine with TypeScript

- Leverage Mantine's inbuilt TypeScript support for `useStyles`, `sx`, and `MantineProvider` for theme customization.
- Example usage:

  ```ts
  const useStyles = createStyles((theme) => ({
    button: {
      backgroundColor: theme.colors.blue[6],
      "&:hover": {
        backgroundColor: theme.colors.blue[8],
      },
    },
  }));

  function MyButton() {
    const { classes } = useStyles();
    return <Button className={classes.button}>Click me</Button>;
  }
  ```

### File Structure for Styling

- Place CSS Modules files next to their corresponding component files.
- Example structure:
  ```plaintext
  components/
    Button/
      Button.tsx
      Button.module.css
    Card/
      Card.tsx
      Card.module.css
  ```

### CSS Modules Best Practices with TypeScript

- Define custom classes in `.module.css` and import them into TypeScript components:
  ```ts
  import styles from "./Component.module.css";
  ```
- Apply classes using the `styles` object:
  ```ts
  <div className={styles.containerClass} />
  ```
- Use variables for colors, fonts, and other repeated values, either using Mantine's `theme` or a custom configuration file.
- Keep specificity low by avoiding deep nesting in CSS Modules.

### Performance Optimization

- Minimize the use of `'use client'`, `useEffect`, and `useState`; favor React Server Components (RSC).
- Wrap client components in `Suspense` with a fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, and implement lazy loading.
- Implement route-based code splitting in Next.js.
- Minimize the use of global styles; prefer modular, scoped styles with CSS Modules.

### Forms and Validation

- Use Mantine's form components with TypeScript support.
- Implement form validation (client-side and server-side).
- Consider using libraries like `react-hook-form` for complex forms with proper type validation.
- Use Zod or Joi for schema validation.

### Error Handling and Validation

- Prioritize error handling and edge cases.
- Handle errors and edge cases at the beginning of functions.
- Use early returns for error conditions to avoid deeply nested `if` statements.
- Avoid unnecessary `else` statements; use `if-return` pattern instead.
- Model expected errors as return values in Server Actions.
- Implement proper error logging and user-friendly error messages.

### Accessibility (a11y)

- Use semantic HTML elements.
- Implement proper ARIA attributes.
- Ensure keyboard navigation support.

### Testing

- Write unit tests for components using Jest and React Testing Library with TypeScript.
- Implement integration tests for critical user flows.
- Use snapshot testing judiciously.

### Security

- Sanitize user inputs to prevent XSS attacks.
- Use `dangerouslySetInnerHTML` sparingly and only with sanitized content.

### Internationalization (i18n)

- Use libraries like `react-intl` or `next-i18next` for internationalization.

### Key Conventions

- Use `nuqs` for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Limit `'use client'`:
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.
css
dockerfile
java
javascript
jest
nestjs
next.js
react
+2 more

First seen in:

ChayFadida/actis

Used in 1 repository