Awesome Cursor Rules Collection

Showing 301-312 of 1033 matches

TypeScript
# Cursor Rules - Tampa Devs Mentorship Platform

## General Principles

- **Modularity Over Duplication**: Prefer iteration and modularization over code duplication.
- **Descriptive Naming**: Use descriptive variable names with auxiliary verbs (e.g., `isLoading`, `hasError`).
- **File Structure**: Structure files in the following order:
  1. Exported component
  2. Subcomponents
  3. Helpers
  4. Static content
  5. Types

## Project Structure

- **Directory Naming**: Use lowercase with dashes for directories (e.g., `components/auth-wizard`).
- **Feature-Based Organization**: Organize code by feature or domain rather than by type.
- **tRPC Placement**: Place tRPC routers and procedures in the `src/server/api` directory.
- **Prisma Setup**: Keep Prisma models and migrations in the `prisma` directory.
- **App Router**: Use the Next.js App Router located in the `app` directory for routing.
- **UI Library Directory**: Place all UI components following atomic design principles in the `src/ui` directory.

## Atomic Design Principles

- **Atomic Structure**: Organize UI components into atoms, molecules, organisms, templates, and pages.
  - **Atoms**: Basic building blocks (e.g., buttons, inputs).
  - **Molecules**: Combinations of atoms (e.g., form fields).
  - **Organisms**: Complex components composed of molecules and atoms (e.g., headers, footers).
  - **Templates**: Page-level layouts that combine organisms.
  - **Pages**: Specific instances of templates with real content.
- **Directory Layout**:
  - `src/ui/atoms`
  - `src/ui/molecules`
  - `src/ui/organisms`
  - `src/ui/templates`
  - `src/ui/pages`

## Naming Conventions

- **Components and Hooks**: Use PascalCase (e.g., `UserProfile`, `useAuth`).
- **Variables and Functions**: Use camelCase (e.g., `userName`, `handleSubmit`).
- **Constants**: Use UPPER_SNAKE_CASE (e.g., `MAX_RETRY_COUNT`).
- **Exports**: Favor named exports for components.

## TypeScript Usage

- **Consistent Typing**: Use TypeScript for all code to ensure type safety.
- **Interfaces Over Types**: Prefer `interface` declarations for object shapes to allow declaration merging.
- **Avoid Enums**: Use union types or maps instead of `enum`s for simplicity.
- **Functional Components**: Define React components as functions with explicit return types.
- **End-to-End Type Safety**: Leverage tRPC and Prisma for type-safe API and database interactions.

## Syntax and Formatting

- **Function Declarations**: Use the `function` keyword for pure functions.
- **Concise Conditionals**: Avoid unnecessary curly braces in simple conditionals.
- **Declarative JSX**: Write JSX in a clear and declarative manner, avoiding inline logic.
- **Linting and Formatting**: Adhere to Prettier and ESLint configurations provided by the t3 stack.

## UI and Styling

- **Component Libraries**: Use **shadcn/ui** and **Radix UI** components for building the interface.
- **Tailwind CSS**: Utilize Tailwind CSS for utility-first styling; avoid custom CSS when possible.
- **Responsive Design**: Implement responsive layouts using Tailwind's mobile-first approach.
- **Class Management**: Use `classnames` or `clsx` libraries for conditional class names.

### shadcn/ui Integration

- **Customizable Components**: Use shadcn/ui components as a base and customize them as needed.
- **Consistent Styling**: Maintain a consistent look and feel across the application by adhering to shadcn/ui design patterns.
- **Dark Mode Support**: Implement dark mode using shadcn/ui's theming capabilities.

### Atomic Design with `src/ui` Directory

- **Atomic Components**: Place all UI components in the `src/ui` directory, organized by atomic design levels.
- **Reusability**: Build components to be reusable and composable across different parts of the application.
- **Isolation**: Ensure UI components are decoupled from business logic and can be tested independently.
- **Examples**:
  - **Atoms**: `src/ui/atoms/Button.tsx`, `src/ui/atoms/Input.tsx`
  - **Molecules**: `src/ui/molecules/FormField.tsx`
  - **Organisms**: `src/ui/organisms/Navbar.tsx`
  - **Templates**: `src/ui/templates/DashboardLayout.tsx`
  - **Pages**: `src/ui/pages/HomePage.tsx`

## Authentication and Authorization

- **NextAuth.js Integration**: Implement authentication flows using NextAuth.js.
- **Session Handling**: Access session data using the `useSession` hook in client components or `getServerSession` in server components.
- **Protected Routes**: Secure pages and API routes by checking authentication status and permissions.

## Data Fetching and State Management

- **tRPC Usage**: Use tRPC for type-safe API communication between client and server.
- **React Query**: Leverage React Query (integrated with tRPC) for data fetching and caching.
- **Server Components**: Prefer React Server Components for rendering whenever possible.
- **Local State Management**: Use local component state or React Query; avoid global state unless necessary.

## Database and ORM

- **Prisma ORM**: Use Prisma for database interactions with auto-generated types.
- **Schema Management**: Define schemas in `prisma/schema.prisma` and keep under version control.
- **Migrations**: Use Prisma migrations for consistent schema changes across environments.
- **Data Validation**: Validate data at both the database level with Prisma and at the API level with tRPC.

## Performance Optimization

- **Minimize 'use client'**: Limit the use of `'use client'` to components that require client-side interactivity.
- **Effects and State**: Minimize `useEffect` and `setState`; prefer server-side data fetching.
- **Dynamic Imports**: Use `next/dynamic` for non-critical components to reduce initial load times.
- **Image Optimization**: Use Next.js `Image` component with WebP format and lazy loading.
- **Caching Strategies**: Implement caching with React Query and proper HTTP headers.

## Key Conventions

- **URL State Management**: Use `nuqs` for managing URL search parameters.
- **Optimize Web Vitals**: Focus on improving LCP, CLS, and FID metrics.
- **Limit 'use client' Usage**:
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.
- **Follow Next.js Docs**: Adhere to Next.js documentation for data fetching, rendering, and routing.

## Routing and Navigation

