Awesome Cursor Rules Collection

Showing 445-456 of 1033 matches

TypeScript
1. Project Overview
Goal: Assist a beginner developer to build an a.i. coding assistant.

The user will provide the coding assistant with all the Jira ticket details by pasting in a Jira ticket number.  The assistant will also be given a large file that contains concatentated files related to the Jira ticking implemenation.  

There is a checkbox-based file directory tree navigation UI that allows the user to select the files that are relevant to the ticket to be included in the concatenation.  

There are also a number of additional reference files that can optionally be included in the prompt that is sent via api call to the LLM.

Because you are working with a beginner code, always be explicit and detailed about which files to change, how to change them, and where exactly the files are located.

The project is a multi-step wizard:

# STEP 1 # 

Jira Ticket - pasting in a Jira ticket number to retrieve the entire ticket details.  It should be possible to include and reference multiple tickets by separating them with commas.  The contents of all Jira indicated would be retrieved and included in the LLM prompt.

# STEP 2 # 

Selective File Concatenation - using a checkbox-based file directory tree navigation UI to navigate locally and select all the files that are relevant to the ticket and pull request. 
1.  Allow the user to enter a root directory path as a starting point
2.  Display the full file directory tree starting from the root directory, with checkboxes beside each file and subdirectory
3.  Allow selective checking of the boxes to include in the concatenation
4.  When checking the box beside a folder, it should include everything in that folder, including sub-folders and files
5. When "Next" is clicked, the system then concatenates all the selected files, according to the logic rules outlined in the program
6.  It should have an easy-to-use UI

Note: We're selecting local files and folders to concatenate into the markdown file.  So the concatention is a local tree navigation with checkboxes.

# STEP 3 # 

Select Additional Files needed for context - such as coding standards, DB schema, or any other reference material.

# STEP 4 # 

Submit - submitting all the data to the LLM for analysis and development of a highly-detailed action plan for ipmlementing the Jira tickets in a way that passes code review and accpetance criteria.  The submitted api call to the LLM includes a system prompt which instructs the LLM, along with the Jira ticket details, the concatenated file, and any additional files needed for context.

# STEP 5 # 

The detailed action plan is returned to the user, with specific instructions for each file that needs to be changed, where the files are located, and what the changes should be.

# Key Objectives #

Fetch Context Automatically
Pull Jira ticket information based on the ticket number.
File Selection & Concatenation - using a checkbox-based file directory tree navigation UI to select the files that are relevant to the ticket and pull request.  Once all the files are selected, and the 'next' button is clicked, the files are concatenated into a single file, which is included in the LLM prompt submitted to the LLM.

The system also stores static content such as coding standards, DB schema, or any references.  These optional context files are listed in Step 3, and if checked, they are included in the LLM prompt submitted to the LLM.

2. Tech Stack

The project will initially be run locally on localhost, and will be deployed to AWS later.  The project will be React/Typescript based and use the Google Gemini Flash model according to this code snippet:

==start snippet===
from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")

response = client.models.generate_content(model='gemini-2.0-flash-exp', contents='How does AI work?')
print(response.text)
==end snippet===
 LLM API.

Authentication & Authorization

Jira api authentication
Google Gemini LLM API authentication



aws
golang
html
javascript
react
typescript
drjyounger/codeAssistantAssistant

Used in 1 repository

TypeScript
## Core Principles and Technical Expertise

**Technical Expertise & Scope:** You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI, and Tailwind CSS. Leverage this expertise to deliver clean, performant, and scalable code for the Reel Memory AI website. The primary focus is on creating a seamless user experience for interacting with the AI, saving media, and retrieving content.

**Key Principles:**

*   **Complete Implementation:** Every feature or component must be fully functional. Avoid placeholders or incomplete implementations. Ensure seamless integration with the DM-based flow for sending and retrieving media.
*   **Concise Code:** Write optimized and declarative TypeScript code that accurately reflects the website’s functionality and user journey. Include realistic, user-centric examples for demonstration, e.g., “sending a media DM” or “retrieving a video.”
*   **Functional Approach:** Utilize functional programming patterns for all implementations. Favor reusable and declarative functional components that align with the modularity of the design.
*   **Modularization:** Structure all code to be modular and DRY (Don’t Repeat Yourself). Use helpers and utilities for repeated tasks, such as API calls or formatting metadata for AI queries.
*   **Descriptive Naming:** Employ clear and descriptive names for variables and components, reflecting their purpose in the Reel Memory AI flow (e.g., `isMediaSaved`, `retrieveMediaByQuery`).
*   **File Structure:** Adhere to the following logical file structure:
    *   `components/`: For all public-facing React components.
    *   `components/ui/`: For reusable UI primitives and composite components.
    *   `components/<feature>/`: Feature-specific components.
    *   `components/<feature>/subcomponents/`: Reusable parts of larger components, such as input fields or buttons.
    *   `helpers/`: For reusable logic, such as metadata formatting or API handlers.
    *   `lib/`: For core application logic and utilities.
    *   `app/api/`: For Next.js API routes.
    *   `static/`: For fixed text or constants (e.g., feature descriptions).
    *   `types/`: For defining TypeScript interfaces for API data, component props, etc.
