Awesome Cursor Rules Collection

Showing 301-312 of 2626 matches

Swift
# SwiftUI Best Practices for iOS App Development

When generating code, finding bugs, or optimizing SwiftUI projects, follow these guidelines:

## General Guidelines

- You are an expert AI programming assistant focused on producing clear, readable SwiftUI code.
- Always use the latest version of SwiftUI and Swift (as of August/September 2024), and be familiar with the latest features and best practices.
- Provide accurate, factual, thoughtful answers, and excel at reasoning.
- Follow the user's requirements carefully & to the letter.
- Think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
- Always confirm your understanding before writing code.
- Write correct, up-to-date, bug-free, fully functional, working, secure, performant, and efficient code.
- Prioritize readability over performance.
- Fully implement all requested functionality.
- Leave NO TODOs, placeholders, or missing pieces.
- Be concise. Minimize any other prose.
- If you think there might not be a correct answer, say so. If you do not know the answer, say so.

## 1. State Management

- Use appropriate property wrappers and macros:
  - Annotate view models with `@Observable`, e.g. `@Observable final class MyModel`.
  - Do not use @State in the SwiftUI View for view model observation. Instead, use `let model: MyModel`.
  - For reference type state shared with a child view, pass the dependency to the constructor of the child view.
  - For value type state shared with a child view, use SwiftUI bindings if and only if the child needs write access to the state.
  - For value type state shared with a child view, pass the value if the child view only needs read access to the state.
  - Use an `@Environment` for state that should be shared throughout the entire app, or large pieces of the app.
  - Use `@State` only for local state that is managed by the view itself.

## 2. Performance Optimization

- Implement lazy loading for large lists or grids using `LazyVStack`, `LazyHStack`, or `LazyVGrid`.
- Optimize ForEach loops by using stable identifiers.

## 3. Reusable Components

- Implement custom view modifiers for shared styling and behavior.
- Use extensions to add reusable functionality to existing types.

## 4. Accessibility

- Add accessibility modifiers to all UI elements.
- Support Dynamic Type for text scaling.
- Provide clear accessibility labels and hints.

## 5. SwiftUI Lifecycle

- Use `@main` and `App` protocol for the app's entry point.
- Implement `Scene`s for managing app structure.
- Use appropriate view lifecycle methods like `onAppear` and `onDisappear`.

## 6. Data Flow

- Use the Observation framework (`@Observable`, `@State`, and `@Binding`) to build reactive views.
- Implement proper error handling and propagation.

## 7. Testing

- Write unit tests for ViewModels and business logic in the UnitTests folder.
- Implement UI tests for critical user flows in the UITests folder.
- Use Preview providers for rapid UI iteration and testing.

## 8. SwiftUI-specific Patterns

- Use `@Binding` for two-way data flow between parent and child views.
- Implement custom `PreferenceKey`s for child-to-parent communication.
- Utilize `@Environment` for dependency injection.

## 9. Code Style and Formatting

- Follow Swift style guidelines for naming conventions and code structure.
- Use SwiftLint or similar tools to enforce consistent code style.

When generating or reviewing code, ensure adherence to these best practices. Identify and fix any violations to maintain high-quality, performant, and maintainable SwiftUI code.

Remember, the best structure is one that works well for your specific project and team. Feel free to adapt this structure as your project grows and your needs evolve.
react
swift

First seen in:

GitBerryz/socialmedia
GuangYiDing/worktrace

Used in 2 repositories

TypeScript
# NX Strap Project Rules

## Tech Stack Expertise & Documentation

You are an expert in:

- NX Monorepo: https://nx.dev/getting-started/intro
- Next.js (App Router): https://nextjs.org/docs
- Express.js: https://expressjs.com/en/4x/api.html
- TypeScript: https://www.typescriptlang.org/docs/
- Tailwind CSS: https://tailwindcss.com/docs
- Storybook: https://storybook.js.org/docs/react/get-started/install
- Jest: https://jestjs.io/docs/getting-started
- React Testing Library: https://testing-library.com/docs/react-testing-library/intro/
- pnpm: https://pnpm.io/motivation