- **App Router Usage**: Define routes in the `app` directory using the Next.js App Router.
- **Layout Components**: Use `layout.tsx` files for shared layouts in nested routes.
- **Dynamic Routes**: Implement dynamic routing with square brackets (e.g., `[id]/page.tsx`).
- **Client-Side Navigation**: Use Next.js `Link` component for navigation between pages.

## Error Handling

- **tRPC Error Management**: Handle errors in tRPC procedures with proper error codes and messages.
- **Client-Side Errors**: Use error boundaries to catch and handle errors in React components.
- **User Feedback**: Provide meaningful error messages and options for users to retry actions.

## Security Best Practices

- **Input Validation**: Always validate and sanitize user inputs on the server side.
- **Secure Authentication**: Use secure session management and CSRF protection with NextAuth.js.
- **Environment Variables**: Keep sensitive information in environment variables, not in code.
- **HTTPS Enforcement**: Serve the application over HTTPS in production environments.

## Testing

- **Testing Framework**: Use **Vitest** as the primary testing framework.
- **Unit and Integration Tests**:
  - **React Testing Library**: Utilize React Testing Library for testing React components.
  - **jest-dom**: Include `@testing-library/jest-dom` for extended DOM assertions.
- **End-to-End Testing**:
  - **Playwright**: Use Playwright for E2E testing to simulate real user interactions.
- **Test Organization**:
  - Place unit tests alongside the components in `__tests__` directories.
  - Organize E2E tests in a separate `tests/e2e` directory.
- **Mocking and Stubbing**:
  - Use Vitest's mocking capabilities to mock external modules and APIs.
  - Mock tRPC procedures and Prisma client where necessary.
- **Continuous Integration**:
  - Integrate tests into the CI/CD pipeline to automatically run on each commit or pull request.
  - Use code coverage tools to ensure adequate test coverage.
- **Best Practices**:
  - Write tests that are fast, reliable, and deterministic.
  - Prefer testing user behavior over implementation details.
  - Use `beforeEach` and `afterEach` hooks to set up and clean up test environments.

## Documentation and Comments

- **Inline Comments**: Use comments to explain complex logic or decisions.
- **Project Documentation**: Maintain up-to-date README and documentation for setup and usage.
- **Type Annotations**: Use TypeScript annotations to improve code readability and maintenance.

## Collaboration and Version Control

- **Git Practices**: Use meaningful commit messages and a consistent branching strategy.
- **Code Reviews**: Conduct peer reviews to maintain code quality.
- **Pull Requests**: Keep PRs focused and small to facilitate easier reviews.

## Accessibility

- **ARIA Attributes**: Implement ARIA attributes where necessary.
- **Semantic HTML**: Use semantic HTML elements for proper structure.
- **Keyboard Navigation**: Ensure all interactive elements are keyboard accessible.
- **Contrast Ratios**: Use color combinations that meet WCAG guidelines.
auth.js
css
dockerfile
eslint
javascript
jest
less
nestjs
+15 more
TampaDevs/mentorship.tampa.dev

Used in 1 repository

TypeScript

  You are an expert in TypeScript, Node.js, Next.js, Next.js App Router, React, Serverless, Shadcn, SQLite and Tailwind.

Database and Types:
- Use SQLite through better-sqlite3 with lib/db.ts connection
- Follow types/db.ts as source of truth for all data models:
  - Producto: Products with stock limits
  - Almacen: Warehouses
  - Inventario: Stock tracking
  - Use Create/Update prefix for DTOs

Data Layer Best Practices:
- Use transactions for multi-table operations
- Validate stock limits at data layer
- Maintain SKU as unique identifier
- Cache frequent inventory queries
- Handle DB constraints with proper error management

Type Conventions:
- Import types from @/types/db.ts
- Use optional chaining for relationships
- Maintain nullable consistency (field?: type | null)
- Use strict number types for stock quantities
- Match DTO types with SQLite schema constraints
  
  Code Style and Structure
  - Write concise, technical TypeScript code with accurate examples.
  - Use functional and declarative programming patterns; avoid classes.
  - Prefer iteration and modularization over code duplication.
  - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
  - Structure files: exported component, subcomponents, helpers, static content, types.
  
  Naming Conventions
  - Use lowercase with dashes for directories (e.g., components/auth-wizard).
  - Favor named exports for components.
  
  TypeScript Usage
  - Use TypeScript for all code; prefer interfaces over types.
  - Avoid enums; use maps instead.
  - Use functional components with TypeScript interfaces.
  - If a function has less than four types, declare them inline.
  
  Syntax and Formatting
  - Use the "function" keyword for pure functions.
  - Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
  - Use declarative JSX.
  - Comment the code using concise comments.
  - Reorder the imports to the top of the file so that they are grouped by type.
  - Remove unused imports.
  
  UI and Styling
  - Use Tailwind for components and styling.
  - Implement responsive design with Tailwind CSS; use a mobile-first approach.
  
  Performance Optimization
  - Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
  - Wrap client components in Suspense with fallback.
  - Use dynamic loading for non-critical components.
  - Optimize images: use WebP format, include size data, implement lazy loading.
  
  Key Conventions
  - Always use yarn as the package manager.
  - Always use app router configurations, not pages router.
  - Use 'nuqs' for URL search parameter state management.
  - Optimize Web Vitals (LCP, CLS, FID).
  - Limit 'use client':
    - Favor server components and Next.js SSR.
    - Use only for Web API access in small components.
    - Avoid for data fetching or state management.
  
  Follow Next.js docs for Data Fetching, Rendering, and Routing: https://nextjs.org/docs
  Follow Tailwind docs for Styling: https://tailwindcss.com/docs/guides/nextjs
  Follow Shadcn docs for Styling: https://ui.shadcn.com/docs/installation/next
  Follow React docs for React: https://react.dev/learn
css
javascript
less
next.js
react
shadcn/ui
sqlite
tailwindcss
+2 more
fobossalmeron/inventario-app

Used in 1 repository

JavaScript
# Defra AI Code Review Frontend

## Project Context
A Web Application for submitting code repositories for review. Also provides a interface for reviewing the code reviews. A frontend for the defra code review API.

## Language
- JavaScript
- TypeScript (for type checking only)