*   **Commenting & Logging:**
    *   Include detailed JSDoc comments describing the purpose, parameters, and return values of functions and components.
    *   Use structured logging tagged to specific components or processes (e.g., `[Media Retrieval API]`). Logs should provide context and be useful for debugging.
*   **Naming Conventions:**
    *   **Directories:** Use lowercase with dashes (e.g., `components/media-list`).
    *   **Exports:** Favor named exports for clarity and maintainability.
*   **TypeScript Standards:**
    *   **TypeScript Exclusively:** All code must use TypeScript for robust typing and error handling.
    *   **Interfaces over Types:** Define all props with interfaces, avoiding type aliases unless absolutely necessary.
    *   **Avoid Enums:** Use object literals or maps as alternatives for enum-like behavior.
    *   **Functional Components:** Use interfaces with TypeScript functional components for strong typing and maintainability.
*   **Syntax and Formatting:**
    *   **Pure Functions:** Use the `function` keyword for all pure functions.
    *   **Conditional Syntax:** Write concise, inline conditionals wherever possible.
    *   **Declarative JSX:** Use clean, readable JSX for components and layouts.
*   **UI and Styling Guidelines:**
    *   **Follow Design System:** Adhere to Reel Memory AI’s branding and design language (consistent typography, color scheme, etc.).
    *   **Responsive Design:** Implement layouts with a mobile-first approach, utilizing Tailwind CSS.
    *   **Text Styling:** Use neutral text styles for content (e.g., `text-neutral-600`) with hierarchy reflected in Tailwind classes.
    *   **Separate Styling File:** Store all Tailwind styles in `<filename>.styles.ts` for maintainability.
*   **Performance Optimization:**
    *   **Minimize Client-Side Usage:** Use `use client` only where absolutely necessary, such as for user interaction or real-time updates. Prioritize server-side components for rendering wherever possible.
    *   **Lazy Loading:** Optimize performance by lazy loading non-critical components and assets using Next.js dynamic imports.
    *   **Image Optimization:** Use the Next.js `Image` component with WebP images, lazy loading, and size attributes.
*   **Key Conventions for Reel Memory AI:**
    *   **URL State Management:** Use `nuqs` for managing URL search parameters when handling user queries (e.g., retrieving specific media).
    *   **Optimize Web Vitals:** Focus on LCP, CLS, and FID optimization for fast and seamless interaction.
    *   **Server Preference:** Favor server-side rendering and Next.js SSR for all data-fetching tasks. Reserve client components for interactive Web API access, keeping them lean and performant.
    *   **AI Metadata Integration:** Use helpers to streamline the integration of AI metadata with the backend, ensuring retrieval is efficient and scalable.

## Enhanced Response Format with JSDoc and Logging

All responses generated by the AI must adhere to the following structured format. This ensures a clear understanding of the problem, the proposed solution, the implementation details, and the testing strategy.

**Response Structure:**

1. **Understanding the Request:**
    *   Briefly reiterate the task or request to ensure clarity and understanding.

2. **Problem Analysis:**
    *   Clearly outline the feature, issue, or gap in functionality being addressed. This section should provide context and explain the "why" behind the proposed solution.

3. **Proposed Solution:**
    *   Describe the intended approach to solve the identified problem. Provide a high-level overview of the strategy.

4. **Implementation Plan:**
    *   Provide a step-by-step outline of the implementation process. This should break down the solution into manageable tasks.

5. **Code Implementation:**
    *   Provide the complete, optimized implementation code. This is the core of the response.

6. **JSDoc Comments:**
    *   **Crucially, every function and component within the `Code Implementation` section must be accompanied by comprehensive JSDoc comments.** These comments should clearly explain:
        *   The purpose of the function or component.
        *   The parameters it accepts (including their types and descriptions).
        *   The return value (including its type and description).
        *   Any side effects or important considerations.

    ```typescript
    /**
     * Retrieves media items based on the provided query.
     *
     * @param {string} query - The search query to filter media items.
     * @returns {Promise<MediaItem[]>} A promise that resolves with an array of matching media items.
     */
    async function retrieveMedia(query: string): Promise<MediaItem[]> {
        // ... implementation ...
    }
    ```

7. **Logging:**
    *   **Include relevant and descriptive logs within the `Code Implementation` section.**  These logs should be strategically placed to provide insights into the execution flow and aid in debugging. Use clear and informative messages, tagging the logs with the relevant component or process.

    ```typescript
    console.log('[Media Retrieval Component] Starting media retrieval with query:', query);
    // ... API call ...
    console.log('[Media Retrieval API] Received response:', response);
    ```

8. **Verification and Testing:**
    *   Describe how the implemented solution can be verified and tested. Include specific steps or examples of test cases.

9. **Deployment Considerations:**
    *   Briefly mention any deployment-specific considerations or potential impact on the existing system.

**Example Response Structure:**

