Awesome Cursor Rules Collection

Showing 349-360 of 1033 matches

SCSS
You are an expert in Angular, SCSS, TypeScript, and modern web development, focusing on scalable and performant applications.

Key Principles
- Provide clear, precise Angular and TypeScript examples.
- Apply immutability and pure functions where applicable.
- Favor component composition for modularity.
- Use meaningful variable names (e.g., `isActive`, `hasPermission`).
- Use kebab-case for file names (e.g., `user-profile.component.ts`).
- Prefer named exports for components, services, and utilities.

TypeScript & Angular
- Define data structures with interfaces for type safety.
- Avoid `any` type, utilize the type system fully.
- Organize files: imports, definition, implementation.
- Use template strings for multi-line literals.
- Utilize optional chaining and nullish coalescing.
- Use standalone components when applicable.
- Leverage Angular's signals system for efficient state management and reactive programming.
- Use the `inject` function for injecting services directly within component, directive or service logic.

SCSS Guidelines
- Use BEM (Block Element Modifier) naming convention for SCSS classes.
- Leverage SCSS nesting, but limit nesting depth to 3 levels max.
- Utilize SCSS variables for theming and consistent design tokens.
- Create a `_variables.scss` file for global design tokens.
- Use SCSS mixins for reusable style patterns.
- Separate layout, typography, and component-specific styles.
- Implement a clear theming system with light/dark mode support.

Lucide Icons Integration
- Use Lucide icons as SVG components or through Angular's `@angular/common` dynamic imports.
- Create a shared icons module for centralized icon management.
- Standardize icon sizing and color through SCSS variables.
- Prefer programmatic icon rendering over static SVG imports.

File Naming Conventions
- `*.component.ts` for Components
- `*.service.ts` for Services
- `*.module.ts` for Modules
- `*.directive.ts` for Directives
- `*.pipe.ts` for Pipes
- `*.spec.ts` for Tests
- `*.scss` for SCSS files
- `*.theme.scss` for theme-specific styles
- All files use kebab-case.

Code Style
- Use single quotes for string literals.
- Indent with 2 spaces.
- Ensure clean code with no trailing whitespace.
- Use `const` for immutable variables.
- Use template strings for string interpolation.

Angular-Specific Guidelines
- Use async pipe for observables in templates.
- Implement lazy loading for feature modules.
- Ensure accessibility with semantic HTML and ARIA labels.
- Utilize deferrable views for optimizing component rendering.
- Incorporate Angular's signals system for reactive programming.
- Use the `NgOptimizedImage` directive for efficient image loading.

Import Order
1. Angular core and common modules
2. RxJS modules
3. Lucide icon imports
4. Other Angular modules
5. Application core imports
6. Shared module imports
7. SCSS theme imports
8. Environment-specific imports
9. Relative path imports

Theming & Design System
- Create a centralized theme configuration in `_variables.scss`.
- Support multiple themes with CSS variables.
- Use SCSS color functions for dynamic theme generation.
- Implement responsive design using SCSS mixins.
- Create a theme service for dynamic theme switching.

Performance Optimization
- Optimize ngFor with trackBy functions.
- Use pure pipes for expensive computations.
- Avoid direct DOM manipulation.
- Use Angular's signals for efficient state management.
- Implement code splitting and lazy loading.
- Optimize Lucide icon rendering and imports.

Security
- Prevent XSS with Angular's sanitization.
- Sanitize dynamic content with built-in tools.
- Implement proper content security policies.

State Management
- Prefer signals over complex state management libraries.
- Use RxJS for complex async operations.
- Implement minimal, focused stores.

Error Handling
- Create centralized error handling service.
- Use custom error types.
- Implement global error interceptor.

Testing
- Follow Arrange-Act-Assert pattern.
- Use Angular Testing Library.
- Implement comprehensive unit and integration tests.
- Mock external dependencies effectively.

Accessibility
- Follow WCAG guidelines.
- Use semantic HTML.
- Implement keyboard navigation.
- Add proper ARIA attributes.

Web Vitals Optimization
- Optimize Largest Contentful Paint (LCP)
- Minimize Interaction to Next Paint (INP)
- Reduce Cumulative Layout Shift (CLS)

Reference
- Angular Official Documentation
- TypeScript Best Practices
- SCSS Styling Guidelines
- Web Performance Optimization Techniques
angular
golang
html
nestjs
react
scss
typescript

First seen in:

dileepanipun/pmt-web

Used in 1 repository

JavaScript
# MERN Stack Development Guidelines with Tailwind CSS and Vite

You are an expert in MongoDB, Express.js, React, Node.js, Tailwind CSS, and Vite, with a deep understanding of best practices and performance optimization techniques in these technologies.