## Tech Stack
- Node.js
- Hapi.js (server framework)
- GOV.UK Frontend (UI components)     
- Nunjucks (template engine)
- Webpack (bundling and asset management)
- Babel (JavaScript transpilation)
- Jest (testing framework)
- ESLint & Prettier (code formatting and linting)
- SCSS (styling)
- PostCSS (CSS processing)
- Stylelint (CSS linting)

## Development Workflow
- Use npm scripts for common tasks
- always run `npm run format` after making any file changes
- always run `npm run lint:fix` after making any file changes
- when you are done modifying all the files, then run `npm run test` to ensure that your changes have not broken any existing functionality

## Project Structure
```
/
├── src/                    # Source code
│   ├── client/            # Frontend assets and code
│   │   ├── common/        # Shared client utilities and helpers
│   │   ├── javascripts/   # Client-side JavaScript
│   │   └── stylesheets/   # SCSS stylesheets
│   ├── server/            # Backend Node.js application code
│   │   ├── common/        # Shared server utilities
│   │   ├── error/         # Error handling and pages
│   │   ├── health/        # Health check endpoints
│   │   ├── home/          # Home page routes and handlers
│   │   ├── index.js       # Server entry point
│   │   └── router.js      # Route definitions
│   ├── config/            # Application configuration
│   └── index.js           # Application entry point
├── compose/               # Docker compose configuration files
├── .github/               # GitHub workflows and templates
├── .jest/                 # Jest test configuration
├── .husky/                # Git hooks configuration
├── config files           # Various configuration files:
│   ├── .eslintrc.cjs     # ESLint configuration
│   ├── .prettierrc.js    # Prettier configuration
│   ├── babel.config.cjs  # Babel configuration
│   ├── jest.config.js    # Jest configuration
│   ├── webpack.config.js # Webpack configuration
│   └── tsconfig.json     # TypeScript configuration
└── package.json          # Project dependencies and scripts
```

Key directories and their purposes:
- `src/client/common`: Shared client-side utilities and helpers
- `src/client/javascripts`: Client-side JavaScript modules
- `src/client/stylesheets`: SCSS styling organized into components, core, helpers, and partials
- `src/server/common`: Shared server-side utilities
- `src/server/error`: Error handling and error pages
- `src/server/health`: Health check endpoints
- `src/server/home`: Home page routes and handlers
- `compose/`: Docker compose files for different environments
- `.github/`: CI/CD workflows and GitHub-specific configuration
- `.jest/`: Test configuration and setup files
- `.husky/`: Git hooks for maintaining code quality

## Coding Standards

## Style
### Code Style
- Use Standard JS for linting and formatting.
- Maintain consistent indentation and code structure.
- Avoid nested callbacks; prefer async/await.
- Format code using prettier and use the .prettierrc file.
- Use JSDoc comments for type annotations in .js files
- Use TypeScript for type checking only (no .ts files)
- Include comprehensive JSDoc type definitions for function parameters and returns
- Follow TypeScript-enhanced ESLint rules

### Styling
- Use SCSS for styling
- Follow GOV.UK Frontend naming conventions for components
- Organize styles into:
  - components/ - For reusable components
  - core/ - For core layout elements
  - helpers/ - For mixins and functions
  - partials/ - For page-specific styles
  - variables/ - For shared variables
- Use BEM-style naming with 'app-' prefix for custom components

## Rules
### General Guidelines
- Use vanilla JavaScript; avoid TypeScript.
- Do not use front-end frameworks like React, Angular, or Vue.
- Ensure all code follows progressive enhancement principles.
- Use clear and descriptive variable and function names.
- Document complex code with comments.
- Separate concerns by organizing code logically.

### Functions
- Use named functions instead of arrow functions for top-level declarations
- Use arrow functions for callbacks and anonymous functions
- Function names should be camelCase and descriptive of their purpose

### Imports/Exports
- Use named exports instead of default exports
- Group imports by type (core Node.js modules first, then external packages, then internal imports)
- Use absolute imports with the '~' alias for internal project files
- Include JSDoc import statements for types when needed

### Types
- Use JSDoc comments for type annotations rather than TypeScript syntax in .js files
- TypeScript is used for type checking only (no .ts files)
- Include comprehensive type definitions for function parameters and returns

### Module System
- Use ES Modules (import/export) instead of CommonJS (require/module.exports)
- Always use named exports instead of default exports
- Add .js extension to all import statements

### File Structure
- Group related functionality into directories (e.g., helpers, components)
- Use index.js files to aggregate and re-export from directories
- Keep files focused on a single responsibility
- Use .gitkeep for empty directories that need to be tracked

### Configuration
- Use convict for configuration management
- Do not embedd secrets in the codebase.
- Validate configuration on startup
- Separate configuration by concern (e.g., redis, session, logging)
- Use postcss.config.js for PostCSS configuration
- Use stylelint.config.js for CSS linting rules
- Use nodemon.json for development server settings

### Error Handling
- Use explicit error types
- Log errors appropriately using the logging system
- Include stack traces in development but not production

### Node.js Standards
- Do not store session state on the app server.
- Use distributed caches for session management.
- Follow the same standards for linting and formatting as front-end code.

## Testing
- Use Jest as the testing framework
- Include comprehensive test cases covering success and error scenarios
- Test the functionality; not the implementation
- Write tests that cover end-to-end functionality covering multipule units
- For apis, test the API calls with expected input and output
- For UI's, test the interface with expected behaviours 
- Mock external dependencies like databases, file systems, API's
- Maintain .jest/setup.js for global test configuration and mocks

## Logging
- Use pino as the logging framework
- Log levels controlled via environment variables
- Different log formats for development (pretty) and production (ECS)
- Include request ID in logs for tracing
- Redact sensitive information in production logs

## Git Usage

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

### Commit Guidelines
- Use lowercase for messages
- Limit the commit message to one line, and no more than two concise, descriptive sentences
- Reference issue numbers when applicable

## Documentation
- Maintain clear README
- Use JSDoc for function and type documentation
- Document configuration options
- Include examples where appropriate

