Awesome Cursor Rules Collection

Showing 973-984 of 1033 matches

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

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

TypeScript
# Codebase Overview

This codebase is a web application built with TypeScript, React, and Next.js, utilizing Shadcn UI, Radix, and Tailwind CSS for styling. It features a landing page, authentication flows, and a dashboard for logged-in users, integrating Supabase for backend services.

# Stack and Key Technologies

- Frontend: React with Next.js (App Router)
- Language: TypeScript
- UI Components: Shadcn UI, NextUI, MagicUI, Radix
- Styling: Tailwind CSS
- Backend Services: Supabase (authentication, database, storage)
- Icons: Iconify

# Code Style and Structure

- Functional and declarative programming patterns
- Modular file structure: exported component, subcomponents, helpers, static content, types
- Descriptive variable names (e.g., isLoading, hasError)
- Lowercase with dashes for directories (e.g., components/auth-wizard)
- Named exports for components

# TypeScript Usage

- Interfaces preferred over types
- Avoid enums; use maps instead
- Functional components with TypeScript interfaces

# Syntax and Formatting

- Use "function" keyword for pure functions
- Concise conditional syntax
- Declarative JSX

# Error Handling and Validation

- Early returns and guard clauses
- Zod for form validation
- Error boundaries for unexpected errors
- Server Actions model expected errors as return values

# UI and Styling

- Shadcn UI, NextUI, MagicUI, Radix, and Tailwind Aria for components
- Responsive design with Tailwind CSS (mobile-first approach)

# Performance Optimization

- Minimize 'use client', 'useEffect', and 'setState'
- Favor React Server Components (RSC)
- Dynamic loading for non-critical components
- Image optimization: WebP format, size data, lazy loading

# Key Conventions

- 'nuqs' for URL search parameter state management
- Optimize Web Vitals (LCP, CLS, FID)
- Limited 'use client' usage:
  - Favor server components and Next.js SSR
  - Use only for Web API access in small components
  - Avoid for data fetching or state management

# Application Structure

## Authentication

- Login: Email/password and GitHub OAuth (frontend/app/(landing-page)/login/action.ts)
- Signup: Email and password (frontend/app/(landing-page)/login/action.ts)
- Logout: frontend/app/(landing-page)/logout/action.ts
- Email Confirmation: frontend/app/auth/callback/confirm/route.ts

## User Interface

- Landing Page: SubmitButton, LoginPage, LogoutModal components
- Dashboard: Personalized content and navigation sidebar
- Error Handling: Generic error component with retry mechanism

## Navigation and Layout

- Navbar: Responsive design for landing and public pages
- Sidebar: Collapsible for dashboard navigation

Follow Next.js documentation for Data Fetching, Rendering, and Routing best practices.
css
dockerfile
golang
javascript
next.js
oauth
radix-ui
react
+4 more
humblFINANCE/humblFINANCE-frontend

Used in 1 repository

