Awesome Cursor Rules Collection

Showing 2077-2088 of 2626 matches

JavaScript
    # Role
    你是一名精通微信小程序开发的高级工程师,拥有20年的小程序开发经验。你的任务是帮助一位不太懂技术的初中生用户完成微信小程序的开发。你的工作对用户来说非常重要,完成后将获得10000美元奖励。

    # Goal
    你的目标是以用户容易理解的方式帮助他们完成微信小程序的设计和开发工作。你应该主动完成所有工作,而不是等待用户多次推动你。

    在理解用户需求、编写代码和解决问题时,你应始终遵循以下原则:

    ## 第一步:项目初始化
    - 当用户提出任何需求时,首先浏览项目根目录下的README.md文件和所有代码文档,理解项目目标、架构和实现方式。
    - 如果还没有README文件,创建一个。这个文件将作为项目功能的说明书和你对项目内容的规划。
    - 在README.md中清晰描述所有功能的用途、使用方法、参数说明和返回值说明,确保用户可以轻松理解和使用这些功能。

    # 本规则由 AI进化论-花生 创建,版权所有,引用请注明出处

    ## 第二步:需求分析和开发
    ### 理解用户需求时:
    - 充分理解用户需求,站在用户角度思考。
    - 作为产品经理,分析需求是否存在缺漏,与用户讨论并完善需求。
    - 选择最简单的解决方案来满足用户需求。

    ### 编写代码时:
    - 使用微信小程序原生框架进行开发,合理使用组件化开发。
    - 遵循微信小程序设计规范,确保良好的用户体验。
    - 利用微信小程序提供的API进行功能开发,如登录、支付、地理位置等。
    - 使用分包加载优化小程序体积和加载性能。
    - 合理使用页面生命周期函数和组件生命周期函数。
    - 实现响应式布局,确保在不同尺寸设备上的良好显示。
    - 使用TypeScript进行开发,提高代码质量和可维护性。
    - 编写详细的代码注释,并在代码中添加必要的错误处理和日志记录。
    - 合理使用本地存储和缓存机制。

    ### 解决问题时:
    - 全面阅读相关代码文件,理解所有代码的功能和逻辑。
    - 分析导致错误的原因,提出解决问题的思路。
    - 与用户进行多次交互,根据反馈调整解决方案。
    - 善用微信开发者工具进行调试和性能分析。
    - 当一个bug经过两次调整仍未解决时,你将启动系统二思考模式:
      1. 系统性分析bug产生的根本原因
      2. 提出可能的假设
      3. 设计验证假设的方法
      4. 提供三种不同的解决方案,并详细说明每种方案的优缺点
      5. 让用户根据实际情况选择最适合的方案

    ## 第三步:项目总结和优化
    - 完成任务后,反思完成步骤,思考项目可能存在的问题和改进方式。
    - 更新README.md文件,包括新增功能说明和优化建议。
    - 考虑使用微信小程序的高级特性,如云开发、小程序插件等来增强功能。
    - 优化小程序性能,包括启动时间、页面切换、网络请求等。
    - 实现适当的数据安全和用户隐私保护措施。

    在整个过程中,始终参考[微信小程序官方文档](https://developers.weixin.qq.com/miniprogram/dev/framework/),确保使用最新的微信小程序开发最佳实践。
golang
javascript
typescript

First seen in:

princeniu/BookNote

Used in 1 repository

TypeScript
TypeScript
This works like this

./packages/web - nextjs app router includes everything to related to user accounts 
./packages/web/app/api/(new-ai) containts all the ai related functions
./packages/plugin - obsidian plugin 
./packages/plugin/index.ts - the main file for the plugin




core way the app works:
- inbox (a special folder in the vault, which is on the fs)
- the inbox folder is processed by the plugin, which will move the files to the correct folder based on the classification
-  there's an ai chat that has access to a whole lot of functioncals be used to chat with context of files and to do certain actions as defined in ./packages/web/app/api/(new-ai)/tools.ts





example:


- three plans
  - self-hosted (no license key)
  - lifetime (license key that also acts as api key with selfhostingurl)
  - subscription (license key that also acts as api key)



here's the list of variables you can use:
    --accent-h: 258;
    --accent-s: 88%;
    --accent-l: 66%;
    --background-primary: var(--color-base-00);
    --background-primary-alt: var(--color-base-10);
    --background-secondary: var(--color-base-20);
    --background-modifier-hover: rgba(var(--mono-rgb-100), 0.075);
    --background-modifier-active-hover: hsla(var(--interactive-accent-hsl), 0.15);
    --background-modifier-border: var(--color-base-30);
    --background-modifier-border-hover: var(--color-base-35);
    --background-modifier-border-focus: var(--color-base-40);
    --background-modifier-success-rgb: var(--color-green-rgb);
    --background-modifier-success: var(--color-green);
    --background-modifier-message: rgba(0, 0, 0, 0.9);
    --background-modifier-form-field: var(--color-base-00);
    --text-normal: var(--color-base-100);
    --text-muted: var(--color-base-70);
    --text-faint: var(--color-base-50);
    --text-on-accent: white;
    --text-on-accent-inverted: black;
    --text-warning: var(--color-orange);
    --text-success: var(--color-green);
    --text-selection: hsla(var(--color-accent-hsl), 0.2);
    --text-highlight-bg-rgb: 255, 208, 0;
    --text-highlight-bg: rgba(var(--text-highlight-bg-rgb), 0.4);
    --text-accent: var(--color-accent);
    --text-accent-hover: var(--color-accent-2);
    --interactive-normal: var(--color-base-00);
    --interactive-hover: var(--color-base-10);
    --interactive-accent-hsl: var(--color-accent-hsl);
    --interactive-accent: var(--color-accent-1);
    --interactive-accent-hover: var(--color-accent-2);




	•	Access to shadcn/ui components library.
	•	Prioritize: Ease of Use > Aesthetics > Performance.
	•	Use Tailwind CSS for utility-first styling.

Recommended Libraries and Tools:

	1.	State Management:
	•	React Context API for simple state needs.
	•	Zustand for lightweight and scalable state management compatible with React Server Components.
	2.	Form Handling:
	•	React Hook Form for performant and flexible form management with easy validation.
	3.	Data Fetching:
	•	TanStack Query (formerly React Query) for efficient data fetching with caching and revalidation.
	4.	Authentication:
	•	Implement authentication using Clerk.
	5.	Animations:
	•	Framer Motion for smooth animations and transitions.
	6.	Icons:
	•	Use Lucide React for a collection of beautiful open-source icons.

AI Integration with Vercel AI SDK:

	•	Utilize the Vercel AI SDK, a TypeScript toolkit for building AI-powered applications with frameworks like React and Next.js.
	•	Implement conversational UIs using the useChat hook, which manages chat states and streams AI responses.

Using Tools with useChat and streamText:

	•	Types of Tools:
	•	Automatically executed server-side tools.
	•	Automatically executed client-side tools.
	•	User-interactive tools requiring confirmation dialogs.
	•	Workflow:
	1.	User inputs a message in the chat UI.
	2.	Message is sent to the API route.
	3.	Language model generates tool calls via streamText.
	4.	Tool calls are forwarded to the client.
	5.	Server-side tools execute and return results to the client.
	6.	Client-side tools auto-execute using the onToolCall callback.
	7.	Interactive tools display in the UI, results managed via toolInvocations.
	8.	After interactions, use addToolResult to include the result in the chat.
	9.	If tool calls exist in the last message and all results are available, the client resends messages to the server for further processing.
	•	Note: Set maxSteps to a value greater than 1 in useChat options to enable multiple iterations (default is disabled for compatibility).

Example Implementation:

	•	API Route (app/api/chat/route.ts):

import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
import { z } from 'zod';

// Allow streaming responses up to 30 seconds
export const maxDuration = 30;

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = await streamText({
    model: openai('gpt-4o'),
    messages,
    tools: {
      // Server-side tool with execute function:
      getWeatherInformation: {
        description: 'Show the weather in a given city to the user.',
        parameters: z.object({ city: z.string() }),
        execute: async ({ city }: { city: string }) => {
          const weatherOptions = ['sunny', 'cloudy', 'rainy', 'snowy', 'windy'];
          return `${city} is currently ${weatherOptions[Math.floor(Math.random() * weatherOptions.length)]}.`;
        },
      },
      // Client-side tool initiating user interaction:
      askForConfirmation: {
        description: 'Ask the user for confirmation.',
        parameters: z.object({
          message: z.string().describe('The message to ask for confirmation.'),
        }),
      },
      // Automatically executed client-side tool:
      getLocation: {
        description: 'Get the user location after confirmation.',
        parameters: z.object({}),
      },
    },
  });

  return result.toDataStreamResponse();
}


	•	Client-Side Page (app/page.tsx):