## Security
- Enable secure contexts in production
- Use TLS for Redis in production
- Implement proper session handling
- Set secure cookie flags in production
- Validate all inputs to prevent injection attacks.

## Nunjucks & GOV.UK Frontend Rules

### Template Structure
- Use `{% extends 'layouts/page.njk' %}` as the base template for all pages
- Place page-specific content within the `{% block content %}` block
- Use `govuk-` prefix for GOV.UK Frontend components
- Use `app-` prefix for custom components
- Keep templates DRY by using macros and includes

### Component Usage
- Import GOV.UK components globally in layout files using:
  ```njk
  {% from "govuk/components/[component-name]/macro.njk" import govuk[ComponentName] %}
  ```
- Import custom components globally in layout files using:
  ```njk
  {% from "[component-name]/macro.njk" import app[ComponentName] %}
  ```
- Follow GOV.UK Frontend component parameter structure:
  ```njk
  {{ govukComponent({
    key: value,
    classes: "additional-classes"
  }) }}
  ```

### Custom Components
- Create components in `src/server/common/components/[component-name]/`
- Include three files per component:
  1. `template.njk` - Component markup
  2. `macro.njk` - Component macro definition
  3. `_[component-name].scss` - Component styles
- Use BEM naming convention with 'app-' prefix
- Include data-testid attributes for testing

### Layout & Grid
- Use GOV.UK Frontend grid system:
  - `govuk-grid-row` for rows
  - `govuk-grid-column-*` for columns
- Follow GOV.UK Frontend spacing units using `govuk-spacing()` function
- Use GOV.UK Frontend typography classes (e.g., `govuk-body`, `govuk-heading-xl`)

### Styling
- Import GOV.UK Frontend styles using:
  ```scss
  @use "govuk-frontend" as *;
  ```
- Use GOV.UK Frontend color variables and functions
- Follow GOV.UK Frontend breakpoints using `govuk-media-query()`
- Namespace custom styles with 'app-' prefix

### Testing
- Use the provided `renderComponent()` helper for component testing
- Include data-testid attributes for component testing
- Test component variations and edge cases

### Configuration
- Configure Nunjucks environment with:
  - `trimBlocks: true`
  - `lstripBlocks: true`
  - `autoescape: true`
- Set up proper paths for GOV.UK Frontend templates
- Use filters for data formatting (e.g., dates, currency)
- Add custom globals when needed

### Best Practices
- Keep templates focused on presentation logic
- Use macros for reusable template patterns
- Follow progressive enhancement principles
- Maintain accessibility standards
- Use proper HTML5 semantic elements
- Include ARIA attributes where necessary

### New Page Template Structure
- Create new pages using the following template structure:
  1. Controller file (`controller.js`) - Handles route logic
  2. Controller test file (`controller.test.js`) - Tests for controller
  3. Route registration file (`index.js`) - Registers routes with Hapi
  4. View template (`index.njk`) - Page template following this structure:
  ```njk
  {% extends 'layouts/page.njk' %}

  {% block content %}
    {{ appHeading({
      text: heading,
      caption: "[caption here]"
    }) }}

    [html content here]

  {% endblock %}
  ```

- Each new page directory should include:
  - `controller.js` - Route handler logic
  - `controller.test.js` - Controller tests
  - `index.js` - Route registration
  - `index.njk` - Page template
- Pass page data from controller to template using h.view()
- Use consistent variable naming between controller and template
- Include comprehensive tests for new routes
angular
bun
docker
dockerfile
eslint
golang
java
javascript
+12 more
DEFRA/defra-ai-codereview-frontend

Used in 1 repository

TypeScript
You are an expert senior software engineer specializing in modern web development, with deep expertise in TypeScript, React 19, Next.js 15 (App Router), Vercel AI SDK, Shadcn UI, Radix UI, and Tailwind CSS. You are thoughtful, precise, and focus on delivering high-quality, maintainable solutions.

## Analysis Process

Before responding to any request, follow these steps:

1. Request Analysis

   - Determine task type (code creation, debugging, architecture, etc.)
   - Identify languages and frameworks involved
   - Note explicit and implicit requirements
   - Define core problem and desired outcome
   - Consider project context and constraints

2. Solution Planning

   - Break down the solution into logical steps
   - Consider modularity and reusability
   - Identify necessary files and dependencies
   - Evaluate alternative approaches
   - Plan for testing and validation

3. Implementation Strategy
   - Choose appropriate design patterns
   - Consider performance implications
   - Plan for error handling and edge cases
   - Ensure accessibility compliance
   - Verify best practices alignment

## Code Style and Structure

### General Principles

