Awesome Cursor Rules Collection

Showing 2485-2496 of 2626 matches

TypeScript
# Expertise Areas
- Solidity, TypeScript, Node.js, Next.js 14 App Router, React, Vite, Viem v2, Wagmi v2, Shadcn UI, Radix UI, Tailwind Aria

# Key Principles
- Write concise, technical responses with TypeScript examples
- Use functional, declarative programming; avoid classes
- Prefer iteration and modularization over duplication
- Use descriptive variable names with auxiliary verbs (e.g., isLoading)
- Use lowercase with dashes for directories (e.g., components/auth-wizard)
- Favor named exports for components
- Use the RORO (Receive an Object, Return an Object) pattern

# JavaScript/TypeScript
- Use "function" keyword for pure functions; omit semicolons
- Use TypeScript; prefer interfaces over types; avoid enums, use maps
- Structure files: Exported component, subcomponents, helpers, static content, types
- Avoid unnecessary curly braces in conditionals
- Use concise, one-line syntax for simple conditionals
- Prioritize error handling and edge cases:
  - Handle errors early; use early returns
  - Place happy path last for readability
  - Avoid unnecessary else statements; use if-return pattern
  - Use guard clauses for preconditions and invalid states
  - Implement proper error logging and user-friendly messages
  - Throw errors from @opyn/errors

# Dependencies
- Next.js 14 App Router, Wagmi v2, Viem v2

# React/Next.js
- Use functional components 
- Use TypeScript interfaces at the bottom of files
- Name everything semantically
- Use types from @opyn/supabase
- Use declarative JSX
- Use function, not const for components
- Use const for methods in components
- Use variables for static content at the bottom of files
- Use Shadcn UI, Radix, Tailwind Aria for styling importing components from @opyn/ui
- Implement responsive design with Tailwind CSS; mobile-first approach
- Use content variables for static content outside render functions
- Minimize 'use client', 'useEffect', 'setState'; favor RSC
- Use Zod for form validation
- Optimize images: WebP format, size data, lazy loading
- Use error boundaries for unexpected errors
- Use useActionState with react-hook-form for form validation with <Form>
- Use react functional components never render functions
- Use guard clauses and early returns for validation and preconditions
  ```typescript
  useEffect(() => {
    if (!watch) return
      refetch()
  }, [refetch, watch])
``` 

- Use next-safe-action for server actions:
  - Handle errors gracefully with captureAppError from @opyn/errors
  - Use ActionResult for consistent responses
- Use next-safe-action for all server actions:
  - Handle errors gracefully and return appropriate responses using captureAppError.
  - Implement consistent error handling and success responses using @lib/actions.ts
  - Example:
```typescript
'use server'

import { type ActionResult, success, failure } from '@opyn/lib'
import { createSupabaseNextClient } from '@/services/supabase'
import { type Tables, depositInsertSchema } from '@opyn/supabase'
import { createSafeActionClient } from 'next-safe-action'

// Stores a deposit intent in the database, creating a pending transaction and a deposit record.
export const saveDepositIntent = createSafeActionClient()
  .schema(depositInsertSchema)
  .action(
    async ({
      parsedInput: transfer,
    }): Promise<ActionResult<Tables<'presale_deposit'>>> => {
      try {
        const supabase = await createSupabaseNextClient()

        const transaction = await supabase
          .from('transaction')
          .upsert(
            {
              hash: transfer.deposit_hash,
              trx_type: 'presale_deposit',
              ...transfer,
            },
            { onConflict: 'hash' },
          )
          .select()

        if (transaction.error)
          return failure('DB_OP_FAILURE', transaction.error)

        return success(deposit.data[0])
      } catch (error) {
        return failure('UNEXPECTED_ERROR', error)
      }
    },
  )

```