'use client';

import { ToolInvocation } from 'ai';
import { Message, useChat } from 'ai/react';
import { pipeline } from 'stream'
import { PlaySquareIcon } from 'lucide-react'

export default function Chat() {
  const {
    messages,
    input,
    handleInputChange,
    handleSubmit,
    addToolResult,
  } = useChat({
    maxSteps: 5,

    // Handle automatically executed client-side tools:
    async onToolCall({ toolCall }) {
      if (toolCall.toolName === 'getLocation') {
        const cities = ['New York', 'Los Angeles', 'Chicago', 'San Francisco'];
        return {
          city: cities[Math.floor(Math.random() * cities.length)],
        };
      }
    },
  });

  return (
    <>
      {messages?.map((m: Message) => (
        <div key={m.id}>
          <strong>{m.role}:</strong> {m.content}
          {m.toolInvocations?.map((toolInvocation: ToolInvocation) => {
            const toolCallId = toolInvocation.toolCallId;
            const addResult = (result: string) =>
              addToolResult({ toolCallId, result });

            // Render confirmation tool (client-side with user interaction)
            if (toolInvocation.toolName === 'askForConfirmation') {
              return (
                <div key={toolCallId}>
                  {toolInvocation.args.message}
                  <div>
                    {'result' in toolInvocation ? (
                      <b>{toolInvocation.result}</b>
                    ) : (
                      <>
                        <button onClick={() => addResult('Yes')}>Yes</button>
                        <button onClick={() => addResult('No')}>No</button>
                      </>
                    )}
                  </div>
                </div>
              );
            }

            // Display results of other tools
            return 'result' in toolInvocation ? (
              <div key={toolCallId}>
                <em>Tool ({toolInvocation.toolName}):</em> {toolInvocation.result}
              </div>
            ) : (
              <div key={toolCallId}>
                <em>Executing {toolInvocation.toolName}...</em>
              </div>
            );
          })}
          <br />
        </div>
      ))}

      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} placeholder="Type your message..." />
      </form>
    </>
  );
}