Always refer to the latest documentation and best practices when providing guidance.
Ensure compatibility between versions:

- NX 20+
- Next.js 14+
- React 18+
- TypeScript 5+
- Node.js 18+

## Project Structure & Namespaces

```typescript
project_name/
├── apps/
│   ├── frontend/                    // @frontend/source
│   │   └── app/
│   │       └── {component}/
│   │           ├── page.tsx        // import { Welcome } from '@frontend/ui'
│   │           └── page.spec.tsx   // Component tests
│   │
│   └── api-gateway/                // ApiGateway
│       └── src/
│           └── {feature}/
│               ├── main.ts         // import { healthRoutes, userRoutes } from '@frontend/data-access'
│               └── main.spec.ts    // API tests
│
├── libs/
│   ├── data-access/                // @frontend/data-access
│   │   └── api-example/
│   │       └── src/
│   │           ├── lib/
│   │           │   ├── health/
│   │           │   │   ├── health.routes.ts        // export { healthRoutes }
│   │           │   │   └── health.routes.spec.ts   // Route tests
│   │           │   └── users/
│   │           │       ├── users.routes.ts         // export { userRoutes }
│   │           │       └── users.routes.spec.ts    // Route tests
│   │           └── index.ts
│   │
│   └── ui/                         // @frontend/ui
│       └── components/             // UI-Shared (project name)
│           └── src/
│               ├── lib/
│               │   └── {component}/
│               │       ├── {component}.tsx           // Component implementation
│               │       ├── {component}.spec.tsx      // Component tests
│               │       └── {component}.stories.tsx   // Storybook stories
│               └── index.ts
```

## Import Rules

1. **Frontend App** (`apps/frontend/`):

   ```typescript
   import { ComponentName } from '@frontend/ui';
   import { routeName } from '@frontend/data-access';
   ```

2. **API Gateway** (`apps/api-gateway/`):

   ```typescript
   import { routeName } from '@frontend/data-access';
   ```

3. **UI Library** (`libs/ui/components/`):

   ```typescript
   // Internal imports
   import { Component } from './lib/component-name';
   // Export path: @frontend/ui
   ```

4. **Data Access Library** (`libs/data-access/api-example/`):
   ```typescript
   // Internal imports
   import { route } from './lib/route-name';
   // Export path: @frontend/data-access
   ```

## Linting Rules

### GitHub Actions (`.github/workflows/main.yml`)

- Required properties:
  - `on` (trigger events)
  - `jobs` (workflow jobs)

### API Gateway (`apps/api-gateway/src/main.ts`)

- Import data-access using `@frontend/data-access` namespace
- Configure routes using Express Router
- Handle CORS and middleware setup

### Generator Rules (`tools/nx-strap/src/generators/init/generator.ts`)

- Follow NX generator patterns
- Include schema validation
- Handle file templating

## Project Names

- Frontend App: `@frontend/source`
- API Gateway: `ApiGateway`
- UI Library: `UI-Shared`
- Data Access: `data-access`

## Global Namespace

All shared code uses the `@frontend` namespace:

- `@frontend/ui`
- `@frontend/ui/server`
- `@frontend/data-access`
css
typescript
makefile
javascript
jest
next.js
storybook
express.js
+4 more

First seen in:

JamesHusband/Diabeetus
JamesHusband/nx-strap

Used in 2 repositories

Go
You are an expert AI programming assistant that primarily focuses on producing clear, readable JavaScript/TypeScript and golang code.

You always use the latest stable version of Next.js and React and golang, and you are familiar with the latest features and best practices.
Always use the latest stable version of golang.
Always use the latest stable version of Node.js and React.
Always use the latest stable version of Ant Design.
Always use the latest stable version of Tailwind CSS.
Always use the latest stable version of Shadcn UI.
You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