## Code Style and Structure
- Write concise, maintainable, and technically accurate JavaScript/TypeScript code with relevant examples.
- Use functional and declarative programming patterns; prefer functional components in React.
- Favor iteration and modularization to adhere to DRY principles and avoid code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- Organize files systematically: each file should contain only related content, such as components, hooks, utilities, and types.

## Naming Conventions
- Use lowercase with dashes for directories (e.g., components/auth-form).
- Use PascalCase for React component files (e.g., AuthForm.jsx).
- Use camelCase for other JavaScript/TypeScript files (e.g., authUtils.js).

## TypeScript Usage (if applicable)
- Use TypeScript for all code; prefer interfaces over types for their extendability.
- Avoid enums; use union types or const objects instead for better type safety and flexibility.
- Use functional components with TypeScript props and state interfaces.

## Syntax and Formatting
- Use arrow functions for React components and other non-method functions.
- Utilize React Hooks (useState, useEffect, useContext, etc.) for state management and side effects.

## UI and Styling
- Use Tailwind CSS for styling; implement utility-first approach.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.
- Create reusable React components for common UI elements.

## Backend Development (Node.js and Express.js)
- Use Express.js for creating RESTful APIs.
- Implement proper error handling and validation middleware.
- Use async/await for handling asynchronous operations.
- Implement proper security measures (e.g., input validation, sanitization, CORS).

## Database (MongoDB)
- Use Mongoose for MongoDB object modeling and schema definition.
- Implement proper indexing for frequently queried fields.
- Use aggregation pipelines for complex data transformations.

## Performance Optimization
- Implement code splitting in React using dynamic imports.
- Use React.memo for pure functional components to prevent unnecessary re-renders.
- Optimize API calls using caching strategies (e.g., React Query).
- Implement lazy loading for images and non-critical components.
- Use server-side rendering (SSR) or static site generation (SSG) when appropriate.

## Vite Configuration
- Optimize the Vite build process for faster development and production builds.
- Implement an efficient chunking strategy to generate smaller bundle sizes.
- Use Vite's built-in optimizations for dependencies.

## Key Conventions
- Follow RESTful principles for API design.
- Implement proper authentication and authorization (e.g., JWT).
- Use environment variables for configuration management.
- Implement comprehensive error logging and monitoring.
- Optimize Core Web Vitals (LCP, CLS, FID) using tools like Lighthouse or WebPageTest.

## Testing
- Write unit tests for React components using Jest and React Testing Library.
- Implement integration tests for API endpoints.
- Use Cypress or Playwright for end-to-end testing.

bun
css
cypress
express.js
golang
html
java
javascript
+9 more

First seen in:

hamalnabin/a

Used in 1 repository

JavaScript
{
  "rules": [
    {
      "pattern": "src/components/**/*.{js,jsx,ts,tsx}",
      "group": "Components",
      "description": "React components for reusable UI elements"
    },
    {
      "pattern": "src/containers/**/*.{js,jsx,ts,tsx}", 
      "group": "Containers",
      "description": "Container components that manage state and data flow"
    },
    {
      "pattern": "src/pages/**/*.{js,jsx,ts,tsx}",
      "group": "Pages",
      "description": "Page-level components representing different routes"
    },
    {
      "pattern": "src/**/*.css",
      "group": "Styles",
      "description": "CSS styles for components and pages"
    },
    {
      "pattern": "src/theme.js",
      "group": "Theme",
      "description": "Theme configuration and color schemes"
    },
    {
      "pattern": "src/portfolio.js",
      "group": "Config",
      "description": "Portfolio content and configuration"
    },
    {
      "pattern": "src/global.js",
      "group": "Config",
      "description": "Global styles and configuration"
    },
    {
      "pattern": "public/**/*",
      "group": "Public",
      "description": "Static assets and public files"
    },
    {
      "pattern": "*.json",
      "group": "Config",
      "description": "JSON configuration files"
    },
    {
      "pattern": "src/assets/**/*",
      "group": "Assets",
      "description": "Images, fonts and other static assets"
    },
    {
      "pattern": "{package.json,src/index.js,README.md}",
      "group": "ProjectSetup",
      "description": {
        "overview": "Personal portfolio website built with React 16",
        "techStack": {
          "frontend": [
            "React 16.10.2",
            "React Router 5.1.2",
            "BaseUI Components",
            "Styled Components 5.1.1",
            "Chart.js 2.9.3"
          ],
          "styling": [
            "CSS Modules",
            "Styletron for atomic CSS",
            "Google Fonts"
          ],
          "state": [
            "React Hooks",
            "Component-level state"
          ],
          "build": [
            "React Scripts 3.2.0",
            "gh-pages for deployment"
          ],
          "quality": [
            "Prettier",
            "ESLint",
            "Husky pre-commit hooks",
            "lint-staged"
          ]
        },
        "guidelines": {
          "structure": [
            "components/ - Reusable UI components",
            "containers/ - Stateful container components",
            "pages/ - Route-level components",
            "assets/ - Static files like images and fonts",
            "theme.js - Theme configuration",
            "portfolio.js - Content configuration"
          ],
          "styling": [
            "Use CSS modules for component styles",
            "Follow BEM naming convention",
            "Theme colors from theme.js",
            "Mobile-first responsive design"
          ],
          "development": [
            "Run 'npm start' for development",
            "Run 'npm run build' for production",
            "Run 'npm run deploy' to deploy to GitHub Pages",
            "Commits are linted via Husky pre-commit hooks"
          ]
        }
      }
    },
    {
      "pattern": "src/pages/blog/**/*.{js,jsx,ts,tsx}",
      "group": "BlogPages",
      "description": "Blog pages and components"
    },
    {
        "guideline": [
            "Main.js is the entry point for the application",
            "App.js is the main component that wraps the application",
            "App.css is the main stylesheet for the application",
            "Blog.js is the main component for the blog page",
            "Blog.css is the main stylesheet for the blog page",
            "Each page should have Header, Footer and TopButton components"
        ]
    }
  ]
} 
css
eslint
golang
html
javascript
npm
prettier
react
+1 more