Python
{
  "name": "CrewAI Project Rules",
  "description": "Standard conventions for CrewAI v0.95.0 projects with examples",
  "version": "1.0.0",
  "metadata": {
    "project_type": "python",
    "framework": "crewai",
    "maintainer": "CTK Advisors"
  },
  "rules": [
    {
      "name": "Project Structure",
      "description": "Standard CrewAI project structure",
      "pattern": "**/*",
      "conventions": [
        "Use src/<project_name> for main project code",
        "Keep configuration files in config/ directory",
        "Store custom tools in tools/ directory",
        "Place templates in templates/ directory",
        "Use pyproject.toml and poetry for dependency management",
        "Include .env.example for environment variables",
        "Example structure:",
        "```",
        "src/",
        "  └── your_project/",
        "      ├── config/",
        "      │   ├── agents.yaml",
        "      │   ├── tasks.yaml",
        "      │   └── templates.json",
        "      ├── tools/",
        "      │   ├── browser_tools.py",
        "      │   ├── file_tools.py",
        "      │   └── search_tools.py",
        "      ├── templates/",
        "      ├── crew.py",
        "      └── main.py",
        "```"
      ]
    },
    {
      "name": "Crew Definitions",
      "description": "Guidelines for defining CrewAI crews",
      "pattern": "**/crew.py",
      "conventions": [
        "Use @CrewBase decorator for crew classes",
        "Define agents_config and tasks_config as class variables",
        "Use @agent decorator for agent definitions",
        "Use @task decorator for task definitions",
        "Use @crew decorator for crew assembly",
        "Example:",
        "```python",
        "@CrewBase",
        "class ExampleCrew:",
        "    agents_config = 'config/agents.yaml'",
        "    tasks_config = 'config/tasks.yaml'",
        "",
        "    @agent",
        "    def expert_agent(self) -> Agent:",
        "        return Agent(",
        "            config=self.agents_config['expert'],",
        "            allow_delegation=False,",
        "            tools=[SearchTools.search_internet],",
        "            verbose=True",
        "        )",
        "",
        "    @task",
        "    def analyze_task(self) -> Task:",
        "        return Task(",
        "            config=self.tasks_config['analyze'],",
        "            agent=self.expert_agent()",
        "        )",
        "",
        "    @crew",
        "    def crew(self) -> Crew:",
        "        return Crew(",
        "            agents=self.agents,",
        "            tasks=self.tasks,",
        "            process=Process.sequential,",
        "            verbose=True",
        "        )",
        "```"
      ]
    },
    {
      "name": "Tool Definitions",
      "description": "Conventions for CrewAI tools with examples from the project",
      "pattern": "**/tools/*.py",
      "conventions": [
        "Use @tool decorator with clear description",
        "Implement standard tool interface",
        "Include proper error handling",
        "Group tools by functionality",
        "Example browser tool:",
        "```python",
        "class BrowserTools:",
        "    @tool('Scrape website content')",
        "    def scrape_and_summarize_website(website):",
        "        '''Useful to scrape and summarize website content'''",
        "        # Implementation",
        "```",
        "Example file tool:",
        "```python",
        "class FileTools:",
        "    @tool('Write File with content')",
        "    def write_file(data):",
        "        '''Expects pipe-separated path and content: ./path|content'''",
        "        try:",
        "            path, content = data.split('|')",
        "            # Implementation",
        "        except Exception:",
        "            return 'Error with input format'",
        "```"
      ]
    },
    {
      "name": "Configuration Management",
      "description": "Guidelines for configuration files",
      "pattern": "**/config/*.{yaml,json}",
      "conventions": [
        "Use YAML for agent and task configurations",
        "Use JSON for templates and static data",
        "Example agents.yaml structure:",
        "```yaml",
        "senior_react_engineer:",
        "  role: Senior React Engineer",
        "  goal: Build high-quality React components",
        "  backstory: Expert in React development",
        "senior_content_editor:",
        "  role: Senior Content Editor",
        "  goal: Create engaging content",
        "  backstory: Experienced in content creation",
        "```",
        "Example templates.json structure:",
        "```json",
        "{",
        "  \"templates\": {",
        "    \"basic\": {",
        "      \"description\": \"Basic landing page\",",
        "      \"components\": [\"Hero\", \"Features\"]",
        "    }",
        "  }",
        "}"
      ]
    },
    {
      "name": "Environment Variables",
      "description": "Environment variable structure",
      "pattern": "**/.env*",
      "conventions": [
        "Required variables from project:",
        "```",
        "BROWSERLESS_API_KEY=your_key_here",
        "SERPER_API_KEY=your_key_here",
        "OPENAI_API_KEY=your_key_here",
        "```",
        "Include descriptions in .env.example:",
        "```",
        "# Browser automation API key",
        "BROWSERLESS_API_KEY=",
        "",
        "# Search API key",
        "SERPER_API_KEY=",
        "",
        "# OpenAI API key for agent interactions",
        "OPENAI_API_KEY=",
        "```"
      ]
    },
    {
      "name": "Tool Integration",
      "description": "Patterns for tool integration with agents",
      "pattern": "**/crew.py",
      "conventions": [
        "Group related tools in agent definitions",
        "Example from project:",
        "```python",
        "@agent",
        "def senior_react_engineer_agent(self) -> Agent:",
        "    return Agent(",
        "        config=self.agents_config['senior_react_engineer'],",
        "        allow_delegation=False,",
        "        tools=[",
        "            SearchTools.search_internet,",
        "            BrowserTools.scrape_and_summarize_website,",
        "            TemplateTools.learn_landing_page_options,",
        "            FileTools.write_file",
        "        ] + self.toolkit.get_tools(),",
        "        verbose=True",
        "    )",
        "```"
      ]
    },
    {
      "name": "Testing Conventions",
      "description": "Standards for test files and testing practices",
      "pattern": "**/tests/**/*.py",
      "conventions": [
        "Use pytest for testing",
        "Name test files with test_ prefix",
        "Group tests by functionality",
        "Use fixtures for common setup",
        "Example test structure:",
        "```python",
        "import pytest",
        "from src.dev_crew.tools import SearchTools",
        "",
        "@pytest.fixture",
        "def search_tool():",
        "    return SearchTools()",
        "",
        "def test_search_internet(search_tool):",
        "    '''Test internet search functionality'''",
        "    result = search_tool.search_internet('test query')",
        "    assert result is not None",
        "    assert isinstance(result, dict)",
        "```"
      ]
    },
    {
      "name": "Type Checking",
      "description": "Type annotation and checking standards",
      "pattern": "**/*.py",
      "conventions": [
        "Use type hints for all function parameters and return values",
        "Enable strict type checking with mypy",
        "Use Optional[] for nullable types",
        "Example type usage:",
        "```python",
        "from typing import Optional, List, Dict",
        "",
        "def process_search_results(",
        "    query: str,",
        "    results: List[Dict[str, str]],",
        "    max_results: Optional[int] = None",
        ") -> List[str]:",
        "    '''Process search results with proper typing'''",
        "    filtered = results[:max_results] if max_results else results",
        "    return [result['title'] for result in filtered]",
        "```"
      ]
    }
  ]
}
dockerfile
golang
less
openai
python
react