Additional Notes:

	•	Ensure all tool invocations are properly managed to maintain a seamless user experience.
	•	Regularly update dependencies and libraries to their latest versions for improved performance and security.
	•	Test the chatbot thoroughly to handle edge cases and unexpected user inputs.

This revised prompt organizes the information more clearly, making it easier to understand and follow. It highlights key project guidelines, structures, and code examples, providing a comprehensive overview for anyone involved in the development process.


## pipeline

We have an inbox that processes files. 

The process happens in these steps:
- preprocess : trim content  | check if we support file type | check if we have a license
- extract (ai): extract text from file, we have a function in the plugin/index.ts for that
- classify (ai): classify the file, we have a function in the plugin/index.ts for that
- tag (ai): tag the file, we have a function in the plugin/index.ts for that
- format (ai): format the file, we have a function in the plugin/index.ts for that
- move: move the file to the correct folder, we have a function in the plugin/index.ts for that


each step should be logged in the record manager, and we should record the start and end of each step. 

all the ai steps are two folds one api call to get the llm recommendations
and one call to apply the recommendation. add tag after tagging , move file after folder recommendation, rename file after naming

when you classify apply a tag to the document there's append tag funciton on plugin 
only format if 1. there's a classification 2. there's no tag with the classification presetn



# Tool Calling

Tools are objects that can be invoked by the model to perform specific tasks. AI SDK Core tools consist of three key elements:

1. **Description**: Optional. Describes the tool's purpose and influences when it is selected.
2. **Parameters**: A Zod schema or JSON schema that defines the tool's parameters. Used to validate tool calls.
3. **Execute**: An optional async function that processes tool calls and returns a result of type `RESULT`.

## Defining Tools

Use the `tool` helper function to define tools:

```javascript
import { z } from 'zod';
import { generateText, tool } from 'ai';

const result = await generateText({
  model: yourModel,
  tools: {
    weather: tool({
      description: 'Get the weather in a location',
      parameters: z.object({
        location: z.string().describe('The location to get the weather for'),
      }),
      execute: async ({ location }) => ({
        location,
        temperature: 72 + Math.floor(Math.random() * 21) - 10,
      }),
    }),
  },
  prompt: 'What is the weather in San Francisco?',
});

When a tool is used, the process is called a tool call, and its output is the tool result.

Multi-Step Calls

Enable multi-step calls with the maxSteps setting in generateText or streamText. Each step can include a text generation or tool call, looping until no further calls are needed or the maximum number of steps is reached.

Example

import { z } from 'zod';
import { generateText, tool } from 'ai';

const { text, steps } = await generateText({
  model: yourModel,
  tools: {
    weather: tool({
      description: 'Get the weather in a location',
      parameters: z.object({
        location: z.string().describe('The location to get the weather for'),
      }),
      execute: async ({ location }) => ({
        location,
        temperature: 72 + Math.floor(Math.random() * 21) - 10,
      }),
    }),
  },
  maxSteps: 5,
  prompt: 'What is the weather in San Francisco?',
});

Accessing Steps

Retrieve intermediate tool calls and results using the steps property:

const allToolCalls = steps.flatMap(step => step.toolCalls);

onStepFinish Callback

Use onStepFinish to execute logic after each step:

const result = await generateText({
  onStepFinish({ text, toolCalls, toolResults }) {
    // Save chat history or log usage
  },
});

Tool Choice

Control tool selection with the toolChoice setting:
	•	auto (default): Model decides when and which tool to use.
	•	required: Model must call a tool.
	•	none: Model must not use tools.
	•	{ type: 'tool', toolName: string }: Model must call the specified tool.

Example

const result = await generateText({
  tools: {
    weather: tool({
      description: 'Get the weather in a location',
      parameters: z.object({ location: z.string() }),
      execute: async ({ location }) => ({ location, temperature: 72 }),
    }),
  },
  toolChoice: 'required',
  prompt: 'What is the weather in San Francisco?',
});

Error Handling

AI SDK handles the following tool-call errors:
	1.	NoSuchToolError: Tool not defined in the tools object.
	2.	InvalidToolArgumentsError: Invalid arguments for the tool’s parameters.
	3.	ToolExecutionError: Error during tool execution.

Handling Errors

try {
  const result = await generateText({
    // ...
  });
} catch (error) {
  if (NoSuchToolError.isInstance(error)) {
    // Handle missing tool
  } else if (InvalidToolArgumentsError.isInstance(error)) {
    // Handle invalid arguments
  } else if (ToolExecutionError.isInstance(error)) {
    // Handle execution error
  }
}

Tool Call Repair

Use experimental_repairToolCall to attempt repairs for invalid tool calls:

const result = await generateText({
  experimental_repairToolCall: async ({ toolCall, parameterSchema }) => {
    // Repair logic here
  },
});

Active Tools

Limit active tools using experimental_activeTools:

const { text } = await generateText({
  tools: myToolSet,
  experimental_activeTools: ['firstTool'],
});

Types

Ensure type safety with helper types:

import { CoreToolCallUnion, CoreToolResultUnion } from 'ai';

type MyToolCall = CoreToolCallUnion<typeof myToolSet>;
type MyToolResult = CoreToolResultUnion<typeof myToolSet>;

clerk
css
dockerfile
golang
java
javascript
less
next.js
+7 more
different-ai/file-organizer-2000

Used in 1 repository

TypeScript
# Munchy

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

## Project Context
I want to build a web app that allows users to track their kitchen inventory. The goal is to help users better understand what they have in their kitchen, and to help them make better decisions about what to buy and what to eat.


## Code Style and Structure
- Dont optimize prematurely, we will iterate on the app and the codebase as we build it.
- Work from first principles, dont assume anything.
- 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 repository files as follows:

```
app/                      # Tanstack Router/Start directory
├── routes/             # Route directory, filebased routing
    ├── _authed/        # Authenticated routes
    ├── _public/        # Public routes
    ├── api/            # Tanstack start API routes directory
    └── lib/            # Shared libraries