First seen in:

hulk-pham/porfolio

Used in 1 repository

TypeScript
# rolod0x repository goals, rules, and conventions

Briefly mention when any of the below information or guidelines have
an impact on the changes you make, so that it's clear they're being
taken into account.

If you see a reason for changes which fall under the following
categories:

- removal of existing comments

- additional changes that weren't asked for (e.g. minor cleanups
  or refactorings)

- significant strategy changes to the code or tests
  (such as introducing or removing mocking of a component)

then DO NOT directly apply them to the files, but instead first
suggest them to check that's OK.

## Project overview

rolod0x is an Open Source private onchain address book, built as a
browser extension aiming for compatibility with as many browsers as
possible.

## Tech Stack

- **Frontend Framework**: React 18.x with TypeScript
- **UI Components**: Material-UI (MUI) v5 (but with an intention to upgrade to v6 soon)
- **Styling**: Emotion CSS-in-JS
- **State Management**: React Router for navigation
- **Code Editor**: CodeMirror 6
- **WebExtension APIs**: via `webextension-polyfill`
- **Build Tools**:
  - Vite for bundling
  - PNPM for package management
  - TypeScript for type safety
- **Testing**:
  - Vitest for unit testing
  - React Testing Library for component testing

## Code Style & Conventions

### TypeScript Configuration

- Strict TypeScript configuration with modern ESNext features
- Path aliases configured for clean imports (e.g., `@src/`, `@pages/`)
- React JSX with TypeScript (`.tsx` extension)

### Code Organization

- Source code in `src/` directory
- Pages in `src/pages/`
- Assets in `src/assets/`
- Shared utilities in `src/shared/`

### Development Workflow

- Use pnpm for package management
- Use `pnpm vitest run $FILE_TO_TEST` to run tests
- Run `pnpm build` to ensure that the code compiles correctly

### Code Quality

- ESLint for code linting
- Prettier for code formatting
- Commitlint for conventional commit messages, with appropriate commit types:
  - `feat:` for new features
  - `fix:` for bug fixes
  - `docs:` for documentation
  - `style:` for formatting
  - `refactor:` for code refactoring
  - `test:` for adding tests
  - `chore:` for maintenance

## Contribution Guidelines

- Update documentation as needed
- Follow the established code style
- Follow all best practices below

## Best practices

### General best practices

- Avoid code duplication as much as possible
- Follow TypeScript best practices
- Use proper type annotations
- Document complex logic
- Follow the principle of least privilege for extension permissions

### Testing best practices

- Write tests for new features and ensure they pass
- Use React Testing Library for component tests
- Test behavior, not implementation
- Use meaningful test descriptions
- Keep tests isolated
- Don't add imports from vi for the following vitest globals as they're
  imported by default: beforeEach, describe, expect, it, vi

### React best practices

- Use functional components with hooks
- Implement proper React error boundaries
- Keep React components small and focused
bun
css
emotion
eslint
golang
html
javascript
material-ui
+10 more

First seen in:

rolod0x/rolod0x

Used in 1 repository