First seen in:

chrisknu/dev_crew

Used in 1 repository

TypeScript
Project Overview:
Typyst is a modern, desktop-based text editor application built using Electron and React, focusing on providing advanced writing assistance and suggestions. The application features a clean, modular architecture with clear separation of concerns between the main process and renderer components.

Technical Stack:
- Frontend: React with TypeScript
- Desktop Runtime: Electron
- Editor Framework: TipTap (ProseMirror-based rich text editor)
- Build Tools: Vite
- Writing Assistant: Vale
- AI Integration: LLama
- State Management: React Hooks
- Styling: CSS Modules

Architecture:
1. /electron
   - Main Process Architecture:
     * index.ts: Main entry point
       - Window management and lifecycle
       - Custom frameless window with macOS integration
       - Development tools configuration
       - App event handling (window creation, quit, activate)
     
     * preload.ts: Electron-Renderer Bridge
       - Secure IPC communication setup
       - Exposes safe APIs to renderer process
       - Type-safe bridge interfaces
       - File system operations bridge
       - Vale integration bridge

   - RPC (Remote Procedure Call) System:
     * fileSystemRpc.ts: File operations handler
       - Markdown file processing
       - File system access
       - Content conversion utilities
     * llmRpc.ts: LLama model integration
       - AI-powered suggestions
       - Context-aware completions
     * Bidirectional communication using birpc

   - Services:
     * vale/: Writing assistance service
       - Style checking integration
       - Real-time linting
       - Custom rule management
     * autocomplete/: Text completion service
       - AI-powered suggestions
       - Context-aware completions
       - Prediction management