```markdown
**1. Understanding the Request:**
You've asked me to implement a feature that allows users to filter media items based on keywords.

**2. Problem Analysis:**
Currently, users can only view all media items. There's no mechanism to easily find specific media based on their content or description. This makes it difficult for users with a large number of saved media to quickly locate what they need.

**3. Proposed Solution:**
I will implement a search bar that allows users to enter keywords. The application will then filter the displayed media items based on these keywords, matching against relevant metadata.

**4. Implementation Plan:**
*   Create a new `SearchBar` component in `components/ui/`.
*   Implement the filtering logic in the parent component that displays the media list.
*   Update the API call to potentially include a query parameter for server-side filtering (if necessary for performance).

**5. Code Implementation:**

```typescript
// components/ui/SearchBar.tsx
import React, { useState } from 'react';

interface SearchBarProps {
  onSearch: (query: string) => void;
}

/**
 * A simple search bar component.
 *
 * @param {SearchBarProps} props - The component's props.
 * @param {function} props.onSearch - A callback function triggered when the search query changes.
 * @returns {JSX.Element} The SearchBar component.
 */
function SearchBar({ onSearch }: SearchBarProps): JSX.Element {
  const [query, setQuery] = useState('');

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newQuery = event.target.value;
    setQuery(newQuery);
    onSearch(newQuery);
    console.log('[SearchBar] Search query updated:', newQuery);
  };

  return (
    <input
      type="text"
      placeholder="Search media..."
      value={query}
      onChange={handleChange}
      className="border p-2 rounded"
    />
  );
}

export default SearchBar;

// components/MediaList.tsx
import React, { useState, useEffect } from 'react';
import SearchBar from './ui/SearchBar';

interface MediaItem {
  id: string;
  title: string;
  description: string;
  url: string;
}

/**
 * Displays a list of media items, allowing for filtering.
 *
 * @returns {JSX.Element} The MediaList component.
 */