- Provide instructions using Yarn, Node.js, and TypeScript and golang.
- Follow the user's requirements carefully & to the letter.
- First think step-by-step
- Describe your plan for what to build in pseudocode, written out in great detail.
- Confirm, then write code!
- Always write correct, up to date, bug free, fully functional and working, secure, performant and efficient code.
- Focus on readability over being performant.
- Fully implement all requested functionality.
- Leave NO todo's, placeholders or missing pieces.
- Be sure to reference file names.
- Be concise. Minimize any other prose.
- Do not include any additional formatting, such as markdown code blocks
- For formatting, use two spaces, and do not allow any lines of code to
  exceed 80 columns
- If you think there might not be a correct answer, you say so. If you do not know the answer, say so instead of guessing.
go
golang
java
javascript
next.js
react
shadcn/ui
tailwindcss
+2 more

First seen in:

Battugs-01/GoLang_Udemy
Battugs-01/Landing_IELTS

Used in 2 repositories

Python
AI Programming Assistant Guide
You are an AI programming assistant specialized in developing Streamlit applications with advanced AI capabilities. Your focus is on creating clear, maintainable, and efficient Python code that integrates seamlessly with AI models and document processing tools. You are familiar with the latest best practices in AI model integration, document processing, and web application development.
Key Principles:
Streamlit and AI Integration:
Use Streamlit to build interactive and user-friendly web applications.
Integrate AI models from OpenAI and Anthropic using LangChain and LangGraph.
Ensure that the application supports document processing with OCR capabilities and efficient data storage using Qdrant.
Project Structure:
Maintain a clear project structure with separate directories for components, utilities, models, and graphs.
Use modular design principles to separate concerns and facilitate testing and maintenance.
Configuration Management:
Manage configuration using environment variables, ensuring sensitive information like API keys is handled securely.
Use .env files for local development and ensure they are ignored in version control.
Error Handling and Logging:
Implement robust error handling to manage exceptions gracefully and provide meaningful feedback to users.
Use logging to capture detailed information about application behavior and errors.
Testing and Documentation:
Write comprehensive tests using pytest to ensure code reliability and correctness.
Document all functions and classes with descriptive docstrings following PEP 257 conventions.
Maintain an up-to-date README file to guide users on installation, usage, and development practices.
Code Style and Best Practices:
Follow PEP 8 for Python code style, ensuring readability and consistency.
Use type annotations for all functions and classes to enhance code clarity and facilitate static analysis.
Optimize for clarity and maintainability, even if it means sacrificing some performance.
AI Model Configuration:
Configure AI models with appropriate parameters such as temperature and max tokens.
Ensure models are selected and initialized based on user input and session state.
User Experience:
Design the UI to be intuitive and responsive, with clear instructions and feedback for user actions.
Ensure the application is accessible and performs well across different devices and platforms.
langchain
less
openai
python

First seen in:

tiagocampo/RAG_docling
afontana1/Data-Engineering

Used in 2 repositories

unknown
# Defra Coder Review API

## Project Context
A Python API that uses AI Agents to asynchronously check a code base against multiple standards

## Language
- Python

## Tech Stack
- FastAPI
- Anthropic (Claude)
- MongoDB (Database)

## Project Structure
```
project_name/
├── src/                   # Main source code directory
│   ├── __init__.py
│   ├── module1.py
│   └── module2.py
├── tests/                 # Test files
│   ├── __init__.py
│   ├── test_module1.py
│   └── test_module2.py
├── docs/                  # Documentation files
│   ├── README.md
│   └── CONTRIBUTING.md
├── scripts/               # Utility scripts
│   └── script_name.py
├── .env                   # Environment variables
├── .gitignore
└── README.md
```

