Awesome Cursor Rules Collection

Showing 1117-1128 of 2626 matches

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
 
 Project uses @apollo/server@4.11.2

 I'm developing on Windows

 I'm using yarn
dockerfile
graphql
shell
typescript
yarn
shiny-coding/bhajan-server

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