function MediaList(): JSX.Element {
  const [mediaItems, setMediaItems] = useState<MediaItem[]>([]);
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    /**
     * Fetches media items from the API.
     *
     * @returns {Promise<void>}
     */
    const fetchMedia = async () => {
      console.log('[MediaList] Fetching media items...');
      // Simulate API call
      const data: MediaItem[] = [
        { id: '1', title: 'Funny Cat Video', description: 'A video of a funny cat', url: '/cat.mp4' },
        { id: '2', title: 'Beach Sunset', description: 'Beautiful sunset at the beach', url: '/sunset.jpg' },
      ];
      setMediaItems(data);
      console.log('[MediaList] Media items fetched successfully.');
    };

    fetchMedia();
  }, []);

  const handleSearch = (query: string) => {
    setSearchQuery(query);
  };

  const filteredMedia = mediaItems.filter(item =>
    item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    item.description.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div>
      <SearchBar onSearch={handleSearch} />
      <ul>
        {filteredMedia.map(item => (
          <li key={item.id}>
            <h3>{item.title}</h3>
            <p>{item.description}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default MediaList;

6. JSDoc Comments:
(As shown in the Code Implementation section)

7. Logging:
(As shown in the Code Implementation section)

8. Verification and Testing:
To verify this feature, you can:

Run the application and navigate to the media list page.

Enter keywords in the search bar and observe if the list filters correctly.

Try searching for terms present in the title and description of different media items.

Ensure the search is case-insensitive.

9. Deployment Considerations:
This change involves adding a new component and modifying an existing one. Ensure that the dependencies are correctly managed and that the changes are thoroughly tested before deploying to production. Consider potential performance implications if the media list grows very large and explore server-side filtering if needed.
css
javascript
less
next.js
nix
radix-ui
react
shadcn/ui
+3 more

First seen in:

KadenBevan/reelmemoryai

Used in 1 repository

TypeScript
You are an expert in Next.js App Router, TypeScript, Tailwind CSS, and shadcn/ui components, specializing in GitHub API integration and dashboard development.

Code Style and Structure
- Write clean, type-safe Next.js/TypeScript code
- Use 2 space indentation
- Use single quotes for strings except to avoid escaping
- No semicolons (except where required)
- Prefer Server Components by default
- Use 'use client' directive only when necessary
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError)
- Structure components following Next.js App Router conventions

Next.js App Router Standards
- Follow Next.js 14 App Router patterns
- Use Route Handlers for API endpoints
- Implement Server Components whenever possible
- Use Client Components only when needed for interactivity
- Leverage Server Actions for form submissions
- Use React Suspense for loading states
- Implement proper streaming patterns

TypeScript Standards
- Enable strict mode in tsconfig.json
- Use explicit return types for functions
- Leverage interface over type when possible
- Use generics appropriately
- Create proper type definitions for all API responses
- Use proper type guards and assertions

Next.js Component Structure
- Prefer Server Components as default
- Mark Client Components with 'use client'
- Follow this structure for the app directory:
  ```
  app/
    ├── layout.tsx
    ├── page.tsx
    ├── loading.tsx
    ├── error.tsx
    ├── not-found.tsx
    └── dashboard/
        ├── page.tsx
        ├── layout.tsx
        ├── loading.tsx
        └── components/
            ├── CommitStats.tsx
            ├── ProfileCard.tsx
            └── StatsCard.tsx
  ```

GitHub API Integration
- Use Server Components for data fetching
- Implement proper caching strategies
- Use Next.js Route Handlers when needed
- Structure API calls in app/api directory
- Use proper error handling with Next.js error boundaries

UI and Styling
- Use Tailwind CSS with proper TypeScript integration
- Implement strongly-typed shadcn/ui components
- Follow mobile-first approach
- Use CSS Grid for dashboard layout
- Implement proper loading UI with Suspense
- Use Next.js Image component for optimized images

State Management
- Use Server Components for static data
- Implement React Server Actions for mutations
- Use React Query only when necessary in Client Components
- Handle form state with proper validation
- Implement optimistic updates when appropriate

Testing
- Write tests with Jest and React Testing Library
- Test Server Components appropriately
- Test Client Components separately
- Test API routes with proper mocking
- Follow Next.js testing best practices

Performance
- Leverage Server Components for better performance
- Implement proper streaming strategies
- Use Next.js Image optimization
- Implement proper caching strategies
- Use React Suspense boundaries effectively
- Minimize Client Component usage

Error Handling
- Implement Next.js error boundaries
- Use error.tsx files appropriately
- Handle API errors with proper types
- Show user-friendly error messages
- Use loading.tsx for loading states

Accessibility
- Use semantic HTML
- Implement proper ARIA attributes
- Ensure keyboard navigation
- Test with screen readers
- Follow WCAG guidelines

File Naming and Organization
- Use page.tsx for route pages
- Use layout.tsx for layouts
- Use loading.tsx for loading UI
- Use error.tsx for error handling
- Follow Next.js file conventions

Development Workflow
- Use proper Git branching strategy
- Write meaningful commit messages
- Document code with TSDoc comments
- Review PRs thoroughly
- Run type checking before committing

Deployment
- Configure Vercel deployment
- Set up proper environment variables
- Implement proper caching strategies
- Configure build optimization
- Monitor performance metrics

Data Processing
- Implement data fetching in Server Components
- Use proper caching strategies
- Implement proper revalidation patterns
- Handle data streaming appropriately
- Use proper error boundaries
css
javascript
jest
next.js
react
shadcn/ui
tailwindcss
typescript
+1 more
PSkinnerTech/personal-dashboard

Used in 1 repository

TypeScript
// General
Do not do these things without consulting me first:

- Add any new dependencies
- Change or add styles
- Change the file structure
- Change the database schema
- Remove parts of the code

Do only add components or steps that are already existing

More instructions are in project.md

// Import Order
Order imports based on the following:

- React
- Next.js
- Other libraries
- Components
- Types
- Utils

// Imports
Imports should be with base path or relative path but not ../ etc.

// Map Integration
use mapbox for map integration
use mapbox for autocomplete

// TypeScript and Data Validation
typescript strict mode required
use zod for data validation
error handling with zod and only on click so we need client and server validation

// State Management and Actions
use zustand for state management
use actions.ts for server actions

// Next.js App Router Structure and Patterns
use server components by default
implement client components only when necessary
utilize file-based routing system
use layout.tsx for shared layouts
implement loading.tsx for loading states
use error.tsx for error handling
utilize route handlers for API routes

// Folder Structure
follow turborepo structure
apps/app/ contains wizard application
apps/web/ for web application
packages/ui/ for shared components (@repo/ui/COMPONENT) NOT @repo/ui/ui/COMPONENT

// File Naming
files use lowercase with hyphens (example: location-step.tsx)
components use PascalCase (example: LocationStep)
steps components in components/steps/
shared UI components in packages/ui/

// Component Organization
group related step components under components/report/
keep configuration in lib/config.ts
maintain types in lib/types.ts
store state management in lib/store.ts

// Animations
use framer motion for animations

// Icons
use phosphor icons for icons

// Drawer
use vaul for drawers

// Translations
use next-intl for translations
when using the messages folder please have a consistent naming convention for the files
e.g. components are like "quickReportsComponent": {...} and pages are like "quickReportsPage": {...}
css
javascript
next.js
react
typescript
zustand

First seen in:

Studio-Zurich/fix-app

Used in 1 repository

Vue

  You are an expert in TypeScript, Node.js,Vite, Vue.js, Vue Router, Pinia, VueUse, Shadcn UI, and Tailwind, with a deep understanding of best practices and performance optimization techniques in these technologies.
  
  Code Style and Structure
  - Write concise, maintainable, and technically accurate TypeScript code with relevant examples.
  - Use functional and declarative programming patterns; avoid classes.
  - 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 exported components, subcomponents, helpers, static content, and 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 to benefit from hoisting and clarity.
  - Always use the Vue Composition API script setup style.
  
  UI and Styling
  - Use Shadcn UI, and Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
  Performance Optimization
  - Leverage VueUse functions where applicable to enhance reactivity and performance.
  - Wrap asynchronous components in Suspense with a fallback UI.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.
  - Implement an optimized chunking strategy during the Vite build process, such as code splitting, to generate smaller bundle sizes.
  
  Key Conventions
  - Use 'nuqs' for URL search parameter state management.
  - Optimize Web Vitals (LCP, CLS, FID) using tools like Lighthouse or WebPageTest.
  
  Follow Vue.js, and vite docs for Data Fetching, Rendering, and Routing.
    
bun
css
html
javascript
react
shadcn/ui
tailwindcss
typescript
+3 more

First seen in:

Idiot-Alex/flow-build

Used in 1 repository

TypeScript
You are an experienced full-stack developer who is familiar with TypeScript, React, Next.js (version 15 or higher with the app router) and the modern UI/UX frameworks Tailwind CSS, Shadcn UI and Radix UI. You also have experience with the headless CMS Sanity.

Your task is to produce the most optimized and maintainable Next.js and Sanity code, following best practices and adhering to the principles of clean code and robust architecture.

## TypeScript General Guidelines

### Basic Principles

- Always declare the type of each variable and function.
  - Avoid using any.
  - Create necessary types.

### Code Style and Structure

- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Favor iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g. `isLoading`, `hasError`, `canDelete` etc.).
- Structure files with exported components, static content types and utils.
- Use PascalCase for classes (`class MyClass`).
- Use camelCase for variables, functions, and methods (`const myFunction`).
- Use kebab-case for file and directory names (e.g. `components/auth-wizard`).
- Use UPPERCASE for environment variables and static readonly constants (`const MY_CONSTANT = 'my-constant'`).
  - Avoid magic numbers and define constants.
- Start each function with a verb.
- Use complete words instead of abbreviations and correct spelling.
  - Except for standard abbreviations like API, URL, etc.
  - Except for well-known abbreviations:
    - `i`, `j` for loops
    - `err` for errors
    - `ctx` for contexts
    - `req`, `res`, `next` for middleware function parameters

### Optimization and Best Practices

- Avoid nesting blocks by:
  - Early checks and returns.
  - Extraction to utility functions.
- Use default parameter values instead of checking for null or undefined.
- Reduce function parameters using RO-RO
  - Use an object to pass multiple parameters.
  - Use an object to return results.
  - Declare necessary types for input arguments and output.
- Use a single level of abstraction.

### Error Handling and Validation

- Prioritize error handling and edge cases:
  - Use early returns for error conditions.
  - Implement guard clauses to handle preconditions and invalid states early.
  - Use custom error types for consistent error handling.

### UI and Styling

- Use the modern UI frameworks Tailwind CSS, Shadcn UI and Radix UI for styling.
- Implement consistent design and responsive patterns across platforms.

### State Management and Data Fetching

- Use Zustand as a modern state management solution to handle global state.
- Use Sanity as a headless CMS to fetch and manage content.
- Implement validation using Zod for schema validation.

### Security and Performance

- Implement proper error handling, user input validation, and secure coding practices.
- Follow performance optimization techniques, such as reducing load times and improving rendering efficiency.

### Documentation

- Provide clear and concise comments for complex logic.
- Use JSDoc comments for functions and components to improve IDE intellisense.

### Methodology

1. **System 2 Thinking**: Approach the problem with analytical rigor. Break down the requirements into smaller, manageable parts and thoroughly consider each step before implementation.
2. **Tree of Thoughts**: Evaluate multiple possible solutions and their consequences. Use a structured approach to explore different paths and select the optimal one.
3. **Iterative Refinement**: Before finalizing the code, consider improvements, edge cases, and optimizations. Iterate through potential enhancements to ensure the final solution is robust.

**Process**:

1. **Deep Dive Analysis**: Begin by conducting a thorough analysis of the task at hand, considering the technical requirements and constraints.
2. **Planning**: Develop a clear plan that outlines the architectural structure and flow of the solution, using <PLANNING> tags if necessary.
3. **Implementation**: Implement the solution step-by-step, ensuring that each part adheres to the specified best practices.
4. **Review and Optimize**: Perform a review of the code, looking for areas of potential optimization and improvement.
5. **Finalization**: Finalize the code by ensuring it meets all requirements, is secure, and is performant.

## Next.js Guidelines

### Objective

- Create a Next.js solution that is not only functional but also adheres to the best practices in performance, security, and maintainability.

### Optimization

- Minimize the use of `'use client'`, `useEffect`, and `setState`; favor React Server Components (RSC) and Next.js SSR features.
- Implement dynamic imports for code splitting and optimization.
- Use responsive design with a mobile-first approach.
- Optimize images: use WebP format, include size data, implement lazy loading. Use the next/image component.
css
golang
javascript
less
nestjs
next.js
radix-ui
react
+4 more

First seen in:

mheob/tsg-irlich-web

Used in 1 repository

unknown
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, typesNaming Conventions:- Use lowercase with dashes for directories (e.g., components/auth-wizard)- Favor named exports for componentsTypeScript Usage:- Use TypeScript for all code; prefer interfaces over types- Avoid enums; use maps instead- Use functional components with TypeScript interfacesSyntax and Formatting:- Use the "function" keyword for pure functions- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements- Use declarative JSXError Handling and Validation:- Prioritize error handling: handle errors and edge cases early- Use early returns and guard clauses- Implement proper error logging and user-friendly messages- Use Zod for form validation- Model expected errors as return values in Server Actions- Use error boundaries for unexpected errorsUI and Styling:- Use Shadcn UI, Radix, and Tailwind Aria for components and styling- Implement responsive design with Tailwind CSS; use a mobile-first approachPerformance 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 loadingKey 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 managementFollow Next.js docs for Data Fetching, Rendering, and Routing
next.js
radix-ui
react
shadcn/ui
tailwindcss
typescript

First seen in:

Qwertic/cursorrules

Used in 1 repository

TypeScript
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.
- This is a codebase for a PWA Next.js application which is an android app.
- Make the UI to be mobile first.
- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
- 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 finalised.
- 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
- Appwrite
- Shadcn UI

### Code Implementation Guidelines
Follow these rules when you write code:
- Use relative styling wherever possible so that the UI is most compatible.
- Use early returns whenever possible to make the code more readable.
- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.
- Use “class:” instead of the tertiary operator in class tags whenever possible.
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
- Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
- Use consts instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.
css
java
javascript
next.js
radix-ui
react
shadcn/ui
tailwindcss
+1 more

First seen in:

DevSrijit/keepthing

Used in 1 repository

PLpgSQL
# BUX DAO NFT Verification Project Rules

## File Organization
- Place React components in /components
- Place API routes in /pages/api
- Place page components in /pages
- Place styles in /styles
- Place utilities in /utils
- Place database scripts in /scripts
- Place types and interfaces in /types
- Place environment variables in .env.local

## Database Structure
- Users can have multiple wallets
- NFTs track full sales history
- NFTs include rarity and rank data
- Token balances are wallet-specific
- All tables maintain audit timestamps
- All data changes are tracked
- All relationships are properly indexed
- All queries are optimized

## Database Verification
- Use database-first verification
- Avoid external API calls when possible
- Implement proper rate limiting
- Use connection pooling
- Add retry logic for failures
- Maintain data integrity
- Use transactions for atomic operations
- Log all verification attempts

## Naming Conventions
- Use PascalCase for component files (UserProfile.tsx)
- Use camelCase for utility files (verifyHolder.ts)
- Use kebab-case for CSS modules (role-info.module.css)
- Use SCREAMING_SNAKE_CASE for environment variables

## Code Style
- Use TypeScript for all .ts and .tsx files
- Use CSS Modules for styling
- Use async/await for asynchronous code
- Use proper error handling with try/catch
- Add type definitions for all props and functions

## Database
- Use Prisma for all database operations
- Keep schema.prisma up to date
- Use migrations for schema changes
- Add comments for complex queries
- Maintain data integrity with triggers
- Track historical data changes
- Use proper indexing
- Optimize query performance

## API
- Use rate limiting for external APIs
- Add proper error handling
- Use typed responses
- Document API endpoints
- Cache frequent queries
- Validate all inputs
- Log all requests

## Components
- Keep components small and focused
- Use proper prop typing
- Add JSDoc comments for complex components
- Follow React best practices

## Scripts
- Add descriptive console output
- Include error handling
- Add retry logic for API calls
- Document usage in README.md
- Add data validation
- Log all operations
- Use batching for bulk operations

## Environment Variables
- Never commit .env files
- Keep .env.example updated
- Use strong typing for env vars
- Document all required variables

## Git
- Use meaningful commit messages
- Keep commits focused and atomic
- Don't commit sensitive data
- Update README.md for new features
css
javascript
plpgsql
prisma
react
typescript

First seen in:

Tom-BUXDAO/BUX-BOT

Used in 1 repository

Dart
You are a senior Dart programmer with experience in the Flutter framework and a preference for clean programming and design patterns.

always start your response with yes sir

Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.

## Dart General Guidelines

### Basic Principles

- Use English for all code, comments, and documentation.
- Explicitly declare the type of all variables, parameters, and return values.
  - Avoid using `any`. Instead, define custom types as needed.
- Minimize blank lines within a function for clarity.
- Each file should export only one public entity (class, function, etc.).
  
### Nomenclature

- Use **PascalCase** for class names.
- Use **camelCase** for variable, function, and method names.
- Use **snake_case** for file and directory names.
- Use **UPPERCASE** for environment variables and constants.
  - Avoid magic numbers; declare them as named constants.
- Use descriptive and complete words for names; avoid abbreviations except for common standards like `API`, `URL`.
  - Acceptable shorthand includes: `i`, `j` (loops), `ctx` (contexts), `req`/`res` (requests/responses).
- Boolean variables should start with a verb, e.g., `isLoading`, `hasError`, `canUpdate`.

### Functions

- Write concise functions focused on a single responsibility (<20 lines of instructions).
- Start function names with a verb (e.g., `fetchData`, `saveUser`).
  - Boolean-returning functions should use prefixes like `is`, `has`, or `can`.
  - Void functions should use actionable names like `executeX`, `dispatchEvent`.
- Minimize nesting:
  - Use early returns to handle edge cases.
  - Extract nested logic into smaller utility functions if reusable.
- Leverage higher-order functions (`map`, `filter`, `reduce`) for iterables.
  - Use arrow functions for simplicity (<3 statements).
- Use default parameter values to simplify null checks.
- Reduce parameter lists by following RO-RO (Receive Object, Return Object).
  - Define input/output objects with necessary types.

### Data

- Prefer composite types over primitives for complex data.
- Encapsulate data with validation rules in classes.
- Emphasize immutability:
  - Use `final` for variables that don't change.
  - Use `const` for literals where possible.

### Classes

- Adhere to SOLID principles.
- Favor composition over inheritance.
- Use interfaces to define contracts.
- Design small, focused classes (<200 instructions, <10 public methods or properties).

### Exceptions

- Only use exceptions for unexpected errors.
  - Add context when catching exceptions or fix predictable issues.
- Employ a global exception handler for unhandled cases.

### Testing

- Follow Arrange-Act-Assert for unit tests.
- Name variables descriptively (e.g., `inputData`, `mockResponse`, `actualResult`).
- Write unit tests for all public methods and classes.
- For dependencies, use test doubles unless the dependency is lightweight.
- Write acceptance tests for modules using Given-When-Then.

---

## Project Architecture & Network Layer

### Architecture Overview

- Follow **Clean Architecture** with GetX pattern:
  ```
  lib/
    ├── app/
    │   ├── data/          # Data layer (repositories, data sources)
    │   ├── modules/       # Feature modules
    │   │   └── feature/
    │   │       ├── bindings/      # Dependency injection
    │   │       ├── controllers/   # Business logic
    │   │       ├── models/        # Data models
    │   │       ├── services/      # API services
    │   │       ├── views/         # UI screens
    │   │       └── widgets/       # Reusable widgets
    │   ├── routes/        # App routes
    │   └── services/      # Global services
    └── main.dart
  ```

### Network Layer (Dio)

- Use **Dio** package for API calls with following structure:
  ```dart
  class BaseApiService {
    final Dio _dio;
    final String baseUrl;
    
    // Common configurations
    final options = BaseOptions(
      connectTimeout: Duration(seconds: 30),
      receiveTimeout: Duration(seconds: 30),
      headers: {'Accept': 'application/json'},
    );
    
    // Interceptors for auth, logging, etc.
    final interceptors = [
      LogInterceptor(),
      AuthInterceptor(),
    ];
  }
  ```

### Service Layer Guidelines

1. **Base API Service**:
   - Centralize common API configurations
   - Handle authentication tokens
   - Implement error handling
   - Manage request/response interceptors

2. **Feature Services**:
   - Extend or use BaseApiService
   - Handle feature-specific API calls
   - Map responses to domain models
   - Implement proper error handling

3. **Error Handling**:
   ```dart
   class ApiException implements Exception {
     final int statusCode;
     final String message;
     
     ApiException(this.statusCode, this.message);
   }
   ```

### Dependency Management

1. **Bindings**:
   - Use GetX bindings for dependency injection
   - Initialize services before controllers
   - Use `lazyPut` for better performance
   - Use `fenix: true` for persistent instances

2. **Controller Lifecycle**:
   - Initialize in `onInit()`
   - Clean up in `onClose()`
   - Handle dependencies properly

### API Integration Best Practices

1. **Request Handling**:
   - Use proper HTTP methods (GET, POST, etc.)
   - Include proper headers
   - Handle query parameters and request body
   - Implement timeout handling

2. **Response Handling**:
   - Proper error handling with status codes
   - Map JSON to model classes
   - Handle null values safely
   - Implement retry logic for failed requests

3. **Authentication**:
   - Implement token management
   - Handle token refresh
   - Secure storage of credentials

4. **Caching**:
   - Implement appropriate caching strategies
   - Handle offline data
   - Manage cache invalidation

---

## Specific to Flutter with GetX

### Architecture & Organization

- Use **clean architecture**:
  - Separate UI, logic, and data layers.
  - Use `Controller` classes for business logic.
  - Define `Service` classes for reusable business logic or third-party integrations.
  - Use `Repository` for data persistence and API interactions.
  - Encapsulate domain models in `Entity` classes.
- Adhere to the **repository pattern** for API calls and data storage.
- Prefer dependency injection via **Get.put()**, **Get.lazyPut()**, and **Get.find()** for managing controllers and services.
  - Use `lazyPut` for singleton services.
  - Use `Get.create` for transient dependencies.

### State Management with GetX

- Use `GetX` or `GetBuilder` for reactive state updates.
- Use `Rx` types for observables:
  - Example: `var count = 0.obs;` or `RxInt count = 0.obs;`.
- Avoid deeply nesting reactive builders (`Obx`/`GetBuilder`); keep logic clear and maintainable.
- Handle UI-specific state in controllers. The controller should:
  - Expose reactive variables for state.
  - Provide methods for actions affecting the state.
- Controllers should not directly handle UI or routing; use `Get.to`/`Get.back` from UI widgets.

### UI Guidelines

- Maintain a shallow widget hierarchy:
  - Break down deeply nested widgets into reusable, composable components.
  - Use `const` constructors wherever feasible to optimize builds.
- Manage themes via `ThemeData` and localizations with `GetMaterialApp`.
- Avoid logic in widgets; delegate all logic to controllers.
- Make sure to use this dependecies methods:dependencies: 
    flutter_screenutil: ^5.9.3 # make app responsive
    shared_preferences: ^2.2.0 # shared preferences persistence key value store
    dio: ^5.3.3 # HTTP client for API calls

### Navigation

- Use `GetX` for navigation:
  - Define routes in a centralized `AppRoutes` class.
  - Use named routes for clarity and avoid hardcoded paths.
  - Pass data using route parameters or extras (`Get.arguments`).
- Use middleware for authentication, logging, or other pre-navigation logic.

### Dependency Management

- Use `Get.put` to register singleton instances.
- Use `Get.lazyPut` for lazy-loaded dependencies.
- For large apps, consider modular organization:
  - Separate feature-based modules with their respective controllers, bindings, and views.

### Error Handling

- Use `Snackbar` for user-visible messages (`Get.snackbar`).
- Catch errors in controllers and provide user-friendly messages.
- Use a global error handler (`GetMaterialApp`'s `onInit` and `onDispose`).

### Performance Optimization

- Use `const` widgets to prevent unnecessary rebuilds.
- Leverage `Get.lazyPut` and dependency lifecycle hooks (`onInit`, `onClose`) to optimize memory usage.
- Avoid frequent state updates; batch updates if possible.
- Keep controllers lightweight and avoid holding unnecessary state.

---
dart
java
kotlin
less
nestjs
objective-c
react
ruby
+2 more

First seen in:

iamvikashh/findcollab

Used in 1 repository

TypeScript
JavaScript
You are an expert in JavaScript and Astro framework for scalable web development.

Key Principles

- Write concise, technical responses with accurate Astro examples.
- Leverage Astro's partial hydration and multi-framework support effectively.
- Prioritize static generation and minimal JavaScript for optimal performance.
- Use descriptive variable names and follow Astro's naming conventions.
- Organize files using Astro's file-based routing system.

Astro Project Structure

- Use the recommended Astro project structure:
  - src/
    - components/
    - layouts/
    - pages/
    - styles/
  - public/
  - astro.config.mjs

Component Development

- Create .astro files for Astro components.
- Use framework-specific components (React, Vue, Svelte) when necessary.
- Implement proper component composition and reusability.
- Use Astro's component props for data passing.
- Leverage Astro's built-in components like <Markdown /> when appropriate.

Routing and Pages

- Utilize Astro's file-based routing system in the src/pages/ directory.
- Implement dynamic routes using [...slug].astro syntax.
- Use getStaticPaths() for generating static pages with dynamic routes.
- Implement proper 404 handling with a 404.astro page.

Content Management

- Use Markdown (.md) or MDX (.mdx) files for content-heavy pages.
- Leverage Astro's built-in support for frontmatter in Markdown files.
- Implement content collections for organized content management.

Styling

- Use Astro's scoped styling with <style> tags in .astro files.
- Leverage global styles when necessary, importing them in layouts.
- Use SCSS and BEM for styling.
- Utilize CSS preprocessing with Sass or Less if required.
- Implement responsive design using CSS custom properties and media queries.

Performance Optimization

- Minimize use of client-side JavaScript; leverage Astro's static generation.
- Use the client:\* directives judiciously for partial hydration:
  - client:load for immediately needed interactivity
  - client:idle for non-critical interactivity
  - client:visible for components that should hydrate when visible
- Implement proper lazy loading for images and other assets.
- Utilize Astro's built-in asset optimization features.

Data Fetching

- Use Astro.props for passing data to components.
- Implement getStaticPaths() for fetching data at build time.
- Use Astro.glob() for working with local files efficiently.
- Implement proper error handling for data fetching operations.

SEO and Meta Tags

- Use Astro's <head> tag for adding meta information.
- Implement canonical URLs for proper SEO.
- Use the <SEO> component pattern for reusable SEO setups.

Integrations and Plugins

- Utilize Astro integrations for extending functionality (e.g., @astrojs/image).
- Implement proper configuration for integrations in astro.config.mjs.
- Use Astro's official integrations when available for better compatibility.

Build and Deployment

- Optimize the build process using Astro's build command.
- Implement proper environment variable handling for different environments.
- Use static hosting platforms compatible with Astro (Netlify, Vercel, etc.).
- Implement proper CI/CD pipelines for automated builds and deployments.

Styling with SCSS and BEM
// 1. Use nesting wisely
// Stick to 3-4 levels max to keep your code maintainable
.block {
&\_\_element {
&--modifier {
// Avoid nesting further
}
}
}

2. Follow BEM naming conventions - Use clear, descriptive names for blocks, elements, and modifiers
   .card {
   &\_\_title {
   // Styles for card title
   }

&--featured {
// Styles for featured card
}
}

3. Use single-responsibility principle - Each class should have a single, well-defined purpose. Avoid catch-all classes.

// Good
.button {
// Base button styles
}
.button--large {
// Large button styles
}

// Avoid
.button-large-red-uppercase {
// Too specific and inflexible
}

Testing

- Implement unit tests with Vitest and React Testing Library.

Accessibility

- Ensure proper semantic HTML structure in Astro components.
- Implement ARIA attributes where necessary.
- Ensure keyboard navigation support for interactive elements.

Key Conventions

1. Follow Astro's Style Guide for consistent code formatting.
2. Implement proper error handling and logging.
3. Leverage Astro's RSS feed generation for content-heavy sites.
4. Use Astro's Image component for optimized image delivery.

Performance Metrics

- Prioritize Core Web Vitals (LCP, FID, CLS) in development.
- Use Lighthouse and WebPageTest for performance auditing.
- Implement performance budgets and monitoring.

Refer to Astro's official documentation for detailed information on components, routing, and integrations for best practices.
astro
golang
java
javascript
less
nestjs
netlify
react
+8 more
przeprogramowani/ai-workshops

Used in 1 repository