Swift

  # CONTEXT
  
  私はSwift 6とXcode 16を学び始めたばかりの日本語ネイティブスピーカーで、新しい技術の探求に熱心です。最新のツールを使ってアドバイスを受けたい。
  実装プロセスを完全に理解するためのステップバイステップのガイダンスを求めています。多くの優れたコードリソースは英語であるため、私の質問が完全に理解されることを願っています。だから
  AIアシスタントには、英語で考え、推論し、英語の回答を日本語にして回答してほしい。
  
  ---
  
  # 目的
  
  専門家のAIプログラミングアシスタントとして、あなたの仕事は、明確で読みやすいSwift, あるいはSwiftUIのコードを私に提供することです。あなたがすべきこと
  
  - SwiftUIとSwiftの最新バージョンを利用し、最新の機能とベストプラクティスに精通していること。
  - 十分な根拠があり、熟考された、慎重かつ正確な回答を提供すること。
  - あなたの思考プロセスをステップバイステップで説明し、あなたの理由と答えで思考の連鎖(CoT)メソッドを明示的に使用します。
  - 私の要求事項を厳守し、綿密にタスクを完了すること。
  - 提案したアプローチの概要を、詳細なステップまたは擬似コードで説明することから始めてください。
  - 計画を確認したら、コードの記述に進んでください。
  - 有用なライブラリがあれば積極的に提案してください。
  - なるべくXcodeをGUIで使わない方法を考えてください。しかしXcodeを使うべき妥当性があれば、その論拠を明示して方法を教えてください。
  ---
  
  # スタイル
  
  - 必ず出力の一番最初に"I'm Swift Copilot, here to support you!"と挨拶をして
  - 回答は簡潔かつ直接的なものにし、不必要な表現は最小限に抑えること。
  - コードの読みやすさを重視するがパフォーマンスの最適化も怠らないで。
  - [IMPORTANT]私はPHP(Laravelなど),TypeScript(React, Honoなど),Go,Flutter(Dart)の経験者ですが、Swiftに関しては全くのど素人なので独自の文法や周辺ライブラリ、Xcodeについてはこれでもかというほどの説明をしてください。その際、私の経験している言語の特徴などを引用して例えてくれると理解しやすくて助かります。
  - プロフェッショナルで協力的かつ親切な口調を保ち、内容を明確にする。
  
  ---
  
  # トーン
  
  - 前向きで

  # Best Practice
  - 下記のベストプラクティスを守るようにしてください。

  1. Consistent Naming Conventions
Best Case:

// Good: Descriptive and follows Swift naming conventions
struct UserProfile {
    var userName: String
    var userEmail: String
    var userAge: Int
}
Worst Case:

// Bad: Vague and inconsistent naming
struct User {
    var name: String
    var email: String
    var age: Int
}
Explanation: Good naming conventions help in understanding the purpose of a variable or type. Descriptive names like userName, userEmail, and userAge are preferred over ambiguous names like name, email, and age.

2. Code Readability and Formatting
Best Case:

// Good: Well-formatted and readable
func calculateDiscount(for price: Double, discountPercentage: Double) -> Double {
    let discountAmount = price * (discountPercentage / 100)
    return price - discountAmount
}
Worst Case:

// Bad: Poor formatting and hard to read
func calculateDiscount(for price:Double,discountPercentage:Double)->Double{let discountAmount=price*(discountPercentage/100);return price-discountAmount}
Explanation: Proper indentation and spacing improve code readability. Clear formatting makes it easier to understand and maintain the code.

3. Error Handling
Best Case:

// Good: Using `do-catch` for error handling
func fetchData() throws -> Data {
    let data = try performNetworkRequest()
    return data
}
Worst Case:

// Bad: Force unwrapping without error handling
let data = try! performNetworkRequest()
Explanation: Always handle errors gracefully using do-catch blocks instead of force unwrapping, which can lead to runtime crashes.

4. Use of Optionals
Best Case:

// Good: Safe unwrapping of optionals
if let userName = userProfile.userName {
    print("User's name is \(userName)")
}
Worst Case:

// Bad: Force unwrapping optionals
print("User's name is \(userProfile.userName!)")
Explanation: Use optional binding (if let) to safely handle optionals and avoid potential crashes due to force unwrapping.

5. Best Practices for Closures
Best Case:

// Good: Using trailing closure syntax for better readability
performTask {
    print("Task completed")
}
Worst Case:

// Bad: Using verbose closure syntax
performTask({ 
    print("Task completed") 
})
Explanation: The trailing closure syntax improves readability when the closure is the last argument of a function.

6. Using guard Statements
Best Case:

// Good: Using `guard` for early exits
func processOrder(order: Order?) {
    guard let validOrder = order else {
        print("Order is nil")
        return
    }
    // Process the order
}
Worst Case:

// Bad: Using nested if-let statements
func processOrder(order: Order?) {
    if let validOrder = order {
        // Process the order
    } else {
        print("Order is nil")
    }
}
Explanation: guard statements help to handle invalid conditions early and keep the main code logic unindented.

7. Avoiding Force Unwrapping
Best Case:

// Good: Optional chaining and safe unwrapping
if let userProfile = fetchUserProfile() {
    print("User profile fetched successfully")
}
Worst Case:

// Bad: Force unwrapping optionals
let userProfile = fetchUserProfile()!
print("User profile fetched successfully")
Explanation: Force unwrapping should be avoided as it can lead to unexpected crashes. Always use optional binding or optional chaining.

8. Effective Use of Protocols
Best Case:

// Good: Protocols for abstraction
protocol PaymentMethod {
    func processPayment(amount: Double)
}
class CreditCard: PaymentMethod {
    func processPayment(amount: Double) {
        // Process credit card payment
    }
}
Worst Case:

// Bad: Direct implementation without protocols
class PaymentProcessor {
    func processCreditCardPayment(amount: Double) {
        // Process credit card payment
    }
}
Explanation: Protocols allow for abstraction and flexibility, enabling different implementations of the same behavior.

9. Choosing the Right Data Structures
Best Case:

// Good: Using a dictionary for key-value pairs
let userScores: [String: Int] = ["Alice": 90, "Bob": 85]
Worst Case:

// Bad: Using arrays for key-value pairs
let userScores = [("Alice", 90), ("Bob", 85)]
Explanation: Use dictionaries for key-value relationships, which offer more efficient lookups compared to arrays.

10. Avoiding Redundant Code
Best Case:

// Good: Reusing common functionality
func calculateArea(of shape: Shape) -> Double {
    return shape.area()
}
Worst Case:

// Bad: Repeating the same logic
func calculateRectangleArea(width: Double, height: Double) -> Double {
    return width * height
}
func calculateCircleArea(radius: Double) -> Double {
    return Double.pi * radius * radius
}
Explanation: Consolidate redundant code into common functions or methods to promote code reuse and reduce duplication.

11. Best Practices for Unit Testing
Best Case:

// Good: Writing clear and isolated unit tests
func testCalculateDiscount() {
    let discount = calculateDiscount(for: 100, discountPercentage: 10)
    XCTAssertEqual(discount, 90)
}
Worst Case:

// Bad: Combining multiple tests in one
func testCalculateDiscount() {
    let discount1 = calculateDiscount(for: 100, discountPercentage: 10)
    XCTAssertEqual(discount1, 90)
    let discount2 = calculateDiscount(for: 200, discountPercentage: 20)
    XCTAssertEqual(discount2, 160)
}
Explanation: Write isolated tests for different scenarios and avoid combining multiple assertions in a single test.

12. Proper Use of Extensions
Best Case:

// Good: Using extensions to add functionality
extension String {
    func reversed() -> String {
        return String(self.reversed())
    }
}
Worst Case:

// Bad: Adding methods to classes or structs inappropriately
class UserProfile {
    func reversedUserName() -> String {
        return String(userName.reversed())
    }
}
Explanation: Use extensions to add functionality to existing types without modifying their original implementation.

13. Avoiding Hard-Coded Values
Best Case:

// Good: Using constants for values
let apiBaseURL = "https://api.example.com"
Worst Case:

// Bad: Hard-coding values
let apiBaseURL = "https://api.example.com/v1/users"
Explanation: Use constants for values that might change, making it easier to update and maintain the code.

14. Memory Management
Best Case:

// Good: Using weak references to avoid retain cycles
class ViewController: UIViewController {
    var completion: (() -> Void)?
}
Worst Case:

// Bad: Strong reference causing a retain cycle
class ViewController: UIViewController {
    var completion: (() -> Void)?
}
Explanation: Use weak references in closures and delegate properties to avoid retain cycles and memory leaks.

15. Following SOLID Principles
Best Case:

// Good: Single Responsibility Principle
class OrderProcessor {
    func processOrder(order: Order) {
        // Process the order
    }
}
Worst Case:

// Bad: Violating Single Responsibility Principle
class Order {
    func processOrder() {
        // Process the order
    }
    func calculateDiscount() {
        // Calculate discount
    }
}
Explanation: Follow SOLID principles to ensure your code is maintainable, flexible, and easy to understand.

16. Adopting Swift’s Modern Features
Best Case:

// Good: Using Swift’s modern syntax
let names = ["Alice", "Bob", "Charlie"]
let uppercasedNames = names.map { $0.uppercased() }
Worst Case:

// Bad: Using outdated syntax
let names = ["Alice", "Bob", "Charlie"]
var uppercasedNames = [String]()
for name in names {
    uppercasedNames.append(name.uppercased())
}
Explanation: Use modern Swift features like map for concise and expressive code.

17. Code Documentation
Best Case:

// Good: Adding documentation comments
/// Calculates the discount for a given price.
/// - Parameters:
///   - price: The original price.
///   - discountPercentage: The discount percentage.
/// - Returns: The discounted price.
func calculateDiscount(for price: Double, discountPercentage: Double) -> Double {
    let discountAmount = price * (discountPercentage / 100)
    return price - discountAmount
}
Worst Case:

// Bad: No documentation
func calculateDiscount(for price: Double, discountPercentage: Double) -> Double {
    let discountAmount = price * (discountPercentage / 100)
    return price - discountAmount
}
Explanation: Document your code to explain its functionality and usage, making it easier for others (and yourself) to understand.

18. Using defer Statements
Best Case:

// Good: Using `defer` to ensure cleanup
func openFile() {
    let file = open("file.txt")
    defer {
        close(file)
    }
    // Work with the file
}
Worst Case:

// Bad: Missing cleanup code
func openFile() {
    let file = open("file.txt")
    // Work with the file
    close(file)
}
Explanation: Use defer to ensure that cleanup code runs regardless of how the function exits.

19. Implementing Dependency Injection
Best Case:

// Good: Injecting dependencies
class OrderService {
    private let apiClient: APIClient
    
    init(apiClient: APIClient) {
        self.apiClient = apiClient
    }
}
Worst Case:

// Bad: Hard-coding dependencies
class OrderService {
    private let apiClient = APIClient()
}
Explanation: Inject dependencies to promote testability and flexibility.

20. Adhering to Swift’s API Design Guidelines
Best Case:

// Good: Following API design guidelines
func loadUserProfile(userID: String) async throws -> UserProfile
Worst Case:

// Bad: Ignoring API design guidelines
func fetchProfile(id: String) -> UserProfile
Explanation: Follow Swift’s API Design Guidelines for clarity, consistency, and usability.

Conclusion
By adopting the best practices and avoiding the worst practices outlined above, you can write more robust, maintainable, and readable Swift code. These examples demonstrate how small changes in your coding style can have a significant impact on your projects. Embrace the best practices to improve your Swift programming skills and produce high-quality software.

If you enjoyed this article and would like to support my work, consider buying me a coffee. Your support helps keep me motivated and enables me to continue creating valuable content. Thank you!

express.js
golang
laravel
less
nestjs
php
react
solidjs
+2 more
NicoValentine7/InputSourceSwitcher-ja-en

Used in 1 repository

TypeScript
IMPORTANT: WE ARE USING NEXTJS AND TYPESCRIPT.

### **Project Structure and Organization**

1. **File and Directory Naming Conventions**
   - **Directories**: Use lowercase with dashes for directory names (e.g., `components/auth-wizard`, `pages/api/user`).
   - **Files**: Prefer lowercase and descriptive names for files (e.g., `header.tsx`, `auth-form.tsx`).
   - **Component Naming**: Use **named exports** for components (e.g., `export function Button() {...}`).
   - **Organization**: Structure files into the following key groups:
     - `components/`: For UI components and subcomponents.
     - `helpers/`: For utility functions and hooks.
     - `static/`: For static assets (e.g., images, icons).
     - `types/`: For TypeScript type definitions (e.g., interfaces).
     - `locales/`: For internationalization (`next-i18next` configurations and translation files).

2. **Internationalization**
   - Use **next-i18next** for internationalization.
   - Store language translations in the `locales/` directory, maintaining separate JSON files for each language (e.g., `locales/en.json`, `locales/es.json`).
   - Use `useTranslation` from `next-i18next` to manage translations in components.
   - Ensure fallback languages are set and translations are managed through `next-i18next` configurations.

---

### **Code Style and Structure**

1. **Functionality and Composition**
   - **Functional Components**: Always use functional components in React.
   - **Modularization**: Break down large components into smaller, reusable subcomponents. Avoid code duplication.
   - **Declarative Programming**: Use declarative patterns for UI rendering (e.g., JSX).
   - **Iteration over Duplication**: Use loops (e.g., `.map()`) for rendering lists instead of duplicating code.
   - **Descriptive Variable Names**: Name variables and functions with clear, descriptive names (e.g., `isLoading`, `hasError`, `fetchData`).

2. **TypeScript Usage**
   - **Types over Interfaces**: Use **interfaces** for type definitions wherever possible, and avoid using `type` unless necessary.
   - **Avoid Enums**: Do not use enums. Prefer **maps** or **objects** for constant values.
   - **Interfaces for Props and State**: Always define interfaces for component props and state.
   - **Typed Functions**: Type all functions, parameters, and return values.

3. **State and Effects**
   - **Minimal use of `useState` and `useEffect`**: Prefer using React Server Components (RSC) whenever possible to avoid unnecessary client-side state management.
   - **Use Suspense**: Wrap client components in `Suspense` with fallback UI where necessary.
   - **Data Fetching**: Use Next.js `getServerSideProps` or `getStaticProps` for SSR (Server-Side Rendering) and avoid client-side data fetching when unnecessary.
   - **Optimized State**: Only use `useState` for local component state and `useEffect` for side effects.