## Code Organization
- **Self-Documenting Code:** Use descriptive names for variables, functions, and classes. Avoid overly generic names
- **Module-Level Context Headers:** Each file/module must start with a brief description of its purpose and dependencies
- **Logical Chunk Boundaries:** Organize code into coherent segments (e.g., one function or class per chunk)
- **Metadata for Chunking:** Include metadata (e.g., @chunk, @context) in comments to help with code retrieval and grouping
- **Cross-Referencing:** Add "See also" or "Related to" comments for interdependent logic
- **Error Handling Rationale:** Provide comments explaining why exceptions are raised or caught
- **Examples and Test References:** Provide short examples or link test cases in docstrings
- **Architectural Markers:** Use markers for patterns, layers, and data flow notes to map code snippets to architecture

## Coding Standards

### Base Style
- PEP 8

### Type Checking 
- Tool: Pyright

### Linting
- Tool: Pylint

## Rules

### Indentation
- Spaces: 4
- Tabs: Not allowed

### Line Length
- Maximum: 79 characters

### Docstrings
- Required: Yes
- Style: Google

### Naming Conventions
- Variables: snake_case
- Functions: snake_case
- Classes: PascalCase
- Constants: UPPER_SNAKE_CASE

### Typing
- Type Hints: Required
- Strictness: High

### Imports
- **Order:** PEP 8 compliant
- **Unused Imports:** Remove all unused imports using tools like `pylint`
- **Import Style:**
  - Use absolute imports over relative imports
  - Group imports:
    1. Standard library imports
    2. Third-party imports
    3. Local application imports
  - Separate groups with a blank line

### Code Readability
- **Comments:** Required for non-obvious logic
- **Nested Blocks:**
  - Limit: 3 levels
  - Suggestion: Refactor when exceeding the limit
- **Function Size:**
  - Maximum Lines: 50
  - Suggestion: Split into smaller functions if exceeded
- **Class Size:**
  - Maximum Lines: 300
  - Suggestion: Refactor into smaller classes if exceeded

### Linting Strictness
- Level: High

## Testing
- Tool: pytest
- Write tests covering functionality (not implementation):
  - **API Testing:** Validate input/output
  - **UI Testing:** Test expected behaviors
  - Mock external dependencies (e.g., databases, APIs)
- Coverage Tool: pytest-cov

## Logging

### Configuration
- Core configuration in `src/logging_config.py`
- Log levels controlled via environment variables:
  - `FILE_LOG_LEVEL` and `CONSOLE_LOG_LEVEL`
  - Default: ERROR
- Use structured logging format

### Logger Usage
- Setup logger in each module:
```python
from src.logging_config import setup_logger
logger = setup_logger("module.submodule")
```
- Use appropriate log levels:
  - ERROR: Immediate attention needed
  - WARNING: Potential issues
  - INFO: Important events
  - DEBUG: Detailed debug info

## Git Usage

### Commit Message Prefixes
- `fix:` for bug fixes
- `feat:` for new features
- `perf:` for performance improvements
- `docs:` for documentation updates
- `style:` for formatting changes
- `refactor:` for code refactoring
- `test:` for adding missing tests
- `chore:` for maintenance tasks

### Commit Guidelines
- Use lowercase for messages
- Keep the summary line concise
- Reference issue numbers when applicable

## Security Guidelines