- Write concise, readable TypeScript code
- Use functional and declarative programming patterns
- Follow DRY (Don't Repeat Yourself) principle
- Implement early returns for better readability
- Structure components logically: exports, subcomponents, helpers, types

### Naming Conventions

- Use descriptive names with auxiliary verbs (isLoading, hasError)
- Prefix event handlers with "handle" (handleClick, handleSubmit)
- Use lowercase with dashes for directories (components/auth-wizard)
- Favor named exports for components

### TypeScript Usage

- Use TypeScript for all code
- Prefer interfaces over types
- Avoid enums; use const maps instead
- Implement proper type safety and inference
- Use `satisfies` operator for type validation

## React 19 and Next.js 15 Best Practices

### Component Architecture

- Favor React Server Components (RSC) where possible
- Minimize 'use client' directives
- Implement proper error boundaries
- Use Suspense for async operations
- Optimize for performance and Web Vitals

### State Management

- Use `useActionState` instead of deprecated `useFormState`
- Leverage enhanced `useFormStatus` with new properties (data, method, action)
- Implement URL state management with 'nuqs'
- Minimize client-side state

### Async Request APIs

```typescript
// Always use async versions of runtime APIs
const cookieStore = await cookies();
const headersList = await headers();
const { isEnabled } = await draftMode();

// Handle async params in layouts/pages
const params = await props.params;
const searchParams = await props.searchParams;
```

### Data Fetching

- Fetch requests are no longer cached by default
- Use `cache: 'force-cache'` for specific cached requests
- Implement `fetchCache = 'default-cache'` for layout/page-level caching
- Use appropriate fetching methods (Server Components, SWR, React Query)

### Route Handlers

```typescript
// Cached route handler example
export const dynamic = "force-static";

export async function GET(request: Request) {
  const params = await request.params;
  // Implementation
}
```

## Vercel AI SDK Integration

### Core Concepts

- Use the AI SDK for building AI-powered streaming text and chat UIs
- Leverage three main packages:
  1. `ai` - Core functionality and streaming utilities
  2. `@ai-sdk/[provider]` - Model provider integrations (e.g., OpenAI)
  3. React hooks for UI components

### Route Handler Setup

```typescript
import { OpenAIStream, StreamingTextResponse } from "ai";
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

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

  const response = await openai.chat.completions.create({
    model: "gpt-4-turbo-preview",
    stream: true,
    messages,
  });

  const stream = OpenAIStream(response);
  return new StreamingTextResponse(stream);
}
```

### Chat UI Implementation

```typescript
"use client";

import { useChat } from "ai/react";

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    maxSteps: 5, // Enable multi-step interactions
  });

  return (
    <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
      {messages.map((m) => (
        <div key={m.id} className="whitespace-pre-wrap">
          {m.role === "user" ? "User: " : "AI: "}
          {m.toolInvocations ? (
            <pre>{JSON.stringify(m.toolInvocations, null, 2)}</pre>
          ) : (
            m.content
          )}
        </div>
      ))}

      <form onSubmit={handleSubmit}>
        <input
          className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl"
          value={input}
          placeholder="Say something..."
          onChange={handleInputChange}
        />
      </form>
    </div>
  );
}
```

## UI Development

### Shadcn UI Components

- Use shadcn/ui as the primary component library
- Follow the CLI installation pattern: `npx shadcn-ui@latest add [component]`
- Customize components through the global.css and components.json
- Extend components using the cn utility for conditional classes
- Common component usage patterns:

  ```typescript
  // Button example
  import { Button } from "@/components/ui/button";

  // Dialog example
  import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
  } from "@/components/ui/dialog";

  // Form components
  import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
  } from "@/components/ui/form";
  ```

- Maintain consistency with Tailwind theme configuration
- Use the shadcn/ui registry pattern for Server Components
- Implement proper form validation with react-hook-form integration
- Follow the shadcn/ui theming system for dark mode support

### Styling

- Use Tailwind CSS with a mobile-first approach
- Implement Shadcn UI and Radix UI components
- Follow consistent spacing and layout patterns
- Ensure responsive design across breakpoints
- Use CSS variables for theme customization

### Accessibility

- Implement proper ARIA attributes
- Ensure keyboard navigation
- Provide appropriate alt text
- Follow WCAG 2.1 guidelines
- Test with screen readers

### Performance

- Optimize images (WebP, sizing, lazy loading)
- Implement code splitting
- Use `next/font` for font optimization
- Configure `staleTimes` for client-side router cache
- Monitor Core Web Vitals

## Configuration

### Next.js Config

```typescript
/** @type {import('next').NextConfig} */
const nextConfig = {
  // Stable features (formerly experimental)
  bundlePagesRouterDependencies: true,
  serverExternalPackages: ["package-name"],

  // Router cache configuration
  experimental: {
    staleTimes: {
      dynamic: 30,
      static: 180,
    },
  },
};
```

### TypeScript Config

```json
{
  "compilerOptions": {
    "strict": true,
    "target": "ES2022",
    "lib": ["dom", "dom.iterable", "esnext"],
    "jsx": "preserve",
    "module": "esnext",
    "moduleResolution": "bundler",
    "noEmit": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}
```

## Testing and Validation

### Code Quality

- Implement comprehensive error handling
- Write maintainable, self-documenting code
- Follow security best practices
- Ensure proper type coverage
- Use ESLint and Prettier

### Testing Strategy

- Plan for unit and integration tests
- Implement proper test coverage
- Consider edge cases and error scenarios
- Validate accessibility compliance
- Use React Testing Library

## Supabase Integration

### Authentication Setup

```typescript
// supabase.ts
import { createClient } from "@supabase/supabase-js";
import { Database } from "@/types/supabase";

export const supabase = createClient<Database>(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
```

### Auth Hooks and Components

```typescript
// hooks/useAuth.ts
import { useRouter } from "next/navigation";
import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";

export function useAuth() {
  const supabase = createClientComponentClient();
  const router = useRouter();

  const signIn = async (email: string, password: string) => {
    const { error } = await supabase.auth.signInWithPassword({
      email,
      password,
    });
    if (!error) router.refresh();
    return { error };
  };

  const signOut = async () => {
    const { error } = await supabase.auth.signOut();
    if (!error) router.refresh();
    return { error };
  };

  return { signIn, signOut };
}
```

### Server-Side Auth

```typescript
// middleware.ts
import { createMiddlewareClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  const supabase = createMiddlewareClient({ req, res });
  await supabase.auth.getSession();
  return res;
}
```

### Database Operations

```typescript
// utils/db.ts
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import type { Database } from "@/types/supabase";

export async function getUser() {
  const supabase = createServerComponentClient<Database>({ cookies });
  const {
    data: { user },
  } = await supabase.auth.getUser();
  return user;
}

// Example of a type-safe database query
export async function getUserPosts(userId: string) {
  const supabase = createServerComponentClient<Database>({ cookies });
  const { data, error } = await supabase
    .from("posts")
    .select("*")
    .eq("user_id", userId)
    .order("created_at", { ascending: false });

  if (error) throw error;
  return data;
}
```

### Type Safety

```typescript
// types/supabase.ts
export type Database = {
  public: {
    Tables: {
      posts: {
        Row: {
          id: string;
          created_at: string;
          title: string;
          content: string;
          user_id: string;
        };
        Insert: {
          title: string;
          content: string;
          user_id: string;
        };
        Update: {
          title?: string;
          content?: string;
        };
      };
      // Add other tables...
    };
  };
};
```

### Best Practices

- Use Server Components for initial data fetching
- Implement real-time subscriptions for live updates
- Handle auth state changes with middleware
- Generate types from your Supabase schema
- Use RLS (Row Level Security) for data protection
- Implement proper error handling for auth/db operations
- Cache frequently accessed data
- Use prepared statements for complex queries
- Implement proper connection pooling
- Monitor database performance

### Real-time Subscriptions

```typescript
"use client"

import { useEffect, useState } from 'react'
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'

export function RealtimePosts() {
  const [posts, setPosts] = useState<Post[]>([])
  const supabase = createClientComponentClient()

  useEffect(() => {
    const channel = supabase
      .channel('posts')
      .on('postgres_changes',
        { event: '*', schema: 'public', table: 'posts' },
        (payload) => {
          // Handle real-time updates
          console.log('Change received!', payload)
      })
      .subscribe()

    return () => {
      supabase.removeChannel(channel)
    }
  }, [supabase])

  return (
    // Your component JSX
  )
}
```

### React Query Best Practices

- Use TanStack Query v5 (React Query) for server state management
- Implement proper query keys and caching strategies:

  ```typescript
  // Structured query keys for better organization
  const queryKeys = {
    todos: {
      all: ["todos"] as const,
      lists: () => [...queryKeys.todos.all, "list"] as const,
      list: (id: string) => [...queryKeys.todos.lists(), id] as const,
      details: () => [...queryKeys.todos.all, "detail"] as const,
      detail: (id: string) => [...queryKeys.todos.details(), id] as const,
    },
  } as const;
  ```

- Configure global defaults:

  ```typescript
  // config/query-client.ts
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 1000 * 60 * 5, // 5 minutes
        gcTime: 1000 * 60 * 60 * 24, // 24 hours
        retry: 3,
        refetchOnWindowFocus: false,
      },
      mutations: {
        retry: 2,
      },
    },
  });
  ```

- Use custom hooks for reusable queries:

  ```typescript
  export function useTodos() {
    return useQuery({
      queryKey: queryKeys.todos.lists(),
      queryFn: fetchTodos,
      placeholderData: keepPreviousData,
    });
  }
  ```

- Implement optimistic updates:

  ```typescript
  const mutation = useMutation({
    mutationFn: updateTodo,
    onMutate: async (newTodo) => {
      await queryClient.cancelQueries({
        queryKey: queryKeys.todos.detail(newTodo.id),
      });
      const previousTodo = queryClient.getQueryData(
        queryKeys.todos.detail(newTodo.id)
      );

      queryClient.setQueryData(queryKeys.todos.detail(newTodo.id), newTodo);

      return { previousTodo };
    },
    onError: (err, newTodo, context) => {
      queryClient.setQueryData(
        queryKeys.todos.detail(newTodo.id),
        context?.previousTodo
      );
    },
    onSettled: (newTodo) => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.todos.detail(newTodo.id),
      });
    },
  });
  ```

- Use suspense mode appropriately:

  ```typescript
  const { data } = useQuery({
    queryKey: queryKeys.todos.detail(id),
    queryFn: () => fetchTodoById(id),
    suspense: true,
  });
  ```

- Implement infinite queries for pagination:

  ```typescript
  const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
    queryKey: queryKeys.todos.lists(),
    queryFn: fetchTodoPage,
    getNextPageParam: (lastPage) => lastPage.nextCursor,
  });
  ```

- Use prefetching for better UX:

  ```typescript
  // Prefetch on hover or route change
  const prefetchTodo = async (id: string) => {
    await queryClient.prefetchQuery({
      queryKey: queryKeys.todos.detail(id),
      queryFn: () => fetchTodoById(id),
    });
  };
  ```

- Handle loading and error states consistently:

  ```typescript
  const { isLoading, isError, error, data } = useQuery({
    queryKey: queryKeys.todos.lists(),
    queryFn: fetchTodos,
  });

  if (isLoading) return <LoadingSpinner />;
  if (isError) return <ErrorComponent error={error} />;
  ```

- Implement proper type safety:

  ```typescript
  interface Todo {
    id: string;
    title: string;
    completed: boolean;
  }

  const { data } = useQuery<Todo[], Error>({
    queryKey: queryKeys.todos.lists(),
    queryFn: fetchTodos,
  });
  ```

Remember: Prioritize clarity and maintainability while delivering robust, accessible, and performant solutions aligned with the latest React 19, Next.js 15, and Vercel AI SDK features and best practices.
bun
css
eslint
javascript
next.js
openai
postgresql
prettier
+7 more
jlfernandezfernandez/giftlist-app

Used in 1 repository

JavaScript
  You are an expert in JavaScript, WXML, WXSS, and Mobile UI for mini program development.
  
  Code Style and Structure:
  - Write Clean, Readable Code: Ensure your code is easy to read and understand. Use descriptive names for variables and functions.
  - Use Functional Components: Prefer functional components with hooks (useState, useEffect, etc.) over class components.
  - Component Modularity: Break down components into smaller, reusable pieces. Keep components focused on a single responsibility.
  - Organize Files by Feature: Group related components, hooks, and styles into feature-based directories (e.g., user-profile, chat-screen).

  Naming Conventions:
  - Variables and Functions: Use camelCase for variables and functions (e.g., isFetchingData, handleUserInput).
  - Components: Use PascalCase for component names (e.g., UserProfile, ChatScreen).
  - Directories: Use lowercase and hyphenated names for directories (e.g., user-profile, chat-screen).

  JavaScript Usage:
  - Avoid Global Variables: Minimize the use of global variables to prevent unintended side effects.

  mini program usage:
  - Use WXML for UI structure, WXSS for styling, and JavaScript for logic.
  - Leverage mini program components and APIs to build your app.
  - Use the WeUI library for consistent UI elements.

  Performance Optimization:
  - Optimize State Management: Avoid unnecessary state updates and use local state only when needed.
  - FlatList Optimization: Optimize FlatList with props like removeClippedSubviews, maxToRenderPerBatch, and windowSize.
  - Avoid Anonymous Functions: Refrain from using anonymous functions in renderItem or event handlers to prevent re-renders.

  UI and Styling:
  - Consistent Styling: Consistent styling for UI components.
  - Responsive Design: Ensure your design adapts to various screen sizes and orientations. Consider using responsive units and libraries like react-native-responsive-screen.

  References:
  - WeUI: https://weui.io/
  - Mini Program API: https://developers.weixin.qq.com/miniprogram/en/dev/framework/

  Refer to Mini Program Official Documentation for best practices and advanced features.

java
javascript
react

First seen in:

gaozih/ncba

Used in 1 repository

unknown

This is a monorepo for a web application.
`./supabase` contains a local instance of Supabase service.
`./trigger` contains the task files for @trigger.dev.
The other repository files are a Next.Js app router project.
Use node 20.x and yarn for package management.

## Code Style and Structure

Write concise, technical TypeScript code with accurate examples.
Use functional and declarative programming patterns; avoid classes.
Prefer iteration and modularization over code duplication.
Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
Structure files: exported component, subcomponents, helpers, static content, types.
use yarn for package management.

## Naming Conventions

Use lowercase with dashes for directories (e.g., components/auth-wizard).
Favor named exports for components.
Create and use shared components from the `./components` repository.

## TypeScript Usage

Use TypeScript for all code; prefer interfaces over types.
Avoid enums; use maps instead.
Use functional components with TypeScript interfaces.
Always check typescript types and fix typescript type errors before completion.

## Syntax and Formatting

Use the "function" keyword for pure functions.
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
Use declarative JSX.

## UI and Styling

Use NextUI and Tailwind CSS for components and styling.
Ensure NextUI components are only used in client side components.
Implement responsive design with Tailwind CSS; use a mobile-first approach.
Use NextUI classes to apply styles with support for themes.
Use Next.js layout.tsx to share common styles accross routes.

## Performance Optimization

Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
Wrap client components in Suspense with fallback.
Wrap dynamic components with Skeleton and provide an isLoaded property that returns true when loaded.
Use dynamic loading for non-critical components.
Optimize images: use WebP format, include size data, implement lazy loading.
Favor server components and Next.js SSR.

## Database Querying & Data Model creation

Use the Supabase SDK for data fetching and querying.
Use the the supabase helper utilities, import "createClient" from `@/utils/supabase/server` for server components and `@/utils/supabase/client` for client components.
For data model creation, use Supabase's schema builder.
Supabase types are in `./types/supabase.ts`.
Use server side actions and 'useCallback' when client components require data.
Never use "@supabase/auth-helpers-nextjs", always use @supabase/ssr and @supabase/supabase-js.
Create supabase migrations in the `./supabase/migrations/` directory.
Migration files must start with a timestamp, followed by the name.
Generate a new timestamp as EPOC, do not guess or hallucinate the time, always use the current time.


## Key Conventions

Optimize Web Vitals (LCP, CLS, FID).
Use only for Web API access in small components.
Avoid for data fetching or state management.
Follow Next.js app router specification for Data Fetching, Rendering, and Routing.

## Evaluation

Ensure all imported components are valid exports of the package.
Modify package.json to include any additional packages required.
Check and correct all errors before finishing.
next.js
react
supabase
tailwindcss
typescript
yarn
turnout-labs/product-stack

Used in 1 repository

Rust
- If there is an error, explain the cause of the error
- Do not omit details as much as possible
- All messages in the code should be in English

このリポジトリの基本技術スタックは以下である。
- TypeScript
    - React
    - Next.js
    - Tailwind CSS
- Rust
    - axum
    - sqlx
- MySQL(TiDB)
- aws

For *.md file
- Use Japanese
- Use PlantUML for diagrams
- markdownのドキュメントにタスクを書く場合は、以下のように書く。タスクの進行度に応じて絵文字を変える。
    - ✅ DONE
    - ✅ DONE
    - 🔄 IN PROGRESS
    - 📝 TODO
    - 📝 TODO
    - 📝 TODO

マイグレーションファイルは`sqlx`を使用して作成する。
crateのディレクトリで `sqlx migrate add -r <name>`で作成できる。

For Cargo.toml file
- パッケージのバージョンは`0.1.0`から始める。
- rootのCargo.tomlに書いてあるcrateを利用する場合は`workspace = true`を設定する。

For *.rs file
You are an expert in Rust.

- Use `#[derive(Debug, Clone, PartialEq, Eq, EnumString, Display)]` for enums
- idは全てULIDを全て小文字にしたものを使用する。def_id!(IdName, "prefix_")で生成できる。
- Error Handling in Rust. use `errors::Result` for error handling.
```rust
use errors::Result;

fn sample() -> Result<()> {w
    Ok(())
}
```

- Use `#[tokio::test]` for testing async functions.
```rust
#[tokio::test]
async fn test_sample() {
    let result = sample().await;
    assert!(result.is_ok());
}
```



For *.tsx file
- As an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI, and Tailwind CSS, write a web application that meets the following requirements:
- Code Style and Structure:
    - Write concise and technical TypeScript code.
    - Use functional and declarative programming patterns, avoiding classes.
    - Avoid code duplication, prioritizing iteration and modularization.
    - Use descriptive variable names including auxiliary verbs (e.g., `isLoading`, `hasError`).
    - Structure the file: exported components, subcomponents, helpers, static content, and types.
- Naming Conventions:
    - Use lowercase and dashes for directories (e.g., `components/auth-wizard`).
    - Prefer named exports for components.
- TypeScript Usage:
    - Use TypeScript for all code. Prefer interfaces over types.
    - Avoid enums, use maps instead.
    - Use functional components with TypeScript interfaces.
- Syntax and Formatting:
    - Use the `function` keyword for pure functions.
    - Avoid unnecessary curly braces in conditional statements, use concise syntax.
    - Use declarative JSX.
- UI and Styling:
    - Use Shadcn UI, Radix, and Tailwind for components and styling.
    - Implement responsive design with Tailwind CSS, using a mobile-first approach.
- Performance Optimization:
    - Minimize the use of `use client`, `useEffect`, and `setState`, prioritizing React Server Components (RSC).
    - Wrap client components with Suspense and provide fallbacks.
    - Use dynamic loading for non-critical components.
    - Optimize images: use WebP format, include size data, and implement lazy loading.
- Key Conventions:
    - Use `nuqs` for URL search parameter state management.
    - Optimize Web Vitals (LCP, CLS, FID).
    - Limit the use of `use client`.
    - Follow Next.js documentation for data fetching, rendering, and routing.
- Development Environment:
    - Install all necessary npm packages.
    - Ensure the application is fully functional and can run in development mode.
aws
golang
mysql
next.js
npm
radix-ui
react
rust
+3 more
quantum-box/google_calender_rs

Used in 1 repository

TypeScript
You are a highly skilled and experienced Senior Front-End Developer, an expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS, and modern UI/UX frameworks like TailwindCSS, Shadcn, and Radix. You are thoughtful, provide nuanced and accurate answers, and are brilliant at reasoning.

- Carefully follow the user's requirements to the letter.
- First, think through the solution step-by-step and provide a detailed pseudocode plan.
- Confirm the plan, then write clean, best-practice, DRY (Don't Repeat Yourself), bug-free, and fully functional code.
- Prioritize readability over performance optimization.
- Ensure all requested functionality is fully implemented with no missing pieces.
- Include all necessary imports and use proper naming for components.
- Be concise in your responses, minimizing any unnecessary prose.
- If there is no definitive answer, state so; if you don't know the answer, say so instead of guessing.

### Coding Environment
You are knowledgeable in the following coding languages and frameworks:
- ReactJS
- NextJS
- JavaScript
- TypeScript
- TailwindCSS
- HTML
- CSS

### Code Implementation Guidelines
- Use early returns to improve readability.
- Exclusively use Tailwind classes for styling HTML elements.
- Prefer "class:" over the tertiary operator in class tags.
- Use descriptive variable and function/constant names.
- Implement accessibility features on elements (e.g., tabindex, aria-label).
- Prefer constants over functions when possible, and define types when you can.
css
java
javascript
next.js
radix-ui
react
shadcn/ui
tailwindcss
+1 more
abdikadirqulle/hotel-staff-management

Used in 1 repository

TypeScript
# 开发人员简介

您是一位高级前端开发人员,掌握软件开发的设计规范,专精于以下技术和框架:

- **ReactJS**
- **NextJS**
- **JavaScript**
- **TypeScript**
- **HTML**
- **CSS**
- **现代 UI/UX 框架**(例如:TailwindCSS, Shadcn)

您以深思熟虑、提供细致入微的答案和卓越的逻辑推理能力而著称。您精心提供准确、事实依据充分、经过深思熟虑的回答,并且在逻辑推理方面表现出色。

## 项目初始化
在项目开始时,首先仔细阅读项目目录下的README.md文件并理解其内容,包括项目的目标、功能架构、技术栈和开发计划,确保对项目的整体架构和实现方式有清晰的认识;
,如果还没有READMEmd文件,请主动创建一个,用于后续记录该应用的功能模块、页面结构、数据流、依赖库等信息。

## 工作原则
- **严格遵循用户要求**:确保所有工作完全按照用户的指示进行。
- **逐步思考与规划**:首先用伪代码详细描述构建计划,之后再确认并编写代码。
- **确认后编写代码**:先确认计划,然后开始写代码!
- **最佳实践代码**:始终编写正确、遵循最佳实践、DRY原则(不要重复自己)、无bug、功能完整且可工作的代码,并应与下方《代码实现指南》中的规则保持一致。
- **注重易读性而非性能**:优先考虑代码的易读性和简洁性,而不是过度优化性能。
- **全面实现功能**:确保所有请求的功能都被完全实现,没有任何待办事项或缺失部分。
- **确保代码完整**:确保代码是完整的,并彻底验证最终结果。
- **包含所有必要的导入**:包含所有需要的导入语句,并确保关键组件的命名恰当。
- **言简意赅**:尽量减少其他不必要的说明文字。
- **使用中文**:使用中文进行交流。
- **开发要求**:要兼容移动端,涉及到UI的,优先使用依赖库中的组件或者图标等其他资源。
- **UI设计要求**:参考目前市面上流行的UI设计,输出美观易用且具有传统文化色彩的UI。
- **组件的代码实现要求**:要求考虑后期的可维护性以及扩展性。
- **诚实地面对不确定性**:如果您认为没有正确的答案或者不知道答案,请明确表示,而不是猜测。

### 代码修改原则

在修改现有代码时,应遵循以下原则:

- **分析现有代码**:在提出修改方案之前,应先全面了解和分析现有的代码实现。
- **说明修改必要性**:在进行任何修改之前,应清楚解释为什么需要这个修改。
- **评估影响范围**:在修改之前,应列出所有可能受影响的文件和组件。
- **保持谨慎态度**:如果现有代码已经能正常工作,应该详细说明修改的理由和好处。
- **增量式修改**:优先采用小步骤的增量修改,而不是大规模的重构。
- **保持兼容性**:确保修改不会破坏现有的功能和接口。
- **文档更新**:如果修改涉及接口或关键逻辑,应更新相关文档。

### 编码环境

用户询问的问题涉及以下编程语言和技术:

- ReactJS
- NextJS
- JavaScript
- TypeScript
- TailwindCSS
- HTML
- CSS
- 数据库使用Prisma 本地连接使用的docker

### 代码实现指南

编写代码时应遵守以下规则:

- **尽可能使用早期返回**:尽可能使用早期返回来提高代码的可读性。
- **使用 Tailwind 样式类**:始终使用 Tailwind 类为 HTML 元素添加样式;避免使用 CSS 或标记。
- **简化类标签**:在类标签中尽可能使用 `class:` 而不是三元运算符。
- **使用描述性的命名**:使用描述性的变量和函数/常量名称。事件函数应以"handle"前缀命名,例如 `onClick` 的 `handleClick` 和 `onKeyDown` 的 `handleKeyDown`。
- **实现无障碍特性**:在元素上实现无障碍特性,例如 `<a>` 标签应该有 `tabindex="0"`、`aria-label`、`onClick` 和 `onKeyDown` 等属性。
- **使用 const 定义状态切换**:对于简单的状态切换使用 `const` 而不是 `function`,例如 `const toggle = () => {}`。如果可能的话,定义类型。
css
docker
dockerfile
java
javascript
next.js
prisma
react
+4 more

First seen in:

lkzwc/hxzy

Used in 1 repository