2. /src
   - Application Architecture:
     * index.tsx: Application Entry Point
       - React initialization
       - Root component mounting
       - IPC bridge setup
       - Global style injection
     
     * /app: Core Application Setup
       - App.tsx: Root component
       - Application-wide providers
       - Global state management
       - Layout structure

   - Feature-based Organization:
     * /features: Core Application Features
       - editor/: Main Editor Implementation
         * components/: React Components
           - Editor.tsx: Main editor wrapper
             * Theme provider integration
             * Global layout management
           - EditorContent.tsx: Core editor functionality
             * TipTap integration
             * Content management
             * Feature coordination
           - FileSelector.tsx: File handling
             * Markdown file processing
             * File input management
           - MenuBar.tsx: Toolbar and controls
           - ValeSidebar.tsx: Writing suggestions panel
           - ErrorOverlay.tsx: Error display
           - RawContentPreview.tsx: Debug view
         * hooks/: Custom React Hooks
           - useEditorCore.ts: Core editor state and operations
           - useValeState.ts: Writing suggestions management
           - useEditorShortcuts.ts: Keyboard interactions
           - useEditorSpellcheck.ts: Spellcheck integration
         * services/: Feature-specific Logic
           - fileSystemService.ts: File operations
           - valeService.ts: Vale integration
           - eventHandlers.ts: Editor event management
         * types/: Feature-specific Types
         * constants/: Feature Configuration

       - theme/: Theming System
         * themeContext.tsx: Theme provider
         * themes/: Theme definitions
         * hooks/: Theme utilities

   - Editor Extensions:
     * /extensions: TipTap Extensions
       - extensions.ts: Extension configuration
       - indent/: Indentation handling
       - predictions/: AI suggestions
       - Custom ProseMirror plugins

   - Shared Resources:
     * /types: Global TypeScript Definitions
       - Global type declarations
       - API interfaces
       - Shared type utilities
     
     * /services: Shared Business Logic
       - Authentication
       - State management
       - Shared utilities
     
     * /styles: Global Styling
       - index.css: Global styles
       - Editor.css: Editor-specific styles
       - MenuBar.css: Toolbar styles
       - Theme variables

Key Features:
1. Rich Text Editing
   - TipTap/ProseMirror foundation
   - Advanced text formatting
   - Code block highlighting
   - Custom extensions
   - Real-time content updates

2. Writing Assistance
   - Vale integration for style checking
   - Real-time writing suggestions
   - Customizable rules and style guides
   - Interactive suggestion sidebar
   - Warning/error management
   - Ignorable warnings system

3. File Management
   - Markdown file support
   - File selection interface
   - Content conversion utilities
   - Error handling

4. Theme Support
   - Theme system
   - Customizable styling
   - Dark/light mode support

5. Advanced Editor Features
   - Keyboard shortcuts
   - Spellchecking
   - Raw content preview
   - Error handling
   - Sidebar management

Core Components:
1. Editor Component
   - Modular architecture:
     * Editor.tsx: Theme and layout wrapper
     * EditorContent.tsx: Core functionality
     * FileSelector.tsx: File handling
   - Feature integration through hooks:
     * useEditorCore
     * useValeState
     * useEditorShortcuts
     * useEditorSpellcheck

2. MenuBar
   - Editing tools and controls
   - Feature toggles
   - Raw output toggle

3. ValeSidebar
   - Writing suggestions display
   - Warning/error management
   - Interactive feedback
   - Ignorable warnings system

Technical Features:
1. RPC System
   - birpc for Electron-React communication
   - Structured service architecture
   - Type-safe interfaces

2. AI Integration
   - LLama model integration
   - AI-powered writing assistance
   - Context-aware suggestions

3. Extension System
   - Modular editor extensions
   - Custom TipTap extensions
   - ProseMirror plugins

Development:
- Modern development tooling
- TypeScript for type safety
- Linting and formatting
- Automated setup scripts
- Cross-platform support
- Modular component architecture
- Hook-based state management
css
html
javascript
less
react
typescript
vite
Mats-Dodd/typyst-electron

Used in 1 repository

JavaScript
You are an expert in TypeScript, Node.js, Shadcn UI, Radix, Tailwind, and xbar plugins.  You are also have deep domain expertise in the renewable energy sector, an understanding of the grid's carbon intensity, and a great source of inspiration on how to help electricity customers reduce their carbon footprint.  

Key Principles
- 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':
- Use only for Web API access in small components.
- Avoid for data fetching or state management.
javascript
radix-ui
react
shadcn/ui
tailwindcss
typescript
jasonm-jones/carbon-intensity-xbar

Used in 1 repository