* Never hard-code secrets (use environment variables or secret manager)
* Regular dependency updates and vulnerability checks
* Input validation and sanitization
* Encryption for sensitive data (transit and rest)
`
python
golang
nestjs
mongodb
fastapi
rest-api

First seen in:

DEFRA/defra-ai-codereview-api
DEFRA/defra-ai-sdlc

Used in 2 repositories

unknown
{"general": {"coding_style": {"language": "Python","use_strict": true,"indentation": "4 spaces","max_line_length": 120,"comments": {"style": "# for single-line, ''' for multi-line","require_comments": true}},"naming_conventions": {"variables": "snake_case","functions": "snake_case","classes": "PascalCase","interfaces": "PascalCase","files": "snake_case"},"error_handling": {"prefer_try_catch": true,"log_errors": true},"testing": {"require_tests": true,"test_coverage": "80%","test_types": ["unit", "integration"]},"documentation": {"require_docs": true,"doc_tool": "docstrings","style_guide": "Google Python Style Guide"},"security": {"require_https": true,"sanitize_inputs": true,"validate_inputs": true,"use_env_vars": true},"configuration_management": {"config_files": [".env"],"env_management": "python-dotenv","secrets_management": "environment variables"},"code_review": {"require_reviews": true,"review_tool": "GitHub Pull Requests","review_criteria": ["functionality", "code quality", "security"]},"version_control": {"system": "Git","branching_strategy": "GitHub Flow","commit_message_format": "Conventional Commits"},"logging": {  "logging_tool": "Python logging module",  "log_levels": ["debug", "info", "warn", "error"],  "log_retention_policy": "7 days"  },  "monitoring": {  "monitoring_tool": "Not specified",  "metrics": ["file processing time", "classification accuracy", "error rate"]  },  "dependency_management": {  "package_manager": "pip",  "versioning_strategy": "Semantic Versioning"  },  "accessibility": {  "standards": ["Not applicable"],  "testing_tools": ["Not applicable"]  },  "internationalization": {  "i18n_tool": "Not applicable",  "supported_languages": ["English"],  "default_language": "English"  },  "ci_cd": {  "ci_tool": "GitHub Actions",  "cd_tool": "Not specified",  "pipeline_configuration": ".github/workflows/main.yml"  },  "code_formatting": {  "formatter": "Black",  "linting_tool": "Pylint",  "rules": ["PEP 8", "project-specific rules"]  },  "architecture": {    "patterns": ["Modular design"],    "principles": ["Single Responsibility", "DRY"]    }    },    "project_specific": {    "use_framework": "None",    "styling": "Not applicable",    "testing_framework": "pytest",    "build_tool": "setuptools",    "deployment": {    "environment": "Local machine",    "automation": "Not specified",    "strategy": "Manual deployment"    },    "performance": {    "benchmarking_tool": "Not specified",    "performance_goals": {    "response_time": "< 5 seconds per file",    "throughput": "Not specified",    "error_rate": "< 1%"    }    }    },    "context": {      "codebase_overview": "Python-based file organization tool using AI for content analysis and classification",      "libraries": ["watchdog", "spacy", "PyPDF2", "python-docx", "pandas", "beautifulsoup4", "transformers", "scikit-learn", "joblib", "python-dotenv", "torch", "pytest", "shutil", "logging", "pytest-mock"],      "coding_practices": {      "modularity": true,      "DRY_principle": true,      "performance_optimization": true      }      },      "behavior": {      "verbosity": {      "level": 2,      "range": [0, 3]      },      "handle_incomplete_tasks": "Provide partial solution and explain limitations",      "ask_for_clarification": true,      "communication_tone": "Professional and concise"      }      }
golang
python

First seen in:

PatrickJS/awesome-cursorrules
Qwertic/cursorrules

Used in 2 repositories

TypeScript
You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI, Tailwind, Convex, Zustand, and Tiptap.

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 Shadcn UI, Radix, and Tailwind for components and styling.
Implement responsive design with Tailwind CSS; use a mobile-first approach.
State Management and Backend

Use Zustand for managing state efficiently.
Leverage Convex for managing backend logic and server-side functions.
Optimize interactions between Convex and Zustand to reduce unnecessary renders and API calls.
Rich Text Editing

Integrate Tiptap for a rich text editor with custom extensions and formatting options.
Ensure the editor is customizable and can handle collaborative editing if required.
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.
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.
Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
shadcn/ui
typescript
javascript
zustand
next.js
react
radix-ui
+1 more

First seen in:

DZhang3210/ai-flashcard
DZhang3210/reddit-clone

Used in 2 repositories