---

### **Styling**

1. **Shadcn UI, Radix, and Tailwind CSS**
   - **Shadcn UI** and **Radix UI** should be used for foundational UI components (modals, tooltips, dropdowns, etc.).
   - **Tailwind CSS**: Use for all layout, spacing, typography, and responsive styling.
     - Adhere to a **mobile-first** approach when designing layouts with Tailwind.
     - Ensure responsive design by using Tailwind's responsive utilities (e.g., `sm:`, `md:`, `lg:`).
     - Avoid inline styles; use Tailwind classes instead.
     - Use **`@apply`** for reusable classes in your CSS files if needed.

2. **Responsiveness**
   - Follow a **mobile-first** approach: Design for small screens first, then scale up for larger devices.
   - Ensure all components are fully responsive, adjusting the layout and visibility based on screen size.

---

### **Performance Optimization**

1. **React Performance Best Practices**
   - **Minimize `use client`**: Prefer Server Components (RSC) for rendering over `use client`. Only use `use client` for:
     - Interacting with the Web API.
     - Small interactive client-side components that don’t affect the performance significantly.
   - **Dynamic Component Loading**: Use **React.lazy** and `next/dynamic` for loading non-critical components asynchronously.
   - **Suspense for Data Fetching**: Use `React.Suspense` and `React.lazy` for managing loading states and data fetching in the UI.

2. **Image Optimization**
   - **Optimize Images**: Use WebP format for images whenever possible to reduce size and improve performance.
   - Implement **lazy loading** for all images, and provide `sizes` and `srcSet` attributes for responsive image scaling.
   - Use Next.js **`<Image />`** component for automatic image optimization.

3. **Web Vitals**
   - Focus on optimizing **LCP (Largest Contentful Paint)**, **CLS (Cumulative Layout Shift)**, and **FID (First Input Delay)** for better Core Web Vitals scores.
   - Implement performance monitoring tools (e.g., Google Lighthouse, Web Vitals).

---

### **Next.js Specific Guidelines**

1. **Routing and API**
   - Use **Next.js App Router** for routing and organizing pages. Ensure pages are stored under the `app/` directory.
   - Use **Next.js API Routes** under the `pages/api/` directory for backend logic.
   - **Dynamic Routing**: Prefer dynamic routes using file-based routing in the `app/` directory.

2. **Data Fetching**
   - Use **getServerSideProps** and **getStaticProps** for data fetching at the page level.
   - **Static Site Generation (SSG)**: Use SSG with `getStaticProps` for content that does not change frequently.
   - **Server-Side Rendering (SSR)**: Use SSR with `getServerSideProps` when data needs to be updated on each request.

3. **Error Handling**
   - Use **Error Boundaries** for managing JavaScript errors in components.
   - Use **try-catch blocks** for error handling in async functions.

4. **URL Search Parameter Management**
   - Use **`nuqs`** for managing URL search parameters and state. This ensures consistency when dealing with dynamic routes or complex query parameters.

---

### **Additional Guidelines**

1. **Testing**
   - Ensure all critical functionality is tested using Jest and React Testing Library.
   - Test components, utility functions, and hooks with appropriate coverage.

2. **Documentation**
   - Maintain updated documentation in the `README.md` file for easy onboarding of new team members.
   - Document all key components, utility functions, and types.
css
golang
java
javascript
jest
less
next.js
radix-ui
+4 more

First seen in:

icarus/web-template

Used in 1 repository

JavaScript
# Patient Listing Application

Every time you choose to apply a rule(s), explicitly state the rule(s) in the output. You can abbreviate the rule description to a single word or phrase.

## Project Context

A SvelteKit-based patient listing application that integrates with HAPI FHIR server

- Manages and displays patient records
- Interfaces with HAPI FHIR for healthcare data
- Provides a modern, responsive UI for healthcare professionals

## Code Style and Structure

- Write concise, technical TypeScript code with accurate examples
- Use functional and declarative programming patterns
- Prefer iteration and modularization over code duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure repository files as follows:

```
src/
├── lib/            # Shared components and utilities
│   ├── components/ # Reusable Svelte components
│   ├── server/     # Server-only code
│   ├── types/      # TypeScript types
│   ├── utils/      # Helper functions
│   └── fhir/       # FHIR related utilities
├── routes/         # SvelteKit routes (+page.svelte, +server.ts)
├── params/         # SvelteKit parameter matchers
├── hooks.server.ts # Server hooks
└── app.html        # App template

static/            # Static assets
tests/             # Test files
```

## Tech Stack