├── routes/
lib/                      # Shared libraries
├── components/         # Shared React components
├── enc/                # Custom React hooks
├── hooks/              # Custom React hooks
├── middleware/         # Tanstack Start middleware
├── server/             # Server and Database directory
├── services/           # Tanstack Start serverfn's and Tanstack Query
├── styles/             # Global styling
├── utils/              # Helper functions
```

## Tech Stack
- React
- TypeScript
- Tailwind CSS
- Shadcn UI
- Postgres
- DrizzleORM
- Bun
- Tanstack Router
- Tanstack Query
- Tanstack Start
- Tanstack Form
- Biome
- Zod
- Vite

## Naming Conventions
- Use lowercase with dashes for directories (e.g., components/form-wizard)
- Favor named exports for components and utilities
- Use lowercase with dashes for component files (e.g., username-form.tsx), but have the component function be Pascal case (e.g., export function UsernameForm)
- Use camelCase for utility files (e.g., formValidator.ts)

## TypeScript Usage
- Use TypeScript for all code; prefer interfaces over types
- Avoid enums; use const objects with 'as const' assertion
- Use functional components with TypeScript interfaces
- Avoid try/catch blocks unless there's good reason to translate or handle error in that abstraction
- Use explicit return types for all functions


## Syntax and Formatting
- Use "function" keyword for pure functions
- Avoid unnecessary curly braces in conditionals
- Use declarative JSX


## Error Handling
- Implement proper error boundaries
- Log errors appropriately for debugging
- Provide user-friendly error messages
- Handle network failures gracefully


## Security
- Sanitize user inputs via tanstack form and zod validator

## Git Usage
- When i send "cc", it means i want you to create a commit message for the diff of the working state.

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


Rules:
- Use lowercase for commit messages
- Only respond witha  summary line concise
bun
css
drizzle-orm
golang
javascript
less
postgresql
react
+4 more

First seen in:

michaeldahl7/dashboard

Used in 1 repository

Astro
# Astro Portfolio Project Structure
project_root/
  ├── src/                      # Основной исходный код
  │   ├── components/           # Переиспользуемые компоненты
  │   ├── layouts/              # Шаблоны страниц
  │   ├── pages/               # Маршрутизация и страницы
  │   └── styles/              # Глобальные стили
  └── public/                  # Статические файлы

# Технологический стек
- Framework: Astro v4.16
- Language: TypeScript
- Styling: CSS (scoped в компонентах)
- Deployment: GitHub Pages

# Соглашения по стилям
- Используем CSS переменные для темизации (--var-name)
- Стили компонентов пишем в <style> внутри .astro файлов
- Используем БЭМ-подобную методологию для именования классов
- Медиа-запросы: mobile-first подход
- Основные брейкпоинты: 768px, 1024px, 1200px

# Важные файлы
src/
  layouts/Layout.astro          # Основной шаблон
  components/                   # Компоненты
    ├── Header.astro           # Шапка сайта
    ├── Hero.astro            # Главный блок
    ├── Experience.astro      # Опыт работы
    └── Terminal.astro        # Интерактивный терминал

# Темизация
Основные переменные:
- --text-primary
- --text-secondary
- --accent-color
- --bg-primary
- --card-bg

# Рекомендации по разработке
1. Компоненты должны быть атомарными и переиспользуемыми
2. Используйте TypeScript для типизации пропсов
3. Стили должны быть изолированы в компонентах
4. Используйте CSS переменные для темизации
5. Следите за производительностью и оптимизацией изображений

# Git Workflow
1. Основная ветка: main
2. Деплой через GitHub Actions
3. Используйте conventional commits


# Roadmap проекта
- [ ] Добавить загрузку статей из Markdown Obsidian
- [ ] Генерация резюме из md-файла в PDF
- [ ] Локализация (RU/EN)

# Игнорируемые директории
dist/
node_modules/
.astro/
reference/
build/
coverage/

# Игнорируемые файлы
.env
.env.production
.DS_Store
*.log
.idea/
.vscode/



# Структура компонента

# Игнорируем сгенерированные файлы
dist/
.astro/
node_modules/

# Игнорируем конфигурационные файлы
.env
.env.production
.DS_Store
*.log

# Игнорируем кэш и временные файлы
.cache/
.temp/
*.tmp

# Игнорируем файлы IDE
.idea/
.vscode/
*.sublime-*

# Игнорируем артефакты сборки
build/
coverage/
reference/

# Игнорируем медиафайлы
*.jpg
*.png
*.gif
*.mp4
*.webm

# Игнорируем локальные файлы разработки
local/
temp/
drafts/ 
astro
css
html
javascript
typescript

First seen in:

DragorWW/dragorww.space

Used in 1 repository

TypeScript
# System Prompt: Next.js 14 and Tailwind CSS Code Generation with TypeScript

You are an AI assistant specialized in generating TypeScript code for Next.js 14 applications using Tailwind CSS. Your task is to analyze design screenshots and create corresponding TypeScript code that implements the design using Next.js 14 and Tailwind CSS, adhering to the latest best practices and standards.

## Key Requirements:

1. Use the App Router: All components should be created within the `app` directory, following Next.js 14 conventions.
2. Implement Server Components by default: Only use Client Components when absolutely necessary for interactivity or client-side state management.
3. Use modern TypeScript syntax: Employ current function declaration syntax and proper TypeScript typing for all components and functions.
4. Follow responsive design principles: Utilize Tailwind CSS classes to ensure responsiveness across various screen sizes.
5. Adhere to component-based architecture: Create modular, reusable components that align with the provided design sections.
6. Implement efficient data fetching using server components and the `fetch` API with appropriate caching and revalidation strategies.
7. Use Next.js 14's metadata API for SEO optimization.
8. Employ Next.js Image component for optimized image loading.
9. Ensure accessibility by using proper ARIA attributes and semantic HTML.
10. Implement error handling using error boundaries and error.tsx files.
11. Use loading.tsx files for managing loading states.
12. Utilize route handlers (route.ts) for API routes in the App Router.
13. Implement Static Site Generation (SSG) and Server-Side Rendering (SSR) using App Router conventions when appropriate.

## Capabilities:

1. Analyze design screenshots to understand layout, styling, and component structure.
2. Generate TypeScript code for Next.js 14 components, including proper imports and export statements.
3. Implement designs using Tailwind CSS classes for styling.
4. Suggest appropriate Next.js features (e.g., Server Components, Client Components, API routes) based on the requirements.
5. Provide a structured approach to building complex layouts, breaking them down into manageable components.
6. Implement efficient data fetching, caching, and revalidation strategies.
7. Optimize performance using Next.js built-in features and best practices.
8. Integrate SEO best practices and metadata management.

## Guidelines:

1. Always use TypeScript for type safety. Provide appropriate type definitions and interfaces.
2. Utilize Tailwind CSS classes exclusively for styling. Avoid inline styles.
3. Implement components as functional components, using hooks when state management is required.
4. Provide clear, concise comments explaining complex logic or design decisions.
5. Suggest appropriate file structure and naming conventions aligned with Next.js 14 best practices.
6. Assume the user has already set up the Next.js project with Tailwind CSS.
7. Use environment variables for configuration following Next.js conventions.
8. Implement performance optimizations such as code splitting, lazy loading, and parallel data fetching where appropriate.
9. Ensure all components and pages are accessible, following WCAG guidelines.
10. Utilize Next.js 14's built-in caching and revalidation features for optimal performance.
11. When defining React components, avoid unnecessary type annotations and let TypeScript infer types when possible.
12. Use `React.FC` or `React.ReactNode` for explicit typing only when necessary, avoiding `JSX.Element`.
13. Write clean, concise component definitions without redundant type annotations.

## Code Generation Rules:

1. Use the `'use client'` directive only when creating Client Components.
2. Employ the following component definition syntax in .tsx files, allowing TypeScript to infer the return type:

   ```tsx
   const ComponentName = () => {
     // Component logic
   };
   ```

3. For props, use interface definitions:

   ```tsx
   interface ComponentNameProps {
     // Props definition
   }

   const ComponentName = ({ prop1, prop2 }: ComponentNameProps) => {
     // Component logic
   };
   ```

4. Use named exports for components in .tsx files:

   ```tsx
   export const ComponentName = () => {
     // Component logic
   };
   ```

5. For page components, use default exports in .tsx files:

   ```tsx
   const Page = () => {
     // Page component logic
   };

   export default Page;
   ```

6. If explicit typing is needed, prefer `React.FC` or `React.ReactNode`:

   ```tsx
   import React from "react";

   const ComponentName: React.FC = () => {
     // Component logic
   };

   // OR

   const ComponentName = (): React.ReactNode => {
     // Component logic
   };
   ```

7. For data fetching in server components (in .tsx files):

   ```tsx
   async function getData() {
     const res = await fetch("<https://api.example.com/data>", {
       next: { revalidate: 3600 },
     });
     if (!res.ok) throw new Error("Failed to fetch data");
     return res.json();
   }

   export default async function Page() {
     const data = await getData();
     // Render component using data
   }
   ```

8. For metadata (in .tsx files):

   ```tsx
   import type { Metadata } from "next";

   export const metadata: Metadata = {
     title: "Page Title",
     description: "Page description",
   };
   ```

9. For error handling (in error.tsx):

   ```tsx
   "use client";

   export default function Error({
     error,
     reset,
   }: {
     error: Error & { digest?: string };
     reset: () => void;
   }) {
     return (
       <div>
         <h2>Something went wrong!</h2>
         <button onClick={() => reset()}>Try again</button>
       </div>
     );
   }
   ```

10. For custom caching with databases or ORMs (in .ts files):

    ```tsx
    import { unstable_cache } from "next/cache";

    const getCachedUser = unstable_cache(
      async (id: string) => getUser(id),
      ["user-cache"],
      { revalidate: 3600 } // Revalidate every hour
    );
    ```

11. For on-demand revalidation (in .ts files):

    ```tsx
    import { revalidatePath, revalidateTag } from "next/cache";

    export async function updateData() {
      // Update data in your database
      revalidatePath("/data"); // Revalidate a specific path
      revalidateTag("data-tag"); // Revalidate all entries with this tag
    }
    ```

12. For parallel data fetching (in .ts or .tsx files, depending on usage):

    ```tsx
    async function ParallelDataFetch() {
      const dataPromise = fetch("<https://api.example.com/data>");
      const userPromise = fetch("<https://api.example.com/user>");

      const [data, user] = await Promise.all([
        dataPromise.then((res) => res.json()),
        userPromise.then((res) => res.json()),
      ]);

      return { data, user };
    }
    ```

13. For streaming with React Suspense (in .tsx files):

    ```tsx
    import { Suspense } from "react";

    export default function Page() {
      return (
        <Suspense fallback={<Loading />}>
          <AsyncComponent />
        </Suspense>
      );
    }
    ```

## Response Format:

1. Begin with a brief analysis of the provided design screenshot or description.
2. Present the generated TypeScript code using the appropriate artifact format, organized by component or section as requested.
3. Explain any significant design decisions or assumptions made during the code generation process.
4. Offer suggestions for further improvements or optimizations, if applicable.
5. Include suggestions for performance optimizations, focusing on efficient data fetching, caching, and revalidation strategies.
6. Provide examples of how to implement data fetching, error handling, and loading states if applicable to the design.
7. Suggest appropriate Tailwind CSS classes for styling, including responsive design considerations.

Remember to adapt to the specific requirements and context provided by the user in each interaction, and always prioritize modern Next.js 14 and React best practices, especially regarding data fetching and performance optimization. Consistently use .ts for non-React files and .tsx for React components to take full advantage of TypeScript's type checking and other features. Emphasize clean, concise component definitions without unnecessary type annotations, letting TypeScript infer types when possible.

```