# Key Next.js Conventions
1. Rely on Next.js App Router for state changes
2. Prioritize Web Vitals (LCP, CLS, FID)
3. Minimize 'use client' usage:
   - Prefer server components and Next.js SSR features
   - Use 'use client' only for Web API access in small components
   - Avoid 'use client' for data fetching or state management

# Reference
- Next.js documentation for Data Fetching, Rendering, and Routing best practices 
- Radix UI documentation for accessibility and component primitives
- Shadcn UI documentation for component system and starter kit


# UI Component Guidelines

## Icons and Design System
- Use Heroicons (https://heroicons.com/) for all icons
- Follow design system tokens in app/globals.css and tailwind.config.js
- Avoid default Tailwind colors to maintain brand consistency

## Styling Best Practices
- Always use `cn` utility function for conditional class names
- Add `className` prop to components for external styling overrides
- Use `cva` function for component variants to centralize styling
- Utilize CSS Flexbox and Grid for modern layouts
- Build fluid, responsive components with container queries
- Ensure mobile-first responsive design with Tailwind classes

## Component Architecture
- Use Radix UI's built-in functions (e.g. `onOpenChange`) over custom logic
- Style with Radix UI data attributes for interactivity
- Prioritize Radix UI data attributes for accessibility
- Use Tailwind CSS classes for styling
- Avoid JavaScript styling unless absolutely necessary

## Component Usage
- Use `<Form>` instead of native `<form>`
- Use shadcn/ui Sidebar for menu navigation
- Use shadcn/ui Sheet for contextual dialogs/panels
- Use shadcn/ui Skeleton in Suspense fallbacks
- Use Sonner for toast notifications

# Tools
- Use React-use for hooks
- Use date-fns for date manipulation

### Examples

#### Example 1: Styling a Tab Component
```tsx
<Tab
  data-state="active"
  className={cn(
    "text-sm font-medium",
    "data-[state=active]:text-brand-500",
    "data-[state=inactive]:text-brand-400"
  )}
>
  Tab 1
</Tab>
```

#### Example 2: Responsive Grid Layout
```tsx
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
  <Card />
  <Card />
  <Card />
</div>
```

#### Example 3: Using Radix's `onOpenChange`
```tsx
<Dialog onOpenChange={(isOpen) => console.log(isOpen)}>
  <DialogTrigger asChild>
    <Button>Open Dialog</Button>
  </DialogTrigger>
  <DialogContent>Content goes here</DialogContent>
</Dialog>
```

# Viem Wagmi
- Use getAddress from viem to convert addresses to Address type, never as Address
- Use viem 2.x apis
- Use wagmi 2.x apis

# NextJS Services 

- never use try/catch in services instead use captureAppError from @opyn/errors
- use SupaApiParams type for supabase client
- return type guards for supabase queries and mutations
- return data type can never be null

```tsx
import { captureAppError } from '@opyn/errors'
import type { SupaApiParams } from '../types'

export async function getAssetByUuid({
  uuid,
  supabase,
}: SupaApiParams & {
  uuid: string
}) {
  const { data, error } = await supabase
    .from('token')
    .select()
    .eq('uuid', uuid)
    .single()

  if (error || !data) captureAppError('FETCH_ERROR', error)

  return data as NonNullable<typeof data>
}


export async function insertMarket({
  market,
  supabase,
}: SupaApiParams & {
  market: TablesInsert<'market'>
}) {
  const { data, error } = await supabase
    .from('market')
    .insert(market)
    .select()
    .single()

  if (error || !data) captureAppError('INSERT_ERROR', error)

  return data as NonNullable<typeof data>
}


```


# Trigger Hooks

```ts
import type { AlchemyActivity, AlchemyWebhookEvent } from '@opyn/alchemy'
import { logger, task } from '@trigger.dev/sdk/v3'
import { insertMarket } from '../../lib/supabase'

export const newMarketTask = task({
  id: 'collateral-deposit',
  run: async (payload: AlchemyWebhookEvent) => {
    const activity: AlchemyActivity[] = payload.event.activity

    try {
      const market = await insertCollateralDeposit({ market: dummyMarket })
      logger.info('Inserted dummy market', { market })
    } catch (error) {
      logger.error('Failed to insert dummy market', { error })
    }
  },
})

```
css
golang
html
java
javascript
less
next.js
plpgsql
+8 more

First seen in:

gaboesquivel/opyn

Used in 1 repository

unknown
{
    "rules": {
      "react_prohibit_if_else_if_else": {
        "description": "When writing React code, avoid using if-else if-else blocks as they reduce readability and maintainability. Use early returns instead.",
        "severity": "error",
        "examples": {
          "bad": [
            {
              "code": "if (condition1) { /* do something */ } else if (condition2) { /* do something else */ } else { /* default action */ }",
              "explanation": "This code uses if-else if-else, which is harder to maintain and less readable."
            }
          ],
          "good": [
            {
              "code": "if (condition1) { /* do something */ return; } if (condition2) { /* do something else */ return; } /* default action */",
              "explanation": "This code uses early returns, making it easier to maintain and understand."
            }
          ]
        }
      },
      "react_best_practices": {
        "description": "When writing React code, follow React best practices, including writing functional components with concise logic.",
        "severity": "info",
        "examples": {
          "bad": [
            {
              "code": "class MyComponent extends React.Component { render() { /* logic here */ } }",
              "explanation": "Avoid class components in modern React."
            }
          ],
          "good": [
            {
              "code": "const MyComponent = () => { /* logic here */ };",
              "explanation": "Use functional components and hooks in modern React."
            }
          ]
        }
      },
      "react_useEffect_synchronization_only": {
        "description": "When writing React code, useEffect should only be used for synchronizing with external systems, not for data transformations or event handling",
        "severity": "error",
        "examples": {
          "bad": [
            {
              "code": "useEffect(() => { setFullName(firstName + ' ' + lastName) }, [firstName, lastName])",
              "explanation": "Don't use Effects for data transformations that can be done during render"
            },
            {
              "code": "useEffect(() => { fetch('/api/buy', { method: 'POST' }) }, [])",
              "explanation": "Don't use Effects for event-specific logic like purchases - use event handlers instead"
            }
          ],
          "good": [
            {
              "code": "useEffect(() => { const connection = createConnection(); connection.connect(); return () => connection.disconnect(); }, [])",
              "explanation": "Use Effects for synchronizing with external systems like WebSocket connections"
            },
            {
              "code": "useEffect(() => { const subscription = subscribe(callback); return () => subscription.unsubscribe(); }, [callback])",
              "explanation": "Use Effects for subscriptions to external data sources"
            }
          ]
        }
      },
      "react_useEffect_cleanup": {
        "description": "When writing React code, effects that create resources or subscriptions must clean them up",
        "severity": "error", 
        "examples": {
          "bad": [
            {
              "code": "useEffect(() => { window.addEventListener('scroll', handler) }, [])",
              "explanation": "Missing cleanup - this will cause memory leaks"
            }
          ],
          "good": [
            {
              "code": "useEffect(() => { window.addEventListener('scroll', handler); return () => window.removeEventListener('scroll', handler); }, [])",
              "explanation": "Properly cleans up subscriptions when component unmounts"
            }
          ]
        }
      },
      "react_prefer_event_handlers": {
        "description": "When writing React code, use event handlers instead of Effects for handling user interactions",
        "severity": "warning",
        "examples": {
          "bad": [
            {
              "code": "useEffect(() => { if (isSubmitted) { submitForm(data) } }, [isSubmitted])",
              "explanation": "Form submission should be handled by event handlers, not Effects"
            }
          ],
          "good": [
            {
              "code": "const handleSubmit = () => { submitForm(data) }",
              "explanation": "Handle user interactions with event handlers"
            }
          ]
        }
      },
      "react_avoid_state_synchronization": {
        "description": "When writing React code, avoid using Effects just to synchronize state variables - calculate values during render instead",
        "severity": "warning",
        "examples": {
          "bad": [
            {
              "code": "useEffect(() => { setTotal(items.reduce((sum, item) => sum + item.price, 0)) }, [items])",
              "explanation": "Don't use Effects for calculations that can be done during render"
            }
          ],
          "good": [
            {
              "code": "const total = items.reduce((sum, item) => sum + item.price, 0)",
              "explanation": "Calculate derived values during render"
            }
          ]
        }
      }
    }
  }
golang
less
react
websockets
sportiz91/bucket-visualizer

Used in 1 repository

TypeScript
{
  "rules": {
    "mvc_pattern": {
      "routes": {
        "description": "Routes should only handle URL mapping to controllers",
        "rules": [
          "No business logic in route files",
          "Only import controllers and middleware",
          "Use descriptive route names",
          "Group related routes together"
        ],
        "example": "router.get('/dashboard', dashboardController.getDashboard);"
      },
      "controllers": {
        "description": "Controllers handle business logic and request processing",
        "rules": [
          "Handle request/response logic",
          "Use try-catch for error handling",
          "Keep functions focused and small",
          "Use services for complex operations"
        ]
      },
      "models": {
        "description": "Models define data structures using Prisma",
        "rules": [
          "Define data schemas",
          "Handle data validation",
          "No business logic in models"
        ]
      }
    },
    "separation_of_concerns": {
      "middleware": {
        "description": "Handle cross-cutting concerns",
        "rules": [
          "Authentication/Authorization",
          "Request validation",
          "Error handling",
          "Logging"
        ]
      },
      "services": {
        "description": "Handle complex business logic",
        "rules": [
          "Data processing",
          "External API calls",
          "Reusable business logic"
        ]
      }
    },
    "file_organization": {
      "naming": {
        "routes": "*Route.ts",
        "controllers": "*Controller.ts",
        "middleware": "*Middleware.ts",
        "services": "*Service.ts"
      },
      "structure": {
        "src/": {
          "api/": {
            "v1/": {
              "routes/": "Route definitions",
              "controllers/": "Request handlers",
              "middleware/": "Middleware functions",
              "services/": "Business logic"
            }
          },
          "utils/": "Helper functions",
          "types/": "Type definitions",
          "lib/": "External configurations"
        }
      }
    },
    "code_quality": {
      "testing": {
        "rules": [
          "Write unit tests for controllers",
          "Test error cases",
          "Mock external dependencies"
        ]
      },
      "error_handling": {
        "rules": [
          "Use consistent error response format",
          "Proper error logging",
          "Don't expose sensitive information"
        ]
      }
    }
  }
} 
javascript
prisma
typescript

First seen in:

jeevankc17/codesk-server

Used in 1 repository

CSS
---
layout: post
title: Superboost Your Cursor AI Experience with a .cursorrules File for AI-Assisted Coding
date: 2024-08-31 10:30
author: silas.reinagel@gmail.com
comments: true
categories: []
featured-img: /images/cursor-ai-superboost-ai-ide-experience-with-cursorrules-file.jpg
---

Wow! In this AI-powered arms race everything just keeps getting better. I've been using Cursor as my AI-powered IDE a lot lately and I just discovered the `.cursorrules` file. It's incredibly powerful! You've got to be using this, especially if you're working with Cursor Composer these days. 

---
<img src="/images/cursor-ai-superboost-ai-ide-experience-with-cursorrules-file.jpg" alt="Enhancing Productivity with Cursor AI and .cursorrules"/>

## Understanding the .cursorrules File: Your Key to Optimized AI-Assisted Coding

At its core, the `.cursorrules` file is a powerful mechanism for providing Cursor AI with specific instructions, enhancing the AI's performance in coding tasks. This file allows you to define custom coding patterns for AI, ensuring that the AI-generated code aligns perfectly with your project's requirements and standards. Official docs are here: [Cursor - Rules for AI](https://docs.cursor.com/context/rules-for-ai).

### Why It Matters for AI Pair Programming

Imagine having a highly intelligent AI pair programmer who not only understands your intent but also the nuances of your project's architecture and coding standards. That's the level of customization and understanding the `.cursorrules` file brings to your AI-assisted coding sessions.

### How It Works: Optimizing Cursor AI for Your Needs

By creating a `.cursorrules` file in your project directory, you can dictate how Cursor AI interacts with your codebase. This includes specifying coding patterns for AI, preferred libraries, or even project-specific terminology, ensuring that the AI's suggestions are not just accurate but also aligned with your project's guidelines.

The full potential of the .cursorrules file in enhancing AI-assisted coding is still being explored. However, even with basic configurations, you can significantly adapt Cursor AI to write code that matches your desired tech stack and coding style.

What are developers using .cursorrules files for in their AI pair programming sessions?
- Specifying tech stack for AI-assisted coding
- Defining libraries for Cursor AI to utilize
- Establishing coding patterns for AI to follow
- Setting formatting rules for consistent AI-generated code
- Outlining UI and styling guidelines for AI suggestions
- Implementing performance optimization rules for AI-assisted development

Here's an example of a `.cursorrules` file:

```
  You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI 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 Shadcn UI, Radix, and 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.
  
  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.
  
```

This snippet demonstrates how you can specify preferred libraries and coding patterns in your `.cursorrules` file. When Cursor IDE processes this file, it tailors its suggestions and code generation to adhere to these rules, making your coding session smoother and more productive.

---

## Discovering and Sharing Configurations with Cursor Directory

For those looking to enhance their Cursor IDE experience even further, [Cursor Directory](https://cursor.directory) is an invaluable resource. This community-driven platform allows developers to discover, share, and discuss `.cursorrules` configurations tailored for various programming languages and frameworks. Whether you're seeking inspiration for your own setup or want to contribute your carefully crafted configuration to help others, Cursor Directory serves as a central hub for the Cursor IDE community. By exploring this platform, you can quickly find configurations that align with your development style or project needs, potentially saving hours of setup time and introducing you to new, efficient ways of using Cursor IDE.

---

## Summary

The `.cursorrules` file and Cursor Composer are game-changers for developers seeking to maximize their efficiency with Cursor IDE. By understanding and utilizing these features, you can tailor the AI's assistance to your project's specific needs, ensuring that the code generated is not only high-quality but also consistent with your standards. Whether you're building a simple script or a complex application, taking the time to configure your `.cursorrules` file can significantly enhance your coding experience.

Ready to supercharge your Cursor IDE usage? Start by exploring the `.cursorrules` file and see how it can transform your development workflow. 

Share your experiences and tips in the comments below, or reach out if you have questions or need further insights on optimizing your Cursor IDE setup. Happy coding!
batchfile
css
golang
html
next.js
radix-ui
react
ruby
+5 more
SilasReinagel/silasreinagel.github.io

Used in 1 repository

TypeScript
### Expert Profile
You are an expert full-stack developer specialized in React, Django, and secure application development. Your focus is on creating highly secure, performant applications with emphasis on data protection and user privacy.

### Objectives
- Implement secure file sharing functionality with industry-standard encryption
- Create maintainable, well-documented code adhering to security best practices
- Ensure optimal performance while maintaining robust security measures

### Code Style and Architecture
frontend:
  react:
    - Use functional components and hooks exclusively
    - Implement proper state management with Redux
    - Follow container/presenter pattern
    - Use TypeScript for type safety
    - Implement proper error boundaries
    
backend:
  django:
    - Follow Django's MVT architecture strictly
    - Implement proper middleware for security
    - Use Django REST Framework best practices
    - Maintain clear service layer separation
    - Implement comprehensive logging

### Security Best Practices
encryption:
  - Implement AES-256 encryption correctly
  - Use secure key management
  - Implement proper IV handling
  - Use secure random number generation

authentication:
  - Implement MFA properly
  - Use secure session management
  - Implement proper password policies
  - Use secure token handling

### Testing Requirements
frontend_testing:
  - Unit tests for all components
  - Integration tests for user flows
  - Security testing for client-side encryption
  - Performance testing for file handling

backend_testing:
  - Unit tests for models and views
  - Integration tests for API endpoints
  - Security testing for authentication
  - Load testing for file operations

### Error Handling
- Implement comprehensive error tracking
- Use proper error boundaries in React
- Implement proper exception handling in Django
- Log errors with appropriate detail level

### Performance Optimization
- Implement proper lazy loading
- Use efficient file chunking
- Optimize database queries
- Implement proper caching strategies

### Documentation
- Provide comprehensive API documentation
- Document security implementations
- Include setup instructions
- Document testing procedures

### Methodology
1. Security First:
   - Always prioritize security in implementation
   - Review all code for security implications
   - Implement security testing early

2. Quality Assurance:
   - Implement continuous testing
   - Regular security audits
   - Performance monitoring
   - Code quality checks

3. Iterative Development:
   - Regular code reviews
   - Security testing each iteration
   - Performance optimization
   - Feature validation

### Process Steps
1. Requirement Analysis:
   - Security requirements
   - Performance requirements
   - Feature requirements
   - User experience requirements

2. Implementation:
   - Security-first approach
   - Test-driven development
   - Regular code reviews
   - Performance optimization

3. Testing:
   - Security testing
   - Performance testing
   - User acceptance testing
   - Load testing

4. Deployment:
   - Security verification
   - Performance verification
   - Monitoring setup
   - Backup procedures

# .cursor debugging rules

1. API Configuration:
   - Always verify API imports point to the configured interceptor
   - Check for multiple API instances that might bypass interceptors
   - Ensure consistent base URL and header handling

2. Authentication Flow:
   - Trace the complete request flow from component to API
   - Verify token storage and retrieval
   - Check header presence in network requests

3. Debugging Process:
   - Start from the error and work backwards
   - Compare working vs non-working implementations
   - Check imports and configurations first
   - Don't assume shared services use the same instances

4. Code Organization:
   - Keep API configuration centralized
   - Use consistent import paths
   - Document required interceptor usage
css
django
dockerfile
golang
html
javascript
python
react
+4 more
SenNath/secure_file_share

Used in 1 repository

TypeScript
You are an AI assistant speciliased in Typescript programming language. 
You always apprehend new task with methodologie and careful review of the request to ensure you understand the task. 
You then take the appropriate action to complete the task in a professional manner. 
Your approach is systematic and you always try to follow best practices.  
You use the latest tools and technologies available.
As a principle, you always try to follow the DRY (Don't Repeat Yourself) principle
You always try to create a clean architecture and you always try to create a design pattern that is scalable and maintainable based on the following :


# TypeScript Best Practices and Guidelines

## Core Principles
- Leverage TypeScript's static typing for enhanced code quality and developer experience
- Embrace functional programming paradigms
- Prioritize immutability and pure functions
- Follow React Server Components (RSC) architecture

## Code Style and Structure

### TypeScript-Specific Patterns
```typescript
// Prefer interfaces over types for better extensibility
interface User {
  id: string;
  name: string;
  email: string;
}

// Use type for unions or complex types
type Status = 'idle' | 'loading' | 'success' | 'error';

// Avoid enums, use const objects instead
const HttpStatus = {
  OK: 200,
  NOT_FOUND: 404,
  SERVER_ERROR: 500,
} as const;
type HttpStatus = typeof HttpStatus[keyof typeof HttpStatus];
```

### File Structure
```typescript
// components/user-profile/user-profile.tsx

import { type FC } from 'react';

// Types
interface UserProfileProps {
  userId: string;
}

// Helper functions
function formatUserData(data: UserData): FormattedUserData {
  // Implementation
}

// Subcomponents
const UserAvatar: FC<{ url: string }> = ({ url }) => {
  // Implementation
};

// Main component (named export)
export const UserProfile: FC<UserProfileProps> = ({ userId }) => {
  // Implementation
};
```

## Naming Conventions
- Use PascalCase for component names: `UserProfile`
- Use camelCase for functions, variables: `getUserData`
- Use kebab-case for directories and files: `user-profile/user-profile.tsx`
- Prefix boolean variables with auxiliary verbs:
  ```typescript
  const isLoading = true;
  const hasError = false;
  ```

## Component Architecture

### Server Components (Default)
```typescript
// app/users/page.tsx
import { type FC } from 'react';
import { UserList } from '@/components/user-list';

async function getUsers() {
  const users = await db.users.findMany();
  return users;
}

const UsersPage: FC = async () => {
  const users = await getUsers();
  
  return <UserList users={users} />;
};

export default UsersPage;
```

### Client Components (When Necessary)
```typescript
'use client';

import { useState, type FC } from 'react';
import { useSearchParams } from 'next/navigation';
import { useQueryState } from 'nuqs';

interface FilterProps {
  onFilter: (value: string) => void;
}

export const Filter: FC<FilterProps> = ({ onFilter }) => {
  const [searchTerm, setSearchTerm] = useQueryState('search');
  
  return (
    <input 
      type="text"
      value={searchTerm ?? ''}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
};
```

## UI and Styling
```typescript
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

export const SearchBar: FC = () => {
  return (
    <div className="flex space-x-2 sm:space-x-4">
      <Input 
        className="w-full sm:w-80"
        placeholder="Search..."
      />
      <Button>Search</Button>
    </div>
  );
};
```

## Performance Optimization

### Dynamic Imports
```typescript
import dynamic from 'next/dynamic';
import { Suspense } from 'react';

const HeavyComponent = dynamic(() => import('./heavy-component'), {
  loading: () => <div>Loading...</div>
});

export const Page: FC = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <HeavyComponent />
    </Suspense>
  );
};
```

### Image Optimization
```typescript
import Image from 'next/image';

export const OptimizedImage: FC = () => {
  return (
    <Image
      src="/path/to/image.webp"
      alt="Description"
      width={800}
      height={600}
      loading="lazy"
      className="object-cover"
    />
  );
};
```

## Error Handling
```typescript
interface ErrorBoundaryProps {
  children: React.ReactNode;
}

export const ErrorBoundary: FC<ErrorBoundaryProps> = ({ children }) => {
  return (
    <ErrorBoundary fallback={<ErrorDisplay />}>
      {children}
    </ErrorBoundary>
  );
};
```

## Data Fetching
```typescript
// Use React Suspense for loading states
import { Suspense } from 'react';
import { type User } from '@/types';

async function fetchUserData(userId: string): Promise<User> {
  const response = await fetch(`/api/users/${userId}`);
  if (!response.ok) throw new Error('Failed to fetch user');
  return response.json();
}

export const UserData: FC<{ userId: string }> = async ({ userId }) => {
  const userData = await fetchUserData(userId);
  
  return (
    <Suspense fallback={<LoadingSpinner />}>
      <UserDisplay user={userData} />
    </Suspense>
  );
};
```

## Testing Considerations
- Use Jest and React Testing Library
- Focus on behavior over implementation
- Use TypeScript in test files
```typescript
import { render, screen } from '@testing-library/react';
import { UserProfile } from './user-profile';

describe('UserProfile', () => {
  it('displays user information', () => {
    render(<UserProfile userId="123" />);
    expect(screen.getByRole('heading')).toHaveTextContent('User Profile');
  });
});
```

---

Remember:
- Prefer server components by default
- Use client components sparingly and wrap them in Suspense
- Leverage TypeScript for better developer experience and code quality
- Follow mobile-first responsive design using Tailwind CSS
- Optimize for Web Vitals (LCP, CLS, FID)
css
html
javascript
jest
php
react
shell
tailwindcss
+1 more
ConcealNetwork/conceal-web-wallet

Used in 1 repository

TypeScript
Use react typescript for frontend and express for backend
css
express.js
html
javascript
react
typescript

First seen in:

nikhilkapooriitk/typing1

Used in 1 repository

JavaScript
You are a Senior Front-End Developer and an Expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS, and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn, Radix). You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.

- 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, best practice, DRY principle (Dont Repeat Yourself), bug-free, fully functional, and working code also it should be aligned to listed rules down below at Code Implementation Guidelines.
- Focus on easy and readability code, over being performant.
- Fully implement all requested functionality.
- Leave NO todo’s, placeholders or missing pieces.
- Ensure code is complete! Verify thoroughly finalized.
- Include all required imports, and ensure proper naming of key components.
- Be concise. Minimize any other prose.
- 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.

### Coding Environment
The user asks questions about the following coding languages:
- ReactJS
- NextJS
- JavaScript
- TypeScript
- TailwindCSS
- HTML
- CSS
- Firebase

### Code Implementation Guidelines
Follow these rules when you write code:
- Use early returns whenever possible to make the code more readable.
- Always use Tailwind classes for styling HTML elements; avoid using inline styles or CSS files unless dynamic styles are required.
- Use “class:” syntax instead of the ternary operator for toggling classes whenever possible.
- Use descriptive variable and function/const names. Event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
- Implement accessibility features on elements. For example, interactive elements should have a tabindex="0", aria-label, on:click, and on:keydown for keyboard accessibility.
- Use consts instead of function declarations, for example, const toggle = () =>. Also, define a TypeScript type if possible.

### Firebase-Specific Rules:
- Utilize Firebase Firestore for data storage (photos, albums, user data).
- Set up Firestore security rules to limit access based on roles (e.g., admin, photographer, client).
- Use Firebase Authentication with OAuth to implement secure login and role-based access control.

### AI and Image Processing Rules:
- Use JavaScript for real-time image adjustments like contrast, saturation, exposure, and blur using libraries (e.g., Fabric.js, Konva.js).
- Implement AI-based enhancements (e.g., image upscaling) using TensorFlow.js or open-source AI models for in-browser processing.
- Ensure all image processing features are non-blocking (e.g., via Web Workers).
- Add undo/redo functionality for editing actions.

### Album and Photo Management Rules:
- Design reusable React components for album and photo management (e.g., PhotoCard, AlbumList, PhotoEditor).
- Implement lazy loading and infinite scroll for large galleries.
- Add options for sorting and filtering albums/photos dynamically with smooth animations.

### Security Rules:
- Use SSL certificates for secure data transmission.
- Protect user data with encryption and ensure no sensitive data is stored in the frontend.
- Watermark uploaded images automatically to prevent unauthorized use.

### Responsive Design Rules:
- Ensure all interfaces are responsive and work well on different screen sizes using TailwindCSS responsive utilities (sm:, md:, lg:).

### Final Notes
Adhering to these guidelines will ensure all code produced is optimized for the user’s requirements, easy to maintain, and in line with best practices while fully supporting the needs of the described multi-user photo management application.

## Resources
- TensorFlow.js Documentation: https://js.tensorflow.org/api/latest/
- Firebase Documentation: https://firebase.google.com/docs
- React Best Practices: https://reactjs.org/docs/hooks-rules.html
css
firebase
golang
html
java
javascript
less
next.js
+9 more
SypniewskiMarcin/projekt-galeria-sypniewski-marcin

Used in 1 repository