- SvelteKit
- TypeScript
- Tailwind CSS
- HAPI FHIR
- Docker
- PostgreSQL

## Naming Conventions

- Use lowercase with dashes for directories (e.g., components/patient-card)
- Use PascalCase for component files (e.g., PatientList.svelte)
- Use camelCase for utility files (e.g., fhirUtils.ts)
- Use +page.svelte for route pages
- Use +server.ts for API endpoints

## TypeScript Usage

- Use TypeScript for all code; prefer interfaces over types
- Avoid enums; use const objects with 'as const' assertion
- Use proper FHIR resource types from @types/fhir
- Use $lib alias for imports from lib directory
- Avoid try/catch blocks unless there's good reason to translate or handle error
- Use explicit return types for all functions
- Implement proper type safety for form data

## SvelteKit Specific

- Use proper load functions (+page.server.ts)
- Implement form actions appropriately
- Handle server-side rendering properly
- Use proper error pages (+error.svelte)
- Implement proper client-side navigation
- Use proper environment variables ($env/static/private)

## State Management

- Use Svelte stores for global state
- Implement proper reactive statements
- Use proper lifecycle methods
- Handle subscription cleanup properly

## Syntax and Formatting

- Use "export function" for pure functions
- Follow Svelte component structure (script, style, markup)
- Use reactive declarations ($:) appropriately
- Use proper event dispatching
- Implement TypeScript discriminated unions where needed

## UI and Styling

- Use Tailwind CSS for styling
- Implement responsive design patterns
- Follow healthcare UI/UX best practices
- Consider accessibility requirements
- Use proper loading states
- Implement proper error states

## FHIR Integration

- Use proper FHIR resource types
- Implement proper FHIR search parameters
- Handle FHIR versioning appropriately
- Implement proper FHIR validation
- Use proper FHIR operations

## Error Handling

- Implement proper error pages
- Log errors appropriately for debugging
- Provide user-friendly error messages
- Handle network failures gracefully
- Implement proper validation errors

## Testing

- Write unit tests for utilities and components
- Implement integration tests for FHIR operations
- Test across different browsers
- Test performance and loading states
- Implement proper mock data for tests

## Security

- Implement proper CORS handling
- Sanitize user inputs
- Handle sensitive health data properly
- Follow HIPAA compliance guidelines
- Implement proper authentication

## Git Usage

Commit Message Prefixes:

- "fix:" for bug fixes
- "feat:" for new features
- "perf:" for performance improvements
- "docs:" for documentation changes
- "style:" for formatting changes
- "refactor:" for code refactoring
- "test:" for adding missing tests
- "chore:" for maintenance tasks

Rules:

- Use lowercase for commit messages
- Keep the summary line concise
- Include description for non-obvious changes
- Reference issue numbers when applicable

## Documentation

- Maintain clear README with setup instructions
- Document FHIR interactions and data flows
- Document environment variables
- Don't include comments unless it's for complex logic
- Document HAPI FHIR configuration

## Development Workflow

- Use proper version control
- Implement proper code review process
- Test in multiple environments
- Follow semantic versioning for releases
- Maintain changelog
- Use proper Docker development workflow
css
docker
golang
html
javascript
less
postgresql
react
+3 more
medblocks/ai-coding-fhir-starter

Used in 1 repository

TypeScript
    You are an expert full-stack developer proficient in TypeScript, React, Next.js 14 App Router, and modern UI/UX frameworks (e.g., Tailwind CSS, Shadcn UI, Radix UI), as well as web3 development with Solidity, Viem v2, Wagmi v2. Your task is to produce the most optimized and maintainable Next.js code, following best practices and adhering to the principles of clean code and robust architecture.

    - Use bun for package management
    - Favor named exports for components.
    - Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
    - Structure files with exported components, subcomponents, helpers, static content, and types.
    - Split up complex components into multiple files
    - Find opportunities to simplify code. complexity is bad, prefer simpler solutions that maximize code reusability and DRY-ness over more complex ones.

### Error Handling and Validation

- Prioritize error handling and edge cases:
  - Use early returns for error conditions.
  - Use custom error types for consistent error handling.

### UI and Styling

- Use Shadcn, Tailwind and radix UI for components and styling.
- Implement mobile first approach for responsive design.
- Minimize the use of "magic values" / custom css and prefer tailwind classes.
- Any styles or variables that are used in multiple components should be defined in tailwind config and globals.css

### State Management and Data Fetching

- Use modern state management solutions (e.g., Zustand, TanStack React Query) to handle global state and data fetching.
- Implement validation using Zod for schema validation.
bun
css
javascript
next.js
perl
radix-ui
react
shadcn/ui
+5 more
META-DREAMER/farcastle-frames

Used in 1 repository

TypeScript