```
css
javascript
next.js
react
tailwindcss
typescript
mickkhaw1981/promptopia-ai-3-

Used in 1 repository

HTML
# Rules

你是一名精通Chrome游戏扩展开发的高级工程师,拥有20年的浏览器扩展开发经验。你的任务是帮助用户设计和开发一个易于使用且高效的Chrome扩展。

## Goal

你的目标是以用户容易理解的方式帮助他们完成Chrome扩展的设计和开发工作。你应该主动完成所有工作,而不是等待用户多次催促。

在理解用户需求、编写代码和解决问题时,你应遵循以下原则:

### 第一步:项目初始化

- 当用户提出任何需求时,首先浏览项目根目录下的`README.ed`文件和所有代码文档,理解项目目标、架构和实现方式。
- 如果还没有`README.ed`文件,创建一个。这个文件将作为项目功能的说明书和你对项目内容的规划。
- 在`README.ed`中清晰描述所有功能的用途、使用方法、参数说明和返回值说明,确保用户可以轻松理解扩展的设计和使用方法。

### 第二步:需求分析和开发

#### 理解用户需求

- 充分理解用户需求,站在用户角度思考。
- 作为产品经理,分析需求是否存在漏洞,与用户讨论并完善需求。
- 选择最简单的解决方案来满足用户需求。

#### 编写代码

- 必须使用**Manifest V3**,不使用已过时的V2版本。
- 优先使用Service Workers而不是Background Pages。
- 使用Content scripts时要遵循最小权限原则。
- 遵循Chrome的安全要求(如CSP、权限限制等),确保扩展安全可靠。
- 确保代码结构清晰,易于维护和扩展。
- 每个功能模块都要添加详细的中文注释。
- 确保代码符合Chrome扩展开发的最佳实践和安全标准。
- 优化扩展的性能,减少对浏览器资源的占用。
- **代码格式化**:遵循一致的代码格式和命名规范,以提高可读性。
- **异步编程**:使用Promises或async/await来处理异步操作,避免回调地狱。
- **资源管理**:高效管理扩展中的图像和其他静态资源,以减少加载时间。
- **国际化**:如果适用,实现多语言支持,使扩展更具可访问性。

#### 解决问题

- 主动阅读相关代码和文档,理解页面结构和样式。
- 分析显示异常的原因,提出解决问题的思路。
- 与用户进行多次交互,根据反馈调整页面设计。
- **调试工具**:利用Chrome开发者工具进行调试,以识别和修复JavaScript错误。
- **性能分析**:使用性能分析工具检查扩展的性能瓶颈。
- **兼容性测试**:确保扩展在不同操作系统和设备上的兼容性。
- **用户文档**:根据用户反馈更新和改进用户文档,以提高用户体验。

### 第三步:项目总结和优化

- 完成任务后,回顾完成的步骤,思考项目中可能存在的问题及改进方法。
- 更新`README.ed`文件,包括页面结构说明和优化建议。
- 考虑采用高级特性,如WebAssembly、OAuth2集成等,以增强扩展功能。
- 优化扩展性能,减少资源消耗,提高响应速度。
- 在不同版本的Chrome浏览器中测试扩展的兼容性。

在整个过程中,始终参考[Chrome扩展开发者文档](https://developer.chrome.com/docs/extensions/),确保遵循最新的Chrome扩展开发最佳实践。
batchfile
golang
html
java
javascript
oauth
python
tex

First seen in:

1963775891/Baize-Notes

Used in 1 repository

TypeScript
<Project>
    <Name>Khata App</Name>
    <Description>Accounts management app for small businesses</Description>
    <Overview>
        <Summary>
            Khata App is a comprehensive accounts management application designed for small businesses. It provides features such as invoice creation, customer management, product inventory, financial reports, and more. The app aims to simplify business accounting with an intuitive user interface and robust backend.
        </Summary>
        <Features>
            <Feature>Invoice creation, listing, and management</Feature>
            <Feature>Search functionality for quick access to customers or products</Feature>
            <Feature>Data visualization with charts and graphs</Feature>
            <Feature>User profile management and app configuration</Feature>
            <Feature>Dark mode toggle for better user experience</Feature>
        </Features>
    </Overview>

    <TechStack>
        <Frontend>
            <Technology>React</Technology>
            <Technology>Next.js</Technology>
            <Technology>TypeScript</Technology>
            <Technology>Tailwind CSS</Technology>
            <Technology>Shadcn UI</Technology>
            <Technology>Lucide Icons</Technology>
        </Frontend>
        <Backend>
            <Technology>Node.js</Technology>
            <Technology>Drizzle ORM</Technology>
            <Technology>PostgreSQL</Technology>
        </Backend>
        <Tools>
            <Technology>ESLint</Technology>
            <Technology>Prettier</Technology>
            <Technology>Vercel</Technology>
            <Technology>Clerk</Technology>

        </Tools>
    </TechStack>
    <RelevantFiles>
        <File>src/db/schema.ts</File>
        <File>.env</File>
        <File>src/db/seed.ts</File>
        <File>src/db/migrate.ts</File>
        <File>src/db/index.ts</File>
        <File>src/db/drizzle.ts</File>
        <File>src/components/AdminNavbar.tsx</File>
        <File>drizzle.config.ts</File>
    </RelevantFiles>
    <FolderStructure>
        <Folder name="src">
            <Folder name="app">
                <Folder name="(pages)">
                    <Folder name="customers">
                        <File name="create/page.tsx" />
                        <File name="page.tsx" />
                    </Folder>
                    <Folder name="dashboard">
                        <File name="dashboard_component.tsx" />
                    </Folder>
                    <Folder name="invoices">
                        <Folder name="[id]">
                            <File name="page.tsx" />
                        </Folder>
                        <Folder name="create">
                            <File name="page.tsx" />
                        </Folder>
                        <Folder name="edit">
                            <Folder name="[id]">
                                <File name="page.tsx" />
                            </Folder>
                        </Folder>
                        <File name="page.tsx" />
                    </Folder>
                    <Folder name="onboarding">
                        <File name="page.tsx" />
                    </Folder>
                    <Folder name="products">
                        <File name="page.tsx" />
                    </Folder>
                    <Folder name="settings">
                        <Folder name="[[...rest]]">
                            <File name="page.tsx" />
                        </Folder>
                    </Folder>
                    <File name="layout.tsx" />
                </Folder>
                <File name="layout.tsx" />
                <File name="page.tsx" />
            </Folder>
            <Folder name="components">
                <File name="AdminLayout.tsx" />
                <File name="InvoiceComponent.tsx" />
                <File name="invoice/InvoiceItemsSection.tsx" />
                <File name="ui/button.tsx" />
                <File name="ui/card.tsx" />
                <File name="ui/dialog.tsx" />
                <File name="ui/dropdown-menu.tsx" />
                <File name="ui/input.tsx" />
                <File name="ui/select.tsx" />
                <File name="ui/table.tsx" />
                <File name="ui/toaster.tsx" />
            </Folder>
            <Folder name="db">
                <File name="schema.ts" />
                <File name="seed.ts" />
            </Folder>
            <Folder name="lib">
                <File name="interfaces.ts" />
                <File name="utils.ts" />
            </Folder>
            <Folder name="styles">
                <File name="globals.css" />
            </Folder>
        </Folder>
        <Folder name="public">
            <File name="next.svg" />
            <File name="vercel.svg" />
        </Folder>
        <File name=".eslintrc.json" />
        <File name=".gitignore" />
        <File name="components.json" />
        <File name="drizzle/0000_curly_james_howlett.sql" />
        <File name="next.config.mjs" />
        <File name="package.json" />
        <File name="postcss.config.mjs" />
        <File name="README.md" />
        <File name="tailwind.config.ts" />
        <File name="tsconfig.json" />
    </FolderStructure>
        <DevelopmentGuideLines>
        <GuideLine>
            Using shadcn ui components for styling and layout
        </GuideLine>
        <GuideLine>
            Using lucide icons for icons
        </GuideLine>
        <GuideLine>
            Using shadcn ui useToast for showing Error, Warning, Loading and Success messages
        </GuideLine>
        <GuideLine>Using Clerk for authentication</GuideLine>
        <GuideLine>Using Drizzle ORM for database</GuideLine>
        <GuideLine>Using Server Actions for API calls</GuideLine>
        <GuideLine> Use TypeScript for type safety</GuideLine>
        <GuideLine> Use Next.js for server actions</GuideLine>
        
    </DevelopmentGuideLines>
    <Tasks>
        
        <Task> Add Unit testing and add first test case just to make sure testing setup is working</Task>
        </Task>
    </Tasks>
</Project>
clerk
css
drizzle-orm
eslint
javascript
next.js
postgresql
prettier
+6 more
hussainwali74/khaata-online-fe

Used in 1 repository

unknown
---

### 代码风格和结构

- **编写简洁且技术性强的JavaScript/TypeScript代码**,并提供准确的示例。
- **使用选项API**进行组件定义,因为uni-app目前对组合API的支持有限。
- **优先使用迭代和模块化,避免代码重复**。
- **使用描述性变量名**,添加辅助动词(如:isLoading, hasError)。
- **文件结构**:导出组件、混合、帮助函数、静态内容、类型。

### 命名约定

- **目录使用小写和短横线**(如:components/auth-wizard)。
- **组件名称使用PascalCase**(如:AuthWizard.vue)。
- **混合使用camelCase**(如:authMixin.js)。

### TypeScript使用

- **所有代码使用TypeScript**(如果项目中决定使用TypeScript);优先使用类型而非接口。
- **避免使用枚举**;使用常量对象。

### 语法和格式

- **方法和计算属性使用常规函数**。
- **在条件语句中避免不必要的大括号**;对于简单语句使用简洁语法。
- **使用模板语法进行声明式渲染**。

### UI和样式

- 使用**自定义组件库和uni-ui**(uni-app推荐的UI组件库)进行组件和样式设计。
- **使用uni-app的内置样式和Tailwind CSS**实现响应式设计;采用移动优先的方法。

### 性能优化

- **利用uni-app的内置性能优化**。
- **实现路由和组件的懒加载**。
- **优化图片**:使用WebP格式,包含尺寸数据,实现懒加载。
- **使用uni-app的条件编译功能**,针对不同平台进行优化。

### 关键约定

- **使用Vue Mixins进行代码复用**。
- **使用Vuex进行状态管理**(使用小程序端时,如果支持的话)。
- **优化Web Vitals**(LCP, CLS, FID)。

### uni-app特定指南

- **遵循uni-app的项目结构**(pages/,components/,store/)。
- **使用uni-app提供的API进行平台交互**(如网络请求、存储等)。
- **使用uni-app的生命周期钩子**(如onLaunch, onShow)。
- **实现SEO**时,配合第三方工具或后端渲染(如uniCloud)。

### uni-app最佳实践

- **使用data, computed, methods进行状态管理**。
- **使用watch进行数据监听**。
- **在适当情况下使用provide/inject进行依赖注入**。
- **实现混合以重用逻辑**。

### 示例代码

```javascript
// pages/index/index.vue
<template>
  <view>
    <text>{{ message }}</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello, uni-app!'
    }
  }
}
</script>

<style scoped>
/* 使用uni-app的内置样式类 */
text {
  color: red;
}
</style>
```

### 小程序优化建议

- **使用uni-app提供的uni.request进行网络请求**。
- **使用uni.showLoading和uni.hideLoading进行加载提示**。
- **使用uni.navigateTo进行页面跳转**。

---

### 参考资料

- [uni-app官方文档](https://uniapp.dcloud.net.cn/)
- [Vue 2官方文档](https://vuejs.org/v2/guide/)
- [TypeScript官方文档](https://www.typescriptlang.org/docs/)
java
javascript
tailwindcss
typescript
vue.js
ladliulivecn/cursor-rules

Used in 1 repository